B
    `X                 @   s  d dl mZ d dlZd dlmZ d dlZd dlZd dlZd dlm	Z
 e Ze dkZyd dlZdZW n ek
r   dZdZY nX G dd	 d	e
Z	d>ddZd?ddZdd Zdd Zdd Zdd ZG dd dZG dd dZG dd dZG dd dZd d! Zd"d# Zd$d% ZG d&d' d'Zed(Z ed)Z!G d*d+ d+Z"d,d- Z#ed.d/ Z$d0d1 Z%d2d3 Z&d@d4d5Z'G d6d7 d7Z(d8d9 Z)d:d; Z*dAd<d=Z+dS )B    )contextmanagerN)compare_digest)DottedNameResolverWindowsTFc               @   s   e Zd ZdddZdS )r   Nc             C   s   t | | d S )N)_DottedNameResolver__init__)selfpackage r
   T/home/kop/projects/devel/pgwui/test_venv/lib/python3.7/site-packages/pyramid/util.pyr      s    zDottedNameResolver.__init__)N)__name__
__module____qualname__r   r
   r
   r
   r   r      s   r   latin-1strictc             C   s   t | tr| ||S | S )zgIf ``s`` is an instance of ``bytes``, return
    ``s.decode(encoding, errors)``, otherwise return ``s``)
isinstancebytesdecode)sencodingerrorsr
   r
   r   text_   s    
r   c             C   s   t | tr| ||S | S )zeIf ``s`` is an instance of ``str``, return
    ``s.encode(encoding, errors)``, otherwise return ``s``)r   strencode)r   r   r   r
   r
   r   bytes_&   s    
r   c             C   s    t | tr| d} t| ddS )z~
    If ``s`` is an instance of ``str``, return
    ``s.encode('ascii')``, otherwise return ``str(s, 'ascii', 'strict')``
    asciir   )r   r   r   )r   r
   r
   r   ascii_.   s    

r   c             C   s   t | trdS t| dS )NF__iter__)r   r   hasattr)vr
   r
   r   is_nonstr_iter8   s    
r    c             C   s    t | trdS t| drdS d S )NTr   )r   r   r   )r   r
   r
   r   is_string_or_iterable>   s    

r!   c             C   s   t | s| f} tt| } | S )N)r    tuplesorted)valr
   r
   r   as_sorted_tupleE   s    r%   c               @   s   e Zd Zdd ZdddZdS )SettablePropertyc             C   s   || _ t| | d S )N)wrapped	functoolsupdate_wrapper)r   r'   r
   r
   r   r   O   s    zSettableProperty.__init__Nc             C   s   |d kr| S |  |S )N)r'   )r   objtyper
   r
   r   __get__S   s    zSettableProperty.__get__)N)r   r   r   r   r,   r
   r
   r
   r   r&   L   s   r&   c               @   sR   e Zd ZdZdd ZedddZedd	 Zedd
dZdddZ	dd Z
dS )InstancePropertyHelpera  A helper object for assigning properties and descriptors to instances.
    It is not normally possible to do this because descriptors must be
    defined on the class itself.

    This class is optimized for adding multiple properties at once to an
    instance. This is done by calling :meth:`.add_property` once
    per-property and then invoking :meth:`.apply` on target objects.

    c             C   s
   i | _ d S )N)
properties)r   r
   r
   r   r   d   s    zInstancePropertyHelper.__init__NFc                s   |dkr t  dstd j}t|}t }|rB|rBtd|rL }n< fdd}||_ j|_|rddl}|j	|}nt
|}||fS )zConvert a callable into one suitable for adding to the
        instance. This will return a 2-tuple containing the computed
        (name, property) pair.
        Nr   z2missing __name__, must specify "name" for propertyzcannot reify a data descriptorc                s    | S )Nr
   )this)callabler
   r   <lambda>{       z6InstancePropertyHelper.make_property.<locals>.<lambda>r   )r   
ValueErrorr   get_callable_nameinspectisdatadescriptor__doc__Zpyramid.decorator	decoratorreifyr&   )clsr0   namer9   Zis_data_descriptorfnr'   Zpyramidr
   )r0   r   make_propertyg   s&    

z$InstancePropertyHelper.make_propertyc             C   sj   t |}|rf|j}|d|j t|j|tf|}x,dD ]$}t||t}|tk	r8t	||| q8W ||_dS )zAccept a list or dict of ``properties`` generated from
        :meth:`.make_property` and apply them to a ``target`` object.
        r   )Z__implemented__Z__provides__N)
dict	__class__
setdefaultr   r+   r   objectgetattr_markersetattr)r:   targetr.   attrsparentZnewclsr;   r$   r
   r
   r   apply_properties   s    
z'InstancePropertyHelper.apply_propertiesc             C   s"   | j |||d}| ||g dS )z:A helper method to apply a single property to an instance.)r;   r9   N)r=   rH   )r:   rE   r0   r;   r9   propr
   r
   r   set_property   s    z#InstancePropertyHelper.set_propertyc             C   s"   | j |||d\}}|| j|< dS )zAdd a new property configuration.

        This should be used in combination with :meth:`.apply` as a
        more efficient version of :meth:`.set_property`.
        )r;   r9   N)r=   r.   )r   r0   r;   r9   r<   r
   r
   r   add_property   s    z#InstancePropertyHelper.add_propertyc             C   s   | j r| || j  dS )z< Apply all configured properties to the ``target`` instance.N)r.   rH   )r   rE   r
   r
   r   apply   s    zInstancePropertyHelper.apply)NF)NF)NF)r   r   r   r7   r   classmethodr=   rH   rJ   rK   rL   r
   r
   r
   r   r-   Y   s   	 !
	r-   c               @   s   e Zd ZdZdddZdS )InstancePropertyMixinzMixin that will allow an instance to add properties at
    run-time as if they had been defined via @property or @reify
    on the class itself.
    NFc             C   s   t j| |||d dS )a  Add a callable or a property descriptor to the instance.

        Properties, unlike attributes, are lazily evaluated by executing
        an underlying callable when accessed. They can be useful for
        adding features to an object without any cost if those features
        go unused.

        A property may also be reified via the
        :class:`pyramid.decorator.reify` decorator by setting
        ``reify=True``, allowing the result of the evaluation to be
        cached. Using this method, the value of the property is only
        computed once for the lifetime of the object.

        ``callable`` can either be a callable that accepts the instance
        as its single positional parameter, or it can be a property
        descriptor.

        If the ``callable`` is a property descriptor, the ``name``
        parameter must be supplied or a ``ValueError`` will be raised.
        Also note that a property descriptor cannot be reified, so
        ``reify`` must be ``False``.

        If ``name`` is None, the name of the property will be computed
        from the name of the ``callable``.

        .. code-block:: python
           :linenos:

           class Foo(InstancePropertyMixin):
               _x = 1

           def _get_x(self):
               return _x

           def _set_x(self, value):
               self._x = value

           foo = Foo()
           foo.set_property(property(_get_x, _set_x), name='x')
           foo.set_property(_get_x, name='y', reify=True)

           >>> foo.x
           1
           >>> foo.y
           1
           >>> foo.x = 5
           >>> foo.x
           5
           >>> foo.y # notice y keeps the original value
           1
        )r;   r9   N)r-   rJ   )r   r0   r;   r9   r
   r
   r   rJ      s    4z"InstancePropertyMixin.set_property)NF)r   r   r   r7   rJ   r
   r
   r
   r   rN      s   rN   c               @   s\   e 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edd ZdS )WeakOrderedSeta  Maintain a set of items.

    Each item is stored as a weakref to avoid extending their lifetime.

    The values may be iterated over or the last item added may be
    accessed via the ``last`` property.

    If items are added more than once, the most recent addition will
    be remembered in the order:

        order = WeakOrderedSet()
        order.add('1')
        order.add('2')
        order.add('1')

        list(order) == ['2', '1']
        order.last == '1'
    c             C   s   i | _ g | _d S )N)_items_order)r   r
   r
   r   r     s    zWeakOrderedSet.__init__c                s^   t |  jkr.j  j  dS t| fdd}|j < j  dS )z Add an item to the set.Nc                s
     S )N)_remove_by_id)x)oidr   r
   r   r1     r2   z$WeakOrderedSet.add.<locals>.<lambda>)idrP   rQ   removeappendweakrefref)r   itemrY   r
   )rT   r   r   add  s    

zWeakOrderedSet.addc             C   s"   || j kr| j |= | j| dS )z Remove an item from the set.N)rP   rQ   rV   )r   rT   r
   r
   r   rR      s    
zWeakOrderedSet._remove_by_idc             C   s   |  t| dS )z Remove an item from the set.N)rR   rU   )r   rZ   r
   r
   r   rV   &  s    zWeakOrderedSet.removec             C   s   i | _ g | _dS )z  Clear all objects from the set.N)rP   rQ   )r   r
   r
   r   empty*  s    zWeakOrderedSet.emptyc             C   s
   t | jS )N)lenrQ   )r   r
   r
   r   __len__/  s    zWeakOrderedSet.__len__c             C   s   t |}|| jkS )N)rU   rP   )r   rZ   rT   r
   r
   r   __contains__2  s    zWeakOrderedSet.__contains__c                s    fdd j D S )Nc             3   s   | ]} j |  V  qd S )N)rP   ).0rT   )r   r
   r   	<genexpr>7  s    z*WeakOrderedSet.__iter__.<locals>.<genexpr>)rQ   )r   r
   )r   r   r   6  s    zWeakOrderedSet.__iter__c             C   s    | j r| j d }| j|  S d S )N)rQ   rP   )r   rT   r
   r
   r   last9  s    
zWeakOrderedSet.lastN)r   r   r   r7   r   r[   rR   rV   r\   r^   r_   r   propertyrc   r
   r
   r
   r   rO      s   rO   c             C   sB   t | t |k}|rd}| }nd}|}|}|t|| 7 }|dkS )a  Check whether two strings differ while avoiding timing attacks.

    This function returns True if the given strings differ and False
    if they are equal.  It's careful not to leak information about *where*
    they differ as a result of its running time, which can be very important
    to avoid certain timing-related crypto attacks:

        http://seb.dbzteam.org/crypto/python-oauth-timing-hmac.pdf

    .. versionchanged:: 1.6
       Support :func:`hmac.compare_digest` if it is available (Python 2.7.7+
       and Python 3.3+).

    r      )r]   r   )Zstring1Zstring2Zlen_eqZinvalid_bitsleftrightr
   r
   r   strings_differ@  s    rh   c             C   s<  t | tr| S t | tr t| S t | tttdfr<t| S t | trPt| dS t | trdt| dS t | t	rxt| dS t | t
rt| dS t| }|dkrdt|  S |j}t| rd| S t| rt| dd}d| j||jjf S t| rd	|| jf }d
| S t| r0d	|| jf }d| S dt|  S )a  Produce a human-consumable text description of ``object``,
    usually involving a Python dotted name. For example:

    >>> object_description(None)
    'None'
    >>> from xml.dom import minidom
    >>> object_description(minidom)
    'module xml.dom.minidom'
    >>> object_description(minidom.Attr)
    'class xml.dom.minidom.Attr'
    >>> object_description(minidom.Attr.appendChild)
    'method appendChild of class xml.dom.minidom.Attr'

    If this method cannot identify the type of the object, a generic
    description ala ``object <object.__name__>`` will be returned.

    If the object passed is already a string, it is simply returned.  If it
    is a boolean, an integer, a list, a tuple, a set, or ``None``, a
    (possibly shortened) string representation is returned.
    N})]z	object %sz	module %s__self__zmethod %s of class %s.%sz%s.%szclass %szfunction %s)r   r   intboolfloatr+   set	shortreprr"   listr>   r5   	getmoduler   ismoduleismethodrB   r?   isclass
isfunction)rA   module
modulenameZoselfZ
dottednamer
   r
   r   object_description\  sB    












rz   c             C   s,   t | }t|dkr(|d d d|  }|S )Nd   z ... %s)r   r]   )rA   closerrr
   r
   r   rq     s    rq   c               @   s   e Zd Zdd Zdd ZdS )Sentinelc             C   s
   || _ d S )N)repr)r   r   r
   r
   r   r     s    zSentinel.__init__c             C   s   | j S )N)r   )r   r
   r
   r   __repr__  s    zSentinel.__repr__N)r   r   r   r   r   r
   r
   r
   r   r~     s   r~   FIRSTLASTc               @   sD   e Zd ZdZedeefddZdd Zdd Zdd	d
Z	dd Z
dS )TopologicalSorterz[A utility class which can be used to perform topological sorts against
    tuple-like data.Nc             C   sJ   g | _ t | _t | _i | _i | _i | _g | _|| _|| _	|| _
|| _d S )N)namesrp   
req_before	req_aftername2before
name2aftername2valorderdefault_beforedefault_afterfirstrc   )r   r   r   r   rc   r
   r
   r   r     s    zTopologicalSorter.__init__c             C   s
   | j  S )N)r   values)r   r
   r
   r   r     s    zTopologicalSorter.valuesc             C   s   | j | | j|= | j|g }|rP| j| x|D ]}| j||f q8W | j|g }|r| j| x|D ]}| j||f qtW dS )z# Remove a node from the sort input N)	r   rV   r   r   popr   r   r   r   )r   r;   afterubeforer
   r
   r   rV     s    

zTopologicalSorter.removec                s    | j kr|   | j   || j < |dkrF|dkrF| j}| j}|dk	rt|s\|f}|| j < |  j fdd|D 7  _| j	
  |dk	rt|s|f}|| j < |  j fdd|D 7  _| j
  dS )a  Add a node to the sort input.  The ``name`` should be a string or
        any other hashable object, the ``val`` should be the sortable (doesn't
        need to be hashable).  ``after`` and ``before`` represents the name of
        one of the other sortables (or a sequence of such named) or one of the
        special sentinel values :attr:`pyramid.util.FIRST`` or
        :attr:`pyramid.util.LAST` representing the first or last positions
        respectively.  ``FIRST`` and ``LAST`` can also be part of a sequence
        passed as ``before`` or ``after``.  A sortable should not be added
        after LAST or before FIRST.  An example::

           sorter = TopologicalSorter()
           sorter.add('a', {'a':1}, before=LAST, after='b')
           sorter.add('b', {'b':2}, before=LAST, after='c')
           sorter.add('c', {'c':3})

           sorter.sorted() # will be {'c':3}, {'b':2}, {'a':1}

        Nc                s   g | ]}| fqS r
   r
   )r`   r   )r;   r
   r   
<listcomp>  s    z)TopologicalSorter.add.<locals>.<listcomp>c                s   g | ]} |fqS r
   r
   )r`   o)r;   r
   r   r     s    )r   rV   rW   r   r   r   r    r   r   r   r[   r   r   )r   r;   r$   r   r   r
   )r;   r   r[     s&    




zTopologicalSorter.addc                s<  | j | jfg}g i  | j | jg}|| j x | jD ]\}}|||f q6W  fdd} fdd}x|D ]}|| qrW t t  }}	x>|D ]6\}}||kr||kr||| || |	| qW | j	|sddl
m}
 |
ddt| j|  | j	|	s<ddl
m}
 |
d	dt| j|	  g }x|rd}||  | d
d }xD|D ]<} | d }|d
8 }| | d< |dkrrd| qrW  |= qBW  rddl
m} i }x&  D ]\}}|d
d ||< qW ||g }x.|D ]&}|| jkr||| j| f qW |S )z< Returns the sort input values in topologically sorted orderc                s    |  kr |  dg | < d S )Nr   )rW   )node)graphrootsr
   r   add_node   s    
z*TopologicalSorter.sorted.<locals>.add_nodec                s8    |   |  | d  d7  < |kr4| d S )Nr   re   )rW   rV   )ZfromnodeZtonode)r   r   r
   r   add_arc  s    z)TopologicalSorter.sorted.<locals>.add_arcr   )ConfigurationErrorz#Unsatisfied before dependencies: %sz, z"Unsatisfied after dependencies: %sre   N)CyclicDependencyError)r   rc   extendr   r   rW   rp   r[   r   issubsetpyramid.exceptionsr   joinr#   r   r   insertr   itemsr   )r   r   r   abr   r   r;   Z
has_beforeZ	has_afterr   Zsorted_namesrootchildrenchildZarcsr   Z	cycledepskr   resultr
   )r   r   r   r#     sd    







zTopologicalSorter.sorted)NN)r   r   r   r7   r   r   r   r   rV   r[   r#   r
   r
   r
   r   r     s   
'r   c          	   C   sB   yt | S  ttfk
r<   ddlm} d}|||  Y nX dS )zg
    Verifies that the ``name`` is ascii and will raise a ``ConfigurationError``
    if it is not.
    r   )r   zY`name="%s"` is invalid. `name` must be ascii because it is used on __name__ of the methodN)r   UnicodeEncodeErrorUnicodeDecodeErrorr   r   )r;   r   msgr
   r
   r   r4   G  s    r4   c          
   g   s|   | dk	r| j ni }i }x|D ]}||t||< qW z
dV  W dx4|D ],}|| }|tk	rd|||< qF||krF||= qFW X dS )z@
    Temporarily delete object attrs and restore afterward.
    N)__dict__r   rC   )r*   rF   Zobj_valsZ
saved_valsr;   Z	saved_valr
   r
   r   
hide_attrsY  s    



r   c             C   s>   |sdS |  }|d dkr6| |p<| |dd kp<|| kS )a3  
    Return ``True`` if the host is either an exact match or a match
    to the wildcard pattern.
    Any pattern beginning with a period matches a domain and all of its
    subdomains. (e.g. ``.example.com`` matches ``example.com`` and
    ``foo.example.com``). Anything else is an exact string match.
    Fr   .re   N)lowerendswith)hostpatternr
   r
   r   is_same_domainm  s    r   c                s@   t  rt S  d kr"dd  tt  fdd}|S )Nc              _   s   d S )Nr
   )r   kwr
   r
   r   r1     r2   z%make_contextmanager.<locals>.<lambda>c              ?   s    | |V  d S )Nr
   )r   r   )r<   r
   r   wrapper  s    z$make_contextmanager.<locals>.wrapper)r5   isgeneratorfunctionr   r(   wraps)r<   r   r
   )r<   r   make_contextmanager  s    
r   c             C   s   d}|d krd}t | r | }n@t | r<| j}t|d}n$yt| |}W n tk
r^   dS X t |}|d }t|ds|r|sdS |dd  }|sdS t|dkrdS |r|d }|d krd}|d |krt|t| dkrdS dS )	NF__call__r   __func__re   T   r
   )	r5   	isroutinerv   r   r   rB   AttributeErrorgetfullargspecr]   )Zcalleeattrargnameru   r<   Zargspecargsdefaultsr
   r
   r   takes_one_arg  s<    


r   c               @   s   e Zd Zdd Zdd ZdS )SimpleSerializerc             C   s   t |S )N)r   )r   Zbstructr
   r
   r   loads  s    zSimpleSerializer.loadsc             C   s   t |S )N)r   )r   Z	appstructr
   r
   r   dumps  s    zSimpleSerializer.dumpsN)r   r   r   r   r   r
   r
   r
   r   r     s   r   c             C   s   t | ot| dd d k	S )Nrl   )r5   ru   rB   )obr
   r
   r   is_bound_method  s    r   c             C   sR   t | }|sNt| rNt| }t|jdko:|jd dk}t| rN|rNdS dS )zO
    This consistently verifies that the callable is bound to a
    class.
    r   r   TF)r   r5   r   r   r]   r   rw   )r<   Zis_boundspecZhas_selfr
   r
   r   is_unbound_method  s    
r   c             C   s:   z*|d kr|  }|j |k	r$|||W d d }d }X d S )N)__traceback__with_traceback)tpvaluetbr
   r
   r   reraise  s    

r   )r   r   )r   r   )NN)N),
contextlibr   r(   hmacr   r5   platformrX   Zpyramid.pathr   r   rA   rC   systemZWINZ__pypy__ZPYPYBaseExceptionr   r   r   r    r!   r%   r&   r-   rN   rO   rh   rz   rq   r~   r   r   r   r4   r   r   r   r   r   r   r   r   r
   r
   r
   r   <module>   sT   



e?C: 
+