1
ewpratten.com/_site/assets/python/shift2/brython_modules.js

3 lines
2.1 MiB

__BRYTHON__.VFS_timestamp = 1567276198820
__BRYTHON__.use_VFS = true
__BRYTHON__.VFS = {"token": [".py", "''\n\n__all__=['tok_name','ISTERMINAL','ISNONTERMINAL','ISEOF']\n\n\n\n\n\n\n\n\n\nENDMARKER=0\nNAME=1\nNUMBER=2\nSTRING=3\nNEWLINE=4\nINDENT=5\nDEDENT=6\nLPAR=7\nRPAR=8\nLSQB=9\nRSQB=10\nCOLON=11\nCOMMA=12\nSEMI=13\nPLUS=14\nMINUS=15\nSTAR=16\nSLASH=17\nVBAR=18\nAMPER=19\nLESS=20\nGREATER=21\nEQUAL=22\nDOT=23\nPERCENT=24\nLBRACE=25\nRBRACE=26\nEQEQUAL=27\nNOTEQUAL=28\nLESSEQUAL=29\nGREATEREQUAL=30\nTILDE=31\nCIRCUMFLEX=32\nLEFTSHIFT=33\nRIGHTSHIFT=34\nDOUBLESTAR=35\nPLUSEQUAL=36\nMINEQUAL=37\nSTAREQUAL=38\nSLASHEQUAL=39\nPERCENTEQUAL=40\nAMPEREQUAL=41\nVBAREQUAL=42\nCIRCUMFLEXEQUAL=43\nLEFTSHIFTEQUAL=44\nRIGHTSHIFTEQUAL=45\nDOUBLESTAREQUAL=46\nDOUBLESLASH=47\nDOUBLESLASHEQUAL=48\nAT=49\nATEQUAL=50\nRARROW=51\nELLIPSIS=52\n\nOP=53\nERRORTOKEN=54\n\nCOMMENT=55\nNL=56\nENCODING=57\nN_TOKENS=58\n\nNT_OFFSET=256\n\n\ntok_name={value:name\nfor name,value in globals().items()\nif isinstance(value,int)and not name.startswith('_')}\n__all__.extend(tok_name.values())\n\ndef ISTERMINAL(x):\n return x <NT_OFFSET\n \ndef ISNONTERMINAL(x):\n return x >=NT_OFFSET\n \ndef ISEOF(x):\n return x ==ENDMARKER\n \n \ndef _main():\n import re\n import sys\n args=sys.argv[1:]\n inFileName=args and args[0]or \"Include/token.h\"\n outFileName=\"Lib/token.py\"\n if len(args)>1:\n outFileName=args[1]\n try :\n fp=open(inFileName)\n except OSError as err:\n sys.stdout.write(\"I/O error: %s\\n\"%str(err))\n sys.exit(1)\n with fp:\n lines=fp.read().split(\"\\n\")\n prog=re.compile(\n r\"#define[ \\t][ \\t]*([A-Z0-9][A-Z0-9_]*)[ \\t][ \\t]*([0-9][0-9]*)\",\n re.IGNORECASE)\n comment_regex=re.compile(\n r\"^\\s*/\\*\\s*(.+?)\\s*\\*/\\s*$\",\n re.IGNORECASE)\n \n tokens={}\n prev_val=None\n for line in lines:\n match=prog.match(line)\n if match:\n name,val=match.group(1,2)\n val=int(val)\n tokens[val]={'token':name}\n prev_val=val\n else :\n comment_match=comment_regex.match(line)\n if comment_match and prev_val is not None :\n comment=comment_match.group(1)\n tokens[prev_val]['comment']=comment\n keys=sorted(tokens.keys())\n \n try :\n fp=open(outFileName)\n except OSError as err:\n sys.stderr.write(\"I/O error: %s\\n\"%str(err))\n sys.exit(2)\n with fp:\n format=fp.read().split(\"\\n\")\n try :\n start=format.index(\"#--start constants--\")+1\n end=format.index(\"#--end constants--\")\n except ValueError:\n sys.stderr.write(\"target does not contain format markers\")\n sys.exit(3)\n lines=[]\n for key in keys:\n lines.append(\"%s = %d\"%(tokens[key][\"token\"],key))\n if \"comment\"in tokens[key]:\n lines.append(\"# %s\"%tokens[key][\"comment\"])\n format[start:end]=lines\n try :\n fp=open(outFileName,'w')\n except OSError as err:\n sys.stderr.write(\"I/O error: %s\\n\"%str(err))\n sys.exit(4)\n with fp:\n fp.write(\"\\n\".join(format))\n \n \nif __name__ ==\"__main__\":\n _main()\n", ["re", "sys"]], "email.parser": [".py", "\n\n\n\n\"\"\"A parser of RFC 2822 and MIME email messages.\"\"\"\n\n__all__=['Parser','HeaderParser','BytesParser','BytesHeaderParser',\n'FeedParser','BytesFeedParser']\n\nfrom io import StringIO,TextIOWrapper\n\nfrom email.feedparser import FeedParser,BytesFeedParser\nfrom email._policybase import compat32\n\n\n\nclass Parser:\n def __init__(self,_class=None ,*,policy=compat32):\n ''\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n \n self._class=_class\n self.policy=policy\n \n def parse(self,fp,headersonly=False ):\n ''\n\n\n\n\n\n \n feedparser=FeedParser(self._class,policy=self.policy)\n if headersonly:\n feedparser._set_headersonly()\n while True :\n data=fp.read(8192)\n if not data:\n break\n feedparser.feed(data)\n return feedparser.close()\n \n def parsestr(self,text,headersonly=False ):\n ''\n\n\n\n\n\n \n return self.parse(StringIO(text),headersonly=headersonly)\n \n \n \nclass HeaderParser(Parser):\n def parse(self,fp,headersonly=True ):\n return Parser.parse(self,fp,True )\n \n def parsestr(self,text,headersonly=True ):\n return Parser.parsestr(self,text,True )\n \n \nclass BytesParser:\n\n def __init__(self,*args,**kw):\n ''\n\n\n\n\n\n\n\n\n\n\n\n\n\n \n self.parser=Parser(*args,**kw)\n \n def parse(self,fp,headersonly=False ):\n ''\n\n\n\n\n\n \n fp=TextIOWrapper(fp,encoding='ascii',errors='surrogateescape')\n try :\n return self.parser.parse(fp,headersonly)\n finally :\n fp.detach()\n \n \n def parsebytes(self,text,headersonly=False ):\n ''\n\n\n\n\n\n \n text=text.decode('ASCII',errors='surrogateescape')\n return self.parser.parsestr(text,headersonly)\n \n \nclass BytesHeaderParser(BytesParser):\n def parse(self,fp,headersonly=True ):\n return BytesParser.parse(self,fp,headersonly=True )\n \n def parsebytes(self,text,headersonly=True ):\n return BytesParser.parsebytes(self,text,headersonly=True )\n", ["email._policybase", "email.feedparser", "io"]], "email": [".py", "\n\n\n\n\"\"\"A package for parsing, handling, and generating email messages.\"\"\"\n\n__all__=[\n'base64mime',\n'charset',\n'encoders',\n'errors',\n'feedparser',\n'generator',\n'header',\n'iterators',\n'message',\n'message_from_file',\n'message_from_binary_file',\n'message_from_string',\n'message_from_bytes',\n'mime',\n'parser',\n'quoprimime',\n'utils',\n]\n\n\n\n\n\ndef message_from_string(s,*args,**kws):\n ''\n\n\n \n from email.parser import Parser\n return Parser(*args,**kws).parsestr(s)\n \ndef message_from_bytes(s,*args,**kws):\n ''\n\n\n \n from email.parser import BytesParser\n return BytesParser(*args,**kws).parsebytes(s)\n \ndef message_from_file(fp,*args,**kws):\n ''\n\n\n \n from email.parser import Parser\n return Parser(*args,**kws).parse(fp)\n \ndef message_from_binary_file(fp,*args,**kws):\n ''\n\n\n \n from email.parser import BytesParser\n return BytesParser(*args,**kws).parse(fp)\n", ["email.parser"], 1], "getopt": [".py", "''\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n__all__=[\"GetoptError\",\"error\",\"getopt\",\"gnu_getopt\"]\n\nimport os\ntry :\n from gettext import gettext as _\nexcept ImportError:\n\n def _(s):return s\n \nclass GetoptError(Exception):\n opt=''\n msg=''\n def __init__(self,msg,opt=''):\n self.msg=msg\n self.opt=opt\n Exception.__init__(self,msg,opt)\n \n def __str__(self):\n return self.msg\n \nerror=GetoptError\n\ndef getopt(args,shortopts,longopts=[]):\n ''\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n \n \n opts=[]\n if type(longopts)==type(\"\"):\n longopts=[longopts]\n else :\n longopts=list(longopts)\n while args and args[0].startswith('-')and args[0]!='-':\n if args[0]=='--':\n args=args[1:]\n break\n if args[0].startswith('--'):\n opts,args=do_longs(opts,args[0][2:],longopts,args[1:])\n else :\n opts,args=do_shorts(opts,args[0][1:],shortopts,args[1:])\n \n return opts,args\n \ndef gnu_getopt(args,shortopts,longopts=[]):\n ''\n\n\n\n\n\n\n\n\n\n\n\n \n \n opts=[]\n prog_args=[]\n if isinstance(longopts,str):\n longopts=[longopts]\n else :\n longopts=list(longopts)\n \n \n if shortopts.startswith('+'):\n shortopts=shortopts[1:]\n all_options_first=True\n elif os.environ.get(\"POSIXLY_CORRECT\"):\n all_options_first=True\n else :\n all_options_first=False\n \n while args:\n if args[0]=='--':\n prog_args +=args[1:]\n break\n \n if args[0][:2]=='--':\n opts,args=do_longs(opts,args[0][2:],longopts,args[1:])\n elif args[0][:1]=='-'and args[0]!='-':\n opts,args=do_shorts(opts,args[0][1:],shortopts,args[1:])\n else :\n if all_options_first:\n prog_args +=args\n break\n else :\n prog_args.append(args[0])\n args=args[1:]\n \n return opts,prog_args\n \ndef do_longs(opts,opt,longopts,args):\n try :\n i=opt.index('=')\n except ValueError:\n optarg=None\n else :\n opt,optarg=opt[:i],opt[i+1:]\n \n has_arg,opt=long_has_args(opt,longopts)\n if has_arg:\n if optarg is None :\n if not args:\n raise GetoptError(_('option --%s requires argument')%opt,opt)\n optarg,args=args[0],args[1:]\n elif optarg is not None :\n raise GetoptError(_('option --%s must not have an argument')%opt,opt)\n opts.append(('--'+opt,optarg or ''))\n return opts,args\n \n \n \n \ndef long_has_args(opt,longopts):\n possibilities=[o for o in longopts if o.startswith(opt)]\n if not possibilities:\n raise GetoptError(_('option --%s not recognized')%opt,opt)\n \n if opt in possibilities:\n return False ,opt\n elif opt+'='in possibilities:\n return True ,opt\n \n if len(possibilities)>1:\n \n \n raise GetoptError(_('option --%s not a unique prefix')%opt,opt)\n assert len(possibilities)==1\n unique_match=possibilities[0]\n has_arg=unique_match.endswith('=')\n if has_arg:\n unique_match=unique_match[:-1]\n return has_arg,unique_match\n \ndef do_shorts(opts,optstring,shortopts,args):\n while optstring !='':\n opt,optstring=optstring[0],optstring[1:]\n if short_has_arg(opt,shortopts):\n if optstring =='':\n if not args:\n raise GetoptError(_('option -%s requires argument')%opt,\n opt)\n optstring,args=args[0],args[1:]\n optarg,optstring=optstring,''\n else :\n optarg=''\n opts.append(('-'+opt,optarg))\n return opts,args\n \ndef short_has_arg(opt,shortopts):\n for i in range(len(shortopts)):\n if opt ==shortopts[i]!=':':\n return shortopts.startswith(':',i+1)\n raise GetoptError(_('option -%s not recognized')%opt,opt)\n \nif __name__ =='__main__':\n import sys\n print(getopt(sys.argv[1:],\"a:b\",[\"alpha=\",\"beta\"]))\n", ["gettext", "os", "sys"]], "typing": [".py", "''\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\nimport abc\nfrom abc import abstractmethod,abstractproperty\nimport collections\nimport collections.abc\nimport contextlib\nimport functools\nimport operator\nimport re as stdlib_re\nimport sys\nimport types\nfrom types import WrapperDescriptorType,MethodWrapperType,MethodDescriptorType\n\n\n__all__=[\n\n'Any',\n'Callable',\n'ClassVar',\n'Generic',\n'Optional',\n'Tuple',\n'Type',\n'TypeVar',\n'Union',\n\n\n'AbstractSet',\n'ByteString',\n'Container',\n'ContextManager',\n'Hashable',\n'ItemsView',\n'Iterable',\n'Iterator',\n'KeysView',\n'Mapping',\n'MappingView',\n'MutableMapping',\n'MutableSequence',\n'MutableSet',\n'Sequence',\n'Sized',\n'ValuesView',\n'Awaitable',\n'AsyncIterator',\n'AsyncIterable',\n'Coroutine',\n'Collection',\n'AsyncGenerator',\n'AsyncContextManager',\n\n\n'Reversible',\n'SupportsAbs',\n'SupportsBytes',\n'SupportsComplex',\n'SupportsFloat',\n'SupportsInt',\n'SupportsRound',\n\n\n'Counter',\n'Deque',\n'Dict',\n'DefaultDict',\n'List',\n'Set',\n'FrozenSet',\n'NamedTuple',\n'Generator',\n\n\n'AnyStr',\n'cast',\n'get_type_hints',\n'NewType',\n'no_type_check',\n'no_type_check_decorator',\n'NoReturn',\n'overload',\n'Text',\n'TYPE_CHECKING',\n]\n\n\n\n\n\n\ndef _type_check(arg,msg,is_argument=True ):\n ''\n\n\n\n\n\n\n\n\n\n \n invalid_generic_forms=(Generic,_Protocol)\n if is_argument:\n invalid_generic_forms=invalid_generic_forms+(ClassVar,)\n \n if arg is None :\n return type(None )\n if isinstance(arg,str):\n return ForwardRef(arg)\n if (isinstance(arg,_GenericAlias)and\n arg.__origin__ in invalid_generic_forms):\n raise TypeError(f\"{arg} is not valid as type argument\")\n if (isinstance(arg,_SpecialForm)and arg is not Any or\n arg in (Generic,_Protocol)):\n raise TypeError(f\"Plain {arg} is not valid as type argument\")\n if isinstance(arg,(type,TypeVar,ForwardRef)):\n return arg\n if not callable(arg):\n raise TypeError(f\"{msg} Got {arg!r:.100}.\")\n return arg\n \n \ndef _type_repr(obj):\n ''\n\n\n\n\n\n \n if isinstance(obj,type):\n if obj.__module__ =='builtins':\n return obj.__qualname__\n return f'{obj.__module__}.{obj.__qualname__}'\n if obj is ...:\n return ('...')\n if isinstance(obj,types.FunctionType):\n return obj.__name__\n return repr(obj)\n \n \ndef _collect_type_vars(types):\n ''\n\n\n\n \n tvars=[]\n for t in types:\n if isinstance(t,TypeVar)and t not in tvars:\n tvars.append(t)\n if isinstance(t,_GenericAlias)and not t._special:\n tvars.extend([t for t in t.__parameters__ if t not in tvars])\n return tuple(tvars)\n \n \ndef _subs_tvars(tp,tvars,subs):\n ''\n\n \n if not isinstance(tp,_GenericAlias):\n return tp\n new_args=list(tp.__args__)\n for a,arg in enumerate(tp.__args__):\n if isinstance(arg,TypeVar):\n for i,tvar in enumerate(tvars):\n if arg ==tvar:\n new_args[a]=subs[i]\n else :\n new_args[a]=_subs_tvars(arg,tvars,subs)\n if tp.__origin__ is Union:\n return Union[tuple(new_args)]\n return tp.copy_with(tuple(new_args))\n \n \ndef _check_generic(cls,parameters):\n ''\n\n \n if not cls.__parameters__:\n raise TypeError(f\"{cls} is not a generic class\")\n alen=len(parameters)\n elen=len(cls.__parameters__)\n if alen !=elen:\n raise TypeError(f\"Too {'many' if alen > elen else 'few'} parameters for {cls};\"\n f\" actual {alen}, expected {elen}\")\n \n \ndef _remove_dups_flatten(parameters):\n ''\n\n \n \n params=[]\n for p in parameters:\n if isinstance(p,_GenericAlias)and p.__origin__ is Union:\n params.extend(p.__args__)\n elif isinstance(p,tuple)and len(p)>0 and p[0]is Union:\n params.extend(p[1:])\n else :\n params.append(p)\n \n all_params=set(params)\n if len(all_params)<len(params):\n new_params=[]\n for t in params:\n if t in all_params:\n new_params.append(t)\n all_params.remove(t)\n params=new_params\n assert not all_params,all_params\n return tuple(params)\n \n \n_cleanups=[]\n\n\ndef _tp_cache(func):\n ''\n\n \n cached=functools.lru_cache()(func)\n _cleanups.append(cached.cache_clear)\n \n @functools.wraps(func)\n def inner(*args,**kwds):\n try :\n return cached(*args,**kwds)\n except TypeError:\n pass\n return func(*args,**kwds)\n return inner\n \n \ndef _eval_type(t,globalns,localns):\n ''\n\n \n if isinstance(t,ForwardRef):\n return t._evaluate(globalns,localns)\n if isinstance(t,_GenericAlias):\n ev_args=tuple(_eval_type(a,globalns,localns)for a in t.__args__)\n if ev_args ==t.__args__:\n return t\n res=t.copy_with(ev_args)\n res._special=t._special\n return res\n return t\n \n \nclass _Final:\n ''\n \n __slots__=('__weakref__',)\n \n def __init_subclass__(self,*args,**kwds):\n if '_root'not in kwds:\n raise TypeError(\"Cannot subclass special typing classes\")\n \nclass _Immutable:\n ''\n \n def __copy__(self):\n return self\n \n def __deepcopy__(self,memo):\n return self\n \n \nclass _SpecialForm(_Final,_Immutable,_root=True ):\n ''\n\n \n \n __slots__=('_name','_doc')\n \n def __new__(cls,*args,**kwds):\n ''\n\n\n\n \n if (len(args)==3 and\n isinstance(args[0],str)and\n isinstance(args[1],tuple)):\n \n raise TypeError(f\"Cannot subclass {cls!r}\")\n return super().__new__(cls)\n \n def __init__(self,name,doc):\n self._name=name\n self._doc=doc\n \n def __eq__(self,other):\n if not isinstance(other,_SpecialForm):\n return NotImplemented\n return self._name ==other._name\n \n def __hash__(self):\n return hash((self._name,))\n \n def __repr__(self):\n return 'typing.'+self._name\n \n def __reduce__(self):\n return self._name\n \n def __call__(self,*args,**kwds):\n raise TypeError(f\"Cannot instantiate {self!r}\")\n \n def __instancecheck__(self,obj):\n raise TypeError(f\"{self} cannot be used with isinstance()\")\n \n def __subclasscheck__(self,cls):\n raise TypeError(f\"{self} cannot be used with issubclass()\")\n \n @_tp_cache\n def __getitem__(self,parameters):\n if self._name =='ClassVar':\n item=_type_check(parameters,'ClassVar accepts only single type.')\n return _GenericAlias(self,(item,))\n if self._name =='Union':\n if parameters ==():\n raise TypeError(\"Cannot take a Union of no types.\")\n if not isinstance(parameters,tuple):\n parameters=(parameters,)\n msg=\"Union[arg, ...]: each arg must be a type.\"\n parameters=tuple(_type_check(p,msg)for p in parameters)\n parameters=_remove_dups_flatten(parameters)\n if len(parameters)==1:\n return parameters[0]\n return _GenericAlias(self,parameters)\n if self._name =='Optional':\n arg=_type_check(parameters,\"Optional[t] requires a single type.\")\n return Union[arg,type(None )]\n raise TypeError(f\"{self} is not subscriptable\")\n \n \nAny=_SpecialForm('Any',doc=\n\"\"\"Special type indicating an unconstrained type.\n\n - Any is compatible with every type.\n - Any assumed to have all methods.\n - All values assumed to be instances of Any.\n\n Note that all the above statements are true from the point of view of\n static type checkers. At runtime, Any should not be used with instance\n or class checks.\n \"\"\")\n\nNoReturn=_SpecialForm('NoReturn',doc=\n\"\"\"Special type indicating functions that never return.\n Example::\n\n from typing import NoReturn\n\n def stop() -> NoReturn:\n raise Exception('no way')\n\n This type is invalid in other positions, e.g., ``List[NoReturn]``\n will fail in static type checkers.\n \"\"\")\n\nClassVar=_SpecialForm('ClassVar',doc=\n\"\"\"Special type construct to mark class variables.\n\n An annotation wrapped in ClassVar indicates that a given\n attribute is intended to be used as a class variable and\n should not be set on instances of that class. Usage::\n\n class Starship:\n stats: ClassVar[Dict[str, int]] = {} # class variable\n damage: int = 10 # instance variable\n\n ClassVar accepts only types and cannot be further subscribed.\n\n Note that ClassVar is not a class itself, and should not\n be used with isinstance() or issubclass().\n \"\"\")\n\nUnion=_SpecialForm('Union',doc=\n\"\"\"Union type; Union[X, Y] means either X or Y.\n\n To define a union, use e.g. Union[int, str]. Details:\n - The arguments must be types and there must be at least one.\n - None as an argument is a special case and is replaced by\n type(None).\n - Unions of unions are flattened, e.g.::\n\n Union[Union[int, str], float] == Union[int, str, float]\n\n - Unions of a single argument vanish, e.g.::\n\n Union[int] == int # The constructor actually returns int\n\n - Redundant arguments are skipped, e.g.::\n\n Union[int, str, int] == Union[int, str]\n\n - When comparing unions, the argument order is ignored, e.g.::\n\n Union[int, str] == Union[str, int]\n\n - You cannot subclass or instantiate a union.\n - You can use Optional[X] as a shorthand for Union[X, None].\n \"\"\")\n\nOptional=_SpecialForm('Optional',doc=\n\"\"\"Optional type.\n\n Optional[X] is equivalent to Union[X, None].\n \"\"\")\n\n\nclass ForwardRef(_Final,_root=True ):\n ''\n \n __slots__=('__forward_arg__','__forward_code__',\n '__forward_evaluated__','__forward_value__',\n '__forward_is_argument__')\n \n def __init__(self,arg,is_argument=True ):\n if not isinstance(arg,str):\n raise TypeError(f\"Forward reference must be a string -- got {arg!r}\")\n try :\n code=compile(arg,'<string>','eval')\n except SyntaxError:\n raise SyntaxError(f\"Forward reference must be an expression -- got {arg!r}\")\n self.__forward_arg__=arg\n self.__forward_code__=code\n self.__forward_evaluated__=False\n self.__forward_value__=None\n self.__forward_is_argument__=is_argument\n \n def _evaluate(self,globalns,localns):\n if not self.__forward_evaluated__ or localns is not globalns:\n if globalns is None and localns is None :\n globalns=localns={}\n elif globalns is None :\n globalns=localns\n elif localns is None :\n localns=globalns\n self.__forward_value__=_type_check(\n eval(self.__forward_code__,globalns,localns),\n \"Forward references must evaluate to types.\",\n is_argument=self.__forward_is_argument__)\n self.__forward_evaluated__=True\n return self.__forward_value__\n \n def __eq__(self,other):\n if not isinstance(other,ForwardRef):\n return NotImplemented\n return (self.__forward_arg__ ==other.__forward_arg__ and\n self.__forward_value__ ==other.__forward_value__)\n \n def __hash__(self):\n return hash((self.__forward_arg__,self.__forward_value__))\n \n def __repr__(self):\n return f'ForwardRef({self.__forward_arg__!r})'\n \n \nclass TypeVar(_Final,_Immutable,_root=True ):\n ''\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n \n \n __slots__=('__name__','__bound__','__constraints__',\n '__covariant__','__contravariant__')\n \n def __init__(self,name,*constraints,bound=None ,\n covariant=False ,contravariant=False ):\n self.__name__=name\n if covariant and contravariant:\n raise ValueError(\"Bivariant types are not supported.\")\n self.__covariant__=bool(covariant)\n self.__contravariant__=bool(contravariant)\n if constraints and bound is not None :\n raise TypeError(\"Constraints cannot be combined with bound=...\")\n if constraints and len(constraints)==1:\n raise TypeError(\"A single constraint is not allowed\")\n msg=\"TypeVar(name, constraint, ...): constraints must be types.\"\n self.__constraints__=tuple(_type_check(t,msg)for t in constraints)\n if bound:\n self.__bound__=_type_check(bound,\"Bound must be a type.\")\n else :\n self.__bound__=None\n def_mod=sys._getframe(1).f_globals['__name__']\n if def_mod !='typing':\n self.__module__=def_mod\n \n def __repr__(self):\n if self.__covariant__:\n prefix='+'\n elif self.__contravariant__:\n prefix='-'\n else :\n prefix='~'\n return prefix+self.__name__\n \n def __reduce__(self):\n return self.__name__\n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n_normalize_alias={'list':'List',\n'tuple':'Tuple',\n'dict':'Dict',\n'set':'Set',\n'frozenset':'FrozenSet',\n'deque':'Deque',\n'defaultdict':'DefaultDict',\n'type':'Type',\n'Set':'AbstractSet'}\n\ndef _is_dunder(attr):\n return attr.startswith('__')and attr.endswith('__')\n \n \nclass _GenericAlias(_Final,_root=True ):\n ''\n\n\n\n\n\n\n \n def __init__(self,origin,params,*,inst=True ,special=False ,name=None ):\n self._inst=inst\n self._special=special\n if special and name is None :\n orig_name=origin.__name__\n name=_normalize_alias.get(orig_name,orig_name)\n self._name=name\n if not isinstance(params,tuple):\n params=(params,)\n self.__origin__=origin\n self.__args__=tuple(...if a is _TypingEllipsis else\n ()if a is _TypingEmpty else\n a for a in params)\n self.__parameters__=_collect_type_vars(params)\n self.__slots__=None\n if not name:\n self.__module__=origin.__module__\n \n @_tp_cache\n def __getitem__(self,params):\n if self.__origin__ in (Generic,_Protocol):\n \n raise TypeError(f\"Cannot subscript already-subscripted {self}\")\n if not isinstance(params,tuple):\n params=(params,)\n msg=\"Parameters to generic types must be types.\"\n params=tuple(_type_check(p,msg)for p in params)\n _check_generic(self,params)\n return _subs_tvars(self,self.__parameters__,params)\n \n def copy_with(self,params):\n \n return _GenericAlias(self.__origin__,params,name=self._name,inst=self._inst)\n \n def __repr__(self):\n if (self._name !='Callable'or\n len(self.__args__)==2 and self.__args__[0]is Ellipsis):\n if self._name:\n name='typing.'+self._name\n else :\n name=_type_repr(self.__origin__)\n if not self._special:\n args=f'[{\", \".join([_type_repr(a) for a in self.__args__])}]'\n else :\n args=''\n return (f'{name}{args}')\n if self._special:\n return 'typing.Callable'\n return (f'typing.Callable'\n f'[[{\", \".join([_type_repr(a) for a in self.__args__[:-1]])}], '\n f'{_type_repr(self.__args__[-1])}]')\n \n def __eq__(self,other):\n if not isinstance(other,_GenericAlias):\n return NotImplemented\n if self.__origin__ !=other.__origin__:\n return False\n if self.__origin__ is Union and other.__origin__ is Union:\n return frozenset(self.__args__)==frozenset(other.__args__)\n return self.__args__ ==other.__args__\n \n def __hash__(self):\n if self.__origin__ is Union:\n return hash((Union,frozenset(self.__args__)))\n return hash((self.__origin__,self.__args__))\n \n def __call__(self,*args,**kwargs):\n if not self._inst:\n raise TypeError(f\"Type {self._name} cannot be instantiated; \"\n f\"use {self._name.lower()}() instead\")\n result=self.__origin__(*args,**kwargs)\n try :\n result.__orig_class__=self\n except AttributeError:\n pass\n return result\n \n def __mro_entries__(self,bases):\n if self._name:\n res=[]\n if self.__origin__ not in bases:\n res.append(self.__origin__)\n i=bases.index(self)\n if not any(isinstance(b,_GenericAlias)or issubclass(b,Generic)\n for b in bases[i+1:]):\n res.append(Generic)\n return tuple(res)\n if self.__origin__ is Generic:\n i=bases.index(self)\n for b in bases[i+1:]:\n if isinstance(b,_GenericAlias)and b is not self:\n return ()\n return (self.__origin__,)\n \n def __getattr__(self,attr):\n \n \n if '__origin__'in self.__dict__ and not _is_dunder(attr):\n return getattr(self.__origin__,attr)\n raise AttributeError(attr)\n \n def __setattr__(self,attr,val):\n if _is_dunder(attr)or attr in ('_name','_inst','_special'):\n super().__setattr__(attr,val)\n else :\n setattr(self.__origin__,attr,val)\n \n def __instancecheck__(self,obj):\n return self.__subclasscheck__(type(obj))\n \n def __subclasscheck__(self,cls):\n if self._special:\n if not isinstance(cls,_GenericAlias):\n return issubclass(cls,self.__origin__)\n if cls._special:\n return issubclass(cls.__origin__,self.__origin__)\n raise TypeError(\"Subscripted generics cannot be used with\"\n \" class and instance checks\")\n \n def __reduce__(self):\n if self._special:\n return self._name\n \n if self._name:\n origin=globals()[self._name]\n else :\n origin=self.__origin__\n if (origin is Callable and\n not (len(self.__args__)==2 and self.__args__[0]is Ellipsis)):\n args=list(self.__args__[:-1]),self.__args__[-1]\n else :\n args=tuple(self.__args__)\n if len(args)==1 and not isinstance(args[0],tuple):\n args,=args\n return operator.getitem,(origin,args)\n \n \nclass _VariadicGenericAlias(_GenericAlias,_root=True ):\n ''\n\n \n def __getitem__(self,params):\n if self._name !='Callable'or not self._special:\n return self.__getitem_inner__(params)\n if not isinstance(params,tuple)or len(params)!=2:\n raise TypeError(\"Callable must be used as \"\n \"Callable[[arg, ...], result].\")\n args,result=params\n if args is Ellipsis:\n params=(Ellipsis,result)\n else :\n if not isinstance(args,list):\n raise TypeError(f\"Callable[args, result]: args must be a list.\"\n f\" Got {args}\")\n params=(tuple(args),result)\n return self.__getitem_inner__(params)\n \n @_tp_cache\n def __getitem_inner__(self,params):\n if self.__origin__ is tuple and self._special:\n if params ==():\n return self.copy_with((_TypingEmpty,))\n if not isinstance(params,tuple):\n params=(params,)\n if len(params)==2 and params[1]is ...:\n msg=\"Tuple[t, ...]: t must be a type.\"\n p=_type_check(params[0],msg)\n return self.copy_with((p,_TypingEllipsis))\n msg=\"Tuple[t0, t1, ...]: each t must be a type.\"\n params=tuple(_type_check(p,msg)for p in params)\n return self.copy_with(params)\n if self.__origin__ is collections.abc.Callable and self._special:\n args,result=params\n msg=\"Callable[args, result]: result must be a type.\"\n result=_type_check(result,msg)\n if args is Ellipsis:\n return self.copy_with((_TypingEllipsis,result))\n msg=\"Callable[[arg, ...], result]: each arg must be a type.\"\n args=tuple(_type_check(arg,msg)for arg in args)\n params=args+(result,)\n return self.copy_with(params)\n return super().__getitem__(params)\n \n \nclass Generic:\n ''\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n \n __slots__=()\n \n def __new__(cls,*args,**kwds):\n if cls is Generic:\n raise TypeError(\"Type Generic cannot be instantiated; \"\n \"it can be used only as a base class\")\n if super().__new__ is object.__new__ and cls.__init__ is not object.__init__:\n obj=super().__new__(cls)\n else :\n obj=super().__new__(cls,*args,**kwds)\n return obj\n \n @_tp_cache\n def __class_getitem__(cls,params):\n if not isinstance(params,tuple):\n params=(params,)\n if not params and cls is not Tuple:\n raise TypeError(\n f\"Parameter list to {cls.__qualname__}[...] cannot be empty\")\n msg=\"Parameters to generic types must be types.\"\n params=tuple(_type_check(p,msg)for p in params)\n if cls is Generic:\n \n if not all(isinstance(p,TypeVar)for p in params):\n raise TypeError(\n \"Parameters to Generic[...] must all be type variables\")\n if len(set(params))!=len(params):\n raise TypeError(\n \"Parameters to Generic[...] must all be unique\")\n elif cls is _Protocol:\n \n pass\n else :\n \n _check_generic(cls,params)\n return _GenericAlias(cls,params)\n \n def __init_subclass__(cls,*args,**kwargs):\n super().__init_subclass__(*args,**kwargs)\n tvars=[]\n if '__orig_bases__'in cls.__dict__:\n error=Generic in cls.__orig_bases__\n else :\n error=Generic in cls.__bases__ and cls.__name__ !='_Protocol'\n if error:\n raise TypeError(\"Cannot inherit from plain Generic\")\n if '__orig_bases__'in cls.__dict__:\n tvars=_collect_type_vars(cls.__orig_bases__)\n \n \n \n \n \n gvars=None\n for base in cls.__orig_bases__:\n if (isinstance(base,_GenericAlias)and\n base.__origin__ is Generic):\n if gvars is not None :\n raise TypeError(\n \"Cannot inherit from Generic[...] multiple types.\")\n gvars=base.__parameters__\n if gvars is None :\n gvars=tvars\n else :\n tvarset=set(tvars)\n gvarset=set(gvars)\n if not tvarset <=gvarset:\n s_vars=', '.join(str(t)for t in tvars if t not in gvarset)\n s_args=', '.join(str(g)for g in gvars)\n raise TypeError(f\"Some type variables ({s_vars}) are\"\n f\" not listed in Generic[{s_args}]\")\n tvars=gvars\n cls.__parameters__=tuple(tvars)\n \n \nclass _TypingEmpty:\n ''\n\n\n \n \n \nclass _TypingEllipsis:\n ''\n \n \ndef cast(typ,val):\n ''\n\n\n\n\n\n \n return val\n \n \ndef _get_defaults(func):\n ''\n try :\n code=func.__code__\n except AttributeError:\n \n return {}\n pos_count=code.co_argcount\n arg_names=code.co_varnames\n arg_names=arg_names[:pos_count]\n defaults=func.__defaults__ or ()\n kwdefaults=func.__kwdefaults__\n res=dict(kwdefaults)if kwdefaults else {}\n pos_offset=pos_count -len(defaults)\n for name,value in zip(arg_names[pos_offset:],defaults):\n assert name not in res\n res[name]=value\n return res\n \n \n_allowed_types=(types.FunctionType,types.BuiltinFunctionType,\ntypes.MethodType,types.ModuleType,\nWrapperDescriptorType,MethodWrapperType,MethodDescriptorType)\n\n\ndef get_type_hints(obj,globalns=None ,localns=None ):\n ''\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n \n \n if getattr(obj,'__no_type_check__',None ):\n return {}\n \n if isinstance(obj,type):\n hints={}\n for base in reversed(obj.__mro__):\n if globalns is None :\n base_globals=sys.modules[base.__module__].__dict__\n else :\n base_globals=globalns\n ann=base.__dict__.get('__annotations__',{})\n for name,value in ann.items():\n if value is None :\n value=type(None )\n if isinstance(value,str):\n value=ForwardRef(value,is_argument=False )\n value=_eval_type(value,base_globals,localns)\n hints[name]=value\n return hints\n \n if globalns is None :\n if isinstance(obj,types.ModuleType):\n globalns=obj.__dict__\n else :\n globalns=getattr(obj,'__globals__',{})\n if localns is None :\n localns=globalns\n elif localns is None :\n localns=globalns\n hints=getattr(obj,'__annotations__',None )\n if hints is None :\n \n if isinstance(obj,_allowed_types):\n return {}\n else :\n raise TypeError('{!r} is not a module, class, method, '\n 'or function.'.format(obj))\n defaults=_get_defaults(obj)\n hints=dict(hints)\n for name,value in hints.items():\n if value is None :\n value=type(None )\n if isinstance(value,str):\n value=ForwardRef(value)\n value=_eval_type(value,globalns,localns)\n if name in defaults and defaults[name]is None :\n value=Optional[value]\n hints[name]=value\n return hints\n \n \ndef no_type_check(arg):\n ''\n\n\n\n\n\n\n \n if isinstance(arg,type):\n arg_attrs=arg.__dict__.copy()\n for attr,val in arg.__dict__.items():\n if val in arg.__bases__+(arg,):\n arg_attrs.pop(attr)\n for obj in arg_attrs.values():\n if isinstance(obj,types.FunctionType):\n obj.__no_type_check__=True\n if isinstance(obj,type):\n no_type_check(obj)\n try :\n arg.__no_type_check__=True\n except TypeError:\n pass\n return arg\n \n \ndef no_type_check_decorator(decorator):\n ''\n\n\n\n \n \n @functools.wraps(decorator)\n def wrapped_decorator(*args,**kwds):\n func=decorator(*args,**kwds)\n func=no_type_check(func)\n return func\n \n return wrapped_decorator\n \n \ndef _overload_dummy(*args,**kwds):\n ''\n raise NotImplementedError(\n \"You should not call an overloaded function. \"\n \"A series of @overload-decorated functions \"\n \"outside a stub module should always be followed \"\n \"by an implementation that is not @overload-ed.\")\n \n \ndef overload(func):\n ''\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n \n return _overload_dummy\n \n \nclass _ProtocolMeta(type):\n ''\n\n\n\n \n \n def __instancecheck__(self,obj):\n if _Protocol not in self.__bases__:\n return super().__instancecheck__(obj)\n raise TypeError(\"Protocols cannot be used with isinstance().\")\n \n def __subclasscheck__(self,cls):\n if not self._is_protocol:\n \n return NotImplemented\n \n if self is _Protocol:\n \n return True\n \n \n attrs=self._get_protocol_attrs()\n \n for attr in attrs:\n if not any(attr in d.__dict__ for d in cls.__mro__):\n return False\n return True\n \n def _get_protocol_attrs(self):\n \n protocol_bases=[]\n for c in self.__mro__:\n if getattr(c,'_is_protocol',False )and c.__name__ !='_Protocol':\n protocol_bases.append(c)\n \n \n attrs=set()\n for base in protocol_bases:\n for attr in base.__dict__.keys():\n \n for c in self.__mro__:\n if (c is not base and attr in c.__dict__ and\n not getattr(c,'_is_protocol',False )):\n break\n else :\n if (not attr.startswith('_abc_')and\n attr !='__abstractmethods__'and\n attr !='__annotations__'and\n attr !='__weakref__'and\n attr !='_is_protocol'and\n attr !='_gorg'and\n attr !='__dict__'and\n attr !='__args__'and\n attr !='__slots__'and\n attr !='_get_protocol_attrs'and\n attr !='__next_in_mro__'and\n attr !='__parameters__'and\n attr !='__origin__'and\n attr !='__orig_bases__'and\n attr !='__extra__'and\n attr !='__tree_hash__'and\n attr !='__module__'):\n attrs.add(attr)\n \n return attrs\n \n \nclass _Protocol(Generic,metaclass=_ProtocolMeta):\n ''\n\n\n\n\n \n \n __slots__=()\n \n _is_protocol=True\n \n def __class_getitem__(cls,params):\n return super().__class_getitem__(params)\n \n \n \n \nT=TypeVar('T')\nKT=TypeVar('KT')\nVT=TypeVar('VT')\nT_co=TypeVar('T_co',covariant=True )\nV_co=TypeVar('V_co',covariant=True )\nVT_co=TypeVar('VT_co',covariant=True )\nT_contra=TypeVar('T_contra',contravariant=True )\n\nCT_co=TypeVar('CT_co',covariant=True ,bound=type)\n\n\n\nAnyStr=TypeVar('AnyStr',bytes,str)\n\n\n\ndef _alias(origin,params,inst=True ):\n return _GenericAlias(origin,params,special=True ,inst=inst)\n \nHashable=_alias(collections.abc.Hashable,())\nAwaitable=_alias(collections.abc.Awaitable,T_co)\nCoroutine=_alias(collections.abc.Coroutine,(T_co,T_contra,V_co))\nAsyncIterable=_alias(collections.abc.AsyncIterable,T_co)\nAsyncIterator=_alias(collections.abc.AsyncIterator,T_co)\nIterable=_alias(collections.abc.Iterable,T_co)\nIterator=_alias(collections.abc.Iterator,T_co)\nReversible=_alias(collections.abc.Reversible,T_co)\nSized=_alias(collections.abc.Sized,())\nContainer=_alias(collections.abc.Container,T_co)\nCollection=_alias(collections.abc.Collection,T_co)\nCallable=_VariadicGenericAlias(collections.abc.Callable,(),special=True )\nCallable.__doc__=\\\n\"\"\"Callable type; Callable[[int], str] is a function of (int) -> str.\n\n The subscription syntax must always be used with exactly two\n values: the argument list and the return type. The argument list\n must be a list of types or ellipsis; the return type must be a single type.\n\n There is no syntax to indicate optional or keyword arguments,\n such function types are rarely used as callback types.\n \"\"\"\nAbstractSet=_alias(collections.abc.Set,T_co)\nMutableSet=_alias(collections.abc.MutableSet,T)\n\nMapping=_alias(collections.abc.Mapping,(KT,VT_co))\nMutableMapping=_alias(collections.abc.MutableMapping,(KT,VT))\nSequence=_alias(collections.abc.Sequence,T_co)\nMutableSequence=_alias(collections.abc.MutableSequence,T)\nByteString=_alias(collections.abc.ByteString,())\nTuple=_VariadicGenericAlias(tuple,(),inst=False ,special=True )\nTuple.__doc__=\\\n\"\"\"Tuple type; Tuple[X, Y] is the cross-product type of X and Y.\n\n Example: Tuple[T1, T2] is a tuple of two elements corresponding\n to type variables T1 and T2. Tuple[int, float, str] is a tuple\n of an int, a float and a string.\n\n To specify a variable-length tuple of homogeneous type, use Tuple[T, ...].\n \"\"\"\nList=_alias(list,T,inst=False )\nDeque=_alias(collections.deque,T)\nSet=_alias(set,T,inst=False )\nFrozenSet=_alias(frozenset,T_co,inst=False )\nMappingView=_alias(collections.abc.MappingView,T_co)\nKeysView=_alias(collections.abc.KeysView,KT)\nItemsView=_alias(collections.abc.ItemsView,(KT,VT_co))\nValuesView=_alias(collections.abc.ValuesView,VT_co)\nContextManager=_alias(contextlib.AbstractContextManager,T_co)\nAsyncContextManager=_alias(contextlib.AbstractAsyncContextManager,T_co)\nDict=_alias(dict,(KT,VT),inst=False )\nDefaultDict=_alias(collections.defaultdict,(KT,VT))\nCounter=_alias(collections.Counter,T)\nChainMap=_alias(collections.ChainMap,(KT,VT))\nGenerator=_alias(collections.abc.Generator,(T_co,T_contra,V_co))\nAsyncGenerator=_alias(collections.abc.AsyncGenerator,(T_co,T_contra))\nType=_alias(type,CT_co,inst=False )\nType.__doc__=\\\n\"\"\"A special construct usable to annotate class objects.\n\n For example, suppose we have the following classes::\n\n class User: ... # Abstract base for User classes\n class BasicUser(User): ...\n class ProUser(User): ...\n class TeamUser(User): ...\n\n And a function that takes a class argument that's a subclass of\n User and returns an instance of the corresponding class::\n\n U = TypeVar('U', bound=User)\n def new_user(user_class: Type[U]) -> U:\n user = user_class()\n # (Here we could write the user object to a database)\n return user\n\n joe = new_user(BasicUser)\n\n At this point the type checker knows that joe has type BasicUser.\n \"\"\"\n\n\nclass SupportsInt(_Protocol):\n __slots__=()\n \n @abstractmethod\n def __int__(self)->int:\n pass\n \n \nclass SupportsFloat(_Protocol):\n __slots__=()\n \n @abstractmethod\n def __float__(self)->float:\n pass\n \n \nclass SupportsComplex(_Protocol):\n __slots__=()\n \n @abstractmethod\n def __complex__(self)->complex:\n pass\n \n \nclass SupportsBytes(_Protocol):\n __slots__=()\n \n @abstractmethod\n def __bytes__(self)->bytes:\n pass\n \n \nclass SupportsAbs(_Protocol[T_co]):\n __slots__=()\n \n @abstractmethod\n def __abs__(self)->T_co:\n pass\n \n \nclass SupportsRound(_Protocol[T_co]):\n __slots__=()\n \n @abstractmethod\n def __round__(self,ndigits:int=0)->T_co:\n pass\n \n \ndef _make_nmtuple(name,types):\n msg=\"NamedTuple('Name', [(f0, t0), (f1, t1), ...]); each t must be a type\"\n types=[(n,_type_check(t,msg))for n,t in types]\n nm_tpl=collections.namedtuple(name,[n for n,t in types])\n \n \n nm_tpl.__annotations__=nm_tpl._field_types=collections.OrderedDict(types)\n try :\n nm_tpl.__module__=sys._getframe(2).f_globals.get('__name__','__main__')\n except (AttributeError,ValueError):\n pass\n return nm_tpl\n \n \n \n_prohibited=('__new__','__init__','__slots__','__getnewargs__',\n'_fields','_field_defaults','_field_types',\n'_make','_replace','_asdict','_source')\n\n_special=('__module__','__name__','__qualname__','__annotations__')\n\n\nclass NamedTupleMeta(type):\n\n def __new__(cls,typename,bases,ns):\n if ns.get('_root',False ):\n return super().__new__(cls,typename,bases,ns)\n types=ns.get('__annotations__',{})\n nm_tpl=_make_nmtuple(typename,types.items())\n defaults=[]\n defaults_dict={}\n for field_name in types:\n if field_name in ns:\n default_value=ns[field_name]\n defaults.append(default_value)\n defaults_dict[field_name]=default_value\n elif defaults:\n raise TypeError(\"Non-default namedtuple field {field_name} cannot \"\n \"follow default field(s) {default_names}\"\n .format(field_name=field_name,\n default_names=', '.join(defaults_dict.keys())))\n nm_tpl.__new__.__annotations__=collections.OrderedDict(types)\n nm_tpl.__new__.__defaults__=tuple(defaults)\n nm_tpl._field_defaults=defaults_dict\n \n for key in ns:\n if key in _prohibited:\n raise AttributeError(\"Cannot overwrite NamedTuple attribute \"+key)\n elif key not in _special and key not in nm_tpl._fields:\n setattr(nm_tpl,key,ns[key])\n return nm_tpl\n \n \nclass NamedTuple(metaclass=NamedTupleMeta):\n ''\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n \n _root=True\n \n def __new__(self,typename,fields=None ,**kwargs):\n if fields is None :\n fields=kwargs.items()\n elif kwargs:\n raise TypeError(\"Either list of fields or keywords\"\n \" can be provided to NamedTuple, not both\")\n return _make_nmtuple(typename,fields)\n \n \ndef NewType(name,tp):\n ''\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n \n \n def new_type(x):\n return x\n \n new_type.__name__=name\n new_type.__supertype__=tp\n return new_type\n \n \n \nText=str\n\n\n\nTYPE_CHECKING=False\n\n\nclass IO(Generic[AnyStr]):\n ''\n\n\n\n\n\n\n\n\n\n \n \n __slots__=()\n \n @abstractproperty\n def mode(self)->str:\n pass\n \n @abstractproperty\n def name(self)->str:\n pass\n \n @abstractmethod\n def close(self)->None :\n pass\n \n @abstractmethod\n def closed(self)->bool:\n pass\n \n @abstractmethod\n def fileno(self)->int:\n pass\n \n @abstractmethod\n def flush(self)->None :\n pass\n \n @abstractmethod\n def isatty(self)->bool:\n pass\n \n @abstractmethod\n def read(self,n:int=-1)->AnyStr:\n pass\n \n @abstractmethod\n def readable(self)->bool:\n pass\n \n @abstractmethod\n def readline(self,limit:int=-1)->AnyStr:\n pass\n \n @abstractmethod\n def readlines(self,hint:int=-1)->List[AnyStr]:\n pass\n \n @abstractmethod\n def seek(self,offset:int,whence:int=0)->int:\n pass\n \n @abstractmethod\n def seekable(self)->bool:\n pass\n \n @abstractmethod\n def tell(self)->int:\n pass\n \n @abstractmethod\n def truncate(self,size:int=None )->int:\n pass\n \n @abstractmethod\n def writable(self)->bool:\n pass\n \n @abstractmethod\n def write(self,s:AnyStr)->int:\n pass\n \n @abstractmethod\n def writelines(self,lines:List[AnyStr])->None :\n pass\n \n @abstractmethod\n def __enter__(self)->'IO[AnyStr]':\n pass\n \n @abstractmethod\n def __exit__(self,type,value,traceback)->None :\n pass\n \n \nclass BinaryIO(IO[bytes]):\n ''\n \n __slots__=()\n \n @abstractmethod\n def write(self,s:Union[bytes,bytearray])->int:\n pass\n \n @abstractmethod\n def __enter__(self)->'BinaryIO':\n pass\n \n \nclass TextIO(IO[str]):\n ''\n \n __slots__=()\n \n @abstractproperty\n def buffer(self)->BinaryIO:\n pass\n \n @abstractproperty\n def encoding(self)->str:\n pass\n \n @abstractproperty\n def errors(self)->Optional[str]:\n pass\n \n @abstractproperty\n def line_buffering(self)->bool:\n pass\n \n @abstractproperty\n def newlines(self)->Any:\n pass\n \n @abstractmethod\n def __enter__(self)->'TextIO':\n pass\n \n \nclass io:\n ''\n \n __all__=['IO','TextIO','BinaryIO']\n IO=IO\n TextIO=TextIO\n BinaryIO=BinaryIO\n \n \nio.__name__=__name__+'.io'\nsys.modules[io.__name__]=io\n\nPattern=_alias(stdlib_re.Pattern,AnyStr)\nMatch=_alias(stdlib_re.Match,AnyStr)\n\nclass re:\n ''\n \n __all__=['Pattern','Match']\n Pattern=Pattern\n Match=Match\n \n \nre.__name__=__name__+'.re'\nsys.modules[re.__name__]=re\n", ["abc", "collections", "collections.abc", "contextlib", "functools", "operator", "re", "sys", "types"]], "signal": [".py", "''\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\nCTRL_BREAK_EVENT=1\nCTRL_C_EVENT=0\nNSIG=23\nSIGABRT=22\nSIGBREAK=21\nSIGFPE=8\nSIGILL=4\nSIGINT=2\nSIGSEGV=11\nSIGTERM=15\nSIG_DFL=0\nSIG_IGN=1\n\ndef signal(signalnum,handler):\n pass\n", []], "_base64": [".js", "var $module=(function($B){\n\nvar _b_ = $B.builtins,\n _keyStr = \"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=\"\n\nfunction make_alphabet(altchars){\n var alphabet = _keyStr\n if(altchars !== undefined && altchars !== _b_.None){\n // altchars is an instance of Python bytes\n var source = altchars.source\n alphabet = alphabet.substr(0,alphabet.length-3) +\n _b_.chr(source[0]) + _b_.chr(source[1]) + '='\n }\n return alphabet\n}\n\nvar Base64 = {\n error: function(){return 'binascii_error'},\n\n encode: function(bytes, altchars){\n\n var input = bytes.source,\n output = \"\",\n chr1, chr2, chr3, enc1, enc2, enc3, enc4\n var i = 0\n\n var alphabet = make_alphabet(altchars)\n\n while(i < input.length){\n\n chr1 = input[i++]\n chr2 = input[i++]\n chr3 = input[i++]\n\n enc1 = chr1 >> 2\n enc2 = ((chr1 & 3) << 4) | (chr2 >> 4)\n enc3 = ((chr2 & 15) << 2) | (chr3 >> 6)\n enc4 = chr3 & 63\n\n if(isNaN(chr2)){\n enc3 = enc4 = 64\n }else if(isNaN(chr3)){\n enc4 = 64\n }\n\n output = output + alphabet.charAt(enc1) +\n alphabet.charAt(enc2) +\n alphabet.charAt(enc3) +\n alphabet.charAt(enc4)\n\n }\n return _b_.bytes.$factory(output, 'utf-8', 'strict')\n },\n\n\n decode: function(bytes, altchars, validate){\n var output = [],\n chr1, chr2, chr3,\n enc1, enc2, enc3, enc4\n\n var alphabet = make_alphabet(altchars)\n\n var input = bytes.source\n\n // If validate is set, check that all characters in input\n // are in the alphabet\n var _input = ''\n var padding = 0\n for(var i = 0, len = input.length; i < len; i++){\n var car = String.fromCharCode(input[i])\n var char_num = alphabet.indexOf(car)\n if(char_num == -1){\n if(validate){throw Base64.error(\"Non-base64 digit found: \" +\n car)}\n }else if(char_num == 64 && i < input.length - 2){\n if(validate){throw Base64.error(\"Non-base64 digit found: \" +\n car)}\n }else if(char_num == 64 && i >= input.length - 2){\n padding++\n _input += car\n }else{\n _input += car\n }\n }\n input = _input\n if(_input.length == padding){return _b_.bytes.$factory([])}\n if( _input.length % 4 > 0){throw Base64.error(\"Incorrect padding\")}\n\n var i = 0\n while(i < input.length){\n\n enc1 = alphabet.indexOf(input.charAt(i++))\n enc2 = alphabet.indexOf(input.charAt(i++))\n enc3 = alphabet.indexOf(input.charAt(i++))\n enc4 = alphabet.indexOf(input.charAt(i++))\n\n chr1 = (enc1 << 2) | (enc2 >> 4)\n chr2 = ((enc2 & 15) << 4) | (enc3 >> 2)\n chr3 = ((enc3 & 3) << 6) | enc4\n\n output.push(chr1)\n\n if(enc3 != 64){output.push(chr2)}\n if(enc4 != 64){output.push(chr3)}\n\n }\n // return Python bytes\n return _b_.bytes.$factory(output, 'utf-8', 'strict')\n\n },\n\n _utf8_encode: function(string) {\n string = string.replace(/\\r\\n/g, \"\\n\")\n var utftext = \"\";\n\n for(var n = 0; n < string.length; n++){\n\n var c = string.charCodeAt(n)\n\n if(c < 128){\n utftext += String.fromCharCode(c)\n }else if((c > 127) && (c < 2048)){\n utftext += String.fromCharCode((c >> 6) | 192)\n utftext += String.fromCharCode((c & 63) | 128)\n }else{\n utftext += String.fromCharCode((c >> 12) | 224)\n utftext += String.fromCharCode(((c >> 6) & 63) | 128)\n utftext += String.fromCharCode((c & 63) | 128)\n }\n\n }\n\n return utftext\n },\n\n _utf8_decode: function(utftext) {\n var string = \"\",\n i = 0,\n c = c1 = c2 = 0\n\n while(i < utftext.length){\n\n c = utftext.charCodeAt(i)\n\n if(c < 128){\n string += String.fromCharCode(c)\n i++\n }else if((c > 191) && (c < 224)){\n c2 = utftext.charCodeAt(i + 1)\n string += String.fromCharCode(((c & 31) << 6) | (c2 & 63))\n i += 2\n }else{\n c2 = utftext.charCodeAt(i + 1)\n c3 = utftext.charCodeAt(i + 2)\n string += String.fromCharCode(\n ((c & 15) << 12) | ((c2 & 63) << 6) | (c3 & 63))\n i += 3\n }\n\n }\n\n return string\n }\n\n}\n\nreturn {Base64:Base64}\n}\n\n)(__BRYTHON__)"], "email.feedparser": [".py", "\n\n\n\n\"\"\"FeedParser - An email feed parser.\n\nThe feed parser implements an interface for incrementally parsing an email\nmessage, line by line. This has advantages for certain applications, such as\nthose reading email messages off a socket.\n\nFeedParser.feed() is the primary interface for pushing new data into the\nparser. It returns when there's nothing more it can do with the available\ndata. When you have no more data to push into the parser, call .close().\nThis completes the parsing and returns the root message object.\n\nThe other advantage of this parser is that it will never raise a parsing\nexception. Instead, when it finds something unexpected, it adds a 'defect' to\nthe current message. Defects are just instances that live on the message\nobject's .defects attribute.\n\"\"\"\n\n__all__=['FeedParser','BytesFeedParser']\n\nimport re\n\nfrom email import errors\nfrom email._policybase import compat32\nfrom collections import deque\nfrom io import StringIO\n\nNLCRE=re.compile(r'\\r\\n|\\r|\\n')\nNLCRE_bol=re.compile(r'(\\r\\n|\\r|\\n)')\nNLCRE_eol=re.compile(r'(\\r\\n|\\r|\\n)\\Z')\nNLCRE_crack=re.compile(r'(\\r\\n|\\r|\\n)')\n\n\nheaderRE=re.compile(r'^(From |[\\041-\\071\\073-\\176]*:|[\\t ])')\nEMPTYSTRING=''\nNL='\\n'\n\nNeedMoreData=object()\n\n\n\nclass BufferedSubFile(object):\n ''\n\n\n\n\n\n \n def __init__(self):\n \n \n self._partial=StringIO(newline='')\n \n self._lines=deque()\n \n self._eofstack=[]\n \n self._closed=False\n \n def push_eof_matcher(self,pred):\n self._eofstack.append(pred)\n \n def pop_eof_matcher(self):\n return self._eofstack.pop()\n \n def close(self):\n \n self._partial.seek(0)\n self.pushlines(self._partial.readlines())\n self._partial.seek(0)\n self._partial.truncate()\n self._closed=True\n \n def readline(self):\n if not self._lines:\n if self._closed:\n return ''\n return NeedMoreData\n \n \n line=self._lines.popleft()\n \n \n \n for ateof in reversed(self._eofstack):\n if ateof(line):\n \n self._lines.appendleft(line)\n return ''\n return line\n \n def unreadline(self,line):\n \n assert line is not NeedMoreData\n self._lines.appendleft(line)\n \n def push(self,data):\n ''\n self._partial.write(data)\n if '\\n'not in data and '\\r'not in data:\n \n return\n \n \n self._partial.seek(0)\n parts=self._partial.readlines()\n self._partial.seek(0)\n self._partial.truncate()\n \n \n \n \n \n if not parts[-1].endswith('\\n'):\n self._partial.write(parts.pop())\n self.pushlines(parts)\n \n def pushlines(self,lines):\n self._lines.extend(lines)\n \n def __iter__(self):\n return self\n \n def __next__(self):\n line=self.readline()\n if line =='':\n raise StopIteration\n return line\n \n \n \nclass FeedParser:\n ''\n \n def __init__(self,_factory=None ,*,policy=compat32):\n ''\n\n\n\n\n\n \n self.policy=policy\n self._old_style_factory=False\n if _factory is None :\n if policy.message_factory is None :\n from email.message import Message\n self._factory=Message\n else :\n self._factory=policy.message_factory\n else :\n self._factory=_factory\n try :\n _factory(policy=self.policy)\n except TypeError:\n \n self._old_style_factory=True\n self._input=BufferedSubFile()\n self._msgstack=[]\n self._parse=self._parsegen().__next__\n self._cur=None\n self._last=None\n self._headersonly=False\n \n \n def _set_headersonly(self):\n self._headersonly=True\n \n def feed(self,data):\n ''\n self._input.push(data)\n self._call_parse()\n \n def _call_parse(self):\n try :\n self._parse()\n except StopIteration:\n pass\n \n def close(self):\n ''\n self._input.close()\n self._call_parse()\n root=self._pop_message()\n assert not self._msgstack\n \n if root.get_content_maintype()=='multipart'\\\n and not root.is_multipart():\n defect=errors.MultipartInvariantViolationDefect()\n self.policy.handle_defect(root,defect)\n return root\n \n def _new_message(self):\n if self._old_style_factory:\n msg=self._factory()\n else :\n msg=self._factory(policy=self.policy)\n if self._cur and self._cur.get_content_type()=='multipart/digest':\n msg.set_default_type('message/rfc822')\n if self._msgstack:\n self._msgstack[-1].attach(msg)\n self._msgstack.append(msg)\n self._cur=msg\n self._last=msg\n \n def _pop_message(self):\n retval=self._msgstack.pop()\n if self._msgstack:\n self._cur=self._msgstack[-1]\n else :\n self._cur=None\n return retval\n \n def _parsegen(self):\n \n self._new_message()\n headers=[]\n \n \n for line in self._input:\n if line is NeedMoreData:\n yield NeedMoreData\n continue\n if not headerRE.match(line):\n \n \n \n if not NLCRE.match(line):\n defect=errors.MissingHeaderBodySeparatorDefect()\n self.policy.handle_defect(self._cur,defect)\n self._input.unreadline(line)\n break\n headers.append(line)\n \n \n self._parse_headers(headers)\n \n \n \n if self._headersonly:\n lines=[]\n while True :\n line=self._input.readline()\n if line is NeedMoreData:\n yield NeedMoreData\n continue\n if line =='':\n break\n lines.append(line)\n self._cur.set_payload(EMPTYSTRING.join(lines))\n return\n if self._cur.get_content_type()=='message/delivery-status':\n \n \n \n \n \n while True :\n self._input.push_eof_matcher(NLCRE.match)\n for retval in self._parsegen():\n if retval is NeedMoreData:\n yield NeedMoreData\n continue\n break\n msg=self._pop_message()\n \n \n \n self._input.pop_eof_matcher()\n \n \n \n \n while True :\n line=self._input.readline()\n if line is NeedMoreData:\n yield NeedMoreData\n continue\n break\n while True :\n line=self._input.readline()\n if line is NeedMoreData:\n yield NeedMoreData\n continue\n break\n if line =='':\n break\n \n self._input.unreadline(line)\n return\n if self._cur.get_content_maintype()=='message':\n \n \n for retval in self._parsegen():\n if retval is NeedMoreData:\n yield NeedMoreData\n continue\n break\n self._pop_message()\n return\n if self._cur.get_content_maintype()=='multipart':\n boundary=self._cur.get_boundary()\n if boundary is None :\n \n \n \n \n defect=errors.NoBoundaryInMultipartDefect()\n self.policy.handle_defect(self._cur,defect)\n lines=[]\n for line in self._input:\n if line is NeedMoreData:\n yield NeedMoreData\n continue\n lines.append(line)\n self._cur.set_payload(EMPTYSTRING.join(lines))\n return\n \n if (self._cur.get('content-transfer-encoding','8bit').lower()\n not in ('7bit','8bit','binary')):\n defect=errors.InvalidMultipartContentTransferEncodingDefect()\n self.policy.handle_defect(self._cur,defect)\n \n \n \n \n separator='--'+boundary\n boundaryre=re.compile(\n '(?P<sep>'+re.escape(separator)+\n r')(?P<end>--)?(?P<ws>[ \\t]*)(?P<linesep>\\r\\n|\\r|\\n)?$')\n capturing_preamble=True\n preamble=[]\n linesep=False\n close_boundary_seen=False\n while True :\n line=self._input.readline()\n if line is NeedMoreData:\n yield NeedMoreData\n continue\n if line =='':\n break\n mo=boundaryre.match(line)\n if mo:\n \n \n \n \n if mo.group('end'):\n close_boundary_seen=True\n linesep=mo.group('linesep')\n break\n \n if capturing_preamble:\n if preamble:\n \n \n lastline=preamble[-1]\n eolmo=NLCRE_eol.search(lastline)\n if eolmo:\n preamble[-1]=lastline[:-len(eolmo.group(0))]\n self._cur.preamble=EMPTYSTRING.join(preamble)\n capturing_preamble=False\n self._input.unreadline(line)\n continue\n \n \n \n \n while True :\n line=self._input.readline()\n if line is NeedMoreData:\n yield NeedMoreData\n continue\n mo=boundaryre.match(line)\n if not mo:\n self._input.unreadline(line)\n break\n \n \n self._input.push_eof_matcher(boundaryre.match)\n for retval in self._parsegen():\n if retval is NeedMoreData:\n yield NeedMoreData\n continue\n break\n \n \n \n \n if self._last.get_content_maintype()=='multipart':\n epilogue=self._last.epilogue\n if epilogue =='':\n self._last.epilogue=None\n elif epilogue is not None :\n mo=NLCRE_eol.search(epilogue)\n if mo:\n end=len(mo.group(0))\n self._last.epilogue=epilogue[:-end]\n else :\n payload=self._last._payload\n if isinstance(payload,str):\n mo=NLCRE_eol.search(payload)\n if mo:\n payload=payload[:-len(mo.group(0))]\n self._last._payload=payload\n self._input.pop_eof_matcher()\n self._pop_message()\n \n \n self._last=self._cur\n else :\n \n assert capturing_preamble\n preamble.append(line)\n \n \n \n if capturing_preamble:\n defect=errors.StartBoundaryNotFoundDefect()\n self.policy.handle_defect(self._cur,defect)\n self._cur.set_payload(EMPTYSTRING.join(preamble))\n epilogue=[]\n for line in self._input:\n if line is NeedMoreData:\n yield NeedMoreData\n continue\n self._cur.epilogue=EMPTYSTRING.join(epilogue)\n return\n \n \n if not close_boundary_seen:\n defect=errors.CloseBoundaryNotFoundDefect()\n self.policy.handle_defect(self._cur,defect)\n return\n \n \n \n if linesep:\n epilogue=['']\n else :\n epilogue=[]\n for line in self._input:\n if line is NeedMoreData:\n yield NeedMoreData\n continue\n epilogue.append(line)\n \n \n \n if epilogue:\n firstline=epilogue[0]\n bolmo=NLCRE_bol.match(firstline)\n if bolmo:\n epilogue[0]=firstline[len(bolmo.group(0)):]\n self._cur.epilogue=EMPTYSTRING.join(epilogue)\n return\n \n \n lines=[]\n for line in self._input:\n if line is NeedMoreData:\n yield NeedMoreData\n continue\n lines.append(line)\n self._cur.set_payload(EMPTYSTRING.join(lines))\n \n def _parse_headers(self,lines):\n \n lastheader=''\n lastvalue=[]\n for lineno,line in enumerate(lines):\n \n if line[0]in ' \\t':\n if not lastheader:\n \n \n \n defect=errors.FirstHeaderLineIsContinuationDefect(line)\n self.policy.handle_defect(self._cur,defect)\n continue\n lastvalue.append(line)\n continue\n if lastheader:\n self._cur.set_raw(*self.policy.header_source_parse(lastvalue))\n lastheader,lastvalue='',[]\n \n if line.startswith('From '):\n if lineno ==0:\n \n mo=NLCRE_eol.search(line)\n if mo:\n line=line[:-len(mo.group(0))]\n self._cur.set_unixfrom(line)\n continue\n elif lineno ==len(lines)-1:\n \n \n \n self._input.unreadline(line)\n return\n else :\n \n \n defect=errors.MisplacedEnvelopeHeaderDefect(line)\n self._cur.defects.append(defect)\n continue\n \n \n \n i=line.find(':')\n \n \n \n \n if i ==0:\n defect=errors.InvalidHeaderDefect(\"Missing header name.\")\n self._cur.defects.append(defect)\n continue\n \n assert i >0,\"_parse_headers fed line with no : and no leading WS\"\n lastheader=line[:i]\n lastvalue=[line]\n \n if lastheader:\n self._cur.set_raw(*self.policy.header_source_parse(lastvalue))\n \n \nclass BytesFeedParser(FeedParser):\n ''\n \n def feed(self,data):\n super().feed(data.decode('ascii','surrogateescape'))\n", ["collections", "email", "email._policybase", "email.errors", "email.message", "io", "re"]], "json.scanner": [".py", "''\n\nimport re\ntry :\n from _json import make_scanner as c_make_scanner\nexcept ImportError:\n c_make_scanner=None\n \n__all__=['make_scanner']\n\nNUMBER_RE=re.compile(\nr'(-?(?:0|[1-9]\\d*))(\\.\\d+)?([eE][-+]?\\d+)?',\n(re.VERBOSE |re.MULTILINE |re.DOTALL))\n\ndef py_make_scanner(context):\n parse_object=context.parse_object\n parse_array=context.parse_array\n parse_string=context.parse_string\n match_number=NUMBER_RE.match\n strict=context.strict\n parse_float=context.parse_float\n parse_int=context.parse_int\n parse_constant=context.parse_constant\n object_hook=context.object_hook\n object_pairs_hook=context.object_pairs_hook\n memo=context.memo\n \n def _scan_once(string,idx):\n try :\n nextchar=string[idx]\n except IndexError:\n raise StopIteration(idx)from None\n \n if nextchar =='\"':\n return parse_string(string,idx+1,strict)\n elif nextchar =='{':\n return parse_object((string,idx+1),strict,\n _scan_once,object_hook,object_pairs_hook,memo)\n elif nextchar =='[':\n return parse_array((string,idx+1),_scan_once)\n elif nextchar =='n'and string[idx:idx+4]=='null':\n return None ,idx+4\n elif nextchar =='t'and string[idx:idx+4]=='true':\n return True ,idx+4\n elif nextchar =='f'and string[idx:idx+5]=='false':\n return False ,idx+5\n \n m=match_number(string,idx)\n if m is not None :\n integer,frac,exp=m.groups()\n if frac or exp:\n res=parse_float(integer+(frac or '')+(exp or ''))\n else :\n res=parse_int(integer)\n return res,m.end()\n elif nextchar =='N'and string[idx:idx+3]=='NaN':\n return parse_constant('NaN'),idx+3\n elif nextchar =='I'and string[idx:idx+8]=='Infinity':\n return parse_constant('Infinity'),idx+8\n elif nextchar =='-'and string[idx:idx+9]=='-Infinity':\n return parse_constant('-Infinity'),idx+9\n else :\n raise StopIteration(idx)\n \n def scan_once(string,idx):\n try :\n return _scan_once(string,idx)\n finally :\n memo.clear()\n \n return scan_once\n \nmake_scanner=c_make_scanner or py_make_scanner\n", ["_json", "re"]], "json": [".py", "''\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n__version__='2.0.9'\n__all__=[\n'dump','dumps','load','loads',\n'JSONDecoder','JSONDecodeError','JSONEncoder',\n]\n\n__author__='Bob Ippolito <bob@redivi.com>'\n\nfrom .decoder import JSONDecoder,JSONDecodeError\nfrom .encoder import JSONEncoder\nimport codecs\n\n_default_encoder=JSONEncoder(\nskipkeys=False ,\nensure_ascii=True ,\ncheck_circular=True ,\nallow_nan=True ,\nindent=None ,\nseparators=None ,\ndefault=None ,\n)\n\ndef dump(obj,fp,*,skipkeys=False ,ensure_ascii=True ,check_circular=True ,\nallow_nan=True ,cls=None ,indent=None ,separators=None ,\ndefault=None ,sort_keys=False ,**kw):\n ''\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n \n \n if (not skipkeys and ensure_ascii and\n check_circular and allow_nan and\n cls is None and indent is None and separators is None and\n default is None and not sort_keys and not kw):\n iterable=_default_encoder.iterencode(obj)\n else :\n if cls is None :\n cls=JSONEncoder\n iterable=cls(skipkeys=skipkeys,ensure_ascii=ensure_ascii,\n check_circular=check_circular,allow_nan=allow_nan,indent=indent,\n separators=separators,\n default=default,sort_keys=sort_keys,**kw).iterencode(obj)\n \n \n for chunk in iterable:\n fp.write(chunk)\n \n \ndef dumps(obj,*,skipkeys=False ,ensure_ascii=True ,check_circular=True ,\nallow_nan=True ,cls=None ,indent=None ,separators=None ,\ndefault=None ,sort_keys=False ,**kw):\n ''\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n \n \n if (not skipkeys and ensure_ascii and\n check_circular and allow_nan and\n cls is None and indent is None and separators is None and\n default is None and not sort_keys and not kw):\n return _default_encoder.encode(obj)\n if cls is None :\n cls=JSONEncoder\n return cls(\n skipkeys=skipkeys,ensure_ascii=ensure_ascii,\n check_circular=check_circular,allow_nan=allow_nan,indent=indent,\n separators=separators,default=default,sort_keys=sort_keys,\n **kw).encode(obj)\n \n \n_default_decoder=JSONDecoder(object_hook=None ,object_pairs_hook=None )\n\n\ndef detect_encoding(b):\n bstartswith=b.startswith\n if bstartswith((codecs.BOM_UTF32_BE,codecs.BOM_UTF32_LE)):\n return 'utf-32'\n if bstartswith((codecs.BOM_UTF16_BE,codecs.BOM_UTF16_LE)):\n return 'utf-16'\n if bstartswith(codecs.BOM_UTF8):\n return 'utf-8-sig'\n \n if len(b)>=4:\n if not b[0]:\n \n \n return 'utf-16-be'if b[1]else 'utf-32-be'\n if not b[1]:\n \n \n \n return 'utf-16-le'if b[2]or b[3]else 'utf-32-le'\n elif len(b)==2:\n if not b[0]:\n \n return 'utf-16-be'\n if not b[1]:\n \n return 'utf-16-le'\n \n return 'utf-8'\n \n \ndef load(fp,*,cls=None ,object_hook=None ,parse_float=None ,\nparse_int=None ,parse_constant=None ,object_pairs_hook=None ,**kw):\n ''\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n \n return loads(fp.read(),\n cls=cls,object_hook=object_hook,\n parse_float=parse_float,parse_int=parse_int,\n parse_constant=parse_constant,object_pairs_hook=object_pairs_hook,**kw)\n \n \ndef loads(s,*,encoding=None ,cls=None ,object_hook=None ,parse_float=None ,\nparse_int=None ,parse_constant=None ,object_pairs_hook=None ,**kw):\n ''\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n \n if isinstance(s,str):\n if s.startswith('\\ufeff'):\n raise JSONDecodeError(\"Unexpected UTF-8 BOM (decode using utf-8-sig)\",\n s,0)\n else :\n if not isinstance(s,(bytes,bytearray)):\n raise TypeError(f'the JSON object must be str, bytes or bytearray, '\n f'not {s.__class__.__name__}')\n s=s.decode(detect_encoding(s),'surrogatepass')\n \n if (cls is None and object_hook is None and\n parse_int is None and parse_float is None and\n parse_constant is None and object_pairs_hook is None and not kw):\n return _default_decoder.decode(s)\n if cls is None :\n cls=JSONDecoder\n if object_hook is not None :\n kw['object_hook']=object_hook\n if object_pairs_hook is not None :\n kw['object_pairs_hook']=object_pairs_hook\n if parse_float is not None :\n kw['parse_float']=parse_float\n if parse_int is not None :\n kw['parse_int']=parse_int\n if parse_constant is not None :\n kw['parse_constant']=parse_constant\n return cls(**kw).decode(s)\n", ["codecs", "json.decoder", "json.encoder"], 1], "browser": [".py", "import javascript\n\nfrom _browser import *\n\nfrom .local_storage import LocalStorage\nfrom .session_storage import SessionStorage\nfrom .object_storage import ObjectStorage\n\nWebSocket=window.WebSocket.new\n", ["_browser", "browser.local_storage", "browser.object_storage", "browser.session_storage", "javascript"], 1], "email.header": [".py", "\n\n\n\n\"\"\"Header encoding and decoding functionality.\"\"\"\n\n__all__=[\n'Header',\n'decode_header',\n'make_header',\n]\n\nimport re\nimport binascii\n\nimport email.quoprimime\nimport email.base64mime\n\nfrom email.errors import HeaderParseError\nfrom email import charset as _charset\nCharset=_charset.Charset\n\nNL='\\n'\nSPACE=' '\nBSPACE=b' '\nSPACE8=' '*8\nEMPTYSTRING=''\nMAXLINELEN=78\nFWS=' \\t'\n\nUSASCII=Charset('us-ascii')\nUTF8=Charset('utf-8')\n\n\necre=re.compile(r'''\n =\\? # literal =?\n (?P<charset>[^?]*?) # non-greedy up to the next ? is the charset\n \\? # literal ?\n (?P<encoding>[qQbB]) # either a \"q\" or a \"b\", case insensitive\n \\? # literal ?\n (?P<encoded>.*?) # non-greedy up to the next ?= is the encoded string\n \\?= # literal ?=\n ''',re.VERBOSE |re.MULTILINE)\n\n\n\n\nfcre=re.compile(r'[\\041-\\176]+:$')\n\n\n\n_embedded_header=re.compile(r'\\n[^ \\t]+:')\n\n\n\n\n_max_append=email.quoprimime._max_append\n\n\n\ndef decode_header(header):\n ''\n\n\n\n\n\n\n\n\n\n\n\n \n \n if hasattr(header,'_chunks'):\n return [(_charset._encode(string,str(charset)),str(charset))\n for string,charset in header._chunks]\n \n if not ecre.search(header):\n return [(header,None )]\n \n \n \n words=[]\n for line in header.splitlines():\n parts=ecre.split(line)\n first=True\n while parts:\n unencoded=parts.pop(0)\n if first:\n unencoded=unencoded.lstrip()\n first=False\n if unencoded:\n words.append((unencoded,None ,None ))\n if parts:\n charset=parts.pop(0).lower()\n encoding=parts.pop(0).lower()\n encoded=parts.pop(0)\n words.append((encoded,encoding,charset))\n \n \n droplist=[]\n for n,w in enumerate(words):\n if n >1 and w[1]and words[n -2][1]and words[n -1][0].isspace():\n droplist.append(n -1)\n for d in reversed(droplist):\n del words[d]\n \n \n \n \n decoded_words=[]\n for encoded_string,encoding,charset in words:\n if encoding is None :\n \n decoded_words.append((encoded_string,charset))\n elif encoding =='q':\n word=email.quoprimime.header_decode(encoded_string)\n decoded_words.append((word,charset))\n elif encoding =='b':\n paderr=len(encoded_string)%4\n if paderr:\n encoded_string +='==='[:4 -paderr]\n try :\n word=email.base64mime.decode(encoded_string)\n except binascii.Error:\n raise HeaderParseError('Base64 decoding error')\n else :\n decoded_words.append((word,charset))\n else :\n raise AssertionError('Unexpected encoding: '+encoding)\n \n \n collapsed=[]\n last_word=last_charset=None\n for word,charset in decoded_words:\n if isinstance(word,str):\n word=bytes(word,'raw-unicode-escape')\n if last_word is None :\n last_word=word\n last_charset=charset\n elif charset !=last_charset:\n collapsed.append((last_word,last_charset))\n last_word=word\n last_charset=charset\n elif last_charset is None :\n last_word +=BSPACE+word\n else :\n last_word +=word\n collapsed.append((last_word,last_charset))\n return collapsed\n \n \n \ndef make_header(decoded_seq,maxlinelen=None ,header_name=None ,\ncontinuation_ws=' '):\n ''\n\n\n\n\n\n\n\n\n \n h=Header(maxlinelen=maxlinelen,header_name=header_name,\n continuation_ws=continuation_ws)\n for s,charset in decoded_seq:\n \n if charset is not None and not isinstance(charset,Charset):\n charset=Charset(charset)\n h.append(s,charset)\n return h\n \n \n \nclass Header:\n def __init__(self,s=None ,charset=None ,\n maxlinelen=None ,header_name=None ,\n continuation_ws=' ',errors='strict'):\n ''\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n \n if charset is None :\n charset=USASCII\n elif not isinstance(charset,Charset):\n charset=Charset(charset)\n self._charset=charset\n self._continuation_ws=continuation_ws\n self._chunks=[]\n if s is not None :\n self.append(s,charset,errors)\n if maxlinelen is None :\n maxlinelen=MAXLINELEN\n self._maxlinelen=maxlinelen\n if header_name is None :\n self._headerlen=0\n else :\n \n self._headerlen=len(header_name)+2\n \n def __str__(self):\n ''\n self._normalize()\n uchunks=[]\n lastcs=None\n lastspace=None\n for string,charset in self._chunks:\n \n \n \n \n \n \n nextcs=charset\n if nextcs ==_charset.UNKNOWN8BIT:\n original_bytes=string.encode('ascii','surrogateescape')\n string=original_bytes.decode('ascii','replace')\n if uchunks:\n hasspace=string and self._nonctext(string[0])\n if lastcs not in (None ,'us-ascii'):\n if nextcs in (None ,'us-ascii')and not hasspace:\n uchunks.append(SPACE)\n nextcs=None\n elif nextcs not in (None ,'us-ascii')and not lastspace:\n uchunks.append(SPACE)\n lastspace=string and self._nonctext(string[-1])\n lastcs=nextcs\n uchunks.append(string)\n return EMPTYSTRING.join(uchunks)\n \n \n \n def __eq__(self,other):\n \n \n \n return other ==str(self)\n \n def append(self,s,charset=None ,errors='strict'):\n ''\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n \n if charset is None :\n charset=self._charset\n elif not isinstance(charset,Charset):\n charset=Charset(charset)\n if not isinstance(s,str):\n input_charset=charset.input_codec or 'us-ascii'\n if input_charset ==_charset.UNKNOWN8BIT:\n s=s.decode('us-ascii','surrogateescape')\n else :\n s=s.decode(input_charset,errors)\n \n \n output_charset=charset.output_codec or 'us-ascii'\n if output_charset !=_charset.UNKNOWN8BIT:\n try :\n s.encode(output_charset,errors)\n except UnicodeEncodeError:\n if output_charset !='us-ascii':\n raise\n charset=UTF8\n self._chunks.append((s,charset))\n \n def _nonctext(self,s):\n ''\n \n return s.isspace()or s in ('(',')','\\\\')\n \n def encode(self,splitchars=';, \\t',maxlinelen=None ,linesep='\\n'):\n ''\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n \n self._normalize()\n if maxlinelen is None :\n maxlinelen=self._maxlinelen\n \n \n \n if maxlinelen ==0:\n maxlinelen=1000000\n formatter=_ValueFormatter(self._headerlen,maxlinelen,\n self._continuation_ws,splitchars)\n lastcs=None\n hasspace=lastspace=None\n for string,charset in self._chunks:\n if hasspace is not None :\n hasspace=string and self._nonctext(string[0])\n if lastcs not in (None ,'us-ascii'):\n if not hasspace or charset not in (None ,'us-ascii'):\n formatter.add_transition()\n elif charset not in (None ,'us-ascii')and not lastspace:\n formatter.add_transition()\n lastspace=string and self._nonctext(string[-1])\n lastcs=charset\n hasspace=False\n lines=string.splitlines()\n if lines:\n formatter.feed('',lines[0],charset)\n else :\n formatter.feed('','',charset)\n for line in lines[1:]:\n formatter.newline()\n if charset.header_encoding is not None :\n formatter.feed(self._continuation_ws,' '+line.lstrip(),\n charset)\n else :\n sline=line.lstrip()\n fws=line[:len(line)-len(sline)]\n formatter.feed(fws,sline,charset)\n if len(lines)>1:\n formatter.newline()\n if self._chunks:\n formatter.add_transition()\n value=formatter._str(linesep)\n if _embedded_header.search(value):\n raise HeaderParseError(\"header value appears to contain \"\n \"an embedded header: {!r}\".format(value))\n return value\n \n def _normalize(self):\n \n \n chunks=[]\n last_charset=None\n last_chunk=[]\n for string,charset in self._chunks:\n if charset ==last_charset:\n last_chunk.append(string)\n else :\n if last_charset is not None :\n chunks.append((SPACE.join(last_chunk),last_charset))\n last_chunk=[string]\n last_charset=charset\n if last_chunk:\n chunks.append((SPACE.join(last_chunk),last_charset))\n self._chunks=chunks\n \n \n \nclass _ValueFormatter:\n def __init__(self,headerlen,maxlen,continuation_ws,splitchars):\n self._maxlen=maxlen\n self._continuation_ws=continuation_ws\n self._continuation_ws_len=len(continuation_ws)\n self._splitchars=splitchars\n self._lines=[]\n self._current_line=_Accumulator(headerlen)\n \n def _str(self,linesep):\n self.newline()\n return linesep.join(self._lines)\n \n def __str__(self):\n return self._str(NL)\n \n def newline(self):\n end_of_line=self._current_line.pop()\n if end_of_line !=(' ',''):\n self._current_line.push(*end_of_line)\n if len(self._current_line)>0:\n if self._current_line.is_onlyws():\n self._lines[-1]+=str(self._current_line)\n else :\n self._lines.append(str(self._current_line))\n self._current_line.reset()\n \n def add_transition(self):\n self._current_line.push(' ','')\n \n def feed(self,fws,string,charset):\n \n \n \n \n \n if charset.header_encoding is None :\n self._ascii_split(fws,string,self._splitchars)\n return\n \n \n \n \n \n \n \n encoded_lines=charset.header_encode_lines(string,self._maxlengths())\n \n \n try :\n first_line=encoded_lines.pop(0)\n except IndexError:\n \n return\n if first_line is not None :\n self._append_chunk(fws,first_line)\n try :\n last_line=encoded_lines.pop()\n except IndexError:\n \n return\n self.newline()\n self._current_line.push(self._continuation_ws,last_line)\n \n for line in encoded_lines:\n self._lines.append(self._continuation_ws+line)\n \n def _maxlengths(self):\n \n yield self._maxlen -len(self._current_line)\n while True :\n yield self._maxlen -self._continuation_ws_len\n \n def _ascii_split(self,fws,string,splitchars):\n \n \n \n \n \n \n \n \n \n \n \n \n \n parts=re.split(\"([\"+FWS+\"]+)\",fws+string)\n if parts[0]:\n parts[:0]=['']\n else :\n parts.pop(0)\n for fws,part in zip(*[iter(parts)]*2):\n self._append_chunk(fws,part)\n \n def _append_chunk(self,fws,string):\n self._current_line.push(fws,string)\n if len(self._current_line)>self._maxlen:\n \n \n for ch in self._splitchars:\n for i in range(self._current_line.part_count()-1,0,-1):\n if ch.isspace():\n fws=self._current_line[i][0]\n if fws and fws[0]==ch:\n break\n prevpart=self._current_line[i -1][1]\n if prevpart and prevpart[-1]==ch:\n break\n else :\n continue\n break\n else :\n fws,part=self._current_line.pop()\n if self._current_line._initial_size >0:\n \n self.newline()\n if not fws:\n \n \n fws=' '\n self._current_line.push(fws,part)\n return\n remainder=self._current_line.pop_from(i)\n self._lines.append(str(self._current_line))\n self._current_line.reset(remainder)\n \n \nclass _Accumulator(list):\n\n def __init__(self,initial_size=0):\n self._initial_size=initial_size\n super().__init__()\n \n def push(self,fws,string):\n self.append((fws,string))\n \n def pop_from(self,i=0):\n popped=self[i:]\n self[i:]=[]\n return popped\n \n def pop(self):\n if self.part_count()==0:\n return ('','')\n return super().pop()\n \n def __len__(self):\n return sum((len(fws)+len(part)for fws,part in self),\n self._initial_size)\n \n def __str__(self):\n return EMPTYSTRING.join((EMPTYSTRING.join((fws,part))\n for fws,part in self))\n \n def reset(self,startval=None ):\n if startval is None :\n startval=[]\n self[:]=startval\n self._initial_size=0\n \n def is_onlyws(self):\n return self._initial_size ==0 and (not self or str(self).isspace())\n \n def part_count(self):\n return super().__len__()\n", ["binascii", "email", "email.base64mime", "email.charset", "email.errors", "email.quoprimime", "re"]], "json.encoder": [".py", "''\n\nimport re\n\ntry :\n from _json import encode_basestring_ascii as c_encode_basestring_ascii\nexcept ImportError:\n c_encode_basestring_ascii=None\ntry :\n from _json import encode_basestring as c_encode_basestring\nexcept ImportError:\n c_encode_basestring=None\ntry :\n from _json import make_encoder as c_make_encoder\nexcept ImportError:\n c_make_encoder=None\n \nESCAPE=re.compile(r'[\\x00-\\x1f\\\\\"\\b\\f\\n\\r\\t]')\nESCAPE_ASCII=re.compile(r'([\\\\\"]|[^\\ -~])')\nHAS_UTF8=re.compile(b'[\\x80-\\xff]')\nESCAPE_DCT={\n'\\\\':'\\\\\\\\',\n'\"':'\\\\\"',\n'\\b':'\\\\b',\n'\\f':'\\\\f',\n'\\n':'\\\\n',\n'\\r':'\\\\r',\n'\\t':'\\\\t',\n}\nfor i in range(0x20):\n ESCAPE_DCT.setdefault(chr(i),'\\\\u{0:04x}'.format(i))\n \n \nINFINITY=float('inf')\n\ndef py_encode_basestring(s):\n ''\n\n \n def replace(match):\n return ESCAPE_DCT[match.group(0)]\n return '\"'+ESCAPE.sub(replace,s)+'\"'\n \n \nencode_basestring=(c_encode_basestring or py_encode_basestring)\n\n\ndef py_encode_basestring_ascii(s):\n ''\n\n \n def replace(match):\n s=match.group(0)\n try :\n return ESCAPE_DCT[s]\n except KeyError:\n n=ord(s)\n if n <0x10000:\n return '\\\\u{0:04x}'.format(n)\n \n else :\n \n n -=0x10000\n s1=0xd800 |((n >>10)&0x3ff)\n s2=0xdc00 |(n&0x3ff)\n return '\\\\u{0:04x}\\\\u{1:04x}'.format(s1,s2)\n return '\"'+ESCAPE_ASCII.sub(replace,s)+'\"'\n \n \nencode_basestring_ascii=(\nc_encode_basestring_ascii or py_encode_basestring_ascii)\n\nclass JSONEncoder(object):\n ''\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n \n item_separator=', '\n key_separator=': '\n def __init__(self,*,skipkeys=False ,ensure_ascii=True ,\n check_circular=True ,allow_nan=True ,sort_keys=False ,\n indent=None ,separators=None ,default=None ):\n ''\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n \n \n self.skipkeys=skipkeys\n self.ensure_ascii=ensure_ascii\n self.check_circular=check_circular\n self.allow_nan=allow_nan\n self.sort_keys=sort_keys\n self.indent=indent\n if separators is not None :\n self.item_separator,self.key_separator=separators\n elif indent is not None :\n self.item_separator=','\n if default is not None :\n self.default=default\n \n def default(self,o):\n ''\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n \n raise TypeError(f'Object of type {o.__class__.__name__} '\n f'is not JSON serializable')\n \n def encode(self,o):\n ''\n\n\n\n\n\n \n \n if isinstance(o,str):\n if self.ensure_ascii:\n return encode_basestring_ascii(o)\n else :\n return encode_basestring(o)\n \n \n \n chunks=self.iterencode(o,_one_shot=True )\n if not isinstance(chunks,(list,tuple)):\n chunks=list(chunks)\n return ''.join(chunks)\n \n def iterencode(self,o,_one_shot=False ):\n ''\n\n\n\n\n\n\n\n \n if self.check_circular:\n markers={}\n else :\n markers=None\n if self.ensure_ascii:\n _encoder=encode_basestring_ascii\n else :\n _encoder=encode_basestring\n \n def floatstr(o,allow_nan=self.allow_nan,\n _repr=float.__repr__,_inf=INFINITY,_neginf=-INFINITY):\n \n \n \n \n if o !=o:\n text='NaN'\n elif o ==_inf:\n text='Infinity'\n elif o ==_neginf:\n text='-Infinity'\n else :\n return _repr(o)\n \n if not allow_nan:\n raise ValueError(\n \"Out of range float values are not JSON compliant: \"+\n repr(o))\n \n return text\n \n \n if (_one_shot and c_make_encoder is not None\n and self.indent is None ):\n _iterencode=c_make_encoder(\n markers,self.default,_encoder,self.indent,\n self.key_separator,self.item_separator,self.sort_keys,\n self.skipkeys,self.allow_nan)\n else :\n _iterencode=_make_iterencode(\n markers,self.default,_encoder,self.indent,floatstr,\n self.key_separator,self.item_separator,self.sort_keys,\n self.skipkeys,_one_shot)\n return _iterencode(o,0)\n \ndef _make_iterencode(markers,_default,_encoder,_indent,_floatstr,\n_key_separator,_item_separator,_sort_keys,_skipkeys,_one_shot,\n\nValueError=ValueError,\ndict=dict,\nfloat=float,\nid=id,\nint=int,\nisinstance=isinstance,\nlist=list,\nstr=str,\ntuple=tuple,\n_intstr=int.__str__,\n):\n\n if _indent is not None and not isinstance(_indent,str):\n _indent=' '*_indent\n \n def _iterencode_list(lst,_current_indent_level):\n if not lst:\n yield '[]'\n return\n if markers is not None :\n markerid=id(lst)\n if markerid in markers:\n raise ValueError(\"Circular reference detected\")\n markers[markerid]=lst\n buf='['\n if _indent is not None :\n _current_indent_level +=1\n newline_indent='\\n'+_indent *_current_indent_level\n separator=_item_separator+newline_indent\n buf +=newline_indent\n else :\n newline_indent=None\n separator=_item_separator\n first=True\n for value in lst:\n if first:\n first=False\n else :\n buf=separator\n if isinstance(value,str):\n yield buf+_encoder(value)\n elif value is None :\n yield buf+'null'\n elif value is True :\n yield buf+'true'\n elif value is False :\n yield buf+'false'\n elif isinstance(value,int):\n \n \n \n yield buf+_intstr(value)\n elif isinstance(value,float):\n \n yield buf+_floatstr(value)\n else :\n yield buf\n if isinstance(value,(list,tuple)):\n chunks=_iterencode_list(value,_current_indent_level)\n elif isinstance(value,dict):\n chunks=_iterencode_dict(value,_current_indent_level)\n else :\n chunks=_iterencode(value,_current_indent_level)\n yield from chunks\n if newline_indent is not None :\n _current_indent_level -=1\n yield '\\n'+_indent *_current_indent_level\n yield ']'\n if markers is not None :\n del markers[markerid]\n \n def _iterencode_dict(dct,_current_indent_level):\n if not dct:\n yield '{}'\n return\n if markers is not None :\n markerid=id(dct)\n if markerid in markers:\n raise ValueError(\"Circular reference detected\")\n markers[markerid]=dct\n yield '{'\n if _indent is not None :\n _current_indent_level +=1\n newline_indent='\\n'+_indent *_current_indent_level\n item_separator=_item_separator+newline_indent\n yield newline_indent\n else :\n newline_indent=None\n item_separator=_item_separator\n first=True\n if _sort_keys:\n items=sorted(dct.items(),key=lambda kv:kv[0])\n else :\n items=dct.items()\n for key,value in items:\n if isinstance(key,str):\n pass\n \n \n elif isinstance(key,float):\n \n key=_floatstr(key)\n elif key is True :\n key='true'\n elif key is False :\n key='false'\n elif key is None :\n key='null'\n elif isinstance(key,int):\n \n key=_intstr(key)\n elif _skipkeys:\n continue\n else :\n raise TypeError(f'keys must be str, int, float, bool or None, '\n f'not {key.__class__.__name__}')\n if first:\n first=False\n else :\n yield item_separator\n yield _encoder(key)\n yield _key_separator\n if isinstance(value,str):\n yield _encoder(value)\n elif value is None :\n yield 'null'\n elif value is True :\n yield 'true'\n elif value is False :\n yield 'false'\n elif isinstance(value,int):\n \n yield _intstr(value)\n elif isinstance(value,float):\n \n yield _floatstr(value)\n else :\n if isinstance(value,(list,tuple)):\n chunks=_iterencode_list(value,_current_indent_level)\n elif isinstance(value,dict):\n chunks=_iterencode_dict(value,_current_indent_level)\n else :\n chunks=_iterencode(value,_current_indent_level)\n yield from chunks\n if newline_indent is not None :\n _current_indent_level -=1\n yield '\\n'+_indent *_current_indent_level\n yield '}'\n if markers is not None :\n del markers[markerid]\n \n def _iterencode(o,_current_indent_level):\n if isinstance(o,str):\n yield _encoder(o)\n elif o is None :\n yield 'null'\n elif o is True :\n yield 'true'\n elif o is False :\n yield 'false'\n elif isinstance(o,int):\n \n yield _intstr(o)\n elif isinstance(o,float):\n \n yield _floatstr(o)\n elif isinstance(o,(list,tuple)):\n yield from _iterencode_list(o,_current_indent_level)\n elif isinstance(o,dict):\n yield from _iterencode_dict(o,_current_indent_level)\n else :\n if markers is not None :\n markerid=id(o)\n if markerid in markers:\n raise ValueError(\"Circular reference detected\")\n markers[markerid]=o\n o=_default(o)\n yield from _iterencode(o,_current_indent_level)\n if markers is not None :\n del markers[markerid]\n return _iterencode\n", ["_json", "re"]], "glob": [".py", "''\n\nimport os\nimport re\nimport fnmatch\n\n__all__=[\"glob\",\"iglob\",\"escape\"]\n\ndef glob(pathname,*,recursive=False ):\n ''\n\n\n\n\n\n\n\n\n \n return list(iglob(pathname,recursive=recursive))\n \ndef iglob(pathname,*,recursive=False ):\n ''\n\n\n\n\n\n\n\n\n \n it=_iglob(pathname,recursive,False )\n if recursive and _isrecursive(pathname):\n s=next(it)\n assert not s\n return it\n \ndef _iglob(pathname,recursive,dironly):\n dirname,basename=os.path.split(pathname)\n if not has_magic(pathname):\n assert not dironly\n if basename:\n if os.path.lexists(pathname):\n yield pathname\n else :\n \n if os.path.isdir(dirname):\n yield pathname\n return\n if not dirname:\n if recursive and _isrecursive(basename):\n yield from _glob2(dirname,basename,dironly)\n else :\n yield from _glob1(dirname,basename,dironly)\n return\n \n \n \n if dirname !=pathname and has_magic(dirname):\n dirs=_iglob(dirname,recursive,True )\n else :\n dirs=[dirname]\n if has_magic(basename):\n if recursive and _isrecursive(basename):\n glob_in_dir=_glob2\n else :\n glob_in_dir=_glob1\n else :\n glob_in_dir=_glob0\n for dirname in dirs:\n for name in glob_in_dir(dirname,basename,dironly):\n yield os.path.join(dirname,name)\n \n \n \n \n \ndef _glob1(dirname,pattern,dironly):\n names=list(_iterdir(dirname,dironly))\n if not _ishidden(pattern):\n names=(x for x in names if not _ishidden(x))\n return fnmatch.filter(names,pattern)\n \ndef _glob0(dirname,basename,dironly):\n if not basename:\n \n \n if os.path.isdir(dirname):\n return [basename]\n else :\n if os.path.lexists(os.path.join(dirname,basename)):\n return [basename]\n return []\n \n \n \ndef glob0(dirname,pattern):\n return _glob0(dirname,pattern,False )\n \ndef glob1(dirname,pattern):\n return _glob1(dirname,pattern,False )\n \n \n \n \ndef _glob2(dirname,pattern,dironly):\n assert _isrecursive(pattern)\n yield pattern[:0]\n yield from _rlistdir(dirname,dironly)\n \n \n \ndef _iterdir(dirname,dironly):\n if not dirname:\n if isinstance(dirname,bytes):\n dirname=bytes(os.curdir,'ASCII')\n else :\n dirname=os.curdir\n try :\n with os.scandir(dirname)as it:\n for entry in it:\n try :\n if not dironly or entry.is_dir():\n yield entry.name\n except OSError:\n pass\n except OSError:\n return\n \n \ndef _rlistdir(dirname,dironly):\n names=list(_iterdir(dirname,dironly))\n for x in names:\n if not _ishidden(x):\n yield x\n path=os.path.join(dirname,x)if dirname else x\n for y in _rlistdir(path,dironly):\n yield os.path.join(x,y)\n \n \nmagic_check=re.compile('([*?[])')\nmagic_check_bytes=re.compile(b'([*?[])')\n\ndef has_magic(s):\n if isinstance(s,bytes):\n match=magic_check_bytes.search(s)\n else :\n match=magic_check.search(s)\n return match is not None\n \ndef _ishidden(path):\n return path[0]in ('.',b'.'[0])\n \ndef _isrecursive(pattern):\n if isinstance(pattern,bytes):\n return pattern ==b'**'\n else :\n return pattern =='**'\n \ndef escape(pathname):\n ''\n \n \n \n drive,pathname=os.path.splitdrive(pathname)\n if isinstance(pathname,bytes):\n pathname=magic_check_bytes.sub(br'[\\1]',pathname)\n else :\n pathname=magic_check.sub(r'[\\1]',pathname)\n return drive+pathname\n", ["fnmatch", "os", "re"]], "select": [".py", "''\n\n\n\n\n\n\n\n\n\nimport errno\nimport os\n\nclass error(Exception):pass\n\nALL=None\n\n_exception_map={\n\n\n\n\n\n\n}\n\ndef _map_exception(exc,circumstance=ALL):\n try :\n mapped_exception=_exception_map[(exc.__class__,circumstance)]\n mapped_exception.java_exception=exc\n return mapped_exception\n except KeyError:\n return error(-1,'Unmapped java exception: <%s:%s>'%(exc.toString(),circumstance))\n \nPOLLIN=1\nPOLLOUT=2\n\n\n\n\n\nPOLLPRI=4\nPOLLERR=8\nPOLLHUP=16\nPOLLNVAL=32\n\ndef _getselectable(selectable_object):\n try :\n channel=selectable_object.getchannel()\n except :\n try :\n channel=selectable_object.fileno().getChannel()\n except :\n raise TypeError(\"Object '%s' is not watchable\"%selectable_object,\n errno.ENOTSOCK)\n \n if channel and not isinstance(channel,java.nio.channels.SelectableChannel):\n raise TypeError(\"Object '%s' is not watchable\"%selectable_object,\n errno.ENOTSOCK)\n return channel\n \nclass poll:\n\n def __init__(self):\n self.selector=java.nio.channels.Selector.open()\n self.chanmap={}\n self.unconnected_sockets=[]\n \n def _register_channel(self,socket_object,channel,mask):\n jmask=0\n if mask&POLLIN:\n \n if channel.validOps()&OP_ACCEPT:\n jmask=OP_ACCEPT\n else :\n jmask=OP_READ\n if mask&POLLOUT:\n if channel.validOps()&OP_WRITE:\n jmask |=OP_WRITE\n if channel.validOps()&OP_CONNECT:\n jmask |=OP_CONNECT\n selectionkey=channel.register(self.selector,jmask)\n self.chanmap[channel]=(socket_object,selectionkey)\n \n def _check_unconnected_sockets(self):\n temp_list=[]\n for socket_object,mask in self.unconnected_sockets:\n channel=_getselectable(socket_object)\n if channel is not None :\n self._register_channel(socket_object,channel,mask)\n else :\n temp_list.append((socket_object,mask))\n self.unconnected_sockets=temp_list\n \n def register(self,socket_object,mask=POLLIN |POLLOUT |POLLPRI):\n try :\n channel=_getselectable(socket_object)\n if channel is None :\n \n \n self.unconnected_sockets.append((socket_object,mask))\n return\n self._register_channel(socket_object,channel,mask)\n except BaseException:\n \n raise _map_exception(jlx)\n \n def unregister(self,socket_object):\n try :\n channel=_getselectable(socket_object)\n self.chanmap[channel][1].cancel()\n del self.chanmap[channel]\n except BaseException:\n \n raise _map_exception(jlx)\n \n def _dopoll(self,timeout):\n if timeout is None or timeout <0:\n self.selector.select()\n else :\n try :\n timeout=int(timeout)\n if not timeout:\n self.selector.selectNow()\n else :\n \n self.selector.select(timeout)\n except ValueError as vx:\n raise error(\"poll timeout must be a number of milliseconds or None\",errno.EINVAL)\n \n return self.selector.selectedKeys()\n \n def poll(self,timeout=None ):\n try :\n self._check_unconnected_sockets()\n selectedkeys=self._dopoll(timeout)\n results=[]\n for k in selectedkeys.iterator():\n jmask=k.readyOps()\n pymask=0\n if jmask&OP_READ:pymask |=POLLIN\n if jmask&OP_WRITE:pymask |=POLLOUT\n if jmask&OP_ACCEPT:pymask |=POLLIN\n if jmask&OP_CONNECT:pymask |=POLLOUT\n \n results.append((self.chanmap[k.channel()][0],pymask))\n return results\n except BaseException:\n \n raise _map_exception(jlx)\n \n def _deregister_all(self):\n try :\n for k in self.selector.keys():\n k.cancel()\n \n self.selector.selectNow()\n except BaseException:\n \n raise _map_exception(jlx)\n \n def close(self):\n try :\n self._deregister_all()\n self.selector.close()\n except BaseException:\n \n raise _map_exception(jlx)\n \ndef _calcselecttimeoutvalue(value):\n if value is None :\n return None\n try :\n floatvalue=float(value)\n except Exception as x:\n raise TypeError(\"Select timeout value must be a number or None\")\n if value <0:\n raise error(\"Select timeout value cannot be negative\",errno.EINVAL)\n if floatvalue <0.000001:\n return 0\n return int(floatvalue *1000)\n \n \n \n \nclass poll_object_cache:\n\n def __init__(self):\n self.is_windows=os.name =='nt'\n if self.is_windows:\n self.poll_object_queue=Queue.Queue()\n import atexit\n atexit.register(self.finalize)\n \n def get_poll_object(self):\n if not self.is_windows:\n return poll()\n try :\n return self.poll_object_queue.get(False )\n except Queue.Empty:\n return poll()\n \n def release_poll_object(self,pobj):\n if self.is_windows:\n pobj._deregister_all()\n self.poll_object_queue.put(pobj)\n else :\n pobj.close()\n \n def finalize(self):\n if self.is_windows:\n while True :\n try :\n p=self.poll_object_queue.get(False )\n p.close()\n except Queue.Empty:\n return\n \n_poll_object_cache=poll_object_cache()\n\ndef native_select(read_fd_list,write_fd_list,outofband_fd_list,timeout=None ):\n timeout=_calcselecttimeoutvalue(timeout)\n \n pobj=_poll_object_cache.get_poll_object()\n try :\n registered_for_read={}\n \n for fd in read_fd_list:\n pobj.register(fd,POLLIN)\n registered_for_read[fd]=1\n \n for fd in write_fd_list:\n if fd in registered_for_read:\n \n pobj.register(fd,POLLIN |POLLOUT)\n else :\n pobj.register(fd,POLLOUT)\n results=pobj.poll(timeout)\n \n read_ready_list,write_ready_list,oob_ready_list=[],[],[]\n for fd,mask in results:\n if mask&POLLIN:\n read_ready_list.append(fd)\n if mask&POLLOUT:\n write_ready_list.append(fd)\n return read_ready_list,write_ready_list,oob_ready_list\n finally :\n _poll_object_cache.release_poll_object(pobj)\n \nselect=native_select\n\ndef cpython_compatible_select(read_fd_list,write_fd_list,outofband_fd_list,timeout=None ):\n\n\n modified_channels=[]\n try :\n for socket_list in [read_fd_list,write_fd_list,outofband_fd_list]:\n for s in socket_list:\n channel=_getselectable(s)\n if channel.isBlocking():\n modified_channels.append(channel)\n channel.configureBlocking(0)\n return native_select(read_fd_list,write_fd_list,outofband_fd_list,timeout)\n finally :\n for channel in modified_channels:\n channel.configureBlocking(1)\n", ["atexit", "errno", "os"]], "pdb": [".py", "#! /usr/bin/env python3\n\n\"\"\"\nThe Python Debugger Pdb\n=======================\n\nTo use the debugger in its simplest form:\n\n >>> import pdb\n >>> pdb.run('<a statement>')\n\nThe debugger's prompt is '(Pdb) '. This will stop in the first\nfunction call in <a statement>.\n\nAlternatively, if a statement terminated with an unhandled exception,\nyou can use pdb's post-mortem facility to inspect the contents of the\ntraceback:\n\n >>> <a statement>\n <exception traceback>\n >>> import pdb\n >>> pdb.pm()\n\nThe commands recognized by the debugger are listed in the next\nsection. Most can be abbreviated as indicated; e.g., h(elp) means\nthat 'help' can be typed as 'h' or 'help' (but not as 'he' or 'hel',\nnor as 'H' or 'Help' or 'HELP'). Optional arguments are enclosed in\nsquare brackets. Alternatives in the command syntax are separated\nby a vertical bar (|).\n\nA blank line repeats the previous command literally, except for\n'list', where it lists the next 11 lines.\n\nCommands that the debugger doesn't recognize are assumed to be Python\nstatements and are executed in the context of the program being\ndebugged. Python statements can also be prefixed with an exclamation\npoint ('!'). This is a powerful way to inspect the program being\ndebugged; it is even possible to change variables or call functions.\nWhen an exception occurs in such a statement, the exception name is\nprinted but the debugger's state is not changed.\n\nThe debugger supports aliases, which can save typing. And aliases can\nhave parameters (see the alias help entry) which allows one a certain\nlevel of adaptability to the context under examination.\n\nMultiple commands may be entered on a single line, separated by the\npair ';;'. No intelligence is applied to separating the commands; the\ninput is split at the first ';;', even if it is in the middle of a\nquoted string.\n\nIf a file \".pdbrc\" exists in your home directory or in the current\ndirectory, it is read in and executed as if it had been typed at the\ndebugger prompt. This is particularly useful for aliases. If both\nfiles exist, the one in the home directory is read first and aliases\ndefined there can be overridden by the local file. This behavior can be\ndisabled by passing the \"readrc=False\" argument to the Pdb constructor.\n\nAside from aliases, the debugger is not directly programmable; but it\nis implemented as a class from which you can derive your own debugger\nclass, which you can make as fancy as you like.\n\n\nDebugger commands\n=================\n\n\"\"\"\n\n\n\nimport os\nimport re\nimport sys\nimport cmd\nimport bdb\nimport dis\nimport code\nimport glob\nimport pprint\nimport signal\nimport inspect\nimport traceback\nimport linecache\n\n\nclass Restart(Exception):\n ''\n pass\n \n__all__=[\"run\",\"pm\",\"Pdb\",\"runeval\",\"runctx\",\"runcall\",\"set_trace\",\n\"post_mortem\",\"help\"]\n\ndef find_function(funcname,filename):\n cre=re.compile(r'def\\s+%s\\s*[(]'%re.escape(funcname))\n try :\n fp=open(filename)\n except OSError:\n return None\n \n with fp:\n for lineno,line in enumerate(fp,start=1):\n if cre.match(line):\n return funcname,filename,lineno\n return None\n \ndef getsourcelines(obj):\n lines,lineno=inspect.findsource(obj)\n if inspect.isframe(obj)and obj.f_globals is obj.f_locals:\n \n return lines,1\n elif inspect.ismodule(obj):\n return lines,1\n return inspect.getblock(lines[lineno:]),lineno+1\n \ndef lasti2lineno(code,lasti):\n linestarts=list(dis.findlinestarts(code))\n linestarts.reverse()\n for i,lineno in linestarts:\n if lasti >=i:\n return lineno\n return 0\n \n \nclass _rstr(str):\n ''\n def __repr__(self):\n return self\n \n \n \n \n \n \n \nline_prefix='\\n-> '\n\nclass Pdb(bdb.Bdb,cmd.Cmd):\n\n _previous_sigint_handler=None\n \n def __init__(self,completekey='tab',stdin=None ,stdout=None ,skip=None ,\n nosigint=False ,readrc=True ):\n bdb.Bdb.__init__(self,skip=skip)\n cmd.Cmd.__init__(self,completekey,stdin,stdout)\n if stdout:\n self.use_rawinput=0\n self.prompt='(Pdb) '\n self.aliases={}\n self.displaying={}\n self.mainpyfile=''\n self._wait_for_mainpyfile=False\n self.tb_lineno={}\n \n try :\n import readline\n \n readline.set_completer_delims(' \\t\\n`@#$%^&*()=+[{]}\\\\|;:\\'\",<>?')\n except ImportError:\n pass\n self.allow_kbdint=False\n self.nosigint=nosigint\n \n \n self.rcLines=[]\n if readrc:\n if 'HOME'in os.environ:\n envHome=os.environ['HOME']\n try :\n with open(os.path.join(envHome,\".pdbrc\"))as rcFile:\n self.rcLines.extend(rcFile)\n except OSError:\n pass\n try :\n with open(\".pdbrc\")as rcFile:\n self.rcLines.extend(rcFile)\n except OSError:\n pass\n \n self.commands={}\n self.commands_doprompt={}\n \n self.commands_silent={}\n \n self.commands_defining=False\n \n self.commands_bnum=None\n \n \n def sigint_handler(self,signum,frame):\n if self.allow_kbdint:\n raise KeyboardInterrupt\n self.message(\"\\nProgram interrupted. (Use 'cont' to resume).\")\n self.set_step()\n self.set_trace(frame)\n \n def reset(self):\n bdb.Bdb.reset(self)\n self.forget()\n \n def forget(self):\n self.lineno=None\n self.stack=[]\n self.curindex=0\n self.curframe=None\n self.tb_lineno.clear()\n \n def setup(self,f,tb):\n self.forget()\n self.stack,self.curindex=self.get_stack(f,tb)\n while tb:\n \n \n \n lineno=lasti2lineno(tb.tb_frame.f_code,tb.tb_lasti)\n self.tb_lineno[tb.tb_frame]=lineno\n tb=tb.tb_next\n self.curframe=self.stack[self.curindex][0]\n \n \n \n self.curframe_locals=self.curframe.f_locals\n return self.execRcLines()\n \n \n def execRcLines(self):\n if not self.rcLines:\n return\n \n rcLines=self.rcLines\n rcLines.reverse()\n \n self.rcLines=[]\n while rcLines:\n line=rcLines.pop().strip()\n if line and line[0]!='#':\n if self.onecmd(line):\n \n \n \n self.rcLines +=reversed(rcLines)\n return True\n \n \n \n def user_call(self,frame,argument_list):\n ''\n \n if self._wait_for_mainpyfile:\n return\n if self.stop_here(frame):\n self.message('--Call--')\n self.interaction(frame,None )\n \n def user_line(self,frame):\n ''\n if self._wait_for_mainpyfile:\n if (self.mainpyfile !=self.canonic(frame.f_code.co_filename)\n or frame.f_lineno <=0):\n return\n self._wait_for_mainpyfile=False\n if self.bp_commands(frame):\n self.interaction(frame,None )\n \n def bp_commands(self,frame):\n ''\n\n\n\n \n \n if getattr(self,\"currentbp\",False )and\\\n self.currentbp in self.commands:\n currentbp=self.currentbp\n self.currentbp=0\n lastcmd_back=self.lastcmd\n self.setup(frame,None )\n for line in self.commands[currentbp]:\n self.onecmd(line)\n self.lastcmd=lastcmd_back\n if not self.commands_silent[currentbp]:\n self.print_stack_entry(self.stack[self.curindex])\n if self.commands_doprompt[currentbp]:\n self._cmdloop()\n self.forget()\n return\n return 1\n \n def user_return(self,frame,return_value):\n ''\n if self._wait_for_mainpyfile:\n return\n frame.f_locals['__return__']=return_value\n self.message('--Return--')\n self.interaction(frame,None )\n \n def user_exception(self,frame,exc_info):\n ''\n \n if self._wait_for_mainpyfile:\n return\n exc_type,exc_value,exc_traceback=exc_info\n frame.f_locals['__exception__']=exc_type,exc_value\n \n \n \n \n \n \n prefix='Internal 'if (not exc_traceback\n and exc_type is StopIteration)else ''\n self.message('%s%s'%(prefix,\n traceback.format_exception_only(exc_type,exc_value)[-1].strip()))\n self.interaction(frame,exc_traceback)\n \n \n def _cmdloop(self):\n while True :\n try :\n \n \n self.allow_kbdint=True\n self.cmdloop()\n self.allow_kbdint=False\n break\n except KeyboardInterrupt:\n self.message('--KeyboardInterrupt--')\n \n \n def preloop(self):\n displaying=self.displaying.get(self.curframe)\n if displaying:\n for expr,oldvalue in displaying.items():\n newvalue=self._getval_except(expr)\n \n \n \n if newvalue is not oldvalue and newvalue !=oldvalue:\n displaying[expr]=newvalue\n self.message('display %s: %r [old: %r]'%\n (expr,newvalue,oldvalue))\n \n def interaction(self,frame,traceback):\n \n if Pdb._previous_sigint_handler:\n signal.signal(signal.SIGINT,Pdb._previous_sigint_handler)\n Pdb._previous_sigint_handler=None\n if self.setup(frame,traceback):\n \n \n self.forget()\n return\n self.print_stack_entry(self.stack[self.curindex])\n self._cmdloop()\n self.forget()\n \n def displayhook(self,obj):\n ''\n\n \n \n if obj is not None :\n self.message(repr(obj))\n \n def default(self,line):\n if line[:1]=='!':line=line[1:]\n locals=self.curframe_locals\n globals=self.curframe.f_globals\n try :\n code=compile(line+'\\n','<stdin>','single')\n save_stdout=sys.stdout\n save_stdin=sys.stdin\n save_displayhook=sys.displayhook\n try :\n sys.stdin=self.stdin\n sys.stdout=self.stdout\n sys.displayhook=self.displayhook\n exec(code,globals,locals)\n finally :\n sys.stdout=save_stdout\n sys.stdin=save_stdin\n sys.displayhook=save_displayhook\n except :\n exc_info=sys.exc_info()[:2]\n self.error(traceback.format_exception_only(*exc_info)[-1].strip())\n \n def precmd(self,line):\n ''\n if not line.strip():\n return line\n args=line.split()\n while args[0]in self.aliases:\n line=self.aliases[args[0]]\n ii=1\n for tmpArg in args[1:]:\n line=line.replace(\"%\"+str(ii),\n tmpArg)\n ii +=1\n line=line.replace(\"%*\",' '.join(args[1:]))\n args=line.split()\n \n \n if args[0]!='alias':\n marker=line.find(';;')\n if marker >=0:\n \n next=line[marker+2:].lstrip()\n self.cmdqueue.append(next)\n line=line[:marker].rstrip()\n return line\n \n def onecmd(self,line):\n ''\n\n\n\n\n \n if not self.commands_defining:\n return cmd.Cmd.onecmd(self,line)\n else :\n return self.handle_command_def(line)\n \n def handle_command_def(self,line):\n ''\n cmd,arg,line=self.parseline(line)\n if not cmd:\n return\n if cmd =='silent':\n self.commands_silent[self.commands_bnum]=True\n return\n elif cmd =='end':\n self.cmdqueue=[]\n return 1\n cmdlist=self.commands[self.commands_bnum]\n if arg:\n cmdlist.append(cmd+' '+arg)\n else :\n cmdlist.append(cmd)\n \n try :\n func=getattr(self,'do_'+cmd)\n except AttributeError:\n func=self.default\n \n if func.__name__ in self.commands_resuming:\n self.commands_doprompt[self.commands_bnum]=False\n self.cmdqueue=[]\n return 1\n return\n \n \n \n def message(self,msg):\n print(msg,file=self.stdout)\n \n def error(self,msg):\n print('***',msg,file=self.stdout)\n \n \n \n \n def _complete_location(self,text,line,begidx,endidx):\n \n if line.strip().endswith((':',',')):\n \n return []\n \n try :\n ret=self._complete_expression(text,line,begidx,endidx)\n except Exception:\n ret=[]\n \n globs=glob.glob(text+'*')\n for fn in globs:\n if os.path.isdir(fn):\n ret.append(fn+'/')\n elif os.path.isfile(fn)and fn.lower().endswith(('.py','.pyw')):\n ret.append(fn+':')\n return ret\n \n def _complete_bpnumber(self,text,line,begidx,endidx):\n \n \n \n return [str(i)for i,bp in enumerate(bdb.Breakpoint.bpbynumber)\n if bp is not None and str(i).startswith(text)]\n \n def _complete_expression(self,text,line,begidx,endidx):\n \n if not self.curframe:\n return []\n \n \n \n ns=self.curframe.f_globals.copy()\n ns.update(self.curframe_locals)\n if '.'in text:\n \n \n \n dotted=text.split('.')\n try :\n obj=ns[dotted[0]]\n for part in dotted[1:-1]:\n obj=getattr(obj,part)\n except (KeyError,AttributeError):\n return []\n prefix='.'.join(dotted[:-1])+'.'\n return [prefix+n for n in dir(obj)if n.startswith(dotted[-1])]\n else :\n \n return [n for n in ns.keys()if n.startswith(text)]\n \n \n \n \n \n def do_commands(self,arg):\n ''\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n \n if not arg:\n bnum=len(bdb.Breakpoint.bpbynumber)-1\n else :\n try :\n bnum=int(arg)\n except :\n self.error(\"Usage: commands [bnum]\\n ...\\n end\")\n return\n self.commands_bnum=bnum\n \n if bnum in self.commands:\n old_command_defs=(self.commands[bnum],\n self.commands_doprompt[bnum],\n self.commands_silent[bnum])\n else :\n old_command_defs=None\n self.commands[bnum]=[]\n self.commands_doprompt[bnum]=True\n self.commands_silent[bnum]=False\n \n prompt_back=self.prompt\n self.prompt='(com) '\n self.commands_defining=True\n try :\n self.cmdloop()\n except KeyboardInterrupt:\n \n if old_command_defs:\n self.commands[bnum]=old_command_defs[0]\n self.commands_doprompt[bnum]=old_command_defs[1]\n self.commands_silent[bnum]=old_command_defs[2]\n else :\n del self.commands[bnum]\n del self.commands_doprompt[bnum]\n del self.commands_silent[bnum]\n self.error('command definition aborted, old commands restored')\n finally :\n self.commands_defining=False\n self.prompt=prompt_back\n \n complete_commands=_complete_bpnumber\n \n def do_break(self,arg,temporary=0):\n ''\n\n\n\n\n\n\n\n\n\n\n\n\n \n if not arg:\n if self.breaks:\n self.message(\"Num Type Disp Enb Where\")\n for bp in bdb.Breakpoint.bpbynumber:\n if bp:\n self.message(bp.bpformat())\n return\n \n \n filename=None\n lineno=None\n cond=None\n comma=arg.find(',')\n if comma >0:\n \n cond=arg[comma+1:].lstrip()\n arg=arg[:comma].rstrip()\n \n colon=arg.rfind(':')\n funcname=None\n if colon >=0:\n filename=arg[:colon].rstrip()\n f=self.lookupmodule(filename)\n if not f:\n self.error('%r not found from sys.path'%filename)\n return\n else :\n filename=f\n arg=arg[colon+1:].lstrip()\n try :\n lineno=int(arg)\n except ValueError:\n self.error('Bad lineno: %s'%arg)\n return\n else :\n \n try :\n lineno=int(arg)\n except ValueError:\n try :\n func=eval(arg,\n self.curframe.f_globals,\n self.curframe_locals)\n except :\n func=arg\n try :\n if hasattr(func,'__func__'):\n func=func.__func__\n code=func.__code__\n \n \n funcname=code.co_name\n lineno=code.co_firstlineno\n filename=code.co_filename\n except :\n \n (ok,filename,ln)=self.lineinfo(arg)\n if not ok:\n self.error('The specified object %r is not a function '\n 'or was not found along sys.path.'%arg)\n return\n funcname=ok\n lineno=int(ln)\n if not filename:\n filename=self.defaultFile()\n \n line=self.checkline(filename,lineno)\n if line:\n \n err=self.set_break(filename,line,temporary,cond,funcname)\n if err:\n self.error(err)\n else :\n bp=self.get_breaks(filename,line)[-1]\n self.message(\"Breakpoint %d at %s:%d\"%\n (bp.number,bp.file,bp.line))\n \n \n def defaultFile(self):\n ''\n filename=self.curframe.f_code.co_filename\n if filename =='<string>'and self.mainpyfile:\n filename=self.mainpyfile\n return filename\n \n do_b=do_break\n \n complete_break=_complete_location\n complete_b=_complete_location\n \n def do_tbreak(self,arg):\n ''\n\n\n \n self.do_break(arg,1)\n \n complete_tbreak=_complete_location\n \n def lineinfo(self,identifier):\n failed=(None ,None ,None )\n \n idstring=identifier.split(\"'\")\n if len(idstring)==1:\n \n id=idstring[0].strip()\n elif len(idstring)==3:\n \n id=idstring[1].strip()\n else :\n return failed\n if id =='':return failed\n parts=id.split('.')\n \n if parts[0]=='self':\n del parts[0]\n if len(parts)==0:\n return failed\n \n fname=self.defaultFile()\n if len(parts)==1:\n item=parts[0]\n else :\n \n \n f=self.lookupmodule(parts[0])\n if f:\n fname=f\n item=parts[1]\n answer=find_function(item,fname)\n return answer or failed\n \n def checkline(self,filename,lineno):\n ''\n\n\n\n \n \n \n globs=self.curframe.f_globals if hasattr(self,'curframe')else None\n line=linecache.getline(filename,lineno,globs)\n if not line:\n self.message('End of file')\n return 0\n line=line.strip()\n \n if (not line or (line[0]=='#')or\n (line[:3]=='\"\"\"')or line[:3]==\"'''\"):\n self.error('Blank or comment')\n return 0\n return lineno\n \n def do_enable(self,arg):\n ''\n\n\n \n args=arg.split()\n for i in args:\n try :\n bp=self.get_bpbynumber(i)\n except ValueError as err:\n self.error(err)\n else :\n bp.enable()\n self.message('Enabled %s'%bp)\n \n complete_enable=_complete_bpnumber\n \n def do_disable(self,arg):\n ''\n\n\n\n\n\n \n args=arg.split()\n for i in args:\n try :\n bp=self.get_bpbynumber(i)\n except ValueError as err:\n self.error(err)\n else :\n bp.disable()\n self.message('Disabled %s'%bp)\n \n complete_disable=_complete_bpnumber\n \n def do_condition(self,arg):\n ''\n\n\n\n\n \n args=arg.split(' ',1)\n try :\n cond=args[1]\n except IndexError:\n cond=None\n try :\n bp=self.get_bpbynumber(args[0].strip())\n except IndexError:\n self.error('Breakpoint number expected')\n except ValueError as err:\n self.error(err)\n else :\n bp.cond=cond\n if not cond:\n self.message('Breakpoint %d is now unconditional.'%bp.number)\n else :\n self.message('New condition set for breakpoint %d.'%bp.number)\n \n complete_condition=_complete_bpnumber\n \n def do_ignore(self,arg):\n ''\n\n\n\n\n\n\n \n args=arg.split()\n try :\n count=int(args[1].strip())\n except :\n count=0\n try :\n bp=self.get_bpbynumber(args[0].strip())\n except IndexError:\n self.error('Breakpoint number expected')\n except ValueError as err:\n self.error(err)\n else :\n bp.ignore=count\n if count >0:\n if count >1:\n countstr='%d crossings'%count\n else :\n countstr='1 crossing'\n self.message('Will ignore next %s of breakpoint %d.'%\n (countstr,bp.number))\n else :\n self.message('Will stop next time breakpoint %d is reached.'\n %bp.number)\n \n complete_ignore=_complete_bpnumber\n \n def do_clear(self,arg):\n ''\n\n\n\n\n \n if not arg:\n try :\n reply=input('Clear all breaks? ')\n except EOFError:\n reply='no'\n reply=reply.strip().lower()\n if reply in ('y','yes'):\n bplist=[bp for bp in bdb.Breakpoint.bpbynumber if bp]\n self.clear_all_breaks()\n for bp in bplist:\n self.message('Deleted %s'%bp)\n return\n if ':'in arg:\n \n i=arg.rfind(':')\n filename=arg[:i]\n arg=arg[i+1:]\n try :\n lineno=int(arg)\n except ValueError:\n err=\"Invalid line number (%s)\"%arg\n else :\n bplist=self.get_breaks(filename,lineno)\n err=self.clear_break(filename,lineno)\n if err:\n self.error(err)\n else :\n for bp in bplist:\n self.message('Deleted %s'%bp)\n return\n numberlist=arg.split()\n for i in numberlist:\n try :\n bp=self.get_bpbynumber(i)\n except ValueError as err:\n self.error(err)\n else :\n self.clear_bpbynumber(i)\n self.message('Deleted %s'%bp)\n do_cl=do_clear\n \n complete_clear=_complete_location\n complete_cl=_complete_location\n \n def do_where(self,arg):\n ''\n\n\n\n \n self.print_stack_trace()\n do_w=do_where\n do_bt=do_where\n \n def _select_frame(self,number):\n assert 0 <=number <len(self.stack)\n self.curindex=number\n self.curframe=self.stack[self.curindex][0]\n self.curframe_locals=self.curframe.f_locals\n self.print_stack_entry(self.stack[self.curindex])\n self.lineno=None\n \n def do_up(self,arg):\n ''\n\n\n \n if self.curindex ==0:\n self.error('Oldest frame')\n return\n try :\n count=int(arg or 1)\n except ValueError:\n self.error('Invalid frame count (%s)'%arg)\n return\n if count <0:\n newframe=0\n else :\n newframe=max(0,self.curindex -count)\n self._select_frame(newframe)\n do_u=do_up\n \n def do_down(self,arg):\n ''\n\n\n \n if self.curindex+1 ==len(self.stack):\n self.error('Newest frame')\n return\n try :\n count=int(arg or 1)\n except ValueError:\n self.error('Invalid frame count (%s)'%arg)\n return\n if count <0:\n newframe=len(self.stack)-1\n else :\n newframe=min(len(self.stack)-1,self.curindex+count)\n self._select_frame(newframe)\n do_d=do_down\n \n def do_until(self,arg):\n ''\n\n\n\n\n\n \n if arg:\n try :\n lineno=int(arg)\n except ValueError:\n self.error('Error in argument: %r'%arg)\n return\n if lineno <=self.curframe.f_lineno:\n self.error('\"until\" line number is smaller than current '\n 'line number')\n return\n else :\n lineno=None\n self.set_until(self.curframe,lineno)\n return 1\n do_unt=do_until\n \n def do_step(self,arg):\n ''\n\n\n\n \n self.set_step()\n return 1\n do_s=do_step\n \n def do_next(self,arg):\n ''\n\n\n \n self.set_next(self.curframe)\n return 1\n do_n=do_next\n \n def do_run(self,arg):\n ''\n\n\n\n\n \n if arg:\n import shlex\n argv0=sys.argv[0:1]\n sys.argv=shlex.split(arg)\n sys.argv[:0]=argv0\n \n raise Restart\n \n do_restart=do_run\n \n def do_return(self,arg):\n ''\n\n \n self.set_return(self.curframe)\n return 1\n do_r=do_return\n \n def do_continue(self,arg):\n ''\n\n \n if not self.nosigint:\n try :\n Pdb._previous_sigint_handler=\\\n signal.signal(signal.SIGINT,self.sigint_handler)\n except ValueError:\n \n \n \n \n pass\n self.set_continue()\n return 1\n do_c=do_cont=do_continue\n \n def do_jump(self,arg):\n ''\n\n\n\n\n\n\n\n\n \n if self.curindex+1 !=len(self.stack):\n self.error('You can only jump within the bottom frame')\n return\n try :\n arg=int(arg)\n except ValueError:\n self.error(\"The 'jump' command requires a line number\")\n else :\n try :\n \n \n self.curframe.f_lineno=arg\n self.stack[self.curindex]=self.stack[self.curindex][0],arg\n self.print_stack_entry(self.stack[self.curindex])\n except ValueError as e:\n self.error('Jump failed: %s'%e)\n do_j=do_jump\n \n def do_debug(self,arg):\n ''\n\n\n\n \n sys.settrace(None )\n globals=self.curframe.f_globals\n locals=self.curframe_locals\n p=Pdb(self.completekey,self.stdin,self.stdout)\n p.prompt=\"(%s) \"%self.prompt.strip()\n self.message(\"ENTERING RECURSIVE DEBUGGER\")\n sys.call_tracing(p.run,(arg,globals,locals))\n self.message(\"LEAVING RECURSIVE DEBUGGER\")\n sys.settrace(self.trace_dispatch)\n self.lastcmd=p.lastcmd\n \n complete_debug=_complete_expression\n \n def do_quit(self,arg):\n ''\n\n \n self._user_requested_quit=True\n self.set_quit()\n return 1\n \n do_q=do_quit\n do_exit=do_quit\n \n def do_EOF(self,arg):\n ''\n\n \n self.message('')\n self._user_requested_quit=True\n self.set_quit()\n return 1\n \n def do_args(self,arg):\n ''\n\n \n co=self.curframe.f_code\n dict=self.curframe_locals\n n=co.co_argcount\n if co.co_flags&4:n=n+1\n if co.co_flags&8:n=n+1\n for i in range(n):\n name=co.co_varnames[i]\n if name in dict:\n self.message('%s = %r'%(name,dict[name]))\n else :\n self.message('%s = *** undefined ***'%(name,))\n do_a=do_args\n \n def do_retval(self,arg):\n ''\n\n \n if '__return__'in self.curframe_locals:\n self.message(repr(self.curframe_locals['__return__']))\n else :\n self.error('Not yet returned!')\n do_rv=do_retval\n \n def _getval(self,arg):\n try :\n return eval(arg,self.curframe.f_globals,self.curframe_locals)\n except :\n exc_info=sys.exc_info()[:2]\n self.error(traceback.format_exception_only(*exc_info)[-1].strip())\n raise\n \n def _getval_except(self,arg,frame=None ):\n try :\n if frame is None :\n return eval(arg,self.curframe.f_globals,self.curframe_locals)\n else :\n return eval(arg,frame.f_globals,frame.f_locals)\n except :\n exc_info=sys.exc_info()[:2]\n err=traceback.format_exception_only(*exc_info)[-1].strip()\n return _rstr('** raised %s **'%err)\n \n def do_p(self,arg):\n ''\n\n \n try :\n self.message(repr(self._getval(arg)))\n except :\n pass\n \n def do_pp(self,arg):\n ''\n\n \n try :\n self.message(pprint.pformat(self._getval(arg)))\n except :\n pass\n \n complete_print=_complete_expression\n complete_p=_complete_expression\n complete_pp=_complete_expression\n \n def do_list(self,arg):\n ''\n\n\n\n\n\n\n\n\n\n\n\n\n \n self.lastcmd='list'\n last=None\n if arg and arg !='.':\n try :\n if ','in arg:\n first,last=arg.split(',')\n first=int(first.strip())\n last=int(last.strip())\n if last <first:\n \n last=first+last\n else :\n first=int(arg.strip())\n first=max(1,first -5)\n except ValueError:\n self.error('Error in argument: %r'%arg)\n return\n elif self.lineno is None or arg =='.':\n first=max(1,self.curframe.f_lineno -5)\n else :\n first=self.lineno+1\n if last is None :\n last=first+10\n filename=self.curframe.f_code.co_filename\n breaklist=self.get_file_breaks(filename)\n try :\n lines=linecache.getlines(filename,self.curframe.f_globals)\n self._print_lines(lines[first -1:last],first,breaklist,\n self.curframe)\n self.lineno=min(last,len(lines))\n if len(lines)<last:\n self.message('[EOF]')\n except KeyboardInterrupt:\n pass\n do_l=do_list\n \n def do_longlist(self,arg):\n ''\n\n \n filename=self.curframe.f_code.co_filename\n breaklist=self.get_file_breaks(filename)\n try :\n lines,lineno=getsourcelines(self.curframe)\n except OSError as err:\n self.error(err)\n return\n self._print_lines(lines,lineno,breaklist,self.curframe)\n do_ll=do_longlist\n \n def do_source(self,arg):\n ''\n\n \n try :\n obj=self._getval(arg)\n except :\n return\n try :\n lines,lineno=getsourcelines(obj)\n except (OSError,TypeError)as err:\n self.error(err)\n return\n self._print_lines(lines,lineno)\n \n complete_source=_complete_expression\n \n def _print_lines(self,lines,start,breaks=(),frame=None ):\n ''\n if frame:\n current_lineno=frame.f_lineno\n exc_lineno=self.tb_lineno.get(frame,-1)\n else :\n current_lineno=exc_lineno=-1\n for lineno,line in enumerate(lines,start):\n s=str(lineno).rjust(3)\n if len(s)<4:\n s +=' '\n if lineno in breaks:\n s +='B'\n else :\n s +=' '\n if lineno ==current_lineno:\n s +='->'\n elif lineno ==exc_lineno:\n s +='>>'\n self.message(s+'\\t'+line.rstrip())\n \n def do_whatis(self,arg):\n ''\n\n \n try :\n value=self._getval(arg)\n except :\n \n return\n code=None\n \n try :\n code=value.__code__\n except Exception:\n pass\n if code:\n self.message('Function %s'%code.co_name)\n return\n \n try :\n code=value.__func__.__code__\n except Exception:\n pass\n if code:\n self.message('Method %s'%code.co_name)\n return\n \n if value.__class__ is type:\n self.message('Class %s.%s'%(value.__module__,value.__qualname__))\n return\n \n self.message(type(value))\n \n complete_whatis=_complete_expression\n \n def do_display(self,arg):\n ''\n\n\n\n\n\n \n if not arg:\n self.message('Currently displaying:')\n for item in self.displaying.get(self.curframe,{}).items():\n self.message('%s: %r'%item)\n else :\n val=self._getval_except(arg)\n self.displaying.setdefault(self.curframe,{})[arg]=val\n self.message('display %s: %r'%(arg,val))\n \n complete_display=_complete_expression\n \n def do_undisplay(self,arg):\n ''\n\n\n\n\n \n if arg:\n try :\n del self.displaying.get(self.curframe,{})[arg]\n except KeyError:\n self.error('not displaying %s'%arg)\n else :\n self.displaying.pop(self.curframe,None )\n \n def complete_undisplay(self,text,line,begidx,endidx):\n return [e for e in self.displaying.get(self.curframe,{})\n if e.startswith(text)]\n \n def do_interact(self,arg):\n ''\n\n\n\n \n ns=self.curframe.f_globals.copy()\n ns.update(self.curframe_locals)\n code.interact(\"*interactive*\",local=ns)\n \n def do_alias(self,arg):\n ''\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n \n args=arg.split()\n if len(args)==0:\n keys=sorted(self.aliases.keys())\n for alias in keys:\n self.message(\"%s = %s\"%(alias,self.aliases[alias]))\n return\n if args[0]in self.aliases and len(args)==1:\n self.message(\"%s = %s\"%(args[0],self.aliases[args[0]]))\n else :\n self.aliases[args[0]]=' '.join(args[1:])\n \n def do_unalias(self,arg):\n ''\n\n \n args=arg.split()\n if len(args)==0:return\n if args[0]in self.aliases:\n del self.aliases[args[0]]\n \n def complete_unalias(self,text,line,begidx,endidx):\n return [a for a in self.aliases if a.startswith(text)]\n \n \n commands_resuming=['do_continue','do_step','do_next','do_return',\n 'do_quit','do_jump']\n \n \n \n \n \n \n \n \n \n def print_stack_trace(self):\n try :\n for frame_lineno in self.stack:\n self.print_stack_entry(frame_lineno)\n except KeyboardInterrupt:\n pass\n \n def print_stack_entry(self,frame_lineno,prompt_prefix=line_prefix):\n frame,lineno=frame_lineno\n if frame is self.curframe:\n prefix='> '\n else :\n prefix=' '\n self.message(prefix+\n self.format_stack_entry(frame_lineno,prompt_prefix))\n \n \n \n def do_help(self,arg):\n ''\n\n\n\n\n \n if not arg:\n return cmd.Cmd.do_help(self,arg)\n try :\n try :\n topic=getattr(self,'help_'+arg)\n return topic()\n except AttributeError:\n command=getattr(self,'do_'+arg)\n except AttributeError:\n self.error('No help for %r'%arg)\n else :\n if sys.flags.optimize >=2:\n self.error('No help for %r; please do not run Python with -OO '\n 'if you need command help'%arg)\n return\n self.message(command.__doc__.rstrip())\n \n do_h=do_help\n \n def help_exec(self):\n ''\n\n\n\n\n\n\n\n \n self.message((self.help_exec.__doc__ or '').strip())\n \n def help_pdb(self):\n help()\n \n \n \n def lookupmodule(self,filename):\n ''\n\n\n\n \n if os.path.isabs(filename)and os.path.exists(filename):\n return filename\n f=os.path.join(sys.path[0],filename)\n if os.path.exists(f)and self.canonic(f)==self.mainpyfile:\n return f\n root,ext=os.path.splitext(filename)\n if ext =='':\n filename=filename+'.py'\n if os.path.isabs(filename):\n return filename\n for dirname in sys.path:\n while os.path.islink(dirname):\n dirname=os.readlink(dirname)\n fullname=os.path.join(dirname,filename)\n if os.path.exists(fullname):\n return fullname\n return None\n \n def _runmodule(self,module_name):\n self._wait_for_mainpyfile=True\n self._user_requested_quit=False\n import runpy\n mod_name,mod_spec,code=runpy._get_module_details(module_name)\n self.mainpyfile=self.canonic(code.co_filename)\n import __main__\n __main__.__dict__.clear()\n __main__.__dict__.update({\n \"__name__\":\"__main__\",\n \"__file__\":self.mainpyfile,\n \"__package__\":mod_spec.parent,\n \"__loader__\":mod_spec.loader,\n \"__spec__\":mod_spec,\n \"__builtins__\":__builtins__,\n })\n self.run(code)\n \n def _runscript(self,filename):\n \n \n \n \n \n import __main__\n __main__.__dict__.clear()\n __main__.__dict__.update({\"__name__\":\"__main__\",\n \"__file__\":filename,\n \"__builtins__\":__builtins__,\n })\n \n \n \n \n \n \n self._wait_for_mainpyfile=True\n self.mainpyfile=self.canonic(filename)\n self._user_requested_quit=False\n with open(filename,\"rb\")as fp:\n statement=\"exec(compile(%r, %r, 'exec'))\"%\\\n (fp.read(),self.mainpyfile)\n self.run(statement)\n \n \n \nif __doc__ is not None :\n\n _help_order=[\n 'help','where','down','up','break','tbreak','clear','disable',\n 'enable','ignore','condition','commands','step','next','until',\n 'jump','return','retval','run','continue','list','longlist',\n 'args','p','pp','whatis','source','display','undisplay',\n 'interact','alias','unalias','debug','quit',\n ]\n \n for _command in _help_order:\n __doc__ +=getattr(Pdb,'do_'+_command).__doc__.strip()+'\\n\\n'\n __doc__ +=Pdb.help_exec.__doc__\n \n del _help_order,_command\n \n \n \n \ndef run(statement,globals=None ,locals=None ):\n Pdb().run(statement,globals,locals)\n \ndef runeval(expression,globals=None ,locals=None ):\n return Pdb().runeval(expression,globals,locals)\n \ndef runctx(statement,globals,locals):\n\n run(statement,globals,locals)\n \ndef runcall(*args,**kwds):\n return Pdb().runcall(*args,**kwds)\n \ndef set_trace(*,header=None ):\n pdb=Pdb()\n if header is not None :\n pdb.message(header)\n pdb.set_trace(sys._getframe().f_back)\n \n \n \ndef post_mortem(t=None ):\n\n if t is None :\n \n \n t=sys.exc_info()[2]\n if t is None :\n raise ValueError(\"A valid traceback must be passed if no \"\n \"exception is being handled\")\n \n p=Pdb()\n p.reset()\n p.interaction(None ,t)\n \ndef pm():\n post_mortem(sys.last_traceback)\n \n \n \n \nTESTCMD='import x; x.main()'\n\ndef test():\n run(TESTCMD)\n \n \ndef help():\n import pydoc\n pydoc.pager(__doc__)\n \n_usage=\"\"\"\\\nusage: pdb.py [-c command] ... [-m module | pyfile] [arg] ...\n\nDebug the Python program given by pyfile. Alternatively,\nan executable module or package to debug can be specified using\nthe -m switch.\n\nInitial commands are read from .pdbrc files in your home directory\nand in the current directory, if they exist. Commands supplied with\n-c are executed after commands from .pdbrc files.\n\nTo let the script run until an exception occurs, use \"-c continue\".\nTo let the script run up to a given line X in the debugged file, use\n\"-c 'until X'\".\"\"\"\n\ndef main():\n import getopt\n \n opts,args=getopt.getopt(sys.argv[1:],'mhc:',['--help','--command='])\n \n if not args:\n print(_usage)\n sys.exit(2)\n \n commands=[]\n run_as_module=False\n for opt,optarg in opts:\n if opt in ['-h','--help']:\n print(_usage)\n sys.exit()\n elif opt in ['-c','--command']:\n commands.append(optarg)\n elif opt in ['-m']:\n run_as_module=True\n \n mainpyfile=args[0]\n if not run_as_module and not os.path.exists(mainpyfile):\n print('Error:',mainpyfile,'does not exist')\n sys.exit(1)\n \n sys.argv[:]=args\n \n \n if not run_as_module:\n sys.path[0]=os.path.dirname(mainpyfile)\n \n \n \n \n \n pdb=Pdb()\n pdb.rcLines.extend(commands)\n while True :\n try :\n if run_as_module:\n pdb._runmodule(mainpyfile)\n else :\n pdb._runscript(mainpyfile)\n if pdb._user_requested_quit:\n break\n print(\"The program finished and will be restarted\")\n except Restart:\n print(\"Restarting\",mainpyfile,\"with arguments:\")\n print(\"\\t\"+\" \".join(args))\n except SystemExit:\n \n print(\"The program exited via sys.exit(). Exit status:\",end=' ')\n print(sys.exc_info()[1])\n except SyntaxError:\n traceback.print_exc()\n sys.exit(1)\n except :\n traceback.print_exc()\n print(\"Uncaught exception. Entering post mortem debugging\")\n print(\"Running 'cont' or 'step' will restart the program\")\n t=sys.exc_info()[2]\n pdb.interaction(None ,t)\n print(\"Post mortem debugger finished. The \"+mainpyfile+\n \" will be restarted\")\n \n \n \nif __name__ =='__main__':\n import pdb\n pdb.main()\n", ["__main__", "bdb", "cmd", "code", "dis", "getopt", "glob", "inspect", "linecache", "os", "pdb", "pprint", "pydoc", "re", "readline", "runpy", "shlex", "signal", "sys", "traceback"]], "bdb": [".py", "''\n\nimport fnmatch\nimport sys\nimport os\nfrom inspect import CO_GENERATOR,CO_COROUTINE,CO_ASYNC_GENERATOR\n\n__all__=[\"BdbQuit\",\"Bdb\",\"Breakpoint\"]\n\nGENERATOR_AND_COROUTINE_FLAGS=CO_GENERATOR |CO_COROUTINE |CO_ASYNC_GENERATOR\n\n\nclass BdbQuit(Exception):\n ''\n \n \nclass Bdb:\n ''\n\n\n\n\n\n\n\n\n\n\n \n \n def __init__(self,skip=None ):\n self.skip=set(skip)if skip else None\n self.breaks={}\n self.fncache={}\n self.frame_returning=None\n \n def canonic(self,filename):\n ''\n\n\n\n\n\n \n if filename ==\"<\"+filename[1:-1]+\">\":\n return filename\n canonic=self.fncache.get(filename)\n if not canonic:\n canonic=os.path.abspath(filename)\n canonic=os.path.normcase(canonic)\n self.fncache[filename]=canonic\n return canonic\n \n def reset(self):\n ''\n import linecache\n linecache.checkcache()\n self.botframe=None\n self._set_stopinfo(None ,None )\n \n def trace_dispatch(self,frame,event,arg):\n ''\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n \n if self.quitting:\n return\n if event =='line':\n return self.dispatch_line(frame)\n if event =='call':\n return self.dispatch_call(frame,arg)\n if event =='return':\n return self.dispatch_return(frame,arg)\n if event =='exception':\n return self.dispatch_exception(frame,arg)\n if event =='c_call':\n return self.trace_dispatch\n if event =='c_exception':\n return self.trace_dispatch\n if event =='c_return':\n return self.trace_dispatch\n print('bdb.Bdb.dispatch: unknown debugging event:',repr(event))\n return self.trace_dispatch\n \n def dispatch_line(self,frame):\n ''\n\n\n\n\n \n if self.stop_here(frame)or self.break_here(frame):\n self.user_line(frame)\n if self.quitting:raise BdbQuit\n return self.trace_dispatch\n \n def dispatch_call(self,frame,arg):\n ''\n\n\n\n\n \n \n if self.botframe is None :\n \n self.botframe=frame.f_back\n return self.trace_dispatch\n if not (self.stop_here(frame)or self.break_anywhere(frame)):\n \n return\n \n if self.stopframe and frame.f_code.co_flags&GENERATOR_AND_COROUTINE_FLAGS:\n return self.trace_dispatch\n self.user_call(frame,arg)\n if self.quitting:raise BdbQuit\n return self.trace_dispatch\n \n def dispatch_return(self,frame,arg):\n ''\n\n\n\n\n \n if self.stop_here(frame)or frame ==self.returnframe:\n \n if self.stopframe and frame.f_code.co_flags&GENERATOR_AND_COROUTINE_FLAGS:\n return self.trace_dispatch\n try :\n self.frame_returning=frame\n self.user_return(frame,arg)\n finally :\n self.frame_returning=None\n if self.quitting:raise BdbQuit\n \n if self.stopframe is frame and self.stoplineno !=-1:\n self._set_stopinfo(None ,None )\n return self.trace_dispatch\n \n def dispatch_exception(self,frame,arg):\n ''\n\n\n\n\n \n if self.stop_here(frame):\n \n \n \n if not (frame.f_code.co_flags&GENERATOR_AND_COROUTINE_FLAGS\n and arg[0]is StopIteration and arg[2]is None ):\n self.user_exception(frame,arg)\n if self.quitting:raise BdbQuit\n \n \n \n \n elif (self.stopframe and frame is not self.stopframe\n and self.stopframe.f_code.co_flags&GENERATOR_AND_COROUTINE_FLAGS\n and arg[0]in (StopIteration,GeneratorExit)):\n self.user_exception(frame,arg)\n if self.quitting:raise BdbQuit\n \n return self.trace_dispatch\n \n \n \n \n \n def is_skipped_module(self,module_name):\n ''\n for pattern in self.skip:\n if fnmatch.fnmatch(module_name,pattern):\n return True\n return False\n \n def stop_here(self,frame):\n ''\n \n \n if self.skip and\\\n self.is_skipped_module(frame.f_globals.get('__name__')):\n return False\n if frame is self.stopframe:\n if self.stoplineno ==-1:\n return False\n return frame.f_lineno >=self.stoplineno\n if not self.stopframe:\n return True\n return False\n \n def break_here(self,frame):\n ''\n\n\n\n \n filename=self.canonic(frame.f_code.co_filename)\n if filename not in self.breaks:\n return False\n lineno=frame.f_lineno\n if lineno not in self.breaks[filename]:\n \n \n lineno=frame.f_code.co_firstlineno\n if lineno not in self.breaks[filename]:\n return False\n \n \n (bp,flag)=effective(filename,lineno,frame)\n if bp:\n self.currentbp=bp.number\n if (flag and bp.temporary):\n self.do_clear(str(bp.number))\n return True\n else :\n return False\n \n def do_clear(self,arg):\n ''\n\n\n \n raise NotImplementedError(\"subclass of bdb must implement do_clear()\")\n \n def break_anywhere(self,frame):\n ''\n \n return self.canonic(frame.f_code.co_filename)in self.breaks\n \n \n \n \n def user_call(self,frame,argument_list):\n ''\n pass\n \n def user_line(self,frame):\n ''\n pass\n \n def user_return(self,frame,return_value):\n ''\n pass\n \n def user_exception(self,frame,exc_info):\n ''\n pass\n \n def _set_stopinfo(self,stopframe,returnframe,stoplineno=0):\n ''\n\n\n\n\n \n self.stopframe=stopframe\n self.returnframe=returnframe\n self.quitting=False\n \n \n self.stoplineno=stoplineno\n \n \n \n \n def set_until(self,frame,lineno=None ):\n ''\n \n \n if lineno is None :\n lineno=frame.f_lineno+1\n self._set_stopinfo(frame,frame,lineno)\n \n def set_step(self):\n ''\n \n \n \n \n if self.frame_returning:\n caller_frame=self.frame_returning.f_back\n if caller_frame and not caller_frame.f_trace:\n caller_frame.f_trace=self.trace_dispatch\n self._set_stopinfo(None ,None )\n \n def set_next(self,frame):\n ''\n self._set_stopinfo(frame,None )\n \n def set_return(self,frame):\n ''\n if frame.f_code.co_flags&GENERATOR_AND_COROUTINE_FLAGS:\n self._set_stopinfo(frame,None ,-1)\n else :\n self._set_stopinfo(frame.f_back,frame)\n \n def set_trace(self,frame=None ):\n ''\n\n\n \n if frame is None :\n frame=sys._getframe().f_back\n self.reset()\n while frame:\n frame.f_trace=self.trace_dispatch\n self.botframe=frame\n frame=frame.f_back\n self.set_step()\n sys.settrace(self.trace_dispatch)\n \n def set_continue(self):\n ''\n\n\n \n \n self._set_stopinfo(self.botframe,None ,-1)\n if not self.breaks:\n \n sys.settrace(None )\n frame=sys._getframe().f_back\n while frame and frame is not self.botframe:\n del frame.f_trace\n frame=frame.f_back\n \n def set_quit(self):\n ''\n\n\n \n self.stopframe=self.botframe\n self.returnframe=None\n self.quitting=True\n sys.settrace(None )\n \n \n \n \n \n \n \n \n def set_break(self,filename,lineno,temporary=False ,cond=None ,\n funcname=None ):\n ''\n\n\n\n \n filename=self.canonic(filename)\n import linecache\n line=linecache.getline(filename,lineno)\n if not line:\n return 'Line %s:%d does not exist'%(filename,lineno)\n list=self.breaks.setdefault(filename,[])\n if lineno not in list:\n list.append(lineno)\n bp=Breakpoint(filename,lineno,temporary,cond,funcname)\n return None\n \n def _prune_breaks(self,filename,lineno):\n ''\n\n\n\n\n\n \n if (filename,lineno)not in Breakpoint.bplist:\n self.breaks[filename].remove(lineno)\n if not self.breaks[filename]:\n del self.breaks[filename]\n \n def clear_break(self,filename,lineno):\n ''\n\n\n \n filename=self.canonic(filename)\n if filename not in self.breaks:\n return 'There are no breakpoints in %s'%filename\n if lineno not in self.breaks[filename]:\n return 'There is no breakpoint at %s:%d'%(filename,lineno)\n \n \n for bp in Breakpoint.bplist[filename,lineno][:]:\n bp.deleteMe()\n self._prune_breaks(filename,lineno)\n return None\n \n def clear_bpbynumber(self,arg):\n ''\n\n\n \n try :\n bp=self.get_bpbynumber(arg)\n except ValueError as err:\n return str(err)\n bp.deleteMe()\n self._prune_breaks(bp.file,bp.line)\n return None\n \n def clear_all_file_breaks(self,filename):\n ''\n\n\n \n filename=self.canonic(filename)\n if filename not in self.breaks:\n return 'There are no breakpoints in %s'%filename\n for line in self.breaks[filename]:\n blist=Breakpoint.bplist[filename,line]\n for bp in blist:\n bp.deleteMe()\n del self.breaks[filename]\n return None\n \n def clear_all_breaks(self):\n ''\n\n\n \n if not self.breaks:\n return 'There are no breakpoints'\n for bp in Breakpoint.bpbynumber:\n if bp:\n bp.deleteMe()\n self.breaks={}\n return None\n \n def get_bpbynumber(self,arg):\n ''\n\n\n\n \n if not arg:\n raise ValueError('Breakpoint number expected')\n try :\n number=int(arg)\n except ValueError:\n raise ValueError('Non-numeric breakpoint number %s'%arg)from None\n try :\n bp=Breakpoint.bpbynumber[number]\n except IndexError:\n raise ValueError('Breakpoint number %d out of range'%number)from None\n if bp is None :\n raise ValueError('Breakpoint %d already deleted'%number)\n return bp\n \n def get_break(self,filename,lineno):\n ''\n filename=self.canonic(filename)\n return filename in self.breaks and\\\n lineno in self.breaks[filename]\n \n def get_breaks(self,filename,lineno):\n ''\n\n\n \n filename=self.canonic(filename)\n return filename in self.breaks and\\\n lineno in self.breaks[filename]and\\\n Breakpoint.bplist[filename,lineno]or []\n \n def get_file_breaks(self,filename):\n ''\n\n\n \n filename=self.canonic(filename)\n if filename in self.breaks:\n return self.breaks[filename]\n else :\n return []\n \n def get_all_breaks(self):\n ''\n return self.breaks\n \n \n \n \n def get_stack(self,f,t):\n ''\n\n\n\n \n stack=[]\n if t and t.tb_frame is f:\n t=t.tb_next\n while f is not None :\n stack.append((f,f.f_lineno))\n if f is self.botframe:\n break\n f=f.f_back\n stack.reverse()\n i=max(0,len(stack)-1)\n while t is not None :\n stack.append((t.tb_frame,t.tb_lineno))\n t=t.tb_next\n if f is None :\n i=max(0,len(stack)-1)\n return stack,i\n \n def format_stack_entry(self,frame_lineno,lprefix=': '):\n ''\n\n\n\n\n\n\n \n import linecache,reprlib\n frame,lineno=frame_lineno\n filename=self.canonic(frame.f_code.co_filename)\n s='%s(%r)'%(filename,lineno)\n if frame.f_code.co_name:\n s +=frame.f_code.co_name\n else :\n s +=\"<lambda>\"\n if '__args__'in frame.f_locals:\n args=frame.f_locals['__args__']\n else :\n args=None\n if args:\n s +=reprlib.repr(args)\n else :\n s +='()'\n if '__return__'in frame.f_locals:\n rv=frame.f_locals['__return__']\n s +='->'\n s +=reprlib.repr(rv)\n line=linecache.getline(filename,lineno,frame.f_globals)\n if line:\n s +=lprefix+line.strip()\n return s\n \n \n \n \n \n def run(self,cmd,globals=None ,locals=None ):\n ''\n\n\n \n if globals is None :\n import __main__\n globals=__main__.__dict__\n if locals is None :\n locals=globals\n self.reset()\n if isinstance(cmd,str):\n cmd=compile(cmd,\"<string>\",\"exec\")\n sys.settrace(self.trace_dispatch)\n try :\n exec(cmd,globals,locals)\n except BdbQuit:\n pass\n finally :\n self.quitting=True\n sys.settrace(None )\n \n def runeval(self,expr,globals=None ,locals=None ):\n ''\n\n\n \n if globals is None :\n import __main__\n globals=__main__.__dict__\n if locals is None :\n locals=globals\n self.reset()\n sys.settrace(self.trace_dispatch)\n try :\n return eval(expr,globals,locals)\n except BdbQuit:\n pass\n finally :\n self.quitting=True\n sys.settrace(None )\n \n def runctx(self,cmd,globals,locals):\n ''\n \n self.run(cmd,globals,locals)\n \n \n \n def runcall(self,func,*args,**kwds):\n ''\n\n\n \n self.reset()\n sys.settrace(self.trace_dispatch)\n res=None\n try :\n res=func(*args,**kwds)\n except BdbQuit:\n pass\n finally :\n self.quitting=True\n sys.settrace(None )\n return res\n \n \ndef set_trace():\n ''\n Bdb().set_trace()\n \n \nclass Breakpoint:\n ''\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n \n \n \n \n \n next=1\n bplist={}\n bpbynumber=[None ]\n \n \n \n def __init__(self,file,line,temporary=False ,cond=None ,funcname=None ):\n self.funcname=funcname\n \n self.func_first_executable_line=None\n self.file=file\n self.line=line\n self.temporary=temporary\n self.cond=cond\n self.enabled=True\n self.ignore=0\n self.hits=0\n self.number=Breakpoint.next\n Breakpoint.next +=1\n \n self.bpbynumber.append(self)\n if (file,line)in self.bplist:\n self.bplist[file,line].append(self)\n else :\n self.bplist[file,line]=[self]\n \n def deleteMe(self):\n ''\n\n\n\n \n \n index=(self.file,self.line)\n self.bpbynumber[self.number]=None\n self.bplist[index].remove(self)\n if not self.bplist[index]:\n \n del self.bplist[index]\n \n def enable(self):\n ''\n self.enabled=True\n \n def disable(self):\n ''\n self.enabled=False\n \n def bpprint(self,out=None ):\n ''\n\n\n\n \n if out is None :\n out=sys.stdout\n print(self.bpformat(),file=out)\n \n def bpformat(self):\n ''\n\n\n\n\n\n \n if self.temporary:\n disp='del '\n else :\n disp='keep '\n if self.enabled:\n disp=disp+'yes '\n else :\n disp=disp+'no '\n ret='%-4dbreakpoint %s at %s:%d'%(self.number,disp,\n self.file,self.line)\n if self.cond:\n ret +='\\n\\tstop only if %s'%(self.cond,)\n if self.ignore:\n ret +='\\n\\tignore next %d hits'%(self.ignore,)\n if self.hits:\n if self.hits >1:\n ss='s'\n else :\n ss=''\n ret +='\\n\\tbreakpoint already hit %d time%s'%(self.hits,ss)\n return ret\n \n def __str__(self):\n ''\n return 'breakpoint %s at %s:%s'%(self.number,self.file,self.line)\n \n \n \n \ndef checkfuncname(b,frame):\n ''\n\n\n\n\n\n \n if not b.funcname:\n \n if b.line !=frame.f_lineno:\n \n \n return False\n return True\n \n \n if frame.f_code.co_name !=b.funcname:\n \n return False\n \n \n if not b.func_first_executable_line:\n \n b.func_first_executable_line=frame.f_lineno\n \n if b.func_first_executable_line !=frame.f_lineno:\n \n return False\n return True\n \n \n \n \ndef effective(file,line,frame):\n ''\n\n\n\n\n\n \n possibles=Breakpoint.bplist[file,line]\n for b in possibles:\n if not b.enabled:\n continue\n if not checkfuncname(b,frame):\n continue\n \n b.hits +=1\n if not b.cond:\n \n if b.ignore >0:\n b.ignore -=1\n continue\n else :\n \n return (b,True )\n else :\n \n \n \n try :\n val=eval(b.cond,frame.f_globals,frame.f_locals)\n if val:\n if b.ignore >0:\n b.ignore -=1\n \n else :\n return (b,True )\n \n \n except :\n \n \n \n return (b,False )\n return (None ,None )\n \n \n \n \nclass Tdb(Bdb):\n def user_call(self,frame,args):\n name=frame.f_code.co_name\n if not name:name='???'\n print('+++ call',name,args)\n def user_line(self,frame):\n import linecache\n name=frame.f_code.co_name\n if not name:name='???'\n fn=self.canonic(frame.f_code.co_filename)\n line=linecache.getline(fn,frame.f_lineno,frame.f_globals)\n print('+++',fn,frame.f_lineno,name,':',line.strip())\n def user_return(self,frame,retval):\n print('+++ return',retval)\n def user_exception(self,frame,exc_stuff):\n print('+++ exception',exc_stuff)\n self.set_continue()\n \ndef foo(n):\n print('foo(',n,')')\n x=bar(n *10)\n print('bar returned',x)\n \ndef bar(a):\n print('bar(',a,')')\n return a /2\n \ndef test():\n t=Tdb()\n t.run('import bdb; bdb.foo(10)')\n", ["__main__", "fnmatch", "inspect", "linecache", "os", "reprlib", "sys"]], "codeop": [".py", "''\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\nimport __future__\n\n_features=[getattr(__future__,fname)\nfor fname in __future__.all_feature_names]\n\n__all__=[\"compile_command\",\"Compile\",\"CommandCompiler\"]\n\nPyCF_DONT_IMPLY_DEDENT=0x200\n\ndef _maybe_compile(compiler,source,filename,symbol):\n\n for line in source.split(\"\\n\"):\n line=line.strip()\n if line and line[0]!='#':\n break\n else :\n if symbol !=\"eval\":\n source=\"pass\"\n \n err=err1=err2=None\n code=code1=code2=None\n \n try :\n code=compiler(source,filename,symbol)\n except SyntaxError as err:\n pass\n \n try :\n code1=compiler(source+\"\\n\",filename,symbol)\n except SyntaxError as e:\n err1=e\n \n try :\n code2=compiler(source+\"\\n\\n\",filename,symbol)\n except SyntaxError as e:\n err2=e\n \n if code:\n return code\n if not code1 and repr(err1)==repr(err2):\n raise err1\n \ndef _compile(source,filename,symbol):\n return compile(source,filename,symbol,PyCF_DONT_IMPLY_DEDENT)\n \ndef compile_command(source,filename=\"<input>\",symbol=\"single\"):\n ''\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n \n return _maybe_compile(_compile,source,filename,symbol)\n \nclass Compile:\n ''\n\n\n \n def __init__(self):\n self.flags=PyCF_DONT_IMPLY_DEDENT\n \n def __call__(self,source,filename,symbol):\n codeob=compile(source,filename,symbol,self.flags,1)\n for feature in _features:\n if codeob.co_flags&feature.compiler_flag:\n self.flags |=feature.compiler_flag\n return codeob\n \nclass CommandCompiler:\n ''\n\n\n\n \n \n def __init__(self,):\n self.compiler=Compile()\n \n def __call__(self,source,filename=\"<input>\",symbol=\"single\"):\n ''\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n \n return _maybe_compile(self.compiler,source,filename,symbol)\n", ["__future__"]], "enum": [".py", "import sys\nfrom types import MappingProxyType,DynamicClassAttribute\n\n\ntry :\n from _collections import OrderedDict\nexcept ImportError:\n from collections import OrderedDict\n \n \n__all__=[\n'EnumMeta',\n'Enum','IntEnum','Flag','IntFlag',\n'auto','unique',\n]\n\n\ndef _is_descriptor(obj):\n ''\n return (\n hasattr(obj,'__get__')or\n hasattr(obj,'__set__')or\n hasattr(obj,'__delete__'))\n \n \ndef _is_dunder(name):\n ''\n return (name[:2]==name[-2:]=='__'and\n name[2:3]!='_'and\n name[-3:-2]!='_'and\n len(name)>4)\n \n \ndef _is_sunder(name):\n ''\n return (name[0]==name[-1]=='_'and\n name[1:2]!='_'and\n name[-2:-1]!='_'and\n len(name)>2)\n \ndef _make_class_unpicklable(cls):\n ''\n def _break_on_call_reduce(self,proto):\n raise TypeError('%r cannot be pickled'%self)\n cls.__reduce_ex__=_break_on_call_reduce\n cls.__module__='<unknown>'\n \n_auto_null=object()\nclass auto:\n ''\n\n \n value=_auto_null\n \n \nclass _EnumDict(dict):\n ''\n\n\n\n\n \n def __init__(self):\n super().__init__()\n self._member_names=[]\n self._last_values=[]\n self._ignore=[]\n \n def __setitem__(self,key,value):\n ''\n\n\n\n\n\n\n \n if _is_sunder(key):\n if key not in (\n '_order_','_create_pseudo_member_',\n '_generate_next_value_','_missing_','_ignore_',\n ):\n raise ValueError('_names_ are reserved for future Enum use')\n if key =='_generate_next_value_':\n setattr(self,'_generate_next_value',value)\n elif key =='_ignore_':\n if isinstance(value,str):\n value=value.replace(',',' ').split()\n else :\n value=list(value)\n self._ignore=value\n already=set(value)&set(self._member_names)\n if already:\n raise ValueError('_ignore_ cannot specify already set names: %r'%(already,))\n elif _is_dunder(key):\n if key =='__order__':\n key='_order_'\n elif key in self._member_names:\n \n raise TypeError('Attempted to reuse key: %r'%key)\n elif key in self._ignore:\n pass\n elif not _is_descriptor(value):\n if key in self:\n \n raise TypeError('%r already defined as: %r'%(key,self[key]))\n if isinstance(value,auto):\n if value.value ==_auto_null:\n value.value=self._generate_next_value(key,1,len(self._member_names),self._last_values[:])\n value=value.value\n self._member_names.append(key)\n self._last_values.append(value)\n super().__setitem__(key,value)\n \n \n \n \n \nEnum=None\n\n\nclass EnumMeta(type):\n ''\n @classmethod\n def __prepare__(metacls,cls,bases):\n \n enum_dict=_EnumDict()\n \n member_type,first_enum=metacls._get_mixins_(bases)\n if first_enum is not None :\n enum_dict['_generate_next_value_']=getattr(first_enum,'_generate_next_value_',None )\n return enum_dict\n \n def __new__(metacls,cls,bases,classdict):\n \n \n \n \n \n \n classdict.setdefault('_ignore_',[]).append('_ignore_')\n ignore=classdict['_ignore_']\n for key in ignore:\n classdict.pop(key,None )\n member_type,first_enum=metacls._get_mixins_(bases)\n __new__,save_new,use_args=metacls._find_new_(classdict,member_type,\n first_enum)\n \n \n \n enum_members={k:classdict[k]for k in classdict._member_names}\n for name in classdict._member_names:\n del classdict[name]\n \n \n _order_=classdict.pop('_order_',None )\n \n \n invalid_names=set(enum_members)&{'mro',}\n if invalid_names:\n raise ValueError('Invalid enum member name: {0}'.format(\n ','.join(invalid_names)))\n \n \n if '__doc__'not in classdict:\n classdict['__doc__']='An enumeration.'\n \n \n enum_class=super().__new__(metacls,cls,bases,classdict)\n enum_class._member_names_=[]\n enum_class._member_map_=OrderedDict()\n enum_class._member_type_=member_type\n \n \n \n base_attributes={a for b in enum_class.mro()for a in b.__dict__}\n \n \n enum_class._value2member_map_={}\n \n \n \n \n \n \n \n \n \n \n \n if '__reduce_ex__'not in classdict:\n if member_type is not object:\n methods=('__getnewargs_ex__','__getnewargs__',\n '__reduce_ex__','__reduce__')\n if not any(m in member_type.__dict__ for m in methods):\n _make_class_unpicklable(enum_class)\n \n \n \n \n \n for member_name in classdict._member_names:\n value=enum_members[member_name]\n if not isinstance(value,tuple):\n args=(value,)\n else :\n args=value\n if member_type is tuple:\n args=(args,)\n if not use_args:\n enum_member=__new__(enum_class)\n if not hasattr(enum_member,'_value_'):\n enum_member._value_=value\n else :\n enum_member=__new__(enum_class,*args)\n if not hasattr(enum_member,'_value_'):\n if member_type is object:\n enum_member._value_=value\n else :\n enum_member._value_=member_type(*args)\n value=enum_member._value_\n enum_member._name_=member_name\n enum_member.__objclass__=enum_class\n enum_member.__init__(*args)\n \n \n for name,canonical_member in enum_class._member_map_.items():\n if canonical_member._value_ ==enum_member._value_:\n enum_member=canonical_member\n break\n else :\n \n enum_class._member_names_.append(member_name)\n \n \n if member_name not in base_attributes:\n setattr(enum_class,member_name,enum_member)\n \n enum_class._member_map_[member_name]=enum_member\n try :\n \n \n \n enum_class._value2member_map_[value]=enum_member\n except TypeError:\n pass\n \n \n \n for name in ('__repr__','__str__','__format__','__reduce_ex__'):\n class_method=getattr(enum_class,name)\n obj_method=getattr(member_type,name,None )\n enum_method=getattr(first_enum,name,None )\n if obj_method is not None and obj_method is class_method:\n setattr(enum_class,name,enum_method)\n \n \n \n if Enum is not None :\n \n \n if save_new:\n enum_class.__new_member__=__new__\n enum_class.__new__=Enum.__new__\n \n \n if _order_ is not None :\n if isinstance(_order_,str):\n _order_=_order_.replace(',',' ').split()\n if _order_ !=enum_class._member_names_:\n raise TypeError('member order does not match _order_')\n \n return enum_class\n \n def __bool__(self):\n ''\n\n \n return True\n \n def __call__(cls,value,names=None ,*,module=None ,qualname=None ,type=None ,start=1):\n ''\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n \n if names is None :\n return cls.__new__(cls,value)\n \n return cls._create_(value,names,module=module,qualname=qualname,type=type,start=start)\n \n def __contains__(cls,member):\n if not isinstance(member,Enum):\n import warnings\n warnings.warn(\n \"using non-Enums in containment checks will raise \"\n \"TypeError in Python 3.8\",\n DeprecationWarning,2)\n return isinstance(member,cls)and member._name_ in cls._member_map_\n \n def __delattr__(cls,attr):\n \n \n if attr in cls._member_map_:\n raise AttributeError(\n \"%s: cannot delete Enum member.\"%cls.__name__)\n super().__delattr__(attr)\n \n def __dir__(self):\n return (['__class__','__doc__','__members__','__module__']+\n self._member_names_)\n \n def __getattr__(cls,name):\n ''\n\n\n\n\n\n\n \n if _is_dunder(name):\n raise AttributeError(name)\n try :\n return cls._member_map_[name]\n except KeyError:\n raise AttributeError(name)from None\n \n def __getitem__(cls,name):\n return cls._member_map_[name]\n \n def __iter__(cls):\n return (cls._member_map_[name]for name in cls._member_names_)\n \n def __len__(cls):\n return len(cls._member_names_)\n \n @property\n def __members__(cls):\n ''\n\n\n\n\n \n return MappingProxyType(cls._member_map_)\n \n def __repr__(cls):\n return \"<enum %r>\"%cls.__name__\n \n def __reversed__(cls):\n return (cls._member_map_[name]for name in reversed(cls._member_names_))\n \n def __setattr__(cls,name,value):\n ''\n\n\n\n\n\n \n member_map=cls.__dict__.get('_member_map_',{})\n if name in member_map:\n raise AttributeError('Cannot reassign members.')\n super().__setattr__(name,value)\n \n def _create_(cls,class_name,names,*,module=None ,qualname=None ,type=None ,start=1):\n ''\n\n\n\n\n\n\n\n\n\n \n metacls=cls.__class__\n bases=(cls,)if type is None else (type,cls)\n _,first_enum=cls._get_mixins_(bases)\n classdict=metacls.__prepare__(class_name,bases)\n \n \n if isinstance(names,str):\n names=names.replace(',',' ').split()\n if isinstance(names,(tuple,list))and names and isinstance(names[0],str):\n original_names,names=names,[]\n last_values=[]\n for count,name in enumerate(original_names):\n value=first_enum._generate_next_value_(name,start,count,last_values[:])\n last_values.append(value)\n names.append((name,value))\n \n \n for item in names:\n if isinstance(item,str):\n member_name,member_value=item,names[item]\n else :\n member_name,member_value=item\n classdict[member_name]=member_value\n enum_class=metacls.__new__(metacls,class_name,bases,classdict)\n \n \n \n if module is None :\n try :\n module=sys._getframe(2).f_globals['__name__']\n except (AttributeError,ValueError)as exc:\n pass\n if module is None :\n _make_class_unpicklable(enum_class)\n else :\n enum_class.__module__=module\n if qualname is not None :\n enum_class.__qualname__=qualname\n \n return enum_class\n \n @staticmethod\n def _get_mixins_(bases):\n ''\n\n\n\n\n \n if not bases:\n return object,Enum\n \n \n \n \n member_type=first_enum=None\n for base in bases:\n if (base is not Enum and\n issubclass(base,Enum)and\n base._member_names_):\n raise TypeError(\"Cannot extend enumerations\")\n \n if not issubclass(base,Enum):\n raise TypeError(\"new enumerations must be created as \"\n \"`ClassName([mixin_type,] enum_type)`\")\n \n \n \n if not issubclass(bases[0],Enum):\n member_type=bases[0]\n first_enum=bases[-1]\n else :\n for base in bases[0].__mro__:\n \n \n \n \n if issubclass(base,Enum):\n if first_enum is None :\n first_enum=base\n else :\n if member_type is None :\n member_type=base\n \n return member_type,first_enum\n \n @staticmethod\n def _find_new_(classdict,member_type,first_enum):\n ''\n\n\n\n\n\n \n \n \n \n __new__=classdict.get('__new__',None )\n \n \n save_new=__new__ is not None\n \n if __new__ is None :\n \n \n for method in ('__new_member__','__new__'):\n for possible in (member_type,first_enum):\n target=getattr(possible,method,None )\n if target not in {\n None ,\n None .__new__,\n object.__new__,\n Enum.__new__,\n }:\n __new__=target\n break\n if __new__ is not None :\n break\n else :\n __new__=object.__new__\n \n \n \n \n if __new__ is object.__new__:\n use_args=False\n else :\n use_args=True\n \n return __new__,save_new,use_args\n \n \nclass Enum(metaclass=EnumMeta):\n ''\n\n\n\n \n def __new__(cls,value):\n \n \n \n if type(value)is cls:\n \n return value\n \n \n try :\n if value in cls._value2member_map_:\n return cls._value2member_map_[value]\n except TypeError:\n \n for member in cls._member_map_.values():\n if member._value_ ==value:\n return member\n \n return cls._missing_(value)\n \n def _generate_next_value_(name,start,count,last_values):\n for last_value in reversed(last_values):\n try :\n return last_value+1\n except TypeError:\n pass\n else :\n return start\n \n @classmethod\n def _missing_(cls,value):\n raise ValueError(\"%r is not a valid %s\"%(value,cls.__name__))\n \n def __repr__(self):\n return \"<%s.%s: %r>\"%(\n self.__class__.__name__,self._name_,self._value_)\n \n def __str__(self):\n return \"%s.%s\"%(self.__class__.__name__,self._name_)\n \n def __dir__(self):\n added_behavior=[\n m\n for cls in self.__class__.mro()\n for m in cls.__dict__\n if m[0]!='_'and m not in self._member_map_\n ]\n return (['__class__','__doc__','__module__']+added_behavior)\n \n def __format__(self,format_spec):\n \n \n \n \n \n if self._member_type_ is object:\n cls=str\n val=str(self)\n \n else :\n cls=self._member_type_\n val=self._value_\n return cls.__format__(val,format_spec)\n \n def __hash__(self):\n return hash(self._name_)\n \n def __reduce_ex__(self,proto):\n return self.__class__,(self._value_,)\n \n \n \n \n \n \n \n \n @DynamicClassAttribute\n def name(self):\n ''\n return self._name_\n \n @DynamicClassAttribute\n def value(self):\n ''\n return self._value_\n \n @classmethod\n def _convert(cls,name,module,filter,source=None ):\n ''\n\n \n \n \n \n \n \n module_globals=vars(sys.modules[module])\n if source:\n source=vars(source)\n else :\n source=module_globals\n \n \n \n \n \n members=[\n (name,source[name])\n for name in source.keys()\n if filter(name)]\n try :\n \n members.sort(key=lambda t:(t[1],t[0]))\n except TypeError:\n \n members.sort(key=lambda t:t[0])\n cls=cls(name,members,module=module)\n cls.__reduce_ex__=_reduce_ex_by_name\n module_globals.update(cls.__members__)\n module_globals[name]=cls\n return cls\n \n \nclass IntEnum(int,Enum):\n ''\n \n \ndef _reduce_ex_by_name(self,proto):\n return self.name\n \nclass Flag(Enum):\n ''\n \n def _generate_next_value_(name,start,count,last_values):\n ''\n\n\n\n\n\n\n \n if not count:\n return start if start is not None else 1\n for last_value in reversed(last_values):\n try :\n high_bit=_high_bit(last_value)\n break\n except Exception:\n raise TypeError('Invalid Flag value: %r'%last_value)from None\n return 2 **(high_bit+1)\n \n @classmethod\n def _missing_(cls,value):\n original_value=value\n if value <0:\n value=~value\n possible_member=cls._create_pseudo_member_(value)\n if original_value <0:\n possible_member=~possible_member\n return possible_member\n \n @classmethod\n def _create_pseudo_member_(cls,value):\n ''\n\n \n pseudo_member=cls._value2member_map_.get(value,None )\n if pseudo_member is None :\n \n _,extra_flags=_decompose(cls,value)\n if extra_flags:\n raise ValueError(\"%r is not a valid %s\"%(value,cls.__name__))\n \n pseudo_member=object.__new__(cls)\n pseudo_member._name_=None\n pseudo_member._value_=value\n \n \n pseudo_member=cls._value2member_map_.setdefault(value,pseudo_member)\n return pseudo_member\n \n def __contains__(self,other):\n if not isinstance(other,self.__class__):\n import warnings\n warnings.warn(\n \"using non-Flags in containment checks will raise \"\n \"TypeError in Python 3.8\",\n DeprecationWarning,2)\n return False\n return other._value_&self._value_ ==other._value_\n \n def __repr__(self):\n cls=self.__class__\n if self._name_ is not None :\n return '<%s.%s: %r>'%(cls.__name__,self._name_,self._value_)\n members,uncovered=_decompose(cls,self._value_)\n return '<%s.%s: %r>'%(\n cls.__name__,\n '|'.join([str(m._name_ or m._value_)for m in members]),\n self._value_,\n )\n \n def __str__(self):\n cls=self.__class__\n if self._name_ is not None :\n return '%s.%s'%(cls.__name__,self._name_)\n members,uncovered=_decompose(cls,self._value_)\n if len(members)==1 and members[0]._name_ is None :\n return '%s.%r'%(cls.__name__,members[0]._value_)\n else :\n return '%s.%s'%(\n cls.__name__,\n '|'.join([str(m._name_ or m._value_)for m in members]),\n )\n \n def __bool__(self):\n return bool(self._value_)\n \n def __or__(self,other):\n if not isinstance(other,self.__class__):\n return NotImplemented\n return self.__class__(self._value_ |other._value_)\n \n def __and__(self,other):\n if not isinstance(other,self.__class__):\n return NotImplemented\n return self.__class__(self._value_&other._value_)\n \n def __xor__(self,other):\n if not isinstance(other,self.__class__):\n return NotImplemented\n return self.__class__(self._value_ ^other._value_)\n \n def __invert__(self):\n members,uncovered=_decompose(self.__class__,self._value_)\n inverted=self.__class__(0)\n for m in self.__class__:\n if m not in members and not (m._value_&self._value_):\n inverted=inverted |m\n return self.__class__(inverted)\n \n \nclass IntFlag(int,Flag):\n ''\n \n @classmethod\n def _missing_(cls,value):\n if not isinstance(value,int):\n raise ValueError(\"%r is not a valid %s\"%(value,cls.__name__))\n new_member=cls._create_pseudo_member_(value)\n return new_member\n \n @classmethod\n def _create_pseudo_member_(cls,value):\n pseudo_member=cls._value2member_map_.get(value,None )\n if pseudo_member is None :\n need_to_create=[value]\n \n _,extra_flags=_decompose(cls,value)\n \n while extra_flags:\n \n bit=_high_bit(extra_flags)\n flag_value=2 **bit\n if (flag_value not in cls._value2member_map_ and\n flag_value not in need_to_create\n ):\n need_to_create.append(flag_value)\n if extra_flags ==-flag_value:\n extra_flags=0\n else :\n extra_flags ^=flag_value\n for value in reversed(need_to_create):\n \n pseudo_member=int.__new__(cls,value)\n pseudo_member._name_=None\n pseudo_member._value_=value\n \n \n pseudo_member=cls._value2member_map_.setdefault(value,pseudo_member)\n return pseudo_member\n \n def __or__(self,other):\n if not isinstance(other,(self.__class__,int)):\n return NotImplemented\n result=self.__class__(self._value_ |self.__class__(other)._value_)\n return result\n \n def __and__(self,other):\n if not isinstance(other,(self.__class__,int)):\n return NotImplemented\n return self.__class__(self._value_&self.__class__(other)._value_)\n \n def __xor__(self,other):\n if not isinstance(other,(self.__class__,int)):\n return NotImplemented\n return self.__class__(self._value_ ^self.__class__(other)._value_)\n \n __ror__=__or__\n __rand__=__and__\n __rxor__=__xor__\n \n def __invert__(self):\n result=self.__class__(~self._value_)\n return result\n \n \ndef _high_bit(value):\n ''\n return value.bit_length()-1\n \ndef unique(enumeration):\n ''\n duplicates=[]\n for name,member in enumeration.__members__.items():\n if name !=member.name:\n duplicates.append((name,member.name))\n if duplicates:\n alias_details=', '.join(\n [\"%s -> %s\"%(alias,name)for (alias,name)in duplicates])\n raise ValueError('duplicate values found in %r: %s'%\n (enumeration,alias_details))\n return enumeration\n \ndef _decompose(flag,value):\n ''\n \n not_covered=value\n negative=value <0\n \n \n \n if negative:\n \n flags_to_check=[\n (m,v)\n for v,m in list(flag._value2member_map_.items())\n if m.name is not None\n ]\n else :\n \n flags_to_check=[\n (m,v)\n for v,m in list(flag._value2member_map_.items())\n if m.name is not None or _power_of_two(v)\n ]\n members=[]\n for member,member_value in flags_to_check:\n if member_value and member_value&value ==member_value:\n members.append(member)\n not_covered &=~member_value\n if not members and value in flag._value2member_map_:\n members.append(flag._value2member_map_[value])\n members.sort(key=lambda m:m._value_,reverse=True )\n if len(members)>1 and members[0].value ==value:\n \n members.pop(0)\n return members,not_covered\n \ndef _power_of_two(value):\n if value <1:\n return False\n return value ==2 **_high_bit(value)\n", ["_collections", "collections", "sys", "types", "warnings"]], "linecache": [".py", "''\n\n\n\n\n\n\nimport functools\nimport sys\nimport os\nimport tokenize\n\n__all__=[\"getline\",\"clearcache\",\"checkcache\"]\n\ndef getline(filename,lineno,module_globals=None ):\n lines=getlines(filename,module_globals)\n if 1 <=lineno <=len(lines):\n return lines[lineno -1]\n else :\n return ''\n \n \n \n \n \n \ncache={}\n\n\ndef clearcache():\n ''\n \n global cache\n cache={}\n \n \ndef getlines(filename,module_globals=None ):\n ''\n \n \n if filename in cache:\n entry=cache[filename]\n if len(entry)!=1:\n return cache[filename][2]\n \n try :\n return updatecache(filename,module_globals)\n except MemoryError:\n clearcache()\n return []\n \n \ndef checkcache(filename=None ):\n ''\n \n \n if filename is None :\n filenames=list(cache.keys())\n else :\n if filename in cache:\n filenames=[filename]\n else :\n return\n \n for filename in filenames:\n entry=cache[filename]\n if len(entry)==1:\n \n continue\n size,mtime,lines,fullname=entry\n if mtime is None :\n continue\n try :\n stat=os.stat(fullname)\n except OSError:\n del cache[filename]\n continue\n if size !=stat.st_size or mtime !=stat.st_mtime:\n del cache[filename]\n \n \ndef updatecache(filename,module_globals=None ):\n ''\n\n \n \n if filename in cache:\n if len(cache[filename])!=1:\n del cache[filename]\n if not filename or (filename.startswith('<')and filename.endswith('>')):\n return []\n \n fullname=filename\n try :\n stat=os.stat(fullname)\n except OSError:\n basename=filename\n \n \n \n if lazycache(filename,module_globals):\n try :\n data=cache[filename][0]()\n except (ImportError,OSError):\n pass\n else :\n if data is None :\n \n \n return []\n cache[filename]=(\n len(data),None ,\n [line+'\\n'for line in data.splitlines()],fullname\n )\n return cache[filename][2]\n \n \n \n if os.path.isabs(filename):\n return []\n \n for dirname in sys.path:\n try :\n fullname=os.path.join(dirname,basename)\n except (TypeError,AttributeError):\n \n continue\n try :\n stat=os.stat(fullname)\n break\n except OSError:\n pass\n else :\n return []\n try :\n with tokenize.open(fullname)as fp:\n lines=fp.readlines()\n except OSError:\n return []\n if lines and not lines[-1].endswith('\\n'):\n lines[-1]+='\\n'\n size,mtime=stat.st_size,stat.st_mtime\n cache[filename]=size,mtime,lines,fullname\n return lines\n \n \ndef lazycache(filename,module_globals):\n ''\n\n\n\n\n\n\n\n\n\n\n \n if filename in cache:\n if len(cache[filename])==1:\n return True\n else :\n return False\n if not filename or (filename.startswith('<')and filename.endswith('>')):\n return False\n \n if module_globals and '__loader__'in module_globals:\n name=module_globals.get('__name__')\n loader=module_globals['__loader__']\n get_source=getattr(loader,'get_source',None )\n \n if name and get_source:\n get_lines=functools.partial(get_source,name)\n cache[filename]=(get_lines,)\n return True\n return False\n", ["functools", "os", "sys", "tokenize"]], "importlib.machinery": [".py", "''\n\nimport _imp\n\nfrom ._bootstrap import ModuleSpec\nfrom ._bootstrap import BuiltinImporter\nfrom ._bootstrap import FrozenImporter\nfrom ._bootstrap_external import (SOURCE_SUFFIXES,DEBUG_BYTECODE_SUFFIXES,\nOPTIMIZED_BYTECODE_SUFFIXES,BYTECODE_SUFFIXES,\nEXTENSION_SUFFIXES)\nfrom ._bootstrap_external import WindowsRegistryFinder\nfrom ._bootstrap_external import PathFinder\nfrom ._bootstrap_external import FileFinder\nfrom ._bootstrap_external import SourceFileLoader\nfrom ._bootstrap_external import SourcelessFileLoader\nfrom ._bootstrap_external import ExtensionFileLoader\n\n\ndef all_suffixes():\n ''\n return SOURCE_SUFFIXES+BYTECODE_SUFFIXES+EXTENSION_SUFFIXES\n", ["_imp", "importlib._bootstrap", "importlib._bootstrap_external"]], "importlib": [".py", "''\n__all__=['__import__','import_module','invalidate_caches','reload']\n\n\n\n\n\n\n\n\n\nimport _imp\nimport sys\n\ntry :\n import _frozen_importlib as _bootstrap\nexcept ImportError:\n from . import _bootstrap\n _bootstrap._setup(sys,_imp)\nelse :\n\n\n _bootstrap.__name__='importlib._bootstrap'\n _bootstrap.__package__='importlib'\n try :\n _bootstrap.__file__=__file__.replace('__init__.py','_bootstrap.py')\n except NameError:\n \n \n pass\n sys.modules['importlib._bootstrap']=_bootstrap\n \ntry :\n import _frozen_importlib_external as _bootstrap_external\nexcept ImportError:\n from . import _bootstrap_external\n _bootstrap_external._setup(_bootstrap)\n _bootstrap._bootstrap_external=_bootstrap_external\nelse :\n _bootstrap_external.__name__='importlib._bootstrap_external'\n _bootstrap_external.__package__='importlib'\n try :\n _bootstrap_external.__file__=__file__.replace('__init__.py','_bootstrap_external.py')\n except NameError:\n \n \n pass\n sys.modules['importlib._bootstrap_external']=_bootstrap_external\n \n \n_w_long=_bootstrap_external._w_long\n_r_long=_bootstrap_external._r_long\n\n\n\n\nimport types\nimport warnings\n\n\n\n\nfrom ._bootstrap import __import__\n\n\ndef invalidate_caches():\n ''\n \n for finder in sys.meta_path:\n if hasattr(finder,'invalidate_caches'):\n finder.invalidate_caches()\n \n \ndef find_loader(name,path=None ):\n ''\n\n\n\n\n\n \n warnings.warn('Deprecated since Python 3.4. '\n 'Use importlib.util.find_spec() instead.',\n DeprecationWarning,stacklevel=2)\n try :\n loader=sys.modules[name].__loader__\n if loader is None :\n raise ValueError('{}.__loader__ is None'.format(name))\n else :\n return loader\n except KeyError:\n pass\n except AttributeError:\n raise ValueError('{}.__loader__ is not set'.format(name))from None\n \n spec=_bootstrap._find_spec(name,path)\n \n if spec is None :\n return None\n if spec.loader is None :\n if spec.submodule_search_locations is None :\n raise ImportError('spec for {} missing loader'.format(name),\n name=name)\n raise ImportError('namespace packages do not have loaders',\n name=name)\n return spec.loader\n \n \ndef import_module(name,package=None ):\n ''\n\n\n\n\n\n \n level=0\n if name.startswith('.'):\n if not package:\n msg=(\"the 'package' argument is required to perform a relative \"\n \"import for {!r}\")\n raise TypeError(msg.format(name))\n for character in name:\n if character !='.':\n break\n level +=1\n return _bootstrap._gcd_import(name[level:],package,level)\n \n \n_RELOADING={}\n\n\ndef reload(module):\n ''\n\n\n\n \n if not module or not isinstance(module,types.ModuleType):\n raise TypeError(\"reload() argument must be a module\")\n try :\n name=module.__spec__.name\n except AttributeError:\n name=module.__name__\n \n if sys.modules.get(name)is not module:\n msg=\"module {} not in sys.modules\"\n raise ImportError(msg.format(name),name=name)\n if name in _RELOADING:\n return _RELOADING[name]\n _RELOADING[name]=module\n try :\n parent_name=name.rpartition('.')[0]\n if parent_name:\n try :\n parent=sys.modules[parent_name]\n except KeyError:\n msg=\"parent {!r} not in sys.modules\"\n raise ImportError(msg.format(parent_name),\n name=parent_name)from None\n else :\n pkgpath=parent.__path__\n else :\n pkgpath=None\n target=module\n spec=module.__spec__=_bootstrap._find_spec(name,pkgpath,target)\n if spec is None :\n raise ModuleNotFoundError(f\"spec not found for the module {name!r}\",name=name)\n _bootstrap._exec(spec,module)\n \n return sys.modules[name]\n finally :\n try :\n del _RELOADING[name]\n except KeyError:\n pass\n", ["_frozen_importlib", "_frozen_importlib_external", "_imp", "importlib", "importlib._bootstrap", "importlib._bootstrap_external", "sys", "types", "warnings"], 1], "email.encoders": [".py", "\n\n\n\n\"\"\"Encodings and related functions.\"\"\"\n\n__all__=[\n'encode_7or8bit',\n'encode_base64',\n'encode_noop',\n'encode_quopri',\n]\n\n\nfrom base64 import encodebytes as _bencode\nfrom quopri import encodestring as _encodestring\n\n\n\ndef _qencode(s):\n enc=_encodestring(s,quotetabs=True )\n \n return enc.replace(b' ',b'=20')\n \n \ndef encode_base64(msg):\n ''\n\n\n \n orig=msg.get_payload(decode=True )\n encdata=str(_bencode(orig),'ascii')\n msg.set_payload(encdata)\n msg['Content-Transfer-Encoding']='base64'\n \n \n \ndef encode_quopri(msg):\n ''\n\n\n \n orig=msg.get_payload(decode=True )\n encdata=_qencode(orig)\n msg.set_payload(encdata)\n msg['Content-Transfer-Encoding']='quoted-printable'\n \n \n \ndef encode_7or8bit(msg):\n ''\n orig=msg.get_payload(decode=True )\n if orig is None :\n \n msg['Content-Transfer-Encoding']='7bit'\n return\n \n \n try :\n orig.decode('ascii')\n except UnicodeError:\n msg['Content-Transfer-Encoding']='8bit'\n else :\n msg['Content-Transfer-Encoding']='7bit'\n \n \n \ndef encode_noop(msg):\n ''\n", ["base64", "quopri"]], "sys": [".py", "\nfrom _sys import *\nimport javascript\n\n_getframe=Getframe\n\nabiflags=0\n\nbrython_debug_mode=__BRYTHON__.debug\n\nbase_exec_prefix=__BRYTHON__.brython_path\n\nbase_prefix=__BRYTHON__.brython_path\n\nbuiltin_module_names=__BRYTHON__.builtin_module_names\n\nbyteorder='little'\n\nexec_prefix=__BRYTHON__.brython_path\n\nexecutable=__BRYTHON__.brython_path+'/brython.js'\n\nargv=__BRYTHON__.__ARGV\n\ndef exit(i=None ):\n raise SystemExit('')\n \nclass flag_class:\n\n def __init__(self):\n self.debug=0\n self.inspect=0\n self.interactive=0\n self.optimize=0\n self.dont_write_bytecode=0\n self.no_user_site=0\n self.no_site=0\n self.ignore_environment=0\n self.verbose=0\n self.bytes_warning=0\n self.quiet=0\n self.hash_randomization=1\n \nflags=flag_class()\n\nclass float_info:\n mant_dig=53\n max=javascript.Number.MAX_VALUE\n min=javascript.Number.MIN_VALUE\n radix=2\n \ndef getfilesystemencoding(*args,**kw):\n ''\n\n \n return 'utf-8'\n \ndef getfilesystemencodeerrors():\n return \"utf-8\"\n \ndef getrecursionlimit():\n return 200\n \ndef intern(string):\n return string\n \nmaxsize=2 **63 -1\n\nmaxunicode=1114111\n\nplatform=\"brython\"\n\nprefix=__BRYTHON__.brython_path\n\ndef settrace(tracefunc):\n print(\"set trace\")\n \nversion='.'.join(str(x)for x in __BRYTHON__.version_info[:3])\nversion +=\" (default, %s) \\n[Javascript 1.5] on Brython\"\\\n%__BRYTHON__.compiled_date\nhexversion=0x03070000\n\nclass _version_info:\n\n def __init__(self,version_info):\n self.version_info=version_info\n self.major=version_info[0]\n self.minor=version_info[1]\n self.micro=version_info[2]\n self.releaselevel=version_info[3]\n self.serial=version_info[4]\n \n def __getitem__(self,index):\n if isinstance(self.version_info[index],list):\n return tuple(self.version_info[index])\n return self.version_info[index]\n \n def hexversion(self):\n try :\n return '0%d0%d0%d'%(self.major,self.minor,self.micro)\n finally :\n return '0%d0000'%(self.major)\n \n def __str__(self):\n _s=\"sys.version(major=%d, minor=%d, micro=%d, releaselevel='%s', \"\\\n \"serial=%d)\"\n return _s %(self.major,self.minor,self.micro,\n self.releaselevel,self.serial)\n \n def __eq__(self,other):\n if isinstance(other,tuple):\n return (self.major,self.minor,self.micro)==other\n \n raise Error(\"Error! I don't know how to compare!\")\n \n def __ge__(self,other):\n if isinstance(other,tuple):\n return (self.major,self.minor,self.micro)>=other\n \n raise Error(\"Error! I don't know how to compare!\")\n \n def __gt__(self,other):\n if isinstance(other,tuple):\n return (self.major,self.minor,self.micro)>other\n \n raise Error(\"Error! I don't know how to compare!\")\n \n def __le__(self,other):\n if isinstance(other,tuple):\n return (self.major,self.minor,self.micro)<=other\n \n raise Error(\"Error! I don't know how to compare!\")\n \n def __lt__(self,other):\n if isinstance(other,tuple):\n return (self.major,self.minor,self.micro)<other\n \n raise Error(\"Error! I don't know how to compare!\")\n \n def __ne__(self,other):\n if isinstance(other,tuple):\n return (self.major,self.minor,self.micro)!=other\n \n raise Error(\"Error! I don't know how to compare!\")\n \n \n \nversion_info=_version_info(__BRYTHON__.version_info)\n\nclass _implementation:\n\n def __init__(self):\n self.name='brython'\n self.version=_version_info(__BRYTHON__.implementation)\n self.hexversion=self.version.hexversion()\n self.cache_tag=None\n \n def __repr__(self):\n return \"namespace(name='%s' version=%s hexversion='%s')\"%(self.name,\n self.version,self.hexversion)\n \n def __str__(self):\n return \"namespace(name='%s' version=%s hexversion='%s')\"%(self.name,\n self.version,self.hexversion)\n \nimplementation=_implementation()\n\nclass _hash_info:\n\n def __init__(self):\n self.width=32,\n self.modulus=2147483647\n self.inf=314159\n self.nan=0\n self.imag=1000003\n self.algorithm='siphash24'\n self.hash_bits=64\n self.seed_bits=128\n cutoff=0\n \n def __repr__(self):\n \n return \"sys.hash_info(width=32, modulus=2147483647, inf=314159, \"\\\n \"nan=0, imag=1000003, algorithm='siphash24', hash_bits=64, \"\\\n \"seed_bits=128, cutoff=0)\"\n \nhash_info=_hash_info()\n\nclass _float_info:\n ''\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n \n def __init__(self):\n self.dig=15\n self.epsilon=2 **-52\n self.mant_dig=53\n self.max=javascript.Number.MAX_VALUE\n self.max_exp=2 **10\n self.max_10_exp=308\n self.min=2 **(-1022)\n self.min_exp=-1021\n self.min_10_exp=-307\n self.radix=2\n self.rounds=1\n self._tuple=(self.max,self.max_exp,self.max_10_exp,self.min,\n self.min_exp,self.min_10_exp,self.dig,self.mant_dig,self.epsilon,\n self.radix,self.rounds)\n \n def __getitem__(self,k):\n return self._tuple[k]\n \n def __iter__(self):\n return iter(self._tuple)\n \nfloat_info=_float_info()\n\nwarnoptions=[]\n\ndef getfilesystemencoding():\n return 'utf-8'\n \n \n__stdout__=__BRYTHON__.stdout\n__stderr__=__BRYTHON__.stderr\n__stdin__=__BRYTHON__.stdin\n\n", ["_sys", "javascript"]], "tokenize": [".py", "''\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n__author__='Ka-Ping Yee <ping@lfw.org>'\n__credits__=('GvR, ESR, Tim Peters, Thomas Wouters, Fred Drake, '\n'Skip Montanaro, Raymond Hettinger, Trent Nelson, '\n'Michael Foord')\nfrom builtins import open as _builtin_open\nfrom codecs import lookup,BOM_UTF8\nimport collections\nfrom io import TextIOWrapper\nfrom itertools import chain\nimport itertools as _itertools\nimport re\nimport sys\nfrom token import *\n\ncookie_re=re.compile(r'^[ \\t\\f]*#.*?coding[:=][ \\t]*([-\\w.]+)',re.ASCII)\nblank_re=re.compile(br'^[ \\t\\f]*(?:[#\\r\\n]|$)',re.ASCII)\n\nimport token\n__all__=token.__all__+[\"tokenize\",\"detect_encoding\",\n\"untokenize\",\"TokenInfo\"]\ndel token\n\nEXACT_TOKEN_TYPES={\n'(':LPAR,\n')':RPAR,\n'[':LSQB,\n']':RSQB,\n':':COLON,\n',':COMMA,\n';':SEMI,\n'+':PLUS,\n'-':MINUS,\n'*':STAR,\n'/':SLASH,\n'|':VBAR,\n'&':AMPER,\n'<':LESS,\n'>':GREATER,\n'=':EQUAL,\n'.':DOT,\n'%':PERCENT,\n'{':LBRACE,\n'}':RBRACE,\n'==':EQEQUAL,\n'!=':NOTEQUAL,\n'<=':LESSEQUAL,\n'>=':GREATEREQUAL,\n'~':TILDE,\n'^':CIRCUMFLEX,\n'<<':LEFTSHIFT,\n'>>':RIGHTSHIFT,\n'**':DOUBLESTAR,\n'+=':PLUSEQUAL,\n'-=':MINEQUAL,\n'*=':STAREQUAL,\n'/=':SLASHEQUAL,\n'%=':PERCENTEQUAL,\n'&=':AMPEREQUAL,\n'|=':VBAREQUAL,\n'^=':CIRCUMFLEXEQUAL,\n'<<=':LEFTSHIFTEQUAL,\n'>>=':RIGHTSHIFTEQUAL,\n'**=':DOUBLESTAREQUAL,\n'//':DOUBLESLASH,\n'//=':DOUBLESLASHEQUAL,\n'...':ELLIPSIS,\n'->':RARROW,\n'@':AT,\n'@=':ATEQUAL,\n}\n\nclass TokenInfo(collections.namedtuple('TokenInfo','type string start end line')):\n def __repr__(self):\n annotated_type='%d (%s)'%(self.type,tok_name[self.type])\n return ('TokenInfo(type=%s, string=%r, start=%r, end=%r, line=%r)'%\n self._replace(type=annotated_type))\n \n @property\n def exact_type(self):\n if self.type ==OP and self.string in EXACT_TOKEN_TYPES:\n return EXACT_TOKEN_TYPES[self.string]\n else :\n return self.type\n \ndef group(*choices):return '('+'|'.join(choices)+')'\ndef any(*choices):return group(*choices)+'*'\ndef maybe(*choices):return group(*choices)+'?'\n\n\n\nWhitespace=r'[ \\f\\t]*'\nComment=r'#[^\\r\\n]*'\nIgnore=Whitespace+any(r'\\\\\\r?\\n'+Whitespace)+maybe(Comment)\nName=r'\\w+'\n\nHexnumber=r'0[xX](?:_?[0-9a-fA-F])+'\nBinnumber=r'0[bB](?:_?[01])+'\nOctnumber=r'0[oO](?:_?[0-7])+'\nDecnumber=r'(?:0(?:_?0)*|[1-9](?:_?[0-9])*)'\nIntnumber=group(Hexnumber,Binnumber,Octnumber,Decnumber)\nExponent=r'[eE][-+]?[0-9](?:_?[0-9])*'\nPointfloat=group(r'[0-9](?:_?[0-9])*\\.(?:[0-9](?:_?[0-9])*)?',\nr'\\.[0-9](?:_?[0-9])*')+maybe(Exponent)\nExpfloat=r'[0-9](?:_?[0-9])*'+Exponent\nFloatnumber=group(Pointfloat,Expfloat)\nImagnumber=group(r'[0-9](?:_?[0-9])*[jJ]',Floatnumber+r'[jJ]')\nNumber=group(Imagnumber,Floatnumber,Intnumber)\n\n\ndef _all_string_prefixes():\n\n\n\n _valid_string_prefixes=['b','r','u','f','br','fr']\n \n result={''}\n for prefix in _valid_string_prefixes:\n for t in _itertools.permutations(prefix):\n \n \n for u in _itertools.product(*[(c,c.upper())for c in t]):\n result.add(''.join(u))\n return result\n \ndef _compile(expr):\n return re.compile(expr,re.UNICODE)\n \n \n \nStringPrefix=group(*_all_string_prefixes())\n\n\nSingle=r\"[^'\\\\]*(?:\\\\.[^'\\\\]*)*'\"\n\nDouble=r'[^\"\\\\]*(?:\\\\.[^\"\\\\]*)*\"'\n\nSingle3=r\"[^'\\\\]*(?:(?:\\\\.|'(?!''))[^'\\\\]*)*'''\"\n\nDouble3=r'[^\"\\\\]*(?:(?:\\\\.|\"(?!\"\"))[^\"\\\\]*)*\"\"\"'\nTriple=group(StringPrefix+\"'''\",StringPrefix+'\"\"\"')\n\nString=group(StringPrefix+r\"'[^\\n'\\\\]*(?:\\\\.[^\\n'\\\\]*)*'\",\nStringPrefix+r'\"[^\\n\"\\\\]*(?:\\\\.[^\\n\"\\\\]*)*\"')\n\n\n\n\nOperator=group(r\"\\*\\*=?\",r\">>=?\",r\"<<=?\",r\"!=\",\nr\"//=?\",r\"->\",\nr\"[+\\-*/%&@|^=<>]=?\",\nr\"~\")\n\nBracket='[][(){}]'\nSpecial=group(r'\\r?\\n',r'\\.\\.\\.',r'[:;.,@]')\nFunny=group(Operator,Bracket,Special)\n\nPlainToken=group(Number,Funny,String,Name)\nToken=Ignore+PlainToken\n\n\nContStr=group(StringPrefix+r\"'[^\\n'\\\\]*(?:\\\\.[^\\n'\\\\]*)*\"+\ngroup(\"'\",r'\\\\\\r?\\n'),\nStringPrefix+r'\"[^\\n\"\\\\]*(?:\\\\.[^\\n\"\\\\]*)*'+\ngroup('\"',r'\\\\\\r?\\n'))\nPseudoExtras=group(r'\\\\\\r?\\n|\\Z',Comment,Triple)\nPseudoToken=Whitespace+group(PseudoExtras,Number,Funny,ContStr,Name)\n\n\n\n\nendpats={}\nfor _prefix in _all_string_prefixes():\n endpats[_prefix+\"'\"]=Single\n endpats[_prefix+'\"']=Double\n endpats[_prefix+\"'''\"]=Single3\n endpats[_prefix+'\"\"\"']=Double3\n \n \n \nsingle_quoted=set()\ntriple_quoted=set()\nfor t in _all_string_prefixes():\n for u in (t+'\"',t+\"'\"):\n single_quoted.add(u)\n for u in (t+'\"\"\"',t+\"'''\"):\n triple_quoted.add(u)\n \ntabsize=8\n\nclass TokenError(Exception):pass\n\nclass StopTokenizing(Exception):pass\n\n\nclass Untokenizer:\n\n def __init__(self):\n self.tokens=[]\n self.prev_row=1\n self.prev_col=0\n self.encoding=None\n \n def add_whitespace(self,start):\n row,col=start\n if row <self.prev_row or row ==self.prev_row and col <self.prev_col:\n raise ValueError(\"start ({},{}) precedes previous end ({},{})\"\n .format(row,col,self.prev_row,self.prev_col))\n row_offset=row -self.prev_row\n if row_offset:\n self.tokens.append(\"\\\\\\n\"*row_offset)\n self.prev_col=0\n col_offset=col -self.prev_col\n if col_offset:\n self.tokens.append(\" \"*col_offset)\n \n def untokenize(self,iterable):\n it=iter(iterable)\n indents=[]\n startline=False\n for t in it:\n if len(t)==2:\n self.compat(t,it)\n break\n tok_type,token,start,end,line=t\n if tok_type ==ENCODING:\n self.encoding=token\n continue\n if tok_type ==ENDMARKER:\n break\n if tok_type ==INDENT:\n indents.append(token)\n continue\n elif tok_type ==DEDENT:\n indents.pop()\n self.prev_row,self.prev_col=end\n continue\n elif tok_type in (NEWLINE,NL):\n startline=True\n elif startline and indents:\n indent=indents[-1]\n if start[1]>=len(indent):\n self.tokens.append(indent)\n self.prev_col=len(indent)\n startline=False\n self.add_whitespace(start)\n self.tokens.append(token)\n self.prev_row,self.prev_col=end\n if tok_type in (NEWLINE,NL):\n self.prev_row +=1\n self.prev_col=0\n return \"\".join(self.tokens)\n \n def compat(self,token,iterable):\n indents=[]\n toks_append=self.tokens.append\n startline=token[0]in (NEWLINE,NL)\n prevstring=False\n \n for tok in chain([token],iterable):\n toknum,tokval=tok[:2]\n if toknum ==ENCODING:\n self.encoding=tokval\n continue\n \n if toknum in (NAME,NUMBER):\n tokval +=' '\n \n \n if toknum ==STRING:\n if prevstring:\n tokval=' '+tokval\n prevstring=True\n else :\n prevstring=False\n \n if toknum ==INDENT:\n indents.append(tokval)\n continue\n elif toknum ==DEDENT:\n indents.pop()\n continue\n elif toknum in (NEWLINE,NL):\n startline=True\n elif startline and indents:\n toks_append(indents[-1])\n startline=False\n toks_append(tokval)\n \n \ndef untokenize(iterable):\n ''\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n \n ut=Untokenizer()\n out=ut.untokenize(iterable)\n if ut.encoding is not None :\n out=out.encode(ut.encoding)\n return out\n \n \ndef _get_normal_name(orig_enc):\n ''\n \n enc=orig_enc[:12].lower().replace(\"_\",\"-\")\n if enc ==\"utf-8\"or enc.startswith(\"utf-8-\"):\n return \"utf-8\"\n if enc in (\"latin-1\",\"iso-8859-1\",\"iso-latin-1\")or\\\n enc.startswith((\"latin-1-\",\"iso-8859-1-\",\"iso-latin-1-\")):\n return \"iso-8859-1\"\n return orig_enc\n \ndef detect_encoding(readline):\n ''\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n \n try :\n filename=readline.__self__.name\n except AttributeError:\n filename=None\n bom_found=False\n encoding=None\n default='utf-8'\n def read_or_stop():\n try :\n return readline()\n except StopIteration:\n return b''\n \n def find_cookie(line):\n try :\n \n \n \n line_string=line.decode('utf-8')\n except UnicodeDecodeError:\n msg=\"invalid or missing encoding declaration\"\n if filename is not None :\n msg='{} for {!r}'.format(msg,filename)\n raise SyntaxError(msg)\n \n match=cookie_re.match(line_string)\n if not match:\n return None\n encoding=_get_normal_name(match.group(1))\n try :\n codec=lookup(encoding)\n except LookupError:\n \n if filename is None :\n msg=\"unknown encoding: \"+encoding\n else :\n msg=\"unknown encoding for {!r}: {}\".format(filename,\n encoding)\n raise SyntaxError(msg)\n \n if bom_found:\n if encoding !='utf-8':\n \n if filename is None :\n msg='encoding problem: utf-8'\n else :\n msg='encoding problem for {!r}: utf-8'.format(filename)\n raise SyntaxError(msg)\n encoding +='-sig'\n return encoding\n \n first=read_or_stop()\n if first.startswith(BOM_UTF8):\n bom_found=True\n first=first[3:]\n default='utf-8-sig'\n if not first:\n return default,[]\n \n encoding=find_cookie(first)\n if encoding:\n return encoding,[first]\n if not blank_re.match(first):\n return default,[first]\n \n second=read_or_stop()\n if not second:\n return default,[first]\n \n encoding=find_cookie(second)\n if encoding:\n return encoding,[first,second]\n \n return default,[first,second]\n \n \ndef open(filename):\n ''\n\n \n buffer=_builtin_open(filename,'rb')\n try :\n encoding,lines=detect_encoding(buffer.readline)\n buffer.seek(0)\n text=TextIOWrapper(buffer,encoding,line_buffering=True )\n text.mode='r'\n return text\n except :\n buffer.close()\n raise\n \n \ndef tokenize(readline):\n ''\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n \n \n \n from itertools import chain,repeat\n encoding,consumed=detect_encoding(readline)\n rl_gen=iter(readline,b\"\")\n empty=repeat(b\"\")\n return _tokenize(chain(consumed,rl_gen,empty).__next__,encoding)\n \n \ndef _tokenize(readline,encoding):\n lnum=parenlev=continued=0\n numchars='0123456789'\n contstr,needcont='',0\n contline=None\n indents=[0]\n \n if encoding is not None :\n if encoding ==\"utf-8-sig\":\n \n encoding=\"utf-8\"\n yield TokenInfo(ENCODING,encoding,(0,0),(0,0),'')\n while True :\n try :\n line=readline()\n except StopIteration:\n line=b''\n \n if encoding is not None :\n line=line.decode(encoding)\n lnum +=1\n pos,max=0,len(line)\n \n if contstr:\n if not line:\n raise TokenError(\"EOF in multi-line string\",strstart)\n endmatch=endprog.match(line)\n if endmatch:\n pos=end=endmatch.end(0)\n yield TokenInfo(STRING,contstr+line[:end],\n strstart,(lnum,end),contline+line)\n contstr,needcont='',0\n contline=None\n elif needcont and line[-2:]!='\\\\\\n'and line[-3:]!='\\\\\\r\\n':\n yield TokenInfo(ERRORTOKEN,contstr+line,\n strstart,(lnum,len(line)),contline)\n contstr=''\n contline=None\n continue\n else :\n contstr=contstr+line\n contline=contline+line\n continue\n \n elif parenlev ==0 and not continued:\n if not line:break\n column=0\n while pos <max:\n if line[pos]==' ':\n column +=1\n elif line[pos]=='\\t':\n column=(column //tabsize+1)*tabsize\n elif line[pos]=='\\f':\n column=0\n else :\n break\n pos +=1\n if pos ==max:\n break\n \n if line[pos]in '#\\r\\n':\n if line[pos]=='#':\n comment_token=line[pos:].rstrip('\\r\\n')\n yield TokenInfo(COMMENT,comment_token,\n (lnum,pos),(lnum,pos+len(comment_token)),line)\n pos +=len(comment_token)\n \n yield TokenInfo(NL,line[pos:],\n (lnum,pos),(lnum,len(line)),line)\n continue\n \n if column >indents[-1]:\n indents.append(column)\n yield TokenInfo(INDENT,line[:pos],(lnum,0),(lnum,pos),line)\n while column <indents[-1]:\n if column not in indents:\n raise IndentationError(\n \"unindent does not match any outer indentation level\",\n (\"<tokenize>\",lnum,pos,line))\n indents=indents[:-1]\n \n yield TokenInfo(DEDENT,'',(lnum,pos),(lnum,pos),line)\n \n else :\n if not line:\n raise TokenError(\"EOF in multi-line statement\",(lnum,0))\n continued=0\n \n while pos <max:\n pseudomatch=_compile(PseudoToken).match(line,pos)\n if pseudomatch:\n start,end=pseudomatch.span(1)\n spos,epos,pos=(lnum,start),(lnum,end),end\n if start ==end:\n continue\n token,initial=line[start:end],line[start]\n \n if (initial in numchars or\n (initial =='.'and token !='.'and token !='...')):\n yield TokenInfo(NUMBER,token,spos,epos,line)\n elif initial in '\\r\\n':\n if parenlev >0:\n yield TokenInfo(NL,token,spos,epos,line)\n else :\n yield TokenInfo(NEWLINE,token,spos,epos,line)\n \n elif initial =='#':\n assert not token.endswith(\"\\n\")\n yield TokenInfo(COMMENT,token,spos,epos,line)\n \n elif token in triple_quoted:\n endprog=_compile(endpats[token])\n endmatch=endprog.match(line,pos)\n if endmatch:\n pos=endmatch.end(0)\n token=line[start:pos]\n yield TokenInfo(STRING,token,spos,(lnum,pos),line)\n else :\n strstart=(lnum,start)\n contstr=line[start:]\n contline=line\n break\n \n \n \n \n \n \n \n \n \n \n \n elif (initial in single_quoted or\n token[:2]in single_quoted or\n token[:3]in single_quoted):\n if token[-1]=='\\n':\n strstart=(lnum,start)\n \n \n \n \n \n \n endprog=_compile(endpats.get(initial)or\n endpats.get(token[1])or\n endpats.get(token[2]))\n contstr,needcont=line[start:],1\n contline=line\n break\n else :\n yield TokenInfo(STRING,token,spos,epos,line)\n \n elif initial.isidentifier():\n yield TokenInfo(NAME,token,spos,epos,line)\n elif initial =='\\\\':\n continued=1\n else :\n if initial in '([{':\n parenlev +=1\n elif initial in ')]}':\n parenlev -=1\n yield TokenInfo(OP,token,spos,epos,line)\n else :\n yield TokenInfo(ERRORTOKEN,line[pos],\n (lnum,pos),(lnum,pos+1),line)\n pos +=1\n \n for indent in indents[1:]:\n yield TokenInfo(DEDENT,'',(lnum,0),(lnum,0),'')\n yield TokenInfo(ENDMARKER,'',(lnum,0),(lnum,0),'')\n \n \n \n \ndef generate_tokens(readline):\n return _tokenize(readline,None )\n \ndef main():\n import argparse\n \n \n def perror(message):\n print(message,file=sys.stderr)\n \n def error(message,filename=None ,location=None ):\n if location:\n args=(filename,)+location+(message,)\n perror(\"%s:%d:%d: error: %s\"%args)\n elif filename:\n perror(\"%s: error: %s\"%(filename,message))\n else :\n perror(\"error: %s\"%message)\n sys.exit(1)\n \n \n parser=argparse.ArgumentParser(prog='python -m tokenize')\n parser.add_argument(dest='filename',nargs='?',\n metavar='filename.py',\n help='the file to tokenize; defaults to stdin')\n parser.add_argument('-e','--exact',dest='exact',action='store_true',\n help='display token names using the exact type')\n args=parser.parse_args()\n \n try :\n \n if args.filename:\n filename=args.filename\n with _builtin_open(filename,'rb')as f:\n tokens=list(tokenize(f.readline))\n else :\n filename=\"<stdin>\"\n tokens=_tokenize(sys.stdin.readline,None )\n \n \n for token in tokens:\n token_type=token.type\n if args.exact:\n token_type=token.exact_type\n token_range=\"%d,%d-%d,%d:\"%(token.start+token.end)\n print(\"%-20s%-15s%-15r\"%\n (token_range,tok_name[token_type],token.string))\n except IndentationError as err:\n line,column=err.args[1][1:3]\n error(err.args[0],filename,(line,column))\n except TokenError as err:\n line,column=err.args[1]\n error(err.args[0],filename,(line,column))\n except SyntaxError as err:\n error(err,filename)\n except OSError as err:\n error(err)\n except KeyboardInterrupt:\n print(\"interrupted\\n\")\n except Exception as err:\n perror(\"unexpected error: %s\"%err)\n raise\n \nif __name__ ==\"__main__\":\n main()\n", ["argparse", "builtins", "codecs", "collections", "io", "itertools", "re", "sys", "token"]], "email._header_value_parser": [".py", "''\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\nimport re\nimport urllib\nfrom string import hexdigits\nfrom collections import OrderedDict\nfrom operator import itemgetter\nfrom email import _encoded_words as _ew\nfrom email import errors\nfrom email import utils\n\n\n\n\n\nWSP=set(' \\t')\nCFWS_LEADER=WSP |set('(')\nSPECIALS=set(r'()<>@,:;.\\\"[]')\nATOM_ENDS=SPECIALS |WSP\nDOT_ATOM_ENDS=ATOM_ENDS -set('.')\n\nPHRASE_ENDS=SPECIALS -set('.\"(')\nTSPECIALS=(SPECIALS |set('/?='))-set('.')\nTOKEN_ENDS=TSPECIALS |WSP\nASPECIALS=TSPECIALS |set(\"*'%\")\nATTRIBUTE_ENDS=ASPECIALS |WSP\nEXTENDED_ATTRIBUTE_ENDS=ATTRIBUTE_ENDS -set('%')\n\ndef quote_string(value):\n return '\"'+str(value).replace('\\\\','\\\\\\\\').replace('\"',r'\\\"')+'\"'\n \n \n \n \n \nclass TokenList(list):\n\n token_type=None\n syntactic_break=True\n ew_combine_allowed=True\n \n def __init__(self,*args,**kw):\n super().__init__(*args,**kw)\n self.defects=[]\n \n def __str__(self):\n return ''.join(str(x)for x in self)\n \n def __repr__(self):\n return '{}({})'.format(self.__class__.__name__,\n super().__repr__())\n \n @property\n def value(self):\n return ''.join(x.value for x in self if x.value)\n \n @property\n def all_defects(self):\n return sum((x.all_defects for x in self),self.defects)\n \n def startswith_fws(self):\n return self[0].startswith_fws()\n \n @property\n def as_ew_allowed(self):\n ''\n return all(part.as_ew_allowed for part in self)\n \n @property\n def comments(self):\n comments=[]\n for token in self:\n comments.extend(token.comments)\n return comments\n \n def fold(self,*,policy):\n return _refold_parse_tree(self,policy=policy)\n \n def pprint(self,indent=''):\n print(self.ppstr(indent=indent))\n \n def ppstr(self,indent=''):\n return '\\n'.join(self._pp(indent=indent))\n \n def _pp(self,indent=''):\n yield '{}{}/{}('.format(\n indent,\n self.__class__.__name__,\n self.token_type)\n for token in self:\n if not hasattr(token,'_pp'):\n yield (indent+' !! invalid element in token '\n 'list: {!r}'.format(token))\n else :\n yield from token._pp(indent+' ')\n if self.defects:\n extra=' Defects: {}'.format(self.defects)\n else :\n extra=''\n yield '{}){}'.format(indent,extra)\n \n \nclass WhiteSpaceTokenList(TokenList):\n\n @property\n def value(self):\n return ' '\n \n @property\n def comments(self):\n return [x.content for x in self if x.token_type =='comment']\n \n \nclass UnstructuredTokenList(TokenList):\n\n token_type='unstructured'\n \n \nclass Phrase(TokenList):\n\n token_type='phrase'\n \nclass Word(TokenList):\n\n token_type='word'\n \n \nclass CFWSList(WhiteSpaceTokenList):\n\n token_type='cfws'\n \n \nclass Atom(TokenList):\n\n token_type='atom'\n \n \nclass Token(TokenList):\n\n token_type='token'\n encode_as_ew=False\n \n \nclass EncodedWord(TokenList):\n\n token_type='encoded-word'\n cte=None\n charset=None\n lang=None\n \n \nclass QuotedString(TokenList):\n\n token_type='quoted-string'\n \n @property\n def content(self):\n for x in self:\n if x.token_type =='bare-quoted-string':\n return x.value\n \n @property\n def quoted_value(self):\n res=[]\n for x in self:\n if x.token_type =='bare-quoted-string':\n res.append(str(x))\n else :\n res.append(x.value)\n return ''.join(res)\n \n @property\n def stripped_value(self):\n for token in self:\n if token.token_type =='bare-quoted-string':\n return token.value\n \n \nclass BareQuotedString(QuotedString):\n\n token_type='bare-quoted-string'\n \n def __str__(self):\n return quote_string(''.join(str(x)for x in self))\n \n @property\n def value(self):\n return ''.join(str(x)for x in self)\n \n \nclass Comment(WhiteSpaceTokenList):\n\n token_type='comment'\n \n def __str__(self):\n return ''.join(sum([\n [\"(\"],\n [self.quote(x)for x in self],\n [\")\"],\n ],[]))\n \n def quote(self,value):\n if value.token_type =='comment':\n return str(value)\n return str(value).replace('\\\\','\\\\\\\\').replace(\n '(',r'\\(').replace(\n ')',r'\\)')\n \n @property\n def content(self):\n return ''.join(str(x)for x in self)\n \n @property\n def comments(self):\n return [self.content]\n \nclass AddressList(TokenList):\n\n token_type='address-list'\n \n @property\n def addresses(self):\n return [x for x in self if x.token_type =='address']\n \n @property\n def mailboxes(self):\n return sum((x.mailboxes\n for x in self if x.token_type =='address'),[])\n \n @property\n def all_mailboxes(self):\n return sum((x.all_mailboxes\n for x in self if x.token_type =='address'),[])\n \n \nclass Address(TokenList):\n\n token_type='address'\n \n @property\n def display_name(self):\n if self[0].token_type =='group':\n return self[0].display_name\n \n @property\n def mailboxes(self):\n if self[0].token_type =='mailbox':\n return [self[0]]\n elif self[0].token_type =='invalid-mailbox':\n return []\n return self[0].mailboxes\n \n @property\n def all_mailboxes(self):\n if self[0].token_type =='mailbox':\n return [self[0]]\n elif self[0].token_type =='invalid-mailbox':\n return [self[0]]\n return self[0].all_mailboxes\n \nclass MailboxList(TokenList):\n\n token_type='mailbox-list'\n \n @property\n def mailboxes(self):\n return [x for x in self if x.token_type =='mailbox']\n \n @property\n def all_mailboxes(self):\n return [x for x in self\n if x.token_type in ('mailbox','invalid-mailbox')]\n \n \nclass GroupList(TokenList):\n\n token_type='group-list'\n \n @property\n def mailboxes(self):\n if not self or self[0].token_type !='mailbox-list':\n return []\n return self[0].mailboxes\n \n @property\n def all_mailboxes(self):\n if not self or self[0].token_type !='mailbox-list':\n return []\n return self[0].all_mailboxes\n \n \nclass Group(TokenList):\n\n token_type=\"group\"\n \n @property\n def mailboxes(self):\n if self[2].token_type !='group-list':\n return []\n return self[2].mailboxes\n \n @property\n def all_mailboxes(self):\n if self[2].token_type !='group-list':\n return []\n return self[2].all_mailboxes\n \n @property\n def display_name(self):\n return self[0].display_name\n \n \nclass NameAddr(TokenList):\n\n token_type='name-addr'\n \n @property\n def display_name(self):\n if len(self)==1:\n return None\n return self[0].display_name\n \n @property\n def local_part(self):\n return self[-1].local_part\n \n @property\n def domain(self):\n return self[-1].domain\n \n @property\n def route(self):\n return self[-1].route\n \n @property\n def addr_spec(self):\n return self[-1].addr_spec\n \n \nclass AngleAddr(TokenList):\n\n token_type='angle-addr'\n \n @property\n def local_part(self):\n for x in self:\n if x.token_type =='addr-spec':\n return x.local_part\n \n @property\n def domain(self):\n for x in self:\n if x.token_type =='addr-spec':\n return x.domain\n \n @property\n def route(self):\n for x in self:\n if x.token_type =='obs-route':\n return x.domains\n \n @property\n def addr_spec(self):\n for x in self:\n if x.token_type =='addr-spec':\n if x.local_part:\n return x.addr_spec\n else :\n return quote_string(x.local_part)+x.addr_spec\n else :\n return '<>'\n \n \nclass ObsRoute(TokenList):\n\n token_type='obs-route'\n \n @property\n def domains(self):\n return [x.domain for x in self if x.token_type =='domain']\n \n \nclass Mailbox(TokenList):\n\n token_type='mailbox'\n \n @property\n def display_name(self):\n if self[0].token_type =='name-addr':\n return self[0].display_name\n \n @property\n def local_part(self):\n return self[0].local_part\n \n @property\n def domain(self):\n return self[0].domain\n \n @property\n def route(self):\n if self[0].token_type =='name-addr':\n return self[0].route\n \n @property\n def addr_spec(self):\n return self[0].addr_spec\n \n \nclass InvalidMailbox(TokenList):\n\n token_type='invalid-mailbox'\n \n @property\n def display_name(self):\n return None\n \n local_part=domain=route=addr_spec=display_name\n \n \nclass Domain(TokenList):\n\n token_type='domain'\n as_ew_allowed=False\n \n @property\n def domain(self):\n return ''.join(super().value.split())\n \n \nclass DotAtom(TokenList):\n\n token_type='dot-atom'\n \n \nclass DotAtomText(TokenList):\n\n token_type='dot-atom-text'\n as_ew_allowed=True\n \n \nclass AddrSpec(TokenList):\n\n token_type='addr-spec'\n as_ew_allowed=False\n \n @property\n def local_part(self):\n return self[0].local_part\n \n @property\n def domain(self):\n if len(self)<3:\n return None\n return self[-1].domain\n \n @property\n def value(self):\n if len(self)<3:\n return self[0].value\n return self[0].value.rstrip()+self[1].value+self[2].value.lstrip()\n \n @property\n def addr_spec(self):\n nameset=set(self.local_part)\n if len(nameset)>len(nameset -DOT_ATOM_ENDS):\n lp=quote_string(self.local_part)\n else :\n lp=self.local_part\n if self.domain is not None :\n return lp+'@'+self.domain\n return lp\n \n \nclass ObsLocalPart(TokenList):\n\n token_type='obs-local-part'\n as_ew_allowed=False\n \n \nclass DisplayName(Phrase):\n\n token_type='display-name'\n ew_combine_allowed=False\n \n @property\n def display_name(self):\n res=TokenList(self)\n if res[0].token_type =='cfws':\n res.pop(0)\n else :\n if res[0][0].token_type =='cfws':\n res[0]=TokenList(res[0][1:])\n if res[-1].token_type =='cfws':\n res.pop()\n else :\n if res[-1][-1].token_type =='cfws':\n res[-1]=TokenList(res[-1][:-1])\n return res.value\n \n @property\n def value(self):\n quote=False\n if self.defects:\n quote=True\n else :\n for x in self:\n if x.token_type =='quoted-string':\n quote=True\n if quote:\n pre=post=''\n if self[0].token_type =='cfws'or self[0][0].token_type =='cfws':\n pre=' '\n if self[-1].token_type =='cfws'or self[-1][-1].token_type =='cfws':\n post=' '\n return pre+quote_string(self.display_name)+post\n else :\n return super().value\n \n \nclass LocalPart(TokenList):\n\n token_type='local-part'\n as_ew_allowed=False\n \n @property\n def value(self):\n if self[0].token_type ==\"quoted-string\":\n return self[0].quoted_value\n else :\n return self[0].value\n \n @property\n def local_part(self):\n \n res=[DOT]\n last=DOT\n last_is_tl=False\n for tok in self[0]+[DOT]:\n if tok.token_type =='cfws':\n continue\n if (last_is_tl and tok.token_type =='dot'and\n last[-1].token_type =='cfws'):\n res[-1]=TokenList(last[:-1])\n is_tl=isinstance(tok,TokenList)\n if (is_tl and last.token_type =='dot'and\n tok[0].token_type =='cfws'):\n res.append(TokenList(tok[1:]))\n else :\n res.append(tok)\n last=res[-1]\n last_is_tl=is_tl\n res=TokenList(res[1:-1])\n return res.value\n \n \nclass DomainLiteral(TokenList):\n\n token_type='domain-literal'\n as_ew_allowed=False\n \n @property\n def domain(self):\n return ''.join(super().value.split())\n \n @property\n def ip(self):\n for x in self:\n if x.token_type =='ptext':\n return x.value\n \n \nclass MIMEVersion(TokenList):\n\n token_type='mime-version'\n major=None\n minor=None\n \n \nclass Parameter(TokenList):\n\n token_type='parameter'\n sectioned=False\n extended=False\n charset='us-ascii'\n \n @property\n def section_number(self):\n \n \n return self[1].number if self.sectioned else 0\n \n @property\n def param_value(self):\n \n for token in self:\n if token.token_type =='value':\n return token.stripped_value\n if token.token_type =='quoted-string':\n for token in token:\n if token.token_type =='bare-quoted-string':\n for token in token:\n if token.token_type =='value':\n return token.stripped_value\n return ''\n \n \nclass InvalidParameter(Parameter):\n\n token_type='invalid-parameter'\n \n \nclass Attribute(TokenList):\n\n token_type='attribute'\n \n @property\n def stripped_value(self):\n for token in self:\n if token.token_type.endswith('attrtext'):\n return token.value\n \nclass Section(TokenList):\n\n token_type='section'\n number=None\n \n \nclass Value(TokenList):\n\n token_type='value'\n \n @property\n def stripped_value(self):\n token=self[0]\n if token.token_type =='cfws':\n token=self[1]\n if token.token_type.endswith(\n ('quoted-string','attribute','extended-attribute')):\n return token.stripped_value\n return self.value\n \n \nclass MimeParameters(TokenList):\n\n token_type='mime-parameters'\n syntactic_break=False\n \n @property\n def params(self):\n \n \n \n \n \n params=OrderedDict()\n for token in self:\n if not token.token_type.endswith('parameter'):\n continue\n if token[0].token_type !='attribute':\n continue\n name=token[0].value.strip()\n if name not in params:\n params[name]=[]\n params[name].append((token.section_number,token))\n for name,parts in params.items():\n parts=sorted(parts,key=itemgetter(0))\n first_param=parts[0][1]\n charset=first_param.charset\n \n \n \n if not first_param.extended and len(parts)>1:\n if parts[1][0]==0:\n parts[1][1].defects.append(errors.InvalidHeaderDefect(\n 'duplicate parameter name; duplicate(s) ignored'))\n parts=parts[:1]\n \n \n value_parts=[]\n i=0\n for section_number,param in parts:\n if section_number !=i:\n \n \n \n if not param.extended:\n param.defects.append(errors.InvalidHeaderDefect(\n 'duplicate parameter name; duplicate ignored'))\n continue\n else :\n param.defects.append(errors.InvalidHeaderDefect(\n \"inconsistent RFC2231 parameter numbering\"))\n i +=1\n value=param.param_value\n if param.extended:\n try :\n value=urllib.parse.unquote_to_bytes(value)\n except UnicodeEncodeError:\n \n \n \n value=urllib.parse.unquote(value,encoding='latin-1')\n else :\n try :\n value=value.decode(charset,'surrogateescape')\n except LookupError:\n \n \n \n \n value=value.decode('us-ascii','surrogateescape')\n if utils._has_surrogates(value):\n param.defects.append(errors.UndecodableBytesDefect())\n value_parts.append(value)\n value=''.join(value_parts)\n yield name,value\n \n def __str__(self):\n params=[]\n for name,value in self.params:\n if value:\n params.append('{}={}'.format(name,quote_string(value)))\n else :\n params.append(name)\n params='; '.join(params)\n return ' '+params if params else ''\n \n \nclass ParameterizedHeaderValue(TokenList):\n\n\n\n syntactic_break=False\n \n @property\n def params(self):\n for token in reversed(self):\n if token.token_type =='mime-parameters':\n return token.params\n return {}\n \n \nclass ContentType(ParameterizedHeaderValue):\n\n token_type='content-type'\n as_ew_allowed=False\n maintype='text'\n subtype='plain'\n \n \nclass ContentDisposition(ParameterizedHeaderValue):\n\n token_type='content-disposition'\n as_ew_allowed=False\n content_disposition=None\n \n \nclass ContentTransferEncoding(TokenList):\n\n token_type='content-transfer-encoding'\n as_ew_allowed=False\n cte='7bit'\n \n \nclass HeaderLabel(TokenList):\n\n token_type='header-label'\n as_ew_allowed=False\n \n \nclass Header(TokenList):\n\n token_type='header'\n \n \n \n \n \n \nclass Terminal(str):\n\n as_ew_allowed=True\n ew_combine_allowed=True\n syntactic_break=True\n \n def __new__(cls,value,token_type):\n self=super().__new__(cls,value)\n self.token_type=token_type\n self.defects=[]\n return self\n \n def __repr__(self):\n return \"{}({})\".format(self.__class__.__name__,super().__repr__())\n \n def pprint(self):\n print(self.__class__.__name__+'/'+self.token_type)\n \n @property\n def all_defects(self):\n return list(self.defects)\n \n def _pp(self,indent=''):\n return [\"{}{}/{}({}){}\".format(\n indent,\n self.__class__.__name__,\n self.token_type,\n super().__repr__(),\n ''if not self.defects else ' {}'.format(self.defects),\n )]\n \n def pop_trailing_ws(self):\n \n return None\n \n @property\n def comments(self):\n return []\n \n def __getnewargs__(self):\n return (str(self),self.token_type)\n \n \nclass WhiteSpaceTerminal(Terminal):\n\n @property\n def value(self):\n return ' '\n \n def startswith_fws(self):\n return True\n \n \nclass ValueTerminal(Terminal):\n\n @property\n def value(self):\n return self\n \n def startswith_fws(self):\n return False\n \n \nclass EWWhiteSpaceTerminal(WhiteSpaceTerminal):\n\n @property\n def value(self):\n return ''\n \n def __str__(self):\n return ''\n \n \n \n \n \nDOT=ValueTerminal('.','dot')\nListSeparator=ValueTerminal(',','list-separator')\nRouteComponentMarker=ValueTerminal('@','route-component-marker')\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n_wsp_splitter=re.compile(r'([{}]+)'.format(''.join(WSP))).split\n_non_atom_end_matcher=re.compile(r\"[^{}]+\".format(\nre.escape(''.join(ATOM_ENDS)))).match\n_non_printable_finder=re.compile(r\"[\\x00-\\x20\\x7F]\").findall\n_non_token_end_matcher=re.compile(r\"[^{}]+\".format(\nre.escape(''.join(TOKEN_ENDS)))).match\n_non_attribute_end_matcher=re.compile(r\"[^{}]+\".format(\nre.escape(''.join(ATTRIBUTE_ENDS)))).match\n_non_extended_attribute_end_matcher=re.compile(r\"[^{}]+\".format(\nre.escape(''.join(EXTENDED_ATTRIBUTE_ENDS)))).match\n\ndef _validate_xtext(xtext):\n ''\n \n non_printables=_non_printable_finder(xtext)\n if non_printables:\n xtext.defects.append(errors.NonPrintableDefect(non_printables))\n if utils._has_surrogates(xtext):\n xtext.defects.append(errors.UndecodableBytesDefect(\n \"Non-ASCII characters found in header token\"))\n \ndef _get_ptext_to_endchars(value,endchars):\n ''\n\n\n\n\n\n\n \n fragment,*remainder=_wsp_splitter(value,1)\n vchars=[]\n escape=False\n had_qp=False\n for pos in range(len(fragment)):\n if fragment[pos]=='\\\\':\n if escape:\n escape=False\n had_qp=True\n else :\n escape=True\n continue\n if escape:\n escape=False\n elif fragment[pos]in endchars:\n break\n vchars.append(fragment[pos])\n else :\n pos=pos+1\n return ''.join(vchars),''.join([fragment[pos:]]+remainder),had_qp\n \ndef get_fws(value):\n ''\n\n\n\n\n\n \n newvalue=value.lstrip()\n fws=WhiteSpaceTerminal(value[:len(value)-len(newvalue)],'fws')\n return fws,newvalue\n \ndef get_encoded_word(value):\n ''\n\n \n ew=EncodedWord()\n if not value.startswith('=?'):\n raise errors.HeaderParseError(\n \"expected encoded word but found {}\".format(value))\n tok,*remainder=value[2:].split('?=',1)\n if tok ==value[2:]:\n raise errors.HeaderParseError(\n \"expected encoded word but found {}\".format(value))\n remstr=''.join(remainder)\n if len(remstr)>1 and remstr[0]in hexdigits and remstr[1]in hexdigits:\n \n rest,*remainder=remstr.split('?=',1)\n tok=tok+'?='+rest\n if len(tok.split())>1:\n ew.defects.append(errors.InvalidHeaderDefect(\n \"whitespace inside encoded word\"))\n ew.cte=value\n value=''.join(remainder)\n try :\n text,charset,lang,defects=_ew.decode('=?'+tok+'?=')\n except ValueError:\n raise errors.HeaderParseError(\n \"encoded word format invalid: '{}'\".format(ew.cte))\n ew.charset=charset\n ew.lang=lang\n ew.defects.extend(defects)\n while text:\n if text[0]in WSP:\n token,text=get_fws(text)\n ew.append(token)\n continue\n chars,*remainder=_wsp_splitter(text,1)\n vtext=ValueTerminal(chars,'vtext')\n _validate_xtext(vtext)\n ew.append(vtext)\n text=''.join(remainder)\n return ew,value\n \ndef get_unstructured(value):\n ''\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n \n \n \n \n \n unstructured=UnstructuredTokenList()\n while value:\n if value[0]in WSP:\n token,value=get_fws(value)\n unstructured.append(token)\n continue\n if value.startswith('=?'):\n try :\n token,value=get_encoded_word(value)\n except errors.HeaderParseError:\n \n \n pass\n else :\n have_ws=True\n if len(unstructured)>0:\n if unstructured[-1].token_type !='fws':\n unstructured.defects.append(errors.InvalidHeaderDefect(\n \"missing whitespace before encoded word\"))\n have_ws=False\n if have_ws and len(unstructured)>1:\n if unstructured[-2].token_type =='encoded-word':\n unstructured[-1]=EWWhiteSpaceTerminal(\n unstructured[-1],'fws')\n unstructured.append(token)\n continue\n tok,*remainder=_wsp_splitter(value,1)\n vtext=ValueTerminal(tok,'vtext')\n _validate_xtext(vtext)\n unstructured.append(vtext)\n value=''.join(remainder)\n return unstructured\n \ndef get_qp_ctext(value):\n ''\n\n\n\n\n\n\n\n\n\n \n ptext,value,_=_get_ptext_to_endchars(value,'()')\n ptext=WhiteSpaceTerminal(ptext,'ptext')\n _validate_xtext(ptext)\n return ptext,value\n \ndef get_qcontent(value):\n ''\n\n\n\n\n\n\n\n \n ptext,value,_=_get_ptext_to_endchars(value,'\"')\n ptext=ValueTerminal(ptext,'ptext')\n _validate_xtext(ptext)\n return ptext,value\n \ndef get_atext(value):\n ''\n\n\n\n \n m=_non_atom_end_matcher(value)\n if not m:\n raise errors.HeaderParseError(\n \"expected atext but found '{}'\".format(value))\n atext=m.group()\n value=value[len(atext):]\n atext=ValueTerminal(atext,'atext')\n _validate_xtext(atext)\n return atext,value\n \ndef get_bare_quoted_string(value):\n ''\n\n\n\n\n \n if value[0]!='\"':\n raise errors.HeaderParseError(\n \"expected '\\\"' but found '{}'\".format(value))\n bare_quoted_string=BareQuotedString()\n value=value[1:]\n if value[0]=='\"':\n token,value=get_qcontent(value)\n bare_quoted_string.append(token)\n while value and value[0]!='\"':\n if value[0]in WSP:\n token,value=get_fws(value)\n elif value[:2]=='=?':\n try :\n token,value=get_encoded_word(value)\n bare_quoted_string.defects.append(errors.InvalidHeaderDefect(\n \"encoded word inside quoted string\"))\n except errors.HeaderParseError:\n token,value=get_qcontent(value)\n else :\n token,value=get_qcontent(value)\n bare_quoted_string.append(token)\n if not value:\n bare_quoted_string.defects.append(errors.InvalidHeaderDefect(\n \"end of header inside quoted string\"))\n return bare_quoted_string,value\n return bare_quoted_string,value[1:]\n \ndef get_comment(value):\n ''\n\n\n\n \n if value and value[0]!='(':\n raise errors.HeaderParseError(\n \"expected '(' but found '{}'\".format(value))\n comment=Comment()\n value=value[1:]\n while value and value[0]!=\")\":\n if value[0]in WSP:\n token,value=get_fws(value)\n elif value[0]=='(':\n token,value=get_comment(value)\n else :\n token,value=get_qp_ctext(value)\n comment.append(token)\n if not value:\n comment.defects.append(errors.InvalidHeaderDefect(\n \"end of header inside comment\"))\n return comment,value\n return comment,value[1:]\n \ndef get_cfws(value):\n ''\n\n \n cfws=CFWSList()\n while value and value[0]in CFWS_LEADER:\n if value[0]in WSP:\n token,value=get_fws(value)\n else :\n token,value=get_comment(value)\n cfws.append(token)\n return cfws,value\n \ndef get_quoted_string(value):\n ''\n\n\n\n\n \n quoted_string=QuotedString()\n if value and value[0]in CFWS_LEADER:\n token,value=get_cfws(value)\n quoted_string.append(token)\n token,value=get_bare_quoted_string(value)\n quoted_string.append(token)\n if value and value[0]in CFWS_LEADER:\n token,value=get_cfws(value)\n quoted_string.append(token)\n return quoted_string,value\n \ndef get_atom(value):\n ''\n\n\n \n atom=Atom()\n if value and value[0]in CFWS_LEADER:\n token,value=get_cfws(value)\n atom.append(token)\n if value and value[0]in ATOM_ENDS:\n raise errors.HeaderParseError(\n \"expected atom but found '{}'\".format(value))\n if value.startswith('=?'):\n try :\n token,value=get_encoded_word(value)\n except errors.HeaderParseError:\n \n \n token,value=get_atext(value)\n else :\n token,value=get_atext(value)\n atom.append(token)\n if value and value[0]in CFWS_LEADER:\n token,value=get_cfws(value)\n atom.append(token)\n return atom,value\n \ndef get_dot_atom_text(value):\n ''\n\n \n dot_atom_text=DotAtomText()\n if not value or value[0]in ATOM_ENDS:\n raise errors.HeaderParseError(\"expected atom at a start of \"\n \"dot-atom-text but found '{}'\".format(value))\n while value and value[0]not in ATOM_ENDS:\n token,value=get_atext(value)\n dot_atom_text.append(token)\n if value and value[0]=='.':\n dot_atom_text.append(DOT)\n value=value[1:]\n if dot_atom_text[-1]is DOT:\n raise errors.HeaderParseError(\"expected atom at end of dot-atom-text \"\n \"but found '{}'\".format('.'+value))\n return dot_atom_text,value\n \ndef get_dot_atom(value):\n ''\n\n\n\n \n dot_atom=DotAtom()\n if value[0]in CFWS_LEADER:\n token,value=get_cfws(value)\n dot_atom.append(token)\n if value.startswith('=?'):\n try :\n token,value=get_encoded_word(value)\n except errors.HeaderParseError:\n \n \n token,value=get_dot_atom_text(value)\n else :\n token,value=get_dot_atom_text(value)\n dot_atom.append(token)\n if value and value[0]in CFWS_LEADER:\n token,value=get_cfws(value)\n dot_atom.append(token)\n return dot_atom,value\n \ndef get_word(value):\n ''\n\n\n\n\n\n\n\n\n\n\n\n\n\n \n if value[0]in CFWS_LEADER:\n leader,value=get_cfws(value)\n else :\n leader=None\n if value[0]=='\"':\n token,value=get_quoted_string(value)\n elif value[0]in SPECIALS:\n raise errors.HeaderParseError(\"Expected 'atom' or 'quoted-string' \"\n \"but found '{}'\".format(value))\n else :\n token,value=get_atom(value)\n if leader is not None :\n token[:0]=[leader]\n return token,value\n \ndef get_phrase(value):\n ''\n\n\n\n\n\n\n\n\n\n \n phrase=Phrase()\n try :\n token,value=get_word(value)\n phrase.append(token)\n except errors.HeaderParseError:\n phrase.defects.append(errors.InvalidHeaderDefect(\n \"phrase does not start with word\"))\n while value and value[0]not in PHRASE_ENDS:\n if value[0]=='.':\n phrase.append(DOT)\n phrase.defects.append(errors.ObsoleteHeaderDefect(\n \"period in 'phrase'\"))\n value=value[1:]\n else :\n try :\n token,value=get_word(value)\n except errors.HeaderParseError:\n if value[0]in CFWS_LEADER:\n token,value=get_cfws(value)\n phrase.defects.append(errors.ObsoleteHeaderDefect(\n \"comment found without atom\"))\n else :\n raise\n phrase.append(token)\n return phrase,value\n \ndef get_local_part(value):\n ''\n\n \n local_part=LocalPart()\n leader=None\n if value[0]in CFWS_LEADER:\n leader,value=get_cfws(value)\n if not value:\n raise errors.HeaderParseError(\n \"expected local-part but found '{}'\".format(value))\n try :\n token,value=get_dot_atom(value)\n except errors.HeaderParseError:\n try :\n token,value=get_word(value)\n except errors.HeaderParseError:\n if value[0]!='\\\\'and value[0]in PHRASE_ENDS:\n raise\n token=TokenList()\n if leader is not None :\n token[:0]=[leader]\n local_part.append(token)\n if value and (value[0]=='\\\\'or value[0]not in PHRASE_ENDS):\n obs_local_part,value=get_obs_local_part(str(local_part)+value)\n if obs_local_part.token_type =='invalid-obs-local-part':\n local_part.defects.append(errors.InvalidHeaderDefect(\n \"local-part is not dot-atom, quoted-string, or obs-local-part\"))\n else :\n local_part.defects.append(errors.ObsoleteHeaderDefect(\n \"local-part is not a dot-atom (contains CFWS)\"))\n local_part[0]=obs_local_part\n try :\n local_part.value.encode('ascii')\n except UnicodeEncodeError:\n local_part.defects.append(errors.NonASCIILocalPartDefect(\n \"local-part contains non-ASCII characters)\"))\n return local_part,value\n \ndef get_obs_local_part(value):\n ''\n \n obs_local_part=ObsLocalPart()\n last_non_ws_was_dot=False\n while value and (value[0]=='\\\\'or value[0]not in PHRASE_ENDS):\n if value[0]=='.':\n if last_non_ws_was_dot:\n obs_local_part.defects.append(errors.InvalidHeaderDefect(\n \"invalid repeated '.'\"))\n obs_local_part.append(DOT)\n last_non_ws_was_dot=True\n value=value[1:]\n continue\n elif value[0]=='\\\\':\n obs_local_part.append(ValueTerminal(value[0],\n 'misplaced-special'))\n value=value[1:]\n obs_local_part.defects.append(errors.InvalidHeaderDefect(\n \"'\\\\' character outside of quoted-string/ccontent\"))\n last_non_ws_was_dot=False\n continue\n if obs_local_part and obs_local_part[-1].token_type !='dot':\n obs_local_part.defects.append(errors.InvalidHeaderDefect(\n \"missing '.' between words\"))\n try :\n token,value=get_word(value)\n last_non_ws_was_dot=False\n except errors.HeaderParseError:\n if value[0]not in CFWS_LEADER:\n raise\n token,value=get_cfws(value)\n obs_local_part.append(token)\n if (obs_local_part[0].token_type =='dot'or\n obs_local_part[0].token_type =='cfws'and\n obs_local_part[1].token_type =='dot'):\n obs_local_part.defects.append(errors.InvalidHeaderDefect(\n \"Invalid leading '.' in local part\"))\n if (obs_local_part[-1].token_type =='dot'or\n obs_local_part[-1].token_type =='cfws'and\n obs_local_part[-2].token_type =='dot'):\n obs_local_part.defects.append(errors.InvalidHeaderDefect(\n \"Invalid trailing '.' in local part\"))\n if obs_local_part.defects:\n obs_local_part.token_type='invalid-obs-local-part'\n return obs_local_part,value\n \ndef get_dtext(value):\n ''\n\n\n\n\n\n\n\n\n\n \n ptext,value,had_qp=_get_ptext_to_endchars(value,'[]')\n ptext=ValueTerminal(ptext,'ptext')\n if had_qp:\n ptext.defects.append(errors.ObsoleteHeaderDefect(\n \"quoted printable found in domain-literal\"))\n _validate_xtext(ptext)\n return ptext,value\n \ndef _check_for_early_dl_end(value,domain_literal):\n if value:\n return False\n domain_literal.append(errors.InvalidHeaderDefect(\n \"end of input inside domain-literal\"))\n domain_literal.append(ValueTerminal(']','domain-literal-end'))\n return True\n \ndef get_domain_literal(value):\n ''\n\n \n domain_literal=DomainLiteral()\n if value[0]in CFWS_LEADER:\n token,value=get_cfws(value)\n domain_literal.append(token)\n if not value:\n raise errors.HeaderParseError(\"expected domain-literal\")\n if value[0]!='[':\n raise errors.HeaderParseError(\"expected '[' at start of domain-literal \"\n \"but found '{}'\".format(value))\n value=value[1:]\n if _check_for_early_dl_end(value,domain_literal):\n return domain_literal,value\n domain_literal.append(ValueTerminal('[','domain-literal-start'))\n if value[0]in WSP:\n token,value=get_fws(value)\n domain_literal.append(token)\n token,value=get_dtext(value)\n domain_literal.append(token)\n if _check_for_early_dl_end(value,domain_literal):\n return domain_literal,value\n if value[0]in WSP:\n token,value=get_fws(value)\n domain_literal.append(token)\n if _check_for_early_dl_end(value,domain_literal):\n return domain_literal,value\n if value[0]!=']':\n raise errors.HeaderParseError(\"expected ']' at end of domain-literal \"\n \"but found '{}'\".format(value))\n domain_literal.append(ValueTerminal(']','domain-literal-end'))\n value=value[1:]\n if value and value[0]in CFWS_LEADER:\n token,value=get_cfws(value)\n domain_literal.append(token)\n return domain_literal,value\n \ndef get_domain(value):\n ''\n\n\n \n domain=Domain()\n leader=None\n if value[0]in CFWS_LEADER:\n leader,value=get_cfws(value)\n if not value:\n raise errors.HeaderParseError(\n \"expected domain but found '{}'\".format(value))\n if value[0]=='[':\n token,value=get_domain_literal(value)\n if leader is not None :\n token[:0]=[leader]\n domain.append(token)\n return domain,value\n try :\n token,value=get_dot_atom(value)\n except errors.HeaderParseError:\n token,value=get_atom(value)\n if leader is not None :\n token[:0]=[leader]\n domain.append(token)\n if value and value[0]=='.':\n domain.defects.append(errors.ObsoleteHeaderDefect(\n \"domain is not a dot-atom (contains CFWS)\"))\n if domain[0].token_type =='dot-atom':\n domain[:]=domain[0]\n while value and value[0]=='.':\n domain.append(DOT)\n token,value=get_atom(value[1:])\n domain.append(token)\n return domain,value\n \ndef get_addr_spec(value):\n ''\n\n \n addr_spec=AddrSpec()\n token,value=get_local_part(value)\n addr_spec.append(token)\n if not value or value[0]!='@':\n addr_spec.defects.append(errors.InvalidHeaderDefect(\n \"add-spec local part with no domain\"))\n return addr_spec,value\n addr_spec.append(ValueTerminal('@','address-at-symbol'))\n token,value=get_domain(value[1:])\n addr_spec.append(token)\n return addr_spec,value\n \ndef get_obs_route(value):\n ''\n\n\n\n\n \n obs_route=ObsRoute()\n while value and (value[0]==','or value[0]in CFWS_LEADER):\n if value[0]in CFWS_LEADER:\n token,value=get_cfws(value)\n obs_route.append(token)\n elif value[0]==',':\n obs_route.append(ListSeparator)\n value=value[1:]\n if not value or value[0]!='@':\n raise errors.HeaderParseError(\n \"expected obs-route domain but found '{}'\".format(value))\n obs_route.append(RouteComponentMarker)\n token,value=get_domain(value[1:])\n obs_route.append(token)\n while value and value[0]==',':\n obs_route.append(ListSeparator)\n value=value[1:]\n if not value:\n break\n if value[0]in CFWS_LEADER:\n token,value=get_cfws(value)\n obs_route.append(token)\n if value[0]=='@':\n obs_route.append(RouteComponentMarker)\n token,value=get_domain(value[1:])\n obs_route.append(token)\n if not value:\n raise errors.HeaderParseError(\"end of header while parsing obs-route\")\n if value[0]!=':':\n raise errors.HeaderParseError(\"expected ':' marking end of \"\n \"obs-route but found '{}'\".format(value))\n obs_route.append(ValueTerminal(':','end-of-obs-route-marker'))\n return obs_route,value[1:]\n \ndef get_angle_addr(value):\n ''\n\n\n \n angle_addr=AngleAddr()\n if value[0]in CFWS_LEADER:\n token,value=get_cfws(value)\n angle_addr.append(token)\n if not value or value[0]!='<':\n raise errors.HeaderParseError(\n \"expected angle-addr but found '{}'\".format(value))\n angle_addr.append(ValueTerminal('<','angle-addr-start'))\n value=value[1:]\n \n \n if value[0]=='>':\n angle_addr.append(ValueTerminal('>','angle-addr-end'))\n angle_addr.defects.append(errors.InvalidHeaderDefect(\n \"null addr-spec in angle-addr\"))\n value=value[1:]\n return angle_addr,value\n try :\n token,value=get_addr_spec(value)\n except errors.HeaderParseError:\n try :\n token,value=get_obs_route(value)\n angle_addr.defects.append(errors.ObsoleteHeaderDefect(\n \"obsolete route specification in angle-addr\"))\n except errors.HeaderParseError:\n raise errors.HeaderParseError(\n \"expected addr-spec or obs-route but found '{}'\".format(value))\n angle_addr.append(token)\n token,value=get_addr_spec(value)\n angle_addr.append(token)\n if value and value[0]=='>':\n value=value[1:]\n else :\n angle_addr.defects.append(errors.InvalidHeaderDefect(\n \"missing trailing '>' on angle-addr\"))\n angle_addr.append(ValueTerminal('>','angle-addr-end'))\n if value and value[0]in CFWS_LEADER:\n token,value=get_cfws(value)\n angle_addr.append(token)\n return angle_addr,value\n \ndef get_display_name(value):\n ''\n\n\n\n\n\n \n display_name=DisplayName()\n token,value=get_phrase(value)\n display_name.extend(token[:])\n display_name.defects=token.defects[:]\n return display_name,value\n \n \ndef get_name_addr(value):\n ''\n\n \n name_addr=NameAddr()\n \n leader=None\n if value[0]in CFWS_LEADER:\n leader,value=get_cfws(value)\n if not value:\n raise errors.HeaderParseError(\n \"expected name-addr but found '{}'\".format(leader))\n if value[0]!='<':\n if value[0]in PHRASE_ENDS:\n raise errors.HeaderParseError(\n \"expected name-addr but found '{}'\".format(value))\n token,value=get_display_name(value)\n if not value:\n raise errors.HeaderParseError(\n \"expected name-addr but found '{}'\".format(token))\n if leader is not None :\n token[0][:0]=[leader]\n leader=None\n name_addr.append(token)\n token,value=get_angle_addr(value)\n if leader is not None :\n token[:0]=[leader]\n name_addr.append(token)\n return name_addr,value\n \ndef get_mailbox(value):\n ''\n\n \n \n \n mailbox=Mailbox()\n try :\n token,value=get_name_addr(value)\n except errors.HeaderParseError:\n try :\n token,value=get_addr_spec(value)\n except errors.HeaderParseError:\n raise errors.HeaderParseError(\n \"expected mailbox but found '{}'\".format(value))\n if any(isinstance(x,errors.InvalidHeaderDefect)\n for x in token.all_defects):\n mailbox.token_type='invalid-mailbox'\n mailbox.append(token)\n return mailbox,value\n \ndef get_invalid_mailbox(value,endchars):\n ''\n\n\n\n\n \n invalid_mailbox=InvalidMailbox()\n while value and value[0]not in endchars:\n if value[0]in PHRASE_ENDS:\n invalid_mailbox.append(ValueTerminal(value[0],\n 'misplaced-special'))\n value=value[1:]\n else :\n token,value=get_phrase(value)\n invalid_mailbox.append(token)\n return invalid_mailbox,value\n \ndef get_mailbox_list(value):\n ''\n\n\n\n\n\n\n\n\n\n \n mailbox_list=MailboxList()\n while value and value[0]!=';':\n try :\n token,value=get_mailbox(value)\n mailbox_list.append(token)\n except errors.HeaderParseError:\n leader=None\n if value[0]in CFWS_LEADER:\n leader,value=get_cfws(value)\n if not value or value[0]in ',;':\n mailbox_list.append(leader)\n mailbox_list.defects.append(errors.ObsoleteHeaderDefect(\n \"empty element in mailbox-list\"))\n else :\n token,value=get_invalid_mailbox(value,',;')\n if leader is not None :\n token[:0]=[leader]\n mailbox_list.append(token)\n mailbox_list.defects.append(errors.InvalidHeaderDefect(\n \"invalid mailbox in mailbox-list\"))\n elif value[0]==',':\n mailbox_list.defects.append(errors.ObsoleteHeaderDefect(\n \"empty element in mailbox-list\"))\n else :\n token,value=get_invalid_mailbox(value,',;')\n if leader is not None :\n token[:0]=[leader]\n mailbox_list.append(token)\n mailbox_list.defects.append(errors.InvalidHeaderDefect(\n \"invalid mailbox in mailbox-list\"))\n if value and value[0]not in ',;':\n \n \n mailbox=mailbox_list[-1]\n mailbox.token_type='invalid-mailbox'\n token,value=get_invalid_mailbox(value,',;')\n mailbox.extend(token)\n mailbox_list.defects.append(errors.InvalidHeaderDefect(\n \"invalid mailbox in mailbox-list\"))\n if value and value[0]==',':\n mailbox_list.append(ListSeparator)\n value=value[1:]\n return mailbox_list,value\n \n \ndef get_group_list(value):\n ''\n\n\n \n group_list=GroupList()\n if not value:\n group_list.defects.append(errors.InvalidHeaderDefect(\n \"end of header before group-list\"))\n return group_list,value\n leader=None\n if value and value[0]in CFWS_LEADER:\n leader,value=get_cfws(value)\n if not value:\n \n \n \n group_list.defects.append(errors.InvalidHeaderDefect(\n \"end of header in group-list\"))\n group_list.append(leader)\n return group_list,value\n if value[0]==';':\n group_list.append(leader)\n return group_list,value\n token,value=get_mailbox_list(value)\n if len(token.all_mailboxes)==0:\n if leader is not None :\n group_list.append(leader)\n group_list.extend(token)\n group_list.defects.append(errors.ObsoleteHeaderDefect(\n \"group-list with empty entries\"))\n return group_list,value\n if leader is not None :\n token[:0]=[leader]\n group_list.append(token)\n return group_list,value\n \ndef get_group(value):\n ''\n\n \n group=Group()\n token,value=get_display_name(value)\n if not value or value[0]!=':':\n raise errors.HeaderParseError(\"expected ':' at end of group \"\n \"display name but found '{}'\".format(value))\n group.append(token)\n group.append(ValueTerminal(':','group-display-name-terminator'))\n value=value[1:]\n if value and value[0]==';':\n group.append(ValueTerminal(';','group-terminator'))\n return group,value[1:]\n token,value=get_group_list(value)\n group.append(token)\n if not value:\n group.defects.append(errors.InvalidHeaderDefect(\n \"end of header in group\"))\n if value[0]!=';':\n raise errors.HeaderParseError(\n \"expected ';' at end of group but found {}\".format(value))\n group.append(ValueTerminal(';','group-terminator'))\n value=value[1:]\n if value and value[0]in CFWS_LEADER:\n token,value=get_cfws(value)\n group.append(token)\n return group,value\n \ndef get_address(value):\n ''\n\n\n\n\n\n\n\n \n \n \n \n \n \n \n \n address=Address()\n try :\n token,value=get_group(value)\n except errors.HeaderParseError:\n try :\n token,value=get_mailbox(value)\n except errors.HeaderParseError:\n raise errors.HeaderParseError(\n \"expected address but found '{}'\".format(value))\n address.append(token)\n return address,value\n \ndef get_address_list(value):\n ''\n\n\n\n\n\n\n\n \n address_list=AddressList()\n while value:\n try :\n token,value=get_address(value)\n address_list.append(token)\n except errors.HeaderParseError as err:\n leader=None\n if value[0]in CFWS_LEADER:\n leader,value=get_cfws(value)\n if not value or value[0]==',':\n address_list.append(leader)\n address_list.defects.append(errors.ObsoleteHeaderDefect(\n \"address-list entry with no content\"))\n else :\n token,value=get_invalid_mailbox(value,',')\n if leader is not None :\n token[:0]=[leader]\n address_list.append(Address([token]))\n address_list.defects.append(errors.InvalidHeaderDefect(\n \"invalid address in address-list\"))\n elif value[0]==',':\n address_list.defects.append(errors.ObsoleteHeaderDefect(\n \"empty element in address-list\"))\n else :\n token,value=get_invalid_mailbox(value,',')\n if leader is not None :\n token[:0]=[leader]\n address_list.append(Address([token]))\n address_list.defects.append(errors.InvalidHeaderDefect(\n \"invalid address in address-list\"))\n if value and value[0]!=',':\n \n \n mailbox=address_list[-1][0]\n mailbox.token_type='invalid-mailbox'\n token,value=get_invalid_mailbox(value,',')\n mailbox.extend(token)\n address_list.defects.append(errors.InvalidHeaderDefect(\n \"invalid address in address-list\"))\n if value:\n address_list.append(ValueTerminal(',','list-separator'))\n value=value[1:]\n return address_list,value\n \n \n \n \n \n \n \n \n \ndef parse_mime_version(value):\n ''\n\n \n \n \n mime_version=MIMEVersion()\n if not value:\n mime_version.defects.append(errors.HeaderMissingRequiredValue(\n \"Missing MIME version number (eg: 1.0)\"))\n return mime_version\n if value[0]in CFWS_LEADER:\n token,value=get_cfws(value)\n mime_version.append(token)\n if not value:\n mime_version.defects.append(errors.HeaderMissingRequiredValue(\n \"Expected MIME version number but found only CFWS\"))\n digits=''\n while value and value[0]!='.'and value[0]not in CFWS_LEADER:\n digits +=value[0]\n value=value[1:]\n if not digits.isdigit():\n mime_version.defects.append(errors.InvalidHeaderDefect(\n \"Expected MIME major version number but found {!r}\".format(digits)))\n mime_version.append(ValueTerminal(digits,'xtext'))\n else :\n mime_version.major=int(digits)\n mime_version.append(ValueTerminal(digits,'digits'))\n if value and value[0]in CFWS_LEADER:\n token,value=get_cfws(value)\n mime_version.append(token)\n if not value or value[0]!='.':\n if mime_version.major is not None :\n mime_version.defects.append(errors.InvalidHeaderDefect(\n \"Incomplete MIME version; found only major number\"))\n if value:\n mime_version.append(ValueTerminal(value,'xtext'))\n return mime_version\n mime_version.append(ValueTerminal('.','version-separator'))\n value=value[1:]\n if value and value[0]in CFWS_LEADER:\n token,value=get_cfws(value)\n mime_version.append(token)\n if not value:\n if mime_version.major is not None :\n mime_version.defects.append(errors.InvalidHeaderDefect(\n \"Incomplete MIME version; found only major number\"))\n return mime_version\n digits=''\n while value and value[0]not in CFWS_LEADER:\n digits +=value[0]\n value=value[1:]\n if not digits.isdigit():\n mime_version.defects.append(errors.InvalidHeaderDefect(\n \"Expected MIME minor version number but found {!r}\".format(digits)))\n mime_version.append(ValueTerminal(digits,'xtext'))\n else :\n mime_version.minor=int(digits)\n mime_version.append(ValueTerminal(digits,'digits'))\n if value and value[0]in CFWS_LEADER:\n token,value=get_cfws(value)\n mime_version.append(token)\n if value:\n mime_version.defects.append(errors.InvalidHeaderDefect(\n \"Excess non-CFWS text after MIME version\"))\n mime_version.append(ValueTerminal(value,'xtext'))\n return mime_version\n \ndef get_invalid_parameter(value):\n ''\n\n\n\n\n \n invalid_parameter=InvalidParameter()\n while value and value[0]!=';':\n if value[0]in PHRASE_ENDS:\n invalid_parameter.append(ValueTerminal(value[0],\n 'misplaced-special'))\n value=value[1:]\n else :\n token,value=get_phrase(value)\n invalid_parameter.append(token)\n return invalid_parameter,value\n \ndef get_ttext(value):\n ''\n\n\n\n\n\n\n \n m=_non_token_end_matcher(value)\n if not m:\n raise errors.HeaderParseError(\n \"expected ttext but found '{}'\".format(value))\n ttext=m.group()\n value=value[len(ttext):]\n ttext=ValueTerminal(ttext,'ttext')\n _validate_xtext(ttext)\n return ttext,value\n \ndef get_token(value):\n ''\n\n\n\n\n\n\n \n mtoken=Token()\n if value and value[0]in CFWS_LEADER:\n token,value=get_cfws(value)\n mtoken.append(token)\n if value and value[0]in TOKEN_ENDS:\n raise errors.HeaderParseError(\n \"expected token but found '{}'\".format(value))\n token,value=get_ttext(value)\n mtoken.append(token)\n if value and value[0]in CFWS_LEADER:\n token,value=get_cfws(value)\n mtoken.append(token)\n return mtoken,value\n \ndef get_attrtext(value):\n ''\n\n\n\n\n\n\n \n m=_non_attribute_end_matcher(value)\n if not m:\n raise errors.HeaderParseError(\n \"expected attrtext but found {!r}\".format(value))\n attrtext=m.group()\n value=value[len(attrtext):]\n attrtext=ValueTerminal(attrtext,'attrtext')\n _validate_xtext(attrtext)\n return attrtext,value\n \ndef get_attribute(value):\n ''\n\n\n\n\n\n\n \n attribute=Attribute()\n if value and value[0]in CFWS_LEADER:\n token,value=get_cfws(value)\n attribute.append(token)\n if value and value[0]in ATTRIBUTE_ENDS:\n raise errors.HeaderParseError(\n \"expected token but found '{}'\".format(value))\n token,value=get_attrtext(value)\n attribute.append(token)\n if value and value[0]in CFWS_LEADER:\n token,value=get_cfws(value)\n attribute.append(token)\n return attribute,value\n \ndef get_extended_attrtext(value):\n ''\n\n\n\n\n\n \n m=_non_extended_attribute_end_matcher(value)\n if not m:\n raise errors.HeaderParseError(\n \"expected extended attrtext but found {!r}\".format(value))\n attrtext=m.group()\n value=value[len(attrtext):]\n attrtext=ValueTerminal(attrtext,'extended-attrtext')\n _validate_xtext(attrtext)\n return attrtext,value\n \ndef get_extended_attribute(value):\n ''\n\n\n\n\n \n \n attribute=Attribute()\n if value and value[0]in CFWS_LEADER:\n token,value=get_cfws(value)\n attribute.append(token)\n if value and value[0]in EXTENDED_ATTRIBUTE_ENDS:\n raise errors.HeaderParseError(\n \"expected token but found '{}'\".format(value))\n token,value=get_extended_attrtext(value)\n attribute.append(token)\n if value and value[0]in CFWS_LEADER:\n token,value=get_cfws(value)\n attribute.append(token)\n return attribute,value\n \ndef get_section(value):\n ''\n\n\n\n\n\n\n \n section=Section()\n if not value or value[0]!='*':\n raise errors.HeaderParseError(\"Expected section but found {}\".format(\n value))\n section.append(ValueTerminal('*','section-marker'))\n value=value[1:]\n if not value or not value[0].isdigit():\n raise errors.HeaderParseError(\"Expected section number but \"\n \"found {}\".format(value))\n digits=''\n while value and value[0].isdigit():\n digits +=value[0]\n value=value[1:]\n if digits[0]=='0'and digits !='0':\n section.defects.append(errors.InvalidHeaderError(\"section number\"\n \"has an invalid leading 0\"))\n section.number=int(digits)\n section.append(ValueTerminal(digits,'digits'))\n return section,value\n \n \ndef get_value(value):\n ''\n\n \n v=Value()\n if not value:\n raise errors.HeaderParseError(\"Expected value but found end of string\")\n leader=None\n if value[0]in CFWS_LEADER:\n leader,value=get_cfws(value)\n if not value:\n raise errors.HeaderParseError(\"Expected value but found \"\n \"only {}\".format(leader))\n if value[0]=='\"':\n token,value=get_quoted_string(value)\n else :\n token,value=get_extended_attribute(value)\n if leader is not None :\n token[:0]=[leader]\n v.append(token)\n return v,value\n \ndef get_parameter(value):\n ''\n\n\n\n\n\n \n \n \n \n param=Parameter()\n token,value=get_attribute(value)\n param.append(token)\n if not value or value[0]==';':\n param.defects.append(errors.InvalidHeaderDefect(\"Parameter contains \"\n \"name ({}) but no value\".format(token)))\n return param,value\n if value[0]=='*':\n try :\n token,value=get_section(value)\n param.sectioned=True\n param.append(token)\n except errors.HeaderParseError:\n pass\n if not value:\n raise errors.HeaderParseError(\"Incomplete parameter\")\n if value[0]=='*':\n param.append(ValueTerminal('*','extended-parameter-marker'))\n value=value[1:]\n param.extended=True\n if value[0]!='=':\n raise errors.HeaderParseError(\"Parameter not followed by '='\")\n param.append(ValueTerminal('=','parameter-separator'))\n value=value[1:]\n leader=None\n if value and value[0]in CFWS_LEADER:\n token,value=get_cfws(value)\n param.append(token)\n remainder=None\n appendto=param\n if param.extended and value and value[0]=='\"':\n \n \n \n qstring,remainder=get_quoted_string(value)\n inner_value=qstring.stripped_value\n semi_valid=False\n if param.section_number ==0:\n if inner_value and inner_value[0]==\"'\":\n semi_valid=True\n else :\n token,rest=get_attrtext(inner_value)\n if rest and rest[0]==\"'\":\n semi_valid=True\n else :\n try :\n token,rest=get_extended_attrtext(inner_value)\n except :\n pass\n else :\n if not rest:\n semi_valid=True\n if semi_valid:\n param.defects.append(errors.InvalidHeaderDefect(\n \"Quoted string value for extended parameter is invalid\"))\n param.append(qstring)\n for t in qstring:\n if t.token_type =='bare-quoted-string':\n t[:]=[]\n appendto=t\n break\n value=inner_value\n else :\n remainder=None\n param.defects.append(errors.InvalidHeaderDefect(\n \"Parameter marked as extended but appears to have a \"\n \"quoted string value that is non-encoded\"))\n if value and value[0]==\"'\":\n token=None\n else :\n token,value=get_value(value)\n if not param.extended or param.section_number >0:\n if not value or value[0]!=\"'\":\n appendto.append(token)\n if remainder is not None :\n assert not value,value\n value=remainder\n return param,value\n param.defects.append(errors.InvalidHeaderDefect(\n \"Apparent initial-extended-value but attribute \"\n \"was not marked as extended or was not initial section\"))\n if not value:\n \n param.defects.append(errors.InvalidHeaderDefect(\n \"Missing required charset/lang delimiters\"))\n appendto.append(token)\n if remainder is None :\n return param,value\n else :\n if token is not None :\n for t in token:\n if t.token_type =='extended-attrtext':\n break\n t.token_type =='attrtext'\n appendto.append(t)\n param.charset=t.value\n if value[0]!=\"'\":\n raise errors.HeaderParseError(\"Expected RFC2231 char/lang encoding \"\n \"delimiter, but found {!r}\".format(value))\n appendto.append(ValueTerminal(\"'\",'RFC2231-delimiter'))\n value=value[1:]\n if value and value[0]!=\"'\":\n token,value=get_attrtext(value)\n appendto.append(token)\n param.lang=token.value\n if not value or value[0]!=\"'\":\n raise errors.HeaderParseError(\"Expected RFC2231 char/lang encoding \"\n \"delimiter, but found {}\".format(value))\n appendto.append(ValueTerminal(\"'\",'RFC2231-delimiter'))\n value=value[1:]\n if remainder is not None :\n \n v=Value()\n while value:\n if value[0]in WSP:\n token,value=get_fws(value)\n else :\n token,value=get_qcontent(value)\n v.append(token)\n token=v\n else :\n token,value=get_value(value)\n appendto.append(token)\n if remainder is not None :\n assert not value,value\n value=remainder\n return param,value\n \ndef parse_mime_parameters(value):\n ''\n\n\n\n\n\n\n\n\n\n\n \n mime_parameters=MimeParameters()\n while value:\n try :\n token,value=get_parameter(value)\n mime_parameters.append(token)\n except errors.HeaderParseError as err:\n leader=None\n if value[0]in CFWS_LEADER:\n leader,value=get_cfws(value)\n if not value:\n mime_parameters.append(leader)\n return mime_parameters\n if value[0]==';':\n if leader is not None :\n mime_parameters.append(leader)\n mime_parameters.defects.append(errors.InvalidHeaderDefect(\n \"parameter entry with no content\"))\n else :\n token,value=get_invalid_parameter(value)\n if leader:\n token[:0]=[leader]\n mime_parameters.append(token)\n mime_parameters.defects.append(errors.InvalidHeaderDefect(\n \"invalid parameter {!r}\".format(token)))\n if value and value[0]!=';':\n \n \n param=mime_parameters[-1]\n param.token_type='invalid-parameter'\n token,value=get_invalid_parameter(value)\n param.extend(token)\n mime_parameters.defects.append(errors.InvalidHeaderDefect(\n \"parameter with invalid trailing text {!r}\".format(token)))\n if value:\n \n mime_parameters.append(ValueTerminal(';','parameter-separator'))\n value=value[1:]\n return mime_parameters\n \ndef _find_mime_parameters(tokenlist,value):\n ''\n\n \n while value and value[0]!=';':\n if value[0]in PHRASE_ENDS:\n tokenlist.append(ValueTerminal(value[0],'misplaced-special'))\n value=value[1:]\n else :\n token,value=get_phrase(value)\n tokenlist.append(token)\n if not value:\n return\n tokenlist.append(ValueTerminal(';','parameter-separator'))\n tokenlist.append(parse_mime_parameters(value[1:]))\n \ndef parse_content_type_header(value):\n ''\n\n\n\n\n \n ctype=ContentType()\n recover=False\n if not value:\n ctype.defects.append(errors.HeaderMissingRequiredValue(\n \"Missing content type specification\"))\n return ctype\n try :\n token,value=get_token(value)\n except errors.HeaderParseError:\n ctype.defects.append(errors.InvalidHeaderDefect(\n \"Expected content maintype but found {!r}\".format(value)))\n _find_mime_parameters(ctype,value)\n return ctype\n ctype.append(token)\n \n \n if not value or value[0]!='/':\n ctype.defects.append(errors.InvalidHeaderDefect(\n \"Invalid content type\"))\n if value:\n _find_mime_parameters(ctype,value)\n return ctype\n ctype.maintype=token.value.strip().lower()\n ctype.append(ValueTerminal('/','content-type-separator'))\n value=value[1:]\n try :\n token,value=get_token(value)\n except errors.HeaderParseError:\n ctype.defects.append(errors.InvalidHeaderDefect(\n \"Expected content subtype but found {!r}\".format(value)))\n _find_mime_parameters(ctype,value)\n return ctype\n ctype.append(token)\n ctype.subtype=token.value.strip().lower()\n if not value:\n return ctype\n if value[0]!=';':\n ctype.defects.append(errors.InvalidHeaderDefect(\n \"Only parameters are valid after content type, but \"\n \"found {!r}\".format(value)))\n \n \n \n del ctype.maintype,ctype.subtype\n _find_mime_parameters(ctype,value)\n return ctype\n ctype.append(ValueTerminal(';','parameter-separator'))\n ctype.append(parse_mime_parameters(value[1:]))\n return ctype\n \ndef parse_content_disposition_header(value):\n ''\n\n \n disp_header=ContentDisposition()\n if not value:\n disp_header.defects.append(errors.HeaderMissingRequiredValue(\n \"Missing content disposition\"))\n return disp_header\n try :\n token,value=get_token(value)\n except errors.HeaderParseError:\n disp_header.defects.append(errors.InvalidHeaderDefect(\n \"Expected content disposition but found {!r}\".format(value)))\n _find_mime_parameters(disp_header,value)\n return disp_header\n disp_header.append(token)\n disp_header.content_disposition=token.value.strip().lower()\n if not value:\n return disp_header\n if value[0]!=';':\n disp_header.defects.append(errors.InvalidHeaderDefect(\n \"Only parameters are valid after content disposition, but \"\n \"found {!r}\".format(value)))\n _find_mime_parameters(disp_header,value)\n return disp_header\n disp_header.append(ValueTerminal(';','parameter-separator'))\n disp_header.append(parse_mime_parameters(value[1:]))\n return disp_header\n \ndef parse_content_transfer_encoding_header(value):\n ''\n\n \n \n cte_header=ContentTransferEncoding()\n if not value:\n cte_header.defects.append(errors.HeaderMissingRequiredValue(\n \"Missing content transfer encoding\"))\n return cte_header\n try :\n token,value=get_token(value)\n except errors.HeaderParseError:\n cte_header.defects.append(errors.InvalidHeaderDefect(\n \"Expected content transfer encoding but found {!r}\".format(value)))\n else :\n cte_header.append(token)\n cte_header.cte=token.value.strip().lower()\n if not value:\n return cte_header\n while value:\n cte_header.defects.append(errors.InvalidHeaderDefect(\n \"Extra text after content transfer encoding\"))\n if value[0]in PHRASE_ENDS:\n cte_header.append(ValueTerminal(value[0],'misplaced-special'))\n value=value[1:]\n else :\n token,value=get_phrase(value)\n cte_header.append(token)\n return cte_header\n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \ndef _steal_trailing_WSP_if_exists(lines):\n wsp=''\n if lines and lines[-1]and lines[-1][-1]in WSP:\n wsp=lines[-1][-1]\n lines[-1]=lines[-1][:-1]\n return wsp\n \ndef _refold_parse_tree(parse_tree,*,policy):\n ''\n\n \n \n maxlen=policy.max_line_length or float(\"+inf\")\n encoding='utf-8'if policy.utf8 else 'us-ascii'\n lines=['']\n last_ew=None\n wrap_as_ew_blocked=0\n want_encoding=False\n end_ew_not_allowed=Terminal('','wrap_as_ew_blocked')\n parts=list(parse_tree)\n while parts:\n part=parts.pop(0)\n if part is end_ew_not_allowed:\n wrap_as_ew_blocked -=1\n continue\n tstr=str(part)\n try :\n tstr.encode(encoding)\n charset=encoding\n except UnicodeEncodeError:\n if any(isinstance(x,errors.UndecodableBytesDefect)\n for x in part.all_defects):\n charset='unknown-8bit'\n else :\n \n \n charset='utf-8'\n want_encoding=True\n if part.token_type =='mime-parameters':\n \n _fold_mime_parameters(part,lines,maxlen,encoding)\n continue\n if want_encoding and not wrap_as_ew_blocked:\n if not part.as_ew_allowed:\n want_encoding=False\n last_ew=None\n if part.syntactic_break:\n encoded_part=part.fold(policy=policy)[:-1]\n if policy.linesep not in encoded_part:\n \n if len(encoded_part)>maxlen -len(lines[-1]):\n \n newline=_steal_trailing_WSP_if_exists(lines)\n \n lines.append(newline)\n lines[-1]+=encoded_part\n continue\n \n \n \n \n if not hasattr(part,'encode'):\n \n parts=list(part)+parts\n else :\n \n \n last_ew=_fold_as_ew(tstr,lines,maxlen,last_ew,\n part.ew_combine_allowed,charset)\n want_encoding=False\n continue\n if len(tstr)<=maxlen -len(lines[-1]):\n lines[-1]+=tstr\n continue\n \n \n \n if (part.syntactic_break and\n len(tstr)+1 <=maxlen):\n newline=_steal_trailing_WSP_if_exists(lines)\n if newline or part.startswith_fws():\n lines.append(newline+tstr)\n continue\n if not hasattr(part,'encode'):\n \n newparts=list(part)\n if not part.as_ew_allowed:\n wrap_as_ew_blocked +=1\n newparts.append(end_ew_not_allowed)\n parts=newparts+parts\n continue\n if part.as_ew_allowed and not wrap_as_ew_blocked:\n \n \n parts.insert(0,part)\n want_encoding=True\n continue\n \n newline=_steal_trailing_WSP_if_exists(lines)\n if newline or part.startswith_fws():\n lines.append(newline+tstr)\n else :\n \n lines[-1]+=tstr\n return policy.linesep.join(lines)+policy.linesep\n \ndef _fold_as_ew(to_encode,lines,maxlen,last_ew,ew_combine_allowed,charset):\n ''\n\n\n\n\n\n\n\n\n \n if last_ew is not None and ew_combine_allowed:\n to_encode=str(\n get_unstructured(lines[-1][last_ew:]+to_encode))\n lines[-1]=lines[-1][:last_ew]\n if to_encode[0]in WSP:\n \n \n leading_wsp=to_encode[0]\n to_encode=to_encode[1:]\n if (len(lines[-1])==maxlen):\n lines.append(_steal_trailing_WSP_if_exists(lines))\n lines[-1]+=leading_wsp\n trailing_wsp=''\n if to_encode[-1]in WSP:\n \n trailing_wsp=to_encode[-1]\n to_encode=to_encode[:-1]\n new_last_ew=len(lines[-1])if last_ew is None else last_ew\n while to_encode:\n remaining_space=maxlen -len(lines[-1])\n \n \n encode_as='utf-8'if charset =='us-ascii'else charset\n text_space=remaining_space -len(encode_as)-7\n if text_space <=0:\n lines.append(' ')\n \n continue\n first_part=to_encode[:text_space]\n ew=_ew.encode(first_part,charset=encode_as)\n excess=len(ew)-remaining_space\n if excess >0:\n \n \n first_part=first_part[:-excess]\n ew=_ew.encode(first_part)\n lines[-1]+=ew\n to_encode=to_encode[len(first_part):]\n if to_encode:\n lines.append(' ')\n new_last_ew=len(lines[-1])\n lines[-1]+=trailing_wsp\n return new_last_ew if ew_combine_allowed else None\n \ndef _fold_mime_parameters(part,lines,maxlen,encoding):\n ''\n\n\n\n\n\n\n \n \n \n \n \n \n \n for name,value in part.params:\n \n \n \n \n \n if not lines[-1].rstrip().endswith(';'):\n lines[-1]+=';'\n charset=encoding\n error_handler='strict'\n try :\n value.encode(encoding)\n encoding_required=False\n except UnicodeEncodeError:\n encoding_required=True\n if utils._has_surrogates(value):\n charset='unknown-8bit'\n error_handler='surrogateescape'\n else :\n charset='utf-8'\n if encoding_required:\n encoded_value=urllib.parse.quote(\n value,safe='',errors=error_handler)\n tstr=\"{}*={}''{}\".format(name,charset,encoded_value)\n else :\n tstr='{}={}'.format(name,quote_string(value))\n if len(lines[-1])+len(tstr)+1 <maxlen:\n lines[-1]=lines[-1]+' '+tstr\n continue\n elif len(tstr)+2 <=maxlen:\n lines.append(' '+tstr)\n continue\n \n \n section=0\n extra_chrome=charset+\"''\"\n while value:\n chrome_len=len(name)+len(str(section))+3+len(extra_chrome)\n if maxlen <=chrome_len+3:\n \n \n \n \n maxlen=78\n splitpoint=maxchars=maxlen -chrome_len -2\n while True :\n partial=value[:splitpoint]\n encoded_value=urllib.parse.quote(\n partial,safe='',errors=error_handler)\n if len(encoded_value)<=maxchars:\n break\n splitpoint -=1\n lines.append(\" {}*{}*={}{}\".format(\n name,section,extra_chrome,encoded_value))\n extra_chrome=''\n section +=1\n value=value[splitpoint:]\n if value:\n lines[-1]+=';'\n", ["collections", "email", "email._encoded_words", "email.errors", "email.utils", "operator", "re", "string", "urllib"]], "copyreg": [".py", "''\n\n\n\n\n\n__all__=[\"pickle\",\"constructor\",\n\"add_extension\",\"remove_extension\",\"clear_extension_cache\"]\n\ndispatch_table={}\n\ndef pickle(ob_type,pickle_function,constructor_ob=None ):\n if not callable(pickle_function):\n raise TypeError(\"reduction functions must be callable\")\n dispatch_table[ob_type]=pickle_function\n \n \n \n if constructor_ob is not None :\n constructor(constructor_ob)\n \ndef constructor(object):\n if not callable(object):\n raise TypeError(\"constructors must be callable\")\n \n \n \ntry :\n complex\nexcept NameError:\n pass\nelse :\n\n def pickle_complex(c):\n return complex,(c.real,c.imag)\n \n pickle(complex,pickle_complex,complex)\n \n \n \ndef _reconstructor(cls,base,state):\n if base is object:\n obj=object.__new__(cls)\n else :\n obj=base.__new__(cls,state)\n if base.__init__ !=object.__init__:\n base.__init__(obj,state)\n return obj\n \n_HEAPTYPE=1 <<9\n\n\n\ndef _reduce_ex(self,proto):\n assert proto <2\n for base in self.__class__.__mro__:\n if hasattr(base,'__flags__')and not base.__flags__&_HEAPTYPE:\n break\n else :\n base=object\n if base is object:\n state=None\n else :\n if base is self.__class__:\n raise TypeError(\"can't pickle %s objects\"%base.__name__)\n state=base(self)\n args=(self.__class__,base,state)\n try :\n getstate=self.__getstate__\n except AttributeError:\n if getattr(self,\"__slots__\",None ):\n raise TypeError(\"a class that defines __slots__ without \"\n \"defining __getstate__ cannot be pickled\")from None\n try :\n dict=self.__dict__\n except AttributeError:\n dict=None\n else :\n dict=getstate()\n if dict:\n return _reconstructor,args,dict\n else :\n return _reconstructor,args\n \n \n \ndef __newobj__(cls,*args):\n return cls.__new__(cls,*args)\n \ndef __newobj_ex__(cls,args,kwargs):\n ''\n\n \n return cls.__new__(cls,*args,**kwargs)\n \ndef _slotnames(cls):\n ''\n\n\n\n\n\n\n\n \n \n \n names=cls.__dict__.get(\"__slotnames__\")\n if names is not None :\n return names\n \n \n names=[]\n if not hasattr(cls,\"__slots__\"):\n \n pass\n else :\n \n for c in cls.__mro__:\n if \"__slots__\"in c.__dict__:\n slots=c.__dict__['__slots__']\n \n if isinstance(slots,str):\n slots=(slots,)\n for name in slots:\n \n if name in (\"__dict__\",\"__weakref__\"):\n continue\n \n elif name.startswith('__')and not name.endswith('__'):\n stripped=c.__name__.lstrip('_')\n if stripped:\n names.append('_%s%s'%(stripped,name))\n else :\n names.append(name)\n else :\n names.append(name)\n \n \n try :\n cls.__slotnames__=names\n except :\n pass\n \n return names\n \n \n \n \n \n \n \n \n \n \n_extension_registry={}\n_inverted_registry={}\n_extension_cache={}\n\n\n\ndef add_extension(module,name,code):\n ''\n code=int(code)\n if not 1 <=code <=0x7fffffff:\n raise ValueError(\"code out of range\")\n key=(module,name)\n if (_extension_registry.get(key)==code and\n _inverted_registry.get(code)==key):\n return\n if key in _extension_registry:\n raise ValueError(\"key %s is already registered with code %s\"%\n (key,_extension_registry[key]))\n if code in _inverted_registry:\n raise ValueError(\"code %s is already in use for key %s\"%\n (code,_inverted_registry[code]))\n _extension_registry[key]=code\n _inverted_registry[code]=key\n \ndef remove_extension(module,name,code):\n ''\n key=(module,name)\n if (_extension_registry.get(key)!=code or\n _inverted_registry.get(code)!=key):\n raise ValueError(\"key %s is not registered with code %s\"%\n (key,code))\n del _extension_registry[key]\n del _inverted_registry[code]\n if code in _extension_cache:\n del _extension_cache[code]\n \ndef clear_extension_cache():\n _extension_cache.clear()\n \n \n \n \n \n \n \n \n \n \n \n \n \n", []], "itertools": [".py", "import operator\n\nclass accumulate:\n def __init__(self,iterable,func=operator.add):\n self.it=iter(iterable)\n self._total=None\n self.func=func\n \n def __iter__(self):\n return self\n \n def __next__(self):\n if not self._total:\n self._total=next(self.it)\n return self._total\n else :\n element=next(self.it)\n try :\n self._total=self.func(self._total,element)\n except :\n raise TypeError(\"unsupported operand type\")\n return self._total\n \n \n \nclass chain:\n def __init__(self,*iterables):\n self._iterables_iter=iter(map(iter,iterables))\n \n self._cur_iterable_iter=iter([])\n \n def __iter__(self):\n return self\n \n def __next__(self):\n while True :\n try :\n return next(self._cur_iterable_iter)\n except StopIteration:\n self._cur_iterable_iter=next(self._iterables_iter)\n \n @classmethod\n def from_iterable(cls,iterable):\n for it in iterable:\n for element in it:\n yield element\n \nclass combinations:\n def __init__(self,iterable,r):\n self.pool=tuple(iterable)\n self.n=len(self.pool)\n self.r=r\n self.indices=list(range(self.r))\n self.zero=False\n \n def __iter__(self):\n return self\n \n def __next__(self):\n if self.r >self.n:\n raise StopIteration\n if not self.zero:\n self.zero=True\n return tuple(self.pool[i]for i in self.indices)\n else :\n try :\n for i in reversed(range(self.r)):\n if self.indices[i]!=i+self.n -self.r:\n break\n self.indices[i]+=1\n for j in range(i+1,self.r):\n self.indices[j]=self.indices[j -1]+1\n return tuple(self.pool[i]for i in self.indices)\n except :\n raise StopIteration\n \nclass combinations_with_replacement:\n def __init__(self,iterable,r):\n self.pool=tuple(iterable)\n self.n=len(self.pool)\n self.r=r\n self.indices=[0]*self.r\n self.zero=False\n \n def __iter__(self):\n return self\n \n def __next__(self):\n if not self.n and self.r:\n raise StopIteration\n if not self.zero:\n self.zero=True\n return tuple(self.pool[i]for i in self.indices)\n else :\n try :\n for i in reversed(range(self.r)):\n if self.indices[i]!=self.n -1:\n break\n self.indices[i:]=[self.indices[i]+1]*(self.r -i)\n return tuple(self.pool[i]for i in self.indices)\n except :\n raise StopIteration\n \n \n \nclass compress:\n def __init__(self,data,selectors):\n self.data=iter(data)\n self.selectors=iter(selectors)\n \n def __iter__(self):\n return self\n \n def __next__(self):\n while True :\n next_item=next(self.data)\n next_selector=next(self.selectors)\n if bool(next_selector):\n return next_item\n \n \n \n \nclass count:\n ''\n\n\n\n \n def __init__(self,start=0,step=1):\n if not isinstance(start,(int,float)):\n raise TypeError('a number is required')\n self.times=start -step\n self.step=step\n \n def __iter__(self):\n return self\n \n def __next__(self):\n self.times +=self.step\n return self.times\n \n def __repr__(self):\n return 'count(%d)'%(self.times+self.step)\n \n \n \nclass cycle:\n def __init__(self,iterable):\n self._cur_iter=iter(iterable)\n self._saved=[]\n self._must_save=True\n \n def __iter__(self):\n return self\n \n def __next__(self):\n try :\n next_elt=next(self._cur_iter)\n if self._must_save:\n self._saved.append(next_elt)\n except StopIteration:\n self._cur_iter=iter(self._saved)\n next_elt=next(self._cur_iter)\n self._must_save=False\n return next_elt\n \n \n \nclass dropwhile:\n def __init__(self,predicate,iterable):\n self._predicate=predicate\n self._iter=iter(iterable)\n self._dropped=False\n \n def __iter__(self):\n return self\n \n def __next__(self):\n value=next(self._iter)\n if self._dropped:\n return value\n while self._predicate(value):\n value=next(self._iter)\n self._dropped=True\n return value\n \n \n \nclass filterfalse:\n def __init__(self,predicate,iterable):\n \n self._iter=iter(iterable)\n if predicate is None :\n self._predicate=bool\n else :\n self._predicate=predicate\n \n def __iter__(self):\n return self\n def __next__(self):\n next_elt=next(self._iter)\n while True :\n if not self._predicate(next_elt):\n return next_elt\n next_elt=next(self._iter)\n \nclass groupby:\n\n\n def __init__(self,iterable,key=None ):\n if key is None :\n key=lambda x:x\n self.keyfunc=key\n self.it=iter(iterable)\n self.tgtkey=self.currkey=self.currvalue=object()\n def __iter__(self):\n return self\n def __next__(self):\n while self.currkey ==self.tgtkey:\n self.currvalue=next(self.it)\n self.currkey=self.keyfunc(self.currvalue)\n self.tgtkey=self.currkey\n return (self.currkey,self._grouper(self.tgtkey))\n def _grouper(self,tgtkey):\n while self.currkey ==tgtkey:\n yield self.currvalue\n self.currvalue=next(self.it)\n self.currkey=self.keyfunc(self.currvalue)\n \n \n \nclass islice:\n def __init__(self,iterable,*args):\n s=slice(*args)\n self.start,self.stop,self.step=s.start or 0,s.stop,s.step\n if not isinstance(self.start,int):\n raise ValueError(\"Start argument must be an integer\")\n if self.stop !=None and not isinstance(self.stop,int):\n raise ValueError(\"Stop argument must be an integer or None\")\n if self.step is None :\n self.step=1\n if self.start <0 or (self.stop !=None and self.stop <0\n )or self.step <=0:\n raise ValueError(\"indices for islice() must be positive\")\n self.it=iter(iterable)\n self.donext=None\n self.cnt=0\n \n def __iter__(self):\n return self\n \n def __next__(self):\n nextindex=self.start\n if self.stop !=None and nextindex >=self.stop:\n raise StopIteration\n while self.cnt <=nextindex:\n nextitem=next(self.it)\n self.cnt +=1\n self.start +=self.step\n return nextitem\n \nclass permutations:\n def __init__(self,iterable,r=None ):\n self.pool=tuple(iterable)\n self.n=len(self.pool)\n self.r=self.n if r is None else r\n self.indices=list(range(self.n))\n self.cycles=list(range(self.n,self.n -self.r,-1))\n self.zero=False\n self.stop=False\n \n def __iter__(self):\n return self\n \n def __next__(self):\n indices=self.indices\n if self.r >self.n:\n raise StopIteration\n if not self.zero:\n self.zero=True\n return tuple(self.pool[i]for i in indices[:self.r])\n \n i=self.r -1\n while i >=0:\n j=self.cycles[i]-1\n if j >0:\n self.cycles[i]=j\n indices[i],indices[-j]=indices[-j],indices[i]\n return tuple(self.pool[i]for i in indices[:self.r])\n self.cycles[i]=len(indices)-i\n n1=len(indices)-1\n assert n1 >=0\n num=indices[i]\n for k in range(i,n1):\n indices[k]=indices[k+1]\n indices[n1]=num\n i -=1\n raise StopIteration\n \n \ndef product(*args,repeat=1):\n\n\n pools=[tuple(pool)for pool in args]*repeat\n result=[[]]\n for pool in pools:\n result=[x+[y]for x in result for y in pool]\n for prod in result:\n yield tuple(prod)\n \n \n \n \n \n \n \n \nclass _product:\n def __init__(self,*args,**kw):\n if len(kw)>1:\n raise TypeError(\"product() takes at most 1 argument (%d given)\"%\n len(kw))\n self.repeat=kw.get('repeat',1)\n if not isinstance(self.repeat,int):\n raise TypeError(\"integer argument expected, got %s\"%\n type(self.repeat))\n self.gears=[x for x in args]*self.repeat\n self.num_gears=len(self.gears)\n \n self.indicies=[(0,len(self.gears[x]))\n for x in range(0,self.num_gears)]\n self.cont=True\n self.zero=False\n \n def roll_gears(self):\n \n \n \n should_carry=True\n for n in range(0,self.num_gears):\n nth_gear=self.num_gears -n -1\n if should_carry:\n count,lim=self.indicies[nth_gear]\n count +=1\n if count ==lim and nth_gear ==0:\n self.cont=False\n if count ==lim:\n should_carry=True\n count=0\n else :\n should_carry=False\n self.indicies[nth_gear]=(count,lim)\n else :\n break\n \n def __iter__(self):\n return self\n \n def __next__(self):\n if self.zero:\n raise StopIteration\n if self.repeat >0:\n if not self.cont:\n raise StopIteration\n l=[]\n for x in range(0,self.num_gears):\n index,limit=self.indicies[x]\n print('itertools 353',self.gears,x,index)\n l.append(self.gears[x][index])\n self.roll_gears()\n return tuple(l)\n elif self.repeat ==0:\n self.zero=True\n return ()\n else :\n raise ValueError(\"repeat argument cannot be negative\")\n \n \n \nclass repeat:\n def __init__(self,obj,times=None ):\n self._obj=obj\n if times is not None :\n range(times)\n if times <0:\n times=0\n self._times=times\n \n def __iter__(self):\n return self\n \n def __next__(self):\n \n if self._times is not None :\n if self._times <=0:\n raise StopIteration()\n self._times -=1\n return self._obj\n \n def __repr__(self):\n if self._times is not None :\n return 'repeat(%r, %r)'%(self._obj,self._times)\n else :\n return 'repeat(%r)'%(self._obj,)\n \n def __len__(self):\n if self._times ==-1 or self._times is None :\n raise TypeError(\"len() of uniszed object\")\n return self._times\n \n \n \nclass starmap(object):\n def __init__(self,function,iterable):\n self._func=function\n self._iter=iter(iterable)\n \n def __iter__(self):\n return self\n \n def __next__(self):\n t=next(self._iter)\n return self._func(*t)\n \n \n \nclass takewhile(object):\n def __init__(self,predicate,iterable):\n self._predicate=predicate\n self._iter=iter(iterable)\n \n def __iter__(self):\n return self\n \n def __next__(self):\n value=next(self._iter)\n if not self._predicate(value):\n raise StopIteration()\n return value\n \n \n \nclass TeeData(object):\n def __init__(self,iterator):\n self.data=[]\n self._iter=iterator\n \n def __getitem__(self,i):\n \n while i >=len(self.data):\n self.data.append(next(self._iter))\n return self.data[i]\n \n \nclass TeeObject(object):\n def __init__(self,iterable=None ,tee_data=None ):\n if tee_data:\n self.tee_data=tee_data\n self.pos=0\n \n elif isinstance(iterable,TeeObject):\n self.tee_data=iterable.tee_data\n self.pos=iterable.pos\n else :\n self.tee_data=TeeData(iter(iterable))\n self.pos=0\n \n def __next__(self):\n data=self.tee_data[self.pos]\n self.pos +=1\n return data\n \n def __iter__(self):\n return self\n \n \ndef tee(iterable,n=2):\n if isinstance(iterable,TeeObject):\n return tuple([iterable]+\n [TeeObject(tee_data=iterable.tee_data)for i in range(n -1)])\n tee_data=TeeData(iter(iterable))\n return tuple([TeeObject(tee_data=tee_data)for i in range(n)])\n \nclass zip_longest:\n def __init__(self,*args,fillvalue=None ):\n self.args=[iter(arg)for arg in args]\n self.fillvalue=fillvalue\n self.units=len(args)\n \n def __iter__(self):\n return self\n \n def __next__(self):\n temp=[]\n nb=0\n for i in range(self.units):\n try :\n temp.append(next(self.args[i]))\n nb +=1\n except StopIteration:\n temp.append(self.fillvalue)\n if nb ==0:\n raise StopIteration\n return tuple(temp)\n", ["operator"]], "builtins": [".js", "var $module = (function(){\n var obj = {\n __class__: __BRYTHON__.module,\n __name__: 'builtins'\n },\n builtin_names = ['ArithmeticError', 'AssertionError', 'AttributeError',\n 'BaseException', 'BlockingIOError', 'BrokenPipeError', 'BufferError',\n 'BytesWarning', 'ChildProcessError', 'ConnectionAbortedError',\n 'ConnectionError', 'ConnectionRefusedError', 'ConnectionResetError',\n 'DeprecationWarning', 'EOFError', 'Ellipsis', 'EnvironmentError', 'Exception',\n 'False', 'FileExistsError', 'FileNotFoundError', 'FloatingPointError',\n 'FutureWarning', 'GeneratorExit', 'IOError', 'ImportError', 'ImportWarning',\n 'IndentationError', 'IndexError', 'InterruptedError', 'IsADirectoryError',\n 'KeyError', 'KeyboardInterrupt', 'LookupError', 'MemoryError', 'NameError',\n 'None', 'NotADirectoryError', 'NotImplemented', 'NotImplementedError',\n 'OSError', 'OverflowError', 'PendingDeprecationWarning', 'PermissionError',\n 'ProcessLookupError', 'ReferenceError', 'ResourceWarning', 'RuntimeError',\n 'RuntimeWarning', 'StopIteration', 'SyntaxError', 'SyntaxWarning',\n 'SystemError', 'SystemExit', 'TabError', 'TimeoutError', 'True', 'TypeError',\n 'UnboundLocalError', 'UnicodeDecodeError', 'UnicodeEncodeError',\n 'UnicodeError', 'UnicodeTranslateError', 'UnicodeWarning', 'UserWarning',\n 'ValueError', 'Warning', 'WindowsError', 'ZeroDivisionError', '_',\n '__build_class__', '__debug__', '__doc__', '__import__', '__name__',\n '__package__', 'abs', 'all', 'any', 'ascii', 'bin', 'bool', 'bytearray',\n 'bytes','callable', 'chr', 'classmethod', 'compile', 'complex', 'copyright',\n 'credits','delattr', 'dict', 'dir', 'divmod', 'enumerate', 'eval', 'exec',\n 'exit', 'filter', 'float', 'format', 'frozenset', 'getattr', 'globals',\n 'hasattr', 'hash', 'help', 'hex', 'id', 'input', 'int', 'isinstance',\n 'issubclass', 'iter', 'len', 'license', 'list', 'locals', 'map', 'max',\n 'memoryview', 'min', 'next', 'object', 'oct', 'open', 'ord', 'pow', 'print',\n 'property', 'quit', 'range', 'repr', 'reversed', 'round', 'set', 'setattr',\n 'slice', 'sorted', 'staticmethod', 'str', 'sum', 'super', 'tuple', 'type',\n 'vars', 'zip',\n '__newobj__' // defined in py_objects.js ; required for pickle\n ]\n for(var i = 0, len = builtin_names.length; i < len; i++){\n try{eval(\"obj['\" + builtin_names[i] + \"'] = __BRYTHON__.builtins.\" +\n builtin_names[i])}\n catch(err){if (__BRYTHON__.$debug) {console.log(err)}}\n }\n return obj\n})()\n"], "keyword": [".py", "#! /usr/bin/env python3\n\n\"\"\"Keywords (from \"graminit.c\")\n\nThis file is automatically generated; please don't muck it up!\n\nTo update the symbols in this file, 'cd' to the top directory of\nthe python source tree after building the interpreter and run:\n\n ./python Lib/keyword.py\n\"\"\"\n\n__all__=[\"iskeyword\",\"kwlist\"]\n\nkwlist=[\n\n'False',\n'None',\n'True',\n'and',\n'as',\n'assert',\n'async',\n'await',\n'break',\n'class',\n'continue',\n'def',\n'del',\n'elif',\n'else',\n'except',\n'finally',\n'for',\n'from',\n'global',\n'if',\n'import',\n'in',\n'is',\n'lambda',\n'nonlocal',\n'not',\n'or',\n'pass',\n'raise',\n'return',\n'try',\n'while',\n'with',\n'yield',\n\n]\n\niskeyword=frozenset(kwlist).__contains__\n\ndef main():\n import sys,re\n \n args=sys.argv[1:]\n iptfile=args and args[0]or \"Python/graminit.c\"\n if len(args)>1:optfile=args[1]\n else :optfile=\"Lib/keyword.py\"\n \n \n \n with open(optfile,newline='')as fp:\n format=fp.readlines()\n nl=format[0][len(format[0].strip()):]if format else '\\n'\n \n \n with open(iptfile)as fp:\n strprog=re.compile('\"([^\"]+)\"')\n lines=[]\n for line in fp:\n if '{1, \"'in line:\n match=strprog.search(line)\n if match:\n lines.append(\" '\"+match.group(1)+\"',\"+nl)\n lines.sort()\n \n \n try :\n start=format.index(\"#--start keywords--\"+nl)+1\n end=format.index(\"#--end keywords--\"+nl)\n format[start:end]=lines\n except ValueError:\n sys.stderr.write(\"target does not contain format markers\\n\")\n sys.exit(1)\n \n \n with open(optfile,'w',newline='')as fp:\n fp.writelines(format)\n \nif __name__ ==\"__main__\":\n main()\n", ["re", "sys"]], "_dummy_thread": [".py", "''\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n__all__=['error','start_new_thread','exit','get_ident','allocate_lock',\n'interrupt_main','LockType']\n\n\nTIMEOUT_MAX=2 **31\n\n\n\n\n\n\nerror=RuntimeError\n\ndef start_new_thread(function,args,kwargs={}):\n ''\n\n\n\n\n\n\n\n\n\n\n \n if type(args)!=type(tuple()):\n raise TypeError(\"2nd arg must be a tuple\")\n if type(kwargs)!=type(dict()):\n raise TypeError(\"3rd arg must be a dict\")\n global _main\n _main=False\n try :\n function(*args,**kwargs)\n except SystemExit:\n pass\n except :\n import traceback\n traceback.print_exc()\n _main=True\n global _interrupt\n if _interrupt:\n _interrupt=False\n raise KeyboardInterrupt\n \ndef exit():\n ''\n raise SystemExit\n \ndef get_ident():\n ''\n\n\n\n\n \n return 1\n \ndef allocate_lock():\n ''\n return LockType()\n \ndef stack_size(size=None ):\n ''\n if size is not None :\n raise error(\"setting thread stack size not supported\")\n return 0\n \ndef _set_sentinel():\n ''\n return LockType()\n \nclass LockType(object):\n ''\n\n\n\n\n\n\n\n \n \n def __init__(self):\n self.locked_status=False\n \n def acquire(self,waitflag=None ,timeout=-1):\n ''\n\n\n\n\n\n\n\n\n \n if waitflag is None or waitflag:\n self.locked_status=True\n return True\n else :\n if not self.locked_status:\n self.locked_status=True\n return True\n else :\n if timeout >0:\n import time\n time.sleep(timeout)\n return False\n \n __enter__=acquire\n \n def __exit__(self,typ,val,tb):\n self.release()\n \n def release(self):\n ''\n \n \n if not self.locked_status:\n raise error\n self.locked_status=False\n return True\n \n def locked(self):\n return self.locked_status\n \n def __repr__(self):\n return \"<%s %s.%s object at %s>\"%(\n \"locked\"if self.locked_status else \"unlocked\",\n self.__class__.__module__,\n self.__class__.__qualname__,\n hex(id(self))\n )\n \n \n_interrupt=False\n\n_main=True\n\ndef interrupt_main():\n ''\n \n if _main:\n raise KeyboardInterrupt\n else :\n global _interrupt\n _interrupt=True\n", ["time", "traceback"]], "shlex": [".py", "''\n\n\n\n\n\n\n\n\nimport os\nimport re\nimport sys\nfrom collections import deque\n\nfrom io import StringIO\n\n__all__=[\"shlex\",\"split\",\"quote\"]\n\nclass shlex:\n ''\n def __init__(self,instream=None ,infile=None ,posix=False ,\n punctuation_chars=False ):\n if isinstance(instream,str):\n instream=StringIO(instream)\n if instream is not None :\n self.instream=instream\n self.infile=infile\n else :\n self.instream=sys.stdin\n self.infile=None\n self.posix=posix\n if posix:\n self.eof=None\n else :\n self.eof=''\n self.commenters='#'\n self.wordchars=('abcdfeghijklmnopqrstuvwxyz'\n 'ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789_')\n if self.posix:\n self.wordchars +=('\u00df\u00e0\u00e1\u00e2\u00e3\u00e4\u00e5\u00e6\u00e7\u00e8\u00e9\u00ea\u00eb\u00ec\u00ed\u00ee\u00ef\u00f0\u00f1\u00f2\u00f3\u00f4\u00f5\u00f6\u00f8\u00f9\u00fa\u00fb\u00fc\u00fd\u00fe\u00ff'\n '\u00c0\u00c1\u00c2\u00c3\u00c4\u00c5\u00c6\u00c7\u00c8\u00c9\u00ca\u00cb\u00cc\u00cd\u00ce\u00cf\u00d0\u00d1\u00d2\u00d3\u00d4\u00d5\u00d6\u00d8\u00d9\u00da\u00db\u00dc\u00dd\u00de')\n self.whitespace=' \\t\\r\\n'\n self.whitespace_split=False\n self.quotes='\\'\"'\n self.escape='\\\\'\n self.escapedquotes='\"'\n self.state=' '\n self.pushback=deque()\n self.lineno=1\n self.debug=0\n self.token=''\n self.filestack=deque()\n self.source=None\n if not punctuation_chars:\n punctuation_chars=''\n elif punctuation_chars is True :\n punctuation_chars='();<>|&'\n self.punctuation_chars=punctuation_chars\n if punctuation_chars:\n \n self._pushback_chars=deque()\n \n self.wordchars +='~-./*?='\n \n t=self.wordchars.maketrans(dict.fromkeys(punctuation_chars))\n self.wordchars=self.wordchars.translate(t)\n \n def push_token(self,tok):\n ''\n if self.debug >=1:\n print(\"shlex: pushing token \"+repr(tok))\n self.pushback.appendleft(tok)\n \n def push_source(self,newstream,newfile=None ):\n ''\n if isinstance(newstream,str):\n newstream=StringIO(newstream)\n self.filestack.appendleft((self.infile,self.instream,self.lineno))\n self.infile=newfile\n self.instream=newstream\n self.lineno=1\n if self.debug:\n if newfile is not None :\n print('shlex: pushing to file %s'%(self.infile,))\n else :\n print('shlex: pushing to stream %s'%(self.instream,))\n \n def pop_source(self):\n ''\n self.instream.close()\n (self.infile,self.instream,self.lineno)=self.filestack.popleft()\n if self.debug:\n print('shlex: popping to %s, line %d'\\\n %(self.instream,self.lineno))\n self.state=' '\n \n def get_token(self):\n ''\n if self.pushback:\n tok=self.pushback.popleft()\n if self.debug >=1:\n print(\"shlex: popping token \"+repr(tok))\n return tok\n \n raw=self.read_token()\n \n if self.source is not None :\n while raw ==self.source:\n spec=self.sourcehook(self.read_token())\n if spec:\n (newfile,newstream)=spec\n self.push_source(newstream,newfile)\n raw=self.get_token()\n \n while raw ==self.eof:\n if not self.filestack:\n return self.eof\n else :\n self.pop_source()\n raw=self.get_token()\n \n if self.debug >=1:\n if raw !=self.eof:\n print(\"shlex: token=\"+repr(raw))\n else :\n print(\"shlex: token=EOF\")\n return raw\n \n def read_token(self):\n quoted=False\n escapedstate=' '\n while True :\n if self.punctuation_chars and self._pushback_chars:\n nextchar=self._pushback_chars.pop()\n else :\n nextchar=self.instream.read(1)\n if nextchar =='\\n':\n self.lineno +=1\n if self.debug >=3:\n print(\"shlex: in state %r I see character: %r\"%(self.state,\n nextchar))\n if self.state is None :\n self.token=''\n break\n elif self.state ==' ':\n if not nextchar:\n self.state=None\n break\n elif nextchar in self.whitespace:\n if self.debug >=2:\n print(\"shlex: I see whitespace in whitespace state\")\n if self.token or (self.posix and quoted):\n break\n else :\n continue\n elif nextchar in self.commenters:\n self.instream.readline()\n self.lineno +=1\n elif self.posix and nextchar in self.escape:\n escapedstate='a'\n self.state=nextchar\n elif nextchar in self.wordchars:\n self.token=nextchar\n self.state='a'\n elif nextchar in self.punctuation_chars:\n self.token=nextchar\n self.state='c'\n elif nextchar in self.quotes:\n if not self.posix:\n self.token=nextchar\n self.state=nextchar\n elif self.whitespace_split:\n self.token=nextchar\n self.state='a'\n else :\n self.token=nextchar\n if self.token or (self.posix and quoted):\n break\n else :\n continue\n elif self.state in self.quotes:\n quoted=True\n if not nextchar:\n if self.debug >=2:\n print(\"shlex: I see EOF in quotes state\")\n \n raise ValueError(\"No closing quotation\")\n if nextchar ==self.state:\n if not self.posix:\n self.token +=nextchar\n self.state=' '\n break\n else :\n self.state='a'\n elif (self.posix and nextchar in self.escape and self.state\n in self.escapedquotes):\n escapedstate=self.state\n self.state=nextchar\n else :\n self.token +=nextchar\n elif self.state in self.escape:\n if not nextchar:\n if self.debug >=2:\n print(\"shlex: I see EOF in escape state\")\n \n raise ValueError(\"No escaped character\")\n \n \n if (escapedstate in self.quotes and\n nextchar !=self.state and nextchar !=escapedstate):\n self.token +=self.state\n self.token +=nextchar\n self.state=escapedstate\n elif self.state in ('a','c'):\n if not nextchar:\n self.state=None\n break\n elif nextchar in self.whitespace:\n if self.debug >=2:\n print(\"shlex: I see whitespace in word state\")\n self.state=' '\n if self.token or (self.posix and quoted):\n break\n else :\n continue\n elif nextchar in self.commenters:\n self.instream.readline()\n self.lineno +=1\n if self.posix:\n self.state=' '\n if self.token or (self.posix and quoted):\n break\n else :\n continue\n elif self.state =='c':\n if nextchar in self.punctuation_chars:\n self.token +=nextchar\n else :\n if nextchar not in self.whitespace:\n self._pushback_chars.append(nextchar)\n self.state=' '\n break\n elif self.posix and nextchar in self.quotes:\n self.state=nextchar\n elif self.posix and nextchar in self.escape:\n escapedstate='a'\n self.state=nextchar\n elif (nextchar in self.wordchars or nextchar in self.quotes\n or self.whitespace_split):\n self.token +=nextchar\n else :\n if self.punctuation_chars:\n self._pushback_chars.append(nextchar)\n else :\n self.pushback.appendleft(nextchar)\n if self.debug >=2:\n print(\"shlex: I see punctuation in word state\")\n self.state=' '\n if self.token or (self.posix and quoted):\n break\n else :\n continue\n result=self.token\n self.token=''\n if self.posix and not quoted and result =='':\n result=None\n if self.debug >1:\n if result:\n print(\"shlex: raw token=\"+repr(result))\n else :\n print(\"shlex: raw token=EOF\")\n return result\n \n def sourcehook(self,newfile):\n ''\n if newfile[0]=='\"':\n newfile=newfile[1:-1]\n \n if isinstance(self.infile,str)and not os.path.isabs(newfile):\n newfile=os.path.join(os.path.dirname(self.infile),newfile)\n return (newfile,open(newfile,\"r\"))\n \n def error_leader(self,infile=None ,lineno=None ):\n ''\n if infile is None :\n infile=self.infile\n if lineno is None :\n lineno=self.lineno\n return \"\\\"%s\\\", line %d: \"%(infile,lineno)\n \n def __iter__(self):\n return self\n \n def __next__(self):\n token=self.get_token()\n if token ==self.eof:\n raise StopIteration\n return token\n \ndef split(s,comments=False ,posix=True ):\n lex=shlex(s,posix=posix)\n lex.whitespace_split=True\n if not comments:\n lex.commenters=''\n return list(lex)\n \n \n_find_unsafe=re.compile(r'[^\\w@%+=:,./-]',re.ASCII).search\n\ndef quote(s):\n ''\n if not s:\n return \"''\"\n if _find_unsafe(s)is None :\n return s\n \n \n \n return \"'\"+s.replace(\"'\",\"'\\\"'\\\"'\")+\"'\"\n \n \ndef _print_tokens(lexer):\n while 1:\n tt=lexer.get_token()\n if not tt:\n break\n print(\"Token: \"+repr(tt))\n \nif __name__ =='__main__':\n if len(sys.argv)==1:\n _print_tokens(shlex())\n else :\n fn=sys.argv[1]\n with open(fn)as f:\n _print_tokens(shlex(f,fn))\n", ["collections", "io", "os", "re", "sys"]], "_py_abc": [".py", "from _weakrefset import WeakSet\n\n\ndef get_cache_token():\n ''\n\n\n\n\n \n return ABCMeta._abc_invalidation_counter\n \n \nclass ABCMeta(type):\n ''\n\n\n\n\n\n\n\n\n\n\n \n \n \n \n \n \n \n _abc_invalidation_counter=0\n \n def __new__(mcls,name,bases,namespace,**kwargs):\n cls=super().__new__(mcls,name,bases,namespace,**kwargs)\n \n abstracts={name\n for name,value in namespace.items()\n if getattr(value,\"__isabstractmethod__\",False )}\n for base in bases:\n for name in getattr(base,\"__abstractmethods__\",set()):\n value=getattr(cls,name,None )\n if getattr(value,\"__isabstractmethod__\",False ):\n abstracts.add(name)\n cls.__abstractmethods__=frozenset(abstracts)\n \n cls._abc_registry=WeakSet()\n cls._abc_cache=WeakSet()\n cls._abc_negative_cache=WeakSet()\n cls._abc_negative_cache_version=ABCMeta._abc_invalidation_counter\n return cls\n \n def register(cls,subclass):\n ''\n\n\n \n if not isinstance(subclass,type):\n raise TypeError(\"Can only register classes\")\n if issubclass(subclass,cls):\n return subclass\n \n \n if issubclass(cls,subclass):\n \n raise RuntimeError(\"Refusing to create an inheritance cycle\")\n cls._abc_registry.add(subclass)\n ABCMeta._abc_invalidation_counter +=1\n return subclass\n \n def _dump_registry(cls,file=None ):\n ''\n print(f\"Class: {cls.__module__}.{cls.__qualname__}\",file=file)\n print(f\"Inv. counter: {get_cache_token()}\",file=file)\n for name in cls.__dict__:\n if name.startswith(\"_abc_\"):\n value=getattr(cls,name)\n if isinstance(value,WeakSet):\n value=set(value)\n print(f\"{name}: {value!r}\",file=file)\n \n def _abc_registry_clear(cls):\n ''\n cls._abc_registry.clear()\n \n def _abc_caches_clear(cls):\n ''\n cls._abc_cache.clear()\n cls._abc_negative_cache.clear()\n \n def __instancecheck__(cls,instance):\n ''\n \n subclass=instance.__class__\n if subclass in cls._abc_cache:\n return True\n subtype=type(instance)\n if subtype is subclass:\n if (cls._abc_negative_cache_version ==\n ABCMeta._abc_invalidation_counter and\n subclass in cls._abc_negative_cache):\n return False\n \n return cls.__subclasscheck__(subclass)\n return any(cls.__subclasscheck__(c)for c in (subclass,subtype))\n \n def __subclasscheck__(cls,subclass):\n ''\n if not isinstance(subclass,type):\n raise TypeError('issubclass() arg 1 must be a class')\n \n if subclass in cls._abc_cache:\n return True\n \n if cls._abc_negative_cache_version <ABCMeta._abc_invalidation_counter:\n \n cls._abc_negative_cache=WeakSet()\n cls._abc_negative_cache_version=ABCMeta._abc_invalidation_counter\n elif subclass in cls._abc_negative_cache:\n return False\n \n ok=cls.__subclasshook__(subclass)\n if ok is not NotImplemented:\n assert isinstance(ok,bool)\n if ok:\n cls._abc_cache.add(subclass)\n else :\n cls._abc_negative_cache.add(subclass)\n return ok\n \n if cls in getattr(subclass,'__mro__',()):\n cls._abc_cache.add(subclass)\n return True\n \n for rcls in cls._abc_registry:\n if issubclass(subclass,rcls):\n cls._abc_cache.add(subclass)\n return True\n \n for scls in cls.__subclasses__():\n if issubclass(subclass,scls):\n cls._abc_cache.add(subclass)\n return True\n \n cls._abc_negative_cache.add(subclass)\n return False\n", ["_weakrefset"]], "_socket": [".py", "''\n\n\n\n\nAF_APPLETALK=16\n\nAF_DECnet=12\n\nAF_INET=2\n\nAF_INET6=23\n\nAF_IPX=6\n\nAF_IRDA=26\n\nAF_SNA=11\n\nAF_UNSPEC=0\n\nAI_ADDRCONFIG=1024\n\nAI_ALL=256\n\nAI_CANONNAME=2\n\nAI_NUMERICHOST=4\n\nAI_NUMERICSERV=8\n\nAI_PASSIVE=1\n\nAI_V4MAPPED=2048\n\nCAPI='<capsule object \"_socket.CAPI\" at 0x00BC4F38>'\n\nEAI_AGAIN=11002\n\nEAI_BADFLAGS=10022\n\nEAI_FAIL=11003\n\nEAI_FAMILY=10047\n\nEAI_MEMORY=8\n\nEAI_NODATA=11001\n\nEAI_NONAME=11001\n\nEAI_SERVICE=10109\n\nEAI_SOCKTYPE=10044\n\nINADDR_ALLHOSTS_GROUP=-536870911\n\nINADDR_ANY=0\n\nINADDR_BROADCAST=-1\n\nINADDR_LOOPBACK=2130706433\n\nINADDR_MAX_LOCAL_GROUP=-536870657\n\nINADDR_NONE=-1\n\nINADDR_UNSPEC_GROUP=-536870912\n\nIPPORT_RESERVED=1024\n\nIPPORT_USERRESERVED=5000\n\nIPPROTO_ICMP=1\n\nIPPROTO_IP=0\n\nIPPROTO_RAW=255\n\nIPPROTO_TCP=6\n\nIPPROTO_UDP=17\n\nIPV6_CHECKSUM=26\n\nIPV6_DONTFRAG=14\n\nIPV6_HOPLIMIT=21\n\nIPV6_HOPOPTS=1\n\nIPV6_JOIN_GROUP=12\n\nIPV6_LEAVE_GROUP=13\n\nIPV6_MULTICAST_HOPS=10\n\nIPV6_MULTICAST_IF=9\n\nIPV6_MULTICAST_LOOP=11\n\nIPV6_PKTINFO=19\n\nIPV6_RECVRTHDR=38\n\nIPV6_RECVTCLASS=40\n\nIPV6_RTHDR=32\n\nIPV6_TCLASS=39\n\nIPV6_UNICAST_HOPS=4\n\nIPV6_V6ONLY=27\n\nIP_ADD_MEMBERSHIP=12\n\nIP_DROP_MEMBERSHIP=13\n\nIP_HDRINCL=2\n\nIP_MULTICAST_IF=9\n\nIP_MULTICAST_LOOP=11\n\nIP_MULTICAST_TTL=10\n\nIP_OPTIONS=1\n\nIP_RECVDSTADDR=25\n\nIP_TOS=3\n\nIP_TTL=4\n\nMSG_BCAST=1024\n\nMSG_CTRUNC=512\n\nMSG_DONTROUTE=4\n\nMSG_MCAST=2048\n\nMSG_OOB=1\n\nMSG_PEEK=2\n\nMSG_TRUNC=256\n\nNI_DGRAM=16\n\nNI_MAXHOST=1025\n\nNI_MAXSERV=32\n\nNI_NAMEREQD=4\n\nNI_NOFQDN=1\n\nNI_NUMERICHOST=2\n\nNI_NUMERICSERV=8\n\nRCVALL_MAX=3\n\nRCVALL_OFF=0\n\nRCVALL_ON=1\n\nRCVALL_SOCKETLEVELONLY=2\n\nSHUT_RD=0\n\nSHUT_RDWR=2\n\nSHUT_WR=1\n\nSIO_KEEPALIVE_VALS=2550136836\n\nSIO_RCVALL=2550136833\n\nSOCK_DGRAM=2\n\nSOCK_RAW=3\n\nSOCK_RDM=4\n\nSOCK_SEQPACKET=5\n\nSOCK_STREAM=1\n\nSOL_IP=0\n\nSOL_SOCKET=65535\n\nSOL_TCP=6\n\nSOL_UDP=17\n\nSOMAXCONN=2147483647\n\nSO_ACCEPTCONN=2\n\nSO_BROADCAST=32\n\nSO_DEBUG=1\n\nSO_DONTROUTE=16\n\nSO_ERROR=4103\n\nSO_EXCLUSIVEADDRUSE=-5\n\nSO_KEEPALIVE=8\n\nSO_LINGER=128\n\nSO_OOBINLINE=256\n\nSO_RCVBUF=4098\n\nSO_RCVLOWAT=4100\n\nSO_RCVTIMEO=4102\n\nSO_REUSEADDR=4\n\nSO_SNDBUF=4097\n\nSO_SNDLOWAT=4099\n\nSO_SNDTIMEO=4101\n\nSO_TYPE=4104\n\nSO_USELOOPBACK=64\n\nclass SocketType:\n pass\n \nTCP_MAXSEG=4\n\nTCP_NODELAY=1\n\n__loader__='<_frozen_importlib.ExtensionFileLoader object at 0x00CA2D90>'\n\ndef dup(*args,**kw):\n ''\n\n \n pass\n \nclass error:\n pass\n \nclass gaierror:\n pass\n \ndef getaddrinfo(*args,**kw):\n ''\n\n \n pass\n \ndef getdefaulttimeout(*args,**kw):\n ''\n\n\n \n pass\n \ndef gethostbyaddr(*args,**kw):\n ''\n\n \n pass\n \ndef gethostbyname(*args,**kw):\n ''\n \n pass\n \ndef gethostbyname_ex(*args,**kw):\n ''\n\n \n pass\n \ndef gethostname(*args,**kw):\n ''\n \n pass\n \ndef getnameinfo(*args,**kw):\n ''\n \n pass\n \ndef getprotobyname(*args,**kw):\n ''\n \n pass\n \ndef getservbyname(*args,**kw):\n ''\n\n\n \n pass\n \ndef getservbyport(*args,**kw):\n ''\n\n\n \n pass\n \nhas_ipv6=True\n\nclass herror:\n pass\n \ndef htonl(*args,**kw):\n ''\n \n pass\n \ndef htons(*args,**kw):\n ''\n \n pass\n \ndef inet_aton(*args,**kw):\n ''\n\n \n pass\n \ndef inet_ntoa(*args,**kw):\n ''\n \n pass\n \ndef ntohl(*args,**kw):\n ''\n \n pass\n \ndef ntohs(*args,**kw):\n ''\n \n pass\n \ndef setdefaulttimeout(*args,**kw):\n ''\n\n\n \n pass\n \nclass socket:\n def __init__(self,*args,**kw):\n pass\n def bind(self,*args,**kw):\n pass\n def close(self):\n pass\n \nclass timeout:\n pass\n", []], "email.message": [".py", "\n\n\n\n\"\"\"Basic message object for the email package object model.\"\"\"\n\n__all__=['Message','EmailMessage']\n\nimport re\nimport uu\nimport quopri\nfrom io import BytesIO,StringIO\n\n\nfrom email import utils\nfrom email import errors\nfrom email._policybase import Policy,compat32\nfrom email import charset as _charset\nfrom email._encoded_words import decode_b\nCharset=_charset.Charset\n\nSEMISPACE='; '\n\n\n\ntspecials=re.compile(r'[ \\(\\)<>@,;:\\\\\"/\\[\\]\\?=]')\n\n\ndef _splitparam(param):\n\n\n\n\n a,sep,b=str(param).partition(';')\n if not sep:\n return a.strip(),None\n return a.strip(),b.strip()\n \ndef _formatparam(param,value=None ,quote=True ):\n ''\n\n\n\n\n\n\n \n if value is not None and len(value)>0:\n \n \n \n if isinstance(value,tuple):\n \n param +='*'\n value=utils.encode_rfc2231(value[2],value[0],value[1])\n return '%s=%s'%(param,value)\n else :\n try :\n value.encode('ascii')\n except UnicodeEncodeError:\n param +='*'\n value=utils.encode_rfc2231(value,'utf-8','')\n return '%s=%s'%(param,value)\n \n \n if quote or tspecials.search(value):\n return '%s=\"%s\"'%(param,utils.quote(value))\n else :\n return '%s=%s'%(param,value)\n else :\n return param\n \ndef _parseparam(s):\n\n s=';'+str(s)\n plist=[]\n while s[:1]==';':\n s=s[1:]\n end=s.find(';')\n while end >0 and (s.count('\"',0,end)-s.count('\\\\\"',0,end))%2:\n end=s.find(';',end+1)\n if end <0:\n end=len(s)\n f=s[:end]\n if '='in f:\n i=f.index('=')\n f=f[:i].strip().lower()+'='+f[i+1:].strip()\n plist.append(f.strip())\n s=s[end:]\n return plist\n \n \ndef _unquotevalue(value):\n\n\n\n\n if isinstance(value,tuple):\n return value[0],value[1],utils.unquote(value[2])\n else :\n return utils.unquote(value)\n \n \n \nclass Message:\n ''\n\n\n\n\n\n\n\n\n\n\n\n\n \n def __init__(self,policy=compat32):\n self.policy=policy\n self._headers=[]\n self._unixfrom=None\n self._payload=None\n self._charset=None\n \n self.preamble=self.epilogue=None\n self.defects=[]\n \n self._default_type='text/plain'\n \n def __str__(self):\n ''\n \n return self.as_string()\n \n def as_string(self,unixfrom=False ,maxheaderlen=0,policy=None ):\n ''\n\n\n\n\n\n\n\n\n\n\n\n \n from email.generator import Generator\n policy=self.policy if policy is None else policy\n fp=StringIO()\n g=Generator(fp,\n mangle_from_=False ,\n maxheaderlen=maxheaderlen,\n policy=policy)\n g.flatten(self,unixfrom=unixfrom)\n return fp.getvalue()\n \n def __bytes__(self):\n ''\n \n return self.as_bytes()\n \n def as_bytes(self,unixfrom=False ,policy=None ):\n ''\n\n\n\n\n\n \n from email.generator import BytesGenerator\n policy=self.policy if policy is None else policy\n fp=BytesIO()\n g=BytesGenerator(fp,mangle_from_=False ,policy=policy)\n g.flatten(self,unixfrom=unixfrom)\n return fp.getvalue()\n \n def is_multipart(self):\n ''\n return isinstance(self._payload,list)\n \n \n \n \n def set_unixfrom(self,unixfrom):\n self._unixfrom=unixfrom\n \n def get_unixfrom(self):\n return self._unixfrom\n \n \n \n \n def attach(self,payload):\n ''\n\n\n\n\n \n if self._payload is None :\n self._payload=[payload]\n else :\n try :\n self._payload.append(payload)\n except AttributeError:\n raise TypeError(\"Attach is not valid on a message with a\"\n \" non-multipart payload\")\n \n def get_payload(self,i=None ,decode=False ):\n ''\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n if self.is_multipart():\n if decode:\n return None\n if i is None :\n return self._payload\n else :\n return self._payload[i]\n \n \n if i is not None and not isinstance(self._payload,list):\n raise TypeError('Expected list, got %s'%type(self._payload))\n payload=self._payload\n \n cte=str(self.get('content-transfer-encoding','')).lower()\n \n if isinstance(payload,str):\n if utils._has_surrogates(payload):\n bpayload=payload.encode('ascii','surrogateescape')\n if not decode:\n try :\n payload=bpayload.decode(self.get_param('charset','ascii'),'replace')\n except LookupError:\n payload=bpayload.decode('ascii','replace')\n elif decode:\n try :\n bpayload=payload.encode('ascii')\n except UnicodeError:\n \n \n \n \n bpayload=payload.encode('raw-unicode-escape')\n if not decode:\n return payload\n if cte =='quoted-printable':\n return quopri.decodestring(bpayload)\n elif cte =='base64':\n \n \n value,defects=decode_b(b''.join(bpayload.splitlines()))\n for defect in defects:\n self.policy.handle_defect(self,defect)\n return value\n elif cte in ('x-uuencode','uuencode','uue','x-uue'):\n in_file=BytesIO(bpayload)\n out_file=BytesIO()\n try :\n uu.decode(in_file,out_file,quiet=True )\n return out_file.getvalue()\n except uu.Error:\n \n return bpayload\n if isinstance(payload,str):\n return bpayload\n return payload\n \n def set_payload(self,payload,charset=None ):\n ''\n\n\n\n \n if hasattr(payload,'encode'):\n if charset is None :\n self._payload=payload\n return\n if not isinstance(charset,Charset):\n charset=Charset(charset)\n payload=payload.encode(charset.output_charset)\n if hasattr(payload,'decode'):\n self._payload=payload.decode('ascii','surrogateescape')\n else :\n self._payload=payload\n if charset is not None :\n self.set_charset(charset)\n \n def set_charset(self,charset):\n ''\n\n\n\n\n\n\n\n\n\n\n\n \n if charset is None :\n self.del_param('charset')\n self._charset=None\n return\n if not isinstance(charset,Charset):\n charset=Charset(charset)\n self._charset=charset\n if 'MIME-Version'not in self:\n self.add_header('MIME-Version','1.0')\n if 'Content-Type'not in self:\n self.add_header('Content-Type','text/plain',\n charset=charset.get_output_charset())\n else :\n self.set_param('charset',charset.get_output_charset())\n if charset !=charset.get_output_charset():\n self._payload=charset.body_encode(self._payload)\n if 'Content-Transfer-Encoding'not in self:\n cte=charset.get_body_encoding()\n try :\n cte(self)\n except TypeError:\n \n \n \n payload=self._payload\n if payload:\n try :\n payload=payload.encode('ascii','surrogateescape')\n except UnicodeError:\n payload=payload.encode(charset.output_charset)\n self._payload=charset.body_encode(payload)\n self.add_header('Content-Transfer-Encoding',cte)\n \n def get_charset(self):\n ''\n \n return self._charset\n \n \n \n \n def __len__(self):\n ''\n return len(self._headers)\n \n def __getitem__(self,name):\n ''\n\n\n\n\n\n\n \n return self.get(name)\n \n def __setitem__(self,name,val):\n ''\n\n\n\n \n max_count=self.policy.header_max_count(name)\n if max_count:\n lname=name.lower()\n found=0\n for k,v in self._headers:\n if k.lower()==lname:\n found +=1\n if found >=max_count:\n raise ValueError(\"There may be at most {} {} headers \"\n \"in a message\".format(max_count,name))\n self._headers.append(self.policy.header_store_parse(name,val))\n \n def __delitem__(self,name):\n ''\n\n\n \n name=name.lower()\n newheaders=[]\n for k,v in self._headers:\n if k.lower()!=name:\n newheaders.append((k,v))\n self._headers=newheaders\n \n def __contains__(self,name):\n return name.lower()in [k.lower()for k,v in self._headers]\n \n def __iter__(self):\n for field,value in self._headers:\n yield field\n \n def keys(self):\n ''\n\n\n\n\n\n \n return [k for k,v in self._headers]\n \n def values(self):\n ''\n\n\n\n\n\n \n return [self.policy.header_fetch_parse(k,v)\n for k,v in self._headers]\n \n def items(self):\n ''\n\n\n\n\n\n \n return [(k,self.policy.header_fetch_parse(k,v))\n for k,v in self._headers]\n \n def get(self,name,failobj=None ):\n ''\n\n\n\n \n name=name.lower()\n for k,v in self._headers:\n if k.lower()==name:\n return self.policy.header_fetch_parse(k,v)\n return failobj\n \n \n \n \n \n \n def set_raw(self,name,value):\n ''\n\n\n \n self._headers.append((name,value))\n \n def raw_items(self):\n ''\n\n\n \n return iter(self._headers.copy())\n \n \n \n \n \n def get_all(self,name,failobj=None ):\n ''\n\n\n\n\n\n\n \n values=[]\n name=name.lower()\n for k,v in self._headers:\n if k.lower()==name:\n values.append(self.policy.header_fetch_parse(k,v))\n if not values:\n return failobj\n return values\n \n def add_header(self,_name,_value,**_params):\n ''\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n \n parts=[]\n for k,v in _params.items():\n if v is None :\n parts.append(k.replace('_','-'))\n else :\n parts.append(_formatparam(k.replace('_','-'),v))\n if _value is not None :\n parts.insert(0,_value)\n self[_name]=SEMISPACE.join(parts)\n \n def replace_header(self,_name,_value):\n ''\n\n\n\n\n \n _name=_name.lower()\n for i,(k,v)in zip(range(len(self._headers)),self._headers):\n if k.lower()==_name:\n self._headers[i]=self.policy.header_store_parse(k,_value)\n break\n else :\n raise KeyError(_name)\n \n \n \n \n \n def get_content_type(self):\n ''\n\n\n\n\n\n\n\n\n\n\n \n missing=object()\n value=self.get('content-type',missing)\n if value is missing:\n \n return self.get_default_type()\n ctype=_splitparam(value)[0].lower()\n \n if ctype.count('/')!=1:\n return 'text/plain'\n return ctype\n \n def get_content_maintype(self):\n ''\n\n\n\n \n ctype=self.get_content_type()\n return ctype.split('/')[0]\n \n def get_content_subtype(self):\n ''\n\n\n\n \n ctype=self.get_content_type()\n return ctype.split('/')[1]\n \n def get_default_type(self):\n ''\n\n\n\n\n \n return self._default_type\n \n def set_default_type(self,ctype):\n ''\n\n\n\n\n \n self._default_type=ctype\n \n def _get_params_preserve(self,failobj,header):\n \n \n missing=object()\n value=self.get(header,missing)\n if value is missing:\n return failobj\n params=[]\n for p in _parseparam(value):\n try :\n name,val=p.split('=',1)\n name=name.strip()\n val=val.strip()\n except ValueError:\n \n name=p.strip()\n val=''\n params.append((name,val))\n params=utils.decode_params(params)\n return params\n \n def get_params(self,failobj=None ,header='content-type',unquote=True ):\n ''\n\n\n\n\n\n\n\n\n\n\n \n missing=object()\n params=self._get_params_preserve(missing,header)\n if params is missing:\n return failobj\n if unquote:\n return [(k,_unquotevalue(v))for k,v in params]\n else :\n return params\n \n def get_param(self,param,failobj=None ,header='content-type',\n unquote=True ):\n ''\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n \n if header not in self:\n return failobj\n for k,v in self._get_params_preserve(failobj,header):\n if k.lower()==param.lower():\n if unquote:\n return _unquotevalue(v)\n else :\n return v\n return failobj\n \n def set_param(self,param,value,header='Content-Type',requote=True ,\n charset=None ,language='',replace=False ):\n ''\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n \n if not isinstance(value,tuple)and charset:\n value=(charset,language,value)\n \n if header not in self and header.lower()=='content-type':\n ctype='text/plain'\n else :\n ctype=self.get(header)\n if not self.get_param(param,header=header):\n if not ctype:\n ctype=_formatparam(param,value,requote)\n else :\n ctype=SEMISPACE.join(\n [ctype,_formatparam(param,value,requote)])\n else :\n ctype=''\n for old_param,old_value in self.get_params(header=header,\n unquote=requote):\n append_param=''\n if old_param.lower()==param.lower():\n append_param=_formatparam(param,value,requote)\n else :\n append_param=_formatparam(old_param,old_value,requote)\n if not ctype:\n ctype=append_param\n else :\n ctype=SEMISPACE.join([ctype,append_param])\n if ctype !=self.get(header):\n if replace:\n self.replace_header(header,ctype)\n else :\n del self[header]\n self[header]=ctype\n \n def del_param(self,param,header='content-type',requote=True ):\n ''\n\n\n\n\n\n \n if header not in self:\n return\n new_ctype=''\n for p,v in self.get_params(header=header,unquote=requote):\n if p.lower()!=param.lower():\n if not new_ctype:\n new_ctype=_formatparam(p,v,requote)\n else :\n new_ctype=SEMISPACE.join([new_ctype,\n _formatparam(p,v,requote)])\n if new_ctype !=self.get(header):\n del self[header]\n self[header]=new_ctype\n \n def set_type(self,type,header='Content-Type',requote=True ):\n ''\n\n\n\n\n\n\n\n\n\n\n\n\n \n \n if not type.count('/')==1:\n raise ValueError\n \n if header.lower()=='content-type':\n del self['mime-version']\n self['MIME-Version']='1.0'\n if header not in self:\n self[header]=type\n return\n params=self.get_params(header=header,unquote=requote)\n del self[header]\n self[header]=type\n \n for p,v in params[1:]:\n self.set_param(p,v,header,requote)\n \n def get_filename(self,failobj=None ):\n ''\n\n\n\n\n\n \n missing=object()\n filename=self.get_param('filename',missing,'content-disposition')\n if filename is missing:\n filename=self.get_param('name',missing,'content-type')\n if filename is missing:\n return failobj\n return utils.collapse_rfc2231_value(filename).strip()\n \n def get_boundary(self,failobj=None ):\n ''\n\n\n\n \n missing=object()\n boundary=self.get_param('boundary',missing)\n if boundary is missing:\n return failobj\n \n return utils.collapse_rfc2231_value(boundary).rstrip()\n \n def set_boundary(self,boundary):\n ''\n\n\n\n\n\n\n\n \n missing=object()\n params=self._get_params_preserve(missing,'content-type')\n if params is missing:\n \n \n raise errors.HeaderParseError('No Content-Type header found')\n newparams=[]\n foundp=False\n for pk,pv in params:\n if pk.lower()=='boundary':\n newparams.append(('boundary','\"%s\"'%boundary))\n foundp=True\n else :\n newparams.append((pk,pv))\n if not foundp:\n \n \n \n newparams.append(('boundary','\"%s\"'%boundary))\n \n newheaders=[]\n for h,v in self._headers:\n if h.lower()=='content-type':\n parts=[]\n for k,v in newparams:\n if v =='':\n parts.append(k)\n else :\n parts.append('%s=%s'%(k,v))\n val=SEMISPACE.join(parts)\n newheaders.append(self.policy.header_store_parse(h,val))\n \n else :\n newheaders.append((h,v))\n self._headers=newheaders\n \n def get_content_charset(self,failobj=None ):\n ''\n\n\n\n\n \n missing=object()\n charset=self.get_param('charset',missing)\n if charset is missing:\n return failobj\n if isinstance(charset,tuple):\n \n pcharset=charset[0]or 'us-ascii'\n try :\n \n \n \n as_bytes=charset[2].encode('raw-unicode-escape')\n charset=str(as_bytes,pcharset)\n except (LookupError,UnicodeError):\n charset=charset[2]\n \n try :\n charset.encode('us-ascii')\n except UnicodeError:\n return failobj\n \n return charset.lower()\n \n def get_charsets(self,failobj=None ):\n ''\n\n\n\n\n\n\n\n\n\n\n\n\n\n \n return [part.get_content_charset(failobj)for part in self.walk()]\n \n def get_content_disposition(self):\n ''\n\n\n\n \n value=self.get('content-disposition')\n if value is None :\n return None\n c_d=_splitparam(value)[0].lower()\n return c_d\n \n \n from email.iterators import walk\n \n \nclass MIMEPart(Message):\n\n def __init__(self,policy=None ):\n if policy is None :\n from email.policy import default\n policy=default\n Message.__init__(self,policy)\n \n \n def as_string(self,unixfrom=False ,maxheaderlen=None ,policy=None ):\n ''\n\n\n\n\n\n\n\n\n \n policy=self.policy if policy is None else policy\n if maxheaderlen is None :\n maxheaderlen=policy.max_line_length\n return super().as_string(maxheaderlen=maxheaderlen,policy=policy)\n \n def __str__(self):\n return self.as_string(policy=self.policy.clone(utf8=True ))\n \n def is_attachment(self):\n c_d=self.get('content-disposition')\n return False if c_d is None else c_d.content_disposition =='attachment'\n \n def _find_body(self,part,preferencelist):\n if part.is_attachment():\n return\n maintype,subtype=part.get_content_type().split('/')\n if maintype =='text':\n if subtype in preferencelist:\n yield (preferencelist.index(subtype),part)\n return\n if maintype !='multipart':\n return\n if subtype !='related':\n for subpart in part.iter_parts():\n yield from self._find_body(subpart,preferencelist)\n return\n if 'related'in preferencelist:\n yield (preferencelist.index('related'),part)\n candidate=None\n start=part.get_param('start')\n if start:\n for subpart in part.iter_parts():\n if subpart['content-id']==start:\n candidate=subpart\n break\n if candidate is None :\n subparts=part.get_payload()\n candidate=subparts[0]if subparts else None\n if candidate is not None :\n yield from self._find_body(candidate,preferencelist)\n \n def get_body(self,preferencelist=('related','html','plain')):\n ''\n\n\n\n\n\n\n\n \n best_prio=len(preferencelist)\n body=None\n for prio,part in self._find_body(self,preferencelist):\n if prio <best_prio:\n best_prio=prio\n body=part\n if prio ==0:\n break\n return body\n \n _body_types={('text','plain'),\n ('text','html'),\n ('multipart','related'),\n ('multipart','alternative')}\n def iter_attachments(self):\n ''\n\n\n\n\n\n\n\n\n \n maintype,subtype=self.get_content_type().split('/')\n if maintype !='multipart'or subtype =='alternative':\n return\n parts=self.get_payload().copy()\n if maintype =='multipart'and subtype =='related':\n \n \n \n start=self.get_param('start')\n if start:\n found=False\n attachments=[]\n for part in parts:\n if part.get('content-id')==start:\n found=True\n else :\n attachments.append(part)\n if found:\n yield from attachments\n return\n parts.pop(0)\n yield from parts\n return\n \n \n \n seen=[]\n for part in parts:\n maintype,subtype=part.get_content_type().split('/')\n if ((maintype,subtype)in self._body_types and\n not part.is_attachment()and subtype not in seen):\n seen.append(subtype)\n continue\n yield part\n \n def iter_parts(self):\n ''\n\n\n \n if self.get_content_maintype()=='multipart':\n yield from self.get_payload()\n \n def get_content(self,*args,content_manager=None ,**kw):\n if content_manager is None :\n content_manager=self.policy.content_manager\n return content_manager.get_content(self,*args,**kw)\n \n def set_content(self,*args,content_manager=None ,**kw):\n if content_manager is None :\n content_manager=self.policy.content_manager\n content_manager.set_content(self,*args,**kw)\n \n def _make_multipart(self,subtype,disallowed_subtypes,boundary):\n if self.get_content_maintype()=='multipart':\n existing_subtype=self.get_content_subtype()\n disallowed_subtypes=disallowed_subtypes+(subtype,)\n if existing_subtype in disallowed_subtypes:\n raise ValueError(\"Cannot convert {} to {}\".format(\n existing_subtype,subtype))\n keep_headers=[]\n part_headers=[]\n for name,value in self._headers:\n if name.lower().startswith('content-'):\n part_headers.append((name,value))\n else :\n keep_headers.append((name,value))\n if part_headers:\n \n part=type(self)(policy=self.policy)\n part._headers=part_headers\n part._payload=self._payload\n self._payload=[part]\n else :\n self._payload=[]\n self._headers=keep_headers\n self['Content-Type']='multipart/'+subtype\n if boundary is not None :\n self.set_param('boundary',boundary)\n \n def make_related(self,boundary=None ):\n self._make_multipart('related',('alternative','mixed'),boundary)\n \n def make_alternative(self,boundary=None ):\n self._make_multipart('alternative',('mixed',),boundary)\n \n def make_mixed(self,boundary=None ):\n self._make_multipart('mixed',(),boundary)\n \n def _add_multipart(self,_subtype,*args,_disp=None ,**kw):\n if (self.get_content_maintype()!='multipart'or\n self.get_content_subtype()!=_subtype):\n getattr(self,'make_'+_subtype)()\n part=type(self)(policy=self.policy)\n part.set_content(*args,**kw)\n if _disp and 'content-disposition'not in part:\n part['Content-Disposition']=_disp\n self.attach(part)\n \n def add_related(self,*args,**kw):\n self._add_multipart('related',*args,_disp='inline',**kw)\n \n def add_alternative(self,*args,**kw):\n self._add_multipart('alternative',*args,**kw)\n \n def add_attachment(self,*args,**kw):\n self._add_multipart('mixed',*args,_disp='attachment',**kw)\n \n def clear(self):\n self._headers=[]\n self._payload=None\n \n def clear_content(self):\n self._headers=[(n,v)for n,v in self._headers\n if not n.lower().startswith('content-')]\n self._payload=None\n \n \nclass EmailMessage(MIMEPart):\n\n def set_content(self,*args,**kw):\n super().set_content(*args,**kw)\n if 'MIME-Version'not in self:\n self['MIME-Version']='1.0'\n", ["email", "email._encoded_words", "email._policybase", "email.charset", "email.errors", "email.generator", "email.iterators", "email.policy", "email.utils", "io", "quopri", "re", "uu"]], "_zlib_utils": [".js", "\nfunction rfind(buf, seq){\n var buflen = buf.length,\n len = seq.length\n for(var i = buflen - len; i >= 0; i--){\n var chunk = buf.slice(i, i + len),\n found = true\n for(var j = 0; j < len; j++){\n if(chunk[j] != seq[j]){\n found = false\n break\n }\n }\n if(found){return i}\n }\n return -1\n}\n\nvar $module = (function($B){\n\n return {\n lz_generator: function(text, size, min_len){\n /*\n Returns a list of items based on the LZ algorithm, using the\n specified window size and a minimum match length.\n The items are a tuple (length, distance) if a match has been\n found, and a byte otherwise.\n */\n // 'text' is an instance of Python 'bytes' class, the actual\n // bytes are in text.source\n text = text.source\n if(min_len === undefined){\n min_len = 3\n }\n var pos = 0, // position in text\n items = [] // returned items\n while(pos < text.length){\n sequence = text.slice(pos, pos + min_len)\n if(sequence.length < 3){\n for(var i = pos; i < text.length; i++){\n items.push(text[i])\n }\n break\n }\n // Search the sequence in the 'size' previous bytes\n buf = text.slice(pos - size, pos)\n buf_pos = rfind(buf, sequence)\n if(buf_pos > -1){\n // Match of length 3 found; search a longer one\n var len = 1\n while(len < 259 &&\n buf_pos + len < buf.length &&\n pos + len < text.length &&\n text[pos + len] == buf[buf_pos + len]){\n len += 1\n }\n match = text.slice(pos, pos + len)\n // \"Lazy matching\": search longer match starting at next\n // position\n longer_match = false\n if(pos + len < text.length - 2){\n match2 = text.slice(pos + 1, pos + len + 2)\n longer_buf_pos = rfind(buf, match2)\n if(longer_buf_pos > -1){\n // found longer match : emit current byte as\n // literal and move 1 byte forward\n longer_match = true\n char = text[pos]\n items.push(char)\n pos += 1\n }\n }\n if(! longer_match){\n distance = buf.length - buf_pos\n items.push($B.fast_tuple([len, distance]))\n if(pos + len == text.length){\n break\n }else{\n pos += len\n items.push(text[pos])\n pos += 1\n }\n }\n }else{\n char = text[pos]\n items.push(char)\n pos += 1\n }\n }\n return items\n }\n }\n})(__BRYTHON__)"], "base64": [".py", "#! /usr/bin/env python3\n\n\"\"\"Base16, Base32, Base64 (RFC 3548), Base85 and Ascii85 data encodings\"\"\"\n\n\n\n\n\nimport re\nimport struct\nimport binascii\n\n\n__all__=[\n\n'encode','decode','encodebytes','decodebytes',\n\n'b64encode','b64decode','b32encode','b32decode',\n'b16encode','b16decode',\n\n'b85encode','b85decode','a85encode','a85decode',\n\n'standard_b64encode','standard_b64decode',\n\n\n\n\n'urlsafe_b64encode','urlsafe_b64decode',\n]\n\n\nbytes_types=(bytes,bytearray)\n\ndef _bytes_from_decode_data(s):\n if isinstance(s,str):\n try :\n return s.encode('ascii')\n except UnicodeEncodeError:\n raise ValueError('string argument should contain only ASCII characters')\n if isinstance(s,bytes_types):\n return s\n try :\n return memoryview(s).tobytes()\n except TypeError:\n raise TypeError(\"argument should be a bytes-like object or ASCII \"\n \"string, not %r\"%s.__class__.__name__)from None\n \n \n \n \ndef b64encode(s,altchars=None ):\n ''\n\n\n\n\n \n encoded=binascii.b2a_base64(s,newline=False )\n if altchars is not None :\n assert len(altchars)==2,repr(altchars)\n return encoded.translate(bytes.maketrans(b'+/',altchars))\n return encoded\n \n \ndef b64decode(s,altchars=None ,validate=False ):\n ''\n\n\n\n\n\n\n\n\n\n\n\n\n \n s=_bytes_from_decode_data(s)\n if altchars is not None :\n altchars=_bytes_from_decode_data(altchars)\n assert len(altchars)==2,repr(altchars)\n s=s.translate(bytes.maketrans(altchars,b'+/'))\n if validate and not re.match(b'^[A-Za-z0-9+/]*={0,2}$',s):\n raise binascii.Error('Non-base64 digit found')\n return binascii.a2b_base64(s)\n \n \ndef standard_b64encode(s):\n ''\n\n\n \n return b64encode(s)\n \ndef standard_b64decode(s):\n ''\n\n\n\n\n\n \n return b64decode(s)\n \n \n_urlsafe_encode_translation=bytes.maketrans(b'+/',b'-_')\n_urlsafe_decode_translation=bytes.maketrans(b'-_',b'+/')\n\ndef urlsafe_b64encode(s):\n ''\n\n\n\n\n \n return b64encode(s).translate(_urlsafe_encode_translation)\n \ndef urlsafe_b64decode(s):\n ''\n\n\n\n\n\n\n\n\n \n s=_bytes_from_decode_data(s)\n s=s.translate(_urlsafe_decode_translation)\n return b64decode(s)\n \n \n \n \n_b32alphabet=b'ABCDEFGHIJKLMNOPQRSTUVWXYZ234567'\n_b32tab2=None\n_b32rev=None\n\ndef b32encode(s):\n ''\n \n global _b32tab2\n \n \n if _b32tab2 is None :\n b32tab=[bytes((i,))for i in _b32alphabet]\n _b32tab2=[a+b for a in b32tab for b in b32tab]\n b32tab=None\n \n if not isinstance(s,bytes_types):\n s=memoryview(s).tobytes()\n leftover=len(s)%5\n \n if leftover:\n s=s+b'\\0'*(5 -leftover)\n encoded=bytearray()\n from_bytes=int.from_bytes\n b32tab2=_b32tab2\n for i in range(0,len(s),5):\n c=from_bytes(s[i:i+5],'big')\n encoded +=(b32tab2[c >>30]+\n b32tab2[(c >>20)&0x3ff]+\n b32tab2[(c >>10)&0x3ff]+\n b32tab2[c&0x3ff]\n )\n \n if leftover ==1:\n encoded[-6:]=b'======'\n elif leftover ==2:\n encoded[-4:]=b'===='\n elif leftover ==3:\n encoded[-3:]=b'==='\n elif leftover ==4:\n encoded[-1:]=b'='\n return bytes(encoded)\n \ndef b32decode(s,casefold=False ,map01=None ):\n ''\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n \n global _b32rev\n \n \n if _b32rev is None :\n _b32rev={v:k for k,v in enumerate(_b32alphabet)}\n s=_bytes_from_decode_data(s)\n if len(s)%8:\n raise binascii.Error('Incorrect padding')\n \n \n \n if map01 is not None :\n map01=_bytes_from_decode_data(map01)\n assert len(map01)==1,repr(map01)\n s=s.translate(bytes.maketrans(b'01',b'O'+map01))\n if casefold:\n s=s.upper()\n \n \n \n l=len(s)\n s=s.rstrip(b'=')\n padchars=l -len(s)\n \n decoded=bytearray()\n b32rev=_b32rev\n for i in range(0,len(s),8):\n quanta=s[i:i+8]\n acc=0\n try :\n for c in quanta:\n acc=(acc <<5)+b32rev[c]\n except KeyError:\n raise binascii.Error('Non-base32 digit found')from None\n decoded +=acc.to_bytes(5,'big')\n \n if l %8 or padchars not in {0,1,3,4,6}:\n raise binascii.Error('Incorrect padding')\n if padchars and decoded:\n acc <<=5 *padchars\n last=acc.to_bytes(5,'big')\n leftover=(43 -5 *padchars)//8\n decoded[-5:]=last[:leftover]\n return bytes(decoded)\n \n \n \n \n \ndef b16encode(s):\n ''\n \n return binascii.hexlify(s).upper()\n \n \ndef b16decode(s,casefold=False ):\n ''\n\n\n\n\n\n\n\n \n s=_bytes_from_decode_data(s)\n if casefold:\n s=s.upper()\n if re.search(b'[^0-9A-F]',s):\n raise binascii.Error('Non-base16 digit found')\n return binascii.unhexlify(s)\n \n \n \n \n \n_a85chars=None\n_a85chars2=None\n_A85START=b\"<~\"\n_A85END=b\"~>\"\n\ndef _85encode(b,chars,chars2,pad=False ,foldnuls=False ,foldspaces=False ):\n\n if not isinstance(b,bytes_types):\n b=memoryview(b).tobytes()\n \n padding=(-len(b))%4\n if padding:\n b=b+b'\\0'*padding\n words=struct.Struct('!%dI'%(len(b)//4)).unpack(b)\n \n chunks=[b'z'if foldnuls and not word else\n b'y'if foldspaces and word ==0x20202020 else\n (chars2[word //614125]+\n chars2[word //85 %7225]+\n chars[word %85])\n for word in words]\n \n if padding and not pad:\n if chunks[-1]==b'z':\n chunks[-1]=chars[0]*5\n chunks[-1]=chunks[-1][:-padding]\n \n return b''.join(chunks)\n \ndef a85encode(b,*,foldspaces=False ,wrapcol=0,pad=False ,adobe=False ):\n ''\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n \n global _a85chars,_a85chars2\n \n \n if _a85chars is None :\n _a85chars=[bytes((i,))for i in range(33,118)]\n _a85chars2=[(a+b)for a in _a85chars for b in _a85chars]\n \n result=_85encode(b,_a85chars,_a85chars2,pad,True ,foldspaces)\n \n if adobe:\n result=_A85START+result\n if wrapcol:\n wrapcol=max(2 if adobe else 1,wrapcol)\n chunks=[result[i:i+wrapcol]\n for i in range(0,len(result),wrapcol)]\n if adobe:\n if len(chunks[-1])+2 >wrapcol:\n chunks.append(b'')\n result=b'\\n'.join(chunks)\n if adobe:\n result +=_A85END\n \n return result\n \ndef a85decode(b,*,foldspaces=False ,adobe=False ,ignorechars=b' \\t\\n\\r\\v'):\n ''\n\n\n\n\n\n\n\n\n\n\n\n\n\n \n b=_bytes_from_decode_data(b)\n if adobe:\n if not b.endswith(_A85END):\n raise ValueError(\n \"Ascii85 encoded byte sequences must end \"\n \"with {!r}\".format(_A85END)\n )\n if b.startswith(_A85START):\n b=b[2:-2]\n else :\n b=b[:-2]\n \n \n \n \n packI=struct.Struct('!I').pack\n decoded=[]\n decoded_append=decoded.append\n curr=[]\n curr_append=curr.append\n curr_clear=curr.clear\n for x in b+b'u'*4:\n if b'!'[0]<=x <=b'u'[0]:\n curr_append(x)\n if len(curr)==5:\n acc=0\n for x in curr:\n acc=85 *acc+(x -33)\n try :\n decoded_append(packI(acc))\n except struct.error:\n raise ValueError('Ascii85 overflow')from None\n curr_clear()\n elif x ==b'z'[0]:\n if curr:\n raise ValueError('z inside Ascii85 5-tuple')\n decoded_append(b'\\0\\0\\0\\0')\n elif foldspaces and x ==b'y'[0]:\n if curr:\n raise ValueError('y inside Ascii85 5-tuple')\n decoded_append(b'\\x20\\x20\\x20\\x20')\n elif x in ignorechars:\n \n continue\n else :\n raise ValueError('Non-Ascii85 digit found: %c'%x)\n \n result=b''.join(decoded)\n padding=4 -len(curr)\n if padding:\n \n result=result[:-padding]\n return result\n \n \n \n_b85alphabet=(b\"0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ\"\nb\"abcdefghijklmnopqrstuvwxyz!#$%&()*+-;<=>?@^_`{|}~\")\n_b85chars=None\n_b85chars2=None\n_b85dec=None\n\ndef b85encode(b,pad=False ):\n ''\n\n\n\n \n global _b85chars,_b85chars2\n \n \n if _b85chars is None :\n _b85chars=[bytes((i,))for i in _b85alphabet]\n _b85chars2=[(a+b)for a in _b85chars for b in _b85chars]\n return _85encode(b,_b85chars,_b85chars2,pad)\n \ndef b85decode(b):\n ''\n\n\n \n global _b85dec\n \n \n if _b85dec is None :\n _b85dec=[None ]*256\n for i,c in enumerate(_b85alphabet):\n _b85dec[c]=i\n \n b=_bytes_from_decode_data(b)\n padding=(-len(b))%5\n b=b+b'~'*padding\n out=[]\n packI=struct.Struct('!I').pack\n for i in range(0,len(b),5):\n chunk=b[i:i+5]\n acc=0\n try :\n for c in chunk:\n acc=acc *85+_b85dec[c]\n except TypeError:\n for j,c in enumerate(chunk):\n if _b85dec[c]is None :\n raise ValueError('bad base85 character at position %d'\n %(i+j))from None\n raise\n try :\n out.append(packI(acc))\n except struct.error:\n raise ValueError('base85 overflow in hunk starting at byte %d'\n %i)from None\n \n result=b''.join(out)\n if padding:\n result=result[:-padding]\n return result\n \n \n \n \n \nMAXLINESIZE=76\nMAXBINSIZE=(MAXLINESIZE //4)*3\n\ndef encode(input,output):\n ''\n while True :\n s=input.read(MAXBINSIZE)\n if not s:\n break\n while len(s)<MAXBINSIZE:\n ns=input.read(MAXBINSIZE -len(s))\n if not ns:\n break\n s +=ns\n line=binascii.b2a_base64(s)\n output.write(line)\n \n \ndef decode(input,output):\n ''\n while True :\n line=input.readline()\n if not line:\n break\n s=binascii.a2b_base64(line)\n output.write(s)\n \ndef _input_type_check(s):\n try :\n m=memoryview(s)\n except TypeError as err:\n msg=\"expected bytes-like object, not %s\"%s.__class__.__name__\n raise TypeError(msg)from err\n if m.format not in ('c','b','B'):\n msg=(\"expected single byte elements, not %r from %s\"%\n (m.format,s.__class__.__name__))\n raise TypeError(msg)\n if m.ndim !=1:\n msg=(\"expected 1-D data, not %d-D data from %s\"%\n (m.ndim,s.__class__.__name__))\n raise TypeError(msg)\n \n \ndef encodebytes(s):\n ''\n \n _input_type_check(s)\n pieces=[]\n for i in range(0,len(s),MAXBINSIZE):\n chunk=s[i:i+MAXBINSIZE]\n pieces.append(binascii.b2a_base64(chunk))\n return b\"\".join(pieces)\n \ndef encodestring(s):\n ''\n import warnings\n warnings.warn(\"encodestring() is a deprecated alias since 3.1, \"\n \"use encodebytes()\",\n DeprecationWarning,2)\n return encodebytes(s)\n \n \ndef decodebytes(s):\n ''\n _input_type_check(s)\n return binascii.a2b_base64(s)\n \ndef decodestring(s):\n ''\n import warnings\n warnings.warn(\"decodestring() is a deprecated alias since Python 3.1, \"\n \"use decodebytes()\",\n DeprecationWarning,2)\n return decodebytes(s)\n \n \n \ndef main():\n ''\n import sys,getopt\n try :\n opts,args=getopt.getopt(sys.argv[1:],'deut')\n except getopt.error as msg:\n sys.stdout=sys.stderr\n print(msg)\n print(\"\"\"usage: %s [-d|-e|-u|-t] [file|-]\n -d, -u: decode\n -e: encode (default)\n -t: encode and decode string 'Aladdin:open sesame'\"\"\"%sys.argv[0])\n sys.exit(2)\n func=encode\n for o,a in opts:\n if o =='-e':func=encode\n if o =='-d':func=decode\n if o =='-u':func=decode\n if o =='-t':test();return\n if args and args[0]!='-':\n with open(args[0],'rb')as f:\n func(f,sys.stdout.buffer)\n else :\n func(sys.stdin.buffer,sys.stdout.buffer)\n \n \ndef test():\n s0=b\"Aladdin:open sesame\"\n print(repr(s0))\n s1=encodebytes(s0)\n print(repr(s1))\n s2=decodebytes(s1)\n print(repr(s2))\n assert s0 ==s2\n \n \nif __name__ =='__main__':\n main()\n", ["binascii", "getopt", "re", "struct", "sys", "warnings"]], "threading": [".py", "''\n\nimport os as _os\nimport sys as _sys\nimport _thread\n\nfrom time import monotonic as _time\nfrom traceback import format_exc as _format_exc\nfrom _weakrefset import WeakSet\nfrom itertools import islice as _islice,count as _count\ntry :\n from _collections import deque as _deque\nexcept ImportError:\n from collections import deque as _deque\n \n \n \n \n \n \n \n \n \n \n \n__all__=['get_ident','active_count','Condition','current_thread',\n'enumerate','main_thread','TIMEOUT_MAX',\n'Event','Lock','RLock','Semaphore','BoundedSemaphore','Thread',\n'Barrier','BrokenBarrierError','Timer','ThreadError',\n'setprofile','settrace','local','stack_size']\n\n\n_start_new_thread=_thread.start_new_thread\n_allocate_lock=_thread.allocate_lock\n_set_sentinel=_thread._set_sentinel\nget_ident=_thread.get_ident\nThreadError=_thread.error\ntry :\n _CRLock=_thread.RLock\nexcept AttributeError:\n _CRLock=None\nTIMEOUT_MAX=_thread.TIMEOUT_MAX\ndel _thread\n\n\n\n\n_profile_hook=None\n_trace_hook=None\n\ndef setprofile(func):\n ''\n\n\n\n\n \n global _profile_hook\n _profile_hook=func\n \ndef settrace(func):\n ''\n\n\n\n\n \n global _trace_hook\n _trace_hook=func\n \n \n \nLock=_allocate_lock\n\ndef RLock(*args,**kwargs):\n ''\n\n\n\n\n\n\n \n if _CRLock is None :\n return _PyRLock(*args,**kwargs)\n return _CRLock(*args,**kwargs)\n \nclass _RLock:\n ''\n\n\n\n\n\n\n \n \n def __init__(self):\n self._block=_allocate_lock()\n self._owner=None\n self._count=0\n \n def __repr__(self):\n owner=self._owner\n try :\n owner=_active[owner].name\n except KeyError:\n pass\n return \"<%s %s.%s object owner=%r count=%d at %s>\"%(\n \"locked\"if self._block.locked()else \"unlocked\",\n self.__class__.__module__,\n self.__class__.__qualname__,\n owner,\n self._count,\n hex(id(self))\n )\n \n def acquire(self,blocking=True ,timeout=-1):\n ''\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n \n me=get_ident()\n if self._owner ==me:\n self._count +=1\n return 1\n rc=self._block.acquire(blocking,timeout)\n if rc:\n self._owner=me\n self._count=1\n return rc\n \n __enter__=acquire\n \n def release(self):\n ''\n\n\n\n\n\n\n\n\n\n\n\n\n\n \n if self._owner !=get_ident():\n raise RuntimeError(\"cannot release un-acquired lock\")\n self._count=count=self._count -1\n if not count:\n self._owner=None\n self._block.release()\n \n def __exit__(self,t,v,tb):\n self.release()\n \n \n \n def _acquire_restore(self,state):\n self._block.acquire()\n self._count,self._owner=state\n \n def _release_save(self):\n if self._count ==0:\n raise RuntimeError(\"cannot release un-acquired lock\")\n count=self._count\n self._count=0\n owner=self._owner\n self._owner=None\n self._block.release()\n return (count,owner)\n \n def _is_owned(self):\n return self._owner ==get_ident()\n \n_PyRLock=_RLock\n\n\nclass Condition:\n ''\n\n\n\n\n\n\n\n\n \n \n def __init__(self,lock=None ):\n if lock is None :\n lock=RLock()\n self._lock=lock\n \n self.acquire=lock.acquire\n self.release=lock.release\n \n \n \n try :\n self._release_save=lock._release_save\n except AttributeError:\n pass\n try :\n self._acquire_restore=lock._acquire_restore\n except AttributeError:\n pass\n try :\n self._is_owned=lock._is_owned\n except AttributeError:\n pass\n self._waiters=_deque()\n \n def __enter__(self):\n return self._lock.__enter__()\n \n def __exit__(self,*args):\n return self._lock.__exit__(*args)\n \n def __repr__(self):\n return \"<Condition(%s, %d)>\"%(self._lock,len(self._waiters))\n \n def _release_save(self):\n self._lock.release()\n \n def _acquire_restore(self,x):\n self._lock.acquire()\n \n def _is_owned(self):\n \n \n if self._lock.acquire(0):\n self._lock.release()\n return False\n else :\n return True\n \n def wait(self,timeout=None ):\n ''\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n \n if not self._is_owned():\n raise RuntimeError(\"cannot wait on un-acquired lock\")\n waiter=_allocate_lock()\n waiter.acquire()\n self._waiters.append(waiter)\n saved_state=self._release_save()\n gotit=False\n try :\n if timeout is None :\n waiter.acquire()\n gotit=True\n else :\n if timeout >0:\n gotit=waiter.acquire(True ,timeout)\n else :\n gotit=waiter.acquire(False )\n return gotit\n finally :\n self._acquire_restore(saved_state)\n if not gotit:\n try :\n self._waiters.remove(waiter)\n except ValueError:\n pass\n \n def wait_for(self,predicate,timeout=None ):\n ''\n\n\n\n\n\n \n endtime=None\n waittime=timeout\n result=predicate()\n while not result:\n if waittime is not None :\n if endtime is None :\n endtime=_time()+waittime\n else :\n waittime=endtime -_time()\n if waittime <=0:\n break\n self.wait(waittime)\n result=predicate()\n return result\n \n def notify(self,n=1):\n ''\n\n\n\n\n\n\n\n \n if not self._is_owned():\n raise RuntimeError(\"cannot notify on un-acquired lock\")\n all_waiters=self._waiters\n waiters_to_notify=_deque(_islice(all_waiters,n))\n if not waiters_to_notify:\n return\n for waiter in waiters_to_notify:\n waiter.release()\n try :\n all_waiters.remove(waiter)\n except ValueError:\n pass\n \n def notify_all(self):\n ''\n\n\n\n\n \n self.notify(len(self._waiters))\n \n notifyAll=notify_all\n \n \nclass Semaphore:\n ''\n\n\n\n\n\n\n \n \n \n \n def __init__(self,value=1):\n if value <0:\n raise ValueError(\"semaphore initial value must be >= 0\")\n self._cond=Condition(Lock())\n self._value=value\n \n def acquire(self,blocking=True ,timeout=None ):\n ''\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n \n if not blocking and timeout is not None :\n raise ValueError(\"can't specify timeout for non-blocking acquire\")\n rc=False\n endtime=None\n with self._cond:\n while self._value ==0:\n if not blocking:\n break\n if timeout is not None :\n if endtime is None :\n endtime=_time()+timeout\n else :\n timeout=endtime -_time()\n if timeout <=0:\n break\n self._cond.wait(timeout)\n else :\n self._value -=1\n rc=True\n return rc\n \n __enter__=acquire\n \n def release(self):\n ''\n\n\n\n\n \n with self._cond:\n self._value +=1\n self._cond.notify()\n \n def __exit__(self,t,v,tb):\n self.release()\n \n \nclass BoundedSemaphore(Semaphore):\n ''\n\n\n\n\n\n\n\n\n\n\n\n\n\n \n \n def __init__(self,value=1):\n Semaphore.__init__(self,value)\n self._initial_value=value\n \n def release(self):\n ''\n\n\n\n\n\n\n\n \n with self._cond:\n if self._value >=self._initial_value:\n raise ValueError(\"Semaphore released too many times\")\n self._value +=1\n self._cond.notify()\n \n \nclass Event:\n ''\n\n\n\n\n\n \n \n \n \n def __init__(self):\n self._cond=Condition(Lock())\n self._flag=False\n \n def _reset_internal_locks(self):\n \n self._cond.__init__(Lock())\n \n def is_set(self):\n ''\n return self._flag\n \n isSet=is_set\n \n def set(self):\n ''\n\n\n\n\n \n with self._cond:\n self._flag=True\n self._cond.notify_all()\n \n def clear(self):\n ''\n\n\n\n\n \n with self._cond:\n self._flag=False\n \n def wait(self,timeout=None ):\n ''\n\n\n\n\n\n\n\n\n\n\n\n\n \n with self._cond:\n signaled=self._flag\n if not signaled:\n signaled=self._cond.wait(timeout)\n return signaled\n \n \n \n \n \n \n \n \n \n \n \n \n \nclass Barrier:\n ''\n\n\n\n\n\n \n \n def __init__(self,parties,action=None ,timeout=None ):\n ''\n\n\n\n\n\n\n \n self._cond=Condition(Lock())\n self._action=action\n self._timeout=timeout\n self._parties=parties\n self._state=0\n self._count=0\n \n def wait(self,timeout=None ):\n ''\n\n\n\n\n\n\n \n if timeout is None :\n timeout=self._timeout\n with self._cond:\n self._enter()\n index=self._count\n self._count +=1\n try :\n if index+1 ==self._parties:\n \n self._release()\n else :\n \n self._wait(timeout)\n return index\n finally :\n self._count -=1\n \n self._exit()\n \n \n \n def _enter(self):\n while self._state in (-1,1):\n \n self._cond.wait()\n \n if self._state <0:\n raise BrokenBarrierError\n assert self._state ==0\n \n \n \n def _release(self):\n try :\n if self._action:\n self._action()\n \n self._state=1\n self._cond.notify_all()\n except :\n \n self._break()\n raise\n \n \n \n def _wait(self,timeout):\n if not self._cond.wait_for(lambda :self._state !=0,timeout):\n \n self._break()\n raise BrokenBarrierError\n if self._state <0:\n raise BrokenBarrierError\n assert self._state ==1\n \n \n \n def _exit(self):\n if self._count ==0:\n if self._state in (-1,1):\n \n self._state=0\n self._cond.notify_all()\n \n def reset(self):\n ''\n\n\n\n\n \n with self._cond:\n if self._count >0:\n if self._state ==0:\n \n self._state=-1\n elif self._state ==-2:\n \n \n self._state=-1\n else :\n self._state=0\n self._cond.notify_all()\n \n def abort(self):\n ''\n\n\n\n\n \n with self._cond:\n self._break()\n \n def _break(self):\n \n \n self._state=-2\n self._cond.notify_all()\n \n @property\n def parties(self):\n ''\n return self._parties\n \n @property\n def n_waiting(self):\n ''\n \n \n if self._state ==0:\n return self._count\n return 0\n \n @property\n def broken(self):\n ''\n return self._state ==-2\n \n \nclass BrokenBarrierError(RuntimeError):\n pass\n \n \n \n_counter=_count().__next__\n_counter()\ndef _newname(template=\"Thread-%d\"):\n return template %_counter()\n \n \n_active_limbo_lock=_allocate_lock()\n_active={}\n_limbo={}\n_dangling=WeakSet()\n\n\n\nclass Thread:\n ''\n\n\n\n\n\n \n \n _initialized=False\n \n \n \n \n _exc_info=_sys.exc_info\n \n \n \n \n def __init__(self,group=None ,target=None ,name=None ,\n args=(),kwargs=None ,*,daemon=None ):\n ''\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n \n assert group is None ,\"group argument must be None for now\"\n if kwargs is None :\n kwargs={}\n self._target=target\n self._name=str(name or _newname())\n self._args=args\n self._kwargs=kwargs\n if daemon is not None :\n self._daemonic=daemon\n else :\n self._daemonic=current_thread().daemon\n self._ident=None\n self._tstate_lock=None\n self._started=Event()\n self._is_stopped=False\n self._initialized=True\n \n \n self._stderr=_sys.stderr\n \n _dangling.add(self)\n \n def _reset_internal_locks(self,is_alive):\n \n \n self._started._reset_internal_locks()\n if is_alive:\n self._set_tstate_lock()\n else :\n \n \n self._is_stopped=True\n self._tstate_lock=None\n \n def __repr__(self):\n assert self._initialized,\"Thread.__init__() was not called\"\n status=\"initial\"\n if self._started.is_set():\n status=\"started\"\n self.is_alive()\n if self._is_stopped:\n status=\"stopped\"\n if self._daemonic:\n status +=\" daemon\"\n if self._ident is not None :\n status +=\" %s\"%self._ident\n return \"<%s(%s, %s)>\"%(self.__class__.__name__,self._name,status)\n \n def start(self):\n ''\n\n\n\n\n\n\n\n \n if not self._initialized:\n raise RuntimeError(\"thread.__init__() not called\")\n \n if self._started.is_set():\n raise RuntimeError(\"threads can only be started once\")\n with _active_limbo_lock:\n _limbo[self]=self\n try :\n _start_new_thread(self._bootstrap,())\n except Exception:\n with _active_limbo_lock:\n del _limbo[self]\n raise\n self._started.wait()\n \n def run(self):\n ''\n\n\n\n\n\n\n \n try :\n if self._target:\n self._target(*self._args,**self._kwargs)\n finally :\n \n \n del self._target,self._args,self._kwargs\n \n def _bootstrap(self):\n \n \n \n \n \n \n \n \n \n \n \n \n try :\n self._bootstrap_inner()\n except :\n if self._daemonic and _sys is None :\n return\n raise\n \n def _set_ident(self):\n self._ident=get_ident()\n \n def _set_tstate_lock(self):\n ''\n\n\n \n self._tstate_lock=_set_sentinel()\n self._tstate_lock.acquire()\n \n def _bootstrap_inner(self):\n try :\n self._set_ident()\n self._set_tstate_lock()\n self._started.set()\n with _active_limbo_lock:\n _active[self._ident]=self\n del _limbo[self]\n \n if _trace_hook:\n _sys.settrace(_trace_hook)\n if _profile_hook:\n _sys.setprofile(_profile_hook)\n \n try :\n self.run()\n except SystemExit:\n pass\n except :\n \n \n \n \n if _sys and _sys.stderr is not None :\n print(\"Exception in thread %s:\\n%s\"%\n (self.name,_format_exc()),file=_sys.stderr)\n elif self._stderr is not None :\n \n \n \n exc_type,exc_value,exc_tb=self._exc_info()\n try :\n print((\n \"Exception in thread \"+self.name+\n \" (most likely raised during interpreter shutdown):\"),file=self._stderr)\n print((\n \"Traceback (most recent call last):\"),file=self._stderr)\n while exc_tb:\n print((\n ' File \"%s\", line %s, in %s'%\n (exc_tb.tb_frame.f_code.co_filename,\n exc_tb.tb_lineno,\n exc_tb.tb_frame.f_code.co_name)),file=self._stderr)\n exc_tb=exc_tb.tb_next\n print((\"%s: %s\"%(exc_type,exc_value)),file=self._stderr)\n self._stderr.flush()\n \n \n finally :\n del exc_type,exc_value,exc_tb\n finally :\n \n \n \n \n \n pass\n finally :\n with _active_limbo_lock:\n try :\n \n \n del _active[get_ident()]\n except :\n pass\n \n def _stop(self):\n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n lock=self._tstate_lock\n if lock is not None :\n assert not lock.locked()\n self._is_stopped=True\n self._tstate_lock=None\n \n def _delete(self):\n ''\n with _active_limbo_lock:\n del _active[get_ident()]\n \n \n \n \n \n def join(self,timeout=None ):\n ''\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n \n if not self._initialized:\n raise RuntimeError(\"Thread.__init__() not called\")\n if not self._started.is_set():\n raise RuntimeError(\"cannot join thread before it is started\")\n if self is current_thread():\n raise RuntimeError(\"cannot join current thread\")\n \n if timeout is None :\n self._wait_for_tstate_lock()\n else :\n \n \n self._wait_for_tstate_lock(timeout=max(timeout,0))\n \n def _wait_for_tstate_lock(self,block=True ,timeout=-1):\n \n \n \n \n \n \n lock=self._tstate_lock\n if lock is None :\n assert self._is_stopped\n elif lock.acquire(block,timeout):\n lock.release()\n self._stop()\n \n @property\n def name(self):\n ''\n\n\n\n\n \n assert self._initialized,\"Thread.__init__() not called\"\n return self._name\n \n @name.setter\n def name(self,name):\n assert self._initialized,\"Thread.__init__() not called\"\n self._name=str(name)\n \n @property\n def ident(self):\n ''\n\n\n\n\n\n \n assert self._initialized,\"Thread.__init__() not called\"\n return self._ident\n \n def is_alive(self):\n ''\n\n\n\n\n\n \n assert self._initialized,\"Thread.__init__() not called\"\n if self._is_stopped or not self._started.is_set():\n return False\n self._wait_for_tstate_lock(False )\n return not self._is_stopped\n \n isAlive=is_alive\n \n @property\n def daemon(self):\n ''\n\n\n\n\n\n\n\n\n\n \n assert self._initialized,\"Thread.__init__() not called\"\n return self._daemonic\n \n @daemon.setter\n def daemon(self,daemonic):\n if not self._initialized:\n raise RuntimeError(\"Thread.__init__() not called\")\n if self._started.is_set():\n raise RuntimeError(\"cannot set daemon status of active thread\")\n self._daemonic=daemonic\n \n def isDaemon(self):\n return self.daemon\n \n def setDaemon(self,daemonic):\n self.daemon=daemonic\n \n def getName(self):\n return self.name\n \n def setName(self,name):\n self.name=name\n \n \n \nclass Timer(Thread):\n ''\n\n\n\n\n\n \n \n def __init__(self,interval,function,args=None ,kwargs=None ):\n Thread.__init__(self)\n self.interval=interval\n self.function=function\n self.args=args if args is not None else []\n self.kwargs=kwargs if kwargs is not None else {}\n self.finished=Event()\n \n def cancel(self):\n ''\n self.finished.set()\n \n def run(self):\n self.finished.wait(self.interval)\n if not self.finished.is_set():\n self.function(*self.args,**self.kwargs)\n self.finished.set()\n \n \n \n \nclass _MainThread(Thread):\n\n def __init__(self):\n Thread.__init__(self,name=\"MainThread\",daemon=False )\n self._set_tstate_lock()\n self._started.set()\n self._set_ident()\n with _active_limbo_lock:\n _active[self._ident]=self\n \n \n \n \n \n \n \n \n \n \nclass _DummyThread(Thread):\n\n def __init__(self):\n Thread.__init__(self,name=_newname(\"Dummy-%d\"),daemon=True )\n \n self._started.set()\n self._set_ident()\n with _active_limbo_lock:\n _active[self._ident]=self\n \n def _stop(self):\n pass\n \n def is_alive(self):\n assert not self._is_stopped and self._started.is_set()\n return True\n \n def join(self,timeout=None ):\n assert False ,\"cannot join a dummy thread\"\n \n \n \n \ndef current_thread():\n ''\n\n\n\n\n \n try :\n return _active[get_ident()]\n except KeyError:\n return _DummyThread()\n \ncurrentThread=current_thread\n\ndef active_count():\n ''\n\n\n\n\n \n with _active_limbo_lock:\n return len(_active)+len(_limbo)\n \nactiveCount=active_count\n\ndef _enumerate():\n\n return list(_active.values())+list(_limbo.values())\n \ndef enumerate():\n ''\n\n\n\n\n\n \n with _active_limbo_lock:\n return list(_active.values())+list(_limbo.values())\n \nfrom _thread import stack_size\n\n\n\n\n\n_main_thread=_MainThread()\n\ndef _shutdown():\n\n\n\n\n\n if _main_thread._is_stopped:\n \n return\n tlock=_main_thread._tstate_lock\n \n \n assert tlock is not None\n assert tlock.locked()\n tlock.release()\n _main_thread._stop()\n t=_pickSomeNonDaemonThread()\n while t:\n t.join()\n t=_pickSomeNonDaemonThread()\n \ndef _pickSomeNonDaemonThread():\n for t in enumerate():\n if not t.daemon and t.is_alive():\n return t\n return None\n \ndef main_thread():\n ''\n\n\n\n \n return _main_thread\n \n \n \n \ntry :\n from _thread import _local as local\nexcept ImportError:\n from _threading_local import local\n \n \ndef _after_fork():\n ''\n\n \n \n \n global _active_limbo_lock,_main_thread\n _active_limbo_lock=_allocate_lock()\n \n \n new_active={}\n current=current_thread()\n _main_thread=current\n with _active_limbo_lock:\n \n \n threads=set(_enumerate())\n threads.update(_dangling)\n for thread in threads:\n \n \n if thread is current:\n \n \n thread._reset_internal_locks(True )\n ident=get_ident()\n thread._ident=ident\n new_active[ident]=thread\n else :\n \n thread._reset_internal_locks(False )\n thread._stop()\n \n _limbo.clear()\n _active.clear()\n _active.update(new_active)\n assert len(_active)==1\n \n \nif hasattr(_os,\"register_at_fork\"):\n _os.register_at_fork(after_in_child=_after_fork)\n", ["_collections", "_thread", "_threading_local", "_weakrefset", "collections", "itertools", "os", "sys", "time", "traceback"]], "importlib._bootstrap_external": [".py", "''\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n_CASE_INSENSITIVE_PLATFORMS_STR_KEY='win',\n_CASE_INSENSITIVE_PLATFORMS_BYTES_KEY='cygwin','darwin'\n_CASE_INSENSITIVE_PLATFORMS=(_CASE_INSENSITIVE_PLATFORMS_BYTES_KEY\n+_CASE_INSENSITIVE_PLATFORMS_STR_KEY)\n\n\ndef _make_relax_case():\n if sys.platform.startswith(_CASE_INSENSITIVE_PLATFORMS):\n if sys.platform.startswith(_CASE_INSENSITIVE_PLATFORMS_STR_KEY):\n key='PYTHONCASEOK'\n else :\n key=b'PYTHONCASEOK'\n \n def _relax_case():\n ''\n return key in _os.environ\n else :\n def _relax_case():\n ''\n return False\n return _relax_case\n \n \ndef _w_long(x):\n ''\n return (int(x)&0xFFFFFFFF).to_bytes(4,'little')\n \n \ndef _r_long(int_bytes):\n ''\n return int.from_bytes(int_bytes,'little')\n \n \ndef _path_join(*path_parts):\n ''\n return path_sep.join([part.rstrip(path_separators)\n for part in path_parts if part])\n \n \ndef _path_split(path):\n ''\n if len(path_separators)==1:\n front,_,tail=path.rpartition(path_sep)\n return front,tail\n for x in reversed(path):\n if x in path_separators:\n front,tail=path.rsplit(x,maxsplit=1)\n return front,tail\n return '',path\n \n \ndef _path_stat(path):\n ''\n\n\n\n\n \n return _os.stat(path)\n \n \ndef _path_is_mode_type(path,mode):\n ''\n try :\n stat_info=_path_stat(path)\n except OSError:\n return False\n return (stat_info.st_mode&0o170000)==mode\n \n \ndef _path_isfile(path):\n ''\n return _path_is_mode_type(path,0o100000)\n \n \ndef _path_isdir(path):\n ''\n if not path:\n path=_os.getcwd()\n return _path_is_mode_type(path,0o040000)\n \n \ndef _write_atomic(path,data,mode=0o666):\n ''\n\n \n \n path_tmp='{}.{}'.format(path,id(path))\n fd=_os.open(path_tmp,\n _os.O_EXCL |_os.O_CREAT |_os.O_WRONLY,mode&0o666)\n try :\n \n \n with _io.FileIO(fd,'wb')as file:\n file.write(data)\n _os.replace(path_tmp,path)\n except OSError:\n try :\n _os.unlink(path_tmp)\n except OSError:\n pass\n raise\n \n \n_code_type=type(_write_atomic.__code__)\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\nMAGIC_NUMBER=(3394).to_bytes(2,'little')+b'\\r\\n'\n_RAW_MAGIC_NUMBER=int.from_bytes(MAGIC_NUMBER,'little')\n\n_PYCACHE='__pycache__'\n_OPT='opt-'\n\nSOURCE_SUFFIXES=['.py']\n\nBYTECODE_SUFFIXES=['.pyc']\n\nDEBUG_BYTECODE_SUFFIXES=OPTIMIZED_BYTECODE_SUFFIXES=BYTECODE_SUFFIXES\n\ndef cache_from_source(path,debug_override=None ,*,optimization=None ):\n ''\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n \n if debug_override is not None :\n _warnings.warn('the debug_override parameter is deprecated; use '\n \"'optimization' instead\",DeprecationWarning)\n if optimization is not None :\n message='debug_override or optimization must be set to None'\n raise TypeError(message)\n optimization=''if debug_override else 1\n path=_os.fspath(path)\n head,tail=_path_split(path)\n base,sep,rest=tail.rpartition('.')\n tag=sys.implementation.cache_tag\n if tag is None :\n raise NotImplementedError('sys.implementation.cache_tag is None')\n almost_filename=''.join([(base if base else rest),sep,tag])\n if optimization is None :\n if sys.flags.optimize ==0:\n optimization=''\n else :\n optimization=sys.flags.optimize\n optimization=str(optimization)\n if optimization !='':\n if not optimization.isalnum():\n raise ValueError('{!r} is not alphanumeric'.format(optimization))\n almost_filename='{}.{}{}'.format(almost_filename,_OPT,optimization)\n return _path_join(head,_PYCACHE,almost_filename+BYTECODE_SUFFIXES[0])\n \n \ndef source_from_cache(path):\n ''\n\n\n\n\n\n\n \n if sys.implementation.cache_tag is None :\n raise NotImplementedError('sys.implementation.cache_tag is None')\n path=_os.fspath(path)\n head,pycache_filename=_path_split(path)\n head,pycache=_path_split(head)\n if pycache !=_PYCACHE:\n raise ValueError('{} not bottom-level directory in '\n '{!r}'.format(_PYCACHE,path))\n dot_count=pycache_filename.count('.')\n if dot_count not in {2,3}:\n raise ValueError('expected only 2 or 3 dots in '\n '{!r}'.format(pycache_filename))\n elif dot_count ==3:\n optimization=pycache_filename.rsplit('.',2)[-2]\n if not optimization.startswith(_OPT):\n raise ValueError(\"optimization portion of filename does not start \"\n \"with {!r}\".format(_OPT))\n opt_level=optimization[len(_OPT):]\n if not opt_level.isalnum():\n raise ValueError(\"optimization level {!r} is not an alphanumeric \"\n \"value\".format(optimization))\n base_filename=pycache_filename.partition('.')[0]\n return _path_join(head,base_filename+SOURCE_SUFFIXES[0])\n \n \ndef _get_sourcefile(bytecode_path):\n ''\n\n\n\n\n \n if len(bytecode_path)==0:\n return None\n rest,_,extension=bytecode_path.rpartition('.')\n if not rest or extension.lower()[-3:-1]!='py':\n return bytecode_path\n try :\n source_path=source_from_cache(bytecode_path)\n except (NotImplementedError,ValueError):\n source_path=bytecode_path[:-1]\n return source_path if _path_isfile(source_path)else bytecode_path\n \n \ndef _get_cached(filename):\n if filename.endswith(tuple(SOURCE_SUFFIXES)):\n try :\n return cache_from_source(filename)\n except NotImplementedError:\n pass\n elif filename.endswith(tuple(BYTECODE_SUFFIXES)):\n return filename\n else :\n return None\n \n \ndef _calc_mode(path):\n ''\n try :\n mode=_path_stat(path).st_mode\n except OSError:\n mode=0o666\n \n \n mode |=0o200\n return mode\n \n \ndef _check_name(method):\n ''\n\n\n\n\n\n \n def _check_name_wrapper(self,name=None ,*args,**kwargs):\n if name is None :\n name=self.name\n elif self.name !=name:\n raise ImportError('loader for %s cannot handle %s'%\n (self.name,name),name=name)\n return method(self,name,*args,**kwargs)\n try :\n _wrap=_bootstrap._wrap\n except NameError:\n \n def _wrap(new,old):\n for replace in ['__module__','__name__','__qualname__','__doc__']:\n if hasattr(old,replace):\n setattr(new,replace,getattr(old,replace))\n new.__dict__.update(old.__dict__)\n _wrap(_check_name_wrapper,method)\n return _check_name_wrapper\n \n \ndef _find_module_shim(self,fullname):\n ''\n\n\n\n\n \n \n \n \n loader,portions=self.find_loader(fullname)\n if loader is None and len(portions):\n msg='Not importing directory {}: missing __init__'\n _warnings.warn(msg.format(portions[0]),ImportWarning)\n return loader\n \n \ndef _classify_pyc(data,name,exc_details):\n ''\n\n\n\n\n\n\n\n\n\n\n\n\n\n \n magic=data[:4]\n if magic !=MAGIC_NUMBER:\n message=f'bad magic number in {name!r}: {magic!r}'\n _bootstrap._verbose_message('{}',message)\n raise ImportError(message,**exc_details)\n if len(data)<16:\n message=f'reached EOF while reading pyc header of {name!r}'\n _bootstrap._verbose_message('{}',message)\n raise EOFError(message)\n flags=_r_long(data[4:8])\n \n if flags&~0b11:\n message=f'invalid flags {flags!r} in {name!r}'\n raise ImportError(message,**exc_details)\n return flags\n \n \ndef _validate_timestamp_pyc(data,source_mtime,source_size,name,\nexc_details):\n ''\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n \n if _r_long(data[8:12])!=(source_mtime&0xFFFFFFFF):\n message=f'bytecode is stale for {name!r}'\n _bootstrap._verbose_message('{}',message)\n raise ImportError(message,**exc_details)\n if (source_size is not None and\n _r_long(data[12:16])!=(source_size&0xFFFFFFFF)):\n raise ImportError(f'bytecode is stale for {name!r}',**exc_details)\n \n \ndef _validate_hash_pyc(data,source_hash,name,exc_details):\n ''\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n \n if data[8:16]!=source_hash:\n raise ImportError(\n f'hash in bytecode doesn\\'t match hash of source {name!r}',\n **exc_details,\n )\n \n \ndef _compile_bytecode(data,name=None ,bytecode_path=None ,source_path=None ):\n ''\n code=marshal.loads(data)\n if isinstance(code,_code_type):\n _bootstrap._verbose_message('code object from {!r}',bytecode_path)\n if source_path is not None :\n _imp._fix_co_filename(code,source_path)\n return code\n else :\n raise ImportError('Non-code object in {!r}'.format(bytecode_path),\n name=name,path=bytecode_path)\n \n \ndef _code_to_timestamp_pyc(code,mtime=0,source_size=0):\n ''\n data=bytearray(MAGIC_NUMBER)\n data.extend(_w_long(0))\n data.extend(_w_long(mtime))\n data.extend(_w_long(source_size))\n data.extend(marshal.dumps(code))\n return data\n \n \ndef _code_to_hash_pyc(code,source_hash,checked=True ):\n ''\n data=bytearray(MAGIC_NUMBER)\n flags=0b1 |checked <<1\n data.extend(_w_long(flags))\n assert len(source_hash)==8\n data.extend(source_hash)\n data.extend(marshal.dumps(code))\n return data\n \n \ndef decode_source(source_bytes):\n ''\n\n\n \n import tokenize\n source_bytes_readline=_io.BytesIO(source_bytes).readline\n encoding=tokenize.detect_encoding(source_bytes_readline)\n newline_decoder=_io.IncrementalNewlineDecoder(None ,True )\n return newline_decoder.decode(source_bytes.decode(encoding[0]))\n \n \n \n \n_POPULATE=object()\n\n\ndef spec_from_file_location(name,location=None ,*,loader=None ,\nsubmodule_search_locations=_POPULATE):\n ''\n\n\n\n\n\n\n\n\n \n if location is None :\n \n \n \n location='<unknown>'\n if hasattr(loader,'get_filename'):\n \n try :\n location=loader.get_filename(name)\n except ImportError:\n pass\n else :\n location=_os.fspath(location)\n \n \n \n \n \n \n \n spec=_bootstrap.ModuleSpec(name,loader,origin=location)\n spec._set_fileattr=True\n \n \n if loader is None :\n for loader_class,suffixes in _get_supported_file_loaders():\n if location.endswith(tuple(suffixes)):\n loader=loader_class(name,location)\n spec.loader=loader\n break\n else :\n return None\n \n \n if submodule_search_locations is _POPULATE:\n \n if hasattr(loader,'is_package'):\n try :\n is_package=loader.is_package(name)\n except ImportError:\n pass\n else :\n if is_package:\n spec.submodule_search_locations=[]\n else :\n spec.submodule_search_locations=submodule_search_locations\n if spec.submodule_search_locations ==[]:\n if location:\n dirname=_path_split(location)[0]\n spec.submodule_search_locations.append(dirname)\n \n return spec\n \n \n \n \nclass WindowsRegistryFinder:\n\n ''\n \n REGISTRY_KEY=(\n 'Software\\\\Python\\\\PythonCore\\\\{sys_version}'\n '\\\\Modules\\\\{fullname}')\n REGISTRY_KEY_DEBUG=(\n 'Software\\\\Python\\\\PythonCore\\\\{sys_version}'\n '\\\\Modules\\\\{fullname}\\\\Debug')\n DEBUG_BUILD=False\n \n @classmethod\n def _open_registry(cls,key):\n try :\n return _winreg.OpenKey(_winreg.HKEY_CURRENT_USER,key)\n except OSError:\n return _winreg.OpenKey(_winreg.HKEY_LOCAL_MACHINE,key)\n \n @classmethod\n def _search_registry(cls,fullname):\n if cls.DEBUG_BUILD:\n registry_key=cls.REGISTRY_KEY_DEBUG\n else :\n registry_key=cls.REGISTRY_KEY\n key=registry_key.format(fullname=fullname,\n sys_version='%d.%d'%sys.version_info[:2])\n try :\n with cls._open_registry(key)as hkey:\n filepath=_winreg.QueryValue(hkey,'')\n except OSError:\n return None\n return filepath\n \n @classmethod\n def find_spec(cls,fullname,path=None ,target=None ):\n filepath=cls._search_registry(fullname)\n if filepath is None :\n return None\n try :\n _path_stat(filepath)\n except OSError:\n return None\n for loader,suffixes in _get_supported_file_loaders():\n if filepath.endswith(tuple(suffixes)):\n spec=_bootstrap.spec_from_loader(fullname,\n loader(fullname,filepath),\n origin=filepath)\n return spec\n \n @classmethod\n def find_module(cls,fullname,path=None ):\n ''\n\n\n\n \n spec=cls.find_spec(fullname,path)\n if spec is not None :\n return spec.loader\n else :\n return None\n \n \nclass _LoaderBasics:\n\n ''\n \n \n def is_package(self,fullname):\n ''\n \n filename=_path_split(self.get_filename(fullname))[1]\n filename_base=filename.rsplit('.',1)[0]\n tail_name=fullname.rpartition('.')[2]\n return filename_base =='__init__'and tail_name !='__init__'\n \n def create_module(self,spec):\n ''\n \n def exec_module(self,module):\n ''\n code=self.get_code(module.__name__)\n if code is None :\n raise ImportError('cannot load module {!r} when get_code() '\n 'returns None'.format(module.__name__))\n _bootstrap._call_with_frames_removed(exec,code,module.__dict__)\n \n def load_module(self,fullname):\n ''\n return _bootstrap._load_module_shim(self,fullname)\n \n \nclass SourceLoader(_LoaderBasics):\n\n def path_mtime(self,path):\n ''\n\n\n\n \n raise OSError\n \n def path_stats(self,path):\n ''\n\n\n\n\n\n\n\n\n \n return {'mtime':self.path_mtime(path)}\n \n def _cache_bytecode(self,source_path,cache_path,data):\n ''\n\n\n\n\n \n \n return self.set_data(cache_path,data)\n \n def set_data(self,path,data):\n ''\n\n\n \n \n \n def get_source(self,fullname):\n ''\n path=self.get_filename(fullname)\n try :\n source_bytes=self.get_data(path)\n except OSError as exc:\n raise ImportError('source not available through get_data()',\n name=fullname)from exc\n return decode_source(source_bytes)\n \n def source_to_code(self,data,path,*,_optimize=-1):\n ''\n\n\n \n return _bootstrap._call_with_frames_removed(compile,data,path,'exec',\n dont_inherit=True ,optimize=_optimize)\n \n def get_code(self,fullname):\n ''\n\n\n\n\n \n source_path=self.get_filename(fullname)\n source_mtime=None\n source_bytes=None\n source_hash=None\n hash_based=False\n check_source=True\n try :\n bytecode_path=cache_from_source(source_path)\n except NotImplementedError:\n bytecode_path=None\n else :\n try :\n st=self.path_stats(source_path)\n except OSError:\n pass\n else :\n source_mtime=int(st['mtime'])\n try :\n data=self.get_data(bytecode_path)\n except OSError:\n pass\n else :\n exc_details={\n 'name':fullname,\n 'path':bytecode_path,\n }\n try :\n flags=_classify_pyc(data,fullname,exc_details)\n bytes_data=memoryview(data)[16:]\n hash_based=flags&0b1 !=0\n if hash_based:\n check_source=flags&0b10 !=0\n if (_imp.check_hash_based_pycs !='never'and\n (check_source or\n _imp.check_hash_based_pycs =='always')):\n source_bytes=self.get_data(source_path)\n source_hash=_imp.source_hash(\n _RAW_MAGIC_NUMBER,\n source_bytes,\n )\n _validate_hash_pyc(data,source_hash,fullname,\n exc_details)\n else :\n _validate_timestamp_pyc(\n data,\n source_mtime,\n st['size'],\n fullname,\n exc_details,\n )\n except (ImportError,EOFError):\n pass\n else :\n _bootstrap._verbose_message('{} matches {}',bytecode_path,\n source_path)\n return _compile_bytecode(bytes_data,name=fullname,\n bytecode_path=bytecode_path,\n source_path=source_path)\n if source_bytes is None :\n source_bytes=self.get_data(source_path)\n code_object=self.source_to_code(source_bytes,source_path)\n _bootstrap._verbose_message('code object from {}',source_path)\n if (not sys.dont_write_bytecode and bytecode_path is not None and\n source_mtime is not None ):\n if hash_based:\n if source_hash is None :\n source_hash=_imp.source_hash(source_bytes)\n data=_code_to_hash_pyc(code_object,source_hash,check_source)\n else :\n data=_code_to_timestamp_pyc(code_object,source_mtime,\n len(source_bytes))\n try :\n self._cache_bytecode(source_path,bytecode_path,data)\n _bootstrap._verbose_message('wrote {!r}',bytecode_path)\n except NotImplementedError:\n pass\n return code_object\n \n \nclass FileLoader:\n\n ''\n \n \n def __init__(self,fullname,path):\n ''\n \n self.name=fullname\n self.path=path\n \n def __eq__(self,other):\n return (self.__class__ ==other.__class__ and\n self.__dict__ ==other.__dict__)\n \n def __hash__(self):\n return hash(self.name)^hash(self.path)\n \n @_check_name\n def load_module(self,fullname):\n ''\n\n\n\n \n \n \n \n return super(FileLoader,self).load_module(fullname)\n \n @_check_name\n def get_filename(self,fullname):\n ''\n return self.path\n \n def get_data(self,path):\n ''\n with _io.FileIO(path,'r')as file:\n return file.read()\n \n \n \n @_check_name\n def get_resource_reader(self,module):\n if self.is_package(module):\n return self\n return None\n \n def open_resource(self,resource):\n path=_path_join(_path_split(self.path)[0],resource)\n return _io.FileIO(path,'r')\n \n def resource_path(self,resource):\n if not self.is_resource(resource):\n raise FileNotFoundError\n path=_path_join(_path_split(self.path)[0],resource)\n return path\n \n def is_resource(self,name):\n if path_sep in name:\n return False\n path=_path_join(_path_split(self.path)[0],name)\n return _path_isfile(path)\n \n def contents(self):\n return iter(_os.listdir(_path_split(self.path)[0]))\n \n \nclass SourceFileLoader(FileLoader,SourceLoader):\n\n ''\n \n def path_stats(self,path):\n ''\n st=_path_stat(path)\n return {'mtime':st.st_mtime,'size':st.st_size}\n \n def _cache_bytecode(self,source_path,bytecode_path,data):\n \n mode=_calc_mode(source_path)\n return self.set_data(bytecode_path,data,_mode=mode)\n \n def set_data(self,path,data,*,_mode=0o666):\n ''\n parent,filename=_path_split(path)\n path_parts=[]\n \n while parent and not _path_isdir(parent):\n parent,part=_path_split(parent)\n path_parts.append(part)\n \n for part in reversed(path_parts):\n parent=_path_join(parent,part)\n try :\n _os.mkdir(parent)\n except FileExistsError:\n \n continue\n except OSError as exc:\n \n \n _bootstrap._verbose_message('could not create {!r}: {!r}',\n parent,exc)\n return\n try :\n _write_atomic(path,data,_mode)\n _bootstrap._verbose_message('created {!r}',path)\n except OSError as exc:\n \n _bootstrap._verbose_message('could not create {!r}: {!r}',path,\n exc)\n \n \nclass SourcelessFileLoader(FileLoader,_LoaderBasics):\n\n ''\n \n def get_code(self,fullname):\n path=self.get_filename(fullname)\n data=self.get_data(path)\n \n \n exc_details={\n 'name':fullname,\n 'path':path,\n }\n _classify_pyc(data,fullname,exc_details)\n return _compile_bytecode(\n memoryview(data)[16:],\n name=fullname,\n bytecode_path=path,\n )\n \n def get_source(self,fullname):\n ''\n return None\n \n \n \nEXTENSION_SUFFIXES=[]\n\n\nclass ExtensionFileLoader(FileLoader,_LoaderBasics):\n\n ''\n\n\n\n \n \n def __init__(self,name,path):\n self.name=name\n self.path=path\n \n def __eq__(self,other):\n return (self.__class__ ==other.__class__ and\n self.__dict__ ==other.__dict__)\n \n def __hash__(self):\n return hash(self.name)^hash(self.path)\n \n def create_module(self,spec):\n ''\n module=_bootstrap._call_with_frames_removed(\n _imp.create_dynamic,spec)\n _bootstrap._verbose_message('extension module {!r} loaded from {!r}',\n spec.name,self.path)\n return module\n \n def exec_module(self,module):\n ''\n _bootstrap._call_with_frames_removed(_imp.exec_dynamic,module)\n _bootstrap._verbose_message('extension module {!r} executed from {!r}',\n self.name,self.path)\n \n def is_package(self,fullname):\n ''\n file_name=_path_split(self.path)[1]\n return any(file_name =='__init__'+suffix\n for suffix in EXTENSION_SUFFIXES)\n \n def get_code(self,fullname):\n ''\n return None\n \n def get_source(self,fullname):\n ''\n return None\n \n @_check_name\n def get_filename(self,fullname):\n ''\n return self.path\n \n \nclass _NamespacePath:\n ''\n\n\n\n \n \n def __init__(self,name,path,path_finder):\n self._name=name\n self._path=path\n self._last_parent_path=tuple(self._get_parent_path())\n self._path_finder=path_finder\n \n def _find_parent_path_names(self):\n ''\n parent,dot,me=self._name.rpartition('.')\n if dot =='':\n \n return 'sys','path'\n \n \n return parent,'__path__'\n \n def _get_parent_path(self):\n parent_module_name,path_attr_name=self._find_parent_path_names()\n return getattr(sys.modules[parent_module_name],path_attr_name)\n \n def _recalculate(self):\n \n parent_path=tuple(self._get_parent_path())\n if parent_path !=self._last_parent_path:\n spec=self._path_finder(self._name,parent_path)\n \n \n if spec is not None and spec.loader is None :\n if spec.submodule_search_locations:\n self._path=spec.submodule_search_locations\n self._last_parent_path=parent_path\n return self._path\n \n def __iter__(self):\n return iter(self._recalculate())\n \n def __setitem__(self,index,path):\n self._path[index]=path\n \n def __len__(self):\n return len(self._recalculate())\n \n def __repr__(self):\n return '_NamespacePath({!r})'.format(self._path)\n \n def __contains__(self,item):\n return item in self._recalculate()\n \n def append(self,item):\n self._path.append(item)\n \n \n \nclass _NamespaceLoader:\n def __init__(self,name,path,path_finder):\n self._path=_NamespacePath(name,path,path_finder)\n \n @classmethod\n def module_repr(cls,module):\n ''\n\n\n\n \n return '<module {!r} (namespace)>'.format(module.__name__)\n \n def is_package(self,fullname):\n return True\n \n def get_source(self,fullname):\n return ''\n \n def get_code(self,fullname):\n return compile('','<string>','exec',dont_inherit=True )\n \n def create_module(self,spec):\n ''\n \n def exec_module(self,module):\n pass\n \n def load_module(self,fullname):\n ''\n\n\n\n \n \n _bootstrap._verbose_message('namespace module loaded with path {!r}',\n self._path)\n return _bootstrap._load_module_shim(self,fullname)\n \n \n \n \nclass PathFinder:\n\n ''\n \n @classmethod\n def invalidate_caches(cls):\n ''\n \n for name,finder in list(sys.path_importer_cache.items()):\n if finder is None :\n del sys.path_importer_cache[name]\n elif hasattr(finder,'invalidate_caches'):\n finder.invalidate_caches()\n \n @classmethod\n def _path_hooks(cls,path):\n ''\n if sys.path_hooks is not None and not sys.path_hooks:\n _warnings.warn('sys.path_hooks is empty',ImportWarning)\n for hook in sys.path_hooks:\n try :\n return hook(path)\n except ImportError:\n continue\n else :\n return None\n \n @classmethod\n def _path_importer_cache(cls,path):\n ''\n\n\n\n\n \n if path =='':\n try :\n path=_os.getcwd()\n except FileNotFoundError:\n \n \n return None\n try :\n finder=sys.path_importer_cache[path]\n except KeyError:\n finder=cls._path_hooks(path)\n sys.path_importer_cache[path]=finder\n return finder\n \n @classmethod\n def _legacy_get_spec(cls,fullname,finder):\n \n \n if hasattr(finder,'find_loader'):\n loader,portions=finder.find_loader(fullname)\n else :\n loader=finder.find_module(fullname)\n portions=[]\n if loader is not None :\n return _bootstrap.spec_from_loader(fullname,loader)\n spec=_bootstrap.ModuleSpec(fullname,None )\n spec.submodule_search_locations=portions\n return spec\n \n @classmethod\n def _get_spec(cls,fullname,path,target=None ):\n ''\n \n \n namespace_path=[]\n for entry in path:\n if not isinstance(entry,(str,bytes)):\n continue\n finder=cls._path_importer_cache(entry)\n if finder is not None :\n if hasattr(finder,'find_spec'):\n spec=finder.find_spec(fullname,target)\n else :\n spec=cls._legacy_get_spec(fullname,finder)\n if spec is None :\n continue\n if spec.loader is not None :\n return spec\n portions=spec.submodule_search_locations\n if portions is None :\n raise ImportError('spec missing loader')\n \n \n \n \n namespace_path.extend(portions)\n else :\n spec=_bootstrap.ModuleSpec(fullname,None )\n spec.submodule_search_locations=namespace_path\n return spec\n \n @classmethod\n def find_spec(cls,fullname,path=None ,target=None ):\n ''\n\n\n \n if path is None :\n path=sys.path\n spec=cls._get_spec(fullname,path,target)\n if spec is None :\n return None\n elif spec.loader is None :\n namespace_path=spec.submodule_search_locations\n if namespace_path:\n \n \n spec.origin=None\n spec.submodule_search_locations=_NamespacePath(fullname,namespace_path,cls._get_spec)\n return spec\n else :\n return None\n else :\n return spec\n \n @classmethod\n def find_module(cls,fullname,path=None ):\n ''\n\n\n\n\n \n spec=cls.find_spec(fullname,path)\n if spec is None :\n return None\n return spec.loader\n \n \nclass FileFinder:\n\n ''\n\n\n\n\n \n \n def __init__(self,path,*loader_details):\n ''\n\n \n loaders=[]\n for loader,suffixes in loader_details:\n loaders.extend((suffix,loader)for suffix in suffixes)\n self._loaders=loaders\n \n self.path=path or '.'\n self._path_mtime=-1\n self._path_cache=set()\n self._relaxed_path_cache=set()\n \n def invalidate_caches(self):\n ''\n self._path_mtime=-1\n \n find_module=_find_module_shim\n \n def find_loader(self,fullname):\n ''\n\n\n\n\n \n spec=self.find_spec(fullname)\n if spec is None :\n return None ,[]\n return spec.loader,spec.submodule_search_locations or []\n \n def _get_spec(self,loader_class,fullname,path,smsl,target):\n loader=loader_class(fullname,path)\n return spec_from_file_location(fullname,path,loader=loader,\n submodule_search_locations=smsl)\n \n def find_spec(self,fullname,target=None ):\n ''\n\n\n \n is_namespace=False\n tail_module=fullname.rpartition('.')[2]\n try :\n mtime=_path_stat(self.path or _os.getcwd()).st_mtime\n except OSError:\n mtime=-1\n if mtime !=self._path_mtime:\n self._fill_cache()\n self._path_mtime=mtime\n \n if _relax_case():\n cache=self._relaxed_path_cache\n cache_module=tail_module.lower()\n else :\n cache=self._path_cache\n cache_module=tail_module\n \n if cache_module in cache:\n base_path=_path_join(self.path,tail_module)\n for suffix,loader_class in self._loaders:\n init_filename='__init__'+suffix\n full_path=_path_join(base_path,init_filename)\n if _path_isfile(full_path):\n return self._get_spec(loader_class,fullname,full_path,[base_path],target)\n else :\n \n \n is_namespace=_path_isdir(base_path)\n \n for suffix,loader_class in self._loaders:\n full_path=_path_join(self.path,tail_module+suffix)\n _bootstrap._verbose_message('trying {}',full_path,verbosity=2)\n if cache_module+suffix in cache:\n if _path_isfile(full_path):\n return self._get_spec(loader_class,fullname,full_path,\n None ,target)\n if is_namespace:\n _bootstrap._verbose_message('possible namespace for {}',base_path)\n spec=_bootstrap.ModuleSpec(fullname,None )\n spec.submodule_search_locations=[base_path]\n return spec\n return None\n \n def _fill_cache(self):\n ''\n path=self.path\n try :\n contents=_os.listdir(path or _os.getcwd())\n except (FileNotFoundError,PermissionError,NotADirectoryError):\n \n \n contents=[]\n \n \n if not sys.platform.startswith('win'):\n self._path_cache=set(contents)\n else :\n \n \n \n \n \n lower_suffix_contents=set()\n for item in contents:\n name,dot,suffix=item.partition('.')\n if dot:\n new_name='{}.{}'.format(name,suffix.lower())\n else :\n new_name=name\n lower_suffix_contents.add(new_name)\n self._path_cache=lower_suffix_contents\n if sys.platform.startswith(_CASE_INSENSITIVE_PLATFORMS):\n self._relaxed_path_cache={fn.lower()for fn in contents}\n \n @classmethod\n def path_hook(cls,*loader_details):\n ''\n\n\n\n\n\n\n \n def path_hook_for_FileFinder(path):\n ''\n if not _path_isdir(path):\n raise ImportError('only directories are supported',path=path)\n return cls(path,*loader_details)\n \n return path_hook_for_FileFinder\n \n def __repr__(self):\n return 'FileFinder({!r})'.format(self.path)\n \n \n \n \ndef _fix_up_module(ns,name,pathname,cpathname=None ):\n\n loader=ns.get('__loader__')\n spec=ns.get('__spec__')\n if not loader:\n if spec:\n loader=spec.loader\n elif pathname ==cpathname:\n loader=SourcelessFileLoader(name,pathname)\n else :\n loader=SourceFileLoader(name,pathname)\n if not spec:\n spec=spec_from_file_location(name,pathname,loader=loader)\n try :\n ns['__spec__']=spec\n ns['__loader__']=loader\n ns['__file__']=pathname\n ns['__cached__']=cpathname\n except Exception:\n \n pass\n \n \ndef _get_supported_file_loaders():\n ''\n\n\n \n extensions=ExtensionFileLoader,_imp.extension_suffixes()\n source=SourceFileLoader,SOURCE_SUFFIXES\n bytecode=SourcelessFileLoader,BYTECODE_SUFFIXES\n return [extensions,source,bytecode]\n \n \ndef _setup(_bootstrap_module):\n ''\n\n\n\n\n \n global sys,_imp,_bootstrap\n _bootstrap=_bootstrap_module\n sys=_bootstrap.sys\n _imp=_bootstrap._imp\n \n \n self_module=sys.modules[__name__]\n \n \n for builtin_name in ('_warnings','builtins','marshal'):\n if builtin_name not in sys.modules:\n builtin_module=_bootstrap._builtin_from_name(builtin_name)\n else :\n builtin_module=sys.modules[builtin_name]\n setattr(self_module,builtin_name,builtin_module)\n \n \n os_details=('posix',['/']),('nt',['\\\\','/'])\n for builtin_os,path_separators in os_details:\n \n assert all(len(sep)==1 for sep in path_separators)\n path_sep=path_separators[0]\n if builtin_os in sys.modules:\n os_module=sys.modules[builtin_os]\n break\n else :\n try :\n os_module=_bootstrap._builtin_from_name(builtin_os)\n break\n except ImportError:\n continue\n else :\n raise ImportError('importlib requires posix or nt')\n setattr(self_module,'_os',os_module)\n setattr(self_module,'path_sep',path_sep)\n setattr(self_module,'path_separators',''.join(path_separators))\n \n \n \n \n import _thread\n setattr(self_module,'_thread',_thread)\n \n \n \n \n import _weakref\n setattr(self_module,'_weakref',_weakref)\n \n \n if builtin_os =='nt':\n winreg_module=_bootstrap._builtin_from_name('winreg')\n setattr(self_module,'_winreg',winreg_module)\n \n \n setattr(self_module,'_relax_case',_make_relax_case())\n EXTENSION_SUFFIXES.extend(_imp.extension_suffixes())\n if builtin_os =='nt':\n SOURCE_SUFFIXES.append('.pyw')\n if '_d.pyd'in EXTENSION_SUFFIXES:\n WindowsRegistryFinder.DEBUG_BUILD=True\n \n \ndef _install(_bootstrap_module):\n ''\n _setup(_bootstrap_module)\n supported_loaders=_get_supported_file_loaders()\n sys.path_hooks.extend([FileFinder.path_hook(*supported_loaders)])\n sys.meta_path.append(PathFinder)\n", ["_thread", "_weakref", "tokenize"]], "email.utils": [".py", "\n\n\n\n\"\"\"Miscellaneous utilities.\"\"\"\n\n__all__=[\n'collapse_rfc2231_value',\n'decode_params',\n'decode_rfc2231',\n'encode_rfc2231',\n'formataddr',\n'formatdate',\n'format_datetime',\n'getaddresses',\n'make_msgid',\n'mktime_tz',\n'parseaddr',\n'parsedate',\n'parsedate_tz',\n'parsedate_to_datetime',\n'unquote',\n]\n\nimport os\nimport re\nimport time\nimport random\nimport socket\nimport datetime\nimport urllib.parse\n\nfrom email._parseaddr import quote\nfrom email._parseaddr import AddressList as _AddressList\nfrom email._parseaddr import mktime_tz\n\nfrom email._parseaddr import parsedate,parsedate_tz,_parsedate_tz\n\n\nfrom email.charset import Charset\n\nCOMMASPACE=', '\nEMPTYSTRING=''\nUEMPTYSTRING=''\nCRLF='\\r\\n'\nTICK=\"'\"\n\nspecialsre=re.compile(r'[][\\\\()<>@,:;\".]')\nescapesre=re.compile(r'[\\\\\"]')\n\ndef _has_surrogates(s):\n ''\n \n \n \n try :\n s.encode()\n return False\n except UnicodeEncodeError:\n return True\n \n \n \ndef _sanitize(string):\n\n\n\n\n original_bytes=string.encode('utf-8','surrogateescape')\n return original_bytes.decode('utf-8','replace')\n \n \n \n \n \ndef formataddr(pair,charset='utf-8'):\n ''\n\n\n\n\n\n\n\n\n\n\n \n name,address=pair\n \n address.encode('ascii')\n if name:\n try :\n name.encode('ascii')\n except UnicodeEncodeError:\n if isinstance(charset,str):\n charset=Charset(charset)\n encoded_name=charset.header_encode(name)\n return \"%s <%s>\"%(encoded_name,address)\n else :\n quotes=''\n if specialsre.search(name):\n quotes='\"'\n name=escapesre.sub(r'\\\\\\g<0>',name)\n return '%s%s%s <%s>'%(quotes,name,quotes,address)\n return address\n \n \n \ndef getaddresses(fieldvalues):\n ''\n all=COMMASPACE.join(fieldvalues)\n a=_AddressList(all)\n return a.addresslist\n \n \ndef _format_timetuple_and_zone(timetuple,zone):\n return '%s, %02d %s %04d %02d:%02d:%02d %s'%(\n ['Mon','Tue','Wed','Thu','Fri','Sat','Sun'][timetuple[6]],\n timetuple[2],\n ['Jan','Feb','Mar','Apr','May','Jun',\n 'Jul','Aug','Sep','Oct','Nov','Dec'][timetuple[1]-1],\n timetuple[0],timetuple[3],timetuple[4],timetuple[5],\n zone)\n \ndef formatdate(timeval=None ,localtime=False ,usegmt=False ):\n ''\n\n\n\n\n\n\n\n\n\n\n\n\n\n \n \n \n if timeval is None :\n timeval=time.time()\n if localtime or usegmt:\n dt=datetime.datetime.fromtimestamp(timeval,datetime.timezone.utc)\n else :\n dt=datetime.datetime.utcfromtimestamp(timeval)\n if localtime:\n dt=dt.astimezone()\n usegmt=False\n return format_datetime(dt,usegmt)\n \ndef format_datetime(dt,usegmt=False ):\n ''\n\n\n\n\n \n now=dt.timetuple()\n if usegmt:\n if dt.tzinfo is None or dt.tzinfo !=datetime.timezone.utc:\n raise ValueError(\"usegmt option requires a UTC datetime\")\n zone='GMT'\n elif dt.tzinfo is None :\n zone='-0000'\n else :\n zone=dt.strftime(\"%z\")\n return _format_timetuple_and_zone(now,zone)\n \n \ndef make_msgid(idstring=None ,domain=None ):\n ''\n\n\n\n\n\n\n\n \n timeval=int(time.time()*100)\n pid=os.getpid()\n randint=random.getrandbits(64)\n if idstring is None :\n idstring=''\n else :\n idstring='.'+idstring\n if domain is None :\n domain=socket.getfqdn()\n msgid='<%d.%d.%d%s@%s>'%(timeval,pid,randint,idstring,domain)\n return msgid\n \n \ndef parsedate_to_datetime(data):\n *dtuple,tz=_parsedate_tz(data)\n if tz is None :\n return datetime.datetime(*dtuple[:6])\n return datetime.datetime(*dtuple[:6],\n tzinfo=datetime.timezone(datetime.timedelta(seconds=tz)))\n \n \ndef parseaddr(addr):\n ''\n\n\n\n\n \n addrs=_AddressList(addr).addresslist\n if not addrs:\n return '',''\n return addrs[0]\n \n \n \ndef unquote(str):\n ''\n if len(str)>1:\n if str.startswith('\"')and str.endswith('\"'):\n return str[1:-1].replace('\\\\\\\\','\\\\').replace('\\\\\"','\"')\n if str.startswith('<')and str.endswith('>'):\n return str[1:-1]\n return str\n \n \n \n \ndef decode_rfc2231(s):\n ''\n parts=s.split(TICK,2)\n if len(parts)<=2:\n return None ,None ,s\n return parts\n \n \ndef encode_rfc2231(s,charset=None ,language=None ):\n ''\n\n\n\n\n \n s=urllib.parse.quote(s,safe='',encoding=charset or 'ascii')\n if charset is None and language is None :\n return s\n if language is None :\n language=''\n return \"%s'%s'%s\"%(charset,language,s)\n \n \nrfc2231_continuation=re.compile(r'^(?P<name>\\w+)\\*((?P<num>[0-9]+)\\*?)?$',\nre.ASCII)\n\ndef decode_params(params):\n ''\n\n\n \n \n params=params[:]\n new_params=[]\n \n \n \n rfc2231_params={}\n name,value=params.pop(0)\n new_params.append((name,value))\n while params:\n name,value=params.pop(0)\n if name.endswith('*'):\n encoded=True\n else :\n encoded=False\n value=unquote(value)\n mo=rfc2231_continuation.match(name)\n if mo:\n name,num=mo.group('name','num')\n if num is not None :\n num=int(num)\n rfc2231_params.setdefault(name,[]).append((num,value,encoded))\n else :\n new_params.append((name,'\"%s\"'%quote(value)))\n if rfc2231_params:\n for name,continuations in rfc2231_params.items():\n value=[]\n extended=False\n \n continuations.sort()\n \n \n \n \n \n for num,s,encoded in continuations:\n if encoded:\n \n \n \n s=urllib.parse.unquote(s,encoding=\"latin-1\")\n extended=True\n value.append(s)\n value=quote(EMPTYSTRING.join(value))\n if extended:\n charset,language,value=decode_rfc2231(value)\n new_params.append((name,(charset,language,'\"%s\"'%value)))\n else :\n new_params.append((name,'\"%s\"'%value))\n return new_params\n \ndef collapse_rfc2231_value(value,errors='replace',\nfallback_charset='us-ascii'):\n if not isinstance(value,tuple)or len(value)!=3:\n return unquote(value)\n \n \n \n charset,language,text=value\n if charset is None :\n \n \n charset=fallback_charset\n rawbytes=bytes(text,'raw-unicode-escape')\n try :\n return str(rawbytes,charset,errors)\n except LookupError:\n \n return unquote(text)\n \n \n \n \n \n \n \n \ndef localtime(dt=None ,isdst=-1):\n ''\n\n\n\n\n\n\n\n\n\n\n\n \n if dt is None :\n return datetime.datetime.now(datetime.timezone.utc).astimezone()\n if dt.tzinfo is not None :\n return dt.astimezone()\n \n \n \n tm=dt.timetuple()[:-1]+(isdst,)\n seconds=time.mktime(tm)\n localtm=time.localtime(seconds)\n try :\n delta=datetime.timedelta(seconds=localtm.tm_gmtoff)\n tz=datetime.timezone(delta,localtm.tm_zone)\n except AttributeError:\n \n \n delta=dt -datetime.datetime(*time.gmtime(seconds)[:6])\n dst=time.daylight and localtm.tm_isdst >0\n gmtoff=-(time.altzone if dst else time.timezone)\n if delta ==datetime.timedelta(seconds=gmtoff):\n tz=datetime.timezone(delta,time.tzname[dst])\n else :\n tz=datetime.timezone(delta)\n return dt.replace(tzinfo=tz)\n", ["datetime", "email._parseaddr", "email.charset", "os", "random", "re", "socket", "time", "urllib.parse"]], "sre_parse": [".py", "\n\n\n\n\n\n\n\n\n\n\"\"\"Internal support module for sre\"\"\"\n\n\n\nfrom sre_constants import *\n\nSPECIAL_CHARS=\".\\\\[{()*+?^$|\"\nREPEAT_CHARS=\"*+?{\"\n\nDIGITS=frozenset(\"0123456789\")\n\nOCTDIGITS=frozenset(\"01234567\")\nHEXDIGITS=frozenset(\"0123456789abcdefABCDEF\")\nASCIILETTERS=frozenset(\"abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ\")\n\nWHITESPACE=frozenset(\" \\t\\n\\r\\v\\f\")\n\n_REPEATCODES=frozenset({MIN_REPEAT,MAX_REPEAT})\n_UNITCODES=frozenset({ANY,RANGE,IN,LITERAL,NOT_LITERAL,CATEGORY})\n\nESCAPES={\nr\"\\a\":(LITERAL,ord(\"\\a\")),\nr\"\\b\":(LITERAL,ord(\"\\b\")),\nr\"\\f\":(LITERAL,ord(\"\\f\")),\nr\"\\n\":(LITERAL,ord(\"\\n\")),\nr\"\\r\":(LITERAL,ord(\"\\r\")),\nr\"\\t\":(LITERAL,ord(\"\\t\")),\nr\"\\v\":(LITERAL,ord(\"\\v\")),\nr\"\\\\\":(LITERAL,ord(\"\\\\\"))\n}\n\nCATEGORIES={\nr\"\\A\":(AT,AT_BEGINNING_STRING),\nr\"\\b\":(AT,AT_BOUNDARY),\nr\"\\B\":(AT,AT_NON_BOUNDARY),\nr\"\\d\":(IN,[(CATEGORY,CATEGORY_DIGIT)]),\nr\"\\D\":(IN,[(CATEGORY,CATEGORY_NOT_DIGIT)]),\nr\"\\s\":(IN,[(CATEGORY,CATEGORY_SPACE)]),\nr\"\\S\":(IN,[(CATEGORY,CATEGORY_NOT_SPACE)]),\nr\"\\w\":(IN,[(CATEGORY,CATEGORY_WORD)]),\nr\"\\W\":(IN,[(CATEGORY,CATEGORY_NOT_WORD)]),\nr\"\\Z\":(AT,AT_END_STRING),\n}\n\nFLAGS={\n\n\"i\":SRE_FLAG_IGNORECASE,\n\"L\":SRE_FLAG_LOCALE,\n\"m\":SRE_FLAG_MULTILINE,\n\"s\":SRE_FLAG_DOTALL,\n\"x\":SRE_FLAG_VERBOSE,\n\n\"a\":SRE_FLAG_ASCII,\n\"t\":SRE_FLAG_TEMPLATE,\n\"u\":SRE_FLAG_UNICODE,\n}\n\nTYPE_FLAGS=SRE_FLAG_ASCII |SRE_FLAG_LOCALE |SRE_FLAG_UNICODE\nGLOBAL_FLAGS=SRE_FLAG_DEBUG |SRE_FLAG_TEMPLATE\n\nclass Verbose(Exception):\n pass\n \nclass Pattern:\n\n def __init__(self):\n self.flags=0\n self.groupdict={}\n self.groupwidths=[None ]\n self.lookbehindgroups=None\n @property\n def groups(self):\n return len(self.groupwidths)\n def opengroup(self,name=None ):\n gid=self.groups\n self.groupwidths.append(None )\n if self.groups >MAXGROUPS:\n raise error(\"too many groups\")\n if name is not None :\n ogid=self.groupdict.get(name,None )\n if ogid is not None :\n raise error(\"redefinition of group name %r as group %d; \"\n \"was group %d\"%(name,gid,ogid))\n self.groupdict[name]=gid\n return gid\n def closegroup(self,gid,p):\n self.groupwidths[gid]=p.getwidth()\n def checkgroup(self,gid):\n return gid <self.groups and self.groupwidths[gid]is not None\n \n def checklookbehindgroup(self,gid,source):\n if self.lookbehindgroups is not None :\n if not self.checkgroup(gid):\n raise source.error('cannot refer to an open group')\n if gid >=self.lookbehindgroups:\n raise source.error('cannot refer to group defined in the same '\n 'lookbehind subpattern')\n \nclass SubPattern:\n\n def __init__(self,pattern,data=None ):\n self.pattern=pattern\n if data is None :\n data=[]\n self.data=data\n self.width=None\n \n def dump(self,level=0):\n nl=True\n seqtypes=(tuple,list)\n for op,av in self.data:\n print(level *\" \"+str(op),end='')\n if op is IN:\n \n print()\n for op,a in av:\n print((level+1)*\" \"+str(op),a)\n elif op is BRANCH:\n print()\n for i,a in enumerate(av[1]):\n if i:\n print(level *\" \"+\"OR\")\n a.dump(level+1)\n elif op is GROUPREF_EXISTS:\n condgroup,item_yes,item_no=av\n print('',condgroup)\n item_yes.dump(level+1)\n if item_no:\n print(level *\" \"+\"ELSE\")\n item_no.dump(level+1)\n elif isinstance(av,seqtypes):\n nl=False\n for a in av:\n if isinstance(a,SubPattern):\n if not nl:\n print()\n a.dump(level+1)\n nl=True\n else :\n if not nl:\n print(' ',end='')\n print(a,end='')\n nl=False\n if not nl:\n print()\n else :\n print('',av)\n def __repr__(self):\n return repr(self.data)\n def __len__(self):\n return len(self.data)\n def __delitem__(self,index):\n del self.data[index]\n def __getitem__(self,index):\n if isinstance(index,slice):\n return SubPattern(self.pattern,self.data[index])\n return self.data[index]\n def __setitem__(self,index,code):\n self.data[index]=code\n def insert(self,index,code):\n self.data.insert(index,code)\n def append(self,code):\n self.data.append(code)\n def getwidth(self):\n \n if self.width is not None :\n return self.width\n lo=hi=0\n for op,av in self.data:\n if op is BRANCH:\n i=MAXREPEAT -1\n j=0\n for av in av[1]:\n l,h=av.getwidth()\n i=min(i,l)\n j=max(j,h)\n lo=lo+i\n hi=hi+j\n elif op is CALL:\n i,j=av.getwidth()\n lo=lo+i\n hi=hi+j\n elif op is SUBPATTERN:\n i,j=av[-1].getwidth()\n lo=lo+i\n hi=hi+j\n elif op in _REPEATCODES:\n i,j=av[2].getwidth()\n lo=lo+i *av[0]\n hi=hi+j *av[1]\n elif op in _UNITCODES:\n lo=lo+1\n hi=hi+1\n elif op is GROUPREF:\n i,j=self.pattern.groupwidths[av]\n lo=lo+i\n hi=hi+j\n elif op is GROUPREF_EXISTS:\n i,j=av[1].getwidth()\n if av[2]is not None :\n l,h=av[2].getwidth()\n i=min(i,l)\n j=max(j,h)\n else :\n i=0\n lo=lo+i\n hi=hi+j\n elif op is SUCCESS:\n break\n self.width=min(lo,MAXREPEAT -1),min(hi,MAXREPEAT)\n return self.width\n \nclass Tokenizer:\n def __init__(self,string):\n self.istext=isinstance(string,str)\n self.string=string\n if not self.istext:\n string=str(string,'latin1')\n self.decoded_string=string\n self.index=0\n self.next=None\n self.__next()\n def __next(self):\n index=self.index\n try :\n char=self.decoded_string[index]\n except IndexError:\n self.next=None\n return\n if char ==\"\\\\\":\n index +=1\n try :\n char +=self.decoded_string[index]\n except IndexError:\n raise error(\"bad escape (end of pattern)\",\n self.string,len(self.string)-1)from None\n self.index=index+1\n self.next=char\n def match(self,char):\n if char ==self.next:\n self.__next()\n return True\n return False\n def get(self):\n this=self.next\n self.__next()\n return this\n def getwhile(self,n,charset):\n result=''\n for _ in range(n):\n c=self.next\n if c not in charset:\n break\n result +=c\n self.__next()\n return result\n def getuntil(self,terminator):\n result=''\n while True :\n c=self.next\n self.__next()\n if c is None :\n if not result:\n raise self.error(\"missing group name\")\n raise self.error(\"missing %s, unterminated name\"%terminator,\n len(result))\n if c ==terminator:\n if not result:\n raise self.error(\"missing group name\",1)\n break\n result +=c\n return result\n @property\n def pos(self):\n return self.index -len(self.next or '')\n def tell(self):\n return self.index -len(self.next or '')\n def seek(self,index):\n self.index=index\n self.__next()\n \n def error(self,msg,offset=0):\n return error(msg,self.string,self.tell()-offset)\n \ndef _class_escape(source,escape):\n\n code=ESCAPES.get(escape)\n if code:\n return code\n code=CATEGORIES.get(escape)\n if code and code[0]is IN:\n return code\n try :\n c=escape[1:2]\n if c ==\"x\":\n \n escape +=source.getwhile(2,HEXDIGITS)\n if len(escape)!=4:\n raise source.error(\"incomplete escape %s\"%escape,len(escape))\n return LITERAL,int(escape[2:],16)\n elif c ==\"u\"and source.istext:\n \n escape +=source.getwhile(4,HEXDIGITS)\n if len(escape)!=6:\n raise source.error(\"incomplete escape %s\"%escape,len(escape))\n return LITERAL,int(escape[2:],16)\n elif c ==\"U\"and source.istext:\n \n escape +=source.getwhile(8,HEXDIGITS)\n if len(escape)!=10:\n raise source.error(\"incomplete escape %s\"%escape,len(escape))\n c=int(escape[2:],16)\n chr(c)\n return LITERAL,c\n elif c in OCTDIGITS:\n \n escape +=source.getwhile(2,OCTDIGITS)\n c=int(escape[1:],8)\n if c >0o377:\n raise source.error('octal escape value %s outside of '\n 'range 0-0o377'%escape,len(escape))\n return LITERAL,c\n elif c in DIGITS:\n raise ValueError\n if len(escape)==2:\n if c in ASCIILETTERS:\n raise source.error('bad escape %s'%escape,len(escape))\n return LITERAL,ord(escape[1])\n except ValueError:\n pass\n raise source.error(\"bad escape %s\"%escape,len(escape))\n \ndef _escape(source,escape,state):\n\n code=CATEGORIES.get(escape)\n if code:\n return code\n code=ESCAPES.get(escape)\n if code:\n return code\n try :\n c=escape[1:2]\n if c ==\"x\":\n \n escape +=source.getwhile(2,HEXDIGITS)\n if len(escape)!=4:\n raise source.error(\"incomplete escape %s\"%escape,len(escape))\n return LITERAL,int(escape[2:],16)\n elif c ==\"u\"and source.istext:\n \n escape +=source.getwhile(4,HEXDIGITS)\n if len(escape)!=6:\n raise source.error(\"incomplete escape %s\"%escape,len(escape))\n return LITERAL,int(escape[2:],16)\n elif c ==\"U\"and source.istext:\n \n escape +=source.getwhile(8,HEXDIGITS)\n if len(escape)!=10:\n raise source.error(\"incomplete escape %s\"%escape,len(escape))\n c=int(escape[2:],16)\n chr(c)\n return LITERAL,c\n elif c ==\"0\":\n \n escape +=source.getwhile(2,OCTDIGITS)\n return LITERAL,int(escape[1:],8)\n elif c in DIGITS:\n \n if source.next in DIGITS:\n escape +=source.get()\n if (escape[1]in OCTDIGITS and escape[2]in OCTDIGITS and\n source.next in OCTDIGITS):\n \n escape +=source.get()\n c=int(escape[1:],8)\n if c >0o377:\n raise source.error('octal escape value %s outside of '\n 'range 0-0o377'%escape,\n len(escape))\n return LITERAL,c\n \n group=int(escape[1:])\n if group <state.groups:\n if not state.checkgroup(group):\n raise source.error(\"cannot refer to an open group\",\n len(escape))\n state.checklookbehindgroup(group,source)\n return GROUPREF,group\n raise source.error(\"invalid group reference %d\"%group,len(escape)-1)\n if len(escape)==2:\n if c in ASCIILETTERS:\n raise source.error(\"bad escape %s\"%escape,len(escape))\n return LITERAL,ord(escape[1])\n except ValueError:\n pass\n raise source.error(\"bad escape %s\"%escape,len(escape))\n \ndef _uniq(items):\n if len(set(items))==len(items):\n return items\n newitems=[]\n for item in items:\n if item not in newitems:\n newitems.append(item)\n return newitems\n \ndef _parse_sub(source,state,verbose,nested):\n\n\n items=[]\n itemsappend=items.append\n sourcematch=source.match\n start=source.tell()\n while True :\n itemsappend(_parse(source,state,verbose,nested+1,\n not nested and not items))\n if not sourcematch(\"|\"):\n break\n \n if len(items)==1:\n return items[0]\n \n subpattern=SubPattern(state)\n \n \n while True :\n prefix=None\n for item in items:\n if not item:\n break\n if prefix is None :\n prefix=item[0]\n elif item[0]!=prefix:\n break\n else :\n \n \n for item in items:\n del item[0]\n subpattern.append(prefix)\n continue\n break\n \n \n set=[]\n for item in items:\n if len(item)!=1:\n break\n op,av=item[0]\n if op is LITERAL:\n set.append((op,av))\n elif op is IN and av[0][0]is not NEGATE:\n set.extend(av)\n else :\n break\n else :\n \n \n subpattern.append((IN,_uniq(set)))\n return subpattern\n \n subpattern.append((BRANCH,(None ,items)))\n return subpattern\n \ndef _parse(source,state,verbose,nested,first=False ):\n\n subpattern=SubPattern(state)\n \n \n subpatternappend=subpattern.append\n sourceget=source.get\n sourcematch=source.match\n _len=len\n _ord=ord\n \n while True :\n \n this=source.next\n if this is None :\n break\n if this in \"|)\":\n break\n sourceget()\n \n if verbose:\n \n if this in WHITESPACE:\n continue\n if this ==\"#\":\n while True :\n this=sourceget()\n if this is None or this ==\"\\n\":\n break\n continue\n \n if this[0]==\"\\\\\":\n code=_escape(source,this,state)\n subpatternappend(code)\n \n elif this not in SPECIAL_CHARS:\n subpatternappend((LITERAL,_ord(this)))\n \n elif this ==\"[\":\n here=source.tell()-1\n \n set=[]\n setappend=set.append\n \n \n if source.next =='[':\n import warnings\n warnings.warn(\n 'Possible nested set at position %d'%source.tell(),\n FutureWarning,stacklevel=nested+6\n )\n negate=sourcematch(\"^\")\n \n while True :\n this=sourceget()\n if this is None :\n raise source.error(\"unterminated character set\",\n source.tell()-here)\n if this ==\"]\"and set:\n break\n elif this[0]==\"\\\\\":\n code1=_class_escape(source,this)\n else :\n if set and this in '-&~|'and source.next ==this:\n import warnings\n warnings.warn(\n 'Possible set %s at position %d'%(\n 'difference'if this =='-'else\n 'intersection'if this =='&'else\n 'symmetric difference'if this =='~'else\n 'union',\n source.tell()-1),\n FutureWarning,stacklevel=nested+6\n )\n code1=LITERAL,_ord(this)\n if sourcematch(\"-\"):\n \n that=sourceget()\n if that is None :\n raise source.error(\"unterminated character set\",\n source.tell()-here)\n if that ==\"]\":\n if code1[0]is IN:\n code1=code1[1][0]\n setappend(code1)\n setappend((LITERAL,_ord(\"-\")))\n break\n if that[0]==\"\\\\\":\n code2=_class_escape(source,that)\n else :\n if that =='-':\n import warnings\n warnings.warn(\n 'Possible set difference at position %d'%(\n source.tell()-2),\n FutureWarning,stacklevel=nested+6\n )\n code2=LITERAL,_ord(that)\n if code1[0]!=LITERAL or code2[0]!=LITERAL:\n msg=\"bad character range %s-%s\"%(this,that)\n raise source.error(msg,len(this)+1+len(that))\n lo=code1[1]\n hi=code2[1]\n if hi <lo:\n msg=\"bad character range %s-%s\"%(this,that)\n raise source.error(msg,len(this)+1+len(that))\n setappend((RANGE,(lo,hi)))\n else :\n if code1[0]is IN:\n code1=code1[1][0]\n setappend(code1)\n \n set=_uniq(set)\n \n if _len(set)==1 and set[0][0]is LITERAL:\n \n if negate:\n subpatternappend((NOT_LITERAL,set[0][1]))\n else :\n subpatternappend(set[0])\n else :\n if negate:\n set.insert(0,(NEGATE,None ))\n \n \n subpatternappend((IN,set))\n \n elif this in REPEAT_CHARS:\n \n here=source.tell()\n if this ==\"?\":\n min,max=0,1\n elif this ==\"*\":\n min,max=0,MAXREPEAT\n \n elif this ==\"+\":\n min,max=1,MAXREPEAT\n elif this ==\"{\":\n if source.next ==\"}\":\n subpatternappend((LITERAL,_ord(this)))\n continue\n \n min,max=0,MAXREPEAT\n lo=hi=\"\"\n while source.next in DIGITS:\n lo +=sourceget()\n if sourcematch(\",\"):\n while source.next in DIGITS:\n hi +=sourceget()\n else :\n hi=lo\n if not sourcematch(\"}\"):\n subpatternappend((LITERAL,_ord(this)))\n source.seek(here)\n continue\n \n if lo:\n min=int(lo)\n if min >=MAXREPEAT:\n raise OverflowError(\"the repetition number is too large\")\n if hi:\n max=int(hi)\n if max >=MAXREPEAT:\n raise OverflowError(\"the repetition number is too large\")\n if max <min:\n raise source.error(\"min repeat greater than max repeat\",\n source.tell()-here)\n else :\n raise AssertionError(\"unsupported quantifier %r\"%(char,))\n \n if subpattern:\n item=subpattern[-1:]\n else :\n item=None\n if not item or item[0][0]is AT:\n raise source.error(\"nothing to repeat\",\n source.tell()-here+len(this))\n if item[0][0]in _REPEATCODES:\n raise source.error(\"multiple repeat\",\n source.tell()-here+len(this))\n if item[0][0]is SUBPATTERN:\n group,add_flags,del_flags,p=item[0][1]\n if group is None and not add_flags and not del_flags:\n item=p\n if sourcematch(\"?\"):\n subpattern[-1]=(MIN_REPEAT,(min,max,item))\n else :\n subpattern[-1]=(MAX_REPEAT,(min,max,item))\n \n elif this ==\".\":\n subpatternappend((ANY,None ))\n \n elif this ==\"(\":\n start=source.tell()-1\n group=True\n name=None\n add_flags=0\n del_flags=0\n if sourcematch(\"?\"):\n \n char=sourceget()\n if char is None :\n raise source.error(\"unexpected end of pattern\")\n if char ==\"P\":\n \n if sourcematch(\"<\"):\n \n name=source.getuntil(\">\")\n if not name.isidentifier():\n msg=\"bad character in group name %r\"%name\n raise source.error(msg,len(name)+1)\n elif sourcematch(\"=\"):\n \n name=source.getuntil(\")\")\n if not name.isidentifier():\n msg=\"bad character in group name %r\"%name\n raise source.error(msg,len(name)+1)\n gid=state.groupdict.get(name)\n if gid is None :\n msg=\"unknown group name %r\"%name\n raise source.error(msg,len(name)+1)\n if not state.checkgroup(gid):\n raise source.error(\"cannot refer to an open group\",\n len(name)+1)\n state.checklookbehindgroup(gid,source)\n subpatternappend((GROUPREF,gid))\n continue\n \n else :\n char=sourceget()\n if char is None :\n raise source.error(\"unexpected end of pattern\")\n raise source.error(\"unknown extension ?P\"+char,\n len(char)+2)\n elif char ==\":\":\n \n group=None\n elif char ==\"#\":\n \n while True :\n if source.next is None :\n raise source.error(\"missing ), unterminated comment\",\n source.tell()-start)\n if sourceget()==\")\":\n break\n continue\n \n elif char in \"=!<\":\n \n dir=1\n if char ==\"<\":\n char=sourceget()\n if char is None :\n raise source.error(\"unexpected end of pattern\")\n if char not in \"=!\":\n raise source.error(\"unknown extension ?<\"+char,\n len(char)+2)\n dir=-1\n lookbehindgroups=state.lookbehindgroups\n if lookbehindgroups is None :\n state.lookbehindgroups=state.groups\n p=_parse_sub(source,state,verbose,nested+1)\n if dir <0:\n if lookbehindgroups is None :\n state.lookbehindgroups=None\n if not sourcematch(\")\"):\n raise source.error(\"missing ), unterminated subpattern\",\n source.tell()-start)\n if char ==\"=\":\n subpatternappend((ASSERT,(dir,p)))\n else :\n subpatternappend((ASSERT_NOT,(dir,p)))\n continue\n \n elif char ==\"(\":\n \n condname=source.getuntil(\")\")\n if condname.isidentifier():\n condgroup=state.groupdict.get(condname)\n if condgroup is None :\n msg=\"unknown group name %r\"%condname\n raise source.error(msg,len(condname)+1)\n else :\n try :\n condgroup=int(condname)\n if condgroup <0:\n raise ValueError\n except ValueError:\n msg=\"bad character in group name %r\"%condname\n raise source.error(msg,len(condname)+1)from None\n if not condgroup:\n raise source.error(\"bad group number\",\n len(condname)+1)\n if condgroup >=MAXGROUPS:\n msg=\"invalid group reference %d\"%condgroup\n raise source.error(msg,len(condname)+1)\n state.checklookbehindgroup(condgroup,source)\n item_yes=_parse(source,state,verbose,nested+1)\n if source.match(\"|\"):\n item_no=_parse(source,state,verbose,nested+1)\n if source.next ==\"|\":\n raise source.error(\"conditional backref with more than two branches\")\n else :\n item_no=None\n if not source.match(\")\"):\n raise source.error(\"missing ), unterminated subpattern\",\n source.tell()-start)\n subpatternappend((GROUPREF_EXISTS,(condgroup,item_yes,item_no)))\n continue\n \n elif char in FLAGS or char ==\"-\":\n \n flags=_parse_flags(source,state,char)\n if flags is None :\n if not first or subpattern:\n import warnings\n warnings.warn(\n 'Flags not at the start of the expression %r%s'%(\n source.string[:20],\n ' (truncated)'if len(source.string)>20 else '',\n ),\n DeprecationWarning,stacklevel=nested+6\n )\n if (state.flags&SRE_FLAG_VERBOSE)and not verbose:\n raise Verbose\n continue\n \n add_flags,del_flags=flags\n group=None\n else :\n raise source.error(\"unknown extension ?\"+char,\n len(char)+1)\n \n \n if group is not None :\n try :\n group=state.opengroup(name)\n except error as err:\n raise source.error(err.msg,len(name)+1)from None\n sub_verbose=((verbose or (add_flags&SRE_FLAG_VERBOSE))and\n not (del_flags&SRE_FLAG_VERBOSE))\n p=_parse_sub(source,state,sub_verbose,nested+1)\n if not source.match(\")\"):\n raise source.error(\"missing ), unterminated subpattern\",\n source.tell()-start)\n if group is not None :\n state.closegroup(group,p)\n subpatternappend((SUBPATTERN,(group,add_flags,del_flags,p)))\n \n elif this ==\"^\":\n subpatternappend((AT,AT_BEGINNING))\n \n elif this ==\"$\":\n subpatternappend((AT,AT_END))\n \n else :\n raise AssertionError(\"unsupported special character %r\"%(char,))\n \n \n for i in range(len(subpattern))[::-1]:\n op,av=subpattern[i]\n if op is SUBPATTERN:\n group,add_flags,del_flags,p=av\n if group is None and not add_flags and not del_flags:\n subpattern[i:i+1]=p\n \n return subpattern\n \ndef _parse_flags(source,state,char):\n sourceget=source.get\n add_flags=0\n del_flags=0\n if char !=\"-\":\n while True :\n flag=FLAGS[char]\n if source.istext:\n if char =='L':\n msg=\"bad inline flags: cannot use 'L' flag with a str pattern\"\n raise source.error(msg)\n else :\n if char =='u':\n msg=\"bad inline flags: cannot use 'u' flag with a bytes pattern\"\n raise source.error(msg)\n add_flags |=flag\n if (flag&TYPE_FLAGS)and (add_flags&TYPE_FLAGS)!=flag:\n msg=\"bad inline flags: flags 'a', 'u' and 'L' are incompatible\"\n raise source.error(msg)\n char=sourceget()\n if char is None :\n raise source.error(\"missing -, : or )\")\n if char in \")-:\":\n break\n if char not in FLAGS:\n msg=\"unknown flag\"if char.isalpha()else \"missing -, : or )\"\n raise source.error(msg,len(char))\n if char ==\")\":\n state.flags |=add_flags\n return None\n if add_flags&GLOBAL_FLAGS:\n raise source.error(\"bad inline flags: cannot turn on global flag\",1)\n if char ==\"-\":\n char=sourceget()\n if char is None :\n raise source.error(\"missing flag\")\n if char not in FLAGS:\n msg=\"unknown flag\"if char.isalpha()else \"missing flag\"\n raise source.error(msg,len(char))\n while True :\n flag=FLAGS[char]\n if flag&TYPE_FLAGS:\n msg=\"bad inline flags: cannot turn off flags 'a', 'u' and 'L'\"\n raise source.error(msg)\n del_flags |=flag\n char=sourceget()\n if char is None :\n raise source.error(\"missing :\")\n if char ==\":\":\n break\n if char not in FLAGS:\n msg=\"unknown flag\"if char.isalpha()else \"missing :\"\n raise source.error(msg,len(char))\n assert char ==\":\"\n if del_flags&GLOBAL_FLAGS:\n raise source.error(\"bad inline flags: cannot turn off global flag\",1)\n if add_flags&del_flags:\n raise source.error(\"bad inline flags: flag turned on and off\",1)\n return add_flags,del_flags\n \ndef fix_flags(src,flags):\n\n if isinstance(src,str):\n if flags&SRE_FLAG_LOCALE:\n raise ValueError(\"cannot use LOCALE flag with a str pattern\")\n if not flags&SRE_FLAG_ASCII:\n flags |=SRE_FLAG_UNICODE\n elif flags&SRE_FLAG_UNICODE:\n raise ValueError(\"ASCII and UNICODE flags are incompatible\")\n else :\n if flags&SRE_FLAG_UNICODE:\n raise ValueError(\"cannot use UNICODE flag with a bytes pattern\")\n if flags&SRE_FLAG_LOCALE and flags&SRE_FLAG_ASCII:\n raise ValueError(\"ASCII and LOCALE flags are incompatible\")\n return flags\n \ndef parse(str,flags=0,pattern=None ):\n\n\n source=Tokenizer(str)\n \n if pattern is None :\n pattern=Pattern()\n pattern.flags=flags\n pattern.str=str\n \n try :\n p=_parse_sub(source,pattern,flags&SRE_FLAG_VERBOSE,0)\n except Verbose:\n \n \n pattern=Pattern()\n pattern.flags=flags |SRE_FLAG_VERBOSE\n pattern.str=str\n source.seek(0)\n p=_parse_sub(source,pattern,True ,0)\n \n p.pattern.flags=fix_flags(str,p.pattern.flags)\n \n if source.next is not None :\n assert source.next ==\")\"\n raise source.error(\"unbalanced parenthesis\")\n \n if flags&SRE_FLAG_DEBUG:\n p.dump()\n \n return p\n \ndef parse_template(source,pattern):\n\n\n s=Tokenizer(source)\n sget=s.get\n groups=[]\n literals=[]\n literal=[]\n lappend=literal.append\n def addgroup(index,pos):\n if index >pattern.groups:\n raise s.error(\"invalid group reference %d\"%index,pos)\n if literal:\n literals.append(''.join(literal))\n del literal[:]\n groups.append((len(literals),index))\n literals.append(None )\n groupindex=pattern.groupindex\n while True :\n this=sget()\n if this is None :\n break\n if this[0]==\"\\\\\":\n \n c=this[1]\n if c ==\"g\":\n name=\"\"\n if not s.match(\"<\"):\n raise s.error(\"missing <\")\n name=s.getuntil(\">\")\n if name.isidentifier():\n try :\n index=groupindex[name]\n except KeyError:\n raise IndexError(\"unknown group name %r\"%name)\n else :\n try :\n index=int(name)\n if index <0:\n raise ValueError\n except ValueError:\n raise s.error(\"bad character in group name %r\"%name,\n len(name)+1)from None\n if index >=MAXGROUPS:\n raise s.error(\"invalid group reference %d\"%index,\n len(name)+1)\n addgroup(index,len(name)+1)\n elif c ==\"0\":\n if s.next in OCTDIGITS:\n this +=sget()\n if s.next in OCTDIGITS:\n this +=sget()\n lappend(chr(int(this[1:],8)&0xff))\n elif c in DIGITS:\n isoctal=False\n if s.next in DIGITS:\n this +=sget()\n if (c in OCTDIGITS and this[2]in OCTDIGITS and\n s.next in OCTDIGITS):\n this +=sget()\n isoctal=True\n c=int(this[1:],8)\n if c >0o377:\n raise s.error('octal escape value %s outside of '\n 'range 0-0o377'%this,len(this))\n lappend(chr(c))\n if not isoctal:\n addgroup(int(this[1:]),len(this)-1)\n else :\n try :\n this=chr(ESCAPES[this][1])\n except KeyError:\n if c in ASCIILETTERS:\n raise s.error('bad escape %s'%this,len(this))\n lappend(this)\n else :\n lappend(this)\n if literal:\n literals.append(''.join(literal))\n if not isinstance(source,str):\n \n \n literals=[None if s is None else s.encode('latin-1')for s in literals]\n return groups,literals\n \ndef expand_template(template,match):\n g=match.group\n empty=match.string[:0]\n groups,literals=template\n literals=literals[:]\n try :\n for index,group in groups:\n literals[index]=g(group)or empty\n except IndexError:\n raise error(\"invalid group reference %d\"%index)\n return empty.join(literals)\n", ["sre_constants", "warnings"]], "_functools": [".py", "from reprlib import recursive_repr\n\nclass partial:\n ''\n\n \n \n __slots__=\"func\",\"args\",\"keywords\",\"__dict__\",\"__weakref__\"\n \n def __new__(*args,**keywords):\n if not args:\n raise TypeError(\"descriptor '__new__' of partial needs an argument\")\n if len(args)<2:\n raise TypeError(\"type 'partial' takes at least one argument\")\n cls,func,*args=args\n if not callable(func):\n raise TypeError(\"the first argument must be callable\")\n args=tuple(args)\n \n if hasattr(func,\"func\"):\n args=func.args+args\n tmpkw=func.keywords.copy()\n tmpkw.update(keywords)\n keywords=tmpkw\n del tmpkw\n func=func.func\n \n self=super(partial,cls).__new__(cls)\n \n self.func=func\n self.args=args\n self.keywords=keywords\n return self\n \n def __call__(*args,**keywords):\n if not args:\n raise TypeError(\"descriptor '__call__' of partial needs an argument\")\n self,*args=args\n newkeywords=self.keywords.copy()\n newkeywords.update(keywords)\n return self.func(*self.args,*args,**newkeywords)\n \n @recursive_repr()\n def __repr__(self):\n qualname=type(self).__qualname__\n args=[repr(self.func)]\n args.extend(repr(x)for x in self.args)\n args.extend(f\"{k}={v!r}\"for (k,v)in self.keywords.items())\n if type(self).__module__ ==\"functools\":\n return f\"functools.{qualname}({', '.join(args)})\"\n return f\"{qualname}({', '.join(args)})\"\n \n def __reduce__(self):\n return type(self),(self.func,),(self.func,self.args,\n self.keywords or None ,self.__dict__ or None )\n \n def __setstate__(self,state):\n if not isinstance(state,tuple):\n raise TypeError(\"argument to __setstate__ must be a tuple\")\n if len(state)!=4:\n raise TypeError(f\"expected 4 items in state, got {len(state)}\")\n func,args,kwds,namespace=state\n if (not callable(func)or not isinstance(args,tuple)or\n (kwds is not None and not isinstance(kwds,dict))or\n (namespace is not None and not isinstance(namespace,dict))):\n raise TypeError(\"invalid partial state\")\n \n args=tuple(args)\n if kwds is None :\n kwds={}\n elif type(kwds)is not dict:\n kwds=dict(kwds)\n if namespace is None :\n namespace={}\n \n self.__dict__=namespace\n self.func=func\n self.args=args\n self.keywords=kwds\n \ndef reduce(func,iterable,initializer=None ):\n args=iter(iterable)\n if initializer is not None :\n res=initializer\n else :\n res=next(args)\n while True :\n try :\n res=func(res,next(args))\n except StopIteration:\n return res\n", ["reprlib"]], "email._policybase": [".py", "''\n\n\n\n\nimport abc\nfrom email import header\nfrom email import charset as _charset\nfrom email.utils import _has_surrogates\n\n__all__=[\n'Policy',\n'Compat32',\n'compat32',\n]\n\n\nclass _PolicyBase:\n\n ''\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n \n \n def __init__(self,**kw):\n ''\n\n\n\n \n for name,value in kw.items():\n if hasattr(self,name):\n super(_PolicyBase,self).__setattr__(name,value)\n else :\n raise TypeError(\n \"{!r} is an invalid keyword argument for {}\".format(\n name,self.__class__.__name__))\n \n def __repr__(self):\n args=[\"{}={!r}\".format(name,value)\n for name,value in self.__dict__.items()]\n return \"{}({})\".format(self.__class__.__name__,', '.join(args))\n \n def clone(self,**kw):\n ''\n\n\n\n\n \n newpolicy=self.__class__.__new__(self.__class__)\n for attr,value in self.__dict__.items():\n object.__setattr__(newpolicy,attr,value)\n for attr,value in kw.items():\n if not hasattr(self,attr):\n raise TypeError(\n \"{!r} is an invalid keyword argument for {}\".format(\n attr,self.__class__.__name__))\n object.__setattr__(newpolicy,attr,value)\n return newpolicy\n \n def __setattr__(self,name,value):\n if hasattr(self,name):\n msg=\"{!r} object attribute {!r} is read-only\"\n else :\n msg=\"{!r} object has no attribute {!r}\"\n raise AttributeError(msg.format(self.__class__.__name__,name))\n \n def __add__(self,other):\n ''\n\n\n\n \n return self.clone(**other.__dict__)\n \n \ndef _append_doc(doc,added_doc):\n doc=doc.rsplit('\\n',1)[0]\n added_doc=added_doc.split('\\n',1)[1]\n return doc+'\\n'+added_doc\n \ndef _extend_docstrings(cls):\n if cls.__doc__ and cls.__doc__.startswith('+'):\n cls.__doc__=_append_doc(cls.__bases__[0].__doc__,cls.__doc__)\n for name,attr in cls.__dict__.items():\n if attr.__doc__ and attr.__doc__.startswith('+'):\n for c in (c for base in cls.__bases__ for c in base.mro()):\n doc=getattr(getattr(c,name),'__doc__')\n if doc:\n attr.__doc__=_append_doc(doc,attr.__doc__)\n break\n return cls\n \n \nclass Policy(_PolicyBase,metaclass=abc.ABCMeta):\n\n ''\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n \n \n raise_on_defect=False\n linesep='\\n'\n cte_type='8bit'\n max_line_length=78\n mangle_from_=False\n message_factory=None\n \n def handle_defect(self,obj,defect):\n ''\n\n\n\n\n\n\n\n\n\n\n\n\n \n if self.raise_on_defect:\n raise defect\n self.register_defect(obj,defect)\n \n def register_defect(self,obj,defect):\n ''\n\n\n\n\n\n\n\n\n \n obj.defects.append(defect)\n \n def header_max_count(self,name):\n ''\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n \n return None\n \n @abc.abstractmethod\n def header_source_parse(self,sourcelines):\n ''\n\n\n\n\n \n raise NotImplementedError\n \n @abc.abstractmethod\n def header_store_parse(self,name,value):\n ''\n\n \n raise NotImplementedError\n \n @abc.abstractmethod\n def header_fetch_parse(self,name,value):\n ''\n\n\n\n\n\n \n raise NotImplementedError\n \n @abc.abstractmethod\n def fold(self,name,value):\n ''\n\n\n\n\n\n\n \n raise NotImplementedError\n \n @abc.abstractmethod\n def fold_binary(self,name,value):\n ''\n\n\n\n\n \n raise NotImplementedError\n \n \n@_extend_docstrings\nclass Compat32(Policy):\n\n ''\n\n\n \n \n mangle_from_=True\n \n def _sanitize_header(self,name,value):\n \n \n if not isinstance(value,str):\n \n return value\n if _has_surrogates(value):\n return header.Header(value,charset=_charset.UNKNOWN8BIT,\n header_name=name)\n else :\n return value\n \n def header_source_parse(self,sourcelines):\n ''\n\n\n\n\n\n \n name,value=sourcelines[0].split(':',1)\n value=value.lstrip(' \\t')+''.join(sourcelines[1:])\n return (name,value.rstrip('\\r\\n'))\n \n def header_store_parse(self,name,value):\n ''\n\n \n return (name,value)\n \n def header_fetch_parse(self,name,value):\n ''\n\n\n \n return self._sanitize_header(name,value)\n \n def fold(self,name,value):\n ''\n\n\n\n\n\n \n return self._fold(name,value,sanitize=True )\n \n def fold_binary(self,name,value):\n ''\n\n\n\n\n\n\n \n folded=self._fold(name,value,sanitize=self.cte_type =='7bit')\n return folded.encode('ascii','surrogateescape')\n \n def _fold(self,name,value,sanitize):\n parts=[]\n parts.append('%s: '%name)\n if isinstance(value,str):\n if _has_surrogates(value):\n if sanitize:\n h=header.Header(value,\n charset=_charset.UNKNOWN8BIT,\n header_name=name)\n else :\n \n \n \n \n \n \n parts.append(value)\n h=None\n else :\n h=header.Header(value,header_name=name)\n else :\n \n h=value\n if h is not None :\n \n \n maxlinelen=0\n if self.max_line_length is not None :\n maxlinelen=self.max_line_length\n parts.append(h.encode(linesep=self.linesep,maxlinelen=maxlinelen))\n parts.append(self.linesep)\n return ''.join(parts)\n \n \ncompat32=Compat32()\n", ["abc", "email", "email.charset", "email.header", "email.utils"]], "posixpath": [".py", "''\n\n\n\n\n\n\n\n\n\n\n\n\n\n\ncurdir='.'\npardir='..'\nextsep='.'\nsep='/'\npathsep=':'\ndefpath=':/bin:/usr/bin'\naltsep=None\ndevnull='/dev/null'\n\nimport os\nimport sys\nimport stat\nimport genericpath\nfrom genericpath import *\n\n__all__=[\"normcase\",\"isabs\",\"join\",\"splitdrive\",\"split\",\"splitext\",\n\"basename\",\"dirname\",\"commonprefix\",\"getsize\",\"getmtime\",\n\"getatime\",\"getctime\",\"islink\",\"exists\",\"lexists\",\"isdir\",\"isfile\",\n\"ismount\",\"expanduser\",\"expandvars\",\"normpath\",\"abspath\",\n\"samefile\",\"sameopenfile\",\"samestat\",\n\"curdir\",\"pardir\",\"sep\",\"pathsep\",\"defpath\",\"altsep\",\"extsep\",\n\"devnull\",\"realpath\",\"supports_unicode_filenames\",\"relpath\",\n\"commonpath\"]\n\n\ndef _get_sep(path):\n if isinstance(path,bytes):\n return b'/'\n else :\n return '/'\n \n \n \n \n \n \ndef normcase(s):\n ''\n s=os.fspath(s)\n if not isinstance(s,(bytes,str)):\n raise TypeError(\"normcase() argument must be str or bytes, \"\n \"not '{}'\".format(s.__class__.__name__))\n return s\n \n \n \n \n \ndef isabs(s):\n ''\n s=os.fspath(s)\n sep=_get_sep(s)\n return s.startswith(sep)\n \n \n \n \n \n \ndef join(a,*p):\n ''\n\n\n \n a=os.fspath(a)\n sep=_get_sep(a)\n path=a\n try :\n if not p:\n path[:0]+sep\n for b in map(os.fspath,p):\n if b.startswith(sep):\n path=b\n elif not path or path.endswith(sep):\n path +=b\n else :\n path +=sep+b\n except (TypeError,AttributeError,BytesWarning):\n genericpath._check_arg_types('join',a,*p)\n raise\n return path\n \n \n \n \n \n \n \ndef split(p):\n ''\n \n p=os.fspath(p)\n sep=_get_sep(p)\n i=p.rfind(sep)+1\n head,tail=p[:i],p[i:]\n if head and head !=sep *len(head):\n head=head.rstrip(sep)\n return head,tail\n \n \n \n \n \n \n \ndef splitext(p):\n p=os.fspath(p)\n if isinstance(p,bytes):\n sep=b'/'\n extsep=b'.'\n else :\n sep='/'\n extsep='.'\n return genericpath._splitext(p,sep,None ,extsep)\nsplitext.__doc__=genericpath._splitext.__doc__\n\n\n\n\ndef splitdrive(p):\n ''\n \n p=os.fspath(p)\n return p[:0],p\n \n \n \n \ndef basename(p):\n ''\n p=os.fspath(p)\n sep=_get_sep(p)\n i=p.rfind(sep)+1\n return p[i:]\n \n \n \n \ndef dirname(p):\n ''\n p=os.fspath(p)\n sep=_get_sep(p)\n i=p.rfind(sep)+1\n head=p[:i]\n if head and head !=sep *len(head):\n head=head.rstrip(sep)\n return head\n \n \n \n \n \ndef islink(path):\n ''\n try :\n st=os.lstat(path)\n except (OSError,AttributeError):\n return False\n return stat.S_ISLNK(st.st_mode)\n \n \n \ndef lexists(path):\n ''\n try :\n os.lstat(path)\n except OSError:\n return False\n return True\n \n \n \n \n \ndef ismount(path):\n ''\n try :\n s1=os.lstat(path)\n except OSError:\n \n return False\n else :\n \n if stat.S_ISLNK(s1.st_mode):\n return False\n \n if isinstance(path,bytes):\n parent=join(path,b'..')\n else :\n parent=join(path,'..')\n parent=realpath(parent)\n try :\n s2=os.lstat(parent)\n except OSError:\n return False\n \n dev1=s1.st_dev\n dev2=s2.st_dev\n if dev1 !=dev2:\n return True\n ino1=s1.st_ino\n ino2=s2.st_ino\n if ino1 ==ino2:\n return True\n return False\n \n \n \n \n \n \n \n \n \n \n \ndef expanduser(path):\n ''\n \n path=os.fspath(path)\n if isinstance(path,bytes):\n tilde=b'~'\n else :\n tilde='~'\n if not path.startswith(tilde):\n return path\n sep=_get_sep(path)\n i=path.find(sep,1)\n if i <0:\n i=len(path)\n if i ==1:\n if 'HOME'not in os.environ:\n import pwd\n userhome=pwd.getpwuid(os.getuid()).pw_dir\n else :\n userhome=os.environ['HOME']\n else :\n import pwd\n name=path[1:i]\n if isinstance(name,bytes):\n name=str(name,'ASCII')\n try :\n pwent=pwd.getpwnam(name)\n except KeyError:\n return path\n userhome=pwent.pw_dir\n if isinstance(path,bytes):\n userhome=os.fsencode(userhome)\n root=b'/'\n else :\n root='/'\n userhome=userhome.rstrip(root)\n return (userhome+path[i:])or root\n \n \n \n \n \n \n_varprog=None\n_varprogb=None\n\ndef expandvars(path):\n ''\n \n path=os.fspath(path)\n global _varprog,_varprogb\n if isinstance(path,bytes):\n if b'$'not in path:\n return path\n if not _varprogb:\n import re\n _varprogb=re.compile(br'\\$(\\w+|\\{[^}]*\\})',re.ASCII)\n search=_varprogb.search\n start=b'{'\n end=b'}'\n environ=getattr(os,'environb',None )\n else :\n if '$'not in path:\n return path\n if not _varprog:\n import re\n _varprog=re.compile(r'\\$(\\w+|\\{[^}]*\\})',re.ASCII)\n search=_varprog.search\n start='{'\n end='}'\n environ=os.environ\n i=0\n while True :\n m=search(path,i)\n if not m:\n break\n i,j=m.span(0)\n name=m.group(1)\n if name.startswith(start)and name.endswith(end):\n name=name[1:-1]\n try :\n if environ is None :\n value=os.fsencode(os.environ[os.fsdecode(name)])\n else :\n value=environ[name]\n except KeyError:\n i=j\n else :\n tail=path[j:]\n path=path[:i]+value\n i=len(path)\n path +=tail\n return path\n \n \n \n \n \n \ndef normpath(path):\n ''\n path=os.fspath(path)\n if isinstance(path,bytes):\n sep=b'/'\n empty=b''\n dot=b'.'\n dotdot=b'..'\n else :\n sep='/'\n empty=''\n dot='.'\n dotdot='..'\n if path ==empty:\n return dot\n initial_slashes=path.startswith(sep)\n \n \n if (initial_slashes and\n path.startswith(sep *2)and not path.startswith(sep *3)):\n initial_slashes=2\n comps=path.split(sep)\n new_comps=[]\n for comp in comps:\n if comp in (empty,dot):\n continue\n if (comp !=dotdot or (not initial_slashes and not new_comps)or\n (new_comps and new_comps[-1]==dotdot)):\n new_comps.append(comp)\n elif new_comps:\n new_comps.pop()\n comps=new_comps\n path=sep.join(comps)\n if initial_slashes:\n path=sep *initial_slashes+path\n return path or dot\n \n \ndef abspath(path):\n ''\n path=os.fspath(path)\n if not isabs(path):\n if isinstance(path,bytes):\n cwd=os.getcwdb()\n else :\n cwd=os.getcwd()\n path=join(cwd,path)\n return normpath(path)\n \n \n \n \n \ndef realpath(filename):\n ''\n \n filename=os.fspath(filename)\n path,ok=_joinrealpath(filename[:0],filename,{})\n return abspath(path)\n \n \n \ndef _joinrealpath(path,rest,seen):\n if isinstance(path,bytes):\n sep=b'/'\n curdir=b'.'\n pardir=b'..'\n else :\n sep='/'\n curdir='.'\n pardir='..'\n \n if isabs(rest):\n rest=rest[1:]\n path=sep\n \n while rest:\n name,_,rest=rest.partition(sep)\n if not name or name ==curdir:\n \n continue\n if name ==pardir:\n \n if path:\n path,name=split(path)\n if name ==pardir:\n path=join(path,pardir,pardir)\n else :\n path=pardir\n continue\n newpath=join(path,name)\n if not islink(newpath):\n path=newpath\n continue\n \n if newpath in seen:\n \n path=seen[newpath]\n if path is not None :\n \n continue\n \n \n return join(newpath,rest),False\n seen[newpath]=None\n path,ok=_joinrealpath(path,os.readlink(newpath),seen)\n if not ok:\n return join(path,rest),False\n seen[newpath]=path\n \n return path,True\n \n \nsupports_unicode_filenames=(sys.platform =='darwin')\n\ndef relpath(path,start=None ):\n ''\n \n if not path:\n raise ValueError(\"no path specified\")\n \n path=os.fspath(path)\n if isinstance(path,bytes):\n curdir=b'.'\n sep=b'/'\n pardir=b'..'\n else :\n curdir='.'\n sep='/'\n pardir='..'\n \n if start is None :\n start=curdir\n else :\n start=os.fspath(start)\n \n try :\n start_list=[x for x in abspath(start).split(sep)if x]\n path_list=[x for x in abspath(path).split(sep)if x]\n \n i=len(commonprefix([start_list,path_list]))\n \n rel_list=[pardir]*(len(start_list)-i)+path_list[i:]\n if not rel_list:\n return curdir\n return join(*rel_list)\n except (TypeError,AttributeError,BytesWarning,DeprecationWarning):\n genericpath._check_arg_types('relpath',path,start)\n raise\n \n \n \n \n \n \n \ndef commonpath(paths):\n ''\n \n if not paths:\n raise ValueError('commonpath() arg is an empty sequence')\n \n paths=tuple(map(os.fspath,paths))\n if isinstance(paths[0],bytes):\n sep=b'/'\n curdir=b'.'\n else :\n sep='/'\n curdir='.'\n \n try :\n split_paths=[path.split(sep)for path in paths]\n \n try :\n isabs,=set(p[:1]==sep for p in paths)\n except ValueError:\n raise ValueError(\"Can't mix absolute and relative paths\")from None\n \n split_paths=[[c for c in s if c and c !=curdir]for s in split_paths]\n s1=min(split_paths)\n s2=max(split_paths)\n common=s1\n for i,c in enumerate(s1):\n if c !=s2[i]:\n common=s1[:i]\n break\n \n prefix=sep if isabs else sep[:0]\n return prefix+sep.join(common)\n except (TypeError,AttributeError):\n genericpath._check_arg_types('commonpath',*paths)\n raise\n", ["genericpath", "os", "pwd", "re", "stat", "sys"]], "code": [".py", "''\n\n\n\n\n\n\nimport sys\nimport traceback\nfrom codeop import CommandCompiler,compile_command\n\n__all__=[\"InteractiveInterpreter\",\"InteractiveConsole\",\"interact\",\n\"compile_command\"]\n\nclass InteractiveInterpreter:\n ''\n\n\n\n\n\n \n \n def __init__(self,locals=None ):\n ''\n\n\n\n\n\n\n \n if locals is None :\n locals={\"__name__\":\"__console__\",\"__doc__\":None }\n self.locals=locals\n self.compile=CommandCompiler()\n \n def runsource(self,source,filename=\"<input>\",symbol=\"single\"):\n ''\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n \n try :\n code=self.compile(source,filename,symbol)\n except (OverflowError,SyntaxError,ValueError):\n \n self.showsyntaxerror(filename)\n return False\n \n if code is None :\n \n return True\n \n \n self.runcode(code)\n return False\n \n def runcode(self,code):\n ''\n\n\n\n\n\n\n\n\n\n \n try :\n exec(code,self.locals)\n except SystemExit:\n raise\n except :\n self.showtraceback()\n \n def showsyntaxerror(self,filename=None ):\n ''\n\n\n\n\n\n\n\n\n\n \n type,value,tb=sys.exc_info()\n sys.last_type=type\n sys.last_value=value\n sys.last_traceback=tb\n if filename and type is SyntaxError:\n \n try :\n msg,(dummy_filename,lineno,offset,line)=value.args\n except ValueError:\n \n pass\n else :\n \n value=SyntaxError(msg,(filename,lineno,offset,line))\n sys.last_value=value\n if sys.excepthook is sys.__excepthook__:\n lines=traceback.format_exception_only(type,value)\n self.write(''.join(lines))\n else :\n \n \n sys.excepthook(type,value,tb)\n \n def showtraceback(self):\n ''\n\n\n\n\n\n \n sys.last_type,sys.last_value,last_tb=ei=sys.exc_info()\n sys.last_traceback=last_tb\n try :\n lines=traceback.format_exception(ei[0],ei[1],last_tb.tb_next)\n if sys.excepthook is sys.__excepthook__:\n self.write(''.join(lines))\n else :\n \n \n sys.excepthook(ei[0],ei[1],last_tb)\n finally :\n last_tb=ei=None\n \n def write(self,data):\n ''\n\n\n\n\n \n sys.stderr.write(data)\n \n \nclass InteractiveConsole(InteractiveInterpreter):\n ''\n\n\n\n\n \n \n def __init__(self,locals=None ,filename=\"<console>\"):\n ''\n\n\n\n\n\n\n\n \n InteractiveInterpreter.__init__(self,locals)\n self.filename=filename\n self.resetbuffer()\n \n def resetbuffer(self):\n ''\n self.buffer=[]\n \n def interact(self,banner=None ,exitmsg=None ):\n ''\n\n\n\n\n\n\n\n\n\n\n\n\n\n \n try :\n sys.ps1\n except AttributeError:\n sys.ps1=\">>> \"\n try :\n sys.ps2\n except AttributeError:\n sys.ps2=\"... \"\n cprt='Type \"help\", \"copyright\", \"credits\" or \"license\" for more information.'\n if banner is None :\n self.write(\"Python %s on %s\\n%s\\n(%s)\\n\"%\n (sys.version,sys.platform,cprt,\n self.__class__.__name__))\n elif banner:\n self.write(\"%s\\n\"%str(banner))\n more=0\n while 1:\n try :\n if more:\n prompt=sys.ps2\n else :\n prompt=sys.ps1\n try :\n line=self.raw_input(prompt)\n except EOFError:\n self.write(\"\\n\")\n break\n else :\n more=self.push(line)\n except KeyboardInterrupt:\n self.write(\"\\nKeyboardInterrupt\\n\")\n self.resetbuffer()\n more=0\n if exitmsg is None :\n self.write('now exiting %s...\\n'%self.__class__.__name__)\n elif exitmsg !='':\n self.write('%s\\n'%exitmsg)\n \n def push(self,line):\n ''\n\n\n\n\n\n\n\n\n\n\n\n \n self.buffer.append(line)\n source=\"\\n\".join(self.buffer)\n more=self.runsource(source,self.filename)\n if not more:\n self.resetbuffer()\n return more\n \n def raw_input(self,prompt=\"\"):\n ''\n\n\n\n\n\n\n\n\n \n return input(prompt)\n \n \n \ndef interact(banner=None ,readfunc=None ,local=None ,exitmsg=None ):\n ''\n\n\n\n\n\n\n\n\n\n\n\n\n \n console=InteractiveConsole(local)\n if readfunc is not None :\n console.raw_input=readfunc\n else :\n try :\n import readline\n except ImportError:\n pass\n console.interact(banner,exitmsg)\n \n \nif __name__ ==\"__main__\":\n import argparse\n \n parser=argparse.ArgumentParser()\n parser.add_argument('-q',action='store_true',\n help=\"don't print version and copyright messages\")\n args=parser.parse_args()\n if args.q or sys.flags.quiet:\n banner=''\n else :\n banner=None\n interact(banner)\n", ["argparse", "codeop", "readline", "sys", "traceback"]], "genericpath": [".py", "''\n\n\n\n\nimport os\nimport stat\n\n__all__=['commonprefix','exists','getatime','getctime','getmtime',\n'getsize','isdir','isfile','samefile','sameopenfile',\n'samestat']\n\n\n\n\ndef exists(path):\n ''\n try :\n os.stat(path)\n except OSError:\n return False\n return True\n \n \n \n \ndef isfile(path):\n ''\n try :\n st=os.stat(path)\n except OSError:\n return False\n return stat.S_ISREG(st.st_mode)\n \n \n \n \n \ndef isdir(s):\n ''\n try :\n st=os.stat(s)\n except OSError:\n return False\n return stat.S_ISDIR(st.st_mode)\n \n \ndef getsize(filename):\n ''\n return os.stat(filename).st_size\n \n \ndef getmtime(filename):\n ''\n return os.stat(filename).st_mtime\n \n \ndef getatime(filename):\n ''\n return os.stat(filename).st_atime\n \n \ndef getctime(filename):\n ''\n return os.stat(filename).st_ctime\n \n \n \ndef commonprefix(m):\n ''\n if not m:return ''\n \n \n \n \n if not isinstance(m[0],(list,tuple)):\n m=tuple(map(os.fspath,m))\n s1=min(m)\n s2=max(m)\n for i,c in enumerate(s1):\n if c !=s2[i]:\n return s1[:i]\n return s1\n \n \n \ndef samestat(s1,s2):\n ''\n return (s1.st_ino ==s2.st_ino and\n s1.st_dev ==s2.st_dev)\n \n \n \ndef samefile(f1,f2):\n ''\n s1=os.stat(f1)\n s2=os.stat(f2)\n return samestat(s1,s2)\n \n \n \n \ndef sameopenfile(fp1,fp2):\n ''\n s1=os.fstat(fp1)\n s2=os.fstat(fp2)\n return samestat(s1,s2)\n \n \n \n \n \n \n \n \n \ndef _splitext(p,sep,altsep,extsep):\n ''\n\n\n \n \n \n sepIndex=p.rfind(sep)\n if altsep:\n altsepIndex=p.rfind(altsep)\n sepIndex=max(sepIndex,altsepIndex)\n \n dotIndex=p.rfind(extsep)\n if dotIndex >sepIndex:\n \n filenameIndex=sepIndex+1\n while filenameIndex <dotIndex:\n if p[filenameIndex:filenameIndex+1]!=extsep:\n return p[:dotIndex],p[dotIndex:]\n filenameIndex +=1\n \n return p,p[:0]\n \ndef _check_arg_types(funcname,*args):\n hasstr=hasbytes=False\n for s in args:\n if isinstance(s,str):\n hasstr=True\n elif isinstance(s,bytes):\n hasbytes=True\n else :\n raise TypeError('%s() argument must be str or bytes, not %r'%\n (funcname,s.__class__.__name__))from None\n if hasstr and hasbytes:\n raise TypeError(\"Can't mix strings and bytes in path components\")from None\n", ["os", "stat"]], "_codecs": [".py", "\ndef ascii_decode(*args,**kw):\n pass\n \ndef ascii_encode(*args,**kw):\n pass\n \ndef charbuffer_encode(*args,**kw):\n pass\n \ndef charmap_build(*args,**kw):\n pass\n \ndef charmap_decode(*args,**kw):\n pass\n \ndef charmap_encode(*args,**kw):\n pass\n \ndef decode(obj,encoding=\"utf-8\",errors=\"strict\"):\n ''\n\n\n\n\n\n \n return __BRYTHON__.decode(obj,encoding,errors)\n \ndef encode(obj,encoding=\"utf-8\",errors=\"strict\"):\n ''\n\n\n\n\n\n \n return __BRYTHON__.encode(obj,encoding,errors)\n \ndef escape_decode(*args,**kw):\n pass\n \ndef escape_encode(*args,**kw):\n pass\n \ndef latin_1_decode(*args,**kw):\n pass\n \ndef latin_1_encode(*args,**kw):\n pass\n \ndef lookup(encoding):\n ''\n\n \n if encoding in ('utf-8','utf_8'):\n from browser import console\n import encodings.utf_8\n return encodings.utf_8.getregentry()\n \n LookupError(encoding)\n \ndef lookup_error(*args,**kw):\n ''\n\n \n pass\n \ndef mbcs_decode(*args,**kw):\n pass\n \ndef mbcs_encode(*args,**kw):\n pass\n \ndef raw_unicode_escape_decode(*args,**kw):\n pass\n \ndef raw_unicode_escape_encode(*args,**kw):\n pass\n \ndef readbuffer_encode(*args,**kw):\n pass\n \ndef register(*args,**kw):\n ''\n\n\n\n \n pass\n \ndef register_error(*args,**kw):\n ''\n\n\n\n\n \n pass\n \ndef unicode_escape_decode(*args,**kw):\n pass\n \ndef unicode_escape_encode(*args,**kw):\n pass\n \ndef unicode_internal_decode(*args,**kw):\n pass\n \ndef unicode_internal_encode(*args,**kw):\n pass\n \ndef utf_16_be_decode(*args,**kw):\n pass\n \ndef utf_16_be_encode(*args,**kw):\n pass\n \ndef utf_16_decode(*args,**kw):\n pass\n \ndef utf_16_encode(*args,**kw):\n pass\n \ndef utf_16_ex_decode(*args,**kw):\n pass\n \ndef utf_16_le_decode(*args,**kw):\n pass\n \ndef utf_16_le_encode(*args,**kw):\n pass\n \ndef utf_32_be_decode(*args,**kw):\n pass\n \ndef utf_32_be_encode(*args,**kw):\n pass\n \ndef utf_32_decode(*args,**kw):\n pass\n \ndef utf_32_encode(*args,**kw):\n pass\n \ndef utf_32_ex_decode(*args,**kw):\n pass\n \ndef utf_32_le_decode(*args,**kw):\n pass\n \ndef utf_32_le_encode(*args,**kw):\n pass\n \ndef utf_7_decode(*args,**kw):\n pass\n \ndef utf_7_encode(*args,**kw):\n pass\n \ndef utf_8_decode(decoder,bytes_obj,errors,*args):\n return (bytes_obj.decode(\"utf-8\"),len(bytes_obj))\n \ndef utf_8_encode(*args,**kw):\n input=args[0]\n if len(args)==2:\n errors=args[1]\n else :\n errors=kw.get('errors','strict')\n \n \n return (bytes(input,'utf-8'),len(input))\n", ["browser", "encodings.utf_8"]], "reprlib": [".py", "''\n\n__all__=[\"Repr\",\"repr\",\"recursive_repr\"]\n\nimport builtins\nfrom itertools import islice\nfrom _thread import get_ident\n\ndef recursive_repr(fillvalue='...'):\n ''\n \n def decorating_function(user_function):\n repr_running=set()\n \n def wrapper(self):\n key=id(self),get_ident()\n if key in repr_running:\n return fillvalue\n repr_running.add(key)\n try :\n result=user_function(self)\n finally :\n repr_running.discard(key)\n return result\n \n \n wrapper.__module__=getattr(user_function,'__module__')\n wrapper.__doc__=getattr(user_function,'__doc__')\n wrapper.__name__=getattr(user_function,'__name__')\n wrapper.__qualname__=getattr(user_function,'__qualname__')\n wrapper.__annotations__=getattr(user_function,'__annotations__',{})\n return wrapper\n \n return decorating_function\n \nclass Repr:\n\n def __init__(self):\n self.maxlevel=6\n self.maxtuple=6\n self.maxlist=6\n self.maxarray=5\n self.maxdict=4\n self.maxset=6\n self.maxfrozenset=6\n self.maxdeque=6\n self.maxstring=30\n self.maxlong=40\n self.maxother=30\n \n def repr(self,x):\n return self.repr1(x,self.maxlevel)\n \n def repr1(self,x,level):\n typename=type(x).__name__\n if ' 'in typename:\n parts=typename.split()\n typename='_'.join(parts)\n if hasattr(self,'repr_'+typename):\n return getattr(self,'repr_'+typename)(x,level)\n else :\n return self.repr_instance(x,level)\n \n def _repr_iterable(self,x,level,left,right,maxiter,trail=''):\n n=len(x)\n if level <=0 and n:\n s='...'\n else :\n newlevel=level -1\n repr1=self.repr1\n pieces=[repr1(elem,newlevel)for elem in islice(x,maxiter)]\n if n >maxiter:pieces.append('...')\n s=', '.join(pieces)\n if n ==1 and trail:right=trail+right\n return '%s%s%s'%(left,s,right)\n \n def repr_tuple(self,x,level):\n return self._repr_iterable(x,level,'(',')',self.maxtuple,',')\n \n def repr_list(self,x,level):\n return self._repr_iterable(x,level,'[',']',self.maxlist)\n \n def repr_array(self,x,level):\n if not x:\n return \"array('%s')\"%x.typecode\n header=\"array('%s', [\"%x.typecode\n return self._repr_iterable(x,level,header,'])',self.maxarray)\n \n def repr_set(self,x,level):\n if not x:\n return 'set()'\n x=_possibly_sorted(x)\n return self._repr_iterable(x,level,'{','}',self.maxset)\n \n def repr_frozenset(self,x,level):\n if not x:\n return 'frozenset()'\n x=_possibly_sorted(x)\n return self._repr_iterable(x,level,'frozenset({','})',\n self.maxfrozenset)\n \n def repr_deque(self,x,level):\n return self._repr_iterable(x,level,'deque([','])',self.maxdeque)\n \n def repr_dict(self,x,level):\n n=len(x)\n if n ==0:return '{}'\n if level <=0:return '{...}'\n newlevel=level -1\n repr1=self.repr1\n pieces=[]\n for key in islice(_possibly_sorted(x),self.maxdict):\n keyrepr=repr1(key,newlevel)\n valrepr=repr1(x[key],newlevel)\n pieces.append('%s: %s'%(keyrepr,valrepr))\n if n >self.maxdict:pieces.append('...')\n s=', '.join(pieces)\n return '{%s}'%(s,)\n \n def repr_str(self,x,level):\n s=builtins.repr(x[:self.maxstring])\n if len(s)>self.maxstring:\n i=max(0,(self.maxstring -3)//2)\n j=max(0,self.maxstring -3 -i)\n s=builtins.repr(x[:i]+x[len(x)-j:])\n s=s[:i]+'...'+s[len(s)-j:]\n return s\n \n def repr_int(self,x,level):\n s=builtins.repr(x)\n if len(s)>self.maxlong:\n i=max(0,(self.maxlong -3)//2)\n j=max(0,self.maxlong -3 -i)\n s=s[:i]+'...'+s[len(s)-j:]\n return s\n \n def repr_instance(self,x,level):\n try :\n s=builtins.repr(x)\n \n \n except Exception:\n return '<%s instance at %#x>'%(x.__class__.__name__,id(x))\n if len(s)>self.maxother:\n i=max(0,(self.maxother -3)//2)\n j=max(0,self.maxother -3 -i)\n s=s[:i]+'...'+s[len(s)-j:]\n return s\n \n \ndef _possibly_sorted(x):\n\n\n\n try :\n return sorted(x)\n except Exception:\n return list(x)\n \naRepr=Repr()\nrepr=aRepr.repr\n", ["_thread", "builtins", "itertools"]], "browser.local_storage": [".py", "\nimport sys\nfrom browser import window,console\n\nhas_local_storage=hasattr(window,'localStorage')\n\nclass _UnProvided():\n pass\n \nclass LocalStorage():\n storage_type=\"local_storage\"\n \n def __init__(self):\n if not has_local_storage:\n raise EnvironmentError(\"LocalStorage not available\")\n self.store=window.localStorage\n \n def __delitem__(self,key):\n if (not isinstance(key,str)):\n raise TypeError(\"key must be string\")\n if key not in self:\n raise KeyError(key)\n self.store.removeItem(key)\n \n def __getitem__(self,key):\n if (not isinstance(key,str)):\n raise TypeError(\"key must be string\")\n res=self.store.getItem(key)\n if res is not None :\n return res\n raise KeyError(key)\n \n def __setitem__(self,key,value):\n if not isinstance(key,str):\n raise TypeError(\"key must be string\")\n if not isinstance(value,str):\n raise TypeError(\"value must be string\")\n self.store.setItem(key,value)\n \n \n def __contains__(self,key):\n if (not isinstance(key,str)):\n raise TypeError(\"key must be string\")\n res=self.store.getItem(key)\n if res is None :\n return False\n return True\n \n def __iter__(self):\n keys=self.keys()\n return keys.__iter__()\n \n def get(self,key,default=None ):\n if (not isinstance(key,str)):\n raise TypeError(\"key must be string\")\n return self.store.getItem(key)or default\n \n def pop(self,key,default=_UnProvided()):\n if (not isinstance(key,str)):\n raise TypeError(\"key must be string\")\n if type(default)is _UnProvided:\n ret=self.get(key)\n del self[key]\n return ret\n else :\n if key in self:\n ret=self.get(key)\n del self[key]\n return ret\n else :\n return default\n \n \n \n def keys(self):\n return [self.store.key(i)for i in range(self.store.length)]\n \n def values(self):\n return [self.__getitem__(k)for k in self.keys()]\n \n def items(self):\n return list(zip(self.keys(),self.values()))\n \n def clear(self):\n self.store.clear()\n \n def __len__(self):\n return self.store.length\n \nif has_local_storage:\n storage=LocalStorage()\n", ["browser", "sys"]], "platform": [".py", "''\n\n\n\nfrom browser import self as window\n\ndef architecture(*args,**kw):\n return \"<unknown>\",window.navigator.platform\n \ndef machine(*args,**kw):\n return ''\n \ndef node(*args,**kw):\n return ''\n \ndef platform(*args,**kw):\n return window.navigator.platform\n \ndef processor(*args,**kw):\n return ''\n \ndef python_build():\n return ('.'.join(map(str,__BRYTHON__.implementation[:-1])),\n __BRYTHON__.compiled_date)\n \ndef python_compiler():\n return ''\n \ndef python_branch():\n return ''\n \ndef python_implementation():\n return 'Brython'\n \ndef python_revision():\n return ''\n \ndef python_version():\n return '.'.join(map(str,__BRYTHON__.version_info[:3]))\n \ndef python_version_tuple():\n return __BRYTHON__.version_info[:3]\n \ndef release():\n return ''\n \ndef system():\n return window.navigator.platform\n \ndef system_alias(*args,**kw):\n return window.navigator.platform\n \ndef uname():\n from collections import namedtuple\n klass=namedtuple('uname_result',\n 'system node release version machine processor')\n return klass(window.navigator.platform,'','','','','')\n", ["browser", "collections"]], "doctest": [".py", "\n\n\n\n\n\n\n\nr\"\"\"Module doctest -- a framework for running examples in docstrings.\n\nIn simplest use, end each module M to be tested with:\n\ndef _test():\n import doctest\n doctest.testmod()\n\nif __name__ == \"__main__\":\n _test()\n\nThen running the module as a script will cause the examples in the\ndocstrings to get executed and verified:\n\npython M.py\n\nThis won't display anything unless an example fails, in which case the\nfailing example(s) and the cause(s) of the failure(s) are printed to stdout\n(why not stderr? because stderr is a lame hack <0.2 wink>), and the final\nline of output is \"Test failed.\".\n\nRun it with the -v switch instead:\n\npython M.py -v\n\nand a detailed report of all examples tried is printed to stdout, along\nwith assorted summaries at the end.\n\nYou can force verbose mode by passing \"verbose=True\" to testmod, or prohibit\nit by passing \"verbose=False\". In either of those cases, sys.argv is not\nexamined by testmod.\n\nThere are a variety of other ways to run doctests, including integration\nwith the unittest framework, and support for running non-Python text\nfiles containing doctests. There are also many ways to override parts\nof doctest's default behaviors. See the Library Reference Manual for\ndetails.\n\"\"\"\n\n__docformat__='reStructuredText en'\n\n__all__=[\n\n'register_optionflag',\n'DONT_ACCEPT_TRUE_FOR_1',\n'DONT_ACCEPT_BLANKLINE',\n'NORMALIZE_WHITESPACE',\n'ELLIPSIS',\n'SKIP',\n'IGNORE_EXCEPTION_DETAIL',\n'COMPARISON_FLAGS',\n'REPORT_UDIFF',\n'REPORT_CDIFF',\n'REPORT_NDIFF',\n'REPORT_ONLY_FIRST_FAILURE',\n'REPORTING_FLAGS',\n'FAIL_FAST',\n\n\n'Example',\n'DocTest',\n\n'DocTestParser',\n\n'DocTestFinder',\n\n'DocTestRunner',\n'OutputChecker',\n'DocTestFailure',\n'UnexpectedException',\n'DebugRunner',\n\n'testmod',\n'testfile',\n'run_docstring_examples',\n\n'DocTestSuite',\n'DocFileSuite',\n'set_unittest_reportflags',\n\n'script_from_examples',\n'testsource',\n'debug_src',\n'debug',\n]\n\nimport __future__\nimport difflib\nimport inspect\nimport linecache\nimport os\nimport pdb\nimport re\nimport sys\nimport traceback\nimport unittest\nfrom io import StringIO\nfrom collections import namedtuple\n\nTestResults=namedtuple('TestResults','failed attempted')\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\nOPTIONFLAGS_BY_NAME={}\ndef register_optionflag(name):\n\n return OPTIONFLAGS_BY_NAME.setdefault(name,1 <<len(OPTIONFLAGS_BY_NAME))\n \nDONT_ACCEPT_TRUE_FOR_1=register_optionflag('DONT_ACCEPT_TRUE_FOR_1')\nDONT_ACCEPT_BLANKLINE=register_optionflag('DONT_ACCEPT_BLANKLINE')\nNORMALIZE_WHITESPACE=register_optionflag('NORMALIZE_WHITESPACE')\nELLIPSIS=register_optionflag('ELLIPSIS')\nSKIP=register_optionflag('SKIP')\nIGNORE_EXCEPTION_DETAIL=register_optionflag('IGNORE_EXCEPTION_DETAIL')\n\nCOMPARISON_FLAGS=(DONT_ACCEPT_TRUE_FOR_1 |\nDONT_ACCEPT_BLANKLINE |\nNORMALIZE_WHITESPACE |\nELLIPSIS |\nSKIP |\nIGNORE_EXCEPTION_DETAIL)\n\nREPORT_UDIFF=register_optionflag('REPORT_UDIFF')\nREPORT_CDIFF=register_optionflag('REPORT_CDIFF')\nREPORT_NDIFF=register_optionflag('REPORT_NDIFF')\nREPORT_ONLY_FIRST_FAILURE=register_optionflag('REPORT_ONLY_FIRST_FAILURE')\nFAIL_FAST=register_optionflag('FAIL_FAST')\n\nREPORTING_FLAGS=(REPORT_UDIFF |\nREPORT_CDIFF |\nREPORT_NDIFF |\nREPORT_ONLY_FIRST_FAILURE |\nFAIL_FAST)\n\n\nBLANKLINE_MARKER='<BLANKLINE>'\nELLIPSIS_MARKER='...'\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\ndef _extract_future_flags(globs):\n ''\n\n\n \n flags=0\n for fname in __future__.all_feature_names:\n feature=globs.get(fname,None )\n if feature is getattr(__future__,fname):\n flags |=feature.compiler_flag\n return flags\n \ndef _normalize_module(module,depth=2):\n ''\n\n\n\n\n\n\n\n \n if inspect.ismodule(module):\n return module\n elif isinstance(module,str):\n return __import__(module,globals(),locals(),[\"*\"])\n elif module is None :\n return sys.modules[sys._getframe(depth).f_globals['__name__']]\n else :\n raise TypeError(\"Expected a module, string, or None\")\n \ndef _load_testfile(filename,package,module_relative,encoding):\n if module_relative:\n package=_normalize_module(package,3)\n filename=_module_relative_path(package,filename)\n if getattr(package,'__loader__',None )is not None :\n if hasattr(package.__loader__,'get_data'):\n file_contents=package.__loader__.get_data(filename)\n file_contents=file_contents.decode(encoding)\n \n \n return file_contents.replace(os.linesep,'\\n'),filename\n with open(filename,encoding=encoding)as f:\n return f.read(),filename\n \ndef _indent(s,indent=4):\n ''\n\n\n \n \n return re.sub('(?m)^(?!$)',indent *' ',s)\n \ndef _exception_traceback(exc_info):\n ''\n\n\n \n \n excout=StringIO()\n exc_type,exc_val,exc_tb=exc_info\n traceback.print_exception(exc_type,exc_val,exc_tb,file=excout)\n return excout.getvalue()\n \n \nclass _SpoofOut(StringIO):\n def getvalue(self):\n result=StringIO.getvalue(self)\n \n \n \n if result and not result.endswith(\"\\n\"):\n result +=\"\\n\"\n return result\n \n def truncate(self,size=None ):\n self.seek(size)\n StringIO.truncate(self)\n \n \ndef _ellipsis_match(want,got):\n ''\n\n\n\n \n if ELLIPSIS_MARKER not in want:\n return want ==got\n \n \n ws=want.split(ELLIPSIS_MARKER)\n assert len(ws)>=2\n \n \n startpos,endpos=0,len(got)\n w=ws[0]\n if w:\n if got.startswith(w):\n startpos=len(w)\n del ws[0]\n else :\n return False\n w=ws[-1]\n if w:\n if got.endswith(w):\n endpos -=len(w)\n del ws[-1]\n else :\n return False\n \n if startpos >endpos:\n \n \n return False\n \n \n \n \n for w in ws:\n \n \n \n startpos=got.find(w,startpos,endpos)\n if startpos <0:\n return False\n startpos +=len(w)\n \n return True\n \ndef _comment_line(line):\n ''\n line=line.rstrip()\n if line:\n return '# '+line\n else :\n return '#'\n \ndef _strip_exception_details(msg):\n\n\n\n\n\n\n\n\n\n\n start,end=0,len(msg)\n \n i=msg.find(\"\\n\")\n if i >=0:\n end=i\n \n i=msg.find(':',0,end)\n if i >=0:\n end=i\n \n i=msg.rfind('.',0,end)\n if i >=0:\n start=i+1\n return msg[start:end]\n \nclass _OutputRedirectingPdb(pdb.Pdb):\n ''\n\n\n\n \n def __init__(self,out):\n self.__out=out\n self.__debugger_used=False\n \n pdb.Pdb.__init__(self,stdout=out,nosigint=True )\n \n self.use_rawinput=1\n \n def set_trace(self,frame=None ):\n self.__debugger_used=True\n if frame is None :\n frame=sys._getframe().f_back\n pdb.Pdb.set_trace(self,frame)\n \n def set_continue(self):\n \n \n if self.__debugger_used:\n pdb.Pdb.set_continue(self)\n \n def trace_dispatch(self,*args):\n \n save_stdout=sys.stdout\n sys.stdout=self.__out\n \n try :\n return pdb.Pdb.trace_dispatch(self,*args)\n finally :\n sys.stdout=save_stdout\n \n \ndef _module_relative_path(module,test_path):\n if not inspect.ismodule(module):\n raise TypeError('Expected a module: %r'%module)\n if test_path.startswith('/'):\n raise ValueError('Module-relative files may not have absolute paths')\n \n \n test_path=os.path.join(*(test_path.split('/')))\n \n \n if hasattr(module,'__file__'):\n \n basedir=os.path.split(module.__file__)[0]\n elif module.__name__ =='__main__':\n \n if len(sys.argv)>0 and sys.argv[0]!='':\n basedir=os.path.split(sys.argv[0])[0]\n else :\n basedir=os.curdir\n else :\n if hasattr(module,'__path__'):\n for directory in module.__path__:\n fullpath=os.path.join(directory,test_path)\n if os.path.exists(fullpath):\n return fullpath\n \n \n raise ValueError(\"Can't resolve paths relative to the module \"\n \"%r (it has no __file__)\"\n %module.__name__)\n \n \n return os.path.join(basedir,test_path)\n \n \n \n \n \n \n \n \n \n \n \n \n \nclass Example:\n ''\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n \n def __init__(self,source,want,exc_msg=None ,lineno=0,indent=0,\n options=None ):\n \n if not source.endswith('\\n'):\n source +='\\n'\n if want and not want.endswith('\\n'):\n want +='\\n'\n if exc_msg is not None and not exc_msg.endswith('\\n'):\n exc_msg +='\\n'\n \n self.source=source\n self.want=want\n self.lineno=lineno\n self.indent=indent\n if options is None :options={}\n self.options=options\n self.exc_msg=exc_msg\n \n def __eq__(self,other):\n if type(self)is not type(other):\n return NotImplemented\n \n return self.source ==other.source and\\\n self.want ==other.want and\\\n self.lineno ==other.lineno and\\\n self.indent ==other.indent and\\\n self.options ==other.options and\\\n self.exc_msg ==other.exc_msg\n \n def __hash__(self):\n return hash((self.source,self.want,self.lineno,self.indent,\n self.exc_msg))\n \nclass DocTest:\n ''\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n \n def __init__(self,examples,globs,name,filename,lineno,docstring):\n ''\n\n\n \n assert not isinstance(examples,str),\\\n \"DocTest no longer accepts str; use DocTestParser instead\"\n self.examples=examples\n self.docstring=docstring\n self.globs=globs.copy()\n self.name=name\n self.filename=filename\n self.lineno=lineno\n \n def __repr__(self):\n if len(self.examples)==0:\n examples='no examples'\n elif len(self.examples)==1:\n examples='1 example'\n else :\n examples='%d examples'%len(self.examples)\n return ('<%s %s from %s:%s (%s)>'%\n (self.__class__.__name__,\n self.name,self.filename,self.lineno,examples))\n \n def __eq__(self,other):\n if type(self)is not type(other):\n return NotImplemented\n \n return self.examples ==other.examples and\\\n self.docstring ==other.docstring and\\\n self.globs ==other.globs and\\\n self.name ==other.name and\\\n self.filename ==other.filename and\\\n self.lineno ==other.lineno\n \n def __hash__(self):\n return hash((self.docstring,self.name,self.filename,self.lineno))\n \n \n def __lt__(self,other):\n if not isinstance(other,DocTest):\n return NotImplemented\n return ((self.name,self.filename,self.lineno,id(self))\n <\n (other.name,other.filename,other.lineno,id(other)))\n \n \n \n \n \nclass DocTestParser:\n ''\n\n \n \n \n \n \n \n _EXAMPLE_RE=re.compile(r'''\n # Source consists of a PS1 line followed by zero or more PS2 lines.\n (?P<source>\n (?:^(?P<indent> [ ]*) >>> .*) # PS1 line\n (?:\\n [ ]* \\.\\.\\. .*)*) # PS2 lines\n \\n?\n # Want consists of any non-blank lines that do not start with PS1.\n (?P<want> (?:(?![ ]*$) # Not a blank line\n (?![ ]*>>>) # Not a line starting with PS1\n .+$\\n? # But any other line\n )*)\n ''',re.MULTILINE |re.VERBOSE)\n \n \n \n \n \n \n \n \n \n \n _EXCEPTION_RE=re.compile(r\"\"\"\n # Grab the traceback header. Different versions of Python have\n # said different things on the first traceback line.\n ^(?P<hdr> Traceback\\ \\(\n (?: most\\ recent\\ call\\ last\n | innermost\\ last\n ) \\) :\n )\n \\s* $ # toss trailing whitespace on the header.\n (?P<stack> .*?) # don't blink: absorb stuff until...\n ^ (?P<msg> \\w+ .*) # a line *starts* with alphanum.\n \"\"\",re.VERBOSE |re.MULTILINE |re.DOTALL)\n \n \n \n _IS_BLANK_OR_COMMENT=re.compile(r'^[ ]*(#.*)?$').match\n \n def parse(self,string,name='<string>'):\n ''\n\n\n\n\n\n \n string=string.expandtabs()\n \n min_indent=self._min_indent(string)\n if min_indent >0:\n string='\\n'.join([l[min_indent:]for l in string.split('\\n')])\n \n output=[]\n charno,lineno=0,0\n \n for m in self._EXAMPLE_RE.finditer(string):\n \n output.append(string[charno:m.start()])\n \n lineno +=string.count('\\n',charno,m.start())\n \n (source,options,want,exc_msg)=\\\n self._parse_example(m,name,lineno)\n \n if not self._IS_BLANK_OR_COMMENT(source):\n output.append(Example(source,want,exc_msg,\n lineno=lineno,\n indent=min_indent+len(m.group('indent')),\n options=options))\n \n lineno +=string.count('\\n',m.start(),m.end())\n \n charno=m.end()\n \n output.append(string[charno:])\n return output\n \n def get_doctest(self,string,globs,name,filename,lineno):\n ''\n\n\n\n\n\n\n \n return DocTest(self.get_examples(string,name),globs,\n name,filename,lineno,string)\n \n def get_examples(self,string,name='<string>'):\n ''\n\n\n\n\n\n\n\n\n \n return [x for x in self.parse(string,name)\n if isinstance(x,Example)]\n \n def _parse_example(self,m,name,lineno):\n ''\n\n\n\n\n\n\n\n\n \n \n indent=len(m.group('indent'))\n \n \n \n source_lines=m.group('source').split('\\n')\n self._check_prompt_blank(source_lines,indent,name,lineno)\n self._check_prefix(source_lines[1:],' '*indent+'.',name,lineno)\n source='\\n'.join([sl[indent+4:]for sl in source_lines])\n \n \n \n \n want=m.group('want')\n want_lines=want.split('\\n')\n if len(want_lines)>1 and re.match(r' *$',want_lines[-1]):\n del want_lines[-1]\n self._check_prefix(want_lines,' '*indent,name,\n lineno+len(source_lines))\n want='\\n'.join([wl[indent:]for wl in want_lines])\n \n \n m=self._EXCEPTION_RE.match(want)\n if m:\n exc_msg=m.group('msg')\n else :\n exc_msg=None\n \n \n options=self._find_options(source,name,lineno)\n \n return source,options,want,exc_msg\n \n \n \n \n \n \n \n \n _OPTION_DIRECTIVE_RE=re.compile(r'#\\s*doctest:\\s*([^\\n\\'\"]*)$',\n re.MULTILINE)\n \n def _find_options(self,source,name,lineno):\n ''\n\n\n\n\n\n \n options={}\n \n for m in self._OPTION_DIRECTIVE_RE.finditer(source):\n option_strings=m.group(1).replace(',',' ').split()\n for option in option_strings:\n if (option[0]not in '+-'or\n option[1:]not in OPTIONFLAGS_BY_NAME):\n raise ValueError('line %r of the doctest for %s '\n 'has an invalid option: %r'%\n (lineno+1,name,option))\n flag=OPTIONFLAGS_BY_NAME[option[1:]]\n options[flag]=(option[0]=='+')\n if options and self._IS_BLANK_OR_COMMENT(source):\n raise ValueError('line %r of the doctest for %s has an option '\n 'directive on a line with no example: %r'%\n (lineno,name,source))\n return options\n \n \n \n _INDENT_RE=re.compile(r'^([ ]*)(?=\\S)',re.MULTILINE)\n \n def _min_indent(self,s):\n ''\n indents=[len(indent)for indent in self._INDENT_RE.findall(s)]\n if len(indents)>0:\n return min(indents)\n else :\n return 0\n \n def _check_prompt_blank(self,lines,indent,name,lineno):\n ''\n\n\n\n\n \n for i,line in enumerate(lines):\n if len(line)>=indent+4 and line[indent+3]!=' ':\n raise ValueError('line %r of the docstring for %s '\n 'lacks blank after %s: %r'%\n (lineno+i+1,name,\n line[indent:indent+3],line))\n \n def _check_prefix(self,lines,prefix,name,lineno):\n ''\n\n\n \n for i,line in enumerate(lines):\n if line and not line.startswith(prefix):\n raise ValueError('line %r of the docstring for %s has '\n 'inconsistent leading whitespace: %r'%\n (lineno+i+1,name,line))\n \n \n \n \n \n \nclass DocTestFinder:\n ''\n\n\n\n\n\n \n \n def __init__(self,verbose=False ,parser=DocTestParser(),\n recurse=True ,exclude_empty=True ):\n ''\n\n\n\n\n\n\n\n\n\n\n\n\n\n \n self._parser=parser\n self._verbose=verbose\n self._recurse=recurse\n self._exclude_empty=exclude_empty\n \n def find(self,obj,name=None ,module=None ,globs=None ,extraglobs=None ):\n ''\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n \n \n if name is None :\n name=getattr(obj,'__name__',None )\n if name is None :\n raise ValueError(\"DocTestFinder.find: name must be given \"\n \"when obj.__name__ doesn't exist: %r\"%\n (type(obj),))\n \n \n \n \n if module is False :\n module=None\n elif module is None :\n module=inspect.getmodule(obj)\n \n \n \n \n try :\n file=inspect.getsourcefile(obj)\n except TypeError:\n source_lines=None\n else :\n if not file:\n \n \n file=inspect.getfile(obj)\n if not file[0]+file[-2:]=='<]>':file=None\n if file is None :\n source_lines=None\n else :\n if module is not None :\n \n \n \n source_lines=linecache.getlines(file,module.__dict__)\n else :\n \n \n source_lines=linecache.getlines(file)\n if not source_lines:\n source_lines=None\n \n \n if globs is None :\n if module is None :\n globs={}\n else :\n globs=module.__dict__.copy()\n else :\n globs=globs.copy()\n if extraglobs is not None :\n globs.update(extraglobs)\n if '__name__'not in globs:\n globs['__name__']='__main__'\n \n \n tests=[]\n self._find(tests,obj,name,module,source_lines,globs,{})\n \n \n \n \n tests.sort()\n return tests\n \n def _from_module(self,module,object):\n ''\n\n\n \n if module is None :\n return True\n elif inspect.getmodule(object)is not None :\n return module is inspect.getmodule(object)\n elif inspect.isfunction(object):\n return module.__dict__ is object.__globals__\n elif inspect.ismethoddescriptor(object):\n if hasattr(object,'__objclass__'):\n obj_mod=object.__objclass__.__module__\n elif hasattr(object,'__module__'):\n obj_mod=object.__module__\n else :\n return True\n return module.__name__ ==obj_mod\n elif inspect.isclass(object):\n return module.__name__ ==object.__module__\n elif hasattr(object,'__module__'):\n return module.__name__ ==object.__module__\n elif isinstance(object,property):\n return True\n else :\n raise ValueError(\"object must be a class or function\")\n \n def _find(self,tests,obj,name,module,source_lines,globs,seen):\n ''\n\n\n \n if self._verbose:\n print('Finding tests in %s'%name)\n \n \n if id(obj)in seen:\n return\n seen[id(obj)]=1\n \n \n test=self._get_test(obj,name,module,globs,source_lines)\n if test is not None :\n tests.append(test)\n \n \n if inspect.ismodule(obj)and self._recurse:\n for valname,val in obj.__dict__.items():\n valname='%s.%s'%(name,valname)\n \n if ((inspect.isroutine(inspect.unwrap(val))\n or inspect.isclass(val))and\n self._from_module(module,val)):\n self._find(tests,val,valname,module,source_lines,\n globs,seen)\n \n \n if inspect.ismodule(obj)and self._recurse:\n for valname,val in getattr(obj,'__test__',{}).items():\n if not isinstance(valname,str):\n raise ValueError(\"DocTestFinder.find: __test__ keys \"\n \"must be strings: %r\"%\n (type(valname),))\n if not (inspect.isroutine(val)or inspect.isclass(val)or\n inspect.ismodule(val)or isinstance(val,str)):\n raise ValueError(\"DocTestFinder.find: __test__ values \"\n \"must be strings, functions, methods, \"\n \"classes, or modules: %r\"%\n (type(val),))\n valname='%s.__test__.%s'%(name,valname)\n self._find(tests,val,valname,module,source_lines,\n globs,seen)\n \n \n if inspect.isclass(obj)and self._recurse:\n for valname,val in obj.__dict__.items():\n \n if isinstance(val,staticmethod):\n val=getattr(obj,valname)\n if isinstance(val,classmethod):\n val=getattr(obj,valname).__func__\n \n \n if ((inspect.isroutine(val)or inspect.isclass(val)or\n isinstance(val,property))and\n self._from_module(module,val)):\n valname='%s.%s'%(name,valname)\n self._find(tests,val,valname,module,source_lines,\n globs,seen)\n \n def _get_test(self,obj,name,module,globs,source_lines):\n ''\n\n\n \n \n \n if isinstance(obj,str):\n docstring=obj\n else :\n try :\n if obj.__doc__ is None :\n docstring=''\n else :\n docstring=obj.__doc__\n if not isinstance(docstring,str):\n docstring=str(docstring)\n except (TypeError,AttributeError):\n docstring=''\n \n \n lineno=self._find_lineno(obj,source_lines)\n \n \n if self._exclude_empty and not docstring:\n return None\n \n \n if module is None :\n filename=None\n else :\n filename=getattr(module,'__file__',module.__name__)\n if filename[-4:]==\".pyc\":\n filename=filename[:-1]\n return self._parser.get_doctest(docstring,globs,name,\n filename,lineno)\n \n def _find_lineno(self,obj,source_lines):\n ''\n\n\n \n lineno=None\n \n \n if inspect.ismodule(obj):\n lineno=0\n \n \n \n \n if inspect.isclass(obj):\n if source_lines is None :\n return None\n pat=re.compile(r'^\\s*class\\s*%s\\b'%\n getattr(obj,'__name__','-'))\n for i,line in enumerate(source_lines):\n if pat.match(line):\n lineno=i\n break\n \n \n if inspect.ismethod(obj):obj=obj.__func__\n if inspect.isfunction(obj):obj=obj.__code__\n if inspect.istraceback(obj):obj=obj.tb_frame\n if inspect.isframe(obj):obj=obj.f_code\n if inspect.iscode(obj):\n lineno=getattr(obj,'co_firstlineno',None )-1\n \n \n \n \n \n \n if lineno is not None :\n if source_lines is None :\n return lineno+1\n pat=re.compile(r'(^|.*:)\\s*\\w*(\"|\\')')\n for lineno in range(lineno,len(source_lines)):\n if pat.match(source_lines[lineno]):\n return lineno\n \n \n return None\n \n \n \n \n \nclass DocTestRunner:\n ''\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n \n \n \n DIVIDER=\"*\"*70\n \n def __init__(self,checker=None ,verbose=None ,optionflags=0):\n ''\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n \n self._checker=checker or OutputChecker()\n if verbose is None :\n verbose='-v'in sys.argv\n self._verbose=verbose\n self.optionflags=optionflags\n self.original_optionflags=optionflags\n \n \n self.tries=0\n self.failures=0\n self._name2ft={}\n \n \n self._fakeout=_SpoofOut()\n \n \n \n \n \n def report_start(self,out,test,example):\n ''\n\n\n \n if self._verbose:\n if example.want:\n out('Trying:\\n'+_indent(example.source)+\n 'Expecting:\\n'+_indent(example.want))\n else :\n out('Trying:\\n'+_indent(example.source)+\n 'Expecting nothing\\n')\n \n def report_success(self,out,test,example,got):\n ''\n\n\n \n if self._verbose:\n out(\"ok\\n\")\n \n def report_failure(self,out,test,example,got):\n ''\n\n \n out(self._failure_header(test,example)+\n self._checker.output_difference(example,got,self.optionflags))\n \n def report_unexpected_exception(self,out,test,example,exc_info):\n ''\n\n \n out(self._failure_header(test,example)+\n 'Exception raised:\\n'+_indent(_exception_traceback(exc_info)))\n \n def _failure_header(self,test,example):\n out=[self.DIVIDER]\n if test.filename:\n if test.lineno is not None and example.lineno is not None :\n lineno=test.lineno+example.lineno+1\n else :\n lineno='?'\n out.append('File \"%s\", line %s, in %s'%\n (test.filename,lineno,test.name))\n else :\n out.append('Line %s, in %s'%(example.lineno+1,test.name))\n out.append('Failed example:')\n source=example.source\n out.append(_indent(source))\n return '\\n'.join(out)\n \n \n \n \n \n def __run(self,test,compileflags,out):\n ''\n\n\n\n\n\n\n\n \n \n failures=tries=0\n \n \n \n original_optionflags=self.optionflags\n \n SUCCESS,FAILURE,BOOM=range(3)\n \n check=self._checker.check_output\n \n \n for examplenum,example in enumerate(test.examples):\n \n \n \n quiet=(self.optionflags&REPORT_ONLY_FIRST_FAILURE and\n failures >0)\n \n \n self.optionflags=original_optionflags\n if example.options:\n for (optionflag,val)in example.options.items():\n if val:\n self.optionflags |=optionflag\n else :\n self.optionflags &=~optionflag\n \n \n if self.optionflags&SKIP:\n continue\n \n \n tries +=1\n if not quiet:\n self.report_start(out,test,example)\n \n \n \n \n filename='<doctest %s[%d]>'%(test.name,examplenum)\n \n \n \n \n try :\n \n exec(compile(example.source,filename,\"single\",\n compileflags,1),test.globs)\n self.debugger.set_continue()\n exception=None\n except KeyboardInterrupt:\n raise\n except :\n exception=sys.exc_info()\n self.debugger.set_continue()\n \n got=self._fakeout.getvalue()\n self._fakeout.truncate(0)\n outcome=FAILURE\n \n \n \n if exception is None :\n if check(example.want,got,self.optionflags):\n outcome=SUCCESS\n \n \n else :\n exc_msg=traceback.format_exception_only(*exception[:2])[-1]\n if not quiet:\n got +=_exception_traceback(exception)\n \n \n \n if example.exc_msg is None :\n outcome=BOOM\n \n \n elif check(example.exc_msg,exc_msg,self.optionflags):\n outcome=SUCCESS\n \n \n elif self.optionflags&IGNORE_EXCEPTION_DETAIL:\n if check(_strip_exception_details(example.exc_msg),\n _strip_exception_details(exc_msg),\n self.optionflags):\n outcome=SUCCESS\n \n \n if outcome is SUCCESS:\n if not quiet:\n self.report_success(out,test,example,got)\n elif outcome is FAILURE:\n if not quiet:\n self.report_failure(out,test,example,got)\n failures +=1\n elif outcome is BOOM:\n if not quiet:\n self.report_unexpected_exception(out,test,example,\n exception)\n failures +=1\n else :\n assert False ,(\"unknown outcome\",outcome)\n \n if failures and self.optionflags&FAIL_FAST:\n break\n \n \n self.optionflags=original_optionflags\n \n \n self.__record_outcome(test,failures,tries)\n return TestResults(failures,tries)\n \n def __record_outcome(self,test,f,t):\n ''\n\n\n \n f2,t2=self._name2ft.get(test.name,(0,0))\n self._name2ft[test.name]=(f+f2,t+t2)\n self.failures +=f\n self.tries +=t\n \n __LINECACHE_FILENAME_RE=re.compile(r'<doctest '\n r'(?P<name>.+)'\n r'\\[(?P<examplenum>\\d+)\\]>$')\n def __patched_linecache_getlines(self,filename,module_globals=None ):\n m=self.__LINECACHE_FILENAME_RE.match(filename)\n if m and m.group('name')==self.test.name:\n example=self.test.examples[int(m.group('examplenum'))]\n return example.source.splitlines(keepends=True )\n else :\n return self.save_linecache_getlines(filename,module_globals)\n \n def run(self,test,compileflags=None ,out=None ,clear_globs=True ):\n ''\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n \n self.test=test\n \n if compileflags is None :\n compileflags=_extract_future_flags(test.globs)\n \n save_stdout=sys.stdout\n if out is None :\n encoding=save_stdout.encoding\n if encoding is None or encoding.lower()=='utf-8':\n out=save_stdout.write\n else :\n \n def out(s):\n s=str(s.encode(encoding,'backslashreplace'),encoding)\n save_stdout.write(s)\n sys.stdout=self._fakeout\n \n \n \n \n \n \n save_trace=sys.gettrace()\n save_set_trace=pdb.set_trace\n self.debugger=_OutputRedirectingPdb(save_stdout)\n self.debugger.reset()\n pdb.set_trace=self.debugger.set_trace\n \n \n \n self.save_linecache_getlines=linecache.getlines\n linecache.getlines=self.__patched_linecache_getlines\n \n \n save_displayhook=sys.displayhook\n sys.displayhook=sys.__displayhook__\n \n try :\n return self.__run(test,compileflags,out)\n finally :\n sys.stdout=save_stdout\n pdb.set_trace=save_set_trace\n sys.settrace(save_trace)\n linecache.getlines=self.save_linecache_getlines\n sys.displayhook=save_displayhook\n if clear_globs:\n test.globs.clear()\n import builtins\n builtins._=None\n \n \n \n \n def summarize(self,verbose=None ):\n ''\n\n\n\n\n\n\n\n\n \n if verbose is None :\n verbose=self._verbose\n notests=[]\n passed=[]\n failed=[]\n totalt=totalf=0\n for x in self._name2ft.items():\n name,(f,t)=x\n assert f <=t\n totalt +=t\n totalf +=f\n if t ==0:\n notests.append(name)\n elif f ==0:\n passed.append((name,t))\n else :\n failed.append(x)\n if verbose:\n if notests:\n print(len(notests),\"items had no tests:\")\n notests.sort()\n for thing in notests:\n print(\" \",thing)\n if passed:\n print(len(passed),\"items passed all tests:\")\n passed.sort()\n for thing,count in passed:\n print(\" %3d tests in %s\"%(count,thing))\n if failed:\n print(self.DIVIDER)\n print(len(failed),\"items had failures:\")\n failed.sort()\n for thing,(f,t)in failed:\n print(\" %3d of %3d in %s\"%(f,t,thing))\n if verbose:\n print(totalt,\"tests in\",len(self._name2ft),\"items.\")\n print(totalt -totalf,\"passed and\",totalf,\"failed.\")\n if totalf:\n print(\"***Test Failed***\",totalf,\"failures.\")\n elif verbose:\n print(\"Test passed.\")\n return TestResults(totalf,totalt)\n \n \n \n \n def merge(self,other):\n d=self._name2ft\n for name,(f,t)in other._name2ft.items():\n if name in d:\n \n \n \n \n f2,t2=d[name]\n f=f+f2\n t=t+t2\n d[name]=f,t\n \nclass OutputChecker:\n ''\n\n\n\n\n\n \n def _toAscii(self,s):\n ''\n\n \n return str(s.encode('ASCII','backslashreplace'),\"ASCII\")\n \n def check_output(self,want,got,optionflags):\n ''\n\n\n\n\n\n\n\n \n \n \n \n \n \n \n got=self._toAscii(got)\n want=self._toAscii(want)\n \n \n \n if got ==want:\n return True\n \n \n \n if not (optionflags&DONT_ACCEPT_TRUE_FOR_1):\n if (got,want)==(\"True\\n\",\"1\\n\"):\n return True\n if (got,want)==(\"False\\n\",\"0\\n\"):\n return True\n \n \n \n if not (optionflags&DONT_ACCEPT_BLANKLINE):\n \n want=re.sub(r'(?m)^%s\\s*?$'%re.escape(BLANKLINE_MARKER),\n '',want)\n \n \n got=re.sub(r'(?m)^[^\\S\\n]+$','',got)\n if got ==want:\n return True\n \n \n \n \n if optionflags&NORMALIZE_WHITESPACE:\n got=' '.join(got.split())\n want=' '.join(want.split())\n if got ==want:\n return True\n \n \n \n if optionflags&ELLIPSIS:\n if _ellipsis_match(want,got):\n return True\n \n \n return False\n \n \n def _do_a_fancy_diff(self,want,got,optionflags):\n \n if not optionflags&(REPORT_UDIFF |\n REPORT_CDIFF |\n REPORT_NDIFF):\n return False\n \n \n \n \n \n \n \n \n \n \n \n if optionflags&REPORT_NDIFF:\n return True\n \n \n return want.count('\\n')>2 and got.count('\\n')>2\n \n def output_difference(self,example,got,optionflags):\n ''\n\n\n\n\n \n want=example.want\n \n \n if not (optionflags&DONT_ACCEPT_BLANKLINE):\n got=re.sub('(?m)^[ ]*(?=\\n)',BLANKLINE_MARKER,got)\n \n \n if self._do_a_fancy_diff(want,got,optionflags):\n \n want_lines=want.splitlines(keepends=True )\n got_lines=got.splitlines(keepends=True )\n \n if optionflags&REPORT_UDIFF:\n diff=difflib.unified_diff(want_lines,got_lines,n=2)\n diff=list(diff)[2:]\n kind='unified diff with -expected +actual'\n elif optionflags&REPORT_CDIFF:\n diff=difflib.context_diff(want_lines,got_lines,n=2)\n diff=list(diff)[2:]\n kind='context diff with expected followed by actual'\n elif optionflags&REPORT_NDIFF:\n engine=difflib.Differ(charjunk=difflib.IS_CHARACTER_JUNK)\n diff=list(engine.compare(want_lines,got_lines))\n kind='ndiff with -expected +actual'\n else :\n assert 0,'Bad diff option'\n \n diff=[line.rstrip()+'\\n'for line in diff]\n return 'Differences (%s):\\n'%kind+_indent(''.join(diff))\n \n \n \n if want and got:\n return 'Expected:\\n%sGot:\\n%s'%(_indent(want),_indent(got))\n elif want:\n return 'Expected:\\n%sGot nothing\\n'%_indent(want)\n elif got:\n return 'Expected nothing\\nGot:\\n%s'%_indent(got)\n else :\n return 'Expected nothing\\nGot nothing\\n'\n \nclass DocTestFailure(Exception):\n ''\n\n\n\n\n\n\n\n\n \n def __init__(self,test,example,got):\n self.test=test\n self.example=example\n self.got=got\n \n def __str__(self):\n return str(self.test)\n \nclass UnexpectedException(Exception):\n ''\n\n\n\n\n\n\n\n\n \n def __init__(self,test,example,exc_info):\n self.test=test\n self.example=example\n self.exc_info=exc_info\n \n def __str__(self):\n return str(self.test)\n \nclass DebugRunner(DocTestRunner):\n ''\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n \n \n def run(self,test,compileflags=None ,out=None ,clear_globs=True ):\n r=DocTestRunner.run(self,test,compileflags,out,False )\n if clear_globs:\n test.globs.clear()\n return r\n \n def report_unexpected_exception(self,out,test,example,exc_info):\n raise UnexpectedException(test,example,exc_info)\n \n def report_failure(self,out,test,example,got):\n raise DocTestFailure(test,example,got)\n \n \n \n \n \n \n \n \nmaster=None\n\ndef testmod(m=None ,name=None ,globs=None ,verbose=None ,\nreport=True ,optionflags=0,extraglobs=None ,\nraise_on_error=False ,exclude_empty=False ):\n ''\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n \n global master\n \n \n if m is None :\n \n \n \n m=sys.modules.get('__main__')\n \n \n if not inspect.ismodule(m):\n raise TypeError(\"testmod: module required; %r\"%(m,))\n \n \n if name is None :\n name=m.__name__\n \n \n finder=DocTestFinder(exclude_empty=exclude_empty)\n \n if raise_on_error:\n runner=DebugRunner(verbose=verbose,optionflags=optionflags)\n else :\n runner=DocTestRunner(verbose=verbose,optionflags=optionflags)\n \n for test in finder.find(m,name,globs=globs,extraglobs=extraglobs):\n runner.run(test)\n \n if report:\n runner.summarize()\n \n if master is None :\n master=runner\n else :\n master.merge(runner)\n \n return TestResults(runner.failures,runner.tries)\n \ndef testfile(filename,module_relative=True ,name=None ,package=None ,\nglobs=None ,verbose=None ,report=True ,optionflags=0,\nextraglobs=None ,raise_on_error=False ,parser=DocTestParser(),\nencoding=None ):\n ''\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n \n global master\n \n if package and not module_relative:\n raise ValueError(\"Package may only be specified for module-\"\n \"relative paths.\")\n \n \n text,filename=_load_testfile(filename,package,module_relative,\n encoding or \"utf-8\")\n \n \n if name is None :\n name=os.path.basename(filename)\n \n \n if globs is None :\n globs={}\n else :\n globs=globs.copy()\n if extraglobs is not None :\n globs.update(extraglobs)\n if '__name__'not in globs:\n globs['__name__']='__main__'\n \n if raise_on_error:\n runner=DebugRunner(verbose=verbose,optionflags=optionflags)\n else :\n runner=DocTestRunner(verbose=verbose,optionflags=optionflags)\n \n \n test=parser.get_doctest(text,globs,name,filename,0)\n runner.run(test)\n \n if report:\n runner.summarize()\n \n if master is None :\n master=runner\n else :\n master.merge(runner)\n \n return TestResults(runner.failures,runner.tries)\n \ndef run_docstring_examples(f,globs,verbose=False ,name=\"NoName\",\ncompileflags=None ,optionflags=0):\n ''\n\n\n\n\n\n\n\n\n\n\n\n\n\n \n \n finder=DocTestFinder(verbose=verbose,recurse=False )\n runner=DocTestRunner(verbose=verbose,optionflags=optionflags)\n for test in finder.find(f,name,globs=globs):\n runner.run(test,compileflags=compileflags)\n \n \n \n \n \n_unittest_reportflags=0\n\ndef set_unittest_reportflags(flags):\n ''\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n \n global _unittest_reportflags\n \n if (flags&REPORTING_FLAGS)!=flags:\n raise ValueError(\"Only reporting flags allowed\",flags)\n old=_unittest_reportflags\n _unittest_reportflags=flags\n return old\n \n \nclass DocTestCase(unittest.TestCase):\n\n def __init__(self,test,optionflags=0,setUp=None ,tearDown=None ,\n checker=None ):\n \n unittest.TestCase.__init__(self)\n self._dt_optionflags=optionflags\n self._dt_checker=checker\n self._dt_test=test\n self._dt_setUp=setUp\n self._dt_tearDown=tearDown\n \n def setUp(self):\n test=self._dt_test\n \n if self._dt_setUp is not None :\n self._dt_setUp(test)\n \n def tearDown(self):\n test=self._dt_test\n \n if self._dt_tearDown is not None :\n self._dt_tearDown(test)\n \n test.globs.clear()\n \n def runTest(self):\n test=self._dt_test\n old=sys.stdout\n new=StringIO()\n optionflags=self._dt_optionflags\n \n if not (optionflags&REPORTING_FLAGS):\n \n \n optionflags |=_unittest_reportflags\n \n runner=DocTestRunner(optionflags=optionflags,\n checker=self._dt_checker,verbose=False )\n \n try :\n runner.DIVIDER=\"-\"*70\n failures,tries=runner.run(\n test,out=new.write,clear_globs=False )\n finally :\n sys.stdout=old\n \n if failures:\n raise self.failureException(self.format_failure(new.getvalue()))\n \n def format_failure(self,err):\n test=self._dt_test\n if test.lineno is None :\n lineno='unknown line number'\n else :\n lineno='%s'%test.lineno\n lname='.'.join(test.name.split('.')[-1:])\n return ('Failed doctest test for %s\\n'\n ' File \"%s\", line %s, in %s\\n\\n%s'\n %(test.name,test.filename,lineno,lname,err)\n )\n \n def debug(self):\n ''\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n \n \n self.setUp()\n runner=DebugRunner(optionflags=self._dt_optionflags,\n checker=self._dt_checker,verbose=False )\n runner.run(self._dt_test,clear_globs=False )\n self.tearDown()\n \n def id(self):\n return self._dt_test.name\n \n def __eq__(self,other):\n if type(self)is not type(other):\n return NotImplemented\n \n return self._dt_test ==other._dt_test and\\\n self._dt_optionflags ==other._dt_optionflags and\\\n self._dt_setUp ==other._dt_setUp and\\\n self._dt_tearDown ==other._dt_tearDown and\\\n self._dt_checker ==other._dt_checker\n \n def __hash__(self):\n return hash((self._dt_optionflags,self._dt_setUp,self._dt_tearDown,\n self._dt_checker))\n \n def __repr__(self):\n name=self._dt_test.name.split('.')\n return \"%s (%s)\"%(name[-1],'.'.join(name[:-1]))\n \n __str__=__repr__\n \n def shortDescription(self):\n return \"Doctest: \"+self._dt_test.name\n \nclass SkipDocTestCase(DocTestCase):\n def __init__(self,module):\n self.module=module\n DocTestCase.__init__(self,None )\n \n def setUp(self):\n self.skipTest(\"DocTestSuite will not work with -O2 and above\")\n \n def test_skip(self):\n pass\n \n def shortDescription(self):\n return \"Skipping tests from %s\"%self.module.__name__\n \n __str__=shortDescription\n \n \nclass _DocTestSuite(unittest.TestSuite):\n\n def _removeTestAtIndex(self,index):\n pass\n \n \ndef DocTestSuite(module=None ,globs=None ,extraglobs=None ,test_finder=None ,\n**options):\n ''\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n \n \n if test_finder is None :\n test_finder=DocTestFinder()\n \n module=_normalize_module(module)\n tests=test_finder.find(module,globs=globs,extraglobs=extraglobs)\n \n if not tests and sys.flags.optimize >=2:\n \n suite=_DocTestSuite()\n suite.addTest(SkipDocTestCase(module))\n return suite\n \n tests.sort()\n suite=_DocTestSuite()\n \n for test in tests:\n if len(test.examples)==0:\n continue\n if not test.filename:\n filename=module.__file__\n if filename[-4:]==\".pyc\":\n filename=filename[:-1]\n test.filename=filename\n suite.addTest(DocTestCase(test,**options))\n \n return suite\n \nclass DocFileCase(DocTestCase):\n\n def id(self):\n return '_'.join(self._dt_test.name.split('.'))\n \n def __repr__(self):\n return self._dt_test.filename\n __str__=__repr__\n \n def format_failure(self,err):\n return ('Failed doctest test for %s\\n File \"%s\", line 0\\n\\n%s'\n %(self._dt_test.name,self._dt_test.filename,err)\n )\n \ndef DocFileTest(path,module_relative=True ,package=None ,\nglobs=None ,parser=DocTestParser(),\nencoding=None ,**options):\n if globs is None :\n globs={}\n else :\n globs=globs.copy()\n \n if package and not module_relative:\n raise ValueError(\"Package may only be specified for module-\"\n \"relative paths.\")\n \n \n doc,path=_load_testfile(path,package,module_relative,\n encoding or \"utf-8\")\n \n if \"__file__\"not in globs:\n globs[\"__file__\"]=path\n \n \n name=os.path.basename(path)\n \n \n test=parser.get_doctest(doc,globs,name,path,0)\n return DocFileCase(test,**options)\n \ndef DocFileSuite(*paths,**kw):\n ''\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n \n suite=_DocTestSuite()\n \n \n \n \n if kw.get('module_relative',True ):\n kw['package']=_normalize_module(kw.get('package'))\n \n for path in paths:\n suite.addTest(DocFileTest(path,**kw))\n \n return suite\n \n \n \n \n \ndef script_from_examples(s):\n ''\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n \n output=[]\n for piece in DocTestParser().parse(s):\n if isinstance(piece,Example):\n \n output.append(piece.source[:-1])\n \n want=piece.want\n if want:\n output.append('# Expected:')\n output +=['## '+l for l in want.split('\\n')[:-1]]\n else :\n \n output +=[_comment_line(l)\n for l in piece.split('\\n')[:-1]]\n \n \n while output and output[-1]=='#':\n output.pop()\n while output and output[0]=='#':\n output.pop(0)\n \n \n return '\\n'.join(output)+'\\n'\n \ndef testsource(module,name):\n ''\n\n\n\n\n \n module=_normalize_module(module)\n tests=DocTestFinder().find(module)\n test=[t for t in tests if t.name ==name]\n if not test:\n raise ValueError(name,\"not found in tests\")\n test=test[0]\n testsrc=script_from_examples(test.docstring)\n return testsrc\n \ndef debug_src(src,pm=False ,globs=None ):\n ''\n testsrc=script_from_examples(src)\n debug_script(testsrc,pm,globs)\n \ndef debug_script(src,pm=False ,globs=None ):\n ''\n import pdb\n \n if globs:\n globs=globs.copy()\n else :\n globs={}\n \n if pm:\n try :\n exec(src,globs,globs)\n except :\n print(sys.exc_info()[1])\n p=pdb.Pdb(nosigint=True )\n p.reset()\n p.interaction(None ,sys.exc_info()[2])\n else :\n pdb.Pdb(nosigint=True ).run(\"exec(%r)\"%src,globs,globs)\n \ndef debug(module,name,pm=False ):\n ''\n\n\n\n\n \n module=_normalize_module(module)\n testsrc=testsource(module,name)\n debug_script(testsrc,pm,module.__dict__)\n \n \n \n \nclass _TestClass:\n ''\n\n\n\n\n\n\n\n\n\n\n \n \n def __init__(self,val):\n ''\n\n\n\n\n \n \n self.val=val\n \n def square(self):\n ''\n\n\n\n \n \n self.val=self.val **2\n return self\n \n def get(self):\n ''\n\n\n\n\n \n \n return self.val\n \n__test__={\"_TestClass\":_TestClass,\n\"string\":r\"\"\"\n Example of a string object, searched as-is.\n >>> x = 1; y = 2\n >>> x + y, x * y\n (3, 2)\n \"\"\",\n\n\"bool-int equivalence\":r\"\"\"\n In 2.2, boolean expressions displayed\n 0 or 1. By default, we still accept\n them. This can be disabled by passing\n DONT_ACCEPT_TRUE_FOR_1 to the new\n optionflags argument.\n >>> 4 == 4\n 1\n >>> 4 == 4\n True\n >>> 4 > 4\n 0\n >>> 4 > 4\n False\n \"\"\",\n\n\"blank lines\":r\"\"\"\n Blank lines can be marked with <BLANKLINE>:\n >>> print('foo\\n\\nbar\\n')\n foo\n <BLANKLINE>\n bar\n <BLANKLINE>\n \"\"\",\n\n\"ellipsis\":r\"\"\"\n If the ellipsis flag is used, then '...' can be used to\n elide substrings in the desired output:\n >>> print(list(range(1000))) #doctest: +ELLIPSIS\n [0, 1, 2, ..., 999]\n \"\"\",\n\n\"whitespace normalization\":r\"\"\"\n If the whitespace normalization flag is used, then\n differences in whitespace are ignored.\n >>> print(list(range(30))) #doctest: +NORMALIZE_WHITESPACE\n [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14,\n 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26,\n 27, 28, 29]\n \"\"\",\n}\n\n\ndef _test():\n import argparse\n \n parser=argparse.ArgumentParser(description=\"doctest runner\")\n parser.add_argument('-v','--verbose',action='store_true',default=False ,\n help='print very verbose output for all tests')\n parser.add_argument('-o','--option',action='append',\n choices=OPTIONFLAGS_BY_NAME.keys(),default=[],\n help=('specify a doctest option flag to apply'\n ' to the test run; may be specified more'\n ' than once to apply multiple options'))\n parser.add_argument('-f','--fail-fast',action='store_true',\n help=('stop running tests after first failure (this'\n ' is a shorthand for -o FAIL_FAST, and is'\n ' in addition to any other -o options)'))\n parser.add_argument('file',nargs='+',\n help='file containing the tests to run')\n args=parser.parse_args()\n testfiles=args.file\n \n \n verbose=args.verbose\n options=0\n for option in args.option:\n options |=OPTIONFLAGS_BY_NAME[option]\n if args.fail_fast:\n options |=FAIL_FAST\n for filename in testfiles:\n if filename.endswith(\".py\"):\n \n \n \n dirname,filename=os.path.split(filename)\n sys.path.insert(0,dirname)\n m=__import__(filename[:-3])\n del sys.path[0]\n failures,_=testmod(m,verbose=verbose,optionflags=options)\n else :\n failures,_=testfile(filename,module_relative=False ,\n verbose=verbose,optionflags=options)\n if failures:\n return 1\n return 0\n \n \nif __name__ ==\"__main__\":\n sys.exit(_test())\n", ["__future__", "argparse", "builtins", "collections", "difflib", "inspect", "io", "linecache", "os", "pdb", "re", "sys", "traceback", "unittest"]], "unittest.main": [".py", "''\n\nimport sys\nimport argparse\nimport os\n\nfrom . import loader,runner\nfrom .signals import installHandler\n\n__unittest=True\n\nMAIN_EXAMPLES=\"\"\"\\\nExamples:\n %(prog)s test_module - run tests from test_module\n %(prog)s module.TestClass - run tests from module.TestClass\n %(prog)s module.Class.test_method - run specified test method\n %(prog)s path/to/test_file.py - run tests from test_file.py\n\"\"\"\n\nMODULE_EXAMPLES=\"\"\"\\\nExamples:\n %(prog)s - run default set of tests\n %(prog)s MyTestSuite - run suite 'MyTestSuite'\n %(prog)s MyTestCase.testSomething - run MyTestCase.testSomething\n %(prog)s MyTestCase - run all 'test*' test methods\n in MyTestCase\n\"\"\"\n\ndef _convert_name(name):\n\n\n\n\n if os.path.isfile(name)and name.lower().endswith('.py'):\n if os.path.isabs(name):\n rel_path=os.path.relpath(name,os.getcwd())\n if os.path.isabs(rel_path)or rel_path.startswith(os.pardir):\n return name\n name=rel_path\n \n \n return name[:-3].replace('\\\\','.').replace('/','.')\n return name\n \ndef _convert_names(names):\n return [_convert_name(name)for name in names]\n \n \ndef _convert_select_pattern(pattern):\n if not '*'in pattern:\n pattern='*%s*'%pattern\n return pattern\n \n \nclass TestProgram(object):\n ''\n\n \n \n module=None\n verbosity=1\n failfast=catchbreak=buffer=progName=warnings=testNamePatterns=None\n _discovery_parser=None\n \n def __init__(self,module='__main__',defaultTest=None ,argv=None ,\n testRunner=None ,testLoader=loader.defaultTestLoader,\n exit=True ,verbosity=1,failfast=None ,catchbreak=None ,\n buffer=None ,warnings=None ,*,tb_locals=False ):\n if isinstance(module,str):\n self.module=__import__(module)\n for part in module.split('.')[1:]:\n self.module=getattr(self.module,part)\n else :\n self.module=module\n if argv is None :\n argv=sys.argv\n \n self.exit=exit\n self.failfast=failfast\n self.catchbreak=catchbreak\n self.verbosity=verbosity\n self.buffer=buffer\n self.tb_locals=tb_locals\n if warnings is None and not sys.warnoptions:\n \n \n \n self.warnings='default'\n else :\n \n \n \n \n \n self.warnings=warnings\n self.defaultTest=defaultTest\n self.testRunner=testRunner\n self.testLoader=testLoader\n self.progName=os.path.basename(argv[0])\n self.parseArgs(argv)\n self.runTests()\n \n def usageExit(self,msg=None ):\n if msg:\n print(msg)\n if self._discovery_parser is None :\n self._initArgParsers()\n self._print_help()\n sys.exit(2)\n \n def _print_help(self,*args,**kwargs):\n if self.module is None :\n print(self._main_parser.format_help())\n print(MAIN_EXAMPLES %{'prog':self.progName})\n self._discovery_parser.print_help()\n else :\n print(self._main_parser.format_help())\n print(MODULE_EXAMPLES %{'prog':self.progName})\n \n def parseArgs(self,argv):\n self._initArgParsers()\n if self.module is None :\n if len(argv)>1 and argv[1].lower()=='discover':\n self._do_discovery(argv[2:])\n return\n self._main_parser.parse_args(argv[1:],self)\n if not self.tests:\n \n \n self._do_discovery([])\n return\n else :\n self._main_parser.parse_args(argv[1:],self)\n \n if self.tests:\n self.testNames=_convert_names(self.tests)\n if __name__ =='__main__':\n \n self.module=None\n elif self.defaultTest is None :\n \n self.testNames=None\n elif isinstance(self.defaultTest,str):\n self.testNames=(self.defaultTest,)\n else :\n self.testNames=list(self.defaultTest)\n self.createTests()\n \n def createTests(self,from_discovery=False ,Loader=None ):\n if self.testNamePatterns:\n self.testLoader.testNamePatterns=self.testNamePatterns\n if from_discovery:\n loader=self.testLoader if Loader is None else Loader()\n self.test=loader.discover(self.start,self.pattern,self.top)\n elif self.testNames is None :\n self.test=self.testLoader.loadTestsFromModule(self.module)\n else :\n self.test=self.testLoader.loadTestsFromNames(self.testNames,\n self.module)\n \n def _initArgParsers(self):\n parent_parser=self._getParentArgParser()\n self._main_parser=self._getMainArgParser(parent_parser)\n self._discovery_parser=self._getDiscoveryArgParser(parent_parser)\n \n def _getParentArgParser(self):\n parser=argparse.ArgumentParser(add_help=False )\n \n parser.add_argument('-v','--verbose',dest='verbosity',\n action='store_const',const=2,\n help='Verbose output')\n parser.add_argument('-q','--quiet',dest='verbosity',\n action='store_const',const=0,\n help='Quiet output')\n parser.add_argument('--locals',dest='tb_locals',\n action='store_true',\n help='Show local variables in tracebacks')\n if self.failfast is None :\n parser.add_argument('-f','--failfast',dest='failfast',\n action='store_true',\n help='Stop on first fail or error')\n self.failfast=False\n if self.catchbreak is None :\n parser.add_argument('-c','--catch',dest='catchbreak',\n action='store_true',\n help='Catch Ctrl-C and display results so far')\n self.catchbreak=False\n if self.buffer is None :\n parser.add_argument('-b','--buffer',dest='buffer',\n action='store_true',\n help='Buffer stdout and stderr during tests')\n self.buffer=False\n if self.testNamePatterns is None :\n parser.add_argument('-k',dest='testNamePatterns',\n action='append',type=_convert_select_pattern,\n help='Only run tests which match the given substring')\n self.testNamePatterns=[]\n \n return parser\n \n def _getMainArgParser(self,parent):\n parser=argparse.ArgumentParser(parents=[parent])\n parser.prog=self.progName\n parser.print_help=self._print_help\n \n parser.add_argument('tests',nargs='*',\n help='a list of any number of test modules, '\n 'classes and test methods.')\n \n return parser\n \n def _getDiscoveryArgParser(self,parent):\n parser=argparse.ArgumentParser(parents=[parent])\n parser.prog='%s discover'%self.progName\n parser.epilog=('For test discovery all test modules must be '\n 'importable from the top level directory of the '\n 'project.')\n \n parser.add_argument('-s','--start-directory',dest='start',\n help=\"Directory to start discovery ('.' default)\")\n parser.add_argument('-p','--pattern',dest='pattern',\n help=\"Pattern to match tests ('test*.py' default)\")\n parser.add_argument('-t','--top-level-directory',dest='top',\n help='Top level directory of project (defaults to '\n 'start directory)')\n for arg in ('start','pattern','top'):\n parser.add_argument(arg,nargs='?',\n default=argparse.SUPPRESS,\n help=argparse.SUPPRESS)\n \n return parser\n \n def _do_discovery(self,argv,Loader=None ):\n self.start='.'\n self.pattern='test*.py'\n self.top=None\n if argv is not None :\n \n if self._discovery_parser is None :\n \n self._initArgParsers()\n self._discovery_parser.parse_args(argv,self)\n \n self.createTests(from_discovery=True ,Loader=Loader)\n \n def runTests(self):\n if self.catchbreak:\n installHandler()\n if self.testRunner is None :\n self.testRunner=runner.TextTestRunner\n if isinstance(self.testRunner,type):\n try :\n try :\n testRunner=self.testRunner(verbosity=self.verbosity,\n failfast=self.failfast,\n buffer=self.buffer,\n warnings=self.warnings,\n tb_locals=self.tb_locals)\n except TypeError:\n \n testRunner=self.testRunner(verbosity=self.verbosity,\n failfast=self.failfast,\n buffer=self.buffer,\n warnings=self.warnings)\n except TypeError:\n \n testRunner=self.testRunner()\n else :\n \n testRunner=self.testRunner\n self.result=testRunner.run(self.test)\n if self.exit:\n sys.exit(not self.result.wasSuccessful())\n \nmain=TestProgram\n", ["argparse", "os", "sys", "unittest", "unittest.loader", "unittest.runner", "unittest.signals"]], "unittest": [".py", "''\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n__all__=['TestResult','TestCase','TestSuite',\n'TextTestRunner','TestLoader','FunctionTestCase','main',\n'defaultTestLoader','SkipTest','skip','skipIf','skipUnless',\n'expectedFailure','TextTestResult','installHandler',\n'registerResult','removeResult','removeHandler']\n\n\n__all__.extend(['getTestCaseNames','makeSuite','findTestCases'])\n\n__unittest=True\n\nfrom .result import TestResult\nfrom .case import (TestCase,FunctionTestCase,SkipTest,skip,skipIf,\nskipUnless,expectedFailure)\nfrom .suite import BaseTestSuite,TestSuite\nfrom .loader import (TestLoader,defaultTestLoader,makeSuite,getTestCaseNames,\nfindTestCases)\nfrom .main import TestProgram,main\nfrom .runner import TextTestRunner,TextTestResult\nfrom .signals import installHandler,registerResult,removeResult,removeHandler\n\n\n_TextTestResult=TextTestResult\n\n\n\n\ndef load_tests(loader,tests,pattern):\n import os.path\n \n this_dir=os.path.dirname(__file__)\n return loader.discover(start_dir=this_dir,pattern=pattern)\n", ["os.path", "unittest.case", "unittest.loader", "unittest.main", "unittest.result", "unittest.runner", "unittest.signals", "unittest.suite"], 1], "io": [".py", "''\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n__author__=(\"Guido van Rossum <guido@python.org>, \"\n\"Mike Verdone <mike.verdone@gmail.com>, \"\n\"Mark Russell <mark.russell@zen.co.uk>, \"\n\"Antoine Pitrou <solipsis@pitrou.net>, \"\n\"Amaury Forgeot d'Arc <amauryfa@gmail.com>, \"\n\"Benjamin Peterson <benjamin@python.org>\")\n\n__all__=[\"BlockingIOError\",\"open\",\"IOBase\",\"RawIOBase\",\"FileIO\",\n\"BytesIO\",\"StringIO\",\"BufferedIOBase\",\n\"BufferedReader\",\"BufferedWriter\",\"BufferedRWPair\",\n\"BufferedRandom\",\"TextIOBase\",\"TextIOWrapper\",\n\"UnsupportedOperation\",\"SEEK_SET\",\"SEEK_CUR\",\"SEEK_END\"]\n\n\nimport _io\nimport abc\n\nfrom _io import (DEFAULT_BUFFER_SIZE,BlockingIOError,UnsupportedOperation,\nopen,FileIO,BytesIO,StringIO,BufferedReader,\nBufferedWriter,BufferedRWPair,BufferedRandom,\nIncrementalNewlineDecoder,TextIOWrapper)\n\nOpenWrapper=_io.open\n\n\nUnsupportedOperation.__module__=\"io\"\n\n\nSEEK_SET=0\nSEEK_CUR=1\nSEEK_END=2\n\n\n\n\nclass IOBase(_io._IOBase,metaclass=abc.ABCMeta):\n __doc__=_io._IOBase.__doc__\n \nclass RawIOBase(_io._RawIOBase,IOBase):\n __doc__=_io._RawIOBase.__doc__\n \nclass BufferedIOBase(_io._BufferedIOBase,IOBase):\n __doc__=_io._BufferedIOBase.__doc__\n \nclass TextIOBase(_io._TextIOBase,IOBase):\n __doc__=_io._TextIOBase.__doc__\n \nRawIOBase.register(FileIO)\n\nfor klass in (BytesIO,BufferedReader,BufferedWriter,BufferedRandom,\nBufferedRWPair):\n BufferedIOBase.register(klass)\n \nfor klass in (StringIO,TextIOWrapper):\n TextIOBase.register(klass)\ndel klass\n\ntry :\n from _io import _WindowsConsoleIO\nexcept ImportError:\n pass\nelse :\n RawIOBase.register(_WindowsConsoleIO)\n", ["_io", "abc"]], "pprint": [".py", "\n\n\n\n\n\n\n\n\n\n\"\"\"Support to pretty-print lists, tuples, & dictionaries recursively.\n\nVery simple, but useful, especially in debugging data structures.\n\nClasses\n-------\n\nPrettyPrinter()\n Handle pretty-printing operations onto a stream using a configured\n set of formatting parameters.\n\nFunctions\n---------\n\npformat()\n Format a Python object into a pretty-printed representation.\n\npprint()\n Pretty-print a Python object to a stream [default is sys.stdout].\n\nsaferepr()\n Generate a 'standard' repr()-like value, but protect against recursive\n data structures.\n\n\"\"\"\n\nimport collections as _collections\nimport re\nimport sys as _sys\nimport types as _types\nfrom io import StringIO as _StringIO\n\n__all__=[\"pprint\",\"pformat\",\"isreadable\",\"isrecursive\",\"saferepr\",\n\"PrettyPrinter\"]\n\n\ndef pprint(object,stream=None ,indent=1,width=80,depth=None ,*,\ncompact=False ):\n ''\n printer=PrettyPrinter(\n stream=stream,indent=indent,width=width,depth=depth,\n compact=compact)\n printer.pprint(object)\n \ndef pformat(object,indent=1,width=80,depth=None ,*,compact=False ):\n ''\n return PrettyPrinter(indent=indent,width=width,depth=depth,\n compact=compact).pformat(object)\n \ndef saferepr(object):\n ''\n return _safe_repr(object,{},None ,0)[0]\n \ndef isreadable(object):\n ''\n return _safe_repr(object,{},None ,0)[1]\n \ndef isrecursive(object):\n ''\n return _safe_repr(object,{},None ,0)[2]\n \nclass _safe_key:\n ''\n\n\n\n\n\n\n \n \n __slots__=['obj']\n \n def __init__(self,obj):\n self.obj=obj\n \n def __lt__(self,other):\n try :\n return self.obj <other.obj\n except TypeError:\n return ((str(type(self.obj)),id(self.obj))<\\\n (str(type(other.obj)),id(other.obj)))\n \ndef _safe_tuple(t):\n ''\n return _safe_key(t[0]),_safe_key(t[1])\n \nclass PrettyPrinter:\n def __init__(self,indent=1,width=80,depth=None ,stream=None ,*,\n compact=False ):\n ''\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n \n indent=int(indent)\n width=int(width)\n if indent <0:\n raise ValueError('indent must be >= 0')\n if depth is not None and depth <=0:\n raise ValueError('depth must be > 0')\n if not width:\n raise ValueError('width must be != 0')\n self._depth=depth\n self._indent_per_level=indent\n self._width=width\n if stream is not None :\n self._stream=stream\n else :\n self._stream=_sys.stdout\n self._compact=bool(compact)\n \n def pprint(self,object):\n self._format(object,self._stream,0,0,{},0)\n self._stream.write(\"\\n\")\n \n def pformat(self,object):\n sio=_StringIO()\n self._format(object,sio,0,0,{},0)\n return sio.getvalue()\n \n def isrecursive(self,object):\n return self.format(object,{},0,0)[2]\n \n def isreadable(self,object):\n s,readable,recursive=self.format(object,{},0,0)\n return readable and not recursive\n \n def _format(self,object,stream,indent,allowance,context,level):\n objid=id(object)\n if objid in context:\n stream.write(_recursion(object))\n self._recursive=True\n self._readable=False\n return\n rep=self._repr(object,context,level)\n max_width=self._width -indent -allowance\n if len(rep)>max_width:\n p=self._dispatch.get(type(object).__repr__,None )\n if p is not None :\n context[objid]=1\n p(self,object,stream,indent,allowance,context,level+1)\n del context[objid]\n return\n elif isinstance(object,dict):\n context[objid]=1\n self._pprint_dict(object,stream,indent,allowance,\n context,level+1)\n del context[objid]\n return\n stream.write(rep)\n \n _dispatch={}\n \n def _pprint_dict(self,object,stream,indent,allowance,context,level):\n write=stream.write\n write('{')\n if self._indent_per_level >1:\n write((self._indent_per_level -1)*' ')\n length=len(object)\n if length:\n items=sorted(object.items(),key=_safe_tuple)\n self._format_dict_items(items,stream,indent,allowance+1,\n context,level)\n write('}')\n \n _dispatch[dict.__repr__]=_pprint_dict\n \n def _pprint_ordered_dict(self,object,stream,indent,allowance,context,level):\n if not len(object):\n stream.write(repr(object))\n return\n cls=object.__class__\n stream.write(cls.__name__+'(')\n self._format(list(object.items()),stream,\n indent+len(cls.__name__)+1,allowance+1,\n context,level)\n stream.write(')')\n \n _dispatch[_collections.OrderedDict.__repr__]=_pprint_ordered_dict\n \n def _pprint_list(self,object,stream,indent,allowance,context,level):\n stream.write('[')\n self._format_items(object,stream,indent,allowance+1,\n context,level)\n stream.write(']')\n \n _dispatch[list.__repr__]=_pprint_list\n \n def _pprint_tuple(self,object,stream,indent,allowance,context,level):\n stream.write('(')\n endchar=',)'if len(object)==1 else ')'\n self._format_items(object,stream,indent,allowance+len(endchar),\n context,level)\n stream.write(endchar)\n \n _dispatch[tuple.__repr__]=_pprint_tuple\n \n def _pprint_set(self,object,stream,indent,allowance,context,level):\n if not len(object):\n stream.write(repr(object))\n return\n typ=object.__class__\n if typ is set:\n stream.write('{')\n endchar='}'\n else :\n stream.write(typ.__name__+'({')\n endchar='})'\n indent +=len(typ.__name__)+1\n object=sorted(object,key=_safe_key)\n self._format_items(object,stream,indent,allowance+len(endchar),\n context,level)\n stream.write(endchar)\n \n _dispatch[set.__repr__]=_pprint_set\n _dispatch[frozenset.__repr__]=_pprint_set\n \n def _pprint_str(self,object,stream,indent,allowance,context,level):\n write=stream.write\n if not len(object):\n write(repr(object))\n return\n chunks=[]\n lines=object.splitlines(True )\n if level ==1:\n indent +=1\n allowance +=1\n max_width1=max_width=self._width -indent\n for i,line in enumerate(lines):\n rep=repr(line)\n if i ==len(lines)-1:\n max_width1 -=allowance\n if len(rep)<=max_width1:\n chunks.append(rep)\n else :\n \n parts=re.findall(r'\\S*\\s*',line)\n assert parts\n assert not parts[-1]\n parts.pop()\n max_width2=max_width\n current=''\n for j,part in enumerate(parts):\n candidate=current+part\n if j ==len(parts)-1 and i ==len(lines)-1:\n max_width2 -=allowance\n if len(repr(candidate))>max_width2:\n if current:\n chunks.append(repr(current))\n current=part\n else :\n current=candidate\n if current:\n chunks.append(repr(current))\n if len(chunks)==1:\n write(rep)\n return\n if level ==1:\n write('(')\n for i,rep in enumerate(chunks):\n if i >0:\n write('\\n'+' '*indent)\n write(rep)\n if level ==1:\n write(')')\n \n _dispatch[str.__repr__]=_pprint_str\n \n def _pprint_bytes(self,object,stream,indent,allowance,context,level):\n write=stream.write\n if len(object)<=4:\n write(repr(object))\n return\n parens=level ==1\n if parens:\n indent +=1\n allowance +=1\n write('(')\n delim=''\n for rep in _wrap_bytes_repr(object,self._width -indent,allowance):\n write(delim)\n write(rep)\n if not delim:\n delim='\\n'+' '*indent\n if parens:\n write(')')\n \n _dispatch[bytes.__repr__]=_pprint_bytes\n \n def _pprint_bytearray(self,object,stream,indent,allowance,context,level):\n write=stream.write\n write('bytearray(')\n self._pprint_bytes(bytes(object),stream,indent+10,\n allowance+1,context,level+1)\n write(')')\n \n _dispatch[bytearray.__repr__]=_pprint_bytearray\n \n def _pprint_mappingproxy(self,object,stream,indent,allowance,context,level):\n stream.write('mappingproxy(')\n self._format(object.copy(),stream,indent+13,allowance+1,\n context,level)\n stream.write(')')\n \n _dispatch[_types.MappingProxyType.__repr__]=_pprint_mappingproxy\n \n def _format_dict_items(self,items,stream,indent,allowance,context,\n level):\n write=stream.write\n indent +=self._indent_per_level\n delimnl=',\\n'+' '*indent\n last_index=len(items)-1\n for i,(key,ent)in enumerate(items):\n last=i ==last_index\n rep=self._repr(key,context,level)\n write(rep)\n write(': ')\n self._format(ent,stream,indent+len(rep)+2,\n allowance if last else 1,\n context,level)\n if not last:\n write(delimnl)\n \n def _format_items(self,items,stream,indent,allowance,context,level):\n write=stream.write\n indent +=self._indent_per_level\n if self._indent_per_level >1:\n write((self._indent_per_level -1)*' ')\n delimnl=',\\n'+' '*indent\n delim=''\n width=max_width=self._width -indent+1\n it=iter(items)\n try :\n next_ent=next(it)\n except StopIteration:\n return\n last=False\n while not last:\n ent=next_ent\n try :\n next_ent=next(it)\n except StopIteration:\n last=True\n max_width -=allowance\n width -=allowance\n if self._compact:\n rep=self._repr(ent,context,level)\n w=len(rep)+2\n if width <w:\n width=max_width\n if delim:\n delim=delimnl\n if width >=w:\n width -=w\n write(delim)\n delim=', '\n write(rep)\n continue\n write(delim)\n delim=delimnl\n self._format(ent,stream,indent,\n allowance if last else 1,\n context,level)\n \n def _repr(self,object,context,level):\n repr,readable,recursive=self.format(object,context.copy(),\n self._depth,level)\n if not readable:\n self._readable=False\n if recursive:\n self._recursive=True\n return repr\n \n def format(self,object,context,maxlevels,level):\n ''\n\n\n \n return _safe_repr(object,context,maxlevels,level)\n \n def _pprint_default_dict(self,object,stream,indent,allowance,context,level):\n if not len(object):\n stream.write(repr(object))\n return\n rdf=self._repr(object.default_factory,context,level)\n cls=object.__class__\n indent +=len(cls.__name__)+1\n stream.write('%s(%s,\\n%s'%(cls.__name__,rdf,' '*indent))\n self._pprint_dict(object,stream,indent,allowance+1,context,level)\n stream.write(')')\n \n _dispatch[_collections.defaultdict.__repr__]=_pprint_default_dict\n \n def _pprint_counter(self,object,stream,indent,allowance,context,level):\n if not len(object):\n stream.write(repr(object))\n return\n cls=object.__class__\n stream.write(cls.__name__+'({')\n if self._indent_per_level >1:\n stream.write((self._indent_per_level -1)*' ')\n items=object.most_common()\n self._format_dict_items(items,stream,\n indent+len(cls.__name__)+1,allowance+2,\n context,level)\n stream.write('})')\n \n _dispatch[_collections.Counter.__repr__]=_pprint_counter\n \n def _pprint_chain_map(self,object,stream,indent,allowance,context,level):\n if not len(object.maps):\n stream.write(repr(object))\n return\n cls=object.__class__\n stream.write(cls.__name__+'(')\n indent +=len(cls.__name__)+1\n for i,m in enumerate(object.maps):\n if i ==len(object.maps)-1:\n self._format(m,stream,indent,allowance+1,context,level)\n stream.write(')')\n else :\n self._format(m,stream,indent,1,context,level)\n stream.write(',\\n'+' '*indent)\n \n _dispatch[_collections.ChainMap.__repr__]=_pprint_chain_map\n \n def _pprint_deque(self,object,stream,indent,allowance,context,level):\n if not len(object):\n stream.write(repr(object))\n return\n cls=object.__class__\n stream.write(cls.__name__+'(')\n indent +=len(cls.__name__)+1\n stream.write('[')\n if object.maxlen is None :\n self._format_items(object,stream,indent,allowance+2,\n context,level)\n stream.write('])')\n else :\n self._format_items(object,stream,indent,2,\n context,level)\n rml=self._repr(object.maxlen,context,level)\n stream.write('],\\n%smaxlen=%s)'%(' '*indent,rml))\n \n _dispatch[_collections.deque.__repr__]=_pprint_deque\n \n def _pprint_user_dict(self,object,stream,indent,allowance,context,level):\n self._format(object.data,stream,indent,allowance,context,level -1)\n \n _dispatch[_collections.UserDict.__repr__]=_pprint_user_dict\n \n def _pprint_user_list(self,object,stream,indent,allowance,context,level):\n self._format(object.data,stream,indent,allowance,context,level -1)\n \n _dispatch[_collections.UserList.__repr__]=_pprint_user_list\n \n def _pprint_user_string(self,object,stream,indent,allowance,context,level):\n self._format(object.data,stream,indent,allowance,context,level -1)\n \n _dispatch[_collections.UserString.__repr__]=_pprint_user_string\n \n \n \ndef _safe_repr(object,context,maxlevels,level):\n typ=type(object)\n if typ in _builtin_scalars:\n return repr(object),True ,False\n \n r=getattr(typ,\"__repr__\",None )\n if issubclass(typ,dict)and r is dict.__repr__:\n if not object:\n return \"{}\",True ,False\n objid=id(object)\n if maxlevels and level >=maxlevels:\n return \"{...}\",False ,objid in context\n if objid in context:\n return _recursion(object),False ,True\n context[objid]=1\n readable=True\n recursive=False\n components=[]\n append=components.append\n level +=1\n saferepr=_safe_repr\n items=sorted(object.items(),key=_safe_tuple)\n for k,v in items:\n krepr,kreadable,krecur=saferepr(k,context,maxlevels,level)\n vrepr,vreadable,vrecur=saferepr(v,context,maxlevels,level)\n append(\"%s: %s\"%(krepr,vrepr))\n readable=readable and kreadable and vreadable\n if krecur or vrecur:\n recursive=True\n del context[objid]\n return \"{%s}\"%\", \".join(components),readable,recursive\n \n if (issubclass(typ,list)and r is list.__repr__)or\\\n (issubclass(typ,tuple)and r is tuple.__repr__):\n if issubclass(typ,list):\n if not object:\n return \"[]\",True ,False\n format=\"[%s]\"\n elif len(object)==1:\n format=\"(%s,)\"\n else :\n if not object:\n return \"()\",True ,False\n format=\"(%s)\"\n objid=id(object)\n if maxlevels and level >=maxlevels:\n return format %\"...\",False ,objid in context\n if objid in context:\n return _recursion(object),False ,True\n context[objid]=1\n readable=True\n recursive=False\n components=[]\n append=components.append\n level +=1\n for o in object:\n orepr,oreadable,orecur=_safe_repr(o,context,maxlevels,level)\n append(orepr)\n if not oreadable:\n readable=False\n if orecur:\n recursive=True\n del context[objid]\n return format %\", \".join(components),readable,recursive\n \n rep=repr(object)\n return rep,(rep and not rep.startswith('<')),False\n \n_builtin_scalars=frozenset({str,bytes,bytearray,int,float,complex,\nbool,type(None )})\n\ndef _recursion(object):\n return (\"<Recursion on %s with id=%s>\"\n %(type(object).__name__,id(object)))\n \n \ndef _perfcheck(object=None ):\n import time\n if object is None :\n object=[(\"string\",(1,2),[3,4],{5:6,7:8})]*100000\n p=PrettyPrinter()\n t1=time.time()\n _safe_repr(object,{},None ,0)\n t2=time.time()\n p.pformat(object)\n t3=time.time()\n print(\"_safe_repr:\",t2 -t1)\n print(\"pformat:\",t3 -t2)\n \ndef _wrap_bytes_repr(object,width,allowance):\n current=b''\n last=len(object)//4 *4\n for i in range(0,len(object),4):\n part=object[i:i+4]\n candidate=current+part\n if i ==last:\n width -=allowance\n if len(repr(candidate))>width:\n if current:\n yield repr(current)\n current=part\n else :\n current=candidate\n if current:\n yield repr(current)\n \nif __name__ ==\"__main__\":\n _perfcheck()\n", ["collections", "io", "re", "sys", "time", "types"]], "os": [".py", "''\n\n\n\nimport sys\n\nerror=OSError\nname='posix'\nlinesep='\\n'\n\nfrom posix import *\nimport posixpath as path\n\nsys.modules['os.path']=path\nfrom os.path import (curdir,pardir,sep,pathsep,defpath,extsep,altsep,\ndevnull)\n\nenviron={'HOME':__BRYTHON__.curdir,\n'PYTHONPATH':__BRYTHON__.brython_path\n}\n\ndef _get_exports_list(module):\n try :\n return list(module.__all__)\n except AttributeError:\n return [n for n in dir(module)if n[0]!='_']\n \ndef getenv(key,default=None ):\n ''\n\n \n return environ.get(key,default)\n \nsupports_bytes_environ=True\n\ndef chdir(path):\n __BRYTHON__.curdir=path\n \ndef fsencode(filename):\n ''\n\n\n\n \n encoding=sys.getfilesystemencoding()\n errors='surrogateescape'\n if isinstance(filename,bytes):\n return filename\n elif isinstance(filename,str):\n return filename.encode(encoding,errors)\n else :\n raise TypeError(\"expect bytes or str, not %s\"%type(filename).__name__)\n \ndef fsdecode(filename):\n ''\n\n\n\n \n encoding=sys.getfilesystemencoding()\n errors='surrogateescape'\n if isinstance(filename,str):\n return filename\n elif isinstance(filename,bytes):\n return filename.decode(encoding,errors)\n else :\n raise TypeError(\"expect bytes or str, not %s\"%type(filename).__name__)\n \ndef fspath(path):\n return path\n \ndef getcwd():\n return __BRYTHON__.curdir\n \n_set=set()\n\nsupports_dir_fd=_set\n\nsupports_effective_ids=_set\n\nsupports_fd=_set\n\nsupports_follow_symlinks=_set\n\n", ["os.path", "posix", "posixpath", "sys"]], "encodings.aliases": [".py", "''\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\naliases={\n\n\n\n\n'646':'ascii',\n'ansi_x3.4_1968':'ascii',\n'ansi_x3_4_1968':'ascii',\n'ansi_x3.4_1986':'ascii',\n'cp367':'ascii',\n'csascii':'ascii',\n'ibm367':'ascii',\n'iso646_us':'ascii',\n'iso_646.irv_1991':'ascii',\n'iso_ir_6':'ascii',\n'us':'ascii',\n'us_ascii':'ascii',\n\n\n'base64':'base64_codec',\n'base_64':'base64_codec',\n\n\n'big5_tw':'big5',\n'csbig5':'big5',\n\n\n'big5_hkscs':'big5hkscs',\n'hkscs':'big5hkscs',\n\n\n'bz2':'bz2_codec',\n\n\n'037':'cp037',\n'csibm037':'cp037',\n'ebcdic_cp_ca':'cp037',\n'ebcdic_cp_nl':'cp037',\n'ebcdic_cp_us':'cp037',\n'ebcdic_cp_wt':'cp037',\n'ibm037':'cp037',\n'ibm039':'cp037',\n\n\n'1026':'cp1026',\n'csibm1026':'cp1026',\n'ibm1026':'cp1026',\n\n\n'1125':'cp1125',\n'ibm1125':'cp1125',\n'cp866u':'cp1125',\n'ruscii':'cp1125',\n\n\n'1140':'cp1140',\n'ibm1140':'cp1140',\n\n\n'1250':'cp1250',\n'windows_1250':'cp1250',\n\n\n'1251':'cp1251',\n'windows_1251':'cp1251',\n\n\n'1252':'cp1252',\n'windows_1252':'cp1252',\n\n\n'1253':'cp1253',\n'windows_1253':'cp1253',\n\n\n'1254':'cp1254',\n'windows_1254':'cp1254',\n\n\n'1255':'cp1255',\n'windows_1255':'cp1255',\n\n\n'1256':'cp1256',\n'windows_1256':'cp1256',\n\n\n'1257':'cp1257',\n'windows_1257':'cp1257',\n\n\n'1258':'cp1258',\n'windows_1258':'cp1258',\n\n\n'273':'cp273',\n'ibm273':'cp273',\n'csibm273':'cp273',\n\n\n'424':'cp424',\n'csibm424':'cp424',\n'ebcdic_cp_he':'cp424',\n'ibm424':'cp424',\n\n\n'437':'cp437',\n'cspc8codepage437':'cp437',\n'ibm437':'cp437',\n\n\n'500':'cp500',\n'csibm500':'cp500',\n'ebcdic_cp_be':'cp500',\n'ebcdic_cp_ch':'cp500',\n'ibm500':'cp500',\n\n\n'775':'cp775',\n'cspc775baltic':'cp775',\n'ibm775':'cp775',\n\n\n'850':'cp850',\n'cspc850multilingual':'cp850',\n'ibm850':'cp850',\n\n\n'852':'cp852',\n'cspcp852':'cp852',\n'ibm852':'cp852',\n\n\n'855':'cp855',\n'csibm855':'cp855',\n'ibm855':'cp855',\n\n\n'857':'cp857',\n'csibm857':'cp857',\n'ibm857':'cp857',\n\n\n'858':'cp858',\n'csibm858':'cp858',\n'ibm858':'cp858',\n\n\n'860':'cp860',\n'csibm860':'cp860',\n'ibm860':'cp860',\n\n\n'861':'cp861',\n'cp_is':'cp861',\n'csibm861':'cp861',\n'ibm861':'cp861',\n\n\n'862':'cp862',\n'cspc862latinhebrew':'cp862',\n'ibm862':'cp862',\n\n\n'863':'cp863',\n'csibm863':'cp863',\n'ibm863':'cp863',\n\n\n'864':'cp864',\n'csibm864':'cp864',\n'ibm864':'cp864',\n\n\n'865':'cp865',\n'csibm865':'cp865',\n'ibm865':'cp865',\n\n\n'866':'cp866',\n'csibm866':'cp866',\n'ibm866':'cp866',\n\n\n'869':'cp869',\n'cp_gr':'cp869',\n'csibm869':'cp869',\n'ibm869':'cp869',\n\n\n'932':'cp932',\n'ms932':'cp932',\n'mskanji':'cp932',\n'ms_kanji':'cp932',\n\n\n'949':'cp949',\n'ms949':'cp949',\n'uhc':'cp949',\n\n\n'950':'cp950',\n'ms950':'cp950',\n\n\n'jisx0213':'euc_jis_2004',\n'eucjis2004':'euc_jis_2004',\n'euc_jis2004':'euc_jis_2004',\n\n\n'eucjisx0213':'euc_jisx0213',\n\n\n'eucjp':'euc_jp',\n'ujis':'euc_jp',\n'u_jis':'euc_jp',\n\n\n'euckr':'euc_kr',\n'korean':'euc_kr',\n'ksc5601':'euc_kr',\n'ks_c_5601':'euc_kr',\n'ks_c_5601_1987':'euc_kr',\n'ksx1001':'euc_kr',\n'ks_x_1001':'euc_kr',\n\n\n'gb18030_2000':'gb18030',\n\n\n'chinese':'gb2312',\n'csiso58gb231280':'gb2312',\n'euc_cn':'gb2312',\n'euccn':'gb2312',\n'eucgb2312_cn':'gb2312',\n'gb2312_1980':'gb2312',\n'gb2312_80':'gb2312',\n'iso_ir_58':'gb2312',\n\n\n'936':'gbk',\n'cp936':'gbk',\n'ms936':'gbk',\n\n\n'hex':'hex_codec',\n\n\n'roman8':'hp_roman8',\n'r8':'hp_roman8',\n'csHPRoman8':'hp_roman8',\n\n\n'hzgb':'hz',\n'hz_gb':'hz',\n'hz_gb_2312':'hz',\n\n\n'csiso2022jp':'iso2022_jp',\n'iso2022jp':'iso2022_jp',\n'iso_2022_jp':'iso2022_jp',\n\n\n'iso2022jp_1':'iso2022_jp_1',\n'iso_2022_jp_1':'iso2022_jp_1',\n\n\n'iso2022jp_2':'iso2022_jp_2',\n'iso_2022_jp_2':'iso2022_jp_2',\n\n\n'iso_2022_jp_2004':'iso2022_jp_2004',\n'iso2022jp_2004':'iso2022_jp_2004',\n\n\n'iso2022jp_3':'iso2022_jp_3',\n'iso_2022_jp_3':'iso2022_jp_3',\n\n\n'iso2022jp_ext':'iso2022_jp_ext',\n'iso_2022_jp_ext':'iso2022_jp_ext',\n\n\n'csiso2022kr':'iso2022_kr',\n'iso2022kr':'iso2022_kr',\n'iso_2022_kr':'iso2022_kr',\n\n\n'csisolatin6':'iso8859_10',\n'iso_8859_10':'iso8859_10',\n'iso_8859_10_1992':'iso8859_10',\n'iso_ir_157':'iso8859_10',\n'l6':'iso8859_10',\n'latin6':'iso8859_10',\n\n\n'thai':'iso8859_11',\n'iso_8859_11':'iso8859_11',\n'iso_8859_11_2001':'iso8859_11',\n\n\n'iso_8859_13':'iso8859_13',\n'l7':'iso8859_13',\n'latin7':'iso8859_13',\n\n\n'iso_8859_14':'iso8859_14',\n'iso_8859_14_1998':'iso8859_14',\n'iso_celtic':'iso8859_14',\n'iso_ir_199':'iso8859_14',\n'l8':'iso8859_14',\n'latin8':'iso8859_14',\n\n\n'iso_8859_15':'iso8859_15',\n'l9':'iso8859_15',\n'latin9':'iso8859_15',\n\n\n'iso_8859_16':'iso8859_16',\n'iso_8859_16_2001':'iso8859_16',\n'iso_ir_226':'iso8859_16',\n'l10':'iso8859_16',\n'latin10':'iso8859_16',\n\n\n'csisolatin2':'iso8859_2',\n'iso_8859_2':'iso8859_2',\n'iso_8859_2_1987':'iso8859_2',\n'iso_ir_101':'iso8859_2',\n'l2':'iso8859_2',\n'latin2':'iso8859_2',\n\n\n'csisolatin3':'iso8859_3',\n'iso_8859_3':'iso8859_3',\n'iso_8859_3_1988':'iso8859_3',\n'iso_ir_109':'iso8859_3',\n'l3':'iso8859_3',\n'latin3':'iso8859_3',\n\n\n'csisolatin4':'iso8859_4',\n'iso_8859_4':'iso8859_4',\n'iso_8859_4_1988':'iso8859_4',\n'iso_ir_110':'iso8859_4',\n'l4':'iso8859_4',\n'latin4':'iso8859_4',\n\n\n'csisolatincyrillic':'iso8859_5',\n'cyrillic':'iso8859_5',\n'iso_8859_5':'iso8859_5',\n'iso_8859_5_1988':'iso8859_5',\n'iso_ir_144':'iso8859_5',\n\n\n'arabic':'iso8859_6',\n'asmo_708':'iso8859_6',\n'csisolatinarabic':'iso8859_6',\n'ecma_114':'iso8859_6',\n'iso_8859_6':'iso8859_6',\n'iso_8859_6_1987':'iso8859_6',\n'iso_ir_127':'iso8859_6',\n\n\n'csisolatingreek':'iso8859_7',\n'ecma_118':'iso8859_7',\n'elot_928':'iso8859_7',\n'greek':'iso8859_7',\n'greek8':'iso8859_7',\n'iso_8859_7':'iso8859_7',\n'iso_8859_7_1987':'iso8859_7',\n'iso_ir_126':'iso8859_7',\n\n\n'csisolatinhebrew':'iso8859_8',\n'hebrew':'iso8859_8',\n'iso_8859_8':'iso8859_8',\n'iso_8859_8_1988':'iso8859_8',\n'iso_ir_138':'iso8859_8',\n\n\n'csisolatin5':'iso8859_9',\n'iso_8859_9':'iso8859_9',\n'iso_8859_9_1989':'iso8859_9',\n'iso_ir_148':'iso8859_9',\n'l5':'iso8859_9',\n'latin5':'iso8859_9',\n\n\n'cp1361':'johab',\n'ms1361':'johab',\n\n\n'cskoi8r':'koi8_r',\n\n\n\n\n\n\n\n\n'8859':'latin_1',\n'cp819':'latin_1',\n'csisolatin1':'latin_1',\n'ibm819':'latin_1',\n'iso8859':'latin_1',\n'iso8859_1':'latin_1',\n'iso_8859_1':'latin_1',\n'iso_8859_1_1987':'latin_1',\n'iso_ir_100':'latin_1',\n'l1':'latin_1',\n'latin':'latin_1',\n'latin1':'latin_1',\n\n\n'maccyrillic':'mac_cyrillic',\n\n\n'macgreek':'mac_greek',\n\n\n'maciceland':'mac_iceland',\n\n\n'maccentraleurope':'mac_latin2',\n'maclatin2':'mac_latin2',\n\n\n'macintosh':'mac_roman',\n'macroman':'mac_roman',\n\n\n'macturkish':'mac_turkish',\n\n\n'dbcs':'mbcs',\n\n\n'csptcp154':'ptcp154',\n'pt154':'ptcp154',\n'cp154':'ptcp154',\n'cyrillic_asian':'ptcp154',\n\n\n'quopri':'quopri_codec',\n'quoted_printable':'quopri_codec',\n'quotedprintable':'quopri_codec',\n\n\n'rot13':'rot_13',\n\n\n'csshiftjis':'shift_jis',\n'shiftjis':'shift_jis',\n'sjis':'shift_jis',\n's_jis':'shift_jis',\n\n\n'shiftjis2004':'shift_jis_2004',\n'sjis_2004':'shift_jis_2004',\n's_jis_2004':'shift_jis_2004',\n\n\n'shiftjisx0213':'shift_jisx0213',\n'sjisx0213':'shift_jisx0213',\n's_jisx0213':'shift_jisx0213',\n\n\n'tis260':'tactis',\n\n\n'tis620':'tis_620',\n'tis_620_0':'tis_620',\n'tis_620_2529_0':'tis_620',\n'tis_620_2529_1':'tis_620',\n'iso_ir_166':'tis_620',\n\n\n'u16':'utf_16',\n'utf16':'utf_16',\n\n\n'unicodebigunmarked':'utf_16_be',\n'utf_16be':'utf_16_be',\n\n\n'unicodelittleunmarked':'utf_16_le',\n'utf_16le':'utf_16_le',\n\n\n'u32':'utf_32',\n'utf32':'utf_32',\n\n\n'utf_32be':'utf_32_be',\n\n\n'utf_32le':'utf_32_le',\n\n\n'u7':'utf_7',\n'utf7':'utf_7',\n'unicode_1_1_utf_7':'utf_7',\n\n\n'u8':'utf_8',\n'utf':'utf_8',\n'utf8':'utf_8',\n'utf8_ucs2':'utf_8',\n'utf8_ucs4':'utf_8',\n\n\n'uu':'uu_codec',\n\n\n'zip':'zlib_codec',\n'zlib':'zlib_codec',\n\n\n'x_mac_japanese':'shift_jis',\n'x_mac_korean':'euc_kr',\n'x_mac_simp_chinese':'gb2312',\n'x_mac_trad_chinese':'big5',\n}\n", []], "encodings": [".py", "", [], 1], "gettext": [".py", "''\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\nimport locale\nimport os\nimport re\nimport sys\n\n\n__all__=['NullTranslations','GNUTranslations','Catalog',\n'find','translation','install','textdomain','bindtextdomain',\n'bind_textdomain_codeset',\n'dgettext','dngettext','gettext','lgettext','ldgettext',\n'ldngettext','lngettext','ngettext',\n]\n\n_default_localedir=os.path.join(sys.base_prefix,'share','locale')\n\n\n\n\n\n\n\n\n\n\n_token_pattern=re.compile(r\"\"\"\n (?P<WHITESPACES>[ \\t]+) | # spaces and horizontal tabs\n (?P<NUMBER>[0-9]+\\b) | # decimal integer\n (?P<NAME>n\\b) | # only n is allowed\n (?P<PARENTHESIS>[()]) |\n (?P<OPERATOR>[-*/%+?:]|[><!]=?|==|&&|\\|\\|) | # !, *, /, %, +, -, <, >,\n # <=, >=, ==, !=, &&, ||,\n # ? :\n # unary and bitwise ops\n # not allowed\n (?P<INVALID>\\w+|.) # invalid token\n \"\"\",re.VERBOSE |re.DOTALL)\n\ndef _tokenize(plural):\n for mo in re.finditer(_token_pattern,plural):\n kind=mo.lastgroup\n if kind =='WHITESPACES':\n continue\n value=mo.group(kind)\n if kind =='INVALID':\n raise ValueError('invalid token in plural form: %s'%value)\n yield value\n yield ''\n \ndef _error(value):\n if value:\n return ValueError('unexpected token in plural form: %s'%value)\n else :\n return ValueError('unexpected end of plural form')\n \n_binary_ops=(\n('||',),\n('&&',),\n('==','!='),\n('<','>','<=','>='),\n('+','-'),\n('*','/','%'),\n)\n_binary_ops={op:i for i,ops in enumerate(_binary_ops,1)for op in ops}\n_c2py_ops={'||':'or','&&':'and','/':'//'}\n\ndef _parse(tokens,priority=-1):\n result=''\n nexttok=next(tokens)\n while nexttok =='!':\n result +='not '\n nexttok=next(tokens)\n \n if nexttok =='(':\n sub,nexttok=_parse(tokens)\n result='%s(%s)'%(result,sub)\n if nexttok !=')':\n raise ValueError('unbalanced parenthesis in plural form')\n elif nexttok =='n':\n result='%s%s'%(result,nexttok)\n else :\n try :\n value=int(nexttok,10)\n except ValueError:\n raise _error(nexttok)from None\n result='%s%d'%(result,value)\n nexttok=next(tokens)\n \n j=100\n while nexttok in _binary_ops:\n i=_binary_ops[nexttok]\n if i <priority:\n break\n \n if i in (3,4)and j in (3,4):\n result='(%s)'%result\n \n op=_c2py_ops.get(nexttok,nexttok)\n right,nexttok=_parse(tokens,i+1)\n result='%s %s %s'%(result,op,right)\n j=i\n if j ==priority ==4:\n result='(%s)'%result\n \n if nexttok =='?'and priority <=0:\n if_true,nexttok=_parse(tokens,0)\n if nexttok !=':':\n raise _error(nexttok)\n if_false,nexttok=_parse(tokens)\n result='%s if %s else %s'%(if_true,result,if_false)\n if priority ==0:\n result='(%s)'%result\n \n return result,nexttok\n \ndef _as_int(n):\n try :\n i=round(n)\n except TypeError:\n raise TypeError('Plural value must be an integer, got %s'%\n (n.__class__.__name__,))from None\n import warnings\n warnings.warn('Plural value must be an integer, got %s'%\n (n.__class__.__name__,),\n DeprecationWarning,4)\n return n\n \ndef c2py(plural):\n ''\n\n \n \n if len(plural)>1000:\n raise ValueError('plural form expression is too long')\n try :\n result,nexttok=_parse(_tokenize(plural))\n if nexttok:\n raise _error(nexttok)\n \n depth=0\n for c in result:\n if c =='(':\n depth +=1\n if depth >20:\n \n \n raise ValueError('plural form expression is too complex')\n elif c ==')':\n depth -=1\n \n ns={'_as_int':_as_int}\n exec('''if True:\n def func(n):\n if not isinstance(n, int):\n n = _as_int(n)\n return int(%s)\n '''%result,ns)\n return ns['func']\n except RecursionError:\n \n raise ValueError('plural form expression is too complex')\n \n \ndef _expand_lang(loc):\n loc=locale.normalize(loc)\n COMPONENT_CODESET=1 <<0\n COMPONENT_TERRITORY=1 <<1\n COMPONENT_MODIFIER=1 <<2\n \n mask=0\n pos=loc.find('@')\n if pos >=0:\n modifier=loc[pos:]\n loc=loc[:pos]\n mask |=COMPONENT_MODIFIER\n else :\n modifier=''\n pos=loc.find('.')\n if pos >=0:\n codeset=loc[pos:]\n loc=loc[:pos]\n mask |=COMPONENT_CODESET\n else :\n codeset=''\n pos=loc.find('_')\n if pos >=0:\n territory=loc[pos:]\n loc=loc[:pos]\n mask |=COMPONENT_TERRITORY\n else :\n territory=''\n language=loc\n ret=[]\n for i in range(mask+1):\n if not (i&~mask):\n val=language\n if i&COMPONENT_TERRITORY:val +=territory\n if i&COMPONENT_CODESET:val +=codeset\n if i&COMPONENT_MODIFIER:val +=modifier\n ret.append(val)\n ret.reverse()\n return ret\n \n \n \nclass NullTranslations:\n def __init__(self,fp=None ):\n self._info={}\n self._charset=None\n self._output_charset=None\n self._fallback=None\n if fp is not None :\n self._parse(fp)\n \n def _parse(self,fp):\n pass\n \n def add_fallback(self,fallback):\n if self._fallback:\n self._fallback.add_fallback(fallback)\n else :\n self._fallback=fallback\n \n def gettext(self,message):\n if self._fallback:\n return self._fallback.gettext(message)\n return message\n \n def lgettext(self,message):\n if self._fallback:\n return self._fallback.lgettext(message)\n if self._output_charset:\n return message.encode(self._output_charset)\n return message.encode(locale.getpreferredencoding())\n \n def ngettext(self,msgid1,msgid2,n):\n if self._fallback:\n return self._fallback.ngettext(msgid1,msgid2,n)\n if n ==1:\n return msgid1\n else :\n return msgid2\n \n def lngettext(self,msgid1,msgid2,n):\n if self._fallback:\n return self._fallback.lngettext(msgid1,msgid2,n)\n if n ==1:\n tmsg=msgid1\n else :\n tmsg=msgid2\n if self._output_charset:\n return tmsg.encode(self._output_charset)\n return tmsg.encode(locale.getpreferredencoding())\n \n def info(self):\n return self._info\n \n def charset(self):\n return self._charset\n \n def output_charset(self):\n return self._output_charset\n \n def set_output_charset(self,charset):\n self._output_charset=charset\n \n def install(self,names=None ):\n import builtins\n builtins.__dict__['_']=self.gettext\n if hasattr(names,\"__contains__\"):\n if \"gettext\"in names:\n builtins.__dict__['gettext']=builtins.__dict__['_']\n if \"ngettext\"in names:\n builtins.__dict__['ngettext']=self.ngettext\n if \"lgettext\"in names:\n builtins.__dict__['lgettext']=self.lgettext\n if \"lngettext\"in names:\n builtins.__dict__['lngettext']=self.lngettext\n \n \nclass GNUTranslations(NullTranslations):\n\n LE_MAGIC=0x950412de\n BE_MAGIC=0xde120495\n \n \n VERSIONS=(0,1)\n \n def _get_versions(self,version):\n ''\n return (version >>16,version&0xffff)\n \n def _parse(self,fp):\n ''\n \n \n from struct import unpack\n filename=getattr(fp,'name','')\n \n \n self._catalog=catalog={}\n self.plural=lambda n:int(n !=1)\n buf=fp.read()\n buflen=len(buf)\n \n magic=unpack('<I',buf[:4])[0]\n if magic ==self.LE_MAGIC:\n version,msgcount,masteridx,transidx=unpack('<4I',buf[4:20])\n ii='<II'\n elif magic ==self.BE_MAGIC:\n version,msgcount,masteridx,transidx=unpack('>4I',buf[4:20])\n ii='>II'\n else :\n raise OSError(0,'Bad magic number',filename)\n \n major_version,minor_version=self._get_versions(version)\n \n if major_version not in self.VERSIONS:\n raise OSError(0,'Bad version number '+str(major_version),filename)\n \n \n \n for i in range(0,msgcount):\n mlen,moff=unpack(ii,buf[masteridx:masteridx+8])\n mend=moff+mlen\n tlen,toff=unpack(ii,buf[transidx:transidx+8])\n tend=toff+tlen\n if mend <buflen and tend <buflen:\n msg=buf[moff:mend]\n tmsg=buf[toff:tend]\n else :\n raise OSError(0,'File is corrupt',filename)\n \n if mlen ==0:\n \n lastk=None\n for b_item in tmsg.split(b'\\n'):\n item=b_item.decode().strip()\n if not item:\n continue\n k=v=None\n if ':'in item:\n k,v=item.split(':',1)\n k=k.strip().lower()\n v=v.strip()\n self._info[k]=v\n lastk=k\n elif lastk:\n self._info[lastk]+='\\n'+item\n if k =='content-type':\n self._charset=v.split('charset=')[1]\n elif k =='plural-forms':\n v=v.split(';')\n plural=v[1].split('plural=')[1]\n self.plural=c2py(plural)\n \n \n \n \n \n \n \n \n \n charset=self._charset or 'ascii'\n if b'\\x00'in msg:\n \n msgid1,msgid2=msg.split(b'\\x00')\n tmsg=tmsg.split(b'\\x00')\n msgid1=str(msgid1,charset)\n for i,x in enumerate(tmsg):\n catalog[(msgid1,i)]=str(x,charset)\n else :\n catalog[str(msg,charset)]=str(tmsg,charset)\n \n masteridx +=8\n transidx +=8\n \n def lgettext(self,message):\n missing=object()\n tmsg=self._catalog.get(message,missing)\n if tmsg is missing:\n if self._fallback:\n return self._fallback.lgettext(message)\n tmsg=message\n if self._output_charset:\n return tmsg.encode(self._output_charset)\n return tmsg.encode(locale.getpreferredencoding())\n \n def lngettext(self,msgid1,msgid2,n):\n try :\n tmsg=self._catalog[(msgid1,self.plural(n))]\n except KeyError:\n if self._fallback:\n return self._fallback.lngettext(msgid1,msgid2,n)\n if n ==1:\n tmsg=msgid1\n else :\n tmsg=msgid2\n if self._output_charset:\n return tmsg.encode(self._output_charset)\n return tmsg.encode(locale.getpreferredencoding())\n \n def gettext(self,message):\n missing=object()\n tmsg=self._catalog.get(message,missing)\n if tmsg is missing:\n if self._fallback:\n return self._fallback.gettext(message)\n return message\n return tmsg\n \n def ngettext(self,msgid1,msgid2,n):\n try :\n tmsg=self._catalog[(msgid1,self.plural(n))]\n except KeyError:\n if self._fallback:\n return self._fallback.ngettext(msgid1,msgid2,n)\n if n ==1:\n tmsg=msgid1\n else :\n tmsg=msgid2\n return tmsg\n \n \n \ndef find(domain,localedir=None ,languages=None ,all=False ):\n\n if localedir is None :\n localedir=_default_localedir\n if languages is None :\n languages=[]\n for envar in ('LANGUAGE','LC_ALL','LC_MESSAGES','LANG'):\n val=os.environ.get(envar)\n if val:\n languages=val.split(':')\n break\n if 'C'not in languages:\n languages.append('C')\n \n nelangs=[]\n for lang in languages:\n for nelang in _expand_lang(lang):\n if nelang not in nelangs:\n nelangs.append(nelang)\n \n if all:\n result=[]\n else :\n result=None\n for lang in nelangs:\n if lang =='C':\n break\n mofile=os.path.join(localedir,lang,'LC_MESSAGES','%s.mo'%domain)\n if os.path.exists(mofile):\n if all:\n result.append(mofile)\n else :\n return mofile\n return result\n \n \n \n \n_translations={}\n\ndef translation(domain,localedir=None ,languages=None ,\nclass_=None ,fallback=False ,codeset=None ):\n if class_ is None :\n class_=GNUTranslations\n mofiles=find(domain,localedir,languages,all=True )\n if not mofiles:\n if fallback:\n return NullTranslations()\n from errno import ENOENT\n raise FileNotFoundError(ENOENT,\n 'No translation file found for domain',domain)\n \n \n result=None\n for mofile in mofiles:\n key=(class_,os.path.abspath(mofile))\n t=_translations.get(key)\n if t is None :\n with open(mofile,'rb')as fp:\n t=_translations.setdefault(key,class_(fp))\n \n \n \n \n \n import copy\n t=copy.copy(t)\n if codeset:\n t.set_output_charset(codeset)\n if result is None :\n result=t\n else :\n result.add_fallback(t)\n return result\n \n \ndef install(domain,localedir=None ,codeset=None ,names=None ):\n t=translation(domain,localedir,fallback=True ,codeset=codeset)\n t.install(names)\n \n \n \n \n_localedirs={}\n\n_localecodesets={}\n\n_current_domain='messages'\n\n\ndef textdomain(domain=None ):\n global _current_domain\n if domain is not None :\n _current_domain=domain\n return _current_domain\n \n \ndef bindtextdomain(domain,localedir=None ):\n global _localedirs\n if localedir is not None :\n _localedirs[domain]=localedir\n return _localedirs.get(domain,_default_localedir)\n \n \ndef bind_textdomain_codeset(domain,codeset=None ):\n global _localecodesets\n if codeset is not None :\n _localecodesets[domain]=codeset\n return _localecodesets.get(domain)\n \n \ndef dgettext(domain,message):\n try :\n t=translation(domain,_localedirs.get(domain,None ),\n codeset=_localecodesets.get(domain))\n except OSError:\n return message\n return t.gettext(message)\n \ndef ldgettext(domain,message):\n codeset=_localecodesets.get(domain)\n try :\n t=translation(domain,_localedirs.get(domain,None ),codeset=codeset)\n except OSError:\n return message.encode(codeset or locale.getpreferredencoding())\n return t.lgettext(message)\n \ndef dngettext(domain,msgid1,msgid2,n):\n try :\n t=translation(domain,_localedirs.get(domain,None ),\n codeset=_localecodesets.get(domain))\n except OSError:\n if n ==1:\n return msgid1\n else :\n return msgid2\n return t.ngettext(msgid1,msgid2,n)\n \ndef ldngettext(domain,msgid1,msgid2,n):\n codeset=_localecodesets.get(domain)\n try :\n t=translation(domain,_localedirs.get(domain,None ),codeset=codeset)\n except OSError:\n if n ==1:\n tmsg=msgid1\n else :\n tmsg=msgid2\n return tmsg.encode(codeset or locale.getpreferredencoding())\n return t.lngettext(msgid1,msgid2,n)\n \ndef gettext(message):\n return dgettext(_current_domain,message)\n \ndef lgettext(message):\n return ldgettext(_current_domain,message)\n \ndef ngettext(msgid1,msgid2,n):\n return dngettext(_current_domain,msgid1,msgid2,n)\n \ndef lngettext(msgid1,msgid2,n):\n return ldngettext(_current_domain,msgid1,msgid2,n)\n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \nCatalog=translation\n", ["builtins", "copy", "errno", "locale", "os", "re", "struct", "sys", "warnings"]], "email._encoded_words": [".py", "''\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\nimport re\nimport base64\nimport binascii\nimport functools\nfrom string import ascii_letters,digits\nfrom email import errors\n\n__all__=['decode_q',\n'encode_q',\n'decode_b',\n'encode_b',\n'len_q',\n'len_b',\n'decode',\n'encode',\n]\n\n\n\n\n\n\n_q_byte_subber=functools.partial(re.compile(br'=([a-fA-F0-9]{2})').sub,\nlambda m:bytes.fromhex(m.group(1).decode()))\n\ndef decode_q(encoded):\n encoded=encoded.replace(b'_',b' ')\n return _q_byte_subber(encoded),[]\n \n \n \nclass _QByteMap(dict):\n\n safe=b'-!*+/'+ascii_letters.encode('ascii')+digits.encode('ascii')\n \n def __missing__(self,key):\n if key in self.safe:\n self[key]=chr(key)\n else :\n self[key]=\"={:02X}\".format(key)\n return self[key]\n \n_q_byte_map=_QByteMap()\n\n\n_q_byte_map[ord(' ')]='_'\n\ndef encode_q(bstring):\n return ''.join(_q_byte_map[x]for x in bstring)\n \ndef len_q(bstring):\n return sum(len(_q_byte_map[x])for x in bstring)\n \n \n \n \n \n \ndef decode_b(encoded):\n defects=[]\n pad_err=len(encoded)%4\n if pad_err:\n defects.append(errors.InvalidBase64PaddingDefect())\n padded_encoded=encoded+b'==='[:4 -pad_err]\n else :\n padded_encoded=encoded\n try :\n return base64.b64decode(padded_encoded,validate=True ),defects\n except binascii.Error:\n \n defects=[errors.InvalidBase64CharactersDefect()]\n \n \n \n for i in 0,1,2,3:\n try :\n return base64.b64decode(encoded+b'='*i,validate=False ),defects\n except binascii.Error:\n if i ==0:\n defects.append(errors.InvalidBase64PaddingDefect())\n else :\n \n raise AssertionError(\"unexpected binascii.Error\")\n \ndef encode_b(bstring):\n return base64.b64encode(bstring).decode('ascii')\n \ndef len_b(bstring):\n groups_of_3,leftover=divmod(len(bstring),3)\n \n return groups_of_3 *4+(4 if leftover else 0)\n \n \n_cte_decoders={\n'q':decode_q,\n'b':decode_b,\n}\n\ndef decode(ew):\n ''\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n \n _,charset,cte,cte_string,_=ew.split('?')\n charset,_,lang=charset.partition('*')\n cte=cte.lower()\n \n bstring=cte_string.encode('ascii','surrogateescape')\n bstring,defects=_cte_decoders[cte](bstring)\n \n try :\n string=bstring.decode(charset)\n except UnicodeError:\n defects.append(errors.UndecodableBytesDefect(\"Encoded word \"\n \"contains bytes not decodable using {} charset\".format(charset)))\n string=bstring.decode(charset,'surrogateescape')\n except LookupError:\n string=bstring.decode('ascii','surrogateescape')\n if charset.lower()!='unknown-8bit':\n defects.append(errors.CharsetError(\"Unknown charset {} \"\n \"in encoded word; decoded as unknown bytes\".format(charset)))\n return string,charset,lang,defects\n \n \n_cte_encoders={\n'q':encode_q,\n'b':encode_b,\n}\n\n_cte_encode_length={\n'q':len_q,\n'b':len_b,\n}\n\ndef encode(string,charset='utf-8',encoding=None ,lang=''):\n ''\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n \n if charset =='unknown-8bit':\n bstring=string.encode('ascii','surrogateescape')\n else :\n bstring=string.encode(charset)\n if encoding is None :\n qlen=_cte_encode_length['q'](bstring)\n blen=_cte_encode_length['b'](bstring)\n \n encoding='q'if qlen -blen <5 else 'b'\n encoded=_cte_encoders[encoding](bstring)\n if lang:\n lang='*'+lang\n return \"=?{}{}?{}?{}?=\".format(charset,lang,encoding,encoded)\n", ["base64", "binascii", "email", "email.errors", "functools", "re", "string"]], "webbrowser": [".py", "\n\nfrom browser import window\n\ndef open(url,new=0,autoraise=True ):\n window.open(url)\n \ndef open_new(url):\n return window.open(url,\"_blank\")\n \ndef open_new_tab(url):\n return open(url)\n \n", ["browser"]], "_thread": [".py", "''\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n__all__=['error','start_new_thread','exit','get_ident','allocate_lock',\n'interrupt_main','LockType']\n\n\nTIMEOUT_MAX=2 **31\n\n\n\n\n\n\nerror=RuntimeError\n\ndef _set_sentinel(*args,**kw):\n return LockType()\n \ndef start_new_thread(function,args,kwargs={}):\n ''\n\n\n\n\n\n\n\n\n\n\n \n if type(args)!=type(tuple()):\n raise TypeError(\"2nd arg must be a tuple\")\n if type(kwargs)!=type(dict()):\n raise TypeError(\"3rd arg must be a dict\")\n global _main\n _main=False\n try :\n function(*args,**kwargs)\n except SystemExit:\n pass\n except :\n import traceback\n traceback.print_exc()\n _main=True\n global _interrupt\n if _interrupt:\n _interrupt=False\n raise KeyboardInterrupt\n \ndef exit():\n ''\n raise SystemExit\n \ndef get_ident():\n ''\n\n\n\n\n \n return -1\n \ndef allocate_lock():\n ''\n return LockType()\n \ndef stack_size(size=None ):\n ''\n if size is not None :\n raise error(\"setting thread stack size not supported\")\n return 0\n \nclass LockType(object):\n ''\n\n\n\n\n\n\n\n \n \n def __init__(self):\n self.locked_status=False\n \n def acquire(self,waitflag=None ,timeout=-1):\n ''\n\n\n\n\n\n\n\n\n \n if waitflag is None or waitflag:\n self.locked_status=True\n return True\n else :\n if not self.locked_status:\n self.locked_status=True\n return True\n else :\n if timeout >0:\n import time\n time.sleep(timeout)\n return False\n \n __enter__=acquire\n \n def __exit__(self,typ,val,tb):\n self.release()\n \n def release(self):\n ''\n \n \n if not self.locked_status:\n raise error\n self.locked_status=False\n return True\n \n def locked(self):\n return self.locked_status\n \n \n_interrupt=False\n\n_main=True\n\ndef interrupt_main():\n ''\n \n if _main:\n raise KeyboardInterrupt\n else :\n global _interrupt\n _interrupt=True\n \n \nclass _local:\n pass\n \nRLock=LockType\n", ["time", "traceback"]], "email.generator": [".py", "\n\n\n\n\"\"\"Classes to generate plain text from a message object tree.\"\"\"\n\n__all__=['Generator','DecodedGenerator','BytesGenerator']\n\nimport re\nimport sys\nimport time\nimport random\n\nfrom copy import deepcopy\nfrom io import StringIO,BytesIO\nfrom email.utils import _has_surrogates\n\nUNDERSCORE='_'\nNL='\\n'\n\nNLCRE=re.compile(r'\\r\\n|\\r|\\n')\nfcre=re.compile(r'^From ',re.MULTILINE)\n\n\n\nclass Generator:\n ''\n\n\n\n \n \n \n \n \n def __init__(self,outfp,mangle_from_=None ,maxheaderlen=None ,*,\n policy=None ):\n ''\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n \n \n if mangle_from_ is None :\n mangle_from_=True if policy is None else policy.mangle_from_\n self._fp=outfp\n self._mangle_from_=mangle_from_\n self.maxheaderlen=maxheaderlen\n self.policy=policy\n \n def write(self,s):\n \n self._fp.write(s)\n \n def flatten(self,msg,unixfrom=False ,linesep=None ):\n ''\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n \n \n \n \n \n policy=msg.policy if self.policy is None else self.policy\n if linesep is not None :\n policy=policy.clone(linesep=linesep)\n if self.maxheaderlen is not None :\n policy=policy.clone(max_line_length=self.maxheaderlen)\n self._NL=policy.linesep\n self._encoded_NL=self._encode(self._NL)\n self._EMPTY=''\n self._encoded_EMPTY=self._encode(self._EMPTY)\n \n \n \n \n old_gen_policy=self.policy\n old_msg_policy=msg.policy\n try :\n self.policy=policy\n msg.policy=policy\n if unixfrom:\n ufrom=msg.get_unixfrom()\n if not ufrom:\n ufrom='From nobody '+time.ctime(time.time())\n self.write(ufrom+self._NL)\n self._write(msg)\n finally :\n self.policy=old_gen_policy\n msg.policy=old_msg_policy\n \n def clone(self,fp):\n ''\n return self.__class__(fp,\n self._mangle_from_,\n None ,\n policy=self.policy)\n \n \n \n \n \n \n \n \n \n \n \n \n \n \n def _new_buffer(self):\n \n return StringIO()\n \n def _encode(self,s):\n \n return s\n \n def _write_lines(self,lines):\n \n if not lines:\n return\n lines=NLCRE.split(lines)\n for line in lines[:-1]:\n self.write(line)\n self.write(self._NL)\n if lines[-1]:\n self.write(lines[-1])\n \n \n \n \n \n \n def _write(self,msg):\n \n \n \n \n \n \n \n \n \n \n \n oldfp=self._fp\n try :\n self._munge_cte=None\n self._fp=sfp=self._new_buffer()\n self._dispatch(msg)\n finally :\n self._fp=oldfp\n munge_cte=self._munge_cte\n del self._munge_cte\n \n if munge_cte:\n msg=deepcopy(msg)\n msg.replace_header('content-transfer-encoding',munge_cte[0])\n msg.replace_header('content-type',munge_cte[1])\n \n \n meth=getattr(msg,'_write_headers',None )\n if meth is None :\n self._write_headers(msg)\n else :\n meth(self)\n self._fp.write(sfp.getvalue())\n \n def _dispatch(self,msg):\n \n \n \n \n main=msg.get_content_maintype()\n sub=msg.get_content_subtype()\n specific=UNDERSCORE.join((main,sub)).replace('-','_')\n meth=getattr(self,'_handle_'+specific,None )\n if meth is None :\n generic=main.replace('-','_')\n meth=getattr(self,'_handle_'+generic,None )\n if meth is None :\n meth=self._writeBody\n meth(msg)\n \n \n \n \n \n def _write_headers(self,msg):\n for h,v in msg.raw_items():\n self.write(self.policy.fold(h,v))\n \n self.write(self._NL)\n \n \n \n \n \n def _handle_text(self,msg):\n payload=msg.get_payload()\n if payload is None :\n return\n if not isinstance(payload,str):\n raise TypeError('string payload expected: %s'%type(payload))\n if _has_surrogates(msg._payload):\n charset=msg.get_param('charset')\n if charset is not None :\n \n \n msg=deepcopy(msg)\n del msg['content-transfer-encoding']\n msg.set_payload(payload,charset)\n payload=msg.get_payload()\n self._munge_cte=(msg['content-transfer-encoding'],\n msg['content-type'])\n if self._mangle_from_:\n payload=fcre.sub('>From ',payload)\n self._write_lines(payload)\n \n \n _writeBody=_handle_text\n \n def _handle_multipart(self,msg):\n \n \n \n msgtexts=[]\n subparts=msg.get_payload()\n if subparts is None :\n subparts=[]\n elif isinstance(subparts,str):\n \n self.write(subparts)\n return\n elif not isinstance(subparts,list):\n \n subparts=[subparts]\n for part in subparts:\n s=self._new_buffer()\n g=self.clone(s)\n g.flatten(part,unixfrom=False ,linesep=self._NL)\n msgtexts.append(s.getvalue())\n \n boundary=msg.get_boundary()\n if not boundary:\n \n \n alltext=self._encoded_NL.join(msgtexts)\n boundary=self._make_boundary(alltext)\n msg.set_boundary(boundary)\n \n if msg.preamble is not None :\n if self._mangle_from_:\n preamble=fcre.sub('>From ',msg.preamble)\n else :\n preamble=msg.preamble\n self._write_lines(preamble)\n self.write(self._NL)\n \n self.write('--'+boundary+self._NL)\n \n if msgtexts:\n self._fp.write(msgtexts.pop(0))\n \n \n \n for body_part in msgtexts:\n \n self.write(self._NL+'--'+boundary+self._NL)\n \n self._fp.write(body_part)\n \n self.write(self._NL+'--'+boundary+'--'+self._NL)\n if msg.epilogue is not None :\n if self._mangle_from_:\n epilogue=fcre.sub('>From ',msg.epilogue)\n else :\n epilogue=msg.epilogue\n self._write_lines(epilogue)\n \n def _handle_multipart_signed(self,msg):\n \n \n \n p=self.policy\n self.policy=p.clone(max_line_length=0)\n try :\n self._handle_multipart(msg)\n finally :\n self.policy=p\n \n def _handle_message_delivery_status(self,msg):\n \n \n \n blocks=[]\n for part in msg.get_payload():\n s=self._new_buffer()\n g=self.clone(s)\n g.flatten(part,unixfrom=False ,linesep=self._NL)\n text=s.getvalue()\n lines=text.split(self._encoded_NL)\n \n if lines and lines[-1]==self._encoded_EMPTY:\n blocks.append(self._encoded_NL.join(lines[:-1]))\n else :\n blocks.append(text)\n \n \n \n self._fp.write(self._encoded_NL.join(blocks))\n \n def _handle_message(self,msg):\n s=self._new_buffer()\n g=self.clone(s)\n \n \n \n \n \n \n \n \n \n payload=msg._payload\n if isinstance(payload,list):\n g.flatten(msg.get_payload(0),unixfrom=False ,linesep=self._NL)\n payload=s.getvalue()\n else :\n payload=self._encode(payload)\n self._fp.write(payload)\n \n \n \n \n \n \n @classmethod\n def _make_boundary(cls,text=None ):\n \n \n token=random.randrange(sys.maxsize)\n boundary=('='*15)+(_fmt %token)+'=='\n if text is None :\n return boundary\n b=boundary\n counter=0\n while True :\n cre=cls._compile_re('^--'+re.escape(b)+'(--)?$',re.MULTILINE)\n if not cre.search(text):\n break\n b=boundary+'.'+str(counter)\n counter +=1\n return b\n \n @classmethod\n def _compile_re(cls,s,flags):\n return re.compile(s,flags)\n \n \nclass BytesGenerator(Generator):\n ''\n\n\n\n\n\n\n\n\n\n \n \n def write(self,s):\n self._fp.write(s.encode('ascii','surrogateescape'))\n \n def _new_buffer(self):\n return BytesIO()\n \n def _encode(self,s):\n return s.encode('ascii')\n \n def _write_headers(self,msg):\n \n \n for h,v in msg.raw_items():\n self._fp.write(self.policy.fold_binary(h,v))\n \n self.write(self._NL)\n \n def _handle_text(self,msg):\n \n \n if msg._payload is None :\n return\n if _has_surrogates(msg._payload)and not self.policy.cte_type =='7bit':\n if self._mangle_from_:\n msg._payload=fcre.sub(\">From \",msg._payload)\n self._write_lines(msg._payload)\n else :\n super(BytesGenerator,self)._handle_text(msg)\n \n \n _writeBody=_handle_text\n \n @classmethod\n def _compile_re(cls,s,flags):\n return re.compile(s.encode('ascii'),flags)\n \n \n \n_FMT='[Non-text (%(type)s) part of message omitted, filename %(filename)s]'\n\nclass DecodedGenerator(Generator):\n ''\n\n\n\n \n def __init__(self,outfp,mangle_from_=None ,maxheaderlen=None ,fmt=None ,*,\n policy=None ):\n ''\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n \n Generator.__init__(self,outfp,mangle_from_,maxheaderlen,\n policy=policy)\n if fmt is None :\n self._fmt=_FMT\n else :\n self._fmt=fmt\n \n def _dispatch(self,msg):\n for part in msg.walk():\n maintype=part.get_content_maintype()\n if maintype =='text':\n print(part.get_payload(decode=False ),file=self)\n elif maintype =='multipart':\n \n pass\n else :\n print(self._fmt %{\n 'type':part.get_content_type(),\n 'maintype':part.get_content_maintype(),\n 'subtype':part.get_content_subtype(),\n 'filename':part.get_filename('[no filename]'),\n 'description':part.get('Content-Description',\n '[no description]'),\n 'encoding':part.get('Content-Transfer-Encoding',\n '[no encoding]'),\n },file=self)\n \n \n \n \n_width=len(repr(sys.maxsize -1))\n_fmt='%%0%dd'%_width\n\n\n_make_boundary=Generator._make_boundary\n", ["copy", "email.utils", "io", "random", "re", "sys", "time"]], "struct": [".py", "__all__=[\n\n'calcsize','pack','pack_into','unpack','unpack_from',\n'iter_unpack',\n\n\n'Struct',\n\n\n'error'\n]\n\nfrom _struct import *\nfrom _struct import _clearcache\nfrom _struct import __doc__\n", ["_struct"]], "email.headerregistry": [".py", "''\n\n\n\n\n\n\n\n\nfrom types import MappingProxyType\n\nfrom email import utils\nfrom email import errors\nfrom email import _header_value_parser as parser\n\nclass Address:\n\n def __init__(self,display_name='',username='',domain='',addr_spec=None ):\n ''\n\n\n\n\n\n\n\n\n\n\n\n\n\n \n \n \n \n \n if addr_spec is not None :\n if username or domain:\n raise TypeError(\"addrspec specified when username and/or \"\n \"domain also specified\")\n a_s,rest=parser.get_addr_spec(addr_spec)\n if rest:\n raise ValueError(\"Invalid addr_spec; only '{}' \"\n \"could be parsed from '{}'\".format(\n a_s,addr_spec))\n if a_s.all_defects:\n raise a_s.all_defects[0]\n username=a_s.local_part\n domain=a_s.domain\n self._display_name=display_name\n self._username=username\n self._domain=domain\n \n @property\n def display_name(self):\n return self._display_name\n \n @property\n def username(self):\n return self._username\n \n @property\n def domain(self):\n return self._domain\n \n @property\n def addr_spec(self):\n ''\n\n \n nameset=set(self.username)\n if len(nameset)>len(nameset -parser.DOT_ATOM_ENDS):\n lp=parser.quote_string(self.username)\n else :\n lp=self.username\n if self.domain:\n return lp+'@'+self.domain\n if not lp:\n return '<>'\n return lp\n \n def __repr__(self):\n return \"{}(display_name={!r}, username={!r}, domain={!r})\".format(\n self.__class__.__name__,\n self.display_name,self.username,self.domain)\n \n def __str__(self):\n nameset=set(self.display_name)\n if len(nameset)>len(nameset -parser.SPECIALS):\n disp=parser.quote_string(self.display_name)\n else :\n disp=self.display_name\n if disp:\n addr_spec=''if self.addr_spec =='<>'else self.addr_spec\n return \"{} <{}>\".format(disp,addr_spec)\n return self.addr_spec\n \n def __eq__(self,other):\n if type(other)!=type(self):\n return False\n return (self.display_name ==other.display_name and\n self.username ==other.username and\n self.domain ==other.domain)\n \n \nclass Group:\n\n def __init__(self,display_name=None ,addresses=None ):\n ''\n\n\n\n\n\n\n\n\n\n\n\n\n \n self._display_name=display_name\n self._addresses=tuple(addresses)if addresses else tuple()\n \n @property\n def display_name(self):\n return self._display_name\n \n @property\n def addresses(self):\n return self._addresses\n \n def __repr__(self):\n return \"{}(display_name={!r}, addresses={!r}\".format(\n self.__class__.__name__,\n self.display_name,self.addresses)\n \n def __str__(self):\n if self.display_name is None and len(self.addresses)==1:\n return str(self.addresses[0])\n disp=self.display_name\n if disp is not None :\n nameset=set(disp)\n if len(nameset)>len(nameset -parser.SPECIALS):\n disp=parser.quote_string(disp)\n adrstr=\", \".join(str(x)for x in self.addresses)\n adrstr=' '+adrstr if adrstr else adrstr\n return \"{}:{};\".format(disp,adrstr)\n \n def __eq__(self,other):\n if type(other)!=type(self):\n return False\n return (self.display_name ==other.display_name and\n self.addresses ==other.addresses)\n \n \n \n \nclass BaseHeader(str):\n\n ''\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n \n \n def __new__(cls,name,value):\n kwds={'defects':[]}\n cls.parse(value,kwds)\n if utils._has_surrogates(kwds['decoded']):\n kwds['decoded']=utils._sanitize(kwds['decoded'])\n self=str.__new__(cls,kwds['decoded'])\n del kwds['decoded']\n self.init(name,**kwds)\n return self\n \n def init(self,name,*,parse_tree,defects):\n self._name=name\n self._parse_tree=parse_tree\n self._defects=defects\n \n @property\n def name(self):\n return self._name\n \n @property\n def defects(self):\n return tuple(self._defects)\n \n def __reduce__(self):\n return (\n _reconstruct_header,\n (\n self.__class__.__name__,\n self.__class__.__bases__,\n str(self),\n ),\n self.__dict__)\n \n @classmethod\n def _reconstruct(cls,value):\n return str.__new__(cls,value)\n \n def fold(self,*,policy):\n ''\n\n\n\n\n\n\n\n\n\n\n\n\n\n \n \n header=parser.Header([\n parser.HeaderLabel([\n parser.ValueTerminal(self.name,'header-name'),\n parser.ValueTerminal(':','header-sep')]),\n ])\n if self._parse_tree:\n header.append(\n parser.CFWSList([parser.WhiteSpaceTerminal(' ','fws')]))\n header.append(self._parse_tree)\n return header.fold(policy=policy)\n \n \ndef _reconstruct_header(cls_name,bases,value):\n return type(cls_name,bases,{})._reconstruct(value)\n \n \nclass UnstructuredHeader:\n\n max_count=None\n value_parser=staticmethod(parser.get_unstructured)\n \n @classmethod\n def parse(cls,value,kwds):\n kwds['parse_tree']=cls.value_parser(value)\n kwds['decoded']=str(kwds['parse_tree'])\n \n \nclass UniqueUnstructuredHeader(UnstructuredHeader):\n\n max_count=1\n \n \nclass DateHeader:\n\n ''\n\n\n\n\n\n\n \n \n max_count=None\n \n \n value_parser=staticmethod(parser.get_unstructured)\n \n @classmethod\n def parse(cls,value,kwds):\n if not value:\n kwds['defects'].append(errors.HeaderMissingRequiredValue())\n kwds['datetime']=None\n kwds['decoded']=''\n kwds['parse_tree']=parser.TokenList()\n return\n if isinstance(value,str):\n value=utils.parsedate_to_datetime(value)\n kwds['datetime']=value\n kwds['decoded']=utils.format_datetime(kwds['datetime'])\n kwds['parse_tree']=cls.value_parser(kwds['decoded'])\n \n def init(self,*args,**kw):\n self._datetime=kw.pop('datetime')\n super().init(*args,**kw)\n \n @property\n def datetime(self):\n return self._datetime\n \n \nclass UniqueDateHeader(DateHeader):\n\n max_count=1\n \n \nclass AddressHeader:\n\n max_count=None\n \n @staticmethod\n def value_parser(value):\n address_list,value=parser.get_address_list(value)\n assert not value,'this should not happen'\n return address_list\n \n @classmethod\n def parse(cls,value,kwds):\n if isinstance(value,str):\n \n \n kwds['parse_tree']=address_list=cls.value_parser(value)\n groups=[]\n for addr in address_list.addresses:\n groups.append(Group(addr.display_name,\n [Address(mb.display_name or '',\n mb.local_part or '',\n mb.domain or '')\n for mb in addr.all_mailboxes]))\n defects=list(address_list.all_defects)\n else :\n \n if not hasattr(value,'__iter__'):\n value=[value]\n groups=[Group(None ,[item])if not hasattr(item,'addresses')\n else item\n for item in value]\n defects=[]\n kwds['groups']=groups\n kwds['defects']=defects\n kwds['decoded']=', '.join([str(item)for item in groups])\n if 'parse_tree'not in kwds:\n kwds['parse_tree']=cls.value_parser(kwds['decoded'])\n \n def init(self,*args,**kw):\n self._groups=tuple(kw.pop('groups'))\n self._addresses=None\n super().init(*args,**kw)\n \n @property\n def groups(self):\n return self._groups\n \n @property\n def addresses(self):\n if self._addresses is None :\n self._addresses=tuple(address for group in self._groups\n for address in group.addresses)\n return self._addresses\n \n \nclass UniqueAddressHeader(AddressHeader):\n\n max_count=1\n \n \nclass SingleAddressHeader(AddressHeader):\n\n @property\n def address(self):\n if len(self.addresses)!=1:\n raise ValueError((\"value of single address header {} is not \"\n \"a single address\").format(self.name))\n return self.addresses[0]\n \n \nclass UniqueSingleAddressHeader(SingleAddressHeader):\n\n max_count=1\n \n \nclass MIMEVersionHeader:\n\n max_count=1\n \n value_parser=staticmethod(parser.parse_mime_version)\n \n @classmethod\n def parse(cls,value,kwds):\n kwds['parse_tree']=parse_tree=cls.value_parser(value)\n kwds['decoded']=str(parse_tree)\n kwds['defects'].extend(parse_tree.all_defects)\n kwds['major']=None if parse_tree.minor is None else parse_tree.major\n kwds['minor']=parse_tree.minor\n if parse_tree.minor is not None :\n kwds['version']='{}.{}'.format(kwds['major'],kwds['minor'])\n else :\n kwds['version']=None\n \n def init(self,*args,**kw):\n self._version=kw.pop('version')\n self._major=kw.pop('major')\n self._minor=kw.pop('minor')\n super().init(*args,**kw)\n \n @property\n def major(self):\n return self._major\n \n @property\n def minor(self):\n return self._minor\n \n @property\n def version(self):\n return self._version\n \n \nclass ParameterizedMIMEHeader:\n\n\n\n\n max_count=1\n \n @classmethod\n def parse(cls,value,kwds):\n kwds['parse_tree']=parse_tree=cls.value_parser(value)\n kwds['decoded']=str(parse_tree)\n kwds['defects'].extend(parse_tree.all_defects)\n if parse_tree.params is None :\n kwds['params']={}\n else :\n \n kwds['params']={utils._sanitize(name).lower():\n utils._sanitize(value)\n for name,value in parse_tree.params}\n \n def init(self,*args,**kw):\n self._params=kw.pop('params')\n super().init(*args,**kw)\n \n @property\n def params(self):\n return MappingProxyType(self._params)\n \n \nclass ContentTypeHeader(ParameterizedMIMEHeader):\n\n value_parser=staticmethod(parser.parse_content_type_header)\n \n def init(self,*args,**kw):\n super().init(*args,**kw)\n self._maintype=utils._sanitize(self._parse_tree.maintype)\n self._subtype=utils._sanitize(self._parse_tree.subtype)\n \n @property\n def maintype(self):\n return self._maintype\n \n @property\n def subtype(self):\n return self._subtype\n \n @property\n def content_type(self):\n return self.maintype+'/'+self.subtype\n \n \nclass ContentDispositionHeader(ParameterizedMIMEHeader):\n\n value_parser=staticmethod(parser.parse_content_disposition_header)\n \n def init(self,*args,**kw):\n super().init(*args,**kw)\n cd=self._parse_tree.content_disposition\n self._content_disposition=cd if cd is None else utils._sanitize(cd)\n \n @property\n def content_disposition(self):\n return self._content_disposition\n \n \nclass ContentTransferEncodingHeader:\n\n max_count=1\n \n value_parser=staticmethod(parser.parse_content_transfer_encoding_header)\n \n @classmethod\n def parse(cls,value,kwds):\n kwds['parse_tree']=parse_tree=cls.value_parser(value)\n kwds['decoded']=str(parse_tree)\n kwds['defects'].extend(parse_tree.all_defects)\n \n def init(self,*args,**kw):\n super().init(*args,**kw)\n self._cte=utils._sanitize(self._parse_tree.cte)\n \n @property\n def cte(self):\n return self._cte\n \n \n \n \n_default_header_map={\n'subject':UniqueUnstructuredHeader,\n'date':UniqueDateHeader,\n'resent-date':DateHeader,\n'orig-date':UniqueDateHeader,\n'sender':UniqueSingleAddressHeader,\n'resent-sender':SingleAddressHeader,\n'to':UniqueAddressHeader,\n'resent-to':AddressHeader,\n'cc':UniqueAddressHeader,\n'resent-cc':AddressHeader,\n'bcc':UniqueAddressHeader,\n'resent-bcc':AddressHeader,\n'from':UniqueAddressHeader,\n'resent-from':AddressHeader,\n'reply-to':UniqueAddressHeader,\n'mime-version':MIMEVersionHeader,\n'content-type':ContentTypeHeader,\n'content-disposition':ContentDispositionHeader,\n'content-transfer-encoding':ContentTransferEncodingHeader,\n}\n\nclass HeaderRegistry:\n\n ''\n \n def __init__(self,base_class=BaseHeader,default_class=UnstructuredHeader,\n use_default_map=True ):\n ''\n\n\n\n\n\n\n\n\n \n self.registry={}\n self.base_class=base_class\n self.default_class=default_class\n if use_default_map:\n self.registry.update(_default_header_map)\n \n def map_to_type(self,name,cls):\n ''\n\n \n self.registry[name.lower()]=cls\n \n def __getitem__(self,name):\n cls=self.registry.get(name.lower(),self.default_class)\n return type('_'+cls.__name__,(cls,self.base_class),{})\n \n def __call__(self,name,value):\n ''\n\n\n\n\n\n\n\n \n return self[name](name,value)\n", ["email", "email._header_value_parser", "email.errors", "email.utils", "types"]], "unittest.result": [".py", "''\n\nimport io\nimport sys\nimport traceback\n\nfrom . import util\nfrom functools import wraps\n\n__unittest=True\n\ndef failfast(method):\n @wraps(method)\n def inner(self,*args,**kw):\n if getattr(self,'failfast',False ):\n self.stop()\n return method(self,*args,**kw)\n return inner\n \nSTDOUT_LINE='\\nStdout:\\n%s'\nSTDERR_LINE='\\nStderr:\\n%s'\n\n\nclass TestResult(object):\n ''\n\n\n\n\n\n\n\n\n \n _previousTestClass=None\n _testRunEntered=False\n _moduleSetUpFailed=False\n def __init__(self,stream=None ,descriptions=None ,verbosity=None ):\n self.failfast=False\n self.failures=[]\n self.errors=[]\n self.testsRun=0\n self.skipped=[]\n self.expectedFailures=[]\n self.unexpectedSuccesses=[]\n self.shouldStop=False\n self.buffer=False\n self.tb_locals=False\n self._stdout_buffer=None\n self._stderr_buffer=None\n self._original_stdout=sys.stdout\n self._original_stderr=sys.stderr\n self._mirrorOutput=False\n \n def printErrors(self):\n ''\n \n def startTest(self,test):\n ''\n self.testsRun +=1\n self._mirrorOutput=False\n self._setupStdout()\n \n def _setupStdout(self):\n if self.buffer:\n if self._stderr_buffer is None :\n self._stderr_buffer=io.StringIO()\n self._stdout_buffer=io.StringIO()\n sys.stdout=self._stdout_buffer\n sys.stderr=self._stderr_buffer\n \n def startTestRun(self):\n ''\n\n\n \n \n def stopTest(self,test):\n ''\n self._restoreStdout()\n self._mirrorOutput=False\n \n def _restoreStdout(self):\n if self.buffer:\n if self._mirrorOutput:\n output=sys.stdout.getvalue()\n error=sys.stderr.getvalue()\n if output:\n if not output.endswith('\\n'):\n output +='\\n'\n self._original_stdout.write(STDOUT_LINE %output)\n if error:\n if not error.endswith('\\n'):\n error +='\\n'\n self._original_stderr.write(STDERR_LINE %error)\n \n sys.stdout=self._original_stdout\n sys.stderr=self._original_stderr\n self._stdout_buffer.seek(0)\n self._stdout_buffer.truncate()\n self._stderr_buffer.seek(0)\n self._stderr_buffer.truncate()\n \n def stopTestRun(self):\n ''\n\n\n \n \n @failfast\n def addError(self,test,err):\n ''\n\n \n self.errors.append((test,self._exc_info_to_string(err,test)))\n self._mirrorOutput=True\n \n @failfast\n def addFailure(self,test,err):\n ''\n \n self.failures.append((test,self._exc_info_to_string(err,test)))\n self._mirrorOutput=True\n \n def addSubTest(self,test,subtest,err):\n ''\n\n\n \n \n \n if err is not None :\n if getattr(self,'failfast',False ):\n self.stop()\n if issubclass(err[0],test.failureException):\n errors=self.failures\n else :\n errors=self.errors\n errors.append((subtest,self._exc_info_to_string(err,test)))\n self._mirrorOutput=True\n \n def addSuccess(self,test):\n ''\n pass\n \n def addSkip(self,test,reason):\n ''\n self.skipped.append((test,reason))\n \n def addExpectedFailure(self,test,err):\n ''\n self.expectedFailures.append(\n (test,self._exc_info_to_string(err,test)))\n \n @failfast\n def addUnexpectedSuccess(self,test):\n ''\n self.unexpectedSuccesses.append(test)\n \n def wasSuccessful(self):\n ''\n \n \n \n return ((len(self.failures)==len(self.errors)==0)and\n (not hasattr(self,'unexpectedSuccesses')or\n len(self.unexpectedSuccesses)==0))\n \n def stop(self):\n ''\n self.shouldStop=True\n \n def _exc_info_to_string(self,err,test):\n ''\n exctype,value,tb=err\n \n while tb and self._is_relevant_tb_level(tb):\n tb=tb.tb_next\n \n if exctype is test.failureException:\n \n length=self._count_relevant_tb_levels(tb)\n else :\n length=None\n tb_e=traceback.TracebackException(\n exctype,value,tb,limit=length,capture_locals=self.tb_locals)\n msgLines=list(tb_e.format())\n \n if self.buffer:\n output=sys.stdout.getvalue()\n error=sys.stderr.getvalue()\n if output:\n if not output.endswith('\\n'):\n output +='\\n'\n msgLines.append(STDOUT_LINE %output)\n if error:\n if not error.endswith('\\n'):\n error +='\\n'\n msgLines.append(STDERR_LINE %error)\n return ''.join(msgLines)\n \n \n def _is_relevant_tb_level(self,tb):\n return '__unittest'in tb.tb_frame.f_globals\n \n def _count_relevant_tb_levels(self,tb):\n length=0\n while tb and not self._is_relevant_tb_level(tb):\n length +=1\n tb=tb.tb_next\n return length\n \n def __repr__(self):\n return (\"<%s run=%i errors=%i failures=%i>\"%\n (util.strclass(self.__class__),self.testsRun,len(self.errors),\n len(self.failures)))\n", ["functools", "io", "sys", "traceback", "unittest", "unittest.util"]], "collections.abc": [".py", "from _collections_abc import *\nfrom _collections_abc import __all__\n", ["_collections_abc"]], "collections": [".py", "''\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n__all__=['deque','defaultdict','namedtuple','UserDict','UserList',\n'UserString','Counter','OrderedDict','ChainMap']\n\nimport _collections_abc\nfrom operator import itemgetter as _itemgetter,eq as _eq\nfrom keyword import iskeyword as _iskeyword\nimport sys as _sys\nimport heapq as _heapq\nfrom _weakref import proxy as _proxy\nfrom itertools import repeat as _repeat,chain as _chain,starmap as _starmap\nfrom reprlib import recursive_repr as _recursive_repr\n\ntry :\n from _collections import deque\nexcept ImportError:\n pass\nelse :\n _collections_abc.MutableSequence.register(deque)\n \ntry :\n from _collections import defaultdict\nexcept ImportError:\n pass\n \n \ndef __getattr__(name):\n\n\n\n if name in _collections_abc.__all__:\n obj=getattr(_collections_abc,name)\n import warnings\n warnings.warn(\"Using or importing the ABCs from 'collections' instead \"\n \"of from 'collections.abc' is deprecated, \"\n \"and in 3.8 it will stop working\",\n DeprecationWarning,stacklevel=2)\n globals()[name]=obj\n return obj\n raise AttributeError(f'module {__name__!r} has no attribute {name!r}')\n \n \n \n \n \nclass _OrderedDictKeysView(_collections_abc.KeysView):\n\n def __reversed__(self):\n yield from reversed(self._mapping)\n \nclass _OrderedDictItemsView(_collections_abc.ItemsView):\n\n def __reversed__(self):\n for key in reversed(self._mapping):\n yield (key,self._mapping[key])\n \nclass _OrderedDictValuesView(_collections_abc.ValuesView):\n\n def __reversed__(self):\n for key in reversed(self._mapping):\n yield self._mapping[key]\n \nclass _Link(object):\n __slots__='prev','next','key','__weakref__'\n \nclass OrderedDict(dict):\n ''\n \n \n \n \n \n \n \n \n \n \n \n \n \n def __init__(*args,**kwds):\n ''\n\n \n if not args:\n raise TypeError(\"descriptor '__init__' of 'OrderedDict' object \"\n \"needs an argument\")\n self,*args=args\n if len(args)>1:\n raise TypeError('expected at most 1 arguments, got %d'%len(args))\n try :\n self.__root\n except AttributeError:\n self.__hardroot=_Link()\n self.__root=root=_proxy(self.__hardroot)\n root.prev=root.next=root\n self.__map={}\n self.__update(*args,**kwds)\n \n def __setitem__(self,key,value,\n dict_setitem=dict.__setitem__,proxy=_proxy,Link=_Link):\n ''\n \n \n if key not in self:\n self.__map[key]=link=Link()\n root=self.__root\n last=root.prev\n link.prev,link.next,link.key=last,root,key\n last.next=link\n root.prev=proxy(link)\n dict_setitem(self,key,value)\n \n def __delitem__(self,key,dict_delitem=dict.__delitem__):\n ''\n \n \n dict_delitem(self,key)\n link=self.__map.pop(key)\n link_prev=link.prev\n link_next=link.next\n link_prev.next=link_next\n link_next.prev=link_prev\n link.prev=None\n link.next=None\n \n def __iter__(self):\n ''\n \n root=self.__root\n curr=root.next\n while curr is not root:\n yield curr.key\n curr=curr.next\n \n def __reversed__(self):\n ''\n \n root=self.__root\n curr=root.prev\n while curr is not root:\n yield curr.key\n curr=curr.prev\n \n def clear(self):\n ''\n root=self.__root\n root.prev=root.next=root\n self.__map.clear()\n dict.clear(self)\n \n def popitem(self,last=True ):\n ''\n\n\n \n if not self:\n raise KeyError('dictionary is empty')\n root=self.__root\n if last:\n link=root.prev\n link_prev=link.prev\n link_prev.next=root\n root.prev=link_prev\n else :\n link=root.next\n link_next=link.next\n root.next=link_next\n link_next.prev=root\n key=link.key\n del self.__map[key]\n value=dict.pop(self,key)\n return key,value\n \n def move_to_end(self,key,last=True ):\n ''\n\n\n \n link=self.__map[key]\n link_prev=link.prev\n link_next=link.next\n soft_link=link_next.prev\n link_prev.next=link_next\n link_next.prev=link_prev\n root=self.__root\n if last:\n last=root.prev\n link.prev=last\n link.next=root\n root.prev=soft_link\n last.next=link\n else :\n first=root.next\n link.prev=root\n link.next=first\n first.prev=soft_link\n root.next=link\n \n def __sizeof__(self):\n sizeof=_sys.getsizeof\n n=len(self)+1\n size=sizeof(self.__dict__)\n size +=sizeof(self.__map)*2\n size +=sizeof(self.__hardroot)*n\n size +=sizeof(self.__root)*n\n return size\n \n update=__update=_collections_abc.MutableMapping.update\n \n def keys(self):\n ''\n return _OrderedDictKeysView(self)\n \n def items(self):\n ''\n return _OrderedDictItemsView(self)\n \n def values(self):\n ''\n return _OrderedDictValuesView(self)\n \n __ne__=_collections_abc.MutableMapping.__ne__\n \n __marker=object()\n \n def pop(self,key,default=__marker):\n ''\n\n\n\n \n if key in self:\n result=self[key]\n del self[key]\n return result\n if default is self.__marker:\n raise KeyError(key)\n return default\n \n def setdefault(self,key,default=None ):\n ''\n\n\n \n if key in self:\n return self[key]\n self[key]=default\n return default\n \n @_recursive_repr()\n def __repr__(self):\n ''\n if not self:\n return '%s()'%(self.__class__.__name__,)\n return '%s(%r)'%(self.__class__.__name__,list(self.items()))\n \n def __reduce__(self):\n ''\n inst_dict=vars(self).copy()\n for k in vars(OrderedDict()):\n inst_dict.pop(k,None )\n return self.__class__,(),inst_dict or None ,None ,iter(self.items())\n \n def copy(self):\n ''\n return self.__class__(self)\n \n @classmethod\n def fromkeys(cls,iterable,value=None ):\n ''\n \n self=cls()\n for key in iterable:\n self[key]=value\n return self\n \n def __eq__(self,other):\n ''\n\n\n \n if isinstance(other,OrderedDict):\n return dict.__eq__(self,other)and all(map(_eq,self,other))\n return dict.__eq__(self,other)\n \n \ntry :\n from _collections import OrderedDict\nexcept ImportError:\n\n pass\n \n \n \n \n \n \n_nt_itemgetters={}\n\ndef namedtuple(typename,field_names,*,rename=False ,defaults=None ,module=None ):\n ''\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n \n \n \n \n if isinstance(field_names,str):\n field_names=field_names.replace(',',' ').split()\n field_names=list(map(str,field_names))\n typename=_sys.intern(str(typename))\n \n if rename:\n seen=set()\n for index,name in enumerate(field_names):\n if (not name.isidentifier()\n or _iskeyword(name)\n or name.startswith('_')\n or name in seen):\n field_names[index]=f'_{index}'\n seen.add(name)\n \n for name in [typename]+field_names:\n if type(name)is not str:\n raise TypeError('Type names and field names must be strings')\n if not name.isidentifier():\n raise ValueError('Type names and field names must be valid '\n f'identifiers: {name!r}')\n if _iskeyword(name):\n raise ValueError('Type names and field names cannot be a '\n f'keyword: {name!r}')\n \n seen=set()\n for name in field_names:\n if name.startswith('_')and not rename:\n raise ValueError('Field names cannot start with an underscore: '\n f'{name!r}')\n if name in seen:\n raise ValueError(f'Encountered duplicate field name: {name!r}')\n seen.add(name)\n \n field_defaults={}\n if defaults is not None :\n defaults=tuple(defaults)\n if len(defaults)>len(field_names):\n raise TypeError('Got more default values than field names')\n field_defaults=dict(reversed(list(zip(reversed(field_names),\n reversed(defaults)))))\n \n \n field_names=tuple(map(_sys.intern,field_names))\n num_fields=len(field_names)\n arg_list=repr(field_names).replace(\"'\",\"\")[1:-1]\n repr_fmt='('+', '.join(f'{name}=%r'for name in field_names)+')'\n tuple_new=tuple.__new__\n _len=len\n \n \n \n s=f'def __new__(_cls, {arg_list}): return _tuple_new(_cls, ({arg_list}))'\n namespace={'_tuple_new':tuple_new,'__name__':f'namedtuple_{typename}'}\n \n exec(s,namespace)\n __new__=namespace['__new__']\n __new__.__doc__=f'Create new instance of {typename}({arg_list})'\n if defaults is not None :\n __new__.__defaults__=defaults\n \n @classmethod\n def _make(cls,iterable):\n result=tuple_new(cls,iterable)\n if _len(result)!=num_fields:\n raise TypeError(f'Expected {num_fields} arguments, got {len(result)}')\n return result\n \n _make.__func__.__doc__=(f'Make a new {typename} object from a sequence '\n 'or iterable')\n \n def _replace(_self,**kwds):\n result=_self._make(map(kwds.pop,field_names,_self))\n if kwds:\n raise ValueError(f'Got unexpected field names: {list(kwds)!r}')\n return result\n \n _replace.__doc__=(f'Return a new {typename} object replacing specified '\n 'fields with new values')\n \n def __repr__(self):\n ''\n return self.__class__.__name__+repr_fmt %self\n \n def _asdict(self):\n ''\n return OrderedDict(zip(self._fields,self))\n \n def __getnewargs__(self):\n ''\n return tuple(self)\n \n \n \n for method in (__new__,_make.__func__,_replace,\n __repr__,_asdict,__getnewargs__):\n method.__qualname__=f'{typename}.{method.__name__}'\n \n \n \n class_namespace={\n '__doc__':f'{typename}({arg_list})',\n '__slots__':(),\n '_fields':field_names,\n '_fields_defaults':field_defaults,\n '__new__':__new__,\n '_make':_make,\n '_replace':_replace,\n '__repr__':__repr__,\n '_asdict':_asdict,\n '__getnewargs__':__getnewargs__,\n }\n cache=_nt_itemgetters\n for index,name in enumerate(field_names):\n try :\n itemgetter_object,doc=cache[index]\n except KeyError:\n itemgetter_object=_itemgetter(index)\n doc=f'Alias for field number {index}'\n cache[index]=itemgetter_object,doc\n class_namespace[name]=property(itemgetter_object,doc=doc)\n \n result=type(typename,(tuple,),class_namespace)\n \n \n \n \n \n \n if module is None :\n try :\n module=_sys._getframe(1).f_globals.get('__name__','__main__')\n except (AttributeError,ValueError):\n pass\n if module is not None :\n result.__module__=module\n \n return result\n \n \n \n \n \n \ndef _count_elements(mapping,iterable):\n ''\n mapping_get=mapping.get\n for elem in iterable:\n mapping[elem]=mapping_get(elem,0)+1\n \ntry :\n from _collections import _count_elements\nexcept ImportError:\n pass\n \nclass Counter(dict):\n ''\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n \n \n \n \n \n \n \n \n def __init__(*args,**kwds):\n ''\n\n\n\n\n\n\n\n\n \n if not args:\n raise TypeError(\"descriptor '__init__' of 'Counter' object \"\n \"needs an argument\")\n self,*args=args\n if len(args)>1:\n raise TypeError('expected at most 1 arguments, got %d'%len(args))\n super(Counter,self).__init__()\n self.update(*args,**kwds)\n \n def __missing__(self,key):\n ''\n \n return 0\n \n def most_common(self,n=None ):\n ''\n\n\n\n\n\n \n \n if n is None :\n return sorted(self.items(),key=_itemgetter(1),reverse=True )\n return _heapq.nlargest(n,self.items(),key=_itemgetter(1))\n \n def elements(self):\n ''\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n \n \n return _chain.from_iterable(_starmap(_repeat,self.items()))\n \n \n \n @classmethod\n def fromkeys(cls,iterable,v=None ):\n \n \n raise NotImplementedError(\n 'Counter.fromkeys() is undefined. Use Counter(iterable) instead.')\n \n def update(*args,**kwds):\n ''\n\n\n\n\n\n\n\n\n\n\n \n \n \n \n \n \n \n \n if not args:\n raise TypeError(\"descriptor 'update' of 'Counter' object \"\n \"needs an argument\")\n self,*args=args\n if len(args)>1:\n raise TypeError('expected at most 1 arguments, got %d'%len(args))\n iterable=args[0]if args else None\n if iterable is not None :\n if isinstance(iterable,_collections_abc.Mapping):\n if self:\n self_get=self.get\n for elem,count in iterable.items():\n self[elem]=count+self_get(elem,0)\n else :\n super(Counter,self).update(iterable)\n else :\n _count_elements(self,iterable)\n if kwds:\n self.update(kwds)\n \n def subtract(*args,**kwds):\n ''\n\n\n\n\n\n\n\n\n\n\n\n\n\n \n if not args:\n raise TypeError(\"descriptor 'subtract' of 'Counter' object \"\n \"needs an argument\")\n self,*args=args\n if len(args)>1:\n raise TypeError('expected at most 1 arguments, got %d'%len(args))\n iterable=args[0]if args else None\n if iterable is not None :\n self_get=self.get\n if isinstance(iterable,_collections_abc.Mapping):\n for elem,count in iterable.items():\n self[elem]=self_get(elem,0)-count\n else :\n for elem in iterable:\n self[elem]=self_get(elem,0)-1\n if kwds:\n self.subtract(kwds)\n \n def copy(self):\n ''\n return self.__class__(self)\n \n def __reduce__(self):\n return self.__class__,(dict(self),)\n \n def __delitem__(self,elem):\n ''\n if elem in self:\n super().__delitem__(elem)\n \n def __repr__(self):\n if not self:\n return '%s()'%self.__class__.__name__\n try :\n items=', '.join(map('%r: %r'.__mod__,self.most_common()))\n return '%s({%s})'%(self.__class__.__name__,items)\n except TypeError:\n \n return '{0}({1!r})'.format(self.__class__.__name__,dict(self))\n \n \n \n \n \n \n \n \n \n \n def __add__(self,other):\n ''\n\n\n\n\n \n if not isinstance(other,Counter):\n return NotImplemented\n result=Counter()\n for elem,count in self.items():\n newcount=count+other[elem]\n if newcount >0:\n result[elem]=newcount\n for elem,count in other.items():\n if elem not in self and count >0:\n result[elem]=count\n return result\n \n def __sub__(self,other):\n ''\n\n\n\n\n \n if not isinstance(other,Counter):\n return NotImplemented\n result=Counter()\n for elem,count in self.items():\n newcount=count -other[elem]\n if newcount >0:\n result[elem]=newcount\n for elem,count in other.items():\n if elem not in self and count <0:\n result[elem]=0 -count\n return result\n \n def __or__(self,other):\n ''\n\n\n\n\n \n if not isinstance(other,Counter):\n return NotImplemented\n result=Counter()\n for elem,count in self.items():\n other_count=other[elem]\n newcount=other_count if count <other_count else count\n if newcount >0:\n result[elem]=newcount\n for elem,count in other.items():\n if elem not in self and count >0:\n result[elem]=count\n return result\n \n def __and__(self,other):\n ''\n\n\n\n\n \n if not isinstance(other,Counter):\n return NotImplemented\n result=Counter()\n for elem,count in self.items():\n other_count=other[elem]\n newcount=count if count <other_count else other_count\n if newcount >0:\n result[elem]=newcount\n return result\n \n def __pos__(self):\n ''\n result=Counter()\n for elem,count in self.items():\n if count >0:\n result[elem]=count\n return result\n \n def __neg__(self):\n ''\n\n\n \n result=Counter()\n for elem,count in self.items():\n if count <0:\n result[elem]=0 -count\n return result\n \n def _keep_positive(self):\n ''\n nonpositive=[elem for elem,count in self.items()if not count >0]\n for elem in nonpositive:\n del self[elem]\n return self\n \n def __iadd__(self,other):\n ''\n\n\n\n\n\n\n \n for elem,count in other.items():\n self[elem]+=count\n return self._keep_positive()\n \n def __isub__(self,other):\n ''\n\n\n\n\n\n\n \n for elem,count in other.items():\n self[elem]-=count\n return self._keep_positive()\n \n def __ior__(self,other):\n ''\n\n\n\n\n\n\n \n for elem,other_count in other.items():\n count=self[elem]\n if other_count >count:\n self[elem]=other_count\n return self._keep_positive()\n \n def __iand__(self,other):\n ''\n\n\n\n\n\n\n \n for elem,count in self.items():\n other_count=other[elem]\n if other_count <count:\n self[elem]=other_count\n return self._keep_positive()\n \n \n \n \n \n \nclass ChainMap(_collections_abc.MutableMapping):\n ''\n\n\n\n\n\n\n\n\n\n\n \n \n def __init__(self,*maps):\n ''\n\n\n \n self.maps=list(maps)or [{}]\n \n def __missing__(self,key):\n raise KeyError(key)\n \n def __getitem__(self,key):\n for mapping in self.maps:\n try :\n return mapping[key]\n except KeyError:\n pass\n return self.__missing__(key)\n \n def get(self,key,default=None ):\n return self[key]if key in self else default\n \n def __len__(self):\n return len(set().union(*self.maps))\n \n def __iter__(self):\n d={}\n for mapping in reversed(self.maps):\n d.update(mapping)\n return iter(d)\n \n def __contains__(self,key):\n return any(key in m for m in self.maps)\n \n def __bool__(self):\n return any(self.maps)\n \n @_recursive_repr()\n def __repr__(self):\n return '{0.__class__.__name__}({1})'.format(\n self,', '.join(map(repr,self.maps)))\n \n @classmethod\n def fromkeys(cls,iterable,*args):\n ''\n return cls(dict.fromkeys(iterable,*args))\n \n def copy(self):\n ''\n return self.__class__(self.maps[0].copy(),*self.maps[1:])\n \n __copy__=copy\n \n def new_child(self,m=None ):\n ''\n\n \n if m is None :\n m={}\n return self.__class__(m,*self.maps)\n \n @property\n def parents(self):\n ''\n return self.__class__(*self.maps[1:])\n \n def __setitem__(self,key,value):\n self.maps[0][key]=value\n \n def __delitem__(self,key):\n try :\n del self.maps[0][key]\n except KeyError:\n raise KeyError('Key not found in the first mapping: {!r}'.format(key))\n \n def popitem(self):\n ''\n try :\n return self.maps[0].popitem()\n except KeyError:\n raise KeyError('No keys found in the first mapping.')\n \n def pop(self,key,*args):\n ''\n try :\n return self.maps[0].pop(key,*args)\n except KeyError:\n raise KeyError('Key not found in the first mapping: {!r}'.format(key))\n \n def clear(self):\n ''\n self.maps[0].clear()\n \n \n \n \n \n \nclass UserDict(_collections_abc.MutableMapping):\n\n\n def __init__(*args,**kwargs):\n if not args:\n raise TypeError(\"descriptor '__init__' of 'UserDict' object \"\n \"needs an argument\")\n self,*args=args\n if len(args)>1:\n raise TypeError('expected at most 1 arguments, got %d'%len(args))\n if args:\n dict=args[0]\n elif 'dict'in kwargs:\n dict=kwargs.pop('dict')\n import warnings\n warnings.warn(\"Passing 'dict' as keyword argument is deprecated\",\n DeprecationWarning,stacklevel=2)\n else :\n dict=None\n self.data={}\n if dict is not None :\n self.update(dict)\n if len(kwargs):\n self.update(kwargs)\n def __len__(self):return len(self.data)\n def __getitem__(self,key):\n if key in self.data:\n return self.data[key]\n if hasattr(self.__class__,\"__missing__\"):\n return self.__class__.__missing__(self,key)\n raise KeyError(key)\n def __setitem__(self,key,item):self.data[key]=item\n def __delitem__(self,key):del self.data[key]\n def __iter__(self):\n return iter(self.data)\n \n \n def __contains__(self,key):\n return key in self.data\n \n \n def __repr__(self):return repr(self.data)\n def copy(self):\n if self.__class__ is UserDict:\n return UserDict(self.data.copy())\n import copy\n data=self.data\n try :\n self.data={}\n c=copy.copy(self)\n finally :\n self.data=data\n c.update(self)\n return c\n @classmethod\n def fromkeys(cls,iterable,value=None ):\n d=cls()\n for key in iterable:\n d[key]=value\n return d\n \n \n \n \n \n \n \nclass UserList(_collections_abc.MutableSequence):\n ''\n def __init__(self,initlist=None ):\n self.data=[]\n if initlist is not None :\n \n if type(initlist)==type(self.data):\n self.data[:]=initlist\n elif isinstance(initlist,UserList):\n self.data[:]=initlist.data[:]\n else :\n self.data=list(initlist)\n def __repr__(self):return repr(self.data)\n def __lt__(self,other):return self.data <self.__cast(other)\n def __le__(self,other):return self.data <=self.__cast(other)\n def __eq__(self,other):return self.data ==self.__cast(other)\n def __gt__(self,other):return self.data >self.__cast(other)\n def __ge__(self,other):return self.data >=self.__cast(other)\n def __cast(self,other):\n return other.data if isinstance(other,UserList)else other\n def __contains__(self,item):return item in self.data\n def __len__(self):return len(self.data)\n def __getitem__(self,i):return self.data[i]\n def __setitem__(self,i,item):self.data[i]=item\n def __delitem__(self,i):del self.data[i]\n def __add__(self,other):\n if isinstance(other,UserList):\n return self.__class__(self.data+other.data)\n elif isinstance(other,type(self.data)):\n return self.__class__(self.data+other)\n return self.__class__(self.data+list(other))\n def __radd__(self,other):\n if isinstance(other,UserList):\n return self.__class__(other.data+self.data)\n elif isinstance(other,type(self.data)):\n return self.__class__(other+self.data)\n return self.__class__(list(other)+self.data)\n def __iadd__(self,other):\n if isinstance(other,UserList):\n self.data +=other.data\n elif isinstance(other,type(self.data)):\n self.data +=other\n else :\n self.data +=list(other)\n return self\n def __mul__(self,n):\n return self.__class__(self.data *n)\n __rmul__=__mul__\n def __imul__(self,n):\n self.data *=n\n return self\n def append(self,item):self.data.append(item)\n def insert(self,i,item):self.data.insert(i,item)\n def pop(self,i=-1):return self.data.pop(i)\n def remove(self,item):self.data.remove(item)\n def clear(self):self.data.clear()\n def copy(self):return self.__class__(self)\n def count(self,item):return self.data.count(item)\n def index(self,item,*args):return self.data.index(item,*args)\n def reverse(self):self.data.reverse()\n def sort(self,*args,**kwds):self.data.sort(*args,**kwds)\n def extend(self,other):\n if isinstance(other,UserList):\n self.data.extend(other.data)\n else :\n self.data.extend(other)\n \n \n \n \n \n \n \nclass UserString(_collections_abc.Sequence):\n def __init__(self,seq):\n if isinstance(seq,str):\n self.data=seq\n elif isinstance(seq,UserString):\n self.data=seq.data[:]\n else :\n self.data=str(seq)\n def __str__(self):return str(self.data)\n def __repr__(self):return repr(self.data)\n def __int__(self):return int(self.data)\n def __float__(self):return float(self.data)\n def __complex__(self):return complex(self.data)\n def __hash__(self):return hash(self.data)\n def __getnewargs__(self):\n return (self.data[:],)\n \n def __eq__(self,string):\n if isinstance(string,UserString):\n return self.data ==string.data\n return self.data ==string\n def __lt__(self,string):\n if isinstance(string,UserString):\n return self.data <string.data\n return self.data <string\n def __le__(self,string):\n if isinstance(string,UserString):\n return self.data <=string.data\n return self.data <=string\n def __gt__(self,string):\n if isinstance(string,UserString):\n return self.data >string.data\n return self.data >string\n def __ge__(self,string):\n if isinstance(string,UserString):\n return self.data >=string.data\n return self.data >=string\n \n def __contains__(self,char):\n if isinstance(char,UserString):\n char=char.data\n return char in self.data\n \n def __len__(self):return len(self.data)\n def __getitem__(self,index):return self.__class__(self.data[index])\n def __add__(self,other):\n if isinstance(other,UserString):\n return self.__class__(self.data+other.data)\n elif isinstance(other,str):\n return self.__class__(self.data+other)\n return self.__class__(self.data+str(other))\n def __radd__(self,other):\n if isinstance(other,str):\n return self.__class__(other+self.data)\n return self.__class__(str(other)+self.data)\n def __mul__(self,n):\n return self.__class__(self.data *n)\n __rmul__=__mul__\n def __mod__(self,args):\n return self.__class__(self.data %args)\n def __rmod__(self,format):\n return self.__class__(format %args)\n \n \n def capitalize(self):return self.__class__(self.data.capitalize())\n def casefold(self):\n return self.__class__(self.data.casefold())\n def center(self,width,*args):\n return self.__class__(self.data.center(width,*args))\n def count(self,sub,start=0,end=_sys.maxsize):\n if isinstance(sub,UserString):\n sub=sub.data\n return self.data.count(sub,start,end)\n def encode(self,encoding=None ,errors=None ):\n if encoding:\n if errors:\n return self.__class__(self.data.encode(encoding,errors))\n return self.__class__(self.data.encode(encoding))\n return self.__class__(self.data.encode())\n def endswith(self,suffix,start=0,end=_sys.maxsize):\n return self.data.endswith(suffix,start,end)\n def expandtabs(self,tabsize=8):\n return self.__class__(self.data.expandtabs(tabsize))\n def find(self,sub,start=0,end=_sys.maxsize):\n if isinstance(sub,UserString):\n sub=sub.data\n return self.data.find(sub,start,end)\n def format(self,*args,**kwds):\n return self.data.format(*args,**kwds)\n def format_map(self,mapping):\n return self.data.format_map(mapping)\n def index(self,sub,start=0,end=_sys.maxsize):\n return self.data.index(sub,start,end)\n def isalpha(self):return self.data.isalpha()\n def isalnum(self):return self.data.isalnum()\n def isascii(self):return self.data.isascii()\n def isdecimal(self):return self.data.isdecimal()\n def isdigit(self):return self.data.isdigit()\n def isidentifier(self):return self.data.isidentifier()\n def islower(self):return self.data.islower()\n def isnumeric(self):return self.data.isnumeric()\n def isprintable(self):return self.data.isprintable()\n def isspace(self):return self.data.isspace()\n def istitle(self):return self.data.istitle()\n def isupper(self):return self.data.isupper()\n def join(self,seq):return self.data.join(seq)\n def ljust(self,width,*args):\n return self.__class__(self.data.ljust(width,*args))\n def lower(self):return self.__class__(self.data.lower())\n def lstrip(self,chars=None ):return self.__class__(self.data.lstrip(chars))\n maketrans=str.maketrans\n def partition(self,sep):\n return self.data.partition(sep)\n def replace(self,old,new,maxsplit=-1):\n if isinstance(old,UserString):\n old=old.data\n if isinstance(new,UserString):\n new=new.data\n return self.__class__(self.data.replace(old,new,maxsplit))\n def rfind(self,sub,start=0,end=_sys.maxsize):\n if isinstance(sub,UserString):\n sub=sub.data\n return self.data.rfind(sub,start,end)\n def rindex(self,sub,start=0,end=_sys.maxsize):\n return self.data.rindex(sub,start,end)\n def rjust(self,width,*args):\n return self.__class__(self.data.rjust(width,*args))\n def rpartition(self,sep):\n return self.data.rpartition(sep)\n def rstrip(self,chars=None ):\n return self.__class__(self.data.rstrip(chars))\n def split(self,sep=None ,maxsplit=-1):\n return self.data.split(sep,maxsplit)\n def rsplit(self,sep=None ,maxsplit=-1):\n return self.data.rsplit(sep,maxsplit)\n def splitlines(self,keepends=False ):return self.data.splitlines(keepends)\n def startswith(self,prefix,start=0,end=_sys.maxsize):\n return self.data.startswith(prefix,start,end)\n def strip(self,chars=None ):return self.__class__(self.data.strip(chars))\n def swapcase(self):return self.__class__(self.data.swapcase())\n def title(self):return self.__class__(self.data.title())\n def translate(self,*args):\n return self.__class__(self.data.translate(*args))\n def upper(self):return self.__class__(self.data.upper())\n def zfill(self,width):return self.__class__(self.data.zfill(width))\n", ["_collections", "_collections_abc", "_weakref", "copy", "heapq", "itertools", "keyword", "operator", "reprlib", "sys", "warnings"], 1], "importlib.util": [".py", "''\nfrom . import abc\nfrom ._bootstrap import module_from_spec\nfrom ._bootstrap import _resolve_name\nfrom ._bootstrap import spec_from_loader\nfrom ._bootstrap import _find_spec\nfrom ._bootstrap_external import MAGIC_NUMBER\nfrom ._bootstrap_external import _RAW_MAGIC_NUMBER\nfrom ._bootstrap_external import cache_from_source\nfrom ._bootstrap_external import decode_source\nfrom ._bootstrap_external import source_from_cache\nfrom ._bootstrap_external import spec_from_file_location\n\nfrom contextlib import contextmanager\nimport _imp\nimport functools\nimport sys\nimport types\nimport warnings\n\n\ndef source_hash(source_bytes):\n ''\n return _imp.source_hash(_RAW_MAGIC_NUMBER,source_bytes)\n \n \ndef resolve_name(name,package):\n ''\n if not name.startswith('.'):\n return name\n elif not package:\n raise ValueError(f'no package specified for {repr(name)} '\n '(required for relative module names)')\n level=0\n for character in name:\n if character !='.':\n break\n level +=1\n return _resolve_name(name[level:],package,level)\n \n \ndef _find_spec_from_path(name,path=None ):\n ''\n\n\n\n\n\n\n\n\n\n\n\n\n \n if name not in sys.modules:\n return _find_spec(name,path)\n else :\n module=sys.modules[name]\n if module is None :\n return None\n try :\n spec=module.__spec__\n except AttributeError:\n raise ValueError('{}.__spec__ is not set'.format(name))from None\n else :\n if spec is None :\n raise ValueError('{}.__spec__ is None'.format(name))\n return spec\n \n \ndef find_spec(name,package=None ):\n ''\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n \n fullname=resolve_name(name,package)if name.startswith('.')else name\n if fullname not in sys.modules:\n parent_name=fullname.rpartition('.')[0]\n if parent_name:\n parent=__import__(parent_name,fromlist=['__path__'])\n try :\n parent_path=parent.__path__\n except AttributeError as e:\n raise ModuleNotFoundError(\n f\"__path__ attribute not found on {parent_name!r} \"\n f\"while trying to find {fullname!r}\",name=fullname)from e\n else :\n parent_path=None\n return _find_spec(fullname,parent_path)\n else :\n module=sys.modules[fullname]\n if module is None :\n return None\n try :\n spec=module.__spec__\n except AttributeError:\n raise ValueError('{}.__spec__ is not set'.format(name))from None\n else :\n if spec is None :\n raise ValueError('{}.__spec__ is None'.format(name))\n return spec\n \n \n@contextmanager\ndef _module_to_load(name):\n is_reload=name in sys.modules\n \n module=sys.modules.get(name)\n if not is_reload:\n \n \n \n module=type(sys)(name)\n \n \n module.__initializing__=True\n sys.modules[name]=module\n try :\n yield module\n except Exception:\n if not is_reload:\n try :\n del sys.modules[name]\n except KeyError:\n pass\n finally :\n module.__initializing__=False\n \n \ndef set_package(fxn):\n ''\n\n\n\n \n @functools.wraps(fxn)\n def set_package_wrapper(*args,**kwargs):\n warnings.warn('The import system now takes care of this automatically.',\n DeprecationWarning,stacklevel=2)\n module=fxn(*args,**kwargs)\n if getattr(module,'__package__',None )is None :\n module.__package__=module.__name__\n if not hasattr(module,'__path__'):\n module.__package__=module.__package__.rpartition('.')[0]\n return module\n return set_package_wrapper\n \n \ndef set_loader(fxn):\n ''\n\n\n\n \n @functools.wraps(fxn)\n def set_loader_wrapper(self,*args,**kwargs):\n warnings.warn('The import system now takes care of this automatically.',\n DeprecationWarning,stacklevel=2)\n module=fxn(self,*args,**kwargs)\n if getattr(module,'__loader__',None )is None :\n module.__loader__=self\n return module\n return set_loader_wrapper\n \n \ndef module_for_loader(fxn):\n ''\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n \n warnings.warn('The import system now takes care of this automatically.',\n DeprecationWarning,stacklevel=2)\n @functools.wraps(fxn)\n def module_for_loader_wrapper(self,fullname,*args,**kwargs):\n with _module_to_load(fullname)as module:\n module.__loader__=self\n try :\n is_package=self.is_package(fullname)\n except (ImportError,AttributeError):\n pass\n else :\n if is_package:\n module.__package__=fullname\n else :\n module.__package__=fullname.rpartition('.')[0]\n \n return fxn(self,module,*args,**kwargs)\n \n return module_for_loader_wrapper\n \n \nclass _LazyModule(types.ModuleType):\n\n ''\n \n def __getattribute__(self,attr):\n ''\n \n \n \n self.__class__=types.ModuleType\n \n \n original_name=self.__spec__.name\n \n \n attrs_then=self.__spec__.loader_state['__dict__']\n original_type=self.__spec__.loader_state['__class__']\n attrs_now=self.__dict__\n attrs_updated={}\n for key,value in attrs_now.items():\n \n \n if key not in attrs_then:\n attrs_updated[key]=value\n elif id(attrs_now[key])!=id(attrs_then[key]):\n attrs_updated[key]=value\n self.__spec__.loader.exec_module(self)\n \n \n if original_name in sys.modules:\n if id(self)!=id(sys.modules[original_name]):\n raise ValueError(f\"module object for {original_name!r} \"\n \"substituted in sys.modules during a lazy \"\n \"load\")\n \n \n self.__dict__.update(attrs_updated)\n return getattr(self,attr)\n \n def __delattr__(self,attr):\n ''\n \n \n self.__getattribute__(attr)\n delattr(self,attr)\n \n \nclass LazyLoader(abc.Loader):\n\n ''\n \n @staticmethod\n def __check_eager_loader(loader):\n if not hasattr(loader,'exec_module'):\n raise TypeError('loader must define exec_module()')\n \n @classmethod\n def factory(cls,loader):\n ''\n cls.__check_eager_loader(loader)\n return lambda *args,**kwargs:cls(loader(*args,**kwargs))\n \n def __init__(self,loader):\n self.__check_eager_loader(loader)\n self.loader=loader\n \n def create_module(self,spec):\n return self.loader.create_module(spec)\n \n def exec_module(self,module):\n ''\n module.__spec__.loader=self.loader\n module.__loader__=self.loader\n \n \n \n \n loader_state={}\n loader_state['__dict__']=module.__dict__.copy()\n loader_state['__class__']=module.__class__\n module.__spec__.loader_state=loader_state\n module.__class__=_LazyModule\n", ["_imp", "contextlib", "functools", "importlib", "importlib._bootstrap", "importlib._bootstrap_external", "importlib.abc", "sys", "types", "warnings"]], "email._parseaddr": [".py", "\n\n\n\"\"\"Email address parsing code.\n\nLifted directly from rfc822.py. This should eventually be rewritten.\n\"\"\"\n\n__all__=[\n'mktime_tz',\n'parsedate',\n'parsedate_tz',\n'quote',\n]\n\nimport time,calendar\n\nSPACE=' '\nEMPTYSTRING=''\nCOMMASPACE=', '\n\n\n_monthnames=['jan','feb','mar','apr','may','jun','jul',\n'aug','sep','oct','nov','dec',\n'january','february','march','april','may','june','july',\n'august','september','october','november','december']\n\n_daynames=['mon','tue','wed','thu','fri','sat','sun']\n\n\n\n\n\n\n\n_timezones={'UT':0,'UTC':0,'GMT':0,'Z':0,\n'AST':-400,'ADT':-300,\n'EST':-500,'EDT':-400,\n'CST':-600,'CDT':-500,\n'MST':-700,'MDT':-600,\n'PST':-800,'PDT':-700\n}\n\n\ndef parsedate_tz(data):\n ''\n\n\n \n res=_parsedate_tz(data)\n if not res:\n return\n if res[9]is None :\n res[9]=0\n return tuple(res)\n \ndef _parsedate_tz(data):\n ''\n\n\n\n\n\n\n\n \n if not data:\n return\n data=data.split()\n \n \n if data[0].endswith(',')or data[0].lower()in _daynames:\n \n del data[0]\n else :\n i=data[0].rfind(',')\n if i >=0:\n data[0]=data[0][i+1:]\n if len(data)==3:\n stuff=data[0].split('-')\n if len(stuff)==3:\n data=stuff+data[1:]\n if len(data)==4:\n s=data[3]\n i=s.find('+')\n if i ==-1:\n i=s.find('-')\n if i >0:\n data[3:]=[s[:i],s[i:]]\n else :\n data.append('')\n if len(data)<5:\n return None\n data=data[:5]\n [dd,mm,yy,tm,tz]=data\n mm=mm.lower()\n if mm not in _monthnames:\n dd,mm=mm,dd.lower()\n if mm not in _monthnames:\n return None\n mm=_monthnames.index(mm)+1\n if mm >12:\n mm -=12\n if dd[-1]==',':\n dd=dd[:-1]\n i=yy.find(':')\n if i >0:\n yy,tm=tm,yy\n if yy[-1]==',':\n yy=yy[:-1]\n if not yy[0].isdigit():\n yy,tz=tz,yy\n if tm[-1]==',':\n tm=tm[:-1]\n tm=tm.split(':')\n if len(tm)==2:\n [thh,tmm]=tm\n tss='0'\n elif len(tm)==3:\n [thh,tmm,tss]=tm\n elif len(tm)==1 and '.'in tm[0]:\n \n tm=tm[0].split('.')\n if len(tm)==2:\n [thh,tmm]=tm\n tss=0\n elif len(tm)==3:\n [thh,tmm,tss]=tm\n else :\n return None\n try :\n yy=int(yy)\n dd=int(dd)\n thh=int(thh)\n tmm=int(tmm)\n tss=int(tss)\n except ValueError:\n return None\n \n \n \n \n \n if yy <100:\n \n if yy >68:\n yy +=1900\n \n else :\n yy +=2000\n tzoffset=None\n tz=tz.upper()\n if tz in _timezones:\n tzoffset=_timezones[tz]\n else :\n try :\n tzoffset=int(tz)\n except ValueError:\n pass\n if tzoffset ==0 and tz.startswith('-'):\n tzoffset=None\n \n if tzoffset:\n if tzoffset <0:\n tzsign=-1\n tzoffset=-tzoffset\n else :\n tzsign=1\n tzoffset=tzsign *((tzoffset //100)*3600+(tzoffset %100)*60)\n \n return [yy,mm,dd,thh,tmm,tss,0,1,-1,tzoffset]\n \n \ndef parsedate(data):\n ''\n t=parsedate_tz(data)\n if isinstance(t,tuple):\n return t[:9]\n else :\n return t\n \n \ndef mktime_tz(data):\n ''\n if data[9]is None :\n \n return time.mktime(data[:8]+(-1,))\n else :\n t=calendar.timegm(data)\n return t -data[9]\n \n \ndef quote(str):\n ''\n\n\n\n\n \n return str.replace('\\\\','\\\\\\\\').replace('\"','\\\\\"')\n \n \nclass AddrlistClass:\n ''\n\n\n\n\n\n\n \n \n def __init__(self,field):\n ''\n\n\n\n \n self.specials='()<>@,:;.\\\"[]'\n self.pos=0\n self.LWS=' \\t'\n self.CR='\\r\\n'\n self.FWS=self.LWS+self.CR\n self.atomends=self.specials+self.LWS+self.CR\n \n \n \n self.phraseends=self.atomends.replace('.','')\n self.field=field\n self.commentlist=[]\n \n def gotonext(self):\n ''\n wslist=[]\n while self.pos <len(self.field):\n if self.field[self.pos]in self.LWS+'\\n\\r':\n if self.field[self.pos]not in '\\n\\r':\n wslist.append(self.field[self.pos])\n self.pos +=1\n elif self.field[self.pos]=='(':\n self.commentlist.append(self.getcomment())\n else :\n break\n return EMPTYSTRING.join(wslist)\n \n def getaddrlist(self):\n ''\n\n\n \n result=[]\n while self.pos <len(self.field):\n ad=self.getaddress()\n if ad:\n result +=ad\n else :\n result.append(('',''))\n return result\n \n def getaddress(self):\n ''\n self.commentlist=[]\n self.gotonext()\n \n oldpos=self.pos\n oldcl=self.commentlist\n plist=self.getphraselist()\n \n self.gotonext()\n returnlist=[]\n \n if self.pos >=len(self.field):\n \n if plist:\n returnlist=[(SPACE.join(self.commentlist),plist[0])]\n \n elif self.field[self.pos]in '.@':\n \n \n self.pos=oldpos\n self.commentlist=oldcl\n addrspec=self.getaddrspec()\n returnlist=[(SPACE.join(self.commentlist),addrspec)]\n \n elif self.field[self.pos]==':':\n \n returnlist=[]\n \n fieldlen=len(self.field)\n self.pos +=1\n while self.pos <len(self.field):\n self.gotonext()\n if self.pos <fieldlen and self.field[self.pos]==';':\n self.pos +=1\n break\n returnlist=returnlist+self.getaddress()\n \n elif self.field[self.pos]=='<':\n \n routeaddr=self.getrouteaddr()\n \n if self.commentlist:\n returnlist=[(SPACE.join(plist)+' ('+\n ' '.join(self.commentlist)+')',routeaddr)]\n else :\n returnlist=[(SPACE.join(plist),routeaddr)]\n \n else :\n if plist:\n returnlist=[(SPACE.join(self.commentlist),plist[0])]\n elif self.field[self.pos]in self.specials:\n self.pos +=1\n \n self.gotonext()\n if self.pos <len(self.field)and self.field[self.pos]==',':\n self.pos +=1\n return returnlist\n \n def getrouteaddr(self):\n ''\n\n\n \n if self.field[self.pos]!='<':\n return\n \n expectroute=False\n self.pos +=1\n self.gotonext()\n adlist=''\n while self.pos <len(self.field):\n if expectroute:\n self.getdomain()\n expectroute=False\n elif self.field[self.pos]=='>':\n self.pos +=1\n break\n elif self.field[self.pos]=='@':\n self.pos +=1\n expectroute=True\n elif self.field[self.pos]==':':\n self.pos +=1\n else :\n adlist=self.getaddrspec()\n self.pos +=1\n break\n self.gotonext()\n \n return adlist\n \n def getaddrspec(self):\n ''\n aslist=[]\n \n self.gotonext()\n while self.pos <len(self.field):\n preserve_ws=True\n if self.field[self.pos]=='.':\n if aslist and not aslist[-1].strip():\n aslist.pop()\n aslist.append('.')\n self.pos +=1\n preserve_ws=False\n elif self.field[self.pos]=='\"':\n aslist.append('\"%s\"'%quote(self.getquote()))\n elif self.field[self.pos]in self.atomends:\n if aslist and not aslist[-1].strip():\n aslist.pop()\n break\n else :\n aslist.append(self.getatom())\n ws=self.gotonext()\n if preserve_ws and ws:\n aslist.append(ws)\n \n if self.pos >=len(self.field)or self.field[self.pos]!='@':\n return EMPTYSTRING.join(aslist)\n \n aslist.append('@')\n self.pos +=1\n self.gotonext()\n return EMPTYSTRING.join(aslist)+self.getdomain()\n \n def getdomain(self):\n ''\n sdlist=[]\n while self.pos <len(self.field):\n if self.field[self.pos]in self.LWS:\n self.pos +=1\n elif self.field[self.pos]=='(':\n self.commentlist.append(self.getcomment())\n elif self.field[self.pos]=='[':\n sdlist.append(self.getdomainliteral())\n elif self.field[self.pos]=='.':\n self.pos +=1\n sdlist.append('.')\n elif self.field[self.pos]in self.atomends:\n break\n else :\n sdlist.append(self.getatom())\n return EMPTYSTRING.join(sdlist)\n \n def getdelimited(self,beginchar,endchars,allowcomments=True ):\n ''\n\n\n\n\n\n\n\n\n\n\n \n if self.field[self.pos]!=beginchar:\n return ''\n \n slist=['']\n quote=False\n self.pos +=1\n while self.pos <len(self.field):\n if quote:\n slist.append(self.field[self.pos])\n quote=False\n elif self.field[self.pos]in endchars:\n self.pos +=1\n break\n elif allowcomments and self.field[self.pos]=='(':\n slist.append(self.getcomment())\n continue\n elif self.field[self.pos]=='\\\\':\n quote=True\n else :\n slist.append(self.field[self.pos])\n self.pos +=1\n \n return EMPTYSTRING.join(slist)\n \n def getquote(self):\n ''\n return self.getdelimited('\"','\"\\r',False )\n \n def getcomment(self):\n ''\n return self.getdelimited('(',')\\r',True )\n \n def getdomainliteral(self):\n ''\n return '[%s]'%self.getdelimited('[',']\\r',False )\n \n def getatom(self,atomends=None ):\n ''\n\n\n\n\n \n atomlist=['']\n if atomends is None :\n atomends=self.atomends\n \n while self.pos <len(self.field):\n if self.field[self.pos]in atomends:\n break\n else :\n atomlist.append(self.field[self.pos])\n self.pos +=1\n \n return EMPTYSTRING.join(atomlist)\n \n def getphraselist(self):\n ''\n\n\n\n\n \n plist=[]\n \n while self.pos <len(self.field):\n if self.field[self.pos]in self.FWS:\n self.pos +=1\n elif self.field[self.pos]=='\"':\n plist.append(self.getquote())\n elif self.field[self.pos]=='(':\n self.commentlist.append(self.getcomment())\n elif self.field[self.pos]in self.phraseends:\n break\n else :\n plist.append(self.getatom(self.phraseends))\n \n return plist\n \nclass AddressList(AddrlistClass):\n ''\n def __init__(self,field):\n AddrlistClass.__init__(self,field)\n if field:\n self.addresslist=self.getaddrlist()\n else :\n self.addresslist=[]\n \n def __len__(self):\n return len(self.addresslist)\n \n def __add__(self,other):\n \n newaddr=AddressList(None )\n newaddr.addresslist=self.addresslist[:]\n for x in other.addresslist:\n if not x in self.addresslist:\n newaddr.addresslist.append(x)\n return newaddr\n \n def __iadd__(self,other):\n \n for x in other.addresslist:\n if not x in self.addresslist:\n self.addresslist.append(x)\n return self\n \n def __sub__(self,other):\n \n newaddr=AddressList(None )\n for x in self.addresslist:\n if not x in other.addresslist:\n newaddr.addresslist.append(x)\n return newaddr\n \n def __isub__(self,other):\n \n for x in other.addresslist:\n if x in self.addresslist:\n self.addresslist.remove(x)\n return self\n \n def __getitem__(self,index):\n \n return self.addresslist[index]\n", ["calendar", "time"]], "_posixsubprocess": [".js", "var $module=(function($B){\n\n return {\n cloexec_pipe: function() {} // fixme\n }\n})(__BRYTHON__)\n"], "email.policy": [".py", "''\n\n\n\nimport re\nfrom email._policybase import Policy,Compat32,compat32,_extend_docstrings\nfrom email.utils import _has_surrogates\nfrom email.headerregistry import HeaderRegistry as HeaderRegistry\nfrom email.contentmanager import raw_data_manager\nfrom email.message import EmailMessage\n\n__all__=[\n'Compat32',\n'compat32',\n'Policy',\n'EmailPolicy',\n'default',\n'strict',\n'SMTP',\n'HTTP',\n]\n\nlinesep_splitter=re.compile(r'\\n|\\r')\n\n@_extend_docstrings\nclass EmailPolicy(Policy):\n\n ''\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n \n \n message_factory=EmailMessage\n utf8=False\n refold_source='long'\n header_factory=HeaderRegistry()\n content_manager=raw_data_manager\n \n def __init__(self,**kw):\n \n \n if 'header_factory'not in kw:\n object.__setattr__(self,'header_factory',HeaderRegistry())\n super().__init__(**kw)\n \n def header_max_count(self,name):\n ''\n\n\n\n \n return self.header_factory[name].max_count\n \n \n \n \n \n \n \n \n \n \n \n def header_source_parse(self,sourcelines):\n ''\n\n\n\n\n\n\n \n name,value=sourcelines[0].split(':',1)\n value=value.lstrip(' \\t')+''.join(sourcelines[1:])\n return (name,value.rstrip('\\r\\n'))\n \n def header_store_parse(self,name,value):\n ''\n\n\n\n\n\n\n\n \n if hasattr(value,'name')and value.name.lower()==name.lower():\n return (name,value)\n if isinstance(value,str)and len(value.splitlines())>1:\n \n \n raise ValueError(\"Header values may not contain linefeed \"\n \"or carriage return characters\")\n return (name,self.header_factory(name,value))\n \n def header_fetch_parse(self,name,value):\n ''\n\n\n\n\n\n\n \n if hasattr(value,'name'):\n return value\n \n value=''.join(linesep_splitter.split(value))\n return self.header_factory(name,value)\n \n def fold(self,name,value):\n ''\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n \n return self._fold(name,value,refold_binary=True )\n \n def fold_binary(self,name,value):\n ''\n\n\n\n\n\n\n\n\n\n\n\n \n folded=self._fold(name,value,refold_binary=self.cte_type =='7bit')\n charset='utf8'if self.utf8 else 'ascii'\n return folded.encode(charset,'surrogateescape')\n \n def _fold(self,name,value,refold_binary=False ):\n if hasattr(value,'name'):\n return value.fold(policy=self)\n maxlen=self.max_line_length if self.max_line_length else float('inf')\n lines=value.splitlines()\n refold=(self.refold_source =='all'or\n self.refold_source =='long'and\n (lines and len(lines[0])+len(name)+2 >maxlen or\n any(len(x)>maxlen for x in lines[1:])))\n if refold or refold_binary and _has_surrogates(value):\n return self.header_factory(name,''.join(lines)).fold(policy=self)\n return name+': '+self.linesep.join(lines)+self.linesep\n \n \ndefault=EmailPolicy()\n\ndel default.header_factory\nstrict=default.clone(raise_on_defect=True )\nSMTP=default.clone(linesep='\\r\\n')\nHTTP=default.clone(linesep='\\r\\n',max_line_length=None )\nSMTPUTF8=SMTP.clone(utf8=True )\n", ["email._policybase", "email.contentmanager", "email.headerregistry", "email.message", "email.utils", "re"]], "_locale": [".js", "var am = {\n \"C\": \"AM\",\n \"aa\": \"saaku\",\n \"ab\": \"AM\",\n \"ae\": \"AM\",\n \"af\": \"vm.\",\n \"ak\": \"AN\",\n \"am\": \"\\u1325\\u12cb\\u1275\",\n \"an\": \"AM\",\n \"ar\": \"\\u0635\",\n \"as\": \"\\u09f0\\u09be\\u09a4\\u09bf\\u09aa\\u09c1\",\n \"av\": \"AM\",\n \"ay\": \"AM\",\n \"az\": \"AM\",\n \"ba\": \"\",\n \"be\": \"\",\n \"bg\": \"\",\n \"bh\": \"AM\",\n \"bi\": \"AM\",\n \"bm\": \"AM\",\n \"bn\": \"AM\",\n \"bo\": \"\\u0f66\\u0f94\\u0f0b\\u0f51\\u0fb2\\u0f7c\",\n \"br\": \"A.M.\",\n \"bs\": \"prijepodne\",\n \"ca\": \"a. m.\",\n \"ce\": \"AM\",\n \"ch\": \"AM\",\n \"co\": \"\",\n \"cr\": \"AM\",\n \"cs\": \"dop.\",\n \"cu\": \"\\u0414\\u041f\",\n \"cv\": \"AM\",\n \"cy\": \"yb\",\n \"da\": \"\",\n \"de\": \"\",\n \"dv\": \"\\u0789\\u0786\",\n \"dz\": \"\\u0f66\\u0f94\\u0f0b\\u0f46\\u0f0b\",\n \"ee\": \"\\u014bdi\",\n \"el\": \"\\u03c0\\u03bc\",\n \"en\": \"AM\",\n \"eo\": \"atm\",\n \"es\": \"\",\n \"et\": \"AM\",\n \"eu\": \"AM\",\n \"fa\": \"\\u0642.\\u0638\",\n \"ff\": \"\",\n \"fi\": \"ap.\",\n \"fj\": \"AM\",\n \"fo\": \"um fyr.\",\n \"fr\": \"\",\n \"fy\": \"AM\",\n \"ga\": \"r.n.\",\n \"gd\": \"m\",\n \"gl\": \"a.m.\",\n \"gn\": \"a.m.\",\n \"gu\": \"\\u0aaa\\u0ac2\\u0ab0\\u0acd\\u0ab5\\u00a0\\u0aae\\u0aa7\\u0acd\\u0aaf\\u0abe\\u0ab9\\u0acd\\u0aa8\",\n \"gv\": \"a.m.\",\n \"ha\": \"AM\",\n \"he\": \"AM\",\n \"hi\": \"\\u092a\\u0942\\u0930\\u094d\\u0935\\u093e\\u0939\\u094d\\u0928\",\n \"ho\": \"AM\",\n \"hr\": \"\",\n \"ht\": \"AM\",\n \"hu\": \"de.\",\n \"hy\": \"\",\n \"hz\": \"AM\",\n \"ia\": \"a.m.\",\n \"id\": \"AM\",\n \"ie\": \"AM\",\n \"ig\": \"A.M.\",\n \"ii\": \"\\ua0b5\\ua1aa\\ua20c\\ua210\",\n \"ik\": \"AM\",\n \"io\": \"AM\",\n \"is\": \"f.h.\",\n \"it\": \"\",\n \"iu\": \"AM\",\n \"ja\": \"\\u5348\\u524d\",\n \"jv\": \"\",\n \"ka\": \"AM\",\n \"kg\": \"AM\",\n \"ki\": \"Kiroko\",\n \"kj\": \"AM\",\n \"kk\": \"AM\",\n \"kl\": \"\",\n \"km\": \"\\u1796\\u17d2\\u179a\\u17b9\\u1780\",\n \"kn\": \"\\u0caa\\u0cc2\\u0cb0\\u0ccd\\u0cb5\\u0cbe\\u0cb9\\u0ccd\\u0ca8\",\n \"ko\": \"\\uc624\\uc804\",\n \"kr\": \"AM\",\n \"ks\": \"AM\",\n \"ku\": \"\\u067e.\\u0646\",\n \"kv\": \"AM\",\n \"kw\": \"a.m.\",\n \"ky\": \"\",\n \"la\": \"\",\n \"lb\": \"\",\n \"lg\": \"AM\",\n \"li\": \"AM\",\n \"ln\": \"nt\\u0254\\u0301ng\\u0254\\u0301\",\n \"lo\": \"\\u0e81\\u0ec8\\u0ead\\u0e99\\u0e97\\u0ec8\\u0ebd\\u0e87\",\n \"lt\": \"prie\\u0161piet\",\n \"lu\": \"Dinda\",\n \"lv\": \"priek\\u0161p.\",\n \"mg\": \"AM\",\n \"mh\": \"AM\",\n \"mi\": \"a.m.\",\n \"mk\": \"\\u043f\\u0440\\u0435\\u0442\\u043f\\u043b.\",\n \"ml\": \"AM\",\n \"mn\": \"??\",\n \"mo\": \"AM\",\n \"mr\": \"\\u092e.\\u092a\\u0942.\",\n \"ms\": \"PG\",\n \"mt\": \"AM\",\n \"my\": \"\\u1014\\u1036\\u1014\\u1000\\u103a\",\n \"na\": \"AM\",\n \"nb\": \"a.m.\",\n \"nd\": \"AM\",\n \"ne\": \"\\u092a\\u0942\\u0930\\u094d\\u0935\\u093e\\u0939\\u094d\\u0928\",\n \"ng\": \"AM\",\n \"nl\": \"\",\n \"nn\": \"f.m.\",\n \"no\": \"a.m.\",\n \"nr\": \"AM\",\n \"nv\": \"AM\",\n \"ny\": \"AM\",\n \"oc\": \"AM\",\n \"oj\": \"AM\",\n \"om\": \"WD\",\n \"or\": \"AM\",\n \"os\": \"AM\",\n \"pa\": \"\\u0a38\\u0a35\\u0a47\\u0a30\",\n \"pi\": \"AM\",\n \"pl\": \"AM\",\n \"ps\": \"\\u063a.\\u0645.\",\n \"pt\": \"\",\n \"qu\": \"a.m.\",\n \"rc\": \"AM\",\n \"rm\": \"AM\",\n \"rn\": \"Z.MU.\",\n \"ro\": \"a.m.\",\n \"ru\": \"\",\n \"rw\": \"AM\",\n \"sa\": \"\\u092e\\u0927\\u094d\\u092f\\u093e\\u0928\\u092a\\u0942\\u0930\\u094d\\u0935\",\n \"sc\": \"AM\",\n \"sd\": \"AM\",\n \"se\": \"i.b.\",\n \"sg\": \"ND\",\n \"sh\": \"AM\",\n \"si\": \"\\u0db4\\u0dd9.\\u0dc0.\",\n \"sk\": \"AM\",\n \"sl\": \"dop.\",\n \"sm\": \"AM\",\n \"sn\": \"AM\",\n \"so\": \"sn.\",\n \"sq\": \"e paradites\",\n \"sr\": \"pre podne\",\n \"ss\": \"AM\",\n \"st\": \"AM\",\n \"su\": \"AM\",\n \"sv\": \"\",\n \"sw\": \"AM\",\n \"ta\": \"\\u0b95\\u0bbe\\u0bb2\\u0bc8\",\n \"te\": \"\\u0c2a\\u0c42\\u0c30\\u0c4d\\u0c35\\u0c3e\\u0c39\\u0c4d\\u0c28\",\n \"tg\": \"\",\n \"th\": \"AM\",\n \"ti\": \"\\u1295\\u1309\\u1206 \\u1230\\u12d3\\u1270\",\n \"tk\": \"\",\n \"tl\": \"AM\",\n \"tn\": \"AM\",\n \"to\": \"AM\",\n \"tr\": \"\\u00d6\\u00d6\",\n \"ts\": \"AM\",\n \"tt\": \"\",\n \"tw\": \"AM\",\n \"ty\": \"AM\",\n \"ug\": \"\\u0686?\\u0634\\u062a\\u0649\\u0646 \\u0628?\\u0631?\\u0646\",\n \"uk\": \"AM\",\n \"ur\": \"AM\",\n \"uz\": \"TO\",\n \"ve\": \"AM\",\n \"vi\": \"SA\",\n \"vo\": \"AM\",\n \"wa\": \"AM\",\n \"wo\": \"\",\n \"xh\": \"AM\",\n \"yi\": \"\\ua0b5\\ua1aa\\ua20c\\ua210\",\n \"yo\": \"\\u00c0\\u00e1r?`\",\n \"za\": \"AM\",\n \"zh\": \"\\u4e0a\\u5348\",\n \"zu\": \"AM\"\n}\nvar pm = {\n \"C\": \"PM\",\n \"aa\": \"carra\",\n \"ab\": \"PM\",\n \"ae\": \"PM\",\n \"af\": \"nm.\",\n \"ak\": \"EW\",\n \"am\": \"\\u12a8\\u1230\\u12d3\\u1275\",\n \"an\": \"PM\",\n \"ar\": \"\\u0645\",\n \"as\": \"\\u0986\\u09ac\\u09c7\\u09b2\\u09bf\",\n \"av\": \"PM\",\n \"ay\": \"PM\",\n \"az\": \"PM\",\n \"ba\": \"\",\n \"be\": \"\",\n \"bg\": \"\",\n \"bh\": \"PM\",\n \"bi\": \"PM\",\n \"bm\": \"PM\",\n \"bn\": \"PM\",\n \"bo\": \"\\u0f55\\u0fb1\\u0f72\\u0f0b\\u0f51\\u0fb2\\u0f7c\",\n \"br\": \"G.M.\",\n \"bs\": \"popodne\",\n \"ca\": \"p. m.\",\n \"ce\": \"PM\",\n \"ch\": \"PM\",\n \"co\": \"\",\n \"cr\": \"PM\",\n \"cs\": \"odp.\",\n \"cu\": \"\\u041f\\u041f\",\n \"cv\": \"PM\",\n \"cy\": \"yh\",\n \"da\": \"\",\n \"de\": \"\",\n \"dv\": \"\\u0789\\u078a\",\n \"dz\": \"\\u0f55\\u0fb1\\u0f72\\u0f0b\\u0f46\\u0f0b\",\n \"ee\": \"\\u0263etr\\u0254\",\n \"el\": \"\\u03bc\\u03bc\",\n \"en\": \"PM\",\n \"eo\": \"ptm\",\n \"es\": \"\",\n \"et\": \"PM\",\n \"eu\": \"PM\",\n \"fa\": \"\\u0628.\\u0638\",\n \"ff\": \"\",\n \"fi\": \"ip.\",\n \"fj\": \"PM\",\n \"fo\": \"um sein.\",\n \"fr\": \"\",\n \"fy\": \"PM\",\n \"ga\": \"i.n.\",\n \"gd\": \"f\",\n \"gl\": \"p.m.\",\n \"gn\": \"p.m.\",\n \"gu\": \"\\u0a89\\u0aa4\\u0acd\\u0aa4\\u0ab0\\u00a0\\u0aae\\u0aa7\\u0acd\\u0aaf\\u0abe\\u0ab9\\u0acd\\u0aa8\",\n \"gv\": \"p.m.\",\n \"ha\": \"PM\",\n \"he\": \"PM\",\n \"hi\": \"\\u0905\\u092a\\u0930\\u093e\\u0939\\u094d\\u0928\",\n \"ho\": \"PM\",\n \"hr\": \"\",\n \"ht\": \"PM\",\n \"hu\": \"du.\",\n \"hy\": \"\",\n \"hz\": \"PM\",\n \"ia\": \"p.m.\",\n \"id\": \"PM\",\n \"ie\": \"PM\",\n \"ig\": \"P.M.\",\n \"ii\": \"\\ua0b5\\ua1aa\\ua20c\\ua248\",\n \"ik\": \"PM\",\n \"io\": \"PM\",\n \"is\": \"e.h.\",\n \"it\": \"\",\n \"iu\": \"PM\",\n \"ja\": \"\\u5348\\u5f8c\",\n \"jv\": \"\",\n \"ka\": \"PM\",\n \"kg\": \"PM\",\n \"ki\": \"Hwa\\u0129-in\\u0129\",\n \"kj\": \"PM\",\n \"kk\": \"PM\",\n \"kl\": \"\",\n \"km\": \"\\u179b\\u17d2\\u1784\\u17b6\\u1785\",\n \"kn\": \"\\u0c85\\u0caa\\u0cb0\\u0cbe\\u0cb9\\u0ccd\\u0ca8\",\n \"ko\": \"\\uc624\\ud6c4\",\n \"kr\": \"PM\",\n \"ks\": \"PM\",\n \"ku\": \"\\u062f.\\u0646\",\n \"kv\": \"PM\",\n \"kw\": \"p.m.\",\n \"ky\": \"\",\n \"la\": \"\",\n \"lb\": \"\",\n \"lg\": \"PM\",\n \"li\": \"PM\",\n \"ln\": \"mp\\u00f3kwa\",\n \"lo\": \"\\u0eab\\u0ebc\\u0eb1\\u0e87\\u0e97\\u0ec8\\u0ebd\\u0e87\",\n \"lt\": \"popiet\",\n \"lu\": \"Dilolo\",\n \"lv\": \"p\\u0113cp.\",\n \"mg\": \"PM\",\n \"mh\": \"PM\",\n \"mi\": \"p.m.\",\n \"mk\": \"\\u043f\\u043e\\u043f\\u043b.\",\n \"ml\": \"PM\",\n \"mn\": \"?\\u0425\",\n \"mo\": \"PM\",\n \"mr\": \"\\u092e.\\u0928\\u0902.\",\n \"ms\": \"PTG\",\n \"mt\": \"PM\",\n \"my\": \"\\u100a\\u1014\\u1031\",\n \"na\": \"PM\",\n \"nb\": \"p.m.\",\n \"nd\": \"PM\",\n \"ne\": \"\\u0905\\u092a\\u0930\\u093e\\u0939\\u094d\\u0928\",\n \"ng\": \"PM\",\n \"nl\": \"\",\n \"nn\": \"e.m.\",\n \"no\": \"p.m.\",\n \"nr\": \"PM\",\n \"nv\": \"PM\",\n \"ny\": \"PM\",\n \"oc\": \"PM\",\n \"oj\": \"PM\",\n \"om\": \"WB\",\n \"or\": \"PM\",\n \"os\": \"PM\",\n \"pa\": \"\\u0a36\\u0a3e\\u0a2e\",\n \"pi\": \"PM\",\n \"pl\": \"PM\",\n \"ps\": \"\\u063a.\\u0648.\",\n \"pt\": \"\",\n \"qu\": \"p.m.\",\n \"rc\": \"PM\",\n \"rm\": \"PM\",\n \"rn\": \"Z.MW.\",\n \"ro\": \"p.m.\",\n \"ru\": \"\",\n \"rw\": \"PM\",\n \"sa\": \"\\u092e\\u0927\\u094d\\u092f\\u093e\\u0928\\u092a\\u091a\\u094d\\u092f\\u093e\\u0924\",\n \"sc\": \"PM\",\n \"sd\": \"PM\",\n \"se\": \"e.b.\",\n \"sg\": \"LK\",\n \"sh\": \"PM\",\n \"si\": \"\\u0db4.\\u0dc0.\",\n \"sk\": \"PM\",\n \"sl\": \"pop.\",\n \"sm\": \"PM\",\n \"sn\": \"PM\",\n \"so\": \"gn.\",\n \"sq\": \"e pasdites\",\n \"sr\": \"po podne\",\n \"ss\": \"PM\",\n \"st\": \"PM\",\n \"su\": \"PM\",\n \"sv\": \"\",\n \"sw\": \"PM\",\n \"ta\": \"\\u0bae\\u0bbe\\u0bb2\\u0bc8\",\n \"te\": \"\\u0c05\\u0c2a\\u0c30\\u0c3e\\u0c39\\u0c4d\\u0c28\",\n \"tg\": \"\",\n \"th\": \"PM\",\n \"ti\": \"\\u12f5\\u1215\\u122d \\u1230\\u12d3\\u1275\",\n \"tk\": \"\",\n \"tl\": \"PM\",\n \"tn\": \"PM\",\n \"to\": \"PM\",\n \"tr\": \"\\u00d6S\",\n \"ts\": \"PM\",\n \"tt\": \"\",\n \"tw\": \"PM\",\n \"ty\": \"PM\",\n \"ug\": \"\\u0686?\\u0634\\u062a\\u0649\\u0646 \\u0643?\\u064a\\u0649\\u0646\",\n \"uk\": \"PM\",\n \"ur\": \"PM\",\n \"uz\": \"TK\",\n \"ve\": \"PM\",\n \"vi\": \"CH\",\n \"vo\": \"PM\",\n \"wa\": \"PM\",\n \"wo\": \"\",\n \"xh\": \"PM\",\n \"yi\": \"\\ua0b5\\ua1aa\\ua20c\\ua248\",\n \"yo\": \"?`s\\u00e1n\",\n \"za\": \"PM\",\n \"zh\": \"\\u4e0b\\u5348\",\n \"zu\": \"PM\"\n}\n\nvar X_format = {\n \"%H:%M:%S\": [\n \"C\",\n \"ab\",\n \"ae\",\n \"af\",\n \"an\",\n \"av\",\n \"ay\",\n \"az\",\n \"ba\",\n \"be\",\n \"bg\",\n \"bh\",\n \"bi\",\n \"bm\",\n \"bo\",\n \"br\",\n \"bs\",\n \"ca\",\n \"ce\",\n \"ch\",\n \"co\",\n \"cr\",\n \"cs\",\n \"cu\",\n \"cv\",\n \"cy\",\n \"da\",\n \"de\",\n \"dv\",\n \"eo\",\n \"es\",\n \"et\",\n \"eu\",\n \"ff\",\n \"fj\",\n \"fo\",\n \"fr\",\n \"fy\",\n \"ga\",\n \"gd\",\n \"gl\",\n \"gn\",\n \"gu\",\n \"gv\",\n \"ha\",\n \"he\",\n \"hi\",\n \"ho\",\n \"hr\",\n \"ht\",\n \"hu\",\n \"hy\",\n \"hz\",\n \"ia\",\n \"ie\",\n \"ig\",\n \"ik\",\n \"io\",\n \"is\",\n \"it\",\n \"ja\",\n \"ka\",\n \"kg\",\n \"ki\",\n \"kj\",\n \"kk\",\n \"kl\",\n \"km\",\n \"kn\",\n \"kv\",\n \"kw\",\n \"ky\",\n \"la\",\n \"lb\",\n \"lg\",\n \"li\",\n \"ln\",\n \"lo\",\n \"lt\",\n \"lu\",\n \"lv\",\n \"mg\",\n \"mh\",\n \"mk\",\n \"mn\",\n \"mo\",\n \"mr\",\n \"mt\",\n \"my\",\n \"na\",\n \"nb\",\n \"nd\",\n \"ng\",\n \"nl\",\n \"nn\",\n \"no\",\n \"nr\",\n \"nv\",\n \"ny\",\n \"oj\",\n \"or\",\n \"os\",\n \"pi\",\n \"pl\",\n \"ps\",\n \"pt\",\n \"rc\",\n \"rm\",\n \"rn\",\n \"ro\",\n \"ru\",\n \"rw\",\n \"sa\",\n \"sc\",\n \"se\",\n \"sg\",\n \"sh\",\n \"sk\",\n \"sl\",\n \"sm\",\n \"sn\",\n \"sr\",\n \"ss\",\n \"st\",\n \"su\",\n \"sv\",\n \"sw\",\n \"ta\",\n \"te\",\n \"tg\",\n \"th\",\n \"tk\",\n \"tl\",\n \"tn\",\n \"tr\",\n \"ts\",\n \"tt\",\n \"tw\",\n \"ty\",\n \"ug\",\n \"uk\",\n \"uz\",\n \"ve\",\n \"vo\",\n \"wa\",\n \"wo\",\n \"xh\",\n \"yo\",\n \"za\",\n \"zh\",\n \"zu\"\n ],\n \"%i:%M:%S %p\": [\n \"aa\",\n \"ak\",\n \"am\",\n \"bn\",\n \"el\",\n \"en\",\n \"iu\",\n \"kr\",\n \"ks\",\n \"mi\",\n \"ml\",\n \"ms\",\n \"ne\",\n \"om\",\n \"sd\",\n \"so\",\n \"sq\",\n \"ti\",\n \"to\",\n \"ur\",\n \"vi\"\n ],\n \"%I:%M:%S %p\": [\n \"ar\",\n \"fa\",\n \"ku\",\n \"qu\"\n ],\n \"%p %i:%M:%S\": [\n \"as\",\n \"ii\",\n \"ko\",\n \"yi\"\n ],\n \"\\u0f46\\u0f74\\u0f0b\\u0f5a\\u0f7c\\u0f51\\u0f0b%i:%M:%S %p\": [\n \"dz\"\n ],\n \"%p ga %i:%M:%S\": [\n \"ee\"\n ],\n \"%H.%M.%S\": [\n \"fi\",\n \"id\",\n \"jv\",\n \"oc\",\n \"si\"\n ],\n \"%p %I:%M:%S\": [\n \"pa\"\n ]\n}\nvar x_format = {\n \"%m/%d/%y\": [\n \"C\"\n ],\n \"%d/%m/%Y\": [\n \"aa\",\n \"am\",\n \"bm\",\n \"bn\",\n \"ca\",\n \"co\",\n \"cy\",\n \"el\",\n \"es\",\n \"ff\",\n \"fr\",\n \"ga\",\n \"gd\",\n \"gl\",\n \"gn\",\n \"gv\",\n \"ha\",\n \"he\",\n \"id\",\n \"ig\",\n \"it\",\n \"iu\",\n \"jv\",\n \"ki\",\n \"kr\",\n \"kw\",\n \"la\",\n \"lg\",\n \"ln\",\n \"lo\",\n \"lu\",\n \"mi\",\n \"ml\",\n \"ms\",\n \"mt\",\n \"nd\",\n \"oc\",\n \"om\",\n \"pt\",\n \"qu\",\n \"rn\",\n \"sd\",\n \"sg\",\n \"so\",\n \"sw\",\n \"ti\",\n \"to\",\n \"uk\",\n \"ur\",\n \"uz\",\n \"vi\",\n \"wo\",\n \"yo\"\n ],\n \"%m/%d/%Y\": [\n \"ab\",\n \"ae\",\n \"an\",\n \"av\",\n \"ay\",\n \"bh\",\n \"bi\",\n \"ch\",\n \"cr\",\n \"cv\",\n \"ee\",\n \"en\",\n \"fj\",\n \"ho\",\n \"ht\",\n \"hz\",\n \"ie\",\n \"ik\",\n \"io\",\n \"kg\",\n \"kj\",\n \"ks\",\n \"kv\",\n \"li\",\n \"mh\",\n \"mo\",\n \"na\",\n \"ne\",\n \"ng\",\n \"nv\",\n \"ny\",\n \"oj\",\n \"pi\",\n \"rc\",\n \"sc\",\n \"sh\",\n \"sm\",\n \"su\",\n \"tl\",\n \"tw\",\n \"ty\",\n \"wa\",\n \"za\",\n \"zu\"\n ],\n \"%Y-%m-%d\": [\n \"af\",\n \"br\",\n \"ce\",\n \"dz\",\n \"eo\",\n \"ko\",\n \"lt\",\n \"mg\",\n \"nr\",\n \"rw\",\n \"se\",\n \"si\",\n \"sn\",\n \"ss\",\n \"st\",\n \"sv\",\n \"tn\",\n \"ts\",\n \"ug\",\n \"ve\",\n \"vo\",\n \"xh\"\n ],\n \"%Y/%m/%d\": [\n \"ak\",\n \"bo\",\n \"eu\",\n \"ia\",\n \"ii\",\n \"ja\",\n \"ku\",\n \"yi\",\n \"zh\"\n ],\n \"null\": [\n \"ar\",\n \"fa\",\n \"ps\",\n \"th\"\n ],\n \"%d-%m-%Y\": [\n \"as\",\n \"da\",\n \"fy\",\n \"hi\",\n \"kl\",\n \"mr\",\n \"my\",\n \"nl\",\n \"rm\",\n \"sa\",\n \"ta\"\n ],\n \"%d.%m.%Y\": [\n \"az\",\n \"cs\",\n \"de\",\n \"et\",\n \"fi\",\n \"fo\",\n \"hy\",\n \"is\",\n \"ka\",\n \"kk\",\n \"lv\",\n \"mk\",\n \"nb\",\n \"nn\",\n \"no\",\n \"os\",\n \"pl\",\n \"ro\",\n \"ru\",\n \"sq\",\n \"tg\",\n \"tr\",\n \"tt\"\n ],\n \"%d.%m.%y\": [\n \"ba\",\n \"be\",\n \"lb\"\n ],\n \"%d.%m.%Y \\u0433.\": [\n \"bg\"\n ],\n \"%d.%m.%Y.\": [\n \"bs\",\n \"hr\",\n \"sr\"\n ],\n \"%Y.%m.%d\": [\n \"cu\",\n \"mn\"\n ],\n \"%d/%m/%y\": [\n \"dv\",\n \"km\"\n ],\n \"%d-%m-%y\": [\n \"gu\",\n \"kn\",\n \"or\",\n \"pa\",\n \"te\"\n ],\n \"%Y. %m. %d.\": [\n \"hu\"\n ],\n \"%d-%b %y\": [\n \"ky\"\n ],\n \"%d. %m. %Y\": [\n \"sk\",\n \"sl\"\n ],\n \"%d.%m.%y \\u00fd.\": [\n \"tk\"\n ]\n}\n\n\nvar $module=(function($B){\n var _b_ = $B.builtins\n return {\n CHAR_MAX: 127,\n LC_ALL: 6,\n LC_COLLATE: 3,\n LC_CTYPE: 0,\n LC_MESSAGES: 5,\n LC_MONETARY: 4,\n LC_NUMERIC: 1,\n LC_TIME: 2,\n Error: _b_.ValueError,\n\n _date_format: function(spec, hour){\n var t,\n locale = __BRYTHON__.locale.substr(0, 2)\n\n if(spec == \"p\"){\n var res = hours < 12 ? am[locale] : pm[locale]\n if(res === undefined){\n throw _b_.ValueError.$factory(\"no format \" + spec + \" for locale \" +\n locale)\n }\n return res\n }\n else if(spec == \"x\"){\n t = x_format\n }else if(spec == \"X\"){\n t = X_format\n }else{\n throw _b_.ValueError.$factory(\"invalid format\", spec)\n }\n for(var key in t){\n if(t[key].indexOf(locale) > -1){\n return key\n }\n }\n throw _b_.ValueError.$factory(\"no format \" + spec + \" for locale \" +\n locale)\n },\n\n localeconv: function(){\n var conv = {'grouping': [127],\n 'currency_symbol': '',\n 'n_sign_posn': 127,\n 'p_cs_precedes': 127,\n 'n_cs_precedes': 127,\n 'mon_grouping': [],\n 'n_sep_by_space': 127,\n 'decimal_point': '.',\n 'negative_sign': '',\n 'positive_sign': '',\n 'p_sep_by_space': 127,\n 'int_curr_symbol': '',\n 'p_sign_posn': 127,\n 'thousands_sep': '',\n 'mon_thousands_sep': '',\n 'frac_digits': 127,\n 'mon_decimal_point': '',\n 'int_frac_digits': 127\n }\n var res = _b_.dict.$factory()\n res.$string_dict = conv\n return res\n },\n\n setlocale : function(){\n var $ = $B.args(\"setlocale\", 2, {category: null, locale: null},\n [\"category\", \"locale\"], arguments, {locale: _b_.None},\n null, null)\n /// XXX category is currently ignored\n if($.locale == \"\"){\n // use browser language setting, if it is set\n var LANG = ($B.language || \"\").substr(0, 2)\n if(am.hasOwnProperty(LANG)){\n $B.locale = LANG\n return LANG\n }else{\n console.log(\"Unknown locale: \" + LANG)\n }\n }else if($.locale === _b_.None){\n // return current locale\n return $B.locale\n }else{\n // Only use 2 first characters\n try{$.locale.substr(0, 2)}\n catch(err){\n throw $module.Error.$factory(\"Invalid locale: \" + $.locale)\n }\n if(am.hasOwnProperty($.locale.substr(0, 2))){\n $B.locale = $.locale\n return $.locale\n }else{\n throw $module.Error.$factory(\"Unknown locale: \" + $.locale)\n }\n }\n }\n }\n})(__BRYTHON__)\n"], "heapq": [".py", "''\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n__about__=\"\"\"Heap queues\n\n[explanation by Fran\u00e7ois Pinard]\n\nHeaps are arrays for which a[k] <= a[2*k+1] and a[k] <= a[2*k+2] for\nall k, counting elements from 0. For the sake of comparison,\nnon-existing elements are considered to be infinite. The interesting\nproperty of a heap is that a[0] is always its smallest element.\n\nThe strange invariant above is meant to be an efficient memory\nrepresentation for a tournament. The numbers below are `k', not a[k]:\n\n 0\n\n 1 2\n\n 3 4 5 6\n\n 7 8 9 10 11 12 13 14\n\n 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30\n\n\nIn the tree above, each cell `k' is topping `2*k+1' and `2*k+2'. In\na usual binary tournament we see in sports, each cell is the winner\nover the two cells it tops, and we can trace the winner down the tree\nto see all opponents s/he had. However, in many computer applications\nof such tournaments, we do not need to trace the history of a winner.\nTo be more memory efficient, when a winner is promoted, we try to\nreplace it by something else at a lower level, and the rule becomes\nthat a cell and the two cells it tops contain three different items,\nbut the top cell \"wins\" over the two topped cells.\n\nIf this heap invariant is protected at all time, index 0 is clearly\nthe overall winner. The simplest algorithmic way to remove it and\nfind the \"next\" winner is to move some loser (let's say cell 30 in the\ndiagram above) into the 0 position, and then percolate this new 0 down\nthe tree, exchanging values, until the invariant is re-established.\nThis is clearly logarithmic on the total number of items in the tree.\nBy iterating over all items, you get an O(n ln n) sort.\n\nA nice feature of this sort is that you can efficiently insert new\nitems while the sort is going on, provided that the inserted items are\nnot \"better\" than the last 0'th element you extracted. This is\nespecially useful in simulation contexts, where the tree holds all\nincoming events, and the \"win\" condition means the smallest scheduled\ntime. When an event schedule other events for execution, they are\nscheduled into the future, so they can easily go into the heap. So, a\nheap is a good structure for implementing schedulers (this is what I\nused for my MIDI sequencer :-).\n\nVarious structures for implementing schedulers have been extensively\nstudied, and heaps are good for this, as they are reasonably speedy,\nthe speed is almost constant, and the worst case is not much different\nthan the average case. However, there are other representations which\nare more efficient overall, yet the worst cases might be terrible.\n\nHeaps are also very useful in big disk sorts. You most probably all\nknow that a big sort implies producing \"runs\" (which are pre-sorted\nsequences, which size is usually related to the amount of CPU memory),\nfollowed by a merging passes for these runs, which merging is often\nvery cleverly organised[1]. It is very important that the initial\nsort produces the longest runs possible. Tournaments are a good way\nto that. If, using all the memory available to hold a tournament, you\nreplace and percolate items that happen to fit the current run, you'll\nproduce runs which are twice the size of the memory for random input,\nand much better for input fuzzily ordered.\n\nMoreover, if you output the 0'th item on disk and get an input which\nmay not fit in the current tournament (because the value \"wins\" over\nthe last output value), it cannot fit in the heap, so the size of the\nheap decreases. The freed memory could be cleverly reused immediately\nfor progressively building a second heap, which grows at exactly the\nsame rate the first heap is melting. When the first heap completely\nvanishes, you switch heaps and start a new run. Clever and quite\neffective!\n\nIn a word, heaps are useful memory structures to know. I use them in\na few applications, and I think it is good to keep a `heap' module\naround. :-)\n\n--------------------\n[1] The disk balancing algorithms which are current, nowadays, are\nmore annoying than clever, and this is a consequence of the seeking\ncapabilities of the disks. On devices which cannot seek, like big\ntape drives, the story was quite different, and one had to be very\nclever to ensure (far in advance) that each tape movement will be the\nmost effective possible (that is, will best participate at\n\"progressing\" the merge). Some tapes were even able to read\nbackwards, and this was also used to avoid the rewinding time.\nBelieve me, real good tape sorts were quite spectacular to watch!\nFrom all times, sorting has always been a Great Art! :-)\n\"\"\"\n\n__all__=['heappush','heappop','heapify','heapreplace','merge',\n'nlargest','nsmallest','heappushpop']\n\ndef heappush(heap,item):\n ''\n heap.append(item)\n _siftdown(heap,0,len(heap)-1)\n \ndef heappop(heap):\n ''\n lastelt=heap.pop()\n if heap:\n returnitem=heap[0]\n heap[0]=lastelt\n _siftup(heap,0)\n return returnitem\n return lastelt\n \ndef heapreplace(heap,item):\n ''\n\n\n\n\n\n\n\n\n \n returnitem=heap[0]\n heap[0]=item\n _siftup(heap,0)\n return returnitem\n \ndef heappushpop(heap,item):\n ''\n if heap and heap[0]<item:\n item,heap[0]=heap[0],item\n _siftup(heap,0)\n return item\n \ndef heapify(x):\n ''\n n=len(x)\n \n \n \n \n \n for i in reversed(range(n //2)):\n _siftup(x,i)\n \ndef _heappop_max(heap):\n ''\n lastelt=heap.pop()\n if heap:\n returnitem=heap[0]\n heap[0]=lastelt\n _siftup_max(heap,0)\n return returnitem\n return lastelt\n \ndef _heapreplace_max(heap,item):\n ''\n returnitem=heap[0]\n heap[0]=item\n _siftup_max(heap,0)\n return returnitem\n \ndef _heapify_max(x):\n ''\n n=len(x)\n for i in reversed(range(n //2)):\n _siftup_max(x,i)\n \n \n \n \ndef _siftdown(heap,startpos,pos):\n newitem=heap[pos]\n \n \n while pos >startpos:\n parentpos=(pos -1)>>1\n parent=heap[parentpos]\n if newitem <parent:\n heap[pos]=parent\n pos=parentpos\n continue\n break\n heap[pos]=newitem\n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \ndef _siftup(heap,pos):\n endpos=len(heap)\n startpos=pos\n newitem=heap[pos]\n \n childpos=2 *pos+1\n while childpos <endpos:\n \n rightpos=childpos+1\n if rightpos <endpos and not heap[childpos]<heap[rightpos]:\n childpos=rightpos\n \n heap[pos]=heap[childpos]\n pos=childpos\n childpos=2 *pos+1\n \n \n heap[pos]=newitem\n _siftdown(heap,startpos,pos)\n \ndef _siftdown_max(heap,startpos,pos):\n ''\n newitem=heap[pos]\n \n \n while pos >startpos:\n parentpos=(pos -1)>>1\n parent=heap[parentpos]\n if parent <newitem:\n heap[pos]=parent\n pos=parentpos\n continue\n break\n heap[pos]=newitem\n \ndef _siftup_max(heap,pos):\n ''\n endpos=len(heap)\n startpos=pos\n newitem=heap[pos]\n \n childpos=2 *pos+1\n while childpos <endpos:\n \n rightpos=childpos+1\n if rightpos <endpos and not heap[rightpos]<heap[childpos]:\n childpos=rightpos\n \n heap[pos]=heap[childpos]\n pos=childpos\n childpos=2 *pos+1\n \n \n heap[pos]=newitem\n _siftdown_max(heap,startpos,pos)\n \ndef merge(*iterables,key=None ,reverse=False ):\n ''\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n \n \n h=[]\n h_append=h.append\n \n if reverse:\n _heapify=_heapify_max\n _heappop=_heappop_max\n _heapreplace=_heapreplace_max\n direction=-1\n else :\n _heapify=heapify\n _heappop=heappop\n _heapreplace=heapreplace\n direction=1\n \n if key is None :\n for order,it in enumerate(map(iter,iterables)):\n try :\n next=it.__next__\n h_append([next(),order *direction,next])\n except StopIteration:\n pass\n _heapify(h)\n while len(h)>1:\n try :\n while True :\n value,order,next=s=h[0]\n yield value\n s[0]=next()\n _heapreplace(h,s)\n except StopIteration:\n _heappop(h)\n if h:\n \n value,order,next=h[0]\n yield value\n yield from next.__self__\n return\n \n for order,it in enumerate(map(iter,iterables)):\n try :\n next=it.__next__\n value=next()\n h_append([key(value),order *direction,value,next])\n except StopIteration:\n pass\n _heapify(h)\n while len(h)>1:\n try :\n while True :\n key_value,order,value,next=s=h[0]\n yield value\n value=next()\n s[0]=key(value)\n s[2]=value\n _heapreplace(h,s)\n except StopIteration:\n _heappop(h)\n if h:\n key_value,order,value,next=h[0]\n yield value\n yield from next.__self__\n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \ndef nsmallest(n,iterable,key=None ):\n ''\n\n\n \n \n \n if n ==1:\n it=iter(iterable)\n sentinel=object()\n if key is None :\n result=min(it,default=sentinel)\n else :\n result=min(it,default=sentinel,key=key)\n return []if result is sentinel else [result]\n \n \n try :\n size=len(iterable)\n except (TypeError,AttributeError):\n pass\n else :\n if n >=size:\n return sorted(iterable,key=key)[:n]\n \n \n if key is None :\n it=iter(iterable)\n \n \n result=[(elem,i)for i,elem in zip(range(n),it)]\n if not result:\n return result\n _heapify_max(result)\n top=result[0][0]\n order=n\n _heapreplace=_heapreplace_max\n for elem in it:\n if elem <top:\n _heapreplace(result,(elem,order))\n top,_order=result[0]\n order +=1\n result.sort()\n return [elem for (elem,order)in result]\n \n \n it=iter(iterable)\n result=[(key(elem),i,elem)for i,elem in zip(range(n),it)]\n if not result:\n return result\n _heapify_max(result)\n top=result[0][0]\n order=n\n _heapreplace=_heapreplace_max\n for elem in it:\n k=key(elem)\n if k <top:\n _heapreplace(result,(k,order,elem))\n top,_order,_elem=result[0]\n order +=1\n result.sort()\n return [elem for (k,order,elem)in result]\n \ndef nlargest(n,iterable,key=None ):\n ''\n\n\n \n \n \n if n ==1:\n it=iter(iterable)\n sentinel=object()\n if key is None :\n result=max(it,default=sentinel)\n else :\n result=max(it,default=sentinel,key=key)\n return []if result is sentinel else [result]\n \n \n try :\n size=len(iterable)\n except (TypeError,AttributeError):\n pass\n else :\n if n >=size:\n return sorted(iterable,key=key,reverse=True )[:n]\n \n \n if key is None :\n it=iter(iterable)\n result=[(elem,i)for i,elem in zip(range(0,-n,-1),it)]\n if not result:\n return result\n heapify(result)\n top=result[0][0]\n order=-n\n _heapreplace=heapreplace\n for elem in it:\n if top <elem:\n _heapreplace(result,(elem,order))\n top,_order=result[0]\n order -=1\n result.sort(reverse=True )\n return [elem for (elem,order)in result]\n \n \n it=iter(iterable)\n result=[(key(elem),i,elem)for i,elem in zip(range(0,-n,-1),it)]\n if not result:\n return result\n heapify(result)\n top=result[0][0]\n order=-n\n _heapreplace=heapreplace\n for elem in it:\n k=key(elem)\n if top <k:\n _heapreplace(result,(k,order,elem))\n top,_order,_elem=result[0]\n order -=1\n result.sort(reverse=True )\n return [elem for (k,order,elem)in result]\n \n \n \n \n\"\"\"\ntry:\n from _heapq import *\nexcept ImportError:\n pass\ntry:\n from _heapq import _heapreplace_max\nexcept ImportError:\n pass\ntry:\n from _heapq import _heapify_max\nexcept ImportError:\n pass\ntry:\n from _heapq import _heappop_max\nexcept ImportError:\n pass\n\"\"\"\n\nif __name__ ==\"__main__\":\n\n import doctest\n print(doctest.testmod())\n", ["doctest"]], "shutil": [".py", "''\n\n\n\n\n\nimport os\nimport sys\nimport stat\nimport fnmatch\nimport collections\nimport errno\n\ntry :\n import zlib\n del zlib\n _ZLIB_SUPPORTED=True\nexcept ImportError:\n _ZLIB_SUPPORTED=False\n \ntry :\n import bz2\n del bz2\n _BZ2_SUPPORTED=True\nexcept ImportError:\n _BZ2_SUPPORTED=False\n \ntry :\n import lzma\n del lzma\n _LZMA_SUPPORTED=True\nexcept ImportError:\n _LZMA_SUPPORTED=False\n \ntry :\n from pwd import getpwnam\nexcept ImportError:\n getpwnam=None\n \ntry :\n from grp import getgrnam\nexcept ImportError:\n getgrnam=None\n \n__all__=[\"copyfileobj\",\"copyfile\",\"copymode\",\"copystat\",\"copy\",\"copy2\",\n\"copytree\",\"move\",\"rmtree\",\"Error\",\"SpecialFileError\",\n\"ExecError\",\"make_archive\",\"get_archive_formats\",\n\"register_archive_format\",\"unregister_archive_format\",\n\"get_unpack_formats\",\"register_unpack_format\",\n\"unregister_unpack_format\",\"unpack_archive\",\n\"ignore_patterns\",\"chown\",\"which\",\"get_terminal_size\",\n\"SameFileError\"]\n\n\nclass Error(OSError):\n pass\n \nclass SameFileError(Error):\n ''\n \nclass SpecialFileError(OSError):\n ''\n \n \nclass ExecError(OSError):\n ''\n \nclass ReadError(OSError):\n ''\n \nclass RegistryError(Exception):\n ''\n \n \n \ndef copyfileobj(fsrc,fdst,length=16 *1024):\n ''\n while 1:\n buf=fsrc.read(length)\n if not buf:\n break\n fdst.write(buf)\n \ndef _samefile(src,dst):\n\n if hasattr(os.path,'samefile'):\n try :\n return os.path.samefile(src,dst)\n except OSError:\n return False\n \n \n return (os.path.normcase(os.path.abspath(src))==\n os.path.normcase(os.path.abspath(dst)))\n \ndef copyfile(src,dst,*,follow_symlinks=True ):\n ''\n\n\n\n\n \n if _samefile(src,dst):\n raise SameFileError(\"{!r} and {!r} are the same file\".format(src,dst))\n \n for fn in [src,dst]:\n try :\n st=os.stat(fn)\n except OSError:\n \n pass\n else :\n \n if stat.S_ISFIFO(st.st_mode):\n raise SpecialFileError(\"`%s` is a named pipe\"%fn)\n \n if not follow_symlinks and os.path.islink(src):\n os.symlink(os.readlink(src),dst)\n else :\n with open(src,'rb')as fsrc:\n with open(dst,'wb')as fdst:\n copyfileobj(fsrc,fdst)\n return dst\n \ndef copymode(src,dst,*,follow_symlinks=True ):\n ''\n\n\n\n\n\n \n if not follow_symlinks and os.path.islink(src)and os.path.islink(dst):\n if hasattr(os,'lchmod'):\n stat_func,chmod_func=os.lstat,os.lchmod\n else :\n return\n elif hasattr(os,'chmod'):\n stat_func,chmod_func=os.stat,os.chmod\n else :\n return\n \n st=stat_func(src)\n chmod_func(dst,stat.S_IMODE(st.st_mode))\n \nif hasattr(os,'listxattr'):\n def _copyxattr(src,dst,*,follow_symlinks=True ):\n ''\n\n\n\n\n\n \n \n try :\n names=os.listxattr(src,follow_symlinks=follow_symlinks)\n except OSError as e:\n if e.errno not in (errno.ENOTSUP,errno.ENODATA):\n raise\n return\n for name in names:\n try :\n value=os.getxattr(src,name,follow_symlinks=follow_symlinks)\n os.setxattr(dst,name,value,follow_symlinks=follow_symlinks)\n except OSError as e:\n if e.errno not in (errno.EPERM,errno.ENOTSUP,errno.ENODATA):\n raise\nelse :\n def _copyxattr(*args,**kwargs):\n pass\n \ndef copystat(src,dst,*,follow_symlinks=True ):\n ''\n\n\n\n\n \n def _nop(*args,ns=None ,follow_symlinks=None ):\n pass\n \n \n follow=follow_symlinks or not (os.path.islink(src)and os.path.islink(dst))\n if follow:\n \n def lookup(name):\n return getattr(os,name,_nop)\n else :\n \n \n def lookup(name):\n fn=getattr(os,name,_nop)\n if fn in os.supports_follow_symlinks:\n return fn\n return _nop\n \n st=lookup(\"stat\")(src,follow_symlinks=follow)\n mode=stat.S_IMODE(st.st_mode)\n lookup(\"utime\")(dst,ns=(st.st_atime_ns,st.st_mtime_ns),\n follow_symlinks=follow)\n try :\n lookup(\"chmod\")(dst,mode,follow_symlinks=follow)\n except NotImplementedError:\n \n \n \n \n \n \n \n \n \n \n pass\n if hasattr(st,'st_flags'):\n try :\n lookup(\"chflags\")(dst,st.st_flags,follow_symlinks=follow)\n except OSError as why:\n for err in 'EOPNOTSUPP','ENOTSUP':\n if hasattr(errno,err)and why.errno ==getattr(errno,err):\n break\n else :\n raise\n _copyxattr(src,dst,follow_symlinks=follow)\n \ndef copy(src,dst,*,follow_symlinks=True ):\n ''\n\n\n\n\n\n\n\n\n\n \n if os.path.isdir(dst):\n dst=os.path.join(dst,os.path.basename(src))\n copyfile(src,dst,follow_symlinks=follow_symlinks)\n copymode(src,dst,follow_symlinks=follow_symlinks)\n return dst\n \ndef copy2(src,dst,*,follow_symlinks=True ):\n ''\n\n\n\n\n\n\n\n \n if os.path.isdir(dst):\n dst=os.path.join(dst,os.path.basename(src))\n copyfile(src,dst,follow_symlinks=follow_symlinks)\n copystat(src,dst,follow_symlinks=follow_symlinks)\n return dst\n \ndef ignore_patterns(*patterns):\n ''\n\n\n \n def _ignore_patterns(path,names):\n ignored_names=[]\n for pattern in patterns:\n ignored_names.extend(fnmatch.filter(names,pattern))\n return set(ignored_names)\n return _ignore_patterns\n \ndef copytree(src,dst,symlinks=False ,ignore=None ,copy_function=copy2,\nignore_dangling_symlinks=False ):\n ''\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n \n names=os.listdir(src)\n if ignore is not None :\n ignored_names=ignore(src,names)\n else :\n ignored_names=set()\n \n os.makedirs(dst)\n errors=[]\n for name in names:\n if name in ignored_names:\n continue\n srcname=os.path.join(src,name)\n dstname=os.path.join(dst,name)\n try :\n if os.path.islink(srcname):\n linkto=os.readlink(srcname)\n if symlinks:\n \n \n \n os.symlink(linkto,dstname)\n copystat(srcname,dstname,follow_symlinks=not symlinks)\n else :\n \n if not os.path.exists(linkto)and ignore_dangling_symlinks:\n continue\n \n if os.path.isdir(srcname):\n copytree(srcname,dstname,symlinks,ignore,\n copy_function)\n else :\n copy_function(srcname,dstname)\n elif os.path.isdir(srcname):\n copytree(srcname,dstname,symlinks,ignore,copy_function)\n else :\n \n copy_function(srcname,dstname)\n \n \n except Error as err:\n errors.extend(err.args[0])\n except OSError as why:\n errors.append((srcname,dstname,str(why)))\n try :\n copystat(src,dst)\n except OSError as why:\n \n if getattr(why,'winerror',None )is None :\n errors.append((src,dst,str(why)))\n if errors:\n raise Error(errors)\n return dst\n \n \ndef _rmtree_unsafe(path,onerror):\n try :\n with os.scandir(path)as scandir_it:\n entries=list(scandir_it)\n except OSError:\n onerror(os.scandir,path,sys.exc_info())\n entries=[]\n for entry in entries:\n fullname=entry.path\n try :\n is_dir=entry.is_dir(follow_symlinks=False )\n except OSError:\n is_dir=False\n if is_dir:\n try :\n if entry.is_symlink():\n \n \n \n raise OSError(\"Cannot call rmtree on a symbolic link\")\n except OSError:\n onerror(os.path.islink,fullname,sys.exc_info())\n continue\n _rmtree_unsafe(fullname,onerror)\n else :\n try :\n os.unlink(fullname)\n except OSError:\n onerror(os.unlink,fullname,sys.exc_info())\n try :\n os.rmdir(path)\n except OSError:\n onerror(os.rmdir,path,sys.exc_info())\n \n \ndef _rmtree_safe_fd(topfd,path,onerror):\n try :\n with os.scandir(topfd)as scandir_it:\n entries=list(scandir_it)\n except OSError as err:\n err.filename=path\n onerror(os.scandir,path,sys.exc_info())\n return\n for entry in entries:\n fullname=os.path.join(path,entry.name)\n try :\n is_dir=entry.is_dir(follow_symlinks=False )\n if is_dir:\n orig_st=entry.stat(follow_symlinks=False )\n is_dir=stat.S_ISDIR(orig_st.st_mode)\n except OSError:\n is_dir=False\n if is_dir:\n try :\n dirfd=os.open(entry.name,os.O_RDONLY,dir_fd=topfd)\n except OSError:\n onerror(os.open,fullname,sys.exc_info())\n else :\n try :\n if os.path.samestat(orig_st,os.fstat(dirfd)):\n _rmtree_safe_fd(dirfd,fullname,onerror)\n try :\n os.rmdir(entry.name,dir_fd=topfd)\n except OSError:\n onerror(os.rmdir,fullname,sys.exc_info())\n else :\n try :\n \n \n \n raise OSError(\"Cannot call rmtree on a symbolic \"\n \"link\")\n except OSError:\n onerror(os.path.islink,fullname,sys.exc_info())\n finally :\n os.close(dirfd)\n else :\n try :\n os.unlink(entry.name,dir_fd=topfd)\n except OSError:\n onerror(os.unlink,fullname,sys.exc_info())\n \n_use_fd_functions=({os.open,os.stat,os.unlink,os.rmdir}<=\nos.supports_dir_fd and\nos.scandir in os.supports_fd and\nos.stat in os.supports_follow_symlinks)\n\ndef rmtree(path,ignore_errors=False ,onerror=None ):\n ''\n\n\n\n\n\n\n\n\n \n if ignore_errors:\n def onerror(*args):\n pass\n elif onerror is None :\n def onerror(*args):\n raise\n if _use_fd_functions:\n \n if isinstance(path,bytes):\n path=os.fsdecode(path)\n \n \n try :\n orig_st=os.lstat(path)\n except Exception:\n onerror(os.lstat,path,sys.exc_info())\n return\n try :\n fd=os.open(path,os.O_RDONLY)\n except Exception:\n onerror(os.lstat,path,sys.exc_info())\n return\n try :\n if os.path.samestat(orig_st,os.fstat(fd)):\n _rmtree_safe_fd(fd,path,onerror)\n try :\n os.rmdir(path)\n except OSError:\n onerror(os.rmdir,path,sys.exc_info())\n else :\n try :\n \n raise OSError(\"Cannot call rmtree on a symbolic link\")\n except OSError:\n onerror(os.path.islink,path,sys.exc_info())\n finally :\n os.close(fd)\n else :\n try :\n if os.path.islink(path):\n \n raise OSError(\"Cannot call rmtree on a symbolic link\")\n except OSError:\n onerror(os.path.islink,path,sys.exc_info())\n \n return\n return _rmtree_unsafe(path,onerror)\n \n \n \nrmtree.avoids_symlink_attacks=_use_fd_functions\n\ndef _basename(path):\n\n\n sep=os.path.sep+(os.path.altsep or '')\n return os.path.basename(path.rstrip(sep))\n \ndef move(src,dst,copy_function=copy2):\n ''\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n \n real_dst=dst\n if os.path.isdir(dst):\n if _samefile(src,dst):\n \n \n os.rename(src,dst)\n return\n \n real_dst=os.path.join(dst,_basename(src))\n if os.path.exists(real_dst):\n raise Error(\"Destination path '%s' already exists\"%real_dst)\n try :\n os.rename(src,real_dst)\n except OSError:\n if os.path.islink(src):\n linkto=os.readlink(src)\n os.symlink(linkto,real_dst)\n os.unlink(src)\n elif os.path.isdir(src):\n if _destinsrc(src,dst):\n raise Error(\"Cannot move a directory '%s' into itself\"\n \" '%s'.\"%(src,dst))\n copytree(src,real_dst,copy_function=copy_function,\n symlinks=True )\n rmtree(src)\n else :\n copy_function(src,real_dst)\n os.unlink(src)\n return real_dst\n \ndef _destinsrc(src,dst):\n src=os.path.abspath(src)\n dst=os.path.abspath(dst)\n if not src.endswith(os.path.sep):\n src +=os.path.sep\n if not dst.endswith(os.path.sep):\n dst +=os.path.sep\n return dst.startswith(src)\n \ndef _get_gid(name):\n ''\n if getgrnam is None or name is None :\n return None\n try :\n result=getgrnam(name)\n except KeyError:\n result=None\n if result is not None :\n return result[2]\n return None\n \ndef _get_uid(name):\n ''\n if getpwnam is None or name is None :\n return None\n try :\n result=getpwnam(name)\n except KeyError:\n result=None\n if result is not None :\n return result[2]\n return None\n \ndef _make_tarball(base_name,base_dir,compress=\"gzip\",verbose=0,dry_run=0,\nowner=None ,group=None ,logger=None ):\n ''\n\n\n\n\n\n\n\n\n\n\n\n\n \n if compress is None :\n tar_compression=''\n elif _ZLIB_SUPPORTED and compress =='gzip':\n tar_compression='gz'\n elif _BZ2_SUPPORTED and compress =='bzip2':\n tar_compression='bz2'\n elif _LZMA_SUPPORTED and compress =='xz':\n tar_compression='xz'\n else :\n raise ValueError(\"bad value for 'compress', or compression format not \"\n \"supported : {0}\".format(compress))\n \n import tarfile\n \n compress_ext='.'+tar_compression if compress else ''\n archive_name=base_name+'.tar'+compress_ext\n archive_dir=os.path.dirname(archive_name)\n \n if archive_dir and not os.path.exists(archive_dir):\n if logger is not None :\n logger.info(\"creating %s\",archive_dir)\n if not dry_run:\n os.makedirs(archive_dir)\n \n \n if logger is not None :\n logger.info('Creating tar archive')\n \n uid=_get_uid(owner)\n gid=_get_gid(group)\n \n def _set_uid_gid(tarinfo):\n if gid is not None :\n tarinfo.gid=gid\n tarinfo.gname=group\n if uid is not None :\n tarinfo.uid=uid\n tarinfo.uname=owner\n return tarinfo\n \n if not dry_run:\n tar=tarfile.open(archive_name,'w|%s'%tar_compression)\n try :\n tar.add(base_dir,filter=_set_uid_gid)\n finally :\n tar.close()\n \n return archive_name\n \ndef _make_zipfile(base_name,base_dir,verbose=0,dry_run=0,logger=None ):\n ''\n\n\n\n \n import zipfile\n \n zip_filename=base_name+\".zip\"\n archive_dir=os.path.dirname(base_name)\n \n if archive_dir and not os.path.exists(archive_dir):\n if logger is not None :\n logger.info(\"creating %s\",archive_dir)\n if not dry_run:\n os.makedirs(archive_dir)\n \n if logger is not None :\n logger.info(\"creating '%s' and adding '%s' to it\",\n zip_filename,base_dir)\n \n if not dry_run:\n with zipfile.ZipFile(zip_filename,\"w\",\n compression=zipfile.ZIP_DEFLATED)as zf:\n path=os.path.normpath(base_dir)\n if path !=os.curdir:\n zf.write(path,path)\n if logger is not None :\n logger.info(\"adding '%s'\",path)\n for dirpath,dirnames,filenames in os.walk(base_dir):\n for name in sorted(dirnames):\n path=os.path.normpath(os.path.join(dirpath,name))\n zf.write(path,path)\n if logger is not None :\n logger.info(\"adding '%s'\",path)\n for name in filenames:\n path=os.path.normpath(os.path.join(dirpath,name))\n if os.path.isfile(path):\n zf.write(path,path)\n if logger is not None :\n logger.info(\"adding '%s'\",path)\n \n return zip_filename\n \n_ARCHIVE_FORMATS={\n'tar':(_make_tarball,[('compress',None )],\"uncompressed tar file\"),\n}\n\nif _ZLIB_SUPPORTED:\n _ARCHIVE_FORMATS['gztar']=(_make_tarball,[('compress','gzip')],\n \"gzip'ed tar-file\")\n _ARCHIVE_FORMATS['zip']=(_make_zipfile,[],\"ZIP file\")\n \nif _BZ2_SUPPORTED:\n _ARCHIVE_FORMATS['bztar']=(_make_tarball,[('compress','bzip2')],\n \"bzip2'ed tar-file\")\n \nif _LZMA_SUPPORTED:\n _ARCHIVE_FORMATS['xztar']=(_make_tarball,[('compress','xz')],\n \"xz'ed tar-file\")\n \ndef get_archive_formats():\n ''\n\n\n \n formats=[(name,registry[2])for name,registry in\n _ARCHIVE_FORMATS.items()]\n formats.sort()\n return formats\n \ndef register_archive_format(name,function,extra_args=None ,description=''):\n ''\n\n\n\n\n\n\n \n if extra_args is None :\n extra_args=[]\n if not callable(function):\n raise TypeError('The %s object is not callable'%function)\n if not isinstance(extra_args,(tuple,list)):\n raise TypeError('extra_args needs to be a sequence')\n for element in extra_args:\n if not isinstance(element,(tuple,list))or len(element)!=2:\n raise TypeError('extra_args elements are : (arg_name, value)')\n \n _ARCHIVE_FORMATS[name]=(function,extra_args,description)\n \ndef unregister_archive_format(name):\n del _ARCHIVE_FORMATS[name]\n \ndef make_archive(base_name,format,root_dir=None ,base_dir=None ,verbose=0,\ndry_run=0,owner=None ,group=None ,logger=None ):\n ''\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n \n save_cwd=os.getcwd()\n if root_dir is not None :\n if logger is not None :\n logger.debug(\"changing into '%s'\",root_dir)\n base_name=os.path.abspath(base_name)\n if not dry_run:\n os.chdir(root_dir)\n \n if base_dir is None :\n base_dir=os.curdir\n \n kwargs={'dry_run':dry_run,'logger':logger}\n \n try :\n format_info=_ARCHIVE_FORMATS[format]\n except KeyError:\n raise ValueError(\"unknown archive format '%s'\"%format)from None\n \n func=format_info[0]\n for arg,val in format_info[1]:\n kwargs[arg]=val\n \n if format !='zip':\n kwargs['owner']=owner\n kwargs['group']=group\n \n try :\n filename=func(base_name,base_dir,**kwargs)\n finally :\n if root_dir is not None :\n if logger is not None :\n logger.debug(\"changing back to '%s'\",save_cwd)\n os.chdir(save_cwd)\n \n return filename\n \n \ndef get_unpack_formats():\n ''\n\n\n\n \n formats=[(name,info[0],info[3])for name,info in\n _UNPACK_FORMATS.items()]\n formats.sort()\n return formats\n \ndef _check_unpack_options(extensions,function,extra_args):\n ''\n \n existing_extensions={}\n for name,info in _UNPACK_FORMATS.items():\n for ext in info[0]:\n existing_extensions[ext]=name\n \n for extension in extensions:\n if extension in existing_extensions:\n msg='%s is already registered for \"%s\"'\n raise RegistryError(msg %(extension,\n existing_extensions[extension]))\n \n if not callable(function):\n raise TypeError('The registered function must be a callable')\n \n \ndef register_unpack_format(name,extensions,function,extra_args=None ,\ndescription=''):\n ''\n\n\n\n\n\n\n\n\n\n\n\n\n\n \n if extra_args is None :\n extra_args=[]\n _check_unpack_options(extensions,function,extra_args)\n _UNPACK_FORMATS[name]=extensions,function,extra_args,description\n \ndef unregister_unpack_format(name):\n ''\n del _UNPACK_FORMATS[name]\n \ndef _ensure_directory(path):\n ''\n dirname=os.path.dirname(path)\n if not os.path.isdir(dirname):\n os.makedirs(dirname)\n \ndef _unpack_zipfile(filename,extract_dir):\n ''\n \n import zipfile\n \n if not zipfile.is_zipfile(filename):\n raise ReadError(\"%s is not a zip file\"%filename)\n \n zip=zipfile.ZipFile(filename)\n try :\n for info in zip.infolist():\n name=info.filename\n \n \n if name.startswith('/')or '..'in name:\n continue\n \n target=os.path.join(extract_dir,*name.split('/'))\n if not target:\n continue\n \n _ensure_directory(target)\n if not name.endswith('/'):\n \n data=zip.read(info.filename)\n f=open(target,'wb')\n try :\n f.write(data)\n finally :\n f.close()\n del data\n finally :\n zip.close()\n \ndef _unpack_tarfile(filename,extract_dir):\n ''\n \n import tarfile\n try :\n tarobj=tarfile.open(filename)\n except tarfile.TarError:\n raise ReadError(\n \"%s is not a compressed or uncompressed tar file\"%filename)\n try :\n tarobj.extractall(extract_dir)\n finally :\n tarobj.close()\n \n_UNPACK_FORMATS={\n'tar':(['.tar'],_unpack_tarfile,[],\"uncompressed tar file\"),\n'zip':(['.zip'],_unpack_zipfile,[],\"ZIP file\"),\n}\n\nif _ZLIB_SUPPORTED:\n _UNPACK_FORMATS['gztar']=(['.tar.gz','.tgz'],_unpack_tarfile,[],\n \"gzip'ed tar-file\")\n \nif _BZ2_SUPPORTED:\n _UNPACK_FORMATS['bztar']=(['.tar.bz2','.tbz2'],_unpack_tarfile,[],\n \"bzip2'ed tar-file\")\n \nif _LZMA_SUPPORTED:\n _UNPACK_FORMATS['xztar']=(['.tar.xz','.txz'],_unpack_tarfile,[],\n \"xz'ed tar-file\")\n \ndef _find_unpack_format(filename):\n for name,info in _UNPACK_FORMATS.items():\n for extension in info[0]:\n if filename.endswith(extension):\n return name\n return None\n \ndef unpack_archive(filename,extract_dir=None ,format=None ):\n ''\n\n\n\n\n\n\n\n\n\n\n\n\n \n if extract_dir is None :\n extract_dir=os.getcwd()\n \n extract_dir=os.fspath(extract_dir)\n filename=os.fspath(filename)\n \n if format is not None :\n try :\n format_info=_UNPACK_FORMATS[format]\n except KeyError:\n raise ValueError(\"Unknown unpack format '{0}'\".format(format))from None\n \n func=format_info[1]\n func(filename,extract_dir,**dict(format_info[2]))\n else :\n \n format=_find_unpack_format(filename)\n if format is None :\n raise ReadError(\"Unknown archive format '{0}'\".format(filename))\n \n func=_UNPACK_FORMATS[format][1]\n kwargs=dict(_UNPACK_FORMATS[format][2])\n func(filename,extract_dir,**kwargs)\n \n \nif hasattr(os,'statvfs'):\n\n __all__.append('disk_usage')\n _ntuple_diskusage=collections.namedtuple('usage','total used free')\n _ntuple_diskusage.total.__doc__='Total space in bytes'\n _ntuple_diskusage.used.__doc__='Used space in bytes'\n _ntuple_diskusage.free.__doc__='Free space in bytes'\n \n def disk_usage(path):\n ''\n\n\n\n \n st=os.statvfs(path)\n free=st.f_bavail *st.f_frsize\n total=st.f_blocks *st.f_frsize\n used=(st.f_blocks -st.f_bfree)*st.f_frsize\n return _ntuple_diskusage(total,used,free)\n \nelif os.name =='nt':\n\n import nt\n __all__.append('disk_usage')\n _ntuple_diskusage=collections.namedtuple('usage','total used free')\n \n def disk_usage(path):\n ''\n\n\n\n \n total,free=nt._getdiskusage(path)\n used=total -free\n return _ntuple_diskusage(total,used,free)\n \n \ndef chown(path,user=None ,group=None ):\n ''\n\n\n\n \n \n if user is None and group is None :\n raise ValueError(\"user and/or group must be set\")\n \n _user=user\n _group=group\n \n \n if user is None :\n _user=-1\n \n elif isinstance(user,str):\n _user=_get_uid(user)\n if _user is None :\n raise LookupError(\"no such user: {!r}\".format(user))\n \n if group is None :\n _group=-1\n elif not isinstance(group,int):\n _group=_get_gid(group)\n if _group is None :\n raise LookupError(\"no such group: {!r}\".format(group))\n \n os.chown(path,_user,_group)\n \ndef get_terminal_size(fallback=(80,24)):\n ''\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n \n \n try :\n columns=int(os.environ['COLUMNS'])\n except (KeyError,ValueError):\n columns=0\n \n try :\n lines=int(os.environ['LINES'])\n except (KeyError,ValueError):\n lines=0\n \n \n if columns <=0 or lines <=0:\n try :\n size=os.get_terminal_size(sys.__stdout__.fileno())\n except (AttributeError,ValueError,OSError):\n \n \n size=os.terminal_size(fallback)\n if columns <=0:\n columns=size.columns\n if lines <=0:\n lines=size.lines\n \n return os.terminal_size((columns,lines))\n \ndef which(cmd,mode=os.F_OK |os.X_OK,path=None ):\n ''\n\n\n\n\n\n\n\n \n \n \n \n def _access_check(fn,mode):\n return (os.path.exists(fn)and os.access(fn,mode)\n and not os.path.isdir(fn))\n \n \n \n \n if os.path.dirname(cmd):\n if _access_check(cmd,mode):\n return cmd\n return None\n \n if path is None :\n path=os.environ.get(\"PATH\",os.defpath)\n if not path:\n return None\n path=path.split(os.pathsep)\n \n if sys.platform ==\"win32\":\n \n if not os.curdir in path:\n path.insert(0,os.curdir)\n \n \n pathext=os.environ.get(\"PATHEXT\",\"\").split(os.pathsep)\n \n \n \n \n if any(cmd.lower().endswith(ext.lower())for ext in pathext):\n files=[cmd]\n else :\n files=[cmd+ext for ext in pathext]\n else :\n \n \n files=[cmd]\n \n seen=set()\n for dir in path:\n normdir=os.path.normcase(dir)\n if not normdir in seen:\n seen.add(normdir)\n for thefile in files:\n name=os.path.join(dir,thefile)\n if _access_check(name,mode):\n return name\n return None\n", ["bz2", "collections", "errno", "fnmatch", "grp", "lzma", "nt", "os", "pwd", "stat", "sys", "tarfile", "zipfile", "zlib"]], "tarfile": [".py", "#!/usr/bin/env python3\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n''\n\n\nversion=\"0.9.0\"\n__author__=\"Lars Gust\\u00e4bel (lars@gustaebel.de)\"\n__credits__=\"Gustavo Niemeyer, Niels Gust\\u00e4bel, Richard Townsend.\"\n\n\n\n\nfrom builtins import open as bltn_open\nimport sys\nimport os\nimport io\nimport shutil\nimport stat\nimport time\nimport struct\nimport copy\nimport re\n\ntry :\n import pwd\nexcept ImportError:\n pwd=None\ntry :\n import grp\nexcept ImportError:\n grp=None\n \n \nsymlink_exception=(AttributeError,NotImplementedError)\ntry :\n\n\n symlink_exception +=(OSError,)\nexcept NameError:\n pass\n \n \n__all__=[\"TarFile\",\"TarInfo\",\"is_tarfile\",\"TarError\",\"ReadError\",\n\"CompressionError\",\"StreamError\",\"ExtractError\",\"HeaderError\",\n\"ENCODING\",\"USTAR_FORMAT\",\"GNU_FORMAT\",\"PAX_FORMAT\",\n\"DEFAULT_FORMAT\",\"open\"]\n\n\n\n\nNUL=b\"\\0\"\nBLOCKSIZE=512\nRECORDSIZE=BLOCKSIZE *20\nGNU_MAGIC=b\"ustar \\0\"\nPOSIX_MAGIC=b\"ustar\\x0000\"\n\nLENGTH_NAME=100\nLENGTH_LINK=100\nLENGTH_PREFIX=155\n\nREGTYPE=b\"0\"\nAREGTYPE=b\"\\0\"\nLNKTYPE=b\"1\"\nSYMTYPE=b\"2\"\nCHRTYPE=b\"3\"\nBLKTYPE=b\"4\"\nDIRTYPE=b\"5\"\nFIFOTYPE=b\"6\"\nCONTTYPE=b\"7\"\n\nGNUTYPE_LONGNAME=b\"L\"\nGNUTYPE_LONGLINK=b\"K\"\nGNUTYPE_SPARSE=b\"S\"\n\nXHDTYPE=b\"x\"\nXGLTYPE=b\"g\"\nSOLARIS_XHDTYPE=b\"X\"\n\nUSTAR_FORMAT=0\nGNU_FORMAT=1\nPAX_FORMAT=2\nDEFAULT_FORMAT=GNU_FORMAT\n\n\n\n\n\nSUPPORTED_TYPES=(REGTYPE,AREGTYPE,LNKTYPE,\nSYMTYPE,DIRTYPE,FIFOTYPE,\nCONTTYPE,CHRTYPE,BLKTYPE,\nGNUTYPE_LONGNAME,GNUTYPE_LONGLINK,\nGNUTYPE_SPARSE)\n\n\nREGULAR_TYPES=(REGTYPE,AREGTYPE,\nCONTTYPE,GNUTYPE_SPARSE)\n\n\nGNU_TYPES=(GNUTYPE_LONGNAME,GNUTYPE_LONGLINK,\nGNUTYPE_SPARSE)\n\n\nPAX_FIELDS=(\"path\",\"linkpath\",\"size\",\"mtime\",\n\"uid\",\"gid\",\"uname\",\"gname\")\n\n\nPAX_NAME_FIELDS={\"path\",\"linkpath\",\"uname\",\"gname\"}\n\n\n\nPAX_NUMBER_FIELDS={\n\"atime\":float,\n\"ctime\":float,\n\"mtime\":float,\n\"uid\":int,\n\"gid\":int,\n\"size\":int\n}\n\n\n\n\nif os.name ==\"nt\":\n ENCODING=\"utf-8\"\nelse :\n ENCODING=sys.getfilesystemencoding()\n \n \n \n \n \ndef stn(s,length,encoding,errors):\n ''\n \n s=s.encode(encoding,errors)\n return s[:length]+(length -len(s))*NUL\n \ndef nts(s,encoding,errors):\n ''\n \n p=s.find(b\"\\0\")\n if p !=-1:\n s=s[:p]\n return s.decode(encoding,errors)\n \ndef nti(s):\n ''\n \n \n \n if s[0]in (0o200,0o377):\n n=0\n for i in range(len(s)-1):\n n <<=8\n n +=s[i+1]\n if s[0]==0o377:\n n=-(256 **(len(s)-1)-n)\n else :\n try :\n s=nts(s,\"ascii\",\"strict\")\n n=int(s.strip()or \"0\",8)\n except ValueError:\n raise InvalidHeaderError(\"invalid header\")\n return n\n \ndef itn(n,digits=8,format=DEFAULT_FORMAT):\n ''\n \n \n \n \n \n \n \n \n \n n=int(n)\n if 0 <=n <8 **(digits -1):\n s=bytes(\"%0*o\"%(digits -1,n),\"ascii\")+NUL\n elif format ==GNU_FORMAT and -256 **(digits -1)<=n <256 **(digits -1):\n if n >=0:\n s=bytearray([0o200])\n else :\n s=bytearray([0o377])\n n=256 **digits+n\n \n for i in range(digits -1):\n s.insert(1,n&0o377)\n n >>=8\n else :\n raise ValueError(\"overflow in number field\")\n \n return s\n \ndef calc_chksums(buf):\n ''\n\n\n\n\n\n\n \n unsigned_chksum=256+sum(struct.unpack_from(\"148B8x356B\",buf))\n signed_chksum=256+sum(struct.unpack_from(\"148b8x356b\",buf))\n return unsigned_chksum,signed_chksum\n \ndef copyfileobj(src,dst,length=None ,exception=OSError,bufsize=None ):\n ''\n\n \n bufsize=bufsize or 16 *1024\n if length ==0:\n return\n if length is None :\n shutil.copyfileobj(src,dst,bufsize)\n return\n \n blocks,remainder=divmod(length,bufsize)\n for b in range(blocks):\n buf=src.read(bufsize)\n if len(buf)<bufsize:\n raise exception(\"unexpected end of data\")\n dst.write(buf)\n \n if remainder !=0:\n buf=src.read(remainder)\n if len(buf)<remainder:\n raise exception(\"unexpected end of data\")\n dst.write(buf)\n return\n \ndef filemode(mode):\n ''\n import warnings\n warnings.warn(\"deprecated in favor of stat.filemode\",\n DeprecationWarning,2)\n return stat.filemode(mode)\n \ndef _safe_print(s):\n encoding=getattr(sys.stdout,'encoding',None )\n if encoding is not None :\n s=s.encode(encoding,'backslashreplace').decode(encoding)\n print(s,end=' ')\n \n \nclass TarError(Exception):\n ''\n pass\nclass ExtractError(TarError):\n ''\n pass\nclass ReadError(TarError):\n ''\n pass\nclass CompressionError(TarError):\n ''\n pass\nclass StreamError(TarError):\n ''\n pass\nclass HeaderError(TarError):\n ''\n pass\nclass EmptyHeaderError(HeaderError):\n ''\n pass\nclass TruncatedHeaderError(HeaderError):\n ''\n pass\nclass EOFHeaderError(HeaderError):\n ''\n pass\nclass InvalidHeaderError(HeaderError):\n ''\n pass\nclass SubsequentHeaderError(HeaderError):\n ''\n pass\n \n \n \n \nclass _LowLevelFile:\n ''\n\n\n \n \n def __init__(self,name,mode):\n mode={\n \"r\":os.O_RDONLY,\n \"w\":os.O_WRONLY |os.O_CREAT |os.O_TRUNC,\n }[mode]\n if hasattr(os,\"O_BINARY\"):\n mode |=os.O_BINARY\n self.fd=os.open(name,mode,0o666)\n \n def close(self):\n os.close(self.fd)\n \n def read(self,size):\n return os.read(self.fd,size)\n \n def write(self,s):\n os.write(self.fd,s)\n \nclass _Stream:\n ''\n\n\n\n\n\n\n\n \n \n def __init__(self,name,mode,comptype,fileobj,bufsize):\n ''\n \n self._extfileobj=True\n if fileobj is None :\n fileobj=_LowLevelFile(name,mode)\n self._extfileobj=False\n \n if comptype =='*':\n \n \n fileobj=_StreamProxy(fileobj)\n comptype=fileobj.getcomptype()\n \n self.name=name or \"\"\n self.mode=mode\n self.comptype=comptype\n self.fileobj=fileobj\n self.bufsize=bufsize\n self.buf=b\"\"\n self.pos=0\n self.closed=False\n \n try :\n if comptype ==\"gz\":\n try :\n import zlib\n except ImportError:\n raise CompressionError(\"zlib module is not available\")\n self.zlib=zlib\n self.crc=zlib.crc32(b\"\")\n if mode ==\"r\":\n self._init_read_gz()\n self.exception=zlib.error\n else :\n self._init_write_gz()\n \n elif comptype ==\"bz2\":\n try :\n import bz2\n except ImportError:\n raise CompressionError(\"bz2 module is not available\")\n if mode ==\"r\":\n self.dbuf=b\"\"\n self.cmp=bz2.BZ2Decompressor()\n self.exception=OSError\n else :\n self.cmp=bz2.BZ2Compressor()\n \n elif comptype ==\"xz\":\n try :\n import lzma\n except ImportError:\n raise CompressionError(\"lzma module is not available\")\n if mode ==\"r\":\n self.dbuf=b\"\"\n self.cmp=lzma.LZMADecompressor()\n self.exception=lzma.LZMAError\n else :\n self.cmp=lzma.LZMACompressor()\n \n elif comptype !=\"tar\":\n raise CompressionError(\"unknown compression type %r\"%comptype)\n \n except :\n if not self._extfileobj:\n self.fileobj.close()\n self.closed=True\n raise\n \n def __del__(self):\n if hasattr(self,\"closed\")and not self.closed:\n self.close()\n \n def _init_write_gz(self):\n ''\n \n self.cmp=self.zlib.compressobj(9,self.zlib.DEFLATED,\n -self.zlib.MAX_WBITS,\n self.zlib.DEF_MEM_LEVEL,\n 0)\n timestamp=struct.pack(\"<L\",int(time.time()))\n self.__write(b\"\\037\\213\\010\\010\"+timestamp+b\"\\002\\377\")\n if self.name.endswith(\".gz\"):\n self.name=self.name[:-3]\n \n self.__write(self.name.encode(\"iso-8859-1\",\"replace\")+NUL)\n \n def write(self,s):\n ''\n \n if self.comptype ==\"gz\":\n self.crc=self.zlib.crc32(s,self.crc)\n self.pos +=len(s)\n if self.comptype !=\"tar\":\n s=self.cmp.compress(s)\n self.__write(s)\n \n def __write(self,s):\n ''\n\n \n self.buf +=s\n while len(self.buf)>self.bufsize:\n self.fileobj.write(self.buf[:self.bufsize])\n self.buf=self.buf[self.bufsize:]\n \n def close(self):\n ''\n\n \n if self.closed:\n return\n \n self.closed=True\n try :\n if self.mode ==\"w\"and self.comptype !=\"tar\":\n self.buf +=self.cmp.flush()\n \n if self.mode ==\"w\"and self.buf:\n self.fileobj.write(self.buf)\n self.buf=b\"\"\n if self.comptype ==\"gz\":\n self.fileobj.write(struct.pack(\"<L\",self.crc))\n self.fileobj.write(struct.pack(\"<L\",self.pos&0xffffFFFF))\n finally :\n if not self._extfileobj:\n self.fileobj.close()\n \n def _init_read_gz(self):\n ''\n \n self.cmp=self.zlib.decompressobj(-self.zlib.MAX_WBITS)\n self.dbuf=b\"\"\n \n \n if self.__read(2)!=b\"\\037\\213\":\n raise ReadError(\"not a gzip file\")\n if self.__read(1)!=b\"\\010\":\n raise CompressionError(\"unsupported compression method\")\n \n flag=ord(self.__read(1))\n self.__read(6)\n \n if flag&4:\n xlen=ord(self.__read(1))+256 *ord(self.__read(1))\n self.read(xlen)\n if flag&8:\n while True :\n s=self.__read(1)\n if not s or s ==NUL:\n break\n if flag&16:\n while True :\n s=self.__read(1)\n if not s or s ==NUL:\n break\n if flag&2:\n self.__read(2)\n \n def tell(self):\n ''\n \n return self.pos\n \n def seek(self,pos=0):\n ''\n\n \n if pos -self.pos >=0:\n blocks,remainder=divmod(pos -self.pos,self.bufsize)\n for i in range(blocks):\n self.read(self.bufsize)\n self.read(remainder)\n else :\n raise StreamError(\"seeking backwards is not allowed\")\n return self.pos\n \n def read(self,size=None ):\n ''\n\n\n \n if size is None :\n t=[]\n while True :\n buf=self._read(self.bufsize)\n if not buf:\n break\n t.append(buf)\n buf=\"\".join(t)\n else :\n buf=self._read(size)\n self.pos +=len(buf)\n return buf\n \n def _read(self,size):\n ''\n \n if self.comptype ==\"tar\":\n return self.__read(size)\n \n c=len(self.dbuf)\n while c <size:\n buf=self.__read(self.bufsize)\n if not buf:\n break\n try :\n buf=self.cmp.decompress(buf)\n except self.exception:\n raise ReadError(\"invalid compressed data\")\n self.dbuf +=buf\n c +=len(buf)\n buf=self.dbuf[:size]\n self.dbuf=self.dbuf[size:]\n return buf\n \n def __read(self,size):\n ''\n\n \n c=len(self.buf)\n while c <size:\n buf=self.fileobj.read(self.bufsize)\n if not buf:\n break\n self.buf +=buf\n c +=len(buf)\n buf=self.buf[:size]\n self.buf=self.buf[size:]\n return buf\n \n \nclass _StreamProxy(object):\n ''\n\n \n \n def __init__(self,fileobj):\n self.fileobj=fileobj\n self.buf=self.fileobj.read(BLOCKSIZE)\n \n def read(self,size):\n self.read=self.fileobj.read\n return self.buf\n \n def getcomptype(self):\n if self.buf.startswith(b\"\\x1f\\x8b\\x08\"):\n return \"gz\"\n elif self.buf[0:3]==b\"BZh\"and self.buf[4:10]==b\"1AY&SY\":\n return \"bz2\"\n elif self.buf.startswith((b\"\\x5d\\x00\\x00\\x80\",b\"\\xfd7zXZ\")):\n return \"xz\"\n else :\n return \"tar\"\n \n def close(self):\n self.fileobj.close()\n \n \n \n \n \nclass _FileInFile(object):\n ''\n\n\n \n \n def __init__(self,fileobj,offset,size,blockinfo=None ):\n self.fileobj=fileobj\n self.offset=offset\n self.size=size\n self.position=0\n self.name=getattr(fileobj,\"name\",None )\n self.closed=False\n \n if blockinfo is None :\n blockinfo=[(0,size)]\n \n \n self.map_index=0\n self.map=[]\n lastpos=0\n realpos=self.offset\n for offset,size in blockinfo:\n if offset >lastpos:\n self.map.append((False ,lastpos,offset,None ))\n self.map.append((True ,offset,offset+size,realpos))\n realpos +=size\n lastpos=offset+size\n if lastpos <self.size:\n self.map.append((False ,lastpos,self.size,None ))\n \n def flush(self):\n pass\n \n def readable(self):\n return True\n \n def writable(self):\n return False\n \n def seekable(self):\n return self.fileobj.seekable()\n \n def tell(self):\n ''\n \n return self.position\n \n def seek(self,position,whence=io.SEEK_SET):\n ''\n \n if whence ==io.SEEK_SET:\n self.position=min(max(position,0),self.size)\n elif whence ==io.SEEK_CUR:\n if position <0:\n self.position=max(self.position+position,0)\n else :\n self.position=min(self.position+position,self.size)\n elif whence ==io.SEEK_END:\n self.position=max(min(self.size+position,self.size),0)\n else :\n raise ValueError(\"Invalid argument\")\n return self.position\n \n def read(self,size=None ):\n ''\n \n if size is None :\n size=self.size -self.position\n else :\n size=min(size,self.size -self.position)\n \n buf=b\"\"\n while size >0:\n while True :\n data,start,stop,offset=self.map[self.map_index]\n if start <=self.position <stop:\n break\n else :\n self.map_index +=1\n if self.map_index ==len(self.map):\n self.map_index=0\n length=min(size,stop -self.position)\n if data:\n self.fileobj.seek(offset+(self.position -start))\n b=self.fileobj.read(length)\n if len(b)!=length:\n raise ReadError(\"unexpected end of data\")\n buf +=b\n else :\n buf +=NUL *length\n size -=length\n self.position +=length\n return buf\n \n def readinto(self,b):\n buf=self.read(len(b))\n b[:len(buf)]=buf\n return len(buf)\n \n def close(self):\n self.closed=True\n \n \nclass ExFileObject(io.BufferedReader):\n\n def __init__(self,tarfile,tarinfo):\n fileobj=_FileInFile(tarfile.fileobj,tarinfo.offset_data,\n tarinfo.size,tarinfo.sparse)\n super().__init__(fileobj)\n \n \n \n \n \nclass TarInfo(object):\n ''\n\n\n\n\n \n \n __slots__=(\"name\",\"mode\",\"uid\",\"gid\",\"size\",\"mtime\",\n \"chksum\",\"type\",\"linkname\",\"uname\",\"gname\",\n \"devmajor\",\"devminor\",\n \"offset\",\"offset_data\",\"pax_headers\",\"sparse\",\n \"tarfile\",\"_sparse_structs\",\"_link_target\")\n \n def __init__(self,name=\"\"):\n ''\n\n \n self.name=name\n self.mode=0o644\n self.uid=0\n self.gid=0\n self.size=0\n self.mtime=0\n self.chksum=0\n self.type=REGTYPE\n self.linkname=\"\"\n self.uname=\"\"\n self.gname=\"\"\n self.devmajor=0\n self.devminor=0\n \n self.offset=0\n self.offset_data=0\n \n self.sparse=None\n self.pax_headers={}\n \n \n \n @property\n def path(self):\n return self.name\n \n @path.setter\n def path(self,name):\n self.name=name\n \n @property\n def linkpath(self):\n return self.linkname\n \n @linkpath.setter\n def linkpath(self,linkname):\n self.linkname=linkname\n \n def __repr__(self):\n return \"<%s %r at %#x>\"%(self.__class__.__name__,self.name,id(self))\n \n def get_info(self):\n ''\n \n info={\n \"name\":self.name,\n \"mode\":self.mode&0o7777,\n \"uid\":self.uid,\n \"gid\":self.gid,\n \"size\":self.size,\n \"mtime\":self.mtime,\n \"chksum\":self.chksum,\n \"type\":self.type,\n \"linkname\":self.linkname,\n \"uname\":self.uname,\n \"gname\":self.gname,\n \"devmajor\":self.devmajor,\n \"devminor\":self.devminor\n }\n \n if info[\"type\"]==DIRTYPE and not info[\"name\"].endswith(\"/\"):\n info[\"name\"]+=\"/\"\n \n return info\n \n def tobuf(self,format=DEFAULT_FORMAT,encoding=ENCODING,errors=\"surrogateescape\"):\n ''\n \n info=self.get_info()\n \n if format ==USTAR_FORMAT:\n return self.create_ustar_header(info,encoding,errors)\n elif format ==GNU_FORMAT:\n return self.create_gnu_header(info,encoding,errors)\n elif format ==PAX_FORMAT:\n return self.create_pax_header(info,encoding)\n else :\n raise ValueError(\"invalid format\")\n \n def create_ustar_header(self,info,encoding,errors):\n ''\n \n info[\"magic\"]=POSIX_MAGIC\n \n if len(info[\"linkname\"].encode(encoding,errors))>LENGTH_LINK:\n raise ValueError(\"linkname is too long\")\n \n if len(info[\"name\"].encode(encoding,errors))>LENGTH_NAME:\n info[\"prefix\"],info[\"name\"]=self._posix_split_name(info[\"name\"],encoding,errors)\n \n return self._create_header(info,USTAR_FORMAT,encoding,errors)\n \n def create_gnu_header(self,info,encoding,errors):\n ''\n \n info[\"magic\"]=GNU_MAGIC\n \n buf=b\"\"\n if len(info[\"linkname\"].encode(encoding,errors))>LENGTH_LINK:\n buf +=self._create_gnu_long_header(info[\"linkname\"],GNUTYPE_LONGLINK,encoding,errors)\n \n if len(info[\"name\"].encode(encoding,errors))>LENGTH_NAME:\n buf +=self._create_gnu_long_header(info[\"name\"],GNUTYPE_LONGNAME,encoding,errors)\n \n return buf+self._create_header(info,GNU_FORMAT,encoding,errors)\n \n def create_pax_header(self,info,encoding):\n ''\n\n\n \n info[\"magic\"]=POSIX_MAGIC\n pax_headers=self.pax_headers.copy()\n \n \n \n for name,hname,length in (\n (\"name\",\"path\",LENGTH_NAME),(\"linkname\",\"linkpath\",LENGTH_LINK),\n (\"uname\",\"uname\",32),(\"gname\",\"gname\",32)):\n \n if hname in pax_headers:\n \n continue\n \n \n try :\n info[name].encode(\"ascii\",\"strict\")\n except UnicodeEncodeError:\n pax_headers[hname]=info[name]\n continue\n \n if len(info[name])>length:\n pax_headers[hname]=info[name]\n \n \n \n for name,digits in ((\"uid\",8),(\"gid\",8),(\"size\",12),(\"mtime\",12)):\n if name in pax_headers:\n \n info[name]=0\n continue\n \n val=info[name]\n if not 0 <=val <8 **(digits -1)or isinstance(val,float):\n pax_headers[name]=str(val)\n info[name]=0\n \n \n if pax_headers:\n buf=self._create_pax_generic_header(pax_headers,XHDTYPE,encoding)\n else :\n buf=b\"\"\n \n return buf+self._create_header(info,USTAR_FORMAT,\"ascii\",\"replace\")\n \n @classmethod\n def create_pax_global_header(cls,pax_headers):\n ''\n \n return cls._create_pax_generic_header(pax_headers,XGLTYPE,\"utf-8\")\n \n def _posix_split_name(self,name,encoding,errors):\n ''\n\n \n components=name.split(\"/\")\n for i in range(1,len(components)):\n prefix=\"/\".join(components[:i])\n name=\"/\".join(components[i:])\n if len(prefix.encode(encoding,errors))<=LENGTH_PREFIX and\\\n len(name.encode(encoding,errors))<=LENGTH_NAME:\n break\n else :\n raise ValueError(\"name is too long\")\n \n return prefix,name\n \n @staticmethod\n def _create_header(info,format,encoding,errors):\n ''\n\n \n parts=[\n stn(info.get(\"name\",\"\"),100,encoding,errors),\n itn(info.get(\"mode\",0)&0o7777,8,format),\n itn(info.get(\"uid\",0),8,format),\n itn(info.get(\"gid\",0),8,format),\n itn(info.get(\"size\",0),12,format),\n itn(info.get(\"mtime\",0),12,format),\n b\" \",\n info.get(\"type\",REGTYPE),\n stn(info.get(\"linkname\",\"\"),100,encoding,errors),\n info.get(\"magic\",POSIX_MAGIC),\n stn(info.get(\"uname\",\"\"),32,encoding,errors),\n stn(info.get(\"gname\",\"\"),32,encoding,errors),\n itn(info.get(\"devmajor\",0),8,format),\n itn(info.get(\"devminor\",0),8,format),\n stn(info.get(\"prefix\",\"\"),155,encoding,errors)\n ]\n \n buf=struct.pack(\"%ds\"%BLOCKSIZE,b\"\".join(parts))\n chksum=calc_chksums(buf[-BLOCKSIZE:])[0]\n buf=buf[:-364]+bytes(\"%06o\\0\"%chksum,\"ascii\")+buf[-357:]\n return buf\n \n @staticmethod\n def _create_payload(payload):\n ''\n\n \n blocks,remainder=divmod(len(payload),BLOCKSIZE)\n if remainder >0:\n payload +=(BLOCKSIZE -remainder)*NUL\n return payload\n \n @classmethod\n def _create_gnu_long_header(cls,name,type,encoding,errors):\n ''\n\n \n name=name.encode(encoding,errors)+NUL\n \n info={}\n info[\"name\"]=\"././@LongLink\"\n info[\"type\"]=type\n info[\"size\"]=len(name)\n info[\"magic\"]=GNU_MAGIC\n \n \n return cls._create_header(info,USTAR_FORMAT,encoding,errors)+\\\n cls._create_payload(name)\n \n @classmethod\n def _create_pax_generic_header(cls,pax_headers,type,encoding):\n ''\n\n\n \n \n \n binary=False\n for keyword,value in pax_headers.items():\n try :\n value.encode(\"utf-8\",\"strict\")\n except UnicodeEncodeError:\n binary=True\n break\n \n records=b\"\"\n if binary:\n \n records +=b\"21 hdrcharset=BINARY\\n\"\n \n for keyword,value in pax_headers.items():\n keyword=keyword.encode(\"utf-8\")\n if binary:\n \n \n value=value.encode(encoding,\"surrogateescape\")\n else :\n value=value.encode(\"utf-8\")\n \n l=len(keyword)+len(value)+3\n n=p=0\n while True :\n n=l+len(str(p))\n if n ==p:\n break\n p=n\n records +=bytes(str(p),\"ascii\")+b\" \"+keyword+b\"=\"+value+b\"\\n\"\n \n \n \n info={}\n info[\"name\"]=\"././@PaxHeader\"\n info[\"type\"]=type\n info[\"size\"]=len(records)\n info[\"magic\"]=POSIX_MAGIC\n \n \n return cls._create_header(info,USTAR_FORMAT,\"ascii\",\"replace\")+\\\n cls._create_payload(records)\n \n @classmethod\n def frombuf(cls,buf,encoding,errors):\n ''\n \n if len(buf)==0:\n raise EmptyHeaderError(\"empty header\")\n if len(buf)!=BLOCKSIZE:\n raise TruncatedHeaderError(\"truncated header\")\n if buf.count(NUL)==BLOCKSIZE:\n raise EOFHeaderError(\"end of file header\")\n \n chksum=nti(buf[148:156])\n if chksum not in calc_chksums(buf):\n raise InvalidHeaderError(\"bad checksum\")\n \n obj=cls()\n obj.name=nts(buf[0:100],encoding,errors)\n obj.mode=nti(buf[100:108])\n obj.uid=nti(buf[108:116])\n obj.gid=nti(buf[116:124])\n obj.size=nti(buf[124:136])\n obj.mtime=nti(buf[136:148])\n obj.chksum=chksum\n obj.type=buf[156:157]\n obj.linkname=nts(buf[157:257],encoding,errors)\n obj.uname=nts(buf[265:297],encoding,errors)\n obj.gname=nts(buf[297:329],encoding,errors)\n obj.devmajor=nti(buf[329:337])\n obj.devminor=nti(buf[337:345])\n prefix=nts(buf[345:500],encoding,errors)\n \n \n \n if obj.type ==AREGTYPE and obj.name.endswith(\"/\"):\n obj.type=DIRTYPE\n \n \n \n \n if obj.type ==GNUTYPE_SPARSE:\n pos=386\n structs=[]\n for i in range(4):\n try :\n offset=nti(buf[pos:pos+12])\n numbytes=nti(buf[pos+12:pos+24])\n except ValueError:\n break\n structs.append((offset,numbytes))\n pos +=24\n isextended=bool(buf[482])\n origsize=nti(buf[483:495])\n obj._sparse_structs=(structs,isextended,origsize)\n \n \n if obj.isdir():\n obj.name=obj.name.rstrip(\"/\")\n \n \n if prefix and obj.type not in GNU_TYPES:\n obj.name=prefix+\"/\"+obj.name\n return obj\n \n @classmethod\n def fromtarfile(cls,tarfile):\n ''\n\n \n buf=tarfile.fileobj.read(BLOCKSIZE)\n obj=cls.frombuf(buf,tarfile.encoding,tarfile.errors)\n obj.offset=tarfile.fileobj.tell()-BLOCKSIZE\n return obj._proc_member(tarfile)\n \n \n \n \n \n \n \n \n \n \n \n \n def _proc_member(self,tarfile):\n ''\n\n \n if self.type in (GNUTYPE_LONGNAME,GNUTYPE_LONGLINK):\n return self._proc_gnulong(tarfile)\n elif self.type ==GNUTYPE_SPARSE:\n return self._proc_sparse(tarfile)\n elif self.type in (XHDTYPE,XGLTYPE,SOLARIS_XHDTYPE):\n return self._proc_pax(tarfile)\n else :\n return self._proc_builtin(tarfile)\n \n def _proc_builtin(self,tarfile):\n ''\n\n \n self.offset_data=tarfile.fileobj.tell()\n offset=self.offset_data\n if self.isreg()or self.type not in SUPPORTED_TYPES:\n \n offset +=self._block(self.size)\n tarfile.offset=offset\n \n \n \n self._apply_pax_info(tarfile.pax_headers,tarfile.encoding,tarfile.errors)\n \n return self\n \n def _proc_gnulong(self,tarfile):\n ''\n\n \n buf=tarfile.fileobj.read(self._block(self.size))\n \n \n try :\n next=self.fromtarfile(tarfile)\n except HeaderError:\n raise SubsequentHeaderError(\"missing or bad subsequent header\")\n \n \n \n next.offset=self.offset\n if self.type ==GNUTYPE_LONGNAME:\n next.name=nts(buf,tarfile.encoding,tarfile.errors)\n elif self.type ==GNUTYPE_LONGLINK:\n next.linkname=nts(buf,tarfile.encoding,tarfile.errors)\n \n return next\n \n def _proc_sparse(self,tarfile):\n ''\n \n \n structs,isextended,origsize=self._sparse_structs\n del self._sparse_structs\n \n \n while isextended:\n buf=tarfile.fileobj.read(BLOCKSIZE)\n pos=0\n for i in range(21):\n try :\n offset=nti(buf[pos:pos+12])\n numbytes=nti(buf[pos+12:pos+24])\n except ValueError:\n break\n if offset and numbytes:\n structs.append((offset,numbytes))\n pos +=24\n isextended=bool(buf[504])\n self.sparse=structs\n \n self.offset_data=tarfile.fileobj.tell()\n tarfile.offset=self.offset_data+self._block(self.size)\n self.size=origsize\n return self\n \n def _proc_pax(self,tarfile):\n ''\n\n \n \n buf=tarfile.fileobj.read(self._block(self.size))\n \n \n \n \n if self.type ==XGLTYPE:\n pax_headers=tarfile.pax_headers\n else :\n pax_headers=tarfile.pax_headers.copy()\n \n \n \n \n \n \n match=re.search(br\"\\d+ hdrcharset=([^\\n]+)\\n\",buf)\n if match is not None :\n pax_headers[\"hdrcharset\"]=match.group(1).decode(\"utf-8\")\n \n \n \n \n hdrcharset=pax_headers.get(\"hdrcharset\")\n if hdrcharset ==\"BINARY\":\n encoding=tarfile.encoding\n else :\n encoding=\"utf-8\"\n \n \n \n \n \n regex=re.compile(br\"(\\d+) ([^=]+)=\")\n pos=0\n while True :\n match=regex.match(buf,pos)\n if not match:\n break\n \n length,keyword=match.groups()\n length=int(length)\n value=buf[match.end(2)+1:match.start(1)+length -1]\n \n \n \n \n \n \n \n \n keyword=self._decode_pax_field(keyword,\"utf-8\",\"utf-8\",\n tarfile.errors)\n if keyword in PAX_NAME_FIELDS:\n value=self._decode_pax_field(value,encoding,tarfile.encoding,\n tarfile.errors)\n else :\n value=self._decode_pax_field(value,\"utf-8\",\"utf-8\",\n tarfile.errors)\n \n pax_headers[keyword]=value\n pos +=length\n \n \n try :\n next=self.fromtarfile(tarfile)\n except HeaderError:\n raise SubsequentHeaderError(\"missing or bad subsequent header\")\n \n \n if \"GNU.sparse.map\"in pax_headers:\n \n self._proc_gnusparse_01(next,pax_headers)\n \n elif \"GNU.sparse.size\"in pax_headers:\n \n self._proc_gnusparse_00(next,pax_headers,buf)\n \n elif pax_headers.get(\"GNU.sparse.major\")==\"1\"and pax_headers.get(\"GNU.sparse.minor\")==\"0\":\n \n self._proc_gnusparse_10(next,pax_headers,tarfile)\n \n if self.type in (XHDTYPE,SOLARIS_XHDTYPE):\n \n next._apply_pax_info(pax_headers,tarfile.encoding,tarfile.errors)\n next.offset=self.offset\n \n if \"size\"in pax_headers:\n \n \n \n offset=next.offset_data\n if next.isreg()or next.type not in SUPPORTED_TYPES:\n offset +=next._block(next.size)\n tarfile.offset=offset\n \n return next\n \n def _proc_gnusparse_00(self,next,pax_headers,buf):\n ''\n \n offsets=[]\n for match in re.finditer(br\"\\d+ GNU.sparse.offset=(\\d+)\\n\",buf):\n offsets.append(int(match.group(1)))\n numbytes=[]\n for match in re.finditer(br\"\\d+ GNU.sparse.numbytes=(\\d+)\\n\",buf):\n numbytes.append(int(match.group(1)))\n next.sparse=list(zip(offsets,numbytes))\n \n def _proc_gnusparse_01(self,next,pax_headers):\n ''\n \n sparse=[int(x)for x in pax_headers[\"GNU.sparse.map\"].split(\",\")]\n next.sparse=list(zip(sparse[::2],sparse[1::2]))\n \n def _proc_gnusparse_10(self,next,pax_headers,tarfile):\n ''\n \n fields=None\n sparse=[]\n buf=tarfile.fileobj.read(BLOCKSIZE)\n fields,buf=buf.split(b\"\\n\",1)\n fields=int(fields)\n while len(sparse)<fields *2:\n if b\"\\n\"not in buf:\n buf +=tarfile.fileobj.read(BLOCKSIZE)\n number,buf=buf.split(b\"\\n\",1)\n sparse.append(int(number))\n next.offset_data=tarfile.fileobj.tell()\n next.sparse=list(zip(sparse[::2],sparse[1::2]))\n \n def _apply_pax_info(self,pax_headers,encoding,errors):\n ''\n\n \n for keyword,value in pax_headers.items():\n if keyword ==\"GNU.sparse.name\":\n setattr(self,\"path\",value)\n elif keyword ==\"GNU.sparse.size\":\n setattr(self,\"size\",int(value))\n elif keyword ==\"GNU.sparse.realsize\":\n setattr(self,\"size\",int(value))\n elif keyword in PAX_FIELDS:\n if keyword in PAX_NUMBER_FIELDS:\n try :\n value=PAX_NUMBER_FIELDS[keyword](value)\n except ValueError:\n value=0\n if keyword ==\"path\":\n value=value.rstrip(\"/\")\n setattr(self,keyword,value)\n \n self.pax_headers=pax_headers.copy()\n \n def _decode_pax_field(self,value,encoding,fallback_encoding,fallback_errors):\n ''\n \n try :\n return value.decode(encoding,\"strict\")\n except UnicodeDecodeError:\n return value.decode(fallback_encoding,fallback_errors)\n \n def _block(self,count):\n ''\n\n \n blocks,remainder=divmod(count,BLOCKSIZE)\n if remainder:\n blocks +=1\n return blocks *BLOCKSIZE\n \n def isreg(self):\n return self.type in REGULAR_TYPES\n def isfile(self):\n return self.isreg()\n def isdir(self):\n return self.type ==DIRTYPE\n def issym(self):\n return self.type ==SYMTYPE\n def islnk(self):\n return self.type ==LNKTYPE\n def ischr(self):\n return self.type ==CHRTYPE\n def isblk(self):\n return self.type ==BLKTYPE\n def isfifo(self):\n return self.type ==FIFOTYPE\n def issparse(self):\n return self.sparse is not None\n def isdev(self):\n return self.type in (CHRTYPE,BLKTYPE,FIFOTYPE)\n \n \nclass TarFile(object):\n ''\n \n \n debug=0\n \n dereference=False\n \n \n ignore_zeros=False\n \n \n errorlevel=1\n \n \n \n format=DEFAULT_FORMAT\n \n encoding=ENCODING\n \n errors=None\n \n tarinfo=TarInfo\n \n fileobject=ExFileObject\n \n def __init__(self,name=None ,mode=\"r\",fileobj=None ,format=None ,\n tarinfo=None ,dereference=None ,ignore_zeros=None ,encoding=None ,\n errors=\"surrogateescape\",pax_headers=None ,debug=None ,\n errorlevel=None ,copybufsize=None ):\n ''\n\n\n\n\n\n\n \n modes={\"r\":\"rb\",\"a\":\"r+b\",\"w\":\"wb\",\"x\":\"xb\"}\n if mode not in modes:\n raise ValueError(\"mode must be 'r', 'a', 'w' or 'x'\")\n self.mode=mode\n self._mode=modes[mode]\n \n if not fileobj:\n if self.mode ==\"a\"and not os.path.exists(name):\n \n self.mode=\"w\"\n self._mode=\"wb\"\n fileobj=bltn_open(name,self._mode)\n self._extfileobj=False\n else :\n if (name is None and hasattr(fileobj,\"name\")and\n isinstance(fileobj.name,(str,bytes))):\n name=fileobj.name\n if hasattr(fileobj,\"mode\"):\n self._mode=fileobj.mode\n self._extfileobj=True\n self.name=os.path.abspath(name)if name else None\n self.fileobj=fileobj\n \n \n if format is not None :\n self.format=format\n if tarinfo is not None :\n self.tarinfo=tarinfo\n if dereference is not None :\n self.dereference=dereference\n if ignore_zeros is not None :\n self.ignore_zeros=ignore_zeros\n if encoding is not None :\n self.encoding=encoding\n self.errors=errors\n \n if pax_headers is not None and self.format ==PAX_FORMAT:\n self.pax_headers=pax_headers\n else :\n self.pax_headers={}\n \n if debug is not None :\n self.debug=debug\n if errorlevel is not None :\n self.errorlevel=errorlevel\n \n \n self.copybufsize=copybufsize\n self.closed=False\n self.members=[]\n self._loaded=False\n self.offset=self.fileobj.tell()\n \n self.inodes={}\n \n \n try :\n if self.mode ==\"r\":\n self.firstmember=None\n self.firstmember=self.next()\n \n if self.mode ==\"a\":\n \n \n while True :\n self.fileobj.seek(self.offset)\n try :\n tarinfo=self.tarinfo.fromtarfile(self)\n self.members.append(tarinfo)\n except EOFHeaderError:\n self.fileobj.seek(self.offset)\n break\n except HeaderError as e:\n raise ReadError(str(e))\n \n if self.mode in (\"a\",\"w\",\"x\"):\n self._loaded=True\n \n if self.pax_headers:\n buf=self.tarinfo.create_pax_global_header(self.pax_headers.copy())\n self.fileobj.write(buf)\n self.offset +=len(buf)\n except :\n if not self._extfileobj:\n self.fileobj.close()\n self.closed=True\n raise\n \n \n \n \n \n \n \n \n \n \n \n \n @classmethod\n def open(cls,name=None ,mode=\"r\",fileobj=None ,bufsize=RECORDSIZE,**kwargs):\n ''\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n \n \n if not name and not fileobj:\n raise ValueError(\"nothing to open\")\n \n if mode in (\"r\",\"r:*\"):\n \n def not_compressed(comptype):\n return cls.OPEN_METH[comptype]=='taropen'\n for comptype in sorted(cls.OPEN_METH,key=not_compressed):\n func=getattr(cls,cls.OPEN_METH[comptype])\n if fileobj is not None :\n saved_pos=fileobj.tell()\n try :\n return func(name,\"r\",fileobj,**kwargs)\n except (ReadError,CompressionError):\n if fileobj is not None :\n fileobj.seek(saved_pos)\n continue\n raise ReadError(\"file could not be opened successfully\")\n \n elif \":\"in mode:\n filemode,comptype=mode.split(\":\",1)\n filemode=filemode or \"r\"\n comptype=comptype or \"tar\"\n \n \n \n if comptype in cls.OPEN_METH:\n func=getattr(cls,cls.OPEN_METH[comptype])\n else :\n raise CompressionError(\"unknown compression type %r\"%comptype)\n return func(name,filemode,fileobj,**kwargs)\n \n elif \"|\"in mode:\n filemode,comptype=mode.split(\"|\",1)\n filemode=filemode or \"r\"\n comptype=comptype or \"tar\"\n \n if filemode not in (\"r\",\"w\"):\n raise ValueError(\"mode must be 'r' or 'w'\")\n \n stream=_Stream(name,filemode,comptype,fileobj,bufsize)\n try :\n t=cls(name,filemode,stream,**kwargs)\n except :\n stream.close()\n raise\n t._extfileobj=False\n return t\n \n elif mode in (\"a\",\"w\",\"x\"):\n return cls.taropen(name,mode,fileobj,**kwargs)\n \n raise ValueError(\"undiscernible mode\")\n \n @classmethod\n def taropen(cls,name,mode=\"r\",fileobj=None ,**kwargs):\n ''\n \n if mode not in (\"r\",\"a\",\"w\",\"x\"):\n raise ValueError(\"mode must be 'r', 'a', 'w' or 'x'\")\n return cls(name,mode,fileobj,**kwargs)\n \n @classmethod\n def gzopen(cls,name,mode=\"r\",fileobj=None ,compresslevel=9,**kwargs):\n ''\n\n \n if mode not in (\"r\",\"w\",\"x\"):\n raise ValueError(\"mode must be 'r', 'w' or 'x'\")\n \n try :\n import gzip\n gzip.GzipFile\n except (ImportError,AttributeError):\n raise CompressionError(\"gzip module is not available\")\n \n try :\n fileobj=gzip.GzipFile(name,mode+\"b\",compresslevel,fileobj)\n except OSError:\n if fileobj is not None and mode =='r':\n raise ReadError(\"not a gzip file\")\n raise\n \n try :\n t=cls.taropen(name,mode,fileobj,**kwargs)\n except OSError:\n fileobj.close()\n if mode =='r':\n raise ReadError(\"not a gzip file\")\n raise\n except :\n fileobj.close()\n raise\n t._extfileobj=False\n return t\n \n @classmethod\n def bz2open(cls,name,mode=\"r\",fileobj=None ,compresslevel=9,**kwargs):\n ''\n\n \n if mode not in (\"r\",\"w\",\"x\"):\n raise ValueError(\"mode must be 'r', 'w' or 'x'\")\n \n try :\n import bz2\n except ImportError:\n raise CompressionError(\"bz2 module is not available\")\n \n fileobj=bz2.BZ2File(fileobj or name,mode,\n compresslevel=compresslevel)\n \n try :\n t=cls.taropen(name,mode,fileobj,**kwargs)\n except (OSError,EOFError):\n fileobj.close()\n if mode =='r':\n raise ReadError(\"not a bzip2 file\")\n raise\n except :\n fileobj.close()\n raise\n t._extfileobj=False\n return t\n \n @classmethod\n def xzopen(cls,name,mode=\"r\",fileobj=None ,preset=None ,**kwargs):\n ''\n\n \n if mode not in (\"r\",\"w\",\"x\"):\n raise ValueError(\"mode must be 'r', 'w' or 'x'\")\n \n try :\n import lzma\n except ImportError:\n raise CompressionError(\"lzma module is not available\")\n \n fileobj=lzma.LZMAFile(fileobj or name,mode,preset=preset)\n \n try :\n t=cls.taropen(name,mode,fileobj,**kwargs)\n except (lzma.LZMAError,EOFError):\n fileobj.close()\n if mode =='r':\n raise ReadError(\"not an lzma file\")\n raise\n except :\n fileobj.close()\n raise\n t._extfileobj=False\n return t\n \n \n OPEN_METH={\n \"tar\":\"taropen\",\n \"gz\":\"gzopen\",\n \"bz2\":\"bz2open\",\n \"xz\":\"xzopen\"\n }\n \n \n \n \n def close(self):\n ''\n\n \n if self.closed:\n return\n \n self.closed=True\n try :\n if self.mode in (\"a\",\"w\",\"x\"):\n self.fileobj.write(NUL *(BLOCKSIZE *2))\n self.offset +=(BLOCKSIZE *2)\n \n \n blocks,remainder=divmod(self.offset,RECORDSIZE)\n if remainder >0:\n self.fileobj.write(NUL *(RECORDSIZE -remainder))\n finally :\n if not self._extfileobj:\n self.fileobj.close()\n \n def getmember(self,name):\n ''\n\n\n\n \n tarinfo=self._getmember(name)\n if tarinfo is None :\n raise KeyError(\"filename %r not found\"%name)\n return tarinfo\n \n def getmembers(self):\n ''\n\n \n self._check()\n if not self._loaded:\n self._load()\n \n return self.members\n \n def getnames(self):\n ''\n\n \n return [tarinfo.name for tarinfo in self.getmembers()]\n \n def gettarinfo(self,name=None ,arcname=None ,fileobj=None ):\n ''\n\n\n\n\n\n\n \n self._check(\"awx\")\n \n \n \n if fileobj is not None :\n name=fileobj.name\n \n \n \n \n if arcname is None :\n arcname=name\n drv,arcname=os.path.splitdrive(arcname)\n arcname=arcname.replace(os.sep,\"/\")\n arcname=arcname.lstrip(\"/\")\n \n \n \n tarinfo=self.tarinfo()\n tarinfo.tarfile=self\n \n \n \n if fileobj is None :\n if hasattr(os,\"lstat\")and not self.dereference:\n statres=os.lstat(name)\n else :\n statres=os.stat(name)\n else :\n statres=os.fstat(fileobj.fileno())\n linkname=\"\"\n \n stmd=statres.st_mode\n if stat.S_ISREG(stmd):\n inode=(statres.st_ino,statres.st_dev)\n if not self.dereference and statres.st_nlink >1 and\\\n inode in self.inodes and arcname !=self.inodes[inode]:\n \n \n type=LNKTYPE\n linkname=self.inodes[inode]\n else :\n \n \n type=REGTYPE\n if inode[0]:\n self.inodes[inode]=arcname\n elif stat.S_ISDIR(stmd):\n type=DIRTYPE\n elif stat.S_ISFIFO(stmd):\n type=FIFOTYPE\n elif stat.S_ISLNK(stmd):\n type=SYMTYPE\n linkname=os.readlink(name)\n elif stat.S_ISCHR(stmd):\n type=CHRTYPE\n elif stat.S_ISBLK(stmd):\n type=BLKTYPE\n else :\n return None\n \n \n \n tarinfo.name=arcname\n tarinfo.mode=stmd\n tarinfo.uid=statres.st_uid\n tarinfo.gid=statres.st_gid\n if type ==REGTYPE:\n tarinfo.size=statres.st_size\n else :\n tarinfo.size=0\n tarinfo.mtime=statres.st_mtime\n tarinfo.type=type\n tarinfo.linkname=linkname\n if pwd:\n try :\n tarinfo.uname=pwd.getpwuid(tarinfo.uid)[0]\n except KeyError:\n pass\n if grp:\n try :\n tarinfo.gname=grp.getgrgid(tarinfo.gid)[0]\n except KeyError:\n pass\n \n if type in (CHRTYPE,BLKTYPE):\n if hasattr(os,\"major\")and hasattr(os,\"minor\"):\n tarinfo.devmajor=os.major(statres.st_rdev)\n tarinfo.devminor=os.minor(statres.st_rdev)\n return tarinfo\n \n def list(self,verbose=True ,*,members=None ):\n ''\n\n\n\n \n self._check()\n \n if members is None :\n members=self\n for tarinfo in members:\n if verbose:\n _safe_print(stat.filemode(tarinfo.mode))\n _safe_print(\"%s/%s\"%(tarinfo.uname or tarinfo.uid,\n tarinfo.gname or tarinfo.gid))\n if tarinfo.ischr()or tarinfo.isblk():\n _safe_print(\"%10s\"%\n (\"%d,%d\"%(tarinfo.devmajor,tarinfo.devminor)))\n else :\n _safe_print(\"%10d\"%tarinfo.size)\n _safe_print(\"%d-%02d-%02d %02d:%02d:%02d\"\\\n %time.localtime(tarinfo.mtime)[:6])\n \n _safe_print(tarinfo.name+(\"/\"if tarinfo.isdir()else \"\"))\n \n if verbose:\n if tarinfo.issym():\n _safe_print(\"-> \"+tarinfo.linkname)\n if tarinfo.islnk():\n _safe_print(\"link to \"+tarinfo.linkname)\n print()\n \n def add(self,name,arcname=None ,recursive=True ,*,filter=None ):\n ''\n\n\n\n\n\n\n\n \n self._check(\"awx\")\n \n if arcname is None :\n arcname=name\n \n \n if self.name is not None and os.path.abspath(name)==self.name:\n self._dbg(2,\"tarfile: Skipped %r\"%name)\n return\n \n self._dbg(1,name)\n \n \n tarinfo=self.gettarinfo(name,arcname)\n \n if tarinfo is None :\n self._dbg(1,\"tarfile: Unsupported type %r\"%name)\n return\n \n \n if filter is not None :\n tarinfo=filter(tarinfo)\n if tarinfo is None :\n self._dbg(2,\"tarfile: Excluded %r\"%name)\n return\n \n \n if tarinfo.isreg():\n with bltn_open(name,\"rb\")as f:\n self.addfile(tarinfo,f)\n \n elif tarinfo.isdir():\n self.addfile(tarinfo)\n if recursive:\n for f in sorted(os.listdir(name)):\n self.add(os.path.join(name,f),os.path.join(arcname,f),\n recursive,filter=filter)\n \n else :\n self.addfile(tarinfo)\n \n def addfile(self,tarinfo,fileobj=None ):\n ''\n\n\n\n \n self._check(\"awx\")\n \n tarinfo=copy.copy(tarinfo)\n \n buf=tarinfo.tobuf(self.format,self.encoding,self.errors)\n self.fileobj.write(buf)\n self.offset +=len(buf)\n bufsize=self.copybufsize\n \n if fileobj is not None :\n copyfileobj(fileobj,self.fileobj,tarinfo.size,bufsize=bufsize)\n blocks,remainder=divmod(tarinfo.size,BLOCKSIZE)\n if remainder >0:\n self.fileobj.write(NUL *(BLOCKSIZE -remainder))\n blocks +=1\n self.offset +=blocks *BLOCKSIZE\n \n self.members.append(tarinfo)\n \n def extractall(self,path=\".\",members=None ,*,numeric_owner=False ):\n ''\n\n\n\n\n\n \n directories=[]\n \n if members is None :\n members=self\n \n for tarinfo in members:\n if tarinfo.isdir():\n \n directories.append(tarinfo)\n tarinfo=copy.copy(tarinfo)\n tarinfo.mode=0o700\n \n self.extract(tarinfo,path,set_attrs=not tarinfo.isdir(),\n numeric_owner=numeric_owner)\n \n \n directories.sort(key=lambda a:a.name)\n directories.reverse()\n \n \n for tarinfo in directories:\n dirpath=os.path.join(path,tarinfo.name)\n try :\n self.chown(tarinfo,dirpath,numeric_owner=numeric_owner)\n self.utime(tarinfo,dirpath)\n self.chmod(tarinfo,dirpath)\n except ExtractError as e:\n if self.errorlevel >1:\n raise\n else :\n self._dbg(1,\"tarfile: %s\"%e)\n \n def extract(self,member,path=\"\",set_attrs=True ,*,numeric_owner=False ):\n ''\n\n\n\n\n\n\n \n self._check(\"r\")\n \n if isinstance(member,str):\n tarinfo=self.getmember(member)\n else :\n tarinfo=member\n \n \n if tarinfo.islnk():\n tarinfo._link_target=os.path.join(path,tarinfo.linkname)\n \n try :\n self._extract_member(tarinfo,os.path.join(path,tarinfo.name),\n set_attrs=set_attrs,\n numeric_owner=numeric_owner)\n except OSError as e:\n if self.errorlevel >0:\n raise\n else :\n if e.filename is None :\n self._dbg(1,\"tarfile: %s\"%e.strerror)\n else :\n self._dbg(1,\"tarfile: %s %r\"%(e.strerror,e.filename))\n except ExtractError as e:\n if self.errorlevel >1:\n raise\n else :\n self._dbg(1,\"tarfile: %s\"%e)\n \n def extractfile(self,member):\n ''\n\n\n\n \n self._check(\"r\")\n \n if isinstance(member,str):\n tarinfo=self.getmember(member)\n else :\n tarinfo=member\n \n if tarinfo.isreg()or tarinfo.type not in SUPPORTED_TYPES:\n \n return self.fileobject(self,tarinfo)\n \n elif tarinfo.islnk()or tarinfo.issym():\n if isinstance(self.fileobj,_Stream):\n \n \n \n raise StreamError(\"cannot extract (sym)link as file object\")\n else :\n \n return self.extractfile(self._find_link_target(tarinfo))\n else :\n \n \n return None\n \n def _extract_member(self,tarinfo,targetpath,set_attrs=True ,\n numeric_owner=False ):\n ''\n\n \n \n \n \n targetpath=targetpath.rstrip(\"/\")\n targetpath=targetpath.replace(\"/\",os.sep)\n \n \n upperdirs=os.path.dirname(targetpath)\n if upperdirs and not os.path.exists(upperdirs):\n \n \n os.makedirs(upperdirs)\n \n if tarinfo.islnk()or tarinfo.issym():\n self._dbg(1,\"%s -> %s\"%(tarinfo.name,tarinfo.linkname))\n else :\n self._dbg(1,tarinfo.name)\n \n if tarinfo.isreg():\n self.makefile(tarinfo,targetpath)\n elif tarinfo.isdir():\n self.makedir(tarinfo,targetpath)\n elif tarinfo.isfifo():\n self.makefifo(tarinfo,targetpath)\n elif tarinfo.ischr()or tarinfo.isblk():\n self.makedev(tarinfo,targetpath)\n elif tarinfo.islnk()or tarinfo.issym():\n self.makelink(tarinfo,targetpath)\n elif tarinfo.type not in SUPPORTED_TYPES:\n self.makeunknown(tarinfo,targetpath)\n else :\n self.makefile(tarinfo,targetpath)\n \n if set_attrs:\n self.chown(tarinfo,targetpath,numeric_owner)\n if not tarinfo.issym():\n self.chmod(tarinfo,targetpath)\n self.utime(tarinfo,targetpath)\n \n \n \n \n \n \n def makedir(self,tarinfo,targetpath):\n ''\n \n try :\n \n \n os.mkdir(targetpath,0o700)\n except FileExistsError:\n pass\n \n def makefile(self,tarinfo,targetpath):\n ''\n \n source=self.fileobj\n source.seek(tarinfo.offset_data)\n bufsize=self.copybufsize\n with bltn_open(targetpath,\"wb\")as target:\n if tarinfo.sparse is not None :\n for offset,size in tarinfo.sparse:\n target.seek(offset)\n copyfileobj(source,target,size,ReadError,bufsize)\n target.seek(tarinfo.size)\n target.truncate()\n else :\n copyfileobj(source,target,tarinfo.size,ReadError,bufsize)\n \n def makeunknown(self,tarinfo,targetpath):\n ''\n\n \n self.makefile(tarinfo,targetpath)\n self._dbg(1,\"tarfile: Unknown file type %r, \"\\\n \"extracted as regular file.\"%tarinfo.type)\n \n def makefifo(self,tarinfo,targetpath):\n ''\n \n if hasattr(os,\"mkfifo\"):\n os.mkfifo(targetpath)\n else :\n raise ExtractError(\"fifo not supported by system\")\n \n def makedev(self,tarinfo,targetpath):\n ''\n \n if not hasattr(os,\"mknod\")or not hasattr(os,\"makedev\"):\n raise ExtractError(\"special devices not supported by system\")\n \n mode=tarinfo.mode\n if tarinfo.isblk():\n mode |=stat.S_IFBLK\n else :\n mode |=stat.S_IFCHR\n \n os.mknod(targetpath,mode,\n os.makedev(tarinfo.devmajor,tarinfo.devminor))\n \n def makelink(self,tarinfo,targetpath):\n ''\n\n\n \n try :\n \n if tarinfo.issym():\n os.symlink(tarinfo.linkname,targetpath)\n else :\n \n if os.path.exists(tarinfo._link_target):\n os.link(tarinfo._link_target,targetpath)\n else :\n self._extract_member(self._find_link_target(tarinfo),\n targetpath)\n except symlink_exception:\n try :\n self._extract_member(self._find_link_target(tarinfo),\n targetpath)\n except KeyError:\n raise ExtractError(\"unable to resolve link inside archive\")\n \n def chown(self,tarinfo,targetpath,numeric_owner):\n ''\n\n\n\n \n if hasattr(os,\"geteuid\")and os.geteuid()==0:\n \n g=tarinfo.gid\n u=tarinfo.uid\n if not numeric_owner:\n try :\n if grp:\n g=grp.getgrnam(tarinfo.gname)[2]\n except KeyError:\n pass\n try :\n if pwd:\n u=pwd.getpwnam(tarinfo.uname)[2]\n except KeyError:\n pass\n try :\n if tarinfo.issym()and hasattr(os,\"lchown\"):\n os.lchown(targetpath,u,g)\n else :\n os.chown(targetpath,u,g)\n except OSError:\n raise ExtractError(\"could not change owner\")\n \n def chmod(self,tarinfo,targetpath):\n ''\n \n if hasattr(os,'chmod'):\n try :\n os.chmod(targetpath,tarinfo.mode)\n except OSError:\n raise ExtractError(\"could not change mode\")\n \n def utime(self,tarinfo,targetpath):\n ''\n \n if not hasattr(os,'utime'):\n return\n try :\n os.utime(targetpath,(tarinfo.mtime,tarinfo.mtime))\n except OSError:\n raise ExtractError(\"could not change modification time\")\n \n \n def next(self):\n ''\n\n\n \n self._check(\"ra\")\n if self.firstmember is not None :\n m=self.firstmember\n self.firstmember=None\n return m\n \n \n if self.offset !=self.fileobj.tell():\n self.fileobj.seek(self.offset -1)\n if not self.fileobj.read(1):\n raise ReadError(\"unexpected end of data\")\n \n \n tarinfo=None\n while True :\n try :\n tarinfo=self.tarinfo.fromtarfile(self)\n except EOFHeaderError as e:\n if self.ignore_zeros:\n self._dbg(2,\"0x%X: %s\"%(self.offset,e))\n self.offset +=BLOCKSIZE\n continue\n except InvalidHeaderError as e:\n if self.ignore_zeros:\n self._dbg(2,\"0x%X: %s\"%(self.offset,e))\n self.offset +=BLOCKSIZE\n continue\n elif self.offset ==0:\n raise ReadError(str(e))\n except EmptyHeaderError:\n if self.offset ==0:\n raise ReadError(\"empty file\")\n except TruncatedHeaderError as e:\n if self.offset ==0:\n raise ReadError(str(e))\n except SubsequentHeaderError as e:\n raise ReadError(str(e))\n break\n \n if tarinfo is not None :\n self.members.append(tarinfo)\n else :\n self._loaded=True\n \n return tarinfo\n \n \n \n \n def _getmember(self,name,tarinfo=None ,normalize=False ):\n ''\n\n \n \n members=self.getmembers()\n \n \n if tarinfo is not None :\n members=members[:members.index(tarinfo)]\n \n if normalize:\n name=os.path.normpath(name)\n \n for member in reversed(members):\n if normalize:\n member_name=os.path.normpath(member.name)\n else :\n member_name=member.name\n \n if name ==member_name:\n return member\n \n def _load(self):\n ''\n\n \n while True :\n tarinfo=self.next()\n if tarinfo is None :\n break\n self._loaded=True\n \n def _check(self,mode=None ):\n ''\n\n \n if self.closed:\n raise OSError(\"%s is closed\"%self.__class__.__name__)\n if mode is not None and self.mode not in mode:\n raise OSError(\"bad operation for mode %r\"%self.mode)\n \n def _find_link_target(self,tarinfo):\n ''\n\n \n if tarinfo.issym():\n \n linkname=\"/\".join(filter(None ,(os.path.dirname(tarinfo.name),tarinfo.linkname)))\n limit=None\n else :\n \n \n linkname=tarinfo.linkname\n limit=tarinfo\n \n member=self._getmember(linkname,tarinfo=limit,normalize=True )\n if member is None :\n raise KeyError(\"linkname %r not found\"%linkname)\n return member\n \n def __iter__(self):\n ''\n \n if self._loaded:\n yield from self.members\n return\n \n \n \n index=0\n \n \n \n if self.firstmember is not None :\n tarinfo=self.next()\n index +=1\n yield tarinfo\n \n while True :\n if index <len(self.members):\n tarinfo=self.members[index]\n elif not self._loaded:\n tarinfo=self.next()\n if not tarinfo:\n self._loaded=True\n return\n else :\n return\n index +=1\n yield tarinfo\n \n def _dbg(self,level,msg):\n ''\n \n if level <=self.debug:\n print(msg,file=sys.stderr)\n \n def __enter__(self):\n self._check()\n return self\n \n def __exit__(self,type,value,traceback):\n if type is None :\n self.close()\n else :\n \n \n if not self._extfileobj:\n self.fileobj.close()\n self.closed=True\n \n \n \n \ndef is_tarfile(name):\n ''\n\n \n try :\n t=open(name)\n t.close()\n return True\n except TarError:\n return False\n \nopen=TarFile.open\n\n\ndef main():\n import argparse\n \n description='A simple command-line interface for tarfile module.'\n parser=argparse.ArgumentParser(description=description)\n parser.add_argument('-v','--verbose',action='store_true',default=False ,\n help='Verbose output')\n group=parser.add_mutually_exclusive_group(required=True )\n group.add_argument('-l','--list',metavar='<tarfile>',\n help='Show listing of a tarfile')\n group.add_argument('-e','--extract',nargs='+',\n metavar=('<tarfile>','<output_dir>'),\n help='Extract tarfile into target dir')\n group.add_argument('-c','--create',nargs='+',\n metavar=('<name>','<file>'),\n help='Create tarfile from sources')\n group.add_argument('-t','--test',metavar='<tarfile>',\n help='Test if a tarfile is valid')\n args=parser.parse_args()\n \n if args.test is not None :\n src=args.test\n if is_tarfile(src):\n with open(src,'r')as tar:\n tar.getmembers()\n print(tar.getmembers(),file=sys.stderr)\n if args.verbose:\n print('{!r} is a tar archive.'.format(src))\n else :\n parser.exit(1,'{!r} is not a tar archive.\\n'.format(src))\n \n elif args.list is not None :\n src=args.list\n if is_tarfile(src):\n with TarFile.open(src,'r:*')as tf:\n tf.list(verbose=args.verbose)\n else :\n parser.exit(1,'{!r} is not a tar archive.\\n'.format(src))\n \n elif args.extract is not None :\n if len(args.extract)==1:\n src=args.extract[0]\n curdir=os.curdir\n elif len(args.extract)==2:\n src,curdir=args.extract\n else :\n parser.exit(1,parser.format_help())\n \n if is_tarfile(src):\n with TarFile.open(src,'r:*')as tf:\n tf.extractall(path=curdir)\n if args.verbose:\n if curdir =='.':\n msg='{!r} file is extracted.'.format(src)\n else :\n msg=('{!r} file is extracted '\n 'into {!r} directory.').format(src,curdir)\n print(msg)\n else :\n parser.exit(1,'{!r} is not a tar archive.\\n'.format(src))\n \n elif args.create is not None :\n tar_name=args.create.pop(0)\n _,ext=os.path.splitext(tar_name)\n compressions={\n \n '.gz':'gz',\n '.tgz':'gz',\n \n '.xz':'xz',\n '.txz':'xz',\n \n '.bz2':'bz2',\n '.tbz':'bz2',\n '.tbz2':'bz2',\n '.tb2':'bz2',\n }\n tar_mode='w:'+compressions[ext]if ext in compressions else 'w'\n tar_files=args.create\n \n with TarFile.open(tar_name,tar_mode)as tf:\n for file_name in tar_files:\n tf.add(file_name)\n \n if args.verbose:\n print('{!r} file created.'.format(tar_name))\n \nif __name__ =='__main__':\n main()\n", ["argparse", "builtins", "bz2", "copy", "grp", "gzip", "io", "lzma", "os", "pwd", "re", "shutil", "stat", "struct", "sys", "time", "warnings", "zlib"]], "dis": [".js", "var $module=(function($B){\n\nvar dict = $B.builtins.dict\nvar mod = {\n dis:function(src){\n $B.$py_module_path['__main__'] = $B.brython_path\n return __BRYTHON__.py2js(src,'__main__','__main__',\n $B.builtins_scope).to_js()\n },\n OPTIMIZED: 1,\n NEWLOCALS: 2,\n VARARGS: 4,\n VARKEYWORDS: 8,\n NESTED: 16,\n GENERATOR: 32,\n NOFREE: 64,\n COROUTINE: 128,\n ITERABLE_COROUTINE: 256,\n ASYNC_GENERATOR: 512,\n COMPILER_FLAG_NAMES: $B.builtins.dict.$factory()\n}\nmod.COMPILER_FLAG_NAMES = dict.$factory([\n [1, \"OPTIMIZED\"],\n [2, \"NEWLOCALS\"],\n [4, \"VARARGS\"],\n [8, \"VARKEYWORDS\"],\n [16, \"NESTED\"],\n [32, \"GENERATOR\"],\n [64, \"NOFREE\"],\n [128, \"COROUTINE\"],\n [256, \"ITERABLE_COROUTINE\"],\n [512, \"ASYNC_GENERATOR\"]\n])\n\nreturn mod\n\n})(__BRYTHON__)"], "_imp": [".py", "''\nimport sys\n\ndef _fix_co_filename(*args,**kw):\n ''\n\n\n\n \n pass\n \ndef acquire_lock(*args,**kw):\n ''\n\n \n pass\n \ncheck_hash_based_pycs=\"\"\"default\"\"\"\n\ndef create_builtin(spec):\n ''\n __import__(spec.name)\n \ndef create_dynamic(*args,**kw):\n ''\n pass\n \ndef exec_builtin(*args,**kw):\n ''\n pass\n \ndef exec_dynamic(*args,**kw):\n ''\n pass\n \ndef extension_suffixes(*args,**kw):\n ''\n return []\n \ndef get_frozen_object(*args,**kw):\n ''\n pass\n \ndef init_frozen(*args,**kw):\n ''\n pass\n \ndef is_builtin(module_name):\n\n return module_name in __BRYTHON__.builtin_module_names\n \ndef is_frozen(*args,**kw):\n ''\n return False\n \ndef is_frozen_package(*args,**kw):\n ''\n pass\n \ndef lock_held(*args,**kw):\n ''\n \n return False\n \ndef release_lock(*args,**kw):\n ''\n \n pass\n \ndef source_hash(*args,**kw):\n pass\n", ["sys"]], "argparse": [".py", "\n\n\"\"\"Command-line parsing library\n\nThis module is an optparse-inspired command-line parsing library that:\n\n - handles both optional and positional arguments\n - produces highly informative usage messages\n - supports parsers that dispatch to sub-parsers\n\nThe following is a simple usage example that sums integers from the\ncommand-line and writes the result to a file::\n\n parser = argparse.ArgumentParser(\n description='sum the integers at the command line')\n parser.add_argument(\n 'integers', metavar='int', nargs='+', type=int,\n help='an integer to be summed')\n parser.add_argument(\n '--log', default=sys.stdout, type=argparse.FileType('w'),\n help='the file where the sum should be written')\n args = parser.parse_args()\n args.log.write('%s' % sum(args.integers))\n args.log.close()\n\nThe module contains the following public classes:\n\n - ArgumentParser -- The main entry point for command-line parsing. As the\n example above shows, the add_argument() method is used to populate\n the parser with actions for optional and positional arguments. Then\n the parse_args() method is invoked to convert the args at the\n command-line into an object with attributes.\n\n - ArgumentError -- The exception raised by ArgumentParser objects when\n there are errors with the parser's actions. Errors raised while\n parsing the command-line are caught by ArgumentParser and emitted\n as command-line messages.\n\n - FileType -- A factory for defining types of files to be created. As the\n example above shows, instances of FileType are typically passed as\n the type= argument of add_argument() calls.\n\n - Action -- The base class for parser actions. Typically actions are\n selected by passing strings like 'store_true' or 'append_const' to\n the action= argument of add_argument(). However, for greater\n customization of ArgumentParser actions, subclasses of Action may\n be defined and passed as the action= argument.\n\n - HelpFormatter, RawDescriptionHelpFormatter, RawTextHelpFormatter,\n ArgumentDefaultsHelpFormatter -- Formatter classes which\n may be passed as the formatter_class= argument to the\n ArgumentParser constructor. HelpFormatter is the default,\n RawDescriptionHelpFormatter and RawTextHelpFormatter tell the parser\n not to change the formatting for help text, and\n ArgumentDefaultsHelpFormatter adds information about argument defaults\n to the help.\n\nAll other classes in this module are considered implementation details.\n(Also note that HelpFormatter and RawDescriptionHelpFormatter are only\nconsidered public as object names -- the API of the formatter objects is\nstill considered an implementation detail.)\n\"\"\"\n\n__version__='1.1'\n__all__=[\n'ArgumentParser',\n'ArgumentError',\n'ArgumentTypeError',\n'FileType',\n'HelpFormatter',\n'ArgumentDefaultsHelpFormatter',\n'RawDescriptionHelpFormatter',\n'RawTextHelpFormatter',\n'MetavarTypeHelpFormatter',\n'Namespace',\n'Action',\n'ONE_OR_MORE',\n'OPTIONAL',\n'PARSER',\n'REMAINDER',\n'SUPPRESS',\n'ZERO_OR_MORE',\n]\n\n\nimport os as _os\nimport re as _re\nimport sys as _sys\n\nfrom gettext import gettext as _,ngettext\n\nSUPPRESS='==SUPPRESS=='\n\nOPTIONAL='?'\nZERO_OR_MORE='*'\nONE_OR_MORE='+'\nPARSER='A...'\nREMAINDER='...'\n_UNRECOGNIZED_ARGS_ATTR='_unrecognized_args'\n\n\n\n\n\nclass _AttributeHolder(object):\n ''\n\n\n\n\n\n \n \n def __repr__(self):\n type_name=type(self).__name__\n arg_strings=[]\n star_args={}\n for arg in self._get_args():\n arg_strings.append(repr(arg))\n for name,value in self._get_kwargs():\n if name.isidentifier():\n arg_strings.append('%s=%r'%(name,value))\n else :\n star_args[name]=value\n if star_args:\n arg_strings.append('**%s'%repr(star_args))\n return '%s(%s)'%(type_name,', '.join(arg_strings))\n \n def _get_kwargs(self):\n return sorted(self.__dict__.items())\n \n def _get_args(self):\n return []\n \n \ndef _copy_items(items):\n if items is None :\n return []\n \n \n \n if type(items)is list:\n return items[:]\n import copy\n return copy.copy(items)\n \n \n \n \n \n \nclass HelpFormatter(object):\n ''\n\n\n\n \n \n def __init__(self,\n prog,\n indent_increment=2,\n max_help_position=24,\n width=None ):\n \n \n if width is None :\n try :\n width=int(_os.environ['COLUMNS'])\n except (KeyError,ValueError):\n width=80\n width -=2\n \n self._prog=prog\n self._indent_increment=indent_increment\n self._max_help_position=max_help_position\n self._max_help_position=min(max_help_position,\n max(width -20,indent_increment *2))\n self._width=width\n \n self._current_indent=0\n self._level=0\n self._action_max_length=0\n \n self._root_section=self._Section(self,None )\n self._current_section=self._root_section\n \n self._whitespace_matcher=_re.compile(r'\\s+',_re.ASCII)\n self._long_break_matcher=_re.compile(r'\\n\\n\\n+')\n \n \n \n \n def _indent(self):\n self._current_indent +=self._indent_increment\n self._level +=1\n \n def _dedent(self):\n self._current_indent -=self._indent_increment\n assert self._current_indent >=0,'Indent decreased below 0.'\n self._level -=1\n \n class _Section(object):\n \n def __init__(self,formatter,parent,heading=None ):\n self.formatter=formatter\n self.parent=parent\n self.heading=heading\n self.items=[]\n \n def format_help(self):\n \n if self.parent is not None :\n self.formatter._indent()\n join=self.formatter._join_parts\n item_help=join([func(*args)for func,args in self.items])\n if self.parent is not None :\n self.formatter._dedent()\n \n \n if not item_help:\n return ''\n \n \n if self.heading is not SUPPRESS and self.heading is not None :\n current_indent=self.formatter._current_indent\n heading='%*s%s:\\n'%(current_indent,'',self.heading)\n else :\n heading=''\n \n \n return join(['\\n',heading,item_help,'\\n'])\n \n def _add_item(self,func,args):\n self._current_section.items.append((func,args))\n \n \n \n \n def start_section(self,heading):\n self._indent()\n section=self._Section(self,self._current_section,heading)\n self._add_item(section.format_help,[])\n self._current_section=section\n \n def end_section(self):\n self._current_section=self._current_section.parent\n self._dedent()\n \n def add_text(self,text):\n if text is not SUPPRESS and text is not None :\n self._add_item(self._format_text,[text])\n \n def add_usage(self,usage,actions,groups,prefix=None ):\n if usage is not SUPPRESS:\n args=usage,actions,groups,prefix\n self._add_item(self._format_usage,args)\n \n def add_argument(self,action):\n if action.help is not SUPPRESS:\n \n \n get_invocation=self._format_action_invocation\n invocations=[get_invocation(action)]\n for subaction in self._iter_indented_subactions(action):\n invocations.append(get_invocation(subaction))\n \n \n invocation_length=max([len(s)for s in invocations])\n action_length=invocation_length+self._current_indent\n self._action_max_length=max(self._action_max_length,\n action_length)\n \n \n self._add_item(self._format_action,[action])\n \n def add_arguments(self,actions):\n for action in actions:\n self.add_argument(action)\n \n \n \n \n def format_help(self):\n help=self._root_section.format_help()\n if help:\n help=self._long_break_matcher.sub('\\n\\n',help)\n help=help.strip('\\n')+'\\n'\n return help\n \n def _join_parts(self,part_strings):\n return ''.join([part\n for part in part_strings\n if part and part is not SUPPRESS])\n \n def _format_usage(self,usage,actions,groups,prefix):\n if prefix is None :\n prefix=_('usage: ')\n \n \n if usage is not None :\n usage=usage %dict(prog=self._prog)\n \n \n elif usage is None and not actions:\n usage='%(prog)s'%dict(prog=self._prog)\n \n \n elif usage is None :\n prog='%(prog)s'%dict(prog=self._prog)\n \n \n optionals=[]\n positionals=[]\n for action in actions:\n if action.option_strings:\n optionals.append(action)\n else :\n positionals.append(action)\n \n \n format=self._format_actions_usage\n action_usage=format(optionals+positionals,groups)\n usage=' '.join([s for s in [prog,action_usage]if s])\n \n \n text_width=self._width -self._current_indent\n if len(prefix)+len(usage)>text_width:\n \n \n part_regexp=(\n r'\\(.*?\\)+(?=\\s|$)|'\n r'\\[.*?\\]+(?=\\s|$)|'\n r'\\S+'\n )\n opt_usage=format(optionals,groups)\n pos_usage=format(positionals,groups)\n opt_parts=_re.findall(part_regexp,opt_usage)\n pos_parts=_re.findall(part_regexp,pos_usage)\n assert ' '.join(opt_parts)==opt_usage\n assert ' '.join(pos_parts)==pos_usage\n \n \n def get_lines(parts,indent,prefix=None ):\n lines=[]\n line=[]\n if prefix is not None :\n line_len=len(prefix)-1\n else :\n line_len=len(indent)-1\n for part in parts:\n if line_len+1+len(part)>text_width and line:\n lines.append(indent+' '.join(line))\n line=[]\n line_len=len(indent)-1\n line.append(part)\n line_len +=len(part)+1\n if line:\n lines.append(indent+' '.join(line))\n if prefix is not None :\n lines[0]=lines[0][len(indent):]\n return lines\n \n \n if len(prefix)+len(prog)<=0.75 *text_width:\n indent=' '*(len(prefix)+len(prog)+1)\n if opt_parts:\n lines=get_lines([prog]+opt_parts,indent,prefix)\n lines.extend(get_lines(pos_parts,indent))\n elif pos_parts:\n lines=get_lines([prog]+pos_parts,indent,prefix)\n else :\n lines=[prog]\n \n \n else :\n indent=' '*len(prefix)\n parts=opt_parts+pos_parts\n lines=get_lines(parts,indent)\n if len(lines)>1:\n lines=[]\n lines.extend(get_lines(opt_parts,indent))\n lines.extend(get_lines(pos_parts,indent))\n lines=[prog]+lines\n \n \n usage='\\n'.join(lines)\n \n \n return '%s%s\\n\\n'%(prefix,usage)\n \n def _format_actions_usage(self,actions,groups):\n \n group_actions=set()\n inserts={}\n for group in groups:\n try :\n start=actions.index(group._group_actions[0])\n except ValueError:\n continue\n else :\n end=start+len(group._group_actions)\n if actions[start:end]==group._group_actions:\n for action in group._group_actions:\n group_actions.add(action)\n if not group.required:\n if start in inserts:\n inserts[start]+=' ['\n else :\n inserts[start]='['\n inserts[end]=']'\n else :\n if start in inserts:\n inserts[start]+=' ('\n else :\n inserts[start]='('\n inserts[end]=')'\n for i in range(start+1,end):\n inserts[i]='|'\n \n \n parts=[]\n for i,action in enumerate(actions):\n \n \n \n if action.help is SUPPRESS:\n parts.append(None )\n if inserts.get(i)=='|':\n inserts.pop(i)\n elif inserts.get(i+1)=='|':\n inserts.pop(i+1)\n \n \n elif not action.option_strings:\n default=self._get_default_metavar_for_positional(action)\n part=self._format_args(action,default)\n \n \n if action in group_actions:\n if part[0]=='['and part[-1]==']':\n part=part[1:-1]\n \n \n parts.append(part)\n \n \n else :\n option_string=action.option_strings[0]\n \n \n \n if action.nargs ==0:\n part='%s'%option_string\n \n \n \n else :\n default=self._get_default_metavar_for_optional(action)\n args_string=self._format_args(action,default)\n part='%s %s'%(option_string,args_string)\n \n \n if not action.required and action not in group_actions:\n part='[%s]'%part\n \n \n parts.append(part)\n \n \n for i in sorted(inserts,reverse=True ):\n parts[i:i]=[inserts[i]]\n \n \n text=' '.join([item for item in parts if item is not None ])\n \n \n open=r'[\\[(]'\n close=r'[\\])]'\n text=_re.sub(r'(%s) '%open,r'\\1',text)\n text=_re.sub(r' (%s)'%close,r'\\1',text)\n text=_re.sub(r'%s *%s'%(open,close),r'',text)\n text=_re.sub(r'\\(([^|]*)\\)',r'\\1',text)\n text=text.strip()\n \n \n return text\n \n def _format_text(self,text):\n if '%(prog)'in text:\n text=text %dict(prog=self._prog)\n text_width=max(self._width -self._current_indent,11)\n indent=' '*self._current_indent\n return self._fill_text(text,text_width,indent)+'\\n\\n'\n \n def _format_action(self,action):\n \n help_position=min(self._action_max_length+2,\n self._max_help_position)\n help_width=max(self._width -help_position,11)\n action_width=help_position -self._current_indent -2\n action_header=self._format_action_invocation(action)\n \n \n if not action.help:\n tup=self._current_indent,'',action_header\n action_header='%*s%s\\n'%tup\n \n \n elif len(action_header)<=action_width:\n tup=self._current_indent,'',action_width,action_header\n action_header='%*s%-*s '%tup\n indent_first=0\n \n \n else :\n tup=self._current_indent,'',action_header\n action_header='%*s%s\\n'%tup\n indent_first=help_position\n \n \n parts=[action_header]\n \n \n if action.help:\n help_text=self._expand_help(action)\n help_lines=self._split_lines(help_text,help_width)\n parts.append('%*s%s\\n'%(indent_first,'',help_lines[0]))\n for line in help_lines[1:]:\n parts.append('%*s%s\\n'%(help_position,'',line))\n \n \n elif not action_header.endswith('\\n'):\n parts.append('\\n')\n \n \n for subaction in self._iter_indented_subactions(action):\n parts.append(self._format_action(subaction))\n \n \n return self._join_parts(parts)\n \n def _format_action_invocation(self,action):\n if not action.option_strings:\n default=self._get_default_metavar_for_positional(action)\n metavar,=self._metavar_formatter(action,default)(1)\n return metavar\n \n else :\n parts=[]\n \n \n \n if action.nargs ==0:\n parts.extend(action.option_strings)\n \n \n \n else :\n default=self._get_default_metavar_for_optional(action)\n args_string=self._format_args(action,default)\n for option_string in action.option_strings:\n parts.append('%s %s'%(option_string,args_string))\n \n return ', '.join(parts)\n \n def _metavar_formatter(self,action,default_metavar):\n if action.metavar is not None :\n result=action.metavar\n elif action.choices is not None :\n choice_strs=[str(choice)for choice in action.choices]\n result='{%s}'%','.join(choice_strs)\n else :\n result=default_metavar\n \n def format(tuple_size):\n if isinstance(result,tuple):\n return result\n else :\n return (result,)*tuple_size\n return format\n \n def _format_args(self,action,default_metavar):\n get_metavar=self._metavar_formatter(action,default_metavar)\n if action.nargs is None :\n result='%s'%get_metavar(1)\n elif action.nargs ==OPTIONAL:\n result='[%s]'%get_metavar(1)\n elif action.nargs ==ZERO_OR_MORE:\n result='[%s [%s ...]]'%get_metavar(2)\n elif action.nargs ==ONE_OR_MORE:\n result='%s [%s ...]'%get_metavar(2)\n elif action.nargs ==REMAINDER:\n result='...'\n elif action.nargs ==PARSER:\n result='%s ...'%get_metavar(1)\n elif action.nargs ==SUPPRESS:\n result=''\n else :\n formats=['%s'for _ in range(action.nargs)]\n result=' '.join(formats)%get_metavar(action.nargs)\n return result\n \n def _expand_help(self,action):\n params=dict(vars(action),prog=self._prog)\n for name in list(params):\n if params[name]is SUPPRESS:\n del params[name]\n for name in list(params):\n if hasattr(params[name],'__name__'):\n params[name]=params[name].__name__\n if params.get('choices')is not None :\n choices_str=', '.join([str(c)for c in params['choices']])\n params['choices']=choices_str\n return self._get_help_string(action)%params\n \n def _iter_indented_subactions(self,action):\n try :\n get_subactions=action._get_subactions\n except AttributeError:\n pass\n else :\n self._indent()\n yield from get_subactions()\n self._dedent()\n \n def _split_lines(self,text,width):\n text=self._whitespace_matcher.sub(' ',text).strip()\n \n \n import textwrap\n return textwrap.wrap(text,width)\n \n def _fill_text(self,text,width,indent):\n text=self._whitespace_matcher.sub(' ',text).strip()\n import textwrap\n return textwrap.fill(text,width,\n initial_indent=indent,\n subsequent_indent=indent)\n \n def _get_help_string(self,action):\n return action.help\n \n def _get_default_metavar_for_optional(self,action):\n return action.dest.upper()\n \n def _get_default_metavar_for_positional(self,action):\n return action.dest\n \n \nclass RawDescriptionHelpFormatter(HelpFormatter):\n ''\n\n\n\n \n \n def _fill_text(self,text,width,indent):\n return ''.join(indent+line for line in text.splitlines(keepends=True ))\n \n \nclass RawTextHelpFormatter(RawDescriptionHelpFormatter):\n ''\n\n\n\n \n \n def _split_lines(self,text,width):\n return text.splitlines()\n \n \nclass ArgumentDefaultsHelpFormatter(HelpFormatter):\n ''\n\n\n\n \n \n def _get_help_string(self,action):\n help=action.help\n if '%(default)'not in action.help:\n if action.default is not SUPPRESS:\n defaulting_nargs=[OPTIONAL,ZERO_OR_MORE]\n if action.option_strings or action.nargs in defaulting_nargs:\n help +=' (default: %(default)s)'\n return help\n \n \nclass MetavarTypeHelpFormatter(HelpFormatter):\n ''\n\n\n\n\n \n \n def _get_default_metavar_for_optional(self,action):\n return action.type.__name__\n \n def _get_default_metavar_for_positional(self,action):\n return action.type.__name__\n \n \n \n \n \n \n \ndef _get_action_name(argument):\n if argument is None :\n return None\n elif argument.option_strings:\n return '/'.join(argument.option_strings)\n elif argument.metavar not in (None ,SUPPRESS):\n return argument.metavar\n elif argument.dest not in (None ,SUPPRESS):\n return argument.dest\n else :\n return None\n \n \nclass ArgumentError(Exception):\n ''\n\n\n\n \n \n def __init__(self,argument,message):\n self.argument_name=_get_action_name(argument)\n self.message=message\n \n def __str__(self):\n if self.argument_name is None :\n format='%(message)s'\n else :\n format='argument %(argument_name)s: %(message)s'\n return format %dict(message=self.message,\n argument_name=self.argument_name)\n \n \nclass ArgumentTypeError(Exception):\n ''\n pass\n \n \n \n \n \n \nclass Action(_AttributeHolder):\n ''\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n \n \n def __init__(self,\n option_strings,\n dest,\n nargs=None ,\n const=None ,\n default=None ,\n type=None ,\n choices=None ,\n required=False ,\n help=None ,\n metavar=None ):\n self.option_strings=option_strings\n self.dest=dest\n self.nargs=nargs\n self.const=const\n self.default=default\n self.type=type\n self.choices=choices\n self.required=required\n self.help=help\n self.metavar=metavar\n \n def _get_kwargs(self):\n names=[\n 'option_strings',\n 'dest',\n 'nargs',\n 'const',\n 'default',\n 'type',\n 'choices',\n 'help',\n 'metavar',\n ]\n return [(name,getattr(self,name))for name in names]\n \n def __call__(self,parser,namespace,values,option_string=None ):\n raise NotImplementedError(_('.__call__() not defined'))\n \n \nclass _StoreAction(Action):\n\n def __init__(self,\n option_strings,\n dest,\n nargs=None ,\n const=None ,\n default=None ,\n type=None ,\n choices=None ,\n required=False ,\n help=None ,\n metavar=None ):\n if nargs ==0:\n raise ValueError('nargs for store actions must be > 0; if you '\n 'have nothing to store, actions such as store '\n 'true or store const may be more appropriate')\n if const is not None and nargs !=OPTIONAL:\n raise ValueError('nargs must be %r to supply const'%OPTIONAL)\n super(_StoreAction,self).__init__(\n option_strings=option_strings,\n dest=dest,\n nargs=nargs,\n const=const,\n default=default,\n type=type,\n choices=choices,\n required=required,\n help=help,\n metavar=metavar)\n \n def __call__(self,parser,namespace,values,option_string=None ):\n setattr(namespace,self.dest,values)\n \n \nclass _StoreConstAction(Action):\n\n def __init__(self,\n option_strings,\n dest,\n const,\n default=None ,\n required=False ,\n help=None ,\n metavar=None ):\n super(_StoreConstAction,self).__init__(\n option_strings=option_strings,\n dest=dest,\n nargs=0,\n const=const,\n default=default,\n required=required,\n help=help)\n \n def __call__(self,parser,namespace,values,option_string=None ):\n setattr(namespace,self.dest,self.const)\n \n \nclass _StoreTrueAction(_StoreConstAction):\n\n def __init__(self,\n option_strings,\n dest,\n default=False ,\n required=False ,\n help=None ):\n super(_StoreTrueAction,self).__init__(\n option_strings=option_strings,\n dest=dest,\n const=True ,\n default=default,\n required=required,\n help=help)\n \n \nclass _StoreFalseAction(_StoreConstAction):\n\n def __init__(self,\n option_strings,\n dest,\n default=True ,\n required=False ,\n help=None ):\n super(_StoreFalseAction,self).__init__(\n option_strings=option_strings,\n dest=dest,\n const=False ,\n default=default,\n required=required,\n help=help)\n \n \nclass _AppendAction(Action):\n\n def __init__(self,\n option_strings,\n dest,\n nargs=None ,\n const=None ,\n default=None ,\n type=None ,\n choices=None ,\n required=False ,\n help=None ,\n metavar=None ):\n if nargs ==0:\n raise ValueError('nargs for append actions must be > 0; if arg '\n 'strings are not supplying the value to append, '\n 'the append const action may be more appropriate')\n if const is not None and nargs !=OPTIONAL:\n raise ValueError('nargs must be %r to supply const'%OPTIONAL)\n super(_AppendAction,self).__init__(\n option_strings=option_strings,\n dest=dest,\n nargs=nargs,\n const=const,\n default=default,\n type=type,\n choices=choices,\n required=required,\n help=help,\n metavar=metavar)\n \n def __call__(self,parser,namespace,values,option_string=None ):\n items=getattr(namespace,self.dest,None )\n items=_copy_items(items)\n items.append(values)\n setattr(namespace,self.dest,items)\n \n \nclass _AppendConstAction(Action):\n\n def __init__(self,\n option_strings,\n dest,\n const,\n default=None ,\n required=False ,\n help=None ,\n metavar=None ):\n super(_AppendConstAction,self).__init__(\n option_strings=option_strings,\n dest=dest,\n nargs=0,\n const=const,\n default=default,\n required=required,\n help=help,\n metavar=metavar)\n \n def __call__(self,parser,namespace,values,option_string=None ):\n items=getattr(namespace,self.dest,None )\n items=_copy_items(items)\n items.append(self.const)\n setattr(namespace,self.dest,items)\n \n \nclass _CountAction(Action):\n\n def __init__(self,\n option_strings,\n dest,\n default=None ,\n required=False ,\n help=None ):\n super(_CountAction,self).__init__(\n option_strings=option_strings,\n dest=dest,\n nargs=0,\n default=default,\n required=required,\n help=help)\n \n def __call__(self,parser,namespace,values,option_string=None ):\n count=getattr(namespace,self.dest,None )\n if count is None :\n count=0\n setattr(namespace,self.dest,count+1)\n \n \nclass _HelpAction(Action):\n\n def __init__(self,\n option_strings,\n dest=SUPPRESS,\n default=SUPPRESS,\n help=None ):\n super(_HelpAction,self).__init__(\n option_strings=option_strings,\n dest=dest,\n default=default,\n nargs=0,\n help=help)\n \n def __call__(self,parser,namespace,values,option_string=None ):\n parser.print_help()\n parser.exit()\n \n \nclass _VersionAction(Action):\n\n def __init__(self,\n option_strings,\n version=None ,\n dest=SUPPRESS,\n default=SUPPRESS,\n help=\"show program's version number and exit\"):\n super(_VersionAction,self).__init__(\n option_strings=option_strings,\n dest=dest,\n default=default,\n nargs=0,\n help=help)\n self.version=version\n \n def __call__(self,parser,namespace,values,option_string=None ):\n version=self.version\n if version is None :\n version=parser.version\n formatter=parser._get_formatter()\n formatter.add_text(version)\n parser._print_message(formatter.format_help(),_sys.stdout)\n parser.exit()\n \n \nclass _SubParsersAction(Action):\n\n class _ChoicesPseudoAction(Action):\n \n def __init__(self,name,aliases,help):\n metavar=dest=name\n if aliases:\n metavar +=' (%s)'%', '.join(aliases)\n sup=super(_SubParsersAction._ChoicesPseudoAction,self)\n sup.__init__(option_strings=[],dest=dest,help=help,\n metavar=metavar)\n \n def __init__(self,\n option_strings,\n prog,\n parser_class,\n dest=SUPPRESS,\n required=False ,\n help=None ,\n metavar=None ):\n \n self._prog_prefix=prog\n self._parser_class=parser_class\n self._name_parser_map={}\n self._choices_actions=[]\n \n super(_SubParsersAction,self).__init__(\n option_strings=option_strings,\n dest=dest,\n nargs=PARSER,\n choices=self._name_parser_map,\n required=required,\n help=help,\n metavar=metavar)\n \n def add_parser(self,name,**kwargs):\n \n if kwargs.get('prog')is None :\n kwargs['prog']='%s %s'%(self._prog_prefix,name)\n \n aliases=kwargs.pop('aliases',())\n \n \n if 'help'in kwargs:\n help=kwargs.pop('help')\n choice_action=self._ChoicesPseudoAction(name,aliases,help)\n self._choices_actions.append(choice_action)\n \n \n parser=self._parser_class(**kwargs)\n self._name_parser_map[name]=parser\n \n \n for alias in aliases:\n self._name_parser_map[alias]=parser\n \n return parser\n \n def _get_subactions(self):\n return self._choices_actions\n \n def __call__(self,parser,namespace,values,option_string=None ):\n parser_name=values[0]\n arg_strings=values[1:]\n \n \n if self.dest is not SUPPRESS:\n setattr(namespace,self.dest,parser_name)\n \n \n try :\n parser=self._name_parser_map[parser_name]\n except KeyError:\n args={'parser_name':parser_name,\n 'choices':', '.join(self._name_parser_map)}\n msg=_('unknown parser %(parser_name)r (choices: %(choices)s)')%args\n raise ArgumentError(self,msg)\n \n \n \n \n \n \n \n \n subnamespace,arg_strings=parser.parse_known_args(arg_strings,None )\n for key,value in vars(subnamespace).items():\n setattr(namespace,key,value)\n \n if arg_strings:\n vars(namespace).setdefault(_UNRECOGNIZED_ARGS_ATTR,[])\n getattr(namespace,_UNRECOGNIZED_ARGS_ATTR).extend(arg_strings)\n \n \n \n \n \n \nclass FileType(object):\n ''\n\n\n\n\n\n\n\n\n\n\n\n\n\n \n \n def __init__(self,mode='r',bufsize=-1,encoding=None ,errors=None ):\n self._mode=mode\n self._bufsize=bufsize\n self._encoding=encoding\n self._errors=errors\n \n def __call__(self,string):\n \n if string =='-':\n if 'r'in self._mode:\n return _sys.stdin\n elif 'w'in self._mode:\n return _sys.stdout\n else :\n msg=_('argument \"-\" with mode %r')%self._mode\n raise ValueError(msg)\n \n \n try :\n return open(string,self._mode,self._bufsize,self._encoding,\n self._errors)\n except OSError as e:\n message=_(\"can't open '%s': %s\")\n raise ArgumentTypeError(message %(string,e))\n \n def __repr__(self):\n args=self._mode,self._bufsize\n kwargs=[('encoding',self._encoding),('errors',self._errors)]\n args_str=', '.join([repr(arg)for arg in args if arg !=-1]+\n ['%s=%r'%(kw,arg)for kw,arg in kwargs\n if arg is not None ])\n return '%s(%s)'%(type(self).__name__,args_str)\n \n \n \n \n \nclass Namespace(_AttributeHolder):\n ''\n\n\n\n \n \n def __init__(self,**kwargs):\n for name in kwargs:\n setattr(self,name,kwargs[name])\n \n def __eq__(self,other):\n if not isinstance(other,Namespace):\n return NotImplemented\n return vars(self)==vars(other)\n \n def __contains__(self,key):\n return key in self.__dict__\n \n \nclass _ActionsContainer(object):\n\n def __init__(self,\n description,\n prefix_chars,\n argument_default,\n conflict_handler):\n super(_ActionsContainer,self).__init__()\n \n self.description=description\n self.argument_default=argument_default\n self.prefix_chars=prefix_chars\n self.conflict_handler=conflict_handler\n \n \n self._registries={}\n \n \n self.register('action',None ,_StoreAction)\n self.register('action','store',_StoreAction)\n self.register('action','store_const',_StoreConstAction)\n self.register('action','store_true',_StoreTrueAction)\n self.register('action','store_false',_StoreFalseAction)\n self.register('action','append',_AppendAction)\n self.register('action','append_const',_AppendConstAction)\n self.register('action','count',_CountAction)\n self.register('action','help',_HelpAction)\n self.register('action','version',_VersionAction)\n self.register('action','parsers',_SubParsersAction)\n \n \n self._get_handler()\n \n \n self._actions=[]\n self._option_string_actions={}\n \n \n self._action_groups=[]\n self._mutually_exclusive_groups=[]\n \n \n self._defaults={}\n \n \n self._negative_number_matcher=_re.compile(r'^-\\d+$|^-\\d*\\.\\d+$')\n \n \n \n self._has_negative_number_optionals=[]\n \n \n \n \n def register(self,registry_name,value,object):\n registry=self._registries.setdefault(registry_name,{})\n registry[value]=object\n \n def _registry_get(self,registry_name,value,default=None ):\n return self._registries[registry_name].get(value,default)\n \n \n \n \n def set_defaults(self,**kwargs):\n self._defaults.update(kwargs)\n \n \n \n for action in self._actions:\n if action.dest in kwargs:\n action.default=kwargs[action.dest]\n \n def get_default(self,dest):\n for action in self._actions:\n if action.dest ==dest and action.default is not None :\n return action.default\n return self._defaults.get(dest,None )\n \n \n \n \n \n def add_argument(self,*args,**kwargs):\n ''\n\n\n \n \n \n \n \n chars=self.prefix_chars\n if not args or len(args)==1 and args[0][0]not in chars:\n if args and 'dest'in kwargs:\n raise ValueError('dest supplied twice for positional argument')\n kwargs=self._get_positional_kwargs(*args,**kwargs)\n \n \n else :\n kwargs=self._get_optional_kwargs(*args,**kwargs)\n \n \n if 'default'not in kwargs:\n dest=kwargs['dest']\n if dest in self._defaults:\n kwargs['default']=self._defaults[dest]\n elif self.argument_default is not None :\n kwargs['default']=self.argument_default\n \n \n action_class=self._pop_action_class(kwargs)\n if not callable(action_class):\n raise ValueError('unknown action \"%s\"'%(action_class,))\n action=action_class(**kwargs)\n \n \n type_func=self._registry_get('type',action.type,action.type)\n if not callable(type_func):\n raise ValueError('%r is not callable'%(type_func,))\n \n \n if hasattr(self,\"_get_formatter\"):\n try :\n self._get_formatter()._format_args(action,None )\n except TypeError:\n raise ValueError(\"length of metavar tuple does not match nargs\")\n \n return self._add_action(action)\n \n def add_argument_group(self,*args,**kwargs):\n group=_ArgumentGroup(self,*args,**kwargs)\n self._action_groups.append(group)\n return group\n \n def add_mutually_exclusive_group(self,**kwargs):\n group=_MutuallyExclusiveGroup(self,**kwargs)\n self._mutually_exclusive_groups.append(group)\n return group\n \n def _add_action(self,action):\n \n self._check_conflict(action)\n \n \n self._actions.append(action)\n action.container=self\n \n \n for option_string in action.option_strings:\n self._option_string_actions[option_string]=action\n \n \n for option_string in action.option_strings:\n if self._negative_number_matcher.match(option_string):\n if not self._has_negative_number_optionals:\n self._has_negative_number_optionals.append(True )\n \n \n return action\n \n def _remove_action(self,action):\n self._actions.remove(action)\n \n def _add_container_actions(self,container):\n \n title_group_map={}\n for group in self._action_groups:\n if group.title in title_group_map:\n msg=_('cannot merge actions - two groups are named %r')\n raise ValueError(msg %(group.title))\n title_group_map[group.title]=group\n \n \n group_map={}\n for group in container._action_groups:\n \n \n \n if group.title not in title_group_map:\n title_group_map[group.title]=self.add_argument_group(\n title=group.title,\n description=group.description,\n conflict_handler=group.conflict_handler)\n \n \n for action in group._group_actions:\n group_map[action]=title_group_map[group.title]\n \n \n \n \n for group in container._mutually_exclusive_groups:\n mutex_group=self.add_mutually_exclusive_group(\n required=group.required)\n \n \n for action in group._group_actions:\n group_map[action]=mutex_group\n \n \n for action in container._actions:\n group_map.get(action,self)._add_action(action)\n \n def _get_positional_kwargs(self,dest,**kwargs):\n \n if 'required'in kwargs:\n msg=_(\"'required' is an invalid argument for positionals\")\n raise TypeError(msg)\n \n \n \n if kwargs.get('nargs')not in [OPTIONAL,ZERO_OR_MORE]:\n kwargs['required']=True\n if kwargs.get('nargs')==ZERO_OR_MORE and 'default'not in kwargs:\n kwargs['required']=True\n \n \n return dict(kwargs,dest=dest,option_strings=[])\n \n def _get_optional_kwargs(self,*args,**kwargs):\n \n option_strings=[]\n long_option_strings=[]\n for option_string in args:\n \n if not option_string[0]in self.prefix_chars:\n args={'option':option_string,\n 'prefix_chars':self.prefix_chars}\n msg=_('invalid option string %(option)r: '\n 'must start with a character %(prefix_chars)r')\n raise ValueError(msg %args)\n \n \n option_strings.append(option_string)\n if option_string[0]in self.prefix_chars:\n if len(option_string)>1:\n if option_string[1]in self.prefix_chars:\n long_option_strings.append(option_string)\n \n \n dest=kwargs.pop('dest',None )\n if dest is None :\n if long_option_strings:\n dest_option_string=long_option_strings[0]\n else :\n dest_option_string=option_strings[0]\n dest=dest_option_string.lstrip(self.prefix_chars)\n if not dest:\n msg=_('dest= is required for options like %r')\n raise ValueError(msg %option_string)\n dest=dest.replace('-','_')\n \n \n return dict(kwargs,dest=dest,option_strings=option_strings)\n \n def _pop_action_class(self,kwargs,default=None ):\n action=kwargs.pop('action',default)\n return self._registry_get('action',action,action)\n \n def _get_handler(self):\n \n handler_func_name='_handle_conflict_%s'%self.conflict_handler\n try :\n return getattr(self,handler_func_name)\n except AttributeError:\n msg=_('invalid conflict_resolution value: %r')\n raise ValueError(msg %self.conflict_handler)\n \n def _check_conflict(self,action):\n \n \n confl_optionals=[]\n for option_string in action.option_strings:\n if option_string in self._option_string_actions:\n confl_optional=self._option_string_actions[option_string]\n confl_optionals.append((option_string,confl_optional))\n \n \n if confl_optionals:\n conflict_handler=self._get_handler()\n conflict_handler(action,confl_optionals)\n \n def _handle_conflict_error(self,action,conflicting_actions):\n message=ngettext('conflicting option string: %s',\n 'conflicting option strings: %s',\n len(conflicting_actions))\n conflict_string=', '.join([option_string\n for option_string,action\n in conflicting_actions])\n raise ArgumentError(action,message %conflict_string)\n \n def _handle_conflict_resolve(self,action,conflicting_actions):\n \n \n for option_string,action in conflicting_actions:\n \n \n action.option_strings.remove(option_string)\n self._option_string_actions.pop(option_string,None )\n \n \n \n if not action.option_strings:\n action.container._remove_action(action)\n \n \nclass _ArgumentGroup(_ActionsContainer):\n\n def __init__(self,container,title=None ,description=None ,**kwargs):\n \n update=kwargs.setdefault\n update('conflict_handler',container.conflict_handler)\n update('prefix_chars',container.prefix_chars)\n update('argument_default',container.argument_default)\n super_init=super(_ArgumentGroup,self).__init__\n super_init(description=description,**kwargs)\n \n \n self.title=title\n self._group_actions=[]\n \n \n self._registries=container._registries\n self._actions=container._actions\n self._option_string_actions=container._option_string_actions\n self._defaults=container._defaults\n self._has_negative_number_optionals=\\\n container._has_negative_number_optionals\n self._mutually_exclusive_groups=container._mutually_exclusive_groups\n \n def _add_action(self,action):\n action=super(_ArgumentGroup,self)._add_action(action)\n self._group_actions.append(action)\n return action\n \n def _remove_action(self,action):\n super(_ArgumentGroup,self)._remove_action(action)\n self._group_actions.remove(action)\n \n \nclass _MutuallyExclusiveGroup(_ArgumentGroup):\n\n def __init__(self,container,required=False ):\n super(_MutuallyExclusiveGroup,self).__init__(container)\n self.required=required\n self._container=container\n \n def _add_action(self,action):\n if action.required:\n msg=_('mutually exclusive arguments must be optional')\n raise ValueError(msg)\n action=self._container._add_action(action)\n self._group_actions.append(action)\n return action\n \n def _remove_action(self,action):\n self._container._remove_action(action)\n self._group_actions.remove(action)\n \n \nclass ArgumentParser(_AttributeHolder,_ActionsContainer):\n ''\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n \n \n def __init__(self,\n prog=None ,\n usage=None ,\n description=None ,\n epilog=None ,\n parents=[],\n formatter_class=HelpFormatter,\n prefix_chars='-',\n fromfile_prefix_chars=None ,\n argument_default=None ,\n conflict_handler='error',\n add_help=True ,\n allow_abbrev=True ):\n \n superinit=super(ArgumentParser,self).__init__\n superinit(description=description,\n prefix_chars=prefix_chars,\n argument_default=argument_default,\n conflict_handler=conflict_handler)\n \n \n if prog is None :\n prog=_os.path.basename(_sys.argv[0])\n \n self.prog=prog\n self.usage=usage\n self.epilog=epilog\n self.formatter_class=formatter_class\n self.fromfile_prefix_chars=fromfile_prefix_chars\n self.add_help=add_help\n self.allow_abbrev=allow_abbrev\n \n add_group=self.add_argument_group\n self._positionals=add_group(_('positional arguments'))\n self._optionals=add_group(_('optional arguments'))\n self._subparsers=None\n \n \n def identity(string):\n return string\n self.register('type',None ,identity)\n \n \n \n default_prefix='-'if '-'in prefix_chars else prefix_chars[0]\n if self.add_help:\n self.add_argument(\n default_prefix+'h',default_prefix *2+'help',\n action='help',default=SUPPRESS,\n help=_('show this help message and exit'))\n \n \n for parent in parents:\n self._add_container_actions(parent)\n try :\n defaults=parent._defaults\n except AttributeError:\n pass\n else :\n self._defaults.update(defaults)\n \n \n \n \n def _get_kwargs(self):\n names=[\n 'prog',\n 'usage',\n 'description',\n 'formatter_class',\n 'conflict_handler',\n 'add_help',\n ]\n return [(name,getattr(self,name))for name in names]\n \n \n \n \n def add_subparsers(self,**kwargs):\n if self._subparsers is not None :\n self.error(_('cannot have multiple subparser arguments'))\n \n \n kwargs.setdefault('parser_class',type(self))\n \n if 'title'in kwargs or 'description'in kwargs:\n title=_(kwargs.pop('title','subcommands'))\n description=_(kwargs.pop('description',None ))\n self._subparsers=self.add_argument_group(title,description)\n else :\n self._subparsers=self._positionals\n \n \n \n if kwargs.get('prog')is None :\n formatter=self._get_formatter()\n positionals=self._get_positional_actions()\n groups=self._mutually_exclusive_groups\n formatter.add_usage(self.usage,positionals,groups,'')\n kwargs['prog']=formatter.format_help().strip()\n \n \n parsers_class=self._pop_action_class(kwargs,'parsers')\n action=parsers_class(option_strings=[],**kwargs)\n self._subparsers._add_action(action)\n \n \n return action\n \n def _add_action(self,action):\n if action.option_strings:\n self._optionals._add_action(action)\n else :\n self._positionals._add_action(action)\n return action\n \n def _get_optional_actions(self):\n return [action\n for action in self._actions\n if action.option_strings]\n \n def _get_positional_actions(self):\n return [action\n for action in self._actions\n if not action.option_strings]\n \n \n \n \n def parse_args(self,args=None ,namespace=None ):\n args,argv=self.parse_known_args(args,namespace)\n if argv:\n msg=_('unrecognized arguments: %s')\n self.error(msg %' '.join(argv))\n return args\n \n def parse_known_args(self,args=None ,namespace=None ):\n if args is None :\n \n args=_sys.argv[1:]\n else :\n \n args=list(args)\n \n \n if namespace is None :\n namespace=Namespace()\n \n \n for action in self._actions:\n if action.dest is not SUPPRESS:\n if not hasattr(namespace,action.dest):\n if action.default is not SUPPRESS:\n setattr(namespace,action.dest,action.default)\n \n \n for dest in self._defaults:\n if not hasattr(namespace,dest):\n setattr(namespace,dest,self._defaults[dest])\n \n \n try :\n namespace,args=self._parse_known_args(args,namespace)\n if hasattr(namespace,_UNRECOGNIZED_ARGS_ATTR):\n args.extend(getattr(namespace,_UNRECOGNIZED_ARGS_ATTR))\n delattr(namespace,_UNRECOGNIZED_ARGS_ATTR)\n return namespace,args\n except ArgumentError:\n err=_sys.exc_info()[1]\n self.error(str(err))\n \n def _parse_known_args(self,arg_strings,namespace):\n \n if self.fromfile_prefix_chars is not None :\n arg_strings=self._read_args_from_files(arg_strings)\n \n \n \n action_conflicts={}\n for mutex_group in self._mutually_exclusive_groups:\n group_actions=mutex_group._group_actions\n for i,mutex_action in enumerate(mutex_group._group_actions):\n conflicts=action_conflicts.setdefault(mutex_action,[])\n conflicts.extend(group_actions[:i])\n conflicts.extend(group_actions[i+1:])\n \n \n \n \n option_string_indices={}\n arg_string_pattern_parts=[]\n arg_strings_iter=iter(arg_strings)\n for i,arg_string in enumerate(arg_strings_iter):\n \n \n if arg_string =='--':\n arg_string_pattern_parts.append('-')\n for arg_string in arg_strings_iter:\n arg_string_pattern_parts.append('A')\n \n \n \n else :\n option_tuple=self._parse_optional(arg_string)\n if option_tuple is None :\n pattern='A'\n else :\n option_string_indices[i]=option_tuple\n pattern='O'\n arg_string_pattern_parts.append(pattern)\n \n \n arg_strings_pattern=''.join(arg_string_pattern_parts)\n \n \n seen_actions=set()\n seen_non_default_actions=set()\n \n def take_action(action,argument_strings,option_string=None ):\n seen_actions.add(action)\n argument_values=self._get_values(action,argument_strings)\n \n \n \n \n if argument_values is not action.default:\n seen_non_default_actions.add(action)\n for conflict_action in action_conflicts.get(action,[]):\n if conflict_action in seen_non_default_actions:\n msg=_('not allowed with argument %s')\n action_name=_get_action_name(conflict_action)\n raise ArgumentError(action,msg %action_name)\n \n \n \n if argument_values is not SUPPRESS:\n action(self,namespace,argument_values,option_string)\n \n \n def consume_optional(start_index):\n \n \n option_tuple=option_string_indices[start_index]\n action,option_string,explicit_arg=option_tuple\n \n \n \n match_argument=self._match_argument\n action_tuples=[]\n while True :\n \n \n if action is None :\n extras.append(arg_strings[start_index])\n return start_index+1\n \n \n \n if explicit_arg is not None :\n arg_count=match_argument(action,'A')\n \n \n \n \n chars=self.prefix_chars\n if arg_count ==0 and option_string[1]not in chars:\n action_tuples.append((action,[],option_string))\n char=option_string[0]\n option_string=char+explicit_arg[0]\n new_explicit_arg=explicit_arg[1:]or None\n optionals_map=self._option_string_actions\n if option_string in optionals_map:\n action=optionals_map[option_string]\n explicit_arg=new_explicit_arg\n else :\n msg=_('ignored explicit argument %r')\n raise ArgumentError(action,msg %explicit_arg)\n \n \n \n elif arg_count ==1:\n stop=start_index+1\n args=[explicit_arg]\n action_tuples.append((action,args,option_string))\n break\n \n \n \n else :\n msg=_('ignored explicit argument %r')\n raise ArgumentError(action,msg %explicit_arg)\n \n \n \n \n else :\n start=start_index+1\n selected_patterns=arg_strings_pattern[start:]\n arg_count=match_argument(action,selected_patterns)\n stop=start+arg_count\n args=arg_strings[start:stop]\n action_tuples.append((action,args,option_string))\n break\n \n \n \n assert action_tuples\n for action,args,option_string in action_tuples:\n take_action(action,args,option_string)\n return stop\n \n \n \n positionals=self._get_positional_actions()\n \n \n def consume_positionals(start_index):\n \n match_partial=self._match_arguments_partial\n selected_pattern=arg_strings_pattern[start_index:]\n arg_counts=match_partial(positionals,selected_pattern)\n \n \n \n for action,arg_count in zip(positionals,arg_counts):\n args=arg_strings[start_index:start_index+arg_count]\n start_index +=arg_count\n take_action(action,args)\n \n \n \n positionals[:]=positionals[len(arg_counts):]\n return start_index\n \n \n \n extras=[]\n start_index=0\n if option_string_indices:\n max_option_string_index=max(option_string_indices)\n else :\n max_option_string_index=-1\n while start_index <=max_option_string_index:\n \n \n next_option_string_index=min([\n index\n for index in option_string_indices\n if index >=start_index])\n if start_index !=next_option_string_index:\n positionals_end_index=consume_positionals(start_index)\n \n \n \n if positionals_end_index >start_index:\n start_index=positionals_end_index\n continue\n else :\n start_index=positionals_end_index\n \n \n \n if start_index not in option_string_indices:\n strings=arg_strings[start_index:next_option_string_index]\n extras.extend(strings)\n start_index=next_option_string_index\n \n \n start_index=consume_optional(start_index)\n \n \n stop_index=consume_positionals(start_index)\n \n \n extras.extend(arg_strings[stop_index:])\n \n \n \n required_actions=[]\n for action in self._actions:\n if action not in seen_actions:\n if action.required:\n required_actions.append(_get_action_name(action))\n else :\n \n \n \n \n if (action.default is not None and\n isinstance(action.default,str)and\n hasattr(namespace,action.dest)and\n action.default is getattr(namespace,action.dest)):\n setattr(namespace,action.dest,\n self._get_value(action,action.default))\n \n if required_actions:\n self.error(_('the following arguments are required: %s')%\n ', '.join(required_actions))\n \n \n for group in self._mutually_exclusive_groups:\n if group.required:\n for action in group._group_actions:\n if action in seen_non_default_actions:\n break\n \n \n else :\n names=[_get_action_name(action)\n for action in group._group_actions\n if action.help is not SUPPRESS]\n msg=_('one of the arguments %s is required')\n self.error(msg %' '.join(names))\n \n \n return namespace,extras\n \n def _read_args_from_files(self,arg_strings):\n \n new_arg_strings=[]\n for arg_string in arg_strings:\n \n \n if not arg_string or arg_string[0]not in self.fromfile_prefix_chars:\n new_arg_strings.append(arg_string)\n \n \n else :\n try :\n with open(arg_string[1:])as args_file:\n arg_strings=[]\n for arg_line in args_file.read().splitlines():\n for arg in self.convert_arg_line_to_args(arg_line):\n arg_strings.append(arg)\n arg_strings=self._read_args_from_files(arg_strings)\n new_arg_strings.extend(arg_strings)\n except OSError:\n err=_sys.exc_info()[1]\n self.error(str(err))\n \n \n return new_arg_strings\n \n def convert_arg_line_to_args(self,arg_line):\n return [arg_line]\n \n def _match_argument(self,action,arg_strings_pattern):\n \n nargs_pattern=self._get_nargs_pattern(action)\n match=_re.match(nargs_pattern,arg_strings_pattern)\n \n \n if match is None :\n nargs_errors={\n None :_('expected one argument'),\n OPTIONAL:_('expected at most one argument'),\n ONE_OR_MORE:_('expected at least one argument'),\n }\n default=ngettext('expected %s argument',\n 'expected %s arguments',\n action.nargs)%action.nargs\n msg=nargs_errors.get(action.nargs,default)\n raise ArgumentError(action,msg)\n \n \n return len(match.group(1))\n \n def _match_arguments_partial(self,actions,arg_strings_pattern):\n \n \n result=[]\n for i in range(len(actions),0,-1):\n actions_slice=actions[:i]\n pattern=''.join([self._get_nargs_pattern(action)\n for action in actions_slice])\n match=_re.match(pattern,arg_strings_pattern)\n if match is not None :\n result.extend([len(string)for string in match.groups()])\n break\n \n \n return result\n \n def _parse_optional(self,arg_string):\n \n if not arg_string:\n return None\n \n \n if not arg_string[0]in self.prefix_chars:\n return None\n \n \n if arg_string in self._option_string_actions:\n action=self._option_string_actions[arg_string]\n return action,arg_string,None\n \n \n if len(arg_string)==1:\n return None\n \n \n if '='in arg_string:\n option_string,explicit_arg=arg_string.split('=',1)\n if option_string in self._option_string_actions:\n action=self._option_string_actions[option_string]\n return action,option_string,explicit_arg\n \n if self.allow_abbrev:\n \n \n option_tuples=self._get_option_tuples(arg_string)\n \n \n if len(option_tuples)>1:\n options=', '.join([option_string\n for action,option_string,explicit_arg in option_tuples])\n args={'option':arg_string,'matches':options}\n msg=_('ambiguous option: %(option)s could match %(matches)s')\n self.error(msg %args)\n \n \n \n elif len(option_tuples)==1:\n option_tuple,=option_tuples\n return option_tuple\n \n \n \n \n if self._negative_number_matcher.match(arg_string):\n if not self._has_negative_number_optionals:\n return None\n \n \n if ' 'in arg_string:\n return None\n \n \n \n return None ,arg_string,None\n \n def _get_option_tuples(self,option_string):\n result=[]\n \n \n \n chars=self.prefix_chars\n if option_string[0]in chars and option_string[1]in chars:\n if '='in option_string:\n option_prefix,explicit_arg=option_string.split('=',1)\n else :\n option_prefix=option_string\n explicit_arg=None\n for option_string in self._option_string_actions:\n if option_string.startswith(option_prefix):\n action=self._option_string_actions[option_string]\n tup=action,option_string,explicit_arg\n result.append(tup)\n \n \n \n \n elif option_string[0]in chars and option_string[1]not in chars:\n option_prefix=option_string\n explicit_arg=None\n short_option_prefix=option_string[:2]\n short_explicit_arg=option_string[2:]\n \n for option_string in self._option_string_actions:\n if option_string ==short_option_prefix:\n action=self._option_string_actions[option_string]\n tup=action,option_string,short_explicit_arg\n result.append(tup)\n elif option_string.startswith(option_prefix):\n action=self._option_string_actions[option_string]\n tup=action,option_string,explicit_arg\n result.append(tup)\n \n \n else :\n self.error(_('unexpected option string: %s')%option_string)\n \n \n return result\n \n def _get_nargs_pattern(self,action):\n \n \n nargs=action.nargs\n \n \n if nargs is None :\n nargs_pattern='(-*A-*)'\n \n \n elif nargs ==OPTIONAL:\n nargs_pattern='(-*A?-*)'\n \n \n elif nargs ==ZERO_OR_MORE:\n nargs_pattern='(-*[A-]*)'\n \n \n elif nargs ==ONE_OR_MORE:\n nargs_pattern='(-*A[A-]*)'\n \n \n elif nargs ==REMAINDER:\n nargs_pattern='([-AO]*)'\n \n \n elif nargs ==PARSER:\n nargs_pattern='(-*A[-AO]*)'\n \n \n elif nargs ==SUPPRESS:\n nargs_pattern='(-*-*)'\n \n \n else :\n nargs_pattern='(-*%s-*)'%'-*'.join('A'*nargs)\n \n \n if action.option_strings:\n nargs_pattern=nargs_pattern.replace('-*','')\n nargs_pattern=nargs_pattern.replace('-','')\n \n \n return nargs_pattern\n \n \n \n \n \n def parse_intermixed_args(self,args=None ,namespace=None ):\n args,argv=self.parse_known_intermixed_args(args,namespace)\n if argv:\n msg=_('unrecognized arguments: %s')\n self.error(msg %' '.join(argv))\n return args\n \n def parse_known_intermixed_args(self,args=None ,namespace=None ):\n \n \n \n \n \n \n \n \n \n \n \n \n positionals=self._get_positional_actions()\n a=[action for action in positionals\n if action.nargs in [PARSER,REMAINDER]]\n if a:\n raise TypeError('parse_intermixed_args: positional arg'\n ' with nargs=%s'%a[0].nargs)\n \n if [action.dest for group in self._mutually_exclusive_groups\n for action in group._group_actions if action in positionals]:\n raise TypeError('parse_intermixed_args: positional in'\n ' mutuallyExclusiveGroup')\n \n try :\n save_usage=self.usage\n try :\n if self.usage is None :\n \n self.usage=self.format_usage()[7:]\n for action in positionals:\n \n action.save_nargs=action.nargs\n \n action.nargs=SUPPRESS\n action.save_default=action.default\n action.default=SUPPRESS\n namespace,remaining_args=self.parse_known_args(args,\n namespace)\n for action in positionals:\n \n if (hasattr(namespace,action.dest)\n and getattr(namespace,action.dest)==[]):\n from warnings import warn\n warn('Do not expect %s in %s'%(action.dest,namespace))\n delattr(namespace,action.dest)\n finally :\n \n for action in positionals:\n action.nargs=action.save_nargs\n action.default=action.save_default\n optionals=self._get_optional_actions()\n try :\n \n \n for action in optionals:\n action.save_required=action.required\n action.required=False\n for group in self._mutually_exclusive_groups:\n group.save_required=group.required\n group.required=False\n namespace,extras=self.parse_known_args(remaining_args,\n namespace)\n finally :\n \n for action in optionals:\n action.required=action.save_required\n for group in self._mutually_exclusive_groups:\n group.required=group.save_required\n finally :\n self.usage=save_usage\n return namespace,extras\n \n \n \n \n def _get_values(self,action,arg_strings):\n \n if action.nargs not in [PARSER,REMAINDER]:\n try :\n arg_strings.remove('--')\n except ValueError:\n pass\n \n \n if not arg_strings and action.nargs ==OPTIONAL:\n if action.option_strings:\n value=action.const\n else :\n value=action.default\n if isinstance(value,str):\n value=self._get_value(action,value)\n self._check_value(action,value)\n \n \n \n elif (not arg_strings and action.nargs ==ZERO_OR_MORE and\n not action.option_strings):\n if action.default is not None :\n value=action.default\n else :\n value=arg_strings\n self._check_value(action,value)\n \n \n elif len(arg_strings)==1 and action.nargs in [None ,OPTIONAL]:\n arg_string,=arg_strings\n value=self._get_value(action,arg_string)\n self._check_value(action,value)\n \n \n elif action.nargs ==REMAINDER:\n value=[self._get_value(action,v)for v in arg_strings]\n \n \n elif action.nargs ==PARSER:\n value=[self._get_value(action,v)for v in arg_strings]\n self._check_value(action,value[0])\n \n \n elif action.nargs ==SUPPRESS:\n value=SUPPRESS\n \n \n else :\n value=[self._get_value(action,v)for v in arg_strings]\n for v in value:\n self._check_value(action,v)\n \n \n return value\n \n def _get_value(self,action,arg_string):\n type_func=self._registry_get('type',action.type,action.type)\n if not callable(type_func):\n msg=_('%r is not callable')\n raise ArgumentError(action,msg %type_func)\n \n \n try :\n result=type_func(arg_string)\n \n \n except ArgumentTypeError:\n name=getattr(action.type,'__name__',repr(action.type))\n msg=str(_sys.exc_info()[1])\n raise ArgumentError(action,msg)\n \n \n except (TypeError,ValueError):\n name=getattr(action.type,'__name__',repr(action.type))\n args={'type':name,'value':arg_string}\n msg=_('invalid %(type)s value: %(value)r')\n raise ArgumentError(action,msg %args)\n \n \n return result\n \n def _check_value(self,action,value):\n \n if action.choices is not None and value not in action.choices:\n args={'value':value,\n 'choices':', '.join(map(repr,action.choices))}\n msg=_('invalid choice: %(value)r (choose from %(choices)s)')\n raise ArgumentError(action,msg %args)\n \n \n \n \n def format_usage(self):\n formatter=self._get_formatter()\n formatter.add_usage(self.usage,self._actions,\n self._mutually_exclusive_groups)\n return formatter.format_help()\n \n def format_help(self):\n formatter=self._get_formatter()\n \n \n formatter.add_usage(self.usage,self._actions,\n self._mutually_exclusive_groups)\n \n \n formatter.add_text(self.description)\n \n \n for action_group in self._action_groups:\n formatter.start_section(action_group.title)\n formatter.add_text(action_group.description)\n formatter.add_arguments(action_group._group_actions)\n formatter.end_section()\n \n \n formatter.add_text(self.epilog)\n \n \n return formatter.format_help()\n \n def _get_formatter(self):\n return self.formatter_class(prog=self.prog)\n \n \n \n \n def print_usage(self,file=None ):\n if file is None :\n file=_sys.stdout\n self._print_message(self.format_usage(),file)\n \n def print_help(self,file=None ):\n if file is None :\n file=_sys.stdout\n self._print_message(self.format_help(),file)\n \n def _print_message(self,message,file=None ):\n if message:\n if file is None :\n file=_sys.stderr\n file.write(message)\n \n \n \n \n def exit(self,status=0,message=None ):\n if message:\n self._print_message(message,_sys.stderr)\n _sys.exit(status)\n \n def error(self,message):\n ''\n\n\n\n\n\n\n \n self.print_usage(_sys.stderr)\n args={'prog':self.prog,'message':message}\n self.exit(2,_('%(prog)s: error: %(message)s\\n')%args)\n", ["copy", "gettext", "os", "re", "sys", "textwrap", "warnings"]], "errno": [".py", "''\n\n\n\n\n\n\n\n\n\n\n\n\n\nE2BIG=7\n\nEACCES=13\n\nEADDRINUSE=10048\n\nEADDRNOTAVAIL=10049\n\nEAFNOSUPPORT=10047\n\nEAGAIN=11\n\nEALREADY=10037\n\nEBADF=9\n\nEBADMSG=104\n\nEBUSY=16\n\nECANCELED=105\n\nECHILD=10\n\nECONNABORTED=10053\n\nECONNREFUSED=10061\n\nECONNRESET=10054\n\nEDEADLK=36\n\nEDEADLOCK=36\n\nEDESTADDRREQ=10039\n\nEDOM=33\n\nEDQUOT=10069\n\nEEXIST=17\n\nEFAULT=14\n\nEFBIG=27\n\nEHOSTDOWN=10064\n\nEHOSTUNREACH=10065\n\nEIDRM=111\n\nEILSEQ=42\n\nEINPROGRESS=10036\n\nEINTR=4\n\nEINVAL=22\n\nEIO=5\n\nEISCONN=10056\n\nEISDIR=21\n\nELOOP=10062\n\nEMFILE=24\n\nEMLINK=31\n\nEMSGSIZE=10040\n\nENAMETOOLONG=38\n\nENETDOWN=10050\n\nENETRESET=10052\n\nENETUNREACH=10051\n\nENFILE=23\n\nENOBUFS=10055\n\nENODATA=120\n\nENODEV=19\n\nENOENT=2\n\nENOEXEC=8\n\nENOLCK=39\n\nENOLINK=121\n\nENOMEM=12\n\nENOMSG=122\n\nENOPROTOOPT=10042\n\nENOSPC=28\n\nENOSR=124\n\nENOSTR=125\n\nENOSYS=40\n\nENOTCONN=10057\n\nENOTDIR=20\n\nENOTEMPTY=41\n\nENOTRECOVERABLE=127\n\nENOTSOCK=10038\n\nENOTSUP=129\n\nENOTTY=25\n\nENXIO=6\n\nEOPNOTSUPP=10045\n\nEOVERFLOW=132\n\nEOWNERDEAD=133\n\nEPERM=1\n\nEPFNOSUPPORT=10046\n\nEPIPE=32\n\nEPROTO=134\n\nEPROTONOSUPPORT=10043\n\nEPROTOTYPE=10041\n\nERANGE=34\n\nEREMOTE=10071\n\nEROFS=30\n\nESHUTDOWN=10058\n\nESOCKTNOSUPPORT=10044\n\nESPIPE=29\n\nESRCH=3\n\nESTALE=10070\n\nETIME=137\n\nETIMEDOUT=10060\n\nETOOMANYREFS=10059\n\nETXTBSY=139\n\nEUSERS=10068\n\nEWOULDBLOCK=10035\n\nEXDEV=18\n\nWSABASEERR=10000\n\nWSAEACCES=10013\n\nWSAEADDRINUSE=10048\n\nWSAEADDRNOTAVAIL=10049\n\nWSAEAFNOSUPPORT=10047\n\nWSAEALREADY=10037\n\nWSAEBADF=10009\n\nWSAECONNABORTED=10053\n\nWSAECONNREFUSED=10061\n\nWSAECONNRESET=10054\n\nWSAEDESTADDRREQ=10039\n\nWSAEDISCON=10101\n\nWSAEDQUOT=10069\n\nWSAEFAULT=10014\n\nWSAEHOSTDOWN=10064\n\nWSAEHOSTUNREACH=10065\n\nWSAEINPROGRESS=10036\n\nWSAEINTR=10004\n\nWSAEINVAL=10022\n\nWSAEISCONN=10056\n\nWSAELOOP=10062\n\nWSAEMFILE=10024\n\nWSAEMSGSIZE=10040\n\nWSAENAMETOOLONG=10063\n\nWSAENETDOWN=10050\n\nWSAENETRESET=10052\n\nWSAENETUNREACH=10051\n\nWSAENOBUFS=10055\n\nWSAENOPROTOOPT=10042\n\nWSAENOTCONN=10057\n\nWSAENOTEMPTY=10066\n\nWSAENOTSOCK=10038\n\nWSAEOPNOTSUPP=10045\n\nWSAEPFNOSUPPORT=10046\n\nWSAEPROCLIM=10067\n\nWSAEPROTONOSUPPORT=10043\n\nWSAEPROTOTYPE=10041\n\nWSAEREMOTE=10071\n\nWSAESHUTDOWN=10058\n\nWSAESOCKTNOSUPPORT=10044\n\nWSAESTALE=10070\n\nWSAETIMEDOUT=10060\n\nWSAETOOMANYREFS=10059\n\nWSAEUSERS=10068\n\nWSAEWOULDBLOCK=10035\n\nWSANOTINITIALISED=10093\n\nWSASYSNOTREADY=10091\n\nWSAVERNOTSUPPORTED=10092\n\nerrorcode={v:k for (k,v)in globals().items()if k ==k.upper()}\n", []], "browser.object_storage": [".py", "import json\n\nclass _UnProvided():\n pass\n \n \nclass ObjectStorage():\n\n def __init__(self,storage):\n self.storage=storage\n \n def __delitem__(self,key):\n del self.storage[json.dumps(key)]\n \n def __getitem__(self,key):\n return json.loads(self.storage[json.dumps(key)])\n \n def __setitem__(self,key,value):\n self.storage[json.dumps(key)]=json.dumps(value)\n \n def __contains__(self,key):\n return json.dumps(key)in self.storage\n \n def get(self,key,default=None ):\n if json.dumps(key)in self.storage:\n return self.storage[json.dumps(key)]\n return default\n \n def pop(self,key,default=_UnProvided()):\n if type(default)is _UnProvided or json.dumps(key)in self.storage:\n return json.loads(self.storage.pop(json.dumps(key)))\n return default\n \n def __iter__(self):\n keys=self.keys()\n return keys.__iter__()\n \n def keys(self):\n return [json.loads(key)for key in self.storage.keys()]\n \n def values(self):\n return [json.loads(val)for val in self.storage.values()]\n \n def items(self):\n return list(zip(self.keys(),self.values()))\n \n def clear(self):\n self.storage.clear()\n \n def __len__(self):\n return len(self.storage)\n", ["json"]], "_strptime": [".js", "var _b_ = __BRYTHON__.builtins\n\nvar $module = (function($B){\n return {\n _strptime_datetime: function(cls, s, fmt){\n var pos_s = 0,\n pos_fmt = 0,\n dt = {}\n function error(){\n throw Error(\"no match \" + pos_s + \" \" + s.charAt(pos_s) + \" \"+\n pos_fmt + \" \" + fmt.charAt(pos_fmt))\n }\n\n var locale = __BRYTHON__.locale,\n shortdays = [],\n longdays = [],\n conv_func = locale == \"C\" ?\n function(d){return d.toDateString()} :\n function(d, options){\n return d.toLocaleDateString(locale, options)\n }\n\n for(var day = 16; day < 23; day++){\n var d = new Date(Date.UTC(2012, 11, day, 3, 0, 0))\n shortdays.push(conv_func(d, {weekday: 'short'}))\n longdays.push(conv_func(d, {weekday: 'long'}))\n }\n\n var shortmonths = [],\n longmonths = []\n\n for(var month = 0; month < 12; month++){\n var d = new Date(Date.UTC(2012, month, 1, 3, 0, 0))\n shortmonths.push(conv_func(d, {month: 'short'}))\n longmonths.push(conv_func(d, {month: 'long'}))\n }\n\n var shortdays_re = new RegExp(shortdays.join(\"|\").replace(\".\", \"\\\\.\")),\n longdays_re = new RegExp(longdays.join(\"|\")),\n shortmonths_re = new RegExp(shortmonths.join(\"|\").replace(\".\", \"\\\\.\")),\n longmonths_re = new RegExp(longmonths.join(\"|\"))\n\n var regexps = {\n d: [\"day\", new RegExp(\"0[1-9]|[123][0-9]\")],\n H: [\"hour\", new RegExp(\"[01][0-9]|2[0-3]|\\\\d\")],\n I: [\"hour\", new RegExp(\"0[0-9]|1[0-2]\")],\n m: [\"month\", new RegExp(\"0[1-9]|1[012]\")],\n M: [\"minute\", new RegExp(\"[0-5][0-9]\")],\n S: [\"second\", new RegExp(\"([1-5]\\\\d)|(0?\\\\d)\")],\n y: [\"year\", new RegExp(\"0{0,2}\\\\d{2}\")],\n Y: [\"year\", new RegExp(\"\\\\d{4}\")]\n }\n\n while(pos_fmt < fmt.length){\n var car = fmt.charAt(pos_fmt)\n if(car == \"%\"){\n var spec = fmt.charAt(pos_fmt + 1),\n regexp = regexps[spec]\n if(regexp !== undefined){\n var re = regexp[1],\n attr = regexp[0],\n res = re.exec(s.substr(pos_s))\n if(res === null){\n error()\n }else{\n if(dt[attr] !== undefined){\n throw Error(attr + \" is defined more than once\")\n }else{\n dt[attr] = parseInt(res[0])\n pos_fmt += 2\n pos_s += res[0].length\n }\n }\n }else if(spec == \"a\" || spec == \"A\"){\n // Locale's abbreviated (a) or full (A) weekday name\n var attr = \"weekday\",\n re = spec == \"a\" ? shortdays_re : longdays_re,\n t = spec == \"a\" ? shortdays : longdays\n res = re.exec(s.substr(pos_s))\n if(res === null){\n error()\n }else{\n var match = res[0],\n ix = t.indexOf(match)\n }\n if(dt.weekday !== undefined){\n throw Error(attr + \" is defined more than once\")\n }else{\n dt.weekday = ix\n }\n pos_fmt += 2\n pos_s += match.length\n }else if(spec == \"b\" || spec == \"B\"){\n // Locales's abbreviated (b) or full (B) month\n var attr = \"month\",\n re = spec == \"b\" ? shortmonths_re : longmonths_re,\n t = spec == \"b\" ? shortmonths : longmonths,\n res = re.exec(s.substr(pos_s))\n if(res === null){\n error()\n }else{\n var match = res[0],\n ix = t.indexOf(match)\n }\n if(dt.month !== undefined){\n throw Error(attr + \" is defined more than once\")\n }else{\n dt.month = ix + 1\n }\n pos_fmt += 2\n pos_s += match.length\n }else if(spec == \"c\"){\n // Locale's appropriate date and time representation\n var fmt1 = fmt.substr(0, pos_fmt - 1) + _locale_c_format() +\n fmt.substr(pos_fmt + 2)\n console.log(\"fmt1\", fmt1)\n fmt = fmt1\n }else if(spec == \"%\"){\n if(s.charAt(pos_s) == \"%\"){\n pos_fmt++\n pos_s++\n }else{\n error()\n }\n }else{\n pos_fmt++\n }\n }else{\n if(car == s.charAt(pos_s)){\n pos_fmt++\n pos_s++\n }else{\n error()\n }\n }\n }\n return $B.$call(cls)(dt.year, dt.month, dt.day,\n dt.hour || 0, dt.minute || 0, dt.second || 0)\n }\n }\n})(__BRYTHON__)\n"], "socket": [".py", "\n\n\n\"\"\"\\\nThis module provides socket operations and some related functions.\nOn Unix, it supports IP (Internet Protocol) and Unix domain sockets.\nOn other systems, it only supports IP. Functions specific for a\nsocket are available as methods of the socket object.\n\nFunctions:\n\nsocket() -- create a new socket object\nsocketpair() -- create a pair of new socket objects [*]\nfromfd() -- create a socket object from an open file descriptor [*]\nfromshare() -- create a socket object from data received from socket.share() [*]\ngethostname() -- return the current hostname\ngethostbyname() -- map a hostname to its IP number\ngethostbyaddr() -- map an IP number or hostname to DNS info\ngetservbyname() -- map a service name and a protocol name to a port number\ngetprotobyname() -- map a protocol name (e.g. 'tcp') to a number\nntohs(), ntohl() -- convert 16, 32 bit int from network to host byte order\nhtons(), htonl() -- convert 16, 32 bit int from host to network byte order\ninet_aton() -- convert IP addr string (123.45.67.89) to 32-bit packed format\ninet_ntoa() -- convert 32-bit packed format IP to string (123.45.67.89)\nsocket.getdefaulttimeout() -- get the default timeout value\nsocket.setdefaulttimeout() -- set the default timeout value\ncreate_connection() -- connects to an address, with an optional timeout and\n optional source address.\n\n [*] not available on all platforms!\n\nSpecial objects:\n\nSocketType -- type object for socket objects\nerror -- exception raised for I/O errors\nhas_ipv6 -- boolean value indicating if IPv6 is supported\n\nIntEnum constants:\n\nAF_INET, AF_UNIX -- socket domains (first argument to socket() call)\nSOCK_STREAM, SOCK_DGRAM, SOCK_RAW -- socket types (second argument)\n\nInteger constants:\n\nMany other constants may be defined; these may be used in calls to\nthe setsockopt() and getsockopt() methods.\n\"\"\"\n\nimport _socket\nfrom _socket import *\n\nimport os,sys,io,selectors\nfrom enum import IntEnum,IntFlag\n\ntry :\n import errno\nexcept ImportError:\n errno=None\nEBADF=getattr(errno,'EBADF',9)\nEAGAIN=getattr(errno,'EAGAIN',11)\nEWOULDBLOCK=getattr(errno,'EWOULDBLOCK',11)\n\n__all__=[\"fromfd\",\"getfqdn\",\"create_connection\",\n\"AddressFamily\",\"SocketKind\"]\n__all__.extend(os._get_exports_list(_socket))\n\n\n\n\n\n\n\nIntEnum._convert(\n'AddressFamily',\n__name__,\nlambda C:C.isupper()and C.startswith('AF_'))\n\nIntEnum._convert(\n'SocketKind',\n__name__,\nlambda C:C.isupper()and C.startswith('SOCK_'))\n\nIntFlag._convert(\n'MsgFlag',\n__name__,\nlambda C:C.isupper()and C.startswith('MSG_'))\n\nIntFlag._convert(\n'AddressInfo',\n__name__,\nlambda C:C.isupper()and C.startswith('AI_'))\n\n_LOCALHOST='127.0.0.1'\n_LOCALHOST_V6='::1'\n\n\ndef _intenum_converter(value,enum_klass):\n ''\n\n\n \n try :\n return enum_klass(value)\n except ValueError:\n return value\n \n_realsocket=socket\n\n\nif sys.platform.lower().startswith(\"win\"):\n errorTab={}\n errorTab[10004]=\"The operation was interrupted.\"\n errorTab[10009]=\"A bad file handle was passed.\"\n errorTab[10013]=\"Permission denied.\"\n errorTab[10014]=\"A fault occurred on the network??\"\n errorTab[10022]=\"An invalid operation was attempted.\"\n errorTab[10035]=\"The socket operation would block\"\n errorTab[10036]=\"A blocking operation is already in progress.\"\n errorTab[10048]=\"The network address is in use.\"\n errorTab[10054]=\"The connection has been reset.\"\n errorTab[10058]=\"The network has been shut down.\"\n errorTab[10060]=\"The operation timed out.\"\n errorTab[10061]=\"Connection refused.\"\n errorTab[10063]=\"The name is too long.\"\n errorTab[10064]=\"The host is down.\"\n errorTab[10065]=\"The host is unreachable.\"\n __all__.append(\"errorTab\")\n \n \nclass _GiveupOnSendfile(Exception):pass\n\n\nclass socket(_socket.socket):\n\n ''\n \n __slots__=[\"__weakref__\",\"_io_refs\",\"_closed\"]\n \n def __init__(self,family=-1,type=-1,proto=-1,fileno=None ):\n \n \n \n \n if fileno is None :\n if family ==-1:\n family=AF_INET\n if type ==-1:\n type=SOCK_STREAM\n if proto ==-1:\n proto=0\n _socket.socket.__init__(self,family,type,proto,fileno)\n self._io_refs=0\n self._closed=False\n \n def __enter__(self):\n return self\n \n def __exit__(self,*args):\n if not self._closed:\n self.close()\n \n def __repr__(self):\n ''\n\n \n closed=getattr(self,'_closed',False )\n s=\"<%s.%s%s fd=%i, family=%s, type=%s, proto=%i\"\\\n %(self.__class__.__module__,\n self.__class__.__qualname__,\n \" [closed]\"if closed else \"\",\n self.fileno(),\n self.family,\n self.type,\n self.proto)\n if not closed:\n try :\n laddr=self.getsockname()\n if laddr:\n s +=\", laddr=%s\"%str(laddr)\n except error:\n pass\n try :\n raddr=self.getpeername()\n if raddr:\n s +=\", raddr=%s\"%str(raddr)\n except error:\n pass\n s +='>'\n return s\n \n def __getstate__(self):\n raise TypeError(\"Cannot serialize socket object\")\n \n def dup(self):\n ''\n\n\n\n \n fd=dup(self.fileno())\n sock=self.__class__(self.family,self.type,self.proto,fileno=fd)\n sock.settimeout(self.gettimeout())\n return sock\n \n def accept(self):\n ''\n\n\n\n\n \n fd,addr=self._accept()\n sock=socket(self.family,self.type,self.proto,fileno=fd)\n \n \n \n if getdefaulttimeout()is None and self.gettimeout():\n sock.setblocking(True )\n return sock,addr\n \n def makefile(self,mode=\"r\",buffering=None ,*,\n encoding=None ,errors=None ,newline=None ):\n ''\n\n\n\n \n \n if not set(mode)<={\"r\",\"w\",\"b\"}:\n raise ValueError(\"invalid mode %r (only r, w, b allowed)\"%(mode,))\n writing=\"w\"in mode\n reading=\"r\"in mode or not writing\n assert reading or writing\n binary=\"b\"in mode\n rawmode=\"\"\n if reading:\n rawmode +=\"r\"\n if writing:\n rawmode +=\"w\"\n raw=SocketIO(self,rawmode)\n self._io_refs +=1\n if buffering is None :\n buffering=-1\n if buffering <0:\n buffering=io.DEFAULT_BUFFER_SIZE\n if buffering ==0:\n if not binary:\n raise ValueError(\"unbuffered streams must be binary\")\n return raw\n if reading and writing:\n buffer=io.BufferedRWPair(raw,raw,buffering)\n elif reading:\n buffer=io.BufferedReader(raw,buffering)\n else :\n assert writing\n buffer=io.BufferedWriter(raw,buffering)\n if binary:\n return buffer\n text=io.TextIOWrapper(buffer,encoding,errors,newline)\n text.mode=mode\n return text\n \n if hasattr(os,'sendfile'):\n \n def _sendfile_use_sendfile(self,file,offset=0,count=None ):\n self._check_sendfile_params(file,offset,count)\n sockno=self.fileno()\n try :\n fileno=file.fileno()\n except (AttributeError,io.UnsupportedOperation)as err:\n raise _GiveupOnSendfile(err)\n try :\n fsize=os.fstat(fileno).st_size\n except OSError as err:\n raise _GiveupOnSendfile(err)\n if not fsize:\n return 0\n blocksize=fsize if not count else count\n \n timeout=self.gettimeout()\n if timeout ==0:\n raise ValueError(\"non-blocking sockets are not supported\")\n \n \n \n if hasattr(selectors,'PollSelector'):\n selector=selectors.PollSelector()\n else :\n selector=selectors.SelectSelector()\n selector.register(sockno,selectors.EVENT_WRITE)\n \n total_sent=0\n \n selector_select=selector.select\n os_sendfile=os.sendfile\n try :\n while True :\n if timeout and not selector_select(timeout):\n raise _socket.timeout('timed out')\n if count:\n blocksize=count -total_sent\n if blocksize <=0:\n break\n try :\n sent=os_sendfile(sockno,fileno,offset,blocksize)\n except BlockingIOError:\n if not timeout:\n \n \n selector_select()\n continue\n except OSError as err:\n if total_sent ==0:\n \n \n \n \n raise _GiveupOnSendfile(err)\n raise err from None\n else :\n if sent ==0:\n break\n offset +=sent\n total_sent +=sent\n return total_sent\n finally :\n if total_sent >0 and hasattr(file,'seek'):\n file.seek(offset)\n else :\n def _sendfile_use_sendfile(self,file,offset=0,count=None ):\n raise _GiveupOnSendfile(\n \"os.sendfile() not available on this platform\")\n \n def _sendfile_use_send(self,file,offset=0,count=None ):\n self._check_sendfile_params(file,offset,count)\n if self.gettimeout()==0:\n raise ValueError(\"non-blocking sockets are not supported\")\n if offset:\n file.seek(offset)\n blocksize=min(count,8192)if count else 8192\n total_sent=0\n \n file_read=file.read\n sock_send=self.send\n try :\n while True :\n if count:\n blocksize=min(count -total_sent,blocksize)\n if blocksize <=0:\n break\n data=memoryview(file_read(blocksize))\n if not data:\n break\n while True :\n try :\n sent=sock_send(data)\n except BlockingIOError:\n continue\n else :\n total_sent +=sent\n if sent <len(data):\n data=data[sent:]\n else :\n break\n return total_sent\n finally :\n if total_sent >0 and hasattr(file,'seek'):\n file.seek(offset+total_sent)\n \n def _check_sendfile_params(self,file,offset,count):\n if 'b'not in getattr(file,'mode','b'):\n raise ValueError(\"file should be opened in binary mode\")\n if not self.type&SOCK_STREAM:\n raise ValueError(\"only SOCK_STREAM type sockets are supported\")\n if count is not None :\n if not isinstance(count,int):\n raise TypeError(\n \"count must be a positive integer (got {!r})\".format(count))\n if count <=0:\n raise ValueError(\n \"count must be a positive integer (got {!r})\".format(count))\n \n def sendfile(self,file,offset=0,count=None ):\n ''\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n \n try :\n return self._sendfile_use_sendfile(file,offset,count)\n except _GiveupOnSendfile:\n return self._sendfile_use_send(file,offset,count)\n \n def _decref_socketios(self):\n if self._io_refs >0:\n self._io_refs -=1\n if self._closed:\n self.close()\n \n def _real_close(self,_ss=_socket.socket):\n \n _ss.close(self)\n \n def close(self):\n \n self._closed=True\n if self._io_refs <=0:\n self._real_close()\n \n def detach(self):\n ''\n\n\n\n\n \n self._closed=True\n return super().detach()\n \n @property\n def family(self):\n ''\n \n return _intenum_converter(super().family,AddressFamily)\n \n @property\n def type(self):\n ''\n \n return _intenum_converter(super().type,SocketKind)\n \n if os.name =='nt':\n def get_inheritable(self):\n return os.get_handle_inheritable(self.fileno())\n def set_inheritable(self,inheritable):\n os.set_handle_inheritable(self.fileno(),inheritable)\n else :\n def get_inheritable(self):\n return os.get_inheritable(self.fileno())\n def set_inheritable(self,inheritable):\n os.set_inheritable(self.fileno(),inheritable)\n get_inheritable.__doc__=\"Get the inheritable flag of the socket\"\n set_inheritable.__doc__=\"Set the inheritable flag of the socket\"\n \ndef fromfd(fd,family,type,proto=0):\n ''\n\n\n\n \n nfd=dup(fd)\n return socket(family,type,proto,nfd)\n \nif hasattr(_socket.socket,\"share\"):\n def fromshare(info):\n ''\n\n\n\n \n return socket(0,0,0,info)\n __all__.append(\"fromshare\")\n \nif hasattr(_socket,\"socketpair\"):\n\n def socketpair(family=None ,type=SOCK_STREAM,proto=0):\n ''\n\n\n\n\n\n \n if family is None :\n try :\n family=AF_UNIX\n except NameError:\n family=AF_INET\n a,b=_socket.socketpair(family,type,proto)\n a=socket(family,type,proto,a.detach())\n b=socket(family,type,proto,b.detach())\n return a,b\n \nelse :\n\n\n def socketpair(family=AF_INET,type=SOCK_STREAM,proto=0):\n if family ==AF_INET:\n host=_LOCALHOST\n elif family ==AF_INET6:\n host=_LOCALHOST_V6\n else :\n raise ValueError(\"Only AF_INET and AF_INET6 socket address families \"\n \"are supported\")\n if type !=SOCK_STREAM:\n raise ValueError(\"Only SOCK_STREAM socket type is supported\")\n if proto !=0:\n raise ValueError(\"Only protocol zero is supported\")\n \n \n \n lsock=socket(family,type,proto)\n try :\n lsock.bind((host,0))\n lsock.listen()\n \n addr,port=lsock.getsockname()[:2]\n csock=socket(family,type,proto)\n try :\n csock.setblocking(False )\n try :\n csock.connect((addr,port))\n except (BlockingIOError,InterruptedError):\n pass\n csock.setblocking(True )\n ssock,_=lsock.accept()\n except :\n csock.close()\n raise\n finally :\n lsock.close()\n return (ssock,csock)\n __all__.append(\"socketpair\")\n \nsocketpair.__doc__=\"\"\"socketpair([family[, type[, proto]]]) -> (socket object, socket object)\nCreate a pair of socket objects from the sockets returned by the platform\nsocketpair() function.\nThe arguments are the same as for socket() except the default family is AF_UNIX\nif defined on the platform; otherwise, the default is AF_INET.\n\"\"\"\n\n_blocking_errnos={EAGAIN,EWOULDBLOCK}\n\nclass SocketIO(io.RawIOBase):\n\n ''\n\n\n\n \n \n \n \n \n \n \n \n \n \n \n def __init__(self,sock,mode):\n if mode not in (\"r\",\"w\",\"rw\",\"rb\",\"wb\",\"rwb\"):\n raise ValueError(\"invalid mode: %r\"%mode)\n io.RawIOBase.__init__(self)\n self._sock=sock\n if \"b\"not in mode:\n mode +=\"b\"\n self._mode=mode\n self._reading=\"r\"in mode\n self._writing=\"w\"in mode\n self._timeout_occurred=False\n \n def readinto(self,b):\n ''\n\n\n\n\n\n \n self._checkClosed()\n self._checkReadable()\n if self._timeout_occurred:\n raise OSError(\"cannot read from timed out object\")\n while True :\n try :\n return self._sock.recv_into(b)\n except timeout:\n self._timeout_occurred=True\n raise\n except error as e:\n if e.args[0]in _blocking_errnos:\n return None\n raise\n \n def write(self,b):\n ''\n\n\n\n \n self._checkClosed()\n self._checkWritable()\n try :\n return self._sock.send(b)\n except error as e:\n \n if e.args[0]in _blocking_errnos:\n return None\n raise\n \n def readable(self):\n ''\n \n if self.closed:\n raise ValueError(\"I/O operation on closed socket.\")\n return self._reading\n \n def writable(self):\n ''\n \n if self.closed:\n raise ValueError(\"I/O operation on closed socket.\")\n return self._writing\n \n def seekable(self):\n ''\n \n if self.closed:\n raise ValueError(\"I/O operation on closed socket.\")\n return super().seekable()\n \n def fileno(self):\n ''\n \n self._checkClosed()\n return self._sock.fileno()\n \n @property\n def name(self):\n if not self.closed:\n return self.fileno()\n else :\n return -1\n \n @property\n def mode(self):\n return self._mode\n \n def close(self):\n ''\n\n \n if self.closed:\n return\n io.RawIOBase.close(self)\n self._sock._decref_socketios()\n self._sock=None\n \n \ndef getfqdn(name=''):\n ''\n\n\n\n\n\n\n \n name=name.strip()\n if not name or name =='0.0.0.0':\n name=gethostname()\n try :\n hostname,aliases,ipaddrs=gethostbyaddr(name)\n except error:\n pass\n else :\n aliases.insert(0,hostname)\n for name in aliases:\n if '.'in name:\n break\n else :\n name=hostname\n return name\n \n \n_GLOBAL_DEFAULT_TIMEOUT=object()\n\ndef create_connection(address,timeout=_GLOBAL_DEFAULT_TIMEOUT,\nsource_address=None ):\n ''\n\n\n\n\n\n\n\n\n\n \n \n host,port=address\n err=None\n for res in getaddrinfo(host,port,0,SOCK_STREAM):\n af,socktype,proto,canonname,sa=res\n sock=None\n try :\n sock=socket(af,socktype,proto)\n if timeout is not _GLOBAL_DEFAULT_TIMEOUT:\n sock.settimeout(timeout)\n if source_address:\n sock.bind(source_address)\n sock.connect(sa)\n \n err=None\n return sock\n \n except error as _:\n err=_\n if sock is not None :\n sock.close()\n \n if err is not None :\n raise err\n else :\n raise error(\"getaddrinfo returns an empty list\")\n \ndef getaddrinfo(host,port,family=0,type=0,proto=0,flags=0):\n ''\n\n\n\n\n\n\n\n\n\n\n\n \n \n \n addrlist=[]\n for res in _socket.getaddrinfo(host,port,family,type,proto,flags):\n af,socktype,proto,canonname,sa=res\n addrlist.append((_intenum_converter(af,AddressFamily),\n _intenum_converter(socktype,SocketKind),\n proto,canonname,sa))\n return addrlist\n", ["_socket", "enum", "errno", "io", "os", "selectors", "sys"]], "browser.session_storage": [".py", "\nimport sys\nfrom browser import window\nfrom .local_storage import LocalStorage\n\nhas_session_storage=hasattr(window,'sessionStorage')\n\nclass SessionStorage(LocalStorage):\n\n storage_type=\"session_storage\"\n \n def __init__(self):\n if not has_session_storage:\n raise EnvironmentError(\"SessionStorage not available\")\n self.store=window.sessionStorage\n \nif has_session_storage:\n storage=SessionStorage()\n", ["browser", "browser.local_storage", "sys"]], "zipfile": [".py", "''\n\n\n\n\nimport io\nimport os\nimport importlib.util\nimport sys\nimport time\nimport stat\nimport shutil\nimport struct\nimport binascii\nimport threading\n\ntry :\n import zlib\n crc32=zlib.crc32\nexcept ImportError:\n zlib=None\n crc32=binascii.crc32\n \ntry :\n import bz2\nexcept ImportError:\n bz2=None\n \ntry :\n import lzma\nexcept ImportError:\n lzma=None\n \n__all__=[\"BadZipFile\",\"BadZipfile\",\"error\",\n\"ZIP_STORED\",\"ZIP_DEFLATED\",\"ZIP_BZIP2\",\"ZIP_LZMA\",\n\"is_zipfile\",\"ZipInfo\",\"ZipFile\",\"PyZipFile\",\"LargeZipFile\"]\n\nclass BadZipFile(Exception):\n pass\n \n \nclass LargeZipFile(Exception):\n ''\n\n\n \n \nerror=BadZipfile=BadZipFile\n\n\nZIP64_LIMIT=(1 <<31)-1\nZIP_FILECOUNT_LIMIT=(1 <<16)-1\nZIP_MAX_COMMENT=(1 <<16)-1\n\n\nZIP_STORED=0\nZIP_DEFLATED=8\nZIP_BZIP2=12\nZIP_LZMA=14\n\n\nDEFAULT_VERSION=20\nZIP64_VERSION=45\nBZIP2_VERSION=46\nLZMA_VERSION=63\n\nMAX_EXTRACT_VERSION=63\n\n\n\n\n\n\n\n\n\nstructEndArchive=b\"<4s4H2LH\"\nstringEndArchive=b\"PK\\005\\006\"\nsizeEndCentDir=struct.calcsize(structEndArchive)\n\n_ECD_SIGNATURE=0\n_ECD_DISK_NUMBER=1\n_ECD_DISK_START=2\n_ECD_ENTRIES_THIS_DISK=3\n_ECD_ENTRIES_TOTAL=4\n_ECD_SIZE=5\n_ECD_OFFSET=6\n_ECD_COMMENT_SIZE=7\n\n\n_ECD_COMMENT=8\n_ECD_LOCATION=9\n\n\n\nstructCentralDir=\"<4s4B4HL2L5H2L\"\nstringCentralDir=b\"PK\\001\\002\"\nsizeCentralDir=struct.calcsize(structCentralDir)\n\n\n_CD_SIGNATURE=0\n_CD_CREATE_VERSION=1\n_CD_CREATE_SYSTEM=2\n_CD_EXTRACT_VERSION=3\n_CD_EXTRACT_SYSTEM=4\n_CD_FLAG_BITS=5\n_CD_COMPRESS_TYPE=6\n_CD_TIME=7\n_CD_DATE=8\n_CD_CRC=9\n_CD_COMPRESSED_SIZE=10\n_CD_UNCOMPRESSED_SIZE=11\n_CD_FILENAME_LENGTH=12\n_CD_EXTRA_FIELD_LENGTH=13\n_CD_COMMENT_LENGTH=14\n_CD_DISK_NUMBER_START=15\n_CD_INTERNAL_FILE_ATTRIBUTES=16\n_CD_EXTERNAL_FILE_ATTRIBUTES=17\n_CD_LOCAL_HEADER_OFFSET=18\n\n\n\nstructFileHeader=\"<4s2B4HL2L2H\"\nstringFileHeader=b\"PK\\003\\004\"\nsizeFileHeader=struct.calcsize(structFileHeader)\n\n_FH_SIGNATURE=0\n_FH_EXTRACT_VERSION=1\n_FH_EXTRACT_SYSTEM=2\n_FH_GENERAL_PURPOSE_FLAG_BITS=3\n_FH_COMPRESSION_METHOD=4\n_FH_LAST_MOD_TIME=5\n_FH_LAST_MOD_DATE=6\n_FH_CRC=7\n_FH_COMPRESSED_SIZE=8\n_FH_UNCOMPRESSED_SIZE=9\n_FH_FILENAME_LENGTH=10\n_FH_EXTRA_FIELD_LENGTH=11\n\n\nstructEndArchive64Locator=\"<4sLQL\"\nstringEndArchive64Locator=b\"PK\\x06\\x07\"\nsizeEndCentDir64Locator=struct.calcsize(structEndArchive64Locator)\n\n\n\nstructEndArchive64=\"<4sQ2H2L4Q\"\nstringEndArchive64=b\"PK\\x06\\x06\"\nsizeEndCentDir64=struct.calcsize(structEndArchive64)\n\n_CD64_SIGNATURE=0\n_CD64_DIRECTORY_RECSIZE=1\n_CD64_CREATE_VERSION=2\n_CD64_EXTRACT_VERSION=3\n_CD64_DISK_NUMBER=4\n_CD64_DISK_NUMBER_START=5\n_CD64_NUMBER_ENTRIES_THIS_DISK=6\n_CD64_NUMBER_ENTRIES_TOTAL=7\n_CD64_DIRECTORY_SIZE=8\n_CD64_OFFSET_START_CENTDIR=9\n\ndef _check_zipfile(fp):\n try :\n if _EndRecData(fp):\n return True\n except OSError:\n pass\n return False\n \ndef is_zipfile(filename):\n ''\n\n\n \n result=False\n try :\n if hasattr(filename,\"read\"):\n result=_check_zipfile(fp=filename)\n else :\n with open(filename,\"rb\")as fp:\n result=_check_zipfile(fp)\n except OSError:\n pass\n return result\n \ndef _EndRecData64(fpin,offset,endrec):\n ''\n\n \n try :\n fpin.seek(offset -sizeEndCentDir64Locator,2)\n except OSError:\n \n \n return endrec\n \n data=fpin.read(sizeEndCentDir64Locator)\n if len(data)!=sizeEndCentDir64Locator:\n return endrec\n sig,diskno,reloff,disks=struct.unpack(structEndArchive64Locator,data)\n if sig !=stringEndArchive64Locator:\n return endrec\n \n if diskno !=0 or disks !=1:\n raise BadZipFile(\"zipfiles that span multiple disks are not supported\")\n \n \n fpin.seek(offset -sizeEndCentDir64Locator -sizeEndCentDir64,2)\n data=fpin.read(sizeEndCentDir64)\n if len(data)!=sizeEndCentDir64:\n return endrec\n sig,sz,create_version,read_version,disk_num,disk_dir,\\\n dircount,dircount2,dirsize,diroffset=\\\n struct.unpack(structEndArchive64,data)\n if sig !=stringEndArchive64:\n return endrec\n \n \n endrec[_ECD_SIGNATURE]=sig\n endrec[_ECD_DISK_NUMBER]=disk_num\n endrec[_ECD_DISK_START]=disk_dir\n endrec[_ECD_ENTRIES_THIS_DISK]=dircount\n endrec[_ECD_ENTRIES_TOTAL]=dircount2\n endrec[_ECD_SIZE]=dirsize\n endrec[_ECD_OFFSET]=diroffset\n return endrec\n \n \ndef _EndRecData(fpin):\n ''\n\n\n \n \n \n fpin.seek(0,2)\n filesize=fpin.tell()\n \n \n \n \n try :\n fpin.seek(-sizeEndCentDir,2)\n except OSError:\n return None\n data=fpin.read()\n if (len(data)==sizeEndCentDir and\n data[0:4]==stringEndArchive and\n data[-2:]==b\"\\000\\000\"):\n \n endrec=struct.unpack(structEndArchive,data)\n endrec=list(endrec)\n \n \n endrec.append(b\"\")\n endrec.append(filesize -sizeEndCentDir)\n \n \n return _EndRecData64(fpin,-sizeEndCentDir,endrec)\n \n \n \n \n \n \n maxCommentStart=max(filesize -(1 <<16)-sizeEndCentDir,0)\n fpin.seek(maxCommentStart,0)\n data=fpin.read()\n start=data.rfind(stringEndArchive)\n if start >=0:\n \n recData=data[start:start+sizeEndCentDir]\n if len(recData)!=sizeEndCentDir:\n \n return None\n endrec=list(struct.unpack(structEndArchive,recData))\n commentSize=endrec[_ECD_COMMENT_SIZE]\n comment=data[start+sizeEndCentDir:start+sizeEndCentDir+commentSize]\n endrec.append(comment)\n endrec.append(maxCommentStart+start)\n \n \n return _EndRecData64(fpin,maxCommentStart+start -filesize,\n endrec)\n \n \n return None\n \n \nclass ZipInfo(object):\n ''\n \n __slots__=(\n 'orig_filename',\n 'filename',\n 'date_time',\n 'compress_type',\n '_compresslevel',\n 'comment',\n 'extra',\n 'create_system',\n 'create_version',\n 'extract_version',\n 'reserved',\n 'flag_bits',\n 'volume',\n 'internal_attr',\n 'external_attr',\n 'header_offset',\n 'CRC',\n 'compress_size',\n 'file_size',\n '_raw_time',\n )\n \n def __init__(self,filename=\"NoName\",date_time=(1980,1,1,0,0,0)):\n self.orig_filename=filename\n \n \n \n null_byte=filename.find(chr(0))\n if null_byte >=0:\n filename=filename[0:null_byte]\n \n \n \n if os.sep !=\"/\"and os.sep in filename:\n filename=filename.replace(os.sep,\"/\")\n \n self.filename=filename\n self.date_time=date_time\n \n if date_time[0]<1980:\n raise ValueError('ZIP does not support timestamps before 1980')\n \n \n self.compress_type=ZIP_STORED\n self._compresslevel=None\n self.comment=b\"\"\n self.extra=b\"\"\n if sys.platform =='win32':\n self.create_system=0\n else :\n \n self.create_system=3\n self.create_version=DEFAULT_VERSION\n self.extract_version=DEFAULT_VERSION\n self.reserved=0\n self.flag_bits=0\n self.volume=0\n self.internal_attr=0\n self.external_attr=0\n \n \n \n \n \n \n def __repr__(self):\n result=['<%s filename=%r'%(self.__class__.__name__,self.filename)]\n if self.compress_type !=ZIP_STORED:\n result.append(' compress_type=%s'%\n compressor_names.get(self.compress_type,\n self.compress_type))\n hi=self.external_attr >>16\n lo=self.external_attr&0xFFFF\n if hi:\n result.append(' filemode=%r'%stat.filemode(hi))\n if lo:\n result.append(' external_attr=%#x'%lo)\n isdir=self.is_dir()\n if not isdir or self.file_size:\n result.append(' file_size=%r'%self.file_size)\n if ((not isdir or self.compress_size)and\n (self.compress_type !=ZIP_STORED or\n self.file_size !=self.compress_size)):\n result.append(' compress_size=%r'%self.compress_size)\n result.append('>')\n return ''.join(result)\n \n def FileHeader(self,zip64=None ):\n ''\n dt=self.date_time\n dosdate=(dt[0]-1980)<<9 |dt[1]<<5 |dt[2]\n dostime=dt[3]<<11 |dt[4]<<5 |(dt[5]//2)\n if self.flag_bits&0x08:\n \n CRC=compress_size=file_size=0\n else :\n CRC=self.CRC\n compress_size=self.compress_size\n file_size=self.file_size\n \n extra=self.extra\n \n min_version=0\n if zip64 is None :\n zip64=file_size >ZIP64_LIMIT or compress_size >ZIP64_LIMIT\n if zip64:\n fmt='<HHQQ'\n extra=extra+struct.pack(fmt,\n 1,struct.calcsize(fmt)-4,file_size,compress_size)\n if file_size >ZIP64_LIMIT or compress_size >ZIP64_LIMIT:\n if not zip64:\n raise LargeZipFile(\"Filesize would require ZIP64 extensions\")\n \n \n file_size=0xffffffff\n compress_size=0xffffffff\n min_version=ZIP64_VERSION\n \n if self.compress_type ==ZIP_BZIP2:\n min_version=max(BZIP2_VERSION,min_version)\n elif self.compress_type ==ZIP_LZMA:\n min_version=max(LZMA_VERSION,min_version)\n \n self.extract_version=max(min_version,self.extract_version)\n self.create_version=max(min_version,self.create_version)\n filename,flag_bits=self._encodeFilenameFlags()\n header=struct.pack(structFileHeader,stringFileHeader,\n self.extract_version,self.reserved,flag_bits,\n self.compress_type,dostime,dosdate,CRC,\n compress_size,file_size,\n len(filename),len(extra))\n return header+filename+extra\n \n def _encodeFilenameFlags(self):\n try :\n return self.filename.encode('ascii'),self.flag_bits\n except UnicodeEncodeError:\n return self.filename.encode('utf-8'),self.flag_bits |0x800\n \n def _decodeExtra(self):\n \n extra=self.extra\n unpack=struct.unpack\n while len(extra)>=4:\n tp,ln=unpack('<HH',extra[:4])\n if ln+4 >len(extra):\n raise BadZipFile(\"Corrupt extra field %04x (size=%d)\"%(tp,ln))\n if tp ==0x0001:\n if ln >=24:\n counts=unpack('<QQQ',extra[4:28])\n elif ln ==16:\n counts=unpack('<QQ',extra[4:20])\n elif ln ==8:\n counts=unpack('<Q',extra[4:12])\n elif ln ==0:\n counts=()\n else :\n raise BadZipFile(\"Corrupt extra field %04x (size=%d)\"%(tp,ln))\n \n idx=0\n \n \n if self.file_size in (0xffffffffffffffff,0xffffffff):\n self.file_size=counts[idx]\n idx +=1\n \n if self.compress_size ==0xFFFFFFFF:\n self.compress_size=counts[idx]\n idx +=1\n \n if self.header_offset ==0xffffffff:\n old=self.header_offset\n self.header_offset=counts[idx]\n idx +=1\n \n extra=extra[ln+4:]\n \n @classmethod\n def from_file(cls,filename,arcname=None ):\n ''\n\n\n\n\n\n\n \n if isinstance(filename,os.PathLike):\n filename=os.fspath(filename)\n st=os.stat(filename)\n isdir=stat.S_ISDIR(st.st_mode)\n mtime=time.localtime(st.st_mtime)\n date_time=mtime[0:6]\n \n if arcname is None :\n arcname=filename\n arcname=os.path.normpath(os.path.splitdrive(arcname)[1])\n while arcname[0]in (os.sep,os.altsep):\n arcname=arcname[1:]\n if isdir:\n arcname +='/'\n zinfo=cls(arcname,date_time)\n zinfo.external_attr=(st.st_mode&0xFFFF)<<16\n if isdir:\n zinfo.file_size=0\n zinfo.external_attr |=0x10\n else :\n zinfo.file_size=st.st_size\n \n return zinfo\n \n def is_dir(self):\n ''\n return self.filename[-1]=='/'\n \n \n \n \n \n \n_crctable=None\ndef _gen_crc(crc):\n for j in range(8):\n if crc&1:\n crc=(crc >>1)^0xEDB88320\n else :\n crc >>=1\n return crc\n \n \n \n \n \n \n \n \n \ndef _ZipDecrypter(pwd):\n key0=305419896\n key1=591751049\n key2=878082192\n \n global _crctable\n if _crctable is None :\n _crctable=list(map(_gen_crc,range(256)))\n crctable=_crctable\n \n def crc32(ch,crc):\n ''\n return (crc >>8)^crctable[(crc ^ch)&0xFF]\n \n def update_keys(c):\n nonlocal key0,key1,key2\n key0=crc32(c,key0)\n key1=(key1+(key0&0xFF))&0xFFFFFFFF\n key1=(key1 *134775813+1)&0xFFFFFFFF\n key2=crc32(key1 >>24,key2)\n \n for p in pwd:\n update_keys(p)\n \n def decrypter(data):\n ''\n result=bytearray()\n append=result.append\n for c in data:\n k=key2 |2\n c ^=((k *(k ^1))>>8)&0xFF\n update_keys(c)\n append(c)\n return bytes(result)\n \n return decrypter\n \n \nclass LZMACompressor:\n\n def __init__(self):\n self._comp=None\n \n def _init(self):\n props=lzma._encode_filter_properties({'id':lzma.FILTER_LZMA1})\n self._comp=lzma.LZMACompressor(lzma.FORMAT_RAW,filters=[\n lzma._decode_filter_properties(lzma.FILTER_LZMA1,props)\n ])\n return struct.pack('<BBH',9,4,len(props))+props\n \n def compress(self,data):\n if self._comp is None :\n return self._init()+self._comp.compress(data)\n return self._comp.compress(data)\n \n def flush(self):\n if self._comp is None :\n return self._init()+self._comp.flush()\n return self._comp.flush()\n \n \nclass LZMADecompressor:\n\n def __init__(self):\n self._decomp=None\n self._unconsumed=b''\n self.eof=False\n \n def decompress(self,data):\n if self._decomp is None :\n self._unconsumed +=data\n if len(self._unconsumed)<=4:\n return b''\n psize,=struct.unpack('<H',self._unconsumed[2:4])\n if len(self._unconsumed)<=4+psize:\n return b''\n \n self._decomp=lzma.LZMADecompressor(lzma.FORMAT_RAW,filters=[\n lzma._decode_filter_properties(lzma.FILTER_LZMA1,\n self._unconsumed[4:4+psize])\n ])\n data=self._unconsumed[4+psize:]\n del self._unconsumed\n \n result=self._decomp.decompress(data)\n self.eof=self._decomp.eof\n return result\n \n \ncompressor_names={\n0:'store',\n1:'shrink',\n2:'reduce',\n3:'reduce',\n4:'reduce',\n5:'reduce',\n6:'implode',\n7:'tokenize',\n8:'deflate',\n9:'deflate64',\n10:'implode',\n12:'bzip2',\n14:'lzma',\n18:'terse',\n19:'lz77',\n97:'wavpack',\n98:'ppmd',\n}\n\ndef _check_compression(compression):\n if compression ==ZIP_STORED:\n pass\n elif compression ==ZIP_DEFLATED:\n if not zlib:\n raise RuntimeError(\n \"Compression requires the (missing) zlib module\")\n elif compression ==ZIP_BZIP2:\n if not bz2:\n raise RuntimeError(\n \"Compression requires the (missing) bz2 module\")\n elif compression ==ZIP_LZMA:\n if not lzma:\n raise RuntimeError(\n \"Compression requires the (missing) lzma module\")\n else :\n raise NotImplementedError(\"That compression method is not supported\")\n \n \ndef _get_compressor(compress_type,compresslevel=None ):\n if compress_type ==ZIP_DEFLATED:\n if compresslevel is not None :\n return zlib.compressobj(compresslevel,zlib.DEFLATED,-15)\n return zlib.compressobj(zlib.Z_DEFAULT_COMPRESSION,zlib.DEFLATED,-15)\n elif compress_type ==ZIP_BZIP2:\n if compresslevel is not None :\n return bz2.BZ2Compressor(compresslevel)\n return bz2.BZ2Compressor()\n \n elif compress_type ==ZIP_LZMA:\n return LZMACompressor()\n else :\n return None\n \n \ndef _get_decompressor(compress_type):\n if compress_type ==ZIP_STORED:\n return None\n elif compress_type ==ZIP_DEFLATED:\n return zlib.decompressobj(-15)\n elif compress_type ==ZIP_BZIP2:\n return bz2.BZ2Decompressor()\n elif compress_type ==ZIP_LZMA:\n return LZMADecompressor()\n else :\n descr=compressor_names.get(compress_type)\n if descr:\n raise NotImplementedError(\"compression type %d (%s)\"%(compress_type,descr))\n else :\n raise NotImplementedError(\"compression type %d\"%(compress_type,))\n \n \nclass _SharedFile:\n def __init__(self,file,pos,close,lock,writing):\n self._file=file\n self._pos=pos\n self._close=close\n self._lock=lock\n self._writing=writing\n self.seekable=file.seekable\n self.tell=file.tell\n \n def seek(self,offset,whence=0):\n with self._lock:\n if self.writing():\n raise ValueError(\"Can't reposition in the ZIP file while \"\n \"there is an open writing handle on it. \"\n \"Close the writing handle before trying to read.\")\n self._file.seek(self._pos)\n self._pos=self._file.tell()\n return self._pos\n \n def read(self,n=-1):\n with self._lock:\n if self._writing():\n raise ValueError(\"Can't read from the ZIP file while there \"\n \"is an open writing handle on it. \"\n \"Close the writing handle before trying to read.\")\n self._file.seek(self._pos)\n data=self._file.read(n)\n self._pos=self._file.tell()\n return data\n \n def close(self):\n if self._file is not None :\n fileobj=self._file\n self._file=None\n self._close(fileobj)\n \n \nclass _Tellable:\n def __init__(self,fp):\n self.fp=fp\n self.offset=0\n \n def write(self,data):\n n=self.fp.write(data)\n self.offset +=n\n return n\n \n def tell(self):\n return self.offset\n \n def flush(self):\n self.fp.flush()\n \n def close(self):\n self.fp.close()\n \n \nclass ZipExtFile(io.BufferedIOBase):\n ''\n\n \n \n \n MAX_N=1 <<31 -1\n \n \n MIN_READ_SIZE=4096\n \n \n MAX_SEEK_READ=1 <<24\n \n def __init__(self,fileobj,mode,zipinfo,decrypter=None ,\n close_fileobj=False ):\n self._fileobj=fileobj\n self._decrypter=decrypter\n self._close_fileobj=close_fileobj\n \n self._compress_type=zipinfo.compress_type\n self._compress_left=zipinfo.compress_size\n self._left=zipinfo.file_size\n \n self._decompressor=_get_decompressor(self._compress_type)\n \n self._eof=False\n self._readbuffer=b''\n self._offset=0\n \n self.newlines=None\n \n \n \n if self._decrypter is not None :\n self._compress_left -=12\n \n self.mode=mode\n self.name=zipinfo.filename\n \n if hasattr(zipinfo,'CRC'):\n self._expected_crc=zipinfo.CRC\n self._running_crc=crc32(b'')\n else :\n self._expected_crc=None\n \n self._seekable=False\n try :\n if fileobj.seekable():\n self._orig_compress_start=fileobj.tell()\n self._orig_compress_size=zipinfo.compress_size\n self._orig_file_size=zipinfo.file_size\n self._orig_start_crc=self._running_crc\n self._seekable=True\n except AttributeError:\n pass\n \n def __repr__(self):\n result=['<%s.%s'%(self.__class__.__module__,\n self.__class__.__qualname__)]\n if not self.closed:\n result.append(' name=%r mode=%r'%(self.name,self.mode))\n if self._compress_type !=ZIP_STORED:\n result.append(' compress_type=%s'%\n compressor_names.get(self._compress_type,\n self._compress_type))\n else :\n result.append(' [closed]')\n result.append('>')\n return ''.join(result)\n \n def readline(self,limit=-1):\n ''\n\n\n \n \n if limit <0:\n \n i=self._readbuffer.find(b'\\n',self._offset)+1\n if i >0:\n line=self._readbuffer[self._offset:i]\n self._offset=i\n return line\n \n return io.BufferedIOBase.readline(self,limit)\n \n def peek(self,n=1):\n ''\n if n >len(self._readbuffer)-self._offset:\n chunk=self.read(n)\n if len(chunk)>self._offset:\n self._readbuffer=chunk+self._readbuffer[self._offset:]\n self._offset=0\n else :\n self._offset -=len(chunk)\n \n \n return self._readbuffer[self._offset:self._offset+512]\n \n def readable(self):\n return True\n \n def read(self,n=-1):\n ''\n\n \n if n is None or n <0:\n buf=self._readbuffer[self._offset:]\n self._readbuffer=b''\n self._offset=0\n while not self._eof:\n buf +=self._read1(self.MAX_N)\n return buf\n \n end=n+self._offset\n if end <len(self._readbuffer):\n buf=self._readbuffer[self._offset:end]\n self._offset=end\n return buf\n \n n=end -len(self._readbuffer)\n buf=self._readbuffer[self._offset:]\n self._readbuffer=b''\n self._offset=0\n while n >0 and not self._eof:\n data=self._read1(n)\n if n <len(data):\n self._readbuffer=data\n self._offset=n\n buf +=data[:n]\n break\n buf +=data\n n -=len(data)\n return buf\n \n def _update_crc(self,newdata):\n \n if self._expected_crc is None :\n \n return\n self._running_crc=crc32(newdata,self._running_crc)\n \n if self._eof and self._running_crc !=self._expected_crc:\n raise BadZipFile(\"Bad CRC-32 for file %r\"%self.name)\n \n def read1(self,n):\n ''\n \n if n is None or n <0:\n buf=self._readbuffer[self._offset:]\n self._readbuffer=b''\n self._offset=0\n while not self._eof:\n data=self._read1(self.MAX_N)\n if data:\n buf +=data\n break\n return buf\n \n end=n+self._offset\n if end <len(self._readbuffer):\n buf=self._readbuffer[self._offset:end]\n self._offset=end\n return buf\n \n n=end -len(self._readbuffer)\n buf=self._readbuffer[self._offset:]\n self._readbuffer=b''\n self._offset=0\n if n >0:\n while not self._eof:\n data=self._read1(n)\n if n <len(data):\n self._readbuffer=data\n self._offset=n\n buf +=data[:n]\n break\n if data:\n buf +=data\n break\n return buf\n \n def _read1(self,n):\n \n \n if self._eof or n <=0:\n return b''\n \n \n if self._compress_type ==ZIP_DEFLATED:\n \n data=self._decompressor.unconsumed_tail\n if n >len(data):\n data +=self._read2(n -len(data))\n else :\n data=self._read2(n)\n \n if self._compress_type ==ZIP_STORED:\n self._eof=self._compress_left <=0\n elif self._compress_type ==ZIP_DEFLATED:\n n=max(n,self.MIN_READ_SIZE)\n data=self._decompressor.decompress(data,n)\n self._eof=(self._decompressor.eof or\n self._compress_left <=0 and\n not self._decompressor.unconsumed_tail)\n if self._eof:\n data +=self._decompressor.flush()\n else :\n data=self._decompressor.decompress(data)\n self._eof=self._decompressor.eof or self._compress_left <=0\n \n data=data[:self._left]\n self._left -=len(data)\n if self._left <=0:\n self._eof=True\n self._update_crc(data)\n return data\n \n def _read2(self,n):\n if self._compress_left <=0:\n return b''\n \n n=max(n,self.MIN_READ_SIZE)\n n=min(n,self._compress_left)\n \n data=self._fileobj.read(n)\n self._compress_left -=len(data)\n if not data:\n raise EOFError\n \n if self._decrypter is not None :\n data=self._decrypter(data)\n return data\n \n def close(self):\n try :\n if self._close_fileobj:\n self._fileobj.close()\n finally :\n super().close()\n \n def seekable(self):\n return self._seekable\n \n def seek(self,offset,whence=0):\n if not self._seekable:\n raise io.UnsupportedOperation(\"underlying stream is not seekable\")\n curr_pos=self.tell()\n if whence ==0:\n new_pos=offset\n elif whence ==1:\n new_pos=curr_pos+offset\n elif whence ==2:\n new_pos=self._orig_file_size+offset\n else :\n raise ValueError(\"whence must be os.SEEK_SET (0), \"\n \"os.SEEK_CUR (1), or os.SEEK_END (2)\")\n \n if new_pos >self._orig_file_size:\n new_pos=self._orig_file_size\n \n if new_pos <0:\n new_pos=0\n \n read_offset=new_pos -curr_pos\n buff_offset=read_offset+self._offset\n \n if buff_offset >=0 and buff_offset <len(self._readbuffer):\n \n self._offset=buff_offset\n read_offset=0\n elif read_offset <0:\n \n \n self._fileobj.seek(self._orig_compress_start)\n self._running_crc=self._orig_start_crc\n self._compress_left=self._orig_compress_size\n self._left=self._orig_file_size\n self._readbuffer=b''\n self._offset=0\n self._decompressor=zipfile._get_decompressor(self._compress_type)\n self._eof=False\n read_offset=new_pos\n \n while read_offset >0:\n read_len=min(self.MAX_SEEK_READ,read_offset)\n self.read(read_len)\n read_offset -=read_len\n \n return self.tell()\n \n def tell(self):\n if not self._seekable:\n raise io.UnsupportedOperation(\"underlying stream is not seekable\")\n filepos=self._orig_file_size -self._left -len(self._readbuffer)+self._offset\n return filepos\n \n \nclass _ZipWriteFile(io.BufferedIOBase):\n def __init__(self,zf,zinfo,zip64):\n self._zinfo=zinfo\n self._zip64=zip64\n self._zipfile=zf\n self._compressor=_get_compressor(zinfo.compress_type,\n zinfo._compresslevel)\n self._file_size=0\n self._compress_size=0\n self._crc=0\n \n @property\n def _fileobj(self):\n return self._zipfile.fp\n \n def writable(self):\n return True\n \n def write(self,data):\n if self.closed:\n raise ValueError('I/O operation on closed file.')\n nbytes=len(data)\n self._file_size +=nbytes\n self._crc=crc32(data,self._crc)\n if self._compressor:\n data=self._compressor.compress(data)\n self._compress_size +=len(data)\n self._fileobj.write(data)\n return nbytes\n \n def close(self):\n if self.closed:\n return\n super().close()\n \n if self._compressor:\n buf=self._compressor.flush()\n self._compress_size +=len(buf)\n self._fileobj.write(buf)\n self._zinfo.compress_size=self._compress_size\n else :\n self._zinfo.compress_size=self._file_size\n self._zinfo.CRC=self._crc\n self._zinfo.file_size=self._file_size\n \n \n if self._zinfo.flag_bits&0x08:\n \n fmt='<LQQ'if self._zip64 else '<LLL'\n self._fileobj.write(struct.pack(fmt,self._zinfo.CRC,\n self._zinfo.compress_size,self._zinfo.file_size))\n self._zipfile.start_dir=self._fileobj.tell()\n else :\n if not self._zip64:\n if self._file_size >ZIP64_LIMIT:\n raise RuntimeError('File size unexpectedly exceeded ZIP64 '\n 'limit')\n if self._compress_size >ZIP64_LIMIT:\n raise RuntimeError('Compressed size unexpectedly exceeded '\n 'ZIP64 limit')\n \n \n \n \n self._zipfile.start_dir=self._fileobj.tell()\n self._fileobj.seek(self._zinfo.header_offset)\n self._fileobj.write(self._zinfo.FileHeader(self._zip64))\n self._fileobj.seek(self._zipfile.start_dir)\n \n self._zipfile._writing=False\n \n \n self._zipfile.filelist.append(self._zinfo)\n self._zipfile.NameToInfo[self._zinfo.filename]=self._zinfo\n \nclass ZipFile:\n ''\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n \n \n fp=None\n _windows_illegal_name_trans_table=None\n \n def __init__(self,file,mode=\"r\",compression=ZIP_STORED,allowZip64=True ,\n compresslevel=None ):\n ''\n \n if mode not in ('r','w','x','a'):\n raise ValueError(\"ZipFile requires mode 'r', 'w', 'x', or 'a'\")\n \n _check_compression(compression)\n \n self._allowZip64=allowZip64\n self._didModify=False\n self.debug=0\n self.NameToInfo={}\n self.filelist=[]\n self.compression=compression\n self.compresslevel=compresslevel\n self.mode=mode\n self.pwd=None\n self._comment=b''\n \n \n if isinstance(file,os.PathLike):\n file=os.fspath(file)\n if isinstance(file,str):\n \n self._filePassed=0\n self.filename=file\n modeDict={'r':'rb','w':'w+b','x':'x+b','a':'r+b',\n 'r+b':'w+b','w+b':'wb','x+b':'xb'}\n filemode=modeDict[mode]\n while True :\n try :\n self.fp=io.open(file,filemode)\n except OSError:\n if filemode in modeDict:\n filemode=modeDict[filemode]\n continue\n raise\n break\n else :\n self._filePassed=1\n self.fp=file\n self.filename=getattr(file,'name',None )\n self._fileRefCnt=1\n self._lock=threading.RLock()\n self._seekable=True\n self._writing=False\n \n try :\n if mode =='r':\n self._RealGetContents()\n elif mode in ('w','x'):\n \n \n self._didModify=True\n try :\n self.start_dir=self.fp.tell()\n except (AttributeError,OSError):\n self.fp=_Tellable(self.fp)\n self.start_dir=0\n self._seekable=False\n else :\n \n try :\n self.fp.seek(self.start_dir)\n except (AttributeError,OSError):\n self._seekable=False\n elif mode =='a':\n try :\n \n self._RealGetContents()\n \n self.fp.seek(self.start_dir)\n except BadZipFile:\n \n self.fp.seek(0,2)\n \n \n \n self._didModify=True\n self.start_dir=self.fp.tell()\n else :\n raise ValueError(\"Mode must be 'r', 'w', 'x', or 'a'\")\n except :\n fp=self.fp\n self.fp=None\n self._fpclose(fp)\n raise\n \n def __enter__(self):\n return self\n \n def __exit__(self,type,value,traceback):\n self.close()\n \n def __repr__(self):\n result=['<%s.%s'%(self.__class__.__module__,\n self.__class__.__qualname__)]\n if self.fp is not None :\n if self._filePassed:\n result.append(' file=%r'%self.fp)\n elif self.filename is not None :\n result.append(' filename=%r'%self.filename)\n result.append(' mode=%r'%self.mode)\n else :\n result.append(' [closed]')\n result.append('>')\n return ''.join(result)\n \n def _RealGetContents(self):\n ''\n fp=self.fp\n try :\n endrec=_EndRecData(fp)\n except OSError:\n raise BadZipFile(\"File is not a zip file\")\n if not endrec:\n raise BadZipFile(\"File is not a zip file\")\n if self.debug >1:\n print(endrec)\n size_cd=endrec[_ECD_SIZE]\n offset_cd=endrec[_ECD_OFFSET]\n self._comment=endrec[_ECD_COMMENT]\n \n \n concat=endrec[_ECD_LOCATION]-size_cd -offset_cd\n if endrec[_ECD_SIGNATURE]==stringEndArchive64:\n \n concat -=(sizeEndCentDir64+sizeEndCentDir64Locator)\n \n if self.debug >2:\n inferred=concat+offset_cd\n print(\"given, inferred, offset\",offset_cd,inferred,concat)\n \n self.start_dir=offset_cd+concat\n fp.seek(self.start_dir,0)\n data=fp.read(size_cd)\n fp=io.BytesIO(data)\n total=0\n while total <size_cd:\n centdir=fp.read(sizeCentralDir)\n if len(centdir)!=sizeCentralDir:\n raise BadZipFile(\"Truncated central directory\")\n centdir=struct.unpack(structCentralDir,centdir)\n if centdir[_CD_SIGNATURE]!=stringCentralDir:\n raise BadZipFile(\"Bad magic number for central directory\")\n if self.debug >2:\n print(centdir)\n filename=fp.read(centdir[_CD_FILENAME_LENGTH])\n flags=centdir[5]\n if flags&0x800:\n \n filename=filename.decode('utf-8')\n else :\n \n filename=filename.decode('cp437')\n \n x=ZipInfo(filename)\n x.extra=fp.read(centdir[_CD_EXTRA_FIELD_LENGTH])\n x.comment=fp.read(centdir[_CD_COMMENT_LENGTH])\n x.header_offset=centdir[_CD_LOCAL_HEADER_OFFSET]\n (x.create_version,x.create_system,x.extract_version,x.reserved,\n x.flag_bits,x.compress_type,t,d,\n x.CRC,x.compress_size,x.file_size)=centdir[1:12]\n if x.extract_version >MAX_EXTRACT_VERSION:\n raise NotImplementedError(\"zip file version %.1f\"%\n (x.extract_version /10))\n x.volume,x.internal_attr,x.external_attr=centdir[15:18]\n \n x._raw_time=t\n x.date_time=((d >>9)+1980,(d >>5)&0xF,d&0x1F,\n t >>11,(t >>5)&0x3F,(t&0x1F)*2)\n \n x._decodeExtra()\n x.header_offset=x.header_offset+concat\n self.filelist.append(x)\n self.NameToInfo[x.filename]=x\n \n \n total=(total+sizeCentralDir+centdir[_CD_FILENAME_LENGTH]\n +centdir[_CD_EXTRA_FIELD_LENGTH]\n +centdir[_CD_COMMENT_LENGTH])\n \n if self.debug >2:\n print(\"total\",total)\n \n \n def namelist(self):\n ''\n return [data.filename for data in self.filelist]\n \n def infolist(self):\n ''\n \n return self.filelist\n \n def printdir(self,file=None ):\n ''\n print(\"%-46s %19s %12s\"%(\"File Name\",\"Modified \",\"Size\"),\n file=file)\n for zinfo in self.filelist:\n date=\"%d-%02d-%02d %02d:%02d:%02d\"%zinfo.date_time[:6]\n print(\"%-46s %s %12d\"%(zinfo.filename,date,zinfo.file_size),\n file=file)\n \n def testzip(self):\n ''\n chunk_size=2 **20\n for zinfo in self.filelist:\n try :\n \n \n with self.open(zinfo.filename,\"r\")as f:\n while f.read(chunk_size):\n pass\n except BadZipFile:\n return zinfo.filename\n \n def getinfo(self,name):\n ''\n info=self.NameToInfo.get(name)\n if info is None :\n raise KeyError(\n 'There is no item named %r in the archive'%name)\n \n return info\n \n def setpassword(self,pwd):\n ''\n if pwd and not isinstance(pwd,bytes):\n raise TypeError(\"pwd: expected bytes, got %s\"%type(pwd).__name__)\n if pwd:\n self.pwd=pwd\n else :\n self.pwd=None\n \n @property\n def comment(self):\n ''\n return self._comment\n \n @comment.setter\n def comment(self,comment):\n if not isinstance(comment,bytes):\n raise TypeError(\"comment: expected bytes, got %s\"%type(comment).__name__)\n \n if len(comment)>ZIP_MAX_COMMENT:\n import warnings\n warnings.warn('Archive comment is too long; truncating to %d bytes'\n %ZIP_MAX_COMMENT,stacklevel=2)\n comment=comment[:ZIP_MAX_COMMENT]\n self._comment=comment\n self._didModify=True\n \n def read(self,name,pwd=None ):\n ''\n with self.open(name,\"r\",pwd)as fp:\n return fp.read()\n \n def open(self,name,mode=\"r\",pwd=None ,*,force_zip64=False ):\n ''\n\n\n\n\n\n\n\n\n\n\n\n\n\n \n if mode not in {\"r\",\"w\"}:\n raise ValueError('open() requires mode \"r\" or \"w\"')\n if pwd and not isinstance(pwd,bytes):\n raise TypeError(\"pwd: expected bytes, got %s\"%type(pwd).__name__)\n if pwd and (mode ==\"w\"):\n raise ValueError(\"pwd is only supported for reading files\")\n if not self.fp:\n raise ValueError(\n \"Attempt to use ZIP archive that was already closed\")\n \n \n if isinstance(name,ZipInfo):\n \n zinfo=name\n elif mode =='w':\n zinfo=ZipInfo(name)\n zinfo.compress_type=self.compression\n zinfo._compresslevel=self.compresslevel\n else :\n \n zinfo=self.getinfo(name)\n \n if mode =='w':\n return self._open_to_write(zinfo,force_zip64=force_zip64)\n \n if self._writing:\n raise ValueError(\"Can't read from the ZIP file while there \"\n \"is an open writing handle on it. \"\n \"Close the writing handle before trying to read.\")\n \n \n self._fileRefCnt +=1\n zef_file=_SharedFile(self.fp,zinfo.header_offset,\n self._fpclose,self._lock,lambda :self._writing)\n try :\n \n fheader=zef_file.read(sizeFileHeader)\n if len(fheader)!=sizeFileHeader:\n raise BadZipFile(\"Truncated file header\")\n fheader=struct.unpack(structFileHeader,fheader)\n if fheader[_FH_SIGNATURE]!=stringFileHeader:\n raise BadZipFile(\"Bad magic number for file header\")\n \n fname=zef_file.read(fheader[_FH_FILENAME_LENGTH])\n if fheader[_FH_EXTRA_FIELD_LENGTH]:\n zef_file.read(fheader[_FH_EXTRA_FIELD_LENGTH])\n \n if zinfo.flag_bits&0x20:\n \n raise NotImplementedError(\"compressed patched data (flag bit 5)\")\n \n if zinfo.flag_bits&0x40:\n \n raise NotImplementedError(\"strong encryption (flag bit 6)\")\n \n if zinfo.flag_bits&0x800:\n \n fname_str=fname.decode(\"utf-8\")\n else :\n fname_str=fname.decode(\"cp437\")\n \n if fname_str !=zinfo.orig_filename:\n raise BadZipFile(\n 'File name in directory %r and header %r differ.'\n %(zinfo.orig_filename,fname))\n \n \n is_encrypted=zinfo.flag_bits&0x1\n zd=None\n if is_encrypted:\n if not pwd:\n pwd=self.pwd\n if not pwd:\n raise RuntimeError(\"File %r is encrypted, password \"\n \"required for extraction\"%name)\n \n zd=_ZipDecrypter(pwd)\n \n \n \n \n \n header=zef_file.read(12)\n h=zd(header[0:12])\n if zinfo.flag_bits&0x8:\n \n check_byte=(zinfo._raw_time >>8)&0xff\n else :\n \n check_byte=(zinfo.CRC >>24)&0xff\n if h[11]!=check_byte:\n raise RuntimeError(\"Bad password for file %r\"%name)\n \n return ZipExtFile(zef_file,mode,zinfo,zd,True )\n except :\n zef_file.close()\n raise\n \n def _open_to_write(self,zinfo,force_zip64=False ):\n if force_zip64 and not self._allowZip64:\n raise ValueError(\n \"force_zip64 is True, but allowZip64 was False when opening \"\n \"the ZIP file.\"\n )\n if self._writing:\n raise ValueError(\"Can't write to the ZIP file while there is \"\n \"another write handle open on it. \"\n \"Close the first handle before opening another.\")\n \n \n if not hasattr(zinfo,'file_size'):\n zinfo.file_size=0\n zinfo.compress_size=0\n zinfo.CRC=0\n \n zinfo.flag_bits=0x00\n if zinfo.compress_type ==ZIP_LZMA:\n \n zinfo.flag_bits |=0x02\n if not self._seekable:\n zinfo.flag_bits |=0x08\n \n if not zinfo.external_attr:\n zinfo.external_attr=0o600 <<16\n \n \n zip64=self._allowZip64 and\\\n (force_zip64 or zinfo.file_size *1.05 >ZIP64_LIMIT)\n \n if self._seekable:\n self.fp.seek(self.start_dir)\n zinfo.header_offset=self.fp.tell()\n \n self._writecheck(zinfo)\n self._didModify=True\n \n self.fp.write(zinfo.FileHeader(zip64))\n \n self._writing=True\n return _ZipWriteFile(self,zinfo,zip64)\n \n def extract(self,member,path=None ,pwd=None ):\n ''\n\n\n\n \n if path is None :\n path=os.getcwd()\n else :\n path=os.fspath(path)\n \n return self._extract_member(member,path,pwd)\n \n def extractall(self,path=None ,members=None ,pwd=None ):\n ''\n\n\n\n \n if members is None :\n members=self.namelist()\n \n if path is None :\n path=os.getcwd()\n else :\n path=os.fspath(path)\n \n for zipinfo in members:\n self._extract_member(zipinfo,path,pwd)\n \n @classmethod\n def _sanitize_windows_name(cls,arcname,pathsep):\n ''\n table=cls._windows_illegal_name_trans_table\n if not table:\n illegal=':<>|\"?*'\n table=str.maketrans(illegal,'_'*len(illegal))\n cls._windows_illegal_name_trans_table=table\n arcname=arcname.translate(table)\n \n arcname=(x.rstrip('.')for x in arcname.split(pathsep))\n \n arcname=pathsep.join(x for x in arcname if x)\n return arcname\n \n def _extract_member(self,member,targetpath,pwd):\n ''\n\n \n if not isinstance(member,ZipInfo):\n member=self.getinfo(member)\n \n \n \n arcname=member.filename.replace('/',os.path.sep)\n \n if os.path.altsep:\n arcname=arcname.replace(os.path.altsep,os.path.sep)\n \n \n arcname=os.path.splitdrive(arcname)[1]\n invalid_path_parts=('',os.path.curdir,os.path.pardir)\n arcname=os.path.sep.join(x for x in arcname.split(os.path.sep)\n if x not in invalid_path_parts)\n if os.path.sep =='\\\\':\n \n arcname=self._sanitize_windows_name(arcname,os.path.sep)\n \n targetpath=os.path.join(targetpath,arcname)\n targetpath=os.path.normpath(targetpath)\n \n \n upperdirs=os.path.dirname(targetpath)\n if upperdirs and not os.path.exists(upperdirs):\n os.makedirs(upperdirs)\n \n if member.is_dir():\n if not os.path.isdir(targetpath):\n os.mkdir(targetpath)\n return targetpath\n \n with self.open(member,pwd=pwd)as source,\\\n open(targetpath,\"wb\")as target:\n shutil.copyfileobj(source,target)\n \n return targetpath\n \n def _writecheck(self,zinfo):\n ''\n if zinfo.filename in self.NameToInfo:\n import warnings\n warnings.warn('Duplicate name: %r'%zinfo.filename,stacklevel=3)\n if self.mode not in ('w','x','a'):\n raise ValueError(\"write() requires mode 'w', 'x', or 'a'\")\n if not self.fp:\n raise ValueError(\n \"Attempt to write ZIP archive that was already closed\")\n _check_compression(zinfo.compress_type)\n if not self._allowZip64:\n requires_zip64=None\n if len(self.filelist)>=ZIP_FILECOUNT_LIMIT:\n requires_zip64=\"Files count\"\n elif zinfo.file_size >ZIP64_LIMIT:\n requires_zip64=\"Filesize\"\n elif zinfo.header_offset >ZIP64_LIMIT:\n requires_zip64=\"Zipfile size\"\n if requires_zip64:\n raise LargeZipFile(requires_zip64+\n \" would require ZIP64 extensions\")\n \n def write(self,filename,arcname=None ,\n compress_type=None ,compresslevel=None ):\n ''\n \n if not self.fp:\n raise ValueError(\n \"Attempt to write to ZIP archive that was already closed\")\n if self._writing:\n raise ValueError(\n \"Can't write to ZIP archive while an open writing handle exists\"\n )\n \n zinfo=ZipInfo.from_file(filename,arcname)\n \n if zinfo.is_dir():\n zinfo.compress_size=0\n zinfo.CRC=0\n else :\n if compress_type is not None :\n zinfo.compress_type=compress_type\n else :\n zinfo.compress_type=self.compression\n \n if compresslevel is not None :\n zinfo._compresslevel=compresslevel\n else :\n zinfo._compresslevel=self.compresslevel\n \n if zinfo.is_dir():\n with self._lock:\n if self._seekable:\n self.fp.seek(self.start_dir)\n zinfo.header_offset=self.fp.tell()\n if zinfo.compress_type ==ZIP_LZMA:\n \n zinfo.flag_bits |=0x02\n \n self._writecheck(zinfo)\n self._didModify=True\n \n self.filelist.append(zinfo)\n self.NameToInfo[zinfo.filename]=zinfo\n self.fp.write(zinfo.FileHeader(False ))\n self.start_dir=self.fp.tell()\n else :\n with open(filename,\"rb\")as src,self.open(zinfo,'w')as dest:\n shutil.copyfileobj(src,dest,1024 *8)\n \n def writestr(self,zinfo_or_arcname,data,\n compress_type=None ,compresslevel=None ):\n ''\n\n\n\n \n if isinstance(data,str):\n data=data.encode(\"utf-8\")\n if not isinstance(zinfo_or_arcname,ZipInfo):\n zinfo=ZipInfo(filename=zinfo_or_arcname,\n date_time=time.localtime(time.time())[:6])\n zinfo.compress_type=self.compression\n zinfo._compresslevel=self.compresslevel\n if zinfo.filename[-1]=='/':\n zinfo.external_attr=0o40775 <<16\n zinfo.external_attr |=0x10\n else :\n zinfo.external_attr=0o600 <<16\n else :\n zinfo=zinfo_or_arcname\n \n if not self.fp:\n raise ValueError(\n \"Attempt to write to ZIP archive that was already closed\")\n if self._writing:\n raise ValueError(\n \"Can't write to ZIP archive while an open writing handle exists.\"\n )\n \n if compress_type is not None :\n zinfo.compress_type=compress_type\n \n if compresslevel is not None :\n zinfo._compresslevel=compresslevel\n \n zinfo.file_size=len(data)\n with self._lock:\n with self.open(zinfo,mode='w')as dest:\n dest.write(data)\n \n def __del__(self):\n ''\n self.close()\n \n def close(self):\n ''\n \n if self.fp is None :\n return\n \n if self._writing:\n raise ValueError(\"Can't close the ZIP file while there is \"\n \"an open writing handle on it. \"\n \"Close the writing handle before closing the zip.\")\n \n try :\n if self.mode in ('w','x','a')and self._didModify:\n with self._lock:\n if self._seekable:\n self.fp.seek(self.start_dir)\n self._write_end_record()\n finally :\n fp=self.fp\n self.fp=None\n self._fpclose(fp)\n \n def _write_end_record(self):\n for zinfo in self.filelist:\n dt=zinfo.date_time\n dosdate=(dt[0]-1980)<<9 |dt[1]<<5 |dt[2]\n dostime=dt[3]<<11 |dt[4]<<5 |(dt[5]//2)\n extra=[]\n if zinfo.file_size >ZIP64_LIMIT\\\n or zinfo.compress_size >ZIP64_LIMIT:\n extra.append(zinfo.file_size)\n extra.append(zinfo.compress_size)\n file_size=0xffffffff\n compress_size=0xffffffff\n else :\n file_size=zinfo.file_size\n compress_size=zinfo.compress_size\n \n if zinfo.header_offset >ZIP64_LIMIT:\n extra.append(zinfo.header_offset)\n header_offset=0xffffffff\n else :\n header_offset=zinfo.header_offset\n \n extra_data=zinfo.extra\n min_version=0\n if extra:\n \n extra_data=struct.pack(\n '<HH'+'Q'*len(extra),\n 1,8 *len(extra),*extra)+extra_data\n \n min_version=ZIP64_VERSION\n \n if zinfo.compress_type ==ZIP_BZIP2:\n min_version=max(BZIP2_VERSION,min_version)\n elif zinfo.compress_type ==ZIP_LZMA:\n min_version=max(LZMA_VERSION,min_version)\n \n extract_version=max(min_version,zinfo.extract_version)\n create_version=max(min_version,zinfo.create_version)\n try :\n filename,flag_bits=zinfo._encodeFilenameFlags()\n centdir=struct.pack(structCentralDir,\n stringCentralDir,create_version,\n zinfo.create_system,extract_version,zinfo.reserved,\n flag_bits,zinfo.compress_type,dostime,dosdate,\n zinfo.CRC,compress_size,file_size,\n len(filename),len(extra_data),len(zinfo.comment),\n 0,zinfo.internal_attr,zinfo.external_attr,\n header_offset)\n except DeprecationWarning:\n print((structCentralDir,stringCentralDir,create_version,\n zinfo.create_system,extract_version,zinfo.reserved,\n zinfo.flag_bits,zinfo.compress_type,dostime,dosdate,\n zinfo.CRC,compress_size,file_size,\n len(zinfo.filename),len(extra_data),len(zinfo.comment),\n 0,zinfo.internal_attr,zinfo.external_attr,\n header_offset),file=sys.stderr)\n raise\n self.fp.write(centdir)\n self.fp.write(filename)\n self.fp.write(extra_data)\n self.fp.write(zinfo.comment)\n \n pos2=self.fp.tell()\n \n centDirCount=len(self.filelist)\n centDirSize=pos2 -self.start_dir\n centDirOffset=self.start_dir\n requires_zip64=None\n if centDirCount >ZIP_FILECOUNT_LIMIT:\n requires_zip64=\"Files count\"\n elif centDirOffset >ZIP64_LIMIT:\n requires_zip64=\"Central directory offset\"\n elif centDirSize >ZIP64_LIMIT:\n requires_zip64=\"Central directory size\"\n if requires_zip64:\n \n if not self._allowZip64:\n raise LargeZipFile(requires_zip64+\n \" would require ZIP64 extensions\")\n zip64endrec=struct.pack(\n structEndArchive64,stringEndArchive64,\n 44,45,45,0,0,centDirCount,centDirCount,\n centDirSize,centDirOffset)\n self.fp.write(zip64endrec)\n \n zip64locrec=struct.pack(\n structEndArchive64Locator,\n stringEndArchive64Locator,0,pos2,1)\n self.fp.write(zip64locrec)\n centDirCount=min(centDirCount,0xFFFF)\n centDirSize=min(centDirSize,0xFFFFFFFF)\n centDirOffset=min(centDirOffset,0xFFFFFFFF)\n \n endrec=struct.pack(structEndArchive,stringEndArchive,\n 0,0,centDirCount,centDirCount,\n centDirSize,centDirOffset,len(self._comment))\n self.fp.write(endrec)\n self.fp.write(self._comment)\n self.fp.flush()\n \n def _fpclose(self,fp):\n assert self._fileRefCnt >0\n self._fileRefCnt -=1\n if not self._fileRefCnt and not self._filePassed:\n fp.close()\n \n \nclass PyZipFile(ZipFile):\n ''\n \n def __init__(self,file,mode=\"r\",compression=ZIP_STORED,\n allowZip64=True ,optimize=-1):\n ZipFile.__init__(self,file,mode=mode,compression=compression,\n allowZip64=allowZip64)\n self._optimize=optimize\n \n def writepy(self,pathname,basename=\"\",filterfunc=None ):\n ''\n\n\n\n\n\n\n\n\n\n\n\n \n pathname=os.fspath(pathname)\n if filterfunc and not filterfunc(pathname):\n if self.debug:\n label='path'if os.path.isdir(pathname)else 'file'\n print('%s %r skipped by filterfunc'%(label,pathname))\n return\n dir,name=os.path.split(pathname)\n if os.path.isdir(pathname):\n initname=os.path.join(pathname,\"__init__.py\")\n if os.path.isfile(initname):\n \n if basename:\n basename=\"%s/%s\"%(basename,name)\n else :\n basename=name\n if self.debug:\n print(\"Adding package in\",pathname,\"as\",basename)\n fname,arcname=self._get_codename(initname[0:-3],basename)\n if self.debug:\n print(\"Adding\",arcname)\n self.write(fname,arcname)\n dirlist=sorted(os.listdir(pathname))\n dirlist.remove(\"__init__.py\")\n \n for filename in dirlist:\n path=os.path.join(pathname,filename)\n root,ext=os.path.splitext(filename)\n if os.path.isdir(path):\n if os.path.isfile(os.path.join(path,\"__init__.py\")):\n \n self.writepy(path,basename,\n filterfunc=filterfunc)\n elif ext ==\".py\":\n if filterfunc and not filterfunc(path):\n if self.debug:\n print('file %r skipped by filterfunc'%path)\n continue\n fname,arcname=self._get_codename(path[0:-3],\n basename)\n if self.debug:\n print(\"Adding\",arcname)\n self.write(fname,arcname)\n else :\n \n if self.debug:\n print(\"Adding files from directory\",pathname)\n for filename in sorted(os.listdir(pathname)):\n path=os.path.join(pathname,filename)\n root,ext=os.path.splitext(filename)\n if ext ==\".py\":\n if filterfunc and not filterfunc(path):\n if self.debug:\n print('file %r skipped by filterfunc'%path)\n continue\n fname,arcname=self._get_codename(path[0:-3],\n basename)\n if self.debug:\n print(\"Adding\",arcname)\n self.write(fname,arcname)\n else :\n if pathname[-3:]!=\".py\":\n raise RuntimeError(\n 'Files added with writepy() must end with \".py\"')\n fname,arcname=self._get_codename(pathname[0:-3],basename)\n if self.debug:\n print(\"Adding file\",arcname)\n self.write(fname,arcname)\n \n def _get_codename(self,pathname,basename):\n ''\n\n\n\n\n \n def _compile(file,optimize=-1):\n import py_compile\n if self.debug:\n print(\"Compiling\",file)\n try :\n py_compile.compile(file,doraise=True ,optimize=optimize)\n except py_compile.PyCompileError as err:\n print(err.msg)\n return False\n return True\n \n file_py=pathname+\".py\"\n file_pyc=pathname+\".pyc\"\n pycache_opt0=importlib.util.cache_from_source(file_py,optimization='')\n pycache_opt1=importlib.util.cache_from_source(file_py,optimization=1)\n pycache_opt2=importlib.util.cache_from_source(file_py,optimization=2)\n if self._optimize ==-1:\n \n if (os.path.isfile(file_pyc)and\n os.stat(file_pyc).st_mtime >=os.stat(file_py).st_mtime):\n \n arcname=fname=file_pyc\n elif (os.path.isfile(pycache_opt0)and\n os.stat(pycache_opt0).st_mtime >=os.stat(file_py).st_mtime):\n \n \n fname=pycache_opt0\n arcname=file_pyc\n elif (os.path.isfile(pycache_opt1)and\n os.stat(pycache_opt1).st_mtime >=os.stat(file_py).st_mtime):\n \n \n fname=pycache_opt1\n arcname=file_pyc\n elif (os.path.isfile(pycache_opt2)and\n os.stat(pycache_opt2).st_mtime >=os.stat(file_py).st_mtime):\n \n \n fname=pycache_opt2\n arcname=file_pyc\n else :\n \n if _compile(file_py):\n if sys.flags.optimize ==0:\n fname=pycache_opt0\n elif sys.flags.optimize ==1:\n fname=pycache_opt1\n else :\n fname=pycache_opt2\n arcname=file_pyc\n else :\n fname=arcname=file_py\n else :\n \n if self._optimize ==0:\n fname=pycache_opt0\n arcname=file_pyc\n else :\n arcname=file_pyc\n if self._optimize ==1:\n fname=pycache_opt1\n elif self._optimize ==2:\n fname=pycache_opt2\n else :\n msg=\"invalid value for 'optimize': {!r}\".format(self._optimize)\n raise ValueError(msg)\n if not (os.path.isfile(fname)and\n os.stat(fname).st_mtime >=os.stat(file_py).st_mtime):\n if not _compile(file_py,optimize=self._optimize):\n fname=arcname=file_py\n archivename=os.path.split(arcname)[1]\n if basename:\n archivename=\"%s/%s\"%(basename,archivename)\n return (fname,archivename)\n \n \ndef main(args=None ):\n import argparse\n \n description='A simple command-line interface for zipfile module.'\n parser=argparse.ArgumentParser(description=description)\n group=parser.add_mutually_exclusive_group(required=True )\n group.add_argument('-l','--list',metavar='<zipfile>',\n help='Show listing of a zipfile')\n group.add_argument('-e','--extract',nargs=2,\n metavar=('<zipfile>','<output_dir>'),\n help='Extract zipfile into target dir')\n group.add_argument('-c','--create',nargs='+',\n metavar=('<name>','<file>'),\n help='Create zipfile from sources')\n group.add_argument('-t','--test',metavar='<zipfile>',\n help='Test if a zipfile is valid')\n args=parser.parse_args(args)\n \n if args.test is not None :\n src=args.test\n with ZipFile(src,'r')as zf:\n badfile=zf.testzip()\n if badfile:\n print(\"The following enclosed file is corrupted: {!r}\".format(badfile))\n print(\"Done testing\")\n \n elif args.list is not None :\n src=args.list\n with ZipFile(src,'r')as zf:\n zf.printdir()\n \n elif args.extract is not None :\n src,curdir=args.extract\n with ZipFile(src,'r')as zf:\n zf.extractall(curdir)\n \n elif args.create is not None :\n zip_name=args.create.pop(0)\n files=args.create\n \n def addToZip(zf,path,zippath):\n if os.path.isfile(path):\n zf.write(path,zippath,ZIP_DEFLATED)\n elif os.path.isdir(path):\n if zippath:\n zf.write(path,zippath)\n for nm in sorted(os.listdir(path)):\n addToZip(zf,\n os.path.join(path,nm),os.path.join(zippath,nm))\n \n \n with ZipFile(zip_name,'w')as zf:\n for path in files:\n zippath=os.path.basename(path)\n if not zippath:\n zippath=os.path.basename(os.path.dirname(path))\n if zippath in ('',os.curdir,os.pardir):\n zippath=''\n addToZip(zf,path,zippath)\n \nif __name__ ==\"__main__\":\n main()\n", ["argparse", "binascii", "bz2", "importlib.util", "io", "lzma", "os", "py_compile", "shutil", "stat", "struct", "sys", "threading", "time", "warnings", "zlib"]], "locale": [".py", "''\n\n\n\n\n\n\n\n\n\n\n\nimport sys\nimport encodings\nimport encodings.aliases\nimport re\nimport _collections_abc\nfrom builtins import str as _builtin_str\nimport functools\n\n\n\n\n\n\n\n__all__=[\"getlocale\",\"getdefaultlocale\",\"getpreferredencoding\",\"Error\",\n\"setlocale\",\"resetlocale\",\"localeconv\",\"strcoll\",\"strxfrm\",\n\"str\",\"atof\",\"atoi\",\"format\",\"format_string\",\"currency\",\n\"normalize\",\"LC_CTYPE\",\"LC_COLLATE\",\"LC_TIME\",\"LC_MONETARY\",\n\"LC_NUMERIC\",\"LC_ALL\",\"CHAR_MAX\"]\n\ndef _strcoll(a,b):\n ''\n\n \n return (a >b)-(a <b)\n \ndef _strxfrm(s):\n ''\n\n \n return s\n \ntry :\n\n from _locale import *\n \nexcept ImportError:\n\n\n\n CHAR_MAX=127\n LC_ALL=6\n LC_COLLATE=3\n LC_CTYPE=0\n LC_MESSAGES=5\n LC_MONETARY=4\n LC_NUMERIC=1\n LC_TIME=2\n Error=ValueError\n \n def localeconv():\n ''\n\n \n \n return {'grouping':[127],\n 'currency_symbol':'',\n 'n_sign_posn':127,\n 'p_cs_precedes':127,\n 'n_cs_precedes':127,\n 'mon_grouping':[],\n 'n_sep_by_space':127,\n 'decimal_point':'.',\n 'negative_sign':'',\n 'positive_sign':'',\n 'p_sep_by_space':127,\n 'int_curr_symbol':'',\n 'p_sign_posn':127,\n 'thousands_sep':'',\n 'mon_thousands_sep':'',\n 'frac_digits':127,\n 'mon_decimal_point':'',\n 'int_frac_digits':127}\n \n def setlocale(category,value=None ):\n ''\n\n \n if value not in (None ,'','C'):\n raise Error('_locale emulation only supports \"C\" locale')\n return 'C'\n \n \nif 'strxfrm'not in globals():\n strxfrm=_strxfrm\nif 'strcoll'not in globals():\n strcoll=_strcoll\n \n \n_localeconv=localeconv\n\n\n\n_override_localeconv={}\n\n@functools.wraps(_localeconv)\ndef localeconv():\n d=_localeconv()\n if _override_localeconv:\n d.update(_override_localeconv)\n return d\n \n \n \n \n \n \n \n \ndef _grouping_intervals(grouping):\n last_interval=None\n for interval in grouping:\n \n if interval ==CHAR_MAX:\n return\n \n if interval ==0:\n if last_interval is None :\n raise ValueError(\"invalid grouping\")\n while True :\n yield last_interval\n yield interval\n last_interval=interval\n \n \ndef _group(s,monetary=False ):\n conv=localeconv()\n thousands_sep=conv[monetary and 'mon_thousands_sep'or 'thousands_sep']\n grouping=conv[monetary and 'mon_grouping'or 'grouping']\n if not grouping:\n return (s,0)\n if s[-1]==' ':\n stripped=s.rstrip()\n right_spaces=s[len(stripped):]\n s=stripped\n else :\n right_spaces=''\n left_spaces=''\n groups=[]\n for interval in _grouping_intervals(grouping):\n if not s or s[-1]not in \"0123456789\":\n \n left_spaces=s\n s=''\n break\n groups.append(s[-interval:])\n s=s[:-interval]\n if s:\n groups.append(s)\n groups.reverse()\n return (\n left_spaces+thousands_sep.join(groups)+right_spaces,\n len(thousands_sep)*(len(groups)-1)\n )\n \n \ndef _strip_padding(s,amount):\n lpos=0\n while amount and s[lpos]==' ':\n lpos +=1\n amount -=1\n rpos=len(s)-1\n while amount and s[rpos]==' ':\n rpos -=1\n amount -=1\n return s[lpos:rpos+1]\n \n_percent_re=re.compile(r'%(?:\\((?P<key>.*?)\\))?'\nr'(?P<modifiers>[-#0-9 +*.hlL]*?)[eEfFgGdiouxXcrs%]')\n\ndef _format(percent,value,grouping=False ,monetary=False ,*additional):\n if additional:\n formatted=percent %((value,)+additional)\n else :\n formatted=percent %value\n \n if percent[-1]in 'eEfFgG':\n seps=0\n parts=formatted.split('.')\n if grouping:\n parts[0],seps=_group(parts[0],monetary=monetary)\n decimal_point=localeconv()[monetary and 'mon_decimal_point'\n or 'decimal_point']\n formatted=decimal_point.join(parts)\n if seps:\n formatted=_strip_padding(formatted,seps)\n elif percent[-1]in 'diu':\n seps=0\n if grouping:\n formatted,seps=_group(formatted,monetary=monetary)\n if seps:\n formatted=_strip_padding(formatted,seps)\n return formatted\n \ndef format_string(f,val,grouping=False ,monetary=False ):\n ''\n\n\n\n\n \n percents=list(_percent_re.finditer(f))\n new_f=_percent_re.sub('%s',f)\n \n if isinstance(val,_collections_abc.Mapping):\n new_val=[]\n for perc in percents:\n if perc.group()[-1]=='%':\n new_val.append('%')\n else :\n new_val.append(_format(perc.group(),val,grouping,monetary))\n else :\n if not isinstance(val,tuple):\n val=(val,)\n new_val=[]\n i=0\n for perc in percents:\n if perc.group()[-1]=='%':\n new_val.append('%')\n else :\n starcount=perc.group('modifiers').count('*')\n new_val.append(_format(perc.group(),\n val[i],\n grouping,\n monetary,\n *val[i+1:i+1+starcount]))\n i +=(1+starcount)\n val=tuple(new_val)\n \n return new_f %val\n \ndef format(percent,value,grouping=False ,monetary=False ,*additional):\n ''\n import warnings\n warnings.warn(\n \"This method will be removed in a future version of Python. \"\n \"Use 'locale.format_string()' instead.\",\n DeprecationWarning,stacklevel=2\n )\n \n match=_percent_re.match(percent)\n if not match or len(match.group())!=len(percent):\n raise ValueError((\"format() must be given exactly one %%char \"\n \"format specifier, %s not valid\")%repr(percent))\n return _format(percent,value,grouping,monetary,*additional)\n \ndef currency(val,symbol=True ,grouping=False ,international=False ):\n ''\n \n conv=localeconv()\n \n \n digits=conv[international and 'int_frac_digits'or 'frac_digits']\n if digits ==127:\n raise ValueError(\"Currency formatting is not possible using \"\n \"the 'C' locale.\")\n \n s=_format('%%.%if'%digits,abs(val),grouping,monetary=True )\n \n s='<'+s+'>'\n \n if symbol:\n smb=conv[international and 'int_curr_symbol'or 'currency_symbol']\n precedes=conv[val <0 and 'n_cs_precedes'or 'p_cs_precedes']\n separated=conv[val <0 and 'n_sep_by_space'or 'p_sep_by_space']\n \n if precedes:\n s=smb+(separated and ' 'or '')+s\n else :\n s=s+(separated and ' 'or '')+smb\n \n sign_pos=conv[val <0 and 'n_sign_posn'or 'p_sign_posn']\n sign=conv[val <0 and 'negative_sign'or 'positive_sign']\n \n if sign_pos ==0:\n s='('+s+')'\n elif sign_pos ==1:\n s=sign+s\n elif sign_pos ==2:\n s=s+sign\n elif sign_pos ==3:\n s=s.replace('<',sign)\n elif sign_pos ==4:\n s=s.replace('>',sign)\n else :\n \n \n s=sign+s\n \n return s.replace('<','').replace('>','')\n \ndef str(val):\n ''\n return _format(\"%.12g\",val)\n \ndef delocalize(string):\n ''\n \n conv=localeconv()\n \n \n ts=conv['thousands_sep']\n if ts:\n string=string.replace(ts,'')\n \n \n dd=conv['decimal_point']\n if dd:\n string=string.replace(dd,'.')\n return string\n \ndef atof(string,func=float):\n ''\n return func(delocalize(string))\n \ndef atoi(string):\n ''\n return int(delocalize(string))\n \ndef _test():\n setlocale(LC_ALL,\"\")\n \n s1=format_string(\"%d\",123456789,1)\n print(s1,\"is\",atoi(s1))\n \n s1=str(3.14)\n print(s1,\"is\",atof(s1))\n \n \n \n \n \n \n \n \n_setlocale=setlocale\n\ndef _replace_encoding(code,encoding):\n if '.'in code:\n langname=code[:code.index('.')]\n else :\n langname=code\n \n norm_encoding=encodings.normalize_encoding(encoding)\n \n norm_encoding=encodings.aliases.aliases.get(norm_encoding.lower(),\n norm_encoding)\n \n encoding=norm_encoding\n norm_encoding=norm_encoding.lower()\n if norm_encoding in locale_encoding_alias:\n encoding=locale_encoding_alias[norm_encoding]\n else :\n norm_encoding=norm_encoding.replace('_','')\n norm_encoding=norm_encoding.replace('-','')\n if norm_encoding in locale_encoding_alias:\n encoding=locale_encoding_alias[norm_encoding]\n \n return langname+'.'+encoding\n \ndef _append_modifier(code,modifier):\n if modifier =='euro':\n if '.'not in code:\n return code+'.ISO8859-15'\n _,_,encoding=code.partition('.')\n if encoding in ('ISO8859-15','UTF-8'):\n return code\n if encoding =='ISO8859-1':\n return _replace_encoding(code,'ISO8859-15')\n return code+'@'+modifier\n \ndef normalize(localename):\n\n ''\n\n\n\n\n\n\n\n\n\n\n\n\n \n \n code=localename.lower()\n if ':'in code:\n \n code=code.replace(':','.')\n if '@'in code:\n code,modifier=code.split('@',1)\n else :\n modifier=''\n if '.'in code:\n langname,encoding=code.split('.')[:2]\n else :\n langname=code\n encoding=''\n \n \n lang_enc=langname\n if encoding:\n norm_encoding=encoding.replace('-','')\n norm_encoding=norm_encoding.replace('_','')\n lang_enc +='.'+norm_encoding\n lookup_name=lang_enc\n if modifier:\n lookup_name +='@'+modifier\n code=locale_alias.get(lookup_name,None )\n if code is not None :\n return code\n \n \n if modifier:\n \n code=locale_alias.get(lang_enc,None )\n if code is not None :\n \n if '@'not in code:\n return _append_modifier(code,modifier)\n if code.split('@',1)[1].lower()==modifier:\n return code\n \n \n if encoding:\n \n lookup_name=langname\n if modifier:\n lookup_name +='@'+modifier\n code=locale_alias.get(lookup_name,None )\n if code is not None :\n \n if '@'not in code:\n return _replace_encoding(code,encoding)\n code,modifier=code.split('@',1)\n return _replace_encoding(code,encoding)+'@'+modifier\n \n if modifier:\n \n code=locale_alias.get(langname,None )\n if code is not None :\n \n if '@'not in code:\n code=_replace_encoding(code,encoding)\n return _append_modifier(code,modifier)\n code,defmod=code.split('@',1)\n if defmod.lower()==modifier:\n return _replace_encoding(code,encoding)+'@'+defmod\n \n return localename\n \ndef _parse_localename(localename):\n\n ''\n\n\n\n\n\n\n\n\n\n\n \n code=normalize(localename)\n if '@'in code:\n \n code,modifier=code.split('@',1)\n if modifier =='euro'and '.'not in code:\n \n \n \n return code,'iso-8859-15'\n \n if '.'in code:\n return tuple(code.split('.')[:2])\n elif code =='C':\n return None ,None\n raise ValueError('unknown locale: %s'%localename)\n \ndef _build_localename(localetuple):\n\n ''\n\n\n\n\n \n try :\n language,encoding=localetuple\n \n if language is None :\n language='C'\n if encoding is None :\n return language\n else :\n return language+'.'+encoding\n except (TypeError,ValueError):\n raise TypeError('Locale must be None, a string, or an iterable of '\n 'two strings -- language code, encoding.')from None\n \ndef getdefaultlocale(envvars=('LC_ALL','LC_CTYPE','LANG','LANGUAGE')):\n\n ''\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n \n \n try :\n \n import _locale\n code,encoding=_locale._getdefaultlocale()\n except (ImportError,AttributeError):\n pass\n else :\n \n if sys.platform ==\"win32\"and code and code[:2]==\"0x\":\n \n code=windows_locale.get(int(code,0))\n \n \n return code,encoding\n \n \n import os\n lookup=os.environ.get\n for variable in envvars:\n localename=lookup(variable,None )\n if localename:\n if variable =='LANGUAGE':\n localename=localename.split(':')[0]\n break\n else :\n localename='C'\n return _parse_localename(localename)\n \n \ndef getlocale(category=LC_CTYPE):\n\n ''\n\n\n\n\n\n\n\n\n\n \n localename=_setlocale(category)\n if category ==LC_ALL and ';'in localename:\n raise TypeError('category LC_ALL is not supported')\n return _parse_localename(localename)\n \ndef setlocale(category,locale=None ):\n\n ''\n\n\n\n\n\n\n\n\n \n if locale and not isinstance(locale,_builtin_str):\n \n locale=normalize(_build_localename(locale))\n return _setlocale(category,locale)\n \ndef resetlocale(category=LC_ALL):\n\n ''\n\n\n\n\n \n _setlocale(category,_build_localename(getdefaultlocale()))\n \nif sys.platform.startswith(\"win\"):\n\n def getpreferredencoding(do_setlocale=True ):\n ''\n if sys.flags.utf8_mode:\n return 'UTF-8'\n import _bootlocale\n return _bootlocale.getpreferredencoding(False )\nelse :\n\n try :\n CODESET\n except NameError:\n if hasattr(sys,'getandroidapilevel'):\n \n \n def getpreferredencoding(do_setlocale=True ):\n return 'UTF-8'\n else :\n \n def getpreferredencoding(do_setlocale=True ):\n ''\n \n if sys.flags.utf8_mode:\n return 'UTF-8'\n res=getdefaultlocale()[1]\n if res is None :\n \n res='ascii'\n return res\n else :\n def getpreferredencoding(do_setlocale=True ):\n ''\n \n if sys.flags.utf8_mode:\n return 'UTF-8'\n import _bootlocale\n if do_setlocale:\n oldloc=setlocale(LC_CTYPE)\n try :\n setlocale(LC_CTYPE,\"\")\n except Error:\n pass\n result=_bootlocale.getpreferredencoding(False )\n if do_setlocale:\n setlocale(LC_CTYPE,oldloc)\n return result\n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \nlocale_encoding_alias={\n\n\n'437':'C',\n'c':'C',\n'en':'ISO8859-1',\n'jis':'JIS7',\n'jis7':'JIS7',\n'ajec':'eucJP',\n'koi8c':'KOI8-C',\n'microsoftcp1251':'CP1251',\n'microsoftcp1255':'CP1255',\n'microsoftcp1256':'CP1256',\n'88591':'ISO8859-1',\n'88592':'ISO8859-2',\n'88595':'ISO8859-5',\n'885915':'ISO8859-15',\n\n\n'ascii':'ISO8859-1',\n'latin_1':'ISO8859-1',\n'iso8859_1':'ISO8859-1',\n'iso8859_10':'ISO8859-10',\n'iso8859_11':'ISO8859-11',\n'iso8859_13':'ISO8859-13',\n'iso8859_14':'ISO8859-14',\n'iso8859_15':'ISO8859-15',\n'iso8859_16':'ISO8859-16',\n'iso8859_2':'ISO8859-2',\n'iso8859_3':'ISO8859-3',\n'iso8859_4':'ISO8859-4',\n'iso8859_5':'ISO8859-5',\n'iso8859_6':'ISO8859-6',\n'iso8859_7':'ISO8859-7',\n'iso8859_8':'ISO8859-8',\n'iso8859_9':'ISO8859-9',\n'iso2022_jp':'JIS7',\n'shift_jis':'SJIS',\n'tactis':'TACTIS',\n'euc_jp':'eucJP',\n'euc_kr':'eucKR',\n'utf_8':'UTF-8',\n'koi8_r':'KOI8-R',\n'koi8_t':'KOI8-T',\n'koi8_u':'KOI8-U',\n'kz1048':'RK1048',\n'cp1251':'CP1251',\n'cp1255':'CP1255',\n'cp1256':'CP1256',\n\n\n\n}\n\nfor k,v in sorted(locale_encoding_alias.items()):\n k=k.replace('_','')\n locale_encoding_alias.setdefault(k,v)\n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \nlocale_alias={\n'a3':'az_AZ.KOI8-C',\n'a3_az':'az_AZ.KOI8-C',\n'a3_az.koic':'az_AZ.KOI8-C',\n'aa_dj':'aa_DJ.ISO8859-1',\n'aa_er':'aa_ER.UTF-8',\n'aa_et':'aa_ET.UTF-8',\n'af':'af_ZA.ISO8859-1',\n'af_za':'af_ZA.ISO8859-1',\n'agr_pe':'agr_PE.UTF-8',\n'ak_gh':'ak_GH.UTF-8',\n'am':'am_ET.UTF-8',\n'am_et':'am_ET.UTF-8',\n'american':'en_US.ISO8859-1',\n'an_es':'an_ES.ISO8859-15',\n'anp_in':'anp_IN.UTF-8',\n'ar':'ar_AA.ISO8859-6',\n'ar_aa':'ar_AA.ISO8859-6',\n'ar_ae':'ar_AE.ISO8859-6',\n'ar_bh':'ar_BH.ISO8859-6',\n'ar_dz':'ar_DZ.ISO8859-6',\n'ar_eg':'ar_EG.ISO8859-6',\n'ar_in':'ar_IN.UTF-8',\n'ar_iq':'ar_IQ.ISO8859-6',\n'ar_jo':'ar_JO.ISO8859-6',\n'ar_kw':'ar_KW.ISO8859-6',\n'ar_lb':'ar_LB.ISO8859-6',\n'ar_ly':'ar_LY.ISO8859-6',\n'ar_ma':'ar_MA.ISO8859-6',\n'ar_om':'ar_OM.ISO8859-6',\n'ar_qa':'ar_QA.ISO8859-6',\n'ar_sa':'ar_SA.ISO8859-6',\n'ar_sd':'ar_SD.ISO8859-6',\n'ar_ss':'ar_SS.UTF-8',\n'ar_sy':'ar_SY.ISO8859-6',\n'ar_tn':'ar_TN.ISO8859-6',\n'ar_ye':'ar_YE.ISO8859-6',\n'arabic':'ar_AA.ISO8859-6',\n'as':'as_IN.UTF-8',\n'as_in':'as_IN.UTF-8',\n'ast_es':'ast_ES.ISO8859-15',\n'ayc_pe':'ayc_PE.UTF-8',\n'az':'az_AZ.ISO8859-9E',\n'az_az':'az_AZ.ISO8859-9E',\n'az_az.iso88599e':'az_AZ.ISO8859-9E',\n'az_ir':'az_IR.UTF-8',\n'be':'be_BY.CP1251',\n'be@latin':'be_BY.UTF-8@latin',\n'be_bg.utf8':'bg_BG.UTF-8',\n'be_by':'be_BY.CP1251',\n'be_by@latin':'be_BY.UTF-8@latin',\n'bem_zm':'bem_ZM.UTF-8',\n'ber_dz':'ber_DZ.UTF-8',\n'ber_ma':'ber_MA.UTF-8',\n'bg':'bg_BG.CP1251',\n'bg_bg':'bg_BG.CP1251',\n'bhb_in.utf8':'bhb_IN.UTF-8',\n'bho_in':'bho_IN.UTF-8',\n'bho_np':'bho_NP.UTF-8',\n'bi_vu':'bi_VU.UTF-8',\n'bn_bd':'bn_BD.UTF-8',\n'bn_in':'bn_IN.UTF-8',\n'bo_cn':'bo_CN.UTF-8',\n'bo_in':'bo_IN.UTF-8',\n'bokmal':'nb_NO.ISO8859-1',\n'bokm\\xe5l':'nb_NO.ISO8859-1',\n'br':'br_FR.ISO8859-1',\n'br_fr':'br_FR.ISO8859-1',\n'brx_in':'brx_IN.UTF-8',\n'bs':'bs_BA.ISO8859-2',\n'bs_ba':'bs_BA.ISO8859-2',\n'bulgarian':'bg_BG.CP1251',\n'byn_er':'byn_ER.UTF-8',\n'c':'C',\n'c-french':'fr_CA.ISO8859-1',\n'c.ascii':'C',\n'c.en':'C',\n'c.iso88591':'en_US.ISO8859-1',\n'c.utf8':'en_US.UTF-8',\n'c_c':'C',\n'c_c.c':'C',\n'ca':'ca_ES.ISO8859-1',\n'ca_ad':'ca_AD.ISO8859-1',\n'ca_es':'ca_ES.ISO8859-1',\n'ca_es@valencia':'ca_ES.UTF-8@valencia',\n'ca_fr':'ca_FR.ISO8859-1',\n'ca_it':'ca_IT.ISO8859-1',\n'catalan':'ca_ES.ISO8859-1',\n'ce_ru':'ce_RU.UTF-8',\n'cextend':'en_US.ISO8859-1',\n'chinese-s':'zh_CN.eucCN',\n'chinese-t':'zh_TW.eucTW',\n'chr_us':'chr_US.UTF-8',\n'ckb_iq':'ckb_IQ.UTF-8',\n'cmn_tw':'cmn_TW.UTF-8',\n'crh_ua':'crh_UA.UTF-8',\n'croatian':'hr_HR.ISO8859-2',\n'cs':'cs_CZ.ISO8859-2',\n'cs_cs':'cs_CZ.ISO8859-2',\n'cs_cz':'cs_CZ.ISO8859-2',\n'csb_pl':'csb_PL.UTF-8',\n'cv_ru':'cv_RU.UTF-8',\n'cy':'cy_GB.ISO8859-1',\n'cy_gb':'cy_GB.ISO8859-1',\n'cz':'cs_CZ.ISO8859-2',\n'cz_cz':'cs_CZ.ISO8859-2',\n'czech':'cs_CZ.ISO8859-2',\n'da':'da_DK.ISO8859-1',\n'da_dk':'da_DK.ISO8859-1',\n'danish':'da_DK.ISO8859-1',\n'dansk':'da_DK.ISO8859-1',\n'de':'de_DE.ISO8859-1',\n'de_at':'de_AT.ISO8859-1',\n'de_be':'de_BE.ISO8859-1',\n'de_ch':'de_CH.ISO8859-1',\n'de_de':'de_DE.ISO8859-1',\n'de_it':'de_IT.ISO8859-1',\n'de_li.utf8':'de_LI.UTF-8',\n'de_lu':'de_LU.ISO8859-1',\n'deutsch':'de_DE.ISO8859-1',\n'doi_in':'doi_IN.UTF-8',\n'dutch':'nl_NL.ISO8859-1',\n'dutch.iso88591':'nl_BE.ISO8859-1',\n'dv_mv':'dv_MV.UTF-8',\n'dz_bt':'dz_BT.UTF-8',\n'ee':'ee_EE.ISO8859-4',\n'ee_ee':'ee_EE.ISO8859-4',\n'eesti':'et_EE.ISO8859-1',\n'el':'el_GR.ISO8859-7',\n'el_cy':'el_CY.ISO8859-7',\n'el_gr':'el_GR.ISO8859-7',\n'el_gr@euro':'el_GR.ISO8859-15',\n'en':'en_US.ISO8859-1',\n'en_ag':'en_AG.UTF-8',\n'en_au':'en_AU.ISO8859-1',\n'en_be':'en_BE.ISO8859-1',\n'en_bw':'en_BW.ISO8859-1',\n'en_ca':'en_CA.ISO8859-1',\n'en_dk':'en_DK.ISO8859-1',\n'en_dl.utf8':'en_DL.UTF-8',\n'en_gb':'en_GB.ISO8859-1',\n'en_hk':'en_HK.ISO8859-1',\n'en_ie':'en_IE.ISO8859-1',\n'en_il':'en_IL.UTF-8',\n'en_in':'en_IN.ISO8859-1',\n'en_ng':'en_NG.UTF-8',\n'en_nz':'en_NZ.ISO8859-1',\n'en_ph':'en_PH.ISO8859-1',\n'en_sc.utf8':'en_SC.UTF-8',\n'en_sg':'en_SG.ISO8859-1',\n'en_uk':'en_GB.ISO8859-1',\n'en_us':'en_US.ISO8859-1',\n'en_us@euro@euro':'en_US.ISO8859-15',\n'en_za':'en_ZA.ISO8859-1',\n'en_zm':'en_ZM.UTF-8',\n'en_zw':'en_ZW.ISO8859-1',\n'en_zw.utf8':'en_ZS.UTF-8',\n'eng_gb':'en_GB.ISO8859-1',\n'english':'en_EN.ISO8859-1',\n'english.iso88591':'en_US.ISO8859-1',\n'english_uk':'en_GB.ISO8859-1',\n'english_united-states':'en_US.ISO8859-1',\n'english_united-states.437':'C',\n'english_us':'en_US.ISO8859-1',\n'eo':'eo_XX.ISO8859-3',\n'eo.utf8':'eo.UTF-8',\n'eo_eo':'eo_EO.ISO8859-3',\n'eo_us.utf8':'eo_US.UTF-8',\n'eo_xx':'eo_XX.ISO8859-3',\n'es':'es_ES.ISO8859-1',\n'es_ar':'es_AR.ISO8859-1',\n'es_bo':'es_BO.ISO8859-1',\n'es_cl':'es_CL.ISO8859-1',\n'es_co':'es_CO.ISO8859-1',\n'es_cr':'es_CR.ISO8859-1',\n'es_cu':'es_CU.UTF-8',\n'es_do':'es_DO.ISO8859-1',\n'es_ec':'es_EC.ISO8859-1',\n'es_es':'es_ES.ISO8859-1',\n'es_gt':'es_GT.ISO8859-1',\n'es_hn':'es_HN.ISO8859-1',\n'es_mx':'es_MX.ISO8859-1',\n'es_ni':'es_NI.ISO8859-1',\n'es_pa':'es_PA.ISO8859-1',\n'es_pe':'es_PE.ISO8859-1',\n'es_pr':'es_PR.ISO8859-1',\n'es_py':'es_PY.ISO8859-1',\n'es_sv':'es_SV.ISO8859-1',\n'es_us':'es_US.ISO8859-1',\n'es_uy':'es_UY.ISO8859-1',\n'es_ve':'es_VE.ISO8859-1',\n'estonian':'et_EE.ISO8859-1',\n'et':'et_EE.ISO8859-15',\n'et_ee':'et_EE.ISO8859-15',\n'eu':'eu_ES.ISO8859-1',\n'eu_es':'eu_ES.ISO8859-1',\n'eu_fr':'eu_FR.ISO8859-1',\n'fa':'fa_IR.UTF-8',\n'fa_ir':'fa_IR.UTF-8',\n'fa_ir.isiri3342':'fa_IR.ISIRI-3342',\n'ff_sn':'ff_SN.UTF-8',\n'fi':'fi_FI.ISO8859-15',\n'fi_fi':'fi_FI.ISO8859-15',\n'fil_ph':'fil_PH.UTF-8',\n'finnish':'fi_FI.ISO8859-1',\n'fo':'fo_FO.ISO8859-1',\n'fo_fo':'fo_FO.ISO8859-1',\n'fr':'fr_FR.ISO8859-1',\n'fr_be':'fr_BE.ISO8859-1',\n'fr_ca':'fr_CA.ISO8859-1',\n'fr_ch':'fr_CH.ISO8859-1',\n'fr_fr':'fr_FR.ISO8859-1',\n'fr_lu':'fr_LU.ISO8859-1',\n'fran\\xe7ais':'fr_FR.ISO8859-1',\n'fre_fr':'fr_FR.ISO8859-1',\n'french':'fr_FR.ISO8859-1',\n'french.iso88591':'fr_CH.ISO8859-1',\n'french_france':'fr_FR.ISO8859-1',\n'fur_it':'fur_IT.UTF-8',\n'fy_de':'fy_DE.UTF-8',\n'fy_nl':'fy_NL.UTF-8',\n'ga':'ga_IE.ISO8859-1',\n'ga_ie':'ga_IE.ISO8859-1',\n'galego':'gl_ES.ISO8859-1',\n'galician':'gl_ES.ISO8859-1',\n'gd':'gd_GB.ISO8859-1',\n'gd_gb':'gd_GB.ISO8859-1',\n'ger_de':'de_DE.ISO8859-1',\n'german':'de_DE.ISO8859-1',\n'german.iso88591':'de_CH.ISO8859-1',\n'german_germany':'de_DE.ISO8859-1',\n'gez_er':'gez_ER.UTF-8',\n'gez_et':'gez_ET.UTF-8',\n'gl':'gl_ES.ISO8859-1',\n'gl_es':'gl_ES.ISO8859-1',\n'greek':'el_GR.ISO8859-7',\n'gu_in':'gu_IN.UTF-8',\n'gv':'gv_GB.ISO8859-1',\n'gv_gb':'gv_GB.ISO8859-1',\n'ha_ng':'ha_NG.UTF-8',\n'hak_tw':'hak_TW.UTF-8',\n'he':'he_IL.ISO8859-8',\n'he_il':'he_IL.ISO8859-8',\n'hebrew':'he_IL.ISO8859-8',\n'hi':'hi_IN.ISCII-DEV',\n'hi_in':'hi_IN.ISCII-DEV',\n'hi_in.isciidev':'hi_IN.ISCII-DEV',\n'hif_fj':'hif_FJ.UTF-8',\n'hne':'hne_IN.UTF-8',\n'hne_in':'hne_IN.UTF-8',\n'hr':'hr_HR.ISO8859-2',\n'hr_hr':'hr_HR.ISO8859-2',\n'hrvatski':'hr_HR.ISO8859-2',\n'hsb_de':'hsb_DE.ISO8859-2',\n'ht_ht':'ht_HT.UTF-8',\n'hu':'hu_HU.ISO8859-2',\n'hu_hu':'hu_HU.ISO8859-2',\n'hungarian':'hu_HU.ISO8859-2',\n'hy_am':'hy_AM.UTF-8',\n'hy_am.armscii8':'hy_AM.ARMSCII_8',\n'ia':'ia.UTF-8',\n'ia_fr':'ia_FR.UTF-8',\n'icelandic':'is_IS.ISO8859-1',\n'id':'id_ID.ISO8859-1',\n'id_id':'id_ID.ISO8859-1',\n'ig_ng':'ig_NG.UTF-8',\n'ik_ca':'ik_CA.UTF-8',\n'in':'id_ID.ISO8859-1',\n'in_id':'id_ID.ISO8859-1',\n'is':'is_IS.ISO8859-1',\n'is_is':'is_IS.ISO8859-1',\n'iso-8859-1':'en_US.ISO8859-1',\n'iso-8859-15':'en_US.ISO8859-15',\n'iso8859-1':'en_US.ISO8859-1',\n'iso8859-15':'en_US.ISO8859-15',\n'iso_8859_1':'en_US.ISO8859-1',\n'iso_8859_15':'en_US.ISO8859-15',\n'it':'it_IT.ISO8859-1',\n'it_ch':'it_CH.ISO8859-1',\n'it_it':'it_IT.ISO8859-1',\n'italian':'it_IT.ISO8859-1',\n'iu':'iu_CA.NUNACOM-8',\n'iu_ca':'iu_CA.NUNACOM-8',\n'iu_ca.nunacom8':'iu_CA.NUNACOM-8',\n'iw':'he_IL.ISO8859-8',\n'iw_il':'he_IL.ISO8859-8',\n'iw_il.utf8':'iw_IL.UTF-8',\n'ja':'ja_JP.eucJP',\n'ja_jp':'ja_JP.eucJP',\n'ja_jp.euc':'ja_JP.eucJP',\n'ja_jp.mscode':'ja_JP.SJIS',\n'ja_jp.pck':'ja_JP.SJIS',\n'japan':'ja_JP.eucJP',\n'japanese':'ja_JP.eucJP',\n'japanese-euc':'ja_JP.eucJP',\n'japanese.euc':'ja_JP.eucJP',\n'jp_jp':'ja_JP.eucJP',\n'ka':'ka_GE.GEORGIAN-ACADEMY',\n'ka_ge':'ka_GE.GEORGIAN-ACADEMY',\n'ka_ge.georgianacademy':'ka_GE.GEORGIAN-ACADEMY',\n'ka_ge.georgianps':'ka_GE.GEORGIAN-PS',\n'ka_ge.georgianrs':'ka_GE.GEORGIAN-ACADEMY',\n'kab_dz':'kab_DZ.UTF-8',\n'kk_kz':'kk_KZ.ptcp154',\n'kl':'kl_GL.ISO8859-1',\n'kl_gl':'kl_GL.ISO8859-1',\n'km_kh':'km_KH.UTF-8',\n'kn':'kn_IN.UTF-8',\n'kn_in':'kn_IN.UTF-8',\n'ko':'ko_KR.eucKR',\n'ko_kr':'ko_KR.eucKR',\n'ko_kr.euc':'ko_KR.eucKR',\n'kok_in':'kok_IN.UTF-8',\n'korean':'ko_KR.eucKR',\n'korean.euc':'ko_KR.eucKR',\n'ks':'ks_IN.UTF-8',\n'ks_in':'ks_IN.UTF-8',\n'ks_in@devanagari.utf8':'ks_IN.UTF-8@devanagari',\n'ku_tr':'ku_TR.ISO8859-9',\n'kw':'kw_GB.ISO8859-1',\n'kw_gb':'kw_GB.ISO8859-1',\n'ky':'ky_KG.UTF-8',\n'ky_kg':'ky_KG.UTF-8',\n'lb_lu':'lb_LU.UTF-8',\n'lg_ug':'lg_UG.ISO8859-10',\n'li_be':'li_BE.UTF-8',\n'li_nl':'li_NL.UTF-8',\n'lij_it':'lij_IT.UTF-8',\n'lithuanian':'lt_LT.ISO8859-13',\n'ln_cd':'ln_CD.UTF-8',\n'lo':'lo_LA.MULELAO-1',\n'lo_la':'lo_LA.MULELAO-1',\n'lo_la.cp1133':'lo_LA.IBM-CP1133',\n'lo_la.ibmcp1133':'lo_LA.IBM-CP1133',\n'lo_la.mulelao1':'lo_LA.MULELAO-1',\n'lt':'lt_LT.ISO8859-13',\n'lt_lt':'lt_LT.ISO8859-13',\n'lv':'lv_LV.ISO8859-13',\n'lv_lv':'lv_LV.ISO8859-13',\n'lzh_tw':'lzh_TW.UTF-8',\n'mag_in':'mag_IN.UTF-8',\n'mai':'mai_IN.UTF-8',\n'mai_in':'mai_IN.UTF-8',\n'mai_np':'mai_NP.UTF-8',\n'mfe_mu':'mfe_MU.UTF-8',\n'mg_mg':'mg_MG.ISO8859-15',\n'mhr_ru':'mhr_RU.UTF-8',\n'mi':'mi_NZ.ISO8859-1',\n'mi_nz':'mi_NZ.ISO8859-1',\n'miq_ni':'miq_NI.UTF-8',\n'mjw_in':'mjw_IN.UTF-8',\n'mk':'mk_MK.ISO8859-5',\n'mk_mk':'mk_MK.ISO8859-5',\n'ml':'ml_IN.UTF-8',\n'ml_in':'ml_IN.UTF-8',\n'mn_mn':'mn_MN.UTF-8',\n'mni_in':'mni_IN.UTF-8',\n'mr':'mr_IN.UTF-8',\n'mr_in':'mr_IN.UTF-8',\n'ms':'ms_MY.ISO8859-1',\n'ms_my':'ms_MY.ISO8859-1',\n'mt':'mt_MT.ISO8859-3',\n'mt_mt':'mt_MT.ISO8859-3',\n'my_mm':'my_MM.UTF-8',\n'nan_tw':'nan_TW.UTF-8',\n'nb':'nb_NO.ISO8859-1',\n'nb_no':'nb_NO.ISO8859-1',\n'nds_de':'nds_DE.UTF-8',\n'nds_nl':'nds_NL.UTF-8',\n'ne_np':'ne_NP.UTF-8',\n'nhn_mx':'nhn_MX.UTF-8',\n'niu_nu':'niu_NU.UTF-8',\n'niu_nz':'niu_NZ.UTF-8',\n'nl':'nl_NL.ISO8859-1',\n'nl_aw':'nl_AW.UTF-8',\n'nl_be':'nl_BE.ISO8859-1',\n'nl_nl':'nl_NL.ISO8859-1',\n'nn':'nn_NO.ISO8859-1',\n'nn_no':'nn_NO.ISO8859-1',\n'no':'no_NO.ISO8859-1',\n'no@nynorsk':'ny_NO.ISO8859-1',\n'no_no':'no_NO.ISO8859-1',\n'no_no.iso88591@bokmal':'no_NO.ISO8859-1',\n'no_no.iso88591@nynorsk':'no_NO.ISO8859-1',\n'norwegian':'no_NO.ISO8859-1',\n'nr':'nr_ZA.ISO8859-1',\n'nr_za':'nr_ZA.ISO8859-1',\n'nso':'nso_ZA.ISO8859-15',\n'nso_za':'nso_ZA.ISO8859-15',\n'ny':'ny_NO.ISO8859-1',\n'ny_no':'ny_NO.ISO8859-1',\n'nynorsk':'nn_NO.ISO8859-1',\n'oc':'oc_FR.ISO8859-1',\n'oc_fr':'oc_FR.ISO8859-1',\n'om_et':'om_ET.UTF-8',\n'om_ke':'om_KE.ISO8859-1',\n'or':'or_IN.UTF-8',\n'or_in':'or_IN.UTF-8',\n'os_ru':'os_RU.UTF-8',\n'pa':'pa_IN.UTF-8',\n'pa_in':'pa_IN.UTF-8',\n'pa_pk':'pa_PK.UTF-8',\n'pap_an':'pap_AN.UTF-8',\n'pap_aw':'pap_AW.UTF-8',\n'pap_cw':'pap_CW.UTF-8',\n'pd':'pd_US.ISO8859-1',\n'pd_de':'pd_DE.ISO8859-1',\n'pd_us':'pd_US.ISO8859-1',\n'ph':'ph_PH.ISO8859-1',\n'ph_ph':'ph_PH.ISO8859-1',\n'pl':'pl_PL.ISO8859-2',\n'pl_pl':'pl_PL.ISO8859-2',\n'polish':'pl_PL.ISO8859-2',\n'portuguese':'pt_PT.ISO8859-1',\n'portuguese_brazil':'pt_BR.ISO8859-1',\n'posix':'C',\n'posix-utf2':'C',\n'pp':'pp_AN.ISO8859-1',\n'pp_an':'pp_AN.ISO8859-1',\n'ps_af':'ps_AF.UTF-8',\n'pt':'pt_PT.ISO8859-1',\n'pt_br':'pt_BR.ISO8859-1',\n'pt_pt':'pt_PT.ISO8859-1',\n'quz_pe':'quz_PE.UTF-8',\n'raj_in':'raj_IN.UTF-8',\n'ro':'ro_RO.ISO8859-2',\n'ro_ro':'ro_RO.ISO8859-2',\n'romanian':'ro_RO.ISO8859-2',\n'ru':'ru_RU.UTF-8',\n'ru_ru':'ru_RU.UTF-8',\n'ru_ua':'ru_UA.KOI8-U',\n'rumanian':'ro_RO.ISO8859-2',\n'russian':'ru_RU.KOI8-R',\n'rw':'rw_RW.ISO8859-1',\n'rw_rw':'rw_RW.ISO8859-1',\n'sa_in':'sa_IN.UTF-8',\n'sat_in':'sat_IN.UTF-8',\n'sc_it':'sc_IT.UTF-8',\n'sd':'sd_IN.UTF-8',\n'sd_in':'sd_IN.UTF-8',\n'sd_in@devanagari.utf8':'sd_IN.UTF-8@devanagari',\n'sd_pk':'sd_PK.UTF-8',\n'se_no':'se_NO.UTF-8',\n'serbocroatian':'sr_RS.UTF-8@latin',\n'sgs_lt':'sgs_LT.UTF-8',\n'sh':'sr_RS.UTF-8@latin',\n'sh_ba.iso88592@bosnia':'sr_CS.ISO8859-2',\n'sh_hr':'sh_HR.ISO8859-2',\n'sh_hr.iso88592':'hr_HR.ISO8859-2',\n'sh_sp':'sr_CS.ISO8859-2',\n'sh_yu':'sr_RS.UTF-8@latin',\n'shn_mm':'shn_MM.UTF-8',\n'shs_ca':'shs_CA.UTF-8',\n'si':'si_LK.UTF-8',\n'si_lk':'si_LK.UTF-8',\n'sid_et':'sid_ET.UTF-8',\n'sinhala':'si_LK.UTF-8',\n'sk':'sk_SK.ISO8859-2',\n'sk_sk':'sk_SK.ISO8859-2',\n'sl':'sl_SI.ISO8859-2',\n'sl_cs':'sl_CS.ISO8859-2',\n'sl_si':'sl_SI.ISO8859-2',\n'slovak':'sk_SK.ISO8859-2',\n'slovene':'sl_SI.ISO8859-2',\n'slovenian':'sl_SI.ISO8859-2',\n'sm_ws':'sm_WS.UTF-8',\n'so_dj':'so_DJ.ISO8859-1',\n'so_et':'so_ET.UTF-8',\n'so_ke':'so_KE.ISO8859-1',\n'so_so':'so_SO.ISO8859-1',\n'sp':'sr_CS.ISO8859-5',\n'sp_yu':'sr_CS.ISO8859-5',\n'spanish':'es_ES.ISO8859-1',\n'spanish_spain':'es_ES.ISO8859-1',\n'sq':'sq_AL.ISO8859-2',\n'sq_al':'sq_AL.ISO8859-2',\n'sq_mk':'sq_MK.UTF-8',\n'sr':'sr_RS.UTF-8',\n'sr@cyrillic':'sr_RS.UTF-8',\n'sr@latn':'sr_CS.UTF-8@latin',\n'sr_cs':'sr_CS.UTF-8',\n'sr_cs.iso88592@latn':'sr_CS.ISO8859-2',\n'sr_cs@latn':'sr_CS.UTF-8@latin',\n'sr_me':'sr_ME.UTF-8',\n'sr_rs':'sr_RS.UTF-8',\n'sr_rs@latn':'sr_RS.UTF-8@latin',\n'sr_sp':'sr_CS.ISO8859-2',\n'sr_yu':'sr_RS.UTF-8@latin',\n'sr_yu.cp1251@cyrillic':'sr_CS.CP1251',\n'sr_yu.iso88592':'sr_CS.ISO8859-2',\n'sr_yu.iso88595':'sr_CS.ISO8859-5',\n'sr_yu.iso88595@cyrillic':'sr_CS.ISO8859-5',\n'sr_yu.microsoftcp1251@cyrillic':'sr_CS.CP1251',\n'sr_yu.utf8':'sr_RS.UTF-8',\n'sr_yu.utf8@cyrillic':'sr_RS.UTF-8',\n'sr_yu@cyrillic':'sr_RS.UTF-8',\n'ss':'ss_ZA.ISO8859-1',\n'ss_za':'ss_ZA.ISO8859-1',\n'st':'st_ZA.ISO8859-1',\n'st_za':'st_ZA.ISO8859-1',\n'sv':'sv_SE.ISO8859-1',\n'sv_fi':'sv_FI.ISO8859-1',\n'sv_se':'sv_SE.ISO8859-1',\n'sw_ke':'sw_KE.UTF-8',\n'sw_tz':'sw_TZ.UTF-8',\n'swedish':'sv_SE.ISO8859-1',\n'szl_pl':'szl_PL.UTF-8',\n'ta':'ta_IN.TSCII-0',\n'ta_in':'ta_IN.TSCII-0',\n'ta_in.tscii':'ta_IN.TSCII-0',\n'ta_in.tscii0':'ta_IN.TSCII-0',\n'ta_lk':'ta_LK.UTF-8',\n'tcy_in.utf8':'tcy_IN.UTF-8',\n'te':'te_IN.UTF-8',\n'te_in':'te_IN.UTF-8',\n'tg':'tg_TJ.KOI8-C',\n'tg_tj':'tg_TJ.KOI8-C',\n'th':'th_TH.ISO8859-11',\n'th_th':'th_TH.ISO8859-11',\n'th_th.tactis':'th_TH.TIS620',\n'th_th.tis620':'th_TH.TIS620',\n'thai':'th_TH.ISO8859-11',\n'the_np':'the_NP.UTF-8',\n'ti_er':'ti_ER.UTF-8',\n'ti_et':'ti_ET.UTF-8',\n'tig_er':'tig_ER.UTF-8',\n'tk_tm':'tk_TM.UTF-8',\n'tl':'tl_PH.ISO8859-1',\n'tl_ph':'tl_PH.ISO8859-1',\n'tn':'tn_ZA.ISO8859-15',\n'tn_za':'tn_ZA.ISO8859-15',\n'to_to':'to_TO.UTF-8',\n'tpi_pg':'tpi_PG.UTF-8',\n'tr':'tr_TR.ISO8859-9',\n'tr_cy':'tr_CY.ISO8859-9',\n'tr_tr':'tr_TR.ISO8859-9',\n'ts':'ts_ZA.ISO8859-1',\n'ts_za':'ts_ZA.ISO8859-1',\n'tt':'tt_RU.TATAR-CYR',\n'tt_ru':'tt_RU.TATAR-CYR',\n'tt_ru.tatarcyr':'tt_RU.TATAR-CYR',\n'tt_ru@iqtelif':'tt_RU.UTF-8@iqtelif',\n'turkish':'tr_TR.ISO8859-9',\n'ug_cn':'ug_CN.UTF-8',\n'uk':'uk_UA.KOI8-U',\n'uk_ua':'uk_UA.KOI8-U',\n'univ':'en_US.utf',\n'universal':'en_US.utf',\n'universal.utf8@ucs4':'en_US.UTF-8',\n'unm_us':'unm_US.UTF-8',\n'ur':'ur_PK.CP1256',\n'ur_in':'ur_IN.UTF-8',\n'ur_pk':'ur_PK.CP1256',\n'uz':'uz_UZ.UTF-8',\n'uz_uz':'uz_UZ.UTF-8',\n'uz_uz@cyrillic':'uz_UZ.UTF-8',\n've':'ve_ZA.UTF-8',\n've_za':'ve_ZA.UTF-8',\n'vi':'vi_VN.TCVN',\n'vi_vn':'vi_VN.TCVN',\n'vi_vn.tcvn':'vi_VN.TCVN',\n'vi_vn.tcvn5712':'vi_VN.TCVN',\n'vi_vn.viscii':'vi_VN.VISCII',\n'vi_vn.viscii111':'vi_VN.VISCII',\n'wa':'wa_BE.ISO8859-1',\n'wa_be':'wa_BE.ISO8859-1',\n'wae_ch':'wae_CH.UTF-8',\n'wal_et':'wal_ET.UTF-8',\n'wo_sn':'wo_SN.UTF-8',\n'xh':'xh_ZA.ISO8859-1',\n'xh_za':'xh_ZA.ISO8859-1',\n'yi':'yi_US.CP1255',\n'yi_us':'yi_US.CP1255',\n'yo_ng':'yo_NG.UTF-8',\n'yue_hk':'yue_HK.UTF-8',\n'yuw_pg':'yuw_PG.UTF-8',\n'zh':'zh_CN.eucCN',\n'zh_cn':'zh_CN.gb2312',\n'zh_cn.big5':'zh_TW.big5',\n'zh_cn.euc':'zh_CN.eucCN',\n'zh_hk':'zh_HK.big5hkscs',\n'zh_hk.big5hk':'zh_HK.big5hkscs',\n'zh_sg':'zh_SG.GB2312',\n'zh_sg.gbk':'zh_SG.GBK',\n'zh_tw':'zh_TW.big5',\n'zh_tw.euc':'zh_TW.eucTW',\n'zh_tw.euctw':'zh_TW.eucTW',\n'zu':'zu_ZA.ISO8859-1',\n'zu_za':'zu_ZA.ISO8859-1',\n}\n\n\n\n\n\n\n\n\n\n\n\n\n\n\nwindows_locale={\n0x0436:\"af_ZA\",\n0x041c:\"sq_AL\",\n0x0484:\"gsw_FR\",\n0x045e:\"am_ET\",\n0x0401:\"ar_SA\",\n0x0801:\"ar_IQ\",\n0x0c01:\"ar_EG\",\n0x1001:\"ar_LY\",\n0x1401:\"ar_DZ\",\n0x1801:\"ar_MA\",\n0x1c01:\"ar_TN\",\n0x2001:\"ar_OM\",\n0x2401:\"ar_YE\",\n0x2801:\"ar_SY\",\n0x2c01:\"ar_JO\",\n0x3001:\"ar_LB\",\n0x3401:\"ar_KW\",\n0x3801:\"ar_AE\",\n0x3c01:\"ar_BH\",\n0x4001:\"ar_QA\",\n0x042b:\"hy_AM\",\n0x044d:\"as_IN\",\n0x042c:\"az_AZ\",\n0x082c:\"az_AZ\",\n0x046d:\"ba_RU\",\n0x042d:\"eu_ES\",\n0x0423:\"be_BY\",\n0x0445:\"bn_IN\",\n0x201a:\"bs_BA\",\n0x141a:\"bs_BA\",\n0x047e:\"br_FR\",\n0x0402:\"bg_BG\",\n\n0x0403:\"ca_ES\",\n0x0004:\"zh_CHS\",\n0x0404:\"zh_TW\",\n0x0804:\"zh_CN\",\n0x0c04:\"zh_HK\",\n0x1004:\"zh_SG\",\n0x1404:\"zh_MO\",\n0x7c04:\"zh_CHT\",\n0x0483:\"co_FR\",\n0x041a:\"hr_HR\",\n0x101a:\"hr_BA\",\n0x0405:\"cs_CZ\",\n0x0406:\"da_DK\",\n0x048c:\"gbz_AF\",\n0x0465:\"div_MV\",\n0x0413:\"nl_NL\",\n0x0813:\"nl_BE\",\n0x0409:\"en_US\",\n0x0809:\"en_GB\",\n0x0c09:\"en_AU\",\n0x1009:\"en_CA\",\n0x1409:\"en_NZ\",\n0x1809:\"en_IE\",\n0x1c09:\"en_ZA\",\n0x2009:\"en_JA\",\n0x2409:\"en_CB\",\n0x2809:\"en_BZ\",\n0x2c09:\"en_TT\",\n0x3009:\"en_ZW\",\n0x3409:\"en_PH\",\n0x4009:\"en_IN\",\n0x4409:\"en_MY\",\n0x4809:\"en_IN\",\n0x0425:\"et_EE\",\n0x0438:\"fo_FO\",\n0x0464:\"fil_PH\",\n0x040b:\"fi_FI\",\n0x040c:\"fr_FR\",\n0x080c:\"fr_BE\",\n0x0c0c:\"fr_CA\",\n0x100c:\"fr_CH\",\n0x140c:\"fr_LU\",\n0x180c:\"fr_MC\",\n0x0462:\"fy_NL\",\n0x0456:\"gl_ES\",\n0x0437:\"ka_GE\",\n0x0407:\"de_DE\",\n0x0807:\"de_CH\",\n0x0c07:\"de_AT\",\n0x1007:\"de_LU\",\n0x1407:\"de_LI\",\n0x0408:\"el_GR\",\n0x046f:\"kl_GL\",\n0x0447:\"gu_IN\",\n0x0468:\"ha_NG\",\n0x040d:\"he_IL\",\n0x0439:\"hi_IN\",\n0x040e:\"hu_HU\",\n0x040f:\"is_IS\",\n0x0421:\"id_ID\",\n0x045d:\"iu_CA\",\n0x085d:\"iu_CA\",\n0x083c:\"ga_IE\",\n0x0410:\"it_IT\",\n0x0810:\"it_CH\",\n0x0411:\"ja_JP\",\n0x044b:\"kn_IN\",\n0x043f:\"kk_KZ\",\n0x0453:\"kh_KH\",\n0x0486:\"qut_GT\",\n0x0487:\"rw_RW\",\n0x0457:\"kok_IN\",\n0x0412:\"ko_KR\",\n0x0440:\"ky_KG\",\n0x0454:\"lo_LA\",\n0x0426:\"lv_LV\",\n0x0427:\"lt_LT\",\n0x082e:\"dsb_DE\",\n0x046e:\"lb_LU\",\n0x042f:\"mk_MK\",\n0x043e:\"ms_MY\",\n0x083e:\"ms_BN\",\n0x044c:\"ml_IN\",\n0x043a:\"mt_MT\",\n0x0481:\"mi_NZ\",\n0x047a:\"arn_CL\",\n0x044e:\"mr_IN\",\n0x047c:\"moh_CA\",\n0x0450:\"mn_MN\",\n0x0850:\"mn_CN\",\n0x0461:\"ne_NP\",\n0x0414:\"nb_NO\",\n0x0814:\"nn_NO\",\n0x0482:\"oc_FR\",\n0x0448:\"or_IN\",\n0x0463:\"ps_AF\",\n0x0429:\"fa_IR\",\n0x0415:\"pl_PL\",\n0x0416:\"pt_BR\",\n0x0816:\"pt_PT\",\n0x0446:\"pa_IN\",\n0x046b:\"quz_BO\",\n0x086b:\"quz_EC\",\n0x0c6b:\"quz_PE\",\n0x0418:\"ro_RO\",\n0x0417:\"rm_CH\",\n0x0419:\"ru_RU\",\n0x243b:\"smn_FI\",\n0x103b:\"smj_NO\",\n0x143b:\"smj_SE\",\n0x043b:\"se_NO\",\n0x083b:\"se_SE\",\n0x0c3b:\"se_FI\",\n0x203b:\"sms_FI\",\n0x183b:\"sma_NO\",\n0x1c3b:\"sma_SE\",\n0x044f:\"sa_IN\",\n0x0c1a:\"sr_SP\",\n0x1c1a:\"sr_BA\",\n0x081a:\"sr_SP\",\n0x181a:\"sr_BA\",\n0x045b:\"si_LK\",\n0x046c:\"ns_ZA\",\n0x0432:\"tn_ZA\",\n0x041b:\"sk_SK\",\n0x0424:\"sl_SI\",\n0x040a:\"es_ES\",\n0x080a:\"es_MX\",\n0x0c0a:\"es_ES\",\n0x100a:\"es_GT\",\n0x140a:\"es_CR\",\n0x180a:\"es_PA\",\n0x1c0a:\"es_DO\",\n0x200a:\"es_VE\",\n0x240a:\"es_CO\",\n0x280a:\"es_PE\",\n0x2c0a:\"es_AR\",\n0x300a:\"es_EC\",\n0x340a:\"es_CL\",\n0x380a:\"es_UR\",\n0x3c0a:\"es_PY\",\n0x400a:\"es_BO\",\n0x440a:\"es_SV\",\n0x480a:\"es_HN\",\n0x4c0a:\"es_NI\",\n0x500a:\"es_PR\",\n0x540a:\"es_US\",\n\n0x0441:\"sw_KE\",\n0x041d:\"sv_SE\",\n0x081d:\"sv_FI\",\n0x045a:\"syr_SY\",\n0x0428:\"tg_TJ\",\n0x085f:\"tmz_DZ\",\n0x0449:\"ta_IN\",\n0x0444:\"tt_RU\",\n0x044a:\"te_IN\",\n0x041e:\"th_TH\",\n0x0851:\"bo_BT\",\n0x0451:\"bo_CN\",\n0x041f:\"tr_TR\",\n0x0442:\"tk_TM\",\n0x0480:\"ug_CN\",\n0x0422:\"uk_UA\",\n0x042e:\"wen_DE\",\n0x0420:\"ur_PK\",\n0x0820:\"ur_IN\",\n0x0443:\"uz_UZ\",\n0x0843:\"uz_UZ\",\n0x042a:\"vi_VN\",\n0x0452:\"cy_GB\",\n0x0488:\"wo_SN\",\n0x0434:\"xh_ZA\",\n0x0485:\"sah_RU\",\n0x0478:\"ii_CN\",\n0x046a:\"yo_NG\",\n0x0435:\"zu_ZA\",\n}\n\ndef _print_locale():\n\n ''\n \n categories={}\n def _init_categories(categories=categories):\n for k,v in globals().items():\n if k[:3]=='LC_':\n categories[k]=v\n _init_categories()\n del categories['LC_ALL']\n \n print('Locale defaults as determined by getdefaultlocale():')\n print('-'*72)\n lang,enc=getdefaultlocale()\n print('Language: ',lang or '(undefined)')\n print('Encoding: ',enc or '(undefined)')\n print()\n \n print('Locale settings on startup:')\n print('-'*72)\n for name,category in categories.items():\n print(name,'...')\n lang,enc=getlocale(category)\n print(' Language: ',lang or '(undefined)')\n print(' Encoding: ',enc or '(undefined)')\n print()\n \n print()\n print('Locale settings after calling resetlocale():')\n print('-'*72)\n resetlocale()\n for name,category in categories.items():\n print(name,'...')\n lang,enc=getlocale(category)\n print(' Language: ',lang or '(undefined)')\n print(' Encoding: ',enc or '(undefined)')\n print()\n \n try :\n setlocale(LC_ALL,\"\")\n except :\n print('NOTE:')\n print('setlocale(LC_ALL, \"\") does not support the default locale')\n print('given in the OS environment variables.')\n else :\n print()\n print('Locale settings after calling setlocale(LC_ALL, \"\"):')\n print('-'*72)\n for name,category in categories.items():\n print(name,'...')\n lang,enc=getlocale(category)\n print(' Language: ',lang or '(undefined)')\n print(' Encoding: ',enc or '(undefined)')\n print()\n \n \n \ntry :\n LC_MESSAGES\nexcept NameError:\n pass\nelse :\n __all__.append(\"LC_MESSAGES\")\n \nif __name__ =='__main__':\n print('Locale aliasing:')\n print()\n _print_locale()\n print()\n print('Number formatting:')\n print()\n _test()\n", ["_bootlocale", "_collections_abc", "_locale", "builtins", "encodings", "encodings.aliases", "functools", "os", "re", "sys", "warnings"]], "binascii": [".py", "''\n\n\n\n\n\n\n\nimport _base64\n\nfrom _binascii import *\n\nclass Error(ValueError):\n def __init__(self,msg=''):\n self._msg=msg\n \n def __str__(self):\n return \" binascii.Error: \"+self._msg\n \n \nclass Done(Exception):\n pass\n \nclass Incomplete(Error):\n pass\n \ndef a2b_uu(s):\n if not s:\n return ''\n \n length=(ord(s[0])-0x20)%64\n \n def quadruplets_gen(s):\n while s:\n try :\n yield ord(s[0]),ord(s[1]),ord(s[2]),ord(s[3])\n except IndexError:\n s +=' '\n yield ord(s[0]),ord(s[1]),ord(s[2]),ord(s[3])\n return\n s=s[4:]\n \n try :\n result=[''.join(\n [chr((A -0x20)<<2 |(((B -0x20)>>4)&0x3)),\n chr(((B -0x20)&0xf)<<4 |(((C -0x20)>>2)&0xf)),\n chr(((C -0x20)&0x3)<<6 |((D -0x20)&0x3f))\n ])for A,B,C,D in quadruplets_gen(s[1:].rstrip())]\n except ValueError:\n raise Error('Illegal char')\n result=''.join(result)\n trailingdata=result[length:]\n if trailingdata.strip('\\x00'):\n raise Error('Trailing garbage')\n result=result[:length]\n if len(result)<length:\n result +=((length -len(result))*'\\x00')\n return bytes(result,__BRYTHON__.charset)\n \n \ntable_a2b_base64={\n'A':0,\n'B':1,\n'C':2,\n'D':3,\n'E':4,\n'F':5,\n'G':6,\n'H':7,\n'I':8,\n'J':9,\n'K':10,\n'L':11,\n'M':12,\n'N':13,\n'O':14,\n'P':15,\n'Q':16,\n'R':17,\n'S':18,\n'T':19,\n'U':20,\n'V':21,\n'W':22,\n'X':23,\n'Y':24,\n'Z':25,\n'a':26,\n'b':27,\n'c':28,\n'd':29,\n'e':30,\n'f':31,\n'g':32,\n'h':33,\n'i':34,\n'j':35,\n'k':36,\n'l':37,\n'm':38,\n'n':39,\n'o':40,\n'p':41,\n'q':42,\n'r':43,\n's':44,\n't':45,\n'u':46,\n'v':47,\n'w':48,\n'x':49,\n'y':50,\n'z':51,\n'0':52,\n'1':53,\n'2':54,\n'3':55,\n'4':56,\n'5':57,\n'6':58,\n'7':59,\n'8':60,\n'9':61,\n'+':62,\n'/':63,\n'=':0,\n}\n\n\ndef XXXa2b_base64(s):\n return _base64.Base64.decode(s)\n \ntable_b2a_base64=\"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz\"\\\n\"0123456789+/\"\n\ndef XXXb2a_base64(s,newline=True ):\n length=len(s)\n final_length=length %3\n \n def triples_gen(s):\n while s:\n try :\n yield s[0],s[1],s[2]\n except IndexError:\n s +=b'\\0\\0'\n yield s[0],s[1],s[2]\n return\n s=s[3:]\n \n a=triples_gen(s[:length -final_length])\n \n result=[''.join(\n [table_b2a_base64[(A >>2)&0x3F],\n table_b2a_base64[((A <<4)|((B >>4)&0xF))&0x3F],\n table_b2a_base64[((B <<2)|((C >>6)&0x3))&0x3F],\n table_b2a_base64[(C)&0x3F]])\n for A,B,C in a]\n \n final=s[length -final_length:]\n if final_length ==0:\n snippet=''\n elif final_length ==1:\n a=final[0]\n snippet=table_b2a_base64[(a >>2)&0x3F]+\\\n table_b2a_base64[(a <<4)&0x3F]+'=='\n else :\n a=final[0]\n b=final[1]\n snippet=table_b2a_base64[(a >>2)&0x3F]+\\\n table_b2a_base64[((a <<4)|(b >>4)&0xF)&0x3F]+\\\n table_b2a_base64[(b <<2)&0x3F]+'='\n \n result=''.join(result)+snippet\n if newline:\n result +='\\n'\n return bytes(result,__BRYTHON__.charset)\n \ndef a2b_qp(s,header=False ):\n inp=0\n odata=[]\n while inp <len(s):\n if s[inp]=='=':\n inp +=1\n if inp >=len(s):\n break\n \n if (s[inp]=='\\n')or (s[inp]=='\\r'):\n if s[inp]!='\\n':\n while inp <len(s)and s[inp]!='\\n':\n inp +=1\n if inp <len(s):\n inp +=1\n elif s[inp]=='=':\n \n odata.append('=')\n inp +=1\n elif s[inp]in hex_numbers and s[inp+1]in hex_numbers:\n ch=chr(int(s[inp:inp+2],16))\n inp +=2\n odata.append(ch)\n else :\n odata.append('=')\n elif header and s[inp]=='_':\n odata.append(' ')\n inp +=1\n else :\n odata.append(s[inp])\n inp +=1\n return bytes(''.join(odata),__BRYTHON__.charset)\n \ndef b2a_qp(data,quotetabs=False ,istext=True ,header=False ):\n ''\n\n\n\n\n \n MAXLINESIZE=76\n \n \n lf=data.find('\\n')\n crlf=lf >0 and data[lf -1]=='\\r'\n \n inp=0\n linelen=0\n odata=[]\n while inp <len(data):\n c=data[inp]\n if (c >'~'or\n c =='='or\n (header and c =='_')or\n (c =='.'and linelen ==0 and (inp+1 ==len(data)or\n data[inp+1]=='\\n'or\n data[inp+1]=='\\r'))or\n (not istext and (c =='\\r'or c =='\\n'))or\n ((c =='\\t'or c ==' ')and (inp+1 ==len(data)))or\n (c <=' 'and c !='\\r'and c !='\\n'and\n (quotetabs or (not quotetabs and (c !='\\t'and c !=' '))))):\n linelen +=3\n if linelen >=MAXLINESIZE:\n odata.append('=')\n if crlf:odata.append('\\r')\n odata.append('\\n')\n linelen=3\n odata.append('='+two_hex_digits(ord(c)))\n inp +=1\n else :\n if (istext and\n (c =='\\n'or (inp+1 <len(data)and c =='\\r'and\n data[inp+1]=='\\n'))):\n linelen=0\n \n if (len(odata)>0 and\n (odata[-1]==' 'or odata[-1]=='\\t')):\n ch=ord(odata[-1])\n odata[-1]='='\n odata.append(two_hex_digits(ch))\n \n if crlf:odata.append('\\r')\n odata.append('\\n')\n if c =='\\r':\n inp +=2\n else :\n inp +=1\n else :\n if (inp+1 <len(data)and\n data[inp+1]!='\\n'and\n (linelen+1)>=MAXLINESIZE):\n odata.append('=')\n if crlf:odata.append('\\r')\n odata.append('\\n')\n linelen=0\n \n linelen +=1\n if header and c ==' ':\n c='_'\n odata.append(c)\n inp +=1\n return ''.join(odata)\n \nhex_numbers='0123456789ABCDEF'\ndef hex(n):\n if n ==0:\n return '0'\n \n if n <0:\n n=-n\n sign='-'\n else :\n sign=''\n arr=[]\n \n def hex_gen(n):\n ''\n while n:\n yield n %0x10\n n=n /0x10\n \n for nibble in hex_gen(n):\n arr=[hex_numbers[nibble]]+arr\n return sign+''.join(arr)\n \ndef two_hex_digits(n):\n return hex_numbers[n /0x10]+hex_numbers[n %0x10]\n \n \ndef strhex_to_int(s):\n i=0\n for c in s:\n i=i *0x10+hex_numbers.index(c)\n return i\n \nhqx_encoding='!\"#$%&\\'()*+,-012345689@ABCDEFGHIJKLMNPQRSTUVXYZ[`abcdefhijklmpqr'\n\nDONE=0x7f\nSKIP=0x7e\nFAIL=0x7d\n\ntable_a2b_hqx=[\n\nFAIL,FAIL,FAIL,FAIL,FAIL,FAIL,FAIL,FAIL,\n\nFAIL,FAIL,SKIP,FAIL,FAIL,SKIP,FAIL,FAIL,\n\nFAIL,FAIL,FAIL,FAIL,FAIL,FAIL,FAIL,FAIL,\n\nFAIL,FAIL,FAIL,FAIL,FAIL,FAIL,FAIL,FAIL,\n\nFAIL,0x00,0x01,0x02,0x03,0x04,0x05,0x06,\n\n0x07,0x08,0x09,0x0A,0x0B,0x0C,FAIL,FAIL,\n\n0x0D,0x0E,0x0F,0x10,0x11,0x12,0x13,FAIL,\n\n0x14,0x15,DONE,FAIL,FAIL,FAIL,FAIL,FAIL,\n\n0x16,0x17,0x18,0x19,0x1A,0x1B,0x1C,0x1D,\n\n0x1E,0x1F,0x20,0x21,0x22,0x23,0x24,FAIL,\n\n0x25,0x26,0x27,0x28,0x29,0x2A,0x2B,FAIL,\n\n0x2C,0x2D,0x2E,0x2F,FAIL,FAIL,FAIL,FAIL,\n\n0x30,0x31,0x32,0x33,0x34,0x35,0x36,FAIL,\n\n0x37,0x38,0x39,0x3A,0x3B,0x3C,FAIL,FAIL,\n\n0x3D,0x3E,0x3F,FAIL,FAIL,FAIL,FAIL,FAIL,\n\nFAIL,FAIL,FAIL,FAIL,FAIL,FAIL,FAIL,FAIL,\nFAIL,FAIL,FAIL,FAIL,FAIL,FAIL,FAIL,FAIL,\nFAIL,FAIL,FAIL,FAIL,FAIL,FAIL,FAIL,FAIL,\nFAIL,FAIL,FAIL,FAIL,FAIL,FAIL,FAIL,FAIL,\nFAIL,FAIL,FAIL,FAIL,FAIL,FAIL,FAIL,FAIL,\nFAIL,FAIL,FAIL,FAIL,FAIL,FAIL,FAIL,FAIL,\nFAIL,FAIL,FAIL,FAIL,FAIL,FAIL,FAIL,FAIL,\nFAIL,FAIL,FAIL,FAIL,FAIL,FAIL,FAIL,FAIL,\nFAIL,FAIL,FAIL,FAIL,FAIL,FAIL,FAIL,FAIL,\nFAIL,FAIL,FAIL,FAIL,FAIL,FAIL,FAIL,FAIL,\nFAIL,FAIL,FAIL,FAIL,FAIL,FAIL,FAIL,FAIL,\nFAIL,FAIL,FAIL,FAIL,FAIL,FAIL,FAIL,FAIL,\nFAIL,FAIL,FAIL,FAIL,FAIL,FAIL,FAIL,FAIL,\nFAIL,FAIL,FAIL,FAIL,FAIL,FAIL,FAIL,FAIL,\nFAIL,FAIL,FAIL,FAIL,FAIL,FAIL,FAIL,FAIL,\nFAIL,FAIL,FAIL,FAIL,FAIL,FAIL,FAIL,FAIL,\nFAIL,FAIL,FAIL,FAIL,FAIL,FAIL,FAIL,FAIL,\n]\n\ndef a2b_hqx(s):\n result=[]\n \n def quadruples_gen(s):\n t=[]\n for c in s:\n res=table_a2b_hqx[ord(c)]\n if res ==SKIP:\n continue\n elif res ==FAIL:\n raise Error('Illegal character')\n elif res ==DONE:\n yield t\n raise Done\n else :\n t.append(res)\n if len(t)==4:\n yield t\n t=[]\n yield t\n \n done=0\n try :\n for snippet in quadruples_gen(s):\n length=len(snippet)\n if length ==4:\n result.append(chr(((snippet[0]&0x3f)<<2)|(snippet[1]>>4)))\n result.append(chr(((snippet[1]&0x0f)<<4)|(snippet[2]>>2)))\n result.append(chr(((snippet[2]&0x03)<<6)|(snippet[3])))\n elif length ==3:\n result.append(chr(((snippet[0]&0x3f)<<2)|(snippet[1]>>4)))\n result.append(chr(((snippet[1]&0x0f)<<4)|(snippet[2]>>2)))\n elif length ==2:\n result.append(chr(((snippet[0]&0x3f)<<2)|(snippet[1]>>4)))\n except Done:\n done=1\n except Error:\n raise\n return (''.join(result),done)\n \n \n \ndef b2a_hqx(s):\n result=[]\n \n def triples_gen(s):\n while s:\n try :\n yield ord(s[0]),ord(s[1]),ord(s[2])\n except IndexError:\n yield tuple([ord(c)for c in s])\n s=s[3:]\n \n for snippet in triples_gen(s):\n length=len(snippet)\n if length ==3:\n result.append(\n hqx_encoding[(snippet[0]&0xfc)>>2])\n result.append(hqx_encoding[\n ((snippet[0]&0x03)<<4)|((snippet[1]&0xf0)>>4)])\n result.append(hqx_encoding[\n (snippet[1]&0x0f)<<2 |((snippet[2]&0xc0)>>6)])\n result.append(hqx_encoding[snippet[2]&0x3f])\n elif length ==2:\n result.append(\n hqx_encoding[(snippet[0]&0xfc)>>2])\n result.append(hqx_encoding[\n ((snippet[0]&0x03)<<4)|((snippet[1]&0xf0)>>4)])\n result.append(hqx_encoding[\n (snippet[1]&0x0f)<<2])\n elif length ==1:\n result.append(\n hqx_encoding[(snippet[0]&0xfc)>>2])\n result.append(hqx_encoding[\n ((snippet[0]&0x03)<<4)])\n return ''.join(result)\n \ncrctab_hqx=[\n0x0000,0x1021,0x2042,0x3063,0x4084,0x50a5,0x60c6,0x70e7,\n0x8108,0x9129,0xa14a,0xb16b,0xc18c,0xd1ad,0xe1ce,0xf1ef,\n0x1231,0x0210,0x3273,0x2252,0x52b5,0x4294,0x72f7,0x62d6,\n0x9339,0x8318,0xb37b,0xa35a,0xd3bd,0xc39c,0xf3ff,0xe3de,\n0x2462,0x3443,0x0420,0x1401,0x64e6,0x74c7,0x44a4,0x5485,\n0xa56a,0xb54b,0x8528,0x9509,0xe5ee,0xf5cf,0xc5ac,0xd58d,\n0x3653,0x2672,0x1611,0x0630,0x76d7,0x66f6,0x5695,0x46b4,\n0xb75b,0xa77a,0x9719,0x8738,0xf7df,0xe7fe,0xd79d,0xc7bc,\n0x48c4,0x58e5,0x6886,0x78a7,0x0840,0x1861,0x2802,0x3823,\n0xc9cc,0xd9ed,0xe98e,0xf9af,0x8948,0x9969,0xa90a,0xb92b,\n0x5af5,0x4ad4,0x7ab7,0x6a96,0x1a71,0x0a50,0x3a33,0x2a12,\n0xdbfd,0xcbdc,0xfbbf,0xeb9e,0x9b79,0x8b58,0xbb3b,0xab1a,\n0x6ca6,0x7c87,0x4ce4,0x5cc5,0x2c22,0x3c03,0x0c60,0x1c41,\n0xedae,0xfd8f,0xcdec,0xddcd,0xad2a,0xbd0b,0x8d68,0x9d49,\n0x7e97,0x6eb6,0x5ed5,0x4ef4,0x3e13,0x2e32,0x1e51,0x0e70,\n0xff9f,0xefbe,0xdfdd,0xcffc,0xbf1b,0xaf3a,0x9f59,0x8f78,\n0x9188,0x81a9,0xb1ca,0xa1eb,0xd10c,0xc12d,0xf14e,0xe16f,\n0x1080,0x00a1,0x30c2,0x20e3,0x5004,0x4025,0x7046,0x6067,\n0x83b9,0x9398,0xa3fb,0xb3da,0xc33d,0xd31c,0xe37f,0xf35e,\n0x02b1,0x1290,0x22f3,0x32d2,0x4235,0x5214,0x6277,0x7256,\n0xb5ea,0xa5cb,0x95a8,0x8589,0xf56e,0xe54f,0xd52c,0xc50d,\n0x34e2,0x24c3,0x14a0,0x0481,0x7466,0x6447,0x5424,0x4405,\n0xa7db,0xb7fa,0x8799,0x97b8,0xe75f,0xf77e,0xc71d,0xd73c,\n0x26d3,0x36f2,0x0691,0x16b0,0x6657,0x7676,0x4615,0x5634,\n0xd94c,0xc96d,0xf90e,0xe92f,0x99c8,0x89e9,0xb98a,0xa9ab,\n0x5844,0x4865,0x7806,0x6827,0x18c0,0x08e1,0x3882,0x28a3,\n0xcb7d,0xdb5c,0xeb3f,0xfb1e,0x8bf9,0x9bd8,0xabbb,0xbb9a,\n0x4a75,0x5a54,0x6a37,0x7a16,0x0af1,0x1ad0,0x2ab3,0x3a92,\n0xfd2e,0xed0f,0xdd6c,0xcd4d,0xbdaa,0xad8b,0x9de8,0x8dc9,\n0x7c26,0x6c07,0x5c64,0x4c45,0x3ca2,0x2c83,0x1ce0,0x0cc1,\n0xef1f,0xff3e,0xcf5d,0xdf7c,0xaf9b,0xbfba,0x8fd9,0x9ff8,\n0x6e17,0x7e36,0x4e55,0x5e74,0x2e93,0x3eb2,0x0ed1,0x1ef0,\n]\n\ndef crc_hqx(s,crc):\n for c in s:\n crc=((crc <<8)&0xff00)^crctab_hqx[((crc >>8)&0xff)^ord(c)]\n \n return crc\n \ndef rlecode_hqx(s):\n ''\n\n\n\n \n if not s:\n return ''\n result=[]\n prev=s[0]\n count=1\n \n \n \n \n if s[-1]=='!':\n s=s[1:]+'?'\n else :\n s=s[1:]+'!'\n \n for c in s:\n if c ==prev and count <255:\n count +=1\n else :\n if count ==1:\n if prev !='\\x90':\n result.append(prev)\n else :\n result.extend(['\\x90','\\x00'])\n elif count <4:\n if prev !='\\x90':\n result.extend([prev]*count)\n else :\n result.extend(['\\x90','\\x00']*count)\n else :\n if prev !='\\x90':\n result.extend([prev,'\\x90',chr(count)])\n else :\n result.extend(['\\x90','\\x00','\\x90',chr(count)])\n count=1\n prev=c\n \n return ''.join(result)\n \ndef rledecode_hqx(s):\n s=s.split('\\x90')\n result=[s[0]]\n prev=s[0]\n for snippet in s[1:]:\n count=ord(snippet[0])\n if count >0:\n result.append(prev[-1]*(count -1))\n prev=snippet\n else :\n result.append('\\x90')\n prev='\\x90'\n result.append(snippet[1:])\n \n return ''.join(result)\n \ncrc_32_tab=[\n0x00000000,0x77073096,0xee0e612c,0x990951ba,0x076dc419,\n0x706af48f,0xe963a535,0x9e6495a3,0x0edb8832,0x79dcb8a4,\n0xe0d5e91e,0x97d2d988,0x09b64c2b,0x7eb17cbd,0xe7b82d07,\n0x90bf1d91,0x1db71064,0x6ab020f2,0xf3b97148,0x84be41de,\n0x1adad47d,0x6ddde4eb,0xf4d4b551,0x83d385c7,0x136c9856,\n0x646ba8c0,0xfd62f97a,0x8a65c9ec,0x14015c4f,0x63066cd9,\n0xfa0f3d63,0x8d080df5,0x3b6e20c8,0x4c69105e,0xd56041e4,\n0xa2677172,0x3c03e4d1,0x4b04d447,0xd20d85fd,0xa50ab56b,\n0x35b5a8fa,0x42b2986c,0xdbbbc9d6,0xacbcf940,0x32d86ce3,\n0x45df5c75,0xdcd60dcf,0xabd13d59,0x26d930ac,0x51de003a,\n0xc8d75180,0xbfd06116,0x21b4f4b5,0x56b3c423,0xcfba9599,\n0xb8bda50f,0x2802b89e,0x5f058808,0xc60cd9b2,0xb10be924,\n0x2f6f7c87,0x58684c11,0xc1611dab,0xb6662d3d,0x76dc4190,\n0x01db7106,0x98d220bc,0xefd5102a,0x71b18589,0x06b6b51f,\n0x9fbfe4a5,0xe8b8d433,0x7807c9a2,0x0f00f934,0x9609a88e,\n0xe10e9818,0x7f6a0dbb,0x086d3d2d,0x91646c97,0xe6635c01,\n0x6b6b51f4,0x1c6c6162,0x856530d8,0xf262004e,0x6c0695ed,\n0x1b01a57b,0x8208f4c1,0xf50fc457,0x65b0d9c6,0x12b7e950,\n0x8bbeb8ea,0xfcb9887c,0x62dd1ddf,0x15da2d49,0x8cd37cf3,\n0xfbd44c65,0x4db26158,0x3ab551ce,0xa3bc0074,0xd4bb30e2,\n0x4adfa541,0x3dd895d7,0xa4d1c46d,0xd3d6f4fb,0x4369e96a,\n0x346ed9fc,0xad678846,0xda60b8d0,0x44042d73,0x33031de5,\n0xaa0a4c5f,0xdd0d7cc9,0x5005713c,0x270241aa,0xbe0b1010,\n0xc90c2086,0x5768b525,0x206f85b3,0xb966d409,0xce61e49f,\n0x5edef90e,0x29d9c998,0xb0d09822,0xc7d7a8b4,0x59b33d17,\n0x2eb40d81,0xb7bd5c3b,0xc0ba6cad,0xedb88320,0x9abfb3b6,\n0x03b6e20c,0x74b1d29a,0xead54739,0x9dd277af,0x04db2615,\n0x73dc1683,0xe3630b12,0x94643b84,0x0d6d6a3e,0x7a6a5aa8,\n0xe40ecf0b,0x9309ff9d,0x0a00ae27,0x7d079eb1,0xf00f9344,\n0x8708a3d2,0x1e01f268,0x6906c2fe,0xf762575d,0x806567cb,\n0x196c3671,0x6e6b06e7,0xfed41b76,0x89d32be0,0x10da7a5a,\n0x67dd4acc,0xf9b9df6f,0x8ebeeff9,0x17b7be43,0x60b08ed5,\n0xd6d6a3e8,0xa1d1937e,0x38d8c2c4,0x4fdff252,0xd1bb67f1,\n0xa6bc5767,0x3fb506dd,0x48b2364b,0xd80d2bda,0xaf0a1b4c,\n0x36034af6,0x41047a60,0xdf60efc3,0xa867df55,0x316e8eef,\n0x4669be79,0xcb61b38c,0xbc66831a,0x256fd2a0,0x5268e236,\n0xcc0c7795,0xbb0b4703,0x220216b9,0x5505262f,0xc5ba3bbe,\n0xb2bd0b28,0x2bb45a92,0x5cb36a04,0xc2d7ffa7,0xb5d0cf31,\n0x2cd99e8b,0x5bdeae1d,0x9b64c2b0,0xec63f226,0x756aa39c,\n0x026d930a,0x9c0906a9,0xeb0e363f,0x72076785,0x05005713,\n0x95bf4a82,0xe2b87a14,0x7bb12bae,0x0cb61b38,0x92d28e9b,\n0xe5d5be0d,0x7cdcefb7,0x0bdbdf21,0x86d3d2d4,0xf1d4e242,\n0x68ddb3f8,0x1fda836e,0x81be16cd,0xf6b9265b,0x6fb077e1,\n0x18b74777,0x88085ae6,0xff0f6a70,0x66063bca,0x11010b5c,\n0x8f659eff,0xf862ae69,0x616bffd3,0x166ccf45,0xa00ae278,\n0xd70dd2ee,0x4e048354,0x3903b3c2,0xa7672661,0xd06016f7,\n0x4969474d,0x3e6e77db,0xaed16a4a,0xd9d65adc,0x40df0b66,\n0x37d83bf0,0xa9bcae53,0xdebb9ec5,0x47b2cf7f,0x30b5ffe9,\n0xbdbdf21c,0xcabac28a,0x53b39330,0x24b4a3a6,0xbad03605,\n0xcdd70693,0x54de5729,0x23d967bf,0xb3667a2e,0xc4614ab8,\n0x5d681b02,0x2a6f2b94,0xb40bbe37,0xc30c8ea1,0x5a05df1b,\n0x2d02ef8d\n]\n\ndef crc32(s,crc=0):\n result=0\n crc=~int(crc)&0xffffffff\n \n for c in s:\n crc=crc_32_tab[(crc ^int(ord(c)))&0xff]^(crc >>8)\n \n \n \n result=crc ^0xffffffff\n \n if result >2 **31:\n result=((result+2 **31)%2 **32)-2 **31\n \n return result\n \ntable_hex=[\n-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,\n-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,\n-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,\n0,1,2,3,4,5,6,7,8,9,-1,-1,-1,-1,-1,-1,\n-1,10,11,12,13,14,15,-1,-1,-1,-1,-1,-1,-1,-1,-1,\n-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,\n-1,10,11,12,13,14,15,-1,-1,-1,-1,-1,-1,-1,-1,-1,\n-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1\n]\n\n\ndef a2b_hex(t):\n result=[]\n \n def pairs_gen(s):\n if isinstance(s,bytes)or isinstance(s,bytearray):\n conv=lambda x:x\n else :\n conv=lambda x:ord(x)\n while s:\n try :\n yield table_hex[conv(s[0])],table_hex[conv(s[1])]\n except IndexError:\n if len(s):\n raise TypeError('Odd-length string')\n return\n s=s[2:]\n \n for a,b in pairs_gen(t):\n if a <0 or b <0:\n raise TypeError('Non-hexadecimal digit found')\n result.append(chr((a <<4)+b))\n return bytes(''.join(result),__BRYTHON__.charset)\n \n \nunhexlify=a2b_hex\n", ["_base64", "_binascii"]], "operator": [".py", "''\n\n\n\n\n\n\n\n\n\n\n\n__all__=['abs','add','and_','attrgetter','concat','contains','countOf',\n'delitem','eq','floordiv','ge','getitem','gt','iadd','iand',\n'iconcat','ifloordiv','ilshift','imatmul','imod','imul',\n'index','indexOf','inv','invert','ior','ipow','irshift',\n'is_','is_not','isub','itemgetter','itruediv','ixor','le',\n'length_hint','lshift','lt','matmul','methodcaller','mod',\n'mul','ne','neg','not_','or_','pos','pow','rshift',\n'setitem','sub','truediv','truth','xor']\n\nfrom builtins import abs as _abs\n\n\n\n\ndef lt(a,b):\n ''\n return a <b\n \ndef le(a,b):\n ''\n return a <=b\n \ndef eq(a,b):\n ''\n return a ==b\n \ndef ne(a,b):\n ''\n return a !=b\n \ndef ge(a,b):\n ''\n return a >=b\n \ndef gt(a,b):\n ''\n return a >b\n \n \n \ndef not_(a):\n ''\n return not a\n \ndef truth(a):\n ''\n return True if a else False\n \ndef is_(a,b):\n ''\n return a is b\n \ndef is_not(a,b):\n ''\n return a is not b\n \n \n \ndef abs(a):\n ''\n return _abs(a)\n \ndef add(a,b):\n ''\n return a+b\n \ndef and_(a,b):\n ''\n return a&b\n \ndef floordiv(a,b):\n ''\n return a //b\n \ndef index(a):\n ''\n return a.__index__()\n \ndef inv(a):\n ''\n return ~a\ninvert=inv\n\ndef lshift(a,b):\n ''\n return a <<b\n \ndef mod(a,b):\n ''\n return a %b\n \ndef mul(a,b):\n ''\n return a *b\n \ndef matmul(a,b):\n ''\n return a @b\n \ndef neg(a):\n ''\n return -a\n \ndef or_(a,b):\n ''\n return a |b\n \ndef pos(a):\n ''\n return +a\n \ndef pow(a,b):\n ''\n return a **b\n \ndef rshift(a,b):\n ''\n return a >>b\n \ndef sub(a,b):\n ''\n return a -b\n \ndef truediv(a,b):\n ''\n return a /b\n \ndef xor(a,b):\n ''\n return a ^b\n \n \n \ndef concat(a,b):\n ''\n if not hasattr(a,'__getitem__'):\n msg=\"'%s' object can't be concatenated\"%type(a).__name__\n raise TypeError(msg)\n return a+b\n \ndef contains(a,b):\n ''\n return b in a\n \ndef countOf(a,b):\n ''\n count=0\n for i in a:\n if i ==b:\n count +=1\n return count\n \ndef delitem(a,b):\n ''\n del a[b]\n \ndef getitem(a,b):\n ''\n return a[b]\n \ndef indexOf(a,b):\n ''\n for i,j in enumerate(a):\n if j ==b:\n return i\n else :\n raise ValueError('sequence.index(x): x not in sequence')\n \ndef setitem(a,b,c):\n ''\n a[b]=c\n \ndef length_hint(obj,default=0):\n ''\n\n\n\n\n\n\n \n if not isinstance(default,int):\n msg=(\"'%s' object cannot be interpreted as an integer\"%\n type(default).__name__)\n raise TypeError(msg)\n \n try :\n return len(obj)\n except TypeError:\n pass\n \n try :\n hint=type(obj).__length_hint__\n except AttributeError:\n return default\n \n try :\n val=hint(obj)\n except TypeError:\n return default\n if val is NotImplemented:\n return default\n if not isinstance(val,int):\n msg=('__length_hint__ must be integer, not %s'%\n type(val).__name__)\n raise TypeError(msg)\n if val <0:\n msg='__length_hint__() should return >= 0'\n raise ValueError(msg)\n return val\n \n \n \nclass attrgetter:\n ''\n\n\n\n\n\n \n __slots__=('_attrs','_call')\n \n def __init__(self,attr,*attrs):\n if not attrs:\n if not isinstance(attr,str):\n raise TypeError('attribute name must be a string')\n self._attrs=(attr,)\n names=attr.split('.')\n def func(obj):\n for name in names:\n obj=getattr(obj,name)\n return obj\n self._call=func\n else :\n self._attrs=(attr,)+attrs\n getters=tuple(map(attrgetter,self._attrs))\n def func(obj):\n return tuple(getter(obj)for getter in getters)\n self._call=func\n \n def __call__(self,obj):\n return self._call(obj)\n \n def __repr__(self):\n return '%s.%s(%s)'%(self.__class__.__module__,\n self.__class__.__qualname__,\n ', '.join(map(repr,self._attrs)))\n \n def __reduce__(self):\n return self.__class__,self._attrs\n \nclass itemgetter:\n ''\n\n\n\n \n __slots__=('_items','_call')\n \n def __init__(self,item,*items):\n if not items:\n self._items=(item,)\n def func(obj):\n return obj[item]\n self._call=func\n else :\n self._items=items=(item,)+items\n def func(obj):\n return tuple(obj[i]for i in items)\n self._call=func\n \n def __call__(self,obj):\n return self._call(obj)\n \n def __repr__(self):\n return '%s.%s(%s)'%(self.__class__.__module__,\n self.__class__.__name__,\n ', '.join(map(repr,self._items)))\n \n def __reduce__(self):\n return self.__class__,self._items\n \nclass methodcaller:\n ''\n\n\n\n\n \n __slots__=('_name','_args','_kwargs')\n \n def __init__(*args,**kwargs):\n if len(args)<2:\n msg=\"methodcaller needs at least one argument, the method name\"\n raise TypeError(msg)\n self=args[0]\n self._name=args[1]\n if not isinstance(self._name,str):\n raise TypeError('method name must be a string')\n self._args=args[2:]\n self._kwargs=kwargs\n \n def __call__(self,obj):\n return getattr(obj,self._name)(*self._args,**self._kwargs)\n \n def __repr__(self):\n args=[repr(self._name)]\n args.extend(map(repr,self._args))\n args.extend('%s=%r'%(k,v)for k,v in self._kwargs.items())\n return '%s.%s(%s)'%(self.__class__.__module__,\n self.__class__.__name__,\n ', '.join(args))\n \n def __reduce__(self):\n if not self._kwargs:\n return self.__class__,(self._name,)+self._args\n else :\n from functools import partial\n return partial(self.__class__,self._name,**self._kwargs),self._args\n \n \n \n \ndef iadd(a,b):\n ''\n a +=b\n return a\n \ndef iand(a,b):\n ''\n a &=b\n return a\n \ndef iconcat(a,b):\n ''\n if not hasattr(a,'__getitem__'):\n msg=\"'%s' object can't be concatenated\"%type(a).__name__\n raise TypeError(msg)\n a +=b\n return a\n \ndef ifloordiv(a,b):\n ''\n a //=b\n return a\n \ndef ilshift(a,b):\n ''\n a <<=b\n return a\n \ndef imod(a,b):\n ''\n a %=b\n return a\n \ndef imul(a,b):\n ''\n a *=b\n return a\n \ndef imatmul(a,b):\n ''\n a @=b\n return a\n \ndef ior(a,b):\n ''\n a |=b\n return a\n \ndef ipow(a,b):\n ''\n a **=b\n return a\n \ndef irshift(a,b):\n ''\n a >>=b\n return a\n \ndef isub(a,b):\n ''\n a -=b\n return a\n \ndef itruediv(a,b):\n ''\n a /=b\n return a\n \ndef ixor(a,b):\n ''\n a ^=b\n return a\n \n \ntry :\n from _operator import *\nexcept ImportError:\n pass\nelse :\n from _operator import __doc__\n \n \n \n__lt__=lt\n__le__=le\n__eq__=eq\n__ne__=ne\n__ge__=ge\n__gt__=gt\n__not__=not_\n__abs__=abs\n__add__=add\n__and__=and_\n__floordiv__=floordiv\n__index__=index\n__inv__=inv\n__invert__=invert\n__lshift__=lshift\n__mod__=mod\n__mul__=mul\n__matmul__=matmul\n__neg__=neg\n__or__=or_\n__pos__=pos\n__pow__=pow\n__rshift__=rshift\n__sub__=sub\n__truediv__=truediv\n__xor__=xor\n__concat__=concat\n__contains__=contains\n__delitem__=delitem\n__getitem__=getitem\n__setitem__=setitem\n__iadd__=iadd\n__iand__=iand\n__iconcat__=iconcat\n__ifloordiv__=ifloordiv\n__ilshift__=ilshift\n__imod__=imod\n__imul__=imul\n__imatmul__=imatmul\n__ior__=ior\n__ipow__=ipow\n__irshift__=irshift\n__isub__=isub\n__itruediv__=itruediv\n__ixor__=ixor\n", ["_operator", "builtins", "functools"]], "weakref": [".py", "''\n\n\n\n\n\n\n\n\n\n\nfrom _weakref import (\ngetweakrefcount,\ngetweakrefs,\nref,\nproxy,\nCallableProxyType,\nProxyType,\nReferenceType,\n_remove_dead_weakref)\n\nfrom _weakrefset import WeakSet,_IterationGuard\n\nimport _collections_abc\nimport sys\nimport itertools\n\nProxyTypes=(ProxyType,CallableProxyType)\n\n__all__=[\"ref\",\"proxy\",\"getweakrefcount\",\"getweakrefs\",\n\"WeakKeyDictionary\",\"ReferenceType\",\"ProxyType\",\n\"CallableProxyType\",\"ProxyTypes\",\"WeakValueDictionary\",\n\"WeakSet\",\"WeakMethod\",\"finalize\"]\n\n\nclass WeakMethod(ref):\n ''\n\n\n \n \n __slots__=\"_func_ref\",\"_meth_type\",\"_alive\",\"__weakref__\"\n \n def __new__(cls,meth,callback=None ):\n try :\n obj=meth.__self__\n func=meth.__func__\n except AttributeError:\n raise TypeError(\"argument should be a bound method, not {}\"\n .format(type(meth)))from None\n def _cb(arg):\n \n \n self=self_wr()\n if self._alive:\n self._alive=False\n if callback is not None :\n callback(self)\n self=ref.__new__(cls,obj,_cb)\n self._func_ref=ref(func,_cb)\n self._meth_type=type(meth)\n self._alive=True\n self_wr=ref(self)\n return self\n \n def __call__(self):\n obj=super().__call__()\n func=self._func_ref()\n if obj is None or func is None :\n return None\n return self._meth_type(func,obj)\n \n def __eq__(self,other):\n if isinstance(other,WeakMethod):\n if not self._alive or not other._alive:\n return self is other\n return ref.__eq__(self,other)and self._func_ref ==other._func_ref\n return False\n \n def __ne__(self,other):\n if isinstance(other,WeakMethod):\n if not self._alive or not other._alive:\n return self is not other\n return ref.__ne__(self,other)or self._func_ref !=other._func_ref\n return True\n \n __hash__=ref.__hash__\n \n \nclass WeakValueDictionary(_collections_abc.MutableMapping):\n ''\n\n\n\n \n \n \n \n \n \n \n def __init__(*args,**kw):\n if not args:\n raise TypeError(\"descriptor '__init__' of 'WeakValueDictionary' \"\n \"object needs an argument\")\n self,*args=args\n if len(args)>1:\n raise TypeError('expected at most 1 arguments, got %d'%len(args))\n def remove(wr,selfref=ref(self),_atomic_removal=_remove_dead_weakref):\n self=selfref()\n if self is not None :\n if self._iterating:\n self._pending_removals.append(wr.key)\n else :\n \n \n _atomic_removal(d,wr.key)\n self._remove=remove\n \n self._pending_removals=[]\n self._iterating=set()\n self.data=d={}\n self.update(*args,**kw)\n \n def _commit_removals(self):\n l=self._pending_removals\n d=self.data\n \n \n while l:\n key=l.pop()\n _remove_dead_weakref(d,key)\n \n def __getitem__(self,key):\n if self._pending_removals:\n self._commit_removals()\n o=self.data[key]()\n if o is None :\n raise KeyError(key)\n else :\n return o\n \n def __delitem__(self,key):\n if self._pending_removals:\n self._commit_removals()\n del self.data[key]\n \n def __len__(self):\n if self._pending_removals:\n self._commit_removals()\n return len(self.data)\n \n def __contains__(self,key):\n if self._pending_removals:\n self._commit_removals()\n try :\n o=self.data[key]()\n except KeyError:\n return False\n return o is not None\n \n def __repr__(self):\n return \"<%s at %#x>\"%(self.__class__.__name__,id(self))\n \n def __setitem__(self,key,value):\n if self._pending_removals:\n self._commit_removals()\n self.data[key]=KeyedRef(value,self._remove,key)\n \n def copy(self):\n if self._pending_removals:\n self._commit_removals()\n new=WeakValueDictionary()\n for key,wr in self.data.items():\n o=wr()\n if o is not None :\n new[key]=o\n return new\n \n __copy__=copy\n \n def __deepcopy__(self,memo):\n from copy import deepcopy\n if self._pending_removals:\n self._commit_removals()\n new=self.__class__()\n for key,wr in self.data.items():\n o=wr()\n if o is not None :\n new[deepcopy(key,memo)]=o\n return new\n \n def get(self,key,default=None ):\n if self._pending_removals:\n self._commit_removals()\n try :\n wr=self.data[key]\n except KeyError:\n return default\n else :\n o=wr()\n if o is None :\n \n return default\n else :\n return o\n \n def items(self):\n if self._pending_removals:\n self._commit_removals()\n with _IterationGuard(self):\n for k,wr in self.data.items():\n v=wr()\n if v is not None :\n yield k,v\n \n def keys(self):\n if self._pending_removals:\n self._commit_removals()\n with _IterationGuard(self):\n for k,wr in self.data.items():\n if wr()is not None :\n yield k\n \n __iter__=keys\n \n def itervaluerefs(self):\n ''\n\n\n\n\n\n\n\n \n if self._pending_removals:\n self._commit_removals()\n with _IterationGuard(self):\n yield from self.data.values()\n \n def values(self):\n if self._pending_removals:\n self._commit_removals()\n with _IterationGuard(self):\n for wr in self.data.values():\n obj=wr()\n if obj is not None :\n yield obj\n \n def popitem(self):\n if self._pending_removals:\n self._commit_removals()\n while True :\n key,wr=self.data.popitem()\n o=wr()\n if o is not None :\n return key,o\n \n def pop(self,key,*args):\n if self._pending_removals:\n self._commit_removals()\n try :\n o=self.data.pop(key)()\n except KeyError:\n o=None\n if o is None :\n if args:\n return args[0]\n else :\n raise KeyError(key)\n else :\n return o\n \n def setdefault(self,key,default=None ):\n try :\n o=self.data[key]()\n except KeyError:\n o=None\n if o is None :\n if self._pending_removals:\n self._commit_removals()\n self.data[key]=KeyedRef(default,self._remove,key)\n return default\n else :\n return o\n \n def update(*args,**kwargs):\n if not args:\n raise TypeError(\"descriptor 'update' of 'WeakValueDictionary' \"\n \"object needs an argument\")\n self,*args=args\n if len(args)>1:\n raise TypeError('expected at most 1 arguments, got %d'%len(args))\n dict=args[0]if args else None\n if self._pending_removals:\n self._commit_removals()\n d=self.data\n if dict is not None :\n if not hasattr(dict,\"items\"):\n dict=type({})(dict)\n for key,o in dict.items():\n d[key]=KeyedRef(o,self._remove,key)\n if len(kwargs):\n self.update(kwargs)\n \n def valuerefs(self):\n ''\n\n\n\n\n\n\n\n \n if self._pending_removals:\n self._commit_removals()\n return list(self.data.values())\n \n \nclass KeyedRef(ref):\n ''\n\n\n\n\n\n\n \n \n __slots__=\"key\",\n \n def __new__(type,ob,callback,key):\n self=ref.__new__(type,ob,callback)\n self.key=key\n return self\n \n def __init__(self,ob,callback,key):\n super().__init__(ob,callback)\n \n \nclass WeakKeyDictionary(_collections_abc.MutableMapping):\n ''\n\n\n\n\n\n\n\n \n \n def __init__(self,dict=None ):\n self.data={}\n def remove(k,selfref=ref(self)):\n self=selfref()\n if self is not None :\n if self._iterating:\n self._pending_removals.append(k)\n else :\n del self.data[k]\n self._remove=remove\n \n self._pending_removals=[]\n self._iterating=set()\n self._dirty_len=False\n if dict is not None :\n self.update(dict)\n \n def _commit_removals(self):\n \n \n \n \n l=self._pending_removals\n d=self.data\n while l:\n try :\n del d[l.pop()]\n except KeyError:\n pass\n \n def _scrub_removals(self):\n d=self.data\n self._pending_removals=[k for k in self._pending_removals if k in d]\n self._dirty_len=False\n \n def __delitem__(self,key):\n self._dirty_len=True\n del self.data[ref(key)]\n \n def __getitem__(self,key):\n return self.data[ref(key)]\n \n def __len__(self):\n if self._dirty_len and self._pending_removals:\n \n \n self._scrub_removals()\n return len(self.data)-len(self._pending_removals)\n \n def __repr__(self):\n return \"<%s at %#x>\"%(self.__class__.__name__,id(self))\n \n def __setitem__(self,key,value):\n self.data[ref(key,self._remove)]=value\n \n def copy(self):\n new=WeakKeyDictionary()\n for key,value in self.data.items():\n o=key()\n if o is not None :\n new[o]=value\n return new\n \n __copy__=copy\n \n def __deepcopy__(self,memo):\n from copy import deepcopy\n new=self.__class__()\n for key,value in self.data.items():\n o=key()\n if o is not None :\n new[o]=deepcopy(value,memo)\n return new\n \n def get(self,key,default=None ):\n return self.data.get(ref(key),default)\n \n def __contains__(self,key):\n try :\n wr=ref(key)\n except TypeError:\n return False\n return wr in self.data\n \n def items(self):\n with _IterationGuard(self):\n for wr,value in self.data.items():\n key=wr()\n if key is not None :\n yield key,value\n \n def keys(self):\n with _IterationGuard(self):\n for wr in self.data:\n obj=wr()\n if obj is not None :\n yield obj\n \n __iter__=keys\n \n def values(self):\n with _IterationGuard(self):\n for wr,value in self.data.items():\n if wr()is not None :\n yield value\n \n def keyrefs(self):\n ''\n\n\n\n\n\n\n\n \n return list(self.data)\n \n def popitem(self):\n self._dirty_len=True\n while True :\n key,value=self.data.popitem()\n o=key()\n if o is not None :\n return o,value\n \n def pop(self,key,*args):\n self._dirty_len=True\n return self.data.pop(ref(key),*args)\n \n def setdefault(self,key,default=None ):\n return self.data.setdefault(ref(key,self._remove),default)\n \n def update(self,dict=None ,**kwargs):\n d=self.data\n if dict is not None :\n if not hasattr(dict,\"items\"):\n dict=type({})(dict)\n for key,value in dict.items():\n d[ref(key,self._remove)]=value\n if len(kwargs):\n self.update(kwargs)\n \n \nclass finalize:\n ''\n\n\n\n\n\n\n\n\n\n\n \n \n \n \n \n \n __slots__=()\n _registry={}\n _shutdown=False\n _index_iter=itertools.count()\n _dirty=False\n _registered_with_atexit=False\n \n class _Info:\n __slots__=(\"weakref\",\"func\",\"args\",\"kwargs\",\"atexit\",\"index\")\n \n def __init__(self,obj,func,*args,**kwargs):\n if not self._registered_with_atexit:\n \n \n import atexit\n atexit.register(self._exitfunc)\n finalize._registered_with_atexit=True\n info=self._Info()\n info.weakref=ref(obj,self)\n info.func=func\n info.args=args\n info.kwargs=kwargs or None\n info.atexit=True\n info.index=next(self._index_iter)\n self._registry[self]=info\n finalize._dirty=True\n \n def __call__(self,_=None ):\n ''\n \n info=self._registry.pop(self,None )\n if info and not self._shutdown:\n return info.func(*info.args,**(info.kwargs or {}))\n \n def detach(self):\n ''\n \n info=self._registry.get(self)\n obj=info and info.weakref()\n if obj is not None and self._registry.pop(self,None ):\n return (obj,info.func,info.args,info.kwargs or {})\n \n def peek(self):\n ''\n \n info=self._registry.get(self)\n obj=info and info.weakref()\n if obj is not None :\n return (obj,info.func,info.args,info.kwargs or {})\n \n @property\n def alive(self):\n ''\n return self in self._registry\n \n @property\n def atexit(self):\n ''\n info=self._registry.get(self)\n return bool(info)and info.atexit\n \n @atexit.setter\n def atexit(self,value):\n info=self._registry.get(self)\n if info:\n info.atexit=bool(value)\n \n def __repr__(self):\n info=self._registry.get(self)\n obj=info and info.weakref()\n if obj is None :\n return '<%s object at %#x; dead>'%(type(self).__name__,id(self))\n else :\n return '<%s object at %#x; for %r at %#x>'%\\\n (type(self).__name__,id(self),type(obj).__name__,id(obj))\n \n @classmethod\n def _select_for_exit(cls):\n \n L=[(f,i)for (f,i)in cls._registry.items()if i.atexit]\n L.sort(key=lambda item:item[1].index)\n return [f for (f,i)in L]\n \n @classmethod\n def _exitfunc(cls):\n \n \n \n reenable_gc=False\n try :\n if cls._registry:\n import gc\n if gc.isenabled():\n reenable_gc=True\n gc.disable()\n pending=None\n while True :\n if pending is None or finalize._dirty:\n pending=cls._select_for_exit()\n finalize._dirty=False\n if not pending:\n break\n f=pending.pop()\n try :\n \n \n \n \n f()\n except Exception:\n sys.excepthook(*sys.exc_info())\n assert f not in cls._registry\n finally :\n \n finalize._shutdown=True\n if reenable_gc:\n gc.enable()\n", ["_collections_abc", "_weakref", "_weakrefset", "atexit", "copy", "gc", "itertools", "sys"]], "datetime": [".py", "''\n\n\n\n\n\nimport time as _time\nimport math as _math\n\ndef _cmp(x,y):\n return 0 if x ==y else 1 if x >y else -1\n \nMINYEAR=1\nMAXYEAR=9999\n_MAXORDINAL=3652059\n\n\n\n\n\n\n\n\n\n\n\n_DAYS_IN_MONTH=[-1,31,28,31,30,31,30,31,31,30,31,30,31]\n\n_DAYS_BEFORE_MONTH=[-1]\ndbm=0\nfor dim in _DAYS_IN_MONTH[1:]:\n _DAYS_BEFORE_MONTH.append(dbm)\n dbm +=dim\ndel dbm,dim\n\ndef _is_leap(year):\n ''\n return year %4 ==0 and (year %100 !=0 or year %400 ==0)\n \ndef _days_before_year(year):\n ''\n y=year -1\n return y *365+y //4 -y //100+y //400\n \ndef _days_in_month(year,month):\n ''\n assert 1 <=month <=12,month\n if month ==2 and _is_leap(year):\n return 29\n return _DAYS_IN_MONTH[month]\n \ndef _days_before_month(year,month):\n ''\n assert 1 <=month <=12,'month must be in 1..12'\n return _DAYS_BEFORE_MONTH[month]+(month >2 and _is_leap(year))\n \ndef _ymd2ord(year,month,day):\n ''\n assert 1 <=month <=12,'month must be in 1..12'\n dim=_days_in_month(year,month)\n assert 1 <=day <=dim,('day must be in 1..%d'%dim)\n return (_days_before_year(year)+\n _days_before_month(year,month)+\n day)\n \n_DI400Y=_days_before_year(401)\n_DI100Y=_days_before_year(101)\n_DI4Y=_days_before_year(5)\n\n\n\nassert _DI4Y ==4 *365+1\n\n\n\nassert _DI400Y ==4 *_DI100Y+1\n\n\n\nassert _DI100Y ==25 *_DI4Y -1\n\ndef _ord2ymd(n):\n ''\n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n n -=1\n n400,n=divmod(n,_DI400Y)\n year=n400 *400+1\n \n \n \n \n \n \n n100,n=divmod(n,_DI100Y)\n \n \n n4,n=divmod(n,_DI4Y)\n \n \n \n n1,n=divmod(n,365)\n \n year +=n100 *100+n4 *4+n1\n if n1 ==4 or n100 ==4:\n assert n ==0\n return year -1,12,31\n \n \n \n leapyear=n1 ==3 and (n4 !=24 or n100 ==3)\n assert leapyear ==_is_leap(year)\n month=(n+50)>>5\n preceding=_DAYS_BEFORE_MONTH[month]+(month >2 and leapyear)\n if preceding >n:\n month -=1\n preceding -=_DAYS_IN_MONTH[month]+(month ==2 and leapyear)\n n -=preceding\n assert 0 <=n <_days_in_month(year,month)\n \n \n \n return year,month,n+1\n \n \n_MONTHNAMES=[None ,\"Jan\",\"Feb\",\"Mar\",\"Apr\",\"May\",\"Jun\",\n\"Jul\",\"Aug\",\"Sep\",\"Oct\",\"Nov\",\"Dec\"]\n_DAYNAMES=[None ,\"Mon\",\"Tue\",\"Wed\",\"Thu\",\"Fri\",\"Sat\",\"Sun\"]\n\n\ndef _build_struct_time(y,m,d,hh,mm,ss,dstflag):\n wday=(_ymd2ord(y,m,d)+6)%7\n dnum=_days_before_month(y,m)+d\n return _time.struct_time((y,m,d,hh,mm,ss,wday,dnum,dstflag))\n \ndef _format_time(hh,mm,ss,us,timespec='auto'):\n specs={\n 'hours':'{:02d}',\n 'minutes':'{:02d}:{:02d}',\n 'seconds':'{:02d}:{:02d}:{:02d}',\n 'milliseconds':'{:02d}:{:02d}:{:02d}.{:03d}',\n 'microseconds':'{:02d}:{:02d}:{:02d}.{:06d}'\n }\n \n if timespec =='auto':\n \n timespec='microseconds'if us else 'seconds'\n elif timespec =='milliseconds':\n us //=1000\n try :\n fmt=specs[timespec]\n except KeyError:\n raise ValueError('Unknown timespec value')\n else :\n return fmt.format(hh,mm,ss,us)\n \ndef _format_offset(off):\n s=''\n if off is not None :\n if off.days <0:\n sign=\"-\"\n off=-off\n else :\n sign=\"+\"\n hh,mm=divmod(off,timedelta(hours=1))\n mm,ss=divmod(mm,timedelta(minutes=1))\n s +=\"%s%02d:%02d\"%(sign,hh,mm)\n if ss or ss.microseconds:\n s +=\":%02d\"%ss.seconds\n \n if ss.microseconds:\n s +='.%06d'%ss.microseconds\n return s\n \n \ndef _wrap_strftime(object,format,timetuple):\n\n freplace=None\n zreplace=None\n Zreplace=None\n \n \n newformat=[]\n push=newformat.append\n i,n=0,len(format)\n while i <n:\n ch=format[i]\n i +=1\n if ch =='%':\n if i <n:\n ch=format[i]\n i +=1\n if ch =='f':\n if freplace is None :\n freplace='%06d'%getattr(object,\n 'microsecond',0)\n newformat.append(freplace)\n elif ch =='z':\n if zreplace is None :\n zreplace=\"\"\n if hasattr(object,\"utcoffset\"):\n offset=object.utcoffset()\n if offset is not None :\n sign='+'\n if offset.days <0:\n offset=-offset\n sign='-'\n h,rest=divmod(offset,timedelta(hours=1))\n m,rest=divmod(rest,timedelta(minutes=1))\n s=rest.seconds\n u=offset.microseconds\n if u:\n zreplace='%c%02d%02d%02d.%06d'%(sign,h,m,s,u)\n elif s:\n zreplace='%c%02d%02d%02d'%(sign,h,m,s)\n else :\n zreplace='%c%02d%02d'%(sign,h,m)\n assert '%'not in zreplace\n newformat.append(zreplace)\n elif ch =='Z':\n if Zreplace is None :\n Zreplace=\"\"\n if hasattr(object,\"tzname\"):\n s=object.tzname()\n if s is not None :\n \n Zreplace=s.replace('%','%%')\n newformat.append(Zreplace)\n else :\n push('%')\n push(ch)\n else :\n push('%')\n else :\n push(ch)\n newformat=\"\".join(newformat)\n return _time.strftime(newformat,timetuple)\n \n \ndef _parse_isoformat_date(dtstr):\n\n\n year=int(dtstr[0:4])\n if dtstr[4]!='-':\n raise ValueError('Invalid date separator: %s'%dtstr[4])\n \n month=int(dtstr[5:7])\n \n if dtstr[7]!='-':\n raise ValueError('Invalid date separator')\n \n day=int(dtstr[8:10])\n \n return [year,month,day]\n \ndef _parse_hh_mm_ss_ff(tstr):\n\n len_str=len(tstr)\n \n time_comps=[0,0,0,0]\n pos=0\n for comp in range(0,3):\n if (len_str -pos)<2:\n raise ValueError('Incomplete time component')\n \n time_comps[comp]=int(tstr[pos:pos+2])\n \n pos +=2\n next_char=tstr[pos:pos+1]\n \n if not next_char or comp >=2:\n break\n \n if next_char !=':':\n raise ValueError('Invalid time separator: %c'%next_char)\n \n pos +=1\n \n if pos <len_str:\n if tstr[pos]!='.':\n raise ValueError('Invalid microsecond component')\n else :\n pos +=1\n \n len_remainder=len_str -pos\n if len_remainder not in (3,6):\n raise ValueError('Invalid microsecond component')\n \n time_comps[3]=int(tstr[pos:])\n if len_remainder ==3:\n time_comps[3]*=1000\n \n return time_comps\n \ndef _parse_isoformat_time(tstr):\n\n len_str=len(tstr)\n if len_str <2:\n raise ValueError('Isoformat time too short')\n \n \n tz_pos=(tstr.find('-')+1 or tstr.find('+')+1)\n timestr=tstr[:tz_pos -1]if tz_pos >0 else tstr\n \n time_comps=_parse_hh_mm_ss_ff(timestr)\n \n tzi=None\n if tz_pos >0:\n tzstr=tstr[tz_pos:]\n \n \n \n \n \n \n if len(tzstr)not in (5,8,15):\n raise ValueError('Malformed time zone string')\n \n tz_comps=_parse_hh_mm_ss_ff(tzstr)\n if all(x ==0 for x in tz_comps):\n tzi=timezone.utc\n else :\n tzsign=-1 if tstr[tz_pos -1]=='-'else 1\n \n td=timedelta(hours=tz_comps[0],minutes=tz_comps[1],\n seconds=tz_comps[2],microseconds=tz_comps[3])\n \n tzi=timezone(tzsign *td)\n \n time_comps.append(tzi)\n \n return time_comps\n \n \n \ndef _check_tzname(name):\n if name is not None and not isinstance(name,str):\n raise TypeError(\"tzinfo.tzname() must return None or string, \"\n \"not '%s'\"%type(name))\n \n \n \n \n \n \n \ndef _check_utc_offset(name,offset):\n assert name in (\"utcoffset\",\"dst\")\n if offset is None :\n return\n if not isinstance(offset,timedelta):\n raise TypeError(\"tzinfo.%s() must return None \"\n \"or timedelta, not '%s'\"%(name,type(offset)))\n if not -timedelta(1)<offset <timedelta(1):\n raise ValueError(\"%s()=%s, must be strictly between \"\n \"-timedelta(hours=24) and timedelta(hours=24)\"%\n (name,offset))\n \ndef _check_int_field(value):\n if isinstance(value,int):\n return value\n if not isinstance(value,float):\n try :\n value=value.__int__()\n except AttributeError:\n pass\n else :\n if isinstance(value,int):\n return value\n raise TypeError('__int__ returned non-int (type %s)'%\n type(value).__name__)\n raise TypeError('an integer is required (got type %s)'%\n type(value).__name__)\n raise TypeError('integer argument expected, got float')\n \ndef _check_date_fields(year,month,day):\n year=_check_int_field(year)\n month=_check_int_field(month)\n day=_check_int_field(day)\n if not MINYEAR <=year <=MAXYEAR:\n raise ValueError('year must be in %d..%d'%(MINYEAR,MAXYEAR),year)\n if not 1 <=month <=12:\n raise ValueError('month must be in 1..12',month)\n dim=_days_in_month(year,month)\n if not 1 <=day <=dim:\n raise ValueError('day must be in 1..%d'%dim,day)\n return year,month,day\n \ndef _check_time_fields(hour,minute,second,microsecond,fold):\n hour=_check_int_field(hour)\n minute=_check_int_field(minute)\n second=_check_int_field(second)\n microsecond=_check_int_field(microsecond)\n if not 0 <=hour <=23:\n raise ValueError('hour must be in 0..23',hour)\n if not 0 <=minute <=59:\n raise ValueError('minute must be in 0..59',minute)\n if not 0 <=second <=59:\n raise ValueError('second must be in 0..59',second)\n if not 0 <=microsecond <=999999:\n raise ValueError('microsecond must be in 0..999999',microsecond)\n if fold not in (0,1):\n raise ValueError('fold must be either 0 or 1',fold)\n return hour,minute,second,microsecond,fold\n \ndef _check_tzinfo_arg(tz):\n if tz is not None and not isinstance(tz,tzinfo):\n raise TypeError(\"tzinfo argument must be None or of a tzinfo subclass\")\n \ndef _cmperror(x,y):\n raise TypeError(\"can't compare '%s' to '%s'\"%(\n type(x).__name__,type(y).__name__))\n \ndef _divide_and_round(a,b):\n ''\n\n\n\n \n \n \n q,r=divmod(a,b)\n \n \n \n r *=2\n greater_than_half=r >b if b >0 else r <b\n if greater_than_half or r ==b and q %2 ==1:\n q +=1\n \n return q\n \n \nclass timedelta:\n ''\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n \n __slots__='_days','_seconds','_microseconds','_hashcode'\n \n def __new__(cls,days=0,seconds=0,microseconds=0,\n milliseconds=0,minutes=0,hours=0,weeks=0):\n \n \n \n \n \n \n \n \n \n \n \n \n d=s=us=0\n \n \n days +=weeks *7\n seconds +=minutes *60+hours *3600\n microseconds +=milliseconds *1000\n \n \n \n if isinstance(days,float):\n dayfrac,days=_math.modf(days)\n daysecondsfrac,daysecondswhole=_math.modf(dayfrac *(24. *3600.))\n assert daysecondswhole ==int(daysecondswhole)\n s=int(daysecondswhole)\n assert days ==int(days)\n d=int(days)\n else :\n daysecondsfrac=0.0\n d=days\n assert isinstance(daysecondsfrac,float)\n assert abs(daysecondsfrac)<=1.0\n assert isinstance(d,int)\n assert abs(s)<=24 *3600\n \n \n if isinstance(seconds,float):\n secondsfrac,seconds=_math.modf(seconds)\n assert seconds ==int(seconds)\n seconds=int(seconds)\n secondsfrac +=daysecondsfrac\n assert abs(secondsfrac)<=2.0\n else :\n secondsfrac=daysecondsfrac\n \n assert isinstance(secondsfrac,float)\n assert abs(secondsfrac)<=2.0\n \n assert isinstance(seconds,int)\n days,seconds=divmod(seconds,24 *3600)\n d +=days\n s +=int(seconds)\n assert isinstance(s,int)\n assert abs(s)<=2 *24 *3600\n \n \n usdouble=secondsfrac *1e6\n assert abs(usdouble)<2.1e6\n \n \n if isinstance(microseconds,float):\n microseconds=round(microseconds+usdouble)\n seconds,microseconds=divmod(microseconds,1000000)\n days,seconds=divmod(seconds,24 *3600)\n d +=days\n s +=seconds\n else :\n microseconds=int(microseconds)\n seconds,microseconds=divmod(microseconds,1000000)\n days,seconds=divmod(seconds,24 *3600)\n d +=days\n s +=seconds\n microseconds=round(microseconds+usdouble)\n assert isinstance(s,int)\n assert isinstance(microseconds,int)\n assert abs(s)<=3 *24 *3600\n assert abs(microseconds)<3.1e6\n \n \n seconds,us=divmod(microseconds,1000000)\n s +=seconds\n days,s=divmod(s,24 *3600)\n d +=days\n \n assert isinstance(d,int)\n assert isinstance(s,int)and 0 <=s <24 *3600\n assert isinstance(us,int)and 0 <=us <1000000\n \n if abs(d)>999999999:\n raise OverflowError(\"timedelta # of days is too large: %d\"%d)\n \n self=object.__new__(cls)\n self._days=d\n self._seconds=s\n self._microseconds=us\n self._hashcode=-1\n return self\n \n def __repr__(self):\n args=[]\n if self._days:\n args.append(\"days=%d\"%self._days)\n if self._seconds:\n args.append(\"seconds=%d\"%self._seconds)\n if self._microseconds:\n args.append(\"microseconds=%d\"%self._microseconds)\n if not args:\n args.append('0')\n return \"%s.%s(%s)\"%(self.__class__.__module__,\n self.__class__.__qualname__,\n ', '.join(args))\n \n def __str__(self):\n mm,ss=divmod(self._seconds,60)\n hh,mm=divmod(mm,60)\n s=\"%d:%02d:%02d\"%(hh,mm,ss)\n if self._days:\n def plural(n):\n return n,abs(n)!=1 and \"s\"or \"\"\n s=(\"%d day%s, \"%plural(self._days))+s\n if self._microseconds:\n s=s+\".%06d\"%self._microseconds\n return s\n \n def total_seconds(self):\n ''\n return ((self.days *86400+self.seconds)*10 **6+\n self.microseconds)/10 **6\n \n \n @property\n def days(self):\n ''\n return self._days\n \n @property\n def seconds(self):\n ''\n return self._seconds\n \n @property\n def microseconds(self):\n ''\n return self._microseconds\n \n def __add__(self,other):\n if isinstance(other,timedelta):\n \n \n return timedelta(self._days+other._days,\n self._seconds+other._seconds,\n self._microseconds+other._microseconds)\n return NotImplemented\n \n __radd__=__add__\n \n def __sub__(self,other):\n if isinstance(other,timedelta):\n \n \n return timedelta(self._days -other._days,\n self._seconds -other._seconds,\n self._microseconds -other._microseconds)\n return NotImplemented\n \n def __rsub__(self,other):\n if isinstance(other,timedelta):\n return -self+other\n return NotImplemented\n \n def __neg__(self):\n \n \n return timedelta(-self._days,\n -self._seconds,\n -self._microseconds)\n \n def __pos__(self):\n return self\n \n def __abs__(self):\n if self._days <0:\n return -self\n else :\n return self\n \n def __mul__(self,other):\n if isinstance(other,int):\n \n \n return timedelta(self._days *other,\n self._seconds *other,\n self._microseconds *other)\n if isinstance(other,float):\n usec=self._to_microseconds()\n a,b=other.as_integer_ratio()\n return timedelta(0,0,_divide_and_round(usec *a,b))\n return NotImplemented\n \n __rmul__=__mul__\n \n def _to_microseconds(self):\n return ((self._days *(24 *3600)+self._seconds)*1000000+\n self._microseconds)\n \n def __floordiv__(self,other):\n if not isinstance(other,(int,timedelta)):\n return NotImplemented\n usec=self._to_microseconds()\n if isinstance(other,timedelta):\n return usec //other._to_microseconds()\n if isinstance(other,int):\n return timedelta(0,0,usec //other)\n \n def __truediv__(self,other):\n if not isinstance(other,(int,float,timedelta)):\n return NotImplemented\n usec=self._to_microseconds()\n if isinstance(other,timedelta):\n return usec /other._to_microseconds()\n if isinstance(other,int):\n return timedelta(0,0,_divide_and_round(usec,other))\n if isinstance(other,float):\n a,b=other.as_integer_ratio()\n return timedelta(0,0,_divide_and_round(b *usec,a))\n \n def __mod__(self,other):\n if isinstance(other,timedelta):\n r=self._to_microseconds()%other._to_microseconds()\n return timedelta(0,0,r)\n return NotImplemented\n \n def __divmod__(self,other):\n if isinstance(other,timedelta):\n q,r=divmod(self._to_microseconds(),\n other._to_microseconds())\n return q,timedelta(0,0,r)\n return NotImplemented\n \n \n \n def __eq__(self,other):\n if isinstance(other,timedelta):\n return self._cmp(other)==0\n else :\n return False\n \n def __le__(self,other):\n if isinstance(other,timedelta):\n return self._cmp(other)<=0\n else :\n _cmperror(self,other)\n \n def __lt__(self,other):\n if isinstance(other,timedelta):\n return self._cmp(other)<0\n else :\n _cmperror(self,other)\n \n def __ge__(self,other):\n if isinstance(other,timedelta):\n return self._cmp(other)>=0\n else :\n _cmperror(self,other)\n \n def __gt__(self,other):\n if isinstance(other,timedelta):\n return self._cmp(other)>0\n else :\n _cmperror(self,other)\n \n def _cmp(self,other):\n assert isinstance(other,timedelta)\n return _cmp(self._getstate(),other._getstate())\n \n def __hash__(self):\n if self._hashcode ==-1:\n self._hashcode=hash(self._getstate())\n return self._hashcode\n \n def __bool__(self):\n return (self._days !=0 or\n self._seconds !=0 or\n self._microseconds !=0)\n \n \n \n def _getstate(self):\n return (self._days,self._seconds,self._microseconds)\n \n def __reduce__(self):\n return (self.__class__,self._getstate())\n \ntimedelta.min=timedelta(-999999999)\ntimedelta.max=timedelta(days=999999999,hours=23,minutes=59,seconds=59,\nmicroseconds=999999)\ntimedelta.resolution=timedelta(microseconds=1)\n\nclass date:\n ''\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n \n __slots__='_year','_month','_day','_hashcode'\n \n def __new__(cls,year,month=None ,day=None ):\n ''\n\n\n\n\n \n if month is None and isinstance(year,bytes)and len(year)==4 and\\\n 1 <=year[2]<=12:\n \n self=object.__new__(cls)\n self.__setstate(year)\n self._hashcode=-1\n return self\n year,month,day=_check_date_fields(year,month,day)\n self=object.__new__(cls)\n self._year=year\n self._month=month\n self._day=day\n self._hashcode=-1\n return self\n \n \n \n @classmethod\n def fromtimestamp(cls,t):\n ''\n y,m,d,hh,mm,ss,weekday,jday,dst=_time.localtime(t)\n return cls(y,m,d)\n \n @classmethod\n def today(cls):\n ''\n t=_time.time()\n return cls.fromtimestamp(t)\n \n @classmethod\n def fromordinal(cls,n):\n ''\n\n\n\n \n y,m,d=_ord2ymd(n)\n return cls(y,m,d)\n \n @classmethod\n def fromisoformat(cls,date_string):\n ''\n if not isinstance(date_string,str):\n raise TypeError('fromisoformat: argument must be str')\n \n try :\n assert len(date_string)==10\n return cls(*_parse_isoformat_date(date_string))\n except Exception:\n raise ValueError('Invalid isoformat string: %s'%date_string)\n \n \n \n \n def __repr__(self):\n ''\n\n\n\n\n\n\n\n\n \n return \"%s.%s(%d, %d, %d)\"%(self.__class__.__module__,\n self.__class__.__qualname__,\n self._year,\n self._month,\n self._day)\n \n \n \n \n \n \n def ctime(self):\n ''\n weekday=self.toordinal()%7 or 7\n return \"%s %s %2d 00:00:00 %04d\"%(\n _DAYNAMES[weekday],\n _MONTHNAMES[self._month],\n self._day,self._year)\n \n def strftime(self,fmt):\n ''\n return _wrap_strftime(self,fmt,self.timetuple())\n \n def __format__(self,fmt):\n if not isinstance(fmt,str):\n raise TypeError(\"must be str, not %s\"%type(fmt).__name__)\n if len(fmt)!=0:\n return self.strftime(fmt)\n return str(self)\n \n def isoformat(self):\n ''\n\n\n\n\n\n\n \n return \"%04d-%02d-%02d\"%(self._year,self._month,self._day)\n \n __str__=isoformat\n \n \n @property\n def year(self):\n ''\n return self._year\n \n @property\n def month(self):\n ''\n return self._month\n \n @property\n def day(self):\n ''\n return self._day\n \n \n \n \n def timetuple(self):\n ''\n return _build_struct_time(self._year,self._month,self._day,\n 0,0,0,-1)\n \n def toordinal(self):\n ''\n\n\n\n \n return _ymd2ord(self._year,self._month,self._day)\n \n def replace(self,year=None ,month=None ,day=None ):\n ''\n if year is None :\n year=self._year\n if month is None :\n month=self._month\n if day is None :\n day=self._day\n return type(self)(year,month,day)\n \n \n \n def __eq__(self,other):\n if isinstance(other,date):\n return self._cmp(other)==0\n return NotImplemented\n \n def __le__(self,other):\n if isinstance(other,date):\n return self._cmp(other)<=0\n return NotImplemented\n \n def __lt__(self,other):\n if isinstance(other,date):\n return self._cmp(other)<0\n return NotImplemented\n \n def __ge__(self,other):\n if isinstance(other,date):\n return self._cmp(other)>=0\n return NotImplemented\n \n def __gt__(self,other):\n if isinstance(other,date):\n return self._cmp(other)>0\n return NotImplemented\n \n def _cmp(self,other):\n assert isinstance(other,date)\n y,m,d=self._year,self._month,self._day\n y2,m2,d2=other._year,other._month,other._day\n return _cmp((y,m,d),(y2,m2,d2))\n \n def __hash__(self):\n ''\n if self._hashcode ==-1:\n self._hashcode=hash(self._getstate())\n return self._hashcode\n \n \n \n def __add__(self,other):\n ''\n if isinstance(other,timedelta):\n o=self.toordinal()+other.days\n if 0 <o <=_MAXORDINAL:\n return date.fromordinal(o)\n raise OverflowError(\"result out of range\")\n return NotImplemented\n \n __radd__=__add__\n \n def __sub__(self,other):\n ''\n if isinstance(other,timedelta):\n return self+timedelta(-other.days)\n if isinstance(other,date):\n days1=self.toordinal()\n days2=other.toordinal()\n return timedelta(days1 -days2)\n return NotImplemented\n \n def weekday(self):\n ''\n return (self.toordinal()+6)%7\n \n \n \n def isoweekday(self):\n ''\n \n return self.toordinal()%7 or 7\n \n def isocalendar(self):\n ''\n\n\n\n\n\n\n\n\n\n\n \n year=self._year\n week1monday=_isoweek1monday(year)\n today=_ymd2ord(self._year,self._month,self._day)\n \n week,day=divmod(today -week1monday,7)\n if week <0:\n year -=1\n week1monday=_isoweek1monday(year)\n week,day=divmod(today -week1monday,7)\n elif week >=52:\n if today >=_isoweek1monday(year+1):\n year +=1\n week=0\n return year,week+1,day+1\n \n \n \n def _getstate(self):\n yhi,ylo=divmod(self._year,256)\n return bytes([yhi,ylo,self._month,self._day]),\n \n def __setstate(self,string):\n yhi,ylo,self._month,self._day=string\n self._year=yhi *256+ylo\n \n def __reduce__(self):\n return (self.__class__,self._getstate())\n \n_date_class=date\n\ndate.min=date(1,1,1)\ndate.max=date(9999,12,31)\ndate.resolution=timedelta(days=1)\n\n\nclass tzinfo:\n ''\n\n\n \n __slots__=()\n \n def tzname(self,dt):\n ''\n raise NotImplementedError(\"tzinfo subclass must override tzname()\")\n \n def utcoffset(self,dt):\n ''\n raise NotImplementedError(\"tzinfo subclass must override utcoffset()\")\n \n def dst(self,dt):\n ''\n\n\n\n \n raise NotImplementedError(\"tzinfo subclass must override dst()\")\n \n def fromutc(self,dt):\n ''\n \n if not isinstance(dt,datetime):\n raise TypeError(\"fromutc() requires a datetime argument\")\n if dt.tzinfo is not self:\n raise ValueError(\"dt.tzinfo is not self\")\n \n dtoff=dt.utcoffset()\n if dtoff is None :\n raise ValueError(\"fromutc() requires a non-None utcoffset() \"\n \"result\")\n \n \n \n dtdst=dt.dst()\n if dtdst is None :\n raise ValueError(\"fromutc() requires a non-None dst() result\")\n delta=dtoff -dtdst\n if delta:\n dt +=delta\n dtdst=dt.dst()\n if dtdst is None :\n raise ValueError(\"fromutc(): dt.dst gave inconsistent \"\n \"results; cannot convert\")\n return dt+dtdst\n \n \n \n def __reduce__(self):\n getinitargs=getattr(self,\"__getinitargs__\",None )\n if getinitargs:\n args=getinitargs()\n else :\n args=()\n getstate=getattr(self,\"__getstate__\",None )\n if getstate:\n state=getstate()\n else :\n state=getattr(self,\"__dict__\",None )or None\n if state is None :\n return (self.__class__,args)\n else :\n return (self.__class__,args,state)\n \n_tzinfo_class=tzinfo\n\nclass time:\n ''\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n \n __slots__='_hour','_minute','_second','_microsecond','_tzinfo','_hashcode','_fold'\n \n def __new__(cls,hour=0,minute=0,second=0,microsecond=0,tzinfo=None ,*,fold=0):\n ''\n\n\n\n\n\n\n\n \n if isinstance(hour,bytes)and len(hour)==6 and hour[0]&0x7F <24:\n \n self=object.__new__(cls)\n self.__setstate(hour,minute or None )\n self._hashcode=-1\n return self\n hour,minute,second,microsecond,fold=_check_time_fields(\n hour,minute,second,microsecond,fold)\n _check_tzinfo_arg(tzinfo)\n self=object.__new__(cls)\n self._hour=hour\n self._minute=minute\n self._second=second\n self._microsecond=microsecond\n self._tzinfo=tzinfo\n self._hashcode=-1\n self._fold=fold\n return self\n \n \n @property\n def hour(self):\n ''\n return self._hour\n \n @property\n def minute(self):\n ''\n return self._minute\n \n @property\n def second(self):\n ''\n return self._second\n \n @property\n def microsecond(self):\n ''\n return self._microsecond\n \n @property\n def tzinfo(self):\n ''\n return self._tzinfo\n \n @property\n def fold(self):\n return self._fold\n \n \n \n \n \n def __eq__(self,other):\n if isinstance(other,time):\n return self._cmp(other,allow_mixed=True )==0\n else :\n return False\n \n def __le__(self,other):\n if isinstance(other,time):\n return self._cmp(other)<=0\n else :\n _cmperror(self,other)\n \n def __lt__(self,other):\n if isinstance(other,time):\n return self._cmp(other)<0\n else :\n _cmperror(self,other)\n \n def __ge__(self,other):\n if isinstance(other,time):\n return self._cmp(other)>=0\n else :\n _cmperror(self,other)\n \n def __gt__(self,other):\n if isinstance(other,time):\n return self._cmp(other)>0\n else :\n _cmperror(self,other)\n \n def _cmp(self,other,allow_mixed=False ):\n assert isinstance(other,time)\n mytz=self._tzinfo\n ottz=other._tzinfo\n myoff=otoff=None\n \n if mytz is ottz:\n base_compare=True\n else :\n myoff=self.utcoffset()\n otoff=other.utcoffset()\n base_compare=myoff ==otoff\n \n if base_compare:\n return _cmp((self._hour,self._minute,self._second,\n self._microsecond),\n (other._hour,other._minute,other._second,\n other._microsecond))\n if myoff is None or otoff is None :\n if allow_mixed:\n return 2\n else :\n raise TypeError(\"cannot compare naive and aware times\")\n myhhmm=self._hour *60+self._minute -myoff //timedelta(minutes=1)\n othhmm=other._hour *60+other._minute -otoff //timedelta(minutes=1)\n return _cmp((myhhmm,self._second,self._microsecond),\n (othhmm,other._second,other._microsecond))\n \n def __hash__(self):\n ''\n if self._hashcode ==-1:\n if self.fold:\n t=self.replace(fold=0)\n else :\n t=self\n tzoff=t.utcoffset()\n if not tzoff:\n self._hashcode=hash(t._getstate()[0])\n else :\n h,m=divmod(timedelta(hours=self.hour,minutes=self.minute)-tzoff,\n timedelta(hours=1))\n assert not m %timedelta(minutes=1),\"whole minute\"\n m //=timedelta(minutes=1)\n if 0 <=h <24:\n self._hashcode=hash(time(h,m,self.second,self.microsecond))\n else :\n self._hashcode=hash((h,m,self.second,self.microsecond))\n return self._hashcode\n \n \n \n def _tzstr(self):\n ''\n off=self.utcoffset()\n return _format_offset(off)\n \n def __repr__(self):\n ''\n if self._microsecond !=0:\n s=\", %d, %d\"%(self._second,self._microsecond)\n elif self._second !=0:\n s=\", %d\"%self._second\n else :\n s=\"\"\n s=\"%s.%s(%d, %d%s)\"%(self.__class__.__module__,\n self.__class__.__qualname__,\n self._hour,self._minute,s)\n if self._tzinfo is not None :\n assert s[-1:]==\")\"\n s=s[:-1]+\", tzinfo=%r\"%self._tzinfo+\")\"\n if self._fold:\n assert s[-1:]==\")\"\n s=s[:-1]+\", fold=1)\"\n return s\n \n def isoformat(self,timespec='auto'):\n ''\n\n\n\n\n\n\n \n s=_format_time(self._hour,self._minute,self._second,\n self._microsecond,timespec)\n tz=self._tzstr()\n if tz:\n s +=tz\n return s\n \n __str__=isoformat\n \n @classmethod\n def fromisoformat(cls,time_string):\n ''\n if not isinstance(time_string,str):\n raise TypeError('fromisoformat: argument must be str')\n \n try :\n return cls(*_parse_isoformat_time(time_string))\n except Exception:\n raise ValueError('Invalid isoformat string: %s'%time_string)\n \n \n def strftime(self,fmt):\n ''\n\n \n \n \n timetuple=(1900,1,1,\n self._hour,self._minute,self._second,\n 0,1,-1)\n return _wrap_strftime(self,fmt,timetuple)\n \n def __format__(self,fmt):\n if not isinstance(fmt,str):\n raise TypeError(\"must be str, not %s\"%type(fmt).__name__)\n if len(fmt)!=0:\n return self.strftime(fmt)\n return str(self)\n \n \n \n def utcoffset(self):\n ''\n \n if self._tzinfo is None :\n return None\n offset=self._tzinfo.utcoffset(None )\n _check_utc_offset(\"utcoffset\",offset)\n return offset\n \n def tzname(self):\n ''\n\n\n\n\n \n if self._tzinfo is None :\n return None\n name=self._tzinfo.tzname(None )\n _check_tzname(name)\n return name\n \n def dst(self):\n ''\n\n\n\n\n\n\n \n if self._tzinfo is None :\n return None\n offset=self._tzinfo.dst(None )\n _check_utc_offset(\"dst\",offset)\n return offset\n \n def replace(self,hour=None ,minute=None ,second=None ,microsecond=None ,\n tzinfo=True ,*,fold=None ):\n ''\n if hour is None :\n hour=self.hour\n if minute is None :\n minute=self.minute\n if second is None :\n second=self.second\n if microsecond is None :\n microsecond=self.microsecond\n if tzinfo is True :\n tzinfo=self.tzinfo\n if fold is None :\n fold=self._fold\n return type(self)(hour,minute,second,microsecond,tzinfo,fold=fold)\n \n \n \n def _getstate(self,protocol=3):\n us2,us3=divmod(self._microsecond,256)\n us1,us2=divmod(us2,256)\n h=self._hour\n if self._fold and protocol >3:\n h +=128\n basestate=bytes([h,self._minute,self._second,\n us1,us2,us3])\n if self._tzinfo is None :\n return (basestate,)\n else :\n return (basestate,self._tzinfo)\n \n def __setstate(self,string,tzinfo):\n if tzinfo is not None and not isinstance(tzinfo,_tzinfo_class):\n raise TypeError(\"bad tzinfo state arg\")\n h,self._minute,self._second,us1,us2,us3=string\n if h >127:\n self._fold=1\n self._hour=h -128\n else :\n self._fold=0\n self._hour=h\n self._microsecond=(((us1 <<8)|us2)<<8)|us3\n self._tzinfo=tzinfo\n \n def __reduce_ex__(self,protocol):\n return (time,self._getstate(protocol))\n \n def __reduce__(self):\n return self.__reduce_ex__(2)\n \n_time_class=time\n\ntime.min=time(0,0,0)\ntime.max=time(23,59,59,999999)\ntime.resolution=timedelta(microseconds=1)\n\nclass datetime(date):\n ''\n\n\n\n \n __slots__=date.__slots__+time.__slots__\n \n def __new__(cls,year,month=None ,day=None ,hour=0,minute=0,second=0,\n microsecond=0,tzinfo=None ,*,fold=0):\n if isinstance(year,bytes)and len(year)==10 and 1 <=year[2]&0x7F <=12:\n \n self=object.__new__(cls)\n self.__setstate(year,month)\n self._hashcode=-1\n return self\n year,month,day=_check_date_fields(year,month,day)\n hour,minute,second,microsecond,fold=_check_time_fields(\n hour,minute,second,microsecond,fold)\n _check_tzinfo_arg(tzinfo)\n self=object.__new__(cls)\n self._year=year\n self._month=month\n self._day=day\n self._hour=hour\n self._minute=minute\n self._second=second\n self._microsecond=microsecond\n self._tzinfo=tzinfo\n self._hashcode=-1\n self._fold=fold\n return self\n \n \n @property\n def hour(self):\n ''\n return self._hour\n \n @property\n def minute(self):\n ''\n return self._minute\n \n @property\n def second(self):\n ''\n return self._second\n \n @property\n def microsecond(self):\n ''\n return self._microsecond\n \n @property\n def tzinfo(self):\n ''\n return self._tzinfo\n \n @property\n def fold(self):\n return self._fold\n \n @classmethod\n def _fromtimestamp(cls,t,utc,tz):\n ''\n\n\n \n frac,t=_math.modf(t)\n us=round(frac *1e6)\n if us >=1000000:\n t +=1\n us -=1000000\n elif us <0:\n t -=1\n us +=1000000\n \n converter=_time.gmtime if utc else _time.localtime\n y,m,d,hh,mm,ss,weekday,jday,dst=converter(t)\n ss=min(ss,59)\n result=cls(y,m,d,hh,mm,ss,us,tz)\n if tz is None :\n \n \n \n max_fold_seconds=24 *3600\n y,m,d,hh,mm,ss=converter(t -max_fold_seconds)[:6]\n probe1=cls(y,m,d,hh,mm,ss,us,tz)\n trans=result -probe1 -timedelta(0,max_fold_seconds)\n if trans.days <0:\n y,m,d,hh,mm,ss=converter(t+trans //timedelta(0,1))[:6]\n probe2=cls(y,m,d,hh,mm,ss,us,tz)\n if probe2 ==result:\n result._fold=1\n else :\n result=tz.fromutc(result)\n return result\n \n @classmethod\n def fromtimestamp(cls,t,tz=None ):\n ''\n\n\n \n _check_tzinfo_arg(tz)\n \n return cls._fromtimestamp(t,tz is not None ,tz)\n \n @classmethod\n def utcfromtimestamp(cls,t):\n ''\n return cls._fromtimestamp(t,True ,None )\n \n @classmethod\n def now(cls,tz=None ):\n ''\n t=_time.time()\n return cls.fromtimestamp(t,tz)\n \n @classmethod\n def utcnow(cls):\n ''\n t=_time.time()\n return cls.utcfromtimestamp(t)\n \n @classmethod\n def combine(cls,date,time,tzinfo=True ):\n ''\n if not isinstance(date,_date_class):\n raise TypeError(\"date argument must be a date instance\")\n if not isinstance(time,_time_class):\n raise TypeError(\"time argument must be a time instance\")\n if tzinfo is True :\n tzinfo=time.tzinfo\n return cls(date.year,date.month,date.day,\n time.hour,time.minute,time.second,time.microsecond,\n tzinfo,fold=time.fold)\n \n @classmethod\n def fromisoformat(cls,date_string):\n ''\n if not isinstance(date_string,str):\n raise TypeError('fromisoformat: argument must be str')\n \n \n dstr=date_string[0:10]\n tstr=date_string[11:]\n \n try :\n date_components=_parse_isoformat_date(dstr)\n except ValueError:\n raise ValueError('Invalid isoformat string: %s'%date_string)\n \n if tstr:\n try :\n time_components=_parse_isoformat_time(tstr)\n except ValueError:\n raise ValueError('Invalid isoformat string: %s'%date_string)\n else :\n time_components=[0,0,0,0,None ]\n \n return cls(*(date_components+time_components))\n \n def timetuple(self):\n ''\n dst=self.dst()\n if dst is None :\n dst=-1\n elif dst:\n dst=1\n else :\n dst=0\n return _build_struct_time(self.year,self.month,self.day,\n self.hour,self.minute,self.second,\n dst)\n \n def _mktime(self):\n ''\n epoch=datetime(1970,1,1)\n max_fold_seconds=24 *3600\n t=(self -epoch)//timedelta(0,1)\n def local(u):\n y,m,d,hh,mm,ss=_time.localtime(u)[:6]\n return (datetime(y,m,d,hh,mm,ss)-epoch)//timedelta(0,1)\n \n \n a=local(t)-t\n u1=t -a\n t1=local(u1)\n if t1 ==t:\n \n \n \n u2=u1+(-max_fold_seconds,max_fold_seconds)[self.fold]\n b=local(u2)-u2\n if a ==b:\n return u1\n else :\n b=t1 -u1\n assert a !=b\n u2=t -b\n t2=local(u2)\n if t2 ==t:\n return u2\n if t1 ==t:\n return u1\n \n \n return (max,min)[self.fold](u1,u2)\n \n \n def timestamp(self):\n ''\n if self._tzinfo is None :\n s=self._mktime()\n return s+self.microsecond /1e6\n else :\n return (self -_EPOCH).total_seconds()\n \n def utctimetuple(self):\n ''\n offset=self.utcoffset()\n if offset:\n self -=offset\n y,m,d=self.year,self.month,self.day\n hh,mm,ss=self.hour,self.minute,self.second\n return _build_struct_time(y,m,d,hh,mm,ss,0)\n \n def date(self):\n ''\n return date(self._year,self._month,self._day)\n \n def time(self):\n ''\n return time(self.hour,self.minute,self.second,self.microsecond,fold=self.fold)\n \n def timetz(self):\n ''\n return time(self.hour,self.minute,self.second,self.microsecond,\n self._tzinfo,fold=self.fold)\n \n def replace(self,year=None ,month=None ,day=None ,hour=None ,\n minute=None ,second=None ,microsecond=None ,tzinfo=True ,\n *,fold=None ):\n ''\n if year is None :\n year=self.year\n if month is None :\n month=self.month\n if day is None :\n day=self.day\n if hour is None :\n hour=self.hour\n if minute is None :\n minute=self.minute\n if second is None :\n second=self.second\n if microsecond is None :\n microsecond=self.microsecond\n if tzinfo is True :\n tzinfo=self.tzinfo\n if fold is None :\n fold=self.fold\n return type(self)(year,month,day,hour,minute,second,\n microsecond,tzinfo,fold=fold)\n \n def _local_timezone(self):\n if self.tzinfo is None :\n ts=self._mktime()\n else :\n ts=(self -_EPOCH)//timedelta(seconds=1)\n localtm=_time.localtime(ts)\n local=datetime(*localtm[:6])\n try :\n \n gmtoff=localtm.tm_gmtoff\n zone=localtm.tm_zone\n except AttributeError:\n delta=local -datetime(*_time.gmtime(ts)[:6])\n zone=_time.strftime('%Z',localtm)\n tz=timezone(delta,zone)\n else :\n tz=timezone(timedelta(seconds=gmtoff),zone)\n return tz\n \n def astimezone(self,tz=None ):\n if tz is None :\n tz=self._local_timezone()\n elif not isinstance(tz,tzinfo):\n raise TypeError(\"tz argument must be an instance of tzinfo\")\n \n mytz=self.tzinfo\n if mytz is None :\n mytz=self._local_timezone()\n myoffset=mytz.utcoffset(self)\n else :\n myoffset=mytz.utcoffset(self)\n if myoffset is None :\n mytz=self.replace(tzinfo=None )._local_timezone()\n myoffset=mytz.utcoffset(self)\n \n if tz is mytz:\n return self\n \n \n utc=(self -myoffset).replace(tzinfo=tz)\n \n \n return tz.fromutc(utc)\n \n \n \n def ctime(self):\n ''\n weekday=self.toordinal()%7 or 7\n return \"%s %s %2d %02d:%02d:%02d %04d\"%(\n _DAYNAMES[weekday],\n _MONTHNAMES[self._month],\n self._day,\n self._hour,self._minute,self._second,\n self._year)\n \n def isoformat(self,sep='T',timespec='auto'):\n ''\n\n\n\n\n\n\n\n\n\n\n\n\n \n s=(\"%04d-%02d-%02d%c\"%(self._year,self._month,self._day,sep)+\n _format_time(self._hour,self._minute,self._second,\n self._microsecond,timespec))\n \n off=self.utcoffset()\n tz=_format_offset(off)\n if tz:\n s +=tz\n \n return s\n \n def __repr__(self):\n ''\n L=[self._year,self._month,self._day,\n self._hour,self._minute,self._second,self._microsecond]\n if L[-1]==0:\n del L[-1]\n if L[-1]==0:\n del L[-1]\n s=\"%s.%s(%s)\"%(self.__class__.__module__,\n self.__class__.__qualname__,\n \", \".join(map(str,L)))\n if self._tzinfo is not None :\n assert s[-1:]==\")\"\n s=s[:-1]+\", tzinfo=%r\"%self._tzinfo+\")\"\n if self._fold:\n assert s[-1:]==\")\"\n s=s[:-1]+\", fold=1)\"\n return s\n \n def __str__(self):\n ''\n return self.isoformat(sep=' ')\n \n @classmethod\n def strptime(cls,date_string,format):\n ''\n import _strptime\n return _strptime._strptime_datetime(cls,date_string,format)\n \n def utcoffset(self):\n ''\n \n if self._tzinfo is None :\n return None\n offset=self._tzinfo.utcoffset(self)\n _check_utc_offset(\"utcoffset\",offset)\n return offset\n \n def tzname(self):\n ''\n\n\n\n\n \n if self._tzinfo is None :\n return None\n name=self._tzinfo.tzname(self)\n _check_tzname(name)\n return name\n \n def dst(self):\n ''\n\n\n\n\n\n\n \n if self._tzinfo is None :\n return None\n offset=self._tzinfo.dst(self)\n _check_utc_offset(\"dst\",offset)\n return offset\n \n \n \n def __eq__(self,other):\n if isinstance(other,datetime):\n return self._cmp(other,allow_mixed=True )==0\n elif not isinstance(other,date):\n return NotImplemented\n else :\n return False\n \n def __le__(self,other):\n if isinstance(other,datetime):\n return self._cmp(other)<=0\n elif not isinstance(other,date):\n return NotImplemented\n else :\n _cmperror(self,other)\n \n def __lt__(self,other):\n if isinstance(other,datetime):\n return self._cmp(other)<0\n elif not isinstance(other,date):\n return NotImplemented\n else :\n _cmperror(self,other)\n \n def __ge__(self,other):\n if isinstance(other,datetime):\n return self._cmp(other)>=0\n elif not isinstance(other,date):\n return NotImplemented\n else :\n _cmperror(self,other)\n \n def __gt__(self,other):\n if isinstance(other,datetime):\n return self._cmp(other)>0\n elif not isinstance(other,date):\n return NotImplemented\n else :\n _cmperror(self,other)\n \n def _cmp(self,other,allow_mixed=False ):\n assert isinstance(other,datetime)\n mytz=self._tzinfo\n ottz=other._tzinfo\n myoff=otoff=None\n \n if mytz is ottz:\n base_compare=True\n else :\n myoff=self.utcoffset()\n otoff=other.utcoffset()\n \n if allow_mixed:\n if myoff !=self.replace(fold=not self.fold).utcoffset():\n return 2\n if otoff !=other.replace(fold=not other.fold).utcoffset():\n return 2\n base_compare=myoff ==otoff\n \n if base_compare:\n return _cmp((self._year,self._month,self._day,\n self._hour,self._minute,self._second,\n self._microsecond),\n (other._year,other._month,other._day,\n other._hour,other._minute,other._second,\n other._microsecond))\n if myoff is None or otoff is None :\n if allow_mixed:\n return 2\n else :\n raise TypeError(\"cannot compare naive and aware datetimes\")\n \n diff=self -other\n if diff.days <0:\n return -1\n return diff and 1 or 0\n \n def __add__(self,other):\n ''\n if not isinstance(other,timedelta):\n return NotImplemented\n delta=timedelta(self.toordinal(),\n hours=self._hour,\n minutes=self._minute,\n seconds=self._second,\n microseconds=self._microsecond)\n delta +=other\n hour,rem=divmod(delta.seconds,3600)\n minute,second=divmod(rem,60)\n if 0 <delta.days <=_MAXORDINAL:\n return datetime.combine(date.fromordinal(delta.days),\n time(hour,minute,second,\n delta.microseconds,\n tzinfo=self._tzinfo))\n raise OverflowError(\"result out of range\")\n \n __radd__=__add__\n \n def __sub__(self,other):\n ''\n if not isinstance(other,datetime):\n if isinstance(other,timedelta):\n return self+-other\n return NotImplemented\n \n days1=self.toordinal()\n days2=other.toordinal()\n secs1=self._second+self._minute *60+self._hour *3600\n secs2=other._second+other._minute *60+other._hour *3600\n base=timedelta(days1 -days2,\n secs1 -secs2,\n self._microsecond -other._microsecond)\n if self._tzinfo is other._tzinfo:\n return base\n myoff=self.utcoffset()\n otoff=other.utcoffset()\n if myoff ==otoff:\n return base\n if myoff is None or otoff is None :\n raise TypeError(\"cannot mix naive and timezone-aware time\")\n return base+otoff -myoff\n \n def __hash__(self):\n if self._hashcode ==-1:\n if self.fold:\n t=self.replace(fold=0)\n else :\n t=self\n tzoff=t.utcoffset()\n if tzoff is None :\n self._hashcode=hash(t._getstate()[0])\n else :\n days=_ymd2ord(self.year,self.month,self.day)\n seconds=self.hour *3600+self.minute *60+self.second\n self._hashcode=hash(timedelta(days,seconds,self.microsecond)-tzoff)\n return self._hashcode\n \n \n \n def _getstate(self,protocol=3):\n yhi,ylo=divmod(self._year,256)\n us2,us3=divmod(self._microsecond,256)\n us1,us2=divmod(us2,256)\n m=self._month\n if self._fold and protocol >3:\n m +=128\n basestate=bytes([yhi,ylo,m,self._day,\n self._hour,self._minute,self._second,\n us1,us2,us3])\n if self._tzinfo is None :\n return (basestate,)\n else :\n return (basestate,self._tzinfo)\n \n def __setstate(self,string,tzinfo):\n if tzinfo is not None and not isinstance(tzinfo,_tzinfo_class):\n raise TypeError(\"bad tzinfo state arg\")\n (yhi,ylo,m,self._day,self._hour,\n self._minute,self._second,us1,us2,us3)=string\n if m >127:\n self._fold=1\n self._month=m -128\n else :\n self._fold=0\n self._month=m\n self._year=yhi *256+ylo\n self._microsecond=(((us1 <<8)|us2)<<8)|us3\n self._tzinfo=tzinfo\n \n def __reduce_ex__(self,protocol):\n return (self.__class__,self._getstate(protocol))\n \n def __reduce__(self):\n return self.__reduce_ex__(2)\n \n \ndatetime.min=datetime(1,1,1)\ndatetime.max=datetime(9999,12,31,23,59,59,999999)\ndatetime.resolution=timedelta(microseconds=1)\n\n\ndef _isoweek1monday(year):\n\n\n THURSDAY=3\n firstday=_ymd2ord(year,1,1)\n firstweekday=(firstday+6)%7\n week1monday=firstday -firstweekday\n if firstweekday >THURSDAY:\n week1monday +=7\n return week1monday\n \nclass timezone(tzinfo):\n __slots__='_offset','_name'\n \n \n _Omitted=object()\n def __new__(cls,offset,name=_Omitted):\n if not isinstance(offset,timedelta):\n raise TypeError(\"offset must be a timedelta\")\n if name is cls._Omitted:\n if not offset:\n return cls.utc\n name=None\n elif not isinstance(name,str):\n raise TypeError(\"name must be a string\")\n if not cls._minoffset <=offset <=cls._maxoffset:\n raise ValueError(\"offset must be a timedelta \"\n \"strictly between -timedelta(hours=24) and \"\n \"timedelta(hours=24).\")\n return cls._create(offset,name)\n \n @classmethod\n def _create(cls,offset,name=None ):\n self=tzinfo.__new__(cls)\n self._offset=offset\n self._name=name\n return self\n \n def __getinitargs__(self):\n ''\n if self._name is None :\n return (self._offset,)\n return (self._offset,self._name)\n \n def __eq__(self,other):\n if type(other)!=timezone:\n return False\n return self._offset ==other._offset\n \n def __hash__(self):\n return hash(self._offset)\n \n def __repr__(self):\n ''\n\n\n\n\n\n\n\n \n if self is self.utc:\n return 'datetime.timezone.utc'\n if self._name is None :\n return \"%s.%s(%r)\"%(self.__class__.__module__,\n self.__class__.__qualname__,\n self._offset)\n return \"%s.%s(%r, %r)\"%(self.__class__.__module__,\n self.__class__.__qualname__,\n self._offset,self._name)\n \n def __str__(self):\n return self.tzname(None )\n \n def utcoffset(self,dt):\n if isinstance(dt,datetime)or dt is None :\n return self._offset\n raise TypeError(\"utcoffset() argument must be a datetime instance\"\n \" or None\")\n \n def tzname(self,dt):\n if isinstance(dt,datetime)or dt is None :\n if self._name is None :\n return self._name_from_offset(self._offset)\n return self._name\n raise TypeError(\"tzname() argument must be a datetime instance\"\n \" or None\")\n \n def dst(self,dt):\n if isinstance(dt,datetime)or dt is None :\n return None\n raise TypeError(\"dst() argument must be a datetime instance\"\n \" or None\")\n \n def fromutc(self,dt):\n if isinstance(dt,datetime):\n if dt.tzinfo is not self:\n raise ValueError(\"fromutc: dt.tzinfo \"\n \"is not self\")\n return dt+self._offset\n raise TypeError(\"fromutc() argument must be a datetime instance\"\n \" or None\")\n \n _maxoffset=timedelta(hours=23,minutes=59)\n _minoffset=-_maxoffset\n \n @staticmethod\n def _name_from_offset(delta):\n if not delta:\n return 'UTC'\n if delta <timedelta(0):\n sign='-'\n delta=-delta\n else :\n sign='+'\n hours,rest=divmod(delta,timedelta(hours=1))\n minutes,rest=divmod(rest,timedelta(minutes=1))\n seconds=rest.seconds\n microseconds=rest.microseconds\n if microseconds:\n return (f'UTC{sign}{hours:02d}:{minutes:02d}:{seconds:02d}'\n f'.{microseconds:06d}')\n if seconds:\n return f'UTC{sign}{hours:02d}:{minutes:02d}:{seconds:02d}'\n return f'UTC{sign}{hours:02d}:{minutes:02d}'\n \ntimezone.utc=timezone._create(timedelta(0))\ntimezone.min=timezone._create(timezone._minoffset)\ntimezone.max=timezone._create(timezone._maxoffset)\n_EPOCH=datetime(1970,1,1,tzinfo=timezone.utc)\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\ntry :\n from _datetime import *\nexcept ImportError:\n pass\nelse :\n\n del (_DAYNAMES,_DAYS_BEFORE_MONTH,_DAYS_IN_MONTH,_DI100Y,_DI400Y,\n _DI4Y,_EPOCH,_MAXORDINAL,_MONTHNAMES,_build_struct_time,\n _check_date_fields,_check_int_field,_check_time_fields,\n _check_tzinfo_arg,_check_tzname,_check_utc_offset,_cmp,_cmperror,\n _date_class,_days_before_month,_days_before_year,_days_in_month,\n _format_time,_format_offset,_is_leap,_isoweek1monday,_math,\n _ord2ymd,_time,_time_class,_tzinfo_class,_wrap_strftime,_ymd2ord,\n _divide_and_round,_parse_isoformat_date,_parse_isoformat_time,\n _parse_hh_mm_ss_ff)\n \n \n \n \n from _datetime import __doc__\n", ["_datetime", "_strptime", "math", "time"]], "json.decoder": [".py", "''\n\nimport re\n\nfrom json import scanner\ntry :\n from _json import scanstring as c_scanstring\nexcept ImportError:\n c_scanstring=None\n \n__all__=['JSONDecoder','JSONDecodeError']\n\nFLAGS=re.VERBOSE |re.MULTILINE |re.DOTALL\n\nNaN=float('nan')\nPosInf=float('inf')\nNegInf=float('-inf')\n\n\nclass JSONDecodeError(ValueError):\n ''\n\n\n\n\n\n\n\n \n \n def __init__(self,msg,doc,pos):\n lineno=doc.count('\\n',0,pos)+1\n colno=pos -doc.rfind('\\n',0,pos)\n errmsg='%s: line %d column %d (char %d)'%(msg,lineno,colno,pos)\n ValueError.__init__(self,errmsg)\n self.msg=msg\n self.doc=doc\n self.pos=pos\n self.lineno=lineno\n self.colno=colno\n \n def __reduce__(self):\n return self.__class__,(self.msg,self.doc,self.pos)\n \n \n_CONSTANTS={\n'-Infinity':NegInf,\n'Infinity':PosInf,\n'NaN':NaN,\n}\n\n\nSTRINGCHUNK=re.compile(r'(.*?)([\"\\\\\\x00-\\x1f])',FLAGS)\nBACKSLASH={\n'\"':'\"','\\\\':'\\\\','/':'/',\n'b':'\\b','f':'\\f','n':'\\n','r':'\\r','t':'\\t',\n}\n\ndef _decode_uXXXX(s,pos):\n esc=s[pos+1:pos+5]\n if len(esc)==4 and esc[1]not in 'xX':\n try :\n return int(esc,16)\n except ValueError:\n pass\n msg=\"Invalid \\\\uXXXX escape\"\n raise JSONDecodeError(msg,s,pos)\n \ndef py_scanstring(s,end,strict=True ,\n_b=BACKSLASH,_m=STRINGCHUNK.match):\n ''\n\n\n\n\n\n\n \n chunks=[]\n _append=chunks.append\n begin=end -1\n while 1:\n chunk=_m(s,end)\n if chunk is None :\n raise JSONDecodeError(\"Unterminated string starting at\",s,begin)\n end=chunk.end()\n content,terminator=chunk.groups()\n \n if content:\n _append(content)\n \n \n if terminator =='\"':\n break\n elif terminator !='\\\\':\n if strict:\n \n msg=\"Invalid control character {0!r} at\".format(terminator)\n raise JSONDecodeError(msg,s,end)\n else :\n _append(terminator)\n continue\n try :\n esc=s[end]\n except IndexError:\n raise JSONDecodeError(\"Unterminated string starting at\",\n s,begin)from None\n \n if esc !='u':\n try :\n char=_b[esc]\n except KeyError:\n msg=\"Invalid \\\\escape: {0!r}\".format(esc)\n raise JSONDecodeError(msg,s,end)\n end +=1\n else :\n uni=_decode_uXXXX(s,end)\n end +=5\n if 0xd800 <=uni <=0xdbff and s[end:end+2]=='\\\\u':\n uni2=_decode_uXXXX(s,end+1)\n if 0xdc00 <=uni2 <=0xdfff:\n uni=0x10000+(((uni -0xd800)<<10)|(uni2 -0xdc00))\n end +=6\n char=chr(uni)\n _append(char)\n return ''.join(chunks),end\n \n \n \nscanstring=c_scanstring or py_scanstring\n\nWHITESPACE=re.compile(r'[ \\t\\n\\r]*',FLAGS)\nWHITESPACE_STR=' \\t\\n\\r'\n\n\ndef JSONObject(s_and_end,strict,scan_once,object_hook,object_pairs_hook,\nmemo=None ,_w=WHITESPACE.match,_ws=WHITESPACE_STR):\n s,end=s_and_end\n pairs=[]\n pairs_append=pairs.append\n \n if memo is None :\n memo={}\n memo_get=memo.setdefault\n \n \n nextchar=s[end:end+1]\n \n if nextchar !='\"':\n if nextchar in _ws:\n end=_w(s,end).end()\n nextchar=s[end:end+1]\n \n if nextchar =='}':\n if object_pairs_hook is not None :\n result=object_pairs_hook(pairs)\n return result,end+1\n pairs={}\n if object_hook is not None :\n pairs=object_hook(pairs)\n return pairs,end+1\n elif nextchar !='\"':\n raise JSONDecodeError(\n \"Expecting property name enclosed in double quotes\",s,end)\n end +=1\n while True :\n key,end=scanstring(s,end,strict)\n key=memo_get(key,key)\n \n \n if s[end:end+1]!=':':\n end=_w(s,end).end()\n if s[end:end+1]!=':':\n raise JSONDecodeError(\"Expecting ':' delimiter\",s,end)\n end +=1\n \n try :\n if s[end]in _ws:\n end +=1\n if s[end]in _ws:\n end=_w(s,end+1).end()\n except IndexError:\n pass\n \n try :\n value,end=scan_once(s,end)\n except StopIteration as err:\n raise JSONDecodeError(\"Expecting value\",s,err.value)from None\n pairs_append((key,value))\n try :\n nextchar=s[end]\n if nextchar in _ws:\n end=_w(s,end+1).end()\n nextchar=s[end]\n except IndexError:\n nextchar=''\n end +=1\n \n if nextchar =='}':\n break\n elif nextchar !=',':\n raise JSONDecodeError(\"Expecting ',' delimiter\",s,end -1)\n end=_w(s,end).end()\n nextchar=s[end:end+1]\n end +=1\n if nextchar !='\"':\n raise JSONDecodeError(\n \"Expecting property name enclosed in double quotes\",s,end -1)\n if object_pairs_hook is not None :\n result=object_pairs_hook(pairs)\n return result,end\n pairs=dict(pairs)\n if object_hook is not None :\n pairs=object_hook(pairs)\n return pairs,end\n \ndef JSONArray(s_and_end,scan_once,_w=WHITESPACE.match,_ws=WHITESPACE_STR):\n s,end=s_and_end\n values=[]\n nextchar=s[end:end+1]\n if nextchar in _ws:\n end=_w(s,end+1).end()\n nextchar=s[end:end+1]\n \n if nextchar ==']':\n return values,end+1\n _append=values.append\n while True :\n try :\n value,end=scan_once(s,end)\n except StopIteration as err:\n raise JSONDecodeError(\"Expecting value\",s,err.value)from None\n _append(value)\n nextchar=s[end:end+1]\n if nextchar in _ws:\n end=_w(s,end+1).end()\n nextchar=s[end:end+1]\n end +=1\n if nextchar ==']':\n break\n elif nextchar !=',':\n raise JSONDecodeError(\"Expecting ',' delimiter\",s,end -1)\n try :\n if s[end]in _ws:\n end +=1\n if s[end]in _ws:\n end=_w(s,end+1).end()\n except IndexError:\n pass\n \n return values,end\n \n \nclass JSONDecoder(object):\n ''\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n \n \n def __init__(self,*,object_hook=None ,parse_float=None ,\n parse_int=None ,parse_constant=None ,strict=True ,\n object_pairs_hook=None ):\n ''\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n \n self.object_hook=object_hook\n self.parse_float=parse_float or float\n self.parse_int=parse_int or int\n self.parse_constant=parse_constant or _CONSTANTS.__getitem__\n self.strict=strict\n self.object_pairs_hook=object_pairs_hook\n self.parse_object=JSONObject\n self.parse_array=JSONArray\n self.parse_string=scanstring\n self.memo={}\n self.scan_once=scanner.make_scanner(self)\n \n \n def decode(self,s,_w=WHITESPACE.match):\n ''\n\n\n \n obj,end=self.raw_decode(s,idx=_w(s,0).end())\n end=_w(s,end).end()\n if end !=len(s):\n raise JSONDecodeError(\"Extra data\",s,end)\n return obj\n \n def raw_decode(self,s,idx=0):\n ''\n\n\n\n\n\n\n \n try :\n obj,end=self.scan_once(s,idx)\n except StopIteration as err:\n raise JSONDecodeError(\"Expecting value\",s,err.value)from None\n return obj,end\n", ["_json", "json", "json.scanner", "re"]], "unittest.runner": [".py", "''\n\nimport sys\nimport time\nimport warnings\n\nfrom . import result\nfrom .signals import registerResult\n\n__unittest=True\n\n\nclass _WritelnDecorator(object):\n ''\n def __init__(self,stream):\n self.stream=stream\n \n def __getattr__(self,attr):\n if attr in ('stream','__getstate__'):\n raise AttributeError(attr)\n return getattr(self.stream,attr)\n \n def writeln(self,arg=None ):\n if arg:\n self.write(arg)\n self.write('\\n')\n \n \nclass TextTestResult(result.TestResult):\n ''\n\n\n \n separator1='='*70\n separator2='-'*70\n \n def __init__(self,stream,descriptions,verbosity):\n super(TextTestResult,self).__init__(stream,descriptions,verbosity)\n self.stream=stream\n self.showAll=verbosity >1\n self.dots=verbosity ==1\n self.descriptions=descriptions\n \n def getDescription(self,test):\n doc_first_line=test.shortDescription()\n if self.descriptions and doc_first_line:\n return '\\n'.join((str(test),doc_first_line))\n else :\n return str(test)\n \n def startTest(self,test):\n super(TextTestResult,self).startTest(test)\n if self.showAll:\n self.stream.write(self.getDescription(test))\n self.stream.write(\" ... \")\n self.stream.flush()\n \n def addSuccess(self,test):\n super(TextTestResult,self).addSuccess(test)\n if self.showAll:\n self.stream.writeln(\"ok\")\n elif self.dots:\n self.stream.write('.')\n self.stream.flush()\n \n def addError(self,test,err):\n super(TextTestResult,self).addError(test,err)\n if self.showAll:\n self.stream.writeln(\"ERROR\")\n elif self.dots:\n self.stream.write('E')\n self.stream.flush()\n \n def addFailure(self,test,err):\n super(TextTestResult,self).addFailure(test,err)\n if self.showAll:\n self.stream.writeln(\"FAIL\")\n elif self.dots:\n self.stream.write('F')\n self.stream.flush()\n \n def addSkip(self,test,reason):\n super(TextTestResult,self).addSkip(test,reason)\n if self.showAll:\n self.stream.writeln(\"skipped {0!r}\".format(reason))\n elif self.dots:\n self.stream.write(\"s\")\n self.stream.flush()\n \n def addExpectedFailure(self,test,err):\n super(TextTestResult,self).addExpectedFailure(test,err)\n if self.showAll:\n self.stream.writeln(\"expected failure\")\n elif self.dots:\n self.stream.write(\"x\")\n self.stream.flush()\n \n def addUnexpectedSuccess(self,test):\n super(TextTestResult,self).addUnexpectedSuccess(test)\n if self.showAll:\n self.stream.writeln(\"unexpected success\")\n elif self.dots:\n self.stream.write(\"u\")\n self.stream.flush()\n \n def printErrors(self):\n if self.dots or self.showAll:\n self.stream.writeln()\n self.printErrorList('ERROR',self.errors)\n self.printErrorList('FAIL',self.failures)\n \n def printErrorList(self,flavour,errors):\n for test,err in errors:\n self.stream.writeln(self.separator1)\n self.stream.writeln(\"%s: %s\"%(flavour,self.getDescription(test)))\n self.stream.writeln(self.separator2)\n self.stream.writeln(\"%s\"%err)\n \n \nclass TextTestRunner(object):\n ''\n\n\n\n \n resultclass=TextTestResult\n \n def __init__(self,stream=None ,descriptions=True ,verbosity=1,\n failfast=False ,buffer=False ,resultclass=None ,warnings=None ,\n *,tb_locals=False ):\n ''\n\n\n\n \n if stream is None :\n stream=sys.stderr\n self.stream=_WritelnDecorator(stream)\n self.descriptions=descriptions\n self.verbosity=verbosity\n self.failfast=failfast\n self.buffer=buffer\n self.tb_locals=tb_locals\n self.warnings=warnings\n if resultclass is not None :\n self.resultclass=resultclass\n \n def _makeResult(self):\n return self.resultclass(self.stream,self.descriptions,self.verbosity)\n \n def run(self,test):\n ''\n result=self._makeResult()\n registerResult(result)\n result.failfast=self.failfast\n result.buffer=self.buffer\n result.tb_locals=self.tb_locals\n with warnings.catch_warnings():\n if self.warnings:\n \n warnings.simplefilter(self.warnings)\n \n \n \n \n \n if self.warnings in ['default','always']:\n warnings.filterwarnings('module',\n category=DeprecationWarning,\n message=r'Please use assert\\w+ instead.')\n startTime=time.time()\n startTestRun=getattr(result,'startTestRun',None )\n if startTestRun is not None :\n startTestRun()\n try :\n test(result)\n finally :\n stopTestRun=getattr(result,'stopTestRun',None )\n if stopTestRun is not None :\n stopTestRun()\n stopTime=time.time()\n timeTaken=stopTime -startTime\n result.printErrors()\n if hasattr(result,'separator2'):\n self.stream.writeln(result.separator2)\n run=result.testsRun\n self.stream.writeln(\"Ran %d test%s in %.3fs\"%\n (run,run !=1 and \"s\"or \"\",timeTaken))\n self.stream.writeln()\n \n expectedFails=unexpectedSuccesses=skipped=0\n try :\n results=map(len,(result.expectedFailures,\n result.unexpectedSuccesses,\n result.skipped))\n except AttributeError:\n pass\n else :\n expectedFails,unexpectedSuccesses,skipped=results\n \n infos=[]\n if not result.wasSuccessful():\n self.stream.write(\"FAILED\")\n failed,errored=len(result.failures),len(result.errors)\n if failed:\n infos.append(\"failures=%d\"%failed)\n if errored:\n infos.append(\"errors=%d\"%errored)\n else :\n self.stream.write(\"OK\")\n if skipped:\n infos.append(\"skipped=%d\"%skipped)\n if expectedFails:\n infos.append(\"expected failures=%d\"%expectedFails)\n if unexpectedSuccesses:\n infos.append(\"unexpected successes=%d\"%unexpectedSuccesses)\n if infos:\n self.stream.writeln(\" (%s)\"%(\", \".join(infos),))\n else :\n self.stream.write(\"\\n\")\n return result\n", ["sys", "time", "unittest", "unittest.result", "unittest.signals", "warnings"]], "urllib.parse": [".py", "''\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\nimport re\nimport sys\nimport collections\n\n__all__=[\"urlparse\",\"urlunparse\",\"urljoin\",\"urldefrag\",\n\"urlsplit\",\"urlunsplit\",\"urlencode\",\"parse_qs\",\n\"parse_qsl\",\"quote\",\"quote_plus\",\"quote_from_bytes\",\n\"unquote\",\"unquote_plus\",\"unquote_to_bytes\"]\n\n\nuses_relative=['ftp','http','gopher','nntp','imap',\n'wais','file','https','shttp','mms',\n'prospero','rtsp','rtspu','','sftp',\n'svn','svn+ssh']\nuses_netloc=['ftp','http','gopher','nntp','telnet',\n'imap','wais','file','mms','https','shttp',\n'snews','prospero','rtsp','rtspu','rsync','',\n'svn','svn+ssh','sftp','nfs','git','git+ssh']\nuses_params=['ftp','hdl','prospero','http','imap',\n'https','shttp','rtsp','rtspu','sip','sips',\n'mms','','sftp','tel']\n\n\n\nnon_hierarchical=['gopher','hdl','mailto','news',\n'telnet','wais','imap','snews','sip','sips']\nuses_query=['http','wais','imap','https','shttp','mms',\n'gopher','rtsp','rtspu','sip','sips','']\nuses_fragment=['ftp','hdl','http','gopher','news',\n'nntp','wais','https','shttp','snews',\n'file','prospero','']\n\n\nscheme_chars=('abcdefghijklmnopqrstuvwxyz'\n'ABCDEFGHIJKLMNOPQRSTUVWXYZ'\n'0123456789'\n'+-.')\n\n\nMAX_CACHE_SIZE=20\n_parse_cache={}\n\ndef clear_cache():\n ''\n _parse_cache.clear()\n _safe_quoters.clear()\n \n \n \n \n \n \n \n \n_implicit_encoding='ascii'\n_implicit_errors='strict'\n\ndef _noop(obj):\n return obj\n \ndef _encode_result(obj,encoding=_implicit_encoding,\nerrors=_implicit_errors):\n return obj.encode(encoding,errors)\n \ndef _decode_args(args,encoding=_implicit_encoding,\nerrors=_implicit_errors):\n return tuple(x.decode(encoding,errors)if x else ''for x in args)\n \ndef _coerce_args(*args):\n\n\n\n\n\n str_input=isinstance(args[0],str)\n for arg in args[1:]:\n \n \n if arg and isinstance(arg,str)!=str_input:\n raise TypeError(\"Cannot mix str and non-str arguments\")\n if str_input:\n return args+(_noop,)\n return _decode_args(args)+(_encode_result,)\n \n \nclass _ResultMixinStr(object):\n ''\n __slots__=()\n \n def encode(self,encoding='ascii',errors='strict'):\n return self._encoded_counterpart(*(x.encode(encoding,errors)for x in self))\n \n \nclass _ResultMixinBytes(object):\n ''\n __slots__=()\n \n def decode(self,encoding='ascii',errors='strict'):\n return self._decoded_counterpart(*(x.decode(encoding,errors)for x in self))\n \n \nclass _NetlocResultMixinBase(object):\n ''\n __slots__=()\n \n @property\n def username(self):\n return self._userinfo[0]\n \n @property\n def password(self):\n return self._userinfo[1]\n \n @property\n def hostname(self):\n hostname=self._hostinfo[0]\n if not hostname:\n hostname=None\n elif hostname is not None :\n hostname=hostname.lower()\n return hostname\n \n @property\n def port(self):\n port=self._hostinfo[1]\n if port is not None :\n port=int(port,10)\n \n if not (0 <=port <=65535):\n return None\n return port\n \n \nclass _NetlocResultMixinStr(_NetlocResultMixinBase,_ResultMixinStr):\n __slots__=()\n \n @property\n def _userinfo(self):\n netloc=self.netloc\n userinfo,have_info,hostinfo=netloc.rpartition('@')\n if have_info:\n username,have_password,password=userinfo.partition(':')\n if not have_password:\n password=None\n else :\n username=password=None\n return username,password\n \n @property\n def _hostinfo(self):\n netloc=self.netloc\n _,_,hostinfo=netloc.rpartition('@')\n _,have_open_br,bracketed=hostinfo.partition('[')\n if have_open_br:\n hostname,_,port=bracketed.partition(']')\n _,have_port,port=port.partition(':')\n else :\n hostname,have_port,port=hostinfo.partition(':')\n if not have_port:\n port=None\n return hostname,port\n \n \nclass _NetlocResultMixinBytes(_NetlocResultMixinBase,_ResultMixinBytes):\n __slots__=()\n \n @property\n def _userinfo(self):\n netloc=self.netloc\n userinfo,have_info,hostinfo=netloc.rpartition(b'@')\n if have_info:\n username,have_password,password=userinfo.partition(b':')\n if not have_password:\n password=None\n else :\n username=password=None\n return username,password\n \n @property\n def _hostinfo(self):\n netloc=self.netloc\n _,_,hostinfo=netloc.rpartition(b'@')\n _,have_open_br,bracketed=hostinfo.partition(b'[')\n if have_open_br:\n hostname,_,port=bracketed.partition(b']')\n _,have_port,port=port.partition(b':')\n else :\n hostname,have_port,port=hostinfo.partition(b':')\n if not have_port:\n port=None\n return hostname,port\n \n \nfrom collections import namedtuple\n\n_DefragResultBase=namedtuple('DefragResult','url fragment')\n_SplitResultBase=namedtuple('SplitResult','scheme netloc path query fragment')\n_ParseResultBase=namedtuple('ParseResult','scheme netloc path params query fragment')\n\n\n\n\nResultBase=_NetlocResultMixinStr\n\n\nclass DefragResult(_DefragResultBase,_ResultMixinStr):\n __slots__=()\n def geturl(self):\n if self.fragment:\n return self.url+'#'+self.fragment\n else :\n return self.url\n \nclass SplitResult(_SplitResultBase,_NetlocResultMixinStr):\n __slots__=()\n def geturl(self):\n return urlunsplit(self)\n \nclass ParseResult(_ParseResultBase,_NetlocResultMixinStr):\n __slots__=()\n def geturl(self):\n return urlunparse(self)\n \n \nclass DefragResultBytes(_DefragResultBase,_ResultMixinBytes):\n __slots__=()\n def geturl(self):\n if self.fragment:\n return self.url+b'#'+self.fragment\n else :\n return self.url\n \nclass SplitResultBytes(_SplitResultBase,_NetlocResultMixinBytes):\n __slots__=()\n def geturl(self):\n return urlunsplit(self)\n \nclass ParseResultBytes(_ParseResultBase,_NetlocResultMixinBytes):\n __slots__=()\n def geturl(self):\n return urlunparse(self)\n \n \ndef _fix_result_transcoding():\n _result_pairs=(\n (DefragResult,DefragResultBytes),\n (SplitResult,SplitResultBytes),\n (ParseResult,ParseResultBytes),\n )\n for _decoded,_encoded in _result_pairs:\n _decoded._encoded_counterpart=_encoded\n _encoded._decoded_counterpart=_decoded\n \n_fix_result_transcoding()\ndel _fix_result_transcoding\n\ndef urlparse(url,scheme='',allow_fragments=True ):\n ''\n\n\n\n \n url,scheme,_coerce_result=_coerce_args(url,scheme)\n splitresult=urlsplit(url,scheme,allow_fragments)\n scheme,netloc,url,query,fragment=splitresult\n if scheme in uses_params and ';'in url:\n url,params=_splitparams(url)\n else :\n params=''\n result=ParseResult(scheme,netloc,url,params,query,fragment)\n return _coerce_result(result)\n \ndef _splitparams(url):\n if '/'in url:\n i=url.find(';',url.rfind('/'))\n if i <0:\n return url,''\n else :\n i=url.find(';')\n return url[:i],url[i+1:]\n \ndef _splitnetloc(url,start=0):\n delim=len(url)\n for c in '/?#':\n wdelim=url.find(c,start)\n if wdelim >=0:\n delim=min(delim,wdelim)\n return url[start:delim],url[delim:]\n \ndef urlsplit(url,scheme='',allow_fragments=True ):\n ''\n\n\n\n \n url,scheme,_coerce_result=_coerce_args(url,scheme)\n allow_fragments=bool(allow_fragments)\n key=url,scheme,allow_fragments,type(url),type(scheme)\n cached=_parse_cache.get(key,None )\n if cached:\n return _coerce_result(cached)\n if len(_parse_cache)>=MAX_CACHE_SIZE:\n clear_cache()\n netloc=query=fragment=''\n i=url.find(':')\n if i >0:\n if url[:i]=='http':\n scheme=url[:i].lower()\n url=url[i+1:]\n if url[:2]=='//':\n netloc,url=_splitnetloc(url,2)\n if (('['in netloc and ']'not in netloc)or\n (']'in netloc and '['not in netloc)):\n raise ValueError(\"Invalid IPv6 URL\")\n if allow_fragments and '#'in url:\n url,fragment=url.split('#',1)\n if '?'in url:\n url,query=url.split('?',1)\n v=SplitResult(scheme,netloc,url,query,fragment)\n _parse_cache[key]=v\n return _coerce_result(v)\n for c in url[:i]:\n if c not in scheme_chars:\n break\n else :\n \n \n rest=url[i+1:]\n if not rest or any(c not in '0123456789'for c in rest):\n \n scheme,url=url[:i].lower(),rest\n \n if url[:2]=='//':\n netloc,url=_splitnetloc(url,2)\n if (('['in netloc and ']'not in netloc)or\n (']'in netloc and '['not in netloc)):\n raise ValueError(\"Invalid IPv6 URL\")\n if allow_fragments and '#'in url:\n url,fragment=url.split('#',1)\n if '?'in url:\n url,query=url.split('?',1)\n v=SplitResult(scheme,netloc,url,query,fragment)\n _parse_cache[key]=v\n return _coerce_result(v)\n \ndef urlunparse(components):\n ''\n\n\n \n scheme,netloc,url,params,query,fragment,_coerce_result=(\n _coerce_args(*components))\n if params:\n url=\"%s;%s\"%(url,params)\n return _coerce_result(urlunsplit((scheme,netloc,url,query,fragment)))\n \ndef urlunsplit(components):\n ''\n\n\n\n \n scheme,netloc,url,query,fragment,_coerce_result=(\n _coerce_args(*components))\n if netloc or (scheme and scheme in uses_netloc and url[:2]!='//'):\n if url and url[:1]!='/':url='/'+url\n url='//'+(netloc or '')+url\n if scheme:\n url=scheme+':'+url\n if query:\n url=url+'?'+query\n if fragment:\n url=url+'#'+fragment\n return _coerce_result(url)\n \ndef urljoin(base,url,allow_fragments=True ):\n ''\n \n if not base:\n return url\n if not url:\n return base\n base,url,_coerce_result=_coerce_args(base,url)\n bscheme,bnetloc,bpath,bparams,bquery,bfragment=\\\n urlparse(base,'',allow_fragments)\n scheme,netloc,path,params,query,fragment=\\\n urlparse(url,bscheme,allow_fragments)\n if scheme !=bscheme or scheme not in uses_relative:\n return _coerce_result(url)\n if scheme in uses_netloc:\n if netloc:\n return _coerce_result(urlunparse((scheme,netloc,path,\n params,query,fragment)))\n netloc=bnetloc\n if path[:1]=='/':\n return _coerce_result(urlunparse((scheme,netloc,path,\n params,query,fragment)))\n if not path and not params:\n path=bpath\n params=bparams\n if not query:\n query=bquery\n return _coerce_result(urlunparse((scheme,netloc,path,\n params,query,fragment)))\n segments=bpath.split('/')[:-1]+path.split('/')\n \n if segments[-1]=='.':\n segments[-1]=''\n while '.'in segments:\n segments.remove('.')\n while 1:\n i=1\n n=len(segments)-1\n while i <n:\n if (segments[i]=='..'\n and segments[i -1]not in ('','..')):\n del segments[i -1:i+1]\n break\n i=i+1\n else :\n break\n if segments ==['','..']:\n segments[-1]=''\n elif len(segments)>=2 and segments[-1]=='..':\n segments[-2:]=['']\n return _coerce_result(urlunparse((scheme,netloc,'/'.join(segments),\n params,query,fragment)))\n \ndef urldefrag(url):\n ''\n\n\n\n\n \n url,_coerce_result=_coerce_args(url)\n if '#'in url:\n s,n,p,a,q,frag=urlparse(url)\n defrag=urlunparse((s,n,p,a,q,''))\n else :\n frag=''\n defrag=url\n return _coerce_result(DefragResult(defrag,frag))\n \n_hexdig='0123456789ABCDEFabcdef'\n_hextobyte={(a+b).encode():bytes([int(a+b,16)])\nfor a in _hexdig for b in _hexdig}\n\ndef unquote_to_bytes(string):\n ''\n \n \n if not string:\n \n string.split\n return b''\n if isinstance(string,str):\n string=string.encode('utf-8')\n bits=string.split(b'%')\n if len(bits)==1:\n return string\n res=[bits[0]]\n append=res.append\n for item in bits[1:]:\n try :\n append(_hextobyte[item[:2]])\n append(item[2:])\n except KeyError:\n append(b'%')\n append(item)\n return b''.join(res)\n \n_asciire=re.compile('([\\x00-\\x7f]+)')\n\ndef unquote(string,encoding='utf-8',errors='replace'):\n ''\n\n\n\n\n\n\n\n \n if '%'not in string:\n string.split\n return string\n if encoding is None :\n encoding='utf-8'\n if errors is None :\n errors='replace'\n bits=_asciire.split(string)\n res=[bits[0]]\n append=res.append\n for i in range(1,len(bits),2):\n append(unquote_to_bytes(bits[i]).decode(encoding,errors))\n append(bits[i+1])\n return ''.join(res)\n \ndef parse_qs(qs,keep_blank_values=False ,strict_parsing=False ,\nencoding='utf-8',errors='replace'):\n ''\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n \n parsed_result={}\n pairs=parse_qsl(qs,keep_blank_values,strict_parsing,\n encoding=encoding,errors=errors)\n for name,value in pairs:\n if name in parsed_result:\n parsed_result[name].append(value)\n else :\n parsed_result[name]=[value]\n return parsed_result\n \ndef parse_qsl(qs,keep_blank_values=False ,strict_parsing=False ,\nencoding='utf-8',errors='replace'):\n ''\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n \n qs,_coerce_result=_coerce_args(qs)\n pairs=[s2 for s1 in qs.split('&')for s2 in s1.split(';')]\n r=[]\n for name_value in pairs:\n if not name_value and not strict_parsing:\n continue\n nv=name_value.split('=',1)\n if len(nv)!=2:\n if strict_parsing:\n raise ValueError(\"bad query field: %r\"%(name_value,))\n \n if keep_blank_values:\n nv.append('')\n else :\n continue\n if len(nv[1])or keep_blank_values:\n name=nv[0].replace('+',' ')\n name=unquote(name,encoding=encoding,errors=errors)\n name=_coerce_result(name)\n value=nv[1].replace('+',' ')\n value=unquote(value,encoding=encoding,errors=errors)\n value=_coerce_result(value)\n r.append((name,value))\n return r\n \ndef unquote_plus(string,encoding='utf-8',errors='replace'):\n ''\n\n\n\n \n string=string.replace('+',' ')\n return unquote(string,encoding,errors)\n \n_ALWAYS_SAFE=frozenset(b'ABCDEFGHIJKLMNOPQRSTUVWXYZ'\nb'abcdefghijklmnopqrstuvwxyz'\nb'0123456789'\nb'_.-')\n_ALWAYS_SAFE_BYTES=bytes(_ALWAYS_SAFE)\n_safe_quoters={}\n\nclass Quoter(collections.defaultdict):\n ''\n\n\n\n \n \n \n def __init__(self,safe):\n ''\n self.safe=_ALWAYS_SAFE.union(safe)\n \n def __repr__(self):\n \n return \"<Quoter %r>\"%dict(self)\n \n def __missing__(self,b):\n \n res=chr(b)if b in self.safe else '%{:02X}'.format(b)\n self[b]=res\n return res\n \ndef quote(string,safe='/',encoding=None ,errors=None ):\n ''\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n \n if isinstance(string,str):\n if not string:\n return string\n if encoding is None :\n encoding='utf-8'\n if errors is None :\n errors='strict'\n string=string.encode(encoding,errors)\n else :\n if encoding is not None :\n raise TypeError(\"quote() doesn't support 'encoding' for bytes\")\n if errors is not None :\n raise TypeError(\"quote() doesn't support 'errors' for bytes\")\n return quote_from_bytes(string,safe)\n \ndef quote_plus(string,safe='',encoding=None ,errors=None ):\n ''\n\n\n \n \n \n if ((isinstance(string,str)and ' 'not in string)or\n (isinstance(string,bytes)and b' 'not in string)):\n return quote(string,safe,encoding,errors)\n if isinstance(safe,str):\n space=' '\n else :\n space=b' '\n string=quote(string,safe+space,encoding,errors)\n return string.replace(' ','+')\n \ndef quote_from_bytes(bs,safe='/'):\n ''\n\n\n \n if not isinstance(bs,(bytes,bytearray)):\n raise TypeError(\"quote_from_bytes() expected bytes\")\n if not bs:\n return ''\n if isinstance(safe,str):\n \n safe=safe.encode('ascii','ignore')\n else :\n safe=bytes([c for c in safe if c <128])\n if not bs.rstrip(_ALWAYS_SAFE_BYTES+safe):\n return bs.decode()\n try :\n quoter=_safe_quoters[safe]\n except KeyError:\n _safe_quoters[safe]=quoter=Quoter(safe).__getitem__\n return ''.join([quoter(char)for char in bs])\n \ndef urlencode(query,doseq=False ,safe='',encoding=None ,errors=None ):\n ''\n\n\n\n\n\n\n\n\n\n\n\n \n \n if hasattr(query,\"items\"):\n query=query.items()\n else :\n \n \n try :\n \n \n if len(query)and not isinstance(query[0],tuple):\n raise TypeError\n \n \n \n \n except TypeError:\n ty,va,tb=sys.exc_info()\n raise TypeError(\"not a valid non-string sequence \"\n \"or mapping object\").with_traceback(tb)\n \n l=[]\n if not doseq:\n for k,v in query:\n if isinstance(k,bytes):\n k=quote_plus(k,safe)\n else :\n k=quote_plus(str(k),safe,encoding,errors)\n \n if isinstance(v,bytes):\n v=quote_plus(v,safe)\n else :\n v=quote_plus(str(v),safe,encoding,errors)\n l.append(k+'='+v)\n else :\n for k,v in query:\n if isinstance(k,bytes):\n k=quote_plus(k,safe)\n else :\n k=quote_plus(str(k),safe,encoding,errors)\n \n if isinstance(v,bytes):\n v=quote_plus(v,safe)\n l.append(k+'='+v)\n elif isinstance(v,str):\n v=quote_plus(v,safe,encoding,errors)\n l.append(k+'='+v)\n else :\n try :\n \n x=len(v)\n except TypeError:\n \n v=quote_plus(str(v),safe,encoding,errors)\n l.append(k+'='+v)\n else :\n \n for elt in v:\n if isinstance(elt,bytes):\n elt=quote_plus(elt,safe)\n else :\n elt=quote_plus(str(elt),safe,encoding,errors)\n l.append(k+'='+elt)\n return '&'.join(l)\n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \ndef to_bytes(url):\n ''\n \n \n \n if isinstance(url,str):\n try :\n url=url.encode(\"ASCII\").decode()\n except UnicodeError:\n raise UnicodeError(\"URL \"+repr(url)+\n \" contains non-ASCII characters\")\n return url\n \ndef unwrap(url):\n ''\n url=str(url).strip()\n if url[:1]=='<'and url[-1:]=='>':\n url=url[1:-1].strip()\n if url[:4]=='URL:':url=url[4:].strip()\n return url\n \n_typeprog=None\ndef splittype(url):\n ''\n global _typeprog\n if _typeprog is None :\n import re\n _typeprog=re.compile('^([^/:]+):')\n \n match=_typeprog.match(url)\n if match:\n scheme=match.group(1)\n return scheme.lower(),url[len(scheme)+1:]\n return None ,url\n \n_hostprog=None\ndef splithost(url):\n ''\n global _hostprog\n if _hostprog is None :\n import re\n _hostprog=re.compile('^//([^/?]*)(.*)$')\n \n match=_hostprog.match(url)\n if match:\n host_port=match.group(1)\n path=match.group(2)\n if path and not path.startswith('/'):\n path='/'+path\n return host_port,path\n return None ,url\n \n_userprog=None\ndef splituser(host):\n ''\n global _userprog\n if _userprog is None :\n import re\n _userprog=re.compile('^(.*)@(.*)$')\n \n match=_userprog.match(host)\n if match:return match.group(1,2)\n return None ,host\n \n_passwdprog=None\ndef splitpasswd(user):\n ''\n global _passwdprog\n if _passwdprog is None :\n import re\n _passwdprog=re.compile('^([^:]*):(.*)$',re.S)\n \n match=_passwdprog.match(user)\n if match:return match.group(1,2)\n return user,None\n \n \n_portprog=None\ndef splitport(host):\n ''\n global _portprog\n if _portprog is None :\n import re\n _portprog=re.compile('^(.*):([0-9]+)$')\n \n match=_portprog.match(host)\n if match:return match.group(1,2)\n return host,None\n \n_nportprog=None\ndef splitnport(host,defport=-1):\n ''\n\n\n \n global _nportprog\n if _nportprog is None :\n import re\n _nportprog=re.compile('^(.*):(.*)$')\n \n match=_nportprog.match(host)\n if match:\n host,port=match.group(1,2)\n try :\n if not port:raise ValueError(\"no digits\")\n nport=int(port)\n except ValueError:\n nport=None\n return host,nport\n return host,defport\n \n_queryprog=None\ndef splitquery(url):\n ''\n global _queryprog\n if _queryprog is None :\n import re\n _queryprog=re.compile('^(.*)\\?([^?]*)$')\n \n match=_queryprog.match(url)\n if match:return match.group(1,2)\n return url,None\n \n_tagprog=None\ndef splittag(url):\n ''\n global _tagprog\n if _tagprog is None :\n import re\n _tagprog=re.compile('^(.*)#([^#]*)$')\n \n match=_tagprog.match(url)\n if match:return match.group(1,2)\n return url,None\n \ndef splitattr(url):\n ''\n \n words=url.split(';')\n return words[0],words[1:]\n \n_valueprog=None\ndef splitvalue(attr):\n ''\n global _valueprog\n if _valueprog is None :\n import re\n _valueprog=re.compile('^([^=]*)=(.*)$')\n \n match=_valueprog.match(attr)\n if match:return match.group(1,2)\n return attr,None\n", ["collections", "re", "sys"]], "urllib": [".py", "", [], 1], "email.errors": [".py", "\n\n\n\n\"\"\"email package exception classes.\"\"\"\n\n\nclass MessageError(Exception):\n ''\n \n \nclass MessageParseError(MessageError):\n ''\n \n \nclass HeaderParseError(MessageParseError):\n ''\n \n \nclass BoundaryError(MessageParseError):\n ''\n \n \nclass MultipartConversionError(MessageError,TypeError):\n ''\n \n \nclass CharsetError(MessageError):\n ''\n \n \n \nclass MessageDefect(ValueError):\n ''\n \n def __init__(self,line=None ):\n if line is not None :\n super().__init__(line)\n self.line=line\n \nclass NoBoundaryInMultipartDefect(MessageDefect):\n ''\n \nclass StartBoundaryNotFoundDefect(MessageDefect):\n ''\n \nclass CloseBoundaryNotFoundDefect(MessageDefect):\n ''\n \nclass FirstHeaderLineIsContinuationDefect(MessageDefect):\n ''\n \nclass MisplacedEnvelopeHeaderDefect(MessageDefect):\n ''\n \nclass MissingHeaderBodySeparatorDefect(MessageDefect):\n ''\n \nMalformedHeaderDefect=MissingHeaderBodySeparatorDefect\n\nclass MultipartInvariantViolationDefect(MessageDefect):\n ''\n \nclass InvalidMultipartContentTransferEncodingDefect(MessageDefect):\n ''\n \nclass UndecodableBytesDefect(MessageDefect):\n ''\n \nclass InvalidBase64PaddingDefect(MessageDefect):\n ''\n \nclass InvalidBase64CharactersDefect(MessageDefect):\n ''\n \n \n \nclass HeaderDefect(MessageDefect):\n ''\n \n def __init__(self,*args,**kw):\n super().__init__(*args,**kw)\n \nclass InvalidHeaderDefect(HeaderDefect):\n ''\n \nclass HeaderMissingRequiredValue(HeaderDefect):\n ''\n \nclass NonPrintableDefect(HeaderDefect):\n ''\n \n def __init__(self,non_printables):\n super().__init__(non_printables)\n self.non_printables=non_printables\n \n def __str__(self):\n return (\"the following ASCII non-printables found in header: \"\n \"{}\".format(self.non_printables))\n \nclass ObsoleteHeaderDefect(HeaderDefect):\n ''\n \nclass NonASCIILocalPartDefect(HeaderDefect):\n ''\n \n \n", []], "pydoc_data.topics": [".py", "\n\ntopics={'assert':'\\nThe ``assert`` statement\\n************************\\n\\nAssert statements are a convenient way to insert debugging assertions\\ninto a program:\\n\\n assert_stmt ::= \"assert\" expression [\",\" expression]\\n\\nThe simple form, ``assert expression``, is equivalent to\\n\\n if __debug__:\\n if not expression: raise AssertionError\\n\\nThe extended form, ``assert expression1, expression2``, is equivalent\\nto\\n\\n if __debug__:\\n if not expression1: raise AssertionError(expression2)\\n\\nThese equivalences assume that ``__debug__`` and ``AssertionError``\\nrefer to the built-in variables with those names. In the current\\nimplementation, the built-in variable ``__debug__`` is ``True`` under\\nnormal circumstances, ``False`` when optimization is requested\\n(command line option -O). The current code generator emits no code\\nfor an assert statement when optimization is requested at compile\\ntime. Note that it is unnecessary to include the source code for the\\nexpression that failed in the error message; it will be displayed as\\npart of the stack trace.\\n\\nAssignments to ``__debug__`` are illegal. The value for the built-in\\nvariable is determined when the interpreter starts.\\n',\n'assignment':'\\nAssignment statements\\n*********************\\n\\nAssignment statements are used to (re)bind names to values and to\\nmodify attributes or items of mutable objects:\\n\\n assignment_stmt ::= (target_list \"=\")+ (expression_list | yield_expression)\\n target_list ::= target (\",\" target)* [\",\"]\\n target ::= identifier\\n | \"(\" target_list \")\"\\n | \"[\" target_list \"]\"\\n | attributeref\\n | subscription\\n | slicing\\n | \"*\" target\\n\\n(See section *Primaries* for the syntax definitions for the last three\\nsymbols.)\\n\\nAn assignment statement evaluates the expression list (remember that\\nthis can be a single expression or a comma-separated list, the latter\\nyielding a tuple) and assigns the single resulting object to each of\\nthe target lists, from left to right.\\n\\nAssignment is defined recursively depending on the form of the target\\n(list). When a target is part of a mutable object (an attribute\\nreference, subscription or slicing), the mutable object must\\nultimately perform the assignment and decide about its validity, and\\nmay raise an exception if the assignment is unacceptable. The rules\\nobserved by various types and the exceptions raised are given with the\\ndefinition of the object types (see section *The standard type\\nhierarchy*).\\n\\nAssignment of an object to a target list, optionally enclosed in\\nparentheses or square brackets, is recursively defined as follows.\\n\\n* If the target list is a single target: The object is assigned to\\n that target.\\n\\n* If the target list is a comma-separated list of targets: The object\\n must be an iterable with the same number of items as there are\\n targets in the target list, and the items are assigned, from left to\\n right, to the corresponding targets.\\n\\n * If the target list contains one target prefixed with an asterisk,\\n called a \"starred\" target: The object must be a sequence with at\\n least as many items as there are targets in the target list, minus\\n one. The first items of the sequence are assigned, from left to\\n right, to the targets before the starred target. The final items\\n of the sequence are assigned to the targets after the starred\\n target. A list of the remaining items in the sequence is then\\n assigned to the starred target (the list can be empty).\\n\\n * Else: The object must be a sequence with the same number of items\\n as there are targets in the target list, and the items are\\n assigned, from left to right, to the corresponding targets.\\n\\nAssignment of an object to a single target is recursively defined as\\nfollows.\\n\\n* If the target is an identifier (name):\\n\\n * If the name does not occur in a ``global`` or ``nonlocal``\\n statement in the current code block: the name is bound to the\\n object in the current local namespace.\\n\\n * Otherwise: the name is bound to the object in the global namespace\\n or the outer namespace determined by ``nonlocal``, respectively.\\n\\n The name is rebound if it was already bound. This may cause the\\n reference count for the object previously bound to the name to reach\\n zero, causing the object to be deallocated and its destructor (if it\\n has one) to be called.\\n\\n* If the target is a target list enclosed in parentheses or in square\\n brackets: The object must be an iterable with the same number of\\n items as there are targets in the target list, and its items are\\n assigned, from left to right, to the corresponding targets.\\n\\n* If the target is an attribute reference: The primary expression in\\n the reference is evaluated. It should yield an object with\\n assignable attributes; if this is not the case, ``TypeError`` is\\n raised. That object is then asked to assign the assigned object to\\n the given attribute; if it cannot perform the assignment, it raises\\n an exception (usually but not necessarily ``AttributeError``).\\n\\n Note: If the object is a class instance and the attribute reference\\n occurs on both sides of the assignment operator, the RHS expression,\\n ``a.x`` can access either an instance attribute or (if no instance\\n attribute exists) a class attribute. The LHS target ``a.x`` is\\n always set as an instance attribute, creating it if necessary.\\n Thus, the two occurrences of ``a.x`` do not necessarily refer to the\\n same attribute: if the RHS expression refers to a class attribute,\\n the LHS creates a new instance attribute as the target of the\\n assignment:\\n\\n class Cls:\\n x = 3 # class variable\\n inst = Cls()\\n inst.x = inst.x + 1 # writes inst.x as 4 leaving Cls.x as 3\\n\\n This description does not necessarily apply to descriptor\\n attributes, such as properties created with ``property()``.\\n\\n* If the target is a subscription: The primary expression in the\\n reference is evaluated. It should yield either a mutable sequence\\n object (such as a list) or a mapping object (such as a dictionary).\\n Next, the subscript expression is evaluated.\\n\\n If the primary is a mutable sequence object (such as a list), the\\n subscript must yield an integer. If it is negative, the sequence\\'s\\n length is added to it. The resulting value must be a nonnegative\\n integer less than the sequence\\'s length, and the sequence is asked\\n to assign the assigned object to its item with that index. If the\\n index is out of range, ``IndexError`` is raised (assignment to a\\n subscripted sequence cannot add new items to a list).\\n\\n If the primary is a mapping object (such as a dictionary), the\\n subscript must have a type compatible with the mapping\\'s key type,\\n and the mapping is then asked to create a key/datum pair which maps\\n the subscript to the assigned object. This can either replace an\\n existing key/value pair with the same key value, or insert a new\\n key/value pair (if no key with the same value existed).\\n\\n For user-defined objects, the ``__setitem__()`` method is called\\n with appropriate arguments.\\n\\n* If the target is a slicing: The primary expression in the reference\\n is evaluated. It should yield a mutable sequence object (such as a\\n list). The assigned object should be a sequence object of the same\\n type. Next, the lower and upper bound expressions are evaluated,\\n insofar they are present; defaults are zero and the sequence\\'s\\n length. The bounds should evaluate to integers. If either bound is\\n negative, the sequence\\'s length is added to it. The resulting\\n bounds are clipped to lie between zero and the sequence\\'s length,\\n inclusive. Finally, the sequence object is asked to replace the\\n slice with the items of the assigned sequence. The length of the\\n slice may be different from the length of the assigned sequence,\\n thus changing the length of the target sequence, if the object\\n allows it.\\n\\n**CPython implementation detail:** In the current implementation, the\\nsyntax for targets is taken to be the same as for expressions, and\\ninvalid syntax is rejected during the code generation phase, causing\\nless detailed error messages.\\n\\nWARNING: Although the definition of assignment implies that overlaps\\nbetween the left-hand side and the right-hand side are \\'safe\\' (for\\nexample ``a, b = b, a`` swaps two variables), overlaps *within* the\\ncollection of assigned-to variables are not safe! For instance, the\\nfollowing program prints ``[0, 2]``:\\n\\n x = [0, 1]\\n i = 0\\n i, x[i] = 1, 2\\n print(x)\\n\\nSee also:\\n\\n **PEP 3132** - Extended Iterable Unpacking\\n The specification for the ``*target`` feature.\\n\\n\\nAugmented assignment statements\\n===============================\\n\\nAugmented assignment is the combination, in a single statement, of a\\nbinary operation and an assignment statement:\\n\\n augmented_assignment_stmt ::= augtarget augop (expression_list | yield_expression)\\n augtarget ::= identifier | attributeref | subscription | slicing\\n augop ::= \"+=\" | \"-=\" | \"*=\" | \"/=\" | \"//=\" | \"%=\" | \"**=\"\\n | \">>=\" | \"<<=\" | \"&=\" | \"^=\" | \"|=\"\\n\\n(See section *Primaries* for the syntax definitions for the last three\\nsymbols.)\\n\\nAn augmented assignment evaluates the target (which, unlike normal\\nassignment statements, cannot be an unpacking) and the expression\\nlist, performs the binary operation specific to the type of assignment\\non the two operands, and assigns the result to the original target.\\nThe target is only evaluated once.\\n\\nAn augmented assignment expression like ``x += 1`` can be rewritten as\\n``x = x + 1`` to achieve a similar, but not exactly equal effect. In\\nthe augmented version, ``x`` is only evaluated once. Also, when\\npossible, the actual operation is performed *in-place*, meaning that\\nrather than creating a new object and assigning that to the target,\\nthe old object is modified instead.\\n\\nWith the exception of assigning to tuples and multiple targets in a\\nsingle statement, the assignment done by augmented assignment\\nstatements is handled the same way as normal assignments. Similarly,\\nwith the exception of the possible *in-place* behavior, the binary\\noperation performed by augmented assignment is the same as the normal\\nbinary operations.\\n\\nFor targets which are attribute references, the same *caveat about\\nclass and instance attributes* applies as for regular assignments.\\n',\n'atom-identifiers':'\\nIdentifiers (Names)\\n*******************\\n\\nAn identifier occurring as an atom is a name. See section\\n*Identifiers and keywords* for lexical definition and section *Naming\\nand binding* for documentation of naming and binding.\\n\\nWhen the name is bound to an object, evaluation of the atom yields\\nthat object. When a name is not bound, an attempt to evaluate it\\nraises a ``NameError`` exception.\\n\\n**Private name mangling:** When an identifier that textually occurs in\\na class definition begins with two or more underscore characters and\\ndoes not end in two or more underscores, it is considered a *private\\nname* of that class. Private names are transformed to a longer form\\nbefore code is generated for them. The transformation inserts the\\nclass name in front of the name, with leading underscores removed, and\\na single underscore inserted in front of the class name. For example,\\nthe identifier ``__spam`` occurring in a class named ``Ham`` will be\\ntransformed to ``_Ham__spam``. This transformation is independent of\\nthe syntactical context in which the identifier is used. If the\\ntransformed name is extremely long (longer than 255 characters),\\nimplementation defined truncation may happen. If the class name\\nconsists only of underscores, no transformation is done.\\n',\n'atom-literals':\"\\nLiterals\\n********\\n\\nPython supports string and bytes literals and various numeric\\nliterals:\\n\\n literal ::= stringliteral | bytesliteral\\n | integer | floatnumber | imagnumber\\n\\nEvaluation of a literal yields an object of the given type (string,\\nbytes, integer, floating point number, complex number) with the given\\nvalue. The value may be approximated in the case of floating point\\nand imaginary (complex) literals. See section *Literals* for details.\\n\\nAll literals correspond to immutable data types, and hence the\\nobject's identity is less important than its value. Multiple\\nevaluations of literals with the same value (either the same\\noccurrence in the program text or a different occurrence) may obtain\\nthe same object or a different object with the same value.\\n\",\n'attribute-access':'\\nCustomizing attribute access\\n****************************\\n\\nThe following methods can be defined to customize the meaning of\\nattribute access (use of, assignment to, or deletion of ``x.name``)\\nfor class instances.\\n\\nobject.__getattr__(self, name)\\n\\n Called when an attribute lookup has not found the attribute in the\\n usual places (i.e. it is not an instance attribute nor is it found\\n in the class tree for ``self``). ``name`` is the attribute name.\\n This method should return the (computed) attribute value or raise\\n an ``AttributeError`` exception.\\n\\n Note that if the attribute is found through the normal mechanism,\\n ``__getattr__()`` is not called. (This is an intentional asymmetry\\n between ``__getattr__()`` and ``__setattr__()``.) This is done both\\n for efficiency reasons and because otherwise ``__getattr__()``\\n would have no way to access other attributes of the instance. Note\\n that at least for instance variables, you can fake total control by\\n not inserting any values in the instance attribute dictionary (but\\n instead inserting them in another object). See the\\n ``__getattribute__()`` method below for a way to actually get total\\n control over attribute access.\\n\\nobject.__getattribute__(self, name)\\n\\n Called unconditionally to implement attribute accesses for\\n instances of the class. If the class also defines\\n ``__getattr__()``, the latter will not be called unless\\n ``__getattribute__()`` either calls it explicitly or raises an\\n ``AttributeError``. This method should return the (computed)\\n attribute value or raise an ``AttributeError`` exception. In order\\n to avoid infinite recursion in this method, its implementation\\n should always call the base class method with the same name to\\n access any attributes it needs, for example,\\n ``object.__getattribute__(self, name)``.\\n\\n Note: This method may still be bypassed when looking up special methods\\n as the result of implicit invocation via language syntax or\\n built-in functions. See *Special method lookup*.\\n\\nobject.__setattr__(self, name, value)\\n\\n Called when an attribute assignment is attempted. This is called\\n instead of the normal mechanism (i.e. store the value in the\\n instance dictionary). *name* is the attribute name, *value* is the\\n value to be assigned to it.\\n\\n If ``__setattr__()`` wants to assign to an instance attribute, it\\n should call the base class method with the same name, for example,\\n ``object.__setattr__(self, name, value)``.\\n\\nobject.__delattr__(self, name)\\n\\n Like ``__setattr__()`` but for attribute deletion instead of\\n assignment. This should only be implemented if ``del obj.name`` is\\n meaningful for the object.\\n\\nobject.__dir__(self)\\n\\n Called when ``dir()`` is called on the object. A sequence must be\\n returned. ``dir()`` converts the returned sequence to a list and\\n sorts it.\\n\\n\\nImplementing Descriptors\\n========================\\n\\nThe following methods only apply when an instance of the class\\ncontaining the method (a so-called *descriptor* class) appears in an\\n*owner* class (the descriptor must be in either the owner\\'s class\\ndictionary or in the class dictionary for one of its parents). In the\\nexamples below, \"the attribute\" refers to the attribute whose name is\\nthe key of the property in the owner class\\' ``__dict__``.\\n\\nobject.__get__(self, instance, owner)\\n\\n Called to get the attribute of the owner class (class attribute\\n access) or of an instance of that class (instance attribute\\n access). *owner* is always the owner class, while *instance* is the\\n instance that the attribute was accessed through, or ``None`` when\\n the attribute is accessed through the *owner*. This method should\\n return the (computed) attribute value or raise an\\n ``AttributeError`` exception.\\n\\nobject.__set__(self, instance, value)\\n\\n Called to set the attribute on an instance *instance* of the owner\\n class to a new value, *value*.\\n\\nobject.__delete__(self, instance)\\n\\n Called to delete the attribute on an instance *instance* of the\\n owner class.\\n\\n\\nInvoking Descriptors\\n====================\\n\\nIn general, a descriptor is an object attribute with \"binding\\nbehavior\", one whose attribute access has been overridden by methods\\nin the descriptor protocol: ``__get__()``, ``__set__()``, and\\n``__delete__()``. If any of those methods are defined for an object,\\nit is said to be a descriptor.\\n\\nThe default behavior for attribute access is to get, set, or delete\\nthe attribute from an object\\'s dictionary. For instance, ``a.x`` has a\\nlookup chain starting with ``a.__dict__[\\'x\\']``, then\\n``type(a).__dict__[\\'x\\']``, and continuing through the base classes of\\n``type(a)`` excluding metaclasses.\\n\\nHowever, if the looked-up value is an object defining one of the\\ndescriptor methods, then Python may override the default behavior and\\ninvoke the descriptor method instead. Where this occurs in the\\nprecedence chain depends on which descriptor methods were defined and\\nhow they were called.\\n\\nThe starting point for descriptor invocation is a binding, ``a.x``.\\nHow the arguments are assembled depends on ``a``:\\n\\nDirect Call\\n The simplest and least common call is when user code directly\\n invokes a descriptor method: ``x.__get__(a)``.\\n\\nInstance Binding\\n If binding to an object instance, ``a.x`` is transformed into the\\n call: ``type(a).__dict__[\\'x\\'].__get__(a, type(a))``.\\n\\nClass Binding\\n If binding to a class, ``A.x`` is transformed into the call:\\n ``A.__dict__[\\'x\\'].__get__(None, A)``.\\n\\nSuper Binding\\n If ``a`` is an instance of ``super``, then the binding ``super(B,\\n obj).m()`` searches ``obj.__class__.__mro__`` for the base class\\n ``A`` immediately preceding ``B`` and then invokes the descriptor\\n with the call: ``A.__dict__[\\'m\\'].__get__(obj, obj.__class__)``.\\n\\nFor instance bindings, the precedence of descriptor invocation depends\\non the which descriptor methods are defined. A descriptor can define\\nany combination of ``__get__()``, ``__set__()`` and ``__delete__()``.\\nIf it does not define ``__get__()``, then accessing the attribute will\\nreturn the descriptor object itself unless there is a value in the\\nobject\\'s instance dictionary. If the descriptor defines ``__set__()``\\nand/or ``__delete__()``, it is a data descriptor; if it defines\\nneither, it is a non-data descriptor. Normally, data descriptors\\ndefine both ``__get__()`` and ``__set__()``, while non-data\\ndescriptors have just the ``__get__()`` method. Data descriptors with\\n``__set__()`` and ``__get__()`` defined always override a redefinition\\nin an instance dictionary. In contrast, non-data descriptors can be\\noverridden by instances.\\n\\nPython methods (including ``staticmethod()`` and ``classmethod()``)\\nare implemented as non-data descriptors. Accordingly, instances can\\nredefine and override methods. This allows individual instances to\\nacquire behaviors that differ from other instances of the same class.\\n\\nThe ``property()`` function is implemented as a data descriptor.\\nAccordingly, instances cannot override the behavior of a property.\\n\\n\\n__slots__\\n=========\\n\\nBy default, instances of classes have a dictionary for attribute\\nstorage. This wastes space for objects having very few instance\\nvariables. The space consumption can become acute when creating large\\nnumbers of instances.\\n\\nThe default can be overridden by defining *__slots__* in a class\\ndefinition. The *__slots__* declaration takes a sequence of instance\\nvariables and reserves just enough space in each instance to hold a\\nvalue for each variable. Space is saved because *__dict__* is not\\ncreated for each instance.\\n\\nobject.__slots__\\n\\n This class variable can be assigned a string, iterable, or sequence\\n of strings with variable names used by instances. If defined in a\\n class, *__slots__* reserves space for the declared variables and\\n prevents the automatic creation of *__dict__* and *__weakref__* for\\n each instance.\\n\\n\\nNotes on using *__slots__*\\n--------------------------\\n\\n* When inheriting from a class without *__slots__*, the *__dict__*\\n attribute of that class will always be accessible, so a *__slots__*\\n definition in the subclass is meaningless.\\n\\n* Without a *__dict__* variable, instances cannot be assigned new\\n variables not listed in the *__slots__* definition. Attempts to\\n assign to an unlisted variable name raises ``AttributeError``. If\\n dynamic assignment of new variables is desired, then add\\n ``\\'__dict__\\'`` to the sequence of strings in the *__slots__*\\n declaration.\\n\\n* Without a *__weakref__* variable for each instance, classes defining\\n *__slots__* do not support weak references to its instances. If weak\\n reference support is needed, then add ``\\'__weakref__\\'`` to the\\n sequence of strings in the *__slots__* declaration.\\n\\n* *__slots__* are implemented at the class level by creating\\n descriptors (*Implementing Descriptors*) for each variable name. As\\n a result, class attributes cannot be used to set default values for\\n instance variables defined by *__slots__*; otherwise, the class\\n attribute would overwrite the descriptor assignment.\\n\\n* The action of a *__slots__* declaration is limited to the class\\n where it is defined. As a result, subclasses will have a *__dict__*\\n unless they also define *__slots__* (which must only contain names\\n of any *additional* slots).\\n\\n* If a class defines a slot also defined in a base class, the instance\\n variable defined by the base class slot is inaccessible (except by\\n retrieving its descriptor directly from the base class). This\\n renders the meaning of the program undefined. In the future, a\\n check may be added to prevent this.\\n\\n* Nonempty *__slots__* does not work for classes derived from\\n \"variable-length\" built-in types such as ``int``, ``str`` and\\n ``tuple``.\\n\\n* Any non-string iterable may be assigned to *__slots__*. Mappings may\\n also be used; however, in the future, special meaning may be\\n assigned to the values corresponding to each key.\\n\\n* *__class__* assignment works only if both classes have the same\\n *__slots__*.\\n',\n'attribute-references':'\\nAttribute references\\n********************\\n\\nAn attribute reference is a primary followed by a period and a name:\\n\\n attributeref ::= primary \".\" identifier\\n\\nThe primary must evaluate to an object of a type that supports\\nattribute references, which most objects do. This object is then\\nasked to produce the attribute whose name is the identifier (which can\\nbe customized by overriding the ``__getattr__()`` method). If this\\nattribute is not available, the exception ``AttributeError`` is\\nraised. Otherwise, the type and value of the object produced is\\ndetermined by the object. Multiple evaluations of the same attribute\\nreference may yield different objects.\\n',\n'augassign':'\\nAugmented assignment statements\\n*******************************\\n\\nAugmented assignment is the combination, in a single statement, of a\\nbinary operation and an assignment statement:\\n\\n augmented_assignment_stmt ::= augtarget augop (expression_list | yield_expression)\\n augtarget ::= identifier | attributeref | subscription | slicing\\n augop ::= \"+=\" | \"-=\" | \"*=\" | \"/=\" | \"//=\" | \"%=\" | \"**=\"\\n | \">>=\" | \"<<=\" | \"&=\" | \"^=\" | \"|=\"\\n\\n(See section *Primaries* for the syntax definitions for the last three\\nsymbols.)\\n\\nAn augmented assignment evaluates the target (which, unlike normal\\nassignment statements, cannot be an unpacking) and the expression\\nlist, performs the binary operation specific to the type of assignment\\non the two operands, and assigns the result to the original target.\\nThe target is only evaluated once.\\n\\nAn augmented assignment expression like ``x += 1`` can be rewritten as\\n``x = x + 1`` to achieve a similar, but not exactly equal effect. In\\nthe augmented version, ``x`` is only evaluated once. Also, when\\npossible, the actual operation is performed *in-place*, meaning that\\nrather than creating a new object and assigning that to the target,\\nthe old object is modified instead.\\n\\nWith the exception of assigning to tuples and multiple targets in a\\nsingle statement, the assignment done by augmented assignment\\nstatements is handled the same way as normal assignments. Similarly,\\nwith the exception of the possible *in-place* behavior, the binary\\noperation performed by augmented assignment is the same as the normal\\nbinary operations.\\n\\nFor targets which are attribute references, the same *caveat about\\nclass and instance attributes* applies as for regular assignments.\\n',\n'binary':'\\nBinary arithmetic operations\\n****************************\\n\\nThe binary arithmetic operations have the conventional priority\\nlevels. Note that some of these operations also apply to certain non-\\nnumeric types. Apart from the power operator, there are only two\\nlevels, one for multiplicative operators and one for additive\\noperators:\\n\\n m_expr ::= u_expr | m_expr \"*\" u_expr | m_expr \"//\" u_expr | m_expr \"/\" u_expr\\n | m_expr \"%\" u_expr\\n a_expr ::= m_expr | a_expr \"+\" m_expr | a_expr \"-\" m_expr\\n\\nThe ``*`` (multiplication) operator yields the product of its\\narguments. The arguments must either both be numbers, or one argument\\nmust be an integer and the other must be a sequence. In the former\\ncase, the numbers are converted to a common type and then multiplied\\ntogether. In the latter case, sequence repetition is performed; a\\nnegative repetition factor yields an empty sequence.\\n\\nThe ``/`` (division) and ``//`` (floor division) operators yield the\\nquotient of their arguments. The numeric arguments are first\\nconverted to a common type. Integer division yields a float, while\\nfloor division of integers results in an integer; the result is that\\nof mathematical division with the \\'floor\\' function applied to the\\nresult. Division by zero raises the ``ZeroDivisionError`` exception.\\n\\nThe ``%`` (modulo) operator yields the remainder from the division of\\nthe first argument by the second. The numeric arguments are first\\nconverted to a common type. A zero right argument raises the\\n``ZeroDivisionError`` exception. The arguments may be floating point\\nnumbers, e.g., ``3.14%0.7`` equals ``0.34`` (since ``3.14`` equals\\n``4*0.7 + 0.34``.) The modulo operator always yields a result with\\nthe same sign as its second operand (or zero); the absolute value of\\nthe result is strictly smaller than the absolute value of the second\\noperand [1].\\n\\nThe floor division and modulo operators are connected by the following\\nidentity: ``x == (x//y)*y + (x%y)``. Floor division and modulo are\\nalso connected with the built-in function ``divmod()``: ``divmod(x, y)\\n== (x//y, x%y)``. [2].\\n\\nIn addition to performing the modulo operation on numbers, the ``%``\\noperator is also overloaded by string objects to perform old-style\\nstring formatting (also known as interpolation). The syntax for\\nstring formatting is described in the Python Library Reference,\\nsection *printf-style String Formatting*.\\n\\nThe floor division operator, the modulo operator, and the ``divmod()``\\nfunction are not defined for complex numbers. Instead, convert to a\\nfloating point number using the ``abs()`` function if appropriate.\\n\\nThe ``+`` (addition) operator yields the sum of its arguments. The\\narguments must either both be numbers or both sequences of the same\\ntype. In the former case, the numbers are converted to a common type\\nand then added together. In the latter case, the sequences are\\nconcatenated.\\n\\nThe ``-`` (subtraction) operator yields the difference of its\\narguments. The numeric arguments are first converted to a common\\ntype.\\n',\n'bitwise':'\\nBinary bitwise operations\\n*************************\\n\\nEach of the three bitwise operations has a different priority level:\\n\\n and_expr ::= shift_expr | and_expr \"&\" shift_expr\\n xor_expr ::= and_expr | xor_expr \"^\" and_expr\\n or_expr ::= xor_expr | or_expr \"|\" xor_expr\\n\\nThe ``&`` operator yields the bitwise AND of its arguments, which must\\nbe integers.\\n\\nThe ``^`` operator yields the bitwise XOR (exclusive OR) of its\\narguments, which must be integers.\\n\\nThe ``|`` operator yields the bitwise (inclusive) OR of its arguments,\\nwhich must be integers.\\n',\n'bltin-code-objects':'\\nCode Objects\\n************\\n\\nCode objects are used by the implementation to represent \"pseudo-\\ncompiled\" executable Python code such as a function body. They differ\\nfrom function objects because they don\\'t contain a reference to their\\nglobal execution environment. Code objects are returned by the built-\\nin ``compile()`` function and can be extracted from function objects\\nthrough their ``__code__`` attribute. See also the ``code`` module.\\n\\nA code object can be executed or evaluated by passing it (instead of a\\nsource string) to the ``exec()`` or ``eval()`` built-in functions.\\n\\nSee *The standard type hierarchy* for more information.\\n',\n'bltin-ellipsis-object':'\\nThe Ellipsis Object\\n*******************\\n\\nThis object is commonly used by slicing (see *Slicings*). It supports\\nno special operations. There is exactly one ellipsis object, named\\n``Ellipsis`` (a built-in name). ``type(Ellipsis)()`` produces the\\n``Ellipsis`` singleton.\\n\\nIt is written as ``Ellipsis`` or ``...``.\\n',\n'bltin-null-object':\"\\nThe Null Object\\n***************\\n\\nThis object is returned by functions that don't explicitly return a\\nvalue. It supports no special operations. There is exactly one null\\nobject, named ``None`` (a built-in name). ``type(None)()`` produces\\nthe same singleton.\\n\\nIt is written as ``None``.\\n\",\n'bltin-type-objects':\"\\nType Objects\\n************\\n\\nType objects represent the various object types. An object's type is\\naccessed by the built-in function ``type()``. There are no special\\noperations on types. The standard module ``types`` defines names for\\nall standard built-in types.\\n\\nTypes are written like this: ``<class 'int'>``.\\n\",\n'booleans':'\\nBoolean operations\\n******************\\n\\n or_test ::= and_test | or_test \"or\" and_test\\n and_test ::= not_test | and_test \"and\" not_test\\n not_test ::= comparison | \"not\" not_test\\n\\nIn the context of Boolean operations, and also when expressions are\\nused by control flow statements, the following values are interpreted\\nas false: ``False``, ``None``, numeric zero of all types, and empty\\nstrings and containers (including strings, tuples, lists,\\ndictionaries, sets and frozensets). All other values are interpreted\\nas true. User-defined objects can customize their truth value by\\nproviding a ``__bool__()`` method.\\n\\nThe operator ``not`` yields ``True`` if its argument is false,\\n``False`` otherwise.\\n\\nThe expression ``x and y`` first evaluates *x*; if *x* is false, its\\nvalue is returned; otherwise, *y* is evaluated and the resulting value\\nis returned.\\n\\nThe expression ``x or y`` first evaluates *x*; if *x* is true, its\\nvalue is returned; otherwise, *y* is evaluated and the resulting value\\nis returned.\\n\\n(Note that neither ``and`` nor ``or`` restrict the value and type they\\nreturn to ``False`` and ``True``, but rather return the last evaluated\\nargument. This is sometimes useful, e.g., if ``s`` is a string that\\nshould be replaced by a default value if it is empty, the expression\\n``s or \\'foo\\'`` yields the desired value. Because ``not`` has to\\ninvent a value anyway, it does not bother to return a value of the\\nsame type as its argument, so e.g., ``not \\'foo\\'`` yields ``False``,\\nnot ``\\'\\'``.)\\n',\n'break':'\\nThe ``break`` statement\\n***********************\\n\\n break_stmt ::= \"break\"\\n\\n``break`` may only occur syntactically nested in a ``for`` or\\n``while`` loop, but not nested in a function or class definition\\nwithin that loop.\\n\\nIt terminates the nearest enclosing loop, skipping the optional\\n``else`` clause if the loop has one.\\n\\nIf a ``for`` loop is terminated by ``break``, the loop control target\\nkeeps its current value.\\n\\nWhen ``break`` passes control out of a ``try`` statement with a\\n``finally`` clause, that ``finally`` clause is executed before really\\nleaving the loop.\\n',\n'callable-types':'\\nEmulating callable objects\\n**************************\\n\\nobject.__call__(self[, args...])\\n\\n Called when the instance is \"called\" as a function; if this method\\n is defined, ``x(arg1, arg2, ...)`` is a shorthand for\\n ``x.__call__(arg1, arg2, ...)``.\\n',\n'calls':'\\nCalls\\n*****\\n\\nA call calls a callable object (e.g., a *function*) with a possibly\\nempty series of *arguments*:\\n\\n call ::= primary \"(\" [argument_list [\",\"] | comprehension] \")\"\\n argument_list ::= positional_arguments [\",\" keyword_arguments]\\n [\",\" \"*\" expression] [\",\" keyword_arguments]\\n [\",\" \"**\" expression]\\n | keyword_arguments [\",\" \"*\" expression]\\n [\",\" keyword_arguments] [\",\" \"**\" expression]\\n | \"*\" expression [\",\" keyword_arguments] [\",\" \"**\" expression]\\n | \"**\" expression\\n positional_arguments ::= expression (\",\" expression)*\\n keyword_arguments ::= keyword_item (\",\" keyword_item)*\\n keyword_item ::= identifier \"=\" expression\\n\\nA trailing comma may be present after the positional and keyword\\narguments but does not affect the semantics.\\n\\nThe primary must evaluate to a callable object (user-defined\\nfunctions, built-in functions, methods of built-in objects, class\\nobjects, methods of class instances, and all objects having a\\n``__call__()`` method are callable). All argument expressions are\\nevaluated before the call is attempted. Please refer to section\\n*Function definitions* for the syntax of formal *parameter* lists.\\n\\nIf keyword arguments are present, they are first converted to\\npositional arguments, as follows. First, a list of unfilled slots is\\ncreated for the formal parameters. If there are N positional\\narguments, they are placed in the first N slots. Next, for each\\nkeyword argument, the identifier is used to determine the\\ncorresponding slot (if the identifier is the same as the first formal\\nparameter name, the first slot is used, and so on). If the slot is\\nalready filled, a ``TypeError`` exception is raised. Otherwise, the\\nvalue of the argument is placed in the slot, filling it (even if the\\nexpression is ``None``, it fills the slot). When all arguments have\\nbeen processed, the slots that are still unfilled are filled with the\\ncorresponding default value from the function definition. (Default\\nvalues are calculated, once, when the function is defined; thus, a\\nmutable object such as a list or dictionary used as default value will\\nbe shared by all calls that don\\'t specify an argument value for the\\ncorresponding slot; this should usually be avoided.) If there are any\\nunfilled slots for which no default value is specified, a\\n``TypeError`` exception is raised. Otherwise, the list of filled\\nslots is used as the argument list for the call.\\n\\n**CPython implementation detail:** An implementation may provide\\nbuilt-in functions whose positional parameters do not have names, even\\nif they are \\'named\\' for the purpose of documentation, and which\\ntherefore cannot be supplied by keyword. In CPython, this is the case\\nfor functions implemented in C that use ``PyArg_ParseTuple()`` to\\nparse their arguments.\\n\\nIf there are more positional arguments than there are formal parameter\\nslots, a ``TypeError`` exception is raised, unless a formal parameter\\nusing the syntax ``*identifier`` is present; in this case, that formal\\nparameter receives a tuple containing the excess positional arguments\\n(or an empty tuple if there were no excess positional arguments).\\n\\nIf any keyword argument does not correspond to a formal parameter\\nname, a ``TypeError`` exception is raised, unless a formal parameter\\nusing the syntax ``**identifier`` is present; in this case, that\\nformal parameter receives a dictionary containing the excess keyword\\narguments (using the keywords as keys and the argument values as\\ncorresponding values), or a (new) empty dictionary if there were no\\nexcess keyword arguments.\\n\\nIf the syntax ``*expression`` appears in the function call,\\n``expression`` must evaluate to an iterable. Elements from this\\niterable are treated as if they were additional positional arguments;\\nif there are positional arguments *x1*, ..., *xN*, and ``expression``\\nevaluates to a sequence *y1*, ..., *yM*, this is equivalent to a call\\nwith M+N positional arguments *x1*, ..., *xN*, *y1*, ..., *yM*.\\n\\nA consequence of this is that although the ``*expression`` syntax may\\nappear *after* some keyword arguments, it is processed *before* the\\nkeyword arguments (and the ``**expression`` argument, if any -- see\\nbelow). So:\\n\\n >>> def f(a, b):\\n ... print(a, b)\\n ...\\n >>> f(b=1, *(2,))\\n 2 1\\n >>> f(a=1, *(2,))\\n Traceback (most recent call last):\\n File \"<stdin>\", line 1, in ?\\n TypeError: f() got multiple values for keyword argument \\'a\\'\\n >>> f(1, *(2,))\\n 1 2\\n\\nIt is unusual for both keyword arguments and the ``*expression``\\nsyntax to be used in the same call, so in practice this confusion does\\nnot arise.\\n\\nIf the syntax ``**expression`` appears in the function call,\\n``expression`` must evaluate to a mapping, the contents of which are\\ntreated as additional keyword arguments. In the case of a keyword\\nappearing in both ``expression`` and as an explicit keyword argument,\\na ``TypeError`` exception is raised.\\n\\nFormal parameters using the syntax ``*identifier`` or ``**identifier``\\ncannot be used as positional argument slots or as keyword argument\\nnames.\\n\\nA call always returns some value, possibly ``None``, unless it raises\\nan exception. How this value is computed depends on the type of the\\ncallable object.\\n\\nIf it is---\\n\\na user-defined function:\\n The code block for the function is executed, passing it the\\n argument list. The first thing the code block will do is bind the\\n formal parameters to the arguments; this is described in section\\n *Function definitions*. When the code block executes a ``return``\\n statement, this specifies the return value of the function call.\\n\\na built-in function or method:\\n The result is up to the interpreter; see *Built-in Functions* for\\n the descriptions of built-in functions and methods.\\n\\na class object:\\n A new instance of that class is returned.\\n\\na class instance method:\\n The corresponding user-defined function is called, with an argument\\n list that is one longer than the argument list of the call: the\\n instance becomes the first argument.\\n\\na class instance:\\n The class must define a ``__call__()`` method; the effect is then\\n the same as if that method was called.\\n',\n'class':'\\nClass definitions\\n*****************\\n\\nA class definition defines a class object (see section *The standard\\ntype hierarchy*):\\n\\n classdef ::= [decorators] \"class\" classname [inheritance] \":\" suite\\n inheritance ::= \"(\" [parameter_list] \")\"\\n classname ::= identifier\\n\\nA class definition is an executable statement. The inheritance list\\nusually gives a list of base classes (see *Customizing class creation*\\nfor more advanced uses), so each item in the list should evaluate to a\\nclass object which allows subclassing. Classes without an inheritance\\nlist inherit, by default, from the base class ``object``; hence,\\n\\n class Foo:\\n pass\\n\\nis equivalent to\\n\\n class Foo(object):\\n pass\\n\\nThe class\\'s suite is then executed in a new execution frame (see\\n*Naming and binding*), using a newly created local namespace and the\\noriginal global namespace. (Usually, the suite contains mostly\\nfunction definitions.) When the class\\'s suite finishes execution, its\\nexecution frame is discarded but its local namespace is saved. [4] A\\nclass object is then created using the inheritance list for the base\\nclasses and the saved local namespace for the attribute dictionary.\\nThe class name is bound to this class object in the original local\\nnamespace.\\n\\nClass creation can be customized heavily using *metaclasses*.\\n\\nClasses can also be decorated: just like when decorating functions,\\n\\n @f1(arg)\\n @f2\\n class Foo: pass\\n\\nis equivalent to\\n\\n class Foo: pass\\n Foo = f1(arg)(f2(Foo))\\n\\nThe evaluation rules for the decorator expressions are the same as for\\nfunction decorators. The result must be a class object, which is then\\nbound to the class name.\\n\\n**Programmer\\'s note:** Variables defined in the class definition are\\nclass attributes; they are shared by instances. Instance attributes\\ncan be set in a method with ``self.name = value``. Both class and\\ninstance attributes are accessible through the notation\\n\"``self.name``\", and an instance attribute hides a class attribute\\nwith the same name when accessed in this way. Class attributes can be\\nused as defaults for instance attributes, but using mutable values\\nthere can lead to unexpected results. *Descriptors* can be used to\\ncreate instance variables with different implementation details.\\n\\nSee also:\\n\\n **PEP 3115** - Metaclasses in Python 3 **PEP 3129** - Class\\n Decorators\\n\\n-[ Footnotes ]-\\n\\n[1] The exception is propagated to the invocation stack unless there\\n is a ``finally`` clause which happens to raise another exception.\\n That new exception causes the old one to be lost.\\n\\n[2] Currently, control \"flows off the end\" except in the case of an\\n exception or the execution of a ``return``, ``continue``, or\\n ``break`` statement.\\n\\n[3] A string literal appearing as the first statement in the function\\n body is transformed into the function\\'s ``__doc__`` attribute and\\n therefore the function\\'s *docstring*.\\n\\n[4] A string literal appearing as the first statement in the class\\n body is transformed into the namespace\\'s ``__doc__`` item and\\n therefore the class\\'s *docstring*.\\n',\n'comparisons':'\\nComparisons\\n***********\\n\\nUnlike C, all comparison operations in Python have the same priority,\\nwhich is lower than that of any arithmetic, shifting or bitwise\\noperation. Also unlike C, expressions like ``a < b < c`` have the\\ninterpretation that is conventional in mathematics:\\n\\n comparison ::= or_expr ( comp_operator or_expr )*\\n comp_operator ::= \"<\" | \">\" | \"==\" | \">=\" | \"<=\" | \"!=\"\\n | \"is\" [\"not\"] | [\"not\"] \"in\"\\n\\nComparisons yield boolean values: ``True`` or ``False``.\\n\\nComparisons can be chained arbitrarily, e.g., ``x < y <= z`` is\\nequivalent to ``x < y and y <= z``, except that ``y`` is evaluated\\nonly once (but in both cases ``z`` is not evaluated at all when ``x <\\ny`` is found to be false).\\n\\nFormally, if *a*, *b*, *c*, ..., *y*, *z* are expressions and *op1*,\\n*op2*, ..., *opN* are comparison operators, then ``a op1 b op2 c ... y\\nopN z`` is equivalent to ``a op1 b and b op2 c and ... y opN z``,\\nexcept that each expression is evaluated at most once.\\n\\nNote that ``a op1 b op2 c`` doesn\\'t imply any kind of comparison\\nbetween *a* and *c*, so that, e.g., ``x < y > z`` is perfectly legal\\n(though perhaps not pretty).\\n\\nThe operators ``<``, ``>``, ``==``, ``>=``, ``<=``, and ``!=`` compare\\nthe values of two objects. The objects need not have the same type.\\nIf both are numbers, they are converted to a common type. Otherwise,\\nthe ``==`` and ``!=`` operators *always* consider objects of different\\ntypes to be unequal, while the ``<``, ``>``, ``>=`` and ``<=``\\noperators raise a ``TypeError`` when comparing objects of different\\ntypes that do not implement these operators for the given pair of\\ntypes. You can control comparison behavior of objects of non-built-in\\ntypes by defining rich comparison methods like ``__gt__()``, described\\nin section *Basic customization*.\\n\\nComparison of objects of the same type depends on the type:\\n\\n* Numbers are compared arithmetically.\\n\\n* The values ``float(\\'NaN\\')`` and ``Decimal(\\'NaN\\')`` are special. The\\n are identical to themselves, ``x is x`` but are not equal to\\n themselves, ``x != x``. Additionally, comparing any value to a\\n not-a-number value will return ``False``. For example, both ``3 <\\n float(\\'NaN\\')`` and ``float(\\'NaN\\') < 3`` will return ``False``.\\n\\n* Bytes objects are compared lexicographically using the numeric\\n values of their elements.\\n\\n* Strings are compared lexicographically using the numeric equivalents\\n (the result of the built-in function ``ord()``) of their characters.\\n [3] String and bytes object can\\'t be compared!\\n\\n* Tuples and lists are compared lexicographically using comparison of\\n corresponding elements. This means that to compare equal, each\\n element must compare equal and the two sequences must be of the same\\n type and have the same length.\\n\\n If not equal, the sequences are ordered the same as their first\\n differing elements. For example, ``[1,2,x] <= [1,2,y]`` has the\\n same value as ``x <= y``. If the corresponding element does not\\n exist, the shorter sequence is ordered first (for example, ``[1,2] <\\n [1,2,3]``).\\n\\n* Mappings (dictionaries) compare equal if and only if they have the\\n same ``(key, value)`` pairs. Order comparisons ``(\\'<\\', \\'<=\\', \\'>=\\',\\n \\'>\\')`` raise ``TypeError``.\\n\\n* Sets and frozensets define comparison operators to mean subset and\\n superset tests. Those relations do not define total orderings (the\\n two sets ``{1,2}`` and {2,3} are not equal, nor subsets of one\\n another, nor supersets of one another). Accordingly, sets are not\\n appropriate arguments for functions which depend on total ordering.\\n For example, ``min()``, ``max()``, and ``sorted()`` produce\\n undefined results given a list of sets as inputs.\\n\\n* Most other objects of built-in types compare unequal unless they are\\n the same object; the choice whether one object is considered smaller\\n or larger than another one is made arbitrarily but consistently\\n within one execution of a program.\\n\\nComparison of objects of the differing types depends on whether either\\nof the types provide explicit support for the comparison. Most\\nnumeric types can be compared with one another. When cross-type\\ncomparison is not supported, the comparison method returns\\n``NotImplemented``.\\n\\nThe operators ``in`` and ``not in`` test for membership. ``x in s``\\nevaluates to true if *x* is a member of *s*, and false otherwise. ``x\\nnot in s`` returns the negation of ``x in s``. All built-in sequences\\nand set types support this as well as dictionary, for which ``in``\\ntests whether a the dictionary has a given key. For container types\\nsuch as list, tuple, set, frozenset, dict, or collections.deque, the\\nexpression ``x in y`` is equivalent to ``any(x is e or x == e for e in\\ny)``.\\n\\nFor the string and bytes types, ``x in y`` is true if and only if *x*\\nis a substring of *y*. An equivalent test is ``y.find(x) != -1``.\\nEmpty strings are always considered to be a substring of any other\\nstring, so ``\"\" in \"abc\"`` will return ``True``.\\n\\nFor user-defined classes which define the ``__contains__()`` method,\\n``x in y`` is true if and only if ``y.__contains__(x)`` is true.\\n\\nFor user-defined classes which do not define ``__contains__()`` but do\\ndefine ``__iter__()``, ``x in y`` is true if some value ``z`` with ``x\\n== z`` is produced while iterating over ``y``. If an exception is\\nraised during the iteration, it is as if ``in`` raised that exception.\\n\\nLastly, the old-style iteration protocol is tried: if a class defines\\n``__getitem__()``, ``x in y`` is true if and only if there is a non-\\nnegative integer index *i* such that ``x == y[i]``, and all lower\\ninteger indices do not raise ``IndexError`` exception. (If any other\\nexception is raised, it is as if ``in`` raised that exception).\\n\\nThe operator ``not in`` is defined to have the inverse true value of\\n``in``.\\n\\nThe operators ``is`` and ``is not`` test for object identity: ``x is\\ny`` is true if and only if *x* and *y* are the same object. ``x is\\nnot y`` yields the inverse truth value. [4]\\n',\n'compound':'\\nCompound statements\\n*******************\\n\\nCompound statements contain (groups of) other statements; they affect\\nor control the execution of those other statements in some way. In\\ngeneral, compound statements span multiple lines, although in simple\\nincarnations a whole compound statement may be contained in one line.\\n\\nThe ``if``, ``while`` and ``for`` statements implement traditional\\ncontrol flow constructs. ``try`` specifies exception handlers and/or\\ncleanup code for a group of statements, while the ``with`` statement\\nallows the execution of initialization and finalization code around a\\nblock of code. Function and class definitions are also syntactically\\ncompound statements.\\n\\nCompound statements consist of one or more \\'clauses.\\' A clause\\nconsists of a header and a \\'suite.\\' The clause headers of a\\nparticular compound statement are all at the same indentation level.\\nEach clause header begins with a uniquely identifying keyword and ends\\nwith a colon. A suite is a group of statements controlled by a\\nclause. A suite can be one or more semicolon-separated simple\\nstatements on the same line as the header, following the header\\'s\\ncolon, or it can be one or more indented statements on subsequent\\nlines. Only the latter form of suite can contain nested compound\\nstatements; the following is illegal, mostly because it wouldn\\'t be\\nclear to which ``if`` clause a following ``else`` clause would belong:\\n\\n if test1: if test2: print(x)\\n\\nAlso note that the semicolon binds tighter than the colon in this\\ncontext, so that in the following example, either all or none of the\\n``print()`` calls are executed:\\n\\n if x < y < z: print(x); print(y); print(z)\\n\\nSummarizing:\\n\\n compound_stmt ::= if_stmt\\n | while_stmt\\n | for_stmt\\n | try_stmt\\n | with_stmt\\n | funcdef\\n | classdef\\n suite ::= stmt_list NEWLINE | NEWLINE INDENT statement+ DEDENT\\n statement ::= stmt_list NEWLINE | compound_stmt\\n stmt_list ::= simple_stmt (\";\" simple_stmt)* [\";\"]\\n\\nNote that statements always end in a ``NEWLINE`` possibly followed by\\na ``DEDENT``. Also note that optional continuation clauses always\\nbegin with a keyword that cannot start a statement, thus there are no\\nambiguities (the \\'dangling ``else``\\' problem is solved in Python by\\nrequiring nested ``if`` statements to be indented).\\n\\nThe formatting of the grammar rules in the following sections places\\neach clause on a separate line for clarity.\\n\\n\\nThe ``if`` statement\\n====================\\n\\nThe ``if`` statement is used for conditional execution:\\n\\n if_stmt ::= \"if\" expression \":\" suite\\n ( \"elif\" expression \":\" suite )*\\n [\"else\" \":\" suite]\\n\\nIt selects exactly one of the suites by evaluating the expressions one\\nby one until one is found to be true (see section *Boolean operations*\\nfor the definition of true and false); then that suite is executed\\n(and no other part of the ``if`` statement is executed or evaluated).\\nIf all expressions are false, the suite of the ``else`` clause, if\\npresent, is executed.\\n\\n\\nThe ``while`` statement\\n=======================\\n\\nThe ``while`` statement is used for repeated execution as long as an\\nexpression is true:\\n\\n while_stmt ::= \"while\" expression \":\" suite\\n [\"else\" \":\" suite]\\n\\nThis repeatedly tests the expression and, if it is true, executes the\\nfirst suite; if the expression is false (which may be the first time\\nit is tested) the suite of the ``else`` clause, if present, is\\nexecuted and the loop terminates.\\n\\nA ``break`` statement executed in the first suite terminates the loop\\nwithout executing the ``else`` clause\\'s suite. A ``continue``\\nstatement executed in the first suite skips the rest of the suite and\\ngoes back to testing the expression.\\n\\n\\nThe ``for`` statement\\n=====================\\n\\nThe ``for`` statement is used to iterate over the elements of a\\nsequence (such as a string, tuple or list) or other iterable object:\\n\\n for_stmt ::= \"for\" target_list \"in\" expression_list \":\" suite\\n [\"else\" \":\" suite]\\n\\nThe expression list is evaluated once; it should yield an iterable\\nobject. An iterator is created for the result of the\\n``expression_list``. The suite is then executed once for each item\\nprovided by the iterator, in the order of ascending indices. Each\\nitem in turn is assigned to the target list using the standard rules\\nfor assignments (see *Assignment statements*), and then the suite is\\nexecuted. When the items are exhausted (which is immediately when the\\nsequence is empty or an iterator raises a ``StopIteration``\\nexception), the suite in the ``else`` clause, if present, is executed,\\nand the loop terminates.\\n\\nA ``break`` statement executed in the first suite terminates the loop\\nwithout executing the ``else`` clause\\'s suite. A ``continue``\\nstatement executed in the first suite skips the rest of the suite and\\ncontinues with the next item, or with the ``else`` clause if there was\\nno next item.\\n\\nThe suite may assign to the variable(s) in the target list; this does\\nnot affect the next item assigned to it.\\n\\nNames in the target list are not deleted when the loop is finished,\\nbut if the sequence is empty, it will not have been assigned to at all\\nby the loop. Hint: the built-in function ``range()`` returns an\\niterator of integers suitable to emulate the effect of Pascal\\'s ``for\\ni := a to b do``; e.g., ``list(range(3))`` returns the list ``[0, 1,\\n2]``.\\n\\nNote: There is a subtlety when the sequence is being modified by the loop\\n (this can only occur for mutable sequences, i.e. lists). An\\n internal counter is used to keep track of which item is used next,\\n and this is incremented on each iteration. When this counter has\\n reached the length of the sequence the loop terminates. This means\\n that if the suite deletes the current (or a previous) item from the\\n sequence, the next item will be skipped (since it gets the index of\\n the current item which has already been treated). Likewise, if the\\n suite inserts an item in the sequence before the current item, the\\n current item will be treated again the next time through the loop.\\n This can lead to nasty bugs that can be avoided by making a\\n temporary copy using a slice of the whole sequence, e.g.,\\n\\n for x in a[:]:\\n if x < 0: a.remove(x)\\n\\n\\nThe ``try`` statement\\n=====================\\n\\nThe ``try`` statement specifies exception handlers and/or cleanup code\\nfor a group of statements:\\n\\n try_stmt ::= try1_stmt | try2_stmt\\n try1_stmt ::= \"try\" \":\" suite\\n (\"except\" [expression [\"as\" target]] \":\" suite)+\\n [\"else\" \":\" suite]\\n [\"finally\" \":\" suite]\\n try2_stmt ::= \"try\" \":\" suite\\n \"finally\" \":\" suite\\n\\nThe ``except`` clause(s) specify one or more exception handlers. When\\nno exception occurs in the ``try`` clause, no exception handler is\\nexecuted. When an exception occurs in the ``try`` suite, a search for\\nan exception handler is started. This search inspects the except\\nclauses in turn until one is found that matches the exception. An\\nexpression-less except clause, if present, must be last; it matches\\nany exception. For an except clause with an expression, that\\nexpression is evaluated, and the clause matches the exception if the\\nresulting object is \"compatible\" with the exception. An object is\\ncompatible with an exception if it is the class or a base class of the\\nexception object or a tuple containing an item compatible with the\\nexception.\\n\\nIf no except clause matches the exception, the search for an exception\\nhandler continues in the surrounding code and on the invocation stack.\\n[1]\\n\\nIf the evaluation of an expression in the header of an except clause\\nraises an exception, the original search for a handler is canceled and\\na search starts for the new exception in the surrounding code and on\\nthe call stack (it is treated as if the entire ``try`` statement\\nraised the exception).\\n\\nWhen a matching except clause is found, the exception is assigned to\\nthe target specified after the ``as`` keyword in that except clause,\\nif present, and the except clause\\'s suite is executed. All except\\nclauses must have an executable block. When the end of this block is\\nreached, execution continues normally after the entire try statement.\\n(This means that if two nested handlers exist for the same exception,\\nand the exception occurs in the try clause of the inner handler, the\\nouter handler will not handle the exception.)\\n\\nWhen an exception has been assigned using ``as target``, it is cleared\\nat the end of the except clause. This is as if\\n\\n except E as N:\\n foo\\n\\nwas translated to\\n\\n except E as N:\\n try:\\n foo\\n finally:\\n del N\\n\\nThis means the exception must be assigned to a different name to be\\nable to refer to it after the except clause. Exceptions are cleared\\nbecause with the traceback attached to them, they form a reference\\ncycle with the stack frame, keeping all locals in that frame alive\\nuntil the next garbage collection occurs.\\n\\nBefore an except clause\\'s suite is executed, details about the\\nexception are stored in the ``sys`` module and can be access via\\n``sys.exc_info()``. ``sys.exc_info()`` returns a 3-tuple consisting of\\nthe exception class, the exception instance and a traceback object\\n(see section *The standard type hierarchy*) identifying the point in\\nthe program where the exception occurred. ``sys.exc_info()`` values\\nare restored to their previous values (before the call) when returning\\nfrom a function that handled an exception.\\n\\nThe optional ``else`` clause is executed if and when control flows off\\nthe end of the ``try`` clause. [2] Exceptions in the ``else`` clause\\nare not handled by the preceding ``except`` clauses.\\n\\nIf ``finally`` is present, it specifies a \\'cleanup\\' handler. The\\n``try`` clause is executed, including any ``except`` and ``else``\\nclauses. If an exception occurs in any of the clauses and is not\\nhandled, the exception is temporarily saved. The ``finally`` clause is\\nexecuted. If there is a saved exception it is re-raised at the end of\\nthe ``finally`` clause. If the ``finally`` clause raises another\\nexception, the saved exception is set as the context of the new\\nexception. If the ``finally`` clause executes a ``return`` or\\n``break`` statement, the saved exception is discarded:\\n\\n def f():\\n try:\\n 1/0\\n finally:\\n return 42\\n\\n >>> f()\\n 42\\n\\nThe exception information is not available to the program during\\nexecution of the ``finally`` clause.\\n\\nWhen a ``return``, ``break`` or ``continue`` statement is executed in\\nthe ``try`` suite of a ``try``...``finally`` statement, the\\n``finally`` clause is also executed \\'on the way out.\\' A ``continue``\\nstatement is illegal in the ``finally`` clause. (The reason is a\\nproblem with the current implementation --- this restriction may be\\nlifted in the future).\\n\\nAdditional information on exceptions can be found in section\\n*Exceptions*, and information on using the ``raise`` statement to\\ngenerate exceptions may be found in section *The raise statement*.\\n\\n\\nThe ``with`` statement\\n======================\\n\\nThe ``with`` statement is used to wrap the execution of a block with\\nmethods defined by a context manager (see section *With Statement\\nContext Managers*). This allows common\\n``try``...``except``...``finally`` usage patterns to be encapsulated\\nfor convenient reuse.\\n\\n with_stmt ::= \"with\" with_item (\",\" with_item)* \":\" suite\\n with_item ::= expression [\"as\" target]\\n\\nThe execution of the ``with`` statement with one \"item\" proceeds as\\nfollows:\\n\\n1. The context expression (the expression given in the ``with_item``)\\n is evaluated to obtain a context manager.\\n\\n2. The context manager\\'s ``__exit__()`` is loaded for later use.\\n\\n3. The context manager\\'s ``__enter__()`` method is invoked.\\n\\n4. If a target was included in the ``with`` statement, the return\\n value from ``__enter__()`` is assigned to it.\\n\\n Note: The ``with`` statement guarantees that if the ``__enter__()``\\n method returns without an error, then ``__exit__()`` will always\\n be called. Thus, if an error occurs during the assignment to the\\n target list, it will be treated the same as an error occurring\\n within the suite would be. See step 6 below.\\n\\n5. The suite is executed.\\n\\n6. The context manager\\'s ``__exit__()`` method is invoked. If an\\n exception caused the suite to be exited, its type, value, and\\n traceback are passed as arguments to ``__exit__()``. Otherwise,\\n three ``None`` arguments are supplied.\\n\\n If the suite was exited due to an exception, and the return value\\n from the ``__exit__()`` method was false, the exception is\\n reraised. If the return value was true, the exception is\\n suppressed, and execution continues with the statement following\\n the ``with`` statement.\\n\\n If the suite was exited for any reason other than an exception, the\\n return value from ``__exit__()`` is ignored, and execution proceeds\\n at the normal location for the kind of exit that was taken.\\n\\nWith more than one item, the context managers are processed as if\\nmultiple ``with`` statements were nested:\\n\\n with A() as a, B() as b:\\n suite\\n\\nis equivalent to\\n\\n with A() as a:\\n with B() as b:\\n suite\\n\\nChanged in version 3.1: Support for multiple context expressions.\\n\\nSee also:\\n\\n **PEP 0343** - The \"with\" statement\\n The specification, background, and examples for the Python\\n ``with`` statement.\\n\\n\\nFunction definitions\\n====================\\n\\nA function definition defines a user-defined function object (see\\nsection *The standard type hierarchy*):\\n\\n funcdef ::= [decorators] \"def\" funcname \"(\" [parameter_list] \")\" [\"->\" expression] \":\" suite\\n decorators ::= decorator+\\n decorator ::= \"@\" dotted_name [\"(\" [parameter_list [\",\"]] \")\"] NEWLINE\\n dotted_name ::= identifier (\".\" identifier)*\\n parameter_list ::= (defparameter \",\")*\\n ( \"*\" [parameter] (\",\" defparameter)* [\",\" \"**\" parameter]\\n | \"**\" parameter\\n | defparameter [\",\"] )\\n parameter ::= identifier [\":\" expression]\\n defparameter ::= parameter [\"=\" expression]\\n funcname ::= identifier\\n\\nA function definition is an executable statement. Its execution binds\\nthe function name in the current local namespace to a function object\\n(a wrapper around the executable code for the function). This\\nfunction object contains a reference to the current global namespace\\nas the global namespace to be used when the function is called.\\n\\nThe function definition does not execute the function body; this gets\\nexecuted only when the function is called. [3]\\n\\nA function definition may be wrapped by one or more *decorator*\\nexpressions. Decorator expressions are evaluated when the function is\\ndefined, in the scope that contains the function definition. The\\nresult must be a callable, which is invoked with the function object\\nas the only argument. The returned value is bound to the function name\\ninstead of the function object. Multiple decorators are applied in\\nnested fashion. For example, the following code\\n\\n @f1(arg)\\n @f2\\n def func(): pass\\n\\nis equivalent to\\n\\n def func(): pass\\n func = f1(arg)(f2(func))\\n\\nWhen one or more *parameters* have the form *parameter* ``=``\\n*expression*, the function is said to have \"default parameter values.\"\\nFor a parameter with a default value, the corresponding *argument* may\\nbe omitted from a call, in which case the parameter\\'s default value is\\nsubstituted. If a parameter has a default value, all following\\nparameters up until the \"``*``\" must also have a default value ---\\nthis is a syntactic restriction that is not expressed by the grammar.\\n\\n**Default parameter values are evaluated when the function definition\\nis executed.** This means that the expression is evaluated once, when\\nthe function is defined, and that the same \"pre-computed\" value is\\nused for each call. This is especially important to understand when a\\ndefault parameter is a mutable object, such as a list or a dictionary:\\nif the function modifies the object (e.g. by appending an item to a\\nlist), the default value is in effect modified. This is generally not\\nwhat was intended. A way around this is to use ``None`` as the\\ndefault, and explicitly test for it in the body of the function, e.g.:\\n\\n def whats_on_the_telly(penguin=None):\\n if penguin is None:\\n penguin = []\\n penguin.append(\"property of the zoo\")\\n return penguin\\n\\nFunction call semantics are described in more detail in section\\n*Calls*. A function call always assigns values to all parameters\\nmentioned in the parameter list, either from position arguments, from\\nkeyword arguments, or from default values. If the form\\n\"``*identifier``\" is present, it is initialized to a tuple receiving\\nany excess positional parameters, defaulting to the empty tuple. If\\nthe form \"``**identifier``\" is present, it is initialized to a new\\ndictionary receiving any excess keyword arguments, defaulting to a new\\nempty dictionary. Parameters after \"``*``\" or \"``*identifier``\" are\\nkeyword-only parameters and may only be passed used keyword arguments.\\n\\nParameters may have annotations of the form \"``: expression``\"\\nfollowing the parameter name. Any parameter may have an annotation\\neven those of the form ``*identifier`` or ``**identifier``. Functions\\nmay have \"return\" annotation of the form \"``-> expression``\" after the\\nparameter list. These annotations can be any valid Python expression\\nand are evaluated when the function definition is executed.\\nAnnotations may be evaluated in a different order than they appear in\\nthe source code. The presence of annotations does not change the\\nsemantics of a function. The annotation values are available as\\nvalues of a dictionary keyed by the parameters\\' names in the\\n``__annotations__`` attribute of the function object.\\n\\nIt is also possible to create anonymous functions (functions not bound\\nto a name), for immediate use in expressions. This uses lambda forms,\\ndescribed in section *Lambdas*. Note that the lambda form is merely a\\nshorthand for a simplified function definition; a function defined in\\na \"``def``\" statement can be passed around or assigned to another name\\njust like a function defined by a lambda form. The \"``def``\" form is\\nactually more powerful since it allows the execution of multiple\\nstatements and annotations.\\n\\n**Programmer\\'s note:** Functions are first-class objects. A \"``def``\"\\nform executed inside a function definition defines a local function\\nthat can be returned or passed around. Free variables used in the\\nnested function can access the local variables of the function\\ncontaining the def. See section *Naming and binding* for details.\\n\\nSee also:\\n\\n **PEP 3107** - Function Annotations\\n The original specification for function annotations.\\n\\n\\nClass definitions\\n=================\\n\\nA class definition defines a class object (see section *The standard\\ntype hierarchy*):\\n\\n classdef ::= [decorators] \"class\" classname [inheritance] \":\" suite\\n inheritance ::= \"(\" [parameter_list] \")\"\\n classname ::= identifier\\n\\nA class definition is an executable statement. The inheritance list\\nusually gives a list of base classes (see *Customizing class creation*\\nfor more advanced uses), so each item in the list should evaluate to a\\nclass object which allows subclassing. Classes without an inheritance\\nlist inherit, by default, from the base class ``object``; hence,\\n\\n class Foo:\\n pass\\n\\nis equivalent to\\n\\n class Foo(object):\\n pass\\n\\nThe class\\'s suite is then executed in a new execution frame (see\\n*Naming and binding*), using a newly created local namespace and the\\noriginal global namespace. (Usually, the suite contains mostly\\nfunction definitions.) When the class\\'s suite finishes execution, its\\nexecution frame is discarded but its local namespace is saved. [4] A\\nclass object is then created using the inheritance list for the base\\nclasses and the saved local namespace for the attribute dictionary.\\nThe class name is bound to this class object in the original local\\nnamespace.\\n\\nClass creation can be customized heavily using *metaclasses*.\\n\\nClasses can also be decorated: just like when decorating functions,\\n\\n @f1(arg)\\n @f2\\n class Foo: pass\\n\\nis equivalent to\\n\\n class Foo: pass\\n Foo = f1(arg)(f2(Foo))\\n\\nThe evaluation rules for the decorator expressions are the same as for\\nfunction decorators. The result must be a class object, which is then\\nbound to the class name.\\n\\n**Programmer\\'s note:** Variables defined in the class definition are\\nclass attributes; they are shared by instances. Instance attributes\\ncan be set in a method with ``self.name = value``. Both class and\\ninstance attributes are accessible through the notation\\n\"``self.name``\", and an instance attribute hides a class attribute\\nwith the same name when accessed in this way. Class attributes can be\\nused as defaults for instance attributes, but using mutable values\\nthere can lead to unexpected results. *Descriptors* can be used to\\ncreate instance variables with different implementation details.\\n\\nSee also:\\n\\n **PEP 3115** - Metaclasses in Python 3 **PEP 3129** - Class\\n Decorators\\n\\n-[ Footnotes ]-\\n\\n[1] The exception is propagated to the invocation stack unless there\\n is a ``finally`` clause which happens to raise another exception.\\n That new exception causes the old one to be lost.\\n\\n[2] Currently, control \"flows off the end\" except in the case of an\\n exception or the execution of a ``return``, ``continue``, or\\n ``break`` statement.\\n\\n[3] A string literal appearing as the first statement in the function\\n body is transformed into the function\\'s ``__doc__`` attribute and\\n therefore the function\\'s *docstring*.\\n\\n[4] A string literal appearing as the first statement in the class\\n body is transformed into the namespace\\'s ``__doc__`` item and\\n therefore the class\\'s *docstring*.\\n',\n'context-managers':'\\nWith Statement Context Managers\\n*******************************\\n\\nA *context manager* is an object that defines the runtime context to\\nbe established when executing a ``with`` statement. The context\\nmanager handles the entry into, and the exit from, the desired runtime\\ncontext for the execution of the block of code. Context managers are\\nnormally invoked using the ``with`` statement (described in section\\n*The with statement*), but can also be used by directly invoking their\\nmethods.\\n\\nTypical uses of context managers include saving and restoring various\\nkinds of global state, locking and unlocking resources, closing opened\\nfiles, etc.\\n\\nFor more information on context managers, see *Context Manager Types*.\\n\\nobject.__enter__(self)\\n\\n Enter the runtime context related to this object. The ``with``\\n statement will bind this method\\'s return value to the target(s)\\n specified in the ``as`` clause of the statement, if any.\\n\\nobject.__exit__(self, exc_type, exc_value, traceback)\\n\\n Exit the runtime context related to this object. The parameters\\n describe the exception that caused the context to be exited. If the\\n context was exited without an exception, all three arguments will\\n be ``None``.\\n\\n If an exception is supplied, and the method wishes to suppress the\\n exception (i.e., prevent it from being propagated), it should\\n return a true value. Otherwise, the exception will be processed\\n normally upon exit from this method.\\n\\n Note that ``__exit__()`` methods should not reraise the passed-in\\n exception; this is the caller\\'s responsibility.\\n\\nSee also:\\n\\n **PEP 0343** - The \"with\" statement\\n The specification, background, and examples for the Python\\n ``with`` statement.\\n',\n'continue':'\\nThe ``continue`` statement\\n**************************\\n\\n continue_stmt ::= \"continue\"\\n\\n``continue`` may only occur syntactically nested in a ``for`` or\\n``while`` loop, but not nested in a function or class definition or\\n``finally`` clause within that loop. It continues with the next cycle\\nof the nearest enclosing loop.\\n\\nWhen ``continue`` passes control out of a ``try`` statement with a\\n``finally`` clause, that ``finally`` clause is executed before really\\nstarting the next loop cycle.\\n',\n'conversions':'\\nArithmetic conversions\\n**********************\\n\\nWhen a description of an arithmetic operator below uses the phrase\\n\"the numeric arguments are converted to a common type,\" this means\\nthat the operator implementation for built-in types works that way:\\n\\n* If either argument is a complex number, the other is converted to\\n complex;\\n\\n* otherwise, if either argument is a floating point number, the other\\n is converted to floating point;\\n\\n* otherwise, both must be integers and no conversion is necessary.\\n\\nSome additional rules apply for certain operators (e.g., a string left\\nargument to the \\'%\\' operator). Extensions must define their own\\nconversion behavior.\\n',\n'customization':'\\nBasic customization\\n*******************\\n\\nobject.__new__(cls[, ...])\\n\\n Called to create a new instance of class *cls*. ``__new__()`` is a\\n static method (special-cased so you need not declare it as such)\\n that takes the class of which an instance was requested as its\\n first argument. The remaining arguments are those passed to the\\n object constructor expression (the call to the class). The return\\n value of ``__new__()`` should be the new object instance (usually\\n an instance of *cls*).\\n\\n Typical implementations create a new instance of the class by\\n invoking the superclass\\'s ``__new__()`` method using\\n ``super(currentclass, cls).__new__(cls[, ...])`` with appropriate\\n arguments and then modifying the newly-created instance as\\n necessary before returning it.\\n\\n If ``__new__()`` returns an instance of *cls*, then the new\\n instance\\'s ``__init__()`` method will be invoked like\\n ``__init__(self[, ...])``, where *self* is the new instance and the\\n remaining arguments are the same as were passed to ``__new__()``.\\n\\n If ``__new__()`` does not return an instance of *cls*, then the new\\n instance\\'s ``__init__()`` method will not be invoked.\\n\\n ``__new__()`` is intended mainly to allow subclasses of immutable\\n types (like int, str, or tuple) to customize instance creation. It\\n is also commonly overridden in custom metaclasses in order to\\n customize class creation.\\n\\nobject.__init__(self[, ...])\\n\\n Called when the instance is created. The arguments are those\\n passed to the class constructor expression. If a base class has an\\n ``__init__()`` method, the derived class\\'s ``__init__()`` method,\\n if any, must explicitly call it to ensure proper initialization of\\n the base class part of the instance; for example:\\n ``BaseClass.__init__(self, [args...])``. As a special constraint\\n on constructors, no value may be returned; doing so will cause a\\n ``TypeError`` to be raised at runtime.\\n\\nobject.__del__(self)\\n\\n Called when the instance is about to be destroyed. This is also\\n called a destructor. If a base class has a ``__del__()`` method,\\n the derived class\\'s ``__del__()`` method, if any, must explicitly\\n call it to ensure proper deletion of the base class part of the\\n instance. Note that it is possible (though not recommended!) for\\n the ``__del__()`` method to postpone destruction of the instance by\\n creating a new reference to it. It may then be called at a later\\n time when this new reference is deleted. It is not guaranteed that\\n ``__del__()`` methods are called for objects that still exist when\\n the interpreter exits.\\n\\n Note: ``del x`` doesn\\'t directly call ``x.__del__()`` --- the former\\n decrements the reference count for ``x`` by one, and the latter\\n is only called when ``x``\\'s reference count reaches zero. Some\\n common situations that may prevent the reference count of an\\n object from going to zero include: circular references between\\n objects (e.g., a doubly-linked list or a tree data structure with\\n parent and child pointers); a reference to the object on the\\n stack frame of a function that caught an exception (the traceback\\n stored in ``sys.exc_info()[2]`` keeps the stack frame alive); or\\n a reference to the object on the stack frame that raised an\\n unhandled exception in interactive mode (the traceback stored in\\n ``sys.last_traceback`` keeps the stack frame alive). The first\\n situation can only be remedied by explicitly breaking the cycles;\\n the latter two situations can be resolved by storing ``None`` in\\n ``sys.last_traceback``. Circular references which are garbage are\\n detected when the option cycle detector is enabled (it\\'s on by\\n default), but can only be cleaned up if there are no Python-\\n level ``__del__()`` methods involved. Refer to the documentation\\n for the ``gc`` module for more information about how\\n ``__del__()`` methods are handled by the cycle detector,\\n particularly the description of the ``garbage`` value.\\n\\n Warning: Due to the precarious circumstances under which ``__del__()``\\n methods are invoked, exceptions that occur during their execution\\n are ignored, and a warning is printed to ``sys.stderr`` instead.\\n Also, when ``__del__()`` is invoked in response to a module being\\n deleted (e.g., when execution of the program is done), other\\n globals referenced by the ``__del__()`` method may already have\\n been deleted or in the process of being torn down (e.g. the\\n import machinery shutting down). For this reason, ``__del__()``\\n methods should do the absolute minimum needed to maintain\\n external invariants. Starting with version 1.5, Python\\n guarantees that globals whose name begins with a single\\n underscore are deleted from their module before other globals are\\n deleted; if no other references to such globals exist, this may\\n help in assuring that imported modules are still available at the\\n time when the ``__del__()`` method is called.\\n\\nobject.__repr__(self)\\n\\n Called by the ``repr()`` built-in function to compute the\\n \"official\" string representation of an object. If at all possible,\\n this should look like a valid Python expression that could be used\\n to recreate an object with the same value (given an appropriate\\n environment). If this is not possible, a string of the form\\n ``<...some useful description...>`` should be returned. The return\\n value must be a string object. If a class defines ``__repr__()``\\n but not ``__str__()``, then ``__repr__()`` is also used when an\\n \"informal\" string representation of instances of that class is\\n required.\\n\\n This is typically used for debugging, so it is important that the\\n representation is information-rich and unambiguous.\\n\\nobject.__str__(self)\\n\\n Called by ``str(object)`` and the built-in functions ``format()``\\n and ``print()`` to compute the \"informal\" or nicely printable\\n string representation of an object. The return value must be a\\n *string* object.\\n\\n This method differs from ``object.__repr__()`` in that there is no\\n expectation that ``__str__()`` return a valid Python expression: a\\n more convenient or concise representation can be used.\\n\\n The default implementation defined by the built-in type ``object``\\n calls ``object.__repr__()``.\\n\\nobject.__bytes__(self)\\n\\n Called by ``bytes()`` to compute a byte-string representation of an\\n object. This should return a ``bytes`` object.\\n\\nobject.__format__(self, format_spec)\\n\\n Called by the ``format()`` built-in function (and by extension, the\\n ``str.format()`` method of class ``str``) to produce a \"formatted\"\\n string representation of an object. The ``format_spec`` argument is\\n a string that contains a description of the formatting options\\n desired. The interpretation of the ``format_spec`` argument is up\\n to the type implementing ``__format__()``, however most classes\\n will either delegate formatting to one of the built-in types, or\\n use a similar formatting option syntax.\\n\\n See *Format Specification Mini-Language* for a description of the\\n standard formatting syntax.\\n\\n The return value must be a string object.\\n\\nobject.__lt__(self, other)\\nobject.__le__(self, other)\\nobject.__eq__(self, other)\\nobject.__ne__(self, other)\\nobject.__gt__(self, other)\\nobject.__ge__(self, other)\\n\\n These are the so-called \"rich comparison\" methods. The\\n correspondence between operator symbols and method names is as\\n follows: ``x<y`` calls ``x.__lt__(y)``, ``x<=y`` calls\\n ``x.__le__(y)``, ``x==y`` calls ``x.__eq__(y)``, ``x!=y`` calls\\n ``x.__ne__(y)``, ``x>y`` calls ``x.__gt__(y)``, and ``x>=y`` calls\\n ``x.__ge__(y)``.\\n\\n A rich comparison method may return the singleton\\n ``NotImplemented`` if it does not implement the operation for a\\n given pair of arguments. By convention, ``False`` and ``True`` are\\n returned for a successful comparison. However, these methods can\\n return any value, so if the comparison operator is used in a\\n Boolean context (e.g., in the condition of an ``if`` statement),\\n Python will call ``bool()`` on the value to determine if the result\\n is true or false.\\n\\n There are no implied relationships among the comparison operators.\\n The truth of ``x==y`` does not imply that ``x!=y`` is false.\\n Accordingly, when defining ``__eq__()``, one should also define\\n ``__ne__()`` so that the operators will behave as expected. See\\n the paragraph on ``__hash__()`` for some important notes on\\n creating *hashable* objects which support custom comparison\\n operations and are usable as dictionary keys.\\n\\n There are no swapped-argument versions of these methods (to be used\\n when the left argument does not support the operation but the right\\n argument does); rather, ``__lt__()`` and ``__gt__()`` are each\\n other\\'s reflection, ``__le__()`` and ``__ge__()`` are each other\\'s\\n reflection, and ``__eq__()`` and ``__ne__()`` are their own\\n reflection.\\n\\n Arguments to rich comparison methods are never coerced.\\n\\n To automatically generate ordering operations from a single root\\n operation, see ``functools.total_ordering()``.\\n\\nobject.__hash__(self)\\n\\n Called by built-in function ``hash()`` and for operations on\\n members of hashed collections including ``set``, ``frozenset``, and\\n ``dict``. ``__hash__()`` should return an integer. The only\\n required property is that objects which compare equal have the same\\n hash value; it is advised to somehow mix together (e.g. using\\n exclusive or) the hash values for the components of the object that\\n also play a part in comparison of objects.\\n\\n If a class does not define an ``__eq__()`` method it should not\\n define a ``__hash__()`` operation either; if it defines\\n ``__eq__()`` but not ``__hash__()``, its instances will not be\\n usable as items in hashable collections. If a class defines\\n mutable objects and implements an ``__eq__()`` method, it should\\n not implement ``__hash__()``, since the implementation of hashable\\n collections requires that a key\\'s hash value is immutable (if the\\n object\\'s hash value changes, it will be in the wrong hash bucket).\\n\\n User-defined classes have ``__eq__()`` and ``__hash__()`` methods\\n by default; with them, all objects compare unequal (except with\\n themselves) and ``x.__hash__()`` returns an appropriate value such\\n that ``x == y`` implies both that ``x is y`` and ``hash(x) ==\\n hash(y)``.\\n\\n A class that overrides ``__eq__()`` and does not define\\n ``__hash__()`` will have its ``__hash__()`` implicitly set to\\n ``None``. When the ``__hash__()`` method of a class is ``None``,\\n instances of the class will raise an appropriate ``TypeError`` when\\n a program attempts to retrieve their hash value, and will also be\\n correctly identified as unhashable when checking ``isinstance(obj,\\n collections.Hashable``).\\n\\n If a class that overrides ``__eq__()`` needs to retain the\\n implementation of ``__hash__()`` from a parent class, the\\n interpreter must be told this explicitly by setting ``__hash__ =\\n <ParentClass>.__hash__``.\\n\\n If a class that does not override ``__eq__()`` wishes to suppress\\n hash support, it should include ``__hash__ = None`` in the class\\n definition. A class which defines its own ``__hash__()`` that\\n explicitly raises a ``TypeError`` would be incorrectly identified\\n as hashable by an ``isinstance(obj, collections.Hashable)`` call.\\n\\n Note: By default, the ``__hash__()`` values of str, bytes and datetime\\n objects are \"salted\" with an unpredictable random value.\\n Although they remain constant within an individual Python\\n process, they are not predictable between repeated invocations of\\n Python.This is intended to provide protection against a denial-\\n of-service caused by carefully-chosen inputs that exploit the\\n worst case performance of a dict insertion, O(n^2) complexity.\\n See http://www.ocert.org/advisories/ocert-2011-003.html for\\n details.Changing hash values affects the iteration order of\\n dicts, sets and other mappings. Python has never made guarantees\\n about this ordering (and it typically varies between 32-bit and\\n 64-bit builds).See also ``PYTHONHASHSEED``.\\n\\n Changed in version 3.3: Hash randomization is enabled by default.\\n\\nobject.__bool__(self)\\n\\n Called to implement truth value testing and the built-in operation\\n ``bool()``; should return ``False`` or ``True``. When this method\\n is not defined, ``__len__()`` is called, if it is defined, and the\\n object is considered true if its result is nonzero. If a class\\n defines neither ``__len__()`` nor ``__bool__()``, all its instances\\n are considered true.\\n',\n'debugger':'\\n``pdb`` --- The Python Debugger\\n*******************************\\n\\nThe module ``pdb`` defines an interactive source code debugger for\\nPython programs. It supports setting (conditional) breakpoints and\\nsingle stepping at the source line level, inspection of stack frames,\\nsource code listing, and evaluation of arbitrary Python code in the\\ncontext of any stack frame. It also supports post-mortem debugging\\nand can be called under program control.\\n\\nThe debugger is extensible -- it is actually defined as the class\\n``Pdb``. This is currently undocumented but easily understood by\\nreading the source. The extension interface uses the modules ``bdb``\\nand ``cmd``.\\n\\nThe debugger\\'s prompt is ``(Pdb)``. Typical usage to run a program\\nunder control of the debugger is:\\n\\n >>> import pdb\\n >>> import mymodule\\n >>> pdb.run(\\'mymodule.test()\\')\\n > <string>(0)?()\\n (Pdb) continue\\n > <string>(1)?()\\n (Pdb) continue\\n NameError: \\'spam\\'\\n > <string>(1)?()\\n (Pdb)\\n\\nChanged in version 3.3: Tab-completion via the ``readline`` module is\\navailable for commands and command arguments, e.g. the current global\\nand local names are offered as arguments of the ``print`` command.\\n\\n``pdb.py`` can also be invoked as a script to debug other scripts.\\nFor example:\\n\\n python3 -m pdb myscript.py\\n\\nWhen invoked as a script, pdb will automatically enter post-mortem\\ndebugging if the program being debugged exits abnormally. After post-\\nmortem debugging (or after normal exit of the program), pdb will\\nrestart the program. Automatic restarting preserves pdb\\'s state (such\\nas breakpoints) and in most cases is more useful than quitting the\\ndebugger upon program\\'s exit.\\n\\nNew in version 3.2: ``pdb.py`` now accepts a ``-c`` option that\\nexecutes commands as if given in a ``.pdbrc`` file, see *Debugger\\nCommands*.\\n\\nThe typical usage to break into the debugger from a running program is\\nto insert\\n\\n import pdb; pdb.set_trace()\\n\\nat the location you want to break into the debugger. You can then\\nstep through the code following this statement, and continue running\\nwithout the debugger using the ``continue`` command.\\n\\nThe typical usage to inspect a crashed program is:\\n\\n >>> import pdb\\n >>> import mymodule\\n >>> mymodule.test()\\n Traceback (most recent call last):\\n File \"<stdin>\", line 1, in ?\\n File \"./mymodule.py\", line 4, in test\\n test2()\\n File \"./mymodule.py\", line 3, in test2\\n print(spam)\\n NameError: spam\\n >>> pdb.pm()\\n > ./mymodule.py(3)test2()\\n -> print(spam)\\n (Pdb)\\n\\nThe module defines the following functions; each enters the debugger\\nin a slightly different way:\\n\\npdb.run(statement, globals=None, locals=None)\\n\\n Execute the *statement* (given as a string or a code object) under\\n debugger control. The debugger prompt appears before any code is\\n executed; you can set breakpoints and type ``continue``, or you can\\n step through the statement using ``step`` or ``next`` (all these\\n commands are explained below). The optional *globals* and *locals*\\n arguments specify the environment in which the code is executed; by\\n default the dictionary of the module ``__main__`` is used. (See\\n the explanation of the built-in ``exec()`` or ``eval()``\\n functions.)\\n\\npdb.runeval(expression, globals=None, locals=None)\\n\\n Evaluate the *expression* (given as a string or a code object)\\n under debugger control. When ``runeval()`` returns, it returns the\\n value of the expression. Otherwise this function is similar to\\n ``run()``.\\n\\npdb.runcall(function, *args, **kwds)\\n\\n Call the *function* (a function or method object, not a string)\\n with the given arguments. When ``runcall()`` returns, it returns\\n whatever the function call returned. The debugger prompt appears\\n as soon as the function is entered.\\n\\npdb.set_trace()\\n\\n Enter the debugger at the calling stack frame. This is useful to\\n hard-code a breakpoint at a given point in a program, even if the\\n code is not otherwise being debugged (e.g. when an assertion\\n fails).\\n\\npdb.post_mortem(traceback=None)\\n\\n Enter post-mortem debugging of the given *traceback* object. If no\\n *traceback* is given, it uses the one of the exception that is\\n currently being handled (an exception must be being handled if the\\n default is to be used).\\n\\npdb.pm()\\n\\n Enter post-mortem debugging of the traceback found in\\n ``sys.last_traceback``.\\n\\nThe ``run*`` functions and ``set_trace()`` are aliases for\\ninstantiating the ``Pdb`` class and calling the method of the same\\nname. If you want to access further features, you have to do this\\nyourself:\\n\\nclass class pdb.Pdb(completekey=\\'tab\\', stdin=None, stdout=None, skip=None, nosigint=False)\\n\\n ``Pdb`` is the debugger class.\\n\\n The *completekey*, *stdin* and *stdout* arguments are passed to the\\n underlying ``cmd.Cmd`` class; see the description there.\\n\\n The *skip* argument, if given, must be an iterable of glob-style\\n module name patterns. The debugger will not step into frames that\\n originate in a module that matches one of these patterns. [1]\\n\\n By default, Pdb sets a handler for the SIGINT signal (which is sent\\n when the user presses Ctrl-C on the console) when you give a\\n ``continue`` command. This allows you to break into the debugger\\n again by pressing Ctrl-C. If you want Pdb not to touch the SIGINT\\n handler, set *nosigint* tot true.\\n\\n Example call to enable tracing with *skip*:\\n\\n import pdb; pdb.Pdb(skip=[\\'django.*\\']).set_trace()\\n\\n New in version 3.1: The *skip* argument.\\n\\n New in version 3.2: The *nosigint* argument. Previously, a SIGINT\\n handler was never set by Pdb.\\n\\n run(statement, globals=None, locals=None)\\n runeval(expression, globals=None, locals=None)\\n runcall(function, *args, **kwds)\\n set_trace()\\n\\n See the documentation for the functions explained above.\\n\\n\\nDebugger Commands\\n=================\\n\\nThe commands recognized by the debugger are listed below. Most\\ncommands can be abbreviated to one or two letters as indicated; e.g.\\n``h(elp)`` means that either ``h`` or ``help`` can be used to enter\\nthe help command (but not ``he`` or ``hel``, nor ``H`` or ``Help`` or\\n``HELP``). Arguments to commands must be separated by whitespace\\n(spaces or tabs). Optional arguments are enclosed in square brackets\\n(``[]``) in the command syntax; the square brackets must not be typed.\\nAlternatives in the command syntax are separated by a vertical bar\\n(``|``).\\n\\nEntering a blank line repeats the last command entered. Exception: if\\nthe last command was a ``list`` command, the next 11 lines are listed.\\n\\nCommands that the debugger doesn\\'t recognize are assumed to be Python\\nstatements and are executed in the context of the program being\\ndebugged. Python statements can also be prefixed with an exclamation\\npoint (``!``). This is a powerful way to inspect the program being\\ndebugged; it is even possible to change a variable or call a function.\\nWhen an exception occurs in such a statement, the exception name is\\nprinted but the debugger\\'s state is not changed.\\n\\nThe debugger supports *aliases*. Aliases can have parameters which\\nallows one a certain level of adaptability to the context under\\nexamination.\\n\\nMultiple commands may be entered on a single line, separated by\\n``;;``. (A single ``;`` is not used as it is the separator for\\nmultiple commands in a line that is passed to the Python parser.) No\\nintelligence is applied to separating the commands; the input is split\\nat the first ``;;`` pair, even if it is in the middle of a quoted\\nstring.\\n\\nIf a file ``.pdbrc`` exists in the user\\'s home directory or in the\\ncurrent directory, it is read in and executed as if it had been typed\\nat the debugger prompt. This is particularly useful for aliases. If\\nboth files exist, the one in the home directory is read first and\\naliases defined there can be overridden by the local file.\\n\\nChanged in version 3.2: ``.pdbrc`` can now contain commands that\\ncontinue debugging, such as ``continue`` or ``next``. Previously,\\nthese commands had no effect.\\n\\nh(elp) [command]\\n\\n Without argument, print the list of available commands. With a\\n *command* as argument, print help about that command. ``help pdb``\\n displays the full documentation (the docstring of the ``pdb``\\n module). Since the *command* argument must be an identifier,\\n ``help exec`` must be entered to get help on the ``!`` command.\\n\\nw(here)\\n\\n Print a stack trace, with the most recent frame at the bottom. An\\n arrow indicates the current frame, which determines the context of\\n most commands.\\n\\nd(own) [count]\\n\\n Move the current frame *count* (default one) levels down in the\\n stack trace (to a newer frame).\\n\\nu(p) [count]\\n\\n Move the current frame *count* (default one) levels up in the stack\\n trace (to an older frame).\\n\\nb(reak) [([filename:]lineno | function) [, condition]]\\n\\n With a *lineno* argument, set a break there in the current file.\\n With a *function* argument, set a break at the first executable\\n statement within that function. The line number may be prefixed\\n with a filename and a colon, to specify a breakpoint in another\\n file (probably one that hasn\\'t been loaded yet). The file is\\n searched on ``sys.path``. Note that each breakpoint is assigned a\\n number to which all the other breakpoint commands refer.\\n\\n If a second argument is present, it is an expression which must\\n evaluate to true before the breakpoint is honored.\\n\\n Without argument, list all breaks, including for each breakpoint,\\n the number of times that breakpoint has been hit, the current\\n ignore count, and the associated condition if any.\\n\\ntbreak [([filename:]lineno | function) [, condition]]\\n\\n Temporary breakpoint, which is removed automatically when it is\\n first hit. The arguments are the same as for ``break``.\\n\\ncl(ear) [filename:lineno | bpnumber [bpnumber ...]]\\n\\n With a *filename:lineno* argument, clear all the breakpoints at\\n this line. With a space separated list of breakpoint numbers, clear\\n those breakpoints. Without argument, clear all breaks (but first\\n ask confirmation).\\n\\ndisable [bpnumber [bpnumber ...]]\\n\\n Disable the breakpoints given as a space separated list of\\n breakpoint numbers. Disabling a breakpoint means it cannot cause\\n the program to stop execution, but unlike clearing a breakpoint, it\\n remains in the list of breakpoints and can be (re-)enabled.\\n\\nenable [bpnumber [bpnumber ...]]\\n\\n Enable the breakpoints specified.\\n\\nignore bpnumber [count]\\n\\n Set the ignore count for the given breakpoint number. If count is\\n omitted, the ignore count is set to 0. A breakpoint becomes active\\n when the ignore count is zero. When non-zero, the count is\\n decremented each time the breakpoint is reached and the breakpoint\\n is not disabled and any associated condition evaluates to true.\\n\\ncondition bpnumber [condition]\\n\\n Set a new *condition* for the breakpoint, an expression which must\\n evaluate to true before the breakpoint is honored. If *condition*\\n is absent, any existing condition is removed; i.e., the breakpoint\\n is made unconditional.\\n\\ncommands [bpnumber]\\n\\n Specify a list of commands for breakpoint number *bpnumber*. The\\n commands themselves appear on the following lines. Type a line\\n containing just ``end`` to terminate the commands. An example:\\n\\n (Pdb) commands 1\\n (com) print some_variable\\n (com) end\\n (Pdb)\\n\\n To remove all commands from a breakpoint, type commands and follow\\n it immediately with ``end``; that is, give no commands.\\n\\n With no *bpnumber* argument, commands refers to the last breakpoint\\n set.\\n\\n You can use breakpoint commands to start your program up again.\\n Simply use the continue command, or step, or any other command that\\n resumes execution.\\n\\n Specifying any command resuming execution (currently continue,\\n step, next, return, jump, quit and their abbreviations) terminates\\n the command list (as if that command was immediately followed by\\n end). This is because any time you resume execution (even with a\\n simple next or step), you may encounter another breakpoint--which\\n could have its own command list, leading to ambiguities about which\\n list to execute.\\n\\n If you use the \\'silent\\' command in the command list, the usual\\n message about stopping at a breakpoint is not printed. This may be\\n desirable for breakpoints that are to print a specific message and\\n then continue. If none of the other commands print anything, you\\n see no sign that the breakpoint was reached.\\n\\ns(tep)\\n\\n Execute the current line, stop at the first possible occasion\\n (either in a function that is called or on the next line in the\\n current function).\\n\\nn(ext)\\n\\n Continue execution until the next line in the current function is\\n reached or it returns. (The difference between ``next`` and\\n ``step`` is that ``step`` stops inside a called function, while\\n ``next`` executes called functions at (nearly) full speed, only\\n stopping at the next line in the current function.)\\n\\nunt(il) [lineno]\\n\\n Without argument, continue execution until the line with a number\\n greater than the current one is reached.\\n\\n With a line number, continue execution until a line with a number\\n greater or equal to that is reached. In both cases, also stop when\\n the current frame returns.\\n\\n Changed in version 3.2: Allow giving an explicit line number.\\n\\nr(eturn)\\n\\n Continue execution until the current function returns.\\n\\nc(ont(inue))\\n\\n Continue execution, only stop when a breakpoint is encountered.\\n\\nj(ump) lineno\\n\\n Set the next line that will be executed. Only available in the\\n bottom-most frame. This lets you jump back and execute code again,\\n or jump forward to skip code that you don\\'t want to run.\\n\\n It should be noted that not all jumps are allowed -- for instance\\n it is not possible to jump into the middle of a ``for`` loop or out\\n of a ``finally`` clause.\\n\\nl(ist) [first[, last]]\\n\\n List source code for the current file. Without arguments, list 11\\n lines around the current line or continue the previous listing.\\n With ``.`` as argument, list 11 lines around the current line.\\n With one argument, list 11 lines around at that line. With two\\n arguments, list the given range; if the second argument is less\\n than the first, it is interpreted as a count.\\n\\n The current line in the current frame is indicated by ``->``. If\\n an exception is being debugged, the line where the exception was\\n originally raised or propagated is indicated by ``>>``, if it\\n differs from the current line.\\n\\n New in version 3.2: The ``>>`` marker.\\n\\nll | longlist\\n\\n List all source code for the current function or frame.\\n Interesting lines are marked as for ``list``.\\n\\n New in version 3.2.\\n\\na(rgs)\\n\\n Print the argument list of the current function.\\n\\np(rint) expression\\n\\n Evaluate the *expression* in the current context and print its\\n value.\\n\\npp expression\\n\\n Like the ``print`` command, except the value of the expression is\\n pretty-printed using the ``pprint`` module.\\n\\nwhatis expression\\n\\n Print the type of the *expression*.\\n\\nsource expression\\n\\n Try to get source code for the given object and display it.\\n\\n New in version 3.2.\\n\\ndisplay [expression]\\n\\n Display the value of the expression if it changed, each time\\n execution stops in the current frame.\\n\\n Without expression, list all display expressions for the current\\n frame.\\n\\n New in version 3.2.\\n\\nundisplay [expression]\\n\\n Do not display the expression any more in the current frame.\\n Without expression, clear all display expressions for the current\\n frame.\\n\\n New in version 3.2.\\n\\ninteract\\n\\n Start an interative interpreter (using the ``code`` module) whose\\n global namespace contains all the (global and local) names found in\\n the current scope.\\n\\n New in version 3.2.\\n\\nalias [name [command]]\\n\\n Create an alias called *name* that executes *command*. The command\\n must *not* be enclosed in quotes. Replaceable parameters can be\\n indicated by ``%1``, ``%2``, and so on, while ``%*`` is replaced by\\n all the parameters. If no command is given, the current alias for\\n *name* is shown. If no arguments are given, all aliases are listed.\\n\\n Aliases may be nested and can contain anything that can be legally\\n typed at the pdb prompt. Note that internal pdb commands *can* be\\n overridden by aliases. Such a command is then hidden until the\\n alias is removed. Aliasing is recursively applied to the first\\n word of the command line; all other words in the line are left\\n alone.\\n\\n As an example, here are two useful aliases (especially when placed\\n in the ``.pdbrc`` file):\\n\\n # Print instance variables (usage \"pi classInst\")\\n alias pi for k in %1.__dict__.keys(): print(\"%1.\",k,\"=\",%1.__dict__[k])\\n # Print instance variables in self\\n alias ps pi self\\n\\nunalias name\\n\\n Delete the specified alias.\\n\\n! statement\\n\\n Execute the (one-line) *statement* in the context of the current\\n stack frame. The exclamation point can be omitted unless the first\\n word of the statement resembles a debugger command. To set a\\n global variable, you can prefix the assignment command with a\\n ``global`` statement on the same line, e.g.:\\n\\n (Pdb) global list_options; list_options = [\\'-l\\']\\n (Pdb)\\n\\nrun [args ...]\\nrestart [args ...]\\n\\n Restart the debugged Python program. If an argument is supplied,\\n it is split with ``shlex`` and the result is used as the new\\n ``sys.argv``. History, breakpoints, actions and debugger options\\n are preserved. ``restart`` is an alias for ``run``.\\n\\nq(uit)\\n\\n Quit from the debugger. The program being executed is aborted.\\n\\n-[ Footnotes ]-\\n\\n[1] Whether a frame is considered to originate in a certain module is\\n determined by the ``__name__`` in the frame globals.\\n',\n'del':'\\nThe ``del`` statement\\n*********************\\n\\n del_stmt ::= \"del\" target_list\\n\\nDeletion is recursively defined very similar to the way assignment is\\ndefined. Rather than spelling it out in full details, here are some\\nhints.\\n\\nDeletion of a target list recursively deletes each target, from left\\nto right.\\n\\nDeletion of a name removes the binding of that name from the local or\\nglobal namespace, depending on whether the name occurs in a ``global``\\nstatement in the same code block. If the name is unbound, a\\n``NameError`` exception will be raised.\\n\\nDeletion of attribute references, subscriptions and slicings is passed\\nto the primary object involved; deletion of a slicing is in general\\nequivalent to assignment of an empty slice of the right type (but even\\nthis is determined by the sliced object).\\n\\nChanged in version 3.2: Previously it was illegal to delete a name\\nfrom the local namespace if it occurs as a free variable in a nested\\nblock.\\n',\n'dict':'\\nDictionary displays\\n*******************\\n\\nA dictionary display is a possibly empty series of key/datum pairs\\nenclosed in curly braces:\\n\\n dict_display ::= \"{\" [key_datum_list | dict_comprehension] \"}\"\\n key_datum_list ::= key_datum (\",\" key_datum)* [\",\"]\\n key_datum ::= expression \":\" expression\\n dict_comprehension ::= expression \":\" expression comp_for\\n\\nA dictionary display yields a new dictionary object.\\n\\nIf a comma-separated sequence of key/datum pairs is given, they are\\nevaluated from left to right to define the entries of the dictionary:\\neach key object is used as a key into the dictionary to store the\\ncorresponding datum. This means that you can specify the same key\\nmultiple times in the key/datum list, and the final dictionary\\'s value\\nfor that key will be the last one given.\\n\\nA dict comprehension, in contrast to list and set comprehensions,\\nneeds two expressions separated with a colon followed by the usual\\n\"for\" and \"if\" clauses. When the comprehension is run, the resulting\\nkey and value elements are inserted in the new dictionary in the order\\nthey are produced.\\n\\nRestrictions on the types of the key values are listed earlier in\\nsection *The standard type hierarchy*. (To summarize, the key type\\nshould be *hashable*, which excludes all mutable objects.) Clashes\\nbetween duplicate keys are not detected; the last datum (textually\\nrightmost in the display) stored for a given key value prevails.\\n',\n'dynamic-features':'\\nInteraction with dynamic features\\n*********************************\\n\\nThere are several cases where Python statements are illegal when used\\nin conjunction with nested scopes that contain free variables.\\n\\nIf a variable is referenced in an enclosing scope, it is illegal to\\ndelete the name. An error will be reported at compile time.\\n\\nIf the wild card form of import --- ``import *`` --- is used in a\\nfunction and the function contains or is a nested block with free\\nvariables, the compiler will raise a ``SyntaxError``.\\n\\nThe ``eval()`` and ``exec()`` functions do not have access to the full\\nenvironment for resolving names. Names may be resolved in the local\\nand global namespaces of the caller. Free variables are not resolved\\nin the nearest enclosing namespace, but in the global namespace. [1]\\nThe ``exec()`` and ``eval()`` functions have optional arguments to\\noverride the global and local namespace. If only one namespace is\\nspecified, it is used for both.\\n',\n'else':'\\nThe ``if`` statement\\n********************\\n\\nThe ``if`` statement is used for conditional execution:\\n\\n if_stmt ::= \"if\" expression \":\" suite\\n ( \"elif\" expression \":\" suite )*\\n [\"else\" \":\" suite]\\n\\nIt selects exactly one of the suites by evaluating the expressions one\\nby one until one is found to be true (see section *Boolean operations*\\nfor the definition of true and false); then that suite is executed\\n(and no other part of the ``if`` statement is executed or evaluated).\\nIf all expressions are false, the suite of the ``else`` clause, if\\npresent, is executed.\\n',\n'exceptions':'\\nExceptions\\n**********\\n\\nExceptions are a means of breaking out of the normal flow of control\\nof a code block in order to handle errors or other exceptional\\nconditions. An exception is *raised* at the point where the error is\\ndetected; it may be *handled* by the surrounding code block or by any\\ncode block that directly or indirectly invoked the code block where\\nthe error occurred.\\n\\nThe Python interpreter raises an exception when it detects a run-time\\nerror (such as division by zero). A Python program can also\\nexplicitly raise an exception with the ``raise`` statement. Exception\\nhandlers are specified with the ``try`` ... ``except`` statement. The\\n``finally`` clause of such a statement can be used to specify cleanup\\ncode which does not handle the exception, but is executed whether an\\nexception occurred or not in the preceding code.\\n\\nPython uses the \"termination\" model of error handling: an exception\\nhandler can find out what happened and continue execution at an outer\\nlevel, but it cannot repair the cause of the error and retry the\\nfailing operation (except by re-entering the offending piece of code\\nfrom the top).\\n\\nWhen an exception is not handled at all, the interpreter terminates\\nexecution of the program, or returns to its interactive main loop. In\\neither case, it prints a stack backtrace, except when the exception is\\n``SystemExit``.\\n\\nExceptions are identified by class instances. The ``except`` clause\\nis selected depending on the class of the instance: it must reference\\nthe class of the instance or a base class thereof. The instance can\\nbe received by the handler and can carry additional information about\\nthe exceptional condition.\\n\\nNote: Exception messages are not part of the Python API. Their contents\\n may change from one version of Python to the next without warning\\n and should not be relied on by code which will run under multiple\\n versions of the interpreter.\\n\\nSee also the description of the ``try`` statement in section *The try\\nstatement* and ``raise`` statement in section *The raise statement*.\\n\\n-[ Footnotes ]-\\n\\n[1] This limitation occurs because the code that is executed by these\\n operations is not available at the time the module is compiled.\\n',\n'execmodel':'\\nExecution model\\n***************\\n\\n\\nNaming and binding\\n==================\\n\\n*Names* refer to objects. Names are introduced by name binding\\noperations. Each occurrence of a name in the program text refers to\\nthe *binding* of that name established in the innermost function block\\ncontaining the use.\\n\\nA *block* is a piece of Python program text that is executed as a\\nunit. The following are blocks: a module, a function body, and a class\\ndefinition. Each command typed interactively is a block. A script\\nfile (a file given as standard input to the interpreter or specified\\non the interpreter command line the first argument) is a code block.\\nA script command (a command specified on the interpreter command line\\nwith the \\'**-c**\\' option) is a code block. The string argument passed\\nto the built-in functions ``eval()`` and ``exec()`` is a code block.\\n\\nA code block is executed in an *execution frame*. A frame contains\\nsome administrative information (used for debugging) and determines\\nwhere and how execution continues after the code block\\'s execution has\\ncompleted.\\n\\nA *scope* defines the visibility of a name within a block. If a local\\nvariable is defined in a block, its scope includes that block. If the\\ndefinition occurs in a function block, the scope extends to any blocks\\ncontained within the defining one, unless a contained block introduces\\na different binding for the name. The scope of names defined in a\\nclass block is limited to the class block; it does not extend to the\\ncode blocks of methods -- this includes comprehensions and generator\\nexpressions since they are implemented using a function scope. This\\nmeans that the following will fail:\\n\\n class A:\\n a = 42\\n b = list(a + i for i in range(10))\\n\\nWhen a name is used in a code block, it is resolved using the nearest\\nenclosing scope. The set of all such scopes visible to a code block\\nis called the block\\'s *environment*.\\n\\nIf a name is bound in a block, it is a local variable of that block,\\nunless declared as ``nonlocal``. If a name is bound at the module\\nlevel, it is a global variable. (The variables of the module code\\nblock are local and global.) If a variable is used in a code block\\nbut not defined there, it is a *free variable*.\\n\\nWhen a name is not found at all, a ``NameError`` exception is raised.\\nIf the name refers to a local variable that has not been bound, a\\n``UnboundLocalError`` exception is raised. ``UnboundLocalError`` is a\\nsubclass of ``NameError``.\\n\\nThe following constructs bind names: formal parameters to functions,\\n``import`` statements, class and function definitions (these bind the\\nclass or function name in the defining block), and targets that are\\nidentifiers if occurring in an assignment, ``for`` loop header, or\\nafter ``as`` in a ``with`` statement or ``except`` clause. The\\n``import`` statement of the form ``from ... import *`` binds all names\\ndefined in the imported module, except those beginning with an\\nunderscore. This form may only be used at the module level.\\n\\nA target occurring in a ``del`` statement is also considered bound for\\nthis purpose (though the actual semantics are to unbind the name).\\n\\nEach assignment or import statement occurs within a block defined by a\\nclass or function definition or at the module level (the top-level\\ncode block).\\n\\nIf a name binding operation occurs anywhere within a code block, all\\nuses of the name within the block are treated as references to the\\ncurrent block. This can lead to errors when a name is used within a\\nblock before it is bound. This rule is subtle. Python lacks\\ndeclarations and allows name binding operations to occur anywhere\\nwithin a code block. The local variables of a code block can be\\ndetermined by scanning the entire text of the block for name binding\\noperations.\\n\\nIf the ``global`` statement occurs within a block, all uses of the\\nname specified in the statement refer to the binding of that name in\\nthe top-level namespace. Names are resolved in the top-level\\nnamespace by searching the global namespace, i.e. the namespace of the\\nmodule containing the code block, and the builtins namespace, the\\nnamespace of the module ``builtins``. The global namespace is\\nsearched first. If the name is not found there, the builtins\\nnamespace is searched. The global statement must precede all uses of\\nthe name.\\n\\nThe builtins namespace associated with the execution of a code block\\nis actually found by looking up the name ``__builtins__`` in its\\nglobal namespace; this should be a dictionary or a module (in the\\nlatter case the module\\'s dictionary is used). By default, when in the\\n``__main__`` module, ``__builtins__`` is the built-in module\\n``builtins``; when in any other module, ``__builtins__`` is an alias\\nfor the dictionary of the ``builtins`` module itself.\\n``__builtins__`` can be set to a user-created dictionary to create a\\nweak form of restricted execution.\\n\\n**CPython implementation detail:** Users should not touch\\n``__builtins__``; it is strictly an implementation detail. Users\\nwanting to override values in the builtins namespace should ``import``\\nthe ``builtins`` module and modify its attributes appropriately.\\n\\nThe namespace for a module is automatically created the first time a\\nmodule is imported. The main module for a script is always called\\n``__main__``.\\n\\nThe ``global`` statement has the same scope as a name binding\\noperation in the same block. If the nearest enclosing scope for a\\nfree variable contains a global statement, the free variable is\\ntreated as a global.\\n\\nA class definition is an executable statement that may use and define\\nnames. These references follow the normal rules for name resolution.\\nThe namespace of the class definition becomes the attribute dictionary\\nof the class. Names defined at the class scope are not visible in\\nmethods.\\n\\n\\nInteraction with dynamic features\\n---------------------------------\\n\\nThere are several cases where Python statements are illegal when used\\nin conjunction with nested scopes that contain free variables.\\n\\nIf a variable is referenced in an enclosing scope, it is illegal to\\ndelete the name. An error will be reported at compile time.\\n\\nIf the wild card form of import --- ``import *`` --- is used in a\\nfunction and the function contains or is a nested block with free\\nvariables, the compiler will raise a ``SyntaxError``.\\n\\nThe ``eval()`` and ``exec()`` functions do not have access to the full\\nenvironment for resolving names. Names may be resolved in the local\\nand global namespaces of the caller. Free variables are not resolved\\nin the nearest enclosing namespace, but in the global namespace. [1]\\nThe ``exec()`` and ``eval()`` functions have optional arguments to\\noverride the global and local namespace. If only one namespace is\\nspecified, it is used for both.\\n\\n\\nExceptions\\n==========\\n\\nExceptions are a means of breaking out of the normal flow of control\\nof a code block in order to handle errors or other exceptional\\nconditions. An exception is *raised* at the point where the error is\\ndetected; it may be *handled* by the surrounding code block or by any\\ncode block that directly or indirectly invoked the code block where\\nthe error occurred.\\n\\nThe Python interpreter raises an exception when it detects a run-time\\nerror (such as division by zero). A Python program can also\\nexplicitly raise an exception with the ``raise`` statement. Exception\\nhandlers are specified with the ``try`` ... ``except`` statement. The\\n``finally`` clause of such a statement can be used to specify cleanup\\ncode which does not handle the exception, but is executed whether an\\nexception occurred or not in the preceding code.\\n\\nPython uses the \"termination\" model of error handling: an exception\\nhandler can find out what happened and continue execution at an outer\\nlevel, but it cannot repair the cause of the error and retry the\\nfailing operation (except by re-entering the offending piece of code\\nfrom the top).\\n\\nWhen an exception is not handled at all, the interpreter terminates\\nexecution of the program, or returns to its interactive main loop. In\\neither case, it prints a stack backtrace, except when the exception is\\n``SystemExit``.\\n\\nExceptions are identified by class instances. The ``except`` clause\\nis selected depending on the class of the instance: it must reference\\nthe class of the instance or a base class thereof. The instance can\\nbe received by the handler and can carry additional information about\\nthe exceptional condition.\\n\\nNote: Exception messages are not part of the Python API. Their contents\\n may change from one version of Python to the next without warning\\n and should not be relied on by code which will run under multiple\\n versions of the interpreter.\\n\\nSee also the description of the ``try`` statement in section *The try\\nstatement* and ``raise`` statement in section *The raise statement*.\\n\\n-[ Footnotes ]-\\n\\n[1] This limitation occurs because the code that is executed by these\\n operations is not available at the time the module is compiled.\\n',\n'exprlists':'\\nExpression lists\\n****************\\n\\n expression_list ::= expression ( \",\" expression )* [\",\"]\\n\\nAn expression list containing at least one comma yields a tuple. The\\nlength of the tuple is the number of expressions in the list. The\\nexpressions are evaluated from left to right.\\n\\nThe trailing comma is required only to create a single tuple (a.k.a. a\\n*singleton*); it is optional in all other cases. A single expression\\nwithout a trailing comma doesn\\'t create a tuple, but rather yields the\\nvalue of that expression. (To create an empty tuple, use an empty pair\\nof parentheses: ``()``.)\\n',\n'floating':'\\nFloating point literals\\n***********************\\n\\nFloating point literals are described by the following lexical\\ndefinitions:\\n\\n floatnumber ::= pointfloat | exponentfloat\\n pointfloat ::= [intpart] fraction | intpart \".\"\\n exponentfloat ::= (intpart | pointfloat) exponent\\n intpart ::= digit+\\n fraction ::= \".\" digit+\\n exponent ::= (\"e\" | \"E\") [\"+\" | \"-\"] digit+\\n\\nNote that the integer and exponent parts are always interpreted using\\nradix 10. For example, ``077e010`` is legal, and denotes the same\\nnumber as ``77e10``. The allowed range of floating point literals is\\nimplementation-dependent. Some examples of floating point literals:\\n\\n 3.14 10. .001 1e100 3.14e-10 0e0\\n\\nNote that numeric literals do not include a sign; a phrase like ``-1``\\nis actually an expression composed of the unary operator ``-`` and the\\nliteral ``1``.\\n',\n'for':'\\nThe ``for`` statement\\n*********************\\n\\nThe ``for`` statement is used to iterate over the elements of a\\nsequence (such as a string, tuple or list) or other iterable object:\\n\\n for_stmt ::= \"for\" target_list \"in\" expression_list \":\" suite\\n [\"else\" \":\" suite]\\n\\nThe expression list is evaluated once; it should yield an iterable\\nobject. An iterator is created for the result of the\\n``expression_list``. The suite is then executed once for each item\\nprovided by the iterator, in the order of ascending indices. Each\\nitem in turn is assigned to the target list using the standard rules\\nfor assignments (see *Assignment statements*), and then the suite is\\nexecuted. When the items are exhausted (which is immediately when the\\nsequence is empty or an iterator raises a ``StopIteration``\\nexception), the suite in the ``else`` clause, if present, is executed,\\nand the loop terminates.\\n\\nA ``break`` statement executed in the first suite terminates the loop\\nwithout executing the ``else`` clause\\'s suite. A ``continue``\\nstatement executed in the first suite skips the rest of the suite and\\ncontinues with the next item, or with the ``else`` clause if there was\\nno next item.\\n\\nThe suite may assign to the variable(s) in the target list; this does\\nnot affect the next item assigned to it.\\n\\nNames in the target list are not deleted when the loop is finished,\\nbut if the sequence is empty, it will not have been assigned to at all\\nby the loop. Hint: the built-in function ``range()`` returns an\\niterator of integers suitable to emulate the effect of Pascal\\'s ``for\\ni := a to b do``; e.g., ``list(range(3))`` returns the list ``[0, 1,\\n2]``.\\n\\nNote: There is a subtlety when the sequence is being modified by the loop\\n (this can only occur for mutable sequences, i.e. lists). An\\n internal counter is used to keep track of which item is used next,\\n and this is incremented on each iteration. When this counter has\\n reached the length of the sequence the loop terminates. This means\\n that if the suite deletes the current (or a previous) item from the\\n sequence, the next item will be skipped (since it gets the index of\\n the current item which has already been treated). Likewise, if the\\n suite inserts an item in the sequence before the current item, the\\n current item will be treated again the next time through the loop.\\n This can lead to nasty bugs that can be avoided by making a\\n temporary copy using a slice of the whole sequence, e.g.,\\n\\n for x in a[:]:\\n if x < 0: a.remove(x)\\n',\n'formatstrings':'\\nFormat String Syntax\\n********************\\n\\nThe ``str.format()`` method and the ``Formatter`` class share the same\\nsyntax for format strings (although in the case of ``Formatter``,\\nsubclasses can define their own format string syntax).\\n\\nFormat strings contain \"replacement fields\" surrounded by curly braces\\n``{}``. Anything that is not contained in braces is considered literal\\ntext, which is copied unchanged to the output. If you need to include\\na brace character in the literal text, it can be escaped by doubling:\\n``{{`` and ``}}``.\\n\\nThe grammar for a replacement field is as follows:\\n\\n replacement_field ::= \"{\" [field_name] [\"!\" conversion] [\":\" format_spec] \"}\"\\n field_name ::= arg_name (\".\" attribute_name | \"[\" element_index \"]\")*\\n arg_name ::= [identifier | integer]\\n attribute_name ::= identifier\\n element_index ::= integer | index_string\\n index_string ::= <any source character except \"]\"> +\\n conversion ::= \"r\" | \"s\" | \"a\"\\n format_spec ::= <described in the next section>\\n\\nIn less formal terms, the replacement field can start with a\\n*field_name* that specifies the object whose value is to be formatted\\nand inserted into the output instead of the replacement field. The\\n*field_name* is optionally followed by a *conversion* field, which is\\npreceded by an exclamation point ``\\'!\\'``, and a *format_spec*, which\\nis preceded by a colon ``\\':\\'``. These specify a non-default format\\nfor the replacement value.\\n\\nSee also the *Format Specification Mini-Language* section.\\n\\nThe *field_name* itself begins with an *arg_name* that is either a\\nnumber or a keyword. If it\\'s a number, it refers to a positional\\nargument, and if it\\'s a keyword, it refers to a named keyword\\nargument. If the numerical arg_names in a format string are 0, 1, 2,\\n... in sequence, they can all be omitted (not just some) and the\\nnumbers 0, 1, 2, ... will be automatically inserted in that order.\\nBecause *arg_name* is not quote-delimited, it is not possible to\\nspecify arbitrary dictionary keys (e.g., the strings ``\\'10\\'`` or\\n``\\':-]\\'``) within a format string. The *arg_name* can be followed by\\nany number of index or attribute expressions. An expression of the\\nform ``\\'.name\\'`` selects the named attribute using ``getattr()``,\\nwhile an expression of the form ``\\'[index]\\'`` does an index lookup\\nusing ``__getitem__()``.\\n\\nChanged in version 3.1: The positional argument specifiers can be\\nomitted, so ``\\'{} {}\\'`` is equivalent to ``\\'{0} {1}\\'``.\\n\\nSome simple format string examples:\\n\\n \"First, thou shalt count to {0}\" # References first positional argument\\n \"Bring me a {}\" # Implicitly references the first positional argument\\n \"From {} to {}\" # Same as \"From {0} to {1}\"\\n \"My quest is {name}\" # References keyword argument \\'name\\'\\n \"Weight in tons {0.weight}\" # \\'weight\\' attribute of first positional arg\\n \"Units destroyed: {players[0]}\" # First element of keyword argument \\'players\\'.\\n\\nThe *conversion* field causes a type coercion before formatting.\\nNormally, the job of formatting a value is done by the\\n``__format__()`` method of the value itself. However, in some cases\\nit is desirable to force a type to be formatted as a string,\\noverriding its own definition of formatting. By converting the value\\nto a string before calling ``__format__()``, the normal formatting\\nlogic is bypassed.\\n\\nThree conversion flags are currently supported: ``\\'!s\\'`` which calls\\n``str()`` on the value, ``\\'!r\\'`` which calls ``repr()`` and ``\\'!a\\'``\\nwhich calls ``ascii()``.\\n\\nSome examples:\\n\\n \"Harold\\'s a clever {0!s}\" # Calls str() on the argument first\\n \"Bring out the holy {name!r}\" # Calls repr() on the argument first\\n \"More {!a}\" # Calls ascii() on the argument first\\n\\nThe *format_spec* field contains a specification of how the value\\nshould be presented, including such details as field width, alignment,\\npadding, decimal precision and so on. Each value type can define its\\nown \"formatting mini-language\" or interpretation of the *format_spec*.\\n\\nMost built-in types support a common formatting mini-language, which\\nis described in the next section.\\n\\nA *format_spec* field can also include nested replacement fields\\nwithin it. These nested replacement fields can contain only a field\\nname; conversion flags and format specifications are not allowed. The\\nreplacement fields within the format_spec are substituted before the\\n*format_spec* string is interpreted. This allows the formatting of a\\nvalue to be dynamically specified.\\n\\nSee the *Format examples* section for some examples.\\n\\n\\nFormat Specification Mini-Language\\n==================================\\n\\n\"Format specifications\" are used within replacement fields contained\\nwithin a format string to define how individual values are presented\\n(see *Format String Syntax*). They can also be passed directly to the\\nbuilt-in ``format()`` function. Each formattable type may define how\\nthe format specification is to be interpreted.\\n\\nMost built-in types implement the following options for format\\nspecifications, although some of the formatting options are only\\nsupported by the numeric types.\\n\\nA general convention is that an empty format string (``\"\"``) produces\\nthe same result as if you had called ``str()`` on the value. A non-\\nempty format string typically modifies the result.\\n\\nThe general form of a *standard format specifier* is:\\n\\n format_spec ::= [[fill]align][sign][#][0][width][,][.precision][type]\\n fill ::= <a character other than \\'{\\' or \\'}\\'>\\n align ::= \"<\" | \">\" | \"=\" | \"^\"\\n sign ::= \"+\" | \"-\" | \" \"\\n width ::= integer\\n precision ::= integer\\n type ::= \"b\" | \"c\" | \"d\" | \"e\" | \"E\" | \"f\" | \"F\" | \"g\" | \"G\" | \"n\" | \"o\" | \"s\" | \"x\" | \"X\" | \"%\"\\n\\nThe *fill* character can be any character other than \\'{\\' or \\'}\\'. The\\npresence of a fill character is signaled by the character following\\nit, which must be one of the alignment options. If the second\\ncharacter of *format_spec* is not a valid alignment option, then it is\\nassumed that both the fill character and the alignment option are\\nabsent.\\n\\nThe meaning of the various alignment options is as follows:\\n\\n +-----------+------------------------------------------------------------+\\n | Option | Meaning |\\n +===========+============================================================+\\n | ``\\'<\\'`` | Forces the field to be left-aligned within the available |\\n | | space (this is the default for most objects). |\\n +-----------+------------------------------------------------------------+\\n | ``\\'>\\'`` | Forces the field to be right-aligned within the available |\\n | | space (this is the default for numbers). |\\n +-----------+------------------------------------------------------------+\\n | ``\\'=\\'`` | Forces the padding to be placed after the sign (if any) |\\n | | but before the digits. This is used for printing fields |\\n | | in the form \\'+000000120\\'. This alignment option is only |\\n | | valid for numeric types. |\\n +-----------+------------------------------------------------------------+\\n | ``\\'^\\'`` | Forces the field to be centered within the available |\\n | | space. |\\n +-----------+------------------------------------------------------------+\\n\\nNote that unless a minimum field width is defined, the field width\\nwill always be the same size as the data to fill it, so that the\\nalignment option has no meaning in this case.\\n\\nThe *sign* option is only valid for number types, and can be one of\\nthe following:\\n\\n +-----------+------------------------------------------------------------+\\n | Option | Meaning |\\n +===========+============================================================+\\n | ``\\'+\\'`` | indicates that a sign should be used for both positive as |\\n | | well as negative numbers. |\\n +-----------+------------------------------------------------------------+\\n | ``\\'-\\'`` | indicates that a sign should be used only for negative |\\n | | numbers (this is the default behavior). |\\n +-----------+------------------------------------------------------------+\\n | space | indicates that a leading space should be used on positive |\\n | | numbers, and a minus sign on negative numbers. |\\n +-----------+------------------------------------------------------------+\\n\\nThe ``\\'#\\'`` option causes the \"alternate form\" to be used for the\\nconversion. The alternate form is defined differently for different\\ntypes. This option is only valid for integer, float, complex and\\nDecimal types. For integers, when binary, octal, or hexadecimal output\\nis used, this option adds the prefix respective ``\\'0b\\'``, ``\\'0o\\'``, or\\n``\\'0x\\'`` to the output value. For floats, complex and Decimal the\\nalternate form causes the result of the conversion to always contain a\\ndecimal-point character, even if no digits follow it. Normally, a\\ndecimal-point character appears in the result of these conversions\\nonly if a digit follows it. In addition, for ``\\'g\\'`` and ``\\'G\\'``\\nconversions, trailing zeros are not removed from the result.\\n\\nThe ``\\',\\'`` option signals the use of a comma for a thousands\\nseparator. For a locale aware separator, use the ``\\'n\\'`` integer\\npresentation type instead.\\n\\nChanged in version 3.1: Added the ``\\',\\'`` option (see also **PEP\\n378**).\\n\\n*width* is a decimal integer defining the minimum field width. If not\\nspecified, then the field width will be determined by the content.\\n\\nPreceding the *width* field by a zero (``\\'0\\'``) character enables\\nsign-aware zero-padding for numeric types. This is equivalent to a\\n*fill* character of ``\\'0\\'`` with an *alignment* type of ``\\'=\\'``.\\n\\nThe *precision* is a decimal number indicating how many digits should\\nbe displayed after the decimal point for a floating point value\\nformatted with ``\\'f\\'`` and ``\\'F\\'``, or before and after the decimal\\npoint for a floating point value formatted with ``\\'g\\'`` or ``\\'G\\'``.\\nFor non-number types the field indicates the maximum field size - in\\nother words, how many characters will be used from the field content.\\nThe *precision* is not allowed for integer values.\\n\\nFinally, the *type* determines how the data should be presented.\\n\\nThe available string presentation types are:\\n\\n +-----------+------------------------------------------------------------+\\n | Type | Meaning |\\n +===========+============================================================+\\n | ``\\'s\\'`` | String format. This is the default type for strings and |\\n | | may be omitted. |\\n +-----------+------------------------------------------------------------+\\n | None | The same as ``\\'s\\'``. |\\n +-----------+------------------------------------------------------------+\\n\\nThe available integer presentation types are:\\n\\n +-----------+------------------------------------------------------------+\\n | Type | Meaning |\\n +===========+============================================================+\\n | ``\\'b\\'`` | Binary format. Outputs the number in base 2. |\\n +-----------+------------------------------------------------------------+\\n | ``\\'c\\'`` | Character. Converts the integer to the corresponding |\\n | | unicode character before printing. |\\n +-----------+------------------------------------------------------------+\\n | ``\\'d\\'`` | Decimal Integer. Outputs the number in base 10. |\\n +-----------+------------------------------------------------------------+\\n | ``\\'o\\'`` | Octal format. Outputs the number in base 8. |\\n +-----------+------------------------------------------------------------+\\n | ``\\'x\\'`` | Hex format. Outputs the number in base 16, using lower- |\\n | | case letters for the digits above 9. |\\n +-----------+------------------------------------------------------------+\\n | ``\\'X\\'`` | Hex format. Outputs the number in base 16, using upper- |\\n | | case letters for the digits above 9. |\\n +-----------+------------------------------------------------------------+\\n | ``\\'n\\'`` | Number. This is the same as ``\\'d\\'``, except that it uses |\\n | | the current locale setting to insert the appropriate |\\n | | number separator characters. |\\n +-----------+------------------------------------------------------------+\\n | None | The same as ``\\'d\\'``. |\\n +-----------+------------------------------------------------------------+\\n\\nIn addition to the above presentation types, integers can be formatted\\nwith the floating point presentation types listed below (except\\n``\\'n\\'`` and None). When doing so, ``float()`` is used to convert the\\ninteger to a floating point number before formatting.\\n\\nThe available presentation types for floating point and decimal values\\nare:\\n\\n +-----------+------------------------------------------------------------+\\n | Type | Meaning |\\n +===========+============================================================+\\n | ``\\'e\\'`` | Exponent notation. Prints the number in scientific |\\n | | notation using the letter \\'e\\' to indicate the exponent. |\\n +-----------+------------------------------------------------------------+\\n | ``\\'E\\'`` | Exponent notation. Same as ``\\'e\\'`` except it uses an upper |\\n | | case \\'E\\' as the separator character. |\\n +-----------+------------------------------------------------------------+\\n | ``\\'f\\'`` | Fixed point. Displays the number as a fixed-point number. |\\n +-----------+------------------------------------------------------------+\\n | ``\\'F\\'`` | Fixed point. Same as ``\\'f\\'``, but converts ``nan`` to |\\n | | ``NAN`` and ``inf`` to ``INF``. |\\n +-----------+------------------------------------------------------------+\\n | ``\\'g\\'`` | General format. For a given precision ``p >= 1``, this |\\n | | rounds the number to ``p`` significant digits and then |\\n | | formats the result in either fixed-point format or in |\\n | | scientific notation, depending on its magnitude. The |\\n | | precise rules are as follows: suppose that the result |\\n | | formatted with presentation type ``\\'e\\'`` and precision |\\n | | ``p-1`` would have exponent ``exp``. Then if ``-4 <= exp |\\n | | < p``, the number is formatted with presentation type |\\n | | ``\\'f\\'`` and precision ``p-1-exp``. Otherwise, the number |\\n | | is formatted with presentation type ``\\'e\\'`` and precision |\\n | | ``p-1``. In both cases insignificant trailing zeros are |\\n | | removed from the significand, and the decimal point is |\\n | | also removed if there are no remaining digits following |\\n | | it. Positive and negative infinity, positive and negative |\\n | | zero, and nans, are formatted as ``inf``, ``-inf``, ``0``, |\\n | | ``-0`` and ``nan`` respectively, regardless of the |\\n | | precision. A precision of ``0`` is treated as equivalent |\\n | | to a precision of ``1``. |\\n +-----------+------------------------------------------------------------+\\n | ``\\'G\\'`` | General format. Same as ``\\'g\\'`` except switches to ``\\'E\\'`` |\\n | | if the number gets too large. The representations of |\\n | | infinity and NaN are uppercased, too. |\\n +-----------+------------------------------------------------------------+\\n | ``\\'n\\'`` | Number. This is the same as ``\\'g\\'``, except that it uses |\\n | | the current locale setting to insert the appropriate |\\n | | number separator characters. |\\n +-----------+------------------------------------------------------------+\\n | ``\\'%\\'`` | Percentage. Multiplies the number by 100 and displays in |\\n | | fixed (``\\'f\\'``) format, followed by a percent sign. |\\n +-----------+------------------------------------------------------------+\\n | None | Similar to ``\\'g\\'``, except with at least one digit past |\\n | | the decimal point and a default precision of 12. This is |\\n | | intended to match ``str()``, except you can add the other |\\n | | format modifiers. |\\n +-----------+------------------------------------------------------------+\\n\\n\\nFormat examples\\n===============\\n\\nThis section contains examples of the new format syntax and comparison\\nwith the old ``%``-formatting.\\n\\nIn most of the cases the syntax is similar to the old\\n``%``-formatting, with the addition of the ``{}`` and with ``:`` used\\ninstead of ``%``. For example, ``\\'%03.2f\\'`` can be translated to\\n``\\'{:03.2f}\\'``.\\n\\nThe new format syntax also supports new and different options, shown\\nin the follow examples.\\n\\nAccessing arguments by position:\\n\\n >>> \\'{0}, {1}, {2}\\'.format(\\'a\\', \\'b\\', \\'c\\')\\n \\'a, b, c\\'\\n >>> \\'{}, {}, {}\\'.format(\\'a\\', \\'b\\', \\'c\\') # 3.1+ only\\n \\'a, b, c\\'\\n >>> \\'{2}, {1}, {0}\\'.format(\\'a\\', \\'b\\', \\'c\\')\\n \\'c, b, a\\'\\n >>> \\'{2}, {1}, {0}\\'.format(*\\'abc\\') # unpacking argument sequence\\n \\'c, b, a\\'\\n >>> \\'{0}{1}{0}\\'.format(\\'abra\\', \\'cad\\') # arguments\\' indices can be repeated\\n \\'abracadabra\\'\\n\\nAccessing arguments by name:\\n\\n >>> \\'Coordinates: {latitude}, {longitude}\\'.format(latitude=\\'37.24N\\', longitude=\\'-115.81W\\')\\n \\'Coordinates: 37.24N, -115.81W\\'\\n >>> coord = {\\'latitude\\': \\'37.24N\\', \\'longitude\\': \\'-115.81W\\'}\\n >>> \\'Coordinates: {latitude}, {longitude}\\'.format(**coord)\\n \\'Coordinates: 37.24N, -115.81W\\'\\n\\nAccessing arguments\\' attributes:\\n\\n >>> c = 3-5j\\n >>> (\\'The complex number {0} is formed from the real part {0.real} \\'\\n ... \\'and the imaginary part {0.imag}.\\').format(c)\\n \\'The complex number (3-5j) is formed from the real part 3.0 and the imaginary part -5.0.\\'\\n >>> class Point:\\n ... def __init__(self, x, y):\\n ... self.x, self.y = x, y\\n ... def __str__(self):\\n ... return \\'Point({self.x}, {self.y})\\'.format(self=self)\\n ...\\n >>> str(Point(4, 2))\\n \\'Point(4, 2)\\'\\n\\nAccessing arguments\\' items:\\n\\n >>> coord = (3, 5)\\n >>> \\'X: {0[0]}; Y: {0[1]}\\'.format(coord)\\n \\'X: 3; Y: 5\\'\\n\\nReplacing ``%s`` and ``%r``:\\n\\n >>> \"repr() shows quotes: {!r}; str() doesn\\'t: {!s}\".format(\\'test1\\', \\'test2\\')\\n \"repr() shows quotes: \\'test1\\'; str() doesn\\'t: test2\"\\n\\nAligning the text and specifying a width:\\n\\n >>> \\'{:<30}\\'.format(\\'left aligned\\')\\n \\'left aligned \\'\\n >>> \\'{:>30}\\'.format(\\'right aligned\\')\\n \\' right aligned\\'\\n >>> \\'{:^30}\\'.format(\\'centered\\')\\n \\' centered \\'\\n >>> \\'{:*^30}\\'.format(\\'centered\\') # use \\'*\\' as a fill char\\n \\'***********centered***********\\'\\n\\nReplacing ``%+f``, ``%-f``, and ``% f`` and specifying a sign:\\n\\n >>> \\'{:+f}; {:+f}\\'.format(3.14, -3.14) # show it always\\n \\'+3.140000; -3.140000\\'\\n >>> \\'{: f}; {: f}\\'.format(3.14, -3.14) # show a space for positive numbers\\n \\' 3.140000; -3.140000\\'\\n >>> \\'{:-f}; {:-f}\\'.format(3.14, -3.14) # show only the minus -- same as \\'{:f}; {:f}\\'\\n \\'3.140000; -3.140000\\'\\n\\nReplacing ``%x`` and ``%o`` and converting the value to different\\nbases:\\n\\n >>> # format also supports binary numbers\\n >>> \"int: {0:d}; hex: {0:x}; oct: {0:o}; bin: {0:b}\".format(42)\\n \\'int: 42; hex: 2a; oct: 52; bin: 101010\\'\\n >>> # with 0x, 0o, or 0b as prefix:\\n >>> \"int: {0:d}; hex: {0:#x}; oct: {0:#o}; bin: {0:#b}\".format(42)\\n \\'int: 42; hex: 0x2a; oct: 0o52; bin: 0b101010\\'\\n\\nUsing the comma as a thousands separator:\\n\\n >>> \\'{:,}\\'.format(1234567890)\\n \\'1,234,567,890\\'\\n\\nExpressing a percentage:\\n\\n >>> points = 19\\n >>> total = 22\\n >>> \\'Correct answers: {:.2%}\\'.format(points/total)\\n \\'Correct answers: 86.36%\\'\\n\\nUsing type-specific formatting:\\n\\n >>> import datetime\\n >>> d = datetime.datetime(2010, 7, 4, 12, 15, 58)\\n >>> \\'{:%Y-%m-%d %H:%M:%S}\\'.format(d)\\n \\'2010-07-04 12:15:58\\'\\n\\nNesting arguments and more complex examples:\\n\\n >>> for align, text in zip(\\'<^>\\', [\\'left\\', \\'center\\', \\'right\\']):\\n ... \\'{0:{fill}{align}16}\\'.format(text, fill=align, align=align)\\n ...\\n \\'left<<<<<<<<<<<<\\'\\n \\'^^^^^center^^^^^\\'\\n \\'>>>>>>>>>>>right\\'\\n >>>\\n >>> octets = [192, 168, 0, 1]\\n >>> \\'{:02X}{:02X}{:02X}{:02X}\\'.format(*octets)\\n \\'C0A80001\\'\\n >>> int(_, 16)\\n 3232235521\\n >>>\\n >>> width = 5\\n >>> for num in range(5,12): #doctest: +NORMALIZE_WHITESPACE\\n ... for base in \\'dXob\\':\\n ... print(\\'{0:{width}{base}}\\'.format(num, base=base, width=width), end=\\' \\')\\n ... print()\\n ...\\n 5 5 5 101\\n 6 6 6 110\\n 7 7 7 111\\n 8 8 10 1000\\n 9 9 11 1001\\n 10 A 12 1010\\n 11 B 13 1011\\n',\n'function':'\\nFunction definitions\\n********************\\n\\nA function definition defines a user-defined function object (see\\nsection *The standard type hierarchy*):\\n\\n funcdef ::= [decorators] \"def\" funcname \"(\" [parameter_list] \")\" [\"->\" expression] \":\" suite\\n decorators ::= decorator+\\n decorator ::= \"@\" dotted_name [\"(\" [parameter_list [\",\"]] \")\"] NEWLINE\\n dotted_name ::= identifier (\".\" identifier)*\\n parameter_list ::= (defparameter \",\")*\\n ( \"*\" [parameter] (\",\" defparameter)* [\",\" \"**\" parameter]\\n | \"**\" parameter\\n | defparameter [\",\"] )\\n parameter ::= identifier [\":\" expression]\\n defparameter ::= parameter [\"=\" expression]\\n funcname ::= identifier\\n\\nA function definition is an executable statement. Its execution binds\\nthe function name in the current local namespace to a function object\\n(a wrapper around the executable code for the function). This\\nfunction object contains a reference to the current global namespace\\nas the global namespace to be used when the function is called.\\n\\nThe function definition does not execute the function body; this gets\\nexecuted only when the function is called. [3]\\n\\nA function definition may be wrapped by one or more *decorator*\\nexpressions. Decorator expressions are evaluated when the function is\\ndefined, in the scope that contains the function definition. The\\nresult must be a callable, which is invoked with the function object\\nas the only argument. The returned value is bound to the function name\\ninstead of the function object. Multiple decorators are applied in\\nnested fashion. For example, the following code\\n\\n @f1(arg)\\n @f2\\n def func(): pass\\n\\nis equivalent to\\n\\n def func(): pass\\n func = f1(arg)(f2(func))\\n\\nWhen one or more *parameters* have the form *parameter* ``=``\\n*expression*, the function is said to have \"default parameter values.\"\\nFor a parameter with a default value, the corresponding *argument* may\\nbe omitted from a call, in which case the parameter\\'s default value is\\nsubstituted. If a parameter has a default value, all following\\nparameters up until the \"``*``\" must also have a default value ---\\nthis is a syntactic restriction that is not expressed by the grammar.\\n\\n**Default parameter values are evaluated when the function definition\\nis executed.** This means that the expression is evaluated once, when\\nthe function is defined, and that the same \"pre-computed\" value is\\nused for each call. This is especially important to understand when a\\ndefault parameter is a mutable object, such as a list or a dictionary:\\nif the function modifies the object (e.g. by appending an item to a\\nlist), the default value is in effect modified. This is generally not\\nwhat was intended. A way around this is to use ``None`` as the\\ndefault, and explicitly test for it in the body of the function, e.g.:\\n\\n def whats_on_the_telly(penguin=None):\\n if penguin is None:\\n penguin = []\\n penguin.append(\"property of the zoo\")\\n return penguin\\n\\nFunction call semantics are described in more detail in section\\n*Calls*. A function call always assigns values to all parameters\\nmentioned in the parameter list, either from position arguments, from\\nkeyword arguments, or from default values. If the form\\n\"``*identifier``\" is present, it is initialized to a tuple receiving\\nany excess positional parameters, defaulting to the empty tuple. If\\nthe form \"``**identifier``\" is present, it is initialized to a new\\ndictionary receiving any excess keyword arguments, defaulting to a new\\nempty dictionary. Parameters after \"``*``\" or \"``*identifier``\" are\\nkeyword-only parameters and may only be passed used keyword arguments.\\n\\nParameters may have annotations of the form \"``: expression``\"\\nfollowing the parameter name. Any parameter may have an annotation\\neven those of the form ``*identifier`` or ``**identifier``. Functions\\nmay have \"return\" annotation of the form \"``-> expression``\" after the\\nparameter list. These annotations can be any valid Python expression\\nand are evaluated when the function definition is executed.\\nAnnotations may be evaluated in a different order than they appear in\\nthe source code. The presence of annotations does not change the\\nsemantics of a function. The annotation values are available as\\nvalues of a dictionary keyed by the parameters\\' names in the\\n``__annotations__`` attribute of the function object.\\n\\nIt is also possible to create anonymous functions (functions not bound\\nto a name), for immediate use in expressions. This uses lambda forms,\\ndescribed in section *Lambdas*. Note that the lambda form is merely a\\nshorthand for a simplified function definition; a function defined in\\na \"``def``\" statement can be passed around or assigned to another name\\njust like a function defined by a lambda form. The \"``def``\" form is\\nactually more powerful since it allows the execution of multiple\\nstatements and annotations.\\n\\n**Programmer\\'s note:** Functions are first-class objects. A \"``def``\"\\nform executed inside a function definition defines a local function\\nthat can be returned or passed around. Free variables used in the\\nnested function can access the local variables of the function\\ncontaining the def. See section *Naming and binding* for details.\\n\\nSee also:\\n\\n **PEP 3107** - Function Annotations\\n The original specification for function annotations.\\n',\n'global':'\\nThe ``global`` statement\\n************************\\n\\n global_stmt ::= \"global\" identifier (\",\" identifier)*\\n\\nThe ``global`` statement is a declaration which holds for the entire\\ncurrent code block. It means that the listed identifiers are to be\\ninterpreted as globals. It would be impossible to assign to a global\\nvariable without ``global``, although free variables may refer to\\nglobals without being declared global.\\n\\nNames listed in a ``global`` statement must not be used in the same\\ncode block textually preceding that ``global`` statement.\\n\\nNames listed in a ``global`` statement must not be defined as formal\\nparameters or in a ``for`` loop control target, ``class`` definition,\\nfunction definition, or ``import`` statement.\\n\\n**CPython implementation detail:** The current implementation does not\\nenforce the latter two restrictions, but programs should not abuse\\nthis freedom, as future implementations may enforce them or silently\\nchange the meaning of the program.\\n\\n**Programmer\\'s note:** the ``global`` is a directive to the parser.\\nIt applies only to code parsed at the same time as the ``global``\\nstatement. In particular, a ``global`` statement contained in a string\\nor code object supplied to the built-in ``exec()`` function does not\\naffect the code block *containing* the function call, and code\\ncontained in such a string is unaffected by ``global`` statements in\\nthe code containing the function call. The same applies to the\\n``eval()`` and ``compile()`` functions.\\n',\n'id-classes':'\\nReserved classes of identifiers\\n*******************************\\n\\nCertain classes of identifiers (besides keywords) have special\\nmeanings. These classes are identified by the patterns of leading and\\ntrailing underscore characters:\\n\\n``_*``\\n Not imported by ``from module import *``. The special identifier\\n ``_`` is used in the interactive interpreter to store the result of\\n the last evaluation; it is stored in the ``builtins`` module. When\\n not in interactive mode, ``_`` has no special meaning and is not\\n defined. See section *The import statement*.\\n\\n Note: The name ``_`` is often used in conjunction with\\n internationalization; refer to the documentation for the\\n ``gettext`` module for more information on this convention.\\n\\n``__*__``\\n System-defined names. These names are defined by the interpreter\\n and its implementation (including the standard library). Current\\n system names are discussed in the *Special method names* section\\n and elsewhere. More will likely be defined in future versions of\\n Python. *Any* use of ``__*__`` names, in any context, that does\\n not follow explicitly documented use, is subject to breakage\\n without warning.\\n\\n``__*``\\n Class-private names. Names in this category, when used within the\\n context of a class definition, are re-written to use a mangled form\\n to help avoid name clashes between \"private\" attributes of base and\\n derived classes. See section *Identifiers (Names)*.\\n',\n'identifiers':'\\nIdentifiers and keywords\\n************************\\n\\nIdentifiers (also referred to as *names*) are described by the\\nfollowing lexical definitions.\\n\\nThe syntax of identifiers in Python is based on the Unicode standard\\nannex UAX-31, with elaboration and changes as defined below; see also\\n**PEP 3131** for further details.\\n\\nWithin the ASCII range (U+0001..U+007F), the valid characters for\\nidentifiers are the same as in Python 2.x: the uppercase and lowercase\\nletters ``A`` through ``Z``, the underscore ``_`` and, except for the\\nfirst character, the digits ``0`` through ``9``.\\n\\nPython 3.0 introduces additional characters from outside the ASCII\\nrange (see **PEP 3131**). For these characters, the classification\\nuses the version of the Unicode Character Database as included in the\\n``unicodedata`` module.\\n\\nIdentifiers are unlimited in length. Case is significant.\\n\\n identifier ::= xid_start xid_continue*\\n id_start ::= <all characters in general categories Lu, Ll, Lt, Lm, Lo, Nl, the underscore, and characters with the Other_ID_Start property>\\n id_continue ::= <all characters in id_start, plus characters in the categories Mn, Mc, Nd, Pc and others with the Other_ID_Continue property>\\n xid_start ::= <all characters in id_start whose NFKC normalization is in \"id_start xid_continue*\">\\n xid_continue ::= <all characters in id_continue whose NFKC normalization is in \"id_continue*\">\\n\\nThe Unicode category codes mentioned above stand for:\\n\\n* *Lu* - uppercase letters\\n\\n* *Ll* - lowercase letters\\n\\n* *Lt* - titlecase letters\\n\\n* *Lm* - modifier letters\\n\\n* *Lo* - other letters\\n\\n* *Nl* - letter numbers\\n\\n* *Mn* - nonspacing marks\\n\\n* *Mc* - spacing combining marks\\n\\n* *Nd* - decimal numbers\\n\\n* *Pc* - connector punctuations\\n\\n* *Other_ID_Start* - explicit list of characters in PropList.txt to\\n support backwards compatibility\\n\\n* *Other_ID_Continue* - likewise\\n\\nAll identifiers are converted into the normal form NFKC while parsing;\\ncomparison of identifiers is based on NFKC.\\n\\nA non-normative HTML file listing all valid identifier characters for\\nUnicode 4.1 can be found at http://www.dcl.hpi.uni-\\npotsdam.de/home/loewis/table-3131.html.\\n\\n\\nKeywords\\n========\\n\\nThe following identifiers are used as reserved words, or *keywords* of\\nthe language, and cannot be used as ordinary identifiers. They must\\nbe spelled exactly as written here:\\n\\n False class finally is return\\n None continue for lambda try\\n True def from nonlocal while\\n and del global not with\\n as elif if or yield\\n assert else import pass\\n break except in raise\\n\\n\\nReserved classes of identifiers\\n===============================\\n\\nCertain classes of identifiers (besides keywords) have special\\nmeanings. These classes are identified by the patterns of leading and\\ntrailing underscore characters:\\n\\n``_*``\\n Not imported by ``from module import *``. The special identifier\\n ``_`` is used in the interactive interpreter to store the result of\\n the last evaluation; it is stored in the ``builtins`` module. When\\n not in interactive mode, ``_`` has no special meaning and is not\\n defined. See section *The import statement*.\\n\\n Note: The name ``_`` is often used in conjunction with\\n internationalization; refer to the documentation for the\\n ``gettext`` module for more information on this convention.\\n\\n``__*__``\\n System-defined names. These names are defined by the interpreter\\n and its implementation (including the standard library). Current\\n system names are discussed in the *Special method names* section\\n and elsewhere. More will likely be defined in future versions of\\n Python. *Any* use of ``__*__`` names, in any context, that does\\n not follow explicitly documented use, is subject to breakage\\n without warning.\\n\\n``__*``\\n Class-private names. Names in this category, when used within the\\n context of a class definition, are re-written to use a mangled form\\n to help avoid name clashes between \"private\" attributes of base and\\n derived classes. See section *Identifiers (Names)*.\\n',\n'if':'\\nThe ``if`` statement\\n********************\\n\\nThe ``if`` statement is used for conditional execution:\\n\\n if_stmt ::= \"if\" expression \":\" suite\\n ( \"elif\" expression \":\" suite )*\\n [\"else\" \":\" suite]\\n\\nIt selects exactly one of the suites by evaluating the expressions one\\nby one until one is found to be true (see section *Boolean operations*\\nfor the definition of true and false); then that suite is executed\\n(and no other part of the ``if`` statement is executed or evaluated).\\nIf all expressions are false, the suite of the ``else`` clause, if\\npresent, is executed.\\n',\n'imaginary':'\\nImaginary literals\\n******************\\n\\nImaginary literals are described by the following lexical definitions:\\n\\n imagnumber ::= (floatnumber | intpart) (\"j\" | \"J\")\\n\\nAn imaginary literal yields a complex number with a real part of 0.0.\\nComplex numbers are represented as a pair of floating point numbers\\nand have the same restrictions on their range. To create a complex\\nnumber with a nonzero real part, add a floating point number to it,\\ne.g., ``(3+4j)``. Some examples of imaginary literals:\\n\\n 3.14j 10.j 10j .001j 1e100j 3.14e-10j\\n',\n'import':'\\nThe ``import`` statement\\n************************\\n\\n import_stmt ::= \"import\" module [\"as\" name] ( \",\" module [\"as\" name] )*\\n | \"from\" relative_module \"import\" identifier [\"as\" name]\\n ( \",\" identifier [\"as\" name] )*\\n | \"from\" relative_module \"import\" \"(\" identifier [\"as\" name]\\n ( \",\" identifier [\"as\" name] )* [\",\"] \")\"\\n | \"from\" module \"import\" \"*\"\\n module ::= (identifier \".\")* identifier\\n relative_module ::= \".\"* module | \".\"+\\n name ::= identifier\\n\\nThe basic import statement (no ``from`` clause) is executed in two\\nsteps:\\n\\n1. find a module, loading and initializing it if necessary\\n\\n2. define a name or names in the local namespace for the scope where\\n the ``import`` statement occurs.\\n\\nWhen the statement contains multiple clauses (separated by commas) the\\ntwo steps are carried out separately for each clause, just as though\\nthe clauses had been separated out into individiual import statements.\\n\\nThe details of the first step, finding and loading modules is\\ndescribed in greater detail in the section on the *import system*,\\nwhich also describes the various types of packages and modules that\\ncan be imported, as well as all the hooks that can be used to\\ncustomize the import system. Note that failures in this step may\\nindicate either that the module could not be located, *or* that an\\nerror occurred while initializing the module, which includes execution\\nof the module\\'s code.\\n\\nIf the requested module is retrieved successfully, it will be made\\navailable in the local namespace in one of three ways:\\n\\n* If the module name is followed by ``as``, then the name following\\n ``as`` is bound directly to the imported module.\\n\\n* If no other name is specified, and the module being imported is a\\n top level module, the module\\'s name is bound in the local namespace\\n as a reference to the imported module\\n\\n* If the module being imported is *not* a top level module, then the\\n name of the top level package that contains the module is bound in\\n the local namespace as a reference to the top level package. The\\n imported module must be accessed using its full qualified name\\n rather than directly\\n\\nThe ``from`` form uses a slightly more complex process:\\n\\n1. find the module specified in the ``from`` clause loading and\\n initializing it if necessary;\\n\\n2. for each of the identifiers specified in the ``import`` clauses:\\n\\n 1. check if the imported module has an attribute by that name\\n\\n 2. if not, attempt to import a submodule with that name and then\\n check the imported module again for that attribute\\n\\n 3. if the attribute is not found, ``ImportError`` is raised.\\n\\n 4. otherwise, a reference to that value is bound in the local\\n namespace, using the name in the ``as`` clause if it is present,\\n otherwise using the attribute name\\n\\nExamples:\\n\\n import foo # foo imported and bound locally\\n import foo.bar.baz # foo.bar.baz imported, foo bound locally\\n import foo.bar.baz as fbb # foo.bar.baz imported and bound as fbb\\n from foo.bar import baz # foo.bar.baz imported and bound as baz\\n from foo import attr # foo imported and foo.attr bound as attr\\n\\nIf the list of identifiers is replaced by a star (``\\'*\\'``), all public\\nnames defined in the module are bound in the local namespace for the\\nscope where the ``import`` statement occurs.\\n\\nThe *public names* defined by a module are determined by checking the\\nmodule\\'s namespace for a variable named ``__all__``; if defined, it\\nmust be a sequence of strings which are names defined or imported by\\nthat module. The names given in ``__all__`` are all considered public\\nand are required to exist. If ``__all__`` is not defined, the set of\\npublic names includes all names found in the module\\'s namespace which\\ndo not begin with an underscore character (``\\'_\\'``). ``__all__``\\nshould contain the entire public API. It is intended to avoid\\naccidentally exporting items that are not part of the API (such as\\nlibrary modules which were imported and used within the module).\\n\\nThe ``from`` form with ``*`` may only occur in a module scope.\\nAttempting to use it in class or function definitions will raise a\\n``SyntaxError``.\\n\\nThe *public names* defined by a module are determined by checking the\\nmodule\\'s namespace for a variable named ``__all__``; if defined, it\\nmust be a sequence of strings which are names defined or imported by\\nthat module. The names given in ``__all__`` are all considered public\\nand are required to exist. If ``__all__`` is not defined, the set of\\npublic names includes all names found in the module\\'s namespace which\\ndo not begin with an underscore character (``\\'_\\'``). ``__all__``\\nshould contain the entire public API. It is intended to avoid\\naccidentally exporting items that are not part of the API (such as\\nlibrary modules which were imported and used within the module).\\n\\nThe ``from`` form with ``*`` may only occur in a module scope. The\\nwild card form of import --- ``import *`` --- is only allowed at the\\nmodule level. Attempting to use it in class or function definitions\\nwill raise a ``SyntaxError``.\\n\\nWhen specifying what module to import you do not have to specify the\\nabsolute name of the module. When a module or package is contained\\nwithin another package it is possible to make a relative import within\\nthe same top package without having to mention the package name. By\\nusing leading dots in the specified module or package after ``from``\\nyou can specify how high to traverse up the current package hierarchy\\nwithout specifying exact names. One leading dot means the current\\npackage where the module making the import exists. Two dots means up\\none package level. Three dots is up two levels, etc. So if you execute\\n``from . import mod`` from a module in the ``pkg`` package then you\\nwill end up importing ``pkg.mod``. If you execute ``from ..subpkg2\\nimport mod`` from within ``pkg.subpkg1`` you will import\\n``pkg.subpkg2.mod``. The specification for relative imports is\\ncontained within **PEP 328**.\\n\\n``importlib.import_module()`` is provided to support applications that\\ndetermine which modules need to be loaded dynamically.\\n\\n\\nFuture statements\\n=================\\n\\nA *future statement* is a directive to the compiler that a particular\\nmodule should be compiled using syntax or semantics that will be\\navailable in a specified future release of Python. The future\\nstatement is intended to ease migration to future versions of Python\\nthat introduce incompatible changes to the language. It allows use of\\nthe new features on a per-module basis before the release in which the\\nfeature becomes standard.\\n\\n future_statement ::= \"from\" \"__future__\" \"import\" feature [\"as\" name]\\n (\",\" feature [\"as\" name])*\\n | \"from\" \"__future__\" \"import\" \"(\" feature [\"as\" name]\\n (\",\" feature [\"as\" name])* [\",\"] \")\"\\n feature ::= identifier\\n name ::= identifier\\n\\nA future statement must appear near the top of the module. The only\\nlines that can appear before a future statement are:\\n\\n* the module docstring (if any),\\n\\n* comments,\\n\\n* blank lines, and\\n\\n* other future statements.\\n\\nThe features recognized by Python 3.0 are ``absolute_import``,\\n``division``, ``generators``, ``unicode_literals``,\\n``print_function``, ``nested_scopes`` and ``with_statement``. They\\nare all redundant because they are always enabled, and only kept for\\nbackwards compatibility.\\n\\nA future statement is recognized and treated specially at compile\\ntime: Changes to the semantics of core constructs are often\\nimplemented by generating different code. It may even be the case\\nthat a new feature introduces new incompatible syntax (such as a new\\nreserved word), in which case the compiler may need to parse the\\nmodule differently. Such decisions cannot be pushed off until\\nruntime.\\n\\nFor any given release, the compiler knows which feature names have\\nbeen defined, and raises a compile-time error if a future statement\\ncontains a feature not known to it.\\n\\nThe direct runtime semantics are the same as for any import statement:\\nthere is a standard module ``__future__``, described later, and it\\nwill be imported in the usual way at the time the future statement is\\nexecuted.\\n\\nThe interesting runtime semantics depend on the specific feature\\nenabled by the future statement.\\n\\nNote that there is nothing special about the statement:\\n\\n import __future__ [as name]\\n\\nThat is not a future statement; it\\'s an ordinary import statement with\\nno special semantics or syntax restrictions.\\n\\nCode compiled by calls to the built-in functions ``exec()`` and\\n``compile()`` that occur in a module ``M`` containing a future\\nstatement will, by default, use the new syntax or semantics associated\\nwith the future statement. This can be controlled by optional\\narguments to ``compile()`` --- see the documentation of that function\\nfor details.\\n\\nA future statement typed at an interactive interpreter prompt will\\ntake effect for the rest of the interpreter session. If an\\ninterpreter is started with the *-i* option, is passed a script name\\nto execute, and the script includes a future statement, it will be in\\neffect in the interactive session started after the script is\\nexecuted.\\n\\nSee also:\\n\\n **PEP 236** - Back to the __future__\\n The original proposal for the __future__ mechanism.\\n',\n'in':'\\nComparisons\\n***********\\n\\nUnlike C, all comparison operations in Python have the same priority,\\nwhich is lower than that of any arithmetic, shifting or bitwise\\noperation. Also unlike C, expressions like ``a < b < c`` have the\\ninterpretation that is conventional in mathematics:\\n\\n comparison ::= or_expr ( comp_operator or_expr )*\\n comp_operator ::= \"<\" | \">\" | \"==\" | \">=\" | \"<=\" | \"!=\"\\n | \"is\" [\"not\"] | [\"not\"] \"in\"\\n\\nComparisons yield boolean values: ``True`` or ``False``.\\n\\nComparisons can be chained arbitrarily, e.g., ``x < y <= z`` is\\nequivalent to ``x < y and y <= z``, except that ``y`` is evaluated\\nonly once (but in both cases ``z`` is not evaluated at all when ``x <\\ny`` is found to be false).\\n\\nFormally, if *a*, *b*, *c*, ..., *y*, *z* are expressions and *op1*,\\n*op2*, ..., *opN* are comparison operators, then ``a op1 b op2 c ... y\\nopN z`` is equivalent to ``a op1 b and b op2 c and ... y opN z``,\\nexcept that each expression is evaluated at most once.\\n\\nNote that ``a op1 b op2 c`` doesn\\'t imply any kind of comparison\\nbetween *a* and *c*, so that, e.g., ``x < y > z`` is perfectly legal\\n(though perhaps not pretty).\\n\\nThe operators ``<``, ``>``, ``==``, ``>=``, ``<=``, and ``!=`` compare\\nthe values of two objects. The objects need not have the same type.\\nIf both are numbers, they are converted to a common type. Otherwise,\\nthe ``==`` and ``!=`` operators *always* consider objects of different\\ntypes to be unequal, while the ``<``, ``>``, ``>=`` and ``<=``\\noperators raise a ``TypeError`` when comparing objects of different\\ntypes that do not implement these operators for the given pair of\\ntypes. You can control comparison behavior of objects of non-built-in\\ntypes by defining rich comparison methods like ``__gt__()``, described\\nin section *Basic customization*.\\n\\nComparison of objects of the same type depends on the type:\\n\\n* Numbers are compared arithmetically.\\n\\n* The values ``float(\\'NaN\\')`` and ``Decimal(\\'NaN\\')`` are special. The\\n are identical to themselves, ``x is x`` but are not equal to\\n themselves, ``x != x``. Additionally, comparing any value to a\\n not-a-number value will return ``False``. For example, both ``3 <\\n float(\\'NaN\\')`` and ``float(\\'NaN\\') < 3`` will return ``False``.\\n\\n* Bytes objects are compared lexicographically using the numeric\\n values of their elements.\\n\\n* Strings are compared lexicographically using the numeric equivalents\\n (the result of the built-in function ``ord()``) of their characters.\\n [3] String and bytes object can\\'t be compared!\\n\\n* Tuples and lists are compared lexicographically using comparison of\\n corresponding elements. This means that to compare equal, each\\n element must compare equal and the two sequences must be of the same\\n type and have the same length.\\n\\n If not equal, the sequences are ordered the same as their first\\n differing elements. For example, ``[1,2,x] <= [1,2,y]`` has the\\n same value as ``x <= y``. If the corresponding element does not\\n exist, the shorter sequence is ordered first (for example, ``[1,2] <\\n [1,2,3]``).\\n\\n* Mappings (dictionaries) compare equal if and only if they have the\\n same ``(key, value)`` pairs. Order comparisons ``(\\'<\\', \\'<=\\', \\'>=\\',\\n \\'>\\')`` raise ``TypeError``.\\n\\n* Sets and frozensets define comparison operators to mean subset and\\n superset tests. Those relations do not define total orderings (the\\n two sets ``{1,2}`` and {2,3} are not equal, nor subsets of one\\n another, nor supersets of one another). Accordingly, sets are not\\n appropriate arguments for functions which depend on total ordering.\\n For example, ``min()``, ``max()``, and ``sorted()`` produce\\n undefined results given a list of sets as inputs.\\n\\n* Most other objects of built-in types compare unequal unless they are\\n the same object; the choice whether one object is considered smaller\\n or larger than another one is made arbitrarily but consistently\\n within one execution of a program.\\n\\nComparison of objects of the differing types depends on whether either\\nof the types provide explicit support for the comparison. Most\\nnumeric types can be compared with one another. When cross-type\\ncomparison is not supported, the comparison method returns\\n``NotImplemented``.\\n\\nThe operators ``in`` and ``not in`` test for membership. ``x in s``\\nevaluates to true if *x* is a member of *s*, and false otherwise. ``x\\nnot in s`` returns the negation of ``x in s``. All built-in sequences\\nand set types support this as well as dictionary, for which ``in``\\ntests whether a the dictionary has a given key. For container types\\nsuch as list, tuple, set, frozenset, dict, or collections.deque, the\\nexpression ``x in y`` is equivalent to ``any(x is e or x == e for e in\\ny)``.\\n\\nFor the string and bytes types, ``x in y`` is true if and only if *x*\\nis a substring of *y*. An equivalent test is ``y.find(x) != -1``.\\nEmpty strings are always considered to be a substring of any other\\nstring, so ``\"\" in \"abc\"`` will return ``True``.\\n\\nFor user-defined classes which define the ``__contains__()`` method,\\n``x in y`` is true if and only if ``y.__contains__(x)`` is true.\\n\\nFor user-defined classes which do not define ``__contains__()`` but do\\ndefine ``__iter__()``, ``x in y`` is true if some value ``z`` with ``x\\n== z`` is produced while iterating over ``y``. If an exception is\\nraised during the iteration, it is as if ``in`` raised that exception.\\n\\nLastly, the old-style iteration protocol is tried: if a class defines\\n``__getitem__()``, ``x in y`` is true if and only if there is a non-\\nnegative integer index *i* such that ``x == y[i]``, and all lower\\ninteger indices do not raise ``IndexError`` exception. (If any other\\nexception is raised, it is as if ``in`` raised that exception).\\n\\nThe operator ``not in`` is defined to have the inverse true value of\\n``in``.\\n\\nThe operators ``is`` and ``is not`` test for object identity: ``x is\\ny`` is true if and only if *x* and *y* are the same object. ``x is\\nnot y`` yields the inverse truth value. [4]\\n',\n'integers':'\\nInteger literals\\n****************\\n\\nInteger literals are described by the following lexical definitions:\\n\\n integer ::= decimalinteger | octinteger | hexinteger | bininteger\\n decimalinteger ::= nonzerodigit digit* | \"0\"+\\n nonzerodigit ::= \"1\"...\"9\"\\n digit ::= \"0\"...\"9\"\\n octinteger ::= \"0\" (\"o\" | \"O\") octdigit+\\n hexinteger ::= \"0\" (\"x\" | \"X\") hexdigit+\\n bininteger ::= \"0\" (\"b\" | \"B\") bindigit+\\n octdigit ::= \"0\"...\"7\"\\n hexdigit ::= digit | \"a\"...\"f\" | \"A\"...\"F\"\\n bindigit ::= \"0\" | \"1\"\\n\\nThere is no limit for the length of integer literals apart from what\\ncan be stored in available memory.\\n\\nNote that leading zeros in a non-zero decimal number are not allowed.\\nThis is for disambiguation with C-style octal literals, which Python\\nused before version 3.0.\\n\\nSome examples of integer literals:\\n\\n 7 2147483647 0o177 0b100110111\\n 3 79228162514264337593543950336 0o377 0x100000000\\n 79228162514264337593543950336 0xdeadbeef\\n',\n'lambda':'\\nLambdas\\n*******\\n\\n lambda_form ::= \"lambda\" [parameter_list]: expression\\n lambda_form_nocond ::= \"lambda\" [parameter_list]: expression_nocond\\n\\nLambda forms (lambda expressions) have the same syntactic position as\\nexpressions. They are a shorthand to create anonymous functions; the\\nexpression ``lambda arguments: expression`` yields a function object.\\nThe unnamed object behaves like a function object defined with\\n\\n def <lambda>(arguments):\\n return expression\\n\\nSee section *Function definitions* for the syntax of parameter lists.\\nNote that functions created with lambda forms cannot contain\\nstatements or annotations.\\n',\n'lists':'\\nList displays\\n*************\\n\\nA list display is a possibly empty series of expressions enclosed in\\nsquare brackets:\\n\\n list_display ::= \"[\" [expression_list | comprehension] \"]\"\\n\\nA list display yields a new list object, the contents being specified\\nby either a list of expressions or a comprehension. When a comma-\\nseparated list of expressions is supplied, its elements are evaluated\\nfrom left to right and placed into the list object in that order.\\nWhen a comprehension is supplied, the list is constructed from the\\nelements resulting from the comprehension.\\n',\n'naming':\"\\nNaming and binding\\n******************\\n\\n*Names* refer to objects. Names are introduced by name binding\\noperations. Each occurrence of a name in the program text refers to\\nthe *binding* of that name established in the innermost function block\\ncontaining the use.\\n\\nA *block* is a piece of Python program text that is executed as a\\nunit. The following are blocks: a module, a function body, and a class\\ndefinition. Each command typed interactively is a block. A script\\nfile (a file given as standard input to the interpreter or specified\\non the interpreter command line the first argument) is a code block.\\nA script command (a command specified on the interpreter command line\\nwith the '**-c**' option) is a code block. The string argument passed\\nto the built-in functions ``eval()`` and ``exec()`` is a code block.\\n\\nA code block is executed in an *execution frame*. A frame contains\\nsome administrative information (used for debugging) and determines\\nwhere and how execution continues after the code block's execution has\\ncompleted.\\n\\nA *scope* defines the visibility of a name within a block. If a local\\nvariable is defined in a block, its scope includes that block. If the\\ndefinition occurs in a function block, the scope extends to any blocks\\ncontained within the defining one, unless a contained block introduces\\na different binding for the name. The scope of names defined in a\\nclass block is limited to the class block; it does not extend to the\\ncode blocks of methods -- this includes comprehensions and generator\\nexpressions since they are implemented using a function scope. This\\nmeans that the following will fail:\\n\\n class A:\\n a = 42\\n b = list(a + i for i in range(10))\\n\\nWhen a name is used in a code block, it is resolved using the nearest\\nenclosing scope. The set of all such scopes visible to a code block\\nis called the block's *environment*.\\n\\nIf a name is bound in a block, it is a local variable of that block,\\nunless declared as ``nonlocal``. If a name is bound at the module\\nlevel, it is a global variable. (The variables of the module code\\nblock are local and global.) If a variable is used in a code block\\nbut not defined there, it is a *free variable*.\\n\\nWhen a name is not found at all, a ``NameError`` exception is raised.\\nIf the name refers to a local variable that has not been bound, a\\n``UnboundLocalError`` exception is raised. ``UnboundLocalError`` is a\\nsubclass of ``NameError``.\\n\\nThe following constructs bind names: formal parameters to functions,\\n``import`` statements, class and function definitions (these bind the\\nclass or function name in the defining block), and targets that are\\nidentifiers if occurring in an assignment, ``for`` loop header, or\\nafter ``as`` in a ``with`` statement or ``except`` clause. The\\n``import`` statement of the form ``from ... import *`` binds all names\\ndefined in the imported module, except those beginning with an\\nunderscore. This form may only be used at the module level.\\n\\nA target occurring in a ``del`` statement is also considered bound for\\nthis purpose (though the actual semantics are to unbind the name).\\n\\nEach assignment or import statement occurs within a block defined by a\\nclass or function definition or at the module level (the top-level\\ncode block).\\n\\nIf a name binding operation occurs anywhere within a code block, all\\nuses of the name within the block are treated as references to the\\ncurrent block. This can lead to errors when a name is used within a\\nblock before it is bound. This rule is subtle. Python lacks\\ndeclarations and allows name binding operations to occur anywhere\\nwithin a code block. The local variables of a code block can be\\ndetermined by scanning the entire text of the block for name binding\\noperations.\\n\\nIf the ``global`` statement occurs within a block, all uses of the\\nname specified in the statement refer to the binding of that name in\\nthe top-level namespace. Names are resolved in the top-level\\nnamespace by searching the global namespace, i.e. the namespace of the\\nmodule containing the code block, and the builtins namespace, the\\nnamespace of the module ``builtins``. The global namespace is\\nsearched first. If the name is not found there, the builtins\\nnamespace is searched. The global statement must precede all uses of\\nthe name.\\n\\nThe builtins namespace associated with the execution of a code block\\nis actually found by looking up the name ``__builtins__`` in its\\nglobal namespace; this should be a dictionary or a module (in the\\nlatter case the module's dictionary is used). By default, when in the\\n``__main__`` module, ``__builtins__`` is the built-in module\\n``builtins``; when in any other module, ``__builtins__`` is an alias\\nfor the dictionary of the ``builtins`` module itself.\\n``__builtins__`` can be set to a user-created dictionary to create a\\nweak form of restricted execution.\\n\\n**CPython implementation detail:** Users should not touch\\n``__builtins__``; it is strictly an implementation detail. Users\\nwanting to override values in the builtins namespace should ``import``\\nthe ``builtins`` module and modify its attributes appropriately.\\n\\nThe namespace for a module is automatically created the first time a\\nmodule is imported. The main module for a script is always called\\n``__main__``.\\n\\nThe ``global`` statement has the same scope as a name binding\\noperation in the same block. If the nearest enclosing scope for a\\nfree variable contains a global statement, the free variable is\\ntreated as a global.\\n\\nA class definition is an executable statement that may use and define\\nnames. These references follow the normal rules for name resolution.\\nThe namespace of the class definition becomes the attribute dictionary\\nof the class. Names defined at the class scope are not visible in\\nmethods.\\n\\n\\nInteraction with dynamic features\\n=================================\\n\\nThere are several cases where Python statements are illegal when used\\nin conjunction with nested scopes that contain free variables.\\n\\nIf a variable is referenced in an enclosing scope, it is illegal to\\ndelete the name. An error will be reported at compile time.\\n\\nIf the wild card form of import --- ``import *`` --- is used in a\\nfunction and the function contains or is a nested block with free\\nvariables, the compiler will raise a ``SyntaxError``.\\n\\nThe ``eval()`` and ``exec()`` functions do not have access to the full\\nenvironment for resolving names. Names may be resolved in the local\\nand global namespaces of the caller. Free variables are not resolved\\nin the nearest enclosing namespace, but in the global namespace. [1]\\nThe ``exec()`` and ``eval()`` functions have optional arguments to\\noverride the global and local namespace. If only one namespace is\\nspecified, it is used for both.\\n\",\n'nonlocal':'\\nThe ``nonlocal`` statement\\n**************************\\n\\n nonlocal_stmt ::= \"nonlocal\" identifier (\",\" identifier)*\\n\\nThe ``nonlocal`` statement causes the listed identifiers to refer to\\npreviously bound variables in the nearest enclosing scope. This is\\nimportant because the default behavior for binding is to search the\\nlocal namespace first. The statement allows encapsulated code to\\nrebind variables outside of the local scope besides the global\\n(module) scope.\\n\\nNames listed in a ``nonlocal`` statement, unlike to those listed in a\\n``global`` statement, must refer to pre-existing bindings in an\\nenclosing scope (the scope in which a new binding should be created\\ncannot be determined unambiguously).\\n\\nNames listed in a ``nonlocal`` statement must not collide with pre-\\nexisting bindings in the local scope.\\n\\nSee also:\\n\\n **PEP 3104** - Access to Names in Outer Scopes\\n The specification for the ``nonlocal`` statement.\\n',\n'numbers':\"\\nNumeric literals\\n****************\\n\\nThere are three types of numeric literals: integers, floating point\\nnumbers, and imaginary numbers. There are no complex literals\\n(complex numbers can be formed by adding a real number and an\\nimaginary number).\\n\\nNote that numeric literals do not include a sign; a phrase like ``-1``\\nis actually an expression composed of the unary operator '``-``' and\\nthe literal ``1``.\\n\",\n'numeric-types':\"\\nEmulating numeric types\\n***********************\\n\\nThe following methods can be defined to emulate numeric objects.\\nMethods corresponding to operations that are not supported by the\\nparticular kind of number implemented (e.g., bitwise operations for\\nnon-integral numbers) should be left undefined.\\n\\nobject.__add__(self, other)\\nobject.__sub__(self, other)\\nobject.__mul__(self, other)\\nobject.__truediv__(self, other)\\nobject.__floordiv__(self, other)\\nobject.__mod__(self, other)\\nobject.__divmod__(self, other)\\nobject.__pow__(self, other[, modulo])\\nobject.__lshift__(self, other)\\nobject.__rshift__(self, other)\\nobject.__and__(self, other)\\nobject.__xor__(self, other)\\nobject.__or__(self, other)\\n\\n These methods are called to implement the binary arithmetic\\n operations (``+``, ``-``, ``*``, ``/``, ``//``, ``%``,\\n ``divmod()``, ``pow()``, ``**``, ``<<``, ``>>``, ``&``, ``^``,\\n ``|``). For instance, to evaluate the expression ``x + y``, where\\n *x* is an instance of a class that has an ``__add__()`` method,\\n ``x.__add__(y)`` is called. The ``__divmod__()`` method should be\\n the equivalent to using ``__floordiv__()`` and ``__mod__()``; it\\n should not be related to ``__truediv__()``. Note that\\n ``__pow__()`` should be defined to accept an optional third\\n argument if the ternary version of the built-in ``pow()`` function\\n is to be supported.\\n\\n If one of those methods does not support the operation with the\\n supplied arguments, it should return ``NotImplemented``.\\n\\nobject.__radd__(self, other)\\nobject.__rsub__(self, other)\\nobject.__rmul__(self, other)\\nobject.__rtruediv__(self, other)\\nobject.__rfloordiv__(self, other)\\nobject.__rmod__(self, other)\\nobject.__rdivmod__(self, other)\\nobject.__rpow__(self, other)\\nobject.__rlshift__(self, other)\\nobject.__rrshift__(self, other)\\nobject.__rand__(self, other)\\nobject.__rxor__(self, other)\\nobject.__ror__(self, other)\\n\\n These methods are called to implement the binary arithmetic\\n operations (``+``, ``-``, ``*``, ``/``, ``//``, ``%``,\\n ``divmod()``, ``pow()``, ``**``, ``<<``, ``>>``, ``&``, ``^``,\\n ``|``) with reflected (swapped) operands. These functions are only\\n called if the left operand does not support the corresponding\\n operation and the operands are of different types. [2] For\\n instance, to evaluate the expression ``x - y``, where *y* is an\\n instance of a class that has an ``__rsub__()`` method,\\n ``y.__rsub__(x)`` is called if ``x.__sub__(y)`` returns\\n *NotImplemented*.\\n\\n Note that ternary ``pow()`` will not try calling ``__rpow__()``\\n (the coercion rules would become too complicated).\\n\\n Note: If the right operand's type is a subclass of the left operand's\\n type and that subclass provides the reflected method for the\\n operation, this method will be called before the left operand's\\n non-reflected method. This behavior allows subclasses to\\n override their ancestors' operations.\\n\\nobject.__iadd__(self, other)\\nobject.__isub__(self, other)\\nobject.__imul__(self, other)\\nobject.__itruediv__(self, other)\\nobject.__ifloordiv__(self, other)\\nobject.__imod__(self, other)\\nobject.__ipow__(self, other[, modulo])\\nobject.__ilshift__(self, other)\\nobject.__irshift__(self, other)\\nobject.__iand__(self, other)\\nobject.__ixor__(self, other)\\nobject.__ior__(self, other)\\n\\n These methods are called to implement the augmented arithmetic\\n assignments (``+=``, ``-=``, ``*=``, ``/=``, ``//=``, ``%=``,\\n ``**=``, ``<<=``, ``>>=``, ``&=``, ``^=``, ``|=``). These methods\\n should attempt to do the operation in-place (modifying *self*) and\\n return the result (which could be, but does not have to be,\\n *self*). If a specific method is not defined, the augmented\\n assignment falls back to the normal methods. For instance, to\\n execute the statement ``x += y``, where *x* is an instance of a\\n class that has an ``__iadd__()`` method, ``x.__iadd__(y)`` is\\n called. If *x* is an instance of a class that does not define a\\n ``__iadd__()`` method, ``x.__add__(y)`` and ``y.__radd__(x)`` are\\n considered, as with the evaluation of ``x + y``.\\n\\nobject.__neg__(self)\\nobject.__pos__(self)\\nobject.__abs__(self)\\nobject.__invert__(self)\\n\\n Called to implement the unary arithmetic operations (``-``, ``+``,\\n ``abs()`` and ``~``).\\n\\nobject.__complex__(self)\\nobject.__int__(self)\\nobject.__float__(self)\\nobject.__round__(self[, n])\\n\\n Called to implement the built-in functions ``complex()``,\\n ``int()``, ``float()`` and ``round()``. Should return a value of\\n the appropriate type.\\n\\nobject.__index__(self)\\n\\n Called to implement ``operator.index()``. Also called whenever\\n Python needs an integer object (such as in slicing, or in the\\n built-in ``bin()``, ``hex()`` and ``oct()`` functions). Must return\\n an integer.\\n\",\n'objects':'\\nObjects, values and types\\n*************************\\n\\n*Objects* are Python\\'s abstraction for data. All data in a Python\\nprogram is represented by objects or by relations between objects. (In\\na sense, and in conformance to Von Neumann\\'s model of a \"stored\\nprogram computer,\" code is also represented by objects.)\\n\\nEvery object has an identity, a type and a value. An object\\'s\\n*identity* never changes once it has been created; you may think of it\\nas the object\\'s address in memory. The \\'``is``\\' operator compares the\\nidentity of two objects; the ``id()`` function returns an integer\\nrepresenting its identity.\\n\\n**CPython implementation detail:** For CPython, ``id(x)`` is the\\nmemory address where ``x`` is stored.\\n\\nAn object\\'s type determines the operations that the object supports\\n(e.g., \"does it have a length?\") and also defines the possible values\\nfor objects of that type. The ``type()`` function returns an object\\'s\\ntype (which is an object itself). Like its identity, an object\\'s\\n*type* is also unchangeable. [1]\\n\\nThe *value* of some objects can change. Objects whose value can\\nchange are said to be *mutable*; objects whose value is unchangeable\\nonce they are created are called *immutable*. (The value of an\\nimmutable container object that contains a reference to a mutable\\nobject can change when the latter\\'s value is changed; however the\\ncontainer is still considered immutable, because the collection of\\nobjects it contains cannot be changed. So, immutability is not\\nstrictly the same as having an unchangeable value, it is more subtle.)\\nAn object\\'s mutability is determined by its type; for instance,\\nnumbers, strings and tuples are immutable, while dictionaries and\\nlists are mutable.\\n\\nObjects are never explicitly destroyed; however, when they become\\nunreachable they may be garbage-collected. An implementation is\\nallowed to postpone garbage collection or omit it altogether --- it is\\na matter of implementation quality how garbage collection is\\nimplemented, as long as no objects are collected that are still\\nreachable.\\n\\n**CPython implementation detail:** CPython currently uses a reference-\\ncounting scheme with (optional) delayed detection of cyclically linked\\ngarbage, which collects most objects as soon as they become\\nunreachable, but is not guaranteed to collect garbage containing\\ncircular references. See the documentation of the ``gc`` module for\\ninformation on controlling the collection of cyclic garbage. Other\\nimplementations act differently and CPython may change. Do not depend\\non immediate finalization of objects when they become unreachable (ex:\\nalways close files).\\n\\nNote that the use of the implementation\\'s tracing or debugging\\nfacilities may keep objects alive that would normally be collectable.\\nAlso note that catching an exception with a \\'``try``...``except``\\'\\nstatement may keep objects alive.\\n\\nSome objects contain references to \"external\" resources such as open\\nfiles or windows. It is understood that these resources are freed\\nwhen the object is garbage-collected, but since garbage collection is\\nnot guaranteed to happen, such objects also provide an explicit way to\\nrelease the external resource, usually a ``close()`` method. Programs\\nare strongly recommended to explicitly close such objects. The\\n\\'``try``...``finally``\\' statement and the \\'``with``\\' statement provide\\nconvenient ways to do this.\\n\\nSome objects contain references to other objects; these are called\\n*containers*. Examples of containers are tuples, lists and\\ndictionaries. The references are part of a container\\'s value. In\\nmost cases, when we talk about the value of a container, we imply the\\nvalues, not the identities of the contained objects; however, when we\\ntalk about the mutability of a container, only the identities of the\\nimmediately contained objects are implied. So, if an immutable\\ncontainer (like a tuple) contains a reference to a mutable object, its\\nvalue changes if that mutable object is changed.\\n\\nTypes affect almost all aspects of object behavior. Even the\\nimportance of object identity is affected in some sense: for immutable\\ntypes, operations that compute new values may actually return a\\nreference to any existing object with the same type and value, while\\nfor mutable objects this is not allowed. E.g., after ``a = 1; b =\\n1``, ``a`` and ``b`` may or may not refer to the same object with the\\nvalue one, depending on the implementation, but after ``c = []; d =\\n[]``, ``c`` and ``d`` are guaranteed to refer to two different,\\nunique, newly created empty lists. (Note that ``c = d = []`` assigns\\nthe same object to both ``c`` and ``d``.)\\n',\n'operator-summary':'\\nOperator precedence\\n*******************\\n\\nThe following table summarizes the operator precedences in Python,\\nfrom lowest precedence (least binding) to highest precedence (most\\nbinding). Operators in the same box have the same precedence. Unless\\nthe syntax is explicitly given, operators are binary. Operators in\\nthe same box group left to right (except for comparisons, including\\ntests, which all have the same precedence and chain from left to right\\n--- see section *Comparisons* --- and exponentiation, which groups\\nfrom right to left).\\n\\n+-------------------------------------------------+---------------------------------------+\\n| Operator | Description |\\n+=================================================+=======================================+\\n| ``lambda`` | Lambda expression |\\n+-------------------------------------------------+---------------------------------------+\\n| ``if`` -- ``else`` | Conditional expression |\\n+-------------------------------------------------+---------------------------------------+\\n| ``or`` | Boolean OR |\\n+-------------------------------------------------+---------------------------------------+\\n| ``and`` | Boolean AND |\\n+-------------------------------------------------+---------------------------------------+\\n| ``not`` ``x`` | Boolean NOT |\\n+-------------------------------------------------+---------------------------------------+\\n| ``in``, ``not in``, ``is``, ``is not``, ``<``, | Comparisons, including membership |\\n| ``<=``, ``>``, ``>=``, ``!=``, ``==`` | tests and identity tests, |\\n+-------------------------------------------------+---------------------------------------+\\n| ``|`` | Bitwise OR |\\n+-------------------------------------------------+---------------------------------------+\\n| ``^`` | Bitwise XOR |\\n+-------------------------------------------------+---------------------------------------+\\n| ``&`` | Bitwise AND |\\n+-------------------------------------------------+---------------------------------------+\\n| ``<<``, ``>>`` | Shifts |\\n+-------------------------------------------------+---------------------------------------+\\n| ``+``, ``-`` | Addition and subtraction |\\n+-------------------------------------------------+---------------------------------------+\\n| ``*``, ``/``, ``//``, ``%`` | Multiplication, division, remainder |\\n| | [5] |\\n+-------------------------------------------------+---------------------------------------+\\n| ``+x``, ``-x``, ``~x`` | Positive, negative, bitwise NOT |\\n+-------------------------------------------------+---------------------------------------+\\n| ``**`` | Exponentiation [6] |\\n+-------------------------------------------------+---------------------------------------+\\n| ``x[index]``, ``x[index:index]``, | Subscription, slicing, call, |\\n| ``x(arguments...)``, ``x.attribute`` | attribute reference |\\n+-------------------------------------------------+---------------------------------------+\\n| ``(expressions...)``, ``[expressions...]``, | Binding or tuple display, list |\\n| ``{key: value...}``, ``{expressions...}`` | display, dictionary display, set |\\n| | display |\\n+-------------------------------------------------+---------------------------------------+\\n\\n-[ Footnotes ]-\\n\\n[1] While ``abs(x%y) < abs(y)`` is true mathematically, for floats it\\n may not be true numerically due to roundoff. For example, and\\n assuming a platform on which a Python float is an IEEE 754 double-\\n precision number, in order that ``-1e-100 % 1e100`` have the same\\n sign as ``1e100``, the computed result is ``-1e-100 + 1e100``,\\n which is numerically exactly equal to ``1e100``. The function\\n ``math.fmod()`` returns a result whose sign matches the sign of\\n the first argument instead, and so returns ``-1e-100`` in this\\n case. Which approach is more appropriate depends on the\\n application.\\n\\n[2] If x is very close to an exact integer multiple of y, it\\'s\\n possible for ``x//y`` to be one larger than ``(x-x%y)//y`` due to\\n rounding. In such cases, Python returns the latter result, in\\n order to preserve that ``divmod(x,y)[0] * y + x % y`` be very\\n close to ``x``.\\n\\n[3] While comparisons between strings make sense at the byte level,\\n they may be counter-intuitive to users. For example, the strings\\n ``\"\\\\u00C7\"`` and ``\"\\\\u0327\\\\u0043\"`` compare differently, even\\n though they both represent the same unicode character (LATIN\\n CAPITAL LETTER C WITH CEDILLA). To compare strings in a human\\n recognizable way, compare using ``unicodedata.normalize()``.\\n\\n[4] Due to automatic garbage-collection, free lists, and the dynamic\\n nature of descriptors, you may notice seemingly unusual behaviour\\n in certain uses of the ``is`` operator, like those involving\\n comparisons between instance methods, or constants. Check their\\n documentation for more info.\\n\\n[5] The ``%`` operator is also used for string formatting; the same\\n precedence applies.\\n\\n[6] The power operator ``**`` binds less tightly than an arithmetic or\\n bitwise unary operator on its right, that is, ``2**-1`` is\\n ``0.5``.\\n',\n'pass':'\\nThe ``pass`` statement\\n**********************\\n\\n pass_stmt ::= \"pass\"\\n\\n``pass`` is a null operation --- when it is executed, nothing happens.\\nIt is useful as a placeholder when a statement is required\\nsyntactically, but no code needs to be executed, for example:\\n\\n def f(arg): pass # a function that does nothing (yet)\\n\\n class C: pass # a class with no methods (yet)\\n',\n'power':'\\nThe power operator\\n******************\\n\\nThe power operator binds more tightly than unary operators on its\\nleft; it binds less tightly than unary operators on its right. The\\nsyntax is:\\n\\n power ::= primary [\"**\" u_expr]\\n\\nThus, in an unparenthesized sequence of power and unary operators, the\\noperators are evaluated from right to left (this does not constrain\\nthe evaluation order for the operands): ``-1**2`` results in ``-1``.\\n\\nThe power operator has the same semantics as the built-in ``pow()``\\nfunction, when called with two arguments: it yields its left argument\\nraised to the power of its right argument. The numeric arguments are\\nfirst converted to a common type, and the result is of that type.\\n\\nFor int operands, the result has the same type as the operands unless\\nthe second argument is negative; in that case, all arguments are\\nconverted to float and a float result is delivered. For example,\\n``10**2`` returns ``100``, but ``10**-2`` returns ``0.01``.\\n\\nRaising ``0.0`` to a negative power results in a\\n``ZeroDivisionError``. Raising a negative number to a fractional power\\nresults in a ``complex`` number. (In earlier versions it raised a\\n``ValueError``.)\\n',\n'raise':'\\nThe ``raise`` statement\\n***********************\\n\\n raise_stmt ::= \"raise\" [expression [\"from\" expression]]\\n\\nIf no expressions are present, ``raise`` re-raises the last exception\\nthat was active in the current scope. If no exception is active in\\nthe current scope, a ``RuntimeError`` exception is raised indicating\\nthat this is an error.\\n\\nOtherwise, ``raise`` evaluates the first expression as the exception\\nobject. It must be either a subclass or an instance of\\n``BaseException``. If it is a class, the exception instance will be\\nobtained when needed by instantiating the class with no arguments.\\n\\nThe *type* of the exception is the exception instance\\'s class, the\\n*value* is the instance itself.\\n\\nA traceback object is normally created automatically when an exception\\nis raised and attached to it as the ``__traceback__`` attribute, which\\nis writable. You can create an exception and set your own traceback in\\none step using the ``with_traceback()`` exception method (which\\nreturns the same exception instance, with its traceback set to its\\nargument), like so:\\n\\n raise Exception(\"foo occurred\").with_traceback(tracebackobj)\\n\\nThe ``from`` clause is used for exception chaining: if given, the\\nsecond *expression* must be another exception class or instance, which\\nwill then be attached to the raised exception as the ``__cause__``\\nattribute (which is writable). If the raised exception is not\\nhandled, both exceptions will be printed:\\n\\n >>> try:\\n ... print(1 / 0)\\n ... except Exception as exc:\\n ... raise RuntimeError(\"Something bad happened\") from exc\\n ...\\n Traceback (most recent call last):\\n File \"<stdin>\", line 2, in <module>\\n ZeroDivisionError: int division or modulo by zero\\n\\n The above exception was the direct cause of the following exception:\\n\\n Traceback (most recent call last):\\n File \"<stdin>\", line 4, in <module>\\n RuntimeError: Something bad happened\\n\\nA similar mechanism works implicitly if an exception is raised inside\\nan exception handler: the previous exception is then attached as the\\nnew exception\\'s ``__context__`` attribute:\\n\\n >>> try:\\n ... print(1 / 0)\\n ... except:\\n ... raise RuntimeError(\"Something bad happened\")\\n ...\\n Traceback (most recent call last):\\n File \"<stdin>\", line 2, in <module>\\n ZeroDivisionError: int division or modulo by zero\\n\\n During handling of the above exception, another exception occurred:\\n\\n Traceback (most recent call last):\\n File \"<stdin>\", line 4, in <module>\\n RuntimeError: Something bad happened\\n\\nAdditional information on exceptions can be found in section\\n*Exceptions*, and information about handling exceptions is in section\\n*The try statement*.\\n',\n'return':'\\nThe ``return`` statement\\n************************\\n\\n return_stmt ::= \"return\" [expression_list]\\n\\n``return`` may only occur syntactically nested in a function\\ndefinition, not within a nested class definition.\\n\\nIf an expression list is present, it is evaluated, else ``None`` is\\nsubstituted.\\n\\n``return`` leaves the current function call with the expression list\\n(or ``None``) as return value.\\n\\nWhen ``return`` passes control out of a ``try`` statement with a\\n``finally`` clause, that ``finally`` clause is executed before really\\nleaving the function.\\n\\nIn a generator function, the ``return`` statement indicates that the\\ngenerator is done and will cause ``StopIteration`` to be raised. The\\nreturned value (if any) is used as an argument to construct\\n``StopIteration`` and becomes the ``StopIteration.value`` attribute.\\n',\n'sequence-types':\"\\nEmulating container types\\n*************************\\n\\nThe following methods can be defined to implement container objects.\\nContainers usually are sequences (such as lists or tuples) or mappings\\n(like dictionaries), but can represent other containers as well. The\\nfirst set of methods is used either to emulate a sequence or to\\nemulate a mapping; the difference is that for a sequence, the\\nallowable keys should be the integers *k* for which ``0 <= k < N``\\nwhere *N* is the length of the sequence, or slice objects, which\\ndefine a range of items. It is also recommended that mappings provide\\nthe methods ``keys()``, ``values()``, ``items()``, ``get()``,\\n``clear()``, ``setdefault()``, ``pop()``, ``popitem()``, ``copy()``,\\nand ``update()`` behaving similar to those for Python's standard\\ndictionary objects. The ``collections`` module provides a\\n``MutableMapping`` abstract base class to help create those methods\\nfrom a base set of ``__getitem__()``, ``__setitem__()``,\\n``__delitem__()``, and ``keys()``. Mutable sequences should provide\\nmethods ``append()``, ``count()``, ``index()``, ``extend()``,\\n``insert()``, ``pop()``, ``remove()``, ``reverse()`` and ``sort()``,\\nlike Python standard list objects. Finally, sequence types should\\nimplement addition (meaning concatenation) and multiplication (meaning\\nrepetition) by defining the methods ``__add__()``, ``__radd__()``,\\n``__iadd__()``, ``__mul__()``, ``__rmul__()`` and ``__imul__()``\\ndescribed below; they should not define other numerical operators. It\\nis recommended that both mappings and sequences implement the\\n``__contains__()`` method to allow efficient use of the ``in``\\noperator; for mappings, ``in`` should search the mapping's keys; for\\nsequences, it should search through the values. It is further\\nrecommended that both mappings and sequences implement the\\n``__iter__()`` method to allow efficient iteration through the\\ncontainer; for mappings, ``__iter__()`` should be the same as\\n``keys()``; for sequences, it should iterate through the values.\\n\\nobject.__len__(self)\\n\\n Called to implement the built-in function ``len()``. Should return\\n the length of the object, an integer ``>=`` 0. Also, an object\\n that doesn't define a ``__bool__()`` method and whose ``__len__()``\\n method returns zero is considered to be false in a Boolean context.\\n\\nNote: Slicing is done exclusively with the following three methods. A\\n call like\\n\\n a[1:2] = b\\n\\n is translated to\\n\\n a[slice(1, 2, None)] = b\\n\\n and so forth. Missing slice items are always filled in with\\n ``None``.\\n\\nobject.__getitem__(self, key)\\n\\n Called to implement evaluation of ``self[key]``. For sequence\\n types, the accepted keys should be integers and slice objects.\\n Note that the special interpretation of negative indexes (if the\\n class wishes to emulate a sequence type) is up to the\\n ``__getitem__()`` method. If *key* is of an inappropriate type,\\n ``TypeError`` may be raised; if of a value outside the set of\\n indexes for the sequence (after any special interpretation of\\n negative values), ``IndexError`` should be raised. For mapping\\n types, if *key* is missing (not in the container), ``KeyError``\\n should be raised.\\n\\n Note: ``for`` loops expect that an ``IndexError`` will be raised for\\n illegal indexes to allow proper detection of the end of the\\n sequence.\\n\\nobject.__setitem__(self, key, value)\\n\\n Called to implement assignment to ``self[key]``. Same note as for\\n ``__getitem__()``. This should only be implemented for mappings if\\n the objects support changes to the values for keys, or if new keys\\n can be added, or for sequences if elements can be replaced. The\\n same exceptions should be raised for improper *key* values as for\\n the ``__getitem__()`` method.\\n\\nobject.__delitem__(self, key)\\n\\n Called to implement deletion of ``self[key]``. Same note as for\\n ``__getitem__()``. This should only be implemented for mappings if\\n the objects support removal of keys, or for sequences if elements\\n can be removed from the sequence. The same exceptions should be\\n raised for improper *key* values as for the ``__getitem__()``\\n method.\\n\\nobject.__iter__(self)\\n\\n This method is called when an iterator is required for a container.\\n This method should return a new iterator object that can iterate\\n over all the objects in the container. For mappings, it should\\n iterate over the keys of the container, and should also be made\\n available as the method ``keys()``.\\n\\n Iterator objects also need to implement this method; they are\\n required to return themselves. For more information on iterator\\n objects, see *Iterator Types*.\\n\\nobject.__reversed__(self)\\n\\n Called (if present) by the ``reversed()`` built-in to implement\\n reverse iteration. It should return a new iterator object that\\n iterates over all the objects in the container in reverse order.\\n\\n If the ``__reversed__()`` method is not provided, the\\n ``reversed()`` built-in will fall back to using the sequence\\n protocol (``__len__()`` and ``__getitem__()``). Objects that\\n support the sequence protocol should only provide\\n ``__reversed__()`` if they can provide an implementation that is\\n more efficient than the one provided by ``reversed()``.\\n\\nThe membership test operators (``in`` and ``not in``) are normally\\nimplemented as an iteration through a sequence. However, container\\nobjects can supply the following special method with a more efficient\\nimplementation, which also does not require the object be a sequence.\\n\\nobject.__contains__(self, item)\\n\\n Called to implement membership test operators. Should return true\\n if *item* is in *self*, false otherwise. For mapping objects, this\\n should consider the keys of the mapping rather than the values or\\n the key-item pairs.\\n\\n For objects that don't define ``__contains__()``, the membership\\n test first tries iteration via ``__iter__()``, then the old\\n sequence iteration protocol via ``__getitem__()``, see *this\\n section in the language reference*.\\n\",\n'shifting':'\\nShifting operations\\n*******************\\n\\nThe shifting operations have lower priority than the arithmetic\\noperations:\\n\\n shift_expr ::= a_expr | shift_expr ( \"<<\" | \">>\" ) a_expr\\n\\nThese operators accept integers as arguments. They shift the first\\nargument to the left or right by the number of bits given by the\\nsecond argument.\\n\\nA right shift by *n* bits is defined as division by ``pow(2,n)``. A\\nleft shift by *n* bits is defined as multiplication with ``pow(2,n)``.\\n\\nNote: In the current implementation, the right-hand operand is required to\\n be at most ``sys.maxsize``. If the right-hand operand is larger\\n than ``sys.maxsize`` an ``OverflowError`` exception is raised.\\n',\n'slicings':'\\nSlicings\\n********\\n\\nA slicing selects a range of items in a sequence object (e.g., a\\nstring, tuple or list). Slicings may be used as expressions or as\\ntargets in assignment or ``del`` statements. The syntax for a\\nslicing:\\n\\n slicing ::= primary \"[\" slice_list \"]\"\\n slice_list ::= slice_item (\",\" slice_item)* [\",\"]\\n slice_item ::= expression | proper_slice\\n proper_slice ::= [lower_bound] \":\" [upper_bound] [ \":\" [stride] ]\\n lower_bound ::= expression\\n upper_bound ::= expression\\n stride ::= expression\\n\\nThere is ambiguity in the formal syntax here: anything that looks like\\nan expression list also looks like a slice list, so any subscription\\ncan be interpreted as a slicing. Rather than further complicating the\\nsyntax, this is disambiguated by defining that in this case the\\ninterpretation as a subscription takes priority over the\\ninterpretation as a slicing (this is the case if the slice list\\ncontains no proper slice).\\n\\nThe semantics for a slicing are as follows. The primary must evaluate\\nto a mapping object, and it is indexed (using the same\\n``__getitem__()`` method as normal subscription) with a key that is\\nconstructed from the slice list, as follows. If the slice list\\ncontains at least one comma, the key is a tuple containing the\\nconversion of the slice items; otherwise, the conversion of the lone\\nslice item is the key. The conversion of a slice item that is an\\nexpression is that expression. The conversion of a proper slice is a\\nslice object (see section *The standard type hierarchy*) whose\\n``start``, ``stop`` and ``step`` attributes are the values of the\\nexpressions given as lower bound, upper bound and stride,\\nrespectively, substituting ``None`` for missing expressions.\\n',\n'specialattrs':'\\nSpecial Attributes\\n******************\\n\\nThe implementation adds a few special read-only attributes to several\\nobject types, where they are relevant. Some of these are not reported\\nby the ``dir()`` built-in function.\\n\\nobject.__dict__\\n\\n A dictionary or other mapping object used to store an object\\'s\\n (writable) attributes.\\n\\ninstance.__class__\\n\\n The class to which a class instance belongs.\\n\\nclass.__bases__\\n\\n The tuple of base classes of a class object.\\n\\nclass.__name__\\n\\n The name of the class or type.\\n\\nclass.__qualname__\\n\\n The *qualified name* of the class or type.\\n\\n New in version 3.3.\\n\\nclass.__mro__\\n\\n This attribute is a tuple of classes that are considered when\\n looking for base classes during method resolution.\\n\\nclass.mro()\\n\\n This method can be overridden by a metaclass to customize the\\n method resolution order for its instances. It is called at class\\n instantiation, and its result is stored in ``__mro__``.\\n\\nclass.__subclasses__()\\n\\n Each class keeps a list of weak references to its immediate\\n subclasses. This method returns a list of all those references\\n still alive. Example:\\n\\n >>> int.__subclasses__()\\n [<class \\'bool\\'>]\\n\\n-[ Footnotes ]-\\n\\n[1] Additional information on these special methods may be found in\\n the Python Reference Manual (*Basic customization*).\\n\\n[2] As a consequence, the list ``[1, 2]`` is considered equal to\\n ``[1.0, 2.0]``, and similarly for tuples.\\n\\n[3] They must have since the parser can\\'t tell the type of the\\n operands.\\n\\n[4] Cased characters are those with general category property being\\n one of \"Lu\" (Letter, uppercase), \"Ll\" (Letter, lowercase), or \"Lt\"\\n (Letter, titlecase).\\n\\n[5] To format only a tuple you should therefore provide a singleton\\n tuple whose only element is the tuple to be formatted.\\n',\n'specialnames':'\\nSpecial method names\\n********************\\n\\nA class can implement certain operations that are invoked by special\\nsyntax (such as arithmetic operations or subscripting and slicing) by\\ndefining methods with special names. This is Python\\'s approach to\\n*operator overloading*, allowing classes to define their own behavior\\nwith respect to language operators. For instance, if a class defines\\na method named ``__getitem__()``, and ``x`` is an instance of this\\nclass, then ``x[i]`` is roughly equivalent to ``type(x).__getitem__(x,\\ni)``. Except where mentioned, attempts to execute an operation raise\\nan exception when no appropriate method is defined (typically\\n``AttributeError`` or ``TypeError``).\\n\\nWhen implementing a class that emulates any built-in type, it is\\nimportant that the emulation only be implemented to the degree that it\\nmakes sense for the object being modelled. For example, some\\nsequences may work well with retrieval of individual elements, but\\nextracting a slice may not make sense. (One example of this is the\\n``NodeList`` interface in the W3C\\'s Document Object Model.)\\n\\n\\nBasic customization\\n===================\\n\\nobject.__new__(cls[, ...])\\n\\n Called to create a new instance of class *cls*. ``__new__()`` is a\\n static method (special-cased so you need not declare it as such)\\n that takes the class of which an instance was requested as its\\n first argument. The remaining arguments are those passed to the\\n object constructor expression (the call to the class). The return\\n value of ``__new__()`` should be the new object instance (usually\\n an instance of *cls*).\\n\\n Typical implementations create a new instance of the class by\\n invoking the superclass\\'s ``__new__()`` method using\\n ``super(currentclass, cls).__new__(cls[, ...])`` with appropriate\\n arguments and then modifying the newly-created instance as\\n necessary before returning it.\\n\\n If ``__new__()`` returns an instance of *cls*, then the new\\n instance\\'s ``__init__()`` method will be invoked like\\n ``__init__(self[, ...])``, where *self* is the new instance and the\\n remaining arguments are the same as were passed to ``__new__()``.\\n\\n If ``__new__()`` does not return an instance of *cls*, then the new\\n instance\\'s ``__init__()`` method will not be invoked.\\n\\n ``__new__()`` is intended mainly to allow subclasses of immutable\\n types (like int, str, or tuple) to customize instance creation. It\\n is also commonly overridden in custom metaclasses in order to\\n customize class creation.\\n\\nobject.__init__(self[, ...])\\n\\n Called when the instance is created. The arguments are those\\n passed to the class constructor expression. If a base class has an\\n ``__init__()`` method, the derived class\\'s ``__init__()`` method,\\n if any, must explicitly call it to ensure proper initialization of\\n the base class part of the instance; for example:\\n ``BaseClass.__init__(self, [args...])``. As a special constraint\\n on constructors, no value may be returned; doing so will cause a\\n ``TypeError`` to be raised at runtime.\\n\\nobject.__del__(self)\\n\\n Called when the instance is about to be destroyed. This is also\\n called a destructor. If a base class has a ``__del__()`` method,\\n the derived class\\'s ``__del__()`` method, if any, must explicitly\\n call it to ensure proper deletion of the base class part of the\\n instance. Note that it is possible (though not recommended!) for\\n the ``__del__()`` method to postpone destruction of the instance by\\n creating a new reference to it. It may then be called at a later\\n time when this new reference is deleted. It is not guaranteed that\\n ``__del__()`` methods are called for objects that still exist when\\n the interpreter exits.\\n\\n Note: ``del x`` doesn\\'t directly call ``x.__del__()`` --- the former\\n decrements the reference count for ``x`` by one, and the latter\\n is only called when ``x``\\'s reference count reaches zero. Some\\n common situations that may prevent the reference count of an\\n object from going to zero include: circular references between\\n objects (e.g., a doubly-linked list or a tree data structure with\\n parent and child pointers); a reference to the object on the\\n stack frame of a function that caught an exception (the traceback\\n stored in ``sys.exc_info()[2]`` keeps the stack frame alive); or\\n a reference to the object on the stack frame that raised an\\n unhandled exception in interactive mode (the traceback stored in\\n ``sys.last_traceback`` keeps the stack frame alive). The first\\n situation can only be remedied by explicitly breaking the cycles;\\n the latter two situations can be resolved by storing ``None`` in\\n ``sys.last_traceback``. Circular references which are garbage are\\n detected when the option cycle detector is enabled (it\\'s on by\\n default), but can only be cleaned up if there are no Python-\\n level ``__del__()`` methods involved. Refer to the documentation\\n for the ``gc`` module for more information about how\\n ``__del__()`` methods are handled by the cycle detector,\\n particularly the description of the ``garbage`` value.\\n\\n Warning: Due to the precarious circumstances under which ``__del__()``\\n methods are invoked, exceptions that occur during their execution\\n are ignored, and a warning is printed to ``sys.stderr`` instead.\\n Also, when ``__del__()`` is invoked in response to a module being\\n deleted (e.g., when execution of the program is done), other\\n globals referenced by the ``__del__()`` method may already have\\n been deleted or in the process of being torn down (e.g. the\\n import machinery shutting down). For this reason, ``__del__()``\\n methods should do the absolute minimum needed to maintain\\n external invariants. Starting with version 1.5, Python\\n guarantees that globals whose name begins with a single\\n underscore are deleted from their module before other globals are\\n deleted; if no other references to such globals exist, this may\\n help in assuring that imported modules are still available at the\\n time when the ``__del__()`` method is called.\\n\\nobject.__repr__(self)\\n\\n Called by the ``repr()`` built-in function to compute the\\n \"official\" string representation of an object. If at all possible,\\n this should look like a valid Python expression that could be used\\n to recreate an object with the same value (given an appropriate\\n environment). If this is not possible, a string of the form\\n ``<...some useful description...>`` should be returned. The return\\n value must be a string object. If a class defines ``__repr__()``\\n but not ``__str__()``, then ``__repr__()`` is also used when an\\n \"informal\" string representation of instances of that class is\\n required.\\n\\n This is typically used for debugging, so it is important that the\\n representation is information-rich and unambiguous.\\n\\nobject.__str__(self)\\n\\n Called by ``str(object)`` and the built-in functions ``format()``\\n and ``print()`` to compute the \"informal\" or nicely printable\\n string representation of an object. The return value must be a\\n *string* object.\\n\\n This method differs from ``object.__repr__()`` in that there is no\\n expectation that ``__str__()`` return a valid Python expression: a\\n more convenient or concise representation can be used.\\n\\n The default implementation defined by the built-in type ``object``\\n calls ``object.__repr__()``.\\n\\nobject.__bytes__(self)\\n\\n Called by ``bytes()`` to compute a byte-string representation of an\\n object. This should return a ``bytes`` object.\\n\\nobject.__format__(self, format_spec)\\n\\n Called by the ``format()`` built-in function (and by extension, the\\n ``str.format()`` method of class ``str``) to produce a \"formatted\"\\n string representation of an object. The ``format_spec`` argument is\\n a string that contains a description of the formatting options\\n desired. The interpretation of the ``format_spec`` argument is up\\n to the type implementing ``__format__()``, however most classes\\n will either delegate formatting to one of the built-in types, or\\n use a similar formatting option syntax.\\n\\n See *Format Specification Mini-Language* for a description of the\\n standard formatting syntax.\\n\\n The return value must be a string object.\\n\\nobject.__lt__(self, other)\\nobject.__le__(self, other)\\nobject.__eq__(self, other)\\nobject.__ne__(self, other)\\nobject.__gt__(self, other)\\nobject.__ge__(self, other)\\n\\n These are the so-called \"rich comparison\" methods. The\\n correspondence between operator symbols and method names is as\\n follows: ``x<y`` calls ``x.__lt__(y)``, ``x<=y`` calls\\n ``x.__le__(y)``, ``x==y`` calls ``x.__eq__(y)``, ``x!=y`` calls\\n ``x.__ne__(y)``, ``x>y`` calls ``x.__gt__(y)``, and ``x>=y`` calls\\n ``x.__ge__(y)``.\\n\\n A rich comparison method may return the singleton\\n ``NotImplemented`` if it does not implement the operation for a\\n given pair of arguments. By convention, ``False`` and ``True`` are\\n returned for a successful comparison. However, these methods can\\n return any value, so if the comparison operator is used in a\\n Boolean context (e.g., in the condition of an ``if`` statement),\\n Python will call ``bool()`` on the value to determine if the result\\n is true or false.\\n\\n There are no implied relationships among the comparison operators.\\n The truth of ``x==y`` does not imply that ``x!=y`` is false.\\n Accordingly, when defining ``__eq__()``, one should also define\\n ``__ne__()`` so that the operators will behave as expected. See\\n the paragraph on ``__hash__()`` for some important notes on\\n creating *hashable* objects which support custom comparison\\n operations and are usable as dictionary keys.\\n\\n There are no swapped-argument versions of these methods (to be used\\n when the left argument does not support the operation but the right\\n argument does); rather, ``__lt__()`` and ``__gt__()`` are each\\n other\\'s reflection, ``__le__()`` and ``__ge__()`` are each other\\'s\\n reflection, and ``__eq__()`` and ``__ne__()`` are their own\\n reflection.\\n\\n Arguments to rich comparison methods are never coerced.\\n\\n To automatically generate ordering operations from a single root\\n operation, see ``functools.total_ordering()``.\\n\\nobject.__hash__(self)\\n\\n Called by built-in function ``hash()`` and for operations on\\n members of hashed collections including ``set``, ``frozenset``, and\\n ``dict``. ``__hash__()`` should return an integer. The only\\n required property is that objects which compare equal have the same\\n hash value; it is advised to somehow mix together (e.g. using\\n exclusive or) the hash values for the components of the object that\\n also play a part in comparison of objects.\\n\\n If a class does not define an ``__eq__()`` method it should not\\n define a ``__hash__()`` operation either; if it defines\\n ``__eq__()`` but not ``__hash__()``, its instances will not be\\n usable as items in hashable collections. If a class defines\\n mutable objects and implements an ``__eq__()`` method, it should\\n not implement ``__hash__()``, since the implementation of hashable\\n collections requires that a key\\'s hash value is immutable (if the\\n object\\'s hash value changes, it will be in the wrong hash bucket).\\n\\n User-defined classes have ``__eq__()`` and ``__hash__()`` methods\\n by default; with them, all objects compare unequal (except with\\n themselves) and ``x.__hash__()`` returns an appropriate value such\\n that ``x == y`` implies both that ``x is y`` and ``hash(x) ==\\n hash(y)``.\\n\\n A class that overrides ``__eq__()`` and does not define\\n ``__hash__()`` will have its ``__hash__()`` implicitly set to\\n ``None``. When the ``__hash__()`` method of a class is ``None``,\\n instances of the class will raise an appropriate ``TypeError`` when\\n a program attempts to retrieve their hash value, and will also be\\n correctly identified as unhashable when checking ``isinstance(obj,\\n collections.Hashable``).\\n\\n If a class that overrides ``__eq__()`` needs to retain the\\n implementation of ``__hash__()`` from a parent class, the\\n interpreter must be told this explicitly by setting ``__hash__ =\\n <ParentClass>.__hash__``.\\n\\n If a class that does not override ``__eq__()`` wishes to suppress\\n hash support, it should include ``__hash__ = None`` in the class\\n definition. A class which defines its own ``__hash__()`` that\\n explicitly raises a ``TypeError`` would be incorrectly identified\\n as hashable by an ``isinstance(obj, collections.Hashable)`` call.\\n\\n Note: By default, the ``__hash__()`` values of str, bytes and datetime\\n objects are \"salted\" with an unpredictable random value.\\n Although they remain constant within an individual Python\\n process, they are not predictable between repeated invocations of\\n Python.This is intended to provide protection against a denial-\\n of-service caused by carefully-chosen inputs that exploit the\\n worst case performance of a dict insertion, O(n^2) complexity.\\n See http://www.ocert.org/advisories/ocert-2011-003.html for\\n details.Changing hash values affects the iteration order of\\n dicts, sets and other mappings. Python has never made guarantees\\n about this ordering (and it typically varies between 32-bit and\\n 64-bit builds).See also ``PYTHONHASHSEED``.\\n\\n Changed in version 3.3: Hash randomization is enabled by default.\\n\\nobject.__bool__(self)\\n\\n Called to implement truth value testing and the built-in operation\\n ``bool()``; should return ``False`` or ``True``. When this method\\n is not defined, ``__len__()`` is called, if it is defined, and the\\n object is considered true if its result is nonzero. If a class\\n defines neither ``__len__()`` nor ``__bool__()``, all its instances\\n are considered true.\\n\\n\\nCustomizing attribute access\\n============================\\n\\nThe following methods can be defined to customize the meaning of\\nattribute access (use of, assignment to, or deletion of ``x.name``)\\nfor class instances.\\n\\nobject.__getattr__(self, name)\\n\\n Called when an attribute lookup has not found the attribute in the\\n usual places (i.e. it is not an instance attribute nor is it found\\n in the class tree for ``self``). ``name`` is the attribute name.\\n This method should return the (computed) attribute value or raise\\n an ``AttributeError`` exception.\\n\\n Note that if the attribute is found through the normal mechanism,\\n ``__getattr__()`` is not called. (This is an intentional asymmetry\\n between ``__getattr__()`` and ``__setattr__()``.) This is done both\\n for efficiency reasons and because otherwise ``__getattr__()``\\n would have no way to access other attributes of the instance. Note\\n that at least for instance variables, you can fake total control by\\n not inserting any values in the instance attribute dictionary (but\\n instead inserting them in another object). See the\\n ``__getattribute__()`` method below for a way to actually get total\\n control over attribute access.\\n\\nobject.__getattribute__(self, name)\\n\\n Called unconditionally to implement attribute accesses for\\n instances of the class. If the class also defines\\n ``__getattr__()``, the latter will not be called unless\\n ``__getattribute__()`` either calls it explicitly or raises an\\n ``AttributeError``. This method should return the (computed)\\n attribute value or raise an ``AttributeError`` exception. In order\\n to avoid infinite recursion in this method, its implementation\\n should always call the base class method with the same name to\\n access any attributes it needs, for example,\\n ``object.__getattribute__(self, name)``.\\n\\n Note: This method may still be bypassed when looking up special methods\\n as the result of implicit invocation via language syntax or\\n built-in functions. See *Special method lookup*.\\n\\nobject.__setattr__(self, name, value)\\n\\n Called when an attribute assignment is attempted. This is called\\n instead of the normal mechanism (i.e. store the value in the\\n instance dictionary). *name* is the attribute name, *value* is the\\n value to be assigned to it.\\n\\n If ``__setattr__()`` wants to assign to an instance attribute, it\\n should call the base class method with the same name, for example,\\n ``object.__setattr__(self, name, value)``.\\n\\nobject.__delattr__(self, name)\\n\\n Like ``__setattr__()`` but for attribute deletion instead of\\n assignment. This should only be implemented if ``del obj.name`` is\\n meaningful for the object.\\n\\nobject.__dir__(self)\\n\\n Called when ``dir()`` is called on the object. A sequence must be\\n returned. ``dir()`` converts the returned sequence to a list and\\n sorts it.\\n\\n\\nImplementing Descriptors\\n------------------------\\n\\nThe following methods only apply when an instance of the class\\ncontaining the method (a so-called *descriptor* class) appears in an\\n*owner* class (the descriptor must be in either the owner\\'s class\\ndictionary or in the class dictionary for one of its parents). In the\\nexamples below, \"the attribute\" refers to the attribute whose name is\\nthe key of the property in the owner class\\' ``__dict__``.\\n\\nobject.__get__(self, instance, owner)\\n\\n Called to get the attribute of the owner class (class attribute\\n access) or of an instance of that class (instance attribute\\n access). *owner* is always the owner class, while *instance* is the\\n instance that the attribute was accessed through, or ``None`` when\\n the attribute is accessed through the *owner*. This method should\\n return the (computed) attribute value or raise an\\n ``AttributeError`` exception.\\n\\nobject.__set__(self, instance, value)\\n\\n Called to set the attribute on an instance *instance* of the owner\\n class to a new value, *value*.\\n\\nobject.__delete__(self, instance)\\n\\n Called to delete the attribute on an instance *instance* of the\\n owner class.\\n\\n\\nInvoking Descriptors\\n--------------------\\n\\nIn general, a descriptor is an object attribute with \"binding\\nbehavior\", one whose attribute access has been overridden by methods\\nin the descriptor protocol: ``__get__()``, ``__set__()``, and\\n``__delete__()``. If any of those methods are defined for an object,\\nit is said to be a descriptor.\\n\\nThe default behavior for attribute access is to get, set, or delete\\nthe attribute from an object\\'s dictionary. For instance, ``a.x`` has a\\nlookup chain starting with ``a.__dict__[\\'x\\']``, then\\n``type(a).__dict__[\\'x\\']``, and continuing through the base classes of\\n``type(a)`` excluding metaclasses.\\n\\nHowever, if the looked-up value is an object defining one of the\\ndescriptor methods, then Python may override the default behavior and\\ninvoke the descriptor method instead. Where this occurs in the\\nprecedence chain depends on which descriptor methods were defined and\\nhow they were called.\\n\\nThe starting point for descriptor invocation is a binding, ``a.x``.\\nHow the arguments are assembled depends on ``a``:\\n\\nDirect Call\\n The simplest and least common call is when user code directly\\n invokes a descriptor method: ``x.__get__(a)``.\\n\\nInstance Binding\\n If binding to an object instance, ``a.x`` is transformed into the\\n call: ``type(a).__dict__[\\'x\\'].__get__(a, type(a))``.\\n\\nClass Binding\\n If binding to a class, ``A.x`` is transformed into the call:\\n ``A.__dict__[\\'x\\'].__get__(None, A)``.\\n\\nSuper Binding\\n If ``a`` is an instance of ``super``, then the binding ``super(B,\\n obj).m()`` searches ``obj.__class__.__mro__`` for the base class\\n ``A`` immediately preceding ``B`` and then invokes the descriptor\\n with the call: ``A.__dict__[\\'m\\'].__get__(obj, obj.__class__)``.\\n\\nFor instance bindings, the precedence of descriptor invocation depends\\non the which descriptor methods are defined. A descriptor can define\\nany combination of ``__get__()``, ``__set__()`` and ``__delete__()``.\\nIf it does not define ``__get__()``, then accessing the attribute will\\nreturn the descriptor object itself unless there is a value in the\\nobject\\'s instance dictionary. If the descriptor defines ``__set__()``\\nand/or ``__delete__()``, it is a data descriptor; if it defines\\nneither, it is a non-data descriptor. Normally, data descriptors\\ndefine both ``__get__()`` and ``__set__()``, while non-data\\ndescriptors have just the ``__get__()`` method. Data descriptors with\\n``__set__()`` and ``__get__()`` defined always override a redefinition\\nin an instance dictionary. In contrast, non-data descriptors can be\\noverridden by instances.\\n\\nPython methods (including ``staticmethod()`` and ``classmethod()``)\\nare implemented as non-data descriptors. Accordingly, instances can\\nredefine and override methods. This allows individual instances to\\nacquire behaviors that differ from other instances of the same class.\\n\\nThe ``property()`` function is implemented as a data descriptor.\\nAccordingly, instances cannot override the behavior of a property.\\n\\n\\n__slots__\\n---------\\n\\nBy default, instances of classes have a dictionary for attribute\\nstorage. This wastes space for objects having very few instance\\nvariables. The space consumption can become acute when creating large\\nnumbers of instances.\\n\\nThe default can be overridden by defining *__slots__* in a class\\ndefinition. The *__slots__* declaration takes a sequence of instance\\nvariables and reserves just enough space in each instance to hold a\\nvalue for each variable. Space is saved because *__dict__* is not\\ncreated for each instance.\\n\\nobject.__slots__\\n\\n This class variable can be assigned a string, iterable, or sequence\\n of strings with variable names used by instances. If defined in a\\n class, *__slots__* reserves space for the declared variables and\\n prevents the automatic creation of *__dict__* and *__weakref__* for\\n each instance.\\n\\n\\nNotes on using *__slots__*\\n~~~~~~~~~~~~~~~~~~~~~~~~~~\\n\\n* When inheriting from a class without *__slots__*, the *__dict__*\\n attribute of that class will always be accessible, so a *__slots__*\\n definition in the subclass is meaningless.\\n\\n* Without a *__dict__* variable, instances cannot be assigned new\\n variables not listed in the *__slots__* definition. Attempts to\\n assign to an unlisted variable name raises ``AttributeError``. If\\n dynamic assignment of new variables is desired, then add\\n ``\\'__dict__\\'`` to the sequence of strings in the *__slots__*\\n declaration.\\n\\n* Without a *__weakref__* variable for each instance, classes defining\\n *__slots__* do not support weak references to its instances. If weak\\n reference support is needed, then add ``\\'__weakref__\\'`` to the\\n sequence of strings in the *__slots__* declaration.\\n\\n* *__slots__* are implemented at the class level by creating\\n descriptors (*Implementing Descriptors*) for each variable name. As\\n a result, class attributes cannot be used to set default values for\\n instance variables defined by *__slots__*; otherwise, the class\\n attribute would overwrite the descriptor assignment.\\n\\n* The action of a *__slots__* declaration is limited to the class\\n where it is defined. As a result, subclasses will have a *__dict__*\\n unless they also define *__slots__* (which must only contain names\\n of any *additional* slots).\\n\\n* If a class defines a slot also defined in a base class, the instance\\n variable defined by the base class slot is inaccessible (except by\\n retrieving its descriptor directly from the base class). This\\n renders the meaning of the program undefined. In the future, a\\n check may be added to prevent this.\\n\\n* Nonempty *__slots__* does not work for classes derived from\\n \"variable-length\" built-in types such as ``int``, ``str`` and\\n ``tuple``.\\n\\n* Any non-string iterable may be assigned to *__slots__*. Mappings may\\n also be used; however, in the future, special meaning may be\\n assigned to the values corresponding to each key.\\n\\n* *__class__* assignment works only if both classes have the same\\n *__slots__*.\\n\\n\\nCustomizing class creation\\n==========================\\n\\nBy default, classes are constructed using ``type()``. The class body\\nis executed in a new namespace and the class name is bound locally to\\nthe result of ``type(name, bases, namespace)``.\\n\\nThe class creation process can be customised by passing the\\n``metaclass`` keyword argument in the class definition line, or by\\ninheriting from an existing class that included such an argument. In\\nthe following example, both ``MyClass`` and ``MySubclass`` are\\ninstances of ``Meta``:\\n\\n class Meta(type):\\n pass\\n\\n class MyClass(metaclass=Meta):\\n pass\\n\\n class MySubclass(MyClass):\\n pass\\n\\nAny other keyword arguments that are specified in the class definition\\nare passed through to all metaclass operations described below.\\n\\nWhen a class definition is executed, the following steps occur:\\n\\n* the appropriate metaclass is determined\\n\\n* the class namespace is prepared\\n\\n* the class body is executed\\n\\n* the class object is created\\n\\n\\nDetermining the appropriate metaclass\\n-------------------------------------\\n\\nThe appropriate metaclass for a class definition is determined as\\nfollows:\\n\\n* if no bases and no explicit metaclass are given, then ``type()`` is\\n used\\n\\n* if an explicit metaclass is given and it is *not* an instance of\\n ``type()``, then it is used directly as the metaclass\\n\\n* if an instance of ``type()`` is given as the explicit metaclass, or\\n bases are defined, then the most derived metaclass is used\\n\\nThe most derived metaclass is selected from the explicitly specified\\nmetaclass (if any) and the metaclasses (i.e. ``type(cls)``) of all\\nspecified base classes. The most derived metaclass is one which is a\\nsubtype of *all* of these candidate metaclasses. If none of the\\ncandidate metaclasses meets that criterion, then the class definition\\nwill fail with ``TypeError``.\\n\\n\\nPreparing the class namespace\\n-----------------------------\\n\\nOnce the appropriate metaclass has been identified, then the class\\nnamespace is prepared. If the metaclass has a ``__prepare__``\\nattribute, it is called as ``namespace = metaclass.__prepare__(name,\\nbases, **kwds)`` (where the additional keyword arguments, if any, come\\nfrom the class definition).\\n\\nIf the metaclass has no ``__prepare__`` attribute, then the class\\nnamespace is initialised as an empty ``dict()`` instance.\\n\\nSee also:\\n\\n **PEP 3115** - Metaclasses in Python 3000\\n Introduced the ``__prepare__`` namespace hook\\n\\n\\nExecuting the class body\\n------------------------\\n\\nThe class body is executed (approximately) as ``exec(body, globals(),\\nnamespace)``. The key difference from a normal call to ``exec()`` is\\nthat lexical scoping allows the class body (including any methods) to\\nreference names from the current and outer scopes when the class\\ndefinition occurs inside a function.\\n\\nHowever, even when the class definition occurs inside the function,\\nmethods defined inside the class still cannot see names defined at the\\nclass scope. Class variables must be accessed through the first\\nparameter of instance or class methods, and cannot be accessed at all\\nfrom static methods.\\n\\n\\nCreating the class object\\n-------------------------\\n\\nOnce the class namespace has been populated by executing the class\\nbody, the class object is created by calling ``metaclass(name, bases,\\nnamespace, **kwds)`` (the additional keywords passed here are the same\\nas those passed to ``__prepare__``).\\n\\nThis class object is the one that will be referenced by the zero-\\nargument form of ``super()``. ``__class__`` is an implicit closure\\nreference created by the compiler if any methods in a class body refer\\nto either ``__class__`` or ``super``. This allows the zero argument\\nform of ``super()`` to correctly identify the class being defined\\nbased on lexical scoping, while the class or instance that was used to\\nmake the current call is identified based on the first argument passed\\nto the method.\\n\\nAfter the class object is created, it is passed to the class\\ndecorators included in the class definition (if any) and the resulting\\nobject is bound in the local namespace as the defined class.\\n\\nSee also:\\n\\n **PEP 3135** - New super\\n Describes the implicit ``__class__`` closure reference\\n\\n\\nMetaclass example\\n-----------------\\n\\nThe potential uses for metaclasses are boundless. Some ideas that have\\nbeen explored include logging, interface checking, automatic\\ndelegation, automatic property creation, proxies, frameworks, and\\nautomatic resource locking/synchronization.\\n\\nHere is an example of a metaclass that uses an\\n``collections.OrderedDict`` to remember the order that class members\\nwere defined:\\n\\n class OrderedClass(type):\\n\\n @classmethod\\n def __prepare__(metacls, name, bases, **kwds):\\n return collections.OrderedDict()\\n\\n def __new__(cls, name, bases, namespace, **kwds):\\n result = type.__new__(cls, name, bases, dict(namespace))\\n result.members = tuple(namespace)\\n return result\\n\\n class A(metaclass=OrderedClass):\\n def one(self): pass\\n def two(self): pass\\n def three(self): pass\\n def four(self): pass\\n\\n >>> A.members\\n (\\'__module__\\', \\'one\\', \\'two\\', \\'three\\', \\'four\\')\\n\\nWhen the class definition for *A* gets executed, the process begins\\nwith calling the metaclass\\'s ``__prepare__()`` method which returns an\\nempty ``collections.OrderedDict``. That mapping records the methods\\nand attributes of *A* as they are defined within the body of the class\\nstatement. Once those definitions are executed, the ordered dictionary\\nis fully populated and the metaclass\\'s ``__new__()`` method gets\\ninvoked. That method builds the new type and it saves the ordered\\ndictionary keys in an attribute called ``members``.\\n\\n\\nCustomizing instance and subclass checks\\n========================================\\n\\nThe following methods are used to override the default behavior of the\\n``isinstance()`` and ``issubclass()`` built-in functions.\\n\\nIn particular, the metaclass ``abc.ABCMeta`` implements these methods\\nin order to allow the addition of Abstract Base Classes (ABCs) as\\n\"virtual base classes\" to any class or type (including built-in\\ntypes), including other ABCs.\\n\\nclass.__instancecheck__(self, instance)\\n\\n Return true if *instance* should be considered a (direct or\\n indirect) instance of *class*. If defined, called to implement\\n ``isinstance(instance, class)``.\\n\\nclass.__subclasscheck__(self, subclass)\\n\\n Return true if *subclass* should be considered a (direct or\\n indirect) subclass of *class*. If defined, called to implement\\n ``issubclass(subclass, class)``.\\n\\nNote that these methods are looked up on the type (metaclass) of a\\nclass. They cannot be defined as class methods in the actual class.\\nThis is consistent with the lookup of special methods that are called\\non instances, only in this case the instance is itself a class.\\n\\nSee also:\\n\\n **PEP 3119** - Introducing Abstract Base Classes\\n Includes the specification for customizing ``isinstance()`` and\\n ``issubclass()`` behavior through ``__instancecheck__()`` and\\n ``__subclasscheck__()``, with motivation for this functionality\\n in the context of adding Abstract Base Classes (see the ``abc``\\n module) to the language.\\n\\n\\nEmulating callable objects\\n==========================\\n\\nobject.__call__(self[, args...])\\n\\n Called when the instance is \"called\" as a function; if this method\\n is defined, ``x(arg1, arg2, ...)`` is a shorthand for\\n ``x.__call__(arg1, arg2, ...)``.\\n\\n\\nEmulating container types\\n=========================\\n\\nThe following methods can be defined to implement container objects.\\nContainers usually are sequences (such as lists or tuples) or mappings\\n(like dictionaries), but can represent other containers as well. The\\nfirst set of methods is used either to emulate a sequence or to\\nemulate a mapping; the difference is that for a sequence, the\\nallowable keys should be the integers *k* for which ``0 <= k < N``\\nwhere *N* is the length of the sequence, or slice objects, which\\ndefine a range of items. It is also recommended that mappings provide\\nthe methods ``keys()``, ``values()``, ``items()``, ``get()``,\\n``clear()``, ``setdefault()``, ``pop()``, ``popitem()``, ``copy()``,\\nand ``update()`` behaving similar to those for Python\\'s standard\\ndictionary objects. The ``collections`` module provides a\\n``MutableMapping`` abstract base class to help create those methods\\nfrom a base set of ``__getitem__()``, ``__setitem__()``,\\n``__delitem__()``, and ``keys()``. Mutable sequences should provide\\nmethods ``append()``, ``count()``, ``index()``, ``extend()``,\\n``insert()``, ``pop()``, ``remove()``, ``reverse()`` and ``sort()``,\\nlike Python standard list objects. Finally, sequence types should\\nimplement addition (meaning concatenation) and multiplication (meaning\\nrepetition) by defining the methods ``__add__()``, ``__radd__()``,\\n``__iadd__()``, ``__mul__()``, ``__rmul__()`` and ``__imul__()``\\ndescribed below; they should not define other numerical operators. It\\nis recommended that both mappings and sequences implement the\\n``__contains__()`` method to allow efficient use of the ``in``\\noperator; for mappings, ``in`` should search the mapping\\'s keys; for\\nsequences, it should search through the values. It is further\\nrecommended that both mappings and sequences implement the\\n``__iter__()`` method to allow efficient iteration through the\\ncontainer; for mappings, ``__iter__()`` should be the same as\\n``keys()``; for sequences, it should iterate through the values.\\n\\nobject.__len__(self)\\n\\n Called to implement the built-in function ``len()``. Should return\\n the length of the object, an integer ``>=`` 0. Also, an object\\n that doesn\\'t define a ``__bool__()`` method and whose ``__len__()``\\n method returns zero is considered to be false in a Boolean context.\\n\\nNote: Slicing is done exclusively with the following three methods. A\\n call like\\n\\n a[1:2] = b\\n\\n is translated to\\n\\n a[slice(1, 2, None)] = b\\n\\n and so forth. Missing slice items are always filled in with\\n ``None``.\\n\\nobject.__getitem__(self, key)\\n\\n Called to implement evaluation of ``self[key]``. For sequence\\n types, the accepted keys should be integers and slice objects.\\n Note that the special interpretation of negative indexes (if the\\n class wishes to emulate a sequence type) is up to the\\n ``__getitem__()`` method. If *key* is of an inappropriate type,\\n ``TypeError`` may be raised; if of a value outside the set of\\n indexes for the sequence (after any special interpretation of\\n negative values), ``IndexError`` should be raised. For mapping\\n types, if *key* is missing (not in the container), ``KeyError``\\n should be raised.\\n\\n Note: ``for`` loops expect that an ``IndexError`` will be raised for\\n illegal indexes to allow proper detection of the end of the\\n sequence.\\n\\nobject.__setitem__(self, key, value)\\n\\n Called to implement assignment to ``self[key]``. Same note as for\\n ``__getitem__()``. This should only be implemented for mappings if\\n the objects support changes to the values for keys, or if new keys\\n can be added, or for sequences if elements can be replaced. The\\n same exceptions should be raised for improper *key* values as for\\n the ``__getitem__()`` method.\\n\\nobject.__delitem__(self, key)\\n\\n Called to implement deletion of ``self[key]``. Same note as for\\n ``__getitem__()``. This should only be implemented for mappings if\\n the objects support removal of keys, or for sequences if elements\\n can be removed from the sequence. The same exceptions should be\\n raised for improper *key* values as for the ``__getitem__()``\\n method.\\n\\nobject.__iter__(self)\\n\\n This method is called when an iterator is required for a container.\\n This method should return a new iterator object that can iterate\\n over all the objects in the container. For mappings, it should\\n iterate over the keys of the container, and should also be made\\n available as the method ``keys()``.\\n\\n Iterator objects also need to implement this method; they are\\n required to return themselves. For more information on iterator\\n objects, see *Iterator Types*.\\n\\nobject.__reversed__(self)\\n\\n Called (if present) by the ``reversed()`` built-in to implement\\n reverse iteration. It should return a new iterator object that\\n iterates over all the objects in the container in reverse order.\\n\\n If the ``__reversed__()`` method is not provided, the\\n ``reversed()`` built-in will fall back to using the sequence\\n protocol (``__len__()`` and ``__getitem__()``). Objects that\\n support the sequence protocol should only provide\\n ``__reversed__()`` if they can provide an implementation that is\\n more efficient than the one provided by ``reversed()``.\\n\\nThe membership test operators (``in`` and ``not in``) are normally\\nimplemented as an iteration through a sequence. However, container\\nobjects can supply the following special method with a more efficient\\nimplementation, which also does not require the object be a sequence.\\n\\nobject.__contains__(self, item)\\n\\n Called to implement membership test operators. Should return true\\n if *item* is in *self*, false otherwise. For mapping objects, this\\n should consider the keys of the mapping rather than the values or\\n the key-item pairs.\\n\\n For objects that don\\'t define ``__contains__()``, the membership\\n test first tries iteration via ``__iter__()``, then the old\\n sequence iteration protocol via ``__getitem__()``, see *this\\n section in the language reference*.\\n\\n\\nEmulating numeric types\\n=======================\\n\\nThe following methods can be defined to emulate numeric objects.\\nMethods corresponding to operations that are not supported by the\\nparticular kind of number implemented (e.g., bitwise operations for\\nnon-integral numbers) should be left undefined.\\n\\nobject.__add__(self, other)\\nobject.__sub__(self, other)\\nobject.__mul__(self, other)\\nobject.__truediv__(self, other)\\nobject.__floordiv__(self, other)\\nobject.__mod__(self, other)\\nobject.__divmod__(self, other)\\nobject.__pow__(self, other[, modulo])\\nobject.__lshift__(self, other)\\nobject.__rshift__(self, other)\\nobject.__and__(self, other)\\nobject.__xor__(self, other)\\nobject.__or__(self, other)\\n\\n These methods are called to implement the binary arithmetic\\n operations (``+``, ``-``, ``*``, ``/``, ``//``, ``%``,\\n ``divmod()``, ``pow()``, ``**``, ``<<``, ``>>``, ``&``, ``^``,\\n ``|``). For instance, to evaluate the expression ``x + y``, where\\n *x* is an instance of a class that has an ``__add__()`` method,\\n ``x.__add__(y)`` is called. The ``__divmod__()`` method should be\\n the equivalent to using ``__floordiv__()`` and ``__mod__()``; it\\n should not be related to ``__truediv__()``. Note that\\n ``__pow__()`` should be defined to accept an optional third\\n argument if the ternary version of the built-in ``pow()`` function\\n is to be supported.\\n\\n If one of those methods does not support the operation with the\\n supplied arguments, it should return ``NotImplemented``.\\n\\nobject.__radd__(self, other)\\nobject.__rsub__(self, other)\\nobject.__rmul__(self, other)\\nobject.__rtruediv__(self, other)\\nobject.__rfloordiv__(self, other)\\nobject.__rmod__(self, other)\\nobject.__rdivmod__(self, other)\\nobject.__rpow__(self, other)\\nobject.__rlshift__(self, other)\\nobject.__rrshift__(self, other)\\nobject.__rand__(self, other)\\nobject.__rxor__(self, other)\\nobject.__ror__(self, other)\\n\\n These methods are called to implement the binary arithmetic\\n operations (``+``, ``-``, ``*``, ``/``, ``//``, ``%``,\\n ``divmod()``, ``pow()``, ``**``, ``<<``, ``>>``, ``&``, ``^``,\\n ``|``) with reflected (swapped) operands. These functions are only\\n called if the left operand does not support the corresponding\\n operation and the operands are of different types. [2] For\\n instance, to evaluate the expression ``x - y``, where *y* is an\\n instance of a class that has an ``__rsub__()`` method,\\n ``y.__rsub__(x)`` is called if ``x.__sub__(y)`` returns\\n *NotImplemented*.\\n\\n Note that ternary ``pow()`` will not try calling ``__rpow__()``\\n (the coercion rules would become too complicated).\\n\\n Note: If the right operand\\'s type is a subclass of the left operand\\'s\\n type and that subclass provides the reflected method for the\\n operation, this method will be called before the left operand\\'s\\n non-reflected method. This behavior allows subclasses to\\n override their ancestors\\' operations.\\n\\nobject.__iadd__(self, other)\\nobject.__isub__(self, other)\\nobject.__imul__(self, other)\\nobject.__itruediv__(self, other)\\nobject.__ifloordiv__(self, other)\\nobject.__imod__(self, other)\\nobject.__ipow__(self, other[, modulo])\\nobject.__ilshift__(self, other)\\nobject.__irshift__(self, other)\\nobject.__iand__(self, other)\\nobject.__ixor__(self, other)\\nobject.__ior__(self, other)\\n\\n These methods are called to implement the augmented arithmetic\\n assignments (``+=``, ``-=``, ``*=``, ``/=``, ``//=``, ``%=``,\\n ``**=``, ``<<=``, ``>>=``, ``&=``, ``^=``, ``|=``). These methods\\n should attempt to do the operation in-place (modifying *self*) and\\n return the result (which could be, but does not have to be,\\n *self*). If a specific method is not defined, the augmented\\n assignment falls back to the normal methods. For instance, to\\n execute the statement ``x += y``, where *x* is an instance of a\\n class that has an ``__iadd__()`` method, ``x.__iadd__(y)`` is\\n called. If *x* is an instance of a class that does not define a\\n ``__iadd__()`` method, ``x.__add__(y)`` and ``y.__radd__(x)`` are\\n considered, as with the evaluation of ``x + y``.\\n\\nobject.__neg__(self)\\nobject.__pos__(self)\\nobject.__abs__(self)\\nobject.__invert__(self)\\n\\n Called to implement the unary arithmetic operations (``-``, ``+``,\\n ``abs()`` and ``~``).\\n\\nobject.__complex__(self)\\nobject.__int__(self)\\nobject.__float__(self)\\nobject.__round__(self[, n])\\n\\n Called to implement the built-in functions ``complex()``,\\n ``int()``, ``float()`` and ``round()``. Should return a value of\\n the appropriate type.\\n\\nobject.__index__(self)\\n\\n Called to implement ``operator.index()``. Also called whenever\\n Python needs an integer object (such as in slicing, or in the\\n built-in ``bin()``, ``hex()`` and ``oct()`` functions). Must return\\n an integer.\\n\\n\\nWith Statement Context Managers\\n===============================\\n\\nA *context manager* is an object that defines the runtime context to\\nbe established when executing a ``with`` statement. The context\\nmanager handles the entry into, and the exit from, the desired runtime\\ncontext for the execution of the block of code. Context managers are\\nnormally invoked using the ``with`` statement (described in section\\n*The with statement*), but can also be used by directly invoking their\\nmethods.\\n\\nTypical uses of context managers include saving and restoring various\\nkinds of global state, locking and unlocking resources, closing opened\\nfiles, etc.\\n\\nFor more information on context managers, see *Context Manager Types*.\\n\\nobject.__enter__(self)\\n\\n Enter the runtime context related to this object. The ``with``\\n statement will bind this method\\'s return value to the target(s)\\n specified in the ``as`` clause of the statement, if any.\\n\\nobject.__exit__(self, exc_type, exc_value, traceback)\\n\\n Exit the runtime context related to this object. The parameters\\n describe the exception that caused the context to be exited. If the\\n context was exited without an exception, all three arguments will\\n be ``None``.\\n\\n If an exception is supplied, and the method wishes to suppress the\\n exception (i.e., prevent it from being propagated), it should\\n return a true value. Otherwise, the exception will be processed\\n normally upon exit from this method.\\n\\n Note that ``__exit__()`` methods should not reraise the passed-in\\n exception; this is the caller\\'s responsibility.\\n\\nSee also:\\n\\n **PEP 0343** - The \"with\" statement\\n The specification, background, and examples for the Python\\n ``with`` statement.\\n\\n\\nSpecial method lookup\\n=====================\\n\\nFor custom classes, implicit invocations of special methods are only\\nguaranteed to work correctly if defined on an object\\'s type, not in\\nthe object\\'s instance dictionary. That behaviour is the reason why\\nthe following code raises an exception:\\n\\n >>> class C:\\n ... pass\\n ...\\n >>> c = C()\\n >>> c.__len__ = lambda: 5\\n >>> len(c)\\n Traceback (most recent call last):\\n File \"<stdin>\", line 1, in <module>\\n TypeError: object of type \\'C\\' has no len()\\n\\nThe rationale behind this behaviour lies with a number of special\\nmethods such as ``__hash__()`` and ``__repr__()`` that are implemented\\nby all objects, including type objects. If the implicit lookup of\\nthese methods used the conventional lookup process, they would fail\\nwhen invoked on the type object itself:\\n\\n >>> 1 .__hash__() == hash(1)\\n True\\n >>> int.__hash__() == hash(int)\\n Traceback (most recent call last):\\n File \"<stdin>\", line 1, in <module>\\n TypeError: descriptor \\'__hash__\\' of \\'int\\' object needs an argument\\n\\nIncorrectly attempting to invoke an unbound method of a class in this\\nway is sometimes referred to as \\'metaclass confusion\\', and is avoided\\nby bypassing the instance when looking up special methods:\\n\\n >>> type(1).__hash__(1) == hash(1)\\n True\\n >>> type(int).__hash__(int) == hash(int)\\n True\\n\\nIn addition to bypassing any instance attributes in the interest of\\ncorrectness, implicit special method lookup generally also bypasses\\nthe ``__getattribute__()`` method even of the object\\'s metaclass:\\n\\n >>> class Meta(type):\\n ... def __getattribute__(*args):\\n ... print(\"Metaclass getattribute invoked\")\\n ... return type.__getattribute__(*args)\\n ...\\n >>> class C(object, metaclass=Meta):\\n ... def __len__(self):\\n ... return 10\\n ... def __getattribute__(*args):\\n ... print(\"Class getattribute invoked\")\\n ... return object.__getattribute__(*args)\\n ...\\n >>> c = C()\\n >>> c.__len__() # Explicit lookup via instance\\n Class getattribute invoked\\n 10\\n >>> type(c).__len__(c) # Explicit lookup via type\\n Metaclass getattribute invoked\\n 10\\n >>> len(c) # Implicit lookup\\n 10\\n\\nBypassing the ``__getattribute__()`` machinery in this fashion\\nprovides significant scope for speed optimisations within the\\ninterpreter, at the cost of some flexibility in the handling of\\nspecial methods (the special method *must* be set on the class object\\nitself in order to be consistently invoked by the interpreter).\\n\\n-[ Footnotes ]-\\n\\n[1] It *is* possible in some cases to change an object\\'s type, under\\n certain controlled conditions. It generally isn\\'t a good idea\\n though, since it can lead to some very strange behaviour if it is\\n handled incorrectly.\\n\\n[2] For operands of the same type, it is assumed that if the non-\\n reflected method (such as ``__add__()``) fails the operation is\\n not supported, which is why the reflected method is not called.\\n',\n'string-methods':'\\nString Methods\\n**************\\n\\nStrings implement all of the *common* sequence operations, along with\\nthe additional methods described below.\\n\\nStrings also support two styles of string formatting, one providing a\\nlarge degree of flexibility and customization (see ``str.format()``,\\n*Format String Syntax* and *String Formatting*) and the other based on\\nC ``printf`` style formatting that handles a narrower range of types\\nand is slightly harder to use correctly, but is often faster for the\\ncases it can handle (*printf-style String Formatting*).\\n\\nThe *Text Processing Services* section of the standard library covers\\na number of other modules that provide various text related utilities\\n(including regular expression support in the ``re`` module).\\n\\nstr.capitalize()\\n\\n Return a copy of the string with its first character capitalized\\n and the rest lowercased.\\n\\nstr.casefold()\\n\\n Return a casefolded copy of the string. Casefolded strings may be\\n used for caseless matching.\\n\\n Casefolding is similar to lowercasing but more aggressive because\\n it is intended to remove all case distinctions in a string. For\\n example, the German lowercase letter ``\\'\\xc3\\x9f\\'`` is equivalent to\\n ``\"ss\"``. Since it is already lowercase, ``lower()`` would do\\n nothing to ``\\'\\xc3\\x9f\\'``; ``casefold()`` converts it to ``\"ss\"``.\\n\\n The casefolding algorithm is described in section 3.13 of the\\n Unicode Standard.\\n\\n New in version 3.3.\\n\\nstr.center(width[, fillchar])\\n\\n Return centered in a string of length *width*. Padding is done\\n using the specified *fillchar* (default is a space).\\n\\nstr.count(sub[, start[, end]])\\n\\n Return the number of non-overlapping occurrences of substring *sub*\\n in the range [*start*, *end*]. Optional arguments *start* and\\n *end* are interpreted as in slice notation.\\n\\nstr.encode(encoding=\"utf-8\", errors=\"strict\")\\n\\n Return an encoded version of the string as a bytes object. Default\\n encoding is ``\\'utf-8\\'``. *errors* may be given to set a different\\n error handling scheme. The default for *errors* is ``\\'strict\\'``,\\n meaning that encoding errors raise a ``UnicodeError``. Other\\n possible values are ``\\'ignore\\'``, ``\\'replace\\'``,\\n ``\\'xmlcharrefreplace\\'``, ``\\'backslashreplace\\'`` and any other name\\n registered via ``codecs.register_error()``, see section *Codec Base\\n Classes*. For a list of possible encodings, see section *Standard\\n Encodings*.\\n\\n Changed in version 3.1: Support for keyword arguments added.\\n\\nstr.endswith(suffix[, start[, end]])\\n\\n Return ``True`` if the string ends with the specified *suffix*,\\n otherwise return ``False``. *suffix* can also be a tuple of\\n suffixes to look for. With optional *start*, test beginning at\\n that position. With optional *end*, stop comparing at that\\n position.\\n\\nstr.expandtabs([tabsize])\\n\\n Return a copy of the string where all tab characters are replaced\\n by zero or more spaces, depending on the current column and the\\n given tab size. The column number is reset to zero after each\\n newline occurring in the string. If *tabsize* is not given, a tab\\n size of ``8`` characters is assumed. This doesn\\'t understand other\\n non-printing characters or escape sequences.\\n\\nstr.find(sub[, start[, end]])\\n\\n Return the lowest index in the string where substring *sub* is\\n found, such that *sub* is contained in the slice ``s[start:end]``.\\n Optional arguments *start* and *end* are interpreted as in slice\\n notation. Return ``-1`` if *sub* is not found.\\n\\n Note: The ``find()`` method should be used only if you need to know the\\n position of *sub*. To check if *sub* is a substring or not, use\\n the ``in`` operator:\\n\\n >>> \\'Py\\' in \\'Python\\'\\n True\\n\\nstr.format(*args, **kwargs)\\n\\n Perform a string formatting operation. The string on which this\\n method is called can contain literal text or replacement fields\\n delimited by braces ``{}``. Each replacement field contains either\\n the numeric index of a positional argument, or the name of a\\n keyword argument. Returns a copy of the string where each\\n replacement field is replaced with the string value of the\\n corresponding argument.\\n\\n >>> \"The sum of 1 + 2 is {0}\".format(1+2)\\n \\'The sum of 1 + 2 is 3\\'\\n\\n See *Format String Syntax* for a description of the various\\n formatting options that can be specified in format strings.\\n\\nstr.format_map(mapping)\\n\\n Similar to ``str.format(**mapping)``, except that ``mapping`` is\\n used directly and not copied to a ``dict`` . This is useful if for\\n example ``mapping`` is a dict subclass:\\n\\n >>> class Default(dict):\\n ... def __missing__(self, key):\\n ... return key\\n ...\\n >>> \\'{name} was born in {country}\\'.format_map(Default(name=\\'Guido\\'))\\n \\'Guido was born in country\\'\\n\\n New in version 3.2.\\n\\nstr.index(sub[, start[, end]])\\n\\n Like ``find()``, but raise ``ValueError`` when the substring is not\\n found.\\n\\nstr.isalnum()\\n\\n Return true if all characters in the string are alphanumeric and\\n there is at least one character, false otherwise. A character\\n ``c`` is alphanumeric if one of the following returns ``True``:\\n ``c.isalpha()``, ``c.isdecimal()``, ``c.isdigit()``, or\\n ``c.isnumeric()``.\\n\\nstr.isalpha()\\n\\n Return true if all characters in the string are alphabetic and\\n there is at least one character, false otherwise. Alphabetic\\n characters are those characters defined in the Unicode character\\n database as \"Letter\", i.e., those with general category property\\n being one of \"Lm\", \"Lt\", \"Lu\", \"Ll\", or \"Lo\". Note that this is\\n different from the \"Alphabetic\" property defined in the Unicode\\n Standard.\\n\\nstr.isdecimal()\\n\\n Return true if all characters in the string are decimal characters\\n and there is at least one character, false otherwise. Decimal\\n characters are those from general category \"Nd\". This category\\n includes digit characters, and all characters that can be used to\\n form decimal-radix numbers, e.g. U+0660, ARABIC-INDIC DIGIT ZERO.\\n\\nstr.isdigit()\\n\\n Return true if all characters in the string are digits and there is\\n at least one character, false otherwise. Digits include decimal\\n characters and digits that need special handling, such as the\\n compatibility superscript digits. Formally, a digit is a character\\n that has the property value Numeric_Type=Digit or\\n Numeric_Type=Decimal.\\n\\nstr.isidentifier()\\n\\n Return true if the string is a valid identifier according to the\\n language definition, section *Identifiers and keywords*.\\n\\nstr.islower()\\n\\n Return true if all cased characters [4] in the string are lowercase\\n and there is at least one cased character, false otherwise.\\n\\nstr.isnumeric()\\n\\n Return true if all characters in the string are numeric characters,\\n and there is at least one character, false otherwise. Numeric\\n characters include digit characters, and all characters that have\\n the Unicode numeric value property, e.g. U+2155, VULGAR FRACTION\\n ONE FIFTH. Formally, numeric characters are those with the\\n property value Numeric_Type=Digit, Numeric_Type=Decimal or\\n Numeric_Type=Numeric.\\n\\nstr.isprintable()\\n\\n Return true if all characters in the string are printable or the\\n string is empty, false otherwise. Nonprintable characters are\\n those characters defined in the Unicode character database as\\n \"Other\" or \"Separator\", excepting the ASCII space (0x20) which is\\n considered printable. (Note that printable characters in this\\n context are those which should not be escaped when ``repr()`` is\\n invoked on a string. It has no bearing on the handling of strings\\n written to ``sys.stdout`` or ``sys.stderr``.)\\n\\nstr.isspace()\\n\\n Return true if there are only whitespace characters in the string\\n and there is at least one character, false otherwise. Whitespace\\n characters are those characters defined in the Unicode character\\n database as \"Other\" or \"Separator\" and those with bidirectional\\n property being one of \"WS\", \"B\", or \"S\".\\n\\nstr.istitle()\\n\\n Return true if the string is a titlecased string and there is at\\n least one character, for example uppercase characters may only\\n follow uncased characters and lowercase characters only cased ones.\\n Return false otherwise.\\n\\nstr.isupper()\\n\\n Return true if all cased characters [4] in the string are uppercase\\n and there is at least one cased character, false otherwise.\\n\\nstr.join(iterable)\\n\\n Return a string which is the concatenation of the strings in the\\n *iterable* *iterable*. A ``TypeError`` will be raised if there are\\n any non-string values in *iterable*, including ``bytes`` objects.\\n The separator between elements is the string providing this method.\\n\\nstr.ljust(width[, fillchar])\\n\\n Return the string left justified in a string of length *width*.\\n Padding is done using the specified *fillchar* (default is a\\n space). The original string is returned if *width* is less than or\\n equal to ``len(s)``.\\n\\nstr.lower()\\n\\n Return a copy of the string with all the cased characters [4]\\n converted to lowercase.\\n\\n The lowercasing algorithm used is described in section 3.13 of the\\n Unicode Standard.\\n\\nstr.lstrip([chars])\\n\\n Return a copy of the string with leading characters removed. The\\n *chars* argument is a string specifying the set of characters to be\\n removed. If omitted or ``None``, the *chars* argument defaults to\\n removing whitespace. The *chars* argument is not a prefix; rather,\\n all combinations of its values are stripped:\\n\\n >>> \\' spacious \\'.lstrip()\\n \\'spacious \\'\\n >>> \\'www.example.com\\'.lstrip(\\'cmowz.\\')\\n \\'example.com\\'\\n\\nstatic str.maketrans(x[, y[, z]])\\n\\n This static method returns a translation table usable for\\n ``str.translate()``.\\n\\n If there is only one argument, it must be a dictionary mapping\\n Unicode ordinals (integers) or characters (strings of length 1) to\\n Unicode ordinals, strings (of arbitrary lengths) or None.\\n Character keys will then be converted to ordinals.\\n\\n If there are two arguments, they must be strings of equal length,\\n and in the resulting dictionary, each character in x will be mapped\\n to the character at the same position in y. If there is a third\\n argument, it must be a string, whose characters will be mapped to\\n None in the result.\\n\\nstr.partition(sep)\\n\\n Split the string at the first occurrence of *sep*, and return a\\n 3-tuple containing the part before the separator, the separator\\n itself, and the part after the separator. If the separator is not\\n found, return a 3-tuple containing the string itself, followed by\\n two empty strings.\\n\\nstr.replace(old, new[, count])\\n\\n Return a copy of the string with all occurrences of substring *old*\\n replaced by *new*. If the optional argument *count* is given, only\\n the first *count* occurrences are replaced.\\n\\nstr.rfind(sub[, start[, end]])\\n\\n Return the highest index in the string where substring *sub* is\\n found, such that *sub* is contained within ``s[start:end]``.\\n Optional arguments *start* and *end* are interpreted as in slice\\n notation. Return ``-1`` on failure.\\n\\nstr.rindex(sub[, start[, end]])\\n\\n Like ``rfind()`` but raises ``ValueError`` when the substring *sub*\\n is not found.\\n\\nstr.rjust(width[, fillchar])\\n\\n Return the string right justified in a string of length *width*.\\n Padding is done using the specified *fillchar* (default is a\\n space). The original string is returned if *width* is less than or\\n equal to ``len(s)``.\\n\\nstr.rpartition(sep)\\n\\n Split the string at the last occurrence of *sep*, and return a\\n 3-tuple containing the part before the separator, the separator\\n itself, and the part after the separator. If the separator is not\\n found, return a 3-tuple containing two empty strings, followed by\\n the string itself.\\n\\nstr.rsplit(sep=None, maxsplit=-1)\\n\\n Return a list of the words in the string, using *sep* as the\\n delimiter string. If *maxsplit* is given, at most *maxsplit* splits\\n are done, the *rightmost* ones. If *sep* is not specified or\\n ``None``, any whitespace string is a separator. Except for\\n splitting from the right, ``rsplit()`` behaves like ``split()``\\n which is described in detail below.\\n\\nstr.rstrip([chars])\\n\\n Return a copy of the string with trailing characters removed. The\\n *chars* argument is a string specifying the set of characters to be\\n removed. If omitted or ``None``, the *chars* argument defaults to\\n removing whitespace. The *chars* argument is not a suffix; rather,\\n all combinations of its values are stripped:\\n\\n >>> \\' spacious \\'.rstrip()\\n \\' spacious\\'\\n >>> \\'mississippi\\'.rstrip(\\'ipz\\')\\n \\'mississ\\'\\n\\nstr.split(sep=None, maxsplit=-1)\\n\\n Return a list of the words in the string, using *sep* as the\\n delimiter string. If *maxsplit* is given, at most *maxsplit*\\n splits are done (thus, the list will have at most ``maxsplit+1``\\n elements). If *maxsplit* is not specified or ``-1``, then there is\\n no limit on the number of splits (all possible splits are made).\\n\\n If *sep* is given, consecutive delimiters are not grouped together\\n and are deemed to delimit empty strings (for example,\\n ``\\'1,,2\\'.split(\\',\\')`` returns ``[\\'1\\', \\'\\', \\'2\\']``). The *sep*\\n argument may consist of multiple characters (for example,\\n ``\\'1<>2<>3\\'.split(\\'<>\\')`` returns ``[\\'1\\', \\'2\\', \\'3\\']``). Splitting\\n an empty string with a specified separator returns ``[\\'\\']``.\\n\\n If *sep* is not specified or is ``None``, a different splitting\\n algorithm is applied: runs of consecutive whitespace are regarded\\n as a single separator, and the result will contain no empty strings\\n at the start or end if the string has leading or trailing\\n whitespace. Consequently, splitting an empty string or a string\\n consisting of just whitespace with a ``None`` separator returns\\n ``[]``.\\n\\n For example, ``\\' 1 2 3 \\'.split()`` returns ``[\\'1\\', \\'2\\', \\'3\\']``,\\n and ``\\' 1 2 3 \\'.split(None, 1)`` returns ``[\\'1\\', \\'2 3 \\']``.\\n\\nstr.splitlines([keepends])\\n\\n Return a list of the lines in the string, breaking at line\\n boundaries. This method uses the *universal newlines* approach to\\n splitting lines. Line breaks are not included in the resulting list\\n unless *keepends* is given and true.\\n\\n For example, ``\\'ab c\\\\n\\\\nde fg\\\\rkl\\\\r\\\\n\\'.splitlines()`` returns\\n ``[\\'ab c\\', \\'\\', \\'de fg\\', \\'kl\\']``, while the same call with\\n ``splitlines(True)`` returns ``[\\'ab c\\\\n\\', \\'\\\\n\\', \\'de fg\\\\r\\',\\n \\'kl\\\\r\\\\n\\']``.\\n\\n Unlike ``split()`` when a delimiter string *sep* is given, this\\n method returns an empty list for the empty string, and a terminal\\n line break does not result in an extra line.\\n\\nstr.startswith(prefix[, start[, end]])\\n\\n Return ``True`` if string starts with the *prefix*, otherwise\\n return ``False``. *prefix* can also be a tuple of prefixes to look\\n for. With optional *start*, test string beginning at that\\n position. With optional *end*, stop comparing string at that\\n position.\\n\\nstr.strip([chars])\\n\\n Return a copy of the string with the leading and trailing\\n characters removed. The *chars* argument is a string specifying the\\n set of characters to be removed. If omitted or ``None``, the\\n *chars* argument defaults to removing whitespace. The *chars*\\n argument is not a prefix or suffix; rather, all combinations of its\\n values are stripped:\\n\\n >>> \\' spacious \\'.strip()\\n \\'spacious\\'\\n >>> \\'www.example.com\\'.strip(\\'cmowz.\\')\\n \\'example\\'\\n\\nstr.swapcase()\\n\\n Return a copy of the string with uppercase characters converted to\\n lowercase and vice versa. Note that it is not necessarily true that\\n ``s.swapcase().swapcase() == s``.\\n\\nstr.title()\\n\\n Return a titlecased version of the string where words start with an\\n uppercase character and the remaining characters are lowercase.\\n\\n The algorithm uses a simple language-independent definition of a\\n word as groups of consecutive letters. The definition works in\\n many contexts but it means that apostrophes in contractions and\\n possessives form word boundaries, which may not be the desired\\n result:\\n\\n >>> \"they\\'re bill\\'s friends from the UK\".title()\\n \"They\\'Re Bill\\'S Friends From The Uk\"\\n\\n A workaround for apostrophes can be constructed using regular\\n expressions:\\n\\n >>> import re\\n >>> def titlecase(s):\\n ... return re.sub(r\"[A-Za-z]+(\\'[A-Za-z]+)?\",\\n ... lambda mo: mo.group(0)[0].upper() +\\n ... mo.group(0)[1:].lower(),\\n ... s)\\n ...\\n >>> titlecase(\"they\\'re bill\\'s friends.\")\\n \"They\\'re Bill\\'s Friends.\"\\n\\nstr.translate(map)\\n\\n Return a copy of the *s* where all characters have been mapped\\n through the *map* which must be a dictionary of Unicode ordinals\\n (integers) to Unicode ordinals, strings or ``None``. Unmapped\\n characters are left untouched. Characters mapped to ``None`` are\\n deleted.\\n\\n You can use ``str.maketrans()`` to create a translation map from\\n character-to-character mappings in different formats.\\n\\n Note: An even more flexible approach is to create a custom character\\n mapping codec using the ``codecs`` module (see\\n ``encodings.cp1251`` for an example).\\n\\nstr.upper()\\n\\n Return a copy of the string with all the cased characters [4]\\n converted to uppercase. Note that ``str.upper().isupper()`` might\\n be ``False`` if ``s`` contains uncased characters or if the Unicode\\n category of the resulting character(s) is not \"Lu\" (Letter,\\n uppercase), but e.g. \"Lt\" (Letter, titlecase).\\n\\n The uppercasing algorithm used is described in section 3.13 of the\\n Unicode Standard.\\n\\nstr.zfill(width)\\n\\n Return the numeric string left filled with zeros in a string of\\n length *width*. A sign prefix is handled correctly. The original\\n string is returned if *width* is less than or equal to ``len(s)``.\\n',\n'strings':'\\nString and Bytes literals\\n*************************\\n\\nString literals are described by the following lexical definitions:\\n\\n stringliteral ::= [stringprefix](shortstring | longstring)\\n stringprefix ::= \"r\" | \"u\" | \"R\" | \"U\"\\n shortstring ::= \"\\'\" shortstringitem* \"\\'\" | \\'\"\\' shortstringitem* \\'\"\\'\\n longstring ::= \"\\'\\'\\'\" longstringitem* \"\\'\\'\\'\" | \\'\"\"\"\\' longstringitem* \\'\"\"\"\\'\\n shortstringitem ::= shortstringchar | stringescapeseq\\n longstringitem ::= longstringchar | stringescapeseq\\n shortstringchar ::= <any source character except \"\\\\\" or newline or the quote>\\n longstringchar ::= <any source character except \"\\\\\">\\n stringescapeseq ::= \"\\\\\" <any source character>\\n\\n bytesliteral ::= bytesprefix(shortbytes | longbytes)\\n bytesprefix ::= \"b\" | \"B\" | \"br\" | \"Br\" | \"bR\" | \"BR\" | \"rb\" | \"rB\" | \"Rb\" | \"RB\"\\n shortbytes ::= \"\\'\" shortbytesitem* \"\\'\" | \\'\"\\' shortbytesitem* \\'\"\\'\\n longbytes ::= \"\\'\\'\\'\" longbytesitem* \"\\'\\'\\'\" | \\'\"\"\"\\' longbytesitem* \\'\"\"\"\\'\\n shortbytesitem ::= shortbyteschar | bytesescapeseq\\n longbytesitem ::= longbyteschar | bytesescapeseq\\n shortbyteschar ::= <any ASCII character except \"\\\\\" or newline or the quote>\\n longbyteschar ::= <any ASCII character except \"\\\\\">\\n bytesescapeseq ::= \"\\\\\" <any ASCII character>\\n\\nOne syntactic restriction not indicated by these productions is that\\nwhitespace is not allowed between the ``stringprefix`` or\\n``bytesprefix`` and the rest of the literal. The source character set\\nis defined by the encoding declaration; it is UTF-8 if no encoding\\ndeclaration is given in the source file; see section *Encoding\\ndeclarations*.\\n\\nIn plain English: Both types of literals can be enclosed in matching\\nsingle quotes (``\\'``) or double quotes (``\"``). They can also be\\nenclosed in matching groups of three single or double quotes (these\\nare generally referred to as *triple-quoted strings*). The backslash\\n(``\\\\``) character is used to escape characters that otherwise have a\\nspecial meaning, such as newline, backslash itself, or the quote\\ncharacter.\\n\\nBytes literals are always prefixed with ``\\'b\\'`` or ``\\'B\\'``; they\\nproduce an instance of the ``bytes`` type instead of the ``str`` type.\\nThey may only contain ASCII characters; bytes with a numeric value of\\n128 or greater must be expressed with escapes.\\n\\nAs of Python 3.3 it is possible again to prefix unicode strings with a\\n``u`` prefix to simplify maintenance of dual 2.x and 3.x codebases.\\n\\nBoth string and bytes literals may optionally be prefixed with a\\nletter ``\\'r\\'`` or ``\\'R\\'``; such strings are called *raw strings* and\\ntreat backslashes as literal characters. As a result, in string\\nliterals, ``\\'\\\\U\\'`` and ``\\'\\\\u\\'`` escapes in raw strings are not treated\\nspecially. Given that Python 2.x\\'s raw unicode literals behave\\ndifferently than Python 3.x\\'s the ``\\'ur\\'`` syntax is not supported.\\n\\n New in version 3.3: The ``\\'rb\\'`` prefix of raw bytes literals has\\n been added as a synonym of ``\\'br\\'``.\\n\\n New in version 3.3: Support for the unicode legacy literal\\n (``u\\'value\\'``) was reintroduced to simplify the maintenance of dual\\n Python 2.x and 3.x codebases. See **PEP 414** for more information.\\n\\nIn triple-quoted strings, unescaped newlines and quotes are allowed\\n(and are retained), except that three unescaped quotes in a row\\nterminate the string. (A \"quote\" is the character used to open the\\nstring, i.e. either ``\\'`` or ``\"``.)\\n\\nUnless an ``\\'r\\'`` or ``\\'R\\'`` prefix is present, escape sequences in\\nstrings are interpreted according to rules similar to those used by\\nStandard C. The recognized escape sequences are:\\n\\n+-------------------+-----------------------------------+---------+\\n| Escape Sequence | Meaning | Notes |\\n+===================+===================================+=========+\\n| ``\\\\newline`` | Backslash and newline ignored | |\\n+-------------------+-----------------------------------+---------+\\n| ``\\\\\\\\`` | Backslash (``\\\\``) | |\\n+-------------------+-----------------------------------+---------+\\n| ``\\\\\\'`` | Single quote (``\\'``) | |\\n+-------------------+-----------------------------------+---------+\\n| ``\\\\\"`` | Double quote (``\"``) | |\\n+-------------------+-----------------------------------+---------+\\n| ``\\\\a`` | ASCII Bell (BEL) | |\\n+-------------------+-----------------------------------+---------+\\n| ``\\\\b`` | ASCII Backspace (BS) | |\\n+-------------------+-----------------------------------+---------+\\n| ``\\\\f`` | ASCII Formfeed (FF) | |\\n+-------------------+-----------------------------------+---------+\\n| ``\\\\n`` | ASCII Linefeed (LF) | |\\n+-------------------+-----------------------------------+---------+\\n| ``\\\\r`` | ASCII Carriage Return (CR) | |\\n+-------------------+-----------------------------------+---------+\\n| ``\\\\t`` | ASCII Horizontal Tab (TAB) | |\\n+-------------------+-----------------------------------+---------+\\n| ``\\\\v`` | ASCII Vertical Tab (VT) | |\\n+-------------------+-----------------------------------+---------+\\n| ``\\\\ooo`` | Character with octal value *ooo* | (1,3) |\\n+-------------------+-----------------------------------+---------+\\n| ``\\\\xhh`` | Character with hex value *hh* | (2,3) |\\n+-------------------+-----------------------------------+---------+\\n\\nEscape sequences only recognized in string literals are:\\n\\n+-------------------+-----------------------------------+---------+\\n| Escape Sequence | Meaning | Notes |\\n+===================+===================================+=========+\\n| ``\\\\N{name}`` | Character named *name* in the | (4) |\\n| | Unicode database | |\\n+-------------------+-----------------------------------+---------+\\n| ``\\\\uxxxx`` | Character with 16-bit hex value | (5) |\\n| | *xxxx* | |\\n+-------------------+-----------------------------------+---------+\\n| ``\\\\Uxxxxxxxx`` | Character with 32-bit hex value | (6) |\\n| | *xxxxxxxx* | |\\n+-------------------+-----------------------------------+---------+\\n\\nNotes:\\n\\n1. As in Standard C, up to three octal digits are accepted.\\n\\n2. Unlike in Standard C, exactly two hex digits are required.\\n\\n3. In a bytes literal, hexadecimal and octal escapes denote the byte\\n with the given value. In a string literal, these escapes denote a\\n Unicode character with the given value.\\n\\n4. Changed in version 3.3: Support for name aliases [1] has been\\n added.\\n\\n5. Individual code units which form parts of a surrogate pair can be\\n encoded using this escape sequence. Exactly four hex digits are\\n required.\\n\\n6. Any Unicode character can be encoded this way. Exactly eight hex\\n digits are required.\\n\\nUnlike Standard C, all unrecognized escape sequences are left in the\\nstring unchanged, i.e., *the backslash is left in the string*. (This\\nbehavior is useful when debugging: if an escape sequence is mistyped,\\nthe resulting output is more easily recognized as broken.) It is also\\nimportant to note that the escape sequences only recognized in string\\nliterals fall into the category of unrecognized escapes for bytes\\nliterals.\\n\\nEven in a raw string, string quotes can be escaped with a backslash,\\nbut the backslash remains in the string; for example, ``r\"\\\\\"\"`` is a\\nvalid string literal consisting of two characters: a backslash and a\\ndouble quote; ``r\"\\\\\"`` is not a valid string literal (even a raw\\nstring cannot end in an odd number of backslashes). Specifically, *a\\nraw string cannot end in a single backslash* (since the backslash\\nwould escape the following quote character). Note also that a single\\nbackslash followed by a newline is interpreted as those two characters\\nas part of the string, *not* as a line continuation.\\n',\n'subscriptions':'\\nSubscriptions\\n*************\\n\\nA subscription selects an item of a sequence (string, tuple or list)\\nor mapping (dictionary) object:\\n\\n subscription ::= primary \"[\" expression_list \"]\"\\n\\nThe primary must evaluate to an object that supports subscription,\\ne.g. a list or dictionary. User-defined objects can support\\nsubscription by defining a ``__getitem__()`` method.\\n\\nFor built-in objects, there are two types of objects that support\\nsubscription:\\n\\nIf the primary is a mapping, the expression list must evaluate to an\\nobject whose value is one of the keys of the mapping, and the\\nsubscription selects the value in the mapping that corresponds to that\\nkey. (The expression list is a tuple except if it has exactly one\\nitem.)\\n\\nIf the primary is a sequence, the expression (list) must evaluate to\\nan integer or a slice (as discussed in the following section).\\n\\nThe formal syntax makes no special provision for negative indices in\\nsequences; however, built-in sequences all provide a ``__getitem__()``\\nmethod that interprets negative indices by adding the length of the\\nsequence to the index (so that ``x[-1]`` selects the last item of\\n``x``). The resulting value must be a nonnegative integer less than\\nthe number of items in the sequence, and the subscription selects the\\nitem whose index is that value (counting from zero). Since the support\\nfor negative indices and slicing occurs in the object\\'s\\n``__getitem__()`` method, subclasses overriding this method will need\\nto explicitly add that support.\\n\\nA string\\'s items are characters. A character is not a separate data\\ntype but a string of exactly one character.\\n',\n'truth':\"\\nTruth Value Testing\\n*******************\\n\\nAny object can be tested for truth value, for use in an ``if`` or\\n``while`` condition or as operand of the Boolean operations below. The\\nfollowing values are considered false:\\n\\n* ``None``\\n\\n* ``False``\\n\\n* zero of any numeric type, for example, ``0``, ``0.0``, ``0j``.\\n\\n* any empty sequence, for example, ``''``, ``()``, ``[]``.\\n\\n* any empty mapping, for example, ``{}``.\\n\\n* instances of user-defined classes, if the class defines a\\n ``__bool__()`` or ``__len__()`` method, when that method returns the\\n integer zero or ``bool`` value ``False``. [1]\\n\\nAll other values are considered true --- so objects of many types are\\nalways true.\\n\\nOperations and built-in functions that have a Boolean result always\\nreturn ``0`` or ``False`` for false and ``1`` or ``True`` for true,\\nunless otherwise stated. (Important exception: the Boolean operations\\n``or`` and ``and`` always return one of their operands.)\\n\",\n'try':'\\nThe ``try`` statement\\n*********************\\n\\nThe ``try`` statement specifies exception handlers and/or cleanup code\\nfor a group of statements:\\n\\n try_stmt ::= try1_stmt | try2_stmt\\n try1_stmt ::= \"try\" \":\" suite\\n (\"except\" [expression [\"as\" target]] \":\" suite)+\\n [\"else\" \":\" suite]\\n [\"finally\" \":\" suite]\\n try2_stmt ::= \"try\" \":\" suite\\n \"finally\" \":\" suite\\n\\nThe ``except`` clause(s) specify one or more exception handlers. When\\nno exception occurs in the ``try`` clause, no exception handler is\\nexecuted. When an exception occurs in the ``try`` suite, a search for\\nan exception handler is started. This search inspects the except\\nclauses in turn until one is found that matches the exception. An\\nexpression-less except clause, if present, must be last; it matches\\nany exception. For an except clause with an expression, that\\nexpression is evaluated, and the clause matches the exception if the\\nresulting object is \"compatible\" with the exception. An object is\\ncompatible with an exception if it is the class or a base class of the\\nexception object or a tuple containing an item compatible with the\\nexception.\\n\\nIf no except clause matches the exception, the search for an exception\\nhandler continues in the surrounding code and on the invocation stack.\\n[1]\\n\\nIf the evaluation of an expression in the header of an except clause\\nraises an exception, the original search for a handler is canceled and\\na search starts for the new exception in the surrounding code and on\\nthe call stack (it is treated as if the entire ``try`` statement\\nraised the exception).\\n\\nWhen a matching except clause is found, the exception is assigned to\\nthe target specified after the ``as`` keyword in that except clause,\\nif present, and the except clause\\'s suite is executed. All except\\nclauses must have an executable block. When the end of this block is\\nreached, execution continues normally after the entire try statement.\\n(This means that if two nested handlers exist for the same exception,\\nand the exception occurs in the try clause of the inner handler, the\\nouter handler will not handle the exception.)\\n\\nWhen an exception has been assigned using ``as target``, it is cleared\\nat the end of the except clause. This is as if\\n\\n except E as N:\\n foo\\n\\nwas translated to\\n\\n except E as N:\\n try:\\n foo\\n finally:\\n del N\\n\\nThis means the exception must be assigned to a different name to be\\nable to refer to it after the except clause. Exceptions are cleared\\nbecause with the traceback attached to them, they form a reference\\ncycle with the stack frame, keeping all locals in that frame alive\\nuntil the next garbage collection occurs.\\n\\nBefore an except clause\\'s suite is executed, details about the\\nexception are stored in the ``sys`` module and can be access via\\n``sys.exc_info()``. ``sys.exc_info()`` returns a 3-tuple consisting of\\nthe exception class, the exception instance and a traceback object\\n(see section *The standard type hierarchy*) identifying the point in\\nthe program where the exception occurred. ``sys.exc_info()`` values\\nare restored to their previous values (before the call) when returning\\nfrom a function that handled an exception.\\n\\nThe optional ``else`` clause is executed if and when control flows off\\nthe end of the ``try`` clause. [2] Exceptions in the ``else`` clause\\nare not handled by the preceding ``except`` clauses.\\n\\nIf ``finally`` is present, it specifies a \\'cleanup\\' handler. The\\n``try`` clause is executed, including any ``except`` and ``else``\\nclauses. If an exception occurs in any of the clauses and is not\\nhandled, the exception is temporarily saved. The ``finally`` clause is\\nexecuted. If there is a saved exception it is re-raised at the end of\\nthe ``finally`` clause. If the ``finally`` clause raises another\\nexception, the saved exception is set as the context of the new\\nexception. If the ``finally`` clause executes a ``return`` or\\n``break`` statement, the saved exception is discarded:\\n\\n def f():\\n try:\\n 1/0\\n finally:\\n return 42\\n\\n >>> f()\\n 42\\n\\nThe exception information is not available to the program during\\nexecution of the ``finally`` clause.\\n\\nWhen a ``return``, ``break`` or ``continue`` statement is executed in\\nthe ``try`` suite of a ``try``...``finally`` statement, the\\n``finally`` clause is also executed \\'on the way out.\\' A ``continue``\\nstatement is illegal in the ``finally`` clause. (The reason is a\\nproblem with the current implementation --- this restriction may be\\nlifted in the future).\\n\\nAdditional information on exceptions can be found in section\\n*Exceptions*, and information on using the ``raise`` statement to\\ngenerate exceptions may be found in section *The raise statement*.\\n',\n'types':'\\nThe standard type hierarchy\\n***************************\\n\\nBelow is a list of the types that are built into Python. Extension\\nmodules (written in C, Java, or other languages, depending on the\\nimplementation) can define additional types. Future versions of\\nPython may add types to the type hierarchy (e.g., rational numbers,\\nefficiently stored arrays of integers, etc.), although such additions\\nwill often be provided via the standard library instead.\\n\\nSome of the type descriptions below contain a paragraph listing\\n\\'special attributes.\\' These are attributes that provide access to the\\nimplementation and are not intended for general use. Their definition\\nmay change in the future.\\n\\nNone\\n This type has a single value. There is a single object with this\\n value. This object is accessed through the built-in name ``None``.\\n It is used to signify the absence of a value in many situations,\\n e.g., it is returned from functions that don\\'t explicitly return\\n anything. Its truth value is false.\\n\\nNotImplemented\\n This type has a single value. There is a single object with this\\n value. This object is accessed through the built-in name\\n ``NotImplemented``. Numeric methods and rich comparison methods may\\n return this value if they do not implement the operation for the\\n operands provided. (The interpreter will then try the reflected\\n operation, or some other fallback, depending on the operator.) Its\\n truth value is true.\\n\\nEllipsis\\n This type has a single value. There is a single object with this\\n value. This object is accessed through the literal ``...`` or the\\n built-in name ``Ellipsis``. Its truth value is true.\\n\\n``numbers.Number``\\n These are created by numeric literals and returned as results by\\n arithmetic operators and arithmetic built-in functions. Numeric\\n objects are immutable; once created their value never changes.\\n Python numbers are of course strongly related to mathematical\\n numbers, but subject to the limitations of numerical representation\\n in computers.\\n\\n Python distinguishes between integers, floating point numbers, and\\n complex numbers:\\n\\n ``numbers.Integral``\\n These represent elements from the mathematical set of integers\\n (positive and negative).\\n\\n There are two types of integers:\\n\\n Integers (``int``)\\n\\n These represent numbers in an unlimited range, subject to\\n available (virtual) memory only. For the purpose of shift\\n and mask operations, a binary representation is assumed, and\\n negative numbers are represented in a variant of 2\\'s\\n complement which gives the illusion of an infinite string of\\n sign bits extending to the left.\\n\\n Booleans (``bool``)\\n These represent the truth values False and True. The two\\n objects representing the values False and True are the only\\n Boolean objects. The Boolean type is a subtype of the integer\\n type, and Boolean values behave like the values 0 and 1,\\n respectively, in almost all contexts, the exception being\\n that when converted to a string, the strings ``\"False\"`` or\\n ``\"True\"`` are returned, respectively.\\n\\n The rules for integer representation are intended to give the\\n most meaningful interpretation of shift and mask operations\\n involving negative integers.\\n\\n ``numbers.Real`` (``float``)\\n These represent machine-level double precision floating point\\n numbers. You are at the mercy of the underlying machine\\n architecture (and C or Java implementation) for the accepted\\n range and handling of overflow. Python does not support single-\\n precision floating point numbers; the savings in processor and\\n memory usage that are usually the reason for using these is\\n dwarfed by the overhead of using objects in Python, so there is\\n no reason to complicate the language with two kinds of floating\\n point numbers.\\n\\n ``numbers.Complex`` (``complex``)\\n These represent complex numbers as a pair of machine-level\\n double precision floating point numbers. The same caveats apply\\n as for floating point numbers. The real and imaginary parts of a\\n complex number ``z`` can be retrieved through the read-only\\n attributes ``z.real`` and ``z.imag``.\\n\\nSequences\\n These represent finite ordered sets indexed by non-negative\\n numbers. The built-in function ``len()`` returns the number of\\n items of a sequence. When the length of a sequence is *n*, the\\n index set contains the numbers 0, 1, ..., *n*-1. Item *i* of\\n sequence *a* is selected by ``a[i]``.\\n\\n Sequences also support slicing: ``a[i:j]`` selects all items with\\n index *k* such that *i* ``<=`` *k* ``<`` *j*. When used as an\\n expression, a slice is a sequence of the same type. This implies\\n that the index set is renumbered so that it starts at 0.\\n\\n Some sequences also support \"extended slicing\" with a third \"step\"\\n parameter: ``a[i:j:k]`` selects all items of *a* with index *x*\\n where ``x = i + n*k``, *n* ``>=`` ``0`` and *i* ``<=`` *x* ``<``\\n *j*.\\n\\n Sequences are distinguished according to their mutability:\\n\\n Immutable sequences\\n An object of an immutable sequence type cannot change once it is\\n created. (If the object contains references to other objects,\\n these other objects may be mutable and may be changed; however,\\n the collection of objects directly referenced by an immutable\\n object cannot change.)\\n\\n The following types are immutable sequences:\\n\\n Strings\\n A string is a sequence of values that represent Unicode\\n codepoints. All the codepoints in range ``U+0000 - U+10FFFF``\\n can be represented in a string. Python doesn\\'t have a\\n ``chr`` type, and every character in the string is\\n represented as a string object with length ``1``. The built-\\n in function ``ord()`` converts a character to its codepoint\\n (as an integer); ``chr()`` converts an integer in range ``0 -\\n 10FFFF`` to the corresponding character. ``str.encode()`` can\\n be used to convert a ``str`` to ``bytes`` using the given\\n encoding, and ``bytes.decode()`` can be used to achieve the\\n opposite.\\n\\n Tuples\\n The items of a tuple are arbitrary Python objects. Tuples of\\n two or more items are formed by comma-separated lists of\\n expressions. A tuple of one item (a \\'singleton\\') can be\\n formed by affixing a comma to an expression (an expression by\\n itself does not create a tuple, since parentheses must be\\n usable for grouping of expressions). An empty tuple can be\\n formed by an empty pair of parentheses.\\n\\n Bytes\\n A bytes object is an immutable array. The items are 8-bit\\n bytes, represented by integers in the range 0 <= x < 256.\\n Bytes literals (like ``b\\'abc\\'``) and the built-in function\\n ``bytes()`` can be used to construct bytes objects. Also,\\n bytes objects can be decoded to strings via the ``decode()``\\n method.\\n\\n Mutable sequences\\n Mutable sequences can be changed after they are created. The\\n subscription and slicing notations can be used as the target of\\n assignment and ``del`` (delete) statements.\\n\\n There are currently two intrinsic mutable sequence types:\\n\\n Lists\\n The items of a list are arbitrary Python objects. Lists are\\n formed by placing a comma-separated list of expressions in\\n square brackets. (Note that there are no special cases needed\\n to form lists of length 0 or 1.)\\n\\n Byte Arrays\\n A bytearray object is a mutable array. They are created by\\n the built-in ``bytearray()`` constructor. Aside from being\\n mutable (and hence unhashable), byte arrays otherwise provide\\n the same interface and functionality as immutable bytes\\n objects.\\n\\n The extension module ``array`` provides an additional example of\\n a mutable sequence type, as does the ``collections`` module.\\n\\nSet types\\n These represent unordered, finite sets of unique, immutable\\n objects. As such, they cannot be indexed by any subscript. However,\\n they can be iterated over, and the built-in function ``len()``\\n returns the number of items in a set. Common uses for sets are fast\\n membership testing, removing duplicates from a sequence, and\\n computing mathematical operations such as intersection, union,\\n difference, and symmetric difference.\\n\\n For set elements, the same immutability rules apply as for\\n dictionary keys. Note that numeric types obey the normal rules for\\n numeric comparison: if two numbers compare equal (e.g., ``1`` and\\n ``1.0``), only one of them can be contained in a set.\\n\\n There are currently two intrinsic set types:\\n\\n Sets\\n These represent a mutable set. They are created by the built-in\\n ``set()`` constructor and can be modified afterwards by several\\n methods, such as ``add()``.\\n\\n Frozen sets\\n These represent an immutable set. They are created by the\\n built-in ``frozenset()`` constructor. As a frozenset is\\n immutable and *hashable*, it can be used again as an element of\\n another set, or as a dictionary key.\\n\\nMappings\\n These represent finite sets of objects indexed by arbitrary index\\n sets. The subscript notation ``a[k]`` selects the item indexed by\\n ``k`` from the mapping ``a``; this can be used in expressions and\\n as the target of assignments or ``del`` statements. The built-in\\n function ``len()`` returns the number of items in a mapping.\\n\\n There is currently a single intrinsic mapping type:\\n\\n Dictionaries\\n These represent finite sets of objects indexed by nearly\\n arbitrary values. The only types of values not acceptable as\\n keys are values containing lists or dictionaries or other\\n mutable types that are compared by value rather than by object\\n identity, the reason being that the efficient implementation of\\n dictionaries requires a key\\'s hash value to remain constant.\\n Numeric types used for keys obey the normal rules for numeric\\n comparison: if two numbers compare equal (e.g., ``1`` and\\n ``1.0``) then they can be used interchangeably to index the same\\n dictionary entry.\\n\\n Dictionaries are mutable; they can be created by the ``{...}``\\n notation (see section *Dictionary displays*).\\n\\n The extension modules ``dbm.ndbm`` and ``dbm.gnu`` provide\\n additional examples of mapping types, as does the\\n ``collections`` module.\\n\\nCallable types\\n These are the types to which the function call operation (see\\n section *Calls*) can be applied:\\n\\n User-defined functions\\n A user-defined function object is created by a function\\n definition (see section *Function definitions*). It should be\\n called with an argument list containing the same number of items\\n as the function\\'s formal parameter list.\\n\\n Special attributes:\\n\\n +---------------------------+---------------------------------+-------------+\\n | Attribute | Meaning | |\\n +===========================+=================================+=============+\\n | ``__doc__`` | The function\\'s documentation | Writable |\\n | | string, or ``None`` if | |\\n | | unavailable | |\\n +---------------------------+---------------------------------+-------------+\\n | ``__name__`` | The function\\'s name | Writable |\\n +---------------------------+---------------------------------+-------------+\\n | ``__qualname__`` | The function\\'s *qualified name* | Writable |\\n | | New in version 3.3. | |\\n +---------------------------+---------------------------------+-------------+\\n | ``__module__`` | The name of the module the | Writable |\\n | | function was defined in, or | |\\n | | ``None`` if unavailable. | |\\n +---------------------------+---------------------------------+-------------+\\n | ``__defaults__`` | A tuple containing default | Writable |\\n | | argument values for those | |\\n | | arguments that have defaults, | |\\n | | or ``None`` if no arguments | |\\n | | have a default value | |\\n +---------------------------+---------------------------------+-------------+\\n | ``__code__`` | The code object representing | Writable |\\n | | the compiled function body. | |\\n +---------------------------+---------------------------------+-------------+\\n | ``__globals__`` | A reference to the dictionary | Read-only |\\n | | that holds the function\\'s | |\\n | | global variables --- the global | |\\n | | namespace of the module in | |\\n | | which the function was defined. | |\\n +---------------------------+---------------------------------+-------------+\\n | ``__dict__`` | The namespace supporting | Writable |\\n | | arbitrary function attributes. | |\\n +---------------------------+---------------------------------+-------------+\\n | ``__closure__`` | ``None`` or a tuple of cells | Read-only |\\n | | that contain bindings for the | |\\n | | function\\'s free variables. | |\\n +---------------------------+---------------------------------+-------------+\\n | ``__annotations__`` | A dict containing annotations | Writable |\\n | | of parameters. The keys of the | |\\n | | dict are the parameter names, | |\\n | | or ``\\'return\\'`` for the return | |\\n | | annotation, if provided. | |\\n +---------------------------+---------------------------------+-------------+\\n | ``__kwdefaults__`` | A dict containing defaults for | Writable |\\n | | keyword-only parameters. | |\\n +---------------------------+---------------------------------+-------------+\\n\\n Most of the attributes labelled \"Writable\" check the type of the\\n assigned value.\\n\\n Function objects also support getting and setting arbitrary\\n attributes, which can be used, for example, to attach metadata\\n to functions. Regular attribute dot-notation is used to get and\\n set such attributes. *Note that the current implementation only\\n supports function attributes on user-defined functions. Function\\n attributes on built-in functions may be supported in the\\n future.*\\n\\n Additional information about a function\\'s definition can be\\n retrieved from its code object; see the description of internal\\n types below.\\n\\n Instance methods\\n An instance method object combines a class, a class instance and\\n any callable object (normally a user-defined function).\\n\\n Special read-only attributes: ``__self__`` is the class instance\\n object, ``__func__`` is the function object; ``__doc__`` is the\\n method\\'s documentation (same as ``__func__.__doc__``);\\n ``__name__`` is the method name (same as ``__func__.__name__``);\\n ``__module__`` is the name of the module the method was defined\\n in, or ``None`` if unavailable.\\n\\n Methods also support accessing (but not setting) the arbitrary\\n function attributes on the underlying function object.\\n\\n User-defined method objects may be created when getting an\\n attribute of a class (perhaps via an instance of that class), if\\n that attribute is a user-defined function object or a class\\n method object.\\n\\n When an instance method object is created by retrieving a user-\\n defined function object from a class via one of its instances,\\n its ``__self__`` attribute is the instance, and the method\\n object is said to be bound. The new method\\'s ``__func__``\\n attribute is the original function object.\\n\\n When a user-defined method object is created by retrieving\\n another method object from a class or instance, the behaviour is\\n the same as for a function object, except that the ``__func__``\\n attribute of the new instance is not the original method object\\n but its ``__func__`` attribute.\\n\\n When an instance method object is created by retrieving a class\\n method object from a class or instance, its ``__self__``\\n attribute is the class itself, and its ``__func__`` attribute is\\n the function object underlying the class method.\\n\\n When an instance method object is called, the underlying\\n function (``__func__``) is called, inserting the class instance\\n (``__self__``) in front of the argument list. For instance,\\n when ``C`` is a class which contains a definition for a function\\n ``f()``, and ``x`` is an instance of ``C``, calling ``x.f(1)``\\n is equivalent to calling ``C.f(x, 1)``.\\n\\n When an instance method object is derived from a class method\\n object, the \"class instance\" stored in ``__self__`` will\\n actually be the class itself, so that calling either ``x.f(1)``\\n or ``C.f(1)`` is equivalent to calling ``f(C,1)`` where ``f`` is\\n the underlying function.\\n\\n Note that the transformation from function object to instance\\n method object happens each time the attribute is retrieved from\\n the instance. In some cases, a fruitful optimization is to\\n assign the attribute to a local variable and call that local\\n variable. Also notice that this transformation only happens for\\n user-defined functions; other callable objects (and all non-\\n callable objects) are retrieved without transformation. It is\\n also important to note that user-defined functions which are\\n attributes of a class instance are not converted to bound\\n methods; this *only* happens when the function is an attribute\\n of the class.\\n\\n Generator functions\\n A function or method which uses the ``yield`` statement (see\\n section *The yield statement*) is called a *generator function*.\\n Such a function, when called, always returns an iterator object\\n which can be used to execute the body of the function: calling\\n the iterator\\'s ``iterator__next__()`` method will cause the\\n function to execute until it provides a value using the\\n ``yield`` statement. When the function executes a ``return``\\n statement or falls off the end, a ``StopIteration`` exception is\\n raised and the iterator will have reached the end of the set of\\n values to be returned.\\n\\n Built-in functions\\n A built-in function object is a wrapper around a C function.\\n Examples of built-in functions are ``len()`` and ``math.sin()``\\n (``math`` is a standard built-in module). The number and type of\\n the arguments are determined by the C function. Special read-\\n only attributes: ``__doc__`` is the function\\'s documentation\\n string, or ``None`` if unavailable; ``__name__`` is the\\n function\\'s name; ``__self__`` is set to ``None`` (but see the\\n next item); ``__module__`` is the name of the module the\\n function was defined in or ``None`` if unavailable.\\n\\n Built-in methods\\n This is really a different disguise of a built-in function, this\\n time containing an object passed to the C function as an\\n implicit extra argument. An example of a built-in method is\\n ``alist.append()``, assuming *alist* is a list object. In this\\n case, the special read-only attribute ``__self__`` is set to the\\n object denoted by *alist*.\\n\\n Classes\\n Classes are callable. These objects normally act as factories\\n for new instances of themselves, but variations are possible for\\n class types that override ``__new__()``. The arguments of the\\n call are passed to ``__new__()`` and, in the typical case, to\\n ``__init__()`` to initialize the new instance.\\n\\n Class Instances\\n Instances of arbitrary classes can be made callable by defining\\n a ``__call__()`` method in their class.\\n\\nModules\\n Modules are a basic organizational unit of Python code, and are\\n created by the *import system* as invoked either by the ``import``\\n statement (see ``import``), or by calling functions such as\\n ``importlib.import_module()`` and built-in ``__import__()``. A\\n module object has a namespace implemented by a dictionary object\\n (this is the dictionary referenced by the ``__globals__`` attribute\\n of functions defined in the module). Attribute references are\\n translated to lookups in this dictionary, e.g., ``m.x`` is\\n equivalent to ``m.__dict__[\"x\"]``. A module object does not contain\\n the code object used to initialize the module (since it isn\\'t\\n needed once the initialization is done).\\n\\n Attribute assignment updates the module\\'s namespace dictionary,\\n e.g., ``m.x = 1`` is equivalent to ``m.__dict__[\"x\"] = 1``.\\n\\n Special read-only attribute: ``__dict__`` is the module\\'s namespace\\n as a dictionary object.\\n\\n **CPython implementation detail:** Because of the way CPython\\n clears module dictionaries, the module dictionary will be cleared\\n when the module falls out of scope even if the dictionary still has\\n live references. To avoid this, copy the dictionary or keep the\\n module around while using its dictionary directly.\\n\\n Predefined (writable) attributes: ``__name__`` is the module\\'s\\n name; ``__doc__`` is the module\\'s documentation string, or ``None``\\n if unavailable; ``__file__`` is the pathname of the file from which\\n the module was loaded, if it was loaded from a file. The\\n ``__file__`` attribute may be missing for certain types of modules,\\n such as C modules that are statically linked into the interpreter;\\n for extension modules loaded dynamically from a shared library, it\\n is the pathname of the shared library file.\\n\\nCustom classes\\n Custom class types are typically created by class definitions (see\\n section *Class definitions*). A class has a namespace implemented\\n by a dictionary object. Class attribute references are translated\\n to lookups in this dictionary, e.g., ``C.x`` is translated to\\n ``C.__dict__[\"x\"]`` (although there are a number of hooks which\\n allow for other means of locating attributes). When the attribute\\n name is not found there, the attribute search continues in the base\\n classes. This search of the base classes uses the C3 method\\n resolution order which behaves correctly even in the presence of\\n \\'diamond\\' inheritance structures where there are multiple\\n inheritance paths leading back to a common ancestor. Additional\\n details on the C3 MRO used by Python can be found in the\\n documentation accompanying the 2.3 release at\\n http://www.python.org/download/releases/2.3/mro/.\\n\\n When a class attribute reference (for class ``C``, say) would yield\\n a class method object, it is transformed into an instance method\\n object whose ``__self__`` attributes is ``C``. When it would yield\\n a static method object, it is transformed into the object wrapped\\n by the static method object. See section *Implementing Descriptors*\\n for another way in which attributes retrieved from a class may\\n differ from those actually contained in its ``__dict__``.\\n\\n Class attribute assignments update the class\\'s dictionary, never\\n the dictionary of a base class.\\n\\n A class object can be called (see above) to yield a class instance\\n (see below).\\n\\n Special attributes: ``__name__`` is the class name; ``__module__``\\n is the module name in which the class was defined; ``__dict__`` is\\n the dictionary containing the class\\'s namespace; ``__bases__`` is a\\n tuple (possibly empty or a singleton) containing the base classes,\\n in the order of their occurrence in the base class list;\\n ``__doc__`` is the class\\'s documentation string, or None if\\n undefined.\\n\\nClass instances\\n A class instance is created by calling a class object (see above).\\n A class instance has a namespace implemented as a dictionary which\\n is the first place in which attribute references are searched.\\n When an attribute is not found there, and the instance\\'s class has\\n an attribute by that name, the search continues with the class\\n attributes. If a class attribute is found that is a user-defined\\n function object, it is transformed into an instance method object\\n whose ``__self__`` attribute is the instance. Static method and\\n class method objects are also transformed; see above under\\n \"Classes\". See section *Implementing Descriptors* for another way\\n in which attributes of a class retrieved via its instances may\\n differ from the objects actually stored in the class\\'s\\n ``__dict__``. If no class attribute is found, and the object\\'s\\n class has a ``__getattr__()`` method, that is called to satisfy the\\n lookup.\\n\\n Attribute assignments and deletions update the instance\\'s\\n dictionary, never a class\\'s dictionary. If the class has a\\n ``__setattr__()`` or ``__delattr__()`` method, this is called\\n instead of updating the instance dictionary directly.\\n\\n Class instances can pretend to be numbers, sequences, or mappings\\n if they have methods with certain special names. See section\\n *Special method names*.\\n\\n Special attributes: ``__dict__`` is the attribute dictionary;\\n ``__class__`` is the instance\\'s class.\\n\\nI/O objects (also known as file objects)\\n A *file object* represents an open file. Various shortcuts are\\n available to create file objects: the ``open()`` built-in function,\\n and also ``os.popen()``, ``os.fdopen()``, and the ``makefile()``\\n method of socket objects (and perhaps by other functions or methods\\n provided by extension modules).\\n\\n The objects ``sys.stdin``, ``sys.stdout`` and ``sys.stderr`` are\\n initialized to file objects corresponding to the interpreter\\'s\\n standard input, output and error streams; they are all open in text\\n mode and therefore follow the interface defined by the\\n ``io.TextIOBase`` abstract class.\\n\\nInternal types\\n A few types used internally by the interpreter are exposed to the\\n user. Their definitions may change with future versions of the\\n interpreter, but they are mentioned here for completeness.\\n\\n Code objects\\n Code objects represent *byte-compiled* executable Python code,\\n or *bytecode*. The difference between a code object and a\\n function object is that the function object contains an explicit\\n reference to the function\\'s globals (the module in which it was\\n defined), while a code object contains no context; also the\\n default argument values are stored in the function object, not\\n in the code object (because they represent values calculated at\\n run-time). Unlike function objects, code objects are immutable\\n and contain no references (directly or indirectly) to mutable\\n objects.\\n\\n Special read-only attributes: ``co_name`` gives the function\\n name; ``co_argcount`` is the number of positional arguments\\n (including arguments with default values); ``co_nlocals`` is the\\n number of local variables used by the function (including\\n arguments); ``co_varnames`` is a tuple containing the names of\\n the local variables (starting with the argument names);\\n ``co_cellvars`` is a tuple containing the names of local\\n variables that are referenced by nested functions;\\n ``co_freevars`` is a tuple containing the names of free\\n variables; ``co_code`` is a string representing the sequence of\\n bytecode instructions; ``co_consts`` is a tuple containing the\\n literals used by the bytecode; ``co_names`` is a tuple\\n containing the names used by the bytecode; ``co_filename`` is\\n the filename from which the code was compiled;\\n ``co_firstlineno`` is the first line number of the function;\\n ``co_lnotab`` is a string encoding the mapping from bytecode\\n offsets to line numbers (for details see the source code of the\\n interpreter); ``co_stacksize`` is the required stack size\\n (including local variables); ``co_flags`` is an integer encoding\\n a number of flags for the interpreter.\\n\\n The following flag bits are defined for ``co_flags``: bit\\n ``0x04`` is set if the function uses the ``*arguments`` syntax\\n to accept an arbitrary number of positional arguments; bit\\n ``0x08`` is set if the function uses the ``**keywords`` syntax\\n to accept arbitrary keyword arguments; bit ``0x20`` is set if\\n the function is a generator.\\n\\n Future feature declarations (``from __future__ import\\n division``) also use bits in ``co_flags`` to indicate whether a\\n code object was compiled with a particular feature enabled: bit\\n ``0x2000`` is set if the function was compiled with future\\n division enabled; bits ``0x10`` and ``0x1000`` were used in\\n earlier versions of Python.\\n\\n Other bits in ``co_flags`` are reserved for internal use.\\n\\n If a code object represents a function, the first item in\\n ``co_consts`` is the documentation string of the function, or\\n ``None`` if undefined.\\n\\n Frame objects\\n Frame objects represent execution frames. They may occur in\\n traceback objects (see below).\\n\\n Special read-only attributes: ``f_back`` is to the previous\\n stack frame (towards the caller), or ``None`` if this is the\\n bottom stack frame; ``f_code`` is the code object being executed\\n in this frame; ``f_locals`` is the dictionary used to look up\\n local variables; ``f_globals`` is used for global variables;\\n ``f_builtins`` is used for built-in (intrinsic) names;\\n ``f_lasti`` gives the precise instruction (this is an index into\\n the bytecode string of the code object).\\n\\n Special writable attributes: ``f_trace``, if not ``None``, is a\\n function called at the start of each source code line (this is\\n used by the debugger); ``f_lineno`` is the current line number\\n of the frame --- writing to this from within a trace function\\n jumps to the given line (only for the bottom-most frame). A\\n debugger can implement a Jump command (aka Set Next Statement)\\n by writing to f_lineno.\\n\\n Traceback objects\\n Traceback objects represent a stack trace of an exception. A\\n traceback object is created when an exception occurs. When the\\n search for an exception handler unwinds the execution stack, at\\n each unwound level a traceback object is inserted in front of\\n the current traceback. When an exception handler is entered,\\n the stack trace is made available to the program. (See section\\n *The try statement*.) It is accessible as the third item of the\\n tuple returned by ``sys.exc_info()``. When the program contains\\n no suitable handler, the stack trace is written (nicely\\n formatted) to the standard error stream; if the interpreter is\\n interactive, it is also made available to the user as\\n ``sys.last_traceback``.\\n\\n Special read-only attributes: ``tb_next`` is the next level in\\n the stack trace (towards the frame where the exception\\n occurred), or ``None`` if there is no next level; ``tb_frame``\\n points to the execution frame of the current level;\\n ``tb_lineno`` gives the line number where the exception\\n occurred; ``tb_lasti`` indicates the precise instruction. The\\n line number and last instruction in the traceback may differ\\n from the line number of its frame object if the exception\\n occurred in a ``try`` statement with no matching except clause\\n or with a finally clause.\\n\\n Slice objects\\n Slice objects are used to represent slices for ``__getitem__()``\\n methods. They are also created by the built-in ``slice()``\\n function.\\n\\n Special read-only attributes: ``start`` is the lower bound;\\n ``stop`` is the upper bound; ``step`` is the step value; each is\\n ``None`` if omitted. These attributes can have any type.\\n\\n Slice objects support one method:\\n\\n slice.indices(self, length)\\n\\n This method takes a single integer argument *length* and\\n computes information about the slice that the slice object\\n would describe if applied to a sequence of *length* items.\\n It returns a tuple of three integers; respectively these are\\n the *start* and *stop* indices and the *step* or stride\\n length of the slice. Missing or out-of-bounds indices are\\n handled in a manner consistent with regular slices.\\n\\n Static method objects\\n Static method objects provide a way of defeating the\\n transformation of function objects to method objects described\\n above. A static method object is a wrapper around any other\\n object, usually a user-defined method object. When a static\\n method object is retrieved from a class or a class instance, the\\n object actually returned is the wrapped object, which is not\\n subject to any further transformation. Static method objects are\\n not themselves callable, although the objects they wrap usually\\n are. Static method objects are created by the built-in\\n ``staticmethod()`` constructor.\\n\\n Class method objects\\n A class method object, like a static method object, is a wrapper\\n around another object that alters the way in which that object\\n is retrieved from classes and class instances. The behaviour of\\n class method objects upon such retrieval is described above,\\n under \"User-defined methods\". Class method objects are created\\n by the built-in ``classmethod()`` constructor.\\n',\n'typesfunctions':'\\nFunctions\\n*********\\n\\nFunction objects are created by function definitions. The only\\noperation on a function object is to call it: ``func(argument-list)``.\\n\\nThere are really two flavors of function objects: built-in functions\\nand user-defined functions. Both support the same operation (to call\\nthe function), but the implementation is different, hence the\\ndifferent object types.\\n\\nSee *Function definitions* for more information.\\n',\n'typesmapping':'\\nMapping Types --- ``dict``\\n**************************\\n\\nA *mapping* object maps *hashable* values to arbitrary objects.\\nMappings are mutable objects. There is currently only one standard\\nmapping type, the *dictionary*. (For other containers see the built-\\nin ``list``, ``set``, and ``tuple`` classes, and the ``collections``\\nmodule.)\\n\\nA dictionary\\'s keys are *almost* arbitrary values. Values that are\\nnot *hashable*, that is, values containing lists, dictionaries or\\nother mutable types (that are compared by value rather than by object\\nidentity) may not be used as keys. Numeric types used for keys obey\\nthe normal rules for numeric comparison: if two numbers compare equal\\n(such as ``1`` and ``1.0``) then they can be used interchangeably to\\nindex the same dictionary entry. (Note however, that since computers\\nstore floating-point numbers as approximations it is usually unwise to\\nuse them as dictionary keys.)\\n\\nDictionaries can be created by placing a comma-separated list of\\n``key: value`` pairs within braces, for example: ``{\\'jack\\': 4098,\\n\\'sjoerd\\': 4127}`` or ``{4098: \\'jack\\', 4127: \\'sjoerd\\'}``, or by the\\n``dict`` constructor.\\n\\nclass class dict(**kwarg)\\nclass class dict(mapping, **kwarg)\\nclass class dict(iterable, **kwarg)\\n\\n Return a new dictionary initialized from an optional positional\\n argument and a possibly empty set of keyword arguments.\\n\\n If no positional argument is given, an empty dictionary is created.\\n If a positional argument is given and it is a mapping object, a\\n dictionary is created with the same key-value pairs as the mapping\\n object. Otherwise, the positional argument must be an *iterator*\\n object. Each item in the iterable must itself be an iterator with\\n exactly two objects. The first object of each item becomes a key\\n in the new dictionary, and the second object the corresponding\\n value. If a key occurs more than once, the last value for that key\\n becomes the corresponding value in the new dictionary.\\n\\n If keyword arguments are given, the keyword arguments and their\\n values are added to the dictionary created from the positional\\n argument. If a key being added is already present, the value from\\n the keyword argument replaces the value from the positional\\n argument.\\n\\n To illustrate, the following examples all return a dictionary equal\\n to ``{\"one\": 1, \"two\": 2, \"three\": 3}``:\\n\\n >>> a = dict(one=1, two=2, three=3)\\n >>> b = {\\'one\\': 1, \\'two\\': 2, \\'three\\': 3}\\n >>> c = dict(zip([\\'one\\', \\'two\\', \\'three\\'], [1, 2, 3]))\\n >>> d = dict([(\\'two\\', 2), (\\'one\\', 1), (\\'three\\', 3)])\\n >>> e = dict({\\'three\\': 3, \\'one\\': 1, \\'two\\': 2})\\n >>> a == b == c == d == e\\n True\\n\\n Providing keyword arguments as in the first example only works for\\n keys that are valid Python identifiers. Otherwise, any valid keys\\n can be used.\\n\\n These are the operations that dictionaries support (and therefore,\\n custom mapping types should support too):\\n\\n len(d)\\n\\n Return the number of items in the dictionary *d*.\\n\\n d[key]\\n\\n Return the item of *d* with key *key*. Raises a ``KeyError`` if\\n *key* is not in the map.\\n\\n If a subclass of dict defines a method ``__missing__()``, if the\\n key *key* is not present, the ``d[key]`` operation calls that\\n method with the key *key* as argument. The ``d[key]`` operation\\n then returns or raises whatever is returned or raised by the\\n ``__missing__(key)`` call if the key is not present. No other\\n operations or methods invoke ``__missing__()``. If\\n ``__missing__()`` is not defined, ``KeyError`` is raised.\\n ``__missing__()`` must be a method; it cannot be an instance\\n variable:\\n\\n >>> class Counter(dict):\\n ... def __missing__(self, key):\\n ... return 0\\n >>> c = Counter()\\n >>> c[\\'red\\']\\n 0\\n >>> c[\\'red\\'] += 1\\n >>> c[\\'red\\']\\n 1\\n\\n See ``collections.Counter`` for a complete implementation\\n including other methods helpful for accumulating and managing\\n tallies.\\n\\n d[key] = value\\n\\n Set ``d[key]`` to *value*.\\n\\n del d[key]\\n\\n Remove ``d[key]`` from *d*. Raises a ``KeyError`` if *key* is\\n not in the map.\\n\\n key in d\\n\\n Return ``True`` if *d* has a key *key*, else ``False``.\\n\\n key not in d\\n\\n Equivalent to ``not key in d``.\\n\\n iter(d)\\n\\n Return an iterator over the keys of the dictionary. This is a\\n shortcut for ``iter(d.keys())``.\\n\\n clear()\\n\\n Remove all items from the dictionary.\\n\\n copy()\\n\\n Return a shallow copy of the dictionary.\\n\\n classmethod fromkeys(seq[, value])\\n\\n Create a new dictionary with keys from *seq* and values set to\\n *value*.\\n\\n ``fromkeys()`` is a class method that returns a new dictionary.\\n *value* defaults to ``None``.\\n\\n get(key[, default])\\n\\n Return the value for *key* if *key* is in the dictionary, else\\n *default*. If *default* is not given, it defaults to ``None``,\\n so that this method never raises a ``KeyError``.\\n\\n items()\\n\\n Return a new view of the dictionary\\'s items (``(key, value)``\\n pairs). See the *documentation of view objects*.\\n\\n keys()\\n\\n Return a new view of the dictionary\\'s keys. See the\\n *documentation of view objects*.\\n\\n pop(key[, default])\\n\\n If *key* is in the dictionary, remove it and return its value,\\n else return *default*. If *default* is not given and *key* is\\n not in the dictionary, a ``KeyError`` is raised.\\n\\n popitem()\\n\\n Remove and return an arbitrary ``(key, value)`` pair from the\\n dictionary.\\n\\n ``popitem()`` is useful to destructively iterate over a\\n dictionary, as often used in set algorithms. If the dictionary\\n is empty, calling ``popitem()`` raises a ``KeyError``.\\n\\n setdefault(key[, default])\\n\\n If *key* is in the dictionary, return its value. If not, insert\\n *key* with a value of *default* and return *default*. *default*\\n defaults to ``None``.\\n\\n update([other])\\n\\n Update the dictionary with the key/value pairs from *other*,\\n overwriting existing keys. Return ``None``.\\n\\n ``update()`` accepts either another dictionary object or an\\n iterable of key/value pairs (as tuples or other iterables of\\n length two). If keyword arguments are specified, the dictionary\\n is then updated with those key/value pairs: ``d.update(red=1,\\n blue=2)``.\\n\\n values()\\n\\n Return a new view of the dictionary\\'s values. See the\\n *documentation of view objects*.\\n\\nSee also:\\n\\n ``types.MappingProxyType`` can be used to create a read-only view\\n of a ``dict``.\\n\\n\\nDictionary view objects\\n=======================\\n\\nThe objects returned by ``dict.keys()``, ``dict.values()`` and\\n``dict.items()`` are *view objects*. They provide a dynamic view on\\nthe dictionary\\'s entries, which means that when the dictionary\\nchanges, the view reflects these changes.\\n\\nDictionary views can be iterated over to yield their respective data,\\nand support membership tests:\\n\\nlen(dictview)\\n\\n Return the number of entries in the dictionary.\\n\\niter(dictview)\\n\\n Return an iterator over the keys, values or items (represented as\\n tuples of ``(key, value)``) in the dictionary.\\n\\n Keys and values are iterated over in an arbitrary order which is\\n non-random, varies across Python implementations, and depends on\\n the dictionary\\'s history of insertions and deletions. If keys,\\n values and items views are iterated over with no intervening\\n modifications to the dictionary, the order of items will directly\\n correspond. This allows the creation of ``(value, key)`` pairs\\n using ``zip()``: ``pairs = zip(d.values(), d.keys())``. Another\\n way to create the same list is ``pairs = [(v, k) for (k, v) in\\n d.items()]``.\\n\\n Iterating views while adding or deleting entries in the dictionary\\n may raise a ``RuntimeError`` or fail to iterate over all entries.\\n\\nx in dictview\\n\\n Return ``True`` if *x* is in the underlying dictionary\\'s keys,\\n values or items (in the latter case, *x* should be a ``(key,\\n value)`` tuple).\\n\\nKeys views are set-like since their entries are unique and hashable.\\nIf all values are hashable, so that ``(key, value)`` pairs are unique\\nand hashable, then the items view is also set-like. (Values views are\\nnot treated as set-like since the entries are generally not unique.)\\nFor set-like views, all of the operations defined for the abstract\\nbase class ``collections.abc.Set`` are available (for example, ``==``,\\n``<``, or ``^``).\\n\\nAn example of dictionary view usage:\\n\\n >>> dishes = {\\'eggs\\': 2, \\'sausage\\': 1, \\'bacon\\': 1, \\'spam\\': 500}\\n >>> keys = dishes.keys()\\n >>> values = dishes.values()\\n\\n >>> # iteration\\n >>> n = 0\\n >>> for val in values:\\n ... n += val\\n >>> print(n)\\n 504\\n\\n >>> # keys and values are iterated over in the same order\\n >>> list(keys)\\n [\\'eggs\\', \\'bacon\\', \\'sausage\\', \\'spam\\']\\n >>> list(values)\\n [2, 1, 1, 500]\\n\\n >>> # view objects are dynamic and reflect dict changes\\n >>> del dishes[\\'eggs\\']\\n >>> del dishes[\\'sausage\\']\\n >>> list(keys)\\n [\\'spam\\', \\'bacon\\']\\n\\n >>> # set operations\\n >>> keys & {\\'eggs\\', \\'bacon\\', \\'salad\\'}\\n {\\'bacon\\'}\\n >>> keys ^ {\\'sausage\\', \\'juice\\'}\\n {\\'juice\\', \\'sausage\\', \\'bacon\\', \\'spam\\'}\\n',\n'typesmethods':'\\nMethods\\n*******\\n\\nMethods are functions that are called using the attribute notation.\\nThere are two flavors: built-in methods (such as ``append()`` on\\nlists) and class instance methods. Built-in methods are described\\nwith the types that support them.\\n\\nIf you access a method (a function defined in a class namespace)\\nthrough an instance, you get a special object: a *bound method* (also\\ncalled *instance method*) object. When called, it will add the\\n``self`` argument to the argument list. Bound methods have two\\nspecial read-only attributes: ``m.__self__`` is the object on which\\nthe method operates, and ``m.__func__`` is the function implementing\\nthe method. Calling ``m(arg-1, arg-2, ..., arg-n)`` is completely\\nequivalent to calling ``m.__func__(m.__self__, arg-1, arg-2, ...,\\narg-n)``.\\n\\nLike function objects, bound method objects support getting arbitrary\\nattributes. However, since method attributes are actually stored on\\nthe underlying function object (``meth.__func__``), setting method\\nattributes on bound methods is disallowed. Attempting to set an\\nattribute on a method results in an ``AttributeError`` being raised.\\nIn order to set a method attribute, you need to explicitly set it on\\nthe underlying function object:\\n\\n >>> class C:\\n ... def method(self):\\n ... pass\\n ...\\n >>> c = C()\\n >>> c.method.whoami = \\'my name is method\\' # can\\'t set on the method\\n Traceback (most recent call last):\\n File \"<stdin>\", line 1, in <module>\\n AttributeError: \\'method\\' object has no attribute \\'whoami\\'\\n >>> c.method.__func__.whoami = \\'my name is method\\'\\n >>> c.method.whoami\\n \\'my name is method\\'\\n\\nSee *The standard type hierarchy* for more information.\\n',\n'typesmodules':\"\\nModules\\n*******\\n\\nThe only special operation on a module is attribute access:\\n``m.name``, where *m* is a module and *name* accesses a name defined\\nin *m*'s symbol table. Module attributes can be assigned to. (Note\\nthat the ``import`` statement is not, strictly speaking, an operation\\non a module object; ``import foo`` does not require a module object\\nnamed *foo* to exist, rather it requires an (external) *definition*\\nfor a module named *foo* somewhere.)\\n\\nA special attribute of every module is ``__dict__``. This is the\\ndictionary containing the module's symbol table. Modifying this\\ndictionary will actually change the module's symbol table, but direct\\nassignment to the ``__dict__`` attribute is not possible (you can\\nwrite ``m.__dict__['a'] = 1``, which defines ``m.a`` to be ``1``, but\\nyou can't write ``m.__dict__ = {}``). Modifying ``__dict__`` directly\\nis not recommended.\\n\\nModules built into the interpreter are written like this: ``<module\\n'sys' (built-in)>``. If loaded from a file, they are written as\\n``<module 'os' from '/usr/local/lib/pythonX.Y/os.pyc'>``.\\n\",\n'typesseq':'\\nSequence Types --- ``list``, ``tuple``, ``range``\\n*************************************************\\n\\nThere are three basic sequence types: lists, tuples, and range\\nobjects. Additional sequence types tailored for processing of *binary\\ndata* and *text strings* are described in dedicated sections.\\n\\n\\nCommon Sequence Operations\\n==========================\\n\\nThe operations in the following table are supported by most sequence\\ntypes, both mutable and immutable. The ``collections.abc.Sequence``\\nABC is provided to make it easier to correctly implement these\\noperations on custom sequence types.\\n\\nThis table lists the sequence operations sorted in ascending priority\\n(operations in the same box have the same priority). In the table,\\n*s* and *t* are sequences of the same type, *n*, *i*, *j* and *k* are\\nintegers and *x* is an arbitrary object that meets any type and value\\nrestrictions imposed by *s*.\\n\\nThe ``in`` and ``not in`` operations have the same priorities as the\\ncomparison operations. The ``+`` (concatenation) and ``*``\\n(repetition) operations have the same priority as the corresponding\\nnumeric operations.\\n\\n+----------------------------+----------------------------------+------------+\\n| Operation | Result | Notes |\\n+============================+==================================+============+\\n| ``x in s`` | ``True`` if an item of *s* is | (1) |\\n| | equal to *x*, else ``False`` | |\\n+----------------------------+----------------------------------+------------+\\n| ``x not in s`` | ``False`` if an item of *s* is | (1) |\\n| | equal to *x*, else ``True`` | |\\n+----------------------------+----------------------------------+------------+\\n| ``s + t`` | the concatenation of *s* and *t* | (6)(7) |\\n+----------------------------+----------------------------------+------------+\\n| ``s * n`` or ``n * s`` | *n* shallow copies of *s* | (2)(7) |\\n| | concatenated | |\\n+----------------------------+----------------------------------+------------+\\n| ``s[i]`` | *i*th item of *s*, origin 0 | (3) |\\n+----------------------------+----------------------------------+------------+\\n| ``s[i:j]`` | slice of *s* from *i* to *j* | (3)(4) |\\n+----------------------------+----------------------------------+------------+\\n| ``s[i:j:k]`` | slice of *s* from *i* to *j* | (3)(5) |\\n| | with step *k* | |\\n+----------------------------+----------------------------------+------------+\\n| ``len(s)`` | length of *s* | |\\n+----------------------------+----------------------------------+------------+\\n| ``min(s)`` | smallest item of *s* | |\\n+----------------------------+----------------------------------+------------+\\n| ``max(s)`` | largest item of *s* | |\\n+----------------------------+----------------------------------+------------+\\n| ``s.index(x[, i[, j]])`` | index of the first occurence of | (8) |\\n| | *x* in *s* (at or after index | |\\n| | *i* and before index *j*) | |\\n+----------------------------+----------------------------------+------------+\\n| ``s.count(x)`` | total number of occurences of | |\\n| | *x* in *s* | |\\n+----------------------------+----------------------------------+------------+\\n\\nSequences of the same type also support comparisons. In particular,\\ntuples and lists are compared lexicographically by comparing\\ncorresponding elements. This means that to compare equal, every\\nelement must compare equal and the two sequences must be of the same\\ntype and have the same length. (For full details see *Comparisons* in\\nthe language reference.)\\n\\nNotes:\\n\\n1. While the ``in`` and ``not in`` operations are used only for simple\\n containment testing in the general case, some specialised sequences\\n (such as ``str``, ``bytes`` and ``bytearray``) also use them for\\n subsequence testing:\\n\\n >>> \"gg\" in \"eggs\"\\n True\\n\\n2. Values of *n* less than ``0`` are treated as ``0`` (which yields an\\n empty sequence of the same type as *s*). Note also that the copies\\n are shallow; nested structures are not copied. This often haunts\\n new Python programmers; consider:\\n\\n >>> lists = [[]] * 3\\n >>> lists\\n [[], [], []]\\n >>> lists[0].append(3)\\n >>> lists\\n [[3], [3], [3]]\\n\\n What has happened is that ``[[]]`` is a one-element list containing\\n an empty list, so all three elements of ``[[]] * 3`` are (pointers\\n to) this single empty list. Modifying any of the elements of\\n ``lists`` modifies this single list. You can create a list of\\n different lists this way:\\n\\n >>> lists = [[] for i in range(3)]\\n >>> lists[0].append(3)\\n >>> lists[1].append(5)\\n >>> lists[2].append(7)\\n >>> lists\\n [[3], [5], [7]]\\n\\n3. If *i* or *j* is negative, the index is relative to the end of the\\n string: ``len(s) + i`` or ``len(s) + j`` is substituted. But note\\n that ``-0`` is still ``0``.\\n\\n4. The slice of *s* from *i* to *j* is defined as the sequence of\\n items with index *k* such that ``i <= k < j``. If *i* or *j* is\\n greater than ``len(s)``, use ``len(s)``. If *i* is omitted or\\n ``None``, use ``0``. If *j* is omitted or ``None``, use\\n ``len(s)``. If *i* is greater than or equal to *j*, the slice is\\n empty.\\n\\n5. The slice of *s* from *i* to *j* with step *k* is defined as the\\n sequence of items with index ``x = i + n*k`` such that ``0 <= n <\\n (j-i)/k``. In other words, the indices are ``i``, ``i+k``,\\n ``i+2*k``, ``i+3*k`` and so on, stopping when *j* is reached (but\\n never including *j*). If *i* or *j* is greater than ``len(s)``,\\n use ``len(s)``. If *i* or *j* are omitted or ``None``, they become\\n \"end\" values (which end depends on the sign of *k*). Note, *k*\\n cannot be zero. If *k* is ``None``, it is treated like ``1``.\\n\\n6. Concatenating immutable sequences always results in a new object.\\n This means that building up a sequence by repeated concatenation\\n will have a quadratic runtime cost in the total sequence length.\\n To get a linear runtime cost, you must switch to one of the\\n alternatives below:\\n\\n * if concatenating ``str`` objects, you can build a list and use\\n ``str.join()`` at the end or else write to a ``io.StringIO``\\n instance and retrieve its value when complete\\n\\n * if concatenating ``bytes`` objects, you can similarly use\\n ``bytes.join()`` or ``io.BytesIO``, or you can do in-place\\n concatenation with a ``bytearray`` object. ``bytearray`` objects\\n are mutable and have an efficient overallocation mechanism\\n\\n * if concatenating ``tuple`` objects, extend a ``list`` instead\\n\\n * for other types, investigate the relevant class documentation\\n\\n7. Some sequence types (such as ``range``) only support item sequences\\n that follow specific patterns, and hence don\\'t support sequence\\n concatenation or repetition.\\n\\n8. ``index`` raises ``ValueError`` when *x* is not found in *s*. When\\n supported, the additional arguments to the index method allow\\n efficient searching of subsections of the sequence. Passing the\\n extra arguments is roughly equivalent to using ``s[i:j].index(x)``,\\n only without copying any data and with the returned index being\\n relative to the start of the sequence rather than the start of the\\n slice.\\n\\n\\nImmutable Sequence Types\\n========================\\n\\nThe only operation that immutable sequence types generally implement\\nthat is not also implemented by mutable sequence types is support for\\nthe ``hash()`` built-in.\\n\\nThis support allows immutable sequences, such as ``tuple`` instances,\\nto be used as ``dict`` keys and stored in ``set`` and ``frozenset``\\ninstances.\\n\\nAttempting to hash an immutable sequence that contains unhashable\\nvalues will result in ``TypeError``.\\n\\n\\nMutable Sequence Types\\n======================\\n\\nThe operations in the following table are defined on mutable sequence\\ntypes. The ``collections.abc.MutableSequence`` ABC is provided to make\\nit easier to correctly implement these operations on custom sequence\\ntypes.\\n\\nIn the table *s* is an instance of a mutable sequence type, *t* is any\\niterable object and *x* is an arbitrary object that meets any type and\\nvalue restrictions imposed by *s* (for example, ``bytearray`` only\\naccepts integers that meet the value restriction ``0 <= x <= 255``).\\n\\n+--------------------------------+----------------------------------+-----------------------+\\n| Operation | Result | Notes |\\n+================================+==================================+=======================+\\n| ``s[i] = x`` | item *i* of *s* is replaced by | |\\n| | *x* | |\\n+--------------------------------+----------------------------------+-----------------------+\\n| ``s[i:j] = t`` | slice of *s* from *i* to *j* is | |\\n| | replaced by the contents of the | |\\n| | iterable *t* | |\\n+--------------------------------+----------------------------------+-----------------------+\\n| ``del s[i:j]`` | same as ``s[i:j] = []`` | |\\n+--------------------------------+----------------------------------+-----------------------+\\n| ``s[i:j:k] = t`` | the elements of ``s[i:j:k]`` are | (1) |\\n| | replaced by those of *t* | |\\n+--------------------------------+----------------------------------+-----------------------+\\n| ``del s[i:j:k]`` | removes the elements of | |\\n| | ``s[i:j:k]`` from the list | |\\n+--------------------------------+----------------------------------+-----------------------+\\n| ``s.append(x)`` | appends *x* to the end of the | |\\n| | sequence (same as | |\\n| | ``s[len(s):len(s)] = [x]``) | |\\n+--------------------------------+----------------------------------+-----------------------+\\n| ``s.clear()`` | removes all items from ``s`` | (5) |\\n| | (same as ``del s[:]``) | |\\n+--------------------------------+----------------------------------+-----------------------+\\n| ``s.copy()`` | creates a shallow copy of ``s`` | (5) |\\n| | (same as ``s[:]``) | |\\n+--------------------------------+----------------------------------+-----------------------+\\n| ``s.extend(t)`` | extends *s* with the contents of | |\\n| | *t* (same as ``s[len(s):len(s)] | |\\n| | = t``) | |\\n+--------------------------------+----------------------------------+-----------------------+\\n| ``s.insert(i, x)`` | inserts *x* into *s* at the | |\\n| | index given by *i* (same as | |\\n| | ``s[i:i] = [x]``) | |\\n+--------------------------------+----------------------------------+-----------------------+\\n| ``s.pop([i])`` | retrieves the item at *i* and | (2) |\\n| | also removes it from *s* | |\\n+--------------------------------+----------------------------------+-----------------------+\\n| ``s.remove(x)`` | remove the first item from *s* | (3) |\\n| | where ``s[i] == x`` | |\\n+--------------------------------+----------------------------------+-----------------------+\\n| ``s.reverse()`` | reverses the items of *s* in | (4) |\\n| | place | |\\n+--------------------------------+----------------------------------+-----------------------+\\n\\nNotes:\\n\\n1. *t* must have the same length as the slice it is replacing.\\n\\n2. The optional argument *i* defaults to ``-1``, so that by default\\n the last item is removed and returned.\\n\\n3. ``remove`` raises ``ValueError`` when *x* is not found in *s*.\\n\\n4. The ``reverse()`` method modifies the sequence in place for economy\\n of space when reversing a large sequence. To remind users that it\\n operates by side effect, it does not return the reversed sequence.\\n\\n5. ``clear()`` and ``copy()`` are included for consistency with the\\n interfaces of mutable containers that don\\'t support slicing\\n operations (such as ``dict`` and ``set``)\\n\\n New in version 3.3: ``clear()`` and ``copy()`` methods.\\n\\n\\nLists\\n=====\\n\\nLists are mutable sequences, typically used to store collections of\\nhomogeneous items (where the precise degree of similarity will vary by\\napplication).\\n\\nclass class list([iterable])\\n\\n Lists may be constructed in several ways:\\n\\n * Using a pair of square brackets to denote the empty list: ``[]``\\n\\n * Using square brackets, separating items with commas: ``[a]``,\\n ``[a, b, c]``\\n\\n * Using a list comprehension: ``[x for x in iterable]``\\n\\n * Using the type constructor: ``list()`` or ``list(iterable)``\\n\\n The constructor builds a list whose items are the same and in the\\n same order as *iterable*\\'s items. *iterable* may be either a\\n sequence, a container that supports iteration, or an iterator\\n object. If *iterable* is already a list, a copy is made and\\n returned, similar to ``iterable[:]``. For example, ``list(\\'abc\\')``\\n returns ``[\\'a\\', \\'b\\', \\'c\\']`` and ``list( (1, 2, 3) )`` returns ``[1,\\n 2, 3]``. If no argument is given, the constructor creates a new\\n empty list, ``[]``.\\n\\n Many other operations also produce lists, including the\\n ``sorted()`` built-in.\\n\\n Lists implement all of the *common* and *mutable* sequence\\n operations. Lists also provide the following additional method:\\n\\n sort(*, key=None, reverse=None)\\n\\n This method sorts the list in place, using only ``<``\\n comparisons between items. Exceptions are not suppressed - if\\n any comparison operations fail, the entire sort operation will\\n fail (and the list will likely be left in a partially modified\\n state).\\n\\n *key* specifies a function of one argument that is used to\\n extract a comparison key from each list element (for example,\\n ``key=str.lower``). The key corresponding to each item in the\\n list is calculated once and then used for the entire sorting\\n process. The default value of ``None`` means that list items are\\n sorted directly without calculating a separate key value.\\n\\n The ``functools.cmp_to_key()`` utility is available to convert a\\n 2.x style *cmp* function to a *key* function.\\n\\n *reverse* is a boolean value. If set to ``True``, then the list\\n elements are sorted as if each comparison were reversed.\\n\\n This method modifies the sequence in place for economy of space\\n when sorting a large sequence. To remind users that it operates\\n by side effect, it does not return the sorted sequence (use\\n ``sorted()`` to explicitly request a new sorted list instance).\\n\\n The ``sort()`` method is guaranteed to be stable. A sort is\\n stable if it guarantees not to change the relative order of\\n elements that compare equal --- this is helpful for sorting in\\n multiple passes (for example, sort by department, then by salary\\n grade).\\n\\n **CPython implementation detail:** While a list is being sorted,\\n the effect of attempting to mutate, or even inspect, the list is\\n undefined. The C implementation of Python makes the list appear\\n empty for the duration, and raises ``ValueError`` if it can\\n detect that the list has been mutated during a sort.\\n\\n\\nTuples\\n======\\n\\nTuples are immutable sequences, typically used to store collections of\\nheterogeneous data (such as the 2-tuples produced by the\\n``enumerate()`` built-in). Tuples are also used for cases where an\\nimmutable sequence of homogeneous data is needed (such as allowing\\nstorage in a ``set`` or ``dict`` instance).\\n\\nclass class tuple([iterable])\\n\\n Tuples may be constructed in a number of ways:\\n\\n * Using a pair of parentheses to denote the empty tuple: ``()``\\n\\n * Using a trailing comma for a singleton tuple: ``a,`` or ``(a,)``\\n\\n * Separating items with commas: ``a, b, c`` or ``(a, b, c)``\\n\\n * Using the ``tuple()`` built-in: ``tuple()`` or\\n ``tuple(iterable)``\\n\\n The constructor builds a tuple whose items are the same and in the\\n same order as *iterable*\\'s items. *iterable* may be either a\\n sequence, a container that supports iteration, or an iterator\\n object. If *iterable* is already a tuple, it is returned\\n unchanged. For example, ``tuple(\\'abc\\')`` returns ``(\\'a\\', \\'b\\',\\n \\'c\\')`` and ``tuple( [1, 2, 3] )`` returns ``(1, 2, 3)``. If no\\n argument is given, the constructor creates a new empty tuple,\\n ``()``.\\n\\n Note that it is actually the comma which makes a tuple, not the\\n parentheses. The parentheses are optional, except in the empty\\n tuple case, or when they are needed to avoid syntactic ambiguity.\\n For example, ``f(a, b, c)`` is a function call with three\\n arguments, while ``f((a, b, c))`` is a function call with a 3-tuple\\n as the sole argument.\\n\\n Tuples implement all of the *common* sequence operations.\\n\\nFor heterogeneous collections of data where access by name is clearer\\nthan access by index, ``collections.namedtuple()`` may be a more\\nappropriate choice than a simple tuple object.\\n\\n\\nRanges\\n======\\n\\nThe ``range`` type represents an immutable sequence of numbers and is\\ncommonly used for looping a specific number of times in ``for`` loops.\\n\\nclass class range(stop)\\nclass class range(start, stop[, step])\\n\\n The arguments to the range constructor must be integers (either\\n built-in ``int`` or any object that implements the ``__index__``\\n special method). If the *step* argument is omitted, it defaults to\\n ``1``. If the *start* argument is omitted, it defaults to ``0``. If\\n *step* is zero, ``ValueError`` is raised.\\n\\n For a positive *step*, the contents of a range ``r`` are determined\\n by the formula ``r[i] = start + step*i`` where ``i >= 0`` and\\n ``r[i] < stop``.\\n\\n For a negative *step*, the contents of the range are still\\n determined by the formula ``r[i] = start + step*i``, but the\\n constraints are ``i >= 0`` and ``r[i] > stop``.\\n\\n A range object will be empty if ``r[0]`` does not meet the value\\n constraint. Ranges do support negative indices, but these are\\n interpreted as indexing from the end of the sequence determined by\\n the positive indices.\\n\\n Ranges containing absolute values larger than ``sys.maxsize`` are\\n permitted but some features (such as ``len()``) may raise\\n ``OverflowError``.\\n\\n Range examples:\\n\\n >>> list(range(10))\\n [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]\\n >>> list(range(1, 11))\\n [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]\\n >>> list(range(0, 30, 5))\\n [0, 5, 10, 15, 20, 25]\\n >>> list(range(0, 10, 3))\\n [0, 3, 6, 9]\\n >>> list(range(0, -10, -1))\\n [0, -1, -2, -3, -4, -5, -6, -7, -8, -9]\\n >>> list(range(0))\\n []\\n >>> list(range(1, 0))\\n []\\n\\n Ranges implement all of the *common* sequence operations except\\n concatenation and repetition (due to the fact that range objects\\n can only represent sequences that follow a strict pattern and\\n repetition and concatenation will usually violate that pattern).\\n\\nThe advantage of the ``range`` type over a regular ``list`` or\\n``tuple`` is that a ``range`` object will always take the same (small)\\namount of memory, no matter the size of the range it represents (as it\\nonly stores the ``start``, ``stop`` and ``step`` values, calculating\\nindividual items and subranges as needed).\\n\\nRange objects implement the ``collections.Sequence`` ABC, and provide\\nfeatures such as containment tests, element index lookup, slicing and\\nsupport for negative indices (see *Sequence Types --- list, tuple,\\nrange*):\\n\\n>>> r = range(0, 20, 2)\\n>>> r\\nrange(0, 20, 2)\\n>>> 11 in r\\nFalse\\n>>> 10 in r\\nTrue\\n>>> r.index(10)\\n5\\n>>> r[5]\\n10\\n>>> r[:5]\\nrange(0, 10, 2)\\n>>> r[-1]\\n18\\n\\nTesting range objects for equality with ``==`` and ``!=`` compares\\nthem as sequences. That is, two range objects are considered equal if\\nthey represent the same sequence of values. (Note that two range\\nobjects that compare equal might have different ``start``, ``stop``\\nand ``step`` attributes, for example ``range(0) == range(2, 1, 3)`` or\\n``range(0, 3, 2) == range(0, 4, 2)``.)\\n\\nChanged in version 3.2: Implement the Sequence ABC. Support slicing\\nand negative indices. Test ``int`` objects for membership in constant\\ntime instead of iterating through all items.\\n\\nChanged in version 3.3: Define \\'==\\' and \\'!=\\' to compare range objects\\nbased on the sequence of values they define (instead of comparing\\nbased on object identity).\\n\\nNew in version 3.3: The ``start``, ``stop`` and ``step`` attributes.\\n',\n'typesseq-mutable':\"\\nMutable Sequence Types\\n**********************\\n\\nThe operations in the following table are defined on mutable sequence\\ntypes. The ``collections.abc.MutableSequence`` ABC is provided to make\\nit easier to correctly implement these operations on custom sequence\\ntypes.\\n\\nIn the table *s* is an instance of a mutable sequence type, *t* is any\\niterable object and *x* is an arbitrary object that meets any type and\\nvalue restrictions imposed by *s* (for example, ``bytearray`` only\\naccepts integers that meet the value restriction ``0 <= x <= 255``).\\n\\n+--------------------------------+----------------------------------+-----------------------+\\n| Operation | Result | Notes |\\n+================================+==================================+=======================+\\n| ``s[i] = x`` | item *i* of *s* is replaced by | |\\n| | *x* | |\\n+--------------------------------+----------------------------------+-----------------------+\\n| ``s[i:j] = t`` | slice of *s* from *i* to *j* is | |\\n| | replaced by the contents of the | |\\n| | iterable *t* | |\\n+--------------------------------+----------------------------------+-----------------------+\\n| ``del s[i:j]`` | same as ``s[i:j] = []`` | |\\n+--------------------------------+----------------------------------+-----------------------+\\n| ``s[i:j:k] = t`` | the elements of ``s[i:j:k]`` are | (1) |\\n| | replaced by those of *t* | |\\n+--------------------------------+----------------------------------+-----------------------+\\n| ``del s[i:j:k]`` | removes the elements of | |\\n| | ``s[i:j:k]`` from the list | |\\n+--------------------------------+----------------------------------+-----------------------+\\n| ``s.append(x)`` | appends *x* to the end of the | |\\n| | sequence (same as | |\\n| | ``s[len(s):len(s)] = [x]``) | |\\n+--------------------------------+----------------------------------+-----------------------+\\n| ``s.clear()`` | removes all items from ``s`` | (5) |\\n| | (same as ``del s[:]``) | |\\n+--------------------------------+----------------------------------+-----------------------+\\n| ``s.copy()`` | creates a shallow copy of ``s`` | (5) |\\n| | (same as ``s[:]``) | |\\n+--------------------------------+----------------------------------+-----------------------+\\n| ``s.extend(t)`` | extends *s* with the contents of | |\\n| | *t* (same as ``s[len(s):len(s)] | |\\n| | = t``) | |\\n+--------------------------------+----------------------------------+-----------------------+\\n| ``s.insert(i, x)`` | inserts *x* into *s* at the | |\\n| | index given by *i* (same as | |\\n| | ``s[i:i] = [x]``) | |\\n+--------------------------------+----------------------------------+-----------------------+\\n| ``s.pop([i])`` | retrieves the item at *i* and | (2) |\\n| | also removes it from *s* | |\\n+--------------------------------+----------------------------------+-----------------------+\\n| ``s.remove(x)`` | remove the first item from *s* | (3) |\\n| | where ``s[i] == x`` | |\\n+--------------------------------+----------------------------------+-----------------------+\\n| ``s.reverse()`` | reverses the items of *s* in | (4) |\\n| | place | |\\n+--------------------------------+----------------------------------+-----------------------+\\n\\nNotes:\\n\\n1. *t* must have the same length as the slice it is replacing.\\n\\n2. The optional argument *i* defaults to ``-1``, so that by default\\n the last item is removed and returned.\\n\\n3. ``remove`` raises ``ValueError`` when *x* is not found in *s*.\\n\\n4. The ``reverse()`` method modifies the sequence in place for economy\\n of space when reversing a large sequence. To remind users that it\\n operates by side effect, it does not return the reversed sequence.\\n\\n5. ``clear()`` and ``copy()`` are included for consistency with the\\n interfaces of mutable containers that don't support slicing\\n operations (such as ``dict`` and ``set``)\\n\\n New in version 3.3: ``clear()`` and ``copy()`` methods.\\n\",\n'unary':'\\nUnary arithmetic and bitwise operations\\n***************************************\\n\\nAll unary arithmetic and bitwise operations have the same priority:\\n\\n u_expr ::= power | \"-\" u_expr | \"+\" u_expr | \"~\" u_expr\\n\\nThe unary ``-`` (minus) operator yields the negation of its numeric\\nargument.\\n\\nThe unary ``+`` (plus) operator yields its numeric argument unchanged.\\n\\nThe unary ``~`` (invert) operator yields the bitwise inversion of its\\ninteger argument. The bitwise inversion of ``x`` is defined as\\n``-(x+1)``. It only applies to integral numbers.\\n\\nIn all three cases, if the argument does not have the proper type, a\\n``TypeError`` exception is raised.\\n',\n'while':'\\nThe ``while`` statement\\n***********************\\n\\nThe ``while`` statement is used for repeated execution as long as an\\nexpression is true:\\n\\n while_stmt ::= \"while\" expression \":\" suite\\n [\"else\" \":\" suite]\\n\\nThis repeatedly tests the expression and, if it is true, executes the\\nfirst suite; if the expression is false (which may be the first time\\nit is tested) the suite of the ``else`` clause, if present, is\\nexecuted and the loop terminates.\\n\\nA ``break`` statement executed in the first suite terminates the loop\\nwithout executing the ``else`` clause\\'s suite. A ``continue``\\nstatement executed in the first suite skips the rest of the suite and\\ngoes back to testing the expression.\\n',\n'with':'\\nThe ``with`` statement\\n**********************\\n\\nThe ``with`` statement is used to wrap the execution of a block with\\nmethods defined by a context manager (see section *With Statement\\nContext Managers*). This allows common\\n``try``...``except``...``finally`` usage patterns to be encapsulated\\nfor convenient reuse.\\n\\n with_stmt ::= \"with\" with_item (\",\" with_item)* \":\" suite\\n with_item ::= expression [\"as\" target]\\n\\nThe execution of the ``with`` statement with one \"item\" proceeds as\\nfollows:\\n\\n1. The context expression (the expression given in the ``with_item``)\\n is evaluated to obtain a context manager.\\n\\n2. The context manager\\'s ``__exit__()`` is loaded for later use.\\n\\n3. The context manager\\'s ``__enter__()`` method is invoked.\\n\\n4. If a target was included in the ``with`` statement, the return\\n value from ``__enter__()`` is assigned to it.\\n\\n Note: The ``with`` statement guarantees that if the ``__enter__()``\\n method returns without an error, then ``__exit__()`` will always\\n be called. Thus, if an error occurs during the assignment to the\\n target list, it will be treated the same as an error occurring\\n within the suite would be. See step 6 below.\\n\\n5. The suite is executed.\\n\\n6. The context manager\\'s ``__exit__()`` method is invoked. If an\\n exception caused the suite to be exited, its type, value, and\\n traceback are passed as arguments to ``__exit__()``. Otherwise,\\n three ``None`` arguments are supplied.\\n\\n If the suite was exited due to an exception, and the return value\\n from the ``__exit__()`` method was false, the exception is\\n reraised. If the return value was true, the exception is\\n suppressed, and execution continues with the statement following\\n the ``with`` statement.\\n\\n If the suite was exited for any reason other than an exception, the\\n return value from ``__exit__()`` is ignored, and execution proceeds\\n at the normal location for the kind of exit that was taken.\\n\\nWith more than one item, the context managers are processed as if\\nmultiple ``with`` statements were nested:\\n\\n with A() as a, B() as b:\\n suite\\n\\nis equivalent to\\n\\n with A() as a:\\n with B() as b:\\n suite\\n\\nChanged in version 3.1: Support for multiple context expressions.\\n\\nSee also:\\n\\n **PEP 0343** - The \"with\" statement\\n The specification, background, and examples for the Python\\n ``with`` statement.\\n',\n'yield':'\\nThe ``yield`` statement\\n***********************\\n\\n yield_stmt ::= yield_expression\\n\\nThe ``yield`` statement is only used when defining a generator\\nfunction, and is only used in the body of the generator function.\\nUsing a ``yield`` statement in a function definition is sufficient to\\ncause that definition to create a generator function instead of a\\nnormal function.\\n\\nWhen a generator function is called, it returns an iterator known as a\\ngenerator iterator, or more commonly, a generator. The body of the\\ngenerator function is executed by calling the ``next()`` function on\\nthe generator repeatedly until it raises an exception.\\n\\nWhen a ``yield`` statement is executed, the state of the generator is\\nfrozen and the value of ``expression_list`` is returned to\\n``next()``\\'s caller. By \"frozen\" we mean that all local state is\\nretained, including the current bindings of local variables, the\\ninstruction pointer, and the internal evaluation stack: enough\\ninformation is saved so that the next time ``next()`` is invoked, the\\nfunction can proceed exactly as if the ``yield`` statement were just\\nanother external call.\\n\\nThe ``yield`` statement is allowed in the ``try`` clause of a ``try``\\n... ``finally`` construct. If the generator is not resumed before it\\nis finalized (by reaching a zero reference count or by being garbage\\ncollected), the generator-iterator\\'s ``close()`` method will be\\ncalled, allowing any pending ``finally`` clauses to execute.\\n\\nWhen ``yield from <expr>`` is used, it treats the supplied expression\\nas a subiterator, producing values from it until the underlying\\niterator is exhausted.\\n\\n Changed in version 3.3: Added ``yield from <expr>`` to delegate\\n control flow to a subiterator\\n\\nFor full details of ``yield`` semantics, refer to the *Yield\\nexpressions* section.\\n\\nSee also:\\n\\n **PEP 0255** - Simple Generators\\n The proposal for adding generators and the ``yield`` statement\\n to Python.\\n\\n **PEP 0342** - Coroutines via Enhanced Generators\\n The proposal to enhance the API and syntax of generators, making\\n them usable as simple coroutines.\\n\\n **PEP 0380** - Syntax for Delegating to a Subgenerator\\n The proposal to introduce the ``yield_from`` syntax, making\\n delegation to sub-generators easy.\\n'}\n", []], "pydoc_data": [".py", "", [], 1], "contextlib": [".py", "''\nimport abc\nimport sys\nimport _collections_abc\nfrom collections import deque\nfrom functools import wraps\n\n__all__=[\"asynccontextmanager\",\"contextmanager\",\"closing\",\"nullcontext\",\n\"AbstractContextManager\",\"AbstractAsyncContextManager\",\n\"AsyncExitStack\",\"ContextDecorator\",\"ExitStack\",\n\"redirect_stdout\",\"redirect_stderr\",\"suppress\"]\n\n\nclass AbstractContextManager(abc.ABC):\n\n ''\n \n def __enter__(self):\n ''\n return self\n \n @abc.abstractmethod\n def __exit__(self,exc_type,exc_value,traceback):\n ''\n return None\n \n @classmethod\n def __subclasshook__(cls,C):\n if cls is AbstractContextManager:\n return _collections_abc._check_methods(C,\"__enter__\",\"__exit__\")\n return NotImplemented\n \n \nclass AbstractAsyncContextManager(abc.ABC):\n\n ''\n \n async def __aenter__(self):\n ''\n return self\n \n @abc.abstractmethod\n async def __aexit__(self,exc_type,exc_value,traceback):\n ''\n return None\n \n @classmethod\n def __subclasshook__(cls,C):\n if cls is AbstractAsyncContextManager:\n return _collections_abc._check_methods(C,\"__aenter__\",\n \"__aexit__\")\n return NotImplemented\n \n \nclass ContextDecorator(object):\n ''\n \n def _recreate_cm(self):\n ''\n\n\n\n\n\n\n\n \n return self\n \n def __call__(self,func):\n @wraps(func)\n def inner(*args,**kwds):\n with self._recreate_cm():\n return func(*args,**kwds)\n return inner\n \n \nclass _GeneratorContextManagerBase:\n ''\n \n def __init__(self,func,args,kwds):\n self.gen=func(*args,**kwds)\n self.func,self.args,self.kwds=func,args,kwds\n \n doc=getattr(func,\"__doc__\",None )\n if doc is None :\n doc=type(self).__doc__\n self.__doc__=doc\n \n \n \n \n \n \n \nclass _GeneratorContextManager(_GeneratorContextManagerBase,\nAbstractContextManager,\nContextDecorator):\n ''\n \n def _recreate_cm(self):\n \n \n \n return self.__class__(self.func,self.args,self.kwds)\n \n def __enter__(self):\n \n \n del self.args,self.kwds,self.func\n try :\n return next(self.gen)\n except StopIteration:\n raise RuntimeError(\"generator didn't yield\")from None\n \n def __exit__(self,type,value,traceback):\n if type is None :\n try :\n next(self.gen)\n except StopIteration:\n return False\n else :\n raise RuntimeError(\"generator didn't stop\")\n else :\n if value is None :\n \n \n value=type()\n try :\n self.gen.throw(type,value,traceback)\n except StopIteration as exc:\n \n \n \n return exc is not value\n except RuntimeError as exc:\n \n if exc is value:\n return False\n \n \n \n if type is StopIteration and exc.__cause__ is value:\n return False\n raise\n except :\n \n \n \n \n \n \n \n \n \n \n \n if sys.exc_info()[1]is value:\n return False\n raise\n raise RuntimeError(\"generator didn't stop after throw()\")\n \n \nclass _AsyncGeneratorContextManager(_GeneratorContextManagerBase,\nAbstractAsyncContextManager):\n ''\n \n async def __aenter__(self):\n try :\n return await self.gen.__anext__()\n except StopAsyncIteration:\n raise RuntimeError(\"generator didn't yield\")from None\n \n async def __aexit__(self,typ,value,traceback):\n if typ is None :\n try :\n await self.gen.__anext__()\n except StopAsyncIteration:\n return\n else :\n raise RuntimeError(\"generator didn't stop\")\n else :\n if value is None :\n value=typ()\n \n \n try :\n await self.gen.athrow(typ,value,traceback)\n raise RuntimeError(\"generator didn't stop after throw()\")\n except StopAsyncIteration as exc:\n return exc is not value\n except RuntimeError as exc:\n if exc is value:\n return False\n \n \n \n \n \n \n if isinstance(value,(StopIteration,StopAsyncIteration)):\n if exc.__cause__ is value:\n return False\n raise\n except BaseException as exc:\n if exc is not value:\n raise\n \n \ndef contextmanager(func):\n ''\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n \n @wraps(func)\n def helper(*args,**kwds):\n return _GeneratorContextManager(func,args,kwds)\n return helper\n \n \ndef asynccontextmanager(func):\n ''\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n \n @wraps(func)\n def helper(*args,**kwds):\n return _AsyncGeneratorContextManager(func,args,kwds)\n return helper\n \n \nclass closing(AbstractContextManager):\n ''\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n \n def __init__(self,thing):\n self.thing=thing\n def __enter__(self):\n return self.thing\n def __exit__(self,*exc_info):\n self.thing.close()\n \n \nclass _RedirectStream(AbstractContextManager):\n\n _stream=None\n \n def __init__(self,new_target):\n self._new_target=new_target\n \n self._old_targets=[]\n \n def __enter__(self):\n self._old_targets.append(getattr(sys,self._stream))\n setattr(sys,self._stream,self._new_target)\n return self._new_target\n \n def __exit__(self,exctype,excinst,exctb):\n setattr(sys,self._stream,self._old_targets.pop())\n \n \nclass redirect_stdout(_RedirectStream):\n ''\n\n\n\n\n\n\n\n\n\n \n \n _stream=\"stdout\"\n \n \nclass redirect_stderr(_RedirectStream):\n ''\n \n _stream=\"stderr\"\n \n \nclass suppress(AbstractContextManager):\n ''\n\n\n\n\n\n\n\n \n \n def __init__(self,*exceptions):\n self._exceptions=exceptions\n \n def __enter__(self):\n pass\n \n def __exit__(self,exctype,excinst,exctb):\n \n \n \n \n \n \n \n \n \n return exctype is not None and issubclass(exctype,self._exceptions)\n \n \nclass _BaseExitStack:\n ''\n \n @staticmethod\n def _create_exit_wrapper(cm,cm_exit):\n def _exit_wrapper(exc_type,exc,tb):\n return cm_exit(cm,exc_type,exc,tb)\n return _exit_wrapper\n \n @staticmethod\n def _create_cb_wrapper(callback,*args,**kwds):\n def _exit_wrapper(exc_type,exc,tb):\n callback(*args,**kwds)\n return _exit_wrapper\n \n def __init__(self):\n self._exit_callbacks=deque()\n \n def pop_all(self):\n ''\n new_stack=type(self)()\n new_stack._exit_callbacks=self._exit_callbacks\n self._exit_callbacks=deque()\n return new_stack\n \n def push(self,exit):\n ''\n\n\n\n\n \n \n \n _cb_type=type(exit)\n \n try :\n exit_method=_cb_type.__exit__\n except AttributeError:\n \n self._push_exit_callback(exit)\n else :\n self._push_cm_exit(exit,exit_method)\n return exit\n \n def enter_context(self,cm):\n ''\n\n\n\n \n \n \n _cm_type=type(cm)\n _exit=_cm_type.__exit__\n result=_cm_type.__enter__(cm)\n self._push_cm_exit(cm,_exit)\n return result\n \n def callback(self,callback,*args,**kwds):\n ''\n\n\n \n _exit_wrapper=self._create_cb_wrapper(callback,*args,**kwds)\n \n \n \n _exit_wrapper.__wrapped__=callback\n self._push_exit_callback(_exit_wrapper)\n return callback\n \n def _push_cm_exit(self,cm,cm_exit):\n ''\n _exit_wrapper=self._create_exit_wrapper(cm,cm_exit)\n _exit_wrapper.__self__=cm\n self._push_exit_callback(_exit_wrapper,True )\n \n def _push_exit_callback(self,callback,is_sync=True ):\n self._exit_callbacks.append((is_sync,callback))\n \n \n \nclass ExitStack(_BaseExitStack,AbstractContextManager):\n ''\n\n\n\n\n\n\n\n \n \n def __enter__(self):\n return self\n \n def __exit__(self,*exc_details):\n received_exc=exc_details[0]is not None\n \n \n \n frame_exc=sys.exc_info()[1]\n def _fix_exception_context(new_exc,old_exc):\n \n while 1:\n exc_context=new_exc.__context__\n if exc_context is old_exc:\n \n return\n if exc_context is None or exc_context is frame_exc:\n break\n new_exc=exc_context\n \n \n new_exc.__context__=old_exc\n \n \n \n suppressed_exc=False\n pending_raise=False\n while self._exit_callbacks:\n is_sync,cb=self._exit_callbacks.pop()\n assert is_sync\n try :\n if cb(*exc_details):\n suppressed_exc=True\n pending_raise=False\n exc_details=(None ,None ,None )\n except :\n new_exc_details=sys.exc_info()\n \n _fix_exception_context(new_exc_details[1],exc_details[1])\n pending_raise=True\n exc_details=new_exc_details\n if pending_raise:\n try :\n \n \n fixed_ctx=exc_details[1].__context__\n raise exc_details[1]\n except BaseException:\n exc_details[1].__context__=fixed_ctx\n raise\n return received_exc and suppressed_exc\n \n def close(self):\n ''\n self.__exit__(None ,None ,None )\n \n \n \nclass AsyncExitStack(_BaseExitStack,AbstractAsyncContextManager):\n ''\n\n\n\n\n\n\n\n\n\n \n \n @staticmethod\n def _create_async_exit_wrapper(cm,cm_exit):\n async def _exit_wrapper(exc_type,exc,tb):\n return await cm_exit(cm,exc_type,exc,tb)\n return _exit_wrapper\n \n @staticmethod\n def _create_async_cb_wrapper(callback,*args,**kwds):\n async def _exit_wrapper(exc_type,exc,tb):\n await callback(*args,**kwds)\n return _exit_wrapper\n \n async def enter_async_context(self,cm):\n ''\n\n\n\n \n _cm_type=type(cm)\n _exit=_cm_type.__aexit__\n result=await _cm_type.__aenter__(cm)\n self._push_async_cm_exit(cm,_exit)\n return result\n \n def push_async_exit(self,exit):\n ''\n\n\n\n\n\n \n _cb_type=type(exit)\n try :\n exit_method=_cb_type.__aexit__\n except AttributeError:\n \n self._push_exit_callback(exit,False )\n else :\n self._push_async_cm_exit(exit,exit_method)\n return exit\n \n def push_async_callback(self,callback,*args,**kwds):\n ''\n\n\n \n _exit_wrapper=self._create_async_cb_wrapper(callback,*args,**kwds)\n \n \n \n _exit_wrapper.__wrapped__=callback\n self._push_exit_callback(_exit_wrapper,False )\n return callback\n \n async def aclose(self):\n ''\n await self.__aexit__(None ,None ,None )\n \n def _push_async_cm_exit(self,cm,cm_exit):\n ''\n \n _exit_wrapper=self._create_async_exit_wrapper(cm,cm_exit)\n _exit_wrapper.__self__=cm\n self._push_exit_callback(_exit_wrapper,False )\n \n async def __aenter__(self):\n return self\n \n async def __aexit__(self,*exc_details):\n received_exc=exc_details[0]is not None\n \n \n \n frame_exc=sys.exc_info()[1]\n def _fix_exception_context(new_exc,old_exc):\n \n while 1:\n exc_context=new_exc.__context__\n if exc_context is old_exc:\n \n return\n if exc_context is None or exc_context is frame_exc:\n break\n new_exc=exc_context\n \n \n new_exc.__context__=old_exc\n \n \n \n suppressed_exc=False\n pending_raise=False\n while self._exit_callbacks:\n is_sync,cb=self._exit_callbacks.pop()\n try :\n if is_sync:\n cb_suppress=cb(*exc_details)\n else :\n cb_suppress=await cb(*exc_details)\n \n if cb_suppress:\n suppressed_exc=True\n pending_raise=False\n exc_details=(None ,None ,None )\n except :\n new_exc_details=sys.exc_info()\n \n _fix_exception_context(new_exc_details[1],exc_details[1])\n pending_raise=True\n exc_details=new_exc_details\n if pending_raise:\n try :\n \n \n fixed_ctx=exc_details[1].__context__\n raise exc_details[1]\n except BaseException:\n exc_details[1].__context__=fixed_ctx\n raise\n return received_exc and suppressed_exc\n \n \nclass nullcontext(AbstractContextManager):\n ''\n\n\n\n\n\n\n\n \n \n def __init__(self,enter_result=None ):\n self.enter_result=enter_result\n \n def __enter__(self):\n return self.enter_result\n \n def __exit__(self,*excinfo):\n pass\n", ["_collections_abc", "abc", "collections", "functools", "sys"]], "subprocess": [".py", "\n\n\n\n\n\n\n\n\nr\"\"\"Subprocesses with accessible I/O streams\n\nThis module allows you to spawn processes, connect to their\ninput/output/error pipes, and obtain their return codes.\n\nFor a complete description of this module see the Python documentation.\n\nMain API\n========\nrun(...): Runs a command, waits for it to complete, then returns a\n CompletedProcess instance.\nPopen(...): A class for flexibly executing a command in a new process\n\nConstants\n---------\nDEVNULL: Special value that indicates that os.devnull should be used\nPIPE: Special value that indicates a pipe should be created\nSTDOUT: Special value that indicates that stderr should go to stdout\n\n\nOlder API\n=========\ncall(...): Runs a command, waits for it to complete, then returns\n the return code.\ncheck_call(...): Same as call() but raises CalledProcessError()\n if return code is not 0\ncheck_output(...): Same as check_call() but returns the contents of\n stdout instead of a return code\ngetoutput(...): Runs a command in the shell, waits for it to complete,\n then returns the output\ngetstatusoutput(...): Runs a command in the shell, waits for it to complete,\n then returns a (exitcode, output) tuple\n\"\"\"\n\nimport sys\n_mswindows=(sys.platform ==\"win32\")\n\nimport io\nimport os\nimport time\nimport signal\nimport builtins\nimport warnings\nimport errno\nfrom time import monotonic as _time\n\n\nclass SubprocessError(Exception):pass\n\n\nclass CalledProcessError(SubprocessError):\n ''\n\n\n\n\n \n def __init__(self,returncode,cmd,output=None ,stderr=None ):\n self.returncode=returncode\n self.cmd=cmd\n self.output=output\n self.stderr=stderr\n \n def __str__(self):\n if self.returncode and self.returncode <0:\n try :\n return \"Command '%s' died with %r.\"%(\n self.cmd,signal.Signals(-self.returncode))\n except ValueError:\n return \"Command '%s' died with unknown signal %d.\"%(\n self.cmd,-self.returncode)\n else :\n return \"Command '%s' returned non-zero exit status %d.\"%(\n self.cmd,self.returncode)\n \n @property\n def stdout(self):\n ''\n return self.output\n \n @stdout.setter\n def stdout(self,value):\n \n \n self.output=value\n \n \nclass TimeoutExpired(SubprocessError):\n ''\n\n\n\n\n \n def __init__(self,cmd,timeout,output=None ,stderr=None ):\n self.cmd=cmd\n self.timeout=timeout\n self.output=output\n self.stderr=stderr\n \n def __str__(self):\n return (\"Command '%s' timed out after %s seconds\"%\n (self.cmd,self.timeout))\n \n @property\n def stdout(self):\n return self.output\n \n @stdout.setter\n def stdout(self,value):\n \n \n self.output=value\n \n \nif _mswindows:\n import threading\n import msvcrt\n import _winapi\n class STARTUPINFO:\n def __init__(self,*,dwFlags=0,hStdInput=None ,hStdOutput=None ,\n hStdError=None ,wShowWindow=0,lpAttributeList=None ):\n self.dwFlags=dwFlags\n self.hStdInput=hStdInput\n self.hStdOutput=hStdOutput\n self.hStdError=hStdError\n self.wShowWindow=wShowWindow\n self.lpAttributeList=lpAttributeList or {\"handle_list\":[]}\nelse :\n import _posixsubprocess\n import select\n import selectors\n import threading\n \n \n \n \n _PIPE_BUF=getattr(select,'PIPE_BUF',512)\n \n \n \n \n if hasattr(selectors,'PollSelector'):\n _PopenSelector=selectors.PollSelector\n else :\n _PopenSelector=selectors.SelectSelector\n \n \n__all__=[\"Popen\",\"PIPE\",\"STDOUT\",\"call\",\"check_call\",\"getstatusoutput\",\n\"getoutput\",\"check_output\",\"run\",\"CalledProcessError\",\"DEVNULL\",\n\"SubprocessError\",\"TimeoutExpired\",\"CompletedProcess\"]\n\n\n\nif _mswindows:\n from _winapi import (CREATE_NEW_CONSOLE,CREATE_NEW_PROCESS_GROUP,\n STD_INPUT_HANDLE,STD_OUTPUT_HANDLE,\n STD_ERROR_HANDLE,SW_HIDE,\n STARTF_USESTDHANDLES,STARTF_USESHOWWINDOW,\n ABOVE_NORMAL_PRIORITY_CLASS,BELOW_NORMAL_PRIORITY_CLASS,\n HIGH_PRIORITY_CLASS,IDLE_PRIORITY_CLASS,\n NORMAL_PRIORITY_CLASS,REALTIME_PRIORITY_CLASS,\n CREATE_NO_WINDOW,DETACHED_PROCESS,\n CREATE_DEFAULT_ERROR_MODE,CREATE_BREAKAWAY_FROM_JOB)\n \n __all__.extend([\"CREATE_NEW_CONSOLE\",\"CREATE_NEW_PROCESS_GROUP\",\n \"STD_INPUT_HANDLE\",\"STD_OUTPUT_HANDLE\",\n \"STD_ERROR_HANDLE\",\"SW_HIDE\",\n \"STARTF_USESTDHANDLES\",\"STARTF_USESHOWWINDOW\",\n \"STARTUPINFO\",\n \"ABOVE_NORMAL_PRIORITY_CLASS\",\"BELOW_NORMAL_PRIORITY_CLASS\",\n \"HIGH_PRIORITY_CLASS\",\"IDLE_PRIORITY_CLASS\",\n \"NORMAL_PRIORITY_CLASS\",\"REALTIME_PRIORITY_CLASS\",\n \"CREATE_NO_WINDOW\",\"DETACHED_PROCESS\",\n \"CREATE_DEFAULT_ERROR_MODE\",\"CREATE_BREAKAWAY_FROM_JOB\"])\n \n class Handle(int):\n closed=False\n \n def Close(self,CloseHandle=_winapi.CloseHandle):\n if not self.closed:\n self.closed=True\n CloseHandle(self)\n \n def Detach(self):\n if not self.closed:\n self.closed=True\n return int(self)\n raise ValueError(\"already closed\")\n \n def __repr__(self):\n return \"%s(%d)\"%(self.__class__.__name__,int(self))\n \n __del__=Close\n __str__=__repr__\n \n \n \n \n \n \n_active=[]\n\ndef _cleanup():\n for inst in _active[:]:\n res=inst._internal_poll(_deadstate=sys.maxsize)\n if res is not None :\n try :\n _active.remove(inst)\n except ValueError:\n \n \n pass\n \nPIPE=-1\nSTDOUT=-2\nDEVNULL=-3\n\n\n\n\n\n\ndef _optim_args_from_interpreter_flags():\n ''\n \n args=[]\n value=sys.flags.optimize\n if value >0:\n args.append('-'+'O'*value)\n return args\n \n \ndef _args_from_interpreter_flags():\n ''\n \n flag_opt_map={\n 'debug':'d',\n \n \n 'dont_write_bytecode':'B',\n 'no_user_site':'s',\n 'no_site':'S',\n 'ignore_environment':'E',\n 'verbose':'v',\n 'bytes_warning':'b',\n 'quiet':'q',\n \n }\n args=_optim_args_from_interpreter_flags()\n for flag,opt in flag_opt_map.items():\n v=getattr(sys.flags,flag)\n if v >0:\n args.append('-'+opt *v)\n \n \n warnopts=sys.warnoptions[:]\n bytes_warning=sys.flags.bytes_warning\n xoptions=getattr(sys,'_xoptions',{})\n dev_mode=('dev'in xoptions)\n \n if bytes_warning >1:\n warnopts.remove(\"error::BytesWarning\")\n elif bytes_warning:\n warnopts.remove(\"default::BytesWarning\")\n if dev_mode:\n warnopts.remove('default')\n for opt in warnopts:\n args.append('-W'+opt)\n \n \n if dev_mode:\n args.extend(('-X','dev'))\n for opt in ('faulthandler','tracemalloc','importtime',\n 'showalloccount','showrefcount','utf8'):\n if opt in xoptions:\n value=xoptions[opt]\n if value is True :\n arg=opt\n else :\n arg='%s=%s'%(opt,value)\n args.extend(('-X',arg))\n \n return args\n \n \ndef call(*popenargs,timeout=None ,**kwargs):\n ''\n\n\n\n\n\n \n with Popen(*popenargs,**kwargs)as p:\n try :\n return p.wait(timeout=timeout)\n except :\n p.kill()\n \n raise\n \n \ndef check_call(*popenargs,**kwargs):\n ''\n\n\n\n\n\n\n\n \n retcode=call(*popenargs,**kwargs)\n if retcode:\n cmd=kwargs.get(\"args\")\n if cmd is None :\n cmd=popenargs[0]\n raise CalledProcessError(retcode,cmd)\n return 0\n \n \ndef check_output(*popenargs,timeout=None ,**kwargs):\n ''\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n \n if 'stdout'in kwargs:\n raise ValueError('stdout argument not allowed, it will be overridden.')\n \n if 'input'in kwargs and kwargs['input']is None :\n \n \n kwargs['input']=''if kwargs.get('universal_newlines',False )else b''\n \n return run(*popenargs,stdout=PIPE,timeout=timeout,check=True ,\n **kwargs).stdout\n \n \nclass CompletedProcess(object):\n ''\n\n\n\n\n\n\n\n\n \n def __init__(self,args,returncode,stdout=None ,stderr=None ):\n self.args=args\n self.returncode=returncode\n self.stdout=stdout\n self.stderr=stderr\n \n def __repr__(self):\n args=['args={!r}'.format(self.args),\n 'returncode={!r}'.format(self.returncode)]\n if self.stdout is not None :\n args.append('stdout={!r}'.format(self.stdout))\n if self.stderr is not None :\n args.append('stderr={!r}'.format(self.stderr))\n return \"{}({})\".format(type(self).__name__,', '.join(args))\n \n def check_returncode(self):\n ''\n if self.returncode:\n raise CalledProcessError(self.returncode,self.args,self.stdout,\n self.stderr)\n \n \ndef run(*popenargs,\ninput=None ,capture_output=False ,timeout=None ,check=False ,**kwargs):\n ''\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n \n if input is not None :\n if 'stdin'in kwargs:\n raise ValueError('stdin and input arguments may not both be used.')\n kwargs['stdin']=PIPE\n \n if capture_output:\n if ('stdout'in kwargs)or ('stderr'in kwargs):\n raise ValueError('stdout and stderr arguments may not be used '\n 'with capture_output.')\n kwargs['stdout']=PIPE\n kwargs['stderr']=PIPE\n \n with Popen(*popenargs,**kwargs)as process:\n try :\n stdout,stderr=process.communicate(input,timeout=timeout)\n except TimeoutExpired:\n process.kill()\n stdout,stderr=process.communicate()\n raise TimeoutExpired(process.args,timeout,output=stdout,\n stderr=stderr)\n except :\n process.kill()\n \n raise\n retcode=process.poll()\n if check and retcode:\n raise CalledProcessError(retcode,process.args,\n output=stdout,stderr=stderr)\n return CompletedProcess(process.args,retcode,stdout,stderr)\n \n \ndef list2cmdline(seq):\n ''\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n \n \n \n \n \n \n result=[]\n needquote=False\n for arg in seq:\n bs_buf=[]\n \n \n if result:\n result.append(' ')\n \n needquote=(\" \"in arg)or (\"\\t\"in arg)or not arg\n if needquote:\n result.append('\"')\n \n for c in arg:\n if c =='\\\\':\n \n bs_buf.append(c)\n elif c =='\"':\n \n result.append('\\\\'*len(bs_buf)*2)\n bs_buf=[]\n result.append('\\\\\"')\n else :\n \n if bs_buf:\n result.extend(bs_buf)\n bs_buf=[]\n result.append(c)\n \n \n if bs_buf:\n result.extend(bs_buf)\n \n if needquote:\n result.extend(bs_buf)\n result.append('\"')\n \n return ''.join(result)\n \n \n \n \n \ndef getstatusoutput(cmd):\n ''\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n \n try :\n data=check_output(cmd,shell=True ,text=True ,stderr=STDOUT)\n exitcode=0\n except CalledProcessError as ex:\n data=ex.output\n exitcode=ex.returncode\n if data[-1:]=='\\n':\n data=data[:-1]\n return exitcode,data\n \ndef getoutput(cmd):\n ''\n\n\n\n\n\n\n\n \n return getstatusoutput(cmd)[1]\n \n \nclass Popen(object):\n ''\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n \n _child_created=False\n \n def __init__(self,args,bufsize=-1,executable=None ,\n stdin=None ,stdout=None ,stderr=None ,\n preexec_fn=None ,close_fds=True ,\n shell=False ,cwd=None ,env=None ,universal_newlines=None ,\n startupinfo=None ,creationflags=0,\n restore_signals=True ,start_new_session=False ,\n pass_fds=(),*,encoding=None ,errors=None ,text=None ):\n ''\n _cleanup()\n \n \n \n \n \n self._waitpid_lock=threading.Lock()\n \n self._input=None\n self._communication_started=False\n if bufsize is None :\n bufsize=-1\n if not isinstance(bufsize,int):\n raise TypeError(\"bufsize must be an integer\")\n \n if _mswindows:\n if preexec_fn is not None :\n raise ValueError(\"preexec_fn is not supported on Windows \"\n \"platforms\")\n else :\n \n if pass_fds and not close_fds:\n warnings.warn(\"pass_fds overriding close_fds.\",RuntimeWarning)\n close_fds=True\n if startupinfo is not None :\n raise ValueError(\"startupinfo is only supported on Windows \"\n \"platforms\")\n if creationflags !=0:\n raise ValueError(\"creationflags is only supported on Windows \"\n \"platforms\")\n \n self.args=args\n self.stdin=None\n self.stdout=None\n self.stderr=None\n self.pid=None\n self.returncode=None\n self.encoding=encoding\n self.errors=errors\n \n \n if (text is not None and universal_newlines is not None\n and bool(universal_newlines)!=bool(text)):\n raise SubprocessError('Cannot disambiguate when both text '\n 'and universal_newlines are supplied but '\n 'different. Pass one or the other.')\n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n (p2cread,p2cwrite,\n c2pread,c2pwrite,\n errread,errwrite)=self._get_handles(stdin,stdout,stderr)\n \n \n \n \n \n if _mswindows:\n if p2cwrite !=-1:\n p2cwrite=msvcrt.open_osfhandle(p2cwrite.Detach(),0)\n if c2pread !=-1:\n c2pread=msvcrt.open_osfhandle(c2pread.Detach(),0)\n if errread !=-1:\n errread=msvcrt.open_osfhandle(errread.Detach(),0)\n \n self.text_mode=encoding or errors or text or universal_newlines\n \n \n \n \n self._sigint_wait_secs=0.25\n \n self._closed_child_pipe_fds=False\n \n try :\n if p2cwrite !=-1:\n self.stdin=io.open(p2cwrite,'wb',bufsize)\n if self.text_mode:\n self.stdin=io.TextIOWrapper(self.stdin,write_through=True ,\n line_buffering=(bufsize ==1),\n encoding=encoding,errors=errors)\n if c2pread !=-1:\n self.stdout=io.open(c2pread,'rb',bufsize)\n if self.text_mode:\n self.stdout=io.TextIOWrapper(self.stdout,\n encoding=encoding,errors=errors)\n if errread !=-1:\n self.stderr=io.open(errread,'rb',bufsize)\n if self.text_mode:\n self.stderr=io.TextIOWrapper(self.stderr,\n encoding=encoding,errors=errors)\n \n self._execute_child(args,executable,preexec_fn,close_fds,\n pass_fds,cwd,env,\n startupinfo,creationflags,shell,\n p2cread,p2cwrite,\n c2pread,c2pwrite,\n errread,errwrite,\n restore_signals,start_new_session)\n except :\n \n for f in filter(None ,(self.stdin,self.stdout,self.stderr)):\n try :\n f.close()\n except OSError:\n pass\n \n if not self._closed_child_pipe_fds:\n to_close=[]\n if stdin ==PIPE:\n to_close.append(p2cread)\n if stdout ==PIPE:\n to_close.append(c2pwrite)\n if stderr ==PIPE:\n to_close.append(errwrite)\n if hasattr(self,'_devnull'):\n to_close.append(self._devnull)\n for fd in to_close:\n try :\n if _mswindows and isinstance(fd,Handle):\n fd.Close()\n else :\n os.close(fd)\n except OSError:\n pass\n \n raise\n \n @property\n def universal_newlines(self):\n \n \n return self.text_mode\n \n @universal_newlines.setter\n def universal_newlines(self,universal_newlines):\n self.text_mode=bool(universal_newlines)\n \n def _translate_newlines(self,data,encoding,errors):\n data=data.decode(encoding,errors)\n return data.replace(\"\\r\\n\",\"\\n\").replace(\"\\r\",\"\\n\")\n \n def __enter__(self):\n return self\n \n def __exit__(self,exc_type,value,traceback):\n if self.stdout:\n self.stdout.close()\n if self.stderr:\n self.stderr.close()\n try :\n if self.stdin:\n self.stdin.close()\n finally :\n if exc_type ==KeyboardInterrupt:\n \n \n \n \n \n \n \n if self._sigint_wait_secs >0:\n try :\n self._wait(timeout=self._sigint_wait_secs)\n except TimeoutExpired:\n pass\n self._sigint_wait_secs=0\n return\n \n \n self.wait()\n \n def __del__(self,_maxsize=sys.maxsize,_warn=warnings.warn):\n if not self._child_created:\n \n return\n if self.returncode is None :\n \n \n _warn(\"subprocess %s is still running\"%self.pid,\n ResourceWarning,source=self)\n \n self._internal_poll(_deadstate=_maxsize)\n if self.returncode is None and _active is not None :\n \n _active.append(self)\n \n def _get_devnull(self):\n if not hasattr(self,'_devnull'):\n self._devnull=os.open(os.devnull,os.O_RDWR)\n return self._devnull\n \n def _stdin_write(self,input):\n if input:\n try :\n self.stdin.write(input)\n except BrokenPipeError:\n pass\n except OSError as exc:\n if exc.errno ==errno.EINVAL:\n \n \n \n pass\n else :\n raise\n \n try :\n self.stdin.close()\n except BrokenPipeError:\n pass\n except OSError as exc:\n if exc.errno ==errno.EINVAL:\n pass\n else :\n raise\n \n def communicate(self,input=None ,timeout=None ):\n ''\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n \n \n if self._communication_started and input:\n raise ValueError(\"Cannot send input after starting communication\")\n \n \n \n \n if (timeout is None and not self._communication_started and\n [self.stdin,self.stdout,self.stderr].count(None )>=2):\n stdout=None\n stderr=None\n if self.stdin:\n self._stdin_write(input)\n elif self.stdout:\n stdout=self.stdout.read()\n self.stdout.close()\n elif self.stderr:\n stderr=self.stderr.read()\n self.stderr.close()\n self.wait()\n else :\n if timeout is not None :\n endtime=_time()+timeout\n else :\n endtime=None\n \n try :\n stdout,stderr=self._communicate(input,endtime,timeout)\n except KeyboardInterrupt:\n \n \n if timeout is not None :\n sigint_timeout=min(self._sigint_wait_secs,\n self._remaining_time(endtime))\n else :\n sigint_timeout=self._sigint_wait_secs\n self._sigint_wait_secs=0\n try :\n self._wait(timeout=sigint_timeout)\n except TimeoutExpired:\n pass\n raise\n \n finally :\n self._communication_started=True\n \n sts=self.wait(timeout=self._remaining_time(endtime))\n \n return (stdout,stderr)\n \n \n def poll(self):\n ''\n \n return self._internal_poll()\n \n \n def _remaining_time(self,endtime):\n ''\n if endtime is None :\n return None\n else :\n return endtime -_time()\n \n \n def _check_timeout(self,endtime,orig_timeout):\n ''\n if endtime is None :\n return\n if _time()>endtime:\n raise TimeoutExpired(self.args,orig_timeout)\n \n \n def wait(self,timeout=None ):\n ''\n if timeout is not None :\n endtime=_time()+timeout\n try :\n return self._wait(timeout=timeout)\n except KeyboardInterrupt:\n \n \n \n \n if timeout is not None :\n sigint_timeout=min(self._sigint_wait_secs,\n self._remaining_time(endtime))\n else :\n sigint_timeout=self._sigint_wait_secs\n self._sigint_wait_secs=0\n try :\n self._wait(timeout=sigint_timeout)\n except TimeoutExpired:\n pass\n raise\n \n \n if _mswindows:\n \n \n \n def _get_handles(self,stdin,stdout,stderr):\n ''\n\n \n if stdin is None and stdout is None and stderr is None :\n return (-1,-1,-1,-1,-1,-1)\n \n p2cread,p2cwrite=-1,-1\n c2pread,c2pwrite=-1,-1\n errread,errwrite=-1,-1\n \n if stdin is None :\n p2cread=_winapi.GetStdHandle(_winapi.STD_INPUT_HANDLE)\n if p2cread is None :\n p2cread,_=_winapi.CreatePipe(None ,0)\n p2cread=Handle(p2cread)\n _winapi.CloseHandle(_)\n elif stdin ==PIPE:\n p2cread,p2cwrite=_winapi.CreatePipe(None ,0)\n p2cread,p2cwrite=Handle(p2cread),Handle(p2cwrite)\n elif stdin ==DEVNULL:\n p2cread=msvcrt.get_osfhandle(self._get_devnull())\n elif isinstance(stdin,int):\n p2cread=msvcrt.get_osfhandle(stdin)\n else :\n \n p2cread=msvcrt.get_osfhandle(stdin.fileno())\n p2cread=self._make_inheritable(p2cread)\n \n if stdout is None :\n c2pwrite=_winapi.GetStdHandle(_winapi.STD_OUTPUT_HANDLE)\n if c2pwrite is None :\n _,c2pwrite=_winapi.CreatePipe(None ,0)\n c2pwrite=Handle(c2pwrite)\n _winapi.CloseHandle(_)\n elif stdout ==PIPE:\n c2pread,c2pwrite=_winapi.CreatePipe(None ,0)\n c2pread,c2pwrite=Handle(c2pread),Handle(c2pwrite)\n elif stdout ==DEVNULL:\n c2pwrite=msvcrt.get_osfhandle(self._get_devnull())\n elif isinstance(stdout,int):\n c2pwrite=msvcrt.get_osfhandle(stdout)\n else :\n \n c2pwrite=msvcrt.get_osfhandle(stdout.fileno())\n c2pwrite=self._make_inheritable(c2pwrite)\n \n if stderr is None :\n errwrite=_winapi.GetStdHandle(_winapi.STD_ERROR_HANDLE)\n if errwrite is None :\n _,errwrite=_winapi.CreatePipe(None ,0)\n errwrite=Handle(errwrite)\n _winapi.CloseHandle(_)\n elif stderr ==PIPE:\n errread,errwrite=_winapi.CreatePipe(None ,0)\n errread,errwrite=Handle(errread),Handle(errwrite)\n elif stderr ==STDOUT:\n errwrite=c2pwrite\n elif stderr ==DEVNULL:\n errwrite=msvcrt.get_osfhandle(self._get_devnull())\n elif isinstance(stderr,int):\n errwrite=msvcrt.get_osfhandle(stderr)\n else :\n \n errwrite=msvcrt.get_osfhandle(stderr.fileno())\n errwrite=self._make_inheritable(errwrite)\n \n return (p2cread,p2cwrite,\n c2pread,c2pwrite,\n errread,errwrite)\n \n \n def _make_inheritable(self,handle):\n ''\n h=_winapi.DuplicateHandle(\n _winapi.GetCurrentProcess(),handle,\n _winapi.GetCurrentProcess(),0,1,\n _winapi.DUPLICATE_SAME_ACCESS)\n return Handle(h)\n \n \n def _filter_handle_list(self,handle_list):\n ''\n\n \n \n \n \n return list({handle for handle in handle_list\n if handle&0x3 !=0x3\n or _winapi.GetFileType(handle)!=\n _winapi.FILE_TYPE_CHAR})\n \n \n def _execute_child(self,args,executable,preexec_fn,close_fds,\n pass_fds,cwd,env,\n startupinfo,creationflags,shell,\n p2cread,p2cwrite,\n c2pread,c2pwrite,\n errread,errwrite,\n unused_restore_signals,unused_start_new_session):\n ''\n \n assert not pass_fds,\"pass_fds not supported on Windows.\"\n \n if not isinstance(args,str):\n args=list2cmdline(args)\n \n \n if startupinfo is None :\n startupinfo=STARTUPINFO()\n \n use_std_handles=-1 not in (p2cread,c2pwrite,errwrite)\n if use_std_handles:\n startupinfo.dwFlags |=_winapi.STARTF_USESTDHANDLES\n startupinfo.hStdInput=p2cread\n startupinfo.hStdOutput=c2pwrite\n startupinfo.hStdError=errwrite\n \n attribute_list=startupinfo.lpAttributeList\n have_handle_list=bool(attribute_list and\n \"handle_list\"in attribute_list and\n attribute_list[\"handle_list\"])\n \n \n if have_handle_list or (use_std_handles and close_fds):\n if attribute_list is None :\n attribute_list=startupinfo.lpAttributeList={}\n handle_list=attribute_list[\"handle_list\"]=\\\n list(attribute_list.get(\"handle_list\",[]))\n \n if use_std_handles:\n handle_list +=[int(p2cread),int(c2pwrite),int(errwrite)]\n \n handle_list[:]=self._filter_handle_list(handle_list)\n \n if handle_list:\n if not close_fds:\n warnings.warn(\"startupinfo.lpAttributeList['handle_list'] \"\n \"overriding close_fds\",RuntimeWarning)\n \n \n \n \n close_fds=False\n \n if shell:\n startupinfo.dwFlags |=_winapi.STARTF_USESHOWWINDOW\n startupinfo.wShowWindow=_winapi.SW_HIDE\n comspec=os.environ.get(\"COMSPEC\",\"cmd.exe\")\n args='{} /c \"{}\"'.format(comspec,args)\n \n \n try :\n hp,ht,pid,tid=_winapi.CreateProcess(executable,args,\n \n None ,None ,\n int(not close_fds),\n creationflags,\n env,\n os.fspath(cwd)if cwd is not None else None ,\n startupinfo)\n finally :\n \n \n \n \n \n \n if p2cread !=-1:\n p2cread.Close()\n if c2pwrite !=-1:\n c2pwrite.Close()\n if errwrite !=-1:\n errwrite.Close()\n if hasattr(self,'_devnull'):\n os.close(self._devnull)\n \n \n self._closed_child_pipe_fds=True\n \n \n self._child_created=True\n self._handle=Handle(hp)\n self.pid=pid\n _winapi.CloseHandle(ht)\n \n def _internal_poll(self,_deadstate=None ,\n _WaitForSingleObject=_winapi.WaitForSingleObject,\n _WAIT_OBJECT_0=_winapi.WAIT_OBJECT_0,\n _GetExitCodeProcess=_winapi.GetExitCodeProcess):\n ''\n\n\n\n\n\n \n if self.returncode is None :\n if _WaitForSingleObject(self._handle,0)==_WAIT_OBJECT_0:\n self.returncode=_GetExitCodeProcess(self._handle)\n return self.returncode\n \n \n def _wait(self,timeout):\n ''\n if timeout is None :\n timeout_millis=_winapi.INFINITE\n else :\n timeout_millis=int(timeout *1000)\n if self.returncode is None :\n \n result=_winapi.WaitForSingleObject(self._handle,\n timeout_millis)\n if result ==_winapi.WAIT_TIMEOUT:\n raise TimeoutExpired(self.args,timeout)\n self.returncode=_winapi.GetExitCodeProcess(self._handle)\n return self.returncode\n \n \n def _readerthread(self,fh,buffer):\n buffer.append(fh.read())\n fh.close()\n \n \n def _communicate(self,input,endtime,orig_timeout):\n \n \n if self.stdout and not hasattr(self,\"_stdout_buff\"):\n self._stdout_buff=[]\n self.stdout_thread=\\\n threading.Thread(target=self._readerthread,\n args=(self.stdout,self._stdout_buff))\n self.stdout_thread.daemon=True\n self.stdout_thread.start()\n if self.stderr and not hasattr(self,\"_stderr_buff\"):\n self._stderr_buff=[]\n self.stderr_thread=\\\n threading.Thread(target=self._readerthread,\n args=(self.stderr,self._stderr_buff))\n self.stderr_thread.daemon=True\n self.stderr_thread.start()\n \n if self.stdin:\n self._stdin_write(input)\n \n \n \n \n if self.stdout is not None :\n self.stdout_thread.join(self._remaining_time(endtime))\n if self.stdout_thread.is_alive():\n raise TimeoutExpired(self.args,orig_timeout)\n if self.stderr is not None :\n self.stderr_thread.join(self._remaining_time(endtime))\n if self.stderr_thread.is_alive():\n raise TimeoutExpired(self.args,orig_timeout)\n \n \n \n stdout=None\n stderr=None\n if self.stdout:\n stdout=self._stdout_buff\n self.stdout.close()\n if self.stderr:\n stderr=self._stderr_buff\n self.stderr.close()\n \n \n if stdout is not None :\n stdout=stdout[0]\n if stderr is not None :\n stderr=stderr[0]\n \n return (stdout,stderr)\n \n def send_signal(self,sig):\n ''\n \n if self.returncode is not None :\n return\n if sig ==signal.SIGTERM:\n self.terminate()\n elif sig ==signal.CTRL_C_EVENT:\n os.kill(self.pid,signal.CTRL_C_EVENT)\n elif sig ==signal.CTRL_BREAK_EVENT:\n os.kill(self.pid,signal.CTRL_BREAK_EVENT)\n else :\n raise ValueError(\"Unsupported signal: {}\".format(sig))\n \n def terminate(self):\n ''\n \n if self.returncode is not None :\n return\n try :\n _winapi.TerminateProcess(self._handle,1)\n except PermissionError:\n \n \n rc=_winapi.GetExitCodeProcess(self._handle)\n if rc ==_winapi.STILL_ACTIVE:\n raise\n self.returncode=rc\n \n kill=terminate\n \n else :\n \n \n \n def _get_handles(self,stdin,stdout,stderr):\n ''\n\n \n p2cread,p2cwrite=-1,-1\n c2pread,c2pwrite=-1,-1\n errread,errwrite=-1,-1\n \n if stdin is None :\n pass\n elif stdin ==PIPE:\n p2cread,p2cwrite=os.pipe()\n elif stdin ==DEVNULL:\n p2cread=self._get_devnull()\n elif isinstance(stdin,int):\n p2cread=stdin\n else :\n \n p2cread=stdin.fileno()\n \n if stdout is None :\n pass\n elif stdout ==PIPE:\n c2pread,c2pwrite=os.pipe()\n elif stdout ==DEVNULL:\n c2pwrite=self._get_devnull()\n elif isinstance(stdout,int):\n c2pwrite=stdout\n else :\n \n c2pwrite=stdout.fileno()\n \n if stderr is None :\n pass\n elif stderr ==PIPE:\n errread,errwrite=os.pipe()\n elif stderr ==STDOUT:\n if c2pwrite !=-1:\n errwrite=c2pwrite\n else :\n errwrite=sys.__stdout__.fileno()\n elif stderr ==DEVNULL:\n errwrite=self._get_devnull()\n elif isinstance(stderr,int):\n errwrite=stderr\n else :\n \n errwrite=stderr.fileno()\n \n return (p2cread,p2cwrite,\n c2pread,c2pwrite,\n errread,errwrite)\n \n \n def _execute_child(self,args,executable,preexec_fn,close_fds,\n pass_fds,cwd,env,\n startupinfo,creationflags,shell,\n p2cread,p2cwrite,\n c2pread,c2pwrite,\n errread,errwrite,\n restore_signals,start_new_session):\n ''\n \n if isinstance(args,(str,bytes)):\n args=[args]\n else :\n args=list(args)\n \n if shell:\n \n unix_shell=('/system/bin/sh'if\n hasattr(sys,'getandroidapilevel')else '/bin/sh')\n args=[unix_shell,\"-c\"]+args\n if executable:\n args[0]=executable\n \n if executable is None :\n executable=args[0]\n orig_executable=executable\n \n \n \n \n errpipe_read,errpipe_write=os.pipe()\n \n low_fds_to_close=[]\n while errpipe_write <3:\n low_fds_to_close.append(errpipe_write)\n errpipe_write=os.dup(errpipe_write)\n for low_fd in low_fds_to_close:\n os.close(low_fd)\n try :\n try :\n \n \n \n \n \n if env is not None :\n env_list=[]\n for k,v in env.items():\n k=os.fsencode(k)\n if b'='in k:\n raise ValueError(\"illegal environment variable name\")\n env_list.append(k+b'='+os.fsencode(v))\n else :\n env_list=None\n executable=os.fsencode(executable)\n if os.path.dirname(executable):\n executable_list=(executable,)\n else :\n \n executable_list=tuple(\n os.path.join(os.fsencode(dir),executable)\n for dir in os.get_exec_path(env))\n fds_to_keep=set(pass_fds)\n fds_to_keep.add(errpipe_write)\n self.pid=_posixsubprocess.fork_exec(\n args,executable_list,\n close_fds,tuple(sorted(map(int,fds_to_keep))),\n cwd,env_list,\n p2cread,p2cwrite,c2pread,c2pwrite,\n errread,errwrite,\n errpipe_read,errpipe_write,\n restore_signals,start_new_session,preexec_fn)\n self._child_created=True\n finally :\n \n os.close(errpipe_write)\n \n \n devnull_fd=getattr(self,'_devnull',None )\n if p2cread !=-1 and p2cwrite !=-1 and p2cread !=devnull_fd:\n os.close(p2cread)\n if c2pwrite !=-1 and c2pread !=-1 and c2pwrite !=devnull_fd:\n os.close(c2pwrite)\n if errwrite !=-1 and errread !=-1 and errwrite !=devnull_fd:\n os.close(errwrite)\n if devnull_fd is not None :\n os.close(devnull_fd)\n \n self._closed_child_pipe_fds=True\n \n \n \n errpipe_data=bytearray()\n while True :\n part=os.read(errpipe_read,50000)\n errpipe_data +=part\n if not part or len(errpipe_data)>50000:\n break\n finally :\n \n os.close(errpipe_read)\n \n if errpipe_data:\n try :\n pid,sts=os.waitpid(self.pid,0)\n if pid ==self.pid:\n self._handle_exitstatus(sts)\n else :\n self.returncode=sys.maxsize\n except ChildProcessError:\n pass\n \n try :\n exception_name,hex_errno,err_msg=(\n errpipe_data.split(b':',2))\n \n \n \n err_msg=err_msg.decode()\n except ValueError:\n exception_name=b'SubprocessError'\n hex_errno=b'0'\n err_msg='Bad exception data from child: {!r}'.format(\n bytes(errpipe_data))\n child_exception_type=getattr(\n builtins,exception_name.decode('ascii'),\n SubprocessError)\n if issubclass(child_exception_type,OSError)and hex_errno:\n errno_num=int(hex_errno,16)\n child_exec_never_called=(err_msg ==\"noexec\")\n if child_exec_never_called:\n err_msg=\"\"\n \n err_filename=cwd\n else :\n err_filename=orig_executable\n if errno_num !=0:\n err_msg=os.strerror(errno_num)\n if errno_num ==errno.ENOENT:\n err_msg +=': '+repr(err_filename)\n raise child_exception_type(errno_num,err_msg,err_filename)\n raise child_exception_type(err_msg)\n \n \n def _handle_exitstatus(self,sts,_WIFSIGNALED=os.WIFSIGNALED,\n _WTERMSIG=os.WTERMSIG,_WIFEXITED=os.WIFEXITED,\n _WEXITSTATUS=os.WEXITSTATUS,_WIFSTOPPED=os.WIFSTOPPED,\n _WSTOPSIG=os.WSTOPSIG):\n ''\n \n \n if _WIFSIGNALED(sts):\n self.returncode=-_WTERMSIG(sts)\n elif _WIFEXITED(sts):\n self.returncode=_WEXITSTATUS(sts)\n elif _WIFSTOPPED(sts):\n self.returncode=-_WSTOPSIG(sts)\n else :\n \n raise SubprocessError(\"Unknown child exit status!\")\n \n \n def _internal_poll(self,_deadstate=None ,_waitpid=os.waitpid,\n _WNOHANG=os.WNOHANG,_ECHILD=errno.ECHILD):\n ''\n\n\n\n\n\n \n if self.returncode is None :\n if not self._waitpid_lock.acquire(False ):\n \n \n return None\n try :\n if self.returncode is not None :\n return self.returncode\n pid,sts=_waitpid(self.pid,_WNOHANG)\n if pid ==self.pid:\n self._handle_exitstatus(sts)\n except OSError as e:\n if _deadstate is not None :\n self.returncode=_deadstate\n elif e.errno ==_ECHILD:\n \n \n \n \n \n self.returncode=0\n finally :\n self._waitpid_lock.release()\n return self.returncode\n \n \n def _try_wait(self,wait_flags):\n ''\n try :\n (pid,sts)=os.waitpid(self.pid,wait_flags)\n except ChildProcessError:\n \n \n \n pid=self.pid\n sts=0\n return (pid,sts)\n \n \n def _wait(self,timeout):\n ''\n if self.returncode is not None :\n return self.returncode\n \n if timeout is not None :\n endtime=_time()+timeout\n \n \n delay=0.0005\n while True :\n if self._waitpid_lock.acquire(False ):\n try :\n if self.returncode is not None :\n break\n (pid,sts)=self._try_wait(os.WNOHANG)\n assert pid ==self.pid or pid ==0\n if pid ==self.pid:\n self._handle_exitstatus(sts)\n break\n finally :\n self._waitpid_lock.release()\n remaining=self._remaining_time(endtime)\n if remaining <=0:\n raise TimeoutExpired(self.args,timeout)\n delay=min(delay *2,remaining,.05)\n time.sleep(delay)\n else :\n while self.returncode is None :\n with self._waitpid_lock:\n if self.returncode is not None :\n break\n (pid,sts)=self._try_wait(0)\n \n \n \n if pid ==self.pid:\n self._handle_exitstatus(sts)\n return self.returncode\n \n \n def _communicate(self,input,endtime,orig_timeout):\n if self.stdin and not self._communication_started:\n \n \n try :\n self.stdin.flush()\n except BrokenPipeError:\n pass\n if not input:\n try :\n self.stdin.close()\n except BrokenPipeError:\n pass\n \n stdout=None\n stderr=None\n \n \n if not self._communication_started:\n self._fileobj2output={}\n if self.stdout:\n self._fileobj2output[self.stdout]=[]\n if self.stderr:\n self._fileobj2output[self.stderr]=[]\n \n if self.stdout:\n stdout=self._fileobj2output[self.stdout]\n if self.stderr:\n stderr=self._fileobj2output[self.stderr]\n \n self._save_input(input)\n \n if self._input:\n input_view=memoryview(self._input)\n \n with _PopenSelector()as selector:\n if self.stdin and input:\n selector.register(self.stdin,selectors.EVENT_WRITE)\n if self.stdout:\n selector.register(self.stdout,selectors.EVENT_READ)\n if self.stderr:\n selector.register(self.stderr,selectors.EVENT_READ)\n \n while selector.get_map():\n timeout=self._remaining_time(endtime)\n if timeout is not None and timeout <0:\n raise TimeoutExpired(self.args,orig_timeout)\n \n ready=selector.select(timeout)\n self._check_timeout(endtime,orig_timeout)\n \n \n \n \n for key,events in ready:\n if key.fileobj is self.stdin:\n chunk=input_view[self._input_offset:\n self._input_offset+_PIPE_BUF]\n try :\n self._input_offset +=os.write(key.fd,chunk)\n except BrokenPipeError:\n selector.unregister(key.fileobj)\n key.fileobj.close()\n else :\n if self._input_offset >=len(self._input):\n selector.unregister(key.fileobj)\n key.fileobj.close()\n elif key.fileobj in (self.stdout,self.stderr):\n data=os.read(key.fd,32768)\n if not data:\n selector.unregister(key.fileobj)\n key.fileobj.close()\n self._fileobj2output[key.fileobj].append(data)\n \n self.wait(timeout=self._remaining_time(endtime))\n \n \n if stdout is not None :\n stdout=b''.join(stdout)\n if stderr is not None :\n stderr=b''.join(stderr)\n \n \n \n if self.text_mode:\n if stdout is not None :\n stdout=self._translate_newlines(stdout,\n self.stdout.encoding,\n self.stdout.errors)\n if stderr is not None :\n stderr=self._translate_newlines(stderr,\n self.stderr.encoding,\n self.stderr.errors)\n \n return (stdout,stderr)\n \n \n def _save_input(self,input):\n \n \n \n if self.stdin and self._input is None :\n self._input_offset=0\n self._input=input\n if input is not None and self.text_mode:\n self._input=self._input.encode(self.stdin.encoding,\n self.stdin.errors)\n \n \n def send_signal(self,sig):\n ''\n \n if self.returncode is None :\n os.kill(self.pid,sig)\n \n def terminate(self):\n ''\n \n self.send_signal(signal.SIGTERM)\n \n def kill(self):\n ''\n \n self.send_signal(signal.SIGKILL)\n", ["_posixsubprocess", "_winapi", "builtins", "errno", "io", "msvcrt", "os", "select", "selectors", "signal", "sys", "threading", "time", "warnings"]], "selectors": [".py", "''\n\n\n\n\n\n\nfrom abc import ABCMeta,abstractmethod\nfrom collections import namedtuple\nfrom collections.abc import Mapping\nimport math\nimport select\nimport sys\n\n\n\nEVENT_READ=(1 <<0)\nEVENT_WRITE=(1 <<1)\n\n\ndef _fileobj_to_fd(fileobj):\n ''\n\n\n\n\n\n\n\n\n\n \n if isinstance(fileobj,int):\n fd=fileobj\n else :\n try :\n fd=int(fileobj.fileno())\n except (AttributeError,TypeError,ValueError):\n raise ValueError(\"Invalid file object: \"\n \"{!r}\".format(fileobj))from None\n if fd <0:\n raise ValueError(\"Invalid file descriptor: {}\".format(fd))\n return fd\n \n \nSelectorKey=namedtuple('SelectorKey',['fileobj','fd','events','data'])\n\nSelectorKey.__doc__=\"\"\"SelectorKey(fileobj, fd, events, data)\n\n Object used to associate a file object to its backing\n file descriptor, selected event mask, and attached data.\n\"\"\"\nif sys.version_info >=(3,5):\n SelectorKey.fileobj.__doc__='File object registered.'\n SelectorKey.fd.__doc__='Underlying file descriptor.'\n SelectorKey.events.__doc__='Events that must be waited for on this file object.'\n SelectorKey.data.__doc__=('''Optional opaque data associated to this file object.\n For example, this could be used to store a per-client session ID.''')\n \nclass _SelectorMapping(Mapping):\n ''\n \n def __init__(self,selector):\n self._selector=selector\n \n def __len__(self):\n return len(self._selector._fd_to_key)\n \n def __getitem__(self,fileobj):\n try :\n fd=self._selector._fileobj_lookup(fileobj)\n return self._selector._fd_to_key[fd]\n except KeyError:\n raise KeyError(\"{!r} is not registered\".format(fileobj))from None\n \n def __iter__(self):\n return iter(self._selector._fd_to_key)\n \n \nclass BaseSelector(metaclass=ABCMeta):\n ''\n\n\n\n\n\n\n\n\n\n\n\n \n \n @abstractmethod\n def register(self,fileobj,events,data=None ):\n ''\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n \n raise NotImplementedError\n \n @abstractmethod\n def unregister(self,fileobj):\n ''\n\n\n\n\n\n\n\n\n\n\n\n\n\n \n raise NotImplementedError\n \n def modify(self,fileobj,events,data=None ):\n ''\n\n\n\n\n\n\n\n\n\n\n\n \n self.unregister(fileobj)\n return self.register(fileobj,events,data)\n \n @abstractmethod\n def select(self,timeout=None ):\n ''\n\n\n\n\n\n\n\n\n\n\n\n\n\n \n raise NotImplementedError\n \n def close(self):\n ''\n\n\n \n pass\n \n def get_key(self,fileobj):\n ''\n\n\n\n \n mapping=self.get_map()\n if mapping is None :\n raise RuntimeError('Selector is closed')\n try :\n return mapping[fileobj]\n except KeyError:\n raise KeyError(\"{!r} is not registered\".format(fileobj))from None\n \n @abstractmethod\n def get_map(self):\n ''\n raise NotImplementedError\n \n def __enter__(self):\n return self\n \n def __exit__(self,*args):\n self.close()\n \n \nclass _BaseSelectorImpl(BaseSelector):\n ''\n \n def __init__(self):\n \n self._fd_to_key={}\n \n self._map=_SelectorMapping(self)\n \n def _fileobj_lookup(self,fileobj):\n ''\n\n\n\n\n\n\n \n try :\n return _fileobj_to_fd(fileobj)\n except ValueError:\n \n for key in self._fd_to_key.values():\n if key.fileobj is fileobj:\n return key.fd\n \n raise\n \n def register(self,fileobj,events,data=None ):\n if (not events)or (events&~(EVENT_READ |EVENT_WRITE)):\n raise ValueError(\"Invalid events: {!r}\".format(events))\n \n key=SelectorKey(fileobj,self._fileobj_lookup(fileobj),events,data)\n \n if key.fd in self._fd_to_key:\n raise KeyError(\"{!r} (FD {}) is already registered\"\n .format(fileobj,key.fd))\n \n self._fd_to_key[key.fd]=key\n return key\n \n def unregister(self,fileobj):\n try :\n key=self._fd_to_key.pop(self._fileobj_lookup(fileobj))\n except KeyError:\n raise KeyError(\"{!r} is not registered\".format(fileobj))from None\n return key\n \n def modify(self,fileobj,events,data=None ):\n try :\n key=self._fd_to_key[self._fileobj_lookup(fileobj)]\n except KeyError:\n raise KeyError(\"{!r} is not registered\".format(fileobj))from None\n if events !=key.events:\n self.unregister(fileobj)\n key=self.register(fileobj,events,data)\n elif data !=key.data:\n \n key=key._replace(data=data)\n self._fd_to_key[key.fd]=key\n return key\n \n def close(self):\n self._fd_to_key.clear()\n self._map=None\n \n def get_map(self):\n return self._map\n \n def _key_from_fd(self,fd):\n ''\n\n\n\n\n\n\n \n try :\n return self._fd_to_key[fd]\n except KeyError:\n return None\n \n \nclass SelectSelector(_BaseSelectorImpl):\n ''\n \n def __init__(self):\n super().__init__()\n self._readers=set()\n self._writers=set()\n \n def register(self,fileobj,events,data=None ):\n key=super().register(fileobj,events,data)\n if events&EVENT_READ:\n self._readers.add(key.fd)\n if events&EVENT_WRITE:\n self._writers.add(key.fd)\n return key\n \n def unregister(self,fileobj):\n key=super().unregister(fileobj)\n self._readers.discard(key.fd)\n self._writers.discard(key.fd)\n return key\n \n if sys.platform =='win32':\n def _select(self,r,w,_,timeout=None ):\n r,w,x=select.select(r,w,w,timeout)\n return r,w+x,[]\n else :\n _select=select.select\n \n def select(self,timeout=None ):\n timeout=None if timeout is None else max(timeout,0)\n ready=[]\n try :\n r,w,_=self._select(self._readers,self._writers,[],timeout)\n except InterruptedError:\n return ready\n r=set(r)\n w=set(w)\n for fd in r |w:\n events=0\n if fd in r:\n events |=EVENT_READ\n if fd in w:\n events |=EVENT_WRITE\n \n key=self._key_from_fd(fd)\n if key:\n ready.append((key,events&key.events))\n return ready\n \n \nclass _PollLikeSelector(_BaseSelectorImpl):\n ''\n _selector_cls=None\n _EVENT_READ=None\n _EVENT_WRITE=None\n \n def __init__(self):\n super().__init__()\n self._selector=self._selector_cls()\n \n def register(self,fileobj,events,data=None ):\n key=super().register(fileobj,events,data)\n poller_events=0\n if events&EVENT_READ:\n poller_events |=self._EVENT_READ\n if events&EVENT_WRITE:\n poller_events |=self._EVENT_WRITE\n try :\n self._selector.register(key.fd,poller_events)\n except :\n super().unregister(fileobj)\n raise\n return key\n \n def unregister(self,fileobj):\n key=super().unregister(fileobj)\n try :\n self._selector.unregister(key.fd)\n except OSError:\n \n \n pass\n return key\n \n def modify(self,fileobj,events,data=None ):\n try :\n key=self._fd_to_key[self._fileobj_lookup(fileobj)]\n except KeyError:\n raise KeyError(f\"{fileobj!r} is not registered\")from None\n \n changed=False\n if events !=key.events:\n selector_events=0\n if events&EVENT_READ:\n selector_events |=self._EVENT_READ\n if events&EVENT_WRITE:\n selector_events |=self._EVENT_WRITE\n try :\n self._selector.modify(key.fd,selector_events)\n except :\n super().unregister(fileobj)\n raise\n changed=True\n if data !=key.data:\n changed=True\n \n if changed:\n key=key._replace(events=events,data=data)\n self._fd_to_key[key.fd]=key\n return key\n \n def select(self,timeout=None ):\n \n \n if timeout is None :\n timeout=None\n elif timeout <=0:\n timeout=0\n else :\n \n \n timeout=math.ceil(timeout *1e3)\n ready=[]\n try :\n fd_event_list=self._selector.poll(timeout)\n except InterruptedError:\n return ready\n for fd,event in fd_event_list:\n events=0\n if event&~self._EVENT_READ:\n events |=EVENT_WRITE\n if event&~self._EVENT_WRITE:\n events |=EVENT_READ\n \n key=self._key_from_fd(fd)\n if key:\n ready.append((key,events&key.events))\n return ready\n \n \nif hasattr(select,'poll'):\n\n class PollSelector(_PollLikeSelector):\n ''\n _selector_cls=select.poll\n _EVENT_READ=select.POLLIN\n _EVENT_WRITE=select.POLLOUT\n \n \nif hasattr(select,'epoll'):\n\n class EpollSelector(_PollLikeSelector):\n ''\n _selector_cls=select.epoll\n _EVENT_READ=select.EPOLLIN\n _EVENT_WRITE=select.EPOLLOUT\n \n def fileno(self):\n return self._selector.fileno()\n \n def select(self,timeout=None ):\n if timeout is None :\n timeout=-1\n elif timeout <=0:\n timeout=0\n else :\n \n \n timeout=math.ceil(timeout *1e3)*1e-3\n \n \n \n \n max_ev=max(len(self._fd_to_key),1)\n \n ready=[]\n try :\n fd_event_list=self._selector.poll(timeout,max_ev)\n except InterruptedError:\n return ready\n for fd,event in fd_event_list:\n events=0\n if event&~select.EPOLLIN:\n events |=EVENT_WRITE\n if event&~select.EPOLLOUT:\n events |=EVENT_READ\n \n key=self._key_from_fd(fd)\n if key:\n ready.append((key,events&key.events))\n return ready\n \n def close(self):\n self._selector.close()\n super().close()\n \n \nif hasattr(select,'devpoll'):\n\n class DevpollSelector(_PollLikeSelector):\n ''\n _selector_cls=select.devpoll\n _EVENT_READ=select.POLLIN\n _EVENT_WRITE=select.POLLOUT\n \n def fileno(self):\n return self._selector.fileno()\n \n def close(self):\n self._selector.close()\n super().close()\n \n \nif hasattr(select,'kqueue'):\n\n class KqueueSelector(_BaseSelectorImpl):\n ''\n \n def __init__(self):\n super().__init__()\n self._selector=select.kqueue()\n \n def fileno(self):\n return self._selector.fileno()\n \n def register(self,fileobj,events,data=None ):\n key=super().register(fileobj,events,data)\n try :\n if events&EVENT_READ:\n kev=select.kevent(key.fd,select.KQ_FILTER_READ,\n select.KQ_EV_ADD)\n self._selector.control([kev],0,0)\n if events&EVENT_WRITE:\n kev=select.kevent(key.fd,select.KQ_FILTER_WRITE,\n select.KQ_EV_ADD)\n self._selector.control([kev],0,0)\n except :\n super().unregister(fileobj)\n raise\n return key\n \n def unregister(self,fileobj):\n key=super().unregister(fileobj)\n if key.events&EVENT_READ:\n kev=select.kevent(key.fd,select.KQ_FILTER_READ,\n select.KQ_EV_DELETE)\n try :\n self._selector.control([kev],0,0)\n except OSError:\n \n \n pass\n if key.events&EVENT_WRITE:\n kev=select.kevent(key.fd,select.KQ_FILTER_WRITE,\n select.KQ_EV_DELETE)\n try :\n self._selector.control([kev],0,0)\n except OSError:\n \n pass\n return key\n \n def select(self,timeout=None ):\n timeout=None if timeout is None else max(timeout,0)\n max_ev=len(self._fd_to_key)\n ready=[]\n try :\n kev_list=self._selector.control(None ,max_ev,timeout)\n except InterruptedError:\n return ready\n for kev in kev_list:\n fd=kev.ident\n flag=kev.filter\n events=0\n if flag ==select.KQ_FILTER_READ:\n events |=EVENT_READ\n if flag ==select.KQ_FILTER_WRITE:\n events |=EVENT_WRITE\n \n key=self._key_from_fd(fd)\n if key:\n ready.append((key,events&key.events))\n return ready\n \n def close(self):\n self._selector.close()\n super().close()\n \n \n \n \n \nif 'KqueueSelector'in globals():\n DefaultSelector=KqueueSelector\nelif 'EpollSelector'in globals():\n DefaultSelector=EpollSelector\nelif 'DevpollSelector'in globals():\n DefaultSelector=DevpollSelector\nelif 'PollSelector'in globals():\n DefaultSelector=PollSelector\nelse :\n DefaultSelector=SelectSelector\n", ["abc", "collections", "collections.abc", "math", "select", "sys"]], "calendar": [".py", "''\n\n\n\n\n\n\nimport sys\nimport datetime\nimport locale as _locale\nfrom itertools import repeat\n\n__all__=[\"IllegalMonthError\",\"IllegalWeekdayError\",\"setfirstweekday\",\n\"firstweekday\",\"isleap\",\"leapdays\",\"weekday\",\"monthrange\",\n\"monthcalendar\",\"prmonth\",\"month\",\"prcal\",\"calendar\",\n\"timegm\",\"month_name\",\"month_abbr\",\"day_name\",\"day_abbr\",\n\"Calendar\",\"TextCalendar\",\"HTMLCalendar\",\"LocaleTextCalendar\",\n\"LocaleHTMLCalendar\",\"weekheader\"]\n\n\nerror=ValueError\n\n\nclass IllegalMonthError(ValueError):\n def __init__(self,month):\n self.month=month\n def __str__(self):\n return \"bad month number %r; must be 1-12\"%self.month\n \n \nclass IllegalWeekdayError(ValueError):\n def __init__(self,weekday):\n self.weekday=weekday\n def __str__(self):\n return \"bad weekday number %r; must be 0 (Monday) to 6 (Sunday)\"%self.weekday\n \n \n \nJanuary=1\nFebruary=2\n\n\nmdays=[0,31,28,31,30,31,30,31,31,30,31,30,31]\n\n\n\n\n\n\nclass _localized_month:\n\n _months=[datetime.date(2001,i+1,1).strftime for i in range(12)]\n _months.insert(0,lambda x:\"\")\n \n def __init__(self,format):\n self.format=format\n \n def __getitem__(self,i):\n funcs=self._months[i]\n if isinstance(i,slice):\n return [f(self.format)for f in funcs]\n else :\n return funcs(self.format)\n \n def __len__(self):\n return 13\n \n \nclass _localized_day:\n\n\n _days=[datetime.date(2001,1,i+1).strftime for i in range(7)]\n \n def __init__(self,format):\n self.format=format\n \n def __getitem__(self,i):\n funcs=self._days[i]\n if isinstance(i,slice):\n return [f(self.format)for f in funcs]\n else :\n return funcs(self.format)\n \n def __len__(self):\n return 7\n \n \n \nday_name=_localized_day('%A')\nday_abbr=_localized_day('%a')\n\n\nmonth_name=_localized_month('%B')\nmonth_abbr=_localized_month('%b')\n\n\n(MONDAY,TUESDAY,WEDNESDAY,THURSDAY,FRIDAY,SATURDAY,SUNDAY)=range(7)\n\n\ndef isleap(year):\n ''\n return year %4 ==0 and (year %100 !=0 or year %400 ==0)\n \n \ndef leapdays(y1,y2):\n ''\n \n y1 -=1\n y2 -=1\n return (y2 //4 -y1 //4)-(y2 //100 -y1 //100)+(y2 //400 -y1 //400)\n \n \ndef weekday(year,month,day):\n ''\n if not datetime.MINYEAR <=year <=datetime.MAXYEAR:\n year=2000+year %400\n return datetime.date(year,month,day).weekday()\n \n \ndef monthrange(year,month):\n ''\n \n if not 1 <=month <=12:\n raise IllegalMonthError(month)\n day1=weekday(year,month,1)\n ndays=mdays[month]+(month ==February and isleap(year))\n return day1,ndays\n \n \ndef monthlen(year,month):\n return mdays[month]+(month ==February and isleap(year))\n \n \ndef prevmonth(year,month):\n if month ==1:\n return year -1,12\n else :\n return year,month -1\n \n \ndef nextmonth(year,month):\n if month ==12:\n return year+1,1\n else :\n return year,month+1\n \n \nclass Calendar(object):\n ''\n\n\n \n \n def __init__(self,firstweekday=0):\n self.firstweekday=firstweekday\n \n def getfirstweekday(self):\n return self._firstweekday %7\n \n def setfirstweekday(self,firstweekday):\n self._firstweekday=firstweekday\n \n firstweekday=property(getfirstweekday,setfirstweekday)\n \n def iterweekdays(self):\n ''\n\n\n \n for i in range(self.firstweekday,self.firstweekday+7):\n yield i %7\n \n def itermonthdates(self,year,month):\n ''\n\n\n\n \n for y,m,d in self.itermonthdays3(year,month):\n yield datetime.date(y,m,d)\n \n def itermonthdays(self,year,month):\n ''\n\n\n \n day1,ndays=monthrange(year,month)\n days_before=(day1 -self.firstweekday)%7\n yield from repeat(0,days_before)\n yield from range(1,ndays+1)\n days_after=(self.firstweekday -day1 -ndays)%7\n yield from repeat(0,days_after)\n \n def itermonthdays2(self,year,month):\n ''\n\n\n \n for i,d in enumerate(self.itermonthdays(year,month),self.firstweekday):\n yield d,i %7\n \n def itermonthdays3(self,year,month):\n ''\n\n\n \n day1,ndays=monthrange(year,month)\n days_before=(day1 -self.firstweekday)%7\n days_after=(self.firstweekday -day1 -ndays)%7\n y,m=prevmonth(year,month)\n end=monthlen(y,m)+1\n for d in range(end -days_before,end):\n yield y,m,d\n for d in range(1,ndays+1):\n yield year,month,d\n y,m=nextmonth(year,month)\n for d in range(1,days_after+1):\n yield y,m,d\n \n def itermonthdays4(self,year,month):\n ''\n\n\n \n for i,(y,m,d)in enumerate(self.itermonthdays3(year,month)):\n yield y,m,d,(self.firstweekday+i)%7\n \n def monthdatescalendar(self,year,month):\n ''\n\n\n \n dates=list(self.itermonthdates(year,month))\n return [dates[i:i+7]for i in range(0,len(dates),7)]\n \n def monthdays2calendar(self,year,month):\n ''\n\n\n\n\n \n days=list(self.itermonthdays2(year,month))\n return [days[i:i+7]for i in range(0,len(days),7)]\n \n def monthdayscalendar(self,year,month):\n ''\n\n\n \n days=list(self.itermonthdays(year,month))\n return [days[i:i+7]for i in range(0,len(days),7)]\n \n def yeardatescalendar(self,year,width=3):\n ''\n\n\n\n\n \n months=[\n self.monthdatescalendar(year,i)\n for i in range(January,January+12)\n ]\n return [months[i:i+width]for i in range(0,len(months),width)]\n \n def yeardays2calendar(self,year,width=3):\n ''\n\n\n\n\n \n months=[\n self.monthdays2calendar(year,i)\n for i in range(January,January+12)\n ]\n return [months[i:i+width]for i in range(0,len(months),width)]\n \n def yeardayscalendar(self,year,width=3):\n ''\n\n\n\n \n months=[\n self.monthdayscalendar(year,i)\n for i in range(January,January+12)\n ]\n return [months[i:i+width]for i in range(0,len(months),width)]\n \n \nclass TextCalendar(Calendar):\n ''\n\n\n \n \n def prweek(self,theweek,width):\n ''\n\n \n print(self.formatweek(theweek,width),end='')\n \n def formatday(self,day,weekday,width):\n ''\n\n \n if day ==0:\n s=''\n else :\n s='%2i'%day\n return s.center(width)\n \n def formatweek(self,theweek,width):\n ''\n\n \n return ' '.join(self.formatday(d,wd,width)for (d,wd)in theweek)\n \n def formatweekday(self,day,width):\n ''\n\n \n if width >=9:\n names=day_name\n else :\n names=day_abbr\n return names[day][:width].center(width)\n \n def formatweekheader(self,width):\n ''\n\n \n return ' '.join(self.formatweekday(i,width)for i in self.iterweekdays())\n \n def formatmonthname(self,theyear,themonth,width,withyear=True ):\n ''\n\n \n s=month_name[themonth]\n if withyear:\n s=\"%s %r\"%(s,theyear)\n return s.center(width)\n \n def prmonth(self,theyear,themonth,w=0,l=0):\n ''\n\n \n print(self.formatmonth(theyear,themonth,w,l),end='')\n \n def formatmonth(self,theyear,themonth,w=0,l=0):\n ''\n\n \n w=max(2,w)\n l=max(1,l)\n s=self.formatmonthname(theyear,themonth,7 *(w+1)-1)\n s=s.rstrip()\n s +='\\n'*l\n s +=self.formatweekheader(w).rstrip()\n s +='\\n'*l\n for week in self.monthdays2calendar(theyear,themonth):\n s +=self.formatweek(week,w).rstrip()\n s +='\\n'*l\n return s\n \n def formatyear(self,theyear,w=2,l=1,c=6,m=3):\n ''\n\n \n w=max(2,w)\n l=max(1,l)\n c=max(2,c)\n colwidth=(w+1)*7 -1\n v=[]\n a=v.append\n a(repr(theyear).center(colwidth *m+c *(m -1)).rstrip())\n a('\\n'*l)\n header=self.formatweekheader(w)\n for (i,row)in enumerate(self.yeardays2calendar(theyear,m)):\n \n months=range(m *i+1,min(m *(i+1)+1,13))\n a('\\n'*l)\n names=(self.formatmonthname(theyear,k,colwidth,False )\n for k in months)\n a(formatstring(names,colwidth,c).rstrip())\n a('\\n'*l)\n headers=(header for k in months)\n a(formatstring(headers,colwidth,c).rstrip())\n a('\\n'*l)\n \n height=max(len(cal)for cal in row)\n for j in range(height):\n weeks=[]\n for cal in row:\n if j >=len(cal):\n weeks.append('')\n else :\n weeks.append(self.formatweek(cal[j],w))\n a(formatstring(weeks,colwidth,c).rstrip())\n a('\\n'*l)\n return ''.join(v)\n \n def pryear(self,theyear,w=0,l=0,c=6,m=3):\n ''\n print(self.formatyear(theyear,w,l,c,m),end='')\n \n \nclass HTMLCalendar(Calendar):\n ''\n\n \n \n \n cssclasses=[\"mon\",\"tue\",\"wed\",\"thu\",\"fri\",\"sat\",\"sun\"]\n \n \n cssclasses_weekday_head=cssclasses\n \n \n cssclass_noday=\"noday\"\n \n \n cssclass_month_head=\"month\"\n \n \n cssclass_month=\"month\"\n \n \n cssclass_year_head=\"year\"\n \n \n cssclass_year=\"year\"\n \n def formatday(self,day,weekday):\n ''\n\n \n if day ==0:\n \n return '<td class=\"%s\">&nbsp;</td>'%self.cssclass_noday\n else :\n return '<td class=\"%s\">%d</td>'%(self.cssclasses[weekday],day)\n \n def formatweek(self,theweek):\n ''\n\n \n s=''.join(self.formatday(d,wd)for (d,wd)in theweek)\n return '<tr>%s</tr>'%s\n \n def formatweekday(self,day):\n ''\n\n \n return '<th class=\"%s\">%s</th>'%(\n self.cssclasses_weekday_head[day],day_abbr[day])\n \n def formatweekheader(self):\n ''\n\n \n s=''.join(self.formatweekday(i)for i in self.iterweekdays())\n return '<tr>%s</tr>'%s\n \n def formatmonthname(self,theyear,themonth,withyear=True ):\n ''\n\n \n if withyear:\n s='%s %s'%(month_name[themonth],theyear)\n else :\n s='%s'%month_name[themonth]\n return '<tr><th colspan=\"7\" class=\"%s\">%s</th></tr>'%(\n self.cssclass_month_head,s)\n \n def formatmonth(self,theyear,themonth,withyear=True ):\n ''\n\n \n v=[]\n a=v.append\n a('<table border=\"0\" cellpadding=\"0\" cellspacing=\"0\" class=\"%s\">'%(\n self.cssclass_month))\n a('\\n')\n a(self.formatmonthname(theyear,themonth,withyear=withyear))\n a('\\n')\n a(self.formatweekheader())\n a('\\n')\n for week in self.monthdays2calendar(theyear,themonth):\n a(self.formatweek(week))\n a('\\n')\n a('</table>')\n a('\\n')\n return ''.join(v)\n \n def formatyear(self,theyear,width=3):\n ''\n\n \n v=[]\n a=v.append\n width=max(width,1)\n a('<table border=\"0\" cellpadding=\"0\" cellspacing=\"0\" class=\"%s\">'%\n self.cssclass_year)\n a('\\n')\n a('<tr><th colspan=\"%d\" class=\"%s\">%s</th></tr>'%(\n width,self.cssclass_year_head,theyear))\n for i in range(January,January+12,width):\n \n months=range(i,min(i+width,13))\n a('<tr>')\n for m in months:\n a('<td>')\n a(self.formatmonth(theyear,m,withyear=False ))\n a('</td>')\n a('</tr>')\n a('</table>')\n return ''.join(v)\n \n def formatyearpage(self,theyear,width=3,css='calendar.css',encoding=None ):\n ''\n\n \n if encoding is None :\n encoding=sys.getdefaultencoding()\n v=[]\n a=v.append\n a('<?xml version=\"1.0\" encoding=\"%s\"?>\\n'%encoding)\n a('<!DOCTYPE html PUBLIC \"-//W3C//DTD XHTML 1.0 Strict//EN\" \"http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd\">\\n')\n a('<html>\\n')\n a('<head>\\n')\n a('<meta http-equiv=\"Content-Type\" content=\"text/html; charset=%s\" />\\n'%encoding)\n if css is not None :\n a('<link rel=\"stylesheet\" type=\"text/css\" href=\"%s\" />\\n'%css)\n a('<title>Calendar for %d</title>\\n'%theyear)\n a('</head>\\n')\n a('<body>\\n')\n a(self.formatyear(theyear,width))\n a('</body>\\n')\n a('</html>\\n')\n return ''.join(v).encode(encoding,\"xmlcharrefreplace\")\n \n \nclass different_locale:\n def __init__(self,locale):\n self.locale=locale\n \n def __enter__(self):\n self.oldlocale=_locale.getlocale(_locale.LC_TIME)\n _locale.setlocale(_locale.LC_TIME,self.locale)\n \n def __exit__(self,*args):\n _locale.setlocale(_locale.LC_TIME,self.oldlocale)\n \n \nclass LocaleTextCalendar(TextCalendar):\n ''\n\n\n\n\n \n \n def __init__(self,firstweekday=0,locale=None ):\n TextCalendar.__init__(self,firstweekday)\n if locale is None :\n locale=_locale.getdefaultlocale()\n self.locale=locale\n \n def formatweekday(self,day,width):\n with different_locale(self.locale):\n if width >=9:\n names=day_name\n else :\n names=day_abbr\n name=names[day]\n return name[:width].center(width)\n \n def formatmonthname(self,theyear,themonth,width,withyear=True ):\n with different_locale(self.locale):\n s=month_name[themonth]\n if withyear:\n s=\"%s %r\"%(s,theyear)\n return s.center(width)\n \n \nclass LocaleHTMLCalendar(HTMLCalendar):\n ''\n\n\n\n\n \n def __init__(self,firstweekday=0,locale=None ):\n HTMLCalendar.__init__(self,firstweekday)\n if locale is None :\n locale=_locale.getdefaultlocale()\n self.locale=locale\n \n def formatweekday(self,day):\n with different_locale(self.locale):\n s=day_abbr[day]\n return '<th class=\"%s\">%s</th>'%(self.cssclasses[day],s)\n \n def formatmonthname(self,theyear,themonth,withyear=True ):\n with different_locale(self.locale):\n s=month_name[themonth]\n if withyear:\n s='%s %s'%(s,theyear)\n return '<tr><th colspan=\"7\" class=\"month\">%s</th></tr>'%s\n \n \n \nc=TextCalendar()\n\nfirstweekday=c.getfirstweekday\n\ndef setfirstweekday(firstweekday):\n if not MONDAY <=firstweekday <=SUNDAY:\n raise IllegalWeekdayError(firstweekday)\n c.firstweekday=firstweekday\n \nmonthcalendar=c.monthdayscalendar\nprweek=c.prweek\nweek=c.formatweek\nweekheader=c.formatweekheader\nprmonth=c.prmonth\nmonth=c.formatmonth\ncalendar=c.formatyear\nprcal=c.pryear\n\n\n\n_colwidth=7 *3 -1\n_spacing=6\n\n\ndef format(cols,colwidth=_colwidth,spacing=_spacing):\n ''\n print(formatstring(cols,colwidth,spacing))\n \n \ndef formatstring(cols,colwidth=_colwidth,spacing=_spacing):\n ''\n spacing *=' '\n return spacing.join(c.center(colwidth)for c in cols)\n \n \nEPOCH=1970\n_EPOCH_ORD=datetime.date(EPOCH,1,1).toordinal()\n\n\ndef timegm(tuple):\n ''\n year,month,day,hour,minute,second=tuple[:6]\n days=datetime.date(year,month,1).toordinal()-_EPOCH_ORD+day -1\n hours=days *24+hour\n minutes=hours *60+minute\n seconds=minutes *60+second\n return seconds\n \n \ndef main(args):\n import argparse\n parser=argparse.ArgumentParser()\n textgroup=parser.add_argument_group('text only arguments')\n htmlgroup=parser.add_argument_group('html only arguments')\n textgroup.add_argument(\n \"-w\",\"--width\",\n type=int,default=2,\n help=\"width of date column (default 2)\"\n )\n textgroup.add_argument(\n \"-l\",\"--lines\",\n type=int,default=1,\n help=\"number of lines for each week (default 1)\"\n )\n textgroup.add_argument(\n \"-s\",\"--spacing\",\n type=int,default=6,\n help=\"spacing between months (default 6)\"\n )\n textgroup.add_argument(\n \"-m\",\"--months\",\n type=int,default=3,\n help=\"months per row (default 3)\"\n )\n htmlgroup.add_argument(\n \"-c\",\"--css\",\n default=\"calendar.css\",\n help=\"CSS to use for page\"\n )\n parser.add_argument(\n \"-L\",\"--locale\",\n default=None ,\n help=\"locale to be used from month and weekday names\"\n )\n parser.add_argument(\n \"-e\",\"--encoding\",\n default=None ,\n help=\"encoding to use for output\"\n )\n parser.add_argument(\n \"-t\",\"--type\",\n default=\"text\",\n choices=(\"text\",\"html\"),\n help=\"output type (text or html)\"\n )\n parser.add_argument(\n \"year\",\n nargs='?',type=int,\n help=\"year number (1-9999)\"\n )\n parser.add_argument(\n \"month\",\n nargs='?',type=int,\n help=\"month number (1-12, text only)\"\n )\n \n options=parser.parse_args(args[1:])\n \n if options.locale and not options.encoding:\n parser.error(\"if --locale is specified --encoding is required\")\n sys.exit(1)\n \n locale=options.locale,options.encoding\n \n if options.type ==\"html\":\n if options.locale:\n cal=LocaleHTMLCalendar(locale=locale)\n else :\n cal=HTMLCalendar()\n encoding=options.encoding\n if encoding is None :\n encoding=sys.getdefaultencoding()\n optdict=dict(encoding=encoding,css=options.css)\n write=sys.stdout.buffer.write\n if options.year is None :\n write(cal.formatyearpage(datetime.date.today().year,**optdict))\n elif options.month is None :\n write(cal.formatyearpage(options.year,**optdict))\n else :\n parser.error(\"incorrect number of arguments\")\n sys.exit(1)\n else :\n if options.locale:\n cal=LocaleTextCalendar(locale=locale)\n else :\n cal=TextCalendar()\n optdict=dict(w=options.width,l=options.lines)\n if options.month is None :\n optdict[\"c\"]=options.spacing\n optdict[\"m\"]=options.months\n if options.year is None :\n result=cal.formatyear(datetime.date.today().year,**optdict)\n elif options.month is None :\n result=cal.formatyear(options.year,**optdict)\n else :\n result=cal.formatmonth(options.year,options.month,**optdict)\n write=sys.stdout.write\n if options.encoding:\n result=result.encode(options.encoding)\n write=sys.stdout.buffer.write\n write(result)\n \n \nif __name__ ==\"__main__\":\n main(sys.argv)\n", ["argparse", "datetime", "itertools", "locale", "sys"]], "_weakref": [".py", "\n\nclass ProxyType:\n\n def __init__(self,obj):\n object.__setattr__(self,\"obj\",obj)\n \n def __setattr__(self,attr,value):\n setattr(object.__getattribute__(self,\"obj\"),attr,value)\n \n def __getattr__(self,attr):\n return getattr(object.__getattribute__(self,\"obj\"),attr)\n \nCallableProxyType=ProxyType\nProxyTypes=[ProxyType,CallableProxyType]\n\nclass ReferenceType:\n\n def __init__(self,obj,callback):\n self.obj=obj\n self.callback=callback\n \nclass ref:\n\n def __init__(self,obj,callback=None ):\n self.obj=ReferenceType(obj,callback)\n self.callback=callback\n \n def __call__(self):\n return self.obj.obj\n \n def __hash__(self):\n return hash(self.obj.obj)\n \n def __eq__(self,other):\n return self.obj.obj ==other.obj.obj\n \ndef getweakrefcount(obj):\n return 1\n \ndef getweakrefs(obj):\n return obj\n \ndef _remove_dead_weakref(*args):\n pass\n \ndef proxy(obj,callback=None ):\n return ProxyType(obj)\n \n", []], "tempfile": [".py", "''\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n__all__=[\n\"NamedTemporaryFile\",\"TemporaryFile\",\n\"SpooledTemporaryFile\",\"TemporaryDirectory\",\n\"mkstemp\",\"mkdtemp\",\n\"mktemp\",\n\"TMP_MAX\",\"gettempprefix\",\n\"tempdir\",\"gettempdir\",\n\"gettempprefixb\",\"gettempdirb\",\n]\n\n\n\n\nimport functools as _functools\nimport warnings as _warnings\nimport io as _io\nimport os as _os\nimport shutil as _shutil\nimport errno as _errno\nfrom random import Random as _Random\nimport weakref as _weakref\nimport _thread\n_allocate_lock=_thread.allocate_lock\n\n_text_openflags=_os.O_RDWR |_os.O_CREAT |_os.O_EXCL\nif hasattr(_os,'O_NOFOLLOW'):\n _text_openflags |=_os.O_NOFOLLOW\n \n_bin_openflags=_text_openflags\nif hasattr(_os,'O_BINARY'):\n _bin_openflags |=_os.O_BINARY\n \nif hasattr(_os,'TMP_MAX'):\n TMP_MAX=_os.TMP_MAX\nelse :\n TMP_MAX=10000\n \n \n \n \n \ntemplate=\"tmp\"\n\n\n\n_once_lock=_allocate_lock()\n\nif hasattr(_os,\"lstat\"):\n _stat=_os.lstat\nelif hasattr(_os,\"stat\"):\n _stat=_os.stat\nelse :\n\n\n def _stat(fn):\n fd=_os.open(fn,_os.O_RDONLY)\n _os.close(fd)\n \ndef _exists(fn):\n try :\n _stat(fn)\n except OSError:\n return False\n else :\n return True\n \n \ndef _infer_return_type(*args):\n ''\n return_type=None\n for arg in args:\n if arg is None :\n continue\n if isinstance(arg,bytes):\n if return_type is str:\n raise TypeError(\"Can't mix bytes and non-bytes in \"\n \"path components.\")\n return_type=bytes\n else :\n if return_type is bytes:\n raise TypeError(\"Can't mix bytes and non-bytes in \"\n \"path components.\")\n return_type=str\n if return_type is None :\n return str\n return return_type\n \n \ndef _sanitize_params(prefix,suffix,dir):\n ''\n output_type=_infer_return_type(prefix,suffix,dir)\n if suffix is None :\n suffix=output_type()\n if prefix is None :\n if output_type is str:\n prefix=template\n else :\n prefix=_os.fsencode(template)\n if dir is None :\n if output_type is str:\n dir=gettempdir()\n else :\n dir=gettempdirb()\n return prefix,suffix,dir,output_type\n \n \nclass _RandomNameSequence:\n ''\n\n\n\n\n \n \n characters=\"abcdefghijklmnopqrstuvwxyz0123456789_\"\n \n @property\n def rng(self):\n cur_pid=_os.getpid()\n if cur_pid !=getattr(self,'_rng_pid',None ):\n self._rng=_Random()\n self._rng_pid=cur_pid\n return self._rng\n \n def __iter__(self):\n return self\n \n def __next__(self):\n c=self.characters\n choose=self.rng.choice\n letters=[choose(c)for dummy in range(8)]\n return ''.join(letters)\n \ndef _candidate_tempdir_list():\n ''\n \n \n dirlist=[]\n \n \n for envname in 'TMPDIR','TEMP','TMP':\n dirname=_os.getenv(envname)\n if dirname:dirlist.append(dirname)\n \n \n if _os.name =='nt':\n dirlist.extend([_os.path.expanduser(r'~\\AppData\\Local\\Temp'),\n _os.path.expandvars(r'%SYSTEMROOT%\\Temp'),\n r'c:\\temp',r'c:\\tmp',r'\\temp',r'\\tmp'])\n else :\n dirlist.extend(['/tmp','/var/tmp','/usr/tmp'])\n \n \n try :\n dirlist.append(_os.getcwd())\n except (AttributeError,OSError):\n dirlist.append(_os.curdir)\n \n return dirlist\n \ndef _get_default_tempdir():\n ''\n\n\n\n\n\n \n \n namer=_RandomNameSequence()\n dirlist=_candidate_tempdir_list()\n \n for dir in dirlist:\n if dir !=_os.curdir:\n dir=_os.path.abspath(dir)\n \n for seq in range(100):\n name=next(namer)\n filename=_os.path.join(dir,name)\n try :\n fd=_os.open(filename,_bin_openflags,0o600)\n try :\n try :\n with _io.open(fd,'wb',closefd=False )as fp:\n fp.write(b'blat')\n finally :\n _os.close(fd)\n finally :\n _os.unlink(filename)\n return dir\n except FileExistsError:\n pass\n except PermissionError:\n \n \n if (_os.name =='nt'and _os.path.isdir(dir)and\n _os.access(dir,_os.W_OK)):\n continue\n break\n except OSError:\n break\n raise FileNotFoundError(_errno.ENOENT,\n \"No usable temporary directory found in %s\"%\n dirlist)\n \n_name_sequence=None\n\ndef _get_candidate_names():\n ''\n \n global _name_sequence\n if _name_sequence is None :\n _once_lock.acquire()\n try :\n if _name_sequence is None :\n _name_sequence=_RandomNameSequence()\n finally :\n _once_lock.release()\n return _name_sequence\n \n \ndef _mkstemp_inner(dir,pre,suf,flags,output_type):\n ''\n \n names=_get_candidate_names()\n if output_type is bytes:\n names=map(_os.fsencode,names)\n \n for seq in range(TMP_MAX):\n name=next(names)\n file=_os.path.join(dir,pre+name+suf)\n try :\n fd=_os.open(file,flags,0o600)\n except FileExistsError:\n continue\n except PermissionError:\n \n \n if (_os.name =='nt'and _os.path.isdir(dir)and\n _os.access(dir,_os.W_OK)):\n continue\n else :\n raise\n return (fd,_os.path.abspath(file))\n \n raise FileExistsError(_errno.EEXIST,\n \"No usable temporary file name found\")\n \n \n \n \ndef gettempprefix():\n ''\n return template\n \ndef gettempprefixb():\n ''\n return _os.fsencode(gettempprefix())\n \ntempdir=None\n\ndef gettempdir():\n ''\n global tempdir\n if tempdir is None :\n _once_lock.acquire()\n try :\n if tempdir is None :\n tempdir=_get_default_tempdir()\n finally :\n _once_lock.release()\n return tempdir\n \ndef gettempdirb():\n ''\n return _os.fsencode(gettempdir())\n \ndef mkstemp(suffix=None ,prefix=None ,dir=None ,text=False ):\n ''\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n \n \n prefix,suffix,dir,output_type=_sanitize_params(prefix,suffix,dir)\n \n if text:\n flags=_text_openflags\n else :\n flags=_bin_openflags\n \n return _mkstemp_inner(dir,prefix,suffix,flags,output_type)\n \n \ndef mkdtemp(suffix=None ,prefix=None ,dir=None ):\n ''\n\n\n\n\n\n\n\n\n\n \n \n prefix,suffix,dir,output_type=_sanitize_params(prefix,suffix,dir)\n \n names=_get_candidate_names()\n if output_type is bytes:\n names=map(_os.fsencode,names)\n \n for seq in range(TMP_MAX):\n name=next(names)\n file=_os.path.join(dir,prefix+name+suffix)\n try :\n _os.mkdir(file,0o700)\n except FileExistsError:\n continue\n except PermissionError:\n \n \n if (_os.name =='nt'and _os.path.isdir(dir)and\n _os.access(dir,_os.W_OK)):\n continue\n else :\n raise\n return file\n \n raise FileExistsError(_errno.EEXIST,\n \"No usable temporary directory name found\")\n \ndef mktemp(suffix=\"\",prefix=template,dir=None ):\n ''\n\n\n\n\n\n\n\n\n\n\n \n \n \n \n \n \n if dir is None :\n dir=gettempdir()\n \n names=_get_candidate_names()\n for seq in range(TMP_MAX):\n name=next(names)\n file=_os.path.join(dir,prefix+name+suffix)\n if not _exists(file):\n return file\n \n raise FileExistsError(_errno.EEXIST,\n \"No usable temporary filename found\")\n \n \nclass _TemporaryFileCloser:\n ''\n\n \n \n file=None\n close_called=False\n \n def __init__(self,file,name,delete=True ):\n self.file=file\n self.name=name\n self.delete=delete\n \n \n \n \n if _os.name !='nt':\n \n \n \n \n \n \n def close(self,unlink=_os.unlink):\n if not self.close_called and self.file is not None :\n self.close_called=True\n try :\n self.file.close()\n finally :\n if self.delete:\n unlink(self.name)\n \n \n def __del__(self):\n self.close()\n \n else :\n def close(self):\n if not self.close_called:\n self.close_called=True\n self.file.close()\n \n \nclass _TemporaryFileWrapper:\n ''\n\n\n\n\n \n \n def __init__(self,file,name,delete=True ):\n self.file=file\n self.name=name\n self.delete=delete\n self._closer=_TemporaryFileCloser(file,name,delete)\n \n def __getattr__(self,name):\n \n \n \n file=self.__dict__['file']\n a=getattr(file,name)\n if hasattr(a,'__call__'):\n func=a\n @_functools.wraps(func)\n def func_wrapper(*args,**kwargs):\n return func(*args,**kwargs)\n \n \n func_wrapper._closer=self._closer\n a=func_wrapper\n if not isinstance(a,int):\n setattr(self,name,a)\n return a\n \n \n \n def __enter__(self):\n self.file.__enter__()\n return self\n \n \n \n def __exit__(self,exc,value,tb):\n result=self.file.__exit__(exc,value,tb)\n self.close()\n return result\n \n def close(self):\n ''\n\n \n self._closer.close()\n \n \n def __iter__(self):\n \n \n \n \n \n for line in self.file:\n yield line\n \n \ndef NamedTemporaryFile(mode='w+b',buffering=-1,encoding=None ,\nnewline=None ,suffix=None ,prefix=None ,\ndir=None ,delete=True ):\n ''\n\n\n\n\n\n\n\n\n\n\n\n\n \n \n prefix,suffix,dir,output_type=_sanitize_params(prefix,suffix,dir)\n \n flags=_bin_openflags\n \n \n \n if _os.name =='nt'and delete:\n flags |=_os.O_TEMPORARY\n \n (fd,name)=_mkstemp_inner(dir,prefix,suffix,flags,output_type)\n try :\n file=_io.open(fd,mode,buffering=buffering,\n newline=newline,encoding=encoding)\n \n return _TemporaryFileWrapper(file,name,delete)\n except BaseException:\n _os.unlink(name)\n _os.close(fd)\n raise\n \nif _os.name !='posix'or _os.sys.platform =='cygwin':\n\n\n TemporaryFile=NamedTemporaryFile\n \nelse :\n\n\n\n _O_TMPFILE_WORKS=hasattr(_os,'O_TMPFILE')\n \n def TemporaryFile(mode='w+b',buffering=-1,encoding=None ,\n newline=None ,suffix=None ,prefix=None ,\n dir=None ):\n ''\n\n\n\n\n\n\n\n\n\n\n \n global _O_TMPFILE_WORKS\n \n prefix,suffix,dir,output_type=_sanitize_params(prefix,suffix,dir)\n \n flags=_bin_openflags\n if _O_TMPFILE_WORKS:\n try :\n flags2=(flags |_os.O_TMPFILE)&~_os.O_CREAT\n fd=_os.open(dir,flags2,0o600)\n except IsADirectoryError:\n \n \n \n \n \n _O_TMPFILE_WORKS=False\n except OSError:\n \n \n \n \n \n \n \n pass\n else :\n try :\n return _io.open(fd,mode,buffering=buffering,\n newline=newline,encoding=encoding)\n except :\n _os.close(fd)\n raise\n \n \n (fd,name)=_mkstemp_inner(dir,prefix,suffix,flags,output_type)\n try :\n _os.unlink(name)\n return _io.open(fd,mode,buffering=buffering,\n newline=newline,encoding=encoding)\n except :\n _os.close(fd)\n raise\n \nclass SpooledTemporaryFile:\n ''\n\n\n \n _rolled=False\n \n def __init__(self,max_size=0,mode='w+b',buffering=-1,\n encoding=None ,newline=None ,\n suffix=None ,prefix=None ,dir=None ):\n if 'b'in mode:\n self._file=_io.BytesIO()\n else :\n \n \n \n self._file=_io.StringIO(newline=\"\\n\")\n self._max_size=max_size\n self._rolled=False\n self._TemporaryFileArgs={'mode':mode,'buffering':buffering,\n 'suffix':suffix,'prefix':prefix,\n 'encoding':encoding,'newline':newline,\n 'dir':dir}\n \n def _check(self,file):\n if self._rolled:return\n max_size=self._max_size\n if max_size and file.tell()>max_size:\n self.rollover()\n \n def rollover(self):\n if self._rolled:return\n file=self._file\n newfile=self._file=TemporaryFile(**self._TemporaryFileArgs)\n del self._TemporaryFileArgs\n \n newfile.write(file.getvalue())\n newfile.seek(file.tell(),0)\n \n self._rolled=True\n \n \n \n \n \n \n \n def __enter__(self):\n if self._file.closed:\n raise ValueError(\"Cannot enter context with closed file\")\n return self\n \n def __exit__(self,exc,value,tb):\n self._file.close()\n \n \n def __iter__(self):\n return self._file.__iter__()\n \n def close(self):\n self._file.close()\n \n @property\n def closed(self):\n return self._file.closed\n \n @property\n def encoding(self):\n try :\n return self._file.encoding\n except AttributeError:\n if 'b'in self._TemporaryFileArgs['mode']:\n raise\n return self._TemporaryFileArgs['encoding']\n \n def fileno(self):\n self.rollover()\n return self._file.fileno()\n \n def flush(self):\n self._file.flush()\n \n def isatty(self):\n return self._file.isatty()\n \n @property\n def mode(self):\n try :\n return self._file.mode\n except AttributeError:\n return self._TemporaryFileArgs['mode']\n \n @property\n def name(self):\n try :\n return self._file.name\n except AttributeError:\n return None\n \n @property\n def newlines(self):\n try :\n return self._file.newlines\n except AttributeError:\n if 'b'in self._TemporaryFileArgs['mode']:\n raise\n return self._TemporaryFileArgs['newline']\n \n def read(self,*args):\n return self._file.read(*args)\n \n def readline(self,*args):\n return self._file.readline(*args)\n \n def readlines(self,*args):\n return self._file.readlines(*args)\n \n def seek(self,*args):\n self._file.seek(*args)\n \n @property\n def softspace(self):\n return self._file.softspace\n \n def tell(self):\n return self._file.tell()\n \n def truncate(self,size=None ):\n if size is None :\n self._file.truncate()\n else :\n if size >self._max_size:\n self.rollover()\n self._file.truncate(size)\n \n def write(self,s):\n file=self._file\n rv=file.write(s)\n self._check(file)\n return rv\n \n def writelines(self,iterable):\n file=self._file\n rv=file.writelines(iterable)\n self._check(file)\n return rv\n \n \nclass TemporaryDirectory(object):\n ''\n\n\n\n\n\n\n\n\n \n \n def __init__(self,suffix=None ,prefix=None ,dir=None ):\n self.name=mkdtemp(suffix,prefix,dir)\n self._finalizer=_weakref.finalize(\n self,self._cleanup,self.name,\n warn_message=\"Implicitly cleaning up {!r}\".format(self))\n \n @classmethod\n def _cleanup(cls,name,warn_message):\n _shutil.rmtree(name)\n _warnings.warn(warn_message,ResourceWarning)\n \n def __repr__(self):\n return \"<{} {!r}>\".format(self.__class__.__name__,self.name)\n \n def __enter__(self):\n return self.name\n \n def __exit__(self,exc,value,tb):\n self.cleanup()\n \n def cleanup(self):\n if self._finalizer.detach():\n _shutil.rmtree(self.name)\n", ["_thread", "errno", "functools", "io", "os", "random", "shutil", "warnings", "weakref"]], "functools": [".py", "''\n\n\n\n\n\n\n\n\n\n\n__all__=['update_wrapper','wraps','WRAPPER_ASSIGNMENTS','WRAPPER_UPDATES',\n'total_ordering','cmp_to_key','lru_cache','reduce','partial',\n'partialmethod','singledispatch']\n\ntry :\n from _functools import reduce\nexcept ImportError:\n pass\nfrom abc import get_cache_token\nfrom collections import namedtuple\n\nfrom reprlib import recursive_repr\nfrom _thread import RLock\n\n\n\n\n\n\n\n\n\nWRAPPER_ASSIGNMENTS=('__module__','__name__','__qualname__','__doc__',\n'__annotations__')\nWRAPPER_UPDATES=('__dict__',)\ndef update_wrapper(wrapper,\nwrapped,\nassigned=WRAPPER_ASSIGNMENTS,\nupdated=WRAPPER_UPDATES):\n ''\n\n\n\n\n\n\n\n\n\n \n for attr in assigned:\n try :\n value=getattr(wrapped,attr)\n except AttributeError:\n pass\n else :\n setattr(wrapper,attr,value)\n for attr in updated:\n getattr(wrapper,attr).update(getattr(wrapped,attr,{}))\n \n \n wrapper.__wrapped__=wrapped\n \n return wrapper\n \ndef wraps(wrapped,\nassigned=WRAPPER_ASSIGNMENTS,\nupdated=WRAPPER_UPDATES):\n ''\n\n\n\n\n\n\n \n return partial(update_wrapper,wrapped=wrapped,\n assigned=assigned,updated=updated)\n \n \n \n \n \n \n \n \n \n \n \ndef _gt_from_lt(self,other,NotImplemented=NotImplemented):\n ''\n op_result=self.__lt__(other)\n if op_result is NotImplemented:\n return op_result\n return not op_result and self !=other\n \ndef _le_from_lt(self,other,NotImplemented=NotImplemented):\n ''\n op_result=self.__lt__(other)\n return op_result or self ==other\n \ndef _ge_from_lt(self,other,NotImplemented=NotImplemented):\n ''\n op_result=self.__lt__(other)\n if op_result is NotImplemented:\n return op_result\n return not op_result\n \ndef _ge_from_le(self,other,NotImplemented=NotImplemented):\n ''\n op_result=self.__le__(other)\n if op_result is NotImplemented:\n return op_result\n return not op_result or self ==other\n \ndef _lt_from_le(self,other,NotImplemented=NotImplemented):\n ''\n op_result=self.__le__(other)\n if op_result is NotImplemented:\n return op_result\n return op_result and self !=other\n \ndef _gt_from_le(self,other,NotImplemented=NotImplemented):\n ''\n op_result=self.__le__(other)\n if op_result is NotImplemented:\n return op_result\n return not op_result\n \ndef _lt_from_gt(self,other,NotImplemented=NotImplemented):\n ''\n op_result=self.__gt__(other)\n if op_result is NotImplemented:\n return op_result\n return not op_result and self !=other\n \ndef _ge_from_gt(self,other,NotImplemented=NotImplemented):\n ''\n op_result=self.__gt__(other)\n return op_result or self ==other\n \ndef _le_from_gt(self,other,NotImplemented=NotImplemented):\n ''\n op_result=self.__gt__(other)\n if op_result is NotImplemented:\n return op_result\n return not op_result\n \ndef _le_from_ge(self,other,NotImplemented=NotImplemented):\n ''\n op_result=self.__ge__(other)\n if op_result is NotImplemented:\n return op_result\n return not op_result or self ==other\n \ndef _gt_from_ge(self,other,NotImplemented=NotImplemented):\n ''\n op_result=self.__ge__(other)\n if op_result is NotImplemented:\n return op_result\n return op_result and self !=other\n \ndef _lt_from_ge(self,other,NotImplemented=NotImplemented):\n ''\n op_result=self.__ge__(other)\n if op_result is NotImplemented:\n return op_result\n return not op_result\n \n_convert={\n'__lt__':[('__gt__',_gt_from_lt),\n('__le__',_le_from_lt),\n('__ge__',_ge_from_lt)],\n'__le__':[('__ge__',_ge_from_le),\n('__lt__',_lt_from_le),\n('__gt__',_gt_from_le)],\n'__gt__':[('__lt__',_lt_from_gt),\n('__ge__',_ge_from_gt),\n('__le__',_le_from_gt)],\n'__ge__':[('__le__',_le_from_ge),\n('__gt__',_gt_from_ge),\n('__lt__',_lt_from_ge)]\n}\n\ndef total_ordering(cls):\n ''\n \n roots={op for op in _convert if getattr(cls,op,None )is not getattr(object,op,None )}\n if not roots:\n raise ValueError('must define at least one ordering operation: < > <= >=')\n root=max(roots)\n for opname,opfunc in _convert[root]:\n if opname not in roots:\n opfunc.__name__=opname\n setattr(cls,opname,opfunc)\n return cls\n \n \n \n \n \n \ndef cmp_to_key(mycmp):\n ''\n class K(object):\n __slots__=['obj']\n def __init__(self,obj):\n self.obj=obj\n def __lt__(self,other):\n return mycmp(self.obj,other.obj)<0\n def __gt__(self,other):\n return mycmp(self.obj,other.obj)>0\n def __eq__(self,other):\n return mycmp(self.obj,other.obj)==0\n def __le__(self,other):\n return mycmp(self.obj,other.obj)<=0\n def __ge__(self,other):\n return mycmp(self.obj,other.obj)>=0\n __hash__=None\n return K\n \ntry :\n from _functools import cmp_to_key\nexcept ImportError:\n pass\n \n \n \n \n \n \n \nclass partial:\n ''\n\n \n \n __slots__=\"func\",\"args\",\"keywords\",\"__dict__\",\"__weakref__\"\n \n def __new__(*args,**keywords):\n if not args:\n raise TypeError(\"descriptor '__new__' of partial needs an argument\")\n if len(args)<2:\n raise TypeError(\"type 'partial' takes at least one argument\")\n cls,func,*args=args\n if not callable(func):\n raise TypeError(\"the first argument must be callable\")\n args=tuple(args)\n \n if hasattr(func,\"func\"):\n args=func.args+args\n tmpkw=func.keywords.copy()\n tmpkw.update(keywords)\n keywords=tmpkw\n del tmpkw\n func=func.func\n \n self=super(partial,cls).__new__(cls)\n \n self.func=func\n self.args=args\n self.keywords=keywords\n return self\n \n def __call__(*args,**keywords):\n if not args:\n raise TypeError(\"descriptor '__call__' of partial needs an argument\")\n self,*args=args\n newkeywords=self.keywords.copy()\n newkeywords.update(keywords)\n return self.func(*self.args,*args,**newkeywords)\n \n @recursive_repr()\n def __repr__(self):\n qualname=type(self).__qualname__\n args=[repr(self.func)]\n args.extend(repr(x)for x in self.args)\n args.extend(f\"{k}={v!r}\"for (k,v)in self.keywords.items())\n if type(self).__module__ ==\"functools\":\n return f\"functools.{qualname}({', '.join(args)})\"\n return f\"{qualname}({', '.join(args)})\"\n \n def __reduce__(self):\n return type(self),(self.func,),(self.func,self.args,\n self.keywords or None ,self.__dict__ or None )\n \n def __setstate__(self,state):\n if not isinstance(state,tuple):\n raise TypeError(\"argument to __setstate__ must be a tuple\")\n if len(state)!=4:\n raise TypeError(f\"expected 4 items in state, got {len(state)}\")\n func,args,kwds,namespace=state\n if (not callable(func)or not isinstance(args,tuple)or\n (kwds is not None and not isinstance(kwds,dict))or\n (namespace is not None and not isinstance(namespace,dict))):\n raise TypeError(\"invalid partial state\")\n \n args=tuple(args)\n if kwds is None :\n kwds={}\n elif type(kwds)is not dict:\n kwds=dict(kwds)\n if namespace is None :\n namespace={}\n \n self.__dict__=namespace\n self.func=func\n self.args=args\n self.keywords=kwds\n \ntry :\n from _functools import partial\nexcept ImportError:\n pass\n \n \nclass partialmethod(object):\n ''\n\n\n\n\n \n \n def __init__(self,func,*args,**keywords):\n if not callable(func)and not hasattr(func,\"__get__\"):\n raise TypeError(\"{!r} is not callable or a descriptor\"\n .format(func))\n \n \n \n if isinstance(func,partialmethod):\n \n \n \n self.func=func.func\n self.args=func.args+args\n self.keywords=func.keywords.copy()\n self.keywords.update(keywords)\n else :\n self.func=func\n self.args=args\n self.keywords=keywords\n \n def __repr__(self):\n args=\", \".join(map(repr,self.args))\n keywords=\", \".join(\"{}={!r}\".format(k,v)\n for k,v in self.keywords.items())\n format_string=\"{module}.{cls}({func}, {args}, {keywords})\"\n return format_string.format(module=self.__class__.__module__,\n cls=self.__class__.__qualname__,\n func=self.func,\n args=args,\n keywords=keywords)\n \n def _make_unbound_method(self):\n def _method(*args,**keywords):\n call_keywords=self.keywords.copy()\n call_keywords.update(keywords)\n cls_or_self,*rest=args\n call_args=(cls_or_self,)+self.args+tuple(rest)\n return self.func(*call_args,**call_keywords)\n _method.__isabstractmethod__=self.__isabstractmethod__\n _method._partialmethod=self\n return _method\n \n def __get__(self,obj,cls):\n get=getattr(self.func,\"__get__\",None )\n result=None\n if get is not None :\n new_func=get(obj,cls)\n if new_func is not self.func:\n \n \n result=partial(new_func,*self.args,**self.keywords)\n try :\n result.__self__=new_func.__self__\n except AttributeError:\n pass\n if result is None :\n \n \n result=self._make_unbound_method().__get__(obj,cls)\n return result\n \n @property\n def __isabstractmethod__(self):\n return getattr(self.func,\"__isabstractmethod__\",False )\n \n \n \n \n \n \n_CacheInfo=namedtuple(\"CacheInfo\",[\"hits\",\"misses\",\"maxsize\",\"currsize\"])\n\nclass _HashedSeq(list):\n ''\n\n\n\n \n \n __slots__='hashvalue'\n \n def __init__(self,tup,hash=hash):\n self[:]=tup\n self.hashvalue=hash(tup)\n \n def __hash__(self):\n return self.hashvalue\n \ndef _make_key(args,kwds,typed,\nkwd_mark=(object(),),\nfasttypes={int,str,frozenset,type(None )},\ntuple=tuple,type=type,len=len):\n ''\n\n\n\n\n\n\n\n\n \n \n \n \n \n key=args\n if kwds:\n key +=kwd_mark\n for item in kwds.items():\n key +=item\n if typed:\n key +=tuple(type(v)for v in args)\n if kwds:\n key +=tuple(type(v)for v in kwds.values())\n elif len(key)==1 and type(key[0])in fasttypes:\n return key[0]\n return _HashedSeq(key)\n \ndef lru_cache(maxsize=128,typed=False ):\n ''\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n \n \n \n \n \n \n \n \n \n \n if maxsize is not None and not isinstance(maxsize,int):\n raise TypeError('Expected maxsize to be an integer or None')\n \n def decorating_function(user_function):\n wrapper=_lru_cache_wrapper(user_function,maxsize,typed,_CacheInfo)\n return update_wrapper(wrapper,user_function)\n \n return decorating_function\n \ndef _lru_cache_wrapper(user_function,maxsize,typed,_CacheInfo):\n\n sentinel=object()\n make_key=_make_key\n PREV,NEXT,KEY,RESULT=0,1,2,3\n \n cache={}\n hits=misses=0\n full=False\n cache_get=cache.get\n cache_len=cache.__len__\n lock=RLock()\n root=[]\n root[:]=[root,root,None ,None ]\n \n if maxsize ==0:\n \n def wrapper(*args,**kwds):\n \n nonlocal misses\n result=user_function(*args,**kwds)\n misses +=1\n return result\n \n elif maxsize is None :\n \n def wrapper(*args,**kwds):\n \n nonlocal hits,misses\n key=make_key(args,kwds,typed)\n result=cache_get(key,sentinel)\n if result is not sentinel:\n hits +=1\n return result\n result=user_function(*args,**kwds)\n cache[key]=result\n misses +=1\n return result\n \n else :\n \n def wrapper(*args,**kwds):\n \n nonlocal root,hits,misses,full\n key=make_key(args,kwds,typed)\n with lock:\n link=cache_get(key)\n if link is not None :\n \n link_prev,link_next,_key,result=link\n link_prev[NEXT]=link_next\n link_next[PREV]=link_prev\n last=root[PREV]\n last[NEXT]=root[PREV]=link\n link[PREV]=last\n link[NEXT]=root\n hits +=1\n return result\n result=user_function(*args,**kwds)\n with lock:\n if key in cache:\n \n \n \n \n pass\n elif full:\n \n oldroot=root\n oldroot[KEY]=key\n oldroot[RESULT]=result\n \n \n \n \n \n \n root=oldroot[NEXT]\n oldkey=root[KEY]\n oldresult=root[RESULT]\n root[KEY]=root[RESULT]=None\n \n del cache[oldkey]\n \n \n \n cache[key]=oldroot\n else :\n \n last=root[PREV]\n link=[last,root,key,result]\n last[NEXT]=root[PREV]=cache[key]=link\n \n \n full=(cache_len()>=maxsize)\n misses +=1\n return result\n \n def cache_info():\n ''\n with lock:\n return _CacheInfo(hits,misses,maxsize,cache_len())\n \n def cache_clear():\n ''\n nonlocal hits,misses,full\n with lock:\n cache.clear()\n root[:]=[root,root,None ,None ]\n hits=misses=0\n full=False\n \n wrapper.cache_info=cache_info\n wrapper.cache_clear=cache_clear\n return wrapper\n \ntry :\n from _functools import _lru_cache_wrapper\nexcept ImportError:\n pass\n \n \n \n \n \n \ndef _c3_merge(sequences):\n ''\n\n\n\n \n result=[]\n while True :\n sequences=[s for s in sequences if s]\n if not sequences:\n return result\n for s1 in sequences:\n candidate=s1[0]\n for s2 in sequences:\n if candidate in s2[1:]:\n candidate=None\n break\n else :\n break\n if candidate is None :\n raise RuntimeError(\"Inconsistent hierarchy\")\n result.append(candidate)\n \n for seq in sequences:\n if seq[0]==candidate:\n del seq[0]\n \ndef _c3_mro(cls,abcs=None ):\n ''\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n \n for i,base in enumerate(reversed(cls.__bases__)):\n if hasattr(base,'__abstractmethods__'):\n boundary=len(cls.__bases__)-i\n break\n else :\n boundary=0\n abcs=list(abcs)if abcs else []\n explicit_bases=list(cls.__bases__[:boundary])\n abstract_bases=[]\n other_bases=list(cls.__bases__[boundary:])\n for base in abcs:\n if issubclass(cls,base)and not any(\n issubclass(b,base)for b in cls.__bases__\n ):\n \n \n abstract_bases.append(base)\n for base in abstract_bases:\n abcs.remove(base)\n explicit_c3_mros=[_c3_mro(base,abcs=abcs)for base in explicit_bases]\n abstract_c3_mros=[_c3_mro(base,abcs=abcs)for base in abstract_bases]\n other_c3_mros=[_c3_mro(base,abcs=abcs)for base in other_bases]\n return _c3_merge(\n [[cls]]+\n explicit_c3_mros+abstract_c3_mros+other_c3_mros+\n [explicit_bases]+[abstract_bases]+[other_bases]\n )\n \ndef _compose_mro(cls,types):\n ''\n\n\n\n\n \n bases=set(cls.__mro__)\n \n def is_related(typ):\n return (typ not in bases and hasattr(typ,'__mro__')\n and issubclass(cls,typ))\n types=[n for n in types if is_related(n)]\n \n \n def is_strict_base(typ):\n for other in types:\n if typ !=other and typ in other.__mro__:\n return True\n return False\n types=[n for n in types if not is_strict_base(n)]\n \n \n type_set=set(types)\n mro=[]\n for typ in types:\n found=[]\n for sub in typ.__subclasses__():\n if sub not in bases and issubclass(cls,sub):\n found.append([s for s in sub.__mro__ if s in type_set])\n if not found:\n mro.append(typ)\n continue\n \n found.sort(key=len,reverse=True )\n for sub in found:\n for subcls in sub:\n if subcls not in mro:\n mro.append(subcls)\n return _c3_mro(cls,abcs=mro)\n \ndef _find_impl(cls,registry):\n ''\n\n\n\n\n\n\n\n \n mro=_compose_mro(cls,registry.keys())\n match=None\n for t in mro:\n if match is not None :\n \n \n if (t in registry and t not in cls.__mro__\n and match not in cls.__mro__\n and not issubclass(match,t)):\n raise RuntimeError(\"Ambiguous dispatch: {} or {}\".format(\n match,t))\n break\n if t in registry:\n match=t\n return registry.get(match)\n \ndef singledispatch(func):\n ''\n\n\n\n\n\n\n \n \n \n \n import types,weakref\n \n registry={}\n dispatch_cache=weakref.WeakKeyDictionary()\n cache_token=None\n \n def dispatch(cls):\n ''\n\n\n\n\n \n nonlocal cache_token\n if cache_token is not None :\n current_token=get_cache_token()\n if cache_token !=current_token:\n dispatch_cache.clear()\n cache_token=current_token\n try :\n impl=dispatch_cache[cls]\n except KeyError:\n try :\n impl=registry[cls]\n except KeyError:\n impl=_find_impl(cls,registry)\n dispatch_cache[cls]=impl\n return impl\n \n def register(cls,func=None ):\n ''\n\n\n\n \n nonlocal cache_token\n if func is None :\n if isinstance(cls,type):\n return lambda f:register(cls,f)\n ann=getattr(cls,'__annotations__',{})\n if not ann:\n raise TypeError(\n f\"Invalid first argument to `register()`: {cls!r}. \"\n f\"Use either `@register(some_class)` or plain `@register` \"\n f\"on an annotated function.\"\n )\n func=cls\n \n \n from typing import get_type_hints\n argname,cls=next(iter(get_type_hints(func).items()))\n assert isinstance(cls,type),(\n f\"Invalid annotation for {argname!r}. {cls!r} is not a class.\"\n )\n registry[cls]=func\n if cache_token is None and hasattr(cls,'__abstractmethods__'):\n cache_token=get_cache_token()\n dispatch_cache.clear()\n return func\n \n def wrapper(*args,**kw):\n return dispatch(args[0].__class__)(*args,**kw)\n \n registry[object]=func\n wrapper.register=register\n wrapper.dispatch=dispatch\n wrapper.registry=types.MappingProxyType(registry)\n wrapper._clear_cache=dispatch_cache.clear\n update_wrapper(wrapper,func)\n return wrapper\n", ["_functools", "_thread", "abc", "collections", "reprlib", "types", "typing", "weakref"]], "cmd": [".py", "''\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\nimport string,sys\n\n__all__=[\"Cmd\"]\n\nPROMPT='(Cmd) '\nIDENTCHARS=string.ascii_letters+string.digits+'_'\n\nclass Cmd:\n ''\n\n\n\n\n\n\n\n\n\n \n prompt=PROMPT\n identchars=IDENTCHARS\n ruler='='\n lastcmd=''\n intro=None\n doc_leader=\"\"\n doc_header=\"Documented commands (type help <topic>):\"\n misc_header=\"Miscellaneous help topics:\"\n undoc_header=\"Undocumented commands:\"\n nohelp=\"*** No help on %s\"\n use_rawinput=1\n \n def __init__(self,completekey='tab',stdin=None ,stdout=None ):\n ''\n\n\n\n\n\n\n\n\n \n if stdin is not None :\n self.stdin=stdin\n else :\n self.stdin=sys.stdin\n if stdout is not None :\n self.stdout=stdout\n else :\n self.stdout=sys.stdout\n self.cmdqueue=[]\n self.completekey=completekey\n \n def cmdloop(self,intro=None ):\n ''\n\n\n\n \n \n self.preloop()\n if self.use_rawinput and self.completekey:\n try :\n import readline\n self.old_completer=readline.get_completer()\n readline.set_completer(self.complete)\n readline.parse_and_bind(self.completekey+\": complete\")\n except ImportError:\n pass\n try :\n if intro is not None :\n self.intro=intro\n if self.intro:\n self.stdout.write(str(self.intro)+\"\\n\")\n stop=None\n while not stop:\n if self.cmdqueue:\n line=self.cmdqueue.pop(0)\n else :\n if self.use_rawinput:\n try :\n line=input(self.prompt)\n except EOFError:\n line='EOF'\n else :\n self.stdout.write(self.prompt)\n self.stdout.flush()\n line=self.stdin.readline()\n if not len(line):\n line='EOF'\n else :\n line=line.rstrip('\\r\\n')\n line=self.precmd(line)\n stop=self.onecmd(line)\n stop=self.postcmd(stop,line)\n self.postloop()\n finally :\n if self.use_rawinput and self.completekey:\n try :\n import readline\n readline.set_completer(self.old_completer)\n except ImportError:\n pass\n \n \n def precmd(self,line):\n ''\n\n\n \n return line\n \n def postcmd(self,stop,line):\n ''\n return stop\n \n def preloop(self):\n ''\n pass\n \n def postloop(self):\n ''\n\n\n \n pass\n \n def parseline(self,line):\n ''\n\n\n \n line=line.strip()\n if not line:\n return None ,None ,line\n elif line[0]=='?':\n line='help '+line[1:]\n elif line[0]=='!':\n if hasattr(self,'do_shell'):\n line='shell '+line[1:]\n else :\n return None ,None ,line\n i,n=0,len(line)\n while i <n and line[i]in self.identchars:i=i+1\n cmd,arg=line[:i],line[i:].strip()\n return cmd,arg,line\n \n def onecmd(self,line):\n ''\n\n\n\n\n\n\n\n \n cmd,arg,line=self.parseline(line)\n if not line:\n return self.emptyline()\n if cmd is None :\n return self.default(line)\n self.lastcmd=line\n if line =='EOF':\n self.lastcmd=''\n if cmd =='':\n return self.default(line)\n else :\n try :\n func=getattr(self,'do_'+cmd)\n except AttributeError:\n return self.default(line)\n return func(arg)\n \n def emptyline(self):\n ''\n\n\n\n\n \n if self.lastcmd:\n return self.onecmd(self.lastcmd)\n \n def default(self,line):\n ''\n\n\n\n\n \n self.stdout.write('*** Unknown syntax: %s\\n'%line)\n \n def completedefault(self,*ignored):\n ''\n\n\n\n\n \n return []\n \n def completenames(self,text,*ignored):\n dotext='do_'+text\n return [a[3:]for a in self.get_names()if a.startswith(dotext)]\n \n def complete(self,text,state):\n ''\n\n\n\n \n if state ==0:\n import readline\n origline=readline.get_line_buffer()\n line=origline.lstrip()\n stripped=len(origline)-len(line)\n begidx=readline.get_begidx()-stripped\n endidx=readline.get_endidx()-stripped\n if begidx >0:\n cmd,args,foo=self.parseline(line)\n if cmd =='':\n compfunc=self.completedefault\n else :\n try :\n compfunc=getattr(self,'complete_'+cmd)\n except AttributeError:\n compfunc=self.completedefault\n else :\n compfunc=self.completenames\n self.completion_matches=compfunc(text,line,begidx,endidx)\n try :\n return self.completion_matches[state]\n except IndexError:\n return None\n \n def get_names(self):\n \n \n return dir(self.__class__)\n \n def complete_help(self,*args):\n commands=set(self.completenames(*args))\n topics=set(a[5:]for a in self.get_names()\n if a.startswith('help_'+args[0]))\n return list(commands |topics)\n \n def do_help(self,arg):\n ''\n if arg:\n \n try :\n func=getattr(self,'help_'+arg)\n except AttributeError:\n try :\n doc=getattr(self,'do_'+arg).__doc__\n if doc:\n self.stdout.write(\"%s\\n\"%str(doc))\n return\n except AttributeError:\n pass\n self.stdout.write(\"%s\\n\"%str(self.nohelp %(arg,)))\n return\n func()\n else :\n names=self.get_names()\n cmds_doc=[]\n cmds_undoc=[]\n help={}\n for name in names:\n if name[:5]=='help_':\n help[name[5:]]=1\n names.sort()\n \n prevname=''\n for name in names:\n if name[:3]=='do_':\n if name ==prevname:\n continue\n prevname=name\n cmd=name[3:]\n if cmd in help:\n cmds_doc.append(cmd)\n del help[cmd]\n elif getattr(self,name).__doc__:\n cmds_doc.append(cmd)\n else :\n cmds_undoc.append(cmd)\n self.stdout.write(\"%s\\n\"%str(self.doc_leader))\n self.print_topics(self.doc_header,cmds_doc,15,80)\n self.print_topics(self.misc_header,list(help.keys()),15,80)\n self.print_topics(self.undoc_header,cmds_undoc,15,80)\n \n def print_topics(self,header,cmds,cmdlen,maxcol):\n if cmds:\n self.stdout.write(\"%s\\n\"%str(header))\n if self.ruler:\n self.stdout.write(\"%s\\n\"%str(self.ruler *len(header)))\n self.columnize(cmds,maxcol -1)\n self.stdout.write(\"\\n\")\n \n def columnize(self,list,displaywidth=80):\n ''\n\n\n\n \n if not list:\n self.stdout.write(\"<empty>\\n\")\n return\n \n nonstrings=[i for i in range(len(list))\n if not isinstance(list[i],str)]\n if nonstrings:\n raise TypeError(\"list[i] not a string for i in %s\"\n %\", \".join(map(str,nonstrings)))\n size=len(list)\n if size ==1:\n self.stdout.write('%s\\n'%str(list[0]))\n return\n \n for nrows in range(1,len(list)):\n ncols=(size+nrows -1)//nrows\n colwidths=[]\n totwidth=-2\n for col in range(ncols):\n colwidth=0\n for row in range(nrows):\n i=row+nrows *col\n if i >=size:\n break\n x=list[i]\n colwidth=max(colwidth,len(x))\n colwidths.append(colwidth)\n totwidth +=colwidth+2\n if totwidth >displaywidth:\n break\n if totwidth <=displaywidth:\n break\n else :\n nrows=len(list)\n ncols=1\n colwidths=[0]\n for row in range(nrows):\n texts=[]\n for col in range(ncols):\n i=row+nrows *col\n if i >=size:\n x=\"\"\n else :\n x=list[i]\n texts.append(x)\n while texts and not texts[-1]:\n del texts[-1]\n for col in range(len(texts)):\n texts[col]=texts[col].ljust(colwidths[col])\n self.stdout.write(\"%s\\n\"%str(\" \".join(texts)))\n", ["readline", "string", "sys"]], "importlib._bootstrap": [".py", "''\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n_bootstrap_external=None\n\ndef _wrap(new,old):\n ''\n for replace in ['__module__','__name__','__qualname__','__doc__']:\n if hasattr(old,replace):\n setattr(new,replace,getattr(old,replace))\n new.__dict__.update(old.__dict__)\n \n \ndef _new_module(name):\n return type(sys)(name)\n \n \n \n \n \n \n_module_locks={}\n\n_blocking_on={}\n\n\nclass _DeadlockError(RuntimeError):\n pass\n \n \nclass _ModuleLock:\n ''\n\n\n \n \n def __init__(self,name):\n self.lock=_thread.allocate_lock()\n self.wakeup=_thread.allocate_lock()\n self.name=name\n self.owner=None\n self.count=0\n self.waiters=0\n \n def has_deadlock(self):\n \n me=_thread.get_ident()\n tid=self.owner\n while True :\n lock=_blocking_on.get(tid)\n if lock is None :\n return False\n tid=lock.owner\n if tid ==me:\n return True\n \n def acquire(self):\n ''\n\n\n\n \n tid=_thread.get_ident()\n _blocking_on[tid]=self\n try :\n while True :\n with self.lock:\n if self.count ==0 or self.owner ==tid:\n self.owner=tid\n self.count +=1\n return True\n if self.has_deadlock():\n raise _DeadlockError('deadlock detected by %r'%self)\n if self.wakeup.acquire(False ):\n self.waiters +=1\n \n self.wakeup.acquire()\n self.wakeup.release()\n finally :\n del _blocking_on[tid]\n \n def release(self):\n tid=_thread.get_ident()\n with self.lock:\n if self.owner !=tid:\n raise RuntimeError('cannot release un-acquired lock')\n assert self.count >0\n self.count -=1\n if self.count ==0:\n self.owner=None\n if self.waiters:\n self.waiters -=1\n self.wakeup.release()\n \n def __repr__(self):\n return '_ModuleLock({!r}) at {}'.format(self.name,id(self))\n \n \nclass _DummyModuleLock:\n ''\n \n \n def __init__(self,name):\n self.name=name\n self.count=0\n \n def acquire(self):\n self.count +=1\n return True\n \n def release(self):\n if self.count ==0:\n raise RuntimeError('cannot release un-acquired lock')\n self.count -=1\n \n def __repr__(self):\n return '_DummyModuleLock({!r}) at {}'.format(self.name,id(self))\n \n \nclass _ModuleLockManager:\n\n def __init__(self,name):\n self._name=name\n self._lock=None\n \n def __enter__(self):\n self._lock=_get_module_lock(self._name)\n self._lock.acquire()\n \n def __exit__(self,*args,**kwargs):\n self._lock.release()\n \n \n \n \ndef _get_module_lock(name):\n ''\n\n\n \n \n _imp.acquire_lock()\n try :\n try :\n lock=_module_locks[name]()\n except KeyError:\n lock=None\n \n if lock is None :\n if _thread is None :\n lock=_DummyModuleLock(name)\n else :\n lock=_ModuleLock(name)\n \n def cb(ref,name=name):\n _imp.acquire_lock()\n try :\n \n \n \n if _module_locks.get(name)is ref:\n del _module_locks[name]\n finally :\n _imp.release_lock()\n \n _module_locks[name]=_weakref.ref(lock,cb)\n finally :\n _imp.release_lock()\n \n return lock\n \n \ndef _lock_unlock_module(name):\n ''\n\n\n\n \n lock=_get_module_lock(name)\n try :\n lock.acquire()\n except _DeadlockError:\n \n \n pass\n else :\n lock.release()\n \n \ndef _call_with_frames_removed(f,*args,**kwds):\n ''\n\n\n\n\n\n \n return f(*args,**kwds)\n \n \ndef _verbose_message(message,*args,verbosity=1):\n ''\n if sys.flags.verbose >=verbosity:\n if not message.startswith(('#','import ')):\n message='# '+message\n print(message.format(*args),file=sys.stderr)\n \n \ndef _requires_builtin(fxn):\n ''\n def _requires_builtin_wrapper(self,fullname):\n if fullname not in sys.builtin_module_names:\n raise ImportError('{!r} is not a built-in module'.format(fullname),\n name=fullname)\n return fxn(self,fullname)\n _wrap(_requires_builtin_wrapper,fxn)\n return _requires_builtin_wrapper\n \n \ndef _requires_frozen(fxn):\n ''\n def _requires_frozen_wrapper(self,fullname):\n if not _imp.is_frozen(fullname):\n raise ImportError('{!r} is not a frozen module'.format(fullname),\n name=fullname)\n return fxn(self,fullname)\n _wrap(_requires_frozen_wrapper,fxn)\n return _requires_frozen_wrapper\n \n \n \ndef _load_module_shim(self,fullname):\n ''\n\n\n\n \n spec=spec_from_loader(fullname,self)\n if fullname in sys.modules:\n module=sys.modules[fullname]\n _exec(spec,module)\n return sys.modules[fullname]\n else :\n return _load(spec)\n \n \n \ndef _module_repr(module):\n\n loader=getattr(module,'__loader__',None )\n if hasattr(loader,'module_repr'):\n \n \n \n try :\n return loader.module_repr(module)\n except Exception:\n pass\n try :\n spec=module.__spec__\n except AttributeError:\n pass\n else :\n if spec is not None :\n return _module_repr_from_spec(spec)\n \n \n \n try :\n name=module.__name__\n except AttributeError:\n name='?'\n try :\n filename=module.__file__\n except AttributeError:\n if loader is None :\n return '<module {!r}>'.format(name)\n else :\n return '<module {!r} ({!r})>'.format(name,loader)\n else :\n return '<module {!r} from {!r}>'.format(name,filename)\n \n \nclass _installed_safely:\n\n def __init__(self,module):\n self._module=module\n self._spec=module.__spec__\n \n def __enter__(self):\n \n \n \n self._spec._initializing=True\n sys.modules[self._spec.name]=self._module\n \n def __exit__(self,*args):\n try :\n spec=self._spec\n if any(arg is not None for arg in args):\n try :\n del sys.modules[spec.name]\n except KeyError:\n pass\n else :\n _verbose_message('import {!r} # {!r}',spec.name,spec.loader)\n finally :\n self._spec._initializing=False\n \n \nclass ModuleSpec:\n ''\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n \n \n def __init__(self,name,loader,*,origin=None ,loader_state=None ,\n is_package=None ):\n self.name=name\n self.loader=loader\n self.origin=origin\n self.loader_state=loader_state\n self.submodule_search_locations=[]if is_package else None\n \n \n self._set_fileattr=False\n self._cached=None\n \n def __repr__(self):\n args=['name={!r}'.format(self.name),\n 'loader={!r}'.format(self.loader)]\n if self.origin is not None :\n args.append('origin={!r}'.format(self.origin))\n if self.submodule_search_locations is not None :\n args.append('submodule_search_locations={}'\n .format(self.submodule_search_locations))\n return '{}({})'.format(self.__class__.__name__,', '.join(args))\n \n def __eq__(self,other):\n smsl=self.submodule_search_locations\n try :\n return (self.name ==other.name and\n self.loader ==other.loader and\n self.origin ==other.origin and\n smsl ==other.submodule_search_locations and\n self.cached ==other.cached and\n self.has_location ==other.has_location)\n except AttributeError:\n return False\n \n @property\n def cached(self):\n if self._cached is None :\n if self.origin is not None and self._set_fileattr:\n if _bootstrap_external is None :\n raise NotImplementedError\n self._cached=_bootstrap_external._get_cached(self.origin)\n return self._cached\n \n @cached.setter\n def cached(self,cached):\n self._cached=cached\n \n @property\n def parent(self):\n ''\n if self.submodule_search_locations is None :\n return self.name.rpartition('.')[0]\n else :\n return self.name\n \n @property\n def has_location(self):\n return self._set_fileattr\n \n @has_location.setter\n def has_location(self,value):\n self._set_fileattr=bool(value)\n \n \ndef spec_from_loader(name,loader,*,origin=None ,is_package=None ):\n ''\n if hasattr(loader,'get_filename'):\n if _bootstrap_external is None :\n raise NotImplementedError\n spec_from_file_location=_bootstrap_external.spec_from_file_location\n \n if is_package is None :\n return spec_from_file_location(name,loader=loader)\n search=[]if is_package else None\n return spec_from_file_location(name,loader=loader,\n submodule_search_locations=search)\n \n if is_package is None :\n if hasattr(loader,'is_package'):\n try :\n is_package=loader.is_package(name)\n except ImportError:\n is_package=None\n else :\n \n is_package=False\n \n return ModuleSpec(name,loader,origin=origin,is_package=is_package)\n \n \ndef _spec_from_module(module,loader=None ,origin=None ):\n\n try :\n spec=module.__spec__\n except AttributeError:\n pass\n else :\n if spec is not None :\n return spec\n \n name=module.__name__\n if loader is None :\n try :\n loader=module.__loader__\n except AttributeError:\n \n pass\n try :\n location=module.__file__\n except AttributeError:\n location=None\n if origin is None :\n if location is None :\n try :\n origin=loader._ORIGIN\n except AttributeError:\n origin=None\n else :\n origin=location\n try :\n cached=module.__cached__\n except AttributeError:\n cached=None\n try :\n submodule_search_locations=list(module.__path__)\n except AttributeError:\n submodule_search_locations=None\n \n spec=ModuleSpec(name,loader,origin=origin)\n spec._set_fileattr=False if location is None else True\n spec.cached=cached\n spec.submodule_search_locations=submodule_search_locations\n return spec\n \n \ndef _init_module_attrs(spec,module,*,override=False ):\n\n\n\n if (override or getattr(module,'__name__',None )is None ):\n try :\n module.__name__=spec.name\n except AttributeError:\n pass\n \n if override or getattr(module,'__loader__',None )is None :\n loader=spec.loader\n if loader is None :\n \n if spec.submodule_search_locations is not None :\n if _bootstrap_external is None :\n raise NotImplementedError\n _NamespaceLoader=_bootstrap_external._NamespaceLoader\n \n loader=_NamespaceLoader.__new__(_NamespaceLoader)\n loader._path=spec.submodule_search_locations\n spec.loader=loader\n \n \n \n \n \n \n \n \n \n \n module.__file__=None\n try :\n module.__loader__=loader\n except AttributeError:\n pass\n \n if override or getattr(module,'__package__',None )is None :\n try :\n module.__package__=spec.parent\n except AttributeError:\n pass\n \n try :\n module.__spec__=spec\n except AttributeError:\n pass\n \n if override or getattr(module,'__path__',None )is None :\n if spec.submodule_search_locations is not None :\n try :\n module.__path__=spec.submodule_search_locations\n except AttributeError:\n pass\n \n if spec.has_location:\n if override or getattr(module,'__file__',None )is None :\n try :\n module.__file__=spec.origin\n except AttributeError:\n pass\n \n if override or getattr(module,'__cached__',None )is None :\n if spec.cached is not None :\n try :\n module.__cached__=spec.cached\n except AttributeError:\n pass\n return module\n \n \ndef module_from_spec(spec):\n ''\n \n module=None\n if hasattr(spec.loader,'create_module'):\n \n \n module=spec.loader.create_module(spec)\n elif hasattr(spec.loader,'exec_module'):\n raise ImportError('loaders that define exec_module() '\n 'must also define create_module()')\n if module is None :\n module=_new_module(spec.name)\n _init_module_attrs(spec,module)\n return module\n \n \ndef _module_repr_from_spec(spec):\n ''\n \n name='?'if spec.name is None else spec.name\n if spec.origin is None :\n if spec.loader is None :\n return '<module {!r}>'.format(name)\n else :\n return '<module {!r} ({!r})>'.format(name,spec.loader)\n else :\n if spec.has_location:\n return '<module {!r} from {!r}>'.format(name,spec.origin)\n else :\n return '<module {!r} ({})>'.format(spec.name,spec.origin)\n \n \n \ndef _exec(spec,module):\n ''\n name=spec.name\n with _ModuleLockManager(name):\n if sys.modules.get(name)is not module:\n msg='module {!r} not in sys.modules'.format(name)\n raise ImportError(msg,name=name)\n if spec.loader is None :\n if spec.submodule_search_locations is None :\n raise ImportError('missing loader',name=spec.name)\n \n _init_module_attrs(spec,module,override=True )\n return module\n _init_module_attrs(spec,module,override=True )\n if not hasattr(spec.loader,'exec_module'):\n \n \n \n spec.loader.load_module(name)\n else :\n spec.loader.exec_module(module)\n return sys.modules[name]\n \n \ndef _load_backward_compatible(spec):\n\n\n\n spec.loader.load_module(spec.name)\n \n module=sys.modules[spec.name]\n if getattr(module,'__loader__',None )is None :\n try :\n module.__loader__=spec.loader\n except AttributeError:\n pass\n if getattr(module,'__package__',None )is None :\n try :\n \n \n \n module.__package__=module.__name__\n if not hasattr(module,'__path__'):\n module.__package__=spec.name.rpartition('.')[0]\n except AttributeError:\n pass\n if getattr(module,'__spec__',None )is None :\n try :\n module.__spec__=spec\n except AttributeError:\n pass\n return module\n \ndef _load_unlocked(spec):\n\n if spec.loader is not None :\n \n if not hasattr(spec.loader,'exec_module'):\n return _load_backward_compatible(spec)\n \n module=module_from_spec(spec)\n with _installed_safely(module):\n if spec.loader is None :\n if spec.submodule_search_locations is None :\n raise ImportError('missing loader',name=spec.name)\n \n else :\n spec.loader.exec_module(module)\n \n \n \n \n return sys.modules[spec.name]\n \n \n \ndef _load(spec):\n ''\n\n\n\n\n\n\n \n with _ModuleLockManager(spec.name):\n return _load_unlocked(spec)\n \n \n \n \nclass BuiltinImporter:\n\n ''\n\n\n\n\n \n \n @staticmethod\n def module_repr(module):\n ''\n\n\n\n \n return '<module {!r} (built-in)>'.format(module.__name__)\n \n @classmethod\n def find_spec(cls,fullname,path=None ,target=None ):\n if path is not None :\n return None\n if _imp.is_builtin(fullname):\n return spec_from_loader(fullname,cls,origin='built-in')\n else :\n return None\n \n @classmethod\n def find_module(cls,fullname,path=None ):\n ''\n\n\n\n\n\n \n spec=cls.find_spec(fullname,path)\n return spec.loader if spec is not None else None\n \n @classmethod\n def create_module(self,spec):\n ''\n if spec.name not in sys.builtin_module_names:\n raise ImportError('{!r} is not a built-in module'.format(spec.name),\n name=spec.name)\n return _call_with_frames_removed(_imp.create_builtin,spec)\n \n @classmethod\n def exec_module(self,module):\n ''\n _call_with_frames_removed(_imp.exec_builtin,module)\n \n @classmethod\n @_requires_builtin\n def get_code(cls,fullname):\n ''\n return None\n \n @classmethod\n @_requires_builtin\n def get_source(cls,fullname):\n ''\n return None\n \n @classmethod\n @_requires_builtin\n def is_package(cls,fullname):\n ''\n return False\n \n load_module=classmethod(_load_module_shim)\n \n \nclass FrozenImporter:\n\n ''\n\n\n\n\n \n \n @staticmethod\n def module_repr(m):\n ''\n\n\n\n \n return '<module {!r} (frozen)>'.format(m.__name__)\n \n @classmethod\n def find_spec(cls,fullname,path=None ,target=None ):\n if _imp.is_frozen(fullname):\n return spec_from_loader(fullname,cls,origin='frozen')\n else :\n return None\n \n @classmethod\n def find_module(cls,fullname,path=None ):\n ''\n\n\n\n \n return cls if _imp.is_frozen(fullname)else None\n \n @classmethod\n def create_module(cls,spec):\n ''\n \n @staticmethod\n def exec_module(module):\n name=module.__spec__.name\n if not _imp.is_frozen(name):\n raise ImportError('{!r} is not a frozen module'.format(name),\n name=name)\n code=_call_with_frames_removed(_imp.get_frozen_object,name)\n exec(code,module.__dict__)\n \n @classmethod\n def load_module(cls,fullname):\n ''\n\n\n\n \n return _load_module_shim(cls,fullname)\n \n @classmethod\n @_requires_frozen\n def get_code(cls,fullname):\n ''\n return _imp.get_frozen_object(fullname)\n \n @classmethod\n @_requires_frozen\n def get_source(cls,fullname):\n ''\n return None\n \n @classmethod\n @_requires_frozen\n def is_package(cls,fullname):\n ''\n return _imp.is_frozen_package(fullname)\n \n \n \n \nclass _ImportLockContext:\n\n ''\n \n def __enter__(self):\n ''\n _imp.acquire_lock()\n \n def __exit__(self,exc_type,exc_value,exc_traceback):\n ''\n _imp.release_lock()\n \n \ndef _resolve_name(name,package,level):\n ''\n bits=package.rsplit('.',level -1)\n if len(bits)<level:\n raise ValueError('attempted relative import beyond top-level package')\n base=bits[0]\n return '{}.{}'.format(base,name)if name else base\n \n \ndef _find_spec_legacy(finder,name,path):\n\n\n loader=finder.find_module(name,path)\n if loader is None :\n return None\n return spec_from_loader(name,loader)\n \n \ndef _find_spec(name,path,target=None ):\n ''\n meta_path=sys.meta_path\n if meta_path is None :\n \n raise ImportError(\"sys.meta_path is None, Python is likely \"\n \"shutting down\")\n \n if not meta_path:\n _warnings.warn('sys.meta_path is empty',ImportWarning)\n \n \n \n \n is_reload=name in sys.modules\n for finder in meta_path:\n with _ImportLockContext():\n try :\n find_spec=finder.find_spec\n except AttributeError:\n spec=_find_spec_legacy(finder,name,path)\n if spec is None :\n continue\n else :\n spec=find_spec(name,path,target)\n if spec is not None :\n \n if not is_reload and name in sys.modules:\n module=sys.modules[name]\n try :\n __spec__=module.__spec__\n except AttributeError:\n \n \n \n return spec\n else :\n if __spec__ is None :\n return spec\n else :\n return __spec__\n else :\n return spec\n else :\n return None\n \n \ndef _sanity_check(name,package,level):\n ''\n if not isinstance(name,str):\n raise TypeError('module name must be str, not {}'.format(type(name)))\n if level <0:\n raise ValueError('level must be >= 0')\n if level >0:\n if not isinstance(package,str):\n raise TypeError('__package__ not set to a string')\n elif not package:\n raise ImportError('attempted relative import with no known parent '\n 'package')\n if not name and level ==0:\n raise ValueError('Empty module name')\n \n \n_ERR_MSG_PREFIX='No module named '\n_ERR_MSG=_ERR_MSG_PREFIX+'{!r}'\n\ndef _find_and_load_unlocked(name,import_):\n path=None\n parent=name.rpartition('.')[0]\n if parent:\n if parent not in sys.modules:\n _call_with_frames_removed(import_,parent)\n \n if name in sys.modules:\n return sys.modules[name]\n parent_module=sys.modules[parent]\n try :\n path=parent_module.__path__\n except AttributeError:\n msg=(_ERR_MSG+'; {!r} is not a package').format(name,parent)\n raise ModuleNotFoundError(msg,name=name)from None\n spec=_find_spec(name,path)\n if spec is None :\n raise ModuleNotFoundError(_ERR_MSG.format(name),name=name)\n else :\n module=_load_unlocked(spec)\n if parent:\n \n parent_module=sys.modules[parent]\n setattr(parent_module,name.rpartition('.')[2],module)\n return module\n \n \n_NEEDS_LOADING=object()\n\n\ndef _find_and_load(name,import_):\n ''\n with _ModuleLockManager(name):\n module=sys.modules.get(name,_NEEDS_LOADING)\n if module is _NEEDS_LOADING:\n return _find_and_load_unlocked(name,import_)\n \n if module is None :\n message=('import of {} halted; '\n 'None in sys.modules'.format(name))\n raise ModuleNotFoundError(message,name=name)\n \n _lock_unlock_module(name)\n return module\n \n \ndef _gcd_import(name,package=None ,level=0):\n ''\n\n\n\n\n\n\n \n _sanity_check(name,package,level)\n if level >0:\n name=_resolve_name(name,package,level)\n return _find_and_load(name,_gcd_import)\n \n \ndef _handle_fromlist(module,fromlist,import_,*,recursive=False ):\n ''\n\n\n\n\n\n \n \n \n if hasattr(module,'__path__'):\n for x in fromlist:\n if not isinstance(x,str):\n if recursive:\n where=module.__name__+'.__all__'\n else :\n where=\"``from list''\"\n raise TypeError(f\"Item in {where} must be str, \"\n f\"not {type(x).__name__}\")\n elif x =='*':\n if not recursive and hasattr(module,'__all__'):\n _handle_fromlist(module,module.__all__,import_,\n recursive=True )\n elif not hasattr(module,x):\n from_name='{}.{}'.format(module.__name__,x)\n try :\n _call_with_frames_removed(import_,from_name)\n except ModuleNotFoundError as exc:\n \n \n \n if (exc.name ==from_name and\n sys.modules.get(from_name,_NEEDS_LOADING)is not None ):\n continue\n raise\n return module\n \n \ndef _calc___package__(globals):\n ''\n\n\n\n\n \n package=globals.get('__package__')\n spec=globals.get('__spec__')\n if package is not None :\n if spec is not None and package !=spec.parent:\n _warnings.warn(\"__package__ != __spec__.parent \"\n f\"({package!r} != {spec.parent!r})\",\n ImportWarning,stacklevel=3)\n return package\n elif spec is not None :\n return spec.parent\n else :\n _warnings.warn(\"can't resolve package from __spec__ or __package__, \"\n \"falling back on __name__ and __path__\",\n ImportWarning,stacklevel=3)\n package=globals['__name__']\n if '__path__'not in globals:\n package=package.rpartition('.')[0]\n return package\n \n \ndef __import__(name,globals=None ,locals=None ,fromlist=(),level=0):\n ''\n\n\n\n\n\n\n\n\n \n if level ==0:\n module=_gcd_import(name)\n else :\n globals_=globals if globals is not None else {}\n package=_calc___package__(globals_)\n module=_gcd_import(name,package,level)\n if not fromlist:\n \n \n if level ==0:\n return _gcd_import(name.partition('.')[0])\n elif not name:\n return module\n else :\n \n \n cut_off=len(name)-len(name.partition('.')[0])\n \n \n return sys.modules[module.__name__[:len(module.__name__)-cut_off]]\n else :\n return _handle_fromlist(module,fromlist,_gcd_import)\n \n \ndef _builtin_from_name(name):\n spec=BuiltinImporter.find_spec(name)\n if spec is None :\n raise ImportError('no built-in module named '+name)\n return _load_unlocked(spec)\n \n \ndef _setup(sys_module,_imp_module):\n ''\n\n\n\n\n\n \n global _imp,sys\n _imp=_imp_module\n sys=sys_module\n \n \n module_type=type(sys)\n for name,module in sys.modules.items():\n if isinstance(module,module_type):\n if name in sys.builtin_module_names:\n loader=BuiltinImporter\n elif _imp.is_frozen(name):\n loader=FrozenImporter\n else :\n continue\n spec=_spec_from_module(module,loader)\n _init_module_attrs(spec,module)\n \n \n self_module=sys.modules[__name__]\n \n \n for builtin_name in ('_warnings',):\n if builtin_name not in sys.modules:\n builtin_module=_builtin_from_name(builtin_name)\n else :\n builtin_module=sys.modules[builtin_name]\n setattr(self_module,builtin_name,builtin_module)\n \n \ndef _install(sys_module,_imp_module):\n ''\n _setup(sys_module,_imp_module)\n \n sys.meta_path.append(BuiltinImporter)\n sys.meta_path.append(FrozenImporter)\n \n \ndef _install_external_importers():\n ''\n global _bootstrap_external\n import _frozen_importlib_external\n _bootstrap_external=_frozen_importlib_external\n _frozen_importlib_external._install(sys.modules[__name__])\n", ["_frozen_importlib_external"]], "abc": [".py", "\n\n\n\"\"\"Abstract Base Classes (ABCs) according to PEP 3119.\"\"\"\n\n\ndef abstractmethod(funcobj):\n ''\n\n\n\n\n\n\n\n\n\n\n\n\n\n \n funcobj.__isabstractmethod__=True\n return funcobj\n \n \nclass abstractclassmethod(classmethod):\n ''\n\n\n\n\n\n\n\n\n\n\n\n\n \n \n __isabstractmethod__=True\n \n def __init__(self,callable):\n callable.__isabstractmethod__=True\n super().__init__(callable)\n \n \nclass abstractstaticmethod(staticmethod):\n ''\n\n\n\n\n\n\n\n\n\n\n\n\n \n \n __isabstractmethod__=True\n \n def __init__(self,callable):\n callable.__isabstractmethod__=True\n super().__init__(callable)\n \n \nclass abstractproperty(property):\n ''\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n \n \n __isabstractmethod__=True\n \n \ntry :\n from _abc import (get_cache_token,_abc_init,_abc_register,\n _abc_instancecheck,_abc_subclasscheck,_get_dump,\n _reset_registry,_reset_caches)\nexcept ImportError:\n from _py_abc import ABCMeta,get_cache_token\n ABCMeta.__module__='abc'\nelse :\n class ABCMeta(type):\n ''\n\n\n\n\n\n\n\n\n\n\n \n def __new__(mcls,name,bases,namespace,**kwargs):\n cls=super().__new__(mcls,name,bases,namespace,**kwargs)\n _abc_init(cls)\n return cls\n \n def register(cls,subclass):\n ''\n\n\n \n return _abc_register(cls,subclass)\n \n def __instancecheck__(cls,instance):\n ''\n return _abc_instancecheck(cls,instance)\n \n def __subclasscheck__(cls,subclass):\n ''\n return _abc_subclasscheck(cls,subclass)\n \n def _dump_registry(cls,file=None ):\n ''\n print(f\"Class: {cls.__module__}.{cls.__qualname__}\",file=file)\n print(f\"Inv. counter: {get_cache_token()}\",file=file)\n (_abc_registry,_abc_cache,_abc_negative_cache,\n _abc_negative_cache_version)=_get_dump(cls)\n print(f\"_abc_registry: {_abc_registry!r}\",file=file)\n print(f\"_abc_cache: {_abc_cache!r}\",file=file)\n print(f\"_abc_negative_cache: {_abc_negative_cache!r}\",file=file)\n print(f\"_abc_negative_cache_version: {_abc_negative_cache_version!r}\",\n file=file)\n \n def _abc_registry_clear(cls):\n ''\n _reset_registry(cls)\n \n def _abc_caches_clear(cls):\n ''\n _reset_caches(cls)\n \n \nclass ABC(metaclass=ABCMeta):\n ''\n\n \n __slots__=()\n", ["_abc", "_py_abc"]], "encodings.utf_8": [".py", "''\n\n\n\n\n\n\n\nimport codecs\n\n\n\nencode=codecs.utf_8_encode\n\ndef decode(input,errors='strict'):\n return codecs.utf_8_decode(input,errors,True )\n \nclass IncrementalEncoder(codecs.IncrementalEncoder):\n def encode(self,input,final=False ):\n return codecs.utf_8_encode(input,self.errors)[0]\n \nclass IncrementalDecoder(codecs.BufferedIncrementalDecoder):\n _buffer_decode=codecs.utf_8_decode\n \nclass StreamWriter(codecs.StreamWriter):\n encode=codecs.utf_8_encode\n \nclass StreamReader(codecs.StreamReader):\n decode=codecs.utf_8_decode\n \n \n \ndef getregentry():\n return codecs.CodecInfo(\n name='utf-8',\n encode=encode,\n decode=decode,\n incrementalencoder=IncrementalEncoder,\n incrementaldecoder=IncrementalDecoder,\n streamreader=StreamReader,\n streamwriter=StreamWriter,\n )\n", ["codecs"]], "string": [".py", "''\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n__all__=[\"ascii_letters\",\"ascii_lowercase\",\"ascii_uppercase\",\"capwords\",\n\"digits\",\"hexdigits\",\"octdigits\",\"printable\",\"punctuation\",\n\"whitespace\",\"Formatter\",\"Template\"]\n\nimport _string\n\n\nwhitespace=' \\t\\n\\r\\v\\f'\nascii_lowercase='abcdefghijklmnopqrstuvwxyz'\nascii_uppercase='ABCDEFGHIJKLMNOPQRSTUVWXYZ'\nascii_letters=ascii_lowercase+ascii_uppercase\ndigits='0123456789'\nhexdigits=digits+'abcdef'+'ABCDEF'\noctdigits='01234567'\npunctuation=r\"\"\"!\"#$%&'()*+,-./:;<=>?@[\\]^_`{|}~\"\"\"\nprintable=digits+ascii_letters+punctuation+whitespace\n\n\n\n\ndef capwords(s,sep=None ):\n ''\n\n\n\n\n\n\n\n\n \n return (sep or ' ').join(x.capitalize()for x in s.split(sep))\n \n \n \nimport re as _re\nfrom collections import ChainMap as _ChainMap\n\nclass _TemplateMetaclass(type):\n pattern=r\"\"\"\n %(delim)s(?:\n (?P<escaped>%(delim)s) | # Escape sequence of two delimiters\n (?P<named>%(id)s) | # delimiter and a Python identifier\n {(?P<braced>%(bid)s)} | # delimiter and a braced identifier\n (?P<invalid>) # Other ill-formed delimiter exprs\n )\n \"\"\"\n \n def __init__(cls,name,bases,dct):\n super(_TemplateMetaclass,cls).__init__(name,bases,dct)\n if 'pattern'in dct:\n pattern=cls.pattern\n else :\n pattern=_TemplateMetaclass.pattern %{\n 'delim':_re.escape(cls.delimiter),\n 'id':cls.idpattern,\n 'bid':cls.braceidpattern or cls.idpattern,\n }\n cls.pattern=_re.compile(pattern,cls.flags |_re.VERBOSE)\n \n \nclass Template(metaclass=_TemplateMetaclass):\n ''\n \n delimiter='$'\n \n \n \n \n idpattern=r'(?a:[_a-z][_a-z0-9]*)'\n braceidpattern=None\n flags=_re.IGNORECASE\n \n def __init__(self,template):\n self.template=template\n \n \n \n def _invalid(self,mo):\n i=mo.start('invalid')\n lines=self.template[:i].splitlines(keepends=True )\n if not lines:\n colno=1\n lineno=1\n else :\n colno=i -len(''.join(lines[:-1]))\n lineno=len(lines)\n raise ValueError('Invalid placeholder in string: line %d, col %d'%\n (lineno,colno))\n \n def substitute(*args,**kws):\n if not args:\n raise TypeError(\"descriptor 'substitute' of 'Template' object \"\n \"needs an argument\")\n self,*args=args\n if len(args)>1:\n raise TypeError('Too many positional arguments')\n if not args:\n mapping=kws\n elif kws:\n mapping=_ChainMap(kws,args[0])\n else :\n mapping=args[0]\n \n def convert(mo):\n \n named=mo.group('named')or mo.group('braced')\n if named is not None :\n return str(mapping[named])\n if mo.group('escaped')is not None :\n return self.delimiter\n if mo.group('invalid')is not None :\n self._invalid(mo)\n raise ValueError('Unrecognized named group in pattern',\n self.pattern)\n return self.pattern.sub(convert,self.template)\n \n def safe_substitute(*args,**kws):\n if not args:\n raise TypeError(\"descriptor 'safe_substitute' of 'Template' object \"\n \"needs an argument\")\n self,*args=args\n if len(args)>1:\n raise TypeError('Too many positional arguments')\n if not args:\n mapping=kws\n elif kws:\n mapping=_ChainMap(kws,args[0])\n else :\n mapping=args[0]\n \n def convert(mo):\n named=mo.group('named')or mo.group('braced')\n if named is not None :\n try :\n return str(mapping[named])\n except KeyError:\n return mo.group()\n if mo.group('escaped')is not None :\n return self.delimiter\n if mo.group('invalid')is not None :\n return mo.group()\n raise ValueError('Unrecognized named group in pattern',\n self.pattern)\n return self.pattern.sub(convert,self.template)\n \n \n \n \n \n \n \n \n \n \n \n \n \nclass Formatter:\n def format(*args,**kwargs):\n if not args:\n raise TypeError(\"descriptor 'format' of 'Formatter' object \"\n \"needs an argument\")\n self,*args=args\n try :\n format_string,*args=args\n except ValueError:\n raise TypeError(\"format() missing 1 required positional \"\n \"argument: 'format_string'\")from None\n return self.vformat(format_string,args,kwargs)\n \n def vformat(self,format_string,args,kwargs):\n used_args=set()\n result,_=self._vformat(format_string,args,kwargs,used_args,2)\n self.check_unused_args(used_args,args,kwargs)\n return result\n \n def _vformat(self,format_string,args,kwargs,used_args,recursion_depth,\n auto_arg_index=0):\n if recursion_depth <0:\n raise ValueError('Max string recursion exceeded')\n result=[]\n for literal_text,field_name,format_spec,conversion in\\\n self.parse(format_string):\n \n \n if literal_text:\n result.append(literal_text)\n \n \n if field_name is not None :\n \n \n \n \n if field_name =='':\n if auto_arg_index is False :\n raise ValueError('cannot switch from manual field '\n 'specification to automatic field '\n 'numbering')\n field_name=str(auto_arg_index)\n auto_arg_index +=1\n elif field_name.isdigit():\n if auto_arg_index:\n raise ValueError('cannot switch from manual field '\n 'specification to automatic field '\n 'numbering')\n \n \n auto_arg_index=False\n \n \n \n obj,arg_used=self.get_field(field_name,args,kwargs)\n used_args.add(arg_used)\n \n \n obj=self.convert_field(obj,conversion)\n \n \n format_spec,auto_arg_index=self._vformat(\n format_spec,args,kwargs,\n used_args,recursion_depth -1,\n auto_arg_index=auto_arg_index)\n \n \n result.append(self.format_field(obj,format_spec))\n \n return ''.join(result),auto_arg_index\n \n \n def get_value(self,key,args,kwargs):\n if isinstance(key,int):\n return args[key]\n else :\n return kwargs[key]\n \n \n def check_unused_args(self,used_args,args,kwargs):\n pass\n \n \n def format_field(self,value,format_spec):\n return format(value,format_spec)\n \n \n def convert_field(self,value,conversion):\n \n if conversion is None :\n return value\n elif conversion =='s':\n return str(value)\n elif conversion =='r':\n return repr(value)\n elif conversion =='a':\n return ascii(value)\n raise ValueError(\"Unknown conversion specifier {0!s}\".format(conversion))\n \n \n \n \n \n \n \n \n \n def parse(self,format_string):\n return _string.formatter_parser(format_string)\n \n \n \n \n \n \n \n def get_field(self,field_name,args,kwargs):\n first,rest=_string.formatter_field_name_split(field_name)\n \n obj=self.get_value(first,args,kwargs)\n \n \n \n for is_attr,i in rest:\n if is_attr:\n obj=getattr(obj,i)\n else :\n obj=obj[i]\n \n return obj,first\n", ["_string", "collections", "re"]], "_string": [".js", "var $module=(function($B){\n\nvar _b_ = $B.builtins\n\nfunction parts(format_string){\n var result = [],\n _parts = $B.split_format(format_string) // defined in py_string.js\n for(var i = 0; i < _parts.length; i+= 2){\n result.push({pre: _parts[i], fmt: _parts[i + 1]})\n }\n return result\n}\n\nfunction Tuple(){\n var args = []\n for(var i=0, len=arguments.length; i < len; i++){\n args.push(arguments[i])\n }\n return _b_.tuple.$factory(args)\n}\n\nreturn{\n\n formatter_field_name_split: function(fieldname){\n // Split the argument as a field name\n var parsed = $B.parse_format(fieldname),\n first = parsed.name,\n rest = []\n if(first.match(/\\d+/)){first = parseInt(first)}\n parsed.name_ext.forEach(function(ext){\n if(ext.startsWith(\"[\")){\n var item = ext.substr(1, ext.length - 2)\n if(item.match(/\\d+/)){\n rest.push(Tuple(false, parseInt(item)))\n }else{\n rest.push(Tuple(false, item))\n }\n }else{\n rest.push(Tuple(true, ext.substr(1)))\n }\n })\n return Tuple(first, _b_.iter(rest))\n },\n formatter_parser: function(format_string){\n // Parse the argument as a format string\n\n if(! _b_.isinstance(format_string, _b_.str)){\n throw _b_.ValueError.$factory(\"Invalid format string type: \" +\n $B.class_name(format_string))\n }\n\n var result = []\n parts(format_string).forEach(function(item){\n var pre = item.pre === undefined ? \"\" : item.pre,\n fmt = item.fmt\n if(fmt === undefined){\n result.push(Tuple(pre, _b_.None, _b_.None, _b_.None))\n }else if(fmt.string == ''){\n result.push(Tuple(pre, '', '', _b_.None))\n }else{\n result.push(Tuple(pre,\n fmt.raw_name + fmt.name_ext.join(\"\"),\n fmt.raw_spec,\n fmt.conv || _b_.None))\n }\n })\n return result\n }\n}\n})(__BRYTHON__)"], "email.base64mime": [".py", "\n\n\n\n\"\"\"Base64 content transfer encoding per RFCs 2045-2047.\n\nThis module handles the content transfer encoding method defined in RFC 2045\nto encode arbitrary 8-bit data using the three 8-bit bytes in four 7-bit\ncharacters encoding known as Base64.\n\nIt is used in the MIME standards for email to attach images, audio, and text\nusing some 8-bit character sets to messages.\n\nThis module provides an interface to encode and decode both headers and bodies\nwith Base64 encoding.\n\nRFC 2045 defines a method for including character set information in an\n`encoded-word' in a header. This method is commonly used for 8-bit real names\nin To:, From:, Cc:, etc. fields, as well as Subject: lines.\n\nThis module does not do the line wrapping or end-of-line character conversion\nnecessary for proper internationalized headers; it only does dumb encoding and\ndecoding. To deal with the various line wrapping issues, use the email.header\nmodule.\n\"\"\"\n\n__all__=[\n'body_decode',\n'body_encode',\n'decode',\n'decodestring',\n'header_encode',\n'header_length',\n]\n\n\nfrom base64 import b64encode\nfrom binascii import b2a_base64,a2b_base64\n\nCRLF='\\r\\n'\nNL='\\n'\nEMPTYSTRING=''\n\n\nMISC_LEN=7\n\n\n\ndef header_length(bytearray):\n ''\n groups_of_3,leftover=divmod(len(bytearray),3)\n \n n=groups_of_3 *4\n if leftover:\n n +=4\n return n\n \n \ndef header_encode(header_bytes,charset='iso-8859-1'):\n ''\n\n\n\n \n if not header_bytes:\n return \"\"\n if isinstance(header_bytes,str):\n header_bytes=header_bytes.encode(charset)\n encoded=b64encode(header_bytes).decode(\"ascii\")\n return '=?%s?b?%s?='%(charset,encoded)\n \n \ndef body_encode(s,maxlinelen=76,eol=NL):\n ''\n\n\n\n\n\n\n\n \n if not s:\n return s\n \n encvec=[]\n max_unencoded=maxlinelen *3 //4\n for i in range(0,len(s),max_unencoded):\n \n \n enc=b2a_base64(s[i:i+max_unencoded]).decode(\"ascii\")\n if enc.endswith(NL)and eol !=NL:\n enc=enc[:-1]+eol\n encvec.append(enc)\n return EMPTYSTRING.join(encvec)\n \n \ndef decode(string):\n ''\n\n\n\n\n \n if not string:\n return bytes()\n elif isinstance(string,str):\n return a2b_base64(string.encode('raw-unicode-escape'))\n else :\n return a2b_base64(string)\n \n \n \nbody_decode=decode\ndecodestring=decode\n", ["base64", "binascii"]], "__future__": [".py", "''\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\nall_feature_names=[\n\"nested_scopes\",\n\"generators\",\n\"division\",\n\"absolute_import\",\n\"with_statement\",\n\"print_function\",\n\"unicode_literals\",\n\"barry_as_FLUFL\",\n\"generator_stop\",\n\"annotations\",\n]\n\n__all__=[\"all_feature_names\"]+all_feature_names\n\n\n\n\n\nCO_NESTED=0x0010\nCO_GENERATOR_ALLOWED=0\nCO_FUTURE_DIVISION=0x2000\nCO_FUTURE_ABSOLUTE_IMPORT=0x4000\nCO_FUTURE_WITH_STATEMENT=0x8000\nCO_FUTURE_PRINT_FUNCTION=0x10000\nCO_FUTURE_UNICODE_LITERALS=0x20000\nCO_FUTURE_BARRY_AS_BDFL=0x40000\nCO_FUTURE_GENERATOR_STOP=0x80000\nCO_FUTURE_ANNOTATIONS=0x100000\n\nclass _Feature:\n def __init__(self,optionalRelease,mandatoryRelease,compiler_flag):\n self.optional=optionalRelease\n self.mandatory=mandatoryRelease\n self.compiler_flag=compiler_flag\n \n def getOptionalRelease(self):\n ''\n\n\n \n \n return self.optional\n \n def getMandatoryRelease(self):\n ''\n\n\n\n \n \n return self.mandatory\n \n def __repr__(self):\n return \"_Feature\"+repr((self.optional,\n self.mandatory,\n self.compiler_flag))\n \nnested_scopes=_Feature((2,1,0,\"beta\",1),\n(2,2,0,\"alpha\",0),\nCO_NESTED)\n\ngenerators=_Feature((2,2,0,\"alpha\",1),\n(2,3,0,\"final\",0),\nCO_GENERATOR_ALLOWED)\n\ndivision=_Feature((2,2,0,\"alpha\",2),\n(3,0,0,\"alpha\",0),\nCO_FUTURE_DIVISION)\n\nabsolute_import=_Feature((2,5,0,\"alpha\",1),\n(3,0,0,\"alpha\",0),\nCO_FUTURE_ABSOLUTE_IMPORT)\n\nwith_statement=_Feature((2,5,0,\"alpha\",1),\n(2,6,0,\"alpha\",0),\nCO_FUTURE_WITH_STATEMENT)\n\nprint_function=_Feature((2,6,0,\"alpha\",2),\n(3,0,0,\"alpha\",0),\nCO_FUTURE_PRINT_FUNCTION)\n\nunicode_literals=_Feature((2,6,0,\"alpha\",2),\n(3,0,0,\"alpha\",0),\nCO_FUTURE_UNICODE_LITERALS)\n\nbarry_as_FLUFL=_Feature((3,1,0,\"alpha\",2),\n(3,9,0,\"alpha\",0),\nCO_FUTURE_BARRY_AS_BDFL)\n\ngenerator_stop=_Feature((3,5,0,\"beta\",1),\n(3,7,0,\"alpha\",0),\nCO_FUTURE_GENERATOR_STOP)\n\nannotations=_Feature((3,7,0,\"beta\",1),\n(4,0,0,\"alpha\",0),\nCO_FUTURE_ANNOTATIONS)\n", []], "time": [".py", "import _locale\nimport javascript\n\n\ndate=javascript.Date.new\nnow=javascript.Date.now\n\n\n\n\n\n\n\n_STRUCT_TM_ITEMS=9\n\n\n\n\n\ndef _get_day_of_year(arg):\n ''\n\n\n\n\n\n\n\n\n\n \n ml=[31,28,31,30,31,30,31,31,30,31,30,31]\n if arg[0]%4 ==0:\n ml[1]+=1\n i=1\n yday=0\n while i <arg[1]:\n yday +=ml[i -1]\n i +=1\n yday +=arg[2]\n return yday\n \ndef _get_week_of_year(arg):\n ''\n\n\n\n\n\n\n\n\n\n\n \n d1=date(arg[0],arg[1]-1,arg[2])\n d0=date(arg[0],0,1)\n firstday=d0.getDay()\n if firstday ==0:\n firstday=7\n firstweek=8 -firstday\n doy=arg[7]\n if firstday !=1:\n doy=doy -firstweek\n if doy %7 ==0:\n week_number=doy //7\n else :\n week_number=doy //7+1\n return week_number\n \ndef _check_struct_time(t):\n mm=t[1]\n if mm ==0:\n mm=1\n if -1 >mm >13:\n raise ValueError(\"month out of range\")\n \n dd=t[2]\n if dd ==0:dd=1\n if -1 >dd >32:\n raise ValueError(\"day of month out of range\")\n \n hh=t[3]\n if -1 >hh >24:\n raise ValueError(\"hour out of range\")\n \n minu=t[4]\n if -1 >minu >60:\n raise ValueError(\"minute out of range\")\n \n ss=t[5]\n if -1 >ss >62:\n raise ValueError(\"seconds out of range\")\n \n wd=t[6]%7\n if wd <-2:\n raise ValueError(\"day of week out of range\")\n \n dy=t[7]\n if dy ==0:dy=1\n if -1 >dy >367:\n raise ValueError(\"day of year out of range\")\n \n return t[0],mm,dd,hh,minu,ss,wd,dy,t[-1]\n \n \ndef _is_dst(secs=None ):\n ''\n d=date()\n if secs is not None :\n d=date(secs *1000)\n \n \n \n jan=date(d.getFullYear(),0,1)\n jul=date(d.getFullYear(),6,1)\n dst=int(d.getTimezoneOffset()<max(abs(jan.getTimezoneOffset()),\n abs(jul.getTimezoneOffset())))\n return dst\n \ndef _get_tzname():\n ''\n d=date()\n d=d.toTimeString()\n try :\n d=d.split('(')[1].split(')')[0]\n return (d,'NotAvailable')\n except :\n return ('','')\n \ndef _set_altzone():\n d=date()\n jan=date(d.getFullYear(),0,1)\n jul=date(d.getFullYear(),6,1)\n result=timezone -(jan.getTimezoneOffset()-jul.getTimezoneOffset())*60\n return result\n \ndef _check_input(t):\n if t and isinstance(t,struct_time)and len(t.args)==9:\n t=t.args\n elif t and isinstance(t,tuple)and len(t)==9:\n t=t\n elif t and isinstance(t,struct_time)and len(t.args)!=9:\n raise TypeError(\"function takes exactly 9 arguments ({} given)\".format(len(t.args)))\n elif t and isinstance(t,tuple)and len(t)!=9:\n raise TypeError(\"function takes exactly 9 arguments ({} given)\".format(len(t)))\n elif t and not isinstance(t,(tuple,struct_time)):\n raise TypeError(\"Tuple or struct_time argument required\")\n else :\n t=localtime().args\n return t\n \n \n \n \n \ndaylight=_is_dst()\ntimezone=date().getTimezoneOffset()*60\ntzname=_get_tzname()\naltzone=_set_altzone()if daylight else timezone\n\n\ndef asctime(t=None ):\n weekdays={i:day for (i,day)in\n enumerate(\"Mon Tue Wed Thu Fri Sat Sun\".split())\n }\n \n months={i+1:month for (i,month)in\n enumerate(\"Jan Fev Mar Apr May Jun Jul Aug Sep Oct Nov Dec\".split())\n }\n \n t=_check_input(t)\n t=_check_struct_time(t)\n \n result=\"%s %s %2d %02d:%02d:%02d %d\"%(\n weekdays[t[6]],months[t[1]],t[2],t[3],t[4],t[5],t[0])\n return result\n \ndef ctime(timestamp=None ):\n return asctime(localtime(timestamp))\n \ndef gmtime(secs=None ):\n d=date()\n if secs is not None :\n d=date(secs *1000)\n wday=d.getUTCDay()-1 if d.getUTCDay()-1 >=0 else 6\n tmp=struct_time([d.getUTCFullYear(),\n d.getUTCMonth()+1,d.getUTCDate(),\n d.getUTCHours(),d.getUTCMinutes(),d.getUTCSeconds(),\n wday,0,0])\n tmp.args[7]=_get_day_of_year(tmp.args)\n return tmp\n \ndef localtime(secs=None ):\n d=date()\n if secs is not None :\n d=date(secs *1000)\n dst=_is_dst(secs)\n wday=d.getDay()-1 if d.getDay()-1 >=0 else 6\n tmp=struct_time([d.getFullYear(),\n d.getMonth()+1,d.getDate(),\n d.getHours(),d.getMinutes(),d.getSeconds(),\n wday,0,dst])\n tmp.args[7]=_get_day_of_year(tmp.args)\n return tmp\n \ndef mktime(t):\n if isinstance(t,struct_time):\n d1=date(t.tm_year,t.tm_mon -1,t.tm_mday,\n t.tm_hour,t.tm_min,t.tm_sec,0).getTime()\n elif isinstance(t,tuple):\n d1=date(t[0],t[1]-1,t[2],t[3],t[4],t[5],0).getTime()\n else :\n raise ValueError(\"Tuple or struct_time argument required\")\n d2=date(0).getTime()\n return (d1 -d2)/1000.\n \ndef monotonic():\n return now()/1000.\n \ndef perf_counter():\n return now()/1000.\n \ndef process_time():\n return now()/1000.\n \ndef time():\n return float(date().getTime()/1000)\n \ndef sleep(secs):\n ''\n\n \n raise NotImplementedError(\"Blocking functions like time.sleep() are not \"\n \"supported in the browser. Use functions in module browser.timer \"\n \"instead.\")\n \ndef strftime(_format,t=None ):\n def ns(t,nb):\n \n res=str(t)\n while len(res)<nb:\n res='0'+res\n return res\n \n t=_check_input(t)\n t=_check_struct_time(t)\n \n YY=ns(t[0],4)\n yy=ns(t[0],4)[2:]\n mm=ns(t[1],2)\n dd=ns(t[2],2)\n HH=t[3]\n HH24=ns(HH,2)\n HH12=ns(HH %12,2)\n if HH12 ==0:\n HH12=12\n AMPM='AM'if 0 <=HH <12 else 'PM'\n MM=ns(t[4],2)\n SS=ns(t[5],2)\n DoY=ns(t[7],3)\n w=t[6]+1 if t[6]<6 else 0\n W=ns(_get_week_of_year(t),2)\n \n abb_weekdays=['Sun','Mon','Tue','Wed','Thu','Fri','Sat']\n full_weekdays=['Sunday','Monday','Tuesday','Wednesday',\n 'Thursday','Friday','Saturday']\n abb_months=['Jan','Feb','Mar','Apr','May','Jun',\n 'Jul','Aug','Sep','Oct','Nov','Dec']\n full_months=['January','February','March','April','May','June',\n 'July','August','September','October','November','December']\n \n res=_format\n if __BRYTHON__.locale ==\"C\":\n res=res.replace(\"%c\",abb_weekdays[w]+' '+abb_months[int(mm)-1]+\n ' '+dd+' '+HH24+':'+MM+':'+SS+' '+YY)\n res=res.replace(\"%x\",mm+'/'+dd+'/'+yy)\n res=res.replace(\"%X\",HH24+':'+MM+':'+SS)\n else :\n formatter=_locale._date_format\n c_format=formatter(\"x\")+\" \"+formatter(\"X\")\n res=res.replace(\"%c\",c_format)\n x_format=formatter(\"x\")\n res=res.replace(\"%x\",x_format)\n X_format=formatter(\"X\")\n res=res.replace(\"%X\",X_format)\n \n res=res.replace(\"%H\",HH24)\n res=res.replace(\"%I\",HH12)\n res=res.replace(\"%i\",HH12.lstrip(\"0\"))\n res=res.replace(\"%p\",AMPM)\n res=res.replace(\"%M\",MM)\n res=res.replace(\"%S\",SS)\n res=res.replace(\"%Y\",YY)\n res=res.replace(\"%y\",yy)\n res=res.replace(\"%m\",mm)\n res=res.replace(\"%d\",dd)\n res=res.replace(\"%a\",abb_weekdays[w])\n res=res.replace(\"%A\",full_weekdays[w])\n res=res.replace(\"%b\",abb_months[int(mm)-1])\n res=res.replace(\"%B\",full_months[int(mm)-1])\n res=res.replace(\"%j\",DoY)\n res=res.replace(\"%w\",str(w))\n res=res.replace(\"%W\",W)\n res=res.replace(\"%%\",'%')\n \n return res\n \nclass struct_time:\n\n def __init__(self,*args,**kw):\n \n time_tuple=args[0]\n if len(time_tuple)!=9:\n raise TypeError(\"time.struct_time() takes a 9-sequence (%s-sequence given)\"%len(args))\n \n self.args=time_tuple\n \n @property\n def tm_year(self):\n return self.args[0]\n \n @property\n def tm_mon(self):\n return self.args[1]\n \n @property\n def tm_mday(self):\n return self.args[2]\n \n @property\n def tm_hour(self):\n return self.args[3]\n \n @property\n def tm_min(self):\n return self.args[4]\n \n @property\n def tm_sec(self):\n return self.args[5]\n \n @property\n def tm_wday(self):\n return self.args[6]\n \n @property\n def tm_yday(self):\n return self.args[7]\n \n @property\n def tm_isdst(self):\n return self.args[8]\n \n def __eq__(self,other):\n return self.args ==other.args\n \n def __getitem__(self,i):\n return self.args[i]\n \n def __iter__(self):\n return iter(self.args)\n \n def __reduce_ex__(self,protocol):\n return (struct_time,(self.args,{}))\n \n def __repr__(self):\n return (\"time.structime(tm_year={}, tm_mon={}, tm_day={}, \"+\\\n \"tm_hour={}, tm_min={}, tm_sec={}, tm_wday={}, \"+\\\n \"tm_yday={}, tm_isdst={})\").format(*self.args)\n \n def __str__(self):\n return self.__repr__()\n \ndef to_struct_time(*arg):\n arg=list(arg)\n \n \n ml=[31,28,31,30,31,30,31,31,30,31,30,31]\n if arg[0]%4 ==0:\n ml[1]+=1\n \n i=1\n yday=0\n while i <arg[1]:\n yday +=ml[i -1]\n i +=1\n yday +=arg[2]\n arg.append(yday)\n arg.append(-1)\n return struct_time(tuple(arg))\n \ndef wait(secs):\n\n pass\n \ndef strptime(string,_format):\n import _strptime\n return _strptime._strptime_datetime(to_struct_time,string,_format)\n \n \n \n_clock_msg=\"\"\"Browser cannot access CPU. See '%s'\"\"\"\ndef _clock_xx(url):\n raise NotImplementedError(_clock_msg %url)\nclock=time\nclock_getres=lambda :_clock_xx(\"https://docs.python.org/3/library/time.html#time.clock_getres\")\nclock_gettime=lambda :_clock_xx(\"https://docs.python.org/3/library/time.html#time.clock_gettime\")\nclock_settime=lambda :_clock_xx(\"https://docs.python.org/3/library/time.html#time.clock_settime\")\nCLOCK_HIGHRES=_clock_msg %\"https://docs.python.org/3/library/time.html#time.CLOCK_HIGHRES\"\nCLOCK_MONOTONIC=_clock_msg %\"https://docs.python.org/3/library/time.html#time.CLOCK_MONOTONIC\"\nCLOCK_MONOTONIC_RAW=_clock_msg %\"https://docs.python.org/3/library/time.html#time.CLOCK_MONOTONIC_RAW\"\nCLOCK_PROCESS_CPUTIME_ID=_clock_msg %\"https://docs.python.org/3/library/time.html#time.CLOCK_PROCESS_CPUTIME_ID\"\nCLOCK_REALTIME=_clock_msg %\"https://docs.python.org/3/library/time.html#time.CLOCK_REALTIME\"\nCLOCK_THREAD_CPUTIME_ID=_clock_msg %\"https://docs.python.org/3/library/time.html#time.CLOCK_THREAD_CPUTIME_ID\"\n\n\ndef get_clock_info(cl):\n from collections import namedtuple\n ClockInfo=namedtuple('ClockInfo',\n ['adjustable','implementation','monotonic','resolution'])\n \n if cl =='monotonic':\n return ClockInfo(adjustable=False ,\n implementation='window.performance.now',\n monotonic=True ,\n resolution=0.000001)\n elif cl =='perf_counter'or cl =='process_time':\n return ClockInfo(adjustable=False ,\n implementation='date.getTime',\n monotonic=False ,\n resolution=0.001)\n else :\n _clock_xx(\"https://docs.python.org/3/library/time.html#time.get_clock_info\")\n \ndef tzset():\n pass\n", ["_locale", "_strptime", "collections", "javascript"]], "_binascii": [".js", "var $module=(function($B){\n\nvar _b_ = $B.builtins,\n _keyStr = \"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=\"\n\nvar error = $B.make_class(\"error\", _b_.Exception.$factory)\nerror.__bases__ = [_b_.Exception]\n$B.set_func_names(error, \"binascii\")\n\nfunction decode(bytes, altchars, validate){\n var output = [],\n chr1, chr2, chr3,\n enc1, enc2, enc3, enc4\n\n var alphabet = make_alphabet(altchars)\n\n var input = bytes.source\n\n // If validate is set, check that all characters in input\n // are in the alphabet\n var _input = ''\n var padding = 0\n for(var i = 0, len = input.length; i < len; i++){\n var car = String.fromCharCode(input[i])\n var char_num = alphabet.indexOf(car)\n if(char_num == -1){\n if(validate){throw error.$factory(\"Non-base64 digit found: \" +\n car)}\n }else if(char_num == 64 && i < input.length - 2){\n if(validate){throw error.$factory(\"Non-base64 digit found: \" +\n car)}\n }else if(char_num == 64 && i >= input.length - 2){\n padding++\n _input += car\n }else{\n _input += car\n }\n }\n input = _input\n if(_input.length == padding){return _b_.bytes.$factory([])}\n if( _input.length % 4 > 0){throw error.$factory(\"Incorrect padding\")}\n\n var i = 0\n while(i < input.length){\n\n enc1 = alphabet.indexOf(input.charAt(i++))\n enc2 = alphabet.indexOf(input.charAt(i++))\n enc3 = alphabet.indexOf(input.charAt(i++))\n enc4 = alphabet.indexOf(input.charAt(i++))\n\n chr1 = (enc1 << 2) | (enc2 >> 4)\n chr2 = ((enc2 & 15) << 4) | (enc3 >> 2)\n chr3 = ((enc3 & 3) << 6) | enc4\n\n output.push(chr1)\n\n if(enc3 != 64){output.push(chr2)}\n if(enc4 != 64){output.push(chr3)}\n\n }\n // return Python bytes\n return _b_.bytes.$factory(output, 'utf-8', 'strict')\n\n}\n\nfunction make_alphabet(altchars){\n var alphabet = _keyStr\n if(altchars !== undefined && altchars !== _b_.None){\n // altchars is an instance of Python bytes\n var source = altchars.source\n alphabet = alphabet.substr(0,alphabet.length-3) +\n _b_.chr(source[0]) + _b_.chr(source[1]) + '='\n }\n return alphabet\n}\n\nvar module = {\n a2b_base64: function(){\n var $ = $B.args(\"a2b_base64\", 1, {s: null}, ['s'],\n arguments, {}, null, null)\n return decode($.s)\n },\n b2a_base64: function(){\n var $ = $B.args(\"b2a_base64\", 1, {data: null}, ['data'],\n arguments, {}, null, \"kw\")\n var newline = false\n if($.kw && $.kw.$string_dict){\n newline = $.kw.$string_dict[\"newline\"]\n }\n\n var string = $B.to_bytes($.data),\n res = btoa(String.fromCharCode.apply(null, string))\n if(newline){res += \"\\n\"}\n return _b_.bytes.$factory(res, \"ascii\")\n },\n b2a_hex: function(obj){\n var string = $B.to_bytes(obj),\n res = []\n function conv(c){\n if(c > 9){\n c = c + 'a'.charCodeAt(0) - 10\n }else{\n c = c + '0'.charCodeAt(0)\n }\n return c\n }\n string.forEach(function(char){\n res.push(conv((char >> 4) & 0xf))\n res.push(conv(char & 0xf))\n })\n return _b_.bytes.$factory(res, \"ascii\")\n },\n b2a_uu: function(obj){\n var string = $B.to_bytes(obj)\n var len = string.length,\n res = String.fromCharCode((0x20 + len) & 0x3F)\n while(string.length > 0){\n var s = string.slice(0, 3)\n while(s.length < 3){s.push(String.fromCharCode(0))}\n var A = s[0],\n B = s[1],\n C = s[2]\n var a = (A >> 2) & 0x3F,\n b = ((A << 4) | ((B >> 4) & 0xF)) & 0x3F,\n c = (((B << 2) | ((C >> 6) & 0x3)) & 0x3F),\n d = C & 0x3F\n res += String.fromCharCode(0x20 + a, 0x20 + b, 0x20 + c, 0x20 + d)\n string = string.slice(3)\n }\n return _b_.bytes.$factory(res + \"\\n\", \"ascii\")\n },\n error: error\n}\n\nmodule.hexlify = module.b2a_hex\n\nreturn module\n}\n)(__BRYTHON__)"], "fnmatch": [".py", "''\n\n\n\n\n\n\n\n\n\n\nimport os\nimport posixpath\nimport re\nimport functools\n\n__all__=[\"filter\",\"fnmatch\",\"fnmatchcase\",\"translate\"]\n\ndef fnmatch(name,pat):\n ''\n\n\n\n\n\n\n\n\n\n\n\n\n \n name=os.path.normcase(name)\n pat=os.path.normcase(pat)\n return fnmatchcase(name,pat)\n \n@functools.lru_cache(maxsize=256,typed=True )\ndef _compile_pattern(pat):\n if isinstance(pat,bytes):\n pat_str=str(pat,'ISO-8859-1')\n res_str=translate(pat_str)\n res=bytes(res_str,'ISO-8859-1')\n else :\n res=translate(pat)\n return re.compile(res).match\n \ndef filter(names,pat):\n ''\n result=[]\n pat=os.path.normcase(pat)\n match=_compile_pattern(pat)\n if os.path is posixpath:\n \n for name in names:\n if match(name):\n result.append(name)\n else :\n for name in names:\n if match(os.path.normcase(name)):\n result.append(name)\n return result\n \ndef fnmatchcase(name,pat):\n ''\n\n\n\n \n match=_compile_pattern(pat)\n return match(name)is not None\n \n \ndef translate(pat):\n ''\n\n\n \n \n i,n=0,len(pat)\n res=''\n while i <n:\n c=pat[i]\n i=i+1\n if c =='*':\n res=res+'.*'\n elif c =='?':\n res=res+'.'\n elif c =='[':\n j=i\n if j <n and pat[j]=='!':\n j=j+1\n if j <n and pat[j]==']':\n j=j+1\n while j <n and pat[j]!=']':\n j=j+1\n if j >=n:\n res=res+'\\\\['\n else :\n stuff=pat[i:j]\n if '--'not in stuff:\n stuff=stuff.replace('\\\\',r'\\\\')\n else :\n chunks=[]\n k=i+2 if pat[i]=='!'else i+1\n while True :\n k=pat.find('-',k,j)\n if k <0:\n break\n chunks.append(pat[i:k])\n i=k+1\n k=k+3\n chunks.append(pat[i:j])\n \n \n stuff='-'.join(s.replace('\\\\',r'\\\\').replace('-',r'\\-')\n for s in chunks)\n \n stuff=re.sub(r'([&~|])',r'\\\\\\1',stuff)\n i=j+1\n if stuff[0]=='!':\n stuff='^'+stuff[1:]\n elif stuff[0]in ('^','['):\n stuff='\\\\'+stuff\n res='%s[%s]'%(res,stuff)\n else :\n res=res+re.escape(c)\n return r'(?s:%s)\\Z'%res\n", ["functools", "os", "posixpath", "re"]], "_warnings": [".js", "var $module = (function($B){\n\n_b_ = $B.builtins\n\nreturn {\n __doc__: \"_warnings provides basic warning filtering support.\\n \" +\n \"It is a helper module to speed up interpreter start-up.\",\n\n default_action: \"default\",\n\n filters: [\n ['ignore', _b_.None, _b_.DeprecationWarning, _b_.None, 0],\n ['ignore', _b_.None, _b_.PendingDeprecationWarning, _b_.None, 0],\n ['ignore', _b_.None, _b_.ImportWarning, _b_.None, 0],\n ['ignore', _b_.None, _b_.BytesWarning, _b_.None, 0]].map(\n function(x){return _b_.tuple.$factory(x)}),\n\n once_registry: _b_.dict.$factory(),\n\n warn: function(){},\n\n warn_explicit: function(){}\n\n}\n\n})(__BRYTHON__)\n"], "math": [".js", "var $module = (function($B){\n\nvar _b_ = $B.builtins,\n $s = [],\n i\nfor(var $b in _b_){$s.push('var ' + $b +' = _b_[\"'+$b+'\"]')}\neval($s.join(';'))\n\n//for(var $py_builtin in _b_){eval(\"var \"+$py_builtin+\"=_b_[$py_builtin]\")}\n\nvar float_check = function(x) {\n if(x.__class__ === $B.long_int){return parseInt(x.value)}\n return _b_.float.$factory(x)\n}\n\nvar isWholeNumber = function(x){return (x * 10) % 10 == 0}\n\nvar isOdd = function(x) {return isWholeNumber(x) && 2 * Math.floor(x / 2) != x}\n\nvar isLargeNumber = function(x) {return x > Math.pow(2, 32)}\n\n// Big number Library from jsfromhell.com\n// This library helps with producing \"correct\" results from\n// mathematic operations\n\n//+ Jonas Raoni Soares Silva\n//@ http://jsfromhell.com/classes/bignumber [rev. #4]\n\n\nvar BigNumber = function(n, p, r){\n var o = this, i\n if(n instanceof BigNumber){\n for(i in {precision: 0, roundType: 0, _s: 0, _f: 0}){o[i] = n[i]}\n o._d = n._d.slice()\n return\n }\n o.precision = isNaN(p = Math.abs(p)) ? BigNumber.defaultPrecision : p\n o.roundType = isNaN(r = Math.abs(r)) ? BigNumber.defaultRoundType : r\n o._s = (n += \"\").charAt(0) == \"-\"\n o._f = ((n = n.replace(/[^\\d.]/g, \"\").split(\".\", 2))[0] =\n n[0].replace(/^0+/, \"\") || \"0\").length\n for(i = (n = o._d = (n.join(\"\") || \"0\").split(\"\")).length; i;\n n[--i] = +n[i]){}\n o.round()\n}\nwith({$: BigNumber, o: BigNumber.prototype}){\n $.ROUND_HALF_EVEN = ($.ROUND_HALF_DOWN = ($.ROUND_HALF_UP =\n ($.ROUND_FLOOR = ($.ROUND_CEIL = ($.ROUND_DOWN = ($.ROUND_UP = 0) + 1) +\n 1) + 1) + 1) + 1) + 1\n $.defaultPrecision = 40\n $.defaultRoundType = $.ROUND_HALF_UP\n o.add = function(n){\n if(this._s != (n = new BigNumber(n))._s){\n return n._s ^= 1, this.subtract(n)\n }\n var o = new BigNumber(this),\n a = o._d,\n b = n._d,\n la = o._f,\n lb = n._f,\n n = Math.max(la, lb),\n i,\n r\n la != lb && ((lb = la - lb) > 0 ? o._zeroes(b, lb, 1) :\n o._zeroes(a, -lb, 1))\n i = (la = a.length) == (lb = b.length) ? a.length :\n ((lb = la - lb) > 0 ? o._zeroes(b, lb) : o._zeroes(a, -lb)).length\n for(r = 0; i; r = (a[--i] = a[i] + b[i] + r) / 10 >>> 0, a[i] %= 10){}\n return r && ++n && a.unshift(r), o._f = n, o.round()\n };\n o.subtract = function(n){\n if(this._s != (n = new BigNumber(n))._s)\n return n._s ^= 1, this.add(n);\n var o = new BigNumber(this),\n c = o.abs().compare(n.abs()) + 1,\n a = c ? o : n,\n b = c ? n : o,\n la = a._f,\n lb = b._f,\n d = la,\n i,\n j;\n a = a._d, b = b._d, la != lb && ((lb = la - lb) > 0 ? o._zeroes(b, lb, 1) : o._zeroes(a, -lb, 1));\n for(i = (la = a.length) == (lb = b.length) ? a.length : ((lb = la - lb) > 0 ? o._zeroes(b, lb) : o._zeroes(a, -lb)).length; i;){\n if(a[--i] < b[i]){\n for(j = i; j && !a[--j]; a[j] = 9);\n --a[j], a[i] += 10;\n }\n b[i] = a[i] - b[i];\n }\n return c || (o._s ^= 1), o._f = d, o._d = b, o.round();\n };\n o.multiply = function(n){\n var o = new BigNumber(this), r = o._d.length >= (n = new BigNumber(n))._d.length, a = (r ? o : n)._d,\n b = (r ? n : o)._d, la = a.length, lb = b.length, x = new BigNumber, i, j, s;\n for(i = lb; i; r && s.unshift(r), x.set(x.add(new BigNumber(s.join(\"\")))))\n for(s = (new Array(lb - --i)).join(\"0\").split(\"\"), r = 0, j = la; j; r += a[--j] * b[i], s.unshift(r % 10), r = (r / 10) >>> 0);\n return o._s = o._s != n._s, o._f = ((r = la + lb - o._f - n._f) >= (j = (o._d = x._d).length) ? this._zeroes(o._d, r - j + 1, 1).length : j) - r, o.round();\n };\n o.divide = function(n){\n if((n = new BigNumber(n)) == \"0\")\n throw new Error(\"Division by 0\");\n else if(this == \"0\")\n return new BigNumber;\n var o = new BigNumber(this), a = o._d, b = n._d, la = a.length - o._f,\n lb = b.length - n._f, r = new BigNumber, i = 0, j, s, l, f = 1, c = 0, e = 0;\n r._s = o._s != n._s, r.precision = Math.max(o.precision, n.precision),\n r._f = +r._d.pop(), la != lb && o._zeroes(la > lb ? b : a, Math.abs(la - lb));\n n._f = b.length, b = n, b._s = false, b = b.round();\n for(n = new BigNumber; a[0] == \"0\"; a.shift());\n out:\n do{\n for(l = c = 0, n == \"0\" && (n._d = [], n._f = 0); i < a.length && n.compare(b) == -1; ++i){\n (l = i + 1 == a.length, (!f && ++c > 1 || (e = l && n == \"0\" && a[i] == \"0\")))\n && (r._f == r._d.length && ++r._f, r._d.push(0));\n (a[i] == \"0\" && n == \"0\") || (n._d.push(a[i]), ++n._f);\n if(e)\n break out;\n if((l && n.compare(b) == -1 && (r._f == r._d.length && ++r._f, 1)) || (l = 0))\n while(r._d.push(0), n._d.push(0), ++n._f, n.compare(b) == -1);\n }\n if(f = 0, n.compare(b) == -1 && !(l = 0))\n while(l ? r._d.push(0) : l = 1, n._d.push(0), ++n._f, n.compare(b) == -1);\n for(s = new BigNumber, j = 0; n.compare(y = s.add(b)) + 1 && ++j; s.set(y));\n n.set(n.subtract(s)), !l && r._f == r._d.length && ++r._f, r._d.push(j);\n }\n while((i < a.length || n != \"0\") && (r._d.length - r._f) <= r.precision);\n return r.round();\n };\n o.mod = function(n){\n return this.subtract(this.divide(n).intPart().multiply(n));\n };\n o.pow = function(n){\n var o = new BigNumber(this), i;\n if((n = (new BigNumber(n)).intPart()) == 0) return o.set(1);\n for(i = Math.abs(n); --i; o.set(o.multiply(this)));\n return n < 0 ? o.set((new BigNumber(1)).divide(o)) : o;\n };\n o.set = function(n){\n return this.constructor(n), this;\n };\n o.compare = function(n){\n var a = this, la = this._f, b = new BigNumber(n), lb = b._f, r = [-1, 1], i, l;\n if(a._s != b._s)\n return a._s ? -1 : 1;\n if(la != lb)\n return r[(la > lb) ^ a._s];\n for(la = (a = a._d).length, lb = (b = b._d).length, i = -1, l = Math.min(la, lb); ++i < l;)\n if(a[i] != b[i])\n return r[(a[i] > b[i]) ^ a._s];\n return la != lb ? r[(la > lb) ^ a._s] : 0;\n };\n o.negate = function(){\n var n = new BigNumber(this); return n._s ^= 1, n;\n };\n o.abs = function(){\n var n = new BigNumber(this); return n._s = 0, n;\n };\n o.intPart = function(){\n return new BigNumber((this._s ? \"-\" : \"\") + (this._d.slice(0, this._f).join(\"\") || \"0\"));\n };\n o.valueOf = o.toString = function(){\n var o = this;\n return (o._s ? \"-\" : \"\") + (o._d.slice(0, o._f).join(\"\") || \"0\") + (o._f != o._d.length ? \".\" + o._d.slice(o._f).join(\"\") : \"\");\n };\n o._zeroes = function(n, l, t){\n var s = [\"push\", \"unshift\"][t || 0];\n for(++l; --l; n[s](0));\n return n;\n };\n o.round = function(){\n if(\"_rounding\" in this) return this;\n var $ = BigNumber, r = this.roundType, b = this._d, d, p, n, x;\n for(this._rounding = true; this._f > 1 && !b[0]; --this._f, b.shift());\n for(d = this._f, p = this.precision + d, n = b[p]; b.length > d && !b[b.length -1]; b.pop());\n x = (this._s ? \"-\" : \"\") + (p - d ? \"0.\" + this._zeroes([], p - d - 1).join(\"\") : \"\") + 1;\n if(b.length > p){\n n && (r == $.DOWN ? false : r == $.UP ? true : r == $.CEIL ? !this._s\n : r == $.FLOOR ? this._s : r == $.HALF_UP ? n >= 5 : r == $.HALF_DOWN ? n > 5\n : r == $.HALF_EVEN ? n >= 5 && b[p - 1] & 1 : false) && this.add(x);\n b.splice(p, b.length - p);\n }\n return delete this._rounding, this;\n };\n}\n\nvar isNegZero = function(x) {return x === 0 && Math.atan2(x,x) < 0}\n\nvar _mod = {\n __getattr__ : function(attr){\n var res = this[attr]\n if(res === undefined){$raise('AttributeError',\n 'module math has no attribute ' + attr)}\n return res\n },\n acos: function(x) {return float.$factory(Math.acos(float_check(x)))},\n acosh: function(x) {\n if(_b_.$isinf(x)){return float.$factory('inf')}\n var y = float_check(x)\n return float.$factory(Math.log(y + Math.sqrt(y * y - 1)))\n },\n asin: function(x) {return float.$factory(Math.asin(float_check(x)))},\n asinh: function(x) {\n if(_b_.$isninf(x)){return float.$factory('-inf')}\n if(_b_.$isinf(x)){return float.$factory('inf')}\n var y = float_check(x)\n return float.$factory(Math.log(y + Math.sqrt(y * y + 1)))\n },\n atan: function(x) {\n if(_b_.$isninf(x)){return float.$factory(-Math.PI / 2)}\n if(_b_.$isinf(x)){return float.$factory(Math.PI / 2)}\n return float.$factory(Math.atan(float_check(x)))},\n atan2: function(y, x) {\n return float.$factory(Math.atan2(float_check(y), float_check(x)))\n },\n atanh: function(x) {\n var y = float_check(x)\n if(y == 0){return 0}\n return float.$factory(0.5 * Math.log((1 / y + 1)/(1 / y - 1)));\n },\n ceil: function(x) {\n try{return getattr(x, '__ceil__')()}catch(err){}\n\n if(_b_.$isninf(x)){return float.$factory('-inf')}\n if(_b_.$isinf(x)){return float.$factory('inf')}\n if(isNaN(x)){return float.$factory('nan')}\n\n var y = float_check(x)\n if(! isNaN(parseFloat(y)) && isFinite(y)){\n return int.$factory(Math.ceil(y))\n }\n\n $raise('ValueError',\n 'object is not a number and does not contain __ceil__')\n },\n copysign: function(x,y) {\n var x1 = Math.abs(float_check(x))\n var y1 = float_check(y)\n var sign = Math.sign(y1)\n sign = (sign == 1 || Object.is(sign, +0)) ? 1 : - 1\n return float.$factory(x1 * sign)\n },\n cos : function(x){return float.$factory(Math.cos(float_check(x)))},\n cosh: function(x){\n if(_b_.$isinf(x)) {return float.$factory('inf')}\n var y = float_check(x)\n if(Math.cosh !== undefined){return float.$factory(Math.cosh(y))}\n return float.$factory((Math.pow(Math.E, y) + Math.pow(Math.E, -y)) / 2)\n },\n degrees: function(x){return float.$factory(float_check(x) * 180 / Math.PI)},\n e: float.$factory(Math.E),\n erf: function(x) {\n // inspired from\n // http://stackoverflow.com/questions/457408/is-there-an-easily-available-implementation-of-erf-for-python\n var y = float_check(x)\n var t = 1.0 / (1.0 + 0.5 * Math.abs(y))\n var ans = 1 - t * Math.exp( -y * y - 1.26551223 +\n t * ( 1.00002368 +\n t * ( 0.37409196 +\n t * ( 0.09678418 +\n t * (-0.18628806 +\n t * ( 0.27886807 +\n t * (-1.13520398 +\n t * ( 1.48851587 +\n t * (-0.82215223 +\n t * 0.17087277)))))))))\n if(y >= 0.0){return ans}\n return -ans\n },\n\n erfc: function(x) {\n // inspired from\n // http://stackoverflow.com/questions/457408/is-there-an-easily-available-implementation-of-erf-for-python\n var y = float_check(x)\n var t = 1.0 / (1.0 + 0.5 * Math.abs(y))\n var ans = 1 - t * Math.exp( -y * y - 1.26551223 +\n t * ( 1.00002368 +\n t * ( 0.37409196 +\n t * ( 0.09678418 +\n t * (-0.18628806 +\n t * ( 0.27886807 +\n t * (-1.13520398 +\n t * ( 1.48851587 +\n t * (-0.82215223 +\n t * 0.17087277)))))))))\n if(y >= 0.0){return 1 - ans}\n return 1 + ans\n },\n exp: function(x){\n if(_b_.$isninf(x)){return float.$factory(0)}\n if(_b_.$isinf(x)){return float.$factory('inf')}\n var _r = Math.exp(float_check(x))\n if(_b_.$isinf(_r)){throw OverflowError(\"math range error\")}\n return float.$factory(_r)\n },\n expm1: function(x){\n if(_b_.$isninf(x)){return float.$factory(0)}\n if(_b_.$isinf(x)){return float.$factory('inf')}\n var _r = Math.expm1(float_check(x))\n if(_b_.$isinf(_r)){throw OverflowError(\"math range error\")}\n return float.$factory(_r)\n },\n //fabs: function(x){ return x>0?float.$factory(x):float.$factory(-x)},\n fabs: function(x){return _b_.$fabs(x)}, //located in py_float.js\n factorial: function(x) {\n //using code from http://stackoverflow.com/questions/3959211/fast-factorial-function-in-javascript\n var y = float_check(x),\n r = 1\n for(var i = 2; i <= y; i++){r *= i}\n return r\n },\n floor: function(x){return Math.floor(float_check(x))},\n fmod: function(x,y){return float.$factory(float_check(x) % float_check(y))},\n frexp: function(x){\n var _l = _b_.$frexp(x)\n return _b_.tuple.$factory([float.$factory(_l[0]), _l[1]])\n },\n fsum: function(x){\n /* Translation into Javascript of the function msum in an Active\n State Cookbook recipe : https://code.activestate.com/recipes/393090/\n by Raymond Hettinger\n */\n var partials = [],\n res = new Number(),\n _it = _b_.iter(x)\n while(true){\n try{\n var x = _b_.next(_it),\n i = 0\n for(var j = 0, len = partials.length; j < len; j++){\n var y = partials[j]\n if(Math.abs(x) < Math.abs(y)){\n var z = x\n x = y\n y = z\n }\n var hi = x + y,\n lo = y - (hi - x)\n if(lo){\n partials[i] = lo\n i++\n }\n x = hi\n }\n partials = partials.slice(0, i).concat([x])\n }catch(err){\n if(_b_.isinstance(err, _b_.StopIteration)){break}\n throw err\n }\n }\n var res = new Number(0)\n for(var i = 0; i < partials.length; i++){\n res += new Number(partials[i])\n }\n return new Number(res)\n },\n gamma: function(x){\n if(_b_.isinstance(x, int)){\n if(i < 1){\n throw _b_.ValueError.$factory(\"math domain error\")\n }\n var res = 1\n for(var i = 1; i < x; i++){res *= i}\n return new Number(res)\n }\n // Adapted from https://en.wikipedia.org/wiki/Lanczos_approximation\n var p = [676.5203681218851,\n -1259.1392167224028,\n 771.32342877765313,\n -176.61502916214059,\n 12.507343278686905,\n -0.13857109526572012,\n 9.9843695780195716e-6,\n 1.5056327351493116e-7\n ]\n\n var EPSILON = 1e-07\n function drop_imag(z){\n if(Math.abs(z.imag) <= EPSILON){\n z = z.real\n }\n return z\n }\n var z = x\n if(z < 0.5){\n var y = Math.PI / (Math.sin(Math.PI * z) * _mod.gamma(1-z)) // Reflection formula\n }else{\n z -= 1\n var x = 0.99999999999980993,\n i = 0\n for(var i = 0, len = p.length; i < len; i++){\n var pval = p[i]\n x += pval / (z + i + 1)\n }\n var t = z + p.length - 0.5,\n sq = Math.sqrt(2 * Math.PI),\n y = sq * Math.pow(t, (z + 0.5)) * Math.exp(-t) * x\n }\n return drop_imag(y)\n },\n gcd: function(){\n var $ = $B.args(\"gcd\", 2, {a: null, b: null}, ['a', 'b'],\n arguments, {}, null, null),\n a = $B.PyNumber_Index($.a),\n b = $B.PyNumber_Index($.b)\n if(a == 0 && b == 0){return 0}\n // https://stackoverflow.com/questions/17445231/js-how-to-find-the-greatest-common-divisor\n a = Math.abs(a);\n b = Math.abs(b);\n if(b > a){var temp = a; a = b; b = temp;}\n while(true){\n if(b == 0){return a}\n a %= b\n if(a == 0){return b}\n b %= a\n }\n },\n hypot: function(x,y){\n if(_b_.$isinf(x) || _b_.$isinf(y)){return float.$factory('inf')}\n var x1 = float_check(x),\n y1 = float_check(y)\n return float.$factory(Math.sqrt(x1 * x1 + y1 * y1))},\n inf: float.$factory('inf'),\n isclose:function(){\n var $ns = $B.args(\"isclose\",\n 4,\n {a: null, b: null, rel_tol: null, abs_tol: null},\n ['a', 'b', 'rel_tol', 'abs_tol'],\n arguments,\n {rel_tol: 1e-09, abs_tol: 0.0},\n null,\n null)\n var a = $ns['a'],\n b = $ns['b'],\n rel_tol = $ns['rel_tol'],\n abs_tol = $ns['abs_tol']\n if(rel_tol < 0.0 || abs_tol < 0.0){\n throw ValueError('tolerances must be non-negative')\n }\n if(a == b){return True}\n if(_b_.$isinf(a) || _b_.$isinf(b)){return false}\n var diff = _b_.$fabs(b - a)\n var result = (\n (diff <= _b_.$fabs(rel_tol * b)) ||\n (diff <= _b_.$fabs(rel_tol * a))\n ) || (diff <= _b_.$fabs(abs_tol)\n )\n return result\n },\n isfinite: function(x){return isFinite(float_check(x))},\n isinf: function(x){return _b_.$isinf(float_check(x))},\n isnan: function(x){return isNaN(float_check(x))},\n ldexp: function(x, i){return _b_.$ldexp(x, i)}, //located in py_float.js\n lgamma: function(x){\n return new Number(Math.log(Math.abs(_mod.gamma(x))))\n },\n log: function(x, base){\n var x1 = float_check(x)\n if(base === undefined){return float.$factory(Math.log(x1))}\n return float.$factory(Math.log(x1) / Math.log(float_check(base)))\n },\n log1p: function(x){return float.$factory(Math.log1p(float_check(x)))},\n log2: function(x){\n if(isNaN(x)){return float.$factory('nan')}\n if(_b_.$isninf(x)) {throw ValueError('')}\n var x1 = float_check(x)\n if(x1 < 0.0){throw ValueError('')}\n return float.$factory(Math.log(x1) / Math.LN2)\n },\n log10: function(x) {\n return float.$factory(Math.log10(float_check(x)))\n },\n modf: function(x) {\n if(_b_.$isninf(x)){\n return _b_.tuple.$factory([0.0, float.$factory('-inf')])\n }\n if(_b_.$isinf(x)){\n return _b_.tuple.$factory([0.0, float.$factory('inf')])\n }\n if(isNaN(x)){\n return _b_.tuple.$factory([float.$factory('nan'),\n float.$factory('nan')])\n }\n\n var x1 = float_check(x)\n if(x1 > 0){\n var i = float.$factory(x1 - Math.floor(x1))\n return _b_.tuple.$factory([i, float.$factory(x1 - i)])\n }\n\n var x2 = Math.ceil(x1)\n var i = float.$factory(x1 - x2)\n return _b_.tuple.$factory([i, float.$factory(x2)])\n },\n nan: float.$factory('nan'),\n pi : float.$factory(Math.PI),\n pow: function(x,y) {\n var x1 = float_check(x)\n var y1 = float_check(y)\n if(y1 == 0){return float.$factory(1)}\n if(x1 == 0 && y1 < 0){throw _b_.ValueError('')}\n\n if(isNaN(y1)){\n if(x1 == 1){return float.$factory(1)}\n return float.$factory('nan')\n }\n if(x1 == 0){return float.$factory(0)}\n\n if(_b_.$isninf(y)){\n if(x1 == 1 || x1 == -1){return float.$factory(1)}\n if(x1 < 1 && x1 > -1){return float.$factory('inf')}\n return float.$factory(0)\n }\n if(_b_.$isinf(y)){\n if(x1 == 1 || x1 == -1){return float.$factory(1)}\n if(x1 < 1 && x1 > -1){return float.$factory(0)}\n return float.$factory('inf')\n }\n\n if(isNaN(x1)){return float.$factory('nan')}\n if(_b_.$isninf(x)){\n if(y1 > 0 && isOdd(y1)){return float.$factory('-inf')}\n if(y1 > 0){return float.$factory('inf')} // this is even or a float\n if(y1 < 0){return float.$factory(0)}\n return float.$factory(1)\n }\n\n if(_b_.$isinf(x)){\n if(y1 > 0){return float.$factory('inf')}\n if(y1 < 0){return float.$factory(0)}\n return float.$factory(1)\n }\n\n var r\n if(isLargeNumber(x1) || isLargeNumber(y1)){\n var x = new BigNumber(x1),\n y = new BigNumber(y1)\n r = x.pow(y)\n }else{\n r = Math.pow(x1,y1)\n }\n\n if(isNaN(r)){return float.$factory('nan')}\n if(_b_.$isninf(r)){return float.$factory('-inf')}\n if(_b_.$isinf(r)){return float.$factory('inf')}\n\n return r\n },\n radians: function(x){\n return float.$factory(float_check(x) * Math.PI / 180)\n },\n sin : function(x){return float.$factory(Math.sin(float_check(x)))},\n sinh: function(x) {\n //if (_b_.$isinf(x)) return float.$factory('inf');\n var y = float_check(x)\n if(Math.sinh !== undefined){return float.$factory(Math.sinh(y))}\n return float.$factory(\n (Math.pow(Math.E, y) - Math.pow(Math.E, -y)) / 2)\n },\n sqrt : function(x){\n var y = float_check(x)\n if(y < 0){throw ValueError(\"math range error\")}\n if(_b_.$isinf(y)){return float.$factory('inf')}\n var _r = Math.sqrt(y)\n if(_b_.$isinf(_r)){throw OverflowError(\"math range error\")}\n return float.$factory(_r)\n },\n tan: function(x) {\n var y = float_check(x)\n return float.$factory(Math.tan(y))\n },\n tanh: function(x) {\n var y = float_check(x)\n if(Math.tanh !== undefined){return float.$factory(Math.tanh(y))}\n return float.$factory((Math.pow(Math.E, y) - Math.pow(Math.E, -y))/\n (Math.pow(Math.E, y) + Math.pow(Math.E, -y)))\n },\n trunc: function(x) {\n try{return getattr(x, '__trunc__')()}catch(err){}\n var x1 = float_check(x)\n if(!isNaN(parseFloat(x1)) && isFinite(x1)){\n if(Math.trunc !== undefined){return int.$factory(Math.trunc(x1))}\n if(x1 > 0){return int.$factory(Math.floor(x1))}\n return int.$factory(Math.ceil(x1)) // x1 < 0\n }\n $raise('ValueError',\n 'object is not a number and does not contain __trunc__')\n }\n}\n\nfor(var $attr in _mod){\n if(typeof _mod[$attr] === 'function'){\n _mod[$attr].__repr__ = (function(func){\n return function(){return '<built-in function ' + func + '>'}\n })($attr)\n _mod[$attr].__str__ = (function(func){\n return function(){return '<built-in function ' + func + '>'}\n })($attr)\n }\n}\n\nreturn _mod\n\n})(__BRYTHON__)\n"], "unittest.suite": [".py", "''\n\nimport sys\n\nfrom . import case\nfrom . import util\n\n__unittest=True\n\n\ndef _call_if_exists(parent,attr):\n func=getattr(parent,attr,lambda :None )\n func()\n \n \nclass BaseTestSuite(object):\n ''\n \n _cleanup=True\n \n def __init__(self,tests=()):\n self._tests=[]\n self._removed_tests=0\n self.addTests(tests)\n \n def __repr__(self):\n return \"<%s tests=%s>\"%(util.strclass(self.__class__),list(self))\n \n def __eq__(self,other):\n if not isinstance(other,self.__class__):\n return NotImplemented\n return list(self)==list(other)\n \n def __iter__(self):\n return iter(self._tests)\n \n def countTestCases(self):\n cases=self._removed_tests\n for test in self:\n if test:\n cases +=test.countTestCases()\n return cases\n \n def addTest(self,test):\n \n if not callable(test):\n raise TypeError(\"{} is not callable\".format(repr(test)))\n if isinstance(test,type)and issubclass(test,\n (case.TestCase,TestSuite)):\n raise TypeError(\"TestCases and TestSuites must be instantiated \"\n \"before passing them to addTest()\")\n self._tests.append(test)\n \n def addTests(self,tests):\n if isinstance(tests,str):\n raise TypeError(\"tests must be an iterable of tests, not a string\")\n for test in tests:\n self.addTest(test)\n \n def run(self,result):\n for index,test in enumerate(self):\n if result.shouldStop:\n break\n test(result)\n if self._cleanup:\n self._removeTestAtIndex(index)\n return result\n \n def _removeTestAtIndex(self,index):\n ''\n try :\n test=self._tests[index]\n except TypeError:\n \n pass\n else :\n \n \n if hasattr(test,'countTestCases'):\n self._removed_tests +=test.countTestCases()\n self._tests[index]=None\n \n def __call__(self,*args,**kwds):\n return self.run(*args,**kwds)\n \n def debug(self):\n ''\n for test in self:\n test.debug()\n \n \nclass TestSuite(BaseTestSuite):\n ''\n\n\n\n\n\n\n \n \n def run(self,result,debug=False ):\n topLevel=False\n if getattr(result,'_testRunEntered',False )is False :\n result._testRunEntered=topLevel=True\n \n for index,test in enumerate(self):\n if result.shouldStop:\n break\n \n if _isnotsuite(test):\n self._tearDownPreviousClass(test,result)\n self._handleModuleFixture(test,result)\n self._handleClassSetUp(test,result)\n result._previousTestClass=test.__class__\n \n if (getattr(test.__class__,'_classSetupFailed',False )or\n getattr(result,'_moduleSetUpFailed',False )):\n continue\n \n if not debug:\n test(result)\n else :\n test.debug()\n \n if self._cleanup:\n self._removeTestAtIndex(index)\n \n if topLevel:\n self._tearDownPreviousClass(None ,result)\n self._handleModuleTearDown(result)\n result._testRunEntered=False\n return result\n \n def debug(self):\n ''\n debug=_DebugResult()\n self.run(debug,True )\n \n \n \n def _handleClassSetUp(self,test,result):\n previousClass=getattr(result,'_previousTestClass',None )\n currentClass=test.__class__\n if currentClass ==previousClass:\n return\n if result._moduleSetUpFailed:\n return\n if getattr(currentClass,\"__unittest_skip__\",False ):\n return\n \n try :\n currentClass._classSetupFailed=False\n except TypeError:\n \n \n pass\n \n setUpClass=getattr(currentClass,'setUpClass',None )\n if setUpClass is not None :\n _call_if_exists(result,'_setupStdout')\n try :\n setUpClass()\n except Exception as e:\n if isinstance(result,_DebugResult):\n raise\n currentClass._classSetupFailed=True\n className=util.strclass(currentClass)\n errorName='setUpClass (%s)'%className\n self._addClassOrModuleLevelException(result,e,errorName)\n finally :\n _call_if_exists(result,'_restoreStdout')\n \n def _get_previous_module(self,result):\n previousModule=None\n previousClass=getattr(result,'_previousTestClass',None )\n if previousClass is not None :\n previousModule=previousClass.__module__\n return previousModule\n \n \n def _handleModuleFixture(self,test,result):\n previousModule=self._get_previous_module(result)\n currentModule=test.__class__.__module__\n if currentModule ==previousModule:\n return\n \n self._handleModuleTearDown(result)\n \n \n result._moduleSetUpFailed=False\n try :\n module=sys.modules[currentModule]\n except KeyError:\n return\n setUpModule=getattr(module,'setUpModule',None )\n if setUpModule is not None :\n _call_if_exists(result,'_setupStdout')\n try :\n setUpModule()\n except Exception as e:\n if isinstance(result,_DebugResult):\n raise\n result._moduleSetUpFailed=True\n errorName='setUpModule (%s)'%currentModule\n self._addClassOrModuleLevelException(result,e,errorName)\n finally :\n _call_if_exists(result,'_restoreStdout')\n \n def _addClassOrModuleLevelException(self,result,exception,errorName):\n error=_ErrorHolder(errorName)\n addSkip=getattr(result,'addSkip',None )\n if addSkip is not None and isinstance(exception,case.SkipTest):\n addSkip(error,str(exception))\n else :\n result.addError(error,sys.exc_info())\n \n def _handleModuleTearDown(self,result):\n previousModule=self._get_previous_module(result)\n if previousModule is None :\n return\n if result._moduleSetUpFailed:\n return\n \n try :\n module=sys.modules[previousModule]\n except KeyError:\n return\n \n tearDownModule=getattr(module,'tearDownModule',None )\n if tearDownModule is not None :\n _call_if_exists(result,'_setupStdout')\n try :\n tearDownModule()\n except Exception as e:\n if isinstance(result,_DebugResult):\n raise\n errorName='tearDownModule (%s)'%previousModule\n self._addClassOrModuleLevelException(result,e,errorName)\n finally :\n _call_if_exists(result,'_restoreStdout')\n \n def _tearDownPreviousClass(self,test,result):\n previousClass=getattr(result,'_previousTestClass',None )\n currentClass=test.__class__\n if currentClass ==previousClass:\n return\n if getattr(previousClass,'_classSetupFailed',False ):\n return\n if getattr(result,'_moduleSetUpFailed',False ):\n return\n if getattr(previousClass,\"__unittest_skip__\",False ):\n return\n \n tearDownClass=getattr(previousClass,'tearDownClass',None )\n if tearDownClass is not None :\n _call_if_exists(result,'_setupStdout')\n try :\n tearDownClass()\n except Exception as e:\n if isinstance(result,_DebugResult):\n raise\n className=util.strclass(previousClass)\n errorName='tearDownClass (%s)'%className\n self._addClassOrModuleLevelException(result,e,errorName)\n finally :\n _call_if_exists(result,'_restoreStdout')\n \n \nclass _ErrorHolder(object):\n ''\n\n\n\n \n \n \n \n \n failureException=None\n \n def __init__(self,description):\n self.description=description\n \n def id(self):\n return self.description\n \n def shortDescription(self):\n return None\n \n def __repr__(self):\n return \"<ErrorHolder description=%r>\"%(self.description,)\n \n def __str__(self):\n return self.id()\n \n def run(self,result):\n \n \n pass\n \n def __call__(self,result):\n return self.run(result)\n \n def countTestCases(self):\n return 0\n \ndef _isnotsuite(test):\n ''\n try :\n iter(test)\n except TypeError:\n return True\n return False\n \n \nclass _DebugResult(object):\n ''\n _previousTestClass=None\n _moduleSetUpFailed=False\n shouldStop=False\n", ["sys", "unittest", "unittest.case", "unittest.util"]], "importlib.abc": [".py", "''\nfrom . import _bootstrap\nfrom . import _bootstrap_external\nfrom . import machinery\ntry :\n import _frozen_importlib\nexcept ImportError as exc:\n if exc.name !='_frozen_importlib':\n raise\n _frozen_importlib=None\ntry :\n import _frozen_importlib_external\nexcept ImportError as exc:\n _frozen_importlib_external=_bootstrap_external\nimport abc\nimport warnings\n\n\ndef _register(abstract_cls,*classes):\n for cls in classes:\n abstract_cls.register(cls)\n if _frozen_importlib is not None :\n try :\n frozen_cls=getattr(_frozen_importlib,cls.__name__)\n except AttributeError:\n frozen_cls=getattr(_frozen_importlib_external,cls.__name__)\n abstract_cls.register(frozen_cls)\n \n \nclass Finder(metaclass=abc.ABCMeta):\n\n ''\n\n\n\n\n\n\n\n \n \n @abc.abstractmethod\n def find_module(self,fullname,path=None ):\n ''\n\n\n \n \n \nclass MetaPathFinder(Finder):\n\n ''\n \n \n \n \n def find_module(self,fullname,path):\n ''\n\n\n\n\n\n\n\n\n \n warnings.warn(\"MetaPathFinder.find_module() is deprecated since Python \"\n \"3.4 in favor of MetaPathFinder.find_spec()\"\n \"(available since 3.4)\",\n DeprecationWarning,\n stacklevel=2)\n if not hasattr(self,'find_spec'):\n return None\n found=self.find_spec(fullname,path)\n return found.loader if found is not None else None\n \n def invalidate_caches(self):\n ''\n\n \n \n_register(MetaPathFinder,machinery.BuiltinImporter,machinery.FrozenImporter,\nmachinery.PathFinder,machinery.WindowsRegistryFinder)\n\n\nclass PathEntryFinder(Finder):\n\n ''\n \n \n \n \n def find_loader(self,fullname):\n ''\n\n\n\n\n\n\n\n\n\n\n\n\n \n warnings.warn(\"PathEntryFinder.find_loader() is deprecated since Python \"\n \"3.4 in favor of PathEntryFinder.find_spec() \"\n \"(available since 3.4)\",\n DeprecationWarning,\n stacklevel=2)\n if not hasattr(self,'find_spec'):\n return None ,[]\n found=self.find_spec(fullname)\n if found is not None :\n if not found.submodule_search_locations:\n portions=[]\n else :\n portions=found.submodule_search_locations\n return found.loader,portions\n else :\n return None ,[]\n \n find_module=_bootstrap_external._find_module_shim\n \n def invalidate_caches(self):\n ''\n\n \n \n_register(PathEntryFinder,machinery.FileFinder)\n\n\nclass Loader(metaclass=abc.ABCMeta):\n\n ''\n \n def create_module(self,spec):\n ''\n\n\n\n\n \n \n return None\n \n \n \n \n def load_module(self,fullname):\n ''\n\n\n\n\n\n\n\n\n\n\n \n if not hasattr(self,'exec_module'):\n raise ImportError\n return _bootstrap._load_module_shim(self,fullname)\n \n def module_repr(self,module):\n ''\n\n\n\n\n\n\n \n \n raise NotImplementedError\n \n \nclass ResourceLoader(Loader):\n\n ''\n\n\n\n\n \n \n @abc.abstractmethod\n def get_data(self,path):\n ''\n \n raise OSError\n \n \nclass InspectLoader(Loader):\n\n ''\n\n\n\n\n \n \n def is_package(self,fullname):\n ''\n\n\n\n \n raise ImportError\n \n def get_code(self,fullname):\n ''\n\n\n\n\n\n \n source=self.get_source(fullname)\n if source is None :\n return None\n return self.source_to_code(source)\n \n @abc.abstractmethod\n def get_source(self,fullname):\n ''\n\n\n\n \n raise ImportError\n \n @staticmethod\n def source_to_code(data,path='<string>'):\n ''\n\n\n \n return compile(data,path,'exec',dont_inherit=True )\n \n exec_module=_bootstrap_external._LoaderBasics.exec_module\n load_module=_bootstrap_external._LoaderBasics.load_module\n \n_register(InspectLoader,machinery.BuiltinImporter,machinery.FrozenImporter)\n\n\nclass ExecutionLoader(InspectLoader):\n\n ''\n\n\n\n\n \n \n @abc.abstractmethod\n def get_filename(self,fullname):\n ''\n\n\n\n \n raise ImportError\n \n def get_code(self,fullname):\n ''\n\n\n\n \n source=self.get_source(fullname)\n if source is None :\n return None\n try :\n path=self.get_filename(fullname)\n except ImportError:\n return self.source_to_code(source)\n else :\n return self.source_to_code(source,path)\n \n_register(ExecutionLoader,machinery.ExtensionFileLoader)\n\n\nclass FileLoader(_bootstrap_external.FileLoader,ResourceLoader,ExecutionLoader):\n\n ''\n \n \n_register(FileLoader,machinery.SourceFileLoader,\nmachinery.SourcelessFileLoader)\n\n\nclass SourceLoader(_bootstrap_external.SourceLoader,ResourceLoader,ExecutionLoader):\n\n ''\n\n\n\n\n\n\n\n\n\n\n\n\n \n \n def path_mtime(self,path):\n ''\n if self.path_stats.__func__ is SourceLoader.path_stats:\n raise OSError\n return int(self.path_stats(path)['mtime'])\n \n def path_stats(self,path):\n ''\n\n\n\n\n \n if self.path_mtime.__func__ is SourceLoader.path_mtime:\n raise OSError\n return {'mtime':self.path_mtime(path)}\n \n def set_data(self,path,data):\n ''\n\n\n\n\n\n\n \n \n_register(SourceLoader,machinery.SourceFileLoader)\n\n\nclass ResourceReader(metaclass=abc.ABCMeta):\n\n ''\n\n\n\n\n \n \n @abc.abstractmethod\n def open_resource(self,resource):\n ''\n\n\n\n\n\n \n raise FileNotFoundError\n \n @abc.abstractmethod\n def resource_path(self,resource):\n ''\n\n\n\n\n\n\n \n raise FileNotFoundError\n \n @abc.abstractmethod\n def is_resource(self,name):\n ''\n raise FileNotFoundError\n \n @abc.abstractmethod\n def contents(self):\n ''\n return []\n \n \n_register(ResourceReader,machinery.SourceFileLoader)\n", ["_frozen_importlib", "_frozen_importlib_external", "abc", "importlib", "importlib._bootstrap", "importlib._bootstrap_external", "importlib.machinery", "warnings"]], "email.iterators": [".py", "\n\n\n\n\"\"\"Various types of useful iterators and generators.\"\"\"\n\n__all__=[\n'body_line_iterator',\n'typed_subpart_iterator',\n'walk',\n\n]\n\nimport sys\nfrom io import StringIO\n\n\n\n\ndef walk(self):\n ''\n\n\n\n \n yield self\n if self.is_multipart():\n for subpart in self.get_payload():\n yield from subpart.walk()\n \n \n \n \ndef body_line_iterator(msg,decode=False ):\n ''\n\n\n \n for subpart in msg.walk():\n payload=subpart.get_payload(decode=decode)\n if isinstance(payload,str):\n yield from StringIO(payload)\n \n \ndef typed_subpart_iterator(msg,maintype='text',subtype=None ):\n ''\n\n\n\n\n \n for subpart in msg.walk():\n if subpart.get_content_maintype()==maintype:\n if subtype is None or subpart.get_content_subtype()==subtype:\n yield subpart\n \n \n \ndef _structure(msg,fp=None ,level=0,include_default=False ):\n ''\n if fp is None :\n fp=sys.stdout\n tab=' '*(level *4)\n print(tab+msg.get_content_type(),end='',file=fp)\n if include_default:\n print(' [%s]'%msg.get_default_type(),file=fp)\n else :\n print(file=fp)\n if msg.is_multipart():\n for subpart in msg.get_payload():\n _structure(subpart,fp,level+1,include_default)\n", ["io", "sys"]], "py_compile": [".py", "''\n\n\n\n\nimport enum\nimport importlib._bootstrap_external\nimport importlib.machinery\nimport importlib.util\nimport os\nimport os.path\nimport sys\nimport traceback\n\n__all__=[\"compile\",\"main\",\"PyCompileError\",\"PycInvalidationMode\"]\n\n\nclass PyCompileError(Exception):\n ''\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n \n \n def __init__(self,exc_type,exc_value,file,msg=''):\n exc_type_name=exc_type.__name__\n if exc_type is SyntaxError:\n tbtext=''.join(traceback.format_exception_only(\n exc_type,exc_value))\n errmsg=tbtext.replace('File \"<string>\"','File \"%s\"'%file)\n else :\n errmsg=\"Sorry: %s: %s\"%(exc_type_name,exc_value)\n \n Exception.__init__(self,msg or errmsg,exc_type_name,exc_value,file)\n \n self.exc_type_name=exc_type_name\n self.exc_value=exc_value\n self.file=file\n self.msg=msg or errmsg\n \n def __str__(self):\n return self.msg\n \n \nclass PycInvalidationMode(enum.Enum):\n TIMESTAMP=1\n CHECKED_HASH=2\n UNCHECKED_HASH=3\n \n \ndef compile(file,cfile=None ,dfile=None ,doraise=False ,optimize=-1,\ninvalidation_mode=PycInvalidationMode.TIMESTAMP):\n ''\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n \n if os.environ.get('SOURCE_DATE_EPOCH'):\n invalidation_mode=PycInvalidationMode.CHECKED_HASH\n if cfile is None :\n if optimize >=0:\n optimization=optimize if optimize >=1 else ''\n cfile=importlib.util.cache_from_source(file,\n optimization=optimization)\n else :\n cfile=importlib.util.cache_from_source(file)\n if os.path.islink(cfile):\n msg=('{} is a symlink and will be changed into a regular file if '\n 'import writes a byte-compiled file to it')\n raise FileExistsError(msg.format(cfile))\n elif os.path.exists(cfile)and not os.path.isfile(cfile):\n msg=('{} is a non-regular file and will be changed into a regular '\n 'one if import writes a byte-compiled file to it')\n raise FileExistsError(msg.format(cfile))\n loader=importlib.machinery.SourceFileLoader('<py_compile>',file)\n source_bytes=loader.get_data(file)\n try :\n code=loader.source_to_code(source_bytes,dfile or file,\n _optimize=optimize)\n except Exception as err:\n py_exc=PyCompileError(err.__class__,err,dfile or file)\n if doraise:\n raise py_exc\n else :\n sys.stderr.write(py_exc.msg+'\\n')\n return\n try :\n dirname=os.path.dirname(cfile)\n if dirname:\n os.makedirs(dirname)\n except FileExistsError:\n pass\n if invalidation_mode ==PycInvalidationMode.TIMESTAMP:\n source_stats=loader.path_stats(file)\n bytecode=importlib._bootstrap_external._code_to_timestamp_pyc(\n code,source_stats['mtime'],source_stats['size'])\n else :\n source_hash=importlib.util.source_hash(source_bytes)\n bytecode=importlib._bootstrap_external._code_to_hash_pyc(\n code,\n source_hash,\n (invalidation_mode ==PycInvalidationMode.CHECKED_HASH),\n )\n mode=importlib._bootstrap_external._calc_mode(file)\n importlib._bootstrap_external._write_atomic(cfile,bytecode,mode)\n return cfile\n \n \ndef main(args=None ):\n ''\n\n\n\n\n\n\n\n\n \n if args is None :\n args=sys.argv[1:]\n rv=0\n if args ==['-']:\n while True :\n filename=sys.stdin.readline()\n if not filename:\n break\n filename=filename.rstrip('\\n')\n try :\n compile(filename,doraise=True )\n except PyCompileError as error:\n rv=1\n sys.stderr.write(\"%s\\n\"%error.msg)\n except OSError as error:\n rv=1\n sys.stderr.write(\"%s\\n\"%error)\n else :\n for filename in args:\n try :\n compile(filename,doraise=True )\n except PyCompileError as error:\n \n rv=1\n sys.stderr.write(\"%s\\n\"%error.msg)\n return rv\n \nif __name__ ==\"__main__\":\n sys.exit(main())\n", ["enum", "importlib._bootstrap_external", "importlib.machinery", "importlib.util", "os", "os.path", "sys", "traceback"]], "_struct": [".py", "\n\n\n\n\n\n\n\n\n\n\n\"\"\"Functions to convert between Python values and C structs.\nPython strings are used to hold the data representing the C struct\nand also as format strings to describe the layout of data in the C struct.\n\nThe optional first format char indicates byte order, size and alignment:\n @: native order, size & alignment (default)\n =: native order, std. size & alignment\n <: little-endian, std. size & alignment\n >: big-endian, std. size & alignment\n !: same as >\n\nThe remaining chars indicate types of args and must match exactly;\nthese can be preceded by a decimal repeat count:\n x: pad byte (no data);\n c:char;\n b:signed byte;\n B:unsigned byte;\n h:short;\n H:unsigned short;\n i:int;\n I:unsigned int;\n l:long;\n L:unsigned long;\n f:float;\n d:double.\nSpecial cases (preceding decimal count indicates length):\n s:string (array of char); p: pascal string (with count byte).\nSpecial case (only available in native format):\n P:an integer type that is wide enough to hold a pointer.\nSpecial case (not in native mode unless 'long long' in platform C):\n q:long long;\n Q:unsigned long long\nWhitespace between formats is ignored.\n\nThe variable struct.error is an exception raised on errors.\"\"\"\n\nimport math\nimport re\nimport sys\n\n\nclass StructError(Exception):\n pass\n \n \nerror=StructError\n\ndef _normalize(fmt):\n ''\n \n if re.search(r\"\\d\\s+\",fmt):\n raise StructError(\"bad char in struct format\")\n return fmt.replace(\" \",\"\")\n \ndef unpack_int(data,index,size,le):\n bytes=[b for b in data[index:index+size]]\n if le =='little':\n bytes.reverse()\n number=0\n for b in bytes:\n number=number <<8 |b\n return int(number)\n \ndef unpack_signed_int(data,index,size,le):\n number=unpack_int(data,index,size,le)\n max=2 **(size *8)\n if number >2 **(size *8 -1)-1:\n number=int(-1 *(max -number))\n return number\n \nINFINITY=1e200 *1e200\nNAN=INFINITY /INFINITY\n\ndef unpack_char(data,index,size,le):\n return data[index:index+size]\n \ndef pack_int(number,size,le):\n x=number\n res=[]\n for i in range(size):\n res.append(x&0xff)\n x >>=8\n if le =='big':\n res.reverse()\n return bytes(res)\n \ndef pack_signed_int(number,size,le):\n if not isinstance(number,int):\n raise StructError(\"argument for i,I,l,L,q,Q,h,H must be integer\")\n if number >2 **(8 *size -1)-1 or number <-1 *2 **(8 *size -1):\n raise OverflowError(\"Number:%i too large to convert\"%number)\n return pack_int(number,size,le)\n \ndef pack_unsigned_int(number,size,le):\n if not isinstance(number,int):\n raise StructError(\"argument for i,I,l,L,q,Q,h,H must be integer\")\n if number <0:\n raise TypeError(\"can't convert negative long to unsigned\")\n if number >2 **(8 *size)-1:\n raise OverflowError(\"Number:%i too large to convert\"%number)\n return pack_int(number,size,le)\n \ndef pack_char(char,size,le):\n return bytes(char)\n \ndef isinf(x):\n return x !=0.0 and x /2 ==x\n \ndef isnan(v):\n return v !=v *1.0 or (v ==1.0 and v ==2.0)\n \ndef pack_float(x,size,le):\n unsigned=float_pack(x,size)\n result=[]\n for i in range(size):\n result.append((unsigned >>(i *8))&0xFF)\n if le ==\"big\":\n result.reverse()\n return bytes(result)\n \ndef unpack_float(data,index,size,le):\n binary=[data[i]for i in range(index,index+size)]\n if le ==\"big\":\n binary.reverse()\n unsigned=0\n for i in range(size):\n unsigned |=binary[i]<<(i *8)\n return float_unpack(unsigned,size,le)\n \ndef round_to_nearest(x):\n ''\n\n\n\n\n\n\n\n\n \n int_part=int(x)\n frac_part=x -int_part\n if frac_part >0.5 or frac_part ==0.5 and int_part&1 ==1:\n int_part +=1\n return int_part\n \ndef float_unpack(Q,size,le):\n ''\n \n \n if size ==8:\n MIN_EXP=-1021\n MAX_EXP=1024\n MANT_DIG=53\n BITS=64\n elif size ==4:\n MIN_EXP=-125\n MAX_EXP=128\n MANT_DIG=24\n BITS=32\n else :\n raise ValueError(\"invalid size value\")\n \n if Q >>BITS:\n raise ValueError(\"input out of range\")\n \n \n sign=Q >>BITS -1\n exp=(Q&((1 <<BITS -1)-(1 <<MANT_DIG -1)))>>MANT_DIG -1\n mant=Q&((1 <<MANT_DIG -1)-1)\n \n if exp ==MAX_EXP -MIN_EXP+2:\n \n result=float('nan')if mant else float('inf')\n elif exp ==0:\n \n result=math.ldexp(float(mant),MIN_EXP -MANT_DIG)\n else :\n \n mant +=1 <<MANT_DIG -1\n result=math.ldexp(float(mant),exp+MIN_EXP -MANT_DIG -1)\n return -result if sign else result\n \n \ndef float_pack(x,size):\n ''\n \n \n if size ==8:\n MIN_EXP=-1021\n MAX_EXP=1024\n MANT_DIG=53\n BITS=64\n elif size ==4:\n MIN_EXP=-125\n MAX_EXP=128\n MANT_DIG=24\n BITS=32\n else :\n raise ValueError(\"invalid size value\")\n \n sign=math.copysign(1.0,x)<0.0\n if math.isinf(x):\n mant=0\n exp=MAX_EXP -MIN_EXP+2\n elif math.isnan(x):\n mant=1 <<(MANT_DIG -2)\n exp=MAX_EXP -MIN_EXP+2\n elif x ==0.0:\n mant=0\n exp=0\n else :\n m,e=math.frexp(abs(x))\n exp=e -(MIN_EXP -1)\n if exp >0:\n \n mant=round_to_nearest(m *(1 <<MANT_DIG))\n mant -=1 <<MANT_DIG -1\n else :\n \n if exp+MANT_DIG -1 >=0:\n mant=round_to_nearest(m *(1 <<exp+MANT_DIG -1))\n else :\n mant=0\n exp=0\n \n \n assert 0 <=mant <=1 <<MANT_DIG -1\n if mant ==1 <<MANT_DIG -1:\n mant=0\n exp +=1\n \n \n \n if exp >=MAX_EXP -MIN_EXP+2:\n raise OverflowError(\"float too large to pack in this format\")\n \n \n assert 0 <=mant <1 <<MANT_DIG -1\n assert 0 <=exp <=MAX_EXP -MIN_EXP+2\n assert 0 <=sign <=1\n return ((sign <<BITS -1)|(exp <<MANT_DIG -1))|mant\n \n \nbig_endian_format={\n'x':{'size':1,'alignment':0,'pack':None ,'unpack':None },\n'b':{'size':1,'alignment':0,'pack':pack_signed_int,'unpack':unpack_signed_int},\n'B':{'size':1,'alignment':0,'pack':pack_unsigned_int,'unpack':unpack_int},\n'c':{'size':1,'alignment':0,'pack':pack_char,'unpack':unpack_char},\n's':{'size':1,'alignment':0,'pack':None ,'unpack':None },\n'p':{'size':1,'alignment':0,'pack':None ,'unpack':None },\n'h':{'size':2,'alignment':0,'pack':pack_signed_int,'unpack':unpack_signed_int},\n'H':{'size':2,'alignment':0,'pack':pack_unsigned_int,'unpack':unpack_int},\n'i':{'size':4,'alignment':0,'pack':pack_signed_int,'unpack':unpack_signed_int},\n'I':{'size':4,'alignment':0,'pack':pack_unsigned_int,'unpack':unpack_int},\n'l':{'size':4,'alignment':0,'pack':pack_signed_int,'unpack':unpack_signed_int},\n'L':{'size':4,'alignment':0,'pack':pack_unsigned_int,'unpack':unpack_int},\n'q':{'size':8,'alignment':0,'pack':pack_signed_int,'unpack':unpack_signed_int},\n'Q':{'size':8,'alignment':0,'pack':pack_unsigned_int,'unpack':unpack_int},\n'f':{'size':4,'alignment':0,'pack':pack_float,'unpack':unpack_float},\n'd':{'size':8,'alignment':0,'pack':pack_float,'unpack':unpack_float},\n}\n\ndefault=big_endian_format\n\nformatmode={'<':(default,'little'),\n'>':(default,'big'),\n'!':(default,'big'),\n'=':(default,sys.byteorder),\n'@':(default,sys.byteorder)\n}\n\ndef _getmode(fmt):\n try :\n formatdef,endianness=formatmode[fmt[0]]\n alignment=fmt[0]not in formatmode or fmt[0]=='@'\n index=1\n except (IndexError,KeyError):\n formatdef,endianness=formatmode['@']\n alignment=True\n index=0\n return formatdef,endianness,index,alignment\n \ndef _getnum(fmt,i):\n num=None\n cur=fmt[i]\n while ('0'<=cur)and (cur <='9'):\n if num ==None :\n num=int(cur)\n else :\n num=10 *num+int(cur)\n i +=1\n cur=fmt[i]\n return num,i\n \ndef calcsize(fmt):\n ''\n\n \n if isinstance(fmt,bytes):\n fmt=fmt.decode(\"ascii\")\n \n fmt=_normalize(fmt)\n \n formatdef,endianness,i,alignment=_getmode(fmt)\n num=0\n result=0\n while i <len(fmt):\n num,i=_getnum(fmt,i)\n cur=fmt[i]\n try :\n format=formatdef[cur]\n except KeyError:\n raise StructError(\"%s is not a valid format\"%cur)\n if num !=None :\n result +=num *format['size']\n else :\n \n \n if alignment and result:\n result +=format['size']-result %format['size']\n result +=format['size']\n num=0\n i +=1\n return result\n \ndef pack(fmt,*args):\n ''\n\n \n fmt=_normalize(fmt)\n formatdef,endianness,i,alignment=_getmode(fmt)\n args=list(args)\n n_args=len(args)\n result=[]\n while i <len(fmt):\n num,i=_getnum(fmt,i)\n cur=fmt[i]\n try :\n format=formatdef[cur]\n except KeyError:\n raise StructError(\"%s is not a valid format\"%cur)\n if num ==None :\n num_s=0\n num=1\n else :\n num_s=num\n \n if cur =='x':\n result +=[b'\\0'*num]\n elif cur =='s':\n if isinstance(args[0],bytes):\n padding=num -len(args[0])\n result +=[args[0][:num]+b'\\0'*padding]\n args.pop(0)\n else :\n raise StructError(\"arg for string format not a string\")\n elif cur =='p':\n if isinstance(args[0],bytes):\n padding=num -len(args[0])-1\n \n if padding >0:\n result +=[bytes([len(args[0])])+args[0][:num -1]+\n b'\\0'*padding]\n else :\n if num <255:\n result +=[bytes([num -1])+args[0][:num -1]]\n else :\n result +=[bytes([255])+args[0][:num -1]]\n args.pop(0)\n else :\n raise StructError(\"arg for string format not a string\")\n \n else :\n if len(args)<num:\n raise StructError(\"insufficient arguments to pack\")\n for var in args[:num]:\n \n if len(result)and alignment:\n padding=format['size']-len(result)%format['size']\n result +=[bytes([0])]*padding\n result +=[format['pack'](var,format['size'],endianness)]\n args=args[num:]\n num=None\n i +=1\n if len(args)!=0:\n raise StructError(\"too many arguments for pack format\")\n return b''.join(result)\n \ndef unpack(fmt,data):\n ''\n\n\n \n fmt=_normalize(fmt)\n formatdef,endianness,i,alignment=_getmode(fmt)\n j=0\n num=0\n result=[]\n length=calcsize(fmt)\n if length !=len(data):\n raise StructError(\"unpack str size does not match format\")\n while i <len(fmt):\n num,i=_getnum(fmt,i)\n cur=fmt[i]\n i +=1\n try :\n format=formatdef[cur]\n except KeyError:\n raise StructError(\"%s is not a valid format\"%cur)\n \n if not num:\n num=1\n \n if cur =='x':\n j +=num\n elif cur =='s':\n result.append(data[j:j+num])\n j +=num\n elif cur =='p':\n n=data[j]\n if n >=num:\n n=num -1\n result.append(data[j+1:j+n+1])\n j +=num\n else :\n \n if j >0 and alignment:\n padding=format['size']-j %format['size']\n j +=padding\n for n in range(num):\n result +=[format['unpack'](data,j,format['size'],\n endianness)]\n j +=format['size']\n \n return tuple(result)\n \ndef pack_into(fmt,buf,offset,*args):\n data=pack(fmt,*args)\n buf[offset:offset+len(data)]=data\n \ndef unpack_from(fmt,buf,offset=0):\n size=calcsize(fmt)\n data=buf[offset:offset+size]\n if len(data)!=size:\n raise error(\"unpack_from requires a buffer of at least %d bytes\"\n %(size,))\n return unpack(fmt,data)\n \ndef _clearcache():\n ''\n \n \nclass Struct:\n\n def __init__(self,fmt):\n self.format=fmt\n \n def pack(self,*args):\n return pack(self.format,*args)\n \n def pack_into(self,*args):\n return pack_into(self.format,*args)\n \n def unpack(self,*args):\n return unpack(self.format,*args)\n \n def unpack_from(self,*args):\n return unpack_from(self.format,*args)\n \nif __name__ =='__main__':\n t=pack('Bf',1,2)\n print(t,len(t))\n print(unpack('Bf',t))\n print(calcsize('Bf'))\n \n", ["math", "re", "sys"]], "traceback": [".py", "''\n\nimport collections\nimport itertools\nimport linecache\nimport sys\n\n__all__=['extract_stack','extract_tb','format_exception',\n'format_exception_only','format_list','format_stack',\n'format_tb','print_exc','format_exc','print_exception',\n'print_last','print_stack','print_tb','clear_frames',\n'FrameSummary','StackSummary','TracebackException',\n'walk_stack','walk_tb']\n\n\n\n\n\ndef print_list(extracted_list,file=None ):\n ''\n \n if file is None :\n file=sys.stderr\n for item in StackSummary.from_list(extracted_list).format():\n print(item,file=file,end=\"\")\n \ndef format_list(extracted_list):\n ''\n\n\n\n\n\n\n\n \n return StackSummary.from_list(extracted_list).format()\n \n \n \n \n \ndef print_tb(tb,limit=None ,file=None ):\n ''\n\n\n\n\n\n \n print_list(extract_tb(tb,limit=limit),file=file)\n \ndef format_tb(tb,limit=None ):\n ''\n return extract_tb(tb,limit=limit).format()\n \ndef extract_tb(tb,limit=None ):\n ''\n\n\n\n\n\n\n\n\n \n return StackSummary.extract(walk_tb(tb),limit=limit)\n \n \n \n \n \n_cause_message=(\n\"\\nThe above exception was the direct cause \"\n\"of the following exception:\\n\\n\")\n\n_context_message=(\n\"\\nDuring handling of the above exception, \"\n\"another exception occurred:\\n\\n\")\n\n\ndef print_exception(etype,value,tb,limit=None ,file=None ,chain=True ):\n ''\n\n\n\n\n\n\n\n\n \n \n \n \n if file is None :\n file=sys.stderr\n for line in TracebackException(\n type(value),value,tb,limit=limit).format(chain=chain):\n print(line,file=file,end=\"\")\n \n \ndef format_exception(etype,value,tb,limit=None ,chain=True ):\n ''\n\n\n\n\n\n\n \n \n \n \n return list(TracebackException(\n type(value),value,tb,limit=limit).format(chain=chain))\n \n \ndef format_exception_only(etype,value):\n ''\n\n\n\n\n\n\n\n\n\n\n\n\n\n \n return list(TracebackException(etype,value,None ).format_exception_only())\n \n \n \n \ndef _format_final_exc_line(etype,value):\n valuestr=_some_str(value)\n if value is None or not valuestr:\n line=\"%s\\n\"%etype\n else :\n line=\"%s: %s\\n\"%(etype,valuestr)\n return line\n \ndef _some_str(value):\n try :\n return str(value)\n except :\n return '<unprintable %s object>'%type(value).__name__\n \n \n \ndef print_exc(limit=None ,file=None ,chain=True ):\n ''\n print_exception(*sys.exc_info(),limit=limit,file=file,chain=chain)\n \ndef format_exc(limit=None ,chain=True ):\n ''\n return \"\".join(format_exception(*sys.exc_info(),limit=limit,chain=chain))\n \ndef print_last(limit=None ,file=None ,chain=True ):\n ''\n \n if not hasattr(sys,\"last_type\"):\n raise ValueError(\"no last exception\")\n print_exception(sys.last_type,sys.last_value,sys.last_traceback,\n limit,file,chain)\n \n \n \n \n \ndef print_stack(f=None ,limit=None ,file=None ):\n ''\n\n\n\n\n \n if f is None :\n f=sys._getframe().f_back\n print_list(extract_stack(f,limit=limit),file=file)\n \n \ndef format_stack(f=None ,limit=None ):\n ''\n if f is None :\n f=sys._getframe().f_back\n return format_list(extract_stack(f,limit=limit))\n \n \ndef extract_stack(f=None ,limit=None ):\n ''\n\n\n\n\n\n\n \n if f is None :\n f=sys._getframe().f_back\n stack=StackSummary.extract(walk_stack(f),limit=limit)\n stack.reverse()\n return stack\n \n \ndef clear_frames(tb):\n ''\n while tb is not None :\n try :\n tb.tb_frame.clear()\n except RuntimeError:\n \n pass\n tb=tb.tb_next\n \n \nclass FrameSummary:\n ''\n\n\n\n\n\n\n\n\n\n\n \n \n __slots__=('filename','lineno','name','_line','locals')\n \n def __init__(self,filename,lineno,name,*,lookup_line=True ,\n locals=None ,line=None ):\n ''\n\n\n\n\n\n\n\n \n self.filename=filename\n self.lineno=lineno\n self.name=name\n self._line=line\n if lookup_line:\n self.line\n self.locals={k:repr(v)for k,v in locals.items()}if locals else None\n \n def __eq__(self,other):\n if isinstance(other,FrameSummary):\n return (self.filename ==other.filename and\n self.lineno ==other.lineno and\n self.name ==other.name and\n self.locals ==other.locals)\n if isinstance(other,tuple):\n return (self.filename,self.lineno,self.name,self.line)==other\n return NotImplemented\n \n def __getitem__(self,pos):\n return (self.filename,self.lineno,self.name,self.line)[pos]\n \n def __iter__(self):\n return iter([self.filename,self.lineno,self.name,self.line])\n \n def __repr__(self):\n return \"<FrameSummary file {filename}, line {lineno} in {name}>\".format(\n filename=self.filename,lineno=self.lineno,name=self.name)\n \n @property\n def line(self):\n if self._line is None :\n self._line=linecache.getline(self.filename,self.lineno).strip()\n return self._line\n \n \ndef walk_stack(f):\n ''\n\n\n\n \n if f is None :\n f=sys._getframe().f_back.f_back\n while f is not None :\n yield f,f.f_lineno\n f=f.f_back\n \n \ndef walk_tb(tb):\n ''\n\n\n\n \n while tb is not None :\n yield tb.tb_frame,tb.tb_lineno\n tb=tb.tb_next\n \n \nclass StackSummary(list):\n ''\n \n @classmethod\n def extract(klass,frame_gen,*,limit=None ,lookup_lines=True ,\n capture_locals=False ):\n ''\n\n\n\n\n\n\n\n\n\n \n if limit is None :\n limit=getattr(sys,'tracebacklimit',None )\n if limit is not None and limit <0:\n limit=0\n if limit is not None :\n if limit >=0:\n frame_gen=itertools.islice(frame_gen,limit)\n else :\n frame_gen=collections.deque(frame_gen,maxlen=-limit)\n \n result=klass()\n fnames=set()\n for f,lineno in frame_gen:\n co=f.f_code\n filename=co.co_filename\n name=co.co_name\n \n fnames.add(filename)\n linecache.lazycache(filename,f.f_globals)\n \n if capture_locals:\n f_locals=f.f_locals\n else :\n f_locals=None\n result.append(FrameSummary(\n filename,lineno,name,lookup_line=False ,locals=f_locals))\n for filename in fnames:\n linecache.checkcache(filename)\n \n if lookup_lines:\n for f in result:\n f.line\n return result\n \n @classmethod\n def from_list(klass,a_list):\n ''\n\n\n\n \n \n \n \n \n result=StackSummary()\n for frame in a_list:\n if isinstance(frame,FrameSummary):\n result.append(frame)\n else :\n filename,lineno,name,line=frame\n result.append(FrameSummary(filename,lineno,name,line=line))\n return result\n \n def format(self):\n ''\n\n\n\n\n\n\n\n\n\n \n result=[]\n last_file=None\n last_line=None\n last_name=None\n count=0\n for frame in self:\n if (last_file is not None and last_file ==frame.filename and\n last_line is not None and last_line ==frame.lineno and\n last_name is not None and last_name ==frame.name):\n count +=1\n else :\n if count >3:\n result.append(f' [Previous line repeated {count-3} more times]\\n')\n last_file=frame.filename\n last_line=frame.lineno\n last_name=frame.name\n count=0\n if count >=3:\n continue\n row=[]\n row.append(' File \"{}\", line {}, in {}\\n'.format(\n frame.filename,frame.lineno,frame.name))\n if frame.line:\n row.append(' {}\\n'.format(frame.line.strip()))\n if frame.locals:\n for name,value in sorted(frame.locals.items()):\n row.append(' {name} = {value}\\n'.format(name=name,value=value))\n result.append(''.join(row))\n if count >3:\n result.append(f' [Previous line repeated {count-3} more times]\\n')\n return result\n \n \nclass TracebackException:\n ''\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n \n \n def __init__(self,exc_type,exc_value,exc_traceback,*,limit=None ,\n lookup_lines=True ,capture_locals=False ,_seen=None ):\n \n \n \n \n if _seen is None :\n _seen=set()\n _seen.add(id(exc_value))\n \n \n if (exc_value and exc_value.__cause__ is not None\n and id(exc_value.__cause__)not in _seen):\n cause=TracebackException(\n type(exc_value.__cause__),\n exc_value.__cause__,\n exc_value.__cause__.__traceback__,\n limit=limit,\n lookup_lines=False ,\n capture_locals=capture_locals,\n _seen=_seen)\n else :\n cause=None\n if (exc_value and exc_value.__context__ is not None\n and id(exc_value.__context__)not in _seen):\n context=TracebackException(\n type(exc_value.__context__),\n exc_value.__context__,\n exc_value.__context__.__traceback__,\n limit=limit,\n lookup_lines=False ,\n capture_locals=capture_locals,\n _seen=_seen)\n else :\n context=None\n self.exc_traceback=exc_traceback\n self.__cause__=cause\n self.__context__=context\n self.__suppress_context__=\\\n exc_value.__suppress_context__ if exc_value else False\n \n self.stack=StackSummary.extract(\n walk_tb(exc_traceback),limit=limit,lookup_lines=lookup_lines,\n capture_locals=capture_locals)\n self.exc_type=exc_type\n \n \n self._str=_some_str(exc_value)\n if exc_type and issubclass(exc_type,SyntaxError):\n \n self.filename=exc_value.filename\n self.lineno=str(exc_value.lineno)\n self.text=exc_value.text\n self.offset=exc_value.offset\n self.msg=exc_value.msg\n if lookup_lines:\n self._load_lines()\n \n @classmethod\n def from_exception(cls,exc,*args,**kwargs):\n ''\n return cls(type(exc),exc,exc.__traceback__,*args,**kwargs)\n \n def _load_lines(self):\n ''\n for frame in self.stack:\n frame.line\n if self.__context__:\n self.__context__._load_lines()\n if self.__cause__:\n self.__cause__._load_lines()\n \n def __eq__(self,other):\n return self.__dict__ ==other.__dict__\n \n def __str__(self):\n return self._str\n \n def format_exception_only(self):\n ''\n\n\n\n\n\n\n\n\n\n\n \n if self.exc_type is None :\n yield _format_final_exc_line(None ,self._str)\n return\n \n stype=self.exc_type.__qualname__\n smod=self.exc_type.__module__\n if smod not in (\"__main__\",\"builtins\"):\n stype=smod+'.'+stype\n \n if not issubclass(self.exc_type,SyntaxError):\n yield _format_final_exc_line(stype,self._str)\n return\n \n \n filename=self.filename or \"<string>\"\n lineno=str(self.lineno)or '?'\n yield ' File \"{}\", line {}\\n'.format(filename,lineno)\n \n badline=self.text\n offset=self.offset\n if badline is not None :\n yield ' {}\\n'.format(badline.strip())\n if offset is not None :\n caretspace=badline.rstrip('\\n')\n offset=min(len(caretspace),offset)-1\n caretspace=caretspace[:offset].lstrip()\n \n caretspace=((c.isspace()and c or ' ')for c in caretspace)\n yield ' {}^\\n'.format(''.join(caretspace))\n msg=self.msg or \"<no detail available>\"\n yield \"{}: {}\\n\".format(stype,msg)\n \n def format(self,*,chain=True ):\n ''\n\n\n\n\n\n\n\n\n\n \n if chain:\n if self.__cause__ is not None :\n yield from self.__cause__.format(chain=chain)\n yield _cause_message\n elif (self.__context__ is not None and\n not self.__suppress_context__):\n yield from self.__context__.format(chain=chain)\n yield _context_message\n if self.exc_traceback is not None :\n yield 'Traceback (most recent call last):\\n'\n yield from self.stack.format()\n yield from self.format_exception_only()\n", ["collections", "itertools", "linecache", "sys"]], "_sre": [".py", "\n''\n\n\n\n\n\n\n\nMAXREPEAT=2147483648\nMAXGROUPS=2147483647\n\nimport array\nimport operator,sys\nfrom sre_constants import ATCODES,OPCODES,CHCODES\nfrom sre_constants import SRE_INFO_PREFIX,SRE_INFO_LITERAL\nfrom sre_constants import SRE_FLAG_UNICODE,SRE_FLAG_LOCALE\n\n\nfrom _sre_utils import (unicode_iscased,ascii_iscased,unicode_tolower,\nascii_tolower)\n\nimport sys\n\n\n\nMAGIC=20031017\n\n\n\n\n\n\n\n\n\n\n\n\n\nCODESIZE=4\n\ncopyright=\"_sre.py 2.4c Copyright 2005 by Nik Haldimann\"\n\n\ndef getcodesize():\n return CODESIZE\n \ndef compile(pattern,flags,code,groups=0,groupindex={},indexgroup=[None ]):\n ''\n \n return SRE_Pattern(pattern,flags,code,groups,groupindex,indexgroup)\n \ndef getlower(char_ord,flags):\n if (char_ord <128)or (flags&SRE_FLAG_UNICODE)\\\n or (flags&SRE_FLAG_LOCALE and char_ord <256):\n \n return ord(chr(char_ord).lower())\n else :\n return char_ord\n \n \nclass SRE_Pattern:\n\n def __init__(self,pattern,flags,code,groups=0,groupindex={},indexgroup=[None ]):\n self.pattern=pattern\n self.flags=flags\n self.groups=groups\n self.groupindex=groupindex\n self._indexgroup=indexgroup\n self._code=code\n \n def match(self,string,pos=0,endpos=sys.maxsize):\n ''\n\n \n state=_State(string,pos,endpos,self.flags)\n if state.match(self._code):\n return SRE_Match(self,state)\n return None\n \n def search(self,string,pos=0,endpos=sys.maxsize):\n ''\n\n\n \n state=_State(string,pos,endpos,self.flags)\n if state.search(self._code):\n return SRE_Match(self,state)\n else :\n return None\n \n def findall(self,string,pos=0,endpos=sys.maxsize):\n ''\n matchlist=[]\n state=_State(string,pos,endpos,self.flags)\n while state.start <=state.end:\n state.reset()\n state.string_position=state.start\n if not state.search(self._code):\n break\n match=SRE_Match(self,state)\n if self.groups ==0 or self.groups ==1:\n item=match.group(self.groups)\n else :\n item=match.groups(\"\")\n matchlist.append(item)\n if state.string_position ==state.start:\n state.start +=1\n else :\n state.start=state.string_position\n return matchlist\n \n def _subx(self,template,string,count=0,subn=False ):\n filter=template\n if not callable(template)and \"\\\\\"in template:\n \n \n \n \n import re as sre\n filter=sre._subx(self,template)\n state=_State(string,0,sys.maxsize,self.flags)\n sublist=[]\n \n n=last_pos=0\n while not count or n <count:\n state.reset()\n state.string_position=state.start\n if not state.search(self._code):\n break\n if last_pos <state.start:\n sublist.append(string[last_pos:state.start])\n if not (last_pos ==state.start and\n last_pos ==state.string_position and n >0):\n \n if callable(filter):\n sublist.append(filter(SRE_Match(self,state)))\n else :\n sublist.append(filter)\n last_pos=state.string_position\n n +=1\n if state.string_position ==state.start:\n state.start +=1\n else :\n state.start=state.string_position\n \n if last_pos <state.end:\n sublist.append(string[last_pos:state.end])\n item=\"\".join(sublist)\n if subn:\n return item,n\n else :\n return item\n \n def sub(self,repl,string,count=0):\n ''\n \n return self._subx(repl,string,count,False )\n \n def subn(self,repl,string,count=0):\n ''\n\n \n return self._subx(repl,string,count,True )\n \n def split(self,string,maxsplit=0):\n ''\n splitlist=[]\n state=_State(string,0,sys.maxsize,self.flags)\n n=0\n last=state.start\n while not maxsplit or n <maxsplit:\n state.reset()\n state.string_position=state.start\n if not state.search(self._code):\n break\n if state.start ==state.string_position:\n if last ==state.end:\n break\n state.start +=1\n continue\n splitlist.append(string[last:state.start])\n \n if self.groups:\n match=SRE_Match(self,state)\n splitlist.extend(list(match.groups(None )))\n n +=1\n last=state.start=state.string_position\n splitlist.append(string[last:state.end])\n return splitlist\n \n def finditer(self,string,pos=0,endpos=sys.maxsize):\n ''\n \n _list=[]\n _m=self.scanner(string,pos,endpos)\n _re=SRE_Scanner(self,string,pos,endpos)\n _m=_re.search()\n while _m:\n _list.append(_m)\n _m=_re.search()\n return _list\n \n \n def scanner(self,string,start=0,end=sys.maxsize):\n return SRE_Scanner(self,string,start,end)\n \n def __copy__(self):\n raise TypeError(\"cannot copy this pattern object\")\n \n def __deepcopy__(self):\n raise TypeError(\"cannot copy this pattern object\")\n \nclass SRE_Scanner:\n ''\n \n def __init__(self,pattern,string,start,end):\n self.pattern=pattern\n self._state=_State(string,start,end,self.pattern.flags)\n \n def _match_search(self,matcher):\n state=self._state\n state.reset()\n state.string_position=state.start\n match=None\n if matcher(self.pattern._code):\n match=SRE_Match(self.pattern,state)\n if match is None or state.string_position ==state.start:\n state.start +=1\n else :\n state.start=state.string_position\n return match\n \n def match(self):\n return self._match_search(self._state.match)\n \n def search(self):\n return self._match_search(self._state.search)\n \nclass SRE_Match:\n\n def __init__(self,pattern,state):\n self.re=pattern\n self.string=state.string\n self.pos=state.pos\n self.endpos=state.end\n self.lastindex=state.lastindex\n if self.lastindex <0:\n self.lastindex=None\n self.regs=self._create_regs(state)\n \n \n \n if self.lastindex is not None and pattern._indexgroup and 0 <=self.lastindex <len(pattern._indexgroup):\n \n \n \n \n \n self.lastgroup=pattern._indexgroup[self.lastindex]\n else :\n self.lastgroup=None\n \n def _create_regs(self,state):\n ''\n regs=[(state.start,state.string_position)]\n for group in range(self.re.groups):\n mark_index=2 *group\n if mark_index+1 <len(state.marks)\\\n and state.marks[mark_index]is not None\\\n and state.marks[mark_index+1]is not None :\n regs.append((state.marks[mark_index],state.marks[mark_index+1]))\n else :\n regs.append((-1,-1))\n return tuple(regs)\n \n def _get_index(self,group):\n if isinstance(group,int):\n if group >=0 and group <=self.re.groups:\n return group\n else :\n if group in self.re.groupindex:\n return self.re.groupindex[group]\n raise IndexError(\"no such group\")\n \n def _get_slice(self,group,default):\n group_indices=self.regs[group]\n if group_indices[0]>=0:\n return self.string[group_indices[0]:group_indices[1]]\n else :\n return default\n \n def start(self,group=0):\n ''\n\n \n return self.regs[self._get_index(group)][0]\n \n def end(self,group=0):\n ''\n\n \n return self.regs[self._get_index(group)][1]\n \n def span(self,group=0):\n ''\n return self.start(group),self.end(group)\n \n def expand(self,template):\n ''\n \n import sre\n return sre._expand(self.re,self,template)\n \n def groups(self,default=None ):\n ''\n\n \n groups=[]\n for indices in self.regs[1:]:\n if indices[0]>=0:\n groups.append(self.string[indices[0]:indices[1]])\n else :\n groups.append(default)\n return tuple(groups)\n \n def groupdict(self,default=None ):\n ''\n\n \n groupdict={}\n for key,value in self.re.groupindex.items():\n groupdict[key]=self._get_slice(value,default)\n return groupdict\n \n def group(self,*args):\n ''\n \n if len(args)==0:\n args=(0,)\n grouplist=[]\n for group in args:\n grouplist.append(self._get_slice(self._get_index(group),None ))\n if len(grouplist)==1:\n return grouplist[0]\n else :\n return tuple(grouplist)\n \n def __copy__():\n raise TypeError(\"cannot copy this pattern object\")\n \n def __deepcopy__():\n raise TypeError(\"cannot copy this pattern object\")\n \n \nclass _State:\n\n def __init__(self,string,start,end,flags):\n if isinstance(string,bytearray):\n string=str(bytes(string),\"latin1\")\n if isinstance(string,bytes):\n string=str(string,\"latin1\")\n self.string=string\n if start <0:\n start=0\n if end >len(string):\n end=len(string)\n self.start=start\n self.string_position=self.start\n self.end=end\n self.pos=start\n self.flags=flags\n self.reset()\n \n def reset(self):\n self.marks=[]\n self.lastindex=-1\n self.marks_stack=[]\n self.context_stack=[]\n self.repeat=None\n \n def match(self,pattern_codes):\n \n \n \n \n \n \n \n \n dispatcher=_OpcodeDispatcher()\n self.context_stack.append(_MatchContext(self,pattern_codes))\n has_matched=None\n while len(self.context_stack)>0:\n context=self.context_stack[-1]\n has_matched=dispatcher.match(context)\n if has_matched is not None :\n self.context_stack.pop()\n return has_matched\n \n def search(self,pattern_codes):\n flags=0\n if OPCODES[pattern_codes[0]].name ==\"info\":\n \n \n if pattern_codes[2]&SRE_INFO_PREFIX and pattern_codes[5]>1:\n return self.fast_search(pattern_codes)\n flags=pattern_codes[2]\n pattern_codes=pattern_codes[pattern_codes[1]+1:]\n \n string_position=self.start\n if OPCODES[pattern_codes[0]].name ==\"literal\":\n \n \n character=pattern_codes[1]\n while True :\n while string_position <self.end\\\n and ord(self.string[string_position])!=character:\n string_position +=1\n if string_position >=self.end:\n return False\n self.start=string_position\n string_position +=1\n self.string_position=string_position\n if flags&SRE_INFO_LITERAL:\n return True\n if self.match(pattern_codes[2:]):\n return True\n return False\n \n \n while string_position <=self.end:\n self.reset()\n self.start=self.string_position=string_position\n if self.match(pattern_codes):\n return True\n string_position +=1\n return False\n \n def fast_search(self,pattern_codes):\n ''\n \n \n \n flags=pattern_codes[2]\n prefix_len=pattern_codes[5]\n prefix_skip=pattern_codes[6]\n prefix=pattern_codes[7:7+prefix_len]\n overlap=pattern_codes[7+prefix_len -1:pattern_codes[1]+1]\n pattern_codes=pattern_codes[pattern_codes[1]+1:]\n i=0\n string_position=self.string_position\n while string_position <self.end:\n while True :\n if ord(self.string[string_position])!=prefix[i]:\n if i ==0:\n break\n else :\n i=overlap[i]\n else :\n i +=1\n if i ==prefix_len:\n \n self.start=string_position+1 -prefix_len\n self.string_position=string_position+1\\\n -prefix_len+prefix_skip\n if flags&SRE_INFO_LITERAL:\n return True\n if self.match(pattern_codes[2 *prefix_skip:]):\n return True\n i=overlap[i]\n break\n string_position +=1\n return False\n \n def set_mark(self,mark_nr,position):\n if mark_nr&1:\n \n \n \n self.lastindex=mark_nr //2+1\n if mark_nr >=len(self.marks):\n self.marks.extend([None ]*(mark_nr -len(self.marks)+1))\n self.marks[mark_nr]=position\n \n def get_marks(self,group_index):\n marks_index=2 *group_index\n if len(self.marks)>marks_index+1:\n return self.marks[marks_index],self.marks[marks_index+1]\n else :\n return None ,None\n \n def marks_push(self):\n self.marks_stack.append((self.marks[:],self.lastindex))\n \n def marks_pop(self):\n self.marks,self.lastindex=self.marks_stack.pop()\n \n def marks_pop_keep(self):\n self.marks,self.lastindex=self.marks_stack[-1]\n \n def marks_pop_discard(self):\n self.marks_stack.pop()\n \n def lower(self,char_ord):\n return getlower(char_ord,self.flags)\n \n \nclass _MatchContext:\n\n def __init__(self,state,pattern_codes):\n self.state=state\n self.pattern_codes=pattern_codes\n self.string_position=state.string_position\n self.code_position=0\n self.has_matched=None\n \n def push_new_context(self,pattern_offset):\n ''\n\n \n child_context=_MatchContext(self.state,\n self.pattern_codes[self.code_position+pattern_offset:])\n \n \n \n \n self.state.context_stack.append(child_context)\n return child_context\n \n def peek_char(self,peek=0):\n return self.state.string[self.string_position+peek]\n \n def skip_char(self,skip_count):\n self.string_position +=skip_count\n \n def remaining_chars(self):\n return self.state.end -self.string_position\n \n def peek_code(self,peek=0):\n return self.pattern_codes[self.code_position+peek]\n \n def skip_code(self,skip_count):\n self.code_position +=skip_count\n \n def remaining_codes(self):\n return len(self.pattern_codes)-self.code_position\n \n def at_beginning(self):\n return self.string_position ==0\n \n def at_end(self):\n return self.string_position ==self.state.end\n \n def at_linebreak(self):\n return not self.at_end()and _is_linebreak(self.peek_char())\n \n def at_boundary(self,word_checker):\n if self.at_beginning()and self.at_end():\n return False\n that=not self.at_beginning()and word_checker(self.peek_char(-1))\n this=not self.at_end()and word_checker(self.peek_char())\n return this !=that\n \n \nclass _RepeatContext(_MatchContext):\n\n def __init__(self,context):\n _MatchContext.__init__(self,context.state,\n context.pattern_codes[context.code_position:])\n self.count=-1\n \n self.previous=context.state.repeat\n self.last_position=None\n \n \nclass _Dispatcher:\n\n DISPATCH_TABLE=None\n \n def dispatch(self,code,context):\n method=self.DISPATCH_TABLE.get(code,self.__class__.unknown)\n return method(self,context)\n \n def unknown(self,code,ctx):\n raise NotImplementedError()\n \n def build_dispatch_table(cls,items,method_prefix):\n if cls.DISPATCH_TABLE is not None :\n return\n table={}\n for item in items:\n key,value=item.name.lower(),int(item)\n if hasattr(cls,\"%s%s\"%(method_prefix,key)):\n table[value]=getattr(cls,\"%s%s\"%(method_prefix,key))\n cls.DISPATCH_TABLE=table\n \n build_dispatch_table=classmethod(build_dispatch_table)\n \n \nclass _OpcodeDispatcher(_Dispatcher):\n\n def __init__(self):\n self.executing_contexts={}\n self.at_dispatcher=_AtcodeDispatcher()\n self.ch_dispatcher=_ChcodeDispatcher()\n self.set_dispatcher=_CharsetDispatcher()\n \n def match(self,context):\n ''\n\n \n while context.remaining_codes()>0 and context.has_matched is None :\n opcode=context.peek_code()\n if not self.dispatch(opcode,context):\n return None\n if context.has_matched is None :\n context.has_matched=False\n return context.has_matched\n \n def dispatch(self,opcode,context):\n ''\n \n \n if id(context)in self.executing_contexts:\n generator=self.executing_contexts[id(context)]\n del self.executing_contexts[id(context)]\n has_finished=next(generator)\n else :\n method=self.DISPATCH_TABLE.get(opcode,_OpcodeDispatcher.unknown)\n has_finished=method(self,context)\n if hasattr(has_finished,\"__next__\"):\n generator=has_finished\n has_finished=next(generator)\n if not has_finished:\n self.executing_contexts[id(context)]=generator\n return has_finished\n \n def op_success(self,ctx):\n \n \n ctx.state.string_position=ctx.string_position\n ctx.has_matched=True\n return True\n \n def op_failure(self,ctx):\n \n \n ctx.has_matched=False\n return True\n \n def general_op_literal(self,ctx,compare,decorate=lambda x:x):\n if ctx.at_end()or not compare(decorate(ord(ctx.peek_char())),\n decorate(ctx.peek_code(1))):\n ctx.has_matched=False\n ctx.skip_code(2)\n ctx.skip_char(1)\n \n def op_literal(self,ctx):\n \n \n \n self.general_op_literal(ctx,operator.eq)\n return True\n \n def op_not_literal(self,ctx):\n \n \n \n self.general_op_literal(ctx,operator.ne)\n return True\n \n def op_literal_ignore(self,ctx):\n \n \n \n self.general_op_literal(ctx,operator.eq,ctx.state.lower)\n return True\n \n def op_literal_uni_ignore(self,ctx):\n self.general_op_literal(ctx,operator.eq,ctx.state.lower)\n return True\n \n def op_not_literal_ignore(self,ctx):\n \n \n \n self.general_op_literal(ctx,operator.ne,ctx.state.lower)\n return True\n \n def op_at(self,ctx):\n \n \n \n if not self.at_dispatcher.dispatch(ctx.peek_code(1),ctx):\n ctx.has_matched=False\n \n return True\n ctx.skip_code(2)\n return True\n \n def op_category(self,ctx):\n \n \n \n if ctx.at_end()or not self.ch_dispatcher.dispatch(ctx.peek_code(1),ctx):\n ctx.has_matched=False\n \n return True\n ctx.skip_code(2)\n ctx.skip_char(1)\n return True\n \n def op_any(self,ctx):\n \n \n \n if ctx.at_end()or ctx.at_linebreak():\n ctx.has_matched=False\n \n return True\n ctx.skip_code(1)\n ctx.skip_char(1)\n return True\n \n def op_any_all(self,ctx):\n \n \n \n if ctx.at_end():\n ctx.has_matched=False\n \n return True\n ctx.skip_code(1)\n ctx.skip_char(1)\n return True\n \n def general_op_in(self,ctx,decorate=lambda x:x):\n \n \n if ctx.at_end():\n ctx.has_matched=False\n \n return\n skip=ctx.peek_code(1)\n ctx.skip_code(2)\n \n \n if not self.check_charset(ctx,decorate(ord(ctx.peek_char()))):\n \n ctx.has_matched=False\n return\n ctx.skip_code(skip -1)\n ctx.skip_char(1)\n \n \n def op_in(self,ctx):\n \n \n \n self.general_op_in(ctx)\n return True\n \n def op_in_ignore(self,ctx):\n \n \n \n self.general_op_in(ctx,ctx.state.lower)\n return True\n \n def op_in_uni_ignore(self,ctx):\n self.general_op_in(ctx,ctx.state.lower)\n return True\n \n def op_jump(self,ctx):\n \n \n \n ctx.skip_code(ctx.peek_code(1)+1)\n return True\n \n \n \n op_info=op_jump\n \n def op_mark(self,ctx):\n \n \n \n ctx.state.set_mark(ctx.peek_code(1),ctx.string_position)\n ctx.skip_code(2)\n return True\n \n def op_branch(self,ctx):\n \n \n \n ctx.state.marks_push()\n ctx.skip_code(1)\n current_branch_length=ctx.peek_code(0)\n while current_branch_length:\n \n \n if not (OPCODES[ctx.peek_code(1)].name ==\"literal\"and\\\n (ctx.at_end()or ctx.peek_code(2)!=ord(ctx.peek_char()))):\n ctx.state.string_position=ctx.string_position\n child_context=ctx.push_new_context(1)\n \n yield False\n if child_context.has_matched:\n ctx.has_matched=True\n yield True\n ctx.state.marks_pop_keep()\n ctx.skip_code(current_branch_length)\n current_branch_length=ctx.peek_code(0)\n ctx.state.marks_pop_discard()\n ctx.has_matched=False\n \n yield True\n \n def op_repeat_one(self,ctx):\n \n \n \n \n mincount=ctx.peek_code(2)\n maxcount=ctx.peek_code(3)\n \n \n \n if ctx.remaining_chars()<mincount:\n ctx.has_matched=False\n yield True\n ctx.state.string_position=ctx.string_position\n count=self.count_repetitions(ctx,maxcount)\n ctx.skip_char(count)\n if count <mincount:\n ctx.has_matched=False\n yield True\n if OPCODES[ctx.peek_code(ctx.peek_code(1)+1)].name ==\"success\":\n \n ctx.state.string_position=ctx.string_position\n ctx.has_matched=True\n yield True\n \n ctx.state.marks_push()\n if OPCODES[ctx.peek_code(ctx.peek_code(1)+1)].name ==\"literal\":\n \n \n char=ctx.peek_code(ctx.peek_code(1)+2)\n while True :\n while count >=mincount and\\\n (ctx.at_end()or ord(ctx.peek_char())!=char):\n ctx.skip_char(-1)\n count -=1\n if count <mincount:\n break\n ctx.state.string_position=ctx.string_position\n child_context=ctx.push_new_context(ctx.peek_code(1)+1)\n \n yield False\n if child_context.has_matched:\n ctx.has_matched=True\n yield True\n ctx.skip_char(-1)\n count -=1\n ctx.state.marks_pop_keep()\n \n else :\n \n while count >=mincount:\n ctx.state.string_position=ctx.string_position\n child_context=ctx.push_new_context(ctx.peek_code(1)+1)\n yield False\n if child_context.has_matched:\n ctx.has_matched=True\n yield True\n ctx.skip_char(-1)\n count -=1\n ctx.state.marks_pop_keep()\n \n ctx.state.marks_pop_discard()\n ctx.has_matched=False\n \n yield True\n \n def op_min_repeat_one(self,ctx):\n \n \n mincount=ctx.peek_code(2)\n maxcount=ctx.peek_code(3)\n \n \n if ctx.remaining_chars()<mincount:\n ctx.has_matched=False\n yield True\n ctx.state.string_position=ctx.string_position\n if mincount ==0:\n count=0\n else :\n count=self.count_repetitions(ctx,mincount)\n if count <mincount:\n ctx.has_matched=False\n \n yield True\n ctx.skip_char(count)\n if OPCODES[ctx.peek_code(ctx.peek_code(1)+1)].name ==\"success\":\n \n ctx.state.string_position=ctx.string_position\n ctx.has_matched=True\n yield True\n \n ctx.state.marks_push()\n while maxcount ==MAXREPEAT or count <=maxcount:\n ctx.state.string_position=ctx.string_position\n child_context=ctx.push_new_context(ctx.peek_code(1)+1)\n \n yield False\n if child_context.has_matched:\n ctx.has_matched=True\n yield True\n ctx.state.string_position=ctx.string_position\n if self.count_repetitions(ctx,1)==0:\n break\n ctx.skip_char(1)\n count +=1\n ctx.state.marks_pop_keep()\n \n ctx.state.marks_pop_discard()\n ctx.has_matched=False\n yield True\n \n def op_repeat(self,ctx):\n \n \n \n \n \n \n \n \n \n repeat=_RepeatContext(ctx)\n ctx.state.repeat=repeat\n ctx.state.string_position=ctx.string_position\n child_context=ctx.push_new_context(ctx.peek_code(1)+1)\n \n \n \n \n yield False\n ctx.state.repeat=repeat.previous\n ctx.has_matched=child_context.has_matched\n yield True\n \n def op_max_until(self,ctx):\n \n \n repeat=ctx.state.repeat\n \n if repeat is None :\n \n raise RuntimeError(\"Internal re error: MAX_UNTIL without REPEAT.\")\n mincount=repeat.peek_code(2)\n maxcount=repeat.peek_code(3)\n ctx.state.string_position=ctx.string_position\n count=repeat.count+1\n \n \n if count <mincount:\n \n repeat.count=count\n child_context=repeat.push_new_context(4)\n yield False\n ctx.has_matched=child_context.has_matched\n if not ctx.has_matched:\n repeat.count=count -1\n ctx.state.string_position=ctx.string_position\n yield True\n \n if (count <maxcount or maxcount ==MAXREPEAT)\\\n and ctx.state.string_position !=repeat.last_position:\n \n repeat.count=count\n ctx.state.marks_push()\n save_last_position=repeat.last_position\n repeat.last_position=ctx.state.string_position\n child_context=repeat.push_new_context(4)\n yield False\n repeat.last_position=save_last_position\n if child_context.has_matched:\n ctx.state.marks_pop_discard()\n ctx.has_matched=True\n yield True\n ctx.state.marks_pop()\n repeat.count=count -1\n ctx.state.string_position=ctx.string_position\n \n \n ctx.state.repeat=repeat.previous\n child_context=ctx.push_new_context(1)\n \n yield False\n ctx.has_matched=child_context.has_matched\n if not ctx.has_matched:\n ctx.state.repeat=repeat\n ctx.state.string_position=ctx.string_position\n yield True\n \n def op_min_until(self,ctx):\n \n \n repeat=ctx.state.repeat\n if repeat is None :\n raise RuntimeError(\"Internal re error: MIN_UNTIL without REPEAT.\")\n mincount=repeat.peek_code(2)\n maxcount=repeat.peek_code(3)\n ctx.state.string_position=ctx.string_position\n count=repeat.count+1\n \n \n if count <mincount:\n \n repeat.count=count\n child_context=repeat.push_new_context(4)\n yield False\n ctx.has_matched=child_context.has_matched\n if not ctx.has_matched:\n repeat.count=count -1\n ctx.state.string_position=ctx.string_position\n yield True\n \n \n ctx.state.marks_push()\n ctx.state.repeat=repeat.previous\n child_context=ctx.push_new_context(1)\n \n yield False\n if child_context.has_matched:\n ctx.has_matched=True\n yield True\n ctx.state.repeat=repeat\n ctx.state.string_position=ctx.string_position\n ctx.state.marks_pop()\n \n \n if count >=maxcount and maxcount !=MAXREPEAT:\n ctx.has_matched=False\n \n yield True\n repeat.count=count\n child_context=repeat.push_new_context(4)\n yield False\n ctx.has_matched=child_context.has_matched\n if not ctx.has_matched:\n repeat.count=count -1\n ctx.state.string_position=ctx.string_position\n yield True\n \n def general_op_groupref(self,ctx,decorate=lambda x:x):\n group_start,group_end=ctx.state.get_marks(ctx.peek_code(1))\n if group_start is None or group_end is None or group_end <group_start:\n ctx.has_matched=False\n return True\n while group_start <group_end:\n if ctx.at_end()or decorate(ord(ctx.peek_char()))\\\n !=decorate(ord(ctx.state.string[group_start])):\n ctx.has_matched=False\n \n return True\n group_start +=1\n ctx.skip_char(1)\n ctx.skip_code(2)\n return True\n \n def op_groupref(self,ctx):\n \n \n \n return self.general_op_groupref(ctx)\n \n def op_groupref_ignore(self,ctx):\n \n \n \n return self.general_op_groupref(ctx,ctx.state.lower)\n \n def op_groupref_exists(self,ctx):\n \n \n group_start,group_end=ctx.state.get_marks(ctx.peek_code(1))\n if group_start is None or group_end is None or group_end <group_start:\n ctx.skip_code(ctx.peek_code(2)+1)\n else :\n ctx.skip_code(3)\n return True\n \n def op_assert(self,ctx):\n \n \n \n ctx.state.string_position=ctx.string_position -ctx.peek_code(2)\n if ctx.state.string_position <0:\n ctx.has_matched=False\n yield True\n child_context=ctx.push_new_context(3)\n yield False\n if child_context.has_matched:\n ctx.skip_code(ctx.peek_code(1)+1)\n else :\n ctx.has_matched=False\n yield True\n \n def op_assert_not(self,ctx):\n \n \n \n ctx.state.string_position=ctx.string_position -ctx.peek_code(2)\n if ctx.state.string_position >=0:\n child_context=ctx.push_new_context(3)\n yield False\n if child_context.has_matched:\n ctx.has_matched=False\n yield True\n ctx.skip_code(ctx.peek_code(1)+1)\n yield True\n \n def unknown(self,ctx):\n \n raise RuntimeError(\"Internal re error. Unknown opcode: %s\"%ctx.peek_code())\n \n def check_charset(self,ctx,char):\n ''\n \n self.set_dispatcher.reset(char)\n save_position=ctx.code_position\n result=None\n while result is None :\n result=self.set_dispatcher.dispatch(ctx.peek_code(),ctx)\n ctx.code_position=save_position\n \n return result\n \n def count_repetitions(self,ctx,maxcount):\n ''\n\n \n count=0\n real_maxcount=ctx.state.end -ctx.string_position\n if maxcount <real_maxcount and maxcount !=MAXREPEAT:\n real_maxcount=maxcount\n \n \n \n code_position=ctx.code_position\n string_position=ctx.string_position\n ctx.skip_code(4)\n reset_position=ctx.code_position\n while count <real_maxcount:\n \n \n ctx.code_position=reset_position\n self.dispatch(ctx.peek_code(),ctx)\n \n if ctx.has_matched is False :\n break\n count +=1\n ctx.has_matched=None\n ctx.code_position=code_position\n ctx.string_position=string_position\n return count\n \n def _log(self,context,opname,*args):\n arg_string=(\"%s \"*len(args))%args\n _log(\"|%s|%s|%s %s\"%(context.pattern_codes,\n context.string_position,opname,arg_string))\n \n_OpcodeDispatcher.build_dispatch_table(OPCODES,\"op_\")\n\n\nclass _CharsetDispatcher(_Dispatcher):\n\n def __init__(self):\n self.ch_dispatcher=_ChcodeDispatcher()\n \n def reset(self,char):\n self.char=char\n self.ok=True\n \n def set_failure(self,ctx):\n return not self.ok\n def set_literal(self,ctx):\n \n if ctx.peek_code(1)==self.char:\n return self.ok\n else :\n ctx.skip_code(2)\n def set_category(self,ctx):\n \n if self.ch_dispatcher.dispatch(ctx.peek_code(1),ctx):\n return self.ok\n else :\n ctx.skip_code(2)\n def set_charset(self,ctx):\n \n char_code=self.char\n ctx.skip_code(1)\n if CODESIZE ==2:\n if char_code <256 and ctx.peek_code(char_code >>4)\\\n &(1 <<(char_code&15)):\n return self.ok\n ctx.skip_code(16)\n else :\n if char_code <256 and ctx.peek_code(char_code >>5)\\\n &(1 <<(char_code&31)):\n return self.ok\n ctx.skip_code(8)\n def set_range(self,ctx):\n \n if ctx.peek_code(1)<=self.char <=ctx.peek_code(2):\n return self.ok\n ctx.skip_code(3)\n def set_negate(self,ctx):\n self.ok=not self.ok\n ctx.skip_code(1)\n \n def set_bigcharset(self,ctx):\n \n char_code=self.char\n count=ctx.peek_code(1)\n ctx.skip_code(2)\n if char_code <65536:\n block_index=char_code >>8\n \n a=array.array(\"B\")\n a.fromstring(array.array(CODESIZE ==2 and \"H\"or \"I\",\n [ctx.peek_code(block_index //CODESIZE)]).tostring())\n block=a[block_index %CODESIZE]\n ctx.skip_code(256 //CODESIZE)\n block_value=ctx.peek_code(block *(32 //CODESIZE)\n +((char_code&255)>>(CODESIZE ==2 and 4 or 5)))\n if block_value&(1 <<(char_code&((8 *CODESIZE)-1))):\n return self.ok\n else :\n ctx.skip_code(256 //CODESIZE)\n ctx.skip_code(count *(32 //CODESIZE))\n \n def unknown(self,ctx):\n return False\n \n_CharsetDispatcher.build_dispatch_table(OPCODES,\"set_\")\n\n\nclass _AtcodeDispatcher(_Dispatcher):\n\n def at_beginning(self,ctx):\n return ctx.at_beginning()\n at_beginning_string=at_beginning\n def at_beginning_line(self,ctx):\n return ctx.at_beginning()or _is_linebreak(ctx.peek_char(-1))\n def at_end(self,ctx):\n return (ctx.remaining_chars()==1 and ctx.at_linebreak())or ctx.at_end()\n def at_end_line(self,ctx):\n return ctx.at_linebreak()or ctx.at_end()\n def at_end_string(self,ctx):\n return ctx.at_end()\n def at_boundary(self,ctx):\n return ctx.at_boundary(_is_word)\n def at_non_boundary(self,ctx):\n return not ctx.at_boundary(_is_word)\n def at_loc_boundary(self,ctx):\n return ctx.at_boundary(_is_loc_word)\n def at_loc_non_boundary(self,ctx):\n return not ctx.at_boundary(_is_loc_word)\n def at_uni_boundary(self,ctx):\n return ctx.at_boundary(_is_uni_word)\n def at_uni_non_boundary(self,ctx):\n return not ctx.at_boundary(_is_uni_word)\n def unknown(self,ctx):\n return False\n \n_AtcodeDispatcher.build_dispatch_table(ATCODES,\"\")\n\n\nclass _ChcodeDispatcher(_Dispatcher):\n\n def category_digit(self,ctx):\n return _is_digit(ctx.peek_char())\n def category_not_digit(self,ctx):\n return not _is_digit(ctx.peek_char())\n def category_space(self,ctx):\n return _is_space(ctx.peek_char())\n def category_not_space(self,ctx):\n return not _is_space(ctx.peek_char())\n def category_word(self,ctx):\n return _is_word(ctx.peek_char())\n def category_not_word(self,ctx):\n return not _is_word(ctx.peek_char())\n def category_linebreak(self,ctx):\n return _is_linebreak(ctx.peek_char())\n def category_not_linebreak(self,ctx):\n return not _is_linebreak(ctx.peek_char())\n def category_loc_word(self,ctx):\n return _is_loc_word(ctx.peek_char())\n def category_loc_not_word(self,ctx):\n return not _is_loc_word(ctx.peek_char())\n def category_uni_digit(self,ctx):\n return ctx.peek_char().isdigit()\n def category_uni_not_digit(self,ctx):\n return not ctx.peek_char().isdigit()\n def category_uni_space(self,ctx):\n return ctx.peek_char().isspace()\n def category_uni_not_space(self,ctx):\n return not ctx.peek_char().isspace()\n def category_uni_word(self,ctx):\n return _is_uni_word(ctx.peek_char())\n def category_uni_not_word(self,ctx):\n return not _is_uni_word(ctx.peek_char())\n def category_uni_linebreak(self,ctx):\n return ord(ctx.peek_char())in _uni_linebreaks\n def category_uni_not_linebreak(self,ctx):\n return ord(ctx.peek_char())not in _uni_linebreaks\n def unknown(self,ctx):\n return False\n \n_ChcodeDispatcher.build_dispatch_table(CHCODES,\"\")\n\n\n_ascii_char_info=[0,0,0,0,0,0,0,0,0,2,6,2,\n2,2,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,2,0,0,\n0,0,0,0,0,0,0,0,0,0,0,0,0,25,25,25,25,25,25,25,25,\n25,25,0,0,0,0,0,0,0,24,24,24,24,24,24,24,24,24,24,\n24,24,24,24,24,24,24,24,24,24,24,24,24,24,24,24,0,0,\n0,0,16,0,24,24,24,24,24,24,24,24,24,24,24,24,24,24,\n24,24,24,24,24,24,24,24,24,24,24,24,0,0,0,0,0]\n\ndef _is_digit(char):\n code=ord(char)\n return code <128 and _ascii_char_info[code]&1\n \ndef _is_space(char):\n code=ord(char)\n return code <128 and _ascii_char_info[code]&2\n \ndef _is_word(char):\n\n code=ord(char)\n return code <128 and _ascii_char_info[code]&16\n \ndef _is_loc_word(char):\n return (not (ord(char)&~255)and char.isalnum())or char =='_'\n \ndef _is_uni_word(char):\n\n\n return chr(ord(char)).isalnum()or char =='_'\n \ndef _is_linebreak(char):\n return char ==\"\\n\"\n \n \n_uni_linebreaks=[10,13,28,29,30,133,8232,8233]\n\ndef _log(message):\n if 0:\n print(message)\n", ["_sre_utils", "array", "operator", "re", "sre", "sre_constants", "sys"]], "inspect": [".py", "''\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n__author__=('Ka-Ping Yee <ping@lfw.org>',\n'Yury Selivanov <yselivanov@sprymix.com>')\n\nimport abc\nimport dis\nimport collections.abc\nimport enum\nimport importlib.machinery\nimport itertools\nimport linecache\nimport os\nimport re\nimport sys\nimport tokenize\nimport token\nimport types\nimport warnings\nimport functools\nimport builtins\nfrom operator import attrgetter\nfrom collections import namedtuple,OrderedDict\n\n\n\nmod_dict=globals()\nfor k,v in dis.COMPILER_FLAG_NAMES.items():\n mod_dict[\"CO_\"+v]=k\n \n \nTPFLAGS_IS_ABSTRACT=1 <<20\n\n\ndef ismodule(object):\n ''\n\n\n\n\n \n return isinstance(object,types.ModuleType)\n \ndef isclass(object):\n ''\n\n\n\n \n return isinstance(object,type)\n \ndef ismethod(object):\n ''\n\n\n\n\n\n \n return isinstance(object,types.MethodType)\n \ndef ismethoddescriptor(object):\n ''\n\n\n\n\n\n\n\n\n\n\n\n \n if isclass(object)or ismethod(object)or isfunction(object):\n \n return False\n tp=type(object)\n return hasattr(tp,\"__get__\")and not hasattr(tp,\"__set__\")\n \ndef isdatadescriptor(object):\n ''\n\n\n\n\n\n \n if isclass(object)or ismethod(object)or isfunction(object):\n \n return False\n tp=type(object)\n return hasattr(tp,\"__set__\")and hasattr(tp,\"__get__\")\n \nif hasattr(types,'MemberDescriptorType'):\n\n def ismemberdescriptor(object):\n ''\n\n\n \n return isinstance(object,types.MemberDescriptorType)\nelse :\n\n def ismemberdescriptor(object):\n ''\n\n\n \n return False\n \nif hasattr(types,'GetSetDescriptorType'):\n\n def isgetsetdescriptor(object):\n ''\n\n\n \n return isinstance(object,types.GetSetDescriptorType)\nelse :\n\n def isgetsetdescriptor(object):\n ''\n\n\n \n return False\n \ndef isfunction(object):\n ''\n\n\n\n\n\n\n\n\n \n return isinstance(object,types.FunctionType)\n \ndef isgeneratorfunction(object):\n ''\n\n\n \n return bool((isfunction(object)or ismethod(object))and\n object.__code__.co_flags&CO_GENERATOR)\n \ndef iscoroutinefunction(object):\n ''\n\n\n \n return bool((isfunction(object)or ismethod(object))and\n object.__code__.co_flags&CO_COROUTINE)\n \ndef isasyncgenfunction(object):\n ''\n\n\n\n \n return bool((isfunction(object)or ismethod(object))and\n object.__code__.co_flags&CO_ASYNC_GENERATOR)\n \ndef isasyncgen(object):\n ''\n return isinstance(object,types.AsyncGeneratorType)\n \ndef isgenerator(object):\n ''\n\n\n\n\n\n\n\n\n\n\n\n\n \n return isinstance(object,types.GeneratorType)\n \ndef iscoroutine(object):\n ''\n return isinstance(object,types.CoroutineType)\n \ndef isawaitable(object):\n ''\n return (isinstance(object,types.CoroutineType)or\n isinstance(object,types.GeneratorType)and\n bool(object.gi_code.co_flags&CO_ITERABLE_COROUTINE)or\n isinstance(object,collections.abc.Awaitable))\n \ndef istraceback(object):\n ''\n\n\n\n\n\n \n return isinstance(object,types.TracebackType)\n \ndef isframe(object):\n ''\n\n\n\n\n\n\n\n\n\n \n return isinstance(object,types.FrameType)\n \ndef iscode(object):\n ''\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n \n return isinstance(object,types.CodeType)\n \ndef isbuiltin(object):\n ''\n\n\n\n\n \n return isinstance(object,types.BuiltinFunctionType)\n \ndef isroutine(object):\n ''\n return (isbuiltin(object)\n or isfunction(object)\n or ismethod(object)\n or ismethoddescriptor(object))\n \ndef isabstract(object):\n ''\n if not isinstance(object,type):\n return False\n if object.__flags__&TPFLAGS_IS_ABSTRACT:\n return True\n if not issubclass(type(object),abc.ABCMeta):\n return False\n if hasattr(object,'__abstractmethods__'):\n \n \n return False\n \n \n for name,value in object.__dict__.items():\n if getattr(value,\"__isabstractmethod__\",False ):\n return True\n for base in object.__bases__:\n for name in getattr(base,\"__abstractmethods__\",()):\n value=getattr(object,name,None )\n if getattr(value,\"__isabstractmethod__\",False ):\n return True\n return False\n \ndef getmembers(object,predicate=None ):\n ''\n \n if isclass(object):\n mro=(object,)+getmro(object)\n else :\n mro=()\n results=[]\n processed=set()\n names=dir(object)\n \n \n \n try :\n for base in object.__bases__:\n for k,v in base.__dict__.items():\n if isinstance(v,types.DynamicClassAttribute):\n names.append(k)\n except AttributeError:\n pass\n for key in names:\n \n \n \n try :\n value=getattr(object,key)\n \n if key in processed:\n raise AttributeError\n except AttributeError:\n for base in mro:\n if key in base.__dict__:\n value=base.__dict__[key]\n break\n else :\n \n \n continue\n if not predicate or predicate(value):\n results.append((key,value))\n processed.add(key)\n results.sort(key=lambda pair:pair[0])\n return results\n \nAttribute=namedtuple('Attribute','name kind defining_class object')\n\ndef classify_class_attrs(cls):\n ''\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n \n \n mro=getmro(cls)\n metamro=getmro(type(cls))\n metamro=tuple(cls for cls in metamro if cls not in (type,object))\n class_bases=(cls,)+mro\n all_bases=class_bases+metamro\n names=dir(cls)\n \n \n \n for base in mro:\n for k,v in base.__dict__.items():\n if isinstance(v,types.DynamicClassAttribute):\n names.append(k)\n result=[]\n processed=set()\n \n for name in names:\n \n \n \n \n \n \n \n \n \n homecls=None\n get_obj=None\n dict_obj=None\n if name not in processed:\n try :\n if name =='__dict__':\n raise Exception(\"__dict__ is special, don't want the proxy\")\n get_obj=getattr(cls,name)\n except Exception as exc:\n pass\n else :\n homecls=getattr(get_obj,\"__objclass__\",homecls)\n if homecls not in class_bases:\n \n \n homecls=None\n last_cls=None\n \n for srch_cls in class_bases:\n srch_obj=getattr(srch_cls,name,None )\n if srch_obj is get_obj:\n last_cls=srch_cls\n \n for srch_cls in metamro:\n try :\n srch_obj=srch_cls.__getattr__(cls,name)\n except AttributeError:\n continue\n if srch_obj is get_obj:\n last_cls=srch_cls\n if last_cls is not None :\n homecls=last_cls\n for base in all_bases:\n if name in base.__dict__:\n dict_obj=base.__dict__[name]\n if homecls not in metamro:\n homecls=base\n break\n if homecls is None :\n \n \n continue\n obj=get_obj if get_obj is not None else dict_obj\n \n if isinstance(dict_obj,(staticmethod,types.BuiltinMethodType)):\n kind=\"static method\"\n obj=dict_obj\n elif isinstance(dict_obj,(classmethod,types.ClassMethodDescriptorType)):\n kind=\"class method\"\n obj=dict_obj\n elif isinstance(dict_obj,property):\n kind=\"property\"\n obj=dict_obj\n elif isroutine(obj):\n kind=\"method\"\n else :\n kind=\"data\"\n result.append(Attribute(name,kind,homecls,obj))\n processed.add(name)\n return result\n \n \n \ndef getmro(cls):\n ''\n return cls.__mro__\n \n \n \ndef unwrap(func,*,stop=None ):\n ''\n\n\n\n\n\n\n\n\n\n\n\n\n\n \n if stop is None :\n def _is_wrapper(f):\n return hasattr(f,'__wrapped__')\n else :\n def _is_wrapper(f):\n return hasattr(f,'__wrapped__')and not stop(f)\n f=func\n \n \n memo={id(f):f}\n recursion_limit=sys.getrecursionlimit()\n while _is_wrapper(func):\n func=func.__wrapped__\n id_func=id(func)\n if (id_func in memo)or (len(memo)>=recursion_limit):\n raise ValueError('wrapper loop when unwrapping {!r}'.format(f))\n memo[id_func]=func\n return func\n \n \ndef indentsize(line):\n ''\n expline=line.expandtabs()\n return len(expline)-len(expline.lstrip())\n \ndef _findclass(func):\n cls=sys.modules.get(func.__module__)\n if cls is None :\n return None\n for name in func.__qualname__.split('.')[:-1]:\n cls=getattr(cls,name)\n if not isclass(cls):\n return None\n return cls\n \ndef _finddoc(obj):\n if isclass(obj):\n for base in obj.__mro__:\n if base is not object:\n try :\n doc=base.__doc__\n except AttributeError:\n continue\n if doc is not None :\n return doc\n return None\n \n if ismethod(obj):\n name=obj.__func__.__name__\n self=obj.__self__\n if (isclass(self)and\n getattr(getattr(self,name,None ),'__func__')is obj.__func__):\n \n cls=self\n else :\n cls=self.__class__\n elif isfunction(obj):\n name=obj.__name__\n cls=_findclass(obj)\n if cls is None or getattr(cls,name)is not obj:\n return None\n elif isbuiltin(obj):\n name=obj.__name__\n self=obj.__self__\n if (isclass(self)and\n self.__qualname__+'.'+name ==obj.__qualname__):\n \n cls=self\n else :\n cls=self.__class__\n \n elif isinstance(obj,property):\n func=obj.fget\n name=func.__name__\n cls=_findclass(func)\n if cls is None or getattr(cls,name)is not obj:\n return None\n elif ismethoddescriptor(obj)or isdatadescriptor(obj):\n name=obj.__name__\n cls=obj.__objclass__\n if getattr(cls,name)is not obj:\n return None\n else :\n return None\n \n for base in cls.__mro__:\n try :\n doc=getattr(base,name).__doc__\n except AttributeError:\n continue\n if doc is not None :\n return doc\n return None\n \ndef getdoc(object):\n ''\n\n\n\n \n try :\n doc=object.__doc__\n except AttributeError:\n return None\n if doc is None :\n try :\n doc=_finddoc(object)\n except (AttributeError,TypeError):\n return None\n if not isinstance(doc,str):\n return None\n return cleandoc(doc)\n \ndef cleandoc(doc):\n ''\n\n\n \n try :\n lines=doc.expandtabs().split('\\n')\n except UnicodeError:\n return None\n else :\n \n margin=sys.maxsize\n for line in lines[1:]:\n content=len(line.lstrip())\n if content:\n indent=len(line)-content\n margin=min(margin,indent)\n \n if lines:\n lines[0]=lines[0].lstrip()\n if margin <sys.maxsize:\n for i in range(1,len(lines)):lines[i]=lines[i][margin:]\n \n while lines and not lines[-1]:\n lines.pop()\n while lines and not lines[0]:\n lines.pop(0)\n return '\\n'.join(lines)\n \ndef getfile(object):\n ''\n if ismodule(object):\n if getattr(object,'__file__',None ):\n return object.__file__\n raise TypeError('{!r} is a built-in module'.format(object))\n if isclass(object):\n if hasattr(object,'__module__'):\n object=sys.modules.get(object.__module__)\n if getattr(object,'__file__',None ):\n return object.__file__\n raise TypeError('{!r} is a built-in class'.format(object))\n if ismethod(object):\n object=object.__func__\n if isfunction(object):\n object=object.__code__\n if istraceback(object):\n object=object.tb_frame\n if isframe(object):\n object=object.f_code\n if iscode(object):\n return object.co_filename\n raise TypeError('module, class, method, function, traceback, frame, or '\n 'code object was expected, got {}'.format(\n type(object).__name__))\n \ndef getmodulename(path):\n ''\n fname=os.path.basename(path)\n \n suffixes=[(-len(suffix),suffix)\n for suffix in importlib.machinery.all_suffixes()]\n suffixes.sort()\n for neglen,suffix in suffixes:\n if fname.endswith(suffix):\n return fname[:neglen]\n return None\n \ndef getsourcefile(object):\n ''\n\n \n filename=getfile(object)\n all_bytecode_suffixes=importlib.machinery.DEBUG_BYTECODE_SUFFIXES[:]\n all_bytecode_suffixes +=importlib.machinery.OPTIMIZED_BYTECODE_SUFFIXES[:]\n if any(filename.endswith(s)for s in all_bytecode_suffixes):\n filename=(os.path.splitext(filename)[0]+\n importlib.machinery.SOURCE_SUFFIXES[0])\n elif any(filename.endswith(s)for s in\n importlib.machinery.EXTENSION_SUFFIXES):\n return None\n if os.path.exists(filename):\n return filename\n \n if getattr(getmodule(object,filename),'__loader__',None )is not None :\n return filename\n \n if filename in linecache.cache:\n return filename\n \ndef getabsfile(object,_filename=None ):\n ''\n\n\n \n if _filename is None :\n _filename=getsourcefile(object)or getfile(object)\n return os.path.normcase(os.path.abspath(_filename))\n \nmodulesbyfile={}\n_filesbymodname={}\n\ndef getmodule(object,_filename=None ):\n ''\n if ismodule(object):\n return object\n if hasattr(object,'__module__'):\n return sys.modules.get(object.__module__)\n \n if _filename is not None and _filename in modulesbyfile:\n return sys.modules.get(modulesbyfile[_filename])\n \n try :\n file=getabsfile(object,_filename)\n except TypeError:\n return None\n if file in modulesbyfile:\n return sys.modules.get(modulesbyfile[file])\n \n \n for modname,module in list(sys.modules.items()):\n if ismodule(module)and hasattr(module,'__file__'):\n f=module.__file__\n if f ==_filesbymodname.get(modname,None ):\n \n continue\n _filesbymodname[modname]=f\n f=getabsfile(module)\n \n modulesbyfile[f]=modulesbyfile[\n os.path.realpath(f)]=module.__name__\n if file in modulesbyfile:\n return sys.modules.get(modulesbyfile[file])\n \n main=sys.modules['__main__']\n if not hasattr(object,'__name__'):\n return None\n if hasattr(main,object.__name__):\n mainobject=getattr(main,object.__name__)\n if mainobject is object:\n return main\n \n builtin=sys.modules['builtins']\n if hasattr(builtin,object.__name__):\n builtinobject=getattr(builtin,object.__name__)\n if builtinobject is object:\n return builtin\n \ndef findsource(object):\n ''\n\n\n\n\n \n \n file=getsourcefile(object)\n if file:\n \n linecache.checkcache(file)\n else :\n file=getfile(object)\n \n \n \n if not (file.startswith('<')and file.endswith('>')):\n raise OSError('source code not available')\n \n module=getmodule(object,file)\n if module:\n lines=linecache.getlines(file,module.__dict__)\n else :\n lines=linecache.getlines(file)\n if not lines:\n raise OSError('could not get source code')\n \n if ismodule(object):\n return lines,0\n \n if isclass(object):\n name=object.__name__\n pat=re.compile(r'^(\\s*)class\\s*'+name+r'\\b')\n \n \n \n candidates=[]\n for i in range(len(lines)):\n match=pat.match(lines[i])\n if match:\n \n if lines[i][0]=='c':\n return lines,i\n \n candidates.append((match.group(1),i))\n if candidates:\n \n \n candidates.sort()\n return lines,candidates[0][1]\n else :\n raise OSError('could not find class definition')\n \n if ismethod(object):\n object=object.__func__\n if isfunction(object):\n object=object.__code__\n if istraceback(object):\n object=object.tb_frame\n if isframe(object):\n object=object.f_code\n if iscode(object):\n if not hasattr(object,'co_firstlineno'):\n raise OSError('could not find function definition')\n lnum=object.co_firstlineno -1\n pat=re.compile(r'^(\\s*def\\s)|(\\s*async\\s+def\\s)|(.*(?<!\\w)lambda(:|\\s))|^(\\s*@)')\n while lnum >0:\n if pat.match(lines[lnum]):break\n lnum=lnum -1\n return lines,lnum\n raise OSError('could not find code object')\n \ndef getcomments(object):\n ''\n\n\n \n try :\n lines,lnum=findsource(object)\n except (OSError,TypeError):\n return None\n \n if ismodule(object):\n \n start=0\n if lines and lines[0][:2]=='#!':start=1\n while start <len(lines)and lines[start].strip()in ('','#'):\n start=start+1\n if start <len(lines)and lines[start][:1]=='#':\n comments=[]\n end=start\n while end <len(lines)and lines[end][:1]=='#':\n comments.append(lines[end].expandtabs())\n end=end+1\n return ''.join(comments)\n \n \n elif lnum >0:\n indent=indentsize(lines[lnum])\n end=lnum -1\n if end >=0 and lines[end].lstrip()[:1]=='#'and\\\n indentsize(lines[end])==indent:\n comments=[lines[end].expandtabs().lstrip()]\n if end >0:\n end=end -1\n comment=lines[end].expandtabs().lstrip()\n while comment[:1]=='#'and indentsize(lines[end])==indent:\n comments[:0]=[comment]\n end=end -1\n if end <0:break\n comment=lines[end].expandtabs().lstrip()\n while comments and comments[0].strip()=='#':\n comments[:1]=[]\n while comments and comments[-1].strip()=='#':\n comments[-1:]=[]\n return ''.join(comments)\n \nclass EndOfBlock(Exception):pass\n\nclass BlockFinder:\n ''\n def __init__(self):\n self.indent=0\n self.islambda=False\n self.started=False\n self.passline=False\n self.indecorator=False\n self.decoratorhasargs=False\n self.last=1\n \n def tokeneater(self,type,token,srowcol,erowcol,line):\n if not self.started and not self.indecorator:\n \n if token ==\"@\":\n self.indecorator=True\n \n elif token in (\"def\",\"class\",\"lambda\"):\n if token ==\"lambda\":\n self.islambda=True\n self.started=True\n self.passline=True\n elif token ==\"(\":\n if self.indecorator:\n self.decoratorhasargs=True\n elif token ==\")\":\n if self.indecorator:\n self.indecorator=False\n self.decoratorhasargs=False\n elif type ==tokenize.NEWLINE:\n self.passline=False\n self.last=srowcol[0]\n if self.islambda:\n raise EndOfBlock\n \n \n if self.indecorator and not self.decoratorhasargs:\n self.indecorator=False\n elif self.passline:\n pass\n elif type ==tokenize.INDENT:\n self.indent=self.indent+1\n self.passline=True\n elif type ==tokenize.DEDENT:\n self.indent=self.indent -1\n \n \n \n if self.indent <=0:\n raise EndOfBlock\n elif self.indent ==0 and type not in (tokenize.COMMENT,tokenize.NL):\n \n \n raise EndOfBlock\n \ndef getblock(lines):\n ''\n blockfinder=BlockFinder()\n try :\n tokens=tokenize.generate_tokens(iter(lines).__next__)\n for _token in tokens:\n blockfinder.tokeneater(*_token)\n except (EndOfBlock,IndentationError):\n pass\n return lines[:blockfinder.last]\n \ndef getsourcelines(object):\n ''\n\n\n\n\n\n \n object=unwrap(object)\n lines,lnum=findsource(object)\n \n if ismodule(object):\n return lines,0\n else :\n return getblock(lines[lnum:]),lnum+1\n \ndef getsource(object):\n ''\n\n\n\n \n lines,lnum=getsourcelines(object)\n return ''.join(lines)\n \n \ndef walktree(classes,children,parent):\n ''\n results=[]\n classes.sort(key=attrgetter('__module__','__name__'))\n for c in classes:\n results.append((c,c.__bases__))\n if c in children:\n results.append(walktree(children[c],children,c))\n return results\n \ndef getclasstree(classes,unique=False ):\n ''\n\n\n\n\n\n\n \n children={}\n roots=[]\n for c in classes:\n if c.__bases__:\n for parent in c.__bases__:\n if not parent in children:\n children[parent]=[]\n if c not in children[parent]:\n children[parent].append(c)\n if unique and parent in classes:break\n elif c not in roots:\n roots.append(c)\n for parent in children:\n if parent not in classes:\n roots.append(parent)\n return walktree(roots,children,None )\n \n \nArguments=namedtuple('Arguments','args, varargs, varkw')\n\ndef getargs(co):\n ''\n\n\n\n\n \n args,varargs,kwonlyargs,varkw=_getfullargs(co)\n return Arguments(args+kwonlyargs,varargs,varkw)\n \ndef _getfullargs(co):\n ''\n\n\n\n \n \n if not iscode(co):\n raise TypeError('{!r} is not a code object'.format(co))\n \n nargs=co.co_argcount\n names=co.co_varnames\n nkwargs=co.co_kwonlyargcount\n args=list(names[:nargs])\n kwonlyargs=list(names[nargs:nargs+nkwargs])\n step=0\n \n nargs +=nkwargs\n varargs=None\n if co.co_flags&CO_VARARGS:\n varargs=co.co_varnames[nargs]\n nargs=nargs+1\n varkw=None\n if co.co_flags&CO_VARKEYWORDS:\n varkw=co.co_varnames[nargs]\n return args,varargs,kwonlyargs,varkw\n \n \nArgSpec=namedtuple('ArgSpec','args varargs keywords defaults')\n\ndef getargspec(func):\n ''\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n \n warnings.warn(\"inspect.getargspec() is deprecated, \"\n \"use inspect.signature() or inspect.getfullargspec()\",\n DeprecationWarning,stacklevel=2)\n args,varargs,varkw,defaults,kwonlyargs,kwonlydefaults,ann=\\\n getfullargspec(func)\n if kwonlyargs or ann:\n raise ValueError(\"Function has keyword-only parameters or annotations\"\n \", use getfullargspec() API which can support them\")\n return ArgSpec(args,varargs,varkw,defaults)\n \nFullArgSpec=namedtuple('FullArgSpec',\n'args, varargs, varkw, defaults, kwonlyargs, kwonlydefaults, annotations')\n\ndef getfullargspec(func):\n ''\n\n\n\n\n\n\n\n\n\n\n\n\n\n \n \n try :\n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n sig=_signature_from_callable(func,\n follow_wrapper_chains=False ,\n skip_bound_arg=False ,\n sigcls=Signature)\n except Exception as ex:\n \n \n \n \n raise TypeError('unsupported callable')from ex\n \n args=[]\n varargs=None\n varkw=None\n kwonlyargs=[]\n defaults=()\n annotations={}\n defaults=()\n kwdefaults={}\n \n if sig.return_annotation is not sig.empty:\n annotations['return']=sig.return_annotation\n \n for param in sig.parameters.values():\n kind=param.kind\n name=param.name\n \n if kind is _POSITIONAL_ONLY:\n args.append(name)\n elif kind is _POSITIONAL_OR_KEYWORD:\n args.append(name)\n if param.default is not param.empty:\n defaults +=(param.default,)\n elif kind is _VAR_POSITIONAL:\n varargs=name\n elif kind is _KEYWORD_ONLY:\n kwonlyargs.append(name)\n if param.default is not param.empty:\n kwdefaults[name]=param.default\n elif kind is _VAR_KEYWORD:\n varkw=name\n \n if param.annotation is not param.empty:\n annotations[name]=param.annotation\n \n if not kwdefaults:\n \n kwdefaults=None\n \n if not defaults:\n \n defaults=None\n \n return FullArgSpec(args,varargs,varkw,defaults,\n kwonlyargs,kwdefaults,annotations)\n \n \nArgInfo=namedtuple('ArgInfo','args varargs keywords locals')\n\ndef getargvalues(frame):\n ''\n\n\n\n\n \n args,varargs,varkw=getargs(frame.f_code)\n return ArgInfo(args,varargs,varkw,frame.f_locals)\n \ndef formatannotation(annotation,base_module=None ):\n if getattr(annotation,'__module__',None )=='typing':\n return repr(annotation).replace('typing.','')\n if isinstance(annotation,type):\n if annotation.__module__ in ('builtins',base_module):\n return annotation.__qualname__\n return annotation.__module__+'.'+annotation.__qualname__\n return repr(annotation)\n \ndef formatannotationrelativeto(object):\n module=getattr(object,'__module__',None )\n def _formatannotation(annotation):\n return formatannotation(annotation,module)\n return _formatannotation\n \ndef formatargspec(args,varargs=None ,varkw=None ,defaults=None ,\nkwonlyargs=(),kwonlydefaults={},annotations={},\nformatarg=str,\nformatvarargs=lambda name:'*'+name,\nformatvarkw=lambda name:'**'+name,\nformatvalue=lambda value:'='+repr(value),\nformatreturns=lambda text:' -> '+text,\nformatannotation=formatannotation):\n ''\n\n\n\n\n\n\n\n\n\n \n \n from warnings import warn\n \n warn(\"`formatargspec` is deprecated since Python 3.5. Use `signature` and \"\n \"the `Signature` object directly\",\n DeprecationWarning,\n stacklevel=2)\n \n def formatargandannotation(arg):\n result=formatarg(arg)\n if arg in annotations:\n result +=': '+formatannotation(annotations[arg])\n return result\n specs=[]\n if defaults:\n firstdefault=len(args)-len(defaults)\n for i,arg in enumerate(args):\n spec=formatargandannotation(arg)\n if defaults and i >=firstdefault:\n spec=spec+formatvalue(defaults[i -firstdefault])\n specs.append(spec)\n if varargs is not None :\n specs.append(formatvarargs(formatargandannotation(varargs)))\n else :\n if kwonlyargs:\n specs.append('*')\n if kwonlyargs:\n for kwonlyarg in kwonlyargs:\n spec=formatargandannotation(kwonlyarg)\n if kwonlydefaults and kwonlyarg in kwonlydefaults:\n spec +=formatvalue(kwonlydefaults[kwonlyarg])\n specs.append(spec)\n if varkw is not None :\n specs.append(formatvarkw(formatargandannotation(varkw)))\n result='('+', '.join(specs)+')'\n if 'return'in annotations:\n result +=formatreturns(formatannotation(annotations['return']))\n return result\n \ndef formatargvalues(args,varargs,varkw,locals,\nformatarg=str,\nformatvarargs=lambda name:'*'+name,\nformatvarkw=lambda name:'**'+name,\nformatvalue=lambda value:'='+repr(value)):\n ''\n\n\n\n\n \n def convert(name,locals=locals,\n formatarg=formatarg,formatvalue=formatvalue):\n return formatarg(name)+formatvalue(locals[name])\n specs=[]\n for i in range(len(args)):\n specs.append(convert(args[i]))\n if varargs:\n specs.append(formatvarargs(varargs)+formatvalue(locals[varargs]))\n if varkw:\n specs.append(formatvarkw(varkw)+formatvalue(locals[varkw]))\n return '('+', '.join(specs)+')'\n \ndef _missing_arguments(f_name,argnames,pos,values):\n names=[repr(name)for name in argnames if name not in values]\n missing=len(names)\n if missing ==1:\n s=names[0]\n elif missing ==2:\n s=\"{} and {}\".format(*names)\n else :\n tail=\", {} and {}\".format(*names[-2:])\n del names[-2:]\n s=\", \".join(names)+tail\n raise TypeError(\"%s() missing %i required %s argument%s: %s\"%\n (f_name,missing,\n \"positional\"if pos else \"keyword-only\",\n \"\"if missing ==1 else \"s\",s))\n \ndef _too_many(f_name,args,kwonly,varargs,defcount,given,values):\n atleast=len(args)-defcount\n kwonly_given=len([arg for arg in kwonly if arg in values])\n if varargs:\n plural=atleast !=1\n sig=\"at least %d\"%(atleast,)\n elif defcount:\n plural=True\n sig=\"from %d to %d\"%(atleast,len(args))\n else :\n plural=len(args)!=1\n sig=str(len(args))\n kwonly_sig=\"\"\n if kwonly_given:\n msg=\" positional argument%s (and %d keyword-only argument%s)\"\n kwonly_sig=(msg %(\"s\"if given !=1 else \"\",kwonly_given,\n \"s\"if kwonly_given !=1 else \"\"))\n raise TypeError(\"%s() takes %s positional argument%s but %d%s %s given\"%\n (f_name,sig,\"s\"if plural else \"\",given,kwonly_sig,\n \"was\"if given ==1 and not kwonly_given else \"were\"))\n \ndef getcallargs(*func_and_positional,**named):\n ''\n\n\n\n \n func=func_and_positional[0]\n positional=func_and_positional[1:]\n spec=getfullargspec(func)\n args,varargs,varkw,defaults,kwonlyargs,kwonlydefaults,ann=spec\n f_name=func.__name__\n arg2value={}\n \n \n if ismethod(func)and func.__self__ is not None :\n \n positional=(func.__self__,)+positional\n num_pos=len(positional)\n num_args=len(args)\n num_defaults=len(defaults)if defaults else 0\n \n n=min(num_pos,num_args)\n for i in range(n):\n arg2value[args[i]]=positional[i]\n if varargs:\n arg2value[varargs]=tuple(positional[n:])\n possible_kwargs=set(args+kwonlyargs)\n if varkw:\n arg2value[varkw]={}\n for kw,value in named.items():\n if kw not in possible_kwargs:\n if not varkw:\n raise TypeError(\"%s() got an unexpected keyword argument %r\"%\n (f_name,kw))\n arg2value[varkw][kw]=value\n continue\n if kw in arg2value:\n raise TypeError(\"%s() got multiple values for argument %r\"%\n (f_name,kw))\n arg2value[kw]=value\n if num_pos >num_args and not varargs:\n _too_many(f_name,args,kwonlyargs,varargs,num_defaults,\n num_pos,arg2value)\n if num_pos <num_args:\n req=args[:num_args -num_defaults]\n for arg in req:\n if arg not in arg2value:\n _missing_arguments(f_name,req,True ,arg2value)\n for i,arg in enumerate(args[num_args -num_defaults:]):\n if arg not in arg2value:\n arg2value[arg]=defaults[i]\n missing=0\n for kwarg in kwonlyargs:\n if kwarg not in arg2value:\n if kwonlydefaults and kwarg in kwonlydefaults:\n arg2value[kwarg]=kwonlydefaults[kwarg]\n else :\n missing +=1\n if missing:\n _missing_arguments(f_name,kwonlyargs,False ,arg2value)\n return arg2value\n \nClosureVars=namedtuple('ClosureVars','nonlocals globals builtins unbound')\n\ndef getclosurevars(func):\n ''\n\n\n\n\n\n \n \n if ismethod(func):\n func=func.__func__\n \n if not isfunction(func):\n raise TypeError(\"{!r} is not a Python function\".format(func))\n \n code=func.__code__\n \n \n if func.__closure__ is None :\n nonlocal_vars={}\n else :\n nonlocal_vars={\n var:cell.cell_contents\n for var,cell in zip(code.co_freevars,func.__closure__)\n }\n \n \n \n global_ns=func.__globals__\n builtin_ns=global_ns.get(\"__builtins__\",builtins.__dict__)\n if ismodule(builtin_ns):\n builtin_ns=builtin_ns.__dict__\n global_vars={}\n builtin_vars={}\n unbound_names=set()\n for name in code.co_names:\n if name in (\"None\",\"True\",\"False\"):\n \n \n continue\n try :\n global_vars[name]=global_ns[name]\n except KeyError:\n try :\n builtin_vars[name]=builtin_ns[name]\n except KeyError:\n unbound_names.add(name)\n \n return ClosureVars(nonlocal_vars,global_vars,\n builtin_vars,unbound_names)\n \n \n \nTraceback=namedtuple('Traceback','filename lineno function code_context index')\n\ndef getframeinfo(frame,context=1):\n ''\n\n\n\n\n\n \n if istraceback(frame):\n lineno=frame.tb_lineno\n frame=frame.tb_frame\n else :\n lineno=frame.f_lineno\n if not isframe(frame):\n raise TypeError('{!r} is not a frame or traceback object'.format(frame))\n \n filename=getsourcefile(frame)or getfile(frame)\n if context >0:\n start=lineno -1 -context //2\n try :\n lines,lnum=findsource(frame)\n except OSError:\n lines=index=None\n else :\n start=max(0,min(start,len(lines)-context))\n lines=lines[start:start+context]\n index=lineno -1 -start\n else :\n lines=index=None\n \n return Traceback(filename,lineno,frame.f_code.co_name,lines,index)\n \ndef getlineno(frame):\n ''\n \n return frame.f_lineno\n \nFrameInfo=namedtuple('FrameInfo',('frame',)+Traceback._fields)\n\ndef getouterframes(frame,context=1):\n ''\n\n\n \n framelist=[]\n while frame:\n frameinfo=(frame,)+getframeinfo(frame,context)\n framelist.append(FrameInfo(*frameinfo))\n frame=frame.f_back\n return framelist\n \ndef getinnerframes(tb,context=1):\n ''\n\n\n \n framelist=[]\n while tb:\n frameinfo=(tb.tb_frame,)+getframeinfo(tb,context)\n framelist.append(FrameInfo(*frameinfo))\n tb=tb.tb_next\n return framelist\n \ndef currentframe():\n ''\n return sys._getframe(1)if hasattr(sys,\"_getframe\")else None\n \ndef stack(context=1):\n ''\n return getouterframes(sys._getframe(1),context)\n \ndef trace(context=1):\n ''\n return getinnerframes(sys.exc_info()[2],context)\n \n \n \n \n_sentinel=object()\n\ndef _static_getmro(klass):\n return type.__dict__['__mro__'].__get__(klass)\n \ndef _check_instance(obj,attr):\n instance_dict={}\n try :\n instance_dict=object.__getattribute__(obj,\"__dict__\")\n except AttributeError:\n pass\n return dict.get(instance_dict,attr,_sentinel)\n \n \ndef _check_class(klass,attr):\n for entry in _static_getmro(klass):\n if _shadowed_dict(type(entry))is _sentinel:\n try :\n return entry.__dict__[attr]\n except KeyError:\n pass\n return _sentinel\n \ndef _is_type(obj):\n try :\n _static_getmro(obj)\n except TypeError:\n return False\n return True\n \ndef _shadowed_dict(klass):\n dict_attr=type.__dict__[\"__dict__\"]\n for entry in _static_getmro(klass):\n try :\n class_dict=dict_attr.__get__(entry)[\"__dict__\"]\n except KeyError:\n pass\n else :\n if not (type(class_dict)is types.GetSetDescriptorType and\n class_dict.__name__ ==\"__dict__\"and\n class_dict.__objclass__ is entry):\n return class_dict\n return _sentinel\n \ndef getattr_static(obj,attr,default=_sentinel):\n ''\n\n\n\n\n\n\n\n\n \n instance_result=_sentinel\n if not _is_type(obj):\n klass=type(obj)\n dict_attr=_shadowed_dict(klass)\n if (dict_attr is _sentinel or\n type(dict_attr)is types.MemberDescriptorType):\n instance_result=_check_instance(obj,attr)\n else :\n klass=obj\n \n klass_result=_check_class(klass,attr)\n \n if instance_result is not _sentinel and klass_result is not _sentinel:\n if (_check_class(type(klass_result),'__get__')is not _sentinel and\n _check_class(type(klass_result),'__set__')is not _sentinel):\n return klass_result\n \n if instance_result is not _sentinel:\n return instance_result\n if klass_result is not _sentinel:\n return klass_result\n \n if obj is klass:\n \n for entry in _static_getmro(type(klass)):\n if _shadowed_dict(type(entry))is _sentinel:\n try :\n return entry.__dict__[attr]\n except KeyError:\n pass\n if default is not _sentinel:\n return default\n raise AttributeError(attr)\n \n \n \n \nGEN_CREATED='GEN_CREATED'\nGEN_RUNNING='GEN_RUNNING'\nGEN_SUSPENDED='GEN_SUSPENDED'\nGEN_CLOSED='GEN_CLOSED'\n\ndef getgeneratorstate(generator):\n ''\n\n\n\n\n\n\n \n if generator.gi_running:\n return GEN_RUNNING\n if generator.gi_frame is None :\n return GEN_CLOSED\n if generator.gi_frame.f_lasti ==-1:\n return GEN_CREATED\n return GEN_SUSPENDED\n \n \ndef getgeneratorlocals(generator):\n ''\n\n\n\n \n \n if not isgenerator(generator):\n raise TypeError(\"{!r} is not a Python generator\".format(generator))\n \n frame=getattr(generator,\"gi_frame\",None )\n if frame is not None :\n return generator.gi_frame.f_locals\n else :\n return {}\n \n \n \n \nCORO_CREATED='CORO_CREATED'\nCORO_RUNNING='CORO_RUNNING'\nCORO_SUSPENDED='CORO_SUSPENDED'\nCORO_CLOSED='CORO_CLOSED'\n\ndef getcoroutinestate(coroutine):\n ''\n\n\n\n\n\n\n \n if coroutine.cr_running:\n return CORO_RUNNING\n if coroutine.cr_frame is None :\n return CORO_CLOSED\n if coroutine.cr_frame.f_lasti ==-1:\n return CORO_CREATED\n return CORO_SUSPENDED\n \n \ndef getcoroutinelocals(coroutine):\n ''\n\n\n\n \n frame=getattr(coroutine,\"cr_frame\",None )\n if frame is not None :\n return frame.f_locals\n else :\n return {}\n \n \n \n \n \n \n \n_WrapperDescriptor=type(type.__call__)\n_MethodWrapper=type(all.__call__)\n_ClassMethodWrapper=type(int.__dict__['from_bytes'])\n\n_NonUserDefinedCallables=(_WrapperDescriptor,\n_MethodWrapper,\n_ClassMethodWrapper,\ntypes.BuiltinFunctionType)\n\n\ndef _signature_get_user_defined_method(cls,method_name):\n ''\n\n\n \n try :\n meth=getattr(cls,method_name)\n except AttributeError:\n return\n else :\n if not isinstance(meth,_NonUserDefinedCallables):\n \n \n return meth\n \n \ndef _signature_get_partial(wrapped_sig,partial,extra_args=()):\n ''\n\n\n \n \n old_params=wrapped_sig.parameters\n new_params=OrderedDict(old_params.items())\n \n partial_args=partial.args or ()\n partial_keywords=partial.keywords or {}\n \n if extra_args:\n partial_args=extra_args+partial_args\n \n try :\n ba=wrapped_sig.bind_partial(*partial_args,**partial_keywords)\n except TypeError as ex:\n msg='partial object {!r} has incorrect arguments'.format(partial)\n raise ValueError(msg)from ex\n \n \n transform_to_kwonly=False\n for param_name,param in old_params.items():\n try :\n arg_value=ba.arguments[param_name]\n except KeyError:\n pass\n else :\n if param.kind is _POSITIONAL_ONLY:\n \n \n new_params.pop(param_name)\n continue\n \n if param.kind is _POSITIONAL_OR_KEYWORD:\n if param_name in partial_keywords:\n \n \n \n \n \n \n \n \n \n \n \n \n transform_to_kwonly=True\n \n new_params[param_name]=param.replace(default=arg_value)\n else :\n \n new_params.pop(param.name)\n continue\n \n if param.kind is _KEYWORD_ONLY:\n \n new_params[param_name]=param.replace(default=arg_value)\n \n if transform_to_kwonly:\n assert param.kind is not _POSITIONAL_ONLY\n \n if param.kind is _POSITIONAL_OR_KEYWORD:\n new_param=new_params[param_name].replace(kind=_KEYWORD_ONLY)\n new_params[param_name]=new_param\n new_params.move_to_end(param_name)\n elif param.kind in (_KEYWORD_ONLY,_VAR_KEYWORD):\n new_params.move_to_end(param_name)\n elif param.kind is _VAR_POSITIONAL:\n new_params.pop(param.name)\n \n return wrapped_sig.replace(parameters=new_params.values())\n \n \ndef _signature_bound_method(sig):\n ''\n\n \n \n params=tuple(sig.parameters.values())\n \n if not params or params[0].kind in (_VAR_KEYWORD,_KEYWORD_ONLY):\n raise ValueError('invalid method signature')\n \n kind=params[0].kind\n if kind in (_POSITIONAL_OR_KEYWORD,_POSITIONAL_ONLY):\n \n \n params=params[1:]\n else :\n if kind is not _VAR_POSITIONAL:\n \n \n raise ValueError('invalid argument type')\n \n \n \n return sig.replace(parameters=params)\n \n \ndef _signature_is_builtin(obj):\n ''\n\n \n return (isbuiltin(obj)or\n ismethoddescriptor(obj)or\n isinstance(obj,_NonUserDefinedCallables)or\n \n \n obj in (type,object))\n \n \ndef _signature_is_functionlike(obj):\n ''\n\n\n\n \n \n if not callable(obj)or isclass(obj):\n \n \n return False\n \n name=getattr(obj,'__name__',None )\n code=getattr(obj,'__code__',None )\n defaults=getattr(obj,'__defaults__',_void)\n kwdefaults=getattr(obj,'__kwdefaults__',_void)\n annotations=getattr(obj,'__annotations__',None )\n \n return (isinstance(code,types.CodeType)and\n isinstance(name,str)and\n (defaults is None or isinstance(defaults,tuple))and\n (kwdefaults is None or isinstance(kwdefaults,dict))and\n isinstance(annotations,dict))\n \n \ndef _signature_get_bound_param(spec):\n ''\n\n\n\n\n \n \n assert spec.startswith('($')\n \n pos=spec.find(',')\n if pos ==-1:\n pos=spec.find(')')\n \n cpos=spec.find(':')\n assert cpos ==-1 or cpos >pos\n \n cpos=spec.find('=')\n assert cpos ==-1 or cpos >pos\n \n return spec[2:pos]\n \n \ndef _signature_strip_non_python_syntax(signature):\n ''\n\n\n\n\n\n\n\n\n\n \n \n if not signature:\n return signature,None ,None\n \n self_parameter=None\n last_positional_only=None\n \n lines=[l.encode('ascii')for l in signature.split('\\n')]\n generator=iter(lines).__next__\n token_stream=tokenize.tokenize(generator)\n \n delayed_comma=False\n skip_next_comma=False\n text=[]\n add=text.append\n \n current_parameter=0\n OP=token.OP\n ERRORTOKEN=token.ERRORTOKEN\n \n \n t=next(token_stream)\n assert t.type ==tokenize.ENCODING\n \n for t in token_stream:\n type,string=t.type,t.string\n \n if type ==OP:\n if string ==',':\n if skip_next_comma:\n skip_next_comma=False\n else :\n assert not delayed_comma\n delayed_comma=True\n current_parameter +=1\n continue\n \n if string =='/':\n assert not skip_next_comma\n assert last_positional_only is None\n skip_next_comma=True\n last_positional_only=current_parameter -1\n continue\n \n if (type ==ERRORTOKEN)and (string =='$'):\n assert self_parameter is None\n self_parameter=current_parameter\n continue\n \n if delayed_comma:\n delayed_comma=False\n if not ((type ==OP)and (string ==')')):\n add(', ')\n add(string)\n if (string ==','):\n add(' ')\n clean_signature=''.join(text)\n return clean_signature,self_parameter,last_positional_only\n \n \ndef _signature_fromstr(cls,obj,s,skip_bound_arg=True ):\n ''\n\n \n \n \n import ast\n \n Parameter=cls._parameter_cls\n \n clean_signature,self_parameter,last_positional_only=\\\n _signature_strip_non_python_syntax(s)\n \n program=\"def foo\"+clean_signature+\": pass\"\n \n try :\n module=ast.parse(program)\n except SyntaxError:\n module=None\n \n if not isinstance(module,ast.Module):\n raise ValueError(\"{!r} builtin has invalid signature\".format(obj))\n \n f=module.body[0]\n \n parameters=[]\n empty=Parameter.empty\n invalid=object()\n \n module=None\n module_dict={}\n module_name=getattr(obj,'__module__',None )\n if module_name:\n module=sys.modules.get(module_name,None )\n if module:\n module_dict=module.__dict__\n sys_module_dict=sys.modules\n \n def parse_name(node):\n assert isinstance(node,ast.arg)\n if node.annotation !=None :\n raise ValueError(\"Annotations are not currently supported\")\n return node.arg\n \n def wrap_value(s):\n try :\n value=eval(s,module_dict)\n except NameError:\n try :\n value=eval(s,sys_module_dict)\n except NameError:\n raise RuntimeError()\n \n if isinstance(value,str):\n return ast.Str(value)\n if isinstance(value,(int,float)):\n return ast.Num(value)\n if isinstance(value,bytes):\n return ast.Bytes(value)\n if value in (True ,False ,None ):\n return ast.NameConstant(value)\n raise RuntimeError()\n \n class RewriteSymbolics(ast.NodeTransformer):\n def visit_Attribute(self,node):\n a=[]\n n=node\n while isinstance(n,ast.Attribute):\n a.append(n.attr)\n n=n.value\n if not isinstance(n,ast.Name):\n raise RuntimeError()\n a.append(n.id)\n value=\".\".join(reversed(a))\n return wrap_value(value)\n \n def visit_Name(self,node):\n if not isinstance(node.ctx,ast.Load):\n raise ValueError()\n return wrap_value(node.id)\n \n def p(name_node,default_node,default=empty):\n name=parse_name(name_node)\n if name is invalid:\n return None\n if default_node and default_node is not _empty:\n try :\n default_node=RewriteSymbolics().visit(default_node)\n o=ast.literal_eval(default_node)\n except ValueError:\n o=invalid\n if o is invalid:\n return None\n default=o if o is not invalid else default\n parameters.append(Parameter(name,kind,default=default,annotation=empty))\n \n \n args=reversed(f.args.args)\n defaults=reversed(f.args.defaults)\n iter=itertools.zip_longest(args,defaults,fillvalue=None )\n if last_positional_only is not None :\n kind=Parameter.POSITIONAL_ONLY\n else :\n kind=Parameter.POSITIONAL_OR_KEYWORD\n for i,(name,default)in enumerate(reversed(list(iter))):\n p(name,default)\n if i ==last_positional_only:\n kind=Parameter.POSITIONAL_OR_KEYWORD\n \n \n if f.args.vararg:\n kind=Parameter.VAR_POSITIONAL\n p(f.args.vararg,empty)\n \n \n kind=Parameter.KEYWORD_ONLY\n for name,default in zip(f.args.kwonlyargs,f.args.kw_defaults):\n p(name,default)\n \n \n if f.args.kwarg:\n kind=Parameter.VAR_KEYWORD\n p(f.args.kwarg,empty)\n \n if self_parameter is not None :\n \n \n \n \n \n assert parameters\n _self=getattr(obj,'__self__',None )\n self_isbound=_self is not None\n self_ismodule=ismodule(_self)\n if self_isbound and (self_ismodule or skip_bound_arg):\n parameters.pop(0)\n else :\n \n p=parameters[0].replace(kind=Parameter.POSITIONAL_ONLY)\n parameters[0]=p\n \n return cls(parameters,return_annotation=cls.empty)\n \n \ndef _signature_from_builtin(cls,func,skip_bound_arg=True ):\n ''\n\n \n \n if not _signature_is_builtin(func):\n raise TypeError(\"{!r} is not a Python builtin \"\n \"function\".format(func))\n \n s=getattr(func,\"__text_signature__\",None )\n if not s:\n raise ValueError(\"no signature found for builtin {!r}\".format(func))\n \n return _signature_fromstr(cls,func,s,skip_bound_arg)\n \n \ndef _signature_from_function(cls,func):\n ''\n \n is_duck_function=False\n if not isfunction(func):\n if _signature_is_functionlike(func):\n is_duck_function=True\n else :\n \n \n raise TypeError('{!r} is not a Python function'.format(func))\n \n Parameter=cls._parameter_cls\n \n \n func_code=func.__code__\n pos_count=func_code.co_argcount\n arg_names=func_code.co_varnames\n positional=tuple(arg_names[:pos_count])\n keyword_only_count=func_code.co_kwonlyargcount\n keyword_only=arg_names[pos_count:(pos_count+keyword_only_count)]\n annotations=func.__annotations__\n defaults=func.__defaults__\n kwdefaults=func.__kwdefaults__\n \n if defaults:\n pos_default_count=len(defaults)\n else :\n pos_default_count=0\n \n parameters=[]\n \n \n non_default_count=pos_count -pos_default_count\n for name in positional[:non_default_count]:\n annotation=annotations.get(name,_empty)\n parameters.append(Parameter(name,annotation=annotation,\n kind=_POSITIONAL_OR_KEYWORD))\n \n \n for offset,name in enumerate(positional[non_default_count:]):\n annotation=annotations.get(name,_empty)\n parameters.append(Parameter(name,annotation=annotation,\n kind=_POSITIONAL_OR_KEYWORD,\n default=defaults[offset]))\n \n \n if func_code.co_flags&CO_VARARGS:\n name=arg_names[pos_count+keyword_only_count]\n annotation=annotations.get(name,_empty)\n parameters.append(Parameter(name,annotation=annotation,\n kind=_VAR_POSITIONAL))\n \n \n for name in keyword_only:\n default=_empty\n if kwdefaults is not None :\n default=kwdefaults.get(name,_empty)\n \n annotation=annotations.get(name,_empty)\n parameters.append(Parameter(name,annotation=annotation,\n kind=_KEYWORD_ONLY,\n default=default))\n \n if func_code.co_flags&CO_VARKEYWORDS:\n index=pos_count+keyword_only_count\n if func_code.co_flags&CO_VARARGS:\n index +=1\n \n name=arg_names[index]\n annotation=annotations.get(name,_empty)\n parameters.append(Parameter(name,annotation=annotation,\n kind=_VAR_KEYWORD))\n \n \n \n return cls(parameters,\n return_annotation=annotations.get('return',_empty),\n __validate_parameters__=is_duck_function)\n \n \ndef _signature_from_callable(obj,*,\nfollow_wrapper_chains=True ,\nskip_bound_arg=True ,\nsigcls):\n\n ''\n\n \n \n if not callable(obj):\n raise TypeError('{!r} is not a callable object'.format(obj))\n \n if isinstance(obj,types.MethodType):\n \n \n sig=_signature_from_callable(\n obj.__func__,\n follow_wrapper_chains=follow_wrapper_chains,\n skip_bound_arg=skip_bound_arg,\n sigcls=sigcls)\n \n if skip_bound_arg:\n return _signature_bound_method(sig)\n else :\n return sig\n \n \n if follow_wrapper_chains:\n obj=unwrap(obj,stop=(lambda f:hasattr(f,\"__signature__\")))\n if isinstance(obj,types.MethodType):\n \n \n \n return _signature_from_callable(\n obj,\n follow_wrapper_chains=follow_wrapper_chains,\n skip_bound_arg=skip_bound_arg,\n sigcls=sigcls)\n \n try :\n sig=obj.__signature__\n except AttributeError:\n pass\n else :\n if sig is not None :\n if not isinstance(sig,Signature):\n raise TypeError(\n 'unexpected object {!r} in __signature__ '\n 'attribute'.format(sig))\n return sig\n \n try :\n partialmethod=obj._partialmethod\n except AttributeError:\n pass\n else :\n if isinstance(partialmethod,functools.partialmethod):\n \n \n \n \n \n \n \n wrapped_sig=_signature_from_callable(\n partialmethod.func,\n follow_wrapper_chains=follow_wrapper_chains,\n skip_bound_arg=skip_bound_arg,\n sigcls=sigcls)\n \n sig=_signature_get_partial(wrapped_sig,partialmethod,(None ,))\n first_wrapped_param=tuple(wrapped_sig.parameters.values())[0]\n if first_wrapped_param.kind is Parameter.VAR_POSITIONAL:\n \n \n return sig\n else :\n sig_params=tuple(sig.parameters.values())\n assert (not sig_params or\n first_wrapped_param is not sig_params[0])\n new_params=(first_wrapped_param,)+sig_params\n return sig.replace(parameters=new_params)\n \n if isfunction(obj)or _signature_is_functionlike(obj):\n \n \n return _signature_from_function(sigcls,obj)\n \n if _signature_is_builtin(obj):\n return _signature_from_builtin(sigcls,obj,\n skip_bound_arg=skip_bound_arg)\n \n if isinstance(obj,functools.partial):\n wrapped_sig=_signature_from_callable(\n obj.func,\n follow_wrapper_chains=follow_wrapper_chains,\n skip_bound_arg=skip_bound_arg,\n sigcls=sigcls)\n return _signature_get_partial(wrapped_sig,obj)\n \n sig=None\n if isinstance(obj,type):\n \n \n \n \n call=_signature_get_user_defined_method(type(obj),'__call__')\n if call is not None :\n sig=_signature_from_callable(\n call,\n follow_wrapper_chains=follow_wrapper_chains,\n skip_bound_arg=skip_bound_arg,\n sigcls=sigcls)\n else :\n \n new=_signature_get_user_defined_method(obj,'__new__')\n if new is not None :\n sig=_signature_from_callable(\n new,\n follow_wrapper_chains=follow_wrapper_chains,\n skip_bound_arg=skip_bound_arg,\n sigcls=sigcls)\n else :\n \n init=_signature_get_user_defined_method(obj,'__init__')\n if init is not None :\n sig=_signature_from_callable(\n init,\n follow_wrapper_chains=follow_wrapper_chains,\n skip_bound_arg=skip_bound_arg,\n sigcls=sigcls)\n \n if sig is None :\n \n \n \n for base in obj.__mro__[:-1]:\n \n \n \n \n \n \n \n try :\n text_sig=base.__text_signature__\n except AttributeError:\n pass\n else :\n if text_sig:\n \n \n return _signature_fromstr(sigcls,obj,text_sig)\n \n \n \n \n if type not in obj.__mro__:\n \n \n if (obj.__init__ is object.__init__ and\n obj.__new__ is object.__new__):\n \n return signature(object)\n else :\n raise ValueError(\n 'no signature found for builtin type {!r}'.format(obj))\n \n elif not isinstance(obj,_NonUserDefinedCallables):\n \n \n \n \n call=_signature_get_user_defined_method(type(obj),'__call__')\n if call is not None :\n try :\n sig=_signature_from_callable(\n call,\n follow_wrapper_chains=follow_wrapper_chains,\n skip_bound_arg=skip_bound_arg,\n sigcls=sigcls)\n except ValueError as ex:\n msg='no signature found for {!r}'.format(obj)\n raise ValueError(msg)from ex\n \n if sig is not None :\n \n \n if skip_bound_arg:\n return _signature_bound_method(sig)\n else :\n return sig\n \n if isinstance(obj,types.BuiltinFunctionType):\n \n msg='no signature found for builtin function {!r}'.format(obj)\n raise ValueError(msg)\n \n raise ValueError('callable {!r} is not supported by signature'.format(obj))\n \n \nclass _void:\n ''\n \n \nclass _empty:\n ''\n \n \nclass _ParameterKind(enum.IntEnum):\n POSITIONAL_ONLY=0\n POSITIONAL_OR_KEYWORD=1\n VAR_POSITIONAL=2\n KEYWORD_ONLY=3\n VAR_KEYWORD=4\n \n def __str__(self):\n return self._name_\n \n \n_POSITIONAL_ONLY=_ParameterKind.POSITIONAL_ONLY\n_POSITIONAL_OR_KEYWORD=_ParameterKind.POSITIONAL_OR_KEYWORD\n_VAR_POSITIONAL=_ParameterKind.VAR_POSITIONAL\n_KEYWORD_ONLY=_ParameterKind.KEYWORD_ONLY\n_VAR_KEYWORD=_ParameterKind.VAR_KEYWORD\n\n_PARAM_NAME_MAPPING={\n_POSITIONAL_ONLY:'positional-only',\n_POSITIONAL_OR_KEYWORD:'positional or keyword',\n_VAR_POSITIONAL:'variadic positional',\n_KEYWORD_ONLY:'keyword-only',\n_VAR_KEYWORD:'variadic keyword'\n}\n\n_get_paramkind_descr=_PARAM_NAME_MAPPING.__getitem__\n\n\nclass Parameter:\n ''\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n \n \n __slots__=('_name','_kind','_default','_annotation')\n \n POSITIONAL_ONLY=_POSITIONAL_ONLY\n POSITIONAL_OR_KEYWORD=_POSITIONAL_OR_KEYWORD\n VAR_POSITIONAL=_VAR_POSITIONAL\n KEYWORD_ONLY=_KEYWORD_ONLY\n VAR_KEYWORD=_VAR_KEYWORD\n \n empty=_empty\n \n def __init__(self,name,kind,*,default=_empty,annotation=_empty):\n try :\n self._kind=_ParameterKind(kind)\n except ValueError:\n raise ValueError(f'value {kind!r} is not a valid Parameter.kind')\n if default is not _empty:\n if self._kind in (_VAR_POSITIONAL,_VAR_KEYWORD):\n msg='{} parameters cannot have default values'\n msg=msg.format(_get_paramkind_descr(self._kind))\n raise ValueError(msg)\n self._default=default\n self._annotation=annotation\n \n if name is _empty:\n raise ValueError('name is a required attribute for Parameter')\n \n if not isinstance(name,str):\n msg='name must be a str, not a {}'.format(type(name).__name__)\n raise TypeError(msg)\n \n if name[0]=='.'and name[1:].isdigit():\n \n \n \n \n if self._kind !=_POSITIONAL_OR_KEYWORD:\n msg=(\n 'implicit arguments must be passed as '\n 'positional or keyword arguments, not {}'\n )\n msg=msg.format(_get_paramkind_descr(self._kind))\n raise ValueError(msg)\n self._kind=_POSITIONAL_ONLY\n name='implicit{}'.format(name[1:])\n \n if not name.isidentifier():\n raise ValueError('{!r} is not a valid parameter name'.format(name))\n \n self._name=name\n \n def __reduce__(self):\n return (type(self),\n (self._name,self._kind),\n {'_default':self._default,\n '_annotation':self._annotation})\n \n def __setstate__(self,state):\n self._default=state['_default']\n self._annotation=state['_annotation']\n \n @property\n def name(self):\n return self._name\n \n @property\n def default(self):\n return self._default\n \n @property\n def annotation(self):\n return self._annotation\n \n @property\n def kind(self):\n return self._kind\n \n def replace(self,*,name=_void,kind=_void,\n annotation=_void,default=_void):\n ''\n \n if name is _void:\n name=self._name\n \n if kind is _void:\n kind=self._kind\n \n if annotation is _void:\n annotation=self._annotation\n \n if default is _void:\n default=self._default\n \n return type(self)(name,kind,default=default,annotation=annotation)\n \n def __str__(self):\n kind=self.kind\n formatted=self._name\n \n \n if self._annotation is not _empty:\n formatted='{}: {}'.format(formatted,\n formatannotation(self._annotation))\n \n if self._default is not _empty:\n if self._annotation is not _empty:\n formatted='{} = {}'.format(formatted,repr(self._default))\n else :\n formatted='{}={}'.format(formatted,repr(self._default))\n \n if kind ==_VAR_POSITIONAL:\n formatted='*'+formatted\n elif kind ==_VAR_KEYWORD:\n formatted='**'+formatted\n \n return formatted\n \n def __repr__(self):\n return '<{} \"{}\">'.format(self.__class__.__name__,self)\n \n def __hash__(self):\n return hash((self.name,self.kind,self.annotation,self.default))\n \n def __eq__(self,other):\n if self is other:\n return True\n if not isinstance(other,Parameter):\n return NotImplemented\n return (self._name ==other._name and\n self._kind ==other._kind and\n self._default ==other._default and\n self._annotation ==other._annotation)\n \n \nclass BoundArguments:\n ''\n\n\n\n\n\n\n\n\n\n\n\n\n\n \n \n __slots__=('arguments','_signature','__weakref__')\n \n def __init__(self,signature,arguments):\n self.arguments=arguments\n self._signature=signature\n \n @property\n def signature(self):\n return self._signature\n \n @property\n def args(self):\n args=[]\n for param_name,param in self._signature.parameters.items():\n if param.kind in (_VAR_KEYWORD,_KEYWORD_ONLY):\n break\n \n try :\n arg=self.arguments[param_name]\n except KeyError:\n \n \n break\n else :\n if param.kind ==_VAR_POSITIONAL:\n \n args.extend(arg)\n else :\n \n args.append(arg)\n \n return tuple(args)\n \n @property\n def kwargs(self):\n kwargs={}\n kwargs_started=False\n for param_name,param in self._signature.parameters.items():\n if not kwargs_started:\n if param.kind in (_VAR_KEYWORD,_KEYWORD_ONLY):\n kwargs_started=True\n else :\n if param_name not in self.arguments:\n kwargs_started=True\n continue\n \n if not kwargs_started:\n continue\n \n try :\n arg=self.arguments[param_name]\n except KeyError:\n pass\n else :\n if param.kind ==_VAR_KEYWORD:\n \n kwargs.update(arg)\n else :\n \n kwargs[param_name]=arg\n \n return kwargs\n \n def apply_defaults(self):\n ''\n\n\n\n\n\n\n \n arguments=self.arguments\n new_arguments=[]\n for name,param in self._signature.parameters.items():\n try :\n new_arguments.append((name,arguments[name]))\n except KeyError:\n if param.default is not _empty:\n val=param.default\n elif param.kind is _VAR_POSITIONAL:\n val=()\n elif param.kind is _VAR_KEYWORD:\n val={}\n else :\n \n \n continue\n new_arguments.append((name,val))\n self.arguments=OrderedDict(new_arguments)\n \n def __eq__(self,other):\n if self is other:\n return True\n if not isinstance(other,BoundArguments):\n return NotImplemented\n return (self.signature ==other.signature and\n self.arguments ==other.arguments)\n \n def __setstate__(self,state):\n self._signature=state['_signature']\n self.arguments=state['arguments']\n \n def __getstate__(self):\n return {'_signature':self._signature,'arguments':self.arguments}\n \n def __repr__(self):\n args=[]\n for arg,value in self.arguments.items():\n args.append('{}={!r}'.format(arg,value))\n return '<{} ({})>'.format(self.__class__.__name__,', '.join(args))\n \n \nclass Signature:\n ''\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n \n \n __slots__=('_return_annotation','_parameters')\n \n _parameter_cls=Parameter\n _bound_arguments_cls=BoundArguments\n \n empty=_empty\n \n def __init__(self,parameters=None ,*,return_annotation=_empty,\n __validate_parameters__=True ):\n ''\n\n \n \n if parameters is None :\n params=OrderedDict()\n else :\n if __validate_parameters__:\n params=OrderedDict()\n top_kind=_POSITIONAL_ONLY\n kind_defaults=False\n \n for idx,param in enumerate(parameters):\n kind=param.kind\n name=param.name\n \n if kind <top_kind:\n msg=(\n 'wrong parameter order: {} parameter before {} '\n 'parameter'\n )\n msg=msg.format(_get_paramkind_descr(top_kind),\n _get_paramkind_descr(kind))\n raise ValueError(msg)\n elif kind >top_kind:\n kind_defaults=False\n top_kind=kind\n \n if kind in (_POSITIONAL_ONLY,_POSITIONAL_OR_KEYWORD):\n if param.default is _empty:\n if kind_defaults:\n \n \n \n msg='non-default argument follows default '\\\n 'argument'\n raise ValueError(msg)\n else :\n \n kind_defaults=True\n \n if name in params:\n msg='duplicate parameter name: {!r}'.format(name)\n raise ValueError(msg)\n \n params[name]=param\n else :\n params=OrderedDict(((param.name,param)\n for param in parameters))\n \n self._parameters=types.MappingProxyType(params)\n self._return_annotation=return_annotation\n \n @classmethod\n def from_function(cls,func):\n ''\n \n warnings.warn(\"inspect.Signature.from_function() is deprecated, \"\n \"use Signature.from_callable()\",\n DeprecationWarning,stacklevel=2)\n return _signature_from_function(cls,func)\n \n @classmethod\n def from_builtin(cls,func):\n ''\n \n warnings.warn(\"inspect.Signature.from_builtin() is deprecated, \"\n \"use Signature.from_callable()\",\n DeprecationWarning,stacklevel=2)\n return _signature_from_builtin(cls,func)\n \n @classmethod\n def from_callable(cls,obj,*,follow_wrapped=True ):\n ''\n return _signature_from_callable(obj,sigcls=cls,\n follow_wrapper_chains=follow_wrapped)\n \n @property\n def parameters(self):\n return self._parameters\n \n @property\n def return_annotation(self):\n return self._return_annotation\n \n def replace(self,*,parameters=_void,return_annotation=_void):\n ''\n\n\n \n \n if parameters is _void:\n parameters=self.parameters.values()\n \n if return_annotation is _void:\n return_annotation=self._return_annotation\n \n return type(self)(parameters,\n return_annotation=return_annotation)\n \n def _hash_basis(self):\n params=tuple(param for param in self.parameters.values()\n if param.kind !=_KEYWORD_ONLY)\n \n kwo_params={param.name:param for param in self.parameters.values()\n if param.kind ==_KEYWORD_ONLY}\n \n return params,kwo_params,self.return_annotation\n \n def __hash__(self):\n params,kwo_params,return_annotation=self._hash_basis()\n kwo_params=frozenset(kwo_params.values())\n return hash((params,kwo_params,return_annotation))\n \n def __eq__(self,other):\n if self is other:\n return True\n if not isinstance(other,Signature):\n return NotImplemented\n return self._hash_basis()==other._hash_basis()\n \n def _bind(self,args,kwargs,*,partial=False ):\n ''\n \n arguments=OrderedDict()\n \n parameters=iter(self.parameters.values())\n parameters_ex=()\n arg_vals=iter(args)\n \n while True :\n \n \n try :\n arg_val=next(arg_vals)\n except StopIteration:\n \n try :\n param=next(parameters)\n except StopIteration:\n \n \n break\n else :\n if param.kind ==_VAR_POSITIONAL:\n \n \n break\n elif param.name in kwargs:\n if param.kind ==_POSITIONAL_ONLY:\n msg='{arg!r} parameter is positional only, '\\\n 'but was passed as a keyword'\n msg=msg.format(arg=param.name)\n raise TypeError(msg)from None\n parameters_ex=(param,)\n break\n elif (param.kind ==_VAR_KEYWORD or\n param.default is not _empty):\n \n \n \n parameters_ex=(param,)\n break\n else :\n \n \n if partial:\n parameters_ex=(param,)\n break\n else :\n msg='missing a required argument: {arg!r}'\n msg=msg.format(arg=param.name)\n raise TypeError(msg)from None\n else :\n \n try :\n param=next(parameters)\n except StopIteration:\n raise TypeError('too many positional arguments')from None\n else :\n if param.kind in (_VAR_KEYWORD,_KEYWORD_ONLY):\n \n \n raise TypeError(\n 'too many positional arguments')from None\n \n if param.kind ==_VAR_POSITIONAL:\n \n \n \n values=[arg_val]\n values.extend(arg_vals)\n arguments[param.name]=tuple(values)\n break\n \n if param.name in kwargs:\n raise TypeError(\n 'multiple values for argument {arg!r}'.format(\n arg=param.name))from None\n \n arguments[param.name]=arg_val\n \n \n \n kwargs_param=None\n for param in itertools.chain(parameters_ex,parameters):\n if param.kind ==_VAR_KEYWORD:\n \n kwargs_param=param\n continue\n \n if param.kind ==_VAR_POSITIONAL:\n \n \n \n continue\n \n param_name=param.name\n try :\n arg_val=kwargs.pop(param_name)\n except KeyError:\n \n \n \n \n if (not partial and param.kind !=_VAR_POSITIONAL and\n param.default is _empty):\n raise TypeError('missing a required argument: {arg!r}'.\\\n format(arg=param_name))from None\n \n else :\n if param.kind ==_POSITIONAL_ONLY:\n \n \n \n raise TypeError('{arg!r} parameter is positional only, '\n 'but was passed as a keyword'.\\\n format(arg=param.name))\n \n arguments[param_name]=arg_val\n \n if kwargs:\n if kwargs_param is not None :\n \n arguments[kwargs_param.name]=kwargs\n else :\n raise TypeError(\n 'got an unexpected keyword argument {arg!r}'.format(\n arg=next(iter(kwargs))))\n \n return self._bound_arguments_cls(self,arguments)\n \n def bind(*args,**kwargs):\n ''\n\n\n \n return args[0]._bind(args[1:],kwargs)\n \n def bind_partial(*args,**kwargs):\n ''\n\n\n \n return args[0]._bind(args[1:],kwargs,partial=True )\n \n def __reduce__(self):\n return (type(self),\n (tuple(self._parameters.values()),),\n {'_return_annotation':self._return_annotation})\n \n def __setstate__(self,state):\n self._return_annotation=state['_return_annotation']\n \n def __repr__(self):\n return '<{} {}>'.format(self.__class__.__name__,self)\n \n def __str__(self):\n result=[]\n render_pos_only_separator=False\n render_kw_only_separator=True\n for param in self.parameters.values():\n formatted=str(param)\n \n kind=param.kind\n \n if kind ==_POSITIONAL_ONLY:\n render_pos_only_separator=True\n elif render_pos_only_separator:\n \n \n result.append('/')\n render_pos_only_separator=False\n \n if kind ==_VAR_POSITIONAL:\n \n \n render_kw_only_separator=False\n elif kind ==_KEYWORD_ONLY and render_kw_only_separator:\n \n \n \n result.append('*')\n \n \n render_kw_only_separator=False\n \n result.append(formatted)\n \n if render_pos_only_separator:\n \n \n result.append('/')\n \n rendered='({})'.format(', '.join(result))\n \n if self.return_annotation is not _empty:\n anno=formatannotation(self.return_annotation)\n rendered +=' -> {}'.format(anno)\n \n return rendered\n \n \ndef signature(obj,*,follow_wrapped=True ):\n ''\n return Signature.from_callable(obj,follow_wrapped=follow_wrapped)\n \n \ndef _main():\n ''\n import argparse\n import importlib\n \n parser=argparse.ArgumentParser()\n parser.add_argument(\n 'object',\n help=\"The object to be analysed. \"\n \"It supports the 'module:qualname' syntax\")\n parser.add_argument(\n '-d','--details',action='store_true',\n help='Display info about the module rather than its source code')\n \n args=parser.parse_args()\n \n target=args.object\n mod_name,has_attrs,attrs=target.partition(\":\")\n try :\n obj=module=importlib.import_module(mod_name)\n except Exception as exc:\n msg=\"Failed to import {} ({}: {})\".format(mod_name,\n type(exc).__name__,\n exc)\n print(msg,file=sys.stderr)\n exit(2)\n \n if has_attrs:\n parts=attrs.split(\".\")\n obj=module\n for part in parts:\n obj=getattr(obj,part)\n \n if module.__name__ in sys.builtin_module_names:\n print(\"Can't get info for builtin modules.\",file=sys.stderr)\n exit(1)\n \n if args.details:\n print('Target: {}'.format(target))\n print('Origin: {}'.format(getsourcefile(module)))\n print('Cached: {}'.format(module.__cached__))\n if obj is module:\n print('Loader: {}'.format(repr(module.__loader__)))\n if hasattr(module,'__path__'):\n print('Submodule search path: {}'.format(module.__path__))\n else :\n try :\n __,lineno=findsource(obj)\n except Exception:\n pass\n else :\n print('Line: {}'.format(lineno))\n \n print('\\n')\n else :\n print(getsource(obj))\n \n \nif __name__ ==\"__main__\":\n _main()\n", ["abc", "argparse", "ast", "builtins", "collections", "collections.abc", "dis", "enum", "functools", "importlib", "importlib.machinery", "itertools", "linecache", "operator", "os", "re", "sys", "token", "tokenize", "types", "warnings"]], "zlib": [".py", "from _zlib_utils import lz_generator\n\nclass BitIO:\n\n def __init__(self,bytestream=b''):\n self.bytestream=bytearray(bytestream)\n self.bytenum=0\n self.bitnum=0\n \n @property\n def pos(self):\n return self.bytenum *8+self.bitnum\n \n def read(self,nb,order=\"lsf\",trace=False ):\n result=0\n coef=1 if order ==\"lsf\"else 2 **(nb -1)\n for _ in range(nb):\n if self.bitnum ==8:\n if self.bytenum ==len(self.bytestream)-1:\n return None\n self.bytenum +=1\n self.bitnum=0\n mask=2 **self.bitnum\n if trace:\n print(\"bit\",int(bool(mask&self.bytestream[self.bytenum])))\n result +=coef *bool(mask&self.bytestream[self.bytenum])\n self.bitnum +=1\n if order ==\"lsf\":\n coef *=2\n else :\n coef //=2\n return result\n \n def move(self,nb):\n if nb ==0:\n return\n elif nb >0:\n bitpos=self.bitnum+nb\n while bitpos >7:\n self.bytenum +=1\n if self.bytenum ==len(self.bytestream):\n raise Exception(\"can't move {} bits\".format(nb))\n bitpos -=8\n self.bitnum=bitpos\n else :\n bitpos=self.bitnum+nb\n while bitpos <0:\n self.bytenum -=1\n if self.bytenum ==-1:\n raise Exception(\"can't move {} bits\".format(nb))\n bitpos +=8\n self.bitnum=bitpos\n \n def show(self):\n res=\"\"\n for x in self.bytestream:\n s=str(bin(x))[2:]\n s=\"0\"*(8 -len(s))+s\n res +=s+\" \"\n return res\n \n def write(self,*bits):\n for bit in bits:\n if not self.bytestream:\n self.bytestream.append(0)\n byte=self.bytestream[self.bytenum]\n if self.bitnum ==8:\n if self.bytenum ==len(self.bytestream)-1:\n byte=0\n self.bytestream +=bytes([byte])\n self.bytenum +=1\n self.bitnum=0\n mask=2 **self.bitnum\n if bit:\n byte |=mask\n else :\n byte &=~mask\n self.bytestream[self.bytenum]=byte\n self.bitnum +=1\n \n def write_int(self,value,nb,order=\"lsf\"):\n ''\n if value >=2 **nb:\n raise ValueError(\"can't write value on {} bits\".format(nb))\n bits=[]\n while value:\n bits.append(value&1)\n value >>=1\n \n bits=bits+[0]*(nb -len(bits))\n if order !=\"lsf\":\n bits.reverse()\n assert len(bits)==nb\n self.write(*bits)\n \nclass ResizeError(Exception):\n pass\n \n \nclass Node:\n\n def __init__(self,char=None ,weight=0,level=0):\n self.char=char\n self.is_leaf=char is not None\n self.level=level\n self.weight=weight\n \n def add(self,children):\n self.children=children\n for child in self.children:\n child.parent=self\n child.level=self.level+1\n \n \nclass Tree:\n\n def __init__(self,root):\n self.root=root\n \n def length(self):\n self.root.level=0\n node=self.root\n nb_levels=0\n def set_level(node):\n nonlocal nb_levels\n for child in node.children:\n child.level=node.level+1\n nb_levels=max(nb_levels,child.level)\n if not child.is_leaf:\n set_level(child)\n set_level(self.root)\n return nb_levels\n \n def reduce_tree(self):\n ''\n\n\n \n currentlen=self.length()\n deepest=self.nodes_at(currentlen)\n deepest_leaves=[node for node in deepest if node.is_leaf]\n rightmost_leaf=deepest_leaves[-1]\n sibling=rightmost_leaf.parent.children[0]\n \n \n parent=rightmost_leaf.parent\n grand_parent=parent.parent\n rank=grand_parent.children.index(parent)\n children=grand_parent.children\n children[rank]=rightmost_leaf\n grand_parent.add(children)\n \n \n up_level=rightmost_leaf.level -2\n while up_level >0:\n nodes=self.nodes_at(up_level)\n leaf_nodes=[node for node in nodes if node.is_leaf]\n if leaf_nodes:\n leftmost_leaf=leaf_nodes[0]\n \n parent=leftmost_leaf.parent\n rank=parent.children.index(leftmost_leaf)\n new_node=Node()\n new_node.level=leftmost_leaf.level\n children=[sibling,leftmost_leaf]\n new_node.add(children)\n parent.children[rank]=new_node\n new_node.parent=parent\n break\n else :\n up_level -=1\n if up_level ==0:\n raise ResizeError\n \n def nodes_at(self,level,top=None ):\n ''\n res=[]\n if top is None :\n top=self.root\n if top.level ==level:\n res=[top]\n elif not top.is_leaf:\n for child in top.children:\n res +=self.nodes_at(level,child)\n return res\n \n def reduce(self,maxlevels):\n ''\n while self.length()>maxlevels:\n self.reduce_tree()\n \n def codes(self,node=None ,code=''):\n ''\n \n if node is None :\n self.dic={}\n node=self.root\n if node.is_leaf:\n self.dic[node.char]=code\n else :\n for i,child in enumerate(node.children):\n self.codes(child,code+str(i))\n return self.dic\n \n \ndef codelengths_from_frequencies(freqs):\n ''\n\n\n\n \n freqs=sorted(freqs.items(),\n key=lambda item:(item[1],-item[0]),reverse=True )\n nodes=[Node(char=key,weight=value)for (key,value)in freqs]\n while len(nodes)>1:\n right,left=nodes.pop(),nodes.pop()\n node=Node(weight=right.weight+left.weight)\n node.add([left,right])\n if not nodes:\n nodes.append(node)\n else :\n pos=0\n while pos <len(nodes)and nodes[pos].weight >node.weight:\n pos +=1\n nodes.insert(pos,node)\n \n top=nodes[0]\n tree=Tree(top)\n tree.reduce(15)\n \n codes=tree.codes()\n \n code_items=list(codes.items())\n code_items.sort(key=lambda item:(len(item[1]),item[0]))\n return [(car,len(value))for car,value in code_items]\n \ndef normalized(codelengths):\n car,codelength=codelengths[0]\n value=0\n codes={car:\"0\"*codelength}\n \n for (newcar,nbits)in codelengths[1:]:\n value +=1\n bvalue=str(bin(value))[2:]\n bvalue=\"0\"*(codelength -len(bvalue))+bvalue\n if nbits >codelength:\n codelength=nbits\n bvalue +=\"0\"*(codelength -len(bvalue))\n value=int(bvalue,2)\n assert len(bvalue)==nbits\n codes[newcar]=bvalue\n \n return codes\n \ndef make_tree(node,codes):\n if not hasattr(node,\"parent\"):\n node.code=''\n children=[]\n for bit in '01':\n next_code=node.code+bit\n if next_code in codes:\n child=Node(char=codes[next_code])\n else :\n child=Node()\n child.code=next_code\n children.append(child)\n node.add(children)\n for child in children:\n if not child.is_leaf:\n make_tree(child,codes)\n \ndef decompresser(codelengths):\n lengths=list(codelengths.items())\n \n lengths=[x for x in lengths if x[1]>0]\n lengths.sort(key=lambda item:(item[1],item[0]))\n codes=normalized(lengths)\n codes={value:key for key,value in codes.items()}\n root=Node()\n make_tree(root,codes)\n return {\"root\":root,\"codes\":codes}\n \ndef tree_from_codelengths(codelengths):\n return decompresser(codelengths)[\"root\"]\n \nclass Error(Exception):\n pass\n \n \nfixed_codelengths={}\nfor car in range(144):\n fixed_codelengths[car]=8\nfor car in range(144,256):\n fixed_codelengths[car]=9\nfor car in range(256,280):\n fixed_codelengths[car]=7\nfor car in range(280,288):\n fixed_codelengths[car]=8\n \nfixed_decomp=decompresser(fixed_codelengths)\nfixed_lit_len_tree=fixed_decomp[\"root\"]\nfixed_lit_len_codes={value:key\nfor (key,value)in fixed_decomp[\"codes\"].items()}\n\ndef cl_encode(lengths):\n ''\n \n dic={char:len(code)for (char,code)in lengths.items()}\n items=[dic.get(i,0)for i in range(max(dic)+1)]\n pos=0\n while pos <len(items):\n if items[pos]==0:\n \n i=pos+1\n while i <len(items)and items[i]==0:\n i +=1\n if i -pos <3:\n for i in range(pos,i):\n yield items[i]\n pos=i+1\n else :\n repeat=i -pos\n if repeat <11:\n yield (17,repeat -3)\n else :\n yield (18,repeat -11)\n pos=i\n else :\n item=items[pos]\n yield item\n i=pos+1\n while i <len(items)and items[i]==item:\n i +=1\n repeat=i -pos -1\n if repeat <3:\n for i in range(repeat):\n yield item\n else :\n nb=repeat -3\n while nb >3:\n yield (16,3)\n nb -=3\n yield (16,nb)\n pos +=repeat+1\n \ndef read_codelengths(reader,root,num):\n ''\n\n \n node=root\n lengths=[]\n nb=0\n while len(lengths)<num:\n code=reader.read(1)\n child=node.children[code]\n if child.is_leaf:\n if child.char <16:\n lengths.append(child.char)\n elif child.char ==16:\n repeat=3+reader.read(2)\n lengths +=[lengths[-1]]*repeat\n elif child.char ==17:\n repeat=3+reader.read(3)\n lengths +=[0]*repeat\n elif child.char ==18:\n repeat=11+reader.read(7)\n lengths +=[0]*repeat\n node=root\n else :\n node=child\n return lengths\n \ndef dynamic_trees(reader):\n ''\n \n HLIT=reader.read(5)\n HDIST=reader.read(5)\n HCLEN=reader.read(4)\n \n alphabet=(16,17,18,0,8,7,9,6,10,5,11,4,12,3,13,2,14,1,\n 15)\n clen={}\n c=[]\n for i,length in zip(range(HCLEN+4),alphabet):\n c.append(reader.read(3))\n clen[length]=c[-1]\n \n \n clen_root=tree_from_codelengths(clen)\n \n \n lit_len=read_codelengths(reader,clen_root,HLIT+257)\n lit_len_tree=tree_from_codelengths(dict(enumerate(lit_len)))\n \n \n distances=read_codelengths(reader,clen_root,HDIST+1)\n distances_tree=tree_from_codelengths(dict(enumerate(distances)))\n \n return lit_len_tree,distances_tree\n \ndef read_distance(reader,root):\n ''\n node=root\n \n while True :\n code=reader.read(1)\n child=node.children[code]\n if child.is_leaf:\n dist_code=child.char\n if dist_code <3:\n distance=dist_code+1\n else :\n nb=(dist_code //2)-1\n extra=reader.read(nb)\n half,delta=divmod(dist_code,2)\n distance=1+(2 **half)+delta *(2 **(half -1))+extra\n return distance\n else :\n node=child\n \ndef distance_to_code(distance):\n if distance <5:\n return (distance -1,0,0)\n else :\n d=distance\n coef=2\n p=2\n while 2 **(p+1)<d:\n p +=1\n d0=2 **p+1\n a,b=divmod(d -d0,2 **(p -1))\n return 2 *p+a,b,p -1\n \ndef length_to_code(length):\n if length <11:\n return (254+length,0,0)\n elif length <19:\n a,b=divmod(length -11,2)\n return (265+a,b,1)\n elif length <35:\n a,b=divmod(length -19,4)\n return (269+a,b,2)\n elif length <67:\n a,b=divmod(length -35,8)\n return (273+a,b,3)\n elif length <131:\n a,b=divmod(length -67,16)\n return (277+a,b,4)\n elif length <258:\n a,b=divmod(length -131,32)\n return (281+a,b,5)\n elif length ==258:\n return (285,0,0)\n \ndef read_literal_or_length(reader,root):\n node=root\n \n while True :\n code=reader.read(1)\n child=node.children[code]\n if child.is_leaf:\n if child.char <256:\n \n return (\"literal\",child.char)\n elif child.char ==256:\n return (\"eob\",None )\n elif child.char >256:\n \n if child.char <265:\n length=child.char -254\n elif child.char <269:\n length=11+2 *(child.char -265)+reader.read(1)\n elif child.char <273:\n length=19+4 *(child.char -269)+reader.read(2)\n elif child.char <277:\n length=35+8 *(child.char -273)+reader.read(3)\n elif child.char <281:\n length=67+16 *(child.char -277)+reader.read(4)\n elif child.char <285:\n length=131+31 *(child.char -281)+reader.read(5)\n elif child.char ==285:\n length=258\n return (\"length\",length)\n else :\n node=child\n \ndef adler32(source):\n a=1\n b=0\n for byte in source:\n a +=byte\n a %=65521\n b +=a\n b %=65521\n return a,b\n \n \ndef compress_dynamic(out,source,store,lit_len_count,distance_count):\n\n\n lit_len_count[256]=1\n \n \n \n \n \n \n lit_len_codes=normalized(codelengths_from_frequencies(lit_len_count))\n HLIT=1+max(lit_len_codes)-257\n \n \n \n \n \n \n coded_lit_len=list(cl_encode(lit_len_codes))\n \n \n distance_codes=normalized(codelengths_from_frequencies(distance_count))\n HDIST=max(distance_codes)\n coded_distance=list(cl_encode(distance_codes))\n \n \n codelengths_count={}\n for coded in coded_lit_len,coded_distance:\n for item in coded:\n length=item[0]if isinstance(item,tuple)else item\n codelengths_count[length]=codelengths_count.get(length,0)+1\n \n \n codelengths_codes=normalized(\n codelengths_from_frequencies(codelengths_count))\n codelengths_dict={char:len(value)\n for (char,value)in codelengths_codes.items()}\n \n alphabet=(16,17,18,0,8,7,9,6,10,5,11,4,12,3,13,2,14,1,\n 15)\n \n \n codelengths_list=[codelengths_dict.get(car,0)for car in alphabet]\n \n while codelengths_list[-1]==0:\n codelengths_list.pop()\n HCLEN=len(codelengths_list)-4\n \n out.write(0,1)\n \n out.write_int(HLIT,5)\n out.write_int(HDIST,5)\n out.write_int(HCLEN,4)\n \n \n for length,car in zip(codelengths_list,alphabet):\n out.write_int(length,3)\n \n \n for item in coded_lit_len+coded_distance:\n if isinstance(item,tuple):\n length,extra=item\n code=codelengths_codes[length]\n value,nbits=int(code,2),len(code)\n out.write_int(value,nbits,order=\"msf\")\n if length ==16:\n out.write_int(extra,2)\n elif length ==17:\n out.write_int(extra,3)\n elif length ==18:\n out.write_int(extra,7)\n else :\n code=codelengths_codes[item]\n value,nbits=int(code,2),len(code)\n out.write_int(value,nbits,order=\"msf\")\n \n \n for item in store:\n if isinstance(item,tuple):\n length,extra_length,distance,extra_distance=item\n \n code=lit_len_codes[length]\n value,nb=int(code,2),len(code)\n out.write_int(value,nb,order=\"msf\")\n \n value,nb=extra_length\n if nb:\n out.write_int(value,nb)\n \n code=distance_codes[distance]\n value,nb=int(code,2),len(code)\n out.write_int(value,nb,order=\"msf\")\n \n value,nb=extra_distance\n if nb:\n out.write_int(value,nb)\n else :\n literal=item\n code=lit_len_codes[item]\n value,nb=int(code,2),len(code)\n out.write_int(value,nb,order=\"msf\")\n \ndef compress_fixed(out,source,items):\n ''\n print(\"fixed\",items)\n out.write(1,0)\n \n for item in items:\n if isinstance(item,tuple):\n length,extra_length,distance,extra_distance=item\n \n code=fixed_lit_len_codes[length]\n value,nb=int(code,2),len(code)\n out.write_int(value,nb,order=\"msf\")\n \n value,nb=extra_length\n if nb:\n out.write_int(value,nb)\n \n out.write_int(distance,5,order=\"msf\")\n \n value,nb=extra_distance\n if nb:\n out.write_int(value,nb)\n else :\n literal=item\n code=fixed_lit_len_codes[item]\n value,nb=int(code,2),len(code)\n out.write_int(value,nb,order=\"msf\")\n \ndef compress(source,window_size=32 *1024):\n\n\n\n lit_len_count={}\n \n \n distance_count={}\n \n store=[]\n replaced=0\n nb_tuples=0\n \n for item in lz_generator(source,window_size):\n if isinstance(item,tuple):\n nb_tuples +=1\n length,distance=item\n replaced +=length\n \n \n length_code,*extra_length=length_to_code(length)\n \n lit_len_count[length_code]=lit_len_count.get(length_code,0)+1\n \n \n \n distance_code,*extra_dist=distance_to_code(distance)\n \n distance_count[distance_code]=\\\n distance_count.get(distance_code,0)+1\n \n \n store.append((length_code,extra_length,distance_code,\n extra_dist))\n else :\n literal=item\n lit_len_count[literal]=lit_len_count.get(literal,0)+1\n store.append(literal)\n \n store.append(256)\n \n \n \n \n score=replaced -100 -(nb_tuples *20 //8)\n \n \n out=BitIO()\n \n \n out.write_int(8,4)\n size=window_size >>8\n nb=0\n while size >1:\n size >>=1\n nb +=1\n out.write_int(nb,4)\n out.write_int(0x9c,8)\n \n out.write(1)\n \n if score <0:\n compress_fixed(out,source,store)\n else :\n compress_dynamic(out,source,store,lit_len_count,distance_count)\n \n \n while out.bitnum !=8:\n out.write(0)\n \n \n a,b=adler32(source)\n a1,a2=divmod(a,256)\n b1,b2=divmod(b,256)\n out.write_int(b1,8)\n out.write_int(b2,8)\n out.write_int(a1,8)\n out.write_int(a2,8)\n \n return bytes(out.bytestream)\n \ndef decompress(buf):\n reader=BitIO(buf)\n \n CM=reader.read(4)\n if CM !=8:\n raise Error(\"unsupported compression method: {}\".format(CM))\n \n CINFO=reader.read(4)\n \n FLG=reader.read(8)\n \n result=bytearray()\n \n while True :\n BFINAL=reader.read(1)\n \n BTYPE=reader.read(2)\n \n if BTYPE ==0b01:\n \n \n root=fixed_lit_len_tree\n \n while True :\n \n _type,value=read_literal_or_length(reader,root)\n if _type =='eob':\n break\n elif _type =='literal':\n result.append(value)\n elif _type =='length':\n length=value\n \n dist_code=reader.read(5,\"msf\")\n if dist_code <3:\n distance=dist_code+1\n else :\n nb=(dist_code //2)-1\n extra=reader.read(nb)\n half,delta=divmod(dist_code,2)\n distance=(1+(2 **half)+\n delta *(2 **(half -1))+extra)\n for _ in range(length):\n result.append(result[-distance])\n \n node=root\n else :\n node=child\n \n elif BTYPE ==0b10:\n \n \n \n lit_len_tree,distance_tree=dynamic_trees(reader)\n \n while True :\n \n _type,value=read_literal_or_length(reader,lit_len_tree)\n if _type =='eob':\n break\n elif _type =='literal':\n result.append(value)\n elif _type =='length':\n \n length=value\n distance=read_distance(reader,distance_tree)\n for _ in range(length):\n result.append(result[-distance])\n \n if BFINAL:\n \n b1=256 *buf[-4]+buf[-3]\n a1=256 *buf[-2]+buf[-1]\n \n a,b=adler32(result)\n \n assert a ==a1\n assert b ==b1\n \n return bytes(result)\n", ["_zlib_utils"]], "textwrap": [".py", "''\n\n\n\n\n\n\nimport re\n\n__all__=['TextWrapper','wrap','fill','dedent','indent','shorten']\n\n\n\n\n_whitespace='\\t\\n\\x0b\\x0c\\r '\n\nclass TextWrapper:\n ''\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n \n \n unicode_whitespace_trans={}\n uspace=ord(' ')\n for x in _whitespace:\n unicode_whitespace_trans[ord(x)]=uspace\n \n \n \n \n \n \n \n word_punct=r'[\\w!\"\\'&.,?]'\n letter=r'[^\\d\\W]'\n whitespace=r'[%s]'%re.escape(_whitespace)\n nowhitespace='[^'+whitespace[1:]\n wordsep_re=re.compile(r'''\n ( # any whitespace\n %(ws)s+\n | # em-dash between words\n (?<=%(wp)s) -{2,} (?=\\w)\n | # word, possibly hyphenated\n %(nws)s+? (?:\n # hyphenated word\n -(?: (?<=%(lt)s{2}-) | (?<=%(lt)s-%(lt)s-))\n (?= %(lt)s -? %(lt)s)\n | # end of word\n (?=%(ws)s|\\Z)\n | # em-dash\n (?<=%(wp)s) (?=-{2,}\\w)\n )\n )'''%{'wp':word_punct,'lt':letter,\n 'ws':whitespace,'nws':nowhitespace},\n re.VERBOSE)\n del word_punct,letter,nowhitespace\n \n \n \n \n \n wordsep_simple_re=re.compile(r'(%s+)'%whitespace)\n del whitespace\n \n \n \n sentence_end_re=re.compile(r'[a-z]'\n r'[\\.\\!\\?]'\n r'[\\\"\\']?'\n r'\\Z')\n \n def __init__(self,\n width=70,\n initial_indent=\"\",\n subsequent_indent=\"\",\n expand_tabs=True ,\n replace_whitespace=True ,\n fix_sentence_endings=False ,\n break_long_words=True ,\n drop_whitespace=True ,\n break_on_hyphens=True ,\n tabsize=8,\n *,\n max_lines=None ,\n placeholder=' [...]'):\n self.width=width\n self.initial_indent=initial_indent\n self.subsequent_indent=subsequent_indent\n self.expand_tabs=expand_tabs\n self.replace_whitespace=replace_whitespace\n self.fix_sentence_endings=fix_sentence_endings\n self.break_long_words=break_long_words\n self.drop_whitespace=drop_whitespace\n self.break_on_hyphens=break_on_hyphens\n self.tabsize=tabsize\n self.max_lines=max_lines\n self.placeholder=placeholder\n \n \n \n \n \n def _munge_whitespace(self,text):\n ''\n\n\n\n\n \n if self.expand_tabs:\n text=text.expandtabs(self.tabsize)\n if self.replace_whitespace:\n text=text.translate(self.unicode_whitespace_trans)\n return text\n \n \n def _split(self,text):\n ''\n\n\n\n\n\n\n\n\n\n\n\n\n \n if self.break_on_hyphens is True :\n chunks=self.wordsep_re.split(text)\n else :\n chunks=self.wordsep_simple_re.split(text)\n chunks=[c for c in chunks if c]\n return chunks\n \n def _fix_sentence_endings(self,chunks):\n ''\n\n\n\n\n\n\n \n i=0\n patsearch=self.sentence_end_re.search\n while i <len(chunks)-1:\n if chunks[i+1]==\" \"and patsearch(chunks[i]):\n chunks[i+1]=\" \"\n i +=2\n else :\n i +=1\n \n def _handle_long_word(self,reversed_chunks,cur_line,cur_len,width):\n ''\n\n\n\n\n\n \n \n \n if width <1:\n space_left=1\n else :\n space_left=width -cur_len\n \n \n \n if self.break_long_words:\n cur_line.append(reversed_chunks[-1][:space_left])\n reversed_chunks[-1]=reversed_chunks[-1][space_left:]\n \n \n \n \n elif not cur_line:\n cur_line.append(reversed_chunks.pop())\n \n \n \n \n \n \n \n def _wrap_chunks(self,chunks):\n ''\n\n\n\n\n\n\n\n\n\n\n \n lines=[]\n if self.width <=0:\n raise ValueError(\"invalid width %r (must be > 0)\"%self.width)\n if self.max_lines is not None :\n if self.max_lines >1:\n indent=self.subsequent_indent\n else :\n indent=self.initial_indent\n if len(indent)+len(self.placeholder.lstrip())>self.width:\n raise ValueError(\"placeholder too large for max width\")\n \n \n \n chunks.reverse()\n \n while chunks:\n \n \n \n cur_line=[]\n cur_len=0\n \n \n if lines:\n indent=self.subsequent_indent\n else :\n indent=self.initial_indent\n \n \n width=self.width -len(indent)\n \n \n \n if self.drop_whitespace and chunks[-1].strip()==''and lines:\n del chunks[-1]\n \n while chunks:\n l=len(chunks[-1])\n \n \n if cur_len+l <=width:\n cur_line.append(chunks.pop())\n cur_len +=l\n \n \n else :\n break\n \n \n \n if chunks and len(chunks[-1])>width:\n self._handle_long_word(chunks,cur_line,cur_len,width)\n cur_len=sum(map(len,cur_line))\n \n \n if self.drop_whitespace and cur_line and cur_line[-1].strip()=='':\n cur_len -=len(cur_line[-1])\n del cur_line[-1]\n \n if cur_line:\n if (self.max_lines is None or\n len(lines)+1 <self.max_lines or\n (not chunks or\n self.drop_whitespace and\n len(chunks)==1 and\n not chunks[0].strip())and cur_len <=width):\n \n \n lines.append(indent+''.join(cur_line))\n else :\n while cur_line:\n if (cur_line[-1].strip()and\n cur_len+len(self.placeholder)<=width):\n cur_line.append(self.placeholder)\n lines.append(indent+''.join(cur_line))\n break\n cur_len -=len(cur_line[-1])\n del cur_line[-1]\n else :\n if lines:\n prev_line=lines[-1].rstrip()\n if (len(prev_line)+len(self.placeholder)<=\n self.width):\n lines[-1]=prev_line+self.placeholder\n break\n lines.append(indent+self.placeholder.lstrip())\n break\n \n return lines\n \n def _split_chunks(self,text):\n text=self._munge_whitespace(text)\n return self._split(text)\n \n \n \n def wrap(self,text):\n ''\n\n\n\n\n\n\n \n chunks=self._split_chunks(text)\n if self.fix_sentence_endings:\n self._fix_sentence_endings(chunks)\n return self._wrap_chunks(chunks)\n \n def fill(self,text):\n ''\n\n\n\n\n \n return \"\\n\".join(self.wrap(text))\n \n \n \n \ndef wrap(text,width=70,**kwargs):\n ''\n\n\n\n\n\n\n\n \n w=TextWrapper(width=width,**kwargs)\n return w.wrap(text)\n \ndef fill(text,width=70,**kwargs):\n ''\n\n\n\n\n\n\n \n w=TextWrapper(width=width,**kwargs)\n return w.fill(text)\n \ndef shorten(text,width,**kwargs):\n ''\n\n\n\n\n\n\n\n\n\n \n w=TextWrapper(width=width,max_lines=1,**kwargs)\n return w.fill(' '.join(text.strip().split()))\n \n \n \n \n_whitespace_only_re=re.compile('^[ \\t]+$',re.MULTILINE)\n_leading_whitespace_re=re.compile('(^[ \\t]*)(?:[^ \\t\\n])',re.MULTILINE)\n\ndef dedent(text):\n ''\n\n\n\n\n\n\n\n\n\n\n \n \n \n margin=None\n text=_whitespace_only_re.sub('',text)\n indents=_leading_whitespace_re.findall(text)\n for indent in indents:\n if margin is None :\n margin=indent\n \n \n \n elif indent.startswith(margin):\n pass\n \n \n \n elif margin.startswith(indent):\n margin=indent\n \n \n \n else :\n for i,(x,y)in enumerate(zip(margin,indent)):\n if x !=y:\n margin=margin[:i]\n break\n \n \n if 0 and margin:\n for line in text.split(\"\\n\"):\n assert not line or line.startswith(margin),\\\n \"line = %r, margin = %r\"%(line,margin)\n \n if margin:\n text=re.sub(r'(?m)^'+margin,'',text)\n return text\n \n \ndef indent(text,prefix,predicate=None ):\n ''\n\n\n\n\n\n \n if predicate is None :\n def predicate(line):\n return line.strip()\n \n def prefixed_lines():\n for line in text.splitlines(True ):\n yield (prefix+line if predicate(line)else line)\n return ''.join(prefixed_lines())\n \n \nif __name__ ==\"__main__\":\n\n\n print(dedent(\"Hello there.\\n This is indented.\"))\n", ["re"]], "email.quoprimime": [".py", "\n\n\n\n\"\"\"Quoted-printable content transfer encoding per RFCs 2045-2047.\n\nThis module handles the content transfer encoding method defined in RFC 2045\nto encode US ASCII-like 8-bit data called `quoted-printable'. It is used to\nsafely encode text that is in a character set similar to the 7-bit US ASCII\ncharacter set, but that includes some 8-bit characters that are normally not\nallowed in email bodies or headers.\n\nQuoted-printable is very space-inefficient for encoding binary files; use the\nemail.base64mime module for that instead.\n\nThis module provides an interface to encode and decode both headers and bodies\nwith quoted-printable encoding.\n\nRFC 2045 defines a method for including character set information in an\n`encoded-word' in a header. This method is commonly used for 8-bit real names\nin To:/From:/Cc: etc. fields, as well as Subject: lines.\n\nThis module does not do the line wrapping or end-of-line character\nconversion necessary for proper internationalized headers; it only\ndoes dumb encoding and decoding. To deal with the various line\nwrapping issues, use the email.header module.\n\"\"\"\n\n__all__=[\n'body_decode',\n'body_encode',\n'body_length',\n'decode',\n'decodestring',\n'header_decode',\n'header_encode',\n'header_length',\n'quote',\n'unquote',\n]\n\nimport re\n\nfrom string import ascii_letters,digits,hexdigits\n\nCRLF='\\r\\n'\nNL='\\n'\nEMPTYSTRING=''\n\n\n\n\n\n\n_QUOPRI_MAP=['=%02X'%c for c in range(256)]\n_QUOPRI_HEADER_MAP=_QUOPRI_MAP[:]\n_QUOPRI_BODY_MAP=_QUOPRI_MAP[:]\n\n\nfor c in b'-!*+/'+ascii_letters.encode('ascii')+digits.encode('ascii'):\n _QUOPRI_HEADER_MAP[c]=chr(c)\n \n_QUOPRI_HEADER_MAP[ord(' ')]='_'\n\n\nfor c in (b' !\"#$%&\\'()*+,-./0123456789:;<>'\nb'?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\\\\]^_`'\nb'abcdefghijklmnopqrstuvwxyz{|}~\\t'):\n _QUOPRI_BODY_MAP[c]=chr(c)\n \n \n \n \ndef header_check(octet):\n ''\n return chr(octet)!=_QUOPRI_HEADER_MAP[octet]\n \n \ndef body_check(octet):\n ''\n return chr(octet)!=_QUOPRI_BODY_MAP[octet]\n \n \ndef header_length(bytearray):\n ''\n\n\n\n\n\n\n\n \n return sum(len(_QUOPRI_HEADER_MAP[octet])for octet in bytearray)\n \n \ndef body_length(bytearray):\n ''\n\n\n\n\n \n return sum(len(_QUOPRI_BODY_MAP[octet])for octet in bytearray)\n \n \ndef _max_append(L,s,maxlen,extra=''):\n if not isinstance(s,str):\n s=chr(s)\n if not L:\n L.append(s.lstrip())\n elif len(L[-1])+len(s)<=maxlen:\n L[-1]+=extra+s\n else :\n L.append(s.lstrip())\n \n \ndef unquote(s):\n ''\n return chr(int(s[1:3],16))\n \n \ndef quote(c):\n return _QUOPRI_MAP[ord(c)]\n \n \ndef header_encode(header_bytes,charset='iso-8859-1'):\n ''\n\n\n\n\n\n\n\n\n \n \n if not header_bytes:\n return ''\n \n encoded=header_bytes.decode('latin1').translate(_QUOPRI_HEADER_MAP)\n \n \n return '=?%s?q?%s?='%(charset,encoded)\n \n \n_QUOPRI_BODY_ENCODE_MAP=_QUOPRI_BODY_MAP[:]\nfor c in b'\\r\\n':\n _QUOPRI_BODY_ENCODE_MAP[c]=chr(c)\n \ndef body_encode(body,maxlinelen=76,eol=NL):\n ''\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n \n \n if maxlinelen <4:\n raise ValueError(\"maxlinelen must be at least 4\")\n if not body:\n return body\n \n \n body=body.translate(_QUOPRI_BODY_ENCODE_MAP)\n \n soft_break='='+eol\n \n maxlinelen1=maxlinelen -1\n \n encoded_body=[]\n append=encoded_body.append\n \n for line in body.splitlines():\n \n start=0\n laststart=len(line)-1 -maxlinelen\n while start <=laststart:\n stop=start+maxlinelen1\n \n if line[stop -2]=='=':\n append(line[start:stop -1])\n start=stop -2\n elif line[stop -1]=='=':\n append(line[start:stop])\n start=stop -1\n else :\n append(line[start:stop]+'=')\n start=stop\n \n \n if line and line[-1]in ' \\t':\n room=start -laststart\n if room >=3:\n \n \n q=quote(line[-1])\n elif room ==2:\n \n q=line[-1]+soft_break\n else :\n \n \n q=soft_break+quote(line[-1])\n append(line[start:-1]+q)\n else :\n append(line[start:])\n \n \n if body[-1]in CRLF:\n append('')\n \n return eol.join(encoded_body)\n \n \n \n \n \ndef decode(encoded,eol=NL):\n ''\n\n\n \n if not encoded:\n return encoded\n \n \n \n decoded=''\n \n for line in encoded.splitlines():\n line=line.rstrip()\n if not line:\n decoded +=eol\n continue\n \n i=0\n n=len(line)\n while i <n:\n c=line[i]\n if c !='=':\n decoded +=c\n i +=1\n \n \n elif i+1 ==n:\n i +=1\n continue\n \n elif i+2 <n and line[i+1]in hexdigits and line[i+2]in hexdigits:\n decoded +=unquote(line[i:i+3])\n i +=3\n \n else :\n decoded +=c\n i +=1\n \n if i ==n:\n decoded +=eol\n \n if encoded[-1]not in '\\r\\n'and decoded.endswith(eol):\n decoded=decoded[:-1]\n return decoded\n \n \n \nbody_decode=decode\ndecodestring=decode\n\n\n\ndef _unquote_match(match):\n ''\n s=match.group(0)\n return unquote(s)\n \n \n \ndef header_decode(s):\n ''\n\n\n\n\n \n s=s.replace('_',' ')\n return re.sub(r'=[a-fA-F0-9]{2}',_unquote_match,s,flags=re.ASCII)\n", ["re", "string"]], "pwd": [".py", "\ndef getpwuid():\n pass\n", []], "unittest.case": [".py", "''\n\nimport sys\nimport functools\nimport difflib\nimport logging\nimport pprint\nimport re\nimport warnings\nimport collections\nimport contextlib\nimport traceback\n\nfrom . import result\nfrom .util import (strclass,safe_repr,_count_diff_all_purpose,\n_count_diff_hashable,_common_shorten_repr)\n\n__unittest=True\n\n_subtest_msg_sentinel=object()\n\nDIFF_OMITTED=('\\nDiff is %s characters long. '\n'Set self.maxDiff to None to see it.')\n\nclass SkipTest(Exception):\n ''\n\n\n\n\n \n \nclass _ShouldStop(Exception):\n ''\n\n \n \nclass _UnexpectedSuccess(Exception):\n ''\n\n \n \n \nclass _Outcome(object):\n def __init__(self,result=None ):\n self.expecting_failure=False\n self.result=result\n self.result_supports_subtests=hasattr(result,\"addSubTest\")\n self.success=True\n self.skipped=[]\n self.expectedFailure=None\n self.errors=[]\n \n @contextlib.contextmanager\n def testPartExecutor(self,test_case,isTest=False ):\n old_success=self.success\n self.success=True\n try :\n yield\n except KeyboardInterrupt:\n raise\n except SkipTest as e:\n self.success=False\n self.skipped.append((test_case,str(e)))\n except _ShouldStop:\n pass\n except :\n exc_info=sys.exc_info()\n if self.expecting_failure:\n self.expectedFailure=exc_info\n else :\n self.success=False\n self.errors.append((test_case,exc_info))\n \n \n exc_info=None\n else :\n if self.result_supports_subtests and self.success:\n self.errors.append((test_case,None ))\n finally :\n self.success=self.success and old_success\n \n \ndef _id(obj):\n return obj\n \ndef skip(reason):\n ''\n\n \n def decorator(test_item):\n if not isinstance(test_item,type):\n @functools.wraps(test_item)\n def skip_wrapper(*args,**kwargs):\n raise SkipTest(reason)\n test_item=skip_wrapper\n \n test_item.__unittest_skip__=True\n test_item.__unittest_skip_why__=reason\n return test_item\n return decorator\n \ndef skipIf(condition,reason):\n ''\n\n \n if condition:\n return skip(reason)\n return _id\n \ndef skipUnless(condition,reason):\n ''\n\n \n if not condition:\n return skip(reason)\n return _id\n \ndef expectedFailure(test_item):\n test_item.__unittest_expecting_failure__=True\n return test_item\n \ndef _is_subtype(expected,basetype):\n if isinstance(expected,tuple):\n return all(_is_subtype(e,basetype)for e in expected)\n return isinstance(expected,type)and issubclass(expected,basetype)\n \nclass _BaseTestCaseContext:\n\n def __init__(self,test_case):\n self.test_case=test_case\n \n def _raiseFailure(self,standardMsg):\n msg=self.test_case._formatMessage(self.msg,standardMsg)\n raise self.test_case.failureException(msg)\n \nclass _AssertRaisesBaseContext(_BaseTestCaseContext):\n\n def __init__(self,expected,test_case,expected_regex=None ):\n _BaseTestCaseContext.__init__(self,test_case)\n self.expected=expected\n self.test_case=test_case\n if expected_regex is not None :\n expected_regex=re.compile(expected_regex)\n self.expected_regex=expected_regex\n self.obj_name=None\n self.msg=None\n \n def handle(self,name,args,kwargs):\n ''\n\n\n\n\n \n try :\n if not _is_subtype(self.expected,self._base_type):\n raise TypeError('%s() arg 1 must be %s'%\n (name,self._base_type_str))\n if args and args[0]is None :\n warnings.warn(\"callable is None\",\n DeprecationWarning,3)\n args=()\n if not args:\n self.msg=kwargs.pop('msg',None )\n if kwargs:\n warnings.warn('%r is an invalid keyword argument for '\n 'this function'%next(iter(kwargs)),\n DeprecationWarning,3)\n return self\n \n callable_obj,*args=args\n try :\n self.obj_name=callable_obj.__name__\n except AttributeError:\n self.obj_name=str(callable_obj)\n with self:\n callable_obj(*args,**kwargs)\n finally :\n \n self=None\n \n \nclass _AssertRaisesContext(_AssertRaisesBaseContext):\n ''\n \n _base_type=BaseException\n _base_type_str='an exception type or tuple of exception types'\n \n def __enter__(self):\n return self\n \n def __exit__(self,exc_type,exc_value,tb):\n if exc_type is None :\n try :\n exc_name=self.expected.__name__\n except AttributeError:\n exc_name=str(self.expected)\n if self.obj_name:\n self._raiseFailure(\"{} not raised by {}\".format(exc_name,\n self.obj_name))\n else :\n self._raiseFailure(\"{} not raised\".format(exc_name))\n else :\n traceback.clear_frames(tb)\n if not issubclass(exc_type,self.expected):\n \n return False\n \n self.exception=exc_value.with_traceback(None )\n if self.expected_regex is None :\n return True\n \n expected_regex=self.expected_regex\n if not expected_regex.search(str(exc_value)):\n self._raiseFailure('\"{}\" does not match \"{}\"'.format(\n expected_regex.pattern,str(exc_value)))\n return True\n \n \nclass _AssertWarnsContext(_AssertRaisesBaseContext):\n ''\n \n _base_type=Warning\n _base_type_str='a warning type or tuple of warning types'\n \n def __enter__(self):\n \n \n for v in sys.modules.values():\n if getattr(v,'__warningregistry__',None ):\n v.__warningregistry__={}\n self.warnings_manager=warnings.catch_warnings(record=True )\n self.warnings=self.warnings_manager.__enter__()\n warnings.simplefilter(\"always\",self.expected)\n return self\n \n def __exit__(self,exc_type,exc_value,tb):\n self.warnings_manager.__exit__(exc_type,exc_value,tb)\n if exc_type is not None :\n \n return\n try :\n exc_name=self.expected.__name__\n except AttributeError:\n exc_name=str(self.expected)\n first_matching=None\n for m in self.warnings:\n w=m.message\n if not isinstance(w,self.expected):\n continue\n if first_matching is None :\n first_matching=w\n if (self.expected_regex is not None and\n not self.expected_regex.search(str(w))):\n continue\n \n self.warning=w\n self.filename=m.filename\n self.lineno=m.lineno\n return\n \n if first_matching is not None :\n self._raiseFailure('\"{}\" does not match \"{}\"'.format(\n self.expected_regex.pattern,str(first_matching)))\n if self.obj_name:\n self._raiseFailure(\"{} not triggered by {}\".format(exc_name,\n self.obj_name))\n else :\n self._raiseFailure(\"{} not triggered\".format(exc_name))\n \n \n \n_LoggingWatcher=collections.namedtuple(\"_LoggingWatcher\",\n[\"records\",\"output\"])\n\n\nclass _CapturingHandler(logging.Handler):\n ''\n\n \n \n def __init__(self):\n logging.Handler.__init__(self)\n self.watcher=_LoggingWatcher([],[])\n \n def flush(self):\n pass\n \n def emit(self,record):\n self.watcher.records.append(record)\n msg=self.format(record)\n self.watcher.output.append(msg)\n \n \n \nclass _AssertLogsContext(_BaseTestCaseContext):\n ''\n \n LOGGING_FORMAT=\"%(levelname)s:%(name)s:%(message)s\"\n \n def __init__(self,test_case,logger_name,level):\n _BaseTestCaseContext.__init__(self,test_case)\n self.logger_name=logger_name\n if level:\n self.level=logging._nameToLevel.get(level,level)\n else :\n self.level=logging.INFO\n self.msg=None\n \n def __enter__(self):\n if isinstance(self.logger_name,logging.Logger):\n logger=self.logger=self.logger_name\n else :\n logger=self.logger=logging.getLogger(self.logger_name)\n formatter=logging.Formatter(self.LOGGING_FORMAT)\n handler=_CapturingHandler()\n handler.setFormatter(formatter)\n self.watcher=handler.watcher\n self.old_handlers=logger.handlers[:]\n self.old_level=logger.level\n self.old_propagate=logger.propagate\n logger.handlers=[handler]\n logger.setLevel(self.level)\n logger.propagate=False\n return handler.watcher\n \n def __exit__(self,exc_type,exc_value,tb):\n self.logger.handlers=self.old_handlers\n self.logger.propagate=self.old_propagate\n self.logger.setLevel(self.old_level)\n if exc_type is not None :\n \n return False\n if len(self.watcher.records)==0:\n self._raiseFailure(\n \"no logs of level {} or higher triggered on {}\"\n .format(logging.getLevelName(self.level),self.logger.name))\n \n \nclass _OrderedChainMap(collections.ChainMap):\n def __iter__(self):\n seen=set()\n for mapping in self.maps:\n for k in mapping:\n if k not in seen:\n seen.add(k)\n yield k\n \n \nclass TestCase(object):\n ''\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n \n \n failureException=AssertionError\n \n longMessage=True\n \n maxDiff=80 *8\n \n \n \n _diffThreshold=2 **16\n \n \n \n _classSetupFailed=False\n \n def __init__(self,methodName='runTest'):\n ''\n\n\n \n self._testMethodName=methodName\n self._outcome=None\n self._testMethodDoc='No test'\n try :\n testMethod=getattr(self,methodName)\n except AttributeError:\n if methodName !='runTest':\n \n \n raise ValueError(\"no such test method in %s: %s\"%\n (self.__class__,methodName))\n else :\n self._testMethodDoc=testMethod.__doc__\n self._cleanups=[]\n self._subtest=None\n \n \n \n \n self._type_equality_funcs={}\n self.addTypeEqualityFunc(dict,'assertDictEqual')\n self.addTypeEqualityFunc(list,'assertListEqual')\n self.addTypeEqualityFunc(tuple,'assertTupleEqual')\n self.addTypeEqualityFunc(set,'assertSetEqual')\n self.addTypeEqualityFunc(frozenset,'assertSetEqual')\n self.addTypeEqualityFunc(str,'assertMultiLineEqual')\n \n def addTypeEqualityFunc(self,typeobj,function):\n ''\n\n\n\n\n\n\n\n\n\n\n \n self._type_equality_funcs[typeobj]=function\n \n def addCleanup(self,function,*args,**kwargs):\n ''\n\n\n\n \n self._cleanups.append((function,args,kwargs))\n \n def setUp(self):\n ''\n pass\n \n def tearDown(self):\n ''\n pass\n \n @classmethod\n def setUpClass(cls):\n ''\n \n @classmethod\n def tearDownClass(cls):\n ''\n \n def countTestCases(self):\n return 1\n \n def defaultTestResult(self):\n return result.TestResult()\n \n def shortDescription(self):\n ''\n\n\n\n\n \n doc=self._testMethodDoc\n return doc and doc.split(\"\\n\")[0].strip()or None\n \n \n def id(self):\n return \"%s.%s\"%(strclass(self.__class__),self._testMethodName)\n \n def __eq__(self,other):\n if type(self)is not type(other):\n return NotImplemented\n \n return self._testMethodName ==other._testMethodName\n \n def __hash__(self):\n return hash((type(self),self._testMethodName))\n \n def __str__(self):\n return \"%s (%s)\"%(self._testMethodName,strclass(self.__class__))\n \n def __repr__(self):\n return \"<%s testMethod=%s>\"%\\\n (strclass(self.__class__),self._testMethodName)\n \n def _addSkip(self,result,test_case,reason):\n addSkip=getattr(result,'addSkip',None )\n if addSkip is not None :\n addSkip(test_case,reason)\n else :\n warnings.warn(\"TestResult has no addSkip method, skips not reported\",\n RuntimeWarning,2)\n result.addSuccess(test_case)\n \n @contextlib.contextmanager\n def subTest(self,msg=_subtest_msg_sentinel,**params):\n ''\n\n\n\n\n \n if not self._outcome.result_supports_subtests:\n yield\n return\n parent=self._subtest\n if parent is None :\n params_map=_OrderedChainMap(params)\n else :\n params_map=parent.params.new_child(params)\n self._subtest=_SubTest(self,msg,params_map)\n try :\n with self._outcome.testPartExecutor(self._subtest,isTest=True ):\n yield\n if not self._outcome.success:\n result=self._outcome.result\n if result is not None and result.failfast:\n raise _ShouldStop\n elif self._outcome.expectedFailure:\n \n \n raise _ShouldStop\n finally :\n self._subtest=parent\n \n def _feedErrorsToResult(self,result,errors):\n for test,exc_info in errors:\n if isinstance(test,_SubTest):\n result.addSubTest(test.test_case,test,exc_info)\n elif exc_info is not None :\n if issubclass(exc_info[0],self.failureException):\n result.addFailure(test,exc_info)\n else :\n result.addError(test,exc_info)\n \n def _addExpectedFailure(self,result,exc_info):\n try :\n addExpectedFailure=result.addExpectedFailure\n except AttributeError:\n warnings.warn(\"TestResult has no addExpectedFailure method, reporting as passes\",\n RuntimeWarning)\n result.addSuccess(self)\n else :\n addExpectedFailure(self,exc_info)\n \n def _addUnexpectedSuccess(self,result):\n try :\n addUnexpectedSuccess=result.addUnexpectedSuccess\n except AttributeError:\n warnings.warn(\"TestResult has no addUnexpectedSuccess method, reporting as failure\",\n RuntimeWarning)\n \n \n try :\n raise _UnexpectedSuccess from None\n except _UnexpectedSuccess:\n result.addFailure(self,sys.exc_info())\n else :\n addUnexpectedSuccess(self)\n \n def run(self,result=None ):\n orig_result=result\n if result is None :\n result=self.defaultTestResult()\n startTestRun=getattr(result,'startTestRun',None )\n if startTestRun is not None :\n startTestRun()\n \n result.startTest(self)\n \n testMethod=getattr(self,self._testMethodName)\n if (getattr(self.__class__,\"__unittest_skip__\",False )or\n getattr(testMethod,\"__unittest_skip__\",False )):\n \n try :\n skip_why=(getattr(self.__class__,'__unittest_skip_why__','')\n or getattr(testMethod,'__unittest_skip_why__',''))\n self._addSkip(result,self,skip_why)\n finally :\n result.stopTest(self)\n return\n expecting_failure_method=getattr(testMethod,\n \"__unittest_expecting_failure__\",False )\n expecting_failure_class=getattr(self,\n \"__unittest_expecting_failure__\",False )\n expecting_failure=expecting_failure_class or expecting_failure_method\n outcome=_Outcome(result)\n try :\n self._outcome=outcome\n \n with outcome.testPartExecutor(self):\n self.setUp()\n if outcome.success:\n outcome.expecting_failure=expecting_failure\n with outcome.testPartExecutor(self,isTest=True ):\n testMethod()\n outcome.expecting_failure=False\n with outcome.testPartExecutor(self):\n self.tearDown()\n \n self.doCleanups()\n for test,reason in outcome.skipped:\n self._addSkip(result,test,reason)\n self._feedErrorsToResult(result,outcome.errors)\n if outcome.success:\n if expecting_failure:\n if outcome.expectedFailure:\n self._addExpectedFailure(result,outcome.expectedFailure)\n else :\n self._addUnexpectedSuccess(result)\n else :\n result.addSuccess(self)\n return result\n finally :\n result.stopTest(self)\n if orig_result is None :\n stopTestRun=getattr(result,'stopTestRun',None )\n if stopTestRun is not None :\n stopTestRun()\n \n \n \n \n outcome.errors.clear()\n outcome.expectedFailure=None\n \n \n self._outcome=None\n \n def doCleanups(self):\n ''\n \n outcome=self._outcome or _Outcome()\n while self._cleanups:\n function,args,kwargs=self._cleanups.pop()\n with outcome.testPartExecutor(self):\n function(*args,**kwargs)\n \n \n \n return outcome.success\n \n def __call__(self,*args,**kwds):\n return self.run(*args,**kwds)\n \n def debug(self):\n ''\n self.setUp()\n getattr(self,self._testMethodName)()\n self.tearDown()\n while self._cleanups:\n function,args,kwargs=self._cleanups.pop(-1)\n function(*args,**kwargs)\n \n def skipTest(self,reason):\n ''\n raise SkipTest(reason)\n \n def fail(self,msg=None ):\n ''\n raise self.failureException(msg)\n \n def assertFalse(self,expr,msg=None ):\n ''\n if expr:\n msg=self._formatMessage(msg,\"%s is not false\"%safe_repr(expr))\n raise self.failureException(msg)\n \n def assertTrue(self,expr,msg=None ):\n ''\n if not expr:\n msg=self._formatMessage(msg,\"%s is not true\"%safe_repr(expr))\n raise self.failureException(msg)\n \n def _formatMessage(self,msg,standardMsg):\n ''\n\n\n\n\n\n\n\n \n if not self.longMessage:\n return msg or standardMsg\n if msg is None :\n return standardMsg\n try :\n \n \n return '%s : %s'%(standardMsg,msg)\n except UnicodeDecodeError:\n return '%s : %s'%(safe_repr(standardMsg),safe_repr(msg))\n \n def assertRaises(self,expected_exception,*args,**kwargs):\n ''\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n \n context=_AssertRaisesContext(expected_exception,self)\n try :\n return context.handle('assertRaises',args,kwargs)\n finally :\n \n context=None\n \n def assertWarns(self,expected_warning,*args,**kwargs):\n ''\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n \n context=_AssertWarnsContext(expected_warning,self)\n return context.handle('assertWarns',args,kwargs)\n \n def assertLogs(self,logger=None ,level=None ):\n ''\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n \n return _AssertLogsContext(self,logger,level)\n \n def _getAssertEqualityFunc(self,first,second):\n ''\n\n\n\n\n \n \n \n \n \n \n \n \n \n \n \n if type(first)is type(second):\n asserter=self._type_equality_funcs.get(type(first))\n if asserter is not None :\n if isinstance(asserter,str):\n asserter=getattr(self,asserter)\n return asserter\n \n return self._baseAssertEqual\n \n def _baseAssertEqual(self,first,second,msg=None ):\n ''\n if not first ==second:\n standardMsg='%s != %s'%_common_shorten_repr(first,second)\n msg=self._formatMessage(msg,standardMsg)\n raise self.failureException(msg)\n \n def assertEqual(self,first,second,msg=None ):\n ''\n\n \n assertion_func=self._getAssertEqualityFunc(first,second)\n assertion_func(first,second,msg=msg)\n \n def assertNotEqual(self,first,second,msg=None ):\n ''\n\n \n if not first !=second:\n msg=self._formatMessage(msg,'%s == %s'%(safe_repr(first),\n safe_repr(second)))\n raise self.failureException(msg)\n \n def assertAlmostEqual(self,first,second,places=None ,msg=None ,\n delta=None ):\n ''\n\n\n\n\n\n\n\n\n\n\n \n if first ==second:\n \n return\n if delta is not None and places is not None :\n raise TypeError(\"specify delta or places not both\")\n \n diff=abs(first -second)\n if delta is not None :\n if diff <=delta:\n return\n \n standardMsg='%s != %s within %s delta (%s difference)'%(\n safe_repr(first),\n safe_repr(second),\n safe_repr(delta),\n safe_repr(diff))\n else :\n if places is None :\n places=7\n \n if round(diff,places)==0:\n return\n \n standardMsg='%s != %s within %r places (%s difference)'%(\n safe_repr(first),\n safe_repr(second),\n places,\n safe_repr(diff))\n msg=self._formatMessage(msg,standardMsg)\n raise self.failureException(msg)\n \n def assertNotAlmostEqual(self,first,second,places=None ,msg=None ,\n delta=None ):\n ''\n\n\n\n\n\n\n\n\n \n if delta is not None and places is not None :\n raise TypeError(\"specify delta or places not both\")\n diff=abs(first -second)\n if delta is not None :\n if not (first ==second)and diff >delta:\n return\n standardMsg='%s == %s within %s delta (%s difference)'%(\n safe_repr(first),\n safe_repr(second),\n safe_repr(delta),\n safe_repr(diff))\n else :\n if places is None :\n places=7\n if not (first ==second)and round(diff,places)!=0:\n return\n standardMsg='%s == %s within %r places'%(safe_repr(first),\n safe_repr(second),\n places)\n \n msg=self._formatMessage(msg,standardMsg)\n raise self.failureException(msg)\n \n def assertSequenceEqual(self,seq1,seq2,msg=None ,seq_type=None ):\n ''\n\n\n\n\n\n\n\n\n\n\n\n \n if seq_type is not None :\n seq_type_name=seq_type.__name__\n if not isinstance(seq1,seq_type):\n raise self.failureException('First sequence is not a %s: %s'\n %(seq_type_name,safe_repr(seq1)))\n if not isinstance(seq2,seq_type):\n raise self.failureException('Second sequence is not a %s: %s'\n %(seq_type_name,safe_repr(seq2)))\n else :\n seq_type_name=\"sequence\"\n \n differing=None\n try :\n len1=len(seq1)\n except (TypeError,NotImplementedError):\n differing='First %s has no length. Non-sequence?'%(\n seq_type_name)\n \n if differing is None :\n try :\n len2=len(seq2)\n except (TypeError,NotImplementedError):\n differing='Second %s has no length. Non-sequence?'%(\n seq_type_name)\n \n if differing is None :\n if seq1 ==seq2:\n return\n \n differing='%ss differ: %s != %s\\n'%(\n (seq_type_name.capitalize(),)+\n _common_shorten_repr(seq1,seq2))\n \n for i in range(min(len1,len2)):\n try :\n item1=seq1[i]\n except (TypeError,IndexError,NotImplementedError):\n differing +=('\\nUnable to index element %d of first %s\\n'%\n (i,seq_type_name))\n break\n \n try :\n item2=seq2[i]\n except (TypeError,IndexError,NotImplementedError):\n differing +=('\\nUnable to index element %d of second %s\\n'%\n (i,seq_type_name))\n break\n \n if item1 !=item2:\n differing +=('\\nFirst differing element %d:\\n%s\\n%s\\n'%\n ((i,)+_common_shorten_repr(item1,item2)))\n break\n else :\n if (len1 ==len2 and seq_type is None and\n type(seq1)!=type(seq2)):\n \n return\n \n if len1 >len2:\n differing +=('\\nFirst %s contains %d additional '\n 'elements.\\n'%(seq_type_name,len1 -len2))\n try :\n differing +=('First extra element %d:\\n%s\\n'%\n (len2,safe_repr(seq1[len2])))\n except (TypeError,IndexError,NotImplementedError):\n differing +=('Unable to index element %d '\n 'of first %s\\n'%(len2,seq_type_name))\n elif len1 <len2:\n differing +=('\\nSecond %s contains %d additional '\n 'elements.\\n'%(seq_type_name,len2 -len1))\n try :\n differing +=('First extra element %d:\\n%s\\n'%\n (len1,safe_repr(seq2[len1])))\n except (TypeError,IndexError,NotImplementedError):\n differing +=('Unable to index element %d '\n 'of second %s\\n'%(len1,seq_type_name))\n standardMsg=differing\n diffMsg='\\n'+'\\n'.join(\n difflib.ndiff(pprint.pformat(seq1).splitlines(),\n pprint.pformat(seq2).splitlines()))\n \n standardMsg=self._truncateMessage(standardMsg,diffMsg)\n msg=self._formatMessage(msg,standardMsg)\n self.fail(msg)\n \n def _truncateMessage(self,message,diff):\n max_diff=self.maxDiff\n if max_diff is None or len(diff)<=max_diff:\n return message+diff\n return message+(DIFF_OMITTED %len(diff))\n \n def assertListEqual(self,list1,list2,msg=None ):\n ''\n\n\n\n\n\n\n\n \n self.assertSequenceEqual(list1,list2,msg,seq_type=list)\n \n def assertTupleEqual(self,tuple1,tuple2,msg=None ):\n ''\n\n\n\n\n\n\n \n self.assertSequenceEqual(tuple1,tuple2,msg,seq_type=tuple)\n \n def assertSetEqual(self,set1,set2,msg=None ):\n ''\n\n\n\n\n\n\n\n\n\n\n \n try :\n difference1=set1.difference(set2)\n except TypeError as e:\n self.fail('invalid type when attempting set difference: %s'%e)\n except AttributeError as e:\n self.fail('first argument does not support set difference: %s'%e)\n \n try :\n difference2=set2.difference(set1)\n except TypeError as e:\n self.fail('invalid type when attempting set difference: %s'%e)\n except AttributeError as e:\n self.fail('second argument does not support set difference: %s'%e)\n \n if not (difference1 or difference2):\n return\n \n lines=[]\n if difference1:\n lines.append('Items in the first set but not the second:')\n for item in difference1:\n lines.append(repr(item))\n if difference2:\n lines.append('Items in the second set but not the first:')\n for item in difference2:\n lines.append(repr(item))\n \n standardMsg='\\n'.join(lines)\n self.fail(self._formatMessage(msg,standardMsg))\n \n def assertIn(self,member,container,msg=None ):\n ''\n if member not in container:\n standardMsg='%s not found in %s'%(safe_repr(member),\n safe_repr(container))\n self.fail(self._formatMessage(msg,standardMsg))\n \n def assertNotIn(self,member,container,msg=None ):\n ''\n if member in container:\n standardMsg='%s unexpectedly found in %s'%(safe_repr(member),\n safe_repr(container))\n self.fail(self._formatMessage(msg,standardMsg))\n \n def assertIs(self,expr1,expr2,msg=None ):\n ''\n if expr1 is not expr2:\n standardMsg='%s is not %s'%(safe_repr(expr1),\n safe_repr(expr2))\n self.fail(self._formatMessage(msg,standardMsg))\n \n def assertIsNot(self,expr1,expr2,msg=None ):\n ''\n if expr1 is expr2:\n standardMsg='unexpectedly identical: %s'%(safe_repr(expr1),)\n self.fail(self._formatMessage(msg,standardMsg))\n \n def assertDictEqual(self,d1,d2,msg=None ):\n self.assertIsInstance(d1,dict,'First argument is not a dictionary')\n self.assertIsInstance(d2,dict,'Second argument is not a dictionary')\n \n if d1 !=d2:\n standardMsg='%s != %s'%_common_shorten_repr(d1,d2)\n diff=('\\n'+'\\n'.join(difflib.ndiff(\n pprint.pformat(d1).splitlines(),\n pprint.pformat(d2).splitlines())))\n standardMsg=self._truncateMessage(standardMsg,diff)\n self.fail(self._formatMessage(msg,standardMsg))\n \n def assertDictContainsSubset(self,subset,dictionary,msg=None ):\n ''\n warnings.warn('assertDictContainsSubset is deprecated',\n DeprecationWarning)\n missing=[]\n mismatched=[]\n for key,value in subset.items():\n if key not in dictionary:\n missing.append(key)\n elif value !=dictionary[key]:\n mismatched.append('%s, expected: %s, actual: %s'%\n (safe_repr(key),safe_repr(value),\n safe_repr(dictionary[key])))\n \n if not (missing or mismatched):\n return\n \n standardMsg=''\n if missing:\n standardMsg='Missing: %s'%','.join(safe_repr(m)for m in\n missing)\n if mismatched:\n if standardMsg:\n standardMsg +='; '\n standardMsg +='Mismatched values: %s'%','.join(mismatched)\n \n self.fail(self._formatMessage(msg,standardMsg))\n \n \n def assertCountEqual(self,first,second,msg=None ):\n ''\n\n\n\n\n\n\n\n\n\n\n \n first_seq,second_seq=list(first),list(second)\n try :\n first=collections.Counter(first_seq)\n second=collections.Counter(second_seq)\n except TypeError:\n \n differences=_count_diff_all_purpose(first_seq,second_seq)\n else :\n if first ==second:\n return\n differences=_count_diff_hashable(first_seq,second_seq)\n \n if differences:\n standardMsg='Element counts were not equal:\\n'\n lines=['First has %d, Second has %d: %r'%diff for diff in differences]\n diffMsg='\\n'.join(lines)\n standardMsg=self._truncateMessage(standardMsg,diffMsg)\n msg=self._formatMessage(msg,standardMsg)\n self.fail(msg)\n \n def assertMultiLineEqual(self,first,second,msg=None ):\n ''\n self.assertIsInstance(first,str,'First argument is not a string')\n self.assertIsInstance(second,str,'Second argument is not a string')\n \n if first !=second:\n \n if (len(first)>self._diffThreshold or\n len(second)>self._diffThreshold):\n self._baseAssertEqual(first,second,msg)\n firstlines=first.splitlines(keepends=True )\n secondlines=second.splitlines(keepends=True )\n if len(firstlines)==1 and first.strip('\\r\\n')==first:\n firstlines=[first+'\\n']\n secondlines=[second+'\\n']\n standardMsg='%s != %s'%_common_shorten_repr(first,second)\n diff='\\n'+''.join(difflib.ndiff(firstlines,secondlines))\n standardMsg=self._truncateMessage(standardMsg,diff)\n self.fail(self._formatMessage(msg,standardMsg))\n \n def assertLess(self,a,b,msg=None ):\n ''\n if not a <b:\n standardMsg='%s not less than %s'%(safe_repr(a),safe_repr(b))\n self.fail(self._formatMessage(msg,standardMsg))\n \n def assertLessEqual(self,a,b,msg=None ):\n ''\n if not a <=b:\n standardMsg='%s not less than or equal to %s'%(safe_repr(a),safe_repr(b))\n self.fail(self._formatMessage(msg,standardMsg))\n \n def assertGreater(self,a,b,msg=None ):\n ''\n if not a >b:\n standardMsg='%s not greater than %s'%(safe_repr(a),safe_repr(b))\n self.fail(self._formatMessage(msg,standardMsg))\n \n def assertGreaterEqual(self,a,b,msg=None ):\n ''\n if not a >=b:\n standardMsg='%s not greater than or equal to %s'%(safe_repr(a),safe_repr(b))\n self.fail(self._formatMessage(msg,standardMsg))\n \n def assertIsNone(self,obj,msg=None ):\n ''\n if obj is not None :\n standardMsg='%s is not None'%(safe_repr(obj),)\n self.fail(self._formatMessage(msg,standardMsg))\n \n def assertIsNotNone(self,obj,msg=None ):\n ''\n if obj is None :\n standardMsg='unexpectedly None'\n self.fail(self._formatMessage(msg,standardMsg))\n \n def assertIsInstance(self,obj,cls,msg=None ):\n ''\n \n if not isinstance(obj,cls):\n standardMsg='%s is not an instance of %r'%(safe_repr(obj),cls)\n self.fail(self._formatMessage(msg,standardMsg))\n \n def assertNotIsInstance(self,obj,cls,msg=None ):\n ''\n if isinstance(obj,cls):\n standardMsg='%s is an instance of %r'%(safe_repr(obj),cls)\n self.fail(self._formatMessage(msg,standardMsg))\n \n def assertRaisesRegex(self,expected_exception,expected_regex,\n *args,**kwargs):\n ''\n\n\n\n\n\n\n\n\n\n \n context=_AssertRaisesContext(expected_exception,self,expected_regex)\n return context.handle('assertRaisesRegex',args,kwargs)\n \n def assertWarnsRegex(self,expected_warning,expected_regex,\n *args,**kwargs):\n ''\n\n\n\n\n\n\n\n\n\n\n\n\n \n context=_AssertWarnsContext(expected_warning,self,expected_regex)\n return context.handle('assertWarnsRegex',args,kwargs)\n \n def assertRegex(self,text,expected_regex,msg=None ):\n ''\n if isinstance(expected_regex,(str,bytes)):\n assert expected_regex,\"expected_regex must not be empty.\"\n expected_regex=re.compile(expected_regex)\n if not expected_regex.search(text):\n standardMsg=\"Regex didn't match: %r not found in %r\"%(\n expected_regex.pattern,text)\n \n msg=self._formatMessage(msg,standardMsg)\n raise self.failureException(msg)\n \n def assertNotRegex(self,text,unexpected_regex,msg=None ):\n ''\n if isinstance(unexpected_regex,(str,bytes)):\n unexpected_regex=re.compile(unexpected_regex)\n match=unexpected_regex.search(text)\n if match:\n standardMsg='Regex matched: %r matches %r in %r'%(\n text[match.start():match.end()],\n unexpected_regex.pattern,\n text)\n \n msg=self._formatMessage(msg,standardMsg)\n raise self.failureException(msg)\n \n \n def _deprecate(original_func):\n def deprecated_func(*args,**kwargs):\n warnings.warn(\n 'Please use {0} instead.'.format(original_func.__name__),\n DeprecationWarning,2)\n return original_func(*args,**kwargs)\n return deprecated_func\n \n \n failUnlessEqual=assertEquals=_deprecate(assertEqual)\n failIfEqual=assertNotEquals=_deprecate(assertNotEqual)\n failUnlessAlmostEqual=assertAlmostEquals=_deprecate(assertAlmostEqual)\n failIfAlmostEqual=assertNotAlmostEquals=_deprecate(assertNotAlmostEqual)\n failUnless=assert_=_deprecate(assertTrue)\n failUnlessRaises=_deprecate(assertRaises)\n failIf=_deprecate(assertFalse)\n assertRaisesRegexp=_deprecate(assertRaisesRegex)\n assertRegexpMatches=_deprecate(assertRegex)\n assertNotRegexpMatches=_deprecate(assertNotRegex)\n \n \n \nclass FunctionTestCase(TestCase):\n ''\n\n\n\n\n\n \n \n def __init__(self,testFunc,setUp=None ,tearDown=None ,description=None ):\n super(FunctionTestCase,self).__init__()\n self._setUpFunc=setUp\n self._tearDownFunc=tearDown\n self._testFunc=testFunc\n self._description=description\n \n def setUp(self):\n if self._setUpFunc is not None :\n self._setUpFunc()\n \n def tearDown(self):\n if self._tearDownFunc is not None :\n self._tearDownFunc()\n \n def runTest(self):\n self._testFunc()\n \n def id(self):\n return self._testFunc.__name__\n \n def __eq__(self,other):\n if not isinstance(other,self.__class__):\n return NotImplemented\n \n return self._setUpFunc ==other._setUpFunc and\\\n self._tearDownFunc ==other._tearDownFunc and\\\n self._testFunc ==other._testFunc and\\\n self._description ==other._description\n \n def __hash__(self):\n return hash((type(self),self._setUpFunc,self._tearDownFunc,\n self._testFunc,self._description))\n \n def __str__(self):\n return \"%s (%s)\"%(strclass(self.__class__),\n self._testFunc.__name__)\n \n def __repr__(self):\n return \"<%s tec=%s>\"%(strclass(self.__class__),\n self._testFunc)\n \n def shortDescription(self):\n if self._description is not None :\n return self._description\n doc=self._testFunc.__doc__\n return doc and doc.split(\"\\n\")[0].strip()or None\n \n \nclass _SubTest(TestCase):\n\n def __init__(self,test_case,message,params):\n super().__init__()\n self._message=message\n self.test_case=test_case\n self.params=params\n self.failureException=test_case.failureException\n \n def runTest(self):\n raise NotImplementedError(\"subtests cannot be run directly\")\n \n def _subDescription(self):\n parts=[]\n if self._message is not _subtest_msg_sentinel:\n parts.append(\"[{}]\".format(self._message))\n if self.params:\n params_desc=', '.join(\n \"{}={!r}\".format(k,v)\n for (k,v)in self.params.items())\n parts.append(\"({})\".format(params_desc))\n return \" \".join(parts)or '(<subtest>)'\n \n def id(self):\n return \"{} {}\".format(self.test_case.id(),self._subDescription())\n \n def shortDescription(self):\n ''\n\n \n return self.test_case.shortDescription()\n \n def __str__(self):\n return \"{} {}\".format(self.test_case,self._subDescription())\n", ["collections", "contextlib", "difflib", "functools", "logging", "pprint", "re", "sys", "traceback", "unittest", "unittest.result", "unittest.util", "warnings"]], "types": [".py", "''\n\n\nimport sys\n\n\n\n\n\n\ndef _f():pass\nFunctionType=type(_f)\nLambdaType=type(lambda :None )\nCodeType=type(_f.__code__)\nMappingProxyType=type(type.__dict__)\nSimpleNamespace=type(sys.implementation)\n\ndef _g():\n yield 1\nGeneratorType=type(_g())\n\nasync def _c():pass\n_c=_c()\nCoroutineType=type(_c)\n_c.close()\n\nasync def _ag():\n yield\n_ag=_ag()\nAsyncGeneratorType=type(_ag)\n\nclass _C:\n def _m(self):pass\nMethodType=type(_C()._m)\n\nBuiltinFunctionType=type(len)\nBuiltinMethodType=type([].append)\n\nWrapperDescriptorType=type(object.__init__)\nMethodWrapperType=type(object().__str__)\nMethodDescriptorType=type(str.join)\nClassMethodDescriptorType=type(dict.__dict__['fromkeys'])\n\nModuleType=type(sys)\n\ntry :\n raise TypeError\nexcept TypeError:\n tb=sys.exc_info()[2]\n TracebackType=type(tb)\n FrameType=type(tb.tb_frame)\n tb=None ;del tb\n \n \nGetSetDescriptorType=type(FunctionType.__code__)\nMemberDescriptorType=type(FunctionType.__globals__)\n\ndel sys,_f,_g,_C,_c,\n\n\n\ndef new_class(name,bases=(),kwds=None ,exec_body=None ):\n ''\n resolved_bases=resolve_bases(bases)\n meta,ns,kwds=prepare_class(name,resolved_bases,kwds)\n if exec_body is not None :\n exec_body(ns)\n if resolved_bases is not bases:\n ns['__orig_bases__']=bases\n return meta(name,resolved_bases,ns,**kwds)\n \ndef resolve_bases(bases):\n ''\n new_bases=list(bases)\n updated=False\n shift=0\n for i,base in enumerate(bases):\n if isinstance(base,type):\n continue\n if not hasattr(base,\"__mro_entries__\"):\n continue\n new_base=base.__mro_entries__(bases)\n updated=True\n if not isinstance(new_base,tuple):\n raise TypeError(\"__mro_entries__ must return a tuple\")\n else :\n new_bases[i+shift:i+shift+1]=new_base\n shift +=len(new_base)-1\n if not updated:\n return bases\n return tuple(new_bases)\n \ndef prepare_class(name,bases=(),kwds=None ):\n ''\n\n\n\n\n\n\n\n\n \n if kwds is None :\n kwds={}\n else :\n kwds=dict(kwds)\n if 'metaclass'in kwds:\n meta=kwds.pop('metaclass')\n else :\n if bases:\n meta=type(bases[0])\n else :\n meta=type\n if isinstance(meta,type):\n \n \n meta=_calculate_meta(meta,bases)\n if hasattr(meta,'__prepare__'):\n ns=meta.__prepare__(name,bases,**kwds)\n else :\n ns={}\n return meta,ns,kwds\n \ndef _calculate_meta(meta,bases):\n ''\n winner=meta\n for base in bases:\n base_meta=type(base)\n if issubclass(winner,base_meta):\n continue\n if issubclass(base_meta,winner):\n winner=base_meta\n continue\n \n raise TypeError(\"metaclass conflict: \"\n \"the metaclass of a derived class \"\n \"must be a (non-strict) subclass \"\n \"of the metaclasses of all its bases\")\n return winner\n \nclass DynamicClassAttribute:\n ''\n\n\n\n\n\n\n\n\n\n \n def __init__(self,fget=None ,fset=None ,fdel=None ,doc=None ):\n self.fget=fget\n self.fset=fset\n self.fdel=fdel\n \n self.__doc__=doc or fget.__doc__\n self.overwrite_doc=doc is None\n \n self.__isabstractmethod__=bool(getattr(fget,'__isabstractmethod__',False ))\n \n def __get__(self,instance,ownerclass=None ):\n if instance is None :\n if self.__isabstractmethod__:\n return self\n raise AttributeError()\n elif self.fget is None :\n raise AttributeError(\"unreadable attribute\")\n return self.fget(instance)\n \n def __set__(self,instance,value):\n if self.fset is None :\n raise AttributeError(\"can't set attribute\")\n self.fset(instance,value)\n \n def __delete__(self,instance):\n if self.fdel is None :\n raise AttributeError(\"can't delete attribute\")\n self.fdel(instance)\n \n def getter(self,fget):\n fdoc=fget.__doc__ if self.overwrite_doc else None\n result=type(self)(fget,self.fset,self.fdel,fdoc or self.__doc__)\n result.overwrite_doc=self.overwrite_doc\n return result\n \n def setter(self,fset):\n result=type(self)(self.fget,fset,self.fdel,self.__doc__)\n result.overwrite_doc=self.overwrite_doc\n return result\n \n def deleter(self,fdel):\n result=type(self)(self.fget,self.fset,fdel,self.__doc__)\n result.overwrite_doc=self.overwrite_doc\n return result\n \n \nclass _GeneratorWrapper:\n\n def __init__(self,gen):\n self.__wrapped=gen\n self.__isgen=gen.__class__ is GeneratorType\n self.__name__=getattr(gen,'__name__',None )\n self.__qualname__=getattr(gen,'__qualname__',None )\n def send(self,val):\n return self.__wrapped.send(val)\n def throw(self,tp,*rest):\n return self.__wrapped.throw(tp,*rest)\n def close(self):\n return self.__wrapped.close()\n @property\n def gi_code(self):\n return self.__wrapped.gi_code\n @property\n def gi_frame(self):\n return self.__wrapped.gi_frame\n @property\n def gi_running(self):\n return self.__wrapped.gi_running\n @property\n def gi_yieldfrom(self):\n return self.__wrapped.gi_yieldfrom\n cr_code=gi_code\n cr_frame=gi_frame\n cr_running=gi_running\n cr_await=gi_yieldfrom\n def __next__(self):\n return next(self.__wrapped)\n def __iter__(self):\n if self.__isgen:\n return self.__wrapped\n return self\n __await__=__iter__\n \ndef coroutine(func):\n ''\n \n if not callable(func):\n raise TypeError('types.coroutine() expects a callable')\n \n if (func.__class__ is FunctionType and\n getattr(func,'__code__',None ).__class__ is CodeType):\n \n co_flags=func.__code__.co_flags\n \n \n \n if co_flags&0x180:\n return func\n \n \n \n if co_flags&0x20:\n \n co=func.__code__\n func.__code__=CodeType(\n co.co_argcount,co.co_kwonlyargcount,co.co_nlocals,\n co.co_stacksize,\n co.co_flags |0x100,\n co.co_code,\n co.co_consts,co.co_names,co.co_varnames,co.co_filename,\n co.co_name,co.co_firstlineno,co.co_lnotab,co.co_freevars,\n co.co_cellvars)\n return func\n \n \n \n \n \n \n import functools\n import _collections_abc\n @functools.wraps(func)\n def wrapped(*args,**kwargs):\n coro=func(*args,**kwargs)\n if (coro.__class__ is CoroutineType or\n coro.__class__ is GeneratorType and coro.gi_code.co_flags&0x100):\n \n return coro\n if (isinstance(coro,_collections_abc.Generator)and\n not isinstance(coro,_collections_abc.Coroutine)):\n \n \n \n return _GeneratorWrapper(coro)\n \n \n return coro\n \n return wrapped\n \n \n__all__=[n for n in globals()if n[:1]!='_']\n", ["_collections_abc", "functools", "sys"]], "atexit": [".py", "''\n\n\n\n\n\nclass __loader__(object):\n pass\n \ndef _clear(*args,**kw):\n ''\n \n pass\n \ndef _run_exitfuncs(*args,**kw):\n ''\n \n pass\n \ndef register(*args,**kw):\n ''\n\n\n\n\n\n\n \n pass\n \ndef unregister(*args,**kw):\n ''\n\n\n\n \n pass\n", []], "_collections_abc": [".py", "\n\n\n\"\"\"Abstract Base Classes (ABCs) for collections, according to PEP 3119.\n\nUnit tests are in test_collections.\n\"\"\"\n\nfrom abc import ABCMeta,abstractmethod\nimport sys\n\n__all__=[\"Awaitable\",\"Coroutine\",\n\"AsyncIterable\",\"AsyncIterator\",\"AsyncGenerator\",\n\"Hashable\",\"Iterable\",\"Iterator\",\"Generator\",\"Reversible\",\n\"Sized\",\"Container\",\"Callable\",\"Collection\",\n\"Set\",\"MutableSet\",\n\"Mapping\",\"MutableMapping\",\n\"MappingView\",\"KeysView\",\"ItemsView\",\"ValuesView\",\n\"Sequence\",\"MutableSequence\",\n\"ByteString\",\n]\n\n\n\n\n\n__name__=\"collections.abc\"\n\n\n\n\n\n\n\n\nbytes_iterator=type(iter(b''))\nbytearray_iterator=type(iter(bytearray()))\n\ndict_keyiterator=type(iter({}.keys()))\ndict_valueiterator=type(iter({}.values()))\ndict_itemiterator=type(iter({}.items()))\nlist_iterator=type(iter([]))\nlist_reverseiterator=type(iter(reversed([])))\nrange_iterator=type(iter(range(0)))\nlongrange_iterator=type(iter(range(1 <<1000)))\nset_iterator=type(iter(set()))\nstr_iterator=type(iter(\"\"))\ntuple_iterator=type(iter(()))\nzip_iterator=type(iter(zip()))\n\ndict_keys=type({}.keys())\ndict_values=type({}.values())\ndict_items=type({}.items())\n\nmappingproxy=type(type.__dict__)\ngenerator=type((lambda :(yield ))())\n\nasync def _coro():pass\n_coro=_coro()\ncoroutine=type(_coro)\n_coro.close()\ndel _coro\n\nasync def _ag():yield\n_ag=_ag()\nasync_generator=type(_ag)\ndel _ag\n\n\n\n\ndef _check_methods(C,*methods):\n mro=C.__mro__\n for method in methods:\n for B in mro:\n if method in B.__dict__:\n if B.__dict__[method]is None :\n return NotImplemented\n break\n else :\n return NotImplemented\n return True\n \nclass Hashable(metaclass=ABCMeta):\n\n __slots__=()\n \n @abstractmethod\n def __hash__(self):\n return 0\n \n @classmethod\n def __subclasshook__(cls,C):\n if cls is Hashable:\n return _check_methods(C,\"__hash__\")\n return NotImplemented\n \n \nclass Awaitable(metaclass=ABCMeta):\n\n __slots__=()\n \n @abstractmethod\n def __await__(self):\n yield\n \n @classmethod\n def __subclasshook__(cls,C):\n if cls is Awaitable:\n return _check_methods(C,\"__await__\")\n return NotImplemented\n \n \nclass Coroutine(Awaitable):\n\n __slots__=()\n \n @abstractmethod\n def send(self,value):\n ''\n\n \n raise StopIteration\n \n @abstractmethod\n def throw(self,typ,val=None ,tb=None ):\n ''\n\n \n if val is None :\n if tb is None :\n raise typ\n val=typ()\n if tb is not None :\n val=val.with_traceback(tb)\n raise val\n \n def close(self):\n ''\n \n try :\n self.throw(GeneratorExit)\n except (GeneratorExit,StopIteration):\n pass\n else :\n raise RuntimeError(\"coroutine ignored GeneratorExit\")\n \n @classmethod\n def __subclasshook__(cls,C):\n if cls is Coroutine:\n return _check_methods(C,'__await__','send','throw','close')\n return NotImplemented\n \n \nCoroutine.register(coroutine)\n\n\nclass AsyncIterable(metaclass=ABCMeta):\n\n __slots__=()\n \n @abstractmethod\n def __aiter__(self):\n return AsyncIterator()\n \n @classmethod\n def __subclasshook__(cls,C):\n if cls is AsyncIterable:\n return _check_methods(C,\"__aiter__\")\n return NotImplemented\n \n \nclass AsyncIterator(AsyncIterable):\n\n __slots__=()\n \n @abstractmethod\n async def __anext__(self):\n ''\n raise StopAsyncIteration\n \n def __aiter__(self):\n return self\n \n @classmethod\n def __subclasshook__(cls,C):\n if cls is AsyncIterator:\n return _check_methods(C,\"__anext__\",\"__aiter__\")\n return NotImplemented\n \n \nclass AsyncGenerator(AsyncIterator):\n\n __slots__=()\n \n async def __anext__(self):\n ''\n\n \n return await self.asend(None )\n \n @abstractmethod\n async def asend(self,value):\n ''\n\n \n raise StopAsyncIteration\n \n @abstractmethod\n async def athrow(self,typ,val=None ,tb=None ):\n ''\n\n \n if val is None :\n if tb is None :\n raise typ\n val=typ()\n if tb is not None :\n val=val.with_traceback(tb)\n raise val\n \n async def aclose(self):\n ''\n \n try :\n await self.athrow(GeneratorExit)\n except (GeneratorExit,StopAsyncIteration):\n pass\n else :\n raise RuntimeError(\"asynchronous generator ignored GeneratorExit\")\n \n @classmethod\n def __subclasshook__(cls,C):\n if cls is AsyncGenerator:\n return _check_methods(C,'__aiter__','__anext__',\n 'asend','athrow','aclose')\n return NotImplemented\n \n \nAsyncGenerator.register(async_generator)\n\n\nclass Iterable(metaclass=ABCMeta):\n\n __slots__=()\n \n @abstractmethod\n def __iter__(self):\n while False :\n yield None\n \n @classmethod\n def __subclasshook__(cls,C):\n if cls is Iterable:\n return _check_methods(C,\"__iter__\")\n return NotImplemented\n \n \nclass Iterator(Iterable):\n\n __slots__=()\n \n @abstractmethod\n def __next__(self):\n ''\n raise StopIteration\n \n def __iter__(self):\n return self\n \n @classmethod\n def __subclasshook__(cls,C):\n if cls is Iterator:\n return _check_methods(C,'__iter__','__next__')\n return NotImplemented\n \nIterator.register(bytes_iterator)\nIterator.register(bytearray_iterator)\n\nIterator.register(dict_keyiterator)\nIterator.register(dict_valueiterator)\nIterator.register(dict_itemiterator)\nIterator.register(list_iterator)\nIterator.register(list_reverseiterator)\nIterator.register(range_iterator)\nIterator.register(longrange_iterator)\nIterator.register(set_iterator)\nIterator.register(str_iterator)\nIterator.register(tuple_iterator)\nIterator.register(zip_iterator)\n\n\nclass Reversible(Iterable):\n\n __slots__=()\n \n @abstractmethod\n def __reversed__(self):\n while False :\n yield None\n \n @classmethod\n def __subclasshook__(cls,C):\n if cls is Reversible:\n return _check_methods(C,\"__reversed__\",\"__iter__\")\n return NotImplemented\n \n \nclass Generator(Iterator):\n\n __slots__=()\n \n def __next__(self):\n ''\n\n \n return self.send(None )\n \n @abstractmethod\n def send(self,value):\n ''\n\n \n raise StopIteration\n \n @abstractmethod\n def throw(self,typ,val=None ,tb=None ):\n ''\n\n \n if val is None :\n if tb is None :\n raise typ\n val=typ()\n if tb is not None :\n val=val.with_traceback(tb)\n raise val\n \n def close(self):\n ''\n \n try :\n self.throw(GeneratorExit)\n except (GeneratorExit,StopIteration):\n pass\n else :\n raise RuntimeError(\"generator ignored GeneratorExit\")\n \n @classmethod\n def __subclasshook__(cls,C):\n if cls is Generator:\n return _check_methods(C,'__iter__','__next__',\n 'send','throw','close')\n return NotImplemented\n \nGenerator.register(generator)\n\n\nclass Sized(metaclass=ABCMeta):\n\n __slots__=()\n \n @abstractmethod\n def __len__(self):\n return 0\n \n @classmethod\n def __subclasshook__(cls,C):\n if cls is Sized:\n return _check_methods(C,\"__len__\")\n return NotImplemented\n \n \nclass Container(metaclass=ABCMeta):\n\n __slots__=()\n \n @abstractmethod\n def __contains__(self,x):\n return False\n \n @classmethod\n def __subclasshook__(cls,C):\n if cls is Container:\n return _check_methods(C,\"__contains__\")\n return NotImplemented\n \nclass Collection(Sized,Iterable,Container):\n\n __slots__=()\n \n @classmethod\n def __subclasshook__(cls,C):\n if cls is Collection:\n return _check_methods(C,\"__len__\",\"__iter__\",\"__contains__\")\n return NotImplemented\n \nclass Callable(metaclass=ABCMeta):\n\n __slots__=()\n \n @abstractmethod\n def __call__(self,*args,**kwds):\n return False\n \n @classmethod\n def __subclasshook__(cls,C):\n if cls is Callable:\n return _check_methods(C,\"__call__\")\n return NotImplemented\n \n \n \n \n \nclass Set(Collection):\n\n ''\n\n\n\n\n\n\n\n \n \n __slots__=()\n \n def __le__(self,other):\n if not isinstance(other,Set):\n return NotImplemented\n if len(self)>len(other):\n return False\n for elem in self:\n if elem not in other:\n return False\n return True\n \n def __lt__(self,other):\n if not isinstance(other,Set):\n return NotImplemented\n return len(self)<len(other)and self.__le__(other)\n \n def __gt__(self,other):\n if not isinstance(other,Set):\n return NotImplemented\n return len(self)>len(other)and self.__ge__(other)\n \n def __ge__(self,other):\n if not isinstance(other,Set):\n return NotImplemented\n if len(self)<len(other):\n return False\n for elem in other:\n if elem not in self:\n return False\n return True\n \n def __eq__(self,other):\n if not isinstance(other,Set):\n return NotImplemented\n return len(self)==len(other)and self.__le__(other)\n \n @classmethod\n def _from_iterable(cls,it):\n ''\n\n\n\n \n return cls(it)\n \n def __and__(self,other):\n if not isinstance(other,Iterable):\n return NotImplemented\n return self._from_iterable(value for value in other if value in self)\n \n __rand__=__and__\n \n def isdisjoint(self,other):\n ''\n for value in other:\n if value in self:\n return False\n return True\n \n def __or__(self,other):\n if not isinstance(other,Iterable):\n return NotImplemented\n chain=(e for s in (self,other)for e in s)\n return self._from_iterable(chain)\n \n __ror__=__or__\n \n def __sub__(self,other):\n if not isinstance(other,Set):\n if not isinstance(other,Iterable):\n return NotImplemented\n other=self._from_iterable(other)\n return self._from_iterable(value for value in self\n if value not in other)\n \n def __rsub__(self,other):\n if not isinstance(other,Set):\n if not isinstance(other,Iterable):\n return NotImplemented\n other=self._from_iterable(other)\n return self._from_iterable(value for value in other\n if value not in self)\n \n def __xor__(self,other):\n if not isinstance(other,Set):\n if not isinstance(other,Iterable):\n return NotImplemented\n other=self._from_iterable(other)\n return (self -other)|(other -self)\n \n __rxor__=__xor__\n \n def _hash(self):\n ''\n\n\n\n\n\n\n\n\n\n\n\n\n \n MAX=sys.maxsize\n MASK=2 *MAX+1\n n=len(self)\n h=1927868237 *(n+1)\n h &=MASK\n for x in self:\n hx=hash(x)\n h ^=(hx ^(hx <<16)^89869747)*3644798167\n h &=MASK\n h=h *69069+907133923\n h &=MASK\n if h >MAX:\n h -=MASK+1\n if h ==-1:\n h=590923713\n return h\n \nSet.register(frozenset)\n\n\nclass MutableSet(Set):\n ''\n\n\n\n\n\n\n\n\n \n \n __slots__=()\n \n @abstractmethod\n def add(self,value):\n ''\n raise NotImplementedError\n \n @abstractmethod\n def discard(self,value):\n ''\n raise NotImplementedError\n \n def remove(self,value):\n ''\n if value not in self:\n raise KeyError(value)\n self.discard(value)\n \n def pop(self):\n ''\n it=iter(self)\n try :\n value=next(it)\n except StopIteration:\n raise KeyError from None\n self.discard(value)\n return value\n \n def clear(self):\n ''\n try :\n while True :\n self.pop()\n except KeyError:\n pass\n \n def __ior__(self,it):\n for value in it:\n self.add(value)\n return self\n \n def __iand__(self,it):\n for value in (self -it):\n self.discard(value)\n return self\n \n def __ixor__(self,it):\n if it is self:\n self.clear()\n else :\n if not isinstance(it,Set):\n it=self._from_iterable(it)\n for value in it:\n if value in self:\n self.discard(value)\n else :\n self.add(value)\n return self\n \n def __isub__(self,it):\n if it is self:\n self.clear()\n else :\n for value in it:\n self.discard(value)\n return self\n \nMutableSet.register(set)\n\n\n\n\n\nclass Mapping(Collection):\n\n __slots__=()\n \n \"\"\"A Mapping is a generic container for associating key/value\n pairs.\n\n This class provides concrete generic implementations of all\n methods except for __getitem__, __iter__, and __len__.\n\n \"\"\"\n \n @abstractmethod\n def __getitem__(self,key):\n raise KeyError\n \n def get(self,key,default=None ):\n ''\n try :\n return self[key]\n except KeyError:\n return default\n \n def __contains__(self,key):\n try :\n self[key]\n except KeyError:\n return False\n else :\n return True\n \n def keys(self):\n ''\n return KeysView(self)\n \n def items(self):\n ''\n return ItemsView(self)\n \n def values(self):\n ''\n return ValuesView(self)\n \n def __eq__(self,other):\n if not isinstance(other,Mapping):\n return NotImplemented\n return dict(self.items())==dict(other.items())\n \n __reversed__=None\n \nMapping.register(mappingproxy)\n\n\nclass MappingView(Sized):\n\n __slots__='_mapping',\n \n def __init__(self,mapping):\n self._mapping=mapping\n \n def __len__(self):\n return len(self._mapping)\n \n def __repr__(self):\n return '{0.__class__.__name__}({0._mapping!r})'.format(self)\n \n \nclass KeysView(MappingView,Set):\n\n __slots__=()\n \n @classmethod\n def _from_iterable(self,it):\n return set(it)\n \n def __contains__(self,key):\n return key in self._mapping\n \n def __iter__(self):\n yield from self._mapping\n \nKeysView.register(dict_keys)\n\n\nclass ItemsView(MappingView,Set):\n\n __slots__=()\n \n @classmethod\n def _from_iterable(self,it):\n return set(it)\n \n def __contains__(self,item):\n key,value=item\n try :\n v=self._mapping[key]\n except KeyError:\n return False\n else :\n return v is value or v ==value\n \n def __iter__(self):\n for key in self._mapping:\n yield (key,self._mapping[key])\n \nItemsView.register(dict_items)\n\n\nclass ValuesView(MappingView,Collection):\n\n __slots__=()\n \n def __contains__(self,value):\n for key in self._mapping:\n v=self._mapping[key]\n if v is value or v ==value:\n return True\n return False\n \n def __iter__(self):\n for key in self._mapping:\n yield self._mapping[key]\n \nValuesView.register(dict_values)\n\n\nclass MutableMapping(Mapping):\n\n __slots__=()\n \n \"\"\"A MutableMapping is a generic container for associating\n key/value pairs.\n\n This class provides concrete generic implementations of all\n methods except for __getitem__, __setitem__, __delitem__,\n __iter__, and __len__.\n\n \"\"\"\n \n @abstractmethod\n def __setitem__(self,key,value):\n raise KeyError\n \n @abstractmethod\n def __delitem__(self,key):\n raise KeyError\n \n __marker=object()\n \n def pop(self,key,default=__marker):\n ''\n\n \n try :\n value=self[key]\n except KeyError:\n if default is self.__marker:\n raise\n return default\n else :\n del self[key]\n return value\n \n def popitem(self):\n ''\n\n \n try :\n key=next(iter(self))\n except StopIteration:\n raise KeyError from None\n value=self[key]\n del self[key]\n return key,value\n \n def clear(self):\n ''\n try :\n while True :\n self.popitem()\n except KeyError:\n pass\n \n def update(*args,**kwds):\n ''\n\n\n\n \n if not args:\n raise TypeError(\"descriptor 'update' of 'MutableMapping' object \"\n \"needs an argument\")\n self,*args=args\n if len(args)>1:\n raise TypeError('update expected at most 1 arguments, got %d'%\n len(args))\n if args:\n other=args[0]\n if isinstance(other,Mapping):\n for key in other:\n self[key]=other[key]\n elif hasattr(other,\"keys\"):\n for key in other.keys():\n self[key]=other[key]\n else :\n for key,value in other:\n self[key]=value\n for key,value in kwds.items():\n self[key]=value\n \n def setdefault(self,key,default=None ):\n ''\n try :\n return self[key]\n except KeyError:\n self[key]=default\n return default\n \nMutableMapping.register(dict)\n\n\n\n\n\nclass Sequence(Reversible,Collection):\n\n ''\n\n\n\n \n \n __slots__=()\n \n @abstractmethod\n def __getitem__(self,index):\n raise IndexError\n \n def __iter__(self):\n i=0\n try :\n while True :\n v=self[i]\n yield v\n i +=1\n except IndexError:\n return\n \n def __contains__(self,value):\n for v in self:\n if v is value or v ==value:\n return True\n return False\n \n def __reversed__(self):\n for i in reversed(range(len(self))):\n yield self[i]\n \n def index(self,value,start=0,stop=None ):\n ''\n\n\n\n\n \n if start is not None and start <0:\n start=max(len(self)+start,0)\n if stop is not None and stop <0:\n stop +=len(self)\n \n i=start\n while stop is None or i <stop:\n try :\n v=self[i]\n if v is value or v ==value:\n return i\n except IndexError:\n break\n i +=1\n raise ValueError\n \n def count(self,value):\n ''\n return sum(1 for v in self if v is value or v ==value)\n \nSequence.register(tuple)\nSequence.register(str)\nSequence.register(range)\nSequence.register(memoryview)\n\n\nclass ByteString(Sequence):\n\n ''\n\n\n \n \n __slots__=()\n \nByteString.register(bytes)\nByteString.register(bytearray)\n\n\nclass MutableSequence(Sequence):\n\n __slots__=()\n \n \"\"\"All the operations on a read-write sequence.\n\n Concrete subclasses must provide __new__ or __init__,\n __getitem__, __setitem__, __delitem__, __len__, and insert().\n\n \"\"\"\n \n @abstractmethod\n def __setitem__(self,index,value):\n raise IndexError\n \n @abstractmethod\n def __delitem__(self,index):\n raise IndexError\n \n @abstractmethod\n def insert(self,index,value):\n ''\n raise IndexError\n \n def append(self,value):\n ''\n self.insert(len(self),value)\n \n def clear(self):\n ''\n try :\n while True :\n self.pop()\n except IndexError:\n pass\n \n def reverse(self):\n ''\n n=len(self)\n for i in range(n //2):\n self[i],self[n -i -1]=self[n -i -1],self[i]\n \n def extend(self,values):\n ''\n for v in values:\n self.append(v)\n \n def pop(self,index=-1):\n ''\n\n \n v=self[index]\n del self[index]\n return v\n \n def remove(self,value):\n ''\n\n \n del self[self.index(value)]\n \n def __iadd__(self,values):\n self.extend(values)\n return self\n \nMutableSequence.register(list)\nMutableSequence.register(bytearray)\n", ["abc", "sys"]], "_collections": [".py", "\n\n\n\n\n\n\n\n\n\nimport operator\n\n\n\ndef _thread_ident():\n return -1\n \n \nn=30\nLFTLNK=n\nRGTLNK=n+1\nBLOCKSIZ=n+2\n\n\n\n\n\n\n\n\nclass deque:\n\n def __new__(cls,iterable=(),*args,**kw):\n \n \n self=object.__new__(cls,*args,**kw)\n self.clear()\n return self\n \n def __init__(self,iterable=(),maxlen=None ):\n object.__init__(self)\n self.clear()\n if maxlen is not None :\n if maxlen <0:\n raise ValueError(\"maxlen must be non-negative\")\n self._maxlen=maxlen\n add=self.append\n for elem in iterable:\n add(elem)\n \n @property\n def maxlen(self):\n return self._maxlen\n \n def clear(self):\n self.right=self.left=[None ]*BLOCKSIZ\n self.rightndx=n //2\n self.leftndx=n //2+1\n self.length=0\n self.state=0\n \n def append(self,x):\n self.state +=1\n self.rightndx +=1\n if self.rightndx ==n:\n newblock=[None ]*BLOCKSIZ\n self.right[RGTLNK]=newblock\n newblock[LFTLNK]=self.right\n self.right=newblock\n self.rightndx=0\n self.length +=1\n self.right[self.rightndx]=x\n if self.maxlen is not None and self.length >self.maxlen:\n self.popleft()\n \n def appendleft(self,x):\n self.state +=1\n self.leftndx -=1\n if self.leftndx ==-1:\n newblock=[None ]*BLOCKSIZ\n self.left[LFTLNK]=newblock\n newblock[RGTLNK]=self.left\n self.left=newblock\n self.leftndx=n -1\n self.length +=1\n self.left[self.leftndx]=x\n if self.maxlen is not None and self.length >self.maxlen:\n self.pop()\n \n def extend(self,iterable):\n if iterable is self:\n iterable=list(iterable)\n for elem in iterable:\n self.append(elem)\n \n def extendleft(self,iterable):\n if iterable is self:\n iterable=list(iterable)\n for elem in iterable:\n self.appendleft(elem)\n \n def pop(self):\n if self.left is self.right and self.leftndx >self.rightndx:\n \n raise IndexError(\"pop from an empty deque\")\n x=self.right[self.rightndx]\n self.right[self.rightndx]=None\n self.length -=1\n self.rightndx -=1\n self.state +=1\n if self.rightndx ==-1:\n prevblock=self.right[LFTLNK]\n if prevblock is None :\n \n self.rightndx=n //2\n self.leftndx=n //2+1\n else :\n prevblock[RGTLNK]=None\n self.right[LFTLNK]=None\n self.right=prevblock\n self.rightndx=n -1\n return x\n \n def popleft(self):\n if self.left is self.right and self.leftndx >self.rightndx:\n \n raise IndexError(\"pop from an empty deque\")\n x=self.left[self.leftndx]\n self.left[self.leftndx]=None\n self.length -=1\n self.leftndx +=1\n self.state +=1\n if self.leftndx ==n:\n prevblock=self.left[RGTLNK]\n if prevblock is None :\n \n self.rightndx=n //2\n self.leftndx=n //2+1\n else :\n prevblock[LFTLNK]=None\n self.left[RGTLNK]=None\n self.left=prevblock\n self.leftndx=0\n return x\n \n def count(self,value):\n c=0\n for item in self:\n if item ==value:\n c +=1\n return c\n \n def remove(self,value):\n \n for i in range(len(self)):\n if self[i]==value:\n del self[i]\n return\n raise ValueError(\"deque.remove(x): x not in deque\")\n \n def rotate(self,n=1):\n length=len(self)\n if length ==0:\n return\n halflen=(length+1)>>1\n if n >halflen or n <-halflen:\n n %=length\n if n >halflen:\n n -=length\n elif n <-halflen:\n n +=length\n while n >0:\n self.appendleft(self.pop())\n n -=1\n while n <0:\n self.append(self.popleft())\n n +=1\n \n def reverse(self):\n ''\n leftblock=self.left\n rightblock=self.right\n leftindex=self.leftndx\n rightindex=self.rightndx\n for i in range(self.length //2):\n \n assert leftblock !=rightblock or leftindex <rightindex\n \n \n (rightblock[rightindex],leftblock[leftindex])=(\n leftblock[leftindex],rightblock[rightindex])\n \n \n leftindex +=1\n if leftindex ==n:\n leftblock=leftblock[RGTLNK]\n assert leftblock is not None\n leftindex=0\n \n \n rightindex -=1\n if rightindex ==-1:\n rightblock=rightblock[LFTLNK]\n assert rightblock is not None\n rightindex=n -1\n \n def __repr__(self):\n threadlocalattr='__repr'+str(_thread_ident())\n if threadlocalattr in self.__dict__:\n return 'deque([...])'\n else :\n self.__dict__[threadlocalattr]=True\n try :\n if self.maxlen is not None :\n return 'deque(%r, maxlen=%s)'%(list(self),self.maxlen)\n else :\n return 'deque(%r)'%(list(self),)\n finally :\n del self.__dict__[threadlocalattr]\n \n def __iter__(self):\n return deque_iterator(self,self._iter_impl)\n \n def _iter_impl(self,original_state,giveup):\n if self.state !=original_state:\n giveup()\n block=self.left\n while block:\n l,r=0,n\n if block is self.left:\n l=self.leftndx\n if block is self.right:\n r=self.rightndx+1\n for elem in block[l:r]:\n yield elem\n if self.state !=original_state:\n giveup()\n block=block[RGTLNK]\n \n def __reversed__(self):\n return deque_iterator(self,self._reversed_impl)\n \n def _reversed_impl(self,original_state,giveup):\n if self.state !=original_state:\n giveup()\n block=self.right\n while block:\n l,r=0,n\n if block is self.left:\n l=self.leftndx\n if block is self.right:\n r=self.rightndx+1\n for elem in reversed(block[l:r]):\n yield elem\n if self.state !=original_state:\n giveup()\n block=block[LFTLNK]\n \n def __len__(self):\n \n \n \n \n \n \n return self.length\n \n def __getref(self,index):\n if index >=0:\n block=self.left\n while block:\n l,r=0,n\n if block is self.left:\n l=self.leftndx\n if block is self.right:\n r=self.rightndx+1\n span=r -l\n if index <span:\n return block,l+index\n index -=span\n block=block[RGTLNK]\n else :\n block=self.right\n while block:\n l,r=0,n\n if block is self.left:\n l=self.leftndx\n if block is self.right:\n r=self.rightndx+1\n negative_span=l -r\n if index >=negative_span:\n return block,r+index\n index -=negative_span\n block=block[LFTLNK]\n raise IndexError(\"deque index out of range\")\n \n def __getitem__(self,index):\n block,index=self.__getref(index)\n return block[index]\n \n def __setitem__(self,index,value):\n block,index=self.__getref(index)\n block[index]=value\n \n def __delitem__(self,index):\n length=len(self)\n if index >=0:\n if index >=length:\n raise IndexError(\"deque index out of range\")\n self.rotate(-index)\n self.popleft()\n self.rotate(index)\n else :\n \n index=index ^(2 **31)\n if index >=length:\n raise IndexError(\"deque index out of range\")\n self.rotate(index)\n self.pop()\n self.rotate(-index)\n \n def __reduce_ex__(self,proto):\n return type(self),(list(self),self.maxlen)\n \n def __hash__(self):\n \n raise TypeError(\"deque objects are unhashable\")\n \n def __copy__(self):\n return self.__class__(self,self.maxlen)\n \n \n def __eq__(self,other):\n if isinstance(other,deque):\n return list(self)==list(other)\n else :\n return NotImplemented\n \n def __ne__(self,other):\n if isinstance(other,deque):\n return list(self)!=list(other)\n else :\n return NotImplemented\n \n def __lt__(self,other):\n if isinstance(other,deque):\n return list(self)<list(other)\n else :\n return NotImplemented\n \n def __le__(self,other):\n if isinstance(other,deque):\n return list(self)<=list(other)\n else :\n return NotImplemented\n \n def __gt__(self,other):\n if isinstance(other,deque):\n return list(self)>list(other)\n else :\n return NotImplemented\n \n def __ge__(self,other):\n if isinstance(other,deque):\n return list(self)>=list(other)\n else :\n return NotImplemented\n \n def __iadd__(self,other):\n self.extend(other)\n return self\n \n \nclass deque_iterator(object):\n\n def __init__(self,deq,itergen):\n self.counter=len(deq)\n def giveup():\n self.counter=0\n \n raise RuntimeError(\"deque mutated during iteration\")\n self._gen=itergen(deq.state,giveup)\n \n def __next__(self):\n res=self._gen.__next__()\n self.counter -=1\n return res\n \n def __iter__(self):\n return self\n \nclass defaultdict(dict):\n\n def __init__(self,*args,**kwds):\n if len(args)>0:\n default_factory=args[0]\n args=args[1:]\n if not callable(default_factory)and default_factory is not None :\n raise TypeError(\"first argument must be callable\")\n else :\n default_factory=None\n dict.__init__(self,*args,**kwds)\n self.default_factory=default_factory\n self.update(*args,**kwds)\n super(defaultdict,self).__init__(*args,**kwds)\n \n def __missing__(self,key):\n \n if self.default_factory is None :\n raise KeyError(key)\n self[key]=value=self.default_factory()\n return value\n \n def __repr__(self,recurse=set()):\n if id(self)in recurse:\n return \"defaultdict(...)\"\n try :\n recurse.add(id(self))\n return \"defaultdict(%s, %s)\"%(repr(self.default_factory),super(defaultdict,self).__repr__())\n finally :\n recurse.remove(id(self))\n \n def copy(self):\n return type(self)(self.default_factory,self)\n \n def __copy__(self):\n return self.copy()\n \n def __reduce__(self):\n \n \n \n \n \n \n \n \n \n \n \n return (type(self),(self.default_factory,),None ,None ,self.items())\n \nfrom operator import itemgetter as _itemgetter\nfrom keyword import iskeyword as _iskeyword\nimport sys as _sys\n\ndef namedtuple(typename,field_names,verbose=False ,rename=False ):\n ''\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n \n \n \n \n if isinstance(field_names,str):\n field_names=field_names.replace(',',' ').split()\n field_names=tuple(map(str,field_names))\n if rename:\n names=list(field_names)\n seen=set()\n for i,name in enumerate(names):\n if (not min(c.isalnum()or c =='_'for c in name)or _iskeyword(name)\n or not name or name[0].isdigit()or name.startswith('_')\n or name in seen):\n names[i]='_%d'%i\n seen.add(name)\n field_names=tuple(names)\n for name in (typename,)+field_names:\n if not min(c.isalnum()or c =='_'for c in name):\n raise ValueError('Type names and field names can only contain alphanumeric characters and underscores: %r'%name)\n if _iskeyword(name):\n raise ValueError('Type names and field names cannot be a keyword: %r'%name)\n if name[0].isdigit():\n raise ValueError('Type names and field names cannot start with a number: %r'%name)\n seen_names=set()\n for name in field_names:\n if name.startswith('_')and not rename:\n raise ValueError('Field names cannot start with an underscore: %r'%name)\n if name in seen_names:\n raise ValueError('Encountered duplicate field name: %r'%name)\n seen_names.add(name)\n \n \n numfields=len(field_names)\n argtxt=repr(field_names).replace(\"'\",\"\")[1:-1]\n reprtxt=', '.join('%s=%%r'%name for name in field_names)\n \n template='''class %(typename)s(tuple):\n '%(typename)s(%(argtxt)s)' \\n\n __slots__ = () \\n\n _fields = %(field_names)r \\n\n def __new__(_cls, %(argtxt)s):\n return tuple.__new__(_cls, (%(argtxt)s)) \\n\n @classmethod\n def _make(cls, iterable, new=tuple.__new__, len=len):\n 'Make a new %(typename)s object from a sequence or iterable'\n result = new(cls, iterable)\n if len(result) != %(numfields)d:\n raise TypeError('Expected %(numfields)d arguments, got %%d' %% len(result))\n return result \\n\n def __repr__(self):\n return '%(typename)s(%(reprtxt)s)' %% self \\n\n def _asdict(self):\n 'Return a new dict which maps field names to their values'\n return dict(zip(self._fields, self)) \\n\n def _replace(_self, **kwds):\n 'Return a new %(typename)s object replacing specified fields with new values'\n result = _self._make(map(kwds.pop, %(field_names)r, _self))\n if kwds:\n raise ValueError('Got unexpected field names: %%r' %% kwds.keys())\n return result \\n\n def __getnewargs__(self):\n return tuple(self) \\n\\n'''%locals()\n for i,name in enumerate(field_names):\n template +=' %s = _property(_itemgetter(%d))\\n'%(name,i)\n \n if verbose:\n print(template)\n \n \n namespace=dict(_itemgetter=_itemgetter,__name__='namedtuple_%s'%typename,\n _property=property,_tuple=tuple)\n try :\n exec(template,namespace)\n except SyntaxError as e:\n raise SyntaxError(e.message+':\\n'+template)\n result=namespace[typename]\n \n \n \n \n \n try :\n result.__module__=_sys._getframe(1).f_globals.get('__name__','__main__')\n except (AttributeError,ValueError):\n pass\n \n return result\n \nif __name__ =='__main__':\n Point=namedtuple('Point',['x','y'])\n p=Point(11,y=22)\n print(p[0]+p[1])\n x,y=p\n print(x,y)\n print(p.x+p.y)\n print(p)\n", ["keyword", "operator", "sys"]], "_io": [".py", "''\n\n\n\nimport os\nimport abc\nimport codecs\nimport errno\n\ntry :\n from _thread import allocate_lock as Lock\nexcept ImportError:\n from _dummy_thread import allocate_lock as Lock\n \nSEEK_SET=0\nSEEK_CUR=1\nSEEK_END=2\n\nvalid_seek_flags={0,1,2}\nif hasattr(os,'SEEK_HOLE'):\n valid_seek_flags.add(os.SEEK_HOLE)\n valid_seek_flags.add(os.SEEK_DATA)\n \n \nDEFAULT_BUFFER_SIZE=8 *1024\n\n\n\n\n\n\nBlockingIOError=BlockingIOError\n\n\ndef __open(file,mode=\"r\",buffering=-1,encoding=None ,errors=None ,\nnewline=None ,closefd=True ,opener=None ):\n\n ''\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n \n if not isinstance(file,(str,bytes,int)):\n raise TypeError(\"invalid file: %r\"%file)\n if not isinstance(mode,str):\n raise TypeError(\"invalid mode: %r\"%mode)\n if not isinstance(buffering,int):\n raise TypeError(\"invalid buffering: %r\"%buffering)\n if encoding is not None and not isinstance(encoding,str):\n raise TypeError(\"invalid encoding: %r\"%encoding)\n if errors is not None and not isinstance(errors,str):\n raise TypeError(\"invalid errors: %r\"%errors)\n modes=set(mode)\n if modes -set(\"axrwb+tU\")or len(mode)>len(modes):\n raise ValueError(\"invalid mode: %r\"%mode)\n creating=\"x\"in modes\n reading=\"r\"in modes\n writing=\"w\"in modes\n appending=\"a\"in modes\n updating=\"+\"in modes\n text=\"t\"in modes\n binary=\"b\"in modes\n if \"U\"in modes:\n if creating or writing or appending:\n raise ValueError(\"can't use U and writing mode at once\")\n reading=True\n if text and binary:\n raise ValueError(\"can't have text and binary mode at once\")\n if creating+reading+writing+appending >1:\n raise ValueError(\"can't have read/write/append mode at once\")\n if not (creating or reading or writing or appending):\n raise ValueError(\"must have exactly one of read/write/append mode\")\n if binary and encoding is not None :\n raise ValueError(\"binary mode doesn't take an encoding argument\")\n if binary and errors is not None :\n raise ValueError(\"binary mode doesn't take an errors argument\")\n if binary and newline is not None :\n raise ValueError(\"binary mode doesn't take a newline argument\")\n raw=FileIO(file,\n (creating and \"x\"or \"\")+\n (reading and \"r\"or \"\")+\n (writing and \"w\"or \"\")+\n (appending and \"a\"or \"\")+\n (updating and \"+\"or \"\"),\n closefd,opener=opener)\n line_buffering=False\n if buffering ==1 or buffering <0 and raw.isatty():\n buffering=-1\n line_buffering=True\n if buffering <0:\n buffering=DEFAULT_BUFFER_SIZE\n try :\n bs=os.fstat(raw.fileno()).st_blksize\n except (os.error,AttributeError):\n pass\n else :\n if bs >1:\n buffering=bs\n if buffering <0:\n raise ValueError(\"invalid buffering size\")\n if buffering ==0:\n if binary:\n return raw\n raise ValueError(\"can't have unbuffered text I/O\")\n if updating:\n buffer=BufferedRandom(raw,buffering)\n elif creating or writing or appending:\n buffer=BufferedWriter(raw,buffering)\n elif reading:\n buffer=BufferedReader(raw,buffering)\n else :\n raise ValueError(\"unknown mode: %r\"%mode)\n if binary:\n return buffer\n text=TextIOWrapper(buffer,encoding,errors,newline,line_buffering)\n text.mode=mode\n return text\n \nopen=__open\n\nclass DocDescriptor:\n ''\n \n def __get__(self,obj,typ):\n return (\n \"open(file, mode='r', buffering=-1, encoding=None, \"\n \"errors=None, newline=None, closefd=True)\\n\\n\"+\n open.__doc__)\n \nclass OpenWrapper:\n ''\n\n\n\n\n\n \n __doc__=DocDescriptor()\n \n def __new__(cls,*args,**kwargs):\n return open(*args,**kwargs)\n \n \n \n \nclass UnsupportedOperation(ValueError,IOError):\n pass\n \n \nclass IOBase(metaclass=abc.ABCMeta):\n\n ''\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n \n \n \n \n def _unsupported(self,name):\n ''\n raise UnsupportedOperation(\"%s.%s() not supported\"%\n (self.__class__.__name__,name))\n \n \n \n def seek(self,pos,whence=0):\n ''\n\n\n\n\n\n\n\n\n\n\n\n \n self._unsupported(\"seek\")\n \n def tell(self):\n ''\n return self.seek(0,1)\n \n def truncate(self,pos=None ):\n ''\n\n\n\n \n self._unsupported(\"truncate\")\n \n \n \n def flush(self):\n ''\n\n\n \n self._checkClosed()\n \n \n __closed=False\n \n def close(self):\n ''\n\n\n \n if not self.__closed:\n try :\n self.flush()\n finally :\n self.__closed=True\n \n def __del__(self):\n ''\n \n \n \n \n \n try :\n self.close()\n except :\n pass\n \n \n \n def seekable(self):\n ''\n\n\n\n \n return False\n \n def _checkSeekable(self,msg=None ):\n ''\n \n if not self.seekable():\n raise UnsupportedOperation(\"File or stream is not seekable.\"\n if msg is None else msg)\n \n def readable(self):\n ''\n\n\n \n return False\n \n def _checkReadable(self,msg=None ):\n ''\n \n if not self.readable():\n raise UnsupportedOperation(\"File or stream is not readable.\"\n if msg is None else msg)\n \n def writable(self):\n ''\n\n\n \n return False\n \n def _checkWritable(self,msg=None ):\n ''\n \n if not self.writable():\n raise UnsupportedOperation(\"File or stream is not writable.\"\n if msg is None else msg)\n \n @property\n def closed(self):\n ''\n\n\n \n return self.__closed\n \n def _checkClosed(self,msg=None ):\n ''\n \n if self.closed:\n raise ValueError(\"I/O operation on closed file.\"\n if msg is None else msg)\n \n \n \n def __enter__(self):\n ''\n self._checkClosed()\n return self\n \n def __exit__(self,*args):\n ''\n self.close()\n \n \n \n \n \n def fileno(self):\n ''\n\n\n \n self._unsupported(\"fileno\")\n \n def isatty(self):\n ''\n\n\n \n self._checkClosed()\n return False\n \n \n \n def readline(self,limit=-1):\n ''\n\n\n\n\n\n\n\n \n \n if hasattr(self,\"peek\"):\n def nreadahead():\n readahead=self.peek(1)\n if not readahead:\n return 1\n n=(readahead.find(b\"\\n\")+1)or len(readahead)\n if limit >=0:\n n=min(n,limit)\n return n\n else :\n def nreadahead():\n return 1\n if limit is None :\n limit=-1\n elif not isinstance(limit,int):\n raise TypeError(\"limit must be an integer\")\n res=bytearray()\n while limit <0 or len(res)<limit:\n b=self.read(nreadahead())\n if not b:\n break\n res +=b\n if res.endswith(b\"\\n\"):\n break\n return bytes(res)\n \n def __iter__(self):\n self._checkClosed()\n return self\n \n def __next__(self):\n line=self.readline()\n if not line:\n raise StopIteration\n return line\n \n def readlines(self,hint=None ):\n ''\n\n\n\n\n \n if hint is None or hint <=0:\n return list(self)\n n=0\n lines=[]\n for line in self:\n lines.append(line)\n n +=len(line)\n if n >=hint:\n break\n return lines\n \n def writelines(self,lines):\n self._checkClosed()\n for line in lines:\n self.write(line)\n \n \n \n \n \nclass RawIOBase(IOBase):\n\n ''\n \n \n \n \n \n \n \n \n \n \n \n def read(self,n=-1):\n ''\n\n\n\n \n if n is None :\n n=-1\n if n <0:\n return self.readall()\n b=bytearray(n.__index__())\n n=self.readinto(b)\n if n is None :\n return None\n del b[n:]\n return bytes(b)\n \n def readall(self):\n ''\n res=bytearray()\n while True :\n data=self.read(DEFAULT_BUFFER_SIZE)\n if not data:\n break\n res +=data\n if res:\n return bytes(res)\n else :\n \n return data\n \n def readinto(self,b):\n ''\n\n\n\n \n self._unsupported(\"readinto\")\n \n def write(self,b):\n ''\n\n\n \n self._unsupported(\"write\")\n \n \n \n \n \n \n \nclass BufferedIOBase(IOBase):\n\n ''\n\n\n\n\n\n\n\n\n\n\n\n\n \n \n def read(self,n=None ):\n ''\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n \n self._unsupported(\"read\")\n \n def read1(self,n=None ):\n ''\n\n \n self._unsupported(\"read1\")\n \n def readinto(self,b):\n ''\n\n\n\n\n\n\n\n\n \n \n data=self.read(len(b))\n n=len(data)\n try :\n b[:n]=data\n except TypeError as err:\n import array\n if not isinstance(b,array.array):\n raise err\n b[:n]=array.array('b',data)\n return n\n \n def write(self,b):\n ''\n\n\n\n\n\n\n \n self._unsupported(\"write\")\n \n def detach(self):\n ''\n\n\n\n\n \n self._unsupported(\"detach\")\n \n \n \n \n \nclass _BufferedIOMixin(BufferedIOBase):\n\n ''\n\n\n\n\n \n \n def __init__(self,raw):\n self._raw=raw\n \n \n \n def seek(self,pos,whence=0):\n new_position=self.raw.seek(pos,whence)\n if new_position <0:\n raise IOError(\"seek() returned an invalid position\")\n return new_position\n \n def tell(self):\n pos=self.raw.tell()\n if pos <0:\n raise IOError(\"tell() returned an invalid position\")\n return pos\n \n def truncate(self,pos=None ):\n \n \n \n self.flush()\n \n if pos is None :\n pos=self.tell()\n \n \n return self.raw.truncate(pos)\n \n \n \n def flush(self):\n if self.closed:\n raise ValueError(\"flush of closed file\")\n self.raw.flush()\n \n def close(self):\n if self.raw is not None and not self.closed:\n try :\n \n self.flush()\n finally :\n self.raw.close()\n \n def detach(self):\n if self.raw is None :\n raise ValueError(\"raw stream already detached\")\n self.flush()\n raw=self._raw\n self._raw=None\n return raw\n \n \n \n def seekable(self):\n return self.raw.seekable()\n \n def readable(self):\n return self.raw.readable()\n \n def writable(self):\n return self.raw.writable()\n \n @property\n def raw(self):\n return self._raw\n \n @property\n def closed(self):\n return self.raw.closed\n \n @property\n def name(self):\n return self.raw.name\n \n @property\n def mode(self):\n return self.raw.mode\n \n def __getstate__(self):\n raise TypeError(\"can not serialize a '{0}' object\"\n .format(self.__class__.__name__))\n \n def __repr__(self):\n clsname=self.__class__.__name__\n try :\n name=self.name\n except AttributeError:\n return \"<_io.{0}>\".format(clsname)\n else :\n return \"<_io.{0} name={1!r}>\".format(clsname,name)\n \n \n \n def fileno(self):\n return self.raw.fileno()\n \n def isatty(self):\n return self.raw.isatty()\n \n \nclass BytesIO(BufferedIOBase):\n\n ''\n \n def __init__(self,initial_bytes=None ):\n buf=bytearray()\n if initial_bytes is not None :\n buf +=initial_bytes\n self._buffer=buf\n self._pos=0\n \n def __getstate__(self):\n if self.closed:\n raise ValueError(\"__getstate__ on closed file\")\n return self.__dict__.copy()\n \n def getvalue(self):\n ''\n \n if self.closed:\n raise ValueError(\"getvalue on closed file\")\n return bytes(self._buffer)\n \n def getbuffer(self):\n ''\n \n return memoryview(self._buffer)\n \n def read(self,n=None ):\n if self.closed:\n raise ValueError(\"read from closed file\")\n if n is None :\n n=-1\n if n <0:\n n=len(self._buffer)\n if len(self._buffer)<=self._pos:\n return b\"\"\n newpos=min(len(self._buffer),self._pos+n)\n b=self._buffer[self._pos:newpos]\n self._pos=newpos\n return bytes(b)\n \n def read1(self,n):\n ''\n \n return self.read(n)\n \n def write(self,b):\n if self.closed:\n raise ValueError(\"write to closed file\")\n if isinstance(b,str):\n raise TypeError(\"can't write str to binary stream\")\n n=len(b)\n if n ==0:\n return 0\n pos=self._pos\n if pos >len(self._buffer):\n \n \n padding=b'\\x00'*(pos -len(self._buffer))\n self._buffer +=padding\n self._buffer[pos:pos+n]=b\n self._pos +=n\n return n\n \n def seek(self,pos,whence=0):\n if self.closed:\n raise ValueError(\"seek on closed file\")\n try :\n pos.__index__\n except AttributeError as err:\n raise TypeError(\"an integer is required\")from err\n if whence ==0:\n if pos <0:\n raise ValueError(\"negative seek position %r\"%(pos,))\n self._pos=pos\n elif whence ==1:\n self._pos=max(0,self._pos+pos)\n elif whence ==2:\n self._pos=max(0,len(self._buffer)+pos)\n else :\n raise ValueError(\"unsupported whence value\")\n return self._pos\n \n def tell(self):\n if self.closed:\n raise ValueError(\"tell on closed file\")\n return self._pos\n \n def truncate(self,pos=None ):\n if self.closed:\n raise ValueError(\"truncate on closed file\")\n if pos is None :\n pos=self._pos\n else :\n try :\n pos.__index__\n except AttributeError as err:\n raise TypeError(\"an integer is required\")from err\n if pos <0:\n raise ValueError(\"negative truncate position %r\"%(pos,))\n del self._buffer[pos:]\n return pos\n \n def readable(self):\n if self.closed:\n raise ValueError(\"I/O operation on closed file.\")\n return True\n \n def writable(self):\n if self.closed:\n raise ValueError(\"I/O operation on closed file.\")\n return True\n \n def seekable(self):\n if self.closed:\n raise ValueError(\"I/O operation on closed file.\")\n return True\n \n \nclass BufferedReader(_BufferedIOMixin):\n\n ''\n\n\n\n\n\n\n \n \n def __init__(self,raw,buffer_size=DEFAULT_BUFFER_SIZE):\n ''\n \n if not raw.readable():\n raise IOError('\"raw\" argument must be readable.')\n \n _BufferedIOMixin.__init__(self,raw)\n if buffer_size <=0:\n raise ValueError(\"invalid buffer size\")\n self.buffer_size=buffer_size\n self._reset_read_buf()\n self._read_lock=Lock()\n \n def _reset_read_buf(self):\n self._read_buf=b\"\"\n self._read_pos=0\n \n def flush(self):\n pass\n \n def read(self,n=None ):\n ''\n\n\n\n\n\n \n if n is not None and n <-1:\n raise ValueError(\"invalid number of bytes to read\")\n with self._read_lock:\n return self._read_unlocked(n)\n \n def _read_unlocked(self,n=None ):\n nodata_val=b\"\"\n empty_values=(b\"\",None )\n buf=self._read_buf\n pos=self._read_pos\n \n \n if n is None or n ==-1:\n self._reset_read_buf()\n if hasattr(self.raw,'readall'):\n chunk=self.raw.readall()\n if chunk is None :\n return buf[pos:]or None\n else :\n return buf[pos:]+chunk\n chunks=[buf[pos:]]\n current_size=0\n while True :\n \n try :\n chunk=self.raw.read()\n except InterruptedError:\n continue\n if chunk in empty_values:\n nodata_val=chunk\n break\n current_size +=len(chunk)\n chunks.append(chunk)\n return b\"\".join(chunks)or nodata_val\n \n \n avail=len(buf)-pos\n if n <=avail:\n \n self._read_pos +=n\n return buf[pos:pos+n]\n \n \n chunks=[buf[pos:]]\n wanted=max(self.buffer_size,n)\n while avail <n:\n try :\n chunk=self.raw.read(wanted)\n except InterruptedError:\n continue\n if chunk in empty_values:\n nodata_val=chunk\n break\n avail +=len(chunk)\n chunks.append(chunk)\n \n \n n=min(n,avail)\n out=b\"\".join(chunks)\n self._read_buf=out[n:]\n self._read_pos=0\n return out[:n]if out else nodata_val\n \n def peek(self,n=0):\n ''\n\n\n\n\n \n with self._read_lock:\n return self._peek_unlocked(n)\n \n def _peek_unlocked(self,n=0):\n want=min(n,self.buffer_size)\n have=len(self._read_buf)-self._read_pos\n if have <want or have <=0:\n to_read=self.buffer_size -have\n while True :\n try :\n current=self.raw.read(to_read)\n except InterruptedError:\n continue\n break\n if current:\n self._read_buf=self._read_buf[self._read_pos:]+current\n self._read_pos=0\n return self._read_buf[self._read_pos:]\n \n def read1(self,n):\n ''\n \n \n if n <0:\n raise ValueError(\"number of bytes to read must be positive\")\n if n ==0:\n return b\"\"\n with self._read_lock:\n self._peek_unlocked(1)\n return self._read_unlocked(\n min(n,len(self._read_buf)-self._read_pos))\n \n def tell(self):\n return _BufferedIOMixin.tell(self)-len(self._read_buf)+self._read_pos\n \n def seek(self,pos,whence=0):\n if whence not in valid_seek_flags:\n raise ValueError(\"invalid whence value\")\n with self._read_lock:\n if whence ==1:\n pos -=len(self._read_buf)-self._read_pos\n pos=_BufferedIOMixin.seek(self,pos,whence)\n self._reset_read_buf()\n return pos\n \nclass BufferedWriter(_BufferedIOMixin):\n\n ''\n\n\n\n\n \n \n def __init__(self,raw,buffer_size=DEFAULT_BUFFER_SIZE):\n if not raw.writable():\n raise IOError('\"raw\" argument must be writable.')\n \n _BufferedIOMixin.__init__(self,raw)\n if buffer_size <=0:\n raise ValueError(\"invalid buffer size\")\n self.buffer_size=buffer_size\n self._write_buf=bytearray()\n self._write_lock=Lock()\n \n def write(self,b):\n if self.closed:\n raise ValueError(\"write to closed file\")\n if isinstance(b,str):\n raise TypeError(\"can't write str to binary stream\")\n with self._write_lock:\n \n \n if len(self._write_buf)>self.buffer_size:\n \n \n self._flush_unlocked()\n before=len(self._write_buf)\n self._write_buf.extend(b)\n written=len(self._write_buf)-before\n if len(self._write_buf)>self.buffer_size:\n try :\n self._flush_unlocked()\n except BlockingIOError as e:\n if len(self._write_buf)>self.buffer_size:\n \n \n overage=len(self._write_buf)-self.buffer_size\n written -=overage\n self._write_buf=self._write_buf[:self.buffer_size]\n raise BlockingIOError(e.errno,e.strerror,written)\n return written\n \n def truncate(self,pos=None ):\n with self._write_lock:\n self._flush_unlocked()\n if pos is None :\n pos=self.raw.tell()\n return self.raw.truncate(pos)\n \n def flush(self):\n with self._write_lock:\n self._flush_unlocked()\n \n def _flush_unlocked(self):\n if self.closed:\n raise ValueError(\"flush of closed file\")\n while self._write_buf:\n try :\n n=self.raw.write(self._write_buf)\n except InterruptedError:\n continue\n except BlockingIOError:\n raise RuntimeError(\"self.raw should implement RawIOBase: it \"\n \"should not raise BlockingIOError\")\n if n is None :\n raise BlockingIOError(\n errno.EAGAIN,\n \"write could not complete without blocking\",0)\n if n >len(self._write_buf)or n <0:\n raise IOError(\"write() returned incorrect number of bytes\")\n del self._write_buf[:n]\n \n def tell(self):\n return _BufferedIOMixin.tell(self)+len(self._write_buf)\n \n def seek(self,pos,whence=0):\n if whence not in valid_seek_flags:\n raise ValueError(\"invalid whence value\")\n with self._write_lock:\n self._flush_unlocked()\n return _BufferedIOMixin.seek(self,pos,whence)\n \n \nclass BufferedRWPair(BufferedIOBase):\n\n ''\n\n\n\n\n\n\n\n\n \n \n \n \n \n def __init__(self,reader,writer,buffer_size=DEFAULT_BUFFER_SIZE):\n ''\n\n\n \n if not reader.readable():\n raise IOError('\"reader\" argument must be readable.')\n \n if not writer.writable():\n raise IOError('\"writer\" argument must be writable.')\n \n self.reader=BufferedReader(reader,buffer_size)\n self.writer=BufferedWriter(writer,buffer_size)\n \n def read(self,n=None ):\n if n is None :\n n=-1\n return self.reader.read(n)\n \n def readinto(self,b):\n return self.reader.readinto(b)\n \n def write(self,b):\n return self.writer.write(b)\n \n def peek(self,n=0):\n return self.reader.peek(n)\n \n def read1(self,n):\n return self.reader.read1(n)\n \n def readable(self):\n return self.reader.readable()\n \n def writable(self):\n return self.writer.writable()\n \n def flush(self):\n return self.writer.flush()\n \n def close(self):\n self.writer.close()\n self.reader.close()\n \n def isatty(self):\n return self.reader.isatty()or self.writer.isatty()\n \n @property\n def closed(self):\n return self.writer.closed\n \n \nclass BufferedRandom(BufferedWriter,BufferedReader):\n\n ''\n\n\n\n\n \n \n def __init__(self,raw,buffer_size=DEFAULT_BUFFER_SIZE):\n raw._checkSeekable()\n BufferedReader.__init__(self,raw,buffer_size)\n BufferedWriter.__init__(self,raw,buffer_size)\n \n def seek(self,pos,whence=0):\n if whence not in valid_seek_flags:\n raise ValueError(\"invalid whence value\")\n self.flush()\n if self._read_buf:\n \n with self._read_lock:\n self.raw.seek(self._read_pos -len(self._read_buf),1)\n \n \n pos=self.raw.seek(pos,whence)\n with self._read_lock:\n self._reset_read_buf()\n if pos <0:\n raise IOError(\"seek() returned invalid position\")\n return pos\n \n def tell(self):\n if self._write_buf:\n return BufferedWriter.tell(self)\n else :\n return BufferedReader.tell(self)\n \n def truncate(self,pos=None ):\n if pos is None :\n pos=self.tell()\n \n return BufferedWriter.truncate(self,pos)\n \n def read(self,n=None ):\n if n is None :\n n=-1\n self.flush()\n return BufferedReader.read(self,n)\n \n def readinto(self,b):\n self.flush()\n return BufferedReader.readinto(self,b)\n \n def peek(self,n=0):\n self.flush()\n return BufferedReader.peek(self,n)\n \n def read1(self,n):\n self.flush()\n return BufferedReader.read1(self,n)\n \n def write(self,b):\n if self._read_buf:\n \n with self._read_lock:\n self.raw.seek(self._read_pos -len(self._read_buf),1)\n self._reset_read_buf()\n return BufferedWriter.write(self,b)\n \n \nclass TextIOBase(IOBase):\n\n ''\n\n\n\n\n \n \n def read(self,n=-1):\n ''\n\n\n\n\n\n \n self._unsupported(\"read\")\n \n def write(self,s):\n ''\n self._unsupported(\"write\")\n \n def truncate(self,pos=None ):\n ''\n self._unsupported(\"truncate\")\n \n def readline(self):\n ''\n\n\n \n self._unsupported(\"readline\")\n \n def detach(self):\n ''\n\n\n\n\n \n self._unsupported(\"detach\")\n \n @property\n def encoding(self):\n ''\n return None\n \n @property\n def newlines(self):\n ''\n\n\n\n\n \n return None\n \n @property\n def errors(self):\n ''\n\n \n return None\n \n \n \n \n \nclass IncrementalNewlineDecoder(codecs.IncrementalDecoder):\n ''\n\n\n\n\n \n def __init__(self,decoder,translate,errors='strict'):\n codecs.IncrementalDecoder.__init__(self,errors=errors)\n self.translate=translate\n self.decoder=decoder\n self.seennl=0\n self.pendingcr=False\n \n def decode(self,input,final=False ):\n \n if self.decoder is None :\n output=input\n else :\n output=self.decoder.decode(input,final=final)\n if self.pendingcr and (output or final):\n output=\"\\r\"+output\n self.pendingcr=False\n \n \n \n if output.endswith(\"\\r\")and not final:\n output=output[:-1]\n self.pendingcr=True\n \n \n crlf=output.count('\\r\\n')\n cr=output.count('\\r')-crlf\n lf=output.count('\\n')-crlf\n self.seennl |=(lf and self._LF)|(cr and self._CR)\\\n |(crlf and self._CRLF)\n \n if self.translate:\n if crlf:\n output=output.replace(\"\\r\\n\",\"\\n\")\n if cr:\n output=output.replace(\"\\r\",\"\\n\")\n \n return output\n \n def getstate(self):\n if self.decoder is None :\n buf=b\"\"\n flag=0\n else :\n buf,flag=self.decoder.getstate()\n flag <<=1\n if self.pendingcr:\n flag |=1\n return buf,flag\n \n def setstate(self,state):\n buf,flag=state\n self.pendingcr=bool(flag&1)\n if self.decoder is not None :\n self.decoder.setstate((buf,flag >>1))\n \n def reset(self):\n self.seennl=0\n self.pendingcr=False\n if self.decoder is not None :\n self.decoder.reset()\n \n _LF=1\n _CR=2\n _CRLF=4\n \n @property\n def newlines(self):\n return (None ,\n \"\\n\",\n \"\\r\",\n (\"\\r\",\"\\n\"),\n \"\\r\\n\",\n (\"\\n\",\"\\r\\n\"),\n (\"\\r\",\"\\r\\n\"),\n (\"\\r\",\"\\n\",\"\\r\\n\")\n )[self.seennl]\n \n \nclass TextIOWrapper(TextIOBase):\n\n ''\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n \n \n _CHUNK_SIZE=2048\n \n \n \n \n def __init__(self,buffer,encoding=None ,errors=None ,newline=None ,\n line_buffering=False ,write_through=False ):\n if newline is not None and not isinstance(newline,str):\n raise TypeError(\"illegal newline type: %r\"%(type(newline),))\n if newline not in (None ,\"\",\"\\n\",\"\\r\",\"\\r\\n\"):\n raise ValueError(\"illegal newline value: %r\"%(newline,))\n if encoding is None :\n try :\n encoding=os.device_encoding(buffer.fileno())\n except (AttributeError,UnsupportedOperation):\n pass\n if encoding is None :\n try :\n import locale\n except ImportError:\n \n encoding=\"ascii\"\n else :\n encoding=locale.getpreferredencoding(False )\n \n if not isinstance(encoding,str):\n raise ValueError(\"invalid encoding: %r\"%encoding)\n \n if errors is None :\n errors=\"strict\"\n else :\n if not isinstance(errors,str):\n raise ValueError(\"invalid errors: %r\"%errors)\n \n self._buffer=buffer\n self._line_buffering=line_buffering\n self._encoding=encoding\n self._errors=errors\n self._readuniversal=not newline\n self._readtranslate=newline is None\n self._readnl=newline\n self._writetranslate=newline !=''\n self._writenl=newline or os.linesep\n self._encoder=None\n self._decoder=None\n self._decoded_chars=''\n self._decoded_chars_used=0\n self._snapshot=None\n self._seekable=self._telling=self.buffer.seekable()\n self._has_read1=hasattr(self.buffer,'read1')\n self._b2cratio=0.0\n \n if self._seekable and self.writable():\n position=self.buffer.tell()\n if position !=0:\n try :\n self._get_encoder().setstate(0)\n except LookupError:\n \n pass\n \n \n \n \n \n \n \n \n \n \n def __repr__(self):\n result=\"<_io.TextIOWrapper\"\n try :\n name=self.name\n except AttributeError:\n pass\n else :\n result +=\" name={0!r}\".format(name)\n try :\n mode=self.mode\n except AttributeError:\n pass\n else :\n result +=\" mode={0!r}\".format(mode)\n return result+\" encoding={0!r}>\".format(self.encoding)\n \n @property\n def encoding(self):\n return self._encoding\n \n @property\n def errors(self):\n return self._errors\n \n @property\n def line_buffering(self):\n return self._line_buffering\n \n @property\n def buffer(self):\n return self._buffer\n \n def seekable(self):\n if self.closed:\n raise ValueError(\"I/O operation on closed file.\")\n return self._seekable\n \n def readable(self):\n return self.buffer.readable()\n \n def writable(self):\n return self.buffer.writable()\n \n def flush(self):\n self.buffer.flush()\n self._telling=self._seekable\n \n def close(self):\n if self.buffer is not None and not self.closed:\n try :\n self.flush()\n finally :\n self.buffer.close()\n \n @property\n def closed(self):\n return self.buffer.closed\n \n @property\n def name(self):\n return self.buffer.name\n \n def fileno(self):\n return self.buffer.fileno()\n \n def isatty(self):\n return self.buffer.isatty()\n \n def write(self,s):\n ''\n if self.closed:\n raise ValueError(\"write to closed file\")\n if not isinstance(s,str):\n raise TypeError(\"can't write %s to text stream\"%\n s.__class__.__name__)\n length=len(s)\n haslf=(self._writetranslate or self._line_buffering)and \"\\n\"in s\n if haslf and self._writetranslate and self._writenl !=\"\\n\":\n s=s.replace(\"\\n\",self._writenl)\n encoder=self._encoder or self._get_encoder()\n \n b=encoder.encode(s)\n self.buffer.write(b)\n if self._line_buffering and (haslf or \"\\r\"in s):\n self.flush()\n self._snapshot=None\n if self._decoder:\n self._decoder.reset()\n return length\n \n def _get_encoder(self):\n make_encoder=codecs.getincrementalencoder(self._encoding)\n self._encoder=make_encoder(self._errors)\n return self._encoder\n \n def _get_decoder(self):\n make_decoder=codecs.getincrementaldecoder(self._encoding)\n decoder=make_decoder(self._errors)\n if self._readuniversal:\n decoder=IncrementalNewlineDecoder(decoder,self._readtranslate)\n self._decoder=decoder\n return decoder\n \n \n \n \n def _set_decoded_chars(self,chars):\n ''\n self._decoded_chars=chars\n self._decoded_chars_used=0\n \n def _get_decoded_chars(self,n=None ):\n ''\n offset=self._decoded_chars_used\n if n is None :\n chars=self._decoded_chars[offset:]\n else :\n chars=self._decoded_chars[offset:offset+n]\n self._decoded_chars_used +=len(chars)\n return chars\n \n def _rewind_decoded_chars(self,n):\n ''\n if self._decoded_chars_used <n:\n raise AssertionError(\"rewind decoded_chars out of bounds\")\n self._decoded_chars_used -=n\n \n def _read_chunk(self):\n ''\n\n \n \n \n \n \n \n \n \n if self._decoder is None :\n raise ValueError(\"no decoder\")\n \n if self._telling:\n \n \n \n dec_buffer,dec_flags=self._decoder.getstate()\n \n \n \n \n if self._has_read1:\n input_chunk=self.buffer.read1(self._CHUNK_SIZE)\n else :\n input_chunk=self.buffer.read(self._CHUNK_SIZE)\n eof=not input_chunk\n decoded_chars=self._decoder.decode(input_chunk,eof)\n self._set_decoded_chars(decoded_chars)\n if decoded_chars:\n self._b2cratio=len(input_chunk)/len(self._decoded_chars)\n else :\n self._b2cratio=0.0\n \n if self._telling:\n \n \n self._snapshot=(dec_flags,dec_buffer+input_chunk)\n \n return not eof\n \n def _pack_cookie(self,position,dec_flags=0,\n bytes_to_feed=0,need_eof=0,chars_to_skip=0):\n \n \n \n \n \n return (position |(dec_flags <<64)|(bytes_to_feed <<128)|\n (chars_to_skip <<192)|bool(need_eof)<<256)\n \n def _unpack_cookie(self,bigint):\n rest,position=divmod(bigint,1 <<64)\n rest,dec_flags=divmod(rest,1 <<64)\n rest,bytes_to_feed=divmod(rest,1 <<64)\n need_eof,chars_to_skip=divmod(rest,1 <<64)\n return position,dec_flags,bytes_to_feed,need_eof,chars_to_skip\n \n def tell(self):\n if not self._seekable:\n raise UnsupportedOperation(\"underlying stream is not seekable\")\n if not self._telling:\n raise IOError(\"telling position disabled by next() call\")\n self.flush()\n position=self.buffer.tell()\n decoder=self._decoder\n if decoder is None or self._snapshot is None :\n if self._decoded_chars:\n \n raise AssertionError(\"pending decoded text\")\n return position\n \n \n dec_flags,next_input=self._snapshot\n position -=len(next_input)\n \n \n chars_to_skip=self._decoded_chars_used\n if chars_to_skip ==0:\n \n return self._pack_cookie(position,dec_flags)\n \n \n \n saved_state=decoder.getstate()\n try :\n \n \n \n \n \n \n \n skip_bytes=int(self._b2cratio *chars_to_skip)\n skip_back=1\n assert skip_bytes <=len(next_input)\n while skip_bytes >0:\n decoder.setstate((b'',dec_flags))\n \n n=len(decoder.decode(next_input[:skip_bytes]))\n if n <=chars_to_skip:\n b,d=decoder.getstate()\n if not b:\n \n dec_flags=d\n chars_to_skip -=n\n break\n \n skip_bytes -=len(b)\n skip_back=1\n else :\n \n skip_bytes -=skip_back\n skip_back=skip_back *2\n else :\n skip_bytes=0\n decoder.setstate((b'',dec_flags))\n \n \n start_pos=position+skip_bytes\n start_flags=dec_flags\n if chars_to_skip ==0:\n \n return self._pack_cookie(start_pos,start_flags)\n \n \n \n \n \n bytes_fed=0\n need_eof=0\n \n chars_decoded=0\n for i in range(skip_bytes,len(next_input)):\n bytes_fed +=1\n chars_decoded +=len(decoder.decode(next_input[i:i+1]))\n dec_buffer,dec_flags=decoder.getstate()\n if not dec_buffer and chars_decoded <=chars_to_skip:\n \n start_pos +=bytes_fed\n chars_to_skip -=chars_decoded\n start_flags,bytes_fed,chars_decoded=dec_flags,0,0\n if chars_decoded >=chars_to_skip:\n break\n else :\n \n chars_decoded +=len(decoder.decode(b'',final=True ))\n need_eof=1\n if chars_decoded <chars_to_skip:\n raise IOError(\"can't reconstruct logical file position\")\n \n \n return self._pack_cookie(\n start_pos,start_flags,bytes_fed,need_eof,chars_to_skip)\n finally :\n decoder.setstate(saved_state)\n \n def truncate(self,pos=None ):\n self.flush()\n if pos is None :\n pos=self.tell()\n return self.buffer.truncate(pos)\n \n def detach(self):\n if self.buffer is None :\n raise ValueError(\"buffer is already detached\")\n self.flush()\n buffer=self._buffer\n self._buffer=None\n return buffer\n \n def seek(self,cookie,whence=0):\n if self.closed:\n raise ValueError(\"tell on closed file\")\n if not self._seekable:\n raise UnsupportedOperation(\"underlying stream is not seekable\")\n if whence ==1:\n if cookie !=0:\n raise UnsupportedOperation(\"can't do nonzero cur-relative seeks\")\n \n \n whence=0\n cookie=self.tell()\n if whence ==2:\n if cookie !=0:\n raise UnsupportedOperation(\"can't do nonzero end-relative seeks\")\n self.flush()\n position=self.buffer.seek(0,2)\n self._set_decoded_chars('')\n self._snapshot=None\n if self._decoder:\n self._decoder.reset()\n return position\n if whence !=0:\n raise ValueError(\"unsupported whence (%r)\"%(whence,))\n if cookie <0:\n raise ValueError(\"negative seek position %r\"%(cookie,))\n self.flush()\n \n \n \n start_pos,dec_flags,bytes_to_feed,need_eof,chars_to_skip=\\\n self._unpack_cookie(cookie)\n \n \n self.buffer.seek(start_pos)\n self._set_decoded_chars('')\n self._snapshot=None\n \n \n if cookie ==0 and self._decoder:\n self._decoder.reset()\n elif self._decoder or dec_flags or chars_to_skip:\n self._decoder=self._decoder or self._get_decoder()\n self._decoder.setstate((b'',dec_flags))\n self._snapshot=(dec_flags,b'')\n \n if chars_to_skip:\n \n input_chunk=self.buffer.read(bytes_to_feed)\n self._set_decoded_chars(\n self._decoder.decode(input_chunk,need_eof))\n self._snapshot=(dec_flags,input_chunk)\n \n \n if len(self._decoded_chars)<chars_to_skip:\n raise IOError(\"can't restore logical file position\")\n self._decoded_chars_used=chars_to_skip\n \n \n try :\n encoder=self._encoder or self._get_encoder()\n except LookupError:\n \n pass\n else :\n if cookie !=0:\n encoder.setstate(0)\n else :\n encoder.reset()\n return cookie\n \n def read(self,n=None ):\n self._checkReadable()\n if n is None :\n n=-1\n decoder=self._decoder or self._get_decoder()\n try :\n n.__index__\n except AttributeError as err:\n raise TypeError(\"an integer is required\")from err\n if n <0:\n \n result=(self._get_decoded_chars()+\n decoder.decode(self.buffer.read(),final=True ))\n self._set_decoded_chars('')\n self._snapshot=None\n return result\n else :\n \n eof=False\n result=self._get_decoded_chars(n)\n while len(result)<n and not eof:\n eof=not self._read_chunk()\n result +=self._get_decoded_chars(n -len(result))\n return result\n \n def __next__(self):\n self._telling=False\n line=self.readline()\n if not line:\n self._snapshot=None\n self._telling=self._seekable\n raise StopIteration\n return line\n \n def readline(self,limit=None ):\n if self.closed:\n raise ValueError(\"read from closed file\")\n if limit is None :\n limit=-1\n elif not isinstance(limit,int):\n raise TypeError(\"limit must be an integer\")\n \n \n line=self._get_decoded_chars()\n \n start=0\n \n if not self._decoder:\n self._get_decoder()\n \n pos=endpos=None\n while True :\n if self._readtranslate:\n \n pos=line.find('\\n',start)\n if pos >=0:\n endpos=pos+1\n break\n else :\n start=len(line)\n \n elif self._readuniversal:\n \n \n \n \n nlpos=line.find(\"\\n\",start)\n crpos=line.find(\"\\r\",start)\n if crpos ==-1:\n if nlpos ==-1:\n \n start=len(line)\n else :\n \n endpos=nlpos+1\n break\n elif nlpos ==-1:\n \n endpos=crpos+1\n break\n elif nlpos <crpos:\n \n endpos=nlpos+1\n break\n elif nlpos ==crpos+1:\n \n endpos=crpos+2\n break\n else :\n \n endpos=crpos+1\n break\n else :\n \n pos=line.find(self._readnl)\n if pos >=0:\n endpos=pos+len(self._readnl)\n break\n \n if limit >=0 and len(line)>=limit:\n endpos=limit\n break\n \n \n while self._read_chunk():\n if self._decoded_chars:\n break\n if self._decoded_chars:\n line +=self._get_decoded_chars()\n else :\n \n self._set_decoded_chars('')\n self._snapshot=None\n return line\n \n if limit >=0 and endpos >limit:\n endpos=limit\n \n \n self._rewind_decoded_chars(len(line)-endpos)\n return line[:endpos]\n \n @property\n def newlines(self):\n return self._decoder.newlines if self._decoder else None\n \n \nclass StringIO(TextIOWrapper):\n ''\n\n\n\n \n \n def __init__(self,initial_value=\"\",newline=\"\\n\"):\n super(StringIO,self).__init__(BytesIO(),\n encoding=\"utf-8\",\n errors=\"strict\",\n newline=newline)\n \n \n if newline is None :\n self._writetranslate=False\n if initial_value is not None :\n if not isinstance(initial_value,str):\n raise TypeError(\"initial_value must be str or None, not {0}\"\n .format(type(initial_value).__name__))\n initial_value=str(initial_value)\n self.write(initial_value)\n self.seek(0)\n \n def getvalue(self):\n self.flush()\n return self.buffer.getvalue().decode(self._encoding,self._errors)\n \n def __repr__(self):\n \n \n return object.__repr__(self)\n \n @property\n def errors(self):\n return None\n \n @property\n def encoding(self):\n return None\n \n def detach(self):\n \n self._unsupported(\"detach\")\n \nclass FileIO(RawIOBase):\n pass\n \n_IOBase=IOBase\n_RawIOBase=RawIOBase\n_BufferedIOBase=BufferedIOBase\n_TextIOBase=TextIOBase\n", ["_dummy_thread", "_thread", "abc", "array", "codecs", "errno", "locale", "os"]], "email.contentmanager": [".py", "import binascii\nimport email.charset\nimport email.message\nimport email.errors\nfrom email import quoprimime\n\nclass ContentManager:\n\n def __init__(self):\n self.get_handlers={}\n self.set_handlers={}\n \n def add_get_handler(self,key,handler):\n self.get_handlers[key]=handler\n \n def get_content(self,msg,*args,**kw):\n content_type=msg.get_content_type()\n if content_type in self.get_handlers:\n return self.get_handlers[content_type](msg,*args,**kw)\n maintype=msg.get_content_maintype()\n if maintype in self.get_handlers:\n return self.get_handlers[maintype](msg,*args,**kw)\n if ''in self.get_handlers:\n return self.get_handlers[''](msg,*args,**kw)\n raise KeyError(content_type)\n \n def add_set_handler(self,typekey,handler):\n self.set_handlers[typekey]=handler\n \n def set_content(self,msg,obj,*args,**kw):\n if msg.get_content_maintype()=='multipart':\n \n \n raise TypeError(\"set_content not valid on multipart\")\n handler=self._find_set_handler(msg,obj)\n msg.clear_content()\n handler(msg,obj,*args,**kw)\n \n def _find_set_handler(self,msg,obj):\n full_path_for_error=None\n for typ in type(obj).__mro__:\n if typ in self.set_handlers:\n return self.set_handlers[typ]\n qname=typ.__qualname__\n modname=getattr(typ,'__module__','')\n full_path='.'.join((modname,qname))if modname else qname\n if full_path_for_error is None :\n full_path_for_error=full_path\n if full_path in self.set_handlers:\n return self.set_handlers[full_path]\n if qname in self.set_handlers:\n return self.set_handlers[qname]\n name=typ.__name__\n if name in self.set_handlers:\n return self.set_handlers[name]\n if None in self.set_handlers:\n return self.set_handlers[None ]\n raise KeyError(full_path_for_error)\n \n \nraw_data_manager=ContentManager()\n\n\ndef get_text_content(msg,errors='replace'):\n content=msg.get_payload(decode=True )\n charset=msg.get_param('charset','ASCII')\n return content.decode(charset,errors=errors)\nraw_data_manager.add_get_handler('text',get_text_content)\n\n\ndef get_non_text_content(msg):\n return msg.get_payload(decode=True )\nfor maintype in 'audio image video application'.split():\n raw_data_manager.add_get_handler(maintype,get_non_text_content)\n \n \ndef get_message_content(msg):\n return msg.get_payload(0)\nfor subtype in 'rfc822 external-body'.split():\n raw_data_manager.add_get_handler('message/'+subtype,get_message_content)\n \n \ndef get_and_fixup_unknown_message_content(msg):\n\n\n\n\n\n\n return bytes(msg.get_payload(0))\nraw_data_manager.add_get_handler('message',\nget_and_fixup_unknown_message_content)\n\n\ndef _prepare_set(msg,maintype,subtype,headers):\n msg['Content-Type']='/'.join((maintype,subtype))\n if headers:\n if not hasattr(headers[0],'name'):\n mp=msg.policy\n headers=[mp.header_factory(*mp.header_source_parse([header]))\n for header in headers]\n try :\n for header in headers:\n if header.defects:\n raise header.defects[0]\n msg[header.name]=header\n except email.errors.HeaderDefect as exc:\n raise ValueError(\"Invalid header: {}\".format(\n header.fold(policy=msg.policy)))from exc\n \n \ndef _finalize_set(msg,disposition,filename,cid,params):\n if disposition is None and filename is not None :\n disposition='attachment'\n if disposition is not None :\n msg['Content-Disposition']=disposition\n if filename is not None :\n msg.set_param('filename',\n filename,\n header='Content-Disposition',\n replace=True )\n if cid is not None :\n msg['Content-ID']=cid\n if params is not None :\n for key,value in params.items():\n msg.set_param(key,value)\n \n \n \n \n \n \ndef _encode_base64(data,max_line_length):\n encoded_lines=[]\n unencoded_bytes_per_line=max_line_length //4 *3\n for i in range(0,len(data),unencoded_bytes_per_line):\n thisline=data[i:i+unencoded_bytes_per_line]\n encoded_lines.append(binascii.b2a_base64(thisline).decode('ascii'))\n return ''.join(encoded_lines)\n \n \ndef _encode_text(string,charset,cte,policy):\n lines=string.encode(charset).splitlines()\n linesep=policy.linesep.encode('ascii')\n def embedded_body(lines):return linesep.join(lines)+linesep\n def normal_body(lines):return b'\\n'.join(lines)+b'\\n'\n if cte ==None :\n \n try :\n return '7bit',normal_body(lines).decode('ascii')\n except UnicodeDecodeError:\n pass\n if (policy.cte_type =='8bit'and\n max(len(x)for x in lines)<=policy.max_line_length):\n return '8bit',normal_body(lines).decode('ascii','surrogateescape')\n sniff=embedded_body(lines[:10])\n sniff_qp=quoprimime.body_encode(sniff.decode('latin-1'),\n policy.max_line_length)\n sniff_base64=binascii.b2a_base64(sniff)\n \n if len(sniff_qp)>len(sniff_base64):\n cte='base64'\n else :\n cte='quoted-printable'\n if len(lines)<=10:\n return cte,sniff_qp\n if cte =='7bit':\n data=normal_body(lines).decode('ascii')\n elif cte =='8bit':\n data=normal_body(lines).decode('ascii','surrogateescape')\n elif cte =='quoted-printable':\n data=quoprimime.body_encode(normal_body(lines).decode('latin-1'),\n policy.max_line_length)\n elif cte =='base64':\n data=_encode_base64(embedded_body(lines),policy.max_line_length)\n else :\n raise ValueError(\"Unknown content transfer encoding {}\".format(cte))\n return cte,data\n \n \ndef set_text_content(msg,string,subtype=\"plain\",charset='utf-8',cte=None ,\ndisposition=None ,filename=None ,cid=None ,\nparams=None ,headers=None ):\n _prepare_set(msg,'text',subtype,headers)\n cte,payload=_encode_text(string,charset,cte,msg.policy)\n msg.set_payload(payload)\n msg.set_param('charset',\n email.charset.ALIASES.get(charset,charset),\n replace=True )\n msg['Content-Transfer-Encoding']=cte\n _finalize_set(msg,disposition,filename,cid,params)\nraw_data_manager.add_set_handler(str,set_text_content)\n\n\ndef set_message_content(msg,message,subtype=\"rfc822\",cte=None ,\ndisposition=None ,filename=None ,cid=None ,\nparams=None ,headers=None ):\n if subtype =='partial':\n raise ValueError(\"message/partial is not supported for Message objects\")\n if subtype =='rfc822':\n if cte not in (None ,'7bit','8bit','binary'):\n \n raise ValueError(\n \"message/rfc822 parts do not support cte={}\".format(cte))\n \n \n \n \n \n cte='8bit'if cte is None else cte\n elif subtype =='external-body':\n if cte not in (None ,'7bit'):\n \n raise ValueError(\n \"message/external-body parts do not support cte={}\".format(cte))\n cte='7bit'\n elif cte is None :\n \n \n cte='7bit'\n _prepare_set(msg,'message',subtype,headers)\n msg.set_payload([message])\n msg['Content-Transfer-Encoding']=cte\n _finalize_set(msg,disposition,filename,cid,params)\nraw_data_manager.add_set_handler(email.message.Message,set_message_content)\n\n\ndef set_bytes_content(msg,data,maintype,subtype,cte='base64',\ndisposition=None ,filename=None ,cid=None ,\nparams=None ,headers=None ):\n _prepare_set(msg,maintype,subtype,headers)\n if cte =='base64':\n data=_encode_base64(data,max_line_length=msg.policy.max_line_length)\n elif cte =='quoted-printable':\n \n \n \n data=binascii.b2a_qp(data,istext=False ,header=False ,quotetabs=True )\n data=data.decode('ascii')\n elif cte =='7bit':\n \n \n data.encode('ascii')\n elif cte in ('8bit','binary'):\n data=data.decode('ascii','surrogateescape')\n msg.set_payload(data)\n msg['Content-Transfer-Encoding']=cte\n _finalize_set(msg,disposition,filename,cid,params)\nfor typ in (bytes,bytearray,memoryview):\n raw_data_manager.add_set_handler(typ,set_bytes_content)\n", ["binascii", "email", "email.charset", "email.errors", "email.message", "email.quoprimime"]], "stat": [".py", "''\n\n\n\n\n\n\nST_MODE=0\nST_INO=1\nST_DEV=2\nST_NLINK=3\nST_UID=4\nST_GID=5\nST_SIZE=6\nST_ATIME=7\nST_MTIME=8\nST_CTIME=9\n\n\n\ndef S_IMODE(mode):\n ''\n\n \n return mode&0o7777\n \ndef S_IFMT(mode):\n ''\n\n \n return mode&0o170000\n \n \n \n \nS_IFDIR=0o040000\nS_IFCHR=0o020000\nS_IFBLK=0o060000\nS_IFREG=0o100000\nS_IFIFO=0o010000\nS_IFLNK=0o120000\nS_IFSOCK=0o140000\n\n\n\ndef S_ISDIR(mode):\n ''\n return S_IFMT(mode)==S_IFDIR\n \ndef S_ISCHR(mode):\n ''\n return S_IFMT(mode)==S_IFCHR\n \ndef S_ISBLK(mode):\n ''\n return S_IFMT(mode)==S_IFBLK\n \ndef S_ISREG(mode):\n ''\n return S_IFMT(mode)==S_IFREG\n \ndef S_ISFIFO(mode):\n ''\n return S_IFMT(mode)==S_IFIFO\n \ndef S_ISLNK(mode):\n ''\n return S_IFMT(mode)==S_IFLNK\n \ndef S_ISSOCK(mode):\n ''\n return S_IFMT(mode)==S_IFSOCK\n \n \n \nS_ISUID=0o4000\nS_ISGID=0o2000\nS_ENFMT=S_ISGID\nS_ISVTX=0o1000\nS_IREAD=0o0400\nS_IWRITE=0o0200\nS_IEXEC=0o0100\nS_IRWXU=0o0700\nS_IRUSR=0o0400\nS_IWUSR=0o0200\nS_IXUSR=0o0100\nS_IRWXG=0o0070\nS_IRGRP=0o0040\nS_IWGRP=0o0020\nS_IXGRP=0o0010\nS_IRWXO=0o0007\nS_IROTH=0o0004\nS_IWOTH=0o0002\nS_IXOTH=0o0001\n\n\n\nUF_NODUMP=0x00000001\nUF_IMMUTABLE=0x00000002\nUF_APPEND=0x00000004\nUF_OPAQUE=0x00000008\nUF_NOUNLINK=0x00000010\nUF_COMPRESSED=0x00000020\nUF_HIDDEN=0x00008000\nSF_ARCHIVED=0x00010000\nSF_IMMUTABLE=0x00020000\nSF_APPEND=0x00040000\nSF_NOUNLINK=0x00100000\nSF_SNAPSHOT=0x00200000\n\n\n_filemode_table=(\n((S_IFLNK,\"l\"),\n(S_IFREG,\"-\"),\n(S_IFBLK,\"b\"),\n(S_IFDIR,\"d\"),\n(S_IFCHR,\"c\"),\n(S_IFIFO,\"p\")),\n\n((S_IRUSR,\"r\"),),\n((S_IWUSR,\"w\"),),\n((S_IXUSR |S_ISUID,\"s\"),\n(S_ISUID,\"S\"),\n(S_IXUSR,\"x\")),\n\n((S_IRGRP,\"r\"),),\n((S_IWGRP,\"w\"),),\n((S_IXGRP |S_ISGID,\"s\"),\n(S_ISGID,\"S\"),\n(S_IXGRP,\"x\")),\n\n((S_IROTH,\"r\"),),\n((S_IWOTH,\"w\"),),\n((S_IXOTH |S_ISVTX,\"t\"),\n(S_ISVTX,\"T\"),\n(S_IXOTH,\"x\"))\n)\n\ndef filemode(mode):\n ''\n perm=[]\n for table in _filemode_table:\n for bit,char in table:\n if mode&bit ==bit:\n perm.append(char)\n break\n else :\n perm.append(\"-\")\n return \"\".join(perm)\n \n \n \n \n \nFILE_ATTRIBUTE_ARCHIVE=32\nFILE_ATTRIBUTE_COMPRESSED=2048\nFILE_ATTRIBUTE_DEVICE=64\nFILE_ATTRIBUTE_DIRECTORY=16\nFILE_ATTRIBUTE_ENCRYPTED=16384\nFILE_ATTRIBUTE_HIDDEN=2\nFILE_ATTRIBUTE_INTEGRITY_STREAM=32768\nFILE_ATTRIBUTE_NORMAL=128\nFILE_ATTRIBUTE_NOT_CONTENT_INDEXED=8192\nFILE_ATTRIBUTE_NO_SCRUB_DATA=131072\nFILE_ATTRIBUTE_OFFLINE=4096\nFILE_ATTRIBUTE_READONLY=1\nFILE_ATTRIBUTE_REPARSE_POINT=1024\nFILE_ATTRIBUTE_SPARSE_FILE=512\nFILE_ATTRIBUTE_SYSTEM=4\nFILE_ATTRIBUTE_TEMPORARY=256\nFILE_ATTRIBUTE_VIRTUAL=65536\n\n\n\ntry :\n from _stat import *\nexcept ImportError:\n pass\n", ["_stat"]], "array": [".js", "var $module = (function($B){\n\nvar _b_ = $B.builtins,\n $s = [],\n i\nfor(var $b in _b_){$s.push('var ' + $b +' = _b_[\"'+$b+'\"]')}\neval($s.join(';'))\n\nvar typecodes = {\n 'b': Int8Array, // signed char, 1 byte\n 'B': Uint8Array, // unsigned char, 1\n 'u': null, // Py_UNICODE Unicode character, 2 (deprecated)\n 'h': Int16Array, // signed short, 2\n 'H': Uint16Array, // unsigned short, 2\n 'i': Int16Array, // signed int, 2\n 'I': Uint16Array, // unsigned int, 2\n 'l': Int32Array, // signed long, 4\n 'L': Uint32Array, // unsigned long, 4\n 'q': null, // signed long, 8 (not implemented)\n 'Q': null, // unsigned long, 8 (not implemented)\n 'f': Float32Array, // float, 4\n 'd': Float64Array // double float, 8\n}\n\nvar array = $B.make_class(\"array\",\n function(){\n var missing = {},\n $ = $B.args(\"array\", 2, {typecode: null, initializer: null},\n [\"typecode\", \"initializer\"], arguments, {initializer: missing},\n null, null),\n typecode = $.typecode,\n initializer = $.initializer\n if(! typecodes.hasOwnProperty(typecode)){\n throw _b_.ValueError.$factory(\"bad typecode (must be b, \" +\n \"B, u, h, H, i, I, l, L, q, Q, f or d)\")\n }\n if(typecodes[typecode] === null){\n throw _b_.NotImplementedError.$factory(\"type code \" +\n typecode + \"is not implemented\")\n }\n var res = {\n __class__: array,\n typecode: typecode,\n obj: null\n }\n if(initializer !== missing){\n if(Array.isArray(initializer)){\n array.fromlist(res, initializer)\n }else if(_b_.isinstance(initializer, _b_.bytes)){\n array.frombytes(res, initializer)\n }else{\n array.extend(res, initializer)\n }\n }\n return res\n }\n)\n\narray.$buffer_protocol = true\n\narray.__getitem__ = function(self, key){\n if(self.obj && self.obj[key] !== undefined){\n return self.obj[key]\n }\n throw _b_.IndexError(\"array index out of range\")\n}\n\nvar array_iterator = $B.make_iterator_class(\"array_iterator\")\narray.__iter__ = function(self){\n return array_iterator.$factory(self.obj)\n}\n\narray.__len__ = function(self){\n return self.obj.length\n}\n\narray.__str__ = function(self){\n $B.args(\"__str__\", 1, {self: null},\n [\"self\"], arguments, {}, null, null)\n var res = \"array('\" + self.typecode + \"'\"\n if(self.obj !== null){\n res += \", [\" + self.obj + \"]\"\n }\n return res + \")\"\n}\n\nfunction normalize_index(self, i){\n // return an index i between 0 and self.obj.length - 1\n if(i < 0){\n i = self.obj.length + i\n }\n if(i < 0){i = 0}\n else if(i > self.obj.length - 1){\n i = self.obj.length\n }\n return i\n}\n\narray.append = function(self, value){\n $B.args(\"append\", 2, {self: null, value: null},\n [\"self\", \"value\"], arguments, {}, null, null)\n var pos = self.obj === null ? 0 : self.obj.length\n return array.insert(self, pos, value)\n}\n\narray.count = function(self, x){\n $B.args(\"count\", 2, {self: null, x: null},\n [\"self\", \"x\"], arguments, {}, null, null)\n if(self.obj === null){return 0}\n return self.obj.filter(function(item){return item == x}).length\n}\n\narray.extend = function(self, iterable){\n $B.args(\"extend\", 2, {self: null, iterable: null},\n [\"self\", \"iterable\"], arguments, {}, null, null)\n if(iterable.__class__ === array){\n if(iterable.typecode !== self.typecode){\n throw _b_.TypeError.$factory(\"can only extend with array \" +\n \"of same kind\")\n }\n if(iterable.obj === null){return _b_.None}\n // create new object with length = sum of lengths\n var newobj = new typecodes[self.typecode](self.obj.length +\n iterable.obj.length)\n // copy self.obj\n newobj.set(self.obj)\n // copy iterable.obj\n newobj.set(iterable.obj, self.obj.length)\n self.obj = newobj\n }else{\n var it = _b_.iter(iterable)\n while(true){\n try{\n var item = _b_.next(it)\n array.append(self, item)\n }catch(err){\n if(err.__class__ !== _b_.StopIteration){\n throw err\n }\n break\n }\n }\n }\n return _b_.None\n}\n\narray.frombytes = function(self, s){\n $B.args(\"frombytes\", 2, {self: null, s: null},\n [\"self\", \"s\"], arguments, {}, null, null)\n if(! _b_.isinstance(s, _b_.bytes)){\n throw _b_.TypeError.$factory(\"a bytes-like object is required, \" +\n \"not '\" + $B.class_name(s) + \"'\")\n }\n self.obj = new typecodes[self.typecode](s.source)\n return None\n}\n\narray.fromlist = function(self, list){\n $B.args(\"fromlist\", 2, {self: null, list: null},\n [\"self\", \"list\"], arguments, {}, null, null)\n var it = _b_.iter(list)\n while(true){\n try{\n var item = _b_.next(it)\n try{\n array.append(self, item)\n }catch(err){\n console.log(err)\n return _b_.None\n }\n }catch(err){\n if(err.__class__ === _b_.StopIteration){\n return _b_.None\n }\n throw err\n }\n }\n}\n\narray.fromstring = array.frombytes\n\narray.index = function(self, x){\n $B.args(\"index\", 2, {self: null, x: null},\n [\"self\", \"x\"], arguments, {}, null, null)\n var res = self.obj.findIndex(function(item){return x == item})\n if(res == -1){\n throw _b_.ValueError.$factory(\"array.index(x): x not in array\")\n }\n return res\n}\n\narray.insert = function(self, i, value){\n $B.args(\"insert\", 3, {self: null, i: null, value: null},\n [\"self\", \"i\", \"value\"], arguments, {}, null, null)\n if(self.obj === null){\n self.obj = [value]\n }else{\n self.obj.splice(i, 0, value)\n }\n return _b_.None\n}\n\narray.itemsize = function(self){\n return typecodes[self.typecode].BYTES_PER_ELEMENT\n}\n\narray.pop = function(self, i){\n var $ = $B.args(\"count\", 2, {self: null, i: null},\n [\"self\", \"i\"], arguments, {i: -1}, null, null)\n i = $.i\n if(self.obj === null){\n throw _b_.IndexError.$factory(\"pop from empty array\")\n }else if(self.obj.length == 1){\n var res = self.obj[0]\n self.obj = null\n return res\n }\n i = normalize_index(self, i)\n // store value to return\n var res = self.obj[i]\n // create new array, size = previous size - 1\n var newobj = new typecodes[self.typecode](self.obj.length - 1)\n // fill new array with values until i excluded\n newobj.set(self.obj.slice(0, i))\n // fill with values after i\n newobj.set(self.obj.slice(i + 1), i)\n // set self.obj to new array\n self.obj = newobj\n // return stored value\n return res\n}\n\narray.remove = function(self, x){\n $B.args(\"remove\", 2, {self: null, x: null},\n [\"self\", \"x\"], arguments, {}, null, null)\n var res = self.obj.findIndex(function(item){return x == item})\n if(res == -1){\n throw _b_.ValueError.$factory(\"array.remove(x): x not in array\")\n }\n array.pop(self, res)\n return _b_.None\n}\n\narray.reverse = function(self){\n $B.args(\"reverse\", 1, {self: null},\n [\"self\"], arguments, {}, null, null)\n if(self.obj === null){return _b_.None}\n self.obj.reverse()\n return _b_.None\n}\n\narray.tobytes = function(self){\n $B.args(\"tobytes\", 1, {self: null},\n [\"self\"], arguments, {}, null, null)\n var items = Array.slice.call(null, self.obj),\n res = []\n items.forEach(function(item){\n while(item > 256){\n res.push(item % 256)\n item = Math.floor(item / 256)\n }\n res.push(item)\n })\n return _b_.bytes.$factory(res)\n}\n\narray.tolist = function(self){\n $B.args(\"tolist\", 1, {self: null},\n [\"self\"], arguments, {}, null, null)\n return Array.slice.call(null, self.obj)\n}\n\narray.tostring = array.tobytes\n\narray.typecode = function(self){\n return self.typecode\n}\n\n$B.set_func_names(array, \"array\")\n\nreturn {\n array: array,\n typecodes: Object.keys(typecodes).join('')\n}\n\n})(__BRYTHON__)\n"], "warnings": [".py", "''\n\nimport sys\n\n\n__all__=[\"warn\",\"warn_explicit\",\"showwarning\",\n\"formatwarning\",\"filterwarnings\",\"simplefilter\",\n\"resetwarnings\",\"catch_warnings\"]\n\ndef showwarning(message,category,filename,lineno,file=None ,line=None ):\n ''\n msg=WarningMessage(message,category,filename,lineno,file,line)\n _showwarnmsg_impl(msg)\n \ndef formatwarning(message,category,filename,lineno,line=None ):\n ''\n msg=WarningMessage(message,category,filename,lineno,None ,line)\n return _formatwarnmsg_impl(msg)\n \ndef _showwarnmsg_impl(msg):\n file=msg.file\n if file is None :\n file=sys.stderr\n if file is None :\n \n \n return\n text=_formatwarnmsg(msg)\n try :\n file.write(text)\n except OSError:\n \n pass\n \ndef _formatwarnmsg_impl(msg):\n s=(\"%s:%s: %s: %s\\n\"\n %(msg.filename,msg.lineno,msg.category.__name__,\n msg.message))\n \n if msg.line is None :\n try :\n import linecache\n line=linecache.getline(msg.filename,msg.lineno)\n except Exception:\n \n \n line=None\n linecache=None\n else :\n line=msg.line\n if line:\n line=line.strip()\n s +=\" %s\\n\"%line\n \n if msg.source is not None :\n try :\n import tracemalloc\n tb=tracemalloc.get_object_traceback(msg.source)\n except Exception:\n \n \n tb=None\n \n if tb is not None :\n s +='Object allocated at (most recent call last):\\n'\n for frame in tb:\n s +=(' File \"%s\", lineno %s\\n'\n %(frame.filename,frame.lineno))\n \n try :\n if linecache is not None :\n line=linecache.getline(frame.filename,frame.lineno)\n else :\n line=None\n except Exception:\n line=None\n if line:\n line=line.strip()\n s +=' %s\\n'%line\n return s\n \n \n_showwarning_orig=showwarning\n\ndef _showwarnmsg(msg):\n ''\n try :\n sw=showwarning\n except NameError:\n pass\n else :\n if sw is not _showwarning_orig:\n \n if not callable(sw):\n raise TypeError(\"warnings.showwarning() must be set to a \"\n \"function or method\")\n \n sw(msg.message,msg.category,msg.filename,msg.lineno,\n msg.file,msg.line)\n return\n _showwarnmsg_impl(msg)\n \n \n_formatwarning_orig=formatwarning\n\ndef _formatwarnmsg(msg):\n ''\n try :\n fw=formatwarning\n except NameError:\n pass\n else :\n if fw is not _formatwarning_orig:\n \n return fw(msg.message,msg.category,\n msg.filename,msg.lineno,line=msg.line)\n return _formatwarnmsg_impl(msg)\n \ndef filterwarnings(action,message=\"\",category=Warning,module=\"\",lineno=0,\nappend=False ):\n ''\n\n\n\n\n\n\n\n\n \n assert action in (\"error\",\"ignore\",\"always\",\"default\",\"module\",\n \"once\"),\"invalid action: %r\"%(action,)\n assert isinstance(message,str),\"message must be a string\"\n assert isinstance(category,type),\"category must be a class\"\n assert issubclass(category,Warning),\"category must be a Warning subclass\"\n assert isinstance(module,str),\"module must be a string\"\n assert isinstance(lineno,int)and lineno >=0,\\\n \"lineno must be an int >= 0\"\n \n if message or module:\n import re\n \n if message:\n message=re.compile(message,re.I)\n else :\n message=None\n if module:\n module=re.compile(module)\n else :\n module=None\n \n _add_filter(action,message,category,module,lineno,append=append)\n \ndef simplefilter(action,category=Warning,lineno=0,append=False ):\n ''\n\n\n\n\n\n\n\n \n assert action in (\"error\",\"ignore\",\"always\",\"default\",\"module\",\n \"once\"),\"invalid action: %r\"%(action,)\n assert isinstance(lineno,int)and lineno >=0,\\\n \"lineno must be an int >= 0\"\n _add_filter(action,None ,category,None ,lineno,append=append)\n \ndef _add_filter(*item,append):\n\n\n if not append:\n try :\n filters.remove(item)\n except ValueError:\n pass\n filters.insert(0,item)\n else :\n if item not in filters:\n filters.append(item)\n _filters_mutated()\n \ndef resetwarnings():\n ''\n filters[:]=[]\n _filters_mutated()\n \nclass _OptionError(Exception):\n ''\n pass\n \n \ndef _processoptions(args):\n for arg in args:\n try :\n _setoption(arg)\n except _OptionError as msg:\n print(\"Invalid -W option ignored:\",msg,file=sys.stderr)\n \n \ndef _setoption(arg):\n import re\n parts=arg.split(':')\n if len(parts)>5:\n raise _OptionError(\"too many fields (max 5): %r\"%(arg,))\n while len(parts)<5:\n parts.append('')\n action,message,category,module,lineno=[s.strip()\n for s in parts]\n action=_getaction(action)\n message=re.escape(message)\n category=_getcategory(category)\n module=re.escape(module)\n if module:\n module=module+'$'\n if lineno:\n try :\n lineno=int(lineno)\n if lineno <0:\n raise ValueError\n except (ValueError,OverflowError):\n raise _OptionError(\"invalid lineno %r\"%(lineno,))from None\n else :\n lineno=0\n filterwarnings(action,message,category,module,lineno)\n \n \ndef _getaction(action):\n if not action:\n return \"default\"\n if action ==\"all\":return \"always\"\n for a in ('default','always','ignore','module','once','error'):\n if a.startswith(action):\n return a\n raise _OptionError(\"invalid action: %r\"%(action,))\n \n \ndef _getcategory(category):\n import re\n if not category:\n return Warning\n if re.match(\"^[a-zA-Z0-9_]+$\",category):\n try :\n cat=eval(category)\n except NameError:\n raise _OptionError(\"unknown warning category: %r\"%(category,))from None\n else :\n i=category.rfind(\".\")\n module=category[:i]\n klass=category[i+1:]\n try :\n m=__import__(module,None ,None ,[klass])\n except ImportError:\n raise _OptionError(\"invalid module name: %r\"%(module,))from None\n try :\n cat=getattr(m,klass)\n except AttributeError:\n raise _OptionError(\"unknown warning category: %r\"%(category,))from None\n if not issubclass(cat,Warning):\n raise _OptionError(\"invalid warning category: %r\"%(category,))\n return cat\n \n \ndef _is_internal_frame(frame):\n ''\n filename=frame.f_code.co_filename\n return 'importlib'in filename and '_bootstrap'in filename\n \n \ndef _next_external_frame(frame):\n ''\n frame=frame.f_back\n while frame is not None and _is_internal_frame(frame):\n frame=frame.f_back\n return frame\n \n \n \ndef warn(message,category=None ,stacklevel=1,source=None ):\n ''\n \n if isinstance(message,Warning):\n category=message.__class__\n \n if category is None :\n category=UserWarning\n if not (isinstance(category,type)and issubclass(category,Warning)):\n raise TypeError(\"category must be a Warning subclass, \"\n \"not '{:s}'\".format(type(category).__name__))\n \n try :\n if stacklevel <=1 or _is_internal_frame(sys._getframe(1)):\n \n \n frame=sys._getframe(stacklevel)\n else :\n frame=sys._getframe(1)\n \n for x in range(stacklevel -1):\n frame=_next_external_frame(frame)\n if frame is None :\n raise ValueError\n except ValueError:\n globals=sys.__dict__\n lineno=1\n else :\n globals=frame.f_globals\n lineno=frame.f_lineno\n if '__name__'in globals:\n module=globals['__name__']\n else :\n module=\"<string>\"\n filename=globals.get('__file__')\n if filename:\n fnl=filename.lower()\n if fnl.endswith(\".pyc\"):\n filename=filename[:-1]\n else :\n if module ==\"__main__\":\n try :\n filename=sys.argv[0]\n except AttributeError:\n \n filename='__main__'\n if not filename:\n filename=module\n registry=globals.setdefault(\"__warningregistry__\",{})\n warn_explicit(message,category,filename,lineno,module,registry,\n globals,source)\n \ndef warn_explicit(message,category,filename,lineno,\nmodule=None ,registry=None ,module_globals=None ,\nsource=None ):\n lineno=int(lineno)\n if module is None :\n module=filename or \"<unknown>\"\n if module[-3:].lower()==\".py\":\n module=module[:-3]\n if registry is None :\n registry={}\n if registry.get('version',0)!=_filters_version:\n registry.clear()\n registry['version']=_filters_version\n if isinstance(message,Warning):\n text=str(message)\n category=message.__class__\n else :\n text=message\n message=category(message)\n key=(text,category,lineno)\n \n if registry.get(key):\n return\n \n for item in filters:\n action,msg,cat,mod,ln=item\n if ((msg is None or msg.match(text))and\n issubclass(category,cat)and\n (mod is None or mod.match(module))and\n (ln ==0 or lineno ==ln)):\n break\n else :\n action=defaultaction\n \n if action ==\"ignore\":\n return\n \n \n \n import linecache\n linecache.getlines(filename,module_globals)\n \n if action ==\"error\":\n raise message\n \n if action ==\"once\":\n registry[key]=1\n oncekey=(text,category)\n if onceregistry.get(oncekey):\n return\n onceregistry[oncekey]=1\n elif action ==\"always\":\n pass\n elif action ==\"module\":\n registry[key]=1\n altkey=(text,category,0)\n if registry.get(altkey):\n return\n registry[altkey]=1\n elif action ==\"default\":\n registry[key]=1\n else :\n \n raise RuntimeError(\n \"Unrecognized action (%r) in warnings.filters:\\n %s\"%\n (action,item))\n \n msg=WarningMessage(message,category,filename,lineno,source)\n _showwarnmsg(msg)\n \n \nclass WarningMessage(object):\n\n _WARNING_DETAILS=(\"message\",\"category\",\"filename\",\"lineno\",\"file\",\n \"line\",\"source\")\n \n def __init__(self,message,category,filename,lineno,file=None ,\n line=None ,source=None ):\n self.message=message\n self.category=category\n self.filename=filename\n self.lineno=lineno\n self.file=file\n self.line=line\n self.source=source\n self._category_name=category.__name__ if category else None\n \n def __str__(self):\n return (\"{message : %r, category : %r, filename : %r, lineno : %s, \"\n \"line : %r}\"%(self.message,self._category_name,\n self.filename,self.lineno,self.line))\n \n \nclass catch_warnings(object):\n\n ''\n\n\n\n\n\n\n\n\n\n\n\n\n \n \n def __init__(self,*,record=False ,module=None ):\n ''\n\n\n\n\n\n \n self._record=record\n self._module=sys.modules['warnings']if module is None else module\n self._entered=False\n \n def __repr__(self):\n args=[]\n if self._record:\n args.append(\"record=True\")\n if self._module is not sys.modules['warnings']:\n args.append(\"module=%r\"%self._module)\n name=type(self).__name__\n return \"%s(%s)\"%(name,\", \".join(args))\n \n def __enter__(self):\n if self._entered:\n raise RuntimeError(\"Cannot enter %r twice\"%self)\n self._entered=True\n self._filters=self._module.filters\n self._module.filters=self._filters[:]\n self._module._filters_mutated()\n self._showwarning=self._module.showwarning\n self._showwarnmsg_impl=self._module._showwarnmsg_impl\n if self._record:\n log=[]\n self._module._showwarnmsg_impl=log.append\n \n \n self._module.showwarning=self._module._showwarning_orig\n return log\n else :\n return None\n \n def __exit__(self,*exc_info):\n if not self._entered:\n raise RuntimeError(\"Cannot exit %r without entering first\"%self)\n self._module.filters=self._filters\n self._module._filters_mutated()\n self._module.showwarning=self._showwarning\n self._module._showwarnmsg_impl=self._showwarnmsg_impl\n \n \n \ndef _warn_unawaited_coroutine(coro):\n msg_lines=[\n f\"coroutine '{coro.__qualname__}' was never awaited\\n\"\n ]\n if coro.cr_origin is not None :\n import linecache,traceback\n def extract():\n for filename,lineno,funcname in reversed(coro.cr_origin):\n line=linecache.getline(filename,lineno)\n yield (filename,lineno,funcname,line)\n msg_lines.append(\"Coroutine created at (most recent call last)\\n\")\n msg_lines +=traceback.format_list(list(extract()))\n msg=\"\".join(msg_lines).rstrip(\"\\n\")\n \n \n \n \n \n \n warn(msg,category=RuntimeWarning,stacklevel=2,source=coro)\n \n \n \n \n \n \n \n \n \n \ntry :\n from _warnings import (filters,_defaultaction,_onceregistry,\n warn,warn_explicit,_filters_mutated)\n defaultaction=_defaultaction\n onceregistry=_onceregistry\n _warnings_defaults=True\nexcept ImportError:\n filters=[]\n defaultaction=\"default\"\n onceregistry={}\n \n _filters_version=1\n \n def _filters_mutated():\n global _filters_version\n _filters_version +=1\n \n _warnings_defaults=False\n \n \n \n_processoptions(sys.warnoptions)\nif not _warnings_defaults:\n\n if not hasattr(sys,'gettotalrefcount'):\n filterwarnings(\"default\",category=DeprecationWarning,\n module=\"__main__\",append=1)\n simplefilter(\"ignore\",category=DeprecationWarning,append=1)\n simplefilter(\"ignore\",category=PendingDeprecationWarning,append=1)\n simplefilter(\"ignore\",category=ImportWarning,append=1)\n simplefilter(\"ignore\",category=ResourceWarning,append=1)\n \ndel _warnings_defaults\n", ["_warnings", "linecache", "re", "sys", "traceback", "tracemalloc"]], "unittest.loader": [".py", "''\n\nimport os\nimport re\nimport sys\nimport traceback\nimport types\nimport functools\nimport warnings\n\nfrom fnmatch import fnmatch,fnmatchcase\n\nfrom . import case,suite,util\n\n__unittest=True\n\n\n\n\nVALID_MODULE_NAME=re.compile(r'[_a-z]\\w*\\.py$',re.IGNORECASE)\n\n\nclass _FailedTest(case.TestCase):\n _testMethodName=None\n \n def __init__(self,method_name,exception):\n self._exception=exception\n super(_FailedTest,self).__init__(method_name)\n \n def __getattr__(self,name):\n if name !=self._testMethodName:\n return super(_FailedTest,self).__getattr__(name)\n def testFailure():\n raise self._exception\n return testFailure\n \n \ndef _make_failed_import_test(name,suiteClass):\n message='Failed to import test module: %s\\n%s'%(\n name,traceback.format_exc())\n return _make_failed_test(name,ImportError(message),suiteClass,message)\n \ndef _make_failed_load_tests(name,exception,suiteClass):\n message='Failed to call load_tests:\\n%s'%(traceback.format_exc(),)\n return _make_failed_test(\n name,exception,suiteClass,message)\n \ndef _make_failed_test(methodname,exception,suiteClass,message):\n test=_FailedTest(methodname,exception)\n return suiteClass((test,)),message\n \ndef _make_skipped_test(methodname,exception,suiteClass):\n @case.skip(str(exception))\n def testSkipped(self):\n pass\n attrs={methodname:testSkipped}\n TestClass=type(\"ModuleSkipped\",(case.TestCase,),attrs)\n return suiteClass((TestClass(methodname),))\n \ndef _jython_aware_splitext(path):\n if path.lower().endswith('$py.class'):\n return path[:-9]\n return os.path.splitext(path)[0]\n \n \nclass TestLoader(object):\n ''\n\n\n \n testMethodPrefix='test'\n sortTestMethodsUsing=staticmethod(util.three_way_cmp)\n testNamePatterns=None\n suiteClass=suite.TestSuite\n _top_level_dir=None\n \n def __init__(self):\n super(TestLoader,self).__init__()\n self.errors=[]\n \n \n self._loading_packages=set()\n \n def loadTestsFromTestCase(self,testCaseClass):\n ''\n if issubclass(testCaseClass,suite.TestSuite):\n raise TypeError(\"Test cases should not be derived from \"\n \"TestSuite. Maybe you meant to derive from \"\n \"TestCase?\")\n testCaseNames=self.getTestCaseNames(testCaseClass)\n if not testCaseNames and hasattr(testCaseClass,'runTest'):\n testCaseNames=['runTest']\n loaded_suite=self.suiteClass(map(testCaseClass,testCaseNames))\n return loaded_suite\n \n \n \n def loadTestsFromModule(self,module,*args,pattern=None ,**kws):\n ''\n \n \n \n \n if len(args)>0 or 'use_load_tests'in kws:\n warnings.warn('use_load_tests is deprecated and ignored',\n DeprecationWarning)\n kws.pop('use_load_tests',None )\n if len(args)>1:\n \n \n complaint=len(args)+1\n raise TypeError('loadTestsFromModule() takes 1 positional argument but {} were given'.format(complaint))\n if len(kws)!=0:\n \n \n \n \n complaint=sorted(kws)[0]\n raise TypeError(\"loadTestsFromModule() got an unexpected keyword argument '{}'\".format(complaint))\n tests=[]\n for name in dir(module):\n obj=getattr(module,name)\n if isinstance(obj,type)and issubclass(obj,case.TestCase):\n tests.append(self.loadTestsFromTestCase(obj))\n \n load_tests=getattr(module,'load_tests',None )\n tests=self.suiteClass(tests)\n if load_tests is not None :\n try :\n return load_tests(self,tests,pattern)\n except Exception as e:\n error_case,error_message=_make_failed_load_tests(\n module.__name__,e,self.suiteClass)\n self.errors.append(error_message)\n return error_case\n return tests\n \n def loadTestsFromName(self,name,module=None ):\n ''\n\n\n\n\n\n\n \n parts=name.split('.')\n error_case,error_message=None ,None\n if module is None :\n parts_copy=parts[:]\n while parts_copy:\n try :\n module_name='.'.join(parts_copy)\n module=__import__(module_name)\n break\n except ImportError:\n next_attribute=parts_copy.pop()\n \n error_case,error_message=_make_failed_import_test(\n next_attribute,self.suiteClass)\n if not parts_copy:\n \n self.errors.append(error_message)\n return error_case\n parts=parts[1:]\n obj=module\n for part in parts:\n try :\n parent,obj=obj,getattr(obj,part)\n except AttributeError as e:\n \n if (getattr(obj,'__path__',None )is not None\n and error_case is not None ):\n \n \n \n \n \n self.errors.append(error_message)\n return error_case\n else :\n \n error_case,error_message=_make_failed_test(\n part,e,self.suiteClass,\n 'Failed to access attribute:\\n%s'%(\n traceback.format_exc(),))\n self.errors.append(error_message)\n return error_case\n \n if isinstance(obj,types.ModuleType):\n return self.loadTestsFromModule(obj)\n elif isinstance(obj,type)and issubclass(obj,case.TestCase):\n return self.loadTestsFromTestCase(obj)\n elif (isinstance(obj,types.FunctionType)and\n isinstance(parent,type)and\n issubclass(parent,case.TestCase)):\n name=parts[-1]\n inst=parent(name)\n \n if not isinstance(getattr(inst,name),types.FunctionType):\n return self.suiteClass([inst])\n elif isinstance(obj,suite.TestSuite):\n return obj\n if callable(obj):\n test=obj()\n if isinstance(test,suite.TestSuite):\n return test\n elif isinstance(test,case.TestCase):\n return self.suiteClass([test])\n else :\n raise TypeError(\"calling %s returned %s, not a test\"%\n (obj,test))\n else :\n raise TypeError(\"don't know how to make test from: %s\"%obj)\n \n def loadTestsFromNames(self,names,module=None ):\n ''\n\n \n suites=[self.loadTestsFromName(name,module)for name in names]\n return self.suiteClass(suites)\n \n def getTestCaseNames(self,testCaseClass):\n ''\n \n def shouldIncludeMethod(attrname):\n if not attrname.startswith(self.testMethodPrefix):\n return False\n testFunc=getattr(testCaseClass,attrname)\n if not callable(testFunc):\n return False\n fullName='%s.%s'%(testCaseClass.__module__,testFunc.__qualname__)\n return self.testNamePatterns is None or\\\n any(fnmatchcase(fullName,pattern)for pattern in self.testNamePatterns)\n testFnNames=list(filter(shouldIncludeMethod,dir(testCaseClass)))\n if self.sortTestMethodsUsing:\n testFnNames.sort(key=functools.cmp_to_key(self.sortTestMethodsUsing))\n return testFnNames\n \n def discover(self,start_dir,pattern='test*.py',top_level_dir=None ):\n ''\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n \n set_implicit_top=False\n if top_level_dir is None and self._top_level_dir is not None :\n \n top_level_dir=self._top_level_dir\n elif top_level_dir is None :\n set_implicit_top=True\n top_level_dir=start_dir\n \n top_level_dir=os.path.abspath(top_level_dir)\n \n if not top_level_dir in sys.path:\n \n \n \n \n sys.path.insert(0,top_level_dir)\n self._top_level_dir=top_level_dir\n \n is_not_importable=False\n is_namespace=False\n tests=[]\n if os.path.isdir(os.path.abspath(start_dir)):\n start_dir=os.path.abspath(start_dir)\n if start_dir !=top_level_dir:\n is_not_importable=not os.path.isfile(os.path.join(start_dir,'__init__.py'))\n else :\n \n try :\n __import__(start_dir)\n except ImportError:\n is_not_importable=True\n else :\n the_module=sys.modules[start_dir]\n top_part=start_dir.split('.')[0]\n try :\n start_dir=os.path.abspath(\n os.path.dirname((the_module.__file__)))\n except AttributeError:\n \n try :\n spec=the_module.__spec__\n except AttributeError:\n spec=None\n \n if spec and spec.loader is None :\n if spec.submodule_search_locations is not None :\n is_namespace=True\n \n for path in the_module.__path__:\n if (not set_implicit_top and\n not path.startswith(top_level_dir)):\n continue\n self._top_level_dir=\\\n (path.split(the_module.__name__\n .replace(\".\",os.path.sep))[0])\n tests.extend(self._find_tests(path,\n pattern,\n namespace=True ))\n elif the_module.__name__ in sys.builtin_module_names:\n \n raise TypeError('Can not use builtin modules '\n 'as dotted module names')from None\n else :\n raise TypeError(\n 'don\\'t know how to discover from {!r}'\n .format(the_module))from None\n \n if set_implicit_top:\n if not is_namespace:\n self._top_level_dir=\\\n self._get_directory_containing_module(top_part)\n sys.path.remove(top_level_dir)\n else :\n sys.path.remove(top_level_dir)\n \n if is_not_importable:\n raise ImportError('Start directory is not importable: %r'%start_dir)\n \n if not is_namespace:\n tests=list(self._find_tests(start_dir,pattern))\n return self.suiteClass(tests)\n \n def _get_directory_containing_module(self,module_name):\n module=sys.modules[module_name]\n full_path=os.path.abspath(module.__file__)\n \n if os.path.basename(full_path).lower().startswith('__init__.py'):\n return os.path.dirname(os.path.dirname(full_path))\n else :\n \n \n \n return os.path.dirname(full_path)\n \n def _get_name_from_path(self,path):\n if path ==self._top_level_dir:\n return '.'\n path=_jython_aware_splitext(os.path.normpath(path))\n \n _relpath=os.path.relpath(path,self._top_level_dir)\n assert not os.path.isabs(_relpath),\"Path must be within the project\"\n assert not _relpath.startswith('..'),\"Path must be within the project\"\n \n name=_relpath.replace(os.path.sep,'.')\n return name\n \n def _get_module_from_name(self,name):\n __import__(name)\n return sys.modules[name]\n \n def _match_path(self,path,full_path,pattern):\n \n return fnmatch(path,pattern)\n \n def _find_tests(self,start_dir,pattern,namespace=False ):\n ''\n \n name=self._get_name_from_path(start_dir)\n \n \n if name !='.'and name not in self._loading_packages:\n \n \n tests,should_recurse=self._find_test_path(\n start_dir,pattern,namespace)\n if tests is not None :\n yield tests\n if not should_recurse:\n \n \n return\n \n paths=sorted(os.listdir(start_dir))\n for path in paths:\n full_path=os.path.join(start_dir,path)\n tests,should_recurse=self._find_test_path(\n full_path,pattern,namespace)\n if tests is not None :\n yield tests\n if should_recurse:\n \n name=self._get_name_from_path(full_path)\n self._loading_packages.add(name)\n try :\n yield from self._find_tests(full_path,pattern,namespace)\n finally :\n self._loading_packages.discard(name)\n \n def _find_test_path(self,full_path,pattern,namespace=False ):\n ''\n\n\n\n\n\n \n basename=os.path.basename(full_path)\n if os.path.isfile(full_path):\n if not VALID_MODULE_NAME.match(basename):\n \n return None ,False\n if not self._match_path(basename,full_path,pattern):\n return None ,False\n \n name=self._get_name_from_path(full_path)\n try :\n module=self._get_module_from_name(name)\n except case.SkipTest as e:\n return _make_skipped_test(name,e,self.suiteClass),False\n except :\n error_case,error_message=\\\n _make_failed_import_test(name,self.suiteClass)\n self.errors.append(error_message)\n return error_case,False\n else :\n mod_file=os.path.abspath(\n getattr(module,'__file__',full_path))\n realpath=_jython_aware_splitext(\n os.path.realpath(mod_file))\n fullpath_noext=_jython_aware_splitext(\n os.path.realpath(full_path))\n if realpath.lower()!=fullpath_noext.lower():\n module_dir=os.path.dirname(realpath)\n mod_name=_jython_aware_splitext(\n os.path.basename(full_path))\n expected_dir=os.path.dirname(full_path)\n msg=(\"%r module incorrectly imported from %r. Expected \"\n \"%r. Is this module globally installed?\")\n raise ImportError(\n msg %(mod_name,module_dir,expected_dir))\n return self.loadTestsFromModule(module,pattern=pattern),False\n elif os.path.isdir(full_path):\n if (not namespace and\n not os.path.isfile(os.path.join(full_path,'__init__.py'))):\n return None ,False\n \n load_tests=None\n tests=None\n name=self._get_name_from_path(full_path)\n try :\n package=self._get_module_from_name(name)\n except case.SkipTest as e:\n return _make_skipped_test(name,e,self.suiteClass),False\n except :\n error_case,error_message=\\\n _make_failed_import_test(name,self.suiteClass)\n self.errors.append(error_message)\n return error_case,False\n else :\n load_tests=getattr(package,'load_tests',None )\n \n self._loading_packages.add(name)\n try :\n tests=self.loadTestsFromModule(package,pattern=pattern)\n if load_tests is not None :\n \n return tests,False\n return tests,True\n finally :\n self._loading_packages.discard(name)\n else :\n return None ,False\n \n \ndefaultTestLoader=TestLoader()\n\n\ndef _makeLoader(prefix,sortUsing,suiteClass=None ,testNamePatterns=None ):\n loader=TestLoader()\n loader.sortTestMethodsUsing=sortUsing\n loader.testMethodPrefix=prefix\n loader.testNamePatterns=testNamePatterns\n if suiteClass:\n loader.suiteClass=suiteClass\n return loader\n \ndef getTestCaseNames(testCaseClass,prefix,sortUsing=util.three_way_cmp,testNamePatterns=None ):\n return _makeLoader(prefix,sortUsing,testNamePatterns=testNamePatterns).getTestCaseNames(testCaseClass)\n \ndef makeSuite(testCaseClass,prefix='test',sortUsing=util.three_way_cmp,\nsuiteClass=suite.TestSuite):\n return _makeLoader(prefix,sortUsing,suiteClass).loadTestsFromTestCase(\n testCaseClass)\n \ndef findTestCases(module,prefix='test',sortUsing=util.three_way_cmp,\nsuiteClass=suite.TestSuite):\n return _makeLoader(prefix,sortUsing,suiteClass).loadTestsFromModule(\\\n module)\n", ["fnmatch", "functools", "os", "re", "sys", "traceback", "types", "unittest", "unittest.case", "unittest.suite", "unittest.util", "warnings"]], "quopri": [".py", "#! /usr/bin/env python3\n\n\"\"\"Conversions to/from quoted-printable transport encoding as per RFC 1521.\"\"\"\n\n\n\n__all__=[\"encode\",\"decode\",\"encodestring\",\"decodestring\"]\n\nESCAPE=b'='\nMAXLINESIZE=76\nHEX=b'0123456789ABCDEF'\nEMPTYSTRING=b''\n\ntry :\n from binascii import a2b_qp,b2a_qp\nexcept ImportError:\n a2b_qp=None\n b2a_qp=None\n \n \ndef needsquoting(c,quotetabs,header):\n ''\n\n\n\n\n \n assert isinstance(c,bytes)\n if c in b' \\t':\n return quotetabs\n \n if c ==b'_':\n return header\n return c ==ESCAPE or not (b' '<=c <=b'~')\n \ndef quote(c):\n ''\n assert isinstance(c,bytes)and len(c)==1\n c=ord(c)\n return ESCAPE+bytes((HEX[c //16],HEX[c %16]))\n \n \n \ndef encode(input,output,quotetabs,header=False ):\n ''\n\n\n\n\n\n \n \n if b2a_qp is not None :\n data=input.read()\n odata=b2a_qp(data,quotetabs=quotetabs,header=header)\n output.write(odata)\n return\n \n def write(s,output=output,lineEnd=b'\\n'):\n \n \n if s and s[-1:]in b' \\t':\n output.write(s[:-1]+quote(s[-1:])+lineEnd)\n elif s ==b'.':\n output.write(quote(s)+lineEnd)\n else :\n output.write(s+lineEnd)\n \n prevline=None\n while 1:\n line=input.readline()\n if not line:\n break\n outline=[]\n \n stripped=b''\n if line[-1:]==b'\\n':\n line=line[:-1]\n stripped=b'\\n'\n \n for c in line:\n c=bytes((c,))\n if needsquoting(c,quotetabs,header):\n c=quote(c)\n if header and c ==b' ':\n outline.append(b'_')\n else :\n outline.append(c)\n \n if prevline is not None :\n write(prevline)\n \n \n thisline=EMPTYSTRING.join(outline)\n while len(thisline)>MAXLINESIZE:\n \n \n write(thisline[:MAXLINESIZE -1],lineEnd=b'=\\n')\n thisline=thisline[MAXLINESIZE -1:]\n \n prevline=thisline\n \n if prevline is not None :\n write(prevline,lineEnd=stripped)\n \ndef encodestring(s,quotetabs=False ,header=False ):\n if b2a_qp is not None :\n return b2a_qp(s,quotetabs=quotetabs,header=header)\n from io import BytesIO\n infp=BytesIO(s)\n outfp=BytesIO()\n encode(infp,outfp,quotetabs,header)\n return outfp.getvalue()\n \n \n \ndef decode(input,output,header=False ):\n ''\n\n \n \n if a2b_qp is not None :\n data=input.read()\n odata=a2b_qp(data,header=header)\n output.write(odata)\n return\n \n new=b''\n while 1:\n line=input.readline()\n if not line:break\n i,n=0,len(line)\n if n >0 and line[n -1:n]==b'\\n':\n partial=0 ;n=n -1\n \n while n >0 and line[n -1:n]in b\" \\t\\r\":\n n=n -1\n else :\n partial=1\n while i <n:\n c=line[i:i+1]\n if c ==b'_'and header:\n new=new+b' ';i=i+1\n elif c !=ESCAPE:\n new=new+c ;i=i+1\n elif i+1 ==n and not partial:\n partial=1 ;break\n elif i+1 <n and line[i+1:i+2]==ESCAPE:\n new=new+ESCAPE ;i=i+2\n elif i+2 <n and ishex(line[i+1:i+2])and ishex(line[i+2:i+3]):\n new=new+bytes((unhex(line[i+1:i+3]),));i=i+3\n else :\n new=new+c ;i=i+1\n if not partial:\n output.write(new+b'\\n')\n new=b''\n if new:\n output.write(new)\n \ndef decodestring(s,header=False ):\n if a2b_qp is not None :\n return a2b_qp(s,header=header)\n from io import BytesIO\n infp=BytesIO(s)\n outfp=BytesIO()\n decode(infp,outfp,header=header)\n return outfp.getvalue()\n \n \n \n \ndef ishex(c):\n ''\n assert isinstance(c,bytes)\n return b'0'<=c <=b'9'or b'a'<=c <=b'f'or b'A'<=c <=b'F'\n \ndef unhex(s):\n ''\n bits=0\n for c in s:\n c=bytes((c,))\n if b'0'<=c <=b'9':\n i=ord('0')\n elif b'a'<=c <=b'f':\n i=ord('a')-10\n elif b'A'<=c <=b'F':\n i=ord(b'A')-10\n else :\n assert False ,\"non-hex digit \"+repr(c)\n bits=bits *16+(ord(c)-i)\n return bits\n \n \n \ndef main():\n import sys\n import getopt\n try :\n opts,args=getopt.getopt(sys.argv[1:],'td')\n except getopt.error as msg:\n sys.stdout=sys.stderr\n print(msg)\n print(\"usage: quopri [-t | -d] [file] ...\")\n print(\"-t: quote tabs\")\n print(\"-d: decode; default encode\")\n sys.exit(2)\n deco=0\n tabs=0\n for o,a in opts:\n if o =='-t':tabs=1\n if o =='-d':deco=1\n if tabs and deco:\n sys.stdout=sys.stderr\n print(\"-t and -d are mutually exclusive\")\n sys.exit(2)\n if not args:args=['-']\n sts=0\n for file in args:\n if file =='-':\n fp=sys.stdin.buffer\n else :\n try :\n fp=open(file,\"rb\")\n except OSError as msg:\n sys.stderr.write(\"%s: can't open (%s)\\n\"%(file,msg))\n sts=1\n continue\n try :\n if deco:\n decode(fp,sys.stdout.buffer)\n else :\n encode(fp,sys.stdout.buffer,tabs)\n finally :\n if file !='-':\n fp.close()\n if sts:\n sys.exit(sts)\n \n \n \nif __name__ =='__main__':\n main()\n", ["binascii", "getopt", "io", "sys"]], "difflib": [".py", "''\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n__all__=['get_close_matches','ndiff','restore','SequenceMatcher',\n'Differ','IS_CHARACTER_JUNK','IS_LINE_JUNK','context_diff',\n'unified_diff','diff_bytes','HtmlDiff','Match']\n\nfrom heapq import nlargest as _nlargest\nfrom collections import namedtuple as _namedtuple\n\nMatch=_namedtuple('Match','a b size')\n\ndef _calculate_ratio(matches,length):\n if length:\n return 2.0 *matches /length\n return 1.0\n \nclass SequenceMatcher:\n\n ''\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n \n \n def __init__(self,isjunk=None ,a='',b='',autojunk=True ):\n ''\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n self.isjunk=isjunk\n self.a=self.b=None\n self.autojunk=autojunk\n self.set_seqs(a,b)\n \n def set_seqs(self,a,b):\n ''\n\n\n\n\n\n \n \n self.set_seq1(a)\n self.set_seq2(b)\n \n def set_seq1(self,a):\n ''\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n \n \n if a is self.a:\n return\n self.a=a\n self.matching_blocks=self.opcodes=None\n \n def set_seq2(self,b):\n ''\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n \n \n if b is self.b:\n return\n self.b=b\n self.matching_blocks=self.opcodes=None\n self.fullbcount=None\n self.__chain_b()\n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n def __chain_b(self):\n \n \n \n \n \n \n \n \n \n \n b=self.b\n self.b2j=b2j={}\n \n for i,elt in enumerate(b):\n indices=b2j.setdefault(elt,[])\n indices.append(i)\n \n \n self.bjunk=junk=set()\n isjunk=self.isjunk\n if isjunk:\n for elt in b2j.keys():\n if isjunk(elt):\n junk.add(elt)\n for elt in junk:\n del b2j[elt]\n \n \n self.bpopular=popular=set()\n n=len(b)\n if self.autojunk and n >=200:\n ntest=n //100+1\n for elt,idxs in b2j.items():\n if len(idxs)>ntest:\n popular.add(elt)\n for elt in popular:\n del b2j[elt]\n \n def find_longest_match(self,alo,ahi,blo,bhi):\n ''\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n \n \n \n \n \n \n \n \n \n \n \n \n \n \n a,b,b2j,isbjunk=self.a,self.b,self.b2j,self.bjunk.__contains__\n besti,bestj,bestsize=alo,blo,0\n \n \n \n j2len={}\n nothing=[]\n for i in range(alo,ahi):\n \n \n j2lenget=j2len.get\n newj2len={}\n for j in b2j.get(a[i],nothing):\n \n if j <blo:\n continue\n if j >=bhi:\n break\n k=newj2len[j]=j2lenget(j -1,0)+1\n if k >bestsize:\n besti,bestj,bestsize=i -k+1,j -k+1,k\n j2len=newj2len\n \n \n \n \n \n while besti >alo and bestj >blo and\\\n not isbjunk(b[bestj -1])and\\\n a[besti -1]==b[bestj -1]:\n besti,bestj,bestsize=besti -1,bestj -1,bestsize+1\n while besti+bestsize <ahi and bestj+bestsize <bhi and\\\n not isbjunk(b[bestj+bestsize])and\\\n a[besti+bestsize]==b[bestj+bestsize]:\n bestsize +=1\n \n \n \n \n \n \n \n \n while besti >alo and bestj >blo and\\\n isbjunk(b[bestj -1])and\\\n a[besti -1]==b[bestj -1]:\n besti,bestj,bestsize=besti -1,bestj -1,bestsize+1\n while besti+bestsize <ahi and bestj+bestsize <bhi and\\\n isbjunk(b[bestj+bestsize])and\\\n a[besti+bestsize]==b[bestj+bestsize]:\n bestsize=bestsize+1\n \n return Match(besti,bestj,bestsize)\n \n def get_matching_blocks(self):\n ''\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n \n \n if self.matching_blocks is not None :\n return self.matching_blocks\n la,lb=len(self.a),len(self.b)\n \n \n \n \n \n \n \n queue=[(0,la,0,lb)]\n matching_blocks=[]\n while queue:\n alo,ahi,blo,bhi=queue.pop()\n i,j,k=x=self.find_longest_match(alo,ahi,blo,bhi)\n \n \n \n if k:\n matching_blocks.append(x)\n if alo <i and blo <j:\n queue.append((alo,i,blo,j))\n if i+k <ahi and j+k <bhi:\n queue.append((i+k,ahi,j+k,bhi))\n matching_blocks.sort()\n \n \n \n \n i1=j1=k1=0\n non_adjacent=[]\n for i2,j2,k2 in matching_blocks:\n \n if i1+k1 ==i2 and j1+k1 ==j2:\n \n \n \n k1 +=k2\n else :\n \n \n \n if k1:\n non_adjacent.append((i1,j1,k1))\n i1,j1,k1=i2,j2,k2\n if k1:\n non_adjacent.append((i1,j1,k1))\n \n non_adjacent.append((la,lb,0))\n self.matching_blocks=list(map(Match._make,non_adjacent))\n return self.matching_blocks\n \n def get_opcodes(self):\n ''\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n \n \n if self.opcodes is not None :\n return self.opcodes\n i=j=0\n self.opcodes=answer=[]\n for ai,bj,size in self.get_matching_blocks():\n \n \n \n \n \n tag=''\n if i <ai and j <bj:\n tag='replace'\n elif i <ai:\n tag='delete'\n elif j <bj:\n tag='insert'\n if tag:\n answer.append((tag,i,ai,j,bj))\n i,j=ai+size,bj+size\n \n \n if size:\n answer.append(('equal',ai,i,bj,j))\n return answer\n \n def get_grouped_opcodes(self,n=3):\n ''\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n \n \n codes=self.get_opcodes()\n if not codes:\n codes=[(\"equal\",0,1,0,1)]\n \n if codes[0][0]=='equal':\n tag,i1,i2,j1,j2=codes[0]\n codes[0]=tag,max(i1,i2 -n),i2,max(j1,j2 -n),j2\n if codes[-1][0]=='equal':\n tag,i1,i2,j1,j2=codes[-1]\n codes[-1]=tag,i1,min(i2,i1+n),j1,min(j2,j1+n)\n \n nn=n+n\n group=[]\n for tag,i1,i2,j1,j2 in codes:\n \n \n if tag =='equal'and i2 -i1 >nn:\n group.append((tag,i1,min(i2,i1+n),j1,min(j2,j1+n)))\n yield group\n group=[]\n i1,j1=max(i1,i2 -n),max(j1,j2 -n)\n group.append((tag,i1,i2,j1,j2))\n if group and not (len(group)==1 and group[0][0]=='equal'):\n yield group\n \n def ratio(self):\n ''\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n \n \n matches=sum(triple[-1]for triple in self.get_matching_blocks())\n return _calculate_ratio(matches,len(self.a)+len(self.b))\n \n def quick_ratio(self):\n ''\n\n\n\n \n \n \n \n \n if self.fullbcount is None :\n self.fullbcount=fullbcount={}\n for elt in self.b:\n fullbcount[elt]=fullbcount.get(elt,0)+1\n fullbcount=self.fullbcount\n \n \n avail={}\n availhas,matches=avail.__contains__,0\n for elt in self.a:\n if availhas(elt):\n numb=avail[elt]\n else :\n numb=fullbcount.get(elt,0)\n avail[elt]=numb -1\n if numb >0:\n matches=matches+1\n return _calculate_ratio(matches,len(self.a)+len(self.b))\n \n def real_quick_ratio(self):\n ''\n\n\n\n \n \n la,lb=len(self.a),len(self.b)\n \n \n return _calculate_ratio(min(la,lb),la+lb)\n \ndef get_close_matches(word,possibilities,n=3,cutoff=0.6):\n ''\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n \n \n if not n >0:\n raise ValueError(\"n must be > 0: %r\"%(n,))\n if not 0.0 <=cutoff <=1.0:\n raise ValueError(\"cutoff must be in [0.0, 1.0]: %r\"%(cutoff,))\n result=[]\n s=SequenceMatcher()\n s.set_seq2(word)\n for x in possibilities:\n s.set_seq1(x)\n if s.real_quick_ratio()>=cutoff and\\\n s.quick_ratio()>=cutoff and\\\n s.ratio()>=cutoff:\n result.append((s.ratio(),x))\n \n \n result=_nlargest(n,result)\n \n return [x for score,x in result]\n \ndef _count_leading(line,ch):\n ''\n\n\n\n\n\n\n \n \n i,n=0,len(line)\n while i <n and line[i]==ch:\n i +=1\n return i\n \nclass Differ:\n ''\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n \n \n def __init__(self,linejunk=None ,charjunk=None ):\n ''\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n \n \n self.linejunk=linejunk\n self.charjunk=charjunk\n \n def compare(self,a,b):\n ''\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n \n \n cruncher=SequenceMatcher(self.linejunk,a,b)\n for tag,alo,ahi,blo,bhi in cruncher.get_opcodes():\n if tag =='replace':\n g=self._fancy_replace(a,alo,ahi,b,blo,bhi)\n elif tag =='delete':\n g=self._dump('-',a,alo,ahi)\n elif tag =='insert':\n g=self._dump('+',b,blo,bhi)\n elif tag =='equal':\n g=self._dump(' ',a,alo,ahi)\n else :\n raise ValueError('unknown tag %r'%(tag,))\n \n yield from g\n \n def _dump(self,tag,x,lo,hi):\n ''\n for i in range(lo,hi):\n yield '%s %s'%(tag,x[i])\n \n def _plain_replace(self,a,alo,ahi,b,blo,bhi):\n assert alo <ahi and blo <bhi\n \n \n if bhi -blo <ahi -alo:\n first=self._dump('+',b,blo,bhi)\n second=self._dump('-',a,alo,ahi)\n else :\n first=self._dump('-',a,alo,ahi)\n second=self._dump('+',b,blo,bhi)\n \n for g in first,second:\n yield from g\n \n def _fancy_replace(self,a,alo,ahi,b,blo,bhi):\n ''\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n \n \n \n \n best_ratio,cutoff=0.74,0.75\n cruncher=SequenceMatcher(self.charjunk)\n eqi,eqj=None ,None\n \n \n \n \n for j in range(blo,bhi):\n bj=b[j]\n cruncher.set_seq2(bj)\n for i in range(alo,ahi):\n ai=a[i]\n if ai ==bj:\n if eqi is None :\n eqi,eqj=i,j\n continue\n cruncher.set_seq1(ai)\n \n \n \n \n \n \n if cruncher.real_quick_ratio()>best_ratio and\\\n cruncher.quick_ratio()>best_ratio and\\\n cruncher.ratio()>best_ratio:\n best_ratio,best_i,best_j=cruncher.ratio(),i,j\n if best_ratio <cutoff:\n \n if eqi is None :\n \n yield from self._plain_replace(a,alo,ahi,b,blo,bhi)\n return\n \n best_i,best_j,best_ratio=eqi,eqj,1.0\n else :\n \n eqi=None\n \n \n \n \n \n yield from self._fancy_helper(a,alo,best_i,b,blo,best_j)\n \n \n aelt,belt=a[best_i],b[best_j]\n if eqi is None :\n \n atags=btags=\"\"\n cruncher.set_seqs(aelt,belt)\n for tag,ai1,ai2,bj1,bj2 in cruncher.get_opcodes():\n la,lb=ai2 -ai1,bj2 -bj1\n if tag =='replace':\n atags +='^'*la\n btags +='^'*lb\n elif tag =='delete':\n atags +='-'*la\n elif tag =='insert':\n btags +='+'*lb\n elif tag =='equal':\n atags +=' '*la\n btags +=' '*lb\n else :\n raise ValueError('unknown tag %r'%(tag,))\n yield from self._qformat(aelt,belt,atags,btags)\n else :\n \n yield ' '+aelt\n \n \n yield from self._fancy_helper(a,best_i+1,ahi,b,best_j+1,bhi)\n \n def _fancy_helper(self,a,alo,ahi,b,blo,bhi):\n g=[]\n if alo <ahi:\n if blo <bhi:\n g=self._fancy_replace(a,alo,ahi,b,blo,bhi)\n else :\n g=self._dump('-',a,alo,ahi)\n elif blo <bhi:\n g=self._dump('+',b,blo,bhi)\n \n yield from g\n \n def _qformat(self,aline,bline,atags,btags):\n ''\n\n\n\n\n\n\n\n\n\n\n\n\n\n \n \n \n common=min(_count_leading(aline,\"\\t\"),\n _count_leading(bline,\"\\t\"))\n common=min(common,_count_leading(atags[:common],\" \"))\n common=min(common,_count_leading(btags[:common],\" \"))\n atags=atags[common:].rstrip()\n btags=btags[common:].rstrip()\n \n yield \"- \"+aline\n if atags:\n yield \"? %s%s\\n\"%(\"\\t\"*common,atags)\n \n yield \"+ \"+bline\n if btags:\n yield \"? %s%s\\n\"%(\"\\t\"*common,btags)\n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \nimport re\n\ndef IS_LINE_JUNK(line,pat=re.compile(r\"\\s*(?:#\\s*)?$\").match):\n ''\n\n\n\n\n\n\n\n\n\n\n \n \n return pat(line)is not None\n \ndef IS_CHARACTER_JUNK(ch,ws=\" \\t\"):\n ''\n\n\n\n\n\n\n\n\n\n\n\n\n \n \n return ch in ws\n \n \n \n \n \n \ndef _format_range_unified(start,stop):\n ''\n \n beginning=start+1\n length=stop -start\n if length ==1:\n return '{}'.format(beginning)\n if not length:\n beginning -=1\n return '{},{}'.format(beginning,length)\n \ndef unified_diff(a,b,fromfile='',tofile='',fromfiledate='',\ntofiledate='',n=3,lineterm='\\n'):\n ''\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n \n \n _check_types(a,b,fromfile,tofile,fromfiledate,tofiledate,lineterm)\n started=False\n for group in SequenceMatcher(None ,a,b).get_grouped_opcodes(n):\n if not started:\n started=True\n fromdate='\\t{}'.format(fromfiledate)if fromfiledate else ''\n todate='\\t{}'.format(tofiledate)if tofiledate else ''\n yield '--- {}{}{}'.format(fromfile,fromdate,lineterm)\n yield '+++ {}{}{}'.format(tofile,todate,lineterm)\n \n first,last=group[0],group[-1]\n file1_range=_format_range_unified(first[1],last[2])\n file2_range=_format_range_unified(first[3],last[4])\n yield '@@ -{} +{} @@{}'.format(file1_range,file2_range,lineterm)\n \n for tag,i1,i2,j1,j2 in group:\n if tag =='equal':\n for line in a[i1:i2]:\n yield ' '+line\n continue\n if tag in {'replace','delete'}:\n for line in a[i1:i2]:\n yield '-'+line\n if tag in {'replace','insert'}:\n for line in b[j1:j2]:\n yield '+'+line\n \n \n \n \n \n \ndef _format_range_context(start,stop):\n ''\n \n beginning=start+1\n length=stop -start\n if not length:\n beginning -=1\n if length <=1:\n return '{}'.format(beginning)\n return '{},{}'.format(beginning,beginning+length -1)\n \n \ndef context_diff(a,b,fromfile='',tofile='',\nfromfiledate='',tofiledate='',n=3,lineterm='\\n'):\n ''\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n \n \n _check_types(a,b,fromfile,tofile,fromfiledate,tofiledate,lineterm)\n prefix=dict(insert='+ ',delete='- ',replace='! ',equal=' ')\n started=False\n for group in SequenceMatcher(None ,a,b).get_grouped_opcodes(n):\n if not started:\n started=True\n fromdate='\\t{}'.format(fromfiledate)if fromfiledate else ''\n todate='\\t{}'.format(tofiledate)if tofiledate else ''\n yield '*** {}{}{}'.format(fromfile,fromdate,lineterm)\n yield '--- {}{}{}'.format(tofile,todate,lineterm)\n \n first,last=group[0],group[-1]\n yield '***************'+lineterm\n \n file1_range=_format_range_context(first[1],last[2])\n yield '*** {} ****{}'.format(file1_range,lineterm)\n \n if any(tag in {'replace','delete'}for tag,_,_,_,_ in group):\n for tag,i1,i2,_,_ in group:\n if tag !='insert':\n for line in a[i1:i2]:\n yield prefix[tag]+line\n \n file2_range=_format_range_context(first[3],last[4])\n yield '--- {} ----{}'.format(file2_range,lineterm)\n \n if any(tag in {'replace','insert'}for tag,_,_,_,_ in group):\n for tag,_,_,j1,j2 in group:\n if tag !='delete':\n for line in b[j1:j2]:\n yield prefix[tag]+line\n \ndef _check_types(a,b,*args):\n\n\n\n\n\n\n if a and not isinstance(a[0],str):\n raise TypeError('lines to compare must be str, not %s (%r)'%\n (type(a[0]).__name__,a[0]))\n if b and not isinstance(b[0],str):\n raise TypeError('lines to compare must be str, not %s (%r)'%\n (type(b[0]).__name__,b[0]))\n for arg in args:\n if not isinstance(arg,str):\n raise TypeError('all arguments must be str, not: %r'%(arg,))\n \ndef diff_bytes(dfunc,a,b,fromfile=b'',tofile=b'',\nfromfiledate=b'',tofiledate=b'',n=3,lineterm=b'\\n'):\n ''\n\n\n\n\n\n\n\n \n def decode(s):\n try :\n return s.decode('ascii','surrogateescape')\n except AttributeError as err:\n msg=('all arguments must be bytes, not %s (%r)'%\n (type(s).__name__,s))\n raise TypeError(msg)from err\n a=list(map(decode,a))\n b=list(map(decode,b))\n fromfile=decode(fromfile)\n tofile=decode(tofile)\n fromfiledate=decode(fromfiledate)\n tofiledate=decode(tofiledate)\n lineterm=decode(lineterm)\n \n lines=dfunc(a,b,fromfile,tofile,fromfiledate,tofiledate,n,lineterm)\n for line in lines:\n yield line.encode('ascii','surrogateescape')\n \ndef ndiff(a,b,linejunk=None ,charjunk=IS_CHARACTER_JUNK):\n ''\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n \n return Differ(linejunk,charjunk).compare(a,b)\n \ndef _mdiff(fromlines,tolines,context=None ,linejunk=None ,\ncharjunk=IS_CHARACTER_JUNK):\n ''\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n \n import re\n \n \n change_re=re.compile(r'(\\++|\\-+|\\^+)')\n \n \n diff_lines_iterator=ndiff(fromlines,tolines,linejunk,charjunk)\n \n def _make_line(lines,format_key,side,num_lines=[0,0]):\n ''\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n \n num_lines[side]+=1\n \n \n if format_key is None :\n return (num_lines[side],lines.pop(0)[2:])\n \n if format_key =='?':\n text,markers=lines.pop(0),lines.pop(0)\n \n sub_info=[]\n def record_sub_info(match_object,sub_info=sub_info):\n sub_info.append([match_object.group(1)[0],match_object.span()])\n return match_object.group(1)\n change_re.sub(record_sub_info,markers)\n \n \n for key,(begin,end)in reversed(sub_info):\n text=text[0:begin]+'\\0'+key+text[begin:end]+'\\1'+text[end:]\n text=text[2:]\n \n else :\n text=lines.pop(0)[2:]\n \n \n if not text:\n text=' '\n \n text='\\0'+format_key+text+'\\1'\n \n \n \n return (num_lines[side],text)\n \n def _line_iterator():\n ''\n\n\n\n\n\n\n\n\n\n\n\n \n lines=[]\n num_blanks_pending,num_blanks_to_yield=0,0\n while True :\n \n \n \n while len(lines)<4:\n lines.append(next(diff_lines_iterator,'X'))\n s=''.join([line[0]for line in lines])\n if s.startswith('X'):\n \n \n \n num_blanks_to_yield=num_blanks_pending\n elif s.startswith('-?+?'):\n \n yield _make_line(lines,'?',0),_make_line(lines,'?',1),True\n continue\n elif s.startswith('--++'):\n \n \n num_blanks_pending -=1\n yield _make_line(lines,'-',0),None ,True\n continue\n elif s.startswith(('--?+','--+','- ')):\n \n \n from_line,to_line=_make_line(lines,'-',0),None\n num_blanks_to_yield,num_blanks_pending=num_blanks_pending -1,0\n elif s.startswith('-+?'):\n \n yield _make_line(lines,None ,0),_make_line(lines,'?',1),True\n continue\n elif s.startswith('-?+'):\n \n yield _make_line(lines,'?',0),_make_line(lines,None ,1),True\n continue\n elif s.startswith('-'):\n \n num_blanks_pending -=1\n yield _make_line(lines,'-',0),None ,True\n continue\n elif s.startswith('+--'):\n \n \n num_blanks_pending +=1\n yield None ,_make_line(lines,'+',1),True\n continue\n elif s.startswith(('+ ','+-')):\n \n from_line,to_line=None ,_make_line(lines,'+',1)\n num_blanks_to_yield,num_blanks_pending=num_blanks_pending+1,0\n elif s.startswith('+'):\n \n num_blanks_pending +=1\n yield None ,_make_line(lines,'+',1),True\n continue\n elif s.startswith(' '):\n \n yield _make_line(lines[:],None ,0),_make_line(lines,None ,1),False\n continue\n \n \n while (num_blanks_to_yield <0):\n num_blanks_to_yield +=1\n yield None ,('','\\n'),True\n while (num_blanks_to_yield >0):\n num_blanks_to_yield -=1\n yield ('','\\n'),None ,True\n if s.startswith('X'):\n return\n else :\n yield from_line,to_line,True\n \n def _line_pair_iterator():\n ''\n\n\n\n\n\n\n\n\n\n\n \n line_iterator=_line_iterator()\n fromlines,tolines=[],[]\n while True :\n \n while (len(fromlines)==0 or len(tolines)==0):\n try :\n from_line,to_line,found_diff=next(line_iterator)\n except StopIteration:\n return\n if from_line is not None :\n fromlines.append((from_line,found_diff))\n if to_line is not None :\n tolines.append((to_line,found_diff))\n \n from_line,fromDiff=fromlines.pop(0)\n to_line,to_diff=tolines.pop(0)\n yield (from_line,to_line,fromDiff or to_diff)\n \n \n \n line_pair_iterator=_line_pair_iterator()\n if context is None :\n yield from line_pair_iterator\n \n \n else :\n context +=1\n lines_to_write=0\n while True :\n \n \n \n index,contextLines=0,[None ]*(context)\n found_diff=False\n while (found_diff is False ):\n try :\n from_line,to_line,found_diff=next(line_pair_iterator)\n except StopIteration:\n return\n i=index %context\n contextLines[i]=(from_line,to_line,found_diff)\n index +=1\n \n \n if index >context:\n yield None ,None ,None\n lines_to_write=context\n else :\n lines_to_write=index\n index=0\n while (lines_to_write):\n i=index %context\n index +=1\n yield contextLines[i]\n lines_to_write -=1\n \n lines_to_write=context -1\n try :\n while (lines_to_write):\n from_line,to_line,found_diff=next(line_pair_iterator)\n \n if found_diff:\n lines_to_write=context -1\n else :\n lines_to_write -=1\n yield from_line,to_line,found_diff\n except StopIteration:\n \n return\n \n \n_file_template=\"\"\"\n<!DOCTYPE html PUBLIC \"-//W3C//DTD XHTML 1.0 Transitional//EN\"\n \"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd\">\n\n<html>\n\n<head>\n <meta http-equiv=\"Content-Type\"\n content=\"text/html; charset=%(charset)s\" />\n <title></title>\n <style type=\"text/css\">%(styles)s\n </style>\n</head>\n\n<body>\n %(table)s%(legend)s\n</body>\n\n</html>\"\"\"\n\n_styles=\"\"\"\n table.diff {font-family:Courier; border:medium;}\n .diff_header {background-color:#e0e0e0}\n td.diff_header {text-align:right}\n .diff_next {background-color:#c0c0c0}\n .diff_add {background-color:#aaffaa}\n .diff_chg {background-color:#ffff77}\n .diff_sub {background-color:#ffaaaa}\"\"\"\n\n_table_template=\"\"\"\n <table class=\"diff\" id=\"difflib_chg_%(prefix)s_top\"\n cellspacing=\"0\" cellpadding=\"0\" rules=\"groups\" >\n <colgroup></colgroup> <colgroup></colgroup> <colgroup></colgroup>\n <colgroup></colgroup> <colgroup></colgroup> <colgroup></colgroup>\n %(header_row)s\n <tbody>\n%(data_rows)s </tbody>\n </table>\"\"\"\n\n_legend=\"\"\"\n <table class=\"diff\" summary=\"Legends\">\n <tr> <th colspan=\"2\"> Legends </th> </tr>\n <tr> <td> <table border=\"\" summary=\"Colors\">\n <tr><th> Colors </th> </tr>\n <tr><td class=\"diff_add\">&nbsp;Added&nbsp;</td></tr>\n <tr><td class=\"diff_chg\">Changed</td> </tr>\n <tr><td class=\"diff_sub\">Deleted</td> </tr>\n </table></td>\n <td> <table border=\"\" summary=\"Links\">\n <tr><th colspan=\"2\"> Links </th> </tr>\n <tr><td>(f)irst change</td> </tr>\n <tr><td>(n)ext change</td> </tr>\n <tr><td>(t)op</td> </tr>\n </table></td> </tr>\n </table>\"\"\"\n\nclass HtmlDiff(object):\n ''\n\n\n\n\n\n\n\n\n\n\n\n\n \n \n _file_template=_file_template\n _styles=_styles\n _table_template=_table_template\n _legend=_legend\n _default_prefix=0\n \n def __init__(self,tabsize=8,wrapcolumn=None ,linejunk=None ,\n charjunk=IS_CHARACTER_JUNK):\n ''\n\n\n\n\n\n\n\n\n \n self._tabsize=tabsize\n self._wrapcolumn=wrapcolumn\n self._linejunk=linejunk\n self._charjunk=charjunk\n \n def make_file(self,fromlines,tolines,fromdesc='',todesc='',\n context=False ,numlines=5,*,charset='utf-8'):\n ''\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n \n \n return (self._file_template %dict(\n styles=self._styles,\n legend=self._legend,\n table=self.make_table(fromlines,tolines,fromdesc,todesc,\n context=context,numlines=numlines),\n charset=charset\n )).encode(charset,'xmlcharrefreplace').decode(charset)\n \n def _tab_newline_replace(self,fromlines,tolines):\n ''\n\n\n\n\n\n\n\n \n def expand_tabs(line):\n \n line=line.replace(' ','\\0')\n \n line=line.expandtabs(self._tabsize)\n \n \n line=line.replace(' ','\\t')\n return line.replace('\\0',' ').rstrip('\\n')\n fromlines=[expand_tabs(line)for line in fromlines]\n tolines=[expand_tabs(line)for line in tolines]\n return fromlines,tolines\n \n def _split_line(self,data_list,line_num,text):\n ''\n\n\n\n\n\n\n \n \n if not line_num:\n data_list.append((line_num,text))\n return\n \n \n size=len(text)\n max=self._wrapcolumn\n if (size <=max)or ((size -(text.count('\\0')*3))<=max):\n data_list.append((line_num,text))\n return\n \n \n \n i=0\n n=0\n mark=''\n while n <max and i <size:\n if text[i]=='\\0':\n i +=1\n mark=text[i]\n i +=1\n elif text[i]=='\\1':\n i +=1\n mark=''\n else :\n i +=1\n n +=1\n \n \n line1=text[:i]\n line2=text[i:]\n \n \n \n \n if mark:\n line1=line1+'\\1'\n line2='\\0'+mark+line2\n \n \n data_list.append((line_num,line1))\n \n \n self._split_line(data_list,'>',line2)\n \n def _line_wrapper(self,diffs):\n ''\n \n \n for fromdata,todata,flag in diffs:\n \n if flag is None :\n yield fromdata,todata,flag\n continue\n (fromline,fromtext),(toline,totext)=fromdata,todata\n \n \n fromlist,tolist=[],[]\n self._split_line(fromlist,fromline,fromtext)\n self._split_line(tolist,toline,totext)\n \n \n while fromlist or tolist:\n if fromlist:\n fromdata=fromlist.pop(0)\n else :\n fromdata=('',' ')\n if tolist:\n todata=tolist.pop(0)\n else :\n todata=('',' ')\n yield fromdata,todata,flag\n \n def _collect_lines(self,diffs):\n ''\n\n\n\n \n \n fromlist,tolist,flaglist=[],[],[]\n \n for fromdata,todata,flag in diffs:\n try :\n \n fromlist.append(self._format_line(0,flag,*fromdata))\n tolist.append(self._format_line(1,flag,*todata))\n except TypeError:\n \n fromlist.append(None )\n tolist.append(None )\n flaglist.append(flag)\n return fromlist,tolist,flaglist\n \n def _format_line(self,side,flag,linenum,text):\n ''\n\n\n\n\n\n \n try :\n linenum='%d'%linenum\n id=' id=\"%s%s\"'%(self._prefix[side],linenum)\n except TypeError:\n \n id=''\n \n text=text.replace(\"&\",\"&amp;\").replace(\">\",\"&gt;\").replace(\"<\",\"&lt;\")\n \n \n text=text.replace(' ','&nbsp;').rstrip()\n \n return '<td class=\"diff_header\"%s>%s</td><td nowrap=\"nowrap\">%s</td>'\\\n %(id,linenum,text)\n \n def _make_prefix(self):\n ''\n \n \n \n fromprefix=\"from%d_\"%HtmlDiff._default_prefix\n toprefix=\"to%d_\"%HtmlDiff._default_prefix\n HtmlDiff._default_prefix +=1\n \n self._prefix=[fromprefix,toprefix]\n \n def _convert_flags(self,fromlist,tolist,flaglist,context,numlines):\n ''\n \n \n toprefix=self._prefix[1]\n \n \n next_id=['']*len(flaglist)\n next_href=['']*len(flaglist)\n num_chg,in_change=0,False\n last=0\n for i,flag in enumerate(flaglist):\n if flag:\n if not in_change:\n in_change=True\n last=i\n \n \n \n i=max([0,i -numlines])\n next_id[i]=' id=\"difflib_chg_%s_%d\"'%(toprefix,num_chg)\n \n \n num_chg +=1\n next_href[last]='<a href=\"#difflib_chg_%s_%d\">n</a>'%(\n toprefix,num_chg)\n else :\n in_change=False\n \n if not flaglist:\n flaglist=[False ]\n next_id=['']\n next_href=['']\n last=0\n if context:\n fromlist=['<td></td><td>&nbsp;No Differences Found&nbsp;</td>']\n tolist=fromlist\n else :\n fromlist=tolist=['<td></td><td>&nbsp;Empty File&nbsp;</td>']\n \n if not flaglist[0]:\n next_href[0]='<a href=\"#difflib_chg_%s_0\">f</a>'%toprefix\n \n next_href[last]='<a href=\"#difflib_chg_%s_top\">t</a>'%(toprefix)\n \n return fromlist,tolist,flaglist,next_href,next_id\n \n def make_table(self,fromlines,tolines,fromdesc='',todesc='',context=False ,\n numlines=5):\n ''\n\n\n\n\n\n\n\n\n\n\n\n\n\n \n \n \n \n self._make_prefix()\n \n \n \n fromlines,tolines=self._tab_newline_replace(fromlines,tolines)\n \n \n if context:\n context_lines=numlines\n else :\n context_lines=None\n diffs=_mdiff(fromlines,tolines,context_lines,linejunk=self._linejunk,\n charjunk=self._charjunk)\n \n \n if self._wrapcolumn:\n diffs=self._line_wrapper(diffs)\n \n \n fromlist,tolist,flaglist=self._collect_lines(diffs)\n \n \n fromlist,tolist,flaglist,next_href,next_id=self._convert_flags(\n fromlist,tolist,flaglist,context,numlines)\n \n s=[]\n fmt=' <tr><td class=\"diff_next\"%s>%s</td>%s'+\\\n '<td class=\"diff_next\">%s</td>%s</tr>\\n'\n for i in range(len(flaglist)):\n if flaglist[i]is None :\n \n \n if i >0:\n s.append(' </tbody> \\n <tbody>\\n')\n else :\n s.append(fmt %(next_id[i],next_href[i],fromlist[i],\n next_href[i],tolist[i]))\n if fromdesc or todesc:\n header_row='<thead><tr>%s%s%s%s</tr></thead>'%(\n '<th class=\"diff_next\"><br /></th>',\n '<th colspan=\"2\" class=\"diff_header\">%s</th>'%fromdesc,\n '<th class=\"diff_next\"><br /></th>',\n '<th colspan=\"2\" class=\"diff_header\">%s</th>'%todesc)\n else :\n header_row=''\n \n table=self._table_template %dict(\n data_rows=''.join(s),\n header_row=header_row,\n prefix=self._prefix[1])\n \n return table.replace('\\0+','<span class=\"diff_add\">').\\\n replace('\\0-','<span class=\"diff_sub\">').\\\n replace('\\0^','<span class=\"diff_chg\">').\\\n replace('\\1','</span>').\\\n replace('\\t','&nbsp;')\n \ndel re\n\ndef restore(delta,which):\n ''\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n \n try :\n tag={1:\"- \",2:\"+ \"}[int(which)]\n except KeyError:\n raise ValueError('unknown delta choice (must be 1 or 2): %r'\n %which)from None\n prefixes=(\" \",tag)\n for line in delta:\n if line[:2]in prefixes:\n yield line[2:]\n \ndef _test():\n import doctest,difflib\n return doctest.testmod(difflib)\n \nif __name__ ==\"__main__\":\n _test()\n", ["collections", "difflib", "doctest", "heapq", "re"]], "posix": [".js", "/*\nThis module provides access to operating system functionality that is\nstandardized by the C Standard and the POSIX standard (a thinly\ndisguised Unix interface). Refer to the library manual and\ncorresponding Unix manual entries for more information on calls.\n*/\n\nvar $B = __BRYTHON__,\n _b_ = $B.builtins\n\nfunction _randint(a, b){\n return parseInt(Math.random() * (b - a + 1) + a)\n}\n\nvar stat_result = $B.make_class(\"stat_result\",\n function(){\n var res = {\n __class__: stat_result,\n st_atime: new Date(),\n st_uid: -1,\n st_gid: -1,\n st_ino: -1,\n st_mode: 0,\n st_size: 1\n };\n [\"mtime\", \"ctime\", \"atime_ns\", \"mtime_ns\", \"ctime_ns\"].\n forEach(function(item){\n res[\"st_\" + item] = res.st_atime\n });\n return res\n }\n)\n$B.set_func_names(stat_result, \"posix\")\n\nvar $module = {\n F_OK: 0,\n O_APPEND: 8,\n O_BINARY: 32768,\n O_CREAT: 256,\n O_EXCL: 1024,\n O_NOINHERIT: 128,\n O_RANDOM: 16,\n O_RDONLY: 0,\n O_RDWR: 2,\n O_SEQUENTIAL: 32,\n O_SHORT_LIVED: 4096,\n O_TEMPORARY: 64,\n O_TEXT: 16384,\n O_TRUNC: 512,\n O_WRONLY: 1,\n P_DETACH: 4,\n P_NOWAIT: 1,\n P_NOWAITO: 3,\n P_OVERLAY: 2,\n P_WAIT: 0,\n R_OK: 4,\n TMP_MAX: 32767,\n W_OK: 2,\n X_OK: 1,\n _have_functions: ['MS_WINDOWS'],\n environ: _b_.dict.$factory(\n [['PYTHONPATH', $B.brython_path],\n ['PYTHONUSERBASE', ' ']]),\n error: _b_.OSError,\n getcwd: function(){return $B.brython_path},\n getpid: function(){return 0},\n lstat: function(){return stat_result.$factory()},\n open: function(path, flags){return _b_.open(path, flags)},\n stat: function(){return stat_result.$factory()},\n urandom: function(n){\n var randbytes = []\n for(var i = 0; i < n; i++){\n randbytes.push(_randint(0, 255))\n }\n return _b_.bytes.$factory(randbytes)\n },\n WTERMSIG: function(){return 0},\n WNOHANG: function(){return _b_.tuple.$factory([0, 0])}\n};\n\n[\"WCOREDUMP\", \"WIFCONTINUED\", \"WIFSTOPPED\", \"WIFSIGNALED\", \"WIFEXITED\"].forEach(function(funcname){\n $module[funcname] = function(){return false}\n });\n\n[\"WEXITSTATUS\", \"WSTOPSIG\", \"WTERMSIG\"].\n forEach(function(funcname){\n $module[funcname] = function(){return _b_.None}\n });\n\n[\"_exit\", \"_getdiskusage\", \"_getfileinformation\", \"_getfinalpathname\",\n \"_getfullpathname\", \"_isdir\", \"abort\", \"access\", \"chdir\", \"chmod\",\n \"close\", \"closerange\", \"device_encoding\", \"dup\", \"dup2\",\n \"execv\", \"execve\", \"fsat\", \"fsync\", \"get_terminal_size\", \"getcwdb\",\n \"getlogin\", \"getppid\", \"isatty\", \"kill\", \"link\", \"listdir\", \"lseek\",\n \"mkdir\", \"pipe\", \"putenv\", \"read\", \"readlink\", \"remove\", \"rename\",\n \"replace\", \"rmdir\", \"spawnv\", \"spawnve\", \"startfile\", \"stat_float_times\",\n \"statvfs_result\", \"strerror\", \"symlink\", \"system\", \"terminal_size\",\n \"times\", \"times_result\", \"umask\", \"uname_result\", \"unlink\", \"utime\",\n \"waitpid\", \"write\"].forEach(function(funcname){\n $module[funcname] = function(){\n throw _b_.NotImplementedError.$factory(\"posix.\" + funcname +\n \" is not implemented\")\n }\n });\n"], "random": [".js", "// Javascript implementation of the random module\n// Based on Ian Bicking's implementation of the Mersenne twister\n\nvar $module = (function($B){\n\nvar _b_ = $B.builtins,\n i\n\nvar VERSION = 3\n\n// Code copied from https://github.com/ianb/whrandom/blob/master/mersenne.js\n// by Ian Bicking\n\n// this program is a JavaScript version of Mersenne Twister,\n// a straight conversion from the original program, mt19937ar.c,\n// translated by y. okada on july 17, 2006.\n// and modified a little at july 20, 2006, but there are not any substantial differences.\n// modularized by Ian Bicking, March 25, 2013 (found original version at http://www.math.sci.hiroshima-u.ac.jp/~m-mat/MT/VERSIONS/JAVASCRIPT/java-script.html)\n// in this program, procedure descriptions and comments of original source code were not removed.\n// lines commented with //c// were originally descriptions of c procedure. and a few following lines are appropriate JavaScript descriptions.\n// lines commented with /* and */ are original comments.\n// lines commented with // are additional comments in this JavaScript version.\n/*\n A C-program for MT19937, with initialization improved 2002/1/26.\n Coded by Takuji Nishimura and Makoto Matsumoto.\n\n Before using, initialize the state by using init_genrand(seed)\n or init_by_array(init_key, key_length).\n\n Copyright (C) 1997 - 2002, Makoto Matsumoto and Takuji Nishimura,\n All rights reserved.\n\n Redistribution and use in source and binary forms, with or without\n modification, are permitted provided that the following conditions\n are met:\n\n 1. Redistributions of source code must retain the above copyright\n notice, this list of conditions and the following disclaimer.\n\n 2. Redistributions in binary form must reproduce the above copyright\n notice, this list of conditions and the following disclaimer in the\n documentation and/or other materials provided with the distribution.\n\n 3. The names of its contributors may not be used to endorse or promote\n products derived from this software without specific prior written\n permission.\n\n THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS\n \"AS IS\" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT\n LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR\n A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR\n CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,\n EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,\n PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR\n PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF\n LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING\n NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS\n SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n\n\n Any feedback is very welcome.\n http://www.math.sci.hiroshima-u.ac.jp/~m-mat/MT/emt.html\n email: m-mat @ math.sci.hiroshima-u.ac.jp (remove space)\n*/\n\nfunction RandomStream(seed) {\n\n /*jshint bitwise:false */\n /* Period parameters */\n //c//#define N 624\n //c//#define M 397\n //c//#define MATRIX_A 0x9908b0dfUL /* constant vector a */\n //c//#define UPPER_MASK 0x80000000UL /* most significant w-r bits */\n //c//#define LOWER_MASK 0x7fffffffUL /* least significant r bits */\n var N = 624\n var M = 397\n var MATRIX_A = 0x9908b0df /* constant vector a */\n var UPPER_MASK = 0x80000000 /* most significant w-r bits */\n var LOWER_MASK = 0x7fffffff /* least significant r bits */\n //c//static unsigned long mt[N]; /* the array for the state vector */\n //c//static int mti=N+1; /* mti==N+1 means mt[N] is not initialized */\n var mt = new Array(N) /* the array for the state vector */\n var mti = N + 1 /* mti==N+1 means mt[N] is not initialized */\n\n function unsigned32(n1){\n // returns a 32-bits unsiged integer from an operand to which applied a\n // bit operator.\n return n1 < 0 ? (n1 ^ UPPER_MASK) + UPPER_MASK : n1\n }\n\n function subtraction32(n1, n2){\n // emulates lowerflow of a c 32-bits unsiged integer variable, instead of\n // the operator -. these both arguments must be non-negative integers\n // expressible using unsigned 32 bits.\n return n1 < n2 ? unsigned32((0x100000000 - (n2 - n1)) & 0xffffffff) :\n n1 - n2\n }\n\n function addition32(n1, n2){\n // emulates overflow of a c 32-bits unsiged integer variable, instead of\n // the operator +. these both arguments must be non-negative integers\n // expressible using unsigned 32 bits.\n return unsigned32((n1 + n2) & 0xffffffff)\n }\n\n function multiplication32(n1, n2){\n // emulates overflow of a c 32-bits unsiged integer variable, instead of the\n // operator *. these both arguments must be non-negative integers\n // expressible using unsigned 32 bits.\n var sum = 0\n for (var i = 0; i < 32; ++i){\n if((n1 >>> i) & 0x1){\n sum = addition32(sum, unsigned32(n2 << i))\n }\n }\n return sum\n }\n\n /* initializes mt[N] with a seed */\n //c//void init_genrand(unsigned long s)\n function init_genrand(s) {\n //c//mt[0]= s & 0xffffffff;\n mt[0] = unsigned32(s & 0xffffffff)\n for(mti = 1; mti < N; mti++){\n mt[mti] =\n //c//(1812433253 * (mt[mti-1] ^ (mt[mti-1] >> 30)) + mti);\n addition32(multiplication32(1812433253,\n unsigned32(mt[mti - 1] ^ (mt[mti - 1] >>> 30))), mti)\n /* See Knuth TAOCP Vol2. 3rd Ed. P.106 for multiplier. */\n /* In the previous versions, MSBs of the seed affect */\n /* only MSBs of the array mt[]. */\n /* 2002/01/09 modified by Makoto Matsumoto */\n //c//mt[mti] &= 0xffffffff;\n mt[mti] = unsigned32(mt[mti] & 0xffffffff);\n /* for >32 bit machines */\n }\n }\n\n /* initialize by an array with array-length */\n /* init_key is the array for initializing keys */\n /* key_length is its length */\n /* slight change for C++, 2004/2/26 */\n //c//void init_by_array(unsigned long init_key[], int key_length)\n function init_by_array(init_key, key_length) {\n //c//int i, j, k;\n var i, j, k\n init_genrand(19650218)\n i = 1\n j = 0\n k = (N > key_length ? N : key_length)\n for(; k; k--){\n //c//mt[i] = (mt[i] ^ ((mt[i-1] ^ (mt[i-1] >> 30)) * 1664525))\n //c// + init_key[j] + j; /* non linear */\n mt[i] = addition32(\n addition32(unsigned32(mt[i] ^\n multiplication32(unsigned32(mt[i - 1] ^ (mt[i - 1] >>> 30)),\n 1664525)),\n init_key[j]), j)\n mt[i] =\n //c//mt[i] &= 0xffffffff; /* for WORDSIZE > 32 machines */\n unsigned32(mt[i] & 0xffffffff)\n i++\n j++\n if(i >= N){mt[0] = mt[N - 1]; i = 1}\n if(j >= key_length){j = 0}\n }\n for(k = N - 1; k; k--){\n //c//mt[i] = (mt[i] ^ ((mt[i-1] ^ (mt[i-1] >> 30)) * 1566083941))\n //c//- i; /* non linear */\n mt[i] = subtraction32(\n unsigned32(\n (mt[i]) ^\n multiplication32(\n unsigned32(mt[i - 1] ^ (mt[i - 1] >>> 30)),\n 1566083941)),\n i\n )\n //c//mt[i] &= 0xffffffff; /* for WORDSIZE > 32 machines */\n mt[i] = unsigned32(mt[i] & 0xffffffff)\n i++\n if(i >= N){mt[0] = mt[N - 1]; i = 1}\n }\n mt[0] = 0x80000000; /* MSB is 1; assuring non-zero initial array */\n }\n\n /* generates a random number on [0,0xffffffff]-interval */\n //c//unsigned long genrand_int32(void)\n function genrand_int32() {\n //c//unsigned long y;\n //c//static unsigned long mag01[2]={0x0UL, MATRIX_A};\n var y;\n var mag01 = [0x0, MATRIX_A];\n /* mag01[x] = x * MATRIX_A for x=0,1 */\n\n if(mti >= N){ /* generate N words at one time */\n //c//int kk;\n var kk\n\n if(mti == N + 1){ /* if init_genrand() has not been called, */\n init_genrand(Date.now()) /* a default initial seed is used */\n }\n\n for(kk = 0; kk < N - M; kk++){\n //c//y = (mt[kk]&UPPER_MASK)|(mt[kk+1]&LOWER_MASK);\n //c//mt[kk] = mt[kk+M] ^ (y >> 1) ^ mag01[y & 0x1];\n y = unsigned32((mt[kk]&UPPER_MASK) | (mt[kk + 1]&LOWER_MASK))\n mt[kk] = unsigned32(mt[kk + M] ^ (y >>> 1) ^ mag01[y & 0x1])\n }\n for(;kk < N - 1; kk++){\n //c//y = (mt[kk]&UPPER_MASK)|(mt[kk+1]&LOWER_MASK);\n //c//mt[kk] = mt[kk+(M-N)] ^ (y >> 1) ^ mag01[y & 0x1];\n y = unsigned32((mt[kk]&UPPER_MASK) | (mt[kk + 1]&LOWER_MASK))\n mt[kk] = unsigned32(mt[kk + (M - N)] ^ (y >>> 1) ^ mag01[y & 0x1])\n }\n //c//y = (mt[N-1]&UPPER_MASK)|(mt[0]&LOWER_MASK);\n //c//mt[N-1] = mt[M-1] ^ (y >> 1) ^ mag01[y & 0x1];\n y = unsigned32((mt[N - 1] & UPPER_MASK) | (mt[0] & LOWER_MASK))\n mt[N - 1] = unsigned32(mt[M - 1] ^ (y >>> 1) ^ mag01[y & 0x1])\n mti = 0\n }\n\n y = mt[mti++]\n\n /* Tempering */\n //c//y ^= (y >> 11);\n //c//y ^= (y << 7) & 0x9d2c5680;\n //c//y ^= (y << 15) & 0xefc60000;\n //c//y ^= (y >> 18);\n y = unsigned32(y ^ (y >>> 11))\n y = unsigned32(y ^ ((y << 7) & 0x9d2c5680))\n y = unsigned32(y ^ ((y << 15) & 0xefc60000))\n y = unsigned32(y ^ (y >>> 18))\n\n return y\n }\n\n /* generates a random number on [0,0x7fffffff]-interval */\n //c//long genrand_int31(void)\n function genrand_int31(){\n //c//return (genrand_int32()>>1);\n return (genrand_int32()>>>1)\n }\n\n /* generates a random number on [0,1]-real-interval */\n //c//double genrand_real1(void)\n function genrand_real1(){\n return genrand_int32()*(1.0/4294967295.0)\n /* divided by 2^32-1 */\n }\n\n /* generates a random number on [0,1)-real-interval */\n //c//double genrand_real2(void)\n function genrand_real2(){\n return genrand_int32() * (1.0 / 4294967296.0)\n /* divided by 2^32 */\n }\n\n /* generates a random number on (0,1)-real-interval */\n //c//double genrand_real3(void)\n function genrand_real3() {\n return ((genrand_int32()) + 0.5) * (1.0 / 4294967296.0)\n /* divided by 2^32 */\n }\n\n /* generates a random number on [0,1) with 53-bit resolution*/\n //c//double genrand_res53(void)\n function genrand_res53() {\n //c//unsigned long a=genrand_int32()>>5, b=genrand_int32()>>6;\n var a = genrand_int32() >>> 5,\n b = genrand_int32() >>> 6\n return (a * 67108864.0 + b) * (1.0 / 9007199254740992.0)\n }\n /* These real versions are due to Isaku Wada, 2002/01/09 added */\n\n var random = genrand_res53\n\n random.seed = function(seed){\n if(! seed){seed = Date.now()}\n if(typeof seed != \"number\"){seed = parseInt(seed, 10)}\n if((seed !== 0 && ! seed) || isNaN(seed)){throw \"Bad seed\"}\n init_genrand(seed)\n }\n\n random.seed(seed)\n\n random.int31 = genrand_int31\n random.real1 = genrand_real1\n random.real2 = genrand_real2\n random.real3 = genrand_real3\n random.res53 = genrand_res53\n\n // Added for compatibility with Python\n random.getstate = function(){return [VERSION, mt, mti]}\n\n random.setstate = function(state){\n mt = state[1]\n mti = state[2]\n }\n\n return random\n\n}\n\n// magic constants\n\nvar NV_MAGICCONST = 4 * Math.exp(-0.5)/Math.sqrt(2),\n gauss_next = null,\n NV_MAGICCONST = 1.71552776992141,\n TWOPI = 6.28318530718,\n LOG4 = 1.38629436111989,\n SG_MAGICCONST = 2.50407739677627,\n VERSION = VERSION\n\nvar Random = $B.make_class(\"Random\",\n function(){\n return {\n __class__: Random,\n _random: RandomStream()\n }\n }\n)\n\nRandom._randbelow = function(self, x){\n return Math.floor(x * self._random())\n}\n\nRandom._urandom = function(self, n){\n /*\n urandom(n) -> str\n Return n random bytes suitable for cryptographic use.\n */\n\n var randbytes = []\n for(i = 0; i < n; i++){randbytes.push(parseInt(self._random() * 256))}\n return _b_.bytes.$factory(randbytes)\n}\n\nRandom.betavariate = function(){\n /* Beta distribution.\n\n Conditions on the parameters are alpha > 0 and beta > 0.\n Returned values range between 0 and 1.\n\n\n # This version due to Janne Sinkkonen, and matches all the std\n # texts (e.g., Knuth Vol 2 Ed 3 pg 134 \"the beta distribution\").\n */\n\n var $ = $B.args('betavariate', 3, {self: null, alpha:null, beta:null},\n ['self', 'alpha', 'beta'], arguments, {}, null, null),\n self = $.self,\n alpha = $.alpha,\n beta = $.beta\n\n var y = Random.gammavariate(self, alpha, 1)\n if(y == 0){return _b_.float.$factory(0)}\n else{return y / (y + Random.gammavariate(self, beta, 1))}\n}\n\nRandom.choice = function(){\n var $ = $B.args(\"choice\", 2,\n {self: null, seq:null},[\"self\", \"seq\"],arguments, {}, null, null),\n self = $.self,\n seq = $.seq\n var len, rank\n if(Array.isArray(seq)){len = seq.length}\n else{len = _b_.getattr(seq,\"__len__\")()}\n if(len == 0){\n throw _b_.IndexError.$factory(\"Cannot choose from an empty sequence\")\n }\n rank = parseInt(self._random() * len)\n if(Array.isArray(seq)){return seq[rank]}\n else{return _b_.getattr(seq, \"__getitem__\")(rank)}\n}\n\nRandom.choices = function(){\n var $ = $B.args(\"choices\", 3,\n {self: null,population:null, weights:null, cum_weights:null, k:null},\n [\"self\", \"population\", \"weights\", \"cum_weights\", \"k\"], arguments,\n {weights: _b_.None, cum_weights: _b_.None, k: 1}, \"*\", null),\n self = $.self,\n population = $.population,\n weights = $.weights,\n cum_weights = $.cum_weights,\n k = $.k\n\n if(population.length == 0){\n throw _b_.ValueError.$factory(\"population is empty\")\n }\n if(weights === _b_.None){\n weights = []\n population.forEach(function(){\n weights.push(1)\n })\n }else if(cum_weights !== _b_.None){\n throw _b_.TypeError.$factory(\"Cannot specify both weights and \" +\n \"cumulative weights\")\n }else{\n if(weights.length != population.length){\n throw _b_.ValueError.$factory('The number of weights does not ' +\n 'match the population')\n }\n }\n if(cum_weights === _b_.None){\n var cum_weights = [weights[0]]\n weights.forEach(function(weight, rank){\n if(rank > 0){\n cum_weights.push(cum_weights[rank - 1] + weight)\n }\n })\n }else if(cum_weights.length != population.length){\n throw _b_.ValueError.$factory('The number of weights does not ' +\n 'match the population')\n }\n\n var result = []\n for(var i = 0; i < k; i++){\n var rand = self._random() * cum_weights[cum_weights.length - 1]\n for(var rank = 0, len = population.length; rank < len; rank++){\n if(cum_weights[rank] > rand){\n result.push(population[rank])\n break\n }\n }\n }\n return result\n}\n\nRandom.expovariate = function(self, lambd){\n /*\n Exponential distribution.\n\n lambd is 1.0 divided by the desired mean. It should be\n nonzero. (The parameter would be called \"lambda\", but that is\n a reserved word in Python.) Returned values range from 0 to\n positive infinity if lambd is positive, and from negative\n infinity to 0 if lambd is negative.\n\n */\n // lambd: rate lambd = 1/mean\n // ('lambda' is a Python reserved word)\n\n // we use 1-random() instead of random() to preclude the\n // possibility of taking the log of zero.\n return -Math.log(1.0 - self._random()) / lambd\n}\n\nRandom.gammavariate = function(self, alpha, beta){\n /* Gamma distribution. Not the gamma function!\n\n Conditions on the parameters are alpha > 0 and beta > 0.\n\n The probability distribution function is:\n\n x ** (alpha - 1) * math.exp(-x / beta)\n pdf(x) = --------------------------------------\n math.gamma(alpha) * beta ** alpha\n\n */\n\n // alpha > 0, beta > 0, mean is alpha*beta, variance is alpha*beta**2\n\n // Warning: a few older sources define the gamma distribution in terms\n // of alpha > -1.0\n\n var $ = $B.args('gammavariate', 3,\n {self: null, alpha:null, beta:null},\n ['self', 'alpha', 'beta'],\n arguments, {}, null, null),\n self = $.self,\n alpha = $.alpha,\n beta = $.beta,\n LOG4 = Math.log(4),\n SG_MAGICCONST = 1.0 + Math.log(4.5)\n\n if(alpha <= 0.0 || beta <= 0.0){\n throw _b_.ValueError.$factory('gammavariate: alpha and beta must be > 0.0')\n }\n\n if(alpha > 1.0){\n\n // Uses R.C.H. Cheng, \"The generation of Gamma\n // variables with non-integral shape parameters\",\n // Applied Statistics, (1977), 26, No. 1, p71-74\n\n var ainv = Math.sqrt(2.0 * alpha - 1.0),\n bbb = alpha - LOG4,\n ccc = alpha + ainv\n\n while(true){\n var u1 = self._random()\n if(!((1e-7 < u1) && (u1 < .9999999))){\n continue\n }\n var u2 = 1.0 - self._random(),\n v = Math.log(u1 / (1.0 - u1)) / ainv,\n x = alpha * Math.exp(v),\n z = u1 * u1 * u2,\n r = bbb + ccc * v - x\n if((r + SG_MAGICCONST - 4.5 * z >= 0.0) || r >= Math.log(z)){\n return x * beta\n }\n }\n }else if(alpha == 1.0){\n // expovariate(1)\n var u = self._random()\n while(u <= 1e-7){u = self._random()}\n return -Math.log(u) * beta\n }else{\n // alpha is between 0 and 1 (exclusive)\n\n // Uses ALGORITHM GS of Statistical Computing - Kennedy & Gentle\n\n while(true){\n var u = self._random(),\n b = (Math.E + alpha)/Math.E,\n p = b*u,\n x\n if(p <= 1.0){x = Math.pow(p, (1.0/alpha))}\n else{x = -Math.log((b-p)/alpha)}\n var u1 = self._random()\n if(p > 1.0){\n if(u1 <= Math.pow(x, alpha - 1.0)){\n break\n }\n }else if(u1 <= Math.exp(-x)){\n break\n }\n }\n return x * beta\n }\n}\n\nRandom.gauss = function(){\n\n /* Gaussian distribution.\n\n mu is the mean, and sigma is the standard deviation. This is\n slightly faster than the normalvariate() function.\n\n Not thread-safe without a lock around calls.\n\n # When x and y are two variables from [0, 1), uniformly\n # distributed, then\n #\n # cos(2*pi*x)*sqrt(-2*log(1-y))\n # sin(2*pi*x)*sqrt(-2*log(1-y))\n #\n # are two *independent* variables with normal distribution\n # (mu = 0, sigma = 1).\n # (Lambert Meertens)\n # (corrected version; bug discovered by Mike Miller, fixed by LM)\n\n # Multithreading note: When two threads call this function\n # simultaneously, it is possible that they will receive the\n # same return value. The window is very small though. To\n # avoid this, you have to use a lock around all calls. (I\n # didn't want to slow this down in the serial case by using a\n # lock here.)\n */\n\n var $ = $B.args('gauss', 3, {self: null, mu:null, sigma:null},\n ['self', 'mu', 'sigma'], arguments, {}, null, null),\n self = $.self,\n mu = $.mu,\n sigma = $.sigma\n\n var z = gauss_next\n gauss_next = null\n if(z === null){\n var x2pi = self._random() * Math.PI * 2,\n g2rad = Math.sqrt(-2.0 * Math.log(1.0 - self._random())),\n z = Math.cos(x2pi) * g2rad\n gauss_next = Math.sin(x2pi) * g2rad\n }\n return mu + z*sigma\n}\n\nRandom.getrandbits = function(){\n var $ = $B.args(\"getrandbits\", 2,\n {self: null, k:null},[\"self\", \"k\"],arguments, {}, null, null),\n self = $.self,\n k = $B.$GetInt($.k)\n // getrandbits(k) -> x. Generates a long int with k random bits.\n if(k <= 0){\n throw _b_.ValueError.$factory('number of bits must be greater than zero')\n }\n if(k != _b_.int.$factory(k)){\n throw _b_.TypeError.$factory('number of bits should be an integer')\n }\n var numbytes = (k + 7), // bits / 8 and rounded up\n x = _b_.int.from_bytes(Random._urandom(self, numbytes), 'big')\n return _b_.getattr(x, '__rshift__')(\n _b_.getattr(numbytes*8,'__sub__')(k))\n}\n\nRandom.getstate = function(){\n // Return internal state; can be passed to setstate() later.\n var $ = $B.args('getstate', 1, {self: null},\n [\"self\"], arguments, {}, null, null)\n return $.self._random.getstate()\n}\n\nRandom.lognormvariate = function(){\n /*\n Log normal distribution.\n\n If you take the natural logarithm of this distribution, you'll get a\n normal distribution with mean mu and standard deviation sigma.\n mu can have any value, and sigma must be greater than zero.\n\n */\n return Math.exp(Random.normalvariate.apply(null, arguments))\n}\n\nRandom.normalvariate = function(){\n /*\n Normal distribution.\n\n mu is the mean, and sigma is the standard deviation.\n\n */\n\n // mu = mean, sigma = standard deviation\n\n // Uses Kinderman and Monahan method. Reference: Kinderman,\n // A.J. and Monahan, J.F., \"Computer generation of random\n // variables using the ratio of uniform deviates\", ACM Trans\n // Math Software, 3, (1977), pp257-260.\n\n var $ = $B.args(\"normalvariate\", 3,\n {self: null, mu:null, sigma:null}, [\"self\", \"mu\", \"sigma\"],\n arguments, {}, null, null),\n self = $.self,\n mu = $.mu,\n sigma = $.sigma\n\n while(true){\n var u1 = self._random(),\n u2 = 1.0 - self._random(),\n z = NV_MAGICCONST * (u1 - 0.5) / u2,\n zz = z * z / 4.0\n if(zz <= -Math.log(u2)){break}\n }\n return mu + z * sigma\n}\n\nRandom.paretovariate = function(){\n /* Pareto distribution. alpha is the shape parameter.*/\n // Jain, pg. 495\n\n var $ = $B.args(\"paretovariate\", 2, {self: null, alpha:null},\n [\"self\", \"alpha\"], arguments, {}, null, null)\n\n var u = 1 - $.self._random()\n return 1 / Math.pow(u, 1 / $.alpha)\n}\n\nRandom.randint = function(self, a, b){\n var $ = $B.args('randint', 3,\n {self: null, a:null, b:null},\n ['self', 'a', 'b'],\n arguments, {}, null, null)\n if(! _b_.isinstance($.b, _b_.int)){\n throw _b_.ValueError.$factory(\"non-integer arg 1 for randrange()\")\n }\n return Random.randrange($.self, $.a, $.b + 1)\n}\n\nRandom.random = function(self){\n var res = self._random()\n if(! Number.isInteger(res)){return new Number(res)}\n return res\n}\n\nRandom.randrange = function(){\n var $ = $B.args('randrange', 4,\n {self: null, x:null, stop:null, step:null},\n ['self', 'x', 'stop', 'step'],\n arguments, {stop:null, step:null}, null, null),\n self = $.self,\n _random = self._random\n //console.log(\"randrange\", $)\n for(var i = 1, len = arguments.length; i < len; i++){\n if(! _b_.isinstance(arguments[i], _b_.int)){\n throw _b_.ValueError.$factory(\"non-integer arg \" + i +\n \" for randrange()\")\n }\n }\n if($.stop === null){\n var start = 0, stop = $.x, step = 1\n }else{\n var start = $.x, stop = $.stop,\n step = $.step === null ? 1 : $.step\n if(step == 0){throw _b_.ValueError.$factory('step cannot be 0')}\n }\n if((step > 0 && start > stop) || (step < 0 && start < stop)){\n throw _b_.ValueError.$factory(\"empty range for randrange() (\" +\n start + \", \" + stop + \", \" + step + \")\")\n }\n if(typeof start == 'number' && typeof stop == 'number' &&\n typeof step == 'number'){\n return start + step * Math.floor(_random() *\n Math.ceil((stop - start) / step))\n }else{\n var d = _b_.getattr(stop, '__sub__')(start)\n d = _b_.getattr(d, '__floordiv__')(step)\n // Force d to be a LongInt\n d = $B.long_int.$factory(d)\n // d is a long integer with n digits ; to choose a random number\n // between 0 and d the most simple is to take a random digit\n // at each position, except the first one\n var s = d.value,\n _len = s.length,\n res = Math.floor(_random() * (parseInt(s.charAt(0)) +\n (_len == 1 ? 0 : 1))) + ''\n var same_start = res.charAt(0) == s.charAt(0)\n for(var i = 1; i < _len; i++){\n if(same_start){\n // If it's the last digit, don't allow stop as valid\n if(i == _len - 1){\n res += Math.floor(_random() * parseInt(s.charAt(i))) + ''\n }else{\n res += Math.floor(_random() *\n (parseInt(s.charAt(i)) + 1)) + ''\n same_start = res.charAt(i) == s.charAt(i)\n }\n }else{\n res += Math.floor(_random() * 10) + ''\n }\n }\n var offset = {__class__: $B.long_int, value: res,\n pos: true}\n d = _b_.getattr(step, '__mul__')(offset)\n d = _b_.getattr(start, '__add__')(d)\n return _b_.int.$factory(d)\n }\n}\n\nRandom.sample = function(){\n /*\n Chooses k unique random elements from a population sequence or set.\n\n Returns a new list containing elements from the population while\n leaving the original population unchanged. The resulting list is\n in selection order so that all sub-slices will also be valid random\n samples. This allows raffle winners (the sample) to be partitioned\n into grand prize and second place winners (the subslices).\n\n Members of the population need not be hashable or unique. If the\n population contains repeats, then each occurrence is a possible\n selection in the sample.\n\n To choose a sample in a range of integers, use range as an argument.\n This is especially fast and space efficient for sampling from a\n large population: sample(range(10000000), 60)\n\n # Sampling without replacement entails tracking either potential\n # selections (the pool) in a list or previous selections in a set.\n\n # When the number of selections is small compared to the\n # population, then tracking selections is efficient, requiring\n # only a small set and an occasional reselection. For\n # a larger number of selections, the pool tracking method is\n # preferred since the list takes less space than the\n # set and it doesn't suffer from frequent reselections.'\n\n */\n var $ = $B.args('sample', 3, {self: null, population: null,k: null},\n ['self', 'population','k'], arguments, {}, null, null),\n self = $.self,\n population = $.population,\n k = $.k\n\n if(!_b_.hasattr(population, '__len__')){\n throw _b_.TypeError.$factory(\"Population must be a sequence or set. \" +\n \"For dicts, use list(d).\")\n }\n var n = _b_.getattr(population, '__len__')()\n\n if(k < 0 || k > n){\n throw _b_.ValueError.$factory(\"Sample larger than population\")\n }\n var result = [],\n setsize = 21 // size of a small set minus size of an empty list\n if(k > 5){\n setsize += Math.pow(4, Math.ceil(Math.log(k * 3, 4))) // table size for big sets\n }\n if(n <= setsize){\n // An n-length list is smaller than a k-length set\n if(Array.isArray(population)){\n var pool = population.slice()\n }else{var pool = _b_.list.$factory(population)}\n for(var i = 0; i < k; i++){ //invariant: non-selected at [0,n-i)\n var j = Random._randbelow(self, n - i)\n result[i] = pool[j]\n pool[j] = pool[n - i - 1] // move non-selected item into vacancy\n }\n }else{\n selected = {}\n for(var i = 0; i < k; i++){\n var j = Random._randbelow(self, n)\n while(selected[j] !== undefined){\n j = Random._randbelow(self, n)\n }\n selected[j] = true\n result[i] = Array.isArray(population) ? population[j] :\n _b_.getattr(population, '__getitem__')(j)\n }\n }\n return result\n}\n\nRandom.seed = function(){\n /*\n Initialize internal state from hashable object.\n\n None or no argument seeds from current time or from an operating\n system specific randomness source if available.\n\n If *a* is an int, all bits are used.\n */\n var $ = $B.args('seed', 3, {self: null, a: null, version: null},\n ['self', 'a', 'version'],\n arguments, {a: new Date(), version: 2}, null, null),\n self = $.self,\n a = $.a,\n version = $.version\n\n if(version == 1){a = _b_.hash(a)}\n else if(version == 2){\n if(_b_.isinstance(a, _b_.str)){\n a = _b_.int.from_bytes(_b_.bytes.$factory(a, 'utf-8'), 'big')\n }else if(_b_.isinstance(a, [_b_.bytes, _b_.bytearray])){\n a = _b_.int.from_bytes(a, 'big')\n }else if(!_b_.isinstance(a, _b_.int)){\n throw _b_.TypeError.$factory('wrong argument')\n }\n if(a.__class__ === $B.long_int){\n // In this implementation, seed() only accepts safe integers\n // Generate a random one from the underlying string value,\n // using an arbitrary seed (99) to always return the same\n // integer\n var numbers = a.value,\n res = '',\n pos\n self._random.seed(99)\n for(var i = 0; i < 17; i++){\n pos = parseInt(self._random() * numbers.length)\n res += numbers.charAt(pos)\n }\n a = parseInt(res)\n }\n }else{\n throw ValueError.$factory('version can only be 1 or 2')\n }\n\n self._random.seed(a)\n gauss_next = null\n}\n\nRandom.setstate = function(state){\n // Restore internal state from object returned by getstate().\n var $ = $B.args('setstate', 2, {self: null, state:null}, ['self', 'state'],\n arguments, {}, null, null),\n self = $.self\n var state = self._random.getstate()\n if(! Array.isArray($.state)){\n throw _b_.TypeError.$factory('state must be a list, not ' +\n $B.class_name($.state))\n }\n if($.state.length < state.length){\n throw _b_.ValueError.$factory(\"need more than \" + $.state.length +\n \" values to unpack\")\n }else if($.state.length > state.length){\n throw _b_.ValueError.$factory(\"too many values to unpack (expected \" +\n state.length + \")\")\n }\n if($.state[0] != 3){\n throw _b_.ValueError.$factory(\"ValueError: state with version \" +\n $.state[0] + \" passed to Random.setstate() of version 3\")\n }\n var second = _b_.list.$factory($.state[1])\n if(second.length !== state[1].length){\n throw _b_.ValueError.$factory('state vector is the wrong size')\n }\n for(var i = 0; i < second.length; i++){\n if(typeof second[i] != 'number'){\n throw _b_.ValueError.$factory('state vector items must be integers')\n }\n }\n self._random.setstate($.state)\n}\n\nRandom.shuffle = function(x, random){\n /*\n x, random = random.random -> shuffle list x in place; return None.\n\n Optional arg random is a 0-argument function returning a random\n float in [0.0, 1.0); by default, the standard random.random.\n */\n\n var $ = $B.args('shuffle', 3, {self: null, x: null, random: null},\n ['self', 'x','random'],\n arguments, {random: null}, null, null),\n self = $.self,\n x = $.x,\n random = $.random\n\n if(random === null){random = self._random}\n\n if(Array.isArray(x)){\n for(var i = x.length - 1; i >= 0;i--){\n var j = Math.floor(random() * (i + 1)),\n temp = x[j]\n x[j] = x[i]\n x[i] = temp\n }\n }else{\n var len = _b_.getattr(x, '__len__')(), temp,\n x_get = _b_.getattr(x, '__getitem__'),\n x_set = _b_.getattr(x, '__setitem__')\n\n for(i = len - 1; i >= 0; i--){\n var j = Math.floor(random() * (i + 1)),\n temp = x_get(j)\n x_set(j, x_get(i))\n x_set(i, temp)\n }\n }\n}\n\nRandom.triangular = function(){\n /*\n Triangular distribution.\n\n Continuous distribution bounded by given lower and upper limits,\n and having a given mode value in-between.\n\n http://en.wikipedia.org/wiki/Triangular_distribution\n */\n var $ = $B.args('triangular', 4,\n {self: null, low: null, high: null, mode: null},\n ['self', 'low', 'high', 'mode'],\n arguments, {low: 0, high: 1, mode: null}, null, null),\n low = $.low,\n high = $.high,\n mode = $.mode\n\n var u = $.self._random(),\n c = mode === null ? 0.5 : (mode - low) / (high - low)\n if(u > c){\n u = 1 - u\n c = 1 - c\n var temp = low\n low = high\n high = temp\n }\n return low + (high - low) * Math.pow(u * c, 0.5)\n}\n\nRandom.uniform = function(){\n var $ = $B.args('uniform', 3, {self: null, a: null, b: null},\n ['self', 'a', 'b'], arguments, {}, null, null),\n a = $B.$GetInt($.a),\n b = $B.$GetInt($.b)\n\n return a + (b - a) * $.self._random()\n}\n\nRandom.vonmisesvariate = function(){\n /* Circular data distribution.\n\n mu is the mean angle, expressed in radians between 0 and 2*pi, and\n kappa is the concentration parameter, which must be greater than or\n equal to zero. If kappa is equal to zero, this distribution reduces\n to a uniform random angle over the range 0 to 2*pi.\n\n */\n // mu: mean angle (in radians between 0 and 2*pi)\n // kappa: concentration parameter kappa (>= 0)\n // if kappa = 0 generate uniform random angle\n\n // Based upon an algorithm published in: Fisher, N.I.,\n // \"Statistical Analysis of Circular Data\", Cambridge\n // University Press, 1993.\n\n // Thanks to Magnus Kessler for a correction to the\n // implementation of step 4.\n\n var $ = $B.args('vonmisesvariate', 3,\n {self: null, mu: null, kappa:null}, ['self', 'mu', 'kappa'],\n arguments, {}, null, null),\n self = $.self,\n mu = $.mu,\n kappa = $.kappa,\n TWOPI = 2*Math.PI\n\n if(kappa <= 1e-6){return TWOPI * self._random()}\n\n var s = 0.5 / kappa,\n r = s + Math.sqrt(1.0 + s * s)\n\n while(true){\n var u1 = self._random(),\n z = Math.cos(Math.PI * u1),\n d = z / (r + z),\n u2 = self._random()\n if((u2 < 1.0 - d * d) ||\n (u2 <= (1.0 - d) * Math.exp(d))){\n break\n }\n }\n var q = 1.0 / r,\n f = (q + z) / (1.0 + q * z),\n u3 = self._random()\n if(u3 > 0.5){var theta = (mu + Math.acos(f)) % TWOPI}\n else{var theta = (mu - Math.acos(f)) % TWOPI}\n return theta\n}\n\nRandom.weibullvariate = function(){\n /*Weibull distribution.\n\n alpha is the scale parameter and beta is the shape parameter.\n\n */\n // Jain, pg. 499; bug fix courtesy Bill Arms\n var $ = $B.args(\"weibullvariate\", 3,\n {self: null, alpha: null, beta: null},\n [\"self\", \"alpha\", \"beta\"], arguments, {}, null, null)\n\n var u = 1 - $.self._random()\n return $.alpha * Math.pow(-Math.log(u), 1 / $.beta)\n}\n\n$B.set_func_names(Random, \"random\")\n\nvar $module = Random.$factory()\nfor(var attr in Random){\n $module[attr] = (function(x){\n return function(){return Random[x]($module, ...arguments)}\n })(attr)\n $module[attr].$infos = Random[attr].$infos\n}\n\n$module.Random = Random\n\nvar SystemRandom = $B.make_class(\"SystemRandom\",\n function(){\n return {__class__: SystemRandom}\n }\n)\nSystemRandom.__getattribute__ = function(){\n throw $B.builtins.NotImplementedError.$factory()\n}\n\n$module.SystemRandom = SystemRandom\n\nreturn $module\n\n})(__BRYTHON__)\n\n"], "gc": [".py", "''\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\nDEBUG_COLLECTABLE=2\n\nDEBUG_LEAK=38\n\nDEBUG_SAVEALL=32\n\nDEBUG_STATS=1\n\nDEBUG_UNCOLLECTABLE=4\n\nclass __loader__:\n pass\n \ncallbacks=[]\n\ndef collect(*args,**kw):\n ''\n\n\n\n\n\n \n pass\n \ndef disable(*args,**kw):\n ''\n\n \n pass\n \ndef enable(*args,**kw):\n ''\n\n \n pass\n \ngarbage=[]\n\ndef get_count(*args,**kw):\n ''\n\n \n pass\n \ndef get_debug(*args,**kw):\n ''\n\n \n pass\n \ndef get_objects(*args,**kw):\n ''\n\n\n \n pass\n \ndef get_referents(*args,**kw):\n ''\n pass\n \ndef get_referrers(*args,**kw):\n ''\n pass\n \ndef get_threshold(*args,**kw):\n ''\n\n \n pass\n \ndef is_tracked(*args,**kw):\n ''\n\n\n \n pass\n \ndef isenabled(*args,**kw):\n ''\n\n \n pass\n \ndef set_debug(*args,**kw):\n ''\n\n\n\n\n\n\n\n\n\n\n \n pass\n \ndef set_threshold(*args,**kw):\n ''\n\n\n \n pass\n", []], "copy": [".py", "''\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\nimport types\nimport weakref\nfrom copyreg import dispatch_table\n\nclass Error(Exception):\n pass\nerror=Error\n\ntry :\n from org.python.core import PyStringMap\nexcept ImportError:\n PyStringMap=None\n \n__all__=[\"Error\",\"copy\",\"deepcopy\"]\n\ndef copy(x):\n ''\n\n\n \n \n cls=type(x)\n \n copier=_copy_dispatch.get(cls)\n if copier:\n return copier(x)\n \n try :\n issc=issubclass(cls,type)\n except TypeError:\n issc=False\n if issc:\n \n return _copy_immutable(x)\n \n copier=getattr(cls,\"__copy__\",None )\n if copier:\n return copier(x)\n \n reductor=dispatch_table.get(cls)\n if reductor:\n rv=reductor(x)\n else :\n reductor=getattr(x,\"__reduce_ex__\",None )\n if reductor:\n rv=reductor(4)\n else :\n reductor=getattr(x,\"__reduce__\",None )\n if reductor:\n rv=reductor()\n else :\n raise Error(\"un(shallow)copyable object of type %s\"%cls)\n \n if isinstance(rv,str):\n return x\n return _reconstruct(x,None ,*rv)\n \n \n_copy_dispatch=d={}\n\ndef _copy_immutable(x):\n return x\nfor t in (type(None ),int,float,bool,complex,str,tuple,\nbytes,frozenset,type,range,slice,\ntypes.BuiltinFunctionType,type(Ellipsis),type(NotImplemented),\ntypes.FunctionType,weakref.ref):\n d[t]=_copy_immutable\nt=getattr(types,\"CodeType\",None )\nif t is not None :\n d[t]=_copy_immutable\n \nd[list]=list.copy\nd[dict]=dict.copy\nd[set]=set.copy\nd[bytearray]=bytearray.copy\n\nif PyStringMap is not None :\n d[PyStringMap]=PyStringMap.copy\n \ndel d,t\n\ndef deepcopy(x,memo=None ,_nil=[]):\n ''\n\n\n \n \n if memo is None :\n memo={}\n \n d=id(x)\n y=memo.get(d,_nil)\n if y is not _nil:\n return y\n \n cls=type(x)\n \n copier=_deepcopy_dispatch.get(cls)\n if copier:\n y=copier(x,memo)\n else :\n try :\n issc=issubclass(cls,type)\n except TypeError:\n issc=0\n if issc:\n y=_deepcopy_atomic(x,memo)\n else :\n copier=getattr(x,\"__deepcopy__\",None )\n if copier:\n y=copier(memo)\n else :\n reductor=dispatch_table.get(cls)\n if reductor:\n rv=reductor(x)\n else :\n reductor=getattr(x,\"__reduce_ex__\",None )\n if reductor:\n rv=reductor(4)\n else :\n reductor=getattr(x,\"__reduce__\",None )\n if reductor:\n rv=reductor()\n else :\n raise Error(\n \"un(deep)copyable object of type %s\"%cls)\n if isinstance(rv,str):\n y=x\n else :\n y=_reconstruct(x,memo,*rv)\n \n \n if y is not x:\n memo[d]=y\n _keep_alive(x,memo)\n return y\n \n_deepcopy_dispatch=d={}\n\ndef _deepcopy_atomic(x,memo):\n return x\nd[type(None )]=_deepcopy_atomic\nd[type(Ellipsis)]=_deepcopy_atomic\nd[type(NotImplemented)]=_deepcopy_atomic\nd[int]=_deepcopy_atomic\nd[float]=_deepcopy_atomic\nd[bool]=_deepcopy_atomic\nd[complex]=_deepcopy_atomic\nd[bytes]=_deepcopy_atomic\nd[str]=_deepcopy_atomic\ntry :\n d[types.CodeType]=_deepcopy_atomic\nexcept AttributeError:\n pass\nd[type]=_deepcopy_atomic\nd[types.BuiltinFunctionType]=_deepcopy_atomic\nd[types.FunctionType]=_deepcopy_atomic\nd[weakref.ref]=_deepcopy_atomic\n\ndef _deepcopy_list(x,memo,deepcopy=deepcopy):\n y=[]\n memo[id(x)]=y\n append=y.append\n for a in x:\n append(deepcopy(a,memo))\n return y\nd[list]=_deepcopy_list\n\ndef _deepcopy_tuple(x,memo,deepcopy=deepcopy):\n y=[deepcopy(a,memo)for a in x]\n \n \n try :\n return memo[id(x)]\n except KeyError:\n pass\n for k,j in zip(x,y):\n if k is not j:\n y=tuple(y)\n break\n else :\n y=x\n return y\nd[tuple]=_deepcopy_tuple\n\ndef _deepcopy_dict(x,memo,deepcopy=deepcopy):\n y={}\n memo[id(x)]=y\n for key,value in x.items():\n y[deepcopy(key,memo)]=deepcopy(value,memo)\n return y\nd[dict]=_deepcopy_dict\nif PyStringMap is not None :\n d[PyStringMap]=_deepcopy_dict\n \ndef _deepcopy_method(x,memo):\n return type(x)(x.__func__,deepcopy(x.__self__,memo))\nd[types.MethodType]=_deepcopy_method\n\ndel d\n\ndef _keep_alive(x,memo):\n ''\n\n\n\n\n\n\n\n \n try :\n memo[id(memo)].append(x)\n except KeyError:\n \n memo[id(memo)]=[x]\n \ndef _reconstruct(x,memo,func,args,\nstate=None ,listiter=None ,dictiter=None ,\ndeepcopy=deepcopy):\n deep=memo is not None\n if deep and args:\n args=(deepcopy(arg,memo)for arg in args)\n y=func(*args)\n if deep:\n memo[id(x)]=y\n \n if state is not None :\n if deep:\n state=deepcopy(state,memo)\n if hasattr(y,'__setstate__'):\n y.__setstate__(state)\n else :\n if isinstance(state,tuple)and len(state)==2:\n state,slotstate=state\n else :\n slotstate=None\n if state is not None :\n y.__dict__.update(state)\n if slotstate is not None :\n for key,value in slotstate.items():\n setattr(y,key,value)\n \n if listiter is not None :\n if deep:\n for item in listiter:\n item=deepcopy(item,memo)\n y.append(item)\n else :\n for item in listiter:\n y.append(item)\n if dictiter is not None :\n if deep:\n for key,value in dictiter:\n key=deepcopy(key,memo)\n value=deepcopy(value,memo)\n y[key]=value\n else :\n for key,value in dictiter:\n y[key]=value\n return y\n \ndel types,weakref,PyStringMap\n", ["copyreg", "org.python.core", "types", "weakref"]], "unittest.signals": [".py", "import signal\nimport weakref\n\nfrom functools import wraps\n\n__unittest=True\n\n\nclass _InterruptHandler(object):\n def __init__(self,default_handler):\n self.called=False\n self.original_handler=default_handler\n if isinstance(default_handler,int):\n if default_handler ==signal.SIG_DFL:\n \n default_handler=signal.default_int_handler\n elif default_handler ==signal.SIG_IGN:\n \n \n def default_handler(unused_signum,unused_frame):\n pass\n else :\n raise TypeError(\"expected SIGINT signal handler to be \"\n \"signal.SIG_IGN, signal.SIG_DFL, or a \"\n \"callable object\")\n self.default_handler=default_handler\n \n def __call__(self,signum,frame):\n installed_handler=signal.getsignal(signal.SIGINT)\n if installed_handler is not self:\n \n \n self.default_handler(signum,frame)\n \n if self.called:\n self.default_handler(signum,frame)\n self.called=True\n for result in _results.keys():\n result.stop()\n \n_results=weakref.WeakKeyDictionary()\ndef registerResult(result):\n _results[result]=1\n \ndef removeResult(result):\n return bool(_results.pop(result,None ))\n \n_interrupt_handler=None\ndef installHandler():\n global _interrupt_handler\n if _interrupt_handler is None :\n default_handler=signal.getsignal(signal.SIGINT)\n _interrupt_handler=_InterruptHandler(default_handler)\n signal.signal(signal.SIGINT,_interrupt_handler)\n \n \ndef removeHandler(method=None ):\n if method is not None :\n @wraps(method)\n def inner(*args,**kwargs):\n initial=signal.getsignal(signal.SIGINT)\n removeHandler()\n try :\n return method(*args,**kwargs)\n finally :\n signal.signal(signal.SIGINT,initial)\n return inner\n \n global _interrupt_handler\n if _interrupt_handler is not None :\n signal.signal(signal.SIGINT,_interrupt_handler.original_handler)\n", ["functools", "signal", "weakref"]], "codecs": [".py", "''\n\n\n\n\n\n\n\n\nimport builtins\nimport sys\n\n\n\ntry :\n from _codecs import *\nexcept ImportError as why:\n raise SystemError('Failed to load the builtin codecs: %s'%why)\n \n__all__=[\"register\",\"lookup\",\"open\",\"EncodedFile\",\"BOM\",\"BOM_BE\",\n\"BOM_LE\",\"BOM32_BE\",\"BOM32_LE\",\"BOM64_BE\",\"BOM64_LE\",\n\"BOM_UTF8\",\"BOM_UTF16\",\"BOM_UTF16_LE\",\"BOM_UTF16_BE\",\n\"BOM_UTF32\",\"BOM_UTF32_LE\",\"BOM_UTF32_BE\",\n\"CodecInfo\",\"Codec\",\"IncrementalEncoder\",\"IncrementalDecoder\",\n\"StreamReader\",\"StreamWriter\",\n\"StreamReaderWriter\",\"StreamRecoder\",\n\"getencoder\",\"getdecoder\",\"getincrementalencoder\",\n\"getincrementaldecoder\",\"getreader\",\"getwriter\",\n\"encode\",\"decode\",\"iterencode\",\"iterdecode\",\n\"strict_errors\",\"ignore_errors\",\"replace_errors\",\n\"xmlcharrefreplace_errors\",\n\"backslashreplace_errors\",\"namereplace_errors\",\n\"register_error\",\"lookup_error\"]\n\n\n\n\n\n\n\n\n\n\nBOM_UTF8=b'\\xef\\xbb\\xbf'\n\n\nBOM_LE=BOM_UTF16_LE=b'\\xff\\xfe'\n\n\nBOM_BE=BOM_UTF16_BE=b'\\xfe\\xff'\n\n\nBOM_UTF32_LE=b'\\xff\\xfe\\x00\\x00'\n\n\nBOM_UTF32_BE=b'\\x00\\x00\\xfe\\xff'\n\nif sys.byteorder =='little':\n\n\n BOM=BOM_UTF16=BOM_UTF16_LE\n \n \n BOM_UTF32=BOM_UTF32_LE\n \nelse :\n\n\n BOM=BOM_UTF16=BOM_UTF16_BE\n \n \n BOM_UTF32=BOM_UTF32_BE\n \n \nBOM32_LE=BOM_UTF16_LE\nBOM32_BE=BOM_UTF16_BE\nBOM64_LE=BOM_UTF32_LE\nBOM64_BE=BOM_UTF32_BE\n\n\n\n\nclass CodecInfo(tuple):\n ''\n \n \n \n \n \n \n \n _is_text_encoding=True\n \n def __new__(cls,encode,decode,streamreader=None ,streamwriter=None ,\n incrementalencoder=None ,incrementaldecoder=None ,name=None ,\n *,_is_text_encoding=None ):\n self=tuple.__new__(cls,(encode,decode,streamreader,streamwriter))\n self.name=name\n self.encode=encode\n self.decode=decode\n self.incrementalencoder=incrementalencoder\n self.incrementaldecoder=incrementaldecoder\n self.streamwriter=streamwriter\n self.streamreader=streamreader\n if _is_text_encoding is not None :\n self._is_text_encoding=_is_text_encoding\n return self\n \n def __repr__(self):\n return \"<%s.%s object for encoding %s at %#x>\"%\\\n (self.__class__.__module__,self.__class__.__qualname__,\n self.name,id(self))\n \nclass Codec:\n\n ''\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n \n def encode(self,input,errors='strict'):\n \n ''\n\n\n\n\n\n\n\n\n\n\n\n\n\n \n raise NotImplementedError\n \n def decode(self,input,errors='strict'):\n \n ''\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n \n raise NotImplementedError\n \nclass IncrementalEncoder(object):\n ''\n\n\n\n \n def __init__(self,errors='strict'):\n ''\n\n\n\n\n\n \n self.errors=errors\n self.buffer=\"\"\n \n def encode(self,input,final=False ):\n ''\n\n \n raise NotImplementedError\n \n def reset(self):\n ''\n\n \n \n def getstate(self):\n ''\n\n \n return 0\n \n def setstate(self,state):\n ''\n\n\n \n \nclass BufferedIncrementalEncoder(IncrementalEncoder):\n ''\n\n\n\n \n def __init__(self,errors='strict'):\n IncrementalEncoder.__init__(self,errors)\n \n self.buffer=\"\"\n \n def _buffer_encode(self,input,errors,final):\n \n \n raise NotImplementedError\n \n def encode(self,input,final=False ):\n \n data=self.buffer+input\n (result,consumed)=self._buffer_encode(data,self.errors,final)\n \n self.buffer=data[consumed:]\n return result\n \n def reset(self):\n IncrementalEncoder.reset(self)\n self.buffer=\"\"\n \n def getstate(self):\n return self.buffer or 0\n \n def setstate(self,state):\n self.buffer=state or \"\"\n \nclass IncrementalDecoder(object):\n ''\n\n\n\n \n def __init__(self,errors='strict'):\n ''\n\n\n\n\n\n \n self.errors=errors\n \n def decode(self,input,final=False ):\n ''\n\n \n raise NotImplementedError\n \n def reset(self):\n ''\n\n \n \n def getstate(self):\n ''\n\n\n\n\n\n\n\n\n\n \n return (b\"\",0)\n \n def setstate(self,state):\n ''\n\n\n\n\n \n \nclass BufferedIncrementalDecoder(IncrementalDecoder):\n ''\n\n\n\n \n def __init__(self,errors='strict'):\n IncrementalDecoder.__init__(self,errors)\n \n self.buffer=b\"\"\n \n def _buffer_decode(self,input,errors,final):\n \n \n raise NotImplementedError\n \n def decode(self,input,final=False ):\n \n data=self.buffer+input\n (result,consumed)=self._buffer_decode(data,self.errors,final)\n \n self.buffer=data[consumed:]\n return result\n \n def reset(self):\n IncrementalDecoder.reset(self)\n self.buffer=b\"\"\n \n def getstate(self):\n \n return (self.buffer,0)\n \n def setstate(self,state):\n \n self.buffer=state[0]\n \n \n \n \n \n \n \n \nclass StreamWriter(Codec):\n\n def __init__(self,stream,errors='strict'):\n \n ''\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n \n self.stream=stream\n self.errors=errors\n \n def write(self,object):\n \n ''\n \n data,consumed=self.encode(object,self.errors)\n self.stream.write(data)\n \n def writelines(self,list):\n \n ''\n\n \n self.write(''.join(list))\n \n def reset(self):\n \n ''\n\n\n\n\n\n\n \n pass\n \n def seek(self,offset,whence=0):\n self.stream.seek(offset,whence)\n if whence ==0 and offset ==0:\n self.reset()\n \n def __getattr__(self,name,\n getattr=getattr):\n \n ''\n \n return getattr(self.stream,name)\n \n def __enter__(self):\n return self\n \n def __exit__(self,type,value,tb):\n self.stream.close()\n \n \n \nclass StreamReader(Codec):\n\n charbuffertype=str\n \n def __init__(self,stream,errors='strict'):\n \n ''\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n \n self.stream=stream\n self.errors=errors\n self.bytebuffer=b\"\"\n self._empty_charbuffer=self.charbuffertype()\n self.charbuffer=self._empty_charbuffer\n self.linebuffer=None\n \n def decode(self,input,errors='strict'):\n raise NotImplementedError\n \n def read(self,size=-1,chars=-1,firstline=False ):\n \n ''\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n \n \n if self.linebuffer:\n self.charbuffer=self._empty_charbuffer.join(self.linebuffer)\n self.linebuffer=None\n \n if chars <0:\n \n \n chars=size\n \n \n while True :\n \n if chars >=0:\n if len(self.charbuffer)>=chars:\n break\n \n if size <0:\n newdata=self.stream.read()\n else :\n newdata=self.stream.read(size)\n \n data=self.bytebuffer+newdata\n if not data:\n break\n try :\n newchars,decodedbytes=self.decode(data,self.errors)\n except UnicodeDecodeError as exc:\n if firstline:\n newchars,decodedbytes=\\\n self.decode(data[:exc.start],self.errors)\n lines=newchars.splitlines(keepends=True )\n if len(lines)<=1:\n raise\n else :\n raise\n \n self.bytebuffer=data[decodedbytes:]\n \n self.charbuffer +=newchars\n \n if not newdata:\n break\n if chars <0:\n \n result=self.charbuffer\n self.charbuffer=self._empty_charbuffer\n else :\n \n result=self.charbuffer[:chars]\n self.charbuffer=self.charbuffer[chars:]\n return result\n \n def readline(self,size=None ,keepends=True ):\n \n ''\n\n\n\n\n\n \n \n \n if self.linebuffer:\n line=self.linebuffer[0]\n del self.linebuffer[0]\n if len(self.linebuffer)==1:\n \n \n self.charbuffer=self.linebuffer[0]\n self.linebuffer=None\n if not keepends:\n line=line.splitlines(keepends=False )[0]\n return line\n \n readsize=size or 72\n line=self._empty_charbuffer\n \n while True :\n data=self.read(readsize,firstline=True )\n if data:\n \n \n \n if (isinstance(data,str)and data.endswith(\"\\r\"))or\\\n (isinstance(data,bytes)and data.endswith(b\"\\r\")):\n data +=self.read(size=1,chars=1)\n \n line +=data\n lines=line.splitlines(keepends=True )\n if lines:\n if len(lines)>1:\n \n \n line=lines[0]\n del lines[0]\n if len(lines)>1:\n \n lines[-1]+=self.charbuffer\n self.linebuffer=lines\n self.charbuffer=None\n else :\n \n self.charbuffer=lines[0]+self.charbuffer\n if not keepends:\n line=line.splitlines(keepends=False )[0]\n break\n line0withend=lines[0]\n line0withoutend=lines[0].splitlines(keepends=False )[0]\n if line0withend !=line0withoutend:\n \n self.charbuffer=self._empty_charbuffer.join(lines[1:])+\\\n self.charbuffer\n if keepends:\n line=line0withend\n else :\n line=line0withoutend\n break\n \n if not data or size is not None :\n if line and not keepends:\n line=line.splitlines(keepends=False )[0]\n break\n if readsize <8000:\n readsize *=2\n return line\n \n def readlines(self,sizehint=None ,keepends=True ):\n \n ''\n\n\n\n\n\n\n\n\n \n data=self.read()\n return data.splitlines(keepends)\n \n def reset(self):\n \n ''\n\n\n\n\n\n \n self.bytebuffer=b\"\"\n self.charbuffer=self._empty_charbuffer\n self.linebuffer=None\n \n def seek(self,offset,whence=0):\n ''\n\n\n \n self.stream.seek(offset,whence)\n self.reset()\n \n def __next__(self):\n \n ''\n line=self.readline()\n if line:\n return line\n raise StopIteration\n \n def __iter__(self):\n return self\n \n def __getattr__(self,name,\n getattr=getattr):\n \n ''\n \n return getattr(self.stream,name)\n \n def __enter__(self):\n return self\n \n def __exit__(self,type,value,tb):\n self.stream.close()\n \n \n \nclass StreamReaderWriter:\n\n ''\n\n\n\n\n\n\n \n \n encoding='unknown'\n \n def __init__(self,stream,Reader,Writer,errors='strict'):\n \n ''\n\n\n\n\n\n\n\n\n\n \n self.stream=stream\n self.reader=Reader(stream,errors)\n self.writer=Writer(stream,errors)\n self.errors=errors\n \n def read(self,size=-1):\n \n return self.reader.read(size)\n \n def readline(self,size=None ):\n \n return self.reader.readline(size)\n \n def readlines(self,sizehint=None ):\n \n return self.reader.readlines(sizehint)\n \n def __next__(self):\n \n ''\n return next(self.reader)\n \n def __iter__(self):\n return self\n \n def write(self,data):\n \n return self.writer.write(data)\n \n def writelines(self,list):\n \n return self.writer.writelines(list)\n \n def reset(self):\n \n self.reader.reset()\n self.writer.reset()\n \n def seek(self,offset,whence=0):\n self.stream.seek(offset,whence)\n self.reader.reset()\n if whence ==0 and offset ==0:\n self.writer.reset()\n \n def __getattr__(self,name,\n getattr=getattr):\n \n ''\n \n return getattr(self.stream,name)\n \n \n \n def __enter__(self):\n return self\n \n def __exit__(self,type,value,tb):\n self.stream.close()\n \n \n \nclass StreamRecoder:\n\n ''\n\n\n\n\n\n\n\n\n\n\n\n\n \n \n data_encoding='unknown'\n file_encoding='unknown'\n \n def __init__(self,stream,encode,decode,Reader,Writer,\n errors='strict'):\n \n ''\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n \n self.stream=stream\n self.encode=encode\n self.decode=decode\n self.reader=Reader(stream,errors)\n self.writer=Writer(stream,errors)\n self.errors=errors\n \n def read(self,size=-1):\n \n data=self.reader.read(size)\n data,bytesencoded=self.encode(data,self.errors)\n return data\n \n def readline(self,size=None ):\n \n if size is None :\n data=self.reader.readline()\n else :\n data=self.reader.readline(size)\n data,bytesencoded=self.encode(data,self.errors)\n return data\n \n def readlines(self,sizehint=None ):\n \n data=self.reader.read()\n data,bytesencoded=self.encode(data,self.errors)\n return data.splitlines(keepends=True )\n \n def __next__(self):\n \n ''\n data=next(self.reader)\n data,bytesencoded=self.encode(data,self.errors)\n return data\n \n def __iter__(self):\n return self\n \n def write(self,data):\n \n data,bytesdecoded=self.decode(data,self.errors)\n return self.writer.write(data)\n \n def writelines(self,list):\n \n data=''.join(list)\n data,bytesdecoded=self.decode(data,self.errors)\n return self.writer.write(data)\n \n def reset(self):\n \n self.reader.reset()\n self.writer.reset()\n \n def __getattr__(self,name,\n getattr=getattr):\n \n ''\n \n return getattr(self.stream,name)\n \n def __enter__(self):\n return self\n \n def __exit__(self,type,value,tb):\n self.stream.close()\n \n \n \ndef open(filename,mode='r',encoding=None ,errors='strict',buffering=1):\n\n ''\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n \n if encoding is not None and\\\n 'b'not in mode:\n \n mode=mode+'b'\n file=builtins.open(filename,mode,buffering)\n if encoding is None :\n return file\n info=lookup(encoding)\n srw=StreamReaderWriter(file,info.streamreader,info.streamwriter,errors)\n \n srw.encoding=encoding\n return srw\n \ndef EncodedFile(file,data_encoding,file_encoding=None ,errors='strict'):\n\n ''\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n \n if file_encoding is None :\n file_encoding=data_encoding\n data_info=lookup(data_encoding)\n file_info=lookup(file_encoding)\n sr=StreamRecoder(file,data_info.encode,data_info.decode,\n file_info.streamreader,file_info.streamwriter,errors)\n \n sr.data_encoding=data_encoding\n sr.file_encoding=file_encoding\n return sr\n \n \n \ndef getencoder(encoding):\n\n ''\n\n\n\n\n \n return lookup(encoding).encode\n \ndef getdecoder(encoding):\n\n ''\n\n\n\n\n \n return lookup(encoding).decode\n \ndef getincrementalencoder(encoding):\n\n ''\n\n\n\n\n\n \n encoder=lookup(encoding).incrementalencoder\n if encoder is None :\n raise LookupError(encoding)\n return encoder\n \ndef getincrementaldecoder(encoding):\n\n ''\n\n\n\n\n\n \n decoder=lookup(encoding).incrementaldecoder\n if decoder is None :\n raise LookupError(encoding)\n return decoder\n \ndef getreader(encoding):\n\n ''\n\n\n\n\n \n return lookup(encoding).streamreader\n \ndef getwriter(encoding):\n\n ''\n\n\n\n\n \n return lookup(encoding).streamwriter\n \ndef iterencode(iterator,encoding,errors='strict',**kwargs):\n ''\n\n\n\n\n\n\n \n encoder=getincrementalencoder(encoding)(errors,**kwargs)\n for input in iterator:\n output=encoder.encode(input)\n if output:\n yield output\n output=encoder.encode(\"\",True )\n if output:\n yield output\n \ndef iterdecode(iterator,encoding,errors='strict',**kwargs):\n ''\n\n\n\n\n\n\n \n decoder=getincrementaldecoder(encoding)(errors,**kwargs)\n for input in iterator:\n output=decoder.decode(input)\n if output:\n yield output\n output=decoder.decode(b\"\",True )\n if output:\n yield output\n \n \n \ndef make_identity_dict(rng):\n\n ''\n\n\n\n\n \n return {i:i for i in rng}\n \ndef make_encoding_map(decoding_map):\n\n ''\n\n\n\n\n\n\n\n\n\n \n m={}\n for k,v in decoding_map.items():\n if not v in m:\n m[v]=k\n else :\n m[v]=None\n return m\n \n \n \ntry :\n strict_errors=lookup_error(\"strict\")\n ignore_errors=lookup_error(\"ignore\")\n replace_errors=lookup_error(\"replace\")\n xmlcharrefreplace_errors=lookup_error(\"xmlcharrefreplace\")\n backslashreplace_errors=lookup_error(\"backslashreplace\")\n namereplace_errors=lookup_error(\"namereplace\")\nexcept LookupError:\n\n strict_errors=None\n ignore_errors=None\n replace_errors=None\n xmlcharrefreplace_errors=None\n backslashreplace_errors=None\n namereplace_errors=None\n \n \n \n_false=0\nif _false:\n import encodings\n \n \n \nif __name__ =='__main__':\n\n\n sys.stdout=EncodedFile(sys.stdout,'latin-1','utf-8')\n \n \n sys.stdin=EncodedFile(sys.stdin,'utf-8','latin-1')\n", ["_codecs", "builtins", "encodings", "sys"]], "_threading_local": [".py", "''\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\nfrom weakref import ref\nfrom contextlib import contextmanager\n\n__all__=[\"local\"]\n\n\n\n\n\n\n\n\n\n\n\nclass _localimpl:\n ''\n __slots__='key','dicts','localargs','locallock','__weakref__'\n \n def __init__(self):\n \n \n \n self.key='_threading_local._localimpl.'+str(id(self))\n \n self.dicts={}\n \n def get_dict(self):\n ''\n \n thread=current_thread()\n return self.dicts[id(thread)][1]\n \n def create_dict(self):\n ''\n localdict={}\n key=self.key\n thread=current_thread()\n idt=id(thread)\n def local_deleted(_,key=key):\n \n thread=wrthread()\n if thread is not None :\n del thread.__dict__[key]\n def thread_deleted(_,idt=idt):\n \n \n \n \n local=wrlocal()\n if local is not None :\n dct=local.dicts.pop(idt)\n wrlocal=ref(self,local_deleted)\n wrthread=ref(thread,thread_deleted)\n thread.__dict__[key]=wrlocal\n self.dicts[idt]=wrthread,localdict\n return localdict\n \n \n@contextmanager\ndef _patch(self):\n impl=object.__getattribute__(self,'_local__impl')\n try :\n dct=impl.get_dict()\n except KeyError:\n dct=impl.create_dict()\n args,kw=impl.localargs\n self.__init__(*args,**kw)\n with impl.locallock:\n object.__setattr__(self,'__dict__',dct)\n yield\n \n \nclass local:\n __slots__='_local__impl','__dict__'\n \n def __new__(cls,*args,**kw):\n if (args or kw)and (cls.__init__ is object.__init__):\n raise TypeError(\"Initialization arguments are not supported\")\n self=object.__new__(cls)\n impl=_localimpl()\n impl.localargs=(args,kw)\n impl.locallock=RLock()\n object.__setattr__(self,'_local__impl',impl)\n \n \n \n impl.create_dict()\n return self\n \n def __getattribute__(self,name):\n with _patch(self):\n return object.__getattribute__(self,name)\n \n def __setattr__(self,name,value):\n if name =='__dict__':\n raise AttributeError(\n \"%r object attribute '__dict__' is read-only\"\n %self.__class__.__name__)\n with _patch(self):\n return object.__setattr__(self,name,value)\n \n def __delattr__(self,name):\n if name =='__dict__':\n raise AttributeError(\n \"%r object attribute '__dict__' is read-only\"\n %self.__class__.__name__)\n with _patch(self):\n return object.__delattr__(self,name)\n \n \nfrom threading import current_thread,RLock\n", ["contextlib", "threading", "weakref"]], "hashlib": [".js", "var $module=(function($B){\n\nvar _b_ = $B.builtins\n\nvar $s = []\nfor(var $b in _b_){$s.push('var ' + $b +' = _b_[\"'+$b+'\"]')}\neval($s.join(';'))\n\nvar $mod = {\n\n __getattr__ : function(attr){\n if(attr == 'new'){return hash.$factory}\n return this[attr]\n },\n md5: function(obj){return hash.$factory('md5', obj)},\n sha1: function(obj){return hash.$factory('sha1', obj)},\n sha224: function(obj){return hash.$factory('sha224', obj)},\n sha256: function(obj){return hash.$factory('sha256', obj)},\n sha384: function(obj){return hash.$factory('sha384', obj)},\n sha512: function(obj){return hash.$factory('sha512', obj)},\n\n algorithms_guaranteed: ['md5', 'sha1', 'sha224', 'sha256', 'sha384', 'sha512'],\n algorithms_available: ['md5', 'sha1', 'sha224', 'sha256', 'sha384', 'sha512']\n}\n\n//todo: eventually move this function to a \"utility\" file or use ajax module?\nfunction $get_CryptoJS_lib(alg){\n if($B.VFS !== undefined){\n // use file in brython_stdlib.js\n var lib = $B.VFS[\"crypto_js.rollups.\" + alg]\n if (lib===undefined){\n throw _b_.ImportError.$factory(\"can't import hashlib.\" + alg)\n }\n var res = lib[1]\n try{\n eval(res + \"; $B.CryptoJS = CryptoJS;\")\n return\n }catch(err){\n throw Error(\"JS Eval Error\",\n \"Cannot eval CryptoJS algorithm '\" + alg + \"' : error:\" + err)\n }\n }\n\n var module = {__name__: 'CryptoJS', $is_package: false}\n var res = $B.$download_module(module, $B.brython_path + 'libs/crypto_js/rollups/' + alg + '.js');\n\n try{\n eval(res + \"; $B.CryptoJS = CryptoJS;\")\n }catch(err){\n throw Error(\"JS Eval Error\",\n \"Cannot eval CryptoJS algorithm '\" + alg + \"' : error:\" + err)\n }\n}\n\nfunction bytes2WordArray(obj){\n // Transform a bytes object into an instance of class WordArray\n // defined in CryptoJS\n if(!_b_.isinstance(obj, _b_.bytes)){\n throw _b_.TypeError(\"expected bytes, got \" + $B.class_name(obj))\n }\n\n var words = []\n for(var i = 0; i < obj.source.length; i += 4){\n var word = obj.source.slice(i, i + 4)\n while(word.length < 4){word.push(0)}\n var w = word[3] + (word[2] << 8) + (word[1] << 16) + (word[0] << 24)\n words.push(w)\n }\n return {words: words, sigBytes: obj.source.length}\n}\n\nvar hash = {\n __class__: _b_.type,\n __mro__: [_b_.object],\n $infos:{\n __name__: 'hash'\n }\n}\n\nhash.update = function(self, msg){\n self.hash.update(bytes2WordArray(msg))\n}\n\nhash.copy = function(self){\n return self.hash.clone()\n}\n\nhash.digest = function(self){\n var obj = self.hash.clone().finalize().toString(),\n res = []\n for(var i = 0; i < obj.length; i += 2){\n res.push(parseInt(obj.substr(i, 2), 16))\n }\n return _b_.bytes.$factory(res)\n}\n\nhash.hexdigest = function(self) {\n return self.hash.clone().finalize().toString()\n}\n\nhash.$factory = function(alg, obj) {\n var res = {\n __class__: hash\n }\n\n switch(alg) {\n case 'md5':\n case 'sha1':\n case 'sha224':\n case 'sha256':\n case 'sha384':\n case 'sha512':\n var ALG = alg.toUpperCase()\n if($B.Crypto === undefined ||\n $B.CryptoJS.algo[ALG] === undefined){$get_CryptoJS_lib(alg)}\n\n res.hash = $B.CryptoJS.algo[ALG].create()\n if(obj !== undefined){\n res.hash.update(bytes2WordArray(obj))\n }\n break\n default:\n throw $B.builtins.AttributeError.$factory('Invalid hash algorithm: ' + alg)\n }\n\n return res\n}\n\nreturn $mod\n\n})(__BRYTHON__)\n"], "re": [".py", "\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\nr\"\"\"Support for regular expressions (RE).\n\nThis module provides regular expression matching operations similar to\nthose found in Perl. It supports both 8-bit and Unicode strings; both\nthe pattern and the strings being processed can contain null bytes and\ncharacters outside the US ASCII range.\n\nRegular expressions can contain both special and ordinary characters.\nMost ordinary characters, like \"A\", \"a\", or \"0\", are the simplest\nregular expressions; they simply match themselves. You can\nconcatenate ordinary characters, so last matches the string 'last'.\n\nThe special characters are:\n \".\" Matches any character except a newline.\n \"^\" Matches the start of the string.\n \"$\" Matches the end of the string or just before the newline at\n the end of the string.\n \"*\" Matches 0 or more (greedy) repetitions of the preceding RE.\n Greedy means that it will match as many repetitions as possible.\n \"+\" Matches 1 or more (greedy) repetitions of the preceding RE.\n \"?\" Matches 0 or 1 (greedy) of the preceding RE.\n *?,+?,?? Non-greedy versions of the previous three special characters.\n {m,n} Matches from m to n repetitions of the preceding RE.\n {m,n}? Non-greedy version of the above.\n \"\\\\\" Either escapes special characters or signals a special sequence.\n [] Indicates a set of characters.\n A \"^\" as the first character indicates a complementing set.\n \"|\" A|B, creates an RE that will match either A or B.\n (...) Matches the RE inside the parentheses.\n The contents can be retrieved or matched later in the string.\n (?aiLmsux) Set the A, I, L, M, S, U, or X flag for the RE (see below).\n (?:...) Non-grouping version of regular parentheses.\n (?P<name>...) The substring matched by the group is accessible by name.\n (?P=name) Matches the text matched earlier by the group named name.\n (?#...) A comment; ignored.\n (?=...) Matches if ... matches next, but doesn't consume the string.\n (?!...) Matches if ... doesn't match next.\n (?<=...) Matches if preceded by ... (must be fixed length).\n (?<!...) Matches if not preceded by ... (must be fixed length).\n (?(id/name)yes|no) Matches yes pattern if the group with id/name matched,\n the (optional) no pattern otherwise.\n\nThe special sequences consist of \"\\\\\" and a character from the list\nbelow. If the ordinary character is not on the list, then the\nresulting RE will match the second character.\n \\number Matches the contents of the group of the same number.\n \\A Matches only at the start of the string.\n \\Z Matches only at the end of the string.\n \\b Matches the empty string, but only at the start or end of a word.\n \\B Matches the empty string, but not at the start or end of a word.\n \\d Matches any decimal digit; equivalent to the set [0-9] in\n bytes patterns or string patterns with the ASCII flag.\n In string patterns without the ASCII flag, it will match the whole\n range of Unicode digits.\n \\D Matches any non-digit character; equivalent to [^\\d].\n \\s Matches any whitespace character; equivalent to [ \\t\\n\\r\\f\\v] in\n bytes patterns or string patterns with the ASCII flag.\n In string patterns without the ASCII flag, it will match the whole\n range of Unicode whitespace characters.\n \\S Matches any non-whitespace character; equivalent to [^\\s].\n \\w Matches any alphanumeric character; equivalent to [a-zA-Z0-9_]\n in bytes patterns or string patterns with the ASCII flag.\n In string patterns without the ASCII flag, it will match the\n range of Unicode alphanumeric characters (letters plus digits\n plus underscore).\n With LOCALE, it will match the set [0-9_] plus characters defined\n as letters for the current locale.\n \\W Matches the complement of \\w.\n \\\\ Matches a literal backslash.\n\nThis module exports the following functions:\n match Match a regular expression pattern to the beginning of a string.\n fullmatch Match a regular expression pattern to all of a string.\n search Search a string for the presence of a pattern.\n sub Substitute occurrences of a pattern found in a string.\n subn Same as sub, but also return the number of substitutions made.\n split Split a string by the occurrences of a pattern.\n findall Find all occurrences of a pattern in a string.\n finditer Return an iterator yielding a Match object for each match.\n compile Compile a pattern into a Pattern object.\n purge Clear the regular expression cache.\n escape Backslash all non-alphanumerics in a string.\n\nSome of the functions in this module takes flags as optional parameters:\n A ASCII For string patterns, make \\w, \\W, \\b, \\B, \\d, \\D\n match the corresponding ASCII character categories\n (rather than the whole Unicode categories, which is the\n default).\n For bytes patterns, this flag is the only available\n behaviour and needn't be specified.\n I IGNORECASE Perform case-insensitive matching.\n L LOCALE Make \\w, \\W, \\b, \\B, dependent on the current locale.\n M MULTILINE \"^\" matches the beginning of lines (after a newline)\n as well as the string.\n \"$\" matches the end of lines (before a newline) as well\n as the end of the string.\n S DOTALL \".\" matches any character at all, including the newline.\n X VERBOSE Ignore whitespace and comments for nicer looking RE's.\n U UNICODE For compatibility only. Ignored for string patterns (it\n is the default), and forbidden for bytes patterns.\n\nThis module also defines an exception 'error'.\n\n\"\"\"\n\nimport enum\nimport sre_compile\nimport sre_parse\nimport functools\ntry :\n import _locale\nexcept ImportError:\n _locale=None\n \n \n \n__all__=[\n\"match\",\"fullmatch\",\"search\",\"sub\",\"subn\",\"split\",\n\"findall\",\"finditer\",\"compile\",\"purge\",\"template\",\"escape\",\n\"error\",\"Pattern\",\"Match\",\"A\",\"I\",\"L\",\"M\",\"S\",\"X\",\"U\",\n\"ASCII\",\"IGNORECASE\",\"LOCALE\",\"MULTILINE\",\"DOTALL\",\"VERBOSE\",\n\"UNICODE\",\n]\n\n__version__=\"2.2.1\"\n\nclass RegexFlag(enum.IntFlag):\n ASCII=sre_compile.SRE_FLAG_ASCII\n IGNORECASE=sre_compile.SRE_FLAG_IGNORECASE\n LOCALE=sre_compile.SRE_FLAG_LOCALE\n UNICODE=sre_compile.SRE_FLAG_UNICODE\n MULTILINE=sre_compile.SRE_FLAG_MULTILINE\n DOTALL=sre_compile.SRE_FLAG_DOTALL\n VERBOSE=sre_compile.SRE_FLAG_VERBOSE\n A=ASCII\n I=IGNORECASE\n L=LOCALE\n U=UNICODE\n M=MULTILINE\n S=DOTALL\n X=VERBOSE\n \n TEMPLATE=sre_compile.SRE_FLAG_TEMPLATE\n T=TEMPLATE\n DEBUG=sre_compile.SRE_FLAG_DEBUG\nglobals().update(RegexFlag.__members__)\n\n\nerror=sre_compile.error\n\n\n\n\ndef match(pattern,string,flags=0):\n ''\n \n return _compile(pattern,flags).match(string)\n \ndef fullmatch(pattern,string,flags=0):\n ''\n \n return _compile(pattern,flags).fullmatch(string)\n \ndef search(pattern,string,flags=0):\n ''\n \n return _compile(pattern,flags).search(string)\n \ndef sub(pattern,repl,string,count=0,flags=0):\n ''\n\n\n\n\n \n return _compile(pattern,flags).sub(repl,string,count)\n \ndef subn(pattern,repl,string,count=0,flags=0):\n ''\n\n\n\n\n\n\n \n return _compile(pattern,flags).subn(repl,string,count)\n \ndef split(pattern,string,maxsplit=0,flags=0):\n ''\n\n\n\n\n\n \n return _compile(pattern,flags).split(string,maxsplit)\n \ndef findall(pattern,string,flags=0):\n ''\n\n\n\n\n\n \n return _compile(pattern,flags).findall(string)\n \ndef finditer(pattern,string,flags=0):\n ''\n\n\n \n return _compile(pattern,flags).finditer(string)\n \ndef compile(pattern,flags=0):\n ''\n return _compile(pattern,flags)\n \ndef purge():\n ''\n _cache.clear()\n _compile_repl.cache_clear()\n \ndef template(pattern,flags=0):\n ''\n return _compile(pattern,flags |T)\n \n \n \n \n \n \n_special_chars_map={i:'\\\\'+chr(i)for i in b'()[]{}?*+-|^$\\\\.&~# \\t\\n\\r\\v\\f'}\n\ndef escape(pattern):\n ''\n\n \n if isinstance(pattern,str):\n return pattern.translate(_special_chars_map)\n else :\n pattern=str(pattern,'latin1')\n return pattern.translate(_special_chars_map).encode('latin1')\n \nPattern=type(sre_compile.compile('',0))\nMatch=type(sre_compile.compile('',0).match(''))\n\n\n\n\n_cache={}\n\n_MAXCACHE=512\ndef _compile(pattern,flags):\n\n if isinstance(flags,RegexFlag):\n flags=flags.value\n try :\n return _cache[type(pattern),pattern,flags]\n except KeyError:\n pass\n if isinstance(pattern,Pattern):\n if flags:\n raise ValueError(\n \"cannot process flags argument with a compiled pattern\")\n return pattern\n if not sre_compile.isstring(pattern):\n raise TypeError(\"first argument must be string or compiled pattern\")\n p=sre_compile.compile(pattern,flags)\n if not (flags&DEBUG):\n if len(_cache)>=_MAXCACHE:\n \n try :\n del _cache[next(iter(_cache))]\n except (StopIteration,RuntimeError,KeyError):\n pass\n _cache[type(pattern),pattern,flags]=p\n return p\n \n@functools.lru_cache(_MAXCACHE)\ndef _compile_repl(repl,pattern):\n\n return sre_parse.parse_template(repl,pattern)\n \ndef _expand(pattern,match,template):\n\n template=sre_parse.parse_template(template,pattern)\n return sre_parse.expand_template(template,match)\n \ndef _subx(pattern,template):\n\n template=_compile_repl(template,pattern)\n if not template[0]and len(template[1])==1:\n \n return template[1][0]\n def filter(match,template=template):\n return sre_parse.expand_template(template,match)\n return filter\n \n \n \nimport copyreg\n\ndef _pickle(p):\n return _compile,(p.pattern,p.flags)\n \ncopyreg.pickle(Pattern,_pickle,_compile)\n\n\n\n\nclass Scanner:\n def __init__(self,lexicon,flags=0):\n from sre_constants import BRANCH,SUBPATTERN\n if isinstance(flags,RegexFlag):\n flags=flags.value\n self.lexicon=lexicon\n \n p=[]\n s=sre_parse.Pattern()\n s.flags=flags\n for phrase,action in lexicon:\n gid=s.opengroup()\n p.append(sre_parse.SubPattern(s,[\n (SUBPATTERN,(gid,0,0,sre_parse.parse(phrase,flags))),\n ]))\n s.closegroup(gid,p[-1])\n p=sre_parse.SubPattern(s,[(BRANCH,(None ,p))])\n self.scanner=sre_compile.compile(p)\n def scan(self,string):\n result=[]\n append=result.append\n match=self.scanner.scanner(string).match\n i=0\n while True :\n m=match()\n if not m:\n break\n j=m.end()\n if i ==j:\n break\n action=self.lexicon[m.lastindex -1][1]\n if callable(action):\n self.match=m\n action=action(self,m.group())\n if action is not None :\n append(action)\n i=j\n return result,string[i:]\n", ["_locale", "copyreg", "enum", "functools", "sre_compile", "sre_constants", "sre_parse"]], "sre_compile": [".py", "\n\n\n\n\n\n\n\n\n\n\"\"\"Internal support module for sre\"\"\"\n\nimport _sre\nimport sre_parse\nfrom sre_constants import *\n\n\n\n_LITERAL_CODES={LITERAL,NOT_LITERAL}\n_REPEATING_CODES={REPEAT,MIN_REPEAT,MAX_REPEAT}\n_SUCCESS_CODES={SUCCESS,FAILURE}\n_ASSERT_CODES={ASSERT,ASSERT_NOT}\n_UNIT_CODES=_LITERAL_CODES |{ANY,IN}\n\n\n_equivalences=(\n\n(0x69,0x131),\n\n(0x73,0x17f),\n\n(0xb5,0x3bc),\n\n(0x345,0x3b9,0x1fbe),\n\n(0x390,0x1fd3),\n\n(0x3b0,0x1fe3),\n\n(0x3b2,0x3d0),\n\n(0x3b5,0x3f5),\n\n(0x3b8,0x3d1),\n\n(0x3ba,0x3f0),\n\n(0x3c0,0x3d6),\n\n(0x3c1,0x3f1),\n\n(0x3c2,0x3c3),\n\n(0x3c6,0x3d5),\n\n(0x1e61,0x1e9b),\n\n(0xfb05,0xfb06),\n)\n\n\n_ignorecase_fixes={i:tuple(j for j in t if i !=j)\nfor t in _equivalences for i in t}\n\ndef _combine_flags(flags,add_flags,del_flags,\nTYPE_FLAGS=sre_parse.TYPE_FLAGS):\n if add_flags&TYPE_FLAGS:\n flags &=~TYPE_FLAGS\n return (flags |add_flags)&~del_flags\n \ndef _compile(code,pattern,flags):\n\n emit=code.append\n _len=len\n LITERAL_CODES=_LITERAL_CODES\n REPEATING_CODES=_REPEATING_CODES\n SUCCESS_CODES=_SUCCESS_CODES\n ASSERT_CODES=_ASSERT_CODES\n iscased=None\n tolower=None\n fixes=None\n if flags&SRE_FLAG_IGNORECASE and not flags&SRE_FLAG_LOCALE:\n if flags&SRE_FLAG_UNICODE and not flags&SRE_FLAG_ASCII:\n iscased=_sre.unicode_iscased\n tolower=_sre.unicode_tolower\n fixes=_ignorecase_fixes\n else :\n iscased=_sre.ascii_iscased\n tolower=_sre.ascii_tolower\n for op,av in pattern:\n if op in LITERAL_CODES:\n if not flags&SRE_FLAG_IGNORECASE:\n emit(op)\n emit(av)\n elif flags&SRE_FLAG_LOCALE:\n emit(OP_LOCALE_IGNORE[op])\n emit(av)\n elif not iscased(av):\n emit(op)\n emit(av)\n else :\n lo=tolower(av)\n if not fixes:\n emit(OP_IGNORE[op])\n emit(lo)\n elif lo not in fixes:\n emit(OP_UNICODE_IGNORE[op])\n emit(lo)\n else :\n emit(IN_UNI_IGNORE)\n skip=_len(code);emit(0)\n if op is NOT_LITERAL:\n emit(NEGATE)\n for k in (lo,)+fixes[lo]:\n emit(LITERAL)\n emit(k)\n emit(FAILURE)\n code[skip]=_len(code)-skip\n elif op is IN:\n charset,hascased=_optimize_charset(av,iscased,tolower,fixes)\n if flags&SRE_FLAG_IGNORECASE and flags&SRE_FLAG_LOCALE:\n emit(IN_LOC_IGNORE)\n elif not hascased:\n emit(IN)\n elif not fixes:\n emit(IN_IGNORE)\n else :\n emit(IN_UNI_IGNORE)\n skip=_len(code);emit(0)\n _compile_charset(charset,flags,code)\n code[skip]=_len(code)-skip\n elif op is ANY:\n if flags&SRE_FLAG_DOTALL:\n emit(ANY_ALL)\n else :\n emit(ANY)\n elif op in REPEATING_CODES:\n if flags&SRE_FLAG_TEMPLATE:\n raise error(\"internal: unsupported template operator %r\"%(op,))\n if _simple(av[2]):\n if op is MAX_REPEAT:\n emit(REPEAT_ONE)\n else :\n emit(MIN_REPEAT_ONE)\n skip=_len(code);emit(0)\n emit(av[0])\n emit(av[1])\n _compile(code,av[2],flags)\n emit(SUCCESS)\n code[skip]=_len(code)-skip\n else :\n emit(REPEAT)\n skip=_len(code);emit(0)\n emit(av[0])\n emit(av[1])\n _compile(code,av[2],flags)\n code[skip]=_len(code)-skip\n if op is MAX_REPEAT:\n emit(MAX_UNTIL)\n else :\n emit(MIN_UNTIL)\n elif op is SUBPATTERN:\n group,add_flags,del_flags,p=av\n if group:\n emit(MARK)\n emit((group -1)*2)\n \n _compile(code,p,_combine_flags(flags,add_flags,del_flags))\n if group:\n emit(MARK)\n emit((group -1)*2+1)\n elif op in SUCCESS_CODES:\n emit(op)\n elif op in ASSERT_CODES:\n emit(op)\n skip=_len(code);emit(0)\n if av[0]>=0:\n emit(0)\n else :\n lo,hi=av[1].getwidth()\n if lo !=hi:\n raise error(\"look-behind requires fixed-width pattern\")\n emit(lo)\n _compile(code,av[1],flags)\n emit(SUCCESS)\n code[skip]=_len(code)-skip\n elif op is CALL:\n emit(op)\n skip=_len(code);emit(0)\n _compile(code,av,flags)\n emit(SUCCESS)\n code[skip]=_len(code)-skip\n elif op is AT:\n emit(op)\n if flags&SRE_FLAG_MULTILINE:\n av=AT_MULTILINE.get(av,av)\n if flags&SRE_FLAG_LOCALE:\n av=AT_LOCALE.get(av,av)\n elif (flags&SRE_FLAG_UNICODE)and not (flags&SRE_FLAG_ASCII):\n av=AT_UNICODE.get(av,av)\n emit(av)\n elif op is BRANCH:\n emit(op)\n tail=[]\n tailappend=tail.append\n for av in av[1]:\n skip=_len(code);emit(0)\n \n _compile(code,av,flags)\n emit(JUMP)\n tailappend(_len(code));emit(0)\n code[skip]=_len(code)-skip\n emit(FAILURE)\n for tail in tail:\n code[tail]=_len(code)-tail\n elif op is CATEGORY:\n emit(op)\n if flags&SRE_FLAG_LOCALE:\n av=CH_LOCALE[av]\n elif (flags&SRE_FLAG_UNICODE)and not (flags&SRE_FLAG_ASCII):\n av=CH_UNICODE[av]\n emit(av)\n elif op is GROUPREF:\n if not flags&SRE_FLAG_IGNORECASE:\n emit(op)\n elif flags&SRE_FLAG_LOCALE:\n emit(GROUPREF_LOC_IGNORE)\n elif not fixes:\n emit(GROUPREF_IGNORE)\n else :\n emit(GROUPREF_UNI_IGNORE)\n emit(av -1)\n elif op is GROUPREF_EXISTS:\n emit(op)\n emit(av[0]-1)\n skipyes=_len(code);emit(0)\n _compile(code,av[1],flags)\n if av[2]:\n emit(JUMP)\n skipno=_len(code);emit(0)\n code[skipyes]=_len(code)-skipyes+1\n _compile(code,av[2],flags)\n code[skipno]=_len(code)-skipno\n else :\n code[skipyes]=_len(code)-skipyes+1\n else :\n raise error(\"internal: unsupported operand type %r\"%(op,))\n \ndef _compile_charset(charset,flags,code):\n\n emit=code.append\n for op,av in charset:\n emit(op)\n if op is NEGATE:\n pass\n elif op is LITERAL:\n emit(av)\n elif op is RANGE or op is RANGE_UNI_IGNORE:\n emit(av[0])\n emit(av[1])\n elif op is CHARSET:\n code.extend(av)\n elif op is BIGCHARSET:\n code.extend(av)\n elif op is CATEGORY:\n if flags&SRE_FLAG_LOCALE:\n emit(CH_LOCALE[av])\n elif (flags&SRE_FLAG_UNICODE)and not (flags&SRE_FLAG_ASCII):\n emit(CH_UNICODE[av])\n else :\n emit(av)\n else :\n raise error(\"internal: unsupported set operator %r\"%(op,))\n emit(FAILURE)\n \ndef _optimize_charset(charset,iscased=None ,fixup=None ,fixes=None ):\n\n out=[]\n tail=[]\n charmap=bytearray(256)\n hascased=False\n for op,av in charset:\n while True :\n try :\n if op is LITERAL:\n if fixup:\n lo=fixup(av)\n charmap[lo]=1\n if fixes and lo in fixes:\n for k in fixes[lo]:\n charmap[k]=1\n if not hascased and iscased(av):\n hascased=True\n else :\n charmap[av]=1\n elif op is RANGE:\n r=range(av[0],av[1]+1)\n if fixup:\n if fixes:\n for i in map(fixup,r):\n charmap[i]=1\n if i in fixes:\n for k in fixes[i]:\n charmap[k]=1\n else :\n for i in map(fixup,r):\n charmap[i]=1\n if not hascased:\n hascased=any(map(iscased,r))\n else :\n for i in r:\n charmap[i]=1\n elif op is NEGATE:\n out.append((op,av))\n else :\n tail.append((op,av))\n except IndexError:\n if len(charmap)==256:\n \n charmap +=b'\\0'*0xff00\n continue\n \n if fixup:\n hascased=True\n \n \n \n if op is RANGE:\n op=RANGE_UNI_IGNORE\n tail.append((op,av))\n break\n \n \n runs=[]\n q=0\n while True :\n p=charmap.find(1,q)\n if p <0:\n break\n if len(runs)>=2:\n runs=None\n break\n q=charmap.find(0,p)\n if q <0:\n runs.append((p,len(charmap)))\n break\n runs.append((p,q))\n if runs is not None :\n \n for p,q in runs:\n if q -p ==1:\n out.append((LITERAL,p))\n else :\n out.append((RANGE,(p,q -1)))\n out +=tail\n \n if hascased or len(out)<len(charset):\n return out,hascased\n \n return charset,hascased\n \n \n if len(charmap)==256:\n data=_mk_bitmap(charmap)\n out.append((CHARSET,data))\n out +=tail\n return out,hascased\n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n charmap=bytes(charmap)\n comps={}\n mapping=bytearray(256)\n block=0\n data=bytearray()\n for i in range(0,65536,256):\n chunk=charmap[i:i+256]\n if chunk in comps:\n mapping[i //256]=comps[chunk]\n else :\n mapping[i //256]=comps[chunk]=block\n block +=1\n data +=chunk\n data=_mk_bitmap(data)\n data[0:0]=[block]+_bytes_to_codes(mapping)\n out.append((BIGCHARSET,data))\n out +=tail\n return out,hascased\n \n_CODEBITS=_sre.CODESIZE *8\nMAXCODE=(1 <<_CODEBITS)-1\n_BITS_TRANS=b'0'+b'1'*255\ndef _mk_bitmap(bits,_CODEBITS=_CODEBITS,_int=int):\n s=bits.translate(_BITS_TRANS)[::-1]\n return [_int(s[i -_CODEBITS:i],2)\n for i in range(len(s),0,-_CODEBITS)]\n \ndef _bytes_to_codes(b):\n\n a=memoryview(b).cast('I')\n assert a.itemsize ==_sre.CODESIZE\n assert len(a)*a.itemsize ==len(b)\n return a.tolist()\n \ndef _simple(p):\n\n if len(p)!=1:\n return False\n op,av=p[0]\n if op is SUBPATTERN:\n return av[0]is None and _simple(av[-1])\n return op in _UNIT_CODES\n \ndef _generate_overlap_table(prefix):\n ''\n\n\n\n\n\n\n \n table=[0]*len(prefix)\n for i in range(1,len(prefix)):\n idx=table[i -1]\n while prefix[i]!=prefix[idx]:\n if idx ==0:\n table[i]=0\n break\n idx=table[idx -1]\n else :\n table[i]=idx+1\n return table\n \ndef _get_iscased(flags):\n if not flags&SRE_FLAG_IGNORECASE:\n return None\n elif flags&SRE_FLAG_UNICODE and not flags&SRE_FLAG_ASCII:\n return _sre.unicode_iscased\n else :\n return _sre.ascii_iscased\n \ndef _get_literal_prefix(pattern,flags):\n\n prefix=[]\n prefixappend=prefix.append\n prefix_skip=None\n iscased=_get_iscased(flags)\n for op,av in pattern.data:\n if op is LITERAL:\n if iscased and iscased(av):\n break\n prefixappend(av)\n elif op is SUBPATTERN:\n group,add_flags,del_flags,p=av\n flags1=_combine_flags(flags,add_flags,del_flags)\n if flags1&SRE_FLAG_IGNORECASE and flags1&SRE_FLAG_LOCALE:\n break\n prefix1,prefix_skip1,got_all=_get_literal_prefix(p,flags1)\n if prefix_skip is None :\n if group is not None :\n prefix_skip=len(prefix)\n elif prefix_skip1 is not None :\n prefix_skip=len(prefix)+prefix_skip1\n prefix.extend(prefix1)\n if not got_all:\n break\n else :\n break\n else :\n return prefix,prefix_skip,True\n return prefix,prefix_skip,False\n \ndef _get_charset_prefix(pattern,flags):\n while True :\n if not pattern.data:\n return None\n op,av=pattern.data[0]\n if op is not SUBPATTERN:\n break\n group,add_flags,del_flags,pattern=av\n flags=_combine_flags(flags,add_flags,del_flags)\n if flags&SRE_FLAG_IGNORECASE and flags&SRE_FLAG_LOCALE:\n return None\n \n iscased=_get_iscased(flags)\n if op is LITERAL:\n if iscased and iscased(av):\n return None\n return [(op,av)]\n elif op is BRANCH:\n charset=[]\n charsetappend=charset.append\n for p in av[1]:\n if not p:\n return None\n op,av=p[0]\n if op is LITERAL and not (iscased and iscased(av)):\n charsetappend((op,av))\n else :\n return None\n return charset\n elif op is IN:\n charset=av\n if iscased:\n for op,av in charset:\n if op is LITERAL:\n if iscased(av):\n return None\n elif op is RANGE:\n if av[1]>0xffff:\n return None\n if any(map(iscased,range(av[0],av[1]+1))):\n return None\n return charset\n return None\n \ndef _compile_info(code,pattern,flags):\n\n\n\n lo,hi=pattern.getwidth()\n if hi >MAXCODE:\n hi=MAXCODE\n if lo ==0:\n code.extend([INFO,4,0,lo,hi])\n return\n \n prefix=[]\n prefix_skip=0\n charset=[]\n if not (flags&SRE_FLAG_IGNORECASE and flags&SRE_FLAG_LOCALE):\n \n prefix,prefix_skip,got_all=_get_literal_prefix(pattern,flags)\n \n if not prefix:\n charset=_get_charset_prefix(pattern,flags)\n \n \n \n \n \n emit=code.append\n emit(INFO)\n skip=len(code);emit(0)\n \n mask=0\n if prefix:\n mask=SRE_INFO_PREFIX\n if prefix_skip is None and got_all:\n mask=mask |SRE_INFO_LITERAL\n elif charset:\n mask=mask |SRE_INFO_CHARSET\n emit(mask)\n \n if lo <MAXCODE:\n emit(lo)\n else :\n emit(MAXCODE)\n prefix=prefix[:MAXCODE]\n emit(min(hi,MAXCODE))\n \n if prefix:\n emit(len(prefix))\n if prefix_skip is None :\n prefix_skip=len(prefix)\n emit(prefix_skip)\n code.extend(prefix)\n \n code.extend(_generate_overlap_table(prefix))\n elif charset:\n charset,hascased=_optimize_charset(charset)\n assert not hascased\n _compile_charset(charset,flags,code)\n code[skip]=len(code)-skip\n \ndef isstring(obj):\n return isinstance(obj,(str,bytes))\n \ndef _code(p,flags):\n\n flags=p.pattern.flags |flags\n code=[]\n \n \n _compile_info(code,p,flags)\n \n \n _compile(code,p.data,flags)\n \n code.append(SUCCESS)\n \n return code\n \ndef _hex_code(code):\n return '[%s]'%', '.join('%#0*x'%(_sre.CODESIZE *2+2,x)for x in code)\n \ndef dis(code):\n import sys\n \n labels=set()\n level=0\n offset_width=len(str(len(code)-1))\n \n def dis_(start,end):\n def print_(*args,to=None ):\n if to is not None :\n labels.add(to)\n args +=('(to %d)'%(to,),)\n print('%*d%s '%(offset_width,start,':'if start in labels else '.'),\n end=' '*(level -1))\n print(*args)\n \n def print_2(*args):\n print(end=' '*(offset_width+2 *level))\n print(*args)\n \n nonlocal level\n level +=1\n i=start\n while i <end:\n start=i\n op=code[i]\n i +=1\n op=OPCODES[op]\n if op in (SUCCESS,FAILURE,ANY,ANY_ALL,\n MAX_UNTIL,MIN_UNTIL,NEGATE):\n print_(op)\n elif op in (LITERAL,NOT_LITERAL,\n LITERAL_IGNORE,NOT_LITERAL_IGNORE,\n LITERAL_UNI_IGNORE,NOT_LITERAL_UNI_IGNORE,\n LITERAL_LOC_IGNORE,NOT_LITERAL_LOC_IGNORE):\n arg=code[i]\n i +=1\n print_(op,'%#02x (%r)'%(arg,chr(arg)))\n elif op is AT:\n arg=code[i]\n i +=1\n arg=str(ATCODES[arg])\n assert arg[:3]=='AT_'\n print_(op,arg[3:])\n elif op is CATEGORY:\n arg=code[i]\n i +=1\n arg=str(CHCODES[arg])\n assert arg[:9]=='CATEGORY_'\n print_(op,arg[9:])\n elif op in (IN,IN_IGNORE,IN_UNI_IGNORE,IN_LOC_IGNORE):\n skip=code[i]\n print_(op,skip,to=i+skip)\n dis_(i+1,i+skip)\n i +=skip\n elif op in (RANGE,RANGE_UNI_IGNORE):\n lo,hi=code[i:i+2]\n i +=2\n print_(op,'%#02x %#02x (%r-%r)'%(lo,hi,chr(lo),chr(hi)))\n elif op is CHARSET:\n print_(op,_hex_code(code[i:i+256 //_CODEBITS]))\n i +=256 //_CODEBITS\n elif op is BIGCHARSET:\n arg=code[i]\n i +=1\n mapping=list(b''.join(x.to_bytes(_sre.CODESIZE,sys.byteorder)\n for x in code[i:i+256 //_sre.CODESIZE]))\n print_(op,arg,mapping)\n i +=256 //_sre.CODESIZE\n level +=1\n for j in range(arg):\n print_2(_hex_code(code[i:i+256 //_CODEBITS]))\n i +=256 //_CODEBITS\n level -=1\n elif op in (MARK,GROUPREF,GROUPREF_IGNORE,GROUPREF_UNI_IGNORE,\n GROUPREF_LOC_IGNORE):\n arg=code[i]\n i +=1\n print_(op,arg)\n elif op is JUMP:\n skip=code[i]\n print_(op,skip,to=i+skip)\n i +=1\n elif op is BRANCH:\n skip=code[i]\n print_(op,skip,to=i+skip)\n while skip:\n dis_(i+1,i+skip)\n i +=skip\n start=i\n skip=code[i]\n if skip:\n print_('branch',skip,to=i+skip)\n else :\n print_(FAILURE)\n i +=1\n elif op in (REPEAT,REPEAT_ONE,MIN_REPEAT_ONE):\n skip,min,max=code[i:i+3]\n if max ==MAXREPEAT:\n max='MAXREPEAT'\n print_(op,skip,min,max,to=i+skip)\n dis_(i+3,i+skip)\n i +=skip\n elif op is GROUPREF_EXISTS:\n arg,skip=code[i:i+2]\n print_(op,arg,skip,to=i+skip)\n i +=2\n elif op in (ASSERT,ASSERT_NOT):\n skip,arg=code[i:i+2]\n print_(op,skip,arg,to=i+skip)\n dis_(i+2,i+skip)\n i +=skip\n elif op is INFO:\n skip,flags,min,max=code[i:i+4]\n if max ==MAXREPEAT:\n max='MAXREPEAT'\n print_(op,skip,bin(flags),min,max,to=i+skip)\n start=i+4\n if flags&SRE_INFO_PREFIX:\n prefix_len,prefix_skip=code[i+4:i+6]\n print_2(' prefix_skip',prefix_skip)\n start=i+6\n prefix=code[start:start+prefix_len]\n print_2(' prefix',\n '[%s]'%', '.join('%#02x'%x for x in prefix),\n '(%r)'%''.join(map(chr,prefix)))\n start +=prefix_len\n print_2(' overlap',code[start:start+prefix_len])\n start +=prefix_len\n if flags&SRE_INFO_CHARSET:\n level +=1\n print_2('in')\n dis_(start,i+skip)\n level -=1\n i +=skip\n else :\n raise ValueError(op)\n \n level -=1\n \n dis_(0,len(code))\n \n \ndef compile(p,flags=0):\n\n\n if isstring(p):\n pattern=p\n p=sre_parse.parse(p,flags)\n else :\n pattern=None\n \n code=_code(p,flags)\n \n if flags&SRE_FLAG_DEBUG:\n print()\n dis(code)\n \n \n groupindex=p.pattern.groupdict\n indexgroup=[None ]*p.pattern.groups\n for k,i in groupindex.items():\n indexgroup[i]=k\n \n return _sre.compile(\n pattern,flags |p.pattern.flags,code,\n p.pattern.groups -1,\n groupindex,tuple(indexgroup)\n )\n", ["_sre", "sre_constants", "sre_parse", "sys"]], "http": [".py", "", [], 1], "unittest.util": [".py", "''\n\nfrom collections import namedtuple,Counter\nfrom os.path import commonprefix\n\n__unittest=True\n\n_MAX_LENGTH=80\n_PLACEHOLDER_LEN=12\n_MIN_BEGIN_LEN=5\n_MIN_END_LEN=5\n_MIN_COMMON_LEN=5\n_MIN_DIFF_LEN=_MAX_LENGTH -\\\n(_MIN_BEGIN_LEN+_PLACEHOLDER_LEN+_MIN_COMMON_LEN+\n_PLACEHOLDER_LEN+_MIN_END_LEN)\nassert _MIN_DIFF_LEN >=0\n\ndef _shorten(s,prefixlen,suffixlen):\n skip=len(s)-prefixlen -suffixlen\n if skip >_PLACEHOLDER_LEN:\n s='%s[%d chars]%s'%(s[:prefixlen],skip,s[len(s)-suffixlen:])\n return s\n \ndef _common_shorten_repr(*args):\n args=tuple(map(safe_repr,args))\n maxlen=max(map(len,args))\n if maxlen <=_MAX_LENGTH:\n return args\n \n prefix=commonprefix(args)\n prefixlen=len(prefix)\n \n common_len=_MAX_LENGTH -\\\n (maxlen -prefixlen+_MIN_BEGIN_LEN+_PLACEHOLDER_LEN)\n if common_len >_MIN_COMMON_LEN:\n assert _MIN_BEGIN_LEN+_PLACEHOLDER_LEN+_MIN_COMMON_LEN+\\\n (maxlen -prefixlen)<_MAX_LENGTH\n prefix=_shorten(prefix,_MIN_BEGIN_LEN,common_len)\n return tuple(prefix+s[prefixlen:]for s in args)\n \n prefix=_shorten(prefix,_MIN_BEGIN_LEN,_MIN_COMMON_LEN)\n return tuple(prefix+_shorten(s[prefixlen:],_MIN_DIFF_LEN,_MIN_END_LEN)\n for s in args)\n \ndef safe_repr(obj,short=False ):\n try :\n result=repr(obj)\n except Exception:\n result=object.__repr__(obj)\n if not short or len(result)<_MAX_LENGTH:\n return result\n return result[:_MAX_LENGTH]+' [truncated]...'\n \ndef strclass(cls):\n return \"%s.%s\"%(cls.__module__,cls.__qualname__)\n \ndef sorted_list_difference(expected,actual):\n ''\n\n\n\n\n\n \n i=j=0\n missing=[]\n unexpected=[]\n while True :\n try :\n e=expected[i]\n a=actual[j]\n if e <a:\n missing.append(e)\n i +=1\n while expected[i]==e:\n i +=1\n elif e >a:\n unexpected.append(a)\n j +=1\n while actual[j]==a:\n j +=1\n else :\n i +=1\n try :\n while expected[i]==e:\n i +=1\n finally :\n j +=1\n while actual[j]==a:\n j +=1\n except IndexError:\n missing.extend(expected[i:])\n unexpected.extend(actual[j:])\n break\n return missing,unexpected\n \n \ndef unorderable_list_difference(expected,actual):\n ''\n\n\n\n \n missing=[]\n while expected:\n item=expected.pop()\n try :\n actual.remove(item)\n except ValueError:\n missing.append(item)\n \n \n return missing,actual\n \ndef three_way_cmp(x,y):\n ''\n return (x >y)-(x <y)\n \n_Mismatch=namedtuple('Mismatch','actual expected value')\n\ndef _count_diff_all_purpose(actual,expected):\n ''\n \n s,t=list(actual),list(expected)\n m,n=len(s),len(t)\n NULL=object()\n result=[]\n for i,elem in enumerate(s):\n if elem is NULL:\n continue\n cnt_s=cnt_t=0\n for j in range(i,m):\n if s[j]==elem:\n cnt_s +=1\n s[j]=NULL\n for j,other_elem in enumerate(t):\n if other_elem ==elem:\n cnt_t +=1\n t[j]=NULL\n if cnt_s !=cnt_t:\n diff=_Mismatch(cnt_s,cnt_t,elem)\n result.append(diff)\n \n for i,elem in enumerate(t):\n if elem is NULL:\n continue\n cnt_t=0\n for j in range(i,n):\n if t[j]==elem:\n cnt_t +=1\n t[j]=NULL\n diff=_Mismatch(0,cnt_t,elem)\n result.append(diff)\n return result\n \ndef _count_diff_hashable(actual,expected):\n ''\n \n s,t=Counter(actual),Counter(expected)\n result=[]\n for elem,cnt_s in s.items():\n cnt_t=t.get(elem,0)\n if cnt_s !=cnt_t:\n diff=_Mismatch(cnt_s,cnt_t,elem)\n result.append(diff)\n for elem,cnt_t in t.items():\n if elem not in s:\n diff=_Mismatch(0,cnt_t,elem)\n result.append(diff)\n return result\n", ["collections", "os.path"]], "pydoc": [".py", "#!/usr/bin/env python3\n''\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n__all__=['help']\n__author__=\"Ka-Ping Yee <ping@lfw.org>\"\n__date__=\"26 February 2001\"\n\n__credits__=\"\"\"Guido van Rossum, for an excellent programming language.\nTommy Burnette, the original creator of manpy.\nPaul Prescod, for all his work on onlinehelp.\nRichard Chamberlain, for the first implementation of textdoc.\n\"\"\"\n\n\n\n\n\n\n\n\nimport builtins\nimport importlib._bootstrap\nimport importlib._bootstrap_external\nimport importlib.machinery\nimport importlib.util\nimport inspect\nimport io\nimport os\nimport pkgutil\nimport platform\nimport re\nimport sys\nimport time\nimport tokenize\nimport urllib.parse\nimport warnings\nfrom collections import deque\nfrom reprlib import Repr\nfrom traceback import format_exception_only\n\n\n\n\ndef pathdirs():\n ''\n dirs=[]\n normdirs=[]\n for dir in sys.path:\n dir=os.path.abspath(dir or '.')\n normdir=os.path.normcase(dir)\n if normdir not in normdirs and os.path.isdir(dir):\n dirs.append(dir)\n normdirs.append(normdir)\n return dirs\n \ndef getdoc(object):\n ''\n result=inspect.getdoc(object)or inspect.getcomments(object)\n return result and re.sub('^ *\\n','',result.rstrip())or ''\n \ndef splitdoc(doc):\n ''\n lines=doc.strip().split('\\n')\n if len(lines)==1:\n return lines[0],''\n elif len(lines)>=2 and not lines[1].rstrip():\n return lines[0],'\\n'.join(lines[2:])\n return '','\\n'.join(lines)\n \ndef classname(object,modname):\n ''\n name=object.__name__\n if object.__module__ !=modname:\n name=object.__module__+'.'+name\n return name\n \ndef isdata(object):\n ''\n return not (inspect.ismodule(object)or inspect.isclass(object)or\n inspect.isroutine(object)or inspect.isframe(object)or\n inspect.istraceback(object)or inspect.iscode(object))\n \ndef replace(text,*pairs):\n ''\n while pairs:\n text=pairs[1].join(text.split(pairs[0]))\n pairs=pairs[2:]\n return text\n \ndef cram(text,maxlen):\n ''\n if len(text)>maxlen:\n pre=max(0,(maxlen -3)//2)\n post=max(0,maxlen -3 -pre)\n return text[:pre]+'...'+text[len(text)-post:]\n return text\n \n_re_stripid=re.compile(r' at 0x[0-9a-f]{6,16}(>+)$',re.IGNORECASE)\ndef stripid(text):\n ''\n \n return _re_stripid.sub(r'\\1',text)\n \ndef _is_some_method(obj):\n return (inspect.isfunction(obj)or\n inspect.ismethod(obj)or\n inspect.isbuiltin(obj)or\n inspect.ismethoddescriptor(obj))\n \ndef _is_bound_method(fn):\n ''\n\n\n \n if inspect.ismethod(fn):\n return True\n if inspect.isbuiltin(fn):\n self=getattr(fn,'__self__',None )\n return not (inspect.ismodule(self)or (self is None ))\n return False\n \n \ndef allmethods(cl):\n methods={}\n for key,value in inspect.getmembers(cl,_is_some_method):\n methods[key]=1\n for base in cl.__bases__:\n methods.update(allmethods(base))\n for key in methods.keys():\n methods[key]=getattr(cl,key)\n return methods\n \ndef _split_list(s,predicate):\n ''\n\n\n\n\n \n \n yes=[]\n no=[]\n for x in s:\n if predicate(x):\n yes.append(x)\n else :\n no.append(x)\n return yes,no\n \ndef visiblename(name,all=None ,obj=None ):\n ''\n \n \n if name in {'__author__','__builtins__','__cached__','__credits__',\n '__date__','__doc__','__file__','__spec__',\n '__loader__','__module__','__name__','__package__',\n '__path__','__qualname__','__slots__','__version__'}:\n return 0\n \n if name.startswith('__')and name.endswith('__'):return 1\n \n if name.startswith('_')and hasattr(obj,'_fields'):\n return True\n if all is not None :\n \n return name in all\n else :\n return not name.startswith('_')\n \ndef classify_class_attrs(object):\n ''\n results=[]\n for (name,kind,cls,value)in inspect.classify_class_attrs(object):\n if inspect.isdatadescriptor(value):\n kind='data descriptor'\n results.append((name,kind,cls,value))\n return results\n \ndef sort_attributes(attrs,object):\n ''\n \n \n fields=getattr(object,'_fields',[])\n try :\n field_order={name:i -len(fields)for (i,name)in enumerate(fields)}\n except TypeError:\n field_order={}\n keyfunc=lambda attr:(field_order.get(attr[0],0),attr[0])\n attrs.sort(key=keyfunc)\n \n \n \ndef ispackage(path):\n ''\n if os.path.isdir(path):\n for ext in ('.py','.pyc'):\n if os.path.isfile(os.path.join(path,'__init__'+ext)):\n return True\n return False\n \ndef source_synopsis(file):\n line=file.readline()\n while line[:1]=='#'or not line.strip():\n line=file.readline()\n if not line:break\n line=line.strip()\n if line[:4]=='r\"\"\"':line=line[1:]\n if line[:3]=='\"\"\"':\n line=line[3:]\n if line[-1:]=='\\\\':line=line[:-1]\n while not line.strip():\n line=file.readline()\n if not line:break\n result=line.split('\"\"\"')[0].strip()\n else :result=None\n return result\n \ndef synopsis(filename,cache={}):\n ''\n mtime=os.stat(filename).st_mtime\n lastupdate,result=cache.get(filename,(None ,None ))\n if lastupdate is None or lastupdate <mtime:\n \n if filename.endswith(tuple(importlib.machinery.BYTECODE_SUFFIXES)):\n loader_cls=importlib.machinery.SourcelessFileLoader\n elif filename.endswith(tuple(importlib.machinery.EXTENSION_SUFFIXES)):\n loader_cls=importlib.machinery.ExtensionFileLoader\n else :\n loader_cls=None\n \n if loader_cls is None :\n \n try :\n file=tokenize.open(filename)\n except OSError:\n \n return None\n \n with file:\n result=source_synopsis(file)\n else :\n \n loader=loader_cls('__temp__',filename)\n \n spec=importlib.util.spec_from_file_location('__temp__',filename,\n loader=loader)\n try :\n module=importlib._bootstrap._load(spec)\n except :\n return None\n del sys.modules['__temp__']\n result=module.__doc__.splitlines()[0]if module.__doc__ else None\n \n cache[filename]=(mtime,result)\n return result\n \nclass ErrorDuringImport(Exception):\n ''\n def __init__(self,filename,exc_info):\n self.filename=filename\n self.exc,self.value,self.tb=exc_info\n \n def __str__(self):\n exc=self.exc.__name__\n return 'problem in %s - %s: %s'%(self.filename,exc,self.value)\n \ndef importfile(path):\n ''\n magic=importlib.util.MAGIC_NUMBER\n with open(path,'rb')as file:\n is_bytecode=magic ==file.read(len(magic))\n filename=os.path.basename(path)\n name,ext=os.path.splitext(filename)\n if is_bytecode:\n loader=importlib._bootstrap_external.SourcelessFileLoader(name,path)\n else :\n loader=importlib._bootstrap_external.SourceFileLoader(name,path)\n \n spec=importlib.util.spec_from_file_location(name,path,loader=loader)\n try :\n return importlib._bootstrap._load(spec)\n except :\n raise ErrorDuringImport(path,sys.exc_info())\n \ndef safeimport(path,forceload=0,cache={}):\n ''\n\n\n\n\n\n \n try :\n \n \n \n \n if forceload and path in sys.modules:\n if path not in sys.builtin_module_names:\n \n \n \n \n \n subs=[m for m in sys.modules if m.startswith(path+'.')]\n for key in [path]+subs:\n \n cache[key]=sys.modules[key]\n del sys.modules[key]\n module=__import__(path)\n except :\n \n (exc,value,tb)=info=sys.exc_info()\n if path in sys.modules:\n \n raise ErrorDuringImport(sys.modules[path].__file__,info)\n elif exc is SyntaxError:\n \n raise ErrorDuringImport(value.filename,info)\n elif issubclass(exc,ImportError)and value.name ==path:\n \n return None\n else :\n \n raise ErrorDuringImport(path,sys.exc_info())\n for part in path.split('.')[1:]:\n try :module=getattr(module,part)\n except AttributeError:return None\n return module\n \n \n \nclass Doc:\n\n PYTHONDOCS=os.environ.get(\"PYTHONDOCS\",\n \"https://docs.python.org/%d.%d/library\"\n %sys.version_info[:2])\n \n def document(self,object,name=None ,*args):\n ''\n args=(object,name)+args\n \n \n \n \n if inspect.isgetsetdescriptor(object):return self.docdata(*args)\n if inspect.ismemberdescriptor(object):return self.docdata(*args)\n try :\n if inspect.ismodule(object):return self.docmodule(*args)\n if inspect.isclass(object):return self.docclass(*args)\n if inspect.isroutine(object):return self.docroutine(*args)\n except AttributeError:\n pass\n if isinstance(object,property):return self.docproperty(*args)\n return self.docother(*args)\n \n def fail(self,object,name=None ,*args):\n ''\n message=\"don't know how to document object%s of type %s\"%(\n name and ' '+repr(name),type(object).__name__)\n raise TypeError(message)\n \n docmodule=docclass=docroutine=docother=docproperty=docdata=fail\n \n def getdocloc(self,object,\n basedir=os.path.join(sys.base_exec_prefix,\"lib\",\n \"python%d.%d\"%sys.version_info[:2])):\n ''\n \n try :\n file=inspect.getabsfile(object)\n except TypeError:\n file='(built-in)'\n \n docloc=os.environ.get(\"PYTHONDOCS\",self.PYTHONDOCS)\n \n basedir=os.path.normcase(basedir)\n if (isinstance(object,type(os))and\n (object.__name__ in ('errno','exceptions','gc','imp',\n 'marshal','posix','signal','sys',\n '_thread','zipimport')or\n (file.startswith(basedir)and\n not file.startswith(os.path.join(basedir,'site-packages'))))and\n object.__name__ not in ('xml.etree','test.pydoc_mod')):\n if docloc.startswith((\"http://\",\"https://\")):\n docloc=\"%s/%s\"%(docloc.rstrip(\"/\"),object.__name__.lower())\n else :\n docloc=os.path.join(docloc,object.__name__.lower()+\".html\")\n else :\n docloc=None\n return docloc\n \n \n \nclass HTMLRepr(Repr):\n ''\n def __init__(self):\n Repr.__init__(self)\n self.maxlist=self.maxtuple=20\n self.maxdict=10\n self.maxstring=self.maxother=100\n \n def escape(self,text):\n return replace(text,'&','&amp;','<','&lt;','>','&gt;')\n \n def repr(self,object):\n return Repr.repr(self,object)\n \n def repr1(self,x,level):\n if hasattr(type(x),'__name__'):\n methodname='repr_'+'_'.join(type(x).__name__.split())\n if hasattr(self,methodname):\n return getattr(self,methodname)(x,level)\n return self.escape(cram(stripid(repr(x)),self.maxother))\n \n def repr_string(self,x,level):\n test=cram(x,self.maxstring)\n testrepr=repr(test)\n if '\\\\'in test and '\\\\'not in replace(testrepr,r'\\\\',''):\n \n \n return 'r'+testrepr[0]+self.escape(test)+testrepr[0]\n return re.sub(r'((\\\\[\\\\abfnrtv\\'\"]|\\\\[0-9]..|\\\\x..|\\\\u....)+)',\n r'<font color=\"#c040c0\">\\1</font>',\n self.escape(testrepr))\n \n repr_str=repr_string\n \n def repr_instance(self,x,level):\n try :\n return self.escape(cram(stripid(repr(x)),self.maxstring))\n except :\n return self.escape('<%s instance>'%x.__class__.__name__)\n \n repr_unicode=repr_string\n \nclass HTMLDoc(Doc):\n ''\n \n \n \n _repr_instance=HTMLRepr()\n repr=_repr_instance.repr\n escape=_repr_instance.escape\n \n def page(self,title,contents):\n ''\n return '''\\\n<!DOCTYPE html PUBLIC \"-//W3C//DTD HTML 4.0 Transitional//EN\">\n<html><head><title>Python: %s</title>\n<meta http-equiv=\"Content-Type\" content=\"text/html; charset=utf-8\">\n</head><body bgcolor=\"#f0f0f8\">\n%s\n</body></html>'''%(title,contents)\n \n def heading(self,title,fgcol,bgcol,extras=''):\n ''\n return '''\n<table width=\"100%%\" cellspacing=0 cellpadding=2 border=0 summary=\"heading\">\n<tr bgcolor=\"%s\">\n<td valign=bottom>&nbsp;<br>\n<font color=\"%s\" face=\"helvetica, arial\">&nbsp;<br>%s</font></td\n><td align=right valign=bottom\n><font color=\"%s\" face=\"helvetica, arial\">%s</font></td></tr></table>\n '''%(bgcol,fgcol,title,fgcol,extras or '&nbsp;')\n \n def section(self,title,fgcol,bgcol,contents,width=6,\n prelude='',marginalia=None ,gap='&nbsp;'):\n ''\n if marginalia is None :\n marginalia='<tt>'+'&nbsp;'*width+'</tt>'\n result='''<p>\n<table width=\"100%%\" cellspacing=0 cellpadding=2 border=0 summary=\"section\">\n<tr bgcolor=\"%s\">\n<td colspan=3 valign=bottom>&nbsp;<br>\n<font color=\"%s\" face=\"helvetica, arial\">%s</font></td></tr>\n '''%(bgcol,fgcol,title)\n if prelude:\n result=result+'''\n<tr bgcolor=\"%s\"><td rowspan=2>%s</td>\n<td colspan=2>%s</td></tr>\n<tr><td>%s</td>'''%(bgcol,marginalia,prelude,gap)\n else :\n result=result+'''\n<tr><td bgcolor=\"%s\">%s</td><td>%s</td>'''%(bgcol,marginalia,gap)\n \n return result+'\\n<td width=\"100%%\">%s</td></tr></table>'%contents\n \n def bigsection(self,title,*args):\n ''\n title='<big><strong>%s</strong></big>'%title\n return self.section(title,*args)\n \n def preformat(self,text):\n ''\n text=self.escape(text.expandtabs())\n return replace(text,'\\n\\n','\\n \\n','\\n\\n','\\n \\n',\n ' ','&nbsp;','\\n','<br>\\n')\n \n def multicolumn(self,list,format,cols=4):\n ''\n result=''\n rows=(len(list)+cols -1)//cols\n for col in range(cols):\n result=result+'<td width=\"%d%%\" valign=top>'%(100 //cols)\n for i in range(rows *col,rows *col+rows):\n if i <len(list):\n result=result+format(list[i])+'<br>\\n'\n result=result+'</td>'\n return '<table width=\"100%%\" summary=\"list\"><tr>%s</tr></table>'%result\n \n def grey(self,text):return '<font color=\"#909090\">%s</font>'%text\n \n def namelink(self,name,*dicts):\n ''\n for dict in dicts:\n if name in dict:\n return '<a href=\"%s\">%s</a>'%(dict[name],name)\n return name\n \n def classlink(self,object,modname):\n ''\n name,module=object.__name__,sys.modules.get(object.__module__)\n if hasattr(module,name)and getattr(module,name)is object:\n return '<a href=\"%s.html#%s\">%s</a>'%(\n module.__name__,name,classname(object,modname))\n return classname(object,modname)\n \n def modulelink(self,object):\n ''\n return '<a href=\"%s.html\">%s</a>'%(object.__name__,object.__name__)\n \n def modpkglink(self,modpkginfo):\n ''\n name,path,ispackage,shadowed=modpkginfo\n if shadowed:\n return self.grey(name)\n if path:\n url='%s.%s.html'%(path,name)\n else :\n url='%s.html'%name\n if ispackage:\n text='<strong>%s</strong>&nbsp;(package)'%name\n else :\n text=name\n return '<a href=\"%s\">%s</a>'%(url,text)\n \n def filelink(self,url,path):\n ''\n return '<a href=\"file:%s\">%s</a>'%(url,path)\n \n def markup(self,text,escape=None ,funcs={},classes={},methods={}):\n ''\n \n escape=escape or self.escape\n results=[]\n here=0\n pattern=re.compile(r'\\b((http|ftp)://\\S+[\\w/]|'\n r'RFC[- ]?(\\d+)|'\n r'PEP[- ]?(\\d+)|'\n r'(self\\.)?(\\w+))')\n while True :\n match=pattern.search(text,here)\n if not match:break\n start,end=match.span()\n results.append(escape(text[here:start]))\n \n all,scheme,rfc,pep,selfdot,name=match.groups()\n if scheme:\n url=escape(all).replace('\"','&quot;')\n results.append('<a href=\"%s\">%s</a>'%(url,url))\n elif rfc:\n url='http://www.rfc-editor.org/rfc/rfc%d.txt'%int(rfc)\n results.append('<a href=\"%s\">%s</a>'%(url,escape(all)))\n elif pep:\n url='http://www.python.org/dev/peps/pep-%04d/'%int(pep)\n results.append('<a href=\"%s\">%s</a>'%(url,escape(all)))\n elif selfdot:\n \n \n if text[end:end+1]=='(':\n results.append('self.'+self.namelink(name,methods))\n else :\n results.append('self.<strong>%s</strong>'%name)\n elif text[end:end+1]=='(':\n results.append(self.namelink(name,methods,funcs,classes))\n else :\n results.append(self.namelink(name,classes))\n here=end\n results.append(escape(text[here:]))\n return ''.join(results)\n \n \n \n def formattree(self,tree,modname,parent=None ):\n ''\n result=''\n for entry in tree:\n if type(entry)is type(()):\n c,bases=entry\n result=result+'<dt><font face=\"helvetica, arial\">'\n result=result+self.classlink(c,modname)\n if bases and bases !=(parent,):\n parents=[]\n for base in bases:\n parents.append(self.classlink(base,modname))\n result=result+'('+', '.join(parents)+')'\n result=result+'\\n</font></dt>'\n elif type(entry)is type([]):\n result=result+'<dd>\\n%s</dd>\\n'%self.formattree(\n entry,modname,c)\n return '<dl>\\n%s</dl>\\n'%result\n \n def docmodule(self,object,name=None ,mod=None ,*ignored):\n ''\n name=object.__name__\n try :\n all=object.__all__\n except AttributeError:\n all=None\n parts=name.split('.')\n links=[]\n for i in range(len(parts)-1):\n links.append(\n '<a href=\"%s.html\"><font color=\"#ffffff\">%s</font></a>'%\n ('.'.join(parts[:i+1]),parts[i]))\n linkedname='.'.join(links+parts[-1:])\n head='<big><big><strong>%s</strong></big></big>'%linkedname\n try :\n path=inspect.getabsfile(object)\n url=urllib.parse.quote(path)\n filelink=self.filelink(url,path)\n except TypeError:\n filelink='(built-in)'\n info=[]\n if hasattr(object,'__version__'):\n version=str(object.__version__)\n if version[:11]=='$'+'Revision: 'and version[-1:]=='$':\n version=version[11:-1].strip()\n info.append('version %s'%self.escape(version))\n if hasattr(object,'__date__'):\n info.append(self.escape(str(object.__date__)))\n if info:\n head=head+' (%s)'%', '.join(info)\n docloc=self.getdocloc(object)\n if docloc is not None :\n docloc='<br><a href=\"%(docloc)s\">Module Reference</a>'%locals()\n else :\n docloc=''\n result=self.heading(\n head,'#ffffff','#7799ee',\n '<a href=\".\">index</a><br>'+filelink+docloc)\n \n modules=inspect.getmembers(object,inspect.ismodule)\n \n classes,cdict=[],{}\n for key,value in inspect.getmembers(object,inspect.isclass):\n \n if (all is not None or\n (inspect.getmodule(value)or object)is object):\n if visiblename(key,all,object):\n classes.append((key,value))\n cdict[key]=cdict[value]='#'+key\n for key,value in classes:\n for base in value.__bases__:\n key,modname=base.__name__,base.__module__\n module=sys.modules.get(modname)\n if modname !=name and module and hasattr(module,key):\n if getattr(module,key)is base:\n if not key in cdict:\n cdict[key]=cdict[base]=modname+'.html#'+key\n funcs,fdict=[],{}\n for key,value in inspect.getmembers(object,inspect.isroutine):\n \n if (all is not None or\n inspect.isbuiltin(value)or inspect.getmodule(value)is object):\n if visiblename(key,all,object):\n funcs.append((key,value))\n fdict[key]='#-'+key\n if inspect.isfunction(value):fdict[value]=fdict[key]\n data=[]\n for key,value in inspect.getmembers(object,isdata):\n if visiblename(key,all,object):\n data.append((key,value))\n \n doc=self.markup(getdoc(object),self.preformat,fdict,cdict)\n doc=doc and '<tt>%s</tt>'%doc\n result=result+'<p>%s</p>\\n'%doc\n \n if hasattr(object,'__path__'):\n modpkgs=[]\n for importer,modname,ispkg in pkgutil.iter_modules(object.__path__):\n modpkgs.append((modname,name,ispkg,0))\n modpkgs.sort()\n contents=self.multicolumn(modpkgs,self.modpkglink)\n result=result+self.bigsection(\n 'Package Contents','#ffffff','#aa55cc',contents)\n elif modules:\n contents=self.multicolumn(\n modules,lambda t:self.modulelink(t[1]))\n result=result+self.bigsection(\n 'Modules','#ffffff','#aa55cc',contents)\n \n if classes:\n classlist=[value for (key,value)in classes]\n contents=[\n self.formattree(inspect.getclasstree(classlist,1),name)]\n for key,value in classes:\n contents.append(self.document(value,key,name,fdict,cdict))\n result=result+self.bigsection(\n 'Classes','#ffffff','#ee77aa',' '.join(contents))\n if funcs:\n contents=[]\n for key,value in funcs:\n contents.append(self.document(value,key,name,fdict,cdict))\n result=result+self.bigsection(\n 'Functions','#ffffff','#eeaa77',' '.join(contents))\n if data:\n contents=[]\n for key,value in data:\n contents.append(self.document(value,key))\n result=result+self.bigsection(\n 'Data','#ffffff','#55aa55','<br>\\n'.join(contents))\n if hasattr(object,'__author__'):\n contents=self.markup(str(object.__author__),self.preformat)\n result=result+self.bigsection(\n 'Author','#ffffff','#7799ee',contents)\n if hasattr(object,'__credits__'):\n contents=self.markup(str(object.__credits__),self.preformat)\n result=result+self.bigsection(\n 'Credits','#ffffff','#7799ee',contents)\n \n return result\n \n def docclass(self,object,name=None ,mod=None ,funcs={},classes={},\n *ignored):\n ''\n realname=object.__name__\n name=name or realname\n bases=object.__bases__\n \n contents=[]\n push=contents.append\n \n \n class HorizontalRule:\n def __init__(self):\n self.needone=0\n def maybe(self):\n if self.needone:\n push('<hr>\\n')\n self.needone=1\n hr=HorizontalRule()\n \n \n mro=deque(inspect.getmro(object))\n if len(mro)>2:\n hr.maybe()\n push('<dl><dt>Method resolution order:</dt>\\n')\n for base in mro:\n push('<dd>%s</dd>\\n'%self.classlink(base,\n object.__module__))\n push('</dl>\\n')\n \n def spill(msg,attrs,predicate):\n ok,attrs=_split_list(attrs,predicate)\n if ok:\n hr.maybe()\n push(msg)\n for name,kind,homecls,value in ok:\n try :\n value=getattr(object,name)\n except Exception:\n \n \n push(self._docdescriptor(name,value,mod))\n else :\n push(self.document(value,name,mod,\n funcs,classes,mdict,object))\n push('\\n')\n return attrs\n \n def spilldescriptors(msg,attrs,predicate):\n ok,attrs=_split_list(attrs,predicate)\n if ok:\n hr.maybe()\n push(msg)\n for name,kind,homecls,value in ok:\n push(self._docdescriptor(name,value,mod))\n return attrs\n \n def spilldata(msg,attrs,predicate):\n ok,attrs=_split_list(attrs,predicate)\n if ok:\n hr.maybe()\n push(msg)\n for name,kind,homecls,value in ok:\n base=self.docother(getattr(object,name),name,mod)\n if callable(value)or inspect.isdatadescriptor(value):\n doc=getattr(value,\"__doc__\",None )\n else :\n doc=None\n if doc is None :\n push('<dl><dt>%s</dl>\\n'%base)\n else :\n doc=self.markup(getdoc(value),self.preformat,\n funcs,classes,mdict)\n doc='<dd><tt>%s</tt>'%doc\n push('<dl><dt>%s%s</dl>\\n'%(base,doc))\n push('\\n')\n return attrs\n \n attrs=[(name,kind,cls,value)\n for name,kind,cls,value in classify_class_attrs(object)\n if visiblename(name,obj=object)]\n \n mdict={}\n for key,kind,homecls,value in attrs:\n mdict[key]=anchor='#'+name+'-'+key\n try :\n value=getattr(object,name)\n except Exception:\n \n \n pass\n try :\n \n \n mdict[value]=anchor\n except TypeError:\n pass\n \n while attrs:\n if mro:\n thisclass=mro.popleft()\n else :\n thisclass=attrs[0][2]\n attrs,inherited=_split_list(attrs,lambda t:t[2]is thisclass)\n \n if thisclass is builtins.object:\n attrs=inherited\n continue\n elif thisclass is object:\n tag='defined here'\n else :\n tag='inherited from %s'%self.classlink(thisclass,\n object.__module__)\n tag +=':<br>\\n'\n \n sort_attributes(attrs,object)\n \n \n attrs=spill('Methods %s'%tag,attrs,\n lambda t:t[1]=='method')\n attrs=spill('Class methods %s'%tag,attrs,\n lambda t:t[1]=='class method')\n attrs=spill('Static methods %s'%tag,attrs,\n lambda t:t[1]=='static method')\n attrs=spilldescriptors('Data descriptors %s'%tag,attrs,\n lambda t:t[1]=='data descriptor')\n attrs=spilldata('Data and other attributes %s'%tag,attrs,\n lambda t:t[1]=='data')\n assert attrs ==[]\n attrs=inherited\n \n contents=''.join(contents)\n \n if name ==realname:\n title='<a name=\"%s\">class <strong>%s</strong></a>'%(\n name,realname)\n else :\n title='<strong>%s</strong> = <a name=\"%s\">class %s</a>'%(\n name,name,realname)\n if bases:\n parents=[]\n for base in bases:\n parents.append(self.classlink(base,object.__module__))\n title=title+'(%s)'%', '.join(parents)\n \n decl=''\n try :\n signature=inspect.signature(object)\n except (ValueError,TypeError):\n signature=None\n if signature:\n argspec=str(signature)\n if argspec and argspec !='()':\n decl=name+self.escape(argspec)+'\\n\\n'\n \n doc=getdoc(object)\n if decl:\n doc=decl+(doc or '')\n doc=self.markup(doc,self.preformat,funcs,classes,mdict)\n doc=doc and '<tt>%s<br>&nbsp;</tt>'%doc\n \n return self.section(title,'#000000','#ffc8d8',contents,3,doc)\n \n def formatvalue(self,object):\n ''\n return self.grey('='+self.repr(object))\n \n def docroutine(self,object,name=None ,mod=None ,\n funcs={},classes={},methods={},cl=None ):\n ''\n realname=object.__name__\n name=name or realname\n anchor=(cl and cl.__name__ or '')+'-'+name\n note=''\n skipdocs=0\n if _is_bound_method(object):\n imclass=object.__self__.__class__\n if cl:\n if imclass is not cl:\n note=' from '+self.classlink(imclass,mod)\n else :\n if object.__self__ is not None :\n note=' method of %s instance'%self.classlink(\n object.__self__.__class__,mod)\n else :\n note=' unbound %s method'%self.classlink(imclass,mod)\n \n if name ==realname:\n title='<a name=\"%s\"><strong>%s</strong></a>'%(anchor,realname)\n else :\n if (cl and realname in cl.__dict__ and\n cl.__dict__[realname]is object):\n reallink='<a href=\"#%s\">%s</a>'%(\n cl.__name__+'-'+realname,realname)\n skipdocs=1\n else :\n reallink=realname\n title='<a name=\"%s\"><strong>%s</strong></a> = %s'%(\n anchor,name,reallink)\n argspec=None\n if inspect.isroutine(object):\n try :\n signature=inspect.signature(object)\n except (ValueError,TypeError):\n signature=None\n if signature:\n argspec=str(signature)\n if realname =='<lambda>':\n title='<strong>%s</strong> <em>lambda</em> '%name\n \n \n \n argspec=argspec[1:-1]\n if not argspec:\n argspec='(...)'\n \n decl=title+self.escape(argspec)+(note and self.grey(\n '<font face=\"helvetica, arial\">%s</font>'%note))\n \n if skipdocs:\n return '<dl><dt>%s</dt></dl>\\n'%decl\n else :\n doc=self.markup(\n getdoc(object),self.preformat,funcs,classes,methods)\n doc=doc and '<dd><tt>%s</tt></dd>'%doc\n return '<dl><dt>%s</dt>%s</dl>\\n'%(decl,doc)\n \n def _docdescriptor(self,name,value,mod):\n results=[]\n push=results.append\n \n if name:\n push('<dl><dt><strong>%s</strong></dt>\\n'%name)\n if value.__doc__ is not None :\n doc=self.markup(getdoc(value),self.preformat)\n push('<dd><tt>%s</tt></dd>\\n'%doc)\n push('</dl>\\n')\n \n return ''.join(results)\n \n def docproperty(self,object,name=None ,mod=None ,cl=None ):\n ''\n return self._docdescriptor(name,object,mod)\n \n def docother(self,object,name=None ,mod=None ,*ignored):\n ''\n lhs=name and '<strong>%s</strong> = '%name or ''\n return lhs+self.repr(object)\n \n def docdata(self,object,name=None ,mod=None ,cl=None ):\n ''\n return self._docdescriptor(name,object,mod)\n \n def index(self,dir,shadowed=None ):\n ''\n modpkgs=[]\n if shadowed is None :shadowed={}\n for importer,name,ispkg in pkgutil.iter_modules([dir]):\n if any((0xD800 <=ord(ch)<=0xDFFF)for ch in name):\n \n continue\n modpkgs.append((name,'',ispkg,name in shadowed))\n shadowed[name]=1\n \n modpkgs.sort()\n contents=self.multicolumn(modpkgs,self.modpkglink)\n return self.bigsection(dir,'#ffffff','#ee77aa',contents)\n \n \n \nclass TextRepr(Repr):\n ''\n def __init__(self):\n Repr.__init__(self)\n self.maxlist=self.maxtuple=20\n self.maxdict=10\n self.maxstring=self.maxother=100\n \n def repr1(self,x,level):\n if hasattr(type(x),'__name__'):\n methodname='repr_'+'_'.join(type(x).__name__.split())\n if hasattr(self,methodname):\n return getattr(self,methodname)(x,level)\n return cram(stripid(repr(x)),self.maxother)\n \n def repr_string(self,x,level):\n test=cram(x,self.maxstring)\n testrepr=repr(test)\n if '\\\\'in test and '\\\\'not in replace(testrepr,r'\\\\',''):\n \n \n return 'r'+testrepr[0]+test+testrepr[0]\n return testrepr\n \n repr_str=repr_string\n \n def repr_instance(self,x,level):\n try :\n return cram(stripid(repr(x)),self.maxstring)\n except :\n return '<%s instance>'%x.__class__.__name__\n \nclass TextDoc(Doc):\n ''\n \n \n \n _repr_instance=TextRepr()\n repr=_repr_instance.repr\n \n def bold(self,text):\n ''\n return ''.join(ch+'\\b'+ch for ch in text)\n \n def indent(self,text,prefix=' '):\n ''\n if not text:return ''\n lines=[prefix+line for line in text.split('\\n')]\n if lines:lines[-1]=lines[-1].rstrip()\n return '\\n'.join(lines)\n \n def section(self,title,contents):\n ''\n clean_contents=self.indent(contents).rstrip()\n return self.bold(title)+'\\n'+clean_contents+'\\n\\n'\n \n \n \n def formattree(self,tree,modname,parent=None ,prefix=''):\n ''\n result=''\n for entry in tree:\n if type(entry)is type(()):\n c,bases=entry\n result=result+prefix+classname(c,modname)\n if bases and bases !=(parent,):\n parents=(classname(c,modname)for c in bases)\n result=result+'(%s)'%', '.join(parents)\n result=result+'\\n'\n elif type(entry)is type([]):\n result=result+self.formattree(\n entry,modname,c,prefix+' ')\n return result\n \n def docmodule(self,object,name=None ,mod=None ):\n ''\n name=object.__name__\n synop,desc=splitdoc(getdoc(object))\n result=self.section('NAME',name+(synop and ' - '+synop))\n all=getattr(object,'__all__',None )\n docloc=self.getdocloc(object)\n if docloc is not None :\n result=result+self.section('MODULE REFERENCE',docloc+\"\"\"\n\nThe following documentation is automatically generated from the Python\nsource files. It may be incomplete, incorrect or include features that\nare considered implementation detail and may vary between Python\nimplementations. When in doubt, consult the module reference at the\nlocation listed above.\n\"\"\")\n \n if desc:\n result=result+self.section('DESCRIPTION',desc)\n \n classes=[]\n for key,value in inspect.getmembers(object,inspect.isclass):\n \n if (all is not None\n or (inspect.getmodule(value)or object)is object):\n if visiblename(key,all,object):\n classes.append((key,value))\n funcs=[]\n for key,value in inspect.getmembers(object,inspect.isroutine):\n \n if (all is not None or\n inspect.isbuiltin(value)or inspect.getmodule(value)is object):\n if visiblename(key,all,object):\n funcs.append((key,value))\n data=[]\n for key,value in inspect.getmembers(object,isdata):\n if visiblename(key,all,object):\n data.append((key,value))\n \n modpkgs=[]\n modpkgs_names=set()\n if hasattr(object,'__path__'):\n for importer,modname,ispkg in pkgutil.iter_modules(object.__path__):\n modpkgs_names.add(modname)\n if ispkg:\n modpkgs.append(modname+' (package)')\n else :\n modpkgs.append(modname)\n \n modpkgs.sort()\n result=result+self.section(\n 'PACKAGE CONTENTS','\\n'.join(modpkgs))\n \n \n submodules=[]\n for key,value in inspect.getmembers(object,inspect.ismodule):\n if value.__name__.startswith(name+'.')and key not in modpkgs_names:\n submodules.append(key)\n if submodules:\n submodules.sort()\n result=result+self.section(\n 'SUBMODULES','\\n'.join(submodules))\n \n if classes:\n classlist=[value for key,value in classes]\n contents=[self.formattree(\n inspect.getclasstree(classlist,1),name)]\n for key,value in classes:\n contents.append(self.document(value,key,name))\n result=result+self.section('CLASSES','\\n'.join(contents))\n \n if funcs:\n contents=[]\n for key,value in funcs:\n contents.append(self.document(value,key,name))\n result=result+self.section('FUNCTIONS','\\n'.join(contents))\n \n if data:\n contents=[]\n for key,value in data:\n contents.append(self.docother(value,key,name,maxlen=70))\n result=result+self.section('DATA','\\n'.join(contents))\n \n if hasattr(object,'__version__'):\n version=str(object.__version__)\n if version[:11]=='$'+'Revision: 'and version[-1:]=='$':\n version=version[11:-1].strip()\n result=result+self.section('VERSION',version)\n if hasattr(object,'__date__'):\n result=result+self.section('DATE',str(object.__date__))\n if hasattr(object,'__author__'):\n result=result+self.section('AUTHOR',str(object.__author__))\n if hasattr(object,'__credits__'):\n result=result+self.section('CREDITS',str(object.__credits__))\n try :\n file=inspect.getabsfile(object)\n except TypeError:\n file='(built-in)'\n result=result+self.section('FILE',file)\n return result\n \n def docclass(self,object,name=None ,mod=None ,*ignored):\n ''\n realname=object.__name__\n name=name or realname\n bases=object.__bases__\n \n def makename(c,m=object.__module__):\n return classname(c,m)\n \n if name ==realname:\n title='class '+self.bold(realname)\n else :\n title=self.bold(name)+' = class '+realname\n if bases:\n parents=map(makename,bases)\n title=title+'(%s)'%', '.join(parents)\n \n contents=[]\n push=contents.append\n \n try :\n signature=inspect.signature(object)\n except (ValueError,TypeError):\n signature=None\n if signature:\n argspec=str(signature)\n if argspec and argspec !='()':\n push(name+argspec+'\\n')\n \n doc=getdoc(object)\n if doc:\n push(doc+'\\n')\n \n \n mro=deque(inspect.getmro(object))\n if len(mro)>2:\n push(\"Method resolution order:\")\n for base in mro:\n push(' '+makename(base))\n push('')\n \n \n class HorizontalRule:\n def __init__(self):\n self.needone=0\n def maybe(self):\n if self.needone:\n push('-'*70)\n self.needone=1\n hr=HorizontalRule()\n \n def spill(msg,attrs,predicate):\n ok,attrs=_split_list(attrs,predicate)\n if ok:\n hr.maybe()\n push(msg)\n for name,kind,homecls,value in ok:\n try :\n value=getattr(object,name)\n except Exception:\n \n \n push(self._docdescriptor(name,value,mod))\n else :\n push(self.document(value,\n name,mod,object))\n return attrs\n \n def spilldescriptors(msg,attrs,predicate):\n ok,attrs=_split_list(attrs,predicate)\n if ok:\n hr.maybe()\n push(msg)\n for name,kind,homecls,value in ok:\n push(self._docdescriptor(name,value,mod))\n return attrs\n \n def spilldata(msg,attrs,predicate):\n ok,attrs=_split_list(attrs,predicate)\n if ok:\n hr.maybe()\n push(msg)\n for name,kind,homecls,value in ok:\n if callable(value)or inspect.isdatadescriptor(value):\n doc=getdoc(value)\n else :\n doc=None\n try :\n obj=getattr(object,name)\n except AttributeError:\n obj=homecls.__dict__[name]\n push(self.docother(obj,name,mod,maxlen=70,doc=doc)+\n '\\n')\n return attrs\n \n attrs=[(name,kind,cls,value)\n for name,kind,cls,value in classify_class_attrs(object)\n if visiblename(name,obj=object)]\n \n while attrs:\n if mro:\n thisclass=mro.popleft()\n else :\n thisclass=attrs[0][2]\n attrs,inherited=_split_list(attrs,lambda t:t[2]is thisclass)\n \n if thisclass is builtins.object:\n attrs=inherited\n continue\n elif thisclass is object:\n tag=\"defined here\"\n else :\n tag=\"inherited from %s\"%classname(thisclass,\n object.__module__)\n \n sort_attributes(attrs,object)\n \n \n attrs=spill(\"Methods %s:\\n\"%tag,attrs,\n lambda t:t[1]=='method')\n attrs=spill(\"Class methods %s:\\n\"%tag,attrs,\n lambda t:t[1]=='class method')\n attrs=spill(\"Static methods %s:\\n\"%tag,attrs,\n lambda t:t[1]=='static method')\n attrs=spilldescriptors(\"Data descriptors %s:\\n\"%tag,attrs,\n lambda t:t[1]=='data descriptor')\n attrs=spilldata(\"Data and other attributes %s:\\n\"%tag,attrs,\n lambda t:t[1]=='data')\n \n assert attrs ==[]\n attrs=inherited\n \n contents='\\n'.join(contents)\n if not contents:\n return title+'\\n'\n return title+'\\n'+self.indent(contents.rstrip(),' | ')+'\\n'\n \n def formatvalue(self,object):\n ''\n return '='+self.repr(object)\n \n def docroutine(self,object,name=None ,mod=None ,cl=None ):\n ''\n realname=object.__name__\n name=name or realname\n note=''\n skipdocs=0\n if _is_bound_method(object):\n imclass=object.__self__.__class__\n if cl:\n if imclass is not cl:\n note=' from '+classname(imclass,mod)\n else :\n if object.__self__ is not None :\n note=' method of %s instance'%classname(\n object.__self__.__class__,mod)\n else :\n note=' unbound %s method'%classname(imclass,mod)\n \n if name ==realname:\n title=self.bold(realname)\n else :\n if (cl and realname in cl.__dict__ and\n cl.__dict__[realname]is object):\n skipdocs=1\n title=self.bold(name)+' = '+realname\n argspec=None\n \n if inspect.isroutine(object):\n try :\n signature=inspect.signature(object)\n except (ValueError,TypeError):\n signature=None\n if signature:\n argspec=str(signature)\n if realname =='<lambda>':\n title=self.bold(name)+' lambda '\n \n \n \n argspec=argspec[1:-1]\n if not argspec:\n argspec='(...)'\n decl=title+argspec+note\n \n if skipdocs:\n return decl+'\\n'\n else :\n doc=getdoc(object)or ''\n return decl+'\\n'+(doc and self.indent(doc).rstrip()+'\\n')\n \n def _docdescriptor(self,name,value,mod):\n results=[]\n push=results.append\n \n if name:\n push(self.bold(name))\n push('\\n')\n doc=getdoc(value)or ''\n if doc:\n push(self.indent(doc))\n push('\\n')\n return ''.join(results)\n \n def docproperty(self,object,name=None ,mod=None ,cl=None ):\n ''\n return self._docdescriptor(name,object,mod)\n \n def docdata(self,object,name=None ,mod=None ,cl=None ):\n ''\n return self._docdescriptor(name,object,mod)\n \n def docother(self,object,name=None ,mod=None ,parent=None ,maxlen=None ,doc=None ):\n ''\n repr=self.repr(object)\n if maxlen:\n line=(name and name+' = 'or '')+repr\n chop=maxlen -len(line)\n if chop <0:repr=repr[:chop]+'...'\n line=(name and self.bold(name)+' = 'or '')+repr\n if doc is not None :\n line +='\\n'+self.indent(str(doc))\n return line\n \nclass _PlainTextDoc(TextDoc):\n ''\n def bold(self,text):\n return text\n \n \n \ndef pager(text):\n ''\n global pager\n pager=getpager()\n pager(text)\n \ndef getpager():\n ''\n if not hasattr(sys.stdin,\"isatty\"):\n return plainpager\n if not hasattr(sys.stdout,\"isatty\"):\n return plainpager\n if not sys.stdin.isatty()or not sys.stdout.isatty():\n return plainpager\n use_pager=os.environ.get('MANPAGER')or os.environ.get('PAGER')\n if use_pager:\n if sys.platform =='win32':\n return lambda text:tempfilepager(plain(text),use_pager)\n elif os.environ.get('TERM')in ('dumb','emacs'):\n return lambda text:pipepager(plain(text),use_pager)\n else :\n return lambda text:pipepager(text,use_pager)\n if os.environ.get('TERM')in ('dumb','emacs'):\n return plainpager\n if sys.platform =='win32':\n return lambda text:tempfilepager(plain(text),'more <')\n if hasattr(os,'system')and os.system('(less) 2>/dev/null')==0:\n return lambda text:pipepager(text,'less')\n \n import tempfile\n (fd,filename)=tempfile.mkstemp()\n os.close(fd)\n try :\n if hasattr(os,'system')and os.system('more \"%s\"'%filename)==0:\n return lambda text:pipepager(text,'more')\n else :\n return ttypager\n finally :\n os.unlink(filename)\n \ndef plain(text):\n ''\n return re.sub('.\\b','',text)\n \ndef pipepager(text,cmd):\n ''\n import subprocess\n proc=subprocess.Popen(cmd,shell=True ,stdin=subprocess.PIPE)\n try :\n with io.TextIOWrapper(proc.stdin,errors='backslashreplace')as pipe:\n try :\n pipe.write(text)\n except KeyboardInterrupt:\n \n \n pass\n except OSError:\n pass\n while True :\n try :\n proc.wait()\n break\n except KeyboardInterrupt:\n \n \n pass\n \ndef tempfilepager(text,cmd):\n ''\n import tempfile\n filename=tempfile.mktemp()\n with open(filename,'w',errors='backslashreplace')as file:\n file.write(text)\n try :\n os.system(cmd+' \"'+filename+'\"')\n finally :\n os.unlink(filename)\n \ndef _escape_stdout(text):\n\n encoding=getattr(sys.stdout,'encoding',None )or 'utf-8'\n return text.encode(encoding,'backslashreplace').decode(encoding)\n \ndef ttypager(text):\n ''\n lines=plain(_escape_stdout(text)).split('\\n')\n try :\n import tty\n fd=sys.stdin.fileno()\n old=tty.tcgetattr(fd)\n tty.setcbreak(fd)\n getchar=lambda :sys.stdin.read(1)\n except (ImportError,AttributeError,io.UnsupportedOperation):\n tty=None\n getchar=lambda :sys.stdin.readline()[:-1][:1]\n \n try :\n try :\n h=int(os.environ.get('LINES',0))\n except ValueError:\n h=0\n if h <=1:\n h=25\n r=inc=h -1\n sys.stdout.write('\\n'.join(lines[:inc])+'\\n')\n while lines[r:]:\n sys.stdout.write('-- more --')\n sys.stdout.flush()\n c=getchar()\n \n if c in ('q','Q'):\n sys.stdout.write('\\r \\r')\n break\n elif c in ('\\r','\\n'):\n sys.stdout.write('\\r \\r'+lines[r]+'\\n')\n r=r+1\n continue\n if c in ('b','B','\\x1b'):\n r=r -inc -inc\n if r <0:r=0\n sys.stdout.write('\\n'+'\\n'.join(lines[r:r+inc])+'\\n')\n r=r+inc\n \n finally :\n if tty:\n tty.tcsetattr(fd,tty.TCSAFLUSH,old)\n \ndef plainpager(text):\n ''\n sys.stdout.write(plain(_escape_stdout(text)))\n \ndef describe(thing):\n ''\n if inspect.ismodule(thing):\n if thing.__name__ in sys.builtin_module_names:\n return 'built-in module '+thing.__name__\n if hasattr(thing,'__path__'):\n return 'package '+thing.__name__\n else :\n return 'module '+thing.__name__\n if inspect.isbuiltin(thing):\n return 'built-in function '+thing.__name__\n if inspect.isgetsetdescriptor(thing):\n return 'getset descriptor %s.%s.%s'%(\n thing.__objclass__.__module__,thing.__objclass__.__name__,\n thing.__name__)\n if inspect.ismemberdescriptor(thing):\n return 'member descriptor %s.%s.%s'%(\n thing.__objclass__.__module__,thing.__objclass__.__name__,\n thing.__name__)\n if inspect.isclass(thing):\n return 'class '+thing.__name__\n if inspect.isfunction(thing):\n return 'function '+thing.__name__\n if inspect.ismethod(thing):\n return 'method '+thing.__name__\n return type(thing).__name__\n \ndef locate(path,forceload=0):\n ''\n parts=[part for part in path.split('.')if part]\n module,n=None ,0\n while n <len(parts):\n nextmodule=safeimport('.'.join(parts[:n+1]),forceload)\n if nextmodule:module,n=nextmodule,n+1\n else :break\n if module:\n object=module\n else :\n object=builtins\n for part in parts[n:]:\n try :\n object=getattr(object,part)\n except AttributeError:\n return None\n return object\n \n \n \ntext=TextDoc()\nplaintext=_PlainTextDoc()\nhtml=HTMLDoc()\n\ndef resolve(thing,forceload=0):\n ''\n if isinstance(thing,str):\n object=locate(thing,forceload)\n if object is None :\n raise ImportError('''\\\nNo Python documentation found for %r.\nUse help() to get the interactive help utility.\nUse help(str) for help on the str class.'''%thing)\n return object,thing\n else :\n name=getattr(thing,'__name__',None )\n return thing,name if isinstance(name,str)else None\n \ndef render_doc(thing,title='Python Library Documentation: %s',forceload=0,\nrenderer=None ):\n ''\n if renderer is None :\n renderer=text\n object,name=resolve(thing,forceload)\n desc=describe(object)\n module=inspect.getmodule(object)\n if name and '.'in name:\n desc +=' in '+name[:name.rfind('.')]\n elif module and module is not object:\n desc +=' in module '+module.__name__\n \n if not (inspect.ismodule(object)or\n inspect.isclass(object)or\n inspect.isroutine(object)or\n inspect.isgetsetdescriptor(object)or\n inspect.ismemberdescriptor(object)or\n isinstance(object,property)):\n \n \n object=type(object)\n desc +=' object'\n return title %desc+'\\n\\n'+renderer.document(object,name)\n \ndef doc(thing,title='Python Library Documentation: %s',forceload=0,\noutput=None ):\n ''\n try :\n if output is None :\n pager(render_doc(thing,title,forceload))\n else :\n output.write(render_doc(thing,title,forceload,plaintext))\n except (ImportError,ErrorDuringImport)as value:\n print(value)\n \ndef writedoc(thing,forceload=0):\n ''\n try :\n object,name=resolve(thing,forceload)\n page=html.page(describe(object),html.document(object,name))\n with open(name+'.html','w',encoding='utf-8')as file:\n file.write(page)\n print('wrote',name+'.html')\n except (ImportError,ErrorDuringImport)as value:\n print(value)\n \ndef writedocs(dir,pkgpath='',done=None ):\n ''\n if done is None :done={}\n for importer,modname,ispkg in pkgutil.walk_packages([dir],pkgpath):\n writedoc(modname)\n return\n \nclass Helper:\n\n\n\n\n\n\n\n\n\n\n\n\n keywords={\n 'False':'',\n 'None':'',\n 'True':'',\n 'and':'BOOLEAN',\n 'as':'with',\n 'assert':('assert',''),\n 'async':('async',''),\n 'await':('await',''),\n 'break':('break','while for'),\n 'class':('class','CLASSES SPECIALMETHODS'),\n 'continue':('continue','while for'),\n 'def':('function',''),\n 'del':('del','BASICMETHODS'),\n 'elif':'if',\n 'else':('else','while for'),\n 'except':'try',\n 'finally':'try',\n 'for':('for','break continue while'),\n 'from':'import',\n 'global':('global','nonlocal NAMESPACES'),\n 'if':('if','TRUTHVALUE'),\n 'import':('import','MODULES'),\n 'in':('in','SEQUENCEMETHODS'),\n 'is':'COMPARISON',\n 'lambda':('lambda','FUNCTIONS'),\n 'nonlocal':('nonlocal','global NAMESPACES'),\n 'not':'BOOLEAN',\n 'or':'BOOLEAN',\n 'pass':('pass',''),\n 'raise':('raise','EXCEPTIONS'),\n 'return':('return','FUNCTIONS'),\n 'try':('try','EXCEPTIONS'),\n 'while':('while','break continue if TRUTHVALUE'),\n 'with':('with','CONTEXTMANAGERS EXCEPTIONS yield'),\n 'yield':('yield',''),\n }\n \n \n _strprefixes=[p+q for p in ('b','f','r','u')for q in (\"'\",'\"')]\n _symbols_inverse={\n 'STRINGS':(\"'\",\"'''\",'\"','\"\"\"',*_strprefixes),\n 'OPERATORS':('+','-','*','**','/','//','%','<<','>>','&',\n '|','^','~','<','>','<=','>=','==','!=','<>'),\n 'COMPARISON':('<','>','<=','>=','==','!=','<>'),\n 'UNARY':('-','~'),\n 'AUGMENTEDASSIGNMENT':('+=','-=','*=','/=','%=','&=','|=',\n '^=','<<=','>>=','**=','//='),\n 'BITWISE':('<<','>>','&','|','^','~'),\n 'COMPLEX':('j','J')\n }\n symbols={\n '%':'OPERATORS FORMATTING',\n '**':'POWER',\n ',':'TUPLES LISTS FUNCTIONS',\n '.':'ATTRIBUTES FLOAT MODULES OBJECTS',\n '...':'ELLIPSIS',\n ':':'SLICINGS DICTIONARYLITERALS',\n '@':'def class',\n '\\\\':'STRINGS',\n '_':'PRIVATENAMES',\n '__':'PRIVATENAMES SPECIALMETHODS',\n '`':'BACKQUOTES',\n '(':'TUPLES FUNCTIONS CALLS',\n ')':'TUPLES FUNCTIONS CALLS',\n '[':'LISTS SUBSCRIPTS SLICINGS',\n ']':'LISTS SUBSCRIPTS SLICINGS'\n }\n for topic,symbols_ in _symbols_inverse.items():\n for symbol in symbols_:\n topics=symbols.get(symbol,topic)\n if topic not in topics:\n topics=topics+' '+topic\n symbols[symbol]=topics\n \n topics={\n 'TYPES':('types','STRINGS UNICODE NUMBERS SEQUENCES MAPPINGS '\n 'FUNCTIONS CLASSES MODULES FILES inspect'),\n 'STRINGS':('strings','str UNICODE SEQUENCES STRINGMETHODS '\n 'FORMATTING TYPES'),\n 'STRINGMETHODS':('string-methods','STRINGS FORMATTING'),\n 'FORMATTING':('formatstrings','OPERATORS'),\n 'UNICODE':('strings','encodings unicode SEQUENCES STRINGMETHODS '\n 'FORMATTING TYPES'),\n 'NUMBERS':('numbers','INTEGER FLOAT COMPLEX TYPES'),\n 'INTEGER':('integers','int range'),\n 'FLOAT':('floating','float math'),\n 'COMPLEX':('imaginary','complex cmath'),\n 'SEQUENCES':('typesseq','STRINGMETHODS FORMATTING range LISTS'),\n 'MAPPINGS':'DICTIONARIES',\n 'FUNCTIONS':('typesfunctions','def TYPES'),\n 'METHODS':('typesmethods','class def CLASSES TYPES'),\n 'CODEOBJECTS':('bltin-code-objects','compile FUNCTIONS TYPES'),\n 'TYPEOBJECTS':('bltin-type-objects','types TYPES'),\n 'FRAMEOBJECTS':'TYPES',\n 'TRACEBACKS':'TYPES',\n 'NONE':('bltin-null-object',''),\n 'ELLIPSIS':('bltin-ellipsis-object','SLICINGS'),\n 'SPECIALATTRIBUTES':('specialattrs',''),\n 'CLASSES':('types','class SPECIALMETHODS PRIVATENAMES'),\n 'MODULES':('typesmodules','import'),\n 'PACKAGES':'import',\n 'EXPRESSIONS':('operator-summary','lambda or and not in is BOOLEAN '\n 'COMPARISON BITWISE SHIFTING BINARY FORMATTING POWER '\n 'UNARY ATTRIBUTES SUBSCRIPTS SLICINGS CALLS TUPLES '\n 'LISTS DICTIONARIES'),\n 'OPERATORS':'EXPRESSIONS',\n 'PRECEDENCE':'EXPRESSIONS',\n 'OBJECTS':('objects','TYPES'),\n 'SPECIALMETHODS':('specialnames','BASICMETHODS ATTRIBUTEMETHODS '\n 'CALLABLEMETHODS SEQUENCEMETHODS MAPPINGMETHODS '\n 'NUMBERMETHODS CLASSES'),\n 'BASICMETHODS':('customization','hash repr str SPECIALMETHODS'),\n 'ATTRIBUTEMETHODS':('attribute-access','ATTRIBUTES SPECIALMETHODS'),\n 'CALLABLEMETHODS':('callable-types','CALLS SPECIALMETHODS'),\n 'SEQUENCEMETHODS':('sequence-types','SEQUENCES SEQUENCEMETHODS '\n 'SPECIALMETHODS'),\n 'MAPPINGMETHODS':('sequence-types','MAPPINGS SPECIALMETHODS'),\n 'NUMBERMETHODS':('numeric-types','NUMBERS AUGMENTEDASSIGNMENT '\n 'SPECIALMETHODS'),\n 'EXECUTION':('execmodel','NAMESPACES DYNAMICFEATURES EXCEPTIONS'),\n 'NAMESPACES':('naming','global nonlocal ASSIGNMENT DELETION DYNAMICFEATURES'),\n 'DYNAMICFEATURES':('dynamic-features',''),\n 'SCOPING':'NAMESPACES',\n 'FRAMES':'NAMESPACES',\n 'EXCEPTIONS':('exceptions','try except finally raise'),\n 'CONVERSIONS':('conversions',''),\n 'IDENTIFIERS':('identifiers','keywords SPECIALIDENTIFIERS'),\n 'SPECIALIDENTIFIERS':('id-classes',''),\n 'PRIVATENAMES':('atom-identifiers',''),\n 'LITERALS':('atom-literals','STRINGS NUMBERS TUPLELITERALS '\n 'LISTLITERALS DICTIONARYLITERALS'),\n 'TUPLES':'SEQUENCES',\n 'TUPLELITERALS':('exprlists','TUPLES LITERALS'),\n 'LISTS':('typesseq-mutable','LISTLITERALS'),\n 'LISTLITERALS':('lists','LISTS LITERALS'),\n 'DICTIONARIES':('typesmapping','DICTIONARYLITERALS'),\n 'DICTIONARYLITERALS':('dict','DICTIONARIES LITERALS'),\n 'ATTRIBUTES':('attribute-references','getattr hasattr setattr ATTRIBUTEMETHODS'),\n 'SUBSCRIPTS':('subscriptions','SEQUENCEMETHODS'),\n 'SLICINGS':('slicings','SEQUENCEMETHODS'),\n 'CALLS':('calls','EXPRESSIONS'),\n 'POWER':('power','EXPRESSIONS'),\n 'UNARY':('unary','EXPRESSIONS'),\n 'BINARY':('binary','EXPRESSIONS'),\n 'SHIFTING':('shifting','EXPRESSIONS'),\n 'BITWISE':('bitwise','EXPRESSIONS'),\n 'COMPARISON':('comparisons','EXPRESSIONS BASICMETHODS'),\n 'BOOLEAN':('booleans','EXPRESSIONS TRUTHVALUE'),\n 'ASSERTION':'assert',\n 'ASSIGNMENT':('assignment','AUGMENTEDASSIGNMENT'),\n 'AUGMENTEDASSIGNMENT':('augassign','NUMBERMETHODS'),\n 'DELETION':'del',\n 'RETURNING':'return',\n 'IMPORTING':'import',\n 'CONDITIONAL':'if',\n 'LOOPING':('compound','for while break continue'),\n 'TRUTHVALUE':('truth','if while and or not BASICMETHODS'),\n 'DEBUGGING':('debugger','pdb'),\n 'CONTEXTMANAGERS':('context-managers','with'),\n }\n \n def __init__(self,input=None ,output=None ):\n self._input=input\n self._output=output\n \n @property\n def input(self):\n return self._input or sys.stdin\n \n @property\n def output(self):\n return self._output or sys.stdout\n \n def __repr__(self):\n if inspect.stack()[1][3]=='?':\n self()\n return ''\n return '<%s.%s instance>'%(self.__class__.__module__,\n self.__class__.__qualname__)\n \n _GoInteractive=object()\n def __call__(self,request=_GoInteractive):\n if request is not self._GoInteractive:\n self.help(request)\n else :\n self.intro()\n self.interact()\n self.output.write('''\nYou are now leaving help and returning to the Python interpreter.\nIf you want to ask for help on a particular object directly from the\ninterpreter, you can type \"help(object)\". Executing \"help('string')\"\nhas the same effect as typing a particular string at the help> prompt.\n''')\n \n def interact(self):\n self.output.write('\\n')\n while True :\n try :\n request=self.getline('help> ')\n if not request:break\n except (KeyboardInterrupt,EOFError):\n break\n request=request.strip()\n \n \n \n if (len(request)>2 and request[0]==request[-1]in (\"'\",'\"')\n and request[0]not in request[1:-1]):\n request=request[1:-1]\n if request.lower()in ('q','quit'):break\n if request =='help':\n self.intro()\n else :\n self.help(request)\n \n def getline(self,prompt):\n ''\n if self.input is sys.stdin:\n return input(prompt)\n else :\n self.output.write(prompt)\n self.output.flush()\n return self.input.readline()\n \n def help(self,request):\n if type(request)is type(''):\n request=request.strip()\n if request =='keywords':self.listkeywords()\n elif request =='symbols':self.listsymbols()\n elif request =='topics':self.listtopics()\n elif request =='modules':self.listmodules()\n elif request[:8]=='modules ':\n self.listmodules(request.split()[1])\n elif request in self.symbols:self.showsymbol(request)\n elif request in ['True','False','None']:\n \n doc(eval(request),'Help on %s:')\n elif request in self.keywords:self.showtopic(request)\n elif request in self.topics:self.showtopic(request)\n elif request:doc(request,'Help on %s:',output=self._output)\n else :doc(str,'Help on %s:',output=self._output)\n elif isinstance(request,Helper):self()\n else :doc(request,'Help on %s:',output=self._output)\n self.output.write('\\n')\n \n def intro(self):\n self.output.write('''\nWelcome to Python {0}'s help utility!\n\nIf this is your first time using Python, you should definitely check out\nthe tutorial on the Internet at https://docs.python.org/{0}/tutorial/.\n\nEnter the name of any module, keyword, or topic to get help on writing\nPython programs and using Python modules. To quit this help utility and\nreturn to the interpreter, just type \"quit\".\n\nTo get a list of available modules, keywords, symbols, or topics, type\n\"modules\", \"keywords\", \"symbols\", or \"topics\". Each module also comes\nwith a one-line summary of what it does; to list the modules whose name\nor summary contain a given string such as \"spam\", type \"modules spam\".\n'''.format('%d.%d'%sys.version_info[:2]))\n \n def list(self,items,columns=4,width=80):\n items=list(sorted(items))\n colw=width //columns\n rows=(len(items)+columns -1)//columns\n for row in range(rows):\n for col in range(columns):\n i=col *rows+row\n if i <len(items):\n self.output.write(items[i])\n if col <columns -1:\n self.output.write(' '+' '*(colw -1 -len(items[i])))\n self.output.write('\\n')\n \n def listkeywords(self):\n self.output.write('''\nHere is a list of the Python keywords. Enter any keyword to get more help.\n\n''')\n self.list(self.keywords.keys())\n \n def listsymbols(self):\n self.output.write('''\nHere is a list of the punctuation symbols which Python assigns special meaning\nto. Enter any symbol to get more help.\n\n''')\n self.list(self.symbols.keys())\n \n def listtopics(self):\n self.output.write('''\nHere is a list of available topics. Enter any topic name to get more help.\n\n''')\n self.list(self.topics.keys())\n \n def showtopic(self,topic,more_xrefs=''):\n try :\n import pydoc_data.topics\n except ImportError:\n self.output.write('''\nSorry, topic and keyword documentation is not available because the\nmodule \"pydoc_data.topics\" could not be found.\n''')\n return\n target=self.topics.get(topic,self.keywords.get(topic))\n if not target:\n self.output.write('no documentation found for %s\\n'%repr(topic))\n return\n if type(target)is type(''):\n return self.showtopic(target,more_xrefs)\n \n label,xrefs=target\n try :\n doc=pydoc_data.topics.topics[label]\n except KeyError:\n self.output.write('no documentation found for %s\\n'%repr(topic))\n return\n pager(doc.strip()+'\\n')\n if more_xrefs:\n xrefs=(xrefs or '')+' '+more_xrefs\n if xrefs:\n import textwrap\n text='Related help topics: '+', '.join(xrefs.split())+'\\n'\n wrapped_text=textwrap.wrap(text,72)\n self.output.write('\\n%s\\n'%''.join(wrapped_text))\n \n def _gettopic(self,topic,more_xrefs=''):\n ''\n\n\n\n\n\n\n \n try :\n import pydoc_data.topics\n except ImportError:\n return ('''\nSorry, topic and keyword documentation is not available because the\nmodule \"pydoc_data.topics\" could not be found.\n''','')\n target=self.topics.get(topic,self.keywords.get(topic))\n if not target:\n raise ValueError('could not find topic')\n if isinstance(target,str):\n return self._gettopic(target,more_xrefs)\n label,xrefs=target\n doc=pydoc_data.topics.topics[label]\n if more_xrefs:\n xrefs=(xrefs or '')+' '+more_xrefs\n return doc,xrefs\n \n def showsymbol(self,symbol):\n target=self.symbols[symbol]\n topic,_,xrefs=target.partition(' ')\n self.showtopic(topic,xrefs)\n \n def listmodules(self,key=''):\n if key:\n self.output.write('''\nHere is a list of modules whose name or summary contains '{}'.\nIf there are any, enter a module name to get more help.\n\n'''.format(key))\n apropos(key)\n else :\n self.output.write('''\nPlease wait a moment while I gather a list of all available modules...\n\n''')\n modules={}\n def callback(path,modname,desc,modules=modules):\n if modname and modname[-9:]=='.__init__':\n modname=modname[:-9]+' (package)'\n if modname.find('.')<0:\n modules[modname]=1\n def onerror(modname):\n callback(None ,modname,None )\n ModuleScanner().run(callback,onerror=onerror)\n self.list(modules.keys())\n self.output.write('''\nEnter any module name to get more help. Or, type \"modules spam\" to search\nfor modules whose name or summary contain the string \"spam\".\n''')\n \nhelp=Helper()\n\nclass ModuleScanner:\n ''\n \n def run(self,callback,key=None ,completer=None ,onerror=None ):\n if key:key=key.lower()\n self.quit=False\n seen={}\n \n for modname in sys.builtin_module_names:\n if modname !='__main__':\n seen[modname]=1\n if key is None :\n callback(None ,modname,'')\n else :\n name=__import__(modname).__doc__ or ''\n desc=name.split('\\n')[0]\n name=modname+' - '+desc\n if name.lower().find(key)>=0:\n callback(None ,modname,desc)\n \n for importer,modname,ispkg in pkgutil.walk_packages(onerror=onerror):\n if self.quit:\n break\n \n if key is None :\n callback(None ,modname,'')\n else :\n try :\n spec=pkgutil._get_spec(importer,modname)\n except SyntaxError:\n \n continue\n loader=spec.loader\n if hasattr(loader,'get_source'):\n try :\n source=loader.get_source(modname)\n except Exception:\n if onerror:\n onerror(modname)\n continue\n desc=source_synopsis(io.StringIO(source))or ''\n if hasattr(loader,'get_filename'):\n path=loader.get_filename(modname)\n else :\n path=None\n else :\n try :\n module=importlib._bootstrap._load(spec)\n except ImportError:\n if onerror:\n onerror(modname)\n continue\n desc=module.__doc__.splitlines()[0]if module.__doc__ else ''\n path=getattr(module,'__file__',None )\n name=modname+' - '+desc\n if name.lower().find(key)>=0:\n callback(path,modname,desc)\n \n if completer:\n completer()\n \ndef apropos(key):\n ''\n def callback(path,modname,desc):\n if modname[-9:]=='.__init__':\n modname=modname[:-9]+' (package)'\n print(modname,desc and '- '+desc)\n def onerror(modname):\n pass\n with warnings.catch_warnings():\n warnings.filterwarnings('ignore')\n ModuleScanner().run(callback,key,onerror=onerror)\n \n \n \ndef _start_server(urlhandler,hostname,port):\n ''\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n \n import http.server\n import email.message\n import select\n import threading\n \n class DocHandler(http.server.BaseHTTPRequestHandler):\n \n def do_GET(self):\n ''\n\n\n\n \n if self.path.endswith('.css'):\n content_type='text/css'\n else :\n content_type='text/html'\n self.send_response(200)\n self.send_header('Content-Type','%s; charset=UTF-8'%content_type)\n self.end_headers()\n self.wfile.write(self.urlhandler(\n self.path,content_type).encode('utf-8'))\n \n def log_message(self,*args):\n \n pass\n \n class DocServer(http.server.HTTPServer):\n \n def __init__(self,host,port,callback):\n self.host=host\n self.address=(self.host,port)\n self.callback=callback\n self.base.__init__(self,self.address,self.handler)\n self.quit=False\n \n def serve_until_quit(self):\n while not self.quit:\n rd,wr,ex=select.select([self.socket.fileno()],[],[],1)\n if rd:\n self.handle_request()\n self.server_close()\n \n def server_activate(self):\n self.base.server_activate(self)\n if self.callback:\n self.callback(self)\n \n class ServerThread(threading.Thread):\n \n def __init__(self,urlhandler,host,port):\n self.urlhandler=urlhandler\n self.host=host\n self.port=int(port)\n threading.Thread.__init__(self)\n self.serving=False\n self.error=None\n \n def run(self):\n ''\n try :\n DocServer.base=http.server.HTTPServer\n DocServer.handler=DocHandler\n DocHandler.MessageClass=email.message.Message\n DocHandler.urlhandler=staticmethod(self.urlhandler)\n docsvr=DocServer(self.host,self.port,self.ready)\n self.docserver=docsvr\n docsvr.serve_until_quit()\n except Exception as e:\n self.error=e\n \n def ready(self,server):\n self.serving=True\n self.host=server.host\n self.port=server.server_port\n self.url='http://%s:%d/'%(self.host,self.port)\n \n def stop(self):\n ''\n self.docserver.quit=True\n self.join()\n \n \n self.docserver=None\n self.serving=False\n self.url=None\n \n thread=ServerThread(urlhandler,hostname,port)\n thread.start()\n \n \n while not thread.error and not thread.serving:\n time.sleep(.01)\n return thread\n \n \ndef _url_handler(url,content_type=\"text/html\"):\n ''\n\n\n\n\n\n\n \n class _HTMLDoc(HTMLDoc):\n \n def page(self,title,contents):\n ''\n css_path=\"pydoc_data/_pydoc.css\"\n css_link=(\n '<link rel=\"stylesheet\" type=\"text/css\" href=\"%s\">'%\n css_path)\n return '''\\\n<!DOCTYPE html PUBLIC \"-//W3C//DTD HTML 4.0 Transitional//EN\">\n<html><head><title>Pydoc: %s</title>\n<meta http-equiv=\"Content-Type\" content=\"text/html; charset=utf-8\">\n%s</head><body bgcolor=\"#f0f0f8\">%s<div style=\"clear:both;padding-top:.5em;\">%s</div>\n</body></html>'''%(title,css_link,html_navbar(),contents)\n \n def filelink(self,url,path):\n return '<a href=\"getfile?key=%s\">%s</a>'%(url,path)\n \n \n html=_HTMLDoc()\n \n def html_navbar():\n version=html.escape(\"%s [%s, %s]\"%(platform.python_version(),\n platform.python_build()[0],\n platform.python_compiler()))\n return \"\"\"\n <div style='float:left'>\n Python %s<br>%s\n </div>\n <div style='float:right'>\n <div style='text-align:center'>\n <a href=\"index.html\">Module Index</a>\n : <a href=\"topics.html\">Topics</a>\n : <a href=\"keywords.html\">Keywords</a>\n </div>\n <div>\n <form action=\"get\" style='display:inline;'>\n <input type=text name=key size=15>\n <input type=submit value=\"Get\">\n </form>&nbsp;\n <form action=\"search\" style='display:inline;'>\n <input type=text name=key size=15>\n <input type=submit value=\"Search\">\n </form>\n </div>\n </div>\n \"\"\"%(version,html.escape(platform.platform(terse=True )))\n \n def html_index():\n ''\n \n def bltinlink(name):\n return '<a href=\"%s.html\">%s</a>'%(name,name)\n \n heading=html.heading(\n '<big><big><strong>Index of Modules</strong></big></big>',\n '#ffffff','#7799ee')\n names=[name for name in sys.builtin_module_names\n if name !='__main__']\n contents=html.multicolumn(names,bltinlink)\n contents=[heading,'<p>'+html.bigsection(\n 'Built-in Modules','#ffffff','#ee77aa',contents)]\n \n seen={}\n for dir in sys.path:\n contents.append(html.index(dir,seen))\n \n contents.append(\n '<p align=right><font color=\"#909090\" face=\"helvetica,'\n 'arial\"><strong>pydoc</strong> by Ka-Ping Yee'\n '&lt;ping@lfw.org&gt;</font>')\n return 'Index of Modules',''.join(contents)\n \n def html_search(key):\n ''\n \n search_result=[]\n \n def callback(path,modname,desc):\n if modname[-9:]=='.__init__':\n modname=modname[:-9]+' (package)'\n search_result.append((modname,desc and '- '+desc))\n \n with warnings.catch_warnings():\n warnings.filterwarnings('ignore')\n def onerror(modname):\n pass\n ModuleScanner().run(callback,key,onerror=onerror)\n \n \n def bltinlink(name):\n return '<a href=\"%s.html\">%s</a>'%(name,name)\n \n results=[]\n heading=html.heading(\n '<big><big><strong>Search Results</strong></big></big>',\n '#ffffff','#7799ee')\n for name,desc in search_result:\n results.append(bltinlink(name)+desc)\n contents=heading+html.bigsection(\n 'key = %s'%key,'#ffffff','#ee77aa','<br>'.join(results))\n return 'Search Results',contents\n \n def html_getfile(path):\n ''\n path=urllib.parse.unquote(path)\n with tokenize.open(path)as fp:\n lines=html.escape(fp.read())\n body='<pre>%s</pre>'%lines\n heading=html.heading(\n '<big><big><strong>File Listing</strong></big></big>',\n '#ffffff','#7799ee')\n contents=heading+html.bigsection(\n 'File: %s'%path,'#ffffff','#ee77aa',body)\n return 'getfile %s'%path,contents\n \n def html_topics():\n ''\n \n def bltinlink(name):\n return '<a href=\"topic?key=%s\">%s</a>'%(name,name)\n \n heading=html.heading(\n '<big><big><strong>INDEX</strong></big></big>',\n '#ffffff','#7799ee')\n names=sorted(Helper.topics.keys())\n \n contents=html.multicolumn(names,bltinlink)\n contents=heading+html.bigsection(\n 'Topics','#ffffff','#ee77aa',contents)\n return 'Topics',contents\n \n def html_keywords():\n ''\n heading=html.heading(\n '<big><big><strong>INDEX</strong></big></big>',\n '#ffffff','#7799ee')\n names=sorted(Helper.keywords.keys())\n \n def bltinlink(name):\n return '<a href=\"topic?key=%s\">%s</a>'%(name,name)\n \n contents=html.multicolumn(names,bltinlink)\n contents=heading+html.bigsection(\n 'Keywords','#ffffff','#ee77aa',contents)\n return 'Keywords',contents\n \n def html_topicpage(topic):\n ''\n buf=io.StringIO()\n htmlhelp=Helper(buf,buf)\n contents,xrefs=htmlhelp._gettopic(topic)\n if topic in htmlhelp.keywords:\n title='KEYWORD'\n else :\n title='TOPIC'\n heading=html.heading(\n '<big><big><strong>%s</strong></big></big>'%title,\n '#ffffff','#7799ee')\n contents='<pre>%s</pre>'%html.markup(contents)\n contents=html.bigsection(topic,'#ffffff','#ee77aa',contents)\n if xrefs:\n xrefs=sorted(xrefs.split())\n \n def bltinlink(name):\n return '<a href=\"topic?key=%s\">%s</a>'%(name,name)\n \n xrefs=html.multicolumn(xrefs,bltinlink)\n xrefs=html.section('Related help topics: ',\n '#ffffff','#ee77aa',xrefs)\n return ('%s %s'%(title,topic),\n ''.join((heading,contents,xrefs)))\n \n def html_getobj(url):\n obj=locate(url,forceload=1)\n if obj is None and url !='None':\n raise ValueError('could not find object')\n title=describe(obj)\n content=html.document(obj,url)\n return title,content\n \n def html_error(url,exc):\n heading=html.heading(\n '<big><big><strong>Error</strong></big></big>',\n '#ffffff','#7799ee')\n contents='<br>'.join(html.escape(line)for line in\n format_exception_only(type(exc),exc))\n contents=heading+html.bigsection(url,'#ffffff','#bb0000',\n contents)\n return \"Error - %s\"%url,contents\n \n def get_html_page(url):\n ''\n complete_url=url\n if url.endswith('.html'):\n url=url[:-5]\n try :\n if url in (\"\",\"index\"):\n title,content=html_index()\n elif url ==\"topics\":\n title,content=html_topics()\n elif url ==\"keywords\":\n title,content=html_keywords()\n elif '='in url:\n op,_,url=url.partition('=')\n if op ==\"search?key\":\n title,content=html_search(url)\n elif op ==\"getfile?key\":\n title,content=html_getfile(url)\n elif op ==\"topic?key\":\n \n try :\n title,content=html_topicpage(url)\n except ValueError:\n title,content=html_getobj(url)\n elif op ==\"get?key\":\n \n if url in (\"\",\"index\"):\n title,content=html_index()\n else :\n try :\n title,content=html_getobj(url)\n except ValueError:\n title,content=html_topicpage(url)\n else :\n raise ValueError('bad pydoc url')\n else :\n title,content=html_getobj(url)\n except Exception as exc:\n \n title,content=html_error(complete_url,exc)\n return html.page(title,content)\n \n if url.startswith('/'):\n url=url[1:]\n if content_type =='text/css':\n path_here=os.path.dirname(os.path.realpath(__file__))\n css_path=os.path.join(path_here,url)\n with open(css_path)as fp:\n return ''.join(fp.readlines())\n elif content_type =='text/html':\n return get_html_page(url)\n \n raise TypeError('unknown content type %r for url %s'%(content_type,url))\n \n \ndef browse(port=0,*,open_browser=True ,hostname='localhost'):\n ''\n\n\n\n \n import webbrowser\n serverthread=_start_server(_url_handler,hostname,port)\n if serverthread.error:\n print(serverthread.error)\n return\n if serverthread.serving:\n server_help_msg='Server commands: [b]rowser, [q]uit'\n if open_browser:\n webbrowser.open(serverthread.url)\n try :\n print('Server ready at',serverthread.url)\n print(server_help_msg)\n while serverthread.serving:\n cmd=input('server> ')\n cmd=cmd.lower()\n if cmd =='q':\n break\n elif cmd =='b':\n webbrowser.open(serverthread.url)\n else :\n print(server_help_msg)\n except (KeyboardInterrupt,EOFError):\n print()\n finally :\n if serverthread.serving:\n serverthread.stop()\n print('Server stopped')\n \n \n \n \ndef ispath(x):\n return isinstance(x,str)and x.find(os.sep)>=0\n \ndef _get_revised_path(given_path,argv0):\n ''\n\n\n\n\n \n \n \n \n \n \n \n if ''in given_path or os.curdir in given_path or os.getcwd()in given_path:\n return None\n \n \n \n stdlib_dir=os.path.dirname(__file__)\n script_dir=os.path.dirname(argv0)\n revised_path=given_path.copy()\n if script_dir in given_path and not os.path.samefile(script_dir,stdlib_dir):\n revised_path.remove(script_dir)\n revised_path.insert(0,os.getcwd())\n return revised_path\n \n \n \ndef _adjust_cli_sys_path():\n ''\n\n\n \n revised_path=_get_revised_path(sys.path,sys.argv[0])\n if revised_path is not None :\n sys.path[:]=revised_path\n \n \ndef cli():\n ''\n import getopt\n class BadUsage(Exception):pass\n \n _adjust_cli_sys_path()\n \n try :\n opts,args=getopt.getopt(sys.argv[1:],'bk:n:p:w')\n writing=False\n start_server=False\n open_browser=False\n port=0\n hostname='localhost'\n for opt,val in opts:\n if opt =='-b':\n start_server=True\n open_browser=True\n if opt =='-k':\n apropos(val)\n return\n if opt =='-p':\n start_server=True\n port=val\n if opt =='-w':\n writing=True\n if opt =='-n':\n start_server=True\n hostname=val\n \n if start_server:\n browse(port,hostname=hostname,open_browser=open_browser)\n return\n \n if not args:raise BadUsage\n for arg in args:\n if ispath(arg)and not os.path.exists(arg):\n print('file %r does not exist'%arg)\n break\n try :\n if ispath(arg)and os.path.isfile(arg):\n arg=importfile(arg)\n if writing:\n if ispath(arg)and os.path.isdir(arg):\n writedocs(arg)\n else :\n writedoc(arg)\n else :\n help.help(arg)\n except ErrorDuringImport as value:\n print(value)\n \n except (getopt.error,BadUsage):\n cmd=os.path.splitext(os.path.basename(sys.argv[0]))[0]\n print(\"\"\"pydoc - the Python documentation tool\n\n{cmd} <name> ...\n Show text documentation on something. <name> may be the name of a\n Python keyword, topic, function, module, or package, or a dotted\n reference to a class or function within a module or module in a\n package. If <name> contains a '{sep}', it is used as the path to a\n Python source file to document. If name is 'keywords', 'topics',\n or 'modules', a listing of these things is displayed.\n\n{cmd} -k <keyword>\n Search for a keyword in the synopsis lines of all available modules.\n\n{cmd} -n <hostname>\n Start an HTTP server with the given hostname (default: localhost).\n\n{cmd} -p <port>\n Start an HTTP server on the given port on the local machine. Port\n number 0 can be used to get an arbitrary unused port.\n\n{cmd} -b\n Start an HTTP server on an arbitrary unused port and open a Web browser\n to interactively browse documentation. This option can be used in\n combination with -n and/or -p.\n\n{cmd} -w <name> ...\n Write out the HTML documentation for a module to a file in the current\n directory. If <name> contains a '{sep}', it is treated as a filename; if\n it names a directory, documentation is written for all the contents.\n\"\"\".format(cmd=cmd,sep=os.sep))\n \nif __name__ =='__main__':\n cli()\n", ["builtins", "collections", "email.message", "getopt", "http.server", "importlib._bootstrap", "importlib._bootstrap_external", "importlib.machinery", "importlib.util", "inspect", "io", "os", "pkgutil", "platform", "pydoc_data.topics", "re", "reprlib", "select", "subprocess", "sys", "tempfile", "textwrap", "threading", "time", "tokenize", "traceback", "tty", "urllib.parse", "warnings", "webbrowser"]], "_sre_utils": [".js", "var $module=(function($B){\n\n function unicode_iscased(cp){\n // cp : Unicode code point\n var letter = String.fromCodePoint(cp)\n return (letter != letter.toLowerCase() ||\n letter != letter.toUpperCase())\n }\n\n function ascii_iscased(cp){\n if(cp > 255){return false}\n return unicode_iscased(cp)\n }\n\n function unicode_tolower(cp){\n var letter = String.fromCodePoint(cp),\n lower = letter.toLowerCase()\n return lower.charCodeAt(0)\n }\n\n function ascii_tolower(cp){\n return unicode_tolower(cp)\n }\n\nreturn {\n unicode_iscased: unicode_iscased,\n ascii_iscased: ascii_iscased,\n unicode_tolower: unicode_tolower,\n ascii_tolower: ascii_tolower\n}\n\n}\n\n)(__BRYTHON__)"], "email.charset": [".py", "\n\n\n\n__all__=[\n'Charset',\n'add_alias',\n'add_charset',\n'add_codec',\n]\n\nfrom functools import partial\n\nimport email.base64mime\nimport email.quoprimime\n\nfrom email import errors\nfrom email.encoders import encode_7or8bit\n\n\n\n\nQP=1\nBASE64=2\nSHORTEST=3\n\n\nRFC2047_CHROME_LEN=7\n\nDEFAULT_CHARSET='us-ascii'\nUNKNOWN8BIT='unknown-8bit'\nEMPTYSTRING=''\n\n\n\n\nCHARSETS={\n\n'iso-8859-1':(QP,QP,None ),\n'iso-8859-2':(QP,QP,None ),\n'iso-8859-3':(QP,QP,None ),\n'iso-8859-4':(QP,QP,None ),\n\n\n\n\n'iso-8859-9':(QP,QP,None ),\n'iso-8859-10':(QP,QP,None ),\n\n'iso-8859-13':(QP,QP,None ),\n'iso-8859-14':(QP,QP,None ),\n'iso-8859-15':(QP,QP,None ),\n'iso-8859-16':(QP,QP,None ),\n'windows-1252':(QP,QP,None ),\n'viscii':(QP,QP,None ),\n'us-ascii':(None ,None ,None ),\n'big5':(BASE64,BASE64,None ),\n'gb2312':(BASE64,BASE64,None ),\n'euc-jp':(BASE64,None ,'iso-2022-jp'),\n'shift_jis':(BASE64,None ,'iso-2022-jp'),\n'iso-2022-jp':(BASE64,None ,None ),\n'koi8-r':(BASE64,BASE64,None ),\n'utf-8':(SHORTEST,BASE64,'utf-8'),\n}\n\n\n\nALIASES={\n'latin_1':'iso-8859-1',\n'latin-1':'iso-8859-1',\n'latin_2':'iso-8859-2',\n'latin-2':'iso-8859-2',\n'latin_3':'iso-8859-3',\n'latin-3':'iso-8859-3',\n'latin_4':'iso-8859-4',\n'latin-4':'iso-8859-4',\n'latin_5':'iso-8859-9',\n'latin-5':'iso-8859-9',\n'latin_6':'iso-8859-10',\n'latin-6':'iso-8859-10',\n'latin_7':'iso-8859-13',\n'latin-7':'iso-8859-13',\n'latin_8':'iso-8859-14',\n'latin-8':'iso-8859-14',\n'latin_9':'iso-8859-15',\n'latin-9':'iso-8859-15',\n'latin_10':'iso-8859-16',\n'latin-10':'iso-8859-16',\n'cp949':'ks_c_5601-1987',\n'euc_jp':'euc-jp',\n'euc_kr':'euc-kr',\n'ascii':'us-ascii',\n}\n\n\n\nCODEC_MAP={\n'gb2312':'eucgb2312_cn',\n'big5':'big5_tw',\n\n\n\n'us-ascii':None ,\n}\n\n\n\n\ndef add_charset(charset,header_enc=None ,body_enc=None ,output_charset=None ):\n ''\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n \n if body_enc ==SHORTEST:\n raise ValueError('SHORTEST not allowed for body_enc')\n CHARSETS[charset]=(header_enc,body_enc,output_charset)\n \n \ndef add_alias(alias,canonical):\n ''\n\n\n\n \n ALIASES[alias]=canonical\n \n \ndef add_codec(charset,codecname):\n ''\n\n\n\n\n \n CODEC_MAP[charset]=codecname\n \n \n \n \n \ndef _encode(string,codec):\n if codec ==UNKNOWN8BIT:\n return string.encode('ascii','surrogateescape')\n else :\n return string.encode(codec)\n \n \n \nclass Charset:\n ''\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n \n def __init__(self,input_charset=DEFAULT_CHARSET):\n \n \n \n \n try :\n if isinstance(input_charset,str):\n input_charset.encode('ascii')\n else :\n input_charset=str(input_charset,'ascii')\n except UnicodeError:\n raise errors.CharsetError(input_charset)\n input_charset=input_charset.lower()\n \n self.input_charset=ALIASES.get(input_charset,input_charset)\n \n \n \n henc,benc,conv=CHARSETS.get(self.input_charset,\n (SHORTEST,BASE64,None ))\n if not conv:\n conv=self.input_charset\n \n self.header_encoding=henc\n self.body_encoding=benc\n self.output_charset=ALIASES.get(conv,conv)\n \n \n self.input_codec=CODEC_MAP.get(self.input_charset,\n self.input_charset)\n self.output_codec=CODEC_MAP.get(self.output_charset,\n self.output_charset)\n \n def __str__(self):\n return self.input_charset.lower()\n \n __repr__=__str__\n \n def __eq__(self,other):\n return str(self)==str(other).lower()\n \n def get_body_encoding(self):\n ''\n\n\n\n\n\n\n\n\n\n\n \n assert self.body_encoding !=SHORTEST\n if self.body_encoding ==QP:\n return 'quoted-printable'\n elif self.body_encoding ==BASE64:\n return 'base64'\n else :\n return encode_7or8bit\n \n def get_output_charset(self):\n ''\n\n\n\n \n return self.output_charset or self.input_charset\n \n def header_encode(self,string):\n ''\n\n\n\n\n\n\n\n\n \n codec=self.output_codec or 'us-ascii'\n header_bytes=_encode(string,codec)\n \n encoder_module=self._get_encoder(header_bytes)\n if encoder_module is None :\n return string\n return encoder_module.header_encode(header_bytes,codec)\n \n def header_encode_lines(self,string,maxlengths):\n ''\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n \n \n codec=self.output_codec or 'us-ascii'\n header_bytes=_encode(string,codec)\n encoder_module=self._get_encoder(header_bytes)\n encoder=partial(encoder_module.header_encode,charset=codec)\n \n \n charset=self.get_output_charset()\n extra=len(charset)+RFC2047_CHROME_LEN\n \n \n \n \n \n \n \n \n \n \n \n lines=[]\n current_line=[]\n maxlen=next(maxlengths)-extra\n for character in string:\n current_line.append(character)\n this_line=EMPTYSTRING.join(current_line)\n length=encoder_module.header_length(_encode(this_line,charset))\n if length >maxlen:\n \n current_line.pop()\n \n if not lines and not current_line:\n lines.append(None )\n else :\n separator=(' 'if lines else '')\n joined_line=EMPTYSTRING.join(current_line)\n header_bytes=_encode(joined_line,codec)\n lines.append(encoder(header_bytes))\n current_line=[character]\n maxlen=next(maxlengths)-extra\n joined_line=EMPTYSTRING.join(current_line)\n header_bytes=_encode(joined_line,codec)\n lines.append(encoder(header_bytes))\n return lines\n \n def _get_encoder(self,header_bytes):\n if self.header_encoding ==BASE64:\n return email.base64mime\n elif self.header_encoding ==QP:\n return email.quoprimime\n elif self.header_encoding ==SHORTEST:\n len64=email.base64mime.header_length(header_bytes)\n lenqp=email.quoprimime.header_length(header_bytes)\n if len64 <lenqp:\n return email.base64mime\n else :\n return email.quoprimime\n else :\n return None\n \n def body_encode(self,string):\n ''\n\n\n\n\n\n\n \n if not string:\n return string\n if self.body_encoding is BASE64:\n if isinstance(string,str):\n string=string.encode(self.output_charset)\n return email.base64mime.body_encode(string)\n elif self.body_encoding is QP:\n \n \n \n \n \n \n if isinstance(string,str):\n string=string.encode(self.output_charset)\n string=string.decode('latin1')\n return email.quoprimime.body_encode(string)\n else :\n if isinstance(string,str):\n string=string.encode(self.output_charset).decode('ascii')\n return string\n", ["email", "email.base64mime", "email.encoders", "email.errors", "email.quoprimime", "functools"]], "logging": [".py", "\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\"\"\"\nLogging package for Python. Based on PEP 282 and comments thereto in\ncomp.lang.python.\n\nCopyright (C) 2001-2013 Vinay Sajip. All Rights Reserved.\n\nTo use, simply 'import logging' and log away!\n\"\"\"\n\nimport sys,os,time,io,traceback,warnings,weakref\nfrom string import Template\nfrom browser import console\n\n__all__=['BASIC_FORMAT','BufferingFormatter','CRITICAL','DEBUG','ERROR',\n'FATAL','FileHandler','Filter','Formatter','Handler','INFO',\n'LogRecord','Logger','LoggerAdapter','NOTSET','NullHandler',\n'StreamHandler','ConsoleHandler','WARN','WARNING','addLevelName','basicConfig',\n'captureWarnings','critical','debug','disable','error',\n'exception','fatal','getLevelName','getLogger','getLoggerClass',\n'info','log','makeLogRecord','setLoggerClass','warn','warning',\n'getLogRecordFactory','setLogRecordFactory','lastResort']\n\ntry :\n import threading\nexcept ImportError:\n threading=None\n \n__author__=\"Vinay Sajip <vinay_sajip@red-dove.com>\"\n__status__=\"production\"\n__version__=\"0.5.1.2\"\n__date__=\"07 February 2010\"\n\n\n\n\n\n\n\n\n\nif hasattr(sys,'frozen'):\n _srcfile=\"logging%s__init__%s\"%(os.sep,__file__[-4:])\nelse :\n _srcfile=__file__\n_srcfile=os.path.normcase(_srcfile)\n\n\nif hasattr(sys,'_getframe'):\n currentframe=lambda :sys._getframe(3)\nelse :\n def currentframe():\n ''\n try :\n raise Exception\n except :\n return sys.exc_info()[2].tb_frame.f_back\n \n \n \n \n \n \n \n \n \n \n \n_startTime=time.time()\n\n\n\n\n\nraiseExceptions=True\n\n\n\n\nlogThreads=True\n\n\n\n\nlogMultiprocessing=True\n\n\n\n\nlogProcesses=True\n\n\n\n\n\n\n\n\n\n\n\n\nCRITICAL=50\nFATAL=CRITICAL\nERROR=40\nWARNING=30\nWARN=WARNING\nINFO=20\nDEBUG=10\nNOTSET=0\n\n_levelNames={\nCRITICAL:'CRITICAL',\nERROR:'ERROR',\nWARNING:'WARNING',\nINFO:'INFO',\nDEBUG:'DEBUG',\nNOTSET:'NOTSET',\n'CRITICAL':CRITICAL,\n'ERROR':ERROR,\n'WARN':WARNING,\n'WARNING':WARNING,\n'INFO':INFO,\n'DEBUG':DEBUG,\n'NOTSET':NOTSET,\n}\n\ndef getLevelName(level):\n ''\n\n\n\n\n\n\n\n\n\n\n\n \n return _levelNames.get(level,(\"Level %s\"%level))\n \ndef addLevelName(level,levelName):\n ''\n\n\n\n \n _acquireLock()\n try :\n _levelNames[level]=levelName\n _levelNames[levelName]=level\n finally :\n _releaseLock()\n \ndef _checkLevel(level):\n if isinstance(level,int):\n rv=level\n elif str(level)==level:\n if level not in _levelNames:\n raise ValueError(\"Unknown level: %r\"%level)\n rv=_levelNames[level]\n else :\n raise TypeError(\"Level not an integer or a valid string: %r\"%level)\n return rv\n \n \n \n \n \n \n \n \n \n \n \n \n \nif threading:\n _lock=threading.RLock()\nelse :\n _lock=None\n \n \ndef _acquireLock():\n ''\n\n\n\n \n if _lock:\n _lock.acquire()\n \ndef _releaseLock():\n ''\n\n \n if _lock:\n _lock.release()\n \n \n \n \n \nclass LogRecord(object):\n ''\n\n\n\n\n\n\n\n\n\n \n def __init__(self,name,level,pathname,lineno,\n msg,args,exc_info,func=None ,sinfo=None ,**kwargs):\n ''\n\n \n ct=time.time()\n self.name=name\n self.msg=msg\n \n \n \n \n \n \n \n \n \n \n \n \n \n if args and len(args)==1 and isinstance(args[0],dict)and args[0]:\n args=args[0]\n self.args=args\n self.levelname=getLevelName(level)\n self.levelno=level\n self.pathname=pathname\n try :\n self.filename=os.path.basename(pathname)\n self.module=os.path.splitext(self.filename)[0]\n except (TypeError,ValueError,AttributeError):\n self.filename=pathname\n self.module=\"Unknown module\"\n self.exc_info=exc_info\n self.exc_text=None\n self.stack_info=sinfo\n self.lineno=lineno\n self.funcName=func\n self.created=ct\n self.msecs=(ct -int(ct))*1000\n self.relativeCreated=(self.created -_startTime)*1000\n if logThreads and threading:\n self.thread=threading.get_ident()\n self.threadName=threading.current_thread().name\n else :\n self.thread=None\n self.threadName=None\n if not logMultiprocessing:\n self.processName=None\n else :\n self.processName='MainProcess'\n mp=sys.modules.get('multiprocessing')\n if mp is not None :\n \n \n \n \n try :\n self.processName=mp.current_process().name\n except Exception:\n pass\n if logProcesses and hasattr(os,'getpid'):\n self.process=os.getpid()\n else :\n self.process=None\n \n def __str__(self):\n return '<LogRecord: %s, %s, %s, %s, \"%s\">'%(self.name,self.levelno,\n self.pathname,self.lineno,self.msg)\n \n def getMessage(self):\n ''\n\n\n\n\n \n msg=str(self.msg)\n if self.args:\n msg=msg %self.args\n return msg\n \n \n \n \n_logRecordFactory=LogRecord\n\ndef setLogRecordFactory(factory):\n ''\n\n\n\n\n \n global _logRecordFactory\n _logRecordFactory=factory\n \ndef getLogRecordFactory():\n ''\n\n \n \n return _logRecordFactory\n \ndef makeLogRecord(dict):\n ''\n\n\n\n\n \n rv=_logRecordFactory(None ,None ,\"\",0,\"\",(),None ,None )\n rv.__dict__.update(dict)\n return rv\n \n \n \n \n \nclass PercentStyle(object):\n\n default_format='%(message)s'\n asctime_format='%(asctime)s'\n asctime_search='%(asctime)'\n \n def __init__(self,fmt):\n self._fmt=fmt or self.default_format\n \n def usesTime(self):\n return self._fmt.find(self.asctime_search)>=0\n \n def format(self,record):\n return self._fmt %record.__dict__\n \nclass StrFormatStyle(PercentStyle):\n default_format='{message}'\n asctime_format='{asctime}'\n asctime_search='{asctime'\n \n def format(self,record):\n return self._fmt.format(**record.__dict__)\n \n \nclass StringTemplateStyle(PercentStyle):\n default_format='${message}'\n asctime_format='${asctime}'\n asctime_search='${asctime}'\n \n def __init__(self,fmt):\n self._fmt=fmt or self.default_format\n self._tpl=Template(self._fmt)\n \n def usesTime(self):\n fmt=self._fmt\n return fmt.find('$asctime')>=0 or fmt.find(self.asctime_format)>=0\n \n def format(self,record):\n return self._tpl.substitute(**record.__dict__)\n \n_STYLES={\n'%':PercentStyle,\n'{':StrFormatStyle,\n'$':StringTemplateStyle\n}\n\nclass Formatter(object):\n ''\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n \n \n converter=time.localtime\n \n def __init__(self,fmt=None ,datefmt=None ,style='%'):\n ''\n\n\n\n\n\n\n\n\n\n\n\n\n \n if style not in _STYLES:\n raise ValueError('Style must be one of: %s'%','.join(\n _STYLES.keys()))\n self._style=_STYLES[style](fmt)\n self._fmt=self._style._fmt\n self.datefmt=datefmt\n \n default_time_format='%Y-%m-%d %H:%M:%S'\n default_msec_format='%s,%03d'\n \n def formatTime(self,record,datefmt=None ):\n ''\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n \n ct=self.converter(record.created)\n if datefmt:\n s=time.strftime(datefmt,ct)\n else :\n t=time.strftime(self.default_time_format,ct)\n s=self.default_msec_format %(t,record.msecs)\n return s\n \n def formatException(self,ei):\n ''\n\n\n\n\n \n sio=io.StringIO()\n tb=ei[2]\n \n \n \n traceback.print_exc(file=sio)\n s=sio.getvalue()\n sio.close()\n if s[-1:]==\"\\n\":\n s=s[:-1]\n return s\n \n def usesTime(self):\n ''\n\n \n return self._style.usesTime()\n \n def formatMessage(self,record):\n return self._style.format(record)\n \n def formatStack(self,stack_info):\n ''\n\n\n\n\n\n\n\n\n \n return stack_info\n \n def format(self,record):\n ''\n\n\n\n\n\n\n\n\n\n\n \n record.message=record.getMessage()\n if self.usesTime():\n record.asctime=self.formatTime(record,self.datefmt)\n s=self.formatMessage(record)\n if record.exc_info:\n \n \n if not record.exc_text:\n record.exc_text=self.formatException(record.exc_info)\n if record.exc_text:\n if s[-1:]!=\"\\n\":\n s=s+\"\\n\"\n s=s+record.exc_text\n if record.stack_info:\n if s[-1:]!=\"\\n\":\n s=s+\"\\n\"\n s=s+self.formatStack(record.stack_info)\n return s\n \n \n \n \n_defaultFormatter=Formatter()\n\nclass BufferingFormatter(object):\n ''\n\n \n def __init__(self,linefmt=None ):\n ''\n\n\n \n if linefmt:\n self.linefmt=linefmt\n else :\n self.linefmt=_defaultFormatter\n \n def formatHeader(self,records):\n ''\n\n \n return \"\"\n \n def formatFooter(self,records):\n ''\n\n \n return \"\"\n \n def format(self,records):\n ''\n\n \n rv=\"\"\n if len(records)>0:\n rv=rv+self.formatHeader(records)\n for record in records:\n rv=rv+self.linefmt.format(record)\n rv=rv+self.formatFooter(records)\n return rv\n \n \n \n \n \nclass Filter(object):\n ''\n\n\n\n\n\n\n\n\n \n def __init__(self,name=''):\n ''\n\n\n\n\n\n \n self.name=name\n self.nlen=len(name)\n \n def filter(self,record):\n ''\n\n\n\n\n \n if self.nlen ==0:\n return True\n elif self.name ==record.name:\n return True\n elif record.name.find(self.name,0,self.nlen)!=0:\n return False\n return (record.name[self.nlen]==\".\")\n \nclass Filterer(object):\n ''\n\n\n \n def __init__(self):\n ''\n\n \n self.filters=[]\n \n def addFilter(self,filter):\n ''\n\n \n if not (filter in self.filters):\n self.filters.append(filter)\n \n def removeFilter(self,filter):\n ''\n\n \n if filter in self.filters:\n self.filters.remove(filter)\n \n def filter(self,record):\n ''\n\n\n\n\n\n\n\n\n\n \n rv=True\n for f in self.filters:\n if hasattr(f,'filter'):\n result=f.filter(record)\n else :\n result=f(record)\n if not result:\n rv=False\n break\n return rv\n \n \n \n \n \n_handlers=weakref.WeakValueDictionary()\n_handlerList=[]\n\ndef _removeHandlerRef(wr):\n ''\n\n \n \n \n \n if (_acquireLock is not None and _handlerList is not None and\n _releaseLock is not None ):\n _acquireLock()\n try :\n if wr in _handlerList:\n _handlerList.remove(wr)\n finally :\n _releaseLock()\n \ndef _addHandlerRef(handler):\n ''\n\n \n _acquireLock()\n try :\n _handlerList.append(weakref.ref(handler,_removeHandlerRef))\n finally :\n _releaseLock()\n \nclass Handler(Filterer):\n ''\n\n\n\n\n\n\n \n def __init__(self,level=NOTSET):\n ''\n\n\n \n Filterer.__init__(self)\n self._name=None\n self.level=_checkLevel(level)\n self.formatter=None\n \n _addHandlerRef(self)\n self.createLock()\n \n def get_name(self):\n return self._name\n \n def set_name(self,name):\n _acquireLock()\n try :\n if self._name in _handlers:\n del _handlers[self._name]\n self._name=name\n if name:\n _handlers[name]=self\n finally :\n _releaseLock()\n \n name=property(get_name,set_name)\n \n def createLock(self):\n ''\n\n \n if threading:\n self.lock=threading.RLock()\n else :\n self.lock=None\n \n def acquire(self):\n ''\n\n \n if self.lock:\n self.lock.acquire()\n \n def release(self):\n ''\n\n \n if self.lock:\n self.lock.release()\n \n def setLevel(self,level):\n ''\n\n \n self.level=_checkLevel(level)\n \n def format(self,record):\n ''\n\n\n\n\n \n if self.formatter:\n fmt=self.formatter\n else :\n fmt=_defaultFormatter\n return fmt.format(record)\n \n def emit(self,record):\n ''\n\n\n\n\n \n raise NotImplementedError('emit must be implemented '\n 'by Handler subclasses')\n \n def handle(self,record):\n ''\n\n\n\n\n\n\n \n rv=self.filter(record)\n if rv:\n self.acquire()\n try :\n self.emit(record)\n finally :\n self.release()\n return rv\n \n def setFormatter(self,fmt):\n ''\n\n \n self.formatter=fmt\n \n def flush(self):\n ''\n\n\n\n\n \n pass\n \n def close(self):\n ''\n\n\n\n\n\n\n \n \n _acquireLock()\n try :\n if self._name and self._name in _handlers:\n del _handlers[self._name]\n finally :\n _releaseLock()\n \n def handleError(self,record):\n ''\n\n\n\n\n\n\n\n\n\n \n if raiseExceptions and sys.stderr:\n try :\n traceback.print_exc(file=sys.stderr)\n sys.stderr.write('Logged from file %s, line %s\\n'%(\n record.filename,record.lineno))\n except IOError:\n pass\n \nclass StreamHandler(Handler):\n ''\n\n\n\n \n \n terminator='\\n'\n \n def __init__(self,stream=None ):\n ''\n\n\n\n \n Handler.__init__(self)\n if stream is None :\n stream=sys.stderr\n self.stream=stream\n \n def flush(self):\n ''\n\n \n self.acquire()\n try :\n if self.stream and hasattr(self.stream,\"flush\"):\n self.stream.flush()\n finally :\n self.release()\n \n def emit(self,record):\n ''\n\n\n\n\n\n\n\n\n \n try :\n msg=self.format(record)\n stream=self.stream\n stream.write(msg)\n stream.write(self.terminator)\n self.flush()\n except (KeyboardInterrupt,SystemExit):\n raise\n except :\n self.handleError(record)\n \nclass FileHandler(StreamHandler):\n ''\n\n \n def __init__(self,filename,mode='a',encoding=None ,delay=False ):\n ''\n\n \n \n \n self.baseFilename=os.path.abspath(filename)\n self.mode=mode\n self.encoding=encoding\n self.delay=delay\n if delay:\n \n \n Handler.__init__(self)\n self.stream=None\n else :\n StreamHandler.__init__(self,self._open())\n \n def close(self):\n ''\n\n \n self.acquire()\n try :\n if self.stream:\n self.flush()\n if hasattr(self.stream,\"close\"):\n self.stream.close()\n StreamHandler.close(self)\n self.stream=None\n finally :\n self.release()\n \n def _open(self):\n ''\n\n\n \n return open(self.baseFilename,self.mode,encoding=self.encoding)\n \n def emit(self,record):\n ''\n\n\n\n\n \n if self.stream is None :\n self.stream=self._open()\n StreamHandler.emit(self,record)\n \nclass _StderrHandler(StreamHandler):\n ''\n\n\n\n \n def __init__(self,level=NOTSET):\n ''\n\n \n Handler.__init__(self,level)\n \n @property\n def stream(self):\n return sys.stderr\n \n \nclass ConsoleHandler(Handler):\n ''\n\n\n \n \n def emit(self,record):\n ''\n\n\n\n\n\n\n \n try :\n msg=self.format(record)\n console.log(msg)\n except :\n self.handleError(record)\n \n_defaultLastResort=ConsoleHandler(WARNING)\nlastResort=_defaultLastResort\n\n\n\n\n\nclass PlaceHolder(object):\n ''\n\n\n\n \n def __init__(self,alogger):\n ''\n\n \n self.loggerMap={alogger:None }\n \n def append(self,alogger):\n ''\n\n \n if alogger not in self.loggerMap:\n self.loggerMap[alogger]=None\n \n \n \n \n_loggerClass=None\n\ndef setLoggerClass(klass):\n ''\n\n\n\n \n if klass !=Logger:\n if not issubclass(klass,Logger):\n raise TypeError(\"logger not derived from logging.Logger: \"\n +klass.__name__)\n global _loggerClass\n _loggerClass=klass\n \ndef getLoggerClass():\n ''\n\n \n \n return _loggerClass\n \nclass Manager(object):\n ''\n\n\n \n def __init__(self,rootnode):\n ''\n\n \n self.root=rootnode\n self.disable=0\n self.emittedNoHandlerWarning=False\n self.loggerDict={}\n self.loggerClass=None\n self.logRecordFactory=None\n \n def getLogger(self,name):\n ''\n\n\n\n\n\n\n\n\n \n rv=None\n if not isinstance(name,str):\n raise TypeError('A logger name must be a string')\n _acquireLock()\n try :\n if name in self.loggerDict:\n rv=self.loggerDict[name]\n if isinstance(rv,PlaceHolder):\n ph=rv\n rv=(self.loggerClass or _loggerClass)(name)\n rv.manager=self\n self.loggerDict[name]=rv\n self._fixupChildren(ph,rv)\n self._fixupParents(rv)\n else :\n rv=(self.loggerClass or _loggerClass)(name)\n rv.manager=self\n self.loggerDict[name]=rv\n self._fixupParents(rv)\n finally :\n _releaseLock()\n return rv\n \n def setLoggerClass(self,klass):\n ''\n\n \n if klass !=Logger:\n if not issubclass(klass,Logger):\n raise TypeError(\"logger not derived from logging.Logger: \"\n +klass.__name__)\n self.loggerClass=klass\n \n def setLogRecordFactory(self,factory):\n ''\n\n\n \n self.logRecordFactory=factory\n \n def _fixupParents(self,alogger):\n ''\n\n\n \n name=alogger.name\n i=name.rfind(\".\")\n rv=None\n while (i >0)and not rv:\n substr=name[:i]\n if substr not in self.loggerDict:\n self.loggerDict[substr]=PlaceHolder(alogger)\n else :\n obj=self.loggerDict[substr]\n if isinstance(obj,Logger):\n rv=obj\n else :\n assert isinstance(obj,PlaceHolder)\n obj.append(alogger)\n i=name.rfind(\".\",0,i -1)\n if not rv:\n rv=self.root\n alogger.parent=rv\n \n def _fixupChildren(self,ph,alogger):\n ''\n\n\n \n name=alogger.name\n namelen=len(name)\n for c in ph.loggerMap.keys():\n \n if c.parent.name[:namelen]!=name:\n alogger.parent=c.parent\n c.parent=alogger\n \n \n \n \n \nclass Logger(Filterer):\n ''\n\n\n\n\n\n\n\n\n\n\n\n\n \n def __init__(self,name,level=NOTSET):\n ''\n\n \n Filterer.__init__(self)\n self.name=name\n self.level=_checkLevel(level)\n self.parent=None\n self.propagate=True\n self.handlers=[]\n self.disabled=False\n \n def setLevel(self,level):\n ''\n\n \n self.level=_checkLevel(level)\n \n def debug(self,msg,*args,**kwargs):\n ''\n\n\n\n\n\n\n \n if self.isEnabledFor(DEBUG):\n self._log(DEBUG,msg,args,**kwargs)\n \n def info(self,msg,*args,**kwargs):\n ''\n\n\n\n\n\n\n \n if self.isEnabledFor(INFO):\n self._log(INFO,msg,args,**kwargs)\n \n def warning(self,msg,*args,**kwargs):\n ''\n\n\n\n\n\n\n \n if self.isEnabledFor(WARNING):\n self._log(WARNING,msg,args,**kwargs)\n \n def warn(self,msg,*args,**kwargs):\n warnings.warn(\"The 'warn' method is deprecated, \"\n \"use 'warning' instead\",DeprecationWarning,2)\n self.warning(msg,*args,**kwargs)\n \n def error(self,msg,*args,**kwargs):\n ''\n\n\n\n\n\n\n \n if self.isEnabledFor(ERROR):\n self._log(ERROR,msg,args,**kwargs)\n \n def exception(self,msg,*args,**kwargs):\n ''\n\n \n kwargs['exc_info']=True\n self.error(msg,*args,**kwargs)\n \n def critical(self,msg,*args,**kwargs):\n ''\n\n\n\n\n\n\n \n if self.isEnabledFor(CRITICAL):\n self._log(CRITICAL,msg,args,**kwargs)\n \n fatal=critical\n \n def log(self,level,msg,*args,**kwargs):\n ''\n\n\n\n\n\n\n \n if not isinstance(level,int):\n if raiseExceptions:\n raise TypeError(\"level must be an integer\")\n else :\n return\n if self.isEnabledFor(level):\n self._log(level,msg,args,**kwargs)\n \n def findCaller(self,stack_info=False ):\n ''\n\n\n \n f=currentframe()\n \n \n if f is not None :\n f=f.f_back\n rv=\"(unknown file)\",0,\"(unknown function)\",None\n while hasattr(f,\"f_code\"):\n co=f.f_code\n filename=os.path.normcase(co.co_filename)\n if filename ==_srcfile:\n f=f.f_back\n continue\n sinfo=None\n if stack_info:\n sio=io.StringIO()\n sio.write('Stack (most recent call last):\\n')\n traceback.print_stack(f,file=sio)\n sinfo=sio.getvalue()\n if sinfo[-1]=='\\n':\n sinfo=sinfo[:-1]\n sio.close()\n rv=(co.co_filename,f.f_lineno,co.co_name,sinfo)\n break\n return rv\n \n def makeRecord(self,name,level,fn,lno,msg,args,exc_info,\n func=None ,extra=None ,sinfo=None ):\n ''\n\n\n \n rv=_logRecordFactory(name,level,fn,lno,msg,args,exc_info,func,\n sinfo)\n if extra is not None :\n for key in extra:\n if (key in [\"message\",\"asctime\"])or (key in rv.__dict__):\n raise KeyError(\"Attempt to overwrite %r in LogRecord\"%key)\n rv.__dict__[key]=extra[key]\n return rv\n \n def _log(self,level,msg,args,exc_info=None ,extra=None ,stack_info=False ):\n ''\n\n\n \n sinfo=None\n if _srcfile:\n \n \n \n try :\n fn,lno,func,sinfo=self.findCaller(stack_info)\n except ValueError:\n fn,lno,func=\"(unknown file)\",0,\"(unknown function)\"\n else :\n fn,lno,func=\"(unknown file)\",0,\"(unknown function)\"\n if exc_info:\n if not isinstance(exc_info,tuple):\n exc_info=sys.exc_info()\n record=self.makeRecord(self.name,level,fn,lno,msg,args,\n exc_info,func,extra,sinfo)\n self.handle(record)\n \n def handle(self,record):\n ''\n\n\n\n\n \n if (not self.disabled)and self.filter(record):\n self.callHandlers(record)\n \n def addHandler(self,hdlr):\n ''\n\n \n _acquireLock()\n try :\n if not (hdlr in self.handlers):\n self.handlers.append(hdlr)\n finally :\n _releaseLock()\n \n def removeHandler(self,hdlr):\n ''\n\n \n _acquireLock()\n try :\n if hdlr in self.handlers:\n self.handlers.remove(hdlr)\n finally :\n _releaseLock()\n \n def hasHandlers(self):\n ''\n\n\n\n\n\n\n\n \n c=self\n rv=False\n while c:\n if c.handlers:\n rv=True\n break\n if not c.propagate:\n break\n else :\n c=c.parent\n return rv\n \n def callHandlers(self,record):\n ''\n\n\n\n\n\n\n\n \n c=self\n found=0\n while c:\n for hdlr in c.handlers:\n found=found+1\n if record.levelno >=hdlr.level:\n hdlr.handle(record)\n if not c.propagate:\n c=None\n else :\n c=c.parent\n if (found ==0):\n if lastResort:\n if record.levelno >=lastResort.level:\n lastResort.handle(record)\n elif raiseExceptions and not self.manager.emittedNoHandlerWarning:\n sys.stderr.write(\"No handlers could be found for logger\"\n \" \\\"%s\\\"\\n\"%self.name)\n self.manager.emittedNoHandlerWarning=True\n \n def getEffectiveLevel(self):\n ''\n\n\n\n\n \n logger=self\n while logger:\n if logger.level:\n return logger.level\n logger=logger.parent\n return NOTSET\n \n def isEnabledFor(self,level):\n ''\n\n \n if self.manager.disable >=level:\n return False\n return level >=self.getEffectiveLevel()\n \n def getChild(self,suffix):\n ''\n\n\n\n\n\n\n\n\n\n\n\n\n \n if self.root is not self:\n suffix='.'.join((self.name,suffix))\n return self.manager.getLogger(suffix)\n \nclass RootLogger(Logger):\n ''\n\n\n\n \n def __init__(self,level):\n ''\n\n \n Logger.__init__(self,\"root\",level)\n \n_loggerClass=Logger\n\nclass LoggerAdapter(object):\n ''\n\n\n \n \n def __init__(self,logger,extra):\n ''\n\n\n\n\n\n\n\n\n \n self.logger=logger\n self.extra=extra\n \n def process(self,msg,kwargs):\n ''\n\n\n\n\n\n\n\n \n kwargs[\"extra\"]=self.extra\n return msg,kwargs\n \n \n \n \n def debug(self,msg,*args,**kwargs):\n ''\n\n \n self.log(DEBUG,msg,*args,**kwargs)\n \n def info(self,msg,*args,**kwargs):\n ''\n\n \n self.log(INFO,msg,*args,**kwargs)\n \n def warning(self,msg,*args,**kwargs):\n ''\n\n \n self.log(WARNING,msg,*args,**kwargs)\n \n def warn(self,msg,*args,**kwargs):\n warnings.warn(\"The 'warn' method is deprecated, \"\n \"use 'warning' instead\",DeprecationWarning,2)\n self.warning(msg,*args,**kwargs)\n \n def error(self,msg,*args,**kwargs):\n ''\n\n \n self.log(ERROR,msg,*args,**kwargs)\n \n def exception(self,msg,*args,**kwargs):\n ''\n\n \n kwargs[\"exc_info\"]=True\n self.log(ERROR,msg,*args,**kwargs)\n \n def critical(self,msg,*args,**kwargs):\n ''\n\n \n self.log(CRITICAL,msg,*args,**kwargs)\n \n def log(self,level,msg,*args,**kwargs):\n ''\n\n\n \n if self.isEnabledFor(level):\n msg,kwargs=self.process(msg,kwargs)\n self.logger._log(level,msg,args,**kwargs)\n \n def isEnabledFor(self,level):\n ''\n\n \n if self.logger.manager.disable >=level:\n return False\n return level >=self.getEffectiveLevel()\n \n def setLevel(self,level):\n ''\n\n \n self.logger.setLevel(level)\n \n def getEffectiveLevel(self):\n ''\n\n \n return self.logger.getEffectiveLevel()\n \n def hasHandlers(self):\n ''\n\n \n return self.logger.hasHandlers()\n \nroot=RootLogger(WARNING)\nLogger.root=root\nLogger.manager=Manager(Logger.root)\n\n\n\n\n\nBASIC_FORMAT=\"%(levelname)s:%(name)s:%(message)s\"\n\ndef basicConfig(**kwargs):\n ''\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n \n \n \n _acquireLock()\n try :\n if len(root.handlers)==0:\n handlers=kwargs.get(\"handlers\")\n if handlers is None :\n if \"stream\"in kwargs and \"filename\"in kwargs:\n raise ValueError(\"'stream' and 'filename' should not be \"\n \"specified together\")\n else :\n if \"stream\"in kwargs or \"filename\"in kwargs:\n raise ValueError(\"'stream' or 'filename' should not be \"\n \"specified together with 'handlers'\")\n if handlers is None :\n filename=kwargs.get(\"filename\")\n if filename:\n mode=kwargs.get(\"filemode\",'a')\n h=FileHandler(filename,mode)\n else :\n stream=kwargs.get(\"stream\")\n if stream:\n h=StreamHandler(stream)\n else :\n h=ConsoleHandler()\n handlers=[h]\n fs=kwargs.get(\"format\",BASIC_FORMAT)\n dfs=kwargs.get(\"datefmt\",None )\n style=kwargs.get(\"style\",'%')\n fmt=Formatter(fs,dfs,style)\n for h in handlers:\n if h.formatter is None :\n h.setFormatter(fmt)\n root.addHandler(h)\n level=kwargs.get(\"level\")\n if level is not None :\n root.setLevel(level)\n finally :\n _releaseLock()\n \n \n \n \n \n \ndef getLogger(name=None ):\n ''\n\n\n\n \n if name:\n return Logger.manager.getLogger(name)\n else :\n return root\n \ndef critical(msg,*args,**kwargs):\n ''\n\n\n\n \n if len(root.handlers)==0:\n basicConfig()\n root.critical(msg,*args,**kwargs)\n \nfatal=critical\n\ndef error(msg,*args,**kwargs):\n ''\n\n\n\n \n if len(root.handlers)==0:\n basicConfig()\n root.error(msg,*args,**kwargs)\n \ndef exception(msg,*args,**kwargs):\n ''\n\n\n\n \n kwargs['exc_info']=True\n error(msg,*args,**kwargs)\n \ndef warning(msg,*args,**kwargs):\n ''\n\n\n\n \n if len(root.handlers)==0:\n basicConfig()\n root.warning(msg,*args,**kwargs)\n \ndef warn(msg,*args,**kwargs):\n warnings.warn(\"The 'warn' function is deprecated, \"\n \"use 'warning' instead\",DeprecationWarning,2)\n warning(msg,*args,**kwargs)\n \ndef info(msg,*args,**kwargs):\n ''\n\n\n\n \n if len(root.handlers)==0:\n basicConfig()\n root.info(msg,*args,**kwargs)\n \ndef debug(msg,*args,**kwargs):\n ''\n\n\n\n \n if len(root.handlers)==0:\n basicConfig()\n root.debug(msg,*args,**kwargs)\n \ndef log(level,msg,*args,**kwargs):\n ''\n\n\n\n \n if len(root.handlers)==0:\n basicConfig()\n root.log(level,msg,*args,**kwargs)\n \ndef disable(level):\n ''\n\n \n root.manager.disable=level\n \ndef shutdown(handlerList=_handlerList):\n ''\n\n\n\n\n \n for wr in reversed(handlerList[:]):\n \n \n try :\n h=wr()\n if h:\n try :\n h.acquire()\n h.flush()\n h.close()\n except (IOError,ValueError):\n \n \n \n \n pass\n finally :\n h.release()\n except :\n if raiseExceptions:\n raise\n \n \n \nimport atexit\natexit.register(shutdown)\n\n\n\nclass NullHandler(Handler):\n ''\n\n\n\n\n\n\n\n \n def handle(self,record):\n ''\n \n def emit(self,record):\n ''\n \n def createLock(self):\n self.lock=None\n \n \n \n_warnings_showwarning=None\n\ndef _showwarning(message,category,filename,lineno,file=None ,line=None ):\n ''\n\n\n\n\n\n \n if file is not None :\n if _warnings_showwarning is not None :\n _warnings_showwarning(message,category,filename,lineno,file,line)\n else :\n s=warnings.formatwarning(message,category,filename,lineno,line)\n logger=getLogger(\"py.warnings\")\n if not logger.handlers:\n logger.addHandler(NullHandler())\n logger.warning(\"%s\",s)\n \ndef captureWarnings(capture):\n ''\n\n\n\n \n global _warnings_showwarning\n if capture:\n if _warnings_showwarning is None :\n _warnings_showwarning=warnings.showwarning\n warnings.showwarning=_showwarning\n else :\n if _warnings_showwarning is not None :\n warnings.showwarning=_warnings_showwarning\n _warnings_showwarning=None\n", ["atexit", "browser", "io", "os", "string", "sys", "threading", "time", "traceback", "warnings", "weakref"], 1], "sre_constants": [".py", "\n\n\n\n\n\n\n\n\n\n\n\"\"\"Internal support module for sre\"\"\"\n\n\n\nMAGIC=20171005\n\nfrom _sre import MAXREPEAT,MAXGROUPS\n\n\n\n\nclass error(Exception):\n ''\n\n\n\n\n\n\n\n\n \n \n __module__='re'\n \n def __init__(self,msg,pattern=None ,pos=None ):\n self.msg=msg\n self.pattern=pattern\n self.pos=pos\n if pattern is not None and pos is not None :\n msg='%s at position %d'%(msg,pos)\n if isinstance(pattern,str):\n newline='\\n'\n else :\n newline=b'\\n'\n self.lineno=pattern.count(newline,0,pos)+1\n self.colno=pos -pattern.rfind(newline,0,pos)\n if newline in pattern:\n msg='%s (line %d, column %d)'%(msg,self.lineno,self.colno)\n else :\n self.lineno=self.colno=None\n super().__init__(msg)\n \n \nclass _NamedIntConstant(int):\n def __new__(cls,value,name):\n self=super(_NamedIntConstant,cls).__new__(cls,value)\n self.name=name\n return self\n \n def __str__(self):\n return self.name\n \n __repr__=__str__\n \nMAXREPEAT=_NamedIntConstant(MAXREPEAT,'MAXREPEAT')\n\ndef _makecodes(names):\n names=names.strip().split()\n items=[_NamedIntConstant(i,name)for i,name in enumerate(names)]\n globals().update({item.name:item for item in items})\n return items\n \n \n \nOPCODES=_makecodes(\"\"\"\n FAILURE SUCCESS\n\n ANY ANY_ALL\n ASSERT ASSERT_NOT\n AT\n BRANCH\n CALL\n CATEGORY\n CHARSET BIGCHARSET\n GROUPREF GROUPREF_EXISTS\n IN\n INFO\n JUMP\n LITERAL\n MARK\n MAX_UNTIL\n MIN_UNTIL\n NOT_LITERAL\n NEGATE\n RANGE\n REPEAT\n REPEAT_ONE\n SUBPATTERN\n MIN_REPEAT_ONE\n\n GROUPREF_IGNORE\n IN_IGNORE\n LITERAL_IGNORE\n NOT_LITERAL_IGNORE\n\n GROUPREF_LOC_IGNORE\n IN_LOC_IGNORE\n LITERAL_LOC_IGNORE\n NOT_LITERAL_LOC_IGNORE\n\n GROUPREF_UNI_IGNORE\n IN_UNI_IGNORE\n LITERAL_UNI_IGNORE\n NOT_LITERAL_UNI_IGNORE\n RANGE_UNI_IGNORE\n\n MIN_REPEAT MAX_REPEAT\n\"\"\")\ndel OPCODES[-2:]\n\n\nATCODES=_makecodes(\"\"\"\n AT_BEGINNING AT_BEGINNING_LINE AT_BEGINNING_STRING\n AT_BOUNDARY AT_NON_BOUNDARY\n AT_END AT_END_LINE AT_END_STRING\n\n AT_LOC_BOUNDARY AT_LOC_NON_BOUNDARY\n\n AT_UNI_BOUNDARY AT_UNI_NON_BOUNDARY\n\"\"\")\n\n\nCHCODES=_makecodes(\"\"\"\n CATEGORY_DIGIT CATEGORY_NOT_DIGIT\n CATEGORY_SPACE CATEGORY_NOT_SPACE\n CATEGORY_WORD CATEGORY_NOT_WORD\n CATEGORY_LINEBREAK CATEGORY_NOT_LINEBREAK\n\n CATEGORY_LOC_WORD CATEGORY_LOC_NOT_WORD\n\n CATEGORY_UNI_DIGIT CATEGORY_UNI_NOT_DIGIT\n CATEGORY_UNI_SPACE CATEGORY_UNI_NOT_SPACE\n CATEGORY_UNI_WORD CATEGORY_UNI_NOT_WORD\n CATEGORY_UNI_LINEBREAK CATEGORY_UNI_NOT_LINEBREAK\n\"\"\")\n\n\n\nOP_IGNORE={\nLITERAL:LITERAL_IGNORE,\nNOT_LITERAL:NOT_LITERAL_IGNORE,\n}\n\nOP_LOCALE_IGNORE={\nLITERAL:LITERAL_LOC_IGNORE,\nNOT_LITERAL:NOT_LITERAL_LOC_IGNORE,\n}\n\nOP_UNICODE_IGNORE={\nLITERAL:LITERAL_UNI_IGNORE,\nNOT_LITERAL:NOT_LITERAL_UNI_IGNORE,\n}\n\nAT_MULTILINE={\nAT_BEGINNING:AT_BEGINNING_LINE,\nAT_END:AT_END_LINE\n}\n\nAT_LOCALE={\nAT_BOUNDARY:AT_LOC_BOUNDARY,\nAT_NON_BOUNDARY:AT_LOC_NON_BOUNDARY\n}\n\nAT_UNICODE={\nAT_BOUNDARY:AT_UNI_BOUNDARY,\nAT_NON_BOUNDARY:AT_UNI_NON_BOUNDARY\n}\n\nCH_LOCALE={\nCATEGORY_DIGIT:CATEGORY_DIGIT,\nCATEGORY_NOT_DIGIT:CATEGORY_NOT_DIGIT,\nCATEGORY_SPACE:CATEGORY_SPACE,\nCATEGORY_NOT_SPACE:CATEGORY_NOT_SPACE,\nCATEGORY_WORD:CATEGORY_LOC_WORD,\nCATEGORY_NOT_WORD:CATEGORY_LOC_NOT_WORD,\nCATEGORY_LINEBREAK:CATEGORY_LINEBREAK,\nCATEGORY_NOT_LINEBREAK:CATEGORY_NOT_LINEBREAK\n}\n\nCH_UNICODE={\nCATEGORY_DIGIT:CATEGORY_UNI_DIGIT,\nCATEGORY_NOT_DIGIT:CATEGORY_UNI_NOT_DIGIT,\nCATEGORY_SPACE:CATEGORY_UNI_SPACE,\nCATEGORY_NOT_SPACE:CATEGORY_UNI_NOT_SPACE,\nCATEGORY_WORD:CATEGORY_UNI_WORD,\nCATEGORY_NOT_WORD:CATEGORY_UNI_NOT_WORD,\nCATEGORY_LINEBREAK:CATEGORY_UNI_LINEBREAK,\nCATEGORY_NOT_LINEBREAK:CATEGORY_UNI_NOT_LINEBREAK\n}\n\n\nSRE_FLAG_TEMPLATE=1\nSRE_FLAG_IGNORECASE=2\nSRE_FLAG_LOCALE=4\nSRE_FLAG_MULTILINE=8\nSRE_FLAG_DOTALL=16\nSRE_FLAG_UNICODE=32\nSRE_FLAG_VERBOSE=64\nSRE_FLAG_DEBUG=128\nSRE_FLAG_ASCII=256\n\n\nSRE_INFO_PREFIX=1\nSRE_INFO_LITERAL=2\nSRE_INFO_CHARSET=4\n\nif __name__ ==\"__main__\":\n def dump(f,d,prefix):\n items=sorted(d)\n for item in items:\n f.write(\"#define %s_%s %d\\n\"%(prefix,item,item))\n with open(\"sre_constants.h\",\"w\")as f:\n f.write(\"\"\"\\\n/*\n * Secret Labs' Regular Expression Engine\n *\n * regular expression matching engine\n *\n * NOTE: This file is generated by sre_constants.py. If you need\n * to change anything in here, edit sre_constants.py and run it.\n *\n * Copyright (c) 1997-2001 by Secret Labs AB. All rights reserved.\n *\n * See the _sre.c file for information on usage and redistribution.\n */\n\n\"\"\")\n \n f.write(\"#define SRE_MAGIC %d\\n\"%MAGIC)\n \n dump(f,OPCODES,\"SRE_OP\")\n dump(f,ATCODES,\"SRE\")\n dump(f,CHCODES,\"SRE\")\n \n f.write(\"#define SRE_FLAG_TEMPLATE %d\\n\"%SRE_FLAG_TEMPLATE)\n f.write(\"#define SRE_FLAG_IGNORECASE %d\\n\"%SRE_FLAG_IGNORECASE)\n f.write(\"#define SRE_FLAG_LOCALE %d\\n\"%SRE_FLAG_LOCALE)\n f.write(\"#define SRE_FLAG_MULTILINE %d\\n\"%SRE_FLAG_MULTILINE)\n f.write(\"#define SRE_FLAG_DOTALL %d\\n\"%SRE_FLAG_DOTALL)\n f.write(\"#define SRE_FLAG_UNICODE %d\\n\"%SRE_FLAG_UNICODE)\n f.write(\"#define SRE_FLAG_VERBOSE %d\\n\"%SRE_FLAG_VERBOSE)\n f.write(\"#define SRE_FLAG_DEBUG %d\\n\"%SRE_FLAG_DEBUG)\n f.write(\"#define SRE_FLAG_ASCII %d\\n\"%SRE_FLAG_ASCII)\n \n f.write(\"#define SRE_INFO_PREFIX %d\\n\"%SRE_INFO_PREFIX)\n f.write(\"#define SRE_INFO_LITERAL %d\\n\"%SRE_INFO_LITERAL)\n f.write(\"#define SRE_INFO_CHARSET %d\\n\"%SRE_INFO_CHARSET)\n \n print(\"done\")\n", ["_sre"]], "_weakrefset": [".py", "\n\n\n\nfrom _weakref import ref\n\n__all__=['WeakSet']\n\n\nclass _IterationGuard:\n\n\n\n\n\n def __init__(self,weakcontainer):\n \n self.weakcontainer=ref(weakcontainer)\n \n def __enter__(self):\n w=self.weakcontainer()\n if w is not None :\n w._iterating.add(self)\n return self\n \n def __exit__(self,e,t,b):\n w=self.weakcontainer()\n if w is not None :\n s=w._iterating\n s.remove(self)\n if not s:\n w._commit_removals()\n \n \nclass WeakSet:\n def __init__(self,data=None ):\n self.data=set()\n def _remove(item,selfref=ref(self)):\n self=selfref()\n if self is not None :\n if self._iterating:\n self._pending_removals.append(item)\n else :\n self.data.discard(item)\n self._remove=_remove\n \n self._pending_removals=[]\n self._iterating=set()\n if data is not None :\n self.update(data)\n \n def _commit_removals(self):\n l=self._pending_removals\n discard=self.data.discard\n while l:\n discard(l.pop())\n \n def __iter__(self):\n with _IterationGuard(self):\n for itemref in self.data:\n item=itemref()\n if item is not None :\n \n \n yield item\n \n def __len__(self):\n return len(self.data)-len(self._pending_removals)\n \n def __contains__(self,item):\n try :\n wr=ref(item)\n except TypeError:\n return False\n return wr in self.data\n \n def __reduce__(self):\n return (self.__class__,(list(self),),\n getattr(self,'__dict__',None ))\n \n def add(self,item):\n if self._pending_removals:\n self._commit_removals()\n self.data.add(ref(item,self._remove))\n \n def clear(self):\n if self._pending_removals:\n self._commit_removals()\n self.data.clear()\n \n def copy(self):\n return self.__class__(self)\n \n def pop(self):\n if self._pending_removals:\n self._commit_removals()\n while True :\n try :\n itemref=self.data.pop()\n except KeyError:\n raise KeyError('pop from empty WeakSet')from None\n item=itemref()\n if item is not None :\n return item\n \n def remove(self,item):\n if self._pending_removals:\n self._commit_removals()\n self.data.remove(ref(item))\n \n def discard(self,item):\n if self._pending_removals:\n self._commit_removals()\n self.data.discard(ref(item))\n \n def update(self,other):\n if self._pending_removals:\n self._commit_removals()\n for element in other:\n self.add(element)\n \n def __ior__(self,other):\n self.update(other)\n return self\n \n def difference(self,other):\n newset=self.copy()\n newset.difference_update(other)\n return newset\n __sub__=difference\n \n def difference_update(self,other):\n self.__isub__(other)\n def __isub__(self,other):\n if self._pending_removals:\n self._commit_removals()\n if self is other:\n self.data.clear()\n else :\n self.data.difference_update(ref(item)for item in other)\n return self\n \n def intersection(self,other):\n return self.__class__(item for item in other if item in self)\n __and__=intersection\n \n def intersection_update(self,other):\n self.__iand__(other)\n def __iand__(self,other):\n if self._pending_removals:\n self._commit_removals()\n self.data.intersection_update(ref(item)for item in other)\n return self\n \n def issubset(self,other):\n return self.data.issubset(ref(item)for item in other)\n __le__=issubset\n \n def __lt__(self,other):\n return self.data <set(map(ref,other))\n \n def issuperset(self,other):\n return self.data.issuperset(ref(item)for item in other)\n __ge__=issuperset\n \n def __gt__(self,other):\n return self.data >set(map(ref,other))\n \n def __eq__(self,other):\n if not isinstance(other,self.__class__):\n return NotImplemented\n return self.data ==set(map(ref,other))\n \n def symmetric_difference(self,other):\n newset=self.copy()\n newset.symmetric_difference_update(other)\n return newset\n __xor__=symmetric_difference\n \n def symmetric_difference_update(self,other):\n self.__ixor__(other)\n def __ixor__(self,other):\n if self._pending_removals:\n self._commit_removals()\n if self is other:\n self.data.clear()\n else :\n self.data.symmetric_difference_update(ref(item,self._remove)for item in other)\n return self\n \n def union(self,other):\n return self.__class__(e for s in (self,other)for e in s)\n __or__=union\n \n def isdisjoint(self,other):\n return len(self.intersection(other))==0\n", ["_weakref"]]}