o
    Zhx                     @   s   d Z ddlZddlZddlZddlZddlmZ ddlmZ ddl	m
Z
 ddlmZmZmZ ddlmZ ddlmZ dd	lmZmZmZ dd
lmZmZmZ ddlmZ erZddlZeeZ g dZ!G dd deZ"dS )z
Spyder kernel for Jupyter.
    N)IPythonKernel)
eventloops)LazyConfigValue)
TEXT_TYPESto_text_stringPY3)FrontendComm)iofunctions)MPL_BACKENDS_FROM_SPYDERMPL_BACKENDS_TO_SPYDERINLINE_FIGURE_FORMATS)get_remote_datamake_remote_viewget_size)SpyderShell)InZOutexitget_ipythonquitc                       s0  e Zd ZdZeZ fddZ fddZ		dd	d
Zdd Z	dd Z
dd Zdd Zdd Zdd Zdd Zdd Zdd ZdddZdd  Z fd!d"Zd#d$ Zd%d& Zd'd( Zd)d* Zd+d, Zdd-d.Zd/d0 Zdd1d2Zd3d4 Zd5d6 Zd7d8 Zd9d: Z dd;d<Z!d=d> Z"d?d@ Z#dAdB Z$dCdD Z%dEdF Z&dGdH Z'dIdJ Z(dKdL Z)dMdN Z*dOdP Z+dQdR Z,dSdT Z-dUdV Z.dWdX Z/ddYdZZ0d[d\ Z1d]d^ Z2d_d` Z3dadb Z4dcdd Z5dedf Z6dgdh Z7didj Z8dkdl Z9dmdn Z:dodp Z;dqdr Z<ddsdtZ=dudv Z>dwdx Z?dydz Z@dd|d}ZAd~d ZBdd ZCdd ZD  ZES )SpyderKernelzSpyder kernel for Jupyter.c                    s(  t t| j|i | | j| j_t| | _i d| jd| j	d| j
d| jd| jd| jd| jd| jd	| jd
| jd| jd| jd| jd| jd| jd| jd| j| j| j| j| j| j| j| j| j | j!| j"| j#| j$| j%d}|D ]}| j&|||  qzi | _'d | _(d | _)d | _*d S )NZset_breakpointsset_pdb_ignore_libset_pdb_execute_eventsset_pdb_use_exclamation_mark	get_value	load_datasave_namespace
is_definedget_doc
get_source	set_valueremove_value
copy_valueset_cwdget_cwdget_syspathget_env)close_all_mpl_figuresshow_mpl_backend_errorsget_namespace_viewset_namespace_view_settingsget_var_propertiesset_sympy_forecolorupdate_syspathis_special_kernel_validget_matplotlib_backendget_mpl_interactive_backendpdb_input_reply_interrupt_eventloopenable_faulthandler)+superr   __init__	_get_commcomm_managerZget_commr   frontend_commset_spyder_breakpointsr   r   r   r   r   r   r   r   r   r   r    r!   r"   r#   r$   r%   r&   r'   r(   r)   r*   r+   r,   r-   r.   r/   r0   r1   r2   Zregister_call_handlernamespace_view_settings_mpl_backend_error_running_namespacefaulthandler_handle)selfargskwargshandlersZcall_id	__class__ T/var/www/html/lang_env/lib/python3.10/site-packages/spyder_kernels/console/kernel.pyr4   4   sx   

	
 
zSpyderKernel.__init__c                    s   |    tt| | dS )z2Disable faulthandler if enabled before proceeding.N)disable_faulthandlerr3   r   do_shutdown)r=   ZrestartrA   rC   rD   rF   e   s   zSpyderKernel.do_shutdownFTNc                 C   s&   |rd}n| j j}| j j||||dS )zCall the frontend.N)blockingcomm_idcallbacktimeout)r7   Zcalling_comm_idZremote_call)r=   rG   	broadcastrJ   rI   rH   rC   rC   rD   frontend_callj   s   zSpyderKernel.frontend_callc                 C   s~   t sdS |   t|d}|| _|d |tt j |d |d	dd t
 D  |d t| dS )	ze
        Open a file to save the faulthandling and identifiers for
        internal threads.
        NwzMain thread id:
z
System threads ids:
 c                 S   s"   g | ]}|t  urt|jqS rC   )	threadingmain_threadhexident).0threadrC   rC   rD   
<listcomp>   s    z4SpyderKernel.enable_faulthandler.<locals>.<listcomp>
)r   rE   openr<   writerQ   rO   rP   rR   join	enumeratefaulthandlerenable)r=   fnfrC   rC   rD   r2   y   s   



z SpyderKernel.enable_faulthandlerc                 C   s.   t sdS | jrt  | j  d| _dS dS )zV
        Cancel the faulthandling, close the file handle and remove the file.
        N)r   r<   r[   disablecloser=   rC   rC   rD   rE      s   

z!SpyderKernel.disable_faulthandlerc                 C   s
   || _ dS )zSet namespace_view_settings.N)r9   )r=   settingsrC   rC   rD   r)         
z(SpyderKernel.set_namespace_view_settingsc                 C   s&   | j }|r|  }t||t}|S dS )a  
        Return the namespace view

        This is a dictionary with the following structure

        {'a':
            {
                'type': 'str',
                'size': 1,
                'view': '1',
                'python_type': 'int',
                'numpy_type': 'Unknown'
            }
        }

        Here:
        * 'a' is the variable name.
        * 'type' and 'size' are self-evident.
        * 'view' is its value or its repr computed with
          `value_to_display`.
        * 'python_type' is its Python type computed with
          `get_type_string`.
        * 'numpy_type' is its Numpy type (if any) computed with
          `get_numpy_type_string`.
        N)r9   _get_current_namespacer   EXCLUDED_NAMES)r=   rb   nsviewrC   rC   rD   r(      s   zSpyderKernel.get_namespace_viewc                 C   s   | j }|rM|  }t||dtd}i }t| D ]1\}}| || || || 	|| 
|| || || || || |d
||< q|S dS )zW
        Get some properties of the variables in the current
        namespace
        editablemodeZmore_excluded_names)
Zis_listZis_dictis_setlenZis_arrayZis_imageZis_data_frameZ	is_seriesZarray_shapeZ
array_ndimN)r9   rd   r   re   listitems_is_list_is_dict_is_set_get_len	_is_array	_is_image_is_data_frame
_is_series_get_array_shape_get_array_ndim)r=   rb   rf   data
propertiesnamevaluerC   rC   rD   r*      s*   zSpyderKernel.get_var_propertiesc                 C   s   |   }|| S )zGet the value of a variable)rd   r=   r{   rf   rC   rC   rD   r      s   zSpyderKernel.get_valuec                 C   s"   |  |}|||< | j| dS )zSet the value of a variableN)_get_reference_namespacelogdebug)r=   r{   r|   rf   rC   rC   rD   r      s   
zSpyderKernel.set_valuec                 C   s   |  |}|| dS )zRemove a variableN)r~   popr}   rC   rC   rD   r       s   
zSpyderKernel.remove_valuec                 C   s   |  |}|| ||< dS )zCopy a variableN)r~   )r=   Z	orig_namenew_namerf   rC   rC   rD   r!      s   
zSpyderKernel.copy_valuec              
   C   s   ddl m} | jj}tj| }||\}}|r|S |s9t| D ]}	||	t| d}
|
|	kr8||	||
< q!z|	| W dS  t
yW } z
t|W  Y d}~S d}~ww )a  
        Load data from filename.

        Use 'overwrite' to determine if conflicts between variable names need
        to be handle or not.

        For example, if a loaded variable is call 'var'
        and there is already a variable 'var' in the namespace, having
        'overwrite=True' will cause 'var' to be updated.
        In the other hand, with 'overwrite=False', a new variable will be
        created with a sufix starting with 000 i.e 'var000' (default behavior).
        r   )fix_reference_name)Z	blacklistN)Zspyder_kernels.utils.miscr   shelluser_nsr	   Z
load_funcsrm   keysr   update	Exceptionstr)r=   filenameext	overwriter   ZglbsZ	load_funcry   error_messagekeyZnew_keyerrorrC   rC   rD   r      s&   
zSpyderKernel.load_datac                 C   s.   |   }| j}t||dtd }t||S )zSave namespace into filenameZ	picklableri   )rd   r9   r   re   copyr	   save)r=   r   rf   rb   ry   rC   rC   rD   r     s   zSpyderKernel.save_namespacec                    s   t t| ||S )zCall parent class do_complete)r3   r   do_completer=   codeZ
cursor_posrA   rC   rD   _do_complete   s   zSpyderKernel._do_completec                 C   s&   | j  r| j j||S | ||S )zw
        Call PdB complete if we are debugging.

        Public method of ipykernel overwritten for debugging.
        )r   is_debuggingpdb_sessionr   r   r   rC   rC   rD   r   $  s   
zSpyderKernel.do_completec                 C   s   | j jr| j j| dS dS z4
        Handle a message from the frontend
        N)r   r   r8   )r=   ZbreakpointsrC   rC   rD   r8   .  s   z#SpyderKernel.set_spyder_breakpointsc                 C      | j jr|| j j_dS dS )zP
        Change the "Ignore libraries while stepping" debugger setting.
        N)r   r   Zpdb_ignore_libr=   staterC   rC   rD   r   5     zSpyderKernel.set_pdb_ignore_libc                 C   r   r   )r   r   Zpdb_execute_eventsr   rC   rC   rD   r   <  r   z#SpyderKernel.set_pdb_execute_eventsc                 C   r   )z
        Set an option on the current debugging session to decide wether
        the Pdb commands needs to be prefixed by '!'
        N)r   r   Zpdb_use_exclamation_markr   rC   rC   rD   r   C  s   z)SpyderKernel.set_pdb_use_exclamation_markc                 C   s4   | j j}|r| |_||_| jr|    dS dS )z$Get a pdb command from the frontend.N)r   r   Z_disable_next_stack_entryZ_cmd_input_line	eventlooprL   Zrequest_interrupt_eventloop)r=   lineZecho_stack_entryZdebuggerrC   rC   rD   r0   K  s   zSpyderKernel.pdb_input_replyc                 C   s   dS )zInterrupts the eventloop.NrC   ra   rC   rC   rD   r1   Z  s   z!SpyderKernel._interrupt_eventloopc                 C   s&   ddl m} | jdd}||||dS )z5Return True if object is defined in current namespacer   )	isdefinedTwith_magics)force_import	namespace)spyder_kernels.utils.dochelpersr   rd   )r=   objr   r   rf   rC   rC   rD   r   `  s   zSpyderKernel.is_definedc                 C   sJ   zddl }d|jd< W n   Y ddlm} | |\}}|r#||S dS )z#Get object documentation dictionaryr   NTzdocstring.hardcopy)getdoc)
matplotlibrcParamsr   r   _eval)r=   objtxtr   r   r   validrC   rC   rD   r   g  s   zSpyderKernel.get_docc                 C   s*   ddl m} | |\}}|r||S dS )zGet object sourcer   )	getsourceN)r   r   r   )r=   r   r   r   r   rC   rC   rD   r   t  s
   zSpyderKernel.get_sourcec                 C   s,   zddl }t|  W S  ty   Y dS w )zGet current matplotlib backend.r   N)r   r   get_backendr   )r=   r   rC   rC   rD   r.   }  s   z#SpyderKernel.get_matplotlib_backendc                 C   s   dddd}d}ddl m} | jj}|dur1|tjkrd}n|tjkr'd	}n
|tjkr/d
}nd}|du r7dS ||v rAt||  S dS )an  
        Get current Matplotlib interactive backend.

        This is different from the current backend because, for instance, the
        user can set first the Qt5 backend, then the Inline one. In that case,
        the current backend is Inline, but the current interactive one is Qt5,
        and this backend can't be changed without a kernel restart.
        ZQtAggZTkAggZMacOSX)qttkmacosxNr   r   r   r   r   other)	IPython.core.getipythonr   kernelr   r   Zloop_tkZloop_qt5Z
loop_cocoar   )r=   mappingZ	frameworkr   Z	loop_funcrC   rC   rD   r/     s(   



z(SpyderKernel.get_mpl_interactive_backendc                 C   s   t t| }| j||d dS )z5Set matplotlib backend given a Spyder backend option.)pylabN)r
   r   _set_mpl_backend)r=   backendr   Zmpl_backendrC   rC   rD   set_matplotlib_backend  s   z#SpyderKernel.set_matplotlib_backendc                 C   s   t | }| d| dS )z4Set the inline figure format to use with matplotlib.zInlineBackend.figure_formatN)r   _set_config_option)r=   Zfigure_formatZmpl_figure_formatrC   rC   rD   set_mpl_inline_figure_format  s   z)SpyderKernel.set_mpl_inline_figure_formatc                 C      |  d| dS )zSet inline figure resolution.z
figure.dpiN_set_mpl_inline_rc_config)r=   
resolutionrC   rC   rD   set_mpl_inline_resolution     z&SpyderKernel.set_mpl_inline_resolutionc                 C   s   ||f}|  d| dS )zSet inline figure size.zfigure.figsizeNr   )r=   widthheightr|   rC   rC   rD   set_mpl_inline_figure_size  s   z'SpyderKernel.set_mpl_inline_figure_sizec                 C   s   ddl m} | jj}d|v r|d ni }d|v r|d ni }d|r$dndi}|| t|tr<| d}|r<|}| 	d	| dS )
z
        Set inline print figure bbox inches.

        The change is done by updating the 'print_figure_kwargs' config dict.
        r   r   ZInlineBackendprint_figure_kwargsbbox_inchesZtightNr   z!InlineBackend.print_figure_kwargs)
r   r   r   configr   
isinstancer   to_dictgetr   )r=   r   r   r   Zinline_configr   Zbbox_inches_dictZfigure_kwargs_dictrC   rC   rD   set_mpl_inline_bbox_inches  s$   


z'SpyderKernel.set_mpl_inline_bbox_inchesc                 C   r   )z4Enable/Disable jedi as the completer for the kernel.zIPCompleter.use_jediNr   )r=   Zuse_jedirC   rC   rD   set_jedi_completer  r   zSpyderKernel.set_jedi_completerc                 C   r   )z/Enable/Disable greedy completer for the kernel.zIPCompleter.greedyNr   )r=   Z
use_greedyrC   rC   rD   set_greedy_completer  r   z!SpyderKernel.set_greedy_completerc                 C   r   )z%Enable/Disable autocall funtionality.zZMQInteractiveShell.autocallNr   )r=   ZautocallrC   rC   rD   set_autocall  r   zSpyderKernel.set_autocallc                 C   s   t | dS )zSet current working directory.N)oschdir)r=   dirnamerC   rC   rD   r"        zSpyderKernel.set_cwdc              	   C   s$   zt  W S  ttfy   Y dS w )zGet current working directory.N)r   getcwdIOErrorOSErrorra   rC   rC   rD   r#     s
   
zSpyderKernel.get_cwdc                 C   s   t jdd S )zReturn sys.path contents.N)syspathra   rC   rC   rD   r$     r   zSpyderKernel.get_syspathc                 C   s
   t j S )zGet environment variables.)r   environr   ra   rC   rC   rD   r%     rc   zSpyderKernel.get_envc                 C   s*   zddl m} |d W dS    Y dS )zClose all Matplotlib figures.r   Nall)Zmatplotlib.pyplotZpyplotr`   )r=   ZpltrC   rC   rD   r&     s
   z"SpyderKernel.close_all_mpl_figuresc                 C   s   z0t jddkrddl}W dS t jddkrddl}W dS t jddkr.ddl}W dS W dS  ty[   t jddkrBY dS t jddkrMY dS t jddkrXY d	S Y dS w )
zT
        Check if optional dependencies are available for special consoles.
        ZSPY_AUTOLOAD_PYLAB_OTruer   NSPY_SYMPY_OZSPY_RUN_CYTHONr   sympycython)r   r   r   r   r   r   r   )r=   r   r   r   rC   rC   rD   r-     s,   



z$SpyderKernel.is_special_kernel_validc                 C   sz   |D ]}|t jv rt j| |t jv s	qdd | D }|r4t j| tjdtj	|i dS tj
dd dS )ab  
        Update the PYTHONPATH of the kernel.

        `path_dict` and `new_path_dict` have the paths as keys and the state
        as values. The state is `True` for active and `False` for inactive.

        `path_dict` corresponds to the previous state of the PYTHONPATH.
        `new_path_dict` corresponds to the new state of the PYTHONPATH.
        c                 S   s   g | ]\}}|r|qS rC   rC   )rS   r   ZactiverC   rC   rD   rU   4  s    z/SpyderKernel.update_syspath.<locals>.<listcomp>
PYTHONPATHN)r   r   removern   extendr   r   r   pathseprY   r   )r=   Z	path_dictZnew_path_dictr   ZpypathrC   rC   rD   r,   $  s   

zSpyderKernel.update_syspathc                 C   s   i }| j  r| j jjr|| j j || j j n | jdu r(|| j j n| j\}}|| |dur;|| |rU| j jj	d }| j jj	d }|| || |S )z
        Return current namespace

        This is globals() if not debugging, or a dictionary containing
        both locals() and globals() for current frame when debugging
        Nr   cell)
r   r   r   Zcurframer   r   _pdb_localsr;   Zmagics_managerZmagics)r=   r   rf   Zrunning_globalsZrunning_localsZline_magicsZcell_magicsrC   rC   rD   rd   =  s    





z#SpyderKernel._get_current_namespacec                 C   s   | j j}||v r
|S | j jS )z
        Return namespace where reference name is defined

        It returns the globals() if reference has not yet been defined
        )r   r   r   )r=   r{   ZlclsrC   rC   rD   r~   ]  s   z%SpyderKernel._get_reference_namespacec                 C   s   zt |W S    Y dS )zReturn sequence lengthN)r   r=   varrC   rC   rD   rr   h  s   
zSpyderKernel._get_lenc                 C   s$   zddl }t||jW S    Y dS )z(Return True if variable is a NumPy arrayr   NF)numpyr   Zndarray)r=   r   r   rC   rC   rD   rs   o  s
   zSpyderKernel._is_arrayc                 C   s(   zddl m} t||jW S    Y dS )z,Return True if variable is a PIL.Image imager   )ImageF)ZPILr   r   )r=   r   r   rC   rC   rD   rt   w  s
   zSpyderKernel._is_imagec                 C   &   zddl m} t||W S    Y dS )z&Return True if variable is a DataFramer   )	DataFrameF)pandasr   r   )r=   r   r   rC   rC   rD   ru     
   zSpyderKernel._is_data_framec                 C   r   )z#Return True if variable is a Seriesr   )SeriesF)r   r   r   )r=   r   r   rC   rC   rD   rv     r   zSpyderKernel._is_seriesc                 C   s&   zt |ttfW S  ty   Y dS w )z+Return True if variable is a list or tuple.F)r   tuplerm   r   r   rC   rC   rD   ro     s
   zSpyderKernel._is_listc                 C   "   zt |tW S  ty   Y dS w )z(Return True if variable is a dictionary.F)r   dictr   r   rC   rC   rD   rp     
   zSpyderKernel._is_dictc                 C   r   )z!Return True if variable is a set.F)r   setr   r   rC   rC   rD   rq     r   zSpyderKernel._is_setc                 C   &   z|  |r
|jW S W dS    Y dS )zReturn array's shapeN)rs   shaper   rC   rC   rD   rw        
zSpyderKernel._get_array_shapec                 C   r   )zReturn array's ndimN)rs   ndimr   rC   rC   rD   rx     r   zSpyderKernel._get_array_ndimc                 C   sB   ddl m} ||sJ | jdd}zt||dfW S    Y dS )z
        Evaluate text and return (obj, valid)
        where *obj* is the object represented by *text*
        and *valid* is True if object evaluation did not raise any exception
        r   )is_text_stringTr   )NF)spyder_kernels.py3compatr   rd   eval)r=   textr   rf   rC   rC   rD   r     s   zSpyderKernel._evalc              
   C   s.  ddl }ddlm} zddl}W n
 ty   Y dS w d}|r!dnd}d}zd|jd< | || W n^ tyb }	 z#d	t|	v rQ|	 }
||

 vrPd
|
}n|| }W Y d}	~	n4d}	~	w ty }	 zdtj}||	d | }W Y d}	~	nd}	~	w ty   || }Y nw || _dS )a  
        Set a backend for Matplotlib.

        backend: A parameter that can be passed to %matplotlib
                 (e.g. 'inline' or 'tk').
        pylab: Is the pylab magic should be used in order to populate the
               namespace from numpy and matplotlib
        r   Nr   z
=========================================================================
NOTE: The following error appeared when setting your Matplotlib backend!!
=========================================================================

{0}r   r   ZAggr   zGUI eventloopsz
NOTE: Spyder *can't* set your selected Matplotlib backend because there is a previous backend already in use.

Your backend will be {0}zThis is most likely caused by missing packages in the Python environment
or installation whose interpreter is located at:

    {0}z

)	tracebackr   r   r   r   r   run_line_magicRuntimeErrorr   r   lowerformat
format_excImportErrorr   
executabler:   )r=   r   r   r   r   r   Zgeneric_errormagicr   errZprevious_backendZadditional_inforC   rC   rD   r     sD   	
	
zSpyderKernel._set_mpl_backendc                 C   s^   ddl m} zd}t|trdnd}|| }| d|j||d W dS  ty.   Y dS w )	z
        Set config options using the %config magic.

        As parameters:
            option: config option, for example 'InlineBackend.figure_format'.
            value: value of the option, for example 'SVG', 'Retina', etc.
        r   r   z{option} = z	'{value}'z{value}r   )optionr|   N)r   r   r   r   r   r   r   )r=   r  r|   r   Zbase_configZ
value_lineZconfig_linerC   rC   rD   r     s   
zSpyderKernel._set_config_optionc                 C   s0   zddl m} |||< W dS  ty   Y dS w )zQ
        Update any of the Matplolib rcParams given an option and value.
        r   )r   N)r   r   r   )r=   r  r|   r   rC   rC   rD   r   $  s   z&SpyderKernel._set_mpl_inline_rc_configc                 C   s   | j durt| j  dS dS )z9Show Matplotlib backend errors after the prompt is ready.N)r:   printra   rC   rC   rD   r'   /  s   
z$SpyderKernel.show_mpl_backend_errorsdarkc                 C   s   t jddkr>z+ddlm} ddlm} |dkr#|d| d W dS |d	kr1|d
| d W dS W dS  ty=   Y dS w dS )z4Set SymPy forecolor depending on console background.r   r   r   )init_printingr   r  ZWhite)Z	forecoloripZlightZBlackN)r   r   r   r   r	  r   r   r   )r=   background_colorr	  r   rC   rC   rD   r+   4  s   z SpyderKernel.set_sympy_forecolorc                 C   sD   ddl m} z| dd | dd W dS  ty!   Y dS w )zLoad %autoreload magic.r   r   
reload_extZ
autoreload2N)r   r   r   r   r=   r   rC   rC   rD   _load_autoreload_magicB  s   z#SpyderKernel._load_autoreload_magicc                 C   sD   t jdks ddlm} z
| dd W dS  ty   Y dS w dS )zLoad wurlitzer extension.ntr   r   r  Z	wurlitzerN)r   r{   r   r   r   r   r  rC   rC   rD   _load_wurlitzerK  s   
zSpyderKernel._load_wurlitzerc                 C   s$   z| j j| W S  ty   Y dS w )z
        We need to redefine this method from ipykernel.comm_manager to
        avoid showing a warning when the comm corresponding to comm_id
        is not present.

        Fixes spyder-ide/spyder#15498
        N)r6   ZcommsKeyError)r=   rH   rC   rC   rD   r5   X  s
   zSpyderKernel._get_comm)FTNN)F)T)r  )F__name__
__module____qualname____doc__r   Zshell_classr4   rF   rL   r2   rE   r)   r(   r*   r   r   r    r!   r   r   r   r   r8   r   r   r   r0   r1   r   r   r   r.   r/   r   r   r   r   r   r   r   r   r"   r#   r$   r%   r&   r-   r,   rd   r~   rr   rs   rt   ru   rv   ro   rp   rq   rw   rx   r   r   r   r   r'   r+   r  r  r5   __classcell__rC   rC   rA   rD   r   /   s    1
#
$	


	
1
 

D
	r   )#r  loggingr   r   rO   Zipykernel.ipkernelr   Z	ipykernelr   Ztraitlets.config.loaderr   r   r   r   r   Z!spyder_kernels.comms.frontendcommr   Zspyder_kernels.utils.iofuncsr	   Zspyder_kernels.utils.mplr
   r   r   Zspyder_kernels.utils.nsviewr   r   r   Zspyder_kernels.console.shellr   r[   	getLoggerr  loggerre   r   rC   rC   rC   rD   <module>   s&   
