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
get_host
Deprecated. Use :func:`parse_url` instead.
pipenv/vendor/urllib3/util/url.py
def get_host(url): """ Deprecated. Use :func:`parse_url` instead. """ p = parse_url(url) return p.scheme or 'http', p.hostname, p.port
def get_host(url): """ Deprecated. Use :func:`parse_url` instead. """ p = parse_url(url) return p.scheme or 'http', p.hostname, p.port
[ "Deprecated", ".", "Use", ":", "func", ":", "parse_url", "instead", "." ]
pypa/pipenv
python
https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/vendor/urllib3/util/url.py#L225-L230
[ "def", "get_host", "(", "url", ")", ":", "p", "=", "parse_url", "(", "url", ")", "return", "p", ".", "scheme", "or", "'http'", ",", "p", ".", "hostname", ",", "p", ".", "port" ]
cae8d76c210b9777e90aab76e9c4b0e53bb19cde
train
Url.request_uri
Absolute path including the query string.
pipenv/vendor/urllib3/util/url.py
def request_uri(self): """Absolute path including the query string.""" uri = self.path or '/' if self.query is not None: uri += '?' + self.query return uri
def request_uri(self): """Absolute path including the query string.""" uri = self.path or '/' if self.query is not None: uri += '?' + self.query return uri
[ "Absolute", "path", "including", "the", "query", "string", "." ]
pypa/pipenv
python
https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/vendor/urllib3/util/url.py#L39-L46
[ "def", "request_uri", "(", "self", ")", ":", "uri", "=", "self", ".", "path", "or", "'/'", "if", "self", ".", "query", "is", "not", "None", ":", "uri", "+=", "'?'", "+", "self", ".", "query", "return", "uri" ]
cae8d76c210b9777e90aab76e9c4b0e53bb19cde
train
Url.netloc
Network location including host and port
pipenv/vendor/urllib3/util/url.py
def netloc(self): """Network location including host and port""" if self.port: return '%s:%d' % (self.host, self.port) return self.host
def netloc(self): """Network location including host and port""" if self.port: return '%s:%d' % (self.host, self.port) return self.host
[ "Network", "location", "including", "host", "and", "port" ]
pypa/pipenv
python
https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/vendor/urllib3/util/url.py#L49-L53
[ "def", "netloc", "(", "self", ")", ":", "if", "self", ".", "port", ":", "return", "'%s:%d'", "%", "(", "self", ".", "host", ",", "self", ".", "port", ")", "return", "self", ".", "host" ]
cae8d76c210b9777e90aab76e9c4b0e53bb19cde
train
Url.url
Convert self into a url This function should more or less round-trip with :func:`.parse_url`. The returned url may not be exactly the same as the url inputted to :func:`.parse_url`, but it should be equivalent by the RFC (e.g., urls with a blank port will have : removed). Example: :: >>> U = parse_url('http://google.com/mail/') >>> U.url 'http://google.com/mail/' >>> Url('http', 'username:password', 'host.com', 80, ... '/path', 'query', 'fragment').url 'http://username:password@host.com:80/path?query#fragment'
pipenv/vendor/urllib3/util/url.py
def url(self): """ Convert self into a url This function should more or less round-trip with :func:`.parse_url`. The returned url may not be exactly the same as the url inputted to :func:`.parse_url`, but it should be equivalent by the RFC (e.g., urls with a blank port will have : removed). Example: :: >>> U = parse_url('http://google.com/mail/') >>> U.url 'http://google.com/mail/' >>> Url('http', 'username:password', 'host.com', 80, ... '/path', 'query', 'fragment').url 'http://username:password@host.com:80/path?query#fragment' """ scheme, auth, host, port, path, query, fragment = self url = '' # We use "is not None" we want things to happen with empty strings (or 0 port) if scheme is not None: url += scheme + '://' if auth is not None: url += auth + '@' if host is not None: url += host if port is not None: url += ':' + str(port) if path is not None: url += path if query is not None: url += '?' + query if fragment is not None: url += '#' + fragment return url
def url(self): """ Convert self into a url This function should more or less round-trip with :func:`.parse_url`. The returned url may not be exactly the same as the url inputted to :func:`.parse_url`, but it should be equivalent by the RFC (e.g., urls with a blank port will have : removed). Example: :: >>> U = parse_url('http://google.com/mail/') >>> U.url 'http://google.com/mail/' >>> Url('http', 'username:password', 'host.com', 80, ... '/path', 'query', 'fragment').url 'http://username:password@host.com:80/path?query#fragment' """ scheme, auth, host, port, path, query, fragment = self url = '' # We use "is not None" we want things to happen with empty strings (or 0 port) if scheme is not None: url += scheme + '://' if auth is not None: url += auth + '@' if host is not None: url += host if port is not None: url += ':' + str(port) if path is not None: url += path if query is not None: url += '?' + query if fragment is not None: url += '#' + fragment return url
[ "Convert", "self", "into", "a", "url" ]
pypa/pipenv
python
https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/vendor/urllib3/util/url.py#L56-L93
[ "def", "url", "(", "self", ")", ":", "scheme", ",", "auth", ",", "host", ",", "port", ",", "path", ",", "query", ",", "fragment", "=", "self", "url", "=", "''", "# We use \"is not None\" we want things to happen with empty strings (or 0 port)", "if", "scheme", "...
cae8d76c210b9777e90aab76e9c4b0e53bb19cde
train
split_template_path
Split a path into segments and perform a sanity check. If it detects '..' in the path it will raise a `TemplateNotFound` error.
pipenv/vendor/jinja2/loaders.py
def split_template_path(template): """Split a path into segments and perform a sanity check. If it detects '..' in the path it will raise a `TemplateNotFound` error. """ pieces = [] for piece in template.split('/'): if path.sep in piece \ or (path.altsep and path.altsep in piece) or \ piece == path.pardir: raise TemplateNotFound(template) elif piece and piece != '.': pieces.append(piece) return pieces
def split_template_path(template): """Split a path into segments and perform a sanity check. If it detects '..' in the path it will raise a `TemplateNotFound` error. """ pieces = [] for piece in template.split('/'): if path.sep in piece \ or (path.altsep and path.altsep in piece) or \ piece == path.pardir: raise TemplateNotFound(template) elif piece and piece != '.': pieces.append(piece) return pieces
[ "Split", "a", "path", "into", "segments", "and", "perform", "a", "sanity", "check", ".", "If", "it", "detects", "..", "in", "the", "path", "it", "will", "raise", "a", "TemplateNotFound", "error", "." ]
pypa/pipenv
python
https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/vendor/jinja2/loaders.py#L22-L34
[ "def", "split_template_path", "(", "template", ")", ":", "pieces", "=", "[", "]", "for", "piece", "in", "template", ".", "split", "(", "'/'", ")", ":", "if", "path", ".", "sep", "in", "piece", "or", "(", "path", ".", "altsep", "and", "path", ".", "...
cae8d76c210b9777e90aab76e9c4b0e53bb19cde
train
BaseLoader.get_source
Get the template source, filename and reload helper for a template. It's passed the environment and template name and has to return a tuple in the form ``(source, filename, uptodate)`` or raise a `TemplateNotFound` error if it can't locate the template. The source part of the returned tuple must be the source of the template as unicode string or a ASCII bytestring. The filename should be the name of the file on the filesystem if it was loaded from there, otherwise `None`. The filename is used by python for the tracebacks if no loader extension is used. The last item in the tuple is the `uptodate` function. If auto reloading is enabled it's always called to check if the template changed. No arguments are passed so the function must store the old state somewhere (for example in a closure). If it returns `False` the template will be reloaded.
pipenv/vendor/jinja2/loaders.py
def get_source(self, environment, template): """Get the template source, filename and reload helper for a template. It's passed the environment and template name and has to return a tuple in the form ``(source, filename, uptodate)`` or raise a `TemplateNotFound` error if it can't locate the template. The source part of the returned tuple must be the source of the template as unicode string or a ASCII bytestring. The filename should be the name of the file on the filesystem if it was loaded from there, otherwise `None`. The filename is used by python for the tracebacks if no loader extension is used. The last item in the tuple is the `uptodate` function. If auto reloading is enabled it's always called to check if the template changed. No arguments are passed so the function must store the old state somewhere (for example in a closure). If it returns `False` the template will be reloaded. """ if not self.has_source_access: raise RuntimeError('%s cannot provide access to the source' % self.__class__.__name__) raise TemplateNotFound(template)
def get_source(self, environment, template): """Get the template source, filename and reload helper for a template. It's passed the environment and template name and has to return a tuple in the form ``(source, filename, uptodate)`` or raise a `TemplateNotFound` error if it can't locate the template. The source part of the returned tuple must be the source of the template as unicode string or a ASCII bytestring. The filename should be the name of the file on the filesystem if it was loaded from there, otherwise `None`. The filename is used by python for the tracebacks if no loader extension is used. The last item in the tuple is the `uptodate` function. If auto reloading is enabled it's always called to check if the template changed. No arguments are passed so the function must store the old state somewhere (for example in a closure). If it returns `False` the template will be reloaded. """ if not self.has_source_access: raise RuntimeError('%s cannot provide access to the source' % self.__class__.__name__) raise TemplateNotFound(template)
[ "Get", "the", "template", "source", "filename", "and", "reload", "helper", "for", "a", "template", ".", "It", "s", "passed", "the", "environment", "and", "template", "name", "and", "has", "to", "return", "a", "tuple", "in", "the", "form", "(", "source", ...
pypa/pipenv
python
https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/vendor/jinja2/loaders.py#L70-L91
[ "def", "get_source", "(", "self", ",", "environment", ",", "template", ")", ":", "if", "not", "self", ".", "has_source_access", ":", "raise", "RuntimeError", "(", "'%s cannot provide access to the source'", "%", "self", ".", "__class__", ".", "__name__", ")", "r...
cae8d76c210b9777e90aab76e9c4b0e53bb19cde
train
BaseLoader.load
Loads a template. This method looks up the template in the cache or loads one by calling :meth:`get_source`. Subclasses should not override this method as loaders working on collections of other loaders (such as :class:`PrefixLoader` or :class:`ChoiceLoader`) will not call this method but `get_source` directly.
pipenv/vendor/jinja2/loaders.py
def load(self, environment, name, globals=None): """Loads a template. This method looks up the template in the cache or loads one by calling :meth:`get_source`. Subclasses should not override this method as loaders working on collections of other loaders (such as :class:`PrefixLoader` or :class:`ChoiceLoader`) will not call this method but `get_source` directly. """ code = None if globals is None: globals = {} # first we try to get the source for this template together # with the filename and the uptodate function. source, filename, uptodate = self.get_source(environment, name) # try to load the code from the bytecode cache if there is a # bytecode cache configured. bcc = environment.bytecode_cache if bcc is not None: bucket = bcc.get_bucket(environment, name, filename, source) code = bucket.code # if we don't have code so far (not cached, no longer up to # date) etc. we compile the template if code is None: code = environment.compile(source, name, filename) # if the bytecode cache is available and the bucket doesn't # have a code so far, we give the bucket the new code and put # it back to the bytecode cache. if bcc is not None and bucket.code is None: bucket.code = code bcc.set_bucket(bucket) return environment.template_class.from_code(environment, code, globals, uptodate)
def load(self, environment, name, globals=None): """Loads a template. This method looks up the template in the cache or loads one by calling :meth:`get_source`. Subclasses should not override this method as loaders working on collections of other loaders (such as :class:`PrefixLoader` or :class:`ChoiceLoader`) will not call this method but `get_source` directly. """ code = None if globals is None: globals = {} # first we try to get the source for this template together # with the filename and the uptodate function. source, filename, uptodate = self.get_source(environment, name) # try to load the code from the bytecode cache if there is a # bytecode cache configured. bcc = environment.bytecode_cache if bcc is not None: bucket = bcc.get_bucket(environment, name, filename, source) code = bucket.code # if we don't have code so far (not cached, no longer up to # date) etc. we compile the template if code is None: code = environment.compile(source, name, filename) # if the bytecode cache is available and the bucket doesn't # have a code so far, we give the bucket the new code and put # it back to the bytecode cache. if bcc is not None and bucket.code is None: bucket.code = code bcc.set_bucket(bucket) return environment.template_class.from_code(environment, code, globals, uptodate)
[ "Loads", "a", "template", ".", "This", "method", "looks", "up", "the", "template", "in", "the", "cache", "or", "loads", "one", "by", "calling", ":", "meth", ":", "get_source", ".", "Subclasses", "should", "not", "override", "this", "method", "as", "loaders...
pypa/pipenv
python
https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/vendor/jinja2/loaders.py#L100-L135
[ "def", "load", "(", "self", ",", "environment", ",", "name", ",", "globals", "=", "None", ")", ":", "code", "=", "None", "if", "globals", "is", "None", ":", "globals", "=", "{", "}", "# first we try to get the source for this template together", "# with the file...
cae8d76c210b9777e90aab76e9c4b0e53bb19cde
train
description_of
Return a string describing the probable encoding of a file or list of strings. :param lines: The lines to get the encoding of. :type lines: Iterable of bytes :param name: Name of file or collection of lines :type name: str
pipenv/vendor/chardet/cli/chardetect.py
def description_of(lines, name='stdin'): """ Return a string describing the probable encoding of a file or list of strings. :param lines: The lines to get the encoding of. :type lines: Iterable of bytes :param name: Name of file or collection of lines :type name: str """ u = UniversalDetector() for line in lines: line = bytearray(line) u.feed(line) # shortcut out of the loop to save reading further - particularly useful if we read a BOM. if u.done: break u.close() result = u.result if PY2: name = name.decode(sys.getfilesystemencoding(), 'ignore') if result['encoding']: return '{0}: {1} with confidence {2}'.format(name, result['encoding'], result['confidence']) else: return '{0}: no result'.format(name)
def description_of(lines, name='stdin'): """ Return a string describing the probable encoding of a file or list of strings. :param lines: The lines to get the encoding of. :type lines: Iterable of bytes :param name: Name of file or collection of lines :type name: str """ u = UniversalDetector() for line in lines: line = bytearray(line) u.feed(line) # shortcut out of the loop to save reading further - particularly useful if we read a BOM. if u.done: break u.close() result = u.result if PY2: name = name.decode(sys.getfilesystemencoding(), 'ignore') if result['encoding']: return '{0}: {1} with confidence {2}'.format(name, result['encoding'], result['confidence']) else: return '{0}: no result'.format(name)
[ "Return", "a", "string", "describing", "the", "probable", "encoding", "of", "a", "file", "or", "list", "of", "strings", "." ]
pypa/pipenv
python
https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/vendor/chardet/cli/chardetect.py#L26-L51
[ "def", "description_of", "(", "lines", ",", "name", "=", "'stdin'", ")", ":", "u", "=", "UniversalDetector", "(", ")", "for", "line", "in", "lines", ":", "line", "=", "bytearray", "(", "line", ")", "u", ".", "feed", "(", "line", ")", "# shortcut out of...
cae8d76c210b9777e90aab76e9c4b0e53bb19cde
train
to_genshi
Convert a tree to a genshi tree :arg walker: the treewalker to use to walk the tree to convert it :returns: generator of genshi nodes
pipenv/patched/notpip/_vendor/html5lib/treeadapters/genshi.py
def to_genshi(walker): """Convert a tree to a genshi tree :arg walker: the treewalker to use to walk the tree to convert it :returns: generator of genshi nodes """ text = [] for token in walker: type = token["type"] if type in ("Characters", "SpaceCharacters"): text.append(token["data"]) elif text: yield TEXT, "".join(text), (None, -1, -1) text = [] if type in ("StartTag", "EmptyTag"): if token["namespace"]: name = "{%s}%s" % (token["namespace"], token["name"]) else: name = token["name"] attrs = Attrs([(QName("{%s}%s" % attr if attr[0] is not None else attr[1]), value) for attr, value in token["data"].items()]) yield (START, (QName(name), attrs), (None, -1, -1)) if type == "EmptyTag": type = "EndTag" if type == "EndTag": if token["namespace"]: name = "{%s}%s" % (token["namespace"], token["name"]) else: name = token["name"] yield END, QName(name), (None, -1, -1) elif type == "Comment": yield COMMENT, token["data"], (None, -1, -1) elif type == "Doctype": yield DOCTYPE, (token["name"], token["publicId"], token["systemId"]), (None, -1, -1) else: pass # FIXME: What to do? if text: yield TEXT, "".join(text), (None, -1, -1)
def to_genshi(walker): """Convert a tree to a genshi tree :arg walker: the treewalker to use to walk the tree to convert it :returns: generator of genshi nodes """ text = [] for token in walker: type = token["type"] if type in ("Characters", "SpaceCharacters"): text.append(token["data"]) elif text: yield TEXT, "".join(text), (None, -1, -1) text = [] if type in ("StartTag", "EmptyTag"): if token["namespace"]: name = "{%s}%s" % (token["namespace"], token["name"]) else: name = token["name"] attrs = Attrs([(QName("{%s}%s" % attr if attr[0] is not None else attr[1]), value) for attr, value in token["data"].items()]) yield (START, (QName(name), attrs), (None, -1, -1)) if type == "EmptyTag": type = "EndTag" if type == "EndTag": if token["namespace"]: name = "{%s}%s" % (token["namespace"], token["name"]) else: name = token["name"] yield END, QName(name), (None, -1, -1) elif type == "Comment": yield COMMENT, token["data"], (None, -1, -1) elif type == "Doctype": yield DOCTYPE, (token["name"], token["publicId"], token["systemId"]), (None, -1, -1) else: pass # FIXME: What to do? if text: yield TEXT, "".join(text), (None, -1, -1)
[ "Convert", "a", "tree", "to", "a", "genshi", "tree" ]
pypa/pipenv
python
https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/patched/notpip/_vendor/html5lib/treeadapters/genshi.py#L7-L54
[ "def", "to_genshi", "(", "walker", ")", ":", "text", "=", "[", "]", "for", "token", "in", "walker", ":", "type", "=", "token", "[", "\"type\"", "]", "if", "type", "in", "(", "\"Characters\"", ",", "\"SpaceCharacters\"", ")", ":", "text", ".", "append",...
cae8d76c210b9777e90aab76e9c4b0e53bb19cde
train
parse_requirements
Parse a requirements formatted file. Traverse a string until a delimiter is detected, then split at said delimiter, get module name by element index, create a dict consisting of module:version, and add dict to list of parsed modules. Args: file_: File to parse. Raises: OSerror: If there's any issues accessing the file. Returns: tuple: The contents of the file, excluding comments.
pipenv/vendor/pipreqs/pipreqs.py
def parse_requirements(file_): """Parse a requirements formatted file. Traverse a string until a delimiter is detected, then split at said delimiter, get module name by element index, create a dict consisting of module:version, and add dict to list of parsed modules. Args: file_: File to parse. Raises: OSerror: If there's any issues accessing the file. Returns: tuple: The contents of the file, excluding comments. """ modules = [] delim = ["<", ">", "=", "!", "~"] # https://www.python.org/dev/peps/pep-0508/#complete-grammar try: f = open_func(file_, "r") except OSError: logging.error("Failed on file: {}".format(file_)) raise else: data = [x.strip() for x in f.readlines() if x != "\n"] finally: f.close() data = [x for x in data if x[0].isalpha()] for x in data: if not any([y in x for y in delim]): # Check for modules w/o a specifier. modules.append({"name": x, "version": None}) for y in x: if y in delim: module = x.split(y) module_name = module[0] module_version = module[-1].replace("=", "") module = {"name": module_name, "version": module_version} if module not in modules: modules.append(module) break return modules
def parse_requirements(file_): """Parse a requirements formatted file. Traverse a string until a delimiter is detected, then split at said delimiter, get module name by element index, create a dict consisting of module:version, and add dict to list of parsed modules. Args: file_: File to parse. Raises: OSerror: If there's any issues accessing the file. Returns: tuple: The contents of the file, excluding comments. """ modules = [] delim = ["<", ">", "=", "!", "~"] # https://www.python.org/dev/peps/pep-0508/#complete-grammar try: f = open_func(file_, "r") except OSError: logging.error("Failed on file: {}".format(file_)) raise else: data = [x.strip() for x in f.readlines() if x != "\n"] finally: f.close() data = [x for x in data if x[0].isalpha()] for x in data: if not any([y in x for y in delim]): # Check for modules w/o a specifier. modules.append({"name": x, "version": None}) for y in x: if y in delim: module = x.split(y) module_name = module[0] module_version = module[-1].replace("=", "") module = {"name": module_name, "version": module_version} if module not in modules: modules.append(module) break return modules
[ "Parse", "a", "requirements", "formatted", "file", "." ]
pypa/pipenv
python
https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/vendor/pipreqs/pipreqs.py#L231-L277
[ "def", "parse_requirements", "(", "file_", ")", ":", "modules", "=", "[", "]", "delim", "=", "[", "\"<\"", ",", "\">\"", ",", "\"=\"", ",", "\"!\"", ",", "\"~\"", "]", "# https://www.python.org/dev/peps/pep-0508/#complete-grammar", "try", ":", "f", "=", "open_...
cae8d76c210b9777e90aab76e9c4b0e53bb19cde
train
compare_modules
Compare modules in a file to imported modules in a project. Args: file_ (str): File to parse for modules to be compared. imports (tuple): Modules being imported in the project. Returns: tuple: The modules not imported in the project, but do exist in the specified file.
pipenv/vendor/pipreqs/pipreqs.py
def compare_modules(file_, imports): """Compare modules in a file to imported modules in a project. Args: file_ (str): File to parse for modules to be compared. imports (tuple): Modules being imported in the project. Returns: tuple: The modules not imported in the project, but do exist in the specified file. """ modules = parse_requirements(file_) imports = [imports[i]["name"] for i in range(len(imports))] modules = [modules[i]["name"] for i in range(len(modules))] modules_not_imported = set(modules) - set(imports) return modules_not_imported
def compare_modules(file_, imports): """Compare modules in a file to imported modules in a project. Args: file_ (str): File to parse for modules to be compared. imports (tuple): Modules being imported in the project. Returns: tuple: The modules not imported in the project, but do exist in the specified file. """ modules = parse_requirements(file_) imports = [imports[i]["name"] for i in range(len(imports))] modules = [modules[i]["name"] for i in range(len(modules))] modules_not_imported = set(modules) - set(imports) return modules_not_imported
[ "Compare", "modules", "in", "a", "file", "to", "imported", "modules", "in", "a", "project", "." ]
pypa/pipenv
python
https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/vendor/pipreqs/pipreqs.py#L280-L297
[ "def", "compare_modules", "(", "file_", ",", "imports", ")", ":", "modules", "=", "parse_requirements", "(", "file_", ")", "imports", "=", "[", "imports", "[", "i", "]", "[", "\"name\"", "]", "for", "i", "in", "range", "(", "len", "(", "imports", ")", ...
cae8d76c210b9777e90aab76e9c4b0e53bb19cde
train
diff
Display the difference between modules in a file and imported modules.
pipenv/vendor/pipreqs/pipreqs.py
def diff(file_, imports): """Display the difference between modules in a file and imported modules.""" modules_not_imported = compare_modules(file_, imports) logging.info("The following modules are in {} but do not seem to be imported: " "{}".format(file_, ", ".join(x for x in modules_not_imported)))
def diff(file_, imports): """Display the difference between modules in a file and imported modules.""" modules_not_imported = compare_modules(file_, imports) logging.info("The following modules are in {} but do not seem to be imported: " "{}".format(file_, ", ".join(x for x in modules_not_imported)))
[ "Display", "the", "difference", "between", "modules", "in", "a", "file", "and", "imported", "modules", "." ]
pypa/pipenv
python
https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/vendor/pipreqs/pipreqs.py#L300-L305
[ "def", "diff", "(", "file_", ",", "imports", ")", ":", "modules_not_imported", "=", "compare_modules", "(", "file_", ",", "imports", ")", "logging", ".", "info", "(", "\"The following modules are in {} but do not seem to be imported: \"", "\"{}\"", ".", "format", "(",...
cae8d76c210b9777e90aab76e9c4b0e53bb19cde
train
clean
Remove modules that aren't imported in project from file.
pipenv/vendor/pipreqs/pipreqs.py
def clean(file_, imports): """Remove modules that aren't imported in project from file.""" modules_not_imported = compare_modules(file_, imports) re_remove = re.compile("|".join(modules_not_imported)) to_write = [] try: f = open_func(file_, "r+") except OSError: logging.error("Failed on file: {}".format(file_)) raise else: for i in f.readlines(): if re_remove.match(i) is None: to_write.append(i) f.seek(0) f.truncate() for i in to_write: f.write(i) finally: f.close() logging.info("Successfully cleaned up requirements in " + file_)
def clean(file_, imports): """Remove modules that aren't imported in project from file.""" modules_not_imported = compare_modules(file_, imports) re_remove = re.compile("|".join(modules_not_imported)) to_write = [] try: f = open_func(file_, "r+") except OSError: logging.error("Failed on file: {}".format(file_)) raise else: for i in f.readlines(): if re_remove.match(i) is None: to_write.append(i) f.seek(0) f.truncate() for i in to_write: f.write(i) finally: f.close() logging.info("Successfully cleaned up requirements in " + file_)
[ "Remove", "modules", "that", "aren", "t", "imported", "in", "project", "from", "file", "." ]
pypa/pipenv
python
https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/vendor/pipreqs/pipreqs.py#L307-L330
[ "def", "clean", "(", "file_", ",", "imports", ")", ":", "modules_not_imported", "=", "compare_modules", "(", "file_", ",", "imports", ")", "re_remove", "=", "re", ".", "compile", "(", "\"|\"", ".", "join", "(", "modules_not_imported", ")", ")", "to_write", ...
cae8d76c210b9777e90aab76e9c4b0e53bb19cde
train
read_requirements
Reads requirements from a file like object and (optionally) from referenced files. :param fh: file like object to read from :param resolve: boolean. resolves referenced files. :return: generator
pipenv/patched/safety/util.py
def read_requirements(fh, resolve=False): """ Reads requirements from a file like object and (optionally) from referenced files. :param fh: file like object to read from :param resolve: boolean. resolves referenced files. :return: generator """ is_temp_file = not hasattr(fh, 'name') for num, line in enumerate(iter_lines(fh)): line = line.strip() if not line: # skip empty lines continue if line.startswith('#') or \ line.startswith('-i') or \ line.startswith('--index-url') or \ line.startswith('--extra-index-url') or \ line.startswith('-f') or line.startswith('--find-links') or \ line.startswith('--no-index') or line.startswith('--allow-external') or \ line.startswith('--allow-unverified') or line.startswith('-Z') or \ line.startswith('--always-unzip'): # skip unsupported lines continue elif line.startswith('-r') or line.startswith('--requirement'): # got a referenced file here, try to resolve the path # if this is a tempfile, skip if is_temp_file: continue filename = line.strip("-r ").strip("--requirement").strip() # if there is a comment, remove it if " #" in filename: filename = filename.split(" #")[0].strip() req_file_path = os.path.join(os.path.dirname(fh.name), filename) if resolve: # recursively yield the resolved requirements if os.path.exists(req_file_path): with open(req_file_path) as _fh: for req in read_requirements(_fh, resolve=True): yield req else: yield RequirementFile(path=req_file_path) else: try: parseable_line = line # multiline requirements are not parseable if "\\" in line: parseable_line = line.replace("\\", "") for next_line in iter_lines(fh, num + 1): parseable_line += next_line.strip().replace("\\", "") line += "\n" + next_line if "\\" in next_line: continue break req, = parse_line(parseable_line) if len(req.specifier._specs) == 1 and \ next(iter(req.specifier._specs))._spec[0] == "==": yield Package(key=req.name, version=next(iter(req.specifier._specs))._spec[1]) else: try: fname = fh.name except AttributeError: fname = line click.secho( "Warning: unpinned requirement '{req}' found in {fname}, " "unable to check.".format(req=req.name, fname=fname), fg="yellow", file=sys.stderr ) except ValueError: continue
def read_requirements(fh, resolve=False): """ Reads requirements from a file like object and (optionally) from referenced files. :param fh: file like object to read from :param resolve: boolean. resolves referenced files. :return: generator """ is_temp_file = not hasattr(fh, 'name') for num, line in enumerate(iter_lines(fh)): line = line.strip() if not line: # skip empty lines continue if line.startswith('#') or \ line.startswith('-i') or \ line.startswith('--index-url') or \ line.startswith('--extra-index-url') or \ line.startswith('-f') or line.startswith('--find-links') or \ line.startswith('--no-index') or line.startswith('--allow-external') or \ line.startswith('--allow-unverified') or line.startswith('-Z') or \ line.startswith('--always-unzip'): # skip unsupported lines continue elif line.startswith('-r') or line.startswith('--requirement'): # got a referenced file here, try to resolve the path # if this is a tempfile, skip if is_temp_file: continue filename = line.strip("-r ").strip("--requirement").strip() # if there is a comment, remove it if " #" in filename: filename = filename.split(" #")[0].strip() req_file_path = os.path.join(os.path.dirname(fh.name), filename) if resolve: # recursively yield the resolved requirements if os.path.exists(req_file_path): with open(req_file_path) as _fh: for req in read_requirements(_fh, resolve=True): yield req else: yield RequirementFile(path=req_file_path) else: try: parseable_line = line # multiline requirements are not parseable if "\\" in line: parseable_line = line.replace("\\", "") for next_line in iter_lines(fh, num + 1): parseable_line += next_line.strip().replace("\\", "") line += "\n" + next_line if "\\" in next_line: continue break req, = parse_line(parseable_line) if len(req.specifier._specs) == 1 and \ next(iter(req.specifier._specs))._spec[0] == "==": yield Package(key=req.name, version=next(iter(req.specifier._specs))._spec[1]) else: try: fname = fh.name except AttributeError: fname = line click.secho( "Warning: unpinned requirement '{req}' found in {fname}, " "unable to check.".format(req=req.name, fname=fname), fg="yellow", file=sys.stderr ) except ValueError: continue
[ "Reads", "requirements", "from", "a", "file", "like", "object", "and", "(", "optionally", ")", "from", "referenced", "files", ".", ":", "param", "fh", ":", "file", "like", "object", "to", "read", "from", ":", "param", "resolve", ":", "boolean", ".", "res...
pypa/pipenv
python
https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/patched/safety/util.py#L27-L98
[ "def", "read_requirements", "(", "fh", ",", "resolve", "=", "False", ")", ":", "is_temp_file", "=", "not", "hasattr", "(", "fh", ",", "'name'", ")", "for", "num", ",", "line", "in", "enumerate", "(", "iter_lines", "(", "fh", ")", ")", ":", "line", "=...
cae8d76c210b9777e90aab76e9c4b0e53bb19cde
train
deprecated
Helper to deprecate existing functionality. reason: Textual reason shown to the user about why this functionality has been deprecated. replacement: Textual suggestion shown to the user about what alternative functionality they can use. gone_in: The version of pip does this functionality should get removed in. Raises errors if pip's current version is greater than or equal to this. issue: Issue number on the tracker that would serve as a useful place for users to find related discussion and provide feedback. Always pass replacement, gone_in and issue as keyword arguments for clarity at the call site.
pipenv/patched/notpip/_internal/utils/deprecation.py
def deprecated(reason, replacement, gone_in, issue=None): # type: (str, Optional[str], Optional[str], Optional[int]) -> None """Helper to deprecate existing functionality. reason: Textual reason shown to the user about why this functionality has been deprecated. replacement: Textual suggestion shown to the user about what alternative functionality they can use. gone_in: The version of pip does this functionality should get removed in. Raises errors if pip's current version is greater than or equal to this. issue: Issue number on the tracker that would serve as a useful place for users to find related discussion and provide feedback. Always pass replacement, gone_in and issue as keyword arguments for clarity at the call site. """ # Construct a nice message. # This is purposely eagerly formatted as we want it to appear as if someone # typed this entire message out. message = "DEPRECATION: " + reason if replacement is not None: message += " A possible replacement is {}.".format(replacement) if issue is not None: url = "https://github.com/pypa/pip/issues/" + str(issue) message += " You can find discussion regarding this at {}.".format(url) # Raise as an error if it has to be removed. if gone_in is not None and parse(current_version) >= parse(gone_in): raise PipDeprecationWarning(message) warnings.warn(message, category=PipDeprecationWarning, stacklevel=2)
def deprecated(reason, replacement, gone_in, issue=None): # type: (str, Optional[str], Optional[str], Optional[int]) -> None """Helper to deprecate existing functionality. reason: Textual reason shown to the user about why this functionality has been deprecated. replacement: Textual suggestion shown to the user about what alternative functionality they can use. gone_in: The version of pip does this functionality should get removed in. Raises errors if pip's current version is greater than or equal to this. issue: Issue number on the tracker that would serve as a useful place for users to find related discussion and provide feedback. Always pass replacement, gone_in and issue as keyword arguments for clarity at the call site. """ # Construct a nice message. # This is purposely eagerly formatted as we want it to appear as if someone # typed this entire message out. message = "DEPRECATION: " + reason if replacement is not None: message += " A possible replacement is {}.".format(replacement) if issue is not None: url = "https://github.com/pypa/pip/issues/" + str(issue) message += " You can find discussion regarding this at {}.".format(url) # Raise as an error if it has to be removed. if gone_in is not None and parse(current_version) >= parse(gone_in): raise PipDeprecationWarning(message) warnings.warn(message, category=PipDeprecationWarning, stacklevel=2)
[ "Helper", "to", "deprecate", "existing", "functionality", "." ]
pypa/pipenv
python
https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/patched/notpip/_internal/utils/deprecation.py#L55-L90
[ "def", "deprecated", "(", "reason", ",", "replacement", ",", "gone_in", ",", "issue", "=", "None", ")", ":", "# type: (str, Optional[str], Optional[str], Optional[int]) -> None", "# Construct a nice message.", "# This is purposely eagerly formatted as we want it to appear as if someo...
cae8d76c210b9777e90aab76e9c4b0e53bb19cde
train
_ipaddress_match
Exact matching of IP addresses. RFC 6125 explicitly doesn't define an algorithm for this (section 1.7.2 - "Out of Scope").
pipenv/vendor/urllib3/packages/ssl_match_hostname/_implementation.py
def _ipaddress_match(ipname, host_ip): """Exact matching of IP addresses. RFC 6125 explicitly doesn't define an algorithm for this (section 1.7.2 - "Out of Scope"). """ # OpenSSL may add a trailing newline to a subjectAltName's IP address # Divergence from upstream: ipaddress can't handle byte str ip = ipaddress.ip_address(_to_unicode(ipname).rstrip()) return ip == host_ip
def _ipaddress_match(ipname, host_ip): """Exact matching of IP addresses. RFC 6125 explicitly doesn't define an algorithm for this (section 1.7.2 - "Out of Scope"). """ # OpenSSL may add a trailing newline to a subjectAltName's IP address # Divergence from upstream: ipaddress can't handle byte str ip = ipaddress.ip_address(_to_unicode(ipname).rstrip()) return ip == host_ip
[ "Exact", "matching", "of", "IP", "addresses", "." ]
pypa/pipenv
python
https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/vendor/urllib3/packages/ssl_match_hostname/_implementation.py#L83-L92
[ "def", "_ipaddress_match", "(", "ipname", ",", "host_ip", ")", ":", "# OpenSSL may add a trailing newline to a subjectAltName's IP address", "# Divergence from upstream: ipaddress can't handle byte str", "ip", "=", "ipaddress", ".", "ip_address", "(", "_to_unicode", "(", "ipname"...
cae8d76c210b9777e90aab76e9c4b0e53bb19cde
train
set_metadata
Add "metadata" to candidates based on the dependency tree. Metadata for a candidate includes markers and a specifier for Python version requirements. :param candidates: A key-candidate mapping. Candidates in the mapping will have their markers set. :param traces: A graph trace (produced by `traces.trace_graph`) providing information about dependency relationships between candidates. :param dependencies: A key-collection mapping containing what dependencies each candidate in `candidates` requested. :param pythons: A key-str mapping containing Requires-Python information of each candidate. Keys in mappings and entries in the trace are identifiers of a package, as implemented by the `identify` method of the resolver's provider. The candidates are modified in-place.
pipenv/vendor/passa/models/metadata.py
def set_metadata(candidates, traces, dependencies, pythons): """Add "metadata" to candidates based on the dependency tree. Metadata for a candidate includes markers and a specifier for Python version requirements. :param candidates: A key-candidate mapping. Candidates in the mapping will have their markers set. :param traces: A graph trace (produced by `traces.trace_graph`) providing information about dependency relationships between candidates. :param dependencies: A key-collection mapping containing what dependencies each candidate in `candidates` requested. :param pythons: A key-str mapping containing Requires-Python information of each candidate. Keys in mappings and entries in the trace are identifiers of a package, as implemented by the `identify` method of the resolver's provider. The candidates are modified in-place. """ metasets_mapping = _calculate_metasets_mapping( dependencies, pythons, copy.deepcopy(traces), ) for key, candidate in candidates.items(): candidate.markers = _format_metasets(metasets_mapping[key])
def set_metadata(candidates, traces, dependencies, pythons): """Add "metadata" to candidates based on the dependency tree. Metadata for a candidate includes markers and a specifier for Python version requirements. :param candidates: A key-candidate mapping. Candidates in the mapping will have their markers set. :param traces: A graph trace (produced by `traces.trace_graph`) providing information about dependency relationships between candidates. :param dependencies: A key-collection mapping containing what dependencies each candidate in `candidates` requested. :param pythons: A key-str mapping containing Requires-Python information of each candidate. Keys in mappings and entries in the trace are identifiers of a package, as implemented by the `identify` method of the resolver's provider. The candidates are modified in-place. """ metasets_mapping = _calculate_metasets_mapping( dependencies, pythons, copy.deepcopy(traces), ) for key, candidate in candidates.items(): candidate.markers = _format_metasets(metasets_mapping[key])
[ "Add", "metadata", "to", "candidates", "based", "on", "the", "dependency", "tree", "." ]
pypa/pipenv
python
https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/vendor/passa/models/metadata.py#L145-L169
[ "def", "set_metadata", "(", "candidates", ",", "traces", ",", "dependencies", ",", "pythons", ")", ":", "metasets_mapping", "=", "_calculate_metasets_mapping", "(", "dependencies", ",", "pythons", ",", "copy", ".", "deepcopy", "(", "traces", ")", ",", ")", "fo...
cae8d76c210b9777e90aab76e9c4b0e53bb19cde
train
_walk
Like Python 3.5's implementation of os.walk() -- faster than the pre-Python 3.5 version as it uses scandir() internally.
pipenv/vendor/scandir.py
def _walk(top, topdown=True, onerror=None, followlinks=False): """Like Python 3.5's implementation of os.walk() -- faster than the pre-Python 3.5 version as it uses scandir() internally. """ dirs = [] nondirs = [] # We may not have read permission for top, in which case we can't # get a list of the files the directory contains. os.walk # always suppressed the exception then, rather than blow up for a # minor reason when (say) a thousand readable directories are still # left to visit. That logic is copied here. try: scandir_it = scandir(top) except OSError as error: if onerror is not None: onerror(error) return while True: try: try: entry = next(scandir_it) except StopIteration: break except OSError as error: if onerror is not None: onerror(error) return try: is_dir = entry.is_dir() except OSError: # If is_dir() raises an OSError, consider that the entry is not # a directory, same behaviour than os.path.isdir(). is_dir = False if is_dir: dirs.append(entry.name) else: nondirs.append(entry.name) if not topdown and is_dir: # Bottom-up: recurse into sub-directory, but exclude symlinks to # directories if followlinks is False if followlinks: walk_into = True else: try: is_symlink = entry.is_symlink() except OSError: # If is_symlink() raises an OSError, consider that the # entry is not a symbolic link, same behaviour than # os.path.islink(). is_symlink = False walk_into = not is_symlink if walk_into: for entry in walk(entry.path, topdown, onerror, followlinks): yield entry # Yield before recursion if going top down if topdown: yield top, dirs, nondirs # Recurse into sub-directories for name in dirs: new_path = join(top, name) # Issue #23605: os.path.islink() is used instead of caching # entry.is_symlink() result during the loop on os.scandir() because # the caller can replace the directory entry during the "yield" # above. if followlinks or not islink(new_path): for entry in walk(new_path, topdown, onerror, followlinks): yield entry else: # Yield after recursion if going bottom up yield top, dirs, nondirs
def _walk(top, topdown=True, onerror=None, followlinks=False): """Like Python 3.5's implementation of os.walk() -- faster than the pre-Python 3.5 version as it uses scandir() internally. """ dirs = [] nondirs = [] # We may not have read permission for top, in which case we can't # get a list of the files the directory contains. os.walk # always suppressed the exception then, rather than blow up for a # minor reason when (say) a thousand readable directories are still # left to visit. That logic is copied here. try: scandir_it = scandir(top) except OSError as error: if onerror is not None: onerror(error) return while True: try: try: entry = next(scandir_it) except StopIteration: break except OSError as error: if onerror is not None: onerror(error) return try: is_dir = entry.is_dir() except OSError: # If is_dir() raises an OSError, consider that the entry is not # a directory, same behaviour than os.path.isdir(). is_dir = False if is_dir: dirs.append(entry.name) else: nondirs.append(entry.name) if not topdown and is_dir: # Bottom-up: recurse into sub-directory, but exclude symlinks to # directories if followlinks is False if followlinks: walk_into = True else: try: is_symlink = entry.is_symlink() except OSError: # If is_symlink() raises an OSError, consider that the # entry is not a symbolic link, same behaviour than # os.path.islink(). is_symlink = False walk_into = not is_symlink if walk_into: for entry in walk(entry.path, topdown, onerror, followlinks): yield entry # Yield before recursion if going top down if topdown: yield top, dirs, nondirs # Recurse into sub-directories for name in dirs: new_path = join(top, name) # Issue #23605: os.path.islink() is used instead of caching # entry.is_symlink() result during the loop on os.scandir() because # the caller can replace the directory entry during the "yield" # above. if followlinks or not islink(new_path): for entry in walk(new_path, topdown, onerror, followlinks): yield entry else: # Yield after recursion if going bottom up yield top, dirs, nondirs
[ "Like", "Python", "3", ".", "5", "s", "implementation", "of", "os", ".", "walk", "()", "--", "faster", "than", "the", "pre", "-", "Python", "3", ".", "5", "version", "as", "it", "uses", "scandir", "()", "internally", "." ]
pypa/pipenv
python
https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/vendor/scandir.py#L600-L677
[ "def", "_walk", "(", "top", ",", "topdown", "=", "True", ",", "onerror", "=", "None", ",", "followlinks", "=", "False", ")", ":", "dirs", "=", "[", "]", "nondirs", "=", "[", "]", "# We may not have read permission for top, in which case we can't", "# get a list ...
cae8d76c210b9777e90aab76e9c4b0e53bb19cde
train
RequestMethods.request_encode_url
Make a request using :meth:`urlopen` with the ``fields`` encoded in the url. This is useful for request methods like GET, HEAD, DELETE, etc.
pipenv/vendor/urllib3/request.py
def request_encode_url(self, method, url, fields=None, headers=None, **urlopen_kw): """ Make a request using :meth:`urlopen` with the ``fields`` encoded in the url. This is useful for request methods like GET, HEAD, DELETE, etc. """ if headers is None: headers = self.headers extra_kw = {'headers': headers} extra_kw.update(urlopen_kw) if fields: url += '?' + urlencode(fields) return self.urlopen(method, url, **extra_kw)
def request_encode_url(self, method, url, fields=None, headers=None, **urlopen_kw): """ Make a request using :meth:`urlopen` with the ``fields`` encoded in the url. This is useful for request methods like GET, HEAD, DELETE, etc. """ if headers is None: headers = self.headers extra_kw = {'headers': headers} extra_kw.update(urlopen_kw) if fields: url += '?' + urlencode(fields) return self.urlopen(method, url, **extra_kw)
[ "Make", "a", "request", "using", ":", "meth", ":", "urlopen", "with", "the", "fields", "encoded", "in", "the", "url", ".", "This", "is", "useful", "for", "request", "methods", "like", "GET", "HEAD", "DELETE", "etc", "." ]
pypa/pipenv
python
https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/vendor/urllib3/request.py#L74-L89
[ "def", "request_encode_url", "(", "self", ",", "method", ",", "url", ",", "fields", "=", "None", ",", "headers", "=", "None", ",", "*", "*", "urlopen_kw", ")", ":", "if", "headers", "is", "None", ":", "headers", "=", "self", ".", "headers", "extra_kw",...
cae8d76c210b9777e90aab76e9c4b0e53bb19cde
train
RequestMethods.request_encode_body
Make a request using :meth:`urlopen` with the ``fields`` encoded in the body. This is useful for request methods like POST, PUT, PATCH, etc. When ``encode_multipart=True`` (default), then :meth:`urllib3.filepost.encode_multipart_formdata` is used to encode the payload with the appropriate content type. Otherwise :meth:`urllib.urlencode` is used with the 'application/x-www-form-urlencoded' content type. Multipart encoding must be used when posting files, and it's reasonably safe to use it in other times too. However, it may break request signing, such as with OAuth. Supports an optional ``fields`` parameter of key/value strings AND key/filetuple. A filetuple is a (filename, data, MIME type) tuple where the MIME type is optional. For example:: fields = { 'foo': 'bar', 'fakefile': ('foofile.txt', 'contents of foofile'), 'realfile': ('barfile.txt', open('realfile').read()), 'typedfile': ('bazfile.bin', open('bazfile').read(), 'image/jpeg'), 'nonamefile': 'contents of nonamefile field', } When uploading a file, providing a filename (the first parameter of the tuple) is optional but recommended to best mimic behavior of browsers. Note that if ``headers`` are supplied, the 'Content-Type' header will be overwritten because it depends on the dynamic random boundary string which is used to compose the body of the request. The random boundary string can be explicitly set with the ``multipart_boundary`` parameter.
pipenv/vendor/urllib3/request.py
def request_encode_body(self, method, url, fields=None, headers=None, encode_multipart=True, multipart_boundary=None, **urlopen_kw): """ Make a request using :meth:`urlopen` with the ``fields`` encoded in the body. This is useful for request methods like POST, PUT, PATCH, etc. When ``encode_multipart=True`` (default), then :meth:`urllib3.filepost.encode_multipart_formdata` is used to encode the payload with the appropriate content type. Otherwise :meth:`urllib.urlencode` is used with the 'application/x-www-form-urlencoded' content type. Multipart encoding must be used when posting files, and it's reasonably safe to use it in other times too. However, it may break request signing, such as with OAuth. Supports an optional ``fields`` parameter of key/value strings AND key/filetuple. A filetuple is a (filename, data, MIME type) tuple where the MIME type is optional. For example:: fields = { 'foo': 'bar', 'fakefile': ('foofile.txt', 'contents of foofile'), 'realfile': ('barfile.txt', open('realfile').read()), 'typedfile': ('bazfile.bin', open('bazfile').read(), 'image/jpeg'), 'nonamefile': 'contents of nonamefile field', } When uploading a file, providing a filename (the first parameter of the tuple) is optional but recommended to best mimic behavior of browsers. Note that if ``headers`` are supplied, the 'Content-Type' header will be overwritten because it depends on the dynamic random boundary string which is used to compose the body of the request. The random boundary string can be explicitly set with the ``multipart_boundary`` parameter. """ if headers is None: headers = self.headers extra_kw = {'headers': {}} if fields: if 'body' in urlopen_kw: raise TypeError( "request got values for both 'fields' and 'body', can only specify one.") if encode_multipart: body, content_type = encode_multipart_formdata(fields, boundary=multipart_boundary) else: body, content_type = urlencode(fields), 'application/x-www-form-urlencoded' extra_kw['body'] = body extra_kw['headers'] = {'Content-Type': content_type} extra_kw['headers'].update(headers) extra_kw.update(urlopen_kw) return self.urlopen(method, url, **extra_kw)
def request_encode_body(self, method, url, fields=None, headers=None, encode_multipart=True, multipart_boundary=None, **urlopen_kw): """ Make a request using :meth:`urlopen` with the ``fields`` encoded in the body. This is useful for request methods like POST, PUT, PATCH, etc. When ``encode_multipart=True`` (default), then :meth:`urllib3.filepost.encode_multipart_formdata` is used to encode the payload with the appropriate content type. Otherwise :meth:`urllib.urlencode` is used with the 'application/x-www-form-urlencoded' content type. Multipart encoding must be used when posting files, and it's reasonably safe to use it in other times too. However, it may break request signing, such as with OAuth. Supports an optional ``fields`` parameter of key/value strings AND key/filetuple. A filetuple is a (filename, data, MIME type) tuple where the MIME type is optional. For example:: fields = { 'foo': 'bar', 'fakefile': ('foofile.txt', 'contents of foofile'), 'realfile': ('barfile.txt', open('realfile').read()), 'typedfile': ('bazfile.bin', open('bazfile').read(), 'image/jpeg'), 'nonamefile': 'contents of nonamefile field', } When uploading a file, providing a filename (the first parameter of the tuple) is optional but recommended to best mimic behavior of browsers. Note that if ``headers`` are supplied, the 'Content-Type' header will be overwritten because it depends on the dynamic random boundary string which is used to compose the body of the request. The random boundary string can be explicitly set with the ``multipart_boundary`` parameter. """ if headers is None: headers = self.headers extra_kw = {'headers': {}} if fields: if 'body' in urlopen_kw: raise TypeError( "request got values for both 'fields' and 'body', can only specify one.") if encode_multipart: body, content_type = encode_multipart_formdata(fields, boundary=multipart_boundary) else: body, content_type = urlencode(fields), 'application/x-www-form-urlencoded' extra_kw['body'] = body extra_kw['headers'] = {'Content-Type': content_type} extra_kw['headers'].update(headers) extra_kw.update(urlopen_kw) return self.urlopen(method, url, **extra_kw)
[ "Make", "a", "request", "using", ":", "meth", ":", "urlopen", "with", "the", "fields", "encoded", "in", "the", "body", ".", "This", "is", "useful", "for", "request", "methods", "like", "POST", "PUT", "PATCH", "etc", "." ]
pypa/pipenv
python
https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/vendor/urllib3/request.py#L91-L150
[ "def", "request_encode_body", "(", "self", ",", "method", ",", "url", ",", "fields", "=", "None", ",", "headers", "=", "None", ",", "encode_multipart", "=", "True", ",", "multipart_boundary", "=", "None", ",", "*", "*", "urlopen_kw", ")", ":", "if", "hea...
cae8d76c210b9777e90aab76e9c4b0e53bb19cde
train
pass_context
Marks a callback as wanting to receive the current context object as first argument.
pipenv/vendor/click/decorators.py
def pass_context(f): """Marks a callback as wanting to receive the current context object as first argument. """ def new_func(*args, **kwargs): return f(get_current_context(), *args, **kwargs) return update_wrapper(new_func, f)
def pass_context(f): """Marks a callback as wanting to receive the current context object as first argument. """ def new_func(*args, **kwargs): return f(get_current_context(), *args, **kwargs) return update_wrapper(new_func, f)
[ "Marks", "a", "callback", "as", "wanting", "to", "receive", "the", "current", "context", "object", "as", "first", "argument", "." ]
pypa/pipenv
python
https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/vendor/click/decorators.py#L12-L18
[ "def", "pass_context", "(", "f", ")", ":", "def", "new_func", "(", "*", "args", ",", "*", "*", "kwargs", ")", ":", "return", "f", "(", "get_current_context", "(", ")", ",", "*", "args", ",", "*", "*", "kwargs", ")", "return", "update_wrapper", "(", ...
cae8d76c210b9777e90aab76e9c4b0e53bb19cde
train
pass_obj
Similar to :func:`pass_context`, but only pass the object on the context onwards (:attr:`Context.obj`). This is useful if that object represents the state of a nested system.
pipenv/vendor/click/decorators.py
def pass_obj(f): """Similar to :func:`pass_context`, but only pass the object on the context onwards (:attr:`Context.obj`). This is useful if that object represents the state of a nested system. """ def new_func(*args, **kwargs): return f(get_current_context().obj, *args, **kwargs) return update_wrapper(new_func, f)
def pass_obj(f): """Similar to :func:`pass_context`, but only pass the object on the context onwards (:attr:`Context.obj`). This is useful if that object represents the state of a nested system. """ def new_func(*args, **kwargs): return f(get_current_context().obj, *args, **kwargs) return update_wrapper(new_func, f)
[ "Similar", "to", ":", "func", ":", "pass_context", "but", "only", "pass", "the", "object", "on", "the", "context", "onwards", "(", ":", "attr", ":", "Context", ".", "obj", ")", ".", "This", "is", "useful", "if", "that", "object", "represents", "the", "...
pypa/pipenv
python
https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/vendor/click/decorators.py#L21-L28
[ "def", "pass_obj", "(", "f", ")", ":", "def", "new_func", "(", "*", "args", ",", "*", "*", "kwargs", ")", ":", "return", "f", "(", "get_current_context", "(", ")", ".", "obj", ",", "*", "args", ",", "*", "*", "kwargs", ")", "return", "update_wrappe...
cae8d76c210b9777e90aab76e9c4b0e53bb19cde
train
make_pass_decorator
Given an object type this creates a decorator that will work similar to :func:`pass_obj` but instead of passing the object of the current context, it will find the innermost context of type :func:`object_type`. This generates a decorator that works roughly like this:: from functools import update_wrapper def decorator(f): @pass_context def new_func(ctx, *args, **kwargs): obj = ctx.find_object(object_type) return ctx.invoke(f, obj, *args, **kwargs) return update_wrapper(new_func, f) return decorator :param object_type: the type of the object to pass. :param ensure: if set to `True`, a new object will be created and remembered on the context if it's not there yet.
pipenv/vendor/click/decorators.py
def make_pass_decorator(object_type, ensure=False): """Given an object type this creates a decorator that will work similar to :func:`pass_obj` but instead of passing the object of the current context, it will find the innermost context of type :func:`object_type`. This generates a decorator that works roughly like this:: from functools import update_wrapper def decorator(f): @pass_context def new_func(ctx, *args, **kwargs): obj = ctx.find_object(object_type) return ctx.invoke(f, obj, *args, **kwargs) return update_wrapper(new_func, f) return decorator :param object_type: the type of the object to pass. :param ensure: if set to `True`, a new object will be created and remembered on the context if it's not there yet. """ def decorator(f): def new_func(*args, **kwargs): ctx = get_current_context() if ensure: obj = ctx.ensure_object(object_type) else: obj = ctx.find_object(object_type) if obj is None: raise RuntimeError('Managed to invoke callback without a ' 'context object of type %r existing' % object_type.__name__) return ctx.invoke(f, obj, *args, **kwargs) return update_wrapper(new_func, f) return decorator
def make_pass_decorator(object_type, ensure=False): """Given an object type this creates a decorator that will work similar to :func:`pass_obj` but instead of passing the object of the current context, it will find the innermost context of type :func:`object_type`. This generates a decorator that works roughly like this:: from functools import update_wrapper def decorator(f): @pass_context def new_func(ctx, *args, **kwargs): obj = ctx.find_object(object_type) return ctx.invoke(f, obj, *args, **kwargs) return update_wrapper(new_func, f) return decorator :param object_type: the type of the object to pass. :param ensure: if set to `True`, a new object will be created and remembered on the context if it's not there yet. """ def decorator(f): def new_func(*args, **kwargs): ctx = get_current_context() if ensure: obj = ctx.ensure_object(object_type) else: obj = ctx.find_object(object_type) if obj is None: raise RuntimeError('Managed to invoke callback without a ' 'context object of type %r existing' % object_type.__name__) return ctx.invoke(f, obj, *args, **kwargs) return update_wrapper(new_func, f) return decorator
[ "Given", "an", "object", "type", "this", "creates", "a", "decorator", "that", "will", "work", "similar", "to", ":", "func", ":", "pass_obj", "but", "instead", "of", "passing", "the", "object", "of", "the", "current", "context", "it", "will", "find", "the",...
pypa/pipenv
python
https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/vendor/click/decorators.py#L31-L66
[ "def", "make_pass_decorator", "(", "object_type", ",", "ensure", "=", "False", ")", ":", "def", "decorator", "(", "f", ")", ":", "def", "new_func", "(", "*", "args", ",", "*", "*", "kwargs", ")", ":", "ctx", "=", "get_current_context", "(", ")", "if", ...
cae8d76c210b9777e90aab76e9c4b0e53bb19cde
train
argument
Attaches an argument to the command. All positional arguments are passed as parameter declarations to :class:`Argument`; all keyword arguments are forwarded unchanged (except ``cls``). This is equivalent to creating an :class:`Argument` instance manually and attaching it to the :attr:`Command.params` list. :param cls: the argument class to instantiate. This defaults to :class:`Argument`.
pipenv/vendor/click/decorators.py
def argument(*param_decls, **attrs): """Attaches an argument to the command. All positional arguments are passed as parameter declarations to :class:`Argument`; all keyword arguments are forwarded unchanged (except ``cls``). This is equivalent to creating an :class:`Argument` instance manually and attaching it to the :attr:`Command.params` list. :param cls: the argument class to instantiate. This defaults to :class:`Argument`. """ def decorator(f): ArgumentClass = attrs.pop('cls', Argument) _param_memo(f, ArgumentClass(param_decls, **attrs)) return f return decorator
def argument(*param_decls, **attrs): """Attaches an argument to the command. All positional arguments are passed as parameter declarations to :class:`Argument`; all keyword arguments are forwarded unchanged (except ``cls``). This is equivalent to creating an :class:`Argument` instance manually and attaching it to the :attr:`Command.params` list. :param cls: the argument class to instantiate. This defaults to :class:`Argument`. """ def decorator(f): ArgumentClass = attrs.pop('cls', Argument) _param_memo(f, ArgumentClass(param_decls, **attrs)) return f return decorator
[ "Attaches", "an", "argument", "to", "the", "command", ".", "All", "positional", "arguments", "are", "passed", "as", "parameter", "declarations", "to", ":", "class", ":", "Argument", ";", "all", "keyword", "arguments", "are", "forwarded", "unchanged", "(", "exc...
pypa/pipenv
python
https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/vendor/click/decorators.py#L139-L153
[ "def", "argument", "(", "*", "param_decls", ",", "*", "*", "attrs", ")", ":", "def", "decorator", "(", "f", ")", ":", "ArgumentClass", "=", "attrs", ".", "pop", "(", "'cls'", ",", "Argument", ")", "_param_memo", "(", "f", ",", "ArgumentClass", "(", "...
cae8d76c210b9777e90aab76e9c4b0e53bb19cde
train
option
Attaches an option to the command. All positional arguments are passed as parameter declarations to :class:`Option`; all keyword arguments are forwarded unchanged (except ``cls``). This is equivalent to creating an :class:`Option` instance manually and attaching it to the :attr:`Command.params` list. :param cls: the option class to instantiate. This defaults to :class:`Option`.
pipenv/vendor/click/decorators.py
def option(*param_decls, **attrs): """Attaches an option to the command. All positional arguments are passed as parameter declarations to :class:`Option`; all keyword arguments are forwarded unchanged (except ``cls``). This is equivalent to creating an :class:`Option` instance manually and attaching it to the :attr:`Command.params` list. :param cls: the option class to instantiate. This defaults to :class:`Option`. """ def decorator(f): # Issue 926, copy attrs, so pre-defined options can re-use the same cls= option_attrs = attrs.copy() if 'help' in option_attrs: option_attrs['help'] = inspect.cleandoc(option_attrs['help']) OptionClass = option_attrs.pop('cls', Option) _param_memo(f, OptionClass(param_decls, **option_attrs)) return f return decorator
def option(*param_decls, **attrs): """Attaches an option to the command. All positional arguments are passed as parameter declarations to :class:`Option`; all keyword arguments are forwarded unchanged (except ``cls``). This is equivalent to creating an :class:`Option` instance manually and attaching it to the :attr:`Command.params` list. :param cls: the option class to instantiate. This defaults to :class:`Option`. """ def decorator(f): # Issue 926, copy attrs, so pre-defined options can re-use the same cls= option_attrs = attrs.copy() if 'help' in option_attrs: option_attrs['help'] = inspect.cleandoc(option_attrs['help']) OptionClass = option_attrs.pop('cls', Option) _param_memo(f, OptionClass(param_decls, **option_attrs)) return f return decorator
[ "Attaches", "an", "option", "to", "the", "command", ".", "All", "positional", "arguments", "are", "passed", "as", "parameter", "declarations", "to", ":", "class", ":", "Option", ";", "all", "keyword", "arguments", "are", "forwarded", "unchanged", "(", "except"...
pypa/pipenv
python
https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/vendor/click/decorators.py#L156-L175
[ "def", "option", "(", "*", "param_decls", ",", "*", "*", "attrs", ")", ":", "def", "decorator", "(", "f", ")", ":", "# Issue 926, copy attrs, so pre-defined options can re-use the same cls=", "option_attrs", "=", "attrs", ".", "copy", "(", ")", "if", "'help'", "...
cae8d76c210b9777e90aab76e9c4b0e53bb19cde
train
confirmation_option
Shortcut for confirmation prompts that can be ignored by passing ``--yes`` as parameter. This is equivalent to decorating a function with :func:`option` with the following parameters:: def callback(ctx, param, value): if not value: ctx.abort() @click.command() @click.option('--yes', is_flag=True, callback=callback, expose_value=False, prompt='Do you want to continue?') def dropdb(): pass
pipenv/vendor/click/decorators.py
def confirmation_option(*param_decls, **attrs): """Shortcut for confirmation prompts that can be ignored by passing ``--yes`` as parameter. This is equivalent to decorating a function with :func:`option` with the following parameters:: def callback(ctx, param, value): if not value: ctx.abort() @click.command() @click.option('--yes', is_flag=True, callback=callback, expose_value=False, prompt='Do you want to continue?') def dropdb(): pass """ def decorator(f): def callback(ctx, param, value): if not value: ctx.abort() attrs.setdefault('is_flag', True) attrs.setdefault('callback', callback) attrs.setdefault('expose_value', False) attrs.setdefault('prompt', 'Do you want to continue?') attrs.setdefault('help', 'Confirm the action without prompting.') return option(*(param_decls or ('--yes',)), **attrs)(f) return decorator
def confirmation_option(*param_decls, **attrs): """Shortcut for confirmation prompts that can be ignored by passing ``--yes`` as parameter. This is equivalent to decorating a function with :func:`option` with the following parameters:: def callback(ctx, param, value): if not value: ctx.abort() @click.command() @click.option('--yes', is_flag=True, callback=callback, expose_value=False, prompt='Do you want to continue?') def dropdb(): pass """ def decorator(f): def callback(ctx, param, value): if not value: ctx.abort() attrs.setdefault('is_flag', True) attrs.setdefault('callback', callback) attrs.setdefault('expose_value', False) attrs.setdefault('prompt', 'Do you want to continue?') attrs.setdefault('help', 'Confirm the action without prompting.') return option(*(param_decls or ('--yes',)), **attrs)(f) return decorator
[ "Shortcut", "for", "confirmation", "prompts", "that", "can", "be", "ignored", "by", "passing", "--", "yes", "as", "parameter", "." ]
pypa/pipenv
python
https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/vendor/click/decorators.py#L178-L205
[ "def", "confirmation_option", "(", "*", "param_decls", ",", "*", "*", "attrs", ")", ":", "def", "decorator", "(", "f", ")", ":", "def", "callback", "(", "ctx", ",", "param", ",", "value", ")", ":", "if", "not", "value", ":", "ctx", ".", "abort", "(...
cae8d76c210b9777e90aab76e9c4b0e53bb19cde
train
password_option
Shortcut for password prompts. This is equivalent to decorating a function with :func:`option` with the following parameters:: @click.command() @click.option('--password', prompt=True, confirmation_prompt=True, hide_input=True) def changeadmin(password): pass
pipenv/vendor/click/decorators.py
def password_option(*param_decls, **attrs): """Shortcut for password prompts. This is equivalent to decorating a function with :func:`option` with the following parameters:: @click.command() @click.option('--password', prompt=True, confirmation_prompt=True, hide_input=True) def changeadmin(password): pass """ def decorator(f): attrs.setdefault('prompt', True) attrs.setdefault('confirmation_prompt', True) attrs.setdefault('hide_input', True) return option(*(param_decls or ('--password',)), **attrs)(f) return decorator
def password_option(*param_decls, **attrs): """Shortcut for password prompts. This is equivalent to decorating a function with :func:`option` with the following parameters:: @click.command() @click.option('--password', prompt=True, confirmation_prompt=True, hide_input=True) def changeadmin(password): pass """ def decorator(f): attrs.setdefault('prompt', True) attrs.setdefault('confirmation_prompt', True) attrs.setdefault('hide_input', True) return option(*(param_decls or ('--password',)), **attrs)(f) return decorator
[ "Shortcut", "for", "password", "prompts", "." ]
pypa/pipenv
python
https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/vendor/click/decorators.py#L208-L225
[ "def", "password_option", "(", "*", "param_decls", ",", "*", "*", "attrs", ")", ":", "def", "decorator", "(", "f", ")", ":", "attrs", ".", "setdefault", "(", "'prompt'", ",", "True", ")", "attrs", ".", "setdefault", "(", "'confirmation_prompt'", ",", "Tr...
cae8d76c210b9777e90aab76e9c4b0e53bb19cde
train
help_option
Adds a ``--help`` option which immediately ends the program printing out the help page. This is usually unnecessary to add as this is added by default to all commands unless suppressed. Like :func:`version_option`, this is implemented as eager option that prints in the callback and exits. All arguments are forwarded to :func:`option`.
pipenv/vendor/click/decorators.py
def help_option(*param_decls, **attrs): """Adds a ``--help`` option which immediately ends the program printing out the help page. This is usually unnecessary to add as this is added by default to all commands unless suppressed. Like :func:`version_option`, this is implemented as eager option that prints in the callback and exits. All arguments are forwarded to :func:`option`. """ def decorator(f): def callback(ctx, param, value): if value and not ctx.resilient_parsing: echo(ctx.get_help(), color=ctx.color) ctx.exit() attrs.setdefault('is_flag', True) attrs.setdefault('expose_value', False) attrs.setdefault('help', 'Show this message and exit.') attrs.setdefault('is_eager', True) attrs['callback'] = callback return option(*(param_decls or ('--help',)), **attrs)(f) return decorator
def help_option(*param_decls, **attrs): """Adds a ``--help`` option which immediately ends the program printing out the help page. This is usually unnecessary to add as this is added by default to all commands unless suppressed. Like :func:`version_option`, this is implemented as eager option that prints in the callback and exits. All arguments are forwarded to :func:`option`. """ def decorator(f): def callback(ctx, param, value): if value and not ctx.resilient_parsing: echo(ctx.get_help(), color=ctx.color) ctx.exit() attrs.setdefault('is_flag', True) attrs.setdefault('expose_value', False) attrs.setdefault('help', 'Show this message and exit.') attrs.setdefault('is_eager', True) attrs['callback'] = callback return option(*(param_decls or ('--help',)), **attrs)(f) return decorator
[ "Adds", "a", "--", "help", "option", "which", "immediately", "ends", "the", "program", "printing", "out", "the", "help", "page", ".", "This", "is", "usually", "unnecessary", "to", "add", "as", "this", "is", "added", "by", "default", "to", "all", "commands"...
pypa/pipenv
python
https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/vendor/click/decorators.py#L286-L307
[ "def", "help_option", "(", "*", "param_decls", ",", "*", "*", "attrs", ")", ":", "def", "decorator", "(", "f", ")", ":", "def", "callback", "(", "ctx", ",", "param", ",", "value", ")", ":", "if", "value", "and", "not", "ctx", ".", "resilient_parsing"...
cae8d76c210b9777e90aab76e9c4b0e53bb19cde
train
was_installed_by_pip
Checks whether pkg was installed by pip This is used not to display the upgrade message when pip is in fact installed by system package manager, such as dnf on Fedora.
pipenv/patched/notpip/_internal/utils/outdated.py
def was_installed_by_pip(pkg): # type: (str) -> bool """Checks whether pkg was installed by pip This is used not to display the upgrade message when pip is in fact installed by system package manager, such as dnf on Fedora. """ try: dist = pkg_resources.get_distribution(pkg) return (dist.has_metadata('INSTALLER') and 'pip' in dist.get_metadata_lines('INSTALLER')) except pkg_resources.DistributionNotFound: return False
def was_installed_by_pip(pkg): # type: (str) -> bool """Checks whether pkg was installed by pip This is used not to display the upgrade message when pip is in fact installed by system package manager, such as dnf on Fedora. """ try: dist = pkg_resources.get_distribution(pkg) return (dist.has_metadata('INSTALLER') and 'pip' in dist.get_metadata_lines('INSTALLER')) except pkg_resources.DistributionNotFound: return False
[ "Checks", "whether", "pkg", "was", "installed", "by", "pip" ]
pypa/pipenv
python
https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/patched/notpip/_internal/utils/outdated.py#L79-L91
[ "def", "was_installed_by_pip", "(", "pkg", ")", ":", "# type: (str) -> bool", "try", ":", "dist", "=", "pkg_resources", ".", "get_distribution", "(", "pkg", ")", "return", "(", "dist", ".", "has_metadata", "(", "'INSTALLER'", ")", "and", "'pip'", "in", "dist",...
cae8d76c210b9777e90aab76e9c4b0e53bb19cde
train
pip_version_check
Check for an update for pip. Limit the frequency of checks to once per week. State is stored either in the active virtualenv or in the user's USER_CACHE_DIR keyed off the prefix of the pip script path.
pipenv/patched/notpip/_internal/utils/outdated.py
def pip_version_check(session, options): # type: (PipSession, optparse.Values) -> None """Check for an update for pip. Limit the frequency of checks to once per week. State is stored either in the active virtualenv or in the user's USER_CACHE_DIR keyed off the prefix of the pip script path. """ installed_version = get_installed_version("pip") if not installed_version: return pip_version = packaging_version.parse(installed_version) pypi_version = None try: state = SelfCheckState(cache_dir=options.cache_dir) current_time = datetime.datetime.utcnow() # Determine if we need to refresh the state if "last_check" in state.state and "pypi_version" in state.state: last_check = datetime.datetime.strptime( state.state["last_check"], SELFCHECK_DATE_FMT ) if (current_time - last_check).total_seconds() < 7 * 24 * 60 * 60: pypi_version = state.state["pypi_version"] # Refresh the version if we need to or just see if we need to warn if pypi_version is None: # Lets use PackageFinder to see what the latest pip version is finder = PackageFinder( find_links=options.find_links, index_urls=[options.index_url] + options.extra_index_urls, allow_all_prereleases=False, # Explicitly set to False trusted_hosts=options.trusted_hosts, session=session, ) all_candidates = finder.find_all_candidates("pip") if not all_candidates: return pypi_version = str( max(all_candidates, key=lambda c: c.version).version ) # save that we've performed a check state.save(pypi_version, current_time) remote_version = packaging_version.parse(pypi_version) # Determine if our pypi_version is older if (pip_version < remote_version and pip_version.base_version != remote_version.base_version and was_installed_by_pip('pip')): # Advise "python -m pip" on Windows to avoid issues # with overwriting pip.exe. if WINDOWS: pip_cmd = "python -m pip" else: pip_cmd = "pip" logger.warning( "You are using pip version %s, however version %s is " "available.\nYou should consider upgrading via the " "'%s install --upgrade pip' command.", pip_version, pypi_version, pip_cmd ) except Exception: logger.debug( "There was an error checking the latest version of pip", exc_info=True, )
def pip_version_check(session, options): # type: (PipSession, optparse.Values) -> None """Check for an update for pip. Limit the frequency of checks to once per week. State is stored either in the active virtualenv or in the user's USER_CACHE_DIR keyed off the prefix of the pip script path. """ installed_version = get_installed_version("pip") if not installed_version: return pip_version = packaging_version.parse(installed_version) pypi_version = None try: state = SelfCheckState(cache_dir=options.cache_dir) current_time = datetime.datetime.utcnow() # Determine if we need to refresh the state if "last_check" in state.state and "pypi_version" in state.state: last_check = datetime.datetime.strptime( state.state["last_check"], SELFCHECK_DATE_FMT ) if (current_time - last_check).total_seconds() < 7 * 24 * 60 * 60: pypi_version = state.state["pypi_version"] # Refresh the version if we need to or just see if we need to warn if pypi_version is None: # Lets use PackageFinder to see what the latest pip version is finder = PackageFinder( find_links=options.find_links, index_urls=[options.index_url] + options.extra_index_urls, allow_all_prereleases=False, # Explicitly set to False trusted_hosts=options.trusted_hosts, session=session, ) all_candidates = finder.find_all_candidates("pip") if not all_candidates: return pypi_version = str( max(all_candidates, key=lambda c: c.version).version ) # save that we've performed a check state.save(pypi_version, current_time) remote_version = packaging_version.parse(pypi_version) # Determine if our pypi_version is older if (pip_version < remote_version and pip_version.base_version != remote_version.base_version and was_installed_by_pip('pip')): # Advise "python -m pip" on Windows to avoid issues # with overwriting pip.exe. if WINDOWS: pip_cmd = "python -m pip" else: pip_cmd = "pip" logger.warning( "You are using pip version %s, however version %s is " "available.\nYou should consider upgrading via the " "'%s install --upgrade pip' command.", pip_version, pypi_version, pip_cmd ) except Exception: logger.debug( "There was an error checking the latest version of pip", exc_info=True, )
[ "Check", "for", "an", "update", "for", "pip", "." ]
pypa/pipenv
python
https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/patched/notpip/_internal/utils/outdated.py#L94-L164
[ "def", "pip_version_check", "(", "session", ",", "options", ")", ":", "# type: (PipSession, optparse.Values) -> None", "installed_version", "=", "get_installed_version", "(", "\"pip\"", ")", "if", "not", "installed_version", ":", "return", "pip_version", "=", "packaging_v...
cae8d76c210b9777e90aab76e9c4b0e53bb19cde
train
get_abbr_impl
Return abbreviated implementation name.
pipenv/patched/notpip/_internal/pep425tags.py
def get_abbr_impl(): # type: () -> str """Return abbreviated implementation name.""" if hasattr(sys, 'pypy_version_info'): pyimpl = 'pp' elif sys.platform.startswith('java'): pyimpl = 'jy' elif sys.platform == 'cli': pyimpl = 'ip' else: pyimpl = 'cp' return pyimpl
def get_abbr_impl(): # type: () -> str """Return abbreviated implementation name.""" if hasattr(sys, 'pypy_version_info'): pyimpl = 'pp' elif sys.platform.startswith('java'): pyimpl = 'jy' elif sys.platform == 'cli': pyimpl = 'ip' else: pyimpl = 'cp' return pyimpl
[ "Return", "abbreviated", "implementation", "name", "." ]
pypa/pipenv
python
https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/patched/notpip/_internal/pep425tags.py#L41-L52
[ "def", "get_abbr_impl", "(", ")", ":", "# type: () -> str", "if", "hasattr", "(", "sys", ",", "'pypy_version_info'", ")", ":", "pyimpl", "=", "'pp'", "elif", "sys", ".", "platform", ".", "startswith", "(", "'java'", ")", ":", "pyimpl", "=", "'jy'", "elif",...
cae8d76c210b9777e90aab76e9c4b0e53bb19cde
train
get_impl_ver
Return implementation version.
pipenv/patched/notpip/_internal/pep425tags.py
def get_impl_ver(): # type: () -> str """Return implementation version.""" impl_ver = get_config_var("py_version_nodot") if not impl_ver or get_abbr_impl() == 'pp': impl_ver = ''.join(map(str, get_impl_version_info())) return impl_ver
def get_impl_ver(): # type: () -> str """Return implementation version.""" impl_ver = get_config_var("py_version_nodot") if not impl_ver or get_abbr_impl() == 'pp': impl_ver = ''.join(map(str, get_impl_version_info())) return impl_ver
[ "Return", "implementation", "version", "." ]
pypa/pipenv
python
https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/patched/notpip/_internal/pep425tags.py#L55-L61
[ "def", "get_impl_ver", "(", ")", ":", "# type: () -> str", "impl_ver", "=", "get_config_var", "(", "\"py_version_nodot\"", ")", "if", "not", "impl_ver", "or", "get_abbr_impl", "(", ")", "==", "'pp'", ":", "impl_ver", "=", "''", ".", "join", "(", "map", "(", ...
cae8d76c210b9777e90aab76e9c4b0e53bb19cde
train
get_impl_version_info
Return sys.version_info-like tuple for use in decrementing the minor version.
pipenv/patched/notpip/_internal/pep425tags.py
def get_impl_version_info(): # type: () -> Tuple[int, ...] """Return sys.version_info-like tuple for use in decrementing the minor version.""" if get_abbr_impl() == 'pp': # as per https://github.com/pypa/pip/issues/2882 # attrs exist only on pypy return (sys.version_info[0], sys.pypy_version_info.major, # type: ignore sys.pypy_version_info.minor) # type: ignore else: return sys.version_info[0], sys.version_info[1]
def get_impl_version_info(): # type: () -> Tuple[int, ...] """Return sys.version_info-like tuple for use in decrementing the minor version.""" if get_abbr_impl() == 'pp': # as per https://github.com/pypa/pip/issues/2882 # attrs exist only on pypy return (sys.version_info[0], sys.pypy_version_info.major, # type: ignore sys.pypy_version_info.minor) # type: ignore else: return sys.version_info[0], sys.version_info[1]
[ "Return", "sys", ".", "version_info", "-", "like", "tuple", "for", "use", "in", "decrementing", "the", "minor", "version", "." ]
pypa/pipenv
python
https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/patched/notpip/_internal/pep425tags.py#L64-L75
[ "def", "get_impl_version_info", "(", ")", ":", "# type: () -> Tuple[int, ...]", "if", "get_abbr_impl", "(", ")", "==", "'pp'", ":", "# as per https://github.com/pypa/pip/issues/2882", "# attrs exist only on pypy", "return", "(", "sys", ".", "version_info", "[", "0", "]", ...
cae8d76c210b9777e90aab76e9c4b0e53bb19cde
train
get_platform
Return our platform name 'win32', 'linux_x86_64
pipenv/patched/notpip/_internal/pep425tags.py
def get_platform(): # type: () -> str """Return our platform name 'win32', 'linux_x86_64'""" if sys.platform == 'darwin': # distutils.util.get_platform() returns the release based on the value # of MACOSX_DEPLOYMENT_TARGET on which Python was built, which may # be significantly older than the user's current machine. release, _, machine = platform.mac_ver() split_ver = release.split('.') if machine == "x86_64" and _is_running_32bit(): machine = "i386" elif machine == "ppc64" and _is_running_32bit(): machine = "ppc" return 'macosx_{}_{}_{}'.format(split_ver[0], split_ver[1], machine) # XXX remove distutils dependency result = distutils.util.get_platform().replace('.', '_').replace('-', '_') if result == "linux_x86_64" and _is_running_32bit(): # 32 bit Python program (running on a 64 bit Linux): pip should only # install and run 32 bit compiled extensions in that case. result = "linux_i686" return result
def get_platform(): # type: () -> str """Return our platform name 'win32', 'linux_x86_64'""" if sys.platform == 'darwin': # distutils.util.get_platform() returns the release based on the value # of MACOSX_DEPLOYMENT_TARGET on which Python was built, which may # be significantly older than the user's current machine. release, _, machine = platform.mac_ver() split_ver = release.split('.') if machine == "x86_64" and _is_running_32bit(): machine = "i386" elif machine == "ppc64" and _is_running_32bit(): machine = "ppc" return 'macosx_{}_{}_{}'.format(split_ver[0], split_ver[1], machine) # XXX remove distutils dependency result = distutils.util.get_platform().replace('.', '_').replace('-', '_') if result == "linux_x86_64" and _is_running_32bit(): # 32 bit Python program (running on a 64 bit Linux): pip should only # install and run 32 bit compiled extensions in that case. result = "linux_i686" return result
[ "Return", "our", "platform", "name", "win32", "linux_x86_64" ]
pypa/pipenv
python
https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/patched/notpip/_internal/pep425tags.py#L139-L163
[ "def", "get_platform", "(", ")", ":", "# type: () -> str", "if", "sys", ".", "platform", "==", "'darwin'", ":", "# distutils.util.get_platform() returns the release based on the value", "# of MACOSX_DEPLOYMENT_TARGET on which Python was built, which may", "# be significantly older than...
cae8d76c210b9777e90aab76e9c4b0e53bb19cde
train
get_supported
Return a list of supported tags for each version specified in `versions`. :param versions: a list of string versions, of the form ["33", "32"], or None. The first version will be assumed to support our ABI. :param platform: specify the exact platform you want valid tags for, or None. If None, use the local system platform. :param impl: specify the exact implementation you want valid tags for, or None. If None, use the local interpreter impl. :param abi: specify the exact abi you want valid tags for, or None. If None, use the local interpreter abi.
pipenv/patched/notpip/_internal/pep425tags.py
def get_supported( versions=None, # type: Optional[List[str]] noarch=False, # type: bool platform=None, # type: Optional[str] impl=None, # type: Optional[str] abi=None # type: Optional[str] ): # type: (...) -> List[Pep425Tag] """Return a list of supported tags for each version specified in `versions`. :param versions: a list of string versions, of the form ["33", "32"], or None. The first version will be assumed to support our ABI. :param platform: specify the exact platform you want valid tags for, or None. If None, use the local system platform. :param impl: specify the exact implementation you want valid tags for, or None. If None, use the local interpreter impl. :param abi: specify the exact abi you want valid tags for, or None. If None, use the local interpreter abi. """ supported = [] # Versions must be given with respect to the preference if versions is None: version_info = get_impl_version_info() versions = get_all_minor_versions_as_strings(version_info) impl = impl or get_abbr_impl() abis = [] # type: List[str] abi = abi or get_abi_tag() if abi: abis[0:0] = [abi] abi3s = set() for suffix in get_extension_suffixes(): if suffix.startswith('.abi'): abi3s.add(suffix.split('.', 2)[1]) abis.extend(sorted(list(abi3s))) abis.append('none') if not noarch: arch = platform or get_platform() arch_prefix, arch_sep, arch_suffix = arch.partition('_') if arch.startswith('macosx'): # support macosx-10.6-intel on macosx-10.9-x86_64 match = _osx_arch_pat.match(arch) if match: name, major, minor, actual_arch = match.groups() tpl = '{}_{}_%i_%s'.format(name, major) arches = [] for m in reversed(range(int(minor) + 1)): for a in get_darwin_arches(int(major), m, actual_arch): arches.append(tpl % (m, a)) else: # arch pattern didn't match (?!) arches = [arch] elif arch_prefix == 'manylinux2010': # manylinux1 wheels run on most manylinux2010 systems with the # exception of wheels depending on ncurses. PEP 571 states # manylinux1 wheels should be considered manylinux2010 wheels: # https://www.python.org/dev/peps/pep-0571/#backwards-compatibility-with-manylinux1-wheels arches = [arch, 'manylinux1' + arch_sep + arch_suffix] elif platform is None: arches = [] if is_manylinux2010_compatible(): arches.append('manylinux2010' + arch_sep + arch_suffix) if is_manylinux1_compatible(): arches.append('manylinux1' + arch_sep + arch_suffix) arches.append(arch) else: arches = [arch] # Current version, current API (built specifically for our Python): for abi in abis: for arch in arches: supported.append(('%s%s' % (impl, versions[0]), abi, arch)) # abi3 modules compatible with older version of Python for version in versions[1:]: # abi3 was introduced in Python 3.2 if version in {'31', '30'}: break for abi in abi3s: # empty set if not Python 3 for arch in arches: supported.append(("%s%s" % (impl, version), abi, arch)) # Has binaries, does not use the Python API: for arch in arches: supported.append(('py%s' % (versions[0][0]), 'none', arch)) # No abi / arch, but requires our implementation: supported.append(('%s%s' % (impl, versions[0]), 'none', 'any')) # Tagged specifically as being cross-version compatible # (with just the major version specified) supported.append(('%s%s' % (impl, versions[0][0]), 'none', 'any')) # No abi / arch, generic Python for i, version in enumerate(versions): supported.append(('py%s' % (version,), 'none', 'any')) if i == 0: supported.append(('py%s' % (version[0]), 'none', 'any')) return supported
def get_supported( versions=None, # type: Optional[List[str]] noarch=False, # type: bool platform=None, # type: Optional[str] impl=None, # type: Optional[str] abi=None # type: Optional[str] ): # type: (...) -> List[Pep425Tag] """Return a list of supported tags for each version specified in `versions`. :param versions: a list of string versions, of the form ["33", "32"], or None. The first version will be assumed to support our ABI. :param platform: specify the exact platform you want valid tags for, or None. If None, use the local system platform. :param impl: specify the exact implementation you want valid tags for, or None. If None, use the local interpreter impl. :param abi: specify the exact abi you want valid tags for, or None. If None, use the local interpreter abi. """ supported = [] # Versions must be given with respect to the preference if versions is None: version_info = get_impl_version_info() versions = get_all_minor_versions_as_strings(version_info) impl = impl or get_abbr_impl() abis = [] # type: List[str] abi = abi or get_abi_tag() if abi: abis[0:0] = [abi] abi3s = set() for suffix in get_extension_suffixes(): if suffix.startswith('.abi'): abi3s.add(suffix.split('.', 2)[1]) abis.extend(sorted(list(abi3s))) abis.append('none') if not noarch: arch = platform or get_platform() arch_prefix, arch_sep, arch_suffix = arch.partition('_') if arch.startswith('macosx'): # support macosx-10.6-intel on macosx-10.9-x86_64 match = _osx_arch_pat.match(arch) if match: name, major, minor, actual_arch = match.groups() tpl = '{}_{}_%i_%s'.format(name, major) arches = [] for m in reversed(range(int(minor) + 1)): for a in get_darwin_arches(int(major), m, actual_arch): arches.append(tpl % (m, a)) else: # arch pattern didn't match (?!) arches = [arch] elif arch_prefix == 'manylinux2010': # manylinux1 wheels run on most manylinux2010 systems with the # exception of wheels depending on ncurses. PEP 571 states # manylinux1 wheels should be considered manylinux2010 wheels: # https://www.python.org/dev/peps/pep-0571/#backwards-compatibility-with-manylinux1-wheels arches = [arch, 'manylinux1' + arch_sep + arch_suffix] elif platform is None: arches = [] if is_manylinux2010_compatible(): arches.append('manylinux2010' + arch_sep + arch_suffix) if is_manylinux1_compatible(): arches.append('manylinux1' + arch_sep + arch_suffix) arches.append(arch) else: arches = [arch] # Current version, current API (built specifically for our Python): for abi in abis: for arch in arches: supported.append(('%s%s' % (impl, versions[0]), abi, arch)) # abi3 modules compatible with older version of Python for version in versions[1:]: # abi3 was introduced in Python 3.2 if version in {'31', '30'}: break for abi in abi3s: # empty set if not Python 3 for arch in arches: supported.append(("%s%s" % (impl, version), abi, arch)) # Has binaries, does not use the Python API: for arch in arches: supported.append(('py%s' % (versions[0][0]), 'none', arch)) # No abi / arch, but requires our implementation: supported.append(('%s%s' % (impl, versions[0]), 'none', 'any')) # Tagged specifically as being cross-version compatible # (with just the major version specified) supported.append(('%s%s' % (impl, versions[0][0]), 'none', 'any')) # No abi / arch, generic Python for i, version in enumerate(versions): supported.append(('py%s' % (version,), 'none', 'any')) if i == 0: supported.append(('py%s' % (version[0]), 'none', 'any')) return supported
[ "Return", "a", "list", "of", "supported", "tags", "for", "each", "version", "specified", "in", "versions", "." ]
pypa/pipenv
python
https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/patched/notpip/_internal/pep425tags.py#L275-L381
[ "def", "get_supported", "(", "versions", "=", "None", ",", "# type: Optional[List[str]]", "noarch", "=", "False", ",", "# type: bool", "platform", "=", "None", ",", "# type: Optional[str]", "impl", "=", "None", ",", "# type: Optional[str]", "abi", "=", "None", "# ...
cae8d76c210b9777e90aab76e9c4b0e53bb19cde
train
get_netrc_auth
Returns the Requests tuple auth for a given url from netrc.
pipenv/vendor/requests/utils.py
def get_netrc_auth(url, raise_errors=False): """Returns the Requests tuple auth for a given url from netrc.""" try: from netrc import netrc, NetrcParseError netrc_path = None for f in NETRC_FILES: try: loc = os.path.expanduser('~/{}'.format(f)) except KeyError: # os.path.expanduser can fail when $HOME is undefined and # getpwuid fails. See https://bugs.python.org/issue20164 & # https://github.com/requests/requests/issues/1846 return if os.path.exists(loc): netrc_path = loc break # Abort early if there isn't one. if netrc_path is None: return ri = urlparse(url) # Strip port numbers from netloc. This weird `if...encode`` dance is # used for Python 3.2, which doesn't support unicode literals. splitstr = b':' if isinstance(url, str): splitstr = splitstr.decode('ascii') host = ri.netloc.split(splitstr)[0] try: _netrc = netrc(netrc_path).authenticators(host) if _netrc: # Return with login / password login_i = (0 if _netrc[0] else 1) return (_netrc[login_i], _netrc[2]) except (NetrcParseError, IOError): # If there was a parsing error or a permissions issue reading the file, # we'll just skip netrc auth unless explicitly asked to raise errors. if raise_errors: raise # AppEngine hackiness. except (ImportError, AttributeError): pass
def get_netrc_auth(url, raise_errors=False): """Returns the Requests tuple auth for a given url from netrc.""" try: from netrc import netrc, NetrcParseError netrc_path = None for f in NETRC_FILES: try: loc = os.path.expanduser('~/{}'.format(f)) except KeyError: # os.path.expanduser can fail when $HOME is undefined and # getpwuid fails. See https://bugs.python.org/issue20164 & # https://github.com/requests/requests/issues/1846 return if os.path.exists(loc): netrc_path = loc break # Abort early if there isn't one. if netrc_path is None: return ri = urlparse(url) # Strip port numbers from netloc. This weird `if...encode`` dance is # used for Python 3.2, which doesn't support unicode literals. splitstr = b':' if isinstance(url, str): splitstr = splitstr.decode('ascii') host = ri.netloc.split(splitstr)[0] try: _netrc = netrc(netrc_path).authenticators(host) if _netrc: # Return with login / password login_i = (0 if _netrc[0] else 1) return (_netrc[login_i], _netrc[2]) except (NetrcParseError, IOError): # If there was a parsing error or a permissions issue reading the file, # we'll just skip netrc auth unless explicitly asked to raise errors. if raise_errors: raise # AppEngine hackiness. except (ImportError, AttributeError): pass
[ "Returns", "the", "Requests", "tuple", "auth", "for", "a", "given", "url", "from", "netrc", "." ]
pypa/pipenv
python
https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/vendor/requests/utils.py#L168-L216
[ "def", "get_netrc_auth", "(", "url", ",", "raise_errors", "=", "False", ")", ":", "try", ":", "from", "netrc", "import", "netrc", ",", "NetrcParseError", "netrc_path", "=", "None", "for", "f", "in", "NETRC_FILES", ":", "try", ":", "loc", "=", "os", ".", ...
cae8d76c210b9777e90aab76e9c4b0e53bb19cde
train
guess_filename
Tries to guess the filename of the given object.
pipenv/vendor/requests/utils.py
def guess_filename(obj): """Tries to guess the filename of the given object.""" name = getattr(obj, 'name', None) if (name and isinstance(name, basestring) and name[0] != '<' and name[-1] != '>'): return os.path.basename(name)
def guess_filename(obj): """Tries to guess the filename of the given object.""" name = getattr(obj, 'name', None) if (name and isinstance(name, basestring) and name[0] != '<' and name[-1] != '>'): return os.path.basename(name)
[ "Tries", "to", "guess", "the", "filename", "of", "the", "given", "object", "." ]
pypa/pipenv
python
https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/vendor/requests/utils.py#L219-L224
[ "def", "guess_filename", "(", "obj", ")", ":", "name", "=", "getattr", "(", "obj", ",", "'name'", ",", "None", ")", "if", "(", "name", "and", "isinstance", "(", "name", ",", "basestring", ")", "and", "name", "[", "0", "]", "!=", "'<'", "and", "name...
cae8d76c210b9777e90aab76e9c4b0e53bb19cde
train
extract_zipped_paths
Replace nonexistent paths that look like they refer to a member of a zip archive with the location of an extracted copy of the target, or else just return the provided path unchanged.
pipenv/vendor/requests/utils.py
def extract_zipped_paths(path): """Replace nonexistent paths that look like they refer to a member of a zip archive with the location of an extracted copy of the target, or else just return the provided path unchanged. """ if os.path.exists(path): # this is already a valid path, no need to do anything further return path # find the first valid part of the provided path and treat that as a zip archive # assume the rest of the path is the name of a member in the archive archive, member = os.path.split(path) while archive and not os.path.exists(archive): archive, prefix = os.path.split(archive) member = '/'.join([prefix, member]) if not zipfile.is_zipfile(archive): return path zip_file = zipfile.ZipFile(archive) if member not in zip_file.namelist(): return path # we have a valid zip archive and a valid member of that archive tmp = tempfile.gettempdir() extracted_path = os.path.join(tmp, *member.split('/')) if not os.path.exists(extracted_path): extracted_path = zip_file.extract(member, path=tmp) return extracted_path
def extract_zipped_paths(path): """Replace nonexistent paths that look like they refer to a member of a zip archive with the location of an extracted copy of the target, or else just return the provided path unchanged. """ if os.path.exists(path): # this is already a valid path, no need to do anything further return path # find the first valid part of the provided path and treat that as a zip archive # assume the rest of the path is the name of a member in the archive archive, member = os.path.split(path) while archive and not os.path.exists(archive): archive, prefix = os.path.split(archive) member = '/'.join([prefix, member]) if not zipfile.is_zipfile(archive): return path zip_file = zipfile.ZipFile(archive) if member not in zip_file.namelist(): return path # we have a valid zip archive and a valid member of that archive tmp = tempfile.gettempdir() extracted_path = os.path.join(tmp, *member.split('/')) if not os.path.exists(extracted_path): extracted_path = zip_file.extract(member, path=tmp) return extracted_path
[ "Replace", "nonexistent", "paths", "that", "look", "like", "they", "refer", "to", "a", "member", "of", "a", "zip", "archive", "with", "the", "location", "of", "an", "extracted", "copy", "of", "the", "target", "or", "else", "just", "return", "the", "provide...
pypa/pipenv
python
https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/vendor/requests/utils.py#L227-L256
[ "def", "extract_zipped_paths", "(", "path", ")", ":", "if", "os", ".", "path", ".", "exists", "(", "path", ")", ":", "# this is already a valid path, no need to do anything further", "return", "path", "# find the first valid part of the provided path and treat that as a zip arc...
cae8d76c210b9777e90aab76e9c4b0e53bb19cde
train
from_key_val_list
Take an object and test to see if it can be represented as a dictionary. Unless it can not be represented as such, return an OrderedDict, e.g., :: >>> from_key_val_list([('key', 'val')]) OrderedDict([('key', 'val')]) >>> from_key_val_list('string') ValueError: cannot encode objects that are not 2-tuples >>> from_key_val_list({'key': 'val'}) OrderedDict([('key', 'val')]) :rtype: OrderedDict
pipenv/vendor/requests/utils.py
def from_key_val_list(value): """Take an object and test to see if it can be represented as a dictionary. Unless it can not be represented as such, return an OrderedDict, e.g., :: >>> from_key_val_list([('key', 'val')]) OrderedDict([('key', 'val')]) >>> from_key_val_list('string') ValueError: cannot encode objects that are not 2-tuples >>> from_key_val_list({'key': 'val'}) OrderedDict([('key', 'val')]) :rtype: OrderedDict """ if value is None: return None if isinstance(value, (str, bytes, bool, int)): raise ValueError('cannot encode objects that are not 2-tuples') return OrderedDict(value)
def from_key_val_list(value): """Take an object and test to see if it can be represented as a dictionary. Unless it can not be represented as such, return an OrderedDict, e.g., :: >>> from_key_val_list([('key', 'val')]) OrderedDict([('key', 'val')]) >>> from_key_val_list('string') ValueError: cannot encode objects that are not 2-tuples >>> from_key_val_list({'key': 'val'}) OrderedDict([('key', 'val')]) :rtype: OrderedDict """ if value is None: return None if isinstance(value, (str, bytes, bool, int)): raise ValueError('cannot encode objects that are not 2-tuples') return OrderedDict(value)
[ "Take", "an", "object", "and", "test", "to", "see", "if", "it", "can", "be", "represented", "as", "a", "dictionary", ".", "Unless", "it", "can", "not", "be", "represented", "as", "such", "return", "an", "OrderedDict", "e", ".", "g", "." ]
pypa/pipenv
python
https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/vendor/requests/utils.py#L259-L281
[ "def", "from_key_val_list", "(", "value", ")", ":", "if", "value", "is", "None", ":", "return", "None", "if", "isinstance", "(", "value", ",", "(", "str", ",", "bytes", ",", "bool", ",", "int", ")", ")", ":", "raise", "ValueError", "(", "'cannot encode...
cae8d76c210b9777e90aab76e9c4b0e53bb19cde
train
parse_list_header
Parse lists as described by RFC 2068 Section 2. In particular, parse comma-separated lists where the elements of the list may include quoted-strings. A quoted-string could contain a comma. A non-quoted string could have quotes in the middle. Quotes are removed automatically after parsing. It basically works like :func:`parse_set_header` just that items may appear multiple times and case sensitivity is preserved. The return value is a standard :class:`list`: >>> parse_list_header('token, "quoted value"') ['token', 'quoted value'] To create a header from the :class:`list` again, use the :func:`dump_header` function. :param value: a string with a list header. :return: :class:`list` :rtype: list
pipenv/vendor/requests/utils.py
def parse_list_header(value): """Parse lists as described by RFC 2068 Section 2. In particular, parse comma-separated lists where the elements of the list may include quoted-strings. A quoted-string could contain a comma. A non-quoted string could have quotes in the middle. Quotes are removed automatically after parsing. It basically works like :func:`parse_set_header` just that items may appear multiple times and case sensitivity is preserved. The return value is a standard :class:`list`: >>> parse_list_header('token, "quoted value"') ['token', 'quoted value'] To create a header from the :class:`list` again, use the :func:`dump_header` function. :param value: a string with a list header. :return: :class:`list` :rtype: list """ result = [] for item in _parse_list_header(value): if item[:1] == item[-1:] == '"': item = unquote_header_value(item[1:-1]) result.append(item) return result
def parse_list_header(value): """Parse lists as described by RFC 2068 Section 2. In particular, parse comma-separated lists where the elements of the list may include quoted-strings. A quoted-string could contain a comma. A non-quoted string could have quotes in the middle. Quotes are removed automatically after parsing. It basically works like :func:`parse_set_header` just that items may appear multiple times and case sensitivity is preserved. The return value is a standard :class:`list`: >>> parse_list_header('token, "quoted value"') ['token', 'quoted value'] To create a header from the :class:`list` again, use the :func:`dump_header` function. :param value: a string with a list header. :return: :class:`list` :rtype: list """ result = [] for item in _parse_list_header(value): if item[:1] == item[-1:] == '"': item = unquote_header_value(item[1:-1]) result.append(item) return result
[ "Parse", "lists", "as", "described", "by", "RFC", "2068", "Section", "2", "." ]
pypa/pipenv
python
https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/vendor/requests/utils.py#L312-L340
[ "def", "parse_list_header", "(", "value", ")", ":", "result", "=", "[", "]", "for", "item", "in", "_parse_list_header", "(", "value", ")", ":", "if", "item", "[", ":", "1", "]", "==", "item", "[", "-", "1", ":", "]", "==", "'\"'", ":", "item", "=...
cae8d76c210b9777e90aab76e9c4b0e53bb19cde
train
parse_dict_header
Parse lists of key, value pairs as described by RFC 2068 Section 2 and convert them into a python dict: >>> d = parse_dict_header('foo="is a fish", bar="as well"') >>> type(d) is dict True >>> sorted(d.items()) [('bar', 'as well'), ('foo', 'is a fish')] If there is no value for a key it will be `None`: >>> parse_dict_header('key_without_value') {'key_without_value': None} To create a header from the :class:`dict` again, use the :func:`dump_header` function. :param value: a string with a dict header. :return: :class:`dict` :rtype: dict
pipenv/vendor/requests/utils.py
def parse_dict_header(value): """Parse lists of key, value pairs as described by RFC 2068 Section 2 and convert them into a python dict: >>> d = parse_dict_header('foo="is a fish", bar="as well"') >>> type(d) is dict True >>> sorted(d.items()) [('bar', 'as well'), ('foo', 'is a fish')] If there is no value for a key it will be `None`: >>> parse_dict_header('key_without_value') {'key_without_value': None} To create a header from the :class:`dict` again, use the :func:`dump_header` function. :param value: a string with a dict header. :return: :class:`dict` :rtype: dict """ result = {} for item in _parse_list_header(value): if '=' not in item: result[item] = None continue name, value = item.split('=', 1) if value[:1] == value[-1:] == '"': value = unquote_header_value(value[1:-1]) result[name] = value return result
def parse_dict_header(value): """Parse lists of key, value pairs as described by RFC 2068 Section 2 and convert them into a python dict: >>> d = parse_dict_header('foo="is a fish", bar="as well"') >>> type(d) is dict True >>> sorted(d.items()) [('bar', 'as well'), ('foo', 'is a fish')] If there is no value for a key it will be `None`: >>> parse_dict_header('key_without_value') {'key_without_value': None} To create a header from the :class:`dict` again, use the :func:`dump_header` function. :param value: a string with a dict header. :return: :class:`dict` :rtype: dict """ result = {} for item in _parse_list_header(value): if '=' not in item: result[item] = None continue name, value = item.split('=', 1) if value[:1] == value[-1:] == '"': value = unquote_header_value(value[1:-1]) result[name] = value return result
[ "Parse", "lists", "of", "key", "value", "pairs", "as", "described", "by", "RFC", "2068", "Section", "2", "and", "convert", "them", "into", "a", "python", "dict", ":" ]
pypa/pipenv
python
https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/vendor/requests/utils.py#L344-L375
[ "def", "parse_dict_header", "(", "value", ")", ":", "result", "=", "{", "}", "for", "item", "in", "_parse_list_header", "(", "value", ")", ":", "if", "'='", "not", "in", "item", ":", "result", "[", "item", "]", "=", "None", "continue", "name", ",", "...
cae8d76c210b9777e90aab76e9c4b0e53bb19cde
train
dict_from_cookiejar
Returns a key/value dictionary from a CookieJar. :param cj: CookieJar object to extract cookies from. :rtype: dict
pipenv/vendor/requests/utils.py
def dict_from_cookiejar(cj): """Returns a key/value dictionary from a CookieJar. :param cj: CookieJar object to extract cookies from. :rtype: dict """ cookie_dict = {} for cookie in cj: cookie_dict[cookie.name] = cookie.value return cookie_dict
def dict_from_cookiejar(cj): """Returns a key/value dictionary from a CookieJar. :param cj: CookieJar object to extract cookies from. :rtype: dict """ cookie_dict = {} for cookie in cj: cookie_dict[cookie.name] = cookie.value return cookie_dict
[ "Returns", "a", "key", "/", "value", "dictionary", "from", "a", "CookieJar", "." ]
pypa/pipenv
python
https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/vendor/requests/utils.py#L404-L416
[ "def", "dict_from_cookiejar", "(", "cj", ")", ":", "cookie_dict", "=", "{", "}", "for", "cookie", "in", "cj", ":", "cookie_dict", "[", "cookie", ".", "name", "]", "=", "cookie", ".", "value", "return", "cookie_dict" ]
cae8d76c210b9777e90aab76e9c4b0e53bb19cde
train
_parse_content_type_header
Returns content type and parameters from given header :param header: string :return: tuple containing content type and dictionary of parameters
pipenv/vendor/requests/utils.py
def _parse_content_type_header(header): """Returns content type and parameters from given header :param header: string :return: tuple containing content type and dictionary of parameters """ tokens = header.split(';') content_type, params = tokens[0].strip(), tokens[1:] params_dict = {} items_to_strip = "\"' " for param in params: param = param.strip() if param: key, value = param, True index_of_equals = param.find("=") if index_of_equals != -1: key = param[:index_of_equals].strip(items_to_strip) value = param[index_of_equals + 1:].strip(items_to_strip) params_dict[key.lower()] = value return content_type, params_dict
def _parse_content_type_header(header): """Returns content type and parameters from given header :param header: string :return: tuple containing content type and dictionary of parameters """ tokens = header.split(';') content_type, params = tokens[0].strip(), tokens[1:] params_dict = {} items_to_strip = "\"' " for param in params: param = param.strip() if param: key, value = param, True index_of_equals = param.find("=") if index_of_equals != -1: key = param[:index_of_equals].strip(items_to_strip) value = param[index_of_equals + 1:].strip(items_to_strip) params_dict[key.lower()] = value return content_type, params_dict
[ "Returns", "content", "type", "and", "parameters", "from", "given", "header" ]
pypa/pipenv
python
https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/vendor/requests/utils.py#L450-L472
[ "def", "_parse_content_type_header", "(", "header", ")", ":", "tokens", "=", "header", ".", "split", "(", "';'", ")", "content_type", ",", "params", "=", "tokens", "[", "0", "]", ".", "strip", "(", ")", ",", "tokens", "[", "1", ":", "]", "params_dict",...
cae8d76c210b9777e90aab76e9c4b0e53bb19cde
train
get_encoding_from_headers
Returns encodings from given HTTP Header Dict. :param headers: dictionary to extract encoding from. :rtype: str
pipenv/vendor/requests/utils.py
def get_encoding_from_headers(headers): """Returns encodings from given HTTP Header Dict. :param headers: dictionary to extract encoding from. :rtype: str """ content_type = headers.get('content-type') if not content_type: return None content_type, params = _parse_content_type_header(content_type) if 'charset' in params: return params['charset'].strip("'\"") if 'text' in content_type: return 'ISO-8859-1'
def get_encoding_from_headers(headers): """Returns encodings from given HTTP Header Dict. :param headers: dictionary to extract encoding from. :rtype: str """ content_type = headers.get('content-type') if not content_type: return None content_type, params = _parse_content_type_header(content_type) if 'charset' in params: return params['charset'].strip("'\"") if 'text' in content_type: return 'ISO-8859-1'
[ "Returns", "encodings", "from", "given", "HTTP", "Header", "Dict", "." ]
pypa/pipenv
python
https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/vendor/requests/utils.py#L475-L493
[ "def", "get_encoding_from_headers", "(", "headers", ")", ":", "content_type", "=", "headers", ".", "get", "(", "'content-type'", ")", "if", "not", "content_type", ":", "return", "None", "content_type", ",", "params", "=", "_parse_content_type_header", "(", "conten...
cae8d76c210b9777e90aab76e9c4b0e53bb19cde
train
iter_slices
Iterate over slices of a string.
pipenv/vendor/requests/utils.py
def iter_slices(string, slice_length): """Iterate over slices of a string.""" pos = 0 if slice_length is None or slice_length <= 0: slice_length = len(string) while pos < len(string): yield string[pos:pos + slice_length] pos += slice_length
def iter_slices(string, slice_length): """Iterate over slices of a string.""" pos = 0 if slice_length is None or slice_length <= 0: slice_length = len(string) while pos < len(string): yield string[pos:pos + slice_length] pos += slice_length
[ "Iterate", "over", "slices", "of", "a", "string", "." ]
pypa/pipenv
python
https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/vendor/requests/utils.py#L514-L521
[ "def", "iter_slices", "(", "string", ",", "slice_length", ")", ":", "pos", "=", "0", "if", "slice_length", "is", "None", "or", "slice_length", "<=", "0", ":", "slice_length", "=", "len", "(", "string", ")", "while", "pos", "<", "len", "(", "string", ")...
cae8d76c210b9777e90aab76e9c4b0e53bb19cde
train
get_unicode_from_response
Returns the requested content back in unicode. :param r: Response object to get unicode content from. Tried: 1. charset from content-type 2. fall back and replace all unicode characters :rtype: str
pipenv/vendor/requests/utils.py
def get_unicode_from_response(r): """Returns the requested content back in unicode. :param r: Response object to get unicode content from. Tried: 1. charset from content-type 2. fall back and replace all unicode characters :rtype: str """ warnings.warn(( 'In requests 3.0, get_unicode_from_response will be removed. For ' 'more information, please see the discussion on issue #2266. (This' ' warning should only appear once.)'), DeprecationWarning) tried_encodings = [] # Try charset from content-type encoding = get_encoding_from_headers(r.headers) if encoding: try: return str(r.content, encoding) except UnicodeError: tried_encodings.append(encoding) # Fall back: try: return str(r.content, encoding, errors='replace') except TypeError: return r.content
def get_unicode_from_response(r): """Returns the requested content back in unicode. :param r: Response object to get unicode content from. Tried: 1. charset from content-type 2. fall back and replace all unicode characters :rtype: str """ warnings.warn(( 'In requests 3.0, get_unicode_from_response will be removed. For ' 'more information, please see the discussion on issue #2266. (This' ' warning should only appear once.)'), DeprecationWarning) tried_encodings = [] # Try charset from content-type encoding = get_encoding_from_headers(r.headers) if encoding: try: return str(r.content, encoding) except UnicodeError: tried_encodings.append(encoding) # Fall back: try: return str(r.content, encoding, errors='replace') except TypeError: return r.content
[ "Returns", "the", "requested", "content", "back", "in", "unicode", "." ]
pypa/pipenv
python
https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/vendor/requests/utils.py#L524-L557
[ "def", "get_unicode_from_response", "(", "r", ")", ":", "warnings", ".", "warn", "(", "(", "'In requests 3.0, get_unicode_from_response will be removed. For '", "'more information, please see the discussion on issue #2266. (This'", "' warning should only appear once.)'", ")", ",", "D...
cae8d76c210b9777e90aab76e9c4b0e53bb19cde
train
requote_uri
Re-quote the given URI. This function passes the given URI through an unquote/quote cycle to ensure that it is fully and consistently quoted. :rtype: str
pipenv/vendor/requests/utils.py
def requote_uri(uri): """Re-quote the given URI. This function passes the given URI through an unquote/quote cycle to ensure that it is fully and consistently quoted. :rtype: str """ safe_with_percent = "!#$%&'()*+,/:;=?@[]~" safe_without_percent = "!#$&'()*+,/:;=?@[]~" try: # Unquote only the unreserved characters # Then quote only illegal characters (do not quote reserved, # unreserved, or '%') return quote(unquote_unreserved(uri), safe=safe_with_percent) except InvalidURL: # We couldn't unquote the given URI, so let's try quoting it, but # there may be unquoted '%'s in the URI. We need to make sure they're # properly quoted so they do not cause issues elsewhere. return quote(uri, safe=safe_without_percent)
def requote_uri(uri): """Re-quote the given URI. This function passes the given URI through an unquote/quote cycle to ensure that it is fully and consistently quoted. :rtype: str """ safe_with_percent = "!#$%&'()*+,/:;=?@[]~" safe_without_percent = "!#$&'()*+,/:;=?@[]~" try: # Unquote only the unreserved characters # Then quote only illegal characters (do not quote reserved, # unreserved, or '%') return quote(unquote_unreserved(uri), safe=safe_with_percent) except InvalidURL: # We couldn't unquote the given URI, so let's try quoting it, but # there may be unquoted '%'s in the URI. We need to make sure they're # properly quoted so they do not cause issues elsewhere. return quote(uri, safe=safe_without_percent)
[ "Re", "-", "quote", "the", "given", "URI", "." ]
pypa/pipenv
python
https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/vendor/requests/utils.py#L589-L608
[ "def", "requote_uri", "(", "uri", ")", ":", "safe_with_percent", "=", "\"!#$%&'()*+,/:;=?@[]~\"", "safe_without_percent", "=", "\"!#$&'()*+,/:;=?@[]~\"", "try", ":", "# Unquote only the unreserved characters", "# Then quote only illegal characters (do not quote reserved,", "# unreser...
cae8d76c210b9777e90aab76e9c4b0e53bb19cde
train
address_in_network
This function allows you to check if an IP belongs to a network subnet Example: returns True if ip = 192.168.1.1 and net = 192.168.1.0/24 returns False if ip = 192.168.1.1 and net = 192.168.100.0/24 :rtype: bool
pipenv/vendor/requests/utils.py
def address_in_network(ip, net): """This function allows you to check if an IP belongs to a network subnet Example: returns True if ip = 192.168.1.1 and net = 192.168.1.0/24 returns False if ip = 192.168.1.1 and net = 192.168.100.0/24 :rtype: bool """ ipaddr = struct.unpack('=L', socket.inet_aton(ip))[0] netaddr, bits = net.split('/') netmask = struct.unpack('=L', socket.inet_aton(dotted_netmask(int(bits))))[0] network = struct.unpack('=L', socket.inet_aton(netaddr))[0] & netmask return (ipaddr & netmask) == (network & netmask)
def address_in_network(ip, net): """This function allows you to check if an IP belongs to a network subnet Example: returns True if ip = 192.168.1.1 and net = 192.168.1.0/24 returns False if ip = 192.168.1.1 and net = 192.168.100.0/24 :rtype: bool """ ipaddr = struct.unpack('=L', socket.inet_aton(ip))[0] netaddr, bits = net.split('/') netmask = struct.unpack('=L', socket.inet_aton(dotted_netmask(int(bits))))[0] network = struct.unpack('=L', socket.inet_aton(netaddr))[0] & netmask return (ipaddr & netmask) == (network & netmask)
[ "This", "function", "allows", "you", "to", "check", "if", "an", "IP", "belongs", "to", "a", "network", "subnet" ]
pypa/pipenv
python
https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/vendor/requests/utils.py#L611-L623
[ "def", "address_in_network", "(", "ip", ",", "net", ")", ":", "ipaddr", "=", "struct", ".", "unpack", "(", "'=L'", ",", "socket", ".", "inet_aton", "(", "ip", ")", ")", "[", "0", "]", "netaddr", ",", "bits", "=", "net", ".", "split", "(", "'/'", ...
cae8d76c210b9777e90aab76e9c4b0e53bb19cde
train
is_valid_cidr
Very simple check of the cidr format in no_proxy variable. :rtype: bool
pipenv/vendor/requests/utils.py
def is_valid_cidr(string_network): """ Very simple check of the cidr format in no_proxy variable. :rtype: bool """ if string_network.count('/') == 1: try: mask = int(string_network.split('/')[1]) except ValueError: return False if mask < 1 or mask > 32: return False try: socket.inet_aton(string_network.split('/')[0]) except socket.error: return False else: return False return True
def is_valid_cidr(string_network): """ Very simple check of the cidr format in no_proxy variable. :rtype: bool """ if string_network.count('/') == 1: try: mask = int(string_network.split('/')[1]) except ValueError: return False if mask < 1 or mask > 32: return False try: socket.inet_aton(string_network.split('/')[0]) except socket.error: return False else: return False return True
[ "Very", "simple", "check", "of", "the", "cidr", "format", "in", "no_proxy", "variable", "." ]
pypa/pipenv
python
https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/vendor/requests/utils.py#L648-L669
[ "def", "is_valid_cidr", "(", "string_network", ")", ":", "if", "string_network", ".", "count", "(", "'/'", ")", "==", "1", ":", "try", ":", "mask", "=", "int", "(", "string_network", ".", "split", "(", "'/'", ")", "[", "1", "]", ")", "except", "Value...
cae8d76c210b9777e90aab76e9c4b0e53bb19cde
train
set_environ
Set the environment variable 'env_name' to 'value' Save previous value, yield, and then restore the previous value stored in the environment variable 'env_name'. If 'value' is None, do nothing
pipenv/vendor/requests/utils.py
def set_environ(env_name, value): """Set the environment variable 'env_name' to 'value' Save previous value, yield, and then restore the previous value stored in the environment variable 'env_name'. If 'value' is None, do nothing""" value_changed = value is not None if value_changed: old_value = os.environ.get(env_name) os.environ[env_name] = value try: yield finally: if value_changed: if old_value is None: del os.environ[env_name] else: os.environ[env_name] = old_value
def set_environ(env_name, value): """Set the environment variable 'env_name' to 'value' Save previous value, yield, and then restore the previous value stored in the environment variable 'env_name'. If 'value' is None, do nothing""" value_changed = value is not None if value_changed: old_value = os.environ.get(env_name) os.environ[env_name] = value try: yield finally: if value_changed: if old_value is None: del os.environ[env_name] else: os.environ[env_name] = old_value
[ "Set", "the", "environment", "variable", "env_name", "to", "value" ]
pypa/pipenv
python
https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/vendor/requests/utils.py#L673-L691
[ "def", "set_environ", "(", "env_name", ",", "value", ")", ":", "value_changed", "=", "value", "is", "not", "None", "if", "value_changed", ":", "old_value", "=", "os", ".", "environ", ".", "get", "(", "env_name", ")", "os", ".", "environ", "[", "env_name"...
cae8d76c210b9777e90aab76e9c4b0e53bb19cde
train
should_bypass_proxies
Returns whether we should bypass proxies or not. :rtype: bool
pipenv/vendor/requests/utils.py
def should_bypass_proxies(url, no_proxy): """ Returns whether we should bypass proxies or not. :rtype: bool """ # Prioritize lowercase environment variables over uppercase # to keep a consistent behaviour with other http projects (curl, wget). get_proxy = lambda k: os.environ.get(k) or os.environ.get(k.upper()) # First check whether no_proxy is defined. If it is, check that the URL # we're getting isn't in the no_proxy list. no_proxy_arg = no_proxy if no_proxy is None: no_proxy = get_proxy('no_proxy') parsed = urlparse(url) if parsed.hostname is None: # URLs don't always have hostnames, e.g. file:/// urls. return True if no_proxy: # We need to check whether we match here. We need to see if we match # the end of the hostname, both with and without the port. no_proxy = ( host for host in no_proxy.replace(' ', '').split(',') if host ) if is_ipv4_address(parsed.hostname): for proxy_ip in no_proxy: if is_valid_cidr(proxy_ip): if address_in_network(parsed.hostname, proxy_ip): return True elif parsed.hostname == proxy_ip: # If no_proxy ip was defined in plain IP notation instead of cidr notation & # matches the IP of the index return True else: host_with_port = parsed.hostname if parsed.port: host_with_port += ':{}'.format(parsed.port) for host in no_proxy: if parsed.hostname.endswith(host) or host_with_port.endswith(host): # The URL does match something in no_proxy, so we don't want # to apply the proxies on this URL. return True with set_environ('no_proxy', no_proxy_arg): # parsed.hostname can be `None` in cases such as a file URI. try: bypass = proxy_bypass(parsed.hostname) except (TypeError, socket.gaierror): bypass = False if bypass: return True return False
def should_bypass_proxies(url, no_proxy): """ Returns whether we should bypass proxies or not. :rtype: bool """ # Prioritize lowercase environment variables over uppercase # to keep a consistent behaviour with other http projects (curl, wget). get_proxy = lambda k: os.environ.get(k) or os.environ.get(k.upper()) # First check whether no_proxy is defined. If it is, check that the URL # we're getting isn't in the no_proxy list. no_proxy_arg = no_proxy if no_proxy is None: no_proxy = get_proxy('no_proxy') parsed = urlparse(url) if parsed.hostname is None: # URLs don't always have hostnames, e.g. file:/// urls. return True if no_proxy: # We need to check whether we match here. We need to see if we match # the end of the hostname, both with and without the port. no_proxy = ( host for host in no_proxy.replace(' ', '').split(',') if host ) if is_ipv4_address(parsed.hostname): for proxy_ip in no_proxy: if is_valid_cidr(proxy_ip): if address_in_network(parsed.hostname, proxy_ip): return True elif parsed.hostname == proxy_ip: # If no_proxy ip was defined in plain IP notation instead of cidr notation & # matches the IP of the index return True else: host_with_port = parsed.hostname if parsed.port: host_with_port += ':{}'.format(parsed.port) for host in no_proxy: if parsed.hostname.endswith(host) or host_with_port.endswith(host): # The URL does match something in no_proxy, so we don't want # to apply the proxies on this URL. return True with set_environ('no_proxy', no_proxy_arg): # parsed.hostname can be `None` in cases such as a file URI. try: bypass = proxy_bypass(parsed.hostname) except (TypeError, socket.gaierror): bypass = False if bypass: return True return False
[ "Returns", "whether", "we", "should", "bypass", "proxies", "or", "not", "." ]
pypa/pipenv
python
https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/vendor/requests/utils.py#L694-L752
[ "def", "should_bypass_proxies", "(", "url", ",", "no_proxy", ")", ":", "# Prioritize lowercase environment variables over uppercase", "# to keep a consistent behaviour with other http projects (curl, wget).", "get_proxy", "=", "lambda", "k", ":", "os", ".", "environ", ".", "get...
cae8d76c210b9777e90aab76e9c4b0e53bb19cde
train
select_proxy
Select a proxy for the url, if applicable. :param url: The url being for the request :param proxies: A dictionary of schemes or schemes and hosts to proxy URLs
pipenv/vendor/requests/utils.py
def select_proxy(url, proxies): """Select a proxy for the url, if applicable. :param url: The url being for the request :param proxies: A dictionary of schemes or schemes and hosts to proxy URLs """ proxies = proxies or {} urlparts = urlparse(url) if urlparts.hostname is None: return proxies.get(urlparts.scheme, proxies.get('all')) proxy_keys = [ urlparts.scheme + '://' + urlparts.hostname, urlparts.scheme, 'all://' + urlparts.hostname, 'all', ] proxy = None for proxy_key in proxy_keys: if proxy_key in proxies: proxy = proxies[proxy_key] break return proxy
def select_proxy(url, proxies): """Select a proxy for the url, if applicable. :param url: The url being for the request :param proxies: A dictionary of schemes or schemes and hosts to proxy URLs """ proxies = proxies or {} urlparts = urlparse(url) if urlparts.hostname is None: return proxies.get(urlparts.scheme, proxies.get('all')) proxy_keys = [ urlparts.scheme + '://' + urlparts.hostname, urlparts.scheme, 'all://' + urlparts.hostname, 'all', ] proxy = None for proxy_key in proxy_keys: if proxy_key in proxies: proxy = proxies[proxy_key] break return proxy
[ "Select", "a", "proxy", "for", "the", "url", "if", "applicable", "." ]
pypa/pipenv
python
https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/vendor/requests/utils.py#L767-L790
[ "def", "select_proxy", "(", "url", ",", "proxies", ")", ":", "proxies", "=", "proxies", "or", "{", "}", "urlparts", "=", "urlparse", "(", "url", ")", "if", "urlparts", ".", "hostname", "is", "None", ":", "return", "proxies", ".", "get", "(", "urlparts"...
cae8d76c210b9777e90aab76e9c4b0e53bb19cde
train
prepend_scheme_if_needed
Given a URL that may or may not have a scheme, prepend the given scheme. Does not replace a present scheme with the one provided as an argument. :rtype: str
pipenv/vendor/requests/utils.py
def prepend_scheme_if_needed(url, new_scheme): """Given a URL that may or may not have a scheme, prepend the given scheme. Does not replace a present scheme with the one provided as an argument. :rtype: str """ scheme, netloc, path, params, query, fragment = urlparse(url, new_scheme) # urlparse is a finicky beast, and sometimes decides that there isn't a # netloc present. Assume that it's being over-cautious, and switch netloc # and path if urlparse decided there was no netloc. if not netloc: netloc, path = path, netloc return urlunparse((scheme, netloc, path, params, query, fragment))
def prepend_scheme_if_needed(url, new_scheme): """Given a URL that may or may not have a scheme, prepend the given scheme. Does not replace a present scheme with the one provided as an argument. :rtype: str """ scheme, netloc, path, params, query, fragment = urlparse(url, new_scheme) # urlparse is a finicky beast, and sometimes decides that there isn't a # netloc present. Assume that it's being over-cautious, and switch netloc # and path if urlparse decided there was no netloc. if not netloc: netloc, path = path, netloc return urlunparse((scheme, netloc, path, params, query, fragment))
[ "Given", "a", "URL", "that", "may", "or", "may", "not", "have", "a", "scheme", "prepend", "the", "given", "scheme", ".", "Does", "not", "replace", "a", "present", "scheme", "with", "the", "one", "provided", "as", "an", "argument", "." ]
pypa/pipenv
python
https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/vendor/requests/utils.py#L889-L903
[ "def", "prepend_scheme_if_needed", "(", "url", ",", "new_scheme", ")", ":", "scheme", ",", "netloc", ",", "path", ",", "params", ",", "query", ",", "fragment", "=", "urlparse", "(", "url", ",", "new_scheme", ")", "# urlparse is a finicky beast, and sometimes decid...
cae8d76c210b9777e90aab76e9c4b0e53bb19cde
train
get_auth_from_url
Given a url with authentication components, extract them into a tuple of username,password. :rtype: (str,str)
pipenv/vendor/requests/utils.py
def get_auth_from_url(url): """Given a url with authentication components, extract them into a tuple of username,password. :rtype: (str,str) """ parsed = urlparse(url) try: auth = (unquote(parsed.username), unquote(parsed.password)) except (AttributeError, TypeError): auth = ('', '') return auth
def get_auth_from_url(url): """Given a url with authentication components, extract them into a tuple of username,password. :rtype: (str,str) """ parsed = urlparse(url) try: auth = (unquote(parsed.username), unquote(parsed.password)) except (AttributeError, TypeError): auth = ('', '') return auth
[ "Given", "a", "url", "with", "authentication", "components", "extract", "them", "into", "a", "tuple", "of", "username", "password", "." ]
pypa/pipenv
python
https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/vendor/requests/utils.py#L906-L919
[ "def", "get_auth_from_url", "(", "url", ")", ":", "parsed", "=", "urlparse", "(", "url", ")", "try", ":", "auth", "=", "(", "unquote", "(", "parsed", ".", "username", ")", ",", "unquote", "(", "parsed", ".", "password", ")", ")", "except", "(", "Attr...
cae8d76c210b9777e90aab76e9c4b0e53bb19cde
train
check_header_validity
Verifies that header value is a string which doesn't contain leading whitespace or return characters. This prevents unintended header injection. :param header: tuple, in the format (name, value).
pipenv/vendor/requests/utils.py
def check_header_validity(header): """Verifies that header value is a string which doesn't contain leading whitespace or return characters. This prevents unintended header injection. :param header: tuple, in the format (name, value). """ name, value = header if isinstance(value, bytes): pat = _CLEAN_HEADER_REGEX_BYTE else: pat = _CLEAN_HEADER_REGEX_STR try: if not pat.match(value): raise InvalidHeader("Invalid return character or leading space in header: %s" % name) except TypeError: raise InvalidHeader("Value for header {%s: %s} must be of type str or " "bytes, not %s" % (name, value, type(value)))
def check_header_validity(header): """Verifies that header value is a string which doesn't contain leading whitespace or return characters. This prevents unintended header injection. :param header: tuple, in the format (name, value). """ name, value = header if isinstance(value, bytes): pat = _CLEAN_HEADER_REGEX_BYTE else: pat = _CLEAN_HEADER_REGEX_STR try: if not pat.match(value): raise InvalidHeader("Invalid return character or leading space in header: %s" % name) except TypeError: raise InvalidHeader("Value for header {%s: %s} must be of type str or " "bytes, not %s" % (name, value, type(value)))
[ "Verifies", "that", "header", "value", "is", "a", "string", "which", "doesn", "t", "contain", "leading", "whitespace", "or", "return", "characters", ".", "This", "prevents", "unintended", "header", "injection", "." ]
pypa/pipenv
python
https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/vendor/requests/utils.py#L927-L945
[ "def", "check_header_validity", "(", "header", ")", ":", "name", ",", "value", "=", "header", "if", "isinstance", "(", "value", ",", "bytes", ")", ":", "pat", "=", "_CLEAN_HEADER_REGEX_BYTE", "else", ":", "pat", "=", "_CLEAN_HEADER_REGEX_STR", "try", ":", "i...
cae8d76c210b9777e90aab76e9c4b0e53bb19cde
train
urldefragauth
Given a url remove the fragment and the authentication part. :rtype: str
pipenv/vendor/requests/utils.py
def urldefragauth(url): """ Given a url remove the fragment and the authentication part. :rtype: str """ scheme, netloc, path, params, query, fragment = urlparse(url) # see func:`prepend_scheme_if_needed` if not netloc: netloc, path = path, netloc netloc = netloc.rsplit('@', 1)[-1] return urlunparse((scheme, netloc, path, params, query, ''))
def urldefragauth(url): """ Given a url remove the fragment and the authentication part. :rtype: str """ scheme, netloc, path, params, query, fragment = urlparse(url) # see func:`prepend_scheme_if_needed` if not netloc: netloc, path = path, netloc netloc = netloc.rsplit('@', 1)[-1] return urlunparse((scheme, netloc, path, params, query, ''))
[ "Given", "a", "url", "remove", "the", "fragment", "and", "the", "authentication", "part", "." ]
pypa/pipenv
python
https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/vendor/requests/utils.py#L948-L962
[ "def", "urldefragauth", "(", "url", ")", ":", "scheme", ",", "netloc", ",", "path", ",", "params", ",", "query", ",", "fragment", "=", "urlparse", "(", "url", ")", "# see func:`prepend_scheme_if_needed`", "if", "not", "netloc", ":", "netloc", ",", "path", ...
cae8d76c210b9777e90aab76e9c4b0e53bb19cde
train
rewind_body
Move file pointer back to its recorded starting position so it can be read again on redirect.
pipenv/vendor/requests/utils.py
def rewind_body(prepared_request): """Move file pointer back to its recorded starting position so it can be read again on redirect. """ body_seek = getattr(prepared_request.body, 'seek', None) if body_seek is not None and isinstance(prepared_request._body_position, integer_types): try: body_seek(prepared_request._body_position) except (IOError, OSError): raise UnrewindableBodyError("An error occurred when rewinding request " "body for redirect.") else: raise UnrewindableBodyError("Unable to rewind request body for redirect.")
def rewind_body(prepared_request): """Move file pointer back to its recorded starting position so it can be read again on redirect. """ body_seek = getattr(prepared_request.body, 'seek', None) if body_seek is not None and isinstance(prepared_request._body_position, integer_types): try: body_seek(prepared_request._body_position) except (IOError, OSError): raise UnrewindableBodyError("An error occurred when rewinding request " "body for redirect.") else: raise UnrewindableBodyError("Unable to rewind request body for redirect.")
[ "Move", "file", "pointer", "back", "to", "its", "recorded", "starting", "position", "so", "it", "can", "be", "read", "again", "on", "redirect", "." ]
pypa/pipenv
python
https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/vendor/requests/utils.py#L965-L977
[ "def", "rewind_body", "(", "prepared_request", ")", ":", "body_seek", "=", "getattr", "(", "prepared_request", ".", "body", ",", "'seek'", ",", "None", ")", "if", "body_seek", "is", "not", "None", "and", "isinstance", "(", "prepared_request", ".", "_body_posit...
cae8d76c210b9777e90aab76e9c4b0e53bb19cde
train
canonicalize_version
This is very similar to Version.__str__, but has one subtle differences with the way it handles the release segment.
pipenv/vendor/packaging/utils.py
def canonicalize_version(version): """ This is very similar to Version.__str__, but has one subtle differences with the way it handles the release segment. """ try: version = Version(version) except InvalidVersion: # Legacy versions cannot be normalized return version parts = [] # Epoch if version.epoch != 0: parts.append("{0}!".format(version.epoch)) # Release segment # NB: This strips trailing '.0's to normalize parts.append(re.sub(r"(\.0)+$", "", ".".join(str(x) for x in version.release))) # Pre-release if version.pre is not None: parts.append("".join(str(x) for x in version.pre)) # Post-release if version.post is not None: parts.append(".post{0}".format(version.post)) # Development release if version.dev is not None: parts.append(".dev{0}".format(version.dev)) # Local version segment if version.local is not None: parts.append("+{0}".format(version.local)) return "".join(parts)
def canonicalize_version(version): """ This is very similar to Version.__str__, but has one subtle differences with the way it handles the release segment. """ try: version = Version(version) except InvalidVersion: # Legacy versions cannot be normalized return version parts = [] # Epoch if version.epoch != 0: parts.append("{0}!".format(version.epoch)) # Release segment # NB: This strips trailing '.0's to normalize parts.append(re.sub(r"(\.0)+$", "", ".".join(str(x) for x in version.release))) # Pre-release if version.pre is not None: parts.append("".join(str(x) for x in version.pre)) # Post-release if version.post is not None: parts.append(".post{0}".format(version.post)) # Development release if version.dev is not None: parts.append(".dev{0}".format(version.dev)) # Local version segment if version.local is not None: parts.append("+{0}".format(version.local)) return "".join(parts)
[ "This", "is", "very", "similar", "to", "Version", ".", "__str__", "but", "has", "one", "subtle", "differences", "with", "the", "way", "it", "handles", "the", "release", "segment", "." ]
pypa/pipenv
python
https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/vendor/packaging/utils.py#L19-L57
[ "def", "canonicalize_version", "(", "version", ")", ":", "try", ":", "version", "=", "Version", "(", "version", ")", "except", "InvalidVersion", ":", "# Legacy versions cannot be normalized", "return", "version", "parts", "=", "[", "]", "# Epoch", "if", "version",...
cae8d76c210b9777e90aab76e9c4b0e53bb19cde
train
generate
Generate the python source for a node tree.
pipenv/vendor/jinja2/compiler.py
def generate(node, environment, name, filename, stream=None, defer_init=False, optimized=True): """Generate the python source for a node tree.""" if not isinstance(node, nodes.Template): raise TypeError('Can\'t compile non template nodes') generator = environment.code_generator_class(environment, name, filename, stream, defer_init, optimized) generator.visit(node) if stream is None: return generator.stream.getvalue()
def generate(node, environment, name, filename, stream=None, defer_init=False, optimized=True): """Generate the python source for a node tree.""" if not isinstance(node, nodes.Template): raise TypeError('Can\'t compile non template nodes') generator = environment.code_generator_class(environment, name, filename, stream, defer_init, optimized) generator.visit(node) if stream is None: return generator.stream.getvalue()
[ "Generate", "the", "python", "source", "for", "a", "node", "tree", "." ]
pypa/pipenv
python
https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/vendor/jinja2/compiler.py#L74-L84
[ "def", "generate", "(", "node", ",", "environment", ",", "name", ",", "filename", ",", "stream", "=", "None", ",", "defer_init", "=", "False", ",", "optimized", "=", "True", ")", ":", "if", "not", "isinstance", "(", "node", ",", "nodes", ".", "Template...
cae8d76c210b9777e90aab76e9c4b0e53bb19cde
train
has_safe_repr
Does the node have a safe representation?
pipenv/vendor/jinja2/compiler.py
def has_safe_repr(value): """Does the node have a safe representation?""" if value is None or value is NotImplemented or value is Ellipsis: return True if type(value) in (bool, int, float, complex, range_type, Markup) + string_types: return True if type(value) in (tuple, list, set, frozenset): for item in value: if not has_safe_repr(item): return False return True elif type(value) is dict: for key, value in iteritems(value): if not has_safe_repr(key): return False if not has_safe_repr(value): return False return True return False
def has_safe_repr(value): """Does the node have a safe representation?""" if value is None or value is NotImplemented or value is Ellipsis: return True if type(value) in (bool, int, float, complex, range_type, Markup) + string_types: return True if type(value) in (tuple, list, set, frozenset): for item in value: if not has_safe_repr(item): return False return True elif type(value) is dict: for key, value in iteritems(value): if not has_safe_repr(key): return False if not has_safe_repr(value): return False return True return False
[ "Does", "the", "node", "have", "a", "safe", "representation?" ]
pypa/pipenv
python
https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/vendor/jinja2/compiler.py#L87-L105
[ "def", "has_safe_repr", "(", "value", ")", ":", "if", "value", "is", "None", "or", "value", "is", "NotImplemented", "or", "value", "is", "Ellipsis", ":", "return", "True", "if", "type", "(", "value", ")", "in", "(", "bool", ",", "int", ",", "float", ...
cae8d76c210b9777e90aab76e9c4b0e53bb19cde
train
find_undeclared
Check if the names passed are accessed undeclared. The return value is a set of all the undeclared names from the sequence of names found.
pipenv/vendor/jinja2/compiler.py
def find_undeclared(nodes, names): """Check if the names passed are accessed undeclared. The return value is a set of all the undeclared names from the sequence of names found. """ visitor = UndeclaredNameVisitor(names) try: for node in nodes: visitor.visit(node) except VisitorExit: pass return visitor.undeclared
def find_undeclared(nodes, names): """Check if the names passed are accessed undeclared. The return value is a set of all the undeclared names from the sequence of names found. """ visitor = UndeclaredNameVisitor(names) try: for node in nodes: visitor.visit(node) except VisitorExit: pass return visitor.undeclared
[ "Check", "if", "the", "names", "passed", "are", "accessed", "undeclared", ".", "The", "return", "value", "is", "a", "set", "of", "all", "the", "undeclared", "names", "from", "the", "sequence", "of", "names", "found", "." ]
pypa/pipenv
python
https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/vendor/jinja2/compiler.py#L108-L118
[ "def", "find_undeclared", "(", "nodes", ",", "names", ")", ":", "visitor", "=", "UndeclaredNameVisitor", "(", "names", ")", "try", ":", "for", "node", "in", "nodes", ":", "visitor", ".", "visit", "(", "node", ")", "except", "VisitorExit", ":", "pass", "r...
cae8d76c210b9777e90aab76e9c4b0e53bb19cde
train
Frame.copy
Create a copy of the current one.
pipenv/vendor/jinja2/compiler.py
def copy(self): """Create a copy of the current one.""" rv = object.__new__(self.__class__) rv.__dict__.update(self.__dict__) rv.symbols = self.symbols.copy() return rv
def copy(self): """Create a copy of the current one.""" rv = object.__new__(self.__class__) rv.__dict__.update(self.__dict__) rv.symbols = self.symbols.copy() return rv
[ "Create", "a", "copy", "of", "the", "current", "one", "." ]
pypa/pipenv
python
https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/vendor/jinja2/compiler.py#L165-L170
[ "def", "copy", "(", "self", ")", ":", "rv", "=", "object", ".", "__new__", "(", "self", ".", "__class__", ")", "rv", ".", "__dict__", ".", "update", "(", "self", ".", "__dict__", ")", "rv", ".", "symbols", "=", "self", ".", "symbols", ".", "copy", ...
cae8d76c210b9777e90aab76e9c4b0e53bb19cde
train
Frame.inner
Return an inner frame.
pipenv/vendor/jinja2/compiler.py
def inner(self, isolated=False): """Return an inner frame.""" if isolated: return Frame(self.eval_ctx, level=self.symbols.level + 1) return Frame(self.eval_ctx, self)
def inner(self, isolated=False): """Return an inner frame.""" if isolated: return Frame(self.eval_ctx, level=self.symbols.level + 1) return Frame(self.eval_ctx, self)
[ "Return", "an", "inner", "frame", "." ]
pypa/pipenv
python
https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/vendor/jinja2/compiler.py#L172-L176
[ "def", "inner", "(", "self", ",", "isolated", "=", "False", ")", ":", "if", "isolated", ":", "return", "Frame", "(", "self", ".", "eval_ctx", ",", "level", "=", "self", ".", "symbols", ".", "level", "+", "1", ")", "return", "Frame", "(", "self", "....
cae8d76c210b9777e90aab76e9c4b0e53bb19cde
train
CodeGenerator.fail
Fail with a :exc:`TemplateAssertionError`.
pipenv/vendor/jinja2/compiler.py
def fail(self, msg, lineno): """Fail with a :exc:`TemplateAssertionError`.""" raise TemplateAssertionError(msg, lineno, self.name, self.filename)
def fail(self, msg, lineno): """Fail with a :exc:`TemplateAssertionError`.""" raise TemplateAssertionError(msg, lineno, self.name, self.filename)
[ "Fail", "with", "a", ":", "exc", ":", "TemplateAssertionError", "." ]
pypa/pipenv
python
https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/vendor/jinja2/compiler.py#L313-L315
[ "def", "fail", "(", "self", ",", "msg", ",", "lineno", ")", ":", "raise", "TemplateAssertionError", "(", "msg", ",", "lineno", ",", "self", ".", "name", ",", "self", ".", "filename", ")" ]
cae8d76c210b9777e90aab76e9c4b0e53bb19cde
train
CodeGenerator.buffer
Enable buffering for the frame from that point onwards.
pipenv/vendor/jinja2/compiler.py
def buffer(self, frame): """Enable buffering for the frame from that point onwards.""" frame.buffer = self.temporary_identifier() self.writeline('%s = []' % frame.buffer)
def buffer(self, frame): """Enable buffering for the frame from that point onwards.""" frame.buffer = self.temporary_identifier() self.writeline('%s = []' % frame.buffer)
[ "Enable", "buffering", "for", "the", "frame", "from", "that", "point", "onwards", "." ]
pypa/pipenv
python
https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/vendor/jinja2/compiler.py#L322-L325
[ "def", "buffer", "(", "self", ",", "frame", ")", ":", "frame", ".", "buffer", "=", "self", ".", "temporary_identifier", "(", ")", "self", ".", "writeline", "(", "'%s = []'", "%", "frame", ".", "buffer", ")" ]
cae8d76c210b9777e90aab76e9c4b0e53bb19cde
train
CodeGenerator.return_buffer_contents
Return the buffer contents of the frame.
pipenv/vendor/jinja2/compiler.py
def return_buffer_contents(self, frame, force_unescaped=False): """Return the buffer contents of the frame.""" if not force_unescaped: if frame.eval_ctx.volatile: self.writeline('if context.eval_ctx.autoescape:') self.indent() self.writeline('return Markup(concat(%s))' % frame.buffer) self.outdent() self.writeline('else:') self.indent() self.writeline('return concat(%s)' % frame.buffer) self.outdent() return elif frame.eval_ctx.autoescape: self.writeline('return Markup(concat(%s))' % frame.buffer) return self.writeline('return concat(%s)' % frame.buffer)
def return_buffer_contents(self, frame, force_unescaped=False): """Return the buffer contents of the frame.""" if not force_unescaped: if frame.eval_ctx.volatile: self.writeline('if context.eval_ctx.autoescape:') self.indent() self.writeline('return Markup(concat(%s))' % frame.buffer) self.outdent() self.writeline('else:') self.indent() self.writeline('return concat(%s)' % frame.buffer) self.outdent() return elif frame.eval_ctx.autoescape: self.writeline('return Markup(concat(%s))' % frame.buffer) return self.writeline('return concat(%s)' % frame.buffer)
[ "Return", "the", "buffer", "contents", "of", "the", "frame", "." ]
pypa/pipenv
python
https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/vendor/jinja2/compiler.py#L327-L343
[ "def", "return_buffer_contents", "(", "self", ",", "frame", ",", "force_unescaped", "=", "False", ")", ":", "if", "not", "force_unescaped", ":", "if", "frame", ".", "eval_ctx", ".", "volatile", ":", "self", ".", "writeline", "(", "'if context.eval_ctx.autoescape...
cae8d76c210b9777e90aab76e9c4b0e53bb19cde
train
CodeGenerator.start_write
Yield or write into the frame buffer.
pipenv/vendor/jinja2/compiler.py
def start_write(self, frame, node=None): """Yield or write into the frame buffer.""" if frame.buffer is None: self.writeline('yield ', node) else: self.writeline('%s.append(' % frame.buffer, node)
def start_write(self, frame, node=None): """Yield or write into the frame buffer.""" if frame.buffer is None: self.writeline('yield ', node) else: self.writeline('%s.append(' % frame.buffer, node)
[ "Yield", "or", "write", "into", "the", "frame", "buffer", "." ]
pypa/pipenv
python
https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/vendor/jinja2/compiler.py#L353-L358
[ "def", "start_write", "(", "self", ",", "frame", ",", "node", "=", "None", ")", ":", "if", "frame", ".", "buffer", "is", "None", ":", "self", ".", "writeline", "(", "'yield '", ",", "node", ")", "else", ":", "self", ".", "writeline", "(", "'%s.append...
cae8d76c210b9777e90aab76e9c4b0e53bb19cde
train
CodeGenerator.simple_write
Simple shortcut for start_write + write + end_write.
pipenv/vendor/jinja2/compiler.py
def simple_write(self, s, frame, node=None): """Simple shortcut for start_write + write + end_write.""" self.start_write(frame, node) self.write(s) self.end_write(frame)
def simple_write(self, s, frame, node=None): """Simple shortcut for start_write + write + end_write.""" self.start_write(frame, node) self.write(s) self.end_write(frame)
[ "Simple", "shortcut", "for", "start_write", "+", "write", "+", "end_write", "." ]
pypa/pipenv
python
https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/vendor/jinja2/compiler.py#L365-L369
[ "def", "simple_write", "(", "self", ",", "s", ",", "frame", ",", "node", "=", "None", ")", ":", "self", ".", "start_write", "(", "frame", ",", "node", ")", "self", ".", "write", "(", "s", ")", "self", ".", "end_write", "(", "frame", ")" ]
cae8d76c210b9777e90aab76e9c4b0e53bb19cde
train
CodeGenerator.write
Write a string into the output stream.
pipenv/vendor/jinja2/compiler.py
def write(self, x): """Write a string into the output stream.""" if self._new_lines: if not self._first_write: self.stream.write('\n' * self._new_lines) self.code_lineno += self._new_lines if self._write_debug_info is not None: self.debug_info.append((self._write_debug_info, self.code_lineno)) self._write_debug_info = None self._first_write = False self.stream.write(' ' * self._indentation) self._new_lines = 0 self.stream.write(x)
def write(self, x): """Write a string into the output stream.""" if self._new_lines: if not self._first_write: self.stream.write('\n' * self._new_lines) self.code_lineno += self._new_lines if self._write_debug_info is not None: self.debug_info.append((self._write_debug_info, self.code_lineno)) self._write_debug_info = None self._first_write = False self.stream.write(' ' * self._indentation) self._new_lines = 0 self.stream.write(x)
[ "Write", "a", "string", "into", "the", "output", "stream", "." ]
pypa/pipenv
python
https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/vendor/jinja2/compiler.py#L382-L395
[ "def", "write", "(", "self", ",", "x", ")", ":", "if", "self", ".", "_new_lines", ":", "if", "not", "self", ".", "_first_write", ":", "self", ".", "stream", ".", "write", "(", "'\\n'", "*", "self", ".", "_new_lines", ")", "self", ".", "code_lineno", ...
cae8d76c210b9777e90aab76e9c4b0e53bb19cde
train
CodeGenerator.writeline
Combination of newline and write.
pipenv/vendor/jinja2/compiler.py
def writeline(self, x, node=None, extra=0): """Combination of newline and write.""" self.newline(node, extra) self.write(x)
def writeline(self, x, node=None, extra=0): """Combination of newline and write.""" self.newline(node, extra) self.write(x)
[ "Combination", "of", "newline", "and", "write", "." ]
pypa/pipenv
python
https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/vendor/jinja2/compiler.py#L397-L400
[ "def", "writeline", "(", "self", ",", "x", ",", "node", "=", "None", ",", "extra", "=", "0", ")", ":", "self", ".", "newline", "(", "node", ",", "extra", ")", "self", ".", "write", "(", "x", ")" ]
cae8d76c210b9777e90aab76e9c4b0e53bb19cde
train
CodeGenerator.newline
Add one or more newlines before the next write.
pipenv/vendor/jinja2/compiler.py
def newline(self, node=None, extra=0): """Add one or more newlines before the next write.""" self._new_lines = max(self._new_lines, 1 + extra) if node is not None and node.lineno != self._last_line: self._write_debug_info = node.lineno self._last_line = node.lineno
def newline(self, node=None, extra=0): """Add one or more newlines before the next write.""" self._new_lines = max(self._new_lines, 1 + extra) if node is not None and node.lineno != self._last_line: self._write_debug_info = node.lineno self._last_line = node.lineno
[ "Add", "one", "or", "more", "newlines", "before", "the", "next", "write", "." ]
pypa/pipenv
python
https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/vendor/jinja2/compiler.py#L402-L407
[ "def", "newline", "(", "self", ",", "node", "=", "None", ",", "extra", "=", "0", ")", ":", "self", ".", "_new_lines", "=", "max", "(", "self", ".", "_new_lines", ",", "1", "+", "extra", ")", "if", "node", "is", "not", "None", "and", "node", ".", ...
cae8d76c210b9777e90aab76e9c4b0e53bb19cde
train
CodeGenerator.signature
Writes a function call to the stream for the current node. A leading comma is added automatically. The extra keyword arguments may not include python keywords otherwise a syntax error could occour. The extra keyword arguments should be given as python dict.
pipenv/vendor/jinja2/compiler.py
def signature(self, node, frame, extra_kwargs=None): """Writes a function call to the stream for the current node. A leading comma is added automatically. The extra keyword arguments may not include python keywords otherwise a syntax error could occour. The extra keyword arguments should be given as python dict. """ # if any of the given keyword arguments is a python keyword # we have to make sure that no invalid call is created. kwarg_workaround = False for kwarg in chain((x.key for x in node.kwargs), extra_kwargs or ()): if is_python_keyword(kwarg): kwarg_workaround = True break for arg in node.args: self.write(', ') self.visit(arg, frame) if not kwarg_workaround: for kwarg in node.kwargs: self.write(', ') self.visit(kwarg, frame) if extra_kwargs is not None: for key, value in iteritems(extra_kwargs): self.write(', %s=%s' % (key, value)) if node.dyn_args: self.write(', *') self.visit(node.dyn_args, frame) if kwarg_workaround: if node.dyn_kwargs is not None: self.write(', **dict({') else: self.write(', **{') for kwarg in node.kwargs: self.write('%r: ' % kwarg.key) self.visit(kwarg.value, frame) self.write(', ') if extra_kwargs is not None: for key, value in iteritems(extra_kwargs): self.write('%r: %s, ' % (key, value)) if node.dyn_kwargs is not None: self.write('}, **') self.visit(node.dyn_kwargs, frame) self.write(')') else: self.write('}') elif node.dyn_kwargs is not None: self.write(', **') self.visit(node.dyn_kwargs, frame)
def signature(self, node, frame, extra_kwargs=None): """Writes a function call to the stream for the current node. A leading comma is added automatically. The extra keyword arguments may not include python keywords otherwise a syntax error could occour. The extra keyword arguments should be given as python dict. """ # if any of the given keyword arguments is a python keyword # we have to make sure that no invalid call is created. kwarg_workaround = False for kwarg in chain((x.key for x in node.kwargs), extra_kwargs or ()): if is_python_keyword(kwarg): kwarg_workaround = True break for arg in node.args: self.write(', ') self.visit(arg, frame) if not kwarg_workaround: for kwarg in node.kwargs: self.write(', ') self.visit(kwarg, frame) if extra_kwargs is not None: for key, value in iteritems(extra_kwargs): self.write(', %s=%s' % (key, value)) if node.dyn_args: self.write(', *') self.visit(node.dyn_args, frame) if kwarg_workaround: if node.dyn_kwargs is not None: self.write(', **dict({') else: self.write(', **{') for kwarg in node.kwargs: self.write('%r: ' % kwarg.key) self.visit(kwarg.value, frame) self.write(', ') if extra_kwargs is not None: for key, value in iteritems(extra_kwargs): self.write('%r: %s, ' % (key, value)) if node.dyn_kwargs is not None: self.write('}, **') self.visit(node.dyn_kwargs, frame) self.write(')') else: self.write('}') elif node.dyn_kwargs is not None: self.write(', **') self.visit(node.dyn_kwargs, frame)
[ "Writes", "a", "function", "call", "to", "the", "stream", "for", "the", "current", "node", ".", "A", "leading", "comma", "is", "added", "automatically", ".", "The", "extra", "keyword", "arguments", "may", "not", "include", "python", "keywords", "otherwise", ...
pypa/pipenv
python
https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/vendor/jinja2/compiler.py#L409-L460
[ "def", "signature", "(", "self", ",", "node", ",", "frame", ",", "extra_kwargs", "=", "None", ")", ":", "# if any of the given keyword arguments is a python keyword", "# we have to make sure that no invalid call is created.", "kwarg_workaround", "=", "False", "for", "kwarg", ...
cae8d76c210b9777e90aab76e9c4b0e53bb19cde
train
CodeGenerator.pull_dependencies
Pull all the dependencies.
pipenv/vendor/jinja2/compiler.py
def pull_dependencies(self, nodes): """Pull all the dependencies.""" visitor = DependencyFinderVisitor() for node in nodes: visitor.visit(node) for dependency in 'filters', 'tests': mapping = getattr(self, dependency) for name in getattr(visitor, dependency): if name not in mapping: mapping[name] = self.temporary_identifier() self.writeline('%s = environment.%s[%r]' % (mapping[name], dependency, name))
def pull_dependencies(self, nodes): """Pull all the dependencies.""" visitor = DependencyFinderVisitor() for node in nodes: visitor.visit(node) for dependency in 'filters', 'tests': mapping = getattr(self, dependency) for name in getattr(visitor, dependency): if name not in mapping: mapping[name] = self.temporary_identifier() self.writeline('%s = environment.%s[%r]' % (mapping[name], dependency, name))
[ "Pull", "all", "the", "dependencies", "." ]
pypa/pipenv
python
https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/vendor/jinja2/compiler.py#L462-L473
[ "def", "pull_dependencies", "(", "self", ",", "nodes", ")", ":", "visitor", "=", "DependencyFinderVisitor", "(", ")", "for", "node", "in", "nodes", ":", "visitor", ".", "visit", "(", "node", ")", "for", "dependency", "in", "'filters'", ",", "'tests'", ":",...
cae8d76c210b9777e90aab76e9c4b0e53bb19cde
train
CodeGenerator.macro_body
Dump the function def of a macro or call block.
pipenv/vendor/jinja2/compiler.py
def macro_body(self, node, frame): """Dump the function def of a macro or call block.""" frame = frame.inner() frame.symbols.analyze_node(node) macro_ref = MacroRef(node) explicit_caller = None skip_special_params = set() args = [] for idx, arg in enumerate(node.args): if arg.name == 'caller': explicit_caller = idx if arg.name in ('kwargs', 'varargs'): skip_special_params.add(arg.name) args.append(frame.symbols.ref(arg.name)) undeclared = find_undeclared(node.body, ('caller', 'kwargs', 'varargs')) if 'caller' in undeclared: # In older Jinja2 versions there was a bug that allowed caller # to retain the special behavior even if it was mentioned in # the argument list. However thankfully this was only really # working if it was the last argument. So we are explicitly # checking this now and error out if it is anywhere else in # the argument list. if explicit_caller is not None: try: node.defaults[explicit_caller - len(node.args)] except IndexError: self.fail('When defining macros or call blocks the ' 'special "caller" argument must be omitted ' 'or be given a default.', node.lineno) else: args.append(frame.symbols.declare_parameter('caller')) macro_ref.accesses_caller = True if 'kwargs' in undeclared and not 'kwargs' in skip_special_params: args.append(frame.symbols.declare_parameter('kwargs')) macro_ref.accesses_kwargs = True if 'varargs' in undeclared and not 'varargs' in skip_special_params: args.append(frame.symbols.declare_parameter('varargs')) macro_ref.accesses_varargs = True # macros are delayed, they never require output checks frame.require_output_check = False frame.symbols.analyze_node(node) self.writeline('%s(%s):' % (self.func('macro'), ', '.join(args)), node) self.indent() self.buffer(frame) self.enter_frame(frame) self.push_parameter_definitions(frame) for idx, arg in enumerate(node.args): ref = frame.symbols.ref(arg.name) self.writeline('if %s is missing:' % ref) self.indent() try: default = node.defaults[idx - len(node.args)] except IndexError: self.writeline('%s = undefined(%r, name=%r)' % ( ref, 'parameter %r was not provided' % arg.name, arg.name)) else: self.writeline('%s = ' % ref) self.visit(default, frame) self.mark_parameter_stored(ref) self.outdent() self.pop_parameter_definitions() self.blockvisit(node.body, frame) self.return_buffer_contents(frame, force_unescaped=True) self.leave_frame(frame, with_python_scope=True) self.outdent() return frame, macro_ref
def macro_body(self, node, frame): """Dump the function def of a macro or call block.""" frame = frame.inner() frame.symbols.analyze_node(node) macro_ref = MacroRef(node) explicit_caller = None skip_special_params = set() args = [] for idx, arg in enumerate(node.args): if arg.name == 'caller': explicit_caller = idx if arg.name in ('kwargs', 'varargs'): skip_special_params.add(arg.name) args.append(frame.symbols.ref(arg.name)) undeclared = find_undeclared(node.body, ('caller', 'kwargs', 'varargs')) if 'caller' in undeclared: # In older Jinja2 versions there was a bug that allowed caller # to retain the special behavior even if it was mentioned in # the argument list. However thankfully this was only really # working if it was the last argument. So we are explicitly # checking this now and error out if it is anywhere else in # the argument list. if explicit_caller is not None: try: node.defaults[explicit_caller - len(node.args)] except IndexError: self.fail('When defining macros or call blocks the ' 'special "caller" argument must be omitted ' 'or be given a default.', node.lineno) else: args.append(frame.symbols.declare_parameter('caller')) macro_ref.accesses_caller = True if 'kwargs' in undeclared and not 'kwargs' in skip_special_params: args.append(frame.symbols.declare_parameter('kwargs')) macro_ref.accesses_kwargs = True if 'varargs' in undeclared and not 'varargs' in skip_special_params: args.append(frame.symbols.declare_parameter('varargs')) macro_ref.accesses_varargs = True # macros are delayed, they never require output checks frame.require_output_check = False frame.symbols.analyze_node(node) self.writeline('%s(%s):' % (self.func('macro'), ', '.join(args)), node) self.indent() self.buffer(frame) self.enter_frame(frame) self.push_parameter_definitions(frame) for idx, arg in enumerate(node.args): ref = frame.symbols.ref(arg.name) self.writeline('if %s is missing:' % ref) self.indent() try: default = node.defaults[idx - len(node.args)] except IndexError: self.writeline('%s = undefined(%r, name=%r)' % ( ref, 'parameter %r was not provided' % arg.name, arg.name)) else: self.writeline('%s = ' % ref) self.visit(default, frame) self.mark_parameter_stored(ref) self.outdent() self.pop_parameter_definitions() self.blockvisit(node.body, frame) self.return_buffer_contents(frame, force_unescaped=True) self.leave_frame(frame, with_python_scope=True) self.outdent() return frame, macro_ref
[ "Dump", "the", "function", "def", "of", "a", "macro", "or", "call", "block", "." ]
pypa/pipenv
python
https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/vendor/jinja2/compiler.py#L505-L580
[ "def", "macro_body", "(", "self", ",", "node", ",", "frame", ")", ":", "frame", "=", "frame", ".", "inner", "(", ")", "frame", ".", "symbols", ".", "analyze_node", "(", "node", ")", "macro_ref", "=", "MacroRef", "(", "node", ")", "explicit_caller", "="...
cae8d76c210b9777e90aab76e9c4b0e53bb19cde
train
CodeGenerator.macro_def
Dump the macro definition for the def created by macro_body.
pipenv/vendor/jinja2/compiler.py
def macro_def(self, macro_ref, frame): """Dump the macro definition for the def created by macro_body.""" arg_tuple = ', '.join(repr(x.name) for x in macro_ref.node.args) name = getattr(macro_ref.node, 'name', None) if len(macro_ref.node.args) == 1: arg_tuple += ',' self.write('Macro(environment, macro, %r, (%s), %r, %r, %r, ' 'context.eval_ctx.autoescape)' % (name, arg_tuple, macro_ref.accesses_kwargs, macro_ref.accesses_varargs, macro_ref.accesses_caller))
def macro_def(self, macro_ref, frame): """Dump the macro definition for the def created by macro_body.""" arg_tuple = ', '.join(repr(x.name) for x in macro_ref.node.args) name = getattr(macro_ref.node, 'name', None) if len(macro_ref.node.args) == 1: arg_tuple += ',' self.write('Macro(environment, macro, %r, (%s), %r, %r, %r, ' 'context.eval_ctx.autoescape)' % (name, arg_tuple, macro_ref.accesses_kwargs, macro_ref.accesses_varargs, macro_ref.accesses_caller))
[ "Dump", "the", "macro", "definition", "for", "the", "def", "created", "by", "macro_body", "." ]
pypa/pipenv
python
https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/vendor/jinja2/compiler.py#L582-L591
[ "def", "macro_def", "(", "self", ",", "macro_ref", ",", "frame", ")", ":", "arg_tuple", "=", "', '", ".", "join", "(", "repr", "(", "x", ".", "name", ")", "for", "x", "in", "macro_ref", ".", "node", ".", "args", ")", "name", "=", "getattr", "(", ...
cae8d76c210b9777e90aab76e9c4b0e53bb19cde
train
CodeGenerator.position
Return a human readable position for the node.
pipenv/vendor/jinja2/compiler.py
def position(self, node): """Return a human readable position for the node.""" rv = 'line %d' % node.lineno if self.name is not None: rv += ' in ' + repr(self.name) return rv
def position(self, node): """Return a human readable position for the node.""" rv = 'line %d' % node.lineno if self.name is not None: rv += ' in ' + repr(self.name) return rv
[ "Return", "a", "human", "readable", "position", "for", "the", "node", "." ]
pypa/pipenv
python
https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/vendor/jinja2/compiler.py#L593-L598
[ "def", "position", "(", "self", ",", "node", ")", ":", "rv", "=", "'line %d'", "%", "node", ".", "lineno", "if", "self", ".", "name", "is", "not", "None", ":", "rv", "+=", "' in '", "+", "repr", "(", "self", ".", "name", ")", "return", "rv" ]
cae8d76c210b9777e90aab76e9c4b0e53bb19cde
train
CodeGenerator.pop_assign_tracking
Pops the topmost level for assignment tracking and updates the context variables if necessary.
pipenv/vendor/jinja2/compiler.py
def pop_assign_tracking(self, frame): """Pops the topmost level for assignment tracking and updates the context variables if necessary. """ vars = self._assign_stack.pop() if not frame.toplevel or not vars: return public_names = [x for x in vars if x[:1] != '_'] if len(vars) == 1: name = next(iter(vars)) ref = frame.symbols.ref(name) self.writeline('context.vars[%r] = %s' % (name, ref)) else: self.writeline('context.vars.update({') for idx, name in enumerate(vars): if idx: self.write(', ') ref = frame.symbols.ref(name) self.write('%r: %s' % (name, ref)) self.write('})') if public_names: if len(public_names) == 1: self.writeline('context.exported_vars.add(%r)' % public_names[0]) else: self.writeline('context.exported_vars.update((%s))' % ', '.join(imap(repr, public_names)))
def pop_assign_tracking(self, frame): """Pops the topmost level for assignment tracking and updates the context variables if necessary. """ vars = self._assign_stack.pop() if not frame.toplevel or not vars: return public_names = [x for x in vars if x[:1] != '_'] if len(vars) == 1: name = next(iter(vars)) ref = frame.symbols.ref(name) self.writeline('context.vars[%r] = %s' % (name, ref)) else: self.writeline('context.vars.update({') for idx, name in enumerate(vars): if idx: self.write(', ') ref = frame.symbols.ref(name) self.write('%r: %s' % (name, ref)) self.write('})') if public_names: if len(public_names) == 1: self.writeline('context.exported_vars.add(%r)' % public_names[0]) else: self.writeline('context.exported_vars.update((%s))' % ', '.join(imap(repr, public_names)))
[ "Pops", "the", "topmost", "level", "for", "assignment", "tracking", "and", "updates", "the", "context", "variables", "if", "necessary", "." ]
pypa/pipenv
python
https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/vendor/jinja2/compiler.py#L665-L691
[ "def", "pop_assign_tracking", "(", "self", ",", "frame", ")", ":", "vars", "=", "self", ".", "_assign_stack", ".", "pop", "(", ")", "if", "not", "frame", ".", "toplevel", "or", "not", "vars", ":", "return", "public_names", "=", "[", "x", "for", "x", ...
cae8d76c210b9777e90aab76e9c4b0e53bb19cde
train
CodeGenerator.visit_Block
Call a block and register it for the template.
pipenv/vendor/jinja2/compiler.py
def visit_Block(self, node, frame): """Call a block and register it for the template.""" level = 0 if frame.toplevel: # if we know that we are a child template, there is no need to # check if we are one if self.has_known_extends: return if self.extends_so_far > 0: self.writeline('if parent_template is None:') self.indent() level += 1 if node.scoped: context = self.derive_context(frame) else: context = self.get_context_ref() if supports_yield_from and not self.environment.is_async and \ frame.buffer is None: self.writeline('yield from context.blocks[%r][0](%s)' % ( node.name, context), node) else: loop = self.environment.is_async and 'async for' or 'for' self.writeline('%s event in context.blocks[%r][0](%s):' % ( loop, node.name, context), node) self.indent() self.simple_write('event', frame) self.outdent() self.outdent(level)
def visit_Block(self, node, frame): """Call a block and register it for the template.""" level = 0 if frame.toplevel: # if we know that we are a child template, there is no need to # check if we are one if self.has_known_extends: return if self.extends_so_far > 0: self.writeline('if parent_template is None:') self.indent() level += 1 if node.scoped: context = self.derive_context(frame) else: context = self.get_context_ref() if supports_yield_from and not self.environment.is_async and \ frame.buffer is None: self.writeline('yield from context.blocks[%r][0](%s)' % ( node.name, context), node) else: loop = self.environment.is_async and 'async for' or 'for' self.writeline('%s event in context.blocks[%r][0](%s):' % ( loop, node.name, context), node) self.indent() self.simple_write('event', frame) self.outdent() self.outdent(level)
[ "Call", "a", "block", "and", "register", "it", "for", "the", "template", "." ]
pypa/pipenv
python
https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/vendor/jinja2/compiler.py#L811-L841
[ "def", "visit_Block", "(", "self", ",", "node", ",", "frame", ")", ":", "level", "=", "0", "if", "frame", ".", "toplevel", ":", "# if we know that we are a child template, there is no need to", "# check if we are one", "if", "self", ".", "has_known_extends", ":", "r...
cae8d76c210b9777e90aab76e9c4b0e53bb19cde
train
CodeGenerator.visit_Extends
Calls the extender.
pipenv/vendor/jinja2/compiler.py
def visit_Extends(self, node, frame): """Calls the extender.""" if not frame.toplevel: self.fail('cannot use extend from a non top-level scope', node.lineno) # if the number of extends statements in general is zero so # far, we don't have to add a check if something extended # the template before this one. if self.extends_so_far > 0: # if we have a known extends we just add a template runtime # error into the generated code. We could catch that at compile # time too, but i welcome it not to confuse users by throwing the # same error at different times just "because we can". if not self.has_known_extends: self.writeline('if parent_template is not None:') self.indent() self.writeline('raise TemplateRuntimeError(%r)' % 'extended multiple times') # if we have a known extends already we don't need that code here # as we know that the template execution will end here. if self.has_known_extends: raise CompilerExit() else: self.outdent() self.writeline('parent_template = environment.get_template(', node) self.visit(node.template, frame) self.write(', %r)' % self.name) self.writeline('for name, parent_block in parent_template.' 'blocks.%s():' % dict_item_iter) self.indent() self.writeline('context.blocks.setdefault(name, []).' 'append(parent_block)') self.outdent() # if this extends statement was in the root level we can take # advantage of that information and simplify the generated code # in the top level from this point onwards if frame.rootlevel: self.has_known_extends = True # and now we have one more self.extends_so_far += 1
def visit_Extends(self, node, frame): """Calls the extender.""" if not frame.toplevel: self.fail('cannot use extend from a non top-level scope', node.lineno) # if the number of extends statements in general is zero so # far, we don't have to add a check if something extended # the template before this one. if self.extends_so_far > 0: # if we have a known extends we just add a template runtime # error into the generated code. We could catch that at compile # time too, but i welcome it not to confuse users by throwing the # same error at different times just "because we can". if not self.has_known_extends: self.writeline('if parent_template is not None:') self.indent() self.writeline('raise TemplateRuntimeError(%r)' % 'extended multiple times') # if we have a known extends already we don't need that code here # as we know that the template execution will end here. if self.has_known_extends: raise CompilerExit() else: self.outdent() self.writeline('parent_template = environment.get_template(', node) self.visit(node.template, frame) self.write(', %r)' % self.name) self.writeline('for name, parent_block in parent_template.' 'blocks.%s():' % dict_item_iter) self.indent() self.writeline('context.blocks.setdefault(name, []).' 'append(parent_block)') self.outdent() # if this extends statement was in the root level we can take # advantage of that information and simplify the generated code # in the top level from this point onwards if frame.rootlevel: self.has_known_extends = True # and now we have one more self.extends_so_far += 1
[ "Calls", "the", "extender", "." ]
pypa/pipenv
python
https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/vendor/jinja2/compiler.py#L843-L888
[ "def", "visit_Extends", "(", "self", ",", "node", ",", "frame", ")", ":", "if", "not", "frame", ".", "toplevel", ":", "self", ".", "fail", "(", "'cannot use extend from a non top-level scope'", ",", "node", ".", "lineno", ")", "# if the number of extends statement...
cae8d76c210b9777e90aab76e9c4b0e53bb19cde
train
CodeGenerator.visit_Include
Handles includes.
pipenv/vendor/jinja2/compiler.py
def visit_Include(self, node, frame): """Handles includes.""" if node.ignore_missing: self.writeline('try:') self.indent() func_name = 'get_or_select_template' if isinstance(node.template, nodes.Const): if isinstance(node.template.value, string_types): func_name = 'get_template' elif isinstance(node.template.value, (tuple, list)): func_name = 'select_template' elif isinstance(node.template, (nodes.Tuple, nodes.List)): func_name = 'select_template' self.writeline('template = environment.%s(' % func_name, node) self.visit(node.template, frame) self.write(', %r)' % self.name) if node.ignore_missing: self.outdent() self.writeline('except TemplateNotFound:') self.indent() self.writeline('pass') self.outdent() self.writeline('else:') self.indent() skip_event_yield = False if node.with_context: loop = self.environment.is_async and 'async for' or 'for' self.writeline('%s event in template.root_render_func(' 'template.new_context(context.get_all(), True, ' '%s)):' % (loop, self.dump_local_context(frame))) elif self.environment.is_async: self.writeline('for event in (await ' 'template._get_default_module_async())' '._body_stream:') else: if supports_yield_from: self.writeline('yield from template._get_default_module()' '._body_stream') skip_event_yield = True else: self.writeline('for event in template._get_default_module()' '._body_stream:') if not skip_event_yield: self.indent() self.simple_write('event', frame) self.outdent() if node.ignore_missing: self.outdent()
def visit_Include(self, node, frame): """Handles includes.""" if node.ignore_missing: self.writeline('try:') self.indent() func_name = 'get_or_select_template' if isinstance(node.template, nodes.Const): if isinstance(node.template.value, string_types): func_name = 'get_template' elif isinstance(node.template.value, (tuple, list)): func_name = 'select_template' elif isinstance(node.template, (nodes.Tuple, nodes.List)): func_name = 'select_template' self.writeline('template = environment.%s(' % func_name, node) self.visit(node.template, frame) self.write(', %r)' % self.name) if node.ignore_missing: self.outdent() self.writeline('except TemplateNotFound:') self.indent() self.writeline('pass') self.outdent() self.writeline('else:') self.indent() skip_event_yield = False if node.with_context: loop = self.environment.is_async and 'async for' or 'for' self.writeline('%s event in template.root_render_func(' 'template.new_context(context.get_all(), True, ' '%s)):' % (loop, self.dump_local_context(frame))) elif self.environment.is_async: self.writeline('for event in (await ' 'template._get_default_module_async())' '._body_stream:') else: if supports_yield_from: self.writeline('yield from template._get_default_module()' '._body_stream') skip_event_yield = True else: self.writeline('for event in template._get_default_module()' '._body_stream:') if not skip_event_yield: self.indent() self.simple_write('event', frame) self.outdent() if node.ignore_missing: self.outdent()
[ "Handles", "includes", "." ]
pypa/pipenv
python
https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/vendor/jinja2/compiler.py#L890-L942
[ "def", "visit_Include", "(", "self", ",", "node", ",", "frame", ")", ":", "if", "node", ".", "ignore_missing", ":", "self", ".", "writeline", "(", "'try:'", ")", "self", ".", "indent", "(", ")", "func_name", "=", "'get_or_select_template'", "if", "isinstan...
cae8d76c210b9777e90aab76e9c4b0e53bb19cde
train
CodeGenerator.visit_Import
Visit regular imports.
pipenv/vendor/jinja2/compiler.py
def visit_Import(self, node, frame): """Visit regular imports.""" self.writeline('%s = ' % frame.symbols.ref(node.target), node) if frame.toplevel: self.write('context.vars[%r] = ' % node.target) if self.environment.is_async: self.write('await ') self.write('environment.get_template(') self.visit(node.template, frame) self.write(', %r).' % self.name) if node.with_context: self.write('make_module%s(context.get_all(), True, %s)' % (self.environment.is_async and '_async' or '', self.dump_local_context(frame))) elif self.environment.is_async: self.write('_get_default_module_async()') else: self.write('_get_default_module()') if frame.toplevel and not node.target.startswith('_'): self.writeline('context.exported_vars.discard(%r)' % node.target)
def visit_Import(self, node, frame): """Visit regular imports.""" self.writeline('%s = ' % frame.symbols.ref(node.target), node) if frame.toplevel: self.write('context.vars[%r] = ' % node.target) if self.environment.is_async: self.write('await ') self.write('environment.get_template(') self.visit(node.template, frame) self.write(', %r).' % self.name) if node.with_context: self.write('make_module%s(context.get_all(), True, %s)' % (self.environment.is_async and '_async' or '', self.dump_local_context(frame))) elif self.environment.is_async: self.write('_get_default_module_async()') else: self.write('_get_default_module()') if frame.toplevel and not node.target.startswith('_'): self.writeline('context.exported_vars.discard(%r)' % node.target)
[ "Visit", "regular", "imports", "." ]
pypa/pipenv
python
https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/vendor/jinja2/compiler.py#L944-L963
[ "def", "visit_Import", "(", "self", ",", "node", ",", "frame", ")", ":", "self", ".", "writeline", "(", "'%s = '", "%", "frame", ".", "symbols", ".", "ref", "(", "node", ".", "target", ")", ",", "node", ")", "if", "frame", ".", "toplevel", ":", "se...
cae8d76c210b9777e90aab76e9c4b0e53bb19cde
train
CodeGenerator.visit_FromImport
Visit named imports.
pipenv/vendor/jinja2/compiler.py
def visit_FromImport(self, node, frame): """Visit named imports.""" self.newline(node) self.write('included_template = %senvironment.get_template(' % (self.environment.is_async and 'await ' or '')) self.visit(node.template, frame) self.write(', %r).' % self.name) if node.with_context: self.write('make_module%s(context.get_all(), True, %s)' % (self.environment.is_async and '_async' or '', self.dump_local_context(frame))) elif self.environment.is_async: self.write('_get_default_module_async()') else: self.write('_get_default_module()') var_names = [] discarded_names = [] for name in node.names: if isinstance(name, tuple): name, alias = name else: alias = name self.writeline('%s = getattr(included_template, ' '%r, missing)' % (frame.symbols.ref(alias), name)) self.writeline('if %s is missing:' % frame.symbols.ref(alias)) self.indent() self.writeline('%s = undefined(%r %% ' 'included_template.__name__, ' 'name=%r)' % (frame.symbols.ref(alias), 'the template %%r (imported on %s) does ' 'not export the requested name %s' % ( self.position(node), repr(name) ), name)) self.outdent() if frame.toplevel: var_names.append(alias) if not alias.startswith('_'): discarded_names.append(alias) if var_names: if len(var_names) == 1: name = var_names[0] self.writeline('context.vars[%r] = %s' % (name, frame.symbols.ref(name))) else: self.writeline('context.vars.update({%s})' % ', '.join( '%r: %s' % (name, frame.symbols.ref(name)) for name in var_names )) if discarded_names: if len(discarded_names) == 1: self.writeline('context.exported_vars.discard(%r)' % discarded_names[0]) else: self.writeline('context.exported_vars.difference_' 'update((%s))' % ', '.join(imap(repr, discarded_names)))
def visit_FromImport(self, node, frame): """Visit named imports.""" self.newline(node) self.write('included_template = %senvironment.get_template(' % (self.environment.is_async and 'await ' or '')) self.visit(node.template, frame) self.write(', %r).' % self.name) if node.with_context: self.write('make_module%s(context.get_all(), True, %s)' % (self.environment.is_async and '_async' or '', self.dump_local_context(frame))) elif self.environment.is_async: self.write('_get_default_module_async()') else: self.write('_get_default_module()') var_names = [] discarded_names = [] for name in node.names: if isinstance(name, tuple): name, alias = name else: alias = name self.writeline('%s = getattr(included_template, ' '%r, missing)' % (frame.symbols.ref(alias), name)) self.writeline('if %s is missing:' % frame.symbols.ref(alias)) self.indent() self.writeline('%s = undefined(%r %% ' 'included_template.__name__, ' 'name=%r)' % (frame.symbols.ref(alias), 'the template %%r (imported on %s) does ' 'not export the requested name %s' % ( self.position(node), repr(name) ), name)) self.outdent() if frame.toplevel: var_names.append(alias) if not alias.startswith('_'): discarded_names.append(alias) if var_names: if len(var_names) == 1: name = var_names[0] self.writeline('context.vars[%r] = %s' % (name, frame.symbols.ref(name))) else: self.writeline('context.vars.update({%s})' % ', '.join( '%r: %s' % (name, frame.symbols.ref(name)) for name in var_names )) if discarded_names: if len(discarded_names) == 1: self.writeline('context.exported_vars.discard(%r)' % discarded_names[0]) else: self.writeline('context.exported_vars.difference_' 'update((%s))' % ', '.join(imap(repr, discarded_names)))
[ "Visit", "named", "imports", "." ]
pypa/pipenv
python
https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/vendor/jinja2/compiler.py#L965-L1022
[ "def", "visit_FromImport", "(", "self", ",", "node", ",", "frame", ")", ":", "self", ".", "newline", "(", "node", ")", "self", ".", "write", "(", "'included_template = %senvironment.get_template('", "%", "(", "self", ".", "environment", ".", "is_async", "and",...
cae8d76c210b9777e90aab76e9c4b0e53bb19cde
train
finalize.detach
If alive then mark as dead and return (obj, func, args, kwargs); otherwise return None
pipenv/vendor/backports/weakref.py
def detach(self): """If alive then mark as dead and return (obj, func, args, kwargs); otherwise return None""" info = self._registry.get(self) obj = info and info.weakref() if obj is not None and self._registry.pop(self, None): return (obj, info.func, info.args, info.kwargs or {})
def detach(self): """If alive then mark as dead and return (obj, func, args, kwargs); otherwise return None""" info = self._registry.get(self) obj = info and info.weakref() if obj is not None and self._registry.pop(self, None): return (obj, info.func, info.args, info.kwargs or {})
[ "If", "alive", "then", "mark", "as", "dead", "and", "return", "(", "obj", "func", "args", "kwargs", ")", ";", "otherwise", "return", "None" ]
pypa/pipenv
python
https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/vendor/backports/weakref.py#L69-L75
[ "def", "detach", "(", "self", ")", ":", "info", "=", "self", ".", "_registry", ".", "get", "(", "self", ")", "obj", "=", "info", "and", "info", ".", "weakref", "(", ")", "if", "obj", "is", "not", "None", "and", "self", ".", "_registry", ".", "pop...
cae8d76c210b9777e90aab76e9c4b0e53bb19cde
train
finalize.peek
If alive then return (obj, func, args, kwargs); otherwise return None
pipenv/vendor/backports/weakref.py
def peek(self): """If alive then return (obj, func, args, kwargs); otherwise return None""" info = self._registry.get(self) obj = info and info.weakref() if obj is not None: return (obj, info.func, info.args, info.kwargs or {})
def peek(self): """If alive then return (obj, func, args, kwargs); otherwise return None""" info = self._registry.get(self) obj = info and info.weakref() if obj is not None: return (obj, info.func, info.args, info.kwargs or {})
[ "If", "alive", "then", "return", "(", "obj", "func", "args", "kwargs", ")", ";", "otherwise", "return", "None" ]
pypa/pipenv
python
https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/vendor/backports/weakref.py#L77-L83
[ "def", "peek", "(", "self", ")", ":", "info", "=", "self", ".", "_registry", ".", "get", "(", "self", ")", "obj", "=", "info", "and", "info", ".", "weakref", "(", ")", "if", "obj", "is", "not", "None", ":", "return", "(", "obj", ",", "info", "....
cae8d76c210b9777e90aab76e9c4b0e53bb19cde
train
finalize.atexit
Whether finalizer should be called at exit
pipenv/vendor/backports/weakref.py
def atexit(self): """Whether finalizer should be called at exit""" info = self._registry.get(self) return bool(info) and info.atexit
def atexit(self): """Whether finalizer should be called at exit""" info = self._registry.get(self) return bool(info) and info.atexit
[ "Whether", "finalizer", "should", "be", "called", "at", "exit" ]
pypa/pipenv
python
https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/vendor/backports/weakref.py#L91-L94
[ "def", "atexit", "(", "self", ")", ":", "info", "=", "self", ".", "_registry", ".", "get", "(", "self", ")", "return", "bool", "(", "info", ")", "and", "info", ".", "atexit" ]
cae8d76c210b9777e90aab76e9c4b0e53bb19cde
train
tostring
Serialize an element and its child nodes to a string
pipenv/patched/notpip/_vendor/html5lib/treebuilders/etree_lxml.py
def tostring(element): """Serialize an element and its child nodes to a string""" rv = [] def serializeElement(element): if not hasattr(element, "tag"): if element.docinfo.internalDTD: if element.docinfo.doctype: dtd_str = element.docinfo.doctype else: dtd_str = "<!DOCTYPE %s>" % element.docinfo.root_name rv.append(dtd_str) serializeElement(element.getroot()) elif element.tag == comment_type: rv.append("<!--%s-->" % (element.text,)) else: # This is assumed to be an ordinary element if not element.attrib: rv.append("<%s>" % (element.tag,)) else: attr = " ".join(["%s=\"%s\"" % (name, value) for name, value in element.attrib.items()]) rv.append("<%s %s>" % (element.tag, attr)) if element.text: rv.append(element.text) for child in element: serializeElement(child) rv.append("</%s>" % (element.tag,)) if hasattr(element, "tail") and element.tail: rv.append(element.tail) serializeElement(element) return "".join(rv)
def tostring(element): """Serialize an element and its child nodes to a string""" rv = [] def serializeElement(element): if not hasattr(element, "tag"): if element.docinfo.internalDTD: if element.docinfo.doctype: dtd_str = element.docinfo.doctype else: dtd_str = "<!DOCTYPE %s>" % element.docinfo.root_name rv.append(dtd_str) serializeElement(element.getroot()) elif element.tag == comment_type: rv.append("<!--%s-->" % (element.text,)) else: # This is assumed to be an ordinary element if not element.attrib: rv.append("<%s>" % (element.tag,)) else: attr = " ".join(["%s=\"%s\"" % (name, value) for name, value in element.attrib.items()]) rv.append("<%s %s>" % (element.tag, attr)) if element.text: rv.append(element.text) for child in element: serializeElement(child) rv.append("</%s>" % (element.tag,)) if hasattr(element, "tail") and element.tail: rv.append(element.tail) serializeElement(element) return "".join(rv)
[ "Serialize", "an", "element", "and", "its", "child", "nodes", "to", "a", "string" ]
pypa/pipenv
python
https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/patched/notpip/_vendor/html5lib/treebuilders/etree_lxml.py#L134-L172
[ "def", "tostring", "(", "element", ")", ":", "rv", "=", "[", "]", "def", "serializeElement", "(", "element", ")", ":", "if", "not", "hasattr", "(", "element", ",", "\"tag\"", ")", ":", "if", "element", ".", "docinfo", ".", "internalDTD", ":", "if", "...
cae8d76c210b9777e90aab76e9c4b0e53bb19cde
train
NodeVisitor.get_visitor
Return the visitor function for this node or `None` if no visitor exists for this node. In that case the generic visit function is used instead.
pipenv/vendor/jinja2/visitor.py
def get_visitor(self, node): """Return the visitor function for this node or `None` if no visitor exists for this node. In that case the generic visit function is used instead. """ method = 'visit_' + node.__class__.__name__ return getattr(self, method, None)
def get_visitor(self, node): """Return the visitor function for this node or `None` if no visitor exists for this node. In that case the generic visit function is used instead. """ method = 'visit_' + node.__class__.__name__ return getattr(self, method, None)
[ "Return", "the", "visitor", "function", "for", "this", "node", "or", "None", "if", "no", "visitor", "exists", "for", "this", "node", ".", "In", "that", "case", "the", "generic", "visit", "function", "is", "used", "instead", "." ]
pypa/pipenv
python
https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/vendor/jinja2/visitor.py#L26-L32
[ "def", "get_visitor", "(", "self", ",", "node", ")", ":", "method", "=", "'visit_'", "+", "node", ".", "__class__", ".", "__name__", "return", "getattr", "(", "self", ",", "method", ",", "None", ")" ]
cae8d76c210b9777e90aab76e9c4b0e53bb19cde
train
NodeVisitor.visit
Visit a node.
pipenv/vendor/jinja2/visitor.py
def visit(self, node, *args, **kwargs): """Visit a node.""" f = self.get_visitor(node) if f is not None: return f(node, *args, **kwargs) return self.generic_visit(node, *args, **kwargs)
def visit(self, node, *args, **kwargs): """Visit a node.""" f = self.get_visitor(node) if f is not None: return f(node, *args, **kwargs) return self.generic_visit(node, *args, **kwargs)
[ "Visit", "a", "node", "." ]
pypa/pipenv
python
https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/vendor/jinja2/visitor.py#L34-L39
[ "def", "visit", "(", "self", ",", "node", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "f", "=", "self", ".", "get_visitor", "(", "node", ")", "if", "f", "is", "not", "None", ":", "return", "f", "(", "node", ",", "*", "args", ",", "*"...
cae8d76c210b9777e90aab76e9c4b0e53bb19cde
train
NodeVisitor.generic_visit
Called if no explicit visitor function exists for a node.
pipenv/vendor/jinja2/visitor.py
def generic_visit(self, node, *args, **kwargs): """Called if no explicit visitor function exists for a node.""" for node in node.iter_child_nodes(): self.visit(node, *args, **kwargs)
def generic_visit(self, node, *args, **kwargs): """Called if no explicit visitor function exists for a node.""" for node in node.iter_child_nodes(): self.visit(node, *args, **kwargs)
[ "Called", "if", "no", "explicit", "visitor", "function", "exists", "for", "a", "node", "." ]
pypa/pipenv
python
https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/vendor/jinja2/visitor.py#L41-L44
[ "def", "generic_visit", "(", "self", ",", "node", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "for", "node", "in", "node", ".", "iter_child_nodes", "(", ")", ":", "self", ".", "visit", "(", "node", ",", "*", "args", ",", "*", "*", "kwarg...
cae8d76c210b9777e90aab76e9c4b0e53bb19cde
train
NodeTransformer.visit_list
As transformers may return lists in some places this method can be used to enforce a list as return value.
pipenv/vendor/jinja2/visitor.py
def visit_list(self, node, *args, **kwargs): """As transformers may return lists in some places this method can be used to enforce a list as return value. """ rv = self.visit(node, *args, **kwargs) if not isinstance(rv, list): rv = [rv] return rv
def visit_list(self, node, *args, **kwargs): """As transformers may return lists in some places this method can be used to enforce a list as return value. """ rv = self.visit(node, *args, **kwargs) if not isinstance(rv, list): rv = [rv] return rv
[ "As", "transformers", "may", "return", "lists", "in", "some", "places", "this", "method", "can", "be", "used", "to", "enforce", "a", "list", "as", "return", "value", "." ]
pypa/pipenv
python
https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/vendor/jinja2/visitor.py#L80-L87
[ "def", "visit_list", "(", "self", ",", "node", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "rv", "=", "self", ".", "visit", "(", "node", ",", "*", "args", ",", "*", "*", "kwargs", ")", "if", "not", "isinstance", "(", "rv", ",", "list",...
cae8d76c210b9777e90aab76e9c4b0e53bb19cde
train
default_subprocess_runner
The default method of calling the wrapper subprocess.
pipenv/vendor/pep517/wrappers.py
def default_subprocess_runner(cmd, cwd=None, extra_environ=None): """The default method of calling the wrapper subprocess.""" env = os.environ.copy() if extra_environ: env.update(extra_environ) check_call(cmd, cwd=cwd, env=env)
def default_subprocess_runner(cmd, cwd=None, extra_environ=None): """The default method of calling the wrapper subprocess.""" env = os.environ.copy() if extra_environ: env.update(extra_environ) check_call(cmd, cwd=cwd, env=env)
[ "The", "default", "method", "of", "calling", "the", "wrapper", "subprocess", "." ]
pypa/pipenv
python
https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/vendor/pep517/wrappers.py#L31-L37
[ "def", "default_subprocess_runner", "(", "cmd", ",", "cwd", "=", "None", ",", "extra_environ", "=", "None", ")", ":", "env", "=", "os", ".", "environ", ".", "copy", "(", ")", "if", "extra_environ", ":", "env", ".", "update", "(", "extra_environ", ")", ...
cae8d76c210b9777e90aab76e9c4b0e53bb19cde
train
Pep517HookCaller.build_wheel
Build a wheel from this project. Returns the name of the newly created file. In general, this will call the 'build_wheel' hook in the backend. However, if that was previously called by 'prepare_metadata_for_build_wheel', and the same metadata_directory is used, the previously built wheel will be copied to wheel_directory.
pipenv/vendor/pep517/wrappers.py
def build_wheel( self, wheel_directory, config_settings=None, metadata_directory=None): """Build a wheel from this project. Returns the name of the newly created file. In general, this will call the 'build_wheel' hook in the backend. However, if that was previously called by 'prepare_metadata_for_build_wheel', and the same metadata_directory is used, the previously built wheel will be copied to wheel_directory. """ if metadata_directory is not None: metadata_directory = abspath(metadata_directory) return self._call_hook('build_wheel', { 'wheel_directory': abspath(wheel_directory), 'config_settings': config_settings, 'metadata_directory': metadata_directory, })
def build_wheel( self, wheel_directory, config_settings=None, metadata_directory=None): """Build a wheel from this project. Returns the name of the newly created file. In general, this will call the 'build_wheel' hook in the backend. However, if that was previously called by 'prepare_metadata_for_build_wheel', and the same metadata_directory is used, the previously built wheel will be copied to wheel_directory. """ if metadata_directory is not None: metadata_directory = abspath(metadata_directory) return self._call_hook('build_wheel', { 'wheel_directory': abspath(wheel_directory), 'config_settings': config_settings, 'metadata_directory': metadata_directory, })
[ "Build", "a", "wheel", "from", "this", "project", "." ]
pypa/pipenv
python
https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/vendor/pep517/wrappers.py#L89-L107
[ "def", "build_wheel", "(", "self", ",", "wheel_directory", ",", "config_settings", "=", "None", ",", "metadata_directory", "=", "None", ")", ":", "if", "metadata_directory", "is", "not", "None", ":", "metadata_directory", "=", "abspath", "(", "metadata_directory",...
cae8d76c210b9777e90aab76e9c4b0e53bb19cde
train
bninception
r"""BNInception model architecture from <https://arxiv.org/pdf/1502.03167.pdf>`_ paper.
pretrainedmodels/models/bninception.py
def bninception(num_classes=1000, pretrained='imagenet'): r"""BNInception model architecture from <https://arxiv.org/pdf/1502.03167.pdf>`_ paper. """ model = BNInception(num_classes=num_classes) if pretrained is not None: settings = pretrained_settings['bninception'][pretrained] assert num_classes == settings['num_classes'], \ "num_classes should be {}, but is {}".format(settings['num_classes'], num_classes) model.load_state_dict(model_zoo.load_url(settings['url'])) model.input_space = settings['input_space'] model.input_size = settings['input_size'] model.input_range = settings['input_range'] model.mean = settings['mean'] model.std = settings['std'] return model
def bninception(num_classes=1000, pretrained='imagenet'): r"""BNInception model architecture from <https://arxiv.org/pdf/1502.03167.pdf>`_ paper. """ model = BNInception(num_classes=num_classes) if pretrained is not None: settings = pretrained_settings['bninception'][pretrained] assert num_classes == settings['num_classes'], \ "num_classes should be {}, but is {}".format(settings['num_classes'], num_classes) model.load_state_dict(model_zoo.load_url(settings['url'])) model.input_space = settings['input_space'] model.input_size = settings['input_size'] model.input_range = settings['input_range'] model.mean = settings['mean'] model.std = settings['std'] return model
[ "r", "BNInception", "model", "architecture", "from", "<https", ":", "//", "arxiv", ".", "org", "/", "pdf", "/", "1502", ".", "03167", ".", "pdf", ">", "_", "paper", "." ]
Cadene/pretrained-models.pytorch
python
https://github.com/Cadene/pretrained-models.pytorch/blob/021d97897c9aa76ec759deff43d341c4fd45d7ba/pretrainedmodels/models/bninception.py#L497-L511
[ "def", "bninception", "(", "num_classes", "=", "1000", ",", "pretrained", "=", "'imagenet'", ")", ":", "model", "=", "BNInception", "(", "num_classes", "=", "num_classes", ")", "if", "pretrained", "is", "not", "None", ":", "settings", "=", "pretrained_settings...
021d97897c9aa76ec759deff43d341c4fd45d7ba
train
conv3x3
3x3 convolution with padding
pretrainedmodels/models/fbresnet/resnet152_load.py
def conv3x3(in_planes, out_planes, stride=1): "3x3 convolution with padding" return nn.Conv2d(in_planes, out_planes, kernel_size=3, stride=stride, padding=1, bias=True)
def conv3x3(in_planes, out_planes, stride=1): "3x3 convolution with padding" return nn.Conv2d(in_planes, out_planes, kernel_size=3, stride=stride, padding=1, bias=True)
[ "3x3", "convolution", "with", "padding" ]
Cadene/pretrained-models.pytorch
python
https://github.com/Cadene/pretrained-models.pytorch/blob/021d97897c9aa76ec759deff43d341c4fd45d7ba/pretrainedmodels/models/fbresnet/resnet152_load.py#L20-L23
[ "def", "conv3x3", "(", "in_planes", ",", "out_planes", ",", "stride", "=", "1", ")", ":", "return", "nn", ".", "Conv2d", "(", "in_planes", ",", "out_planes", ",", "kernel_size", "=", "3", ",", "stride", "=", "stride", ",", "padding", "=", "1", ",", "...
021d97897c9aa76ec759deff43d341c4fd45d7ba
train
resnet18
Constructs a ResNet-18 model. Args: pretrained (bool): If True, returns a model pre-trained on ImageNet
pretrainedmodels/models/fbresnet/resnet152_load.py
def resnet18(pretrained=False, **kwargs): """Constructs a ResNet-18 model. Args: pretrained (bool): If True, returns a model pre-trained on ImageNet """ model = ResNet(BasicBlock, [2, 2, 2, 2], **kwargs) if pretrained: model.load_state_dict(model_zoo.load_url(model_urls['resnet18'])) return model
def resnet18(pretrained=False, **kwargs): """Constructs a ResNet-18 model. Args: pretrained (bool): If True, returns a model pre-trained on ImageNet """ model = ResNet(BasicBlock, [2, 2, 2, 2], **kwargs) if pretrained: model.load_state_dict(model_zoo.load_url(model_urls['resnet18'])) return model
[ "Constructs", "a", "ResNet", "-", "18", "model", "." ]
Cadene/pretrained-models.pytorch
python
https://github.com/Cadene/pretrained-models.pytorch/blob/021d97897c9aa76ec759deff43d341c4fd45d7ba/pretrainedmodels/models/fbresnet/resnet152_load.py#L160-L169
[ "def", "resnet18", "(", "pretrained", "=", "False", ",", "*", "*", "kwargs", ")", ":", "model", "=", "ResNet", "(", "BasicBlock", ",", "[", "2", ",", "2", ",", "2", ",", "2", "]", ",", "*", "*", "kwargs", ")", "if", "pretrained", ":", "model", ...
021d97897c9aa76ec759deff43d341c4fd45d7ba
train
resnet50
Constructs a ResNet-50 model. Args: pretrained (bool): If True, returns a model pre-trained on ImageNet
pretrainedmodels/models/fbresnet/resnet152_load.py
def resnet50(pretrained=False, **kwargs): """Constructs a ResNet-50 model. Args: pretrained (bool): If True, returns a model pre-trained on ImageNet """ model = ResNet(Bottleneck, [3, 4, 6, 3], **kwargs) if pretrained: model.load_state_dict(model_zoo.load_url(model_urls['resnet50'])) return model
def resnet50(pretrained=False, **kwargs): """Constructs a ResNet-50 model. Args: pretrained (bool): If True, returns a model pre-trained on ImageNet """ model = ResNet(Bottleneck, [3, 4, 6, 3], **kwargs) if pretrained: model.load_state_dict(model_zoo.load_url(model_urls['resnet50'])) return model
[ "Constructs", "a", "ResNet", "-", "50", "model", "." ]
Cadene/pretrained-models.pytorch
python
https://github.com/Cadene/pretrained-models.pytorch/blob/021d97897c9aa76ec759deff43d341c4fd45d7ba/pretrainedmodels/models/fbresnet/resnet152_load.py#L184-L193
[ "def", "resnet50", "(", "pretrained", "=", "False", ",", "*", "*", "kwargs", ")", ":", "model", "=", "ResNet", "(", "Bottleneck", ",", "[", "3", ",", "4", ",", "6", ",", "3", "]", ",", "*", "*", "kwargs", ")", "if", "pretrained", ":", "model", ...
021d97897c9aa76ec759deff43d341c4fd45d7ba
train
nasnetamobile
r"""NASNetALarge model architecture from the `"NASNet" <https://arxiv.org/abs/1707.07012>`_ paper.
pretrainedmodels/models/nasnet_mobile.py
def nasnetamobile(num_classes=1000, pretrained='imagenet'): r"""NASNetALarge model architecture from the `"NASNet" <https://arxiv.org/abs/1707.07012>`_ paper. """ if pretrained: settings = pretrained_settings['nasnetamobile'][pretrained] assert num_classes == settings['num_classes'], \ "num_classes should be {}, but is {}".format(settings['num_classes'], num_classes) # both 'imagenet'&'imagenet+background' are loaded from same parameters model = NASNetAMobile(num_classes=num_classes) model.load_state_dict(model_zoo.load_url(settings['url'], map_location=None)) # if pretrained == 'imagenet': # new_last_linear = nn.Linear(model.last_linear.in_features, 1000) # new_last_linear.weight.data = model.last_linear.weight.data[1:] # new_last_linear.bias.data = model.last_linear.bias.data[1:] # model.last_linear = new_last_linear model.input_space = settings['input_space'] model.input_size = settings['input_size'] model.input_range = settings['input_range'] model.mean = settings['mean'] model.std = settings['std'] else: settings = pretrained_settings['nasnetamobile']['imagenet'] model = NASNetAMobile(num_classes=num_classes) model.input_space = settings['input_space'] model.input_size = settings['input_size'] model.input_range = settings['input_range'] model.mean = settings['mean'] model.std = settings['std'] return model
def nasnetamobile(num_classes=1000, pretrained='imagenet'): r"""NASNetALarge model architecture from the `"NASNet" <https://arxiv.org/abs/1707.07012>`_ paper. """ if pretrained: settings = pretrained_settings['nasnetamobile'][pretrained] assert num_classes == settings['num_classes'], \ "num_classes should be {}, but is {}".format(settings['num_classes'], num_classes) # both 'imagenet'&'imagenet+background' are loaded from same parameters model = NASNetAMobile(num_classes=num_classes) model.load_state_dict(model_zoo.load_url(settings['url'], map_location=None)) # if pretrained == 'imagenet': # new_last_linear = nn.Linear(model.last_linear.in_features, 1000) # new_last_linear.weight.data = model.last_linear.weight.data[1:] # new_last_linear.bias.data = model.last_linear.bias.data[1:] # model.last_linear = new_last_linear model.input_space = settings['input_space'] model.input_size = settings['input_size'] model.input_range = settings['input_range'] model.mean = settings['mean'] model.std = settings['std'] else: settings = pretrained_settings['nasnetamobile']['imagenet'] model = NASNetAMobile(num_classes=num_classes) model.input_space = settings['input_space'] model.input_size = settings['input_size'] model.input_range = settings['input_range'] model.mean = settings['mean'] model.std = settings['std'] return model
[ "r", "NASNetALarge", "model", "architecture", "from", "the", "NASNet", "<https", ":", "//", "arxiv", ".", "org", "/", "abs", "/", "1707", ".", "07012", ">", "_", "paper", "." ]
Cadene/pretrained-models.pytorch
python
https://github.com/Cadene/pretrained-models.pytorch/blob/021d97897c9aa76ec759deff43d341c4fd45d7ba/pretrainedmodels/models/nasnet_mobile.py#L618-L652
[ "def", "nasnetamobile", "(", "num_classes", "=", "1000", ",", "pretrained", "=", "'imagenet'", ")", ":", "if", "pretrained", ":", "settings", "=", "pretrained_settings", "[", "'nasnetamobile'", "]", "[", "pretrained", "]", "assert", "num_classes", "==", "setting...
021d97897c9aa76ec759deff43d341c4fd45d7ba
train
cafferesnet101
Constructs a ResNet-101 model. Args: pretrained (bool): If True, returns a model pre-trained on ImageNet
pretrainedmodels/models/cafferesnet.py
def cafferesnet101(num_classes=1000, pretrained='imagenet'): """Constructs a ResNet-101 model. Args: pretrained (bool): If True, returns a model pre-trained on ImageNet """ model = ResNet(Bottleneck, [3, 4, 23, 3], num_classes=num_classes) if pretrained is not None: settings = pretrained_settings['cafferesnet101'][pretrained] assert num_classes == settings['num_classes'], \ "num_classes should be {}, but is {}".format(settings['num_classes'], num_classes) model.load_state_dict(model_zoo.load_url(settings['url'])) model.input_space = settings['input_space'] model.input_size = settings['input_size'] model.input_range = settings['input_range'] model.mean = settings['mean'] model.std = settings['std'] return model
def cafferesnet101(num_classes=1000, pretrained='imagenet'): """Constructs a ResNet-101 model. Args: pretrained (bool): If True, returns a model pre-trained on ImageNet """ model = ResNet(Bottleneck, [3, 4, 23, 3], num_classes=num_classes) if pretrained is not None: settings = pretrained_settings['cafferesnet101'][pretrained] assert num_classes == settings['num_classes'], \ "num_classes should be {}, but is {}".format(settings['num_classes'], num_classes) model.load_state_dict(model_zoo.load_url(settings['url'])) model.input_space = settings['input_space'] model.input_size = settings['input_size'] model.input_range = settings['input_range'] model.mean = settings['mean'] model.std = settings['std'] return model
[ "Constructs", "a", "ResNet", "-", "101", "model", ".", "Args", ":", "pretrained", "(", "bool", ")", ":", "If", "True", "returns", "a", "model", "pre", "-", "trained", "on", "ImageNet" ]
Cadene/pretrained-models.pytorch
python
https://github.com/Cadene/pretrained-models.pytorch/blob/021d97897c9aa76ec759deff43d341c4fd45d7ba/pretrainedmodels/models/cafferesnet.py#L168-L184
[ "def", "cafferesnet101", "(", "num_classes", "=", "1000", ",", "pretrained", "=", "'imagenet'", ")", ":", "model", "=", "ResNet", "(", "Bottleneck", ",", "[", "3", ",", "4", ",", "23", ",", "3", "]", ",", "num_classes", "=", "num_classes", ")", "if", ...
021d97897c9aa76ec759deff43d341c4fd45d7ba
train
fbresnet152
Constructs a ResNet-152 model. Args: pretrained (bool): If True, returns a model pre-trained on ImageNet
pretrainedmodels/models/fbresnet.py
def fbresnet152(num_classes=1000, pretrained='imagenet'): """Constructs a ResNet-152 model. Args: pretrained (bool): If True, returns a model pre-trained on ImageNet """ model = FBResNet(Bottleneck, [3, 8, 36, 3], num_classes=num_classes) if pretrained is not None: settings = pretrained_settings['fbresnet152'][pretrained] assert num_classes == settings['num_classes'], \ "num_classes should be {}, but is {}".format(settings['num_classes'], num_classes) model.load_state_dict(model_zoo.load_url(settings['url'])) model.input_space = settings['input_space'] model.input_size = settings['input_size'] model.input_range = settings['input_range'] model.mean = settings['mean'] model.std = settings['std'] return model
def fbresnet152(num_classes=1000, pretrained='imagenet'): """Constructs a ResNet-152 model. Args: pretrained (bool): If True, returns a model pre-trained on ImageNet """ model = FBResNet(Bottleneck, [3, 8, 36, 3], num_classes=num_classes) if pretrained is not None: settings = pretrained_settings['fbresnet152'][pretrained] assert num_classes == settings['num_classes'], \ "num_classes should be {}, but is {}".format(settings['num_classes'], num_classes) model.load_state_dict(model_zoo.load_url(settings['url'])) model.input_space = settings['input_space'] model.input_size = settings['input_size'] model.input_range = settings['input_range'] model.mean = settings['mean'] model.std = settings['std'] return model
[ "Constructs", "a", "ResNet", "-", "152", "model", "." ]
Cadene/pretrained-models.pytorch
python
https://github.com/Cadene/pretrained-models.pytorch/blob/021d97897c9aa76ec759deff43d341c4fd45d7ba/pretrainedmodels/models/fbresnet.py#L216-L233
[ "def", "fbresnet152", "(", "num_classes", "=", "1000", ",", "pretrained", "=", "'imagenet'", ")", ":", "model", "=", "FBResNet", "(", "Bottleneck", ",", "[", "3", ",", "8", ",", "36", ",", "3", "]", ",", "num_classes", "=", "num_classes", ")", "if", ...
021d97897c9aa76ec759deff43d341c4fd45d7ba
train
alexnet
r"""AlexNet model architecture from the `"One weird trick..." <https://arxiv.org/abs/1404.5997>`_ paper.
pretrainedmodels/models/torchvision_models.py
def alexnet(num_classes=1000, pretrained='imagenet'): r"""AlexNet model architecture from the `"One weird trick..." <https://arxiv.org/abs/1404.5997>`_ paper. """ # https://github.com/pytorch/vision/blob/master/torchvision/models/alexnet.py model = models.alexnet(pretrained=False) if pretrained is not None: settings = pretrained_settings['alexnet'][pretrained] model = load_pretrained(model, num_classes, settings) model = modify_alexnet(model) return model
def alexnet(num_classes=1000, pretrained='imagenet'): r"""AlexNet model architecture from the `"One weird trick..." <https://arxiv.org/abs/1404.5997>`_ paper. """ # https://github.com/pytorch/vision/blob/master/torchvision/models/alexnet.py model = models.alexnet(pretrained=False) if pretrained is not None: settings = pretrained_settings['alexnet'][pretrained] model = load_pretrained(model, num_classes, settings) model = modify_alexnet(model) return model
[ "r", "AlexNet", "model", "architecture", "from", "the", "One", "weird", "trick", "...", "<https", ":", "//", "arxiv", ".", "org", "/", "abs", "/", "1404", ".", "5997", ">", "_", "paper", "." ]
Cadene/pretrained-models.pytorch
python
https://github.com/Cadene/pretrained-models.pytorch/blob/021d97897c9aa76ec759deff43d341c4fd45d7ba/pretrainedmodels/models/torchvision_models.py#L168-L178
[ "def", "alexnet", "(", "num_classes", "=", "1000", ",", "pretrained", "=", "'imagenet'", ")", ":", "# https://github.com/pytorch/vision/blob/master/torchvision/models/alexnet.py", "model", "=", "models", ".", "alexnet", "(", "pretrained", "=", "False", ")", "if", "pre...
021d97897c9aa76ec759deff43d341c4fd45d7ba