U
    ýÇ-e°  ã                   @   sX  d Z ddlZddlZddlZddlZddlZddl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 ddlmZ ddlmZ dd	lmZ d
ZzddlZdZW n ek
rÐ   Y nX edƒ\ZZZddddgZdd„ Z G dd„ de!ƒZ"G dd„ deƒZ#dd„ Z$dd„ Z%e&dkrTej' (d¡sFe )d¡ e%ƒ  e*dƒ dS )aA  
Sphinx directive to support embedded IPython code.

IPython provides an extension for `Sphinx <http://www.sphinx-doc.org/>`_ to
highlight and run code.

This directive allows pasting of entire interactive IPython sessions, prompts
and all, and their code will actually get re-executed at doc build time, with
all prompts renumbered sequentially. It also allows you to input code as a pure
python input by giving the argument python to the directive. The output looks
like an interactive ipython section.

Here is an example of how the IPython directive can
**run** python code, at build time.

.. ipython::

   In [1]: 1+1

   In [1]: import datetime
      ...: datetime.date.fromisoformat('2022-02-22')

It supports IPython construct that plain
Python does not understand (like magics):

.. ipython::

   In [0]: import time

   In [0]: %pdoc time.sleep

This will also support top-level async when using IPython 7.0+

.. ipython::

   In [2]: import asyncio
      ...: print('before')
      ...: await asyncio.sleep(1)
      ...: print('after')


The namespace will persist across multiple code chucks, Let's define a variable:

.. ipython::

   In [0]: who = "World"

And now say hello:

.. ipython::

   In [0]: print('Hello,', who)

If the current section raises an exception, you can add the ``:okexcept:`` flag
to the current block, otherwise the build will fail.

.. ipython::
   :okexcept:

   In [1]: 1/0

IPython Sphinx directive module
===============================

To enable this directive, simply list it in your Sphinx ``conf.py`` file
(making sure the directory where you placed it is visible to sphinx, as is
needed for all Sphinx directives). For example, to enable syntax highlighting
and the IPython directive::

    extensions = ['IPython.sphinxext.ipython_console_highlighting',
                  'IPython.sphinxext.ipython_directive']

The IPython directive outputs code-blocks with the language 'ipython'. So
if you do not have the syntax highlighting extension enabled as well, then
all rendered code-blocks will be uncolored. By default this directive assumes
that your prompts are unchanged IPython ones, but this can be customized.
The configurable options that can be placed in conf.py are:

ipython_savefig_dir:
    The directory in which to save the figures. This is relative to the
    Sphinx source directory. The default is `html_static_path`.
ipython_rgxin:
    The compiled regular expression to denote the start of IPython input
    lines. The default is ``re.compile('In \[(\d+)\]:\s?(.*)\s*')``. You
    shouldn't need to change this.
ipython_warning_is_error: [default to True]
    Fail the build if something unexpected happen, for example if a block raise
    an exception but does not have the `:okexcept:` flag. The exact behavior of
    what is considered strict, may change between the sphinx directive version.
ipython_rgxout:
    The compiled regular expression to denote the start of IPython output
    lines. The default is ``re.compile('Out\[(\d+)\]:\s?(.*)\s*')``. You
    shouldn't need to change this.
ipython_promptin:
    The string to represent the IPython input prompt in the generated ReST.
    The default is ``'In [%d]:'``. This expects that the line numbers are used
    in the prompt.
ipython_promptout:
    The string to represent the IPython prompt in the generated ReST. The
    default is ``'Out [%d]:'``. This expects that the line numbers are used
    in the prompt.
ipython_mplbackend:
    The string which specifies if the embedded Sphinx shell should import
    Matplotlib and set the backend. The value specifies a backend that is
    passed to `matplotlib.use()` before any lines in `ipython_execlines` are
    executed. If not specified in conf.py, then the default value of 'agg' is
    used. To use the IPython directive without matplotlib as a dependency, set
    the value to `None`. It may end up that matplotlib is still imported
    if the user specifies so in `ipython_execlines` or makes use of the
    @savefig pseudo decorator.
ipython_execlines:
    A list of strings to be exec'd in the embedded Sphinx shell. Typical
    usage is to make certain packages always available. Set this to an empty
    list if you wish to have no imports always available. If specified in
    ``conf.py`` as `None`, then it has the effect of making no imports available.
    If omitted from conf.py altogether, then the default value of
    ['import numpy as np', 'import matplotlib.pyplot as plt'] is used.
ipython_holdcount
    When the @suppress pseudo-decorator is used, the execution count can be
    incremented or not. The default behavior is to hold the execution count,
    corresponding to a value of `True`. Set this to `False` to increment
    the execution count after each suppressed command.

As an example, to use the IPython directive when `matplotlib` is not available,
one sets the backend to `None`::

    ipython_mplbackend = None

An example usage of the directive is:

.. code-block:: rst

    .. ipython::

        In [1]: x = 1

        In [2]: y = x**2

        In [3]: print(y)

See http://matplotlib.org/sampledoc/ipython_directive.html for additional
documentation.

Pseudo-Decorators
=================

Note: Only one decorator is supported per input. If more than one decorator
is specified, then only the last one is used.

In addition to the Pseudo-Decorators/options described at the above link,
several enhancements have been made. The directive will emit a message to the
console at build-time if code-execution resulted in an exception or warning.
You can suppress these on a per-block basis by specifying the :okexcept:
or :okwarning: options:

.. code-block:: rst

    .. ipython::
        :okexcept:
        :okwarning:

        In [1]: 1/0
        In [2]: # raise warning.

To Do
=====

- Turn the ad-hoc test() function into a real test suite.
- Break up ipython-specific functionality from matplotlib stuff into better
  separated code.

é    N)ÚStringIO)Ú
directives)Ú	Directive)Úlogging)ÚConfig)ÚInteractiveShell)Ú
ProfileDirFTé   ÚsuppressÚverbatimÚsavefigÚdoctestc                    sì  g }|   d¡}t|ƒ}d}d}	||kr*qè|| }
|d7 }|
 ¡ ‰ ˆ  d¡r\| t|
f¡ qt‡ fdd„tD ƒƒr†|	r€tdƒ‚nˆ }	q| 	|
¡}|r†t
| d¡ƒ| d	¡ }}d
d dgtt|ƒƒd	  ¡ }t|ƒ}g }||k rj|| }| 	|¡}|sj| d¡rqjnP| |¡rV||d… }|rH|d dkrH|dd… }|d| 7 }n
| |¡ |d7 }qÜ| t|	|d |¡ff¡ q| 	|
¡}|rt
| d¡ƒ| d	¡ }}||d k rÔd |g||d…  ¡}| t|f¡ qèq|S )a•  
    part is a string of ipython text, comprised of at most one
    input, one output, comments, and blank lines.  The block parser
    parses the text into a list of::

      blocks = [ (TOKEN0, data0), (TOKEN1, data1), ...]

    where TOKEN is one of [COMMENT | INPUT | OUTPUT ] and
    data is, depending on the type of token::

      COMMENT : the comment string

      INPUT: the (DECORATOR, INPUT_LINE, REST) where
         DECORATOR: the input decorator (or None)
         INPUT_LINE: the input as string (possibly multi-line)
         REST : any stdout generated by the input line (not OUTPUT)

      OUTPUT: the output string, possibly multi-line

    Ú
r   Né   ú#c                 3   s   | ]}ˆ   d | ¡V  qdS ©ú@N©Ú
startswith©Ú.0Zpseudo_decorator©Zline_stripped© úd/var/www/html/Darija-Ai-Train/env/lib/python3.8/site-packages/IPython/sphinxext/ipython_directive.pyÚ	<genexpr>  s   ÿzblock_parser.<locals>.<genexpr>z@Applying multiple pseudo-decorators on one line is not supportedé   ú   %s:Ú Ú.ú )ÚsplitÚlenÚstripr   ÚappendÚCOMMENTÚanyÚPSEUDO_DECORATORSÚRuntimeErrorÚmatchÚintÚgroupÚjoinÚstrÚINPUTÚOUTPUT)ÚpartÚrgxinÚrgxoutÚfmtinZfmtoutÚblockÚlinesÚNÚiÚ	decoratorÚlineZmatchinÚlinenoZ	inputlineÚcontinuationZNcÚrestÚnextlineZmatchoutÚoutputr   r   r   Úblock_parserå   sd    

þÿ
 




r>   c                   @   s„   e Zd ZdZd dd„Zdd„ Zdd„ Zd	d
„ Zd!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dd„ ZdS )"ÚEmbeddedSphinxShellz1An embedded IPython instance to run inside SphinxNc           	      C   sâ   t ƒ | _|d krg }tƒ }d|j_d|j_d|j_d|j_t	j
dd}d}tj ||¡}t |¡}tj||d}t | j¡ || _| jj| _| jj| _d| _d| _|| _d| _d| _d| _d | _d| _|D ]}| j|dd	 qÊd S )
Nz:memory:FZNoColorZprofile_)ÚprefixZauto_profile_sphinx_build)ÚconfigZprofile_dirr   ©Ústore_history) r   Úcoutr   ZHistoryManagerZ	hist_filer   ZautocallZ
autoindentÚcolorsÚtempfileÚmkdtempÚosÚpathr+   r   Zcreate_profile_dirÚinstanceÚatexitÚregisterÚcleanupÚIPZuser_nsZuser_global_nsÚinputr=   Útmp_profile_dirÚis_verbatimÚ
is_doctestÚis_suppressÚ	directiveÚ_pyplot_importedÚprocess_input_line)	ÚselfÚ
exec_linesrA   rP   ZprofnameZpdirZprofilerN   r8   r   r   r   Ú__init__V  s6    


zEmbeddedSphinxShell.__init__c                 C   s   t j| jdd d S )NT)Úignore_errors)ÚshutilÚrmtreerP   ©rW   r   r   r   rM   ‹  s    zEmbeddedSphinxShell.cleanupc                 C   s   | j  d¡ | j  d¡ d S )Nr   )rD   ÚseekÚtruncater]   r   r   r   Ú
clear_coutŽ  s    zEmbeddedSphinxShell.clear_coutc                 C   s   | j |g|dS )NrB   )Úprocess_input_lines)rW   r8   rC   r   r   r   rV   ’  s    z&EmbeddedSphinxShell.process_input_lineTc                 C   s:   t j}d |¡}z| jt _| jj||d W 5 |t _X dS )z#process the input, capturing stdoutr   rB   N)ÚsysÚstdoutr+   rD   rN   Zrun_cell)rW   r4   rC   rc   Z
source_rawr   r   r   ra   •  s    
z'EmbeddedSphinxShell.process_input_linesc                 C   s¦   | j }| j}| d¡}|d }t ||¡}d| |¡ ¡  }d| g}|dd… D ]4}	|	 d¡\}
}|
 ¡ }
| ¡ }| d|
|f ¡ qRt	j
 |¡}d	 |¡}||fS )
z¿
        # build out an image directive like
        # .. image:: somefile.png
        #    :width 4in
        #
        # from an input like
        # savefig somefile.png width=4in
        r   r   ú/z.. image:: %sr   Nú=z
   :%s: %sr   )Úsavefig_dirÚ
source_dirr    ÚpathlibÚPathÚrelative_toÚas_posixr"   r#   rH   rI   Úbasenamer+   )rW   r7   rf   rg   ZsaveargsÚfilenamerI   ÚoutfileZ	imagerowsÚkwargÚargÚvalÚ
image_fileÚimage_directiver   r   r   Úprocess_imageŸ  s    	


z!EmbeddedSphinxShell.process_imagec              	   C   s0  |\}}}d}d}|dkp| j }	|dk	r2| d¡p6| j}
|dkpD| j}|dkpR| j}|dkp`| j}|dk	or| d¡}| d¡}t|ƒd	kr |d
 dkr | d¡ dd 	dgtt
|ƒƒd  ¡ }|rÒ|  |¡\}}g }d}|rê| jrêd}nd}tjddL}|d  d¡rd}|	r4|  dg¡ | j jd	7  _n| j||d W 5 Q R X |s”t|ƒD ]8\}}|dkrzd||f }nd||f }| |¡ qZ|s¸t| ¡ ƒr¸|	r¸| |¡ | j d¡ | j ¡ }|sæ|sæ| |¡ n|rö| d¡ d}d}| jjr | jjjj}| jjjj}t t¡}|s–d|ksDd|kr–d}|d||f 7 }|d7 }||d 7 }|d7 }|  |¡ | j!r–t"d #||¡ƒ‚|s|D ]t}d}|d||f 7 }|d7 }|d 7 }|t $|j%|j&|j'|j(|j)¡7 }|d7 }|  |¡ | j!r t"d! #||¡ƒ‚q |  *¡  ||||
|||fS )"z6
        Process data block for INPUT token.

        Nú	@verbatimú@doctestz	@suppressz	@okexceptz
@okwarningz@savefigr   r   éÿÿÿÿr   r   r   r   FT)Úrecordr   ú;rB   ú%s %sÚUnknownÚ	TracebackÚSyntaxErrorzN
>>>-------------------------------------------------------------------------
z+Exception in %s at block ending on line %s
zPSpecify :okexcept: as an option in the ipython:: block to suppress this message
zL<<<-------------------------------------------------------------------------z&Non Expected exception in `{}` line {}z)Warning in %s at block ending on line %s
zQSpecify :okwarning: as an option in the ipython:: block to suppress this message
zM----------------------------------------------------------------------------
z$Non Expected warning in `{}` line {})+rQ   r   rR   rS   Úis_okexceptÚis_okwarningr    r!   r#   r+   r,   rt   Ú
hold_countÚwarningsÚcatch_warningsÚendswithra   rN   Úexecution_countÚ	enumerater"   rD   r^   ÚreadrT   ÚstateÚdocumentÚcurrent_sourceÚcurrent_liner   Ú	getLoggerÚ__name__ÚwarningÚwarning_is_errorr'   ÚformatÚformatwarningÚmessageÚcategoryrm   r9   r8   r`   )rW   ÚdataÚinput_promptr9   r7   rO   r;   rr   rs   rQ   rR   rS   r~   r   Z
is_savefigÚinput_linesr:   ÚretZis_semicolonrC   Úwsr6   r8   Zformatted_lineZprocessed_outputrm   ÚloggerÚsÚwr   r   r   Úprocess_input¿  s¶    
ÿÿÿ

 



)


ÿÿ
    ÿ
   ÿz!EmbeddedSphinxShell.process_inputc                    sH  d‰ |r|dk	r|}|  ¡ }|  ¡ }	| jdkr<d}
d}n,| jjjj}
| jj}d ‡ fdd„|D ƒ¡}| |¡}|dk r¤d}|j|
|d |¡t	|ƒˆ d	}t
|ƒ‚|t|ƒd…   ¡ }|  ¡ d
krþ||	krüd}|j|
|d |¡t	|ƒt	|	ƒˆ d	}t
|ƒ‚n|  ||||	¡ g }|dkp | j}|rD|  ¡ rD| d ||¡¡ |S )z7
        Process data block for OUTPUT token.

        ú    NÚUnavailabler   c                    s   g | ]}ˆ | ‘qS r   r   ©r   r8   ©ZTABr   r   Ú
<listcomp>w  s     z6EmbeddedSphinxShell.process_output.<locals>.<listcomp>r   zƒoutput does not contain output prompt

Document source: {0}

Raw content: 
{1}

Input line(s):
{TAB}{2}

Output line(s):
{TAB}{3}

rŸ   rv   z”doctest failure

Document source: {0}

Raw content: 
{1}

On input line(s):
{TAB}{2}

we found output:
{TAB}{3}

instead of the expected:
{TAB}{4}

ru   z{0} {1}
)r"   rT   r‡   rˆ   r‰   Úcontentr+   Úfindr   Úreprr'   r!   Úcustom_doctestrQ   r#   )rW   r“   Úoutput_promptr•   r=   rR   r7   rr   ÚfoundÚ	submittedÚsourcer¡   ÚindÚeÚout_datarQ   r   rŸ   r   Úprocess_output_  sF    	

 ÿ  ÿ
z"EmbeddedSphinxShell.process_outputc                 C   s   | j s|gS dS )z'Process data fPblock for COMMENT token.N)rS   )rW   r“   r   r   r   Úprocess_comment¯  s    z#EmbeddedSphinxShell.process_commentc                 C   sb   |   ¡  d| }| jddd | jddd | j|dd | jddd | jddd |  ¡  dS )	z/
        Saves the image file to disk.
        zplt.gcf().savefig("%s")zbookmark ipy_thisdirFrB   zcd -b ipy_savedirzcd -b ipy_thisdirzbookmark -d ipy_thisdirN)Úensure_pyplotrV   r`   )rW   rr   Úcommandr   r   r   Ú
save_image´  s    zEmbeddedSphinxShell.save_imagec              
      sj  g }d}d}| j j}| j| }| j| }d}d}	d}
|D ]\}}|tkrV|  |¡}nè|tkr€d}
|  |||¡\}}}}}}}	n¾|tkr>|
s
d‰ d}d}d}| j	rÞ| j	j
jj}| j	j
jj}| j	j}d ‡ fdd	„|D ƒ¡}d
}|j||||ˆ d}tj |¡ tdƒ‚|  |||||||¡}|r>|d dks8t‚|d= |r8| |¡ q8|dk	rb|  |¡ ||	fS )zZ
        process block from the block_parser and return a list of processed lines
        NFTrœ   r   r   r   c                    s   g | ]}ˆ | ‘qS r   r   rž   rŸ   r   r   r    å  s     z5EmbeddedSphinxShell.process_block.<locals>.<listcomp>z²

Invalid block: Block contains an output prompt without an input prompt.

Document source: {0}

Content begins at line {1}: 

{2}

Problematic block within content: 

{TAB}{3}

rŸ   zAn invalid block was detected.rw   r   )rN   r„   ÚpromptinÚ	promptoutr$   r­   r-   r›   r.   rT   r‡   rˆ   rŠ   r‰   r¡   r+   r   rb   rc   Úwriter'   r¬   ÚAssertionErrorÚextendr°   )rW   r3   r–   r=   r•   r9   r”   r¥   rr   rs   Zfound_inputÚtokenr“   r«   rR   r7   Z
linenumberr¨   r¡   rª   r   rŸ   r   Úprocess_blockÂ  sd    

þ
  ÿ

  þÿ

z!EmbeddedSphinxShell.process_blockc                 C   s:   | j s6dtjkr"ddl}| d¡ | jddd d| _ dS )	z¨
        Ensures that pyplot has been imported into the embedded IPython shell.

        Also, makes sure to set the backend appropriately if not set already.

        úmatplotlib.backendsr   NÚaggúimport matplotlib.pyplot as pltFrB   T)rU   rb   ÚmodulesÚ
matplotlibÚuserV   )rW   r¼   r   r   r   r®     s    

ÿz!EmbeddedSphinxShell.ensure_pyplotc              	      s  g }d}d}d}| j }d}t|ƒD ]æ\}}	|	 ¡ ‰ t|	ƒsH| |	¡ q"t‡ fdd„tD ƒƒrx| |	g¡ d|	kr"d}q"ˆ  d¡r| |	g¡ q"d	d
 	dgtt
|ƒƒd  ¡ }
|sd|| ˆ f }| |¡ |d7 }zt ˆ ¡ | d
¡ W n tk
r   d}|}Y nX nÒd|
|	f }| |¡ t|ƒ|d krb||d  }t|ƒt| ¡ ƒ dkrbq"zjt d 	|||d … ¡¡}t|jd tjƒr¼|jd jD ]}t|tjƒr d}q n| d
¡ d}W n tk
râ   Y nX |r"|  ¡  | jddd |  ¡  d}q"|S )a  
        content is a list of strings. it is unedited directive content

        This runs it line by line in the InteractiveShell, prepends
        prompts as needed capturing stderr and stdout, then returns
        the content as a list as if it were ipython code
        FNr   c                 3   s   | ]}ˆ   d | ¡V  qdS r   r   r   r   r   r   r   9  s   ÿz:EmbeddedSphinxShell.process_pure_python.<locals>.<genexpr>r   Tr   r   r   r   r   rz   r   r	   r   z	plt.clf()rB   )r±   r…   r"   r!   r#   r%   r&   rµ   r   r+   r,   ÚastÚparseÚ	ExceptionÚlstripÚ
isinstanceÚbodyÚFunctionDefÚReturnr®   rV   r`   )rW   r¡   r=   r   Ú	multilineZmultiline_startr2   Úctr9   r8   r:   Úmodifiedr<   ÚmodÚelementr   r   r   Úprocess_pure_python!  sp    
þ
 


ÿ

z'EmbeddedSphinxShell.process_pure_pythonc           	      C   sP   ddl m} | ¡ }|d }||kr:|| | ||||ƒ nd |¡}t|ƒ‚dS )z1
        Perform a specialized doctest.

        r   )ÚdoctestszInvalid option to @doctest: {0}N)Zcustom_doctestsrÌ   r    r   rÀ   )	rW   r7   r•   r¦   r§   rÌ   ÚargsZdoctest_typerª   r   r   r   r¤   r  s    
z"EmbeddedSphinxShell.custom_doctest)N)T)rŒ   Ú
__module__Ú__qualname__Ú__doc__rY   rM   r`   rV   ra   rt   r›   r¬   r­   r°   r·   r®   rË   r¤   r   r   r   r   r?   S  s    
5

  !PEQr?   c                   @   sd   e Zd ZdZdZdZdZejej	ej	ej	ej	ej	dœZ
dZeƒ Zdd„ Zdd	„ Zd
d„ Zdd„ ZdS )ÚIPythonDirectiveTr   é   )Úpythonr
   r   r   ÚokexceptÚ	okwarningNc              
   C   sx   | j jjjj}|j}| j jjjj}tj 	||¡}|j
}|j}|j}|j}|j}|j}	|j}
|j}|||||||	|
||f
S )N)r‡   rˆ   ÚsettingsÚenvrA   Úipython_savefig_dirÚsrcdirrH   rI   r+   Úipython_rgxinÚipython_rgxoutÚipython_warning_is_errorÚipython_promptinÚipython_promptoutÚipython_mplbackendÚipython_execlinesÚipython_holdcount)rW   rA   rf   rg   r0   r1   rŽ   r±   r²   Ú
mplbackendrX   r€   r   r   r   Úget_config_options”  s(         ÿz#IPythonDirective.get_config_optionsc              
   C   s@  |   ¡ \
}}}}}}}}}	}
zt |¡ W n0 tk
rZ } z|jtjkrJ‚ W 5 d }~X Y nX | jd krœ|rŠdtjkrŠt	rŠdd l
}| |¡ t|ƒ| _| | j_| jjj| jkrÖ| jjj ¡  d| jj_| j | jjj¡ || j_|| j_|| j_|| j_|| j_|| j_|	| j_|
| j_| jjd| dd | j  ¡  ||||fS )Nr¸   r   r   zbookmark ipy_savedir "%s"FrB   )!rã   rH   ÚmakedirsÚOSErrorÚerrnoÚEEXISTÚshellrb   r»   Úuse_matplotlibr¼   r½   r?   rT   r‡   rˆ   r‰   Ú	seen_docsrN   Zhistory_managerÚresetr„   Úaddr0   r1   r±   r²   rf   rg   r€   rŽ   rV   r`   )rW   rf   rg   r0   r1   r±   r²   râ   rX   r€   rŽ   rª   r¼   r   r   r   Úsetupª  sF    ÿ   



 ÿ
zIPythonDirective.setupc                 C   s   | j jddd | j  ¡  d S )Nzbookmark -d ipy_savedirFrB   )rè   rV   r`   r]   r   r   r   Úteardownß  s    ÿzIPythonDirective.teardownc                 C   s¸  d}|   ¡ \}}}}| j}d|k| j_d|k| j_d|k| j_d|k| j_d|k| j_d| jkrt| j	}| j 
|¡| _	d | j	¡ d	¡}d
dg}	g }
t t¡}|D ]ž}t|||||ƒ}t|ƒr| j |¡\}}|D ]}|	 dd„ | d¡D ƒ¡ qÒ|d k	r>|
 |¡ q d | jjj| jjj¡}| jjr4t|ƒ‚q | |¡ q |
D ]*}|	 d¡ |	 | d¡¡ |	 d¡ qDt|	ƒdkr¬|r”td |	¡ƒ n| j |	| jj  !d¡¡ |  "¡  g S )NFr
   r   r   rÔ   rÕ   rÓ   r   z

z.. code-block:: ipythonr   c                 S   s   g | ]}d   |¡‘qS )z   {0})r   rž   r   r   r   r      s   ÿz(IPythonDirective.run.<locals>.<listcomp>z&Code input with no code at {}, line {}r   r   )#rí   Úoptionsrè   rS   rR   rQ   r~   r   Ú	argumentsr¡   rË   r+   r    r   r‹   rŒ   r>   r!   r·   rµ   r#   r   r‡   rˆ   r‰   rŠ   rŽ   r'   r   ÚprintÚstate_machineZinsert_inputr•   r¨   rî   )rW   Údebugr0   r1   r±   r²   rï   r¡   Úpartsr4   Zfiguresr˜   r/   r3   ÚrowsZfigureÚrowr‘   r   r   r   Úrunå  sZ    



ÿ

ý


 ÿzIPythonDirective.run)rŒ   rÎ   rÏ   Zhas_contentZrequired_argumentsZoptional_argumentsZfinal_argumuent_whitespacer   Z	unchangedÚflagZoption_specrè   Úsetrê   rã   rí   rî   r÷   r   r   r   r   rÑ   ‚  s"   û5rÑ   c                 C   s¾   | t _|  dt¡ |  ddd¡ |  ddd¡ |  dt d¡d¡ |  d	t d
¡d¡ |  ddd¡ |  ddd¡ |  ddd¡ dg}tr”| d¡ |  d|d¡ |  ddd¡ dddœ}|S )NÚipythonrØ   r   r×   rÜ   TrÚ   zIn \[(\d+)\]:\s?(.*)\s*rÛ   zOut\[(\d+)\]:\s?(.*)\s*rÝ   zIn [%d]:rÞ   zOut[%d]:rß   r¹   zimport numpy as nprº   rà   rá   )Zparallel_read_safeZparallel_write_safe)	rí   ÚappZadd_directiverÑ   Zadd_config_valueÚreÚcompileré   r#   )rû   Z	execlinesÚmetadatar   r   r   rí   +  s,     ÿ ÿ

rí   c                  C   sV   ddddddddg} | d	d … } i }| D ](}|  d
¡}tdd ||dd d d d d	 q(d S )Na6  
In [9]: pwd
Out[9]: '/home/jdhunter/py4science/book'

In [10]: cd bookdata/
/home/jdhunter/py4science/book/bookdata

In [2]: from pylab import *

In [2]: ion()

In [3]: im = imread('stinkbug.png')

@savefig mystinkbug.png width=4in
In [4]: imshow(im)
Out[4]: <matplotlib.image.AxesImage object at 0x39ea850>

z´

In [1]: x = 'hello world'

# string methods can be
# used to alter the string
@doctest
In [2]: x.upper()
Out[2]: 'HELLO WORLD'

@verbatim
In [3]: x.st<TAB>
x.startswith  x.strip
a6  

In [130]: url = 'http://ichart.finance.yahoo.com/table.csv?s=CROX\
   .....: &d=9&e=22&f=2009&g=d&a=1&br=8&c=2006&ignore=.csv'

In [131]: print url.split('&')
['http://ichart.finance.yahoo.com/table.csv?s=CROX', 'd=9', 'e=22', 'f=2009', 'g=d', 'a=1', 'b=8', 'c=2006', 'ignore=.csv']

In [60]: import urllib

aä  \

In [133]: import numpy.random

@suppress
In [134]: numpy.random.seed(2358)

@doctest
In [135]: numpy.random.rand(10,2)
Out[135]:
array([[ 0.64524308,  0.59943846],
       [ 0.47102322,  0.8715456 ],
       [ 0.29370834,  0.74776844],
       [ 0.99539577,  0.1313423 ],
       [ 0.16250302,  0.21103583],
       [ 0.81626524,  0.1312433 ],
       [ 0.67338089,  0.72302393],
       [ 0.7566368 ,  0.07033696],
       [ 0.22591016,  0.77731835],
       [ 0.0072729 ,  0.34273127]])

zt
In [106]: print x
jdh

In [109]: for i in range(10):
   .....:     print i
   .....:
   .....:
0
1
2
3
4
5
6
7
8
9
zü

In [144]: from pylab import *

In [145]: ion()

# use a semicolon to suppress the output
@savefig test_hist.png width=4in
In [151]: hist(np.random.randn(10000), 100);


@savefig test_plot.png width=4in
In [151]: plot(np.random.randn(10000), 'o');
   zÌ
# use a semicolon to suppress the output
In [151]: plt.clf()

@savefig plot_simple.png width=4in
In [151]: plot([1,2,3])

@savefig hist_simple.png width=4in
In [151]: hist(np.random.randn(10000), 100);

a~  
# update the current fig
In [151]: ylabel('number')

In [152]: title('normal distribution')


@savefig hist_with_text.png
In [153]: grid(True)

@doctest float
In [154]: 0.1 + 0.2
Out[154]: 0.3

@doctest float
In [155]: np.arange(16).reshape(4,4)
Out[155]:
array([[ 0,  1,  2,  3],
       [ 4,  5,  6,  7],
       [ 8,  9, 10, 11],
       [12, 13, 14, 15]])

In [1]: x = np.arange(16, dtype=float).reshape(4,4)

In [2]: x[0,0] = np.inf

In [3]: x[0,1] = np.nan

@doctest float
In [4]: x
Out[4]:
array([[ inf,  nan,   2.,   3.],
       [  4.,   5.,   6.,   7.],
       [  8.,   9.,  10.,  11.],
       [ 12.,  13.,  14.,  15.]])


        r   r   ró   r   )rð   rï   r¡   r9   Zcontent_offsetZ
block_textr‡   rò   )r    rÑ   )Zexamplesrï   Zexampler¡   r   r   r   ÚtestK  s,     
   ýrÿ   Ú__main__Z_staticz!All OK? Check figures in _static/)+rÐ   rK   ræ   rH   rh   rü   rb   rF   r¾   r   r[   Úior   Zdocutils.parsers.rstr   r   Zsphinx.utilr   Ztraitlets.configr   ZIPythonr   ZIPython.core.profiledirr   ré   r¼   rÀ   Úranger$   r-   r.   r&   r>   Úobjectr?   rÑ   rí   rÿ   rŒ   rI   ÚisdirÚmkdirrñ   r   r   r   r   Ú<module>   sT    ;n    3 *  *

