partition
stringclasses
3 values
func_name
stringlengths
1
134
docstring
stringlengths
1
46.9k
path
stringlengths
4
223
original_string
stringlengths
75
104k
code
stringlengths
75
104k
docstring_tokens
listlengths
1
1.97k
repo
stringlengths
7
55
language
stringclasses
1 value
url
stringlengths
87
315
code_tokens
listlengths
19
28.4k
sha
stringlengths
40
40
train
create_connection
Connect to *address* and return the socket object. Convenience function. Connect to *address* (a 2-tuple ``(host, port)``) and return the socket object. Passing the optional *timeout* parameter will set the timeout on the socket instance before attempting to connect. If no *timeout* is supplied, the global default timeout setting returned by :func:`getdefaulttimeout` is used. If *source_address* is set it must be a tuple of (host, port) for the socket to bind as a source address before making the connection. An host of '' or port 0 tells the OS to use the default.
pipenv/vendor/urllib3/util/connection.py
def create_connection(address, timeout=socket._GLOBAL_DEFAULT_TIMEOUT, source_address=None, socket_options=None): """Connect to *address* and return the socket object. Convenience function. Connect to *address* (a 2-tuple ``(host, port)``) and return the socket object. Passing the optional *timeout* parameter will set the timeout on the socket instance before attempting to connect. If no *timeout* is supplied, the global default timeout setting returned by :func:`getdefaulttimeout` is used. If *source_address* is set it must be a tuple of (host, port) for the socket to bind as a source address before making the connection. An host of '' or port 0 tells the OS to use the default. """ host, port = address if host.startswith('['): host = host.strip('[]') err = None # Using the value from allowed_gai_family() in the context of getaddrinfo lets # us select whether to work with IPv4 DNS records, IPv6 records, or both. # The original create_connection function always returns all records. family = allowed_gai_family() for res in socket.getaddrinfo(host, port, family, socket.SOCK_STREAM): af, socktype, proto, canonname, sa = res sock = None try: sock = socket.socket(af, socktype, proto) # If provided, set socket level options before connecting. _set_socket_options(sock, socket_options) if timeout is not socket._GLOBAL_DEFAULT_TIMEOUT: sock.settimeout(timeout) if source_address: sock.bind(source_address) sock.connect(sa) return sock except socket.error as e: err = e if sock is not None: sock.close() sock = None if err is not None: raise err raise socket.error("getaddrinfo returns an empty list")
def create_connection(address, timeout=socket._GLOBAL_DEFAULT_TIMEOUT, source_address=None, socket_options=None): """Connect to *address* and return the socket object. Convenience function. Connect to *address* (a 2-tuple ``(host, port)``) and return the socket object. Passing the optional *timeout* parameter will set the timeout on the socket instance before attempting to connect. If no *timeout* is supplied, the global default timeout setting returned by :func:`getdefaulttimeout` is used. If *source_address* is set it must be a tuple of (host, port) for the socket to bind as a source address before making the connection. An host of '' or port 0 tells the OS to use the default. """ host, port = address if host.startswith('['): host = host.strip('[]') err = None # Using the value from allowed_gai_family() in the context of getaddrinfo lets # us select whether to work with IPv4 DNS records, IPv6 records, or both. # The original create_connection function always returns all records. family = allowed_gai_family() for res in socket.getaddrinfo(host, port, family, socket.SOCK_STREAM): af, socktype, proto, canonname, sa = res sock = None try: sock = socket.socket(af, socktype, proto) # If provided, set socket level options before connecting. _set_socket_options(sock, socket_options) if timeout is not socket._GLOBAL_DEFAULT_TIMEOUT: sock.settimeout(timeout) if source_address: sock.bind(source_address) sock.connect(sa) return sock except socket.error as e: err = e if sock is not None: sock.close() sock = None if err is not None: raise err raise socket.error("getaddrinfo returns an empty list")
[ "Connect", "to", "*", "address", "*", "and", "return", "the", "socket", "object", "." ]
pypa/pipenv
python
https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/vendor/urllib3/util/connection.py#L33-L82
[ "def", "create_connection", "(", "address", ",", "timeout", "=", "socket", ".", "_GLOBAL_DEFAULT_TIMEOUT", ",", "source_address", "=", "None", ",", "socket_options", "=", "None", ")", ":", "host", ",", "port", "=", "address", "if", "host", ".", "startswith", ...
cae8d76c210b9777e90aab76e9c4b0e53bb19cde
train
_has_ipv6
Returns True if the system can bind an IPv6 address.
pipenv/vendor/urllib3/util/connection.py
def _has_ipv6(host): """ Returns True if the system can bind an IPv6 address. """ sock = None has_ipv6 = False # App Engine doesn't support IPV6 sockets and actually has a quota on the # number of sockets that can be used, so just early out here instead of # creating a socket needlessly. # See https://github.com/urllib3/urllib3/issues/1446 if _appengine_environ.is_appengine_sandbox(): return False if socket.has_ipv6: # has_ipv6 returns true if cPython was compiled with IPv6 support. # It does not tell us if the system has IPv6 support enabled. To # determine that we must bind to an IPv6 address. # https://github.com/shazow/urllib3/pull/611 # https://bugs.python.org/issue658327 try: sock = socket.socket(socket.AF_INET6) sock.bind((host, 0)) has_ipv6 = True except Exception: pass if sock: sock.close() return has_ipv6
def _has_ipv6(host): """ Returns True if the system can bind an IPv6 address. """ sock = None has_ipv6 = False # App Engine doesn't support IPV6 sockets and actually has a quota on the # number of sockets that can be used, so just early out here instead of # creating a socket needlessly. # See https://github.com/urllib3/urllib3/issues/1446 if _appengine_environ.is_appengine_sandbox(): return False if socket.has_ipv6: # has_ipv6 returns true if cPython was compiled with IPv6 support. # It does not tell us if the system has IPv6 support enabled. To # determine that we must bind to an IPv6 address. # https://github.com/shazow/urllib3/pull/611 # https://bugs.python.org/issue658327 try: sock = socket.socket(socket.AF_INET6) sock.bind((host, 0)) has_ipv6 = True except Exception: pass if sock: sock.close() return has_ipv6
[ "Returns", "True", "if", "the", "system", "can", "bind", "an", "IPv6", "address", "." ]
pypa/pipenv
python
https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/vendor/urllib3/util/connection.py#L104-L131
[ "def", "_has_ipv6", "(", "host", ")", ":", "sock", "=", "None", "has_ipv6", "=", "False", "# App Engine doesn't support IPV6 sockets and actually has a quota on the", "# number of sockets that can be used, so just early out here instead of", "# creating a socket needlessly.", "# See ht...
cae8d76c210b9777e90aab76e9c4b0e53bb19cde
train
_parse_local_version
Takes a string like abc.1.twelve and turns it into ("abc", 1, "twelve").
pipenv/vendor/packaging/version.py
def _parse_local_version(local): """ Takes a string like abc.1.twelve and turns it into ("abc", 1, "twelve"). """ if local is not None: return tuple( part.lower() if not part.isdigit() else int(part) for part in _local_version_separators.split(local) )
def _parse_local_version(local): """ Takes a string like abc.1.twelve and turns it into ("abc", 1, "twelve"). """ if local is not None: return tuple( part.lower() if not part.isdigit() else int(part) for part in _local_version_separators.split(local) )
[ "Takes", "a", "string", "like", "abc", ".", "1", ".", "twelve", "and", "turns", "it", "into", "(", "abc", "1", "twelve", ")", "." ]
pypa/pipenv
python
https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/vendor/packaging/version.py#L367-L375
[ "def", "_parse_local_version", "(", "local", ")", ":", "if", "local", "is", "not", "None", ":", "return", "tuple", "(", "part", ".", "lower", "(", ")", "if", "not", "part", ".", "isdigit", "(", ")", "else", "int", "(", "part", ")", "for", "part", "...
cae8d76c210b9777e90aab76e9c4b0e53bb19cde
train
unicode_is_ascii
Determine if unicode string only contains ASCII characters. :param str u_string: unicode string to check. Must be unicode and not Python 2 `str`. :rtype: bool
pipenv/vendor/requests/_internal_utils.py
def unicode_is_ascii(u_string): """Determine if unicode string only contains ASCII characters. :param str u_string: unicode string to check. Must be unicode and not Python 2 `str`. :rtype: bool """ assert isinstance(u_string, str) try: u_string.encode('ascii') return True except UnicodeEncodeError: return False
def unicode_is_ascii(u_string): """Determine if unicode string only contains ASCII characters. :param str u_string: unicode string to check. Must be unicode and not Python 2 `str`. :rtype: bool """ assert isinstance(u_string, str) try: u_string.encode('ascii') return True except UnicodeEncodeError: return False
[ "Determine", "if", "unicode", "string", "only", "contains", "ASCII", "characters", "." ]
pypa/pipenv
python
https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/vendor/requests/_internal_utils.py#L30-L42
[ "def", "unicode_is_ascii", "(", "u_string", ")", ":", "assert", "isinstance", "(", "u_string", ",", "str", ")", "try", ":", "u_string", ".", "encode", "(", "'ascii'", ")", "return", "True", "except", "UnicodeEncodeError", ":", "return", "False" ]
cae8d76c210b9777e90aab76e9c4b0e53bb19cde
train
raise_option_error
Raise an option parsing error using parser.error(). Args: parser: an OptionParser instance. option: an Option instance. msg: the error text.
pipenv/patched/notpip/_internal/cli/cmdoptions.py
def raise_option_error(parser, option, msg): """ Raise an option parsing error using parser.error(). Args: parser: an OptionParser instance. option: an Option instance. msg: the error text. """ msg = '{} error: {}'.format(option, msg) msg = textwrap.fill(' '.join(msg.split())) parser.error(msg)
def raise_option_error(parser, option, msg): """ Raise an option parsing error using parser.error(). Args: parser: an OptionParser instance. option: an Option instance. msg: the error text. """ msg = '{} error: {}'.format(option, msg) msg = textwrap.fill(' '.join(msg.split())) parser.error(msg)
[ "Raise", "an", "option", "parsing", "error", "using", "parser", ".", "error", "()", "." ]
pypa/pipenv
python
https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/patched/notpip/_internal/cli/cmdoptions.py#L32-L43
[ "def", "raise_option_error", "(", "parser", ",", "option", ",", "msg", ")", ":", "msg", "=", "'{} error: {}'", ".", "format", "(", "option", ",", "msg", ")", "msg", "=", "textwrap", ".", "fill", "(", "' '", ".", "join", "(", "msg", ".", "split", "(",...
cae8d76c210b9777e90aab76e9c4b0e53bb19cde
train
make_option_group
Return an OptionGroup object group -- assumed to be dict with 'name' and 'options' keys parser -- an optparse Parser
pipenv/patched/notpip/_internal/cli/cmdoptions.py
def make_option_group(group, parser): # type: (Dict[str, Any], ConfigOptionParser) -> OptionGroup """ Return an OptionGroup object group -- assumed to be dict with 'name' and 'options' keys parser -- an optparse Parser """ option_group = OptionGroup(parser, group['name']) for option in group['options']: option_group.add_option(option()) return option_group
def make_option_group(group, parser): # type: (Dict[str, Any], ConfigOptionParser) -> OptionGroup """ Return an OptionGroup object group -- assumed to be dict with 'name' and 'options' keys parser -- an optparse Parser """ option_group = OptionGroup(parser, group['name']) for option in group['options']: option_group.add_option(option()) return option_group
[ "Return", "an", "OptionGroup", "object", "group", "--", "assumed", "to", "be", "dict", "with", "name", "and", "options", "keys", "parser", "--", "an", "optparse", "Parser" ]
pypa/pipenv
python
https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/patched/notpip/_internal/cli/cmdoptions.py#L46-L56
[ "def", "make_option_group", "(", "group", ",", "parser", ")", ":", "# type: (Dict[str, Any], ConfigOptionParser) -> OptionGroup", "option_group", "=", "OptionGroup", "(", "parser", ",", "group", "[", "'name'", "]", ")", "for", "option", "in", "group", "[", "'options...
cae8d76c210b9777e90aab76e9c4b0e53bb19cde
train
check_install_build_global
Disable wheels if per-setup.py call options are set. :param options: The OptionParser options to update. :param check_options: The options to check, if not supplied defaults to options.
pipenv/patched/notpip/_internal/cli/cmdoptions.py
def check_install_build_global(options, check_options=None): # type: (Values, Optional[Values]) -> None """Disable wheels if per-setup.py call options are set. :param options: The OptionParser options to update. :param check_options: The options to check, if not supplied defaults to options. """ if check_options is None: check_options = options def getname(n): return getattr(check_options, n, None) names = ["build_options", "global_options", "install_options"] if any(map(getname, names)): control = options.format_control control.disallow_binaries() warnings.warn( 'Disabling all use of wheels due to the use of --build-options ' '/ --global-options / --install-options.', stacklevel=2, )
def check_install_build_global(options, check_options=None): # type: (Values, Optional[Values]) -> None """Disable wheels if per-setup.py call options are set. :param options: The OptionParser options to update. :param check_options: The options to check, if not supplied defaults to options. """ if check_options is None: check_options = options def getname(n): return getattr(check_options, n, None) names = ["build_options", "global_options", "install_options"] if any(map(getname, names)): control = options.format_control control.disallow_binaries() warnings.warn( 'Disabling all use of wheels due to the use of --build-options ' '/ --global-options / --install-options.', stacklevel=2, )
[ "Disable", "wheels", "if", "per", "-", "setup", ".", "py", "call", "options", "are", "set", "." ]
pypa/pipenv
python
https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/patched/notpip/_internal/cli/cmdoptions.py#L59-L79
[ "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",...
cae8d76c210b9777e90aab76e9c4b0e53bb19cde
train
check_dist_restriction
Function for determining if custom platform options are allowed. :param options: The OptionParser options. :param check_target: Whether or not to check if --target is being used.
pipenv/patched/notpip/_internal/cli/cmdoptions.py
def check_dist_restriction(options, check_target=False): # type: (Values, bool) -> None """Function for determining if custom platform options are allowed. :param options: The OptionParser options. :param check_target: Whether or not to check if --target is being used. """ dist_restriction_set = any([ options.python_version, options.platform, options.abi, options.implementation, ]) binary_only = FormatControl(set(), {':all:'}) sdist_dependencies_allowed = ( options.format_control != binary_only and not options.ignore_dependencies ) # Installations or downloads using dist restrictions must not combine # source distributions and dist-specific wheels, as they are not # gauranteed to be locally compatible. if dist_restriction_set and sdist_dependencies_allowed: raise CommandError( "When restricting platform and interpreter constraints using " "--python-version, --platform, --abi, or --implementation, " "either --no-deps must be set, or --only-binary=:all: must be " "set and --no-binary must not be set (or must be set to " ":none:)." ) if check_target: if dist_restriction_set and not options.target_dir: raise CommandError( "Can not use any platform or abi specific options unless " "installing via '--target'" )
def check_dist_restriction(options, check_target=False): # type: (Values, bool) -> None """Function for determining if custom platform options are allowed. :param options: The OptionParser options. :param check_target: Whether or not to check if --target is being used. """ dist_restriction_set = any([ options.python_version, options.platform, options.abi, options.implementation, ]) binary_only = FormatControl(set(), {':all:'}) sdist_dependencies_allowed = ( options.format_control != binary_only and not options.ignore_dependencies ) # Installations or downloads using dist restrictions must not combine # source distributions and dist-specific wheels, as they are not # gauranteed to be locally compatible. if dist_restriction_set and sdist_dependencies_allowed: raise CommandError( "When restricting platform and interpreter constraints using " "--python-version, --platform, --abi, or --implementation, " "either --no-deps must be set, or --only-binary=:all: must be " "set and --no-binary must not be set (or must be set to " ":none:)." ) if check_target: if dist_restriction_set and not options.target_dir: raise CommandError( "Can not use any platform or abi specific options unless " "installing via '--target'" )
[ "Function", "for", "determining", "if", "custom", "platform", "options", "are", "allowed", "." ]
pypa/pipenv
python
https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/patched/notpip/_internal/cli/cmdoptions.py#L82-L119
[ "def", "check_dist_restriction", "(", "options", ",", "check_target", "=", "False", ")", ":", "# type: (Values, bool) -> None", "dist_restriction_set", "=", "any", "(", "[", "options", ".", "python_version", ",", "options", ".", "platform", ",", "options", ".", "a...
cae8d76c210b9777e90aab76e9c4b0e53bb19cde
train
no_cache_dir_callback
Process a value provided for the --no-cache-dir option. This is an optparse.Option callback for the --no-cache-dir option.
pipenv/patched/notpip/_internal/cli/cmdoptions.py
def no_cache_dir_callback(option, opt, value, parser): """ Process a value provided for the --no-cache-dir option. This is an optparse.Option callback for the --no-cache-dir option. """ # 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 an # environment variable, like PIP_NO_CACHE_DIR=true. if value is not None: # Then parse the string value to get argument error-checking. try: strtobool(value) except ValueError as exc: raise_option_error(parser, option=option, msg=str(exc)) # Originally, setting PIP_NO_CACHE_DIR to a value that strtobool() # converted to 0 (like "false" or "no") caused cache_dir to be disabled # rather than enabled (logic would say the latter). Thus, we disable # the cache directory not just on values that parse to True, but (for # backwards compatibility reasons) also on values that parse to False. # In other words, always set it to False if the option is provided in # some (valid) form. parser.values.cache_dir = False
def no_cache_dir_callback(option, opt, value, parser): """ Process a value provided for the --no-cache-dir option. This is an optparse.Option callback for the --no-cache-dir option. """ # 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 an # environment variable, like PIP_NO_CACHE_DIR=true. if value is not None: # Then parse the string value to get argument error-checking. try: strtobool(value) except ValueError as exc: raise_option_error(parser, option=option, msg=str(exc)) # Originally, setting PIP_NO_CACHE_DIR to a value that strtobool() # converted to 0 (like "false" or "no") caused cache_dir to be disabled # rather than enabled (logic would say the latter). Thus, we disable # the cache directory not just on values that parse to True, but (for # backwards compatibility reasons) also on values that parse to False. # In other words, always set it to False if the option is provided in # some (valid) form. parser.values.cache_dir = False
[ "Process", "a", "value", "provided", "for", "the", "--", "no", "-", "cache", "-", "dir", "option", "." ]
pypa/pipenv
python
https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/patched/notpip/_internal/cli/cmdoptions.py#L546-L570
[ "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...
cae8d76c210b9777e90aab76e9c4b0e53bb19cde
train
no_use_pep517_callback
Process a value provided for the --no-use-pep517 option. This is an optparse.Option callback for the no_use_pep517 option.
pipenv/patched/notpip/_internal/cli/cmdoptions.py
def no_use_pep517_callback(option, opt, value, parser): """ Process a value provided for the --no-use-pep517 option. This is an optparse.Option callback for the no_use_pep517 option. """ # 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. # by an environment variable, for example "PIP_NO_USE_PEP517=true". if value is not None: msg = """A value was passed for --no-use-pep517, probably using either the PIP_NO_USE_PEP517 environment variable or the "no-use-pep517" config file option. Use an appropriate value of the PIP_USE_PEP517 environment variable or the "use-pep517" config file option instead. """ raise_option_error(parser, option=option, msg=msg) # Otherwise, --no-use-pep517 was passed via the command-line. parser.values.use_pep517 = False
def no_use_pep517_callback(option, opt, value, parser): """ Process a value provided for the --no-use-pep517 option. This is an optparse.Option callback for the no_use_pep517 option. """ # 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. # by an environment variable, for example "PIP_NO_USE_PEP517=true". if value is not None: msg = """A value was passed for --no-use-pep517, probably using either the PIP_NO_USE_PEP517 environment variable or the "no-use-pep517" config file option. Use an appropriate value of the PIP_USE_PEP517 environment variable or the "use-pep517" config file option instead. """ raise_option_error(parser, option=option, msg=msg) # Otherwise, --no-use-pep517 was passed via the command-line. parser.values.use_pep517 = False
[ "Process", "a", "value", "provided", "for", "the", "--", "no", "-", "use", "-", "pep517", "option", "." ]
pypa/pipenv
python
https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/patched/notpip/_internal/cli/cmdoptions.py#L623-L643
[ "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 opt...
cae8d76c210b9777e90aab76e9c4b0e53bb19cde
train
_merge_hash
Given a value spelled "algo:digest", append the digest to a list pointed to in a dict by the algo name.
pipenv/patched/notpip/_internal/cli/cmdoptions.py
def _merge_hash(option, opt_str, value, parser): # type: (Option, str, str, OptionParser) -> None """Given a value spelled "algo:digest", append the digest to a list pointed to in a dict by the algo name.""" if not parser.values.hashes: parser.values.hashes = {} # type: ignore try: algo, digest = value.split(':', 1) except ValueError: parser.error('Arguments to %s must be a hash name ' 'followed by a value, like --hash=sha256:abcde...' % opt_str) if algo not in STRONG_HASHES: parser.error('Allowed hash algorithms for %s are %s.' % (opt_str, ', '.join(STRONG_HASHES))) parser.values.hashes.setdefault(algo, []).append(digest)
def _merge_hash(option, opt_str, value, parser): # type: (Option, str, str, OptionParser) -> None """Given a value spelled "algo:digest", append the digest to a list pointed to in a dict by the algo name.""" if not parser.values.hashes: parser.values.hashes = {} # type: ignore try: algo, digest = value.split(':', 1) except ValueError: parser.error('Arguments to %s must be a hash name ' 'followed by a value, like --hash=sha256:abcde...' % opt_str) if algo not in STRONG_HASHES: parser.error('Allowed hash algorithms for %s are %s.' % (opt_str, ', '.join(STRONG_HASHES))) parser.values.hashes.setdefault(algo, []).append(digest)
[ "Given", "a", "value", "spelled", "algo", ":", "digest", "append", "the", "digest", "to", "a", "list", "pointed", "to", "in", "a", "dict", "by", "the", "algo", "name", "." ]
pypa/pipenv
python
https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/patched/notpip/_internal/cli/cmdoptions.py#L727-L742
[ "def", "_merge_hash", "(", "option", ",", "opt_str", ",", "value", ",", "parser", ")", ":", "# type: (Option, str, str, OptionParser) -> None", "if", "not", "parser", ".", "values", ".", "hashes", ":", "parser", ".", "values", ".", "hashes", "=", "{", "}", "...
cae8d76c210b9777e90aab76e9c4b0e53bb19cde
train
PipfileLoader.populate_source
Derive missing values of source from the existing fields.
pipenv/vendor/requirementslib/models/pipfile.py
def populate_source(cls, source): """Derive missing values of source from the existing fields.""" # 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"] = "https://" in source["url"] if not isinstance(source["verify_ssl"], bool): source["verify_ssl"] = source["verify_ssl"].lower() == "true" return source
def populate_source(cls, source): """Derive missing values of source from the existing fields.""" # 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"] = "https://" in source["url"] if not isinstance(source["verify_ssl"], bool): source["verify_ssl"] = source["verify_ssl"].lower() == "true" return source
[ "Derive", "missing", "values", "of", "source", "from", "the", "existing", "fields", "." ]
pypa/pipenv
python
https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/vendor/requirementslib/models/pipfile.py#L111-L120
[ "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\"", "]", ...
cae8d76c210b9777e90aab76e9c4b0e53bb19cde
train
get_pinned_version
Get the pinned version of an InstallRequirement. An InstallRequirement is considered pinned if: - Is not editable - It has exactly one specifier - That specifier is "==" - The version does not contain a wildcard Examples: django==1.8 # pinned django>1.8 # NOT pinned django~=1.8 # NOT pinned django==1.* # NOT pinned Raises `TypeError` if the input is not a valid InstallRequirement, or `ValueError` if the InstallRequirement is not pinned.
pipenv/vendor/passa/internals/utils.py
def get_pinned_version(ireq): """Get the pinned version of an InstallRequirement. An InstallRequirement is considered pinned if: - Is not editable - It has exactly one specifier - That specifier is "==" - The version does not contain a wildcard Examples: django==1.8 # pinned django>1.8 # NOT pinned django~=1.8 # NOT pinned django==1.* # NOT pinned Raises `TypeError` if the input is not a valid InstallRequirement, or `ValueError` if the InstallRequirement is not pinned. """ try: specifier = ireq.specifier except AttributeError: raise TypeError("Expected InstallRequirement, not {}".format( type(ireq).__name__, )) if ireq.editable: raise ValueError("InstallRequirement is editable") if not specifier: raise ValueError("InstallRequirement has no version specification") if len(specifier._specs) != 1: raise ValueError("InstallRequirement has multiple specifications") op, version = next(iter(specifier._specs))._spec if op not in ('==', '===') or version.endswith('.*'): raise ValueError("InstallRequirement not pinned (is {0!r})".format( op + version, )) return version
def get_pinned_version(ireq): """Get the pinned version of an InstallRequirement. An InstallRequirement is considered pinned if: - Is not editable - It has exactly one specifier - That specifier is "==" - The version does not contain a wildcard Examples: django==1.8 # pinned django>1.8 # NOT pinned django~=1.8 # NOT pinned django==1.* # NOT pinned Raises `TypeError` if the input is not a valid InstallRequirement, or `ValueError` if the InstallRequirement is not pinned. """ try: specifier = ireq.specifier except AttributeError: raise TypeError("Expected InstallRequirement, not {}".format( type(ireq).__name__, )) if ireq.editable: raise ValueError("InstallRequirement is editable") if not specifier: raise ValueError("InstallRequirement has no version specification") if len(specifier._specs) != 1: raise ValueError("InstallRequirement has multiple specifications") op, version = next(iter(specifier._specs))._spec if op not in ('==', '===') or version.endswith('.*'): raise ValueError("InstallRequirement not pinned (is {0!r})".format( op + version, )) return version
[ "Get", "the", "pinned", "version", "of", "an", "InstallRequirement", "." ]
pypa/pipenv
python
https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/vendor/passa/internals/utils.py#L20-L59
[ "def", "get_pinned_version", "(", "ireq", ")", ":", "try", ":", "specifier", "=", "ireq", ".", "specifier", "except", "AttributeError", ":", "raise", "TypeError", "(", "\"Expected InstallRequirement, not {}\"", ".", "format", "(", "type", "(", "ireq", ")", ".", ...
cae8d76c210b9777e90aab76e9c4b0e53bb19cde
train
strip_extras
Returns a new requirement object with extras removed.
pipenv/vendor/passa/internals/utils.py
def strip_extras(requirement): """Returns a new requirement object with extras removed. """ line = requirement.as_line() new = type(requirement).from_line(line) new.extras = None return new
def strip_extras(requirement): """Returns a new requirement object with extras removed. """ line = requirement.as_line() new = type(requirement).from_line(line) new.extras = None return new
[ "Returns", "a", "new", "requirement", "object", "with", "extras", "removed", "." ]
pypa/pipenv
python
https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/vendor/passa/internals/utils.py#L112-L118
[ "def", "strip_extras", "(", "requirement", ")", ":", "line", "=", "requirement", ".", "as_line", "(", ")", "new", "=", "type", "(", "requirement", ")", ".", "from_line", "(", "line", ")", "new", ".", "extras", "=", "None", "return", "new" ]
cae8d76c210b9777e90aab76e9c4b0e53bb19cde
train
_subst_vars
In the string `path`, replace tokens like {some.thing} with the corresponding value from the map `local_vars`. If there is no corresponding value, leave the token unchanged.
pipenv/vendor/distlib/_backport/sysconfig.py
def _subst_vars(path, local_vars): """In the string `path`, replace tokens like {some.thing} with the corresponding value from the map `local_vars`. If there is no corresponding value, leave the token unchanged. """ 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) return _VAR_REPL.sub(_replacer, path)
def _subst_vars(path, local_vars): """In the string `path`, replace tokens like {some.thing} with the corresponding value from the map `local_vars`. If there is no corresponding value, leave the token unchanged. """ 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) return _VAR_REPL.sub(_replacer, path)
[ "In", "the", "string", "path", "replace", "tokens", "like", "{", "some", ".", "thing", "}", "with", "the", "corresponding", "value", "from", "the", "map", "local_vars", "." ]
pypa/pipenv
python
https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/vendor/distlib/_backport/sysconfig.py#L133-L146
[ "def", "_subst_vars", "(", "path", ",", "local_vars", ")", ":", "def", "_replacer", "(", "matchobj", ")", ":", "name", "=", "matchobj", ".", "group", "(", "1", ")", "if", "name", "in", "local_vars", ":", "return", "local_vars", "[", "name", "]", "elif"...
cae8d76c210b9777e90aab76e9c4b0e53bb19cde
train
get_makefile_filename
Return the path of the Makefile.
pipenv/vendor/distlib/_backport/sysconfig.py
def get_makefile_filename(): """Return the path of the Makefile.""" 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 os.path.join(get_path('stdlib'), config_dir_name, 'Makefile')
def get_makefile_filename(): """Return the path of the Makefile.""" 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 os.path.join(get_path('stdlib'), config_dir_name, 'Makefile')
[ "Return", "the", "path", "of", "the", "Makefile", "." ]
pypa/pipenv
python
https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/vendor/distlib/_backport/sysconfig.py#L333-L341
[ "def", "get_makefile_filename", "(", ")", ":", "if", "_PYTHON_BUILD", ":", "return", "os", ".", "path", ".", "join", "(", "_PROJECT_BASE", ",", "\"Makefile\"", ")", "if", "hasattr", "(", "sys", ",", "'abiflags'", ")", ":", "config_dir_name", "=", "'config-%s...
cae8d76c210b9777e90aab76e9c4b0e53bb19cde
train
_init_posix
Initialize the module as appropriate for POSIX systems.
pipenv/vendor/distlib/_backport/sysconfig.py
def _init_posix(vars): """Initialize the module as appropriate for POSIX systems.""" # 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, "strerror"): msg = msg + " (%s)" % e.strerror raise IOError(msg) # load the installed pyconfig.h: config_h = get_config_h_filename() try: with open(config_h) as f: parse_config_h(f, vars) except IOError as e: msg = "invalid Python installation: unable to open %s" % config_h if hasattr(e, "strerror"): msg = msg + " (%s)" % e.strerror raise IOError(msg) # On AIX, there are wrong paths to the linker scripts in the Makefile # -- these paths are relative to the Python source, but when installed # the scripts are in another directory. if _PYTHON_BUILD: vars['LDSHARED'] = vars['BLDSHARED']
def _init_posix(vars): """Initialize the module as appropriate for POSIX systems.""" # 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, "strerror"): msg = msg + " (%s)" % e.strerror raise IOError(msg) # load the installed pyconfig.h: config_h = get_config_h_filename() try: with open(config_h) as f: parse_config_h(f, vars) except IOError as e: msg = "invalid Python installation: unable to open %s" % config_h if hasattr(e, "strerror"): msg = msg + " (%s)" % e.strerror raise IOError(msg) # On AIX, there are wrong paths to the linker scripts in the Makefile # -- these paths are relative to the Python source, but when installed # the scripts are in another directory. if _PYTHON_BUILD: vars['LDSHARED'] = vars['BLDSHARED']
[ "Initialize", "the", "module", "as", "appropriate", "for", "POSIX", "systems", "." ]
pypa/pipenv
python
https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/vendor/distlib/_backport/sysconfig.py#L344-L369
[ "def", "_init_posix", "(", "vars", ")", ":", "# load the installed Makefile:", "makefile", "=", "get_makefile_filename", "(", ")", "try", ":", "_parse_makefile", "(", "makefile", ",", "vars", ")", "except", "IOError", "as", "e", ":", "msg", "=", "\"invalid Pytho...
cae8d76c210b9777e90aab76e9c4b0e53bb19cde
train
_init_non_posix
Initialize the module as appropriate for NT
pipenv/vendor/distlib/_backport/sysconfig.py
def _init_non_posix(vars): """Initialize the module as appropriate for NT""" # 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_VERSION_SHORT_NO_DOT vars['BINDIR'] = os.path.dirname(_safe_realpath(sys.executable))
def _init_non_posix(vars): """Initialize the module as appropriate for NT""" # 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_VERSION_SHORT_NO_DOT vars['BINDIR'] = os.path.dirname(_safe_realpath(sys.executable))
[ "Initialize", "the", "module", "as", "appropriate", "for", "NT" ]
pypa/pipenv
python
https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/vendor/distlib/_backport/sysconfig.py#L372-L381
[ "def", "_init_non_posix", "(", "vars", ")", ":", "# set basic install directories", "vars", "[", "'LIBDEST'", "]", "=", "get_path", "(", "'stdlib'", ")", "vars", "[", "'BINLIBDEST'", "]", "=", "get_path", "(", "'platstdlib'", ")", "vars", "[", "'INCLUDEPY'", "...
cae8d76c210b9777e90aab76e9c4b0e53bb19cde
train
parse_config_h
Parse a config.h-style file. A dictionary containing name/value pairs is returned. If an optional dictionary is passed in as the second argument, it is used instead of a new dictionary.
pipenv/vendor/distlib/_backport/sysconfig.py
def parse_config_h(fp, vars=None): """Parse a config.h-style file. A dictionary containing name/value pairs is returned. If an optional dictionary is passed in as the second argument, it is used instead of a new dictionary. """ 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 line: break m = define_rx.match(line) if m: n, v = m.group(1, 2) try: v = int(v) except ValueError: pass vars[n] = v else: m = undef_rx.match(line) if m: vars[m.group(1)] = 0 return vars
def parse_config_h(fp, vars=None): """Parse a config.h-style file. A dictionary containing name/value pairs is returned. If an optional dictionary is passed in as the second argument, it is used instead of a new dictionary. """ 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 line: break m = define_rx.match(line) if m: n, v = m.group(1, 2) try: v = int(v) except ValueError: pass vars[n] = v else: m = undef_rx.match(line) if m: vars[m.group(1)] = 0 return vars
[ "Parse", "a", "config", ".", "h", "-", "style", "file", "." ]
pypa/pipenv
python
https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/vendor/distlib/_backport/sysconfig.py#L388-L416
[ "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", ".", "com...
cae8d76c210b9777e90aab76e9c4b0e53bb19cde
train
get_config_h_filename
Return the path of pyconfig.h.
pipenv/vendor/distlib/_backport/sysconfig.py
def get_config_h_filename(): """Return the path of pyconfig.h.""" 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, 'pyconfig.h')
def get_config_h_filename(): """Return the path of pyconfig.h.""" 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, 'pyconfig.h')
[ "Return", "the", "path", "of", "pyconfig", ".", "h", "." ]
pypa/pipenv
python
https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/vendor/distlib/_backport/sysconfig.py#L419-L428
[ "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...
cae8d76c210b9777e90aab76e9c4b0e53bb19cde
train
get_paths
Return a mapping containing an install scheme. ``scheme`` is the install scheme name. If not provided, it will return the default scheme for the current platform.
pipenv/vendor/distlib/_backport/sysconfig.py
def get_paths(scheme=_get_default_scheme(), vars=None, expand=True): """Return a mapping containing an install scheme. ``scheme`` is the install scheme name. If not provided, it will return the default scheme for the current platform. """ _ensure_cfg_read() if expand: return _expand_vars(scheme, vars) else: return dict(_SCHEMES.items(scheme))
def get_paths(scheme=_get_default_scheme(), vars=None, expand=True): """Return a mapping containing an install scheme. ``scheme`` is the install scheme name. If not provided, it will return the default scheme for the current platform. """ _ensure_cfg_read() if expand: return _expand_vars(scheme, vars) else: return dict(_SCHEMES.items(scheme))
[ "Return", "a", "mapping", "containing", "an", "install", "scheme", "." ]
pypa/pipenv
python
https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/vendor/distlib/_backport/sysconfig.py#L442-L452
[ "def", "get_paths", "(", "scheme", "=", "_get_default_scheme", "(", ")", ",", "vars", "=", "None", ",", "expand", "=", "True", ")", ":", "_ensure_cfg_read", "(", ")", "if", "expand", ":", "return", "_expand_vars", "(", "scheme", ",", "vars", ")", "else",...
cae8d76c210b9777e90aab76e9c4b0e53bb19cde
train
get_path
Return a path corresponding to the scheme. ``scheme`` is the install scheme name.
pipenv/vendor/distlib/_backport/sysconfig.py
def get_path(name, scheme=_get_default_scheme(), vars=None, expand=True): """Return a path corresponding to the scheme. ``scheme`` is the install scheme name. """ return get_paths(scheme, vars, expand)[name]
def get_path(name, scheme=_get_default_scheme(), vars=None, expand=True): """Return a path corresponding to the scheme. ``scheme`` is the install scheme name. """ return get_paths(scheme, vars, expand)[name]
[ "Return", "a", "path", "corresponding", "to", "the", "scheme", "." ]
pypa/pipenv
python
https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/vendor/distlib/_backport/sysconfig.py#L455-L460
[ "def", "get_path", "(", "name", ",", "scheme", "=", "_get_default_scheme", "(", ")", ",", "vars", "=", "None", ",", "expand", "=", "True", ")", ":", "return", "get_paths", "(", "scheme", ",", "vars", ",", "expand", ")", "[", "name", "]" ]
cae8d76c210b9777e90aab76e9c4b0e53bb19cde
train
_main
Display all information sysconfig detains.
pipenv/vendor/distlib/_backport/sysconfig.py
def _main(): """Display all information sysconfig detains.""" 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('Variables', get_config_vars())
def _main(): """Display all information sysconfig detains.""" 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('Variables', get_config_vars())
[ "Display", "all", "information", "sysconfig", "detains", "." ]
pypa/pipenv
python
https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/vendor/distlib/_backport/sysconfig.py#L776-L784
[ "def", "_main", "(", ")", ":", "print", "(", "'Platform: \"%s\"'", "%", "get_platform", "(", ")", ")", "print", "(", "'Python version: \"%s\"'", "%", "get_python_version", "(", ")", ")", "print", "(", "'Current installation scheme: \"%s\"'", "%", "_get_default_schem...
cae8d76c210b9777e90aab76e9c4b0e53bb19cde
train
Source.inc
Increments the parser if the end of the input has not been reached. Returns whether or not it was able to advance.
pipenv/vendor/tomlkit/source.py
def inc(self, exception=None): # type: (Optional[ParseError.__class__]) -> bool """ Increments the parser if the end of the input has not been reached. Returns whether or not it was able to advance. """ try: self._idx, self._current = next(self._chars) return True except StopIteration: self._idx = len(self) self._current = self.EOF if exception: raise self.parse_error(exception) return False
def inc(self, exception=None): # type: (Optional[ParseError.__class__]) -> bool """ Increments the parser if the end of the input has not been reached. Returns whether or not it was able to advance. """ try: self._idx, self._current = next(self._chars) return True except StopIteration: self._idx = len(self) self._current = self.EOF if exception: raise self.parse_error(exception) return False
[ "Increments", "the", "parser", "if", "the", "end", "of", "the", "input", "has", "not", "been", "reached", ".", "Returns", "whether", "or", "not", "it", "was", "able", "to", "advance", "." ]
pypa/pipenv
python
https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/vendor/tomlkit/source.py#L117-L132
[ "def", "inc", "(", "self", ",", "exception", "=", "None", ")", ":", "# type: (Optional[ParseError.__class__]) -> bool", "try", ":", "self", ".", "_idx", ",", "self", ".", "_current", "=", "next", "(", "self", ".", "_chars", ")", "return", "True", "except", ...
cae8d76c210b9777e90aab76e9c4b0e53bb19cde
train
Source.inc_n
Increments the parser by n characters if the end of the input has not been reached.
pipenv/vendor/tomlkit/source.py
def inc_n(self, n, exception=None): # type: (int, Exception) -> bool """ Increments the parser by n characters if the end of the input has not been reached. """ for _ in range(n): if not self.inc(exception=exception): return False return True
def inc_n(self, n, exception=None): # type: (int, Exception) -> bool """ Increments the parser by n characters if the end of the input has not been reached. """ for _ in range(n): if not self.inc(exception=exception): return False return True
[ "Increments", "the", "parser", "by", "n", "characters", "if", "the", "end", "of", "the", "input", "has", "not", "been", "reached", "." ]
pypa/pipenv
python
https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/vendor/tomlkit/source.py#L134-L143
[ "def", "inc_n", "(", "self", ",", "n", ",", "exception", "=", "None", ")", ":", "# type: (int, Exception) -> bool", "for", "_", "in", "range", "(", "n", ")", ":", "if", "not", "self", ".", "inc", "(", "exception", "=", "exception", ")", ":", "return", ...
cae8d76c210b9777e90aab76e9c4b0e53bb19cde
train
Source.consume
Consume chars until min/max is satisfied is valid.
pipenv/vendor/tomlkit/source.py
def consume(self, chars, min=0, max=-1): """ Consume chars until min/max is satisfied is valid. """ 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: self.parse_error(UnexpectedCharError)
def consume(self, chars, min=0, max=-1): """ Consume chars until min/max is satisfied is valid. """ 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: self.parse_error(UnexpectedCharError)
[ "Consume", "chars", "until", "min", "/", "max", "is", "satisfied", "is", "valid", "." ]
pypa/pipenv
python
https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/vendor/tomlkit/source.py#L145-L157
[ "def", "consume", "(", "self", ",", "chars", ",", "min", "=", "0", ",", "max", "=", "-", "1", ")", ":", "while", "self", ".", "current", "in", "chars", "and", "max", "!=", "0", ":", "min", "-=", "1", "max", "-=", "1", "if", "not", "self", "."...
cae8d76c210b9777e90aab76e9c4b0e53bb19cde
train
Source.parse_error
Creates a generic "parse error" at the current position.
pipenv/vendor/tomlkit/source.py
def parse_error( self, exception=ParseError, *args ): # type: (ParseError.__class__, ...) -> ParseError """ Creates a generic "parse error" at the current position. """ line, col = self._to_linecol() return exception(line, col, *args)
def parse_error( self, exception=ParseError, *args ): # type: (ParseError.__class__, ...) -> ParseError """ Creates a generic "parse error" at the current position. """ line, col = self._to_linecol() return exception(line, col, *args)
[ "Creates", "a", "generic", "parse", "error", "at", "the", "current", "position", "." ]
pypa/pipenv
python
https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/vendor/tomlkit/source.py#L171-L179
[ "def", "parse_error", "(", "self", ",", "exception", "=", "ParseError", ",", "*", "args", ")", ":", "# type: (ParseError.__class__, ...) -> ParseError", "line", ",", "col", "=", "self", ".", "_to_linecol", "(", ")", "return", "exception", "(", "line", ",", "co...
cae8d76c210b9777e90aab76e9c4b0e53bb19cde
train
get_summaries
Yields sorted (command name, command summary) tuples.
pipenv/patched/notpip/_internal/commands/__init__.py
def get_summaries(ordered=True): """Yields sorted (command name, command summary) tuples.""" 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)
def get_summaries(ordered=True): """Yields sorted (command name, command summary) tuples.""" 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", "." ]
pypa/pipenv
python
https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/patched/notpip/_internal/commands/__init__.py#L45-L54
[ "def", "get_summaries", "(", "ordered", "=", "True", ")", ":", "if", "ordered", ":", "cmditems", "=", "_sort_commands", "(", "commands_dict", ",", "commands_order", ")", "else", ":", "cmditems", "=", "commands_dict", ".", "items", "(", ")", "for", "name", ...
cae8d76c210b9777e90aab76e9c4b0e53bb19cde
train
get_similar_commands
Command name auto-correct.
pipenv/patched/notpip/_internal/commands/__init__.py
def get_similar_commands(name): """Command name auto-correct.""" 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
def get_similar_commands(name): """Command name auto-correct.""" 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", "." ]
pypa/pipenv
python
https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/patched/notpip/_internal/commands/__init__.py#L57-L68
[ "def", "get_similar_commands", "(", "name", ")", ":", "from", "difflib", "import", "get_close_matches", "name", "=", "name", ".", "lower", "(", ")", "close_commands", "=", "get_close_matches", "(", "name", ",", "commands_dict", ".", "keys", "(", ")", ")", "i...
cae8d76c210b9777e90aab76e9c4b0e53bb19cde
train
Extension.bind
Create a copy of this extension bound to another environment.
pipenv/vendor/jinja2/ext.py
def bind(self, environment): """Create a copy of this extension bound to another environment.""" rv = object.__new__(self.__class__) rv.__dict__.update(self.__dict__) rv.environment = environment return rv
def bind(self, environment): """Create a copy of this extension bound to another 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", "." ]
pypa/pipenv
python
https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/vendor/jinja2/ext.py#L75-L80
[ "def", "bind", "(", "self", ",", "environment", ")", ":", "rv", "=", "object", ".", "__new__", "(", "self", ".", "__class__", ")", "rv", ".", "__dict__", ".", "update", "(", "self", ".", "__dict__", ")", "rv", ".", "environment", "=", "environment", ...
cae8d76c210b9777e90aab76e9c4b0e53bb19cde
train
Extension.attr
Return an attribute node for the current extension. This is useful to pass constants on extensions to generated template code. :: self.attr('_my_attribute', lineno=lineno)
pipenv/vendor/jinja2/ext.py
def attr(self, name, lineno=None): """Return an attribute node for the current extension. This is useful to pass constants on extensions to generated template code. :: self.attr('_my_attribute', lineno=lineno) """ return nodes.ExtensionAttribute(self.identifier, name, lineno=lineno)
def attr(self, name, lineno=None): """Return an attribute node for the current extension. This is useful to pass constants on extensions to generated template code. :: self.attr('_my_attribute', lineno=lineno) """ return nodes.ExtensionAttribute(self.identifier, name, lineno=lineno)
[ "Return", "an", "attribute", "node", "for", "the", "current", "extension", ".", "This", "is", "useful", "to", "pass", "constants", "on", "extensions", "to", "generated", "template", "code", "." ]
pypa/pipenv
python
https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/vendor/jinja2/ext.py#L109-L117
[ "def", "attr", "(", "self", ",", "name", ",", "lineno", "=", "None", ")", ":", "return", "nodes", ".", "ExtensionAttribute", "(", "self", ".", "identifier", ",", "name", ",", "lineno", "=", "lineno", ")" ]
cae8d76c210b9777e90aab76e9c4b0e53bb19cde
train
Extension.call_method
Call a method of the extension. This is a shortcut for :meth:`attr` + :class:`jinja2.nodes.Call`.
pipenv/vendor/jinja2/ext.py
def call_method(self, name, args=None, kwargs=None, dyn_args=None, dyn_kwargs=None, lineno=None): """Call a method of the extension. This is a shortcut for :meth:`attr` + :class:`jinja2.nodes.Call`. """ if args is None: args = [] if kwargs is None: kwargs = [] return nodes.Call(self.attr(name, lineno=lineno), args, kwargs, dyn_args, dyn_kwargs, lineno=lineno)
def call_method(self, name, args=None, kwargs=None, dyn_args=None, dyn_kwargs=None, lineno=None): """Call a method of the extension. This is a shortcut for :meth:`attr` + :class:`jinja2.nodes.Call`. """ if args is None: args = [] if kwargs is None: kwargs = [] return nodes.Call(self.attr(name, lineno=lineno), args, kwargs, dyn_args, dyn_kwargs, lineno=lineno)
[ "Call", "a", "method", "of", "the", "extension", ".", "This", "is", "a", "shortcut", "for", ":", "meth", ":", "attr", "+", ":", "class", ":", "jinja2", ".", "nodes", ".", "Call", "." ]
pypa/pipenv
python
https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/vendor/jinja2/ext.py#L119-L129
[ "def", "call_method", "(", "self", ",", "name", ",", "args", "=", "None", ",", "kwargs", "=", "None", ",", "dyn_args", "=", "None", ",", "dyn_kwargs", "=", "None", ",", "lineno", "=", "None", ")", ":", "if", "args", "is", "None", ":", "args", "=", ...
cae8d76c210b9777e90aab76e9c4b0e53bb19cde
train
InternationalizationExtension.parse
Parse a translatable tag.
pipenv/vendor/jinja2/ext.py
def parse(self, parser): """Parse a translatable tag.""" 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 later state. plural_expr = None plural_expr_assignment = None variables = {} trimmed = None while parser.stream.current.type != 'block_end': if variables: parser.stream.expect('comma') # skip colon for python compatibility if parser.stream.skip_if('colon'): break name = parser.stream.expect('name') if name.value in variables: parser.fail('translatable variable %r defined twice.' % name.value, name.lineno, exc=TemplateAssertionError) # expressions if parser.stream.current.type == 'assign': next(parser.stream) variables[name.value] = var = parser.parse_expression() elif trimmed is None and name.value in ('trimmed', 'notrimmed'): trimmed = name.value == 'trimmed' continue else: variables[name.value] = var = nodes.Name(name.value, 'load') if plural_expr is None: if isinstance(var, nodes.Call): plural_expr = nodes.Name('_trans', 'load') variables[name.value] = plural_expr plural_expr_assignment = nodes.Assign( nodes.Name('_trans', 'store'), var) else: plural_expr = var num_called_num = name.value == 'num' parser.stream.expect('block_end') plural = None have_plural = False referenced = set() # now parse until endtrans or pluralize singular_names, singular = self._parse_block(parser, True) if singular_names: referenced.update(singular_names) if plural_expr is None: plural_expr = nodes.Name(singular_names[0], 'load') num_called_num = singular_names[0] == 'num' # if we have a pluralize block, we parse that too if parser.stream.current.test('name:pluralize'): have_plural = True next(parser.stream) if parser.stream.current.type != 'block_end': name = parser.stream.expect('name') if name.value not in variables: parser.fail('unknown variable %r for pluralization' % name.value, name.lineno, exc=TemplateAssertionError) plural_expr = variables[name.value] num_called_num = name.value == 'num' parser.stream.expect('block_end') plural_names, plural = self._parse_block(parser, False) next(parser.stream) referenced.update(plural_names) else: next(parser.stream) # register free names as simple name expressions for var in referenced: if var not in variables: variables[var] = nodes.Name(var, 'load') if not have_plural: plural_expr = None elif plural_expr is None: parser.fail('pluralize without variables', lineno) if trimmed is None: trimmed = self.environment.policies['ext.i18n.trimmed'] if trimmed: singular = self._trim_whitespace(singular) if plural: plural = self._trim_whitespace(plural) node = self._make_node(singular, plural, variables, plural_expr, bool(referenced), num_called_num and have_plural) node.set_lineno(lineno) if plural_expr_assignment is not None: return [plural_expr_assignment, node] else: return node
def parse(self, parser): """Parse a translatable tag.""" 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 later state. plural_expr = None plural_expr_assignment = None variables = {} trimmed = None while parser.stream.current.type != 'block_end': if variables: parser.stream.expect('comma') # skip colon for python compatibility if parser.stream.skip_if('colon'): break name = parser.stream.expect('name') if name.value in variables: parser.fail('translatable variable %r defined twice.' % name.value, name.lineno, exc=TemplateAssertionError) # expressions if parser.stream.current.type == 'assign': next(parser.stream) variables[name.value] = var = parser.parse_expression() elif trimmed is None and name.value in ('trimmed', 'notrimmed'): trimmed = name.value == 'trimmed' continue else: variables[name.value] = var = nodes.Name(name.value, 'load') if plural_expr is None: if isinstance(var, nodes.Call): plural_expr = nodes.Name('_trans', 'load') variables[name.value] = plural_expr plural_expr_assignment = nodes.Assign( nodes.Name('_trans', 'store'), var) else: plural_expr = var num_called_num = name.value == 'num' parser.stream.expect('block_end') plural = None have_plural = False referenced = set() # now parse until endtrans or pluralize singular_names, singular = self._parse_block(parser, True) if singular_names: referenced.update(singular_names) if plural_expr is None: plural_expr = nodes.Name(singular_names[0], 'load') num_called_num = singular_names[0] == 'num' # if we have a pluralize block, we parse that too if parser.stream.current.test('name:pluralize'): have_plural = True next(parser.stream) if parser.stream.current.type != 'block_end': name = parser.stream.expect('name') if name.value not in variables: parser.fail('unknown variable %r for pluralization' % name.value, name.lineno, exc=TemplateAssertionError) plural_expr = variables[name.value] num_called_num = name.value == 'num' parser.stream.expect('block_end') plural_names, plural = self._parse_block(parser, False) next(parser.stream) referenced.update(plural_names) else: next(parser.stream) # register free names as simple name expressions for var in referenced: if var not in variables: variables[var] = nodes.Name(var, 'load') if not have_plural: plural_expr = None elif plural_expr is None: parser.fail('pluralize without variables', lineno) if trimmed is None: trimmed = self.environment.policies['ext.i18n.trimmed'] if trimmed: singular = self._trim_whitespace(singular) if plural: plural = self._trim_whitespace(plural) node = self._make_node(singular, plural, variables, plural_expr, bool(referenced), num_called_num and have_plural) node.set_lineno(lineno) if plural_expr_assignment is not None: return [plural_expr_assignment, node] else: return node
[ "Parse", "a", "translatable", "tag", "." ]
pypa/pipenv
python
https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/vendor/jinja2/ext.py#L217-L320
[ "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...
cae8d76c210b9777e90aab76e9c4b0e53bb19cde
train
InternationalizationExtension._parse_block
Parse until the next block tag with a given name.
pipenv/vendor/jinja2/ext.py
def _parse_block(self, parser, allow_pluralize): """Parse until the next block tag with a given name.""" referenced = [] buf = [] while 1: if parser.stream.current.type == 'data': buf.append(parser.stream.current.value.replace('%', '%%')) next(parser.stream) elif parser.stream.current.type == 'variable_begin': next(parser.stream) name = parser.stream.expect('name').value referenced.append(name) buf.append('%%(%s)s' % name) parser.stream.expect('variable_end') elif parser.stream.current.type == 'block_begin': next(parser.stream) if parser.stream.current.test('name:endtrans'): break elif parser.stream.current.test('name:pluralize'): if allow_pluralize: break parser.fail('a translatable section can have only one ' 'pluralize section') parser.fail('control structures in translatable sections are ' 'not allowed') elif parser.stream.eos: parser.fail('unclosed translation block') else: assert False, 'internal parser error' return referenced, concat(buf)
def _parse_block(self, parser, allow_pluralize): """Parse until the next block tag with a given name.""" referenced = [] buf = [] while 1: if parser.stream.current.type == 'data': buf.append(parser.stream.current.value.replace('%', '%%')) next(parser.stream) elif parser.stream.current.type == 'variable_begin': next(parser.stream) name = parser.stream.expect('name').value referenced.append(name) buf.append('%%(%s)s' % name) parser.stream.expect('variable_end') elif parser.stream.current.type == 'block_begin': next(parser.stream) if parser.stream.current.test('name:endtrans'): break elif parser.stream.current.test('name:pluralize'): if allow_pluralize: break parser.fail('a translatable section can have only one ' 'pluralize section') parser.fail('control structures in translatable sections are ' 'not allowed') elif parser.stream.eos: parser.fail('unclosed translation block') else: assert False, 'internal parser error' return referenced, concat(buf)
[ "Parse", "until", "the", "next", "block", "tag", "with", "a", "given", "name", "." ]
pypa/pipenv
python
https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/vendor/jinja2/ext.py#L325-L355
[ "def", "_parse_block", "(", "self", ",", "parser", ",", "allow_pluralize", ")", ":", "referenced", "=", "[", "]", "buf", "=", "[", "]", "while", "1", ":", "if", "parser", ".", "stream", ".", "current", ".", "type", "==", "'data'", ":", "buf", ".", ...
cae8d76c210b9777e90aab76e9c4b0e53bb19cde
train
InternationalizationExtension._make_node
Generates a useful node from the data provided.
pipenv/vendor/jinja2/ext.py
def _make_node(self, singular, plural, variables, plural_expr, vars_referenced, num_called_num): """Generates a useful node from the data provided.""" # no variables referenced? no need to escape for old style # gettext invocations only if there are vars. if not vars_referenced and not self.environment.newstyle_gettext: singular = singular.replace('%%', '%') if plural: plural = plural.replace('%%', '%') # singular only: if plural_expr is None: gettext = nodes.Name('gettext', 'load') node = nodes.Call(gettext, [nodes.Const(singular)], [], None, None) # singular and plural else: ngettext = nodes.Name('ngettext', 'load') node = nodes.Call(ngettext, [ nodes.Const(singular), nodes.Const(plural), plural_expr ], [], None, None) # in case newstyle gettext is used, the method is powerful # enough to handle the variable expansion and autoescape # handling itself if self.environment.newstyle_gettext: for key, value in iteritems(variables): # the function adds that later anyways in case num was # called num, so just skip it. if num_called_num and key == 'num': continue node.kwargs.append(nodes.Keyword(key, value)) # otherwise do that here else: # mark the return value as safe if we are in an # environment with autoescaping turned on node = nodes.MarkSafeIfAutoescape(node) if variables: node = nodes.Mod(node, nodes.Dict([ nodes.Pair(nodes.Const(key), value) for key, value in variables.items() ])) return nodes.Output([node])
def _make_node(self, singular, plural, variables, plural_expr, vars_referenced, num_called_num): """Generates a useful node from the data provided.""" # no variables referenced? no need to escape for old style # gettext invocations only if there are vars. if not vars_referenced and not self.environment.newstyle_gettext: singular = singular.replace('%%', '%') if plural: plural = plural.replace('%%', '%') # singular only: if plural_expr is None: gettext = nodes.Name('gettext', 'load') node = nodes.Call(gettext, [nodes.Const(singular)], [], None, None) # singular and plural else: ngettext = nodes.Name('ngettext', 'load') node = nodes.Call(ngettext, [ nodes.Const(singular), nodes.Const(plural), plural_expr ], [], None, None) # in case newstyle gettext is used, the method is powerful # enough to handle the variable expansion and autoescape # handling itself if self.environment.newstyle_gettext: for key, value in iteritems(variables): # the function adds that later anyways in case num was # called num, so just skip it. if num_called_num and key == 'num': continue node.kwargs.append(nodes.Keyword(key, value)) # otherwise do that here else: # mark the return value as safe if we are in an # environment with autoescaping turned on node = nodes.MarkSafeIfAutoescape(node) if variables: node = nodes.Mod(node, nodes.Dict([ nodes.Pair(nodes.Const(key), value) for key, value in variables.items() ])) return nodes.Output([node])
[ "Generates", "a", "useful", "node", "from", "the", "data", "provided", "." ]
pypa/pipenv
python
https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/vendor/jinja2/ext.py#L357-L403
[ "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...
cae8d76c210b9777e90aab76e9c4b0e53bb19cde
train
get_cli_string
Returns a string suitable for running as a shell script. Useful for converting a arguments passed to a fabric task to be passed to a `local` or `run` command.
pipenv/vendor/dotenv/__init__.py
def get_cli_string(path=None, action=None, key=None, value=None, quote=None): """Returns a string suitable for running as a shell script. Useful for converting a arguments passed to a fabric task to be passed to a `local` or `run` command. """ command = ['dotenv'] if quote: command.append('-q %s' % quote) if path: command.append('-f %s' % path) if action: command.append(action) if key: command.append(key) if value: if ' ' in value: command.append('"%s"' % value) else: command.append(value) return ' '.join(command).strip()
def get_cli_string(path=None, action=None, key=None, value=None, quote=None): """Returns a string suitable for running as a shell script. Useful for converting a arguments passed to a fabric task to be passed to a `local` or `run` command. """ command = ['dotenv'] if quote: command.append('-q %s' % quote) if path: command.append('-f %s' % path) if action: command.append(action) if key: command.append(key) if value: if ' ' in value: command.append('"%s"' % value) else: command.append(value) return ' '.join(command).strip()
[ "Returns", "a", "string", "suitable", "for", "running", "as", "a", "shell", "script", "." ]
pypa/pipenv
python
https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/vendor/dotenv/__init__.py#L9-L30
[ "def", "get_cli_string", "(", "path", "=", "None", ",", "action", "=", "None", ",", "key", "=", "None", ",", "value", "=", "None", ",", "quote", "=", "None", ")", ":", "command", "=", "[", "'dotenv'", "]", "if", "quote", ":", "command", ".", "appen...
cae8d76c210b9777e90aab76e9c4b0e53bb19cde
train
merge_hooks
Properly merges both requests and session hooks. This is necessary because when request_hooks == {'response': []}, the merge breaks Session hooks entirely.
pipenv/vendor/requests/sessions.py
def merge_hooks(request_hooks, session_hooks, dict_class=OrderedDict): """Properly merges both requests and session hooks. This is necessary because when request_hooks == {'response': []}, the merge breaks Session hooks entirely. """ 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 return merge_setting(request_hooks, session_hooks, dict_class)
def merge_hooks(request_hooks, session_hooks, dict_class=OrderedDict): """Properly merges both requests and session hooks. This is necessary because when request_hooks == {'response': []}, the merge breaks Session hooks entirely. """ 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 return merge_setting(request_hooks, session_hooks, dict_class)
[ "Properly", "merges", "both", "requests", "and", "session", "hooks", "." ]
pypa/pipenv
python
https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/vendor/requests/sessions.py#L80-L92
[ "def", "merge_hooks", "(", "request_hooks", ",", "session_hooks", ",", "dict_class", "=", "OrderedDict", ")", ":", "if", "session_hooks", "is", "None", "or", "session_hooks", ".", "get", "(", "'response'", ")", "==", "[", "]", ":", "return", "request_hooks", ...
cae8d76c210b9777e90aab76e9c4b0e53bb19cde
train
SessionRedirectMixin.get_redirect_target
Receives a Response. Returns a redirect URI or ``None``
pipenv/vendor/requests/sessions.py
def get_redirect_target(self, resp): """Receives a Response. Returns a redirect URI or ``None``""" # 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). # If a custom mixin is used to handle this logic, it may be advantageous # to cache the redirect location onto the response object as a private # attribute. if resp.is_redirect: location = resp.headers['location'] # Currently the underlying http module on py3 decode headers # in latin1, but empirical evidence suggests that latin1 is very # rarely used with non-ASCII characters in HTTP headers. # It is more likely to get UTF8 header rather than latin1. # This causes incorrect handling of UTF8 encoded location headers. # To solve this, we re-encode the location in latin1. if is_py3: location = location.encode('latin1') return to_native_string(location, 'utf8') return None
def get_redirect_target(self, resp): """Receives a Response. Returns a redirect URI or ``None``""" # 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). # If a custom mixin is used to handle this logic, it may be advantageous # to cache the redirect location onto the response object as a private # attribute. if resp.is_redirect: location = resp.headers['location'] # Currently the underlying http module on py3 decode headers # in latin1, but empirical evidence suggests that latin1 is very # rarely used with non-ASCII characters in HTTP headers. # It is more likely to get UTF8 header rather than latin1. # This causes incorrect handling of UTF8 encoded location headers. # To solve this, we re-encode the location in latin1. if is_py3: location = location.encode('latin1') return to_native_string(location, 'utf8') return None
[ "Receives", "a", "Response", ".", "Returns", "a", "redirect", "URI", "or", "None" ]
pypa/pipenv
python
https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/vendor/requests/sessions.py#L97-L116
[ "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).", "# If a custom mixin is u...
cae8d76c210b9777e90aab76e9c4b0e53bb19cde
train
SessionRedirectMixin.should_strip_auth
Decide whether Authorization header should be removed when redirecting
pipenv/vendor/requests/sessions.py
def should_strip_auth(self, old_url, new_url): """Decide whether Authorization header should be removed when redirecting""" 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 using the standard # ports. This isn't specified by RFC 7235, but is kept to avoid # breaking backwards compatibility with older versions of requests # that allowed any redirects on the same host. if (old_parsed.scheme == 'http' and old_parsed.port in (80, None) and new_parsed.scheme == 'https' and new_parsed.port in (443, None)): return False # Handle default port usage corresponding to scheme. changed_port = old_parsed.port != new_parsed.port changed_scheme = old_parsed.scheme != new_parsed.scheme default_port = (DEFAULT_PORTS.get(old_parsed.scheme, None), None) if (not changed_scheme and old_parsed.port in default_port and new_parsed.port in default_port): return False # Standard case: root URI must match return changed_port or changed_scheme
def should_strip_auth(self, old_url, new_url): """Decide whether Authorization header should be removed when redirecting""" 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 using the standard # ports. This isn't specified by RFC 7235, but is kept to avoid # breaking backwards compatibility with older versions of requests # that allowed any redirects on the same host. if (old_parsed.scheme == 'http' and old_parsed.port in (80, None) and new_parsed.scheme == 'https' and new_parsed.port in (443, None)): return False # Handle default port usage corresponding to scheme. changed_port = old_parsed.port != new_parsed.port changed_scheme = old_parsed.scheme != new_parsed.scheme default_port = (DEFAULT_PORTS.get(old_parsed.scheme, None), None) if (not changed_scheme and old_parsed.port in default_port and new_parsed.port in default_port): return False # Standard case: root URI must match return changed_port or changed_scheme
[ "Decide", "whether", "Authorization", "header", "should", "be", "removed", "when", "redirecting" ]
pypa/pipenv
python
https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/vendor/requests/sessions.py#L118-L141
[ "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...
cae8d76c210b9777e90aab76e9c4b0e53bb19cde
train
SessionRedirectMixin.rebuild_auth
When being redirected we may want to strip authentication from the request to avoid leaking credentials. This method intelligently removes and reapplies authentication where possible to avoid credential loss.
pipenv/vendor/requests/sessions.py
def rebuild_auth(self, prepared_request, response): """When being redirected we may want to strip authentication from the request to avoid leaking credentials. This method intelligently removes and reapplies authentication where possible to avoid credential loss. """ 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 new host, we should strip out any # authentication headers. del headers['Authorization'] # .netrc might have more auth for us on our new host. new_auth = get_netrc_auth(url) if self.trust_env else None if new_auth is not None: prepared_request.prepare_auth(new_auth) return
def rebuild_auth(self, prepared_request, response): """When being redirected we may want to strip authentication from the request to avoid leaking credentials. This method intelligently removes and reapplies authentication where possible to avoid credential loss. """ 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 new host, we should strip out any # authentication headers. del headers['Authorization'] # .netrc might have more auth for us on our new host. new_auth = get_netrc_auth(url) if self.trust_env else None if new_auth is not None: prepared_request.prepare_auth(new_auth) return
[ "When", "being", "redirected", "we", "may", "want", "to", "strip", "authentication", "from", "the", "request", "to", "avoid", "leaking", "credentials", ".", "This", "method", "intelligently", "removes", "and", "reapplies", "authentication", "where", "possible", "t...
pypa/pipenv
python
https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/vendor/requests/sessions.py#L256-L274
[ "def", "rebuild_auth", "(", "self", ",", "prepared_request", ",", "response", ")", ":", "headers", "=", "prepared_request", ".", "headers", "url", "=", "prepared_request", ".", "url", "if", "'Authorization'", "in", "headers", "and", "self", ".", "should_strip_au...
cae8d76c210b9777e90aab76e9c4b0e53bb19cde
train
SessionRedirectMixin.rebuild_proxies
This method re-evaluates the proxy configuration by considering the environment variables. If we are redirected to a URL covered by NO_PROXY, we strip the proxy configuration. Otherwise, we set missing proxy keys for this URL (in case they were stripped by a previous redirect). This method also replaces the Proxy-Authorization header where necessary. :rtype: dict
pipenv/vendor/requests/sessions.py
def rebuild_proxies(self, prepared_request, proxies): """This method re-evaluates the proxy configuration by considering the environment variables. If we are redirected to a URL covered by NO_PROXY, we strip the proxy configuration. Otherwise, we set missing proxy keys for this URL (in case they were stripped by a previous redirect). This method also replaces the Proxy-Authorization header where necessary. :rtype: dict """ proxies = proxies if proxies is not None else {} headers = prepared_request.headers url = prepared_request.url scheme = urlparse(url).scheme new_proxies = proxies.copy() no_proxy = proxies.get('no_proxy') bypass_proxy = should_bypass_proxies(url, no_proxy=no_proxy) if self.trust_env and not bypass_proxy: environ_proxies = get_environ_proxies(url, no_proxy=no_proxy) proxy = environ_proxies.get(scheme, environ_proxies.get('all')) if proxy: new_proxies.setdefault(scheme, proxy) if 'Proxy-Authorization' in headers: del headers['Proxy-Authorization'] try: username, password = get_auth_from_url(new_proxies[scheme]) except KeyError: username, password = None, None if username and password: headers['Proxy-Authorization'] = _basic_auth_str(username, password) return new_proxies
def rebuild_proxies(self, prepared_request, proxies): """This method re-evaluates the proxy configuration by considering the environment variables. If we are redirected to a URL covered by NO_PROXY, we strip the proxy configuration. Otherwise, we set missing proxy keys for this URL (in case they were stripped by a previous redirect). This method also replaces the Proxy-Authorization header where necessary. :rtype: dict """ proxies = proxies if proxies is not None else {} headers = prepared_request.headers url = prepared_request.url scheme = urlparse(url).scheme new_proxies = proxies.copy() no_proxy = proxies.get('no_proxy') bypass_proxy = should_bypass_proxies(url, no_proxy=no_proxy) if self.trust_env and not bypass_proxy: environ_proxies = get_environ_proxies(url, no_proxy=no_proxy) proxy = environ_proxies.get(scheme, environ_proxies.get('all')) if proxy: new_proxies.setdefault(scheme, proxy) if 'Proxy-Authorization' in headers: del headers['Proxy-Authorization'] try: username, password = get_auth_from_url(new_proxies[scheme]) except KeyError: username, password = None, None if username and password: headers['Proxy-Authorization'] = _basic_auth_str(username, password) return new_proxies
[ "This", "method", "re", "-", "evaluates", "the", "proxy", "configuration", "by", "considering", "the", "environment", "variables", ".", "If", "we", "are", "redirected", "to", "a", "URL", "covered", "by", "NO_PROXY", "we", "strip", "the", "proxy", "configuratio...
pypa/pipenv
python
https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/vendor/requests/sessions.py#L276-L315
[ "def", "rebuild_proxies", "(", "self", ",", "prepared_request", ",", "proxies", ")", ":", "proxies", "=", "proxies", "if", "proxies", "is", "not", "None", "else", "{", "}", "headers", "=", "prepared_request", ".", "headers", "url", "=", "prepared_request", "...
cae8d76c210b9777e90aab76e9c4b0e53bb19cde
train
Session.prepare_request
Constructs a :class:`PreparedRequest <PreparedRequest>` for transmission and returns it. The :class:`PreparedRequest` has settings merged from the :class:`Request <Request>` instance and those of the :class:`Session`. :param request: :class:`Request` instance to prepare with this session's settings. :rtype: requests.PreparedRequest
pipenv/vendor/requests/sessions.py
def prepare_request(self, request): """Constructs a :class:`PreparedRequest <PreparedRequest>` for transmission and returns it. The :class:`PreparedRequest` has settings merged from the :class:`Request <Request>` instance and those of the :class:`Session`. :param request: :class:`Request` instance to prepare with this session's settings. :rtype: requests.PreparedRequest """ cookies = request.cookies or {} # Bootstrap CookieJar. if not isinstance(cookies, cookielib.CookieJar): cookies = cookiejar_from_dict(cookies) # Merge with session cookies merged_cookies = merge_cookies( merge_cookies(RequestsCookieJar(), self.cookies), cookies) # Set environment's basic authentication if not explicitly set. auth = request.auth if self.trust_env and not auth and not self.auth: auth = get_netrc_auth(request.url) p = PreparedRequest() p.prepare( method=request.method.upper(), url=request.url, files=request.files, data=request.data, json=request.json, headers=merge_setting(request.headers, self.headers, dict_class=CaseInsensitiveDict), params=merge_setting(request.params, self.params), auth=merge_setting(auth, self.auth), cookies=merged_cookies, hooks=merge_hooks(request.hooks, self.hooks), ) return p
def prepare_request(self, request): """Constructs a :class:`PreparedRequest <PreparedRequest>` for transmission and returns it. The :class:`PreparedRequest` has settings merged from the :class:`Request <Request>` instance and those of the :class:`Session`. :param request: :class:`Request` instance to prepare with this session's settings. :rtype: requests.PreparedRequest """ cookies = request.cookies or {} # Bootstrap CookieJar. if not isinstance(cookies, cookielib.CookieJar): cookies = cookiejar_from_dict(cookies) # Merge with session cookies merged_cookies = merge_cookies( merge_cookies(RequestsCookieJar(), self.cookies), cookies) # Set environment's basic authentication if not explicitly set. auth = request.auth if self.trust_env and not auth and not self.auth: auth = get_netrc_auth(request.url) p = PreparedRequest() p.prepare( method=request.method.upper(), url=request.url, files=request.files, data=request.data, json=request.json, headers=merge_setting(request.headers, self.headers, dict_class=CaseInsensitiveDict), params=merge_setting(request.params, self.params), auth=merge_setting(auth, self.auth), cookies=merged_cookies, hooks=merge_hooks(request.hooks, self.hooks), ) return p
[ "Constructs", "a", ":", "class", ":", "PreparedRequest", "<PreparedRequest", ">", "for", "transmission", "and", "returns", "it", ".", "The", ":", "class", ":", "PreparedRequest", "has", "settings", "merged", "from", "the", ":", "class", ":", "Request", "<Reque...
pypa/pipenv
python
https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/vendor/requests/sessions.py#L426-L464
[ "def", "prepare_request", "(", "self", ",", "request", ")", ":", "cookies", "=", "request", ".", "cookies", "or", "{", "}", "# Bootstrap CookieJar.", "if", "not", "isinstance", "(", "cookies", ",", "cookielib", ".", "CookieJar", ")", ":", "cookies", "=", "...
cae8d76c210b9777e90aab76e9c4b0e53bb19cde
train
Session.request
Constructs a :class:`Request <Request>`, prepares it and sends it. Returns :class:`Response <Response>` object. :param method: method for the new :class:`Request` object. :param url: URL for the new :class:`Request` object. :param params: (optional) Dictionary or bytes to be sent in the query string for the :class:`Request`. :param data: (optional) Dictionary, list of tuples, bytes, or file-like object to send in the body of the :class:`Request`. :param json: (optional) json to send in the body of the :class:`Request`. :param headers: (optional) Dictionary of HTTP Headers to send with the :class:`Request`. :param cookies: (optional) Dict or CookieJar object to send with the :class:`Request`. :param files: (optional) Dictionary of ``'filename': file-like-objects`` for multipart encoding upload. :param auth: (optional) Auth tuple or callable to enable Basic/Digest/Custom HTTP Auth. :param timeout: (optional) How long to wait for the server to send data before giving up, as a float, or a :ref:`(connect timeout, read timeout) <timeouts>` tuple. :type timeout: float or tuple :param allow_redirects: (optional) Set to True by default. :type allow_redirects: bool :param proxies: (optional) Dictionary mapping protocol or protocol and hostname to the URL of the proxy. :param stream: (optional) whether to immediately download the response content. Defaults to ``False``. :param verify: (optional) Either a boolean, in which case it controls whether we verify the server's TLS certificate, or a string, in which case it must be a path to a CA bundle to use. Defaults to ``True``. :param cert: (optional) if String, path to ssl client cert file (.pem). If Tuple, ('cert', 'key') pair. :rtype: requests.Response
pipenv/vendor/requests/sessions.py
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): """Constructs a :class:`Request <Request>`, prepares it and sends it. Returns :class:`Response <Response>` object. :param method: method for the new :class:`Request` object. :param url: URL for the new :class:`Request` object. :param params: (optional) Dictionary or bytes to be sent in the query string for the :class:`Request`. :param data: (optional) Dictionary, list of tuples, bytes, or file-like object to send in the body of the :class:`Request`. :param json: (optional) json to send in the body of the :class:`Request`. :param headers: (optional) Dictionary of HTTP Headers to send with the :class:`Request`. :param cookies: (optional) Dict or CookieJar object to send with the :class:`Request`. :param files: (optional) Dictionary of ``'filename': file-like-objects`` for multipart encoding upload. :param auth: (optional) Auth tuple or callable to enable Basic/Digest/Custom HTTP Auth. :param timeout: (optional) How long to wait for the server to send data before giving up, as a float, or a :ref:`(connect timeout, read timeout) <timeouts>` tuple. :type timeout: float or tuple :param allow_redirects: (optional) Set to True by default. :type allow_redirects: bool :param proxies: (optional) Dictionary mapping protocol or protocol and hostname to the URL of the proxy. :param stream: (optional) whether to immediately download the response content. Defaults to ``False``. :param verify: (optional) Either a boolean, in which case it controls whether we verify the server's TLS certificate, or a string, in which case it must be a path to a CA bundle to use. Defaults to ``True``. :param cert: (optional) if String, path to ssl client cert file (.pem). If Tuple, ('cert', 'key') pair. :rtype: requests.Response """ # Create the Request. req = Request( method=method.upper(), url=url, headers=headers, files=files, data=data or {}, json=json, params=params or {}, auth=auth, cookies=cookies, hooks=hooks, ) prep = self.prepare_request(req) proxies = proxies or {} settings = self.merge_environment_settings( prep.url, proxies, stream, verify, cert ) # Send the request. send_kwargs = { 'timeout': timeout, 'allow_redirects': allow_redirects, } send_kwargs.update(settings) resp = self.send(prep, **send_kwargs) return resp
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): """Constructs a :class:`Request <Request>`, prepares it and sends it. Returns :class:`Response <Response>` object. :param method: method for the new :class:`Request` object. :param url: URL for the new :class:`Request` object. :param params: (optional) Dictionary or bytes to be sent in the query string for the :class:`Request`. :param data: (optional) Dictionary, list of tuples, bytes, or file-like object to send in the body of the :class:`Request`. :param json: (optional) json to send in the body of the :class:`Request`. :param headers: (optional) Dictionary of HTTP Headers to send with the :class:`Request`. :param cookies: (optional) Dict or CookieJar object to send with the :class:`Request`. :param files: (optional) Dictionary of ``'filename': file-like-objects`` for multipart encoding upload. :param auth: (optional) Auth tuple or callable to enable Basic/Digest/Custom HTTP Auth. :param timeout: (optional) How long to wait for the server to send data before giving up, as a float, or a :ref:`(connect timeout, read timeout) <timeouts>` tuple. :type timeout: float or tuple :param allow_redirects: (optional) Set to True by default. :type allow_redirects: bool :param proxies: (optional) Dictionary mapping protocol or protocol and hostname to the URL of the proxy. :param stream: (optional) whether to immediately download the response content. Defaults to ``False``. :param verify: (optional) Either a boolean, in which case it controls whether we verify the server's TLS certificate, or a string, in which case it must be a path to a CA bundle to use. Defaults to ``True``. :param cert: (optional) if String, path to ssl client cert file (.pem). If Tuple, ('cert', 'key') pair. :rtype: requests.Response """ # Create the Request. req = Request( method=method.upper(), url=url, headers=headers, files=files, data=data or {}, json=json, params=params or {}, auth=auth, cookies=cookies, hooks=hooks, ) prep = self.prepare_request(req) proxies = proxies or {} settings = self.merge_environment_settings( prep.url, proxies, stream, verify, cert ) # Send the request. send_kwargs = { 'timeout': timeout, 'allow_redirects': allow_redirects, } send_kwargs.update(settings) resp = self.send(prep, **send_kwargs) return resp
[ "Constructs", "a", ":", "class", ":", "Request", "<Request", ">", "prepares", "it", "and", "sends", "it", ".", "Returns", ":", "class", ":", "Response", "<Response", ">", "object", "." ]
pypa/pipenv
python
https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/vendor/requests/sessions.py#L466-L535
[ "def", "request", "(", "self", ",", "method", ",", "url", ",", "params", "=", "None", ",", "data", "=", "None", ",", "headers", "=", "None", ",", "cookies", "=", "None", ",", "files", "=", "None", ",", "auth", "=", "None", ",", "timeout", "=", "N...
cae8d76c210b9777e90aab76e9c4b0e53bb19cde
train
Session.get
r"""Sends a GET request. Returns :class:`Response` object. :param url: URL for the new :class:`Request` object. :param \*\*kwargs: Optional arguments that ``request`` takes. :rtype: requests.Response
pipenv/vendor/requests/sessions.py
def get(self, url, **kwargs): r"""Sends a GET request. Returns :class:`Response` object. :param url: URL for the new :class:`Request` object. :param \*\*kwargs: Optional arguments that ``request`` takes. :rtype: requests.Response """ kwargs.setdefault('allow_redirects', True) return self.request('GET', url, **kwargs)
def get(self, url, **kwargs): r"""Sends a GET request. Returns :class:`Response` object. :param url: URL for the new :class:`Request` object. :param \*\*kwargs: Optional arguments that ``request`` takes. :rtype: requests.Response """ kwargs.setdefault('allow_redirects', True) return self.request('GET', url, **kwargs)
[ "r", "Sends", "a", "GET", "request", ".", "Returns", ":", "class", ":", "Response", "object", "." ]
pypa/pipenv
python
https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/vendor/requests/sessions.py#L537-L546
[ "def", "get", "(", "self", ",", "url", ",", "*", "*", "kwargs", ")", ":", "kwargs", ".", "setdefault", "(", "'allow_redirects'", ",", "True", ")", "return", "self", ".", "request", "(", "'GET'", ",", "url", ",", "*", "*", "kwargs", ")" ]
cae8d76c210b9777e90aab76e9c4b0e53bb19cde
train
Session.options
r"""Sends a OPTIONS request. Returns :class:`Response` object. :param url: URL for the new :class:`Request` object. :param \*\*kwargs: Optional arguments that ``request`` takes. :rtype: requests.Response
pipenv/vendor/requests/sessions.py
def options(self, url, **kwargs): r"""Sends a OPTIONS request. Returns :class:`Response` object. :param url: URL for the new :class:`Request` object. :param \*\*kwargs: Optional arguments that ``request`` takes. :rtype: requests.Response """ kwargs.setdefault('allow_redirects', True) return self.request('OPTIONS', url, **kwargs)
def options(self, url, **kwargs): r"""Sends a OPTIONS request. Returns :class:`Response` object. :param url: URL for the new :class:`Request` object. :param \*\*kwargs: Optional arguments that ``request`` takes. :rtype: requests.Response """ kwargs.setdefault('allow_redirects', True) return self.request('OPTIONS', url, **kwargs)
[ "r", "Sends", "a", "OPTIONS", "request", ".", "Returns", ":", "class", ":", "Response", "object", "." ]
pypa/pipenv
python
https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/vendor/requests/sessions.py#L548-L557
[ "def", "options", "(", "self", ",", "url", ",", "*", "*", "kwargs", ")", ":", "kwargs", ".", "setdefault", "(", "'allow_redirects'", ",", "True", ")", "return", "self", ".", "request", "(", "'OPTIONS'", ",", "url", ",", "*", "*", "kwargs", ")" ]
cae8d76c210b9777e90aab76e9c4b0e53bb19cde
train
Session.head
r"""Sends a HEAD request. Returns :class:`Response` object. :param url: URL for the new :class:`Request` object. :param \*\*kwargs: Optional arguments that ``request`` takes. :rtype: requests.Response
pipenv/vendor/requests/sessions.py
def head(self, url, **kwargs): r"""Sends a HEAD request. Returns :class:`Response` object. :param url: URL for the new :class:`Request` object. :param \*\*kwargs: Optional arguments that ``request`` takes. :rtype: requests.Response """ kwargs.setdefault('allow_redirects', False) return self.request('HEAD', url, **kwargs)
def head(self, url, **kwargs): r"""Sends a HEAD request. Returns :class:`Response` object. :param url: URL for the new :class:`Request` object. :param \*\*kwargs: Optional arguments that ``request`` takes. :rtype: requests.Response """ kwargs.setdefault('allow_redirects', False) return self.request('HEAD', url, **kwargs)
[ "r", "Sends", "a", "HEAD", "request", ".", "Returns", ":", "class", ":", "Response", "object", "." ]
pypa/pipenv
python
https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/vendor/requests/sessions.py#L559-L568
[ "def", "head", "(", "self", ",", "url", ",", "*", "*", "kwargs", ")", ":", "kwargs", ".", "setdefault", "(", "'allow_redirects'", ",", "False", ")", "return", "self", ".", "request", "(", "'HEAD'", ",", "url", ",", "*", "*", "kwargs", ")" ]
cae8d76c210b9777e90aab76e9c4b0e53bb19cde
train
Session.send
Send a given PreparedRequest. :rtype: requests.Response
pipenv/vendor/requests/sessions.py
def send(self, request, **kwargs): """Send a given PreparedRequest. :rtype: requests.Response """ # 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', self.verify) kwargs.setdefault('cert', self.cert) kwargs.setdefault('proxies', self.proxies) # It's possible that users might accidentally send a Request object. # Guard against that specific failure case. if isinstance(request, Request): raise ValueError('You can only send PreparedRequests.') # Set up variables needed for resolve_redirects and dispatching of hooks allow_redirects = kwargs.pop('allow_redirects', True) stream = kwargs.get('stream') hooks = request.hooks # Get the appropriate adapter to use adapter = self.get_adapter(url=request.url) # Start time (approximately) of the request start = preferred_clock() # Send the request r = adapter.send(request, **kwargs) # Total elapsed time of the request (approximately) elapsed = preferred_clock() - start r.elapsed = timedelta(seconds=elapsed) # Response manipulation hooks r = dispatch_hook('response', hooks, r, **kwargs) # Persist cookies if r.history: # If the hooks create history then we want those cookies too for resp in r.history: extract_cookies_to_jar(self.cookies, resp.request, resp.raw) extract_cookies_to_jar(self.cookies, request, r.raw) # Redirect resolving generator. gen = self.resolve_redirects(r, request, **kwargs) # Resolve redirects if allowed. history = [resp for resp in gen] if allow_redirects else [] # Shuffle things around if there's history. if history: # Insert the first (original) request at the start history.insert(0, r) # Get the last request made r = history.pop() r.history = history # If redirects aren't being followed, store the response on the Request for Response.next(). if not allow_redirects: try: r._next = next(self.resolve_redirects(r, request, yield_requests=True, **kwargs)) except StopIteration: pass if not stream: r.content return r
def send(self, request, **kwargs): """Send a given PreparedRequest. :rtype: requests.Response """ # 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', self.verify) kwargs.setdefault('cert', self.cert) kwargs.setdefault('proxies', self.proxies) # It's possible that users might accidentally send a Request object. # Guard against that specific failure case. if isinstance(request, Request): raise ValueError('You can only send PreparedRequests.') # Set up variables needed for resolve_redirects and dispatching of hooks allow_redirects = kwargs.pop('allow_redirects', True) stream = kwargs.get('stream') hooks = request.hooks # Get the appropriate adapter to use adapter = self.get_adapter(url=request.url) # Start time (approximately) of the request start = preferred_clock() # Send the request r = adapter.send(request, **kwargs) # Total elapsed time of the request (approximately) elapsed = preferred_clock() - start r.elapsed = timedelta(seconds=elapsed) # Response manipulation hooks r = dispatch_hook('response', hooks, r, **kwargs) # Persist cookies if r.history: # If the hooks create history then we want those cookies too for resp in r.history: extract_cookies_to_jar(self.cookies, resp.request, resp.raw) extract_cookies_to_jar(self.cookies, request, r.raw) # Redirect resolving generator. gen = self.resolve_redirects(r, request, **kwargs) # Resolve redirects if allowed. history = [resp for resp in gen] if allow_redirects else [] # Shuffle things around if there's history. if history: # Insert the first (original) request at the start history.insert(0, r) # Get the last request made r = history.pop() r.history = history # If redirects aren't being followed, store the response on the Request for Response.next(). if not allow_redirects: try: r._next = next(self.resolve_redirects(r, request, yield_requests=True, **kwargs)) except StopIteration: pass if not stream: r.content return r
[ "Send", "a", "given", "PreparedRequest", "." ]
pypa/pipenv
python
https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/vendor/requests/sessions.py#L617-L688
[ "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", "...
cae8d76c210b9777e90aab76e9c4b0e53bb19cde
train
Session.merge_environment_settings
Check the environment and merge it with some settings. :rtype: dict
pipenv/vendor/requests/sessions.py
def merge_environment_settings(self, url, proxies, stream, verify, cert): """ Check the environment and merge it with some settings. :rtype: dict """ # Gather clues from the surrounding environment. if self.trust_env: # Set environment's proxies. no_proxy = proxies.get('no_proxy') if proxies is not None else None env_proxies = get_environ_proxies(url, no_proxy=no_proxy) for (k, v) in env_proxies.items(): proxies.setdefault(k, v) # Look for requests environment configuration and be compatible # with cURL. if verify is True or verify is None: verify = (os.environ.get('REQUESTS_CA_BUNDLE') or os.environ.get('CURL_CA_BUNDLE')) # Merge all the kwargs. proxies = merge_setting(proxies, self.proxies) stream = merge_setting(stream, self.stream) verify = merge_setting(verify, self.verify) cert = merge_setting(cert, self.cert) return {'verify': verify, 'proxies': proxies, 'stream': stream, 'cert': cert}
def merge_environment_settings(self, url, proxies, stream, verify, cert): """ Check the environment and merge it with some settings. :rtype: dict """ # Gather clues from the surrounding environment. if self.trust_env: # Set environment's proxies. no_proxy = proxies.get('no_proxy') if proxies is not None else None env_proxies = get_environ_proxies(url, no_proxy=no_proxy) for (k, v) in env_proxies.items(): proxies.setdefault(k, v) # Look for requests environment configuration and be compatible # with cURL. if verify is True or verify is None: verify = (os.environ.get('REQUESTS_CA_BUNDLE') or os.environ.get('CURL_CA_BUNDLE')) # Merge all the kwargs. proxies = merge_setting(proxies, self.proxies) stream = merge_setting(stream, self.stream) verify = merge_setting(verify, self.verify) cert = merge_setting(cert, self.cert) return {'verify': verify, 'proxies': proxies, 'stream': stream, 'cert': cert}
[ "Check", "the", "environment", "and", "merge", "it", "with", "some", "settings", "." ]
pypa/pipenv
python
https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/vendor/requests/sessions.py#L690-L717
[ "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", "=",...
cae8d76c210b9777e90aab76e9c4b0e53bb19cde
train
Session.get_adapter
Returns the appropriate connection adapter for the given URL. :rtype: requests.adapters.BaseAdapter
pipenv/vendor/requests/sessions.py
def get_adapter(self, url): """ Returns the appropriate connection adapter for the given URL. :rtype: requests.adapters.BaseAdapter """ for (prefix, adapter) in self.adapters.items(): if url.lower().startswith(prefix.lower()): return adapter # Nothing matches :-/ raise InvalidSchema("No connection adapters were found for '%s'" % url)
def get_adapter(self, url): """ Returns the appropriate connection adapter for the given URL. :rtype: requests.adapters.BaseAdapter """ for (prefix, adapter) in self.adapters.items(): if url.lower().startswith(prefix.lower()): return adapter # Nothing matches :-/ raise InvalidSchema("No connection adapters were found for '%s'" % url)
[ "Returns", "the", "appropriate", "connection", "adapter", "for", "the", "given", "URL", "." ]
pypa/pipenv
python
https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/vendor/requests/sessions.py#L719-L731
[ "def", "get_adapter", "(", "self", ",", "url", ")", ":", "for", "(", "prefix", ",", "adapter", ")", "in", "self", ".", "adapters", ".", "items", "(", ")", ":", "if", "url", ".", "lower", "(", ")", ".", "startswith", "(", "prefix", ".", "lower", "...
cae8d76c210b9777e90aab76e9c4b0e53bb19cde
train
Session.mount
Registers a connection adapter to a prefix. Adapters are sorted in descending order by prefix length.
pipenv/vendor/requests/sessions.py
def mount(self, prefix, adapter): """Registers a connection adapter to a prefix. Adapters are sorted in descending order by prefix length. """ 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)
def mount(self, prefix, adapter): """Registers a connection adapter to a prefix. Adapters are sorted in descending order by prefix length. """ 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", "." ]
pypa/pipenv
python
https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/vendor/requests/sessions.py#L738-L747
[ "def", "mount", "(", "self", ",", "prefix", ",", "adapter", ")", ":", "self", ".", "adapters", "[", "prefix", "]", "=", "adapter", "keys_to_move", "=", "[", "k", "for", "k", "in", "self", ".", "adapters", "if", "len", "(", "k", ")", "<", "len", "...
cae8d76c210b9777e90aab76e9c4b0e53bb19cde
train
console_to_str
Return a string, safe for output, of subprocess output. We assume the data is in the locale preferred encoding. If it won't decode properly, we warn the user but decode as best we can. We also ensure that the output can be safely written to standard output without encoding errors.
pipenv/patched/notpip/_internal/utils/compat.py
def console_to_str(data): # type: (bytes) -> Text """Return a string, safe for output, of subprocess output. We assume the data is in the locale preferred encoding. If it won't decode properly, we warn the user but decode as best we can. We also ensure that the output can be safely written to standard output without encoding errors. """ # 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() if (not encoding) or codecs.lookup(encoding).name == "ascii": encoding = "utf-8" # Now try to decode the data - if we fail, warn the user and # decode with replacement. try: decoded_data = data.decode(encoding) except UnicodeDecodeError: logger.warning( "Subprocess output does not appear to be encoded as %s", encoding, ) decoded_data = data.decode(encoding, errors=backslashreplace_decode) # Make sure we can print the output, by encoding it to the output # encoding with replacement of unencodable characters, and then # decoding again. # We use stderr's encoding because it's less likely to be # redirected and if we don't find an encoding we skip this # step (on the assumption that output is wrapped by something # that won't fail). # The double getattr is to deal with the possibility that we're # being called in a situation where sys.__stderr__ doesn't exist, # or doesn't have an encoding attribute. Neither of these cases # should occur in normal pip use, but there's no harm in checking # in case people use pip in (unsupported) unusual situations. output_encoding = getattr(getattr(sys, "__stderr__", None), "encoding", None) if output_encoding: output_encoded = decoded_data.encode( output_encoding, errors="backslashreplace" ) decoded_data = output_encoded.decode(output_encoding) return decoded_data
def console_to_str(data): # type: (bytes) -> Text """Return a string, safe for output, of subprocess output. We assume the data is in the locale preferred encoding. If it won't decode properly, we warn the user but decode as best we can. We also ensure that the output can be safely written to standard output without encoding errors. """ # 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() if (not encoding) or codecs.lookup(encoding).name == "ascii": encoding = "utf-8" # Now try to decode the data - if we fail, warn the user and # decode with replacement. try: decoded_data = data.decode(encoding) except UnicodeDecodeError: logger.warning( "Subprocess output does not appear to be encoded as %s", encoding, ) decoded_data = data.decode(encoding, errors=backslashreplace_decode) # Make sure we can print the output, by encoding it to the output # encoding with replacement of unencodable characters, and then # decoding again. # We use stderr's encoding because it's less likely to be # redirected and if we don't find an encoding we skip this # step (on the assumption that output is wrapped by something # that won't fail). # The double getattr is to deal with the possibility that we're # being called in a situation where sys.__stderr__ doesn't exist, # or doesn't have an encoding attribute. Neither of these cases # should occur in normal pip use, but there's no harm in checking # in case people use pip in (unsupported) unusual situations. output_encoding = getattr(getattr(sys, "__stderr__", None), "encoding", None) if output_encoding: output_encoded = decoded_data.encode( output_encoding, errors="backslashreplace" ) decoded_data = output_encoded.decode(output_encoding) return decoded_data
[ "Return", "a", "string", "safe", "for", "output", "of", "subprocess", "output", "." ]
pypa/pipenv
python
https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/patched/notpip/_internal/utils/compat.py#L75-L127
[ "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", ".", "getpreferreden...
cae8d76c210b9777e90aab76e9c4b0e53bb19cde
train
get_path_uid
Return path's uid. Does not follow symlinks: https://github.com/pypa/pip/pull/935#discussion_r5307003 Placed this function in compat due to differences on AIX and Jython, that should eventually go away. :raises OSError: When path is a symlink or can't be read.
pipenv/patched/notpip/_internal/utils/compat.py
def get_path_uid(path): # type: (str) -> int """ Return path's uid. Does not follow symlinks: https://github.com/pypa/pip/pull/935#discussion_r5307003 Placed this function in compat due to differences on AIX and Jython, that should eventually go away. :raises OSError: When path is a symlink or can't be read. """ 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 vulnerability, but best we can do w/o NOFOLLOW if not os.path.islink(path): # older versions of Jython don't have `os.fstat` file_uid = os.stat(path).st_uid else: # raise OSError for parity with os.O_NOFOLLOW above raise OSError( "%s is a symlink; Will not return uid for symlinks" % path ) return file_uid
def get_path_uid(path): # type: (str) -> int """ Return path's uid. Does not follow symlinks: https://github.com/pypa/pip/pull/935#discussion_r5307003 Placed this function in compat due to differences on AIX and Jython, that should eventually go away. :raises OSError: When path is a symlink or can't be read. """ 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 vulnerability, but best we can do w/o NOFOLLOW if not os.path.islink(path): # older versions of Jython don't have `os.fstat` file_uid = os.stat(path).st_uid else: # raise OSError for parity with os.O_NOFOLLOW above raise OSError( "%s is a symlink; Will not return uid for symlinks" % path ) return file_uid
[ "Return", "path", "s", "uid", "." ]
pypa/pipenv
python
https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/patched/notpip/_internal/utils/compat.py#L146-L173
[ "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", "=", ...
cae8d76c210b9777e90aab76e9c4b0e53bb19cde
train
expanduser
Expand ~ and ~user constructions. Includes a workaround for https://bugs.python.org/issue14768
pipenv/patched/notpip/_internal/utils/compat.py
def expanduser(path): # type: (str) -> str """ Expand ~ and ~user constructions. Includes a workaround for https://bugs.python.org/issue14768 """ expanded = os.path.expanduser(path) if path.startswith('~/') and expanded.startswith('//'): expanded = expanded[1:] return expanded
def expanduser(path): # type: (str) -> str """ Expand ~ and ~user constructions. Includes a workaround for https://bugs.python.org/issue14768 """ expanded = os.path.expanduser(path) if path.startswith('~/') and expanded.startswith('//'): expanded = expanded[1:] return expanded
[ "Expand", "~", "and", "~user", "constructions", "." ]
pypa/pipenv
python
https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/patched/notpip/_internal/utils/compat.py#L188-L198
[ "def", "expanduser", "(", "path", ")", ":", "# type: (str) -> str", "expanded", "=", "os", ".", "path", ".", "expanduser", "(", "path", ")", "if", "path", ".", "startswith", "(", "'~/'", ")", "and", "expanded", ".", "startswith", "(", "'//'", ")", ":", ...
cae8d76c210b9777e90aab76e9c4b0e53bb19cde
train
samefile
Provide an alternative for os.path.samefile on Windows/Python2
pipenv/patched/notpip/_internal/utils/compat.py
def samefile(file1, file2): # type: (str, str) -> bool """Provide an alternative for os.path.samefile on Windows/Python2""" 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)) return path1 == path2
def samefile(file1, file2): # type: (str, str) -> bool """Provide an alternative for os.path.samefile on Windows/Python2""" 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)) return path1 == path2
[ "Provide", "an", "alternative", "for", "os", ".", "path", ".", "samefile", "on", "Windows", "/", "Python2" ]
pypa/pipenv
python
https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/patched/notpip/_internal/utils/compat.py#L214-L222
[ "def", "samefile", "(", "file1", ",", "file2", ")", ":", "# type: (str, str) -> bool", "if", "hasattr", "(", "os", ".", "path", ",", "'samefile'", ")", ":", "return", "os", ".", "path", ".", "samefile", "(", "file1", ",", "file2", ")", "else", ":", "pa...
cae8d76c210b9777e90aab76e9c4b0e53bb19cde
train
Entry.ensure_least_updates_possible
Mutate the current entry to ensure that we are making the smallest amount of changes possible to the existing lockfile -- this will keep the old locked versions of packages if they satisfy new constraints. :return: None
pipenv/resolver.py
def ensure_least_updates_possible(self): """ Mutate the current entry to ensure that we are making the smallest amount of changes possible to the existing lockfile -- this will keep the old locked versions of packages if they satisfy new constraints. :return: None """ constraints = self.get_constraints() can_use_original = True can_use_updated = True satisfied_by_versions = set() for constraint in constraints: if not constraint.specifier.contains(self.original_version): self.can_use_original = False if not constraint.specifier.contains(self.updated_version): self.can_use_updated = False satisfied_by_value = getattr(constraint, "satisfied_by", None) if satisfied_by_value: satisfied_by = "{0}".format( self.clean_specifier(str(satisfied_by_value.version)) ) satisfied_by_versions.add(satisfied_by) if can_use_original: self.entry_dict = self.lockfile_dict.copy() elif can_use_updated: if len(satisfied_by_versions) == 1: self.entry_dict["version"] = next(iter( sat_by for sat_by in satisfied_by_versions if sat_by ), None) hashes = None if self.lockfile_entry.specifiers == satisfied_by: ireq = self.lockfile_entry.as_ireq() if not self.lockfile_entry.hashes and self.resolver._should_include_hash(ireq): hashes = self.resolver.get_hash(ireq) else: hashes = self.lockfile_entry.hashes else: if self.resolver._should_include_hash(constraint): hashes = self.resolver.get_hash(constraint) if hashes: self.entry_dict["hashes"] = list(hashes) self._entry.hashes = frozenset(hashes) else: # check for any parents, since they depend on this and the current # installed versions are not compatible with the new version, so # we will need to update the top level dependency if possible self.check_flattened_parents()
def ensure_least_updates_possible(self): """ Mutate the current entry to ensure that we are making the smallest amount of changes possible to the existing lockfile -- this will keep the old locked versions of packages if they satisfy new constraints. :return: None """ constraints = self.get_constraints() can_use_original = True can_use_updated = True satisfied_by_versions = set() for constraint in constraints: if not constraint.specifier.contains(self.original_version): self.can_use_original = False if not constraint.specifier.contains(self.updated_version): self.can_use_updated = False satisfied_by_value = getattr(constraint, "satisfied_by", None) if satisfied_by_value: satisfied_by = "{0}".format( self.clean_specifier(str(satisfied_by_value.version)) ) satisfied_by_versions.add(satisfied_by) if can_use_original: self.entry_dict = self.lockfile_dict.copy() elif can_use_updated: if len(satisfied_by_versions) == 1: self.entry_dict["version"] = next(iter( sat_by for sat_by in satisfied_by_versions if sat_by ), None) hashes = None if self.lockfile_entry.specifiers == satisfied_by: ireq = self.lockfile_entry.as_ireq() if not self.lockfile_entry.hashes and self.resolver._should_include_hash(ireq): hashes = self.resolver.get_hash(ireq) else: hashes = self.lockfile_entry.hashes else: if self.resolver._should_include_hash(constraint): hashes = self.resolver.get_hash(constraint) if hashes: self.entry_dict["hashes"] = list(hashes) self._entry.hashes = frozenset(hashes) else: # check for any parents, since they depend on this and the current # installed versions are not compatible with the new version, so # we will need to update the top level dependency if possible self.check_flattened_parents()
[ "Mutate", "the", "current", "entry", "to", "ensure", "that", "we", "are", "making", "the", "smallest", "amount", "of", "changes", "possible", "to", "the", "existing", "lockfile", "--", "this", "will", "keep", "the", "old", "locked", "versions", "of", "packag...
pypa/pipenv
python
https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/resolver.py#L314-L361
[ "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", ...
cae8d76c210b9777e90aab76e9c4b0e53bb19cde
train
Entry.get_constraints
Retrieve all of the relevant constraints, aggregated from the pipfile, resolver, and parent dependencies and their respective conflict resolution where possible. :return: A set of **InstallRequirement** instances representing constraints :rtype: Set
pipenv/resolver.py
def get_constraints(self): """ Retrieve all of the relevant constraints, aggregated from the pipfile, resolver, and parent dependencies and their respective conflict resolution where possible. :return: A set of **InstallRequirement** instances representing constraints :rtype: Set """ 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: constraints.add(pipfile_constraint) return constraints
def get_constraints(self): """ Retrieve all of the relevant constraints, aggregated from the pipfile, resolver, and parent dependencies and their respective conflict resolution where possible. :return: A set of **InstallRequirement** instances representing constraints :rtype: Set """ 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: constraints.add(pipfile_constraint) return constraints
[ "Retrieve", "all", "of", "the", "relevant", "constraints", "aggregated", "from", "the", "pipfile", "resolver", "and", "parent", "dependencies", "and", "their", "respective", "conflict", "resolution", "where", "possible", "." ]
pypa/pipenv
python
https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/resolver.py#L363-L378
[ "def", "get_constraints", "(", "self", ")", ":", "constraints", "=", "{", "c", "for", "c", "in", "self", ".", "resolver", ".", "parsed_constraints", "if", "c", "and", "c", ".", "name", "==", "self", ".", "entry", ".", "name", "}", "pipfile_constraint", ...
cae8d76c210b9777e90aab76e9c4b0e53bb19cde
train
Entry.constraint_from_parent_conflicts
Given a resolved entry with multiple parent dependencies with different constraints, searches for the resolution that satisfies all of the parent constraints. :return: A new **InstallRequirement** satisfying all parent constraints :raises: :exc:`~pipenv.exceptions.DependencyConflict` if resolution is impossible
pipenv/resolver.py
def constraint_from_parent_conflicts(self): """ Given a resolved entry with multiple parent dependencies with different constraints, searches for the resolution that satisfies all of the parent constraints. :return: A new **InstallRequirement** satisfying all parent constraints :raises: :exc:`~pipenv.exceptions.DependencyConflict` if resolution is impossible """ # 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_original = True for p in self.parent_deps: # updated dependencies should be satisfied since they were resolved already if p.is_updated: continue # parents with no requirements can't conflict if not p.requirements: continue needed = p.requirements.get("dependencies", []) entry_ref = p.get_dependency(self.name) required = entry_ref.get("required_version", "*") required = self.clean_specifier(required) parent_requires = self.make_requirement(self.name, required) parent_dependencies.add("{0} => {1} ({2})".format(p.name, self.name, required)) if not parent_requires.requirement.specifier.contains(self.original_version): can_use_original = False if not parent_requires.requirement.specifier.contains(self.updated_version): has_mismatch = True if has_mismatch and not can_use_original: from pipenv.exceptions import DependencyConflict msg = ( "Cannot resolve {0} ({1}) due to conflicting parent dependencies: " "\n\t{2}".format( self.name, self.updated_version, "\n\t".join(parent_dependencies) ) ) raise DependencyConflict(msg) elif can_use_original: return self.lockfile_entry.as_ireq() return self.entry.as_ireq()
def constraint_from_parent_conflicts(self): """ Given a resolved entry with multiple parent dependencies with different constraints, searches for the resolution that satisfies all of the parent constraints. :return: A new **InstallRequirement** satisfying all parent constraints :raises: :exc:`~pipenv.exceptions.DependencyConflict` if resolution is impossible """ # 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_original = True for p in self.parent_deps: # updated dependencies should be satisfied since they were resolved already if p.is_updated: continue # parents with no requirements can't conflict if not p.requirements: continue needed = p.requirements.get("dependencies", []) entry_ref = p.get_dependency(self.name) required = entry_ref.get("required_version", "*") required = self.clean_specifier(required) parent_requires = self.make_requirement(self.name, required) parent_dependencies.add("{0} => {1} ({2})".format(p.name, self.name, required)) if not parent_requires.requirement.specifier.contains(self.original_version): can_use_original = False if not parent_requires.requirement.specifier.contains(self.updated_version): has_mismatch = True if has_mismatch and not can_use_original: from pipenv.exceptions import DependencyConflict msg = ( "Cannot resolve {0} ({1}) due to conflicting parent dependencies: " "\n\t{2}".format( self.name, self.updated_version, "\n\t".join(parent_dependencies) ) ) raise DependencyConflict(msg) elif can_use_original: return self.lockfile_entry.as_ireq() return self.entry.as_ireq()
[ "Given", "a", "resolved", "entry", "with", "multiple", "parent", "dependencies", "with", "different", "constraints", "searches", "for", "the", "resolution", "that", "satisfies", "all", "of", "the", "parent", "constraints", "." ]
pypa/pipenv
python
https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/resolver.py#L391-L433
[ "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...
cae8d76c210b9777e90aab76e9c4b0e53bb19cde
train
Entry.validate_constraints
Retrieves the full set of available constraints and iterate over them, validating that they exist and that they are not causing unresolvable conflicts. :return: True if the constraints are satisfied by the resolution provided :raises: :exc:`pipenv.exceptions.DependencyConflict` if the constraints dont exist
pipenv/resolver.py
def validate_constraints(self): """ Retrieves the full set of available constraints and iterate over them, validating that they exist and that they are not causing unresolvable conflicts. :return: True if the constraints are satisfied by the resolution provided :raises: :exc:`pipenv.exceptions.DependencyConflict` if the constraints dont exist """ constraints = self.get_constraints() for constraint in constraints: try: constraint.check_if_exists(False) except Exception: from pipenv.exceptions import DependencyConflict msg = ( "Cannot resolve conflicting version {0}{1} while {1}{2} is " "locked.".format( self.name, self.updated_specifier, self.old_name, self.old_specifiers ) ) raise DependencyConflict(msg) return True
def validate_constraints(self): """ Retrieves the full set of available constraints and iterate over them, validating that they exist and that they are not causing unresolvable conflicts. :return: True if the constraints are satisfied by the resolution provided :raises: :exc:`pipenv.exceptions.DependencyConflict` if the constraints dont exist """ constraints = self.get_constraints() for constraint in constraints: try: constraint.check_if_exists(False) except Exception: from pipenv.exceptions import DependencyConflict msg = ( "Cannot resolve conflicting version {0}{1} while {1}{2} is " "locked.".format( self.name, self.updated_specifier, self.old_name, self.old_specifiers ) ) raise DependencyConflict(msg) return True
[ "Retrieves", "the", "full", "set", "of", "available", "constraints", "and", "iterate", "over", "them", "validating", "that", "they", "exist", "and", "that", "they", "are", "not", "causing", "unresolvable", "conflicts", "." ]
pypa/pipenv
python
https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/resolver.py#L435-L456
[ "def", "validate_constraints", "(", "self", ")", ":", "constraints", "=", "self", ".", "get_constraints", "(", ")", "for", "constraint", "in", "constraints", ":", "try", ":", "constraint", ".", "check_if_exists", "(", "False", ")", "except", "Exception", ":", ...
cae8d76c210b9777e90aab76e9c4b0e53bb19cde
train
inject_into_urllib3
Monkey-patch urllib3 with SecureTransport-backed SSL-support.
pipenv/vendor/urllib3/contrib/securetransport.py
def inject_into_urllib3(): """ Monkey-patch urllib3 with SecureTransport-backed SSL-support. """ util.ssl_.SSLContext = SecureTransportContext util.HAS_SNI = HAS_SNI util.ssl_.HAS_SNI = HAS_SNI util.IS_SECURETRANSPORT = True util.ssl_.IS_SECURETRANSPORT = True
def inject_into_urllib3(): """ Monkey-patch urllib3 with SecureTransport-backed SSL-support. """ util.ssl_.SSLContext = SecureTransportContext util.HAS_SNI = HAS_SNI util.ssl_.HAS_SNI = HAS_SNI util.IS_SECURETRANSPORT = True util.ssl_.IS_SECURETRANSPORT = True
[ "Monkey", "-", "patch", "urllib3", "with", "SecureTransport", "-", "backed", "SSL", "-", "support", "." ]
pypa/pipenv
python
https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/vendor/urllib3/contrib/securetransport.py#L154-L162
[ "def", "inject_into_urllib3", "(", ")", ":", "util", ".", "ssl_", ".", "SSLContext", "=", "SecureTransportContext", "util", ".", "HAS_SNI", "=", "HAS_SNI", "util", ".", "ssl_", ".", "HAS_SNI", "=", "HAS_SNI", "util", ".", "IS_SECURETRANSPORT", "=", "True", "...
cae8d76c210b9777e90aab76e9c4b0e53bb19cde
train
extract_from_urllib3
Undo monkey-patching by :func:`inject_into_urllib3`.
pipenv/vendor/urllib3/contrib/securetransport.py
def extract_from_urllib3(): """ Undo monkey-patching by :func:`inject_into_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
def extract_from_urllib3(): """ Undo monkey-patching by :func:`inject_into_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
[ "Undo", "monkey", "-", "patching", "by", ":", "func", ":", "inject_into_urllib3", "." ]
pypa/pipenv
python
https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/vendor/urllib3/contrib/securetransport.py#L165-L173
[ "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", ...
cae8d76c210b9777e90aab76e9c4b0e53bb19cde
train
_read_callback
SecureTransport read callback. This is called by ST to request that data be returned from the socket.
pipenv/vendor/urllib3/contrib/securetransport.py
def _read_callback(connection_id, data_buffer, data_length_pointer): """ SecureTransport read callback. This is called by ST to request that data be returned from the socket. """ wrapped_socket = None try: wrapped_socket = _connection_refs.get(connection_id) if wrapped_socket is None: return SecurityConst.errSSLInternal base_socket = wrapped_socket.socket requested_length = data_length_pointer[0] timeout = wrapped_socket.gettimeout() error = None read_count = 0 try: while read_count < requested_length: if timeout is None or timeout >= 0: if not util.wait_for_read(base_socket, timeout): raise socket.error(errno.EAGAIN, 'timed out') remaining = requested_length - read_count buffer = (ctypes.c_char * remaining).from_address( data_buffer + read_count ) chunk_size = base_socket.recv_into(buffer, remaining) read_count += chunk_size if not chunk_size: if not read_count: return SecurityConst.errSSLClosedGraceful break except (socket.error) as e: error = e.errno if error is not None and error != errno.EAGAIN: data_length_pointer[0] = read_count if error == errno.ECONNRESET or error == errno.EPIPE: return SecurityConst.errSSLClosedAbort raise data_length_pointer[0] = read_count if read_count != requested_length: return SecurityConst.errSSLWouldBlock return 0 except Exception as e: if wrapped_socket is not None: wrapped_socket._exception = e return SecurityConst.errSSLInternal
def _read_callback(connection_id, data_buffer, data_length_pointer): """ SecureTransport read callback. This is called by ST to request that data be returned from the socket. """ wrapped_socket = None try: wrapped_socket = _connection_refs.get(connection_id) if wrapped_socket is None: return SecurityConst.errSSLInternal base_socket = wrapped_socket.socket requested_length = data_length_pointer[0] timeout = wrapped_socket.gettimeout() error = None read_count = 0 try: while read_count < requested_length: if timeout is None or timeout >= 0: if not util.wait_for_read(base_socket, timeout): raise socket.error(errno.EAGAIN, 'timed out') remaining = requested_length - read_count buffer = (ctypes.c_char * remaining).from_address( data_buffer + read_count ) chunk_size = base_socket.recv_into(buffer, remaining) read_count += chunk_size if not chunk_size: if not read_count: return SecurityConst.errSSLClosedGraceful break except (socket.error) as e: error = e.errno if error is not None and error != errno.EAGAIN: data_length_pointer[0] = read_count if error == errno.ECONNRESET or error == errno.EPIPE: return SecurityConst.errSSLClosedAbort raise data_length_pointer[0] = read_count if read_count != requested_length: return SecurityConst.errSSLWouldBlock return 0 except Exception as e: if wrapped_socket is not None: wrapped_socket._exception = e return SecurityConst.errSSLInternal
[ "SecureTransport", "read", "callback", ".", "This", "is", "called", "by", "ST", "to", "request", "that", "data", "be", "returned", "from", "the", "socket", "." ]
pypa/pipenv
python
https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/vendor/urllib3/contrib/securetransport.py#L176-L228
[ "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", "Non...
cae8d76c210b9777e90aab76e9c4b0e53bb19cde
train
_write_callback
SecureTransport write callback. This is called by ST to request that data actually be sent on the network.
pipenv/vendor/urllib3/contrib/securetransport.py
def _write_callback(connection_id, data_buffer, data_length_pointer): """ SecureTransport write callback. This is called by ST to request that data actually be sent on the network. """ wrapped_socket = None try: wrapped_socket = _connection_refs.get(connection_id) if wrapped_socket is None: return SecurityConst.errSSLInternal base_socket = wrapped_socket.socket bytes_to_write = data_length_pointer[0] data = ctypes.string_at(data_buffer, bytes_to_write) timeout = wrapped_socket.gettimeout() error = None sent = 0 try: while sent < bytes_to_write: if timeout is None or timeout >= 0: if not util.wait_for_write(base_socket, timeout): raise socket.error(errno.EAGAIN, 'timed out') chunk_sent = base_socket.send(data) sent += chunk_sent # This has some needless copying here, but I'm not sure there's # much value in optimising this data path. data = data[chunk_sent:] except (socket.error) as e: error = e.errno if error is not None and error != errno.EAGAIN: data_length_pointer[0] = sent if error == errno.ECONNRESET or error == errno.EPIPE: return SecurityConst.errSSLClosedAbort raise data_length_pointer[0] = sent if sent != bytes_to_write: return SecurityConst.errSSLWouldBlock return 0 except Exception as e: if wrapped_socket is not None: wrapped_socket._exception = e return SecurityConst.errSSLInternal
def _write_callback(connection_id, data_buffer, data_length_pointer): """ SecureTransport write callback. This is called by ST to request that data actually be sent on the network. """ wrapped_socket = None try: wrapped_socket = _connection_refs.get(connection_id) if wrapped_socket is None: return SecurityConst.errSSLInternal base_socket = wrapped_socket.socket bytes_to_write = data_length_pointer[0] data = ctypes.string_at(data_buffer, bytes_to_write) timeout = wrapped_socket.gettimeout() error = None sent = 0 try: while sent < bytes_to_write: if timeout is None or timeout >= 0: if not util.wait_for_write(base_socket, timeout): raise socket.error(errno.EAGAIN, 'timed out') chunk_sent = base_socket.send(data) sent += chunk_sent # This has some needless copying here, but I'm not sure there's # much value in optimising this data path. data = data[chunk_sent:] except (socket.error) as e: error = e.errno if error is not None and error != errno.EAGAIN: data_length_pointer[0] = sent if error == errno.ECONNRESET or error == errno.EPIPE: return SecurityConst.errSSLClosedAbort raise data_length_pointer[0] = sent if sent != bytes_to_write: return SecurityConst.errSSLWouldBlock return 0 except Exception as e: if wrapped_socket is not None: wrapped_socket._exception = e return SecurityConst.errSSLInternal
[ "SecureTransport", "write", "callback", ".", "This", "is", "called", "by", "ST", "to", "request", "that", "data", "actually", "be", "sent", "on", "the", "network", "." ]
pypa/pipenv
python
https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/vendor/urllib3/contrib/securetransport.py#L231-L279
[ "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", "No...
cae8d76c210b9777e90aab76e9c4b0e53bb19cde
train
WrappedSocket._raise_on_error
A context manager that can be used to wrap calls that do I/O from SecureTransport. If any of the I/O callbacks hit an exception, this context manager will correctly propagate the exception after the fact. This avoids silently swallowing those exceptions. It also correctly forces the socket closed.
pipenv/vendor/urllib3/contrib/securetransport.py
def _raise_on_error(self): """ A context manager that can be used to wrap calls that do I/O from SecureTransport. If any of the I/O callbacks hit an exception, this context manager will correctly propagate the exception after the fact. This avoids silently swallowing those exceptions. It also correctly forces the socket closed. """ 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._exception is not None: exception, self._exception = self._exception, None self.close() raise exception
def _raise_on_error(self): """ A context manager that can be used to wrap calls that do I/O from SecureTransport. If any of the I/O callbacks hit an exception, this context manager will correctly propagate the exception after the fact. This avoids silently swallowing those exceptions. It also correctly forces the socket closed. """ 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._exception is not None: exception, self._exception = self._exception, None self.close() raise exception
[ "A", "context", "manager", "that", "can", "be", "used", "to", "wrap", "calls", "that", "do", "I", "/", "O", "from", "SecureTransport", ".", "If", "any", "of", "the", "I", "/", "O", "callbacks", "hit", "an", "exception", "this", "context", "manager", "w...
pypa/pipenv
python
https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/vendor/urllib3/contrib/securetransport.py#L315-L333
[ "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...
cae8d76c210b9777e90aab76e9c4b0e53bb19cde
train
WrappedSocket._set_ciphers
Sets up the allowed ciphers. By default this matches the set in util.ssl_.DEFAULT_CIPHERS, at least as supported by macOS. This is done custom and doesn't allow changing at this time, mostly because parsing OpenSSL cipher strings is going to be a freaking nightmare.
pipenv/vendor/urllib3/contrib/securetransport.py
def _set_ciphers(self): """ Sets up the allowed ciphers. By default this matches the set in util.ssl_.DEFAULT_CIPHERS, at least as supported by macOS. This is done custom and doesn't allow changing at this time, mostly because parsing OpenSSL cipher strings is going to be a freaking nightmare. """ ciphers = (Security.SSLCipherSuite * len(CIPHER_SUITES))(*CIPHER_SUITES) result = Security.SSLSetEnabledCiphers( self.context, ciphers, len(CIPHER_SUITES) ) _assert_no_error(result)
def _set_ciphers(self): """ Sets up the allowed ciphers. By default this matches the set in util.ssl_.DEFAULT_CIPHERS, at least as supported by macOS. This is done custom and doesn't allow changing at this time, mostly because parsing OpenSSL cipher strings is going to be a freaking nightmare. """ ciphers = (Security.SSLCipherSuite * len(CIPHER_SUITES))(*CIPHER_SUITES) result = Security.SSLSetEnabledCiphers( self.context, ciphers, len(CIPHER_SUITES) ) _assert_no_error(result)
[ "Sets", "up", "the", "allowed", "ciphers", ".", "By", "default", "this", "matches", "the", "set", "in", "util", ".", "ssl_", ".", "DEFAULT_CIPHERS", "at", "least", "as", "supported", "by", "macOS", ".", "This", "is", "done", "custom", "and", "doesn", "t"...
pypa/pipenv
python
https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/vendor/urllib3/contrib/securetransport.py#L335-L346
[ "def", "_set_ciphers", "(", "self", ")", ":", "ciphers", "=", "(", "Security", ".", "SSLCipherSuite", "*", "len", "(", "CIPHER_SUITES", ")", ")", "(", "*", "CIPHER_SUITES", ")", "result", "=", "Security", ".", "SSLSetEnabledCiphers", "(", "self", ".", "con...
cae8d76c210b9777e90aab76e9c4b0e53bb19cde
train
WrappedSocket._custom_validate
Called when we have set custom validation. We do this in two cases: first, when cert validation is entirely disabled; and second, when using a custom trust DB.
pipenv/vendor/urllib3/contrib/securetransport.py
def _custom_validate(self, verify, trust_bundle): """ Called when we have set custom validation. We do this in two cases: first, when cert validation is entirely disabled; and second, when using a custom trust DB. """ # 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(trust_bundle, 'rb') as f: trust_bundle = f.read() cert_array = None trust = Security.SecTrustRef() try: # Get a CFArray that contains the certs we want. cert_array = _cert_array_from_pem(trust_bundle) # Ok, now the hard part. We want to get the SecTrustRef that ST has # created for this connection, shove our CAs into it, tell ST to # ignore everything else it knows, and then ask if it can build a # chain. This is a buuuunch of code. result = Security.SSLCopyPeerTrust( self.context, ctypes.byref(trust) ) _assert_no_error(result) if not trust: raise ssl.SSLError("Failed to copy trust reference") result = Security.SecTrustSetAnchorCertificates(trust, cert_array) _assert_no_error(result) result = Security.SecTrustSetAnchorCertificatesOnly(trust, True) _assert_no_error(result) trust_result = Security.SecTrustResultType() result = Security.SecTrustEvaluate( trust, ctypes.byref(trust_result) ) _assert_no_error(result) finally: if trust: CoreFoundation.CFRelease(trust) if cert_array is not None: CoreFoundation.CFRelease(cert_array) # Ok, now we can look at what the result was. successes = ( SecurityConst.kSecTrustResultUnspecified, SecurityConst.kSecTrustResultProceed ) if trust_result.value not in successes: raise ssl.SSLError( "certificate verify failed, error code: %d" % trust_result.value )
def _custom_validate(self, verify, trust_bundle): """ Called when we have set custom validation. We do this in two cases: first, when cert validation is entirely disabled; and second, when using a custom trust DB. """ # 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(trust_bundle, 'rb') as f: trust_bundle = f.read() cert_array = None trust = Security.SecTrustRef() try: # Get a CFArray that contains the certs we want. cert_array = _cert_array_from_pem(trust_bundle) # Ok, now the hard part. We want to get the SecTrustRef that ST has # created for this connection, shove our CAs into it, tell ST to # ignore everything else it knows, and then ask if it can build a # chain. This is a buuuunch of code. result = Security.SSLCopyPeerTrust( self.context, ctypes.byref(trust) ) _assert_no_error(result) if not trust: raise ssl.SSLError("Failed to copy trust reference") result = Security.SecTrustSetAnchorCertificates(trust, cert_array) _assert_no_error(result) result = Security.SecTrustSetAnchorCertificatesOnly(trust, True) _assert_no_error(result) trust_result = Security.SecTrustResultType() result = Security.SecTrustEvaluate( trust, ctypes.byref(trust_result) ) _assert_no_error(result) finally: if trust: CoreFoundation.CFRelease(trust) if cert_array is not None: CoreFoundation.CFRelease(cert_array) # Ok, now we can look at what the result was. successes = ( SecurityConst.kSecTrustResultUnspecified, SecurityConst.kSecTrustResultProceed ) if trust_result.value not in successes: raise ssl.SSLError( "certificate verify failed, error code: %d" % trust_result.value )
[ "Called", "when", "we", "have", "set", "custom", "validation", ".", "We", "do", "this", "in", "two", "cases", ":", "first", "when", "cert", "validation", "is", "entirely", "disabled", ";", "and", "second", "when", "using", "a", "custom", "trust", "DB", "...
pypa/pipenv
python
https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/vendor/urllib3/contrib/securetransport.py#L348-L408
[ "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", "(", "t...
cae8d76c210b9777e90aab76e9c4b0e53bb19cde
train
WrappedSocket.handshake
Actually performs the TLS handshake. This is run automatically by wrapped socket, and shouldn't be needed in user code.
pipenv/vendor/urllib3/contrib/securetransport.py
def handshake(self, server_hostname, verify, trust_bundle, min_version, max_version, client_cert, client_key, client_key_passphrase): """ Actually performs the TLS handshake. This is run automatically by wrapped socket, and shouldn't be needed in user code. """ # First, we do the initial bits of connection setup. We need to create # a context, set its I/O funcs, and set the connection reference. self.context = Security.SSLCreateContext( None, SecurityConst.kSSLClientSide, SecurityConst.kSSLStreamType ) result = Security.SSLSetIOFuncs( self.context, _read_callback_pointer, _write_callback_pointer ) _assert_no_error(result) # Here we need to compute the handle to use. We do this by taking the # id of self modulo 2**31 - 1. If this is already in the dictionary, we # just keep incrementing by one until we find a free space. with _connection_ref_lock: handle = id(self) % 2147483647 while handle in _connection_refs: handle = (handle + 1) % 2147483647 _connection_refs[handle] = self result = Security.SSLSetConnection(self.context, handle) _assert_no_error(result) # If we have a server hostname, we should set that too. if server_hostname: if not isinstance(server_hostname, bytes): server_hostname = server_hostname.encode('utf-8') result = Security.SSLSetPeerDomainName( self.context, server_hostname, len(server_hostname) ) _assert_no_error(result) # Setup the ciphers. self._set_ciphers() # Set the minimum and maximum TLS versions. result = Security.SSLSetProtocolVersionMin(self.context, min_version) _assert_no_error(result) result = Security.SSLSetProtocolVersionMax(self.context, max_version) _assert_no_error(result) # If there's a trust DB, we need to use it. We do that by telling # SecureTransport to break on server auth. We also do that if we don't # want to validate the certs at all: we just won't actually do any # authing in that case. if not verify or trust_bundle is not None: result = Security.SSLSetSessionOption( self.context, SecurityConst.kSSLSessionOptionBreakOnServerAuth, True ) _assert_no_error(result) # If there's a client cert, we need to use it. if client_cert: self._keychain, self._keychain_dir = _temporary_keychain() self._client_cert_chain = _load_client_cert_chain( self._keychain, client_cert, client_key ) result = Security.SSLSetCertificate( self.context, self._client_cert_chain ) _assert_no_error(result) while True: with self._raise_on_error(): result = Security.SSLHandshake(self.context) if result == SecurityConst.errSSLWouldBlock: raise socket.timeout("handshake timed out") elif result == SecurityConst.errSSLServerAuthCompleted: self._custom_validate(verify, trust_bundle) continue else: _assert_no_error(result) break
def handshake(self, server_hostname, verify, trust_bundle, min_version, max_version, client_cert, client_key, client_key_passphrase): """ Actually performs the TLS handshake. This is run automatically by wrapped socket, and shouldn't be needed in user code. """ # First, we do the initial bits of connection setup. We need to create # a context, set its I/O funcs, and set the connection reference. self.context = Security.SSLCreateContext( None, SecurityConst.kSSLClientSide, SecurityConst.kSSLStreamType ) result = Security.SSLSetIOFuncs( self.context, _read_callback_pointer, _write_callback_pointer ) _assert_no_error(result) # Here we need to compute the handle to use. We do this by taking the # id of self modulo 2**31 - 1. If this is already in the dictionary, we # just keep incrementing by one until we find a free space. with _connection_ref_lock: handle = id(self) % 2147483647 while handle in _connection_refs: handle = (handle + 1) % 2147483647 _connection_refs[handle] = self result = Security.SSLSetConnection(self.context, handle) _assert_no_error(result) # If we have a server hostname, we should set that too. if server_hostname: if not isinstance(server_hostname, bytes): server_hostname = server_hostname.encode('utf-8') result = Security.SSLSetPeerDomainName( self.context, server_hostname, len(server_hostname) ) _assert_no_error(result) # Setup the ciphers. self._set_ciphers() # Set the minimum and maximum TLS versions. result = Security.SSLSetProtocolVersionMin(self.context, min_version) _assert_no_error(result) result = Security.SSLSetProtocolVersionMax(self.context, max_version) _assert_no_error(result) # If there's a trust DB, we need to use it. We do that by telling # SecureTransport to break on server auth. We also do that if we don't # want to validate the certs at all: we just won't actually do any # authing in that case. if not verify or trust_bundle is not None: result = Security.SSLSetSessionOption( self.context, SecurityConst.kSSLSessionOptionBreakOnServerAuth, True ) _assert_no_error(result) # If there's a client cert, we need to use it. if client_cert: self._keychain, self._keychain_dir = _temporary_keychain() self._client_cert_chain = _load_client_cert_chain( self._keychain, client_cert, client_key ) result = Security.SSLSetCertificate( self.context, self._client_cert_chain ) _assert_no_error(result) while True: with self._raise_on_error(): result = Security.SSLHandshake(self.context) if result == SecurityConst.errSSLWouldBlock: raise socket.timeout("handshake timed out") elif result == SecurityConst.errSSLServerAuthCompleted: self._custom_validate(verify, trust_bundle) continue else: _assert_no_error(result) break
[ "Actually", "performs", "the", "TLS", "handshake", ".", "This", "is", "run", "automatically", "by", "wrapped", "socket", "and", "shouldn", "t", "be", "needed", "in", "user", "code", "." ]
pypa/pipenv
python
https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/vendor/urllib3/contrib/securetransport.py#L410-L498
[ "def", "handshake", "(", "self", ",", "server_hostname", ",", "verify", ",", "trust_bundle", ",", "min_version", ",", "max_version", ",", "client_cert", ",", "client_key", ",", "client_key_passphrase", ")", ":", "# First, we do the initial bits of connection setup. We nee...
cae8d76c210b9777e90aab76e9c4b0e53bb19cde
train
Bucket.write_bytecode
Dump the bytecode into the file or file like object passed.
pipenv/vendor/jinja2/bccache.py
def write_bytecode(self, f): """Dump the bytecode into the file or file like object passed.""" 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)
def write_bytecode(self, f): """Dump the bytecode into the file or file like object passed.""" 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", "." ]
pypa/pipenv
python
https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/vendor/jinja2/bccache.py#L98-L104
[ "def", "write_bytecode", "(", "self", ",", "f", ")", ":", "if", "self", ".", "code", "is", "None", ":", "raise", "TypeError", "(", "'can\\'t write empty bucket'", ")", "f", ".", "write", "(", "bc_magic", ")", "pickle", ".", "dump", "(", "self", ".", "c...
cae8d76c210b9777e90aab76e9c4b0e53bb19cde
train
BytecodeCache.get_cache_key
Returns the unique hash key for this template name.
pipenv/vendor/jinja2/bccache.py
def get_cache_key(self, name, filename=None): """Returns the unique hash key for this template name.""" hash = sha1(name.encode('utf-8')) if filename is not None: filename = '|' + filename if isinstance(filename, text_type): filename = filename.encode('utf-8') hash.update(filename) return hash.hexdigest()
def get_cache_key(self, name, filename=None): """Returns the unique hash key for this template name.""" hash = sha1(name.encode('utf-8')) if filename is not None: filename = '|' + filename if isinstance(filename, text_type): filename = filename.encode('utf-8') hash.update(filename) return hash.hexdigest()
[ "Returns", "the", "unique", "hash", "key", "for", "this", "template", "name", "." ]
pypa/pipenv
python
https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/vendor/jinja2/bccache.py#L166-L174
[ "def", "get_cache_key", "(", "self", ",", "name", ",", "filename", "=", "None", ")", ":", "hash", "=", "sha1", "(", "name", ".", "encode", "(", "'utf-8'", ")", ")", "if", "filename", "is", "not", "None", ":", "filename", "=", "'|'", "+", "filename", ...
cae8d76c210b9777e90aab76e9c4b0e53bb19cde
train
BytecodeCache.get_bucket
Return a cache bucket for the given template. All arguments are mandatory but filename may be `None`.
pipenv/vendor/jinja2/bccache.py
def get_bucket(self, environment, name, filename, source): """Return a cache bucket for the given template. All arguments are mandatory but filename may be `None`. """ key = self.get_cache_key(name, filename) checksum = self.get_source_checksum(source) bucket = Bucket(environment, key, checksum) self.load_bytecode(bucket) return bucket
def get_bucket(self, environment, name, filename, source): """Return a cache bucket for the given template. All arguments are mandatory but filename may be `None`. """ key = self.get_cache_key(name, filename) checksum = self.get_source_checksum(source) bucket = Bucket(environment, key, checksum) self.load_bytecode(bucket) return bucket
[ "Return", "a", "cache", "bucket", "for", "the", "given", "template", ".", "All", "arguments", "are", "mandatory", "but", "filename", "may", "be", "None", "." ]
pypa/pipenv
python
https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/vendor/jinja2/bccache.py#L180-L188
[ "def", "get_bucket", "(", "self", ",", "environment", ",", "name", ",", "filename", ",", "source", ")", ":", "key", "=", "self", ".", "get_cache_key", "(", "name", ",", "filename", ")", "checksum", "=", "self", ".", "get_source_checksum", "(", "source", ...
cae8d76c210b9777e90aab76e9c4b0e53bb19cde
train
lookup
Look for an encoding by its label. This is the spec’s `get an encoding <http://encoding.spec.whatwg.org/#concept-encoding-get>`_ algorithm. Supported labels are listed there. :param label: A string. :returns: An :class:`Encoding` object, or :obj:`None` for an unknown label.
pipenv/patched/notpip/_vendor/webencodings/__init__.py
def lookup(label): """ Look for an encoding by its label. This is the spec’s `get an encoding <http://encoding.spec.whatwg.org/#concept-encoding-get>`_ algorithm. Supported labels are listed there. :param label: A string. :returns: An :class:`Encoding` object, or :obj:`None` for an unknown 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 None: if name == 'x-user-defined': from .x_user_defined import codec_info else: python_name = PYTHON_NAMES.get(name, name) # Any python_name value that gets to here should be valid. codec_info = codecs.lookup(python_name) encoding = Encoding(name, codec_info) CACHE[name] = encoding return encoding
def lookup(label): """ Look for an encoding by its label. This is the spec’s `get an encoding <http://encoding.spec.whatwg.org/#concept-encoding-get>`_ algorithm. Supported labels are listed there. :param label: A string. :returns: An :class:`Encoding` object, or :obj:`None` for an unknown 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 None: if name == 'x-user-defined': from .x_user_defined import codec_info else: python_name = PYTHON_NAMES.get(name, name) # Any python_name value that gets to here should be valid. codec_info = codecs.lookup(python_name) encoding = Encoding(name, codec_info) CACHE[name] = encoding return encoding
[ "Look", "for", "an", "encoding", "by", "its", "label", ".", "This", "is", "the", "spec’s", "get", "an", "encoding", "<http", ":", "//", "encoding", ".", "spec", ".", "whatwg", ".", "org", "/", "#concept", "-", "encoding", "-", "get", ">", "_", "algor...
pypa/pipenv
python
https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/patched/notpip/_vendor/webencodings/__init__.py#L61-L88
[ "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", ")", ...
cae8d76c210b9777e90aab76e9c4b0e53bb19cde
train
_get_encoding
Accept either an encoding object or label. :param encoding: An :class:`Encoding` object or a label string. :returns: An :class:`Encoding` object. :raises: :exc:`~exceptions.LookupError` for an unknown label.
pipenv/patched/notpip/_vendor/webencodings/__init__.py
def _get_encoding(encoding_or_label): """ Accept either an encoding object or label. :param encoding: An :class:`Encoding` object or a label string. :returns: An :class:`Encoding` object. :raises: :exc:`~exceptions.LookupError` for an unknown 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) return encoding
def _get_encoding(encoding_or_label): """ Accept either an encoding object or label. :param encoding: An :class:`Encoding` object or a label string. :returns: An :class:`Encoding` object. :raises: :exc:`~exceptions.LookupError` for an unknown 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) return encoding
[ "Accept", "either", "an", "encoding", "object", "or", "label", "." ]
pypa/pipenv
python
https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/patched/notpip/_vendor/webencodings/__init__.py#L91-L106
[ "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", ":", "r...
cae8d76c210b9777e90aab76e9c4b0e53bb19cde
train
decode
Decode a single string. :param input: A byte string :param fallback_encoding: An :class:`Encoding` object or a label string. The encoding to use if :obj:`input` does note have a BOM. :param errors: Type of error handling. See :func:`codecs.register`. :raises: :exc:`~exceptions.LookupError` for an unknown encoding label. :return: A ``(output, encoding)`` tuple of an Unicode string and an :obj:`Encoding`.
pipenv/patched/notpip/_vendor/webencodings/__init__.py
def decode(input, fallback_encoding, errors='replace'): """ Decode a single string. :param input: A byte string :param fallback_encoding: An :class:`Encoding` object or a label string. The encoding to use if :obj:`input` does note have a BOM. :param errors: Type of error handling. See :func:`codecs.register`. :raises: :exc:`~exceptions.LookupError` for an unknown encoding label. :return: A ``(output, encoding)`` tuple of an Unicode string and an :obj:`Encoding`. """ # 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 encoding.codec_info.decode(input, errors)[0], encoding
def decode(input, fallback_encoding, errors='replace'): """ Decode a single string. :param input: A byte string :param fallback_encoding: An :class:`Encoding` object or a label string. The encoding to use if :obj:`input` does note have a BOM. :param errors: Type of error handling. See :func:`codecs.register`. :raises: :exc:`~exceptions.LookupError` for an unknown encoding label. :return: A ``(output, encoding)`` tuple of an Unicode string and an :obj:`Encoding`. """ # 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 encoding.codec_info.decode(input, errors)[0], encoding
[ "Decode", "a", "single", "string", "." ]
pypa/pipenv
python
https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/patched/notpip/_vendor/webencodings/__init__.py#L139-L158
[ "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_b...
cae8d76c210b9777e90aab76e9c4b0e53bb19cde
train
_detect_bom
Return (bom_encoding, input), with any BOM removed from the input.
pipenv/patched/notpip/_vendor/webencodings/__init__.py
def _detect_bom(input): """Return (bom_encoding, input), with any BOM removed from the 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
def _detect_bom(input): """Return (bom_encoding, input), with any BOM removed from the 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", "." ]
pypa/pipenv
python
https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/patched/notpip/_vendor/webencodings/__init__.py#L161-L169
[ "def", "_detect_bom", "(", "input", ")", ":", "if", "input", ".", "startswith", "(", "b'\\xFF\\xFE'", ")", ":", "return", "_UTF16LE", ",", "input", "[", "2", ":", "]", "if", "input", ".", "startswith", "(", "b'\\xFE\\xFF'", ")", ":", "return", "_UTF16BE"...
cae8d76c210b9777e90aab76e9c4b0e53bb19cde
train
encode
Encode a single string. :param input: An Unicode string. :param encoding: An :class:`Encoding` object or a label string. :param errors: Type of error handling. See :func:`codecs.register`. :raises: :exc:`~exceptions.LookupError` for an unknown encoding label. :return: A byte string.
pipenv/patched/notpip/_vendor/webencodings/__init__.py
def encode(input, encoding=UTF8, errors='strict'): """ Encode a single string. :param input: An Unicode string. :param encoding: An :class:`Encoding` object or a label string. :param errors: Type of error handling. See :func:`codecs.register`. :raises: :exc:`~exceptions.LookupError` for an unknown encoding label. :return: A byte string. """ return _get_encoding(encoding).codec_info.encode(input, errors)[0]
def encode(input, encoding=UTF8, errors='strict'): """ Encode a single string. :param input: An Unicode string. :param encoding: An :class:`Encoding` object or a label string. :param errors: Type of error handling. See :func:`codecs.register`. :raises: :exc:`~exceptions.LookupError` for an unknown encoding label. :return: A byte string. """ return _get_encoding(encoding).codec_info.encode(input, errors)[0]
[ "Encode", "a", "single", "string", "." ]
pypa/pipenv
python
https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/patched/notpip/_vendor/webencodings/__init__.py#L172-L183
[ "def", "encode", "(", "input", ",", "encoding", "=", "UTF8", ",", "errors", "=", "'strict'", ")", ":", "return", "_get_encoding", "(", "encoding", ")", ".", "codec_info", ".", "encode", "(", "input", ",", "errors", ")", "[", "0", "]" ]
cae8d76c210b9777e90aab76e9c4b0e53bb19cde
train
iter_decode
"Pull"-based decoder. :param input: An iterable of byte strings. The input is first consumed just enough to determine the encoding based on the precense of a BOM, then consumed on demand when the return value is. :param fallback_encoding: An :class:`Encoding` object or a label string. The encoding to use if :obj:`input` does note have a BOM. :param errors: Type of error handling. See :func:`codecs.register`. :raises: :exc:`~exceptions.LookupError` for an unknown encoding label. :returns: An ``(output, encoding)`` tuple. :obj:`output` is an iterable of Unicode strings, :obj:`encoding` is the :obj:`Encoding` that is being used.
pipenv/patched/notpip/_vendor/webencodings/__init__.py
def iter_decode(input, fallback_encoding, errors='replace'): """ "Pull"-based decoder. :param input: An iterable of byte strings. The input is first consumed just enough to determine the encoding based on the precense of a BOM, then consumed on demand when the return value is. :param fallback_encoding: An :class:`Encoding` object or a label string. The encoding to use if :obj:`input` does note have a BOM. :param errors: Type of error handling. See :func:`codecs.register`. :raises: :exc:`~exceptions.LookupError` for an unknown encoding label. :returns: An ``(output, encoding)`` tuple. :obj:`output` is an iterable of Unicode strings, :obj:`encoding` is the :obj:`Encoding` that is being used. """ decoder = IncrementalDecoder(fallback_encoding, errors) generator = _iter_decode_generator(input, decoder) encoding = next(generator) return generator, encoding
def iter_decode(input, fallback_encoding, errors='replace'): """ "Pull"-based decoder. :param input: An iterable of byte strings. The input is first consumed just enough to determine the encoding based on the precense of a BOM, then consumed on demand when the return value is. :param fallback_encoding: An :class:`Encoding` object or a label string. The encoding to use if :obj:`input` does note have a BOM. :param errors: Type of error handling. See :func:`codecs.register`. :raises: :exc:`~exceptions.LookupError` for an unknown encoding label. :returns: An ``(output, encoding)`` tuple. :obj:`output` is an iterable of Unicode strings, :obj:`encoding` is the :obj:`Encoding` that is being used. """ decoder = IncrementalDecoder(fallback_encoding, errors) generator = _iter_decode_generator(input, decoder) encoding = next(generator) return generator, encoding
[ "Pull", "-", "based", "decoder", "." ]
pypa/pipenv
python
https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/patched/notpip/_vendor/webencodings/__init__.py#L186-L211
[ "def", "iter_decode", "(", "input", ",", "fallback_encoding", ",", "errors", "=", "'replace'", ")", ":", "decoder", "=", "IncrementalDecoder", "(", "fallback_encoding", ",", "errors", ")", "generator", "=", "_iter_decode_generator", "(", "input", ",", "decoder", ...
cae8d76c210b9777e90aab76e9c4b0e53bb19cde
train
_iter_decode_generator
Return a generator that first yields the :obj:`Encoding`, then yields output chukns as Unicode strings.
pipenv/patched/notpip/_vendor/webencodings/__init__.py
def _iter_decode_generator(input, decoder): """Return a generator that first yields the :obj:`Encoding`, then yields output chukns as Unicode strings. """ decode = decoder.decode input = iter(input) for chunck in input: output = decode(chunck) if output: assert decoder.encoding is not None yield decoder.encoding yield output break else: # Input exhausted without determining the encoding output = decode(b'', final=True) assert decoder.encoding is not None yield decoder.encoding if output: yield output return for chunck in input: output = decode(chunck) if output: yield output output = decode(b'', final=True) if output: yield output
def _iter_decode_generator(input, decoder): """Return a generator that first yields the :obj:`Encoding`, then yields output chukns as Unicode strings. """ decode = decoder.decode input = iter(input) for chunck in input: output = decode(chunck) if output: assert decoder.encoding is not None yield decoder.encoding yield output break else: # Input exhausted without determining the encoding output = decode(b'', final=True) assert decoder.encoding is not None yield decoder.encoding if output: yield output return for chunck in input: output = decode(chunck) if output: yield output output = decode(b'', final=True) if output: yield output
[ "Return", "a", "generator", "that", "first", "yields", "the", ":", "obj", ":", "Encoding", "then", "yields", "output", "chukns", "as", "Unicode", "strings", "." ]
pypa/pipenv
python
https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/patched/notpip/_vendor/webencodings/__init__.py#L214-L243
[ "def", "_iter_decode_generator", "(", "input", ",", "decoder", ")", ":", "decode", "=", "decoder", ".", "decode", "input", "=", "iter", "(", "input", ")", "for", "chunck", "in", "input", ":", "output", "=", "decode", "(", "chunck", ")", "if", "output", ...
cae8d76c210b9777e90aab76e9c4b0e53bb19cde
train
iter_encode
“Pull”-based encoder. :param input: An iterable of Unicode strings. :param encoding: An :class:`Encoding` object or a label string. :param errors: Type of error handling. See :func:`codecs.register`. :raises: :exc:`~exceptions.LookupError` for an unknown encoding label. :returns: An iterable of byte strings.
pipenv/patched/notpip/_vendor/webencodings/__init__.py
def iter_encode(input, encoding=UTF8, errors='strict'): """ “Pull”-based encoder. :param input: An iterable of Unicode strings. :param encoding: An :class:`Encoding` object or a label string. :param errors: Type of error handling. See :func:`codecs.register`. :raises: :exc:`~exceptions.LookupError` for an unknown encoding label. :returns: An iterable of byte strings. """ # Fail early if `encoding` is an invalid label. encode = IncrementalEncoder(encoding, errors).encode return _iter_encode_generator(input, encode)
def iter_encode(input, encoding=UTF8, errors='strict'): """ “Pull”-based encoder. :param input: An iterable of Unicode strings. :param encoding: An :class:`Encoding` object or a label string. :param errors: Type of error handling. See :func:`codecs.register`. :raises: :exc:`~exceptions.LookupError` for an unknown encoding label. :returns: An iterable of byte strings. """ # Fail early if `encoding` is an invalid label. encode = IncrementalEncoder(encoding, errors).encode return _iter_encode_generator(input, encode)
[ "“Pull”", "-", "based", "encoder", "." ]
pypa/pipenv
python
https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/patched/notpip/_vendor/webencodings/__init__.py#L246-L259
[ "def", "iter_encode", "(", "input", ",", "encoding", "=", "UTF8", ",", "errors", "=", "'strict'", ")", ":", "# Fail early if `encoding` is an invalid label.", "encode", "=", "IncrementalEncoder", "(", "encoding", ",", "errors", ")", ".", "encode", "return", "_iter...
cae8d76c210b9777e90aab76e9c4b0e53bb19cde
train
IncrementalDecoder.decode
Decode one chunk of the input. :param input: A byte string. :param final: Indicate that no more input is available. Must be :obj:`True` if this is the last call. :returns: An Unicode string.
pipenv/patched/notpip/_vendor/webencodings/__init__.py
def decode(self, input, final=False): """Decode one chunk of the input. :param input: A byte string. :param final: Indicate that no more input is available. Must be :obj:`True` if this is the last call. :returns: An Unicode string. """ 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: if len(input) < 3 and not final: # Not enough data yet. self._buffer = input return '' else: # No BOM encoding = self._fallback_encoding decoder = encoding.codec_info.incrementaldecoder(self._errors).decode self._decoder = decoder self.encoding = encoding return decoder(input, final)
def decode(self, input, final=False): """Decode one chunk of the input. :param input: A byte string. :param final: Indicate that no more input is available. Must be :obj:`True` if this is the last call. :returns: An Unicode string. """ 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: if len(input) < 3 and not final: # Not enough data yet. self._buffer = input return '' else: # No BOM encoding = self._fallback_encoding decoder = encoding.codec_info.incrementaldecoder(self._errors).decode self._decoder = decoder self.encoding = encoding return decoder(input, final)
[ "Decode", "one", "chunk", "of", "the", "input", "." ]
pypa/pipenv
python
https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/patched/notpip/_vendor/webencodings/__init__.py#L295-L320
[ "def", "decode", "(", "self", ",", "input", ",", "final", "=", "False", ")", ":", "decoder", "=", "self", ".", "_decoder", "if", "decoder", "is", "not", "None", ":", "return", "decoder", "(", "input", ",", "final", ")", "input", "=", "self", ".", "...
cae8d76c210b9777e90aab76e9c4b0e53bb19cde
train
_cf_dictionary_from_tuples
Given a list of Python tuples, create an associated CFDictionary.
pipenv/vendor/urllib3/contrib/_securetransport/low_level.py
def _cf_dictionary_from_tuples(tuples): """ Given a list of Python tuples, create an associated CFDictionary. """ 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 * dictionary_size)(*keys) cf_values = (CoreFoundation.CFTypeRef * dictionary_size)(*values) return CoreFoundation.CFDictionaryCreate( CoreFoundation.kCFAllocatorDefault, cf_keys, cf_values, dictionary_size, CoreFoundation.kCFTypeDictionaryKeyCallBacks, CoreFoundation.kCFTypeDictionaryValueCallBacks, )
def _cf_dictionary_from_tuples(tuples): """ Given a list of Python tuples, create an associated CFDictionary. """ 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 * dictionary_size)(*keys) cf_values = (CoreFoundation.CFTypeRef * dictionary_size)(*values) return CoreFoundation.CFDictionaryCreate( CoreFoundation.kCFAllocatorDefault, cf_keys, cf_values, dictionary_size, CoreFoundation.kCFTypeDictionaryKeyCallBacks, CoreFoundation.kCFTypeDictionaryValueCallBacks, )
[ "Given", "a", "list", "of", "Python", "tuples", "create", "an", "associated", "CFDictionary", "." ]
pypa/pipenv
python
https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/vendor/urllib3/contrib/_securetransport/low_level.py#L37-L56
[ "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"...
cae8d76c210b9777e90aab76e9c4b0e53bb19cde
train
_cf_string_to_unicode
Creates a Unicode string from a CFString object. Used entirely for error reporting. Yes, it annoys me quite a lot that this function is this complex.
pipenv/vendor/urllib3/contrib/_securetransport/low_level.py
def _cf_string_to_unicode(value): """ Creates a Unicode string from a CFString object. Used entirely for error reporting. Yes, it annoys me quite a lot that this function is this complex. """ 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 = ctypes.create_string_buffer(1024) result = CoreFoundation.CFStringGetCString( value_as_void_p, buffer, 1024, CFConst.kCFStringEncodingUTF8 ) if not result: raise OSError('Error copying C string from CFStringRef') string = buffer.value if string is not None: string = string.decode('utf-8') return string
def _cf_string_to_unicode(value): """ Creates a Unicode string from a CFString object. Used entirely for error reporting. Yes, it annoys me quite a lot that this function is this complex. """ 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 = ctypes.create_string_buffer(1024) result = CoreFoundation.CFStringGetCString( value_as_void_p, buffer, 1024, CFConst.kCFStringEncodingUTF8 ) if not result: raise OSError('Error copying C string from CFStringRef') string = buffer.value if string is not None: string = string.decode('utf-8') return string
[ "Creates", "a", "Unicode", "string", "from", "a", "CFString", "object", ".", "Used", "entirely", "for", "error", "reporting", "." ]
pypa/pipenv
python
https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/vendor/urllib3/contrib/_securetransport/low_level.py#L59-L85
[ "def", "_cf_string_to_unicode", "(", "value", ")", ":", "value_as_void_p", "=", "ctypes", ".", "cast", "(", "value", ",", "ctypes", ".", "POINTER", "(", "ctypes", ".", "c_void_p", ")", ")", "string", "=", "CoreFoundation", ".", "CFStringGetCStringPtr", "(", ...
cae8d76c210b9777e90aab76e9c4b0e53bb19cde
train
_assert_no_error
Checks the return code and throws an exception if there is an error to report
pipenv/vendor/urllib3/contrib/_securetransport/low_level.py
def _assert_no_error(error, exception_class=None): """ Checks the return code and throws an exception if there is an error to report """ 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 is None or output == u'': output = u'OSStatus %s' % error if exception_class is None: exception_class = ssl.SSLError raise exception_class(output)
def _assert_no_error(error, exception_class=None): """ Checks the return code and throws an exception if there is an error to report """ 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 is None or output == u'': output = u'OSStatus %s' % error if exception_class is None: exception_class = ssl.SSLError raise exception_class(output)
[ "Checks", "the", "return", "code", "and", "throws", "an", "exception", "if", "there", "is", "an", "error", "to", "report" ]
pypa/pipenv
python
https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/vendor/urllib3/contrib/_securetransport/low_level.py#L88-L106
[ "def", "_assert_no_error", "(", "error", ",", "exception_class", "=", "None", ")", ":", "if", "error", "==", "0", ":", "return", "cf_error_string", "=", "Security", ".", "SecCopyErrorMessageString", "(", "error", ",", "None", ")", "output", "=", "_cf_string_to...
cae8d76c210b9777e90aab76e9c4b0e53bb19cde
train
_cert_array_from_pem
Given a bundle of certs in PEM format, turns them into a CFArray of certs that can be used to validate a cert chain.
pipenv/vendor/urllib3/contrib/_securetransport/low_level.py
def _cert_array_from_pem(pem_bundle): """ Given a bundle of certs in PEM format, turns them into a CFArray of certs that can be used to validate a cert chain. """ # 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 der_certs: raise ssl.SSLError("No root certificates specified") cert_array = CoreFoundation.CFArrayCreateMutable( CoreFoundation.kCFAllocatorDefault, 0, ctypes.byref(CoreFoundation.kCFTypeArrayCallBacks) ) if not cert_array: raise ssl.SSLError("Unable to allocate memory!") try: for der_bytes in der_certs: certdata = _cf_data_from_bytes(der_bytes) if not certdata: raise ssl.SSLError("Unable to allocate memory!") cert = Security.SecCertificateCreateWithData( CoreFoundation.kCFAllocatorDefault, certdata ) CoreFoundation.CFRelease(certdata) if not cert: raise ssl.SSLError("Unable to build cert object!") CoreFoundation.CFArrayAppendValue(cert_array, cert) CoreFoundation.CFRelease(cert) except Exception: # We need to free the array before the exception bubbles further. # We only want to do that if an error occurs: otherwise, the caller # should free. CoreFoundation.CFRelease(cert_array) return cert_array
def _cert_array_from_pem(pem_bundle): """ Given a bundle of certs in PEM format, turns them into a CFArray of certs that can be used to validate a cert chain. """ # 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 der_certs: raise ssl.SSLError("No root certificates specified") cert_array = CoreFoundation.CFArrayCreateMutable( CoreFoundation.kCFAllocatorDefault, 0, ctypes.byref(CoreFoundation.kCFTypeArrayCallBacks) ) if not cert_array: raise ssl.SSLError("Unable to allocate memory!") try: for der_bytes in der_certs: certdata = _cf_data_from_bytes(der_bytes) if not certdata: raise ssl.SSLError("Unable to allocate memory!") cert = Security.SecCertificateCreateWithData( CoreFoundation.kCFAllocatorDefault, certdata ) CoreFoundation.CFRelease(certdata) if not cert: raise ssl.SSLError("Unable to build cert object!") CoreFoundation.CFArrayAppendValue(cert_array, cert) CoreFoundation.CFRelease(cert) except Exception: # We need to free the array before the exception bubbles further. # We only want to do that if an error occurs: otherwise, the caller # should free. CoreFoundation.CFRelease(cert_array) return cert_array
[ "Given", "a", "bundle", "of", "certs", "in", "PEM", "format", "turns", "them", "into", "a", "CFArray", "of", "certs", "that", "can", "be", "used", "to", "validate", "a", "cert", "chain", "." ]
pypa/pipenv
python
https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/vendor/urllib3/contrib/_securetransport/low_level.py#L109-L152
[ "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", ".",...
cae8d76c210b9777e90aab76e9c4b0e53bb19cde
train
_temporary_keychain
This function creates a temporary Mac keychain that we can use to work with credentials. This keychain uses a one-time password and a temporary file to store the data. We expect to have one keychain per socket. The returned SecKeychainRef must be freed by the caller, including calling SecKeychainDelete. Returns a tuple of the SecKeychainRef and the path to the temporary directory that contains it.
pipenv/vendor/urllib3/contrib/_securetransport/low_level.py
def _temporary_keychain(): """ This function creates a temporary Mac keychain that we can use to work with credentials. This keychain uses a one-time password and a temporary file to store the data. We expect to have one keychain per socket. The returned SecKeychainRef must be freed by the caller, including calling SecKeychainDelete. Returns a tuple of the SecKeychainRef and the path to the temporary directory that contains it. """ # 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 filename will be 8 random bytes expanded into base64. We also need # some random bytes to password-protect the keychain we're creating, so we # ask for 40 random bytes. random_bytes = os.urandom(40) filename = base64.b16encode(random_bytes[:8]).decode('utf-8') password = base64.b16encode(random_bytes[8:]) # Must be valid UTF-8 tempdirectory = tempfile.mkdtemp() keychain_path = os.path.join(tempdirectory, filename).encode('utf-8') # We now want to create the keychain itself. keychain = Security.SecKeychainRef() status = Security.SecKeychainCreate( keychain_path, len(password), password, False, None, ctypes.byref(keychain) ) _assert_no_error(status) # Having created the keychain, we want to pass it off to the caller. return keychain, tempdirectory
def _temporary_keychain(): """ This function creates a temporary Mac keychain that we can use to work with credentials. This keychain uses a one-time password and a temporary file to store the data. We expect to have one keychain per socket. The returned SecKeychainRef must be freed by the caller, including calling SecKeychainDelete. Returns a tuple of the SecKeychainRef and the path to the temporary directory that contains it. """ # 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 filename will be 8 random bytes expanded into base64. We also need # some random bytes to password-protect the keychain we're creating, so we # ask for 40 random bytes. random_bytes = os.urandom(40) filename = base64.b16encode(random_bytes[:8]).decode('utf-8') password = base64.b16encode(random_bytes[8:]) # Must be valid UTF-8 tempdirectory = tempfile.mkdtemp() keychain_path = os.path.join(tempdirectory, filename).encode('utf-8') # We now want to create the keychain itself. keychain = Security.SecKeychainRef() status = Security.SecKeychainCreate( keychain_path, len(password), password, False, None, ctypes.byref(keychain) ) _assert_no_error(status) # Having created the keychain, we want to pass it off to the caller. return keychain, tempdirectory
[ "This", "function", "creates", "a", "temporary", "Mac", "keychain", "that", "we", "can", "use", "to", "work", "with", "credentials", ".", "This", "keychain", "uses", "a", "one", "-", "time", "password", "and", "a", "temporary", "file", "to", "store", "the"...
pypa/pipenv
python
https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/vendor/urllib3/contrib/_securetransport/low_level.py#L171-L208
[ "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 filename will be 8 r...
cae8d76c210b9777e90aab76e9c4b0e53bb19cde
train
_load_items_from_file
Given a single file, loads all the trust objects from it into arrays and the keychain. Returns a tuple of lists: the first list is a list of identities, the second a list of certs.
pipenv/vendor/urllib3/contrib/_securetransport/low_level.py
def _load_items_from_file(keychain, path): """ Given a single file, loads all the trust objects from it into arrays and the keychain. Returns a tuple of lists: the first list is a list of identities, the second a list of certs. """ certificates = [] identities = [] result_array = None with open(path, 'rb') as f: raw_filedata = f.read() try: filedata = CoreFoundation.CFDataCreate( CoreFoundation.kCFAllocatorDefault, raw_filedata, len(raw_filedata) ) result_array = CoreFoundation.CFArrayRef() result = Security.SecItemImport( filedata, # cert data None, # Filename, leaving it out for now None, # What the type of the file is, we don't care None, # what's in the file, we don't care 0, # import flags None, # key params, can include passphrase in the future keychain, # The keychain to insert into ctypes.byref(result_array) # Results ) _assert_no_error(result) # A CFArray is not very useful to us as an intermediary # representation, so we are going to extract the objects we want # and then free the array. We don't need to keep hold of keys: the # keychain already has them! result_count = CoreFoundation.CFArrayGetCount(result_array) for index in range(result_count): item = CoreFoundation.CFArrayGetValueAtIndex( result_array, index ) item = ctypes.cast(item, CoreFoundation.CFTypeRef) if _is_cert(item): CoreFoundation.CFRetain(item) certificates.append(item) elif _is_identity(item): CoreFoundation.CFRetain(item) identities.append(item) finally: if result_array: CoreFoundation.CFRelease(result_array) CoreFoundation.CFRelease(filedata) return (identities, certificates)
def _load_items_from_file(keychain, path): """ Given a single file, loads all the trust objects from it into arrays and the keychain. Returns a tuple of lists: the first list is a list of identities, the second a list of certs. """ certificates = [] identities = [] result_array = None with open(path, 'rb') as f: raw_filedata = f.read() try: filedata = CoreFoundation.CFDataCreate( CoreFoundation.kCFAllocatorDefault, raw_filedata, len(raw_filedata) ) result_array = CoreFoundation.CFArrayRef() result = Security.SecItemImport( filedata, # cert data None, # Filename, leaving it out for now None, # What the type of the file is, we don't care None, # what's in the file, we don't care 0, # import flags None, # key params, can include passphrase in the future keychain, # The keychain to insert into ctypes.byref(result_array) # Results ) _assert_no_error(result) # A CFArray is not very useful to us as an intermediary # representation, so we are going to extract the objects we want # and then free the array. We don't need to keep hold of keys: the # keychain already has them! result_count = CoreFoundation.CFArrayGetCount(result_array) for index in range(result_count): item = CoreFoundation.CFArrayGetValueAtIndex( result_array, index ) item = ctypes.cast(item, CoreFoundation.CFTypeRef) if _is_cert(item): CoreFoundation.CFRetain(item) certificates.append(item) elif _is_identity(item): CoreFoundation.CFRetain(item) identities.append(item) finally: if result_array: CoreFoundation.CFRelease(result_array) CoreFoundation.CFRelease(filedata) return (identities, certificates)
[ "Given", "a", "single", "file", "loads", "all", "the", "trust", "objects", "from", "it", "into", "arrays", "and", "the", "keychain", ".", "Returns", "a", "tuple", "of", "lists", ":", "the", "first", "list", "is", "a", "list", "of", "identities", "the", ...
pypa/pipenv
python
https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/vendor/urllib3/contrib/_securetransport/low_level.py#L211-L267
[ "def", "_load_items_from_file", "(", "keychain", ",", "path", ")", ":", "certificates", "=", "[", "]", "identities", "=", "[", "]", "result_array", "=", "None", "with", "open", "(", "path", ",", "'rb'", ")", "as", "f", ":", "raw_filedata", "=", "f", "....
cae8d76c210b9777e90aab76e9c4b0e53bb19cde
train
_load_client_cert_chain
Load certificates and maybe keys from a number of files. Has the end goal of returning a CFArray containing one SecIdentityRef, and then zero or more SecCertificateRef objects, suitable for use as a client certificate trust chain.
pipenv/vendor/urllib3/contrib/_securetransport/low_level.py
def _load_client_cert_chain(keychain, *paths): """ Load certificates and maybe keys from a number of files. Has the end goal of returning a CFArray containing one SecIdentityRef, and then zero or more SecCertificateRef objects, suitable for use as a client certificate trust chain. """ # 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 example, it doesn't necessarily # affect iOS), but there is nothing inside Security.framework that lets you # get a SecIdentityRef without having a key in a keychain. # # So the policy here is we take all the files and iterate them in order. # Each one will use SecItemImport to have one or more objects loaded from # it. We will also point at a keychain that macOS can use to work with the # private key. # # Once we have all the objects, we'll check what we actually have. If we # already have a SecIdentityRef in hand, fab: we'll use that. Otherwise, # we'll take the first certificate (which we assume to be our leaf) and # ask the keychain to give us a SecIdentityRef with that cert's associated # key. # # We'll then return a CFArray containing the trust chain: one # SecIdentityRef and then zero-or-more SecCertificateRef objects. The # responsibility for freeing this CFArray will be with the caller. This # CFArray must remain alive for the entire connection, so in practice it # will be stored with a single SSLSocket, along with the reference to the # keychain. certificates = [] identities = [] # Filter out bad paths. paths = (path for path in paths if path) try: for file_path in paths: new_identities, new_certs = _load_items_from_file( keychain, file_path ) identities.extend(new_identities) certificates.extend(new_certs) # Ok, we have everything. The question is: do we have an identity? If # not, we want to grab one from the first cert we have. if not identities: new_identity = Security.SecIdentityRef() status = Security.SecIdentityCreateWithCertificate( keychain, certificates[0], ctypes.byref(new_identity) ) _assert_no_error(status) identities.append(new_identity) # We now want to release the original certificate, as we no longer # need it. CoreFoundation.CFRelease(certificates.pop(0)) # We now need to build a new CFArray that holds the trust chain. trust_chain = CoreFoundation.CFArrayCreateMutable( CoreFoundation.kCFAllocatorDefault, 0, ctypes.byref(CoreFoundation.kCFTypeArrayCallBacks), ) for item in itertools.chain(identities, certificates): # ArrayAppendValue does a CFRetain on the item. That's fine, # because the finally block will release our other refs to them. CoreFoundation.CFArrayAppendValue(trust_chain, item) return trust_chain finally: for obj in itertools.chain(identities, certificates): CoreFoundation.CFRelease(obj)
def _load_client_cert_chain(keychain, *paths): """ Load certificates and maybe keys from a number of files. Has the end goal of returning a CFArray containing one SecIdentityRef, and then zero or more SecCertificateRef objects, suitable for use as a client certificate trust chain. """ # 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 example, it doesn't necessarily # affect iOS), but there is nothing inside Security.framework that lets you # get a SecIdentityRef without having a key in a keychain. # # So the policy here is we take all the files and iterate them in order. # Each one will use SecItemImport to have one or more objects loaded from # it. We will also point at a keychain that macOS can use to work with the # private key. # # Once we have all the objects, we'll check what we actually have. If we # already have a SecIdentityRef in hand, fab: we'll use that. Otherwise, # we'll take the first certificate (which we assume to be our leaf) and # ask the keychain to give us a SecIdentityRef with that cert's associated # key. # # We'll then return a CFArray containing the trust chain: one # SecIdentityRef and then zero-or-more SecCertificateRef objects. The # responsibility for freeing this CFArray will be with the caller. This # CFArray must remain alive for the entire connection, so in practice it # will be stored with a single SSLSocket, along with the reference to the # keychain. certificates = [] identities = [] # Filter out bad paths. paths = (path for path in paths if path) try: for file_path in paths: new_identities, new_certs = _load_items_from_file( keychain, file_path ) identities.extend(new_identities) certificates.extend(new_certs) # Ok, we have everything. The question is: do we have an identity? If # not, we want to grab one from the first cert we have. if not identities: new_identity = Security.SecIdentityRef() status = Security.SecIdentityCreateWithCertificate( keychain, certificates[0], ctypes.byref(new_identity) ) _assert_no_error(status) identities.append(new_identity) # We now want to release the original certificate, as we no longer # need it. CoreFoundation.CFRelease(certificates.pop(0)) # We now need to build a new CFArray that holds the trust chain. trust_chain = CoreFoundation.CFArrayCreateMutable( CoreFoundation.kCFAllocatorDefault, 0, ctypes.byref(CoreFoundation.kCFTypeArrayCallBacks), ) for item in itertools.chain(identities, certificates): # ArrayAppendValue does a CFRetain on the item. That's fine, # because the finally block will release our other refs to them. CoreFoundation.CFArrayAppendValue(trust_chain, item) return trust_chain finally: for obj in itertools.chain(identities, certificates): CoreFoundation.CFRelease(obj)
[ "Load", "certificates", "and", "maybe", "keys", "from", "a", "number", "of", "files", ".", "Has", "the", "end", "goal", "of", "returning", "a", "CFArray", "containing", "one", "SecIdentityRef", "and", "then", "zero", "or", "more", "SecCertificateRef", "objects...
pypa/pipenv
python
https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/vendor/urllib3/contrib/_securetransport/low_level.py#L270-L346
[ "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 (f...
cae8d76c210b9777e90aab76e9c4b0e53bb19cde
train
HTTPResponse.get_redirect_location
Should we redirect and where to? :returns: Truthy redirect location string if we got a redirect status code and valid location. ``None`` if redirect status and no location. ``False`` if not a redirect status code.
pipenv/vendor/urllib3/response.py
def get_redirect_location(self): """ Should we redirect and where to? :returns: Truthy redirect location string if we got a redirect status code and valid location. ``None`` if redirect status and no location. ``False`` if not a redirect status code. """ if self.status in self.REDIRECT_STATUSES: return self.headers.get('location') return False
def get_redirect_location(self): """ Should we redirect and where to? :returns: Truthy redirect location string if we got a redirect status code and valid location. ``None`` if redirect status and no location. ``False`` if not a redirect status code. """ if self.status in self.REDIRECT_STATUSES: return self.headers.get('location') return False
[ "Should", "we", "redirect", "and", "where", "to?" ]
pypa/pipenv
python
https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/vendor/urllib3/response.py#L211-L222
[ "def", "get_redirect_location", "(", "self", ")", ":", "if", "self", ".", "status", "in", "self", ".", "REDIRECT_STATUSES", ":", "return", "self", ".", "headers", ".", "get", "(", "'location'", ")", "return", "False" ]
cae8d76c210b9777e90aab76e9c4b0e53bb19cde
train
HTTPResponse._init_length
Set initial length value for Response content if available.
pipenv/vendor/urllib3/response.py
def _init_length(self, request_method): """ Set initial length value for Response content if available. """ 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 chunked. This method falls back to attempt reading # the response before raising an exception. log.warning("Received response with both Content-Length and " "Transfer-Encoding set. This is expressly forbidden " "by RFC 7230 sec 3.3.2. Ignoring Content-Length and " "attempting to process response as Transfer-Encoding: " "chunked.") return None try: # RFC 7230 section 3.3.2 specifies multiple content lengths can # be sent in a single Content-Length header # (e.g. Content-Length: 42, 42). This line ensures the values # are all valid ints and that as long as the `set` length is 1, # all values are the same. Otherwise, the header is invalid. lengths = set([int(val) for val in length.split(',')]) if len(lengths) > 1: raise InvalidHeader("Content-Length contained multiple " "unmatching values (%s)" % length) length = lengths.pop() except ValueError: length = None else: if length < 0: length = None # Convert status to int for comparison # In some cases, httplib returns a status of "_UNKNOWN" try: status = int(self.status) except ValueError: status = 0 # Check for responses that shouldn't include a body if status in (204, 304) or 100 <= status < 200 or request_method == 'HEAD': length = 0 return length
def _init_length(self, request_method): """ Set initial length value for Response content if available. """ 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 chunked. This method falls back to attempt reading # the response before raising an exception. log.warning("Received response with both Content-Length and " "Transfer-Encoding set. This is expressly forbidden " "by RFC 7230 sec 3.3.2. Ignoring Content-Length and " "attempting to process response as Transfer-Encoding: " "chunked.") return None try: # RFC 7230 section 3.3.2 specifies multiple content lengths can # be sent in a single Content-Length header # (e.g. Content-Length: 42, 42). This line ensures the values # are all valid ints and that as long as the `set` length is 1, # all values are the same. Otherwise, the header is invalid. lengths = set([int(val) for val in length.split(',')]) if len(lengths) > 1: raise InvalidHeader("Content-Length contained multiple " "unmatching values (%s)" % length) length = lengths.pop() except ValueError: length = None else: if length < 0: length = None # Convert status to int for comparison # In some cases, httplib returns a status of "_UNKNOWN" try: status = int(self.status) except ValueError: status = 0 # Check for responses that shouldn't include a body if status in (204, 304) or 100 <= status < 200 or request_method == 'HEAD': length = 0 return length
[ "Set", "initial", "length", "value", "for", "Response", "content", "if", "available", "." ]
pypa/pipenv
python
https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/vendor/urllib3/response.py#L255-L301
[ "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...
cae8d76c210b9777e90aab76e9c4b0e53bb19cde
train
HTTPResponse._init_decoder
Set-up the _decoder attribute if necessary.
pipenv/vendor/urllib3/response.py
def _init_decoder(self): """ Set-up the _decoder attribute if necessary. """ # 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_encoding in self.CONTENT_DECODERS: self._decoder = _get_decoder(content_encoding) elif ',' in content_encoding: encodings = [e.strip() for e in content_encoding.split(',') if e.strip() in self.CONTENT_DECODERS] if len(encodings): self._decoder = _get_decoder(content_encoding)
def _init_decoder(self): """ Set-up the _decoder attribute if necessary. """ # 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_encoding in self.CONTENT_DECODERS: self._decoder = _get_decoder(content_encoding) elif ',' in content_encoding: encodings = [e.strip() for e in content_encoding.split(',') if e.strip() in self.CONTENT_DECODERS] if len(encodings): self._decoder = _get_decoder(content_encoding)
[ "Set", "-", "up", "the", "_decoder", "attribute", "if", "necessary", "." ]
pypa/pipenv
python
https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/vendor/urllib3/response.py#L303-L316
[ "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", "(", ")", "...
cae8d76c210b9777e90aab76e9c4b0e53bb19cde
train
HTTPResponse._flush_decoder
Flushes the decoder. Should only be called if the decoder is actually being used.
pipenv/vendor/urllib3/response.py
def _flush_decoder(self): """ Flushes the decoder. Should only be called if the decoder is actually being used. """ if self._decoder: buf = self._decoder.decompress(b'') return buf + self._decoder.flush() return b''
def _flush_decoder(self): """ Flushes the decoder. Should only be called if the decoder is actually being used. """ if self._decoder: buf = self._decoder.decompress(b'') return buf + self._decoder.flush() return b''
[ "Flushes", "the", "decoder", ".", "Should", "only", "be", "called", "if", "the", "decoder", "is", "actually", "being", "used", "." ]
pypa/pipenv
python
https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/vendor/urllib3/response.py#L336-L345
[ "def", "_flush_decoder", "(", "self", ")", ":", "if", "self", ".", "_decoder", ":", "buf", "=", "self", ".", "_decoder", ".", "decompress", "(", "b''", ")", "return", "buf", "+", "self", ".", "_decoder", ".", "flush", "(", ")", "return", "b''" ]
cae8d76c210b9777e90aab76e9c4b0e53bb19cde
train
HTTPResponse._error_catcher
Catch low-level python exceptions, instead re-raising urllib3 variants, so that low-level exceptions are not leaked in the high-level api. On exit, release the connection back to the pool.
pipenv/vendor/urllib3/response.py
def _error_catcher(self): """ Catch low-level python exceptions, instead re-raising urllib3 variants, so that low-level exceptions are not leaked in the high-level api. On exit, release the connection back to the pool. """ 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 clean way to get at it from this context. raise ReadTimeoutError(self._pool, None, 'Read timed out.') except BaseSSLError as e: # FIXME: Is there a better way to differentiate between SSLErrors? if 'read operation timed out' not in str(e): # Defensive: # This shouldn't happen but just in case we're missing an edge # case, let's avoid swallowing SSL errors. raise raise ReadTimeoutError(self._pool, None, 'Read timed out.') except (HTTPException, SocketError) as e: # This includes IncompleteRead. raise ProtocolError('Connection broken: %r' % e, e) # If no exception is thrown, we should avoid cleaning up # unnecessarily. clean_exit = True finally: # If we didn't terminate cleanly, we need to throw away our # connection. if not clean_exit: # The response may not be closed but we're not going to use it # anymore so close it now to ensure that the connection is # released back to the pool. if self._original_response: self._original_response.close() # Closing the response may not actually be sufficient to close # everything, so if we have a hold of the connection close that # too. if self._connection: self._connection.close() # If we hold the original response but it's closed now, we should # return the connection back to the pool. if self._original_response and self._original_response.isclosed(): self.release_conn()
def _error_catcher(self): """ Catch low-level python exceptions, instead re-raising urllib3 variants, so that low-level exceptions are not leaked in the high-level api. On exit, release the connection back to the pool. """ 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 clean way to get at it from this context. raise ReadTimeoutError(self._pool, None, 'Read timed out.') except BaseSSLError as e: # FIXME: Is there a better way to differentiate between SSLErrors? if 'read operation timed out' not in str(e): # Defensive: # This shouldn't happen but just in case we're missing an edge # case, let's avoid swallowing SSL errors. raise raise ReadTimeoutError(self._pool, None, 'Read timed out.') except (HTTPException, SocketError) as e: # This includes IncompleteRead. raise ProtocolError('Connection broken: %r' % e, e) # If no exception is thrown, we should avoid cleaning up # unnecessarily. clean_exit = True finally: # If we didn't terminate cleanly, we need to throw away our # connection. if not clean_exit: # The response may not be closed but we're not going to use it # anymore so close it now to ensure that the connection is # released back to the pool. if self._original_response: self._original_response.close() # Closing the response may not actually be sufficient to close # everything, so if we have a hold of the connection close that # too. if self._connection: self._connection.close() # If we hold the original response but it's closed now, we should # return the connection back to the pool. if self._original_response and self._original_response.isclosed(): self.release_conn()
[ "Catch", "low", "-", "level", "python", "exceptions", "instead", "re", "-", "raising", "urllib3", "variants", "so", "that", "low", "-", "level", "exceptions", "are", "not", "leaked", "in", "the", "high", "-", "level", "api", "." ]
pypa/pipenv
python
https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/vendor/urllib3/response.py#L348-L402
[ "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 clean way to get at it from this context.",...
cae8d76c210b9777e90aab76e9c4b0e53bb19cde
train
HTTPResponse.read
Similar to :meth:`httplib.HTTPResponse.read`, but with two additional parameters: ``decode_content`` and ``cache_content``. :param amt: How much of the content to read. If specified, caching is skipped because it doesn't make sense to cache partial content as the full response. :param decode_content: If True, will attempt to decode the body based on the 'content-encoding' header. :param cache_content: If True, will save the returned data such that the same result is returned despite of the state of the underlying file object. This is useful if you want the ``.data`` property to continue working after having ``.read()`` the file object. (Overridden if ``amt`` is set.)
pipenv/vendor/urllib3/response.py
def read(self, amt=None, decode_content=None, cache_content=False): """ Similar to :meth:`httplib.HTTPResponse.read`, but with two additional parameters: ``decode_content`` and ``cache_content``. :param amt: How much of the content to read. If specified, caching is skipped because it doesn't make sense to cache partial content as the full response. :param decode_content: If True, will attempt to decode the body based on the 'content-encoding' header. :param cache_content: If True, will save the returned data such that the same result is returned despite of the state of the underlying file object. This is useful if you want the ``.data`` property to continue working after having ``.read()`` the file object. (Overridden if ``amt`` is set.) """ self._init_decoder() if decode_content is None: decode_content = self.decode_content if self._fp is None: return flush_decoder = False data = None with self._error_catcher(): if amt is None: # cStringIO doesn't like amt=None data = self._fp.read() flush_decoder = True else: cache_content = False data = self._fp.read(amt) if amt != 0 and not data: # Platform-specific: Buggy versions of Python. # Close the connection when no data is returned # # This is redundant to what httplib/http.client _should_ # already do. However, versions of python released before # December 15, 2012 (http://bugs.python.org/issue16298) do # not properly close the connection in all cases. There is # no harm in redundantly calling close. self._fp.close() flush_decoder = True if self.enforce_content_length and self.length_remaining not in (0, None): # This is an edge case that httplib failed to cover due # to concerns of backward compatibility. We're # addressing it here to make sure IncompleteRead is # raised during streaming, so all calls with incorrect # Content-Length are caught. raise IncompleteRead(self._fp_bytes_read, self.length_remaining) if data: self._fp_bytes_read += len(data) if self.length_remaining is not None: self.length_remaining -= len(data) data = self._decode(data, decode_content, flush_decoder) if cache_content: self._body = data return data
def read(self, amt=None, decode_content=None, cache_content=False): """ Similar to :meth:`httplib.HTTPResponse.read`, but with two additional parameters: ``decode_content`` and ``cache_content``. :param amt: How much of the content to read. If specified, caching is skipped because it doesn't make sense to cache partial content as the full response. :param decode_content: If True, will attempt to decode the body based on the 'content-encoding' header. :param cache_content: If True, will save the returned data such that the same result is returned despite of the state of the underlying file object. This is useful if you want the ``.data`` property to continue working after having ``.read()`` the file object. (Overridden if ``amt`` is set.) """ self._init_decoder() if decode_content is None: decode_content = self.decode_content if self._fp is None: return flush_decoder = False data = None with self._error_catcher(): if amt is None: # cStringIO doesn't like amt=None data = self._fp.read() flush_decoder = True else: cache_content = False data = self._fp.read(amt) if amt != 0 and not data: # Platform-specific: Buggy versions of Python. # Close the connection when no data is returned # # This is redundant to what httplib/http.client _should_ # already do. However, versions of python released before # December 15, 2012 (http://bugs.python.org/issue16298) do # not properly close the connection in all cases. There is # no harm in redundantly calling close. self._fp.close() flush_decoder = True if self.enforce_content_length and self.length_remaining not in (0, None): # This is an edge case that httplib failed to cover due # to concerns of backward compatibility. We're # addressing it here to make sure IncompleteRead is # raised during streaming, so all calls with incorrect # Content-Length are caught. raise IncompleteRead(self._fp_bytes_read, self.length_remaining) if data: self._fp_bytes_read += len(data) if self.length_remaining is not None: self.length_remaining -= len(data) data = self._decode(data, decode_content, flush_decoder) if cache_content: self._body = data return data
[ "Similar", "to", ":", "meth", ":", "httplib", ".", "HTTPResponse", ".", "read", "but", "with", "two", "additional", "parameters", ":", "decode_content", "and", "cache_content", "." ]
pypa/pipenv
python
https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/vendor/urllib3/response.py#L404-L471
[ "def", "read", "(", "self", ",", "amt", "=", "None", ",", "decode_content", "=", "None", ",", "cache_content", "=", "False", ")", ":", "self", ".", "_init_decoder", "(", ")", "if", "decode_content", "is", "None", ":", "decode_content", "=", "self", ".", ...
cae8d76c210b9777e90aab76e9c4b0e53bb19cde
train
HTTPResponse.from_httplib
Given an :class:`httplib.HTTPResponse` instance ``r``, return a corresponding :class:`urllib3.response.HTTPResponse` object. Remaining parameters are passed to the HTTPResponse constructor, along with ``original_response=r``.
pipenv/vendor/urllib3/response.py
def from_httplib(ResponseCls, r, **response_kw): """ Given an :class:`httplib.HTTPResponse` instance ``r``, return a corresponding :class:`urllib3.response.HTTPResponse` object. Remaining parameters are passed to the HTTPResponse constructor, along with ``original_response=r``. """ headers = r.msg if not isinstance(headers, HTTPHeaderDict): if PY3: # Python 3 headers = HTTPHeaderDict(headers.items()) else: # Python 2 headers = HTTPHeaderDict.from_httplib(headers) # HTTPResponse objects in Python 3 don't have a .strict attribute strict = getattr(r, 'strict', 0) resp = ResponseCls(body=r, headers=headers, status=r.status, version=r.version, reason=r.reason, strict=strict, original_response=r, **response_kw) return resp
def from_httplib(ResponseCls, r, **response_kw): """ Given an :class:`httplib.HTTPResponse` instance ``r``, return a corresponding :class:`urllib3.response.HTTPResponse` object. Remaining parameters are passed to the HTTPResponse constructor, along with ``original_response=r``. """ headers = r.msg if not isinstance(headers, HTTPHeaderDict): if PY3: # Python 3 headers = HTTPHeaderDict(headers.items()) else: # Python 2 headers = HTTPHeaderDict.from_httplib(headers) # HTTPResponse objects in Python 3 don't have a .strict attribute strict = getattr(r, 'strict', 0) resp = ResponseCls(body=r, headers=headers, status=r.status, version=r.version, reason=r.reason, strict=strict, original_response=r, **response_kw) return resp
[ "Given", "an", ":", "class", ":", "httplib", ".", "HTTPResponse", "instance", "r", "return", "a", "corresponding", ":", "class", ":", "urllib3", ".", "response", ".", "HTTPResponse", "object", "." ]
pypa/pipenv
python
https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/vendor/urllib3/response.py#L500-L526
[ "def", "from_httplib", "(", "ResponseCls", ",", "r", ",", "*", "*", "response_kw", ")", ":", "headers", "=", "r", ".", "msg", "if", "not", "isinstance", "(", "headers", ",", "HTTPHeaderDict", ")", ":", "if", "PY3", ":", "# Python 3", "headers", "=", "H...
cae8d76c210b9777e90aab76e9c4b0e53bb19cde
train
HTTPResponse.read_chunked
Similar to :meth:`HTTPResponse.read`, but with an additional parameter: ``decode_content``. :param amt: How much of the content to read. If specified, caching is skipped because it doesn't make sense to cache partial content as the full response. :param decode_content: If True, will attempt to decode the body based on the 'content-encoding' header.
pipenv/vendor/urllib3/response.py
def read_chunked(self, amt=None, decode_content=None): """ Similar to :meth:`HTTPResponse.read`, but with an additional parameter: ``decode_content``. :param amt: How much of the content to read. If specified, caching is skipped because it doesn't make sense to cache partial content as the full response. :param decode_content: If True, will attempt to decode the body based on the 'content-encoding' header. """ self._init_decoder() # FIXME: Rewrite this method and make it a class with a better structured logic. if not self.chunked: raise ResponseNotChunked( "Response is not chunked. " "Header 'transfer-encoding: chunked' is missing.") if not self.supports_chunked_reads(): raise BodyNotHttplibCompatible( "Body should be httplib.HTTPResponse like. " "It should have have an fp attribute which returns raw chunks.") with self._error_catcher(): # Don't bother reading the body of a HEAD request. if self._original_response and is_response_to_head(self._original_response): self._original_response.close() return # If a response is already read and closed # then return immediately. if self._fp.fp is None: return while True: self._update_chunk_length() if self.chunk_left == 0: break chunk = self._handle_chunk(amt) decoded = self._decode(chunk, decode_content=decode_content, flush_decoder=False) if decoded: yield decoded if decode_content: # On CPython and PyPy, we should never need to flush the # decoder. However, on Jython we *might* need to, so # lets defensively do it anyway. decoded = self._flush_decoder() if decoded: # Platform-specific: Jython. yield decoded # Chunk content ends with \r\n: discard it. while True: line = self._fp.fp.readline() if not line: # Some sites may not end with '\r\n'. break if line == b'\r\n': break # We read everything; close the "file". if self._original_response: self._original_response.close()
def read_chunked(self, amt=None, decode_content=None): """ Similar to :meth:`HTTPResponse.read`, but with an additional parameter: ``decode_content``. :param amt: How much of the content to read. If specified, caching is skipped because it doesn't make sense to cache partial content as the full response. :param decode_content: If True, will attempt to decode the body based on the 'content-encoding' header. """ self._init_decoder() # FIXME: Rewrite this method and make it a class with a better structured logic. if not self.chunked: raise ResponseNotChunked( "Response is not chunked. " "Header 'transfer-encoding: chunked' is missing.") if not self.supports_chunked_reads(): raise BodyNotHttplibCompatible( "Body should be httplib.HTTPResponse like. " "It should have have an fp attribute which returns raw chunks.") with self._error_catcher(): # Don't bother reading the body of a HEAD request. if self._original_response and is_response_to_head(self._original_response): self._original_response.close() return # If a response is already read and closed # then return immediately. if self._fp.fp is None: return while True: self._update_chunk_length() if self.chunk_left == 0: break chunk = self._handle_chunk(amt) decoded = self._decode(chunk, decode_content=decode_content, flush_decoder=False) if decoded: yield decoded if decode_content: # On CPython and PyPy, we should never need to flush the # decoder. However, on Jython we *might* need to, so # lets defensively do it anyway. decoded = self._flush_decoder() if decoded: # Platform-specific: Jython. yield decoded # Chunk content ends with \r\n: discard it. while True: line = self._fp.fp.readline() if not line: # Some sites may not end with '\r\n'. break if line == b'\r\n': break # We read everything; close the "file". if self._original_response: self._original_response.close()
[ "Similar", "to", ":", "meth", ":", "HTTPResponse", ".", "read", "but", "with", "an", "additional", "parameter", ":", "decode_content", "." ]
pypa/pipenv
python
https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/vendor/urllib3/response.py#L629-L694
[ "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", ...
cae8d76c210b9777e90aab76e9c4b0e53bb19cde
train
HTTPResponse.geturl
Returns the URL that was the source of this response. If the request that generated this response redirected, this method will return the final redirect location.
pipenv/vendor/urllib3/response.py
def geturl(self): """ Returns the URL that was the source of this response. If the request that generated this response redirected, this method will return the final redirect location. """ if self.retries is not None and len(self.retries.history): return self.retries.history[-1].redirect_location else: return self._request_url
def geturl(self): """ Returns the URL that was the source of this response. If the request that generated this response redirected, this method will return the final redirect location. """ if self.retries is not None and len(self.retries.history): return self.retries.history[-1].redirect_location else: return self._request_url
[ "Returns", "the", "URL", "that", "was", "the", "source", "of", "this", "response", ".", "If", "the", "request", "that", "generated", "this", "response", "redirected", "this", "method", "will", "return", "the", "final", "redirect", "location", "." ]
pypa/pipenv
python
https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/vendor/urllib3/response.py#L696-L705
[ "def", "geturl", "(", "self", ")", ":", "if", "self", ".", "retries", "is", "not", "None", "and", "len", "(", "self", ".", "retries", ".", "history", ")", ":", "return", "self", ".", "retries", ".", "history", "[", "-", "1", "]", ".", "redirect_loc...
cae8d76c210b9777e90aab76e9c4b0e53bb19cde
train
VistirSpinner.ok
Set Ok (success) finalizer to a spinner.
pipenv/vendor/vistir/spin.py
def ok(self, text=u"OK", err=False): """Set Ok (success) finalizer to a spinner.""" # 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)
def ok(self, text=u"OK", err=False): """Set Ok (success) finalizer to a spinner.""" # 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", "." ]
pypa/pipenv
python
https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/vendor/vistir/spin.py#L227-L234
[ "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", "=...
cae8d76c210b9777e90aab76e9c4b0e53bb19cde
train
VistirSpinner.fail
Set fail finalizer to a spinner.
pipenv/vendor/vistir/spin.py
def fail(self, text=u"FAIL", err=False): """Set fail finalizer to a spinner.""" # 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)
def fail(self, text=u"FAIL", err=False): """Set fail finalizer to a spinner.""" # 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", "." ]
pypa/pipenv
python
https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/vendor/vistir/spin.py#L236-L243
[ "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",...
cae8d76c210b9777e90aab76e9c4b0e53bb19cde
train
VistirSpinner.write_err
Write error text in the terminal without breaking the spinner.
pipenv/vendor/vistir/spin.py
def write_err(self, text): """Write error text in the terminal without breaking the spinner.""" 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 text is None: text = "" text = decode_output(u"{0}\n".format(text), target_stream=stderr) self.stderr.write(text) self.out_buff.write(decode_output(text, target_stream=self.out_buff))
def write_err(self, text): """Write error text in the terminal without breaking the spinner.""" 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 text is None: text = "" text = decode_output(u"{0}\n".format(text), target_stream=stderr) self.stderr.write(text) self.out_buff.write(decode_output(text, target_stream=self.out_buff))
[ "Write", "error", "text", "in", "the", "terminal", "without", "breaking", "the", "spinner", "." ]
pypa/pipenv
python
https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/vendor/vistir/spin.py#L270-L281
[ "def", "write_err", "(", "self", ",", "text", ")", ":", "stderr", "=", "self", ".", "stderr", "if", "self", ".", "stderr", ".", "closed", ":", "stderr", "=", "sys", ".", "stderr", "stderr", ".", "write", "(", "decode_output", "(", "u\"\\r\"", ",", "t...
cae8d76c210b9777e90aab76e9c4b0e53bb19cde
train
VistirSpinner._freeze
Stop spinner, compose last frame and 'freeze' it.
pipenv/vendor/vistir/spin.py
def _freeze(self, final_text, err=False): """Stop spinner, compose last frame and 'freeze' it.""" 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) last_frame = self._compose_out(text, mode="last") self._last_frame = decode_output(last_frame, target_stream=target) # Should be stopped here, otherwise prints after # self._freeze call will mess up the spinner self.stop() target.write(self._last_frame)
def _freeze(self, final_text, err=False): """Stop spinner, compose last frame and 'freeze' it.""" 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) last_frame = self._compose_out(text, mode="last") self._last_frame = decode_output(last_frame, target_stream=target) # Should be stopped here, otherwise prints after # self._freeze call will mess up the spinner self.stop() target.write(self._last_frame)
[ "Stop", "spinner", "compose", "last", "frame", "and", "freeze", "it", "." ]
pypa/pipenv
python
https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/vendor/vistir/spin.py#L318-L332
[ "def", "_freeze", "(", "self", ",", "final_text", ",", "err", "=", "False", ")", ":", "if", "not", "final_text", ":", "final_text", "=", "\"\"", "target", "=", "self", ".", "stderr", "if", "err", "else", "self", ".", "stdout", "if", "target", ".", "c...
cae8d76c210b9777e90aab76e9c4b0e53bb19cde
train
describe_token_expr
Like `describe_token` but for token expressions.
pipenv/vendor/jinja2/lexer.py
def describe_token_expr(expr): """Like `describe_token` but for token expressions.""" if ':' in expr: type, value = expr.split(':', 1) if type == 'name': return value else: type = expr return _describe_token_type(type)
def describe_token_expr(expr): """Like `describe_token` but for token expressions.""" 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", "." ]
pypa/pipenv
python
https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/vendor/jinja2/lexer.py#L178-L186
[ "def", "describe_token_expr", "(", "expr", ")", ":", "if", "':'", "in", "expr", ":", "type", ",", "value", "=", "expr", ".", "split", "(", "':'", ",", "1", ")", "if", "type", "==", "'name'", ":", "return", "value", "else", ":", "type", "=", "expr",...
cae8d76c210b9777e90aab76e9c4b0e53bb19cde
train
get_lexer
Return a lexer which is probably cached.
pipenv/vendor/jinja2/lexer.py
def get_lexer(environment): """Return a lexer which is probably cached.""" key = (environment.block_start_string, environment.block_end_string, environment.variable_start_string, environment.variable_end_string, environment.comment_start_string, environment.comment_end_string, environment.line_statement_prefix, environment.line_comment_prefix, environment.trim_blocks, environment.lstrip_blocks, environment.newline_sequence, environment.keep_trailing_newline) lexer = _lexer_cache.get(key) if lexer is None: lexer = Lexer(environment) _lexer_cache[key] = lexer return lexer
def get_lexer(environment): """Return a lexer which is probably cached.""" key = (environment.block_start_string, environment.block_end_string, environment.variable_start_string, environment.variable_end_string, environment.comment_start_string, environment.comment_end_string, environment.line_statement_prefix, environment.line_comment_prefix, environment.trim_blocks, environment.lstrip_blocks, environment.newline_sequence, environment.keep_trailing_newline) lexer = _lexer_cache.get(key) if lexer is None: lexer = Lexer(environment) _lexer_cache[key] = lexer return lexer
[ "Return", "a", "lexer", "which", "is", "probably", "cached", "." ]
pypa/pipenv
python
https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/vendor/jinja2/lexer.py#L391-L409
[ "def", "get_lexer", "(", "environment", ")", ":", "key", "=", "(", "environment", ".", "block_start_string", ",", "environment", ".", "block_end_string", ",", "environment", ".", "variable_start_string", ",", "environment", ".", "variable_end_string", ",", "environm...
cae8d76c210b9777e90aab76e9c4b0e53bb19cde