
    MZd>                    4   U d Z ddlm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
mZ  G d de      ZddZdd	Zd
 Z e ej$                  d      dz        dz   Z eej*                  dd      Zg aded<   dad Zd Zd ZddZddZd Zd Z ddZ!d Z"d dZ#y)!z;Miscellaneous stuff that does not really fit anywhere else.    )annotationsN)filldedentc                      e Zd Zy)UndecidableN)__name__
__module____qualname__     6/usr/lib/python3/dist-packages/sympy/utilities/misc.pyr   r      s     	r   r   c                f    dt        t        t        |             j                  d      fd|i|z   S )a  
    Strips leading and trailing empty lines from a copy of ``s``, then dedents,
    fills and returns it.

    Empty line stripping serves to deal with docstrings like this one that
    start with a newline after the initial triple quote, inserting an empty
    line at the beginning of the string.

    Additional keyword arguments will be passed to ``textwrap.fill()``.

    See Also
    ========
    strlines, rawlines

    
width)r   r   strstrip)swkwargss      r   
filldedentr      s1      $vc!f~++D1EEfEEEr   Fc                   t        | t              st        d      d| v rt        |       S t	        |       j                  d      rdnd}|fdz  }d| v rd|z  }d|z  }|d	z  }nd
|z  }d|z  }|dz  }g }| r|j                  | d|        | |d } | r|r't        |      dk(  r||d   z  j                         d   S ||j                  |      z  S )aX  Return a cut-and-pastable string that, when printed, is
    equivalent to the input.  The lines will be surrounded by
    parentheses and no line will be longer than c (default 64)
    characters. If the line contains newlines characters, the
    `rawlines` result will be returned.  If ``short`` is True
    (default is False) then if there is one line it will be
    returned without bounding parentheses.

    Examples
    ========

    >>> from sympy.utilities.misc import strlines
    >>> q = 'this is a long string that should be broken into shorter lines'
    >>> print(strlines(q, 40))
    (
    'this is a long string that should be b'
    'roken into shorter lines'
    )
    >>> q == (
    ... 'this is a long string that should be b'
    ... 'roken into shorter lines'
    ... )
    True

    See Also
    ========
    filldedent, rawlines
    zexpecting string inputr   "'   \z(
r%s%%s%s
)z%s
r%s   z(
%s%%s%s
)z%s
%sN   r   )

isinstancer   
ValueErrorrawlinesrepr
startswithappendlen
splitlinesjoin)r   cshortqmjouts          r   strlinesr-   &   s    : a122qy{Aw!!#&CA	
QAqyq M	QaqL	Q
C


1Ra5
AB%  SQCF
&&(++qvvc{?r   c                   | j                  d      }t        |      dk(  rt        |d         S d| v d| v g}t        d |D              sd| v st	        |      rg }| j                  d      }t        |      dz
  }t        |      D ]D  \  }}||k7  s|r|j                  t        |dz                +|j                  t        |             F dd	j                  |      z  S d	j                  |      }|d   rd
|z  S d|z  S )ax  Return a cut-and-pastable string that, when printed, is equivalent
    to the input. Use this when there is more than one line in the
    string. The string returned is formatted so it can be indented
    nicely within tests; in some cases it is wrapped in the dedent
    function which has to be imported from textwrap.

    Examples
    ========

    Note: because there are characters in the examples below that need
    to be escaped because they are themselves within a triple quoted
    docstring, expressions below look more complicated than they would
    be if they were printed in an interpreter window.

    >>> from sympy.utilities.misc import rawlines
    >>> from sympy import TableForm
    >>> s = str(TableForm([[1, 10]], headings=(None, ['a', 'bee'])))
    >>> print(rawlines(s))
    (
        'a bee\n'
        '-----\n'
        '1 10 '
    )
    >>> print(rawlines('''this
    ... that'''))
    dedent('''\
        this
        that''')

    >>> print(rawlines('''this
    ... that
    ... '''))
    dedent('''\
        this
        that
        ''')

    >>> s = """this
    ... is a triple '''
    ... """
    >>> print(rawlines(s))
    dedent("""\
        this
        is a triple '''
        """)

    >>> print(rawlines('''this
    ... that
    ...     '''))
    (
        'this\n'
        'that\n'
        '    '
    )

    See Also
    ========
    filldedent, strlines
    r   r   r   z'''z"""c              3  >   K   | ]  }|j                  d         yw) N)endswith).0lis     r   	<genexpr>zrawlines.<locals>.<genexpr>   s     
,2;;s
,s   r   z
(
    %s
)z
    zdedent("""\
    %s""")zdedent('''\
    %s'''))	splitr$   r!   anyallr1   	enumerater#   r&   )r   linestriplervtrailinglastir3   s           r   r    r    Z   s    x GGDME
5zQE!H~qj%1*%F

,e
,,	S[::d#5zA~u% 	$EArDyH		$rDy/*		$r(#		$
 b 111]]5!!9-22-22r   P   z-bithash_randomizationz	list[str]
_debug_tmpc                0     ddl m} |s S d  fd}|S )zIf SYMPY_DEBUG is True, it will print a nice execution tree with
    arguments and results of all decorated functions, else do nothing.
    r   SYMPY_DEBUGc                   t         }g a t        dz  ad } | |i |}t        dz  a| j                  |d|d}t         g k7  r| |t               z  }|a t         j                  |       t        dk(  rt	        t         d          g a |S )Nr   c                    dd}t        |       dk(  ryg }| d d D ]  }|j                   ||              |j                   || d   d             dj                  |      S )Nc                    | j                  d      }d|d   z  }|dd  D ]  }|dk(  r	|dk(  r	|d|z  z  }|d|z  z  }  |S )Nr   z+-%s
r   r    z| %s
z  %s
)r5   )r   variantxras        r   indentz?debug_decorator.<locals>.maketree.<locals>.tree.<locals>.indent   se    GGDMqtO12 *ABw !|X\)X\)* r   r   rI   r   )r   )r$   r#   r&   )subtreesrN   frM   s       r   treez/debug_decorator.<locals>.maketree.<locals>.tree   sg    
 8}!Acr] $#$HHVHRL!,-771:r   z = r   r   )rB   _debug_iterr   r#   print)rQ   argskwoldtmprR   rL   r   s          r   maketreez!debug_decorator.<locals>.maketree   s     
q	6 tNrNqZZq1j!!A
!!*Q- Jr   c                      g| i |S Nr   )rU   r   funcrX   s     r   	decoratedz"debug_decorator.<locals>.decorated   s    .t.v..r   )sympyrE   )r[   rE   r\   rX   s   `  @r   debug_decoratorr^      s#     "-^/ r   c                 H    ddl m} |rt        | dt        j                  i yy)zB
    Print ``*args`` if SYMPY_DEBUG is True, else do nothing.
    r   rD   fileNr]   rE   rT   sysstderr)rU   rE   s     r   debugrd      s      "t%#**% r   c                R    ddl m} |rt        | |z  t        j                         yy)z
    Print ``string%args`` if SYMPY_DEBUG is True, else do nothing. This is
    intended for debug messages using formatted strings.
    r   rD   )r`   Nra   )stringrU   rE   s      r   debugfrg      s!    
 "fTk

+ r   c                   ddl m}  |ddd       |t        j                  d   }|j	                  t        j
                        }d	g}t        j                  d
k(  r*t        j                  j                  |       \  }}|s| dz   } nt        j                  dk(  rtt        j                  d   j                         j	                  t        j
                        }t        j                  j                  |       \  }}|j                         |vr|}|D ]v  }| |z   }t        j                  j                  |      r|c S |D ]G  }	t        j                  j                  |	|      }
t        j                  j                  |
      sC|
c c S  x y)zTry to find 'executable' in the directories listed in 'path' (a
    string listing directories separated by 'os.pathsep'; defaults to
    os.environ['PATH']).  Returns the complete filename or None if not
    found
    r   )sympy_deprecation_warningz
        sympy.utilities.misc.find_executable() is deprecated. Use the standard
        library shutil.which() function instead.
        z1.7zdeprecated-find-executable)deprecated_since_versionactive_deprecations_targetNPATHrI   os2z.exewin32PATHEXT)
exceptionsri   osenvironr5   pathsepnamepathsplitextrb   platformlowerisfiler&   )
executableru   ri   pathsextlistbaseextpathextexecnameprQ   s              r   find_executabler     sE    6	 "'#? |zz&!JJrzz"EdG	ww%gg&&z2s #f,J		 **Y'--/55bjjAgg&&z2s99;g%G #77>>(#O GGLLH-77>>!$H r   c                   ddddddd}t        |       }t        |      j                  d      r0t        |      j                  d	      d
   j                  d	      d   }nIt        |      j                  d      r/t        |      j                  d	      d
   j                  d	      d   }t	        t	        | d|       d|      }d|v r|j                  d      d   }|r|j                  ||      }|S )a  Return function name of `x` (if defined) else the `type(x)`.
    If short is True and there is a shorter alias for the result,
    return the alias.

    Examples
    ========

    >>> from sympy.utilities.misc import func_name
    >>> from sympy import Matrix
    >>> from sympy.abc import x
    >>> func_name(Matrix.eye(3))
    'MutableDenseMatrix'
    >>> func_name(x < 1)
    'StrictLessThan'
    >>> func_name(x < 1, short=True)
    'Lt'
    GeGtLeLtEqNe)GreaterThanStrictGreaterThanLessThanStrictLessThanEquality
Unequalityz<type 'r   r   r   z<class 'r[   r   .rO   )typer   r"   r5   getattrget)rK   r(   aliastypr;   s        r   	func_namer   1  s    & E q'C
3x9%#hnnS!!$**3/2	S		Z	(#hnnS!!$**3/2	FA&
C	8B
byXXc]2YYr2Ir   c                     sd S  fdt        j                  dj                   j                         D cg c]  \  }}t        j                  |       c}}      t         j
                        fdS c c}}w )aU  Return a function that can make the replacements, given in
    ``reps``, on a string. The replacements should be given as mapping.

    Examples
    ========

    >>> from sympy.utilities.misc import _replace
    >>> f = _replace(dict(foo='bar', d='t'))
    >>> f('food')
    'bart'
    >>> f = _replace({})
    >>> f('food')
    'food'
    c                    | S rZ   r   )rK   s    r   <lambda>z_replace.<locals>.<lambda>h  s     r   c                ,    | j                  d         S )Nr   )group)matchrepss    r   r   z_replace.<locals>.<lambda>i  s    d5;;q>* r   |c                (    j                  |       S rZ   )sub)rf   Dpatterns    r   r   z_replace.<locals>.<lambda>l  s    '++a0 r   )_recompiler&   itemsescapeM)r   kvr   r   s   `  @@r   _replacer   X  s^     *Akk#((#'::<041aA023655:G00 	1s   A;c                    t        |      dk(  r'|d   }t        |t              r|}n | j                  | S t        |      } t	        |      |       S )ar  Return ``string`` with all keys in ``reps`` replaced with
    their corresponding values, longer strings first, irrespective
    of the order they are given.  ``reps`` may be passed as tuples
    or a single mapping.

    Examples
    ========

    >>> from sympy.utilities.misc import replace
    >>> replace('foo', {'oo': 'ar', 'f': 'b'})
    'bar'
    >>> replace("spamham sha", ("spam", "eggs"), ("sha","md5"))
    'eggsham md5'

    There is no guarantee that a unique answer will be
    obtained if keys in a mapping overlap (i.e. are the same
    length and have some identical sequence at the
    beginning/end):

    >>> reps = [
    ...     ('ab', 'x'),
    ...     ('bc', 'y')]
    >>> replace('abc', *reps) in ('xc', 'ay')
    True

    References
    ==========

    .. [1] https://stackoverflow.com/questions/6116978/how-to-replace-multiple-substrings-of-a-string
    r   r   )r$   r   dictreplacer   )rf   r   kvs      r   r   r   o  sR    > 4yA~!Wb$D!6>>2&&Dz8D>&!!r   c                   i }||t        d|z        || S |}dx}}nt        |t              ri }t        |j	                               D ]7  }t        |      dk(  st        ||         dk(  s$|j                  |      ||<   9 |}|}|r@t        t        |j                                D cg c]  }dj                  |       c}\  }}n'dx}}n"t        |      t        |      k7  rt        d      |r(t        j                  dd|      }| j                  |      } t        | |      } t        j                  ||      }	| j                  |	      S c c}w )a  Return ``s`` where characters have been replaced or deleted.

    SYNTAX
    ======

    translate(s, None, deletechars):
        all characters in ``deletechars`` are deleted
    translate(s, map [,deletechars]):
        all characters in ``deletechars`` (if provided) are deleted
        then the replacements defined by map are made; if the keys
        of map are strings then the longer ones are handled first.
        Multicharacter deletions should have a value of ''.
    translate(s, oldchars, newchars, deletechars)
        all characters in ``deletechars`` are deleted
        then each character in ``oldchars`` is replaced with the
        corresponding character in ``newchars``

    Examples
    ========

    >>> from sympy.utilities.misc import translate
    >>> abc = 'abc'
    >>> translate(abc, None, 'a')
    'bc'
    >>> translate(abc, {'a': 'x'}, 'c')
    'xb'
    >>> translate(abc, {'abc': 'x', 'a': 'y'})
    'x'

    >>> translate('abcd', 'ac', 'AC', 'd')
    'AbC'

    There is no guarantee that a unique answer will be
    obtained if keys in a mapping overlap are the same
    length and have some identical sequences at the
    beginning/end:

    >>> translate(abc, {'ab': 'x', 'bc': 'y'}) in ('xc', 'ay')
    True
    z6c should be None when a=None is passed, instead got %srI   r   z,oldchars and newchars have different lengths)r   r   r   listkeysr$   popzipr   r&   r   	maketrans	translater   )
r   rM   br'   mrr(   r   r>   valns
             r   r   r     sB   T 
By=UXYYZZ9H
AaE!&&(^ (q6Q;3qt9> uuQxE!H( BA,0ekkm1D,EFq
F1
AVs1vKLLmmBA&KK2AaA;;q> Gs   ,Ec                    t        |       }t        |      dz  }d|cxk  rdk  rn nd}n#|dz  dk(  rd}n|dz  dk(  rd	}n|dz  d
k(  rd}nd}t        |      |z   S )z=Return ordinal number string of num, e.g. 1 becomes 1st.
    d         th
   r   str   ndr   rd)as_intabsr   )numr   r   suffixs       r   ordinalr     sm     	sAAA	Q}"}	
R1	
R1	
R1q6F?r   c                   |r,	 t        | t              rt        t        j                  |       S 	 t        |       }| |k7  rt        | d      |S # t        $ r t        | d      w xY w# t        $ r t        | d      w xY w)a  
    Convert the argument to a builtin integer.

    The return value is guaranteed to be equal to the input. ValueError is
    raised if the input has a non-integral value. When ``strict`` is True, this
    uses `__index__ <https://docs.python.org/3/reference/datamodel.html#object.__index__>`_
    and when it is False it uses ``int``.


    Examples
    ========

    >>> from sympy.utilities.misc import as_int
    >>> from sympy import sqrt, S

    The function is primarily concerned with sanitizing input for
    functions that need to work with builtin integers, so anything that
    is unambiguously an integer should be returned as an int:

    >>> as_int(S(3))
    3

    Floats, being of limited precision, are not assumed to be exact and
    will raise an error unless the ``strict`` flag is False. This
    precision issue becomes apparent for large floating point numbers:

    >>> big = 1e23
    >>> type(big) is float
    True
    >>> big == int(big)
    True
    >>> as_int(big)
    Traceback (most recent call last):
    ...
    ValueError: ... is not an integer
    >>> as_int(big, strict=False)
    99999999999999991611392

    Input that might be a complex representation of an integer value is
    also rejected by default:

    >>> one = sqrt(3 + 2*sqrt(2)) - sqrt(2)
    >>> int(one) == 1
    True
    >>> as_int(one)
    Traceback (most recent call last):
    ...
    ValueError: ... is not an integer
    z is not an integer)r   bool	TypeErroroperatorindexr   int)r   strictresults      r   r   r     s    d 	<!T">>!$$	<VF ;q:;;  	<q:;;	<
  	<q:;;	<s   *A A+ A(+B)F   )@   FrZ   )F)NN)T)$__doc__
__future__r   r   rb   rq   rer   structtextwrapr   r   r   r   r   r-   r    r   calcsizeARCHr   flagsHASH_RANDOMIZATIONrB   __annotations__rS   r^   rd   rg   r   r   r   r   r   r   r   r   r   r   <module>r      s    A "  
 	   !	* 	F&1hP3d ?6??3!#$v- SYY(<eD 
I ;|&,(V$N1.'"TFR&@r   