repository_name
stringlengths
5
67
func_path_in_repository
stringlengths
4
234
func_name
stringlengths
0
314
whole_func_string
stringlengths
52
3.87M
language
stringclasses
6 values
func_code_string
stringlengths
52
3.87M
func_documentation_string
stringlengths
1
47.2k
func_code_url
stringlengths
85
339
insightindustry/validator-collection
validator_collection/checkers.py
are_equivalent
def are_equivalent(*args, **kwargs): """Indicate if arguments passed to this function are equivalent. .. hint:: This checker operates recursively on the members contained within iterables and :class:`dict <python:dict>` objects. .. caution:: If you only pass one argument to this checker - even if it is an iterable - the checker will *always* return ``True``. To evaluate members of an iterable for equivalence, you should instead unpack the iterable into the function like so: .. code-block:: python obj = [1, 1, 1, 2] result = are_equivalent(*obj) # Will return ``False`` by unpacking and evaluating the iterable's members result = are_equivalent(obj) # Will always return True :param args: One or more values, passed as positional arguments. :returns: ``True`` if ``args`` are equivalent, and ``False`` if not. :rtype: :class:`bool <python:bool>` :raises SyntaxError: if ``kwargs`` contains duplicate keyword parameters or duplicates keyword parameters passed to the underlying validator """ if len(args) == 1: return True first_item = args[0] for item in args[1:]: if type(item) != type(first_item): # pylint: disable=C0123 return False if isinstance(item, dict): if not are_dicts_equivalent(item, first_item): return False elif hasattr(item, '__iter__') and not isinstance(item, (str, bytes, dict)): if len(item) != len(first_item): return False for value in item: if value not in first_item: return False for value in first_item: if value not in item: return False else: if item != first_item: return False return True
python
def are_equivalent(*args, **kwargs): """Indicate if arguments passed to this function are equivalent. .. hint:: This checker operates recursively on the members contained within iterables and :class:`dict <python:dict>` objects. .. caution:: If you only pass one argument to this checker - even if it is an iterable - the checker will *always* return ``True``. To evaluate members of an iterable for equivalence, you should instead unpack the iterable into the function like so: .. code-block:: python obj = [1, 1, 1, 2] result = are_equivalent(*obj) # Will return ``False`` by unpacking and evaluating the iterable's members result = are_equivalent(obj) # Will always return True :param args: One or more values, passed as positional arguments. :returns: ``True`` if ``args`` are equivalent, and ``False`` if not. :rtype: :class:`bool <python:bool>` :raises SyntaxError: if ``kwargs`` contains duplicate keyword parameters or duplicates keyword parameters passed to the underlying validator """ if len(args) == 1: return True first_item = args[0] for item in args[1:]: if type(item) != type(first_item): # pylint: disable=C0123 return False if isinstance(item, dict): if not are_dicts_equivalent(item, first_item): return False elif hasattr(item, '__iter__') and not isinstance(item, (str, bytes, dict)): if len(item) != len(first_item): return False for value in item: if value not in first_item: return False for value in first_item: if value not in item: return False else: if item != first_item: return False return True
Indicate if arguments passed to this function are equivalent. .. hint:: This checker operates recursively on the members contained within iterables and :class:`dict <python:dict>` objects. .. caution:: If you only pass one argument to this checker - even if it is an iterable - the checker will *always* return ``True``. To evaluate members of an iterable for equivalence, you should instead unpack the iterable into the function like so: .. code-block:: python obj = [1, 1, 1, 2] result = are_equivalent(*obj) # Will return ``False`` by unpacking and evaluating the iterable's members result = are_equivalent(obj) # Will always return True :param args: One or more values, passed as positional arguments. :returns: ``True`` if ``args`` are equivalent, and ``False`` if not. :rtype: :class:`bool <python:bool>` :raises SyntaxError: if ``kwargs`` contains duplicate keyword parameters or duplicates keyword parameters passed to the underlying validator
https://github.com/insightindustry/validator-collection/blob/8c8047a0fa36cc88a021771279898278c4cc98e3/validator_collection/checkers.py#L89-L148
insightindustry/validator-collection
validator_collection/checkers.py
are_dicts_equivalent
def are_dicts_equivalent(*args, **kwargs): """Indicate if :ref:`dicts <python:dict>` passed to this function have identical keys and values. :param args: One or more values, passed as positional arguments. :returns: ``True`` if ``args`` have identical keys/values, and ``False`` if not. :rtype: :class:`bool <python:bool>` :raises SyntaxError: if ``kwargs`` contains duplicate keyword parameters or duplicates keyword parameters passed to the underlying validator """ # pylint: disable=too-many-return-statements if not args: return False if len(args) == 1: return True if not all(is_dict(x) for x in args): return False first_item = args[0] for item in args[1:]: if len(item) != len(first_item): return False for key in item: if key not in first_item: return False if not are_equivalent(item[key], first_item[key]): return False for key in first_item: if key not in item: return False if not are_equivalent(first_item[key], item[key]): return False return True
python
def are_dicts_equivalent(*args, **kwargs): """Indicate if :ref:`dicts <python:dict>` passed to this function have identical keys and values. :param args: One or more values, passed as positional arguments. :returns: ``True`` if ``args`` have identical keys/values, and ``False`` if not. :rtype: :class:`bool <python:bool>` :raises SyntaxError: if ``kwargs`` contains duplicate keyword parameters or duplicates keyword parameters passed to the underlying validator """ # pylint: disable=too-many-return-statements if not args: return False if len(args) == 1: return True if not all(is_dict(x) for x in args): return False first_item = args[0] for item in args[1:]: if len(item) != len(first_item): return False for key in item: if key not in first_item: return False if not are_equivalent(item[key], first_item[key]): return False for key in first_item: if key not in item: return False if not are_equivalent(first_item[key], item[key]): return False return True
Indicate if :ref:`dicts <python:dict>` passed to this function have identical keys and values. :param args: One or more values, passed as positional arguments. :returns: ``True`` if ``args`` have identical keys/values, and ``False`` if not. :rtype: :class:`bool <python:bool>` :raises SyntaxError: if ``kwargs`` contains duplicate keyword parameters or duplicates keyword parameters passed to the underlying validator
https://github.com/insightindustry/validator-collection/blob/8c8047a0fa36cc88a021771279898278c4cc98e3/validator_collection/checkers.py#L152-L194
insightindustry/validator-collection
validator_collection/checkers.py
is_between
def is_between(value, minimum = None, maximum = None, **kwargs): """Indicate whether ``value`` is greater than or equal to a supplied ``minimum`` and/or less than or equal to ``maximum``. .. note:: This function works on any ``value`` that support comparison operators, whether they are numbers or not. Technically, this means that ``value``, ``minimum``, or ``maximum`` need to implement the Python magic methods :func:`__lte__ <python:object.__lte__>` and :func:`__gte__ <python:object.__gte__>`. If ``value``, ``minimum``, or ``maximum`` do not support comparison operators, they will raise :class:`NotImplemented <python:NotImplemented>`. :param value: The ``value`` to check. :type value: anything that supports comparison operators :param minimum: If supplied, will return ``True`` if ``value`` is greater than or equal to this value. :type minimum: anything that supports comparison operators / :obj:`None <python:None>` :param maximum: If supplied, will return ``True`` if ``value`` is less than or equal to this value. :type maximum: anything that supports comparison operators / :obj:`None <python:None>` :returns: ``True`` if ``value`` is greater than or equal to a supplied ``minimum`` and less than or equal to a supplied ``maximum``. Otherwise, returns ``False``. :rtype: :class:`bool <python:bool>` :raises SyntaxError: if ``kwargs`` contains duplicate keyword parameters or duplicates keyword parameters passed to the underlying validator :raises NotImplemented: if ``value``, ``minimum``, or ``maximum`` do not support comparison operators :raises ValueError: if both ``minimum`` and ``maximum`` are :obj:`None <python:None>` """ if minimum is None and maximum is None: raise ValueError('minimum and maximum cannot both be None') if value is None: return False if minimum is not None and maximum is None: return value >= minimum elif minimum is None and maximum is not None: return value <= maximum elif minimum is not None and maximum is not None: return value >= minimum and value <= maximum
python
def is_between(value, minimum = None, maximum = None, **kwargs): """Indicate whether ``value`` is greater than or equal to a supplied ``minimum`` and/or less than or equal to ``maximum``. .. note:: This function works on any ``value`` that support comparison operators, whether they are numbers or not. Technically, this means that ``value``, ``minimum``, or ``maximum`` need to implement the Python magic methods :func:`__lte__ <python:object.__lte__>` and :func:`__gte__ <python:object.__gte__>`. If ``value``, ``minimum``, or ``maximum`` do not support comparison operators, they will raise :class:`NotImplemented <python:NotImplemented>`. :param value: The ``value`` to check. :type value: anything that supports comparison operators :param minimum: If supplied, will return ``True`` if ``value`` is greater than or equal to this value. :type minimum: anything that supports comparison operators / :obj:`None <python:None>` :param maximum: If supplied, will return ``True`` if ``value`` is less than or equal to this value. :type maximum: anything that supports comparison operators / :obj:`None <python:None>` :returns: ``True`` if ``value`` is greater than or equal to a supplied ``minimum`` and less than or equal to a supplied ``maximum``. Otherwise, returns ``False``. :rtype: :class:`bool <python:bool>` :raises SyntaxError: if ``kwargs`` contains duplicate keyword parameters or duplicates keyword parameters passed to the underlying validator :raises NotImplemented: if ``value``, ``minimum``, or ``maximum`` do not support comparison operators :raises ValueError: if both ``minimum`` and ``maximum`` are :obj:`None <python:None>` """ if minimum is None and maximum is None: raise ValueError('minimum and maximum cannot both be None') if value is None: return False if minimum is not None and maximum is None: return value >= minimum elif minimum is None and maximum is not None: return value <= maximum elif minimum is not None and maximum is not None: return value >= minimum and value <= maximum
Indicate whether ``value`` is greater than or equal to a supplied ``minimum`` and/or less than or equal to ``maximum``. .. note:: This function works on any ``value`` that support comparison operators, whether they are numbers or not. Technically, this means that ``value``, ``minimum``, or ``maximum`` need to implement the Python magic methods :func:`__lte__ <python:object.__lte__>` and :func:`__gte__ <python:object.__gte__>`. If ``value``, ``minimum``, or ``maximum`` do not support comparison operators, they will raise :class:`NotImplemented <python:NotImplemented>`. :param value: The ``value`` to check. :type value: anything that supports comparison operators :param minimum: If supplied, will return ``True`` if ``value`` is greater than or equal to this value. :type minimum: anything that supports comparison operators / :obj:`None <python:None>` :param maximum: If supplied, will return ``True`` if ``value`` is less than or equal to this value. :type maximum: anything that supports comparison operators / :obj:`None <python:None>` :returns: ``True`` if ``value`` is greater than or equal to a supplied ``minimum`` and less than or equal to a supplied ``maximum``. Otherwise, returns ``False``. :rtype: :class:`bool <python:bool>` :raises SyntaxError: if ``kwargs`` contains duplicate keyword parameters or duplicates keyword parameters passed to the underlying validator :raises NotImplemented: if ``value``, ``minimum``, or ``maximum`` do not support comparison operators :raises ValueError: if both ``minimum`` and ``maximum`` are :obj:`None <python:None>`
https://github.com/insightindustry/validator-collection/blob/8c8047a0fa36cc88a021771279898278c4cc98e3/validator_collection/checkers.py#L198-L251
insightindustry/validator-collection
validator_collection/checkers.py
has_length
def has_length(value, minimum = None, maximum = None, **kwargs): """Indicate whether ``value`` has a length greater than or equal to a supplied ``minimum`` and/or less than or equal to ``maximum``. .. note:: This function works on any ``value`` that supports the :func:`len() <python:len>` operation. This means that ``value`` must implement the :func:`__len__ <python:__len__>` magic method. If ``value`` does not support length evaluation, the checker will raise :class:`NotImplemented <python:NotImplemented>`. :param value: The ``value`` to check. :type value: anything that supports length evaluation :param minimum: If supplied, will return ``True`` if ``value`` is greater than or equal to this value. :type minimum: numeric :param maximum: If supplied, will return ``True`` if ``value`` is less than or equal to this value. :type maximum: numeric :returns: ``True`` if ``value`` has length greater than or equal to a supplied ``minimum`` and less than or equal to a supplied ``maximum``. Otherwise, returns ``False``. :rtype: :class:`bool <python:bool>` :raises SyntaxError: if ``kwargs`` contains duplicate keyword parameters or duplicates keyword parameters passed to the underlying validator :raises TypeError: if ``value`` does not support length evaluation :raises ValueError: if both ``minimum`` and ``maximum`` are :obj:`None <python:None>` """ if minimum is None and maximum is None: raise ValueError('minimum and maximum cannot both be None') length = len(value) minimum = validators.numeric(minimum, allow_empty = True) maximum = validators.numeric(maximum, allow_empty = True) return is_between(length, minimum = minimum, maximum = maximum)
python
def has_length(value, minimum = None, maximum = None, **kwargs): """Indicate whether ``value`` has a length greater than or equal to a supplied ``minimum`` and/or less than or equal to ``maximum``. .. note:: This function works on any ``value`` that supports the :func:`len() <python:len>` operation. This means that ``value`` must implement the :func:`__len__ <python:__len__>` magic method. If ``value`` does not support length evaluation, the checker will raise :class:`NotImplemented <python:NotImplemented>`. :param value: The ``value`` to check. :type value: anything that supports length evaluation :param minimum: If supplied, will return ``True`` if ``value`` is greater than or equal to this value. :type minimum: numeric :param maximum: If supplied, will return ``True`` if ``value`` is less than or equal to this value. :type maximum: numeric :returns: ``True`` if ``value`` has length greater than or equal to a supplied ``minimum`` and less than or equal to a supplied ``maximum``. Otherwise, returns ``False``. :rtype: :class:`bool <python:bool>` :raises SyntaxError: if ``kwargs`` contains duplicate keyword parameters or duplicates keyword parameters passed to the underlying validator :raises TypeError: if ``value`` does not support length evaluation :raises ValueError: if both ``minimum`` and ``maximum`` are :obj:`None <python:None>` """ if minimum is None and maximum is None: raise ValueError('minimum and maximum cannot both be None') length = len(value) minimum = validators.numeric(minimum, allow_empty = True) maximum = validators.numeric(maximum, allow_empty = True) return is_between(length, minimum = minimum, maximum = maximum)
Indicate whether ``value`` has a length greater than or equal to a supplied ``minimum`` and/or less than or equal to ``maximum``. .. note:: This function works on any ``value`` that supports the :func:`len() <python:len>` operation. This means that ``value`` must implement the :func:`__len__ <python:__len__>` magic method. If ``value`` does not support length evaluation, the checker will raise :class:`NotImplemented <python:NotImplemented>`. :param value: The ``value`` to check. :type value: anything that supports length evaluation :param minimum: If supplied, will return ``True`` if ``value`` is greater than or equal to this value. :type minimum: numeric :param maximum: If supplied, will return ``True`` if ``value`` is less than or equal to this value. :type maximum: numeric :returns: ``True`` if ``value`` has length greater than or equal to a supplied ``minimum`` and less than or equal to a supplied ``maximum``. Otherwise, returns ``False``. :rtype: :class:`bool <python:bool>` :raises SyntaxError: if ``kwargs`` contains duplicate keyword parameters or duplicates keyword parameters passed to the underlying validator :raises TypeError: if ``value`` does not support length evaluation :raises ValueError: if both ``minimum`` and ``maximum`` are :obj:`None <python:None>`
https://github.com/insightindustry/validator-collection/blob/8c8047a0fa36cc88a021771279898278c4cc98e3/validator_collection/checkers.py#L255-L305
insightindustry/validator-collection
validator_collection/checkers.py
is_dict
def is_dict(value, **kwargs): """Indicate whether ``value`` is a valid :class:`dict <python:dict>` .. note:: This will return ``True`` even if ``value`` is an empty :class:`dict <python:dict>`. :param value: The value to evaluate. :returns: ``True`` if ``value`` is valid, ``False`` if it is not. :rtype: :class:`bool <python:bool>` :raises SyntaxError: if ``kwargs`` contains duplicate keyword parameters or duplicates keyword parameters passed to the underlying validator """ if isinstance(value, dict): return True try: value = validators.dict(value, **kwargs) except SyntaxError as error: raise error except Exception: return False return True
python
def is_dict(value, **kwargs): """Indicate whether ``value`` is a valid :class:`dict <python:dict>` .. note:: This will return ``True`` even if ``value`` is an empty :class:`dict <python:dict>`. :param value: The value to evaluate. :returns: ``True`` if ``value`` is valid, ``False`` if it is not. :rtype: :class:`bool <python:bool>` :raises SyntaxError: if ``kwargs`` contains duplicate keyword parameters or duplicates keyword parameters passed to the underlying validator """ if isinstance(value, dict): return True try: value = validators.dict(value, **kwargs) except SyntaxError as error: raise error except Exception: return False return True
Indicate whether ``value`` is a valid :class:`dict <python:dict>` .. note:: This will return ``True`` even if ``value`` is an empty :class:`dict <python:dict>`. :param value: The value to evaluate. :returns: ``True`` if ``value`` is valid, ``False`` if it is not. :rtype: :class:`bool <python:bool>` :raises SyntaxError: if ``kwargs`` contains duplicate keyword parameters or duplicates keyword parameters passed to the underlying validator
https://github.com/insightindustry/validator-collection/blob/8c8047a0fa36cc88a021771279898278c4cc98e3/validator_collection/checkers.py#L309-L336
insightindustry/validator-collection
validator_collection/checkers.py
is_json
def is_json(value, schema = None, json_serializer = None, **kwargs): """Indicate whether ``value`` is a valid JSON object. .. note:: ``schema`` supports JSON Schema Drafts 3 - 7. Unless the JSON Schema indicates the meta-schema using a ``$schema`` property, the schema will be assumed to conform to Draft 7. :param value: The value to evaluate. :param schema: An optional JSON schema against which ``value`` will be validated. :type schema: :class:`dict <python:dict>` / :class:`str <python:str>` / :obj:`None <python:None>` :returns: ``True`` if ``value`` is valid, ``False`` if it is not. :rtype: :class:`bool <python:bool>` :raises SyntaxError: if ``kwargs`` contains duplicate keyword parameters or duplicates keyword parameters passed to the underlying validator """ try: value = validators.json(value, schema = schema, json_serializer = json_serializer, **kwargs) except SyntaxError as error: raise error except Exception: return False return True
python
def is_json(value, schema = None, json_serializer = None, **kwargs): """Indicate whether ``value`` is a valid JSON object. .. note:: ``schema`` supports JSON Schema Drafts 3 - 7. Unless the JSON Schema indicates the meta-schema using a ``$schema`` property, the schema will be assumed to conform to Draft 7. :param value: The value to evaluate. :param schema: An optional JSON schema against which ``value`` will be validated. :type schema: :class:`dict <python:dict>` / :class:`str <python:str>` / :obj:`None <python:None>` :returns: ``True`` if ``value`` is valid, ``False`` if it is not. :rtype: :class:`bool <python:bool>` :raises SyntaxError: if ``kwargs`` contains duplicate keyword parameters or duplicates keyword parameters passed to the underlying validator """ try: value = validators.json(value, schema = schema, json_serializer = json_serializer, **kwargs) except SyntaxError as error: raise error except Exception: return False return True
Indicate whether ``value`` is a valid JSON object. .. note:: ``schema`` supports JSON Schema Drafts 3 - 7. Unless the JSON Schema indicates the meta-schema using a ``$schema`` property, the schema will be assumed to conform to Draft 7. :param value: The value to evaluate. :param schema: An optional JSON schema against which ``value`` will be validated. :type schema: :class:`dict <python:dict>` / :class:`str <python:str>` / :obj:`None <python:None>` :returns: ``True`` if ``value`` is valid, ``False`` if it is not. :rtype: :class:`bool <python:bool>` :raises SyntaxError: if ``kwargs`` contains duplicate keyword parameters or duplicates keyword parameters passed to the underlying validator
https://github.com/insightindustry/validator-collection/blob/8c8047a0fa36cc88a021771279898278c4cc98e3/validator_collection/checkers.py#L340-L375
insightindustry/validator-collection
validator_collection/checkers.py
is_string
def is_string(value, coerce_value = False, minimum_length = None, maximum_length = None, whitespace_padding = False, **kwargs): """Indicate whether ``value`` is a string. :param value: The value to evaluate. :param coerce_value: If ``True``, will check whether ``value`` can be coerced to a string if it is not already. Defaults to ``False``. :type coerce_value: :class:`bool <python:bool>` :param minimum_length: If supplied, indicates the minimum number of characters needed to be valid. :type minimum_length: :class:`int <python:int>` :param maximum_length: If supplied, indicates the minimum number of characters needed to be valid. :type maximum_length: :class:`int <python:int>` :param whitespace_padding: If ``True`` and the value is below the ``minimum_length``, pad the value with spaces. Defaults to ``False``. :type whitespace_padding: :class:`bool <python:bool>` :returns: ``True`` if ``value`` is valid, ``False`` if it is not. :rtype: :class:`bool <python:bool>` :raises SyntaxError: if ``kwargs`` contains duplicate keyword parameters or duplicates keyword parameters passed to the underlying validator """ if value is None: return False minimum_length = validators.integer(minimum_length, allow_empty = True, **kwargs) maximum_length = validators.integer(maximum_length, allow_empty = True, **kwargs) if isinstance(value, basestring) and not value: if minimum_length and minimum_length > 0 and not whitespace_padding: return False return True try: value = validators.string(value, coerce_value = coerce_value, minimum_length = minimum_length, maximum_length = maximum_length, whitespace_padding = whitespace_padding, **kwargs) except SyntaxError as error: raise error except Exception: return False return True
python
def is_string(value, coerce_value = False, minimum_length = None, maximum_length = None, whitespace_padding = False, **kwargs): """Indicate whether ``value`` is a string. :param value: The value to evaluate. :param coerce_value: If ``True``, will check whether ``value`` can be coerced to a string if it is not already. Defaults to ``False``. :type coerce_value: :class:`bool <python:bool>` :param minimum_length: If supplied, indicates the minimum number of characters needed to be valid. :type minimum_length: :class:`int <python:int>` :param maximum_length: If supplied, indicates the minimum number of characters needed to be valid. :type maximum_length: :class:`int <python:int>` :param whitespace_padding: If ``True`` and the value is below the ``minimum_length``, pad the value with spaces. Defaults to ``False``. :type whitespace_padding: :class:`bool <python:bool>` :returns: ``True`` if ``value`` is valid, ``False`` if it is not. :rtype: :class:`bool <python:bool>` :raises SyntaxError: if ``kwargs`` contains duplicate keyword parameters or duplicates keyword parameters passed to the underlying validator """ if value is None: return False minimum_length = validators.integer(minimum_length, allow_empty = True, **kwargs) maximum_length = validators.integer(maximum_length, allow_empty = True, **kwargs) if isinstance(value, basestring) and not value: if minimum_length and minimum_length > 0 and not whitespace_padding: return False return True try: value = validators.string(value, coerce_value = coerce_value, minimum_length = minimum_length, maximum_length = maximum_length, whitespace_padding = whitespace_padding, **kwargs) except SyntaxError as error: raise error except Exception: return False return True
Indicate whether ``value`` is a string. :param value: The value to evaluate. :param coerce_value: If ``True``, will check whether ``value`` can be coerced to a string if it is not already. Defaults to ``False``. :type coerce_value: :class:`bool <python:bool>` :param minimum_length: If supplied, indicates the minimum number of characters needed to be valid. :type minimum_length: :class:`int <python:int>` :param maximum_length: If supplied, indicates the minimum number of characters needed to be valid. :type maximum_length: :class:`int <python:int>` :param whitespace_padding: If ``True`` and the value is below the ``minimum_length``, pad the value with spaces. Defaults to ``False``. :type whitespace_padding: :class:`bool <python:bool>` :returns: ``True`` if ``value`` is valid, ``False`` if it is not. :rtype: :class:`bool <python:bool>` :raises SyntaxError: if ``kwargs`` contains duplicate keyword parameters or duplicates keyword parameters passed to the underlying validator
https://github.com/insightindustry/validator-collection/blob/8c8047a0fa36cc88a021771279898278c4cc98e3/validator_collection/checkers.py#L379-L436
insightindustry/validator-collection
validator_collection/checkers.py
is_iterable
def is_iterable(obj, forbid_literals = (str, bytes), minimum_length = None, maximum_length = None, **kwargs): """Indicate whether ``obj`` is iterable. :param forbid_literals: A collection of literals that will be considered invalid even if they are (actually) iterable. Defaults to a :class:`tuple <python:tuple>` containing :class:`str <python:str>` and :class:`bytes <python:bytes>`. :type forbid_literals: iterable :param minimum_length: If supplied, indicates the minimum number of members needed to be valid. :type minimum_length: :class:`int <python:int>` :param maximum_length: If supplied, indicates the minimum number of members needed to be valid. :type maximum_length: :class:`int <python:int>` :returns: ``True`` if ``obj`` is a valid iterable, ``False`` if not. :rtype: :class:`bool <python:bool>` :raises SyntaxError: if ``kwargs`` contains duplicate keyword parameters or duplicates keyword parameters passed to the underlying validator """ if obj is None: return False if obj in forbid_literals: return False try: obj = validators.iterable(obj, allow_empty = True, forbid_literals = forbid_literals, minimum_length = minimum_length, maximum_length = maximum_length, **kwargs) except SyntaxError as error: raise error except Exception: return False return True
python
def is_iterable(obj, forbid_literals = (str, bytes), minimum_length = None, maximum_length = None, **kwargs): """Indicate whether ``obj`` is iterable. :param forbid_literals: A collection of literals that will be considered invalid even if they are (actually) iterable. Defaults to a :class:`tuple <python:tuple>` containing :class:`str <python:str>` and :class:`bytes <python:bytes>`. :type forbid_literals: iterable :param minimum_length: If supplied, indicates the minimum number of members needed to be valid. :type minimum_length: :class:`int <python:int>` :param maximum_length: If supplied, indicates the minimum number of members needed to be valid. :type maximum_length: :class:`int <python:int>` :returns: ``True`` if ``obj`` is a valid iterable, ``False`` if not. :rtype: :class:`bool <python:bool>` :raises SyntaxError: if ``kwargs`` contains duplicate keyword parameters or duplicates keyword parameters passed to the underlying validator """ if obj is None: return False if obj in forbid_literals: return False try: obj = validators.iterable(obj, allow_empty = True, forbid_literals = forbid_literals, minimum_length = minimum_length, maximum_length = maximum_length, **kwargs) except SyntaxError as error: raise error except Exception: return False return True
Indicate whether ``obj`` is iterable. :param forbid_literals: A collection of literals that will be considered invalid even if they are (actually) iterable. Defaults to a :class:`tuple <python:tuple>` containing :class:`str <python:str>` and :class:`bytes <python:bytes>`. :type forbid_literals: iterable :param minimum_length: If supplied, indicates the minimum number of members needed to be valid. :type minimum_length: :class:`int <python:int>` :param maximum_length: If supplied, indicates the minimum number of members needed to be valid. :type maximum_length: :class:`int <python:int>` :returns: ``True`` if ``obj`` is a valid iterable, ``False`` if not. :rtype: :class:`bool <python:bool>` :raises SyntaxError: if ``kwargs`` contains duplicate keyword parameters or duplicates keyword parameters passed to the underlying validator
https://github.com/insightindustry/validator-collection/blob/8c8047a0fa36cc88a021771279898278c4cc98e3/validator_collection/checkers.py#L440-L485
insightindustry/validator-collection
validator_collection/checkers.py
is_not_empty
def is_not_empty(value, **kwargs): """Indicate whether ``value`` is empty. :param value: The value to evaluate. :returns: ``True`` if ``value`` is empty, ``False`` if it is not. :rtype: :class:`bool <python:bool>` :raises SyntaxError: if ``kwargs`` contains duplicate keyword parameters or duplicates keyword parameters passed to the underlying validator """ try: value = validators.not_empty(value, **kwargs) except SyntaxError as error: raise error except Exception: return False return True
python
def is_not_empty(value, **kwargs): """Indicate whether ``value`` is empty. :param value: The value to evaluate. :returns: ``True`` if ``value`` is empty, ``False`` if it is not. :rtype: :class:`bool <python:bool>` :raises SyntaxError: if ``kwargs`` contains duplicate keyword parameters or duplicates keyword parameters passed to the underlying validator """ try: value = validators.not_empty(value, **kwargs) except SyntaxError as error: raise error except Exception: return False return True
Indicate whether ``value`` is empty. :param value: The value to evaluate. :returns: ``True`` if ``value`` is empty, ``False`` if it is not. :rtype: :class:`bool <python:bool>` :raises SyntaxError: if ``kwargs`` contains duplicate keyword parameters or duplicates keyword parameters passed to the underlying validator
https://github.com/insightindustry/validator-collection/blob/8c8047a0fa36cc88a021771279898278c4cc98e3/validator_collection/checkers.py#L489-L508
insightindustry/validator-collection
validator_collection/checkers.py
is_none
def is_none(value, allow_empty = False, **kwargs): """Indicate whether ``value`` is :obj:`None <python:None>`. :param value: The value to evaluate. :param allow_empty: If ``True``, accepts falsey values as equivalent to :obj:`None <python:None>`. Defaults to ``False``. :type allow_empty: :class:`bool <python:bool>` :returns: ``True`` if ``value`` is :obj:`None <python:None>`, ``False`` if it is not. :rtype: :class:`bool <python:bool>` :raises SyntaxError: if ``kwargs`` contains duplicate keyword parameters or duplicates keyword parameters passed to the underlying validator """ try: validators.none(value, allow_empty = allow_empty, **kwargs) except SyntaxError as error: raise error except Exception: return False return True
python
def is_none(value, allow_empty = False, **kwargs): """Indicate whether ``value`` is :obj:`None <python:None>`. :param value: The value to evaluate. :param allow_empty: If ``True``, accepts falsey values as equivalent to :obj:`None <python:None>`. Defaults to ``False``. :type allow_empty: :class:`bool <python:bool>` :returns: ``True`` if ``value`` is :obj:`None <python:None>`, ``False`` if it is not. :rtype: :class:`bool <python:bool>` :raises SyntaxError: if ``kwargs`` contains duplicate keyword parameters or duplicates keyword parameters passed to the underlying validator """ try: validators.none(value, allow_empty = allow_empty, **kwargs) except SyntaxError as error: raise error except Exception: return False return True
Indicate whether ``value`` is :obj:`None <python:None>`. :param value: The value to evaluate. :param allow_empty: If ``True``, accepts falsey values as equivalent to :obj:`None <python:None>`. Defaults to ``False``. :type allow_empty: :class:`bool <python:bool>` :returns: ``True`` if ``value`` is :obj:`None <python:None>`, ``False`` if it is not. :rtype: :class:`bool <python:bool>` :raises SyntaxError: if ``kwargs`` contains duplicate keyword parameters or duplicates keyword parameters passed to the underlying validator
https://github.com/insightindustry/validator-collection/blob/8c8047a0fa36cc88a021771279898278c4cc98e3/validator_collection/checkers.py#L512-L536
insightindustry/validator-collection
validator_collection/checkers.py
is_variable_name
def is_variable_name(value, **kwargs): """Indicate whether ``value`` is a valid Python variable name. .. caution:: This function does **NOT** check whether the variable exists. It only checks that the ``value`` would work as a Python variable (or class, or function, etc.) name. :param value: The value to evaluate. :returns: ``True`` if ``value`` is valid, ``False`` if it is not. :rtype: :class:`bool <python:bool>` :raises SyntaxError: if ``kwargs`` contains duplicate keyword parameters or duplicates keyword parameters passed to the underlying validator """ try: validators.variable_name(value, **kwargs) except SyntaxError as error: raise error except Exception: return False return True
python
def is_variable_name(value, **kwargs): """Indicate whether ``value`` is a valid Python variable name. .. caution:: This function does **NOT** check whether the variable exists. It only checks that the ``value`` would work as a Python variable (or class, or function, etc.) name. :param value: The value to evaluate. :returns: ``True`` if ``value`` is valid, ``False`` if it is not. :rtype: :class:`bool <python:bool>` :raises SyntaxError: if ``kwargs`` contains duplicate keyword parameters or duplicates keyword parameters passed to the underlying validator """ try: validators.variable_name(value, **kwargs) except SyntaxError as error: raise error except Exception: return False return True
Indicate whether ``value`` is a valid Python variable name. .. caution:: This function does **NOT** check whether the variable exists. It only checks that the ``value`` would work as a Python variable (or class, or function, etc.) name. :param value: The value to evaluate. :returns: ``True`` if ``value`` is valid, ``False`` if it is not. :rtype: :class:`bool <python:bool>` :raises SyntaxError: if ``kwargs`` contains duplicate keyword parameters or duplicates keyword parameters passed to the underlying validator
https://github.com/insightindustry/validator-collection/blob/8c8047a0fa36cc88a021771279898278c4cc98e3/validator_collection/checkers.py#L540-L565
insightindustry/validator-collection
validator_collection/checkers.py
is_uuid
def is_uuid(value, **kwargs): """Indicate whether ``value`` contains a :class:`UUID <python:uuid.UUID>` :param value: The value to evaluate. :returns: ``True`` if ``value`` is valid, ``False`` if it is not. :rtype: :class:`bool <python:bool>` :raises SyntaxError: if ``kwargs`` contains duplicate keyword parameters or duplicates keyword parameters passed to the underlying validator """ try: validators.uuid(value, **kwargs) except SyntaxError as error: raise error except Exception: return False return True
python
def is_uuid(value, **kwargs): """Indicate whether ``value`` contains a :class:`UUID <python:uuid.UUID>` :param value: The value to evaluate. :returns: ``True`` if ``value`` is valid, ``False`` if it is not. :rtype: :class:`bool <python:bool>` :raises SyntaxError: if ``kwargs`` contains duplicate keyword parameters or duplicates keyword parameters passed to the underlying validator """ try: validators.uuid(value, **kwargs) except SyntaxError as error: raise error except Exception: return False return True
Indicate whether ``value`` contains a :class:`UUID <python:uuid.UUID>` :param value: The value to evaluate. :returns: ``True`` if ``value`` is valid, ``False`` if it is not. :rtype: :class:`bool <python:bool>` :raises SyntaxError: if ``kwargs`` contains duplicate keyword parameters or duplicates keyword parameters passed to the underlying validator
https://github.com/insightindustry/validator-collection/blob/8c8047a0fa36cc88a021771279898278c4cc98e3/validator_collection/checkers.py#L585-L604
insightindustry/validator-collection
validator_collection/checkers.py
is_date
def is_date(value, minimum = None, maximum = None, coerce_value = False, **kwargs): """Indicate whether ``value`` is a :class:`date <python:datetime.date>`. :param value: The value to evaluate. :param minimum: If supplied, will make sure that ``value`` is on or after this value. :type minimum: :class:`datetime <python:datetime.datetime>` / :class:`date <python:datetime.date>` / compliant :class:`str <python:str>` / :obj:`None <python:None>` :param maximum: If supplied, will make sure that ``value`` is on or before this value. :type maximum: :class:`datetime <python:datetime.datetime>` / :class:`date <python:datetime.date>` / compliant :class:`str <python:str>` / :obj:`None <python:None>` :param coerce_value: If ``True``, will return ``True`` if ``value`` can be coerced to a :class:`date <python:datetime.date>`. If ``False``, will only return ``True`` if ``value`` is a date value only. Defaults to ``False``. :type coerce_value: :class:`bool <python:bool>` :returns: ``True`` if ``value`` is valid, ``False`` if it is not. :rtype: :class:`bool <python:bool>` :raises SyntaxError: if ``kwargs`` contains duplicate keyword parameters or duplicates keyword parameters passed to the underlying validator """ try: value = validators.date(value, minimum = minimum, maximum = maximum, coerce_value = coerce_value, **kwargs) except SyntaxError as error: raise error except Exception: return False return True
python
def is_date(value, minimum = None, maximum = None, coerce_value = False, **kwargs): """Indicate whether ``value`` is a :class:`date <python:datetime.date>`. :param value: The value to evaluate. :param minimum: If supplied, will make sure that ``value`` is on or after this value. :type minimum: :class:`datetime <python:datetime.datetime>` / :class:`date <python:datetime.date>` / compliant :class:`str <python:str>` / :obj:`None <python:None>` :param maximum: If supplied, will make sure that ``value`` is on or before this value. :type maximum: :class:`datetime <python:datetime.datetime>` / :class:`date <python:datetime.date>` / compliant :class:`str <python:str>` / :obj:`None <python:None>` :param coerce_value: If ``True``, will return ``True`` if ``value`` can be coerced to a :class:`date <python:datetime.date>`. If ``False``, will only return ``True`` if ``value`` is a date value only. Defaults to ``False``. :type coerce_value: :class:`bool <python:bool>` :returns: ``True`` if ``value`` is valid, ``False`` if it is not. :rtype: :class:`bool <python:bool>` :raises SyntaxError: if ``kwargs`` contains duplicate keyword parameters or duplicates keyword parameters passed to the underlying validator """ try: value = validators.date(value, minimum = minimum, maximum = maximum, coerce_value = coerce_value, **kwargs) except SyntaxError as error: raise error except Exception: return False return True
Indicate whether ``value`` is a :class:`date <python:datetime.date>`. :param value: The value to evaluate. :param minimum: If supplied, will make sure that ``value`` is on or after this value. :type minimum: :class:`datetime <python:datetime.datetime>` / :class:`date <python:datetime.date>` / compliant :class:`str <python:str>` / :obj:`None <python:None>` :param maximum: If supplied, will make sure that ``value`` is on or before this value. :type maximum: :class:`datetime <python:datetime.datetime>` / :class:`date <python:datetime.date>` / compliant :class:`str <python:str>` / :obj:`None <python:None>` :param coerce_value: If ``True``, will return ``True`` if ``value`` can be coerced to a :class:`date <python:datetime.date>`. If ``False``, will only return ``True`` if ``value`` is a date value only. Defaults to ``False``. :type coerce_value: :class:`bool <python:bool>` :returns: ``True`` if ``value`` is valid, ``False`` if it is not. :rtype: :class:`bool <python:bool>` :raises SyntaxError: if ``kwargs`` contains duplicate keyword parameters or duplicates keyword parameters passed to the underlying validator
https://github.com/insightindustry/validator-collection/blob/8c8047a0fa36cc88a021771279898278c4cc98e3/validator_collection/checkers.py#L610-L655
insightindustry/validator-collection
validator_collection/checkers.py
is_datetime
def is_datetime(value, minimum = None, maximum = None, coerce_value = False, **kwargs): """Indicate whether ``value`` is a :class:`datetime <python:datetime.datetime>`. :param value: The value to evaluate. :param minimum: If supplied, will make sure that ``value`` is on or after this value. :type minimum: :class:`datetime <python:datetime.datetime>` / :class:`date <python:datetime.date>` / compliant :class:`str <python:str>` / :obj:`None <python:None>` :param maximum: If supplied, will make sure that ``value`` is on or before this value. :type maximum: :class:`datetime <python:datetime.datetime>` / :class:`date <python:datetime.date>` / compliant :class:`str <python:str>` / :obj:`None <python:None>` :param coerce_value: If ``True``, will return ``True`` if ``value`` can be coerced to a :class:`datetime <python:datetime.datetime>`. If ``False``, will only return ``True`` if ``value`` is a complete timestamp. Defaults to ``False``. :type coerce_value: :class:`bool <python:bool>` :returns: ``True`` if ``value`` is valid, ``False`` if it is not. :rtype: :class:`bool <python:bool>` :raises SyntaxError: if ``kwargs`` contains duplicate keyword parameters or duplicates keyword parameters passed to the underlying validator """ try: value = validators.datetime(value, minimum = minimum, maximum = maximum, coerce_value = coerce_value, **kwargs) except SyntaxError as error: raise error except Exception: return False return True
python
def is_datetime(value, minimum = None, maximum = None, coerce_value = False, **kwargs): """Indicate whether ``value`` is a :class:`datetime <python:datetime.datetime>`. :param value: The value to evaluate. :param minimum: If supplied, will make sure that ``value`` is on or after this value. :type minimum: :class:`datetime <python:datetime.datetime>` / :class:`date <python:datetime.date>` / compliant :class:`str <python:str>` / :obj:`None <python:None>` :param maximum: If supplied, will make sure that ``value`` is on or before this value. :type maximum: :class:`datetime <python:datetime.datetime>` / :class:`date <python:datetime.date>` / compliant :class:`str <python:str>` / :obj:`None <python:None>` :param coerce_value: If ``True``, will return ``True`` if ``value`` can be coerced to a :class:`datetime <python:datetime.datetime>`. If ``False``, will only return ``True`` if ``value`` is a complete timestamp. Defaults to ``False``. :type coerce_value: :class:`bool <python:bool>` :returns: ``True`` if ``value`` is valid, ``False`` if it is not. :rtype: :class:`bool <python:bool>` :raises SyntaxError: if ``kwargs`` contains duplicate keyword parameters or duplicates keyword parameters passed to the underlying validator """ try: value = validators.datetime(value, minimum = minimum, maximum = maximum, coerce_value = coerce_value, **kwargs) except SyntaxError as error: raise error except Exception: return False return True
Indicate whether ``value`` is a :class:`datetime <python:datetime.datetime>`. :param value: The value to evaluate. :param minimum: If supplied, will make sure that ``value`` is on or after this value. :type minimum: :class:`datetime <python:datetime.datetime>` / :class:`date <python:datetime.date>` / compliant :class:`str <python:str>` / :obj:`None <python:None>` :param maximum: If supplied, will make sure that ``value`` is on or before this value. :type maximum: :class:`datetime <python:datetime.datetime>` / :class:`date <python:datetime.date>` / compliant :class:`str <python:str>` / :obj:`None <python:None>` :param coerce_value: If ``True``, will return ``True`` if ``value`` can be coerced to a :class:`datetime <python:datetime.datetime>`. If ``False``, will only return ``True`` if ``value`` is a complete timestamp. Defaults to ``False``. :type coerce_value: :class:`bool <python:bool>` :returns: ``True`` if ``value`` is valid, ``False`` if it is not. :rtype: :class:`bool <python:bool>` :raises SyntaxError: if ``kwargs`` contains duplicate keyword parameters or duplicates keyword parameters passed to the underlying validator
https://github.com/insightindustry/validator-collection/blob/8c8047a0fa36cc88a021771279898278c4cc98e3/validator_collection/checkers.py#L659-L704
insightindustry/validator-collection
validator_collection/checkers.py
is_time
def is_time(value, minimum = None, maximum = None, coerce_value = False, **kwargs): """Indicate whether ``value`` is a :class:`time <python:datetime.time>`. :param value: The value to evaluate. :param minimum: If supplied, will make sure that ``value`` is on or after this value. :type minimum: :func:`datetime <validator_collection.validators.datetime>` or :func:`time <validator_collection.validators.time>`-compliant :class:`str <python:str>` / :class:`datetime <python:datetime.datetime>` / :class:`time <python:datetime.time> / numeric / :obj:`None <python:None>` :param maximum: If supplied, will make sure that ``value`` is on or before this value. :type maximum: :func:`datetime <validator_collection.validators.datetime>` or :func:`time <validator_collection.validators.time>`-compliant :class:`str <python:str>` / :class:`datetime <python:datetime.datetime>` / :class:`time <python:datetime.time> / numeric / :obj:`None <python:None>` :param coerce_value: If ``True``, will return ``True`` if ``value`` can be coerced to a :class:`time <python:datetime.time>`. If ``False``, will only return ``True`` if ``value`` is a valid time. Defaults to ``False``. :type coerce_value: :class:`bool <python:bool>` :returns: ``True`` if ``value`` is valid, ``False`` if it is not. :rtype: :class:`bool <python:bool>` :raises SyntaxError: if ``kwargs`` contains duplicate keyword parameters or duplicates keyword parameters passed to the underlying validator """ try: value = validators.time(value, minimum = minimum, maximum = maximum, coerce_value = coerce_value, **kwargs) except SyntaxError as error: raise error except Exception: return False return True
python
def is_time(value, minimum = None, maximum = None, coerce_value = False, **kwargs): """Indicate whether ``value`` is a :class:`time <python:datetime.time>`. :param value: The value to evaluate. :param minimum: If supplied, will make sure that ``value`` is on or after this value. :type minimum: :func:`datetime <validator_collection.validators.datetime>` or :func:`time <validator_collection.validators.time>`-compliant :class:`str <python:str>` / :class:`datetime <python:datetime.datetime>` / :class:`time <python:datetime.time> / numeric / :obj:`None <python:None>` :param maximum: If supplied, will make sure that ``value`` is on or before this value. :type maximum: :func:`datetime <validator_collection.validators.datetime>` or :func:`time <validator_collection.validators.time>`-compliant :class:`str <python:str>` / :class:`datetime <python:datetime.datetime>` / :class:`time <python:datetime.time> / numeric / :obj:`None <python:None>` :param coerce_value: If ``True``, will return ``True`` if ``value`` can be coerced to a :class:`time <python:datetime.time>`. If ``False``, will only return ``True`` if ``value`` is a valid time. Defaults to ``False``. :type coerce_value: :class:`bool <python:bool>` :returns: ``True`` if ``value`` is valid, ``False`` if it is not. :rtype: :class:`bool <python:bool>` :raises SyntaxError: if ``kwargs`` contains duplicate keyword parameters or duplicates keyword parameters passed to the underlying validator """ try: value = validators.time(value, minimum = minimum, maximum = maximum, coerce_value = coerce_value, **kwargs) except SyntaxError as error: raise error except Exception: return False return True
Indicate whether ``value`` is a :class:`time <python:datetime.time>`. :param value: The value to evaluate. :param minimum: If supplied, will make sure that ``value`` is on or after this value. :type minimum: :func:`datetime <validator_collection.validators.datetime>` or :func:`time <validator_collection.validators.time>`-compliant :class:`str <python:str>` / :class:`datetime <python:datetime.datetime>` / :class:`time <python:datetime.time> / numeric / :obj:`None <python:None>` :param maximum: If supplied, will make sure that ``value`` is on or before this value. :type maximum: :func:`datetime <validator_collection.validators.datetime>` or :func:`time <validator_collection.validators.time>`-compliant :class:`str <python:str>` / :class:`datetime <python:datetime.datetime>` / :class:`time <python:datetime.time> / numeric / :obj:`None <python:None>` :param coerce_value: If ``True``, will return ``True`` if ``value`` can be coerced to a :class:`time <python:datetime.time>`. If ``False``, will only return ``True`` if ``value`` is a valid time. Defaults to ``False``. :type coerce_value: :class:`bool <python:bool>` :returns: ``True`` if ``value`` is valid, ``False`` if it is not. :rtype: :class:`bool <python:bool>` :raises SyntaxError: if ``kwargs`` contains duplicate keyword parameters or duplicates keyword parameters passed to the underlying validator
https://github.com/insightindustry/validator-collection/blob/8c8047a0fa36cc88a021771279898278c4cc98e3/validator_collection/checkers.py#L708-L754
insightindustry/validator-collection
validator_collection/checkers.py
is_timezone
def is_timezone(value, positive = True, **kwargs): """Indicate whether ``value`` is a :class:`tzinfo <python:datetime.tzinfo>`. .. caution:: This does **not** validate whether the value is a timezone that actually exists, nor can it resolve timzone names (e.g. ``'Eastern'`` or ``'CET'``). For that kind of functionality, we recommend you utilize: `pytz <https://pypi.python.org/pypi/pytz>`_ :param value: The value to evaluate. :param positive: Indicates whether the ``value`` is positive or negative (only has meaning if ``value`` is a string). Defaults to ``True``. :type positive: :class:`bool <python:bool>` :returns: ``True`` if ``value`` is valid, ``False`` if it is not. :rtype: :class:`bool <python:bool>` :raises SyntaxError: if ``kwargs`` contains duplicate keyword parameters or duplicates keyword parameters passed to the underlying validator """ try: value = validators.timezone(value, positive = positive, **kwargs) except SyntaxError as error: raise error except Exception: return False return True
python
def is_timezone(value, positive = True, **kwargs): """Indicate whether ``value`` is a :class:`tzinfo <python:datetime.tzinfo>`. .. caution:: This does **not** validate whether the value is a timezone that actually exists, nor can it resolve timzone names (e.g. ``'Eastern'`` or ``'CET'``). For that kind of functionality, we recommend you utilize: `pytz <https://pypi.python.org/pypi/pytz>`_ :param value: The value to evaluate. :param positive: Indicates whether the ``value`` is positive or negative (only has meaning if ``value`` is a string). Defaults to ``True``. :type positive: :class:`bool <python:bool>` :returns: ``True`` if ``value`` is valid, ``False`` if it is not. :rtype: :class:`bool <python:bool>` :raises SyntaxError: if ``kwargs`` contains duplicate keyword parameters or duplicates keyword parameters passed to the underlying validator """ try: value = validators.timezone(value, positive = positive, **kwargs) except SyntaxError as error: raise error except Exception: return False return True
Indicate whether ``value`` is a :class:`tzinfo <python:datetime.tzinfo>`. .. caution:: This does **not** validate whether the value is a timezone that actually exists, nor can it resolve timzone names (e.g. ``'Eastern'`` or ``'CET'``). For that kind of functionality, we recommend you utilize: `pytz <https://pypi.python.org/pypi/pytz>`_ :param value: The value to evaluate. :param positive: Indicates whether the ``value`` is positive or negative (only has meaning if ``value`` is a string). Defaults to ``True``. :type positive: :class:`bool <python:bool>` :returns: ``True`` if ``value`` is valid, ``False`` if it is not. :rtype: :class:`bool <python:bool>` :raises SyntaxError: if ``kwargs`` contains duplicate keyword parameters or duplicates keyword parameters passed to the underlying validator
https://github.com/insightindustry/validator-collection/blob/8c8047a0fa36cc88a021771279898278c4cc98e3/validator_collection/checkers.py#L758-L793
insightindustry/validator-collection
validator_collection/checkers.py
is_numeric
def is_numeric(value, minimum = None, maximum = None, **kwargs): """Indicate whether ``value`` is a numeric value. :param value: The value to evaluate. :param minimum: If supplied, will make sure that ``value`` is greater than or equal to this value. :type minimum: numeric :param maximum: If supplied, will make sure that ``value`` is less than or equal to this value. :type maximum: numeric :returns: ``True`` if ``value`` is valid, ``False`` if it is not. :rtype: :class:`bool <python:bool>` :raises SyntaxError: if ``kwargs`` contains duplicate keyword parameters or duplicates keyword parameters passed to the underlying validator """ try: value = validators.numeric(value, minimum = minimum, maximum = maximum, **kwargs) except SyntaxError as error: raise error except Exception: return False return True
python
def is_numeric(value, minimum = None, maximum = None, **kwargs): """Indicate whether ``value`` is a numeric value. :param value: The value to evaluate. :param minimum: If supplied, will make sure that ``value`` is greater than or equal to this value. :type minimum: numeric :param maximum: If supplied, will make sure that ``value`` is less than or equal to this value. :type maximum: numeric :returns: ``True`` if ``value`` is valid, ``False`` if it is not. :rtype: :class:`bool <python:bool>` :raises SyntaxError: if ``kwargs`` contains duplicate keyword parameters or duplicates keyword parameters passed to the underlying validator """ try: value = validators.numeric(value, minimum = minimum, maximum = maximum, **kwargs) except SyntaxError as error: raise error except Exception: return False return True
Indicate whether ``value`` is a numeric value. :param value: The value to evaluate. :param minimum: If supplied, will make sure that ``value`` is greater than or equal to this value. :type minimum: numeric :param maximum: If supplied, will make sure that ``value`` is less than or equal to this value. :type maximum: numeric :returns: ``True`` if ``value`` is valid, ``False`` if it is not. :rtype: :class:`bool <python:bool>` :raises SyntaxError: if ``kwargs`` contains duplicate keyword parameters or duplicates keyword parameters passed to the underlying validator
https://github.com/insightindustry/validator-collection/blob/8c8047a0fa36cc88a021771279898278c4cc98e3/validator_collection/checkers.py#L799-L832
insightindustry/validator-collection
validator_collection/checkers.py
is_integer
def is_integer(value, coerce_value = False, minimum = None, maximum = None, base = 10, **kwargs): """Indicate whether ``value`` contains a whole number. :param value: The value to evaluate. :param coerce_value: If ``True``, will return ``True`` if ``value`` can be coerced to whole number. If ``False``, will only return ``True`` if ``value`` is already a whole number (regardless of type). Defaults to ``False``. :type coerce_value: :class:`bool <python:bool>` :param minimum: If supplied, will make sure that ``value`` is greater than or equal to this value. :type minimum: numeric :param maximum: If supplied, will make sure that ``value`` is less than or equal to this value. :type maximum: numeric :param base: Indicates the base that is used to determine the integer value. The allowed values are 0 and 2–36. Base-2, -8, and -16 literals can be optionally prefixed with ``0b/0B``, ``0o/0O/0``, or ``0x/0X``, as with integer literals in code. Base 0 means to interpret the string exactly as an integer literal, so that the actual base is 2, 8, 10, or 16. Defaults to ``10``. :type base: :class:`int <python:int>` :returns: ``True`` if ``value`` is valid, ``False`` if it is not. :rtype: :class:`bool <python:bool>` :raises SyntaxError: if ``kwargs`` contains duplicate keyword parameters or duplicates keyword parameters passed to the underlying validator """ try: value = validators.integer(value, coerce_value = coerce_value, minimum = minimum, maximum = maximum, base = base, **kwargs) except SyntaxError as error: raise error except Exception: return False return True
python
def is_integer(value, coerce_value = False, minimum = None, maximum = None, base = 10, **kwargs): """Indicate whether ``value`` contains a whole number. :param value: The value to evaluate. :param coerce_value: If ``True``, will return ``True`` if ``value`` can be coerced to whole number. If ``False``, will only return ``True`` if ``value`` is already a whole number (regardless of type). Defaults to ``False``. :type coerce_value: :class:`bool <python:bool>` :param minimum: If supplied, will make sure that ``value`` is greater than or equal to this value. :type minimum: numeric :param maximum: If supplied, will make sure that ``value`` is less than or equal to this value. :type maximum: numeric :param base: Indicates the base that is used to determine the integer value. The allowed values are 0 and 2–36. Base-2, -8, and -16 literals can be optionally prefixed with ``0b/0B``, ``0o/0O/0``, or ``0x/0X``, as with integer literals in code. Base 0 means to interpret the string exactly as an integer literal, so that the actual base is 2, 8, 10, or 16. Defaults to ``10``. :type base: :class:`int <python:int>` :returns: ``True`` if ``value`` is valid, ``False`` if it is not. :rtype: :class:`bool <python:bool>` :raises SyntaxError: if ``kwargs`` contains duplicate keyword parameters or duplicates keyword parameters passed to the underlying validator """ try: value = validators.integer(value, coerce_value = coerce_value, minimum = minimum, maximum = maximum, base = base, **kwargs) except SyntaxError as error: raise error except Exception: return False return True
Indicate whether ``value`` contains a whole number. :param value: The value to evaluate. :param coerce_value: If ``True``, will return ``True`` if ``value`` can be coerced to whole number. If ``False``, will only return ``True`` if ``value`` is already a whole number (regardless of type). Defaults to ``False``. :type coerce_value: :class:`bool <python:bool>` :param minimum: If supplied, will make sure that ``value`` is greater than or equal to this value. :type minimum: numeric :param maximum: If supplied, will make sure that ``value`` is less than or equal to this value. :type maximum: numeric :param base: Indicates the base that is used to determine the integer value. The allowed values are 0 and 2–36. Base-2, -8, and -16 literals can be optionally prefixed with ``0b/0B``, ``0o/0O/0``, or ``0x/0X``, as with integer literals in code. Base 0 means to interpret the string exactly as an integer literal, so that the actual base is 2, 8, 10, or 16. Defaults to ``10``. :type base: :class:`int <python:int>` :returns: ``True`` if ``value`` is valid, ``False`` if it is not. :rtype: :class:`bool <python:bool>` :raises SyntaxError: if ``kwargs`` contains duplicate keyword parameters or duplicates keyword parameters passed to the underlying validator
https://github.com/insightindustry/validator-collection/blob/8c8047a0fa36cc88a021771279898278c4cc98e3/validator_collection/checkers.py#L836-L886
insightindustry/validator-collection
validator_collection/checkers.py
is_float
def is_float(value, minimum = None, maximum = None, **kwargs): """Indicate whether ``value`` is a :class:`float <python:float>`. :param value: The value to evaluate. :param minimum: If supplied, will make sure that ``value`` is greater than or equal to this value. :type minimum: numeric :param maximum: If supplied, will make sure that ``value`` is less than or equal to this value. :type maximum: numeric :returns: ``True`` if ``value`` is valid, ``False`` if it is not. :rtype: :class:`bool <python:bool>` :raises SyntaxError: if ``kwargs`` contains duplicate keyword parameters or duplicates keyword parameters passed to the underlying validator """ try: value = validators.float(value, minimum = minimum, maximum = maximum, **kwargs) except SyntaxError as error: raise error except Exception: return False return True
python
def is_float(value, minimum = None, maximum = None, **kwargs): """Indicate whether ``value`` is a :class:`float <python:float>`. :param value: The value to evaluate. :param minimum: If supplied, will make sure that ``value`` is greater than or equal to this value. :type minimum: numeric :param maximum: If supplied, will make sure that ``value`` is less than or equal to this value. :type maximum: numeric :returns: ``True`` if ``value`` is valid, ``False`` if it is not. :rtype: :class:`bool <python:bool>` :raises SyntaxError: if ``kwargs`` contains duplicate keyword parameters or duplicates keyword parameters passed to the underlying validator """ try: value = validators.float(value, minimum = minimum, maximum = maximum, **kwargs) except SyntaxError as error: raise error except Exception: return False return True
Indicate whether ``value`` is a :class:`float <python:float>`. :param value: The value to evaluate. :param minimum: If supplied, will make sure that ``value`` is greater than or equal to this value. :type minimum: numeric :param maximum: If supplied, will make sure that ``value`` is less than or equal to this value. :type maximum: numeric :returns: ``True`` if ``value`` is valid, ``False`` if it is not. :rtype: :class:`bool <python:bool>` :raises SyntaxError: if ``kwargs`` contains duplicate keyword parameters or duplicates keyword parameters passed to the underlying validator
https://github.com/insightindustry/validator-collection/blob/8c8047a0fa36cc88a021771279898278c4cc98e3/validator_collection/checkers.py#L890-L923
insightindustry/validator-collection
validator_collection/checkers.py
is_fraction
def is_fraction(value, minimum = None, maximum = None, **kwargs): """Indicate whether ``value`` is a :class:`Fraction <python:fractions.Fraction>`. :param value: The value to evaluate. :param minimum: If supplied, will make sure that ``value`` is greater than or equal to this value. :type minimum: numeric :param maximum: If supplied, will make sure that ``value`` is less than or equal to this value. :type maximum: numeric :returns: ``True`` if ``value`` is valid, ``False`` if it is not. :rtype: :class:`bool <python:bool>` :raises SyntaxError: if ``kwargs`` contains duplicate keyword parameters or duplicates keyword parameters passed to the underlying validator """ try: value = validators.fraction(value, minimum = minimum, maximum = maximum, **kwargs) except SyntaxError as error: raise error except Exception: return False return True
python
def is_fraction(value, minimum = None, maximum = None, **kwargs): """Indicate whether ``value`` is a :class:`Fraction <python:fractions.Fraction>`. :param value: The value to evaluate. :param minimum: If supplied, will make sure that ``value`` is greater than or equal to this value. :type minimum: numeric :param maximum: If supplied, will make sure that ``value`` is less than or equal to this value. :type maximum: numeric :returns: ``True`` if ``value`` is valid, ``False`` if it is not. :rtype: :class:`bool <python:bool>` :raises SyntaxError: if ``kwargs`` contains duplicate keyword parameters or duplicates keyword parameters passed to the underlying validator """ try: value = validators.fraction(value, minimum = minimum, maximum = maximum, **kwargs) except SyntaxError as error: raise error except Exception: return False return True
Indicate whether ``value`` is a :class:`Fraction <python:fractions.Fraction>`. :param value: The value to evaluate. :param minimum: If supplied, will make sure that ``value`` is greater than or equal to this value. :type minimum: numeric :param maximum: If supplied, will make sure that ``value`` is less than or equal to this value. :type maximum: numeric :returns: ``True`` if ``value`` is valid, ``False`` if it is not. :rtype: :class:`bool <python:bool>` :raises SyntaxError: if ``kwargs`` contains duplicate keyword parameters or duplicates keyword parameters passed to the underlying validator
https://github.com/insightindustry/validator-collection/blob/8c8047a0fa36cc88a021771279898278c4cc98e3/validator_collection/checkers.py#L927-L960
insightindustry/validator-collection
validator_collection/checkers.py
is_decimal
def is_decimal(value, minimum = None, maximum = None, **kwargs): """Indicate whether ``value`` contains a :class:`Decimal <python:decimal.Decimal>`. :param value: The value to evaluate. :param minimum: If supplied, will make sure that ``value`` is greater than or equal to this value. :type minimum: numeric :param maximum: If supplied, will make sure that ``value`` is less than or equal to this value. :type maximum: numeric :returns: ``True`` if ``value`` is valid, ``False`` if it is not. :rtype: :class:`bool <python:bool>` :raises SyntaxError: if ``kwargs`` contains duplicate keyword parameters or duplicates keyword parameters passed to the underlying validator """ try: value = validators.decimal(value, minimum = minimum, maximum = maximum, **kwargs) except SyntaxError as error: raise error except Exception: return False return True
python
def is_decimal(value, minimum = None, maximum = None, **kwargs): """Indicate whether ``value`` contains a :class:`Decimal <python:decimal.Decimal>`. :param value: The value to evaluate. :param minimum: If supplied, will make sure that ``value`` is greater than or equal to this value. :type minimum: numeric :param maximum: If supplied, will make sure that ``value`` is less than or equal to this value. :type maximum: numeric :returns: ``True`` if ``value`` is valid, ``False`` if it is not. :rtype: :class:`bool <python:bool>` :raises SyntaxError: if ``kwargs`` contains duplicate keyword parameters or duplicates keyword parameters passed to the underlying validator """ try: value = validators.decimal(value, minimum = minimum, maximum = maximum, **kwargs) except SyntaxError as error: raise error except Exception: return False return True
Indicate whether ``value`` contains a :class:`Decimal <python:decimal.Decimal>`. :param value: The value to evaluate. :param minimum: If supplied, will make sure that ``value`` is greater than or equal to this value. :type minimum: numeric :param maximum: If supplied, will make sure that ``value`` is less than or equal to this value. :type maximum: numeric :returns: ``True`` if ``value`` is valid, ``False`` if it is not. :rtype: :class:`bool <python:bool>` :raises SyntaxError: if ``kwargs`` contains duplicate keyword parameters or duplicates keyword parameters passed to the underlying validator
https://github.com/insightindustry/validator-collection/blob/8c8047a0fa36cc88a021771279898278c4cc98e3/validator_collection/checkers.py#L964-L997
insightindustry/validator-collection
validator_collection/checkers.py
is_pathlike
def is_pathlike(value, **kwargs): """Indicate whether ``value`` is a path-like object. :param value: The value to evaluate. :returns: ``True`` if ``value`` is valid, ``False`` if it is not. :rtype: :class:`bool <python:bool>` :raises SyntaxError: if ``kwargs`` contains duplicate keyword parameters or duplicates keyword parameters passed to the underlying validator """ try: value = validators.path(value, **kwargs) except SyntaxError as error: raise error except Exception: return False return True
python
def is_pathlike(value, **kwargs): """Indicate whether ``value`` is a path-like object. :param value: The value to evaluate. :returns: ``True`` if ``value`` is valid, ``False`` if it is not. :rtype: :class:`bool <python:bool>` :raises SyntaxError: if ``kwargs`` contains duplicate keyword parameters or duplicates keyword parameters passed to the underlying validator """ try: value = validators.path(value, **kwargs) except SyntaxError as error: raise error except Exception: return False return True
Indicate whether ``value`` is a path-like object. :param value: The value to evaluate. :returns: ``True`` if ``value`` is valid, ``False`` if it is not. :rtype: :class:`bool <python:bool>` :raises SyntaxError: if ``kwargs`` contains duplicate keyword parameters or duplicates keyword parameters passed to the underlying validator
https://github.com/insightindustry/validator-collection/blob/8c8047a0fa36cc88a021771279898278c4cc98e3/validator_collection/checkers.py#L1045-L1064
insightindustry/validator-collection
validator_collection/checkers.py
is_on_filesystem
def is_on_filesystem(value, **kwargs): """Indicate whether ``value`` is a file or directory that exists on the local filesystem. :param value: The value to evaluate. :returns: ``True`` if ``value`` is valid, ``False`` if it is not. :rtype: :class:`bool <python:bool>` :raises SyntaxError: if ``kwargs`` contains duplicate keyword parameters or duplicates keyword parameters passed to the underlying validator """ try: value = validators.path_exists(value, **kwargs) except SyntaxError as error: raise error except Exception: return False return True
python
def is_on_filesystem(value, **kwargs): """Indicate whether ``value`` is a file or directory that exists on the local filesystem. :param value: The value to evaluate. :returns: ``True`` if ``value`` is valid, ``False`` if it is not. :rtype: :class:`bool <python:bool>` :raises SyntaxError: if ``kwargs`` contains duplicate keyword parameters or duplicates keyword parameters passed to the underlying validator """ try: value = validators.path_exists(value, **kwargs) except SyntaxError as error: raise error except Exception: return False return True
Indicate whether ``value`` is a file or directory that exists on the local filesystem. :param value: The value to evaluate. :returns: ``True`` if ``value`` is valid, ``False`` if it is not. :rtype: :class:`bool <python:bool>` :raises SyntaxError: if ``kwargs`` contains duplicate keyword parameters or duplicates keyword parameters passed to the underlying validator
https://github.com/insightindustry/validator-collection/blob/8c8047a0fa36cc88a021771279898278c4cc98e3/validator_collection/checkers.py#L1068-L1088
insightindustry/validator-collection
validator_collection/checkers.py
is_file
def is_file(value, **kwargs): """Indicate whether ``value`` is a file that exists on the local filesystem. :param value: The value to evaluate. :returns: ``True`` if ``value`` is valid, ``False`` if it is not. :rtype: :class:`bool <python:bool>` :raises SyntaxError: if ``kwargs`` contains duplicate keyword parameters or duplicates keyword parameters passed to the underlying validator """ try: value = validators.file_exists(value, **kwargs) except SyntaxError as error: raise error except Exception: return False return True
python
def is_file(value, **kwargs): """Indicate whether ``value`` is a file that exists on the local filesystem. :param value: The value to evaluate. :returns: ``True`` if ``value`` is valid, ``False`` if it is not. :rtype: :class:`bool <python:bool>` :raises SyntaxError: if ``kwargs`` contains duplicate keyword parameters or duplicates keyword parameters passed to the underlying validator """ try: value = validators.file_exists(value, **kwargs) except SyntaxError as error: raise error except Exception: return False return True
Indicate whether ``value`` is a file that exists on the local filesystem. :param value: The value to evaluate. :returns: ``True`` if ``value`` is valid, ``False`` if it is not. :rtype: :class:`bool <python:bool>` :raises SyntaxError: if ``kwargs`` contains duplicate keyword parameters or duplicates keyword parameters passed to the underlying validator
https://github.com/insightindustry/validator-collection/blob/8c8047a0fa36cc88a021771279898278c4cc98e3/validator_collection/checkers.py#L1092-L1111
insightindustry/validator-collection
validator_collection/checkers.py
is_directory
def is_directory(value, **kwargs): """Indicate whether ``value`` is a directory that exists on the local filesystem. :param value: The value to evaluate. :returns: ``True`` if ``value`` is valid, ``False`` if it is not. :rtype: :class:`bool <python:bool>` :raises SyntaxError: if ``kwargs`` contains duplicate keyword parameters or duplicates keyword parameters passed to the underlying validator """ try: value = validators.directory_exists(value, **kwargs) except SyntaxError as error: raise error except Exception: return False return True
python
def is_directory(value, **kwargs): """Indicate whether ``value`` is a directory that exists on the local filesystem. :param value: The value to evaluate. :returns: ``True`` if ``value`` is valid, ``False`` if it is not. :rtype: :class:`bool <python:bool>` :raises SyntaxError: if ``kwargs`` contains duplicate keyword parameters or duplicates keyword parameters passed to the underlying validator """ try: value = validators.directory_exists(value, **kwargs) except SyntaxError as error: raise error except Exception: return False return True
Indicate whether ``value`` is a directory that exists on the local filesystem. :param value: The value to evaluate. :returns: ``True`` if ``value`` is valid, ``False`` if it is not. :rtype: :class:`bool <python:bool>` :raises SyntaxError: if ``kwargs`` contains duplicate keyword parameters or duplicates keyword parameters passed to the underlying validator
https://github.com/insightindustry/validator-collection/blob/8c8047a0fa36cc88a021771279898278c4cc98e3/validator_collection/checkers.py#L1115-L1134
insightindustry/validator-collection
validator_collection/checkers.py
is_readable
def is_readable(value, **kwargs): """Indicate whether ``value`` is a readable file. .. caution:: **Use of this validator is an anti-pattern and should be used with caution.** Validating the readability of a file *before* attempting to read it exposes your code to a bug called `TOCTOU <https://en.wikipedia.org/wiki/Time_of_check_to_time_of_use>`_. This particular class of bug can expose your code to **security vulnerabilities** and so this validator should only be used if you are an advanced user. A better pattern to use when reading from a file is to apply the principle of EAFP ("easier to ask forgiveness than permission"), and simply attempt to write to the file using a ``try ... except`` block: .. code-block:: python try: with open('path/to/filename.txt', mode = 'r') as file_object: # read from file here except (OSError, IOError) as error: # Handle an error if unable to write. :param value: The value to evaluate. :type value: Path-like object :returns: ``True`` if ``value`` is valid, ``False`` if it is not. :rtype: :class:`bool <python:bool>` :raises SyntaxError: if ``kwargs`` contains duplicate keyword parameters or duplicates keyword parameters passed to the underlying validator """ try: validators.readable(value, **kwargs) except SyntaxError as error: raise error except Exception: return False return True
python
def is_readable(value, **kwargs): """Indicate whether ``value`` is a readable file. .. caution:: **Use of this validator is an anti-pattern and should be used with caution.** Validating the readability of a file *before* attempting to read it exposes your code to a bug called `TOCTOU <https://en.wikipedia.org/wiki/Time_of_check_to_time_of_use>`_. This particular class of bug can expose your code to **security vulnerabilities** and so this validator should only be used if you are an advanced user. A better pattern to use when reading from a file is to apply the principle of EAFP ("easier to ask forgiveness than permission"), and simply attempt to write to the file using a ``try ... except`` block: .. code-block:: python try: with open('path/to/filename.txt', mode = 'r') as file_object: # read from file here except (OSError, IOError) as error: # Handle an error if unable to write. :param value: The value to evaluate. :type value: Path-like object :returns: ``True`` if ``value`` is valid, ``False`` if it is not. :rtype: :class:`bool <python:bool>` :raises SyntaxError: if ``kwargs`` contains duplicate keyword parameters or duplicates keyword parameters passed to the underlying validator """ try: validators.readable(value, **kwargs) except SyntaxError as error: raise error except Exception: return False return True
Indicate whether ``value`` is a readable file. .. caution:: **Use of this validator is an anti-pattern and should be used with caution.** Validating the readability of a file *before* attempting to read it exposes your code to a bug called `TOCTOU <https://en.wikipedia.org/wiki/Time_of_check_to_time_of_use>`_. This particular class of bug can expose your code to **security vulnerabilities** and so this validator should only be used if you are an advanced user. A better pattern to use when reading from a file is to apply the principle of EAFP ("easier to ask forgiveness than permission"), and simply attempt to write to the file using a ``try ... except`` block: .. code-block:: python try: with open('path/to/filename.txt', mode = 'r') as file_object: # read from file here except (OSError, IOError) as error: # Handle an error if unable to write. :param value: The value to evaluate. :type value: Path-like object :returns: ``True`` if ``value`` is valid, ``False`` if it is not. :rtype: :class:`bool <python:bool>` :raises SyntaxError: if ``kwargs`` contains duplicate keyword parameters or duplicates keyword parameters passed to the underlying validator
https://github.com/insightindustry/validator-collection/blob/8c8047a0fa36cc88a021771279898278c4cc98e3/validator_collection/checkers.py#L1138-L1181
insightindustry/validator-collection
validator_collection/checkers.py
is_writeable
def is_writeable(value, **kwargs): """Indicate whether ``value`` is a writeable file. .. caution:: This validator does **NOT** work correctly on a Windows file system. This is due to the vagaries of how Windows manages its file system and the various ways in which it can manage file permission. If called on a Windows file system, this validator will raise :class:`NotImplementedError() <python:NotImplementedError>`. .. caution:: **Use of this validator is an anti-pattern and should be used with caution.** Validating the writability of a file *before* attempting to write to it exposes your code to a bug called `TOCTOU <https://en.wikipedia.org/wiki/Time_of_check_to_time_of_use>`_. This particular class of bug can expose your code to **security vulnerabilities** and so this validator should only be used if you are an advanced user. A better pattern to use when writing to file is to apply the principle of EAFP ("easier to ask forgiveness than permission"), and simply attempt to write to the file using a ``try ... except`` block: .. code-block:: python try: with open('path/to/filename.txt', mode = 'a') as file_object: # write to file here except (OSError, IOError) as error: # Handle an error if unable to write. .. note:: This validator relies on :func:`os.access() <python:os.access>` to check whether ``value`` is writeable. This function has certain limitations, most especially that: * It will **ignore** file-locking (yielding a false-positive) if the file is locked. * It focuses on *local operating system permissions*, which means if trying to access a path over a network you might get a false positive or false negative (because network paths may have more complicated authentication methods). :param value: The value to evaluate. :type value: Path-like object :returns: ``True`` if ``value`` is valid, ``False`` if it is not. :rtype: :class:`bool <python:bool>` :raises NotImplementedError: if called on a Windows system :raises SyntaxError: if ``kwargs`` contains duplicate keyword parameters or duplicates keyword parameters passed to the underlying validator """ if sys.platform in ['win32', 'cygwin']: raise NotImplementedError('not supported on Windows') try: validators.writeable(value, allow_empty = False, **kwargs) except SyntaxError as error: raise error except Exception: return False return True
python
def is_writeable(value, **kwargs): """Indicate whether ``value`` is a writeable file. .. caution:: This validator does **NOT** work correctly on a Windows file system. This is due to the vagaries of how Windows manages its file system and the various ways in which it can manage file permission. If called on a Windows file system, this validator will raise :class:`NotImplementedError() <python:NotImplementedError>`. .. caution:: **Use of this validator is an anti-pattern and should be used with caution.** Validating the writability of a file *before* attempting to write to it exposes your code to a bug called `TOCTOU <https://en.wikipedia.org/wiki/Time_of_check_to_time_of_use>`_. This particular class of bug can expose your code to **security vulnerabilities** and so this validator should only be used if you are an advanced user. A better pattern to use when writing to file is to apply the principle of EAFP ("easier to ask forgiveness than permission"), and simply attempt to write to the file using a ``try ... except`` block: .. code-block:: python try: with open('path/to/filename.txt', mode = 'a') as file_object: # write to file here except (OSError, IOError) as error: # Handle an error if unable to write. .. note:: This validator relies on :func:`os.access() <python:os.access>` to check whether ``value`` is writeable. This function has certain limitations, most especially that: * It will **ignore** file-locking (yielding a false-positive) if the file is locked. * It focuses on *local operating system permissions*, which means if trying to access a path over a network you might get a false positive or false negative (because network paths may have more complicated authentication methods). :param value: The value to evaluate. :type value: Path-like object :returns: ``True`` if ``value`` is valid, ``False`` if it is not. :rtype: :class:`bool <python:bool>` :raises NotImplementedError: if called on a Windows system :raises SyntaxError: if ``kwargs`` contains duplicate keyword parameters or duplicates keyword parameters passed to the underlying validator """ if sys.platform in ['win32', 'cygwin']: raise NotImplementedError('not supported on Windows') try: validators.writeable(value, allow_empty = False, **kwargs) except SyntaxError as error: raise error except Exception: return False return True
Indicate whether ``value`` is a writeable file. .. caution:: This validator does **NOT** work correctly on a Windows file system. This is due to the vagaries of how Windows manages its file system and the various ways in which it can manage file permission. If called on a Windows file system, this validator will raise :class:`NotImplementedError() <python:NotImplementedError>`. .. caution:: **Use of this validator is an anti-pattern and should be used with caution.** Validating the writability of a file *before* attempting to write to it exposes your code to a bug called `TOCTOU <https://en.wikipedia.org/wiki/Time_of_check_to_time_of_use>`_. This particular class of bug can expose your code to **security vulnerabilities** and so this validator should only be used if you are an advanced user. A better pattern to use when writing to file is to apply the principle of EAFP ("easier to ask forgiveness than permission"), and simply attempt to write to the file using a ``try ... except`` block: .. code-block:: python try: with open('path/to/filename.txt', mode = 'a') as file_object: # write to file here except (OSError, IOError) as error: # Handle an error if unable to write. .. note:: This validator relies on :func:`os.access() <python:os.access>` to check whether ``value`` is writeable. This function has certain limitations, most especially that: * It will **ignore** file-locking (yielding a false-positive) if the file is locked. * It focuses on *local operating system permissions*, which means if trying to access a path over a network you might get a false positive or false negative (because network paths may have more complicated authentication methods). :param value: The value to evaluate. :type value: Path-like object :returns: ``True`` if ``value`` is valid, ``False`` if it is not. :rtype: :class:`bool <python:bool>` :raises NotImplementedError: if called on a Windows system :raises SyntaxError: if ``kwargs`` contains duplicate keyword parameters or duplicates keyword parameters passed to the underlying validator
https://github.com/insightindustry/validator-collection/blob/8c8047a0fa36cc88a021771279898278c4cc98e3/validator_collection/checkers.py#L1185-L1257
insightindustry/validator-collection
validator_collection/checkers.py
is_executable
def is_executable(value, **kwargs): """Indicate whether ``value`` is an executable file. .. caution:: This validator does **NOT** work correctly on a Windows file system. This is due to the vagaries of how Windows manages its file system and the various ways in which it can manage file permission. If called on a Windows file system, this validator will raise :class:`NotImplementedError() <python:NotImplementedError>`. .. caution:: **Use of this validator is an anti-pattern and should be used with caution.** Validating the writability of a file *before* attempting to execute it exposes your code to a bug called `TOCTOU <https://en.wikipedia.org/wiki/Time_of_check_to_time_of_use>`_. This particular class of bug can expose your code to **security vulnerabilities** and so this validator should only be used if you are an advanced user. A better pattern to use when writing to file is to apply the principle of EAFP ("easier to ask forgiveness than permission"), and simply attempt to execute the file using a ``try ... except`` block. .. note:: This validator relies on :func:`os.access() <python:os.access>` to check whether ``value`` is writeable. This function has certain limitations, most especially that: * It will **ignore** file-locking (yielding a false-positive) if the file is locked. * It focuses on *local operating system permissions*, which means if trying to access a path over a network you might get a false positive or false negative (because network paths may have more complicated authentication methods). :param value: The value to evaluate. :type value: Path-like object :returns: ``True`` if ``value`` is valid, ``False`` if it is not. :rtype: :class:`bool <python:bool>` :raises NotImplementedError: if called on a Windows system :raises SyntaxError: if ``kwargs`` contains duplicate keyword parameters or duplicates keyword parameters passed to the underlying validator """ if sys.platform in ['win32', 'cygwin']: raise NotImplementedError('not supported on Windows') try: validators.executable(value, **kwargs) except SyntaxError as error: raise error except Exception: return False return True
python
def is_executable(value, **kwargs): """Indicate whether ``value`` is an executable file. .. caution:: This validator does **NOT** work correctly on a Windows file system. This is due to the vagaries of how Windows manages its file system and the various ways in which it can manage file permission. If called on a Windows file system, this validator will raise :class:`NotImplementedError() <python:NotImplementedError>`. .. caution:: **Use of this validator is an anti-pattern and should be used with caution.** Validating the writability of a file *before* attempting to execute it exposes your code to a bug called `TOCTOU <https://en.wikipedia.org/wiki/Time_of_check_to_time_of_use>`_. This particular class of bug can expose your code to **security vulnerabilities** and so this validator should only be used if you are an advanced user. A better pattern to use when writing to file is to apply the principle of EAFP ("easier to ask forgiveness than permission"), and simply attempt to execute the file using a ``try ... except`` block. .. note:: This validator relies on :func:`os.access() <python:os.access>` to check whether ``value`` is writeable. This function has certain limitations, most especially that: * It will **ignore** file-locking (yielding a false-positive) if the file is locked. * It focuses on *local operating system permissions*, which means if trying to access a path over a network you might get a false positive or false negative (because network paths may have more complicated authentication methods). :param value: The value to evaluate. :type value: Path-like object :returns: ``True`` if ``value`` is valid, ``False`` if it is not. :rtype: :class:`bool <python:bool>` :raises NotImplementedError: if called on a Windows system :raises SyntaxError: if ``kwargs`` contains duplicate keyword parameters or duplicates keyword parameters passed to the underlying validator """ if sys.platform in ['win32', 'cygwin']: raise NotImplementedError('not supported on Windows') try: validators.executable(value, **kwargs) except SyntaxError as error: raise error except Exception: return False return True
Indicate whether ``value`` is an executable file. .. caution:: This validator does **NOT** work correctly on a Windows file system. This is due to the vagaries of how Windows manages its file system and the various ways in which it can manage file permission. If called on a Windows file system, this validator will raise :class:`NotImplementedError() <python:NotImplementedError>`. .. caution:: **Use of this validator is an anti-pattern and should be used with caution.** Validating the writability of a file *before* attempting to execute it exposes your code to a bug called `TOCTOU <https://en.wikipedia.org/wiki/Time_of_check_to_time_of_use>`_. This particular class of bug can expose your code to **security vulnerabilities** and so this validator should only be used if you are an advanced user. A better pattern to use when writing to file is to apply the principle of EAFP ("easier to ask forgiveness than permission"), and simply attempt to execute the file using a ``try ... except`` block. .. note:: This validator relies on :func:`os.access() <python:os.access>` to check whether ``value`` is writeable. This function has certain limitations, most especially that: * It will **ignore** file-locking (yielding a false-positive) if the file is locked. * It focuses on *local operating system permissions*, which means if trying to access a path over a network you might get a false positive or false negative (because network paths may have more complicated authentication methods). :param value: The value to evaluate. :type value: Path-like object :returns: ``True`` if ``value`` is valid, ``False`` if it is not. :rtype: :class:`bool <python:bool>` :raises NotImplementedError: if called on a Windows system :raises SyntaxError: if ``kwargs`` contains duplicate keyword parameters or duplicates keyword parameters passed to the underlying validator
https://github.com/insightindustry/validator-collection/blob/8c8047a0fa36cc88a021771279898278c4cc98e3/validator_collection/checkers.py#L1260-L1323
insightindustry/validator-collection
validator_collection/checkers.py
is_email
def is_email(value, **kwargs): """Indicate whether ``value`` is an email address. .. note:: Email address validation is...complicated. The methodology that we have adopted here is *generally* compliant with `RFC 5322 <https://tools.ietf.org/html/rfc5322>`_ and uses a combination of string parsing and regular expressions. String parsing in particular is used to validate certain *highly unusual* but still valid email patterns, including the use of escaped text and comments within an email address' local address (the user name part). This approach ensures more complete coverage for unusual edge cases, while still letting us use regular expressions that perform quickly. :param value: The value to evaluate. :returns: ``True`` if ``value`` is valid, ``False`` if it is not. :rtype: :class:`bool <python:bool>` :raises SyntaxError: if ``kwargs`` contains duplicate keyword parameters or duplicates keyword parameters passed to the underlying validator """ try: value = validators.email(value, **kwargs) except SyntaxError as error: raise error except Exception: return False return True
python
def is_email(value, **kwargs): """Indicate whether ``value`` is an email address. .. note:: Email address validation is...complicated. The methodology that we have adopted here is *generally* compliant with `RFC 5322 <https://tools.ietf.org/html/rfc5322>`_ and uses a combination of string parsing and regular expressions. String parsing in particular is used to validate certain *highly unusual* but still valid email patterns, including the use of escaped text and comments within an email address' local address (the user name part). This approach ensures more complete coverage for unusual edge cases, while still letting us use regular expressions that perform quickly. :param value: The value to evaluate. :returns: ``True`` if ``value`` is valid, ``False`` if it is not. :rtype: :class:`bool <python:bool>` :raises SyntaxError: if ``kwargs`` contains duplicate keyword parameters or duplicates keyword parameters passed to the underlying validator """ try: value = validators.email(value, **kwargs) except SyntaxError as error: raise error except Exception: return False return True
Indicate whether ``value`` is an email address. .. note:: Email address validation is...complicated. The methodology that we have adopted here is *generally* compliant with `RFC 5322 <https://tools.ietf.org/html/rfc5322>`_ and uses a combination of string parsing and regular expressions. String parsing in particular is used to validate certain *highly unusual* but still valid email patterns, including the use of escaped text and comments within an email address' local address (the user name part). This approach ensures more complete coverage for unusual edge cases, while still letting us use regular expressions that perform quickly. :param value: The value to evaluate. :returns: ``True`` if ``value`` is valid, ``False`` if it is not. :rtype: :class:`bool <python:bool>` :raises SyntaxError: if ``kwargs`` contains duplicate keyword parameters or duplicates keyword parameters passed to the underlying validator
https://github.com/insightindustry/validator-collection/blob/8c8047a0fa36cc88a021771279898278c4cc98e3/validator_collection/checkers.py#L1329-L1362
insightindustry/validator-collection
validator_collection/checkers.py
is_url
def is_url(value, **kwargs): """Indicate whether ``value`` is a URL. .. note:: URL validation is...complicated. The methodology that we have adopted here is *generally* compliant with `RFC 1738 <https://tools.ietf.org/html/rfc1738>`_, `RFC 6761 <https://tools.ietf.org/html/rfc6761>`_, `RFC 2181 <https://tools.ietf.org/html/rfc2181>`_ and uses a combination of string parsing and regular expressions, This approach ensures more complete coverage for unusual edge cases, while still letting us use regular expressions that perform quickly. :param value: The value to evaluate. :param allow_special_ips: If ``True``, will succeed when validating special IP addresses, such as loopback IPs like ``127.0.0.1`` or ``0.0.0.0``. If ``False``, will fail if ``value`` is a special IP address. Defaults to ``False``. :type allow_special_ips: :class:`bool <python:bool>` :returns: ``True`` if ``value`` is valid, ``False`` if it is not. :rtype: :class:`bool <python:bool>` :raises SyntaxError: if ``kwargs`` contains duplicate keyword parameters or duplicates keyword parameters passed to the underlying validator """ try: value = validators.url(value, **kwargs) except SyntaxError as error: raise error except Exception: return False return True
python
def is_url(value, **kwargs): """Indicate whether ``value`` is a URL. .. note:: URL validation is...complicated. The methodology that we have adopted here is *generally* compliant with `RFC 1738 <https://tools.ietf.org/html/rfc1738>`_, `RFC 6761 <https://tools.ietf.org/html/rfc6761>`_, `RFC 2181 <https://tools.ietf.org/html/rfc2181>`_ and uses a combination of string parsing and regular expressions, This approach ensures more complete coverage for unusual edge cases, while still letting us use regular expressions that perform quickly. :param value: The value to evaluate. :param allow_special_ips: If ``True``, will succeed when validating special IP addresses, such as loopback IPs like ``127.0.0.1`` or ``0.0.0.0``. If ``False``, will fail if ``value`` is a special IP address. Defaults to ``False``. :type allow_special_ips: :class:`bool <python:bool>` :returns: ``True`` if ``value`` is valid, ``False`` if it is not. :rtype: :class:`bool <python:bool>` :raises SyntaxError: if ``kwargs`` contains duplicate keyword parameters or duplicates keyword parameters passed to the underlying validator """ try: value = validators.url(value, **kwargs) except SyntaxError as error: raise error except Exception: return False return True
Indicate whether ``value`` is a URL. .. note:: URL validation is...complicated. The methodology that we have adopted here is *generally* compliant with `RFC 1738 <https://tools.ietf.org/html/rfc1738>`_, `RFC 6761 <https://tools.ietf.org/html/rfc6761>`_, `RFC 2181 <https://tools.ietf.org/html/rfc2181>`_ and uses a combination of string parsing and regular expressions, This approach ensures more complete coverage for unusual edge cases, while still letting us use regular expressions that perform quickly. :param value: The value to evaluate. :param allow_special_ips: If ``True``, will succeed when validating special IP addresses, such as loopback IPs like ``127.0.0.1`` or ``0.0.0.0``. If ``False``, will fail if ``value`` is a special IP address. Defaults to ``False``. :type allow_special_ips: :class:`bool <python:bool>` :returns: ``True`` if ``value`` is valid, ``False`` if it is not. :rtype: :class:`bool <python:bool>` :raises SyntaxError: if ``kwargs`` contains duplicate keyword parameters or duplicates keyword parameters passed to the underlying validator
https://github.com/insightindustry/validator-collection/blob/8c8047a0fa36cc88a021771279898278c4cc98e3/validator_collection/checkers.py#L1366-L1402
insightindustry/validator-collection
validator_collection/checkers.py
is_domain
def is_domain(value, **kwargs): """Indicate whether ``value`` is a valid domain. .. caution:: This validator does not verify that ``value`` **exists** as a domain. It merely verifies that its contents *might* exist as a domain. .. note:: This validator checks to validate that ``value`` resembles a valid domain name. It is - generally - compliant with `RFC 1035 <https://tools.ietf.org/html/rfc1035>`_ and `RFC 6761 <https://tools.ietf.org/html/rfc6761>`_, however it diverges in a number of key ways: * Including authentication (e.g. ``username:[email protected]``) will fail validation. * Including a path (e.g. ``domain.dev/path/to/file``) will fail validation. * Including a port (e.g. ``domain.dev:8080``) will fail validation. If you are hoping to validate a more complete URL, we recommend that you see :func:`url <validator_collection.validators.url>`. :param value: The value to evaluate. :param allow_ips: If ``True``, will succeed when validating IP addresses, If ``False``, will fail if ``value`` is an IP address. Defaults to ``False``. :type allow_ips: :class:`bool <python:bool>` :returns: ``True`` if ``value`` is valid, ``False`` if it is not. :rtype: :class:`bool <python:bool>` :raises SyntaxError: if ``kwargs`` contains duplicate keyword parameters or duplicates keyword parameters passed to the underlying validator """ try: value = validators.domain(value, **kwargs) except SyntaxError as error: raise error except Exception: return False return True
python
def is_domain(value, **kwargs): """Indicate whether ``value`` is a valid domain. .. caution:: This validator does not verify that ``value`` **exists** as a domain. It merely verifies that its contents *might* exist as a domain. .. note:: This validator checks to validate that ``value`` resembles a valid domain name. It is - generally - compliant with `RFC 1035 <https://tools.ietf.org/html/rfc1035>`_ and `RFC 6761 <https://tools.ietf.org/html/rfc6761>`_, however it diverges in a number of key ways: * Including authentication (e.g. ``username:[email protected]``) will fail validation. * Including a path (e.g. ``domain.dev/path/to/file``) will fail validation. * Including a port (e.g. ``domain.dev:8080``) will fail validation. If you are hoping to validate a more complete URL, we recommend that you see :func:`url <validator_collection.validators.url>`. :param value: The value to evaluate. :param allow_ips: If ``True``, will succeed when validating IP addresses, If ``False``, will fail if ``value`` is an IP address. Defaults to ``False``. :type allow_ips: :class:`bool <python:bool>` :returns: ``True`` if ``value`` is valid, ``False`` if it is not. :rtype: :class:`bool <python:bool>` :raises SyntaxError: if ``kwargs`` contains duplicate keyword parameters or duplicates keyword parameters passed to the underlying validator """ try: value = validators.domain(value, **kwargs) except SyntaxError as error: raise error except Exception: return False return True
Indicate whether ``value`` is a valid domain. .. caution:: This validator does not verify that ``value`` **exists** as a domain. It merely verifies that its contents *might* exist as a domain. .. note:: This validator checks to validate that ``value`` resembles a valid domain name. It is - generally - compliant with `RFC 1035 <https://tools.ietf.org/html/rfc1035>`_ and `RFC 6761 <https://tools.ietf.org/html/rfc6761>`_, however it diverges in a number of key ways: * Including authentication (e.g. ``username:[email protected]``) will fail validation. * Including a path (e.g. ``domain.dev/path/to/file``) will fail validation. * Including a port (e.g. ``domain.dev:8080``) will fail validation. If you are hoping to validate a more complete URL, we recommend that you see :func:`url <validator_collection.validators.url>`. :param value: The value to evaluate. :param allow_ips: If ``True``, will succeed when validating IP addresses, If ``False``, will fail if ``value`` is an IP address. Defaults to ``False``. :type allow_ips: :class:`bool <python:bool>` :returns: ``True`` if ``value`` is valid, ``False`` if it is not. :rtype: :class:`bool <python:bool>` :raises SyntaxError: if ``kwargs`` contains duplicate keyword parameters or duplicates keyword parameters passed to the underlying validator
https://github.com/insightindustry/validator-collection/blob/8c8047a0fa36cc88a021771279898278c4cc98e3/validator_collection/checkers.py#L1406-L1450
insightindustry/validator-collection
validator_collection/checkers.py
is_ip_address
def is_ip_address(value, **kwargs): """Indicate whether ``value`` is a valid IP address (version 4 or version 6). :param value: The value to evaluate. :returns: ``True`` if ``value`` is valid, ``False`` if it is not. :rtype: :class:`bool <python:bool>` :raises SyntaxError: if ``kwargs`` contains duplicate keyword parameters or duplicates keyword parameters passed to the underlying validator """ try: value = validators.ip_address(value, **kwargs) except SyntaxError as error: raise error except Exception: return False return True
python
def is_ip_address(value, **kwargs): """Indicate whether ``value`` is a valid IP address (version 4 or version 6). :param value: The value to evaluate. :returns: ``True`` if ``value`` is valid, ``False`` if it is not. :rtype: :class:`bool <python:bool>` :raises SyntaxError: if ``kwargs`` contains duplicate keyword parameters or duplicates keyword parameters passed to the underlying validator """ try: value = validators.ip_address(value, **kwargs) except SyntaxError as error: raise error except Exception: return False return True
Indicate whether ``value`` is a valid IP address (version 4 or version 6). :param value: The value to evaluate. :returns: ``True`` if ``value`` is valid, ``False`` if it is not. :rtype: :class:`bool <python:bool>` :raises SyntaxError: if ``kwargs`` contains duplicate keyword parameters or duplicates keyword parameters passed to the underlying validator
https://github.com/insightindustry/validator-collection/blob/8c8047a0fa36cc88a021771279898278c4cc98e3/validator_collection/checkers.py#L1454-L1473
insightindustry/validator-collection
validator_collection/checkers.py
is_ipv4
def is_ipv4(value, **kwargs): """Indicate whether ``value`` is a valid IP version 4 address. :param value: The value to evaluate. :returns: ``True`` if ``value`` is valid, ``False`` if it is not. :rtype: :class:`bool <python:bool>` :raises SyntaxError: if ``kwargs`` contains duplicate keyword parameters or duplicates keyword parameters passed to the underlying validator """ try: value = validators.ipv4(value, **kwargs) except SyntaxError as error: raise error except Exception: return False return True
python
def is_ipv4(value, **kwargs): """Indicate whether ``value`` is a valid IP version 4 address. :param value: The value to evaluate. :returns: ``True`` if ``value`` is valid, ``False`` if it is not. :rtype: :class:`bool <python:bool>` :raises SyntaxError: if ``kwargs`` contains duplicate keyword parameters or duplicates keyword parameters passed to the underlying validator """ try: value = validators.ipv4(value, **kwargs) except SyntaxError as error: raise error except Exception: return False return True
Indicate whether ``value`` is a valid IP version 4 address. :param value: The value to evaluate. :returns: ``True`` if ``value`` is valid, ``False`` if it is not. :rtype: :class:`bool <python:bool>` :raises SyntaxError: if ``kwargs`` contains duplicate keyword parameters or duplicates keyword parameters passed to the underlying validator
https://github.com/insightindustry/validator-collection/blob/8c8047a0fa36cc88a021771279898278c4cc98e3/validator_collection/checkers.py#L1477-L1496
insightindustry/validator-collection
validator_collection/checkers.py
is_ipv6
def is_ipv6(value, **kwargs): """Indicate whether ``value`` is a valid IP version 6 address. :param value: The value to evaluate. :returns: ``True`` if ``value`` is valid, ``False`` if it is not. :rtype: :class:`bool <python:bool>` :raises SyntaxError: if ``kwargs`` contains duplicate keyword parameters or duplicates keyword parameters passed to the underlying validator """ try: value = validators.ipv6(value, **kwargs) except SyntaxError as error: raise error except Exception: return False return True
python
def is_ipv6(value, **kwargs): """Indicate whether ``value`` is a valid IP version 6 address. :param value: The value to evaluate. :returns: ``True`` if ``value`` is valid, ``False`` if it is not. :rtype: :class:`bool <python:bool>` :raises SyntaxError: if ``kwargs`` contains duplicate keyword parameters or duplicates keyword parameters passed to the underlying validator """ try: value = validators.ipv6(value, **kwargs) except SyntaxError as error: raise error except Exception: return False return True
Indicate whether ``value`` is a valid IP version 6 address. :param value: The value to evaluate. :returns: ``True`` if ``value`` is valid, ``False`` if it is not. :rtype: :class:`bool <python:bool>` :raises SyntaxError: if ``kwargs`` contains duplicate keyword parameters or duplicates keyword parameters passed to the underlying validator
https://github.com/insightindustry/validator-collection/blob/8c8047a0fa36cc88a021771279898278c4cc98e3/validator_collection/checkers.py#L1500-L1518
insightindustry/validator-collection
validator_collection/checkers.py
is_mac_address
def is_mac_address(value, **kwargs): """Indicate whether ``value`` is a valid MAC address. :param value: The value to evaluate. :returns: ``True`` if ``value`` is valid, ``False`` if it is not. :rtype: :class:`bool <python:bool>` :raises SyntaxError: if ``kwargs`` contains duplicate keyword parameters or duplicates keyword parameters passed to the underlying validator """ try: value = validators.mac_address(value, **kwargs) except SyntaxError as error: raise error except Exception: return False return True
python
def is_mac_address(value, **kwargs): """Indicate whether ``value`` is a valid MAC address. :param value: The value to evaluate. :returns: ``True`` if ``value`` is valid, ``False`` if it is not. :rtype: :class:`bool <python:bool>` :raises SyntaxError: if ``kwargs`` contains duplicate keyword parameters or duplicates keyword parameters passed to the underlying validator """ try: value = validators.mac_address(value, **kwargs) except SyntaxError as error: raise error except Exception: return False return True
Indicate whether ``value`` is a valid MAC address. :param value: The value to evaluate. :returns: ``True`` if ``value`` is valid, ``False`` if it is not. :rtype: :class:`bool <python:bool>` :raises SyntaxError: if ``kwargs`` contains duplicate keyword parameters or duplicates keyword parameters passed to the underlying validator
https://github.com/insightindustry/validator-collection/blob/8c8047a0fa36cc88a021771279898278c4cc98e3/validator_collection/checkers.py#L1522-L1540
kevinpt/syntrax
syntrax.py
RailroadLayout.draw_line
def draw_line(self, lx, ltor): '''Draw a series of elements from left to right''' tag = self.get_tag() c = self.canvas s = self.style sep = s.h_sep exx = 0 exy = 0 terms = lx if ltor else reversed(lx) # Reverse so we can draw left to right for term in terms: t, texx, texy = self.draw_diagram(term, ltor) # Draw each element if exx > 0: # Second element onward xn = exx + sep # Add space between elements c.move(t, xn, exy) # Shift last element forward arr = 'last' if ltor else 'first' c.create_line(exx-1, exy, xn, exy, tags=(tag,), width=s.line_width, arrow=arr) # Connecting line (NOTE: -1 fudge) exx = xn + texx # Start at end of this element else: # First element exx = texx # Start at end of this element exy = texy c.addtag_withtag(tag, t) # Retag this element c.dtag(t, t) # Drop old tags if exx == 0: # Nothing drawn, Add a line segment with an arrow in the middle exx = sep * 2 c.create_line(0,0,sep,0, width=s.line_width, tags=(tag,), arrow='last') c.create_line(sep, 0,exx,0, width=s.line_width, tags=(tag,)) exx = sep return [tag, exx, exy]
python
def draw_line(self, lx, ltor): '''Draw a series of elements from left to right''' tag = self.get_tag() c = self.canvas s = self.style sep = s.h_sep exx = 0 exy = 0 terms = lx if ltor else reversed(lx) # Reverse so we can draw left to right for term in terms: t, texx, texy = self.draw_diagram(term, ltor) # Draw each element if exx > 0: # Second element onward xn = exx + sep # Add space between elements c.move(t, xn, exy) # Shift last element forward arr = 'last' if ltor else 'first' c.create_line(exx-1, exy, xn, exy, tags=(tag,), width=s.line_width, arrow=arr) # Connecting line (NOTE: -1 fudge) exx = xn + texx # Start at end of this element else: # First element exx = texx # Start at end of this element exy = texy c.addtag_withtag(tag, t) # Retag this element c.dtag(t, t) # Drop old tags if exx == 0: # Nothing drawn, Add a line segment with an arrow in the middle exx = sep * 2 c.create_line(0,0,sep,0, width=s.line_width, tags=(tag,), arrow='last') c.create_line(sep, 0,exx,0, width=s.line_width, tags=(tag,)) exx = sep return [tag, exx, exy]
Draw a series of elements from left to right
https://github.com/kevinpt/syntrax/blob/eecc2714731ec6475d264326441e0f2a47467c28/syntrax.py#L1291-L1325
akolpakov/django-unused-media
django_unused_media/utils.py
get_file_fields
def get_file_fields(): """ Get all fields which are inherited from FileField """ # get models all_models = apps.get_models() # get fields fields = [] for model in all_models: for field in model._meta.get_fields(): if isinstance(field, models.FileField): fields.append(field) return fields
python
def get_file_fields(): """ Get all fields which are inherited from FileField """ # get models all_models = apps.get_models() # get fields fields = [] for model in all_models: for field in model._meta.get_fields(): if isinstance(field, models.FileField): fields.append(field) return fields
Get all fields which are inherited from FileField
https://github.com/akolpakov/django-unused-media/blob/0a6c38840f4eac49d285c7be5da7330a564cee92/django_unused_media/utils.py#L7-L25
akolpakov/django-unused-media
django_unused_media/remove.py
remove_media
def remove_media(files): """ Delete file from media dir """ for filename in files: os.remove(os.path.join(settings.MEDIA_ROOT, filename))
python
def remove_media(files): """ Delete file from media dir """ for filename in files: os.remove(os.path.join(settings.MEDIA_ROOT, filename))
Delete file from media dir
https://github.com/akolpakov/django-unused-media/blob/0a6c38840f4eac49d285c7be5da7330a564cee92/django_unused_media/remove.py#L8-L13
akolpakov/django-unused-media
django_unused_media/remove.py
remove_empty_dirs
def remove_empty_dirs(path=None): """ Recursively delete empty directories; return True if everything was deleted. """ if not path: path = settings.MEDIA_ROOT if not os.path.isdir(path): return False listdir = [os.path.join(path, filename) for filename in os.listdir(path)] if all(list(map(remove_empty_dirs, listdir))): os.rmdir(path) return True else: return False
python
def remove_empty_dirs(path=None): """ Recursively delete empty directories; return True if everything was deleted. """ if not path: path = settings.MEDIA_ROOT if not os.path.isdir(path): return False listdir = [os.path.join(path, filename) for filename in os.listdir(path)] if all(list(map(remove_empty_dirs, listdir))): os.rmdir(path) return True else: return False
Recursively delete empty directories; return True if everything was deleted.
https://github.com/akolpakov/django-unused-media/blob/0a6c38840f4eac49d285c7be5da7330a564cee92/django_unused_media/remove.py#L16-L33
akolpakov/django-unused-media
django_unused_media/cleanup.py
get_used_media
def get_used_media(): """ Get media which are still used in models """ media = set() for field in get_file_fields(): is_null = { '%s__isnull' % field.name: True, } is_empty = { '%s' % field.name: '', } storage = field.storage for value in field.model.objects \ .values_list(field.name, flat=True) \ .exclude(**is_empty).exclude(**is_null): if value not in EMPTY_VALUES: media.add(storage.path(value)) return media
python
def get_used_media(): """ Get media which are still used in models """ media = set() for field in get_file_fields(): is_null = { '%s__isnull' % field.name: True, } is_empty = { '%s' % field.name: '', } storage = field.storage for value in field.model.objects \ .values_list(field.name, flat=True) \ .exclude(**is_empty).exclude(**is_null): if value not in EMPTY_VALUES: media.add(storage.path(value)) return media
Get media which are still used in models
https://github.com/akolpakov/django-unused-media/blob/0a6c38840f4eac49d285c7be5da7330a564cee92/django_unused_media/cleanup.py#L14-L37
akolpakov/django-unused-media
django_unused_media/cleanup.py
get_all_media
def get_all_media(exclude=None): """ Get all media from MEDIA_ROOT """ if not exclude: exclude = [] media = set() for root, dirs, files in os.walk(six.text_type(settings.MEDIA_ROOT)): for name in files: path = os.path.abspath(os.path.join(root, name)) relpath = os.path.relpath(path, settings.MEDIA_ROOT) for e in exclude: if re.match(r'^%s$' % re.escape(e).replace('\\*', '.*'), relpath): break else: media.add(path) return media
python
def get_all_media(exclude=None): """ Get all media from MEDIA_ROOT """ if not exclude: exclude = [] media = set() for root, dirs, files in os.walk(six.text_type(settings.MEDIA_ROOT)): for name in files: path = os.path.abspath(os.path.join(root, name)) relpath = os.path.relpath(path, settings.MEDIA_ROOT) for e in exclude: if re.match(r'^%s$' % re.escape(e).replace('\\*', '.*'), relpath): break else: media.add(path) return media
Get all media from MEDIA_ROOT
https://github.com/akolpakov/django-unused-media/blob/0a6c38840f4eac49d285c7be5da7330a564cee92/django_unused_media/cleanup.py#L40-L60
akolpakov/django-unused-media
django_unused_media/cleanup.py
get_unused_media
def get_unused_media(exclude=None): """ Get media which are not used in models """ if not exclude: exclude = [] all_media = get_all_media(exclude) used_media = get_used_media() return all_media - used_media
python
def get_unused_media(exclude=None): """ Get media which are not used in models """ if not exclude: exclude = [] all_media = get_all_media(exclude) used_media = get_used_media() return all_media - used_media
Get media which are not used in models
https://github.com/akolpakov/django-unused-media/blob/0a6c38840f4eac49d285c7be5da7330a564cee92/django_unused_media/cleanup.py#L63-L74
hazelcast/hazelcast-remote-controller
python-controller/hzrc/RemoteController.py
Client.createCluster
def createCluster(self, hzVersion, xmlconfig): """ Parameters: - hzVersion - xmlconfig """ self.send_createCluster(hzVersion, xmlconfig) return self.recv_createCluster()
python
def createCluster(self, hzVersion, xmlconfig): """ Parameters: - hzVersion - xmlconfig """ self.send_createCluster(hzVersion, xmlconfig) return self.recv_createCluster()
Parameters: - hzVersion - xmlconfig
https://github.com/hazelcast/hazelcast-remote-controller/blob/41b9e7d2d722b69ff79642eb34b702c9a6087635/python-controller/hzrc/RemoteController.py#L199-L206
hazelcast/hazelcast-remote-controller
python-controller/hzrc/RemoteController.py
Client.shutdownMember
def shutdownMember(self, clusterId, memberId): """ Parameters: - clusterId - memberId """ self.send_shutdownMember(clusterId, memberId) return self.recv_shutdownMember()
python
def shutdownMember(self, clusterId, memberId): """ Parameters: - clusterId - memberId """ self.send_shutdownMember(clusterId, memberId) return self.recv_shutdownMember()
Parameters: - clusterId - memberId
https://github.com/hazelcast/hazelcast-remote-controller/blob/41b9e7d2d722b69ff79642eb34b702c9a6087635/python-controller/hzrc/RemoteController.py#L267-L274
hazelcast/hazelcast-remote-controller
python-controller/hzrc/RemoteController.py
Client.terminateMember
def terminateMember(self, clusterId, memberId): """ Parameters: - clusterId - memberId """ self.send_terminateMember(clusterId, memberId) return self.recv_terminateMember()
python
def terminateMember(self, clusterId, memberId): """ Parameters: - clusterId - memberId """ self.send_terminateMember(clusterId, memberId) return self.recv_terminateMember()
Parameters: - clusterId - memberId
https://github.com/hazelcast/hazelcast-remote-controller/blob/41b9e7d2d722b69ff79642eb34b702c9a6087635/python-controller/hzrc/RemoteController.py#L300-L307
hazelcast/hazelcast-remote-controller
python-controller/hzrc/RemoteController.py
Client.suspendMember
def suspendMember(self, clusterId, memberId): """ Parameters: - clusterId - memberId """ self.send_suspendMember(clusterId, memberId) return self.recv_suspendMember()
python
def suspendMember(self, clusterId, memberId): """ Parameters: - clusterId - memberId """ self.send_suspendMember(clusterId, memberId) return self.recv_suspendMember()
Parameters: - clusterId - memberId
https://github.com/hazelcast/hazelcast-remote-controller/blob/41b9e7d2d722b69ff79642eb34b702c9a6087635/python-controller/hzrc/RemoteController.py#L333-L340
hazelcast/hazelcast-remote-controller
python-controller/hzrc/RemoteController.py
Client.resumeMember
def resumeMember(self, clusterId, memberId): """ Parameters: - clusterId - memberId """ self.send_resumeMember(clusterId, memberId) return self.recv_resumeMember()
python
def resumeMember(self, clusterId, memberId): """ Parameters: - clusterId - memberId """ self.send_resumeMember(clusterId, memberId) return self.recv_resumeMember()
Parameters: - clusterId - memberId
https://github.com/hazelcast/hazelcast-remote-controller/blob/41b9e7d2d722b69ff79642eb34b702c9a6087635/python-controller/hzrc/RemoteController.py#L366-L373
hazelcast/hazelcast-remote-controller
python-controller/hzrc/RemoteController.py
Client.mergeMemberToCluster
def mergeMemberToCluster(self, clusterId, memberId): """ Parameters: - clusterId - memberId """ self.send_mergeMemberToCluster(clusterId, memberId) return self.recv_mergeMemberToCluster()
python
def mergeMemberToCluster(self, clusterId, memberId): """ Parameters: - clusterId - memberId """ self.send_mergeMemberToCluster(clusterId, memberId) return self.recv_mergeMemberToCluster()
Parameters: - clusterId - memberId
https://github.com/hazelcast/hazelcast-remote-controller/blob/41b9e7d2d722b69ff79642eb34b702c9a6087635/python-controller/hzrc/RemoteController.py#L492-L499
hazelcast/hazelcast-remote-controller
python-controller/hzrc/RemoteController.py
Client.executeOnController
def executeOnController(self, clusterId, script, lang): """ Parameters: - clusterId - script - lang """ self.send_executeOnController(clusterId, script, lang) return self.recv_executeOnController()
python
def executeOnController(self, clusterId, script, lang): """ Parameters: - clusterId - script - lang """ self.send_executeOnController(clusterId, script, lang) return self.recv_executeOnController()
Parameters: - clusterId - script - lang
https://github.com/hazelcast/hazelcast-remote-controller/blob/41b9e7d2d722b69ff79642eb34b702c9a6087635/python-controller/hzrc/RemoteController.py#L525-L533
njsmith/colorspacious
colorspacious/comparison.py
deltaE
def deltaE(color1, color2, input_space="sRGB1", uniform_space="CAM02-UCS"): """Computes the :math:`\Delta E` distance between pairs of colors. :param input_space: The space the colors start out in. Can be anything recognized by :func:`cspace_convert`. Default: "sRGB1" :param uniform_space: Which space to perform the distance measurement in. This should be a uniform space like CAM02-UCS where Euclidean distance approximates similarity judgements, because otherwise the results of this function won't be very meaningful, but in fact any color space known to :func:`cspace_convert` will be accepted. By default, computes the euclidean distance in CAM02-UCS :math:`J'a'b'` space (thus giving :math:`\Delta E'`); for details, see :cite:`CAM02-UCS`. If you want the classic :math:`\Delta E^*_{ab}` defined by CIE 1976, use ``uniform_space="CIELab"``. Other good choices include ``"CAM02-LCD"`` and ``"CAM02-SCD"``. This function has no ability to perform :math:`\Delta E` calculations like CIEDE2000 that are not based on euclidean distances. This function is vectorized, i.e., color1, color2 may be arrays with shape (..., 3), in which case we compute the distance between corresponding pairs of colors. """ uniform1 = cspace_convert(color1, input_space, uniform_space) uniform2 = cspace_convert(color2, input_space, uniform_space) return np.sqrt(np.sum((uniform1 - uniform2) ** 2, axis=-1))
python
def deltaE(color1, color2, input_space="sRGB1", uniform_space="CAM02-UCS"): """Computes the :math:`\Delta E` distance between pairs of colors. :param input_space: The space the colors start out in. Can be anything recognized by :func:`cspace_convert`. Default: "sRGB1" :param uniform_space: Which space to perform the distance measurement in. This should be a uniform space like CAM02-UCS where Euclidean distance approximates similarity judgements, because otherwise the results of this function won't be very meaningful, but in fact any color space known to :func:`cspace_convert` will be accepted. By default, computes the euclidean distance in CAM02-UCS :math:`J'a'b'` space (thus giving :math:`\Delta E'`); for details, see :cite:`CAM02-UCS`. If you want the classic :math:`\Delta E^*_{ab}` defined by CIE 1976, use ``uniform_space="CIELab"``. Other good choices include ``"CAM02-LCD"`` and ``"CAM02-SCD"``. This function has no ability to perform :math:`\Delta E` calculations like CIEDE2000 that are not based on euclidean distances. This function is vectorized, i.e., color1, color2 may be arrays with shape (..., 3), in which case we compute the distance between corresponding pairs of colors. """ uniform1 = cspace_convert(color1, input_space, uniform_space) uniform2 = cspace_convert(color2, input_space, uniform_space) return np.sqrt(np.sum((uniform1 - uniform2) ** 2, axis=-1))
Computes the :math:`\Delta E` distance between pairs of colors. :param input_space: The space the colors start out in. Can be anything recognized by :func:`cspace_convert`. Default: "sRGB1" :param uniform_space: Which space to perform the distance measurement in. This should be a uniform space like CAM02-UCS where Euclidean distance approximates similarity judgements, because otherwise the results of this function won't be very meaningful, but in fact any color space known to :func:`cspace_convert` will be accepted. By default, computes the euclidean distance in CAM02-UCS :math:`J'a'b'` space (thus giving :math:`\Delta E'`); for details, see :cite:`CAM02-UCS`. If you want the classic :math:`\Delta E^*_{ab}` defined by CIE 1976, use ``uniform_space="CIELab"``. Other good choices include ``"CAM02-LCD"`` and ``"CAM02-SCD"``. This function has no ability to perform :math:`\Delta E` calculations like CIEDE2000 that are not based on euclidean distances. This function is vectorized, i.e., color1, color2 may be arrays with shape (..., 3), in which case we compute the distance between corresponding pairs of colors.
https://github.com/njsmith/colorspacious/blob/59e0226003fb1b894597c5081e8ca5a3aa4fcefd/colorspacious/comparison.py#L9-L38
njsmith/colorspacious
colorspacious/basics.py
XYZ100_to_sRGB1_linear
def XYZ100_to_sRGB1_linear(XYZ100): """Convert XYZ to linear sRGB, where XYZ is normalized so that reference white D65 is X=95.05, Y=100, Z=108.90 and sRGB is on the 0-1 scale. Linear sRGB has a linear relationship to actual light, so it is an appropriate space for simulating light (e.g. for alpha blending). """ XYZ100 = np.asarray(XYZ100, dtype=float) # this is broadcasting matrix * array-of-vectors, where the vector is the # last dim RGB_linear = np.einsum("...ij,...j->...i", XYZ100_to_sRGB1_matrix, XYZ100 / 100) return RGB_linear
python
def XYZ100_to_sRGB1_linear(XYZ100): """Convert XYZ to linear sRGB, where XYZ is normalized so that reference white D65 is X=95.05, Y=100, Z=108.90 and sRGB is on the 0-1 scale. Linear sRGB has a linear relationship to actual light, so it is an appropriate space for simulating light (e.g. for alpha blending). """ XYZ100 = np.asarray(XYZ100, dtype=float) # this is broadcasting matrix * array-of-vectors, where the vector is the # last dim RGB_linear = np.einsum("...ij,...j->...i", XYZ100_to_sRGB1_matrix, XYZ100 / 100) return RGB_linear
Convert XYZ to linear sRGB, where XYZ is normalized so that reference white D65 is X=95.05, Y=100, Z=108.90 and sRGB is on the 0-1 scale. Linear sRGB has a linear relationship to actual light, so it is an appropriate space for simulating light (e.g. for alpha blending).
https://github.com/njsmith/colorspacious/blob/59e0226003fb1b894597c5081e8ca5a3aa4fcefd/colorspacious/basics.py#L44-L55
njsmith/colorspacious
colorspacious/basics.py
sRGB1_to_sRGB1_linear
def sRGB1_to_sRGB1_linear(sRGB1): """Convert sRGB (as floats in the 0-to-1 range) to linear sRGB.""" sRGB1 = np.asarray(sRGB1, dtype=float) sRGB1_linear = C_linear(sRGB1) return sRGB1_linear
python
def sRGB1_to_sRGB1_linear(sRGB1): """Convert sRGB (as floats in the 0-to-1 range) to linear sRGB.""" sRGB1 = np.asarray(sRGB1, dtype=float) sRGB1_linear = C_linear(sRGB1) return sRGB1_linear
Convert sRGB (as floats in the 0-to-1 range) to linear sRGB.
https://github.com/njsmith/colorspacious/blob/59e0226003fb1b894597c5081e8ca5a3aa4fcefd/colorspacious/basics.py#L60-L64
njsmith/colorspacious
colorspacious/conversion.py
cspace_converter
def cspace_converter(start, end): """Returns a function for converting from colorspace ``start`` to colorspace ``end``. E.g., these are equivalent:: out = cspace_convert(arr, start, end) :: start_to_end_fn = cspace_converter(start, end) out = start_to_end_fn(arr) If you are doing a large number of conversions between the same pair of spaces, then calling this function once and then using the returned function repeatedly will be slightly more efficient than calling :func:`cspace_convert` repeatedly. But I wouldn't bother unless you know that this is a bottleneck for you, or it simplifies your code. """ start = norm_cspace_id(start) end = norm_cspace_id(end) return GRAPH.get_transform(start, end)
python
def cspace_converter(start, end): """Returns a function for converting from colorspace ``start`` to colorspace ``end``. E.g., these are equivalent:: out = cspace_convert(arr, start, end) :: start_to_end_fn = cspace_converter(start, end) out = start_to_end_fn(arr) If you are doing a large number of conversions between the same pair of spaces, then calling this function once and then using the returned function repeatedly will be slightly more efficient than calling :func:`cspace_convert` repeatedly. But I wouldn't bother unless you know that this is a bottleneck for you, or it simplifies your code. """ start = norm_cspace_id(start) end = norm_cspace_id(end) return GRAPH.get_transform(start, end)
Returns a function for converting from colorspace ``start`` to colorspace ``end``. E.g., these are equivalent:: out = cspace_convert(arr, start, end) :: start_to_end_fn = cspace_converter(start, end) out = start_to_end_fn(arr) If you are doing a large number of conversions between the same pair of spaces, then calling this function once and then using the returned function repeatedly will be slightly more efficient than calling :func:`cspace_convert` repeatedly. But I wouldn't bother unless you know that this is a bottleneck for you, or it simplifies your code.
https://github.com/njsmith/colorspacious/blob/59e0226003fb1b894597c5081e8ca5a3aa4fcefd/colorspacious/conversion.py#L198-L220
njsmith/colorspacious
colorspacious/conversion.py
cspace_convert
def cspace_convert(arr, start, end): """Converts the colors in ``arr`` from colorspace ``start`` to colorspace ``end``. :param arr: An array-like of colors. :param start, end: Any supported colorspace specifiers. See :ref:`supported-colorspaces` for details. """ converter = cspace_converter(start, end) return converter(arr)
python
def cspace_convert(arr, start, end): """Converts the colors in ``arr`` from colorspace ``start`` to colorspace ``end``. :param arr: An array-like of colors. :param start, end: Any supported colorspace specifiers. See :ref:`supported-colorspaces` for details. """ converter = cspace_converter(start, end) return converter(arr)
Converts the colors in ``arr`` from colorspace ``start`` to colorspace ``end``. :param arr: An array-like of colors. :param start, end: Any supported colorspace specifiers. See :ref:`supported-colorspaces` for details.
https://github.com/njsmith/colorspacious/blob/59e0226003fb1b894597c5081e8ca5a3aa4fcefd/colorspacious/conversion.py#L222-L232
njsmith/colorspacious
colorspacious/ciecam02.py
CIECAM02Space.XYZ100_to_CIECAM02
def XYZ100_to_CIECAM02(self, XYZ100, on_negative_A="raise"): """Computes CIECAM02 appearance correlates for the given tristimulus value(s) XYZ (normalized to be on the 0-100 scale). Example: ``vc.XYZ100_to_CIECAM02([30.0, 45.5, 21.0])`` :param XYZ100: An array-like of tristimulus values. These should be given on the 0-100 scale, not the 0-1 scale. The array-like should have shape ``(..., 3)``; e.g., you can use a simple 3-item list (shape = ``(3,)``), or to efficiently perform multiple computations at once, you could pass a higher-dimensional array, e.g. an image. :arg on_negative_A: A known infelicity of the CIECAM02 model is that for some inputs, the achromatic signal :math:`A` can be negative, which makes it impossible to compute :math:`J`, :math:`C`, :math:`Q`, :math:`M`, or :math:`s` -- only :math:`h`: and :math:`H` are spared. (See, e.g., section 2.6.4.1 of :cite:`Luo-CIECAM02` for discussion.) This argument allows you to specify a strategy for handling such points. Options are: * ``"raise"``: throws a :class:`NegativeAError` (a subclass of :class:`ValueError`) * ``"nan"``: return not-a-number values for the affected elements. (This may be particularly useful if converting a large number of points at once.) :returns: A named tuple of type :class:`JChQMsH`, with attributes ``J``, ``C``, ``h``, ``Q``, ``M``, ``s``, and ``H`` containing the CIECAM02 appearance correlates. """ #### Argument checking XYZ100 = np.asarray(XYZ100, dtype=float) if XYZ100.shape[-1] != 3: raise ValueError("XYZ100 shape must be (..., 3)") #### Step 1 RGB = broadcasting_matvec(M_CAT02, XYZ100) #### Step 2 RGB_C = self.D_RGB * RGB #### Step 3 RGBprime = broadcasting_matvec(M_HPE_M_CAT02_inv, RGB_C) #### Step 4 RGBprime_signs = np.sign(RGBprime) tmp = (self.F_L * RGBprime_signs * RGBprime / 100) ** 0.42 RGBprime_a = RGBprime_signs * 400 * (tmp / (tmp + 27.13)) + 0.1 #### Step 5 a = broadcasting_matvec([1, -12. / 11, 1. / 11], RGBprime_a) b = broadcasting_matvec([1. / 9, 1. / 9, -2. / 9], RGBprime_a) h_rad = np.arctan2(b, a) h = np.rad2deg(h_rad) % 360 # #### Step 6 # hprime = h, unless h < 20.14, in which case hprime = h + 360. hprime = np.select([h < h_i[0], True], [h + 360, h]) # we use 0-based indexing, so our i is one less than the reference # formulas' i. i = np.searchsorted(h_i, hprime, side="right") - 1 tmp = (hprime - h_i[i]) / e_i[i] H = H_i[i] + ((100 * tmp) / (tmp + (h_i[i + 1] - hprime) / e_i[i + 1])) #### Step 7 A = ((broadcasting_matvec([2, 1, 1. / 20], RGBprime_a) - 0.305) * self.N_bb) if on_negative_A == "raise": if np.any(A < 0): raise NegativeAError("attempted to convert a tristimulus " "value whose achromatic signal was " "negative, and on_negative_A=\"raise\"") elif on_negative_A == "nan": A = np.select([A < 0, True], [np.nan, A]) else: raise ValueError("Invalid on_negative_A argument: got %r, " "expected \"raise\" or \"nan\"" % (on_negative_A,)) #### Step 8 J = 100 * (A / self.A_w) ** (self.c * self.z) #### Step 9 Q = self._J_to_Q(J) #### Step 10 e = (12500. / 13) * self.N_c * self.N_cb * (np.cos(h_rad + 2) + 3.8) t = (e * np.sqrt(a ** 2 + b ** 2) / broadcasting_matvec([1, 1, 21. / 20], RGBprime_a)) C = t**0.9 * (J / 100)**0.5 * (1.64 - 0.29**self.n)**0.73 M = C * self.F_L**0.25 s = 100 * (M / Q)**0.5 return JChQMsH(J, C, h, Q, M, s, H)
python
def XYZ100_to_CIECAM02(self, XYZ100, on_negative_A="raise"): """Computes CIECAM02 appearance correlates for the given tristimulus value(s) XYZ (normalized to be on the 0-100 scale). Example: ``vc.XYZ100_to_CIECAM02([30.0, 45.5, 21.0])`` :param XYZ100: An array-like of tristimulus values. These should be given on the 0-100 scale, not the 0-1 scale. The array-like should have shape ``(..., 3)``; e.g., you can use a simple 3-item list (shape = ``(3,)``), or to efficiently perform multiple computations at once, you could pass a higher-dimensional array, e.g. an image. :arg on_negative_A: A known infelicity of the CIECAM02 model is that for some inputs, the achromatic signal :math:`A` can be negative, which makes it impossible to compute :math:`J`, :math:`C`, :math:`Q`, :math:`M`, or :math:`s` -- only :math:`h`: and :math:`H` are spared. (See, e.g., section 2.6.4.1 of :cite:`Luo-CIECAM02` for discussion.) This argument allows you to specify a strategy for handling such points. Options are: * ``"raise"``: throws a :class:`NegativeAError` (a subclass of :class:`ValueError`) * ``"nan"``: return not-a-number values for the affected elements. (This may be particularly useful if converting a large number of points at once.) :returns: A named tuple of type :class:`JChQMsH`, with attributes ``J``, ``C``, ``h``, ``Q``, ``M``, ``s``, and ``H`` containing the CIECAM02 appearance correlates. """ #### Argument checking XYZ100 = np.asarray(XYZ100, dtype=float) if XYZ100.shape[-1] != 3: raise ValueError("XYZ100 shape must be (..., 3)") #### Step 1 RGB = broadcasting_matvec(M_CAT02, XYZ100) #### Step 2 RGB_C = self.D_RGB * RGB #### Step 3 RGBprime = broadcasting_matvec(M_HPE_M_CAT02_inv, RGB_C) #### Step 4 RGBprime_signs = np.sign(RGBprime) tmp = (self.F_L * RGBprime_signs * RGBprime / 100) ** 0.42 RGBprime_a = RGBprime_signs * 400 * (tmp / (tmp + 27.13)) + 0.1 #### Step 5 a = broadcasting_matvec([1, -12. / 11, 1. / 11], RGBprime_a) b = broadcasting_matvec([1. / 9, 1. / 9, -2. / 9], RGBprime_a) h_rad = np.arctan2(b, a) h = np.rad2deg(h_rad) % 360 # #### Step 6 # hprime = h, unless h < 20.14, in which case hprime = h + 360. hprime = np.select([h < h_i[0], True], [h + 360, h]) # we use 0-based indexing, so our i is one less than the reference # formulas' i. i = np.searchsorted(h_i, hprime, side="right") - 1 tmp = (hprime - h_i[i]) / e_i[i] H = H_i[i] + ((100 * tmp) / (tmp + (h_i[i + 1] - hprime) / e_i[i + 1])) #### Step 7 A = ((broadcasting_matvec([2, 1, 1. / 20], RGBprime_a) - 0.305) * self.N_bb) if on_negative_A == "raise": if np.any(A < 0): raise NegativeAError("attempted to convert a tristimulus " "value whose achromatic signal was " "negative, and on_negative_A=\"raise\"") elif on_negative_A == "nan": A = np.select([A < 0, True], [np.nan, A]) else: raise ValueError("Invalid on_negative_A argument: got %r, " "expected \"raise\" or \"nan\"" % (on_negative_A,)) #### Step 8 J = 100 * (A / self.A_w) ** (self.c * self.z) #### Step 9 Q = self._J_to_Q(J) #### Step 10 e = (12500. / 13) * self.N_c * self.N_cb * (np.cos(h_rad + 2) + 3.8) t = (e * np.sqrt(a ** 2 + b ** 2) / broadcasting_matvec([1, 1, 21. / 20], RGBprime_a)) C = t**0.9 * (J / 100)**0.5 * (1.64 - 0.29**self.n)**0.73 M = C * self.F_L**0.25 s = 100 * (M / Q)**0.5 return JChQMsH(J, C, h, Q, M, s, H)
Computes CIECAM02 appearance correlates for the given tristimulus value(s) XYZ (normalized to be on the 0-100 scale). Example: ``vc.XYZ100_to_CIECAM02([30.0, 45.5, 21.0])`` :param XYZ100: An array-like of tristimulus values. These should be given on the 0-100 scale, not the 0-1 scale. The array-like should have shape ``(..., 3)``; e.g., you can use a simple 3-item list (shape = ``(3,)``), or to efficiently perform multiple computations at once, you could pass a higher-dimensional array, e.g. an image. :arg on_negative_A: A known infelicity of the CIECAM02 model is that for some inputs, the achromatic signal :math:`A` can be negative, which makes it impossible to compute :math:`J`, :math:`C`, :math:`Q`, :math:`M`, or :math:`s` -- only :math:`h`: and :math:`H` are spared. (See, e.g., section 2.6.4.1 of :cite:`Luo-CIECAM02` for discussion.) This argument allows you to specify a strategy for handling such points. Options are: * ``"raise"``: throws a :class:`NegativeAError` (a subclass of :class:`ValueError`) * ``"nan"``: return not-a-number values for the affected elements. (This may be particularly useful if converting a large number of points at once.) :returns: A named tuple of type :class:`JChQMsH`, with attributes ``J``, ``C``, ``h``, ``Q``, ``M``, ``s``, and ``H`` containing the CIECAM02 appearance correlates.
https://github.com/njsmith/colorspacious/blob/59e0226003fb1b894597c5081e8ca5a3aa4fcefd/colorspacious/ciecam02.py#L143-L252
njsmith/colorspacious
colorspacious/ciecam02.py
CIECAM02Space.CIECAM02_to_XYZ100
def CIECAM02_to_XYZ100(self, J=None, C=None, h=None, Q=None, M=None, s=None, H=None): """Return the unique tristimulus values that have the given CIECAM02 appearance correlates under these viewing conditions. You must specify 3 arguments: * Exactly one of ``J`` and ``Q`` * Exactly one of ``C``, ``M``, and ``s`` * Exactly one of ``h`` and ``H``. Arguments can be vectors, in which case they will be broadcast against each other. Returned tristimulus values will be on the 0-100 scale, not the 0-1 scale. """ #### Argument checking require_exactly_one(J=J, Q=Q) require_exactly_one(C=C, M=M, s=s) require_exactly_one(h=h, H=H) if J is not None: J = np.asarray(J, dtype=float) if C is not None: C = np.asarray(C, dtype=float) if h is not None: h = np.asarray(h, dtype=float) if Q is not None: Q = np.asarray(Q, dtype=float) if M is not None: M = np.asarray(M, dtype=float) if s is not None: s = np.asarray(s, dtype=float) if H is not None: H = np.asarray(H, dtype=float) #### Step 1: conversions to get JCh if J is None: J = 6.25 * ((self.c * Q) / ((self.A_w + 4) * self.F_L**0.25)) ** 2 if C is None: if M is not None: C = M / self.F_L**0.25 else: assert s is not None # when starting from s, we need Q if Q is None: Q = self._J_to_Q(J) C = (s / 100) ** 2 * (Q / self.F_L**0.25) if h is None: i = np.searchsorted(H_i, H, side="right") - 1 # BROKEN: num1 = (H - H_i[i]) * (e_i[i + 1] * h_i[i] - e_i[i] * h_i[i + 1]) num2 = -100 * h_i[i] * e_i[i + 1] denom1 = (H - H_i[i]) * (e_i[i + 1] - e_i[i]) denom2 = -100 * e_i[i + 1] hprime = (num1 + num2) / (denom1 + denom2) h = np.select([hprime > 360, True], [hprime - 360, hprime]) J, C, h = np.broadcast_arrays(J, C, h) target_shape = J.shape # 0d arrays break indexing stuff if J.ndim == 0: J = np.atleast_1d(J) C = np.atleast_1d(C) h = np.atleast_1d(h) #### Step 2 t = (C / (np.sqrt(J / 100) * (1.64 - 0.29**self.n) ** 0.73) ) ** (1 / 0.9) e_t = 0.25 * (np.cos(np.deg2rad(h) + 2) + 3.8) A = self.A_w * (J / 100) ** (1 / (self.c * self.z)) # an awkward way of calculating 1/t such that 1/0 -> inf with np.errstate(divide="ignore"): one_over_t = 1 / t one_over_t = np.select([np.isnan(one_over_t), True], [np.inf, one_over_t]) p_1 = (50000. / 13) * self.N_c * self.N_cb * e_t * one_over_t p_2 = A / self.N_bb + 0.305 p_3 = 21. / 20 #### Step 3 sin_h = np.sin(np.deg2rad(h)) cos_h = np.cos(np.deg2rad(h)) # to avoid divide-by-zero (or divide-by-eps) issues, we use different # computations when |sin_h| > |cos_h| and vice-versa num = p_2 * (2 + p_3) * (460. / 1403) denom_part2 = (2 + p_3) * (220. / 1403) denom_part3 = (-27. / 1403) + p_3 * (6300. / 1403) a = np.empty_like(h) b = np.empty_like(h) small_cos = (np.abs(sin_h) >= np.abs(cos_h)) # NB denom_part2 and denom_part3 are scalars b[small_cos] = (num[small_cos] / (p_1[small_cos] / sin_h[small_cos] + (denom_part2 * cos_h[small_cos] / sin_h[small_cos]) + denom_part3)) a[small_cos] = b[small_cos] * cos_h[small_cos] / sin_h[small_cos] a[~small_cos] = (num[~small_cos] / (p_1[~small_cos] / cos_h[~small_cos] + denom_part2 + (denom_part3 * sin_h[~small_cos] / cos_h[~small_cos]))) b[~small_cos] = a[~small_cos] * sin_h[~small_cos] / cos_h[~small_cos] #### Step 4 p2ab = np.concatenate((p_2[..., np.newaxis], a[..., np.newaxis], b[..., np.newaxis]), axis=-1) RGBprime_a_matrix = (1. / 1403 * np.asarray([[ 460, 451, 288], [ 460, -891, -261], [ 460, -220, -6300]], dtype=float)) RGBprime_a = broadcasting_matvec(RGBprime_a_matrix, p2ab) #### Step 5 RGBprime = (np.sign(RGBprime_a - 0.1) * (100 / self.F_L) * ((27.13 * np.abs(RGBprime_a - 0.1)) / (400 - np.abs(RGBprime_a - 0.1))) ** (1 / 0.42)) #### Step 6 RGB_C = broadcasting_matvec(M_CAT02_M_HPE_inv, RGBprime) #### Step 7 RGB = RGB_C / self.D_RGB #### Step 8 XYZ100 = broadcasting_matvec(M_CAT02_inv, RGB) XYZ100 = XYZ100.reshape(target_shape + (3,)) return XYZ100
python
def CIECAM02_to_XYZ100(self, J=None, C=None, h=None, Q=None, M=None, s=None, H=None): """Return the unique tristimulus values that have the given CIECAM02 appearance correlates under these viewing conditions. You must specify 3 arguments: * Exactly one of ``J`` and ``Q`` * Exactly one of ``C``, ``M``, and ``s`` * Exactly one of ``h`` and ``H``. Arguments can be vectors, in which case they will be broadcast against each other. Returned tristimulus values will be on the 0-100 scale, not the 0-1 scale. """ #### Argument checking require_exactly_one(J=J, Q=Q) require_exactly_one(C=C, M=M, s=s) require_exactly_one(h=h, H=H) if J is not None: J = np.asarray(J, dtype=float) if C is not None: C = np.asarray(C, dtype=float) if h is not None: h = np.asarray(h, dtype=float) if Q is not None: Q = np.asarray(Q, dtype=float) if M is not None: M = np.asarray(M, dtype=float) if s is not None: s = np.asarray(s, dtype=float) if H is not None: H = np.asarray(H, dtype=float) #### Step 1: conversions to get JCh if J is None: J = 6.25 * ((self.c * Q) / ((self.A_w + 4) * self.F_L**0.25)) ** 2 if C is None: if M is not None: C = M / self.F_L**0.25 else: assert s is not None # when starting from s, we need Q if Q is None: Q = self._J_to_Q(J) C = (s / 100) ** 2 * (Q / self.F_L**0.25) if h is None: i = np.searchsorted(H_i, H, side="right") - 1 # BROKEN: num1 = (H - H_i[i]) * (e_i[i + 1] * h_i[i] - e_i[i] * h_i[i + 1]) num2 = -100 * h_i[i] * e_i[i + 1] denom1 = (H - H_i[i]) * (e_i[i + 1] - e_i[i]) denom2 = -100 * e_i[i + 1] hprime = (num1 + num2) / (denom1 + denom2) h = np.select([hprime > 360, True], [hprime - 360, hprime]) J, C, h = np.broadcast_arrays(J, C, h) target_shape = J.shape # 0d arrays break indexing stuff if J.ndim == 0: J = np.atleast_1d(J) C = np.atleast_1d(C) h = np.atleast_1d(h) #### Step 2 t = (C / (np.sqrt(J / 100) * (1.64 - 0.29**self.n) ** 0.73) ) ** (1 / 0.9) e_t = 0.25 * (np.cos(np.deg2rad(h) + 2) + 3.8) A = self.A_w * (J / 100) ** (1 / (self.c * self.z)) # an awkward way of calculating 1/t such that 1/0 -> inf with np.errstate(divide="ignore"): one_over_t = 1 / t one_over_t = np.select([np.isnan(one_over_t), True], [np.inf, one_over_t]) p_1 = (50000. / 13) * self.N_c * self.N_cb * e_t * one_over_t p_2 = A / self.N_bb + 0.305 p_3 = 21. / 20 #### Step 3 sin_h = np.sin(np.deg2rad(h)) cos_h = np.cos(np.deg2rad(h)) # to avoid divide-by-zero (or divide-by-eps) issues, we use different # computations when |sin_h| > |cos_h| and vice-versa num = p_2 * (2 + p_3) * (460. / 1403) denom_part2 = (2 + p_3) * (220. / 1403) denom_part3 = (-27. / 1403) + p_3 * (6300. / 1403) a = np.empty_like(h) b = np.empty_like(h) small_cos = (np.abs(sin_h) >= np.abs(cos_h)) # NB denom_part2 and denom_part3 are scalars b[small_cos] = (num[small_cos] / (p_1[small_cos] / sin_h[small_cos] + (denom_part2 * cos_h[small_cos] / sin_h[small_cos]) + denom_part3)) a[small_cos] = b[small_cos] * cos_h[small_cos] / sin_h[small_cos] a[~small_cos] = (num[~small_cos] / (p_1[~small_cos] / cos_h[~small_cos] + denom_part2 + (denom_part3 * sin_h[~small_cos] / cos_h[~small_cos]))) b[~small_cos] = a[~small_cos] * sin_h[~small_cos] / cos_h[~small_cos] #### Step 4 p2ab = np.concatenate((p_2[..., np.newaxis], a[..., np.newaxis], b[..., np.newaxis]), axis=-1) RGBprime_a_matrix = (1. / 1403 * np.asarray([[ 460, 451, 288], [ 460, -891, -261], [ 460, -220, -6300]], dtype=float)) RGBprime_a = broadcasting_matvec(RGBprime_a_matrix, p2ab) #### Step 5 RGBprime = (np.sign(RGBprime_a - 0.1) * (100 / self.F_L) * ((27.13 * np.abs(RGBprime_a - 0.1)) / (400 - np.abs(RGBprime_a - 0.1))) ** (1 / 0.42)) #### Step 6 RGB_C = broadcasting_matvec(M_CAT02_M_HPE_inv, RGBprime) #### Step 7 RGB = RGB_C / self.D_RGB #### Step 8 XYZ100 = broadcasting_matvec(M_CAT02_inv, RGB) XYZ100 = XYZ100.reshape(target_shape + (3,)) return XYZ100
Return the unique tristimulus values that have the given CIECAM02 appearance correlates under these viewing conditions. You must specify 3 arguments: * Exactly one of ``J`` and ``Q`` * Exactly one of ``C``, ``M``, and ``s`` * Exactly one of ``h`` and ``H``. Arguments can be vectors, in which case they will be broadcast against each other. Returned tristimulus values will be on the 0-100 scale, not the 0-1 scale.
https://github.com/njsmith/colorspacious/blob/59e0226003fb1b894597c5081e8ca5a3aa4fcefd/colorspacious/ciecam02.py#L258-L414
njsmith/colorspacious
colorspacious/illuminants.py
standard_illuminant_XYZ100
def standard_illuminant_XYZ100(name, observer="CIE 1931 2 deg"): """Takes a string naming a standard illuminant, and returns its XYZ coordinates (normalized to Y = 100). We currently have the following standard illuminants in our database: * ``"A"`` * ``"C"`` * ``"D50"`` * ``"D55"`` * ``"D65"`` * ``"D75"`` If you need another that isn't on this list, then feel free to send a pull request. When in doubt, use D65: it's the whitepoint used by the sRGB standard (61966-2-1:1999) and ISO 10526:1999 says "D65 should be used in all colorimetric calculations requiring representative daylight, unless there are specific reasons for using a different illuminant". By default, we return points in the XYZ space defined by the CIE 1931 2 degree standard observer. By specifying ``observer="CIE 1964 10 deg"``, you can instead get the whitepoint coordinates in XYZ space defined by the CIE 1964 10 degree observer. This is probably only useful if you have XYZ points you want to do calculations on that were somehow measured using the CIE 1964 color matching functions, perhaps via a spectrophotometer; consumer equipment (monitors, cameras, etc.) assumes the use of the CIE 1931 standard observer in all cases I know of. """ if observer == "CIE 1931 2 deg": return np.asarray(cie1931[name], dtype=float) elif observer == "CIE 1964 10 deg": return np.asarray(cie1964[name], dtype=float) else: raise ValueError("observer must be 'CIE 1931 2 deg' or " "'CIE 1964 10 deg', not %s" % (observer,))
python
def standard_illuminant_XYZ100(name, observer="CIE 1931 2 deg"): """Takes a string naming a standard illuminant, and returns its XYZ coordinates (normalized to Y = 100). We currently have the following standard illuminants in our database: * ``"A"`` * ``"C"`` * ``"D50"`` * ``"D55"`` * ``"D65"`` * ``"D75"`` If you need another that isn't on this list, then feel free to send a pull request. When in doubt, use D65: it's the whitepoint used by the sRGB standard (61966-2-1:1999) and ISO 10526:1999 says "D65 should be used in all colorimetric calculations requiring representative daylight, unless there are specific reasons for using a different illuminant". By default, we return points in the XYZ space defined by the CIE 1931 2 degree standard observer. By specifying ``observer="CIE 1964 10 deg"``, you can instead get the whitepoint coordinates in XYZ space defined by the CIE 1964 10 degree observer. This is probably only useful if you have XYZ points you want to do calculations on that were somehow measured using the CIE 1964 color matching functions, perhaps via a spectrophotometer; consumer equipment (monitors, cameras, etc.) assumes the use of the CIE 1931 standard observer in all cases I know of. """ if observer == "CIE 1931 2 deg": return np.asarray(cie1931[name], dtype=float) elif observer == "CIE 1964 10 deg": return np.asarray(cie1964[name], dtype=float) else: raise ValueError("observer must be 'CIE 1931 2 deg' or " "'CIE 1964 10 deg', not %s" % (observer,))
Takes a string naming a standard illuminant, and returns its XYZ coordinates (normalized to Y = 100). We currently have the following standard illuminants in our database: * ``"A"`` * ``"C"`` * ``"D50"`` * ``"D55"`` * ``"D65"`` * ``"D75"`` If you need another that isn't on this list, then feel free to send a pull request. When in doubt, use D65: it's the whitepoint used by the sRGB standard (61966-2-1:1999) and ISO 10526:1999 says "D65 should be used in all colorimetric calculations requiring representative daylight, unless there are specific reasons for using a different illuminant". By default, we return points in the XYZ space defined by the CIE 1931 2 degree standard observer. By specifying ``observer="CIE 1964 10 deg"``, you can instead get the whitepoint coordinates in XYZ space defined by the CIE 1964 10 degree observer. This is probably only useful if you have XYZ points you want to do calculations on that were somehow measured using the CIE 1964 color matching functions, perhaps via a spectrophotometer; consumer equipment (monitors, cameras, etc.) assumes the use of the CIE 1931 standard observer in all cases I know of.
https://github.com/njsmith/colorspacious/blob/59e0226003fb1b894597c5081e8ca5a3aa4fcefd/colorspacious/illuminants.py#L44-L81
njsmith/colorspacious
colorspacious/illuminants.py
as_XYZ100_w
def as_XYZ100_w(whitepoint): """A convenience function for getting whitepoints. ``whitepoint`` can be either a string naming a standard illuminant (see :func:`standard_illuminant_XYZ100`), or else a whitepoint given explicitly as an array-like of XYZ values. We internally call this function anywhere you have to specify a whitepoint (e.g. for CIECAM02 or CIELAB conversions). Always uses the "standard" 2 degree observer. """ if isinstance(whitepoint, str): return standard_illuminant_XYZ100(whitepoint) else: whitepoint = np.asarray(whitepoint, dtype=float) if whitepoint.shape[-1] != 3: raise ValueError("Bad whitepoint shape") return whitepoint
python
def as_XYZ100_w(whitepoint): """A convenience function for getting whitepoints. ``whitepoint`` can be either a string naming a standard illuminant (see :func:`standard_illuminant_XYZ100`), or else a whitepoint given explicitly as an array-like of XYZ values. We internally call this function anywhere you have to specify a whitepoint (e.g. for CIECAM02 or CIELAB conversions). Always uses the "standard" 2 degree observer. """ if isinstance(whitepoint, str): return standard_illuminant_XYZ100(whitepoint) else: whitepoint = np.asarray(whitepoint, dtype=float) if whitepoint.shape[-1] != 3: raise ValueError("Bad whitepoint shape") return whitepoint
A convenience function for getting whitepoints. ``whitepoint`` can be either a string naming a standard illuminant (see :func:`standard_illuminant_XYZ100`), or else a whitepoint given explicitly as an array-like of XYZ values. We internally call this function anywhere you have to specify a whitepoint (e.g. for CIECAM02 or CIELAB conversions). Always uses the "standard" 2 degree observer.
https://github.com/njsmith/colorspacious/blob/59e0226003fb1b894597c5081e8ca5a3aa4fcefd/colorspacious/illuminants.py#L97-L116
njsmith/colorspacious
colorspacious/cvd.py
machado_et_al_2009_matrix
def machado_et_al_2009_matrix(cvd_type, severity): """Retrieve a matrix for simulating anomalous color vision. :param cvd_type: One of "protanomaly", "deuteranomaly", or "tritanomaly". :param severity: A value between 0 and 100. :returns: A 3x3 CVD simulation matrix as computed by Machado et al (2009). These matrices were downloaded from: http://www.inf.ufrgs.br/~oliveira/pubs_files/CVD_Simulation/CVD_Simulation.html which is supplementary data from :cite:`Machado-CVD`. If severity is a multiple of 10, then simply returns the matrix from that webpage. For other severities, performs linear interpolation. """ assert 0 <= severity <= 100 fraction = severity % 10 low = int(severity - fraction) high = low + 10 assert low <= severity <= high low_matrix = np.asarray(MACHADO_ET_AL_MATRICES[cvd_type][low]) if severity == 100: # Don't try interpolating between 100 and 110, there is no 110... return low_matrix high_matrix = np.asarray(MACHADO_ET_AL_MATRICES[cvd_type][high]) return ((1 - fraction / 10.0) * low_matrix + fraction / 10.0 * high_matrix)
python
def machado_et_al_2009_matrix(cvd_type, severity): """Retrieve a matrix for simulating anomalous color vision. :param cvd_type: One of "protanomaly", "deuteranomaly", or "tritanomaly". :param severity: A value between 0 and 100. :returns: A 3x3 CVD simulation matrix as computed by Machado et al (2009). These matrices were downloaded from: http://www.inf.ufrgs.br/~oliveira/pubs_files/CVD_Simulation/CVD_Simulation.html which is supplementary data from :cite:`Machado-CVD`. If severity is a multiple of 10, then simply returns the matrix from that webpage. For other severities, performs linear interpolation. """ assert 0 <= severity <= 100 fraction = severity % 10 low = int(severity - fraction) high = low + 10 assert low <= severity <= high low_matrix = np.asarray(MACHADO_ET_AL_MATRICES[cvd_type][low]) if severity == 100: # Don't try interpolating between 100 and 110, there is no 110... return low_matrix high_matrix = np.asarray(MACHADO_ET_AL_MATRICES[cvd_type][high]) return ((1 - fraction / 10.0) * low_matrix + fraction / 10.0 * high_matrix)
Retrieve a matrix for simulating anomalous color vision. :param cvd_type: One of "protanomaly", "deuteranomaly", or "tritanomaly". :param severity: A value between 0 and 100. :returns: A 3x3 CVD simulation matrix as computed by Machado et al (2009). These matrices were downloaded from: http://www.inf.ufrgs.br/~oliveira/pubs_files/CVD_Simulation/CVD_Simulation.html which is supplementary data from :cite:`Machado-CVD`. If severity is a multiple of 10, then simply returns the matrix from that webpage. For other severities, performs linear interpolation.
https://github.com/njsmith/colorspacious/blob/59e0226003fb1b894597c5081e8ca5a3aa4fcefd/colorspacious/cvd.py#L21-L54
h2oai/typesentry
typesentry/signature.py
Signature._make_retval_checker
def _make_retval_checker(self): """Create a function that checks the return value of the function.""" rvchk = self.retval.checker if rvchk: def _checker(value): if not rvchk.check(value): raise self._type_error( "Incorrect return type in %s: expected %s got %s" % (self.name_bt, rvchk.name(), checker_for_type(type(value)).name()) ) else: def _checker(value): pass return _checker
python
def _make_retval_checker(self): """Create a function that checks the return value of the function.""" rvchk = self.retval.checker if rvchk: def _checker(value): if not rvchk.check(value): raise self._type_error( "Incorrect return type in %s: expected %s got %s" % (self.name_bt, rvchk.name(), checker_for_type(type(value)).name()) ) else: def _checker(value): pass return _checker
Create a function that checks the return value of the function.
https://github.com/h2oai/typesentry/blob/0ca8ed0e62d15ffe430545e7648c9a9b2547b49c/typesentry/signature.py#L172-L186
h2oai/typesentry
typesentry/signature.py
Signature._make_args_checker
def _make_args_checker(self): """ Create a function that checks signature of the source function. """ def _checker(*args, **kws): # Check if too many arguments are provided nargs = len(args) nnonvaargs = min(nargs, self._max_positional_args) if nargs > self._max_positional_args and self._ivararg is None: raise self._too_many_args_error(nargs) # Check if there are too few positional arguments (without defaults) if nargs < self._min_positional_args: missing = [p.name for p in self.params[nargs:self._min_positional_args] if p.name not in kws] # The "missing" arguments may still be provided as keywords, in # which case it's not an error at all. if missing: raise self._too_few_args_error(missing, "positional") # Check if there are too few required keyword arguments if self._required_kwonly_args: missing = [kw for kw in self._required_kwonly_args if kw not in kws] if missing: raise self._too_few_args_error(missing, "keyword") # Check types of positional arguments for i, argvalue in enumerate(args): param = self.params[i if i < self._max_positional_args else self._ivararg] if param.checker and not ( param.checker.check(argvalue) or param.has_default and (argvalue is param.default or argvalue == param.default) ): raise self._param_type_error(param, param.name, argvalue) # Check types of keyword arguments for argname, argvalue in kws.items(): argindex = self._iargs.get(argname) if argindex is not None and argindex < nnonvaargs: raise self._repeating_arg_error(argname) index = self._iargs.get(argname) if index is None: index = self._ivarkws if index is None: s = "%s got an unexpected keyword argument `%s`" % \ (self.name_bt, argname) raise self._type_error(s) param = self.params[index] if param.checker and not ( param.checker.check(argvalue) or param.has_default and (argvalue is param.default or argvalue == param.default) ): raise self._param_type_error(param, argname, argvalue) return _checker
python
def _make_args_checker(self): """ Create a function that checks signature of the source function. """ def _checker(*args, **kws): # Check if too many arguments are provided nargs = len(args) nnonvaargs = min(nargs, self._max_positional_args) if nargs > self._max_positional_args and self._ivararg is None: raise self._too_many_args_error(nargs) # Check if there are too few positional arguments (without defaults) if nargs < self._min_positional_args: missing = [p.name for p in self.params[nargs:self._min_positional_args] if p.name not in kws] # The "missing" arguments may still be provided as keywords, in # which case it's not an error at all. if missing: raise self._too_few_args_error(missing, "positional") # Check if there are too few required keyword arguments if self._required_kwonly_args: missing = [kw for kw in self._required_kwonly_args if kw not in kws] if missing: raise self._too_few_args_error(missing, "keyword") # Check types of positional arguments for i, argvalue in enumerate(args): param = self.params[i if i < self._max_positional_args else self._ivararg] if param.checker and not ( param.checker.check(argvalue) or param.has_default and (argvalue is param.default or argvalue == param.default) ): raise self._param_type_error(param, param.name, argvalue) # Check types of keyword arguments for argname, argvalue in kws.items(): argindex = self._iargs.get(argname) if argindex is not None and argindex < nnonvaargs: raise self._repeating_arg_error(argname) index = self._iargs.get(argname) if index is None: index = self._ivarkws if index is None: s = "%s got an unexpected keyword argument `%s`" % \ (self.name_bt, argname) raise self._type_error(s) param = self.params[index] if param.checker and not ( param.checker.check(argvalue) or param.has_default and (argvalue is param.default or argvalue == param.default) ): raise self._param_type_error(param, argname, argvalue) return _checker
Create a function that checks signature of the source function.
https://github.com/h2oai/typesentry/blob/0ca8ed0e62d15ffe430545e7648c9a9b2547b49c/typesentry/signature.py#L189-L249
h2oai/typesentry
typesentry/checks.py
checker_for_type
def checker_for_type(t): """ Return "checker" function for the given type `t`. This checker function will accept a single argument (of any type), and return True if the argument matches type `t`, or False otherwise. For example: chkr = checker_for_type(int) assert chkr.check(123) is True assert chkr.check("5") is False """ try: if t is True: return true_checker if t is False: return false_checker checker = memoized_type_checkers.get(t) if checker is not None: return checker hashable = True except TypeError: # Exception may be raised if `t` is not hashable (e.g. a dict) hashable = False # The type checker needs to be created checker = _create_checker_for_type(t) if hashable: memoized_type_checkers[t] = checker return checker
python
def checker_for_type(t): """ Return "checker" function for the given type `t`. This checker function will accept a single argument (of any type), and return True if the argument matches type `t`, or False otherwise. For example: chkr = checker_for_type(int) assert chkr.check(123) is True assert chkr.check("5") is False """ try: if t is True: return true_checker if t is False: return false_checker checker = memoized_type_checkers.get(t) if checker is not None: return checker hashable = True except TypeError: # Exception may be raised if `t` is not hashable (e.g. a dict) hashable = False # The type checker needs to be created checker = _create_checker_for_type(t) if hashable: memoized_type_checkers[t] = checker return checker
Return "checker" function for the given type `t`. This checker function will accept a single argument (of any type), and return True if the argument matches type `t`, or False otherwise. For example: chkr = checker_for_type(int) assert chkr.check(123) is True assert chkr.check("5") is False
https://github.com/h2oai/typesentry/blob/0ca8ed0e62d15ffe430545e7648c9a9b2547b49c/typesentry/checks.py#L32-L61
h2oai/typesentry
typesentry/checks.py
_prepare_value
def _prepare_value(val, maxlen=50, notype=False): """ Stringify value `val`, ensuring that it is not too long. """ if val is None or val is True or val is False: return str(val) sval = repr(val) sval = sval.replace("\n", " ").replace("\t", " ").replace("`", "'") if len(sval) > maxlen: sval = sval[:maxlen - 4] + "..." + sval[-1] if notype: return sval else: tval = checker_for_type(type(val)).name() return "%s of type %s" % (sval, tval)
python
def _prepare_value(val, maxlen=50, notype=False): """ Stringify value `val`, ensuring that it is not too long. """ if val is None or val is True or val is False: return str(val) sval = repr(val) sval = sval.replace("\n", " ").replace("\t", " ").replace("`", "'") if len(sval) > maxlen: sval = sval[:maxlen - 4] + "..." + sval[-1] if notype: return sval else: tval = checker_for_type(type(val)).name() return "%s of type %s" % (sval, tval)
Stringify value `val`, ensuring that it is not too long.
https://github.com/h2oai/typesentry/blob/0ca8ed0e62d15ffe430545e7648c9a9b2547b49c/typesentry/checks.py#L774-L788
h2oai/typesentry
typesentry/checks.py
_nth_str
def _nth_str(n): """Return posessive form of numeral `n`: 1st, 2nd, 3rd, etc.""" if n % 10 == 1 and n % 100 != 11: return "%dst" % n if n % 10 == 2 and n % 100 != 12: return "%dnd" % n if n % 10 == 3 and n % 100 != 13: return "%drd" % n return "%dth" % n
python
def _nth_str(n): """Return posessive form of numeral `n`: 1st, 2nd, 3rd, etc.""" if n % 10 == 1 and n % 100 != 11: return "%dst" % n if n % 10 == 2 and n % 100 != 12: return "%dnd" % n if n % 10 == 3 and n % 100 != 13: return "%drd" % n return "%dth" % n
Return posessive form of numeral `n`: 1st, 2nd, 3rd, etc.
https://github.com/h2oai/typesentry/blob/0ca8ed0e62d15ffe430545e7648c9a9b2547b49c/typesentry/checks.py#L790-L798
muatik/naive-bayes-classifier
naiveBayesClassifier/trainer.py
Trainer.train
def train(self, text, className): """ enhances trained data using the given text and class """ self.data.increaseClass(className) tokens = self.tokenizer.tokenize(text) for token in tokens: token = self.tokenizer.remove_stop_words(token) token = self.tokenizer.remove_punctuation(token) self.data.increaseToken(token, className)
python
def train(self, text, className): """ enhances trained data using the given text and class """ self.data.increaseClass(className) tokens = self.tokenizer.tokenize(text) for token in tokens: token = self.tokenizer.remove_stop_words(token) token = self.tokenizer.remove_punctuation(token) self.data.increaseToken(token, className)
enhances trained data using the given text and class
https://github.com/muatik/naive-bayes-classifier/blob/cdc1d8681ef6674e946cff38e87ce3b00c732fbb/naiveBayesClassifier/trainer.py#L11-L21
rene-aguirre/pywinusb
pywinusb/hid/core.py
hid_device_path_exists
def hid_device_path_exists(device_path, guid = None): """Test if required device_path is still valid (HID device connected to host) """ # expecing HID devices if not guid: guid = winapi.GetHidGuid() info_data = winapi.SP_DEVINFO_DATA() info_data.cb_size = sizeof(winapi.SP_DEVINFO_DATA) with winapi.DeviceInterfaceSetInfo(guid) as h_info: for interface_data in winapi.enum_device_interfaces(h_info, guid): test_device_path = winapi.get_device_path(h_info, interface_data, byref(info_data)) if test_device_path == device_path: return True # Not any device now with that path return False
python
def hid_device_path_exists(device_path, guid = None): """Test if required device_path is still valid (HID device connected to host) """ # expecing HID devices if not guid: guid = winapi.GetHidGuid() info_data = winapi.SP_DEVINFO_DATA() info_data.cb_size = sizeof(winapi.SP_DEVINFO_DATA) with winapi.DeviceInterfaceSetInfo(guid) as h_info: for interface_data in winapi.enum_device_interfaces(h_info, guid): test_device_path = winapi.get_device_path(h_info, interface_data, byref(info_data)) if test_device_path == device_path: return True # Not any device now with that path return False
Test if required device_path is still valid (HID device connected to host)
https://github.com/rene-aguirre/pywinusb/blob/954c4b2105d9f01cb0c50e24500bb747d4ecdc43/pywinusb/hid/core.py#L67-L86
rene-aguirre/pywinusb
pywinusb/hid/core.py
find_all_hid_devices
def find_all_hid_devices(): "Finds all HID devices connected to the system" # # From DDK documentation (finding and Opening HID collection): # After a user-mode application is loaded, it does the following sequence # of operations: # # * Calls HidD_GetHidGuid to obtain the system-defined GUID for HIDClass # devices. # # * Calls SetupDiGetClassDevs to obtain a handle to an opaque device # information set that describes the device interfaces supported by all # the HID collections currently installed in the system. The # application should specify DIGCF_PRESENT and DIGCF_INTERFACEDEVICE # in the Flags parameter passed to SetupDiGetClassDevs. # # * Calls SetupDiEnumDeviceInterfaces repeatedly to retrieve all the # available interface information. # # * Calls SetupDiGetDeviceInterfaceDetail to format interface information # for each collection as a SP_INTERFACE_DEVICE_DETAIL_DATA structure. # The device_path member of this structure contains the user-mode name # that the application uses with the Win32 function CreateFile to # obtain a file handle to a HID collection. # # get HID device class guid guid = winapi.GetHidGuid() # retrieve all the available interface information. results = [] required_size = DWORD() info_data = winapi.SP_DEVINFO_DATA() info_data.cb_size = sizeof(winapi.SP_DEVINFO_DATA) with winapi.DeviceInterfaceSetInfo(guid) as h_info: for interface_data in winapi.enum_device_interfaces(h_info, guid): device_path = winapi.get_device_path(h_info, interface_data, byref(info_data)) parent_device = c_ulong() #get parent instance id (so we can discriminate on port) if setup_api.CM_Get_Parent(byref(parent_device), info_data.dev_inst, 0) != 0: #CR_SUCCESS = 0 parent_device.value = 0 #null #get unique instance id string required_size.value = 0 winapi.SetupDiGetDeviceInstanceId(h_info, byref(info_data), None, 0, byref(required_size) ) device_instance_id = create_unicode_buffer(required_size.value) if required_size.value > 0: winapi.SetupDiGetDeviceInstanceId(h_info, byref(info_data), device_instance_id, required_size, byref(required_size) ) hid_device = HidDevice(device_path, parent_device.value, device_instance_id.value ) else: hid_device = HidDevice(device_path, parent_device.value ) # add device to results, if not protected if hid_device.vendor_id: results.append(hid_device) return results
python
def find_all_hid_devices(): "Finds all HID devices connected to the system" # # From DDK documentation (finding and Opening HID collection): # After a user-mode application is loaded, it does the following sequence # of operations: # # * Calls HidD_GetHidGuid to obtain the system-defined GUID for HIDClass # devices. # # * Calls SetupDiGetClassDevs to obtain a handle to an opaque device # information set that describes the device interfaces supported by all # the HID collections currently installed in the system. The # application should specify DIGCF_PRESENT and DIGCF_INTERFACEDEVICE # in the Flags parameter passed to SetupDiGetClassDevs. # # * Calls SetupDiEnumDeviceInterfaces repeatedly to retrieve all the # available interface information. # # * Calls SetupDiGetDeviceInterfaceDetail to format interface information # for each collection as a SP_INTERFACE_DEVICE_DETAIL_DATA structure. # The device_path member of this structure contains the user-mode name # that the application uses with the Win32 function CreateFile to # obtain a file handle to a HID collection. # # get HID device class guid guid = winapi.GetHidGuid() # retrieve all the available interface information. results = [] required_size = DWORD() info_data = winapi.SP_DEVINFO_DATA() info_data.cb_size = sizeof(winapi.SP_DEVINFO_DATA) with winapi.DeviceInterfaceSetInfo(guid) as h_info: for interface_data in winapi.enum_device_interfaces(h_info, guid): device_path = winapi.get_device_path(h_info, interface_data, byref(info_data)) parent_device = c_ulong() #get parent instance id (so we can discriminate on port) if setup_api.CM_Get_Parent(byref(parent_device), info_data.dev_inst, 0) != 0: #CR_SUCCESS = 0 parent_device.value = 0 #null #get unique instance id string required_size.value = 0 winapi.SetupDiGetDeviceInstanceId(h_info, byref(info_data), None, 0, byref(required_size) ) device_instance_id = create_unicode_buffer(required_size.value) if required_size.value > 0: winapi.SetupDiGetDeviceInstanceId(h_info, byref(info_data), device_instance_id, required_size, byref(required_size) ) hid_device = HidDevice(device_path, parent_device.value, device_instance_id.value ) else: hid_device = HidDevice(device_path, parent_device.value ) # add device to results, if not protected if hid_device.vendor_id: results.append(hid_device) return results
Finds all HID devices connected to the system
https://github.com/rene-aguirre/pywinusb/blob/954c4b2105d9f01cb0c50e24500bb747d4ecdc43/pywinusb/hid/core.py#L88-L156
rene-aguirre/pywinusb
pywinusb/hid/core.py
show_hids
def show_hids(target_vid = 0, target_pid = 0, output = None): """Check all HID devices conected to PC hosts.""" # first be kind with local encodings if not output: # beware your script should manage encodings output = sys.stdout # then the big cheese... from . import tools all_hids = None if target_vid: if target_pid: # both vendor and product Id provided device_filter = HidDeviceFilter(vendor_id = target_vid, product_id = target_pid) else: # only vendor id device_filter = HidDeviceFilter(vendor_id = target_vid) all_hids = device_filter.get_devices() else: all_hids = find_all_hid_devices() if all_hids: print("Found HID class devices!, writting details...") for dev in all_hids: device_name = str(dev) output.write(device_name) output.write('\n\n Path: %s\n' % dev.device_path) output.write('\n Instance: %s\n' % dev.instance_id) output.write('\n Port (ID): %s\n' % dev.get_parent_instance_id()) output.write('\n Port (str):%s\n' % str(dev.get_parent_device())) # try: dev.open() tools.write_documentation(dev, output) finally: dev.close() print("done!") else: print("There's not any non system HID class device available")
python
def show_hids(target_vid = 0, target_pid = 0, output = None): """Check all HID devices conected to PC hosts.""" # first be kind with local encodings if not output: # beware your script should manage encodings output = sys.stdout # then the big cheese... from . import tools all_hids = None if target_vid: if target_pid: # both vendor and product Id provided device_filter = HidDeviceFilter(vendor_id = target_vid, product_id = target_pid) else: # only vendor id device_filter = HidDeviceFilter(vendor_id = target_vid) all_hids = device_filter.get_devices() else: all_hids = find_all_hid_devices() if all_hids: print("Found HID class devices!, writting details...") for dev in all_hids: device_name = str(dev) output.write(device_name) output.write('\n\n Path: %s\n' % dev.device_path) output.write('\n Instance: %s\n' % dev.instance_id) output.write('\n Port (ID): %s\n' % dev.get_parent_instance_id()) output.write('\n Port (str):%s\n' % str(dev.get_parent_device())) # try: dev.open() tools.write_documentation(dev, output) finally: dev.close() print("done!") else: print("There's not any non system HID class device available")
Check all HID devices conected to PC hosts.
https://github.com/rene-aguirre/pywinusb/blob/954c4b2105d9f01cb0c50e24500bb747d4ecdc43/pywinusb/hid/core.py#L1571-L1609
rene-aguirre/pywinusb
pywinusb/hid/core.py
HidDeviceFilter.get_devices_by_parent
def get_devices_by_parent(self, hid_filter=None): """Group devices returned from filter query in order \ by devcice parent id. """ all_devs = self.get_devices(hid_filter) dev_group = dict() for hid_device in all_devs: #keep a list of known devices matching parent device Ids parent_id = hid_device.get_parent_instance_id() device_set = dev_group.get(parent_id, []) device_set.append(hid_device) if parent_id not in dev_group: #add new dev_group[parent_id] = device_set return dev_group
python
def get_devices_by_parent(self, hid_filter=None): """Group devices returned from filter query in order \ by devcice parent id. """ all_devs = self.get_devices(hid_filter) dev_group = dict() for hid_device in all_devs: #keep a list of known devices matching parent device Ids parent_id = hid_device.get_parent_instance_id() device_set = dev_group.get(parent_id, []) device_set.append(hid_device) if parent_id not in dev_group: #add new dev_group[parent_id] = device_set return dev_group
Group devices returned from filter query in order \ by devcice parent id.
https://github.com/rene-aguirre/pywinusb/blob/954c4b2105d9f01cb0c50e24500bb747d4ecdc43/pywinusb/hid/core.py#L168-L182
rene-aguirre/pywinusb
pywinusb/hid/core.py
HidDeviceFilter.get_devices
def get_devices(self, hid_filter = None): """Filter a HID device list by current object parameters. Devices must match the all of the filtering parameters """ if not hid_filter: #empty list or called without any parameters if type(hid_filter) == type(None): #request to query connected devices hid_filter = find_all_hid_devices() else: return hid_filter #initially all accepted results = {}.fromkeys(hid_filter) #the filter parameters validating_attributes = list(self.filter_params.keys()) #first filter out restricted access devices if not len(results): return {} for device in list(results.keys()): if not device.is_active(): del results[device] if not len(results): return {} #filter out for item in validating_attributes: if item.endswith("_includes"): item = item[:-len("_includes")] elif item.endswith("_mask"): item = item[:-len("_mask")] elif item +"_mask" in self.filter_params or item + "_includes" \ in self.filter_params: continue # value mask or string search is being queried elif item not in HidDevice.filter_attributes: continue # field does not exist sys.error.write(...) #start filtering out for device in list(results.keys()): if not hasattr(device, item): del results[device] elif item + "_mask" in validating_attributes: #masked value if getattr(device, item) & self.filter_params[item + \ "_mask"] != self.filter_params[item] \ & self.filter_params[item + "_mask"]: del results[device] elif item + "_includes" in validating_attributes: #subset item if self.filter_params[item + "_includes"] not in \ getattr(device, item): del results[device] else: #plain comparison if getattr(device, item) != self.filter_params[item]: del results[device] # return list(results.keys())
python
def get_devices(self, hid_filter = None): """Filter a HID device list by current object parameters. Devices must match the all of the filtering parameters """ if not hid_filter: #empty list or called without any parameters if type(hid_filter) == type(None): #request to query connected devices hid_filter = find_all_hid_devices() else: return hid_filter #initially all accepted results = {}.fromkeys(hid_filter) #the filter parameters validating_attributes = list(self.filter_params.keys()) #first filter out restricted access devices if not len(results): return {} for device in list(results.keys()): if not device.is_active(): del results[device] if not len(results): return {} #filter out for item in validating_attributes: if item.endswith("_includes"): item = item[:-len("_includes")] elif item.endswith("_mask"): item = item[:-len("_mask")] elif item +"_mask" in self.filter_params or item + "_includes" \ in self.filter_params: continue # value mask or string search is being queried elif item not in HidDevice.filter_attributes: continue # field does not exist sys.error.write(...) #start filtering out for device in list(results.keys()): if not hasattr(device, item): del results[device] elif item + "_mask" in validating_attributes: #masked value if getattr(device, item) & self.filter_params[item + \ "_mask"] != self.filter_params[item] \ & self.filter_params[item + "_mask"]: del results[device] elif item + "_includes" in validating_attributes: #subset item if self.filter_params[item + "_includes"] not in \ getattr(device, item): del results[device] else: #plain comparison if getattr(device, item) != self.filter_params[item]: del results[device] # return list(results.keys())
Filter a HID device list by current object parameters. Devices must match the all of the filtering parameters
https://github.com/rene-aguirre/pywinusb/blob/954c4b2105d9f01cb0c50e24500bb747d4ecdc43/pywinusb/hid/core.py#L184-L242
rene-aguirre/pywinusb
pywinusb/hid/core.py
HidDevice.get_parent_device
def get_parent_device(self): """Retreive parent device string id""" if not self.parent_instance_id: return "" dev_buffer_type = winapi.c_tchar * MAX_DEVICE_ID_LEN dev_buffer = dev_buffer_type() try: if winapi.CM_Get_Device_ID(self.parent_instance_id, byref(dev_buffer), MAX_DEVICE_ID_LEN, 0) == 0: #success return dev_buffer.value return "" finally: del dev_buffer del dev_buffer_type
python
def get_parent_device(self): """Retreive parent device string id""" if not self.parent_instance_id: return "" dev_buffer_type = winapi.c_tchar * MAX_DEVICE_ID_LEN dev_buffer = dev_buffer_type() try: if winapi.CM_Get_Device_ID(self.parent_instance_id, byref(dev_buffer), MAX_DEVICE_ID_LEN, 0) == 0: #success return dev_buffer.value return "" finally: del dev_buffer del dev_buffer_type
Retreive parent device string id
https://github.com/rene-aguirre/pywinusb/blob/954c4b2105d9f01cb0c50e24500bb747d4ecdc43/pywinusb/hid/core.py#L266-L279
rene-aguirre/pywinusb
pywinusb/hid/core.py
HidDevice.open
def open(self, output_only = False, shared = True): """Open HID device and obtain 'Collection Information'. It effectively prepares the HidDevice object for reading and writing """ if self.is_opened(): raise HIDError("Device already opened") sharing_flags = 0 if shared: sharing_flags = winapi.FILE_SHARE_READ | winapi.FILE_SHARE_WRITE hid_handle = winapi.CreateFile( self.device_path, winapi.GENERIC_READ | winapi.GENERIC_WRITE, sharing_flags, None, # no security winapi.OPEN_EXISTING, winapi.FILE_ATTRIBUTE_NORMAL | winapi.FILE_FLAG_OVERLAPPED, 0 ) if not hid_handle or hid_handle == INVALID_HANDLE_VALUE: raise HIDError("Error opening HID device: %s\n"%self.product_name) #get pre parsed data ptr_preparsed_data = ctypes.c_void_p() if not hid_dll.HidD_GetPreparsedData(int(hid_handle), byref(ptr_preparsed_data)): winapi.CloseHandle(int(hid_handle)) raise HIDError("Failure to get HID pre parsed data") self.ptr_preparsed_data = ptr_preparsed_data self.hid_handle = hid_handle #get top level capabilities self.hid_caps = winapi.HIDP_CAPS() HidStatus( hid_dll.HidP_GetCaps(ptr_preparsed_data, byref(self.hid_caps)) ) #proceed with button capabilities caps_length = c_ulong() all_items = [\ (HidP_Input, winapi.HIDP_BUTTON_CAPS, self.hid_caps.number_input_button_caps, hid_dll.HidP_GetButtonCaps ), (HidP_Input, winapi.HIDP_VALUE_CAPS, self.hid_caps.number_input_value_caps, hid_dll.HidP_GetValueCaps ), (HidP_Output, winapi.HIDP_BUTTON_CAPS, self.hid_caps.number_output_button_caps, hid_dll.HidP_GetButtonCaps ), (HidP_Output, winapi.HIDP_VALUE_CAPS, self.hid_caps.number_output_value_caps, hid_dll.HidP_GetValueCaps ), (HidP_Feature, winapi.HIDP_BUTTON_CAPS, self.hid_caps.number_feature_button_caps, hid_dll.HidP_GetButtonCaps ), (HidP_Feature, winapi.HIDP_VALUE_CAPS, self.hid_caps.number_feature_value_caps, hid_dll.HidP_GetValueCaps ), ] for report_kind, struct_kind, max_items, get_control_caps in all_items: if not int(max_items): continue #nothing here #create storage for control/data ctrl_array_type = struct_kind * max_items ctrl_array_struct = ctrl_array_type() #target max size for API function caps_length.value = max_items HidStatus( get_control_caps(\ report_kind, byref(ctrl_array_struct), byref(caps_length), ptr_preparsed_data) ) #keep reference of usages for idx in range(caps_length.value): usage_item = HidPUsageCaps( ctrl_array_struct[idx] ) #by report type if report_kind not in self.usages_storage: self.usages_storage[report_kind] = list() self.usages_storage[report_kind].append( usage_item ) #also add report_id to known reports set if report_kind not in self.report_set: self.report_set[report_kind] = set() self.report_set[report_kind].add( usage_item.report_id ) del ctrl_array_struct del ctrl_array_type # now is the time to consider the device opened, as report # handling threads enforce it self.__open_status = True #now prepare the input report handler self.__input_report_templates = dict() if not output_only and self.hid_caps.input_report_byte_length and \ HidP_Input in self.report_set: #first make templates for easy parsing input reports for report_id in self.report_set[HidP_Input]: self.__input_report_templates[report_id] = \ HidReport( self, HidP_Input, report_id ) #prepare input reports handlers self._input_report_queue = HidDevice.InputReportQueue( \ self.max_input_queue_size, self.hid_caps.input_report_byte_length) self.__input_processing_thread = \ HidDevice.InputReportProcessingThread(self) self.__reading_thread = HidDevice.InputReportReaderThread( \ self, self.hid_caps.input_report_byte_length)
python
def open(self, output_only = False, shared = True): """Open HID device and obtain 'Collection Information'. It effectively prepares the HidDevice object for reading and writing """ if self.is_opened(): raise HIDError("Device already opened") sharing_flags = 0 if shared: sharing_flags = winapi.FILE_SHARE_READ | winapi.FILE_SHARE_WRITE hid_handle = winapi.CreateFile( self.device_path, winapi.GENERIC_READ | winapi.GENERIC_WRITE, sharing_flags, None, # no security winapi.OPEN_EXISTING, winapi.FILE_ATTRIBUTE_NORMAL | winapi.FILE_FLAG_OVERLAPPED, 0 ) if not hid_handle or hid_handle == INVALID_HANDLE_VALUE: raise HIDError("Error opening HID device: %s\n"%self.product_name) #get pre parsed data ptr_preparsed_data = ctypes.c_void_p() if not hid_dll.HidD_GetPreparsedData(int(hid_handle), byref(ptr_preparsed_data)): winapi.CloseHandle(int(hid_handle)) raise HIDError("Failure to get HID pre parsed data") self.ptr_preparsed_data = ptr_preparsed_data self.hid_handle = hid_handle #get top level capabilities self.hid_caps = winapi.HIDP_CAPS() HidStatus( hid_dll.HidP_GetCaps(ptr_preparsed_data, byref(self.hid_caps)) ) #proceed with button capabilities caps_length = c_ulong() all_items = [\ (HidP_Input, winapi.HIDP_BUTTON_CAPS, self.hid_caps.number_input_button_caps, hid_dll.HidP_GetButtonCaps ), (HidP_Input, winapi.HIDP_VALUE_CAPS, self.hid_caps.number_input_value_caps, hid_dll.HidP_GetValueCaps ), (HidP_Output, winapi.HIDP_BUTTON_CAPS, self.hid_caps.number_output_button_caps, hid_dll.HidP_GetButtonCaps ), (HidP_Output, winapi.HIDP_VALUE_CAPS, self.hid_caps.number_output_value_caps, hid_dll.HidP_GetValueCaps ), (HidP_Feature, winapi.HIDP_BUTTON_CAPS, self.hid_caps.number_feature_button_caps, hid_dll.HidP_GetButtonCaps ), (HidP_Feature, winapi.HIDP_VALUE_CAPS, self.hid_caps.number_feature_value_caps, hid_dll.HidP_GetValueCaps ), ] for report_kind, struct_kind, max_items, get_control_caps in all_items: if not int(max_items): continue #nothing here #create storage for control/data ctrl_array_type = struct_kind * max_items ctrl_array_struct = ctrl_array_type() #target max size for API function caps_length.value = max_items HidStatus( get_control_caps(\ report_kind, byref(ctrl_array_struct), byref(caps_length), ptr_preparsed_data) ) #keep reference of usages for idx in range(caps_length.value): usage_item = HidPUsageCaps( ctrl_array_struct[idx] ) #by report type if report_kind not in self.usages_storage: self.usages_storage[report_kind] = list() self.usages_storage[report_kind].append( usage_item ) #also add report_id to known reports set if report_kind not in self.report_set: self.report_set[report_kind] = set() self.report_set[report_kind].add( usage_item.report_id ) del ctrl_array_struct del ctrl_array_type # now is the time to consider the device opened, as report # handling threads enforce it self.__open_status = True #now prepare the input report handler self.__input_report_templates = dict() if not output_only and self.hid_caps.input_report_byte_length and \ HidP_Input in self.report_set: #first make templates for easy parsing input reports for report_id in self.report_set[HidP_Input]: self.__input_report_templates[report_id] = \ HidReport( self, HidP_Input, report_id ) #prepare input reports handlers self._input_report_queue = HidDevice.InputReportQueue( \ self.max_input_queue_size, self.hid_caps.input_report_byte_length) self.__input_processing_thread = \ HidDevice.InputReportProcessingThread(self) self.__reading_thread = HidDevice.InputReportReaderThread( \ self, self.hid_caps.input_report_byte_length)
Open HID device and obtain 'Collection Information'. It effectively prepares the HidDevice object for reading and writing
https://github.com/rene-aguirre/pywinusb/blob/954c4b2105d9f01cb0c50e24500bb747d4ecdc43/pywinusb/hid/core.py#L395-L507
rene-aguirre/pywinusb
pywinusb/hid/core.py
HidDevice.get_physical_descriptor
def get_physical_descriptor(self): """Returns physical HID device descriptor """ raw_data_type = c_ubyte * 1024 raw_data = raw_data_type() if hid_dll.HidD_GetPhysicalDescriptor(self.hid_handle, byref(raw_data), 1024 ): return [x for x in raw_data] return []
python
def get_physical_descriptor(self): """Returns physical HID device descriptor """ raw_data_type = c_ubyte * 1024 raw_data = raw_data_type() if hid_dll.HidD_GetPhysicalDescriptor(self.hid_handle, byref(raw_data), 1024 ): return [x for x in raw_data] return []
Returns physical HID device descriptor
https://github.com/rene-aguirre/pywinusb/blob/954c4b2105d9f01cb0c50e24500bb747d4ecdc43/pywinusb/hid/core.py#L510-L518
rene-aguirre/pywinusb
pywinusb/hid/core.py
HidDevice.send_output_report
def send_output_report(self, data): """Send input/output/feature report ID = report_id, data should be a c_ubyte object with included the required report data """ assert( self.is_opened() ) #make sure we have c_ubyte array storage if not ( isinstance(data, ctypes.Array) and \ issubclass(data._type_, c_ubyte) ): raw_data_type = c_ubyte * len(data) raw_data = raw_data_type() for index in range( len(data) ): raw_data[index] = data[index] else: raw_data = data # # Adding a lock when writing (overlapped writes) over_write = winapi.OVERLAPPED() over_write.h_event = winapi.CreateEvent(None, 0, 0, None) if over_write.h_event: try: overlapped_write = over_write winapi.WriteFile(int(self.hid_handle), byref(raw_data), len(raw_data), None, byref(overlapped_write)) #none overlapped error = ctypes.GetLastError() if error == winapi.ERROR_IO_PENDING: # overlapped operation in progress result = error elif error == 1167: raise HIDError("Error device disconnected before write") else: raise HIDError("Error %d when trying to write to HID "\ "device: %s"%(error, ctypes.FormatError(error)) ) result = winapi.WaitForSingleObject(overlapped_write.h_event, 10000 ) if result != winapi.WAIT_OBJECT_0: # If the write times out make sure to # cancel it, otherwise memory could # get corrupted if the async write # completes after this functions returns winapi.CancelIo( int(self.hid_handle) ) raise HIDError("Write timed out") finally: # Make sure the event is closed so resources aren't leaked winapi.CloseHandle(over_write.h_event) else: return winapi.WriteFile(int(self.hid_handle), byref(raw_data), len(raw_data), None, None) #none overlapped return True
python
def send_output_report(self, data): """Send input/output/feature report ID = report_id, data should be a c_ubyte object with included the required report data """ assert( self.is_opened() ) #make sure we have c_ubyte array storage if not ( isinstance(data, ctypes.Array) and \ issubclass(data._type_, c_ubyte) ): raw_data_type = c_ubyte * len(data) raw_data = raw_data_type() for index in range( len(data) ): raw_data[index] = data[index] else: raw_data = data # # Adding a lock when writing (overlapped writes) over_write = winapi.OVERLAPPED() over_write.h_event = winapi.CreateEvent(None, 0, 0, None) if over_write.h_event: try: overlapped_write = over_write winapi.WriteFile(int(self.hid_handle), byref(raw_data), len(raw_data), None, byref(overlapped_write)) #none overlapped error = ctypes.GetLastError() if error == winapi.ERROR_IO_PENDING: # overlapped operation in progress result = error elif error == 1167: raise HIDError("Error device disconnected before write") else: raise HIDError("Error %d when trying to write to HID "\ "device: %s"%(error, ctypes.FormatError(error)) ) result = winapi.WaitForSingleObject(overlapped_write.h_event, 10000 ) if result != winapi.WAIT_OBJECT_0: # If the write times out make sure to # cancel it, otherwise memory could # get corrupted if the async write # completes after this functions returns winapi.CancelIo( int(self.hid_handle) ) raise HIDError("Write timed out") finally: # Make sure the event is closed so resources aren't leaked winapi.CloseHandle(over_write.h_event) else: return winapi.WriteFile(int(self.hid_handle), byref(raw_data), len(raw_data), None, None) #none overlapped return True
Send input/output/feature report ID = report_id, data should be a c_ubyte object with included the required report data
https://github.com/rene-aguirre/pywinusb/blob/954c4b2105d9f01cb0c50e24500bb747d4ecdc43/pywinusb/hid/core.py#L520-L567
rene-aguirre/pywinusb
pywinusb/hid/core.py
HidDevice.send_feature_report
def send_feature_report(self, data): """Send input/output/feature report ID = report_id, data should be a c_byte object with included the required report data """ assert( self.is_opened() ) #make sure we have c_ubyte array storage if not ( isinstance(data, ctypes.Array) and issubclass(data._type_, c_ubyte) ): raw_data_type = c_ubyte * len(data) raw_data = raw_data_type() for index in range( len(data) ): raw_data[index] = data[index] else: raw_data = data return hid_dll.HidD_SetFeature(int(self.hid_handle), byref(raw_data), len(raw_data))
python
def send_feature_report(self, data): """Send input/output/feature report ID = report_id, data should be a c_byte object with included the required report data """ assert( self.is_opened() ) #make sure we have c_ubyte array storage if not ( isinstance(data, ctypes.Array) and issubclass(data._type_, c_ubyte) ): raw_data_type = c_ubyte * len(data) raw_data = raw_data_type() for index in range( len(data) ): raw_data[index] = data[index] else: raw_data = data return hid_dll.HidD_SetFeature(int(self.hid_handle), byref(raw_data), len(raw_data))
Send input/output/feature report ID = report_id, data should be a c_byte object with included the required report data
https://github.com/rene-aguirre/pywinusb/blob/954c4b2105d9f01cb0c50e24500bb747d4ecdc43/pywinusb/hid/core.py#L569-L585
rene-aguirre/pywinusb
pywinusb/hid/core.py
HidDevice.__reset_vars
def __reset_vars(self): """Reset vars (for init or gc)""" self.__button_caps_storage = list() self.usages_storage = dict() self.report_set = dict() self.ptr_preparsed_data = None self.hid_handle = None #don't clean up the report queue because the #consumer & producer threads might needed it self.__evt_handlers = dict() #other self.__reading_thread = None self.__input_processing_thread = None self._input_report_queue = None
python
def __reset_vars(self): """Reset vars (for init or gc)""" self.__button_caps_storage = list() self.usages_storage = dict() self.report_set = dict() self.ptr_preparsed_data = None self.hid_handle = None #don't clean up the report queue because the #consumer & producer threads might needed it self.__evt_handlers = dict() #other self.__reading_thread = None self.__input_processing_thread = None self._input_report_queue = None
Reset vars (for init or gc)
https://github.com/rene-aguirre/pywinusb/blob/954c4b2105d9f01cb0c50e24500bb747d4ecdc43/pywinusb/hid/core.py#L587-L601
rene-aguirre/pywinusb
pywinusb/hid/core.py
HidDevice.close
def close(self): """Release system resources""" # free parsed data if not self.is_opened(): return self.__open_status = False # abort all running threads first if self.__reading_thread and self.__reading_thread.is_alive(): self.__reading_thread.abort() #avoid posting new reports if self._input_report_queue: self._input_report_queue.release_events() if self.__input_processing_thread and \ self.__input_processing_thread.is_alive(): self.__input_processing_thread.abort() #properly close API handlers and pointers if self.ptr_preparsed_data: ptr_preparsed_data = self.ptr_preparsed_data self.ptr_preparsed_data = None hid_dll.HidD_FreePreparsedData(ptr_preparsed_data) # wait for the reading thread to complete before closing device handle if self.__reading_thread: self.__reading_thread.join() if self.hid_handle: winapi.CloseHandle(self.hid_handle) # make sure report procesing thread is closed if self.__input_processing_thread: self.__input_processing_thread.join() #reset vars (for GC) button_caps_storage = self.__button_caps_storage self.__reset_vars() while button_caps_storage: item = button_caps_storage.pop() del item
python
def close(self): """Release system resources""" # free parsed data if not self.is_opened(): return self.__open_status = False # abort all running threads first if self.__reading_thread and self.__reading_thread.is_alive(): self.__reading_thread.abort() #avoid posting new reports if self._input_report_queue: self._input_report_queue.release_events() if self.__input_processing_thread and \ self.__input_processing_thread.is_alive(): self.__input_processing_thread.abort() #properly close API handlers and pointers if self.ptr_preparsed_data: ptr_preparsed_data = self.ptr_preparsed_data self.ptr_preparsed_data = None hid_dll.HidD_FreePreparsedData(ptr_preparsed_data) # wait for the reading thread to complete before closing device handle if self.__reading_thread: self.__reading_thread.join() if self.hid_handle: winapi.CloseHandle(self.hid_handle) # make sure report procesing thread is closed if self.__input_processing_thread: self.__input_processing_thread.join() #reset vars (for GC) button_caps_storage = self.__button_caps_storage self.__reset_vars() while button_caps_storage: item = button_caps_storage.pop() del item
Release system resources
https://github.com/rene-aguirre/pywinusb/blob/954c4b2105d9f01cb0c50e24500bb747d4ecdc43/pywinusb/hid/core.py#L612-L654
rene-aguirre/pywinusb
pywinusb/hid/core.py
HidDevice.__find_reports
def __find_reports(self, report_type, usage_page, usage_id = 0): "Find input report referencing HID usage control/data item" if not self.is_opened(): raise HIDError("Device must be opened") # results = list() if usage_page: for report_id in self.report_set.get( report_type, set() ): #build report object, gathering usages matching report_id report_obj = HidReport(self, report_type, report_id) if get_full_usage_id(usage_page, usage_id) in report_obj: results.append( report_obj ) else: #all (any one) for report_id in self.report_set.get(report_type, set()): report_obj = HidReport(self, report_type, report_id) results.append( report_obj ) return results
python
def __find_reports(self, report_type, usage_page, usage_id = 0): "Find input report referencing HID usage control/data item" if not self.is_opened(): raise HIDError("Device must be opened") # results = list() if usage_page: for report_id in self.report_set.get( report_type, set() ): #build report object, gathering usages matching report_id report_obj = HidReport(self, report_type, report_id) if get_full_usage_id(usage_page, usage_id) in report_obj: results.append( report_obj ) else: #all (any one) for report_id in self.report_set.get(report_type, set()): report_obj = HidReport(self, report_type, report_id) results.append( report_obj ) return results
Find input report referencing HID usage control/data item
https://github.com/rene-aguirre/pywinusb/blob/954c4b2105d9f01cb0c50e24500bb747d4ecdc43/pywinusb/hid/core.py#L656-L673
rene-aguirre/pywinusb
pywinusb/hid/core.py
HidDevice.find_any_reports
def find_any_reports(self, usage_page = 0, usage_id = 0): """Find any report type referencing HID usage control/data item. Results are returned in a dictionary mapping report_type to usage lists. """ items = [ (HidP_Input, self.find_input_reports(usage_page, usage_id)), (HidP_Output, self.find_output_reports(usage_page, usage_id)), (HidP_Feature, self.find_feature_reports(usage_page, usage_id)), ] return dict([(t, r) for t, r in items if r])
python
def find_any_reports(self, usage_page = 0, usage_id = 0): """Find any report type referencing HID usage control/data item. Results are returned in a dictionary mapping report_type to usage lists. """ items = [ (HidP_Input, self.find_input_reports(usage_page, usage_id)), (HidP_Output, self.find_output_reports(usage_page, usage_id)), (HidP_Feature, self.find_feature_reports(usage_page, usage_id)), ] return dict([(t, r) for t, r in items if r])
Find any report type referencing HID usage control/data item. Results are returned in a dictionary mapping report_type to usage lists.
https://github.com/rene-aguirre/pywinusb/blob/954c4b2105d9f01cb0c50e24500bb747d4ecdc43/pywinusb/hid/core.py#L692-L702
rene-aguirre/pywinusb
pywinusb/hid/core.py
HidDevice._process_raw_report
def _process_raw_report(self, raw_report): "Default raw input report data handler" if not self.is_opened(): return if not self.__evt_handlers and not self.__raw_handler: return if not raw_report[0] and \ (raw_report[0] not in self.__input_report_templates): # windows sends an empty array when disconnecting # but, this might have a collision with report_id = 0 if not hid_device_path_exists(self.device_path): #windows XP sends empty report when disconnecting self.__reading_thread.abort() #device disconnected return if self.__raw_handler: #this might slow down data throughput, but at the expense of safety self.__raw_handler(helpers.ReadOnlyList(raw_report)) return # using pre-parsed report templates, by report id report_template = self.__input_report_templates[raw_report[0]] # old condition snapshot old_values = report_template.get_usages() # parse incoming data report_template.set_raw_data(raw_report) # and compare it event_applies = self.evt_decision evt_handlers = self.__evt_handlers for key in report_template.keys(): if key not in evt_handlers: continue #check if event handler exist! for event_kind, handlers in evt_handlers[key].items(): #key=event_kind, values=handler set new_value = report_template[key].value if not event_applies[event_kind](old_values[key], new_value): continue #decision applies, call handlers for function_handler in handlers: #check if the application wants some particular parameter if handlers[function_handler]: function_handler(new_value, event_kind, handlers[function_handler]) else: function_handler(new_value, event_kind)
python
def _process_raw_report(self, raw_report): "Default raw input report data handler" if not self.is_opened(): return if not self.__evt_handlers and not self.__raw_handler: return if not raw_report[0] and \ (raw_report[0] not in self.__input_report_templates): # windows sends an empty array when disconnecting # but, this might have a collision with report_id = 0 if not hid_device_path_exists(self.device_path): #windows XP sends empty report when disconnecting self.__reading_thread.abort() #device disconnected return if self.__raw_handler: #this might slow down data throughput, but at the expense of safety self.__raw_handler(helpers.ReadOnlyList(raw_report)) return # using pre-parsed report templates, by report id report_template = self.__input_report_templates[raw_report[0]] # old condition snapshot old_values = report_template.get_usages() # parse incoming data report_template.set_raw_data(raw_report) # and compare it event_applies = self.evt_decision evt_handlers = self.__evt_handlers for key in report_template.keys(): if key not in evt_handlers: continue #check if event handler exist! for event_kind, handlers in evt_handlers[key].items(): #key=event_kind, values=handler set new_value = report_template[key].value if not event_applies[event_kind](old_values[key], new_value): continue #decision applies, call handlers for function_handler in handlers: #check if the application wants some particular parameter if handlers[function_handler]: function_handler(new_value, event_kind, handlers[function_handler]) else: function_handler(new_value, event_kind)
Default raw input report data handler
https://github.com/rene-aguirre/pywinusb/blob/954c4b2105d9f01cb0c50e24500bb747d4ecdc43/pywinusb/hid/core.py#L717-L763
rene-aguirre/pywinusb
pywinusb/hid/core.py
HidDevice.find_input_usage
def find_input_usage(self, full_usage_id): """Check if full usage Id included in input reports set Parameters: full_usage_id Full target usage, use get_full_usage_id Returns: Report ID as integer value, or None if report does not exist with target usage. Nottice that report ID 0 is a valid report. """ for report_id, report_obj in self.__input_report_templates.items(): if full_usage_id in report_obj: return report_id return None
python
def find_input_usage(self, full_usage_id): """Check if full usage Id included in input reports set Parameters: full_usage_id Full target usage, use get_full_usage_id Returns: Report ID as integer value, or None if report does not exist with target usage. Nottice that report ID 0 is a valid report. """ for report_id, report_obj in self.__input_report_templates.items(): if full_usage_id in report_obj: return report_id return None
Check if full usage Id included in input reports set Parameters: full_usage_id Full target usage, use get_full_usage_id Returns: Report ID as integer value, or None if report does not exist with target usage. Nottice that report ID 0 is a valid report.
https://github.com/rene-aguirre/pywinusb/blob/954c4b2105d9f01cb0c50e24500bb747d4ecdc43/pywinusb/hid/core.py#L769-L781
rene-aguirre/pywinusb
pywinusb/hid/core.py
HidDevice.add_event_handler
def add_event_handler(self, full_usage_id, handler_function, event_kind = HID_EVT_ALL, aux_data = None): """Add event handler for usage value/button changes, returns True if the handler function was updated""" report_id = self.find_input_usage(full_usage_id) if report_id != None: # allow first zero to trigger changes and releases events self.__input_report_templates[report_id][full_usage_id].__value = None if report_id == None or not handler_function: # do not add handler return False assert(isinstance(handler_function, collections.Callable)) # must be a function # get dictionary for full usages top_map_handler = self.__evt_handlers.get(full_usage_id, dict()) event_handler_set = top_map_handler.get(event_kind, dict()) # update handler event_handler_set[handler_function] = aux_data if event_kind not in top_map_handler: top_map_handler[event_kind] = event_handler_set if full_usage_id not in self.__evt_handlers: self.__evt_handlers[full_usage_id] = top_map_handler return True
python
def add_event_handler(self, full_usage_id, handler_function, event_kind = HID_EVT_ALL, aux_data = None): """Add event handler for usage value/button changes, returns True if the handler function was updated""" report_id = self.find_input_usage(full_usage_id) if report_id != None: # allow first zero to trigger changes and releases events self.__input_report_templates[report_id][full_usage_id].__value = None if report_id == None or not handler_function: # do not add handler return False assert(isinstance(handler_function, collections.Callable)) # must be a function # get dictionary for full usages top_map_handler = self.__evt_handlers.get(full_usage_id, dict()) event_handler_set = top_map_handler.get(event_kind, dict()) # update handler event_handler_set[handler_function] = aux_data if event_kind not in top_map_handler: top_map_handler[event_kind] = event_handler_set if full_usage_id not in self.__evt_handlers: self.__evt_handlers[full_usage_id] = top_map_handler return True
Add event handler for usage value/button changes, returns True if the handler function was updated
https://github.com/rene-aguirre/pywinusb/blob/954c4b2105d9f01cb0c50e24500bb747d4ecdc43/pywinusb/hid/core.py#L783-L804
rene-aguirre/pywinusb
pywinusb/hid/core.py
ReportItem.set_value
def set_value(self, value): """Set usage value within report""" if self.__is_value_array: if len(value) == self.__report_count: for index, item in enumerate(value): self.__setitem__(index, item) else: raise ValueError("Value size should match report item size "\ "length" ) else: self.__value = value & ((1 << self.__bit_size) - 1)
python
def set_value(self, value): """Set usage value within report""" if self.__is_value_array: if len(value) == self.__report_count: for index, item in enumerate(value): self.__setitem__(index, item) else: raise ValueError("Value size should match report item size "\ "length" ) else: self.__value = value & ((1 << self.__bit_size) - 1)
Set usage value within report
https://github.com/rene-aguirre/pywinusb/blob/954c4b2105d9f01cb0c50e24500bb747d4ecdc43/pywinusb/hid/core.py#L1094-L1104
rene-aguirre/pywinusb
pywinusb/hid/core.py
ReportItem.get_value
def get_value(self): """Retreive usage value within report""" if self.__is_value_array: if self.__bit_size == 8: #matching c_ubyte return list(self.__value) else: result = [] for i in range(self.__report_count): result.append(self.__getitem__(i)) return result else: return self.__value
python
def get_value(self): """Retreive usage value within report""" if self.__is_value_array: if self.__bit_size == 8: #matching c_ubyte return list(self.__value) else: result = [] for i in range(self.__report_count): result.append(self.__getitem__(i)) return result else: return self.__value
Retreive usage value within report
https://github.com/rene-aguirre/pywinusb/blob/954c4b2105d9f01cb0c50e24500bb747d4ecdc43/pywinusb/hid/core.py#L1106-L1117
rene-aguirre/pywinusb
pywinusb/hid/core.py
ReportItem.get_usage_string
def get_usage_string(self): """Returns usage representation string (as embedded in HID device if available) """ if self.string_index: usage_string_type = c_wchar * MAX_HID_STRING_LENGTH # 128 max string length abuffer = usage_string_type() hid_dll.HidD_GetIndexedString( self.hid_report.get_hid_object().hid_handle, self.string_index, byref(abuffer), MAX_HID_STRING_LENGTH-1 ) return abuffer.value return ""
python
def get_usage_string(self): """Returns usage representation string (as embedded in HID device if available) """ if self.string_index: usage_string_type = c_wchar * MAX_HID_STRING_LENGTH # 128 max string length abuffer = usage_string_type() hid_dll.HidD_GetIndexedString( self.hid_report.get_hid_object().hid_handle, self.string_index, byref(abuffer), MAX_HID_STRING_LENGTH-1 ) return abuffer.value return ""
Returns usage representation string (as embedded in HID device if available)
https://github.com/rene-aguirre/pywinusb/blob/954c4b2105d9f01cb0c50e24500bb747d4ecdc43/pywinusb/hid/core.py#L1143-L1156
rene-aguirre/pywinusb
pywinusb/hid/core.py
HidReport.get_usages
def get_usages(self): "Return a dictionary mapping full usages Ids to plain values" result = dict() for key, usage in self.items(): result[key] = usage.value return result
python
def get_usages(self): "Return a dictionary mapping full usages Ids to plain values" result = dict() for key, usage in self.items(): result[key] = usage.value return result
Return a dictionary mapping full usages Ids to plain values
https://github.com/rene-aguirre/pywinusb/blob/954c4b2105d9f01cb0c50e24500bb747d4ecdc43/pywinusb/hid/core.py#L1295-L1300
rene-aguirre/pywinusb
pywinusb/hid/core.py
HidReport.__alloc_raw_data
def __alloc_raw_data(self, initial_values=None): """Pre-allocate re-usagle memory""" #allocate c_ubyte storage if self.__raw_data == None: #first time only, create storage raw_data_type = c_ubyte * self.__raw_report_size self.__raw_data = raw_data_type() elif initial_values == self.__raw_data: # already return else: #initialize ctypes.memset(self.__raw_data, 0, len(self.__raw_data)) if initial_values: for index in range(len(initial_values)): self.__raw_data[index] = initial_values[index]
python
def __alloc_raw_data(self, initial_values=None): """Pre-allocate re-usagle memory""" #allocate c_ubyte storage if self.__raw_data == None: #first time only, create storage raw_data_type = c_ubyte * self.__raw_report_size self.__raw_data = raw_data_type() elif initial_values == self.__raw_data: # already return else: #initialize ctypes.memset(self.__raw_data, 0, len(self.__raw_data)) if initial_values: for index in range(len(initial_values)): self.__raw_data[index] = initial_values[index]
Pre-allocate re-usagle memory
https://github.com/rene-aguirre/pywinusb/blob/954c4b2105d9f01cb0c50e24500bb747d4ecdc43/pywinusb/hid/core.py#L1302-L1316
rene-aguirre/pywinusb
pywinusb/hid/core.py
HidReport.set_raw_data
def set_raw_data(self, raw_data): """Set usage values based on given raw data, item[0] is report_id, length should match 'raw_data_length' value, best performance if raw_data is c_ubyte ctypes array object type """ #pre-parsed data should exist assert(self.__hid_object.is_opened()) #valid length if len(raw_data) != self.__raw_report_size: raise HIDError( "Report size has to be %d elements (bytes)" \ % self.__raw_report_size ) # copy to internal storage self.__alloc_raw_data(raw_data) if not self.__usage_data_list: # create HIDP_DATA buffer max_items = hid_dll.HidP_MaxDataListLength(self.__report_kind, self.__hid_object.ptr_preparsed_data) data_list_type = winapi.HIDP_DATA * max_items self.__usage_data_list = data_list_type() #reference HIDP_DATA buffer data_list = self.__usage_data_list data_len = c_ulong(len(data_list)) #reset old values for item in self.values(): if item.is_value_array(): item.value = [0, ]*len(item) else: item.value = 0 #ready, parse raw data HidStatus( hid_dll.HidP_GetData(self.__report_kind, byref(data_list), byref(data_len), self.__hid_object.ptr_preparsed_data, byref(self.__raw_data), len(self.__raw_data)) ) #set values on internal report item objects for idx in range(data_len.value): value_item = data_list[idx] report_item = self.__idx_items.get(value_item.data_index) if not report_item: # This is not expected to happen continue if report_item.is_value(): report_item.value = value_item.value.raw_value elif report_item.is_button(): report_item.value = value_item.value.on else: pass # HID API should give us either, at least one of 'em #get values of array items for item in self.__value_array_items: #ask hid API to parse HidStatus( hid_dll.HidP_GetUsageValueArray(self.__report_kind, item.page_id, 0, #link collection item.usage_id, #short usage byref(item.value_array), #output data (c_ubyte storage) len(item.value_array), self.__hid_object.ptr_preparsed_data, byref(self.__raw_data), len(self.__raw_data)) )
python
def set_raw_data(self, raw_data): """Set usage values based on given raw data, item[0] is report_id, length should match 'raw_data_length' value, best performance if raw_data is c_ubyte ctypes array object type """ #pre-parsed data should exist assert(self.__hid_object.is_opened()) #valid length if len(raw_data) != self.__raw_report_size: raise HIDError( "Report size has to be %d elements (bytes)" \ % self.__raw_report_size ) # copy to internal storage self.__alloc_raw_data(raw_data) if not self.__usage_data_list: # create HIDP_DATA buffer max_items = hid_dll.HidP_MaxDataListLength(self.__report_kind, self.__hid_object.ptr_preparsed_data) data_list_type = winapi.HIDP_DATA * max_items self.__usage_data_list = data_list_type() #reference HIDP_DATA buffer data_list = self.__usage_data_list data_len = c_ulong(len(data_list)) #reset old values for item in self.values(): if item.is_value_array(): item.value = [0, ]*len(item) else: item.value = 0 #ready, parse raw data HidStatus( hid_dll.HidP_GetData(self.__report_kind, byref(data_list), byref(data_len), self.__hid_object.ptr_preparsed_data, byref(self.__raw_data), len(self.__raw_data)) ) #set values on internal report item objects for idx in range(data_len.value): value_item = data_list[idx] report_item = self.__idx_items.get(value_item.data_index) if not report_item: # This is not expected to happen continue if report_item.is_value(): report_item.value = value_item.value.raw_value elif report_item.is_button(): report_item.value = value_item.value.on else: pass # HID API should give us either, at least one of 'em #get values of array items for item in self.__value_array_items: #ask hid API to parse HidStatus( hid_dll.HidP_GetUsageValueArray(self.__report_kind, item.page_id, 0, #link collection item.usage_id, #short usage byref(item.value_array), #output data (c_ubyte storage) len(item.value_array), self.__hid_object.ptr_preparsed_data, byref(self.__raw_data), len(self.__raw_data)) )
Set usage values based on given raw data, item[0] is report_id, length should match 'raw_data_length' value, best performance if raw_data is c_ubyte ctypes array object type
https://github.com/rene-aguirre/pywinusb/blob/954c4b2105d9f01cb0c50e24500bb747d4ecdc43/pywinusb/hid/core.py#L1318-L1375
rene-aguirre/pywinusb
pywinusb/hid/core.py
HidReport.__prepare_raw_data
def __prepare_raw_data(self): "Format internal __raw_data storage according to usages setting" #pre-parsed data should exist if not self.__hid_object.ptr_preparsed_data: raise HIDError("HID object close or unable to request pre parsed "\ "report data") # make sure pre-memory allocation already done self.__alloc_raw_data() try: HidStatus( hid_dll.HidP_InitializeReportForID(self.__report_kind, self.__report_id, self.__hid_object.ptr_preparsed_data, byref(self.__raw_data), self.__raw_report_size) ) # except HIDError: self.__raw_data[0] = self.__report_id #check if we have pre-allocated usage storage if not self.__usage_data_list: # create HIDP_DATA buffer max_items = hid_dll.HidP_MaxDataListLength(self.__report_kind, self.__hid_object.ptr_preparsed_data) if not max_items: raise HIDError("Internal error while requesting usage length") data_list_type = winapi.HIDP_DATA * max_items self.__usage_data_list = data_list_type() #reference HIDP_DATA buffer data_list = self.__usage_data_list #set buttons and values usages first n_total_usages = 0 single_usage = USAGE() single_usage_len = c_ulong() for data_index, report_item in self.__idx_items.items(): if (not report_item.is_value_array()) and \ report_item.value != None: #set by user, include in request if report_item.is_button() and report_item.value: # windows just can't handle button arrays!, we just don't # know if usage is button array or plain single usage, so # we set all usages at once single_usage.value = report_item.usage_id single_usage_len.value = 1 HidStatus( hid_dll.HidP_SetUsages(self.__report_kind, report_item.page_id, 0, byref(single_usage), byref(single_usage_len), self.__hid_object.ptr_preparsed_data, byref(self.__raw_data), self.__raw_report_size) ) continue elif report_item.is_value() and \ not report_item.is_value_array(): data_list[n_total_usages].value.raw_value = report_item.value else: continue #do nothing data_list[n_total_usages].reserved = 0 #reset data_list[n_total_usages].data_index = data_index #reference n_total_usages += 1 #set data if any usage is not 'none' (and not any value array) if n_total_usages: #some usages set usage_len = c_ulong(n_total_usages) HidStatus( hid_dll.HidP_SetData(self.__report_kind, byref(data_list), byref(usage_len), self.__hid_object.ptr_preparsed_data, byref(self.__raw_data), self.__raw_report_size) ) #set values based on value arrays for report_item in self.__value_array_items: HidStatus( hid_dll.HidP_SetUsageValueArray(self.__report_kind, report_item.page_id, 0, #all link collections report_item.usage_id, byref(report_item.value_array), len(report_item.value_array), self.__hid_object.ptr_preparsed_data, byref(self.__raw_data), len(self.__raw_data)) )
python
def __prepare_raw_data(self): "Format internal __raw_data storage according to usages setting" #pre-parsed data should exist if not self.__hid_object.ptr_preparsed_data: raise HIDError("HID object close or unable to request pre parsed "\ "report data") # make sure pre-memory allocation already done self.__alloc_raw_data() try: HidStatus( hid_dll.HidP_InitializeReportForID(self.__report_kind, self.__report_id, self.__hid_object.ptr_preparsed_data, byref(self.__raw_data), self.__raw_report_size) ) # except HIDError: self.__raw_data[0] = self.__report_id #check if we have pre-allocated usage storage if not self.__usage_data_list: # create HIDP_DATA buffer max_items = hid_dll.HidP_MaxDataListLength(self.__report_kind, self.__hid_object.ptr_preparsed_data) if not max_items: raise HIDError("Internal error while requesting usage length") data_list_type = winapi.HIDP_DATA * max_items self.__usage_data_list = data_list_type() #reference HIDP_DATA buffer data_list = self.__usage_data_list #set buttons and values usages first n_total_usages = 0 single_usage = USAGE() single_usage_len = c_ulong() for data_index, report_item in self.__idx_items.items(): if (not report_item.is_value_array()) and \ report_item.value != None: #set by user, include in request if report_item.is_button() and report_item.value: # windows just can't handle button arrays!, we just don't # know if usage is button array or plain single usage, so # we set all usages at once single_usage.value = report_item.usage_id single_usage_len.value = 1 HidStatus( hid_dll.HidP_SetUsages(self.__report_kind, report_item.page_id, 0, byref(single_usage), byref(single_usage_len), self.__hid_object.ptr_preparsed_data, byref(self.__raw_data), self.__raw_report_size) ) continue elif report_item.is_value() and \ not report_item.is_value_array(): data_list[n_total_usages].value.raw_value = report_item.value else: continue #do nothing data_list[n_total_usages].reserved = 0 #reset data_list[n_total_usages].data_index = data_index #reference n_total_usages += 1 #set data if any usage is not 'none' (and not any value array) if n_total_usages: #some usages set usage_len = c_ulong(n_total_usages) HidStatus( hid_dll.HidP_SetData(self.__report_kind, byref(data_list), byref(usage_len), self.__hid_object.ptr_preparsed_data, byref(self.__raw_data), self.__raw_report_size) ) #set values based on value arrays for report_item in self.__value_array_items: HidStatus( hid_dll.HidP_SetUsageValueArray(self.__report_kind, report_item.page_id, 0, #all link collections report_item.usage_id, byref(report_item.value_array), len(report_item.value_array), self.__hid_object.ptr_preparsed_data, byref(self.__raw_data), len(self.__raw_data)) )
Format internal __raw_data storage according to usages setting
https://github.com/rene-aguirre/pywinusb/blob/954c4b2105d9f01cb0c50e24500bb747d4ecdc43/pywinusb/hid/core.py#L1378-L1452
rene-aguirre/pywinusb
pywinusb/hid/core.py
HidReport.get_raw_data
def get_raw_data(self): """Get raw HID report based on internal report item settings, creates new c_ubytes storage """ if self.__report_kind != HidP_Output \ and self.__report_kind != HidP_Feature: raise HIDError("Only for output or feature reports") self.__prepare_raw_data() #return read-only object for internal storage return helpers.ReadOnlyList(self.__raw_data)
python
def get_raw_data(self): """Get raw HID report based on internal report item settings, creates new c_ubytes storage """ if self.__report_kind != HidP_Output \ and self.__report_kind != HidP_Feature: raise HIDError("Only for output or feature reports") self.__prepare_raw_data() #return read-only object for internal storage return helpers.ReadOnlyList(self.__raw_data)
Get raw HID report based on internal report item settings, creates new c_ubytes storage
https://github.com/rene-aguirre/pywinusb/blob/954c4b2105d9f01cb0c50e24500bb747d4ecdc43/pywinusb/hid/core.py#L1454-L1463
rene-aguirre/pywinusb
pywinusb/hid/core.py
HidReport.send
def send(self, raw_data = None): """Prepare HID raw report (unless raw_data is provided) and send it to HID device """ if self.__report_kind != HidP_Output \ and self.__report_kind != HidP_Feature: raise HIDError("Only for output or feature reports") #valid length if raw_data and (len(raw_data) != self.__raw_report_size): raise HIDError("Report size has to be %d elements (bytes)" \ % self.__raw_report_size) #should be valid report id if raw_data and raw_data[0] != self.__report_id.value: #hint, raw_data should be a plain list of integer values raise HIDError("Not matching report id") # if self.__report_kind != HidP_Output and \ self.__report_kind != HidP_Feature: raise HIDError("Can only send output or feature reports") # if not raw_data: # we'll construct the raw report self.__prepare_raw_data() elif not ( isinstance(raw_data, ctypes.Array) and \ issubclass(raw_data._type_, c_ubyte) ): # pre-memory allocation for performance self.__alloc_raw_data(raw_data) #reference proper object raw_data = self.__raw_data if self.__report_kind == HidP_Output: return self.__hid_object.send_output_report(raw_data) elif self.__report_kind == HidP_Feature: return self.__hid_object.send_feature_report(raw_data) else: pass
python
def send(self, raw_data = None): """Prepare HID raw report (unless raw_data is provided) and send it to HID device """ if self.__report_kind != HidP_Output \ and self.__report_kind != HidP_Feature: raise HIDError("Only for output or feature reports") #valid length if raw_data and (len(raw_data) != self.__raw_report_size): raise HIDError("Report size has to be %d elements (bytes)" \ % self.__raw_report_size) #should be valid report id if raw_data and raw_data[0] != self.__report_id.value: #hint, raw_data should be a plain list of integer values raise HIDError("Not matching report id") # if self.__report_kind != HidP_Output and \ self.__report_kind != HidP_Feature: raise HIDError("Can only send output or feature reports") # if not raw_data: # we'll construct the raw report self.__prepare_raw_data() elif not ( isinstance(raw_data, ctypes.Array) and \ issubclass(raw_data._type_, c_ubyte) ): # pre-memory allocation for performance self.__alloc_raw_data(raw_data) #reference proper object raw_data = self.__raw_data if self.__report_kind == HidP_Output: return self.__hid_object.send_output_report(raw_data) elif self.__report_kind == HidP_Feature: return self.__hid_object.send_feature_report(raw_data) else: pass
Prepare HID raw report (unless raw_data is provided) and send it to HID device
https://github.com/rene-aguirre/pywinusb/blob/954c4b2105d9f01cb0c50e24500bb747d4ecdc43/pywinusb/hid/core.py#L1465-L1499
rene-aguirre/pywinusb
pywinusb/hid/core.py
HidReport.get
def get(self, do_process_raw_report = True): "Read report from device" assert(self.__hid_object.is_opened()) if self.__report_kind != HidP_Input and \ self.__report_kind != HidP_Feature: raise HIDError("Only for input or feature reports") # pre-alloc raw data self.__alloc_raw_data() # now use it raw_data = self.__raw_data raw_data[0] = self.__report_id read_function = None if self.__report_kind == HidP_Feature: read_function = hid_dll.HidD_GetFeature elif self.__report_kind == HidP_Input: read_function = hid_dll.HidD_GetInputReport if read_function and read_function(int(self.__hid_object.hid_handle), byref(raw_data), len(raw_data)): #success if do_process_raw_report: self.set_raw_data(raw_data) self.__hid_object._process_raw_report(raw_data) return helpers.ReadOnlyList(raw_data) return helpers.ReadOnlyList([])
python
def get(self, do_process_raw_report = True): "Read report from device" assert(self.__hid_object.is_opened()) if self.__report_kind != HidP_Input and \ self.__report_kind != HidP_Feature: raise HIDError("Only for input or feature reports") # pre-alloc raw data self.__alloc_raw_data() # now use it raw_data = self.__raw_data raw_data[0] = self.__report_id read_function = None if self.__report_kind == HidP_Feature: read_function = hid_dll.HidD_GetFeature elif self.__report_kind == HidP_Input: read_function = hid_dll.HidD_GetInputReport if read_function and read_function(int(self.__hid_object.hid_handle), byref(raw_data), len(raw_data)): #success if do_process_raw_report: self.set_raw_data(raw_data) self.__hid_object._process_raw_report(raw_data) return helpers.ReadOnlyList(raw_data) return helpers.ReadOnlyList([])
Read report from device
https://github.com/rene-aguirre/pywinusb/blob/954c4b2105d9f01cb0c50e24500bb747d4ecdc43/pywinusb/hid/core.py#L1501-L1525
rene-aguirre/pywinusb
pywinusb/hid/core.py
HidPUsageCaps.inspect
def inspect(self): """Retreive dictionary of 'Field: Value' attributes""" results = {} for fname in dir(self): if not fname.startswith('_'): value = getattr(self, fname) if isinstance(value, collections.Callable): continue results[fname] = value return results
python
def inspect(self): """Retreive dictionary of 'Field: Value' attributes""" results = {} for fname in dir(self): if not fname.startswith('_'): value = getattr(self, fname) if isinstance(value, collections.Callable): continue results[fname] = value return results
Retreive dictionary of 'Field: Value' attributes
https://github.com/rene-aguirre/pywinusb/blob/954c4b2105d9f01cb0c50e24500bb747d4ecdc43/pywinusb/hid/core.py#L1560-L1569
rene-aguirre/pywinusb
examples/raw_set.py
set_mute
def set_mute(mute_value): "Browse for mute usages and set value" all_mutes = ( \ (0x8, 0x9), # LED page (0x1, 0xA7), # desktop page (0xb, 0x2f), ) all_target_usages = [hid.get_full_usage_id(u[0], u[1]) for u in all_mutes] # usually you'll find and open the target device, here we'll browse for the # current connected devices all_devices = hid.find_all_hid_devices() success = 0 if not all_devices: print("Can't any HID device!") else: # search for our target usage # target pageId, usageId for device in all_devices: try: device.open() # target 'to set' value could be in feature or output reports for report in device.find_output_reports() + device.find_feature_reports(): for target_usage in all_target_usages: if target_usage in report: # set our value and send print("Found in report: {0}\n".format(report)) old_raw_data = report.get_raw_data() print(" Empty raw report: {0}".format(old_raw_data)) report[target_usage] = value new_raw_data = report.get_raw_data() print(" Set raw report: {0}\n".format(new_raw_data)) # validate that set_raw_data() is working properly report.set_raw_data( new_raw_data ) report.send() success += 1 finally: device.close() # fit to sys.exit() proper result values print("{0} Mute usage(s) set\n".format(success)) if success: return 0 return -1
python
def set_mute(mute_value): "Browse for mute usages and set value" all_mutes = ( \ (0x8, 0x9), # LED page (0x1, 0xA7), # desktop page (0xb, 0x2f), ) all_target_usages = [hid.get_full_usage_id(u[0], u[1]) for u in all_mutes] # usually you'll find and open the target device, here we'll browse for the # current connected devices all_devices = hid.find_all_hid_devices() success = 0 if not all_devices: print("Can't any HID device!") else: # search for our target usage # target pageId, usageId for device in all_devices: try: device.open() # target 'to set' value could be in feature or output reports for report in device.find_output_reports() + device.find_feature_reports(): for target_usage in all_target_usages: if target_usage in report: # set our value and send print("Found in report: {0}\n".format(report)) old_raw_data = report.get_raw_data() print(" Empty raw report: {0}".format(old_raw_data)) report[target_usage] = value new_raw_data = report.get_raw_data() print(" Set raw report: {0}\n".format(new_raw_data)) # validate that set_raw_data() is working properly report.set_raw_data( new_raw_data ) report.send() success += 1 finally: device.close() # fit to sys.exit() proper result values print("{0} Mute usage(s) set\n".format(success)) if success: return 0 return -1
Browse for mute usages and set value
https://github.com/rene-aguirre/pywinusb/blob/954c4b2105d9f01cb0c50e24500bb747d4ecdc43/examples/raw_set.py#L13-L57
rene-aguirre/pywinusb
examples/pnp_sample.py
MyFrame.on_hid_pnp
def on_hid_pnp(self, hid_event = None): """This function will be called on per class event changes, so we need to test if our device has being connected or is just gone""" # keep old reference for UI updates old_device = self.device if hid_event: print("Hey, a hid device just %s!" % hid_event) if hid_event == "connected": # test if our device is available if self.device: # see, at this point we could detect multiple devices! # but... we only want just one pass else: self.test_for_connection() elif hid_event == "disconnected": # the hid object is automatically closed on disconnection we just # test if still is plugged (important as the object might be # closing) if self.device and not self.device.is_plugged(): self.device = None print("you removed my hid device!") else: # poll for devices self.test_for_connection() if old_device != self.device: # update ui pass
python
def on_hid_pnp(self, hid_event = None): """This function will be called on per class event changes, so we need to test if our device has being connected or is just gone""" # keep old reference for UI updates old_device = self.device if hid_event: print("Hey, a hid device just %s!" % hid_event) if hid_event == "connected": # test if our device is available if self.device: # see, at this point we could detect multiple devices! # but... we only want just one pass else: self.test_for_connection() elif hid_event == "disconnected": # the hid object is automatically closed on disconnection we just # test if still is plugged (important as the object might be # closing) if self.device and not self.device.is_plugged(): self.device = None print("you removed my hid device!") else: # poll for devices self.test_for_connection() if old_device != self.device: # update ui pass
This function will be called on per class event changes, so we need to test if our device has being connected or is just gone
https://github.com/rene-aguirre/pywinusb/blob/954c4b2105d9f01cb0c50e24500bb747d4ecdc43/examples/pnp_sample.py#L35-L65
rene-aguirre/pywinusb
pywinusb/hid/helpers.py
simple_decorator
def simple_decorator(decorator): """This decorator can be used to turn simple functions into well-behaved decorators, so long as the decorators are fairly simple. If a decorator expects a function and returns a function (no descriptors), and if it doesn't modify function attributes or docstring, then it is eligible to use this. Simply apply @simple_decorator to your decorator and it will automatically preserve the docstring and function attributes of functions to which it is applied.""" def new_decorator(funct_target): """This will be modified""" decorated = decorator(funct_target) decorated.__name__ = funct_target.__name__ decorated.__doc__ = funct_target.__doc__ decorated.__dict__.update(funct_target.__dict__) return decorated # Now a few lines needed to make simple_decorator itself # be a well-behaved decorator. new_decorator.__name__ = decorator.__name__ new_decorator.__doc__ = decorator.__doc__ new_decorator.__dict__.update(decorator.__dict__) return new_decorator
python
def simple_decorator(decorator): """This decorator can be used to turn simple functions into well-behaved decorators, so long as the decorators are fairly simple. If a decorator expects a function and returns a function (no descriptors), and if it doesn't modify function attributes or docstring, then it is eligible to use this. Simply apply @simple_decorator to your decorator and it will automatically preserve the docstring and function attributes of functions to which it is applied.""" def new_decorator(funct_target): """This will be modified""" decorated = decorator(funct_target) decorated.__name__ = funct_target.__name__ decorated.__doc__ = funct_target.__doc__ decorated.__dict__.update(funct_target.__dict__) return decorated # Now a few lines needed to make simple_decorator itself # be a well-behaved decorator. new_decorator.__name__ = decorator.__name__ new_decorator.__doc__ = decorator.__doc__ new_decorator.__dict__.update(decorator.__dict__) return new_decorator
This decorator can be used to turn simple functions into well-behaved decorators, so long as the decorators are fairly simple. If a decorator expects a function and returns a function (no descriptors), and if it doesn't modify function attributes or docstring, then it is eligible to use this. Simply apply @simple_decorator to your decorator and it will automatically preserve the docstring and function attributes of functions to which it is applied.
https://github.com/rene-aguirre/pywinusb/blob/954c4b2105d9f01cb0c50e24500bb747d4ecdc43/pywinusb/hid/helpers.py#L18-L40
rene-aguirre/pywinusb
pywinusb/hid/helpers.py
logging_decorator
def logging_decorator(func): """Allow logging function calls""" def you_will_never_see_this_name(*args, **kwargs): """Neither this docstring""" print('calling %s ...' % func.__name__) result = func(*args, **kwargs) print('completed: %s' % func.__name__) return result return you_will_never_see_this_name
python
def logging_decorator(func): """Allow logging function calls""" def you_will_never_see_this_name(*args, **kwargs): """Neither this docstring""" print('calling %s ...' % func.__name__) result = func(*args, **kwargs) print('completed: %s' % func.__name__) return result return you_will_never_see_this_name
Allow logging function calls
https://github.com/rene-aguirre/pywinusb/blob/954c4b2105d9f01cb0c50e24500bb747d4ecdc43/pywinusb/hid/helpers.py#L46-L54
rene-aguirre/pywinusb
pywinusb/hid/helpers.py
synchronized
def synchronized(lock): """ Synchronization decorator. Allos to set a mutex on any function """ @simple_decorator def wrap(function_target): """Decorator wrapper""" def new_function(*args, **kw): """Decorated function with Mutex""" lock.acquire() try: return function_target(*args, **kw) finally: lock.release() return new_function return wrap
python
def synchronized(lock): """ Synchronization decorator. Allos to set a mutex on any function """ @simple_decorator def wrap(function_target): """Decorator wrapper""" def new_function(*args, **kw): """Decorated function with Mutex""" lock.acquire() try: return function_target(*args, **kw) finally: lock.release() return new_function return wrap
Synchronization decorator. Allos to set a mutex on any function
https://github.com/rene-aguirre/pywinusb/blob/954c4b2105d9f01cb0c50e24500bb747d4ecdc43/pywinusb/hid/helpers.py#L56-L71
rene-aguirre/pywinusb
examples/pnp_qt.py
HidQtPnPWindowMixin.on_hid_pnp
def on_hid_pnp(self, hid_event = None): """This function will be called on per class event changes, so we need to test if our device has being connected or is just gone""" old_device = self.hid_device if hid_event: self.pnpChanged.emit(hid_event) if hid_event == "connected": # test if our device is available if self.hid_device: # see, at this point we could detect multiple devices! # but... we only want just one pass else: self.test_for_connection() elif hid_event == "disconnected": # the hid object is automatically closed on disconnection we just # test if still is plugged (important as the object might be # closing) if self.hid_device and not self.hid_device.is_plugged(): self.hid_device = None else: # poll for devices self.test_for_connection() # update ui if old_device != self.hid_device: if hid_event == "disconnected": self.hidConnected.emit(old_device, hid_event) else: self.hidConnected.emit(self.hid_device, hid_event)
python
def on_hid_pnp(self, hid_event = None): """This function will be called on per class event changes, so we need to test if our device has being connected or is just gone""" old_device = self.hid_device if hid_event: self.pnpChanged.emit(hid_event) if hid_event == "connected": # test if our device is available if self.hid_device: # see, at this point we could detect multiple devices! # but... we only want just one pass else: self.test_for_connection() elif hid_event == "disconnected": # the hid object is automatically closed on disconnection we just # test if still is plugged (important as the object might be # closing) if self.hid_device and not self.hid_device.is_plugged(): self.hid_device = None else: # poll for devices self.test_for_connection() # update ui if old_device != self.hid_device: if hid_event == "disconnected": self.hidConnected.emit(old_device, hid_event) else: self.hidConnected.emit(self.hid_device, hid_event)
This function will be called on per class event changes, so we need to test if our device has being connected or is just gone
https://github.com/rene-aguirre/pywinusb/blob/954c4b2105d9f01cb0c50e24500bb747d4ecdc43/examples/pnp_qt.py#L41-L71
rene-aguirre/pywinusb
pywinusb/hid/hid_pnp_mixin.py
HidPnPWindowMixin._on_hid_pnp
def _on_hid_pnp(self, w_param, l_param): "Process WM_DEVICECHANGE system messages" new_status = "unknown" if w_param == DBT_DEVICEARRIVAL: # hid device attached notify_obj = None if int(l_param): # Disable this error since pylint doesn't reconize # that from_address actually exists # pylint: disable=no-member notify_obj = DevBroadcastDevInterface.from_address(l_param) #confirm if the right message received if notify_obj and \ notify_obj.dbcc_devicetype == DBT_DEVTYP_DEVICEINTERFACE: #only connect if already disconnected new_status = "connected" elif w_param == DBT_DEVICEREMOVECOMPLETE: # hid device removed notify_obj = None if int(l_param): # Disable this error since pylint doesn't reconize # that from_address actually exists # pylint: disable=no-member notify_obj = DevBroadcastDevInterface.from_address(l_param) if notify_obj and \ notify_obj.dbcc_devicetype == DBT_DEVTYP_DEVICEINTERFACE: #only connect if already disconnected new_status = "disconnected" #verify if need to call event handler if new_status != "unknown" and new_status != self.current_status: self.current_status = new_status self.on_hid_pnp(self.current_status) # return True
python
def _on_hid_pnp(self, w_param, l_param): "Process WM_DEVICECHANGE system messages" new_status = "unknown" if w_param == DBT_DEVICEARRIVAL: # hid device attached notify_obj = None if int(l_param): # Disable this error since pylint doesn't reconize # that from_address actually exists # pylint: disable=no-member notify_obj = DevBroadcastDevInterface.from_address(l_param) #confirm if the right message received if notify_obj and \ notify_obj.dbcc_devicetype == DBT_DEVTYP_DEVICEINTERFACE: #only connect if already disconnected new_status = "connected" elif w_param == DBT_DEVICEREMOVECOMPLETE: # hid device removed notify_obj = None if int(l_param): # Disable this error since pylint doesn't reconize # that from_address actually exists # pylint: disable=no-member notify_obj = DevBroadcastDevInterface.from_address(l_param) if notify_obj and \ notify_obj.dbcc_devicetype == DBT_DEVTYP_DEVICEINTERFACE: #only connect if already disconnected new_status = "disconnected" #verify if need to call event handler if new_status != "unknown" and new_status != self.current_status: self.current_status = new_status self.on_hid_pnp(self.current_status) # return True
Process WM_DEVICECHANGE system messages
https://github.com/rene-aguirre/pywinusb/blob/954c4b2105d9f01cb0c50e24500bb747d4ecdc43/pywinusb/hid/hid_pnp_mixin.py#L96-L130