Code stringlengths 103 85.9k | Summary listlengths 0 94 |
|---|---|
Please provide a description of the function:def _check_unpack_options(extensions, function, extra_args):
# first make sure no other unpacker is registered for this extension
existing_extensions = {}
for name, info in _UNPACK_FORMATS.items():
for ext in info[0]:
existing_extensions[... | [
"Checks what gets registered as an unpacker."
] |
Please provide a description of the function:def register_unpack_format(name, extensions, function, extra_args=None,
description=''):
if extra_args is None:
extra_args = []
_check_unpack_options(extensions, function, extra_args)
_UNPACK_FORMATS[name] = extensions, fun... | [
"Registers an unpack format.\n\n `name` is the name of the format. `extensions` is a list of extensions\n corresponding to the format.\n\n `function` is the callable that will be\n used to unpack archives. The callable will receive archives to unpack.\n If it's unable to handle an archive, it needs t... |
Please provide a description of the function:def _ensure_directory(path):
dirname = os.path.dirname(path)
if not os.path.isdir(dirname):
os.makedirs(dirname) | [
"Ensure that the parent directory of `path` exists"
] |
Please provide a description of the function:def _unpack_zipfile(filename, extract_dir):
try:
import zipfile
except ImportError:
raise ReadError('zlib not supported, cannot unpack this archive.')
if not zipfile.is_zipfile(filename):
raise ReadError("%s is not a zip file" % file... | [
"Unpack zip `filename` to `extract_dir`\n "
] |
Please provide a description of the function:def _unpack_tarfile(filename, extract_dir):
try:
tarobj = tarfile.open(filename)
except tarfile.TarError:
raise ReadError(
"%s is not a compressed or uncompressed tar file" % filename)
try:
tarobj.extractall(extract_dir)
... | [
"Unpack tar/tar.gz/tar.bz2 `filename` to `extract_dir`\n "
] |
Please provide a description of the function:def unpack_archive(filename, extract_dir=None, format=None):
if extract_dir is None:
extract_dir = os.getcwd()
if format is not None:
try:
format_info = _UNPACK_FORMATS[format]
except KeyError:
raise ValueError("U... | [
"Unpack an archive.\n\n `filename` is the name of the archive.\n\n `extract_dir` is the name of the target directory, where the archive\n is unpacked. If not provided, the current working directory is used.\n\n `format` is the archive format: one of \"zip\", \"tar\", or \"gztar\". Or any\n other regi... |
Please provide a description of the function:def parseFragment(doc, container="div", treebuilder="etree", namespaceHTMLElements=True, **kwargs):
tb = treebuilders.getTreeBuilder(treebuilder)
p = HTMLParser(tb, namespaceHTMLElements=namespaceHTMLElements)
return p.parseFragment(doc, container=container,... | [
"Parse an HTML fragment as a string or file-like object into a tree\n\n :arg doc: the fragment to parse as a string or file-like object\n\n :arg container: the container context to parse the fragment in\n\n :arg treebuilder: the treebuilder to use when parsing\n\n :arg namespaceHTMLElements: whether or ... |
Please provide a description of the function:def parse(self, stream, *args, **kwargs):
self._parse(stream, False, None, *args, **kwargs)
return self.tree.getDocument() | [
"Parse a HTML document into a well-formed tree\n\n :arg stream: a file-like object or string containing the HTML to be parsed\n\n The optional encoding parameter must be a string that indicates\n the encoding. If specified, that encoding will be used,\n regardless of any BOM... |
Please provide a description of the function:def parseFragment(self, stream, *args, **kwargs):
self._parse(stream, True, *args, **kwargs)
return self.tree.getFragment() | [
"Parse a HTML fragment into a well-formed tree fragment\n\n :arg container: name of the element we're setting the innerHTML\n property if set to None, default to 'div'\n\n :arg stream: a file-like object or string containing the HTML to be parsed\n\n The optional encoding paramet... |
Please provide a description of the function:def construct_tree(index):
return dict((p, [ReqPackage(r, index.get(r.key))
for r in p.requires()])
for p in index.values()) | [
"Construct tree representation of the pkgs from the index.\n\n The keys of the dict representing the tree will be objects of type\n DistPackage and the values will be list of ReqPackage objects.\n\n :param dict index: dist index ie. index of pkgs by their keys\n :returns: tree of pkgs and their dependen... |
Please provide a description of the function:def sorted_tree(tree):
return OrderedDict(sorted([(k, sorted(v, key=attrgetter('key')))
for k, v in tree.items()],
key=lambda kv: kv[0].key)) | [
"Sorts the dict representation of the tree\n\n The root packages as well as the intermediate packages are sorted\n in the alphabetical order of the package names.\n\n :param dict tree: the pkg dependency tree obtained by calling\n `construct_tree` function\n :returns: sorted tree\n ... |
Please provide a description of the function:def find_tree_root(tree, key):
result = [p for p in tree.keys() if p.key == key]
assert len(result) in [0, 1]
return None if len(result) == 0 else result[0] | [
"Find a root in a tree by it's key\n\n :param dict tree: the pkg dependency tree obtained by calling\n `construct_tree` function\n :param str key: key of the root node to find\n :returns: a root node if found else None\n :rtype: mixed\n\n "
] |
Please provide a description of the function:def reverse_tree(tree):
rtree = defaultdict(list)
child_keys = set(c.key for c in flatten(tree.values()))
for k, vs in tree.items():
for v in vs:
node = find_tree_root(rtree, v.key) or v
rtree[node].append(k.as_required_by(v))... | [
"Reverse the dependency tree.\n\n ie. the keys of the resulting dict are objects of type\n ReqPackage and the values are lists of DistPackage objects.\n\n :param dict tree: the pkg dependency tree obtained by calling\n `construct_tree` function\n :returns: reversed tree\n :rtype:... |
Please provide a description of the function:def guess_version(pkg_key, default='?'):
try:
m = import_module(pkg_key)
except ImportError:
return default
else:
return getattr(m, '__version__', default) | [
"Guess the version of a pkg when pip doesn't provide it\n\n :param str pkg_key: key of the package\n :param str default: default version to return if unable to find\n :returns: version\n :rtype: string\n\n "
] |
Please provide a description of the function:def render_tree(tree, list_all=True, show_only=None, frozen=False, exclude=None):
tree = sorted_tree(tree)
branch_keys = set(r.key for r in flatten(tree.values()))
nodes = tree.keys()
use_bullets = not frozen
key_tree = dict((k.key, v) for k, v in t... | [
"Convert tree to string representation\n\n :param dict tree: the package tree\n :param bool list_all: whether to list all the pgks at the root\n level or only those that are the\n sub-dependencies\n :param set show_only: set of select packages to be shown i... |
Please provide a description of the function:def render_json(tree, indent):
return json.dumps([{'package': k.as_dict(),
'dependencies': [v.as_dict() for v in vs]}
for k, vs in tree.items()],
indent=indent) | [
"Converts the tree into a flat json representation.\n\n The json repr will be a list of hashes, each hash having 2 fields:\n - package\n - dependencies: list of dependencies\n\n :param dict tree: dependency tree\n :param int indent: no. of spaces to indent json\n :returns: json representation ... |
Please provide a description of the function:def render_json_tree(tree, indent):
tree = sorted_tree(tree)
branch_keys = set(r.key for r in flatten(tree.values()))
nodes = [p for p in tree.keys() if p.key not in branch_keys]
key_tree = dict((k.key, v) for k, v in tree.items())
get_children = lam... | [
"Converts the tree into a nested json representation.\n\n The json repr will be a list of hashes, each hash having the following fields:\n - package_name\n - key\n - required_version\n - installed_version\n - dependencies: list of dependencies\n\n :param dict tree: dependency tree\n ... |
Please provide a description of the function:def dump_graphviz(tree, output_format='dot'):
try:
from graphviz import backend, Digraph
except ImportError:
print('graphviz is not available, but necessary for the output '
'option. Please install it.', file=sys.stderr)
sys... | [
"Output dependency graph as one of the supported GraphViz output formats.\n\n :param dict tree: dependency graph\n :param string output_format: output format\n :returns: representation of tree in the specified output format\n :rtype: str or binary representation depending on the output format\n\n "
] |
Please provide a description of the function:def print_graphviz(dump_output):
if hasattr(dump_output, 'encode'):
print(dump_output)
else:
with os.fdopen(sys.stdout.fileno(), 'wb') as bytestream:
bytestream.write(dump_output) | [
"Dump the data generated by GraphViz to stdout.\n\n :param dump_output: The output from dump_graphviz\n "
] |
Please provide a description of the function:def conflicting_deps(tree):
conflicting = defaultdict(list)
for p, rs in tree.items():
for req in rs:
if req.is_conflicting():
conflicting[p].append(req)
return conflicting | [
"Returns dependencies which are not present or conflict with the\n requirements of other packages.\n\n e.g. will warn if pkg1 requires pkg2==2.0 and pkg2==1.0 is installed\n\n :param tree: the requirements tree (dict)\n :returns: dict of DistPackage -> list of unsatisfied/unknown ReqPackage\n :rtype:... |
Please provide a description of the function:def cyclic_deps(tree):
key_tree = dict((k.key, v) for k, v in tree.items())
get_children = lambda n: key_tree.get(n.key, [])
cyclic = []
for p, rs in tree.items():
for req in rs:
if p.key in map(attrgetter('key'), get_children(req)):
... | [
"Return cyclic dependencies as list of tuples\n\n :param list pkgs: pkg_resources.Distribution instances\n :param dict pkg_index: mapping of pkgs with their respective keys\n :returns: list of tuples representing cyclic dependencies\n :rtype: generator\n\n "
] |
Please provide a description of the function:def is_conflicting(self):
# unknown installed version is also considered conflicting
if self.installed_version == self.UNKNOWN_VERSION:
return True
ver_spec = (self.version_spec if self.version_spec else '')
req_version_st... | [
"If installed version conflicts with required version"
] |
Please provide a description of the function:def check_against_chunks(self, chunks):
# type: (Iterator[bytes]) -> None
gots = {}
for hash_name in iterkeys(self._allowed):
try:
gots[hash_name] = hashlib.new(hash_name)
except (ValueError, TypeError)... | [
"Check good hashes against ones built from iterable of chunks of\n data.\n\n Raise HashMismatch if none match.\n\n "
] |
Please provide a description of the function:def default_if_none(default=NOTHING, factory=None):
if default is NOTHING and factory is None:
raise TypeError("Must pass either `default` or `factory`.")
if default is not NOTHING and factory is not None:
raise TypeError(
"Must pass... | [
"\n A converter that allows to replace ``None`` values by *default* or the\n result of *factory*.\n\n :param default: Value to be used if ``None`` is passed. Passing an instance\n of :class:`attr.Factory` is supported, however the ``takes_self`` option\n is *not*.\n :param callable factory: ... |
Please provide a description of the function:def _drop_nodes_from_errorpaths(self, _errors, dp_items, sp_items):
dp_basedepth = len(self.document_path)
sp_basedepth = len(self.schema_path)
for error in _errors:
for i in sorted(dp_items, reverse=True):
error.d... | [
" Removes nodes by index from an errorpath, relatively to the\n basepaths of self.\n\n :param errors: A list of :class:`errors.ValidationError` instances.\n :param dp_items: A list of integers, pointing at the nodes to drop from\n the :attr:`document_path`.\n ... |
Please provide a description of the function:def _lookup_field(self, path):
if path.startswith('^'):
path = path[1:]
context = self.document if path.startswith('^') \
else self.root_document
else:
context = self.document
parts = path.... | [
" Searches for a field as defined by path. This method is used by the\n ``dependency`` evaluation logic.\n\n :param path: Path elements are separated by a ``.``. A leading ``^``\n indicates that the path relates to the document root,\n otherwise it relates t... |
Please provide a description of the function:def types(cls):
redundant_types = \
set(cls.types_mapping) & set(cls._types_from_methods)
if redundant_types:
warn("These types are defined both with a method and in the"
"'types_mapping' property of this vali... | [
" The constraints that can be used for the 'type' rule.\n Type: A tuple of strings. "
] |
Please provide a description of the function:def _drop_remaining_rules(self, *rules):
if rules:
for rule in rules:
try:
self._remaining_rules.remove(rule)
except ValueError:
pass
else:
self._remainin... | [
" Drops rules from the queue of the rules that still need to be\n evaluated for the currently processed field.\n If no arguments are given, the whole queue is emptied.\n "
] |
Please provide a description of the function:def normalized(self, document, schema=None, always_return_document=False):
self.__init_processing(document, schema)
self.__normalize_mapping(self.document, self.schema)
self.error_handler.end(self)
if self._errors and not always_retur... | [
" Returns the document normalized according to the specified rules\n of a schema.\n\n :param document: The document to normalize.\n :type document: any :term:`mapping`\n :param schema: The validation schema. Defaults to :obj:`None`. If not\n provided here, the schem... |
Please provide a description of the function:def _normalize_coerce(self, mapping, schema):
error = errors.COERCION_FAILED
for field in mapping:
if field in schema and 'coerce' in schema[field]:
mapping[field] = self.__normalize_coerce(
schema[fie... | [
" {'oneof': [\n {'type': 'callable'},\n {'type': 'list',\n 'schema': {'oneof': [{'type': 'callable'},\n {'type': 'string'}]}},\n {'type': 'string'}\n ]} "
] |
Please provide a description of the function:def _normalize_purge_unknown(mapping, schema):
for field in tuple(mapping):
if field not in schema:
del mapping[field]
return mapping | [
" {'type': 'boolean'} "
] |
Please provide a description of the function:def _normalize_rename(self, mapping, schema, field):
if 'rename' in schema[field]:
mapping[schema[field]['rename']] = mapping[field]
del mapping[field] | [
" {'type': 'hashable'} "
] |
Please provide a description of the function:def _normalize_rename_handler(self, mapping, schema, field):
if 'rename_handler' not in schema[field]:
return
new_name = self.__normalize_coerce(
schema[field]['rename_handler'], field, field,
False, errors.RENAMIN... | [
" {'oneof': [\n {'type': 'callable'},\n {'type': 'list',\n 'schema': {'oneof': [{'type': 'callable'},\n {'type': 'string'}]}},\n {'type': 'string'}\n ]} "
] |
Please provide a description of the function:def _normalize_default_setter(self, mapping, schema, field):
if 'default_setter' in schema[field]:
setter = schema[field]['default_setter']
if isinstance(setter, _str_type):
setter = self.__get_rule_handler('normalize_... | [
" {'oneof': [\n {'type': 'callable'},\n {'type': 'string'}\n ]} "
] |
Please provide a description of the function:def validate(self, document, schema=None, update=False, normalize=True):
self.update = update
self._unrequired_by_excludes = set()
self.__init_processing(document, schema)
if normalize:
self.__normalize_mapping(self.docum... | [
" Normalizes and validates a mapping against a validation-schema of\n defined rules.\n\n :param document: The document to normalize.\n :type document: any :term:`mapping`\n :param schema: The validation schema. Defaults to :obj:`None`. If not\n provided here, the sc... |
Please provide a description of the function:def validated(self, *args, **kwargs):
always_return_document = kwargs.pop('always_return_document', False)
self.validate(*args, **kwargs)
if self._errors and not always_return_document:
return None
else:
return... | [
" Wrapper around :meth:`~cerberus.Validator.validate` that returns\n the normalized and validated document or :obj:`None` if validation\n failed. "
] |
Please provide a description of the function:def _validate_allowed(self, allowed_values, field, value):
if isinstance(value, Iterable) and not isinstance(value, _str_type):
unallowed = set(value) - set(allowed_values)
if unallowed:
self._error(field, errors.UNALL... | [
" {'type': 'list'} "
] |
Please provide a description of the function:def _validate_empty(self, empty, field, value):
if isinstance(value, Iterable) and len(value) == 0:
self._drop_remaining_rules(
'allowed', 'forbidden', 'items', 'minlength', 'maxlength',
'regex', 'validator')
... | [
" {'type': 'boolean'} "
] |
Please provide a description of the function:def _validate_excludes(self, excludes, field, value):
if isinstance(excludes, Hashable):
excludes = [excludes]
# Save required field to be checked latter
if 'required' in self.schema[field] and self.schema[field]['required']:
... | [
" {'type': ('hashable', 'list'),\n 'schema': {'type': 'hashable'}} "
] |
Please provide a description of the function:def _validate_forbidden(self, forbidden_values, field, value):
if isinstance(value, _str_type):
if value in forbidden_values:
self._error(field, errors.FORBIDDEN_VALUE, value)
elif isinstance(value, Sequence):
... | [
" {'type': 'list'} "
] |
Please provide a description of the function:def __validate_logical(self, operator, definitions, field, value):
valid_counter = 0
_errors = errors.ErrorList()
for i, definition in enumerate(definitions):
schema = {field: definition.copy()}
for rule in ('allow_un... | [
" Validates value against all definitions and logs errors according\n to the operator. "
] |
Please provide a description of the function:def _validate_anyof(self, definitions, field, value):
valids, _errors = \
self.__validate_logical('anyof', definitions, field, value)
if valids < 1:
self._error(field, errors.ANYOF, _errors,
valids, len... | [
" {'type': 'list', 'logical': 'anyof'} "
] |
Please provide a description of the function:def _validate_allof(self, definitions, field, value):
valids, _errors = \
self.__validate_logical('allof', definitions, field, value)
if valids < len(definitions):
self._error(field, errors.ALLOF, _errors,
... | [
" {'type': 'list', 'logical': 'allof'} "
] |
Please provide a description of the function:def _validate_noneof(self, definitions, field, value):
valids, _errors = \
self.__validate_logical('noneof', definitions, field, value)
if valids > 0:
self._error(field, errors.NONEOF, _errors,
valids, ... | [
" {'type': 'list', 'logical': 'noneof'} "
] |
Please provide a description of the function:def _validate_oneof(self, definitions, field, value):
valids, _errors = \
self.__validate_logical('oneof', definitions, field, value)
if valids != 1:
self._error(field, errors.ONEOF, _errors,
valids, le... | [
" {'type': 'list', 'logical': 'oneof'} "
] |
Please provide a description of the function:def _validate_max(self, max_value, field, value):
try:
if value > max_value:
self._error(field, errors.MAX_VALUE)
except TypeError:
pass | [
" {'nullable': False } "
] |
Please provide a description of the function:def _validate_min(self, min_value, field, value):
try:
if value < min_value:
self._error(field, errors.MIN_VALUE)
except TypeError:
pass | [
" {'nullable': False } "
] |
Please provide a description of the function:def _validate_maxlength(self, max_length, field, value):
if isinstance(value, Iterable) and len(value) > max_length:
self._error(field, errors.MAX_LENGTH, len(value)) | [
" {'type': 'integer'} "
] |
Please provide a description of the function:def _validate_minlength(self, min_length, field, value):
if isinstance(value, Iterable) and len(value) < min_length:
self._error(field, errors.MIN_LENGTH, len(value)) | [
" {'type': 'integer'} "
] |
Please provide a description of the function:def _validate_keyschema(self, schema, field, value):
if isinstance(value, Mapping):
validator = self._get_child_validator(
document_crumb=field,
schema_crumb=(field, 'keyschema'),
schema=dict(((k, s... | [
" {'type': ['dict', 'string'], 'validator': 'bulk_schema',\n 'forbidden': ['rename', 'rename_handler']} "
] |
Please provide a description of the function:def _validate_readonly(self, readonly, field, value):
if readonly:
if not self._is_normalized:
self._error(field, errors.READONLY_FIELD)
# If the document was normalized (and therefore already been
# checke... | [
" {'type': 'boolean'} "
] |
Please provide a description of the function:def _validate_regex(self, pattern, field, value):
if not isinstance(value, _str_type):
return
if not pattern.endswith('$'):
pattern += '$'
re_obj = re.compile(pattern)
if not re_obj.match(value):
se... | [
" {'type': 'string'} "
] |
Please provide a description of the function:def __validate_required_fields(self, document):
try:
required = set(field for field, definition in self.schema.items()
if self._resolve_rules_set(definition).
get('required') is True)
... | [
" Validates that required fields are not missing.\n\n :param document: The document being validated.\n "
] |
Please provide a description of the function:def _validate_schema(self, schema, field, value):
if schema is None:
return
if isinstance(value, Sequence) and not isinstance(value, _str_type):
self.__validate_schema_sequence(field, schema, value)
elif isinstance(va... | [
" {'type': ['dict', 'string'],\n 'anyof': [{'validator': 'schema'},\n {'validator': 'bulk_schema'}]} "
] |
Please provide a description of the function:def _validate_type(self, data_type, field, value):
if not data_type:
return
types = (data_type,) if isinstance(data_type, _str_type) else data_type
for _type in types:
# TODO remove this block on next major release
... | [
" {'type': ['string', 'list'],\n 'validator': 'type'} "
] |
Please provide a description of the function:def _validate_validator(self, validator, field, value):
if isinstance(validator, _str_type):
validator = self.__get_rule_handler('validator', validator)
validator(field, value)
elif isinstance(validator, Iterable):
... | [
" {'oneof': [\n {'type': 'callable'},\n {'type': 'list',\n 'schema': {'oneof': [{'type': 'callable'},\n {'type': 'string'}]}},\n {'type': 'string'}\n ]} "
] |
Please provide a description of the function:def _validate_valueschema(self, schema, field, value):
schema_crumb = (field, 'valueschema')
if isinstance(value, Mapping):
validator = self._get_child_validator(
document_crumb=field, schema_crumb=schema_crumb,
... | [
" {'type': ['dict', 'string'], 'validator': 'bulk_schema',\n 'forbidden': ['rename', 'rename_handler']} "
] |
Please provide a description of the function:def make_attrgetter(environment, attribute, postprocess=None):
if attribute is None:
attribute = []
elif isinstance(attribute, string_types):
attribute = [int(x) if x.isdigit() else x for x in attribute.split('.')]
else:
attribute = [... | [
"Returns a callable that looks up the given attribute from a\n passed object with the rules of the environment. Dots are allowed\n to access attributes of attributes. Integer parts in paths are\n looked up as integers.\n "
] |
Please provide a description of the function:def do_forceescape(value):
if hasattr(value, '__html__'):
value = value.__html__()
return escape(text_type(value)) | [
"Enforce HTML escaping. This will probably double escape variables."
] |
Please provide a description of the function:def do_urlencode(value):
itemiter = None
if isinstance(value, dict):
itemiter = iteritems(value)
elif not isinstance(value, string_types):
try:
itemiter = iter(value)
except TypeError:
pass
if itemiter is N... | [
"Escape strings for use in URLs (uses UTF-8 encoding). It accepts both\n dictionaries and regular strings as well as pairwise iterables.\n\n .. versionadded:: 2.7\n "
] |
Please provide a description of the function:def do_title(s):
return ''.join(
[item[0].upper() + item[1:].lower()
for item in _word_beginning_split_re.split(soft_unicode(s))
if item]) | [
"Return a titlecased version of the value. I.e. words will start with\n uppercase letters, all remaining characters are lowercase.\n "
] |
Please provide a description of the function:def do_dictsort(value, case_sensitive=False, by='key', reverse=False):
if by == 'key':
pos = 0
elif by == 'value':
pos = 1
else:
raise FilterArgumentError(
'You can only sort by either "key" or "value"'
)
def ... | [
"Sort a dict and yield (key, value) pairs. Because python dicts are\n unsorted you may want to use this function to order them by either\n key or value:\n\n .. sourcecode:: jinja\n\n {% for item in mydict|dictsort %}\n sort the dict by key, case insensitive\n\n {% for item in mydic... |
Please provide a description of the function:def do_sort(
environment, value, reverse=False, case_sensitive=False, attribute=None
):
key_func = make_attrgetter(
environment, attribute,
postprocess=ignore_case if not case_sensitive else None
)
return sorted(value, key=key_func, rever... | [
"Sort an iterable. Per default it sorts ascending, if you pass it\n true as first argument it will reverse the sorting.\n\n If the iterable is made of strings the third parameter can be used to\n control the case sensitiveness of the comparison which is disabled by\n default.\n\n .. sourcecode:: jin... |
Please provide a description of the function:def do_unique(environment, value, case_sensitive=False, attribute=None):
getter = make_attrgetter(
environment, attribute,
postprocess=ignore_case if not case_sensitive else None
)
seen = set()
for item in value:
key = getter(ite... | [
"Returns a list of unique items from the the given iterable.\n\n .. sourcecode:: jinja\n\n {{ ['foo', 'bar', 'foobar', 'FooBar']|unique }}\n -> ['foo', 'bar', 'foobar']\n\n The unique items are yielded in the same order as their first occurrence in\n the iterable passed to the filter.\n\n... |
Please provide a description of the function:def do_min(environment, value, case_sensitive=False, attribute=None):
return _min_or_max(environment, value, min, case_sensitive, attribute) | [
"Return the smallest item from the sequence.\n\n .. sourcecode:: jinja\n\n {{ [1, 2, 3]|min }}\n -> 1\n\n :param case_sensitive: Treat upper and lower case strings as distinct.\n :param attribute: Get the object with the max value of this attribute.\n "
] |
Please provide a description of the function:def do_max(environment, value, case_sensitive=False, attribute=None):
return _min_or_max(environment, value, max, case_sensitive, attribute) | [
"Return the largest item from the sequence.\n\n .. sourcecode:: jinja\n\n {{ [1, 2, 3]|max }}\n -> 3\n\n :param case_sensitive: Treat upper and lower case strings as distinct.\n :param attribute: Get the object with the max value of this attribute.\n "
] |
Please provide a description of the function:def do_join(eval_ctx, value, d=u'', attribute=None):
if attribute is not None:
value = imap(make_attrgetter(eval_ctx.environment, attribute), value)
# no automatic escaping? joining is a lot eaiser then
if not eval_ctx.autoescape:
return te... | [
"Return a string which is the concatenation of the strings in the\n sequence. The separator between elements is an empty string per\n default, you can define it with the optional parameter:\n\n .. sourcecode:: jinja\n\n {{ [1, 2, 3]|join('|') }}\n -> 1|2|3\n\n {{ [1, 2, 3]|join }}\... |
Please provide a description of the function:def do_last(environment, seq):
try:
return next(iter(reversed(seq)))
except StopIteration:
return environment.undefined('No last item, sequence was empty.') | [
"Return the last item of a sequence."
] |
Please provide a description of the function:def do_random(context, seq):
try:
return random.choice(seq)
except IndexError:
return context.environment.undefined('No random item, sequence was empty.') | [
"Return a random item from the sequence."
] |
Please provide a description of the function:def do_filesizeformat(value, binary=False):
bytes = float(value)
base = binary and 1024 or 1000
prefixes = [
(binary and 'KiB' or 'kB'),
(binary and 'MiB' or 'MB'),
(binary and 'GiB' or 'GB'),
(binary and 'TiB' or 'TB'),
... | [
"Format the value like a 'human-readable' file size (i.e. 13 kB,\n 4.1 MB, 102 Bytes, etc). Per default decimal prefixes are used (Mega,\n Giga, etc.), if the second parameter is set to `True` the binary\n prefixes are used (Mebi, Gibi).\n "
] |
Please provide a description of the function:def do_urlize(eval_ctx, value, trim_url_limit=None, nofollow=False,
target=None, rel=None):
policies = eval_ctx.environment.policies
rel = set((rel or '').split() or [])
if nofollow:
rel.add('nofollow')
rel.update((policies['urlize.... | [
"Converts URLs in plain text into clickable links.\n\n If you pass the filter an additional integer it will shorten the urls\n to that number. Also a third argument exists that makes the urls\n \"nofollow\":\n\n .. sourcecode:: jinja\n\n {{ mytext|urlize(40, true) }}\n links are shorte... |
Please provide a description of the function:def do_indent(
s, width=4, first=False, blank=False, indentfirst=None
):
if indentfirst is not None:
warnings.warn(DeprecationWarning(
'The "indentfirst" argument is renamed to "first".'
), stacklevel=2)
first = indentfirst
... | [
"Return a copy of the string with each line indented by 4 spaces. The\n first line and blank lines are not indented by default.\n\n :param width: Number of spaces to indent by.\n :param first: Don't skip indenting the first line.\n :param blank: Don't skip indenting empty lines.\n\n .. versionchanged... |
Please provide a description of the function:def do_truncate(env, s, length=255, killwords=False, end='...', leeway=None):
if leeway is None:
leeway = env.policies['truncate.leeway']
assert length >= len(end), 'expected length >= %s, got %s' % (len(end), length)
assert leeway >= 0, 'expected le... | [
"Return a truncated copy of the string. The length is specified\n with the first parameter which defaults to ``255``. If the second\n parameter is ``true`` the filter will cut the text at length. Otherwise\n it will discard the last word. If the text was in fact\n truncated it will append an ellipsis si... |
Please provide a description of the function:def do_wordwrap(environment, s, width=79, break_long_words=True,
wrapstring=None):
if not wrapstring:
wrapstring = environment.newline_sequence
import textwrap
return wrapstring.join(textwrap.wrap(s, width=width, expand_tabs=False,
... | [
"\n Return a copy of the string passed to the filter wrapped after\n ``79`` characters. You can override this default using the first\n parameter. If you set the second parameter to `false` Jinja will not\n split words apart if they are longer than `width`. By default, the newlines\n will be the de... |
Please provide a description of the function:def do_int(value, default=0, base=10):
try:
if isinstance(value, string_types):
return int(value, base)
return int(value)
except (TypeError, ValueError):
# this quirk is necessary so that "42.23"|int gives 42.
try:
... | [
"Convert the value into an integer. If the\n conversion doesn't work it will return ``0``. You can\n override this default using the first parameter. You\n can also override the default base (10) in the second\n parameter, which handles input with prefixes such as\n 0b, 0o and 0x for bases 2, 8 and 1... |
Please provide a description of the function:def do_format(value, *args, **kwargs):
if args and kwargs:
raise FilterArgumentError('can\'t handle positional and keyword '
'arguments at the same time')
return soft_unicode(value) % (kwargs or args) | [
"\n Apply python string formatting on an object:\n\n .. sourcecode:: jinja\n\n {{ \"%s - %s\"|format(\"Hello?\", \"Foo!\") }}\n -> Hello? - Foo!\n "
] |
Please provide a description of the function:def do_striptags(value):
if hasattr(value, '__html__'):
value = value.__html__()
return Markup(text_type(value)).striptags() | [
"Strip SGML/XML tags and replace adjacent whitespace by one space.\n "
] |
Please provide a description of the function:def do_slice(value, slices, fill_with=None):
seq = list(value)
length = len(seq)
items_per_slice = length // slices
slices_with_extra = length % slices
offset = 0
for slice_number in range(slices):
start = offset + slice_number * items_pe... | [
"Slice an iterator and return a list of lists containing\n those items. Useful if you want to create a div containing\n three ul tags that represent columns:\n\n .. sourcecode:: html+jinja\n\n <div class=\"columwrapper\">\n {%- for column in items|slice(3) %}\n <ul class=\"column... |
Please provide a description of the function:def do_batch(value, linecount, fill_with=None):
tmp = []
for item in value:
if len(tmp) == linecount:
yield tmp
tmp = []
tmp.append(item)
if tmp:
if fill_with is not None and len(tmp) < linecount:
t... | [
"\n A filter that batches items. It works pretty much like `slice`\n just the other way round. It returns a list of lists with the\n given number of items. If you provide a second parameter this\n is used to fill up missing items. See this example:\n\n .. sourcecode:: html+jinja\n\n <table>\n ... |
Please provide a description of the function:def do_round(value, precision=0, method='common'):
if not method in ('common', 'ceil', 'floor'):
raise FilterArgumentError('method must be common, ceil or floor')
if method == 'common':
return round(value, precision)
func = getattr(math, meth... | [
"Round the number to a given precision. The first\n parameter specifies the precision (default is ``0``), the\n second the rounding method:\n\n - ``'common'`` rounds either up or down\n - ``'ceil'`` always rounds up\n - ``'floor'`` always rounds down\n\n If you don't specify a method ``'common'`` ... |
Please provide a description of the function:def do_groupby(environment, value, attribute):
expr = make_attrgetter(environment, attribute)
return [_GroupTuple(key, list(values)) for key, values
in groupby(sorted(value, key=expr), expr)] | [
"Group a sequence of objects by a common attribute.\n\n If you for example have a list of dicts or objects that represent persons\n with `gender`, `first_name` and `last_name` attributes and you want to\n group all users by genders you can do something like the following\n snippet:\n\n .. sourcecode:... |
Please provide a description of the function:def do_sum(environment, iterable, attribute=None, start=0):
if attribute is not None:
iterable = imap(make_attrgetter(environment, attribute), iterable)
return sum(iterable, start) | [
"Returns the sum of a sequence of numbers plus the value of parameter\n 'start' (which defaults to 0). When the sequence is empty it returns\n start.\n\n It is also possible to sum up only certain attributes:\n\n .. sourcecode:: jinja\n\n Total: {{ items|sum(attribute='price') }}\n\n .. versi... |
Please provide a description of the function:def do_reverse(value):
if isinstance(value, string_types):
return value[::-1]
try:
return reversed(value)
except TypeError:
try:
rv = list(value)
rv.reverse()
return rv
except TypeError:
... | [
"Reverse the object or return an iterator that iterates over it the other\n way round.\n "
] |
Please provide a description of the function:def do_attr(environment, obj, name):
try:
name = str(name)
except UnicodeError:
pass
else:
try:
value = getattr(obj, name)
except AttributeError:
pass
else:
if environment.sandboxed ... | [
"Get an attribute of an object. ``foo|attr(\"bar\")`` works like\n ``foo.bar`` just that always an attribute is returned and items are not\n looked up.\n\n See :ref:`Notes on subscriptions <notes-on-subscriptions>` for more details.\n "
] |
Please provide a description of the function:def do_map(*args, **kwargs):
seq, func = prepare_map(args, kwargs)
if seq:
for item in seq:
yield func(item) | [
"Applies a filter on a sequence of objects or looks up an attribute.\n This is useful when dealing with lists of objects but you are really\n only interested in a certain value of it.\n\n The basic usage is mapping on an attribute. Imagine you have a list\n of users but you are only interested in a lis... |
Please provide a description of the function:def do_tojson(eval_ctx, value, indent=None):
policies = eval_ctx.environment.policies
dumper = policies['json.dumps_function']
options = policies['json.dumps_kwargs']
if indent is not None:
options = dict(options)
options['indent'] = inde... | [
"Dumps a structure to JSON so that it's safe to use in ``<script>``\n tags. It accepts the same arguments and returns a JSON string. Note that\n this is available in templates through the ``|tojson`` filter which will\n also mark the result as safe. Due to how this function escapes certain\n characte... |
Please provide a description of the function:def autocomplete():
# Don't complete if user hasn't sourced bash_completion file.
if 'PIP_AUTO_COMPLETE' not in os.environ:
return
cwords = os.environ['COMP_WORDS'].split()[1:]
cword = int(os.environ['COMP_CWORD'])
try:
current = cwor... | [
"Entry Point for completion of main and subcommand options.\n "
] |
Please provide a description of the function:def get_path_completion_type(cwords, cword, opts):
if cword < 2 or not cwords[cword - 2].startswith('-'):
return
for opt in opts:
if opt.help == optparse.SUPPRESS_HELP:
continue
for o in str(opt).split('/'):
if cwo... | [
"Get the type of path completion (``file``, ``dir``, ``path`` or None)\n\n :param cwords: same as the environmental variable ``COMP_WORDS``\n :param cword: same as the environmental variable ``COMP_CWORD``\n :param opts: The available options to check\n :return: path completion type (``file``, ``dir``, ... |
Please provide a description of the function:def auto_complete_paths(current, completion_type):
directory, filename = os.path.split(current)
current_path = os.path.abspath(directory)
# Don't complete paths if they can't be accessed
if not os.access(current_path, os.R_OK):
return
filenam... | [
"If ``completion_type`` is ``file`` or ``path``, list all regular files\n and directories starting with ``current``; otherwise only list directories\n starting with ``current``.\n\n :param current: The word to be completed\n :param completion_type: path completion type(`file`, `path` or `dir`)i\n :re... |
Please provide a description of the function:def _build_wheel_modern(ireq, output_dir, finder, wheel_cache, kwargs):
kwargs.update({"progress_bar": "off", "build_isolation": False})
with pip_shims.RequirementTracker() as req_tracker:
if req_tracker:
kwargs["req_tracker"] = req_tracker
... | [
"Build a wheel.\n\n * ireq: The InstallRequirement object to build\n * output_dir: The directory to build the wheel in.\n * finder: pip's internal Finder object to find the source out of ireq.\n * kwargs: Various keyword arguments from `_prepare_wheel_building_kwargs`.\n "
] |
Please provide a description of the function:def get_python_version(path):
# type: (str) -> str
version_cmd = [path, "-c", "import sys; print(sys.version.split()[0])"]
try:
c = vistir.misc.run(
version_cmd,
block=True,
nospin=True,
return_object=T... | [
"Get python version string using subprocess from a given path."
] |
Please provide a description of the function:def path_is_known_executable(path):
# type: (vistir.compat.Path) -> bool
return (
path_is_executable(path)
or os.access(str(path), os.R_OK)
and path.suffix in KNOWN_EXTS
) | [
"\n Returns whether a given path is a known executable from known executable extensions\n or has the executable bit toggled.\n\n :param path: The path to the target executable.\n :type path: :class:`~vistir.compat.Path`\n :return: True if the path has chmod +x, or is a readable, known executable exte... |
Please provide a description of the function:def looks_like_python(name):
# type: (str) -> bool
if not any(name.lower().startswith(py_name) for py_name in PYTHON_IMPLEMENTATIONS):
return False
match = RE_MATCHER.match(name)
if match:
return any(fnmatch(name, rule) for rule in MATCH... | [
"\n Determine whether the supplied filename looks like a possible name of python.\n\n :param str name: The name of the provided file.\n :return: Whether the provided name looks like python.\n :rtype: bool\n "
] |
Please provide a description of the function:def ensure_path(path):
# type: (Union[vistir.compat.Path, str]) -> vistir.compat.Path
if isinstance(path, vistir.compat.Path):
return path
path = vistir.compat.Path(os.path.expandvars(path))
return path.absolute() | [
"\n Given a path (either a string or a Path object), expand variables and return a Path object.\n\n :param path: A string or a :class:`~pathlib.Path` object.\n :type path: str or :class:`~pathlib.Path`\n :return: A fully expanded Path object.\n :rtype: :class:`~pathlib.Path`\n "
] |
Please provide a description of the function:def filter_pythons(path):
# type: (Union[str, vistir.compat.Path]) -> Iterable
if not isinstance(path, vistir.compat.Path):
path = vistir.compat.Path(str(path))
if not path.is_dir():
return path if path_is_python(path) else None
return fi... | [
"Return all valid pythons in a given path"
] |
Please provide a description of the function:def expand_paths(path, only_python=True):
# type: (Union[Sequence, PathEntry], bool) -> Iterator
if path is not None and (
isinstance(path, Sequence)
and not getattr(path.__class__, "__name__", "") == "PathEntry"
):
for p in unnest(p... | [
"\n Recursively expand a list or :class:`~pythonfinder.models.path.PathEntry` instance\n\n :param Union[Sequence, PathEntry] path: The path or list of paths to expand\n :param bool only_python: Whether to filter to include only python paths, default True\n :returns: An iterator over the expanded set of ... |
Please provide a description of the function:def _get_cache_path_parts(self, link):
# type: (Link) -> List[str]
# We want to generate an url to use as our cache key, we don't want to
# just re-use the URL because it might have other items in the fragment
# and we don't care abo... | [
"Get parts of part that must be os.path.joined with cache_dir\n "
] |
Please provide a description of the function:def get_path_for_link(self, link):
# type: (Link) -> str
parts = self._get_cache_path_parts(link)
# Store wheels within the root cache_dir
return os.path.join(self.cache_dir, "wheels", *parts) | [
"Return a directory to store cached wheels for link\n\n Because there are M wheels for any one sdist, we provide a directory\n to cache them in, and then consult that directory when looking up\n cache hits.\n\n We only insert things into the cache if they have plausible version\n ... |
Please provide a description of the function:def is_artifact(self):
# type: () -> bool
from pipenv.patched.notpip._internal.vcs import vcs
if self.scheme in vcs.all_schemes:
return False
return True | [
"\n Determines if this points to an actual artifact (e.g. a tarball) or if\n it points to an \"abstract\" thing like a path or a VCS location.\n "
] |
Please provide a description of the function:def _get_dependencies_from_cache(ireq):
if os.environ.get("PASSA_IGNORE_LOCAL_CACHE"):
return
if ireq.editable:
return
try:
deps = DEPENDENCY_CACHE[ireq]
pyrq = REQUIRES_PYTHON_CACHE[ireq]
except KeyError:
return
... | [
"Retrieves dependencies for the requirement from the dependency cache.\n "
] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.