Code
stringlengths
103
85.9k
Summary
listlengths
0
94
Please provide a description of the function:def _get_dependencies_from_json(ireq, sources): if os.environ.get("PASSA_IGNORE_JSON_API"): return # It is technically possible to parse extras out of the JSON API's # requirement format, but it is such a chore let's just use the simple API. if ...
[ "Retrieves dependencies for the install requirement from the JSON API.\n\n :param ireq: A single InstallRequirement\n :type ireq: :class:`~pip._internal.req.req_install.InstallRequirement`\n :return: A set of dependency lines for generating new InstallRequirements.\n :rtype: set(str) or None\n " ]
Please provide a description of the function:def _read_requirements(metadata, extras): extras = extras or () requirements = [] for entry in metadata.run_requires: if isinstance(entry, six.text_type): entry = {"requires": [entry]} extra = None else: ex...
[ "Read wheel metadata to know what it depends on.\n\n The `run_requires` attribute contains a list of dict or str specifying\n requirements. For dicts, it may contain an \"extra\" key to specify these\n requirements are for a specific extra. Unfortunately, not all fields are\n specificed like this (I don...
Please provide a description of the function:def _read_requires_python(metadata): # TODO: Support more metadata formats. value = metadata.dictionary.get("requires_python") if value is not None: return value if metadata._legacy: value = metadata._legacy.get("Requires-Python") ...
[ "Read wheel metadata to know the value of Requires-Python.\n\n This is surprisingly poorly supported in Distlib. This function tries\n several ways to get this information:\n\n * Metadata 2.0: metadata.dictionary.get(\"requires_python\") is not None\n * Metadata 2.1: metadata._legacy.get(\"Requires-Pyth...
Please provide a description of the function:def _get_dependencies_from_pip(ireq, sources): extras = ireq.extras or () try: wheel = build_wheel(ireq, sources) except WheelBuildError: # XXX: This depends on a side effect of `build_wheel`. This block is # reached when it fails to ...
[ "Retrieves dependencies for the requirement from pipenv.patched.notpip internals.\n\n The current strategy is to try the followings in order, returning the\n first successful result.\n\n 1. Try to build a wheel out of the ireq, and read metadata out of it.\n 2. Read metadata out of the egg-info director...
Please provide a description of the function:def get_dependencies(requirement, sources): getters = [ _get_dependencies_from_cache, _cached(_get_dependencies_from_json, sources=sources), _cached(_get_dependencies_from_pip, sources=sources), ] ireq = requirement.as_ireq() last...
[ "Get all dependencies for a given install requirement.\n\n :param requirement: A requirement\n :param sources: Pipfile-formatted sources\n :type sources: list[dict]\n " ]
Please provide a description of the function:def format_header_param(name, value): if not any(ch in value for ch in '"\\\r\n'): result = '%s="%s"' % (name, value) try: result.encode('ascii') except (UnicodeEncodeError, UnicodeDecodeError): pass else: ...
[ "\n Helper function to format and quote a single header parameter.\n\n Particularly useful for header parameters which might contain\n non-ASCII values, like file names. This follows RFC 2231, as\n suggested by RFC 2388 Section 4.4.\n\n :param name:\n The name of the parameter, a string expect...
Please provide a description of the function:def from_tuples(cls, fieldname, value): if isinstance(value, tuple): if len(value) == 3: filename, data, content_type = value else: filename, data = value content_type = guess_content_ty...
[ "\n A :class:`~urllib3.fields.RequestField` factory from old-style tuple parameters.\n\n Supports constructing :class:`~urllib3.fields.RequestField` from\n parameter of key/value strings AND key/filetuple. A filetuple is a\n (filename, data, MIME type) tuple where the MIME type is option...
Please provide a description of the function:def _render_parts(self, header_parts): parts = [] iterable = header_parts if isinstance(header_parts, dict): iterable = header_parts.items() for name, value in iterable: if value is not None: p...
[ "\n Helper function to format and quote a single header.\n\n Useful for single headers that are composed of multiple items. E.g.,\n 'Content-Disposition' fields.\n\n :param header_parts:\n A sequence of (k, v) tuples or a :class:`dict` of (k, v) to format\n as `k1=\...
Please provide a description of the function:def render_headers(self): lines = [] sort_keys = ['Content-Disposition', 'Content-Type', 'Content-Location'] for sort_key in sort_keys: if self.headers.get(sort_key, False): lines.append('%s: %s' % (sort_key, self...
[ "\n Renders the headers for this request field.\n " ]
Please provide a description of the function:def make_multipart(self, content_disposition=None, content_type=None, content_location=None): self.headers['Content-Disposition'] = content_disposition or 'form-data' self.headers['Content-Disposition'] += '; '.join([ ...
[ "\n Makes this request field into a multipart request field.\n\n This method overrides \"Content-Disposition\", \"Content-Type\" and\n \"Content-Location\" headers to the request parameter.\n\n :param content_type:\n The 'Content-Type' of the request body.\n :param cont...
Please provide a description of the function:def emptyTag(self, namespace, name, attrs, hasChildren=False): yield {"type": "EmptyTag", "name": name, "namespace": namespace, "data": attrs} if hasChildren: yield self.error("Void element has children")
[ "Generates an EmptyTag token\n\n :arg namespace: the namespace of the token--can be ``None``\n\n :arg name: the name of the element\n\n :arg attrs: the attributes of the element as a dict\n\n :arg hasChildren: whether or not to yield a SerializationError because\n this tag sho...
Please provide a description of the function:def text(self, data): data = data middle = data.lstrip(spaceCharacters) left = data[:len(data) - len(middle)] if left: yield {"type": "SpaceCharacters", "data": left} data = middle middle = data.rstrip(spac...
[ "Generates SpaceCharacters and Characters tokens\n\n Depending on what's in the data, this generates one or more\n ``SpaceCharacters`` and ``Characters`` tokens.\n\n For example:\n\n >>> from html5lib.treewalkers.base import TreeWalker\n >>> # Give it an empty tree just so...
Please provide a description of the function:def _get_activate_script(cmd, venv): # Suffix and source command for other shells. # Support for fish shell. if "fish" in cmd: suffix = ".fish" command = "source" # Support for csh shell. elif "csh" in cmd: suffix = ".csh" ...
[ "Returns the string to activate a virtualenv.\n\n This is POSIX-only at the moment since the compat (pexpect-based) shell\n does not work elsewhere anyway.\n " ]
Please provide a description of the function:def filename(self): if self.buildver: buildver = '-' + self.buildver else: buildver = '' pyver = '.'.join(self.pyver) abi = '.'.join(self.abi) arch = '.'.join(self.arch) # replace - with _ as a ...
[ "\n Build and return a filename from the various components.\n " ]
Please provide a description of the function:def build(self, paths, tags=None, wheel_version=None): if tags is None: tags = {} libkey = list(filter(lambda o: o in paths, ('purelib', 'platlib')))[0] if libkey == 'platlib': is_pure = 'false' default_py...
[ "\n Build a wheel from files in specified paths, and use any specified tags\n when determining the name of the wheel.\n " ]
Please provide a description of the function:def install(self, paths, maker, **kwargs): dry_run = maker.dry_run warner = kwargs.get('warner') lib_only = kwargs.get('lib_only', False) bc_hashed_invalidation = kwargs.get('bytecode_hashed_invalidation', False) pathname = ...
[ "\n Install a wheel to the specified paths. If kwarg ``warner`` is\n specified, it should be a callable, which will be called with two\n tuples indicating the wheel version of this software and the wheel\n version in the file, if there is a discrepancy in the versions.\n This can ...
Please provide a description of the function:def update(self, modifier, dest_dir=None, **kwargs): def get_version(path_map, info_dir): version = path = None key = '%s/%s' % (info_dir, METADATA_FILENAME) if key not in path_map: key = '%s/PKG-INFO' % i...
[ "\n Update the contents of a wheel in a generic way. The modifier should\n be a callable which expects a dictionary argument: its keys are\n archive-entry paths, and its values are absolute filesystem paths\n where the contents the corresponding archive entries can be found. The\n ...
Please provide a description of the function:def load_dot_env(): if not environments.PIPENV_DONT_LOAD_ENV: # If the project doesn't exist yet, check current directory for a .env file project_directory = project.project_directory or "." dotenv_file = environments.PIPENV_DOTENV_LOCATION o...
[ "Loads .env file into sys.environ." ]
Please provide a description of the function:def add_to_path(p): if p not in os.environ["PATH"]: os.environ["PATH"] = "{0}{1}{2}".format(p, os.pathsep, os.environ["PATH"])
[ "Adds a given path to the PATH." ]
Please provide a description of the function:def cleanup_virtualenv(bare=True): if not bare: click.echo(crayons.red("Environment creation aborted.")) try: # Delete the virtualenv. vistir.path.rmtree(project.virtualenv_location) except OSError as e: click.echo( ...
[ "Removes the virtualenv directory from the system." ]
Please provide a description of the function:def ensure_pipfile(validate=True, skip_requirements=False, system=False): from .environments import PIPENV_VIRTUALENV # Assert Pipfile exists. python = which("python") if not (USING_DEFAULT_PYTHON or system) else None if project.pipfile_is_empty: ...
[ "Creates a Pipfile for the project, if it doesn't exist." ]
Please provide a description of the function:def find_a_system_python(line): from .vendor.pythonfinder import Finder finder = Finder(system=False, global_search=True) if not line: return next(iter(finder.find_all_python_versions()), None) # Use the windows finder executable if (line.st...
[ "Find a Python installation from a given line.\n\n This tries to parse the line in various of ways:\n\n * Looks like an absolute path? Use it directly.\n * Looks like a py.exe call? Use py.exe to get the executable.\n * Starts with \"py\" something? Looks like a python command. Try to find it\n in ...
Please provide a description of the function:def ensure_virtualenv(three=None, python=None, site_packages=False, pypi_mirror=None): from .environments import PIPENV_USE_SYSTEM def abort(): sys.exit(1) global USING_DEFAULT_PYTHON if not project.virtualenv_exists: try: #...
[ "Creates a virtualenv, if one doesn't exist." ]
Please provide a description of the function:def ensure_project( three=None, python=None, validate=True, system=False, warn=True, site_packages=False, deploy=False, skip_requirements=False, pypi_mirror=None, clear=False, ): from .environments import PIPENV_USE_SYSTEM ...
[ "Ensures both Pipfile and virtualenv exist for the project." ]
Please provide a description of the function:def shorten_path(location, bold=False): original = location short = os.sep.join( [s[0] if len(s) > (len("2long4")) else s for s in location.split(os.sep)] ) short = short.split(os.sep) short[-1] = original.split(os.sep)[-1] if bold: ...
[ "Returns a visually shorter representation of a given system path." ]
Please provide a description of the function:def do_where(virtualenv=False, bare=True): if not virtualenv: if not project.pipfile_exists: click.echo( "No Pipfile present at project home. Consider running " "{0} first to automatically generate a Pipfile for yo...
[ "Executes the where functionality." ]
Please provide a description of the function:def do_install_dependencies( dev=False, only=False, bare=False, requirements=False, allow_global=False, ignore_hashes=False, skip_lock=False, concurrent=True, requirements_dir=None, pypi_mirror=False, ): from six.moves import...
[ "\"\n Executes the install functionality.\n\n If requirements is True, simply spits out a requirements format to stdout.\n " ]
Please provide a description of the function:def do_create_virtualenv(python=None, site_packages=False, pypi_mirror=None): click.echo( crayons.normal(fix_utf8("Creating a virtualenv for this project…"), bold=True), err=True ) click.echo( u"Pipfile: {0}".format(crayons.red(project.pipfi...
[ "Creates a virtualenv." ]
Please provide a description of the function:def do_lock( ctx=None, system=False, clear=False, pre=False, keep_outdated=False, write=True, pypi_mirror=None, ): cached_lockfile = {} if not pre: pre = project.settings.get("allow_prereleases") if keep_outdated: ...
[ "Executes the freeze functionality." ]
Please provide a description of the function:def do_purge(bare=False, downloads=False, allow_global=False): if downloads: if not bare: click.echo(crayons.normal(fix_utf8("Clearing out downloads directory…"), bold=True)) vistir.path.rmtree(project.download_location) return ...
[ "Executes the purge functionality." ]
Please provide a description of the function:def do_init( dev=False, requirements=False, allow_global=False, ignore_pipfile=False, skip_lock=False, system=False, concurrent=True, deploy=False, pre=False, keep_outdated=False, requirements_dir=None, pypi_mirror=None, ): ...
[ "Executes the init functionality." ]
Please provide a description of the function:def fallback_which(command, location=None, allow_global=False, system=False): from .vendor.pythonfinder import Finder if not command: raise ValueError("fallback_which: Must provide a command to search for...") if not isinstance(command, six.string_t...
[ "\n A fallback implementation of the `which` utility command that relies exclusively on\n searching the path for commands.\n\n :param str command: The command to search for, optional\n :param str location: The search location to prioritize (prepend to path), defaults to None\n :param bool allow_globa...
Please provide a description of the function:def which_pip(allow_global=False): location = None if "VIRTUAL_ENV" in os.environ: location = os.environ["VIRTUAL_ENV"] if allow_global: if location: pip = which("pip", location=location) if pip: retur...
[ "Returns the location of virtualenv-installed pip." ]
Please provide a description of the function:def system_which(command, mult=False): _which = "which -a" if not os.name == "nt" else "where" os.environ = { vistir.compat.fs_str(k): vistir.compat.fs_str(val) for k, val in os.environ.items() } result = None try: c = delegat...
[ "Emulates the system's which. Returns None if not found." ]
Please provide a description of the function:def format_help(help): help = help.replace("Options:", str(crayons.normal("Options:", bold=True))) help = help.replace( "Usage: pipenv", str("Usage: {0}".format(crayons.normal("pipenv", bold=True))) ) help = help.replace(" check", str(crayons.re...
[ "Formats the help string.", "\nUsage Examples:\n Create a new project using Python 3.7, specifically:\n $ {1}\n\n Remove project virtualenv (inferred from current directory):\n $ {9}\n\n Install all dependencies for a project (including dev):\n $ {2}\n\n Create a lockfile containing pre-releases:\n ...
Please provide a description of the function:def ensure_lockfile(keep_outdated=False, pypi_mirror=None): if not keep_outdated: keep_outdated = project.settings.get("keep_outdated") # Write out the lockfile if it doesn't exist, but not if the Pipfile is being ignored if project.lockfile_exists: ...
[ "Ensures that the lockfile is up-to-date." ]
Please provide a description of the function:def _inline_activate_venv(): components = [] for name in ("bin", "Scripts"): bindir = os.path.join(project.virtualenv_location, name) if os.path.exists(bindir): components.append(bindir) if "PATH" in os.environ: components...
[ "Built-in venv doesn't have activate_this.py, but doesn't need it anyway.\n\n As long as we find the correct executable, built-in venv sets up the\n environment automatically.\n\n See: https://bugs.python.org/issue21496#msg218455\n " ]
Please provide a description of the function:def do_run(command, args, three=None, python=False, pypi_mirror=None): from .cmdparse import ScriptEmptyError # Ensure that virtualenv is available. ensure_project( three=three, python=python, validate=False, pypi_mirror=pypi_mirror, ) load...
[ "Attempt to run command either pulling from project or interpreting as executable.\n\n Args are appended to the command in [scripts] section of project if found.\n " ]
Please provide a description of the function:def _iter_process(): # TODO: Process32{First,Next} does not return full executable path, only # the name. To get the full path, Module32{First,Next} is needed, but that # does not contain parent process information. We probably need to call # BOTH to bui...
[ "Iterate through processes, yielding process ID and properties of each.\n\n Example usage::\n\n >>> for pid, info in _iter_process():\n ... print(pid, '->', info)\n 1509 -> {'parent_pid': 1201, 'executable': 'python.exe'}\n " ]
Please provide a description of the function:def get_shell(pid=None, max_depth=6): if not pid: pid = os.getpid() processes = dict(_iter_process()) def check_parent(pid, lvl=0): ppid = processes[pid].get('parent_pid') shell_name = _get_executable(processes.get(ppid)) if ...
[ "Get the shell that the supplied pid or os.getpid() is running in.\n " ]
Please provide a description of the function:def fail(self, message, param=None, ctx=None): raise BadParameter(message, ctx=ctx, param=param)
[ "Helper method to fail with an invalid value message." ]
Please provide a description of the function:def user_cache_dir(appname): # type: (str) -> str r if WINDOWS: # Get the base path path = os.path.normpath(_get_win_folder("CSIDL_LOCAL_APPDATA")) # When using Python 2, return paths as bytes on Windows like we do on # other oper...
[ "\n Return full path to the user-specific cache dir for this application.\n\n \"appname\" is the name of application.\n\n Typical user cache directories are:\n macOS: ~/Library/Caches/<AppName>\n Unix: ~/.cache/<AppName> (XDG default)\n Windows: C:\\Users\\<username>\...
Please provide a description of the function:def auto_decode(data): # type: (bytes) -> Text for bom, encoding in BOMS: if data.startswith(bom): return data[len(bom):].decode(encoding) # Lets check the first two lines as in PEP263 for line in data.split(b'\n')[:2]: if lin...
[ "Check a bytes string for a BOM to correctly detect the encoding\n\n Fallback to locale.getpreferredencoding(False) like open() on Python3" ]
Please provide a description of the function:def resolve_color_default(color=None): if color is not None: return color ctx = get_current_context(silent=True) if ctx is not None: return ctx.color
[ "\"Internal helper to get the default value of the color flag. If a\n value is passed it's returned unchanged, otherwise it's looked up from\n the current context.\n " ]
Please provide a description of the function:def load(f, _dict=dict, decoder=None): if _ispath(f): with io.open(_getpath(f), encoding='utf-8') as ffile: return loads(ffile.read(), _dict, decoder) elif isinstance(f, list): from os import path as op from warnings import w...
[ "Parses named file or files as toml and returns a dictionary\n\n Args:\n f: Path to the file to open, array of files to read into single dict\n or a file descriptor\n _dict: (optional) Specifies the class of the returned toml dictionary\n\n Returns:\n Parsed toml file represente...
Please provide a description of the function:def loads(s, _dict=dict, decoder=None): implicitgroups = [] if decoder is None: decoder = TomlDecoder(_dict) retval = decoder.get_empty_table() currentlevel = retval if not isinstance(s, basestring): raise TypeError("Expecting someth...
[ "Parses string as toml\n\n Args:\n s: String to be parsed\n _dict: (optional) Specifies the class of the returned toml dictionary\n\n Returns:\n Parsed toml file represented as a dictionary\n\n Raises:\n TypeError: When a non-string is passed\n TomlDecodeError: Error whil...
Please provide a description of the function:def markup_join(seq): buf = [] iterator = imap(soft_unicode, seq) for arg in iterator: buf.append(arg) if hasattr(arg, '__html__'): return Markup(u'').join(chain(buf, iterator)) return concat(buf)
[ "Concatenation that escapes if necessary and converts to unicode." ]
Please provide a description of the function:def new_context(environment, template_name, blocks, vars=None, shared=None, globals=None, locals=None): if vars is None: vars = {} if shared: parent = vars else: parent = dict(globals or (), **vars) if locals: ...
[ "Internal helper to for context creation." ]
Please provide a description of the function:def make_logging_undefined(logger=None, base=None): if logger is None: import logging logger = logging.getLogger(__name__) logger.addHandler(logging.StreamHandler(sys.stderr)) if base is None: base = Undefined def _log_messag...
[ "Given a logger object this returns a new undefined class that will\n log certain failures. It will log iterations and printing. If no\n logger is given a default logger is created.\n\n Example::\n\n logger = logging.getLogger(__name__)\n LoggingUndefined = make_logging_undefined(\n ...
Please provide a description of the function:def super(self, name, current): try: blocks = self.blocks[name] index = blocks.index(current) + 1 blocks[index] except LookupError: return self.environment.undefined('there is no parent block ' ...
[ "Render a parent block." ]
Please provide a description of the function:def resolve(self, key): if self._legacy_resolve_mode: rv = resolve_or_missing(self, key) else: rv = self.resolve_or_missing(key) if rv is missing: return self.environment.undefined(name=key) return ...
[ "Looks up a variable like `__getitem__` or `get` but returns an\n :class:`Undefined` object with the name of the name looked up.\n " ]
Please provide a description of the function:def resolve_or_missing(self, key): if self._legacy_resolve_mode: rv = self.resolve(key) if isinstance(rv, Undefined): rv = missing return rv return resolve_or_missing(self, key)
[ "Resolves a variable like :meth:`resolve` but returns the\n special `missing` value if it cannot be found.\n " ]
Please provide a description of the function:def get_exported(self): return dict((k, self.vars[k]) for k in self.exported_vars)
[ "Get a new dict with the exported variables." ]
Please provide a description of the function:def get_all(self): if not self.vars: return self.parent if not self.parent: return self.vars return dict(self.parent, **self.vars)
[ "Return the complete context as dict including the exported\n variables. For optimizations reasons this might not return an\n actual copy so be careful with using it.\n " ]
Please provide a description of the function:def derived(self, locals=None): context = new_context(self.environment, self.name, {}, self.get_all(), True, None, locals) context.eval_ctx = self.eval_ctx context.blocks.update((k, list(v)) for k, v in iteritems...
[ "Internal helper function to create a derived context. This is\n used in situations where the system needs a new context in the same\n template that is independent.\n " ]
Please provide a description of the function:def super(self): if self._depth + 1 >= len(self._stack): return self._context.environment. \ undefined('there is no parent block called %r.' % self.name, name='super') return BlockReference(self.n...
[ "Super the block." ]
Please provide a description of the function:def cycle(self, *args): if not args: raise TypeError('no items for cycling given') return args[self.index0 % len(args)]
[ "Cycles among the arguments with the current loop index." ]
Please provide a description of the function:def changed(self, *value): if self._last_checked_value != value: self._last_checked_value = value return True return False
[ "Checks whether the value has changed since the last call." ]
Please provide a description of the function:def _invoke(self, arguments, autoescape): rv = self._func(*arguments) if autoescape: rv = Markup(rv) return rv
[ "This method is being swapped out by the async implementation." ]
Please provide a description of the function:def main(): '''This is where the example starts and the FSM state transitions are defined. Note that states are strings (such as 'INIT'). This is not necessary, but it makes the example easier to read. ''' f = FSM ('INIT', []) f.set_default_transition (...
[]
Please provide a description of the function:def add_transition (self, input_symbol, state, action=None, next_state=None): '''This adds a transition that associates: (input_symbol, current_state) --> (action, next_state) The action may be set to None in which case the process() method...
[]
Please provide a description of the function:def add_transition_list (self, list_input_symbols, state, action=None, next_state=None): '''This adds the same transition for a list of input symbols. You can pass a list or a string. Note that it is handy to use string.digits, string.whitespace, str...
[]
Please provide a description of the function:def add_transition_any (self, state, action=None, next_state=None): '''This adds a transition that associates: (current_state) --> (action, next_state) That is, any input symbol will match the current state. The process() method che...
[]
Please provide a description of the function:def get_transition (self, input_symbol, state): '''This returns (action, next state) given an input_symbol and state. This does not modify the FSM state, so calling this method has no side effects. Normally you do not call this method directly. It is...
[]
Please provide a description of the function:def process (self, input_symbol): '''This is the main method that you call to process input. This may cause the FSM to change state and call an action. This method calls get_transition() to find the action and next_state associated with the i...
[]
Please provide a description of the function:def ip_address(address): try: return IPv4Address(address) except (AddressValueError, NetmaskValueError): pass try: return IPv6Address(address) except (AddressValueError, NetmaskValueError): pass if isinstance(address...
[ "Take an IP string/int and return an object of the correct type.\n\n Args:\n address: A string or integer, the IP address. Either IPv4 or\n IPv6 addresses may be supplied; integers less than 2**32 will\n be considered to be IPv4 by default.\n\n Returns:\n An IPv4Address or IPv...
Please provide a description of the function:def ip_interface(address): try: return IPv4Interface(address) except (AddressValueError, NetmaskValueError): pass try: return IPv6Interface(address) except (AddressValueError, NetmaskValueError): pass raise ValueErro...
[ "Take an IP string/int and return an object of the correct type.\n\n Args:\n address: A string or integer, the IP address. Either IPv4 or\n IPv6 addresses may be supplied; integers less than 2**32 will\n be considered to be IPv4 by default.\n\n Returns:\n An IPv4Interface or I...
Please provide a description of the function:def _split_optional_netmask(address): addr = _compat_str(address).split('/') if len(addr) > 2: raise AddressValueError("Only one '/' permitted in %r" % address) return addr
[ "Helper to split the netmask and raise AddressValueError if needed" ]
Please provide a description of the function:def _find_address_range(addresses): it = iter(addresses) first = last = next(it) for ip in it: if ip._ip != last._ip + 1: yield first, last first = ip last = ip yield first, last
[ "Find a sequence of sorted deduplicated IPv#Address.\n\n Args:\n addresses: a list of IPv#Address objects.\n\n Yields:\n A tuple containing the first and last IP addresses in the sequence.\n\n " ]
Please provide a description of the function:def _count_righthand_zero_bits(number, bits): if number == 0: return bits return min(bits, _compat_bit_length(~number & (number - 1)))
[ "Count the number of zero bits on the right hand side.\n\n Args:\n number: an integer.\n bits: maximum number of bits to count.\n\n Returns:\n The number of zero bits on the right hand side of the number.\n\n " ]
Please provide a description of the function:def _collapse_addresses_internal(addresses): # First merge to_merge = list(addresses) subnets = {} while to_merge: net = to_merge.pop() supernet = net.supernet() existing = subnets.get(supernet) if existing is None: ...
[ "Loops through the addresses, collapsing concurrent netblocks.\n\n Example:\n\n ip1 = IPv4Network('192.0.2.0/26')\n ip2 = IPv4Network('192.0.2.64/26')\n ip3 = IPv4Network('192.0.2.128/26')\n ip4 = IPv4Network('192.0.2.192/26')\n\n _collapse_addresses_internal([ip1, ip2, ip3, ip...
Please provide a description of the function:def collapse_addresses(addresses): addrs = [] ips = [] nets = [] # split IP addresses and networks for ip in addresses: if isinstance(ip, _BaseAddress): if ips and ips[-1]._version != ip._version: raise TypeError(...
[ "Collapse a list of IP objects.\n\n Example:\n collapse_addresses([IPv4Network('192.0.2.0/25'),\n IPv4Network('192.0.2.128/25')]) ->\n [IPv4Network('192.0.2.0/24')]\n\n Args:\n addresses: An iterator of IPv4Network or IPv6Network objects.\n\n ...
Please provide a description of the function:def get_mixed_type_key(obj): if isinstance(obj, _BaseNetwork): return obj._get_networks_key() elif isinstance(obj, _BaseAddress): return obj._get_address_key() return NotImplemented
[ "Return a key suitable for sorting between networks and addresses.\n\n Address and Network objects are not sortable by default; they're\n fundamentally different so the expression\n\n IPv4Address('192.0.2.0') <= IPv4Network('192.0.2.0/24')\n\n doesn't make any sense. There are some times however, w...
Please provide a description of the function:def _prefix_from_ip_int(cls, ip_int): trailing_zeroes = _count_righthand_zero_bits(ip_int, cls._max_prefixlen) prefixlen = cls._max_prefixlen - trailing_zeroes leading_ones = ip_int >> trai...
[ "Return prefix length from the bitwise netmask.\n\n Args:\n ip_int: An integer, the netmask in expanded bitwise format\n\n Returns:\n An integer, the prefix length.\n\n Raises:\n ValueError: If the input intermingles zeroes & ones\n " ]
Please provide a description of the function:def _prefix_from_prefix_string(cls, prefixlen_str): # int allows a leading +/- as well as surrounding whitespace, # so we ensure that isn't the case if not _BaseV4._DECIMAL_DIGITS.issuperset(prefixlen_str): cls._report_invalid_net...
[ "Return prefix length from a numeric string\n\n Args:\n prefixlen_str: The string to be converted\n\n Returns:\n An integer, the prefix length.\n\n Raises:\n NetmaskValueError: If the input is not a valid netmask\n " ]
Please provide a description of the function:def _prefix_from_ip_string(cls, ip_str): # Parse the netmask/hostmask like an IP address. try: ip_int = cls._ip_int_from_string(ip_str) except AddressValueError: cls._report_invalid_netmask(ip_str) # Try match...
[ "Turn a netmask/hostmask string into a prefix length\n\n Args:\n ip_str: The netmask/hostmask to be converted\n\n Returns:\n An integer, the prefix length.\n\n Raises:\n NetmaskValueError: If the input is not a valid netmask/hostmask\n " ]
Please provide a description of the function:def overlaps(self, other): return self.network_address in other or ( self.broadcast_address in other or ( other.network_address in self or ( other.broadcast_address in self)))
[ "Tell if self is partly contained in other." ]
Please provide a description of the function:def address_exclude(self, other): if not self._version == other._version: raise TypeError("%s and %s are not of the same version" % ( self, other)) if not isinstance(other, _BaseNetwork): raise Typ...
[ "Remove an address from a larger block.\n\n For example:\n\n addr1 = ip_network('192.0.2.0/28')\n addr2 = ip_network('192.0.2.1/32')\n list(addr1.address_exclude(addr2)) =\n [IPv4Network('192.0.2.0/32'), IPv4Network('192.0.2.2/31'),\n IPv4Networ...
Please provide a description of the function:def compare_networks(self, other): # does this need to raise a ValueError? if self._version != other._version: raise TypeError('%s and %s are not of the same type' % ( self, other)) # self._version == o...
[ "Compare two IP objects.\n\n This is only concerned about the comparison of the integer\n representation of the network addresses. This means that the\n host bits aren't considered at all in this method. If you want\n to compare host bits, you can easily enough do a\n 'HostA._ip...
Please provide a description of the function:def subnets(self, prefixlen_diff=1, new_prefix=None): if self._prefixlen == self._max_prefixlen: yield self return if new_prefix is not None: if new_prefix < self._prefixlen: raise ValueError('new ...
[ "The subnets which join to make the current subnet.\n\n In the case that self contains only one IP\n (self._prefixlen == 32 for IPv4 or self._prefixlen == 128\n for IPv6), yield an iterator with just ourself.\n\n Args:\n prefixlen_diff: An integer, the amount the prefix length...
Please provide a description of the function:def supernet(self, prefixlen_diff=1, new_prefix=None): if self._prefixlen == 0: return self if new_prefix is not None: if new_prefix > self._prefixlen: raise ValueError('new prefix must be shorter') ...
[ "The supernet containing the current network.\n\n Args:\n prefixlen_diff: An integer, the amount the prefix length of\n the network should be decreased by. For example, given a\n /24 network and a prefixlen_diff of 3, a supernet with a\n /21 netmask is retur...
Please provide a description of the function:def _make_netmask(cls, arg): if arg not in cls._netmask_cache: if isinstance(arg, _compat_int_types): prefixlen = arg else: try: # Check for a netmask in prefix length form ...
[ "Make a (netmask, prefix_len) tuple from the given argument.\n\n Argument can be:\n - an integer (the prefix length)\n - a string representing the prefix length (e.g. \"24\")\n - a string representing the prefix netmask (e.g. \"255.255.255.0\")\n " ]
Please provide a description of the function:def _ip_int_from_string(cls, ip_str): if not ip_str: raise AddressValueError('Address cannot be empty') octets = ip_str.split('.') if len(octets) != 4: raise AddressValueError("Expected 4 octets in %r" % ip_str) ...
[ "Turn the given IP string into an integer for comparison.\n\n Args:\n ip_str: A string, the IP ip_str.\n\n Returns:\n The IP ip_str as an integer.\n\n Raises:\n AddressValueError: if ip_str isn't a valid IPv4 Address.\n\n " ]
Please provide a description of the function:def _string_from_ip_int(cls, ip_int): return '.'.join(_compat_str(struct.unpack(b'!B', b)[0] if isinstance(b, bytes) else b) for b in _compat_to_bytes(ip_int, 4, ...
[ "Turns a 32-bit integer into dotted decimal notation.\n\n Args:\n ip_int: An integer, the IP address.\n\n Returns:\n The IP address as a string in dotted decimal notation.\n\n " ]
Please provide a description of the function:def _is_hostmask(self, ip_str): bits = ip_str.split('.') try: parts = [x for x in map(int, bits) if x in self._valid_mask_octets] except ValueError: return False if len(parts) != len(bits): return F...
[ "Test if the IP string is a hostmask (rather than a netmask).\n\n Args:\n ip_str: A string, the potential hostmask.\n\n Returns:\n A boolean, True if the IP string is a hostmask.\n\n " ]
Please provide a description of the function:def is_global(self): return (not (self.network_address in IPv4Network('100.64.0.0/10') and self.broadcast_address in IPv4Network('100.64.0.0/10')) and not self.is_private)
[ "Test if this address is allocated for public networks.\n\n Returns:\n A boolean, True if the address is not reserved per\n iana-ipv4-special-registry.\n\n " ]
Please provide a description of the function:def _make_netmask(cls, arg): if arg not in cls._netmask_cache: if isinstance(arg, _compat_int_types): prefixlen = arg else: prefixlen = cls._prefix_from_prefix_string(arg) netmask = IPv6Addr...
[ "Make a (netmask, prefix_len) tuple from the given argument.\n\n Argument can be:\n - an integer (the prefix length)\n - a string representing the prefix length (e.g. \"24\")\n - a string representing the prefix netmask (e.g. \"255.255.255.0\")\n " ]
Please provide a description of the function:def _ip_int_from_string(cls, ip_str): if not ip_str: raise AddressValueError('Address cannot be empty') parts = ip_str.split(':') # An IPv6 address needs at least 2 colons (3 parts). _min_parts = 3 if len(parts) ...
[ "Turn an IPv6 ip_str into an integer.\n\n Args:\n ip_str: A string, the IPv6 ip_str.\n\n Returns:\n An int, the IPv6 address\n\n Raises:\n AddressValueError: if ip_str isn't a valid IPv6 Address.\n\n " ]
Please provide a description of the function:def _parse_hextet(cls, hextet_str): # Whitelist the characters, since int() allows a lot of bizarre stuff. if not cls._HEX_DIGITS.issuperset(hextet_str): raise ValueError("Only hex digits permitted in %r" % hextet_str) # We do the...
[ "Convert an IPv6 hextet string into an integer.\n\n Args:\n hextet_str: A string, the number to parse.\n\n Returns:\n The hextet as an integer.\n\n Raises:\n ValueError: if the input isn't strictly a hex number from\n [0..FFFF].\n\n " ]
Please provide a description of the function:def _compress_hextets(cls, hextets): best_doublecolon_start = -1 best_doublecolon_len = 0 doublecolon_start = -1 doublecolon_len = 0 for index, hextet in enumerate(hextets): if hextet == '0': double...
[ "Compresses a list of hextets.\n\n Compresses a list of strings, replacing the longest continuous\n sequence of \"0\" in the list with \"\" and adding empty strings at\n the beginning or at the end of the string such that subsequently\n calling \":\".join(hextets) will produce the compre...
Please provide a description of the function:def teredo(self): if (self._ip >> 96) != 0x20010000: return None return (IPv4Address((self._ip >> 64) & 0xFFFFFFFF), IPv4Address(~self._ip & 0xFFFFFFFF))
[ "Tuple of embedded teredo IPs.\n\n Returns:\n Tuple of the (server, client) IPs or None if the address\n doesn't appear to be a teredo address (doesn't start with\n 2001::/32)\n\n " ]
Please provide a description of the function:def serialize(input, tree="etree", encoding=None, **serializer_opts): # XXX: Should we cache this? walker = treewalkers.getTreeWalker(tree) s = HTMLSerializer(**serializer_opts) return s.render(walker(input), encoding)
[ "Serializes the input token stream using the specified treewalker\n\n :arg input: the token stream to serialize\n\n :arg tree: the treewalker to use\n\n :arg encoding: the encoding to use\n\n :arg serializer_opts: any options to pass to the\n :py:class:`html5lib.serializer.HTMLSerializer` that ge...
Please provide a description of the function:def render(self, treewalker, encoding=None): if encoding: return b"".join(list(self.serialize(treewalker, encoding))) else: return "".join(list(self.serialize(treewalker)))
[ "Serializes the stream from the treewalker into a string\n\n :arg treewalker: the treewalker to serialize\n\n :arg encoding: the string encoding to use\n\n :returns: the serialized tree\n\n Example:\n\n >>> from html5lib import parse, getTreeWalker\n >>> from html5lib.seria...
Please provide a description of the function:def get_current_branch(self, location): # git-symbolic-ref exits with empty stdout if "HEAD" is a detached # HEAD rather than a symbolic ref. In addition, the -q causes the # command to exit with status code 1 instead of 128 in this case ...
[ "\n Return the current branch, or None if HEAD isn't at a branch\n (e.g. detached HEAD).\n " ]
Please provide a description of the function:def get_revision_sha(self, dest, rev): # Pass rev to pre-filter the list. output = self.run_command(['show-ref', rev], cwd=dest, show_stdout=False, on_returncode='ignore') refs = {} for line in output...
[ "\n Return (sha_or_none, is_branch), where sha_or_none is a commit hash\n if the revision names a remote branch or tag, otherwise None.\n\n Args:\n dest: the repository directory.\n rev: the revision name.\n " ]
Please provide a description of the function:def resolve_revision(self, dest, url, rev_options): rev = rev_options.arg_rev sha, is_branch = self.get_revision_sha(dest, rev) if sha is not None: rev_options = rev_options.make_new(sha) rev_options.branch_name = rev...
[ "\n Resolve a revision to a new RevOptions object with the SHA1 of the\n branch, tag, or ref if found.\n\n Args:\n rev_options: a RevOptions object.\n " ]
Please provide a description of the function:def is_commit_id_equal(self, dest, name): if not name: # Then avoid an unnecessary subprocess call. return False return self.get_revision(dest) == name
[ "\n Return whether the current commit hash equals the given name.\n\n Args:\n dest: the repository directory.\n name: a string name.\n " ]
Please provide a description of the function:def get_remote_url(cls, location): # We need to pass 1 for extra_ok_returncodes since the command # exits with return code 1 if there are no matching lines. stdout = cls.run_command( ['config', '--get-regexp', r'remote\..*\.url'],...
[ "\n Return URL of the first remote encountered.\n\n Raises RemoteNotFoundError if the repository does not have a remote\n url configured.\n " ]
Please provide a description of the function:def _get_subdirectory(cls, location): # find the repo root git_dir = cls.run_command(['rev-parse', '--git-dir'], show_stdout=False, cwd=location).strip() if not os.path.isabs(git_dir): git_dir = o...
[ "Return the relative path of setup.py to the git repo root." ]
Please provide a description of the function:def get_url_rev_and_auth(self, url): if '://' not in url: assert 'file:' not in url url = url.replace('git+', 'git+ssh://') url, rev, user_pass = super(Git, self).get_url_rev_and_auth(url) url = url.replace('ss...
[ "\n Prefixes stub URLs like 'user@hostname:user/repo.git' with 'ssh://'.\n That's required because although they use SSH they sometimes don't\n work with a ssh:// scheme (e.g. GitHub). But we need a scheme for\n parsing. Hence we remove it again afterwards and return it as a stub.\n ...