Code stringlengths 103 85.9k | Summary listlengths 0 94 |
|---|---|
Please provide a description of the function:def _parse_local_version(local):
if local is not None:
return tuple(
part.lower() if not part.isdigit() else int(part)
for part in _local_version_separators.split(local)
) | [
"\n Takes a string like abc.1.twelve and turns it into (\"abc\", 1, \"twelve\").\n "
] |
Please provide a description of the function:def unicode_is_ascii(u_string):
assert isinstance(u_string, str)
try:
u_string.encode('ascii')
return True
except UnicodeEncodeError:
return False | [
"Determine if unicode string only contains ASCII characters.\n\n :param str u_string: unicode string to check. Must be unicode\n and not Python 2 `str`.\n :rtype: bool\n "
] |
Please provide a description of the function:def raise_option_error(parser, option, msg):
msg = '{} error: {}'.format(option, msg)
msg = textwrap.fill(' '.join(msg.split()))
parser.error(msg) | [
"\n Raise an option parsing error using parser.error().\n\n Args:\n parser: an OptionParser instance.\n option: an Option instance.\n msg: the error text.\n "
] |
Please provide a description of the function:def make_option_group(group, parser):
# type: (Dict[str, Any], ConfigOptionParser) -> OptionGroup
option_group = OptionGroup(parser, group['name'])
for option in group['options']:
option_group.add_option(option())
return option_group | [
"\n Return an OptionGroup object\n group -- assumed to be dict with 'name' and 'options' keys\n parser -- an optparse Parser\n "
] |
Please provide a description of the function:def check_install_build_global(options, check_options=None):
# type: (Values, Optional[Values]) -> None
if check_options is None:
check_options = options
def getname(n):
return getattr(check_options, n, None)
names = ["build_options", "g... | [
"Disable wheels if per-setup.py call options are set.\n\n :param options: The OptionParser options to update.\n :param check_options: The options to check, if not supplied defaults to\n options.\n "
] |
Please provide a description of the function:def check_dist_restriction(options, check_target=False):
# type: (Values, bool) -> None
dist_restriction_set = any([
options.python_version,
options.platform,
options.abi,
options.implementation,
])
binary_only = FormatCo... | [
"Function for determining if custom platform options are allowed.\n\n :param options: The OptionParser options.\n :param check_target: Whether or not to check if --target is being used.\n "
] |
Please provide a description of the function:def no_cache_dir_callback(option, opt, value, parser):
# The value argument will be None if --no-cache-dir is passed via the
# command-line, since the option doesn't accept arguments. However,
# the value can be non-None if the option is triggered e.g. by a... | [
"\n Process a value provided for the --no-cache-dir option.\n\n This is an optparse.Option callback for the --no-cache-dir option.\n "
] |
Please provide a description of the function:def no_use_pep517_callback(option, opt, value, parser):
# Since --no-use-pep517 doesn't accept arguments, the value argument
# will be None if --no-use-pep517 is passed via the command-line.
# However, the value can be non-None if the option is triggered e.g... | [
"\n Process a value provided for the --no-use-pep517 option.\n\n This is an optparse.Option callback for the no_use_pep517 option.\n ",
"A value was passed for --no-use-pep517,\n probably using either the PIP_NO_USE_PEP517 environment variable\n or the \"no-use-pep517\" config file option. ... |
Please provide a description of the function:def _merge_hash(option, opt_str, value, parser):
# type: (Option, str, str, OptionParser) -> None
if not parser.values.hashes:
parser.values.hashes = {} # type: ignore
try:
algo, digest = value.split(':', 1)
except ValueError:
pa... | [
"Given a value spelled \"algo:digest\", append the digest to a list\n pointed to in a dict by the algo name."
] |
Please provide a description of the function:def populate_source(cls, source):
# Only URL pararemter is mandatory, let the KeyError be thrown.
if "name" not in source:
source["name"] = get_url_name(source["url"])
if "verify_ssl" not in source:
source["verify_ssl"... | [
"Derive missing values of source from the existing fields."
] |
Please provide a description of the function:def get_pinned_version(ireq):
try:
specifier = ireq.specifier
except AttributeError:
raise TypeError("Expected InstallRequirement, not {}".format(
type(ireq).__name__,
))
if ireq.editable:
raise ValueError("Instal... | [
"Get the pinned version of an InstallRequirement.\n\n An InstallRequirement is considered pinned if:\n\n - Is not editable\n - It has exactly one specifier\n - That specifier is \"==\"\n - The version does not contain a wildcard\n\n Examples:\n django==1.8 # pinned\n django>1.8 ... |
Please provide a description of the function:def strip_extras(requirement):
line = requirement.as_line()
new = type(requirement).from_line(line)
new.extras = None
return new | [
"Returns a new requirement object with extras removed.\n "
] |
Please provide a description of the function:def _subst_vars(path, local_vars):
def _replacer(matchobj):
name = matchobj.group(1)
if name in local_vars:
return local_vars[name]
elif name in os.environ:
return os.environ[name]
return matchobj.group(0)
... | [
"In the string `path`, replace tokens like {some.thing} with the\n corresponding value from the map `local_vars`.\n\n If there is no corresponding value, leave the token unchanged.\n "
] |
Please provide a description of the function:def get_makefile_filename():
if _PYTHON_BUILD:
return os.path.join(_PROJECT_BASE, "Makefile")
if hasattr(sys, 'abiflags'):
config_dir_name = 'config-%s%s' % (_PY_VERSION_SHORT, sys.abiflags)
else:
config_dir_name = 'config'
return... | [
"Return the path of the Makefile."
] |
Please provide a description of the function:def _init_posix(vars):
# load the installed Makefile:
makefile = get_makefile_filename()
try:
_parse_makefile(makefile, vars)
except IOError as e:
msg = "invalid Python installation: unable to open %s" % makefile
if hasattr(e, "st... | [
"Initialize the module as appropriate for POSIX systems."
] |
Please provide a description of the function:def _init_non_posix(vars):
# set basic install directories
vars['LIBDEST'] = get_path('stdlib')
vars['BINLIBDEST'] = get_path('platstdlib')
vars['INCLUDEPY'] = get_path('include')
vars['SO'] = '.pyd'
vars['EXE'] = '.exe'
vars['VERSION'] = _PY... | [
"Initialize the module as appropriate for NT"
] |
Please provide a description of the function:def parse_config_h(fp, vars=None):
if vars is None:
vars = {}
define_rx = re.compile("#define ([A-Z][A-Za-z0-9_]+) (.*)\n")
undef_rx = re.compile("/[*] #undef ([A-Z][A-Za-z0-9_]+) [*]/\n")
while True:
line = fp.readline()
if not ... | [
"Parse a config.h-style file.\n\n A dictionary containing name/value pairs is returned. If an\n optional dictionary is passed in as the second argument, it is\n used instead of a new dictionary.\n "
] |
Please provide a description of the function:def get_config_h_filename():
if _PYTHON_BUILD:
if os.name == "nt":
inc_dir = os.path.join(_PROJECT_BASE, "PC")
else:
inc_dir = _PROJECT_BASE
else:
inc_dir = get_path('platinclude')
return os.path.join(inc_dir, ... | [
"Return the path of pyconfig.h."
] |
Please provide a description of the function:def get_paths(scheme=_get_default_scheme(), vars=None, expand=True):
_ensure_cfg_read()
if expand:
return _expand_vars(scheme, vars)
else:
return dict(_SCHEMES.items(scheme)) | [
"Return a mapping containing an install scheme.\n\n ``scheme`` is the install scheme name. If not provided, it will\n return the default scheme for the current platform.\n "
] |
Please provide a description of the function:def get_path(name, scheme=_get_default_scheme(), vars=None, expand=True):
return get_paths(scheme, vars, expand)[name] | [
"Return a path corresponding to the scheme.\n\n ``scheme`` is the install scheme name.\n "
] |
Please provide a description of the function:def _main():
print('Platform: "%s"' % get_platform())
print('Python version: "%s"' % get_python_version())
print('Current installation scheme: "%s"' % _get_default_scheme())
print()
_print_dict('Paths', get_paths())
print()
_print_dict('Varia... | [
"Display all information sysconfig detains."
] |
Please provide a description of the function:def inc(self, exception=None): # type: (Optional[ParseError.__class__]) -> bool
try:
self._idx, self._current = next(self._chars)
return True
except StopIteration:
self._idx = len(self)
self._current ... | [
"\n Increments the parser if the end of the input has not been reached.\n Returns whether or not it was able to advance.\n "
] |
Please provide a description of the function:def inc_n(self, n, exception=None): # type: (int, Exception) -> bool
for _ in range(n):
if not self.inc(exception=exception):
return False
return True | [
"\n Increments the parser by n characters\n if the end of the input has not been reached.\n "
] |
Please provide a description of the function:def consume(self, chars, min=0, max=-1):
while self.current in chars and max != 0:
min -= 1
max -= 1
if not self.inc():
break
# failed to consume minimum number of characters
if min > 0:
... | [
"\n Consume chars until min/max is satisfied is valid.\n "
] |
Please provide a description of the function:def parse_error(
self, exception=ParseError, *args
): # type: (ParseError.__class__, ...) -> ParseError
line, col = self._to_linecol()
return exception(line, col, *args) | [
"\n Creates a generic \"parse error\" at the current position.\n "
] |
Please provide a description of the function:def get_summaries(ordered=True):
if ordered:
cmditems = _sort_commands(commands_dict, commands_order)
else:
cmditems = commands_dict.items()
for name, command_class in cmditems:
yield (name, command_class.summary) | [
"Yields sorted (command name, command summary) tuples."
] |
Please provide a description of the function:def get_similar_commands(name):
from difflib import get_close_matches
name = name.lower()
close_commands = get_close_matches(name, commands_dict.keys())
if close_commands:
return close_commands[0]
else:
return False | [
"Command name auto-correct."
] |
Please provide a description of the function:def bind(self, environment):
rv = object.__new__(self.__class__)
rv.__dict__.update(self.__dict__)
rv.environment = environment
return rv | [
"Create a copy of this extension bound to another environment."
] |
Please provide a description of the function:def attr(self, name, lineno=None):
return nodes.ExtensionAttribute(self.identifier, name, lineno=lineno) | [
"Return an attribute node for the current extension. This is useful\n to pass constants on extensions to generated template code.\n\n ::\n\n self.attr('_my_attribute', lineno=lineno)\n "
] |
Please provide a description of the function:def call_method(self, name, args=None, kwargs=None, dyn_args=None,
dyn_kwargs=None, lineno=None):
if args is None:
args = []
if kwargs is None:
kwargs = []
return nodes.Call(self.attr(name, lineno=l... | [
"Call a method of the extension. This is a shortcut for\n :meth:`attr` + :class:`jinja2.nodes.Call`.\n "
] |
Please provide a description of the function:def parse(self, parser):
lineno = next(parser.stream).lineno
num_called_num = False
# find all the variables referenced. Additionally a variable can be
# defined in the body of the trans block too, but this is checked at
# a... | [
"Parse a translatable tag."
] |
Please provide a description of the function:def _parse_block(self, parser, allow_pluralize):
referenced = []
buf = []
while 1:
if parser.stream.current.type == 'data':
buf.append(parser.stream.current.value.replace('%', '%%'))
next(parser.str... | [
"Parse until the next block tag with a given name."
] |
Please provide a description of the function:def _make_node(self, singular, plural, variables, plural_expr,
vars_referenced, num_called_num):
# no variables referenced? no need to escape for old style
# gettext invocations only if there are vars.
if not vars_referenc... | [
"Generates a useful node from the data provided."
] |
Please provide a description of the function:def get_cli_string(path=None, action=None, key=None, value=None, quote=None):
command = ['dotenv']
if quote:
command.append('-q %s' % quote)
if path:
command.append('-f %s' % path)
if action:
command.append(action)
if key:... | [
"Returns a string suitable for running as a shell script.\n\n Useful for converting a arguments passed to a fabric task\n to be passed to a `local` or `run` command.\n "
] |
Please provide a description of the function:def merge_hooks(request_hooks, session_hooks, dict_class=OrderedDict):
if session_hooks is None or session_hooks.get('response') == []:
return request_hooks
if request_hooks is None or request_hooks.get('response') == []:
return session_hooks
... | [
"Properly merges both requests and session hooks.\n\n This is necessary because when request_hooks == {'response': []}, the\n merge breaks Session hooks entirely.\n "
] |
Please provide a description of the function:def get_redirect_target(self, resp):
# Due to the nature of how requests processes redirects this method will
# be called at least once upon the original response and at least twice
# on each subsequent redirect response (if any).
# I... | [
"Receives a Response. Returns a redirect URI or ``None``"
] |
Please provide a description of the function:def should_strip_auth(self, old_url, new_url):
old_parsed = urlparse(old_url)
new_parsed = urlparse(new_url)
if old_parsed.hostname != new_parsed.hostname:
return True
# Special case: allow http -> https redirect when usin... | [
"Decide whether Authorization header should be removed when redirecting"
] |
Please provide a description of the function:def rebuild_auth(self, prepared_request, response):
headers = prepared_request.headers
url = prepared_request.url
if 'Authorization' in headers and self.should_strip_auth(response.request.url, url):
# If we get redirected to a ne... | [
"When being redirected we may want to strip authentication from the\n request to avoid leaking credentials. This method intelligently removes\n and reapplies authentication where possible to avoid credential loss.\n "
] |
Please provide a description of the function:def rebuild_proxies(self, prepared_request, proxies):
proxies = proxies if proxies is not None else {}
headers = prepared_request.headers
url = prepared_request.url
scheme = urlparse(url).scheme
new_proxies = proxies.copy()
... | [
"This method re-evaluates the proxy configuration by considering the\n environment variables. If we are redirected to a URL covered by\n NO_PROXY, we strip the proxy configuration. Otherwise, we set missing\n proxy keys for this URL (in case they were stripped by a previous\n redirect).\... |
Please provide a description of the function:def prepare_request(self, request):
cookies = request.cookies or {}
# Bootstrap CookieJar.
if not isinstance(cookies, cookielib.CookieJar):
cookies = cookiejar_from_dict(cookies)
# Merge with session cookies
merg... | [
"Constructs a :class:`PreparedRequest <PreparedRequest>` for\n transmission and returns it. The :class:`PreparedRequest` has settings\n merged from the :class:`Request <Request>` instance and those of the\n :class:`Session`.\n\n :param request: :class:`Request` instance to prepare with t... |
Please provide a description of the function:def request(self, method, url,
params=None, data=None, headers=None, cookies=None, files=None,
auth=None, timeout=None, allow_redirects=True, proxies=None,
hooks=None, stream=None, verify=None, cert=None, json=None):
# Cre... | [
"Constructs a :class:`Request <Request>`, prepares it and sends it.\n Returns :class:`Response <Response>` object.\n\n :param method: method for the new :class:`Request` object.\n :param url: URL for the new :class:`Request` object.\n :param params: (optional) Dictionary or bytes to be s... |
Please provide a description of the function:def get(self, url, **kwargs):
r
kwargs.setdefault('allow_redirects', True)
return self.request('GET', url, **kwargs) | [
"Sends a GET request. Returns :class:`Response` object.\n\n :param url: URL for the new :class:`Request` object.\n :param \\*\\*kwargs: Optional arguments that ``request`` takes.\n :rtype: requests.Response\n "
] |
Please provide a description of the function:def options(self, url, **kwargs):
r
kwargs.setdefault('allow_redirects', True)
return self.request('OPTIONS', url, **kwargs) | [
"Sends a OPTIONS request. Returns :class:`Response` object.\n\n :param url: URL for the new :class:`Request` object.\n :param \\*\\*kwargs: Optional arguments that ``request`` takes.\n :rtype: requests.Response\n "
] |
Please provide a description of the function:def head(self, url, **kwargs):
r
kwargs.setdefault('allow_redirects', False)
return self.request('HEAD', url, **kwargs) | [
"Sends a HEAD request. Returns :class:`Response` object.\n\n :param url: URL for the new :class:`Request` object.\n :param \\*\\*kwargs: Optional arguments that ``request`` takes.\n :rtype: requests.Response\n "
] |
Please provide a description of the function:def send(self, request, **kwargs):
# Set defaults that the hooks can utilize to ensure they always have
# the correct parameters to reproduce the previous request.
kwargs.setdefault('stream', self.stream)
kwargs.setdefault('verify', s... | [
"Send a given PreparedRequest.\n\n :rtype: requests.Response\n "
] |
Please provide a description of the function:def merge_environment_settings(self, url, proxies, stream, verify, cert):
# Gather clues from the surrounding environment.
if self.trust_env:
# Set environment's proxies.
no_proxy = proxies.get('no_proxy') if proxies is not No... | [
"\n Check the environment and merge it with some settings.\n\n :rtype: dict\n "
] |
Please provide a description of the function:def get_adapter(self, url):
for (prefix, adapter) in self.adapters.items():
if url.lower().startswith(prefix.lower()):
return adapter
# Nothing matches :-/
raise InvalidSchema("No connection adapters were found f... | [
"\n Returns the appropriate connection adapter for the given URL.\n\n :rtype: requests.adapters.BaseAdapter\n "
] |
Please provide a description of the function:def mount(self, prefix, adapter):
self.adapters[prefix] = adapter
keys_to_move = [k for k in self.adapters if len(k) < len(prefix)]
for key in keys_to_move:
self.adapters[key] = self.adapters.pop(key) | [
"Registers a connection adapter to a prefix.\n\n Adapters are sorted in descending order by prefix length.\n "
] |
Please provide a description of the function:def console_to_str(data):
# type: (bytes) -> Text
# First, get the encoding we assume. This is the preferred
# encoding for the locale, unless that is not found, or
# it is ASCII, in which case assume UTF-8
encoding = locale.getpreferredencoding()
... | [
"Return a string, safe for output, of subprocess output.\n\n We assume the data is in the locale preferred encoding.\n If it won't decode properly, we warn the user but decode as\n best we can.\n\n We also ensure that the output can be safely written to\n standard output without encoding errors.\n ... |
Please provide a description of the function:def get_path_uid(path):
# type: (str) -> int
if hasattr(os, 'O_NOFOLLOW'):
fd = os.open(path, os.O_RDONLY | os.O_NOFOLLOW)
file_uid = os.fstat(fd).st_uid
os.close(fd)
else: # AIX and Jython
# WARNING: time of check vulnerabil... | [
"\n Return path's uid.\n\n Does not follow symlinks:\n https://github.com/pypa/pip/pull/935#discussion_r5307003\n\n Placed this function in compat due to differences on AIX and\n Jython, that should eventually go away.\n\n :raises OSError: When path is a symlink or can't be read.\n "
] |
Please provide a description of the function:def expanduser(path):
# type: (str) -> str
expanded = os.path.expanduser(path)
if path.startswith('~/') and expanded.startswith('//'):
expanded = expanded[1:]
return expanded | [
"\n Expand ~ and ~user constructions.\n\n Includes a workaround for https://bugs.python.org/issue14768\n "
] |
Please provide a description of the function:def samefile(file1, file2):
# type: (str, str) -> bool
if hasattr(os.path, 'samefile'):
return os.path.samefile(file1, file2)
else:
path1 = os.path.normcase(os.path.abspath(file1))
path2 = os.path.normcase(os.path.abspath(file2))
... | [
"Provide an alternative for os.path.samefile on Windows/Python2"
] |
Please provide a description of the function:def ensure_least_updates_possible(self):
constraints = self.get_constraints()
can_use_original = True
can_use_updated = True
satisfied_by_versions = set()
for constraint in constraints:
if not constraint.specifier.... | [
"\n Mutate the current entry to ensure that we are making the smallest amount of\n changes possible to the existing lockfile -- this will keep the old locked\n versions of packages if they satisfy new constraints.\n\n :return: None\n "
] |
Please provide a description of the function:def get_constraints(self):
constraints = {
c for c in self.resolver.parsed_constraints
if c and c.name == self.entry.name
}
pipfile_constraint = self.get_pipfile_constraint()
if pipfile_constraint:
... | [
"\n Retrieve all of the relevant constraints, aggregated from the pipfile, resolver,\n and parent dependencies and their respective conflict resolution where possible.\n\n :return: A set of **InstallRequirement** instances representing constraints\n :rtype: Set\n "
] |
Please provide a description of the function:def constraint_from_parent_conflicts(self):
# ensure that we satisfy the parent dependencies of this dep
from pipenv.vendor.packaging.specifiers import Specifier
parent_dependencies = set()
has_mismatch = False
can_use_origina... | [
"\n Given a resolved entry with multiple parent dependencies with different\n constraints, searches for the resolution that satisfies all of the parent\n constraints.\n\n :return: A new **InstallRequirement** satisfying all parent constraints\n :raises: :exc:`~pipenv.exceptions.De... |
Please provide a description of the function:def validate_constraints(self):
constraints = self.get_constraints()
for constraint in constraints:
try:
constraint.check_if_exists(False)
except Exception:
from pipenv.exceptions import Depende... | [
"\n Retrieves the full set of available constraints and iterate over them, validating\n that they exist and that they are not causing unresolvable conflicts.\n\n :return: True if the constraints are satisfied by the resolution provided\n :raises: :exc:`pipenv.exceptions.DependencyConflic... |
Please provide a description of the function:def inject_into_urllib3():
util.ssl_.SSLContext = SecureTransportContext
util.HAS_SNI = HAS_SNI
util.ssl_.HAS_SNI = HAS_SNI
util.IS_SECURETRANSPORT = True
util.ssl_.IS_SECURETRANSPORT = True | [
"\n Monkey-patch urllib3 with SecureTransport-backed SSL-support.\n "
] |
Please provide a description of the function:def extract_from_urllib3():
util.ssl_.SSLContext = orig_util_SSLContext
util.HAS_SNI = orig_util_HAS_SNI
util.ssl_.HAS_SNI = orig_util_HAS_SNI
util.IS_SECURETRANSPORT = False
util.ssl_.IS_SECURETRANSPORT = False | [
"\n Undo monkey-patching by :func:`inject_into_urllib3`.\n "
] |
Please provide a description of the function:def _read_callback(connection_id, data_buffer, data_length_pointer):
wrapped_socket = None
try:
wrapped_socket = _connection_refs.get(connection_id)
if wrapped_socket is None:
return SecurityConst.errSSLInternal
base_socket = ... | [
"\n SecureTransport read callback. This is called by ST to request that data\n be returned from the socket.\n "
] |
Please provide a description of the function:def _write_callback(connection_id, data_buffer, data_length_pointer):
wrapped_socket = None
try:
wrapped_socket = _connection_refs.get(connection_id)
if wrapped_socket is None:
return SecurityConst.errSSLInternal
base_socket =... | [
"\n SecureTransport write callback. This is called by ST to request that data\n actually be sent on the network.\n "
] |
Please provide a description of the function:def _raise_on_error(self):
self._exception = None
# We explicitly don't catch around this yield because in the unlikely
# event that an exception was hit in the block we don't want to swallow
# it.
yield
if self._exce... | [
"\n A context manager that can be used to wrap calls that do I/O from\n SecureTransport. If any of the I/O callbacks hit an exception, this\n context manager will correctly propagate the exception after the fact.\n This avoids silently swallowing those exceptions.\n\n It also corr... |
Please provide a description of the function:def _set_ciphers(self):
ciphers = (Security.SSLCipherSuite * len(CIPHER_SUITES))(*CIPHER_SUITES)
result = Security.SSLSetEnabledCiphers(
self.context, ciphers, len(CIPHER_SUITES)
)
_assert_no_error(result) | [
"\n Sets up the allowed ciphers. By default this matches the set in\n util.ssl_.DEFAULT_CIPHERS, at least as supported by macOS. This is done\n custom and doesn't allow changing at this time, mostly because parsing\n OpenSSL cipher strings is going to be a freaking nightmare.\n "
... |
Please provide a description of the function:def _custom_validate(self, verify, trust_bundle):
# If we disabled cert validation, just say: cool.
if not verify:
return
# We want data in memory, so load it up.
if os.path.isfile(trust_bundle):
with open(tru... | [
"\n Called when we have set custom validation. We do this in two cases:\n first, when cert validation is entirely disabled; and second, when\n using a custom trust DB.\n "
] |
Please provide a description of the function:def handshake(self,
server_hostname,
verify,
trust_bundle,
min_version,
max_version,
client_cert,
client_key,
client_key_passphrase... | [
"\n Actually performs the TLS handshake. This is run automatically by\n wrapped socket, and shouldn't be needed in user code.\n "
] |
Please provide a description of the function:def write_bytecode(self, f):
if self.code is None:
raise TypeError('can\'t write empty bucket')
f.write(bc_magic)
pickle.dump(self.checksum, f, 2)
marshal_dump(self.code, f) | [
"Dump the bytecode into the file or file like object passed."
] |
Please provide a description of the function:def get_cache_key(self, name, filename=None):
hash = sha1(name.encode('utf-8'))
if filename is not None:
filename = '|' + filename
if isinstance(filename, text_type):
filename = filename.encode('utf-8')
... | [
"Returns the unique hash key for this template name."
] |
Please provide a description of the function:def get_bucket(self, environment, name, filename, source):
key = self.get_cache_key(name, filename)
checksum = self.get_source_checksum(source)
bucket = Bucket(environment, key, checksum)
self.load_bytecode(bucket)
return buck... | [
"Return a cache bucket for the given template. All arguments are\n mandatory but filename may be `None`.\n "
] |
Please provide a description of the function:def lookup(label):
# Only strip ASCII whitespace: U+0009, U+000A, U+000C, U+000D, and U+0020.
label = ascii_lower(label.strip('\t\n\f\r '))
name = LABELS.get(label)
if name is None:
return None
encoding = CACHE.get(name)
if encoding is No... | [
"\n Look for an encoding by its label.\n This is the spec’s `get an encoding\n <http://encoding.spec.whatwg.org/#concept-encoding-get>`_ algorithm.\n Supported labels are listed there.\n\n :param label: A string.\n :returns:\n An :class:`Encoding` object, or :obj:`None` for an unknown label... |
Please provide a description of the function:def _get_encoding(encoding_or_label):
if hasattr(encoding_or_label, 'codec_info'):
return encoding_or_label
encoding = lookup(encoding_or_label)
if encoding is None:
raise LookupError('Unknown encoding label: %r' % encoding_or_label)
ret... | [
"\n Accept either an encoding object or label.\n\n :param encoding: An :class:`Encoding` object or a label string.\n :returns: An :class:`Encoding` object.\n :raises: :exc:`~exceptions.LookupError` for an unknown label.\n\n "
] |
Please provide a description of the function:def decode(input, fallback_encoding, errors='replace'):
# Fail early if `encoding` is an invalid label.
fallback_encoding = _get_encoding(fallback_encoding)
bom_encoding, input = _detect_bom(input)
encoding = bom_encoding or fallback_encoding
return ... | [
"\n Decode a single string.\n\n :param input: A byte string\n :param fallback_encoding:\n An :class:`Encoding` object or a label string.\n The encoding to use if :obj:`input` does note have a BOM.\n :param errors: Type of error handling. See :func:`codecs.register`.\n :raises: :exc:`~ex... |
Please provide a description of the function:def _detect_bom(input):
if input.startswith(b'\xFF\xFE'):
return _UTF16LE, input[2:]
if input.startswith(b'\xFE\xFF'):
return _UTF16BE, input[2:]
if input.startswith(b'\xEF\xBB\xBF'):
return UTF8, input[3:]
return None, input | [
"Return (bom_encoding, input), with any BOM removed from the input."
] |
Please provide a description of the function:def encode(input, encoding=UTF8, errors='strict'):
return _get_encoding(encoding).codec_info.encode(input, errors)[0] | [
"\n Encode a single string.\n\n :param input: An Unicode string.\n :param encoding: An :class:`Encoding` object or a label string.\n :param errors: Type of error handling. See :func:`codecs.register`.\n :raises: :exc:`~exceptions.LookupError` for an unknown encoding label.\n :return: A byte string... |
Please provide a description of the function:def iter_decode(input, fallback_encoding, errors='replace'):
decoder = IncrementalDecoder(fallback_encoding, errors)
generator = _iter_decode_generator(input, decoder)
encoding = next(generator)
return generator, encoding | [
"\n \"Pull\"-based decoder.\n\n :param input:\n An iterable of byte strings.\n\n The input is first consumed just enough to determine the encoding\n based on the precense of a BOM,\n then consumed on demand when the return value is.\n :param fallback_encoding:\n An :class... |
Please provide a description of the function:def _iter_decode_generator(input, decoder):
decode = decoder.decode
input = iter(input)
for chunck in input:
output = decode(chunck)
if output:
assert decoder.encoding is not None
yield decoder.encoding
yie... | [
"Return a generator that first yields the :obj:`Encoding`,\n then yields output chukns as Unicode strings.\n\n "
] |
Please provide a description of the function:def iter_encode(input, encoding=UTF8, errors='strict'):
# Fail early if `encoding` is an invalid label.
encode = IncrementalEncoder(encoding, errors).encode
return _iter_encode_generator(input, encode) | [
"\n “Pull”-based encoder.\n\n :param input: An iterable of Unicode strings.\n :param encoding: An :class:`Encoding` object or a label string.\n :param errors: Type of error handling. See :func:`codecs.register`.\n :raises: :exc:`~exceptions.LookupError` for an unknown encoding label.\n :returns: A... |
Please provide a description of the function:def decode(self, input, final=False):
decoder = self._decoder
if decoder is not None:
return decoder(input, final)
input = self._buffer + input
encoding, input = _detect_bom(input)
if encoding is None:
... | [
"Decode one chunk of the input.\n\n :param input: A byte string.\n :param final:\n Indicate that no more input is available.\n Must be :obj:`True` if this is the last call.\n :returns: An Unicode string.\n\n "
] |
Please provide a description of the function:def _cf_dictionary_from_tuples(tuples):
dictionary_size = len(tuples)
# We need to get the dictionary keys and values out in the same order.
keys = (t[0] for t in tuples)
values = (t[1] for t in tuples)
cf_keys = (CoreFoundation.CFTypeRef * dictiona... | [
"\n Given a list of Python tuples, create an associated CFDictionary.\n "
] |
Please provide a description of the function:def _cf_string_to_unicode(value):
value_as_void_p = ctypes.cast(value, ctypes.POINTER(ctypes.c_void_p))
string = CoreFoundation.CFStringGetCStringPtr(
value_as_void_p,
CFConst.kCFStringEncodingUTF8
)
if string is None:
buffer = c... | [
"\n Creates a Unicode string from a CFString object. Used entirely for error\n reporting.\n\n Yes, it annoys me quite a lot that this function is this complex.\n "
] |
Please provide a description of the function:def _assert_no_error(error, exception_class=None):
if error == 0:
return
cf_error_string = Security.SecCopyErrorMessageString(error, None)
output = _cf_string_to_unicode(cf_error_string)
CoreFoundation.CFRelease(cf_error_string)
if output i... | [
"\n Checks the return code and throws an exception if there is an error to\n report\n "
] |
Please provide a description of the function:def _cert_array_from_pem(pem_bundle):
# Normalize the PEM bundle's line endings.
pem_bundle = pem_bundle.replace(b"\r\n", b"\n")
der_certs = [
base64.b64decode(match.group(1))
for match in _PEM_CERTS_RE.finditer(pem_bundle)
]
if not ... | [
"\n Given a bundle of certs in PEM format, turns them into a CFArray of certs\n that can be used to validate a cert chain.\n "
] |
Please provide a description of the function:def _temporary_keychain():
# Unfortunately, SecKeychainCreate requires a path to a keychain. This
# means we cannot use mkstemp to use a generic temporary file. Instead,
# we're going to create a temporary directory and a filename to use there.
# This fi... | [
"\n This function creates a temporary Mac keychain that we can use to work with\n credentials. This keychain uses a one-time password and a temporary file to\n store the data. We expect to have one keychain per socket. The returned\n SecKeychainRef must be freed by the caller, including calling\n Sec... |
Please provide a description of the function:def _load_items_from_file(keychain, path):
certificates = []
identities = []
result_array = None
with open(path, 'rb') as f:
raw_filedata = f.read()
try:
filedata = CoreFoundation.CFDataCreate(
CoreFoundation.kCFAllocato... | [
"\n Given a single file, loads all the trust objects from it into arrays and\n the keychain.\n Returns a tuple of lists: the first list is a list of identities, the\n second a list of certs.\n "
] |
Please provide a description of the function:def _load_client_cert_chain(keychain, *paths):
# Ok, the strategy.
#
# This relies on knowing that macOS will not give you a SecIdentityRef
# unless you have imported a key into a keychain. This is a somewhat
# artificial limitation of macOS (for exa... | [
"\n Load certificates and maybe keys from a number of files. Has the end goal\n of returning a CFArray containing one SecIdentityRef, and then zero or more\n SecCertificateRef objects, suitable for use as a client certificate trust\n chain.\n "
] |
Please provide a description of the function:def get_redirect_location(self):
if self.status in self.REDIRECT_STATUSES:
return self.headers.get('location')
return False | [
"\n Should we redirect and where to?\n\n :returns: Truthy redirect location string if we got a redirect status\n code and valid location. ``None`` if redirect status and no\n location. ``False`` if not a redirect status code.\n "
] |
Please provide a description of the function:def _init_length(self, request_method):
length = self.headers.get('content-length')
if length is not None:
if self.chunked:
# This Response will fail with an IncompleteRead if it can't be
# received as chu... | [
"\n Set initial length value for Response content if available.\n "
] |
Please provide a description of the function:def _init_decoder(self):
# Note: content-encoding value should be case-insensitive, per RFC 7230
# Section 3.2
content_encoding = self.headers.get('content-encoding', '').lower()
if self._decoder is None:
if content_encodi... | [
"\n Set-up the _decoder attribute if necessary.\n "
] |
Please provide a description of the function:def _flush_decoder(self):
if self._decoder:
buf = self._decoder.decompress(b'')
return buf + self._decoder.flush()
return b'' | [
"\n Flushes the decoder. Should only be called if the decoder is actually\n being used.\n "
] |
Please provide a description of the function:def _error_catcher(self):
clean_exit = False
try:
try:
yield
except SocketTimeout:
# FIXME: Ideally we'd like to include the url in the ReadTimeoutError but
# there is yet no c... | [
"\n Catch low-level python exceptions, instead re-raising urllib3\n variants, so that low-level exceptions are not leaked in the\n high-level api.\n\n On exit, release the connection back to the pool.\n "
] |
Please provide a description of the function:def read(self, amt=None, decode_content=None, cache_content=False):
self._init_decoder()
if decode_content is None:
decode_content = self.decode_content
if self._fp is None:
return
flush_decoder = False
... | [
"\n Similar to :meth:`httplib.HTTPResponse.read`, but with two additional\n parameters: ``decode_content`` and ``cache_content``.\n\n :param amt:\n How much of the content to read. If specified, caching is skipped\n because it doesn't make sense to cache partial content as... |
Please provide a description of the function:def from_httplib(ResponseCls, r, **response_kw):
headers = r.msg
if not isinstance(headers, HTTPHeaderDict):
if PY3: # Python 3
headers = HTTPHeaderDict(headers.items())
else: # Python 2
head... | [
"\n Given an :class:`httplib.HTTPResponse` instance ``r``, return a\n corresponding :class:`urllib3.response.HTTPResponse` object.\n\n Remaining parameters are passed to the HTTPResponse constructor, along\n with ``original_response=r``.\n "
] |
Please provide a description of the function:def read_chunked(self, amt=None, decode_content=None):
self._init_decoder()
# FIXME: Rewrite this method and make it a class with a better structured logic.
if not self.chunked:
raise ResponseNotChunked(
"Response ... | [
"\n Similar to :meth:`HTTPResponse.read`, but with an additional\n parameter: ``decode_content``.\n\n :param amt:\n How much of the content to read. If specified, caching is skipped\n because it doesn't make sense to cache partial content as the full\n response.... |
Please provide a description of the function:def geturl(self):
if self.retries is not None and len(self.retries.history):
return self.retries.history[-1].redirect_location
else:
return self._request_url | [
"\n Returns the URL that was the source of this response.\n If the request that generated this response redirected, this method\n will return the final redirect location.\n "
] |
Please provide a description of the function:def ok(self, text=u"OK", err=False):
# Do not display spin text for ok state
self._text = None
_text = to_text(text) if text else u"OK"
err = err or not self.write_to_stdout
self._freeze(_text, err=err) | [
"Set Ok (success) finalizer to a spinner."
] |
Please provide a description of the function:def fail(self, text=u"FAIL", err=False):
# Do not display spin text for fail state
self._text = None
_text = text if text else u"FAIL"
err = err or not self.write_to_stdout
self._freeze(_text, err=err) | [
"Set fail finalizer to a spinner."
] |
Please provide a description of the function:def write_err(self, text):
stderr = self.stderr
if self.stderr.closed:
stderr = sys.stderr
stderr.write(decode_output(u"\r", target_stream=stderr))
stderr.write(decode_output(CLEAR_LINE, target_stream=stderr))
if t... | [
"Write error text in the terminal without breaking the spinner."
] |
Please provide a description of the function:def _freeze(self, final_text, err=False):
if not final_text:
final_text = ""
target = self.stderr if err else self.stdout
if target.closed:
target = sys.stderr if err else sys.stdout
text = to_text(final_text)
... | [
"Stop spinner, compose last frame and 'freeze' it."
] |
Please provide a description of the function:def describe_token_expr(expr):
if ':' in expr:
type, value = expr.split(':', 1)
if type == 'name':
return value
else:
type = expr
return _describe_token_type(type) | [
"Like `describe_token` but for token expressions."
] |
Please provide a description of the function:def get_lexer(environment):
key = (environment.block_start_string,
environment.block_end_string,
environment.variable_start_string,
environment.variable_end_string,
environment.comment_start_string,
environment.... | [
"Return a lexer which is probably cached."
] |
Please provide a description of the function:def tokenize(self, source, name=None, filename=None, state=None):
stream = self.tokeniter(source, name, filename, state)
return TokenStream(self.wrap(stream, name, filename), name, filename) | [
"Calls tokeniter + tokenize and wraps it in a token stream.\n "
] |
Please provide a description of the function:def wrap(self, stream, name=None, filename=None):
for lineno, token, value in stream:
if token in ignored_tokens:
continue
elif token == 'linestatement_begin':
token = 'block_begin'
elif tok... | [
"This is called with the stream as returned by `tokenize` and wraps\n every token in a :class:`Token` and converts the value.\n "
] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.