
    gf`                     ,   d Z ddlmZmZmZ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 ddddd	d
edZdZ ee      D  ci c]  \  } }|| 
 c}} Zed   Zg ZdZd Z	 ddlmZ dZ	 d)dZ	 	 	 d*dZ	 d+dZd Zd Z	 	 d,dZeedfdZd-dZ ddefdZ!eddddd dfd!Z"e#ed"   ed#   ed$   fd%Z$d& Z% e$e#ed"   ed#   ed$         Z& e!ejN                  jQ                  e#             dd'l) ddl)Z*e+d(k(  r	 e%e        yyc c}} w # e$ r dZeZY w xY w).zA
FlyingCircus - Everything you always wanted to have in Python.*
    )divisionabsolute_importprint_functionunicode_literalsN)__version__FlyingCircuszFlyingCircus developers)z Riccardo Metere <rick@metere.it>zCopyright (C) 2014-2018z6GNU General Public License version 3 or later (GPLv3+)z
This program is free software and it comes with ABSOLUTELY NO WARRANTY.
It is covered by the GNU General Public License version 3 (GPLv3+).
You are welcome to redistribute it under its terms and conditions.
        )nameauthorcontrib	copyrightlicensenoticeversion)
nonelowestlowerlowmediumhighhigherhighestwarningdebugr   aW  
 _____ _       _              ____ _                    
|  ___| |_   _(_)_ __   __ _ / ___(_)_ __ ___ _   _ ___ 
| |_  | | | | | | '_ \ / _` | |   | | '__/ __| | | / __|
|  _| | | |_| | | | | | (_| | |___| | | | (__| |_| \__ \
|_|   |_|\__, |_|_| |_|\__, |\____|_|_|  \___|\__,_|___/
         |___/         |___/                            
c                      d }t        |       dkD  rt        | d         rt        |      dkD  r|S t        |       dk(  r|S | d   S )aC  
    Callable decorator that does nothing.

    Arguments are catched, but ignored.
    This is very useful to provide proxy for decorators that may not be
    defined.

    Args:
        *_args: Positional arguments.
        **_kws: Keyword arguments.

    Returns:
        result (callable): The unmodified callable.
    c                     | S N )fs    m/var/dept/share/cheung/public_html/OutSchool/python/env/lib/python3.12/site-packages/flyingcircus/__init__.pywrapperz%do_nothing_decorator.<locals>.wrapperb   s        r   )lencallable)_args_kwsr    s      r   do_nothing_decoratorr&   R   sG      5zA~huQx0CIM	UqQxr!   )jitTFc                 T    |r| |z  S | dk  r| | k  ry| dk  r| |z   S | |k\  r|dz
  S | S )a  
    Return a valid index for an object of given size.

    Args:
        idx (int): The input index.
        size (int): The size of the object to index.
        circular (bool): Use circular normalization.
            If True, just use a modulo operation.
            Otherwise, indices beyond the edges are set to the edges.

    Returns:
        idx (int): The valid index.

    Examples:
        >>> print([(i, valid_index(i, 3)) for i in range(-4, 4)])
        [(-4, 0), (-3, 0), (-2, 1), (-1, 2), (0, 0), (1, 1), (2, 2), (3, 2)]
        >>> print([(i, valid_index(i, 3, True)) for i in range(-4, 4)])
        [(-4, 2), (-3, 0), (-2, 1), (-1, 2), (0, 0), (1, 1), (2, 2), (3, 0)]
    r      r   )idxsizecirculars      r   valid_indexr-   y   sI    . Tz	qSD5[	qTz	ax
r!   c              #      K   t        |       }|dkD  rZt        ||      }t        ||      }|rdnt        |      xs d}|}	 | j                  ||      }d|cxk  r|k  rn n
| ||z  }ny,yw)aB  
    Find all occurrences of the pattern in the text.

    For dense inputs (pattern is more than ~20% of the text), a looping
    comprehension may be faster.

    Args:
        text (str|bytes|bytearray): The input text.
        pattern (str|bytes|bytearray): The pattern to find.
        overlap (bool): Detect overlapping patterns.
        first (int): The first index.
            The index is forced within boundaries.
        last (int): The last index (included).
            The index is forced within boundaries.

    Yields:
        position (int): The position of the next finding.

    Examples:
        >>> list(find_all('0010120123012340123450123456', '0'))
        [0, 1, 3, 6, 10, 15, 21]
        >>> list(find_all('  1 12 123 1234 12345 123456', '0'))
        []
        >>> list(find_all('  1 12 123 1234 12345 123456', '12'))
        [4, 7, 11, 16, 22]
        >>> list(find_all(b'  1 12 123 1234 12345 123456', b'12'))
        [4, 7, 11, 16, 22]
        >>> list(find_all(bytearray(b'  1 12 123 1234 12345 123456'), b'12'))
        [4, 7, 11, 16, 22]
        >>> list(find_all('0123456789', ''))
        [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
        >>> list(find_all('', ''))
        []
        >>> list(find_all('', '0123456789'))
        []
        >>> list(find_all(b'0123456789', b''))
        [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
        >>> list(find_all(b'', b''))
        []
        >>> list(find_all(b'', b'0123456789'))
        []
        >>> list(find_all('000000000', '000'))
        [0, 3, 6]
        >>> list(find_all('000000000', '000', True))
        [0, 1, 2, 3, 4, 5, 6]
    r   r)   N)r"   r-   find)textpatternoverlapfirstlastnoffsetis           r   find_allr8      s     h 	D	A1uE1%4#CL$5A		'1%AA~~V  	s   A,A.c           	   #     K   |rt        |      nd}|rt        |      nd}g }t        t        | |            }t        t        | |            }|j                  |      }	t	        |	      D ]  }
|
|v r|j                  |
dz          |
|v s!t        |      dkD  r'|j                         }||z
  |
|z   t        |      f Vt        dj                  t        |      t        |      z
  ||
             t        |      dkD  rBt        dj                  t        |      t        |      z
  ||j                         dz
              yw)a  
    Find matching delimiters in a sequence.

    The delimiters are matched according to nesting level.

    Args:
        text (str|bytes|bytearray): The input text.
        l_delim (str|bytes|bytearray): The left delimiter.
        r_delim (str|bytes|bytearray): The right delimiter.
        including (bool): Include delimiters.

    yields:
        result (tuple[int]): The matching delimiters.

    Examples:
        >>> s = '{a} {b:{c}}'
        >>> list(nested_delimiters(s, '{', '}'))
        [(0, 3, 0), (7, 10, 1), (4, 11, 0)]
        >>> [s[i:j] for i, j, depth in nested_delimiters(s, '{', '}')]
        ['{a}', '{c}', '{b:{c}}']
        >>> [s[i:j] for i, j, d in nested_delimiters(s, '{', '}') if d == 0]
        ['{a}', '{b:{c}}']
        >>> list(nested_delimiters('{a} {b:{c}', '{', '}'))
        Traceback (most recent call last):
            ...
        ValueError: Found `1` unmatched left token(s) `{` (position: 4).
        >>> list(nested_delimiters('{a}} {b:{c}}', '{', '}'))
        Traceback (most recent call last):
            ...
        ValueError: Found `1` unmatched right token(s) `}` (position: 3).
        >>> list(nested_delimiters(s.encode(), b'{', b'}'))
        [(0, 3, 0), (7, 10, 1), (4, 11, 0)]
        >>> list(nested_delimiters(bytearray(s.encode()), b'{', b'}'))
        [(0, 3, 0), (7, 10, 1), (4, 11, 0)]

    See Also:
        - flyingcircus.nested_pairs()
    r   r)   z8Found `{}` unmatched right token(s) `{}` (position: {}).z7Found `{}` unmatched left token(s) `{}` (position: {}).N)	r"   setr8   unionsortedappendpop
ValueErrorformat)r0   l_delimr_delim	includingl_offsetr_offsetstackl_tokensr_tokens	positionsposprevs               r   nested_delimitersrL      s5    V  )s7|aH(s7|aHE8D'*+H8D'*+Hx(Ii  
N(?LLq!H_5zA~yy{hhE
CC NHH =wLN N
N 5zA~EHH-w		aIJ 	J s   BE
B8Ec                 f   g }t        | dd      D ]5  \  }}}|dk(  s	 | || j                  |      }|j                  |||f       7 d}t	        |       d}}t	        |      dkD  r0|}|j                         \  }}}|| || z   |z   }t	        |      dkD  r0|dkD  r| d| |z   }|S # t        $ r Y w xY w)a  
    Perform safe string formatting from a mapping source.

    If a value is missing from source, this is simply ignored, and no
    `KeyError` is raised.

    Args:
        text (str): Text to format.
        source (Mapping|None): The mapping to use as source.
            If None, uses caller's `vars()`.

    Returns:
        result (str): The formatted text.

    See Also:
        - flyingcircus.fmt()
        - flyingcircus.fmtm()

    Examples:
        >>> text = '{a} {b} {c}'
        >>> safe_format_map(text, dict(a='-A-'))
        '-A- {b} {c}'
        >>> safe_format_map(text, dict(b='-B-'))
        '{a} -B- {c}'
        >>> safe_format_map(text, dict(c='-C-'))
        '{a} {b} -C-'

        >>> source = dict(a=4, c=101, d=dict(x='FOO'), e=[1, 2])
        >>> safe_format_map('{b} {f}', source)
        '{b} {f}'
        >>> safe_format_map('{a} {b}', source)
        '4 {b}'
        >>> safe_format_map('{a} {b} {c:5d}', source)
        '4 {b}   101'
        >>> safe_format_map('{a} {b} {c!s}', source)
        '4 {b} 101'
        >>> safe_format_map('{a} {b} {c!s:>{a}s}', source)
        '4 {b}  101'
        >>> safe_format_map('{a} {b} {c:0{a}d}', source)
        '4 {b} 0101'
        >>> safe_format_map('{a} {b} {d[x]}', source)
        '4 {b} FOO'
        >>> safe_format_map('{a} {b} {e.index}', source)  # doctest:+ELLIPSIS
        '4 {b} <built-in method index of list object at ...>'
        >>> safe_format_map('{a} {b} {f[g]}', source)
        '4 {b} {f[g]}'
        >>> safe_format_map('{a} {b} {f.values}', source)
        '4 {b} {f.values}'
        >>> safe_format_map('{a} {b} {e[0]}', source)
        '4 {b} 1'
        >>> safe_format_map('{{a}} {b}', source)
        '{a} {b}'
        >>> safe_format_map('{{a}} {{b}}', source)
        '{a} {b}'
    {}r    )rL   
format_mapr=   KeyErrorr"   r>   )	r0   sourcerF   r7   jdepth	replacingresultlast_is	            r   safe_format_maprY   (  s    t E(sC8 01eA:0 1I008	 aI./0 Ft9aqA
e*q.))+1iT!F^+f4 e*q. 	1uaV#M  s   B$$	B0/B0c                 &     | j                   |i |S )a  
    Perform string formatting using `text.format()`.

    Args:
        text (str): Text to format.
        *_args: Positional arguments for `str.format()`.
        **_kws: Keyword arguments for `str.format()`.

    Returns:
        result (str): The formatted text.

    Examples:
        >>> a, b, c = 1, 2, 3
        >>> dd = dict(a=10, b=20, c=30)
        >>> fmt('{a} + {a} = {b}', a=a, b=b)
        '1 + 1 = 2'
        >>> fmt('{a} + {a} = {b}', **dd)
        '10 + 10 = 20'
        >>> fmt('{} + {} = {}', 2, 2, 4)
        '2 + 2 = 4'
        >>> fmt('{b} + {b} = {}', 4, b=2)
        '2 + 2 = 4'

    See Also:
        - flyingcircus.fmtm()
        - flyingcircus.partial_format()
    )r@   )r0   r$   r%   s      r   fmtr[   w  s    > 4;;&&&r!   c                     |*t        j                         }|j                  j                  }|rt	        | |      S | j                  |      S )a  
    Perform string formatting from a mapping source.

    Args:
        text (str): Text to format.
        source (Mapping|None): The mapping to use as source.
            If None, uses caller's `vars()`.
        safe (bool): Apply mapping safely.
            Uses `flyingcircus.partial_format()`.

    Returns:
        result (str): The formatted text.

    Examples:
        >>> a, b, c = 1, 2, 3
        >>> dd = dict(a=10, b=20, c=30)
        >>> fmtm('{a} + {a} = {b}')
        '1 + 1 = 2'
        >>> fmtm('{a} + {a} = {b}', dd)
        '10 + 10 = 20'
        >>> fmtm('{} + {} = {}', 2, 2, 4)  # doctest:+ELLIPSIS
        Traceback (most recent call last):
            ...
        TypeError: fmtm() takes from 1 to 3 positional arguments ...
        >>> fmtm('{b} + {b} = {}', 4)  # doctest:+ELLIPSIS
        Traceback (most recent call last):
            ...
        TypeError: ...

    See Also:
        - flyingcircus.fmt()
        - flyingcircus.partial_format()
    )inspectcurrentframef_backf_localsrY   rQ   )r0   rS   safeframes       r   fmtmrc     sF    J ~$$&&&tV,,v&&r!   c                    ||k\  r| 	 ddl m} t	        |      r |       nd}||rt        |       } |du rt        d   |cxk  rt        d   k  rn n|j                  }nt        d   |cxk  rt        d   k  rn n|j                  }n|t        d   k\  r|j                  }nf| j                  d	      r|j                  }nH| j                  d
      r|j                  }n*| j                  d      r|j                  }n|j                  }t        | j!                               dkD  r| j#                  dd      d   nd}	| j%                  |	      }
| d|
 }| |
t        |	      z   d }t'        |||j                  k(  r|j(                  ndz   |||j                  k7  r|j(                  ndz   ||	||j*                        }dj-                  |      } n>d|vrdj/                  |      }d|vr|dz  }|j/                  | |      |j*                  z   } t1        | g|i | yyy# t        $ r 	 ddlm} n# t        $ r d}Y nw xY wY 3w xY w)a  
    Display a feedback message to the standard output.

    Args:
        text (str|Any): Message to display or object with `__str__`.
        verb_lvl (int): Current level of verbosity.
        verb_threshold (int): Threshold level of verbosity.
        fmtt (str|bool|None): Format of the message (if `blessed` supported).
            If True, a standard formatting is used.
            If False, empty string or None, no formatting is applied.
            If str, the specified formatting is used.
            This must be in the form of `{t.NAME}` where `NAME` refer to
            a formatting supported by `Terminal()` from `blessed`/`blessings`.
        *_args: Positional arguments for `print()`.
        **_kws: Keyword arguments for `print()`.

    Returns:
        None.

    Examples:
        >>> s = 'Hello World!'
        >>> msg(s)
        Hello World!
        >>> msg(s, VERB_LVL['medium'], VERB_LVL['low'])
        Hello World!
        >>> msg(s, VERB_LVL['low'], VERB_LVL['medium'])  # no output
        >>> msg(s, fmtt='{t.green}')  # if ANSI Terminal, green text
        Hello World!
        >>> msg('   :  a b c', fmtt='{t.red}{}')  # if ANSI Terminal, red text
           :  a b c
        >>> msg(' : a b c', fmtt='cyan')  # if ANSI Terminal, cyan text
         : a b c
    Nr   )TerminalFTr   r   r   zI:zW:zE:r)   rP   )e1e2t0t1t2r5   z{t0}{e1}{t1}{n}{e2}{t2}{n}zt.z{{t.{}}}z{})t)blessedre   ImportError	blessingsr#   strVERB_LVLcyanmagentablue
startswithgreenyellowredwhiter"   stripsplitr/   dictboldnormalrQ   r@   print)r0   verb_lvlverb_thresholdfmttr$   r%   re   rk   etxt1r5   txt0txt2txt_kwss                 r   msgr     s   P >!d&6	!( #8,HJ$=Tt9Dt|E?^Ix7IIAh'.L8G;LL		A#x'88A__T*A__T*A__T*AA14TZZ\1BQ1Ftzz$*1-BIIdOBQxAD	MN+a177lAFF;a177lAFF;; 4>>wGt#%,,T2Dt#DLD{{41{-8d#U#d#] '7!  	!!. ! !	!s5   H 	I)H0/I0H>;I=H>>IIc                    t        j                  t        j                               d   }|d   d   dd }t        ||d       t	        | t
              r"t        t        | j                                     } t        |       }t        |d	       y)
a  
    Print content of a variable for debug purposes.

    Args:
        obj: The name to be inspected.
        fmt (str): Format of the message (if `blessed` supported).
            If None, a standard formatting is used.

    Returns:
        None.

    Examples:
        >>> my_dict = {'a': 1, 'b': 1}
        >>> dbg(my_dict)
        dbg(my_dict): (('a', 1), ('b', 1))
        >>> dbg(my_dict['a'])
        dbg(my_dict['a']): 1
    r)      r   N: r   endr}   r   )
r]   getouterframesr^   r   
isinstancer{   tupler<   itemsrepr)objr   outer_framename_strr0   s        r   dbgr   #  su    & (()=)=)?@CK1~a "%Ht&#tF399;'(9D8r!   c                     | %t         }t        j                  j                  |      } |st        j                  j                         }|j                  | |f       y)a_  
    Append a named event point to the events list.

    Args:
        name (str): The name of the event point.
        time_point (float): The time in seconds since the epoch.
        events (list[(str,datetime.datetime)]): A list of named time points.
            Each event is a 2-tuple: (label, datetime.datetime).

    Returns:
        None.
    N)__file__ospathbasenamedatetimenowr=   )r	   
time_pointeventsfilenames       r   elapsedr   @  sJ      |ww)&&**,

MM4$%r!   zElapsed Time(s))LabelzDuration / szCum. Duration / s)$      r   =-c           	         d}| rT|s	t        |       dkD  r dj                  | }|r|t        |      z  dt        |       dz   nd}||t        |       dkD  rd|z   dz   ndz   z  }|r t        |       dkD  r| |j                  | z  }|r&| |j                  |D 	cg c]
  }	||	z  d|	  c}	 z  }| d   d   }
t        dt        |             D ]B  }| |   \  }}| |dz
     d   }||
z
  }||z
  }||k(  rd	}||j                  |d|d    ||      z  }D nHt        |       dkD  r8 d
j                  | }| d   \  }}| d   d   }||j                  |||z
        z  }nd} | s|d|j                         z   dz   z  }|S c c}	w )a  
    Print quick-and-dirty elapsed times between named event points.

    Args:
        events (list[(str,datetime.datetime)]): A list of named time points.
            Each event is a 2-tuple: (label, time).
        title (str): heading of the elapsed time table.
        labels (Iterable[str]): Labels for the report.
            Three elements are expected.
        max_col_widths (Iterable[int]): Maximum width of columns in the report.
            Three elements are expected.
        title_sep (str): The separator used to underline the title.
        label_sep (str): The separator used to underline the labels.
        only_last (bool): print only the last event (useful inside a loop).

    Returns:
        None.
    
   z%{{!s:{}s}}  {{!s:>{}s}}  {{!s:>{}s}}
NrP   r   r   r)   r   z{{!s:{}s}}  {{!s:>{}s}}r   zNo z to report!)r"   r@   ranger   )r   titlelabelsmax_col_widths	title_sep	label_sep	only_lastr0   r   max_col_widthfirst_elapsedr7   r	   curr_elapsedprev_elapsed
diff_first	diff_lasts                    r   reportr   Z  s   4 DS[1_B;BB!D  $c%j0+3u:>E"$ E+.v;?y 4'F FD #f+/f-.+9;' !=0.=A ;< = #1IaLM1c&k* F%+AY"l%a!e}Q/)M9
(<7	*!$J+.+,iE FF [1_3,33^DD!'D,!!9Q<LT[[|l'BCDDF%55K/;s   E7
r	   r
   r   c                 
   t        dt        j                  |||      fdt        j                  |||      fdt        j                  |||      fdt        j                  |||      ff      }|j                         D ]<  \  }}t        j                  j                  |      r&t        j                  |d       > t        j                  j                  |       |d<   t        j                  j                  |d   d      |d<   |S )	a  
    Generate application directories.

    Args:
        current_filepath (str): The current filepath.
        name (str): Application name.
        author (str): Application author.
        version (str): Application version.

    Returns:
        dirs (dict): The package directories.
            - 'config': directory for configuration files.
            - 'cache': directory for caching files.
            - 'data': directory for data files.
            - 'log': directory for log files.
            - 'base': base directory of the module.
            - 'resources': directory for the data resources.

    Examples:
        >>> sorted(pkg_paths().keys())
        ['base', 'cache', 'config', 'data', 'log', 'resources']
    configcachedatalogT)exist_okbase	resources)r{   appdirsuser_config_diruser_cache_diruser_data_dirr   r   r   isdirmakedirsdirnamejoin)current_filepathr	   r
   r   dirpathsdirpaths         r   	pkg_pathsr     s    6 	7**4AB	'((vw?@	&&tVW=>	%%dFG<= H ") 0gww}}W%KK$/0 ww'78HVGGLL&)9;GH[Or!   c                 ~   t        | j                                t        dd       t        j                         }|j                  |j
                  z
  }|j
                  dkD  rdnd}t        t        d      dd	
       t        t        d      dd	
       t        t        d      |       t        t                      y )NzRunning `doctest.testmod()`... r|   r   r   z{t.bold}{t.red}z{t.bold}{t.green}zTests = {results.attempted}; z{t.bold}{t.cyan}rP   r   zOK = {results_ok}; zFail = {results.failed})r   ry   doctesttestmod	attemptedfailedrc   r   )module_docstringresults
results_okresults_fmts       r   run_doctestsr     s     !)7ooG""W^^3J>>A $#6 ,-4FBO"#*=2F&'k:Mr!   )*__main__)F)Fr   r   )T)NTr   ),__doc__
__future__r   r   r   r   r   r]   r   r   r   flyingcircus._versionr   INFOVERB_LVL_NAMES	enumeraterp   
D_VERB_LVL_EVENTSMY_GREETINGSr&   numbar'   HAS_JITrm   r-   r8   rL   rY   r[   rc   r   r   r   r   r   r   r   PATHr   r   flyingcircus.baseflyingcircus__name__)vks   00r   <module>r      s  C C
   	   .
 ' +G	
 & '~67TQAqD7h
 ":
 G  N BT 	AJJK^'J +'b !	V$t< &6 =#@J "&\H~Y	'V
 4<hiI " #    z _ 8r  G
Cs    DD 	DD