sentence1 stringlengths 52 3.87M | sentence2 stringlengths 1 47.2k | label stringclasses 1
value |
|---|---|---|
def ensure_directory(directory):
"""
Create the directories along the provided directory path that do not exist.
"""
directory = os.path.expanduser(directory)
try:
os.makedirs(directory)
except OSError as e:
if e.errno != errno.EEXIST:
raise e | Create the directories along the provided directory path that do not exist. | entailment |
def _process_validation_function_s(validation_func, # type: ValidationFuncs
auto_and_wrapper=True # type: bool
):
# type: (...) -> Union[Callable, List[Callable]]
"""
This function handles the various ways that users may enter 'val... | This function handles the various ways that users may enter 'validation functions', so as to output a single
callable method. Setting "auto_and_wrapper" to False allows callers to get a list of callables instead.
valid8 supports the following expressions for 'validation functions'
* <ValidationFunc>
... | entailment |
def and_(*validation_func # type: ValidationFuncs
):
# type: (...) -> Callable
"""
An 'and' validator: it returns `True` if all of the provided validators return `True`, or raises a
`AtLeastOneFailed` failure on the first `False` received or `Exception` caught.
Note that an implicit `and_... | An 'and' validator: it returns `True` if all of the provided validators return `True`, or raises a
`AtLeastOneFailed` failure on the first `False` received or `Exception` caught.
Note that an implicit `and_` is performed if you provide a list of validators to any of the entry points
(`validate`, `validatio... | entailment |
def not_(validation_func, # type: ValidationFuncs
catch_all=False # type: bool
):
# type: (...) -> Callable
"""
Generates the inverse of the provided validation functions: when the validator returns `False` or raises a
`Failure`, this function returns `True`. Otherwise it raises a `... | Generates the inverse of the provided validation functions: when the validator returns `False` or raises a
`Failure`, this function returns `True`. Otherwise it raises a `DidNotFail` failure.
By default, exceptions of types other than `Failure` are not caught and therefore fail the validation
(`catch_all=F... | entailment |
def or_(*validation_func # type: ValidationFuncs
):
# type: (...) -> Callable
"""
An 'or' validator: returns `True` if at least one of the provided validators returns `True`. All exceptions will be
silently caught. In case of failure, a global `AllValidatorsFailed` failure will be raised, toget... | An 'or' validator: returns `True` if at least one of the provided validators returns `True`. All exceptions will be
silently caught. In case of failure, a global `AllValidatorsFailed` failure will be raised, together with details
about all validation results.
:param validation_func: the base validation fun... | entailment |
def xor_(*validation_func # type: ValidationFuncs
):
# type: (...) -> Callable
"""
A 'xor' validation function: returns `True` if exactly one of the provided validators returns `True`. All exceptions
will be silently caught. In case of failure, a global `XorTooManySuccess` or `AllValidatorsFai... | A 'xor' validation function: returns `True` if exactly one of the provided validators returns `True`. All exceptions
will be silently caught. In case of failure, a global `XorTooManySuccess` or `AllValidatorsFailed` will be raised,
together with details about the various validation results.
:param validati... | entailment |
def not_all(*validation_func, # type: ValidationFuncs
**kwargs
):
# type: (...) -> Callable
"""
An alias for not_(and_(validators)).
:param validation_func: the base validation function or list of base validation functions to use. A callable, a
tuple(callable, help_msg_... | An alias for not_(and_(validators)).
:param validation_func: the base validation function or list of base validation functions to use. A callable, a
tuple(callable, help_msg_str), a tuple(callable, failure_type), or a list of several such elements. Nested lists
are supported and indicate an implici... | entailment |
def failure_raiser(*validation_func, # type: ValidationFuncs
**kwargs
):
# type: (...) -> Callable
"""
This function is automatically used if you provide a tuple `(<function>, <msg>_or_<Failure_type>)`, to any of the
methods in this page or to one of the `valid8` ... | This function is automatically used if you provide a tuple `(<function>, <msg>_or_<Failure_type>)`, to any of the
methods in this page or to one of the `valid8` decorators. It transforms the provided `<function>` into a failure
raiser, raising a subclass of `Failure` in case of failure (either not returning `Tr... | entailment |
def pop_kwargs(kwargs,
names_with_defaults, # type: List[Tuple[str, Any]]
allow_others=False
):
"""
Internal utility method to extract optional arguments from kwargs.
:param kwargs:
:param names_with_defaults:
:param allow_others: if False (default) the... | Internal utility method to extract optional arguments from kwargs.
:param kwargs:
:param names_with_defaults:
:param allow_others: if False (default) then an error will be raised if kwargs still contains something at the end.
:return: | entailment |
def get_details(self):
""" Overrides the base method in order to give details on the various successes and failures """
# transform the dictionary of failures into a printable form
need_to_print_value = True
failures_for_print = OrderedDict()
for validator, failure in self.failu... | Overrides the base method in order to give details on the various successes and failures | entailment |
def play_all_validators(self, validators, value):
"""
Utility method to play all the provided validators on the provided value and output the
:param validators:
:param value:
:return:
"""
successes = list()
failures = OrderedDict()
for validator i... | Utility method to play all the provided validators on the provided value and output the
:param validators:
:param value:
:return: | entailment |
def gen_secret(length=64):
""" Generates a secret of given length
"""
charset = string.ascii_letters + string.digits
return ''.join(random.SystemRandom().choice(charset)
for _ in range(length)) | Generates a secret of given length | entailment |
def encryptfile(filename, passphrase, algo='srp'):
"""
Encrypt a file and write it with .cryptoshop extension.
:param filename: a string with the path to the file to encrypt.
:param passphrase: a string with the user passphrase.
:param algo: a string with the algorithm. Can be srp, aes, twf. Default... | Encrypt a file and write it with .cryptoshop extension.
:param filename: a string with the path to the file to encrypt.
:param passphrase: a string with the user passphrase.
:param algo: a string with the algorithm. Can be srp, aes, twf. Default is srp.
:return: a string with "successfully encrypted" or... | entailment |
def decryptfile(filename, passphrase):
"""
Decrypt a file and write corresponding decrypted file. We remove the .cryptoshop extension.
:param filename: a string with the path to the file to decrypt.
:param passphrase: a string with the user passphrase.
:return: a string with "successfully decrypted"... | Decrypt a file and write corresponding decrypted file. We remove the .cryptoshop extension.
:param filename: a string with the path to the file to decrypt.
:param passphrase: a string with the user passphrase.
:return: a string with "successfully decrypted" or error. | entailment |
def _tokenize(cls, sentence):
"""
Split a sentence while preserving tags.
"""
while True:
match = cls._regex_tag.search(sentence)
if not match:
yield from cls._split(sentence)
return
chunk = sentence[:match.start()]
... | Split a sentence while preserving tags. | entailment |
def map(process, paths, threads=None):
"""
Implements a distributed stategy for processing XML files. This
function constructs a set of py:mod:`multiprocessing` threads (spread over
multiple cores) and uses an internal queue to aggregate outputs. To use
this function, implement a `process()` funct... | Implements a distributed stategy for processing XML files. This
function constructs a set of py:mod:`multiprocessing` threads (spread over
multiple cores) and uses an internal queue to aggregate outputs. To use
this function, implement a `process()` function that takes two arguments
-- a :class:`mwxml... | entailment |
def dump(self):
"""Return the object itself."""
return {
'title': self.title,
'issue_id': self.issue_id,
'reporter': self.reporter,
'assignee': self.assignee,
'status': self.status,
'product': self.product,
'component':... | Return the object itself. | entailment |
def apply_on_each_func_args_sig(func,
cur_args,
cur_kwargs,
sig, # type: Signature
func_to_apply,
func_to_apply_params_dict):
"""
Applies func_to_apply... | Applies func_to_apply on each argument of func according to what's received in current call (cur_args, cur_kwargs).
For each argument of func named 'att' in its signature, the following method is called:
`func_to_apply(cur_att_value, func_to_apply_paramers_dict[att], func, att_name)`
:param func:
:par... | entailment |
def is_product_owner(self, team_id):
"""Ensure the user is a PRODUCT_OWNER."""
if self.is_super_admin():
return True
team_id = uuid.UUID(str(team_id))
return team_id in self.child_teams_ids | Ensure the user is a PRODUCT_OWNER. | entailment |
def is_in_team(self, team_id):
"""Test if user is in team"""
if self.is_super_admin():
return True
team_id = uuid.UUID(str(team_id))
return team_id in self.teams or team_id in self.child_teams_ids | Test if user is in team | entailment |
def is_remoteci(self, team_id=None):
"""Ensure ther resource has the role REMOTECI."""
if team_id is None:
return self._is_remoteci
team_id = uuid.UUID(str(team_id))
if team_id not in self.teams_ids:
return False
return self.teams[team_id]['role'] == 'REMO... | Ensure ther resource has the role REMOTECI. | entailment |
def is_feeder(self, team_id=None):
"""Ensure ther resource has the role FEEDER."""
if team_id is None:
return self._is_feeder
team_id = uuid.UUID(str(team_id))
if team_id not in self.teams_ids:
return False
return self.teams[team_id]['role'] == 'FEEDER' | Ensure ther resource has the role FEEDER. | entailment |
def document(self):
"""
:return: the :class:`Document` node that contains this node,
or ``self`` if this node is the document.
"""
if self.is_document:
return self
return self.adapter.wrap_document(self.adapter.impl_document) | :return: the :class:`Document` node that contains this node,
or ``self`` if this node is the document. | entailment |
def root(self):
"""
:return: the root :class:`Element` node of the document that
contains this node, or ``self`` if this node is the root element.
"""
if self.is_root:
return self
return self.adapter.wrap_node(
self.adapter.impl_root_element, s... | :return: the root :class:`Element` node of the document that
contains this node, or ``self`` if this node is the root element. | entailment |
def _convert_nodelist(self, impl_nodelist):
"""
Convert a list of underlying implementation nodes into a list of
*xml4h* wrapper nodes.
"""
nodelist = [
self.adapter.wrap_node(n, self.adapter.impl_document, self.adapter)
for n in impl_nodelist]
ret... | Convert a list of underlying implementation nodes into a list of
*xml4h* wrapper nodes. | entailment |
def parent(self):
"""
:return: the parent of this node, or *None* of the node has no parent.
"""
parent_impl_node = self.adapter.get_node_parent(self.impl_node)
return self.adapter.wrap_node(
parent_impl_node, self.adapter.impl_document, self.adapter) | :return: the parent of this node, or *None* of the node has no parent. | entailment |
def children(self):
"""
:return: a :class:`NodeList` of this node's child nodes.
"""
impl_nodelist = self.adapter.get_node_children(self.impl_node)
return self._convert_nodelist(impl_nodelist) | :return: a :class:`NodeList` of this node's child nodes. | entailment |
def child(self, local_name=None, name=None, ns_uri=None, node_type=None,
filter_fn=None):
"""
:return: the first child node matching the given constraints, or \
*None* if there are no matching child nodes.
Delegates to :meth:`NodeList.filter`.
"""
re... | :return: the first child node matching the given constraints, or \
*None* if there are no matching child nodes.
Delegates to :meth:`NodeList.filter`. | entailment |
def siblings(self):
"""
:return: a list of this node's sibling nodes.
:rtype: NodeList
"""
impl_nodelist = self.adapter.get_node_children(self.parent.impl_node)
return self._convert_nodelist(
[n for n in impl_nodelist if n != self.impl_node]) | :return: a list of this node's sibling nodes.
:rtype: NodeList | entailment |
def siblings_before(self):
"""
:return: a list of this node's siblings that occur *before* this
node in the DOM.
"""
impl_nodelist = self.adapter.get_node_children(self.parent.impl_node)
before_nodelist = []
for n in impl_nodelist:
if n == self.imp... | :return: a list of this node's siblings that occur *before* this
node in the DOM. | entailment |
def siblings_after(self):
"""
:return: a list of this node's siblings that occur *after* this
node in the DOM.
"""
impl_nodelist = self.adapter.get_node_children(self.parent.impl_node)
after_nodelist = []
is_after_myself = False
for n in impl_nodelist:... | :return: a list of this node's siblings that occur *after* this
node in the DOM. | entailment |
def delete(self, destroy=True):
"""
Delete this node from the owning document.
:param bool destroy: if True the child node will be destroyed in
addition to being removed from the document.
:returns: the removed child node, or *None* if the child was destroyed.
"""
... | Delete this node from the owning document.
:param bool destroy: if True the child node will be destroyed in
addition to being removed from the document.
:returns: the removed child node, or *None* if the child was destroyed. | entailment |
def clone_node(self, node):
"""
Clone a node from another document to become a child of this node, by
copying the node's data into this document but leaving the node
untouched in the source document. The node to be cloned can be
a :class:`Node` based on the same underlying XML li... | Clone a node from another document to become a child of this node, by
copying the node's data into this document but leaving the node
untouched in the source document. The node to be cloned can be
a :class:`Node` based on the same underlying XML library implementation
and adapter, or a "... | entailment |
def transplant_node(self, node):
"""
Transplant a node from another document to become a child of this node,
removing it from the source document. The node to be transplanted can
be a :class:`Node` based on the same underlying XML library
implementation and adapter, or a "raw" n... | Transplant a node from another document to become a child of this node,
removing it from the source document. The node to be transplanted can
be a :class:`Node` based on the same underlying XML library
implementation and adapter, or a "raw" node from that implementation.
:param node: t... | entailment |
def find(self, name=None, ns_uri=None, first_only=False):
"""
Find :class:`Element` node descendants of this node, with optional
constraints to limit the results.
:param name: limit results to elements with this name.
If *None* or ``'*'`` all element names are matched.
... | Find :class:`Element` node descendants of this node, with optional
constraints to limit the results.
:param name: limit results to elements with this name.
If *None* or ``'*'`` all element names are matched.
:type name: string or None
:param ns_uri: limit results to elements... | entailment |
def find_first(self, name=None, ns_uri=None):
"""
Find the first :class:`Element` node descendant of this node that
matches any optional constraints, or None if there are no matching
elements.
Delegates to :meth:`find` with ``first_only=True``.
"""
return self.fi... | Find the first :class:`Element` node descendant of this node that
matches any optional constraints, or None if there are no matching
elements.
Delegates to :meth:`find` with ``first_only=True``. | entailment |
def find_doc(self, name=None, ns_uri=None, first_only=False):
"""
Find :class:`Element` node descendants of the document containing
this node, with optional constraints to limit the results.
Delegates to :meth:`find` applied to this node's owning document.
"""
return sel... | Find :class:`Element` node descendants of the document containing
this node, with optional constraints to limit the results.
Delegates to :meth:`find` applied to this node's owning document. | entailment |
def write(self, writer=None, encoding='utf-8', indent=0, newline='',
omit_declaration=False, node_depth=0, quote_char='"'):
"""
Serialize this node and its descendants to text, writing
the output to a given *writer* or to stdout.
:param writer: an object such as a file or st... | Serialize this node and its descendants to text, writing
the output to a given *writer* or to stdout.
:param writer: an object such as a file or stream to which XML text
is sent. If *None* text is sent to :attr:`sys.stdout`.
:type writer: a file, stream, etc or None
:param s... | entailment |
def xml(self, indent=4, **kwargs):
"""
:return: this node as XML text.
Delegates to :meth:`write`
"""
writer = StringIO()
self.write(writer, indent=indent, **kwargs)
return writer.getvalue() | :return: this node as XML text.
Delegates to :meth:`write` | entailment |
def xpath(self, xpath, **kwargs):
"""
Perform an XPath query on the current node.
:param string xpath: XPath query.
:param dict kwargs: Optional keyword arguments that are passed through
to the underlying XML library implementation.
:return: results of the query as ... | Perform an XPath query on the current node.
:param string xpath: XPath query.
:param dict kwargs: Optional keyword arguments that are passed through
to the underlying XML library implementation.
:return: results of the query as a list of :class:`Node` objects, or
a list... | entailment |
def set_attributes(self, attr_obj=None, ns_uri=None, **attr_dict):
"""
Add or update this element's attributes, where attributes can be
specified in a number of ways.
:param attr_obj: a dictionary or list of attribute name/value pairs.
:type attr_obj: dict, list, tuple, or None
... | Add or update this element's attributes, where attributes can be
specified in a number of ways.
:param attr_obj: a dictionary or list of attribute name/value pairs.
:type attr_obj: dict, list, tuple, or None
:param ns_uri: a URI defining a namespace for the new attributes.
:type... | entailment |
def attributes(self):
"""
Get or set this element's attributes as name/value pairs.
.. note::
Setting element attributes via this accessor will **remove**
any existing attributes, as opposed to the :meth:`set_attributes`
method which only updates and replaces... | Get or set this element's attributes as name/value pairs.
.. note::
Setting element attributes via this accessor will **remove**
any existing attributes, as opposed to the :meth:`set_attributes`
method which only updates and replaces them. | entailment |
def attribute_nodes(self):
"""
:return: a list of this element's attributes as
:class:`Attribute` nodes.
"""
impl_attr_nodes = self.adapter.get_node_attributes(self.impl_node)
wrapped_attr_nodes = [
self.adapter.wrap_node(a, self.adapter.impl_document, sel... | :return: a list of this element's attributes as
:class:`Attribute` nodes. | entailment |
def attribute_node(self, name, ns_uri=None):
"""
:param string name: the name of the attribute to return.
:param ns_uri: a URI defining a namespace constraint on the attribute.
:type ns_uri: string or None
:return: this element's attributes that match ``ns_uri`` as
:... | :param string name: the name of the attribute to return.
:param ns_uri: a URI defining a namespace constraint on the attribute.
:type ns_uri: string or None
:return: this element's attributes that match ``ns_uri`` as
:class:`Attribute` nodes. | entailment |
def set_ns_prefix(self, prefix, ns_uri):
"""
Define a namespace prefix that will serve as shorthand for the given
namespace URI in element names.
:param string prefix: prefix that will serve as an alias for a
the namespace URI.
:param string ns_uri: namespace URI tha... | Define a namespace prefix that will serve as shorthand for the given
namespace URI in element names.
:param string prefix: prefix that will serve as an alias for a
the namespace URI.
:param string ns_uri: namespace URI that will be denoted by the
prefix. | entailment |
def add_element(self, name, ns_uri=None, attributes=None,
text=None, before_this_element=False):
"""
Add a new child element to this element, with an optional namespace
definition. If no namespace is provided the child will be assigned
to the default namespace.
:para... | Add a new child element to this element, with an optional namespace
definition. If no namespace is provided the child will be assigned
to the default namespace.
:param string name: a name for the child node. The name may be used
to apply a namespace to the child by including:
... | entailment |
def add_text(self, text):
"""
Add a text node to this element.
Adding text with this method is subtly different from assigning a new
text value with :meth:`text` accessor, because it "appends" to rather
than replacing this element's set of text nodes.
:param text: text ... | Add a text node to this element.
Adding text with this method is subtly different from assigning a new
text value with :meth:`text` accessor, because it "appends" to rather
than replacing this element's set of text nodes.
:param text: text content to add to this element.
:param... | entailment |
def add_instruction(self, target, data):
"""
Add an instruction node to this element.
:param string text: text content to add as an instruction.
"""
self._add_instruction(self.impl_node, target, data) | Add an instruction node to this element.
:param string text: text content to add as an instruction. | entailment |
def items(self):
"""
:return: a list of name/value attribute pairs sorted by attribute name.
"""
sorted_keys = sorted(self.keys())
return [(k, self[k]) for k in sorted_keys] | :return: a list of name/value attribute pairs sorted by attribute name. | entailment |
def namespace_uri(self, name):
"""
:param string name: the name of an attribute to look up.
:return: the namespace URI associated with the named attribute,
or None.
"""
a_node = self.adapter.get_node_attribute_node(self.impl_element, name)
if a_node is None:
... | :param string name: the name of an attribute to look up.
:return: the namespace URI associated with the named attribute,
or None. | entailment |
def prefix(self, name):
"""
:param string name: the name of an attribute to look up.
:return: the prefix component of the named attribute's name,
or None.
"""
a_node = self.adapter.get_node_attribute_node(self.impl_element, name)
if a_node is None:
... | :param string name: the name of an attribute to look up.
:return: the prefix component of the named attribute's name,
or None. | entailment |
def element(self):
"""
:return: the :class:`Element` that contains these attributes.
"""
return self.adapter.wrap_node(
self.impl_element, self.adapter.impl_document, self.adapter) | :return: the :class:`Element` that contains these attributes. | entailment |
def filter(self, local_name=None, name=None, ns_uri=None, node_type=None,
filter_fn=None, first_only=False):
"""
Apply filters to the set of nodes in this list.
:param local_name: a local name used to filter the nodes.
:type local_name: string or None
:param name: a ... | Apply filters to the set of nodes in this list.
:param local_name: a local name used to filter the nodes.
:type local_name: string or None
:param name: a name used to filter the nodes.
:type name: string or None
:param ns_uri: a namespace URI used to filter the nodes.
... | entailment |
def get_all_analytics(user, job_id):
"""Get all analytics of a job."""
args = schemas.args(flask.request.args.to_dict())
v1_utils.verify_existence_and_get(job_id, models.JOBS)
query = v1_utils.QueryBuilder(_TABLE, args, _A_COLUMNS)
# If not admin nor rh employee then restrict the view to the team
... | Get all analytics of a job. | entailment |
def get_analytic(user, job_id, anc_id):
"""Get an analytic."""
v1_utils.verify_existence_and_get(job_id, models.JOBS)
analytic = v1_utils.verify_existence_and_get(anc_id, _TABLE)
analytic = dict(analytic)
if not user.is_in_team(analytic['team_id']):
raise dci_exc.Unauthorized()
return f... | Get an analytic. | entailment |
def write_node(node, writer=None, encoding='utf-8', indent=0, newline='',
omit_declaration=False, node_depth=0, quote_char='"'):
"""
Serialize an *xml4h* DOM node and its descendants to text, writing
the output to a given *writer* or to stdout.
:param node: the DOM node whose content and descen... | Serialize an *xml4h* DOM node and its descendants to text, writing
the output to a given *writer* or to stdout.
:param node: the DOM node whose content and descendants will
be serialized.
:type node: an :class:`xml4h.nodes.Node` or subclass
:param writer: an object such as a file or stream to w... | entailment |
def encry_decry_chunk(chunk, key, algo, bool_encry, assoc_data):
"""
When bool_encry is True, encrypt a chunk of the file with the key and a randomly generated nonce. When it is False,
the function extract the nonce from the cipherchunk (first 16 bytes), and decrypt the rest of the chunk.
:param chunk: ... | When bool_encry is True, encrypt a chunk of the file with the key and a randomly generated nonce. When it is False,
the function extract the nonce from the cipherchunk (first 16 bytes), and decrypt the rest of the chunk.
:param chunk: a chunk in bytes to encrypt or decrypt.
:param key: a 32 bytes key in byt... | entailment |
def retrieve_info(self):
"""Query Bugzilla API to retrieve the needed infos."""
scheme = urlparse(self.url).scheme
netloc = urlparse(self.url).netloc
query = urlparse(self.url).query
if scheme not in ('http', 'https'):
return
for item in query.split('&'):
... | Query Bugzilla API to retrieve the needed infos. | entailment |
def minlen(min_length,
strict=False # type: bool
):
"""
'Minimum length' validation_function generator.
Returns a validation_function to check that len(x) >= min_length (strict=False, default)
or len(x) > min_length (strict=True)
:param min_length: minimum length for x
:p... | 'Minimum length' validation_function generator.
Returns a validation_function to check that len(x) >= min_length (strict=False, default)
or len(x) > min_length (strict=True)
:param min_length: minimum length for x
:param strict: Boolean flag to switch between len(x) >= min_length (strict=False) and len... | entailment |
def maxlen(max_length,
strict=False # type: bool
):
"""
'Maximum length' validation_function generator.
Returns a validation_function to check that len(x) <= max_length (strict=False, default) or len(x) < max_length (strict=True)
:param max_length: maximum length for x
:param... | 'Maximum length' validation_function generator.
Returns a validation_function to check that len(x) <= max_length (strict=False, default) or len(x) < max_length (strict=True)
:param max_length: maximum length for x
:param strict: Boolean flag to switch between len(x) <= max_length (strict=False) and len(x) ... | entailment |
def has_length(ref_length):
"""
'length equals' validation function generator.
Returns a validation_function to check that `len(x) == ref_length`
:param ref_length:
:return:
"""
def has_length_(x):
if len(x) == ref_length:
return True
else:
raise Wron... | 'length equals' validation function generator.
Returns a validation_function to check that `len(x) == ref_length`
:param ref_length:
:return: | entailment |
def length_between(min_len,
max_len,
open_left=False, # type: bool
open_right=False # type: bool
):
"""
'Is length between' validation_function generator.
Returns a validation_function to check that `min_len <= len(x) <= max_len (... | 'Is length between' validation_function generator.
Returns a validation_function to check that `min_len <= len(x) <= max_len (default)`. `open_right` and `open_left`
flags allow to transform each side into strict mode. For example setting `open_left=True` will enforce
`min_len < len(x) <= max_len`.
:pa... | entailment |
def is_in(allowed_values # type: Set
):
"""
'Values in' validation_function generator.
Returns a validation_function to check that x is in the provided set of allowed values
:param allowed_values: a set of allowed values
:return:
"""
def is_in_allowed_values(x):
if x in a... | 'Values in' validation_function generator.
Returns a validation_function to check that x is in the provided set of allowed values
:param allowed_values: a set of allowed values
:return: | entailment |
def is_subset(reference_set # type: Set
):
"""
'Is subset' validation_function generator.
Returns a validation_function to check that x is a subset of reference_set
:param reference_set: the reference set
:return:
"""
def is_subset_of(x):
missing = x - reference_set
... | 'Is subset' validation_function generator.
Returns a validation_function to check that x is a subset of reference_set
:param reference_set: the reference set
:return: | entailment |
def contains(ref_value):
"""
'Contains' validation_function generator.
Returns a validation_function to check that `ref_value in x`
:param ref_value: a value that must be present in x
:return:
"""
def contains_ref_value(x):
if ref_value in x:
return True
else:
... | 'Contains' validation_function generator.
Returns a validation_function to check that `ref_value in x`
:param ref_value: a value that must be present in x
:return: | entailment |
def is_superset(reference_set # type: Set
):
"""
'Is superset' validation_function generator.
Returns a validation_function to check that x is a superset of reference_set
:param reference_set: the reference set
:return:
"""
def is_superset_of(x):
missing = reference... | 'Is superset' validation_function generator.
Returns a validation_function to check that x is a superset of reference_set
:param reference_set: the reference set
:return: | entailment |
def on_all_(*validation_func):
"""
Generates a validation_function for collection inputs where each element of the input will be validated against the
validation_functions provided. For convenience, a list of validation_functions can be provided and will be replaced
with an 'and_'.
Note that if you... | Generates a validation_function for collection inputs where each element of the input will be validated against the
validation_functions provided. For convenience, a list of validation_functions can be provided and will be replaced
with an 'and_'.
Note that if you want to apply DIFFERENT validation_functio... | entailment |
def on_each_(*validation_functions_collection):
"""
Generates a validation_function for collection inputs where each element of the input will be validated against the
corresponding validation_function(s) in the validation_functions_collection. Validators inside the tuple can be
provided as a list for c... | Generates a validation_function for collection inputs where each element of the input will be validated against the
corresponding validation_function(s) in the validation_functions_collection. Validators inside the tuple can be
provided as a list for convenience, this will be replaced with an 'and_' operator if... | entailment |
def get_jobs_events_from_sequence(user, sequence):
"""Get all the jobs events from a given sequence number."""
args = schemas.args(flask.request.args.to_dict())
if user.is_not_super_admin():
raise dci_exc.Unauthorized()
query = sql.select([models.JOBS_EVENTS]). \
select_from(models.JO... | Get all the jobs events from a given sequence number. | entailment |
def from_file(cls, f):
"""
Constructs a :class:`~mwxml.iteration.dump.Dump` from a `file` pointer.
:Parameters:
f : `file`
A plain text file pointer containing XML to process
"""
element = ElementIterator.from_file(f)
assert element.tag == "me... | Constructs a :class:`~mwxml.iteration.dump.Dump` from a `file` pointer.
:Parameters:
f : `file`
A plain text file pointer containing XML to process | entailment |
def from_page_xml(cls, page_xml):
"""
Constructs a :class:`~mwxml.iteration.dump.Dump` from a <page> block.
:Parameters:
page_xml : `str` | `file`
Either a plain string or a file containing <page> block XML to
process
"""
header = """
... | Constructs a :class:`~mwxml.iteration.dump.Dump` from a <page> block.
:Parameters:
page_xml : `str` | `file`
Either a plain string or a file containing <page> block XML to
process | entailment |
def calc_derivation(passphrase, salt):
"""
Calculate a 32 bytes key derivation with Argon2.
:param passphrase: A string of any length specified by user.
:param salt: 512 bits generated by Botan Random Number Generator.
:return: a 32 bytes keys.
"""
argonhash = argon2.low_level.hash_secret_ra... | Calculate a 32 bytes key derivation with Argon2.
:param passphrase: A string of any length specified by user.
:param salt: 512 bits generated by Botan Random Number Generator.
:return: a 32 bytes keys. | entailment |
def get_node_text(self, node):
"""
Return contatenated value of all text node children of this element
"""
text_children = [n.nodeValue for n in self.get_node_children(node)
if n.nodeType == xml.dom.Node.TEXT_NODE]
if text_children:
return u''... | Return contatenated value of all text node children of this element | entailment |
def set_node_text(self, node, text):
"""
Set text value as sole Text child node of element; any existing
Text nodes are removed
"""
# Remove any existing Text node children
for child in self.get_node_children(node):
if child.nodeType == xml.dom.Node.TEXT_NODE:... | Set text value as sole Text child node of element; any existing
Text nodes are removed | entailment |
def _get_contents(self):
"""Create strings from glob strings."""
def files():
for value in super(GlobBundle, self)._get_contents():
for path in glob.glob(value):
yield path
return list(files()) | Create strings from glob strings. | entailment |
def is_generic_type(tp):
"""Test if the given type is a generic type. This includes Generic itself, but
excludes special typing constructs such as Union, Tuple, Callable, ClassVar.
Examples::
is_generic_type(int) == False
is_generic_type(Union[int, str]) == False
is_generic_type(Uni... | Test if the given type is a generic type. This includes Generic itself, but
excludes special typing constructs such as Union, Tuple, Callable, ClassVar.
Examples::
is_generic_type(int) == False
is_generic_type(Union[int, str]) == False
is_generic_type(Union[int, T]) == False
is_... | entailment |
def is_union_type(tp):
"""Test if the type is a union type. Examples::
is_union_type(int) == False
is_union_type(Union) == True
is_union_type(Union[int, int]) == False
is_union_type(Union[T, int]) == True
"""
if NEW_TYPING:
return (tp is Union or
isin... | Test if the type is a union type. Examples::
is_union_type(int) == False
is_union_type(Union) == True
is_union_type(Union[int, int]) == False
is_union_type(Union[T, int]) == True | entailment |
def is_classvar(tp):
"""Test if the type represents a class variable. Examples::
is_classvar(int) == False
is_classvar(ClassVar) == True
is_classvar(ClassVar[int]) == True
is_classvar(ClassVar[List[T]]) == True
"""
if NEW_TYPING:
return (tp is ClassVar or
... | Test if the type represents a class variable. Examples::
is_classvar(int) == False
is_classvar(ClassVar) == True
is_classvar(ClassVar[int]) == True
is_classvar(ClassVar[List[T]]) == True | entailment |
def parse(to_parse, ignore_whitespace_text_nodes=True, adapter=None):
"""
Parse an XML document into an *xml4h*-wrapped DOM representation
using an underlying XML library implementation.
:param to_parse: an XML document file, document string, or the
path to an XML file. If a string value is giv... | Parse an XML document into an *xml4h*-wrapped DOM representation
using an underlying XML library implementation.
:param to_parse: an XML document file, document string, or the
path to an XML file. If a string value is given that contains
a ``<`` character it is treated as literal XML data, othe... | entailment |
def build(tagname_or_element, ns_uri=None, adapter=None):
"""
Return a :class:`~xml4h.builder.Builder` that represents an element in
a new or existing XML DOM and provides "chainable" methods focussed
specifically on adding XML content.
:param tagname_or_element: a string name for the root node of ... | Return a :class:`~xml4h.builder.Builder` that represents an element in
a new or existing XML DOM and provides "chainable" methods focussed
specifically on adding XML content.
:param tagname_or_element: a string name for the root node of a
new XML document, or an :class:`~xml4h.nodes.Element` node i... | entailment |
def get_none_policy_text(none_policy, # type: int
verbose=False # type: bool
):
"""
Returns a user-friendly description of a NonePolicy taking into account NoneArgPolicy
:param none_policy:
:param verbose:
:return:
"""
if none_policy is N... | Returns a user-friendly description of a NonePolicy taking into account NoneArgPolicy
:param none_policy:
:param verbose:
:return: | entailment |
def _add_none_handler(validation_callable, # type: Callable
none_policy # type: int
):
# type: (...) -> Callable
"""
Adds a wrapper or nothing around the provided validation_callable, depending on the selected policy
:param validation_callable:
... | Adds a wrapper or nothing around the provided validation_callable, depending on the selected policy
:param validation_callable:
:param none_policy: an int representing the None policy, see NonePolicy
:return: | entailment |
def add_base_type_dynamically(error_type, additional_type):
"""
Utility method to create a new type dynamically, inheriting from both error_type (first) and additional_type
(second). The class representation (repr(cls)) of the resulting class reflects this by displaying both names
(fully qualified for t... | Utility method to create a new type dynamically, inheriting from both error_type (first) and additional_type
(second). The class representation (repr(cls)) of the resulting class reflects this by displaying both names
(fully qualified for the first type, __name__ for the second)
For example
```
> n... | entailment |
def assert_valid(name, # type: str
value, # type: Any
*validation_func, # type: ValidationFuncs
**kwargs):
"""
Validates value `value` using validation function(s) `base_validator_s`.
As opposed to `is_valid`, this function raises ... | Validates value `value` using validation function(s) `base_validator_s`.
As opposed to `is_valid`, this function raises a `ValidationError` if validation fails.
It is therefore designed to be used for defensive programming, in an independent statement before the code that you
intent to protect.
```pyt... | entailment |
def is_valid(value,
*validation_func, # type: Union[Callable, List[Callable]]
**kwargs
):
# type: (...) -> bool
"""
Validates value `value` using validation function(s) `validator_func`.
As opposed to `assert_valid`, this function returns a boolean indicating if v... | Validates value `value` using validation function(s) `validator_func`.
As opposed to `assert_valid`, this function returns a boolean indicating if validation was a success or a failure.
It is therefore designed to be used within if ... else ... statements:
```python
if is_valid(x, isfinite):
..... | entailment |
def create_manually(cls,
validation_function_name, # type: str
var_name, # type: str
var_value,
validation_outcome=None, # type: Any
help_msg=None, # type: str
... | Creates an instance without using a Validator.
This method is not the primary way that errors are created - they should rather created by the validation entry
points. However it can be handy in rare edge cases.
:param validation_function_name:
:param var_name:
:param var_value:... | entailment |
def get_details(self):
""" The function called to get the details appended to the help message when self.append_details is True """
# create the exception main message according to the type of result
if isinstance(self.validation_outcome, Exception):
prefix = 'Validation function [... | The function called to get the details appended to the help message when self.append_details is True | entailment |
def get_variable_str(self):
"""
Utility method to get the variable value or 'var_name=value' if name is not None.
Note that values with large string representations will not get printed
:return:
"""
if self.var_name is None:
prefix = ''
else:
... | Utility method to get the variable value or 'var_name=value' if name is not None.
Note that values with large string representations will not get printed
:return: | entailment |
def assert_valid(self,
name, # type: str
value, # type: Any
error_type=None, # type: Type[ValidationError]
help_msg=None, # type: str
**kw_context_args):
"""
Asserts that t... | Asserts that the provided named value is valid with respect to the inner base validation functions. It returns
silently in case of success, and raises a `ValidationError` or a subclass in case of failure. This corresponds
to a 'Defensive programming' (sometimes known as 'Offensive programming') mode.
... | entailment |
def _create_validation_error(self,
name, # type: str
value, # type: Any
validation_outcome=None, # type: Any
error_type=None, # type: Type[... | The function doing the final error raising. | entailment |
def is_valid(self,
value # type: Any
):
# type: (...) -> bool
"""
Validates the provided value and returns a boolean indicating success or failure. Any Exception happening in
the validation process will be silently caught.
:param value: the val... | Validates the provided value and returns a boolean indicating success or failure. Any Exception happening in
the validation process will be silently caught.
:param value: the value to validate
:return: a boolean flag indicating success or failure | entailment |
def create_tags(user):
"""Create a tag."""
values = {
'id': utils.gen_uuid(),
'created_at': datetime.datetime.utcnow().isoformat()
}
values.update(schemas.tag.post(flask.request.json))
with flask.g.db_conn.begin():
where_clause = sql.and_(
_TABLE.c.name == values... | Create a tag. | entailment |
def get_tags(user):
"""Get all tags."""
args = schemas.args(flask.request.args.to_dict())
query = v1_utils.QueryBuilder(_TABLE, args, _T_COLUMNS)
nb_rows = query.get_number_of_rows()
rows = query.execute(fetchall=True)
rows = v1_utils.format_result(rows, _TABLE.name)
return flask.jsonify({'t... | Get all tags. | entailment |
def delete_tag_by_id(user, tag_id):
"""Delete a tag."""
query = _TABLE.delete().where(_TABLE.c.id == tag_id)
result = flask.g.db_conn.execute(query)
if not result.rowcount:
raise dci_exc.DCIConflict('Tag deletion conflict', tag_id)
return flask.Response(None, 204, content_type='application... | Delete a tag. | entailment |
def init_app(self, app, entry_point_group='invenio_assets.bundles',
**kwargs):
"""Initialize application object.
:param app: An instance of :class:`~flask.Flask`.
:param entry_point_group: A name of entry point group used to load
``webassets`` bundles.
.. v... | Initialize application object.
:param app: An instance of :class:`~flask.Flask`.
:param entry_point_group: A name of entry point group used to load
``webassets`` bundles.
.. versionchanged:: 1.0.0b2
The *entrypoint* has been renamed to *entry_point_group*. | entailment |
def init_config(self, app):
"""Initialize configuration.
:param app: An instance of :class:`~flask.Flask`.
"""
app.config.setdefault('REQUIREJS_BASEURL', app.static_folder)
app.config.setdefault('COLLECT_STATIC_ROOT', app.static_folder)
app.config.setdefault('COLLECT_STO... | Initialize configuration.
:param app: An instance of :class:`~flask.Flask`. | entailment |
def load_entrypoint(self, entry_point_group):
"""Load entrypoint.
:param entry_point_group: A name of entry point group used to load
``webassets`` bundles.
.. versionchanged:: 1.0.0b2
The *entrypoint* has been renamed to *entry_point_group*.
"""
for ep in... | Load entrypoint.
:param entry_point_group: A name of entry point group used to load
``webassets`` bundles.
.. versionchanged:: 1.0.0b2
The *entrypoint* has been renamed to *entry_point_group*. | entailment |
def assert_instance_of(value,
allowed_types # type: Union[Type, Tuple[Type]]
):
"""
An inlined version of instance_of(var_types)(value) without 'return True': it does not return anything in case of
success, and raises a HasWrongType exception in case of failure... | An inlined version of instance_of(var_types)(value) without 'return True': it does not return anything in case of
success, and raises a HasWrongType exception in case of failure.
Used in validate and validation/validator
:param value: the value to check
:param allowed_types: the type(s) to enforce. If... | entailment |
def assert_subclass_of(typ,
allowed_types # type: Union[Type, Tuple[Type]]
):
"""
An inlined version of subclass_of(var_types)(value) without 'return True': it does not return anything in case of
success, and raises a IsWrongType exception in case of failure.
... | An inlined version of subclass_of(var_types)(value) without 'return True': it does not return anything in case of
success, and raises a IsWrongType exception in case of failure.
Used in validate and validation/validator
:param typ: the type to check
:param allowed_types: the type(s) to enforce. If a t... | entailment |
def validate(name, # type: str
value, # type: Any
enforce_not_none=True, # type: bool
equals=None, # type: Any
instance_of=None, # type: Union[Type, Tuple[Type]]
subclass_of=None, # type: Union[Ty... | A validation function for quick inline validation of `value`, with minimal capabilities:
* None handling: reject None (enforce_not_none=True, default), or accept None silently (enforce_not_none=False)
* Type validation: `value` should be an instance of any of `var_types` if provided
* Value validation:
... | entailment |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.