Code
stringlengths
103
85.9k
Summary
listlengths
0
94
Please provide a description of the function:def get_dist(self): # type: () -> Distribution if self.metadata_directory: base_dir, distinfo = os.path.split(self.metadata_directory) metadata = pkg_resources.PathMetadata( base_dir, self.metadata_directory ...
[ "Return a pkg_resources.Distribution for this requirement" ]
Please provide a description of the function:def uninstall(self, auto_confirm=False, verbose=False, use_user_site=False): # type: (bool, bool, bool) -> Optional[UninstallPathSet] if not self.check_if_exists(use_user_site): logger.warning("Skipping %s as it is not i...
[ "\n Uninstall the distribution currently satisfying this requirement.\n\n Prompts before removing or modifying files unless\n ``auto_confirm`` is True.\n\n Refuses to delete or modify files outside of ``sys.prefix`` -\n thus uninstallation within a virtual environment can only\n ...
Please provide a description of the function:def populate_requirement_set(requirement_set, # type: RequirementSet args, # type: List[str] options, # type: Values finder, # type: PackageFind...
[ "\n Marshal cmd line args into a requirement set.\n " ]
Please provide a description of the function:def _build_package_finder( self, options, # type: Values session, # type: PipSession platform=None, # type: Optional[str] python_versions=None, # type: Optional[List[str]] abi=None, ...
[ "\n Create a package finder appropriate to this requirement command.\n " ]
Please provide a description of the function:def intranges_from_list(list_): sorted_list = sorted(list_) ranges = [] last_write = -1 for i in range(len(sorted_list)): if i+1 < len(sorted_list): if sorted_list[i] == sorted_list[i+1]-1: continue current_ra...
[ "Represent a list of integers as a sequence of ranges:\n ((start_0, end_0), (start_1, end_1), ...), such that the original\n integers are exactly those x such that start_i <= x < end_i for some i.\n\n Ranges are encoded as single integers (start << 32 | end), not as tuples.\n " ]
Please provide a description of the function:def intranges_contain(int_, ranges): tuple_ = _encode_range(int_, 0) pos = bisect.bisect_left(ranges, tuple_) # we could be immediately ahead of a tuple (start, end) # with start < int_ <= end if pos > 0: left, right = _decode_range(ranges[po...
[ "Determine if `int_` falls into one of the ranges in `ranges`." ]
Please provide a description of the function:def _hash_of_file(path, algorithm): with open(path, 'rb') as archive: hash = hashlib.new(algorithm) for chunk in read_chunks(archive): hash.update(chunk) return hash.hexdigest()
[ "Return the hash digest of a file." ]
Please provide a description of the function:def linux_distribution(self, full_distribution_name=True): return ( self.name() if full_distribution_name else self.id(), self.version(), self.codename() )
[ "\n Return information about the OS distribution that is compatible\n with Python's :func:`platform.linux_distribution`, supporting a subset\n of its parameters.\n\n For details, see :func:`distro.linux_distribution`.\n " ]
Please provide a description of the function:def id(self): def normalize(distro_id, table): distro_id = distro_id.lower().replace(' ', '_') return table.get(distro_id, distro_id) distro_id = self.os_release_attr('id') if distro_id: return normalize(d...
[ "Return the distro ID of the OS distribution, as a string.\n\n For details, see :func:`distro.id`.\n " ]
Please provide a description of the function:def name(self, pretty=False): name = self.os_release_attr('name') \ or self.lsb_release_attr('distributor_id') \ or self.distro_release_attr('name') \ or self.uname_attr('name') if pretty: name = self.o...
[ "\n Return the name of the OS distribution, as a string.\n\n For details, see :func:`distro.name`.\n " ]
Please provide a description of the function:def version(self, pretty=False, best=False): versions = [ self.os_release_attr('version_id'), self.lsb_release_attr('release'), self.distro_release_attr('version_id'), self._parse_distro_release_content( ...
[ "\n Return the version of the OS distribution, as a string.\n\n For details, see :func:`distro.version`.\n " ]
Please provide a description of the function:def version_parts(self, best=False): version_str = self.version(best=best) if version_str: version_regex = re.compile(r'(\d+)\.?(\d+)?\.?(\d+)?') matches = version_regex.match(version_str) if matches: ...
[ "\n Return the version of the OS distribution, as a tuple of version\n numbers.\n\n For details, see :func:`distro.version_parts`.\n " ]
Please provide a description of the function:def info(self, pretty=False, best=False): return dict( id=self.id(), version=self.version(pretty, best), version_parts=dict( major=self.major_version(best), minor=self.minor_version(best), ...
[ "\n Return certain machine-readable information about the OS\n distribution.\n\n For details, see :func:`distro.info`.\n " ]
Please provide a description of the function:def _os_release_info(self): if os.path.isfile(self.os_release_file): with open(self.os_release_file) as release_file: return self._parse_os_release_content(release_file) return {}
[ "\n Get the information items from the specified os-release file.\n\n Returns:\n A dictionary containing all information items.\n " ]
Please provide a description of the function:def _lsb_release_info(self): if not self.include_lsb: return {} with open(os.devnull, 'w') as devnull: try: cmd = ('lsb_release', '-a') stdout = subprocess.check_output(cmd, stderr=devnull) ...
[ "\n Get the information items from the lsb_release command output.\n\n Returns:\n A dictionary containing all information items.\n " ]
Please provide a description of the function:def _parse_lsb_release_content(lines): props = {} for line in lines: kv = line.strip('\n').split(':', 1) if len(kv) != 2: # Ignore lines without colon. continue k, v = kv ...
[ "\n Parse the output of the lsb_release command.\n\n Parameters:\n\n * lines: Iterable through the lines of the lsb_release output.\n Each line must be a unicode string or a UTF-8 encoded byte\n string.\n\n Returns:\n A dictionary containing all...
Please provide a description of the function:def _distro_release_info(self): if self.distro_release_file: # If it was specified, we use it and parse what we can, even if # its file name or content does not match the expected pattern. distro_info = self._parse_distro_...
[ "\n Get the information items from the specified distro release file.\n\n Returns:\n A dictionary containing all information items.\n " ]
Please provide a description of the function:def _parse_distro_release_file(self, filepath): try: with open(filepath) as fp: # Only parse the first line. For instance, on SLES there # are multiple lines. We don't want them... return self._pars...
[ "\n Parse a distro release file.\n\n Parameters:\n\n * filepath: Path name of the distro release file.\n\n Returns:\n A dictionary containing all information items.\n " ]
Please provide a description of the function:def _parse_distro_release_content(line): if isinstance(line, bytes): line = line.decode('utf-8') matches = _DISTRO_RELEASE_CONTENT_REVERSED_PATTERN.match( line.strip()[::-1]) distro_info = {} if matches: ...
[ "\n Parse a line from a distro release file.\n\n Parameters:\n * line: Line from the distro release file. Must be a unicode string\n or a UTF-8 encoded byte string.\n\n Returns:\n A dictionary containing all information items.\n " ]
Please provide a description of the function:def dependency_tree(installed_keys, root_key): dependencies = set() queue = collections.deque() if root_key in installed_keys: dep = installed_keys[root_key] queue.append(dep) while queue: v = queue.popleft() key = key_f...
[ "\n Calculate the dependency tree for the package `root_key` and return\n a collection of all its dependencies. Uses a DFS traversal algorithm.\n\n `installed_keys` should be a {key: requirement} mapping, e.g.\n {'django': from_line('django==1.8')}\n `root_key` should be the key to return the de...
Please provide a description of the function:def get_dists_to_ignore(installed): installed_keys = {key_from_req(r): r for r in installed} return list(flat_map(lambda req: dependency_tree(installed_keys, req), PACKAGES_TO_IGNORE))
[ "\n Returns a collection of package names to ignore when performing pip-sync,\n based on the currently installed environment. For example, when pip-tools\n is installed in the local environment, it should be ignored, including all\n of its dependencies (e.g. click). When pip-tools is not installed\n ...
Please provide a description of the function:def diff(compiled_requirements, installed_dists): requirements_lut = {r.link or key_from_req(r.req): r for r in compiled_requirements} satisfied = set() # holds keys to_install = set() # holds InstallRequirement objects to_uninstall = set() # holds k...
[ "\n Calculate which packages should be installed or uninstalled, given a set\n of compiled requirements and a list of currently installed modules.\n " ]
Please provide a description of the function:def sync(to_install, to_uninstall, verbose=False, dry_run=False, install_flags=None): if not to_uninstall and not to_install: click.echo("Everything up-to-date") pip_flags = [] if not verbose: pip_flags += ['-q'] if to_uninstall: ...
[ "\n Install and uninstalls the given sets of modules.\n " ]
Please provide a description of the function:def get_spontaneous_environment(*args): try: env = _spontaneous_environments.get(args) except TypeError: return Environment(*args) if env is not None: return env _spontaneous_environments[args] = env = Environment(*args) env.s...
[ "Return a new spontaneous environment. A spontaneous environment is an\n unnamed and unaccessible (in theory) environment that is used for\n templates generated from a string and not from the file system.\n " ]
Please provide a description of the function:def _environment_sanity_check(environment): assert issubclass(environment.undefined, Undefined), 'undefined must ' \ 'be a subclass of undefined because filters depend on it.' assert environment.block_start_string != \ environment.variable_start_...
[ "Perform a sanity check on the environment." ]
Please provide a description of the function:def overlay(self, block_start_string=missing, block_end_string=missing, variable_start_string=missing, variable_end_string=missing, comment_start_string=missing, comment_end_string=missing, line_statement_prefix=missing, line_c...
[ "Create a new overlay environment that shares all the data with the\n current environment except for cache and the overridden attributes.\n Extensions cannot be removed for an overlayed environment. An overlayed\n environment automatically gets all the extensions of the environment it\n ...
Please provide a description of the function:def iter_extensions(self): return iter(sorted(self.extensions.values(), key=lambda x: x.priority))
[ "Iterates over the extensions by priority." ]
Please provide a description of the function:def getattr(self, obj, attribute): try: return getattr(obj, attribute) except AttributeError: pass try: return obj[attribute] except (TypeError, LookupError, AttributeError): return self...
[ "Get an item or attribute of an object but prefer the attribute.\n Unlike :meth:`getitem` the attribute *must* be a bytestring.\n " ]
Please provide a description of the function:def call_filter(self, name, value, args=None, kwargs=None, context=None, eval_ctx=None): func = self.filters.get(name) if func is None: fail_for_missing_callable('no filter named %r', name) args = [value] + lis...
[ "Invokes a filter on a value the same way the compiler does it.\n\n Note that on Python 3 this might return a coroutine in case the\n filter is running from an environment in async mode and the filter\n supports async execution. It's your responsibility to await this\n if needed.\n\n ...
Please provide a description of the function:def parse(self, source, name=None, filename=None): try: return self._parse(source, name, filename) except TemplateSyntaxError: exc_info = sys.exc_info() self.handle_exception(exc_info, source_hint=source)
[ "Parse the sourcecode and return the abstract syntax tree. This\n tree of nodes is used by the compiler to convert the template into\n executable source- or bytecode. This is useful for debugging or to\n extract information from templates.\n\n If you are :ref:`developing Jinja2 extensi...
Please provide a description of the function:def _parse(self, source, name, filename): return Parser(self, source, name, encode_filename(filename)).parse()
[ "Internal parsing function used by `parse` and `compile`." ]
Please provide a description of the function:def lex(self, source, name=None, filename=None): source = text_type(source) try: return self.lexer.tokeniter(source, name, filename) except TemplateSyntaxError: exc_info = sys.exc_info() self.handle_exception(e...
[ "Lex the given sourcecode and return a generator that yields\n tokens as tuples in the form ``(lineno, token_type, value)``.\n This can be useful for :ref:`extension development <writing-extensions>`\n and debugging templates.\n\n This does not perform preprocessing. If you want the pre...
Please provide a description of the function:def _tokenize(self, source, name, filename=None, state=None): source = self.preprocess(source, name, filename) stream = self.lexer.tokenize(source, name, filename, state) for ext in self.iter_extensions(): stream = ext.filter_stre...
[ "Called by the parser to do the preprocessing and filtering\n for all the extensions. Returns a :class:`~jinja2.lexer.TokenStream`.\n " ]
Please provide a description of the function:def compile(self, source, name=None, filename=None, raw=False, defer_init=False): source_hint = None try: if isinstance(source, string_types): source_hint = source source = self._parse(sourc...
[ "Compile a node or template source code. The `name` parameter is\n the load name of the template after it was joined using\n :meth:`join_path` if necessary, not the filename on the file system.\n the `filename` parameter is the estimated filename of the template on\n the file system. I...
Please provide a description of the function:def compile_expression(self, source, undefined_to_none=True): parser = Parser(self, source, state='variable') exc_info = None try: expr = parser.parse_expression() if not parser.stream.eos: raise Templa...
[ "A handy helper method that returns a callable that accepts keyword\n arguments that appear as variables in the expression. If called it\n returns the result of the expression.\n\n This is useful if applications want to use the same rules as Jinja\n in template \"configuration files\" o...
Please provide a description of the function:def get_template(self, name, parent=None, globals=None): if isinstance(name, Template): return name if parent is not None: name = self.join_path(name, parent) return self._load_template(name, self.make_globals(globals)...
[ "Load a template from the loader. If a loader is configured this\n method asks the loader for the template and returns a :class:`Template`.\n If the `parent` parameter is not `None`, :meth:`join_path` is called\n to get the real template name before loading.\n\n The `globals` parameter ...
Please provide a description of the function:def select_template(self, names, parent=None, globals=None): if not names: raise TemplatesNotFound(message=u'Tried to select from an empty list ' u'of templates.') globals = self.make_globals(gl...
[ "Works like :meth:`get_template` but tries a number of templates\n before it fails. If it cannot find any of the templates, it will\n raise a :exc:`TemplatesNotFound` exception.\n\n .. versionadded:: 2.3\n\n .. versionchanged:: 2.4\n If `names` contains a :class:`Template` obj...
Please provide a description of the function:def get_or_select_template(self, template_name_or_list, parent=None, globals=None): if isinstance(template_name_or_list, string_types): return self.get_template(template_name_or_list, parent, globals) elif i...
[ "Does a typecheck and dispatches to :meth:`select_template`\n if an iterable of template names is given, otherwise to\n :meth:`get_template`.\n\n .. versionadded:: 2.3\n " ]
Please provide a description of the function:def from_string(self, source, globals=None, template_class=None): globals = self.make_globals(globals) cls = template_class or self.template_class return cls.from_code(self, self.compile(source), globals, None)
[ "Load a template from a string. This parses the source given and\n returns a :class:`Template` object.\n " ]
Please provide a description of the function:def make_globals(self, d): if not d: return self.globals return dict(self.globals, **d)
[ "Return a dict for the globals." ]
Please provide a description of the function:def from_module_dict(cls, environment, module_dict, globals): return cls._from_namespace(environment, module_dict, globals)
[ "Creates a template object from a module. This is used by the\n module loader to create a template object.\n\n .. versionadded:: 2.4\n " ]
Please provide a description of the function:def new_context(self, vars=None, shared=False, locals=None): return new_context(self.environment, self.name, self.blocks, vars, shared, self.globals, locals)
[ "Create a new :class:`Context` for this template. The vars\n provided will be passed to the template. Per default the globals\n are added to the context. If shared is set to `True` the data\n is passed as it to the context without adding the globals.\n\n `locals` can be a dict of loca...
Please provide a description of the function:def make_module(self, vars=None, shared=False, locals=None): return TemplateModule(self, self.new_context(vars, shared, locals))
[ "This method works like the :attr:`module` attribute when called\n without arguments but it will evaluate the template on every call\n rather than caching it. It's also possible to provide\n a dict which is then used as context. The arguments are the same\n as for the :meth:`new_contex...
Please provide a description of the function:def get_corresponding_lineno(self, lineno): for template_line, code_line in reversed(self.debug_info): if code_line <= lineno: return template_line return 1
[ "Return the source line number of a line number in the\n generated bytecode as they are not in sync.\n " ]
Please provide a description of the function:def debug_info(self): return [tuple(imap(int, x.split('='))) for x in self._debug_info.split('&')]
[ "The debug info mapping." ]
Please provide a description of the function:def _get_parsed_url(url): # type: (S) -> Url try: parsed = urllib3_parse(url) except ValueError: scheme, _, url = url.partition("://") auth, _, url = url.rpartition("@") url = "{scheme}://{url}".format(scheme=scheme, url=url)...
[ "\n This is a stand-in function for `urllib3.util.parse_url`\n\n The orignal function doesn't handle special characters very well, this simply splits\n out the authentication section, creates the parsed url, then puts the authentication\n section back in, bypassing validation.\n\n :return: The new, p...
Please provide a description of the function:def remove_password_from_url(url): # type: (S) -> S parsed = _get_parsed_url(url) if parsed.auth: auth, _, _ = parsed.auth.partition(":") return parsed._replace(auth="{auth}:----".format(auth=auth)).url return parsed.url
[ "\n Given a url, remove the password and insert 4 dashes\n\n :param url: The url to replace the authentication in\n :type url: S\n :return: The new URL without authentication\n :rtype: S\n " ]
Please provide a description of the function:def _verify_python3_env(): if PY2: return try: import locale fs_enc = codecs.lookup(locale.getpreferredencoding()).name except Exception: fs_enc = 'ascii' if fs_enc != 'ascii': return extra = '' if os.name...
[ "Ensures that the environment is good for unicode on Python 3." ]
Please provide a description of the function:def rmtree_errorhandler(func, path, exc_info): # if file type currently read only if os.stat(path).st_mode & stat.S_IREAD: # convert to read/write os.chmod(path, stat.S_IWRITE) # use the original function to repeat the operation f...
[ "On Windows, the files in .svn are read-only, so when rmtree() tries to\n remove them, an exception is thrown. We catch that here, remove the\n read-only attribute, and hopefully continue without problems." ]
Please provide a description of the function:def display_path(path): # type: (Union[str, Text]) -> str path = os.path.normcase(os.path.abspath(path)) if sys.version_info[0] == 2: path = path.decode(sys.getfilesystemencoding(), 'replace') path = path.encode(sys.getdefaultencoding(), 'rep...
[ "Gives the display value for a given path, making it relative to cwd\n if possible." ]
Please provide a description of the function:def is_installable_dir(path): # type: (str) -> bool if not os.path.isdir(path): return False setup_py = os.path.join(path, 'setup.py') if os.path.isfile(setup_py): return True pyproject_toml = os.path.join(path, 'pyproject.toml') ...
[ "Is path is a directory containing setup.py or pyproject.toml?\n " ]
Please provide a description of the function:def is_svn_page(html): # type: (Union[str, Text]) -> Optional[Match[Union[str, Text]]] return (re.search(r'<title>[^<]*Revision \d+:', html) and re.search(r'Powered by (?:<a[^>]*?>)?Subversion', html, re.I))
[ "\n Returns true if the page appears to be the index page of an svn repository\n " ]
Please provide a description of the function:def read_chunks(file, size=io.DEFAULT_BUFFER_SIZE): while True: chunk = file.read(size) if not chunk: break yield chunk
[ "Yield pieces of data from a file-like object until EOF." ]
Please provide a description of the function:def normalize_path(path, resolve_symlinks=True): # type: (str, bool) -> str path = expanduser(path) if resolve_symlinks: path = os.path.realpath(path) else: path = os.path.abspath(path) return os.path.normcase(path)
[ "\n Convert a path to its canonical, case-normalized, absolute version.\n\n " ]
Please provide a description of the function:def splitext(path): # type: (str) -> Tuple[str, str] base, ext = posixpath.splitext(path) if base.lower().endswith('.tar'): ext = base[-4:] + ext base = base[:-4] return base, ext
[ "Like os.path.splitext, but take off .tar too" ]
Please provide a description of the function:def renames(old, new): # type: (str, str) -> None # Implementation borrowed from os.renames(). head, tail = os.path.split(new) if head and tail and not os.path.exists(head): os.makedirs(head) shutil.move(old, new) head, tail = os.path.s...
[ "Like os.renames(), but handles renaming across devices." ]
Please provide a description of the function:def is_local(path): # type: (str) -> bool if not running_under_virtualenv(): return True return normalize_path(path).startswith(normalize_path(sys.prefix))
[ "\n Return True if path is within sys.prefix, if we're running in a virtualenv.\n\n If we're not in a virtualenv, all paths are considered \"local.\"\n\n " ]
Please provide a description of the function:def dist_is_editable(dist): # type: (Distribution) -> bool for path_item in sys.path: egg_link = os.path.join(path_item, dist.project_name + '.egg-link') if os.path.isfile(egg_link): return True return False
[ "\n Return True if given Distribution is an editable install.\n " ]
Please provide a description of the function:def get_installed_distributions(local_only=True, skip=stdlib_pkgs, include_editables=True, editables_only=False, user_only=False): # type: (boo...
[ "\n Return a list of installed Distribution objects.\n\n If ``local_only`` is True (default), only return installations\n local to the current virtualenv, if in a virtualenv.\n\n ``skip`` argument is an iterable of lower-case project names to\n ignore; defaults to stdlib_pkgs\n\n If ``include_edit...
Please provide a description of the function:def egg_link_path(dist): # type: (Distribution) -> Optional[str] sites = [] if running_under_virtualenv(): if virtualenv_no_global(): sites.append(site_packages) else: sites.append(site_packages) if user_si...
[ "\n Return the path for the .egg-link file if it exists, otherwise, None.\n\n There's 3 scenarios:\n 1) not in a virtualenv\n try to find in site.USER_SITE, then site_packages\n 2) in a no-global virtualenv\n try to find in site_packages\n 3) in a yes-global virtualenv\n try to find...
Please provide a description of the function:def unzip_file(filename, location, flatten=True): # type: (str, str, bool) -> None ensure_dir(location) zipfp = open(filename, 'rb') try: zip = zipfile.ZipFile(zipfp, allowZip64=True) leading = has_leading_dir(zip.namelist()) and flatten ...
[ "\n Unzip the file (with path `filename`) to the destination `location`. All\n files are written based on system defaults and umask (i.e. permissions are\n not preserved), except that regular file members with any execute\n permissions (user, group, or world) have \"chmod +x\" applied after being\n ...
Please provide a description of the function:def call_subprocess( cmd, # type: List[str] show_stdout=True, # type: bool cwd=None, # type: Optional[str] on_returncode='raise', # type: str extra_ok_returncodes=None, # type: Optional[Iterable[int]] command_desc=None, # type: Optional[str] ...
[ "\n Args:\n extra_ok_returncodes: an iterable of integer return codes that are\n acceptable, in addition to 0. Defaults to None, which means [].\n unset_environ: an iterable of environment variable names to unset\n prior to calling subprocess.Popen().\n " ]
Please provide a description of the function:def read_text_file(filename): # type: (str) -> str with open(filename, 'rb') as fp: data = fp.read() encodings = ['utf-8', locale.getpreferredencoding(False), 'latin1'] for enc in encodings: try: # https://github.com/python/m...
[ "Return the contents of *filename*.\n\n Try to decode the file contents with utf-8, the preferred system encoding\n (e.g., cp1252 on some Windows machines), and latin1, in that order.\n Decoding a byte string with latin1 will never raise an error. In the worst\n case, the returned string will contain so...
Please provide a description of the function:def captured_output(stream_name): orig_stdout = getattr(sys, stream_name) setattr(sys, stream_name, StreamWrapper.from_stream(orig_stdout)) try: yield getattr(sys, stream_name) finally: setattr(sys, stream_name, orig_stdout)
[ "Return a context manager used by captured_stdout/stdin/stderr\n that temporarily replaces the sys stream *stream_name* with a StringIO.\n\n Taken from Lib/support/__init__.py in the CPython repo.\n " ]
Please provide a description of the function:def get_installed_version(dist_name, working_set=None): # Create a requirement that we'll look for inside of setuptools. req = pkg_resources.Requirement.parse(dist_name) if working_set is None: # We want to avoid having this cached, so we need to co...
[ "Get the installed version of dist_name avoiding pkg_resources cache" ]
Please provide a description of the function:def make_vcs_requirement_url(repo_url, rev, project_name, subdir=None): egg_project_name = pkg_resources.to_filename(project_name) req = '{}@{}#egg={}'.format(repo_url, rev, egg_project_name) if subdir: req += '&subdirectory={}'.format(subdir) r...
[ "\n Return the URL for a VCS requirement.\n\n Args:\n repo_url: the remote VCS url, with any needed VCS prefix (e.g. \"git+\").\n project_name: the (unescaped) project name.\n " ]
Please provide a description of the function:def split_auth_from_netloc(netloc): if '@' not in netloc: return netloc, (None, None) # Split from the right because that's how urllib.parse.urlsplit() # behaves if more than one @ is present (which can be checked using # the password attribute ...
[ "\n Parse out and remove the auth information from a netloc.\n\n Returns: (netloc, (username, password)).\n " ]
Please provide a description of the function:def redact_netloc(netloc): # type: (str) -> str netloc, (user, password) = split_auth_from_netloc(netloc) if user is None: return netloc password = '' if password is None else ':****' return '{user}{password}@{netloc}'.format(user=urllib_pars...
[ "\n Replace the password in a netloc with \"****\", if it exists.\n\n For example, \"user:pass@example.com\" returns \"user:****@example.com\".\n " ]
Please provide a description of the function:def protect_pip_from_modification_on_windows(modifying_pip): pip_names = [ "pip.exe", "pip{}.exe".format(sys.version_info[0]), "pip{}.{}.exe".format(*sys.version_info[:2]) ] # See https://github.com/pypa/pip/issues/1299 for more disc...
[ "Protection of pip.exe from modification on Windows\n\n On Windows, any operation modifying pip should be run as:\n python -m pip ...\n " ]
Please provide a description of the function:def check_requires_python(requires_python): # type: (Optional[str]) -> bool if requires_python is None: # The package provides no information return True requires_python_specifier = specifiers.SpecifierSet(requires_python) # We only use ...
[ "\n Check if the python version in use match the `requires_python` specifier.\n\n Returns `True` if the version of python in use matches the requirement.\n Returns `False` if the version of python in use does not matches the\n requirement.\n\n Raises an InvalidSpecifier if `requires_python` have an i...
Please provide a description of the function:def init(complete_options=False, match_incomplete=None): global _initialized if not _initialized: _patch() completion_configuration.complete_options = complete_options if match_incomplete is not None: completion_configuration....
[ "Initialize the enhanced click completion\n\n Parameters\n ----------\n complete_options : bool\n always complete the options, even when the user hasn't typed a first dash (Default value = False)\n match_incomplete : func\n a function with two parameters choice and incomplete. Must return ...
Please provide a description of the function:def transform_hits(hits): packages = OrderedDict() for hit in hits: name = hit['name'] summary = hit['summary'] version = hit['version'] if name not in packages.keys(): packages[name] = { 'name': name,...
[ "\n The list from pypi is really a list of versions. We want a list of\n packages with the list of versions stored inline. This converts the\n list from pypi into one we can use.\n " ]
Please provide a description of the function:def add_requirement( self, install_req, # type: InstallRequirement parent_req_name=None, # type: Optional[str] extras_requested=None # type: Optional[Iterable[str]] ): # type: (...) -> Tuple[List[InstallRequirement], Optional[In...
[ "Add install_req as a requirement to install.\n\n :param parent_req_name: The name of the requirement that needed this\n added. The name is used because when multiple unnamed requirements\n resolve to the same name, we could otherwise end up with dependency\n links that point...
Please provide a description of the function:def resolve(self, requirement_set): # type: (RequirementSet) -> None # make the wheelhouse if self.preparer.wheel_download_dir: ensure_dir(self.preparer.wheel_download_dir) # If any top-level requirement has a hash specif...
[ "Resolve what operations need to be done\n\n As a side-effect of this method, the packages (and their dependencies)\n are downloaded, unpacked and prepared for installation. This\n preparation is done by ``pip.operations.prepare``.\n\n Once PyPI has static dependency metadata available, ...
Please provide a description of the function:def _set_req_to_reinstall(self, req): # type: (InstallRequirement) -> None # Don't uninstall the conflict if doing a user install and the # conflict is not a user install. if not self.use_user_site or dist_in_usersite(req.satisfied_by...
[ "\n Set a requirement to be installed.\n " ]
Please provide a description of the function:def _check_skip_installed(self, req_to_install): # type: (InstallRequirement) -> Optional[str] if self.ignore_installed: return None req_to_install.check_if_exists(self.use_user_site) if not req_to_install.satisfied_by: ...
[ "Check if req_to_install should be skipped.\n\n This will check if the req is installed, and whether we should upgrade\n or reinstall it, taking into account all the relevant user options.\n\n After calling this req_to_install will only have satisfied_by set to\n None if the req_to_insta...
Please provide a description of the function:def _get_abstract_dist_for(self, req): # type: (InstallRequirement) -> DistAbstraction assert self.require_hashes is not None, ( "require_hashes should have been set in Resolver.resolve()" ) if req.editable: r...
[ "Takes a InstallRequirement and returns a single AbstractDist \\\n representing a prepared variant of the same.\n " ]
Please provide a description of the function:def _resolve_one( self, requirement_set, # type: RequirementSet req_to_install, # type: InstallRequirement ignore_requires_python=False # type: bool ): # type: (...) -> List[InstallRequirement] # Tell user what ...
[ "Prepare a single requirements file.\n\n :return: A list of additional InstallRequirements to also install.\n " ]
Please provide a description of the function:def get_installation_order(self, req_set): # type: (RequirementSet) -> List[InstallRequirement] # The current implementation, which we may change at any point # installs the user specified things in the order given, except when # depe...
[ "Create the installation order.\n\n The installation order is topological - requirements are installed\n before the requiring thing. We break cycles at an arbitrary point,\n and make no other guarantees.\n " ]
Please provide a description of the function:def _xml_escape(data): # ampersand must be replaced first from_symbols = '&><"\'' to_symbols = ('&'+s+';' for s in "amp gt lt quot apos".split()) for from_,to_ in zip(from_symbols, to_symbols): data = data.replace(from_, to_) return data
[ "Escape &, <, >, \", ', etc. in a string of data." ]
Please provide a description of the function:def line( loc, strg ): lastCR = strg.rfind("\n", 0, loc) nextCR = strg.find("\n", loc) if nextCR >= 0: return strg[lastCR+1:nextCR] else: return strg[lastCR+1:]
[ "Returns the line of text containing loc within a string, counting newlines as line separators.\n " ]
Please provide a description of the function:def traceParseAction(f): f = _trim_arity(f) def z(*paArgs): thisFunc = f.__name__ s,l,t = paArgs[-3:] if len(paArgs)>3: thisFunc = paArgs[0].__class__.__name__ + '.' + thisFunc sys.stderr.write( ">>entering %s(line: '%...
[ "Decorator for debugging parse actions.\n\n When the parse action is called, this decorator will print\n ``\">> entering method-name(line:<current_source_line>, <parse_location>, <matched_tokens>)\"``.\n When the parse action completes, the decorator will print\n ``\"<<\"`` followed by the returned valu...
Please provide a description of the function:def delimitedList( expr, delim=",", combine=False ): dlName = _ustr(expr)+" ["+_ustr(delim)+" "+_ustr(expr)+"]..." if combine: return Combine( expr + ZeroOrMore( delim + expr ) ).setName(dlName) else: return ( expr + ZeroOrMore( Suppress( del...
[ "Helper to define a delimited list of expressions - the delimiter\n defaults to ','. By default, the list elements and delimiters can\n have intervening whitespace, and comments, but this can be\n overridden by passing ``combine=True`` in the constructor. If\n ``combine`` is set to ``True``, the matchin...
Please provide a description of the function:def originalTextFor(expr, asString=True): locMarker = Empty().setParseAction(lambda s,loc,t: loc) endlocMarker = locMarker.copy() endlocMarker.callPreparse = False matchExpr = locMarker("_original_start") + expr + endlocMarker("_original_end") if asS...
[ "Helper to return the original, untokenized text for a given\n expression. Useful to restore the parsed fields of an HTML start\n tag into the raw tag text itself, or to revert separate tokens with\n intervening whitespace back to the original matching input text. By\n default, returns astring containi...
Please provide a description of the function:def locatedExpr(expr): locator = Empty().setParseAction(lambda s,l,t: l) return Group(locator("locn_start") + expr("value") + locator.copy().leaveWhitespace()("locn_end"))
[ "Helper to decorate a returned token with its starting and ending\n locations in the input string.\n\n This helper adds the following results names:\n\n - locn_start = location where matched expression begins\n - locn_end = location where matched expression ends\n - value = the actual parsed resul...
Please provide a description of the function:def srange(s): r _expanded = lambda p: p if not isinstance(p,ParseResults) else ''.join(unichr(c) for c in range(ord(p[0]),ord(p[1])+1)) try: return "".join(_expanded(part) for part in _reBracketExpr.parseString(s).body) except Exception: retu...
[ "Helper to easily define string ranges for use in Word\n construction. Borrows syntax from regexp '[]' string range\n definitions::\n\n srange(\"[0-9]\") -> \"0123456789\"\n srange(\"[a-z]\") -> \"abcdefghijklmnopqrstuvwxyz\"\n srange(\"[a-z$_]\") -> \"abcdefghijklmnopqrstuvwxyz$_\"\n...
Please provide a description of the function:def matchOnlyAtCol(n): def verifyCol(strg,locn,toks): if col(locn,strg) != n: raise ParseException(strg,locn,"matched token not at column %d" % n) return verifyCol
[ "Helper method for defining parse actions that require matching at\n a specific column in the input text.\n " ]
Please provide a description of the function:def tokenMap(func, *args): def pa(s,l,t): return [func(tokn, *args) for tokn in t] try: func_name = getattr(func, '__name__', getattr(func, '__class__').__name__) except Exception: func_name = str(func) ...
[ "Helper to define a parse action by mapping a function to all\n elements of a ParseResults list. If any additional args are passed,\n they are forwarded to the given function as additional arguments\n after the token, as in\n ``hex_integer = Word(hexnums).setParseAction(tokenMap(int, 16))``,\n which ...
Please provide a description of the function:def withAttribute(*args,**attrDict): if args: attrs = args[:] else: attrs = attrDict.items() attrs = [(k,v) for k,v in attrs] def pa(s,l,tokens): for attrName,attrValue in attrs: if attrName not in tokens: ...
[ "Helper to create a validating parse action to be used with start\n tags created with :class:`makeXMLTags` or\n :class:`makeHTMLTags`. Use ``withAttribute`` to qualify\n a starting tag with a required attribute value, to avoid false\n matches on common tags such as ``<TD>`` or ``<DIV>``.\n\n Call ``w...
Please provide a description of the function:def nestedExpr(opener="(", closer=")", content=None, ignoreExpr=quotedString.copy()): if opener == closer: raise ValueError("opening and closing strings cannot be the same") if content is None: if isinstance(opener,basestring) and isinstance(clos...
[ "Helper method for defining nested lists enclosed in opening and\n closing delimiters (\"(\" and \")\" are the default).\n\n Parameters:\n - opener - opening character for a nested list\n (default= ``\"(\"``); can also be a pyparsing expression\n - closer - closing character for a nested list\n ...
Please provide a description of the function:def _from_exception(cls, pe): return cls(pe.pstr, pe.loc, pe.msg, pe.parserElement)
[ "\n internal factory method to simplify creating one type of ParseException\n from another - avoids having __init__ signature conflicts among subclasses\n " ]
Please provide a description of the function:def markInputline( self, markerString = ">!<" ): line_str = self.line line_column = self.column - 1 if markerString: line_str = "".join((line_str[:line_column], markerString, line_str[line_column:])...
[ "Extracts the exception line from the input string, and marks\n the location of the exception with a special symbol.\n " ]
Please provide a description of the function:def explain(exc, depth=16): import inspect if depth is None: depth = sys.getrecursionlimit() ret = [] if isinstance(exc, ParseBaseException): ret.append(exc.line) ret.append(' ' * (exc.col - 1) + '...
[ "\n Method to take an exception and translate the Python internal traceback into a list\n of the pyparsing expressions that caused the exception to be raised.\n\n Parameters:\n\n - exc - exception raised during parsing (need not be a ParseException, in support\n of Python exce...
Please provide a description of the function:def pop( self, *args, **kwargs): if not args: args = [-1] for k,v in kwargs.items(): if k == 'default': args = (args[0], v) else: raise TypeError("pop() got an unexpected keyword arg...
[ "\n Removes and returns item at specified index (default= ``last``).\n Supports both ``list`` and ``dict`` semantics for ``pop()``. If\n passed no argument or an integer argument, it will use ``list``\n semantics and pop tokens from the list of parsed tokens. If passed\n a non-int...
Please provide a description of the function:def extend( self, itemseq ): if isinstance(itemseq, ParseResults): self += itemseq else: self.__toklist.extend(itemseq)
[ "\n Add sequence of elements to end of ParseResults list of elements.\n\n Example::\n\n patt = OneOrMore(Word(alphas))\n\n # use a parse action to append the reverse of the matched strings, to make a palindrome\n def make_palindrome(tokens):\n tokens.ext...
Please provide a description of the function:def asList( self ): return [res.asList() if isinstance(res,ParseResults) else res for res in self.__toklist]
[ "\n Returns the parse results as a nested list of matching tokens, all converted to strings.\n\n Example::\n\n patt = OneOrMore(Word(alphas))\n result = patt.parseString(\"sldkj lsdkj sldkj\")\n # even though the result prints in string-like form, it is actually a pypa...
Please provide a description of the function:def asDict( self ): if PY_3: item_fn = self.items else: item_fn = self.iteritems def toItem(obj): if isinstance(obj, ParseResults): if obj.haskeys(): return obj.asDict()...
[ "\n Returns the named parse results as a nested dictionary.\n\n Example::\n\n integer = Word(nums)\n date_str = integer(\"year\") + '/' + integer(\"month\") + '/' + integer(\"day\")\n\n result = date_str.parseString('12/31/1999')\n print(type(result), repr(r...
Please provide a description of the function:def getName(self): r if self.__name: return self.__name elif self.__parent: par = self.__parent() if par: return par.__lookup(self) else: return None elif (len(sel...
[ "\n Returns the results name for this token expression. Useful when several\n different expressions might match at a particular location.\n\n Example::\n\n integer = Word(nums)\n ssn_expr = Regex(r\"\\d\\d\\d-\\d\\d-\\d\\d\\d\\d\")\n house_number_expr = Suppress...
Please provide a description of the function:def dump(self, indent='', depth=0, full=True): out = [] NL = '\n' out.append( indent+_ustr(self.asList()) ) if full: if self.haskeys(): items = sorted((str(k), v) for k,v in self.items()) fo...
[ "\n Diagnostic method for listing out the contents of\n a :class:`ParseResults`. Accepts an optional ``indent`` argument so\n that this string can be embedded in a nested display of other data.\n\n Example::\n\n integer = Word(nums)\n date_str = integer(\"year\") + ...
Please provide a description of the function:def pprint(self, *args, **kwargs): pprint.pprint(self.asList(), *args, **kwargs)
[ "\n Pretty-printer for parsed results as a list, using the\n `pprint <https://docs.python.org/3/library/pprint.html>`_ module.\n Accepts additional positional or keyword args as defined for\n `pprint.pprint <https://docs.python.org/3/library/pprint.html#pprint.pprint>`_ .\n\n Exam...