Search is not available for this dataset
identifier
stringlengths
1
155
parameters
stringlengths
2
6.09k
docstring
stringlengths
11
63.4k
docstring_summary
stringlengths
0
63.4k
function
stringlengths
29
99.8k
function_tokens
sequence
start_point
sequence
end_point
sequence
language
stringclasses
1 value
docstring_language
stringlengths
2
7
docstring_language_predictions
stringlengths
18
23
is_langid_reliable
stringclasses
2 values
parse_requirements
(strs)
Yield ``Requirement`` objects for each specification in `strs` `strs` must be a string, or a (possibly-nested) iterable thereof.
Yield ``Requirement`` objects for each specification in `strs`
def parse_requirements(strs): """Yield ``Requirement`` objects for each specification in `strs` `strs` must be a string, or a (possibly-nested) iterable thereof. """ # create a steppable iterator, so we can handle \-continuations lines = iter(yield_lines(strs)) for line in lines: # Drop comments -- a hash without a space may be in a URL. if ' #' in line: line = line[:line.find(' #')] # If there is a line continuation, drop it, and append the next line. if line.endswith('\\'): line = line[:-2].strip() try: line += next(lines) except StopIteration: return yield Requirement(line)
[ "def", "parse_requirements", "(", "strs", ")", ":", "# create a steppable iterator, so we can handle \\-continuations", "lines", "=", "iter", "(", "yield_lines", "(", "strs", ")", ")", "for", "line", "in", "lines", ":", "# Drop comments -- a hash without a space may be in a URL.", "if", "' #'", "in", "line", ":", "line", "=", "line", "[", ":", "line", ".", "find", "(", "' #'", ")", "]", "# If there is a line continuation, drop it, and append the next line.", "if", "line", ".", "endswith", "(", "'\\\\'", ")", ":", "line", "=", "line", "[", ":", "-", "2", "]", ".", "strip", "(", ")", "try", ":", "line", "+=", "next", "(", "lines", ")", "except", "StopIteration", ":", "return", "yield", "Requirement", "(", "line", ")" ]
[ 2915, 0 ]
[ 2934, 31 ]
python
en
['en', 'en', 'en']
True
_always_object
(classes)
Ensure object appears in the mro even for old-style classes.
Ensure object appears in the mro even for old-style classes.
def _always_object(classes): """ Ensure object appears in the mro even for old-style classes. """ if object not in classes: return classes + (object,) return classes
[ "def", "_always_object", "(", "classes", ")", ":", "if", "object", "not", "in", "classes", ":", "return", "classes", "+", "(", "object", ",", ")", "return", "classes" ]
[ 2991, 0 ]
[ 2998, 18 ]
python
en
['en', 'error', 'th']
False
_find_adapter
(registry, ob)
Return an adapter factory for `ob` from `registry`
Return an adapter factory for `ob` from `registry`
def _find_adapter(registry, ob): """Return an adapter factory for `ob` from `registry`""" types = _always_object(inspect.getmro(getattr(ob, '__class__', type(ob)))) for t in types: if t in registry: return registry[t]
[ "def", "_find_adapter", "(", "registry", ",", "ob", ")", ":", "types", "=", "_always_object", "(", "inspect", ".", "getmro", "(", "getattr", "(", "ob", ",", "'__class__'", ",", "type", "(", "ob", ")", ")", ")", ")", "for", "t", "in", "types", ":", "if", "t", "in", "registry", ":", "return", "registry", "[", "t", "]" ]
[ 3001, 0 ]
[ 3006, 30 ]
python
en
['en', 'en', 'en']
True
VersionConflict.with_context
(self, required_by)
If required_by is non-empty, return a version of self that is a ContextualVersionConflict.
If required_by is non-empty, return a version of self that is a ContextualVersionConflict.
def with_context(self, required_by): """ If required_by is non-empty, return a version of self that is a ContextualVersionConflict. """ if not required_by: return self args = self.args + (required_by,) return ContextualVersionConflict(*args)
[ "def", "with_context", "(", "self", ",", "required_by", ")", ":", "if", "not", "required_by", ":", "return", "self", "args", "=", "self", ".", "args", "+", "(", "required_by", ",", ")", "return", "ContextualVersionConflict", "(", "*", "args", ")" ]
[ 265, 4 ]
[ 273, 47 ]
python
en
['en', 'error', 'th']
False
IMetadataProvider.has_metadata
(name)
Does the package's distribution contain the named metadata?
Does the package's distribution contain the named metadata?
def has_metadata(name): """Does the package's distribution contain the named metadata?"""
[ "def", "has_metadata", "(", "name", ")", ":" ]
[ 493, 4 ]
[ 494, 73 ]
python
en
['en', 'en', 'en']
True
IMetadataProvider.get_metadata
(name)
The named metadata resource as a string
The named metadata resource as a string
def get_metadata(name): """The named metadata resource as a string"""
[ "def", "get_metadata", "(", "name", ")", ":" ]
[ 496, 4 ]
[ 497, 53 ]
python
en
['en', 'en', 'en']
True
IMetadataProvider.get_metadata_lines
(name)
Yield named metadata resource as list of non-blank non-comment lines Leading and trailing whitespace is stripped from each line, and lines with ``#`` as the first non-blank character are omitted.
Yield named metadata resource as list of non-blank non-comment lines
def get_metadata_lines(name): """Yield named metadata resource as list of non-blank non-comment lines Leading and trailing whitespace is stripped from each line, and lines with ``#`` as the first non-blank character are omitted."""
[ "def", "get_metadata_lines", "(", "name", ")", ":" ]
[ 499, 4 ]
[ 503, 66 ]
python
en
['en', 'en', 'en']
True
IMetadataProvider.metadata_isdir
(name)
Is the named metadata a directory? (like ``os.path.isdir()``)
Is the named metadata a directory? (like ``os.path.isdir()``)
def metadata_isdir(name): """Is the named metadata a directory? (like ``os.path.isdir()``)"""
[ "def", "metadata_isdir", "(", "name", ")", ":" ]
[ 505, 4 ]
[ 506, 76 ]
python
en
['en', 'en', 'en']
True
IMetadataProvider.metadata_listdir
(name)
List of metadata names in the directory (like ``os.listdir()``)
List of metadata names in the directory (like ``os.listdir()``)
def metadata_listdir(name): """List of metadata names in the directory (like ``os.listdir()``)"""
[ "def", "metadata_listdir", "(", "name", ")", ":" ]
[ 508, 4 ]
[ 509, 77 ]
python
en
['en', 'en', 'en']
True
IMetadataProvider.run_script
(script_name, namespace)
Execute the named script in the supplied namespace dictionary
Execute the named script in the supplied namespace dictionary
def run_script(script_name, namespace): """Execute the named script in the supplied namespace dictionary"""
[ "def", "run_script", "(", "script_name", ",", "namespace", ")", ":" ]
[ 511, 4 ]
[ 512, 75 ]
python
en
['en', 'en', 'en']
True
IResourceProvider.get_resource_filename
(manager, resource_name)
Return a true filesystem path for `resource_name` `manager` must be an ``IResourceManager``
Return a true filesystem path for `resource_name`
def get_resource_filename(manager, resource_name): """Return a true filesystem path for `resource_name` `manager` must be an ``IResourceManager``"""
[ "def", "get_resource_filename", "(", "manager", ",", "resource_name", ")", ":" ]
[ 518, 4 ]
[ 521, 52 ]
python
en
['en', 'en', 'en']
True
IResourceProvider.get_resource_stream
(manager, resource_name)
Return a readable file-like object for `resource_name` `manager` must be an ``IResourceManager``
Return a readable file-like object for `resource_name`
def get_resource_stream(manager, resource_name): """Return a readable file-like object for `resource_name` `manager` must be an ``IResourceManager``"""
[ "def", "get_resource_stream", "(", "manager", ",", "resource_name", ")", ":" ]
[ 523, 4 ]
[ 526, 52 ]
python
en
['en', 'en', 'en']
True
IResourceProvider.get_resource_string
(manager, resource_name)
Return a string containing the contents of `resource_name` `manager` must be an ``IResourceManager``
Return a string containing the contents of `resource_name`
def get_resource_string(manager, resource_name): """Return a string containing the contents of `resource_name` `manager` must be an ``IResourceManager``"""
[ "def", "get_resource_string", "(", "manager", ",", "resource_name", ")", ":" ]
[ 528, 4 ]
[ 531, 52 ]
python
en
['en', 'en', 'en']
True
IResourceProvider.has_resource
(resource_name)
Does the package contain the named resource?
Does the package contain the named resource?
def has_resource(resource_name): """Does the package contain the named resource?"""
[ "def", "has_resource", "(", "resource_name", ")", ":" ]
[ 533, 4 ]
[ 534, 58 ]
python
en
['en', 'en', 'en']
True
IResourceProvider.resource_isdir
(resource_name)
Is the named resource a directory? (like ``os.path.isdir()``)
Is the named resource a directory? (like ``os.path.isdir()``)
def resource_isdir(resource_name): """Is the named resource a directory? (like ``os.path.isdir()``)"""
[ "def", "resource_isdir", "(", "resource_name", ")", ":" ]
[ 536, 4 ]
[ 537, 76 ]
python
en
['en', 'en', 'en']
True
IResourceProvider.resource_listdir
(resource_name)
List of resource names in the directory (like ``os.listdir()``)
List of resource names in the directory (like ``os.listdir()``)
def resource_listdir(resource_name): """List of resource names in the directory (like ``os.listdir()``)"""
[ "def", "resource_listdir", "(", "resource_name", ")", ":" ]
[ 539, 4 ]
[ 540, 77 ]
python
en
['en', 'en', 'en']
True
WorkingSet.__init__
(self, entries=None)
Create working set from list of path entries (default=sys.path)
Create working set from list of path entries (default=sys.path)
def __init__(self, entries=None): """Create working set from list of path entries (default=sys.path)""" self.entries = [] self.entry_keys = {} self.by_key = {} self.callbacks = [] if entries is None: entries = sys.path for entry in entries: self.add_entry(entry)
[ "def", "__init__", "(", "self", ",", "entries", "=", "None", ")", ":", "self", ".", "entries", "=", "[", "]", "self", ".", "entry_keys", "=", "{", "}", "self", ".", "by_key", "=", "{", "}", "self", ".", "callbacks", "=", "[", "]", "if", "entries", "is", "None", ":", "entries", "=", "sys", ".", "path", "for", "entry", "in", "entries", ":", "self", ".", "add_entry", "(", "entry", ")" ]
[ 546, 4 ]
[ 557, 33 ]
python
en
['en', 'en', 'en']
True
WorkingSet._build_master
(cls)
Prepare the master working set.
Prepare the master working set.
def _build_master(cls): """ Prepare the master working set. """ ws = cls() try: from __main__ import __requires__ except ImportError: # The main program does not list any requirements return ws # ensure the requirements are met try: ws.require(__requires__) except VersionConflict: return cls._build_from_requirements(__requires__) return ws
[ "def", "_build_master", "(", "cls", ")", ":", "ws", "=", "cls", "(", ")", "try", ":", "from", "__main__", "import", "__requires__", "except", "ImportError", ":", "# The main program does not list any requirements", "return", "ws", "# ensure the requirements are met", "try", ":", "ws", ".", "require", "(", "__requires__", ")", "except", "VersionConflict", ":", "return", "cls", ".", "_build_from_requirements", "(", "__requires__", ")", "return", "ws" ]
[ 560, 4 ]
[ 577, 17 ]
python
en
['en', 'error', 'th']
False
WorkingSet._build_from_requirements
(cls, req_spec)
Build a working set from a requirement spec. Rewrites sys.path.
Build a working set from a requirement spec. Rewrites sys.path.
def _build_from_requirements(cls, req_spec): """ Build a working set from a requirement spec. Rewrites sys.path. """ # try it without defaults already on sys.path # by starting with an empty path ws = cls([]) reqs = parse_requirements(req_spec) dists = ws.resolve(reqs, Environment()) for dist in dists: ws.add(dist) # add any missing entries from sys.path for entry in sys.path: if entry not in ws.entries: ws.add_entry(entry) # then copy back to sys.path sys.path[:] = ws.entries return ws
[ "def", "_build_from_requirements", "(", "cls", ",", "req_spec", ")", ":", "# try it without defaults already on sys.path", "# by starting with an empty path", "ws", "=", "cls", "(", "[", "]", ")", "reqs", "=", "parse_requirements", "(", "req_spec", ")", "dists", "=", "ws", ".", "resolve", "(", "reqs", ",", "Environment", "(", ")", ")", "for", "dist", "in", "dists", ":", "ws", ".", "add", "(", "dist", ")", "# add any missing entries from sys.path", "for", "entry", "in", "sys", ".", "path", ":", "if", "entry", "not", "in", "ws", ".", "entries", ":", "ws", ".", "add_entry", "(", "entry", ")", "# then copy back to sys.path", "sys", ".", "path", "[", ":", "]", "=", "ws", ".", "entries", "return", "ws" ]
[ 580, 4 ]
[ 599, 17 ]
python
en
['en', 'error', 'th']
False
WorkingSet.add_entry
(self, entry)
Add a path item to ``.entries``, finding any distributions on it ``find_distributions(entry, True)`` is used to find distributions corresponding to the path entry, and they are added. `entry` is always appended to ``.entries``, even if it is already present. (This is because ``sys.path`` can contain the same value more than once, and the ``.entries`` of the ``sys.path`` WorkingSet should always equal ``sys.path``.)
Add a path item to ``.entries``, finding any distributions on it
def add_entry(self, entry): """Add a path item to ``.entries``, finding any distributions on it ``find_distributions(entry, True)`` is used to find distributions corresponding to the path entry, and they are added. `entry` is always appended to ``.entries``, even if it is already present. (This is because ``sys.path`` can contain the same value more than once, and the ``.entries`` of the ``sys.path`` WorkingSet should always equal ``sys.path``.) """ self.entry_keys.setdefault(entry, []) self.entries.append(entry) for dist in find_distributions(entry, True): self.add(dist, entry, False)
[ "def", "add_entry", "(", "self", ",", "entry", ")", ":", "self", ".", "entry_keys", ".", "setdefault", "(", "entry", ",", "[", "]", ")", "self", ".", "entries", ".", "append", "(", "entry", ")", "for", "dist", "in", "find_distributions", "(", "entry", ",", "True", ")", ":", "self", ".", "add", "(", "dist", ",", "entry", ",", "False", ")" ]
[ 601, 4 ]
[ 614, 40 ]
python
en
['en', 'en', 'en']
True
WorkingSet.__contains__
(self, dist)
True if `dist` is the active distribution for its project
True if `dist` is the active distribution for its project
def __contains__(self, dist): """True if `dist` is the active distribution for its project""" return self.by_key.get(dist.key) == dist
[ "def", "__contains__", "(", "self", ",", "dist", ")", ":", "return", "self", ".", "by_key", ".", "get", "(", "dist", ".", "key", ")", "==", "dist" ]
[ 616, 4 ]
[ 618, 48 ]
python
en
['en', 'en', 'en']
True
WorkingSet.find
(self, req)
Find a distribution matching requirement `req` If there is an active distribution for the requested project, this returns it as long as it meets the version requirement specified by `req`. But, if there is an active distribution for the project and it does *not* meet the `req` requirement, ``VersionConflict`` is raised. If there is no active distribution for the requested project, ``None`` is returned.
Find a distribution matching requirement `req`
def find(self, req): """Find a distribution matching requirement `req` If there is an active distribution for the requested project, this returns it as long as it meets the version requirement specified by `req`. But, if there is an active distribution for the project and it does *not* meet the `req` requirement, ``VersionConflict`` is raised. If there is no active distribution for the requested project, ``None`` is returned. """ dist = self.by_key.get(req.key) if dist is not None and dist not in req: # XXX add more info raise VersionConflict(dist, req) return dist
[ "def", "find", "(", "self", ",", "req", ")", ":", "dist", "=", "self", ".", "by_key", ".", "get", "(", "req", ".", "key", ")", "if", "dist", "is", "not", "None", "and", "dist", "not", "in", "req", ":", "# XXX add more info", "raise", "VersionConflict", "(", "dist", ",", "req", ")", "return", "dist" ]
[ 620, 4 ]
[ 634, 19 ]
python
en
['en', 'en', 'en']
True
WorkingSet.iter_entry_points
(self, group, name=None)
Yield entry point objects from `group` matching `name` If `name` is None, yields all entry points in `group` from all distributions in the working set, otherwise only ones matching both `group` and `name` are yielded (in distribution order).
Yield entry point objects from `group` matching `name`
def iter_entry_points(self, group, name=None): """Yield entry point objects from `group` matching `name` If `name` is None, yields all entry points in `group` from all distributions in the working set, otherwise only ones matching both `group` and `name` are yielded (in distribution order). """ for dist in self: entries = dist.get_entry_map(group) if name is None: for ep in entries.values(): yield ep elif name in entries: yield entries[name]
[ "def", "iter_entry_points", "(", "self", ",", "group", ",", "name", "=", "None", ")", ":", "for", "dist", "in", "self", ":", "entries", "=", "dist", ".", "get_entry_map", "(", "group", ")", "if", "name", "is", "None", ":", "for", "ep", "in", "entries", ".", "values", "(", ")", ":", "yield", "ep", "elif", "name", "in", "entries", ":", "yield", "entries", "[", "name", "]" ]
[ 636, 4 ]
[ 649, 35 ]
python
en
['en', 'en', 'en']
True
WorkingSet.run_script
(self, requires, script_name)
Locate distribution for `requires` and run `script_name` script
Locate distribution for `requires` and run `script_name` script
def run_script(self, requires, script_name): """Locate distribution for `requires` and run `script_name` script""" ns = sys._getframe(1).f_globals name = ns['__name__'] ns.clear() ns['__name__'] = name self.require(requires)[0].run_script(script_name, ns)
[ "def", "run_script", "(", "self", ",", "requires", ",", "script_name", ")", ":", "ns", "=", "sys", ".", "_getframe", "(", "1", ")", ".", "f_globals", "name", "=", "ns", "[", "'__name__'", "]", "ns", ".", "clear", "(", ")", "ns", "[", "'__name__'", "]", "=", "name", "self", ".", "require", "(", "requires", ")", "[", "0", "]", ".", "run_script", "(", "script_name", ",", "ns", ")" ]
[ 651, 4 ]
[ 657, 61 ]
python
en
['en', 'en', 'en']
True
WorkingSet.__iter__
(self)
Yield distributions for non-duplicate projects in the working set The yield order is the order in which the items' path entries were added to the working set.
Yield distributions for non-duplicate projects in the working set
def __iter__(self): """Yield distributions for non-duplicate projects in the working set The yield order is the order in which the items' path entries were added to the working set. """ seen = {} for item in self.entries: if item not in self.entry_keys: # workaround a cache issue continue for key in self.entry_keys[item]: if key not in seen: seen[key] = 1 yield self.by_key[key]
[ "def", "__iter__", "(", "self", ")", ":", "seen", "=", "{", "}", "for", "item", "in", "self", ".", "entries", ":", "if", "item", "not", "in", "self", ".", "entry_keys", ":", "# workaround a cache issue", "continue", "for", "key", "in", "self", ".", "entry_keys", "[", "item", "]", ":", "if", "key", "not", "in", "seen", ":", "seen", "[", "key", "]", "=", "1", "yield", "self", ".", "by_key", "[", "key", "]" ]
[ 659, 4 ]
[ 674, 42 ]
python
en
['en', 'en', 'en']
True
WorkingSet.add
(self, dist, entry=None, insert=True, replace=False)
Add `dist` to working set, associated with `entry` If `entry` is unspecified, it defaults to the ``.location`` of `dist`. On exit from this routine, `entry` is added to the end of the working set's ``.entries`` (if it wasn't already present). `dist` is only added to the working set if it's for a project that doesn't already have a distribution in the set, unless `replace=True`. If it's added, any callbacks registered with the ``subscribe()`` method will be called.
Add `dist` to working set, associated with `entry`
def add(self, dist, entry=None, insert=True, replace=False): """Add `dist` to working set, associated with `entry` If `entry` is unspecified, it defaults to the ``.location`` of `dist`. On exit from this routine, `entry` is added to the end of the working set's ``.entries`` (if it wasn't already present). `dist` is only added to the working set if it's for a project that doesn't already have a distribution in the set, unless `replace=True`. If it's added, any callbacks registered with the ``subscribe()`` method will be called. """ if insert: dist.insert_on(self.entries, entry, replace=replace) if entry is None: entry = dist.location keys = self.entry_keys.setdefault(entry, []) keys2 = self.entry_keys.setdefault(dist.location, []) if not replace and dist.key in self.by_key: # ignore hidden distros return self.by_key[dist.key] = dist if dist.key not in keys: keys.append(dist.key) if dist.key not in keys2: keys2.append(dist.key) self._added_new(dist)
[ "def", "add", "(", "self", ",", "dist", ",", "entry", "=", "None", ",", "insert", "=", "True", ",", "replace", "=", "False", ")", ":", "if", "insert", ":", "dist", ".", "insert_on", "(", "self", ".", "entries", ",", "entry", ",", "replace", "=", "replace", ")", "if", "entry", "is", "None", ":", "entry", "=", "dist", ".", "location", "keys", "=", "self", ".", "entry_keys", ".", "setdefault", "(", "entry", ",", "[", "]", ")", "keys2", "=", "self", ".", "entry_keys", ".", "setdefault", "(", "dist", ".", "location", ",", "[", "]", ")", "if", "not", "replace", "and", "dist", ".", "key", "in", "self", ".", "by_key", ":", "# ignore hidden distros", "return", "self", ".", "by_key", "[", "dist", ".", "key", "]", "=", "dist", "if", "dist", ".", "key", "not", "in", "keys", ":", "keys", ".", "append", "(", "dist", ".", "key", ")", "if", "dist", ".", "key", "not", "in", "keys2", ":", "keys2", ".", "append", "(", "dist", ".", "key", ")", "self", ".", "_added_new", "(", "dist", ")" ]
[ 676, 4 ]
[ 704, 29 ]
python
en
['en', 'en', 'en']
True
WorkingSet.resolve
(self, requirements, env=None, installer=None, replace_conflicting=False, extras=None)
List all distributions needed to (recursively) meet `requirements` `requirements` must be a sequence of ``Requirement`` objects. `env`, if supplied, should be an ``Environment`` instance. If not supplied, it defaults to all distributions available within any entry or distribution in the working set. `installer`, if supplied, will be invoked with each requirement that cannot be met by an already-installed distribution; it should return a ``Distribution`` or ``None``. Unless `replace_conflicting=True`, raises a VersionConflict exception if any requirements are found on the path that have the correct name but the wrong version. Otherwise, if an `installer` is supplied it will be invoked to obtain the correct version of the requirement and activate it. `extras` is a list of the extras to be used with these requirements. This is important because extra requirements may look like `my_req; extra = "my_extra"`, which would otherwise be interpreted as a purely optional requirement. Instead, we want to be able to assert that these requirements are truly required.
List all distributions needed to (recursively) meet `requirements`
def resolve(self, requirements, env=None, installer=None, replace_conflicting=False, extras=None): """List all distributions needed to (recursively) meet `requirements` `requirements` must be a sequence of ``Requirement`` objects. `env`, if supplied, should be an ``Environment`` instance. If not supplied, it defaults to all distributions available within any entry or distribution in the working set. `installer`, if supplied, will be invoked with each requirement that cannot be met by an already-installed distribution; it should return a ``Distribution`` or ``None``. Unless `replace_conflicting=True`, raises a VersionConflict exception if any requirements are found on the path that have the correct name but the wrong version. Otherwise, if an `installer` is supplied it will be invoked to obtain the correct version of the requirement and activate it. `extras` is a list of the extras to be used with these requirements. This is important because extra requirements may look like `my_req; extra = "my_extra"`, which would otherwise be interpreted as a purely optional requirement. Instead, we want to be able to assert that these requirements are truly required. """ # set up the stack requirements = list(requirements)[::-1] # set of processed requirements processed = {} # key -> dist best = {} to_activate = [] req_extras = _ReqExtras() # Mapping of requirement to set of distributions that required it; # useful for reporting info about conflicts. required_by = collections.defaultdict(set) while requirements: # process dependencies breadth-first req = requirements.pop(0) if req in processed: # Ignore cyclic or redundant dependencies continue if not req_extras.markers_pass(req, extras): continue dist = best.get(req.key) if dist is None: # Find the best distribution and add it to the map dist = self.by_key.get(req.key) if dist is None or (dist not in req and replace_conflicting): ws = self if env is None: if dist is None: env = Environment(self.entries) else: # Use an empty environment and workingset to avoid # any further conflicts with the conflicting # distribution env = Environment([]) ws = WorkingSet([]) dist = best[req.key] = env.best_match( req, ws, installer, replace_conflicting=replace_conflicting ) if dist is None: requirers = required_by.get(req, None) raise DistributionNotFound(req, requirers) to_activate.append(dist) if dist not in req: # Oops, the "best" so far conflicts with a dependency dependent_req = required_by[req] raise VersionConflict(dist, req).with_context(dependent_req) # push the new requirements onto the stack new_requirements = dist.requires(req.extras)[::-1] requirements.extend(new_requirements) # Register the new requirements needed by req for new_requirement in new_requirements: required_by[new_requirement].add(req.project_name) req_extras[new_requirement] = req.extras processed[req] = True # return list of distros to activate return to_activate
[ "def", "resolve", "(", "self", ",", "requirements", ",", "env", "=", "None", ",", "installer", "=", "None", ",", "replace_conflicting", "=", "False", ",", "extras", "=", "None", ")", ":", "# set up the stack", "requirements", "=", "list", "(", "requirements", ")", "[", ":", ":", "-", "1", "]", "# set of processed requirements", "processed", "=", "{", "}", "# key -> dist", "best", "=", "{", "}", "to_activate", "=", "[", "]", "req_extras", "=", "_ReqExtras", "(", ")", "# Mapping of requirement to set of distributions that required it;", "# useful for reporting info about conflicts.", "required_by", "=", "collections", ".", "defaultdict", "(", "set", ")", "while", "requirements", ":", "# process dependencies breadth-first", "req", "=", "requirements", ".", "pop", "(", "0", ")", "if", "req", "in", "processed", ":", "# Ignore cyclic or redundant dependencies", "continue", "if", "not", "req_extras", ".", "markers_pass", "(", "req", ",", "extras", ")", ":", "continue", "dist", "=", "best", ".", "get", "(", "req", ".", "key", ")", "if", "dist", "is", "None", ":", "# Find the best distribution and add it to the map", "dist", "=", "self", ".", "by_key", ".", "get", "(", "req", ".", "key", ")", "if", "dist", "is", "None", "or", "(", "dist", "not", "in", "req", "and", "replace_conflicting", ")", ":", "ws", "=", "self", "if", "env", "is", "None", ":", "if", "dist", "is", "None", ":", "env", "=", "Environment", "(", "self", ".", "entries", ")", "else", ":", "# Use an empty environment and workingset to avoid", "# any further conflicts with the conflicting", "# distribution", "env", "=", "Environment", "(", "[", "]", ")", "ws", "=", "WorkingSet", "(", "[", "]", ")", "dist", "=", "best", "[", "req", ".", "key", "]", "=", "env", ".", "best_match", "(", "req", ",", "ws", ",", "installer", ",", "replace_conflicting", "=", "replace_conflicting", ")", "if", "dist", "is", "None", ":", "requirers", "=", "required_by", ".", "get", "(", "req", ",", "None", ")", "raise", "DistributionNotFound", "(", "req", ",", "requirers", ")", "to_activate", ".", "append", "(", "dist", ")", "if", "dist", "not", "in", "req", ":", "# Oops, the \"best\" so far conflicts with a dependency", "dependent_req", "=", "required_by", "[", "req", "]", "raise", "VersionConflict", "(", "dist", ",", "req", ")", ".", "with_context", "(", "dependent_req", ")", "# push the new requirements onto the stack", "new_requirements", "=", "dist", ".", "requires", "(", "req", ".", "extras", ")", "[", ":", ":", "-", "1", "]", "requirements", ".", "extend", "(", "new_requirements", ")", "# Register the new requirements needed by req", "for", "new_requirement", "in", "new_requirements", ":", "required_by", "[", "new_requirement", "]", ".", "add", "(", "req", ".", "project_name", ")", "req_extras", "[", "new_requirement", "]", "=", "req", ".", "extras", "processed", "[", "req", "]", "=", "True", "# return list of distros to activate", "return", "to_activate" ]
[ 706, 4 ]
[ 796, 26 ]
python
en
['en', 'en', 'en']
True
WorkingSet.find_plugins
( self, plugin_env, full_env=None, installer=None, fallback=True)
Find all activatable distributions in `plugin_env` Example usage:: distributions, errors = working_set.find_plugins( Environment(plugin_dirlist) ) # add plugins+libs to sys.path map(working_set.add, distributions) # display errors print('Could not load', errors) The `plugin_env` should be an ``Environment`` instance that contains only distributions that are in the project's "plugin directory" or directories. The `full_env`, if supplied, should be an ``Environment`` contains all currently-available distributions. If `full_env` is not supplied, one is created automatically from the ``WorkingSet`` this method is called on, which will typically mean that every directory on ``sys.path`` will be scanned for distributions. `installer` is a standard installer callback as used by the ``resolve()`` method. The `fallback` flag indicates whether we should attempt to resolve older versions of a plugin if the newest version cannot be resolved. This method returns a 2-tuple: (`distributions`, `error_info`), where `distributions` is a list of the distributions found in `plugin_env` that were loadable, along with any other distributions that are needed to resolve their dependencies. `error_info` is a dictionary mapping unloadable plugin distributions to an exception instance describing the error that occurred. Usually this will be a ``DistributionNotFound`` or ``VersionConflict`` instance.
Find all activatable distributions in `plugin_env`
def find_plugins( self, plugin_env, full_env=None, installer=None, fallback=True): """Find all activatable distributions in `plugin_env` Example usage:: distributions, errors = working_set.find_plugins( Environment(plugin_dirlist) ) # add plugins+libs to sys.path map(working_set.add, distributions) # display errors print('Could not load', errors) The `plugin_env` should be an ``Environment`` instance that contains only distributions that are in the project's "plugin directory" or directories. The `full_env`, if supplied, should be an ``Environment`` contains all currently-available distributions. If `full_env` is not supplied, one is created automatically from the ``WorkingSet`` this method is called on, which will typically mean that every directory on ``sys.path`` will be scanned for distributions. `installer` is a standard installer callback as used by the ``resolve()`` method. The `fallback` flag indicates whether we should attempt to resolve older versions of a plugin if the newest version cannot be resolved. This method returns a 2-tuple: (`distributions`, `error_info`), where `distributions` is a list of the distributions found in `plugin_env` that were loadable, along with any other distributions that are needed to resolve their dependencies. `error_info` is a dictionary mapping unloadable plugin distributions to an exception instance describing the error that occurred. Usually this will be a ``DistributionNotFound`` or ``VersionConflict`` instance. """ plugin_projects = list(plugin_env) # scan project names in alphabetic order plugin_projects.sort() error_info = {} distributions = {} if full_env is None: env = Environment(self.entries) env += plugin_env else: env = full_env + plugin_env shadow_set = self.__class__([]) # put all our entries in shadow_set list(map(shadow_set.add, self)) for project_name in plugin_projects: for dist in plugin_env[project_name]: req = [dist.as_requirement()] try: resolvees = shadow_set.resolve(req, env, installer) except ResolutionError as v: # save error info error_info[dist] = v if fallback: # try the next older version of project continue else: # give up on this project, keep going break else: list(map(shadow_set.add, resolvees)) distributions.update(dict.fromkeys(resolvees)) # success, no need to try any more versions of this project break distributions = list(distributions) distributions.sort() return distributions, error_info
[ "def", "find_plugins", "(", "self", ",", "plugin_env", ",", "full_env", "=", "None", ",", "installer", "=", "None", ",", "fallback", "=", "True", ")", ":", "plugin_projects", "=", "list", "(", "plugin_env", ")", "# scan project names in alphabetic order", "plugin_projects", ".", "sort", "(", ")", "error_info", "=", "{", "}", "distributions", "=", "{", "}", "if", "full_env", "is", "None", ":", "env", "=", "Environment", "(", "self", ".", "entries", ")", "env", "+=", "plugin_env", "else", ":", "env", "=", "full_env", "+", "plugin_env", "shadow_set", "=", "self", ".", "__class__", "(", "[", "]", ")", "# put all our entries in shadow_set", "list", "(", "map", "(", "shadow_set", ".", "add", ",", "self", ")", ")", "for", "project_name", "in", "plugin_projects", ":", "for", "dist", "in", "plugin_env", "[", "project_name", "]", ":", "req", "=", "[", "dist", ".", "as_requirement", "(", ")", "]", "try", ":", "resolvees", "=", "shadow_set", ".", "resolve", "(", "req", ",", "env", ",", "installer", ")", "except", "ResolutionError", "as", "v", ":", "# save error info", "error_info", "[", "dist", "]", "=", "v", "if", "fallback", ":", "# try the next older version of project", "continue", "else", ":", "# give up on this project, keep going", "break", "else", ":", "list", "(", "map", "(", "shadow_set", ".", "add", ",", "resolvees", ")", ")", "distributions", ".", "update", "(", "dict", ".", "fromkeys", "(", "resolvees", ")", ")", "# success, no need to try any more versions of this project", "break", "distributions", "=", "list", "(", "distributions", ")", "distributions", ".", "sort", "(", ")", "return", "distributions", ",", "error_info" ]
[ 798, 4 ]
[ 880, 40 ]
python
en
['en', 'en', 'en']
True
WorkingSet.require
(self, *requirements)
Ensure that distributions matching `requirements` are activated `requirements` must be a string or a (possibly-nested) sequence thereof, specifying the distributions and versions required. The return value is a sequence of the distributions that needed to be activated to fulfill the requirements; all relevant distributions are included, even if they were already activated in this working set.
Ensure that distributions matching `requirements` are activated
def require(self, *requirements): """Ensure that distributions matching `requirements` are activated `requirements` must be a string or a (possibly-nested) sequence thereof, specifying the distributions and versions required. The return value is a sequence of the distributions that needed to be activated to fulfill the requirements; all relevant distributions are included, even if they were already activated in this working set. """ needed = self.resolve(parse_requirements(requirements)) for dist in needed: self.add(dist) return needed
[ "def", "require", "(", "self", ",", "*", "requirements", ")", ":", "needed", "=", "self", ".", "resolve", "(", "parse_requirements", "(", "requirements", ")", ")", "for", "dist", "in", "needed", ":", "self", ".", "add", "(", "dist", ")", "return", "needed" ]
[ 882, 4 ]
[ 896, 21 ]
python
en
['en', 'en', 'en']
True
WorkingSet.subscribe
(self, callback, existing=True)
Invoke `callback` for all distributions If `existing=True` (default), call on all existing ones, as well.
Invoke `callback` for all distributions
def subscribe(self, callback, existing=True): """Invoke `callback` for all distributions If `existing=True` (default), call on all existing ones, as well. """ if callback in self.callbacks: return self.callbacks.append(callback) if not existing: return for dist in self: callback(dist)
[ "def", "subscribe", "(", "self", ",", "callback", ",", "existing", "=", "True", ")", ":", "if", "callback", "in", "self", ".", "callbacks", ":", "return", "self", ".", "callbacks", ".", "append", "(", "callback", ")", "if", "not", "existing", ":", "return", "for", "dist", "in", "self", ":", "callback", "(", "dist", ")" ]
[ 898, 4 ]
[ 910, 26 ]
python
en
['en', 'no', 'en']
True
_ReqExtras.markers_pass
(self, req, extras=None)
Evaluate markers for req against each extra that demanded it. Return False if the req has a marker and fails evaluation. Otherwise, return True.
Evaluate markers for req against each extra that demanded it.
def markers_pass(self, req, extras=None): """ Evaluate markers for req against each extra that demanded it. Return False if the req has a marker and fails evaluation. Otherwise, return True. """ extra_evals = ( req.marker.evaluate({'extra': extra}) for extra in self.get(req, ()) + (extras or (None,)) ) return not req.marker or any(extra_evals)
[ "def", "markers_pass", "(", "self", ",", "req", ",", "extras", "=", "None", ")", ":", "extra_evals", "=", "(", "req", ".", "marker", ".", "evaluate", "(", "{", "'extra'", ":", "extra", "}", ")", "for", "extra", "in", "self", ".", "get", "(", "req", ",", "(", ")", ")", "+", "(", "extras", "or", "(", "None", ",", ")", ")", ")", "return", "not", "req", ".", "marker", "or", "any", "(", "extra_evals", ")" ]
[ 935, 4 ]
[ 947, 49 ]
python
en
['en', 'error', 'th']
False
Environment.__init__
( self, search_path=None, platform=get_supported_platform(), python=PY_MAJOR)
Snapshot distributions available on a search path Any distributions found on `search_path` are added to the environment. `search_path` should be a sequence of ``sys.path`` items. If not supplied, ``sys.path`` is used. `platform` is an optional string specifying the name of the platform that platform-specific distributions must be compatible with. If unspecified, it defaults to the current platform. `python` is an optional string naming the desired version of Python (e.g. ``'3.3'``); it defaults to the current version. You may explicitly set `platform` (and/or `python`) to ``None`` if you wish to map *all* distributions, not just those compatible with the running platform or Python version.
Snapshot distributions available on a search path
def __init__( self, search_path=None, platform=get_supported_platform(), python=PY_MAJOR): """Snapshot distributions available on a search path Any distributions found on `search_path` are added to the environment. `search_path` should be a sequence of ``sys.path`` items. If not supplied, ``sys.path`` is used. `platform` is an optional string specifying the name of the platform that platform-specific distributions must be compatible with. If unspecified, it defaults to the current platform. `python` is an optional string naming the desired version of Python (e.g. ``'3.3'``); it defaults to the current version. You may explicitly set `platform` (and/or `python`) to ``None`` if you wish to map *all* distributions, not just those compatible with the running platform or Python version. """ self._distmap = {} self.platform = platform self.python = python self.scan(search_path)
[ "def", "__init__", "(", "self", ",", "search_path", "=", "None", ",", "platform", "=", "get_supported_platform", "(", ")", ",", "python", "=", "PY_MAJOR", ")", ":", "self", ".", "_distmap", "=", "{", "}", "self", ".", "platform", "=", "platform", "self", ".", "python", "=", "python", "self", ".", "scan", "(", "search_path", ")" ]
[ 953, 4 ]
[ 975, 30 ]
python
en
['en', 'en', 'en']
True
Environment.can_add
(self, dist)
Is distribution `dist` acceptable for this environment? The distribution must match the platform and python version requirements specified when this environment was created, or False is returned.
Is distribution `dist` acceptable for this environment?
def can_add(self, dist): """Is distribution `dist` acceptable for this environment? The distribution must match the platform and python version requirements specified when this environment was created, or False is returned. """ py_compat = ( self.python is None or dist.py_version is None or dist.py_version == self.python ) return py_compat and compatible_platforms(dist.platform, self.platform)
[ "def", "can_add", "(", "self", ",", "dist", ")", ":", "py_compat", "=", "(", "self", ".", "python", "is", "None", "or", "dist", ".", "py_version", "is", "None", "or", "dist", ".", "py_version", "==", "self", ".", "python", ")", "return", "py_compat", "and", "compatible_platforms", "(", "dist", ".", "platform", ",", "self", ".", "platform", ")" ]
[ 977, 4 ]
[ 989, 79 ]
python
en
['en', 'en', 'en']
True
Environment.remove
(self, dist)
Remove `dist` from the environment
Remove `dist` from the environment
def remove(self, dist): """Remove `dist` from the environment""" self._distmap[dist.key].remove(dist)
[ "def", "remove", "(", "self", ",", "dist", ")", ":", "self", ".", "_distmap", "[", "dist", ".", "key", "]", ".", "remove", "(", "dist", ")" ]
[ 991, 4 ]
[ 993, 44 ]
python
en
['en', 'en', 'en']
True
Environment.scan
(self, search_path=None)
Scan `search_path` for distributions usable in this environment Any distributions found are added to the environment. `search_path` should be a sequence of ``sys.path`` items. If not supplied, ``sys.path`` is used. Only distributions conforming to the platform/python version defined at initialization are added.
Scan `search_path` for distributions usable in this environment
def scan(self, search_path=None): """Scan `search_path` for distributions usable in this environment Any distributions found are added to the environment. `search_path` should be a sequence of ``sys.path`` items. If not supplied, ``sys.path`` is used. Only distributions conforming to the platform/python version defined at initialization are added. """ if search_path is None: search_path = sys.path for item in search_path: for dist in find_distributions(item): self.add(dist)
[ "def", "scan", "(", "self", ",", "search_path", "=", "None", ")", ":", "if", "search_path", "is", "None", ":", "search_path", "=", "sys", ".", "path", "for", "item", "in", "search_path", ":", "for", "dist", "in", "find_distributions", "(", "item", ")", ":", "self", ".", "add", "(", "dist", ")" ]
[ 995, 4 ]
[ 1008, 30 ]
python
en
['en', 'en', 'en']
True
Environment.__getitem__
(self, project_name)
Return a newest-to-oldest list of distributions for `project_name` Uses case-insensitive `project_name` comparison, assuming all the project's distributions use their project's name converted to all lowercase as their key.
Return a newest-to-oldest list of distributions for `project_name`
def __getitem__(self, project_name): """Return a newest-to-oldest list of distributions for `project_name` Uses case-insensitive `project_name` comparison, assuming all the project's distributions use their project's name converted to all lowercase as their key. """ distribution_key = project_name.lower() return self._distmap.get(distribution_key, [])
[ "def", "__getitem__", "(", "self", ",", "project_name", ")", ":", "distribution_key", "=", "project_name", ".", "lower", "(", ")", "return", "self", ".", "_distmap", ".", "get", "(", "distribution_key", ",", "[", "]", ")" ]
[ 1010, 4 ]
[ 1019, 54 ]
python
en
['en', 'en', 'en']
True
Environment.add
(self, dist)
Add `dist` if we ``can_add()`` it and it has not already been added
Add `dist` if we ``can_add()`` it and it has not already been added
def add(self, dist): """Add `dist` if we ``can_add()`` it and it has not already been added """ if self.can_add(dist) and dist.has_version(): dists = self._distmap.setdefault(dist.key, []) if dist not in dists: dists.append(dist) dists.sort(key=operator.attrgetter('hashcmp'), reverse=True)
[ "def", "add", "(", "self", ",", "dist", ")", ":", "if", "self", ".", "can_add", "(", "dist", ")", "and", "dist", ".", "has_version", "(", ")", ":", "dists", "=", "self", ".", "_distmap", ".", "setdefault", "(", "dist", ".", "key", ",", "[", "]", ")", "if", "dist", "not", "in", "dists", ":", "dists", ".", "append", "(", "dist", ")", "dists", ".", "sort", "(", "key", "=", "operator", ".", "attrgetter", "(", "'hashcmp'", ")", ",", "reverse", "=", "True", ")" ]
[ 1021, 4 ]
[ 1028, 76 ]
python
en
['en', 'en', 'en']
True
Environment.best_match
( self, req, working_set, installer=None, replace_conflicting=False)
Find distribution best matching `req` and usable on `working_set` This calls the ``find(req)`` method of the `working_set` to see if a suitable distribution is already active. (This may raise ``VersionConflict`` if an unsuitable version of the project is already active in the specified `working_set`.) If a suitable distribution isn't active, this method returns the newest distribution in the environment that meets the ``Requirement`` in `req`. If no suitable distribution is found, and `installer` is supplied, then the result of calling the environment's ``obtain(req, installer)`` method will be returned.
Find distribution best matching `req` and usable on `working_set`
def best_match( self, req, working_set, installer=None, replace_conflicting=False): """Find distribution best matching `req` and usable on `working_set` This calls the ``find(req)`` method of the `working_set` to see if a suitable distribution is already active. (This may raise ``VersionConflict`` if an unsuitable version of the project is already active in the specified `working_set`.) If a suitable distribution isn't active, this method returns the newest distribution in the environment that meets the ``Requirement`` in `req`. If no suitable distribution is found, and `installer` is supplied, then the result of calling the environment's ``obtain(req, installer)`` method will be returned. """ try: dist = working_set.find(req) except VersionConflict: if not replace_conflicting: raise dist = None if dist is not None: return dist for dist in self[req.key]: if dist in req: return dist # try to download/install return self.obtain(req, installer)
[ "def", "best_match", "(", "self", ",", "req", ",", "working_set", ",", "installer", "=", "None", ",", "replace_conflicting", "=", "False", ")", ":", "try", ":", "dist", "=", "working_set", ".", "find", "(", "req", ")", "except", "VersionConflict", ":", "if", "not", "replace_conflicting", ":", "raise", "dist", "=", "None", "if", "dist", "is", "not", "None", ":", "return", "dist", "for", "dist", "in", "self", "[", "req", ".", "key", "]", ":", "if", "dist", "in", "req", ":", "return", "dist", "# try to download/install", "return", "self", ".", "obtain", "(", "req", ",", "installer", ")" ]
[ 1030, 4 ]
[ 1056, 42 ]
python
en
['en', 'en', 'en']
True
Environment.obtain
(self, requirement, installer=None)
Obtain a distribution matching `requirement` (e.g. via download) Obtain a distro that matches requirement (e.g. via download). In the base ``Environment`` class, this routine just returns ``installer(requirement)``, unless `installer` is None, in which case None is returned instead. This method is a hook that allows subclasses to attempt other ways of obtaining a distribution before falling back to the `installer` argument.
Obtain a distribution matching `requirement` (e.g. via download)
def obtain(self, requirement, installer=None): """Obtain a distribution matching `requirement` (e.g. via download) Obtain a distro that matches requirement (e.g. via download). In the base ``Environment`` class, this routine just returns ``installer(requirement)``, unless `installer` is None, in which case None is returned instead. This method is a hook that allows subclasses to attempt other ways of obtaining a distribution before falling back to the `installer` argument.""" if installer is not None: return installer(requirement)
[ "def", "obtain", "(", "self", ",", "requirement", ",", "installer", "=", "None", ")", ":", "if", "installer", "is", "not", "None", ":", "return", "installer", "(", "requirement", ")" ]
[ 1058, 4 ]
[ 1068, 41 ]
python
en
['it', 'en', 'en']
True
Environment.__iter__
(self)
Yield the unique project names of the available distributions
Yield the unique project names of the available distributions
def __iter__(self): """Yield the unique project names of the available distributions""" for key in self._distmap.keys(): if self[key]: yield key
[ "def", "__iter__", "(", "self", ")", ":", "for", "key", "in", "self", ".", "_distmap", ".", "keys", "(", ")", ":", "if", "self", "[", "key", "]", ":", "yield", "key" ]
[ 1070, 4 ]
[ 1074, 25 ]
python
en
['en', 'en', 'en']
True
Environment.__iadd__
(self, other)
In-place addition of a distribution or environment
In-place addition of a distribution or environment
def __iadd__(self, other): """In-place addition of a distribution or environment""" if isinstance(other, Distribution): self.add(other) elif isinstance(other, Environment): for project in other: for dist in other[project]: self.add(dist) else: raise TypeError("Can't add %r to environment" % (other,)) return self
[ "def", "__iadd__", "(", "self", ",", "other", ")", ":", "if", "isinstance", "(", "other", ",", "Distribution", ")", ":", "self", ".", "add", "(", "other", ")", "elif", "isinstance", "(", "other", ",", "Environment", ")", ":", "for", "project", "in", "other", ":", "for", "dist", "in", "other", "[", "project", "]", ":", "self", ".", "add", "(", "dist", ")", "else", ":", "raise", "TypeError", "(", "\"Can't add %r to environment\"", "%", "(", "other", ",", ")", ")", "return", "self" ]
[ 1076, 4 ]
[ 1086, 19 ]
python
en
['en', 'en', 'en']
True
Environment.__add__
(self, other)
Add an environment or distribution to an environment
Add an environment or distribution to an environment
def __add__(self, other): """Add an environment or distribution to an environment""" new = self.__class__([], platform=None, python=None) for env in self, other: new += env return new
[ "def", "__add__", "(", "self", ",", "other", ")", ":", "new", "=", "self", ".", "__class__", "(", "[", "]", ",", "platform", "=", "None", ",", "python", "=", "None", ")", "for", "env", "in", "self", ",", "other", ":", "new", "+=", "env", "return", "new" ]
[ 1088, 4 ]
[ 1093, 18 ]
python
en
['en', 'en', 'en']
True
ResourceManager.resource_exists
(self, package_or_requirement, resource_name)
Does the named resource exist?
Does the named resource exist?
def resource_exists(self, package_or_requirement, resource_name): """Does the named resource exist?""" return get_provider(package_or_requirement).has_resource(resource_name)
[ "def", "resource_exists", "(", "self", ",", "package_or_requirement", ",", "resource_name", ")", ":", "return", "get_provider", "(", "package_or_requirement", ")", ".", "has_resource", "(", "resource_name", ")" ]
[ 1123, 4 ]
[ 1125, 79 ]
python
en
['en', 'en', 'en']
True
ResourceManager.resource_isdir
(self, package_or_requirement, resource_name)
Is the named resource an existing directory?
Is the named resource an existing directory?
def resource_isdir(self, package_or_requirement, resource_name): """Is the named resource an existing directory?""" return get_provider(package_or_requirement).resource_isdir( resource_name )
[ "def", "resource_isdir", "(", "self", ",", "package_or_requirement", ",", "resource_name", ")", ":", "return", "get_provider", "(", "package_or_requirement", ")", ".", "resource_isdir", "(", "resource_name", ")" ]
[ 1127, 4 ]
[ 1131, 9 ]
python
en
['en', 'en', 'en']
True
ResourceManager.resource_filename
(self, package_or_requirement, resource_name)
Return a true filesystem path for specified resource
Return a true filesystem path for specified resource
def resource_filename(self, package_or_requirement, resource_name): """Return a true filesystem path for specified resource""" return get_provider(package_or_requirement).get_resource_filename( self, resource_name )
[ "def", "resource_filename", "(", "self", ",", "package_or_requirement", ",", "resource_name", ")", ":", "return", "get_provider", "(", "package_or_requirement", ")", ".", "get_resource_filename", "(", "self", ",", "resource_name", ")" ]
[ 1133, 4 ]
[ 1137, 9 ]
python
en
['en', 'en', 'en']
True
ResourceManager.resource_stream
(self, package_or_requirement, resource_name)
Return a readable file-like object for specified resource
Return a readable file-like object for specified resource
def resource_stream(self, package_or_requirement, resource_name): """Return a readable file-like object for specified resource""" return get_provider(package_or_requirement).get_resource_stream( self, resource_name )
[ "def", "resource_stream", "(", "self", ",", "package_or_requirement", ",", "resource_name", ")", ":", "return", "get_provider", "(", "package_or_requirement", ")", ".", "get_resource_stream", "(", "self", ",", "resource_name", ")" ]
[ 1139, 4 ]
[ 1143, 9 ]
python
en
['en', 'en', 'en']
True
ResourceManager.resource_string
(self, package_or_requirement, resource_name)
Return specified resource as a string
Return specified resource as a string
def resource_string(self, package_or_requirement, resource_name): """Return specified resource as a string""" return get_provider(package_or_requirement).get_resource_string( self, resource_name )
[ "def", "resource_string", "(", "self", ",", "package_or_requirement", ",", "resource_name", ")", ":", "return", "get_provider", "(", "package_or_requirement", ")", ".", "get_resource_string", "(", "self", ",", "resource_name", ")" ]
[ 1145, 4 ]
[ 1149, 9 ]
python
en
['en', 'en', 'en']
True
ResourceManager.resource_listdir
(self, package_or_requirement, resource_name)
List the contents of the named resource directory
List the contents of the named resource directory
def resource_listdir(self, package_or_requirement, resource_name): """List the contents of the named resource directory""" return get_provider(package_or_requirement).resource_listdir( resource_name )
[ "def", "resource_listdir", "(", "self", ",", "package_or_requirement", ",", "resource_name", ")", ":", "return", "get_provider", "(", "package_or_requirement", ")", ".", "resource_listdir", "(", "resource_name", ")" ]
[ 1151, 4 ]
[ 1155, 9 ]
python
en
['en', 'en', 'en']
True
ResourceManager.extraction_error
(self)
Give an error message for problems extracting file(s)
Give an error message for problems extracting file(s)
def extraction_error(self): """Give an error message for problems extracting file(s)""" old_exc = sys.exc_info()[1] cache_path = self.extraction_path or get_default_cache() tmpl = textwrap.dedent(""" Can't extract file(s) to egg cache The following error occurred while trying to extract file(s) to the Python egg cache: {old_exc} The Python egg cache directory is currently set to: {cache_path} Perhaps your account does not have write access to this directory? You can change the cache directory by setting the PYTHON_EGG_CACHE environment variable to point to an accessible directory. """).lstrip() err = ExtractionError(tmpl.format(**locals())) err.manager = self err.cache_path = cache_path err.original_error = old_exc raise err
[ "def", "extraction_error", "(", "self", ")", ":", "old_exc", "=", "sys", ".", "exc_info", "(", ")", "[", "1", "]", "cache_path", "=", "self", ".", "extraction_path", "or", "get_default_cache", "(", ")", "tmpl", "=", "textwrap", ".", "dedent", "(", "\"\"\"\n Can't extract file(s) to egg cache\n\n The following error occurred while trying to extract file(s)\n to the Python egg cache:\n\n {old_exc}\n\n The Python egg cache directory is currently set to:\n\n {cache_path}\n\n Perhaps your account does not have write access to this directory?\n You can change the cache directory by setting the PYTHON_EGG_CACHE\n environment variable to point to an accessible directory.\n \"\"\"", ")", ".", "lstrip", "(", ")", "err", "=", "ExtractionError", "(", "tmpl", ".", "format", "(", "*", "*", "locals", "(", ")", ")", ")", "err", ".", "manager", "=", "self", "err", ".", "cache_path", "=", "cache_path", "err", ".", "original_error", "=", "old_exc", "raise", "err" ]
[ 1157, 4 ]
[ 1183, 17 ]
python
en
['en', 'en', 'en']
True
ResourceManager.get_cache_path
(self, archive_name, names=())
Return absolute location in cache for `archive_name` and `names` The parent directory of the resulting path will be created if it does not already exist. `archive_name` should be the base filename of the enclosing egg (which may not be the name of the enclosing zipfile!), including its ".egg" extension. `names`, if provided, should be a sequence of path name parts "under" the egg's extraction location. This method should only be called by resource providers that need to obtain an extraction location, and only for names they intend to extract, as it tracks the generated names for possible cleanup later.
Return absolute location in cache for `archive_name` and `names`
def get_cache_path(self, archive_name, names=()): """Return absolute location in cache for `archive_name` and `names` The parent directory of the resulting path will be created if it does not already exist. `archive_name` should be the base filename of the enclosing egg (which may not be the name of the enclosing zipfile!), including its ".egg" extension. `names`, if provided, should be a sequence of path name parts "under" the egg's extraction location. This method should only be called by resource providers that need to obtain an extraction location, and only for names they intend to extract, as it tracks the generated names for possible cleanup later. """ extract_path = self.extraction_path or get_default_cache() target_path = os.path.join(extract_path, archive_name + '-tmp', *names) try: _bypass_ensure_directory(target_path) except Exception: self.extraction_error() self._warn_unsafe_extraction_path(extract_path) self.cached_files[target_path] = 1 return target_path
[ "def", "get_cache_path", "(", "self", ",", "archive_name", ",", "names", "=", "(", ")", ")", ":", "extract_path", "=", "self", ".", "extraction_path", "or", "get_default_cache", "(", ")", "target_path", "=", "os", ".", "path", ".", "join", "(", "extract_path", ",", "archive_name", "+", "'-tmp'", ",", "*", "names", ")", "try", ":", "_bypass_ensure_directory", "(", "target_path", ")", "except", "Exception", ":", "self", ".", "extraction_error", "(", ")", "self", ".", "_warn_unsafe_extraction_path", "(", "extract_path", ")", "self", ".", "cached_files", "[", "target_path", "]", "=", "1", "return", "target_path" ]
[ 1185, 4 ]
[ 1208, 26 ]
python
en
['en', 'en', 'en']
True
ResourceManager._warn_unsafe_extraction_path
(path)
If the default extraction path is overridden and set to an insecure location, such as /tmp, it opens up an opportunity for an attacker to replace an extracted file with an unauthorized payload. Warn the user if a known insecure location is used. See Distribute #375 for more details.
If the default extraction path is overridden and set to an insecure location, such as /tmp, it opens up an opportunity for an attacker to replace an extracted file with an unauthorized payload. Warn the user if a known insecure location is used.
def _warn_unsafe_extraction_path(path): """ If the default extraction path is overridden and set to an insecure location, such as /tmp, it opens up an opportunity for an attacker to replace an extracted file with an unauthorized payload. Warn the user if a known insecure location is used. See Distribute #375 for more details. """ if os.name == 'nt' and not path.startswith(os.environ['windir']): # On Windows, permissions are generally restrictive by default # and temp directories are not writable by other users, so # bypass the warning. return mode = os.stat(path).st_mode if mode & stat.S_IWOTH or mode & stat.S_IWGRP: msg = ( "%s is writable by group/others and vulnerable to attack " "when " "used with get_resource_filename. Consider a more secure " "location (set with .set_extraction_path or the " "PYTHON_EGG_CACHE environment variable)." % path ) warnings.warn(msg, UserWarning)
[ "def", "_warn_unsafe_extraction_path", "(", "path", ")", ":", "if", "os", ".", "name", "==", "'nt'", "and", "not", "path", ".", "startswith", "(", "os", ".", "environ", "[", "'windir'", "]", ")", ":", "# On Windows, permissions are generally restrictive by default", "# and temp directories are not writable by other users, so", "# bypass the warning.", "return", "mode", "=", "os", ".", "stat", "(", "path", ")", ".", "st_mode", "if", "mode", "&", "stat", ".", "S_IWOTH", "or", "mode", "&", "stat", ".", "S_IWGRP", ":", "msg", "=", "(", "\"%s is writable by group/others and vulnerable to attack \"", "\"when \"", "\"used with get_resource_filename. Consider a more secure \"", "\"location (set with .set_extraction_path or the \"", "\"PYTHON_EGG_CACHE environment variable).\"", "%", "path", ")", "warnings", ".", "warn", "(", "msg", ",", "UserWarning", ")" ]
[ 1211, 4 ]
[ 1234, 43 ]
python
en
['en', 'error', 'th']
False
ResourceManager.postprocess
(self, tempname, filename)
Perform any platform-specific postprocessing of `tempname` This is where Mac header rewrites should be done; other platforms don't have anything special they should do. Resource providers should call this method ONLY after successfully extracting a compressed resource. They must NOT call it on resources that are already in the filesystem. `tempname` is the current (temporary) name of the file, and `filename` is the name it will be renamed to by the caller after this routine returns.
Perform any platform-specific postprocessing of `tempname`
def postprocess(self, tempname, filename): """Perform any platform-specific postprocessing of `tempname` This is where Mac header rewrites should be done; other platforms don't have anything special they should do. Resource providers should call this method ONLY after successfully extracting a compressed resource. They must NOT call it on resources that are already in the filesystem. `tempname` is the current (temporary) name of the file, and `filename` is the name it will be renamed to by the caller after this routine returns. """ if os.name == 'posix': # Make the resource executable mode = ((os.stat(tempname).st_mode) | 0o555) & 0o7777 os.chmod(tempname, mode)
[ "def", "postprocess", "(", "self", ",", "tempname", ",", "filename", ")", ":", "if", "os", ".", "name", "==", "'posix'", ":", "# Make the resource executable", "mode", "=", "(", "(", "os", ".", "stat", "(", "tempname", ")", ".", "st_mode", ")", "|", "0o555", ")", "&", "0o7777", "os", ".", "chmod", "(", "tempname", ",", "mode", ")" ]
[ 1236, 4 ]
[ 1254, 36 ]
python
en
['en', 'en', 'en']
True
ResourceManager.set_extraction_path
(self, path)
Set the base path where resources will be extracted to, if needed. If you do not call this routine before any extractions take place, the path defaults to the return value of ``get_default_cache()``. (Which is based on the ``PYTHON_EGG_CACHE`` environment variable, with various platform-specific fallbacks. See that routine's documentation for more details.) Resources are extracted to subdirectories of this path based upon information given by the ``IResourceProvider``. You may set this to a temporary directory, but then you must call ``cleanup_resources()`` to delete the extracted files when done. There is no guarantee that ``cleanup_resources()`` will be able to remove all extracted files. (Note: you may not change the extraction path for a given resource manager once resources have been extracted, unless you first call ``cleanup_resources()``.)
Set the base path where resources will be extracted to, if needed.
def set_extraction_path(self, path): """Set the base path where resources will be extracted to, if needed. If you do not call this routine before any extractions take place, the path defaults to the return value of ``get_default_cache()``. (Which is based on the ``PYTHON_EGG_CACHE`` environment variable, with various platform-specific fallbacks. See that routine's documentation for more details.) Resources are extracted to subdirectories of this path based upon information given by the ``IResourceProvider``. You may set this to a temporary directory, but then you must call ``cleanup_resources()`` to delete the extracted files when done. There is no guarantee that ``cleanup_resources()`` will be able to remove all extracted files. (Note: you may not change the extraction path for a given resource manager once resources have been extracted, unless you first call ``cleanup_resources()``.) """ if self.cached_files: raise ValueError( "Can't change extraction path, files already extracted" ) self.extraction_path = path
[ "def", "set_extraction_path", "(", "self", ",", "path", ")", ":", "if", "self", ".", "cached_files", ":", "raise", "ValueError", "(", "\"Can't change extraction path, files already extracted\"", ")", "self", ".", "extraction_path", "=", "path" ]
[ 1256, 4 ]
[ 1280, 35 ]
python
en
['en', 'en', 'en']
True
ResourceManager.cleanup_resources
(self, force=False)
Delete all extracted resource files and directories, returning a list of the file and directory names that could not be successfully removed. This function does not have any concurrency protection, so it should generally only be called when the extraction path is a temporary directory exclusive to a single process. This method is not automatically called; you must call it explicitly or register it as an ``atexit`` function if you wish to ensure cleanup of a temporary directory used for extractions.
Delete all extracted resource files and directories, returning a list of the file and directory names that could not be successfully removed. This function does not have any concurrency protection, so it should generally only be called when the extraction path is a temporary directory exclusive to a single process. This method is not automatically called; you must call it explicitly or register it as an ``atexit`` function if you wish to ensure cleanup of a temporary directory used for extractions.
def cleanup_resources(self, force=False): """ Delete all extracted resource files and directories, returning a list of the file and directory names that could not be successfully removed. This function does not have any concurrency protection, so it should generally only be called when the extraction path is a temporary directory exclusive to a single process. This method is not automatically called; you must call it explicitly or register it as an ``atexit`` function if you wish to ensure cleanup of a temporary directory used for extractions. """
[ "def", "cleanup_resources", "(", "self", ",", "force", "=", "False", ")", ":" ]
[ 1282, 4 ]
[ 1292, 11 ]
python
en
['en', 'error', 'th']
False
ZipManifests.build
(cls, path)
Build a dictionary similar to the zipimport directory caches, except instead of tuples, store ZipInfo objects. Use a platform-specific path separator (os.sep) for the path keys for compatibility with pypy on Windows.
Build a dictionary similar to the zipimport directory caches, except instead of tuples, store ZipInfo objects.
def build(cls, path): """ Build a dictionary similar to the zipimport directory caches, except instead of tuples, store ZipInfo objects. Use a platform-specific path separator (os.sep) for the path keys for compatibility with pypy on Windows. """ with zipfile.ZipFile(path) as zfile: items = ( ( name.replace('/', os.sep), zfile.getinfo(name), ) for name in zfile.namelist() ) return dict(items)
[ "def", "build", "(", "cls", ",", "path", ")", ":", "with", "zipfile", ".", "ZipFile", "(", "path", ")", "as", "zfile", ":", "items", "=", "(", "(", "name", ".", "replace", "(", "'/'", ",", "os", ".", "sep", ")", ",", "zfile", ".", "getinfo", "(", "name", ")", ",", ")", "for", "name", "in", "zfile", ".", "namelist", "(", ")", ")", "return", "dict", "(", "items", ")" ]
[ 1557, 4 ]
[ 1573, 30 ]
python
en
['en', 'error', 'th']
False
MemoizedZipManifests.load
(self, path)
Load a manifest at path or return a suitable manifest already loaded.
Load a manifest at path or return a suitable manifest already loaded.
def load(self, path): """ Load a manifest at path or return a suitable manifest already loaded. """ path = os.path.normpath(path) mtime = os.stat(path).st_mtime if path not in self or self[path].mtime != mtime: manifest = self.build(path) self[path] = self.manifest_mod(manifest, mtime) return self[path].manifest
[ "def", "load", "(", "self", ",", "path", ")", ":", "path", "=", "os", ".", "path", ".", "normpath", "(", "path", ")", "mtime", "=", "os", ".", "stat", "(", "path", ")", ".", "st_mtime", "if", "path", "not", "in", "self", "or", "self", "[", "path", "]", ".", "mtime", "!=", "mtime", ":", "manifest", "=", "self", ".", "build", "(", "path", ")", "self", "[", "path", "]", "=", "self", ".", "manifest_mod", "(", "manifest", ",", "mtime", ")", "return", "self", "[", "path", "]", ".", "manifest" ]
[ 1584, 4 ]
[ 1595, 34 ]
python
en
['en', 'error', 'th']
False
ZipProvider._is_current
(self, file_path, zip_path)
Return True if the file_path is current for this zip_path
Return True if the file_path is current for this zip_path
def _is_current(self, file_path, zip_path): """ Return True if the file_path is current for this zip_path """ timestamp, size = self._get_date_and_size(self.zipinfo[zip_path]) if not os.path.isfile(file_path): return False stat = os.stat(file_path) if stat.st_size != size or stat.st_mtime != timestamp: return False # check that the contents match zip_contents = self.loader.get_data(zip_path) with open(file_path, 'rb') as f: file_contents = f.read() return zip_contents == file_contents
[ "def", "_is_current", "(", "self", ",", "file_path", ",", "zip_path", ")", ":", "timestamp", ",", "size", "=", "self", ".", "_get_date_and_size", "(", "self", ".", "zipinfo", "[", "zip_path", "]", ")", "if", "not", "os", ".", "path", ".", "isfile", "(", "file_path", ")", ":", "return", "False", "stat", "=", "os", ".", "stat", "(", "file_path", ")", "if", "stat", ".", "st_size", "!=", "size", "or", "stat", ".", "st_mtime", "!=", "timestamp", ":", "return", "False", "# check that the contents match", "zip_contents", "=", "self", ".", "loader", ".", "get_data", "(", "zip_path", ")", "with", "open", "(", "file_path", ",", "'rb'", ")", "as", "f", ":", "file_contents", "=", "f", ".", "read", "(", ")", "return", "zip_contents", "==", "file_contents" ]
[ 1711, 4 ]
[ 1725, 44 ]
python
en
['en', 'error', 'th']
False
EggMetadata.__init__
(self, importer)
Create a metadata provider from a zipimporter
Create a metadata provider from a zipimporter
def __init__(self, importer): """Create a metadata provider from a zipimporter""" self.zip_pre = importer.archive + os.sep self.loader = importer if importer.prefix: self.module_path = os.path.join(importer.archive, importer.prefix) else: self.module_path = importer.archive self._setup_prefix()
[ "def", "__init__", "(", "self", ",", "importer", ")", ":", "self", ".", "zip_pre", "=", "importer", ".", "archive", "+", "os", ".", "sep", "self", ".", "loader", "=", "importer", "if", "importer", ".", "prefix", ":", "self", ".", "module_path", "=", "os", ".", "path", ".", "join", "(", "importer", ".", "archive", ",", "importer", ".", "prefix", ")", "else", ":", "self", ".", "module_path", "=", "importer", ".", "archive", "self", ".", "_setup_prefix", "(", ")" ]
[ 1840, 4 ]
[ 1849, 28 ]
python
en
['en', 'en', 'en']
True
EntryPoint.load
(self, require=True, *args, **kwargs)
Require packages for this EntryPoint, then resolve it.
Require packages for this EntryPoint, then resolve it.
def load(self, require=True, *args, **kwargs): """ Require packages for this EntryPoint, then resolve it. """ if not require or args or kwargs: warnings.warn( "Parameters to load are deprecated. Call .resolve and " ".require separately.", DeprecationWarning, stacklevel=2, ) if require: self.require(*args, **kwargs) return self.resolve()
[ "def", "load", "(", "self", ",", "require", "=", "True", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "if", "not", "require", "or", "args", "or", "kwargs", ":", "warnings", ".", "warn", "(", "\"Parameters to load are deprecated. Call .resolve and \"", "\".require separately.\"", ",", "DeprecationWarning", ",", "stacklevel", "=", "2", ",", ")", "if", "require", ":", "self", ".", "require", "(", "*", "args", ",", "*", "*", "kwargs", ")", "return", "self", ".", "resolve", "(", ")" ]
[ 2310, 4 ]
[ 2323, 29 ]
python
en
['en', 'error', 'th']
False
EntryPoint.resolve
(self)
Resolve the entry point from its module and attrs.
Resolve the entry point from its module and attrs.
def resolve(self): """ Resolve the entry point from its module and attrs. """ module = __import__(self.module_name, fromlist=['__name__'], level=0) try: return functools.reduce(getattr, self.attrs, module) except AttributeError as exc: raise ImportError(str(exc))
[ "def", "resolve", "(", "self", ")", ":", "module", "=", "__import__", "(", "self", ".", "module_name", ",", "fromlist", "=", "[", "'__name__'", "]", ",", "level", "=", "0", ")", "try", ":", "return", "functools", ".", "reduce", "(", "getattr", ",", "self", ".", "attrs", ",", "module", ")", "except", "AttributeError", "as", "exc", ":", "raise", "ImportError", "(", "str", "(", "exc", ")", ")" ]
[ 2325, 4 ]
[ 2333, 39 ]
python
en
['en', 'error', 'th']
False
EntryPoint.parse
(cls, src, dist=None)
Parse a single entry point from string `src` Entry point syntax follows the form:: name = some.module:some.attr [extra1, extra2] The entry name and module name are required, but the ``:attrs`` and ``[extras]`` parts are optional
Parse a single entry point from string `src`
def parse(cls, src, dist=None): """Parse a single entry point from string `src` Entry point syntax follows the form:: name = some.module:some.attr [extra1, extra2] The entry name and module name are required, but the ``:attrs`` and ``[extras]`` parts are optional """ m = cls.pattern.match(src) if not m: msg = "EntryPoint must be in 'name=module:attrs [extras]' format" raise ValueError(msg, src) res = m.groupdict() extras = cls._parse_extras(res['extras']) attrs = res['attr'].split('.') if res['attr'] else () return cls(res['name'], res['module'], attrs, extras, dist)
[ "def", "parse", "(", "cls", ",", "src", ",", "dist", "=", "None", ")", ":", "m", "=", "cls", ".", "pattern", ".", "match", "(", "src", ")", "if", "not", "m", ":", "msg", "=", "\"EntryPoint must be in 'name=module:attrs [extras]' format\"", "raise", "ValueError", "(", "msg", ",", "src", ")", "res", "=", "m", ".", "groupdict", "(", ")", "extras", "=", "cls", ".", "_parse_extras", "(", "res", "[", "'extras'", "]", ")", "attrs", "=", "res", "[", "'attr'", "]", ".", "split", "(", "'.'", ")", "if", "res", "[", "'attr'", "]", "else", "(", ")", "return", "cls", "(", "res", "[", "'name'", "]", ",", "res", "[", "'module'", "]", ",", "attrs", ",", "extras", ",", "dist", ")" ]
[ 2358, 4 ]
[ 2375, 67 ]
python
en
['en', 'en', 'en']
True
EntryPoint.parse_group
(cls, group, lines, dist=None)
Parse an entry point group
Parse an entry point group
def parse_group(cls, group, lines, dist=None): """Parse an entry point group""" if not MODULE(group): raise ValueError("Invalid group name", group) this = {} for line in yield_lines(lines): ep = cls.parse(line, dist) if ep.name in this: raise ValueError("Duplicate entry point", group, ep.name) this[ep.name] = ep return this
[ "def", "parse_group", "(", "cls", ",", "group", ",", "lines", ",", "dist", "=", "None", ")", ":", "if", "not", "MODULE", "(", "group", ")", ":", "raise", "ValueError", "(", "\"Invalid group name\"", ",", "group", ")", "this", "=", "{", "}", "for", "line", "in", "yield_lines", "(", "lines", ")", ":", "ep", "=", "cls", ".", "parse", "(", "line", ",", "dist", ")", "if", "ep", ".", "name", "in", "this", ":", "raise", "ValueError", "(", "\"Duplicate entry point\"", ",", "group", ",", "ep", ".", "name", ")", "this", "[", "ep", ".", "name", "]", "=", "ep", "return", "this" ]
[ 2387, 4 ]
[ 2397, 19 ]
python
en
['en', 'en', 'en']
True
EntryPoint.parse_map
(cls, data, dist=None)
Parse a map of entry point groups
Parse a map of entry point groups
def parse_map(cls, data, dist=None): """Parse a map of entry point groups""" if isinstance(data, dict): data = data.items() else: data = split_sections(data) maps = {} for group, lines in data: if group is None: if not lines: continue raise ValueError("Entry points must be listed in groups") group = group.strip() if group in maps: raise ValueError("Duplicate group name", group) maps[group] = cls.parse_group(group, lines, dist) return maps
[ "def", "parse_map", "(", "cls", ",", "data", ",", "dist", "=", "None", ")", ":", "if", "isinstance", "(", "data", ",", "dict", ")", ":", "data", "=", "data", ".", "items", "(", ")", "else", ":", "data", "=", "split_sections", "(", "data", ")", "maps", "=", "{", "}", "for", "group", ",", "lines", "in", "data", ":", "if", "group", "is", "None", ":", "if", "not", "lines", ":", "continue", "raise", "ValueError", "(", "\"Entry points must be listed in groups\"", ")", "group", "=", "group", ".", "strip", "(", ")", "if", "group", "in", "maps", ":", "raise", "ValueError", "(", "\"Duplicate group name\"", ",", "group", ")", "maps", "[", "group", "]", "=", "cls", ".", "parse_group", "(", "group", ",", "lines", ",", "dist", ")", "return", "maps" ]
[ 2400, 4 ]
[ 2416, 19 ]
python
en
['en', 'en', 'en']
True
Distribution._dep_map
(self)
A map of extra to its list of (direct) requirements for this distribution, including the null extra.
A map of extra to its list of (direct) requirements for this distribution, including the null extra.
def _dep_map(self): """ A map of extra to its list of (direct) requirements for this distribution, including the null extra. """ try: return self.__dep_map except AttributeError: self.__dep_map = self._filter_extras(self._build_dep_map()) return self.__dep_map
[ "def", "_dep_map", "(", "self", ")", ":", "try", ":", "return", "self", ".", "__dep_map", "except", "AttributeError", ":", "self", ".", "__dep_map", "=", "self", ".", "_filter_extras", "(", "self", ".", "_build_dep_map", "(", ")", ")", "return", "self", ".", "__dep_map" ]
[ 2570, 4 ]
[ 2579, 29 ]
python
en
['en', 'error', 'th']
False
Distribution._filter_extras
(dm)
Given a mapping of extras to dependencies, strip off environment markers and filter out any dependencies not matching the markers.
Given a mapping of extras to dependencies, strip off environment markers and filter out any dependencies not matching the markers.
def _filter_extras(dm): """ Given a mapping of extras to dependencies, strip off environment markers and filter out any dependencies not matching the markers. """ for extra in list(filter(None, dm)): new_extra = extra reqs = dm.pop(extra) new_extra, _, marker = extra.partition(':') fails_marker = marker and ( invalid_marker(marker) or not evaluate_marker(marker) ) if fails_marker: reqs = [] new_extra = safe_extra(new_extra) or None dm.setdefault(new_extra, []).extend(reqs) return dm
[ "def", "_filter_extras", "(", "dm", ")", ":", "for", "extra", "in", "list", "(", "filter", "(", "None", ",", "dm", ")", ")", ":", "new_extra", "=", "extra", "reqs", "=", "dm", ".", "pop", "(", "extra", ")", "new_extra", ",", "_", ",", "marker", "=", "extra", ".", "partition", "(", "':'", ")", "fails_marker", "=", "marker", "and", "(", "invalid_marker", "(", "marker", ")", "or", "not", "evaluate_marker", "(", "marker", ")", ")", "if", "fails_marker", ":", "reqs", "=", "[", "]", "new_extra", "=", "safe_extra", "(", "new_extra", ")", "or", "None", "dm", ".", "setdefault", "(", "new_extra", ",", "[", "]", ")", ".", "extend", "(", "reqs", ")", "return", "dm" ]
[ 2582, 4 ]
[ 2601, 17 ]
python
en
['en', 'error', 'th']
False
Distribution.requires
(self, extras=())
List of Requirements needed for this distro if `extras` are used
List of Requirements needed for this distro if `extras` are used
def requires(self, extras=()): """List of Requirements needed for this distro if `extras` are used""" dm = self._dep_map deps = [] deps.extend(dm.get(None, ())) for ext in extras: try: deps.extend(dm[safe_extra(ext)]) except KeyError: raise UnknownExtra( "%s has no such extra feature %r" % (self, ext) ) return deps
[ "def", "requires", "(", "self", ",", "extras", "=", "(", ")", ")", ":", "dm", "=", "self", ".", "_dep_map", "deps", "=", "[", "]", "deps", ".", "extend", "(", "dm", ".", "get", "(", "None", ",", "(", ")", ")", ")", "for", "ext", "in", "extras", ":", "try", ":", "deps", ".", "extend", "(", "dm", "[", "safe_extra", "(", "ext", ")", "]", ")", "except", "KeyError", ":", "raise", "UnknownExtra", "(", "\"%s has no such extra feature %r\"", "%", "(", "self", ",", "ext", ")", ")", "return", "deps" ]
[ 2610, 4 ]
[ 2622, 19 ]
python
en
['en', 'en', 'en']
True
Distribution.activate
(self, path=None, replace=False)
Ensure distribution is importable on `path` (default=sys.path)
Ensure distribution is importable on `path` (default=sys.path)
def activate(self, path=None, replace=False): """Ensure distribution is importable on `path` (default=sys.path)""" if path is None: path = sys.path self.insert_on(path, replace=replace) if path is sys.path: fixup_namespace_packages(self.location) for pkg in self._get_metadata('namespace_packages.txt'): if pkg in sys.modules: declare_namespace(pkg)
[ "def", "activate", "(", "self", ",", "path", "=", "None", ",", "replace", "=", "False", ")", ":", "if", "path", "is", "None", ":", "path", "=", "sys", ".", "path", "self", ".", "insert_on", "(", "path", ",", "replace", "=", "replace", ")", "if", "path", "is", "sys", ".", "path", ":", "fixup_namespace_packages", "(", "self", ".", "location", ")", "for", "pkg", "in", "self", ".", "_get_metadata", "(", "'namespace_packages.txt'", ")", ":", "if", "pkg", "in", "sys", ".", "modules", ":", "declare_namespace", "(", "pkg", ")" ]
[ 2629, 4 ]
[ 2638, 42 ]
python
en
['en', 'en', 'en']
True
Distribution.egg_name
(self)
Return what this distribution's standard .egg filename should be
Return what this distribution's standard .egg filename should be
def egg_name(self): """Return what this distribution's standard .egg filename should be""" filename = "%s-%s-py%s" % ( to_filename(self.project_name), to_filename(self.version), self.py_version or PY_MAJOR ) if self.platform: filename += '-' + self.platform return filename
[ "def", "egg_name", "(", "self", ")", ":", "filename", "=", "\"%s-%s-py%s\"", "%", "(", "to_filename", "(", "self", ".", "project_name", ")", ",", "to_filename", "(", "self", ".", "version", ")", ",", "self", ".", "py_version", "or", "PY_MAJOR", ")", "if", "self", ".", "platform", ":", "filename", "+=", "'-'", "+", "self", ".", "platform", "return", "filename" ]
[ 2640, 4 ]
[ 2649, 23 ]
python
en
['en', 'en', 'en']
True
Distribution.__getattr__
(self, attr)
Delegate all unrecognized public attributes to .metadata provider
Delegate all unrecognized public attributes to .metadata provider
def __getattr__(self, attr): """Delegate all unrecognized public attributes to .metadata provider""" if attr.startswith('_'): raise AttributeError(attr) return getattr(self._provider, attr)
[ "def", "__getattr__", "(", "self", ",", "attr", ")", ":", "if", "attr", ".", "startswith", "(", "'_'", ")", ":", "raise", "AttributeError", "(", "attr", ")", "return", "getattr", "(", "self", ".", "_provider", ",", "attr", ")" ]
[ 2665, 4 ]
[ 2669, 44 ]
python
en
['en', 'it', 'en']
True
Distribution.as_requirement
(self)
Return a ``Requirement`` that matches this distribution exactly
Return a ``Requirement`` that matches this distribution exactly
def as_requirement(self): """Return a ``Requirement`` that matches this distribution exactly""" if isinstance(self.parsed_version, packaging.version.Version): spec = "%s==%s" % (self.project_name, self.parsed_version) else: spec = "%s===%s" % (self.project_name, self.parsed_version) return Requirement.parse(spec)
[ "def", "as_requirement", "(", "self", ")", ":", "if", "isinstance", "(", "self", ".", "parsed_version", ",", "packaging", ".", "version", ".", "Version", ")", ":", "spec", "=", "\"%s==%s\"", "%", "(", "self", ".", "project_name", ",", "self", ".", "parsed_version", ")", "else", ":", "spec", "=", "\"%s===%s\"", "%", "(", "self", ".", "project_name", ",", "self", ".", "parsed_version", ")", "return", "Requirement", ".", "parse", "(", "spec", ")" ]
[ 2678, 4 ]
[ 2685, 38 ]
python
en
['en', 'en', 'en']
True
Distribution.load_entry_point
(self, group, name)
Return the `name` entry point of `group` or raise ImportError
Return the `name` entry point of `group` or raise ImportError
def load_entry_point(self, group, name): """Return the `name` entry point of `group` or raise ImportError""" ep = self.get_entry_info(group, name) if ep is None: raise ImportError("Entry point %r not found" % ((group, name),)) return ep.load()
[ "def", "load_entry_point", "(", "self", ",", "group", ",", "name", ")", ":", "ep", "=", "self", ".", "get_entry_info", "(", "group", ",", "name", ")", "if", "ep", "is", "None", ":", "raise", "ImportError", "(", "\"Entry point %r not found\"", "%", "(", "(", "group", ",", "name", ")", ",", ")", ")", "return", "ep", ".", "load", "(", ")" ]
[ 2687, 4 ]
[ 2692, 24 ]
python
en
['en', 'en', 'en']
True
Distribution.get_entry_map
(self, group=None)
Return the entry point map for `group`, or the full entry map
Return the entry point map for `group`, or the full entry map
def get_entry_map(self, group=None): """Return the entry point map for `group`, or the full entry map""" try: ep_map = self._ep_map except AttributeError: ep_map = self._ep_map = EntryPoint.parse_map( self._get_metadata('entry_points.txt'), self ) if group is not None: return ep_map.get(group, {}) return ep_map
[ "def", "get_entry_map", "(", "self", ",", "group", "=", "None", ")", ":", "try", ":", "ep_map", "=", "self", ".", "_ep_map", "except", "AttributeError", ":", "ep_map", "=", "self", ".", "_ep_map", "=", "EntryPoint", ".", "parse_map", "(", "self", ".", "_get_metadata", "(", "'entry_points.txt'", ")", ",", "self", ")", "if", "group", "is", "not", "None", ":", "return", "ep_map", ".", "get", "(", "group", ",", "{", "}", ")", "return", "ep_map" ]
[ 2694, 4 ]
[ 2704, 21 ]
python
en
['en', 'en', 'en']
True
Distribution.get_entry_info
(self, group, name)
Return the EntryPoint object for `group`+`name`, or ``None``
Return the EntryPoint object for `group`+`name`, or ``None``
def get_entry_info(self, group, name): """Return the EntryPoint object for `group`+`name`, or ``None``""" return self.get_entry_map(group).get(name)
[ "def", "get_entry_info", "(", "self", ",", "group", ",", "name", ")", ":", "return", "self", ".", "get_entry_map", "(", "group", ")", ".", "get", "(", "name", ")" ]
[ 2706, 4 ]
[ 2708, 50 ]
python
en
['en', 'en', 'en']
True
Distribution.insert_on
(self, path, loc=None, replace=False)
Ensure self.location is on path If replace=False (default): - If location is already in path anywhere, do nothing. - Else: - If it's an egg and its parent directory is on path, insert just ahead of the parent. - Else: add to the end of path. If replace=True: - If location is already on path anywhere (not eggs) or higher priority than its parent (eggs) do nothing. - Else: - If it's an egg and its parent directory is on path, insert just ahead of the parent, removing any lower-priority entries. - Else: add it to the front of path.
Ensure self.location is on path
def insert_on(self, path, loc=None, replace=False): """Ensure self.location is on path If replace=False (default): - If location is already in path anywhere, do nothing. - Else: - If it's an egg and its parent directory is on path, insert just ahead of the parent. - Else: add to the end of path. If replace=True: - If location is already on path anywhere (not eggs) or higher priority than its parent (eggs) do nothing. - Else: - If it's an egg and its parent directory is on path, insert just ahead of the parent, removing any lower-priority entries. - Else: add it to the front of path. """ loc = loc or self.location if not loc: return nloc = _normalize_cached(loc) bdir = os.path.dirname(nloc) npath = [(p and _normalize_cached(p) or p) for p in path] for p, item in enumerate(npath): if item == nloc: if replace: break else: # don't modify path (even removing duplicates) if # found and not replace return elif item == bdir and self.precedence == EGG_DIST: # if it's an .egg, give it precedence over its directory # UNLESS it's already been added to sys.path and replace=False if (not replace) and nloc in npath[p:]: return if path is sys.path: self.check_version_conflict() path.insert(p, loc) npath.insert(p, nloc) break else: if path is sys.path: self.check_version_conflict() if replace: path.insert(0, loc) else: path.append(loc) return # p is the spot where we found or inserted loc; now remove duplicates while True: try: np = npath.index(nloc, p + 1) except ValueError: break else: del npath[np], path[np] # ha! p = np return
[ "def", "insert_on", "(", "self", ",", "path", ",", "loc", "=", "None", ",", "replace", "=", "False", ")", ":", "loc", "=", "loc", "or", "self", ".", "location", "if", "not", "loc", ":", "return", "nloc", "=", "_normalize_cached", "(", "loc", ")", "bdir", "=", "os", ".", "path", ".", "dirname", "(", "nloc", ")", "npath", "=", "[", "(", "p", "and", "_normalize_cached", "(", "p", ")", "or", "p", ")", "for", "p", "in", "path", "]", "for", "p", ",", "item", "in", "enumerate", "(", "npath", ")", ":", "if", "item", "==", "nloc", ":", "if", "replace", ":", "break", "else", ":", "# don't modify path (even removing duplicates) if", "# found and not replace", "return", "elif", "item", "==", "bdir", "and", "self", ".", "precedence", "==", "EGG_DIST", ":", "# if it's an .egg, give it precedence over its directory", "# UNLESS it's already been added to sys.path and replace=False", "if", "(", "not", "replace", ")", "and", "nloc", "in", "npath", "[", "p", ":", "]", ":", "return", "if", "path", "is", "sys", ".", "path", ":", "self", ".", "check_version_conflict", "(", ")", "path", ".", "insert", "(", "p", ",", "loc", ")", "npath", ".", "insert", "(", "p", ",", "nloc", ")", "break", "else", ":", "if", "path", "is", "sys", ".", "path", ":", "self", ".", "check_version_conflict", "(", ")", "if", "replace", ":", "path", ".", "insert", "(", "0", ",", "loc", ")", "else", ":", "path", ".", "append", "(", "loc", ")", "return", "# p is the spot where we found or inserted loc; now remove duplicates", "while", "True", ":", "try", ":", "np", "=", "npath", ".", "index", "(", "nloc", ",", "p", "+", "1", ")", "except", "ValueError", ":", "break", "else", ":", "del", "npath", "[", "np", "]", ",", "path", "[", "np", "]", "# ha!", "p", "=", "np", "return" ]
[ 2710, 4 ]
[ 2776, 14 ]
python
en
['en', 'en', 'en']
True
Distribution.clone
(self, **kw)
Copy this distribution, substituting in any changed keyword args
Copy this distribution, substituting in any changed keyword args
def clone(self, **kw): """Copy this distribution, substituting in any changed keyword args""" names = 'project_name version py_version platform location precedence' for attr in names.split(): kw.setdefault(attr, getattr(self, attr, None)) kw.setdefault('metadata', self._provider) return self.__class__(**kw)
[ "def", "clone", "(", "self", ",", "*", "*", "kw", ")", ":", "names", "=", "'project_name version py_version platform location precedence'", "for", "attr", "in", "names", ".", "split", "(", ")", ":", "kw", ".", "setdefault", "(", "attr", ",", "getattr", "(", "self", ",", "attr", ",", "None", ")", ")", "kw", ".", "setdefault", "(", "'metadata'", ",", "self", ".", "_provider", ")", "return", "self", ".", "__class__", "(", "*", "*", "kw", ")" ]
[ 2808, 4 ]
[ 2814, 35 ]
python
en
['en', 'en', 'en']
True
EggInfoDistribution._reload_version
(self)
Packages installed by distutils (e.g. numpy or scipy), which uses an old safe_version, and so their version numbers can get mangled when converted to filenames (e.g., 1.11.0.dev0+2329eae to 1.11.0.dev0_2329eae). These distributions will not be parsed properly downstream by Distribution and safe_version, so take an extra step and try to get the version number from the metadata file itself instead of the filename.
Packages installed by distutils (e.g. numpy or scipy), which uses an old safe_version, and so their version numbers can get mangled when converted to filenames (e.g., 1.11.0.dev0+2329eae to 1.11.0.dev0_2329eae). These distributions will not be parsed properly downstream by Distribution and safe_version, so take an extra step and try to get the version number from the metadata file itself instead of the filename.
def _reload_version(self): """ Packages installed by distutils (e.g. numpy or scipy), which uses an old safe_version, and so their version numbers can get mangled when converted to filenames (e.g., 1.11.0.dev0+2329eae to 1.11.0.dev0_2329eae). These distributions will not be parsed properly downstream by Distribution and safe_version, so take an extra step and try to get the version number from the metadata file itself instead of the filename. """ md_version = _version_from_file(self._get_metadata(self.PKG_INFO)) if md_version: self._version = md_version return self
[ "def", "_reload_version", "(", "self", ")", ":", "md_version", "=", "_version_from_file", "(", "self", ".", "_get_metadata", "(", "self", ".", "PKG_INFO", ")", ")", "if", "md_version", ":", "self", ".", "_version", "=", "md_version", "return", "self" ]
[ 2822, 4 ]
[ 2837, 19 ]
python
en
['en', 'error', 'th']
False
DistInfoDistribution._parsed_pkg_info
(self)
Parse and cache metadata
Parse and cache metadata
def _parsed_pkg_info(self): """Parse and cache metadata""" try: return self._pkg_info except AttributeError: metadata = self.get_metadata(self.PKG_INFO) self._pkg_info = email.parser.Parser().parsestr(metadata) return self._pkg_info
[ "def", "_parsed_pkg_info", "(", "self", ")", ":", "try", ":", "return", "self", ".", "_pkg_info", "except", "AttributeError", ":", "metadata", "=", "self", ".", "get_metadata", "(", "self", ".", "PKG_INFO", ")", "self", ".", "_pkg_info", "=", "email", ".", "parser", ".", "Parser", "(", ")", ".", "parsestr", "(", "metadata", ")", "return", "self", ".", "_pkg_info" ]
[ 2849, 4 ]
[ 2856, 33 ]
python
en
['en', 'la', 'en']
True
DistInfoDistribution._compute_dependencies
(self)
Recompute this distribution's dependencies.
Recompute this distribution's dependencies.
def _compute_dependencies(self): """Recompute this distribution's dependencies.""" dm = self.__dep_map = {None: []} reqs = [] # Including any condition expressions for req in self._parsed_pkg_info.get_all('Requires-Dist') or []: reqs.extend(parse_requirements(req)) def reqs_for_extra(extra): for req in reqs: if not req.marker or req.marker.evaluate({'extra': extra}): yield req common = frozenset(reqs_for_extra(None)) dm[None].extend(common) for extra in self._parsed_pkg_info.get_all('Provides-Extra') or []: s_extra = safe_extra(extra.strip()) dm[s_extra] = list(frozenset(reqs_for_extra(extra)) - common) return dm
[ "def", "_compute_dependencies", "(", "self", ")", ":", "dm", "=", "self", ".", "__dep_map", "=", "{", "None", ":", "[", "]", "}", "reqs", "=", "[", "]", "# Including any condition expressions", "for", "req", "in", "self", ".", "_parsed_pkg_info", ".", "get_all", "(", "'Requires-Dist'", ")", "or", "[", "]", ":", "reqs", ".", "extend", "(", "parse_requirements", "(", "req", ")", ")", "def", "reqs_for_extra", "(", "extra", ")", ":", "for", "req", "in", "reqs", ":", "if", "not", "req", ".", "marker", "or", "req", ".", "marker", ".", "evaluate", "(", "{", "'extra'", ":", "extra", "}", ")", ":", "yield", "req", "common", "=", "frozenset", "(", "reqs_for_extra", "(", "None", ")", ")", "dm", "[", "None", "]", ".", "extend", "(", "common", ")", "for", "extra", "in", "self", ".", "_parsed_pkg_info", ".", "get_all", "(", "'Provides-Extra'", ")", "or", "[", "]", ":", "s_extra", "=", "safe_extra", "(", "extra", ".", "strip", "(", ")", ")", "dm", "[", "s_extra", "]", "=", "list", "(", "frozenset", "(", "reqs_for_extra", "(", "extra", ")", ")", "-", "common", ")", "return", "dm" ]
[ 2866, 4 ]
[ 2887, 17 ]
python
en
['en', 'en', 'en']
True
Requirement.__init__
(self, requirement_string)
DO NOT CALL THIS UNDOCUMENTED METHOD; use Requirement.parse()!
DO NOT CALL THIS UNDOCUMENTED METHOD; use Requirement.parse()!
def __init__(self, requirement_string): """DO NOT CALL THIS UNDOCUMENTED METHOD; use Requirement.parse()!""" try: super(Requirement, self).__init__(requirement_string) except packaging.requirements.InvalidRequirement as e: raise RequirementParseError(str(e)) self.unsafe_name = self.name project_name = safe_name(self.name) self.project_name, self.key = project_name, project_name.lower() self.specs = [ (spec.operator, spec.version) for spec in self.specifier] self.extras = tuple(map(safe_extra, self.extras)) self.hashCmp = ( self.key, self.specifier, frozenset(self.extras), str(self.marker) if self.marker else None, ) self.__hash = hash(self.hashCmp)
[ "def", "__init__", "(", "self", ",", "requirement_string", ")", ":", "try", ":", "super", "(", "Requirement", ",", "self", ")", ".", "__init__", "(", "requirement_string", ")", "except", "packaging", ".", "requirements", ".", "InvalidRequirement", "as", "e", ":", "raise", "RequirementParseError", "(", "str", "(", "e", ")", ")", "self", ".", "unsafe_name", "=", "self", ".", "name", "project_name", "=", "safe_name", "(", "self", ".", "name", ")", "self", ".", "project_name", ",", "self", ".", "key", "=", "project_name", ",", "project_name", ".", "lower", "(", ")", "self", ".", "specs", "=", "[", "(", "spec", ".", "operator", ",", "spec", ".", "version", ")", "for", "spec", "in", "self", ".", "specifier", "]", "self", ".", "extras", "=", "tuple", "(", "map", "(", "safe_extra", ",", "self", ".", "extras", ")", ")", "self", ".", "hashCmp", "=", "(", "self", ".", "key", ",", "self", ".", "specifier", ",", "frozenset", "(", "self", ".", "extras", ")", ",", "str", "(", "self", ".", "marker", ")", "if", "self", ".", "marker", "else", "None", ",", ")", "self", ".", "__hash", "=", "hash", "(", "self", ".", "hashCmp", ")" ]
[ 2938, 4 ]
[ 2956, 40 ]
python
en
['en', 'en', 'en']
True
conv2DBatchNorm
(inputs, filters=128, kernel_size=(2, 2), activation=ACTIVATION, name=None)
Convolution 2D with BatchNormalization and activation :param inputs: input to the layer :param filters: number of filters from convoltuion, defaults to 128 :param kernel_size: kernel for convolution, defaults to (2, 2) :param name: name of the scope :return: output from convolution layer
Convolution 2D with BatchNormalization and activation :param inputs: input to the layer :param filters: number of filters from convoltuion, defaults to 128 :param kernel_size: kernel for convolution, defaults to (2, 2) :param name: name of the scope :return: output from convolution layer
def conv2DBatchNorm(inputs, filters=128, kernel_size=(2, 2), activation=ACTIVATION, name=None): """ Convolution 2D with BatchNormalization and activation :param inputs: input to the layer :param filters: number of filters from convoltuion, defaults to 128 :param kernel_size: kernel for convolution, defaults to (2, 2) :param name: name of the scope :return: output from convolution layer """ with tf.name_scope(name) as scope: layer = tf.keras.layers.Conv2D( filters, kernel_size, padding="same", kernel_initializer=KERNEL_INIT, use_bias=False )(inputs) layer = BatchNormalization()(layer) layer = tf.keras.layers.Activation(activation, name=name)(layer) return layer
[ "def", "conv2DBatchNorm", "(", "inputs", ",", "filters", "=", "128", ",", "kernel_size", "=", "(", "2", ",", "2", ")", ",", "activation", "=", "ACTIVATION", ",", "name", "=", "None", ")", ":", "with", "tf", ".", "name_scope", "(", "name", ")", "as", "scope", ":", "layer", "=", "tf", ".", "keras", ".", "layers", ".", "Conv2D", "(", "filters", ",", "kernel_size", ",", "padding", "=", "\"same\"", ",", "kernel_initializer", "=", "KERNEL_INIT", ",", "use_bias", "=", "False", ")", "(", "inputs", ")", "layer", "=", "BatchNormalization", "(", ")", "(", "layer", ")", "layer", "=", "tf", ".", "keras", ".", "layers", ".", "Activation", "(", "activation", ",", "name", "=", "name", ")", "(", "layer", ")", "return", "layer" ]
[ 7, 0 ]
[ 22, 20 ]
python
en
['en', 'error', 'th']
False
deformConv2D
(inputs, filters=64, kernel_size=(4, 4), strides=(2, 2), activation=ACTIVATION, name=None)
Apply deformable with conv2d transpose on inputs. :param inputs: input from upper layer :param filters: numbere of filters, defaults to 64 :param kernel_size: kernel size, defaults to (4, 4) :param strides: kernel strides, defaults to (2, 2) :param activation: relu activation, defaults to ACTIVATION :param name: name of the scope, defaults to None :return: output from sequence of layers
Apply deformable with conv2d transpose on inputs. :param inputs: input from upper layer :param filters: numbere of filters, defaults to 64 :param kernel_size: kernel size, defaults to (4, 4) :param strides: kernel strides, defaults to (2, 2) :param activation: relu activation, defaults to ACTIVATION :param name: name of the scope, defaults to None :return: output from sequence of layers
def deformConv2D(inputs, filters=64, kernel_size=(4, 4), strides=(2, 2), activation=ACTIVATION, name=None): """ Apply deformable with conv2d transpose on inputs. :param inputs: input from upper layer :param filters: numbere of filters, defaults to 64 :param kernel_size: kernel size, defaults to (4, 4) :param strides: kernel strides, defaults to (2, 2) :param activation: relu activation, defaults to ACTIVATION :param name: name of the scope, defaults to None :return: output from sequence of layers """ from tensorflow_addons.layers.deformable_conv2d import DeformableConv2D with tf.name_scope(name) as scope: fc = DeformableConv2D( filters, kernel_size=(3, 3), strides=(1, 1), use_bias=False, padding="same", kernel_initializer=KERNEL_INIT, kernel_regularizer=tf.keras.regularizers.l2(L2_REG), )(inputs) layer = BatchNormalization()(fc) layer = tf.keras.layers.Activation(activation)(layer) up = tf.keras.layers.Conv2DTranspose( filters, kernel_size, strides=strides, padding="same", use_bias=False, kernel_initializer=KERNEL_INIT, kernel_regularizer=tf.keras.regularizers.l2(L2_REG), )(layer) layer = BatchNormalization()(up) layer = tf.keras.layers.Activation(activation)(layer) return layer
[ "def", "deformConv2D", "(", "inputs", ",", "filters", "=", "64", ",", "kernel_size", "=", "(", "4", ",", "4", ")", ",", "strides", "=", "(", "2", ",", "2", ")", ",", "activation", "=", "ACTIVATION", ",", "name", "=", "None", ")", ":", "from", "tensorflow_addons", ".", "layers", ".", "deformable_conv2d", "import", "DeformableConv2D", "with", "tf", ".", "name_scope", "(", "name", ")", "as", "scope", ":", "fc", "=", "DeformableConv2D", "(", "filters", ",", "kernel_size", "=", "(", "3", ",", "3", ")", ",", "strides", "=", "(", "1", ",", "1", ")", ",", "use_bias", "=", "False", ",", "padding", "=", "\"same\"", ",", "kernel_initializer", "=", "KERNEL_INIT", ",", "kernel_regularizer", "=", "tf", ".", "keras", ".", "regularizers", ".", "l2", "(", "L2_REG", ")", ",", ")", "(", "inputs", ")", "layer", "=", "BatchNormalization", "(", ")", "(", "fc", ")", "layer", "=", "tf", ".", "keras", ".", "layers", ".", "Activation", "(", "activation", ")", "(", "layer", ")", "up", "=", "tf", ".", "keras", ".", "layers", ".", "Conv2DTranspose", "(", "filters", ",", "kernel_size", ",", "strides", "=", "strides", ",", "padding", "=", "\"same\"", ",", "use_bias", "=", "False", ",", "kernel_initializer", "=", "KERNEL_INIT", ",", "kernel_regularizer", "=", "tf", ".", "keras", ".", "regularizers", ".", "l2", "(", "L2_REG", ")", ",", ")", "(", "layer", ")", "layer", "=", "BatchNormalization", "(", ")", "(", "up", ")", "layer", "=", "tf", ".", "keras", ".", "layers", ".", "Activation", "(", "activation", ")", "(", "layer", ")", "return", "layer" ]
[ 25, 0 ]
[ 61, 20 ]
python
en
['en', 'error', 'th']
False
deformConv2DShortcut
( inputs, shortcut, shortcut_number, filters=64, kernel_size=(3, 3), strides=(1, 1), activation=ACTIVATION, mode=None, name=None, )
Similar to TTF Net, we are merging deformable conv2d with shortcut connections from backbone. :param inputs: input to the deformable convolution :param shortcut: output from backbone :param shortcut_number: how many layers we should apply before merging shortuct with deformable convolution :param filters: number of filters to compute, defaults to 64 :param kernel_size: conv kernel size, defaults to (3, 3) :param strides: conv strides, defaults to (1, 1) :param activation: name of activation layer, :param mode: concat or sum, defaults to "sum" (ttfnet) :param name: name of the scope, defaults to None :return: output from sequence of layers
Similar to TTF Net, we are merging deformable conv2d with shortcut connections from backbone. :param inputs: input to the deformable convolution :param shortcut: output from backbone :param shortcut_number: how many layers we should apply before merging shortuct with deformable convolution :param filters: number of filters to compute, defaults to 64 :param kernel_size: conv kernel size, defaults to (3, 3) :param strides: conv strides, defaults to (1, 1) :param activation: name of activation layer, :param mode: concat or sum, defaults to "sum" (ttfnet) :param name: name of the scope, defaults to None :return: output from sequence of layers
def deformConv2DShortcut( inputs, shortcut, shortcut_number, filters=64, kernel_size=(3, 3), strides=(1, 1), activation=ACTIVATION, mode=None, name=None, ): """ Similar to TTF Net, we are merging deformable conv2d with shortcut connections from backbone. :param inputs: input to the deformable convolution :param shortcut: output from backbone :param shortcut_number: how many layers we should apply before merging shortuct with deformable convolution :param filters: number of filters to compute, defaults to 64 :param kernel_size: conv kernel size, defaults to (3, 3) :param strides: conv strides, defaults to (1, 1) :param activation: name of activation layer, :param mode: concat or sum, defaults to "sum" (ttfnet) :param name: name of the scope, defaults to None :return: output from sequence of layers """ from tensorflow_addons.layers.deformable_conv2d import DeformableConv2D filters = int(filters) with tf.name_scope(name) as scope: dcn = DeformableConv2D( filters, kernel_size=kernel_size, strides=strides, padding="same", use_bias=False, kernel_initializer=KERNEL_INIT, kernel_regularizer=tf.keras.regularizers.l2(L2_REG), )(inputs) dcn = BatchNormalization()(dcn) dcn = tf.keras.layers.Activation(activation)(dcn) dcn = tf.keras.layers.UpSampling2D(interpolation="bilinear")(dcn) # shortcut from backbone for i in range(shortcut_number): bias = False if i < (shortcut_number - 1) or mode == XModelMode.DCNSHORTCUTCONCAT else True shortcut = tf.keras.layers.Conv2D( filters, kernel_size=kernel_size, strides=strides, padding="same", use_bias=bias, kernel_initializer=KERNEL_INIT, kernel_regularizer=tf.keras.regularizers.l2(L2_REG), )(shortcut) # do not call activation layer on the last output from shortcut if i < (shortcut_number - 1) or mode == XModelMode.DCNSHORTCUTCONCAT: shortcut = BatchNormalization()(shortcut) shortcut = tf.keras.layers.Activation(activation)(shortcut) if mode == XModelMode.DCNSHORTCUTCONCAT: return tf.keras.layers.Concatenate()([dcn, shortcut]) return dcn + shortcut
[ "def", "deformConv2DShortcut", "(", "inputs", ",", "shortcut", ",", "shortcut_number", ",", "filters", "=", "64", ",", "kernel_size", "=", "(", "3", ",", "3", ")", ",", "strides", "=", "(", "1", ",", "1", ")", ",", "activation", "=", "ACTIVATION", ",", "mode", "=", "None", ",", "name", "=", "None", ",", ")", ":", "from", "tensorflow_addons", ".", "layers", ".", "deformable_conv2d", "import", "DeformableConv2D", "filters", "=", "int", "(", "filters", ")", "with", "tf", ".", "name_scope", "(", "name", ")", "as", "scope", ":", "dcn", "=", "DeformableConv2D", "(", "filters", ",", "kernel_size", "=", "kernel_size", ",", "strides", "=", "strides", ",", "padding", "=", "\"same\"", ",", "use_bias", "=", "False", ",", "kernel_initializer", "=", "KERNEL_INIT", ",", "kernel_regularizer", "=", "tf", ".", "keras", ".", "regularizers", ".", "l2", "(", "L2_REG", ")", ",", ")", "(", "inputs", ")", "dcn", "=", "BatchNormalization", "(", ")", "(", "dcn", ")", "dcn", "=", "tf", ".", "keras", ".", "layers", ".", "Activation", "(", "activation", ")", "(", "dcn", ")", "dcn", "=", "tf", ".", "keras", ".", "layers", ".", "UpSampling2D", "(", "interpolation", "=", "\"bilinear\"", ")", "(", "dcn", ")", "# shortcut from backbone", "for", "i", "in", "range", "(", "shortcut_number", ")", ":", "bias", "=", "False", "if", "i", "<", "(", "shortcut_number", "-", "1", ")", "or", "mode", "==", "XModelMode", ".", "DCNSHORTCUTCONCAT", "else", "True", "shortcut", "=", "tf", ".", "keras", ".", "layers", ".", "Conv2D", "(", "filters", ",", "kernel_size", "=", "kernel_size", ",", "strides", "=", "strides", ",", "padding", "=", "\"same\"", ",", "use_bias", "=", "bias", ",", "kernel_initializer", "=", "KERNEL_INIT", ",", "kernel_regularizer", "=", "tf", ".", "keras", ".", "regularizers", ".", "l2", "(", "L2_REG", ")", ",", ")", "(", "shortcut", ")", "# do not call activation layer on the last output from shortcut", "if", "i", "<", "(", "shortcut_number", "-", "1", ")", "or", "mode", "==", "XModelMode", ".", "DCNSHORTCUTCONCAT", ":", "shortcut", "=", "BatchNormalization", "(", ")", "(", "shortcut", ")", "shortcut", "=", "tf", ".", "keras", ".", "layers", ".", "Activation", "(", "activation", ")", "(", "shortcut", ")", "if", "mode", "==", "XModelMode", ".", "DCNSHORTCUTCONCAT", ":", "return", "tf", ".", "keras", ".", "layers", ".", "Concatenate", "(", ")", "(", "[", "dcn", ",", "shortcut", "]", ")", "return", "dcn", "+", "shortcut" ]
[ 64, 0 ]
[ 127, 29 ]
python
en
['en', 'error', 'th']
False
deConv2DBatchNorm
(inputs, filters=128, kernel_size=(2, 2), strides=(2, 2), activation=ACTIVATION, name=None)
Deconvolution with BatchNormalization and activation :param inputs: input to the layer :param filters: number of filters from convoltuion, defaults to 128 :param kernel_size: kernel for convolution, defaults to (2, 2) :param strides: strides of convolution, defaults to (2, 2) :param name: name of the scope :return: output deconvolution layer
Deconvolution with BatchNormalization and activation :param inputs: input to the layer :param filters: number of filters from convoltuion, defaults to 128 :param kernel_size: kernel for convolution, defaults to (2, 2) :param strides: strides of convolution, defaults to (2, 2) :param name: name of the scope :return: output deconvolution layer
def deConv2DBatchNorm(inputs, filters=128, kernel_size=(2, 2), strides=(2, 2), activation=ACTIVATION, name=None): """ Deconvolution with BatchNormalization and activation :param inputs: input to the layer :param filters: number of filters from convoltuion, defaults to 128 :param kernel_size: kernel for convolution, defaults to (2, 2) :param strides: strides of convolution, defaults to (2, 2) :param name: name of the scope :return: output deconvolution layer """ with tf.name_scope(name) as scope: layer = tf.keras.layers.Conv2DTranspose( filters, kernel_size, strides=strides, padding="same", use_bias=False, kernel_initializer=KERNEL_INIT, kernel_regularizer=tf.keras.regularizers.l2(L2_REG), )(inputs) layer = BatchNormalization()(layer) layer = tf.keras.layers.Activation(activation)(layer) return layer
[ "def", "deConv2DBatchNorm", "(", "inputs", ",", "filters", "=", "128", ",", "kernel_size", "=", "(", "2", ",", "2", ")", ",", "strides", "=", "(", "2", ",", "2", ")", ",", "activation", "=", "ACTIVATION", ",", "name", "=", "None", ")", ":", "with", "tf", ".", "name_scope", "(", "name", ")", "as", "scope", ":", "layer", "=", "tf", ".", "keras", ".", "layers", ".", "Conv2DTranspose", "(", "filters", ",", "kernel_size", ",", "strides", "=", "strides", ",", "padding", "=", "\"same\"", ",", "use_bias", "=", "False", ",", "kernel_initializer", "=", "KERNEL_INIT", ",", "kernel_regularizer", "=", "tf", ".", "keras", ".", "regularizers", ".", "l2", "(", "L2_REG", ")", ",", ")", "(", "inputs", ")", "layer", "=", "BatchNormalization", "(", ")", "(", "layer", ")", "layer", "=", "tf", ".", "keras", ".", "layers", ".", "Activation", "(", "activation", ")", "(", "layer", ")", "return", "layer" ]
[ 130, 0 ]
[ 152, 20 ]
python
en
['en', 'error', 'th']
False
upsampleConcat
(filter_out1, filter_out2, z, p, activation=ACTIVATION, name=None)
Upsample output from convolution and merge it with another convolution :param filter_out1: number of upsampling filter :param filter_out2: number of output filter :param z: input to upsample :param p: input to merge with upsample :param name: name of the scope :return: upsampled output
Upsample output from convolution and merge it with another convolution :param filter_out1: number of upsampling filter :param filter_out2: number of output filter :param z: input to upsample :param p: input to merge with upsample :param name: name of the scope :return: upsampled output
def upsampleConcat(filter_out1, filter_out2, z, p, activation=ACTIVATION, name=None): """ Upsample output from convolution and merge it with another convolution :param filter_out1: number of upsampling filter :param filter_out2: number of output filter :param z: input to upsample :param p: input to merge with upsample :param name: name of the scope :return: upsampled output """ with tf.name_scope(name) as scope: x = tf.keras.layers.UpSampling2D()(z) x = tf.keras.layers.Conv2D( filter_out1, 1, padding="same", use_bias=False, kernel_initializer=KERNEL_INIT, kernel_regularizer=tf.keras.regularizers.l2(L2_REG), )(x) x = BatchNormalization()(x) x = tf.keras.layers.Activation(activation)(x) x = tf.keras.layers.Concatenate()([p, x]) x = tf.keras.layers.Conv2D( filter_out2, 3, padding="same", use_bias=False, kernel_initializer=KERNEL_INIT, kernel_regularizer=tf.keras.regularizers.l2(L2_REG), )(x) x = BatchNormalization()(x) x = tf.keras.layers.Activation(activation, name=name)(x) return x
[ "def", "upsampleConcat", "(", "filter_out1", ",", "filter_out2", ",", "z", ",", "p", ",", "activation", "=", "ACTIVATION", ",", "name", "=", "None", ")", ":", "with", "tf", ".", "name_scope", "(", "name", ")", "as", "scope", ":", "x", "=", "tf", ".", "keras", ".", "layers", ".", "UpSampling2D", "(", ")", "(", "z", ")", "x", "=", "tf", ".", "keras", ".", "layers", ".", "Conv2D", "(", "filter_out1", ",", "1", ",", "padding", "=", "\"same\"", ",", "use_bias", "=", "False", ",", "kernel_initializer", "=", "KERNEL_INIT", ",", "kernel_regularizer", "=", "tf", ".", "keras", ".", "regularizers", ".", "l2", "(", "L2_REG", ")", ",", ")", "(", "x", ")", "x", "=", "BatchNormalization", "(", ")", "(", "x", ")", "x", "=", "tf", ".", "keras", ".", "layers", ".", "Activation", "(", "activation", ")", "(", "x", ")", "x", "=", "tf", ".", "keras", ".", "layers", ".", "Concatenate", "(", ")", "(", "[", "p", ",", "x", "]", ")", "x", "=", "tf", ".", "keras", ".", "layers", ".", "Conv2D", "(", "filter_out2", ",", "3", ",", "padding", "=", "\"same\"", ",", "use_bias", "=", "False", ",", "kernel_initializer", "=", "KERNEL_INIT", ",", "kernel_regularizer", "=", "tf", ".", "keras", ".", "regularizers", ".", "l2", "(", "L2_REG", ")", ",", ")", "(", "x", ")", "x", "=", "BatchNormalization", "(", ")", "(", "x", ")", "x", "=", "tf", ".", "keras", ".", "layers", ".", "Activation", "(", "activation", ",", "name", "=", "name", ")", "(", "x", ")", "return", "x" ]
[ 155, 0 ]
[ 188, 16 ]
python
en
['en', 'error', 'th']
False
upsampleSum
(x, conv, filters=128, ratio=0.5, activation=ACTIVATION, name=None)
Upsample convolution layer and average it with another one with same shape. :param x: output from conv layer that should be upsampled :param conv: convolution layer to average :param filters: number of output filters, defaults to 128 :param ratio: ratio of the sum :param name: name of the scope :return: upsampled and merged output
Upsample convolution layer and average it with another one with same shape. :param x: output from conv layer that should be upsampled :param conv: convolution layer to average :param filters: number of output filters, defaults to 128 :param ratio: ratio of the sum :param name: name of the scope :return: upsampled and merged output
def upsampleSum(x, conv, filters=128, ratio=0.5, activation=ACTIVATION, name=None): """ Upsample convolution layer and average it with another one with same shape. :param x: output from conv layer that should be upsampled :param conv: convolution layer to average :param filters: number of output filters, defaults to 128 :param ratio: ratio of the sum :param name: name of the scope :return: upsampled and merged output """ with tf.name_scope(name) as scope: x_up = tf.keras.layers.UpSampling2D(size=(2, 2), interpolation="nearest")(x) p = (1.0 - ratio) * x_up + ratio * conv2DBatchNorm( conv, filters=filters, kernel_size=(1, 1), name="upsum" + name ) return p
[ "def", "upsampleSum", "(", "x", ",", "conv", ",", "filters", "=", "128", ",", "ratio", "=", "0.5", ",", "activation", "=", "ACTIVATION", ",", "name", "=", "None", ")", ":", "with", "tf", ".", "name_scope", "(", "name", ")", "as", "scope", ":", "x_up", "=", "tf", ".", "keras", ".", "layers", ".", "UpSampling2D", "(", "size", "=", "(", "2", ",", "2", ")", ",", "interpolation", "=", "\"nearest\"", ")", "(", "x", ")", "p", "=", "(", "1.0", "-", "ratio", ")", "*", "x_up", "+", "ratio", "*", "conv2DBatchNorm", "(", "conv", ",", "filters", "=", "filters", ",", "kernel_size", "=", "(", "1", ",", "1", ")", ",", "name", "=", "\"upsum\"", "+", "name", ")", "return", "p" ]
[ 191, 0 ]
[ 206, 16 ]
python
en
['en', 'error', 'th']
False
set_regularization
(model, kernel_regularizer=None, bias_regularizer=None)
Adds regularization to the all layers of the base model. :param model: base model :param kernel_regularizer: tf.keras.regularizers.*, defaults to None :param bias_regularizer: tf.keras.regularizers*, defaults to None :return: modified model with regularizations
Adds regularization to the all layers of the base model. :param model: base model :param kernel_regularizer: tf.keras.regularizers.*, defaults to None :param bias_regularizer: tf.keras.regularizers*, defaults to None :return: modified model with regularizations
def set_regularization(model, kernel_regularizer=None, bias_regularizer=None): """ Adds regularization to the all layers of the base model. :param model: base model :param kernel_regularizer: tf.keras.regularizers.*, defaults to None :param bias_regularizer: tf.keras.regularizers*, defaults to None :return: modified model with regularizations """ for layer in model.layers: if kernel_regularizer is not None and hasattr(layer, "kernel_regularizer"): layer.kernel_regularizer = kernel_regularizer if bias_regularizer is not None and hasattr(layer, "bias_regularizer"): layer.bias_regularizer = bias_regularizer out = tf.keras.models.model_from_json(model.to_json()) out.set_weights(model.get_weights()) return out
[ "def", "set_regularization", "(", "model", ",", "kernel_regularizer", "=", "None", ",", "bias_regularizer", "=", "None", ")", ":", "for", "layer", "in", "model", ".", "layers", ":", "if", "kernel_regularizer", "is", "not", "None", "and", "hasattr", "(", "layer", ",", "\"kernel_regularizer\"", ")", ":", "layer", ".", "kernel_regularizer", "=", "kernel_regularizer", "if", "bias_regularizer", "is", "not", "None", "and", "hasattr", "(", "layer", ",", "\"bias_regularizer\"", ")", ":", "layer", ".", "bias_regularizer", "=", "bias_regularizer", "out", "=", "tf", ".", "keras", ".", "models", ".", "model_from_json", "(", "model", ".", "to_json", "(", ")", ")", "out", ".", "set_weights", "(", "model", ".", "get_weights", "(", ")", ")", "return", "out" ]
[ 209, 0 ]
[ 226, 14 ]
python
en
['en', 'error', 'th']
False
TemplateCommand.handle_template
(self, template, subdir)
Determine where the app or project templates are. Use django.__path__[0] as the default because the Django install directory isn't known.
Determine where the app or project templates are. Use django.__path__[0] as the default because the Django install directory isn't known.
def handle_template(self, template, subdir): """ Determine where the app or project templates are. Use django.__path__[0] as the default because the Django install directory isn't known. """ if template is None: return os.path.join(django.__path__[0], 'conf', subdir) else: if template.startswith('file://'): template = template[7:] expanded_template = os.path.expanduser(template) expanded_template = os.path.normpath(expanded_template) if os.path.isdir(expanded_template): return expanded_template if self.is_url(template): # downloads the file and returns the path absolute_path = self.download(template) else: absolute_path = os.path.abspath(expanded_template) if os.path.exists(absolute_path): return self.extract(absolute_path) raise CommandError("couldn't handle %s template %s." % (self.app_or_project, template))
[ "def", "handle_template", "(", "self", ",", "template", ",", "subdir", ")", ":", "if", "template", "is", "None", ":", "return", "os", ".", "path", ".", "join", "(", "django", ".", "__path__", "[", "0", "]", ",", "'conf'", ",", "subdir", ")", "else", ":", "if", "template", ".", "startswith", "(", "'file://'", ")", ":", "template", "=", "template", "[", "7", ":", "]", "expanded_template", "=", "os", ".", "path", ".", "expanduser", "(", "template", ")", "expanded_template", "=", "os", ".", "path", ".", "normpath", "(", "expanded_template", ")", "if", "os", ".", "path", ".", "isdir", "(", "expanded_template", ")", ":", "return", "expanded_template", "if", "self", ".", "is_url", "(", "template", ")", ":", "# downloads the file and returns the path", "absolute_path", "=", "self", ".", "download", "(", "template", ")", "else", ":", "absolute_path", "=", "os", ".", "path", ".", "abspath", "(", "expanded_template", ")", "if", "os", ".", "path", ".", "exists", "(", "absolute_path", ")", ":", "return", "self", ".", "extract", "(", "absolute_path", ")", "raise", "CommandError", "(", "\"couldn't handle %s template %s.\"", "%", "(", "self", ".", "app_or_project", ",", "template", ")", ")" ]
[ 184, 4 ]
[ 208, 59 ]
python
en
['en', 'error', 'th']
False
TemplateCommand.download
(self, url)
Download the given URL and return the file name.
Download the given URL and return the file name.
def download(self, url): """ Download the given URL and return the file name. """ def cleanup_url(url): tmp = url.rstrip('/') filename = tmp.split('/')[-1] if url.endswith('/'): display_url = tmp + '/' else: display_url = url return filename, display_url prefix = 'django_%s_template_' % self.app_or_project tempdir = tempfile.mkdtemp(prefix=prefix, suffix='_download') self.paths_to_remove.append(tempdir) filename, display_url = cleanup_url(url) if self.verbosity >= 2: self.stdout.write('Downloading %s' % display_url) try: the_path, info = urlretrieve(url, os.path.join(tempdir, filename)) except OSError as e: raise CommandError("couldn't download URL %s to %s: %s" % (url, filename, e)) used_name = the_path.split('/')[-1] # Trying to get better name from response headers content_disposition = info.get('content-disposition') if content_disposition: _, params = cgi.parse_header(content_disposition) guessed_filename = params.get('filename') or used_name else: guessed_filename = used_name # Falling back to content type guessing ext = self.splitext(guessed_filename)[1] content_type = info.get('content-type') if not ext and content_type: ext = mimetypes.guess_extension(content_type) if ext: guessed_filename += ext # Move the temporary file to a filename that has better # chances of being recognized by the archive utils if used_name != guessed_filename: guessed_path = os.path.join(tempdir, guessed_filename) shutil.move(the_path, guessed_path) return guessed_path # Giving up return the_path
[ "def", "download", "(", "self", ",", "url", ")", ":", "def", "cleanup_url", "(", "url", ")", ":", "tmp", "=", "url", ".", "rstrip", "(", "'/'", ")", "filename", "=", "tmp", ".", "split", "(", "'/'", ")", "[", "-", "1", "]", "if", "url", ".", "endswith", "(", "'/'", ")", ":", "display_url", "=", "tmp", "+", "'/'", "else", ":", "display_url", "=", "url", "return", "filename", ",", "display_url", "prefix", "=", "'django_%s_template_'", "%", "self", ".", "app_or_project", "tempdir", "=", "tempfile", ".", "mkdtemp", "(", "prefix", "=", "prefix", ",", "suffix", "=", "'_download'", ")", "self", ".", "paths_to_remove", ".", "append", "(", "tempdir", ")", "filename", ",", "display_url", "=", "cleanup_url", "(", "url", ")", "if", "self", ".", "verbosity", ">=", "2", ":", "self", ".", "stdout", ".", "write", "(", "'Downloading %s'", "%", "display_url", ")", "try", ":", "the_path", ",", "info", "=", "urlretrieve", "(", "url", ",", "os", ".", "path", ".", "join", "(", "tempdir", ",", "filename", ")", ")", "except", "OSError", "as", "e", ":", "raise", "CommandError", "(", "\"couldn't download URL %s to %s: %s\"", "%", "(", "url", ",", "filename", ",", "e", ")", ")", "used_name", "=", "the_path", ".", "split", "(", "'/'", ")", "[", "-", "1", "]", "# Trying to get better name from response headers", "content_disposition", "=", "info", ".", "get", "(", "'content-disposition'", ")", "if", "content_disposition", ":", "_", ",", "params", "=", "cgi", ".", "parse_header", "(", "content_disposition", ")", "guessed_filename", "=", "params", ".", "get", "(", "'filename'", ")", "or", "used_name", "else", ":", "guessed_filename", "=", "used_name", "# Falling back to content type guessing", "ext", "=", "self", ".", "splitext", "(", "guessed_filename", ")", "[", "1", "]", "content_type", "=", "info", ".", "get", "(", "'content-type'", ")", "if", "not", "ext", "and", "content_type", ":", "ext", "=", "mimetypes", ".", "guess_extension", "(", "content_type", ")", "if", "ext", ":", "guessed_filename", "+=", "ext", "# Move the temporary file to a filename that has better", "# chances of being recognized by the archive utils", "if", "used_name", "!=", "guessed_filename", ":", "guessed_path", "=", "os", ".", "path", ".", "join", "(", "tempdir", ",", "guessed_filename", ")", "shutil", ".", "move", "(", "the_path", ",", "guessed_path", ")", "return", "guessed_path", "# Giving up", "return", "the_path" ]
[ 243, 4 ]
[ 295, 23 ]
python
en
['en', 'error', 'th']
False
TemplateCommand.splitext
(self, the_path)
Like os.path.splitext, but takes off .tar, too
Like os.path.splitext, but takes off .tar, too
def splitext(self, the_path): """ Like os.path.splitext, but takes off .tar, too """ base, ext = posixpath.splitext(the_path) if base.lower().endswith('.tar'): ext = base[-4:] + ext base = base[:-4] return base, ext
[ "def", "splitext", "(", "self", ",", "the_path", ")", ":", "base", ",", "ext", "=", "posixpath", ".", "splitext", "(", "the_path", ")", "if", "base", ".", "lower", "(", ")", ".", "endswith", "(", "'.tar'", ")", ":", "ext", "=", "base", "[", "-", "4", ":", "]", "+", "ext", "base", "=", "base", "[", ":", "-", "4", "]", "return", "base", ",", "ext" ]
[ 297, 4 ]
[ 305, 24 ]
python
en
['en', 'error', 'th']
False
TemplateCommand.extract
(self, filename)
Extract the given file to a temporary directory and return the path of the directory with the extracted content.
Extract the given file to a temporary directory and return the path of the directory with the extracted content.
def extract(self, filename): """ Extract the given file to a temporary directory and return the path of the directory with the extracted content. """ prefix = 'django_%s_template_' % self.app_or_project tempdir = tempfile.mkdtemp(prefix=prefix, suffix='_extract') self.paths_to_remove.append(tempdir) if self.verbosity >= 2: self.stdout.write('Extracting %s' % filename) try: archive.extract(filename, tempdir) return tempdir except (archive.ArchiveException, OSError) as e: raise CommandError("couldn't extract file %s to %s: %s" % (filename, tempdir, e))
[ "def", "extract", "(", "self", ",", "filename", ")", ":", "prefix", "=", "'django_%s_template_'", "%", "self", ".", "app_or_project", "tempdir", "=", "tempfile", ".", "mkdtemp", "(", "prefix", "=", "prefix", ",", "suffix", "=", "'_extract'", ")", "self", ".", "paths_to_remove", ".", "append", "(", "tempdir", ")", "if", "self", ".", "verbosity", ">=", "2", ":", "self", ".", "stdout", ".", "write", "(", "'Extracting %s'", "%", "filename", ")", "try", ":", "archive", ".", "extract", "(", "filename", ",", "tempdir", ")", "return", "tempdir", "except", "(", "archive", ".", "ArchiveException", ",", "OSError", ")", "as", "e", ":", "raise", "CommandError", "(", "\"couldn't extract file %s to %s: %s\"", "%", "(", "filename", ",", "tempdir", ",", "e", ")", ")" ]
[ 307, 4 ]
[ 322, 54 ]
python
en
['en', 'error', 'th']
False
TemplateCommand.is_url
(self, template)
Return True if the name looks like a URL.
Return True if the name looks like a URL.
def is_url(self, template): """Return True if the name looks like a URL.""" if ':' not in template: return False scheme = template.split(':', 1)[0].lower() return scheme in self.url_schemes
[ "def", "is_url", "(", "self", ",", "template", ")", ":", "if", "':'", "not", "in", "template", ":", "return", "False", "scheme", "=", "template", ".", "split", "(", "':'", ",", "1", ")", "[", "0", "]", ".", "lower", "(", ")", "return", "scheme", "in", "self", ".", "url_schemes" ]
[ 324, 4 ]
[ 329, 41 ]
python
en
['en', 'ig', 'en']
True
TemplateCommand.make_writeable
(self, filename)
Make sure that the file is writeable. Useful if our source is read-only.
Make sure that the file is writeable. Useful if our source is read-only.
def make_writeable(self, filename): """ Make sure that the file is writeable. Useful if our source is read-only. """ if not os.access(filename, os.W_OK): st = os.stat(filename) new_permissions = stat.S_IMODE(st.st_mode) | stat.S_IWUSR os.chmod(filename, new_permissions)
[ "def", "make_writeable", "(", "self", ",", "filename", ")", ":", "if", "not", "os", ".", "access", "(", "filename", ",", "os", ".", "W_OK", ")", ":", "st", "=", "os", ".", "stat", "(", "filename", ")", "new_permissions", "=", "stat", ".", "S_IMODE", "(", "st", ".", "st_mode", ")", "|", "stat", ".", "S_IWUSR", "os", ".", "chmod", "(", "filename", ",", "new_permissions", ")" ]
[ 331, 4 ]
[ 339, 47 ]
python
en
['en', 'error', 'th']
False
create_command
(name: str, **kwargs: Any)
Create an instance of the Command class with the given name.
Create an instance of the Command class with the given name.
def create_command(name: str, **kwargs: Any) -> Command: """ Create an instance of the Command class with the given name. """ module_path, class_name, summary = commands_dict[name] module = importlib.import_module(module_path) command_class = getattr(module, class_name) command = command_class(name=name, summary=summary, **kwargs) return command
[ "def", "create_command", "(", "name", ":", "str", ",", "*", "*", "kwargs", ":", "Any", ")", "->", "Command", ":", "module_path", ",", "class_name", ",", "summary", "=", "commands_dict", "[", "name", "]", "module", "=", "importlib", ".", "import_module", "(", "module_path", ")", "command_class", "=", "getattr", "(", "module", ",", "class_name", ")", "command", "=", "command_class", "(", "name", "=", "name", ",", "summary", "=", "summary", ",", "*", "*", "kwargs", ")", "return", "command" ]
[ 88, 0 ]
[ 97, 18 ]
python
en
['en', 'error', 'th']
False
get_similar_commands
(name: str)
Command name auto-correct.
Command name auto-correct.
def get_similar_commands(name: str) -> Optional[str]: """Command name auto-correct.""" from difflib import get_close_matches name = name.lower() close_commands = get_close_matches(name, commands_dict.keys()) if close_commands: return close_commands[0] else: return None
[ "def", "get_similar_commands", "(", "name", ":", "str", ")", "->", "Optional", "[", "str", "]", ":", "from", "difflib", "import", "get_close_matches", "name", "=", "name", ".", "lower", "(", ")", "close_commands", "=", "get_close_matches", "(", "name", ",", "commands_dict", ".", "keys", "(", ")", ")", "if", "close_commands", ":", "return", "close_commands", "[", "0", "]", "else", ":", "return", "None" ]
[ 100, 0 ]
[ 111, 19 ]
python
en
['en', 'sm', 'en']
True
_get_observations
( tasks: Sequence[task_if.Task], action_mapper=None, )
Encode the initial scene and the goal as arrays. Args: task: list of thift tasks. Returns: A tuple (scenes, objects, goals). scenes: uint8 array with shape (task, height, width). featurized_objects: list (length tasks) of FeaturizedObjects contianing float arrays of size (number scene objects, OBJECT_FEATURE_SIZE). goals: uint8 array with shape (task, 3). Each goal is encoded with three numbers: (obj_type1, obj_type2, rel). All three are less than MAX_GOAL. To be more presize, obj_types are less than MAX_OBJECT_TYPE and rel is less than MAX_RELATION.
Encode the initial scene and the goal as arrays.
def _get_observations( tasks: Sequence[task_if.Task], action_mapper=None, ) -> Tuple[np.ndarray, np.ndarray, np.ndarray]: """Encode the initial scene and the goal as arrays. Args: task: list of thift tasks. Returns: A tuple (scenes, objects, goals). scenes: uint8 array with shape (task, height, width). featurized_objects: list (length tasks) of FeaturizedObjects contianing float arrays of size (number scene objects, OBJECT_FEATURE_SIZE). goals: uint8 array with shape (task, 3). Each goal is encoded with three numbers: (obj_type1, obj_type2, rel). All three are less than MAX_GOAL. To be more presize, obj_types are less than MAX_OBJECT_TYPE and rel is less than MAX_RELATION. """ scenes = np.stack( [phyre.simulator.scene_to_raster(task.scene) for task in tasks]) featurized_objects = [ phyre.simulator.scene_to_featurized_objects(task.scene) for task in tasks ] goals = np.array([_encode_goal(task) for task in tasks], dtype=np.uint8) return (scenes, featurized_objects, goals)
[ "def", "_get_observations", "(", "tasks", ":", "Sequence", "[", "task_if", ".", "Task", "]", ",", "action_mapper", "=", "None", ",", ")", "->", "Tuple", "[", "np", ".", "ndarray", ",", "np", ".", "ndarray", ",", "np", ".", "ndarray", "]", ":", "scenes", "=", "np", ".", "stack", "(", "[", "phyre", ".", "simulator", ".", "scene_to_raster", "(", "task", ".", "scene", ")", "for", "task", "in", "tasks", "]", ")", "featurized_objects", "=", "[", "phyre", ".", "simulator", ".", "scene_to_featurized_objects", "(", "task", ".", "scene", ")", "for", "task", "in", "tasks", "]", "goals", "=", "np", ".", "array", "(", "[", "_encode_goal", "(", "task", ")", "for", "task", "in", "tasks", "]", ",", "dtype", "=", "np", ".", "uint8", ")", "return", "(", "scenes", ",", "featurized_objects", ",", "goals", ")" ]
[ 364, 0 ]
[ 392, 46 ]
python
en
['en', 'en', 'en']
True
initialize_simulator
(task_ids: Sequence[str], action_tier: str, drop_objs: Sequence[int] = ())
Initialize ActionSimulator for given tasks and tier.
Initialize ActionSimulator for given tasks and tier.
def initialize_simulator(task_ids: Sequence[str], action_tier: str, drop_objs: Sequence[int] = ()) -> ActionSimulator: """Initialize ActionSimulator for given tasks and tier.""" tasks = phyre.loader.load_compiled_task_list(task_ids) return ActionSimulator(tasks, action_tier, drop_objs=drop_objs)
[ "def", "initialize_simulator", "(", "task_ids", ":", "Sequence", "[", "str", "]", ",", "action_tier", ":", "str", ",", "drop_objs", ":", "Sequence", "[", "int", "]", "=", "(", ")", ")", "->", "ActionSimulator", ":", "tasks", "=", "phyre", ".", "loader", ".", "load_compiled_task_list", "(", "task_ids", ")", "return", "ActionSimulator", "(", "tasks", ",", "action_tier", ",", "drop_objs", "=", "drop_objs", ")" ]
[ 395, 0 ]
[ 400, 67 ]
python
en
['en', 'en', 'en']
True
SimulationStatus.is_solved
(self)
Whether the action solved the task.
Whether the action solved the task.
def is_solved(self) -> bool: """Whether the action solved the task.""" return (self is SimulationStatus.SOLVED or self is SimulationStatus.STABLY_SOLVED or self is SimulationStatus.UNSTABLY_SOLVED)
[ "def", "is_solved", "(", "self", ")", "->", "bool", ":", "return", "(", "self", "is", "SimulationStatus", ".", "SOLVED", "or", "self", "is", "SimulationStatus", ".", "STABLY_SOLVED", "or", "self", "is", "SimulationStatus", ".", "UNSTABLY_SOLVED", ")" ]
[ 53, 4 ]
[ 57, 57 ]
python
en
['en', 'en', 'en']
True
SimulationStatus.is_stably_solved
(self)
Whether the action is stable solution for the task. This only applies if the simulation was called with `stable` flag.
Whether the action is stable solution for the task.
def is_stably_solved(self) -> bool: """Whether the action is stable solution for the task. This only applies if the simulation was called with `stable` flag. """ return self is SimulationStatus.STABLY_SOLVED
[ "def", "is_stably_solved", "(", "self", ")", "->", "bool", ":", "return", "self", "is", "SimulationStatus", ".", "STABLY_SOLVED" ]
[ 59, 4 ]
[ 64, 53 ]
python
en
['en', 'en', 'en']
True
SimulationStatus.is_not_solved
(self)
Whether the action is valid, but doesn't solve the task.
Whether the action is valid, but doesn't solve the task.
def is_not_solved(self) -> bool: """Whether the action is valid, but doesn't solve the task.""" return self is SimulationStatus.NOT_SOLVED
[ "def", "is_not_solved", "(", "self", ")", "->", "bool", ":", "return", "self", "is", "SimulationStatus", ".", "NOT_SOLVED" ]
[ 66, 4 ]
[ 68, 50 ]
python
en
['en', 'en', 'en']
True
SimulationStatus.is_invalid
(self)
whether the action is invalid for the task.
whether the action is invalid for the task.
def is_invalid(self) -> bool: """whether the action is invalid for the task.""" return self is SimulationStatus.INVALID_INPUT
[ "def", "is_invalid", "(", "self", ")", "->", "bool", ":", "return", "self", "is", "SimulationStatus", ".", "INVALID_INPUT" ]
[ 70, 4 ]
[ 72, 53 ]
python
en
['en', 'en', 'en']
True