func_code_string stringlengths 52 1.94M | func_documentation_string stringlengths 1 47.2k |
|---|---|
def are_equivalent(*args, **kwargs):
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 a... | 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 ch... |
def are_dicts_equivalent(*args, **kwargs):
# 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(... | 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:... |
def is_between(value,
minimum = None,
maximum = None,
**kwargs):
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:
... | 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 `... |
def has_length(value,
minimum = None,
maximum = None,
**kwargs):
if minimum is None and maximum is None:
raise ValueError('minimum and maximum cannot both be None')
length = len(value)
minimum = validators.numeric(minimum,
... | 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__... |
def is_dict(value, **kwargs):
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 <py... |
def is_json(value,
schema = None,
json_serializer = None,
**kwargs):
try:
value = validators.json(value,
schema = schema,
json_serializer = json_serializer,
**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... |
def is_string(value,
coerce_value = False,
minimum_length = None,
maximum_length = None,
whitespace_padding = False,
**kwargs):
if value is None:
return False
minimum_length = validators.integer(minimum_length, allow_empty = 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,... |
def is_iterable(obj,
forbid_literals = (str, bytes),
minimum_length = None,
maximum_length = None,
**kwargs):
if obj is None:
return False
if obj in forbid_literals:
return False
try:
obj = validators.iterable(obj,
... | 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: ite... |
def is_not_empty(value, **kwargs):
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... |
def is_none(value, allow_empty = False, **kwargs):
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`` ... |
def is_variable_name(value, **kwargs):
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: ``... |
def is_uuid(value, **kwargs):
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
... |
def is_date(value,
minimum = None,
maximum = None,
coerce_value = False,
**kwargs):
try:
value = validators.date(value,
minimum = minimum,
maximum = maximum,
c... | 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>` / ... |
def is_datetime(value,
minimum = None,
maximum = None,
coerce_value = False,
**kwargs):
try:
value = validators.datetime(value,
minimum = minimum,
maximum = maximum,
... | 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.d... |
def is_time(value,
minimum = None,
maximum = None,
coerce_value = False,
**kwargs):
try:
value = validators.time(value,
minimum = minimum,
maximum = maximum,
c... | 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_collec... |
def is_timezone(value,
positive = True,
**kwargs):
try:
value = validators.timezone(value,
positive = positive,
**kwargs)
except SyntaxError as error:
raise error
except Exception:
... | 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:
... |
def is_numeric(value,
minimum = None,
maximum = None,
**kwargs):
try:
value = validators.numeric(value,
minimum = minimum,
maximum = maximum,
**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... |
def is_integer(value,
coerce_value = False,
minimum = None,
maximum = None,
base = 10,
**kwargs):
try:
value = validators.integer(value,
coerce_value = coerce_value,
... | 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... |
def is_float(value,
minimum = None,
maximum = None,
**kwargs):
try:
value = validators.float(value,
minimum = minimum,
maximum = maximum,
**kwargs)
except Syntax... | 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 o... |
def is_fraction(value,
minimum = None,
maximum = None,
**kwargs):
try:
value = validators.fraction(value,
minimum = minimum,
maximum = maximum,
**k... | 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`... |
def is_decimal(value,
minimum = None,
maximum = None,
**kwargs):
try:
value = validators.decimal(value,
minimum = minimum,
maximum = maximum,
**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 ``valu... |
def is_pathlike(value, **kwargs):
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 ... |
def is_on_filesystem(value, **kwargs):
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 parameter... |
def is_file(value, **kwargs):
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
... |
def is_directory(value, **kwargs):
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 duplica... |
def is_readable(value, **kwargs):
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_ch... |
def is_writeable(value,
**kwargs):
if sys.platform in ['win32', 'cygwin']:
raise NotImplementedError('not supported on Windows')
try:
validators.writeable(value,
allow_empty = False,
**kwargs)
except SyntaxError ... | 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 sys... |
def is_executable(value,
**kwargs):
if sys.platform in ['win32', 'cygwin']:
raise NotImplementedError('not supported on Windows')
try:
validators.executable(value,
**kwargs)
except SyntaxError as error:
raise error
except Excep... | 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 s... |
def is_email(value, **kwargs):
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.
... |
def is_url(value, **kwargs):
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.... |
def is_domain(value, **kwargs):
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. I... |
def is_ip_address(value, **kwargs):
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
... |
def is_ipv4(value, **kwargs):
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 p... |
def is_ipv6(value, **kwargs):
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 p... |
def is_mac_address(value, **kwargs):
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... |
def draw_line(self, lx, ltor):
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 e... | Draw a series of elements from left to right |
def get_file_fields():
# 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 |
def remove_media(files):
for filename in files:
os.remove(os.path.join(settings.MEDIA_ROOT, filename)) | Delete file from media dir |
def remove_empty_dirs(path=None):
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
... | Recursively delete empty directories; return True if everything was deleted. |
def get_used_media():
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... | Get media which are still used in models |
def get_all_media(exclude=None):
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_RO... | Get all media from MEDIA_ROOT |
def get_unused_media(exclude=None):
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 |
def createCluster(self, hzVersion, xmlconfig):
self.send_createCluster(hzVersion, xmlconfig)
return self.recv_createCluster() | Parameters:
- hzVersion
- xmlconfig |
def shutdownMember(self, clusterId, memberId):
self.send_shutdownMember(clusterId, memberId)
return self.recv_shutdownMember() | Parameters:
- clusterId
- memberId |
def terminateMember(self, clusterId, memberId):
self.send_terminateMember(clusterId, memberId)
return self.recv_terminateMember() | Parameters:
- clusterId
- memberId |
def suspendMember(self, clusterId, memberId):
self.send_suspendMember(clusterId, memberId)
return self.recv_suspendMember() | Parameters:
- clusterId
- memberId |
def resumeMember(self, clusterId, memberId):
self.send_resumeMember(clusterId, memberId)
return self.recv_resumeMember() | Parameters:
- clusterId
- memberId |
def mergeMemberToCluster(self, clusterId, memberId):
self.send_mergeMemberToCluster(clusterId, memberId)
return self.recv_mergeMemberToCluster() | Parameters:
- clusterId
- memberId |
def executeOnController(self, clusterId, script, lang):
self.send_executeOnController(clusterId, script, lang)
return self.recv_executeOnController() | Parameters:
- clusterId
- script
- lang |
def deltaE(color1, color2,
input_space="sRGB1", uniform_space="CAM02-UCS"):
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 li... |
def XYZ100_to_sRGB1_linear(XYZ100):
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). |
def sRGB1_to_sRGB1_linear(sRGB1):
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. |
def cspace_converter(start, end):
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 b... |
def cspace_convert(arr, start, end):
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. |
def XYZ100_to_CIECAM02(self, XYZ100, on_negative_A="raise"):
#### 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)
... | 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... |
def CIECAM02_to_XYZ100(self, J=None, C=None, h=None,
Q=None, M=None, s=None, H=None):
#### 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.asa... | 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 c... |
def standard_illuminant_XYZ100(name, observer="CIE 1931 2 deg"):
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 ... | 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 li... |
def as_XYZ100_w(whitepoint):
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
... |
def machado_et_al_2009_matrix(cvd_type, severity):
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 in... | 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:
... |
def _make_retval_checker(self):
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... | Create a function that checks the return value of the function. |
def _make_args_checker(self):
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... | Create a function that checks signature of the source function. |
def checker_for_type(t):
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:
# Exceptio... | 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")... |
def _prepare_value(val, maxlen=50, notype=False):
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:
... | Stringify value `val`, ensuring that it is not too long. |
def _nth_str(n):
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. |
def train(self, text, className):
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(t... | enhances trained data using the given text and class |
def hid_device_path_exists(device_path, guid = None):
# 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:
fo... | Test if required device_path is still valid
(HID device connected to host) |
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-de... | Finds all HID devices connected to the system |
def show_hids(target_vid = 0, target_pid = 0, output = None):
# 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... | Check all HID devices conected to PC hosts. |
def get_devices_by_parent(self, hid_filter=None):
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()
de... | Group devices returned from filter query in order \
by devcice parent id. |
def get_devices(self, hid_filter = None):
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:
retur... | Filter a HID device list by current object parameters. Devices
must match the all of the filtering parameters |
def get_parent_device(self):
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),
... | Retreive parent device string id |
def open(self, output_only = False, shared = True):
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(
... | Open HID device and obtain 'Collection Information'.
It effectively prepares the HidDevice object for reading and writing |
def get_physical_descriptor(self):
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 |
def send_output_report(self, 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_dat... | Send input/output/feature report ID = report_id, data should be a
c_ubyte object with included the required report data |
def send_feature_report(self, 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... | Send input/output/feature report ID = report_id, data should be a
c_byte object with included the required report data |
def __reset_vars(self):
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 mig... | Reset vars (for init or gc) |
def close(self):
# 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()
#avo... | Release system resources |
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.rep... | Find input report referencing HID usage control/data item |
def find_any_reports(self, usage_page = 0, usage_id = 0):
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)),... | Find any report type referencing HID usage control/data item.
Results are returned in a dictionary mapping report_type to usage
lists. |
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... | Default raw input report data handler |
def find_input_usage(self, full_usage_id):
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. |
def add_event_handler(self, full_usage_id, handler_function,
event_kind = HID_EVT_ALL, aux_data = None):
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... | Add event handler for usage value/button changes,
returns True if the handler function was updated |
def set_value(self, value):
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 s... | Set usage value within report |
def get_value(self):
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... | Retreive usage value within report |
def get_usage_string(self):
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,
... | Returns usage representation string (as embedded in HID device
if available) |
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 |
def __alloc_raw_data(self, initial_values=None):
#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... | Pre-allocate re-usagle memory |
def set_raw_data(self, raw_data):
#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_si... | 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 |
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")
... | Format internal __raw_data storage according to usages setting |
def get_raw_data(self):
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.R... | Get raw HID report based on internal report item settings,
creates new c_ubytes storage |
def send(self, raw_data = None):
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):
ra... | Prepare HID raw report (unless raw_data is provided) and send
it to HID device |
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... | Read report from device |
def inspect(self):
results = {}
for fname in dir(self):
if not fname.startswith('_'):
value = getattr(self, fname)
if isinstance(value, collections.Callable):
continue
results[fname] = value
return ... | Retreive dictionary of 'Field: Value' attributes |
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 ... | Browse for mute usages and set value |
def on_hid_pnp(self, hid_event = None):
# 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 se... | 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 |
def simple_decorator(decorator):
def new_decorator(funct_target):
decorated = decorator(funct_target)
decorated.__name__ = funct_target.__name__
decorated.__doc__ = funct_target.__doc__
decorated.__dict__.update(funct_target.__dict__)
return decorated
... | 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. S... |
def logging_decorator(func):
def you_will_never_see_this_name(*args, **kwargs):
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 |
def synchronized(lock):
@simple_decorator
def wrap(function_target):
def new_function(*args, **kw):
lock.acquire()
try:
return function_target(*args, **kw)
finally:
lock.release()
return ne... | Synchronization decorator.
Allos to set a mutex on any function |
def on_hid_pnp(self, hid_event = None):
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 ... | 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 |
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... | Process WM_DEVICECHANGE system messages |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.