
    Mh_                        d 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	m
Z
 ddlmZ ddlmZ ddlmZ dd	lmZmZ dd
lmZmZmZ ddlmZmZ ddlmZ ddlmZmZ ddl m!Z! ddl"m#Z#m$Z$ ddl%m&Z&m'Z' ddl(m)Z) ddl*m+Z+m,Z,m-Z-m.Z.m/Z/m0Z0m1Z1m2Z2 ddl3m4Z4m5Z5m6Z6 ddl7m8Z8 ddl9m:Z:m;Z;  G d de          Z<e G d de                      Z= G d de          Z> ej?        e>           dS )ak  A ZMQ-based subclass of InteractiveShell.

This code is meant to ease the refactoring of the base InteractiveShell into
something with a cleaner architecture for 2-process use, without actually
breaking InteractiveShell itself.  So we're doing something a bit ugly, where
we subclass and override what we want to fix.  Once this is working well, we
can go back to the base class and refactor the code for a cleaner inheritance
implementation that doesn't rely on so much monkeypatching.

But this lets us maintain a fully working IPython as we develop the new
machinery.  This should thus be thought of as scaffolding.
    N)Pathlocal)pagepayloadpageZMQExitAutocall)DisplayPublisher)
UsageError)InteractiveShellInteractiveShellABC)Magics
line_magicmagics_class)
CodeMagicsMacroToEditdefault_banner)
Javascriptdisplay)openpy)	arg_splitsystem)Sessionextract_header)jupyter_runtime_dir)AnyCBoolCBytesDictInstanceTypedefaultobserve)connect_qtconsoleget_connection_fileget_connection_info)ZMQShellDisplayHook)encode_images
json_cleanc                       e Zd ZdZ eed          Z ed          Z e	i           Z
 ed          Z e            Zd Zd Z ed          d             Zed	             Z	 	 	 ddZddZd Zd Zd
S )ZMQDisplayPublisherzBA display publisher that publishes data using a ZeroMQ PUB socket.T)
allow_nones   display_datac                 .    t          |          | _        dS )z%Set the parent for outbound messages.N)r   parent_headerselfparents     R/var/www/html/test/jupyter/venv/lib/python3.11/site-packages/ipykernel/zmqshell.py
set_parentzZMQDisplayPublisher.set_parent<   s    +F33    c                 ~    t           j                                         t           j                                         dS )z!flush IO Streams prior to displayN)sysstdoutflushstderrr1   s    r3   _flush_streamsz"ZMQDisplayPublisher._flush_streams@   s0    

r5   _thread_localc                     t                      S )z#Initialize our thread local storager   r;   s    r3   _default_thread_localz)ZMQDisplayPublisher._default_thread_localE   s     wwr5   c                 \    t          | j        d          sg | j        _        | j        j        S )Nhooks)hasattrr=   rA   r;   s    r3   _hookszZMQDisplayPublisher._hooksJ   s.    t)733 	*')D$!''r5   NFc                    |                                   |i }|i }|                     ||           i }t          |          |d<   ||d<   ||d<   |rdnd}| j        J | j                            |t          |          | j                  }| j        D ]} ||          }| dS | j                            | j	        || j
                   dS )	aE  Publish a display-data message

        Parameters
        ----------
        data : dict
            A mime-bundle dict, keyed by mime-type.
        metadata : dict, optional
            Metadata associated with the data.
        transient : dict, optional, keyword-only
            Transient data that may only be relevant during a live display,
            such as display_id.
            Transient data should not be persisted to documents.
        update : bool, optional, keyword-only
            If True, send an update_display_data message instead of display_data.
        Ndatametadata	transientupdate_display_datadisplay_datar2   ident)r<   _validate_datar)   sessionmsgr*   r/   rC   send
pub_sockettopic)	r1   rE   rF   rG   updatecontentmsg_typerO   hooks	            r3   publishzZMQDisplayPublisher.publishQ   s   , 	HID(+++'--&
(,2F((
 |'''lxG)<)<TEWXX
 K 	 	D$s))C{  	O* 	 	
 	
 	
 	
 	
r5   c                 @   t          |          }|                                  | j        J | j                            dt	          |          | j                  }| j        D ]} ||          }| dS | j                            | j        || j	                   dS )aZ  Clear output associated with the current execution (cell).

        Parameters
        ----------
        wait : bool (default: False)
            If True, the output will not be cleared immediately,
            instead waiting for the next display before clearing.
            This reduces bounce during repeated clear & display loops.

        )waitNclear_outputrJ   rK   )
dictr<   rN   rO   r*   r/   rC   rP   rQ   rR   )r1   rY   rT   rO   rV   s        r3   rZ   z ZMQDisplayPublisher.clear_output   s     D///|'''l~z'/B/B4K]^^ K 	 	D$s))C{  	O* 	 	
 	
 	
 	
 	
r5   c                 :    | j                             |           dS )a  
        Registers a hook with the thread-local storage.

        Parameters
        ----------
        hook : Any callable object

        Returns
        -------
        Either a publishable message, or `None`.
        The DisplayHook objects must return a message from
        the __call__ method if they still require the
        `session.send` method to be called after transformation.
        Returning `None` will halt that execution path, and
        session.send will not be called.
        N)rC   appendr1   rV   s     r3   register_hookz!ZMQDisplayPublisher.register_hook   s     " 	4     r5   c                 ^    	 | j                             |           dS # t          $ r Y dS w xY w)aB  
        Un-registers a hook with the thread-local storage.

        Parameters
        ----------
        hook : Any callable object which has previously been
            registered as a hook.

        Returns
        -------
        bool - `True` if the hook was removed, `False` if it wasn't
            found.
        TF)rC   remove
ValueErrorr^   s     r3   unregister_hookz#ZMQDisplayPublisher.unregister_hook   sD    	Kt$$$4 	 	 	55	s    
,,)NNFF)__name__
__module____qualname____doc__r!   r   rN   r   rQ   r    r/   r   rR   r=   r4   r<   r#   r?   propertyrC   rW   rZ   r_   rc    r5   r3   r,   r,   /   s       LLhw4000G%%%JDHHMF?##E
 CEEM4 4 4  
 W_   ( ( X( 5
 5
 5
 5
n
 
 
 
8! ! !&    r5   r,   c                   *   e Zd ZdZedd            Zed             Zej        dk    r  ed          e          Z	ed             Z
  ed	          e
          Zej        d
k    red             Zed             Zed             Zed             ZdS )KernelMagicszKernel magics. Nc                    |pddg}|                      |d          \  }}	 t          j        | j        |||          \  }}}n # t          $ r t          d           Y dS w xY wt          t          |                                                    }d||d}| j        J | j        j	        
                    |           dS )a  Bring up an editor and execute the resulting code.

        Usage:
          %edit [options] [args]

        %edit runs an external text editor. You will need to set the command for
        this editor via the ``TerminalInteractiveShell.editor`` option in your
        configuration file before it will work.

        This command allows you to conveniently edit multi-line code right in
        your IPython session.

        If called without arguments, %edit opens up an empty editor with a
        temporary file and will execute the contents of this file when you
        close it (don't forget to save it!).

        Options:

        -n <number>
          Open the editor at a specified line number. By default, the IPython
          editor hook uses the unix syntax 'editor +N filename', but you can
          configure this by providing your own modified hook if your favorite
          editor supports line-number specifications with a different syntax.

        -p
          Call the editor with the same data as the previous time it was used,
          regardless of how long ago (in your current session) it was.

        -r
          Use 'raw' input. This option only applies to input taken from the
          user's history.  By default, the 'processed' history is used, so that
          magics are loaded in their transformed version to valid Python.  If
          this option is given, the raw input as typed as the command line is
          used instead.  When you exit the editor, it will be executed by
          IPython's own processor.

        Arguments:

        If arguments are given, the following possibilities exist:

        - The arguments are numbers or pairs of colon-separated numbers (like
          1 4:8 9). These are interpreted as lines of previous input to be
          loaded into the editor. The syntax is the same of the %macro command.

        - If the argument doesn't start with a number, it is evaluated as a
          variable and its contents loaded into the editor. You can thus edit
          any string which contains python code (including the result of
          previous edits).

        - If the argument is the name of an object (other than a string),
          IPython will try to locate the file where it was defined and open the
          editor at the point where it is defined. You can use ``%edit function``
          to load an editor exactly at the point where 'function' is defined,
          edit it and have the file be executed automatically.

          If the object is a macro (see %macro for details), this opens up your
          specified editor with a temporary file containing the macro's data.
          Upon exit, the macro is reloaded with the contents of the file.

          Note: opening at an exact line is only supported under Unix, and some
          editors (like kedit and gedit up to Gnome 2.8) do not understand the
          '+NUMBER' parameter necessary for this feature. Good editors like
          (X)Emacs, vi, jed, pico and joe all do.

        - If the argument is not found as a variable, IPython will look for a
          file with that name (adding .py if necessary) and load it into the
          editor. It will execute its contents with execfile() when you exit,
          loading any code in the file into your interactive namespace.

        Unlike in the terminal, this is designed to use a GUI editor, and we do
        not know when it has closed. So the file you edit will not be
        automatically executed or printed.

        Note that %edit is also available through the alias %ed.
        rm   zprn:z5Macro editing not yet implemented in 2-process model.N
edit_magic)sourcefilenameline_number)parse_optionsr   _find_edit_targetshellr   printstrr   resolvepayload_managerwrite_payload)	r1   parameter_s	last_calloptsargsrq   lineno_payloads	            r3   editzKernelMagics.edit   s    Z )"b	''V<<
d	",">tz4QUW`"a"aHfaa 	 	 	IJJJFF	 tH~~--//00)xPVWWz%%%
"0099999s    A AAc                     | j         J t          j        dk    r| j                             d           dS | j                             d           dS )zClear the terminal.Nposixclearcls)ru   osnamer   r1   arg_ss     r3   r   zKernelMagics.clear:  sW     z%%%7gJg&&&&&Je$$$$$r5   ntr   c                 d   |sd}t          |          |                    d          r8| j        J | j                            t	          j        |d                    }n;t          |          5 }|                                }ddd           n# 1 swxY w Y   t          j        |           dS )zSShow a file through the pager.

        Files ending in .py are syntax-highlighted.zMissing filename.z.pyNF)skip_encoding_cookie)	r   endswithru   
pycolorizer   read_py_fileopenreadr   )r1   r   rO   contfids        r3   lesszKernelMagics.lessI  s    
  	"%CS//!>>%   	":))):(()<UY^)_)_)_``DDe "xxzz" " " " " " " " " " " " " " "	$s   0BBBmorer   c                 z    | j         J t          j        | j                             d|z  d                     dS )z=Find the man page for the given command and display in pager.Nzman %s | col -bF)split)ru   r   	getoutputr   s     r3   manzKernelMagics.man_  sC     :)))Idj**+<u+DE*RRSSSSSr5   c                    	 t                      }t          d          }n1# t          $ r$}t          j        d|z  d           Y d}~dS d}~ww xY wt                      t          t          |          j                  k    rt          |          j	        }t          |t                    sJ t          |dz              t          d| d	           dS )
ao  Print information for connecting other clients to this kernel

        It will print the contents of this session's connection file, as well as
        shortcuts for local clients.

        In the simplest case, when called from the most recently launched kernel,
        secondary clients can be connected, simply with:

        $> jupyter <app> --existing

        F)unpackz!Could not get connection info: %r   
stacklevelN
zPaste the above JSON into a file, and connect with:
    $> jupyter <app> --existing <file>
or, if you are local, you can connect with just:
    $> jupyter <app> --existing zj
or even just:
    $> jupyter <app> --existing
if this is the most recent Jupyter kernel you have started.)r&   r'   	Exceptionwarningswarnr   rw   r   r2   r   
isinstancerv   )r1   r   connection_fileinfoes        r3   connect_infozKernelMagics.connect_infoe  s   	133O&e444DD 	 	 	M=AaPPPPFFFFF	
   C_(=(=(D$E$EEE"?338O$$$$$$dTkK 0?K K K	
 	
 	
 	
 	
s   ! 
AA

Ac                     dt           j        v rddlm}  |             	 t	          t          |t          j        dk                         d	S # t          $ r$}t          j
        d|z  d           Y d	}~d	S d	}~ww xY w)
zOpen a qtconsole connected to this kernel.

        Useful for connecting a qtconsole to running notebooks, for better
        debugging.
        ipyparallelr   )bind_kernelr   )argvzCould not start qtconsole: %rr   r   N)r7   modulesr   r   r%   r   r   r   r   r   r   )r1   r   r   r   s       r3   	qtconsolezKernelMagics.qtconsole  s     CK''//////KMMM	9UBGw4F#G#GHHHHHH 	 	 	M9A=!LLLLFFFFF	s   ,A 
A<A77A<c                 
   	 t          |          }n%# t          $ r}t          d|z            |d}~ww xY wd|z  }t          t	          d|z            dg           |rt          d|z             dS t          d           dS )	a*  Set the autosave interval in the notebook (in seconds).

        The default value is 120, or two minutes.
        ``%autosave 0`` will disable autosave.

        This magic only has an effect when called from the notebook interface.
        It has no effect when called in a startup file.
        z&%%autosave requires an integer, got %rNi  z*IPython.notebook.set_autosave_interval(%i)zapplication/javascript)includezAutosaving every %i secondszAutosave disabled)intrb   r   r   r   rv   )r1   r   intervalr   millisecondss        r3   autosavezKernelMagics.autosave  s    	V5zzHH 	V 	V 	VEMNNTUU	V hClRSS-.	
 	
 	
 	
  	'/(:;;;;;%&&&&&s    
4/4)rm   N)re   rf   rg   rh   r   r   r   r   r   r   r   r   r   r   r   r   rj   r5   r3   rl   rl      s3        \: \: \: Z\:B % % Z% 
w$jj&&   Z  ::fd##D 
w'		T 	T 
	T
 "
 "
 Z"
H   Z( ' ' Z' ' 'r5   rl   c                       e Zd ZdZ ee          Z ee          Z e	            Z
 e	            Z e	            Z ed          d             Z ed          Z ed          Z ee          Z ed          d             Z ed          d             Zd	Zd
 Zd Z fdZd Zed             Zej        d             Zd Z  fdZ!d Z"ddZ#d Z$d Z% fdZ&d Z'd Z(e(Z) xZ*S )ZMQInteractiveShellz'A subclass of InteractiveShell for ZMQ.banner1c                     t           S Nr   r;   s    r3   _default_banner1z$ZMQInteractiveShell._default_banner1  s    r5   Fexiterc                      t          |           S r   r   r;   s    r3   _default_exiterz#ZMQInteractiveShell._default_exiter  s    t$$$r5   exit_nowc                    |d         rwt          | j        d          r'| j        j        }|                    d|j                   | j        j        r1t          | j        j        dd          }|r || j                   dS dS dS dS )z"stop eventloop when exit_now firesnewio_loopg?	exit_hookN)rB   kernelr   
call_laterstop	eventloopgetattr)r1   changeloopr   s       r3   _update_exit_nowz$ZMQInteractiveShell._update_exit_now  s     %= 	+t{I.. 0{*TY///{$ +#DK$9;MM	 +Idk*****	+ 	++ ++ +r5   Nc                     ddl m} 	  ||           || _        dS # t          $ r}t	          d|z            |d}~ww xY w)zEnable a given guil.   )
enable_guiz%sN)
eventloopsr   active_eventlooprb   r   )r1   guireal_enable_guir   s       r3   r   zZMQInteractiveShell.enable_gui  sj    ======	.OC   $'D!!! 	. 	. 	.TAX&&A-	.s    
>9>c                 Z    t           j        }d|d<   d|d<   d|d<   d|d<   d|d<   d|d	<   d
S )z!Configure the user's environment.zxterm-colorTERM1CLICOLORFORCE_COLORCLICOLOR_FORCEcatPAGER	GIT_PAGERN)r   environ)r1   envs     r3   init_environmentz$ZMQInteractiveShell.init_environment  sK    j#FJ M # G Kr5   c                     t                                                       |                     dt          j        t
          j                  d           dS )zInitialize hooks.show_in_pagerc   N)super
init_hooksset_hookr   as_hookr   r1   	__class__s    r3   r   zZMQInteractiveShell.init_hooks  sB    ot|K4D'E'ErJJJJJr5   c                     dS )z:Delay datapub init until request, for deprecation warningsNrj   r;   s    r3   init_data_pubz!ZMQInteractiveShell.init_data_pub        r5   c                     t          | d          sct          j        dt          d           |                     |           | _        | j        j        | j        _        | j        j        | j        _        | j        S )N	_data_pubzAInteractiveShell.data_pub is deprecated outside IPython parallel.r   r   rJ   )	rB   r   r   DeprecationWarningdata_pub_classr   display_pubrN   rQ   r;   s    r3   data_pubzZMQInteractiveShell.data_pub  sy    t[)) 		DMS"    "000==DN%)%5%=DN"(,(8(CDN%~r5   c                     || _         d S r   )r   )r1   pubs     r3   r   zZMQInteractiveShell.data_pub  s    r5   c                     | j          | _        t          d| j                   }| j                            |           dS )zEngage the exit actions.ask_exit)rp   
keepkernelN)keepkernel_on_exitr   r[   ry   rz   )r1   r   s     r3   r   zZMQInteractiveShell.ask_exit  sK     33.
 
 
 	**733333r5   c                 D    d| _          t                      j        |i |S )zRun a cell.N)_last_tracebackr   run_cell)r1   r~   kwargsr   s      r3   r   zZMQInteractiveShell.run_cell"  s'    #uww0000r5   c                    t           j                                         t           j                                         |t	          |j                  t	          |          d}| j        }d }|j        r|j                            dd          }|j	        
                    |j        dt          |          |j        |           || _        d S )N)	tracebackenameevalues   execute_results   errorerrorrK   )r7   r8   r9   r:   rw   re   displayhookrR   replacerN   rP   rQ   r*   r/   r   )r1   etyper   stbexc_contentdhrR   s          r3   _showtracebackz"ZMQInteractiveShell._showtraceback'  s    

 ((&kk
 
  8 	BH$$%6AAE

M{## 	 	
 	
 	
  #r5   c                 ^    t          d||          }| j                            |           dS )zWSend the specified text to the frontend to be presented at the next
        input cell.set_next_input)rp   textr   N)r[   ry   rz   )r1   r  r   r   s       r3   r  z"ZMQInteractiveShell.set_next_inputE  s@     #
 
 

 	**733333r5   c                    || _         | j                            |           | j                            |           t	          | d          r| j                            |           	 t          j                            |           n# t          $ r Y nw xY w	 t          j	                            |           dS # t          $ r Y dS w xY w)zFSet the parent header for associating output with its triggering inputr   N)
r/   r   r4   r   rB   r   r7   r8   AttributeErrorr:   r0   s     r3   r4   zZMQInteractiveShell.set_parentO  s    ###F+++##F+++4%% 	-M$$V,,,	J!!&)))) 	 	 	D		J!!&))))) 	 	 	DD	s$   'B 
BBB9 9
CCc                     | j         S )zGet the parent header.)r/   r;   s    r3   
get_parentzZMQInteractiveShell.get_parent_  s    !!r5   c                     t                                                       |                     t                     | j                            dd           dS )zInitialize magics.edr   N)r   init_magicsregister_magicsrl   magics_managerregister_aliasr   s    r3   r  zZMQInteractiveShell.init_magicsc  sL    \*****488888r5   c                     dS )zInitialize virtual environment.Nrj   r;   s    r3   init_virtualenvz#ZMQInteractiveShell.init_virtualenvi  r   r5   c                    |                                                     d          rd}t          |          t          j        dk    rc|                     |d          }ddlm}  |            5 }|d	| d
| }t          |          | j	        d<   ddd           dS # 1 swxY w Y   dS t          |                     |d                    | j	        d<   dS )a2  Call the given cmd in a subprocess, piping stdout/err

        Parameters
        ----------
        cmd : str
            Command to execute (can not end in '&', as background processes are
            not supported.  Should not be a command that expects input
            other than simple text.
        &z#Background processes not supported.win32r   )depthr   )AvoidUNCPathNzpushd z &&
_exit_code)
rstripr   OSErrorr7   platform
var_expandIPython.utils._process_win32r  r   user_ns)r1   cmdrO   r  paths        r3   system_pipedz ZMQInteractiveShell.system_pipedp  s1    ::<<  %% 	 8C#,, <7""//#Q///CAAAAAA 94#1411C11C-3C[[\*9 9 9 9 9 9 9 9 9 9 9 9 9 9 9 9 9 9
 *010M0M)N)NDL&&&s   0"BB#&B#rd   )+re   rf   rg   rh   r"   r(   displayhook_classr,   display_pub_classr   r   r   r/   r#   r   r   readline_use
autoindentr!   r	   r   r   r$   r   r   r   r   r   r   ri   r   setterr   r   r  r  r4   r  r  r  r#  r   __classcell__)r   s   @r3   r   r     s0       11011011SUUNSUUFCEEMWY   5<<L uJXo&&FWX% % % WZ	+ 	+ 	+ . . .! ! !K K K K K
I I I   X _  _4 4 41 1 1 1 1
# # #<4 4 4 4   " " "9 9 9 9 9. . .!O !O !OH FFFFFr5   r   )@rh   r   r7   r   pathlibr   	threadingr   IPython.corer   r   IPython.core.autocallr	   IPython.core.displaypubr
   IPython.core.errorr   IPython.core.interactiveshellr   r   IPython.core.magicr   r   r   IPython.core.magicsr   r   IPython.core.usager   IPython.displayr   r   IPython.utilsr   IPython.utils.processr   r   jupyter_client.sessionr   r   jupyter_core.pathsr   	traitletsr   r   r   r    r!   r"   r#   r$   	ipykernelr%   r&   r'   ipykernel.displayhookr(   ipykernel.jsonutilr)   r*   r,   rl   r   registerrj   r5   r3   <module>r>     s     
			 



              * * * * * * * * 1 1 1 1 1 1 4 4 4 4 4 4 ) ) ) ) ) ) O O O O O O O O ? ? ? ? ? ? ? ? ? ? 7 7 7 7 7 7 7 7 - - - - - - / / / / / / / /             3 3 3 3 3 3 3 3 : : : : : : : : 2 2 2 2 2 2 P P P P P P P P P P P P P P P P P P P P Q Q Q Q Q Q Q Q Q Q 5 5 5 5 5 5 8 8 8 8 8 8 8 8Z Z Z Z Z* Z Z Zz k' k' k' k' k'6 k' k' k'\Y Y Y Y Y* Y Y Yx   0 1 1 1 1 1r5   