B A[Z@sdZddlmZddlZddlmZddlmZm Z ddl m Z m ZddlZddlZddlmZddlmZmZmZdd lmZmZmZmZdd l m!Z!m"Z"m#Z#m$Z$d d Zdd lm%Z%e$ryddl&m'Z'Wn e(k rddl)m'Z'YnXn4yddl*m'Z'Wn"e(k r"ddl+m'Z'YnXd3ddZ,Gddde-Z.Gddde/Z0yddl m Z ddlm1Z1Wne(k rYnXddZ2Gddde/Z3ddZ4d4dd Z5Gd!d"d"e Z6dd#lm7Z7e7dfd$d%Z8d&d'Z9e0Z:e3Z;e4Ze2Z?e,Z@e6ZAe8ZBe9ZCejDd(krndd)lm0Z0m3Z3dd*lm5Z5dd+lEm9Z9ydd,lm4Z4Wne(k r`YnXdd-lm8Z8ejDd.krddlmZdd/lm2Z2ejDd0krdd1lFm,Z,dd2lm6Z6dS)5a Miscellaneous function (re)definitions from the Py3.4+ standard library for Python 2.6/2.7. - math.ceil (for Python 2.7) - collections.OrderedDict (for Python 2.6) - collections.Counter (for Python 2.6) - collections.ChainMap (for all versions prior to Python 3.3) - itertools.count (for Python 2.6, with step parameter) - subprocess.check_output (for Python 2.6) - reprlib.recursive_repr (for Python 2.6+) - functools.cmp_to_key (for Python 2.6) )absolute_importN)ceil)MappingMutableMapping) itemgettereq)proxy)repeatchainstarmap) getaddrinfo SOCK_STREAMerrorsocket) iteritems itervaluesPY26PY3cCs tt|S)zZ Return the ceiling of x as an int. This is the smallest integral value >= x. )intoldceil)xrF/opt/alt/python37/lib/python3.7/site-packages/future/backports/misc.pyrsr)islice) get_ident...csfdd}|S)zGDecorator to make a repr function return fillvalue for a recursive callcsLtfdd}td|_td|_td|_tdi|_|S)Nc sBt|tf}|krS|z |}Wd|X|S)N)idradddiscard)selfkeyresult) fillvalue repr_running user_functionrrwrapper?s   z.decorating_function..wrapper __module____doc____name____annotations__)setgetattrr&r'r(r))r$r%)r")r#r$rdecorating_function<s   z+recursive_repr..decorating_functionr)r"r,r)r"rrecursive_repr9s r-c@seZdZdZdS)_Link)prevnextr __weakref__N)r(r& __qualname__ __slots__rrrrr.Xsr.c@seZdZdZddZejeefddZej fddZ dd Z d d Z d d Z d$ddZ d%ddZddZejZZejZejZejZejZeZefddZd&ddZeddZddZddZed'd d!Z d"d#Z!dS)( OrderedDictz)Dictionary that remembers insertion ordercOs|s td|d}|dd}t|dkrtk rt|_t|j|_}||_|_i|_ YnX|j ||dS)zInitialize an ordered dictionary. The signature is the same as regular dictionaries, but keyword arguments are not recommended because their insertion order is arbitrary. z?descriptor '__init__' of 'OrderedDict' object needs an argumentrNz$expected at most 1 arguments, got %d) TypeErrorlen_OrderedDict__rootAttributeErrorr._OrderedDict__hardroot_proxyr/r0_OrderedDict__map_OrderedDict__update)argskwdsrrootrrr__init__js     zOrderedDict.__init__c CsZ||krJ||j|<}|j}|j}||||_|_|_||_|||_||||dS)z!od.__setitem__(i, y) <==> od[i]=yN)r<r8r/r0r ) rr valueZ dict_setitemrZLinklinkr@lastrrr __setitem__s zOrderedDict.__setitem__cCs2||||j|}|j}|j}||_||_dS)z od.__delitem__(y) <==> del od[y]N)r<popr/r0)rr Z dict_delitemrC link_prev link_nextrrr __delitem__s   zOrderedDict.__delitem__ccs,|j}|j}x||k r&|jV|j}qWdS)zod.__iter__() <==> iter(od)N)r8r0r )rr@currrrr__iter__s  zOrderedDict.__iter__ccs,|j}|j}x||k r&|jV|j}qWdS)z#od.__reversed__() <==> reversed(od)N)r8r/r )rr@rJrrr __reversed__s  zOrderedDict.__reversed__cCs*|j}||_|_|jt|dS)z.od.clear() -> None. Remove all items from od.N)r8r/r0r<cleardict)rr@rrrrMs  zOrderedDict.clearTcCsj|s td|j}|r0|j}|j}||_||_n|j}|j}||_||_|j}|j|=t||}||fS)zod.popitem() -> (k, v), return and remove a (key, value) pair. Pairs are returned in LIFO order if last is true or FIFO order if false. zdictionary is empty)KeyErrorr8r/r0r r<rNrF)rrDr@rCrGrHr rBrrrpopitems  zOrderedDict.popitemcCsn|j|}|j}|j}||_||_|j}|rL|j}||_||_||_|_n|j}||_||_||_|_dS)zMove an existing element to the end (or beginning if last==False). Raises KeyError if the element does not exist. When last=True, acts like a fast version of self[key]=self.pop(key). N)r<r/r0r8)rr rDrCrGrHr@firstrrr move_to_ends zOrderedDict.move_to_endcCsVtj}t|d}||j}|||jd7}|||j|7}|||j|7}|S)Nr5)sys getsizeofr7__dict__r<r:r8)rZsizeofnsizerrr __sizeof__s  zOrderedDict.__sizeof__cCs0||kr||}||=|S||jkr,t||S)zod.pop(k[,d]) -> v, remove specified key and return the corresponding value. If key is not found, d is returned if given, otherwise KeyError is raised. )_OrderedDict__markerrO)rr defaultr!rrrrFs zOrderedDict.popNcCs||kr||S|||<|S)zDod.setdefault(k[,d]) -> od.get(k,d), also set od[k]=d if k not in odr)rr r[rrr setdefaultszOrderedDict.setdefaultcCs*|sd|jjfSd|jjt|fS)zod.__repr__() <==> repr(od)z%s()z%s(%r)) __class__r(listitems)rrrr__repr__szOrderedDict.__repr__cCsHt|}xttD]}||dqW|jd|p8ddt|fS)z%Return state information for picklingNr)varscopyr4rFr]iterr_)rZ inst_dictkrrr __reduce__s zOrderedDict.__reduce__cCs ||S)z!od.copy() -> a shallow copy of od)r])rrrrrbszOrderedDict.copycCs |}x|D] }|||<q W|S)zOD.fromkeys(S[, v]) -> New ordered dictionary with keys from S. If not specified, the value defaults to None. r)clsiterablerBrr rrrfromkeyss  zOrderedDict.fromkeyscCs2t|tr&t||o$ttt||St||S)zod.__eq__(y) <==> od==y. Comparison to another OD is order-sensitive while comparison to a regular mapping is order-insensitive. ) isinstancer4rN__eq__allmap_eq)rotherrrrrj$s zOrderedDict.__eq__)T)T)N)N)"r(r&r2r'rArNrEr;r.rIrKrLrMrPrRrYrupdater=keysvaluesr___ne__objectrZrFr\r-r`rerb classmethodrhrjrrrrr4[s0          r4)r)nlargestcCs*|j}x|D]}||dd||<q WdS)z!Tally elements from the iterable.rr5N)get)mappingrgZ mapping_getelemrrr_count_elements:s rycseZdZdZfddZddZd/ddZd d Zed0d d Z fd dZ ddZ ddZ ddZ fddZddZddZddZddZdd Zd!d"Zd#d$Zd%d&Zd'd(Zd)d*Zd+d,Zd-d.ZZS)1CounteraDict subclass for counting hashable items. Sometimes called a bag or multiset. Elements are stored as dictionary keys and their counts are stored as dictionary values. >>> c = Counter('abcdeabcdabcaba') # count elements from a string >>> c.most_common(3) # three most common elements [('a', 5), ('b', 4), ('c', 3)] >>> sorted(c) # list all unique elements ['a', 'b', 'c', 'd', 'e'] >>> ''.join(sorted(c.elements())) # list elements with repetitions 'aaaaabbbbcccdde' >>> sum(c.values()) # total of all counts 15 >>> c['a'] # count of letter 'a' 5 >>> for elem in 'shazam': # update counts from an iterable ... c[elem] += 1 # by adding 1 to each element's count >>> c['a'] # now there are seven 'a' 7 >>> del c['b'] # remove all 'b' >>> c['b'] # now there are zero 'b' 0 >>> d = Counter('simsalabim') # make another counter >>> c.update(d) # add in the second counter >>> c['a'] # now there are nine 'a' 9 >>> c.clear() # empty the counter >>> c Counter() Note: If a count is set to zero or reduced to zero, it will remain in the counter until the entry is deleted or the counter is cleared: >>> c = Counter('aaabbc') >>> c['b'] -= 2 # reduce the count of 'b' by two >>> c.most_common() # 'b' is still in, but its count is zero [('a', 3), ('c', 1), ('b', 0)] csZ|s td|d}|dd}t|dkr>> c = Counter() # a new, empty counter >>> c = Counter('gallahad') # a new counter from an iterable >>> c = Counter({'a': 4, 'b': 2}) # a new counter from a mapping >>> c = Counter(a=4, b=2) # a new counter from keyword args z;descriptor '__init__' of 'Counter' object needs an argumentrr5Nz$expected at most 1 arguments, got %d)r6r7superrzrAro)r>r?r)r]rrrAss   zCounter.__init__cCsdS)z1The count of elements not in the Counter is zero.rr)rr rrr __missing__szCounter.__missing__NcCs6|dkrt|tdddStj||tddS)zList the n most common elements and their counts from the most common to the least. If n is None, then list all element counts. >>> Counter('abcdeabcdabcaba').most_common(3) [('a', 5), ('b', 4), ('c', 3)] Nr5T)r reverse)r )sortedr_ _itemgetter_heapqru)rrWrrr most_commons zCounter.most_commoncCsttt|S)aIterator over elements repeating each as many times as its count. >>> c = Counter('ABCABC') >>> sorted(c.elements()) ['A', 'A', 'B', 'B', 'C', 'C'] # Knuth's example for prime factors of 1836: 2**2 * 3**3 * 17**1 >>> prime_factors = Counter({2: 2, 3: 3, 17: 1}) >>> product = 1 >>> for factor in prime_factors.elements(): # loop over factors ... product *= factor # and multiply them >>> product 1836 Note, if an element's count has been set to zero or is a negative number, elements() will ignore it. )_chain from_iterable_starmap_repeatr_)rrrrelementsszCounter.elementscCs tddS)Nz@Counter.fromkeys() is undefined. Use Counter(iterable) instead.)NotImplementedError)rfrgvrrrrhszCounter.fromkeyscs|s td|d}|dd}t|dkr>> c = Counter('which') >>> c.update('witch') # add elements from another iterable >>> d = Counter('watch') >>> c.update(d) # add elements from another counter >>> c['h'] # four 'h' in which, witch, and watch 4 z9descriptor 'update' of 'Counter' object needs an argumentrr5Nz$expected at most 1 arguments, got %d) r6r7rirrvr_r{rzrory)r>r?rrgself_getrxcount)r]rrros"    zCounter.updatecOs|s td|d}|dd}t|dkr>> c = Counter('which') >>> c.subtract('witch') # subtract elements from another iterable >>> c.subtract(Counter('watch')) # subtract elements from another counter >>> c['h'] # 2 in which, minus 1 in witch, minus 1 in watch 0 >>> c['w'] # 1 in which, minus 1 in witch, minus 1 in watch -1 z;descriptor 'subtract' of 'Counter' object needs an argumentrr5Nz$expected at most 1 arguments, got %d)r6r7rvrirr_subtract)r>r?rrgrrxrrrrrs     zCounter.subtractcCs ||S)zReturn a shallow copy.)r])rrrrrbsz Counter.copycCs|jt|ffS)N)r]rN)rrrrre szCounter.__reduce__cs||krtt||dS)zGLike dict.__delitem__() but does not raise KeyError for missing values.N)r{rzrI)rrx)r]rrrI szCounter.__delitem__cCs`|sd|jjSy&dtdj|}d|jj|fStk rZd|jjt|SXdS)Nz%s()z, z%r: %rz%s({%s})z {0}({1!r})) r]r(joinrl__mod__rr6formatrN)rr_rrrr`s zCounter.__repr__cCsxt|tstSt}x0|D]$\}}|||}|dkr|||<qWx,|D] \}}||krP|dkrP|||<qPW|S)zAdd counts from two counters. >>> Counter('abbb') + Counter('bcc') Counter({'b': 4, 'c': 2, 'a': 1}) r)rirzNotImplementedr_)rrnr!rxrnewcountrrr__add__$s    zCounter.__add__cCs|t|tstSt}x0|D]$\}}|||}|dkr|||<qWx0|D]$\}}||krP|dkrPd|||<qPW|S)z Subtract count, but keep only results with positive counts. >>> Counter('abbbc') - Counter('bccd') Counter({'b': 2, 'a': 1}) r)rirzrr_)rrnr!rxrrrrr__sub__7s   zCounter.__sub__cCst|tstSt}x<|D]0\}}||}||kr:|n|}|dkr|||<qWx,|D] \}}||kr\|dkr\|||<q\W|S)zUnion is the maximum of value in either of the input counters. >>> Counter('abbb') | Counter('bcc') Counter({'b': 3, 'c': 2, 'a': 1}) r)rirzrr_)rrnr!rxr other_countrrrr__or__Js   zCounter.__or__cCsVt|tstSt}x<|D]0\}}||}||kr:|n|}|dkr|||<qW|S)z Intersection is the minimum of corresponding counts. >>> Counter('abbb') & Counter('bcc') Counter({'b': 1}) r)rirzrr_)rrnr!rxrrrrrr__and__^s  zCounter.__and__cCs |tS)zEAdds an empty counter, effectively stripping negative and zero counts)rz)rrrr__pos__oszCounter.__pos__cCs t|S)z{Subtracts from an empty counter. Strips positive and zero counts, and flips the sign on negative counts. )rz)rrrr__neg__sszCounter.__neg__cCs*dd|D}x|D] }||=qW|S)z?Internal method to strip elements with a negative or zero countcSsg|]\}}|dks|qS)rr).0rxrrrr |sz*Counter._keep_positive..)r_)r nonpositiverxrrr_keep_positivezs  zCounter._keep_positivecCs.x$|D]\}}|||7<q W|S)zInplace add from another counter, keeping only positive counts. >>> c = Counter('abbb') >>> c += Counter('bcc') >>> c Counter({'b': 4, 'c': 2, 'a': 1}) )r_r)rrnrxrrrr__iadd__s zCounter.__iadd__cCs.x$|D]\}}|||8<q W|S)zInplace subtract counter, but keep only results with positive counts. >>> c = Counter('abbbc') >>> c -= Counter('bccd') >>> c Counter({'b': 2, 'a': 1}) )r_r)rrnrxrrrr__isub__s zCounter.__isub__cCs6x,|D] \}}||}||kr |||<q W|S)zInplace union is the maximum of value from either counter. >>> c = Counter('abbb') >>> c |= Counter('bcc') >>> c Counter({'b': 3, 'c': 2, 'a': 1}) )r_r)rrnrxrrrrr__ior__s  zCounter.__ior__cCs6x,|D] \}}||}||kr |||<q W|S)zInplace intersection is the minimum of corresponding counts. >>> c = Counter('abbb') >>> c &= Counter('bcc') >>> c Counter({'b': 1}) )r_r)rrnrxrrrrr__iand__s  zCounter.__iand__)N)N)r(r&r2r'rAr|rrrtrhrorrbrerIr`rrrrrrrrrrr __classcell__rr)r]rrz@s0+    )#   rzcOshd|krtdtj|dtji|}|\}}|}|rd|d}|dkrX|d}t|||S)z[ For Python 2.6 compatibility: see http://stackoverflow.com/questions/4814970/ stdoutz3stdout argument not allowed, it will be overridden.r>Nr) ValueError subprocessPopenPIPE communicatepollrvCalledProcessError) popenargskwargsprocessoutputZ unused_errretcodecmdrrr check_outputs   rr5ccsx|V||7}qWdS)z ``itertools.count`` in Py 2.6 doesn't accept a step parameter. This is an enhanced version of ``itertools.count`` for Py2.6 equivalent to ``itertools.count`` in Python 2.7+. Nr)startsteprrrrsrc@seZdZdZddZddZddZd'd d Zd d Zd dZ ddZ ddZ e Z e ddZeddZddZeZd(ddZeddZddZdd Zd!d"Zd#d$Zd%d&ZdS))ChainMapa A ChainMap groups multiple dicts (or other mappings) together to create a single, updateable view. The underlying mappings are stored in a list. That list is public and can accessed or updated using the *maps* attribute. There is no other state. Lookups search the underlying mappings successively until a key is found. In contrast, writes, updates, and deletions only operate on the first mapping. cGst|p ig|_dS)zInitialize a ChainMap by setting *maps* to the given mappings. If no mappings are provided, a single empty dictionary is used. N)r^maps)rrrrrrAszChainMap.__init__cCs t|dS)N)rO)rr rrrr|szChainMap.__missing__c Cs8x,|jD]"}y||Stk r(YqXqW||S)N)rrOr|)rr rwrrr __getitem__s   zChainMap.__getitem__NcCs||kr||S|S)Nr)rr r[rrrrvsz ChainMap.getcCsttj|jS)N)r7r*unionr)rrrr__len__szChainMap.__len__cCsttj|jS)N)rcr*rr)rrrrrKszChainMap.__iter__cstfdd|jDS)Nc3s|]}|kVqdS)Nr)rm)r rr sz(ChainMap.__contains__..)anyr)rr r)r r __contains__szChainMap.__contains__cCs t|jS)N)rr)rrrr__bool__ szChainMap.__bool__cCsd|dtt|jS)Nz{0.__class__.__name__}({1})z, )rrrlreprr)rrrrr`szChainMap.__repr__cGs|tj|f|S)z?Create a ChainMap with a single dict created from the iterable.)rNrh)rfrgr>rrrrhszChainMap.fromkeyscCs$|j|jdf|jddS)zHNew ChainMap or subclass with a new copy of maps[0] and refs to maps[1:]rr5N)r]rrb)rrrrrbsz ChainMap.copycCs|dkr i}|j|f|jS)z New ChainMap with a new map followed by all previous maps. If no map is provided, an empty dict is used. N)r]r)rrrrr new_childszChainMap.new_childcCs|j|jddS)zNew ChainMap from maps[1:].r5N)r]r)rrrrparents(szChainMap.parentscCs||jd|<dS)Nr)r)rr rBrrrrE-szChainMap.__setitem__cCs8y|jd|=Wn"tk r2td|YnXdS)Nrz)Key not found in the first mapping: {0!r})rrOr)rr rrrrI0szChainMap.__delitem__cCs0y|jdStk r*tdYnXdS)zPRemove and return an item pair from maps[0]. Raise KeyError is maps[0] is empty.rz#No keys found in the first mapping.N)rrPrO)rrrrrP6szChainMap.popitemcGs>y|jdj|f|Stk r8td|YnXdS)zWRemove *key* from maps[0] and return its value. Raise KeyError if *key* not in maps[0].rz)Key not found in the first mapping: {0!r}N)rrFrOr)rr r>rrrrF=sz ChainMap.popcCs|jddS)z'Clear maps[0], leaving maps[1:] intact.rN)rrM)rrrrrMDszChainMap.clear)N)N)r(r&r2r'rAr|rrvrrKrrZ __nonzero__r-r`rtrhrb__copy__rpropertyrrErIrPrFrMrrrrrs*    r)_GLOBAL_DEFAULT_TIMEOUTc Cs|\}}d}xt||dtD]}|\}}} } } d} y:t||| } |tk rR| ||r`| || | | Stk r} z| }| dk r| Wdd} ~ XYqXqW|dk r|ntddS)aBackport of 3-argument create_connection() for Py2.6. Connect to *address* and return the socket object. Convenience function. Connect to *address* (a 2-tuple ``(host, port)``) and return the socket object. Passing the optional *timeout* parameter will set the timeout on the socket instance before attempting to connect. If no *timeout* is supplied, the global default timeout setting returned by :func:`getdefaulttimeout` is used. If *source_address* is set it must be a tuple of (host, port) for the socket to bind as a source address before making the connection. An host of '' or port 0 tells the OS to use the default. Nrz!getaddrinfo returns an empty list) r r rrZ settimeoutZbindZconnectrclose)ZaddresstimeoutZsource_addresshostZporterrresZafZsocktypeprotoZ canonnameZsaZsock_rrrcreate_connectionNs(    rcsGfdddt}|S)z,Convert a cmp= function into a key= functioncsjeZdZdgZddZfddZfddZfdd Zfd d Zfd d Z fddZ ddZ dS)zcmp_to_key..KobjcWs ||_dS)N)r)rrr>rrrrA{szcmp_to_key..K.__init__cs|j|jdkS)Nr)r)rrn)mycmprr__lt__}szcmp_to_key..K.__lt__cs|j|jdkS)Nr)r)rrn)rrr__gt__szcmp_to_key..K.__gt__cs|j|jdkS)Nr)r)rrn)rrrrjszcmp_to_key..K.__eq__cs|j|jdkS)Nr)r)rrn)rrr__le__szcmp_to_key..K.__le__cs|j|jdkS)Nr)r)rrn)rrr__ge__szcmp_to_key..K.__ge__cs|j|jdkS)Nr)r)rrn)rrrrrszcmp_to_key..K.__ne__cSs tddS)Nzhash not implemented)r6)rrrr__hash__szcmp_to_key..K.__hash__N) r(r&r2r3rArrrjrrrrrr)rrrKys      r)rs)rrr)rr cmp_to_keywsr)rS)r4rz)r)r)r)r)r)ry)rr)r-)r)r)rr5)Gr'Z __future__rrmathrr collectionsrroperatorrrrrmrTheapqr_weakrefrr; itertoolsr rr rr rrr r rZ future.utilsrrrrr_threadr ImportErrorZ _dummy_threadthreadZ dummy_threadr-rsr.rNr4ruryrzrrrrrrZ _OrderedDictZ_CounterZ _check_output_countZ_ceilZ__count_elements_recursive_repr _ChainMapZ_create_connectionZ _cmp_to_key version_info functoolsreprlibrrrr s     V | l  (