B
    `a]                 @   sz  d Z ddlmZ ddlmZ ddlmZmZmZmZm	Z	m
Z
mZmZmZmZmZmZmZmZ ddlmZ ddlZddlmZ dd	lmZ dd
lmZ ddlZddlmZ dddddddgiZddddddddgZ G dd de!Z"G dd de#Z$G dd de%Z&G dd de&e'Z(G dd de&e)Z*G d d de&e+Z,G d!d" d"e-Z.e./  G d#d$ d$e-Z0G d%d deZ1d&d Z2dS )'z
Customisable progressbar decorator for iterators.
Includes a default (x)range iterator printing to stderr.

Usage:
  >>> from tqdm import trange[, tqdm]
  >>> for i in trange(10): #same as: for i in tqdm(xrange(10))
  ...     ...
    )absolute_import)division   )_supports_unicode_environ_cols_wrapper_range_unich_term_move_up_unicodeWeakSet_basestring_OrderedDict
ComparableRE_ANSI	_is_asciiSimpleTextIOWrapperFormatReplace)TMonitorN)Number)time)contextmanager)warnzgithub.com/ZnoamraphZobiwanusZkmikeZhadimZ	casperdclZlrq3000tqdmtrangeTqdmTypeErrorTqdmKeyErrorTqdmWarningTqdmExperimentalWarningTqdmDeprecationWarningTqdmMonitorWarningc               @   s   e Zd ZdS )r   N)__name__
__module____qualname__ r#   r#   'lib/python3.7/site-packages/tqdm/std.pyr   #   s   c               @   s   e Zd ZdS )r   N)r    r!   r"   r#   r#   r#   r$   r   '   s   c                   s"   e Zd ZdZd fdd	Z  ZS )r   zqbase class for all tqdm warnings.

    Used for non-external-code-breaking errors, such as garbled printing.
    Nc                sJ   |d k	r.|d| j j d t|  d  ntt| j|f|| d S )N
z: )	__class__r    strrstripsuperr   __init__)selfmsgfp_writeak)r&   r#   r$   r*   0   s    $zTqdmWarning.__init__)N)r    r!   r"   __doc__r*   __classcell__r#   r#   )r&   r$   r   +   s   c               @   s   e Zd ZdZdS )r   z(beta feature, unstable API and behaviourN)r    r!   r"   r0   r#   r#   r#   r$   r   8   s   c               @   s   e Zd ZdS )r   N)r    r!   r"   r#   r#   r#   r$   r   =   s   c               @   s   e Zd ZdZdS )r   z>tqdm monitor errors which do not affect external functionalityN)r    r!   r"   r0   r#   r#   r#   r$   r   B   s   c               @   sP   e Zd ZdZdd Zdd Zdd Zdd	 Zd
d Ze	dd Z
e	dd ZdS )TqdmDefaultWriteLocka  
    Provide a default write lock for thread and multiprocessing safety.
    Works only on platforms supporting `fork` (so Windows is excluded).
    You must initialise a `tqdm` or `TqdmDefaultWriteLock` instance
    before forking in order for the write lock to work.
    On Windows, you need to supply the lock from the parent to the children as
    an argument to joblib or the parallelism lib you use.
    c             C   s4   |    |   t| }dd |j|jgD | _d S )Nc             S   s   g | ]}|d k	r|qS )Nr#   ).0Zlkr#   r#   r$   
<listcomp>V   s    z1TqdmDefaultWriteLock.__init__.<locals>.<listcomp>)create_mp_lockcreate_th_locktypemp_lockth_locklocks)r+   clsr#   r#   r$   r*   P   s    zTqdmDefaultWriteLock.__init__c             C   s   x| j D ]}|  qW d S )N)r:   acquire)r+   lockr#   r#   r$   r<   X   s    zTqdmDefaultWriteLock.acquirec             C   s&   x | j d d d D ]}|  qW d S )N)r:   release)r+   r=   r#   r#   r$   r?   \   s    zTqdmDefaultWriteLock.releasec             C   s   |    d S )N)r<   )r+   r#   r#   r$   	__enter__`   s    zTqdmDefaultWriteLock.__enter__c             G   s   |    d S )N)r?   )r+   excr#   r#   r$   __exit__c   s    zTqdmDefaultWriteLock.__exit__c             C   sZ   t | dsVyddlm} | | _W n2 tk
r<   d | _Y n tk
rT   d | _Y nX d S )Nr8   r   )RLock)hasattrZmultiprocessingrC   r8   ImportErrorOSError)r;   rC   r#   r#   r$   r5   f   s    

z#TqdmDefaultWriteLock.create_mp_lockc             C   s8   t | ds4yt | _W n tk
r2   d | _Y nX d S )Nr9   )rD   thrC   r9   rF   )r;   r#   r#   r$   r6   q   s
    
z#TqdmDefaultWriteLock.create_th_lockN)r    r!   r"   r0   r*   r<   r?   r@   rB   classmethodr5   r6   r#   r#   r#   r$   r2   G   s   r2   c            	   @   sJ   e Zd ZdZdZddeeeddd Z	dZ
d	e	fd
dZdd ZdS )Bara  
    `str.format`-able bar with format specifiers: `[width][type]`

    - `width`
      + unspecified (default): use `self.default_len`
      + `int >= 0`: overrides `self.default_len`
      + `int < 0`: subtract from `self.default_len`
    - `type`
      + `a`: ascii (`charset=self.ASCII` override)
      + `u`: unicode (`charset=self.UTF` override)
      + `b`: blank (`charset="  "` override)
    z 123456789#  i%  i%  r>   z  
   c             C   s<   d|  krdksn t |dks&t || _|| _|| _d S )Nr   r   )AssertionErrorfracdefault_lencharset)r+   rN   rO   rP   r#   r#   r$   r*      s
    zBar.__init__c       
      C   s   |r||d   }yt| j| j| jd| }W n tk
rF   | j}Y nX |d d }|rtt|}|dk rz|| j7 }q| j}n| j}| j}t	|d }t
t| j| | |\}}|d | }|| }	||k r||	 |d || d   S ||d ||   S )Nr>   )r.   ubr   r   )lowerdictASCIIUTFBLANKKeyErrorrP   intrO   lendivmodrN   )
r+   format_specZ_typerP   ZN_BARSZnsymsZ
bar_lengthZfrac_bar_lengthbarZfrac_barr#   r#   r$   
__format__   s.    zBar.__format__N)r    r!   r"   r0   rU   joinmapr   rangerV   rW   r*   r^   r#   r#   r#   r$   rI      s   rI   c               @   s  e Zd ZdZdZdZed[ddZedd	 Zed
d Z	ed\ddZ
edd Zed]ddZdd Zed^ddZedd Zed_ddZeed`ddZed d! Zed"d# Zed$d% Zdad*d+Zd,d- Zd.d/ Zd0d1 Zd2d3 Zd4d5 Zd6d7 Zd8d9 Zed:d; Z d<d= Z!d>d? Z"dbdAdBZ#dCdD Z$dcdEdFZ%dddGdHZ&dIdJ Z'dedKdLZ(dfdMdNZ)dgdOdPZ*dhdQdRZ+didSdTZ,dUdV Z-edWdX Z.djdYdZZ/dS )kr   z
    Decorate an iterable object, returning an iterator which acts exactly
    like the original iterable, but prints a dynamically updating
    progressbar every time a value is requested.
    rL   NrK     c             C   s~   xndD ]f}t | dk rdt | dk rRt | dk r@d| | | S d| | | S d| | | S | | } qW d| | S )	a  
        Formats a number (greater than unity) with SI Order of Magnitude
        prefixes.

        Parameters
        ----------
        num  : float
            Number ( >= 1) to format.
        suffix  : str, optional
            Post-postfix [default: ''].
        divisor  : float, optional
            Divisor between prefixes [default: 1000].

        Returns
        -------
        out  : str
            Number with Order of Magnitude SI unit postfix.
        )rK   r/   MGTPEZg     <@gX@g=
ףp#@z{0:1.2f}z{0:2.1f}z{0:3.0f}z	{0:3.1f}Y)absformat)Znumsuffixdivisorunitr#   r#   r$   format_sizeof   s    
ztqdm.format_sizeofc             C   sB   t t| d\}}t |d\}}|r2d|||S d||S dS )z
        Formats a number of seconds as a clock time, [H:]MM:SS

        Parameters
        ----------
        t  : int
            Number of seconds.

        Returns
        -------
        out  : str
            [H:]MM:SS
        <   z{0:d}:{1:02d}:{2:02d}z{0:02d}:{1:02d}N)r[   rY   rj   )tZminsshmr#   r#   r$   format_interval   s
    ztqdm.format_intervalc             C   s:   d | dddd}t| } t|t| k r6|S | S )z
        Intelligent scientific notation (.3g).

        Parameters
        ----------
        n  : int or float or Numeric
            A Number.

        Returns
        -------
        out  : str
            Formatted number.
        z{0:.3g}z+0+z-0-)rj   replacer'   rZ   )nfr#   r#   r$   
format_num   s    ztqdm.format_num333333?c             C   s    |dkr| S ||  d| |  S )a  
        Exponential moving average: smoothing to give progressively lower
        weights to older values.

        Parameters
        ----------
        x  : float
            New value to include in EMA.
        mu  : float, optional
            Previous EMA value.
        alpha  : float, optional
            Smoothing factor in range [0, 1], [default: 0.3].
            Increase to give more weight to recent values.
            Ranges from 0 (yields mu) to 1 (yields x).
        Nr   r#   )xZmuZalphar#   r#   r$   ema  s    ztqdm.emac                s:   |  t  ddd  fdddgfdd}|S )	z
        Manage the printing and in-place updating of a line of characters.
        Note that if the string is longer than a line, then in-place
        updating may not work (it will print a new line at each refresh).
        flushc               S   s   d S )Nr#   r#   r#   r#   r$   <lambda>&      z%tqdm.status_printer.<locals>.<lambda>c                s     t|    d S )N)writer
   )rq   )fpfp_flushr#   r$   r-   (  s    z%tqdm.status_printer.<locals>.fp_writer   c                s6   t | } d|  dtd | d   |d< d S )NrJ   r   )rZ   max)rq   Zlen_s)r-   last_lenr#   r$   print_status.  s    "z)tqdm.status_printer.<locals>.print_status)getattr)filer   r#   )r   r   r-   r   r$   status_printer  s    ztqdm.status_printerFitc             K   s  |r| |krd}|r@|dkr@|r(||9 }| |9 } |r<||9 }d}t |}|dkr^|r^| | }|rjd| nd}t j}|r|r||qd|nd| d }|r|r||qd|ndd | }|r|dkr|n|}|r|| |d	}|dk	r|||d	nd}nt| }|dk	rt|nd}y|
r,d
|
 nd}
W n tk
rH   Y nX |rb|rb||  | nd}|rvt |nd}|r|dd dk}|r|n|d }nd}d||||||
}tf | |||||||pd||r|dkr|n|||||||
|||||d|}|r*| | }|d }|d|7 }|dkrV|dd |dd  S |j|d |	r|j|d |s|	dd}	nd}	t	 }|	jf d|i|}|j
s|S t||rtd|ttd| nd|dkrtjn
|ptjd}t|jst|	rt|	}	|	jf d|i|S |	r|d7 }|j|dd t	 }|	jf d|i|}|j
sl|S td|rtd|ttd| ndtjd}|	jf d|i|S |r|d ndd|||||
 S dS )a
  
        Return a string-based progress bar given some parameters

        Parameters
        ----------
        n  : int
            Number of finished iterations.
        total  : int
            The expected total number of iterations. If meaningless (), only
            basic progress statistics are displayed (no ETA).
        elapsed  : float
            Number of seconds passed since start.
        ncols  : int, optional
            The width of the entire output message. If specified,
            dynamically resizes `{bar}` to stay within this bound
            [default: None]. If `0`, will not print any bar (only stats).
            The fallback is `{bar:10}`.
        prefix  : str, optional
            Prefix message (included in total width) [default: ''].
            Use as {desc} in bar_format string.
        ascii  : bool, optional or str, optional
            If not set, use unicode (smooth blocks) to fill the meter
            [default: False]. The fallback is to use ASCII characters
            " 123456789#".
        unit  : str, optional
            The iteration unit [default: 'it'].
        unit_scale  : bool or int or float, optional
            If 1 or True, the number of iterations will be printed with an
            appropriate SI metric prefix (k = 10^3, M = 10^6, etc.)
            [default: False]. If any other non-zero number, will scale
            `total` and `n`.
        rate  : float, optional
            Manual override for iteration rate.
            If [default: None], uses n/elapsed.
        bar_format  : str, optional
            Specify a custom bar string formatting. May impact performance.
            [default: '{l_bar}{bar}{r_bar}'], where
            l_bar='{desc}: {percentage:3.0f}%|' and
            r_bar='| {n_fmt}/{total_fmt} [{elapsed}<{remaining}, '
              '{rate_fmt}{postfix}]'
            Possible vars: l_bar, bar, r_bar, n, n_fmt, total, total_fmt,
              percentage, elapsed, elapsed_s, ncols, desc, unit,
              rate, rate_fmt, rate_noinv, rate_noinv_fmt,
              rate_inv, rate_inv_fmt, postfix, unit_divisor,
              remaining, remaining_s.
            Note that a trailing ": " is automatically removed after {desc}
            if the latter is empty.
        postfix  : *, optional
            Similar to `prefix`, but placed at the end
            (e.g. for additional stats).
            Note: postfix is usually a string (not a dict) for this method,
            and will if possible be set to postfix = ', ' + postfix.
            However other types are supported (#382).
        unit_divisor  : float, optional
            [default: 1000], ignored unless `unit_scale` is True.

        Returns
        -------
        out  : Formatted meter and stats, ready to display.
        N)Tr   Fr   z{0:5.2f}?z/szs/)rl   z, rK   r   z: z| {0}/{1} [{2}<{3}, {4}{5}])rx   n_fmttotal	total_fmtelapsedZ	elapsed_sncolsdescrm   raterate_fmtZ
rate_noinvrate_noinv_fmtZrate_invrate_inv_fmtpostfixunit_divisor	remainingZremaining_sl_barr_bard   z
{0:3.0f}%|r>   )r   )
percentagez{desc}: z{l_bar}{bar}{r_bar}r]   rL   T)rP   |)r   r   z{0}{1} [{2}, {3}{4}])r   rt   rn   rj   r'   	TypeErrorrT   updaterw   r   Zformat_calledrI   r   rZ   r   subrU   rV   r   rP   r
   rW   )rx   r   r   r   prefixasciirm   
unit_scaler   
bar_formatr   r   Zextra_kwargsZelapsed_strZinv_ratern   r   r   r   r   r   r   Zremaining_strZbool_prefix_colon_alreadyr   r   format_dictrN   r   Zfull_barZnobarr#   r#   r$   format_meter5  s    B
&&
" "
ztqdm.format_meterc             O   s   t | }|   t| ds&t | _| j| | jr| jd ksL| j	 syt
| | j| _W n: tk
r } ztdt| t d| _W d d }~X Y nX W d Q R X |S )N
_instancesz>tqdm:disabling monitor support (monitor_interval = 0) due to:
r   )object__new__get_lockrD   r   r   addmonitor_intervalmonitorZreportr   	Exceptionr   r'   r   )r;   argskwargsinstanceer#   r#   r$   r     s    



"ztqdm.__new__c                s6   t  fdd| jD }tt tt|d |S )zSkips specified instance.c             3   s*   | ]"}| k	rt |d rt|jV  qdS )posN)rD   ri   r   )r3   inst)r   r#   r$   	<genexpr>  s    z%tqdm._get_free_pos.<locals>.<genexpr>r   )setr   minra   rZ   
difference)r;   r   Z	positionsr#   )r   r$   _get_free_pos  s    ztqdm._get_free_posc          	   C   s   | j  y| j| W n tk
r,   Y nX |jsxxB| jD ]8}t|dr<|jt|jkr<|jdd | jd8  _q<W | js| j	ry| j	
  | `	W n tk
r   Y nX d| _	W dQ R X dS )zs
        Remove from list and reposition other bars
        so that newer bars won't overlap previous bars
        r   T)nolockr   N)_lockr   removerX   guirD   r   ri   clearr   exitAttributeError)r;   r   r   r#   r#   r$   _decr_instances  s"    
ztqdm._decr_instancesr%   c          	   C   sD   |dk	r|nt j}| j||d || || W dQ R X dS )z5Print a message via tqdm (without overlap with bars).N)r   r   )sysstdoutexternal_write_moder   )r;   rq   r   endr   r   r#   r#   r$   r   2  s    
z
tqdm.writec             c   s   |dk	r|nt j}|s"|    g }xVt| dg D ]F}t|dr4|j|ksdtdd ||jfD r4|jdd |	| q4W dV  x|D ]}|j
dd qW |s| j  dS )z
        Disable tqdm within context and refresh tqdm when exits.
        Useful when writing to standard output stream
        Nr   start_tc             s   s   | ]}|t jt jfkV  qd S )N)r   r   stderr)r3   ry   r#   r#   r$   r   M  s    z+tqdm.external_write_mode.<locals>.<genexpr>T)r   )r   r   r   r<   r   rD   r   allr   appendrefreshr   r?   )r;   r   r   r   Zinst_clearedr   r#   r#   r$   r   ;  s    
ztqdm.external_write_modec             C   s
   || _ dS )zSet the global lock.N)r   )r;   r=   r#   r#   r$   set_lockW  s    ztqdm.set_lockc             C   s   t | dst | _| jS )z7Get the global lock. Construct it if it does not exist.r   )rD   r2   r   )r;   r#   r#   r$   r   \  s    
ztqdm.get_lockc       
         s  ddl m} ddlm  ddlm} yddlm W n tk
rL   dY nX yddl	m
}m} W nN tk
r   yddlm
}m} W n$ tk
r   ddlm
}m} Y nX Y nX yddlm} W n  tk
r   ddlm} Y nX ydd	lm} W nB tk
r6   ydd	lm} W n tk
r0   d}Y nX Y nX d
dgd fdd	}	|	  _|	 |_|	d _|	d|_|	 |_|	 |_|	d|_|	 |_|dk	r|	 |_|	 |_|	d|_|	d|_dk	r|	 _dS )ab  
        Registers the given `tqdm` class with
            pandas.core.
            ( frame.DataFrame
            | series.Series
            | groupby.(generic.)DataFrameGroupBy
            | groupby.(generic.)SeriesGroupBy
            ).progress_apply

        A new instance will be create every time `progress_apply` is called,
        and each instance will automatically close() upon completion.

        Parameters
        ----------
        targs, tkwargs  : arguments for the tqdm instance

        Examples
        --------
        >>> import pandas as pd
        >>> import numpy as np
        >>> from tqdm import tqdm
        >>> from tqdm.gui import tqdm as tqdm_gui
        >>>
        >>> df = pd.DataFrame(np.random.randint(0, 100, (100000, 6)))
        >>> tqdm.pandas(ncols=50)  # can use tqdm_gui, optional kwargs, etc
        >>> # Now you can use `progress_apply` instead of `apply`
        >>> df.groupby(0).progress_apply(lambda x: x**2)

        References
        ----------
        https://stackoverflow.com/questions/18603270/
        progress-indicator-during-pandas-operations-python
        r   )	DataFrame)Series)Panel)_Rolling_and_ExpandingN)DataFrameGroupBySeriesGroupBy)GroupBy)PanelGroupBydeprecated_tapplyc                s    fdd}|S )Nc                s
   dt| dd}|dkrdkr,| j}n\t| r@t| }nHdksRt| s|dd}|dkrld}n|dkrxd	}| j| j|  }d dk	rd dd< nd|it|dkrtd
tjdt	j
jd  fdd}t| |f|}  |S )aT  
                Parameters
                ----------
                df  : (DataFrame|Series)[GroupBy]
                    Data (may be grouped).
                func  : function
                    To be applied on the (grouped) data.
                **kwargs  : optional
                    Transmitted to `df.apply()`.
                r   ZngroupsNapplymapaxisr   indexcolumnsr   zExcept func, normal arguments are intentionally not supported by `(DataFrame|Series|GroupBy).progress_apply`. Use keyword arguments instead.r   )r-   c                 s,   j jrjjk rdndd  | |S )Nr   r   )rx   )r   r   rx   )r   r   )funcrp   r#   r$   wrapper  s    "zDtqdm.pandas.<locals>.inner_generator.<locals>.inner.<locals>.wrapper)popr   size
isinstancerZ   getshaper   r   r   r   r   close)Zdfr   r   r   r   r   r   result)r   r   r   df_functiontargstclasstkwargs)r   rp   r$   inner  s4    




z3tqdm.pandas.<locals>.inner_generator.<locals>.innerr#   )r   r   )r   r   r   r   r   r   )r   r$   inner_generator  s    ?z$tqdm.pandas.<locals>.inner_generatorr`   r   Z	aggregateZ	transform)r   )Zpandas.core.framer   Zpandas.core.seriesr   pandasr   Zpandas.core.windowr   rE   Zpandas.core.groupby.genericr   r   Zpandas.core.groupby.groupbyZpandas.core.groupbyr   r   r   Zprogress_applyZprogress_mapZprogress_applymapZprogress_aggregateZprogress_transform)
r   r   r   r   r   r   r   r   r   r   r#   )r   r   r   r   r   r   r$   r   c  sT    #
D






ztqdm.pandasT皙?      $@r   c          	   K   s  |dkr|dkot jdk }|dkr(t j}|rDt|t|ddp>dd}|dkrbt|drb| sbd}|dkr|dk	ryt|}W n tt	fk
r   d}Y nX |t
dkrd}|r|| _|| _| j | | | _| j|  W dQ R X || _|| _dS |rnd| _| j | | | _| j|  W dQ R X d	d
lm} d|kr^t|dt|dt jjdntdt| |dkr|t jt jfks|r|rt }|r||}nt }|r||}|	dkrd	}	d}nd}|dkrd	}|dkrd	}|
dkrt| }
|r*|
dks*t|
s*t|}|dkr8d	}|| _|pFd| _|| _|| _ || _!|| _"|| _#|| _$|	| _%|| _&|
| _'|| _|| _(|| _)|| _*|| _+|| _,|| _-d| _.t/| _0|| _1d| _2|ry| j3f ddi| W n tk
r   || _2Y nX || _4|| _| j& |dkr*| | | _n| | _W dQ R X |sj| 5| j!| _6| j | 7  W dQ R X | 0 | _8| j8| _9dS )a  
        Parameters
        ----------
        iterable  : iterable, optional
            Iterable to decorate with a progressbar.
            Leave blank to manually manage the updates.
        desc  : str, optional
            Prefix for the progressbar.
        total  : int, optional
            The number of expected iterations. If unspecified,
            len(iterable) is used if possible. If float("inf") or as a last
            resort, only basic progress statistics are displayed
            (no ETA, no progressbar).
            If `gui` is True and this parameter needs subsequent updating,
            specify an initial arbitrary large positive integer,
            e.g. int(9e9).
        leave  : bool, optional
            If [default: True], keeps all traces of the progressbar
            upon termination of iteration.
            If `None`, will leave only if `position` is `0`.
        file  : `io.TextIOWrapper` or `io.StringIO`, optional
            Specifies where to output the progress messages
            (default: sys.stderr). Uses `file.write(str)` and `file.flush()`
            methods.  For encoding, see `write_bytes`.
        ncols  : int, optional
            The width of the entire output message. If specified,
            dynamically resizes the progressbar to stay within this bound.
            If unspecified, attempts to use environment width. The
            fallback is a meter width of 10 and no limit for the counter and
            statistics. If 0, will not print any meter (only stats).
        mininterval  : float, optional
            Minimum progress display update interval [default: 0.1] seconds.
        maxinterval  : float, optional
            Maximum progress display update interval [default: 10] seconds.
            Automatically adjusts `miniters` to correspond to `mininterval`
            after long display update lag. Only works if `dynamic_miniters`
            or monitor thread is enabled.
        miniters  : int, optional
            Minimum progress display update interval, in iterations.
            If 0 and `dynamic_miniters`, will automatically adjust to equal
            `mininterval` (more CPU efficient, good for tight loops).
            If > 0, will skip display of specified number of iterations.
            Tweak this and `mininterval` to get very efficient loops.
            If your progress is erratic with both fast and slow iterations
            (network, skipping items, etc) you should set miniters=1.
        ascii  : bool or str, optional
            If unspecified or False, use unicode (smooth blocks) to fill
            the meter. The fallback is to use ASCII characters " 123456789#".
        disable  : bool, optional
            Whether to disable the entire progressbar wrapper
            [default: False]. If set to None, disable on non-TTY.
        unit  : str, optional
            String that will be used to define the unit of each iteration
            [default: it].
        unit_scale  : bool or int or float, optional
            If 1 or True, the number of iterations will be reduced/scaled
            automatically and a metric prefix following the
            International System of Units standard will be added
            (kilo, mega, etc.) [default: False]. If any other non-zero
            number, will scale `total` and `n`.
        dynamic_ncols  : bool, optional
            If set, constantly alters `ncols` to the environment (allowing
            for window resizes) [default: False].
        smoothing  : float, optional
            Exponential moving average smoothing factor for speed estimates
            (ignored in GUI mode). Ranges from 0 (average speed) to 1
            (current/instantaneous speed) [default: 0.3].
        bar_format  : str, optional
            Specify a custom bar string formatting. May impact performance.
            [default: '{l_bar}{bar}{r_bar}'], where
            l_bar='{desc}: {percentage:3.0f}%|' and
            r_bar='| {n_fmt}/{total_fmt} [{elapsed}<{remaining}, '
              '{rate_fmt}{postfix}]'
            Possible vars: l_bar, bar, r_bar, n, n_fmt, total, total_fmt,
              percentage, elapsed, elapsed_s, ncols, desc, unit,
              rate, rate_fmt, rate_noinv, rate_noinv_fmt,
              rate_inv, rate_inv_fmt, postfix, unit_divisor,
              remaining, remaining_s.
            Note that a trailing ": " is automatically removed after {desc}
            if the latter is empty.
        initial  : int, optional
            The initial counter value. Useful when restarting a progress
            bar [default: 0].
        position  : int, optional
            Specify the line offset to print this bar (starting from 0)
            Automatic if unspecified.
            Useful to manage multiple bars at once (eg, from threads).
        postfix  : dict or *, optional
            Specify additional stats to display at the end of the bar.
            Calls `set_postfix(**postfix)` if possible (dict).
        unit_divisor  : float, optional
            [default: 1000], ignored unless `unit_scale` is True.
        write_bytes  : bool, optional
            If (default: None) and `file` is unspecified,
            bytes will be written in Python 2. If `True` will also write
            bytes. In all other cases will default to unicode.
        gui  : bool, optional
            WARNING: internal parameter - do not use.
            Use tqdm.gui.tqdm(...) instead. If set, will attempt to use
            matplotlib animations for a graphical output [default: False].

        Returns
        -------
        out  : decorated iterator.
        N)   encodingzutf-8)r   isattyTinfr   )dedentnestedz                       `nested` is deprecated and automated.
                       Use `position` instead for manual control.
                       r   )r-   zUnknown argument(s): FrK   r   ):r   version_infor   r   r   rD   r   rZ   r   r   floatiterabledisabler   r   r   r   r   rx   r   textwrapr   r   r   r   r'   r   r   r   r   r
   r   leaver   r   minintervalmaxintervalminitersdynamic_minitersr   rm   r   r   r   dynamic_ncols	smoothingavg_timer   _timer   r   set_postfixlast_print_nr   spdisplaylast_print_tr   )r+   r   r   r   r   r   r   r   r   r   r   r   rm   r   r   r   r   initialZpositionr   r   Zwrite_bytesr   r   r   Z_dynamic_ncolsr   r#   r#   r$   r*     s    o
&








ztqdm.__init__c             C   s0   | j d k	r| j dkS | jd kr&tdt| jS )Nr   z/bool() undefined when iterable == total == None)r   r   r   bool)r+   r#   r#   r$   __bool__  s
    


ztqdm.__bool__c             C   s   |   S )N)r	  )r+   r#   r#   r$   __nonzero__  s    ztqdm.__nonzero__c             C   sJ   | j d kr| jS t| j dr(| j jd S t| j dr>t| j S t| dd S )Nr   r   __len__r   )r   r   rD   r   rZ   r   )r+   r#   r#   r$   r    s    ztqdm.__len__c             C   s   | S )Nr#   )r+   r#   r#   r$   r@     s    ztqdm.__enter__c             C   s@   y|    W n. tk
r:   |||fdkr, tdt Y nX d S )N)NNNzAttributeError ignored)r   r   r   r   )r+   exc_type	exc_value	tracebackr#   r#   r$   rB     s    ztqdm.__exit__c             C   s   |    d S )N)r   )r+   r#   r#   r$   __del__  s    ztqdm.__del__c             C   s   | j f | jS )N)r   r   )r+   r#   r#   r$   __repr__  s    ztqdm.__repr__c             C   s   t t| ddS )Nr   l        )ri   r   )r+   r#   r#   r$   _comparable  s    ztqdm._comparablec             C   s   t | S )N)id)r+   r#   r#   r$   __hash__  s    ztqdm.__hash__c          
   c   s  | j }| jr$x|D ]
}|V  qW dS | j}| j}| j}| j}| j}| j}| j}	| j	}
| j
}| j}t| dsddlm} t|dt| jdtjjdx2|D ](}|V  |	d7 }	|	| | jkr| j}| | }||kr| }|	| }|
r|r|r|| }| |||
}|| _
|	| _| j |   W dQ R X |r|rj||krj|r\|| | }n|| | }n<|
r|}|r|r||| 9 }| |||
}n
t||}|	 | _ | _}| | _}|| _qW || _|	| _|| _|   dS )	z6Backward-compatibility to use: for x in tqdm(iterable)Nr  r   )r   zY            Please use `tqdm.gui.tqdm(...)` instead of `tqdm(..., gui=True)`
            r   )r-   r   )r   r   r   r   r   r   r  r  rx   r   r   r  rD   r   r   r   r   r   r   r   r   r}   r   r  r   r   )r+   r   objr   r   r   r   r  r  rx   r   r   r   r   delta_tcur_tdelta_itr   r#   r#   r$   __iter__  sj    






ztqdm.__iter__r   c          	   C   s  | j r
dS |dk r |  j|7  _|  j|7  _| j| j | jkr~|  | j }|| jkr~|  }| j| j }| jr|r|r|| }| || j	| j| _	t
| dstdt| jdtjjd| j |   W dQ R X | jrp| jr || jkr | jr|| j | | _n|| j | | _nP| jrb| j| | jrH|rH| j| nd d| j | j  | _nt| j|| _| j| _|| _dS )a~  
        Manually update the progress bar, useful for streams
        such as reading files.
        E.g.:
        >>> t = tqdm(total=filesize) # Initialise
        >>> for current_buffer in stream:
        ...    ...
        ...    t.update(len(current_buffer))
        >>> t.close()
        The last line is highly recommended, but possibly not necessary if
        `t.update()` will be called in such a way that `filesize` will be
        exactly reached and printed.

        Parameters
        ----------
        n  : int, optional
            Increment to add to the internal counter of iterations
            [default: 1].
        Nr   r  zAPlease use `tqdm.gui.tqdm(...)` instead of `tqdm(..., gui=True)`
r   )r-   r   )r   r  rx   r   r  r  r   r   r}   r   rD   r   r   r   r   r   r   r   r  r   r   r   )r+   rx   r  r  r  r   r#   r#   r$   r   q  sB    
ztqdm.updatec          
      s    j r
dS d _ t j}   t ds2dS  fdd}y|d W n4 tk
r~ } zdt|krldS  W dd}~X Y nX  jdkr|dkn j} j@ |rd _	 j
dd	 |d
 n j
d|d |s|d W dQ R X dS )z3Cleanup and (if leave=False) close the progressbar.NTr  c                s    j t|  d S )N)r   r   r
   )rq   )r+   r#   r$   r-     s    ztqdm.close.<locals>.fp_writerK   closedr   )r   r%   )r,   r   r   )r   ri   r   r   rD   
ValueErrorr'   r   r   r   r  )r+   r   r-   r   r   r#   )r+   r$   r     s.    



z
tqdm.closec             C   sb   | j r
dS |s| j  | t| j | d | jd | t| j  |s^| j	  dS )zClear current bar display.NrK   r   )
r   r   r<   movetori   r   r  r   r   r?   )r+   r   r#   r#   r$   r     s    

z
tqdm.clearc             C   s2   | j r
dS |s| j  |   |s.| j  dS )z&Force refresh the display of this bar.N)r   r   r<   r  r?   )r+   r   r#   r#   r$   r     s    
ztqdm.refreshc             C   s&   |   }|  j|| j 7  _|| _dS )z(Restart tqdm timer from last print time.N)r  r   r  )r+   r  r#   r#   r$   unpause  s    ztqdm.unpausec             C   s6   d | _ | _|   | _| _|dk	r*|| _|   dS )z
        Resets to 0 iterations for repeated use.

        Consider combining with `leave=True`.

        Parameters
        ----------
        total  : int, optional. Total to use for the new bar.
        r   N)r  rx   r  r  r   r   r   )r+   r   r#   r#   r$   reset  s
    
z
tqdm.resetc             C   s"   |r|d nd| _ |r|   dS )z
        Set/modify description of the progress bar.

        Parameters
        ----------
        desc  : str, optional
        refresh  : bool, optional
            Forces refresh [default: True].
        z: rK   N)r   r   )r+   r   r   r#   r#   r$   set_description  s    
ztqdm.set_descriptionc             C   s   |pd| _ |r|   dS )z-Set/modify description without ': ' appended.rK   N)r   r   )r+   r   r   r#   r#   r$   set_description_str"  s    
ztqdm.set_description_strc                s   t |dkrg n| x t| D ]}||  |< q"W xP  D ]D}t | trf|  |  |< q@t | ts@t |  |< q@W d fdd  D | _	|r| 
  dS )a8  
        Set/modify postfix (additional stats)
        with automatic formatting based on datatype.

        Parameters
        ----------
        ordered_dict  : dict or OrderedDict, optional
        refresh  : bool, optional
            Forces refresh [default: True].
        kwargs  : dict, optional
        Nz, c             3   s"   | ]}|d   |    V  qdS )=N)strip)r3   key)r   r#   r$   r   B  s   z#tqdm.set_postfix.<locals>.<genexpr>)r   sortedkeysr   r   rz   r   r'   r_   r   r   )r+   Zordered_dictr   r   r"  r#   )r   r$   r  (  s    ztqdm.set_postfixc             C   s   t || _|r|   dS )zS
        Postfix without dictionary expansion, similar to prefix handling.
        N)r'   r   r   )r+   rq   r   r#   r#   r$   set_postfix_strG  s    
ztqdm.set_postfix_strc             C   s.   | j td| t |    | j   d S )Nr%   )r   r   r
   r	   r~   )r+   rx   r#   r#   r$   r  O  s     ztqdm.movetoc             C   sn   t | j| jt| dr"|  | j nd| jr6| | jn| j| j	| j
| j| j| jrZd| j nd| j| j| jdS )z'Public API for read-only member access.r   r   r   N)rx   r   r   r   r   r   rm   r   r   r   r   r   )rT   rx   r   rD   r  r   r   r   r   r   r   rm   r   r   r   r   r   )r+   r#   r#   r$   r   T  s    ztqdm.format_dictc             C   sN   |dkrt | j}|r | | | |dkr4|  n| |rJ| |  dS )a  
        Use `self.sp` to display `msg` in the specified `pos`.

        Consider overloading this function when inheriting to use e.g.:
        `self.some_frontend(**self.format_dict)` instead of `self.sp`.

        Parameters
        ----------
        msg  : str, optional. What to display (default: `repr(self)`).
        pos  : int, optional. Position to `moveto`
          (default: `abs(self.pos)`).
        N)ri   r   r  r  r  )r+   r,   r   r#   r#   r$   r  c  s    

ztqdm.display)rK   rb   )Nr{   )	NrK   Fr   FNNNrb   )N)Nr%   F)NF)NNNTNNr   r   NNFr   FFr{   Nr   NNrb   NF)r   )F)F)N)NT)NT)NT)rK   T)NN)0r    r!   r"   r0   r   r   staticmethodrn   rt   rz   r}   r   r   r   rH   r   r   r   r   r   r   r   r   r*   r	  r
  r  r@   rB   r  r  propertyr  r  r  r   r   r   r   r  r  r  r  r  r%  r  r   r  r#   r#   r#   r$   r      st      ?      
 p	V
L(






c              O   s   t t|  f|S )zh
    A shortcut for tqdm(xrange(*args), **kwargs).
    On Python3+ range is used instead of xrange.
    )r   r   )r   r   r#   r#   r$   r   z  s    )3r0   Z
__future__r   r   Zutilsr   r   r   r   r	   r
   r   r   r   r   r   r   r   r   Z_monitorr   r   Znumbersr   r   
contextlibr   Z	threadingrG   warningsr   
__author____all__r   r   rX   r   Warningr   FutureWarningr   DeprecationWarningr   RuntimeWarningr   r   r2   r6   rI   r   r   r#   r#   r#   r$   <module>	   sH   @

79         I