Code
stringlengths
103
85.9k
Summary
listlengths
0
94
Please provide a description of the function:def clean(file_, imports): modules_not_imported = compare_modules(file_, imports) re_remove = re.compile("|".join(modules_not_imported)) to_write = [] try: f = open_func(file_, "r+") except OSError: logging.error("Failed on file: {}"...
[ "Remove modules that aren't imported in project from file." ]
Please provide a description of the function:def read_requirements(fh, resolve=False): is_temp_file = not hasattr(fh, 'name') for num, line in enumerate(iter_lines(fh)): line = line.strip() if not line: # skip empty lines continue if line.startswith('#') or \...
[ "\n Reads requirements from a file like object and (optionally) from referenced files.\n :param fh: file like object to read from\n :param resolve: boolean. resolves referenced files.\n :return: generator\n " ]
Please provide a description of the function:def deprecated(reason, replacement, gone_in, issue=None): # type: (str, Optional[str], Optional[str], Optional[int]) -> None # Construct a nice message. # This is purposely eagerly formatted as we want it to appear as if someone # typed this entire mess...
[ "Helper to deprecate existing functionality.\n\n reason:\n Textual reason shown to the user about why this functionality has\n been deprecated.\n replacement:\n Textual suggestion shown to the user about what alternative\n functionality they can use.\n gone_in:\n The vers...
Please provide a description of the function:def _ipaddress_match(ipname, host_ip): # OpenSSL may add a trailing newline to a subjectAltName's IP address # Divergence from upstream: ipaddress can't handle byte str ip = ipaddress.ip_address(_to_unicode(ipname).rstrip()) return ip == host_ip
[ "Exact matching of IP addresses.\n\n RFC 6125 explicitly doesn't define an algorithm for this\n (section 1.7.2 - \"Out of Scope\").\n " ]
Please provide a description of the function:def set_metadata(candidates, traces, dependencies, pythons): metasets_mapping = _calculate_metasets_mapping( dependencies, pythons, copy.deepcopy(traces), ) for key, candidate in candidates.items(): candidate.markers = _format_metasets(metase...
[ "Add \"metadata\" to candidates based on the dependency tree.\n\n Metadata for a candidate includes markers and a specifier for Python\n version requirements.\n\n :param candidates: A key-candidate mapping. Candidates in the mapping will\n have their markers set.\n :param traces: A graph trace (p...
Please provide a description of the function:def _walk(top, topdown=True, onerror=None, followlinks=False): dirs = [] nondirs = [] # We may not have read permission for top, in which case we can't # get a list of the files the directory contains. os.walk # always suppressed the exception then...
[ "Like Python 3.5's implementation of os.walk() -- faster than\n the pre-Python 3.5 version as it uses scandir() internally.\n " ]
Please provide a description of the function:def request_encode_url(self, method, url, fields=None, headers=None, **urlopen_kw): if headers is None: headers = self.headers extra_kw = {'headers': headers} extra_kw.update(urlopen_kw) if fie...
[ "\n Make a request using :meth:`urlopen` with the ``fields`` encoded in\n the url. This is useful for request methods like GET, HEAD, DELETE, etc.\n " ]
Please provide a description of the function:def request_encode_body(self, method, url, fields=None, headers=None, encode_multipart=True, multipart_boundary=None, **urlopen_kw): if headers is None: headers = self.headers extra...
[ "\n Make a request using :meth:`urlopen` with the ``fields`` encoded in\n the body. This is useful for request methods like POST, PUT, PATCH, etc.\n\n When ``encode_multipart=True`` (default), then\n :meth:`urllib3.filepost.encode_multipart_formdata` is used to encode\n the payloa...
Please provide a description of the function:def pass_context(f): def new_func(*args, **kwargs): return f(get_current_context(), *args, **kwargs) return update_wrapper(new_func, f)
[ "Marks a callback as wanting to receive the current context\n object as first argument.\n " ]
Please provide a description of the function:def pass_obj(f): def new_func(*args, **kwargs): return f(get_current_context().obj, *args, **kwargs) return update_wrapper(new_func, f)
[ "Similar to :func:`pass_context`, but only pass the object on the\n context onwards (:attr:`Context.obj`). This is useful if that object\n represents the state of a nested system.\n " ]
Please provide a description of the function:def make_pass_decorator(object_type, ensure=False): def decorator(f): def new_func(*args, **kwargs): ctx = get_current_context() if ensure: obj = ctx.ensure_object(object_type) else: obj = c...
[ "Given an object type this creates a decorator that will work\n similar to :func:`pass_obj` but instead of passing the object of the\n current context, it will find the innermost context of type\n :func:`object_type`.\n\n This generates a decorator that works roughly like this::\n\n from functool...
Please provide a description of the function:def argument(*param_decls, **attrs): def decorator(f): ArgumentClass = attrs.pop('cls', Argument) _param_memo(f, ArgumentClass(param_decls, **attrs)) return f return decorator
[ "Attaches an argument to the command. All positional arguments are\n passed as parameter declarations to :class:`Argument`; all keyword\n arguments are forwarded unchanged (except ``cls``).\n This is equivalent to creating an :class:`Argument` instance manually\n and attaching it to the :attr:`Command....
Please provide a description of the function:def option(*param_decls, **attrs): def decorator(f): # Issue 926, copy attrs, so pre-defined options can re-use the same cls= option_attrs = attrs.copy() if 'help' in option_attrs: option_attrs['help'] = inspect.cleandoc(option_a...
[ "Attaches an option to the command. All positional arguments are\n passed as parameter declarations to :class:`Option`; all keyword\n arguments are forwarded unchanged (except ``cls``).\n This is equivalent to creating an :class:`Option` instance manually\n and attaching it to the :attr:`Command.params...
Please provide a description of the function:def confirmation_option(*param_decls, **attrs): def decorator(f): def callback(ctx, param, value): if not value: ctx.abort() attrs.setdefault('is_flag', True) attrs.setdefault('callback', callback) attrs.se...
[ "Shortcut for confirmation prompts that can be ignored by passing\n ``--yes`` as parameter.\n\n This is equivalent to decorating a function with :func:`option` with\n the following parameters::\n\n def callback(ctx, param, value):\n if not value:\n ctx.abort()\n\n @c...
Please provide a description of the function:def password_option(*param_decls, **attrs): def decorator(f): attrs.setdefault('prompt', True) attrs.setdefault('confirmation_prompt', True) attrs.setdefault('hide_input', True) return option(*(param_decls or ('--password',)), **attrs...
[ "Shortcut for password prompts.\n\n This is equivalent to decorating a function with :func:`option` with\n the following parameters::\n\n @click.command()\n @click.option('--password', prompt=True, confirmation_prompt=True,\n hide_input=True)\n def changeadmin(passwor...
Please provide a description of the function:def help_option(*param_decls, **attrs): def decorator(f): def callback(ctx, param, value): if value and not ctx.resilient_parsing: echo(ctx.get_help(), color=ctx.color) ctx.exit() attrs.setdefault('is_flag'...
[ "Adds a ``--help`` option which immediately ends the program\n printing out the help page. This is usually unnecessary to add as\n this is added by default to all commands unless suppressed.\n\n Like :func:`version_option`, this is implemented as eager option that\n prints in the callback and exits.\n\...
Please provide a description of the function:def was_installed_by_pip(pkg): # type: (str) -> bool try: dist = pkg_resources.get_distribution(pkg) return (dist.has_metadata('INSTALLER') and 'pip' in dist.get_metadata_lines('INSTALLER')) except pkg_resources.DistributionNo...
[ "Checks whether pkg was installed by pip\n\n This is used not to display the upgrade message when pip is in fact\n installed by system package manager, such as dnf on Fedora.\n " ]
Please provide a description of the function:def pip_version_check(session, options): # type: (PipSession, optparse.Values) -> None installed_version = get_installed_version("pip") if not installed_version: return pip_version = packaging_version.parse(installed_version) pypi_version = ...
[ "Check for an update for pip.\n\n Limit the frequency of checks to once per week. State is stored either in\n the active virtualenv or in the user's USER_CACHE_DIR keyed off the prefix\n of the pip script path.\n " ]
Please provide a description of the function:def get_abbr_impl(): # type: () -> str if hasattr(sys, 'pypy_version_info'): pyimpl = 'pp' elif sys.platform.startswith('java'): pyimpl = 'jy' elif sys.platform == 'cli': pyimpl = 'ip' else: pyimpl = 'cp' return py...
[ "Return abbreviated implementation name." ]
Please provide a description of the function:def get_impl_ver(): # type: () -> str impl_ver = get_config_var("py_version_nodot") if not impl_ver or get_abbr_impl() == 'pp': impl_ver = ''.join(map(str, get_impl_version_info())) return impl_ver
[ "Return implementation version." ]
Please provide a description of the function:def get_impl_version_info(): # type: () -> Tuple[int, ...] if get_abbr_impl() == 'pp': # as per https://github.com/pypa/pip/issues/2882 # attrs exist only on pypy return (sys.version_info[0], sys.pypy_version_info.major, ...
[ "Return sys.version_info-like tuple for use in decrementing the minor\n version." ]
Please provide a description of the function:def get_platform(): # type: () -> str if sys.platform == 'darwin': # distutils.util.get_platform() returns the release based on the value # of MACOSX_DEPLOYMENT_TARGET on which Python was built, which may # be significantly older than the...
[ "Return our platform name 'win32', 'linux_x86_64'" ]
Please provide a description of the function:def get_supported( versions=None, # type: Optional[List[str]] noarch=False, # type: bool platform=None, # type: Optional[str] impl=None, # type: Optional[str] abi=None # type: Optional[str] ): # type: (...) -> List[Pep425Tag] supported =...
[ "Return a list of supported tags for each version specified in\n `versions`.\n\n :param versions: a list of string versions, of the form [\"33\", \"32\"],\n or None. The first version will be assumed to support our ABI.\n :param platform: specify the exact platform you want valid\n tags for, ...
Please provide a description of the function:def get_netrc_auth(url, raise_errors=False): try: from netrc import netrc, NetrcParseError netrc_path = None for f in NETRC_FILES: try: loc = os.path.expanduser('~/{}'.format(f)) except KeyError: ...
[ "Returns the Requests tuple auth for a given url from netrc." ]
Please provide a description of the function:def guess_filename(obj): name = getattr(obj, 'name', None) if (name and isinstance(name, basestring) and name[0] != '<' and name[-1] != '>'): return os.path.basename(name)
[ "Tries to guess the filename of the given object." ]
Please provide a description of the function:def extract_zipped_paths(path): if os.path.exists(path): # this is already a valid path, no need to do anything further return path # find the first valid part of the provided path and treat that as a zip archive # assume the rest of the pat...
[ "Replace nonexistent paths that look like they refer to a member of a zip\n archive with the location of an extracted copy of the target, or else\n just return the provided path unchanged.\n " ]
Please provide a description of the function:def from_key_val_list(value): if value is None: return None if isinstance(value, (str, bytes, bool, int)): raise ValueError('cannot encode objects that are not 2-tuples') return OrderedDict(value)
[ "Take an object and test to see if it can be represented as a\n dictionary. Unless it can not be represented as such, return an\n OrderedDict, e.g.,\n\n ::\n\n >>> from_key_val_list([('key', 'val')])\n OrderedDict([('key', 'val')])\n >>> from_key_val_list('string')\n ValueError:...
Please provide a description of the function:def parse_list_header(value): result = [] for item in _parse_list_header(value): if item[:1] == item[-1:] == '"': item = unquote_header_value(item[1:-1]) result.append(item) return result
[ "Parse lists as described by RFC 2068 Section 2.\n\n In particular, parse comma-separated lists where the elements of\n the list may include quoted-strings. A quoted-string could\n contain a comma. A non-quoted string could have quotes in the\n middle. Quotes are removed automatically after parsing.\...
Please provide a description of the function:def parse_dict_header(value): result = {} for item in _parse_list_header(value): if '=' not in item: result[item] = None continue name, value = item.split('=', 1) if value[:1] == value[-1:] == '"': valu...
[ "Parse lists of key, value pairs as described by RFC 2068 Section 2 and\n convert them into a python dict:\n\n >>> d = parse_dict_header('foo=\"is a fish\", bar=\"as well\"')\n >>> type(d) is dict\n True\n >>> sorted(d.items())\n [('bar', 'as well'), ('foo', 'is a fish')]\n\n If there is no val...
Please provide a description of the function:def dict_from_cookiejar(cj): cookie_dict = {} for cookie in cj: cookie_dict[cookie.name] = cookie.value return cookie_dict
[ "Returns a key/value dictionary from a CookieJar.\n\n :param cj: CookieJar object to extract cookies from.\n :rtype: dict\n " ]
Please provide a description of the function:def _parse_content_type_header(header): tokens = header.split(';') content_type, params = tokens[0].strip(), tokens[1:] params_dict = {} items_to_strip = "\"' " for param in params: param = param.strip() if param: key, v...
[ "Returns content type and parameters from given header\n\n :param header: string\n :return: tuple containing content type and dictionary of\n parameters\n " ]
Please provide a description of the function:def get_encoding_from_headers(headers): content_type = headers.get('content-type') if not content_type: return None content_type, params = _parse_content_type_header(content_type) if 'charset' in params: return params['charset'].strip...
[ "Returns encodings from given HTTP Header Dict.\n\n :param headers: dictionary to extract encoding from.\n :rtype: str\n " ]
Please provide a description of the function:def iter_slices(string, slice_length): pos = 0 if slice_length is None or slice_length <= 0: slice_length = len(string) while pos < len(string): yield string[pos:pos + slice_length] pos += slice_length
[ "Iterate over slices of a string." ]
Please provide a description of the function:def get_unicode_from_response(r): warnings.warn(( 'In requests 3.0, get_unicode_from_response will be removed. For ' 'more information, please see the discussion on issue #2266. (This' ' warning should only appear once.)'), Deprecatio...
[ "Returns the requested content back in unicode.\n\n :param r: Response object to get unicode content from.\n\n Tried:\n\n 1. charset from content-type\n 2. fall back and replace all unicode characters\n\n :rtype: str\n " ]
Please provide a description of the function:def requote_uri(uri): safe_with_percent = "!#$%&'()*+,/:;=?@[]~" safe_without_percent = "!#$&'()*+,/:;=?@[]~" try: # Unquote only the unreserved characters # Then quote only illegal characters (do not quote reserved, # unreserved, or ...
[ "Re-quote the given URI.\n\n This function passes the given URI through an unquote/quote cycle to\n ensure that it is fully and consistently quoted.\n\n :rtype: str\n " ]
Please provide a description of the function:def address_in_network(ip, net): ipaddr = struct.unpack('=L', socket.inet_aton(ip))[0] netaddr, bits = net.split('/') netmask = struct.unpack('=L', socket.inet_aton(dotted_netmask(int(bits))))[0] network = struct.unpack('=L', socket.inet_aton(netaddr))[0...
[ "This function allows you to check if an IP belongs to a network subnet\n\n Example: returns True if ip = 192.168.1.1 and net = 192.168.1.0/24\n returns False if ip = 192.168.1.1 and net = 192.168.100.0/24\n\n :rtype: bool\n " ]
Please provide a description of the function:def is_valid_cidr(string_network): if string_network.count('/') == 1: try: mask = int(string_network.split('/')[1]) except ValueError: return False if mask < 1 or mask > 32: return False try: ...
[ "\n Very simple check of the cidr format in no_proxy variable.\n\n :rtype: bool\n " ]
Please provide a description of the function:def set_environ(env_name, value): value_changed = value is not None if value_changed: old_value = os.environ.get(env_name) os.environ[env_name] = value try: yield finally: if value_changed: if old_value is None...
[ "Set the environment variable 'env_name' to 'value'\n\n Save previous value, yield, and then restore the previous value stored in\n the environment variable 'env_name'.\n\n If 'value' is None, do nothing" ]
Please provide a description of the function:def should_bypass_proxies(url, no_proxy): # Prioritize lowercase environment variables over uppercase # to keep a consistent behaviour with other http projects (curl, wget). get_proxy = lambda k: os.environ.get(k) or os.environ.get(k.upper()) # First ch...
[ "\n Returns whether we should bypass proxies or not.\n\n :rtype: bool\n " ]
Please provide a description of the function:def select_proxy(url, proxies): proxies = proxies or {} urlparts = urlparse(url) if urlparts.hostname is None: return proxies.get(urlparts.scheme, proxies.get('all')) proxy_keys = [ urlparts.scheme + '://' + urlparts.hostname, ur...
[ "Select a proxy for the url, if applicable.\n\n :param url: The url being for the request\n :param proxies: A dictionary of schemes or schemes and hosts to proxy URLs\n " ]
Please provide a description of the function:def prepend_scheme_if_needed(url, new_scheme): scheme, netloc, path, params, query, fragment = urlparse(url, new_scheme) # urlparse is a finicky beast, and sometimes decides that there isn't a # netloc present. Assume that it's being over-cautious, and swit...
[ "Given a URL that may or may not have a scheme, prepend the given scheme.\n Does not replace a present scheme with the one provided as an argument.\n\n :rtype: str\n " ]
Please provide a description of the function:def get_auth_from_url(url): parsed = urlparse(url) try: auth = (unquote(parsed.username), unquote(parsed.password)) except (AttributeError, TypeError): auth = ('', '') return auth
[ "Given a url with authentication components, extract them into a tuple of\n username,password.\n\n :rtype: (str,str)\n " ]
Please provide a description of the function:def check_header_validity(header): name, value = header if isinstance(value, bytes): pat = _CLEAN_HEADER_REGEX_BYTE else: pat = _CLEAN_HEADER_REGEX_STR try: if not pat.match(value): raise InvalidHeader("Invalid return...
[ "Verifies that header value is a string which doesn't contain\n leading whitespace or return characters. This prevents unintended\n header injection.\n\n :param header: tuple, in the format (name, value).\n " ]
Please provide a description of the function:def urldefragauth(url): scheme, netloc, path, params, query, fragment = urlparse(url) # see func:`prepend_scheme_if_needed` if not netloc: netloc, path = path, netloc netloc = netloc.rsplit('@', 1)[-1] return urlunparse((scheme, netloc, pa...
[ "\n Given a url remove the fragment and the authentication part.\n\n :rtype: str\n " ]
Please provide a description of the function:def rewind_body(prepared_request): body_seek = getattr(prepared_request.body, 'seek', None) if body_seek is not None and isinstance(prepared_request._body_position, integer_types): try: body_seek(prepared_request._body_position) excep...
[ "Move file pointer back to its recorded starting position\n so it can be read again on redirect.\n " ]
Please provide a description of the function:def canonicalize_version(version): try: version = Version(version) except InvalidVersion: # Legacy versions cannot be normalized return version parts = [] # Epoch if version.epoch != 0: parts.append("{0}!".format(ve...
[ "\n This is very similar to Version.__str__, but has one subtle differences\n with the way it handles the release segment.\n " ]
Please provide a description of the function:def generate(node, environment, name, filename, stream=None, defer_init=False, optimized=True): if not isinstance(node, nodes.Template): raise TypeError('Can\'t compile non template nodes') generator = environment.code_generator_class(enviro...
[ "Generate the python source for a node tree." ]
Please provide a description of the function:def has_safe_repr(value): if value is None or value is NotImplemented or value is Ellipsis: return True if type(value) in (bool, int, float, complex, range_type, Markup) + string_types: return True if type(value) in (tuple, list, set, frozens...
[ "Does the node have a safe representation?" ]
Please provide a description of the function:def find_undeclared(nodes, names): visitor = UndeclaredNameVisitor(names) try: for node in nodes: visitor.visit(node) except VisitorExit: pass return visitor.undeclared
[ "Check if the names passed are accessed undeclared. The return value\n is a set of all the undeclared names from the sequence of names found.\n " ]
Please provide a description of the function:def copy(self): rv = object.__new__(self.__class__) rv.__dict__.update(self.__dict__) rv.symbols = self.symbols.copy() return rv
[ "Create a copy of the current one." ]
Please provide a description of the function:def inner(self, isolated=False): if isolated: return Frame(self.eval_ctx, level=self.symbols.level + 1) return Frame(self.eval_ctx, self)
[ "Return an inner frame." ]
Please provide a description of the function:def fail(self, msg, lineno): raise TemplateAssertionError(msg, lineno, self.name, self.filename)
[ "Fail with a :exc:`TemplateAssertionError`." ]
Please provide a description of the function:def buffer(self, frame): frame.buffer = self.temporary_identifier() self.writeline('%s = []' % frame.buffer)
[ "Enable buffering for the frame from that point onwards." ]
Please provide a description of the function:def return_buffer_contents(self, frame, force_unescaped=False): if not force_unescaped: if frame.eval_ctx.volatile: self.writeline('if context.eval_ctx.autoescape:') self.indent() self.writeline('re...
[ "Return the buffer contents of the frame." ]
Please provide a description of the function:def start_write(self, frame, node=None): if frame.buffer is None: self.writeline('yield ', node) else: self.writeline('%s.append(' % frame.buffer, node)
[ "Yield or write into the frame buffer." ]
Please provide a description of the function:def simple_write(self, s, frame, node=None): self.start_write(frame, node) self.write(s) self.end_write(frame)
[ "Simple shortcut for start_write + write + end_write." ]
Please provide a description of the function:def write(self, x): if self._new_lines: if not self._first_write: self.stream.write('\n' * self._new_lines) self.code_lineno += self._new_lines if self._write_debug_info is not None: ...
[ "Write a string into the output stream." ]
Please provide a description of the function:def writeline(self, x, node=None, extra=0): self.newline(node, extra) self.write(x)
[ "Combination of newline and write." ]
Please provide a description of the function:def newline(self, node=None, extra=0): self._new_lines = max(self._new_lines, 1 + extra) if node is not None and node.lineno != self._last_line: self._write_debug_info = node.lineno self._last_line = node.lineno
[ "Add one or more newlines before the next write." ]
Please provide a description of the function:def signature(self, node, frame, extra_kwargs=None): # if any of the given keyword arguments is a python keyword # we have to make sure that no invalid call is created. kwarg_workaround = False for kwarg in chain((x.key for x in node....
[ "Writes a function call to the stream for the current node.\n A leading comma is added automatically. The extra keyword\n arguments may not include python keywords otherwise a syntax\n error could occour. The extra keyword arguments should be given\n as python dict.\n " ]
Please provide a description of the function:def pull_dependencies(self, nodes): visitor = DependencyFinderVisitor() for node in nodes: visitor.visit(node) for dependency in 'filters', 'tests': mapping = getattr(self, dependency) for name in getattr(v...
[ "Pull all the dependencies." ]
Please provide a description of the function:def macro_body(self, node, frame): frame = frame.inner() frame.symbols.analyze_node(node) macro_ref = MacroRef(node) explicit_caller = None skip_special_params = set() args = [] for idx, arg in enumerate(node....
[ "Dump the function def of a macro or call block." ]
Please provide a description of the function:def macro_def(self, macro_ref, frame): arg_tuple = ', '.join(repr(x.name) for x in macro_ref.node.args) name = getattr(macro_ref.node, 'name', None) if len(macro_ref.node.args) == 1: arg_tuple += ',' self.write('Macro(envi...
[ "Dump the macro definition for the def created by macro_body." ]
Please provide a description of the function:def position(self, node): rv = 'line %d' % node.lineno if self.name is not None: rv += ' in ' + repr(self.name) return rv
[ "Return a human readable position for the node." ]
Please provide a description of the function:def pop_assign_tracking(self, frame): vars = self._assign_stack.pop() if not frame.toplevel or not vars: return public_names = [x for x in vars if x[:1] != '_'] if len(vars) == 1: name = next(iter(vars)) ...
[ "Pops the topmost level for assignment tracking and updates the\n context variables if necessary.\n " ]
Please provide a description of the function:def visit_Block(self, node, frame): level = 0 if frame.toplevel: # if we know that we are a child template, there is no need to # check if we are one if self.has_known_extends: return if...
[ "Call a block and register it for the template." ]
Please provide a description of the function:def visit_Extends(self, node, frame): if not frame.toplevel: self.fail('cannot use extend from a non top-level scope', node.lineno) # if the number of extends statements in general is zero so # far, we don't...
[ "Calls the extender." ]
Please provide a description of the function:def visit_Include(self, node, frame): if node.ignore_missing: self.writeline('try:') self.indent() func_name = 'get_or_select_template' if isinstance(node.template, nodes.Const): if isinstance(node.templat...
[ "Handles includes." ]
Please provide a description of the function:def visit_Import(self, node, frame): self.writeline('%s = ' % frame.symbols.ref(node.target), node) if frame.toplevel: self.write('context.vars[%r] = ' % node.target) if self.environment.is_async: self.write('await ') ...
[ "Visit regular imports." ]
Please provide a description of the function:def visit_FromImport(self, node, frame): self.newline(node) self.write('included_template = %senvironment.get_template(' % (self.environment.is_async and 'await ' or '')) self.visit(node.template, frame) self.write(...
[ "Visit named imports." ]
Please provide a description of the function:def detach(self): info = self._registry.get(self) obj = info and info.weakref() if obj is not None and self._registry.pop(self, None): return (obj, info.func, info.args, info.kwargs or {})
[ "If alive then mark as dead and return (obj, func, args, kwargs);\n otherwise return None" ]
Please provide a description of the function:def peek(self): info = self._registry.get(self) obj = info and info.weakref() if obj is not None: return (obj, info.func, info.args, info.kwargs or {})
[ "If alive then return (obj, func, args, kwargs);\n otherwise return None" ]
Please provide a description of the function:def atexit(self): info = self._registry.get(self) return bool(info) and info.atexit
[ "Whether finalizer should be called at exit" ]
Please provide a description of the function:def tostring(element): rv = [] def serializeElement(element): if not hasattr(element, "tag"): if element.docinfo.internalDTD: if element.docinfo.doctype: dtd_str = element.docinfo.doctype e...
[ "Serialize an element and its child nodes to a string" ]
Please provide a description of the function:def get_visitor(self, node): method = 'visit_' + node.__class__.__name__ return getattr(self, method, None)
[ "Return the visitor function for this node or `None` if no visitor\n exists for this node. In that case the generic visit function is\n used instead.\n " ]
Please provide a description of the function:def visit(self, node, *args, **kwargs): f = self.get_visitor(node) if f is not None: return f(node, *args, **kwargs) return self.generic_visit(node, *args, **kwargs)
[ "Visit a node." ]
Please provide a description of the function:def generic_visit(self, node, *args, **kwargs): for node in node.iter_child_nodes(): self.visit(node, *args, **kwargs)
[ "Called if no explicit visitor function exists for a node." ]
Please provide a description of the function:def visit_list(self, node, *args, **kwargs): rv = self.visit(node, *args, **kwargs) if not isinstance(rv, list): rv = [rv] return rv
[ "As transformers may return lists in some places this method\n can be used to enforce a list as return value.\n " ]
Please provide a description of the function:def default_subprocess_runner(cmd, cwd=None, extra_environ=None): env = os.environ.copy() if extra_environ: env.update(extra_environ) check_call(cmd, cwd=cwd, env=env)
[ "The default method of calling the wrapper subprocess." ]
Please provide a description of the function:def build_wheel( self, wheel_directory, config_settings=None, metadata_directory=None): if metadata_directory is not None: metadata_directory = abspath(metadata_directory) return self._call_hook('build_wheel', { ...
[ "Build a wheel from this project.\n\n Returns the name of the newly created file.\n\n In general, this will call the 'build_wheel' hook in the backend.\n However, if that was previously called by\n 'prepare_metadata_for_build_wheel', and the same metadata_directory is\n used, the ...
Please provide a description of the function:def bninception(num_classes=1000, pretrained='imagenet'): r model = BNInception(num_classes=num_classes) if pretrained is not None: settings = pretrained_settings['bninception'][pretrained] assert num_classes == settings['num_classes'], \ ...
[ "BNInception model architecture from <https://arxiv.org/pdf/1502.03167.pdf>`_ paper.\n " ]
Please provide a description of the function:def conv3x3(in_planes, out_planes, stride=1): "3x3 convolution with padding" return nn.Conv2d(in_planes, out_planes, kernel_size=3, stride=stride, padding=1, bias=True)
[]
Please provide a description of the function:def resnet18(pretrained=False, **kwargs): model = ResNet(BasicBlock, [2, 2, 2, 2], **kwargs) if pretrained: model.load_state_dict(model_zoo.load_url(model_urls['resnet18'])) return model
[ "Constructs a ResNet-18 model.\n\n Args:\n pretrained (bool): If True, returns a model pre-trained on ImageNet\n " ]
Please provide a description of the function:def resnet50(pretrained=False, **kwargs): model = ResNet(Bottleneck, [3, 4, 6, 3], **kwargs) if pretrained: model.load_state_dict(model_zoo.load_url(model_urls['resnet50'])) return model
[ "Constructs a ResNet-50 model.\n\n Args:\n pretrained (bool): If True, returns a model pre-trained on ImageNet\n " ]
Please provide a description of the function:def cafferesnet101(num_classes=1000, pretrained='imagenet'): model = ResNet(Bottleneck, [3, 4, 23, 3], num_classes=num_classes) if pretrained is not None: settings = pretrained_settings['cafferesnet101'][pretrained] assert num_classes == settings...
[ "Constructs a ResNet-101 model.\n Args:\n pretrained (bool): If True, returns a model pre-trained on ImageNet\n " ]
Please provide a description of the function:def fbresnet152(num_classes=1000, pretrained='imagenet'): model = FBResNet(Bottleneck, [3, 8, 36, 3], num_classes=num_classes) if pretrained is not None: settings = pretrained_settings['fbresnet152'][pretrained] assert num_classes == settings['nu...
[ "Constructs a ResNet-152 model.\n\n Args:\n pretrained (bool): If True, returns a model pre-trained on ImageNet\n " ]
Please provide a description of the function:def alexnet(num_classes=1000, pretrained='imagenet'): r # https://github.com/pytorch/vision/blob/master/torchvision/models/alexnet.py model = models.alexnet(pretrained=False) if pretrained is not None: settings = pretrained_settings['alexnet'][pretrai...
[ "AlexNet model architecture from the\n `\"One weird trick...\" <https://arxiv.org/abs/1404.5997>`_ paper.\n " ]
Please provide a description of the function:def densenet121(num_classes=1000, pretrained='imagenet'): r model = models.densenet121(pretrained=False) if pretrained is not None: settings = pretrained_settings['densenet121'][pretrained] model = load_pretrained(model, num_classes, settings) ...
[ "Densenet-121 model from\n `\"Densely Connected Convolutional Networks\" <https://arxiv.org/pdf/1608.06993.pdf>`\n " ]
Please provide a description of the function:def inceptionv3(num_classes=1000, pretrained='imagenet'): r model = models.inception_v3(pretrained=False) if pretrained is not None: settings = pretrained_settings['inceptionv3'][pretrained] model = load_pretrained(model, num_classes, settings) ...
[ "Inception v3 model architecture from\n `\"Rethinking the Inception Architecture for Computer Vision\" <http://arxiv.org/abs/1512.00567>`_.\n " ]
Please provide a description of the function:def resnet50(num_classes=1000, pretrained='imagenet'): model = models.resnet50(pretrained=False) if pretrained is not None: settings = pretrained_settings['resnet50'][pretrained] model = load_pretrained(model, num_classes, settings) model = m...
[ "Constructs a ResNet-50 model.\n " ]
Please provide a description of the function:def squeezenet1_0(num_classes=1000, pretrained='imagenet'): r model = models.squeezenet1_0(pretrained=False) if pretrained is not None: settings = pretrained_settings['squeezenet1_0'][pretrained] model = load_pretrained(model, num_classes, setting...
[ "SqueezeNet model architecture from the `\"SqueezeNet: AlexNet-level\n accuracy with 50x fewer parameters and <0.5MB model size\"\n <https://arxiv.org/abs/1602.07360>`_ paper.\n " ]
Please provide a description of the function:def vgg11(num_classes=1000, pretrained='imagenet'): model = models.vgg11(pretrained=False) if pretrained is not None: settings = pretrained_settings['vgg11'][pretrained] model = load_pretrained(model, num_classes, settings) model = modify_vgg...
[ "VGG 11-layer model (configuration \"A\")\n " ]
Please provide a description of the function:def adjust_learning_rate(optimizer, epoch): lr = args.lr * (0.1 ** (epoch // 30)) for param_group in optimizer.param_groups: param_group['lr'] = lr
[ "Sets the learning rate to the initial LR decayed by 10 every 30 epochs" ]
Please provide a description of the function:def nasnetalarge(num_classes=1001, pretrained='imagenet'): r if pretrained: settings = pretrained_settings['nasnetalarge'][pretrained] assert num_classes == settings['num_classes'], \ "num_classes should be {}, but is {}".format(settings['...
[ "NASNetALarge model architecture from the\n `\"NASNet\" <https://arxiv.org/abs/1707.07012>`_ paper.\n " ]
Please provide a description of the function:def adaptive_avgmax_pool2d(x, pool_type='avg', padding=0, count_include_pad=False): if pool_type == 'avgmaxc': x = torch.cat([ F.avg_pool2d( x, kernel_size=(x.size(2), x.size(3)), padding=padding, count_include_pad=count_include_p...
[ "Selectable global pooling function with dynamic input kernel size\n " ]
Please provide a description of the function:def download_url(url, destination=None, progress_bar=True): def my_hook(t): last_b = [0] def inner(b=1, bsize=1, tsize=None): if tsize is not None: t.total = tsize if b > 0: t.update((b - last...
[ "Download a URL to a local file.\n\n Parameters\n ----------\n url : str\n The URL to download.\n destination : str, None\n The destination of the file. If None is given the file is saved to a temporary directory.\n progress_bar : bool\n Whether to show a command-line progress ba...
Please provide a description of the function:def add(self, output, target): if not torch.is_tensor(output): output = torch.from_numpy(output) if not torch.is_tensor(target): target = torch.from_numpy(target) if output.dim() == 1: output = output.view...
[ "\n Args:\n output (Tensor): NxK tensor that for each of the N examples\n indicates the probability of the example belonging to each of\n the K classes, according to the model. The probabilities should\n sum to one over all classes\n target (...
Please provide a description of the function:def value(self): if self.scores.numel() == 0: return 0 ap = torch.zeros(self.scores.size(1)) rg = torch.arange(1, self.scores.size(0)).float() # compute average precision for each class for k in range(self.scores...
[ "Returns the model's average precision for each class\n Return:\n ap (FloatTensor): 1xK tensor, with avg precision for each class k\n " ]
Please provide a description of the function:def polynet(num_classes=1000, pretrained='imagenet'): if pretrained: settings = pretrained_settings['polynet'][pretrained] assert num_classes == settings['num_classes'], \ 'num_classes should be {}, but is {}'.format( sett...
[ "PolyNet architecture from the paper\n 'PolyNet: A Pursuit of Structural Diversity in Very Deep Networks'\n https://arxiv.org/abs/1611.05725\n " ]
Please provide a description of the function:def unwrap(self, dt): expires = self._expires if expires is AlwaysExpired or expires < dt: raise Expired(self._expires) return self._value
[ "\n Get the cached value.\n\n Returns\n -------\n value : object\n The cached value.\n\n Raises\n ------\n Expired\n Raised when `dt` is greater than self.expires.\n " ]