
    .Ph                        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mZ ddlm	Z	m
Z
mZmZmZ 	 ddlmZ  ed          Z ed          Zn# e$ r  e            Z e            ZY nw xY wd	 Zd
 Z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?dZ d Z!d@dZ"efdZ#efdZ$efdZ%efdZ&dAdZ'dAd Z(dBd"Z)dBd#Z*e+ddfd$Z,e+fd%Z-d>d&Z.d>d'Z/dCd(Z0d=d)Z1d=d*Z2d+ Z3d, Z4efd-Z5d. Z6e6Z7d/ Z8d0 Z9e6e8e9fd1Z: G d2 d3e;e<e=          Z>efd4Z?d5 de8fd6Z@ G d7 d8          ZA G d9 d:eA          ZB eA            ZC eB            ZDdDd;ZEdCd<ZFdS )Ea  :mod:`itertools` is full of great examples of Python generator
usage. However, there are still some critical gaps. ``iterutils``
fills many of those gaps with featureful, tested, and Pythonic
solutions.

Many of the functions below have two versions, one which
returns an iterator (denoted by the ``*_iter`` naming pattern), and a
shorter-named convenience form that returns a list. Some of the
following are based on examples in itertools docs.
    N)zip_longest)MappingSequenceSet	ItemsViewIterable   )make_sentinel_UNSET_REMAP_EXITc                 J    	 t          |            n# t          $ r Y dS w xY wdS )a  Similar in nature to :func:`callable`, ``is_iterable`` returns
    ``True`` if an object is `iterable`_, ``False`` if not.

    >>> is_iterable([])
    True
    >>> is_iterable(object())
    False

    .. _iterable: https://docs.python.org/2/glossary.html#term-iterable
    FT)iter	TypeErrorobjs    Q/var/www/html/test/jupyter/venv/lib/python3.11/site-packages/boltons/iterutils.pyis_iterabler   =   s;    S				   uu4s    
  c                 Z    t          |            pt          | t          t          f          S )av  A near-mirror of :func:`is_iterable`. Returns ``False`` if an
    object is an iterable container type. Strings are considered
    scalar as well, because strings are more often treated as whole
    values as opposed to iterables of 1-character substrings.

    >>> is_scalar(object())
    True
    >>> is_scalar(range(10))
    False
    >>> is_scalar('hello')
    True
    r   
isinstancestrbytesr   s    r   	is_scalarr   O   s(     3@:cC<#@#@@    c                 Z    t          |           ot          | t          t          f           S )zThe opposite of :func:`is_scalar`.  Returns ``True`` if an object
    is an iterable other than a string.

    >>> is_collection(object())
    False
    >>> is_collection(range(10))
    True
    >>> is_collection('hello')
    False
    r   r   s    r   is_collectionr   _   s(     sAJsS%L$A$A AAr   c                 >    t          t          | ||                    S )a  Splits an iterable based on a separator. Like :meth:`str.split`,
    but for all iterables. Returns a list of lists.

    >>> split(['hi', 'hello', None, None, 'sup', None, 'soap', None])
    [['hi', 'hello'], ['sup'], ['soap']]

    See :func:`split_iter` docs for more info.
    )list
split_iter)srcsepmaxsplits      r   splitr#   m   s     
3X..///r   c              #     K   t          |           st          d          |t          |          }|dk    r| gV  dS t                    r}n)t	                    st                    fd}nfd}g }d}| D ]>}|	||k    rd } ||          r|s|dz  }|V  g })|                    |           ?|s|V  dS )a  Splits an iterable based on a separator, *sep*, a max of
    *maxsplit* times (no max by default). *sep* can be:

      * a single value
      * an iterable of separators
      * a single-argument callable that returns True when a separator is
        encountered

    ``split_iter()`` yields lists of non-separator values. A separator will
    never appear in the output.

    >>> list(split_iter(['hi', 'hello', None, None, 'sup', None, 'soap', None]))
    [['hi', 'hello'], ['sup'], ['soap']]

    Note that ``split_iter`` is based on :func:`str.split`, so if
    *sep* is ``None``, ``split()`` **groups** separators. If empty lists
    are desired between two contiguous ``None`` values, simply use
    ``sep=[None]``:

    >>> list(split_iter(['hi', 'hello', None, None, 'sup', None]))
    [['hi', 'hello'], ['sup']]
    >>> list(split_iter(['hi', 'hello', None, None, 'sup', None], sep=[None]))
    [['hi', 'hello'], [], ['sup'], []]

    Using a callable separator:

    >>> falsy_sep = lambda x: not x
    >>> list(split_iter(['hi', 'hello', None, '', 'sup', False], falsy_sep))
    [['hi', 'hello'], [], ['sup'], []]

    See :func:`split` for a list-returning version.

    expected an iterableNr   c                     | v S N xr!   s    r   sep_funczsplit_iter.<locals>.sep_func   s    Sr   c                     | k    S r'   r(   r)   s    r   r+   zsplit_iter.<locals>.sep_func   s    Sr   c                     dS NFr(   r*   s    r   r+   zsplit_iter.<locals>.sep_func   s    EEr   r	   )r   r   intcallabler   	frozensetappend)r    r!   r"   r+   	cur_groupsplit_countss    `     r   r   r   y   s=     D s 0.///x==q==%KKKF}} )s^^ )nn(((((((((((IK    K8$;$;)))8A;; 		 {9{ 1KOOOIIQ CO
Fr   c                 <    t          t          | |                    S )a  Strips values from the beginning of an iterable. Stripped items will
    match the value of the argument strip_value. Functionality is analogous
    to that of the method str.lstrip. Returns a list.

    >>> lstrip(['Foo', 'Bar', 'Bam'], 'Foo')
    ['Bar', 'Bam']

    )r   lstrip_iteriterablestrip_values     r   lstripr<           Hk22333r   c              #   \   K   t          |           }|D ]}||k    r|V   n|D ]}|V  dS )a  Strips values from the beginning of an iterable. Stripped items will
    match the value of the argument strip_value. Functionality is analogous
    to that of the method str.lstrip. Returns a generator.

    >>> list(lstrip_iter(['Foo', 'Bar', 'Bam'], 'Foo'))
    ['Bar', 'Bam']

    N)r   )r:   r;   iteratoris       r   r8   r8      sf       H~~H  GGGE     r   c                 <    t          t          | |                    S )a  Strips values from the end of an iterable. Stripped items will
    match the value of the argument strip_value. Functionality is analogous
    to that of the method str.rstrip. Returns a list.

    >>> rstrip(['Foo', 'Bar', 'Bam'], 'Bam')
    ['Foo', 'Bar']

    )r   rstrip_iterr9   s     r   rstriprC      r=   r   c              #      K   t          |           }|D ]a}||k    rUt                      }|                    |           d}|D ] }||k    r|                    |           d} |s dS |E d{V  |V  bdS )a  Strips values from the end of an iterable. Stripped items will
    match the value of the argument strip_value. Functionality is analogous
    to that of the method str.rstrip. Returns a generator.

    >>> list(rstrip_iter(['Foo', 'Bar', 'Bam'], 'Bam'))
    ['Foo', 'Bar']

    FTN)r   r   r3   )r:   r;   r?   r@   cachebrokens         r   rB   rB      s       H~~H  FFELLOOOF  ##LLOOOO!F  r   c                 <    t          t          | |                    S )a%  Strips values from the beginning and end of an iterable. Stripped items
    will match the value of the argument strip_value. Functionality is
    analogous to that of the method str.strip. Returns a list.

    >>> strip(['Fu', 'Foo', 'Bar', 'Bam', 'Fu'], 'Fu')
    ['Foo', 'Bar', 'Bam']

    )r   
strip_iterr9   s     r   striprI     s     
8[11222r   c                 >    t          t          | |          |          S )a5  Strips values from the beginning and end of an iterable. Stripped items
    will match the value of the argument strip_value. Functionality is
    analogous to that of the method str.strip. Returns a generator.

    >>> list(strip_iter(['Fu', 'Foo', 'Bar', 'Bam', 'Fu'], 'Fu'))
    ['Foo', 'Bar', 'Bam']

    )rB   r8   r9   s     r   rH   rH     s     {8[99;GGGr   c                     t          | |fi |}|t          |          S t          t          j        ||                    S )a`  Returns a list of *count* chunks, each with *size* elements,
    generated from iterable *src*. If *src* is not evenly divisible by
    *size*, the final chunk will have fewer than *size* elements.
    Provide the *fill* keyword argument to provide a pad value and
    enable padding, otherwise no padding will take place.

    >>> chunked(range(10), 3)
    [[0, 1, 2], [3, 4, 5], [6, 7, 8], [9]]
    >>> chunked(range(10), 3, fill=None)
    [[0, 1, 2], [3, 4, 5], [6, 7, 8], [9, None, None]]
    >>> chunked(range(10), 3, count=2)
    [[0, 1, 2], [3, 4, 5]]

    See :func:`chunked_iter` for more info.
    )chunked_iterr   	itertoolsislice)r    sizecountkw
chunk_iters        r   chunkedrS     sI      c4..2..J}JI$Z77888r   Tc                 d    t          |           } | dk     s|r| dk    rt          d|z             | S )Nr   zexpected a positive integer )r0   
ValueError)valuenamestrictly_positives      r   _validate_positive_intrY   5  s<    JJEqyy&y5A::7$>???Lr   c              +     K   t          |           st          d          t          |d          }d}	 |                    d          }n# t          $ r d}d}Y nw xY w|r$t          d|                                z            | sdS d }t          | t          t          f          r2 t          |                       fd	}t          | t                    rd
 }t          |           }	 t          t          j        ||                    }|sn3t          |          }||k     r|r|g||z
  z  ||d<    ||          V  XdS )a  Generates *size*-sized chunks from *src* iterable. Unless the
    optional *fill* keyword argument is provided, iterables not evenly
    divisible by *size* will have a final chunk that is smaller than
    *size*.

    >>> list(chunked_iter(range(10), 3))
    [[0, 1, 2], [3, 4, 5], [6, 7, 8], [9]]
    >>> list(chunked_iter(range(10), 3, fill=None))
    [[0, 1, 2], [3, 4, 5], [6, 7, 8], [9, None, None]]

    Note that ``fill=None`` in fact uses ``None`` as the fill value.
    r%   z
chunk sizeTfillFNz$got unexpected keyword arguments: %rc                     | S r'   r(   chks    r   postprocessz!chunked_iter.<locals>.postprocessX  s    *r   c                 ,    |                     |           S r'   )join)r^   _seps     r   r_   z!chunked_iter.<locals>.postprocessZ  s    tyy~~0Er   c                      t          |           S r'   )r   r]   s    r   r_   z!chunked_iter.<locals>.postprocess\  s    s"3r   )r   r   rY   popKeyErrorrU   keysr   r   r   typer   r   rM   rN   len)	r    rO   rQ   do_fillfill_valr_   src_iter	cur_chunklcs	            r   rL   rL   <  s      s 0.///!$55DG66&>>    
 M?"''))KLLL $$$#U|$$ 4"+$s))++EEEEc5!! 	4333CyyH%)(D99::	 	^^999&Z4"95IbccNk)$$$$$% Fs   A
 
AAFc              #     K   t          | dd          } t          |d          }t          |dd          }t          |dd          }|| z   }|r;||||z
  z  z
  }||k    r*|t          ||z   |          fV  ||z   |k    rdS ||z   |z
  }t          ||||z
            D ]%}|t          ||z   |          fV  ||z   |k    r dS &dS )a  Generates *chunk_size*-sized chunk ranges for an input with length *input_size*.
    Optionally, a start of the input can be set via *input_offset*, and
    and overlap between the chunks may be specified via *overlap_size*.
    Also, if *align* is set to *True*, any items with *i % (chunk_size-overlap_size) == 0*
    are always at the beginning of the chunk.

    Returns an iterator of (start, end) tuples, one tuple per chunk.

    >>> list(chunk_ranges(input_offset=10, input_size=10, chunk_size=5))
    [(10, 15), (15, 20)]
    >>> list(chunk_ranges(input_offset=10, input_size=10, chunk_size=5, overlap_size=1))
    [(10, 15), (14, 19), (18, 20)]
    >>> list(chunk_ranges(input_offset=10, input_size=10, chunk_size=5, overlap_size=2))
    [(10, 15), (13, 18), (16, 20)]

    >>> list(chunk_ranges(input_offset=4, input_size=15, chunk_size=5, align=False))
    [(4, 9), (9, 14), (14, 19)]
    >>> list(chunk_ranges(input_offset=4, input_size=15, chunk_size=5, align=True))
    [(4, 5), (5, 10), (10, 15), (15, 19)]

    >>> list(chunk_ranges(input_offset=2, input_size=15, chunk_size=5, overlap_size=1, align=False))
    [(2, 7), (6, 11), (10, 15), (14, 17)]
    >>> list(chunk_ranges(input_offset=2, input_size=15, chunk_size=5, overlap_size=1, align=True))
    [(2, 5), (4, 9), (8, 13), (12, 17)]
    >>> list(chunk_ranges(input_offset=3, input_size=15, chunk_size=5, overlap_size=1, align=True))
    [(3, 5), (4, 9), (8, 13), (12, 17), (16, 18)]
    
input_sizeF)rX   
chunk_sizeinput_offsetoverlap_sizeN)rY   minrange)ro   rp   rq   rr   align
input_stopinitial_chunk_lenr@   s           r   chunk_rangesrx   i  sK     8 (LE; ; ;J'
LAAJ)n? ? ?L)n? ? ?L 
*J K&J567,,\4E%Ez!R!RSSSS//:=='*;;lJL<Z,-FGG  #a*nj112222z>Z''FF ( r   c                 &    t          | d|          S )a  Convenience function for calling :func:`windowed` on *src*, with
    *size* set to 2.

    >>> pairwise(range(5))
    [(0, 1), (1, 2), (2, 3), (3, 4)]
    >>> pairwise([])
    []

    Unless *end* is set, the number of pairs is always one less than 
    the number of elements in the iterable passed in, except on an empty input, 
    which will return an empty list.

    With *end* set, a number of pairs equal to the length of *src* is returned,
    with the last item of the last pair being equal to *end*.

    >>> list(pairwise(range(3), end=None))
    [(0, 1), (1, 2), (2, None)]

    This way, *end* values can be useful as sentinels to signal the end of the iterable.
       r[   )windowedr    ends     r   pairwiser     s    * C%%%%r   c                 &    t          | d|          S )a  Convenience function for calling :func:`windowed_iter` on *src*,
    with *size* set to 2.

    >>> list(pairwise_iter(range(5)))
    [(0, 1), (1, 2), (2, 3), (3, 4)]
    >>> list(pairwise_iter([]))
    []

    Unless *end* is set, the number of pairs is always one less 
    than the number of elements in the iterable passed in, 
    or zero, when *src* is empty.

    With *end* set, a number of pairs equal to the length of *src* is returned,
    with the last item of the last pair being equal to *end*. 

    >>> list(pairwise_iter(range(3), end=None))
    [(0, 1), (1, 2), (2, None)]    

    This way, *end* values can be useful as sentinels to signal the end
    of the iterable. For infinite iterators, setting *end* has no effect.
    rz   r{   )windowed_iterr}   s     r   pairwise_iterr     s    , ac****r   c                 @    t          t          | ||                    S )zReturns tuples with exactly length *size*. If *fill* is unset 
    and the iterable is too short to make a window of length *size*, 
    no tuples are returned. See :func:`windowed_iter` for more.
    r{   )r   r   )r    rO   r[   s      r   r|   r|     s!    
 c4d333444r   c                    t          j        | |          }|t          u r`	 t          |          D ]&\  }}t	          |          D ]}t          |           'n# t          $ r t          g           cY S w xY wt          | S t          |          D ]7\  }}t	          |          D ]"}	 t          |           # t          $ r Y w xY w8t          |d|iS )a  Returns tuples with length *size* which represent a sliding
    window over iterable *src*.

    >>> list(windowed_iter(range(7), 3))
    [(0, 1, 2), (1, 2, 3), (2, 3, 4), (3, 4, 5), (4, 5, 6)]

    If *fill* is unset, and the iterable is too short to make a window 
    of length *size*, then no window tuples are returned.

    >>> list(windowed_iter(range(3), 5))
    []

    With *fill* set, the iterator always yields a number of windows
    equal to the length of the *src* iterable.

    >>> windowed(range(4), 3, fill=None)
    [(0, 1, 2), (1, 2, 3), (2, 3, None), (3, None, None)]

    This way, *fill* values can be useful to signal the end of the iterable.
    For infinite iterators, setting *fill* has no effect.
    	fillvalue)	rM   teer   	enumeratert   nextStopIterationzipr   )r    rO   r[   teesr@   t_s          r   r   r     s   , =d##Dv~~	!$  1q  AGGGG  	 	 	r77NNN	Dz$  1q 	 	AQ    	
 ----s#   6A A32A3%B55
CC      ?c              #      K   |st          d          |d| dz  } }n
|dz  | dz  }} |}|| k     r|V  ||z  }|| k     dS dS )zSame as :func:`frange`, but generator-based instead of returning a
    list.

    >>> tuple(xfrange(1, 3, step=0.75))
    (1.0, 1.75, 2.5)

    See :func:`frange` for more details.
    step must be non-zeroN        r   )rU   )stopstartstepcurs       r   xfranger     sy        20111}4#:t ck4#:e
C
**			t ******r   c                    |st          d          |d| dz  } }n
|dz  | dz  }} t          t          j        | |z
  |z                      }dg|z  }|s|S ||d<   t	          d|          D ]}||dz
           |z   ||<   |S )a>  A :func:`range` clone for float-based ranges.

    >>> frange(5)
    [0.0, 1.0, 2.0, 3.0, 4.0]
    >>> frange(6, step=1.25)
    [0.0, 1.25, 2.5, 3.75, 5.0]
    >>> frange(100.5, 101.5, 0.25)
    [100.5, 100.75, 101.0, 101.25]
    >>> frange(5, 0)
    []
    >>> frange(5, 0, step=-1.25)
    [5.0, 3.75, 2.5, 1.25]
    r   Nr   r   r   r	   )rU   r0   mathceilrt   )r   r   r   rP   retr@   s         r   franger     s      20111}4#:t ck4#:e	4%<4/0011E&5.C 
CF1e__ # #QUd"AJr          @c           	      n    |dk    rt          d          t          t          | ||||                    S )a  Returns a list of geometrically-increasing floating-point numbers,
    suitable for usage with `exponential backoff`_. Exactly like
    :func:`backoff_iter`, but without the ``'repeat'`` option for
    *count*. See :func:`backoff_iter` for more details.

    .. _exponential backoff: https://en.wikipedia.org/wiki/Exponential_backoff

    >>> backoff(1, 10)
    [1.0, 2.0, 4.0, 8.0, 10.0]
    repeatz/'repeat' supported in backoff_iter, not backoff)rP   factorjitter)rU   r   backoff_iter)r   r   rP   r   r   s        r   backoffr   6  sL     JKKKUD$*6; ; ; < < <r   c              #     K   t          |           } t          |          }t          |          }| dk     rt          d| z            |dk     rt          d|z            |dk    rt          d          || k     rt          d|z            |<| r| nd}dt          j        t          j        ||z  |                    z   }| r|n|dz   }|d	k    r|d
k     rt          d|z            |r0t          |          }d|cxk    rdk    sn t          d|z            | d
}}|d	k    s||k     rT|s|}n|r|||z  t          j                    z  z
  }|V  |dz  }|d
k    rd}n||k     r||z  }||k    r|}|d	k    N||k     TdS )a  Generates a sequence of geometrically-increasing floats, suitable
    for usage with `exponential backoff`_. Starts with *start*,
    increasing by *factor* until *stop* is reached, optionally
    stopping iteration once *count* numbers are yielded. *factor*
    defaults to 2. In general retrying with properly-configured
    backoff creates a better-behaved component for a larger service
    ecosystem.

    .. _exponential backoff: https://en.wikipedia.org/wiki/Exponential_backoff

    >>> list(backoff_iter(1.0, 10.0, count=5))
    [1.0, 2.0, 4.0, 8.0, 10.0]
    >>> list(backoff_iter(1.0, 10.0, count=8))
    [1.0, 2.0, 4.0, 8.0, 10.0, 10.0, 10.0, 10.0]
    >>> list(backoff_iter(0.25, 100.0, factor=10))
    [0.25, 2.5, 25.0, 100.0]

    A simplified usage example:

    .. code-block:: python

      for timeout in backoff_iter(0.25, 5.0):
          try:
              res = network_call()
              break
          except Exception as e:
              log(e)
              time.sleep(timeout)

    An enhancement for large-scale systems would be to add variation,
    or *jitter*, to timeout values. This is done to avoid a thundering
    herd on the receiving end of the network call.

    Finally, for *count*, the special value ``'repeat'`` can be passed to
    continue yielding indefinitely.

    Args:

        start (float): Positive number for baseline.
        stop (float): Positive number for maximum.
        count (int): Number of steps before stopping
            iteration. Defaults to the number of steps between *start* and
            *stop*. Pass the string, `'repeat'`, to continue iteration
            indefinitely.
        factor (float): Rate of exponential increase. Defaults to `2.0`,
            e.g., `[1, 2, 4, 8, 16]`.
        jitter (float): A factor between `-1.0` and `1.0`, used to
            uniformly randomize and thus spread out timeouts in a distributed
            system, avoiding rhythm effects. Positive values use the base
            backoff curve as a maximum, negative values use the curve as a
            minimum. Set to 1.0 or `True` for a jitter approximating
            Ethernet's time-tested backoff solution. Defaults to `False`.

    r   zexpected start >= 0, not %rr   zexpected factor >= 1.0, not %rzexpected stop >= 0zexpected stop >= start, not %rNr	   r   r   z*count must be positive or "repeat", not %rg      z%expected jitter -1 <= j <= 1, not: %r)floatrU   r   r   lograndom)	r   r   rP   r   r   denomr   r@   cur_rets	            r   r   r   G  s     n %LLE;;D6]]Fs{{6>???||9FBCCCs{{-...e||9D@AAA}%ADIdhtEz6::;;;-EAIUQYYEMNNN Ov%%%%#%%%%DvMNNNAC
8

q5yy 	=GG 	=S6\FMOO;<G	Q!88CC4ZZ6MC::C 8

q5yy Fr   c                    t          |           st          d          t          t                    r?t	                    t	          |           k    rt          d          t          |           } t          t                    rfd}n:t                    r}n(t          t                    rd }nt          d          |d }t          |          st          d          t          t                    r|fd	}i }| D ]L} ||          }| ||          r2|	                    |g           
                     ||                     M|S )
aj  Group values in the *src* iterable by the value returned by *key*.

    >>> bucketize(range(5))
    {False: [0], True: [1, 2, 3, 4]}
    >>> is_odd = lambda x: x % 2 == 1
    >>> bucketize(range(5), is_odd)
    {False: [0, 2, 4], True: [1, 3]}

    *key* is :class:`bool` by default, but can either be a callable or a string or a list
    if it is a string, it is the name of the attribute on which to bucketize objects.

    >>> bucketize([1+1j, 2+2j, 1, 2], key='real')
    {1.0: [(1+1j), 1], 2.0: [(2+2j), 2]}

    if *key* is a list, it contains the buckets where to put each object

    >>> bucketize([1,2,365,4,98],key=[0,1,2,0,2])
    {0: [1, 4], 1: [2], 2: [365, 98]}


    Value lists are not deduplicated:

    >>> bucketize([None, None, None, 'hello'])
    {False: [None, None, None], True: ['hello']}

    Bucketize into more than 3 groups

    >>> bucketize(range(10), lambda x: x % 3)
    {0: [0, 3, 6, 9], 1: [1, 4, 7], 2: [2, 5, 8]}

    ``bucketize`` has a couple of advanced options useful in certain
    cases.  *value_transform* can be used to modify values as they are
    added to buckets, and *key_filter* will allow excluding certain
    buckets from being collected.

    >>> bucketize(range(5), value_transform=lambda x: x*x)
    {False: [0], True: [1, 4, 9, 16]}

    >>> bucketize(range(10), key=lambda x: x % 3, key_filter=lambda k: k % 3 != 1)
    {0: [0, 3, 6, 9], 2: [2, 5, 8]}

    Note in some of these examples there were at most two keys, ``True`` and
    ``False``, and each key present has a list with at least one
    item. See :func:`partition` for a version specialized for binary
    use cases.

    r%   z&key and src have to be the same lengthc                 &    t          | |           S r'   getattrr*   keys    r   key_funczbucketize.<locals>.key_func      3 2 22r   c                     | d         S )Nr   r(   r/   s    r   r   zbucketize.<locals>.key_func  s
    !r   z1expected key to be callable or a string or a listNc                     | S r'   r(   r/   s    r   value_transformz"bucketize.<locals>.value_transform  s    qr   z*expected callable value transform functionc                 &     | d                   S )Nr	   r(   )r*   fs    r   r   z"bucketize.<locals>.value_transform  s    qq1wwr   )r   r   r   r   rh   rU   r   r   r1   
setdefaultr3   )	r    r   r   
key_filterr   r   val
key_of_valr   s	    `      @r   	bucketizer     s   ` s .///	C		 s88s3xxEFFF#smm#s M222222	# M	C		 M$$$$KLLL(((O$$ FDEEE#t /.....
C H HXc]]
J!7!7NN:r**11//#2F2FGGGJr   c                 z    t          | |          }|                    dg           |                    dg           fS )a  No relation to :meth:`str.partition`, ``partition`` is like
    :func:`bucketize`, but for added convenience returns a tuple of
    ``(truthy_values, falsy_values)``.

    >>> nonempty, empty = partition(['', '', 'hi', '', 'bye'])
    >>> nonempty
    ['hi', 'bye']

    *key* defaults to :class:`bool`, but can be carefully overridden to
    use either a function that returns either ``True`` or ``False`` or
    a string name of the attribute on which to partition objects.

    >>> import string
    >>> is_digit = lambda x: x in string.digits
    >>> decimal_digits, hexletters = partition(string.hexdigits, is_digit)
    >>> ''.join(decimal_digits), ''.join(hexletters)
    ('0123456789', 'abcdefABCDEF')
    TF)r   get)r    r   
bucketizeds      r   	partitionr     s:    & 3$$J>>$##Z^^E2%>%>>>r   c                 <    t          t          | |                    S )a&  ``unique()`` returns a list of unique values, as determined by
    *key*, in the order they first appeared in the input iterable,
    *src*.

    >>> ones_n_zeros = '11010110001010010101010'
    >>> ''.join(unique(ones_n_zeros))
    '10'

    See :func:`unique_iter` docs for more details.
    )r   unique_iter)r    r   s     r   uniquer     s     C%%&&&r   c              #   h  K   t          |           st          dt          |           z            d }n?t                    r}n-t	          t
                    rfd}nt          dz            t                      }| D ]*} ||          }||vr|                    |           |V  +dS )aW  Yield unique elements from the iterable, *src*, based on *key*,
    in the order in which they first appeared in *src*.

    >>> repetitious = [1, 2, 3] * 10
    >>> list(unique_iter(repetitious))
    [1, 2, 3]

    By default, *key* is the object itself, but *key* can either be a
    callable or, for convenience, a string name of the attribute on
    which to uniqueify objects, falling back on identity when the
    attribute is not present.

    >>> pleasantries = ['hi', 'hello', 'ok', 'bye', 'yes']
    >>> list(unique_iter(pleasantries, key=lambda x: len(x)))
    ['hi', 'hello', 'bye']
    zexpected an iterable, not %rNc                     | S r'   r(   r/   s    r   r   zunique_iter.<locals>.key_func.  s    r   c                 &    t          | |           S r'   r   r   s    r   r   zunique_iter.<locals>.key_func2  r   r   +"key" expected a string or callable, not %r)r   r   rg   r1   r   r   setadd)r    r   r   seenr@   ks    `    r   r   r     s      " s D6cBCCC
{!!!!	# M	C		 M222222EKLLL55D  HQKKD==HHQKKKGGG
Fr   c                   	 nFt                    r}n4t          t          t          f          rfd}nt	          dz            i }g }i 	| D ]_}r ||          n|}||vr|||<   |	v r|r	|                             |           =|                    |           ||         |g	|<   `|s	fd|D             }n	fd|D             }|S )aT  The complement of :func:`unique()`.

    By default returns non-unique/duplicate values as a list of the
    *first* redundant value in *src*. Pass ``groups=True`` to get
    groups of all values with redundancies, ordered by position of the
    first redundant value. This is useful in conjunction with some
    normalizing *key* function.

    >>> redundant([1, 2, 3, 4])
    []
    >>> redundant([1, 2, 3, 2, 3, 3, 4])
    [2, 3]
    >>> redundant([1, 2, 3, 2, 3, 3, 4], groups=True)
    [[2, 2], [3, 3, 3]]

    An example using a *key* function to do case-insensitive
    redundancy detection.

    >>> redundant(['hi', 'Hi', 'HI', 'hello'], key=str.lower)
    ['Hi']
    >>> redundant(['hi', 'Hi', 'HI', 'hello'], groups=True, key=str.lower)
    [['hi', 'Hi', 'HI']]

    *key* should also be used when the values in *src* are not hashable.

    .. note::

       This output of this function is designed for reporting
       duplicates in contexts when a unique input is desired. Due to
       the grouped return type, there is no streaming equivalent of
       this function for the time being.

    Nc                 &    t          | |           S r'   r   r   s    r   r   zredundant.<locals>.key_funce  r   r   r   c                 ,    g | ]}|         d          S )r	   r(   .0r   redundant_groupss     r   
<listcomp>zredundant.<locals>.<listcomp>w  s$    ???!"1%???r   c                      g | ]
}|         S r(   r(   r   s     r   r   zredundant.<locals>.<listcomp>y  s    <<<q"<<<r   )r1   r   r   r   r   r3   )
r    r   groupsr   r   redundant_orderr@   r   r   r   s
    `       @r   	redundantr   >  sD   D {	# M	C#u	&	& M222222EKLLLDO 
3 
3%HHQKKKAD==DGG$$$ 2$Q'..q111&&q)))'+Awl ## =???????<<<<O<<<Jr   c                     t          t          j        t          ||           d                    }t	          |          dk    r|d         n|S )u!  Along the same lines as builtins, :func:`all` and :func:`any`, and
    similar to :func:`first`, ``one()`` returns the single object in
    the given iterable *src* that evaluates to ``True``, as determined
    by callable *key*. If unset, *key* defaults to :class:`bool`. If
    no such objects are found, *default* is returned. If *default* is
    not passed, ``None`` is returned.

    If *src* has more than one object that evaluates to ``True``, or
    if there is no object that fulfills such condition, return
    *default*. It's like an `XOR`_ over an iterable.

    >>> one((True, False, False))
    True
    >>> one((True, False, True))
    >>> one((0, 0, 'a'))
    'a'
    >>> one((0, False, None))
    >>> one((True, True), default=False)
    False
    >>> bool(one(('', 1)))
    True
    >>> one((10, 20, 30, 42), key=lambda i: i > 40)
    42

    See `Martín Gaitán's original repo`_ for further use cases.

    .. _Martín Gaitán's original repo: https://github.com/mgaitan/one
    .. _XOR: https://en.wikipedia.org/wiki/Exclusive_or

    rz   r	   r   )r   rM   rN   filterrh   )r    defaultr   oness       r   oner   }  sD    > 	 S!1!115566D$ii1nn477'1r   c                 >    t          t          ||           |          S )aw  Return first element of *iterable* that evaluates to ``True``, else
    return ``None`` or optional *default*. Similar to :func:`one`.

    >>> first([0, False, None, [], (), 42])
    42
    >>> first([0, False, None, [], ()]) is None
    True
    >>> first([0, False, None, [], ()], default='ohai')
    'ohai'
    >>> import re
    >>> m = first(re.match(regex, 'abc') for regex in ['b.*', 'a(.*)'])
    >>> m.group(1)
    'bc'

    The optional *key* argument specifies a one-argument predicate function
    like that used for *filter()*.  The *key* argument, if supplied, should be
    in keyword form. For example, finding the first even number in an iterable:

    >>> first([1, 1, 3, 4, 5], key=lambda x: x % 2 == 0)
    4

    Contributed by Hynek Schlawack, author of `the original standalone module`_.

    .. _the original standalone module: https://github.com/hynek/first
    )r   r   )r:   r   r   s      r   firstr     s    4 sH%%w///r   c              #      K   | D ]M}t          |t                    r2t          |t          t          f          st	          |          E d{V  I|V  NdS )z``flatten_iter()`` yields all the elements from *iterable* while
    collapsing any nested iterables.

    >>> nested = [[1, 2], [[3], [4, 5]]]
    >>> list(flatten_iter(nested))
    [1, 2, 3, 4, 5]
    N)r   r   r   r   flatten_iter)r:   items     r   r   r     sv         dH%% 	jU|.L.L 	#D))))))))))JJJJ	 r   c                 :    t          t          |                     S )z``flatten()`` returns a collapsed list of all the elements from
    *iterable* while collapsing any nested iterables.

    >>> nested = [[1, 2], [[3], [4, 5]]]
    >>> flatten(nested)
    [1, 2, 3, 4, 5]
    )r   r   )r:   s    r   flattenr     s     X&&'''r   c                     t          |           }t          u rt          |          t          fd|D                       S )a  ``same()`` returns ``True`` when all values in *iterable* are
    equal to one another, or optionally a reference value,
    *ref*. Similar to :func:`all` and :func:`any` in that it evaluates
    an iterable and returns a :class:`bool`. ``same()`` returns
    ``True`` for empty iterables.

    >>> same([])
    True
    >>> same([1])
    True
    >>> same(['a', 'a', 'a'])
    True
    >>> same(range(20))
    False
    >>> same([[], []])
    True
    >>> same([[], []], ref='test')
    False

    c              3   $   K   | ]
}|k    V  d S r'   r(   )r   r   refs     r   	<genexpr>zsame.<locals>.<genexpr>  s'      ..cscz......r   )r   r   r   all)r:   r   r?   s    ` r   samer     sK    * H~~H
f}}8S!!....X......r   c                 
    ||fS r'   r(   pathr   rV   s      r   default_visitr     s    :r   c                    t          |t          t          f          r|dfS t          |t                    r#|                                t          |          fS t          |t                    r#|                                t          |          fS t          |t                    r#|                                t          |          fS |dfS r.   )	r   r   r   r   	__class__r   r   r   r   r   s      r   default_enterr     s    %#u&& e|	E7	#	# 	  )E"2"222	E8	$	$   )E"2"222	E3		   )E"2"222 e|r   c                    |}t          |t                    r|                    |           nt          |t                    rHd |D             }	 |                    |           n# t
          $ r |                    |          }Y nw xY wt          |t                    rHd |D             }	 |                    |           nD# t
          $ r |                    |          }Y n#w xY wt          dt          |          z            |S )Nc                     g | ]\  }}|S r(   r(   r   r@   vs      r   r   z default_exit.<locals>.<listcomp>      (((da(((r   c                     g | ]\  }}|S r(   r(   r   s      r   r   z default_exit.<locals>.<listcomp>  r   r   zunexpected iterable type: %r)
r   r   updater   extendAttributeErrorr   r   RuntimeErrorrg   )r   r   
old_parent
new_parent	new_itemsr   valss          r   default_exitr     s>    C*g&& N)$$$$	J	)	) N((i(((	-d#### 	- 	- 	-&&t,,CCC	-	J	$	$ N((i(((	-d#### 	- 	- 	-&&t,,CCC	- 9D<L<LLMMMJs$   A& &BB-C C%$C%c                    t          |          st          d|z            t          |          st          d|z            t          |          st          d|z            |                    dd          }|                    dd          }|du rd}nt          |t                    r|f}t          |t
          t          t          f          st          d	|z            d
|v d|v d|v }	}}|r$t          d|                                z            di d| fg}}}
g }|rc|                                \  }}t          |          }|t          u rq|\  }}}t          |          }|                                \  }
}|rt          d|
d|d|d|d|
  
          ||
||||          }|rt          d|           |||<   |sn||v r	||         }n|rt          d|
d|d|            ||
||          }|rt          d|           	 |\  }}n # t          $ r t          d|z            w xY w|dur|||<   |                    |
g f           || ur|
|fz  }
|                    t          |||ff           |r/|                    t          t          |                               |rt          dt          |                     |t           u r||f}nk	 |	rt          d|
d|d|            ||
||          }n# t"          $ r |r d}Y nw xY w|du r|	rt          d           |du r||f}|	rt          d|           	 |d         d                             |           n # t$          $ r t          d| z            w xY w|c|S )a-  The remap ("recursive map") function is used to traverse and
    transform nested structures. Lists, tuples, sets, and dictionaries
    are just a few of the data structures nested into heterogeneous
    tree-like structures that are so common in programming.
    Unfortunately, Python's built-in ways to manipulate collections
    are almost all flat. List comprehensions may be fast and succinct,
    but they do not recurse, making it tedious to apply quick changes
    or complex transforms to real-world data.

    remap goes where list comprehensions cannot.

    Here's an example of removing all Nones from some data:

    >>> from pprint import pprint
    >>> reviews = {'Star Trek': {'TNG': 10, 'DS9': 8.5, 'ENT': None},
    ...            'Babylon 5': 6, 'Dr. Who': None}
    >>> pprint(remap(reviews, lambda p, k, v: v is not None))
    {'Babylon 5': 6, 'Star Trek': {'DS9': 8.5, 'TNG': 10}}

    Notice how both Nones have been removed despite the nesting in the
    dictionary. Not bad for a one-liner, and that's just the beginning.
    See `this remap cookbook`_ for more delicious recipes.

    .. _this remap cookbook: http://sedimental.org/remap.html

    remap takes four main arguments: the object to traverse and three
    optional callables which determine how the remapped object will be
    created.

    Args:

        root: The target object to traverse. By default, remap
            supports iterables like :class:`list`, :class:`tuple`,
            :class:`dict`, and :class:`set`, but any object traversable by
            *enter* will work.
        visit (callable): This function is called on every item in
            *root*. It must accept three positional arguments, *path*,
            *key*, and *value*. *path* is simply a tuple of parents'
            keys. *visit* should return the new key-value pair. It may
            also return ``True`` as shorthand to keep the old item
            unmodified, or ``False`` to drop the item from the new
            structure. *visit* is called after *enter*, on the new parent.

            The *visit* function is called for every item in root,
            including duplicate items. For traversable values, it is
            called on the new parent object, after all its children
            have been visited. The default visit behavior simply
            returns the key-value pair unmodified.
        enter (callable): This function controls which items in *root*
            are traversed. It accepts the same arguments as *visit*: the
            path, the key, and the value of the current item. It returns a
            pair of the blank new parent, and an iterator over the items
            which should be visited. If ``False`` is returned instead of
            an iterator, the value will not be traversed.

            The *enter* function is only called once per unique value. The
            default enter behavior support mappings, sequences, and
            sets. Strings and all other iterables will not be traversed.
        exit (callable): This function determines how to handle items
            once they have been visited. It gets the same three
            arguments as the other functions -- *path*, *key*, *value*
            -- plus two more: the blank new parent object returned
            from *enter*, and a list of the new items, as remapped by
            *visit*.

            Like *enter*, the *exit* function is only called once per
            unique value. The default exit behavior is to simply add
            all new items to the new parent, e.g., using
            :meth:`list.extend` and :meth:`dict.update` to add to the
            new parent. Immutable objects, such as a :class:`tuple` or
            :class:`namedtuple`, must be recreated from scratch, but
            use the same type as the new parent passed back from the
            *enter* function.
        reraise_visit (bool): A pragmatic convenience for the *visit*
            callable. When set to ``False``, remap ignores any errors
            raised by the *visit* callback. Items causing exceptions
            are kept. See examples for more details.
        trace (bool): Pass ``trace=True`` to print out the entire
            traversal. Or pass a tuple of ``'visit'``, ``'enter'``,
            or ``'exit'`` to print only the selected events.

    remap is designed to cover the majority of cases with just the
    *visit* callable. While passing in multiple callables is very
    empowering, remap is designed so very few cases should require
    passing more than one function.

    When passing *enter* and *exit*, it's common and easiest to build
    on the default behavior. Simply add ``from boltons.iterutils import
    default_enter`` (or ``default_exit``), and have your enter/exit
    function call the default behavior before or after your custom
    logic. See `this example`_.

    Duplicate and self-referential objects (aka reference loops) are
    automatically handled internally, `as shown here`_.

    .. _this example: http://sedimental.org/remap.html#sort_all_lists
    .. _as shown here: http://sedimental.org/remap.html#corner_cases

    z visit expected callable, not: %rz enter expected callable, not: %rzexit expected callable, not: %rreraise_visitTtracer(   )visitenterexitz,trace expected tuple of event names, not: %rr  r  r   z unexpected keyword arguments: %rNz .. remap exit:-z .. remap exit result:z .. remap enter:z .. remap enter result:zDenter should return a tuple of (new_parent, items_iterator), not: %rFz .. remap stack size now:z .. remap visit:z .. remap visit result: <drop>z .. remap visit result:r	   z!expected remappable root, not: %r)r1   r   rd   r   r   tupler   r   rf   idr   printr3   r   reversedrh   _orig_default_visit	Exception
IndexError)rootr   r  r  kwargsr   r   trace_enter
trace_exittrace_visitr   registrystacknew_items_stackr   rV   id_valuer   r   r   resvisited_items                         r   remapr  "  s   N E?? D:UBCCCE?? D:UBCCCD>> B9D@AAAJJ55MJJw##E}}*	E3		 eeT3/00 PFNOOO+2e+;Vu_gY^N^[K L:V[[]]JKKKdD\NE(DO
 DHYY[[
Ue99+*/'CZ*~~H-1133OD) C'sC #z3	C C CDsJ
IFFE 7.666!&HX" !!X&EE F($S#uEEE%c5))C 6/555C(+%
II C C C !<>A!B C C CC %%%/"&&bz222$$SFNDkCU+CDEEE <LL$y//!:!:;;; C5s5zzBBB'''<LL$ J,dCc5III$uT366 $ $ $  #$ u$$ <:;;;%% #U| ?/>>>	HB")),7777 	H 	H 	H?$FGGG	HG  DHJ Ls*   H H)#K: :LL!M# #N c                   $    e Zd ZdZd Zd Zd ZdS )PathAccessErrorzAn amalgamation of KeyError, IndexError, and TypeError,
    representing what can occur when looking up a path in a nested
    object.
    c                 0    || _         || _        || _        d S r'   )excsegr   )selfr  r  r   s       r   __init__zPathAccessError.__init__  s    			r   c                 T    | j         j        }| d| j        d| j        d| j        dS )N(z, ))r   __name__r  r  r   )r  cns     r   __repr__zPathAccessError.__repr__  s9    ^$AAtxAATXAA49AAAAr   c                 6    d| j         d| j        d| j        S )Nzcould not access z from path z, got error: )r  r   r  r  s    r   __str__zPathAccessError.__str__  s%     888TYYY2 	3r   N)r"  
__module____qualname____doc__r  r$  r'  r(   r   r   r  r    sN         
  
B B B3 3 3 3 3r   r  c           	      *   t          |t                    r|                    d          }| }	 |D ]}	 ||         }# t          t          f$ r}t          |||          d}~wt          $ r}	 t          |          }||         }ne# t          t          t          t          f$ rE t          |          s$t          dt          |          j        z            }t          |||          w xY wY d}~d}~ww xY wn# t
          $ r |t          u r |cY S w xY w|S )a	  Retrieve a value from a nested object via a tuple representing the
    lookup path.

    >>> root = {'a': {'b': {'c': [[1], [2], [3]]}}}
    >>> get_path(root, ('a', 'b', 'c', 2, 0))
    3

    The path tuple format is intentionally consistent with that of
    :func:`remap`, but a single dotted string can also be passed.

    One of get_path's chief aims is improved error messaging. EAFP is
    great, but the error messages are not.

    For instance, ``root['a']['b']['c'][2][1]`` gives back
    ``IndexError: list index out of range``

    What went out of range where? get_path currently raises
    ``PathAccessError: could not access 2 from path ('a', 'b', 'c', 2,
    1), got error: IndexError('list index out of range',)``, a
    subclass of IndexError and KeyError.

    You can also pass a default that covers the entire operation,
    should the lookup fail at any level.

    Args:
       root: The target nesting of dictionaries, lists, or other
          objects supporting ``__getitem__``.
       path (tuple): A sequence of strings and integers to be successively
          looked up within *root*. A dot-separated (``a.b``) string may 
          also be passed.
       default: The value to be returned should any
          ``PathAccessError`` exceptions be raised.
    .Nz%r object is not indexable)r   r   r#   re   r  r  r   r0   rU   r   rg   r"  r   )r  r   r   r   r  r  s         r   get_pathr-    sl   D $ zz#
C 	: 	:C:#hj) 6 6 6%c3555 
: 
: 
::c((Cc(CC"Hj)D : : :&s++ >'(D*.s))*<)= > >)#sD999	: CCCC
:	:     f JsV   C7 <C7 C3AC3,BC.A"C&&C.)C7 .C33C7 7DDc                     dS )NTr(   )pr   r   s      r   <lambda>r0  7  s     r   c                     g t                    st          dz            fd}t          | |           S )aq  The :func:`research` function uses :func:`remap` to recurse over
    any data nested in *root*, and find values which match a given
    criterion, specified by the *query* callable.

    Results are returned as a list of ``(path, value)`` pairs. The
    paths are tuples in the same format accepted by
    :func:`get_path`. This can be useful for comparing values nested
    in two or more different structures.

    Here's a simple example that finds all integers:

    >>> root = {'a': {'b': 1, 'c': (2, 'd', 3)}, 'e': None}
    >>> res = research(root, query=lambda p, k, v: isinstance(v, int))
    >>> print(sorted(res))
    [(('a', 'b'), 1), (('a', 'c', 0), 2), (('a', 'c', 2), 3)]

    Note how *query* follows the same, familiar ``path, key, value``
    signature as the ``visit`` and ``enter`` functions on
    :func:`remap`, and returns a :class:`bool`.

    Args:
       root: The target object to search. Supports the same types of
          objects as :func:`remap`, including :class:`list`,
          :class:`tuple`, :class:`dict`, and :class:`set`.
       query (callable): The function called on every object to
          determine whether to include it in the search results. The
          callable must accept three arguments, *path*, *key*, and
          *value*, commonly abbreviated *p*, *k*, and *v*, same as
          *enter* and *visit* from :func:`remap`.
       reraise (bool): Whether to reraise exceptions raised by *query*
          or to simply drop the result that caused the error.


    With :func:`research` it's easy to inspect the details of a data
    structure, like finding values that are at a certain depth (using
    ``len(p)``) and much more. If more advanced functionality is
    needed, check out the code and make your own :func:`remap`
    wrapper, and consider `submitting a patch`_!

    .. _submitting a patch: https://github.com/mahmoud/boltons/pulls
    z query expected callable, not: %rc                     	  | ||          r                     | |fz   |f           n# t          $ r r Y nw xY w | ||          S r'   )r3   r
  )r   r   rV   r  queryreraiser   s      r   _enterzresearch.<locals>._enterf  s    	uT3&& 3

DC6M51222 	 	 	  	 uT3&&&s   (, <<)r  )r1   r   r  )r  r3  r4  r  r5  r   s    ``` @r   researchr6  7  ss    T CE?? D:UBCCC' ' ' ' ' ' ' ' 
$fJr   c                   0    e Zd ZdZddZd Zd Zd ZeZdS )	
GUIDeratora  The GUIDerator is an iterator that yields a globally-unique
    identifier (GUID) on every iteration. The GUIDs produced are
    hexadecimal strings.

    Testing shows it to be around 12x faster than the uuid module. By
    default it is also more compact, partly due to its default 96-bit
    (24-hexdigit) length. 96 bits of randomness means that there is a
    1 in 2 ^ 32 chance of collision after 2 ^ 64 iterations. If more
    or less uniqueness is desired, the *size* argument can be adjusted
    accordingly.

    Args:
        size (int): character length of the GUID, defaults to 24. Lengths
                    between 20 and 36 are considered valid.

    The GUIDerator has built-in fork protection that causes it to
    detect a fork on next iteration and reseed accordingly.

       c                     || _         |dk     s|dk    rt          d          dd l}|j        | _        t          j                    | _        |                                  d S )N   $   zexpected 20 < size <= 36r   )rO   rU   hashlibsha1_sha1rM   rP   reseed)r  rO   r=  s      r   r  zGUIDerator.__init__  s[    	"99r		7888\
_&&
r   c                 J   dd l }t          j                    | _        d                    t          | j                  |                                pdt          t          j                              t          j        d          	                                g          | _
        d S )Nr   r  z<nohostname>   )socketosgetpidpidra   r   gethostnametimeurandomhexsalt)r  rC  s     r   r@  zGUIDerator.reseed  s    9;;HHc$(mm$0022Dn!$)++.. jmm//113 4 4	 	r   c                     | S r'   r(   r&  s    r   __iter__zGUIDerator.__iter__  s    r   c                 F   t          j                    | j        k    r|                                  | j        t          t          | j                            z                       d          }| 	                    |          
                                d | j                 }|S )Nutf8)rD  rE  rF  r@  rK  r   r   rP   encoder?  	hexdigestrO   )r  target_bytes	hash_texts      r   __next__zGUIDerator.__next__  s|    9;;$(""KKMMM	CTZ(8(8$9$99AA&IIJJ|,,6688$)D	r   N)r9  )	r"  r(  r)  r*  r  r@  rM  rT  r   r(   r   r   r8  r8  z  s`         (          DDDr   r8  c                   ,     e Zd ZdZ fdZd ZeZ xZS )SequentialGUIDeratora  Much like the standard GUIDerator, the SequentialGUIDerator is an
    iterator that yields a globally-unique identifier (GUID) on every
    iteration. The GUIDs produced are hexadecimal strings.

    The SequentialGUIDerator differs in that it picks a starting GUID
    value and increments every iteration. This yields GUIDs which are
    of course unique, but also ordered and lexicographically sortable.

    The SequentialGUIDerator is around 50% faster than the normal
    GUIDerator, making it almost 20x as fast as the built-in uuid
    module. By default it is also more compact, partly due to its
    96-bit (24-hexdigit) default length. 96 bits of randomness means that
    there is a 1 in 2 ^ 32 chance of collision after 2 ^ 64
    iterations. If more or less uniqueness is desired, the *size*
    argument can be adjusted accordingly.

    Args:
        size (int): character length of the GUID, defaults to 24.

    Note that with SequentialGUIDerator there is a chance of GUIDs
    growing larger than the size configured. The SequentialGUIDerator
    has built-in fork protection that causes it to detect a fork on
    next iteration and reseed accordingly.

    c                 F   t                                                       |                     | j                            d                                                    }t          |d | j                 d          | _        | xj        d| j        dz  dz
  z  z  c_        d S )NrO     r	      rz   )	superr@  r?  rK  rP  rQ  r0   rO   r   )r  	start_strr   s     r   r@  zSequentialGUIDerator.reseed  s    JJty//7788BBDD	:DI:.33


qdi!mq012



r   c                     t          j                    | j        k    r|                                  dt	          | j                  | j        z   z  S )Nz%x)rD  rE  rF  r@  r   rP   r   r&  s    r   rT  zSequentialGUIDerator.__next__  s>    9;;$(""KKMMMtDJ''$*455r   )r"  r(  r)  r*  r@  rT  r   __classcell__)r   s   @r   rV  rV    sL         43 3 3 3 36 6 6
 DDDDDr   rV  c                 .   pg pg pd t          |           }fd|D             }|                    |           r"t          fd|D             fd          r"t          fd|D             fd          |z   z   S )	aT  For when you care about the order of some elements, but not about
    others.

    Use this to float to the top and/or sink to the bottom a specific
    ordering, while sorting the rest of the elements according to
    normal :func:`sorted` rules.

    >>> soft_sorted(['two', 'b', 'one', 'a'], first=['one', 'two'])
    ['one', 'two', 'a', 'b']
    >>> soft_sorted(range(7), first=[6, 15], last=[2, 4], reverse=True)
    [6, 5, 3, 1, 0, 2, 4]
    >>> import string
    >>> ''.join(soft_sorted(string.hexdigits, first='za1', last='b', key=str.lower))
    'aA1023456789cCdDeEfFbB'

    Args:
       iterable (list): A list or other iterable to sort.
       first (list): A sequence to enforce for elements which should
          appear at the beginning of the returned list.
       last (list): A sequence to enforce for elements which should
          appear at the end of the returned list.
       key (callable): Callable used to generate a comparable key for
          each item to be sorted, same as the key in
          :func:`sorted`. Note that entries in *first* and *last*
          should be the keys for the items. Defaults to
          passthrough/the identity function.
       reverse (bool): Whether or not elements not explicitly ordered
          by *first* and *last* should be in reverse order or not.

    Returns a new list in sorted order.
    c                     | S r'   r(   r/   s    r   r0  zsoft_sorted.<locals>.<lambda>  s    A r   c                 P    g | ]"}r |          v r |          v  |#S r(   r(   )r   r*   r   r   lasts     r   r   zsoft_sorted.<locals>.<listcomp>  sQ     C C C1	C3q66U???Q4 1?r   r   reversec                 .    g | ]} |          v |S r(   r(   )r   r*   r   r   s     r   r   zsoft_sorted.<locals>.<listcomp>  s&    :::a##a&&E/////r   c                 @                          |                     S r'   index)r*   r   r   s    r   r0  zsoft_sorted.<locals>.<lambda>  s    U[[Q%8%8 r   r   c                 .    g | ]} |          v |S r(   r(   )r   r*   r   ra  s     r   r   zsoft_sorted.<locals>.<listcomp>  s&    888QQ4qr   c                 @                          |                     S r'   rf  )r*   r   ra  s    r   r0  zsoft_sorted.<locals>.<lambda>  s    DJJss1vv$6$6 r   )r   sortsorted)r:   r   ra  r   rc  seqothers    ```   r   soft_sortedro    s   @ KRE:2D

++C
x..CC C C C C C C C CE	JJ3J((( ::::::3:::88888: : : 888888#888666668 8 85=4r   c                      G fdd          }!t                    st          dz            t          | ||          S )a!  A version of :func:`sorted` which will happily sort an iterable of
    heterogeneous types and return a new list, similar to legacy Python's
    behavior.

    >>> untyped_sorted(['abc', 2.0, 1, 2, 'def'])
    [1, 2.0, 2, 'abc', 'def']

    Note how mutually orderable types are sorted as expected, as in
    the case of the integers and floats above.

    .. note::

       Results may vary across Python versions and builds, but the
       function will produce a sorted list, except in the case of
       explicitly unorderable objects.

    c                   $    e Zd ZdZd Z fdZdS ) untyped_sorted.<locals>._Wrapperr   c                     || _         d S r'   r   )r  r   s     r   r  z)untyped_sorted.<locals>._Wrapper.__init__!  s    DHHHr   c                 d    | j                   n| j         } |j                   n|j         }	 ||k     }nt# t          $ rg t          |          j        t	          t          |                    |ft          |          j        t	          t          |                    |fk     }Y nw xY w|S r'   )r   r   rg   r"  r  )r  rn  r   r   r   s       r   __lt__z'untyped_sorted.<locals>._Wrapper.__lt__$  s    #&?##dh---C&)oCC	NNN59EIEk I I IS		*BtCyyMM3?u++.4;;GHI Js   < A.B-,B-N)r"  r(  r)  slotsr  ru  rh  s   r   _Wrapperrr    sB        	 	 		 	 	 	 	 	 	r   rw  Nz5expected function or callable object for key, not: %rrb  )r1   r   rl  )r:   r   rc  rw  s    `  r   untyped_sortedrx    sz    $           x}}O   	 ('::::r   )NNr'   )T)r   r   F)Nr   )Nr   Fr.   )NNNF)Gr*  rD  r   rH  codecsr   rM   r   collections.abcr   r   r   r   r   	typeutilsr
   r   r   ImportErrorobjectr   r   r   r#   r   r<   r8   rC   rB   rI   rH   rS   rY   rL   rx   r   r   r|   r   r   r   r   r   boolr   r   r   r   r   r   r   r   r   r   r   r	  r   r   r  re   r  r   r  r-  r6  r8  rV  	guid_iterseq_guid_iterro  rx  r(   r   r   <module>r     s  >	 	 
			         ! ! ! ! ! ! G G G G G G G G G G G G G G((((((]8$$F-..KK   &((KVXXFFF
  $A A A B B B	0 	0 	0 	0E E E EP	4 	4 	4 	4   $	4 	4 	4 	4   6	3 	3 	3 	3	H 	H 	H 	H9 9 9 9.   * * *Z3 3 3 3l  & & & &0 " + + + +2 $ 5 5 5 5 #) &. &. &. &.R   ,   >< < < <"[ [ [ [| Td M M M M`  ? ? ? ?.' ' ' '! ! ! !H< < < <~ 2  2  2  2F0 0 0 0:  ( ( (  / / / /6   $      . $=| A A A AH3 3 3 3 3h
I 3 3 3( "( : : : :z .-uM 9 9 9 9F1 1 1 1 1 1 1 1h& & & & &: & & &R JLL	$$&&.  .  .  . b&; &; &; &;R s   A A)(A)