repository_name
stringlengths
7
55
func_path_in_repository
stringlengths
4
223
func_name
stringlengths
1
134
whole_func_string
stringlengths
75
104k
language
stringclasses
1 value
func_code_string
stringlengths
75
104k
func_code_tokens
listlengths
19
28.4k
func_documentation_string
stringlengths
1
46.9k
func_documentation_tokens
listlengths
1
1.97k
split_name
stringclasses
1 value
func_code_url
stringlengths
87
315
danijar/sets
sets/utility.py
ensure_directory
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
python
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
[ "def", "ensure_directory", "(", "directory", ")", ":", "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.
[ "Create", "the", "directories", "along", "the", "provided", "directory", "path", "that", "do", "not", "exist", "." ]
train
https://github.com/danijar/sets/blob/2542c28f43d0af18932cb5b82f54ffb6ae557d12/sets/utility.py#L71-L80
smarie/python-valid8
valid8/composition.py
_process_validation_function_s
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 '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> * List[<ValidationFunc>(s)]. The list must not be empty. <ValidationFunc> may either be * a callable or a mini-lambda expression (instance of LambdaExpression - in which case it is automatically 'closed'). * a Tuple[callable or mini-lambda expression ; failure_type]. Where failure type should be a subclass of valid8.Failure. In which case the tuple will be replaced with a _failure_raiser(callable, failure_type) When the contents provided does not match the above, this function raises a ValueError. Otherwise it produces a list of callables, that will typically be turned into a `and_` in the nominal case except if this is called inside `or_` or `xor_`. :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 implicit `and_`. Tuples indicate an implicit `_failure_raiser`. [mini_lambda](https://smarie.github.io/python-mini-lambda/) expressions can be used instead of callables, they will be transformed to functions automatically. :param auto_and_wrapper: if True (default), this function returns a single callable that is a and_() of all functions. Otherwise a list is returned. :return: """ # handle the case where validation_func is not yet a list or is empty or none if validation_func is None: raise ValueError('mandatory validation_func is None') elif not isinstance(validation_func, list): # so not use list() because we do not want to convert tuples here. validation_func = [validation_func] elif len(validation_func) == 0: raise ValueError('provided validation_func list is empty') # now validation_func is a non-empty list final_list = [] for v in validation_func: # special case of a LambdaExpression: automatically convert to a function # note: we have to do it before anything else (such as .index) otherwise we may get failures v = as_function(v) if isinstance(v, tuple): # convert all the tuples to failure raisers if len(v) == 2: if isinstance(v[1], str): final_list.append(_failure_raiser(v[0], help_msg=v[1])) elif isinstance(v[1], type) and issubclass(v[1], WrappingFailure): final_list.append(_failure_raiser(v[0], failure_type=v[1])) else: raise TypeError('base validation function(s) not compliant with the allowed syntax. Base validation' ' function(s) can be {}. Found [{}].'.format(supported_syntax, str(v))) else: raise TypeError('base validation function(s) not compliant with the allowed syntax. Base validation' ' function(s) can be {}. Found [{}].'.format(supported_syntax, str(v))) elif callable(v): # use the validator directly final_list.append(v) elif isinstance(v, list): # a list is an implicit and_, make it explicit final_list.append(and_(*v)) else: raise TypeError('base validation function(s) not compliant with the allowed syntax. Base validation' ' function(s) can be {}. Found [{}].'.format(supported_syntax, str(v))) # return what is required: if auto_and_wrapper: # a single callable doing the 'and' return and_(*final_list) else: # or the list (typically for use inside or_(), xor_()...) return final_list
python
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 '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> * List[<ValidationFunc>(s)]. The list must not be empty. <ValidationFunc> may either be * a callable or a mini-lambda expression (instance of LambdaExpression - in which case it is automatically 'closed'). * a Tuple[callable or mini-lambda expression ; failure_type]. Where failure type should be a subclass of valid8.Failure. In which case the tuple will be replaced with a _failure_raiser(callable, failure_type) When the contents provided does not match the above, this function raises a ValueError. Otherwise it produces a list of callables, that will typically be turned into a `and_` in the nominal case except if this is called inside `or_` or `xor_`. :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 implicit `and_`. Tuples indicate an implicit `_failure_raiser`. [mini_lambda](https://smarie.github.io/python-mini-lambda/) expressions can be used instead of callables, they will be transformed to functions automatically. :param auto_and_wrapper: if True (default), this function returns a single callable that is a and_() of all functions. Otherwise a list is returned. :return: """ # handle the case where validation_func is not yet a list or is empty or none if validation_func is None: raise ValueError('mandatory validation_func is None') elif not isinstance(validation_func, list): # so not use list() because we do not want to convert tuples here. validation_func = [validation_func] elif len(validation_func) == 0: raise ValueError('provided validation_func list is empty') # now validation_func is a non-empty list final_list = [] for v in validation_func: # special case of a LambdaExpression: automatically convert to a function # note: we have to do it before anything else (such as .index) otherwise we may get failures v = as_function(v) if isinstance(v, tuple): # convert all the tuples to failure raisers if len(v) == 2: if isinstance(v[1], str): final_list.append(_failure_raiser(v[0], help_msg=v[1])) elif isinstance(v[1], type) and issubclass(v[1], WrappingFailure): final_list.append(_failure_raiser(v[0], failure_type=v[1])) else: raise TypeError('base validation function(s) not compliant with the allowed syntax. Base validation' ' function(s) can be {}. Found [{}].'.format(supported_syntax, str(v))) else: raise TypeError('base validation function(s) not compliant with the allowed syntax. Base validation' ' function(s) can be {}. Found [{}].'.format(supported_syntax, str(v))) elif callable(v): # use the validator directly final_list.append(v) elif isinstance(v, list): # a list is an implicit and_, make it explicit final_list.append(and_(*v)) else: raise TypeError('base validation function(s) not compliant with the allowed syntax. Base validation' ' function(s) can be {}. Found [{}].'.format(supported_syntax, str(v))) # return what is required: if auto_and_wrapper: # a single callable doing the 'and' return and_(*final_list) else: # or the list (typically for use inside or_(), xor_()...) return final_list
[ "def", "_process_validation_function_s", "(", "validation_func", ",", "# type: ValidationFuncs", "auto_and_wrapper", "=", "True", "# type: bool", ")", ":", "# type: (...) -> Union[Callable, List[Callable]]", "# handle the case where validation_func is not yet a list or is empty or none", "if", "validation_func", "is", "None", ":", "raise", "ValueError", "(", "'mandatory validation_func is None'", ")", "elif", "not", "isinstance", "(", "validation_func", ",", "list", ")", ":", "# so not use list() because we do not want to convert tuples here.", "validation_func", "=", "[", "validation_func", "]", "elif", "len", "(", "validation_func", ")", "==", "0", ":", "raise", "ValueError", "(", "'provided validation_func list is empty'", ")", "# now validation_func is a non-empty list", "final_list", "=", "[", "]", "for", "v", "in", "validation_func", ":", "# special case of a LambdaExpression: automatically convert to a function", "# note: we have to do it before anything else (such as .index) otherwise we may get failures", "v", "=", "as_function", "(", "v", ")", "if", "isinstance", "(", "v", ",", "tuple", ")", ":", "# convert all the tuples to failure raisers", "if", "len", "(", "v", ")", "==", "2", ":", "if", "isinstance", "(", "v", "[", "1", "]", ",", "str", ")", ":", "final_list", ".", "append", "(", "_failure_raiser", "(", "v", "[", "0", "]", ",", "help_msg", "=", "v", "[", "1", "]", ")", ")", "elif", "isinstance", "(", "v", "[", "1", "]", ",", "type", ")", "and", "issubclass", "(", "v", "[", "1", "]", ",", "WrappingFailure", ")", ":", "final_list", ".", "append", "(", "_failure_raiser", "(", "v", "[", "0", "]", ",", "failure_type", "=", "v", "[", "1", "]", ")", ")", "else", ":", "raise", "TypeError", "(", "'base validation function(s) not compliant with the allowed syntax. Base validation'", "' function(s) can be {}. Found [{}].'", ".", "format", "(", "supported_syntax", ",", "str", "(", "v", ")", ")", ")", "else", ":", "raise", "TypeError", "(", "'base validation function(s) not compliant with the allowed syntax. Base validation'", "' function(s) can be {}. Found [{}].'", ".", "format", "(", "supported_syntax", ",", "str", "(", "v", ")", ")", ")", "elif", "callable", "(", "v", ")", ":", "# use the validator directly", "final_list", ".", "append", "(", "v", ")", "elif", "isinstance", "(", "v", ",", "list", ")", ":", "# a list is an implicit and_, make it explicit", "final_list", ".", "append", "(", "and_", "(", "*", "v", ")", ")", "else", ":", "raise", "TypeError", "(", "'base validation function(s) not compliant with the allowed syntax. Base validation'", "' function(s) can be {}. Found [{}].'", ".", "format", "(", "supported_syntax", ",", "str", "(", "v", ")", ")", ")", "# return what is required:", "if", "auto_and_wrapper", ":", "# a single callable doing the 'and'", "return", "and_", "(", "*", "final_list", ")", "else", ":", "# or the list (typically for use inside or_(), xor_()...)", "return", "final_list" ]
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> * List[<ValidationFunc>(s)]. The list must not be empty. <ValidationFunc> may either be * a callable or a mini-lambda expression (instance of LambdaExpression - in which case it is automatically 'closed'). * a Tuple[callable or mini-lambda expression ; failure_type]. Where failure type should be a subclass of valid8.Failure. In which case the tuple will be replaced with a _failure_raiser(callable, failure_type) When the contents provided does not match the above, this function raises a ValueError. Otherwise it produces a list of callables, that will typically be turned into a `and_` in the nominal case except if this is called inside `or_` or `xor_`. :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 implicit `and_`. Tuples indicate an implicit `_failure_raiser`. [mini_lambda](https://smarie.github.io/python-mini-lambda/) expressions can be used instead of callables, they will be transformed to functions automatically. :param auto_and_wrapper: if True (default), this function returns a single callable that is a and_() of all functions. Otherwise a list is returned. :return:
[ "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", "." ]
train
https://github.com/smarie/python-valid8/blob/5e15d1de11602933c5114eb9f73277ad91d97800/valid8/composition.py#L43-L125
smarie/python-valid8
valid8/composition.py
and_
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_` is performed if you provide a list of validators to any of the entry points (`validate`, `validation`/`validator`, `@validate_arg`, `@validate_out`, `@validate_field` ...) :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 implicit `and_` (such as the main list). Tuples indicate an implicit `_failure_raiser`. [mini_lambda](https://smarie.github.io/python-mini-lambda/) expressions can be used instead of callables, they will be transformed to functions automatically. :return: """ validation_func = _process_validation_function_s(list(validation_func), auto_and_wrapper=False) if len(validation_func) == 1: return validation_func[0] # simplification for single validator case: no wrapper else: def and_v_(x): for validator in validation_func: try: res = validator(x) except Exception as e: # one validator was unhappy > raise raise AtLeastOneFailed(validation_func, x, cause=e) if not result_is_success(res): # one validator was unhappy > raise raise AtLeastOneFailed(validation_func, x) return True and_v_.__name__ = 'and({})'.format(get_callable_names(validation_func)) return and_v_
python
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_` is performed if you provide a list of validators to any of the entry points (`validate`, `validation`/`validator`, `@validate_arg`, `@validate_out`, `@validate_field` ...) :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 implicit `and_` (such as the main list). Tuples indicate an implicit `_failure_raiser`. [mini_lambda](https://smarie.github.io/python-mini-lambda/) expressions can be used instead of callables, they will be transformed to functions automatically. :return: """ validation_func = _process_validation_function_s(list(validation_func), auto_and_wrapper=False) if len(validation_func) == 1: return validation_func[0] # simplification for single validator case: no wrapper else: def and_v_(x): for validator in validation_func: try: res = validator(x) except Exception as e: # one validator was unhappy > raise raise AtLeastOneFailed(validation_func, x, cause=e) if not result_is_success(res): # one validator was unhappy > raise raise AtLeastOneFailed(validation_func, x) return True and_v_.__name__ = 'and({})'.format(get_callable_names(validation_func)) return and_v_
[ "def", "and_", "(", "*", "validation_func", "# type: ValidationFuncs", ")", ":", "# type: (...) -> Callable", "validation_func", "=", "_process_validation_function_s", "(", "list", "(", "validation_func", ")", ",", "auto_and_wrapper", "=", "False", ")", "if", "len", "(", "validation_func", ")", "==", "1", ":", "return", "validation_func", "[", "0", "]", "# simplification for single validator case: no wrapper", "else", ":", "def", "and_v_", "(", "x", ")", ":", "for", "validator", "in", "validation_func", ":", "try", ":", "res", "=", "validator", "(", "x", ")", "except", "Exception", "as", "e", ":", "# one validator was unhappy > raise", "raise", "AtLeastOneFailed", "(", "validation_func", ",", "x", ",", "cause", "=", "e", ")", "if", "not", "result_is_success", "(", "res", ")", ":", "# one validator was unhappy > raise", "raise", "AtLeastOneFailed", "(", "validation_func", ",", "x", ")", "return", "True", "and_v_", ".", "__name__", "=", "'and({})'", ".", "format", "(", "get_callable_names", "(", "validation_func", ")", ")", "return", "and_v_" ]
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`, `validation`/`validator`, `@validate_arg`, `@validate_out`, `@validate_field` ...) :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 implicit `and_` (such as the main list). Tuples indicate an implicit `_failure_raiser`. [mini_lambda](https://smarie.github.io/python-mini-lambda/) expressions can be used instead of callables, they will be transformed to functions automatically. :return:
[ "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", "." ]
train
https://github.com/smarie/python-valid8/blob/5e15d1de11602933c5114eb9f73277ad91d97800/valid8/composition.py#L229-L266
smarie/python-valid8
valid8/composition.py
not_
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 `DidNotFail` failure. By default, exceptions of types other than `Failure` are not caught and therefore fail the validation (`catch_all=False`). To change this behaviour you can turn the `catch_all` parameter to `True`, in which case all exceptions will be caught instead of just `Failure`s. Note that you may use `not_all(<validation_functions_list>)` as a shortcut for `not_(and_(<validation_functions_list>))` :param validation_func: the base validation function. 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 implicit `and_` (such as the main list). Tuples indicate an implicit `_failure_raiser`. [mini_lambda](https://smarie.github.io/python-mini-lambda/) expressions can be used instead of callables, they will be transformed to functions automatically. :param catch_all: an optional boolean flag. By default, only Failure are silently caught and turned into a 'ok' result. Turning this flag to True will assume that all exceptions should be caught and turned to a 'ok' result :return: """ def not_v_(x): try: res = validation_func(x) if not result_is_success(res): # inverse the result return True except Failure: return True # caught failure: always return True except Exception as e: if not catch_all: raise e else: return True # caught exception in 'catch_all' mode: return True # if we're here that's a failure raise DidNotFail(wrapped_func=validation_func, wrong_value=x, validation_outcome=res) not_v_.__name__ = 'not({})'.format(get_callable_name(validation_func)) return not_v_
python
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 `DidNotFail` failure. By default, exceptions of types other than `Failure` are not caught and therefore fail the validation (`catch_all=False`). To change this behaviour you can turn the `catch_all` parameter to `True`, in which case all exceptions will be caught instead of just `Failure`s. Note that you may use `not_all(<validation_functions_list>)` as a shortcut for `not_(and_(<validation_functions_list>))` :param validation_func: the base validation function. 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 implicit `and_` (such as the main list). Tuples indicate an implicit `_failure_raiser`. [mini_lambda](https://smarie.github.io/python-mini-lambda/) expressions can be used instead of callables, they will be transformed to functions automatically. :param catch_all: an optional boolean flag. By default, only Failure are silently caught and turned into a 'ok' result. Turning this flag to True will assume that all exceptions should be caught and turned to a 'ok' result :return: """ def not_v_(x): try: res = validation_func(x) if not result_is_success(res): # inverse the result return True except Failure: return True # caught failure: always return True except Exception as e: if not catch_all: raise e else: return True # caught exception in 'catch_all' mode: return True # if we're here that's a failure raise DidNotFail(wrapped_func=validation_func, wrong_value=x, validation_outcome=res) not_v_.__name__ = 'not({})'.format(get_callable_name(validation_func)) return not_v_
[ "def", "not_", "(", "validation_func", ",", "# type: ValidationFuncs", "catch_all", "=", "False", "# type: bool", ")", ":", "# type: (...) -> Callable", "def", "not_v_", "(", "x", ")", ":", "try", ":", "res", "=", "validation_func", "(", "x", ")", "if", "not", "result_is_success", "(", "res", ")", ":", "# inverse the result", "return", "True", "except", "Failure", ":", "return", "True", "# caught failure: always return True", "except", "Exception", "as", "e", ":", "if", "not", "catch_all", ":", "raise", "e", "else", ":", "return", "True", "# caught exception in 'catch_all' mode: return True", "# if we're here that's a failure", "raise", "DidNotFail", "(", "wrapped_func", "=", "validation_func", ",", "wrong_value", "=", "x", ",", "validation_outcome", "=", "res", ")", "not_v_", ".", "__name__", "=", "'not({})'", ".", "format", "(", "get_callable_name", "(", "validation_func", ")", ")", "return", "not_v_" ]
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=False`). To change this behaviour you can turn the `catch_all` parameter to `True`, in which case all exceptions will be caught instead of just `Failure`s. Note that you may use `not_all(<validation_functions_list>)` as a shortcut for `not_(and_(<validation_functions_list>))` :param validation_func: the base validation function. 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 implicit `and_` (such as the main list). Tuples indicate an implicit `_failure_raiser`. [mini_lambda](https://smarie.github.io/python-mini-lambda/) expressions can be used instead of callables, they will be transformed to functions automatically. :param catch_all: an optional boolean flag. By default, only Failure are silently caught and turned into a 'ok' result. Turning this flag to True will assume that all exceptions should be caught and turned to a 'ok' result :return:
[ "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", "." ]
train
https://github.com/smarie/python-valid8/blob/5e15d1de11602933c5114eb9f73277ad91d97800/valid8/composition.py#L274-L319
smarie/python-valid8
valid8/composition.py
or_
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, together with details about all validation results. :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 implicit `and_` (such as the main list). Tuples indicate an implicit `_failure_raiser`. [mini_lambda](https://smarie.github.io/python-mini-lambda/) expressions can be used instead of callables, they will be transformed to functions automatically. :return: """ validation_func = _process_validation_function_s(list(validation_func), auto_and_wrapper=False) if len(validation_func) == 1: return validation_func[0] # simplification for single validator case else: def or_v_(x): for validator in validation_func: # noinspection PyBroadException try: res = validator(x) if result_is_success(res): # we can return : one validator was happy return True except Exception: # catch all silently pass # no validator accepted: gather details and raise raise AllValidatorsFailed(validation_func, x) or_v_.__name__ = 'or({})'.format(get_callable_names(validation_func)) return or_v_
python
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, together with details about all validation results. :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 implicit `and_` (such as the main list). Tuples indicate an implicit `_failure_raiser`. [mini_lambda](https://smarie.github.io/python-mini-lambda/) expressions can be used instead of callables, they will be transformed to functions automatically. :return: """ validation_func = _process_validation_function_s(list(validation_func), auto_and_wrapper=False) if len(validation_func) == 1: return validation_func[0] # simplification for single validator case else: def or_v_(x): for validator in validation_func: # noinspection PyBroadException try: res = validator(x) if result_is_success(res): # we can return : one validator was happy return True except Exception: # catch all silently pass # no validator accepted: gather details and raise raise AllValidatorsFailed(validation_func, x) or_v_.__name__ = 'or({})'.format(get_callable_names(validation_func)) return or_v_
[ "def", "or_", "(", "*", "validation_func", "# type: ValidationFuncs", ")", ":", "# type: (...) -> Callable", "validation_func", "=", "_process_validation_function_s", "(", "list", "(", "validation_func", ")", ",", "auto_and_wrapper", "=", "False", ")", "if", "len", "(", "validation_func", ")", "==", "1", ":", "return", "validation_func", "[", "0", "]", "# simplification for single validator case", "else", ":", "def", "or_v_", "(", "x", ")", ":", "for", "validator", "in", "validation_func", ":", "# noinspection PyBroadException", "try", ":", "res", "=", "validator", "(", "x", ")", "if", "result_is_success", "(", "res", ")", ":", "# we can return : one validator was happy", "return", "True", "except", "Exception", ":", "# catch all silently", "pass", "# no validator accepted: gather details and raise", "raise", "AllValidatorsFailed", "(", "validation_func", ",", "x", ")", "or_v_", ".", "__name__", "=", "'or({})'", ".", "format", "(", "get_callable_names", "(", "validation_func", ")", ")", "return", "or_v_" ]
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 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 implicit `and_` (such as the main list). Tuples indicate an implicit `_failure_raiser`. [mini_lambda](https://smarie.github.io/python-mini-lambda/) expressions can be used instead of callables, they will be transformed to functions automatically. :return:
[ "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", "." ]
train
https://github.com/smarie/python-valid8/blob/5e15d1de11602933c5114eb9f73277ad91d97800/valid8/composition.py#L330-L367
smarie/python-valid8
valid8/composition.py
xor_
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 `AllValidatorsFailed` will be raised, together with details about the various validation results. :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 implicit `and_` (such as the main list). Tuples indicate an implicit `_failure_raiser`. [mini_lambda](https://smarie.github.io/python-mini-lambda/) expressions can be used instead of callables, they will be transformed to functions automatically. :return: """ validation_func = _process_validation_function_s(list(validation_func), auto_and_wrapper=False) if len(validation_func) == 1: return validation_func[0] # simplification for single validation function case else: def xor_v_(x): ok_validators = [] for val_func in validation_func: # noinspection PyBroadException try: res = val_func(x) if result_is_success(res): ok_validators.append(val_func) except Exception: pass # return if were happy or not if len(ok_validators) == 1: # one unique validation function happy: success return True elif len(ok_validators) > 1: # several validation_func happy : fail raise XorTooManySuccess(validation_func, x) else: # no validation function happy, fail raise AllValidatorsFailed(validation_func, x) xor_v_.__name__ = 'xor({})'.format(get_callable_names(validation_func)) return xor_v_
python
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 `AllValidatorsFailed` will be raised, together with details about the various validation results. :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 implicit `and_` (such as the main list). Tuples indicate an implicit `_failure_raiser`. [mini_lambda](https://smarie.github.io/python-mini-lambda/) expressions can be used instead of callables, they will be transformed to functions automatically. :return: """ validation_func = _process_validation_function_s(list(validation_func), auto_and_wrapper=False) if len(validation_func) == 1: return validation_func[0] # simplification for single validation function case else: def xor_v_(x): ok_validators = [] for val_func in validation_func: # noinspection PyBroadException try: res = val_func(x) if result_is_success(res): ok_validators.append(val_func) except Exception: pass # return if were happy or not if len(ok_validators) == 1: # one unique validation function happy: success return True elif len(ok_validators) > 1: # several validation_func happy : fail raise XorTooManySuccess(validation_func, x) else: # no validation function happy, fail raise AllValidatorsFailed(validation_func, x) xor_v_.__name__ = 'xor({})'.format(get_callable_names(validation_func)) return xor_v_
[ "def", "xor_", "(", "*", "validation_func", "# type: ValidationFuncs", ")", ":", "# type: (...) -> Callable", "validation_func", "=", "_process_validation_function_s", "(", "list", "(", "validation_func", ")", ",", "auto_and_wrapper", "=", "False", ")", "if", "len", "(", "validation_func", ")", "==", "1", ":", "return", "validation_func", "[", "0", "]", "# simplification for single validation function case", "else", ":", "def", "xor_v_", "(", "x", ")", ":", "ok_validators", "=", "[", "]", "for", "val_func", "in", "validation_func", ":", "# noinspection PyBroadException", "try", ":", "res", "=", "val_func", "(", "x", ")", "if", "result_is_success", "(", "res", ")", ":", "ok_validators", ".", "append", "(", "val_func", ")", "except", "Exception", ":", "pass", "# return if were happy or not", "if", "len", "(", "ok_validators", ")", "==", "1", ":", "# one unique validation function happy: success", "return", "True", "elif", "len", "(", "ok_validators", ")", ">", "1", ":", "# several validation_func happy : fail", "raise", "XorTooManySuccess", "(", "validation_func", ",", "x", ")", "else", ":", "# no validation function happy, fail", "raise", "AllValidatorsFailed", "(", "validation_func", ",", "x", ")", "xor_v_", ".", "__name__", "=", "'xor({})'", ".", "format", "(", "get_callable_names", "(", "validation_func", ")", ")", "return", "xor_v_" ]
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 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 implicit `and_` (such as the main list). Tuples indicate an implicit `_failure_raiser`. [mini_lambda](https://smarie.github.io/python-mini-lambda/) expressions can be used instead of callables, they will be transformed to functions automatically. :return:
[ "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", "." ]
train
https://github.com/smarie/python-valid8/blob/5e15d1de11602933c5114eb9f73277ad91d97800/valid8/composition.py#L378-L424
smarie/python-valid8
valid8/composition.py
not_all
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_str), a tuple(callable, failure_type), or a list of several such elements. Nested lists are supported and indicate an implicit `and_` (such as the main list). Tuples indicate an implicit `_failure_raiser`. [mini_lambda](https://smarie.github.io/python-mini-lambda/) expressions can be used instead of callables, they will be transformed to functions automatically. :param catch_all: an optional boolean flag. By default, only Failure are silently caught and turned into a 'ok' result. Turning this flag to True will assume that all exceptions should be caught and turned to a 'ok' result :return: """ catch_all = pop_kwargs(kwargs, [('catch_all', False)]) # in case this is a list, create a 'and_' around it (otherwise and_ will return the validation function without # wrapping it) main_validator = and_(*validation_func) return not_(main_validator, catch_all=catch_all)
python
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_str), a tuple(callable, failure_type), or a list of several such elements. Nested lists are supported and indicate an implicit `and_` (such as the main list). Tuples indicate an implicit `_failure_raiser`. [mini_lambda](https://smarie.github.io/python-mini-lambda/) expressions can be used instead of callables, they will be transformed to functions automatically. :param catch_all: an optional boolean flag. By default, only Failure are silently caught and turned into a 'ok' result. Turning this flag to True will assume that all exceptions should be caught and turned to a 'ok' result :return: """ catch_all = pop_kwargs(kwargs, [('catch_all', False)]) # in case this is a list, create a 'and_' around it (otherwise and_ will return the validation function without # wrapping it) main_validator = and_(*validation_func) return not_(main_validator, catch_all=catch_all)
[ "def", "not_all", "(", "*", "validation_func", ",", "# type: ValidationFuncs", "*", "*", "kwargs", ")", ":", "# type: (...) -> Callable", "catch_all", "=", "pop_kwargs", "(", "kwargs", ",", "[", "(", "'catch_all'", ",", "False", ")", "]", ")", "# in case this is a list, create a 'and_' around it (otherwise and_ will return the validation function without", "# wrapping it)", "main_validator", "=", "and_", "(", "*", "validation_func", ")", "return", "not_", "(", "main_validator", ",", "catch_all", "=", "catch_all", ")" ]
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 implicit `and_` (such as the main list). Tuples indicate an implicit `_failure_raiser`. [mini_lambda](https://smarie.github.io/python-mini-lambda/) expressions can be used instead of callables, they will be transformed to functions automatically. :param catch_all: an optional boolean flag. By default, only Failure are silently caught and turned into a 'ok' result. Turning this flag to True will assume that all exceptions should be caught and turned to a 'ok' result :return:
[ "An", "alias", "for", "not_", "(", "and_", "(", "validators", "))", "." ]
train
https://github.com/smarie/python-valid8/blob/5e15d1de11602933c5114eb9f73277ad91d97800/valid8/composition.py#L436-L458
smarie/python-valid8
valid8/composition.py
failure_raiser
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` decorators. It transforms the provided `<function>` into a failure raiser, raising a subclass of `Failure` in case of failure (either not returning `True` or raising an exception) :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 implicit `and_` (such as the main list). Tuples indicate an implicit `_failure_raiser`. [mini_lambda](https://smarie.github.io/python-mini-lambda/) expressions can be used instead of callables, they will be transformed to functions automatically. :param failure_type: a subclass of `WrappingFailure` that should be raised in case of failure :param help_msg: a string help message for the raised `WrappingFailure`. Optional (default = WrappingFailure with no help message). :param kw_context_args :return: """ failure_type, help_msg = pop_kwargs(kwargs, [('failure_type', None), ('help_msg', None)], allow_others=True) # the rest of keyword arguments is used as context. kw_context_args = kwargs main_func = _process_validation_function_s(list(validation_func)) return _failure_raiser(main_func, failure_type=failure_type, help_msg=help_msg, **kw_context_args)
python
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` decorators. It transforms the provided `<function>` into a failure raiser, raising a subclass of `Failure` in case of failure (either not returning `True` or raising an exception) :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 implicit `and_` (such as the main list). Tuples indicate an implicit `_failure_raiser`. [mini_lambda](https://smarie.github.io/python-mini-lambda/) expressions can be used instead of callables, they will be transformed to functions automatically. :param failure_type: a subclass of `WrappingFailure` that should be raised in case of failure :param help_msg: a string help message for the raised `WrappingFailure`. Optional (default = WrappingFailure with no help message). :param kw_context_args :return: """ failure_type, help_msg = pop_kwargs(kwargs, [('failure_type', None), ('help_msg', None)], allow_others=True) # the rest of keyword arguments is used as context. kw_context_args = kwargs main_func = _process_validation_function_s(list(validation_func)) return _failure_raiser(main_func, failure_type=failure_type, help_msg=help_msg, **kw_context_args)
[ "def", "failure_raiser", "(", "*", "validation_func", ",", "# type: ValidationFuncs", "*", "*", "kwargs", ")", ":", "# type: (...) -> Callable", "failure_type", ",", "help_msg", "=", "pop_kwargs", "(", "kwargs", ",", "[", "(", "'failure_type'", ",", "None", ")", ",", "(", "'help_msg'", ",", "None", ")", "]", ",", "allow_others", "=", "True", ")", "# the rest of keyword arguments is used as context.", "kw_context_args", "=", "kwargs", "main_func", "=", "_process_validation_function_s", "(", "list", "(", "validation_func", ")", ")", "return", "_failure_raiser", "(", "main_func", ",", "failure_type", "=", "failure_type", ",", "help_msg", "=", "help_msg", ",", "*", "*", "kw_context_args", ")" ]
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 `True` or raising an exception) :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 implicit `and_` (such as the main list). Tuples indicate an implicit `_failure_raiser`. [mini_lambda](https://smarie.github.io/python-mini-lambda/) expressions can be used instead of callables, they will be transformed to functions automatically. :param failure_type: a subclass of `WrappingFailure` that should be raised in case of failure :param help_msg: a string help message for the raised `WrappingFailure`. Optional (default = WrappingFailure with no help message). :param kw_context_args :return:
[ "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", "True", "or", "raising", "an", "exception", ")" ]
train
https://github.com/smarie/python-valid8/blob/5e15d1de11602933c5114eb9f73277ad91d97800/valid8/composition.py#L473-L498
smarie/python-valid8
valid8/composition.py
pop_kwargs
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) then an error will be raised if kwargs still contains something at the end. :return: """ all_arguments = [] for name, default_ in names_with_defaults: try: val = kwargs.pop(name) except KeyError: val = default_ all_arguments.append(val) if not allow_others and len(kwargs) > 0: raise ValueError("Unsupported arguments: %s" % kwargs) if len(names_with_defaults) == 1: return all_arguments[0] else: return all_arguments
python
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) then an error will be raised if kwargs still contains something at the end. :return: """ all_arguments = [] for name, default_ in names_with_defaults: try: val = kwargs.pop(name) except KeyError: val = default_ all_arguments.append(val) if not allow_others and len(kwargs) > 0: raise ValueError("Unsupported arguments: %s" % kwargs) if len(names_with_defaults) == 1: return all_arguments[0] else: return all_arguments
[ "def", "pop_kwargs", "(", "kwargs", ",", "names_with_defaults", ",", "# type: List[Tuple[str, Any]]", "allow_others", "=", "False", ")", ":", "all_arguments", "=", "[", "]", "for", "name", ",", "default_", "in", "names_with_defaults", ":", "try", ":", "val", "=", "kwargs", ".", "pop", "(", "name", ")", "except", "KeyError", ":", "val", "=", "default_", "all_arguments", ".", "append", "(", "val", ")", "if", "not", "allow_others", "and", "len", "(", "kwargs", ")", ">", "0", ":", "raise", "ValueError", "(", "\"Unsupported arguments: %s\"", "%", "kwargs", ")", "if", "len", "(", "names_with_defaults", ")", "==", "1", ":", "return", "all_arguments", "[", "0", "]", "else", ":", "return", "all_arguments" ]
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:
[ "Internal", "utility", "method", "to", "extract", "optional", "arguments", "from", "kwargs", "." ]
train
https://github.com/smarie/python-valid8/blob/5e15d1de11602933c5114eb9f73277ad91d97800/valid8/composition.py#L539-L565
smarie/python-valid8
valid8/composition.py
CompositionFailure.get_details
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.failures.items(): name = get_callable_name(validator) if isinstance(failure, Exception): if isinstance(failure, WrappingFailure) or isinstance(failure, CompositionFailure): need_to_print_value = False failures_for_print[name] = '{exc_type}: {msg}'.format(exc_type=type(failure).__name__, msg=str(failure)) else: failures_for_print[name] = str(failure) if need_to_print_value: value_str = ' for value [{val}]'.format(val=self.wrong_value) else: value_str = '' # OrderedDict does not pretty print... key_values_str = [repr(key) + ': ' + repr(val) for key, val in failures_for_print.items()] failures_for_print_str = '{' + ', '.join(key_values_str) + '}' # Note: we do note cite the value in the message since it is most probably available in inner messages [{val}] msg = '{what}{possibly_value}. Successes: {success} / Failures: {fails}' \ ''.format(what=self.get_what(), possibly_value=value_str, success=self.successes, fails=failures_for_print_str) return msg
python
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.failures.items(): name = get_callable_name(validator) if isinstance(failure, Exception): if isinstance(failure, WrappingFailure) or isinstance(failure, CompositionFailure): need_to_print_value = False failures_for_print[name] = '{exc_type}: {msg}'.format(exc_type=type(failure).__name__, msg=str(failure)) else: failures_for_print[name] = str(failure) if need_to_print_value: value_str = ' for value [{val}]'.format(val=self.wrong_value) else: value_str = '' # OrderedDict does not pretty print... key_values_str = [repr(key) + ': ' + repr(val) for key, val in failures_for_print.items()] failures_for_print_str = '{' + ', '.join(key_values_str) + '}' # Note: we do note cite the value in the message since it is most probably available in inner messages [{val}] msg = '{what}{possibly_value}. Successes: {success} / Failures: {fails}' \ ''.format(what=self.get_what(), possibly_value=value_str, success=self.successes, fails=failures_for_print_str) return msg
[ "def", "get_details", "(", "self", ")", ":", "# transform the dictionary of failures into a printable form", "need_to_print_value", "=", "True", "failures_for_print", "=", "OrderedDict", "(", ")", "for", "validator", ",", "failure", "in", "self", ".", "failures", ".", "items", "(", ")", ":", "name", "=", "get_callable_name", "(", "validator", ")", "if", "isinstance", "(", "failure", ",", "Exception", ")", ":", "if", "isinstance", "(", "failure", ",", "WrappingFailure", ")", "or", "isinstance", "(", "failure", ",", "CompositionFailure", ")", ":", "need_to_print_value", "=", "False", "failures_for_print", "[", "name", "]", "=", "'{exc_type}: {msg}'", ".", "format", "(", "exc_type", "=", "type", "(", "failure", ")", ".", "__name__", ",", "msg", "=", "str", "(", "failure", ")", ")", "else", ":", "failures_for_print", "[", "name", "]", "=", "str", "(", "failure", ")", "if", "need_to_print_value", ":", "value_str", "=", "' for value [{val}]'", ".", "format", "(", "val", "=", "self", ".", "wrong_value", ")", "else", ":", "value_str", "=", "''", "# OrderedDict does not pretty print...", "key_values_str", "=", "[", "repr", "(", "key", ")", "+", "': '", "+", "repr", "(", "val", ")", "for", "key", ",", "val", "in", "failures_for_print", ".", "items", "(", ")", "]", "failures_for_print_str", "=", "'{'", "+", "', '", ".", "join", "(", "key_values_str", ")", "+", "'}'", "# Note: we do note cite the value in the message since it is most probably available in inner messages [{val}]", "msg", "=", "'{what}{possibly_value}. Successes: {success} / Failures: {fails}'", "''", ".", "format", "(", "what", "=", "self", ".", "get_what", "(", ")", ",", "possibly_value", "=", "value_str", ",", "success", "=", "self", ".", "successes", ",", "fails", "=", "failures_for_print_str", ")", "return", "msg" ]
Overrides the base method in order to give details on the various successes and failures
[ "Overrides", "the", "base", "method", "in", "order", "to", "give", "details", "on", "the", "various", "successes", "and", "failures" ]
train
https://github.com/smarie/python-valid8/blob/5e15d1de11602933c5114eb9f73277ad91d97800/valid8/composition.py#L160-L189
smarie/python-valid8
valid8/composition.py
CompositionFailure.play_all_validators
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 in validators: name = get_callable_name(validator) try: res = validator(value) if result_is_success(res): successes.append(name) else: failures[validator] = res except Exception as exc: failures[validator] = exc return successes, failures
python
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 in validators: name = get_callable_name(validator) try: res = validator(value) if result_is_success(res): successes.append(name) else: failures[validator] = res except Exception as exc: failures[validator] = exc return successes, failures
[ "def", "play_all_validators", "(", "self", ",", "validators", ",", "value", ")", ":", "successes", "=", "list", "(", ")", "failures", "=", "OrderedDict", "(", ")", "for", "validator", "in", "validators", ":", "name", "=", "get_callable_name", "(", "validator", ")", "try", ":", "res", "=", "validator", "(", "value", ")", "if", "result_is_success", "(", "res", ")", ":", "successes", ".", "append", "(", "name", ")", "else", ":", "failures", "[", "validator", "]", "=", "res", "except", "Exception", "as", "exc", ":", "failures", "[", "validator", "]", "=", "exc", "return", "successes", ",", "failures" ]
Utility method to play all the provided validators on the provided value and output the :param validators: :param value: :return:
[ "Utility", "method", "to", "play", "all", "the", "provided", "validators", "on", "the", "provided", "value", "and", "output", "the" ]
train
https://github.com/smarie/python-valid8/blob/5e15d1de11602933c5114eb9f73277ad91d97800/valid8/composition.py#L191-L213
redhat-cip/dci-control-server
dci/common/signature.py
gen_secret
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))
python
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))
[ "def", "gen_secret", "(", "length", "=", "64", ")", ":", "charset", "=", "string", ".", "ascii_letters", "+", "string", ".", "digits", "return", "''", ".", "join", "(", "random", ".", "SystemRandom", "(", ")", ".", "choice", "(", "charset", ")", "for", "_", "in", "range", "(", "length", ")", ")" ]
Generates a secret of given length
[ "Generates", "a", "secret", "of", "given", "length" ]
train
https://github.com/redhat-cip/dci-control-server/blob/b416cf935ec93e4fdd5741f61a21cabecf8454d2/dci/common/signature.py#L21-L26
Antidote1911/cryptoshop
cryptoshop/cryptoshop.py
encryptfile
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 is srp. :return: a string with "successfully encrypted" or error. """ try: if algo == "srp": header = b"Cryptoshop srp " + b_version crypto_algo = "Serpent/GCM" if algo == "aes": header = b"Cryptoshop aes " + b_version crypto_algo = "AES-256/GCM" if algo == "twf": header = b"Cryptoshop twf " + b_version crypto_algo = "Twofish/GCM" if algo != "srp" and algo != "aes" and algo != "twf": return "No valid algo. Use 'srp' 'aes' or 'twf'" outname = filename + ".cryptoshop" internal_key = botan.rng().get(internal_key_length) # Passphrase derivation... salt = botan.rng().get(__salt_size__) masterkey = calc_derivation(passphrase=passphrase, salt=salt) # Encrypt internal key... encrypted_key = encry_decry_cascade(data=internal_key, masterkey=masterkey, bool_encry=True, assoc_data=header) with open(filename, 'rb') as filestream: file_size = os.stat(filename).st_size if file_size == 0: raise Exception("Error: You can't encrypt empty file.") with open(str(outname), 'wb') as filestreamout: filestreamout.write(header) filestreamout.write(salt) filestreamout.write(encrypted_key) finished = False # the maximum of the progress bar is the total chunk to process. It's files_size // chunk_size bar = tqdm(range(file_size // __chunk_size__)) while not finished: chunk = filestream.read(__chunk_size__) if len(chunk) == 0 or len(chunk) % __chunk_size__ != 0: finished = True # An encrypted-chunk output is nonce, gcmtag, and cipher-chunk concatenation. encryptedchunk = encry_decry_chunk(chunk=chunk, key=internal_key, bool_encry=True, algo=crypto_algo, assoc_data=header) filestreamout.write(encryptedchunk) bar.update(1) return "successfully encrypted" except IOError: exit("Error: file \"" + filename + "\" was not found.")
python
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 is srp. :return: a string with "successfully encrypted" or error. """ try: if algo == "srp": header = b"Cryptoshop srp " + b_version crypto_algo = "Serpent/GCM" if algo == "aes": header = b"Cryptoshop aes " + b_version crypto_algo = "AES-256/GCM" if algo == "twf": header = b"Cryptoshop twf " + b_version crypto_algo = "Twofish/GCM" if algo != "srp" and algo != "aes" and algo != "twf": return "No valid algo. Use 'srp' 'aes' or 'twf'" outname = filename + ".cryptoshop" internal_key = botan.rng().get(internal_key_length) # Passphrase derivation... salt = botan.rng().get(__salt_size__) masterkey = calc_derivation(passphrase=passphrase, salt=salt) # Encrypt internal key... encrypted_key = encry_decry_cascade(data=internal_key, masterkey=masterkey, bool_encry=True, assoc_data=header) with open(filename, 'rb') as filestream: file_size = os.stat(filename).st_size if file_size == 0: raise Exception("Error: You can't encrypt empty file.") with open(str(outname), 'wb') as filestreamout: filestreamout.write(header) filestreamout.write(salt) filestreamout.write(encrypted_key) finished = False # the maximum of the progress bar is the total chunk to process. It's files_size // chunk_size bar = tqdm(range(file_size // __chunk_size__)) while not finished: chunk = filestream.read(__chunk_size__) if len(chunk) == 0 or len(chunk) % __chunk_size__ != 0: finished = True # An encrypted-chunk output is nonce, gcmtag, and cipher-chunk concatenation. encryptedchunk = encry_decry_chunk(chunk=chunk, key=internal_key, bool_encry=True, algo=crypto_algo, assoc_data=header) filestreamout.write(encryptedchunk) bar.update(1) return "successfully encrypted" except IOError: exit("Error: file \"" + filename + "\" was not found.")
[ "def", "encryptfile", "(", "filename", ",", "passphrase", ",", "algo", "=", "'srp'", ")", ":", "try", ":", "if", "algo", "==", "\"srp\"", ":", "header", "=", "b\"Cryptoshop srp \"", "+", "b_version", "crypto_algo", "=", "\"Serpent/GCM\"", "if", "algo", "==", "\"aes\"", ":", "header", "=", "b\"Cryptoshop aes \"", "+", "b_version", "crypto_algo", "=", "\"AES-256/GCM\"", "if", "algo", "==", "\"twf\"", ":", "header", "=", "b\"Cryptoshop twf \"", "+", "b_version", "crypto_algo", "=", "\"Twofish/GCM\"", "if", "algo", "!=", "\"srp\"", "and", "algo", "!=", "\"aes\"", "and", "algo", "!=", "\"twf\"", ":", "return", "\"No valid algo. Use 'srp' 'aes' or 'twf'\"", "outname", "=", "filename", "+", "\".cryptoshop\"", "internal_key", "=", "botan", ".", "rng", "(", ")", ".", "get", "(", "internal_key_length", ")", "# Passphrase derivation...", "salt", "=", "botan", ".", "rng", "(", ")", ".", "get", "(", "__salt_size__", ")", "masterkey", "=", "calc_derivation", "(", "passphrase", "=", "passphrase", ",", "salt", "=", "salt", ")", "# Encrypt internal key...", "encrypted_key", "=", "encry_decry_cascade", "(", "data", "=", "internal_key", ",", "masterkey", "=", "masterkey", ",", "bool_encry", "=", "True", ",", "assoc_data", "=", "header", ")", "with", "open", "(", "filename", ",", "'rb'", ")", "as", "filestream", ":", "file_size", "=", "os", ".", "stat", "(", "filename", ")", ".", "st_size", "if", "file_size", "==", "0", ":", "raise", "Exception", "(", "\"Error: You can't encrypt empty file.\"", ")", "with", "open", "(", "str", "(", "outname", ")", ",", "'wb'", ")", "as", "filestreamout", ":", "filestreamout", ".", "write", "(", "header", ")", "filestreamout", ".", "write", "(", "salt", ")", "filestreamout", ".", "write", "(", "encrypted_key", ")", "finished", "=", "False", "# the maximum of the progress bar is the total chunk to process. It's files_size // chunk_size", "bar", "=", "tqdm", "(", "range", "(", "file_size", "//", "__chunk_size__", ")", ")", "while", "not", "finished", ":", "chunk", "=", "filestream", ".", "read", "(", "__chunk_size__", ")", "if", "len", "(", "chunk", ")", "==", "0", "or", "len", "(", "chunk", ")", "%", "__chunk_size__", "!=", "0", ":", "finished", "=", "True", "# An encrypted-chunk output is nonce, gcmtag, and cipher-chunk concatenation.", "encryptedchunk", "=", "encry_decry_chunk", "(", "chunk", "=", "chunk", ",", "key", "=", "internal_key", ",", "bool_encry", "=", "True", ",", "algo", "=", "crypto_algo", ",", "assoc_data", "=", "header", ")", "filestreamout", ".", "write", "(", "encryptedchunk", ")", "bar", ".", "update", "(", "1", ")", "return", "\"successfully encrypted\"", "except", "IOError", ":", "exit", "(", "\"Error: file \\\"\"", "+", "filename", "+", "\"\\\" was not found.\"", ")" ]
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 error.
[ "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", "error", "." ]
train
https://github.com/Antidote1911/cryptoshop/blob/0b7ff4a6848f2733f4737606957e8042a4d6ca0b/cryptoshop/cryptoshop.py#L104-L161
Antidote1911/cryptoshop
cryptoshop/cryptoshop.py
decryptfile
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" or error. """ try: outname = os.path.splitext(filename)[0].split("_")[-1] # create a string file name without extension. with open(filename, 'rb') as filestream: file_size = os.stat(filename).st_size if file_size == 0: raise Exception("Error: You can't decrypt empty file.") fileheader = filestream.read(header_length) if fileheader == b"Cryptoshop srp " + b_version: decrypt_algo = "Serpent/GCM" if fileheader == b"Cryptoshop aes " + b_version: decrypt_algo = "AES-256/GCM" if fileheader == b"Cryptoshop twf " + b_version: decrypt_algo = "Twofish/GCM" if fileheader != b"Cryptoshop srp " + b_version and fileheader != b"Cryptoshop aes " + b_version and fileheader != b"Cryptoshop twf " + b_version: raise Exception("Integrity failure: Bad header") salt = filestream.read(__salt_size__) encrypted_key = filestream.read(encrypted_key_length) # Derive the passphrase... masterkey = calc_derivation(passphrase=passphrase, salt=salt) # Decrypt internal key... try: internal_key = encry_decry_cascade(data=encrypted_key, masterkey=masterkey, bool_encry=False, assoc_data=fileheader) except Exception as e: return e with open(str(outname), 'wb') as filestreamout: files_size = os.stat(filename).st_size # the maximum of the progress bar is the total chunk to process. It's files_size // chunk_size bar = tqdm(range(files_size // __chunk_size__)) while True: # Don't forget... an encrypted chunk is nonce, gcmtag, and cipher-chunk concatenation. encryptedchunk = filestream.read(__nonce_length__ + __gcmtag_length__ + __chunk_size__) if len(encryptedchunk) == 0: break # Chunk decryption. try: original = encry_decry_chunk(chunk=encryptedchunk, key=internal_key, algo=decrypt_algo, bool_encry=False, assoc_data=fileheader) except Exception as e: return e else: filestreamout.write(original) bar.update(1) return "successfully decrypted" except IOError: exit("Error: file \"" + filename + "\" was not found.")
python
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" or error. """ try: outname = os.path.splitext(filename)[0].split("_")[-1] # create a string file name without extension. with open(filename, 'rb') as filestream: file_size = os.stat(filename).st_size if file_size == 0: raise Exception("Error: You can't decrypt empty file.") fileheader = filestream.read(header_length) if fileheader == b"Cryptoshop srp " + b_version: decrypt_algo = "Serpent/GCM" if fileheader == b"Cryptoshop aes " + b_version: decrypt_algo = "AES-256/GCM" if fileheader == b"Cryptoshop twf " + b_version: decrypt_algo = "Twofish/GCM" if fileheader != b"Cryptoshop srp " + b_version and fileheader != b"Cryptoshop aes " + b_version and fileheader != b"Cryptoshop twf " + b_version: raise Exception("Integrity failure: Bad header") salt = filestream.read(__salt_size__) encrypted_key = filestream.read(encrypted_key_length) # Derive the passphrase... masterkey = calc_derivation(passphrase=passphrase, salt=salt) # Decrypt internal key... try: internal_key = encry_decry_cascade(data=encrypted_key, masterkey=masterkey, bool_encry=False, assoc_data=fileheader) except Exception as e: return e with open(str(outname), 'wb') as filestreamout: files_size = os.stat(filename).st_size # the maximum of the progress bar is the total chunk to process. It's files_size // chunk_size bar = tqdm(range(files_size // __chunk_size__)) while True: # Don't forget... an encrypted chunk is nonce, gcmtag, and cipher-chunk concatenation. encryptedchunk = filestream.read(__nonce_length__ + __gcmtag_length__ + __chunk_size__) if len(encryptedchunk) == 0: break # Chunk decryption. try: original = encry_decry_chunk(chunk=encryptedchunk, key=internal_key, algo=decrypt_algo, bool_encry=False, assoc_data=fileheader) except Exception as e: return e else: filestreamout.write(original) bar.update(1) return "successfully decrypted" except IOError: exit("Error: file \"" + filename + "\" was not found.")
[ "def", "decryptfile", "(", "filename", ",", "passphrase", ")", ":", "try", ":", "outname", "=", "os", ".", "path", ".", "splitext", "(", "filename", ")", "[", "0", "]", ".", "split", "(", "\"_\"", ")", "[", "-", "1", "]", "# create a string file name without extension.", "with", "open", "(", "filename", ",", "'rb'", ")", "as", "filestream", ":", "file_size", "=", "os", ".", "stat", "(", "filename", ")", ".", "st_size", "if", "file_size", "==", "0", ":", "raise", "Exception", "(", "\"Error: You can't decrypt empty file.\"", ")", "fileheader", "=", "filestream", ".", "read", "(", "header_length", ")", "if", "fileheader", "==", "b\"Cryptoshop srp \"", "+", "b_version", ":", "decrypt_algo", "=", "\"Serpent/GCM\"", "if", "fileheader", "==", "b\"Cryptoshop aes \"", "+", "b_version", ":", "decrypt_algo", "=", "\"AES-256/GCM\"", "if", "fileheader", "==", "b\"Cryptoshop twf \"", "+", "b_version", ":", "decrypt_algo", "=", "\"Twofish/GCM\"", "if", "fileheader", "!=", "b\"Cryptoshop srp \"", "+", "b_version", "and", "fileheader", "!=", "b\"Cryptoshop aes \"", "+", "b_version", "and", "fileheader", "!=", "b\"Cryptoshop twf \"", "+", "b_version", ":", "raise", "Exception", "(", "\"Integrity failure: Bad header\"", ")", "salt", "=", "filestream", ".", "read", "(", "__salt_size__", ")", "encrypted_key", "=", "filestream", ".", "read", "(", "encrypted_key_length", ")", "# Derive the passphrase...", "masterkey", "=", "calc_derivation", "(", "passphrase", "=", "passphrase", ",", "salt", "=", "salt", ")", "# Decrypt internal key...", "try", ":", "internal_key", "=", "encry_decry_cascade", "(", "data", "=", "encrypted_key", ",", "masterkey", "=", "masterkey", ",", "bool_encry", "=", "False", ",", "assoc_data", "=", "fileheader", ")", "except", "Exception", "as", "e", ":", "return", "e", "with", "open", "(", "str", "(", "outname", ")", ",", "'wb'", ")", "as", "filestreamout", ":", "files_size", "=", "os", ".", "stat", "(", "filename", ")", ".", "st_size", "# the maximum of the progress bar is the total chunk to process. It's files_size // chunk_size", "bar", "=", "tqdm", "(", "range", "(", "files_size", "//", "__chunk_size__", ")", ")", "while", "True", ":", "# Don't forget... an encrypted chunk is nonce, gcmtag, and cipher-chunk concatenation.", "encryptedchunk", "=", "filestream", ".", "read", "(", "__nonce_length__", "+", "__gcmtag_length__", "+", "__chunk_size__", ")", "if", "len", "(", "encryptedchunk", ")", "==", "0", ":", "break", "# Chunk decryption.", "try", ":", "original", "=", "encry_decry_chunk", "(", "chunk", "=", "encryptedchunk", ",", "key", "=", "internal_key", ",", "algo", "=", "decrypt_algo", ",", "bool_encry", "=", "False", ",", "assoc_data", "=", "fileheader", ")", "except", "Exception", "as", "e", ":", "return", "e", "else", ":", "filestreamout", ".", "write", "(", "original", ")", "bar", ".", "update", "(", "1", ")", "return", "\"successfully decrypted\"", "except", "IOError", ":", "exit", "(", "\"Error: file \\\"\"", "+", "filename", "+", "\"\\\" was not found.\"", ")" ]
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.
[ "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", "." ]
train
https://github.com/Antidote1911/cryptoshop/blob/0b7ff4a6848f2733f4737606957e8042a4d6ca0b/cryptoshop/cryptoshop.py#L164-L225
danijar/sets
sets/process/tokenize.py
Tokenize._tokenize
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()] yield from cls._split(chunk) tag = match.group(0) yield tag sentence = sentence[(len(chunk) + len(tag)):]
python
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()] yield from cls._split(chunk) tag = match.group(0) yield tag sentence = sentence[(len(chunk) + len(tag)):]
[ "def", "_tokenize", "(", "cls", ",", "sentence", ")", ":", "while", "True", ":", "match", "=", "cls", ".", "_regex_tag", ".", "search", "(", "sentence", ")", "if", "not", "match", ":", "yield", "from", "cls", ".", "_split", "(", "sentence", ")", "return", "chunk", "=", "sentence", "[", ":", "match", ".", "start", "(", ")", "]", "yield", "from", "cls", ".", "_split", "(", "chunk", ")", "tag", "=", "match", ".", "group", "(", "0", ")", "yield", "tag", "sentence", "=", "sentence", "[", "(", "len", "(", "chunk", ")", "+", "len", "(", "tag", ")", ")", ":", "]" ]
Split a sentence while preserving tags.
[ "Split", "a", "sentence", "while", "preserving", "tags", "." ]
train
https://github.com/danijar/sets/blob/2542c28f43d0af18932cb5b82f54ffb6ae557d12/sets/process/tokenize.py#L22-L35
mediawiki-utilities/python-mwxml
mwxml/map/map.py
map
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()` function that takes two arguments -- a :class:`mwxml.Dump` and the path the dump was loaded from. Anything that this function ``yield``s will be `yielded` in turn from the :func:`mwxml.map` function. :Parameters: paths : `iterable` ( `str` | `file` ) a list of paths to dump files to process process : `func` A function that takes a :class:`~mwxml.iteration.dump.Dump` and the path the dump was loaded from and yields threads : int the number of individual processing threads to spool up :Example: >>> import mwxml >>> files = ["examples/dump.xml", "examples/dump2.xml"] >>> >>> def page_info(dump, path): ... for page in dump: ... yield page.id, page.namespace, page.title ... >>> for id, namespace, title in mwxml.map(page_info, files): ... print(id, namespace, title) ... """ paths = [mwtypes.files.normalize_path(path) for path in paths] def process_path(path): dump = Dump.from_file(mwtypes.files.reader(path)) yield from process(dump, path) yield from para.map(process_path, paths, mappers=threads)
python
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()` function that takes two arguments -- a :class:`mwxml.Dump` and the path the dump was loaded from. Anything that this function ``yield``s will be `yielded` in turn from the :func:`mwxml.map` function. :Parameters: paths : `iterable` ( `str` | `file` ) a list of paths to dump files to process process : `func` A function that takes a :class:`~mwxml.iteration.dump.Dump` and the path the dump was loaded from and yields threads : int the number of individual processing threads to spool up :Example: >>> import mwxml >>> files = ["examples/dump.xml", "examples/dump2.xml"] >>> >>> def page_info(dump, path): ... for page in dump: ... yield page.id, page.namespace, page.title ... >>> for id, namespace, title in mwxml.map(page_info, files): ... print(id, namespace, title) ... """ paths = [mwtypes.files.normalize_path(path) for path in paths] def process_path(path): dump = Dump.from_file(mwtypes.files.reader(path)) yield from process(dump, path) yield from para.map(process_path, paths, mappers=threads)
[ "def", "map", "(", "process", ",", "paths", ",", "threads", "=", "None", ")", ":", "paths", "=", "[", "mwtypes", ".", "files", ".", "normalize_path", "(", "path", ")", "for", "path", "in", "paths", "]", "def", "process_path", "(", "path", ")", ":", "dump", "=", "Dump", ".", "from_file", "(", "mwtypes", ".", "files", ".", "reader", "(", "path", ")", ")", "yield", "from", "process", "(", "dump", ",", "path", ")", "yield", "from", "para", ".", "map", "(", "process_path", ",", "paths", ",", "mappers", "=", "threads", ")" ]
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.Dump` and the path the dump was loaded from. Anything that this function ``yield``s will be `yielded` in turn from the :func:`mwxml.map` function. :Parameters: paths : `iterable` ( `str` | `file` ) a list of paths to dump files to process process : `func` A function that takes a :class:`~mwxml.iteration.dump.Dump` and the path the dump was loaded from and yields threads : int the number of individual processing threads to spool up :Example: >>> import mwxml >>> files = ["examples/dump.xml", "examples/dump2.xml"] >>> >>> def page_info(dump, path): ... for page in dump: ... yield page.id, page.namespace, page.title ... >>> for id, namespace, title in mwxml.map(page_info, files): ... print(id, namespace, title) ...
[ "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", ".", "Dump", "and", "the", "path", "the", "dump", "was", "loaded", "from", ".", "Anything", "that", "this", "function", "yield", "s", "will", "be", "yielded", "in", "turn", "from", "the", ":", "func", ":", "mwxml", ".", "map", "function", "." ]
train
https://github.com/mediawiki-utilities/python-mwxml/blob/6a8c18be99cd0bcee9c496e607f08bf4dfe5b510/mwxml/map/map.py#L11-L49
redhat-cip/dci-control-server
dci/trackers/__init__.py
Tracker.dump
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': self.component, 'created_at': self.created_at, 'updated_at': self.updated_at, 'closed_at': self.closed_at, 'status_code': self.status_code }
python
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': self.component, 'created_at': self.created_at, 'updated_at': self.updated_at, 'closed_at': self.closed_at, 'status_code': self.status_code }
[ "def", "dump", "(", "self", ")", ":", "return", "{", "'title'", ":", "self", ".", "title", ",", "'issue_id'", ":", "self", ".", "issue_id", ",", "'reporter'", ":", "self", ".", "reporter", ",", "'assignee'", ":", "self", ".", "assignee", ",", "'status'", ":", "self", ".", "status", ",", "'product'", ":", "self", ".", "product", ",", "'component'", ":", "self", ".", "component", ",", "'created_at'", ":", "self", ".", "created_at", ",", "'updated_at'", ":", "self", ".", "updated_at", ",", "'closed_at'", ":", "self", ".", "closed_at", ",", "'status_code'", ":", "self", ".", "status_code", "}" ]
Return the object itself.
[ "Return", "the", "object", "itself", "." ]
train
https://github.com/redhat-cip/dci-control-server/blob/b416cf935ec93e4fdd5741f61a21cabecf8454d2/dci/trackers/__init__.py#L39-L54
smarie/python-valid8
valid8/utils_decoration.py
apply_on_each_func_args_sig
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 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: :param cur_args: :param cur_kwargs: :param sig: :param func_to_apply: :param func_to_apply_params_dict: :return: """ # match the received arguments with the signature to know who is who bound_values = sig.bind(*cur_args, **cur_kwargs) # add the default values in here to get a full list apply_defaults(bound_values) for att_name, att_value in bound_values.arguments.items(): if att_name in func_to_apply_params_dict.keys(): # value = a normal value, or cur_kwargs as a whole func_to_apply(att_value, func_to_apply_params_dict[att_name], func, att_name)
python
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 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: :param cur_args: :param cur_kwargs: :param sig: :param func_to_apply: :param func_to_apply_params_dict: :return: """ # match the received arguments with the signature to know who is who bound_values = sig.bind(*cur_args, **cur_kwargs) # add the default values in here to get a full list apply_defaults(bound_values) for att_name, att_value in bound_values.arguments.items(): if att_name in func_to_apply_params_dict.keys(): # value = a normal value, or cur_kwargs as a whole func_to_apply(att_value, func_to_apply_params_dict[att_name], func, att_name)
[ "def", "apply_on_each_func_args_sig", "(", "func", ",", "cur_args", ",", "cur_kwargs", ",", "sig", ",", "# type: Signature", "func_to_apply", ",", "func_to_apply_params_dict", ")", ":", "# match the received arguments with the signature to know who is who", "bound_values", "=", "sig", ".", "bind", "(", "*", "cur_args", ",", "*", "*", "cur_kwargs", ")", "# add the default values in here to get a full list", "apply_defaults", "(", "bound_values", ")", "for", "att_name", ",", "att_value", "in", "bound_values", ".", "arguments", ".", "items", "(", ")", ":", "if", "att_name", "in", "func_to_apply_params_dict", ".", "keys", "(", ")", ":", "# value = a normal value, or cur_kwargs as a whole", "func_to_apply", "(", "att_value", ",", "func_to_apply_params_dict", "[", "att_name", "]", ",", "func", ",", "att_name", ")" ]
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: :param cur_args: :param cur_kwargs: :param sig: :param func_to_apply: :param func_to_apply_params_dict: :return:
[ "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", ":" ]
train
https://github.com/smarie/python-valid8/blob/5e15d1de11602933c5114eb9f73277ad91d97800/valid8/utils_decoration.py#L15-L45
redhat-cip/dci-control-server
dci/identity.py
Identity.is_product_owner
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
python
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
[ "def", "is_product_owner", "(", "self", ",", "team_id", ")", ":", "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.
[ "Ensure", "the", "user", "is", "a", "PRODUCT_OWNER", "." ]
train
https://github.com/redhat-cip/dci-control-server/blob/b416cf935ec93e4fdd5741f61a21cabecf8454d2/dci/identity.py#L71-L77
redhat-cip/dci-control-server
dci/identity.py
Identity.is_in_team
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
python
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
[ "def", "is_in_team", "(", "self", ",", "team_id", ")", ":", "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
[ "Test", "if", "user", "is", "in", "team" ]
train
https://github.com/redhat-cip/dci-control-server/blob/b416cf935ec93e4fdd5741f61a21cabecf8454d2/dci/identity.py#L96-L102
redhat-cip/dci-control-server
dci/identity.py
Identity.is_remoteci
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'] == 'REMOTECI'
python
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'] == 'REMOTECI'
[ "def", "is_remoteci", "(", "self", ",", "team_id", "=", "None", ")", ":", "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'", "]", "==", "'REMOTECI'" ]
Ensure ther resource has the role REMOTECI.
[ "Ensure", "ther", "resource", "has", "the", "role", "REMOTECI", "." ]
train
https://github.com/redhat-cip/dci-control-server/blob/b416cf935ec93e4fdd5741f61a21cabecf8454d2/dci/identity.py#L112-L119
redhat-cip/dci-control-server
dci/identity.py
Identity.is_feeder
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'
python
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'
[ "def", "is_feeder", "(", "self", ",", "team_id", "=", "None", ")", ":", "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.
[ "Ensure", "ther", "resource", "has", "the", "role", "FEEDER", "." ]
train
https://github.com/redhat-cip/dci-control-server/blob/b416cf935ec93e4fdd5741f61a21cabecf8454d2/dci/identity.py#L121-L128
jmurty/xml4h
xml4h/nodes.py
Node.document
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)
python
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)
[ "def", "document", "(", "self", ")", ":", "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.
[ ":", "return", ":", "the", ":", "class", ":", "Document", "node", "that", "contains", "this", "node", "or", "self", "if", "this", "node", "is", "the", "document", "." ]
train
https://github.com/jmurty/xml4h/blob/adbb45e27a01a869a505aee7bc16bad2f517b511/xml4h/nodes.py#L111-L118
jmurty/xml4h
xml4h/nodes.py
Node.root
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, self.adapter.impl_document, self.adapter)
python
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, self.adapter.impl_document, self.adapter)
[ "def", "root", "(", "self", ")", ":", "if", "self", ".", "is_root", ":", "return", "self", "return", "self", ".", "adapter", ".", "wrap_node", "(", "self", ".", "adapter", ".", "impl_root_element", ",", "self", ".", "adapter", ".", "impl_document", ",", "self", ".", "adapter", ")" ]
:return: the root :class:`Element` node of the document that contains this node, or ``self`` if this node is the root element.
[ ":", "return", ":", "the", "root", ":", "class", ":", "Element", "node", "of", "the", "document", "that", "contains", "this", "node", "or", "self", "if", "this", "node", "is", "the", "root", "element", "." ]
train
https://github.com/jmurty/xml4h/blob/adbb45e27a01a869a505aee7bc16bad2f517b511/xml4h/nodes.py#L121-L130
jmurty/xml4h
xml4h/nodes.py
Node._convert_nodelist
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] return NodeList(nodelist)
python
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] return NodeList(nodelist)
[ "def", "_convert_nodelist", "(", "self", ",", "impl_nodelist", ")", ":", "nodelist", "=", "[", "self", ".", "adapter", ".", "wrap_node", "(", "n", ",", "self", ".", "adapter", ".", "impl_document", ",", "self", ".", "adapter", ")", "for", "n", "in", "impl_nodelist", "]", "return", "NodeList", "(", "nodelist", ")" ]
Convert a list of underlying implementation nodes into a list of *xml4h* wrapper nodes.
[ "Convert", "a", "list", "of", "underlying", "implementation", "nodes", "into", "a", "list", "of", "*", "xml4h", "*", "wrapper", "nodes", "." ]
train
https://github.com/jmurty/xml4h/blob/adbb45e27a01a869a505aee7bc16bad2f517b511/xml4h/nodes.py#L235-L243
jmurty/xml4h
xml4h/nodes.py
Node.parent
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)
python
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)
[ "def", "parent", "(", "self", ")", ":", "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.
[ ":", "return", ":", "the", "parent", "of", "this", "node", "or", "*", "None", "*", "of", "the", "node", "has", "no", "parent", "." ]
train
https://github.com/jmurty/xml4h/blob/adbb45e27a01a869a505aee7bc16bad2f517b511/xml4h/nodes.py#L246-L252
jmurty/xml4h
xml4h/nodes.py
Node.children
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)
python
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)
[ "def", "children", "(", "self", ")", ":", "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.
[ ":", "return", ":", "a", ":", "class", ":", "NodeList", "of", "this", "node", "s", "child", "nodes", "." ]
train
https://github.com/jmurty/xml4h/blob/adbb45e27a01a869a505aee7bc16bad2f517b511/xml4h/nodes.py#L268-L273
jmurty/xml4h
xml4h/nodes.py
Node.child
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`. """ return self.children(name=name, local_name=local_name, ns_uri=ns_uri, node_type=node_type, filter_fn=filter_fn, first_only=True)
python
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`. """ return self.children(name=name, local_name=local_name, ns_uri=ns_uri, node_type=node_type, filter_fn=filter_fn, first_only=True)
[ "def", "child", "(", "self", ",", "local_name", "=", "None", ",", "name", "=", "None", ",", "ns_uri", "=", "None", ",", "node_type", "=", "None", ",", "filter_fn", "=", "None", ")", ":", "return", "self", ".", "children", "(", "name", "=", "name", ",", "local_name", "=", "local_name", ",", "ns_uri", "=", "ns_uri", ",", "node_type", "=", "node_type", ",", "filter_fn", "=", "filter_fn", ",", "first_only", "=", "True", ")" ]
:return: the first child node matching the given constraints, or \ *None* if there are no matching child nodes. Delegates to :meth:`NodeList.filter`.
[ ":", "return", ":", "the", "first", "child", "node", "matching", "the", "given", "constraints", "or", "\\", "*", "None", "*", "if", "there", "are", "no", "matching", "child", "nodes", "." ]
train
https://github.com/jmurty/xml4h/blob/adbb45e27a01a869a505aee7bc16bad2f517b511/xml4h/nodes.py#L275-L284
jmurty/xml4h
xml4h/nodes.py
Node.siblings
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])
python
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])
[ "def", "siblings", "(", "self", ")", ":", "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
[ ":", "return", ":", "a", "list", "of", "this", "node", "s", "sibling", "nodes", ".", ":", "rtype", ":", "NodeList" ]
train
https://github.com/jmurty/xml4h/blob/adbb45e27a01a869a505aee7bc16bad2f517b511/xml4h/nodes.py#L295-L302
jmurty/xml4h
xml4h/nodes.py
Node.siblings_before
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.impl_node: break before_nodelist.append(n) return self._convert_nodelist(before_nodelist)
python
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.impl_node: break before_nodelist.append(n) return self._convert_nodelist(before_nodelist)
[ "def", "siblings_before", "(", "self", ")", ":", "impl_nodelist", "=", "self", ".", "adapter", ".", "get_node_children", "(", "self", ".", "parent", ".", "impl_node", ")", "before_nodelist", "=", "[", "]", "for", "n", "in", "impl_nodelist", ":", "if", "n", "==", "self", ".", "impl_node", ":", "break", "before_nodelist", ".", "append", "(", "n", ")", "return", "self", ".", "_convert_nodelist", "(", "before_nodelist", ")" ]
:return: a list of this node's siblings that occur *before* this node in the DOM.
[ ":", "return", ":", "a", "list", "of", "this", "node", "s", "siblings", "that", "occur", "*", "before", "*", "this", "node", "in", "the", "DOM", "." ]
train
https://github.com/jmurty/xml4h/blob/adbb45e27a01a869a505aee7bc16bad2f517b511/xml4h/nodes.py#L305-L316
jmurty/xml4h
xml4h/nodes.py
Node.siblings_after
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: if is_after_myself: after_nodelist.append(n) elif n == self.impl_node: is_after_myself = True return self._convert_nodelist(after_nodelist)
python
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: if is_after_myself: after_nodelist.append(n) elif n == self.impl_node: is_after_myself = True return self._convert_nodelist(after_nodelist)
[ "def", "siblings_after", "(", "self", ")", ":", "impl_nodelist", "=", "self", ".", "adapter", ".", "get_node_children", "(", "self", ".", "parent", ".", "impl_node", ")", "after_nodelist", "=", "[", "]", "is_after_myself", "=", "False", "for", "n", "in", "impl_nodelist", ":", "if", "is_after_myself", ":", "after_nodelist", ".", "append", "(", "n", ")", "elif", "n", "==", "self", ".", "impl_node", ":", "is_after_myself", "=", "True", "return", "self", ".", "_convert_nodelist", "(", "after_nodelist", ")" ]
:return: a list of this node's siblings that occur *after* this node in the DOM.
[ ":", "return", ":", "a", "list", "of", "this", "node", "s", "siblings", "that", "occur", "*", "after", "*", "this", "node", "in", "the", "DOM", "." ]
train
https://github.com/jmurty/xml4h/blob/adbb45e27a01a869a505aee7bc16bad2f517b511/xml4h/nodes.py#L319-L332
jmurty/xml4h
xml4h/nodes.py
Node.delete
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. """ removed_child = self.adapter.remove_node_child( self.adapter.get_node_parent(self.impl_node), self.impl_node, destroy_node=destroy) if removed_child is not None: return self.adapter.wrap_node(removed_child, None, self.adapter) else: return None
python
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. """ removed_child = self.adapter.remove_node_child( self.adapter.get_node_parent(self.impl_node), self.impl_node, destroy_node=destroy) if removed_child is not None: return self.adapter.wrap_node(removed_child, None, self.adapter) else: return None
[ "def", "delete", "(", "self", ",", "destroy", "=", "True", ")", ":", "removed_child", "=", "self", ".", "adapter", ".", "remove_node_child", "(", "self", ".", "adapter", ".", "get_node_parent", "(", "self", ".", "impl_node", ")", ",", "self", ".", "impl_node", ",", "destroy_node", "=", "destroy", ")", "if", "removed_child", "is", "not", "None", ":", "return", "self", ".", "adapter", ".", "wrap_node", "(", "removed_child", ",", "None", ",", "self", ".", "adapter", ")", "else", ":", "return", "None" ]
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", "." ]
train
https://github.com/jmurty/xml4h/blob/adbb45e27a01a869a505aee7bc16bad2f517b511/xml4h/nodes.py#L344-L359
jmurty/xml4h
xml4h/nodes.py
Node.clone_node
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 library implementation and adapter, or a "raw" node from that implementation. :param node: the node in another document to clone. :type node: xml4h or implementation node """ if isinstance(node, xml4h.nodes.Node): child_impl_node = node.impl_node else: child_impl_node = node # Assume it's a valid impl node self.adapter.import_node(self.impl_node, child_impl_node, clone=True)
python
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 library implementation and adapter, or a "raw" node from that implementation. :param node: the node in another document to clone. :type node: xml4h or implementation node """ if isinstance(node, xml4h.nodes.Node): child_impl_node = node.impl_node else: child_impl_node = node # Assume it's a valid impl node self.adapter.import_node(self.impl_node, child_impl_node, clone=True)
[ "def", "clone_node", "(", "self", ",", "node", ")", ":", "if", "isinstance", "(", "node", ",", "xml4h", ".", "nodes", ".", "Node", ")", ":", "child_impl_node", "=", "node", ".", "impl_node", "else", ":", "child_impl_node", "=", "node", "# Assume it's a valid impl node", "self", ".", "adapter", ".", "import_node", "(", "self", ".", "impl_node", ",", "child_impl_node", ",", "clone", "=", "True", ")" ]
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 "raw" node from that implementation. :param node: the node in another document to clone. :type node: xml4h or implementation 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", "library", "implementation", "and", "adapter", "or", "a", "raw", "node", "from", "that", "implementation", "." ]
train
https://github.com/jmurty/xml4h/blob/adbb45e27a01a869a505aee7bc16bad2f517b511/xml4h/nodes.py#L361-L376
jmurty/xml4h
xml4h/nodes.py
Node.transplant_node
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" node from that implementation. :param node: the node in another document to transplant. :type node: xml4h or implementation node """ if isinstance(node, xml4h.nodes.Node): child_impl_node = node.impl_node original_parent_impl_node = node.parent.impl_node else: child_impl_node = node # Assume it's a valid impl node original_parent_impl_node = self.adapter.get_node_parent(node) self.adapter.import_node(self.impl_node, child_impl_node, original_parent_impl_node, clone=False)
python
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" node from that implementation. :param node: the node in another document to transplant. :type node: xml4h or implementation node """ if isinstance(node, xml4h.nodes.Node): child_impl_node = node.impl_node original_parent_impl_node = node.parent.impl_node else: child_impl_node = node # Assume it's a valid impl node original_parent_impl_node = self.adapter.get_node_parent(node) self.adapter.import_node(self.impl_node, child_impl_node, original_parent_impl_node, clone=False)
[ "def", "transplant_node", "(", "self", ",", "node", ")", ":", "if", "isinstance", "(", "node", ",", "xml4h", ".", "nodes", ".", "Node", ")", ":", "child_impl_node", "=", "node", ".", "impl_node", "original_parent_impl_node", "=", "node", ".", "parent", ".", "impl_node", "else", ":", "child_impl_node", "=", "node", "# Assume it's a valid impl node", "original_parent_impl_node", "=", "self", ".", "adapter", ".", "get_node_parent", "(", "node", ")", "self", ".", "adapter", ".", "import_node", "(", "self", ".", "impl_node", ",", "child_impl_node", ",", "original_parent_impl_node", ",", "clone", "=", "False", ")" ]
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: the node in another document to transplant. :type node: xml4h or implementation 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", "node", "from", "that", "implementation", "." ]
train
https://github.com/jmurty/xml4h/blob/adbb45e27a01a869a505aee7bc16bad2f517b511/xml4h/nodes.py#L378-L395
jmurty/xml4h
xml4h/nodes.py
Node.find
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. :type name: string or None :param ns_uri: limit results to elements within this namespace URI. If *None* all elements are matched, regardless of namespace. :type ns_uri: string or None :param bool first_only: if *True* only return the first result node or *None* if there is no matching node. :returns: a list of :class:`Element` nodes matching any given constraints, or a single node if ``first_only=True``. """ if name is None: name = '*' # Match all element names if ns_uri is None: ns_uri = '*' # Match all namespaces impl_nodelist = self.adapter.find_node_elements( self.impl_node, name=name, ns_uri=ns_uri) if first_only: if impl_nodelist: return self.adapter.wrap_node( impl_nodelist[0], self.adapter.impl_document, self.adapter) else: return None return self._convert_nodelist(impl_nodelist)
python
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. :type name: string or None :param ns_uri: limit results to elements within this namespace URI. If *None* all elements are matched, regardless of namespace. :type ns_uri: string or None :param bool first_only: if *True* only return the first result node or *None* if there is no matching node. :returns: a list of :class:`Element` nodes matching any given constraints, or a single node if ``first_only=True``. """ if name is None: name = '*' # Match all element names if ns_uri is None: ns_uri = '*' # Match all namespaces impl_nodelist = self.adapter.find_node_elements( self.impl_node, name=name, ns_uri=ns_uri) if first_only: if impl_nodelist: return self.adapter.wrap_node( impl_nodelist[0], self.adapter.impl_document, self.adapter) else: return None return self._convert_nodelist(impl_nodelist)
[ "def", "find", "(", "self", ",", "name", "=", "None", ",", "ns_uri", "=", "None", ",", "first_only", "=", "False", ")", ":", "if", "name", "is", "None", ":", "name", "=", "'*'", "# Match all element names", "if", "ns_uri", "is", "None", ":", "ns_uri", "=", "'*'", "# Match all namespaces", "impl_nodelist", "=", "self", ".", "adapter", ".", "find_node_elements", "(", "self", ".", "impl_node", ",", "name", "=", "name", ",", "ns_uri", "=", "ns_uri", ")", "if", "first_only", ":", "if", "impl_nodelist", ":", "return", "self", ".", "adapter", ".", "wrap_node", "(", "impl_nodelist", "[", "0", "]", ",", "self", ".", "adapter", ".", "impl_document", ",", "self", ".", "adapter", ")", "else", ":", "return", "None", "return", "self", ".", "_convert_nodelist", "(", "impl_nodelist", ")" ]
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 within this namespace URI. If *None* all elements are matched, regardless of namespace. :type ns_uri: string or None :param bool first_only: if *True* only return the first result node or *None* if there is no matching node. :returns: a list of :class:`Element` nodes matching any given constraints, or a single node if ``first_only=True``.
[ "Find", ":", "class", ":", "Element", "node", "descendants", "of", "this", "node", "with", "optional", "constraints", "to", "limit", "the", "results", "." ]
train
https://github.com/jmurty/xml4h/blob/adbb45e27a01a869a505aee7bc16bad2f517b511/xml4h/nodes.py#L397-L426
jmurty/xml4h
xml4h/nodes.py
Node.find_first
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.find(name=name, ns_uri=ns_uri, first_only=True)
python
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.find(name=name, ns_uri=ns_uri, first_only=True)
[ "def", "find_first", "(", "self", ",", "name", "=", "None", ",", "ns_uri", "=", "None", ")", ":", "return", "self", ".", "find", "(", "name", "=", "name", ",", "ns_uri", "=", "ns_uri", ",", "first_only", "=", "True", ")" ]
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``.
[ "Find", "the", "first", ":", "class", ":", "Element", "node", "descendant", "of", "this", "node", "that", "matches", "any", "optional", "constraints", "or", "None", "if", "there", "are", "no", "matching", "elements", "." ]
train
https://github.com/jmurty/xml4h/blob/adbb45e27a01a869a505aee7bc16bad2f517b511/xml4h/nodes.py#L428-L436
jmurty/xml4h
xml4h/nodes.py
Node.find_doc
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 self.document.find(name=name, ns_uri=ns_uri, first_only=first_only)
python
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 self.document.find(name=name, ns_uri=ns_uri, first_only=first_only)
[ "def", "find_doc", "(", "self", ",", "name", "=", "None", ",", "ns_uri", "=", "None", ",", "first_only", "=", "False", ")", ":", "return", "self", ".", "document", ".", "find", "(", "name", "=", "name", ",", "ns_uri", "=", "ns_uri", ",", "first_only", "=", "first_only", ")" ]
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.
[ "Find", ":", "class", ":", "Element", "node", "descendants", "of", "the", "document", "containing", "this", "node", "with", "optional", "constraints", "to", "limit", "the", "results", "." ]
train
https://github.com/jmurty/xml4h/blob/adbb45e27a01a869a505aee7bc16bad2f517b511/xml4h/nodes.py#L438-L446
jmurty/xml4h
xml4h/nodes.py
Node.write
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 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 string encoding: the character encoding for serialized text. :param indent: indentation prefix to apply to descendent nodes for pretty-printing. The value can take many forms: - *int*: the number of spaces to indent. 0 means no indent. - *string*: a literal prefix for indented nodes, such as ``\\t``. - *bool*: no indent if *False*, four spaces indent if *True*. - *None*: no indent :type indent: string, int, bool, or None :param newline: the string value used to separate lines of output. The value can take a number of forms: - *string*: the literal newline value, such as ``\\n`` or ``\\r``. An empty string means no newline. - *bool*: no newline if *False*, ``\\n`` newline if *True*. - *None*: no newline. :type newline: string, bool, or None :param boolean omit_declaration: if *True* the XML declaration header is omitted, otherwise it is included. Note that the declaration is only output when serializing an :class:`xml4h.nodes.Document` node. :param int node_depth: the indentation level to start at, such as 2 to indent output as if the given *node* has two ancestors. This parameter will only be useful if you need to output XML text fragments that can be assembled into a document. This parameter has no effect unless indentation is applied. :param string quote_char: the character that delimits quoted content. You should never need to mess with this. Delegates to :func:`xml4h.writer.write_node` applied to this node. """ xml4h.write_node(self, writer=writer, encoding=encoding, indent=indent, newline=newline, omit_declaration=omit_declaration, node_depth=node_depth, quote_char=quote_char)
python
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 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 string encoding: the character encoding for serialized text. :param indent: indentation prefix to apply to descendent nodes for pretty-printing. The value can take many forms: - *int*: the number of spaces to indent. 0 means no indent. - *string*: a literal prefix for indented nodes, such as ``\\t``. - *bool*: no indent if *False*, four spaces indent if *True*. - *None*: no indent :type indent: string, int, bool, or None :param newline: the string value used to separate lines of output. The value can take a number of forms: - *string*: the literal newline value, such as ``\\n`` or ``\\r``. An empty string means no newline. - *bool*: no newline if *False*, ``\\n`` newline if *True*. - *None*: no newline. :type newline: string, bool, or None :param boolean omit_declaration: if *True* the XML declaration header is omitted, otherwise it is included. Note that the declaration is only output when serializing an :class:`xml4h.nodes.Document` node. :param int node_depth: the indentation level to start at, such as 2 to indent output as if the given *node* has two ancestors. This parameter will only be useful if you need to output XML text fragments that can be assembled into a document. This parameter has no effect unless indentation is applied. :param string quote_char: the character that delimits quoted content. You should never need to mess with this. Delegates to :func:`xml4h.writer.write_node` applied to this node. """ xml4h.write_node(self, writer=writer, encoding=encoding, indent=indent, newline=newline, omit_declaration=omit_declaration, node_depth=node_depth, quote_char=quote_char)
[ "def", "write", "(", "self", ",", "writer", "=", "None", ",", "encoding", "=", "'utf-8'", ",", "indent", "=", "0", ",", "newline", "=", "''", ",", "omit_declaration", "=", "False", ",", "node_depth", "=", "0", ",", "quote_char", "=", "'\"'", ")", ":", "xml4h", ".", "write_node", "(", "self", ",", "writer", "=", "writer", ",", "encoding", "=", "encoding", ",", "indent", "=", "indent", ",", "newline", "=", "newline", ",", "omit_declaration", "=", "omit_declaration", ",", "node_depth", "=", "node_depth", ",", "quote_char", "=", "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 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 string encoding: the character encoding for serialized text. :param indent: indentation prefix to apply to descendent nodes for pretty-printing. The value can take many forms: - *int*: the number of spaces to indent. 0 means no indent. - *string*: a literal prefix for indented nodes, such as ``\\t``. - *bool*: no indent if *False*, four spaces indent if *True*. - *None*: no indent :type indent: string, int, bool, or None :param newline: the string value used to separate lines of output. The value can take a number of forms: - *string*: the literal newline value, such as ``\\n`` or ``\\r``. An empty string means no newline. - *bool*: no newline if *False*, ``\\n`` newline if *True*. - *None*: no newline. :type newline: string, bool, or None :param boolean omit_declaration: if *True* the XML declaration header is omitted, otherwise it is included. Note that the declaration is only output when serializing an :class:`xml4h.nodes.Document` node. :param int node_depth: the indentation level to start at, such as 2 to indent output as if the given *node* has two ancestors. This parameter will only be useful if you need to output XML text fragments that can be assembled into a document. This parameter has no effect unless indentation is applied. :param string quote_char: the character that delimits quoted content. You should never need to mess with this. Delegates to :func:`xml4h.writer.write_node` applied to this node.
[ "Serialize", "this", "node", "and", "its", "descendants", "to", "text", "writing", "the", "output", "to", "a", "given", "*", "writer", "*", "or", "to", "stdout", "." ]
train
https://github.com/jmurty/xml4h/blob/adbb45e27a01a869a505aee7bc16bad2f517b511/xml4h/nodes.py#L450-L492
jmurty/xml4h
xml4h/nodes.py
Node.xml
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()
python
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()
[ "def", "xml", "(", "self", ",", "indent", "=", "4", ",", "*", "*", "kwargs", ")", ":", "writer", "=", "StringIO", "(", ")", "self", ".", "write", "(", "writer", ",", "indent", "=", "indent", ",", "*", "*", "kwargs", ")", "return", "writer", ".", "getvalue", "(", ")" ]
:return: this node as XML text. Delegates to :meth:`write`
[ ":", "return", ":", "this", "node", "as", "XML", "text", "." ]
train
https://github.com/jmurty/xml4h/blob/adbb45e27a01a869a505aee7bc16bad2f517b511/xml4h/nodes.py#L503-L511
jmurty/xml4h
xml4h/nodes.py
XPathMixin.xpath
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 a list of :class:`Node` objects, or a list of base type objects if the XPath query does not reference node objects. """ result = self.adapter.xpath_on_node(self.impl_node, xpath, **kwargs) if isinstance(result, (list, tuple)): return [self._maybe_wrap_node(r) for r in result] else: return self._maybe_wrap_node(result)
python
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 a list of :class:`Node` objects, or a list of base type objects if the XPath query does not reference node objects. """ result = self.adapter.xpath_on_node(self.impl_node, xpath, **kwargs) if isinstance(result, (list, tuple)): return [self._maybe_wrap_node(r) for r in result] else: return self._maybe_wrap_node(result)
[ "def", "xpath", "(", "self", ",", "xpath", ",", "*", "*", "kwargs", ")", ":", "result", "=", "self", ".", "adapter", ".", "xpath_on_node", "(", "self", ".", "impl_node", ",", "xpath", ",", "*", "*", "kwargs", ")", "if", "isinstance", "(", "result", ",", "(", "list", ",", "tuple", ")", ")", ":", "return", "[", "self", ".", "_maybe_wrap_node", "(", "r", ")", "for", "r", "in", "result", "]", "else", ":", "return", "self", ".", "_maybe_wrap_node", "(", "result", ")" ]
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 of base type objects if the XPath query does not reference node objects.
[ "Perform", "an", "XPath", "query", "on", "the", "current", "node", "." ]
train
https://github.com/jmurty/xml4h/blob/adbb45e27a01a869a505aee7bc16bad2f517b511/xml4h/nodes.py#L595-L611
jmurty/xml4h
xml4h/nodes.py
Element.set_attributes
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 :param ns_uri: a URI defining a namespace for the new attributes. :type ns_uri: string or None :param dict attr_dict: attribute name and values specified as keyword arguments. """ self._set_element_attributes(self.impl_node, attr_obj=attr_obj, ns_uri=ns_uri, **attr_dict)
python
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 :param ns_uri: a URI defining a namespace for the new attributes. :type ns_uri: string or None :param dict attr_dict: attribute name and values specified as keyword arguments. """ self._set_element_attributes(self.impl_node, attr_obj=attr_obj, ns_uri=ns_uri, **attr_dict)
[ "def", "set_attributes", "(", "self", ",", "attr_obj", "=", "None", ",", "ns_uri", "=", "None", ",", "*", "*", "attr_dict", ")", ":", "self", ".", "_set_element_attributes", "(", "self", ".", "impl_node", ",", "attr_obj", "=", "attr_obj", ",", "ns_uri", "=", "ns_uri", ",", "*", "*", "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 :param ns_uri: a URI defining a namespace for the new attributes. :type ns_uri: string or None :param dict attr_dict: attribute name and values specified as keyword arguments.
[ "Add", "or", "update", "this", "element", "s", "attributes", "where", "attributes", "can", "be", "specified", "in", "a", "number", "of", "ways", "." ]
train
https://github.com/jmurty/xml4h/blob/adbb45e27a01a869a505aee7bc16bad2f517b511/xml4h/nodes.py#L841-L854
jmurty/xml4h
xml4h/nodes.py
Element.attributes
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 them. """ attr_impl_nodes = self.adapter.get_node_attributes(self.impl_node) return AttributeDict(attr_impl_nodes, self.impl_node, self.adapter)
python
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 them. """ attr_impl_nodes = self.adapter.get_node_attributes(self.impl_node) return AttributeDict(attr_impl_nodes, self.impl_node, self.adapter)
[ "def", "attributes", "(", "self", ")", ":", "attr_impl_nodes", "=", "self", ".", "adapter", ".", "get_node_attributes", "(", "self", ".", "impl_node", ")", "return", "AttributeDict", "(", "attr_impl_nodes", ",", "self", ".", "impl_node", ",", "self", ".", "adapter", ")" ]
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.
[ "Get", "or", "set", "this", "element", "s", "attributes", "as", "name", "/", "value", "pairs", "." ]
train
https://github.com/jmurty/xml4h/blob/adbb45e27a01a869a505aee7bc16bad2f517b511/xml4h/nodes.py#L857-L867
jmurty/xml4h
xml4h/nodes.py
Element.attribute_nodes
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, self.adapter) for a in impl_attr_nodes] return sorted(wrapped_attr_nodes, key=lambda x: x.name)
python
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, self.adapter) for a in impl_attr_nodes] return sorted(wrapped_attr_nodes, key=lambda x: x.name)
[ "def", "attribute_nodes", "(", "self", ")", ":", "impl_attr_nodes", "=", "self", ".", "adapter", ".", "get_node_attributes", "(", "self", ".", "impl_node", ")", "wrapped_attr_nodes", "=", "[", "self", ".", "adapter", ".", "wrap_node", "(", "a", ",", "self", ".", "adapter", ".", "impl_document", ",", "self", ".", "adapter", ")", "for", "a", "in", "impl_attr_nodes", "]", "return", "sorted", "(", "wrapped_attr_nodes", ",", "key", "=", "lambda", "x", ":", "x", ".", "name", ")" ]
:return: a list of this element's attributes as :class:`Attribute` nodes.
[ ":", "return", ":", "a", "list", "of", "this", "element", "s", "attributes", "as", ":", "class", ":", "Attribute", "nodes", "." ]
train
https://github.com/jmurty/xml4h/blob/adbb45e27a01a869a505aee7bc16bad2f517b511/xml4h/nodes.py#L891-L900
jmurty/xml4h
xml4h/nodes.py
Element.attribute_node
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 :class:`Attribute` nodes. """ attr_impl_node = self.adapter.get_node_attribute_node( self.impl_node, name, ns_uri) return self.adapter.wrap_node( attr_impl_node, self.adapter.impl_document, self.adapter)
python
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 :class:`Attribute` nodes. """ attr_impl_node = self.adapter.get_node_attribute_node( self.impl_node, name, ns_uri) return self.adapter.wrap_node( attr_impl_node, self.adapter.impl_document, self.adapter)
[ "def", "attribute_node", "(", "self", ",", "name", ",", "ns_uri", "=", "None", ")", ":", "attr_impl_node", "=", "self", ".", "adapter", ".", "get_node_attribute_node", "(", "self", ".", "impl_node", ",", "name", ",", "ns_uri", ")", "return", "self", ".", "adapter", ".", "wrap_node", "(", "attr_impl_node", ",", "self", ".", "adapter", ".", "impl_document", ",", "self", ".", "adapter", ")" ]
: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.
[ ":", "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" ]
train
https://github.com/jmurty/xml4h/blob/adbb45e27a01a869a505aee7bc16bad2f517b511/xml4h/nodes.py#L902-L914
jmurty/xml4h
xml4h/nodes.py
Element.set_ns_prefix
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 that will be denoted by the prefix. """ self._add_ns_prefix_attr(self.impl_node, prefix, ns_uri)
python
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 that will be denoted by the prefix. """ self._add_ns_prefix_attr(self.impl_node, prefix, ns_uri)
[ "def", "set_ns_prefix", "(", "self", ",", "prefix", ",", "ns_uri", ")", ":", "self", ".", "_add_ns_prefix_attr", "(", "self", ".", "impl_node", ",", "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 that will be denoted by the prefix.
[ "Define", "a", "namespace", "prefix", "that", "will", "serve", "as", "shorthand", "for", "the", "given", "namespace", "URI", "in", "element", "names", "." ]
train
https://github.com/jmurty/xml4h/blob/adbb45e27a01a869a505aee7bc16bad2f517b511/xml4h/nodes.py#L925-L935
jmurty/xml4h
xml4h/nodes.py
Element.add_element
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. :param string name: a name for the child node. The name may be used to apply a namespace to the child by including: - a prefix component in the name of the form ``ns_prefix:element_name``, where the prefix has already been defined for a namespace URI (such as via :meth:`set_ns_prefix`). - a literal namespace URI value delimited by curly braces, of the form ``{ns_uri}element_name``. :param ns_uri: a URI specifying the new element's namespace. If the ``name`` parameter specifies a namespace this parameter is ignored. :type ns_uri: string or None :param attributes: collection of attributes to assign to the new child. :type attributes: dict, list, tuple, or None :param text: text value to assign to the new child. :type text: string or None :param bool before_this_element: if *True* the new element is added as a sibling preceding this element, instead of as a child. In other words, the new element will be a child of this element's parent node, and will immediately precent this element in the DOM. :return: the new child as a an :class:`Element` node. """ # Determine local name, namespace and prefix info from tag name prefix, local_name, node_ns_uri = \ self.adapter.get_ns_info_from_node_name(name, self.impl_node) if prefix: qname = u'%s:%s' % (prefix, local_name) else: qname = local_name # If no name-derived namespace, apply an alternate namespace if node_ns_uri is None: if ns_uri is None: # Default document namespace node_ns_uri = self.adapter.get_ns_uri_for_prefix( self.impl_node, None) else: # keyword-parameter namespace node_ns_uri = ns_uri # Create element child_elem = self.adapter.new_impl_element( qname, node_ns_uri, parent=self.impl_node) # If element's default namespace was defined by literal uri prefix, # create corresponding xmlns attribute for element... if not prefix and '}' in name: self._set_element_attributes(child_elem, {'xmlns': node_ns_uri}, ns_uri=self.XMLNS_URI) # ...otherwise define keyword-defined namespace as the default, if any elif ns_uri is not None: self._set_element_attributes(child_elem, {'xmlns': ns_uri}, ns_uri=self.XMLNS_URI) # Create subordinate nodes if attributes is not None: self._set_element_attributes(child_elem, attr_obj=attributes) if text is not None: self._add_text(child_elem, text) # Add new element to its parent before a given node... if before_this_element: self.adapter.add_node_child( self.adapter.get_node_parent(self.impl_node), child_elem, before_sibling=self.impl_node) # ...or in the default position, appended after existing nodes else: self.adapter.add_node_child(self.impl_node, child_elem) return self.adapter.wrap_node( child_elem, self.adapter.impl_document, self.adapter)
python
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. :param string name: a name for the child node. The name may be used to apply a namespace to the child by including: - a prefix component in the name of the form ``ns_prefix:element_name``, where the prefix has already been defined for a namespace URI (such as via :meth:`set_ns_prefix`). - a literal namespace URI value delimited by curly braces, of the form ``{ns_uri}element_name``. :param ns_uri: a URI specifying the new element's namespace. If the ``name`` parameter specifies a namespace this parameter is ignored. :type ns_uri: string or None :param attributes: collection of attributes to assign to the new child. :type attributes: dict, list, tuple, or None :param text: text value to assign to the new child. :type text: string or None :param bool before_this_element: if *True* the new element is added as a sibling preceding this element, instead of as a child. In other words, the new element will be a child of this element's parent node, and will immediately precent this element in the DOM. :return: the new child as a an :class:`Element` node. """ # Determine local name, namespace and prefix info from tag name prefix, local_name, node_ns_uri = \ self.adapter.get_ns_info_from_node_name(name, self.impl_node) if prefix: qname = u'%s:%s' % (prefix, local_name) else: qname = local_name # If no name-derived namespace, apply an alternate namespace if node_ns_uri is None: if ns_uri is None: # Default document namespace node_ns_uri = self.adapter.get_ns_uri_for_prefix( self.impl_node, None) else: # keyword-parameter namespace node_ns_uri = ns_uri # Create element child_elem = self.adapter.new_impl_element( qname, node_ns_uri, parent=self.impl_node) # If element's default namespace was defined by literal uri prefix, # create corresponding xmlns attribute for element... if not prefix and '}' in name: self._set_element_attributes(child_elem, {'xmlns': node_ns_uri}, ns_uri=self.XMLNS_URI) # ...otherwise define keyword-defined namespace as the default, if any elif ns_uri is not None: self._set_element_attributes(child_elem, {'xmlns': ns_uri}, ns_uri=self.XMLNS_URI) # Create subordinate nodes if attributes is not None: self._set_element_attributes(child_elem, attr_obj=attributes) if text is not None: self._add_text(child_elem, text) # Add new element to its parent before a given node... if before_this_element: self.adapter.add_node_child( self.adapter.get_node_parent(self.impl_node), child_elem, before_sibling=self.impl_node) # ...or in the default position, appended after existing nodes else: self.adapter.add_node_child(self.impl_node, child_elem) return self.adapter.wrap_node( child_elem, self.adapter.impl_document, self.adapter)
[ "def", "add_element", "(", "self", ",", "name", ",", "ns_uri", "=", "None", ",", "attributes", "=", "None", ",", "text", "=", "None", ",", "before_this_element", "=", "False", ")", ":", "# Determine local name, namespace and prefix info from tag name", "prefix", ",", "local_name", ",", "node_ns_uri", "=", "self", ".", "adapter", ".", "get_ns_info_from_node_name", "(", "name", ",", "self", ".", "impl_node", ")", "if", "prefix", ":", "qname", "=", "u'%s:%s'", "%", "(", "prefix", ",", "local_name", ")", "else", ":", "qname", "=", "local_name", "# If no name-derived namespace, apply an alternate namespace", "if", "node_ns_uri", "is", "None", ":", "if", "ns_uri", "is", "None", ":", "# Default document namespace", "node_ns_uri", "=", "self", ".", "adapter", ".", "get_ns_uri_for_prefix", "(", "self", ".", "impl_node", ",", "None", ")", "else", ":", "# keyword-parameter namespace", "node_ns_uri", "=", "ns_uri", "# Create element", "child_elem", "=", "self", ".", "adapter", ".", "new_impl_element", "(", "qname", ",", "node_ns_uri", ",", "parent", "=", "self", ".", "impl_node", ")", "# If element's default namespace was defined by literal uri prefix,", "# create corresponding xmlns attribute for element...", "if", "not", "prefix", "and", "'}'", "in", "name", ":", "self", ".", "_set_element_attributes", "(", "child_elem", ",", "{", "'xmlns'", ":", "node_ns_uri", "}", ",", "ns_uri", "=", "self", ".", "XMLNS_URI", ")", "# ...otherwise define keyword-defined namespace as the default, if any", "elif", "ns_uri", "is", "not", "None", ":", "self", ".", "_set_element_attributes", "(", "child_elem", ",", "{", "'xmlns'", ":", "ns_uri", "}", ",", "ns_uri", "=", "self", ".", "XMLNS_URI", ")", "# Create subordinate nodes", "if", "attributes", "is", "not", "None", ":", "self", ".", "_set_element_attributes", "(", "child_elem", ",", "attr_obj", "=", "attributes", ")", "if", "text", "is", "not", "None", ":", "self", ".", "_add_text", "(", "child_elem", ",", "text", ")", "# Add new element to its parent before a given node...", "if", "before_this_element", ":", "self", ".", "adapter", ".", "add_node_child", "(", "self", ".", "adapter", ".", "get_node_parent", "(", "self", ".", "impl_node", ")", ",", "child_elem", ",", "before_sibling", "=", "self", ".", "impl_node", ")", "# ...or in the default position, appended after existing nodes", "else", ":", "self", ".", "adapter", ".", "add_node_child", "(", "self", ".", "impl_node", ",", "child_elem", ")", "return", "self", ".", "adapter", ".", "wrap_node", "(", "child_elem", ",", "self", ".", "adapter", ".", "impl_document", ",", "self", ".", "adapter", ")" ]
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: - a prefix component in the name of the form ``ns_prefix:element_name``, where the prefix has already been defined for a namespace URI (such as via :meth:`set_ns_prefix`). - a literal namespace URI value delimited by curly braces, of the form ``{ns_uri}element_name``. :param ns_uri: a URI specifying the new element's namespace. If the ``name`` parameter specifies a namespace this parameter is ignored. :type ns_uri: string or None :param attributes: collection of attributes to assign to the new child. :type attributes: dict, list, tuple, or None :param text: text value to assign to the new child. :type text: string or None :param bool before_this_element: if *True* the new element is added as a sibling preceding this element, instead of as a child. In other words, the new element will be a child of this element's parent node, and will immediately precent this element in the DOM. :return: the new child as a an :class:`Element` node.
[ "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", "." ]
train
https://github.com/jmurty/xml4h/blob/adbb45e27a01a869a505aee7bc16bad2f517b511/xml4h/nodes.py#L937-L1008
jmurty/xml4h
xml4h/nodes.py
Element.add_text
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 content to add to this element. :param type: string or anything that can be coerced by :func:`unicode`. """ if not isinstance(text, basestring): text = unicode(text) self._add_text(self.impl_node, text)
python
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 content to add to this element. :param type: string or anything that can be coerced by :func:`unicode`. """ if not isinstance(text, basestring): text = unicode(text) self._add_text(self.impl_node, text)
[ "def", "add_text", "(", "self", ",", "text", ")", ":", "if", "not", "isinstance", "(", "text", ",", "basestring", ")", ":", "text", "=", "unicode", "(", "text", ")", "self", ".", "_add_text", "(", "self", ".", "impl_node", ",", "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 type: string or anything that can be coerced by :func:`unicode`.
[ "Add", "a", "text", "node", "to", "this", "element", "." ]
train
https://github.com/jmurty/xml4h/blob/adbb45e27a01a869a505aee7bc16bad2f517b511/xml4h/nodes.py#L1014-L1027
jmurty/xml4h
xml4h/nodes.py
Element.add_instruction
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)
python
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)
[ "def", "add_instruction", "(", "self", ",", "target", ",", "data", ")", ":", "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.
[ "Add", "an", "instruction", "node", "to", "this", "element", "." ]
train
https://github.com/jmurty/xml4h/blob/adbb45e27a01a869a505aee7bc16bad2f517b511/xml4h/nodes.py#L1045-L1051
jmurty/xml4h
xml4h/nodes.py
AttributeDict.items
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]
python
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]
[ "def", "items", "(", "self", ")", ":", "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.
[ ":", "return", ":", "a", "list", "of", "name", "/", "value", "attribute", "pairs", "sorted", "by", "attribute", "name", "." ]
train
https://github.com/jmurty/xml4h/blob/adbb45e27a01a869a505aee7bc16bad2f517b511/xml4h/nodes.py#L1135-L1140
jmurty/xml4h
xml4h/nodes.py
AttributeDict.namespace_uri
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: return None return self.adapter.get_node_namespace_uri(a_node)
python
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: return None return self.adapter.get_node_namespace_uri(a_node)
[ "def", "namespace_uri", "(", "self", ",", "name", ")", ":", "a_node", "=", "self", ".", "adapter", ".", "get_node_attribute_node", "(", "self", ".", "impl_element", ",", "name", ")", "if", "a_node", "is", "None", ":", "return", "None", "return", "self", ".", "adapter", ".", "get_node_namespace_uri", "(", "a_node", ")" ]
:param string name: the name of an attribute to look up. :return: the namespace URI associated with the named attribute, or None.
[ ":", "param", "string", "name", ":", "the", "name", "of", "an", "attribute", "to", "look", "up", "." ]
train
https://github.com/jmurty/xml4h/blob/adbb45e27a01a869a505aee7bc16bad2f517b511/xml4h/nodes.py#L1142-L1152
jmurty/xml4h
xml4h/nodes.py
AttributeDict.prefix
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: return None return a_node.prefix
python
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: return None return a_node.prefix
[ "def", "prefix", "(", "self", ",", "name", ")", ":", "a_node", "=", "self", ".", "adapter", ".", "get_node_attribute_node", "(", "self", ".", "impl_element", ",", "name", ")", "if", "a_node", "is", "None", ":", "return", "None", "return", "a_node", ".", "prefix" ]
:param string name: the name of an attribute to look up. :return: the prefix component of the named attribute's name, or None.
[ ":", "param", "string", "name", ":", "the", "name", "of", "an", "attribute", "to", "look", "up", "." ]
train
https://github.com/jmurty/xml4h/blob/adbb45e27a01a869a505aee7bc16bad2f517b511/xml4h/nodes.py#L1154-L1164
jmurty/xml4h
xml4h/nodes.py
AttributeDict.element
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)
python
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)
[ "def", "element", "(", "self", ")", ":", "return", "self", ".", "adapter", ".", "wrap_node", "(", "self", ".", "impl_element", ",", "self", ".", "adapter", ".", "impl_document", ",", "self", ".", "adapter", ")" ]
:return: the :class:`Element` that contains these attributes.
[ ":", "return", ":", "the", ":", "class", ":", "Element", "that", "contains", "these", "attributes", "." ]
train
https://github.com/jmurty/xml4h/blob/adbb45e27a01a869a505aee7bc16bad2f517b511/xml4h/nodes.py#L1175-L1180
jmurty/xml4h
xml4h/nodes.py
NodeList.filter
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 name used to filter the nodes. :type name: string or None :param ns_uri: a namespace URI used to filter the nodes. If *None* all nodes are returned regardless of namespace. :type ns_uri: string or None :param node_type: a node type definition used to filter the nodes. :type node_type: int node type constant, class, or None :param filter_fn: an arbitrary function to filter nodes in this list. This function must accept a single :class:`Node` argument and return a bool indicating whether to include the node in the filtered results. .. note:: if ``filter_fn`` is provided all other filter arguments are ignore. :type filter_fn: function or None :return: the type of the return value depends on the value of the ``first_only`` parameter and how many nodes match the filter: - if ``first_only=False`` return a :class:`NodeList` of filtered nodes, which will be empty if there are no matching nodes. - if ``first_only=True`` and at least one node matches, return the first matching :class:`Node` - if ``first_only=True`` and there are no matching nodes, return *None* """ # Build our own filter function unless a custom function is provided if filter_fn is None: def filter_fn(n): # Test node type first in case other tests require this type if node_type is not None: # Node type can be specified as an integer constant (e.g. # ELEMENT_NODE) or a class. if isinstance(node_type, int): if not n.is_type(node_type): return False elif n.__class__ != node_type: return False if name is not None and n.name != name: return False if local_name is not None and n.local_name != local_name: return False if ns_uri is not None and n.ns_uri != ns_uri: return False return True # Filter nodes nodelist = filter(filter_fn, self) # If requested, return just the first node (or None if no nodes) if first_only: return nodelist[0] if nodelist else None else: return NodeList(nodelist)
python
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 name used to filter the nodes. :type name: string or None :param ns_uri: a namespace URI used to filter the nodes. If *None* all nodes are returned regardless of namespace. :type ns_uri: string or None :param node_type: a node type definition used to filter the nodes. :type node_type: int node type constant, class, or None :param filter_fn: an arbitrary function to filter nodes in this list. This function must accept a single :class:`Node` argument and return a bool indicating whether to include the node in the filtered results. .. note:: if ``filter_fn`` is provided all other filter arguments are ignore. :type filter_fn: function or None :return: the type of the return value depends on the value of the ``first_only`` parameter and how many nodes match the filter: - if ``first_only=False`` return a :class:`NodeList` of filtered nodes, which will be empty if there are no matching nodes. - if ``first_only=True`` and at least one node matches, return the first matching :class:`Node` - if ``first_only=True`` and there are no matching nodes, return *None* """ # Build our own filter function unless a custom function is provided if filter_fn is None: def filter_fn(n): # Test node type first in case other tests require this type if node_type is not None: # Node type can be specified as an integer constant (e.g. # ELEMENT_NODE) or a class. if isinstance(node_type, int): if not n.is_type(node_type): return False elif n.__class__ != node_type: return False if name is not None and n.name != name: return False if local_name is not None and n.local_name != local_name: return False if ns_uri is not None and n.ns_uri != ns_uri: return False return True # Filter nodes nodelist = filter(filter_fn, self) # If requested, return just the first node (or None if no nodes) if first_only: return nodelist[0] if nodelist else None else: return NodeList(nodelist)
[ "def", "filter", "(", "self", ",", "local_name", "=", "None", ",", "name", "=", "None", ",", "ns_uri", "=", "None", ",", "node_type", "=", "None", ",", "filter_fn", "=", "None", ",", "first_only", "=", "False", ")", ":", "# Build our own filter function unless a custom function is provided", "if", "filter_fn", "is", "None", ":", "def", "filter_fn", "(", "n", ")", ":", "# Test node type first in case other tests require this type", "if", "node_type", "is", "not", "None", ":", "# Node type can be specified as an integer constant (e.g.", "# ELEMENT_NODE) or a class.", "if", "isinstance", "(", "node_type", ",", "int", ")", ":", "if", "not", "n", ".", "is_type", "(", "node_type", ")", ":", "return", "False", "elif", "n", ".", "__class__", "!=", "node_type", ":", "return", "False", "if", "name", "is", "not", "None", "and", "n", ".", "name", "!=", "name", ":", "return", "False", "if", "local_name", "is", "not", "None", "and", "n", ".", "local_name", "!=", "local_name", ":", "return", "False", "if", "ns_uri", "is", "not", "None", "and", "n", ".", "ns_uri", "!=", "ns_uri", ":", "return", "False", "return", "True", "# Filter nodes", "nodelist", "=", "filter", "(", "filter_fn", ",", "self", ")", "# If requested, return just the first node (or None if no nodes)", "if", "first_only", ":", "return", "nodelist", "[", "0", "]", "if", "nodelist", "else", "None", "else", ":", "return", "NodeList", "(", "nodelist", ")" ]
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. If *None* all nodes are returned regardless of namespace. :type ns_uri: string or None :param node_type: a node type definition used to filter the nodes. :type node_type: int node type constant, class, or None :param filter_fn: an arbitrary function to filter nodes in this list. This function must accept a single :class:`Node` argument and return a bool indicating whether to include the node in the filtered results. .. note:: if ``filter_fn`` is provided all other filter arguments are ignore. :type filter_fn: function or None :return: the type of the return value depends on the value of the ``first_only`` parameter and how many nodes match the filter: - if ``first_only=False`` return a :class:`NodeList` of filtered nodes, which will be empty if there are no matching nodes. - if ``first_only=True`` and at least one node matches, return the first matching :class:`Node` - if ``first_only=True`` and there are no matching nodes, return *None*
[ "Apply", "filters", "to", "the", "set", "of", "nodes", "in", "this", "list", "." ]
train
https://github.com/jmurty/xml4h/blob/adbb45e27a01a869a505aee7bc16bad2f517b511/xml4h/nodes.py#L1197-L1255
redhat-cip/dci-control-server
dci/api/v1/analytics.py
get_all_analytics
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 if user.is_not_super_admin() and not user.is_read_only_user(): query.add_extra_condition(_TABLE.c.team_id.in_(user.teams_ids)) query.add_extra_condition(_TABLE.c.job_id == job_id) nb_rows = query.get_number_of_rows() rows = query.execute(fetchall=True) rows = v1_utils.format_result(rows, _TABLE.name) return flask.jsonify({'analytics': rows, '_meta': {'count': nb_rows}})
python
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 if user.is_not_super_admin() and not user.is_read_only_user(): query.add_extra_condition(_TABLE.c.team_id.in_(user.teams_ids)) query.add_extra_condition(_TABLE.c.job_id == job_id) nb_rows = query.get_number_of_rows() rows = query.execute(fetchall=True) rows = v1_utils.format_result(rows, _TABLE.name) return flask.jsonify({'analytics': rows, '_meta': {'count': nb_rows}})
[ "def", "get_all_analytics", "(", "user", ",", "job_id", ")", ":", "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", "if", "user", ".", "is_not_super_admin", "(", ")", "and", "not", "user", ".", "is_read_only_user", "(", ")", ":", "query", ".", "add_extra_condition", "(", "_TABLE", ".", "c", ".", "team_id", ".", "in_", "(", "user", ".", "teams_ids", ")", ")", "query", ".", "add_extra_condition", "(", "_TABLE", ".", "c", ".", "job_id", "==", "job_id", ")", "nb_rows", "=", "query", ".", "get_number_of_rows", "(", ")", "rows", "=", "query", ".", "execute", "(", "fetchall", "=", "True", ")", "rows", "=", "v1_utils", ".", "format_result", "(", "rows", ",", "_TABLE", ".", "name", ")", "return", "flask", ".", "jsonify", "(", "{", "'analytics'", ":", "rows", ",", "'_meta'", ":", "{", "'count'", ":", "nb_rows", "}", "}", ")" ]
Get all analytics of a job.
[ "Get", "all", "analytics", "of", "a", "job", "." ]
train
https://github.com/redhat-cip/dci-control-server/blob/b416cf935ec93e4fdd5741f61a21cabecf8454d2/dci/api/v1/analytics.py#L53-L70
redhat-cip/dci-control-server
dci/api/v1/analytics.py
get_analytic
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 flask.jsonify({'analytic': analytic})
python
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 flask.jsonify({'analytic': analytic})
[ "def", "get_analytic", "(", "user", ",", "job_id", ",", "anc_id", ")", ":", "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", "flask", ".", "jsonify", "(", "{", "'analytic'", ":", "analytic", "}", ")" ]
Get an analytic.
[ "Get", "an", "analytic", "." ]
train
https://github.com/redhat-cip/dci-control-server/blob/b416cf935ec93e4fdd5741f61a21cabecf8454d2/dci/api/v1/analytics.py#L75-L83
jmurty/xml4h
xml4h/writer.py
write_node
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 descendants will be serialized. :type node: an :class:`xml4h.nodes.Node` or subclass :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 string encoding: the character encoding for serialized text. :param indent: indentation prefix to apply to descendent nodes for pretty-printing. The value can take many forms: - *int*: the number of spaces to indent. 0 means no indent. - *string*: a literal prefix for indented nodes, such as ``\\t``. - *bool*: no indent if *False*, four spaces indent if *True*. - *None*: no indent. :type indent: string, int, bool, or None :param newline: the string value used to separate lines of output. The value can take a number of forms: - *string*: the literal newline value, such as ``\\n`` or ``\\r``. An empty string means no newline. - *bool*: no newline if *False*, ``\\n`` newline if *True*. - *None*: no newline. :type newline: string, bool, or None :param boolean omit_declaration: if *True* the XML declaration header is omitted, otherwise it is included. Note that the declaration is only output when serializing an :class:`xml4h.nodes.Document` node. :param int node_depth: the indentation level to start at, such as 2 to indent output as if the given *node* has two ancestors. This parameter will only be useful if you need to output XML text fragments that can be assembled into a document. This parameter has no effect unless indentation is applied. :param string quote_char: the character that delimits quoted content. You should never need to mess with this. """ def _sanitize_write_value(value): """Return XML-encoded value.""" if not value: return value return (value .replace("&", "&amp;") .replace("<", "&lt;") .replace("\"", "&quot;") .replace(">", "&gt;") ) def _write_node_impl(node, node_depth): """ Internal write implementation that does the real work while keeping track of node depth. """ # Output document declaration if we're outputting the whole doc if node.is_document: if not omit_declaration: writer.write( '<?xml version=%s1.0%s' % (quote_char, quote_char)) if encoding: writer.write(' encoding=%s%s%s' % (quote_char, encoding, quote_char)) writer.write('?>%s' % newline) for child in node.children: _write_node_impl(child, node_depth) # node_depth not incremented writer.write(newline) elif node.is_document_type: writer.write("<!DOCTYPE %s SYSTEM %s%s%s" % (node.name, quote_char, node.public_id)) if node.system_id is not None: writer.write( " %s%s%s" % (quote_char, node.system_id, quote_char)) if node.children: writer.write("[") for child in node.children: _write_node_impl(child, node_depth + 1) writer.write("]") writer.write(">") elif node.is_text: writer.write(_sanitize_write_value(node.value)) elif node.is_cdata: if ']]>' in node.value: raise ValueError("']]>' is not allowed in CDATA node value") writer.write("<![CDATA[%s]]>" % node.value) #elif node.is_entity_reference: # TODO elif node.is_entity: writer.write(newline + indent * node_depth) writer.write("<!ENTITY ") if node.is_paremeter_entity: writer.write('%% ') writer.write("%s %s%s%s>" % (node.name, quote_char, node.value, quote_char)) elif node.is_processing_instruction: writer.write(newline + indent * node_depth) writer.write("<?%s %s?>" % (node.target, node.data)) elif node.is_comment: if '--' in node.value: raise ValueError("'--' is not allowed in COMMENT node value") writer.write("<!--%s-->" % node.value) elif node.is_notation: writer.write(newline + indent * node_depth) writer.write("<!NOTATION %s" % node.name) if node.is_system_identifier: writer.write(" system %s%s%s>" % (quote_char, node.external_id, quote_char)) elif node.is_system_identifier: writer.write(" system %s%s%s %s%s%s>" % (quote_char, node.external_id, quote_char, quote_char, node.uri, quote_char)) elif node.is_attribute: writer.write(" %s=%s" % (node.name, quote_char)) writer.write(_sanitize_write_value(node.value)) writer.write(quote_char) elif node.is_element: # Only need a preceding newline if we're in a sub-element if node_depth > 0: writer.write(newline) writer.write(indent * node_depth) writer.write("<" + node.name) for attr in node.attribute_nodes: _write_node_impl(attr, node_depth) if node.children: found_indented_child = False writer.write(">") for child in node.children: _write_node_impl(child, node_depth + 1) if not (child.is_text or child.is_comment or child.is_cdata): found_indented_child = True if found_indented_child: writer.write(newline + indent * node_depth) writer.write('</%s>' % node.name) else: writer.write('/>') else: raise exceptions.Xml4hImplementationBug( 'Cannot write node with class: %s' % node.__class__) # Sanitize whitespace parameters if indent is True: indent = ' ' * 4 elif indent is False: indent = '' elif isinstance(indent, int): indent = ' ' * indent # If indent but no newline set, always apply a newline (it makes sense) if indent and not newline: newline = True if newline is None or newline is False: newline = '' elif newline is True: newline = '\n' # We always need a writer, use stdout by default if writer is None: writer = sys.stdout # Apply a text encoding if we have one if encoding is None: writer = writer else: writer = codecs.getwriter(encoding)(writer) # Do the business... _write_node_impl(node, node_depth)
python
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 descendants will be serialized. :type node: an :class:`xml4h.nodes.Node` or subclass :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 string encoding: the character encoding for serialized text. :param indent: indentation prefix to apply to descendent nodes for pretty-printing. The value can take many forms: - *int*: the number of spaces to indent. 0 means no indent. - *string*: a literal prefix for indented nodes, such as ``\\t``. - *bool*: no indent if *False*, four spaces indent if *True*. - *None*: no indent. :type indent: string, int, bool, or None :param newline: the string value used to separate lines of output. The value can take a number of forms: - *string*: the literal newline value, such as ``\\n`` or ``\\r``. An empty string means no newline. - *bool*: no newline if *False*, ``\\n`` newline if *True*. - *None*: no newline. :type newline: string, bool, or None :param boolean omit_declaration: if *True* the XML declaration header is omitted, otherwise it is included. Note that the declaration is only output when serializing an :class:`xml4h.nodes.Document` node. :param int node_depth: the indentation level to start at, such as 2 to indent output as if the given *node* has two ancestors. This parameter will only be useful if you need to output XML text fragments that can be assembled into a document. This parameter has no effect unless indentation is applied. :param string quote_char: the character that delimits quoted content. You should never need to mess with this. """ def _sanitize_write_value(value): """Return XML-encoded value.""" if not value: return value return (value .replace("&", "&amp;") .replace("<", "&lt;") .replace("\"", "&quot;") .replace(">", "&gt;") ) def _write_node_impl(node, node_depth): """ Internal write implementation that does the real work while keeping track of node depth. """ # Output document declaration if we're outputting the whole doc if node.is_document: if not omit_declaration: writer.write( '<?xml version=%s1.0%s' % (quote_char, quote_char)) if encoding: writer.write(' encoding=%s%s%s' % (quote_char, encoding, quote_char)) writer.write('?>%s' % newline) for child in node.children: _write_node_impl(child, node_depth) # node_depth not incremented writer.write(newline) elif node.is_document_type: writer.write("<!DOCTYPE %s SYSTEM %s%s%s" % (node.name, quote_char, node.public_id)) if node.system_id is not None: writer.write( " %s%s%s" % (quote_char, node.system_id, quote_char)) if node.children: writer.write("[") for child in node.children: _write_node_impl(child, node_depth + 1) writer.write("]") writer.write(">") elif node.is_text: writer.write(_sanitize_write_value(node.value)) elif node.is_cdata: if ']]>' in node.value: raise ValueError("']]>' is not allowed in CDATA node value") writer.write("<![CDATA[%s]]>" % node.value) #elif node.is_entity_reference: # TODO elif node.is_entity: writer.write(newline + indent * node_depth) writer.write("<!ENTITY ") if node.is_paremeter_entity: writer.write('%% ') writer.write("%s %s%s%s>" % (node.name, quote_char, node.value, quote_char)) elif node.is_processing_instruction: writer.write(newline + indent * node_depth) writer.write("<?%s %s?>" % (node.target, node.data)) elif node.is_comment: if '--' in node.value: raise ValueError("'--' is not allowed in COMMENT node value") writer.write("<!--%s-->" % node.value) elif node.is_notation: writer.write(newline + indent * node_depth) writer.write("<!NOTATION %s" % node.name) if node.is_system_identifier: writer.write(" system %s%s%s>" % (quote_char, node.external_id, quote_char)) elif node.is_system_identifier: writer.write(" system %s%s%s %s%s%s>" % (quote_char, node.external_id, quote_char, quote_char, node.uri, quote_char)) elif node.is_attribute: writer.write(" %s=%s" % (node.name, quote_char)) writer.write(_sanitize_write_value(node.value)) writer.write(quote_char) elif node.is_element: # Only need a preceding newline if we're in a sub-element if node_depth > 0: writer.write(newline) writer.write(indent * node_depth) writer.write("<" + node.name) for attr in node.attribute_nodes: _write_node_impl(attr, node_depth) if node.children: found_indented_child = False writer.write(">") for child in node.children: _write_node_impl(child, node_depth + 1) if not (child.is_text or child.is_comment or child.is_cdata): found_indented_child = True if found_indented_child: writer.write(newline + indent * node_depth) writer.write('</%s>' % node.name) else: writer.write('/>') else: raise exceptions.Xml4hImplementationBug( 'Cannot write node with class: %s' % node.__class__) # Sanitize whitespace parameters if indent is True: indent = ' ' * 4 elif indent is False: indent = '' elif isinstance(indent, int): indent = ' ' * indent # If indent but no newline set, always apply a newline (it makes sense) if indent and not newline: newline = True if newline is None or newline is False: newline = '' elif newline is True: newline = '\n' # We always need a writer, use stdout by default if writer is None: writer = sys.stdout # Apply a text encoding if we have one if encoding is None: writer = writer else: writer = codecs.getwriter(encoding)(writer) # Do the business... _write_node_impl(node, node_depth)
[ "def", "write_node", "(", "node", ",", "writer", "=", "None", ",", "encoding", "=", "'utf-8'", ",", "indent", "=", "0", ",", "newline", "=", "''", ",", "omit_declaration", "=", "False", ",", "node_depth", "=", "0", ",", "quote_char", "=", "'\"'", ")", ":", "def", "_sanitize_write_value", "(", "value", ")", ":", "\"\"\"Return XML-encoded value.\"\"\"", "if", "not", "value", ":", "return", "value", "return", "(", "value", ".", "replace", "(", "\"&\"", ",", "\"&amp;\"", ")", ".", "replace", "(", "\"<\"", ",", "\"&lt;\"", ")", ".", "replace", "(", "\"\\\"\"", ",", "\"&quot;\"", ")", ".", "replace", "(", "\">\"", ",", "\"&gt;\"", ")", ")", "def", "_write_node_impl", "(", "node", ",", "node_depth", ")", ":", "\"\"\"\n Internal write implementation that does the real work while keeping\n track of node depth.\n \"\"\"", "# Output document declaration if we're outputting the whole doc", "if", "node", ".", "is_document", ":", "if", "not", "omit_declaration", ":", "writer", ".", "write", "(", "'<?xml version=%s1.0%s'", "%", "(", "quote_char", ",", "quote_char", ")", ")", "if", "encoding", ":", "writer", ".", "write", "(", "' encoding=%s%s%s'", "%", "(", "quote_char", ",", "encoding", ",", "quote_char", ")", ")", "writer", ".", "write", "(", "'?>%s'", "%", "newline", ")", "for", "child", "in", "node", ".", "children", ":", "_write_node_impl", "(", "child", ",", "node_depth", ")", "# node_depth not incremented", "writer", ".", "write", "(", "newline", ")", "elif", "node", ".", "is_document_type", ":", "writer", ".", "write", "(", "\"<!DOCTYPE %s SYSTEM %s%s%s\"", "%", "(", "node", ".", "name", ",", "quote_char", ",", "node", ".", "public_id", ")", ")", "if", "node", ".", "system_id", "is", "not", "None", ":", "writer", ".", "write", "(", "\" %s%s%s\"", "%", "(", "quote_char", ",", "node", ".", "system_id", ",", "quote_char", ")", ")", "if", "node", ".", "children", ":", "writer", ".", "write", "(", "\"[\"", ")", "for", "child", "in", "node", ".", "children", ":", "_write_node_impl", "(", "child", ",", "node_depth", "+", "1", ")", "writer", ".", "write", "(", "\"]\"", ")", "writer", ".", "write", "(", "\">\"", ")", "elif", "node", ".", "is_text", ":", "writer", ".", "write", "(", "_sanitize_write_value", "(", "node", ".", "value", ")", ")", "elif", "node", ".", "is_cdata", ":", "if", "']]>'", "in", "node", ".", "value", ":", "raise", "ValueError", "(", "\"']]>' is not allowed in CDATA node value\"", ")", "writer", ".", "write", "(", "\"<![CDATA[%s]]>\"", "%", "node", ".", "value", ")", "#elif node.is_entity_reference: # TODO", "elif", "node", ".", "is_entity", ":", "writer", ".", "write", "(", "newline", "+", "indent", "*", "node_depth", ")", "writer", ".", "write", "(", "\"<!ENTITY \"", ")", "if", "node", ".", "is_paremeter_entity", ":", "writer", ".", "write", "(", "'%% '", ")", "writer", ".", "write", "(", "\"%s %s%s%s>\"", "%", "(", "node", ".", "name", ",", "quote_char", ",", "node", ".", "value", ",", "quote_char", ")", ")", "elif", "node", ".", "is_processing_instruction", ":", "writer", ".", "write", "(", "newline", "+", "indent", "*", "node_depth", ")", "writer", ".", "write", "(", "\"<?%s %s?>\"", "%", "(", "node", ".", "target", ",", "node", ".", "data", ")", ")", "elif", "node", ".", "is_comment", ":", "if", "'--'", "in", "node", ".", "value", ":", "raise", "ValueError", "(", "\"'--' is not allowed in COMMENT node value\"", ")", "writer", ".", "write", "(", "\"<!--%s-->\"", "%", "node", ".", "value", ")", "elif", "node", ".", "is_notation", ":", "writer", ".", "write", "(", "newline", "+", "indent", "*", "node_depth", ")", "writer", ".", "write", "(", "\"<!NOTATION %s\"", "%", "node", ".", "name", ")", "if", "node", ".", "is_system_identifier", ":", "writer", ".", "write", "(", "\" system %s%s%s>\"", "%", "(", "quote_char", ",", "node", ".", "external_id", ",", "quote_char", ")", ")", "elif", "node", ".", "is_system_identifier", ":", "writer", ".", "write", "(", "\" system %s%s%s %s%s%s>\"", "%", "(", "quote_char", ",", "node", ".", "external_id", ",", "quote_char", ",", "quote_char", ",", "node", ".", "uri", ",", "quote_char", ")", ")", "elif", "node", ".", "is_attribute", ":", "writer", ".", "write", "(", "\" %s=%s\"", "%", "(", "node", ".", "name", ",", "quote_char", ")", ")", "writer", ".", "write", "(", "_sanitize_write_value", "(", "node", ".", "value", ")", ")", "writer", ".", "write", "(", "quote_char", ")", "elif", "node", ".", "is_element", ":", "# Only need a preceding newline if we're in a sub-element", "if", "node_depth", ">", "0", ":", "writer", ".", "write", "(", "newline", ")", "writer", ".", "write", "(", "indent", "*", "node_depth", ")", "writer", ".", "write", "(", "\"<\"", "+", "node", ".", "name", ")", "for", "attr", "in", "node", ".", "attribute_nodes", ":", "_write_node_impl", "(", "attr", ",", "node_depth", ")", "if", "node", ".", "children", ":", "found_indented_child", "=", "False", "writer", ".", "write", "(", "\">\"", ")", "for", "child", "in", "node", ".", "children", ":", "_write_node_impl", "(", "child", ",", "node_depth", "+", "1", ")", "if", "not", "(", "child", ".", "is_text", "or", "child", ".", "is_comment", "or", "child", ".", "is_cdata", ")", ":", "found_indented_child", "=", "True", "if", "found_indented_child", ":", "writer", ".", "write", "(", "newline", "+", "indent", "*", "node_depth", ")", "writer", ".", "write", "(", "'</%s>'", "%", "node", ".", "name", ")", "else", ":", "writer", ".", "write", "(", "'/>'", ")", "else", ":", "raise", "exceptions", ".", "Xml4hImplementationBug", "(", "'Cannot write node with class: %s'", "%", "node", ".", "__class__", ")", "# Sanitize whitespace parameters", "if", "indent", "is", "True", ":", "indent", "=", "' '", "*", "4", "elif", "indent", "is", "False", ":", "indent", "=", "''", "elif", "isinstance", "(", "indent", ",", "int", ")", ":", "indent", "=", "' '", "*", "indent", "# If indent but no newline set, always apply a newline (it makes sense)", "if", "indent", "and", "not", "newline", ":", "newline", "=", "True", "if", "newline", "is", "None", "or", "newline", "is", "False", ":", "newline", "=", "''", "elif", "newline", "is", "True", ":", "newline", "=", "'\\n'", "# We always need a writer, use stdout by default", "if", "writer", "is", "None", ":", "writer", "=", "sys", ".", "stdout", "# Apply a text encoding if we have one", "if", "encoding", "is", "None", ":", "writer", "=", "writer", "else", ":", "writer", "=", "codecs", ".", "getwriter", "(", "encoding", ")", "(", "writer", ")", "# Do the business...", "_write_node_impl", "(", "node", ",", "node_depth", ")" ]
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 which XML text is sent. If *None* text is sent to :attr:`sys.stdout`. :type writer: a file, stream, etc or None :param string encoding: the character encoding for serialized text. :param indent: indentation prefix to apply to descendent nodes for pretty-printing. The value can take many forms: - *int*: the number of spaces to indent. 0 means no indent. - *string*: a literal prefix for indented nodes, such as ``\\t``. - *bool*: no indent if *False*, four spaces indent if *True*. - *None*: no indent. :type indent: string, int, bool, or None :param newline: the string value used to separate lines of output. The value can take a number of forms: - *string*: the literal newline value, such as ``\\n`` or ``\\r``. An empty string means no newline. - *bool*: no newline if *False*, ``\\n`` newline if *True*. - *None*: no newline. :type newline: string, bool, or None :param boolean omit_declaration: if *True* the XML declaration header is omitted, otherwise it is included. Note that the declaration is only output when serializing an :class:`xml4h.nodes.Document` node. :param int node_depth: the indentation level to start at, such as 2 to indent output as if the given *node* has two ancestors. This parameter will only be useful if you need to output XML text fragments that can be assembled into a document. This parameter has no effect unless indentation is applied. :param string quote_char: the character that delimits quoted content. You should never need to mess with this.
[ "Serialize", "an", "*", "xml4h", "*", "DOM", "node", "and", "its", "descendants", "to", "text", "writing", "the", "output", "to", "a", "given", "*", "writer", "*", "or", "to", "stdout", "." ]
train
https://github.com/jmurty/xml4h/blob/adbb45e27a01a869a505aee7bc16bad2f517b511/xml4h/writer.py#L12-L182
Antidote1911/cryptoshop
cryptoshop/_chunk_engine.py
encry_decry_chunk
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: a chunk in bytes to encrypt or decrypt. :param key: a 32 bytes key in bytes. :param algo: a string of algorithm. Can be "srp" , "AES" or "twf" :param bool_encry: if bool_encry is True, chunk is encrypted. Else, it will be decrypted. :param assoc_data: bytes string of additional data for GCM Authentication. :return: if bool_encry is True, corresponding nonce + cipherchunk else, a decrypted chunk. """ engine = botan.cipher(algo=algo, encrypt=bool_encry) engine.set_key(key=key) engine.set_assoc_data(assoc_data) if bool_encry is True: nonce = generate_nonce_timestamp() engine.start(nonce=nonce) return nonce + engine.finish(chunk) else: nonce = chunk[:__nonce_length__] encryptedchunk = chunk[__nonce_length__:__nonce_length__ + __gcmtag_length__ + __chunk_size__] engine.start(nonce=nonce) decryptedchunk = engine.finish(encryptedchunk) if decryptedchunk == b"": raise Exception("Integrity failure: Invalid passphrase or corrupted data") return decryptedchunk
python
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: a chunk in bytes to encrypt or decrypt. :param key: a 32 bytes key in bytes. :param algo: a string of algorithm. Can be "srp" , "AES" or "twf" :param bool_encry: if bool_encry is True, chunk is encrypted. Else, it will be decrypted. :param assoc_data: bytes string of additional data for GCM Authentication. :return: if bool_encry is True, corresponding nonce + cipherchunk else, a decrypted chunk. """ engine = botan.cipher(algo=algo, encrypt=bool_encry) engine.set_key(key=key) engine.set_assoc_data(assoc_data) if bool_encry is True: nonce = generate_nonce_timestamp() engine.start(nonce=nonce) return nonce + engine.finish(chunk) else: nonce = chunk[:__nonce_length__] encryptedchunk = chunk[__nonce_length__:__nonce_length__ + __gcmtag_length__ + __chunk_size__] engine.start(nonce=nonce) decryptedchunk = engine.finish(encryptedchunk) if decryptedchunk == b"": raise Exception("Integrity failure: Invalid passphrase or corrupted data") return decryptedchunk
[ "def", "encry_decry_chunk", "(", "chunk", ",", "key", ",", "algo", ",", "bool_encry", ",", "assoc_data", ")", ":", "engine", "=", "botan", ".", "cipher", "(", "algo", "=", "algo", ",", "encrypt", "=", "bool_encry", ")", "engine", ".", "set_key", "(", "key", "=", "key", ")", "engine", ".", "set_assoc_data", "(", "assoc_data", ")", "if", "bool_encry", "is", "True", ":", "nonce", "=", "generate_nonce_timestamp", "(", ")", "engine", ".", "start", "(", "nonce", "=", "nonce", ")", "return", "nonce", "+", "engine", ".", "finish", "(", "chunk", ")", "else", ":", "nonce", "=", "chunk", "[", ":", "__nonce_length__", "]", "encryptedchunk", "=", "chunk", "[", "__nonce_length__", ":", "__nonce_length__", "+", "__gcmtag_length__", "+", "__chunk_size__", "]", "engine", ".", "start", "(", "nonce", "=", "nonce", ")", "decryptedchunk", "=", "engine", ".", "finish", "(", "encryptedchunk", ")", "if", "decryptedchunk", "==", "b\"\"", ":", "raise", "Exception", "(", "\"Integrity failure: Invalid passphrase or corrupted data\"", ")", "return", "decryptedchunk" ]
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 bytes. :param algo: a string of algorithm. Can be "srp" , "AES" or "twf" :param bool_encry: if bool_encry is True, chunk is encrypted. Else, it will be decrypted. :param assoc_data: bytes string of additional data for GCM Authentication. :return: if bool_encry is True, corresponding nonce + cipherchunk else, a decrypted 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", "bytes", ".", ":", "param", "algo", ":", "a", "string", "of", "algorithm", ".", "Can", "be", "srp", "AES", "or", "twf", ":", "param", "bool_encry", ":", "if", "bool_encry", "is", "True", "chunk", "is", "encrypted", ".", "Else", "it", "will", "be", "decrypted", ".", ":", "param", "assoc_data", ":", "bytes", "string", "of", "additional", "data", "for", "GCM", "Authentication", ".", ":", "return", ":", "if", "bool_encry", "is", "True", "corresponding", "nonce", "+", "cipherchunk", "else", "a", "decrypted", "chunk", "." ]
train
https://github.com/Antidote1911/cryptoshop/blob/0b7ff4a6848f2733f4737606957e8042a4d6ca0b/cryptoshop/_chunk_engine.py#L39-L64
redhat-cip/dci-control-server
dci/trackers/bugzilla.py
Bugzilla.retrieve_info
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('&'): if 'id=' in item: ticket_id = item.split('=')[1] break else: return bugzilla_url = '%s://%s/%s%s' % (scheme, netloc, _URI_BASE, ticket_id) result = requests.get(bugzilla_url) self.status_code = result.status_code if result.status_code == 200: tree = ElementTree.fromstring(result.content) self.title = tree.findall("./bug/short_desc").pop().text self.issue_id = tree.findall("./bug/bug_id").pop().text self.reporter = tree.findall("./bug/reporter").pop().text self.assignee = tree.findall("./bug/assigned_to").pop().text self.status = tree.findall("./bug/bug_status").pop().text self.product = tree.findall("./bug/product").pop().text self.component = tree.findall("./bug/component").pop().text self.created_at = tree.findall("./bug/creation_ts").pop().text self.updated_at = tree.findall("./bug/delta_ts").pop().text try: self.closed_at = ( tree.findall("./bug/cf_last_closed").pop().text ) except IndexError: # cf_last_closed is present only if the issue has been closed # if not present it raises an IndexError, meaning the issue # isn't closed yet, which is a valid use case. pass
python
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('&'): if 'id=' in item: ticket_id = item.split('=')[1] break else: return bugzilla_url = '%s://%s/%s%s' % (scheme, netloc, _URI_BASE, ticket_id) result = requests.get(bugzilla_url) self.status_code = result.status_code if result.status_code == 200: tree = ElementTree.fromstring(result.content) self.title = tree.findall("./bug/short_desc").pop().text self.issue_id = tree.findall("./bug/bug_id").pop().text self.reporter = tree.findall("./bug/reporter").pop().text self.assignee = tree.findall("./bug/assigned_to").pop().text self.status = tree.findall("./bug/bug_status").pop().text self.product = tree.findall("./bug/product").pop().text self.component = tree.findall("./bug/component").pop().text self.created_at = tree.findall("./bug/creation_ts").pop().text self.updated_at = tree.findall("./bug/delta_ts").pop().text try: self.closed_at = ( tree.findall("./bug/cf_last_closed").pop().text ) except IndexError: # cf_last_closed is present only if the issue has been closed # if not present it raises an IndexError, meaning the issue # isn't closed yet, which is a valid use case. pass
[ "def", "retrieve_info", "(", "self", ")", ":", "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", "(", "'&'", ")", ":", "if", "'id='", "in", "item", ":", "ticket_id", "=", "item", ".", "split", "(", "'='", ")", "[", "1", "]", "break", "else", ":", "return", "bugzilla_url", "=", "'%s://%s/%s%s'", "%", "(", "scheme", ",", "netloc", ",", "_URI_BASE", ",", "ticket_id", ")", "result", "=", "requests", ".", "get", "(", "bugzilla_url", ")", "self", ".", "status_code", "=", "result", ".", "status_code", "if", "result", ".", "status_code", "==", "200", ":", "tree", "=", "ElementTree", ".", "fromstring", "(", "result", ".", "content", ")", "self", ".", "title", "=", "tree", ".", "findall", "(", "\"./bug/short_desc\"", ")", ".", "pop", "(", ")", ".", "text", "self", ".", "issue_id", "=", "tree", ".", "findall", "(", "\"./bug/bug_id\"", ")", ".", "pop", "(", ")", ".", "text", "self", ".", "reporter", "=", "tree", ".", "findall", "(", "\"./bug/reporter\"", ")", ".", "pop", "(", ")", ".", "text", "self", ".", "assignee", "=", "tree", ".", "findall", "(", "\"./bug/assigned_to\"", ")", ".", "pop", "(", ")", ".", "text", "self", ".", "status", "=", "tree", ".", "findall", "(", "\"./bug/bug_status\"", ")", ".", "pop", "(", ")", ".", "text", "self", ".", "product", "=", "tree", ".", "findall", "(", "\"./bug/product\"", ")", ".", "pop", "(", ")", ".", "text", "self", ".", "component", "=", "tree", ".", "findall", "(", "\"./bug/component\"", ")", ".", "pop", "(", ")", ".", "text", "self", ".", "created_at", "=", "tree", ".", "findall", "(", "\"./bug/creation_ts\"", ")", ".", "pop", "(", ")", ".", "text", "self", ".", "updated_at", "=", "tree", ".", "findall", "(", "\"./bug/delta_ts\"", ")", ".", "pop", "(", ")", ".", "text", "try", ":", "self", ".", "closed_at", "=", "(", "tree", ".", "findall", "(", "\"./bug/cf_last_closed\"", ")", ".", "pop", "(", ")", ".", "text", ")", "except", "IndexError", ":", "# cf_last_closed is present only if the issue has been closed", "# if not present it raises an IndexError, meaning the issue", "# isn't closed yet, which is a valid use case.", "pass" ]
Query Bugzilla API to retrieve the needed infos.
[ "Query", "Bugzilla", "API", "to", "retrieve", "the", "needed", "infos", "." ]
train
https://github.com/redhat-cip/dci-control-server/blob/b416cf935ec93e4fdd5741f61a21cabecf8454d2/dci/trackers/bugzilla.py#L32-L74
smarie/python-valid8
valid8/validation_lib/collections.py
minlen
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 :param strict: Boolean flag to switch between len(x) >= min_length (strict=False) and len(x) > min_length (strict=True) :return: """ if strict: def minlen_(x): if len(x) > min_length: return True else: # raise Failure('minlen: len(x) > ' + str(min_length) + ' does not hold for x=' + str(x)) raise TooShort(wrong_value=x, min_length=min_length, strict=True) else: def minlen_(x): if len(x) >= min_length: return True else: # raise Failure('minlen: len(x) >= ' + str(min_length) + ' does not hold for x=' + str(x)) raise TooShort(wrong_value=x, min_length=min_length, strict=False) minlen_.__name__ = 'length_{}greater_than_{}'.format('strictly_' if strict else '', min_length) return minlen_
python
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 :param strict: Boolean flag to switch between len(x) >= min_length (strict=False) and len(x) > min_length (strict=True) :return: """ if strict: def minlen_(x): if len(x) > min_length: return True else: # raise Failure('minlen: len(x) > ' + str(min_length) + ' does not hold for x=' + str(x)) raise TooShort(wrong_value=x, min_length=min_length, strict=True) else: def minlen_(x): if len(x) >= min_length: return True else: # raise Failure('minlen: len(x) >= ' + str(min_length) + ' does not hold for x=' + str(x)) raise TooShort(wrong_value=x, min_length=min_length, strict=False) minlen_.__name__ = 'length_{}greater_than_{}'.format('strictly_' if strict else '', min_length) return minlen_
[ "def", "minlen", "(", "min_length", ",", "strict", "=", "False", "# type: bool", ")", ":", "if", "strict", ":", "def", "minlen_", "(", "x", ")", ":", "if", "len", "(", "x", ")", ">", "min_length", ":", "return", "True", "else", ":", "# raise Failure('minlen: len(x) > ' + str(min_length) + ' does not hold for x=' + str(x))", "raise", "TooShort", "(", "wrong_value", "=", "x", ",", "min_length", "=", "min_length", ",", "strict", "=", "True", ")", "else", ":", "def", "minlen_", "(", "x", ")", ":", "if", "len", "(", "x", ")", ">=", "min_length", ":", "return", "True", "else", ":", "# raise Failure('minlen: len(x) >= ' + str(min_length) + ' does not hold for x=' + str(x))", "raise", "TooShort", "(", "wrong_value", "=", "x", ",", "min_length", "=", "min_length", ",", "strict", "=", "False", ")", "minlen_", ".", "__name__", "=", "'length_{}greater_than_{}'", ".", "format", "(", "'strictly_'", "if", "strict", "else", "''", ",", "min_length", ")", "return", "minlen_" ]
'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(x) > min_length (strict=True) :return:
[ "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", ")" ]
train
https://github.com/smarie/python-valid8/blob/5e15d1de11602933c5114eb9f73277ad91d97800/valid8/validation_lib/collections.py#L18-L47
smarie/python-valid8
valid8/validation_lib/collections.py
maxlen
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 strict: Boolean flag to switch between len(x) <= max_length (strict=False) and len(x) < max_length (strict=True) :return: """ if strict: def maxlen_(x): if len(x) < max_length: return True else: # raise Failure('maxlen: len(x) < ' + str(max_length) + ' does not hold for x=' + str(x)) raise TooLong(wrong_value=x, max_length=max_length, strict=True) else: def maxlen_(x): if len(x) <= max_length: return True else: # raise Failure('maxlen: len(x) <= ' + str(max_length) + ' does not hold for x=' + str(x)) raise TooLong(wrong_value=x, max_length=max_length, strict=False) maxlen_.__name__ = 'length_{}lesser_than_{}'.format('strictly_' if strict else '', max_length) return maxlen_
python
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 strict: Boolean flag to switch between len(x) <= max_length (strict=False) and len(x) < max_length (strict=True) :return: """ if strict: def maxlen_(x): if len(x) < max_length: return True else: # raise Failure('maxlen: len(x) < ' + str(max_length) + ' does not hold for x=' + str(x)) raise TooLong(wrong_value=x, max_length=max_length, strict=True) else: def maxlen_(x): if len(x) <= max_length: return True else: # raise Failure('maxlen: len(x) <= ' + str(max_length) + ' does not hold for x=' + str(x)) raise TooLong(wrong_value=x, max_length=max_length, strict=False) maxlen_.__name__ = 'length_{}lesser_than_{}'.format('strictly_' if strict else '', max_length) return maxlen_
[ "def", "maxlen", "(", "max_length", ",", "strict", "=", "False", "# type: bool", ")", ":", "if", "strict", ":", "def", "maxlen_", "(", "x", ")", ":", "if", "len", "(", "x", ")", "<", "max_length", ":", "return", "True", "else", ":", "# raise Failure('maxlen: len(x) < ' + str(max_length) + ' does not hold for x=' + str(x))", "raise", "TooLong", "(", "wrong_value", "=", "x", ",", "max_length", "=", "max_length", ",", "strict", "=", "True", ")", "else", ":", "def", "maxlen_", "(", "x", ")", ":", "if", "len", "(", "x", ")", "<=", "max_length", ":", "return", "True", "else", ":", "# raise Failure('maxlen: len(x) <= ' + str(max_length) + ' does not hold for x=' + str(x))", "raise", "TooLong", "(", "wrong_value", "=", "x", ",", "max_length", "=", "max_length", ",", "strict", "=", "False", ")", "maxlen_", ".", "__name__", "=", "'length_{}lesser_than_{}'", ".", "format", "(", "'strictly_'", "if", "strict", "else", "''", ",", "max_length", ")", "return", "maxlen_" ]
'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) < max_length (strict=True) :return:
[ "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", ")" ]
train
https://github.com/smarie/python-valid8/blob/5e15d1de11602933c5114eb9f73277ad91d97800/valid8/validation_lib/collections.py#L63-L91
smarie/python-valid8
valid8/validation_lib/collections.py
has_length
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 WrongLength(wrong_value=x, ref_length=ref_length) has_length_.__name__ = 'length_equals_{}'.format(ref_length) return has_length_
python
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 WrongLength(wrong_value=x, ref_length=ref_length) has_length_.__name__ = 'length_equals_{}'.format(ref_length) return has_length_
[ "def", "has_length", "(", "ref_length", ")", ":", "def", "has_length_", "(", "x", ")", ":", "if", "len", "(", "x", ")", "==", "ref_length", ":", "return", "True", "else", ":", "raise", "WrongLength", "(", "wrong_value", "=", "x", ",", "ref_length", "=", "ref_length", ")", "has_length_", ".", "__name__", "=", "'length_equals_{}'", ".", "format", "(", "ref_length", ")", "return", "has_length_" ]
'length equals' validation function generator. Returns a validation_function to check that `len(x) == ref_length` :param ref_length: :return:
[ "length", "equals", "validation", "function", "generator", ".", "Returns", "a", "validation_function", "to", "check", "that", "len", "(", "x", ")", "==", "ref_length" ]
train
https://github.com/smarie/python-valid8/blob/5e15d1de11602933c5114eb9f73277ad91d97800/valid8/validation_lib/collections.py#L106-L121
smarie/python-valid8
valid8/validation_lib/collections.py
length_between
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 (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`. :param min_len: minimum length for x :param max_len: maximum length for x :param open_left: Boolean flag to turn the left inequality to strict mode :param open_right: Boolean flag to turn the right inequality to strict mode :return: """ if open_left and open_right: def length_between_(x): if (min_len < len(x)) and (len(x) < max_len): return True else: # raise Failure('length between: {} < len(x) < {} does not hold for x={}'.format(min_len, max_len, # x)) raise LengthNotInRange(wrong_value=x, min_length=min_len, left_strict=True, max_length=max_len, right_strict=True) elif open_left: def length_between_(x): if (min_len < len(x)) and (len(x) <= max_len): return True else: # raise Failure('length between: {} < len(x) <= {} does not hold for x={}'.format(min_len, max_len, # x)) raise LengthNotInRange(wrong_value=x, min_length=min_len, left_strict=True, max_length=max_len, right_strict=False) elif open_right: def length_between_(x): if (min_len <= len(x)) and (len(x) < max_len): return True else: # raise Failure('length between: {} <= len(x) < {} does not hold for x={}'.format(min_len, max_len, # x)) raise LengthNotInRange(wrong_value=x, min_length=min_len, left_strict=False, max_length=max_len, right_strict=True) else: def length_between_(x): if (min_len <= len(x)) and (len(x) <= max_len): return True else: # raise Failure('length between: {} <= len(x) <= {} does not hold for x={}'.format(min_len, # max_len, x)) raise LengthNotInRange(wrong_value=x, min_length=min_len, left_strict=False, max_length=max_len, right_strict=False) length_between_.__name__ = 'length_between_{}_and_{}'.format(min_len, max_len) return length_between_
python
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 (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`. :param min_len: minimum length for x :param max_len: maximum length for x :param open_left: Boolean flag to turn the left inequality to strict mode :param open_right: Boolean flag to turn the right inequality to strict mode :return: """ if open_left and open_right: def length_between_(x): if (min_len < len(x)) and (len(x) < max_len): return True else: # raise Failure('length between: {} < len(x) < {} does not hold for x={}'.format(min_len, max_len, # x)) raise LengthNotInRange(wrong_value=x, min_length=min_len, left_strict=True, max_length=max_len, right_strict=True) elif open_left: def length_between_(x): if (min_len < len(x)) and (len(x) <= max_len): return True else: # raise Failure('length between: {} < len(x) <= {} does not hold for x={}'.format(min_len, max_len, # x)) raise LengthNotInRange(wrong_value=x, min_length=min_len, left_strict=True, max_length=max_len, right_strict=False) elif open_right: def length_between_(x): if (min_len <= len(x)) and (len(x) < max_len): return True else: # raise Failure('length between: {} <= len(x) < {} does not hold for x={}'.format(min_len, max_len, # x)) raise LengthNotInRange(wrong_value=x, min_length=min_len, left_strict=False, max_length=max_len, right_strict=True) else: def length_between_(x): if (min_len <= len(x)) and (len(x) <= max_len): return True else: # raise Failure('length between: {} <= len(x) <= {} does not hold for x={}'.format(min_len, # max_len, x)) raise LengthNotInRange(wrong_value=x, min_length=min_len, left_strict=False, max_length=max_len, right_strict=False) length_between_.__name__ = 'length_between_{}_and_{}'.format(min_len, max_len) return length_between_
[ "def", "length_between", "(", "min_len", ",", "max_len", ",", "open_left", "=", "False", ",", "# type: bool", "open_right", "=", "False", "# type: bool", ")", ":", "if", "open_left", "and", "open_right", ":", "def", "length_between_", "(", "x", ")", ":", "if", "(", "min_len", "<", "len", "(", "x", ")", ")", "and", "(", "len", "(", "x", ")", "<", "max_len", ")", ":", "return", "True", "else", ":", "# raise Failure('length between: {} < len(x) < {} does not hold for x={}'.format(min_len, max_len,", "# x))", "raise", "LengthNotInRange", "(", "wrong_value", "=", "x", ",", "min_length", "=", "min_len", ",", "left_strict", "=", "True", ",", "max_length", "=", "max_len", ",", "right_strict", "=", "True", ")", "elif", "open_left", ":", "def", "length_between_", "(", "x", ")", ":", "if", "(", "min_len", "<", "len", "(", "x", ")", ")", "and", "(", "len", "(", "x", ")", "<=", "max_len", ")", ":", "return", "True", "else", ":", "# raise Failure('length between: {} < len(x) <= {} does not hold for x={}'.format(min_len, max_len,", "# x))", "raise", "LengthNotInRange", "(", "wrong_value", "=", "x", ",", "min_length", "=", "min_len", ",", "left_strict", "=", "True", ",", "max_length", "=", "max_len", ",", "right_strict", "=", "False", ")", "elif", "open_right", ":", "def", "length_between_", "(", "x", ")", ":", "if", "(", "min_len", "<=", "len", "(", "x", ")", ")", "and", "(", "len", "(", "x", ")", "<", "max_len", ")", ":", "return", "True", "else", ":", "# raise Failure('length between: {} <= len(x) < {} does not hold for x={}'.format(min_len, max_len,", "# x))", "raise", "LengthNotInRange", "(", "wrong_value", "=", "x", ",", "min_length", "=", "min_len", ",", "left_strict", "=", "False", ",", "max_length", "=", "max_len", ",", "right_strict", "=", "True", ")", "else", ":", "def", "length_between_", "(", "x", ")", ":", "if", "(", "min_len", "<=", "len", "(", "x", ")", ")", "and", "(", "len", "(", "x", ")", "<=", "max_len", ")", ":", "return", "True", "else", ":", "# raise Failure('length between: {} <= len(x) <= {} does not hold for x={}'.format(min_len,", "# max_len, x))", "raise", "LengthNotInRange", "(", "wrong_value", "=", "x", ",", "min_length", "=", "min_len", ",", "left_strict", "=", "False", ",", "max_length", "=", "max_len", ",", "right_strict", "=", "False", ")", "length_between_", ".", "__name__", "=", "'length_between_{}_and_{}'", ".", "format", "(", "min_len", ",", "max_len", ")", "return", "length_between_" ]
'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`. :param min_len: minimum length for x :param max_len: maximum length for x :param open_left: Boolean flag to turn the left inequality to strict mode :param open_right: Boolean flag to turn the right inequality to strict mode :return:
[ "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", "." ]
train
https://github.com/smarie/python-valid8/blob/5e15d1de11602933c5114eb9f73277ad91d97800/valid8/validation_lib/collections.py#L134-L189
smarie/python-valid8
valid8/validation_lib/collections.py
is_in
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 allowed_values: return True else: # raise Failure('is_in: x in ' + str(allowed_values) + ' does not hold for x=' + str(x)) raise NotInAllowedValues(wrong_value=x, allowed_values=allowed_values) is_in_allowed_values.__name__ = 'is_in_{}'.format(allowed_values) return is_in_allowed_values
python
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 allowed_values: return True else: # raise Failure('is_in: x in ' + str(allowed_values) + ' does not hold for x=' + str(x)) raise NotInAllowedValues(wrong_value=x, allowed_values=allowed_values) is_in_allowed_values.__name__ = 'is_in_{}'.format(allowed_values) return is_in_allowed_values
[ "def", "is_in", "(", "allowed_values", "# type: Set", ")", ":", "def", "is_in_allowed_values", "(", "x", ")", ":", "if", "x", "in", "allowed_values", ":", "return", "True", "else", ":", "# raise Failure('is_in: x in ' + str(allowed_values) + ' does not hold for x=' + str(x))", "raise", "NotInAllowedValues", "(", "wrong_value", "=", "x", ",", "allowed_values", "=", "allowed_values", ")", "is_in_allowed_values", ".", "__name__", "=", "'is_in_{}'", ".", "format", "(", "allowed_values", ")", "return", "is_in_allowed_values" ]
'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:
[ "Values", "in", "validation_function", "generator", ".", "Returns", "a", "validation_function", "to", "check", "that", "x", "is", "in", "the", "provided", "set", "of", "allowed", "values" ]
train
https://github.com/smarie/python-valid8/blob/5e15d1de11602933c5114eb9f73277ad91d97800/valid8/validation_lib/collections.py#L200-L217
smarie/python-valid8
valid8/validation_lib/collections.py
is_subset
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 if len(missing) == 0: return True else: # raise Failure('is_subset: len(x - reference_set) == 0 does not hold for x=' + str(x) # + ' and reference_set=' + str(reference_set) + '. x contains unsupported ' # 'elements ' + str(missing)) raise NotSubset(wrong_value=x, reference_set=reference_set, unsupported=missing) is_subset_of.__name__ = 'is_subset_of_{}'.format(reference_set) return is_subset_of
python
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 if len(missing) == 0: return True else: # raise Failure('is_subset: len(x - reference_set) == 0 does not hold for x=' + str(x) # + ' and reference_set=' + str(reference_set) + '. x contains unsupported ' # 'elements ' + str(missing)) raise NotSubset(wrong_value=x, reference_set=reference_set, unsupported=missing) is_subset_of.__name__ = 'is_subset_of_{}'.format(reference_set) return is_subset_of
[ "def", "is_subset", "(", "reference_set", "# type: Set", ")", ":", "def", "is_subset_of", "(", "x", ")", ":", "missing", "=", "x", "-", "reference_set", "if", "len", "(", "missing", ")", "==", "0", ":", "return", "True", "else", ":", "# raise Failure('is_subset: len(x - reference_set) == 0 does not hold for x=' + str(x)", "# + ' and reference_set=' + str(reference_set) + '. x contains unsupported '", "# 'elements ' + str(missing))", "raise", "NotSubset", "(", "wrong_value", "=", "x", ",", "reference_set", "=", "reference_set", ",", "unsupported", "=", "missing", ")", "is_subset_of", ".", "__name__", "=", "'is_subset_of_{}'", ".", "format", "(", "reference_set", ")", "return", "is_subset_of" ]
'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:
[ "Is", "subset", "validation_function", "generator", ".", "Returns", "a", "validation_function", "to", "check", "that", "x", "is", "a", "subset", "of", "reference_set" ]
train
https://github.com/smarie/python-valid8/blob/5e15d1de11602933c5114eb9f73277ad91d97800/valid8/validation_lib/collections.py#L228-L248
smarie/python-valid8
valid8/validation_lib/collections.py
contains
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: raise DoesNotContainValue(wrong_value=x, ref_value=ref_value) contains_ref_value.__name__ = 'contains_{}'.format(ref_value) return contains_ref_value
python
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: raise DoesNotContainValue(wrong_value=x, ref_value=ref_value) contains_ref_value.__name__ = 'contains_{}'.format(ref_value) return contains_ref_value
[ "def", "contains", "(", "ref_value", ")", ":", "def", "contains_ref_value", "(", "x", ")", ":", "if", "ref_value", "in", "x", ":", "return", "True", "else", ":", "raise", "DoesNotContainValue", "(", "wrong_value", "=", "x", ",", "ref_value", "=", "ref_value", ")", "contains_ref_value", ".", "__name__", "=", "'contains_{}'", ".", "format", "(", "ref_value", ")", "return", "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:
[ "Contains", "validation_function", "generator", ".", "Returns", "a", "validation_function", "to", "check", "that", "ref_value", "in", "x" ]
train
https://github.com/smarie/python-valid8/blob/5e15d1de11602933c5114eb9f73277ad91d97800/valid8/validation_lib/collections.py#L259-L274
smarie/python-valid8
valid8/validation_lib/collections.py
is_superset
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_set - x if len(missing) == 0: return True else: # raise Failure('is_superset: len(reference_set - x) == 0 does not hold for x=' + str(x) # + ' and reference_set=' + str(reference_set) + '. x does not contain required ' # 'elements ' + str(missing)) raise NotSuperset(wrong_value=x, reference_set=reference_set, missing=missing) is_superset_of.__name__ = 'is_superset_of_{}'.format(reference_set) return is_superset_of
python
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_set - x if len(missing) == 0: return True else: # raise Failure('is_superset: len(reference_set - x) == 0 does not hold for x=' + str(x) # + ' and reference_set=' + str(reference_set) + '. x does not contain required ' # 'elements ' + str(missing)) raise NotSuperset(wrong_value=x, reference_set=reference_set, missing=missing) is_superset_of.__name__ = 'is_superset_of_{}'.format(reference_set) return is_superset_of
[ "def", "is_superset", "(", "reference_set", "# type: Set", ")", ":", "def", "is_superset_of", "(", "x", ")", ":", "missing", "=", "reference_set", "-", "x", "if", "len", "(", "missing", ")", "==", "0", ":", "return", "True", "else", ":", "# raise Failure('is_superset: len(reference_set - x) == 0 does not hold for x=' + str(x)", "# + ' and reference_set=' + str(reference_set) + '. x does not contain required '", "# 'elements ' + str(missing))", "raise", "NotSuperset", "(", "wrong_value", "=", "x", ",", "reference_set", "=", "reference_set", ",", "missing", "=", "missing", ")", "is_superset_of", ".", "__name__", "=", "'is_superset_of_{}'", ".", "format", "(", "reference_set", ")", "return", "is_superset_of" ]
'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:
[ "Is", "superset", "validation_function", "generator", ".", "Returns", "a", "validation_function", "to", "check", "that", "x", "is", "a", "superset", "of", "reference_set" ]
train
https://github.com/smarie/python-valid8/blob/5e15d1de11602933c5114eb9f73277ad91d97800/valid8/validation_lib/collections.py#L285-L305
smarie/python-valid8
valid8/validation_lib/collections.py
on_all_
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 want to apply DIFFERENT validation_functions for each element in the input, you should rather use on_each_. :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 implicit `and_` (such as the main list). Tuples indicate an implicit `_failure_raiser`. [mini_lambda](https://smarie.github.io/python-mini-lambda/) expressions can be used instead of callables, they will be transformed to functions automatically. :return: """ # create the validation functions validation_function_func = _process_validation_function_s(list(validation_func)) def on_all_val(x): # validate all elements in x in turn for idx, x_elt in enumerate(x): try: res = validation_function_func(x_elt) except Exception as e: raise InvalidItemInSequence(wrong_value=x_elt, wrapped_func=validation_function_func, validation_outcome=e) if not result_is_success(res): # one element of x was not valid > raise # raise Failure('on_all_(' + str(validation_func) + '): failed validation for input ' # 'element [' + str(idx) + ']: ' + str(x_elt)) raise InvalidItemInSequence(wrong_value=x_elt, wrapped_func=validation_function_func, validation_outcome=res) return True on_all_val.__name__ = 'apply_<{}>_on_all_elts'.format(get_callable_name(validation_function_func)) return on_all_val
python
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 want to apply DIFFERENT validation_functions for each element in the input, you should rather use on_each_. :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 implicit `and_` (such as the main list). Tuples indicate an implicit `_failure_raiser`. [mini_lambda](https://smarie.github.io/python-mini-lambda/) expressions can be used instead of callables, they will be transformed to functions automatically. :return: """ # create the validation functions validation_function_func = _process_validation_function_s(list(validation_func)) def on_all_val(x): # validate all elements in x in turn for idx, x_elt in enumerate(x): try: res = validation_function_func(x_elt) except Exception as e: raise InvalidItemInSequence(wrong_value=x_elt, wrapped_func=validation_function_func, validation_outcome=e) if not result_is_success(res): # one element of x was not valid > raise # raise Failure('on_all_(' + str(validation_func) + '): failed validation for input ' # 'element [' + str(idx) + ']: ' + str(x_elt)) raise InvalidItemInSequence(wrong_value=x_elt, wrapped_func=validation_function_func, validation_outcome=res) return True on_all_val.__name__ = 'apply_<{}>_on_all_elts'.format(get_callable_name(validation_function_func)) return on_all_val
[ "def", "on_all_", "(", "*", "validation_func", ")", ":", "# create the validation functions", "validation_function_func", "=", "_process_validation_function_s", "(", "list", "(", "validation_func", ")", ")", "def", "on_all_val", "(", "x", ")", ":", "# validate all elements in x in turn", "for", "idx", ",", "x_elt", "in", "enumerate", "(", "x", ")", ":", "try", ":", "res", "=", "validation_function_func", "(", "x_elt", ")", "except", "Exception", "as", "e", ":", "raise", "InvalidItemInSequence", "(", "wrong_value", "=", "x_elt", ",", "wrapped_func", "=", "validation_function_func", ",", "validation_outcome", "=", "e", ")", "if", "not", "result_is_success", "(", "res", ")", ":", "# one element of x was not valid > raise", "# raise Failure('on_all_(' + str(validation_func) + '): failed validation for input '", "# 'element [' + str(idx) + ']: ' + str(x_elt))", "raise", "InvalidItemInSequence", "(", "wrong_value", "=", "x_elt", ",", "wrapped_func", "=", "validation_function_func", ",", "validation_outcome", "=", "res", ")", "return", "True", "on_all_val", ".", "__name__", "=", "'apply_<{}>_on_all_elts'", ".", "format", "(", "get_callable_name", "(", "validation_function_func", ")", ")", "return", "on_all_val" ]
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_functions for each element in the input, you should rather use on_each_. :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 implicit `and_` (such as the main list). Tuples indicate an implicit `_failure_raiser`. [mini_lambda](https://smarie.github.io/python-mini-lambda/) expressions can be used instead of callables, they will be transformed to functions automatically. :return:
[ "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_", "." ]
train
https://github.com/smarie/python-valid8/blob/5e15d1de11602933c5114eb9f73277ad91d97800/valid8/validation_lib/collections.py#L314-L349
smarie/python-valid8
valid8/validation_lib/collections.py
on_each_
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 convenience, this will be replaced with an 'and_' operator if the list has more than one element. Note that if you want to apply the SAME validation_functions to all elements in the input, you should rather use on_all_. :param validation_functions_collection: a sequence of (base validation function or list of base validation functions to use). A base validation function may be 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 implicit `and_` (such as the main list). Tuples indicate an implicit `_failure_raiser`. [mini_lambda](https://smarie.github.io/python-mini-lambda/) expressions can be used instead of callables, they will be transformed to functions automatically. :return: """ # create a tuple of validation functions. validation_function_funcs = tuple(_process_validation_function_s(validation_func) for validation_func in validation_functions_collection) # generate a validation function based on the tuple of validation_functions lists def on_each_val(x # type: Tuple ): if len(validation_function_funcs) != len(x): raise Failure('on_each_: x does not have the same number of elements than validation_functions_collection.') else: # apply each validation_function on the input with the same position in the collection idx = -1 for elt, validation_function_func in zip(x, validation_function_funcs): idx += 1 try: res = validation_function_func(elt) except Exception as e: raise InvalidItemInSequence(wrong_value=elt, wrapped_func=validation_function_func, validation_outcome=e) if not result_is_success(res): # one validation_function was unhappy > raise # raise Failure('on_each_(' + str(validation_functions_collection) + '): _validation_function [' + str(idx) # + '] (' + str(validation_functions_collection[idx]) + ') failed validation for ' # 'input ' + str(x[idx])) raise InvalidItemInSequence(wrong_value=elt, wrapped_func=validation_function_func, validation_outcome=res) return True on_each_val.__name__ = 'map_<{}>_on_elts' \ ''.format('(' + ', '.join([get_callable_name(f) for f in validation_function_funcs]) + ')') return on_each_val
python
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 convenience, this will be replaced with an 'and_' operator if the list has more than one element. Note that if you want to apply the SAME validation_functions to all elements in the input, you should rather use on_all_. :param validation_functions_collection: a sequence of (base validation function or list of base validation functions to use). A base validation function may be 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 implicit `and_` (such as the main list). Tuples indicate an implicit `_failure_raiser`. [mini_lambda](https://smarie.github.io/python-mini-lambda/) expressions can be used instead of callables, they will be transformed to functions automatically. :return: """ # create a tuple of validation functions. validation_function_funcs = tuple(_process_validation_function_s(validation_func) for validation_func in validation_functions_collection) # generate a validation function based on the tuple of validation_functions lists def on_each_val(x # type: Tuple ): if len(validation_function_funcs) != len(x): raise Failure('on_each_: x does not have the same number of elements than validation_functions_collection.') else: # apply each validation_function on the input with the same position in the collection idx = -1 for elt, validation_function_func in zip(x, validation_function_funcs): idx += 1 try: res = validation_function_func(elt) except Exception as e: raise InvalidItemInSequence(wrong_value=elt, wrapped_func=validation_function_func, validation_outcome=e) if not result_is_success(res): # one validation_function was unhappy > raise # raise Failure('on_each_(' + str(validation_functions_collection) + '): _validation_function [' + str(idx) # + '] (' + str(validation_functions_collection[idx]) + ') failed validation for ' # 'input ' + str(x[idx])) raise InvalidItemInSequence(wrong_value=elt, wrapped_func=validation_function_func, validation_outcome=res) return True on_each_val.__name__ = 'map_<{}>_on_elts' \ ''.format('(' + ', '.join([get_callable_name(f) for f in validation_function_funcs]) + ')') return on_each_val
[ "def", "on_each_", "(", "*", "validation_functions_collection", ")", ":", "# create a tuple of validation functions.", "validation_function_funcs", "=", "tuple", "(", "_process_validation_function_s", "(", "validation_func", ")", "for", "validation_func", "in", "validation_functions_collection", ")", "# generate a validation function based on the tuple of validation_functions lists", "def", "on_each_val", "(", "x", "# type: Tuple", ")", ":", "if", "len", "(", "validation_function_funcs", ")", "!=", "len", "(", "x", ")", ":", "raise", "Failure", "(", "'on_each_: x does not have the same number of elements than validation_functions_collection.'", ")", "else", ":", "# apply each validation_function on the input with the same position in the collection", "idx", "=", "-", "1", "for", "elt", ",", "validation_function_func", "in", "zip", "(", "x", ",", "validation_function_funcs", ")", ":", "idx", "+=", "1", "try", ":", "res", "=", "validation_function_func", "(", "elt", ")", "except", "Exception", "as", "e", ":", "raise", "InvalidItemInSequence", "(", "wrong_value", "=", "elt", ",", "wrapped_func", "=", "validation_function_func", ",", "validation_outcome", "=", "e", ")", "if", "not", "result_is_success", "(", "res", ")", ":", "# one validation_function was unhappy > raise", "# raise Failure('on_each_(' + str(validation_functions_collection) + '): _validation_function [' + str(idx)", "# + '] (' + str(validation_functions_collection[idx]) + ') failed validation for '", "# 'input ' + str(x[idx]))", "raise", "InvalidItemInSequence", "(", "wrong_value", "=", "elt", ",", "wrapped_func", "=", "validation_function_func", ",", "validation_outcome", "=", "res", ")", "return", "True", "on_each_val", ".", "__name__", "=", "'map_<{}>_on_elts'", "''", ".", "format", "(", "'('", "+", "', '", ".", "join", "(", "[", "get_callable_name", "(", "f", ")", "for", "f", "in", "validation_function_funcs", "]", ")", "+", "')'", ")", "return", "on_each_val" ]
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 the list has more than one element. Note that if you want to apply the SAME validation_functions to all elements in the input, you should rather use on_all_. :param validation_functions_collection: a sequence of (base validation function or list of base validation functions to use). A base validation function may be 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 implicit `and_` (such as the main list). Tuples indicate an implicit `_failure_raiser`. [mini_lambda](https://smarie.github.io/python-mini-lambda/) expressions can be used instead of callables, they will be transformed to functions automatically. :return:
[ "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", "the", "list", "has", "more", "than", "one", "element", "." ]
train
https://github.com/smarie/python-valid8/blob/5e15d1de11602933c5114eb9f73277ad91d97800/valid8/validation_lib/collections.py#L353-L404
redhat-cip/dci-control-server
dci/api/v1/jobs_events.py
get_jobs_events_from_sequence
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.JOBS_EVENTS.join(models.JOBS, models.JOBS.c.id == models.JOBS_EVENTS.c.job_id)). \ where(_TABLE.c.id >= sequence) sort_list = v1_utils.sort_query(args['sort'], _JOBS_EVENTS_COLUMNS, default='created_at') query = v1_utils.add_sort_to_query(query, sort_list) if args.get('limit', None): query = query.limit(args.get('limit')) if args.get('offset', None): query = query.offset(args.get('offset')) rows = flask.g.db_conn.execute(query).fetchall() query_nb_rows = sql.select([func.count(models.JOBS_EVENTS.c.id)]) nb_rows = flask.g.db_conn.execute(query_nb_rows).scalar() return json.jsonify({'jobs_events': rows, '_meta': {'count': nb_rows}})
python
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.JOBS_EVENTS.join(models.JOBS, models.JOBS.c.id == models.JOBS_EVENTS.c.job_id)). \ where(_TABLE.c.id >= sequence) sort_list = v1_utils.sort_query(args['sort'], _JOBS_EVENTS_COLUMNS, default='created_at') query = v1_utils.add_sort_to_query(query, sort_list) if args.get('limit', None): query = query.limit(args.get('limit')) if args.get('offset', None): query = query.offset(args.get('offset')) rows = flask.g.db_conn.execute(query).fetchall() query_nb_rows = sql.select([func.count(models.JOBS_EVENTS.c.id)]) nb_rows = flask.g.db_conn.execute(query_nb_rows).scalar() return json.jsonify({'jobs_events': rows, '_meta': {'count': nb_rows}})
[ "def", "get_jobs_events_from_sequence", "(", "user", ",", "sequence", ")", ":", "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", ".", "JOBS_EVENTS", ".", "join", "(", "models", ".", "JOBS", ",", "models", ".", "JOBS", ".", "c", ".", "id", "==", "models", ".", "JOBS_EVENTS", ".", "c", ".", "job_id", ")", ")", ".", "where", "(", "_TABLE", ".", "c", ".", "id", ">=", "sequence", ")", "sort_list", "=", "v1_utils", ".", "sort_query", "(", "args", "[", "'sort'", "]", ",", "_JOBS_EVENTS_COLUMNS", ",", "default", "=", "'created_at'", ")", "query", "=", "v1_utils", ".", "add_sort_to_query", "(", "query", ",", "sort_list", ")", "if", "args", ".", "get", "(", "'limit'", ",", "None", ")", ":", "query", "=", "query", ".", "limit", "(", "args", ".", "get", "(", "'limit'", ")", ")", "if", "args", ".", "get", "(", "'offset'", ",", "None", ")", ":", "query", "=", "query", ".", "offset", "(", "args", ".", "get", "(", "'offset'", ")", ")", "rows", "=", "flask", ".", "g", ".", "db_conn", ".", "execute", "(", "query", ")", ".", "fetchall", "(", ")", "query_nb_rows", "=", "sql", ".", "select", "(", "[", "func", ".", "count", "(", "models", ".", "JOBS_EVENTS", ".", "c", ".", "id", ")", "]", ")", "nb_rows", "=", "flask", ".", "g", ".", "db_conn", ".", "execute", "(", "query_nb_rows", ")", ".", "scalar", "(", ")", "return", "json", ".", "jsonify", "(", "{", "'jobs_events'", ":", "rows", ",", "'_meta'", ":", "{", "'count'", ":", "nb_rows", "}", "}", ")" ]
Get all the jobs events from a given sequence number.
[ "Get", "all", "the", "jobs", "events", "from", "a", "given", "sequence", "number", "." ]
train
https://github.com/redhat-cip/dci-control-server/blob/b416cf935ec93e4fdd5741f61a21cabecf8454d2/dci/api/v1/jobs_events.py#L37-L63
mediawiki-utilities/python-mwxml
mwxml/iteration/dump.py
Dump.from_file
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 == "mediawiki" return cls.from_element(element)
python
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 == "mediawiki" return cls.from_element(element)
[ "def", "from_file", "(", "cls", ",", "f", ")", ":", "element", "=", "ElementIterator", ".", "from_file", "(", "f", ")", "assert", "element", ".", "tag", "==", "\"mediawiki\"", "return", "cls", ".", "from_element", "(", "element", ")" ]
Constructs a :class:`~mwxml.iteration.dump.Dump` from a `file` pointer. :Parameters: f : `file` A plain text file pointer containing XML to process
[ "Constructs", "a", ":", "class", ":", "~mwxml", ".", "iteration", ".", "dump", ".", "Dump", "from", "a", "file", "pointer", "." ]
train
https://github.com/mediawiki-utilities/python-mwxml/blob/6a8c18be99cd0bcee9c496e607f08bf4dfe5b510/mwxml/iteration/dump.py#L136-L146
mediawiki-utilities/python-mwxml
mwxml/iteration/dump.py
Dump.from_page_xml
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 = """ <mediawiki xmlns="http://www.mediawiki.org/xml/export-0.5/" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://www.mediawiki.org/xml/export-0.5/ http://www.mediawiki.org/xml/export-0.5.xsd" version="0.5" xml:lang="en"> <siteinfo> </siteinfo> """ footer = "</mediawiki>" return cls.from_file(mwtypes.files.concat(header, page_xml, footer))
python
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 = """ <mediawiki xmlns="http://www.mediawiki.org/xml/export-0.5/" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://www.mediawiki.org/xml/export-0.5/ http://www.mediawiki.org/xml/export-0.5.xsd" version="0.5" xml:lang="en"> <siteinfo> </siteinfo> """ footer = "</mediawiki>" return cls.from_file(mwtypes.files.concat(header, page_xml, footer))
[ "def", "from_page_xml", "(", "cls", ",", "page_xml", ")", ":", "header", "=", "\"\"\"\n <mediawiki xmlns=\"http://www.mediawiki.org/xml/export-0.5/\"\n xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\"\n xsi:schemaLocation=\"http://www.mediawiki.org/xml/export-0.5/\n http://www.mediawiki.org/xml/export-0.5.xsd\" version=\"0.5\"\n xml:lang=\"en\">\n <siteinfo>\n </siteinfo>\n \"\"\"", "footer", "=", "\"</mediawiki>\"", "return", "cls", ".", "from_file", "(", "mwtypes", ".", "files", ".", "concat", "(", "header", ",", "page_xml", ",", "footer", ")", ")" ]
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
[ "Constructs", "a", ":", "class", ":", "~mwxml", ".", "iteration", ".", "dump", ".", "Dump", "from", "a", "<page", ">", "block", "." ]
train
https://github.com/mediawiki-utilities/python-mwxml/blob/6a8c18be99cd0bcee9c496e607f08bf4dfe5b510/mwxml/iteration/dump.py#L149-L170
Antidote1911/cryptoshop
cryptoshop/_derivation_engine.py
calc_derivation
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_raw((str.encode(passphrase)), salt=salt, hash_len=32, time_cost=__argon2_timing_cost__, memory_cost=__argon2_memory_cost__, parallelism=__argon2_parallelism__, type=argon2.low_level.Type.I) return argonhash
python
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_raw((str.encode(passphrase)), salt=salt, hash_len=32, time_cost=__argon2_timing_cost__, memory_cost=__argon2_memory_cost__, parallelism=__argon2_parallelism__, type=argon2.low_level.Type.I) return argonhash
[ "def", "calc_derivation", "(", "passphrase", ",", "salt", ")", ":", "argonhash", "=", "argon2", ".", "low_level", ".", "hash_secret_raw", "(", "(", "str", ".", "encode", "(", "passphrase", ")", ")", ",", "salt", "=", "salt", ",", "hash_len", "=", "32", ",", "time_cost", "=", "__argon2_timing_cost__", ",", "memory_cost", "=", "__argon2_memory_cost__", ",", "parallelism", "=", "__argon2_parallelism__", ",", "type", "=", "argon2", ".", "low_level", ".", "Type", ".", "I", ")", "return", "argonhash" ]
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.
[ "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", "." ]
train
https://github.com/Antidote1911/cryptoshop/blob/0b7ff4a6848f2733f4737606957e8042a4d6ca0b/cryptoshop/_derivation_engine.py#L29-L39
jmurty/xml4h
xml4h/impls/xml_dom_minidom.py
XmlDomImplAdapter.get_node_text
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''.join(text_children) else: return None
python
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''.join(text_children) else: return None
[ "def", "get_node_text", "(", "self", ",", "node", ")", ":", "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''", ".", "join", "(", "text_children", ")", "else", ":", "return", "None" ]
Return contatenated value of all text node children of this element
[ "Return", "contatenated", "value", "of", "all", "text", "node", "children", "of", "this", "element" ]
train
https://github.com/jmurty/xml4h/blob/adbb45e27a01a869a505aee7bc16bad2f517b511/xml4h/impls/xml_dom_minidom.py#L119-L128
jmurty/xml4h
xml4h/impls/xml_dom_minidom.py
XmlDomImplAdapter.set_node_text
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: self.remove_node_child(node, child, True) if text is not None: text_node = self.new_impl_text(text) self.add_node_child(node, text_node)
python
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: self.remove_node_child(node, child, True) if text is not None: text_node = self.new_impl_text(text) self.add_node_child(node, text_node)
[ "def", "set_node_text", "(", "self", ",", "node", ",", "text", ")", ":", "# Remove any existing Text node children", "for", "child", "in", "self", ".", "get_node_children", "(", "node", ")", ":", "if", "child", ".", "nodeType", "==", "xml", ".", "dom", ".", "Node", ".", "TEXT_NODE", ":", "self", ".", "remove_node_child", "(", "node", ",", "child", ",", "True", ")", "if", "text", "is", "not", "None", ":", "text_node", "=", "self", ".", "new_impl_text", "(", "text", ")", "self", ".", "add_node_child", "(", "node", ",", "text_node", ")" ]
Set text value as sole Text child node of element; any existing Text nodes are removed
[ "Set", "text", "value", "as", "sole", "Text", "child", "node", "of", "element", ";", "any", "existing", "Text", "nodes", "are", "removed" ]
train
https://github.com/jmurty/xml4h/blob/adbb45e27a01a869a505aee7bc16bad2f517b511/xml4h/impls/xml_dom_minidom.py#L130-L141
inveniosoftware/invenio-assets
invenio_assets/glob.py
GlobBundle._get_contents
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())
python
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())
[ "def", "_get_contents", "(", "self", ")", ":", "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.
[ "Create", "strings", "from", "glob", "strings", "." ]
train
https://github.com/inveniosoftware/invenio-assets/blob/836cc75ebe0c179f0d72456bd8b784cdc18394a6/invenio_assets/glob.py#L31-L37
smarie/python-valid8
valid8/_typing_inspect.py
is_generic_type
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(Union[int, T]) == False is_generic_type(ClassVar[List[int]]) == False is_generic_type(Callable[..., T]) == False is_generic_type(Generic) == True is_generic_type(Generic[T]) == True is_generic_type(Iterable[int]) == True is_generic_type(Mapping) == True is_generic_type(MutableMapping[T, List[int]]) == True is_generic_type(Sequence[Union[str, bytes]]) == True """ if NEW_TYPING: return (isinstance(tp, type) and issubclass(tp, Generic) or isinstance(tp, _GenericAlias) and tp.__origin__ not in (Union, tuple, ClassVar, collections.abc.Callable)) # SMA: refering to is_callable_type and is_tuple_type to avoid duplicate code return isinstance(tp, GenericMeta) and not is_callable_type(tp) and not is_tuple_type(tp)
python
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(Union[int, T]) == False is_generic_type(ClassVar[List[int]]) == False is_generic_type(Callable[..., T]) == False is_generic_type(Generic) == True is_generic_type(Generic[T]) == True is_generic_type(Iterable[int]) == True is_generic_type(Mapping) == True is_generic_type(MutableMapping[T, List[int]]) == True is_generic_type(Sequence[Union[str, bytes]]) == True """ if NEW_TYPING: return (isinstance(tp, type) and issubclass(tp, Generic) or isinstance(tp, _GenericAlias) and tp.__origin__ not in (Union, tuple, ClassVar, collections.abc.Callable)) # SMA: refering to is_callable_type and is_tuple_type to avoid duplicate code return isinstance(tp, GenericMeta) and not is_callable_type(tp) and not is_tuple_type(tp)
[ "def", "is_generic_type", "(", "tp", ")", ":", "if", "NEW_TYPING", ":", "return", "(", "isinstance", "(", "tp", ",", "type", ")", "and", "issubclass", "(", "tp", ",", "Generic", ")", "or", "isinstance", "(", "tp", ",", "_GenericAlias", ")", "and", "tp", ".", "__origin__", "not", "in", "(", "Union", ",", "tuple", ",", "ClassVar", ",", "collections", ".", "abc", ".", "Callable", ")", ")", "# SMA: refering to is_callable_type and is_tuple_type to avoid duplicate code", "return", "isinstance", "(", "tp", ",", "GenericMeta", ")", "and", "not", "is_callable_type", "(", "tp", ")", "and", "not", "is_tuple_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(Union[int, T]) == False is_generic_type(ClassVar[List[int]]) == False is_generic_type(Callable[..., T]) == False is_generic_type(Generic) == True is_generic_type(Generic[T]) == True is_generic_type(Iterable[int]) == True is_generic_type(Mapping) == True is_generic_type(MutableMapping[T, List[int]]) == True is_generic_type(Sequence[Union[str, bytes]]) == True
[ "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", "::" ]
train
https://github.com/smarie/python-valid8/blob/5e15d1de11602933c5114eb9f73277ad91d97800/valid8/_typing_inspect.py#L39-L62
smarie/python-valid8
valid8/_typing_inspect.py
is_union_type
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 isinstance(tp, _GenericAlias) and tp.__origin__ is Union) try: from typing import _Union return type(tp) is _Union except ImportError: # SMA: support for very old typing module <=3.5.3 return type(tp) is Union or type(tp) is type(Union)
python
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 isinstance(tp, _GenericAlias) and tp.__origin__ is Union) try: from typing import _Union return type(tp) is _Union except ImportError: # SMA: support for very old typing module <=3.5.3 return type(tp) is Union or type(tp) is type(Union)
[ "def", "is_union_type", "(", "tp", ")", ":", "if", "NEW_TYPING", ":", "return", "(", "tp", "is", "Union", "or", "isinstance", "(", "tp", ",", "_GenericAlias", ")", "and", "tp", ".", "__origin__", "is", "Union", ")", "try", ":", "from", "typing", "import", "_Union", "return", "type", "(", "tp", ")", "is", "_Union", "except", "ImportError", ":", "# SMA: support for very old typing module <=3.5.3", "return", "type", "(", "tp", ")", "is", "Union", "or", "type", "(", "tp", ")", "is", "type", "(", "Union", ")" ]
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
[ "Test", "if", "the", "type", "is", "a", "union", "type", ".", "Examples", "::" ]
train
https://github.com/smarie/python-valid8/blob/5e15d1de11602933c5114eb9f73277ad91d97800/valid8/_typing_inspect.py#L136-L152
smarie/python-valid8
valid8/_typing_inspect.py
is_classvar
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 isinstance(tp, _GenericAlias) and tp.__origin__ is ClassVar) try: from typing import _ClassVar return type(tp) is _ClassVar except: # SMA: support for very old typing module <=3.5.3 return False
python
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 isinstance(tp, _GenericAlias) and tp.__origin__ is ClassVar) try: from typing import _ClassVar return type(tp) is _ClassVar except: # SMA: support for very old typing module <=3.5.3 return False
[ "def", "is_classvar", "(", "tp", ")", ":", "if", "NEW_TYPING", ":", "return", "(", "tp", "is", "ClassVar", "or", "isinstance", "(", "tp", ",", "_GenericAlias", ")", "and", "tp", ".", "__origin__", "is", "ClassVar", ")", "try", ":", "from", "typing", "import", "_ClassVar", "return", "type", "(", "tp", ")", "is", "_ClassVar", "except", ":", "# SMA: support for very old typing module <=3.5.3", "return", "False" ]
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
[ "Test", "if", "the", "type", "represents", "a", "class", "variable", ".", "Examples", "::" ]
train
https://github.com/smarie/python-valid8/blob/5e15d1de11602933c5114eb9f73277ad91d97800/valid8/_typing_inspect.py#L166-L182
jmurty/xml4h
xml4h/__init__.py
parse
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 given that contains a ``<`` character it is treated as literal XML data, otherwise a string value is treated as a file path. :type to_parse: a file-like object or string :param bool ignore_whitespace_text_nodes: if ``True`` pure whitespace nodes are stripped from the parsed document, since these are usually noise introduced by XML docs serialized to be human-friendly. :param adapter: the *xml4h* implementation adapter class used to parse the document and to interact with the resulting nodes. If None, :attr:`best_adapter` will be used. :type adapter: adapter class or None :return: an :class:`xml4h.nodes.Document` node representing the parsed document. Delegates to an adapter's :meth:`~xml4h.impls.interface.parse_string` or :meth:`~xml4h.impls.interface.parse_file` implementation. """ if adapter is None: adapter = best_adapter if isinstance(to_parse, basestring) and '<' in to_parse: return adapter.parse_string(to_parse, ignore_whitespace_text_nodes) else: return adapter.parse_file(to_parse, ignore_whitespace_text_nodes)
python
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 given that contains a ``<`` character it is treated as literal XML data, otherwise a string value is treated as a file path. :type to_parse: a file-like object or string :param bool ignore_whitespace_text_nodes: if ``True`` pure whitespace nodes are stripped from the parsed document, since these are usually noise introduced by XML docs serialized to be human-friendly. :param adapter: the *xml4h* implementation adapter class used to parse the document and to interact with the resulting nodes. If None, :attr:`best_adapter` will be used. :type adapter: adapter class or None :return: an :class:`xml4h.nodes.Document` node representing the parsed document. Delegates to an adapter's :meth:`~xml4h.impls.interface.parse_string` or :meth:`~xml4h.impls.interface.parse_file` implementation. """ if adapter is None: adapter = best_adapter if isinstance(to_parse, basestring) and '<' in to_parse: return adapter.parse_string(to_parse, ignore_whitespace_text_nodes) else: return adapter.parse_file(to_parse, ignore_whitespace_text_nodes)
[ "def", "parse", "(", "to_parse", ",", "ignore_whitespace_text_nodes", "=", "True", ",", "adapter", "=", "None", ")", ":", "if", "adapter", "is", "None", ":", "adapter", "=", "best_adapter", "if", "isinstance", "(", "to_parse", ",", "basestring", ")", "and", "'<'", "in", "to_parse", ":", "return", "adapter", ".", "parse_string", "(", "to_parse", ",", "ignore_whitespace_text_nodes", ")", "else", ":", "return", "adapter", ".", "parse_file", "(", "to_parse", ",", "ignore_whitespace_text_nodes", ")" ]
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, otherwise a string value is treated as a file path. :type to_parse: a file-like object or string :param bool ignore_whitespace_text_nodes: if ``True`` pure whitespace nodes are stripped from the parsed document, since these are usually noise introduced by XML docs serialized to be human-friendly. :param adapter: the *xml4h* implementation adapter class used to parse the document and to interact with the resulting nodes. If None, :attr:`best_adapter` will be used. :type adapter: adapter class or None :return: an :class:`xml4h.nodes.Document` node representing the parsed document. Delegates to an adapter's :meth:`~xml4h.impls.interface.parse_string` or :meth:`~xml4h.impls.interface.parse_file` implementation.
[ "Parse", "an", "XML", "document", "into", "an", "*", "xml4h", "*", "-", "wrapped", "DOM", "representation", "using", "an", "underlying", "XML", "library", "implementation", "." ]
train
https://github.com/jmurty/xml4h/blob/adbb45e27a01a869a505aee7bc16bad2f517b511/xml4h/__init__.py#L41-L70
jmurty/xml4h
xml4h/__init__.py
build
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 a new XML document, or an :class:`~xml4h.nodes.Element` node in an existing document. :type tagname_or_element: string or :class:`~xml4h.nodes.Element` node :param ns_uri: a namespace URI to apply to the new root node. This argument has no effect this method is acting on an element. :type ns_uri: string or None :param adapter: the *xml4h* implementation adapter class used to interact with the document DOM nodes. If None, :attr:`best_adapter` will be used. :type adapter: adapter class or None :return: a :class:`~xml4h.builder.Builder` instance that represents an :class:`~xml4h.nodes.Element` node in an XML DOM. """ if adapter is None: adapter = best_adapter if isinstance(tagname_or_element, basestring): doc = adapter.create_document( tagname_or_element, ns_uri=ns_uri) element = doc.root elif isinstance(tagname_or_element, xml4h.nodes.Element): element = tagname_or_element else: raise xml4h.exceptions.IncorrectArgumentTypeException( tagname_or_element, [basestring, xml4h.nodes.Element]) return Builder(element)
python
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 a new XML document, or an :class:`~xml4h.nodes.Element` node in an existing document. :type tagname_or_element: string or :class:`~xml4h.nodes.Element` node :param ns_uri: a namespace URI to apply to the new root node. This argument has no effect this method is acting on an element. :type ns_uri: string or None :param adapter: the *xml4h* implementation adapter class used to interact with the document DOM nodes. If None, :attr:`best_adapter` will be used. :type adapter: adapter class or None :return: a :class:`~xml4h.builder.Builder` instance that represents an :class:`~xml4h.nodes.Element` node in an XML DOM. """ if adapter is None: adapter = best_adapter if isinstance(tagname_or_element, basestring): doc = adapter.create_document( tagname_or_element, ns_uri=ns_uri) element = doc.root elif isinstance(tagname_or_element, xml4h.nodes.Element): element = tagname_or_element else: raise xml4h.exceptions.IncorrectArgumentTypeException( tagname_or_element, [basestring, xml4h.nodes.Element]) return Builder(element)
[ "def", "build", "(", "tagname_or_element", ",", "ns_uri", "=", "None", ",", "adapter", "=", "None", ")", ":", "if", "adapter", "is", "None", ":", "adapter", "=", "best_adapter", "if", "isinstance", "(", "tagname_or_element", ",", "basestring", ")", ":", "doc", "=", "adapter", ".", "create_document", "(", "tagname_or_element", ",", "ns_uri", "=", "ns_uri", ")", "element", "=", "doc", ".", "root", "elif", "isinstance", "(", "tagname_or_element", ",", "xml4h", ".", "nodes", ".", "Element", ")", ":", "element", "=", "tagname_or_element", "else", ":", "raise", "xml4h", ".", "exceptions", ".", "IncorrectArgumentTypeException", "(", "tagname_or_element", ",", "[", "basestring", ",", "xml4h", ".", "nodes", ".", "Element", "]", ")", "return", "Builder", "(", "element", ")" ]
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 in an existing document. :type tagname_or_element: string or :class:`~xml4h.nodes.Element` node :param ns_uri: a namespace URI to apply to the new root node. This argument has no effect this method is acting on an element. :type ns_uri: string or None :param adapter: the *xml4h* implementation adapter class used to interact with the document DOM nodes. If None, :attr:`best_adapter` will be used. :type adapter: adapter class or None :return: a :class:`~xml4h.builder.Builder` instance that represents an :class:`~xml4h.nodes.Element` node in an XML DOM.
[ "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", "." ]
train
https://github.com/jmurty/xml4h/blob/adbb45e27a01a869a505aee7bc16bad2f517b511/xml4h/__init__.py#L73-L105
smarie/python-valid8
valid8/entry_points.py
get_none_policy_text
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 NonePolicy.SKIP: return "accept None without performing validation" if verbose else 'SKIP' elif none_policy is NonePolicy.FAIL: return "fail on None without performing validation" if verbose else 'FAIL' elif none_policy is NonePolicy.VALIDATE: return "validate None as any other values" if verbose else 'VALIDATE' elif none_policy is NoneArgPolicy.SKIP_IF_NONABLE_ELSE_FAIL: return "accept None without validation if the argument is optional, otherwise fail on None" if verbose \ else 'SKIP_IF_NONABLE_ELSE_FAIL' elif none_policy is NoneArgPolicy.SKIP_IF_NONABLE_ELSE_VALIDATE: return "accept None without validation if the argument is optional, otherwise validate None as any other " \ "values" if verbose else 'SKIP_IF_NONABLE_ELSE_VALIDATE' else: raise ValueError('Invalid none_policy ' + str(none_policy))
python
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 NonePolicy.SKIP: return "accept None without performing validation" if verbose else 'SKIP' elif none_policy is NonePolicy.FAIL: return "fail on None without performing validation" if verbose else 'FAIL' elif none_policy is NonePolicy.VALIDATE: return "validate None as any other values" if verbose else 'VALIDATE' elif none_policy is NoneArgPolicy.SKIP_IF_NONABLE_ELSE_FAIL: return "accept None without validation if the argument is optional, otherwise fail on None" if verbose \ else 'SKIP_IF_NONABLE_ELSE_FAIL' elif none_policy is NoneArgPolicy.SKIP_IF_NONABLE_ELSE_VALIDATE: return "accept None without validation if the argument is optional, otherwise validate None as any other " \ "values" if verbose else 'SKIP_IF_NONABLE_ELSE_VALIDATE' else: raise ValueError('Invalid none_policy ' + str(none_policy))
[ "def", "get_none_policy_text", "(", "none_policy", ",", "# type: int", "verbose", "=", "False", "# type: bool", ")", ":", "if", "none_policy", "is", "NonePolicy", ".", "SKIP", ":", "return", "\"accept None without performing validation\"", "if", "verbose", "else", "'SKIP'", "elif", "none_policy", "is", "NonePolicy", ".", "FAIL", ":", "return", "\"fail on None without performing validation\"", "if", "verbose", "else", "'FAIL'", "elif", "none_policy", "is", "NonePolicy", ".", "VALIDATE", ":", "return", "\"validate None as any other values\"", "if", "verbose", "else", "'VALIDATE'", "elif", "none_policy", "is", "NoneArgPolicy", ".", "SKIP_IF_NONABLE_ELSE_FAIL", ":", "return", "\"accept None without validation if the argument is optional, otherwise fail on None\"", "if", "verbose", "else", "'SKIP_IF_NONABLE_ELSE_FAIL'", "elif", "none_policy", "is", "NoneArgPolicy", ".", "SKIP_IF_NONABLE_ELSE_VALIDATE", ":", "return", "\"accept None without validation if the argument is optional, otherwise validate None as any other \"", "\"values\"", "if", "verbose", "else", "'SKIP_IF_NONABLE_ELSE_VALIDATE'", "else", ":", "raise", "ValueError", "(", "'Invalid none_policy '", "+", "str", "(", "none_policy", ")", ")" ]
Returns a user-friendly description of a NonePolicy taking into account NoneArgPolicy :param none_policy: :param verbose: :return:
[ "Returns", "a", "user", "-", "friendly", "description", "of", "a", "NonePolicy", "taking", "into", "account", "NoneArgPolicy" ]
train
https://github.com/smarie/python-valid8/blob/5e15d1de11602933c5114eb9f73277ad91d97800/valid8/entry_points.py#L53-L76
smarie/python-valid8
valid8/entry_points.py
_add_none_handler
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: :param none_policy: an int representing the None policy, see NonePolicy :return: """ if none_policy is NonePolicy.SKIP: return _none_accepter(validation_callable) # accept all None values elif none_policy is NonePolicy.FAIL: return _none_rejecter(validation_callable) # reject all None values elif none_policy is NonePolicy.VALIDATE: return validation_callable # do not handle None specifically, do not wrap else: raise ValueError('Invalid none_policy : ' + str(none_policy))
python
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: :param none_policy: an int representing the None policy, see NonePolicy :return: """ if none_policy is NonePolicy.SKIP: return _none_accepter(validation_callable) # accept all None values elif none_policy is NonePolicy.FAIL: return _none_rejecter(validation_callable) # reject all None values elif none_policy is NonePolicy.VALIDATE: return validation_callable # do not handle None specifically, do not wrap else: raise ValueError('Invalid none_policy : ' + str(none_policy))
[ "def", "_add_none_handler", "(", "validation_callable", ",", "# type: Callable", "none_policy", "# type: int", ")", ":", "# type: (...) -> Callable", "if", "none_policy", "is", "NonePolicy", ".", "SKIP", ":", "return", "_none_accepter", "(", "validation_callable", ")", "# accept all None values", "elif", "none_policy", "is", "NonePolicy", ".", "FAIL", ":", "return", "_none_rejecter", "(", "validation_callable", ")", "# reject all None values", "elif", "none_policy", "is", "NonePolicy", ".", "VALIDATE", ":", "return", "validation_callable", "# do not handle None specifically, do not wrap", "else", ":", "raise", "ValueError", "(", "'Invalid none_policy : '", "+", "str", "(", "none_policy", ")", ")" ]
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:
[ "Adds", "a", "wrapper", "or", "nothing", "around", "the", "provided", "validation_callable", "depending", "on", "the", "selected", "policy" ]
train
https://github.com/smarie/python-valid8/blob/5e15d1de11602933c5114eb9f73277ad91d97800/valid8/entry_points.py#L79-L100
smarie/python-valid8
valid8/entry_points.py
add_base_type_dynamically
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 the first type, __name__ for the second) For example ``` > new_type = add_base_type_dynamically(ValidationError, ValueError) > repr(new_type) "<class 'valid8.entry_points.ValidationError+ValueError'>" ``` :return: """ # the new type created dynamically, with the same name class new_error_type(with_metaclass(MetaReprForValidator, error_type, additional_type, object)): pass new_error_type.__name__ = error_type.__name__ + '[' + additional_type.__name__ + ']' if sys.version_info >= (3, 0): new_error_type.__qualname__ = error_type.__qualname__ + '[' + additional_type.__qualname__+ ']' new_error_type.__module__ = error_type.__module__ return new_error_type
python
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 the first type, __name__ for the second) For example ``` > new_type = add_base_type_dynamically(ValidationError, ValueError) > repr(new_type) "<class 'valid8.entry_points.ValidationError+ValueError'>" ``` :return: """ # the new type created dynamically, with the same name class new_error_type(with_metaclass(MetaReprForValidator, error_type, additional_type, object)): pass new_error_type.__name__ = error_type.__name__ + '[' + additional_type.__name__ + ']' if sys.version_info >= (3, 0): new_error_type.__qualname__ = error_type.__qualname__ + '[' + additional_type.__qualname__+ ']' new_error_type.__module__ = error_type.__module__ return new_error_type
[ "def", "add_base_type_dynamically", "(", "error_type", ",", "additional_type", ")", ":", "# the new type created dynamically, with the same name", "class", "new_error_type", "(", "with_metaclass", "(", "MetaReprForValidator", ",", "error_type", ",", "additional_type", ",", "object", ")", ")", ":", "pass", "new_error_type", ".", "__name__", "=", "error_type", ".", "__name__", "+", "'['", "+", "additional_type", ".", "__name__", "+", "']'", "if", "sys", ".", "version_info", ">=", "(", "3", ",", "0", ")", ":", "new_error_type", ".", "__qualname__", "=", "error_type", ".", "__qualname__", "+", "'['", "+", "additional_type", ".", "__qualname__", "+", "']'", "new_error_type", ".", "__module__", "=", "error_type", ".", "__module__", "return", "new_error_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 the first type, __name__ for the second) For example ``` > new_type = add_base_type_dynamically(ValidationError, ValueError) > repr(new_type) "<class 'valid8.entry_points.ValidationError+ValueError'>" ``` :return:
[ "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", ")" ]
train
https://github.com/smarie/python-valid8/blob/5e15d1de11602933c5114eb9f73277ad91d97800/valid8/entry_points.py#L346-L369
smarie/python-valid8
valid8/entry_points.py
assert_valid
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 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. ```python assert_valid(x, isfinite): ...<your code> ``` Note: this is a friendly alias for `_validator(base_validator_s)(value)` :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 implicit `and_` (such as the main list). Tuples indicate an implicit `_failure_raiser`. [mini_lambda](https://smarie.github.io/python-mini-lambda/) expressions can be used instead of callables, they will be transformed to functions automatically. :param name: the name of the variable to validate. It will be used in error messages :param value: the value to validate :param none_policy: describes how None values should be handled. See `NonePolicy` for the various possibilities. Default is `NonePolicy.VALIDATE`, meaning that None values will be treated exactly like other values and follow the same validation process. :param error_type: a subclass of ValidationError to raise in case of validation failure. By default a ValidationError will be raised with the provided help_msg :param help_msg: an optional help message to be used in the raised error in case of validation failure. :param kw_context_args: optional keyword arguments providing additional context, that will be provided to the error in case of validation failure :return: nothing in case of success. In case of failure, raises a <error_type> if provided, or a ValidationError. """ error_type, help_msg, none_policy = pop_kwargs(kwargs, [('error_type', None), ('help_msg', None), ('none_policy', None)], allow_others=True) # the rest of keyword arguments is used as context. kw_context_args = kwargs return Validator(*validation_func, error_type=error_type, help_msg=help_msg, none_policy=none_policy).assert_valid(name=name, value=value, **kw_context_args)
python
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 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. ```python assert_valid(x, isfinite): ...<your code> ``` Note: this is a friendly alias for `_validator(base_validator_s)(value)` :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 implicit `and_` (such as the main list). Tuples indicate an implicit `_failure_raiser`. [mini_lambda](https://smarie.github.io/python-mini-lambda/) expressions can be used instead of callables, they will be transformed to functions automatically. :param name: the name of the variable to validate. It will be used in error messages :param value: the value to validate :param none_policy: describes how None values should be handled. See `NonePolicy` for the various possibilities. Default is `NonePolicy.VALIDATE`, meaning that None values will be treated exactly like other values and follow the same validation process. :param error_type: a subclass of ValidationError to raise in case of validation failure. By default a ValidationError will be raised with the provided help_msg :param help_msg: an optional help message to be used in the raised error in case of validation failure. :param kw_context_args: optional keyword arguments providing additional context, that will be provided to the error in case of validation failure :return: nothing in case of success. In case of failure, raises a <error_type> if provided, or a ValidationError. """ error_type, help_msg, none_policy = pop_kwargs(kwargs, [('error_type', None), ('help_msg', None), ('none_policy', None)], allow_others=True) # the rest of keyword arguments is used as context. kw_context_args = kwargs return Validator(*validation_func, error_type=error_type, help_msg=help_msg, none_policy=none_policy).assert_valid(name=name, value=value, **kw_context_args)
[ "def", "assert_valid", "(", "name", ",", "# type: str", "value", ",", "# type: Any", "*", "validation_func", ",", "# type: ValidationFuncs", "*", "*", "kwargs", ")", ":", "error_type", ",", "help_msg", ",", "none_policy", "=", "pop_kwargs", "(", "kwargs", ",", "[", "(", "'error_type'", ",", "None", ")", ",", "(", "'help_msg'", ",", "None", ")", ",", "(", "'none_policy'", ",", "None", ")", "]", ",", "allow_others", "=", "True", ")", "# the rest of keyword arguments is used as context.", "kw_context_args", "=", "kwargs", "return", "Validator", "(", "*", "validation_func", ",", "error_type", "=", "error_type", ",", "help_msg", "=", "help_msg", ",", "none_policy", "=", "none_policy", ")", ".", "assert_valid", "(", "name", "=", "name", ",", "value", "=", "value", ",", "*", "*", "kw_context_args", ")" ]
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. ```python assert_valid(x, isfinite): ...<your code> ``` Note: this is a friendly alias for `_validator(base_validator_s)(value)` :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 implicit `and_` (such as the main list). Tuples indicate an implicit `_failure_raiser`. [mini_lambda](https://smarie.github.io/python-mini-lambda/) expressions can be used instead of callables, they will be transformed to functions automatically. :param name: the name of the variable to validate. It will be used in error messages :param value: the value to validate :param none_policy: describes how None values should be handled. See `NonePolicy` for the various possibilities. Default is `NonePolicy.VALIDATE`, meaning that None values will be treated exactly like other values and follow the same validation process. :param error_type: a subclass of ValidationError to raise in case of validation failure. By default a ValidationError will be raised with the provided help_msg :param help_msg: an optional help message to be used in the raised error in case of validation failure. :param kw_context_args: optional keyword arguments providing additional context, that will be provided to the error in case of validation failure :return: nothing in case of success. In case of failure, raises a <error_type> if provided, or a ValidationError.
[ "Validates", "value", "value", "using", "validation", "function", "(", "s", ")", "base_validator_s", ".", "As", "opposed", "to", "is_valid", "this", "function", "raises", "a", "ValidationError", "if", "validation", "fails", "." ]
train
https://github.com/smarie/python-valid8/blob/5e15d1de11602933c5114eb9f73277ad91d97800/valid8/entry_points.py#L669-L711
smarie/python-valid8
valid8/entry_points.py
is_valid
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 validation was a success or a failure. It is therefore designed to be used within if ... else ... statements: ```python if is_valid(x, isfinite): ...<code> else ...<code> ``` Note: this is a friendly alias for `return _validator(validator_func, return_bool=True)(value)` :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 implicit `and_` (such as the main list). Tuples indicate an implicit `_failure_raiser`. [mini_lambda](https://smarie.github.io/python-mini-lambda/) expressions can be used instead of callables, they will be transformed to functions automatically. :param value: the value to validate :param none_policy: describes how None values should be handled. See `NonePolicy` for the various possibilities. Default is `NonePolicy.VALIDATE`, meaning that None values will be treated exactly like other values and follow the same validation process. Note that errors raised by NonePolicy.FAIL will be caught and transformed into a returned value of False :return: True if validation was a success, False otherwise """ none_policy = pop_kwargs(kwargs, [('none_policy', None)]) return Validator(*validation_func, none_policy=none_policy).is_valid(value)
python
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 validation was a success or a failure. It is therefore designed to be used within if ... else ... statements: ```python if is_valid(x, isfinite): ...<code> else ...<code> ``` Note: this is a friendly alias for `return _validator(validator_func, return_bool=True)(value)` :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 implicit `and_` (such as the main list). Tuples indicate an implicit `_failure_raiser`. [mini_lambda](https://smarie.github.io/python-mini-lambda/) expressions can be used instead of callables, they will be transformed to functions automatically. :param value: the value to validate :param none_policy: describes how None values should be handled. See `NonePolicy` for the various possibilities. Default is `NonePolicy.VALIDATE`, meaning that None values will be treated exactly like other values and follow the same validation process. Note that errors raised by NonePolicy.FAIL will be caught and transformed into a returned value of False :return: True if validation was a success, False otherwise """ none_policy = pop_kwargs(kwargs, [('none_policy', None)]) return Validator(*validation_func, none_policy=none_policy).is_valid(value)
[ "def", "is_valid", "(", "value", ",", "*", "validation_func", ",", "# type: Union[Callable, List[Callable]]", "*", "*", "kwargs", ")", ":", "# type: (...) -> bool", "none_policy", "=", "pop_kwargs", "(", "kwargs", ",", "[", "(", "'none_policy'", ",", "None", ")", "]", ")", "return", "Validator", "(", "*", "validation_func", ",", "none_policy", "=", "none_policy", ")", ".", "is_valid", "(", "value", ")" ]
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): ...<code> else ...<code> ``` Note: this is a friendly alias for `return _validator(validator_func, return_bool=True)(value)` :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 implicit `and_` (such as the main list). Tuples indicate an implicit `_failure_raiser`. [mini_lambda](https://smarie.github.io/python-mini-lambda/) expressions can be used instead of callables, they will be transformed to functions automatically. :param value: the value to validate :param none_policy: describes how None values should be handled. See `NonePolicy` for the various possibilities. Default is `NonePolicy.VALIDATE`, meaning that None values will be treated exactly like other values and follow the same validation process. Note that errors raised by NonePolicy.FAIL will be caught and transformed into a returned value of False :return: True if validation was a success, False otherwise
[ "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", ":" ]
train
https://github.com/smarie/python-valid8/blob/5e15d1de11602933c5114eb9f73277ad91d97800/valid8/entry_points.py#L724-L757
smarie/python-valid8
valid8/entry_points.py
ValidationError.create_manually
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 append_details=True, # type: bool **kw_context_args): """ 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: :param validation_outcome: :param help_msg: :param append_details: :param kw_context_args: :return: """ # create a dummy validator def val_fun(x): pass val_fun.__name__ = validation_function_name validator = Validator(val_fun, error_type=cls, help_msg=help_msg, **kw_context_args) # create the exception # e = cls(validator, var_value, var_name, validation_outcome=validation_outcome, help_msg=help_msg, # append_details=append_details, **kw_context_args) e = validator._create_validation_error(var_name, var_value, validation_outcome, error_type=cls, help_msg=help_msg, **kw_context_args) return e
python
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 append_details=True, # type: bool **kw_context_args): """ 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: :param validation_outcome: :param help_msg: :param append_details: :param kw_context_args: :return: """ # create a dummy validator def val_fun(x): pass val_fun.__name__ = validation_function_name validator = Validator(val_fun, error_type=cls, help_msg=help_msg, **kw_context_args) # create the exception # e = cls(validator, var_value, var_name, validation_outcome=validation_outcome, help_msg=help_msg, # append_details=append_details, **kw_context_args) e = validator._create_validation_error(var_name, var_value, validation_outcome, error_type=cls, help_msg=help_msg, **kw_context_args) return e
[ "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", "append_details", "=", "True", ",", "# type: bool", "*", "*", "kw_context_args", ")", ":", "# create a dummy validator", "def", "val_fun", "(", "x", ")", ":", "pass", "val_fun", ".", "__name__", "=", "validation_function_name", "validator", "=", "Validator", "(", "val_fun", ",", "error_type", "=", "cls", ",", "help_msg", "=", "help_msg", ",", "*", "*", "kw_context_args", ")", "# create the exception", "# e = cls(validator, var_value, var_name, validation_outcome=validation_outcome, help_msg=help_msg,", "# append_details=append_details, **kw_context_args)", "e", "=", "validator", ".", "_create_validation_error", "(", "var_name", ",", "var_value", ",", "validation_outcome", ",", "error_type", "=", "cls", ",", "help_msg", "=", "help_msg", ",", "*", "*", "kw_context_args", ")", "return", "e" ]
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: :param validation_outcome: :param help_msg: :param append_details: :param kw_context_args: :return:
[ "Creates", "an", "instance", "without", "using", "a", "Validator", "." ]
train
https://github.com/smarie/python-valid8/blob/5e15d1de11602933c5114eb9f73277ad91d97800/valid8/entry_points.py#L174-L208
smarie/python-valid8
valid8/entry_points.py
ValidationError.get_details
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 [{val}] raised ' if self.display_prefix_for_exc_outcomes else '' # new: we now remove "Root validator was [{validator}]", users can get it through e.validator contents = ('Error validating {what}. ' + prefix + '{exception}: {details}')\ .format(what=self.get_what_txt(), val=self.validator.get_main_function_name(), exception=type(self.validation_outcome).__name__, details=end_with_dot(str(self.validation_outcome))) else: contents = 'Error validating {what}: validation function [{val}] returned [{result}].' \ ''.format(what=self.get_what_txt(), val=self.validator.get_main_function_name(), result=self.validation_outcome) # return 'Wrong value: [{}]'.format(self.var_value) return contents
python
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 [{val}] raised ' if self.display_prefix_for_exc_outcomes else '' # new: we now remove "Root validator was [{validator}]", users can get it through e.validator contents = ('Error validating {what}. ' + prefix + '{exception}: {details}')\ .format(what=self.get_what_txt(), val=self.validator.get_main_function_name(), exception=type(self.validation_outcome).__name__, details=end_with_dot(str(self.validation_outcome))) else: contents = 'Error validating {what}: validation function [{val}] returned [{result}].' \ ''.format(what=self.get_what_txt(), val=self.validator.get_main_function_name(), result=self.validation_outcome) # return 'Wrong value: [{}]'.format(self.var_value) return contents
[ "def", "get_details", "(", "self", ")", ":", "# create the exception main message according to the type of result", "if", "isinstance", "(", "self", ".", "validation_outcome", ",", "Exception", ")", ":", "prefix", "=", "'Validation function [{val}] raised '", "if", "self", ".", "display_prefix_for_exc_outcomes", "else", "''", "# new: we now remove \"Root validator was [{validator}]\", users can get it through e.validator", "contents", "=", "(", "'Error validating {what}. '", "+", "prefix", "+", "'{exception}: {details}'", ")", ".", "format", "(", "what", "=", "self", ".", "get_what_txt", "(", ")", ",", "val", "=", "self", ".", "validator", ".", "get_main_function_name", "(", ")", ",", "exception", "=", "type", "(", "self", ".", "validation_outcome", ")", ".", "__name__", ",", "details", "=", "end_with_dot", "(", "str", "(", "self", ".", "validation_outcome", ")", ")", ")", "else", ":", "contents", "=", "'Error validating {what}: validation function [{val}] returned [{result}].'", "''", ".", "format", "(", "what", "=", "self", ".", "get_what_txt", "(", ")", ",", "val", "=", "self", ".", "validator", ".", "get_main_function_name", "(", ")", ",", "result", "=", "self", ".", "validation_outcome", ")", "# return 'Wrong value: [{}]'.format(self.var_value)", "return", "contents" ]
The function called to get the details appended to the help message when self.append_details is True
[ "The", "function", "called", "to", "get", "the", "details", "appended", "to", "the", "help", "message", "when", "self", ".", "append_details", "is", "True" ]
train
https://github.com/smarie/python-valid8/blob/5e15d1de11602933c5114eb9f73277ad91d97800/valid8/entry_points.py#L282-L303
smarie/python-valid8
valid8/entry_points.py
ValidationError.get_variable_str
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: prefix = self.var_name suffix = str(self.var_value) if len(suffix) == 0: suffix = "''" elif len(suffix) > self.__max_str_length_displayed__: suffix = '' if len(prefix) > 0 and len(suffix) > 0: return prefix + '=' + suffix else: return prefix + suffix
python
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: prefix = self.var_name suffix = str(self.var_value) if len(suffix) == 0: suffix = "''" elif len(suffix) > self.__max_str_length_displayed__: suffix = '' if len(prefix) > 0 and len(suffix) > 0: return prefix + '=' + suffix else: return prefix + suffix
[ "def", "get_variable_str", "(", "self", ")", ":", "if", "self", ".", "var_name", "is", "None", ":", "prefix", "=", "''", "else", ":", "prefix", "=", "self", ".", "var_name", "suffix", "=", "str", "(", "self", ".", "var_value", ")", "if", "len", "(", "suffix", ")", "==", "0", ":", "suffix", "=", "\"''\"", "elif", "len", "(", "suffix", ")", ">", "self", ".", "__max_str_length_displayed__", ":", "suffix", "=", "''", "if", "len", "(", "prefix", ")", ">", "0", "and", "len", "(", "suffix", ")", ">", "0", ":", "return", "prefix", "+", "'='", "+", "suffix", "else", ":", "return", "prefix", "+", "suffix" ]
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:
[ "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" ]
train
https://github.com/smarie/python-valid8/blob/5e15d1de11602933c5114eb9f73277ad91d97800/valid8/entry_points.py#L305-L326
smarie/python-valid8
valid8/entry_points.py
Validator.assert_valid
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 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. By default this raises instances of `ValidationError` with a default message, in case of failure. There are two ways that you can customize this behaviour: * if you set `help_msg` in this method or in `Validator` constructor, instances of `ValidationError` created will be customized with the provided help message. * if you set `error_type` in this method or in `Validator` constructor, instances of your custom class will be created. Note that you may still provide a `help_msg`. It is recommended that Users define their own validation error types (case 2 above), so as to provide a unique error type for each kind of applicative error. This eases the process of error handling at app-level. :param name: the name of the variable to validate (for error messages) :param value: the value to validate :param error_type: a subclass of `ValidationError` to raise in case of validation failure. By default a `ValidationError` will be raised with the provided `help_msg` :param help_msg: an optional help message to be used in the raised error in case of validation failure. :param kw_context_args: optional contextual information to store in the exception, and that may be also used to format the help message :return: nothing in case of success. Otherwise, raises a ValidationError """ try: # perform validation res = self.main_function(value) except Exception as e: # caught any exception: raise ValidationError or subclass with that exception in the details # --old bad idea: first wrap into a failure ==> NO !!! I tried and it was making it far too messy/verbose # note: we do not have to 'raise x from e' of `raise_from`since the ValidationError constructor already # sets the __cause__ so we can safely take the same handling than for non-exception failures. res = e # check the result if not result_is_success(res): raise_(self._create_validation_error(name, value, validation_outcome=res, error_type=error_type, help_msg=help_msg, **kw_context_args))
python
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 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. By default this raises instances of `ValidationError` with a default message, in case of failure. There are two ways that you can customize this behaviour: * if you set `help_msg` in this method or in `Validator` constructor, instances of `ValidationError` created will be customized with the provided help message. * if you set `error_type` in this method or in `Validator` constructor, instances of your custom class will be created. Note that you may still provide a `help_msg`. It is recommended that Users define their own validation error types (case 2 above), so as to provide a unique error type for each kind of applicative error. This eases the process of error handling at app-level. :param name: the name of the variable to validate (for error messages) :param value: the value to validate :param error_type: a subclass of `ValidationError` to raise in case of validation failure. By default a `ValidationError` will be raised with the provided `help_msg` :param help_msg: an optional help message to be used in the raised error in case of validation failure. :param kw_context_args: optional contextual information to store in the exception, and that may be also used to format the help message :return: nothing in case of success. Otherwise, raises a ValidationError """ try: # perform validation res = self.main_function(value) except Exception as e: # caught any exception: raise ValidationError or subclass with that exception in the details # --old bad idea: first wrap into a failure ==> NO !!! I tried and it was making it far too messy/verbose # note: we do not have to 'raise x from e' of `raise_from`since the ValidationError constructor already # sets the __cause__ so we can safely take the same handling than for non-exception failures. res = e # check the result if not result_is_success(res): raise_(self._create_validation_error(name, value, validation_outcome=res, error_type=error_type, help_msg=help_msg, **kw_context_args))
[ "def", "assert_valid", "(", "self", ",", "name", ",", "# type: str", "value", ",", "# type: Any", "error_type", "=", "None", ",", "# type: Type[ValidationError]", "help_msg", "=", "None", ",", "# type: str", "*", "*", "kw_context_args", ")", ":", "try", ":", "# perform validation", "res", "=", "self", ".", "main_function", "(", "value", ")", "except", "Exception", "as", "e", ":", "# caught any exception: raise ValidationError or subclass with that exception in the details", "# --old bad idea: first wrap into a failure ==> NO !!! I tried and it was making it far too messy/verbose", "# note: we do not have to 'raise x from e' of `raise_from`since the ValidationError constructor already", "# sets the __cause__ so we can safely take the same handling than for non-exception failures.", "res", "=", "e", "# check the result", "if", "not", "result_is_success", "(", "res", ")", ":", "raise_", "(", "self", ".", "_create_validation_error", "(", "name", ",", "value", ",", "validation_outcome", "=", "res", ",", "error_type", "=", "error_type", ",", "help_msg", "=", "help_msg", ",", "*", "*", "kw_context_args", ")", ")" ]
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. By default this raises instances of `ValidationError` with a default message, in case of failure. There are two ways that you can customize this behaviour: * if you set `help_msg` in this method or in `Validator` constructor, instances of `ValidationError` created will be customized with the provided help message. * if you set `error_type` in this method or in `Validator` constructor, instances of your custom class will be created. Note that you may still provide a `help_msg`. It is recommended that Users define their own validation error types (case 2 above), so as to provide a unique error type for each kind of applicative error. This eases the process of error handling at app-level. :param name: the name of the variable to validate (for error messages) :param value: the value to validate :param error_type: a subclass of `ValidationError` to raise in case of validation failure. By default a `ValidationError` will be raised with the provided `help_msg` :param help_msg: an optional help message to be used in the raised error in case of validation failure. :param kw_context_args: optional contextual information to store in the exception, and that may be also used to format the help message :return: nothing in case of success. Otherwise, raises a ValidationError
[ "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", "." ]
train
https://github.com/smarie/python-valid8/blob/5e15d1de11602933c5114eb9f73277ad91d97800/valid8/entry_points.py#L517-L564
smarie/python-valid8
valid8/entry_points.py
Validator._create_validation_error
def _create_validation_error(self, name, # type: str value, # type: Any validation_outcome=None, # type: Any error_type=None, # type: Type[ValidationError] help_msg=None, # type: str **kw_context_args): """ The function doing the final error raising. """ # first merge the info provided in arguments and in self error_type = error_type or self.error_type help_msg = help_msg or self.help_msg ctx = copy(self.kw_context_args) ctx.update(kw_context_args) # allow the class to override the name name = self._get_name_for_errors(name) if issubclass(error_type, TypeError) or issubclass(error_type, ValueError): # this is most probably a custom error type, it is already annotated with ValueError and/or TypeError # so use it 'as is' new_error_type = error_type else: # Add the appropriate TypeError/ValueError base type dynamically additional_type = None if isinstance(validation_outcome, Exception): if is_error_of_type(validation_outcome, TypeError): additional_type = TypeError elif is_error_of_type(validation_outcome, ValueError): additional_type = ValueError if additional_type is None: # not much we can do here, let's assume a ValueError, that is more probable additional_type = ValueError new_error_type = add_base_type_dynamically(error_type, additional_type) # then raise the appropriate ValidationError or subclass return new_error_type(validator=self, var_value=value, var_name=name, validation_outcome=validation_outcome, help_msg=help_msg, **ctx)
python
def _create_validation_error(self, name, # type: str value, # type: Any validation_outcome=None, # type: Any error_type=None, # type: Type[ValidationError] help_msg=None, # type: str **kw_context_args): """ The function doing the final error raising. """ # first merge the info provided in arguments and in self error_type = error_type or self.error_type help_msg = help_msg or self.help_msg ctx = copy(self.kw_context_args) ctx.update(kw_context_args) # allow the class to override the name name = self._get_name_for_errors(name) if issubclass(error_type, TypeError) or issubclass(error_type, ValueError): # this is most probably a custom error type, it is already annotated with ValueError and/or TypeError # so use it 'as is' new_error_type = error_type else: # Add the appropriate TypeError/ValueError base type dynamically additional_type = None if isinstance(validation_outcome, Exception): if is_error_of_type(validation_outcome, TypeError): additional_type = TypeError elif is_error_of_type(validation_outcome, ValueError): additional_type = ValueError if additional_type is None: # not much we can do here, let's assume a ValueError, that is more probable additional_type = ValueError new_error_type = add_base_type_dynamically(error_type, additional_type) # then raise the appropriate ValidationError or subclass return new_error_type(validator=self, var_value=value, var_name=name, validation_outcome=validation_outcome, help_msg=help_msg, **ctx)
[ "def", "_create_validation_error", "(", "self", ",", "name", ",", "# type: str", "value", ",", "# type: Any", "validation_outcome", "=", "None", ",", "# type: Any", "error_type", "=", "None", ",", "# type: Type[ValidationError]", "help_msg", "=", "None", ",", "# type: str", "*", "*", "kw_context_args", ")", ":", "# first merge the info provided in arguments and in self", "error_type", "=", "error_type", "or", "self", ".", "error_type", "help_msg", "=", "help_msg", "or", "self", ".", "help_msg", "ctx", "=", "copy", "(", "self", ".", "kw_context_args", ")", "ctx", ".", "update", "(", "kw_context_args", ")", "# allow the class to override the name", "name", "=", "self", ".", "_get_name_for_errors", "(", "name", ")", "if", "issubclass", "(", "error_type", ",", "TypeError", ")", "or", "issubclass", "(", "error_type", ",", "ValueError", ")", ":", "# this is most probably a custom error type, it is already annotated with ValueError and/or TypeError", "# so use it 'as is'", "new_error_type", "=", "error_type", "else", ":", "# Add the appropriate TypeError/ValueError base type dynamically", "additional_type", "=", "None", "if", "isinstance", "(", "validation_outcome", ",", "Exception", ")", ":", "if", "is_error_of_type", "(", "validation_outcome", ",", "TypeError", ")", ":", "additional_type", "=", "TypeError", "elif", "is_error_of_type", "(", "validation_outcome", ",", "ValueError", ")", ":", "additional_type", "=", "ValueError", "if", "additional_type", "is", "None", ":", "# not much we can do here, let's assume a ValueError, that is more probable", "additional_type", "=", "ValueError", "new_error_type", "=", "add_base_type_dynamically", "(", "error_type", ",", "additional_type", ")", "# then raise the appropriate ValidationError or subclass", "return", "new_error_type", "(", "validator", "=", "self", ",", "var_value", "=", "value", ",", "var_name", "=", "name", ",", "validation_outcome", "=", "validation_outcome", ",", "help_msg", "=", "help_msg", ",", "*", "*", "ctx", ")" ]
The function doing the final error raising.
[ "The", "function", "doing", "the", "final", "error", "raising", "." ]
train
https://github.com/smarie/python-valid8/blob/5e15d1de11602933c5114eb9f73277ad91d97800/valid8/entry_points.py#L566-L604
smarie/python-valid8
valid8/entry_points.py
Validator.is_valid
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 value to validate :return: a boolean flag indicating success or failure """ # noinspection PyBroadException try: # perform validation res = self.main_function(value) # return a boolean indicating if success or failure return result_is_success(res) except Exception: # caught exception means failure > return False return False
python
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 value to validate :return: a boolean flag indicating success or failure """ # noinspection PyBroadException try: # perform validation res = self.main_function(value) # return a boolean indicating if success or failure return result_is_success(res) except Exception: # caught exception means failure > return False return False
[ "def", "is_valid", "(", "self", ",", "value", "# type: Any", ")", ":", "# type: (...) -> bool", "# noinspection PyBroadException", "try", ":", "# perform validation", "res", "=", "self", ".", "main_function", "(", "value", ")", "# return a boolean indicating if success or failure", "return", "result_is_success", "(", "res", ")", "except", "Exception", ":", "# caught exception means failure > return False", "return", "False" ]
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
[ "Validates", "the", "provided", "value", "and", "returns", "a", "boolean", "indicating", "success", "or", "failure", ".", "Any", "Exception", "happening", "in", "the", "validation", "process", "will", "be", "silently", "caught", "." ]
train
https://github.com/smarie/python-valid8/blob/5e15d1de11602933c5114eb9f73277ad91d97800/valid8/entry_points.py#L631-L652
redhat-cip/dci-control-server
dci/api/v1/tags.py
create_tags
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['name']) query = sql.select([_TABLE.c.id]).where(where_clause) if flask.g.db_conn.execute(query).fetchone(): raise dci_exc.DCIConflict('Tag already exists', values) # create the label/value row query = _TABLE.insert().values(**values) flask.g.db_conn.execute(query) result = json.dumps({'tag': values}) return flask.Response(result, 201, content_type='application/json')
python
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['name']) query = sql.select([_TABLE.c.id]).where(where_clause) if flask.g.db_conn.execute(query).fetchone(): raise dci_exc.DCIConflict('Tag already exists', values) # create the label/value row query = _TABLE.insert().values(**values) flask.g.db_conn.execute(query) result = json.dumps({'tag': values}) return flask.Response(result, 201, content_type='application/json')
[ "def", "create_tags", "(", "user", ")", ":", "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", "[", "'name'", "]", ")", "query", "=", "sql", ".", "select", "(", "[", "_TABLE", ".", "c", ".", "id", "]", ")", ".", "where", "(", "where_clause", ")", "if", "flask", ".", "g", ".", "db_conn", ".", "execute", "(", "query", ")", ".", "fetchone", "(", ")", ":", "raise", "dci_exc", ".", "DCIConflict", "(", "'Tag already exists'", ",", "values", ")", "# create the label/value row", "query", "=", "_TABLE", ".", "insert", "(", ")", ".", "values", "(", "*", "*", "values", ")", "flask", ".", "g", ".", "db_conn", ".", "execute", "(", "query", ")", "result", "=", "json", ".", "dumps", "(", "{", "'tag'", ":", "values", "}", ")", "return", "flask", ".", "Response", "(", "result", ",", "201", ",", "content_type", "=", "'application/json'", ")" ]
Create a tag.
[ "Create", "a", "tag", "." ]
train
https://github.com/redhat-cip/dci-control-server/blob/b416cf935ec93e4fdd5741f61a21cabecf8454d2/dci/api/v1/tags.py#L72-L93
redhat-cip/dci-control-server
dci/api/v1/tags.py
get_tags
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({'tags': rows, '_meta': {'count': nb_rows}})
python
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({'tags': rows, '_meta': {'count': nb_rows}})
[ "def", "get_tags", "(", "user", ")", ":", "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", "(", "{", "'tags'", ":", "rows", ",", "'_meta'", ":", "{", "'count'", ":", "nb_rows", "}", "}", ")" ]
Get all tags.
[ "Get", "all", "tags", "." ]
train
https://github.com/redhat-cip/dci-control-server/blob/b416cf935ec93e4fdd5741f61a21cabecf8454d2/dci/api/v1/tags.py#L98-L105
redhat-cip/dci-control-server
dci/api/v1/tags.py
delete_tag_by_id
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/json')
python
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/json')
[ "def", "delete_tag_by_id", "(", "user", ",", "tag_id", ")", ":", "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/json'", ")" ]
Delete a tag.
[ "Delete", "a", "tag", "." ]
train
https://github.com/redhat-cip/dci-control-server/blob/b416cf935ec93e4fdd5741f61a21cabecf8454d2/dci/api/v1/tags.py#L110-L118
inveniosoftware/invenio-assets
invenio_assets/ext.py
InvenioAssets.init_app
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. .. versionchanged:: 1.0.0b2 The *entrypoint* has been renamed to *entry_point_group*. """ self.init_config(app) self.env.init_app(app) self.collect.init_app(app) self.webpack.init_app(app) if entry_point_group: self.load_entrypoint(entry_point_group) app.extensions['invenio-assets'] = self
python
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. .. versionchanged:: 1.0.0b2 The *entrypoint* has been renamed to *entry_point_group*. """ self.init_config(app) self.env.init_app(app) self.collect.init_app(app) self.webpack.init_app(app) if entry_point_group: self.load_entrypoint(entry_point_group) app.extensions['invenio-assets'] = self
[ "def", "init_app", "(", "self", ",", "app", ",", "entry_point_group", "=", "'invenio_assets.bundles'", ",", "*", "*", "kwargs", ")", ":", "self", ".", "init_config", "(", "app", ")", "self", ".", "env", ".", "init_app", "(", "app", ")", "self", ".", "collect", ".", "init_app", "(", "app", ")", "self", ".", "webpack", ".", "init_app", "(", "app", ")", "if", "entry_point_group", ":", "self", ".", "load_entrypoint", "(", "entry_point_group", ")", "app", ".", "extensions", "[", "'invenio-assets'", "]", "=", "self" ]
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*.
[ "Initialize", "application", "object", "." ]
train
https://github.com/inveniosoftware/invenio-assets/blob/836cc75ebe0c179f0d72456bd8b784cdc18394a6/invenio_assets/ext.py#L41-L60
inveniosoftware/invenio-assets
invenio_assets/ext.py
InvenioAssets.init_config
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_STORAGE', 'flask_collect.storage.link') app.config.setdefault( 'COLLECT_FILTER', partial(collect_staticroot_removal, app)) app.config.setdefault( 'WEBPACKEXT_PROJECT', 'invenio_assets.webpack:project')
python
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_STORAGE', 'flask_collect.storage.link') app.config.setdefault( 'COLLECT_FILTER', partial(collect_staticroot_removal, app)) app.config.setdefault( 'WEBPACKEXT_PROJECT', 'invenio_assets.webpack:project')
[ "def", "init_config", "(", "self", ",", "app", ")", ":", "app", ".", "config", ".", "setdefault", "(", "'REQUIREJS_BASEURL'", ",", "app", ".", "static_folder", ")", "app", ".", "config", ".", "setdefault", "(", "'COLLECT_STATIC_ROOT'", ",", "app", ".", "static_folder", ")", "app", ".", "config", ".", "setdefault", "(", "'COLLECT_STORAGE'", ",", "'flask_collect.storage.link'", ")", "app", ".", "config", ".", "setdefault", "(", "'COLLECT_FILTER'", ",", "partial", "(", "collect_staticroot_removal", ",", "app", ")", ")", "app", ".", "config", ".", "setdefault", "(", "'WEBPACKEXT_PROJECT'", ",", "'invenio_assets.webpack:project'", ")" ]
Initialize configuration. :param app: An instance of :class:`~flask.Flask`.
[ "Initialize", "configuration", "." ]
train
https://github.com/inveniosoftware/invenio-assets/blob/836cc75ebe0c179f0d72456bd8b784cdc18394a6/invenio_assets/ext.py#L62-L73
inveniosoftware/invenio-assets
invenio_assets/ext.py
InvenioAssets.load_entrypoint
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 pkg_resources.iter_entry_points(entry_point_group): self.env.register(ep.name, ep.load())
python
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 pkg_resources.iter_entry_points(entry_point_group): self.env.register(ep.name, ep.load())
[ "def", "load_entrypoint", "(", "self", ",", "entry_point_group", ")", ":", "for", "ep", "in", "pkg_resources", ".", "iter_entry_points", "(", "entry_point_group", ")", ":", "self", ".", "env", ".", "register", "(", "ep", ".", "name", ",", "ep", ".", "load", "(", ")", ")" ]
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*.
[ "Load", "entrypoint", "." ]
train
https://github.com/inveniosoftware/invenio-assets/blob/836cc75ebe0c179f0d72456bd8b784cdc18394a6/invenio_assets/ext.py#L75-L85
smarie/python-valid8
valid8/entry_points_inline.py
assert_instance_of
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. Used in validate and validation/validator :param value: the value to check :param allowed_types: the type(s) to enforce. If a tuple of types is provided it is considered alternate types: one match is enough to succeed. If None, type will not be enforced :return: """ if not isinstance(value, allowed_types): try: # more than 1 ? allowed_types[1] raise HasWrongType(wrong_value=value, ref_type=allowed_types, help_msg='Value should be an instance of any of {ref_type}') except IndexError: # 1 allowed_types = allowed_types[0] except TypeError: # 1 pass raise HasWrongType(wrong_value=value, ref_type=allowed_types)
python
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. Used in validate and validation/validator :param value: the value to check :param allowed_types: the type(s) to enforce. If a tuple of types is provided it is considered alternate types: one match is enough to succeed. If None, type will not be enforced :return: """ if not isinstance(value, allowed_types): try: # more than 1 ? allowed_types[1] raise HasWrongType(wrong_value=value, ref_type=allowed_types, help_msg='Value should be an instance of any of {ref_type}') except IndexError: # 1 allowed_types = allowed_types[0] except TypeError: # 1 pass raise HasWrongType(wrong_value=value, ref_type=allowed_types)
[ "def", "assert_instance_of", "(", "value", ",", "allowed_types", "# type: Union[Type, Tuple[Type]]", ")", ":", "if", "not", "isinstance", "(", "value", ",", "allowed_types", ")", ":", "try", ":", "# more than 1 ?", "allowed_types", "[", "1", "]", "raise", "HasWrongType", "(", "wrong_value", "=", "value", ",", "ref_type", "=", "allowed_types", ",", "help_msg", "=", "'Value should be an instance of any of {ref_type}'", ")", "except", "IndexError", ":", "# 1", "allowed_types", "=", "allowed_types", "[", "0", "]", "except", "TypeError", ":", "# 1", "pass", "raise", "HasWrongType", "(", "wrong_value", "=", "value", ",", "ref_type", "=", "allowed_types", ")" ]
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 a tuple of types is provided it is considered alternate types: one match is enough to succeed. If None, type will not be enforced :return:
[ "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", "." ]
train
https://github.com/smarie/python-valid8/blob/5e15d1de11602933c5114eb9f73277ad91d97800/valid8/entry_points_inline.py#L25-L51
smarie/python-valid8
valid8/entry_points_inline.py
assert_subclass_of
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. Used in validate and validation/validator :param typ: the type to check :param allowed_types: the type(s) to enforce. If a tuple of types is provided it is considered alternate types: one match is enough to succeed. If None, type will not be enforced :return: """ if not issubclass(typ, allowed_types): try: # more than 1 ? allowed_types[1] raise IsWrongType(wrong_value=typ, ref_type=allowed_types, help_msg='Value should be a subclass of any of {ref_type}') except IndexError: # 1 allowed_types = allowed_types[0] except TypeError: # 1 pass raise IsWrongType(wrong_value=typ, ref_type=allowed_types)
python
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. Used in validate and validation/validator :param typ: the type to check :param allowed_types: the type(s) to enforce. If a tuple of types is provided it is considered alternate types: one match is enough to succeed. If None, type will not be enforced :return: """ if not issubclass(typ, allowed_types): try: # more than 1 ? allowed_types[1] raise IsWrongType(wrong_value=typ, ref_type=allowed_types, help_msg='Value should be a subclass of any of {ref_type}') except IndexError: # 1 allowed_types = allowed_types[0] except TypeError: # 1 pass raise IsWrongType(wrong_value=typ, ref_type=allowed_types)
[ "def", "assert_subclass_of", "(", "typ", ",", "allowed_types", "# type: Union[Type, Tuple[Type]]", ")", ":", "if", "not", "issubclass", "(", "typ", ",", "allowed_types", ")", ":", "try", ":", "# more than 1 ?", "allowed_types", "[", "1", "]", "raise", "IsWrongType", "(", "wrong_value", "=", "typ", ",", "ref_type", "=", "allowed_types", ",", "help_msg", "=", "'Value should be a subclass of any of {ref_type}'", ")", "except", "IndexError", ":", "# 1", "allowed_types", "=", "allowed_types", "[", "0", "]", "except", "TypeError", ":", "# 1", "pass", "raise", "IsWrongType", "(", "wrong_value", "=", "typ", ",", "ref_type", "=", "allowed_types", ")" ]
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 tuple of types is provided it is considered alternate types: one match is enough to succeed. If None, type will not be enforced :return:
[ "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", "." ]
train
https://github.com/smarie/python-valid8/blob/5e15d1de11602933c5114eb9f73277ad91d97800/valid8/entry_points_inline.py#L54-L80
smarie/python-valid8
valid8/entry_points_inline.py
validate
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[Type, Tuple[Type]] is_in=None, # type: Container subset_of=None, # type: Set contains = None, # type: Union[Any, Iterable] superset_of=None, # type: Set min_value=None, # type: Any min_strict=False, # type: bool max_value=None, # type: Any max_strict=False, # type: bool length=None, # type: int min_len=None, # type: int min_len_strict=False, # type: bool max_len=None, # type: int max_len_strict=False, # type: bool custom=None, # type: Callable[[Any], Any] error_type=None, # type: Type[ValidationError] help_msg=None, # type: str **kw_context_args): """ 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: * if `allowed_values` is provided, `value` should be in that set * if `min_value` (resp. `max_value`) is provided, `value` should be greater than it. Comparison is not strict by default and can be set to strict by setting `min_strict`, resp. `max_strict`, to `True` * if `min_len` (resp. `max_len`) is provided, `len(value)` should be greater than it. Comparison is not strict by default and can be set to strict by setting `min_len_strict`, resp. `max_len_strict`, to `True` :param name: the applicative name of the checked value, that will be used in error messages :param value: the value to check :param enforce_not_none: boolean, default True. Whether to enforce that `value` is not None. :param equals: an optional value to enforce. :param instance_of: optional type(s) to enforce. If a tuple of types is provided it is considered alternate types: one match is enough to succeed. If None, type will not be enforced :param subclass_of: optional type(s) to enforce. If a tuple of types is provided it is considered alternate types: one match is enough to succeed. If None, type will not be enforced :param is_in: an optional set of allowed values. :param subset_of: an optional superset for the variable :param contains: an optional value that the variable should contain (value in variable == True) :param superset_of: an optional subset for the variable :param min_value: an optional minimum value :param min_strict: if True, only values strictly greater than `min_value` will be accepted :param max_value: an optional maximum value :param max_strict: if True, only values strictly lesser than `max_value` will be accepted :param length: an optional strict length :param min_len: an optional minimum length :param min_len_strict: if True, only values with length strictly greater than `min_len` will be accepted :param max_len: an optional maximum length :param max_len_strict: if True, only values with length strictly lesser than `max_len` will be accepted :param custom: a custom base validation function or list of base validation functions to use. This is the same syntax than for valid8 decorators. 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 implicit `and_`. Tuples indicate an implicit `_failure_raiser`. [mini_lambda](https://smarie.github.io/python-mini-lambda/) expressions can be used instead of callables, they will be transformed to functions automatically. :param error_type: a subclass of `ValidationError` to raise in case of validation failure. By default a `ValidationError` will be raised with the provided `help_msg` :param help_msg: an optional help message to be used in the raised error in case of validation failure. :param kw_context_args: optional contextual information to store in the exception, and that may be also used to format the help message :return: nothing in case of success. Otherwise, raises a ValidationError """ # backwards compatibility instance_of = instance_of or (kw_context_args.pop('allowed_types') if 'allowed_types' in kw_context_args else None) is_in = is_in or (kw_context_args.pop('allowed_values') if 'allowed_values' in kw_context_args else None) try: # the following corresponds to an inline version of # - _none_rejecter in base.py # - gt/lt in comparables.py # - is_in/contains/subset_of/superset_of/has_length/minlen/maxlen/is_in in collections.py # - instance_of/subclass_of in types.py # try (https://github.com/orf/inliner) to perform the inlining below automatically without code duplication ? # > maybe not because quite dangerous (AST mod) and below we skip the "return True" everywhere for performance # # Another alternative: easy Cython compiling https://github.com/AlanCristhian/statically # > but this is not py2 compliant if value is None: # inlined version of _none_rejecter in base.py if enforce_not_none: raise ValueIsNone(wrong_value=value) # raise MissingMandatoryParameterException('Error, ' + name + '" is mandatory, it should be non-None') # else do nothing and return else: if equals is not None: if value != equals: raise NotEqual(wrong_value=value, ref_value=equals) if instance_of is not None: assert_instance_of(value, instance_of) if subclass_of is not None: assert_subclass_of(value, subclass_of) if is_in is not None: # inlined version of is_in(allowed_values=allowed_values)(value) without 'return True' if value not in is_in: raise NotInAllowedValues(wrong_value=value, allowed_values=is_in) if contains is not None: # inlined version of contains(ref_value=contains)(value) without 'return True' if contains not in value: raise DoesNotContainValue(wrong_value=value, ref_value=contains) if subset_of is not None: # inlined version of is_subset(reference_set=subset_of)(value) missing = value - subset_of if len(missing) != 0: raise NotSubset(wrong_value=value, reference_set=subset_of, unsupported=missing) if superset_of is not None: # inlined version of is_superset(reference_set=superset_of)(value) missing = superset_of - value if len(missing) != 0: raise NotSuperset(wrong_value=value, reference_set=superset_of, missing=missing) if min_value is not None: # inlined version of gt(min_value=min_value, strict=min_strict)(value) without 'return True' if min_strict: if not value > min_value: raise TooSmall(wrong_value=value, min_value=min_value, strict=True) else: if not value >= min_value: raise TooSmall(wrong_value=value, min_value=min_value, strict=False) if max_value is not None: # inlined version of lt(max_value=max_value, strict=max_strict)(value) without 'return True' if max_strict: if not value < max_value: raise TooBig(wrong_value=value, max_value=max_value, strict=True) else: if not value <= max_value: raise TooBig(wrong_value=value, max_value=max_value, strict=False) if length is not None: # inlined version of has_length() without 'return True' if len(value) != length: raise WrongLength(wrong_value=value, ref_length=length) if min_len is not None: # inlined version of minlen(min_length=min_len, strict=min_len_strict)(value) without 'return True' if min_len_strict: if not len(value) > min_len: raise TooShort(wrong_value=value, min_length=min_len, strict=True) else: if not len(value) >= min_len: raise TooShort(wrong_value=value, min_length=min_len, strict=False) if max_len is not None: # inlined version of maxlen(max_length=max_len, strict=max_len_strict)(value) without 'return True' if max_len_strict: if not len(value) < max_len: raise TooLong(wrong_value=value, max_length=max_len, strict=True) else: if not len(value) <= max_len: raise TooLong(wrong_value=value, max_length=max_len, strict=False) except Exception as e: err = _QUICK_VALIDATOR._create_validation_error(name, value, validation_outcome=e, error_type=error_type, help_msg=help_msg, **kw_context_args) raise_(err) if custom is not None: # traditional custom validator assert_valid(name, value, custom, error_type=error_type, help_msg=help_msg, **kw_context_args) else: # basic (and not enough) check to verify that there was no typo leading an argument to be put in kw_context_args if error_type is None and help_msg is None and len(kw_context_args) > 0: raise ValueError("Keyword context arguments have been provided but help_msg and error_type are not: {}" "".format(kw_context_args))
python
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[Type, Tuple[Type]] is_in=None, # type: Container subset_of=None, # type: Set contains = None, # type: Union[Any, Iterable] superset_of=None, # type: Set min_value=None, # type: Any min_strict=False, # type: bool max_value=None, # type: Any max_strict=False, # type: bool length=None, # type: int min_len=None, # type: int min_len_strict=False, # type: bool max_len=None, # type: int max_len_strict=False, # type: bool custom=None, # type: Callable[[Any], Any] error_type=None, # type: Type[ValidationError] help_msg=None, # type: str **kw_context_args): """ 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: * if `allowed_values` is provided, `value` should be in that set * if `min_value` (resp. `max_value`) is provided, `value` should be greater than it. Comparison is not strict by default and can be set to strict by setting `min_strict`, resp. `max_strict`, to `True` * if `min_len` (resp. `max_len`) is provided, `len(value)` should be greater than it. Comparison is not strict by default and can be set to strict by setting `min_len_strict`, resp. `max_len_strict`, to `True` :param name: the applicative name of the checked value, that will be used in error messages :param value: the value to check :param enforce_not_none: boolean, default True. Whether to enforce that `value` is not None. :param equals: an optional value to enforce. :param instance_of: optional type(s) to enforce. If a tuple of types is provided it is considered alternate types: one match is enough to succeed. If None, type will not be enforced :param subclass_of: optional type(s) to enforce. If a tuple of types is provided it is considered alternate types: one match is enough to succeed. If None, type will not be enforced :param is_in: an optional set of allowed values. :param subset_of: an optional superset for the variable :param contains: an optional value that the variable should contain (value in variable == True) :param superset_of: an optional subset for the variable :param min_value: an optional minimum value :param min_strict: if True, only values strictly greater than `min_value` will be accepted :param max_value: an optional maximum value :param max_strict: if True, only values strictly lesser than `max_value` will be accepted :param length: an optional strict length :param min_len: an optional minimum length :param min_len_strict: if True, only values with length strictly greater than `min_len` will be accepted :param max_len: an optional maximum length :param max_len_strict: if True, only values with length strictly lesser than `max_len` will be accepted :param custom: a custom base validation function or list of base validation functions to use. This is the same syntax than for valid8 decorators. 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 implicit `and_`. Tuples indicate an implicit `_failure_raiser`. [mini_lambda](https://smarie.github.io/python-mini-lambda/) expressions can be used instead of callables, they will be transformed to functions automatically. :param error_type: a subclass of `ValidationError` to raise in case of validation failure. By default a `ValidationError` will be raised with the provided `help_msg` :param help_msg: an optional help message to be used in the raised error in case of validation failure. :param kw_context_args: optional contextual information to store in the exception, and that may be also used to format the help message :return: nothing in case of success. Otherwise, raises a ValidationError """ # backwards compatibility instance_of = instance_of or (kw_context_args.pop('allowed_types') if 'allowed_types' in kw_context_args else None) is_in = is_in or (kw_context_args.pop('allowed_values') if 'allowed_values' in kw_context_args else None) try: # the following corresponds to an inline version of # - _none_rejecter in base.py # - gt/lt in comparables.py # - is_in/contains/subset_of/superset_of/has_length/minlen/maxlen/is_in in collections.py # - instance_of/subclass_of in types.py # try (https://github.com/orf/inliner) to perform the inlining below automatically without code duplication ? # > maybe not because quite dangerous (AST mod) and below we skip the "return True" everywhere for performance # # Another alternative: easy Cython compiling https://github.com/AlanCristhian/statically # > but this is not py2 compliant if value is None: # inlined version of _none_rejecter in base.py if enforce_not_none: raise ValueIsNone(wrong_value=value) # raise MissingMandatoryParameterException('Error, ' + name + '" is mandatory, it should be non-None') # else do nothing and return else: if equals is not None: if value != equals: raise NotEqual(wrong_value=value, ref_value=equals) if instance_of is not None: assert_instance_of(value, instance_of) if subclass_of is not None: assert_subclass_of(value, subclass_of) if is_in is not None: # inlined version of is_in(allowed_values=allowed_values)(value) without 'return True' if value not in is_in: raise NotInAllowedValues(wrong_value=value, allowed_values=is_in) if contains is not None: # inlined version of contains(ref_value=contains)(value) without 'return True' if contains not in value: raise DoesNotContainValue(wrong_value=value, ref_value=contains) if subset_of is not None: # inlined version of is_subset(reference_set=subset_of)(value) missing = value - subset_of if len(missing) != 0: raise NotSubset(wrong_value=value, reference_set=subset_of, unsupported=missing) if superset_of is not None: # inlined version of is_superset(reference_set=superset_of)(value) missing = superset_of - value if len(missing) != 0: raise NotSuperset(wrong_value=value, reference_set=superset_of, missing=missing) if min_value is not None: # inlined version of gt(min_value=min_value, strict=min_strict)(value) without 'return True' if min_strict: if not value > min_value: raise TooSmall(wrong_value=value, min_value=min_value, strict=True) else: if not value >= min_value: raise TooSmall(wrong_value=value, min_value=min_value, strict=False) if max_value is not None: # inlined version of lt(max_value=max_value, strict=max_strict)(value) without 'return True' if max_strict: if not value < max_value: raise TooBig(wrong_value=value, max_value=max_value, strict=True) else: if not value <= max_value: raise TooBig(wrong_value=value, max_value=max_value, strict=False) if length is not None: # inlined version of has_length() without 'return True' if len(value) != length: raise WrongLength(wrong_value=value, ref_length=length) if min_len is not None: # inlined version of minlen(min_length=min_len, strict=min_len_strict)(value) without 'return True' if min_len_strict: if not len(value) > min_len: raise TooShort(wrong_value=value, min_length=min_len, strict=True) else: if not len(value) >= min_len: raise TooShort(wrong_value=value, min_length=min_len, strict=False) if max_len is not None: # inlined version of maxlen(max_length=max_len, strict=max_len_strict)(value) without 'return True' if max_len_strict: if not len(value) < max_len: raise TooLong(wrong_value=value, max_length=max_len, strict=True) else: if not len(value) <= max_len: raise TooLong(wrong_value=value, max_length=max_len, strict=False) except Exception as e: err = _QUICK_VALIDATOR._create_validation_error(name, value, validation_outcome=e, error_type=error_type, help_msg=help_msg, **kw_context_args) raise_(err) if custom is not None: # traditional custom validator assert_valid(name, value, custom, error_type=error_type, help_msg=help_msg, **kw_context_args) else: # basic (and not enough) check to verify that there was no typo leading an argument to be put in kw_context_args if error_type is None and help_msg is None and len(kw_context_args) > 0: raise ValueError("Keyword context arguments have been provided but help_msg and error_type are not: {}" "".format(kw_context_args))
[ "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[Type, Tuple[Type]]", "is_in", "=", "None", ",", "# type: Container", "subset_of", "=", "None", ",", "# type: Set", "contains", "=", "None", ",", "# type: Union[Any, Iterable]", "superset_of", "=", "None", ",", "# type: Set", "min_value", "=", "None", ",", "# type: Any", "min_strict", "=", "False", ",", "# type: bool", "max_value", "=", "None", ",", "# type: Any", "max_strict", "=", "False", ",", "# type: bool", "length", "=", "None", ",", "# type: int", "min_len", "=", "None", ",", "# type: int", "min_len_strict", "=", "False", ",", "# type: bool", "max_len", "=", "None", ",", "# type: int", "max_len_strict", "=", "False", ",", "# type: bool", "custom", "=", "None", ",", "# type: Callable[[Any], Any]", "error_type", "=", "None", ",", "# type: Type[ValidationError]", "help_msg", "=", "None", ",", "# type: str", "*", "*", "kw_context_args", ")", ":", "# backwards compatibility", "instance_of", "=", "instance_of", "or", "(", "kw_context_args", ".", "pop", "(", "'allowed_types'", ")", "if", "'allowed_types'", "in", "kw_context_args", "else", "None", ")", "is_in", "=", "is_in", "or", "(", "kw_context_args", ".", "pop", "(", "'allowed_values'", ")", "if", "'allowed_values'", "in", "kw_context_args", "else", "None", ")", "try", ":", "# the following corresponds to an inline version of", "# - _none_rejecter in base.py", "# - gt/lt in comparables.py", "# - is_in/contains/subset_of/superset_of/has_length/minlen/maxlen/is_in in collections.py", "# - instance_of/subclass_of in types.py", "# try (https://github.com/orf/inliner) to perform the inlining below automatically without code duplication ?", "# > maybe not because quite dangerous (AST mod) and below we skip the \"return True\" everywhere for performance", "#", "# Another alternative: easy Cython compiling https://github.com/AlanCristhian/statically", "# > but this is not py2 compliant", "if", "value", "is", "None", ":", "# inlined version of _none_rejecter in base.py", "if", "enforce_not_none", ":", "raise", "ValueIsNone", "(", "wrong_value", "=", "value", ")", "# raise MissingMandatoryParameterException('Error, ' + name + '\" is mandatory, it should be non-None')", "# else do nothing and return", "else", ":", "if", "equals", "is", "not", "None", ":", "if", "value", "!=", "equals", ":", "raise", "NotEqual", "(", "wrong_value", "=", "value", ",", "ref_value", "=", "equals", ")", "if", "instance_of", "is", "not", "None", ":", "assert_instance_of", "(", "value", ",", "instance_of", ")", "if", "subclass_of", "is", "not", "None", ":", "assert_subclass_of", "(", "value", ",", "subclass_of", ")", "if", "is_in", "is", "not", "None", ":", "# inlined version of is_in(allowed_values=allowed_values)(value) without 'return True'", "if", "value", "not", "in", "is_in", ":", "raise", "NotInAllowedValues", "(", "wrong_value", "=", "value", ",", "allowed_values", "=", "is_in", ")", "if", "contains", "is", "not", "None", ":", "# inlined version of contains(ref_value=contains)(value) without 'return True'", "if", "contains", "not", "in", "value", ":", "raise", "DoesNotContainValue", "(", "wrong_value", "=", "value", ",", "ref_value", "=", "contains", ")", "if", "subset_of", "is", "not", "None", ":", "# inlined version of is_subset(reference_set=subset_of)(value)", "missing", "=", "value", "-", "subset_of", "if", "len", "(", "missing", ")", "!=", "0", ":", "raise", "NotSubset", "(", "wrong_value", "=", "value", ",", "reference_set", "=", "subset_of", ",", "unsupported", "=", "missing", ")", "if", "superset_of", "is", "not", "None", ":", "# inlined version of is_superset(reference_set=superset_of)(value)", "missing", "=", "superset_of", "-", "value", "if", "len", "(", "missing", ")", "!=", "0", ":", "raise", "NotSuperset", "(", "wrong_value", "=", "value", ",", "reference_set", "=", "superset_of", ",", "missing", "=", "missing", ")", "if", "min_value", "is", "not", "None", ":", "# inlined version of gt(min_value=min_value, strict=min_strict)(value) without 'return True'", "if", "min_strict", ":", "if", "not", "value", ">", "min_value", ":", "raise", "TooSmall", "(", "wrong_value", "=", "value", ",", "min_value", "=", "min_value", ",", "strict", "=", "True", ")", "else", ":", "if", "not", "value", ">=", "min_value", ":", "raise", "TooSmall", "(", "wrong_value", "=", "value", ",", "min_value", "=", "min_value", ",", "strict", "=", "False", ")", "if", "max_value", "is", "not", "None", ":", "# inlined version of lt(max_value=max_value, strict=max_strict)(value) without 'return True'", "if", "max_strict", ":", "if", "not", "value", "<", "max_value", ":", "raise", "TooBig", "(", "wrong_value", "=", "value", ",", "max_value", "=", "max_value", ",", "strict", "=", "True", ")", "else", ":", "if", "not", "value", "<=", "max_value", ":", "raise", "TooBig", "(", "wrong_value", "=", "value", ",", "max_value", "=", "max_value", ",", "strict", "=", "False", ")", "if", "length", "is", "not", "None", ":", "# inlined version of has_length() without 'return True'", "if", "len", "(", "value", ")", "!=", "length", ":", "raise", "WrongLength", "(", "wrong_value", "=", "value", ",", "ref_length", "=", "length", ")", "if", "min_len", "is", "not", "None", ":", "# inlined version of minlen(min_length=min_len, strict=min_len_strict)(value) without 'return True'", "if", "min_len_strict", ":", "if", "not", "len", "(", "value", ")", ">", "min_len", ":", "raise", "TooShort", "(", "wrong_value", "=", "value", ",", "min_length", "=", "min_len", ",", "strict", "=", "True", ")", "else", ":", "if", "not", "len", "(", "value", ")", ">=", "min_len", ":", "raise", "TooShort", "(", "wrong_value", "=", "value", ",", "min_length", "=", "min_len", ",", "strict", "=", "False", ")", "if", "max_len", "is", "not", "None", ":", "# inlined version of maxlen(max_length=max_len, strict=max_len_strict)(value) without 'return True'", "if", "max_len_strict", ":", "if", "not", "len", "(", "value", ")", "<", "max_len", ":", "raise", "TooLong", "(", "wrong_value", "=", "value", ",", "max_length", "=", "max_len", ",", "strict", "=", "True", ")", "else", ":", "if", "not", "len", "(", "value", ")", "<=", "max_len", ":", "raise", "TooLong", "(", "wrong_value", "=", "value", ",", "max_length", "=", "max_len", ",", "strict", "=", "False", ")", "except", "Exception", "as", "e", ":", "err", "=", "_QUICK_VALIDATOR", ".", "_create_validation_error", "(", "name", ",", "value", ",", "validation_outcome", "=", "e", ",", "error_type", "=", "error_type", ",", "help_msg", "=", "help_msg", ",", "*", "*", "kw_context_args", ")", "raise_", "(", "err", ")", "if", "custom", "is", "not", "None", ":", "# traditional custom validator", "assert_valid", "(", "name", ",", "value", ",", "custom", ",", "error_type", "=", "error_type", ",", "help_msg", "=", "help_msg", ",", "*", "*", "kw_context_args", ")", "else", ":", "# basic (and not enough) check to verify that there was no typo leading an argument to be put in kw_context_args", "if", "error_type", "is", "None", "and", "help_msg", "is", "None", "and", "len", "(", "kw_context_args", ")", ">", "0", ":", "raise", "ValueError", "(", "\"Keyword context arguments have been provided but help_msg and error_type are not: {}\"", "\"\"", ".", "format", "(", "kw_context_args", ")", ")" ]
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: * if `allowed_values` is provided, `value` should be in that set * if `min_value` (resp. `max_value`) is provided, `value` should be greater than it. Comparison is not strict by default and can be set to strict by setting `min_strict`, resp. `max_strict`, to `True` * if `min_len` (resp. `max_len`) is provided, `len(value)` should be greater than it. Comparison is not strict by default and can be set to strict by setting `min_len_strict`, resp. `max_len_strict`, to `True` :param name: the applicative name of the checked value, that will be used in error messages :param value: the value to check :param enforce_not_none: boolean, default True. Whether to enforce that `value` is not None. :param equals: an optional value to enforce. :param instance_of: optional type(s) to enforce. If a tuple of types is provided it is considered alternate types: one match is enough to succeed. If None, type will not be enforced :param subclass_of: optional type(s) to enforce. If a tuple of types is provided it is considered alternate types: one match is enough to succeed. If None, type will not be enforced :param is_in: an optional set of allowed values. :param subset_of: an optional superset for the variable :param contains: an optional value that the variable should contain (value in variable == True) :param superset_of: an optional subset for the variable :param min_value: an optional minimum value :param min_strict: if True, only values strictly greater than `min_value` will be accepted :param max_value: an optional maximum value :param max_strict: if True, only values strictly lesser than `max_value` will be accepted :param length: an optional strict length :param min_len: an optional minimum length :param min_len_strict: if True, only values with length strictly greater than `min_len` will be accepted :param max_len: an optional maximum length :param max_len_strict: if True, only values with length strictly lesser than `max_len` will be accepted :param custom: a custom base validation function or list of base validation functions to use. This is the same syntax than for valid8 decorators. 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 implicit `and_`. Tuples indicate an implicit `_failure_raiser`. [mini_lambda](https://smarie.github.io/python-mini-lambda/) expressions can be used instead of callables, they will be transformed to functions automatically. :param error_type: a subclass of `ValidationError` to raise in case of validation failure. By default a `ValidationError` will be raised with the provided `help_msg` :param help_msg: an optional help message to be used in the raised error in case of validation failure. :param kw_context_args: optional contextual information to store in the exception, and that may be also used to format the help message :return: nothing in case of success. Otherwise, raises a ValidationError
[ "A", "validation", "function", "for", "quick", "inline", "validation", "of", "value", "with", "minimal", "capabilities", ":" ]
train
https://github.com/smarie/python-valid8/blob/5e15d1de11602933c5114eb9f73277ad91d97800/valid8/entry_points_inline.py#L125-L305