diff --git a/.gitignore b/.gitignore index 5a8edc0..d0f9438 100644 --- a/.gitignore +++ b/.gitignore @@ -9,3 +9,5 @@ build/ *.pyo *.egg *.egg-info +single_file/single_file_icecream.py +single_file/icecream_pypy.py diff --git a/single_file/compare_versions.py b/single_file/compare_versions.py new file mode 100644 index 0000000..be7b1b3 --- /dev/null +++ b/single_file/compare_versions.py @@ -0,0 +1,24 @@ +""" +Utility to see which version files differ. +""" + +from collections import defaultdict +from glob import glob +from pathlib import Path + +result = defaultdict(list) + +for filename in glob("icecream_*.py"): + group = result[hash(Path(filename).read_text())] + group.append(filename.replace("icecream_", "").replace(".py", "")) + group.sort() + +for group in sorted(result.values()): + print(group) + +""" +The result is that the files fall into these groups: +['py27', 'pypy27'] +['py35', 'pypy35'] +['py36', 'py37', 'py38', 'py39', 'pypy36'] +""" diff --git a/single_file/icecream_py27.py b/single_file/icecream_py27.py new file mode 100644 index 0000000..a039c0b --- /dev/null +++ b/single_file/icecream_py27.py @@ -0,0 +1,90 @@ +#!/usr/bin/env python +import contextlib as __stickytape_contextlib + +@__stickytape_contextlib.contextmanager +def __stickytape_temporary_dir(): + import tempfile + import shutil + dir_path = tempfile.mkdtemp() + try: + yield dir_path + finally: + shutil.rmtree(dir_path) + +with __stickytape_temporary_dir() as __stickytape_working_dir: + def __stickytape_write_module(path, contents): + import os, os.path + + def make_package(path): + parts = path.split("/") + partial_path = __stickytape_working_dir + for part in parts: + partial_path = os.path.join(partial_path, part) + if not os.path.exists(partial_path): + os.mkdir(partial_path) + with open(os.path.join(partial_path, "__init__.py"), "wb") as f: + f.write(b"\n") + + make_package(os.path.dirname(path)) + + full_path = os.path.join(__stickytape_working_dir, path) + with open(full_path, "wb") as module_file: + module_file.write(contents) + + import sys as __stickytape_sys + __stickytape_sys.path.insert(0, __stickytape_working_dir) + + __stickytape_write_module('asttokens/__init__.py', b'# Copyright 2016 Grist Labs, Inc.\n#\n# Licensed under the Apache License, Version 2.0 (the "License");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an "AS IS" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\n"""\nThis module enhances the Python AST tree with token and source code information, sufficent to\ndetect the source text of each AST node. This is helpful for tools that make source code\ntransformations.\n"""\n\nfrom .line_numbers import LineNumbers\nfrom .asttokens import ASTTokens\n') + __stickytape_write_module('asttokens/line_numbers.py', b'# Copyright 2016 Grist Labs, Inc.\n#\n# Licensed under the Apache License, Version 2.0 (the "License");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an "AS IS" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\nimport bisect\nimport re\n\n_line_start_re = re.compile(r\'^\', re.M)\n\nclass LineNumbers(object):\n """\n Class to convert between character offsets in a text string, and pairs (line, column) of 1-based\n line and 0-based column numbers, as used by tokens and AST nodes.\n\n This class expects unicode for input and stores positions in unicode. But it supports\n translating to and from utf8 offsets, which are used by ast parsing.\n """\n def __init__(self, text):\n # A list of character offsets of each line\'s first character.\n self._line_offsets = [m.start(0) for m in _line_start_re.finditer(text)]\n self._text = text\n self._text_len = len(text)\n self._utf8_offset_cache = {} # maps line num to list of char offset for each byte in line\n\n def from_utf8_col(self, line, utf8_column):\n """\n Given a 1-based line number and 0-based utf8 column, returns a 0-based unicode column.\n """\n offsets = self._utf8_offset_cache.get(line)\n if offsets is None:\n end_offset = self._line_offsets[line] if line < len(self._line_offsets) else self._text_len\n line_text = self._text[self._line_offsets[line - 1] : end_offset]\n\n offsets = [i for i,c in enumerate(line_text) for byte in c.encode(\'utf8\')]\n offsets.append(len(line_text))\n self._utf8_offset_cache[line] = offsets\n\n return offsets[max(0, min(len(offsets)-1, utf8_column))]\n\n def line_to_offset(self, line, column):\n """\n Converts 1-based line number and 0-based column to 0-based character offset into text.\n """\n line -= 1\n if line >= len(self._line_offsets):\n return self._text_len\n elif line < 0:\n return 0\n else:\n return min(self._line_offsets[line] + max(0, column), self._text_len)\n\n def offset_to_line(self, offset):\n """\n Converts 0-based character offset to pair (line, col) of 1-based line and 0-based column\n numbers.\n """\n offset = max(0, min(self._text_len, offset))\n line_index = bisect.bisect_right(self._line_offsets, offset) - 1\n return (line_index + 1, offset - self._line_offsets[line_index])\n\n\n') + __stickytape_write_module('asttokens/asttokens.py', b'# Copyright 2016 Grist Labs, Inc.\n#\n# Licensed under the Apache License, Version 2.0 (the "License");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an "AS IS" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\nimport ast\nimport bisect\nimport token\nimport tokenize\nimport io\nimport six\nfrom six.moves import xrange # pylint: disable=redefined-builtin\nfrom .line_numbers import LineNumbers\nfrom .util import Token, match_token, is_non_coding_token\nfrom .mark_tokens import MarkTokens\n\nclass ASTTokens(object):\n """\n ASTTokens maintains the text of Python code in several forms: as a string, as line numbers, and\n as tokens, and is used to mark and access token and position information.\n\n ``source_text`` must be a unicode or UTF8-encoded string. If you pass in UTF8 bytes, remember\n that all offsets you\'ll get are to the unicode text, which is available as the ``.text``\n property.\n\n If ``parse`` is set, the ``source_text`` will be parsed with ``ast.parse()``, and the resulting\n tree marked with token info and made available as the ``.tree`` property.\n\n If ``tree`` is given, it will be marked and made available as the ``.tree`` property. In\n addition to the trees produced by the ``ast`` module, ASTTokens will also mark trees produced\n using ``astroid`` library .\n\n If only ``source_text`` is given, you may use ``.mark_tokens(tree)`` to mark the nodes of an AST\n tree created separately.\n """\n def __init__(self, source_text, parse=False, tree=None, filename=\'\'):\n self._filename = filename\n self._tree = ast.parse(source_text, filename) if parse else tree\n\n # Decode source after parsing to let Python 2 handle coding declarations.\n # (If the encoding was not utf-8 compatible, then even if it parses correctly,\n # we\'ll fail with a unicode error here.)\n if isinstance(source_text, six.binary_type):\n source_text = source_text.decode(\'utf8\')\n\n self._text = source_text\n self._line_numbers = LineNumbers(source_text)\n\n # Tokenize the code.\n self._tokens = list(self._generate_tokens(source_text))\n\n # Extract the start positions of all tokens, so that we can quickly map positions to tokens.\n self._token_offsets = [tok.startpos for tok in self._tokens]\n\n if self._tree:\n self.mark_tokens(self._tree)\n\n\n def mark_tokens(self, root_node):\n """\n Given the root of the AST or Astroid tree produced from source_text, visits all nodes marking\n them with token and position information by adding ``.first_token`` and\n ``.last_token``attributes. This is done automatically in the constructor when ``parse`` or\n ``tree`` arguments are set, but may be used manually with a separate AST or Astroid tree.\n """\n # The hard work of this class is done by MarkTokens\n MarkTokens(self).visit_tree(root_node)\n\n\n def _generate_tokens(self, text):\n """\n Generates tokens for the given code.\n """\n # This is technically an undocumented API for Python3, but allows us to use the same API as for\n # Python2. See http://stackoverflow.com/a/4952291/328565.\n for index, tok in enumerate(tokenize.generate_tokens(io.StringIO(text).readline)):\n tok_type, tok_str, start, end, line = tok\n yield Token(tok_type, tok_str, start, end, line, index,\n self._line_numbers.line_to_offset(start[0], start[1]),\n self._line_numbers.line_to_offset(end[0], end[1]))\n\n @property\n def text(self):\n """The source code passed into the constructor."""\n return self._text\n\n @property\n def tokens(self):\n """The list of tokens corresponding to the source code from the constructor."""\n return self._tokens\n\n @property\n def tree(self):\n """The root of the AST tree passed into the constructor or parsed from the source code."""\n return self._tree\n\n @property\n def filename(self):\n """The filename that was parsed"""\n return self._filename\n\n def get_token_from_offset(self, offset):\n """\n Returns the token containing the given character offset (0-based position in source text),\n or the preceeding token if the position is between tokens.\n """\n return self._tokens[bisect.bisect(self._token_offsets, offset) - 1]\n\n def get_token(self, lineno, col_offset):\n """\n Returns the token containing the given (lineno, col_offset) position, or the preceeding token\n if the position is between tokens.\n """\n # TODO: add test for multibyte unicode. We need to translate offsets from ast module (which\n # are in utf8) to offsets into the unicode text. tokenize module seems to use unicode offsets\n # but isn\'t explicit.\n return self.get_token_from_offset(self._line_numbers.line_to_offset(lineno, col_offset))\n\n def get_token_from_utf8(self, lineno, col_offset):\n """\n Same as get_token(), but interprets col_offset as a UTF8 offset, which is what `ast` uses.\n """\n return self.get_token(lineno, self._line_numbers.from_utf8_col(lineno, col_offset))\n\n def next_token(self, tok, include_extra=False):\n """\n Returns the next token after the given one. If include_extra is True, includes non-coding\n tokens from the tokenize module, such as NL and COMMENT.\n """\n i = tok.index + 1\n if not include_extra:\n while is_non_coding_token(self._tokens[i].type):\n i += 1\n return self._tokens[i]\n\n def prev_token(self, tok, include_extra=False):\n """\n Returns the previous token before the given one. If include_extra is True, includes non-coding\n tokens from the tokenize module, such as NL and COMMENT.\n """\n i = tok.index - 1\n if not include_extra:\n while is_non_coding_token(self._tokens[i].type):\n i -= 1\n return self._tokens[i]\n\n def find_token(self, start_token, tok_type, tok_str=None, reverse=False):\n """\n Looks for the first token, starting at start_token, that matches tok_type and, if given, the\n token string. Searches backwards if reverse is True. Returns ENDMARKER token if not found (you\n can check it with `token.ISEOF(t.type)`.\n """\n t = start_token\n advance = self.prev_token if reverse else self.next_token\n while not match_token(t, tok_type, tok_str) and not token.ISEOF(t.type):\n t = advance(t, include_extra=True)\n return t\n\n def token_range(self, first_token, last_token, include_extra=False):\n """\n Yields all tokens in order from first_token through and including last_token. If\n include_extra is True, includes non-coding tokens such as tokenize.NL and .COMMENT.\n """\n for i in xrange(first_token.index, last_token.index + 1):\n if include_extra or not is_non_coding_token(self._tokens[i].type):\n yield self._tokens[i]\n\n def get_tokens(self, node, include_extra=False):\n """\n Yields all tokens making up the given node. If include_extra is True, includes non-coding\n tokens such as tokenize.NL and .COMMENT.\n """\n return self.token_range(node.first_token, node.last_token, include_extra=include_extra)\n\n def get_text_range(self, node):\n """\n After mark_tokens() has been called, returns the (startpos, endpos) positions in source text\n corresponding to the given node. Returns (0, 0) for nodes (like `Load`) that don\'t correspond\n to any particular text.\n """\n if not hasattr(node, \'first_token\'):\n return (0, 0)\n\n start = node.first_token.startpos\n if any(match_token(t, token.NEWLINE) for t in self.get_tokens(node)):\n # Multi-line nodes would be invalid unless we keep the indentation of the first node.\n start = self._text.rfind(\'\\n\', 0, start) + 1\n\n return (start, node.last_token.endpos)\n\n def get_text(self, node):\n """\n After mark_tokens() has been called, returns the text corresponding to the given node. Returns\n \'\' for nodes (like `Load`) that don\'t correspond to any particular text.\n """\n start, end = self.get_text_range(node)\n return self._text[start : end]\n') + __stickytape_write_module('six.py', b'# Copyright (c) 2010-2020 Benjamin Peterson\n#\n# Permission is hereby granted, free of charge, to any person obtaining a copy\n# of this software and associated documentation files (the "Software"), to deal\n# in the Software without restriction, including without limitation the rights\n# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell\n# copies of the Software, and to permit persons to whom the Software is\n# furnished to do so, subject to the following conditions:\n#\n# The above copyright notice and this permission notice shall be included in all\n# copies or substantial portions of the Software.\n#\n# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\n# SOFTWARE.\n\n"""Utilities for writing code that runs on Python 2 and 3"""\n\nfrom __future__ import absolute_import\n\nimport functools\nimport itertools\nimport operator\nimport sys\nimport types\n\n__author__ = "Benjamin Peterson "\n__version__ = "1.15.0"\n\n\n# Useful for very coarse version differentiation.\nPY2 = sys.version_info[0] == 2\nPY3 = sys.version_info[0] == 3\nPY34 = sys.version_info[0:2] >= (3, 4)\n\nif PY3:\n string_types = str,\n integer_types = int,\n class_types = type,\n text_type = str\n binary_type = bytes\n\n MAXSIZE = sys.maxsize\nelse:\n string_types = basestring,\n integer_types = (int, long)\n class_types = (type, types.ClassType)\n text_type = unicode\n binary_type = str\n\n if sys.platform.startswith("java"):\n # Jython always uses 32 bits.\n MAXSIZE = int((1 << 31) - 1)\n else:\n # It\'s possible to have sizeof(long) != sizeof(Py_ssize_t).\n class X(object):\n\n def __len__(self):\n return 1 << 31\n try:\n len(X())\n except OverflowError:\n # 32-bit\n MAXSIZE = int((1 << 31) - 1)\n else:\n # 64-bit\n MAXSIZE = int((1 << 63) - 1)\n del X\n\n\ndef _add_doc(func, doc):\n """Add documentation to a function."""\n func.__doc__ = doc\n\n\ndef _import_module(name):\n """Import module, returning the module after the last dot."""\n __import__(name)\n return sys.modules[name]\n\n\nclass _LazyDescr(object):\n\n def __init__(self, name):\n self.name = name\n\n def __get__(self, obj, tp):\n result = self._resolve()\n setattr(obj, self.name, result) # Invokes __set__.\n try:\n # This is a bit ugly, but it avoids running this again by\n # removing this descriptor.\n delattr(obj.__class__, self.name)\n except AttributeError:\n pass\n return result\n\n\nclass MovedModule(_LazyDescr):\n\n def __init__(self, name, old, new=None):\n super(MovedModule, self).__init__(name)\n if PY3:\n if new is None:\n new = name\n self.mod = new\n else:\n self.mod = old\n\n def _resolve(self):\n return _import_module(self.mod)\n\n def __getattr__(self, attr):\n _module = self._resolve()\n value = getattr(_module, attr)\n setattr(self, attr, value)\n return value\n\n\nclass _LazyModule(types.ModuleType):\n\n def __init__(self, name):\n super(_LazyModule, self).__init__(name)\n self.__doc__ = self.__class__.__doc__\n\n def __dir__(self):\n attrs = ["__doc__", "__name__"]\n attrs += [attr.name for attr in self._moved_attributes]\n return attrs\n\n # Subclasses should override this\n _moved_attributes = []\n\n\nclass MovedAttribute(_LazyDescr):\n\n def __init__(self, name, old_mod, new_mod, old_attr=None, new_attr=None):\n super(MovedAttribute, self).__init__(name)\n if PY3:\n if new_mod is None:\n new_mod = name\n self.mod = new_mod\n if new_attr is None:\n if old_attr is None:\n new_attr = name\n else:\n new_attr = old_attr\n self.attr = new_attr\n else:\n self.mod = old_mod\n if old_attr is None:\n old_attr = name\n self.attr = old_attr\n\n def _resolve(self):\n module = _import_module(self.mod)\n return getattr(module, self.attr)\n\n\nclass _SixMetaPathImporter(object):\n\n """\n A meta path importer to import six.moves and its submodules.\n\n This class implements a PEP302 finder and loader. It should be compatible\n with Python 2.5 and all existing versions of Python3\n """\n\n def __init__(self, six_module_name):\n self.name = six_module_name\n self.known_modules = {}\n\n def _add_module(self, mod, *fullnames):\n for fullname in fullnames:\n self.known_modules[self.name + "." + fullname] = mod\n\n def _get_module(self, fullname):\n return self.known_modules[self.name + "." + fullname]\n\n def find_module(self, fullname, path=None):\n if fullname in self.known_modules:\n return self\n return None\n\n def __get_module(self, fullname):\n try:\n return self.known_modules[fullname]\n except KeyError:\n raise ImportError("This loader does not know module " + fullname)\n\n def load_module(self, fullname):\n try:\n # in case of a reload\n return sys.modules[fullname]\n except KeyError:\n pass\n mod = self.__get_module(fullname)\n if isinstance(mod, MovedModule):\n mod = mod._resolve()\n else:\n mod.__loader__ = self\n sys.modules[fullname] = mod\n return mod\n\n def is_package(self, fullname):\n """\n Return true, if the named module is a package.\n\n We need this method to get correct spec objects with\n Python 3.4 (see PEP451)\n """\n return hasattr(self.__get_module(fullname), "__path__")\n\n def get_code(self, fullname):\n """Return None\n\n Required, if is_package is implemented"""\n self.__get_module(fullname) # eventually raises ImportError\n return None\n get_source = get_code # same as get_code\n\n_importer = _SixMetaPathImporter(__name__)\n\n\nclass _MovedItems(_LazyModule):\n\n """Lazy loading of moved objects"""\n __path__ = [] # mark as package\n\n\n_moved_attributes = [\n MovedAttribute("cStringIO", "cStringIO", "io", "StringIO"),\n MovedAttribute("filter", "itertools", "builtins", "ifilter", "filter"),\n MovedAttribute("filterfalse", "itertools", "itertools", "ifilterfalse", "filterfalse"),\n MovedAttribute("input", "__builtin__", "builtins", "raw_input", "input"),\n MovedAttribute("intern", "__builtin__", "sys"),\n MovedAttribute("map", "itertools", "builtins", "imap", "map"),\n MovedAttribute("getcwd", "os", "os", "getcwdu", "getcwd"),\n MovedAttribute("getcwdb", "os", "os", "getcwd", "getcwdb"),\n MovedAttribute("getoutput", "commands", "subprocess"),\n MovedAttribute("range", "__builtin__", "builtins", "xrange", "range"),\n MovedAttribute("reload_module", "__builtin__", "importlib" if PY34 else "imp", "reload"),\n MovedAttribute("reduce", "__builtin__", "functools"),\n MovedAttribute("shlex_quote", "pipes", "shlex", "quote"),\n MovedAttribute("StringIO", "StringIO", "io"),\n MovedAttribute("UserDict", "UserDict", "collections"),\n MovedAttribute("UserList", "UserList", "collections"),\n MovedAttribute("UserString", "UserString", "collections"),\n MovedAttribute("xrange", "__builtin__", "builtins", "xrange", "range"),\n MovedAttribute("zip", "itertools", "builtins", "izip", "zip"),\n MovedAttribute("zip_longest", "itertools", "itertools", "izip_longest", "zip_longest"),\n MovedModule("builtins", "__builtin__"),\n MovedModule("configparser", "ConfigParser"),\n MovedModule("collections_abc", "collections", "collections.abc" if sys.version_info >= (3, 3) else "collections"),\n MovedModule("copyreg", "copy_reg"),\n MovedModule("dbm_gnu", "gdbm", "dbm.gnu"),\n MovedModule("dbm_ndbm", "dbm", "dbm.ndbm"),\n MovedModule("_dummy_thread", "dummy_thread", "_dummy_thread" if sys.version_info < (3, 9) else "_thread"),\n MovedModule("http_cookiejar", "cookielib", "http.cookiejar"),\n MovedModule("http_cookies", "Cookie", "http.cookies"),\n MovedModule("html_entities", "htmlentitydefs", "html.entities"),\n MovedModule("html_parser", "HTMLParser", "html.parser"),\n MovedModule("http_client", "httplib", "http.client"),\n MovedModule("email_mime_base", "email.MIMEBase", "email.mime.base"),\n MovedModule("email_mime_image", "email.MIMEImage", "email.mime.image"),\n MovedModule("email_mime_multipart", "email.MIMEMultipart", "email.mime.multipart"),\n MovedModule("email_mime_nonmultipart", "email.MIMENonMultipart", "email.mime.nonmultipart"),\n MovedModule("email_mime_text", "email.MIMEText", "email.mime.text"),\n MovedModule("BaseHTTPServer", "BaseHTTPServer", "http.server"),\n MovedModule("CGIHTTPServer", "CGIHTTPServer", "http.server"),\n MovedModule("SimpleHTTPServer", "SimpleHTTPServer", "http.server"),\n MovedModule("cPickle", "cPickle", "pickle"),\n MovedModule("queue", "Queue"),\n MovedModule("reprlib", "repr"),\n MovedModule("socketserver", "SocketServer"),\n MovedModule("_thread", "thread", "_thread"),\n MovedModule("tkinter", "Tkinter"),\n MovedModule("tkinter_dialog", "Dialog", "tkinter.dialog"),\n MovedModule("tkinter_filedialog", "FileDialog", "tkinter.filedialog"),\n MovedModule("tkinter_scrolledtext", "ScrolledText", "tkinter.scrolledtext"),\n MovedModule("tkinter_simpledialog", "SimpleDialog", "tkinter.simpledialog"),\n MovedModule("tkinter_tix", "Tix", "tkinter.tix"),\n MovedModule("tkinter_ttk", "ttk", "tkinter.ttk"),\n MovedModule("tkinter_constants", "Tkconstants", "tkinter.constants"),\n MovedModule("tkinter_dnd", "Tkdnd", "tkinter.dnd"),\n MovedModule("tkinter_colorchooser", "tkColorChooser",\n "tkinter.colorchooser"),\n MovedModule("tkinter_commondialog", "tkCommonDialog",\n "tkinter.commondialog"),\n MovedModule("tkinter_tkfiledialog", "tkFileDialog", "tkinter.filedialog"),\n MovedModule("tkinter_font", "tkFont", "tkinter.font"),\n MovedModule("tkinter_messagebox", "tkMessageBox", "tkinter.messagebox"),\n MovedModule("tkinter_tksimpledialog", "tkSimpleDialog",\n "tkinter.simpledialog"),\n MovedModule("urllib_parse", __name__ + ".moves.urllib_parse", "urllib.parse"),\n MovedModule("urllib_error", __name__ + ".moves.urllib_error", "urllib.error"),\n MovedModule("urllib", __name__ + ".moves.urllib", __name__ + ".moves.urllib"),\n MovedModule("urllib_robotparser", "robotparser", "urllib.robotparser"),\n MovedModule("xmlrpc_client", "xmlrpclib", "xmlrpc.client"),\n MovedModule("xmlrpc_server", "SimpleXMLRPCServer", "xmlrpc.server"),\n]\n# Add windows specific modules.\nif sys.platform == "win32":\n _moved_attributes += [\n MovedModule("winreg", "_winreg"),\n ]\n\nfor attr in _moved_attributes:\n setattr(_MovedItems, attr.name, attr)\n if isinstance(attr, MovedModule):\n _importer._add_module(attr, "moves." + attr.name)\ndel attr\n\n_MovedItems._moved_attributes = _moved_attributes\n\nmoves = _MovedItems(__name__ + ".moves")\n_importer._add_module(moves, "moves")\n\n\nclass Module_six_moves_urllib_parse(_LazyModule):\n\n """Lazy loading of moved objects in six.moves.urllib_parse"""\n\n\n_urllib_parse_moved_attributes = [\n MovedAttribute("ParseResult", "urlparse", "urllib.parse"),\n MovedAttribute("SplitResult", "urlparse", "urllib.parse"),\n MovedAttribute("parse_qs", "urlparse", "urllib.parse"),\n MovedAttribute("parse_qsl", "urlparse", "urllib.parse"),\n MovedAttribute("urldefrag", "urlparse", "urllib.parse"),\n MovedAttribute("urljoin", "urlparse", "urllib.parse"),\n MovedAttribute("urlparse", "urlparse", "urllib.parse"),\n MovedAttribute("urlsplit", "urlparse", "urllib.parse"),\n MovedAttribute("urlunparse", "urlparse", "urllib.parse"),\n MovedAttribute("urlunsplit", "urlparse", "urllib.parse"),\n MovedAttribute("quote", "urllib", "urllib.parse"),\n MovedAttribute("quote_plus", "urllib", "urllib.parse"),\n MovedAttribute("unquote", "urllib", "urllib.parse"),\n MovedAttribute("unquote_plus", "urllib", "urllib.parse"),\n MovedAttribute("unquote_to_bytes", "urllib", "urllib.parse", "unquote", "unquote_to_bytes"),\n MovedAttribute("urlencode", "urllib", "urllib.parse"),\n MovedAttribute("splitquery", "urllib", "urllib.parse"),\n MovedAttribute("splittag", "urllib", "urllib.parse"),\n MovedAttribute("splituser", "urllib", "urllib.parse"),\n MovedAttribute("splitvalue", "urllib", "urllib.parse"),\n MovedAttribute("uses_fragment", "urlparse", "urllib.parse"),\n MovedAttribute("uses_netloc", "urlparse", "urllib.parse"),\n MovedAttribute("uses_params", "urlparse", "urllib.parse"),\n MovedAttribute("uses_query", "urlparse", "urllib.parse"),\n MovedAttribute("uses_relative", "urlparse", "urllib.parse"),\n]\nfor attr in _urllib_parse_moved_attributes:\n setattr(Module_six_moves_urllib_parse, attr.name, attr)\ndel attr\n\nModule_six_moves_urllib_parse._moved_attributes = _urllib_parse_moved_attributes\n\n_importer._add_module(Module_six_moves_urllib_parse(__name__ + ".moves.urllib_parse"),\n "moves.urllib_parse", "moves.urllib.parse")\n\n\nclass Module_six_moves_urllib_error(_LazyModule):\n\n """Lazy loading of moved objects in six.moves.urllib_error"""\n\n\n_urllib_error_moved_attributes = [\n MovedAttribute("URLError", "urllib2", "urllib.error"),\n MovedAttribute("HTTPError", "urllib2", "urllib.error"),\n MovedAttribute("ContentTooShortError", "urllib", "urllib.error"),\n]\nfor attr in _urllib_error_moved_attributes:\n setattr(Module_six_moves_urllib_error, attr.name, attr)\ndel attr\n\nModule_six_moves_urllib_error._moved_attributes = _urllib_error_moved_attributes\n\n_importer._add_module(Module_six_moves_urllib_error(__name__ + ".moves.urllib.error"),\n "moves.urllib_error", "moves.urllib.error")\n\n\nclass Module_six_moves_urllib_request(_LazyModule):\n\n """Lazy loading of moved objects in six.moves.urllib_request"""\n\n\n_urllib_request_moved_attributes = [\n MovedAttribute("urlopen", "urllib2", "urllib.request"),\n MovedAttribute("install_opener", "urllib2", "urllib.request"),\n MovedAttribute("build_opener", "urllib2", "urllib.request"),\n MovedAttribute("pathname2url", "urllib", "urllib.request"),\n MovedAttribute("url2pathname", "urllib", "urllib.request"),\n MovedAttribute("getproxies", "urllib", "urllib.request"),\n MovedAttribute("Request", "urllib2", "urllib.request"),\n MovedAttribute("OpenerDirector", "urllib2", "urllib.request"),\n MovedAttribute("HTTPDefaultErrorHandler", "urllib2", "urllib.request"),\n MovedAttribute("HTTPRedirectHandler", "urllib2", "urllib.request"),\n MovedAttribute("HTTPCookieProcessor", "urllib2", "urllib.request"),\n MovedAttribute("ProxyHandler", "urllib2", "urllib.request"),\n MovedAttribute("BaseHandler", "urllib2", "urllib.request"),\n MovedAttribute("HTTPPasswordMgr", "urllib2", "urllib.request"),\n MovedAttribute("HTTPPasswordMgrWithDefaultRealm", "urllib2", "urllib.request"),\n MovedAttribute("AbstractBasicAuthHandler", "urllib2", "urllib.request"),\n MovedAttribute("HTTPBasicAuthHandler", "urllib2", "urllib.request"),\n MovedAttribute("ProxyBasicAuthHandler", "urllib2", "urllib.request"),\n MovedAttribute("AbstractDigestAuthHandler", "urllib2", "urllib.request"),\n MovedAttribute("HTTPDigestAuthHandler", "urllib2", "urllib.request"),\n MovedAttribute("ProxyDigestAuthHandler", "urllib2", "urllib.request"),\n MovedAttribute("HTTPHandler", "urllib2", "urllib.request"),\n MovedAttribute("HTTPSHandler", "urllib2", "urllib.request"),\n MovedAttribute("FileHandler", "urllib2", "urllib.request"),\n MovedAttribute("FTPHandler", "urllib2", "urllib.request"),\n MovedAttribute("CacheFTPHandler", "urllib2", "urllib.request"),\n MovedAttribute("UnknownHandler", "urllib2", "urllib.request"),\n MovedAttribute("HTTPErrorProcessor", "urllib2", "urllib.request"),\n MovedAttribute("urlretrieve", "urllib", "urllib.request"),\n MovedAttribute("urlcleanup", "urllib", "urllib.request"),\n MovedAttribute("URLopener", "urllib", "urllib.request"),\n MovedAttribute("FancyURLopener", "urllib", "urllib.request"),\n MovedAttribute("proxy_bypass", "urllib", "urllib.request"),\n MovedAttribute("parse_http_list", "urllib2", "urllib.request"),\n MovedAttribute("parse_keqv_list", "urllib2", "urllib.request"),\n]\nfor attr in _urllib_request_moved_attributes:\n setattr(Module_six_moves_urllib_request, attr.name, attr)\ndel attr\n\nModule_six_moves_urllib_request._moved_attributes = _urllib_request_moved_attributes\n\n_importer._add_module(Module_six_moves_urllib_request(__name__ + ".moves.urllib.request"),\n "moves.urllib_request", "moves.urllib.request")\n\n\nclass Module_six_moves_urllib_response(_LazyModule):\n\n """Lazy loading of moved objects in six.moves.urllib_response"""\n\n\n_urllib_response_moved_attributes = [\n MovedAttribute("addbase", "urllib", "urllib.response"),\n MovedAttribute("addclosehook", "urllib", "urllib.response"),\n MovedAttribute("addinfo", "urllib", "urllib.response"),\n MovedAttribute("addinfourl", "urllib", "urllib.response"),\n]\nfor attr in _urllib_response_moved_attributes:\n setattr(Module_six_moves_urllib_response, attr.name, attr)\ndel attr\n\nModule_six_moves_urllib_response._moved_attributes = _urllib_response_moved_attributes\n\n_importer._add_module(Module_six_moves_urllib_response(__name__ + ".moves.urllib.response"),\n "moves.urllib_response", "moves.urllib.response")\n\n\nclass Module_six_moves_urllib_robotparser(_LazyModule):\n\n """Lazy loading of moved objects in six.moves.urllib_robotparser"""\n\n\n_urllib_robotparser_moved_attributes = [\n MovedAttribute("RobotFileParser", "robotparser", "urllib.robotparser"),\n]\nfor attr in _urllib_robotparser_moved_attributes:\n setattr(Module_six_moves_urllib_robotparser, attr.name, attr)\ndel attr\n\nModule_six_moves_urllib_robotparser._moved_attributes = _urllib_robotparser_moved_attributes\n\n_importer._add_module(Module_six_moves_urllib_robotparser(__name__ + ".moves.urllib.robotparser"),\n "moves.urllib_robotparser", "moves.urllib.robotparser")\n\n\nclass Module_six_moves_urllib(types.ModuleType):\n\n """Create a six.moves.urllib namespace that resembles the Python 3 namespace"""\n __path__ = [] # mark as package\n parse = _importer._get_module("moves.urllib_parse")\n error = _importer._get_module("moves.urllib_error")\n request = _importer._get_module("moves.urllib_request")\n response = _importer._get_module("moves.urllib_response")\n robotparser = _importer._get_module("moves.urllib_robotparser")\n\n def __dir__(self):\n return [\'parse\', \'error\', \'request\', \'response\', \'robotparser\']\n\n_importer._add_module(Module_six_moves_urllib(__name__ + ".moves.urllib"),\n "moves.urllib")\n\n\ndef add_move(move):\n """Add an item to six.moves."""\n setattr(_MovedItems, move.name, move)\n\n\ndef remove_move(name):\n """Remove item from six.moves."""\n try:\n delattr(_MovedItems, name)\n except AttributeError:\n try:\n del moves.__dict__[name]\n except KeyError:\n raise AttributeError("no such move, %r" % (name,))\n\n\nif PY3:\n _meth_func = "__func__"\n _meth_self = "__self__"\n\n _func_closure = "__closure__"\n _func_code = "__code__"\n _func_defaults = "__defaults__"\n _func_globals = "__globals__"\nelse:\n _meth_func = "im_func"\n _meth_self = "im_self"\n\n _func_closure = "func_closure"\n _func_code = "func_code"\n _func_defaults = "func_defaults"\n _func_globals = "func_globals"\n\n\ntry:\n advance_iterator = next\nexcept NameError:\n def advance_iterator(it):\n return it.next()\nnext = advance_iterator\n\n\ntry:\n callable = callable\nexcept NameError:\n def callable(obj):\n return any("__call__" in klass.__dict__ for klass in type(obj).__mro__)\n\n\nif PY3:\n def get_unbound_function(unbound):\n return unbound\n\n create_bound_method = types.MethodType\n\n def create_unbound_method(func, cls):\n return func\n\n Iterator = object\nelse:\n def get_unbound_function(unbound):\n return unbound.im_func\n\n def create_bound_method(func, obj):\n return types.MethodType(func, obj, obj.__class__)\n\n def create_unbound_method(func, cls):\n return types.MethodType(func, None, cls)\n\n class Iterator(object):\n\n def next(self):\n return type(self).__next__(self)\n\n callable = callable\n_add_doc(get_unbound_function,\n """Get the function out of a possibly unbound function""")\n\n\nget_method_function = operator.attrgetter(_meth_func)\nget_method_self = operator.attrgetter(_meth_self)\nget_function_closure = operator.attrgetter(_func_closure)\nget_function_code = operator.attrgetter(_func_code)\nget_function_defaults = operator.attrgetter(_func_defaults)\nget_function_globals = operator.attrgetter(_func_globals)\n\n\nif PY3:\n def iterkeys(d, **kw):\n return iter(d.keys(**kw))\n\n def itervalues(d, **kw):\n return iter(d.values(**kw))\n\n def iteritems(d, **kw):\n return iter(d.items(**kw))\n\n def iterlists(d, **kw):\n return iter(d.lists(**kw))\n\n viewkeys = operator.methodcaller("keys")\n\n viewvalues = operator.methodcaller("values")\n\n viewitems = operator.methodcaller("items")\nelse:\n def iterkeys(d, **kw):\n return d.iterkeys(**kw)\n\n def itervalues(d, **kw):\n return d.itervalues(**kw)\n\n def iteritems(d, **kw):\n return d.iteritems(**kw)\n\n def iterlists(d, **kw):\n return d.iterlists(**kw)\n\n viewkeys = operator.methodcaller("viewkeys")\n\n viewvalues = operator.methodcaller("viewvalues")\n\n viewitems = operator.methodcaller("viewitems")\n\n_add_doc(iterkeys, "Return an iterator over the keys of a dictionary.")\n_add_doc(itervalues, "Return an iterator over the values of a dictionary.")\n_add_doc(iteritems,\n "Return an iterator over the (key, value) pairs of a dictionary.")\n_add_doc(iterlists,\n "Return an iterator over the (key, [values]) pairs of a dictionary.")\n\n\nif PY3:\n def b(s):\n return s.encode("latin-1")\n\n def u(s):\n return s\n unichr = chr\n import struct\n int2byte = struct.Struct(">B").pack\n del struct\n byte2int = operator.itemgetter(0)\n indexbytes = operator.getitem\n iterbytes = iter\n import io\n StringIO = io.StringIO\n BytesIO = io.BytesIO\n del io\n _assertCountEqual = "assertCountEqual"\n if sys.version_info[1] <= 1:\n _assertRaisesRegex = "assertRaisesRegexp"\n _assertRegex = "assertRegexpMatches"\n _assertNotRegex = "assertNotRegexpMatches"\n else:\n _assertRaisesRegex = "assertRaisesRegex"\n _assertRegex = "assertRegex"\n _assertNotRegex = "assertNotRegex"\nelse:\n def b(s):\n return s\n # Workaround for standalone backslash\n\n def u(s):\n return unicode(s.replace(r\'\\\\\', r\'\\\\\\\\\'), "unicode_escape")\n unichr = unichr\n int2byte = chr\n\n def byte2int(bs):\n return ord(bs[0])\n\n def indexbytes(buf, i):\n return ord(buf[i])\n iterbytes = functools.partial(itertools.imap, ord)\n import StringIO\n StringIO = BytesIO = StringIO.StringIO\n _assertCountEqual = "assertItemsEqual"\n _assertRaisesRegex = "assertRaisesRegexp"\n _assertRegex = "assertRegexpMatches"\n _assertNotRegex = "assertNotRegexpMatches"\n_add_doc(b, """Byte literal""")\n_add_doc(u, """Text literal""")\n\n\ndef assertCountEqual(self, *args, **kwargs):\n return getattr(self, _assertCountEqual)(*args, **kwargs)\n\n\ndef assertRaisesRegex(self, *args, **kwargs):\n return getattr(self, _assertRaisesRegex)(*args, **kwargs)\n\n\ndef assertRegex(self, *args, **kwargs):\n return getattr(self, _assertRegex)(*args, **kwargs)\n\n\ndef assertNotRegex(self, *args, **kwargs):\n return getattr(self, _assertNotRegex)(*args, **kwargs)\n\n\nif PY3:\n exec_ = getattr(moves.builtins, "exec")\n\n def reraise(tp, value, tb=None):\n try:\n if value is None:\n value = tp()\n if value.__traceback__ is not tb:\n raise value.with_traceback(tb)\n raise value\n finally:\n value = None\n tb = None\n\nelse:\n def exec_(_code_, _globs_=None, _locs_=None):\n """Execute code in a namespace."""\n if _globs_ is None:\n frame = sys._getframe(1)\n _globs_ = frame.f_globals\n if _locs_ is None:\n _locs_ = frame.f_locals\n del frame\n elif _locs_ is None:\n _locs_ = _globs_\n exec("""exec _code_ in _globs_, _locs_""")\n\n exec_("""def reraise(tp, value, tb=None):\n try:\n raise tp, value, tb\n finally:\n tb = None\n""")\n\n\nif sys.version_info[:2] > (3,):\n exec_("""def raise_from(value, from_value):\n try:\n raise value from from_value\n finally:\n value = None\n""")\nelse:\n def raise_from(value, from_value):\n raise value\n\n\nprint_ = getattr(moves.builtins, "print", None)\nif print_ is None:\n def print_(*args, **kwargs):\n """The new-style print function for Python 2.4 and 2.5."""\n fp = kwargs.pop("file", sys.stdout)\n if fp is None:\n return\n\n def write(data):\n if not isinstance(data, basestring):\n data = str(data)\n # If the file has an encoding, encode unicode with it.\n if (isinstance(fp, file) and\n isinstance(data, unicode) and\n fp.encoding is not None):\n errors = getattr(fp, "errors", None)\n if errors is None:\n errors = "strict"\n data = data.encode(fp.encoding, errors)\n fp.write(data)\n want_unicode = False\n sep = kwargs.pop("sep", None)\n if sep is not None:\n if isinstance(sep, unicode):\n want_unicode = True\n elif not isinstance(sep, str):\n raise TypeError("sep must be None or a string")\n end = kwargs.pop("end", None)\n if end is not None:\n if isinstance(end, unicode):\n want_unicode = True\n elif not isinstance(end, str):\n raise TypeError("end must be None or a string")\n if kwargs:\n raise TypeError("invalid keyword arguments to print()")\n if not want_unicode:\n for arg in args:\n if isinstance(arg, unicode):\n want_unicode = True\n break\n if want_unicode:\n newline = unicode("\\n")\n space = unicode(" ")\n else:\n newline = "\\n"\n space = " "\n if sep is None:\n sep = space\n if end is None:\n end = newline\n for i, arg in enumerate(args):\n if i:\n write(sep)\n write(arg)\n write(end)\nif sys.version_info[:2] < (3, 3):\n _print = print_\n\n def print_(*args, **kwargs):\n fp = kwargs.get("file", sys.stdout)\n flush = kwargs.pop("flush", False)\n _print(*args, **kwargs)\n if flush and fp is not None:\n fp.flush()\n\n_add_doc(reraise, """Reraise an exception.""")\n\nif sys.version_info[0:2] < (3, 4):\n # This does exactly the same what the :func:`py3:functools.update_wrapper`\n # function does on Python versions after 3.2. It sets the ``__wrapped__``\n # attribute on ``wrapper`` object and it doesn\'t raise an error if any of\n # the attributes mentioned in ``assigned`` and ``updated`` are missing on\n # ``wrapped`` object.\n def _update_wrapper(wrapper, wrapped,\n assigned=functools.WRAPPER_ASSIGNMENTS,\n updated=functools.WRAPPER_UPDATES):\n for attr in assigned:\n try:\n value = getattr(wrapped, attr)\n except AttributeError:\n continue\n else:\n setattr(wrapper, attr, value)\n for attr in updated:\n getattr(wrapper, attr).update(getattr(wrapped, attr, {}))\n wrapper.__wrapped__ = wrapped\n return wrapper\n _update_wrapper.__doc__ = functools.update_wrapper.__doc__\n\n def wraps(wrapped, assigned=functools.WRAPPER_ASSIGNMENTS,\n updated=functools.WRAPPER_UPDATES):\n return functools.partial(_update_wrapper, wrapped=wrapped,\n assigned=assigned, updated=updated)\n wraps.__doc__ = functools.wraps.__doc__\n\nelse:\n wraps = functools.wraps\n\n\ndef with_metaclass(meta, *bases):\n """Create a base class with a metaclass."""\n # This requires a bit of explanation: the basic idea is to make a dummy\n # metaclass for one level of class instantiation that replaces itself with\n # the actual metaclass.\n class metaclass(type):\n\n def __new__(cls, name, this_bases, d):\n if sys.version_info[:2] >= (3, 7):\n # This version introduced PEP 560 that requires a bit\n # of extra care (we mimic what is done by __build_class__).\n resolved_bases = types.resolve_bases(bases)\n if resolved_bases is not bases:\n d[\'__orig_bases__\'] = bases\n else:\n resolved_bases = bases\n return meta(name, resolved_bases, d)\n\n @classmethod\n def __prepare__(cls, name, this_bases):\n return meta.__prepare__(name, bases)\n return type.__new__(metaclass, \'temporary_class\', (), {})\n\n\ndef add_metaclass(metaclass):\n """Class decorator for creating a class with a metaclass."""\n def wrapper(cls):\n orig_vars = cls.__dict__.copy()\n slots = orig_vars.get(\'__slots__\')\n if slots is not None:\n if isinstance(slots, str):\n slots = [slots]\n for slots_var in slots:\n orig_vars.pop(slots_var)\n orig_vars.pop(\'__dict__\', None)\n orig_vars.pop(\'__weakref__\', None)\n if hasattr(cls, \'__qualname__\'):\n orig_vars[\'__qualname__\'] = cls.__qualname__\n return metaclass(cls.__name__, cls.__bases__, orig_vars)\n return wrapper\n\n\ndef ensure_binary(s, encoding=\'utf-8\', errors=\'strict\'):\n """Coerce **s** to six.binary_type.\n\n For Python 2:\n - `unicode` -> encoded to `str`\n - `str` -> `str`\n\n For Python 3:\n - `str` -> encoded to `bytes`\n - `bytes` -> `bytes`\n """\n if isinstance(s, binary_type):\n return s\n if isinstance(s, text_type):\n return s.encode(encoding, errors)\n raise TypeError("not expecting type \'%s\'" % type(s))\n\n\ndef ensure_str(s, encoding=\'utf-8\', errors=\'strict\'):\n """Coerce *s* to `str`.\n\n For Python 2:\n - `unicode` -> encoded to `str`\n - `str` -> `str`\n\n For Python 3:\n - `str` -> `str`\n - `bytes` -> decoded to `str`\n """\n # Optimization: Fast return for the common case.\n if type(s) is str:\n return s\n if PY2 and isinstance(s, text_type):\n return s.encode(encoding, errors)\n elif PY3 and isinstance(s, binary_type):\n return s.decode(encoding, errors)\n elif not isinstance(s, (text_type, binary_type)):\n raise TypeError("not expecting type \'%s\'" % type(s))\n return s\n\n\ndef ensure_text(s, encoding=\'utf-8\', errors=\'strict\'):\n """Coerce *s* to six.text_type.\n\n For Python 2:\n - `unicode` -> `unicode`\n - `str` -> `unicode`\n\n For Python 3:\n - `str` -> `str`\n - `bytes` -> decoded to `str`\n """\n if isinstance(s, binary_type):\n return s.decode(encoding, errors)\n elif isinstance(s, text_type):\n return s\n else:\n raise TypeError("not expecting type \'%s\'" % type(s))\n\n\ndef python_2_unicode_compatible(klass):\n """\n A class decorator that defines __unicode__ and __str__ methods under Python 2.\n Under Python 3 it does nothing.\n\n To support Python 2 and 3 with a single code base, define a __str__ method\n returning text and apply this decorator to the class.\n """\n if PY2:\n if \'__str__\' not in klass.__dict__:\n raise ValueError("@python_2_unicode_compatible cannot be applied "\n "to %s because it doesn\'t define __str__()." %\n klass.__name__)\n klass.__unicode__ = klass.__str__\n klass.__str__ = lambda self: self.__unicode__().encode(\'utf-8\')\n return klass\n\n\n# Complete the moves implementation.\n# This code is at the end of this module to speed up module loading.\n# Turn this module into a package.\n__path__ = [] # required for PEP 302 and PEP 451\n__package__ = __name__ # see PEP 366 @ReservedAssignment\nif globals().get("__spec__") is not None:\n __spec__.submodule_search_locations = [] # PEP 451 @UndefinedVariable\n# Remove other six meta path importers, since they cause problems. This can\n# happen if six is removed from sys.modules and then reloaded. (Setuptools does\n# this for some reason.)\nif sys.meta_path:\n for i, importer in enumerate(sys.meta_path):\n # Here\'s some real nastiness: Another "instance" of the six module might\n # be floating around. Therefore, we can\'t use isinstance() to check for\n # the six meta path importer, since the other six instance will have\n # inserted an importer with different class.\n if (type(importer).__name__ == "_SixMetaPathImporter" and\n importer.name == __name__):\n del sys.meta_path[i]\n break\n del i, importer\n# Finally, add the importer to the meta path import hook.\nsys.meta_path.append(_importer)\n') + __stickytape_write_module('asttokens/util.py', b'# Copyright 2016 Grist Labs, Inc.\n#\n# Licensed under the Apache License, Version 2.0 (the "License");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an "AS IS" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\nimport ast\nimport collections\nimport token\nfrom six import iteritems\n\n\ndef token_repr(tok_type, string):\n """Returns a human-friendly representation of a token with the given type and string."""\n # repr() prefixes unicode with \'u\' on Python2 but not Python3; strip it out for consistency.\n return \'%s:%s\' % (token.tok_name[tok_type], repr(string).lstrip(\'u\'))\n\n\nclass Token(collections.namedtuple(\'Token\', \'type string start end line index startpos endpos\')):\n """\n TokenInfo is an 8-tuple containing the same 5 fields as the tokens produced by the tokenize\n module, and 3 additional ones useful for this module:\n\n - [0] .type Token type (see token.py)\n - [1] .string Token (a string)\n - [2] .start Starting (row, column) indices of the token (a 2-tuple of ints)\n - [3] .end Ending (row, column) indices of the token (a 2-tuple of ints)\n - [4] .line Original line (string)\n - [5] .index Index of the token in the list of tokens that it belongs to.\n - [6] .startpos Starting character offset into the input text.\n - [7] .endpos Ending character offset into the input text.\n """\n def __str__(self):\n return token_repr(self.type, self.string)\n\n\ndef match_token(token, tok_type, tok_str=None):\n """Returns true if token is of the given type and, if a string is given, has that string."""\n return token.type == tok_type and (tok_str is None or token.string == tok_str)\n\n\ndef expect_token(token, tok_type, tok_str=None):\n """\n Verifies that the given token is of the expected type. If tok_str is given, the token string\n is verified too. If the token doesn\'t match, raises an informative ValueError.\n """\n if not match_token(token, tok_type, tok_str):\n raise ValueError("Expected token %s, got %s on line %s col %s" % (\n token_repr(tok_type, tok_str), str(token),\n token.start[0], token.start[1] + 1))\n\n# These were previously defined in tokenize.py and distinguishable by being greater than\n# token.N_TOKEN. As of python3.7, they are in token.py, and we check for them explicitly.\nif hasattr(token, \'ENCODING\'):\n def is_non_coding_token(token_type):\n """\n These are considered non-coding tokens, as they don\'t affect the syntax tree.\n """\n return token_type in (token.NL, token.COMMENT, token.ENCODING)\nelse:\n def is_non_coding_token(token_type):\n """\n These are considered non-coding tokens, as they don\'t affect the syntax tree.\n """\n return token_type >= token.N_TOKENS\n\n\ndef iter_children_func(node):\n """\n Returns a function which yields all direct children of a AST node,\n skipping children that are singleton nodes.\n The function depends on whether ``node`` is from ``ast`` or from the ``astroid`` module.\n """\n return iter_children_astroid if hasattr(node, \'get_children\') else iter_children_ast\n\n\ndef iter_children_astroid(node):\n # Don\'t attempt to process children of JoinedStr nodes, which we can\'t fully handle yet.\n if is_joined_str(node):\n return []\n\n return node.get_children()\n\n\nSINGLETONS = {c for n, c in iteritems(ast.__dict__) if isinstance(c, type) and\n issubclass(c, (ast.expr_context, ast.boolop, ast.operator, ast.unaryop, ast.cmpop))}\n\ndef iter_children_ast(node):\n # Don\'t attempt to process children of JoinedStr nodes, which we can\'t fully handle yet.\n if is_joined_str(node):\n return\n\n if isinstance(node, ast.Dict):\n # override the iteration order: instead of , ,\n # yield keys and values in source order (key1, value1, key2, value2, ...)\n for (key, value) in zip(node.keys, node.values):\n if key is not None:\n yield key\n yield value\n return\n\n for child in ast.iter_child_nodes(node):\n # Skip singleton children; they don\'t reflect particular positions in the code and break the\n # assumptions about the tree consisting of distinct nodes. Note that collecting classes\n # beforehand and checking them in a set is faster than using isinstance each time.\n if child.__class__ not in SINGLETONS:\n yield child\n\n\nstmt_class_names = {n for n, c in iteritems(ast.__dict__)\n if isinstance(c, type) and issubclass(c, ast.stmt)}\nexpr_class_names = ({n for n, c in iteritems(ast.__dict__)\n if isinstance(c, type) and issubclass(c, ast.expr)} |\n {\'AssignName\', \'DelName\', \'Const\', \'AssignAttr\', \'DelAttr\'})\n\n# These feel hacky compared to isinstance() but allow us to work with both ast and astroid nodes\n# in the same way, and without even importing astroid.\ndef is_expr(node):\n """Returns whether node is an expression node."""\n return node.__class__.__name__ in expr_class_names\n\ndef is_stmt(node):\n """Returns whether node is a statement node."""\n return node.__class__.__name__ in stmt_class_names\n\ndef is_module(node):\n """Returns whether node is a module node."""\n return node.__class__.__name__ == \'Module\'\n\ndef is_joined_str(node):\n """Returns whether node is a JoinedStr node, used to represent f-strings."""\n # At the moment, nodes below JoinedStr have wrong line/col info, and trying to process them only\n # leads to errors.\n return node.__class__.__name__ == \'JoinedStr\'\n\n\ndef is_slice(node):\n """Returns whether node represents a slice, e.g. `1:2` in `x[1:2]`"""\n # Before 3.9, a tuple containing a slice is an ExtSlice,\n # but this was removed in https://bugs.python.org/issue34822\n return (\n node.__class__.__name__ in (\'Slice\', \'ExtSlice\')\n or (\n node.__class__.__name__ == \'Tuple\'\n and any(map(is_slice, node.elts))\n )\n )\n\n\n# Sentinel value used by visit_tree().\n_PREVISIT = object()\n\ndef visit_tree(node, previsit, postvisit):\n """\n Scans the tree under the node depth-first using an explicit stack. It avoids implicit recursion\n via the function call stack to avoid hitting \'maximum recursion depth exceeded\' error.\n\n It calls ``previsit()`` and ``postvisit()`` as follows:\n\n * ``previsit(node, par_value)`` - should return ``(par_value, value)``\n ``par_value`` is as returned from ``previsit()`` of the parent.\n\n * ``postvisit(node, par_value, value)`` - should return ``value``\n ``par_value`` is as returned from ``previsit()`` of the parent, and ``value`` is as\n returned from ``previsit()`` of this node itself. The return ``value`` is ignored except\n the one for the root node, which is returned from the overall ``visit_tree()`` call.\n\n For the initial node, ``par_value`` is None. ``postvisit`` may be None.\n """\n if not postvisit:\n postvisit = lambda node, pvalue, value: None\n\n iter_children = iter_children_func(node)\n done = set()\n ret = None\n stack = [(node, None, _PREVISIT)]\n while stack:\n current, par_value, value = stack.pop()\n if value is _PREVISIT:\n assert current not in done # protect againt infinite loop in case of a bad tree.\n done.add(current)\n\n pvalue, post_value = previsit(current, par_value)\n stack.append((current, par_value, post_value))\n\n # Insert all children in reverse order (so that first child ends up on top of the stack).\n ins = len(stack)\n for n in iter_children(current):\n stack.insert(ins, (n, pvalue, _PREVISIT))\n else:\n ret = postvisit(current, par_value, value)\n return ret\n\n\n\ndef walk(node):\n """\n Recursively yield all descendant nodes in the tree starting at ``node`` (including ``node``\n itself), using depth-first pre-order traversal (yieling parents before their children).\n\n This is similar to ``ast.walk()``, but with a different order, and it works for both ``ast`` and\n ``astroid`` trees. Also, as ``iter_children()``, it skips singleton nodes generated by ``ast``.\n """\n iter_children = iter_children_func(node)\n done = set()\n stack = [node]\n while stack:\n current = stack.pop()\n assert current not in done # protect againt infinite loop in case of a bad tree.\n done.add(current)\n\n yield current\n\n # Insert all children in reverse order (so that first child ends up on top of the stack).\n # This is faster than building a list and reversing it.\n ins = len(stack)\n for c in iter_children(current):\n stack.insert(ins, c)\n\n\ndef replace(text, replacements):\n """\n Replaces multiple slices of text with new values. This is a convenience method for making code\n modifications of ranges e.g. as identified by ``ASTTokens.get_text_range(node)``. Replacements is\n an iterable of ``(start, end, new_text)`` tuples.\n\n For example, ``replace("this is a test", [(0, 4, "X"), (8, 9, "THE")])`` produces\n ``"X is THE test"``.\n """\n p = 0\n parts = []\n for (start, end, new_text) in sorted(replacements):\n parts.append(text[p:start])\n parts.append(new_text)\n p = end\n parts.append(text[p:])\n return \'\'.join(parts)\n\n\nclass NodeMethods(object):\n """\n Helper to get `visit_{node_type}` methods given a node\'s class and cache the results.\n """\n def __init__(self):\n self._cache = {}\n\n def get(self, obj, cls):\n """\n Using the lowercase name of the class as node_type, returns `obj.visit_{node_type}`,\n or `obj.visit_default` if the type-specific method is not found.\n """\n method = self._cache.get(cls)\n if not method:\n name = "visit_" + cls.__name__.lower()\n method = getattr(obj, name, obj.visit_default)\n self._cache[cls] = method\n return method\n') + __stickytape_write_module('asttokens/mark_tokens.py', b'# Copyright 2016 Grist Labs, Inc.\n#\n# Licensed under the Apache License, Version 2.0 (the "License");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an "AS IS" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\nimport numbers\nimport sys\nimport token\n\nimport six\n\nfrom . import util\n\n# Mapping of matching braces. To find a token here, look up token[:2].\n_matching_pairs_left = {\n (token.OP, \'(\'): (token.OP, \')\'),\n (token.OP, \'[\'): (token.OP, \']\'),\n (token.OP, \'{\'): (token.OP, \'}\'),\n}\n\n_matching_pairs_right = {\n (token.OP, \')\'): (token.OP, \'(\'),\n (token.OP, \']\'): (token.OP, \'[\'),\n (token.OP, \'}\'): (token.OP, \'{\'),\n}\n\n\nclass MarkTokens(object):\n """\n Helper that visits all nodes in the AST tree and assigns .first_token and .last_token attributes\n to each of them. This is the heart of the token-marking logic.\n """\n def __init__(self, code):\n self._code = code\n self._methods = util.NodeMethods()\n self._iter_children = None\n\n def visit_tree(self, node):\n self._iter_children = util.iter_children_func(node)\n util.visit_tree(node, self._visit_before_children, self._visit_after_children)\n\n def _visit_before_children(self, node, parent_token):\n col = getattr(node, \'col_offset\', None)\n token = self._code.get_token_from_utf8(node.lineno, col) if col is not None else None\n\n if not token and util.is_module(node):\n # We\'ll assume that a Module node starts at the start of the source code.\n token = self._code.get_token(1, 0)\n\n # Use our own token, or our parent\'s if we don\'t have one, to pass to child calls as\n # parent_token argument. The second value becomes the token argument of _visit_after_children.\n return (token or parent_token, token)\n\n def _visit_after_children(self, node, parent_token, token):\n # This processes the node generically first, after all children have been processed.\n\n # Get the first and last tokens that belong to children. Note how this doesn\'t assume that we\n # iterate through children in order that corresponds to occurrence in source code. This\n # assumption can fail (e.g. with return annotations).\n first = token\n last = None\n for child in self._iter_children(node):\n if not first or child.first_token.index < first.index:\n first = child.first_token\n if not last or child.last_token.index > last.index:\n last = child.last_token\n\n # If we don\'t have a first token from _visit_before_children, and there were no children, then\n # use the parent\'s token as the first token.\n first = first or parent_token\n\n # If no children, set last token to the first one.\n last = last or first\n\n # Statements continue to before NEWLINE. This helps cover a few different cases at once.\n if util.is_stmt(node):\n last = self._find_last_in_stmt(last)\n\n # Capture any unmatched brackets.\n first, last = self._expand_to_matching_pairs(first, last, node)\n\n # Give a chance to node-specific methods to adjust.\n nfirst, nlast = self._methods.get(self, node.__class__)(node, first, last)\n\n if (nfirst, nlast) != (first, last):\n # If anything changed, expand again to capture any unmatched brackets.\n nfirst, nlast = self._expand_to_matching_pairs(nfirst, nlast, node)\n\n node.first_token = nfirst\n node.last_token = nlast\n\n def _find_last_in_stmt(self, start_token):\n t = start_token\n while (not util.match_token(t, token.NEWLINE) and\n not util.match_token(t, token.OP, \';\') and\n not token.ISEOF(t.type)):\n t = self._code.next_token(t, include_extra=True)\n return self._code.prev_token(t)\n\n def _expand_to_matching_pairs(self, first_token, last_token, node):\n """\n Scan tokens in [first_token, last_token] range that are between node\'s children, and for any\n unmatched brackets, adjust first/last tokens to include the closing pair.\n """\n # We look for opening parens/braces among non-child tokens (i.e. tokens between our actual\n # child nodes). If we find any closing ones, we match them to the opens.\n to_match_right = []\n to_match_left = []\n for tok in self._code.token_range(first_token, last_token):\n tok_info = tok[:2]\n if to_match_right and tok_info == to_match_right[-1]:\n to_match_right.pop()\n elif tok_info in _matching_pairs_left:\n to_match_right.append(_matching_pairs_left[tok_info])\n elif tok_info in _matching_pairs_right:\n to_match_left.append(_matching_pairs_right[tok_info])\n\n # Once done, extend `last_token` to match any unclosed parens/braces.\n for match in reversed(to_match_right):\n last = self._code.next_token(last_token)\n # Allow for trailing commas or colons (allowed in subscripts) before the closing delimiter\n while any(util.match_token(last, token.OP, x) for x in (\',\', \':\')):\n last = self._code.next_token(last)\n # Now check for the actual closing delimiter.\n if util.match_token(last, *match):\n last_token = last\n\n # And extend `first_token` to match any unclosed opening parens/braces.\n for match in to_match_left:\n first = self._code.prev_token(first_token)\n if util.match_token(first, *match):\n first_token = first\n\n return (first_token, last_token)\n\n #----------------------------------------------------------------------\n # Node visitors. Each takes a preliminary first and last tokens, and returns the adjusted pair\n # that will actually be assigned.\n\n def visit_default(self, node, first_token, last_token):\n # pylint: disable=no-self-use\n # By default, we don\'t need to adjust the token we computed earlier.\n return (first_token, last_token)\n\n def handle_comp(self, open_brace, node, first_token, last_token):\n # For list/set/dict comprehensions, we only get the token of the first child, so adjust it to\n # include the opening brace (the closing brace will be matched automatically).\n before = self._code.prev_token(first_token)\n util.expect_token(before, token.OP, open_brace)\n return (before, last_token)\n\n # Python 3.8 fixed the starting position of list comprehensions:\n # https://bugs.python.org/issue31241\n if sys.version_info < (3, 8):\n def visit_listcomp(self, node, first_token, last_token):\n return self.handle_comp(\'[\', node, first_token, last_token)\n\n if six.PY2:\n # We shouldn\'t do this on PY3 because its SetComp/DictComp already have a correct start.\n def visit_setcomp(self, node, first_token, last_token):\n return self.handle_comp(\'{\', node, first_token, last_token)\n\n def visit_dictcomp(self, node, first_token, last_token):\n return self.handle_comp(\'{\', node, first_token, last_token)\n\n def visit_comprehension(self, node, first_token, last_token):\n # The \'comprehension\' node starts with \'for\' but we only get first child; we search backwards\n # to find the \'for\' keyword.\n first = self._code.find_token(first_token, token.NAME, \'for\', reverse=True)\n return (first, last_token)\n\n def visit_if(self, node, first_token, last_token):\n while first_token.string not in (\'if\', \'elif\'):\n first_token = self._code.prev_token(first_token)\n return first_token, last_token\n\n def handle_attr(self, node, first_token, last_token):\n # Attribute node has ".attr" (2 tokens) after the last child.\n dot = self._code.find_token(last_token, token.OP, \'.\')\n name = self._code.next_token(dot)\n util.expect_token(name, token.NAME)\n return (first_token, name)\n\n visit_attribute = handle_attr\n visit_assignattr = handle_attr\n visit_delattr = handle_attr\n\n def handle_def(self, node, first_token, last_token):\n # With astroid, nodes that start with a doc-string can have an empty body, in which case we\n # need to adjust the last token to include the doc string.\n if not node.body and getattr(node, \'doc\', None):\n last_token = self._code.find_token(last_token, token.STRING)\n\n # Include @ from decorator\n if first_token.index > 0:\n prev = self._code.prev_token(first_token)\n if util.match_token(prev, token.OP, \'@\'):\n first_token = prev\n return (first_token, last_token)\n\n visit_classdef = handle_def\n visit_functiondef = handle_def\n\n def handle_following_brackets(self, node, last_token, opening_bracket):\n # This is for calls and subscripts, which have a pair of brackets\n # at the end which may contain no nodes, e.g. foo() or bar[:].\n # We look for the opening bracket and then let the matching pair be found automatically\n # Remember that last_token is at the end of all children,\n # so we are not worried about encountering a bracket that belongs to a child.\n first_child = next(self._iter_children(node))\n call_start = self._code.find_token(first_child.last_token, token.OP, opening_bracket)\n if call_start.index > last_token.index:\n last_token = call_start\n return last_token\n\n def visit_call(self, node, first_token, last_token):\n last_token = self.handle_following_brackets(node, last_token, \'(\')\n\n # Handling a python bug with decorators with empty parens, e.g.\n # @deco()\n # def ...\n if util.match_token(first_token, token.OP, \'@\'):\n first_token = self._code.next_token(first_token)\n return (first_token, last_token)\n\n def visit_subscript(self, node, first_token, last_token):\n last_token = self.handle_following_brackets(node, last_token, \'[\')\n return (first_token, last_token)\n\n def handle_bare_tuple(self, node, first_token, last_token):\n # A bare tuple doesn\'t include parens; if there is a trailing comma, make it part of the tuple.\n maybe_comma = self._code.next_token(last_token)\n if util.match_token(maybe_comma, token.OP, \',\'):\n last_token = maybe_comma\n return (first_token, last_token)\n\n if sys.version_info >= (3, 8):\n # In Python3.8 parsed tuples include parentheses when present.\n def handle_tuple_nonempty(self, node, first_token, last_token):\n # It\'s a bare tuple if the first token belongs to the first child. The first child may\n # include extraneous parentheses (which don\'t create new nodes), so account for those too.\n child = node.elts[0]\n child_first, child_last = self._gobble_parens(child.first_token, child.last_token, True)\n if first_token == child_first:\n return self.handle_bare_tuple(node, first_token, last_token)\n return (first_token, last_token)\n else:\n # Before python 3.8, parsed tuples do not include parens.\n def handle_tuple_nonempty(self, node, first_token, last_token):\n (first_token, last_token) = self.handle_bare_tuple(node, first_token, last_token)\n return self._gobble_parens(first_token, last_token, False)\n\n def visit_tuple(self, node, first_token, last_token):\n if not node.elts:\n # An empty tuple is just "()", and we need no further info.\n return (first_token, last_token)\n return self.handle_tuple_nonempty(node, first_token, last_token)\n\n def _gobble_parens(self, first_token, last_token, include_all=False):\n # Expands a range of tokens to include one or all pairs of surrounding parentheses, and\n # returns (first, last) tokens that include these parens.\n while first_token.index > 0:\n prev = self._code.prev_token(first_token)\n next = self._code.next_token(last_token)\n if util.match_token(prev, token.OP, \'(\') and util.match_token(next, token.OP, \')\'):\n first_token, last_token = prev, next\n if include_all:\n continue\n break\n return (first_token, last_token)\n\n def visit_str(self, node, first_token, last_token):\n return self.handle_str(first_token, last_token)\n\n def visit_joinedstr(self, node, first_token, last_token):\n return self.handle_str(first_token, last_token)\n\n def visit_bytes(self, node, first_token, last_token):\n return self.handle_str(first_token, last_token)\n\n def handle_str(self, first_token, last_token):\n # Multiple adjacent STRING tokens form a single string.\n last = self._code.next_token(last_token)\n while util.match_token(last, token.STRING):\n last_token = last\n last = self._code.next_token(last_token)\n return (first_token, last_token)\n\n def handle_num(self, node, value, first_token, last_token):\n # A constant like \'-1\' gets turned into two tokens; this will skip the \'-\'.\n while util.match_token(last_token, token.OP):\n last_token = self._code.next_token(last_token)\n\n if isinstance(value, complex):\n # A complex number like -2j cannot be compared directly to 0\n # A complex number like 1-2j is expressed as a binary operation\n # so we don\'t need to worry about it\n value = value.imag\n\n # This makes sure that the - is included\n if value < 0 and first_token.type == token.NUMBER:\n first_token = self._code.prev_token(first_token)\n return (first_token, last_token)\n\n def visit_num(self, node, first_token, last_token):\n return self.handle_num(node, node.n, first_token, last_token)\n\n # In Astroid, the Num and Str nodes are replaced by Const.\n def visit_const(self, node, first_token, last_token):\n if isinstance(node.value, numbers.Number):\n return self.handle_num(node, node.value, first_token, last_token)\n elif isinstance(node.value, (six.text_type, six.binary_type)):\n return self.visit_str(node, first_token, last_token)\n return (first_token, last_token)\n\n # In Python >= 3.6, there is a similar class \'Constant\' for literals\n # In 3.8 it became the type produced by ast.parse\n # https://bugs.python.org/issue32892\n visit_constant = visit_const\n\n def visit_keyword(self, node, first_token, last_token):\n # Until python 3.9 (https://bugs.python.org/issue40141),\n # ast.keyword nodes didn\'t have line info. Astroid has lineno None.\n if node.arg is not None and getattr(node, \'lineno\', None) is None:\n equals = self._code.find_token(first_token, token.OP, \'=\', reverse=True)\n name = self._code.prev_token(equals)\n util.expect_token(name, token.NAME, node.arg)\n first_token = name\n return (first_token, last_token)\n\n def visit_starred(self, node, first_token, last_token):\n # Astroid has \'Starred\' nodes (for "foo(*bar)" type args), but they need to be adjusted.\n if not util.match_token(first_token, token.OP, \'*\'):\n star = self._code.prev_token(first_token)\n if util.match_token(star, token.OP, \'*\'):\n first_token = star\n return (first_token, last_token)\n\n def visit_assignname(self, node, first_token, last_token):\n # Astroid may turn \'except\' clause into AssignName, but we need to adjust it.\n if util.match_token(first_token, token.NAME, \'except\'):\n colon = self._code.find_token(last_token, token.OP, \':\')\n first_token = last_token = self._code.prev_token(colon)\n return (first_token, last_token)\n\n if six.PY2:\n # No need for this on Python3, which already handles \'with\' nodes correctly.\n def visit_with(self, node, first_token, last_token):\n first = self._code.find_token(first_token, token.NAME, \'with\', reverse=True)\n return (first, last_token)\n\n # Async nodes should typically start with the word \'async\'\n # but Python < 3.7 doesn\'t put the col_offset there\n # AsyncFunctionDef is slightly different because it might have\n # decorators before that, which visit_functiondef handles\n def handle_async(self, node, first_token, last_token):\n if not first_token.string == \'async\':\n first_token = self._code.prev_token(first_token)\n return (first_token, last_token)\n\n visit_asyncfor = handle_async\n visit_asyncwith = handle_async\n\n def visit_asyncfunctiondef(self, node, first_token, last_token):\n if util.match_token(first_token, token.NAME, \'def\'):\n # Include the \'async\' token\n first_token = self._code.prev_token(first_token)\n return self.visit_functiondef(node, first_token, last_token)\n') + __stickytape_write_module('icecream/__init__.py', b"# -*- coding: utf-8 -*-\n\n#\n# IceCream - Never use print() to debug again\n#\n# Ansgar Grunseid\n# grunseid.com\n# grunseid@gmail.com\n#\n# License: MIT\n#\n\nfrom os.path import dirname, join as pjoin\n\nfrom .icecream import * # noqa\nfrom .builtins import install, uninstall\n\n# Import all variables in __version__.py without explicit imports.\nmeta = {}\nwith open(pjoin(dirname(__file__), '__version__.py')) as f:\n exec(f.read(), meta)\nglobals().update(dict((k, v) for k, v in meta.items() if k not in globals()))\n") + __stickytape_write_module('icecream/icecream.py', b'#!/usr/bin/env python\n# -*- coding: utf-8 -*-\n\n#\n# IceCream - Never use print() to debug again\n#\n# Ansgar Grunseid\n# grunseid.com\n# grunseid@gmail.com\n#\n# License: MIT\n#\n\nfrom __future__ import print_function\n\nimport ast\nimport inspect\nimport pprint\nimport sys\nfrom datetime import datetime\nfrom contextlib import contextmanager\nfrom os.path import basename\nfrom textwrap import dedent\n\nimport colorama\nimport executing\nfrom pygments import highlight\n# See https://gist.github.com/XVilka/8346728 for color support in various\n# terminals and thus whether to use Terminal256Formatter or\n# TerminalTrueColorFormatter.\nfrom pygments.formatters import Terminal256Formatter\nfrom pygments.lexers import PythonLexer as PyLexer, Python3Lexer as Py3Lexer\n\nfrom .coloring import SolarizedDark\n\n\nPYTHON2 = (sys.version_info[0] == 2)\n\n\n_absent = object()\n\n\ndef bindStaticVariable(name, value):\n def decorator(fn):\n setattr(fn, name, value)\n return fn\n return decorator\n\n\n@bindStaticVariable(\'formatter\', Terminal256Formatter(style=SolarizedDark))\n@bindStaticVariable(\n \'lexer\', PyLexer(ensurenl=False) if PYTHON2 else Py3Lexer(ensurenl=False))\ndef colorize(s):\n self = colorize\n return highlight(s, self.lexer, self.formatter)\n\n\n@contextmanager\ndef supportTerminalColorsInWindows():\n # Filter and replace ANSI escape sequences on Windows with equivalent Win32\n # API calls. This code does nothing on non-Windows systems.\n colorama.init()\n yield\n colorama.deinit()\n\n\ndef stderrPrint(*args):\n print(*args, file=sys.stderr)\n\n\ndef isLiteral(s):\n try:\n ast.literal_eval(s)\n except Exception:\n return False\n return True\n\n\ndef colorizedStderrPrint(s):\n colored = colorize(s)\n with supportTerminalColorsInWindows():\n stderrPrint(colored)\n\n\nDEFAULT_PREFIX = \'ic| \'\nDEFAULT_LINE_WRAP_WIDTH = 70 # Characters.\nDEFAULT_CONTEXT_DELIMITER = \'- \'\nDEFAULT_OUTPUT_FUNCTION = colorizedStderrPrint\nDEFAULT_ARG_TO_STRING_FUNCTION = pprint.pformat\n\n\nclass NoSourceAvailableError(OSError):\n """\n Raised when icecream fails to find or access source code that\'s\n required to parse and analyze. This can happen, for example, when\n\n - ic() is invoked inside an interactive shell, e.g. python -i.\n\n - The source code is mangled and/or packaged, e.g. with a project\n freezer like PyInstaller.\n\n - The underlying source code changed during execution. See\n https://stackoverflow.com/a/33175832.\n """\n infoMessage = (\n \'Failed to access the underlying source code for analysis. Was ic() \'\n \'invoked in an interpreter (e.g. python -i), a frozen application \'\n \'(e.g. packaged with PyInstaller), or did the underlying source code \'\n \'change during execution?\')\n\n\ndef callOrValue(obj):\n return obj() if callable(obj) else obj\n\n\nclass Source(executing.Source):\n def get_text_with_indentation(self, node):\n result = self.asttokens().get_text(node)\n if \'\\n\' in result:\n result = \' \' * node.first_token.start[1] + result\n result = dedent(result)\n result = result.strip()\n return result\n\n\ndef prefixLinesAfterFirst(prefix, s):\n lines = s.splitlines(True)\n\n for i in range(1, len(lines)):\n lines[i] = prefix + lines[i]\n\n return \'\'.join(lines)\n\n\ndef indented_lines(prefix, string):\n lines = string.splitlines()\n return [prefix + lines[0]] + [\n \' \' * len(prefix) + line\n for line in lines[1:]\n ]\n\n\ndef format_pair(prefix, arg, value):\n arg_lines = indented_lines(prefix, arg)\n value_prefix = arg_lines[-1] + \': \'\n\n looksLikeAString = value[0] + value[-1] in ["\'\'", \'""\']\n if looksLikeAString: # Align the start of multiline strings.\n value = prefixLinesAfterFirst(\' \', value)\n\n value_lines = indented_lines(value_prefix, value)\n lines = arg_lines[:-1] + value_lines\n return \'\\n\'.join(lines)\n\n\ndef argumentToString(obj):\n s = DEFAULT_ARG_TO_STRING_FUNCTION(obj)\n s = s.replace(\'\\\\n\', \'\\n\') # Preserve string newlines in output.\n return s\n\n\nclass IceCreamDebugger:\n _pairDelimiter = \', \' # Used by the tests in tests/.\n lineWrapWidth = DEFAULT_LINE_WRAP_WIDTH\n contextDelimiter = DEFAULT_CONTEXT_DELIMITER\n\n def __init__(self, prefix=DEFAULT_PREFIX,\n outputFunction=DEFAULT_OUTPUT_FUNCTION,\n argToStringFunction=argumentToString, includeContext=False):\n self.enabled = True\n self.prefix = prefix\n self.includeContext = includeContext\n self.outputFunction = outputFunction\n self.argToStringFunction = argToStringFunction\n\n def __call__(self, *args):\n if self.enabled:\n callFrame = inspect.currentframe().f_back\n try:\n out = self._format(callFrame, *args)\n except NoSourceAvailableError as err:\n prefix = callOrValue(self.prefix)\n out = prefix + \'Error: \' + err.infoMessage\n self.outputFunction(out)\n\n if not args: # E.g. ic().\n passthrough = None\n elif len(args) == 1: # E.g. ic(1).\n passthrough = args[0]\n else: # E.g. ic(1, 2, 3).\n passthrough = args\n\n return passthrough\n\n def format(self, *args):\n callFrame = inspect.currentframe().f_back\n out = self._format(callFrame, *args)\n return out\n\n def _format(self, callFrame, *args):\n prefix = callOrValue(self.prefix)\n\n callNode = Source.executing(callFrame).node\n if callNode is None:\n raise NoSourceAvailableError()\n\n context = self._formatContext(callFrame, callNode)\n if not args:\n time = self._formatTime()\n out = prefix + context + time\n else:\n if not self.includeContext:\n context = \'\'\n out = self._formatArgs(\n callFrame, callNode, prefix, context, args)\n\n return out\n\n def _formatArgs(self, callFrame, callNode, prefix, context, args):\n source = Source.for_frame(callFrame)\n sanitizedArgStrs = [\n source.get_text_with_indentation(arg)\n for arg in callNode.args]\n\n pairs = list(zip(sanitizedArgStrs, args))\n\n out = self._constructArgumentOutput(prefix, context, pairs)\n return out\n\n def _constructArgumentOutput(self, prefix, context, pairs):\n def argPrefix(arg):\n return \'%s: \' % arg\n\n pairs = [(arg, self.argToStringFunction(val)) for arg, val in pairs]\n # For cleaner output, if is a literal, eg 3, "string", b\'bytes\',\n # etc, only output the value, not the argument and the value, as the\n # argument and the value will be identical or nigh identical. Ex: with\n # ic("hello"), just output\n #\n # ic| \'hello\',\n #\n # instead of\n #\n # ic| "hello": \'hello\'.\n #\n pairStrs = [\n val if isLiteral(arg) else (argPrefix(arg) + val)\n for arg, val in pairs]\n\n allArgsOnOneLine = self._pairDelimiter.join(pairStrs)\n multilineArgs = len(allArgsOnOneLine.splitlines()) > 1\n\n contextDelimiter = self.contextDelimiter if context else \'\'\n allPairs = prefix + context + contextDelimiter + allArgsOnOneLine\n firstLineTooLong = len(allPairs.splitlines()[0]) > self.lineWrapWidth\n\n if multilineArgs or firstLineTooLong:\n # ic| foo.py:11 in foo()\n # multilineStr: \'line1\n # line2\'\n #\n # ic| foo.py:11 in foo()\n # a: 11111111111111111111\n # b: 22222222222222222222\n if context:\n lines = [prefix + context] + [\n format_pair(len(prefix) * \' \', arg, value)\n for arg, value in pairs\n ]\n # ic| multilineStr: \'line1\n # line2\'\n #\n # ic| a: 11111111111111111111\n # b: 22222222222222222222\n else:\n arg_lines = [\n format_pair(\'\', arg, value)\n for arg, value in pairs\n ]\n lines = indented_lines(prefix, \'\\n\'.join(arg_lines))\n # ic| foo.py:11 in foo()- a: 1, b: 2\n # ic| a: 1, b: 2, c: 3\n else:\n lines = [prefix + context + contextDelimiter + allArgsOnOneLine]\n\n return \'\\n\'.join(lines)\n\n def _formatContext(self, callFrame, callNode):\n filename, lineNumber, parentFunction = self._getContext(\n callFrame, callNode)\n\n if parentFunction != \'\':\n parentFunction = \'%s()\' % parentFunction\n\n context = \'%s:%s in %s\' % (filename, lineNumber, parentFunction)\n return context\n\n def _formatTime(self):\n now = datetime.now()\n formatted = now.strftime(\'%H:%M:%S.%f\')[:-3]\n return \' at %s\' % formatted\n\n def _getContext(self, callFrame, callNode):\n lineNumber = callNode.lineno\n frameInfo = inspect.getframeinfo(callFrame)\n parentFunction = frameInfo.function\n filename = basename(frameInfo.filename)\n\n return filename, lineNumber, parentFunction\n\n def enable(self):\n self.enabled = True\n\n def disable(self):\n self.enabled = False\n\n def configureOutput(self, prefix=_absent, outputFunction=_absent,\n argToStringFunction=_absent, includeContext=_absent):\n if prefix is not _absent:\n self.prefix = prefix\n\n if outputFunction is not _absent:\n self.outputFunction = outputFunction\n\n if argToStringFunction is not _absent:\n self.argToStringFunction = argToStringFunction\n\n if includeContext is not _absent:\n self.includeContext = includeContext\n\n\nic = IceCreamDebugger()\n') + __stickytape_write_module('colorama/__init__.py', b"# Copyright Jonathan Hartley 2013. BSD 3-Clause license, see LICENSE file.\nfrom .initialise import init, deinit, reinit, colorama_text\nfrom .ansi import Fore, Back, Style, Cursor\nfrom .ansitowin32 import AnsiToWin32\n\n__version__ = '0.4.4'\n") + __stickytape_write_module('colorama/initialise.py', b"# Copyright Jonathan Hartley 2013. BSD 3-Clause license, see LICENSE file.\nimport atexit\nimport contextlib\nimport sys\n\nfrom .ansitowin32 import AnsiToWin32\n\n\norig_stdout = None\norig_stderr = None\n\nwrapped_stdout = None\nwrapped_stderr = None\n\natexit_done = False\n\n\ndef reset_all():\n if AnsiToWin32 is not None: # Issue #74: objects might become None at exit\n AnsiToWin32(orig_stdout).reset_all()\n\n\ndef init(autoreset=False, convert=None, strip=None, wrap=True):\n\n if not wrap and any([autoreset, convert, strip]):\n raise ValueError('wrap=False conflicts with any other arg=True')\n\n global wrapped_stdout, wrapped_stderr\n global orig_stdout, orig_stderr\n\n orig_stdout = sys.stdout\n orig_stderr = sys.stderr\n\n if sys.stdout is None:\n wrapped_stdout = None\n else:\n sys.stdout = wrapped_stdout = \\\n wrap_stream(orig_stdout, convert, strip, autoreset, wrap)\n if sys.stderr is None:\n wrapped_stderr = None\n else:\n sys.stderr = wrapped_stderr = \\\n wrap_stream(orig_stderr, convert, strip, autoreset, wrap)\n\n global atexit_done\n if not atexit_done:\n atexit.register(reset_all)\n atexit_done = True\n\n\ndef deinit():\n if orig_stdout is not None:\n sys.stdout = orig_stdout\n if orig_stderr is not None:\n sys.stderr = orig_stderr\n\n\n@contextlib.contextmanager\ndef colorama_text(*args, **kwargs):\n init(*args, **kwargs)\n try:\n yield\n finally:\n deinit()\n\n\ndef reinit():\n if wrapped_stdout is not None:\n sys.stdout = wrapped_stdout\n if wrapped_stderr is not None:\n sys.stderr = wrapped_stderr\n\n\ndef wrap_stream(stream, convert, strip, autoreset, wrap):\n if wrap:\n wrapper = AnsiToWin32(stream,\n convert=convert, strip=strip, autoreset=autoreset)\n if wrapper.should_wrap():\n stream = wrapper.stream\n return stream\n") + __stickytape_write_module('colorama/ansitowin32.py', b'# Copyright Jonathan Hartley 2013. BSD 3-Clause license, see LICENSE file.\nimport re\nimport sys\nimport os\n\nfrom .ansi import AnsiFore, AnsiBack, AnsiStyle, Style, BEL\nfrom .winterm import WinTerm, WinColor, WinStyle\nfrom .win32 import windll, winapi_test\n\n\nwinterm = None\nif windll is not None:\n winterm = WinTerm()\n\n\nclass StreamWrapper(object):\n \'\'\'\n Wraps a stream (such as stdout), acting as a transparent proxy for all\n attribute access apart from method \'write()\', which is delegated to our\n Converter instance.\n \'\'\'\n def __init__(self, wrapped, converter):\n # double-underscore everything to prevent clashes with names of\n # attributes on the wrapped stream object.\n self.__wrapped = wrapped\n self.__convertor = converter\n\n def __getattr__(self, name):\n return getattr(self.__wrapped, name)\n\n def __enter__(self, *args, **kwargs):\n # special method lookup bypasses __getattr__/__getattribute__, see\n # https://stackoverflow.com/questions/12632894/why-doesnt-getattr-work-with-exit\n # thus, contextlib magic methods are not proxied via __getattr__\n return self.__wrapped.__enter__(*args, **kwargs)\n\n def __exit__(self, *args, **kwargs):\n return self.__wrapped.__exit__(*args, **kwargs)\n\n def write(self, text):\n self.__convertor.write(text)\n\n def isatty(self):\n stream = self.__wrapped\n if \'PYCHARM_HOSTED\' in os.environ:\n if stream is not None and (stream is sys.__stdout__ or stream is sys.__stderr__):\n return True\n try:\n stream_isatty = stream.isatty\n except AttributeError:\n return False\n else:\n return stream_isatty()\n\n @property\n def closed(self):\n stream = self.__wrapped\n try:\n return stream.closed\n except AttributeError:\n return True\n\n\nclass AnsiToWin32(object):\n \'\'\'\n Implements a \'write()\' method which, on Windows, will strip ANSI character\n sequences from the text, and if outputting to a tty, will convert them into\n win32 function calls.\n \'\'\'\n ANSI_CSI_RE = re.compile(\'\\001?\\033\\\\[((?:\\\\d|;)*)([a-zA-Z])\\002?\') # Control Sequence Introducer\n ANSI_OSC_RE = re.compile(\'\\001?\\033\\\\]([^\\a]*)(\\a)\\002?\') # Operating System Command\n\n def __init__(self, wrapped, convert=None, strip=None, autoreset=False):\n # The wrapped stream (normally sys.stdout or sys.stderr)\n self.wrapped = wrapped\n\n # should we reset colors to defaults after every .write()\n self.autoreset = autoreset\n\n # create the proxy wrapping our output stream\n self.stream = StreamWrapper(wrapped, self)\n\n on_windows = os.name == \'nt\'\n # We test if the WinAPI works, because even if we are on Windows\n # we may be using a terminal that doesn\'t support the WinAPI\n # (e.g. Cygwin Terminal). In this case it\'s up to the terminal\n # to support the ANSI codes.\n conversion_supported = on_windows and winapi_test()\n\n # should we strip ANSI sequences from our output?\n if strip is None:\n strip = conversion_supported or (not self.stream.closed and not self.stream.isatty())\n self.strip = strip\n\n # should we should convert ANSI sequences into win32 calls?\n if convert is None:\n convert = conversion_supported and not self.stream.closed and self.stream.isatty()\n self.convert = convert\n\n # dict of ansi codes to win32 functions and parameters\n self.win32_calls = self.get_win32_calls()\n\n # are we wrapping stderr?\n self.on_stderr = self.wrapped is sys.stderr\n\n def should_wrap(self):\n \'\'\'\n True if this class is actually needed. If false, then the output\n stream will not be affected, nor will win32 calls be issued, so\n wrapping stdout is not actually required. This will generally be\n False on non-Windows platforms, unless optional functionality like\n autoreset has been requested using kwargs to init()\n \'\'\'\n return self.convert or self.strip or self.autoreset\n\n def get_win32_calls(self):\n if self.convert and winterm:\n return {\n AnsiStyle.RESET_ALL: (winterm.reset_all, ),\n AnsiStyle.BRIGHT: (winterm.style, WinStyle.BRIGHT),\n AnsiStyle.DIM: (winterm.style, WinStyle.NORMAL),\n AnsiStyle.NORMAL: (winterm.style, WinStyle.NORMAL),\n AnsiFore.BLACK: (winterm.fore, WinColor.BLACK),\n AnsiFore.RED: (winterm.fore, WinColor.RED),\n AnsiFore.GREEN: (winterm.fore, WinColor.GREEN),\n AnsiFore.YELLOW: (winterm.fore, WinColor.YELLOW),\n AnsiFore.BLUE: (winterm.fore, WinColor.BLUE),\n AnsiFore.MAGENTA: (winterm.fore, WinColor.MAGENTA),\n AnsiFore.CYAN: (winterm.fore, WinColor.CYAN),\n AnsiFore.WHITE: (winterm.fore, WinColor.GREY),\n AnsiFore.RESET: (winterm.fore, ),\n AnsiFore.LIGHTBLACK_EX: (winterm.fore, WinColor.BLACK, True),\n AnsiFore.LIGHTRED_EX: (winterm.fore, WinColor.RED, True),\n AnsiFore.LIGHTGREEN_EX: (winterm.fore, WinColor.GREEN, True),\n AnsiFore.LIGHTYELLOW_EX: (winterm.fore, WinColor.YELLOW, True),\n AnsiFore.LIGHTBLUE_EX: (winterm.fore, WinColor.BLUE, True),\n AnsiFore.LIGHTMAGENTA_EX: (winterm.fore, WinColor.MAGENTA, True),\n AnsiFore.LIGHTCYAN_EX: (winterm.fore, WinColor.CYAN, True),\n AnsiFore.LIGHTWHITE_EX: (winterm.fore, WinColor.GREY, True),\n AnsiBack.BLACK: (winterm.back, WinColor.BLACK),\n AnsiBack.RED: (winterm.back, WinColor.RED),\n AnsiBack.GREEN: (winterm.back, WinColor.GREEN),\n AnsiBack.YELLOW: (winterm.back, WinColor.YELLOW),\n AnsiBack.BLUE: (winterm.back, WinColor.BLUE),\n AnsiBack.MAGENTA: (winterm.back, WinColor.MAGENTA),\n AnsiBack.CYAN: (winterm.back, WinColor.CYAN),\n AnsiBack.WHITE: (winterm.back, WinColor.GREY),\n AnsiBack.RESET: (winterm.back, ),\n AnsiBack.LIGHTBLACK_EX: (winterm.back, WinColor.BLACK, True),\n AnsiBack.LIGHTRED_EX: (winterm.back, WinColor.RED, True),\n AnsiBack.LIGHTGREEN_EX: (winterm.back, WinColor.GREEN, True),\n AnsiBack.LIGHTYELLOW_EX: (winterm.back, WinColor.YELLOW, True),\n AnsiBack.LIGHTBLUE_EX: (winterm.back, WinColor.BLUE, True),\n AnsiBack.LIGHTMAGENTA_EX: (winterm.back, WinColor.MAGENTA, True),\n AnsiBack.LIGHTCYAN_EX: (winterm.back, WinColor.CYAN, True),\n AnsiBack.LIGHTWHITE_EX: (winterm.back, WinColor.GREY, True),\n }\n return dict()\n\n def write(self, text):\n if self.strip or self.convert:\n self.write_and_convert(text)\n else:\n self.wrapped.write(text)\n self.wrapped.flush()\n if self.autoreset:\n self.reset_all()\n\n\n def reset_all(self):\n if self.convert:\n self.call_win32(\'m\', (0,))\n elif not self.strip and not self.stream.closed:\n self.wrapped.write(Style.RESET_ALL)\n\n\n def write_and_convert(self, text):\n \'\'\'\n Write the given text to our wrapped stream, stripping any ANSI\n sequences from the text, and optionally converting them into win32\n calls.\n \'\'\'\n cursor = 0\n text = self.convert_osc(text)\n for match in self.ANSI_CSI_RE.finditer(text):\n start, end = match.span()\n self.write_plain_text(text, cursor, start)\n self.convert_ansi(*match.groups())\n cursor = end\n self.write_plain_text(text, cursor, len(text))\n\n\n def write_plain_text(self, text, start, end):\n if start < end:\n self.wrapped.write(text[start:end])\n self.wrapped.flush()\n\n\n def convert_ansi(self, paramstring, command):\n if self.convert:\n params = self.extract_params(command, paramstring)\n self.call_win32(command, params)\n\n\n def extract_params(self, command, paramstring):\n if command in \'Hf\':\n params = tuple(int(p) if len(p) != 0 else 1 for p in paramstring.split(\';\'))\n while len(params) < 2:\n # defaults:\n params = params + (1,)\n else:\n params = tuple(int(p) for p in paramstring.split(\';\') if len(p) != 0)\n if len(params) == 0:\n # defaults:\n if command in \'JKm\':\n params = (0,)\n elif command in \'ABCD\':\n params = (1,)\n\n return params\n\n\n def call_win32(self, command, params):\n if command == \'m\':\n for param in params:\n if param in self.win32_calls:\n func_args = self.win32_calls[param]\n func = func_args[0]\n args = func_args[1:]\n kwargs = dict(on_stderr=self.on_stderr)\n func(*args, **kwargs)\n elif command in \'J\':\n winterm.erase_screen(params[0], on_stderr=self.on_stderr)\n elif command in \'K\':\n winterm.erase_line(params[0], on_stderr=self.on_stderr)\n elif command in \'Hf\': # cursor position - absolute\n winterm.set_cursor_position(params, on_stderr=self.on_stderr)\n elif command in \'ABCD\': # cursor position - relative\n n = params[0]\n # A - up, B - down, C - forward, D - back\n x, y = {\'A\': (0, -n), \'B\': (0, n), \'C\': (n, 0), \'D\': (-n, 0)}[command]\n winterm.cursor_adjust(x, y, on_stderr=self.on_stderr)\n\n\n def convert_osc(self, text):\n for match in self.ANSI_OSC_RE.finditer(text):\n start, end = match.span()\n text = text[:start] + text[end:]\n paramstring, command = match.groups()\n if command == BEL:\n if paramstring.count(";") == 1:\n params = paramstring.split(";")\n # 0 - change title and icon (we will only change title)\n # 1 - change icon (we don\'t support this)\n # 2 - change title\n if params[0] in \'02\':\n winterm.set_title(params[1])\n return text\n') + __stickytape_write_module('colorama/ansi.py', b"# Copyright Jonathan Hartley 2013. BSD 3-Clause license, see LICENSE file.\n'''\nThis module generates ANSI character codes to printing colors to terminals.\nSee: http://en.wikipedia.org/wiki/ANSI_escape_code\n'''\n\nCSI = '\\033['\nOSC = '\\033]'\nBEL = '\\a'\n\n\ndef code_to_chars(code):\n return CSI + str(code) + 'm'\n\ndef set_title(title):\n return OSC + '2;' + title + BEL\n\ndef clear_screen(mode=2):\n return CSI + str(mode) + 'J'\n\ndef clear_line(mode=2):\n return CSI + str(mode) + 'K'\n\n\nclass AnsiCodes(object):\n def __init__(self):\n # the subclasses declare class attributes which are numbers.\n # Upon instantiation we define instance attributes, which are the same\n # as the class attributes but wrapped with the ANSI escape sequence\n for name in dir(self):\n if not name.startswith('_'):\n value = getattr(self, name)\n setattr(self, name, code_to_chars(value))\n\n\nclass AnsiCursor(object):\n def UP(self, n=1):\n return CSI + str(n) + 'A'\n def DOWN(self, n=1):\n return CSI + str(n) + 'B'\n def FORWARD(self, n=1):\n return CSI + str(n) + 'C'\n def BACK(self, n=1):\n return CSI + str(n) + 'D'\n def POS(self, x=1, y=1):\n return CSI + str(y) + ';' + str(x) + 'H'\n\n\nclass AnsiFore(AnsiCodes):\n BLACK = 30\n RED = 31\n GREEN = 32\n YELLOW = 33\n BLUE = 34\n MAGENTA = 35\n CYAN = 36\n WHITE = 37\n RESET = 39\n\n # These are fairly well supported, but not part of the standard.\n LIGHTBLACK_EX = 90\n LIGHTRED_EX = 91\n LIGHTGREEN_EX = 92\n LIGHTYELLOW_EX = 93\n LIGHTBLUE_EX = 94\n LIGHTMAGENTA_EX = 95\n LIGHTCYAN_EX = 96\n LIGHTWHITE_EX = 97\n\n\nclass AnsiBack(AnsiCodes):\n BLACK = 40\n RED = 41\n GREEN = 42\n YELLOW = 43\n BLUE = 44\n MAGENTA = 45\n CYAN = 46\n WHITE = 47\n RESET = 49\n\n # These are fairly well supported, but not part of the standard.\n LIGHTBLACK_EX = 100\n LIGHTRED_EX = 101\n LIGHTGREEN_EX = 102\n LIGHTYELLOW_EX = 103\n LIGHTBLUE_EX = 104\n LIGHTMAGENTA_EX = 105\n LIGHTCYAN_EX = 106\n LIGHTWHITE_EX = 107\n\n\nclass AnsiStyle(AnsiCodes):\n BRIGHT = 1\n DIM = 2\n NORMAL = 22\n RESET_ALL = 0\n\nFore = AnsiFore()\nBack = AnsiBack()\nStyle = AnsiStyle()\nCursor = AnsiCursor()\n") + __stickytape_write_module('colorama/winterm.py', b"# Copyright Jonathan Hartley 2013. BSD 3-Clause license, see LICENSE file.\nfrom . import win32\n\n\n# from wincon.h\nclass WinColor(object):\n BLACK = 0\n BLUE = 1\n GREEN = 2\n CYAN = 3\n RED = 4\n MAGENTA = 5\n YELLOW = 6\n GREY = 7\n\n# from wincon.h\nclass WinStyle(object):\n NORMAL = 0x00 # dim text, dim background\n BRIGHT = 0x08 # bright text, dim background\n BRIGHT_BACKGROUND = 0x80 # dim text, bright background\n\nclass WinTerm(object):\n\n def __init__(self):\n self._default = win32.GetConsoleScreenBufferInfo(win32.STDOUT).wAttributes\n self.set_attrs(self._default)\n self._default_fore = self._fore\n self._default_back = self._back\n self._default_style = self._style\n # In order to emulate LIGHT_EX in windows, we borrow the BRIGHT style.\n # So that LIGHT_EX colors and BRIGHT style do not clobber each other,\n # we track them separately, since LIGHT_EX is overwritten by Fore/Back\n # and BRIGHT is overwritten by Style codes.\n self._light = 0\n\n def get_attrs(self):\n return self._fore + self._back * 16 + (self._style | self._light)\n\n def set_attrs(self, value):\n self._fore = value & 7\n self._back = (value >> 4) & 7\n self._style = value & (WinStyle.BRIGHT | WinStyle.BRIGHT_BACKGROUND)\n\n def reset_all(self, on_stderr=None):\n self.set_attrs(self._default)\n self.set_console(attrs=self._default)\n self._light = 0\n\n def fore(self, fore=None, light=False, on_stderr=False):\n if fore is None:\n fore = self._default_fore\n self._fore = fore\n # Emulate LIGHT_EX with BRIGHT Style\n if light:\n self._light |= WinStyle.BRIGHT\n else:\n self._light &= ~WinStyle.BRIGHT\n self.set_console(on_stderr=on_stderr)\n\n def back(self, back=None, light=False, on_stderr=False):\n if back is None:\n back = self._default_back\n self._back = back\n # Emulate LIGHT_EX with BRIGHT_BACKGROUND Style\n if light:\n self._light |= WinStyle.BRIGHT_BACKGROUND\n else:\n self._light &= ~WinStyle.BRIGHT_BACKGROUND\n self.set_console(on_stderr=on_stderr)\n\n def style(self, style=None, on_stderr=False):\n if style is None:\n style = self._default_style\n self._style = style\n self.set_console(on_stderr=on_stderr)\n\n def set_console(self, attrs=None, on_stderr=False):\n if attrs is None:\n attrs = self.get_attrs()\n handle = win32.STDOUT\n if on_stderr:\n handle = win32.STDERR\n win32.SetConsoleTextAttribute(handle, attrs)\n\n def get_position(self, handle):\n position = win32.GetConsoleScreenBufferInfo(handle).dwCursorPosition\n # Because Windows coordinates are 0-based,\n # and win32.SetConsoleCursorPosition expects 1-based.\n position.X += 1\n position.Y += 1\n return position\n\n def set_cursor_position(self, position=None, on_stderr=False):\n if position is None:\n # I'm not currently tracking the position, so there is no default.\n # position = self.get_position()\n return\n handle = win32.STDOUT\n if on_stderr:\n handle = win32.STDERR\n win32.SetConsoleCursorPosition(handle, position)\n\n def cursor_adjust(self, x, y, on_stderr=False):\n handle = win32.STDOUT\n if on_stderr:\n handle = win32.STDERR\n position = self.get_position(handle)\n adjusted_position = (position.Y + y, position.X + x)\n win32.SetConsoleCursorPosition(handle, adjusted_position, adjust=False)\n\n def erase_screen(self, mode=0, on_stderr=False):\n # 0 should clear from the cursor to the end of the screen.\n # 1 should clear from the cursor to the beginning of the screen.\n # 2 should clear the entire screen, and move cursor to (1,1)\n handle = win32.STDOUT\n if on_stderr:\n handle = win32.STDERR\n csbi = win32.GetConsoleScreenBufferInfo(handle)\n # get the number of character cells in the current buffer\n cells_in_screen = csbi.dwSize.X * csbi.dwSize.Y\n # get number of character cells before current cursor position\n cells_before_cursor = csbi.dwSize.X * csbi.dwCursorPosition.Y + csbi.dwCursorPosition.X\n if mode == 0:\n from_coord = csbi.dwCursorPosition\n cells_to_erase = cells_in_screen - cells_before_cursor\n elif mode == 1:\n from_coord = win32.COORD(0, 0)\n cells_to_erase = cells_before_cursor\n elif mode == 2:\n from_coord = win32.COORD(0, 0)\n cells_to_erase = cells_in_screen\n else:\n # invalid mode\n return\n # fill the entire screen with blanks\n win32.FillConsoleOutputCharacter(handle, ' ', cells_to_erase, from_coord)\n # now set the buffer's attributes accordingly\n win32.FillConsoleOutputAttribute(handle, self.get_attrs(), cells_to_erase, from_coord)\n if mode == 2:\n # put the cursor where needed\n win32.SetConsoleCursorPosition(handle, (1, 1))\n\n def erase_line(self, mode=0, on_stderr=False):\n # 0 should clear from the cursor to the end of the line.\n # 1 should clear from the cursor to the beginning of the line.\n # 2 should clear the entire line.\n handle = win32.STDOUT\n if on_stderr:\n handle = win32.STDERR\n csbi = win32.GetConsoleScreenBufferInfo(handle)\n if mode == 0:\n from_coord = csbi.dwCursorPosition\n cells_to_erase = csbi.dwSize.X - csbi.dwCursorPosition.X\n elif mode == 1:\n from_coord = win32.COORD(0, csbi.dwCursorPosition.Y)\n cells_to_erase = csbi.dwCursorPosition.X\n elif mode == 2:\n from_coord = win32.COORD(0, csbi.dwCursorPosition.Y)\n cells_to_erase = csbi.dwSize.X\n else:\n # invalid mode\n return\n # fill the entire screen with blanks\n win32.FillConsoleOutputCharacter(handle, ' ', cells_to_erase, from_coord)\n # now set the buffer's attributes accordingly\n win32.FillConsoleOutputAttribute(handle, self.get_attrs(), cells_to_erase, from_coord)\n\n def set_title(self, title):\n win32.SetConsoleTitle(title)\n") + __stickytape_write_module('colorama/win32.py', b'# Copyright Jonathan Hartley 2013. BSD 3-Clause license, see LICENSE file.\n\n# from winbase.h\nSTDOUT = -11\nSTDERR = -12\n\ntry:\n import ctypes\n from ctypes import LibraryLoader\n windll = LibraryLoader(ctypes.WinDLL)\n from ctypes import wintypes\nexcept (AttributeError, ImportError):\n windll = None\n SetConsoleTextAttribute = lambda *_: None\n winapi_test = lambda *_: None\nelse:\n from ctypes import byref, Structure, c_char, POINTER\n\n COORD = wintypes._COORD\n\n class CONSOLE_SCREEN_BUFFER_INFO(Structure):\n """struct in wincon.h."""\n _fields_ = [\n ("dwSize", COORD),\n ("dwCursorPosition", COORD),\n ("wAttributes", wintypes.WORD),\n ("srWindow", wintypes.SMALL_RECT),\n ("dwMaximumWindowSize", COORD),\n ]\n def __str__(self):\n return \'(%d,%d,%d,%d,%d,%d,%d,%d,%d,%d,%d)\' % (\n self.dwSize.Y, self.dwSize.X\n , self.dwCursorPosition.Y, self.dwCursorPosition.X\n , self.wAttributes\n , self.srWindow.Top, self.srWindow.Left, self.srWindow.Bottom, self.srWindow.Right\n , self.dwMaximumWindowSize.Y, self.dwMaximumWindowSize.X\n )\n\n _GetStdHandle = windll.kernel32.GetStdHandle\n _GetStdHandle.argtypes = [\n wintypes.DWORD,\n ]\n _GetStdHandle.restype = wintypes.HANDLE\n\n _GetConsoleScreenBufferInfo = windll.kernel32.GetConsoleScreenBufferInfo\n _GetConsoleScreenBufferInfo.argtypes = [\n wintypes.HANDLE,\n POINTER(CONSOLE_SCREEN_BUFFER_INFO),\n ]\n _GetConsoleScreenBufferInfo.restype = wintypes.BOOL\n\n _SetConsoleTextAttribute = windll.kernel32.SetConsoleTextAttribute\n _SetConsoleTextAttribute.argtypes = [\n wintypes.HANDLE,\n wintypes.WORD,\n ]\n _SetConsoleTextAttribute.restype = wintypes.BOOL\n\n _SetConsoleCursorPosition = windll.kernel32.SetConsoleCursorPosition\n _SetConsoleCursorPosition.argtypes = [\n wintypes.HANDLE,\n COORD,\n ]\n _SetConsoleCursorPosition.restype = wintypes.BOOL\n\n _FillConsoleOutputCharacterA = windll.kernel32.FillConsoleOutputCharacterA\n _FillConsoleOutputCharacterA.argtypes = [\n wintypes.HANDLE,\n c_char,\n wintypes.DWORD,\n COORD,\n POINTER(wintypes.DWORD),\n ]\n _FillConsoleOutputCharacterA.restype = wintypes.BOOL\n\n _FillConsoleOutputAttribute = windll.kernel32.FillConsoleOutputAttribute\n _FillConsoleOutputAttribute.argtypes = [\n wintypes.HANDLE,\n wintypes.WORD,\n wintypes.DWORD,\n COORD,\n POINTER(wintypes.DWORD),\n ]\n _FillConsoleOutputAttribute.restype = wintypes.BOOL\n\n _SetConsoleTitleW = windll.kernel32.SetConsoleTitleW\n _SetConsoleTitleW.argtypes = [\n wintypes.LPCWSTR\n ]\n _SetConsoleTitleW.restype = wintypes.BOOL\n\n def _winapi_test(handle):\n csbi = CONSOLE_SCREEN_BUFFER_INFO()\n success = _GetConsoleScreenBufferInfo(\n handle, byref(csbi))\n return bool(success)\n\n def winapi_test():\n return any(_winapi_test(h) for h in\n (_GetStdHandle(STDOUT), _GetStdHandle(STDERR)))\n\n def GetConsoleScreenBufferInfo(stream_id=STDOUT):\n handle = _GetStdHandle(stream_id)\n csbi = CONSOLE_SCREEN_BUFFER_INFO()\n success = _GetConsoleScreenBufferInfo(\n handle, byref(csbi))\n return csbi\n\n def SetConsoleTextAttribute(stream_id, attrs):\n handle = _GetStdHandle(stream_id)\n return _SetConsoleTextAttribute(handle, attrs)\n\n def SetConsoleCursorPosition(stream_id, position, adjust=True):\n position = COORD(*position)\n # If the position is out of range, do nothing.\n if position.Y <= 0 or position.X <= 0:\n return\n # Adjust for Windows\' SetConsoleCursorPosition:\n # 1. being 0-based, while ANSI is 1-based.\n # 2. expecting (x,y), while ANSI uses (y,x).\n adjusted_position = COORD(position.Y - 1, position.X - 1)\n if adjust:\n # Adjust for viewport\'s scroll position\n sr = GetConsoleScreenBufferInfo(STDOUT).srWindow\n adjusted_position.Y += sr.Top\n adjusted_position.X += sr.Left\n # Resume normal processing\n handle = _GetStdHandle(stream_id)\n return _SetConsoleCursorPosition(handle, adjusted_position)\n\n def FillConsoleOutputCharacter(stream_id, char, length, start):\n handle = _GetStdHandle(stream_id)\n char = c_char(char.encode())\n length = wintypes.DWORD(length)\n num_written = wintypes.DWORD(0)\n # Note that this is hard-coded for ANSI (vs wide) bytes.\n success = _FillConsoleOutputCharacterA(\n handle, char, length, start, byref(num_written))\n return num_written.value\n\n def FillConsoleOutputAttribute(stream_id, attr, length, start):\n \'\'\' FillConsoleOutputAttribute( hConsole, csbi.wAttributes, dwConSize, coordScreen, &cCharsWritten )\'\'\'\n handle = _GetStdHandle(stream_id)\n attribute = wintypes.WORD(attr)\n length = wintypes.DWORD(length)\n num_written = wintypes.DWORD(0)\n # Note that this is hard-coded for ANSI (vs wide) bytes.\n return _FillConsoleOutputAttribute(\n handle, attribute, length, start, byref(num_written))\n\n def SetConsoleTitle(title):\n return _SetConsoleTitleW(title)\n') + __stickytape_write_module('executing/__init__.py', b'"""\nGet information about what a frame is currently doing. Typical usage:\n\n import executing\n\n node = executing.Source.executing(frame).node\n # node will be an AST node or None\n"""\n\nfrom collections import namedtuple\n_VersionInfo = namedtuple(\'VersionInfo\', (\'major\', \'minor\', \'micro\'))\nfrom .executing import Source, Executing, only, NotOneValueFound, cache, future_flags\ntry:\n from .version import __version__\n if "dev" in __version__:\n raise ValueError\nexcept Exception:\n # version.py is auto-generated with the git tag when building\n __version__ = "???"\n __version_info__ = _VersionInfo(-1, -1, -1)\nelse:\n __version_info__ = _VersionInfo(*map(int, __version__.split(\'.\')))\n\n\n__all__ = ["Source"]\n') + __stickytape_write_module('executing/executing.py', b'import __future__\nimport ast\nimport dis\nimport functools\nimport inspect\nimport io\nimport linecache\nimport sys\nimport types\nfrom collections import defaultdict, namedtuple\nfrom itertools import islice\nfrom operator import attrgetter\nfrom threading import RLock\n\nPY3 = sys.version_info[0] == 3\n\nif PY3:\n # noinspection PyUnresolvedReferences\n from functools import lru_cache\n # noinspection PyUnresolvedReferences\n from tokenize import detect_encoding\n from itertools import zip_longest\n # noinspection PyUnresolvedReferences,PyCompatibility\n from pathlib import Path\n\n cache = lru_cache(maxsize=None)\n text_type = str\nelse:\n from lib2to3.pgen2.tokenize import detect_encoding, cookie_re as encoding_pattern\n from itertools import izip_longest as zip_longest\n\n\n class Path(object):\n pass\n\n\n def cache(func):\n d = {}\n\n @functools.wraps(func)\n def wrapper(*args):\n if args in d:\n return d[args]\n result = d[args] = func(*args)\n return result\n\n return wrapper\n\n\n # noinspection PyUnresolvedReferences\n text_type = unicode\ntry:\n # noinspection PyUnresolvedReferences\n _get_instructions = dis.get_instructions\nexcept AttributeError:\n class Instruction(namedtuple(\'Instruction\', \'offset argval opname starts_line\')):\n lineno = None\n\n\n from dis import HAVE_ARGUMENT, EXTENDED_ARG, hasconst, opname, findlinestarts\n\n # Based on dis.disassemble from 2.7\n # Left as similar as possible for easy diff\n\n def _get_instructions(co):\n code = co.co_code\n linestarts = dict(findlinestarts(co))\n n = len(code)\n i = 0\n extended_arg = 0\n while i < n:\n offset = i\n c = code[i]\n op = ord(c)\n lineno = linestarts.get(i)\n argval = None\n i = i + 1\n if op >= HAVE_ARGUMENT:\n oparg = ord(code[i]) + ord(code[i + 1]) * 256 + extended_arg\n extended_arg = 0\n i = i + 2\n if op == EXTENDED_ARG:\n extended_arg = oparg * 65536\n\n if op in hasconst:\n argval = co.co_consts[oparg]\n yield Instruction(offset, argval, opname[op], lineno)\n\n\ndef assert_(condition, message=""):\n """\n Like an assert statement, but unaffected by -O\n :param condition: value that is expected to be truthy\n :type message: Any\n """\n if not condition:\n raise AssertionError(str(message))\n\n\ndef get_instructions(co):\n lineno = None\n for inst in _get_instructions(co):\n lineno = inst.starts_line or lineno\n assert_(lineno)\n inst.lineno = lineno\n yield inst\n\n\nTESTING = 0\n\n\nclass NotOneValueFound(Exception):\n pass\n\n\ndef only(it):\n if hasattr(it, \'__len__\'):\n if len(it) != 1:\n raise NotOneValueFound(\'Expected one value, found %s\' % len(it))\n # noinspection PyTypeChecker\n return list(it)[0]\n\n lst = tuple(islice(it, 2))\n if len(lst) == 0:\n raise NotOneValueFound(\'Expected one value, found 0\')\n if len(lst) > 1:\n raise NotOneValueFound(\'Expected one value, found several\')\n return lst[0]\n\n\nclass Source(object):\n """\n The source code of a single file and associated metadata.\n\n The main method of interest is the classmethod `executing(frame)`.\n\n If you want an instance of this class, don\'t construct it.\n Ideally use the classmethod `for_frame(frame)`.\n If you don\'t have a frame, use `for_filename(filename [, module_globals])`.\n These methods cache instances by filename, so at most one instance exists per filename.\n\n Attributes:\n - filename\n - text\n - lines\n - tree: AST parsed from text, or None if text is not valid Python\n All nodes in the tree have an extra `parent` attribute\n\n Other methods of interest:\n - statements_at_line\n - asttokens\n - code_qualname\n """\n\n def __init__(self, filename, lines):\n """\n Don\'t call this constructor, see the class docstring.\n """\n\n self.filename = filename\n text = \'\'.join(lines)\n\n if not isinstance(text, text_type):\n encoding = self.detect_encoding(text)\n # noinspection PyUnresolvedReferences\n text = text.decode(encoding)\n lines = [line.decode(encoding) for line in lines]\n\n self.text = text\n self.lines = [line.rstrip(\'\\r\\n\') for line in lines]\n\n if PY3:\n ast_text = text\n else:\n # In python 2 it\'s a syntax error to parse unicode\n # with an encoding declaration, so we remove it but\n # leave empty lines in its place to keep line numbers the same\n ast_text = \'\'.join([\n \'\\n\' if i < 2 and encoding_pattern.match(line)\n else line\n for i, line in enumerate(lines)\n ])\n\n self._nodes_by_line = defaultdict(list)\n self.tree = None\n self._qualnames = {}\n\n try:\n self.tree = ast.parse(ast_text, filename=filename)\n except SyntaxError:\n pass\n else:\n for node in ast.walk(self.tree):\n for child in ast.iter_child_nodes(node):\n child.parent = node\n if hasattr(node, \'lineno\'):\n self._nodes_by_line[node.lineno].append(node)\n\n visitor = QualnameVisitor()\n visitor.visit(self.tree)\n self._qualnames = visitor.qualnames\n\n @classmethod\n def for_frame(cls, frame, use_cache=True):\n """\n Returns the `Source` object corresponding to the file the frame is executing in.\n """\n return cls.for_filename(frame.f_code.co_filename, frame.f_globals or {}, use_cache)\n\n @classmethod\n def for_filename(cls, filename, module_globals=None, use_cache=True):\n if isinstance(filename, Path):\n filename = str(filename)\n\n source_cache = cls._class_local(\'__source_cache\', {})\n if use_cache:\n try:\n return source_cache[filename]\n except KeyError:\n pass\n\n if not use_cache:\n linecache.checkcache(filename)\n\n lines = tuple(linecache.getlines(filename, module_globals))\n result = source_cache[filename] = cls._for_filename_and_lines(filename, lines)\n return result\n\n @classmethod\n def _for_filename_and_lines(cls, filename, lines):\n source_cache = cls._class_local(\'__source_cache_with_lines\', {})\n try:\n return source_cache[(filename, lines)]\n except KeyError:\n pass\n\n result = source_cache[(filename, lines)] = cls(filename, lines)\n return result\n\n @classmethod\n def lazycache(cls, frame):\n if hasattr(linecache, \'lazycache\'):\n linecache.lazycache(frame.f_code.co_filename, frame.f_globals)\n\n @classmethod\n def executing(cls, frame_or_tb):\n """\n Returns an `Executing` object representing the operation\n currently executing in the given frame or traceback object.\n """\n if isinstance(frame_or_tb, types.TracebackType):\n # https://docs.python.org/3/reference/datamodel.html#traceback-objects\n # "tb_lineno gives the line number where the exception occurred;\n # tb_lasti indicates the precise instruction.\n # The line number and last instruction in the traceback may differ\n # from the line number of its frame object\n # if the exception occurred in a try statement with no matching except clause\n # or with a finally clause."\n tb = frame_or_tb\n frame = tb.tb_frame\n lineno = tb.tb_lineno\n lasti = tb.tb_lasti\n else:\n frame = frame_or_tb\n lineno = frame.f_lineno\n lasti = frame.f_lasti\n\n code = frame.f_code\n key = (code, id(code), lasti)\n executing_cache = cls._class_local(\'__executing_cache\', {})\n\n try:\n args = executing_cache[key]\n except KeyError:\n def find(source, retry_cache):\n node = stmts = None\n tree = source.tree\n if tree:\n try:\n stmts = source.statements_at_line(lineno)\n if stmts:\n if code.co_filename.startswith(\'\':\n tree = _extract_ipython_statement(stmts, tree)\n node = NodeFinder(frame, stmts, tree, lasti).result\n except Exception as e:\n # These exceptions can be caused by the source code having changed\n # so the cached Source doesn\'t match the running code\n # (e.g. when using IPython %autoreload)\n # Try again with a fresh Source object\n if retry_cache and isinstance(e, (NotOneValueFound, AssertionError)):\n return find(\n source=cls.for_frame(frame, use_cache=False),\n retry_cache=False,\n )\n if TESTING:\n raise\n\n if node:\n new_stmts = {statement_containing_node(node)}\n assert_(new_stmts <= stmts)\n stmts = new_stmts\n\n return source, node, stmts\n\n args = find(source=cls.for_frame(frame), retry_cache=True)\n executing_cache[key] = args\n\n return Executing(frame, *args)\n\n @classmethod\n def _class_local(cls, name, default):\n """\n Returns an attribute directly associated with this class\n (as opposed to subclasses), setting default if necessary\n """\n # classes have a mappingproxy preventing us from using setdefault\n result = cls.__dict__.get(name, default)\n setattr(cls, name, result)\n return result\n\n @cache\n def statements_at_line(self, lineno):\n """\n Returns the statement nodes overlapping the given line.\n\n Returns at most one statement unless semicolons are present.\n\n If the `text` attribute is not valid python, meaning\n `tree` is None, returns an empty set.\n\n Otherwise, `Source.for_frame(frame).statements_at_line(frame.f_lineno)`\n should return at least one statement.\n """\n\n return {\n statement_containing_node(node)\n for node in\n self._nodes_by_line[lineno]\n }\n\n @cache\n def asttokens(self):\n """\n Returns an ASTTokens object for getting the source of specific AST nodes.\n\n See http://asttokens.readthedocs.io/en/latest/api-index.html\n """\n from asttokens import ASTTokens # must be installed separately\n return ASTTokens(\n self.text,\n tree=self.tree,\n filename=self.filename,\n )\n\n @staticmethod\n def decode_source(source):\n if isinstance(source, bytes):\n encoding = Source.detect_encoding(source)\n source = source.decode(encoding)\n return source\n\n @staticmethod\n def detect_encoding(source):\n return detect_encoding(io.BytesIO(source).readline)[0]\n\n def code_qualname(self, code):\n """\n Imitates the __qualname__ attribute of functions for code objects.\n Given:\n\n - A function `func`\n - A frame `frame` for an execution of `func`, meaning:\n `frame.f_code is func.__code__`\n\n `Source.for_frame(frame).code_qualname(frame.f_code)`\n will be equal to `func.__qualname__`*. Works for Python 2 as well,\n where of course no `__qualname__` attribute exists.\n\n Falls back to `code.co_name` if there is no appropriate qualname.\n\n Based on https://github.com/wbolster/qualname\n\n (* unless `func` is a lambda\n nested inside another lambda on the same line, in which case\n the outer lambda\'s qualname will be returned for the codes\n of both lambdas)\n """\n assert_(code.co_filename == self.filename)\n return self._qualnames.get((code.co_name, code.co_firstlineno), code.co_name)\n\n\nclass Executing(object):\n """\n Information about the operation a frame is currently executing.\n\n Generally you will just want `node`, which is the AST node being executed,\n or None if it\'s unknown.\n """\n\n def __init__(self, frame, source, node, stmts):\n self.frame = frame\n self.source = source\n self.node = node\n self.statements = stmts\n\n def code_qualname(self):\n return self.source.code_qualname(self.frame.f_code)\n\n def text(self):\n return self.source.asttokens().get_text(self.node)\n\n def text_range(self):\n return self.source.asttokens().get_text_range(self.node)\n\n\nclass QualnameVisitor(ast.NodeVisitor):\n def __init__(self):\n super(QualnameVisitor, self).__init__()\n self.stack = []\n self.qualnames = {}\n\n def add_qualname(self, node, name=None):\n name = name or node.name\n self.stack.append(name)\n if getattr(node, \'decorator_list\', ()):\n lineno = node.decorator_list[0].lineno\n else:\n lineno = node.lineno\n self.qualnames.setdefault((name, lineno), ".".join(self.stack))\n\n def visit_FunctionDef(self, node, name=None):\n self.add_qualname(node, name)\n self.stack.append(\'\')\n if isinstance(node, ast.Lambda):\n children = [node.body]\n else:\n children = node.body\n for child in children:\n self.visit(child)\n self.stack.pop()\n self.stack.pop()\n\n # Find lambdas in the function definition outside the body,\n # e.g. decorators or default arguments\n # Based on iter_child_nodes\n for field, child in ast.iter_fields(node):\n if field == \'body\':\n continue\n if isinstance(child, ast.AST):\n self.visit(child)\n elif isinstance(child, list):\n for grandchild in child:\n if isinstance(grandchild, ast.AST):\n self.visit(grandchild)\n\n visit_AsyncFunctionDef = visit_FunctionDef\n\n def visit_Lambda(self, node):\n # noinspection PyTypeChecker\n self.visit_FunctionDef(node, \'\')\n\n def visit_ClassDef(self, node):\n self.add_qualname(node)\n self.generic_visit(node)\n self.stack.pop()\n\n\nfuture_flags = sum(\n getattr(__future__, fname).compiler_flag\n for fname in __future__.all_feature_names\n)\n\n\ndef compile_similar_to(source, matching_code):\n return compile(\n source,\n matching_code.co_filename,\n \'exec\',\n flags=future_flags & matching_code.co_flags,\n dont_inherit=True,\n )\n\n\nsentinel = \'io8urthglkjdghvljusketgIYRFYUVGHFRTBGVHKGF78678957647698\'\n\n\nclass NodeFinder(object):\n def __init__(self, frame, stmts, tree, lasti):\n self.frame = frame\n self.tree = tree\n self.code = code = frame.f_code\n self.is_pytest = any(\n \'pytest\' in name.lower()\n for group in [code.co_names, code.co_varnames]\n for name in group\n )\n\n if self.is_pytest:\n self.ignore_linenos = frozenset(assert_linenos(tree))\n else:\n self.ignore_linenos = frozenset()\n\n instruction = self.get_actual_current_instruction(lasti)\n op_name = instruction.opname\n self.lasti = instruction.offset\n\n if op_name.startswith(\'CALL_\'):\n typ = ast.Call\n elif op_name.startswith((\'BINARY_SUBSCR\', \'SLICE+\')):\n typ = ast.Subscript\n elif op_name.startswith(\'BINARY_\'):\n typ = ast.BinOp\n elif op_name.startswith(\'UNARY_\'):\n typ = ast.UnaryOp\n elif op_name in (\'LOAD_ATTR\', \'LOAD_METHOD\', \'LOOKUP_METHOD\'):\n typ = ast.Attribute\n elif op_name in (\'COMPARE_OP\', \'IS_OP\', \'CONTAINS_OP\'):\n typ = ast.Compare\n else:\n raise RuntimeError(op_name)\n\n with lock:\n exprs = {\n node\n for stmt in stmts\n for node in ast.walk(stmt)\n if isinstance(node, typ)\n if not (hasattr(node, "ctx") and not isinstance(node.ctx, ast.Load))\n }\n\n self.result = only(list(self.matching_nodes(exprs)))\n\n def clean_instructions(self, code):\n return [\n inst\n for inst in get_instructions(code)\n if inst.opname != \'EXTENDED_ARG\'\n if inst.lineno not in self.ignore_linenos\n ]\n\n def get_original_clean_instructions(self):\n result = self.clean_instructions(self.code)\n\n # pypy sometimes (when is not clear)\n # inserts JUMP_IF_NOT_DEBUG instructions in bytecode\n # If they\'re not present in our compiled instructions,\n # ignore them in the original bytecode\n if not any(\n inst.opname == "JUMP_IF_NOT_DEBUG"\n for inst in self.compile_instructions()\n ):\n result = [\n inst for inst in result\n if inst.opname != "JUMP_IF_NOT_DEBUG"\n ]\n\n return result\n\n def matching_nodes(self, exprs):\n original_instructions = self.get_original_clean_instructions()\n original_index = only(\n i\n for i, inst in enumerate(original_instructions)\n if inst.offset == self.lasti\n )\n for i, expr in enumerate(exprs):\n setter = get_setter(expr)\n # noinspection PyArgumentList\n replacement = ast.BinOp(\n left=expr,\n op=ast.Pow(),\n right=ast.Str(s=sentinel),\n )\n ast.fix_missing_locations(replacement)\n setter(replacement)\n try:\n instructions = self.compile_instructions()\n finally:\n setter(expr)\n indices = [\n i\n for i, instruction in enumerate(instructions)\n if instruction.argval == sentinel\n ]\n\n # There can be several indices when the bytecode is duplicated,\n # as happens in a finally block in 3.9+\n # First we remove the opcodes caused by our modifications\n for index_num, sentinel_index in enumerate(indices):\n # Adjustment for removing sentinel instructions below\n # in past iterations\n sentinel_index -= index_num * 2\n\n assert_(instructions.pop(sentinel_index).opname == \'LOAD_CONST\')\n assert_(instructions.pop(sentinel_index).opname == \'BINARY_POWER\')\n\n # Then we see if any of the instruction indices match\n for index_num, sentinel_index in enumerate(indices):\n sentinel_index -= index_num * 2\n new_index = sentinel_index - 1\n\n if new_index != original_index:\n continue\n\n original_inst = original_instructions[original_index]\n new_inst = instructions[new_index]\n\n # In Python 3.9+, changing \'not x in y\' to \'not sentinel_transformation(x in y)\'\n # changes a CONTAINS_OP(invert=1) to CONTAINS_OP(invert=0),,UNARY_NOT\n if (\n original_inst.opname == new_inst.opname in (\'CONTAINS_OP\', \'IS_OP\')\n and original_inst.arg != new_inst.arg\n and (\n original_instructions[original_index + 1].opname\n != instructions[new_index + 1].opname == \'UNARY_NOT\'\n )):\n # Remove the difference for the upcoming assert\n instructions.pop(new_index + 1)\n\n # Check that the modified instructions don\'t have anything unexpected\n for inst1, inst2 in zip_longest(original_instructions, instructions):\n assert_(\n inst1.opname == inst2.opname or\n all(\n \'JUMP_IF_\' in inst.opname\n for inst in [inst1, inst2]\n ) or\n all(\n inst.opname in (\'JUMP_FORWARD\', \'JUMP_ABSOLUTE\')\n for inst in [inst1, inst2]\n )\n or (\n inst1.opname == \'PRINT_EXPR\' and\n inst2.opname == \'POP_TOP\'\n )\n or (\n inst1.opname in (\'LOAD_METHOD\', \'LOOKUP_METHOD\') and\n inst2.opname == \'LOAD_ATTR\'\n )\n or (\n inst1.opname == \'CALL_METHOD\' and\n inst2.opname == \'CALL_FUNCTION\'\n ),\n (inst1, inst2, ast.dump(expr), expr.lineno, self.code.co_filename)\n )\n\n yield expr\n\n def compile_instructions(self):\n module_code = compile_similar_to(self.tree, self.code)\n code = only(self.find_codes(module_code))\n return self.clean_instructions(code)\n\n def find_codes(self, root_code):\n checks = [\n attrgetter(\'co_firstlineno\'),\n attrgetter(\'co_name\'),\n attrgetter(\'co_freevars\'),\n attrgetter(\'co_cellvars\'),\n ]\n if not self.is_pytest:\n checks += [\n attrgetter(\'co_names\'),\n attrgetter(\'co_varnames\'),\n ]\n\n def matches(c):\n return all(\n f(c) == f(self.code)\n for f in checks\n )\n\n code_options = []\n if matches(root_code):\n code_options.append(root_code)\n\n def finder(code):\n for const in code.co_consts:\n if not inspect.iscode(const):\n continue\n\n if matches(const):\n code_options.append(const)\n finder(const)\n\n finder(root_code)\n return code_options\n\n def get_actual_current_instruction(self, lasti):\n """\n Get the instruction corresponding to the current\n frame offset, skipping EXTENDED_ARG instructions\n """\n # Don\'t use get_original_clean_instructions\n # because we need the actual instructions including\n # EXTENDED_ARG\n instructions = list(get_instructions(self.code))\n index = only(\n i\n for i, inst in enumerate(instructions)\n if inst.offset == lasti\n )\n\n while True:\n instruction = instructions[index]\n if instruction.opname != "EXTENDED_ARG":\n return instruction\n index += 1\n\n\ndef get_setter(node):\n parent = node.parent\n for name, field in ast.iter_fields(parent):\n if field is node:\n return lambda new_node: setattr(parent, name, new_node)\n elif isinstance(field, list):\n for i, item in enumerate(field):\n if item is node:\n def setter(new_node):\n field[i] = new_node\n\n return setter\n\n\nlock = RLock()\n\n\n@cache\ndef statement_containing_node(node):\n while not isinstance(node, ast.stmt):\n node = node.parent\n return node\n\n\ndef assert_linenos(tree):\n for node in ast.walk(tree):\n if (\n hasattr(node, \'parent\') and\n hasattr(node, \'lineno\') and\n isinstance(statement_containing_node(node), ast.Assert)\n ):\n yield node.lineno\n\n\ndef _extract_ipython_statement(stmts, tree):\n # IPython separates each statement in a cell to be executed separately\n # So NodeFinder should only compile one statement at a time or it\n # will find a code mismatch.\n stmt = list(stmts)[0]\n while not isinstance(stmt.parent, ast.Module):\n stmt = stmt.parent\n # use `ast.parse` instead of `ast.Module` for better portability\n # python3.8 changes the signature of `ast.Module`\n # Inspired by https://github.com/pallets/werkzeug/pull/1552/files\n tree = ast.parse("")\n tree.body = [stmt]\n ast.copy_location(tree, stmt)\n return tree\n') + __stickytape_write_module('executing/version.py', b"__version__ = '0.5.4'") + __stickytape_write_module('pygments/__init__.py', b'# -*- coding: utf-8 -*-\n"""\n Pygments\n ~~~~~~~~\n\n Pygments is a syntax highlighting package written in Python.\n\n It is a generic syntax highlighter for general use in all kinds of software\n such as forum systems, wikis or other applications that need to prettify\n source code. Highlights are:\n\n * a wide range of common languages and markup formats is supported\n * special attention is paid to details, increasing quality by a fair amount\n * support for new languages and formats are added easily\n * a number of output formats, presently HTML, LaTeX, RTF, SVG, all image\n formats that PIL supports, and ANSI sequences\n * it is usable as a command-line tool and as a library\n * ... and it highlights even Brainfuck!\n\n The `Pygments master branch`_ is installable with ``easy_install Pygments==dev``.\n\n .. _Pygments master branch:\n https://github.com/pygments/pygments/archive/master.zip#egg=Pygments-dev\n\n :copyright: Copyright 2006-2019 by the Pygments team, see AUTHORS.\n :license: BSD, see LICENSE for details.\n"""\nimport sys\n\nfrom pygments.util import StringIO, BytesIO\n\n__version__ = \'2.5.2\'\n__docformat__ = \'restructuredtext\'\n\n__all__ = [\'lex\', \'format\', \'highlight\']\n\n\ndef lex(code, lexer):\n """\n Lex ``code`` with ``lexer`` and return an iterable of tokens.\n """\n try:\n return lexer.get_tokens(code)\n except TypeError as err:\n if (isinstance(err.args[0], str) and\n (\'unbound method get_tokens\' in err.args[0] or\n \'missing 1 required positional argument\' in err.args[0])):\n raise TypeError(\'lex() argument must be a lexer instance, \'\n \'not a class\')\n raise\n\n\ndef format(tokens, formatter, outfile=None): # pylint: disable=redefined-builtin\n """\n Format a tokenlist ``tokens`` with the formatter ``formatter``.\n\n If ``outfile`` is given and a valid file object (an object\n with a ``write`` method), the result will be written to it, otherwise\n it is returned as a string.\n """\n try:\n if not outfile:\n realoutfile = getattr(formatter, \'encoding\', None) and BytesIO() or StringIO()\n formatter.format(tokens, realoutfile)\n return realoutfile.getvalue()\n else:\n formatter.format(tokens, outfile)\n except TypeError as err:\n if (isinstance(err.args[0], str) and\n (\'unbound method format\' in err.args[0] or\n \'missing 1 required positional argument\' in err.args[0])):\n raise TypeError(\'format() argument must be a formatter instance, \'\n \'not a class\')\n raise\n\n\ndef highlight(code, lexer, formatter, outfile=None):\n """\n Lex ``code`` with ``lexer`` and format it with the formatter ``formatter``.\n\n If ``outfile`` is given and a valid file object (an object\n with a ``write`` method), the result will be written to it, otherwise\n it is returned as a string.\n """\n return format(lex(code, lexer), formatter, outfile)\n\n\nif __name__ == \'__main__\': # pragma: no cover\n from pygments.cmdline import main\n sys.exit(main(sys.argv))\n') + __stickytape_write_module('pygments/util.py', b'# -*- coding: utf-8 -*-\n"""\n pygments.util\n ~~~~~~~~~~~~~\n\n Utility functions.\n\n :copyright: Copyright 2006-2019 by the Pygments team, see AUTHORS.\n :license: BSD, see LICENSE for details.\n"""\n\nimport re\nimport sys\n\n\nsplit_path_re = re.compile(r\'[/\\\\ ]\')\ndoctype_lookup_re = re.compile(r\'\'\'\n (<\\?.*?\\?>)?\\s*\n ]*>\n\'\'\', re.DOTALL | re.MULTILINE | re.VERBOSE)\ntag_re = re.compile(r\'<(.+?)(\\s.*?)?>.*?\',\n re.UNICODE | re.IGNORECASE | re.DOTALL | re.MULTILINE)\nxml_decl_re = re.compile(r\'\\s*<\\?xml[^>]*\\?>\', re.I)\n\n\nclass ClassNotFound(ValueError):\n """Raised if one of the lookup functions didn\'t find a matching class."""\n\n\nclass OptionError(Exception):\n pass\n\n\ndef get_choice_opt(options, optname, allowed, default=None, normcase=False):\n string = options.get(optname, default)\n if normcase:\n string = string.lower()\n if string not in allowed:\n raise OptionError(\'Value for option %s must be one of %s\' %\n (optname, \', \'.join(map(str, allowed))))\n return string\n\n\ndef get_bool_opt(options, optname, default=None):\n string = options.get(optname, default)\n if isinstance(string, bool):\n return string\n elif isinstance(string, int):\n return bool(string)\n elif not isinstance(string, string_types):\n raise OptionError(\'Invalid type %r for option %s; use \'\n \'1/0, yes/no, true/false, on/off\' % (\n string, optname))\n elif string.lower() in (\'1\', \'yes\', \'true\', \'on\'):\n return True\n elif string.lower() in (\'0\', \'no\', \'false\', \'off\'):\n return False\n else:\n raise OptionError(\'Invalid value %r for option %s; use \'\n \'1/0, yes/no, true/false, on/off\' % (\n string, optname))\n\n\ndef get_int_opt(options, optname, default=None):\n string = options.get(optname, default)\n try:\n return int(string)\n except TypeError:\n raise OptionError(\'Invalid type %r for option %s; you \'\n \'must give an integer value\' % (\n string, optname))\n except ValueError:\n raise OptionError(\'Invalid value %r for option %s; you \'\n \'must give an integer value\' % (\n string, optname))\n\n\ndef get_list_opt(options, optname, default=None):\n val = options.get(optname, default)\n if isinstance(val, string_types):\n return val.split()\n elif isinstance(val, (list, tuple)):\n return list(val)\n else:\n raise OptionError(\'Invalid type %r for option %s; you \'\n \'must give a list value\' % (\n val, optname))\n\n\ndef docstring_headline(obj):\n if not obj.__doc__:\n return \'\'\n res = []\n for line in obj.__doc__.strip().splitlines():\n if line.strip():\n res.append(" " + line.strip())\n else:\n break\n return \'\'.join(res).lstrip()\n\n\ndef make_analysator(f):\n """Return a static text analyser function that returns float values."""\n def text_analyse(text):\n try:\n rv = f(text)\n except Exception:\n return 0.0\n if not rv:\n return 0.0\n try:\n return min(1.0, max(0.0, float(rv)))\n except (ValueError, TypeError):\n return 0.0\n text_analyse.__doc__ = f.__doc__\n return staticmethod(text_analyse)\n\n\ndef shebang_matches(text, regex):\n r"""Check if the given regular expression matches the last part of the\n shebang if one exists.\n\n >>> from pygments.util import shebang_matches\n >>> shebang_matches(\'#!/usr/bin/env python\', r\'python(2\\.\\d)?\')\n True\n >>> shebang_matches(\'#!/usr/bin/python2.4\', r\'python(2\\.\\d)?\')\n True\n >>> shebang_matches(\'#!/usr/bin/python-ruby\', r\'python(2\\.\\d)?\')\n False\n >>> shebang_matches(\'#!/usr/bin/python/ruby\', r\'python(2\\.\\d)?\')\n False\n >>> shebang_matches(\'#!/usr/bin/startsomethingwith python\',\n ... r\'python(2\\.\\d)?\')\n True\n\n It also checks for common windows executable file extensions::\n\n >>> shebang_matches(\'#!C:\\\\Python2.4\\\\Python.exe\', r\'python(2\\.\\d)?\')\n True\n\n Parameters (``\'-f\'`` or ``\'--foo\'`` are ignored so ``\'perl\'`` does\n the same as ``\'perl -e\'``)\n\n Note that this method automatically searches the whole string (eg:\n the regular expression is wrapped in ``\'^$\'``)\n """\n index = text.find(\'\\n\')\n if index >= 0:\n first_line = text[:index].lower()\n else:\n first_line = text.lower()\n if first_line.startswith(\'#!\'):\n try:\n found = [x for x in split_path_re.split(first_line[2:].strip())\n if x and not x.startswith(\'-\')][-1]\n except IndexError:\n return False\n regex = re.compile(r\'^%s(\\.(exe|cmd|bat|bin))?$\' % regex, re.IGNORECASE)\n if regex.search(found) is not None:\n return True\n return False\n\n\ndef doctype_matches(text, regex):\n """Check if the doctype matches a regular expression (if present).\n\n Note that this method only checks the first part of a DOCTYPE.\n eg: \'html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"\'\n """\n m = doctype_lookup_re.match(text)\n if m is None:\n return False\n doctype = m.group(2)\n return re.compile(regex, re.I).match(doctype.strip()) is not None\n\n\ndef html_doctype_matches(text):\n """Check if the file looks like it has a html doctype."""\n return doctype_matches(text, r\'html\')\n\n\n_looks_like_xml_cache = {}\n\n\ndef looks_like_xml(text):\n """Check if a doctype exists or if we have some tags."""\n if xml_decl_re.match(text):\n return True\n key = hash(text)\n try:\n return _looks_like_xml_cache[key]\n except KeyError:\n m = doctype_lookup_re.match(text)\n if m is not None:\n return True\n rv = tag_re.search(text[:1000]) is not None\n _looks_like_xml_cache[key] = rv\n return rv\n\n\n# Python narrow build compatibility\n\ndef _surrogatepair(c):\n # Given a unicode character code\n # with length greater than 16 bits,\n # return the two 16 bit surrogate pair.\n # From example D28 of:\n # http://www.unicode.org/book/ch03.pdf\n return (0xd7c0 + (c >> 10), (0xdc00 + (c & 0x3ff)))\n\n\ndef unirange(a, b):\n """Returns a regular expression string to match the given non-BMP range."""\n if b < a:\n raise ValueError("Bad character range")\n if a < 0x10000 or b < 0x10000:\n raise ValueError("unirange is only defined for non-BMP ranges")\n\n if sys.maxunicode > 0xffff:\n # wide build\n return u\'[%s-%s]\' % (unichr(a), unichr(b))\n else:\n # narrow build stores surrogates, and the \'re\' module handles them\n # (incorrectly) as characters. Since there is still ordering among\n # these characters, expand the range to one that it understands. Some\n # background in http://bugs.python.org/issue3665 and\n # http://bugs.python.org/issue12749\n #\n # Additionally, the lower constants are using unichr rather than\n # literals because jython [which uses the wide path] can\'t load this\n # file if they are literals.\n ah, al = _surrogatepair(a)\n bh, bl = _surrogatepair(b)\n if ah == bh:\n return u\'(?:%s[%s-%s])\' % (unichr(ah), unichr(al), unichr(bl))\n else:\n buf = []\n buf.append(u\'%s[%s-%s]\' %\n (unichr(ah), unichr(al),\n ah == bh and unichr(bl) or unichr(0xdfff)))\n if ah - bh > 1:\n buf.append(u\'[%s-%s][%s-%s]\' %\n unichr(ah+1), unichr(bh-1), unichr(0xdc00), unichr(0xdfff))\n if ah != bh:\n buf.append(u\'%s[%s-%s]\' %\n (unichr(bh), unichr(0xdc00), unichr(bl)))\n\n return u\'(?:\' + u\'|\'.join(buf) + u\')\'\n\n\ndef format_lines(var_name, seq, raw=False, indent_level=0):\n """Formats a sequence of strings for output."""\n lines = []\n base_indent = \' \' * indent_level * 4\n inner_indent = \' \' * (indent_level + 1) * 4\n lines.append(base_indent + var_name + \' = (\')\n if raw:\n # These should be preformatted reprs of, say, tuples.\n for i in seq:\n lines.append(inner_indent + i + \',\')\n else:\n for i in seq:\n # Force use of single quotes\n r = repr(i + \'"\')\n lines.append(inner_indent + r[:-2] + r[-1] + \',\')\n lines.append(base_indent + \')\')\n return \'\\n\'.join(lines)\n\n\ndef duplicates_removed(it, already_seen=()):\n """\n Returns a list with duplicates removed from the iterable `it`.\n\n Order is preserved.\n """\n lst = []\n seen = set()\n for i in it:\n if i in seen or i in already_seen:\n continue\n lst.append(i)\n seen.add(i)\n return lst\n\n\nclass Future(object):\n """Generic class to defer some work.\n\n Handled specially in RegexLexerMeta, to support regex string construction at\n first use.\n """\n def get(self):\n raise NotImplementedError\n\n\ndef guess_decode(text):\n """Decode *text* with guessed encoding.\n\n First try UTF-8; this should fail for non-UTF-8 encodings.\n Then try the preferred locale encoding.\n Fall back to latin-1, which always works.\n """\n try:\n text = text.decode(\'utf-8\')\n return text, \'utf-8\'\n except UnicodeDecodeError:\n try:\n import locale\n prefencoding = locale.getpreferredencoding()\n text = text.decode()\n return text, prefencoding\n except (UnicodeDecodeError, LookupError):\n text = text.decode(\'latin1\')\n return text, \'latin1\'\n\n\ndef guess_decode_from_terminal(text, term):\n """Decode *text* coming from terminal *term*.\n\n First try the terminal encoding, if given.\n Then try UTF-8. Then try the preferred locale encoding.\n Fall back to latin-1, which always works.\n """\n if getattr(term, \'encoding\', None):\n try:\n text = text.decode(term.encoding)\n except UnicodeDecodeError:\n pass\n else:\n return text, term.encoding\n return guess_decode(text)\n\n\ndef terminal_encoding(term):\n """Return our best guess of encoding for the given *term*."""\n if getattr(term, \'encoding\', None):\n return term.encoding\n import locale\n return locale.getpreferredencoding()\n\n\n# Python 2/3 compatibility\n\nif sys.version_info < (3, 0):\n unichr = unichr\n xrange = xrange\n string_types = (str, unicode)\n text_type = unicode\n u_prefix = \'u\'\n iteritems = dict.iteritems\n itervalues = dict.itervalues\n import StringIO\n import cStringIO\n # unfortunately, io.StringIO in Python 2 doesn\'t accept str at all\n StringIO = StringIO.StringIO\n BytesIO = cStringIO.StringIO\nelse:\n unichr = chr\n xrange = range\n string_types = (str,)\n text_type = str\n u_prefix = \'\'\n iteritems = dict.items\n itervalues = dict.values\n from io import StringIO, BytesIO, TextIOWrapper\n\n class UnclosingTextIOWrapper(TextIOWrapper):\n # Don\'t close underlying buffer on destruction.\n def close(self):\n self.flush()\n\n\ndef add_metaclass(metaclass):\n """Class decorator for creating a class with a metaclass."""\n def wrapper(cls):\n orig_vars = cls.__dict__.copy()\n orig_vars.pop(\'__dict__\', None)\n orig_vars.pop(\'__weakref__\', None)\n for slots_var in orig_vars.get(\'__slots__\', ()):\n orig_vars.pop(slots_var)\n return metaclass(cls.__name__, cls.__bases__, orig_vars)\n return wrapper\n') + __stickytape_write_module('pygments/cmdline.py', b'# -*- coding: utf-8 -*-\n"""\n pygments.cmdline\n ~~~~~~~~~~~~~~~~\n\n Command line interface.\n\n :copyright: Copyright 2006-2019 by the Pygments team, see AUTHORS.\n :license: BSD, see LICENSE for details.\n"""\n\nfrom __future__ import print_function\n\nimport os\nimport sys\nimport getopt\nfrom textwrap import dedent\n\nfrom pygments import __version__, highlight\nfrom pygments.util import ClassNotFound, OptionError, docstring_headline, \\\n guess_decode, guess_decode_from_terminal, terminal_encoding\nfrom pygments.lexers import get_all_lexers, get_lexer_by_name, guess_lexer, \\\n load_lexer_from_file, get_lexer_for_filename, find_lexer_class_for_filename\nfrom pygments.lexers.special import TextLexer\nfrom pygments.formatters.latex import LatexEmbeddedLexer, LatexFormatter\nfrom pygments.formatters import get_all_formatters, get_formatter_by_name, \\\n load_formatter_from_file, get_formatter_for_filename, find_formatter_class\nfrom pygments.formatters.terminal import TerminalFormatter\nfrom pygments.formatters.terminal256 import Terminal256Formatter\nfrom pygments.filters import get_all_filters, find_filter_class\nfrom pygments.styles import get_all_styles, get_style_by_name\n\n\nUSAGE = """\\\nUsage: %s [-l | -g] [-F [:]] [-f ]\n [-O ] [-P ] [-s] [-v] [-x] [-o ] []\n\n %s -S