INSTRUCTION stringlengths 1 8.43k | RESPONSE stringlengths 75 104k |
|---|---|
Recursively move a file or directory to another location. This is similar to the Unix mv command. | def move(src, dst):
"""Recursively move a file or directory to another location. This is
similar to the Unix "mv" command.
If the destination is a directory or a symlink to a directory, the source
is moved inside the directory. The destination path must not already
exist.
If the destination al... |
Returns a gid given a group name. | def _get_gid(name):
"""Returns a gid, given a group name."""
if getgrnam is None or name is None:
return None
try:
result = getgrnam(name)
except KeyError:
result = None
if result is not None:
return result[2]
return None |
Returns an uid given a user name. | def _get_uid(name):
"""Returns an uid, given a user name."""
if getpwnam is None or name is None:
return None
try:
result = getpwnam(name)
except KeyError:
result = None
if result is not None:
return result[2]
return None |
Create a ( possibly compressed ) tar file from all the files under base_dir. | def _make_tarball(base_name, base_dir, compress="gzip", verbose=0, dry_run=0,
owner=None, group=None, logger=None):
"""Create a (possibly compressed) tar file from all the files under
'base_dir'.
'compress' must be "gzip" (the default), "bzip2", or None.
'owner' and 'group' can be us... |
Create a zip file from all the files under base_dir. | def _make_zipfile(base_name, base_dir, verbose=0, dry_run=0, logger=None):
"""Create a zip file from all the files under 'base_dir'.
The output zip file will be named 'base_name' + ".zip". Uses either the
"zipfile" Python module (if available) or the InfoZIP "zip" utility
(if installed and found on th... |
Returns a list of supported formats for archiving and unarchiving. | def get_archive_formats():
"""Returns a list of supported formats for archiving and unarchiving.
Each element of the returned sequence is a tuple (name, description)
"""
formats = [(name, registry[2]) for name, registry in
_ARCHIVE_FORMATS.items()]
formats.sort()
return formats |
Registers an archive format. | def register_archive_format(name, function, extra_args=None, description=''):
"""Registers an archive format.
name is the name of the format. function is the callable that will be
used to create archives. If provided, extra_args is a sequence of
(name, value) tuples that will be passed as arguments to ... |
Create an archive file ( eg. zip or tar ). | def make_archive(base_name, format, root_dir=None, base_dir=None, verbose=0,
dry_run=0, owner=None, group=None, logger=None):
"""Create an archive file (eg. zip or tar).
'base_name' is the name of the file to create, minus any format-specific
extension; 'format' is the archive format: one ... |
Returns a list of supported formats for unpacking. | def get_unpack_formats():
"""Returns a list of supported formats for unpacking.
Each element of the returned sequence is a tuple
(name, extensions, description)
"""
formats = [(name, info[0], info[3]) for name, info in
_UNPACK_FORMATS.items()]
formats.sort()
return formats |
Checks what gets registered as an unpacker. | def _check_unpack_options(extensions, function, extra_args):
"""Checks what gets registered as an unpacker."""
# 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_extensi... |
Registers an unpack format. | def register_unpack_format(name, extensions, function, extra_args=None,
description=''):
"""Registers an unpack format.
`name` is the name of the format. `extensions` is a list of extensions
corresponding to the format.
`function` is the callable that will be
used to unp... |
Ensure that the parent directory of path exists | def _ensure_directory(path):
"""Ensure that the parent directory of `path` exists"""
dirname = os.path.dirname(path)
if not os.path.isdir(dirname):
os.makedirs(dirname) |
Unpack zip filename to extract_dir | def _unpack_zipfile(filename, extract_dir):
"""Unpack zip `filename` to `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" % ... |
Unpack tar/ tar. gz/ tar. bz2 filename to extract_dir | def _unpack_tarfile(filename, extract_dir):
"""Unpack tar/tar.gz/tar.bz2 `filename` to `extract_dir`
"""
try:
tarobj = tarfile.open(filename)
except tarfile.TarError:
raise ReadError(
"%s is not a compressed or uncompressed tar file" % filename)
try:
tarobj.extrac... |
Unpack an archive. | def unpack_archive(filename, extract_dir=None, format=None):
"""Unpack an archive.
`filename` is the name of the archive.
`extract_dir` is the name of the target directory, where the archive
is unpacked. If not provided, the current working directory is used.
`format` is the archive format: one o... |
Parse an HTML fragment as a string or file - like object into a tree | def parseFragment(doc, container="div", treebuilder="etree", namespaceHTMLElements=True, **kwargs):
"""Parse an HTML fragment as a string or file-like object into a tree
:arg doc: the fragment to parse as a string or file-like object
:arg container: the container context to parse the fragment in
:arg... |
Parse a HTML document into a well - formed tree | def parse(self, stream, *args, **kwargs):
"""Parse a HTML document into a well-formed tree
:arg stream: a file-like object or string containing the HTML to be parsed
The optional encoding parameter must be a string that indicates
the encoding. If specified, that encoding will ... |
Parse a HTML fragment into a well - formed tree fragment | def parseFragment(self, stream, *args, **kwargs):
"""Parse a HTML fragment into a well-formed tree fragment
:arg container: name of the element we're setting the innerHTML
property if set to None, default to 'div'
:arg stream: a file-like object or string containing the HTML to be ... |
Construct tree representation of the pkgs from the index. | def construct_tree(index):
"""Construct tree representation of the pkgs from the index.
The keys of the dict representing the tree will be objects of type
DistPackage and the values will be list of ReqPackage objects.
:param dict index: dist index ie. index of pkgs by their keys
:returns: tree of ... |
Sorts the dict representation of the tree | def sorted_tree(tree):
"""Sorts the dict representation of the tree
The root packages as well as the intermediate packages are sorted
in the alphabetical order of the package names.
:param dict tree: the pkg dependency tree obtained by calling
`construct_tree` function
:return... |
Find a root in a tree by it s key | def find_tree_root(tree, key):
"""Find a root in a tree by it's key
:param dict tree: the pkg dependency tree obtained by calling
`construct_tree` function
:param str key: key of the root node to find
:returns: a root node if found else None
:rtype: mixed
"""
result = ... |
Reverse the dependency tree. | def reverse_tree(tree):
"""Reverse the dependency tree.
ie. the keys of the resulting dict are objects of type
ReqPackage and the values are lists of DistPackage objects.
:param dict tree: the pkg dependency tree obtained by calling
`construct_tree` function
:returns: reverse... |
Guess the version of a pkg when pip doesn t provide it | def guess_version(pkg_key, default='?'):
"""Guess the version of a pkg when pip doesn't provide it
:param str pkg_key: key of the package
:param str default: default version to return if unable to find
:returns: version
:rtype: string
"""
try:
m = import_module(pkg_key)
except ... |
Convert tree to string representation | def render_tree(tree, list_all=True, show_only=None, frozen=False, exclude=None):
"""Convert tree to string representation
:param dict tree: the package tree
:param bool list_all: whether to list all the pgks at the root
level or only those that are the
s... |
Converts the tree into a flat json representation. | def render_json(tree, indent):
"""Converts the tree into a flat json representation.
The json repr will be a list of hashes, each hash having 2 fields:
- package
- dependencies: list of dependencies
:param dict tree: dependency tree
:param int indent: no. of spaces to indent json
:retu... |
Converts the tree into a nested json representation. | def render_json_tree(tree, indent):
"""Converts the tree into a nested json representation.
The json repr will be a list of hashes, each hash having the following fields:
- package_name
- key
- required_version
- installed_version
- dependencies: list of dependencies
:param d... |
Output dependency graph as one of the supported GraphViz output formats. | def dump_graphviz(tree, output_format='dot'):
"""Output dependency graph as one of the supported GraphViz output formats.
:param dict tree: dependency graph
:param string output_format: output format
:returns: representation of tree in the specified output format
:rtype: str or binary representatio... |
Dump the data generated by GraphViz to stdout. | def print_graphviz(dump_output):
"""Dump the data generated by GraphViz to stdout.
:param dump_output: The output from dump_graphviz
"""
if hasattr(dump_output, 'encode'):
print(dump_output)
else:
with os.fdopen(sys.stdout.fileno(), 'wb') as bytestream:
bytestream.write(... |
Returns dependencies which are not present or conflict with the requirements of other packages. | def conflicting_deps(tree):
"""Returns dependencies which are not present or conflict with the
requirements of other packages.
e.g. will warn if pkg1 requires pkg2==2.0 and pkg2==1.0 is installed
:param tree: the requirements tree (dict)
:returns: dict of DistPackage -> list of unsatisfied/unknown... |
Return cyclic dependencies as list of tuples | def cyclic_deps(tree):
"""Return cyclic dependencies as list of tuples
:param list pkgs: pkg_resources.Distribution instances
:param dict pkg_index: mapping of pkgs with their respective keys
:returns: list of tuples representing cyclic dependencies
:rtype: generator
"""
key_tree = dict((k... |
If installed version conflicts with required version | def is_conflicting(self):
"""If installed version conflicts with required version"""
# 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 '')
r... |
Check good hashes against ones built from iterable of chunks of data. | def check_against_chunks(self, chunks):
# type: (Iterator[bytes]) -> None
"""Check good hashes against ones built from iterable of chunks of
data.
Raise HashMismatch if none match.
"""
gots = {}
for hash_name in iterkeys(self._allowed):
try:
... |
A converter that allows to replace None values by * default * or the result of * factory *. | def default_if_none(default=NOTHING, factory=None):
"""
A converter that allows to replace ``None`` values by *default* or the
result of *factory*.
:param default: Value to be used if ``None`` is passed. Passing an instance
of :class:`attr.Factory` is supported, however the ``takes_self`` option... |
Removes nodes by index from an errorpath relatively to the basepaths of self. | def _drop_nodes_from_errorpaths(self, _errors, dp_items, sp_items):
""" Removes nodes by index from an errorpath, relatively to the
basepaths of self.
:param errors: A list of :class:`errors.ValidationError` instances.
:param dp_items: A list of integers, pointing at the nodes to dr... |
Searches for a field as defined by path. This method is used by the dependency evaluation logic. | def _lookup_field(self, path):
""" Searches for a field as defined by path. This method is used by the
``dependency`` evaluation logic.
:param path: Path elements are separated by a ``.``. A leading ``^``
indicates that the path relates to the document root,
... |
The constraints that can be used for the type rule. Type: A tuple of strings. | def types(cls):
""" The constraints that can be used for the 'type' rule.
Type: A tuple of strings. """
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"
... |
Drops rules from the queue of the rules that still need to be evaluated for the currently processed field. If no arguments are given the whole queue is emptied. | def _drop_remaining_rules(self, *rules):
""" Drops rules from the queue of the rules that still need to be
evaluated for the currently processed field.
If no arguments are given, the whole queue is emptied.
"""
if rules:
for rule in rules:
try:... |
Returns the document normalized according to the specified rules of a schema. | def normalized(self, document, schema=None, always_return_document=False):
""" Returns the document normalized according to the specified rules
of a schema.
:param document: The document to normalize.
:type document: any :term:`mapping`
:param schema: The validation schema. Defa... |
{ oneof: [ { type: callable } { type: list schema: { oneof: [ { type: callable } { type: string } ] }} { type: string } ] } | def _normalize_coerce(self, mapping, schema):
""" {'oneof': [
{'type': 'callable'},
{'type': 'list',
'schema': {'oneof': [{'type': 'callable'},
{'type': 'string'}]}},
{'type': 'string'}
]} """
... |
{ type: boolean } | def _normalize_purge_unknown(mapping, schema):
""" {'type': 'boolean'} """
for field in tuple(mapping):
if field not in schema:
del mapping[field]
return mapping |
{ type: hashable } | def _normalize_rename(self, mapping, schema, field):
""" {'type': 'hashable'} """
if 'rename' in schema[field]:
mapping[schema[field]['rename']] = mapping[field]
del mapping[field] |
{ oneof: [ { type: callable } { type: list schema: { oneof: [ { type: callable } { type: string } ] }} { type: string } ] } | def _normalize_rename_handler(self, mapping, schema, field):
""" {'oneof': [
{'type': 'callable'},
{'type': 'list',
'schema': {'oneof': [{'type': 'callable'},
{'type': 'string'}]}},
{'type': 'string'}
... |
{ oneof: [ { type: callable } { type: string } ] } | def _normalize_default_setter(self, mapping, schema, field):
""" {'oneof': [
{'type': 'callable'},
{'type': 'string'}
]} """
if 'default_setter' in schema[field]:
setter = schema[field]['default_setter']
if isinstance(setter, _str_t... |
Normalizes and validates a mapping against a validation - schema of defined rules. | def validate(self, document, schema=None, update=False, normalize=True):
""" Normalizes and validates a mapping against a validation-schema of
defined rules.
:param document: The document to normalize.
:type document: any :term:`mapping`
:param schema: The validation schema. Def... |
Wrapper around: meth: ~cerberus. Validator. validate that returns the normalized and validated document or: obj: None if validation failed. | def validated(self, *args, **kwargs):
""" Wrapper around :meth:`~cerberus.Validator.validate` that returns
the normalized and validated document or :obj:`None` if validation
failed. """
always_return_document = kwargs.pop('always_return_document', False)
self.validate(*ar... |
{ type: list } | def _validate_allowed(self, allowed_values, field, value):
""" {'type': 'list'} """
if isinstance(value, Iterable) and not isinstance(value, _str_type):
unallowed = set(value) - set(allowed_values)
if unallowed:
self._error(field, errors.UNALLOWED_VALUES, list(una... |
{ type: boolean } | def _validate_empty(self, empty, field, value):
""" {'type': 'boolean'} """
if isinstance(value, Iterable) and len(value) == 0:
self._drop_remaining_rules(
'allowed', 'forbidden', 'items', 'minlength', 'maxlength',
'regex', 'validator')
if not empt... |
{ type: ( hashable list ) schema: { type: hashable }} | def _validate_excludes(self, excludes, field, value):
""" {'type': ('hashable', 'list'),
'schema': {'type': 'hashable'}} """
if isinstance(excludes, Hashable):
excludes = [excludes]
# Save required field to be checked latter
if 'required' in self.schema[field] a... |
{ type: list } | def _validate_forbidden(self, forbidden_values, field, value):
""" {'type': 'list'} """
if isinstance(value, _str_type):
if value in forbidden_values:
self._error(field, errors.FORBIDDEN_VALUE, value)
elif isinstance(value, Sequence):
forbidden = set(value... |
Validates value against all definitions and logs errors according to the operator. | def __validate_logical(self, operator, definitions, field, value):
""" Validates value against all definitions and logs errors according
to the operator. """
valid_counter = 0
_errors = errors.ErrorList()
for i, definition in enumerate(definitions):
schema = {fie... |
{ type: list logical: anyof } | def _validate_anyof(self, definitions, field, value):
""" {'type': 'list', 'logical': 'anyof'} """
valids, _errors = \
self.__validate_logical('anyof', definitions, field, value)
if valids < 1:
self._error(field, errors.ANYOF, _errors,
valids, len(... |
{ type: list logical: allof } | def _validate_allof(self, definitions, field, value):
""" {'type': 'list', 'logical': 'allof'} """
valids, _errors = \
self.__validate_logical('allof', definitions, field, value)
if valids < len(definitions):
self._error(field, errors.ALLOF, _errors,
... |
{ type: list logical: noneof } | def _validate_noneof(self, definitions, field, value):
""" {'type': 'list', 'logical': 'noneof'} """
valids, _errors = \
self.__validate_logical('noneof', definitions, field, value)
if valids > 0:
self._error(field, errors.NONEOF, _errors,
valids, ... |
{ type: list logical: oneof } | def _validate_oneof(self, definitions, field, value):
""" {'type': 'list', 'logical': 'oneof'} """
valids, _errors = \
self.__validate_logical('oneof', definitions, field, value)
if valids != 1:
self._error(field, errors.ONEOF, _errors,
valids, len... |
{ nullable: False } | def _validate_max(self, max_value, field, value):
""" {'nullable': False } """
try:
if value > max_value:
self._error(field, errors.MAX_VALUE)
except TypeError:
pass |
{ nullable: False } | def _validate_min(self, min_value, field, value):
""" {'nullable': False } """
try:
if value < min_value:
self._error(field, errors.MIN_VALUE)
except TypeError:
pass |
{ type: integer } | def _validate_maxlength(self, max_length, field, value):
""" {'type': 'integer'} """
if isinstance(value, Iterable) and len(value) > max_length:
self._error(field, errors.MAX_LENGTH, len(value)) |
{ type: integer } | def _validate_minlength(self, min_length, field, value):
""" {'type': 'integer'} """
if isinstance(value, Iterable) and len(value) < min_length:
self._error(field, errors.MIN_LENGTH, len(value)) |
{ type: [ dict string ] validator: bulk_schema forbidden: [ rename rename_handler ] } | def _validate_keyschema(self, schema, field, value):
""" {'type': ['dict', 'string'], 'validator': 'bulk_schema',
'forbidden': ['rename', 'rename_handler']} """
if isinstance(value, Mapping):
validator = self._get_child_validator(
document_crumb=field,
... |
{ type: boolean } | def _validate_readonly(self, readonly, field, value):
""" {'type': 'boolean'} """
if readonly:
if not self._is_normalized:
self._error(field, errors.READONLY_FIELD)
# If the document was normalized (and therefore already been
# checked for readonly fie... |
{ type: string } | def _validate_regex(self, pattern, field, value):
""" {'type': 'string'} """
if not isinstance(value, _str_type):
return
if not pattern.endswith('$'):
pattern += '$'
re_obj = re.compile(pattern)
if not re_obj.match(value):
self._error(field, er... |
Validates that required fields are not missing. | def __validate_required_fields(self, document):
""" Validates that required fields are not missing.
:param document: The document being validated.
"""
try:
required = set(field for field, definition in self.schema.items()
if self._resolve_rules_set... |
{ type: [ dict string ] anyof: [ { validator: schema } { validator: bulk_schema } ] } | def _validate_schema(self, schema, field, value):
""" {'type': ['dict', 'string'],
'anyof': [{'validator': 'schema'},
{'validator': 'bulk_schema'}]} """
if schema is None:
return
if isinstance(value, Sequence) and not isinstance(value, _str_type):... |
{ type: [ string list ] validator: type } | def _validate_type(self, data_type, field, value):
""" {'type': ['string', 'list'],
'validator': 'type'} """
if not data_type:
return
types = (data_type,) if isinstance(data_type, _str_type) else data_type
for _type in types:
# TODO remove this bloc... |
{ oneof: [ { type: callable } { type: list schema: { oneof: [ { type: callable } { type: string } ] }} { type: string } ] } | def _validate_validator(self, validator, field, value):
""" {'oneof': [
{'type': 'callable'},
{'type': 'list',
'schema': {'oneof': [{'type': 'callable'},
{'type': 'string'}]}},
{'type': 'string'}
... |
{ type: [ dict string ] validator: bulk_schema forbidden: [ rename rename_handler ] } | def _validate_valueschema(self, schema, field, value):
""" {'type': ['dict', 'string'], 'validator': 'bulk_schema',
'forbidden': ['rename', 'rename_handler']} """
schema_crumb = (field, 'valueschema')
if isinstance(value, Mapping):
validator = self._get_child_validator(
... |
Returns a callable that looks up the given attribute from a passed object with the rules of the environment. Dots are allowed to access attributes of attributes. Integer parts in paths are looked up as integers. | def make_attrgetter(environment, attribute, postprocess=None):
"""Returns a callable that looks up the given attribute from a
passed object with the rules of the environment. Dots are allowed
to access attributes of attributes. Integer parts in paths are
looked up as integers.
"""
if attribute... |
Enforce HTML escaping. This will probably double escape variables. | def do_forceescape(value):
"""Enforce HTML escaping. This will probably double escape variables."""
if hasattr(value, '__html__'):
value = value.__html__()
return escape(text_type(value)) |
Escape strings for use in URLs ( uses UTF - 8 encoding ). It accepts both dictionaries and regular strings as well as pairwise iterables. | def do_urlencode(value):
"""Escape strings for use in URLs (uses UTF-8 encoding). It accepts both
dictionaries and regular strings as well as pairwise iterables.
.. versionadded:: 2.7
"""
itemiter = None
if isinstance(value, dict):
itemiter = iteritems(value)
elif not isinstance(va... |
Return a titlecased version of the value. I. e. words will start with uppercase letters all remaining characters are lowercase. | def do_title(s):
"""Return a titlecased version of the value. I.e. words will start with
uppercase letters, all remaining characters are lowercase.
"""
return ''.join(
[item[0].upper() + item[1:].lower()
for item in _word_beginning_split_re.split(soft_unicode(s))
if item]) |
Sort a dict and yield ( key value ) pairs. Because python dicts are unsorted you may want to use this function to order them by either key or value: | def do_dictsort(value, case_sensitive=False, by='key', reverse=False):
"""Sort a dict and yield (key, value) pairs. Because python dicts are
unsorted you may want to use this function to order them by either
key or value:
.. sourcecode:: jinja
{% for item in mydict|dictsort %}
sort... |
Sort an iterable. Per default it sorts ascending if you pass it true as first argument it will reverse the sorting. | def do_sort(
environment, value, reverse=False, case_sensitive=False, attribute=None
):
"""Sort an iterable. Per default it sorts ascending, if you pass it
true as first argument it will reverse the sorting.
If the iterable is made of strings the third parameter can be used to
control the case sen... |
Returns a list of unique items from the the given iterable. | def do_unique(environment, value, case_sensitive=False, attribute=None):
"""Returns a list of unique items from the the given iterable.
.. sourcecode:: jinja
{{ ['foo', 'bar', 'foobar', 'FooBar']|unique }}
-> ['foo', 'bar', 'foobar']
The unique items are yielded in the same order as t... |
Return the smallest item from the sequence. | def do_min(environment, value, case_sensitive=False, attribute=None):
"""Return the smallest item from the sequence.
.. sourcecode:: jinja
{{ [1, 2, 3]|min }}
-> 1
:param case_sensitive: Treat upper and lower case strings as distinct.
:param attribute: Get the object with the max ... |
Return the largest item from the sequence. | def do_max(environment, value, case_sensitive=False, attribute=None):
"""Return the largest item from the sequence.
.. sourcecode:: jinja
{{ [1, 2, 3]|max }}
-> 3
:param case_sensitive: Treat upper and lower case strings as distinct.
:param attribute: Get the object with the max v... |
Return a string which is the concatenation of the strings in the sequence. The separator between elements is an empty string per default you can define it with the optional parameter: | def do_join(eval_ctx, value, d=u'', attribute=None):
"""Return a string which is the concatenation of the strings in the
sequence. The separator between elements is an empty string per
default, you can define it with the optional parameter:
.. sourcecode:: jinja
{{ [1, 2, 3]|join('|') }}
... |
Return the last item of a sequence. | def do_last(environment, seq):
"""Return the last item of a sequence."""
try:
return next(iter(reversed(seq)))
except StopIteration:
return environment.undefined('No last item, sequence was empty.') |
Return a random item from the sequence. | def do_random(context, seq):
"""Return a random item from the sequence."""
try:
return random.choice(seq)
except IndexError:
return context.environment.undefined('No random item, sequence was empty.') |
Format the value like a human - readable file size ( i. e. 13 kB 4. 1 MB 102 Bytes etc ). Per default decimal prefixes are used ( Mega Giga etc. ) if the second parameter is set to True the binary prefixes are used ( Mebi Gibi ). | def do_filesizeformat(value, binary=False):
"""Format the value like a 'human-readable' file size (i.e. 13 kB,
4.1 MB, 102 Bytes, etc). Per default decimal prefixes are used (Mega,
Giga, etc.), if the second parameter is set to `True` the binary
prefixes are used (Mebi, Gibi).
"""
bytes = float... |
Converts URLs in plain text into clickable links. | def do_urlize(eval_ctx, value, trim_url_limit=None, nofollow=False,
target=None, rel=None):
"""Converts URLs in plain text into clickable links.
If you pass the filter an additional integer it will shorten the urls
to that number. Also a third argument exists that makes the urls
"nofollow... |
Return a copy of the string with each line indented by 4 spaces. The first line and blank lines are not indented by default. | def do_indent(
s, width=4, first=False, blank=False, indentfirst=None
):
"""Return a copy of the string with each line indented by 4 spaces. The
first line and blank lines are not indented by default.
:param width: Number of spaces to indent by.
:param first: Don't skip indenting the first line.
... |
Return a truncated copy of the string. The length is specified with the first parameter which defaults to 255. If the second parameter is true the filter will cut the text at length. Otherwise it will discard the last word. If the text was in fact truncated it will append an ellipsis sign (... ). If you want a differen... | def do_truncate(env, s, length=255, killwords=False, end='...', leeway=None):
"""Return a truncated copy of the string. The length is specified
with the first parameter which defaults to ``255``. If the second
parameter is ``true`` the filter will cut the text at length. Otherwise
it will discard the la... |
Return a copy of the string passed to the filter wrapped after 79 characters. You can override this default using the first parameter. If you set the second parameter to false Jinja will not split words apart if they are longer than width. By default the newlines will be the default newlines for the environment but thi... | def do_wordwrap(environment, s, width=79, break_long_words=True,
wrapstring=None):
"""
Return a copy of the string passed to the filter wrapped after
``79`` characters. You can override this default using the first
parameter. If you set the second parameter to `false` Jinja will not
... |
Convert the value into an integer. If the conversion doesn t work it will return 0. You can override this default using the first parameter. You can also override the default base ( 10 ) in the second parameter which handles input with prefixes such as 0b 0o and 0x for bases 2 8 and 16 respectively. The base is ignored... | def do_int(value, default=0, base=10):
"""Convert the value into an integer. If the
conversion doesn't work it will return ``0``. You can
override this default using the first parameter. You
can also override the default base (10) in the second
parameter, which handles input with prefixes such as
... |
Apply python string formatting on an object: | def do_format(value, *args, **kwargs):
"""
Apply python string formatting on an object:
.. sourcecode:: jinja
{{ "%s - %s"|format("Hello?", "Foo!") }}
-> Hello? - Foo!
"""
if args and kwargs:
raise FilterArgumentError('can\'t handle positional and keyword '
... |
Strip SGML/ XML tags and replace adjacent whitespace by one space. | def do_striptags(value):
"""Strip SGML/XML tags and replace adjacent whitespace by one space.
"""
if hasattr(value, '__html__'):
value = value.__html__()
return Markup(text_type(value)).striptags() |
Slice an iterator and return a list of lists containing those items. Useful if you want to create a div containing three ul tags that represent columns: | def do_slice(value, slices, fill_with=None):
"""Slice an iterator and return a list of lists containing
those items. Useful if you want to create a div containing
three ul tags that represent columns:
.. sourcecode:: html+jinja
<div class="columwrapper">
{%- for column in items|slice... |
A filter that batches items. It works pretty much like slice just the other way round. It returns a list of lists with the given number of items. If you provide a second parameter this is used to fill up missing items. See this example: | def do_batch(value, linecount, fill_with=None):
"""
A filter that batches items. It works pretty much like `slice`
just the other way round. It returns a list of lists with the
given number of items. If you provide a second parameter this
is used to fill up missing items. See this example:
.. s... |
Round the number to a given precision. The first parameter specifies the precision ( default is 0 ) the second the rounding method: | def do_round(value, precision=0, method='common'):
"""Round the number to a given precision. The first
parameter specifies the precision (default is ``0``), the
second the rounding method:
- ``'common'`` rounds either up or down
- ``'ceil'`` always rounds up
- ``'floor'`` always rounds down
... |
Group a sequence of objects by a common attribute. | def do_groupby(environment, value, attribute):
"""Group a sequence of objects by a common attribute.
If you for example have a list of dicts or objects that represent persons
with `gender`, `first_name` and `last_name` attributes and you want to
group all users by genders you can do something like the ... |
Returns the sum of a sequence of numbers plus the value of parameter start ( which defaults to 0 ). When the sequence is empty it returns start. | def do_sum(environment, iterable, attribute=None, start=0):
"""Returns the sum of a sequence of numbers plus the value of parameter
'start' (which defaults to 0). When the sequence is empty it returns
start.
It is also possible to sum up only certain attributes:
.. sourcecode:: jinja
Tot... |
Reverse the object or return an iterator that iterates over it the other way round. | def do_reverse(value):
"""Reverse the object or return an iterator that iterates over it the other
way round.
"""
if isinstance(value, string_types):
return value[::-1]
try:
return reversed(value)
except TypeError:
try:
rv = list(value)
rv.reverse(... |
Get an attribute of an object. foo|attr ( bar ) works like foo. bar just that always an attribute is returned and items are not looked up. | def do_attr(environment, obj, name):
"""Get an attribute of an object. ``foo|attr("bar")`` works like
``foo.bar`` just that always an attribute is returned and items are not
looked up.
See :ref:`Notes on subscriptions <notes-on-subscriptions>` for more details.
"""
try:
name = str(name... |
Applies a filter on a sequence of objects or looks up an attribute. This is useful when dealing with lists of objects but you are really only interested in a certain value of it. | def do_map(*args, **kwargs):
"""Applies a filter on a sequence of objects or looks up an attribute.
This is useful when dealing with lists of objects but you are really
only interested in a certain value of it.
The basic usage is mapping on an attribute. Imagine you have a list
of users but you ar... |
Dumps a structure to JSON so that it s safe to use in <script > tags. It accepts the same arguments and returns a JSON string. Note that this is available in templates through the |tojson filter which will also mark the result as safe. Due to how this function escapes certain characters this is safe even if used outsid... | def do_tojson(eval_ctx, value, indent=None):
"""Dumps a structure to JSON so that it's safe to use in ``<script>``
tags. It accepts the same arguments and returns a JSON string. Note that
this is available in templates through the ``|tojson`` filter which will
also mark the result as safe. Due to how... |
Entry Point for completion of main and subcommand options. | def autocomplete():
"""Entry Point for completion of main and subcommand options.
"""
# 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... |
Get the type of path completion ( file dir path or None ) | def get_path_completion_type(cwords, cword, opts):
"""Get the type of path completion (``file``, ``dir``, ``path`` or None)
:param cwords: same as the environmental variable ``COMP_WORDS``
:param cword: same as the environmental variable ``COMP_CWORD``
:param opts: The available options to check
:r... |
If completion_type is file or path list all regular files and directories starting with current ; otherwise only list directories starting with current. | def auto_complete_paths(current, completion_type):
"""If ``completion_type`` is ``file`` or ``path``, list all regular files
and directories starting with ``current``; otherwise only list directories
starting with ``current``.
:param current: The word to be completed
:param completion_type: path co... |
Build a wheel. | def _build_wheel_modern(ireq, output_dir, finder, wheel_cache, kwargs):
"""Build a wheel.
* ireq: The InstallRequirement object to build
* output_dir: The directory to build the wheel in.
* finder: pip's internal Finder object to find the source out of ireq.
* kwargs: Various keyword arguments from... |
Get python version string using subprocess from a given path. | def get_python_version(path):
# type: (str) -> str
"""Get python version string using subprocess from a given path."""
version_cmd = [path, "-c", "import sys; print(sys.version.split()[0])"]
try:
c = vistir.misc.run(
version_cmd,
block=True,
nospin=True,
... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.