id
int32
0
252k
repo
stringlengths
7
55
path
stringlengths
4
127
func_name
stringlengths
1
88
original_string
stringlengths
75
19.8k
language
stringclasses
1 value
code
stringlengths
51
19.8k
code_tokens
list
docstring
stringlengths
3
17.3k
docstring_tokens
list
sha
stringlengths
40
40
url
stringlengths
87
242
26,900
scidash/sciunit
sciunit/validators.py
ObservationValidator._validate_units
def _validate_units(self, has_units, key, value): """Validate fields with `units` key in schema set to True. The rule's arguments are validated against this schema: {'type': 'boolean'} """ if has_units: if isinstance(self.test.units, dict): required_units = self.test.units[key] else: required_units = self.test.units if not isinstance(value, pq.quantity.Quantity): self._error(key, "Must be a python quantity") if not isinstance(value, pq.quantity.Quantity): self._error(key, "Must be a python quantity") provided_units = value.simplified.units if not isinstance(required_units, pq.Dimensionless): required_units = required_units.simplified.units if not required_units == provided_units: self._error(key, "Must have units of '%s'" % self.test.units.name)
python
def _validate_units(self, has_units, key, value): if has_units: if isinstance(self.test.units, dict): required_units = self.test.units[key] else: required_units = self.test.units if not isinstance(value, pq.quantity.Quantity): self._error(key, "Must be a python quantity") if not isinstance(value, pq.quantity.Quantity): self._error(key, "Must be a python quantity") provided_units = value.simplified.units if not isinstance(required_units, pq.Dimensionless): required_units = required_units.simplified.units if not required_units == provided_units: self._error(key, "Must have units of '%s'" % self.test.units.name)
[ "def", "_validate_units", "(", "self", ",", "has_units", ",", "key", ",", "value", ")", ":", "if", "has_units", ":", "if", "isinstance", "(", "self", ".", "test", ".", "units", ",", "dict", ")", ":", "required_units", "=", "self", ".", "test", ".", "...
Validate fields with `units` key in schema set to True. The rule's arguments are validated against this schema: {'type': 'boolean'}
[ "Validate", "fields", "with", "units", "key", "in", "schema", "set", "to", "True", "." ]
41b2e38c45c0776727ab1f281a572b65be19cea1
https://github.com/scidash/sciunit/blob/41b2e38c45c0776727ab1f281a572b65be19cea1/sciunit/validators.py#L45-L65
26,901
scidash/sciunit
sciunit/validators.py
ParametersValidator.validate_quantity
def validate_quantity(self, value): """Validate that the value is of the `Quantity` type.""" if not isinstance(value, pq.quantity.Quantity): self._error('%s' % value, "Must be a Python quantity.")
python
def validate_quantity(self, value): if not isinstance(value, pq.quantity.Quantity): self._error('%s' % value, "Must be a Python quantity.")
[ "def", "validate_quantity", "(", "self", ",", "value", ")", ":", "if", "not", "isinstance", "(", "value", ",", "pq", ".", "quantity", ".", "Quantity", ")", ":", "self", ".", "_error", "(", "'%s'", "%", "value", ",", "\"Must be a Python quantity.\"", ")" ]
Validate that the value is of the `Quantity` type.
[ "Validate", "that", "the", "value", "is", "of", "the", "Quantity", "type", "." ]
41b2e38c45c0776727ab1f281a572b65be19cea1
https://github.com/scidash/sciunit/blob/41b2e38c45c0776727ab1f281a572b65be19cea1/sciunit/validators.py#L73-L76
26,902
scidash/sciunit
sciunit/scores/complete.py
ZScore.compute
def compute(cls, observation, prediction): """Compute a z-score from an observation and a prediction.""" assert isinstance(observation, dict) try: p_value = prediction['mean'] # Use the prediction's mean. except (TypeError, KeyError, IndexError): # If there isn't one... try: p_value = prediction['value'] # Use the prediction's value. except (TypeError, IndexError): # If there isn't one... p_value = prediction # Use the prediction (assume numeric). o_mean = observation['mean'] o_std = observation['std'] value = (p_value - o_mean)/o_std value = utils.assert_dimensionless(value) if np.isnan(value): score = InsufficientDataScore('One of the input values was NaN') else: score = ZScore(value) return score
python
def compute(cls, observation, prediction): assert isinstance(observation, dict) try: p_value = prediction['mean'] # Use the prediction's mean. except (TypeError, KeyError, IndexError): # If there isn't one... try: p_value = prediction['value'] # Use the prediction's value. except (TypeError, IndexError): # If there isn't one... p_value = prediction # Use the prediction (assume numeric). o_mean = observation['mean'] o_std = observation['std'] value = (p_value - o_mean)/o_std value = utils.assert_dimensionless(value) if np.isnan(value): score = InsufficientDataScore('One of the input values was NaN') else: score = ZScore(value) return score
[ "def", "compute", "(", "cls", ",", "observation", ",", "prediction", ")", ":", "assert", "isinstance", "(", "observation", ",", "dict", ")", "try", ":", "p_value", "=", "prediction", "[", "'mean'", "]", "# Use the prediction's mean.", "except", "(", "TypeError...
Compute a z-score from an observation and a prediction.
[ "Compute", "a", "z", "-", "score", "from", "an", "observation", "and", "a", "prediction", "." ]
41b2e38c45c0776727ab1f281a572b65be19cea1
https://github.com/scidash/sciunit/blob/41b2e38c45c0776727ab1f281a572b65be19cea1/sciunit/scores/complete.py#L55-L73
26,903
scidash/sciunit
sciunit/scores/complete.py
ZScore.norm_score
def norm_score(self): """Return the normalized score. Equals 1.0 for a z-score of 0, falling to 0.0 for extremely positive or negative values. """ cdf = (1.0 + math.erf(self.score / math.sqrt(2.0))) / 2.0 return 1 - 2*math.fabs(0.5 - cdf)
python
def norm_score(self): cdf = (1.0 + math.erf(self.score / math.sqrt(2.0))) / 2.0 return 1 - 2*math.fabs(0.5 - cdf)
[ "def", "norm_score", "(", "self", ")", ":", "cdf", "=", "(", "1.0", "+", "math", ".", "erf", "(", "self", ".", "score", "/", "math", ".", "sqrt", "(", "2.0", ")", ")", ")", "/", "2.0", "return", "1", "-", "2", "*", "math", ".", "fabs", "(", ...
Return the normalized score. Equals 1.0 for a z-score of 0, falling to 0.0 for extremely positive or negative values.
[ "Return", "the", "normalized", "score", "." ]
41b2e38c45c0776727ab1f281a572b65be19cea1
https://github.com/scidash/sciunit/blob/41b2e38c45c0776727ab1f281a572b65be19cea1/sciunit/scores/complete.py#L76-L83
26,904
scidash/sciunit
sciunit/scores/complete.py
CohenDScore.compute
def compute(cls, observation, prediction): """Compute a Cohen's D from an observation and a prediction.""" assert isinstance(observation, dict) assert isinstance(prediction, dict) p_mean = prediction['mean'] # Use the prediction's mean. p_std = prediction['std'] o_mean = observation['mean'] o_std = observation['std'] try: # Try to pool taking samples sizes into account. p_n = prediction['n'] o_n = observation['n'] s = (((p_n-1)*(p_std**2) + (o_n-1)*(o_std**2))/(p_n+o_n-2))**0.5 except KeyError: # If sample sizes are not available. s = (p_std**2 + o_std**2)**0.5 value = (p_mean - o_mean)/s value = utils.assert_dimensionless(value) return CohenDScore(value)
python
def compute(cls, observation, prediction): assert isinstance(observation, dict) assert isinstance(prediction, dict) p_mean = prediction['mean'] # Use the prediction's mean. p_std = prediction['std'] o_mean = observation['mean'] o_std = observation['std'] try: # Try to pool taking samples sizes into account. p_n = prediction['n'] o_n = observation['n'] s = (((p_n-1)*(p_std**2) + (o_n-1)*(o_std**2))/(p_n+o_n-2))**0.5 except KeyError: # If sample sizes are not available. s = (p_std**2 + o_std**2)**0.5 value = (p_mean - o_mean)/s value = utils.assert_dimensionless(value) return CohenDScore(value)
[ "def", "compute", "(", "cls", ",", "observation", ",", "prediction", ")", ":", "assert", "isinstance", "(", "observation", ",", "dict", ")", "assert", "isinstance", "(", "prediction", ",", "dict", ")", "p_mean", "=", "prediction", "[", "'mean'", "]", "# Us...
Compute a Cohen's D from an observation and a prediction.
[ "Compute", "a", "Cohen", "s", "D", "from", "an", "observation", "and", "a", "prediction", "." ]
41b2e38c45c0776727ab1f281a572b65be19cea1
https://github.com/scidash/sciunit/blob/41b2e38c45c0776727ab1f281a572b65be19cea1/sciunit/scores/complete.py#L99-L115
26,905
scidash/sciunit
sciunit/scores/complete.py
RatioScore.compute
def compute(cls, observation, prediction, key=None): """Compute a ratio from an observation and a prediction.""" assert isinstance(observation, (dict, float, int, pq.Quantity)) assert isinstance(prediction, (dict, float, int, pq.Quantity)) obs, pred = cls.extract_means_or_values(observation, prediction, key=key) value = pred / obs value = utils.assert_dimensionless(value) return RatioScore(value)
python
def compute(cls, observation, prediction, key=None): assert isinstance(observation, (dict, float, int, pq.Quantity)) assert isinstance(prediction, (dict, float, int, pq.Quantity)) obs, pred = cls.extract_means_or_values(observation, prediction, key=key) value = pred / obs value = utils.assert_dimensionless(value) return RatioScore(value)
[ "def", "compute", "(", "cls", ",", "observation", ",", "prediction", ",", "key", "=", "None", ")", ":", "assert", "isinstance", "(", "observation", ",", "(", "dict", ",", "float", ",", "int", ",", "pq", ".", "Quantity", ")", ")", "assert", "isinstance"...
Compute a ratio from an observation and a prediction.
[ "Compute", "a", "ratio", "from", "an", "observation", "and", "a", "prediction", "." ]
41b2e38c45c0776727ab1f281a572b65be19cea1
https://github.com/scidash/sciunit/blob/41b2e38c45c0776727ab1f281a572b65be19cea1/sciunit/scores/complete.py#L139-L148
26,906
scidash/sciunit
sciunit/scores/complete.py
FloatScore.compute_ssd
def compute_ssd(cls, observation, prediction): """Compute sum-squared diff between observation and prediction.""" # The sum of the squared differences. value = ((observation - prediction)**2).sum() score = FloatScore(value) return score
python
def compute_ssd(cls, observation, prediction): # The sum of the squared differences. value = ((observation - prediction)**2).sum() score = FloatScore(value) return score
[ "def", "compute_ssd", "(", "cls", ",", "observation", ",", "prediction", ")", ":", "# The sum of the squared differences.", "value", "=", "(", "(", "observation", "-", "prediction", ")", "**", "2", ")", ".", "sum", "(", ")", "score", "=", "FloatScore", "(", ...
Compute sum-squared diff between observation and prediction.
[ "Compute", "sum", "-", "squared", "diff", "between", "observation", "and", "prediction", "." ]
41b2e38c45c0776727ab1f281a572b65be19cea1
https://github.com/scidash/sciunit/blob/41b2e38c45c0776727ab1f281a572b65be19cea1/sciunit/scores/complete.py#L203-L208
26,907
scidash/sciunit
setup.py
read_requirements
def read_requirements(): '''parses requirements from requirements.txt''' reqs_path = os.path.join('.', 'requirements.txt') install_reqs = parse_requirements(reqs_path, session=PipSession()) reqs = [str(ir.req) for ir in install_reqs] return reqs
python
def read_requirements(): '''parses requirements from requirements.txt''' reqs_path = os.path.join('.', 'requirements.txt') install_reqs = parse_requirements(reqs_path, session=PipSession()) reqs = [str(ir.req) for ir in install_reqs] return reqs
[ "def", "read_requirements", "(", ")", ":", "reqs_path", "=", "os", ".", "path", ".", "join", "(", "'.'", ",", "'requirements.txt'", ")", "install_reqs", "=", "parse_requirements", "(", "reqs_path", ",", "session", "=", "PipSession", "(", ")", ")", "reqs", ...
parses requirements from requirements.txt
[ "parses", "requirements", "from", "requirements", ".", "txt" ]
41b2e38c45c0776727ab1f281a572b65be19cea1
https://github.com/scidash/sciunit/blob/41b2e38c45c0776727ab1f281a572b65be19cea1/setup.py#L21-L26
26,908
scidash/sciunit
sciunit/models/backends.py
register_backends
def register_backends(vars): """Register backends for use with models. `vars` should be a dictionary of variables obtained from e.g. `locals()`, at least some of which are Backend classes, e.g. from imports. """ new_backends = {x.replace('Backend', ''): cls for x, cls in vars.items() if inspect.isclass(cls) and issubclass(cls, Backend)} available_backends.update(new_backends)
python
def register_backends(vars): new_backends = {x.replace('Backend', ''): cls for x, cls in vars.items() if inspect.isclass(cls) and issubclass(cls, Backend)} available_backends.update(new_backends)
[ "def", "register_backends", "(", "vars", ")", ":", "new_backends", "=", "{", "x", ".", "replace", "(", "'Backend'", ",", "''", ")", ":", "cls", "for", "x", ",", "cls", "in", "vars", ".", "items", "(", ")", "if", "inspect", ".", "isclass", "(", "cls...
Register backends for use with models. `vars` should be a dictionary of variables obtained from e.g. `locals()`, at least some of which are Backend classes, e.g. from imports.
[ "Register", "backends", "for", "use", "with", "models", "." ]
41b2e38c45c0776727ab1f281a572b65be19cea1
https://github.com/scidash/sciunit/blob/41b2e38c45c0776727ab1f281a572b65be19cea1/sciunit/models/backends.py#L12-L21
26,909
scidash/sciunit
sciunit/models/backends.py
Backend.init_backend
def init_backend(self, *args, **kwargs): """Initialize the backend.""" self.model.attrs = {} self.use_memory_cache = kwargs.get('use_memory_cache', True) if self.use_memory_cache: self.init_memory_cache() self.use_disk_cache = kwargs.get('use_disk_cache', False) if self.use_disk_cache: self.init_disk_cache() self.load_model() self.model.unpicklable += ['_backend']
python
def init_backend(self, *args, **kwargs): self.model.attrs = {} self.use_memory_cache = kwargs.get('use_memory_cache', True) if self.use_memory_cache: self.init_memory_cache() self.use_disk_cache = kwargs.get('use_disk_cache', False) if self.use_disk_cache: self.init_disk_cache() self.load_model() self.model.unpicklable += ['_backend']
[ "def", "init_backend", "(", "self", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "self", ".", "model", ".", "attrs", "=", "{", "}", "self", ".", "use_memory_cache", "=", "kwargs", ".", "get", "(", "'use_memory_cache'", ",", "True", ")", "if",...
Initialize the backend.
[ "Initialize", "the", "backend", "." ]
41b2e38c45c0776727ab1f281a572b65be19cea1
https://github.com/scidash/sciunit/blob/41b2e38c45c0776727ab1f281a572b65be19cea1/sciunit/models/backends.py#L33-L44
26,910
scidash/sciunit
sciunit/models/backends.py
Backend.init_disk_cache
def init_disk_cache(self): """Initialize the on-disk version of the cache.""" try: # Cleanup old disk cache files path = self.disk_cache_location os.remove(path) except Exception: pass self.disk_cache_location = os.path.join(tempfile.mkdtemp(), 'cache')
python
def init_disk_cache(self): try: # Cleanup old disk cache files path = self.disk_cache_location os.remove(path) except Exception: pass self.disk_cache_location = os.path.join(tempfile.mkdtemp(), 'cache')
[ "def", "init_disk_cache", "(", "self", ")", ":", "try", ":", "# Cleanup old disk cache files", "path", "=", "self", ".", "disk_cache_location", "os", ".", "remove", "(", "path", ")", "except", "Exception", ":", "pass", "self", ".", "disk_cache_location", "=", ...
Initialize the on-disk version of the cache.
[ "Initialize", "the", "on", "-", "disk", "version", "of", "the", "cache", "." ]
41b2e38c45c0776727ab1f281a572b65be19cea1
https://github.com/scidash/sciunit/blob/41b2e38c45c0776727ab1f281a572b65be19cea1/sciunit/models/backends.py#L64-L72
26,911
scidash/sciunit
sciunit/models/backends.py
Backend.get_memory_cache
def get_memory_cache(self, key=None): """Return result in memory cache for key 'key' or None if not found.""" key = self.model.hash if key is None else key self._results = self.memory_cache.get(key) return self._results
python
def get_memory_cache(self, key=None): key = self.model.hash if key is None else key self._results = self.memory_cache.get(key) return self._results
[ "def", "get_memory_cache", "(", "self", ",", "key", "=", "None", ")", ":", "key", "=", "self", ".", "model", ".", "hash", "if", "key", "is", "None", "else", "key", "self", ".", "_results", "=", "self", ".", "memory_cache", ".", "get", "(", "key", "...
Return result in memory cache for key 'key' or None if not found.
[ "Return", "result", "in", "memory", "cache", "for", "key", "key", "or", "None", "if", "not", "found", "." ]
41b2e38c45c0776727ab1f281a572b65be19cea1
https://github.com/scidash/sciunit/blob/41b2e38c45c0776727ab1f281a572b65be19cea1/sciunit/models/backends.py#L74-L78
26,912
scidash/sciunit
sciunit/models/backends.py
Backend.get_disk_cache
def get_disk_cache(self, key=None): """Return result in disk cache for key 'key' or None if not found.""" key = self.model.hash if key is None else key if not getattr(self, 'disk_cache_location', False): self.init_disk_cache() disk_cache = shelve.open(self.disk_cache_location) self._results = disk_cache.get(key) disk_cache.close() return self._results
python
def get_disk_cache(self, key=None): key = self.model.hash if key is None else key if not getattr(self, 'disk_cache_location', False): self.init_disk_cache() disk_cache = shelve.open(self.disk_cache_location) self._results = disk_cache.get(key) disk_cache.close() return self._results
[ "def", "get_disk_cache", "(", "self", ",", "key", "=", "None", ")", ":", "key", "=", "self", ".", "model", ".", "hash", "if", "key", "is", "None", "else", "key", "if", "not", "getattr", "(", "self", ",", "'disk_cache_location'", ",", "False", ")", ":...
Return result in disk cache for key 'key' or None if not found.
[ "Return", "result", "in", "disk", "cache", "for", "key", "key", "or", "None", "if", "not", "found", "." ]
41b2e38c45c0776727ab1f281a572b65be19cea1
https://github.com/scidash/sciunit/blob/41b2e38c45c0776727ab1f281a572b65be19cea1/sciunit/models/backends.py#L80-L88
26,913
scidash/sciunit
sciunit/models/backends.py
Backend.set_memory_cache
def set_memory_cache(self, results, key=None): """Store result in memory cache with key matching model state.""" key = self.model.hash if key is None else key self.memory_cache[key] = results
python
def set_memory_cache(self, results, key=None): key = self.model.hash if key is None else key self.memory_cache[key] = results
[ "def", "set_memory_cache", "(", "self", ",", "results", ",", "key", "=", "None", ")", ":", "key", "=", "self", ".", "model", ".", "hash", "if", "key", "is", "None", "else", "key", "self", ".", "memory_cache", "[", "key", "]", "=", "results" ]
Store result in memory cache with key matching model state.
[ "Store", "result", "in", "memory", "cache", "with", "key", "matching", "model", "state", "." ]
41b2e38c45c0776727ab1f281a572b65be19cea1
https://github.com/scidash/sciunit/blob/41b2e38c45c0776727ab1f281a572b65be19cea1/sciunit/models/backends.py#L90-L93
26,914
scidash/sciunit
sciunit/models/backends.py
Backend.set_disk_cache
def set_disk_cache(self, results, key=None): """Store result in disk cache with key matching model state.""" if not getattr(self, 'disk_cache_location', False): self.init_disk_cache() disk_cache = shelve.open(self.disk_cache_location) key = self.model.hash if key is None else key disk_cache[key] = results disk_cache.close()
python
def set_disk_cache(self, results, key=None): if not getattr(self, 'disk_cache_location', False): self.init_disk_cache() disk_cache = shelve.open(self.disk_cache_location) key = self.model.hash if key is None else key disk_cache[key] = results disk_cache.close()
[ "def", "set_disk_cache", "(", "self", ",", "results", ",", "key", "=", "None", ")", ":", "if", "not", "getattr", "(", "self", ",", "'disk_cache_location'", ",", "False", ")", ":", "self", ".", "init_disk_cache", "(", ")", "disk_cache", "=", "shelve", "."...
Store result in disk cache with key matching model state.
[ "Store", "result", "in", "disk", "cache", "with", "key", "matching", "model", "state", "." ]
41b2e38c45c0776727ab1f281a572b65be19cea1
https://github.com/scidash/sciunit/blob/41b2e38c45c0776727ab1f281a572b65be19cea1/sciunit/models/backends.py#L95-L102
26,915
scidash/sciunit
sciunit/models/backends.py
Backend.backend_run
def backend_run(self): """Check for cached results; then run the model if needed.""" key = self.model.hash if self.use_memory_cache and self.get_memory_cache(key): return self._results if self.use_disk_cache and self.get_disk_cache(key): return self._results results = self._backend_run() if self.use_memory_cache: self.set_memory_cache(results, key) if self.use_disk_cache: self.set_disk_cache(results, key) return results
python
def backend_run(self): key = self.model.hash if self.use_memory_cache and self.get_memory_cache(key): return self._results if self.use_disk_cache and self.get_disk_cache(key): return self._results results = self._backend_run() if self.use_memory_cache: self.set_memory_cache(results, key) if self.use_disk_cache: self.set_disk_cache(results, key) return results
[ "def", "backend_run", "(", "self", ")", ":", "key", "=", "self", ".", "model", ".", "hash", "if", "self", ".", "use_memory_cache", "and", "self", ".", "get_memory_cache", "(", "key", ")", ":", "return", "self", ".", "_results", "if", "self", ".", "use_...
Check for cached results; then run the model if needed.
[ "Check", "for", "cached", "results", ";", "then", "run", "the", "model", "if", "needed", "." ]
41b2e38c45c0776727ab1f281a572b65be19cea1
https://github.com/scidash/sciunit/blob/41b2e38c45c0776727ab1f281a572b65be19cea1/sciunit/models/backends.py#L116-L128
26,916
scidash/sciunit
sciunit/models/backends.py
Backend.save_results
def save_results(self, path='.'): """Save results on disk.""" with open(path, 'wb') as f: pickle.dump(self.results, f)
python
def save_results(self, path='.'): with open(path, 'wb') as f: pickle.dump(self.results, f)
[ "def", "save_results", "(", "self", ",", "path", "=", "'.'", ")", ":", "with", "open", "(", "path", ",", "'wb'", ")", "as", "f", ":", "pickle", ".", "dump", "(", "self", ".", "results", ",", "f", ")" ]
Save results on disk.
[ "Save", "results", "on", "disk", "." ]
41b2e38c45c0776727ab1f281a572b65be19cea1
https://github.com/scidash/sciunit/blob/41b2e38c45c0776727ab1f281a572b65be19cea1/sciunit/models/backends.py#L134-L137
26,917
scidash/sciunit
sciunit/capabilities.py
Capability.check
def check(cls, model, require_extra=False): """Check whether the provided model has this capability. By default, uses isinstance. If `require_extra`, also requires that an instance check be present in `model.extra_capability_checks`. """ class_capable = isinstance(model, cls) f_name = model.extra_capability_checks.get(cls, None) \ if model.extra_capability_checks is not None \ else False if f_name: f = getattr(model, f_name) instance_capable = f() elif not require_extra: instance_capable = True else: instance_capable = False return class_capable and instance_capable
python
def check(cls, model, require_extra=False): class_capable = isinstance(model, cls) f_name = model.extra_capability_checks.get(cls, None) \ if model.extra_capability_checks is not None \ else False if f_name: f = getattr(model, f_name) instance_capable = f() elif not require_extra: instance_capable = True else: instance_capable = False return class_capable and instance_capable
[ "def", "check", "(", "cls", ",", "model", ",", "require_extra", "=", "False", ")", ":", "class_capable", "=", "isinstance", "(", "model", ",", "cls", ")", "f_name", "=", "model", ".", "extra_capability_checks", ".", "get", "(", "cls", ",", "None", ")", ...
Check whether the provided model has this capability. By default, uses isinstance. If `require_extra`, also requires that an instance check be present in `model.extra_capability_checks`.
[ "Check", "whether", "the", "provided", "model", "has", "this", "capability", "." ]
41b2e38c45c0776727ab1f281a572b65be19cea1
https://github.com/scidash/sciunit/blob/41b2e38c45c0776727ab1f281a572b65be19cea1/sciunit/capabilities.py#L18-L37
26,918
scidash/sciunit
sciunit/models/runnable.py
RunnableModel.set_backend
def set_backend(self, backend): """Set the simulation backend.""" if isinstance(backend, str): name = backend args = [] kwargs = {} elif isinstance(backend, (tuple, list)): name = '' args = [] kwargs = {} for i in range(len(backend)): if i == 0: name = backend[i] else: if isinstance(backend[i], dict): kwargs.update(backend[i]) else: args += backend[i] else: raise TypeError("Backend must be string, tuple, or list") if name in available_backends: self.backend = name self._backend = available_backends[name]() elif name is None: # The base class should not be called. raise Exception(("A backend (e.g. 'jNeuroML' or 'NEURON') " "must be selected")) else: raise Exception("Backend %s not found in backends.py" % name) self._backend.model = self self._backend.init_backend(*args, **kwargs)
python
def set_backend(self, backend): if isinstance(backend, str): name = backend args = [] kwargs = {} elif isinstance(backend, (tuple, list)): name = '' args = [] kwargs = {} for i in range(len(backend)): if i == 0: name = backend[i] else: if isinstance(backend[i], dict): kwargs.update(backend[i]) else: args += backend[i] else: raise TypeError("Backend must be string, tuple, or list") if name in available_backends: self.backend = name self._backend = available_backends[name]() elif name is None: # The base class should not be called. raise Exception(("A backend (e.g. 'jNeuroML' or 'NEURON') " "must be selected")) else: raise Exception("Backend %s not found in backends.py" % name) self._backend.model = self self._backend.init_backend(*args, **kwargs)
[ "def", "set_backend", "(", "self", ",", "backend", ")", ":", "if", "isinstance", "(", "backend", ",", "str", ")", ":", "name", "=", "backend", "args", "=", "[", "]", "kwargs", "=", "{", "}", "elif", "isinstance", "(", "backend", ",", "(", "tuple", ...
Set the simulation backend.
[ "Set", "the", "simulation", "backend", "." ]
41b2e38c45c0776727ab1f281a572b65be19cea1
https://github.com/scidash/sciunit/blob/41b2e38c45c0776727ab1f281a572b65be19cea1/sciunit/models/runnable.py#L33-L64
26,919
scidash/sciunit
sciunit/scores/base.py
Score.color
def color(self, value=None): """Turn the score intp an RGB color tuple of three 8-bit integers.""" if value is None: value = self.norm_score rgb = Score.value_color(value) return rgb
python
def color(self, value=None): if value is None: value = self.norm_score rgb = Score.value_color(value) return rgb
[ "def", "color", "(", "self", ",", "value", "=", "None", ")", ":", "if", "value", "is", "None", ":", "value", "=", "self", ".", "norm_score", "rgb", "=", "Score", ".", "value_color", "(", "value", ")", "return", "rgb" ]
Turn the score intp an RGB color tuple of three 8-bit integers.
[ "Turn", "the", "score", "intp", "an", "RGB", "color", "tuple", "of", "three", "8", "-", "bit", "integers", "." ]
41b2e38c45c0776727ab1f281a572b65be19cea1
https://github.com/scidash/sciunit/blob/41b2e38c45c0776727ab1f281a572b65be19cea1/sciunit/scores/base.py#L83-L88
26,920
scidash/sciunit
sciunit/scores/base.py
Score.extract_means_or_values
def extract_means_or_values(cls, observation, prediction, key=None): """Extracts the mean, value, or user-provided key from the observation and prediction dictionaries. """ obs_mv = cls.extract_mean_or_value(observation, key) pred_mv = cls.extract_mean_or_value(prediction, key) return obs_mv, pred_mv
python
def extract_means_or_values(cls, observation, prediction, key=None): obs_mv = cls.extract_mean_or_value(observation, key) pred_mv = cls.extract_mean_or_value(prediction, key) return obs_mv, pred_mv
[ "def", "extract_means_or_values", "(", "cls", ",", "observation", ",", "prediction", ",", "key", "=", "None", ")", ":", "obs_mv", "=", "cls", ".", "extract_mean_or_value", "(", "observation", ",", "key", ")", "pred_mv", "=", "cls", ".", "extract_mean_or_value"...
Extracts the mean, value, or user-provided key from the observation and prediction dictionaries.
[ "Extracts", "the", "mean", "value", "or", "user", "-", "provided", "key", "from", "the", "observation", "and", "prediction", "dictionaries", "." ]
41b2e38c45c0776727ab1f281a572b65be19cea1
https://github.com/scidash/sciunit/blob/41b2e38c45c0776727ab1f281a572b65be19cea1/sciunit/scores/base.py#L209-L216
26,921
scidash/sciunit
sciunit/scores/base.py
Score.extract_mean_or_value
def extract_mean_or_value(cls, obs_or_pred, key=None): """Extracts the mean, value, or user-provided key from an observation or prediction dictionary. """ result = None if not isinstance(obs_or_pred, dict): result = obs_or_pred else: keys = ([key] if key is not None else []) + ['mean', 'value'] for k in keys: if k in obs_or_pred: result = obs_or_pred[k] break if result is None: raise KeyError(("%s has neither a mean nor a single " "value" % obs_or_pred)) return result
python
def extract_mean_or_value(cls, obs_or_pred, key=None): result = None if not isinstance(obs_or_pred, dict): result = obs_or_pred else: keys = ([key] if key is not None else []) + ['mean', 'value'] for k in keys: if k in obs_or_pred: result = obs_or_pred[k] break if result is None: raise KeyError(("%s has neither a mean nor a single " "value" % obs_or_pred)) return result
[ "def", "extract_mean_or_value", "(", "cls", ",", "obs_or_pred", ",", "key", "=", "None", ")", ":", "result", "=", "None", "if", "not", "isinstance", "(", "obs_or_pred", ",", "dict", ")", ":", "result", "=", "obs_or_pred", "else", ":", "keys", "=", "(", ...
Extracts the mean, value, or user-provided key from an observation or prediction dictionary.
[ "Extracts", "the", "mean", "value", "or", "user", "-", "provided", "key", "from", "an", "observation", "or", "prediction", "dictionary", "." ]
41b2e38c45c0776727ab1f281a572b65be19cea1
https://github.com/scidash/sciunit/blob/41b2e38c45c0776727ab1f281a572b65be19cea1/sciunit/scores/base.py#L219-L236
26,922
scidash/sciunit
sciunit/scores/base.py
ErrorScore.summary
def summary(self): """Summarize the performance of a model on a test.""" return "== Model %s did not complete test %s due to error '%s'. ==" %\ (str(self.model), str(self.test), str(self.score))
python
def summary(self): return "== Model %s did not complete test %s due to error '%s'. ==" %\ (str(self.model), str(self.test), str(self.score))
[ "def", "summary", "(", "self", ")", ":", "return", "\"== Model %s did not complete test %s due to error '%s'. ==\"", "%", "(", "str", "(", "self", ".", "model", ")", ",", "str", "(", "self", ".", "test", ")", ",", "str", "(", "self", ".", "score", ")", ")"...
Summarize the performance of a model on a test.
[ "Summarize", "the", "performance", "of", "a", "model", "on", "a", "test", "." ]
41b2e38c45c0776727ab1f281a572b65be19cea1
https://github.com/scidash/sciunit/blob/41b2e38c45c0776727ab1f281a572b65be19cea1/sciunit/scores/base.py#L247-L250
26,923
mon/ifstools
ifstools/handlers/TexFolder.py
ImageCanvas.load
def load(self, draw_bbox = False, **kwargs): ''' Makes the canvas. This could be far speedier if it copied raw pixels, but that would take far too much time to write vs using Image inbuilts ''' im = Image.new('RGBA', self.img_size) draw = None if draw_bbox: draw = ImageDraw.Draw(im) for sprite in self.images: data = sprite.load() sprite_im = Image.open(BytesIO(data)) size = sprite.imgrect im.paste(sprite_im, (size[0], size[2])) if draw_bbox: draw.rectangle((size[0], size[2], size[1], size[3]), outline='red') del draw b = BytesIO() im.save(b, format = 'PNG') return b.getvalue()
python
def load(self, draw_bbox = False, **kwargs): ''' Makes the canvas. This could be far speedier if it copied raw pixels, but that would take far too much time to write vs using Image inbuilts ''' im = Image.new('RGBA', self.img_size) draw = None if draw_bbox: draw = ImageDraw.Draw(im) for sprite in self.images: data = sprite.load() sprite_im = Image.open(BytesIO(data)) size = sprite.imgrect im.paste(sprite_im, (size[0], size[2])) if draw_bbox: draw.rectangle((size[0], size[2], size[1], size[3]), outline='red') del draw b = BytesIO() im.save(b, format = 'PNG') return b.getvalue()
[ "def", "load", "(", "self", ",", "draw_bbox", "=", "False", ",", "*", "*", "kwargs", ")", ":", "im", "=", "Image", ".", "new", "(", "'RGBA'", ",", "self", ".", "img_size", ")", "draw", "=", "None", "if", "draw_bbox", ":", "draw", "=", "ImageDraw", ...
Makes the canvas. This could be far speedier if it copied raw pixels, but that would take far too much time to write vs using Image inbuilts
[ "Makes", "the", "canvas", ".", "This", "could", "be", "far", "speedier", "if", "it", "copied", "raw", "pixels", "but", "that", "would", "take", "far", "too", "much", "time", "to", "write", "vs", "using", "Image", "inbuilts" ]
ccd9c1c3632aa22cdcc4e064f17e07803b1d27ba
https://github.com/mon/ifstools/blob/ccd9c1c3632aa22cdcc4e064f17e07803b1d27ba/ifstools/handlers/TexFolder.py#L35-L56
26,924
mon/ifstools
ifstools/handlers/lz77.py
match_window
def match_window(in_data, offset): '''Find the longest match for the string starting at offset in the preceeding data ''' window_start = max(offset - WINDOW_MASK, 0) for n in range(MAX_LEN, THRESHOLD-1, -1): window_end = min(offset + n, len(in_data)) # we've not got enough data left for a meaningful result if window_end - offset < THRESHOLD: return None str_to_find = in_data[offset:window_end] idx = in_data.rfind(str_to_find, window_start, window_end-n) if idx != -1: code_offset = offset - idx # - 1 code_len = len(str_to_find) return (code_offset, code_len) return None
python
def match_window(in_data, offset): '''Find the longest match for the string starting at offset in the preceeding data ''' window_start = max(offset - WINDOW_MASK, 0) for n in range(MAX_LEN, THRESHOLD-1, -1): window_end = min(offset + n, len(in_data)) # we've not got enough data left for a meaningful result if window_end - offset < THRESHOLD: return None str_to_find = in_data[offset:window_end] idx = in_data.rfind(str_to_find, window_start, window_end-n) if idx != -1: code_offset = offset - idx # - 1 code_len = len(str_to_find) return (code_offset, code_len) return None
[ "def", "match_window", "(", "in_data", ",", "offset", ")", ":", "window_start", "=", "max", "(", "offset", "-", "WINDOW_MASK", ",", "0", ")", "for", "n", "in", "range", "(", "MAX_LEN", ",", "THRESHOLD", "-", "1", ",", "-", "1", ")", ":", "window_end"...
Find the longest match for the string starting at offset in the preceeding data
[ "Find", "the", "longest", "match", "for", "the", "string", "starting", "at", "offset", "in", "the", "preceeding", "data" ]
ccd9c1c3632aa22cdcc4e064f17e07803b1d27ba
https://github.com/mon/ifstools/blob/ccd9c1c3632aa22cdcc4e064f17e07803b1d27ba/ifstools/handlers/lz77.py#L44-L61
26,925
Ch00k/ffmpy
ffmpy.py
_merge_args_opts
def _merge_args_opts(args_opts_dict, **kwargs): """Merge options with their corresponding arguments. Iterates over the dictionary holding arguments (keys) and options (values). Merges each options string with its corresponding argument. :param dict args_opts_dict: a dictionary of arguments and options :param dict kwargs: *input_option* - if specified prepends ``-i`` to input argument :return: merged list of strings with arguments and their corresponding options :rtype: list """ merged = [] if not args_opts_dict: return merged for arg, opt in args_opts_dict.items(): if not _is_sequence(opt): opt = shlex.split(opt or '') merged += opt if not arg: continue if 'add_input_option' in kwargs: merged.append('-i') merged.append(arg) return merged
python
def _merge_args_opts(args_opts_dict, **kwargs): merged = [] if not args_opts_dict: return merged for arg, opt in args_opts_dict.items(): if not _is_sequence(opt): opt = shlex.split(opt or '') merged += opt if not arg: continue if 'add_input_option' in kwargs: merged.append('-i') merged.append(arg) return merged
[ "def", "_merge_args_opts", "(", "args_opts_dict", ",", "*", "*", "kwargs", ")", ":", "merged", "=", "[", "]", "if", "not", "args_opts_dict", ":", "return", "merged", "for", "arg", ",", "opt", "in", "args_opts_dict", ".", "items", "(", ")", ":", "if", "...
Merge options with their corresponding arguments. Iterates over the dictionary holding arguments (keys) and options (values). Merges each options string with its corresponding argument. :param dict args_opts_dict: a dictionary of arguments and options :param dict kwargs: *input_option* - if specified prepends ``-i`` to input argument :return: merged list of strings with arguments and their corresponding options :rtype: list
[ "Merge", "options", "with", "their", "corresponding", "arguments", "." ]
4ed3ab7ce1c1c2e7181c03278b2311fd407cfc75
https://github.com/Ch00k/ffmpy/blob/4ed3ab7ce1c1c2e7181c03278b2311fd407cfc75/ffmpy.py#L171-L200
26,926
Ch00k/ffmpy
ffmpy.py
FFmpeg.run
def run(self, input_data=None, stdout=None, stderr=None): """Execute FFmpeg command line. ``input_data`` can contain input for FFmpeg in case ``pipe`` protocol is used for input. ``stdout`` and ``stderr`` specify where to redirect the ``stdout`` and ``stderr`` of the process. By default no redirection is done, which means all output goes to running shell (this mode should normally only be used for debugging purposes). If FFmpeg ``pipe`` protocol is used for output, ``stdout`` must be redirected to a pipe by passing `subprocess.PIPE` as ``stdout`` argument. Returns a 2-tuple containing ``stdout`` and ``stderr`` of the process. If there was no redirection or if the output was redirected to e.g. `os.devnull`, the value returned will be a tuple of two `None` values, otherwise it will contain the actual ``stdout`` and ``stderr`` data returned by ffmpeg process. More info about ``pipe`` protocol `here <https://ffmpeg.org/ffmpeg-protocols.html#pipe>`_. :param str input_data: input data for FFmpeg to deal with (audio, video etc.) as bytes (e.g. the result of reading a file in binary mode) :param stdout: redirect FFmpeg ``stdout`` there (default is `None` which means no redirection) :param stderr: redirect FFmpeg ``stderr`` there (default is `None` which means no redirection) :return: a 2-tuple containing ``stdout`` and ``stderr`` of the process :rtype: tuple :raise: `FFRuntimeError` in case FFmpeg command exits with a non-zero code; `FFExecutableNotFoundError` in case the executable path passed was not valid """ try: self.process = subprocess.Popen( self._cmd, stdin=subprocess.PIPE, stdout=stdout, stderr=stderr ) except OSError as e: if e.errno == errno.ENOENT: raise FFExecutableNotFoundError("Executable '{0}' not found".format(self.executable)) else: raise out = self.process.communicate(input=input_data) if self.process.returncode != 0: raise FFRuntimeError(self.cmd, self.process.returncode, out[0], out[1]) return out
python
def run(self, input_data=None, stdout=None, stderr=None): try: self.process = subprocess.Popen( self._cmd, stdin=subprocess.PIPE, stdout=stdout, stderr=stderr ) except OSError as e: if e.errno == errno.ENOENT: raise FFExecutableNotFoundError("Executable '{0}' not found".format(self.executable)) else: raise out = self.process.communicate(input=input_data) if self.process.returncode != 0: raise FFRuntimeError(self.cmd, self.process.returncode, out[0], out[1]) return out
[ "def", "run", "(", "self", ",", "input_data", "=", "None", ",", "stdout", "=", "None", ",", "stderr", "=", "None", ")", ":", "try", ":", "self", ".", "process", "=", "subprocess", ".", "Popen", "(", "self", ".", "_cmd", ",", "stdin", "=", "subproce...
Execute FFmpeg command line. ``input_data`` can contain input for FFmpeg in case ``pipe`` protocol is used for input. ``stdout`` and ``stderr`` specify where to redirect the ``stdout`` and ``stderr`` of the process. By default no redirection is done, which means all output goes to running shell (this mode should normally only be used for debugging purposes). If FFmpeg ``pipe`` protocol is used for output, ``stdout`` must be redirected to a pipe by passing `subprocess.PIPE` as ``stdout`` argument. Returns a 2-tuple containing ``stdout`` and ``stderr`` of the process. If there was no redirection or if the output was redirected to e.g. `os.devnull`, the value returned will be a tuple of two `None` values, otherwise it will contain the actual ``stdout`` and ``stderr`` data returned by ffmpeg process. More info about ``pipe`` protocol `here <https://ffmpeg.org/ffmpeg-protocols.html#pipe>`_. :param str input_data: input data for FFmpeg to deal with (audio, video etc.) as bytes (e.g. the result of reading a file in binary mode) :param stdout: redirect FFmpeg ``stdout`` there (default is `None` which means no redirection) :param stderr: redirect FFmpeg ``stderr`` there (default is `None` which means no redirection) :return: a 2-tuple containing ``stdout`` and ``stderr`` of the process :rtype: tuple :raise: `FFRuntimeError` in case FFmpeg command exits with a non-zero code; `FFExecutableNotFoundError` in case the executable path passed was not valid
[ "Execute", "FFmpeg", "command", "line", "." ]
4ed3ab7ce1c1c2e7181c03278b2311fd407cfc75
https://github.com/Ch00k/ffmpy/blob/4ed3ab7ce1c1c2e7181c03278b2311fd407cfc75/ffmpy.py#L62-L107
26,927
click-contrib/sphinx-click
sphinx_click/ext.py
_get_usage
def _get_usage(ctx): """Alternative, non-prefixed version of 'get_usage'.""" formatter = ctx.make_formatter() pieces = ctx.command.collect_usage_pieces(ctx) formatter.write_usage(ctx.command_path, ' '.join(pieces), prefix='') return formatter.getvalue().rstrip('\n')
python
def _get_usage(ctx): formatter = ctx.make_formatter() pieces = ctx.command.collect_usage_pieces(ctx) formatter.write_usage(ctx.command_path, ' '.join(pieces), prefix='') return formatter.getvalue().rstrip('\n')
[ "def", "_get_usage", "(", "ctx", ")", ":", "formatter", "=", "ctx", ".", "make_formatter", "(", ")", "pieces", "=", "ctx", ".", "command", ".", "collect_usage_pieces", "(", "ctx", ")", "formatter", ".", "write_usage", "(", "ctx", ".", "command_path", ",", ...
Alternative, non-prefixed version of 'get_usage'.
[ "Alternative", "non", "-", "prefixed", "version", "of", "get_usage", "." ]
ec76d15697ec80e51486a6e3daa0aec60b04870f
https://github.com/click-contrib/sphinx-click/blob/ec76d15697ec80e51486a6e3daa0aec60b04870f/sphinx_click/ext.py#L23-L28
26,928
click-contrib/sphinx-click
sphinx_click/ext.py
_get_help_record
def _get_help_record(opt): """Re-implementation of click.Opt.get_help_record. The variant of 'get_help_record' found in Click makes uses of slashes to separate multiple opts, and formats option arguments using upper case. This is not compatible with Sphinx's 'option' directive, which expects comma-separated opts and option arguments surrounded by angle brackets [1]. [1] http://www.sphinx-doc.org/en/stable/domains.html#directive-option """ def _write_opts(opts): rv, _ = click.formatting.join_options(opts) if not opt.is_flag and not opt.count: rv += ' <{}>'.format(opt.name) return rv rv = [_write_opts(opt.opts)] if opt.secondary_opts: rv.append(_write_opts(opt.secondary_opts)) help = opt.help or '' extra = [] if opt.default is not None and opt.show_default: extra.append( 'default: %s' % (', '.join('%s' % d for d in opt.default) if isinstance(opt.default, (list, tuple)) else opt.default, )) if opt.required: extra.append('required') if extra: help = '%s[%s]' % (help and help + ' ' or '', '; '.join(extra)) return ', '.join(rv), help
python
def _get_help_record(opt): def _write_opts(opts): rv, _ = click.formatting.join_options(opts) if not opt.is_flag and not opt.count: rv += ' <{}>'.format(opt.name) return rv rv = [_write_opts(opt.opts)] if opt.secondary_opts: rv.append(_write_opts(opt.secondary_opts)) help = opt.help or '' extra = [] if opt.default is not None and opt.show_default: extra.append( 'default: %s' % (', '.join('%s' % d for d in opt.default) if isinstance(opt.default, (list, tuple)) else opt.default, )) if opt.required: extra.append('required') if extra: help = '%s[%s]' % (help and help + ' ' or '', '; '.join(extra)) return ', '.join(rv), help
[ "def", "_get_help_record", "(", "opt", ")", ":", "def", "_write_opts", "(", "opts", ")", ":", "rv", ",", "_", "=", "click", ".", "formatting", ".", "join_options", "(", "opts", ")", "if", "not", "opt", ".", "is_flag", "and", "not", "opt", ".", "count...
Re-implementation of click.Opt.get_help_record. The variant of 'get_help_record' found in Click makes uses of slashes to separate multiple opts, and formats option arguments using upper case. This is not compatible with Sphinx's 'option' directive, which expects comma-separated opts and option arguments surrounded by angle brackets [1]. [1] http://www.sphinx-doc.org/en/stable/domains.html#directive-option
[ "Re", "-", "implementation", "of", "click", ".", "Opt", ".", "get_help_record", "." ]
ec76d15697ec80e51486a6e3daa0aec60b04870f
https://github.com/click-contrib/sphinx-click/blob/ec76d15697ec80e51486a6e3daa0aec60b04870f/sphinx_click/ext.py#L31-L64
26,929
click-contrib/sphinx-click
sphinx_click/ext.py
_format_description
def _format_description(ctx): """Format the description for a given `click.Command`. We parse this as reStructuredText, allowing users to embed rich information in their help messages if they so choose. """ help_string = ctx.command.help or ctx.command.short_help if not help_string: return bar_enabled = False for line in statemachine.string2lines( help_string, tab_width=4, convert_whitespace=True): if line == '\b': bar_enabled = True continue if line == '': bar_enabled = False line = '| ' + line if bar_enabled else line yield line yield ''
python
def _format_description(ctx): help_string = ctx.command.help or ctx.command.short_help if not help_string: return bar_enabled = False for line in statemachine.string2lines( help_string, tab_width=4, convert_whitespace=True): if line == '\b': bar_enabled = True continue if line == '': bar_enabled = False line = '| ' + line if bar_enabled else line yield line yield ''
[ "def", "_format_description", "(", "ctx", ")", ":", "help_string", "=", "ctx", ".", "command", ".", "help", "or", "ctx", ".", "command", ".", "short_help", "if", "not", "help_string", ":", "return", "bar_enabled", "=", "False", "for", "line", "in", "statem...
Format the description for a given `click.Command`. We parse this as reStructuredText, allowing users to embed rich information in their help messages if they so choose.
[ "Format", "the", "description", "for", "a", "given", "click", ".", "Command", "." ]
ec76d15697ec80e51486a6e3daa0aec60b04870f
https://github.com/click-contrib/sphinx-click/blob/ec76d15697ec80e51486a6e3daa0aec60b04870f/sphinx_click/ext.py#L67-L87
26,930
click-contrib/sphinx-click
sphinx_click/ext.py
_format_option
def _format_option(opt): """Format the output for a `click.Option`.""" opt = _get_help_record(opt) yield '.. option:: {}'.format(opt[0]) if opt[1]: yield '' for line in statemachine.string2lines( opt[1], tab_width=4, convert_whitespace=True): yield _indent(line)
python
def _format_option(opt): opt = _get_help_record(opt) yield '.. option:: {}'.format(opt[0]) if opt[1]: yield '' for line in statemachine.string2lines( opt[1], tab_width=4, convert_whitespace=True): yield _indent(line)
[ "def", "_format_option", "(", "opt", ")", ":", "opt", "=", "_get_help_record", "(", "opt", ")", "yield", "'.. option:: {}'", ".", "format", "(", "opt", "[", "0", "]", ")", "if", "opt", "[", "1", "]", ":", "yield", "''", "for", "line", "in", "statemac...
Format the output for a `click.Option`.
[ "Format", "the", "output", "for", "a", "click", ".", "Option", "." ]
ec76d15697ec80e51486a6e3daa0aec60b04870f
https://github.com/click-contrib/sphinx-click/blob/ec76d15697ec80e51486a6e3daa0aec60b04870f/sphinx_click/ext.py#L99-L108
26,931
click-contrib/sphinx-click
sphinx_click/ext.py
_format_options
def _format_options(ctx): """Format all `click.Option` for a `click.Command`.""" # the hidden attribute is part of click 7.x only hence use of getattr params = [ x for x in ctx.command.params if isinstance(x, click.Option) and not getattr(x, 'hidden', False) ] for param in params: for line in _format_option(param): yield line yield ''
python
def _format_options(ctx): # the hidden attribute is part of click 7.x only hence use of getattr params = [ x for x in ctx.command.params if isinstance(x, click.Option) and not getattr(x, 'hidden', False) ] for param in params: for line in _format_option(param): yield line yield ''
[ "def", "_format_options", "(", "ctx", ")", ":", "# the hidden attribute is part of click 7.x only hence use of getattr", "params", "=", "[", "x", "for", "x", "in", "ctx", ".", "command", ".", "params", "if", "isinstance", "(", "x", ",", "click", ".", "Option", "...
Format all `click.Option` for a `click.Command`.
[ "Format", "all", "click", ".", "Option", "for", "a", "click", ".", "Command", "." ]
ec76d15697ec80e51486a6e3daa0aec60b04870f
https://github.com/click-contrib/sphinx-click/blob/ec76d15697ec80e51486a6e3daa0aec60b04870f/sphinx_click/ext.py#L111-L122
26,932
click-contrib/sphinx-click
sphinx_click/ext.py
_format_argument
def _format_argument(arg): """Format the output of a `click.Argument`.""" yield '.. option:: {}'.format(arg.human_readable_name) yield '' yield _indent('{} argument{}'.format( 'Required' if arg.required else 'Optional', '(s)' if arg.nargs != 1 else ''))
python
def _format_argument(arg): yield '.. option:: {}'.format(arg.human_readable_name) yield '' yield _indent('{} argument{}'.format( 'Required' if arg.required else 'Optional', '(s)' if arg.nargs != 1 else ''))
[ "def", "_format_argument", "(", "arg", ")", ":", "yield", "'.. option:: {}'", ".", "format", "(", "arg", ".", "human_readable_name", ")", "yield", "''", "yield", "_indent", "(", "'{} argument{}'", ".", "format", "(", "'Required'", "if", "arg", ".", "required",...
Format the output of a `click.Argument`.
[ "Format", "the", "output", "of", "a", "click", ".", "Argument", "." ]
ec76d15697ec80e51486a6e3daa0aec60b04870f
https://github.com/click-contrib/sphinx-click/blob/ec76d15697ec80e51486a6e3daa0aec60b04870f/sphinx_click/ext.py#L125-L131
26,933
click-contrib/sphinx-click
sphinx_click/ext.py
_format_arguments
def _format_arguments(ctx): """Format all `click.Argument` for a `click.Command`.""" params = [x for x in ctx.command.params if isinstance(x, click.Argument)] for param in params: for line in _format_argument(param): yield line yield ''
python
def _format_arguments(ctx): params = [x for x in ctx.command.params if isinstance(x, click.Argument)] for param in params: for line in _format_argument(param): yield line yield ''
[ "def", "_format_arguments", "(", "ctx", ")", ":", "params", "=", "[", "x", "for", "x", "in", "ctx", ".", "command", ".", "params", "if", "isinstance", "(", "x", ",", "click", ".", "Argument", ")", "]", "for", "param", "in", "params", ":", "for", "l...
Format all `click.Argument` for a `click.Command`.
[ "Format", "all", "click", ".", "Argument", "for", "a", "click", ".", "Command", "." ]
ec76d15697ec80e51486a6e3daa0aec60b04870f
https://github.com/click-contrib/sphinx-click/blob/ec76d15697ec80e51486a6e3daa0aec60b04870f/sphinx_click/ext.py#L134-L141
26,934
click-contrib/sphinx-click
sphinx_click/ext.py
_format_envvar
def _format_envvar(param): """Format the envvars of a `click.Option` or `click.Argument`.""" yield '.. envvar:: {}'.format(param.envvar) yield ' :noindex:' yield '' if isinstance(param, click.Argument): param_ref = param.human_readable_name else: # if a user has defined an opt with multiple "aliases", always use the # first. For example, if '--foo' or '-f' are possible, use '--foo'. param_ref = param.opts[0] yield _indent('Provide a default for :option:`{}`'.format(param_ref))
python
def _format_envvar(param): yield '.. envvar:: {}'.format(param.envvar) yield ' :noindex:' yield '' if isinstance(param, click.Argument): param_ref = param.human_readable_name else: # if a user has defined an opt with multiple "aliases", always use the # first. For example, if '--foo' or '-f' are possible, use '--foo'. param_ref = param.opts[0] yield _indent('Provide a default for :option:`{}`'.format(param_ref))
[ "def", "_format_envvar", "(", "param", ")", ":", "yield", "'.. envvar:: {}'", ".", "format", "(", "param", ".", "envvar", ")", "yield", "' :noindex:'", "yield", "''", "if", "isinstance", "(", "param", ",", "click", ".", "Argument", ")", ":", "param_ref", ...
Format the envvars of a `click.Option` or `click.Argument`.
[ "Format", "the", "envvars", "of", "a", "click", ".", "Option", "or", "click", ".", "Argument", "." ]
ec76d15697ec80e51486a6e3daa0aec60b04870f
https://github.com/click-contrib/sphinx-click/blob/ec76d15697ec80e51486a6e3daa0aec60b04870f/sphinx_click/ext.py#L144-L156
26,935
click-contrib/sphinx-click
sphinx_click/ext.py
_format_envvars
def _format_envvars(ctx): """Format all envvars for a `click.Command`.""" params = [x for x in ctx.command.params if getattr(x, 'envvar')] for param in params: yield '.. _{command_name}-{param_name}-{envvar}:'.format( command_name=ctx.command_path.replace(' ', '-'), param_name=param.name, envvar=param.envvar, ) yield '' for line in _format_envvar(param): yield line yield ''
python
def _format_envvars(ctx): params = [x for x in ctx.command.params if getattr(x, 'envvar')] for param in params: yield '.. _{command_name}-{param_name}-{envvar}:'.format( command_name=ctx.command_path.replace(' ', '-'), param_name=param.name, envvar=param.envvar, ) yield '' for line in _format_envvar(param): yield line yield ''
[ "def", "_format_envvars", "(", "ctx", ")", ":", "params", "=", "[", "x", "for", "x", "in", "ctx", ".", "command", ".", "params", "if", "getattr", "(", "x", ",", "'envvar'", ")", "]", "for", "param", "in", "params", ":", "yield", "'.. _{command_name}-{p...
Format all envvars for a `click.Command`.
[ "Format", "all", "envvars", "for", "a", "click", ".", "Command", "." ]
ec76d15697ec80e51486a6e3daa0aec60b04870f
https://github.com/click-contrib/sphinx-click/blob/ec76d15697ec80e51486a6e3daa0aec60b04870f/sphinx_click/ext.py#L159-L172
26,936
click-contrib/sphinx-click
sphinx_click/ext.py
_format_subcommand
def _format_subcommand(command): """Format a sub-command of a `click.Command` or `click.Group`.""" yield '.. object:: {}'.format(command.name) # click 7.0 stopped setting short_help by default if CLICK_VERSION < (7, 0): short_help = command.short_help else: short_help = command.get_short_help_str() if short_help: yield '' for line in statemachine.string2lines( short_help, tab_width=4, convert_whitespace=True): yield _indent(line)
python
def _format_subcommand(command): yield '.. object:: {}'.format(command.name) # click 7.0 stopped setting short_help by default if CLICK_VERSION < (7, 0): short_help = command.short_help else: short_help = command.get_short_help_str() if short_help: yield '' for line in statemachine.string2lines( short_help, tab_width=4, convert_whitespace=True): yield _indent(line)
[ "def", "_format_subcommand", "(", "command", ")", ":", "yield", "'.. object:: {}'", ".", "format", "(", "command", ".", "name", ")", "# click 7.0 stopped setting short_help by default", "if", "CLICK_VERSION", "<", "(", "7", ",", "0", ")", ":", "short_help", "=", ...
Format a sub-command of a `click.Command` or `click.Group`.
[ "Format", "a", "sub", "-", "command", "of", "a", "click", ".", "Command", "or", "click", ".", "Group", "." ]
ec76d15697ec80e51486a6e3daa0aec60b04870f
https://github.com/click-contrib/sphinx-click/blob/ec76d15697ec80e51486a6e3daa0aec60b04870f/sphinx_click/ext.py#L175-L189
26,937
click-contrib/sphinx-click
sphinx_click/ext.py
_filter_commands
def _filter_commands(ctx, commands=None): """Return list of used commands.""" lookup = getattr(ctx.command, 'commands', {}) if not lookup and isinstance(ctx.command, click.MultiCommand): lookup = _get_lazyload_commands(ctx.command) if commands is None: return sorted(lookup.values(), key=lambda item: item.name) names = [name.strip() for name in commands.split(',')] return [lookup[name] for name in names if name in lookup]
python
def _filter_commands(ctx, commands=None): lookup = getattr(ctx.command, 'commands', {}) if not lookup and isinstance(ctx.command, click.MultiCommand): lookup = _get_lazyload_commands(ctx.command) if commands is None: return sorted(lookup.values(), key=lambda item: item.name) names = [name.strip() for name in commands.split(',')] return [lookup[name] for name in names if name in lookup]
[ "def", "_filter_commands", "(", "ctx", ",", "commands", "=", "None", ")", ":", "lookup", "=", "getattr", "(", "ctx", ".", "command", ",", "'commands'", ",", "{", "}", ")", "if", "not", "lookup", "and", "isinstance", "(", "ctx", ".", "command", ",", "...
Return list of used commands.
[ "Return", "list", "of", "used", "commands", "." ]
ec76d15697ec80e51486a6e3daa0aec60b04870f
https://github.com/click-contrib/sphinx-click/blob/ec76d15697ec80e51486a6e3daa0aec60b04870f/sphinx_click/ext.py#L200-L210
26,938
click-contrib/sphinx-click
sphinx_click/ext.py
_format_command
def _format_command(ctx, show_nested, commands=None): """Format the output of `click.Command`.""" # the hidden attribute is part of click 7.x only hence use of getattr if getattr(ctx.command, 'hidden', False): return # description for line in _format_description(ctx): yield line yield '.. program:: {}'.format(ctx.command_path) # usage for line in _format_usage(ctx): yield line # options lines = list(_format_options(ctx)) if lines: # we use rubric to provide some separation without exploding the table # of contents yield '.. rubric:: Options' yield '' for line in lines: yield line # arguments lines = list(_format_arguments(ctx)) if lines: yield '.. rubric:: Arguments' yield '' for line in lines: yield line # environment variables lines = list(_format_envvars(ctx)) if lines: yield '.. rubric:: Environment variables' yield '' for line in lines: yield line # if we're nesting commands, we need to do this slightly differently if show_nested: return commands = _filter_commands(ctx, commands) if commands: yield '.. rubric:: Commands' yield '' for command in commands: # Don't show hidden subcommands if CLICK_VERSION >= (7, 0): if command.hidden: continue for line in _format_subcommand(command): yield line yield ''
python
def _format_command(ctx, show_nested, commands=None): # the hidden attribute is part of click 7.x only hence use of getattr if getattr(ctx.command, 'hidden', False): return # description for line in _format_description(ctx): yield line yield '.. program:: {}'.format(ctx.command_path) # usage for line in _format_usage(ctx): yield line # options lines = list(_format_options(ctx)) if lines: # we use rubric to provide some separation without exploding the table # of contents yield '.. rubric:: Options' yield '' for line in lines: yield line # arguments lines = list(_format_arguments(ctx)) if lines: yield '.. rubric:: Arguments' yield '' for line in lines: yield line # environment variables lines = list(_format_envvars(ctx)) if lines: yield '.. rubric:: Environment variables' yield '' for line in lines: yield line # if we're nesting commands, we need to do this slightly differently if show_nested: return commands = _filter_commands(ctx, commands) if commands: yield '.. rubric:: Commands' yield '' for command in commands: # Don't show hidden subcommands if CLICK_VERSION >= (7, 0): if command.hidden: continue for line in _format_subcommand(command): yield line yield ''
[ "def", "_format_command", "(", "ctx", ",", "show_nested", ",", "commands", "=", "None", ")", ":", "# the hidden attribute is part of click 7.x only hence use of getattr", "if", "getattr", "(", "ctx", ".", "command", ",", "'hidden'", ",", "False", ")", ":", "return",...
Format the output of `click.Command`.
[ "Format", "the", "output", "of", "click", ".", "Command", "." ]
ec76d15697ec80e51486a6e3daa0aec60b04870f
https://github.com/click-contrib/sphinx-click/blob/ec76d15697ec80e51486a6e3daa0aec60b04870f/sphinx_click/ext.py#L213-L281
26,939
click-contrib/sphinx-click
sphinx_click/ext.py
ClickDirective._load_module
def _load_module(self, module_path): """Load the module.""" # __import__ will fail on unicode, # so we ensure module path is a string here. module_path = str(module_path) try: module_name, attr_name = module_path.split(':', 1) except ValueError: # noqa raise self.error( '"{}" is not of format "module:parser"'.format(module_path)) try: mod = __import__(module_name, globals(), locals(), [attr_name]) except (Exception, SystemExit) as exc: # noqa err_msg = 'Failed to import "{}" from "{}". '.format( attr_name, module_name) if isinstance(exc, SystemExit): err_msg += 'The module appeared to call sys.exit()' else: err_msg += 'The following exception was raised:\n{}'.format( traceback.format_exc()) raise self.error(err_msg) if not hasattr(mod, attr_name): raise self.error('Module "{}" has no attribute "{}"'.format( module_name, attr_name)) parser = getattr(mod, attr_name) if not isinstance(parser, click.BaseCommand): raise self.error('"{}" of type "{}" is not derived from ' '"click.BaseCommand"'.format( type(parser), module_path)) return parser
python
def _load_module(self, module_path): # __import__ will fail on unicode, # so we ensure module path is a string here. module_path = str(module_path) try: module_name, attr_name = module_path.split(':', 1) except ValueError: # noqa raise self.error( '"{}" is not of format "module:parser"'.format(module_path)) try: mod = __import__(module_name, globals(), locals(), [attr_name]) except (Exception, SystemExit) as exc: # noqa err_msg = 'Failed to import "{}" from "{}". '.format( attr_name, module_name) if isinstance(exc, SystemExit): err_msg += 'The module appeared to call sys.exit()' else: err_msg += 'The following exception was raised:\n{}'.format( traceback.format_exc()) raise self.error(err_msg) if not hasattr(mod, attr_name): raise self.error('Module "{}" has no attribute "{}"'.format( module_name, attr_name)) parser = getattr(mod, attr_name) if not isinstance(parser, click.BaseCommand): raise self.error('"{}" of type "{}" is not derived from ' '"click.BaseCommand"'.format( type(parser), module_path)) return parser
[ "def", "_load_module", "(", "self", ",", "module_path", ")", ":", "# __import__ will fail on unicode,", "# so we ensure module path is a string here.", "module_path", "=", "str", "(", "module_path", ")", "try", ":", "module_name", ",", "attr_name", "=", "module_path", "...
Load the module.
[ "Load", "the", "module", "." ]
ec76d15697ec80e51486a6e3daa0aec60b04870f
https://github.com/click-contrib/sphinx-click/blob/ec76d15697ec80e51486a6e3daa0aec60b04870f/sphinx_click/ext.py#L294-L329
26,940
joferkington/mpldatacursor
mpldatacursor/datacursor.py
DataCursor._show_annotation_box
def _show_annotation_box(self, event): """Update an existing box or create an annotation box for an event.""" ax = event.artist.axes # Get the pre-created annotation box for the axes or create a new one. if self.display != 'multiple': annotation = self.annotations[ax] elif event.mouseevent in self.annotations: # Avoid creating multiple datacursors for the same click event # when several artists are selected. annotation = self.annotations[event.mouseevent] else: annotation = self.annotate(ax, **self._annotation_kwargs) self.annotations[event.mouseevent] = annotation if self.display == 'single': # Hide any other annotation boxes... for ann in self.annotations.values(): ann.set_visible(False) self.update(event, annotation)
python
def _show_annotation_box(self, event): ax = event.artist.axes # Get the pre-created annotation box for the axes or create a new one. if self.display != 'multiple': annotation = self.annotations[ax] elif event.mouseevent in self.annotations: # Avoid creating multiple datacursors for the same click event # when several artists are selected. annotation = self.annotations[event.mouseevent] else: annotation = self.annotate(ax, **self._annotation_kwargs) self.annotations[event.mouseevent] = annotation if self.display == 'single': # Hide any other annotation boxes... for ann in self.annotations.values(): ann.set_visible(False) self.update(event, annotation)
[ "def", "_show_annotation_box", "(", "self", ",", "event", ")", ":", "ax", "=", "event", ".", "artist", ".", "axes", "# Get the pre-created annotation box for the axes or create a new one.", "if", "self", ".", "display", "!=", "'multiple'", ":", "annotation", "=", "s...
Update an existing box or create an annotation box for an event.
[ "Update", "an", "existing", "box", "or", "create", "an", "annotation", "box", "for", "an", "event", "." ]
7dabc589ed02c35ac5d89de5931f91e0323aa795
https://github.com/joferkington/mpldatacursor/blob/7dabc589ed02c35ac5d89de5931f91e0323aa795/mpldatacursor/datacursor.py#L256-L275
26,941
joferkington/mpldatacursor
mpldatacursor/datacursor.py
DataCursor.event_info
def event_info(self, event): """Get a dict of info for the artist selected by "event".""" def default_func(event): return {} registry = { AxesImage : [pick_info.image_props], PathCollection : [pick_info.scatter_props, self._contour_info, pick_info.collection_props], Line2D : [pick_info.line_props, pick_info.errorbar_props], LineCollection : [pick_info.collection_props, self._contour_info, pick_info.errorbar_props], PatchCollection : [pick_info.collection_props, self._contour_info], PolyCollection : [pick_info.collection_props, pick_info.scatter_props], QuadMesh : [pick_info.collection_props], Rectangle : [pick_info.rectangle_props], } x, y = event.mouseevent.xdata, event.mouseevent.ydata props = dict(x=x, y=y, label=event.artist.get_label(), event=event) props['ind'] = getattr(event, 'ind', None) props['point_label'] = self._point_label(event) funcs = registry.get(type(event.artist), [default_func]) # 3D artist don't share inheritance. Fall back to naming convention. if '3D' in type(event.artist).__name__: funcs += [pick_info.three_dim_props] for func in funcs: props.update(func(event)) return props
python
def event_info(self, event): def default_func(event): return {} registry = { AxesImage : [pick_info.image_props], PathCollection : [pick_info.scatter_props, self._contour_info, pick_info.collection_props], Line2D : [pick_info.line_props, pick_info.errorbar_props], LineCollection : [pick_info.collection_props, self._contour_info, pick_info.errorbar_props], PatchCollection : [pick_info.collection_props, self._contour_info], PolyCollection : [pick_info.collection_props, pick_info.scatter_props], QuadMesh : [pick_info.collection_props], Rectangle : [pick_info.rectangle_props], } x, y = event.mouseevent.xdata, event.mouseevent.ydata props = dict(x=x, y=y, label=event.artist.get_label(), event=event) props['ind'] = getattr(event, 'ind', None) props['point_label'] = self._point_label(event) funcs = registry.get(type(event.artist), [default_func]) # 3D artist don't share inheritance. Fall back to naming convention. if '3D' in type(event.artist).__name__: funcs += [pick_info.three_dim_props] for func in funcs: props.update(func(event)) return props
[ "def", "event_info", "(", "self", ",", "event", ")", ":", "def", "default_func", "(", "event", ")", ":", "return", "{", "}", "registry", "=", "{", "AxesImage", ":", "[", "pick_info", ".", "image_props", "]", ",", "PathCollection", ":", "[", "pick_info", ...
Get a dict of info for the artist selected by "event".
[ "Get", "a", "dict", "of", "info", "for", "the", "artist", "selected", "by", "event", "." ]
7dabc589ed02c35ac5d89de5931f91e0323aa795
https://github.com/joferkington/mpldatacursor/blob/7dabc589ed02c35ac5d89de5931f91e0323aa795/mpldatacursor/datacursor.py#L277-L310
26,942
joferkington/mpldatacursor
mpldatacursor/datacursor.py
DataCursor._formatter
def _formatter(self, x=None, y=None, z=None, s=None, label=None, **kwargs): """ Default formatter function, if no `formatter` kwarg is specified. Takes information about the pick event as a series of kwargs and returns the string to be displayed. """ def is_date(axis): fmt = axis.get_major_formatter() return (isinstance(fmt, mdates.DateFormatter) or isinstance(fmt, mdates.AutoDateFormatter)) def format_date(num): if num is not None: return mdates.num2date(num).strftime(self.date_format) ax = kwargs['event'].artist.axes # Display x and y with range-specific formatting if is_date(ax.xaxis): x = format_date(x) else: limits = ax.get_xlim() x = self._format_coord(x, limits) kwargs['xerror'] = self._format_coord(kwargs.get('xerror'), limits) if is_date(ax.yaxis): y = format_date(y) else: limits = ax.get_ylim() y = self._format_coord(y, limits) kwargs['yerror'] = self._format_coord(kwargs.get('yerror'), limits) output = [] for key, val in zip(['x', 'y', 'z', 's'], [x, y, z, s]): if val is not None: try: output.append(u'{key}: {val:0.3g}'.format(key=key, val=val)) except ValueError: # X & Y will be strings at this point. # For masked arrays, etc, "z" and s values may be a string output.append(u'{key}: {val}'.format(key=key, val=val)) # label may be None or an empty string (for an un-labeled AxesImage)... # Un-labeled Line2D's will have labels that start with an underscore if label and not label.startswith('_'): output.append(u'Label: {}'.format(label)) if kwargs.get(u'point_label', None) is not None: output.append(u'Point: ' + u', '.join(kwargs['point_label'])) for arg in ['xerror', 'yerror']: val = kwargs.get(arg, None) if val is not None: output.append(u'{}: {}'.format(arg, val)) return u'\n'.join(output)
python
def _formatter(self, x=None, y=None, z=None, s=None, label=None, **kwargs): def is_date(axis): fmt = axis.get_major_formatter() return (isinstance(fmt, mdates.DateFormatter) or isinstance(fmt, mdates.AutoDateFormatter)) def format_date(num): if num is not None: return mdates.num2date(num).strftime(self.date_format) ax = kwargs['event'].artist.axes # Display x and y with range-specific formatting if is_date(ax.xaxis): x = format_date(x) else: limits = ax.get_xlim() x = self._format_coord(x, limits) kwargs['xerror'] = self._format_coord(kwargs.get('xerror'), limits) if is_date(ax.yaxis): y = format_date(y) else: limits = ax.get_ylim() y = self._format_coord(y, limits) kwargs['yerror'] = self._format_coord(kwargs.get('yerror'), limits) output = [] for key, val in zip(['x', 'y', 'z', 's'], [x, y, z, s]): if val is not None: try: output.append(u'{key}: {val:0.3g}'.format(key=key, val=val)) except ValueError: # X & Y will be strings at this point. # For masked arrays, etc, "z" and s values may be a string output.append(u'{key}: {val}'.format(key=key, val=val)) # label may be None or an empty string (for an un-labeled AxesImage)... # Un-labeled Line2D's will have labels that start with an underscore if label and not label.startswith('_'): output.append(u'Label: {}'.format(label)) if kwargs.get(u'point_label', None) is not None: output.append(u'Point: ' + u', '.join(kwargs['point_label'])) for arg in ['xerror', 'yerror']: val = kwargs.get(arg, None) if val is not None: output.append(u'{}: {}'.format(arg, val)) return u'\n'.join(output)
[ "def", "_formatter", "(", "self", ",", "x", "=", "None", ",", "y", "=", "None", ",", "z", "=", "None", ",", "s", "=", "None", ",", "label", "=", "None", ",", "*", "*", "kwargs", ")", ":", "def", "is_date", "(", "axis", ")", ":", "fmt", "=", ...
Default formatter function, if no `formatter` kwarg is specified. Takes information about the pick event as a series of kwargs and returns the string to be displayed.
[ "Default", "formatter", "function", "if", "no", "formatter", "kwarg", "is", "specified", ".", "Takes", "information", "about", "the", "pick", "event", "as", "a", "series", "of", "kwargs", "and", "returns", "the", "string", "to", "be", "displayed", "." ]
7dabc589ed02c35ac5d89de5931f91e0323aa795
https://github.com/joferkington/mpldatacursor/blob/7dabc589ed02c35ac5d89de5931f91e0323aa795/mpldatacursor/datacursor.py#L327-L381
26,943
joferkington/mpldatacursor
mpldatacursor/datacursor.py
DataCursor._format_coord
def _format_coord(self, x, limits): """ Handles display-range-specific formatting for the x and y coords. Parameters ---------- x : number The number to be formatted limits : 2-item sequence The min and max of the current display limits for the axis. """ if x is None: return None formatter = self._mplformatter # Trick the formatter into thinking we have an axes # The 7 tick locations is arbitrary but gives a reasonable detail level formatter.locs = np.linspace(limits[0], limits[1], 7) formatter._set_format(*limits) formatter._set_orderOfMagnitude(abs(np.diff(limits))) return formatter.pprint_val(x)
python
def _format_coord(self, x, limits): if x is None: return None formatter = self._mplformatter # Trick the formatter into thinking we have an axes # The 7 tick locations is arbitrary but gives a reasonable detail level formatter.locs = np.linspace(limits[0], limits[1], 7) formatter._set_format(*limits) formatter._set_orderOfMagnitude(abs(np.diff(limits))) return formatter.pprint_val(x)
[ "def", "_format_coord", "(", "self", ",", "x", ",", "limits", ")", ":", "if", "x", "is", "None", ":", "return", "None", "formatter", "=", "self", ".", "_mplformatter", "# Trick the formatter into thinking we have an axes", "# The 7 tick locations is arbitrary but gives ...
Handles display-range-specific formatting for the x and y coords. Parameters ---------- x : number The number to be formatted limits : 2-item sequence The min and max of the current display limits for the axis.
[ "Handles", "display", "-", "range", "-", "specific", "formatting", "for", "the", "x", "and", "y", "coords", "." ]
7dabc589ed02c35ac5d89de5931f91e0323aa795
https://github.com/joferkington/mpldatacursor/blob/7dabc589ed02c35ac5d89de5931f91e0323aa795/mpldatacursor/datacursor.py#L383-L403
26,944
joferkington/mpldatacursor
mpldatacursor/datacursor.py
DataCursor._hide_box
def _hide_box(self, annotation): """Remove a specific annotation box.""" annotation.set_visible(False) if self.display == 'multiple': annotation.axes.figure.texts.remove(annotation) # Remove the annotation from self.annotations. lookup = dict((self.annotations[k], k) for k in self.annotations) del self.annotations[lookup[annotation]] annotation.figure.canvas.draw()
python
def _hide_box(self, annotation): annotation.set_visible(False) if self.display == 'multiple': annotation.axes.figure.texts.remove(annotation) # Remove the annotation from self.annotations. lookup = dict((self.annotations[k], k) for k in self.annotations) del self.annotations[lookup[annotation]] annotation.figure.canvas.draw()
[ "def", "_hide_box", "(", "self", ",", "annotation", ")", ":", "annotation", ".", "set_visible", "(", "False", ")", "if", "self", ".", "display", "==", "'multiple'", ":", "annotation", ".", "axes", ".", "figure", ".", "texts", ".", "remove", "(", "annotat...
Remove a specific annotation box.
[ "Remove", "a", "specific", "annotation", "box", "." ]
7dabc589ed02c35ac5d89de5931f91e0323aa795
https://github.com/joferkington/mpldatacursor/blob/7dabc589ed02c35ac5d89de5931f91e0323aa795/mpldatacursor/datacursor.py#L487-L497
26,945
joferkington/mpldatacursor
mpldatacursor/datacursor.py
DataCursor.enable
def enable(self): """Connects callbacks and makes artists pickable. If the datacursor has already been enabled, this function has no effect.""" def connect(fig): if self.hover: event = 'motion_notify_event' else: event = 'button_press_event' cids = [fig.canvas.mpl_connect(event, self._select)] # None of this should be necessary. Workaround for a bug in some # mpl versions try: proxy = fig.canvas.callbacks.BoundMethodProxy(self) fig.canvas.callbacks.callbacks[event][cids[-1]] = proxy except AttributeError: # In some versions of mpl, BoundMethodProxy doesn't exist... # See: https://github.com/joferkington/mpldatacursor/issues/2 pass return cids if not getattr(self, '_enabled', False): self._cids = [(fig, connect(fig)) for fig in self.figures] self._enabled = True try: # Newer versions of MPL use set_pickradius for artist in self.artists: artist.set_pickradius(self.tolerance) except AttributeError: # Older versions of MPL control pick radius through set_picker for artist in self.artists: artist.set_picker(self.tolerance) return self
python
def enable(self): def connect(fig): if self.hover: event = 'motion_notify_event' else: event = 'button_press_event' cids = [fig.canvas.mpl_connect(event, self._select)] # None of this should be necessary. Workaround for a bug in some # mpl versions try: proxy = fig.canvas.callbacks.BoundMethodProxy(self) fig.canvas.callbacks.callbacks[event][cids[-1]] = proxy except AttributeError: # In some versions of mpl, BoundMethodProxy doesn't exist... # See: https://github.com/joferkington/mpldatacursor/issues/2 pass return cids if not getattr(self, '_enabled', False): self._cids = [(fig, connect(fig)) for fig in self.figures] self._enabled = True try: # Newer versions of MPL use set_pickradius for artist in self.artists: artist.set_pickradius(self.tolerance) except AttributeError: # Older versions of MPL control pick radius through set_picker for artist in self.artists: artist.set_picker(self.tolerance) return self
[ "def", "enable", "(", "self", ")", ":", "def", "connect", "(", "fig", ")", ":", "if", "self", ".", "hover", ":", "event", "=", "'motion_notify_event'", "else", ":", "event", "=", "'button_press_event'", "cids", "=", "[", "fig", ".", "canvas", ".", "mpl...
Connects callbacks and makes artists pickable. If the datacursor has already been enabled, this function has no effect.
[ "Connects", "callbacks", "and", "makes", "artists", "pickable", ".", "If", "the", "datacursor", "has", "already", "been", "enabled", "this", "function", "has", "no", "effect", "." ]
7dabc589ed02c35ac5d89de5931f91e0323aa795
https://github.com/joferkington/mpldatacursor/blob/7dabc589ed02c35ac5d89de5931f91e0323aa795/mpldatacursor/datacursor.py#L513-L546
26,946
joferkington/mpldatacursor
mpldatacursor/datacursor.py
DataCursor._increment_index
def _increment_index(self, di=1): """ Move the most recently displayed annotation to the next item in the series, if possible. If ``di`` is -1, move it to the previous item. """ if self._last_event is None: return if not hasattr(self._last_event, 'ind'): return event = self._last_event xy = pick_info.get_xy(event.artist) if xy is not None: x, y = xy i = (event.ind[0] + di) % len(x) event.ind = [i] event.mouseevent.xdata = x[i] event.mouseevent.ydata = y[i] self.update(event, self._last_annotation)
python
def _increment_index(self, di=1): if self._last_event is None: return if not hasattr(self._last_event, 'ind'): return event = self._last_event xy = pick_info.get_xy(event.artist) if xy is not None: x, y = xy i = (event.ind[0] + di) % len(x) event.ind = [i] event.mouseevent.xdata = x[i] event.mouseevent.ydata = y[i] self.update(event, self._last_annotation)
[ "def", "_increment_index", "(", "self", ",", "di", "=", "1", ")", ":", "if", "self", ".", "_last_event", "is", "None", ":", "return", "if", "not", "hasattr", "(", "self", ".", "_last_event", ",", "'ind'", ")", ":", "return", "event", "=", "self", "."...
Move the most recently displayed annotation to the next item in the series, if possible. If ``di`` is -1, move it to the previous item.
[ "Move", "the", "most", "recently", "displayed", "annotation", "to", "the", "next", "item", "in", "the", "series", "if", "possible", ".", "If", "di", "is", "-", "1", "move", "it", "to", "the", "previous", "item", "." ]
7dabc589ed02c35ac5d89de5931f91e0323aa795
https://github.com/joferkington/mpldatacursor/blob/7dabc589ed02c35ac5d89de5931f91e0323aa795/mpldatacursor/datacursor.py#L635-L656
26,947
joferkington/mpldatacursor
mpldatacursor/datacursor.py
HighlightingDataCursor.show_highlight
def show_highlight(self, artist): """Show or create a highlight for a givent artist.""" # This is a separate method to make subclassing easier. if artist in self.highlights: self.highlights[artist].set_visible(True) else: self.highlights[artist] = self.create_highlight(artist) return self.highlights[artist]
python
def show_highlight(self, artist): # This is a separate method to make subclassing easier. if artist in self.highlights: self.highlights[artist].set_visible(True) else: self.highlights[artist] = self.create_highlight(artist) return self.highlights[artist]
[ "def", "show_highlight", "(", "self", ",", "artist", ")", ":", "# This is a separate method to make subclassing easier.", "if", "artist", "in", "self", ".", "highlights", ":", "self", ".", "highlights", "[", "artist", "]", ".", "set_visible", "(", "True", ")", "...
Show or create a highlight for a givent artist.
[ "Show", "or", "create", "a", "highlight", "for", "a", "givent", "artist", "." ]
7dabc589ed02c35ac5d89de5931f91e0323aa795
https://github.com/joferkington/mpldatacursor/blob/7dabc589ed02c35ac5d89de5931f91e0323aa795/mpldatacursor/datacursor.py#L755-L762
26,948
joferkington/mpldatacursor
mpldatacursor/datacursor.py
HighlightingDataCursor.create_highlight
def create_highlight(self, artist): """Create a new highlight for the given artist.""" highlight = copy.copy(artist) highlight.set(color=self.highlight_color, mec=self.highlight_color, lw=self.highlight_width, mew=self.highlight_width) artist.axes.add_artist(highlight) return highlight
python
def create_highlight(self, artist): highlight = copy.copy(artist) highlight.set(color=self.highlight_color, mec=self.highlight_color, lw=self.highlight_width, mew=self.highlight_width) artist.axes.add_artist(highlight) return highlight
[ "def", "create_highlight", "(", "self", ",", "artist", ")", ":", "highlight", "=", "copy", ".", "copy", "(", "artist", ")", "highlight", ".", "set", "(", "color", "=", "self", ".", "highlight_color", ",", "mec", "=", "self", ".", "highlight_color", ",", ...
Create a new highlight for the given artist.
[ "Create", "a", "new", "highlight", "for", "the", "given", "artist", "." ]
7dabc589ed02c35ac5d89de5931f91e0323aa795
https://github.com/joferkington/mpldatacursor/blob/7dabc589ed02c35ac5d89de5931f91e0323aa795/mpldatacursor/datacursor.py#L764-L770
26,949
joferkington/mpldatacursor
mpldatacursor/pick_info.py
_coords2index
def _coords2index(im, x, y, inverted=False): """ Converts data coordinates to index coordinates of the array. Parameters ----------- im : An AxesImage instance The image artist to operation on x : number The x-coordinate in data coordinates. y : number The y-coordinate in data coordinates. inverted : bool, optional If True, convert index to data coordinates instead of data coordinates to index. Returns -------- i, j : Index coordinates of the array associated with the image. """ xmin, xmax, ymin, ymax = im.get_extent() if im.origin == 'upper': ymin, ymax = ymax, ymin data_extent = mtransforms.Bbox([[ymin, xmin], [ymax, xmax]]) array_extent = mtransforms.Bbox([[0, 0], im.get_array().shape[:2]]) trans = mtransforms.BboxTransformFrom(data_extent) +\ mtransforms.BboxTransformTo(array_extent) if inverted: trans = trans.inverted() return trans.transform_point([y,x]).astype(int)
python
def _coords2index(im, x, y, inverted=False): xmin, xmax, ymin, ymax = im.get_extent() if im.origin == 'upper': ymin, ymax = ymax, ymin data_extent = mtransforms.Bbox([[ymin, xmin], [ymax, xmax]]) array_extent = mtransforms.Bbox([[0, 0], im.get_array().shape[:2]]) trans = mtransforms.BboxTransformFrom(data_extent) +\ mtransforms.BboxTransformTo(array_extent) if inverted: trans = trans.inverted() return trans.transform_point([y,x]).astype(int)
[ "def", "_coords2index", "(", "im", ",", "x", ",", "y", ",", "inverted", "=", "False", ")", ":", "xmin", ",", "xmax", ",", "ymin", ",", "ymax", "=", "im", ".", "get_extent", "(", ")", "if", "im", ".", "origin", "==", "'upper'", ":", "ymin", ",", ...
Converts data coordinates to index coordinates of the array. Parameters ----------- im : An AxesImage instance The image artist to operation on x : number The x-coordinate in data coordinates. y : number The y-coordinate in data coordinates. inverted : bool, optional If True, convert index to data coordinates instead of data coordinates to index. Returns -------- i, j : Index coordinates of the array associated with the image.
[ "Converts", "data", "coordinates", "to", "index", "coordinates", "of", "the", "array", "." ]
7dabc589ed02c35ac5d89de5931f91e0323aa795
https://github.com/joferkington/mpldatacursor/blob/7dabc589ed02c35ac5d89de5931f91e0323aa795/mpldatacursor/pick_info.py#L28-L59
26,950
joferkington/mpldatacursor
mpldatacursor/pick_info.py
_interleave
def _interleave(a, b): """Interleave arrays a and b; b may have multiple columns and must be shorter by 1. """ b = np.column_stack([b]) # Turn b into a column array. nx, ny = b.shape c = np.zeros((nx + 1, ny + 1)) c[:, 0] = a c[:-1, 1:] = b return c.ravel()[:-(c.shape[1] - 1)]
python
def _interleave(a, b): b = np.column_stack([b]) # Turn b into a column array. nx, ny = b.shape c = np.zeros((nx + 1, ny + 1)) c[:, 0] = a c[:-1, 1:] = b return c.ravel()[:-(c.shape[1] - 1)]
[ "def", "_interleave", "(", "a", ",", "b", ")", ":", "b", "=", "np", ".", "column_stack", "(", "[", "b", "]", ")", "# Turn b into a column array.", "nx", ",", "ny", "=", "b", ".", "shape", "c", "=", "np", ".", "zeros", "(", "(", "nx", "+", "1", ...
Interleave arrays a and b; b may have multiple columns and must be shorter by 1.
[ "Interleave", "arrays", "a", "and", "b", ";", "b", "may", "have", "multiple", "columns", "and", "must", "be", "shorter", "by", "1", "." ]
7dabc589ed02c35ac5d89de5931f91e0323aa795
https://github.com/joferkington/mpldatacursor/blob/7dabc589ed02c35ac5d89de5931f91e0323aa795/mpldatacursor/pick_info.py#L148-L157
26,951
joferkington/mpldatacursor
mpldatacursor/pick_info.py
three_dim_props
def three_dim_props(event): """ Get information for a pick event on a 3D artist. Parameters ----------- event : PickEvent The pick event to process Returns -------- A dict with keys: `x`: The estimated x-value of the click on the artist `y`: The estimated y-value of the click on the artist `z`: The estimated z-value of the click on the artist Notes ----- Based on mpl_toolkits.axes3d.Axes3D.format_coord Many thanks to Ben Root for pointing this out! """ ax = event.artist.axes if ax.M is None: return {} xd, yd = event.mouseevent.xdata, event.mouseevent.ydata p = (xd, yd) edges = ax.tunit_edges() ldists = [(mplot3d.proj3d.line2d_seg_dist(p0, p1, p), i) for \ i, (p0, p1) in enumerate(edges)] ldists.sort() # nearest edge edgei = ldists[0][1] p0, p1 = edges[edgei] # scale the z value to match x0, y0, z0 = p0 x1, y1, z1 = p1 d0 = np.hypot(x0-xd, y0-yd) d1 = np.hypot(x1-xd, y1-yd) dt = d0+d1 z = d1/dt * z0 + d0/dt * z1 x, y, z = mplot3d.proj3d.inv_transform(xd, yd, z, ax.M) return dict(x=x, y=y, z=z)
python
def three_dim_props(event): ax = event.artist.axes if ax.M is None: return {} xd, yd = event.mouseevent.xdata, event.mouseevent.ydata p = (xd, yd) edges = ax.tunit_edges() ldists = [(mplot3d.proj3d.line2d_seg_dist(p0, p1, p), i) for \ i, (p0, p1) in enumerate(edges)] ldists.sort() # nearest edge edgei = ldists[0][1] p0, p1 = edges[edgei] # scale the z value to match x0, y0, z0 = p0 x1, y1, z1 = p1 d0 = np.hypot(x0-xd, y0-yd) d1 = np.hypot(x1-xd, y1-yd) dt = d0+d1 z = d1/dt * z0 + d0/dt * z1 x, y, z = mplot3d.proj3d.inv_transform(xd, yd, z, ax.M) return dict(x=x, y=y, z=z)
[ "def", "three_dim_props", "(", "event", ")", ":", "ax", "=", "event", ".", "artist", ".", "axes", "if", "ax", ".", "M", "is", "None", ":", "return", "{", "}", "xd", ",", "yd", "=", "event", ".", "mouseevent", ".", "xdata", ",", "event", ".", "mou...
Get information for a pick event on a 3D artist. Parameters ----------- event : PickEvent The pick event to process Returns -------- A dict with keys: `x`: The estimated x-value of the click on the artist `y`: The estimated y-value of the click on the artist `z`: The estimated z-value of the click on the artist Notes ----- Based on mpl_toolkits.axes3d.Axes3D.format_coord Many thanks to Ben Root for pointing this out!
[ "Get", "information", "for", "a", "pick", "event", "on", "a", "3D", "artist", "." ]
7dabc589ed02c35ac5d89de5931f91e0323aa795
https://github.com/joferkington/mpldatacursor/blob/7dabc589ed02c35ac5d89de5931f91e0323aa795/mpldatacursor/pick_info.py#L268-L314
26,952
joferkington/mpldatacursor
mpldatacursor/pick_info.py
rectangle_props
def rectangle_props(event): """ Returns the width, height, left, and bottom of a rectangle artist. Parameters ----------- event : PickEvent The pick event to process Returns -------- A dict with keys: `width` : The width of the rectangle `height` : The height of the rectangle `left` : The minimum x-coordinate of the rectangle `right` : The maximum x-coordinate of the rectangle `bottom` : The minimum y-coordinate of the rectangle `top` : The maximum y-coordinate of the rectangle `xcenter` : The mean x-coordinate of the rectangle `ycenter` : The mean y-coordinate of the rectangle `label` : The label for the rectangle or None """ artist = event.artist width, height = artist.get_width(), artist.get_height() left, bottom = artist.xy right, top = left + width, bottom + height xcenter = left + 0.5 * width ycenter = bottom + 0.5 * height label = artist.get_label() if label is None or label.startswith('_nolegend'): try: label = artist._mpldatacursor_label except AttributeError: label = None return dict(width=width, height=height, left=left, bottom=bottom, label=label, right=right, top=top, xcenter=xcenter, ycenter=ycenter)
python
def rectangle_props(event): artist = event.artist width, height = artist.get_width(), artist.get_height() left, bottom = artist.xy right, top = left + width, bottom + height xcenter = left + 0.5 * width ycenter = bottom + 0.5 * height label = artist.get_label() if label is None or label.startswith('_nolegend'): try: label = artist._mpldatacursor_label except AttributeError: label = None return dict(width=width, height=height, left=left, bottom=bottom, label=label, right=right, top=top, xcenter=xcenter, ycenter=ycenter)
[ "def", "rectangle_props", "(", "event", ")", ":", "artist", "=", "event", ".", "artist", "width", ",", "height", "=", "artist", ".", "get_width", "(", ")", ",", "artist", ".", "get_height", "(", ")", "left", ",", "bottom", "=", "artist", ".", "xy", "...
Returns the width, height, left, and bottom of a rectangle artist. Parameters ----------- event : PickEvent The pick event to process Returns -------- A dict with keys: `width` : The width of the rectangle `height` : The height of the rectangle `left` : The minimum x-coordinate of the rectangle `right` : The maximum x-coordinate of the rectangle `bottom` : The minimum y-coordinate of the rectangle `top` : The maximum y-coordinate of the rectangle `xcenter` : The mean x-coordinate of the rectangle `ycenter` : The mean y-coordinate of the rectangle `label` : The label for the rectangle or None
[ "Returns", "the", "width", "height", "left", "and", "bottom", "of", "a", "rectangle", "artist", "." ]
7dabc589ed02c35ac5d89de5931f91e0323aa795
https://github.com/joferkington/mpldatacursor/blob/7dabc589ed02c35ac5d89de5931f91e0323aa795/mpldatacursor/pick_info.py#L316-L354
26,953
joferkington/mpldatacursor
mpldatacursor/pick_info.py
get_xy
def get_xy(artist): """ Attempts to get the x,y data for individual items subitems of the artist. Returns None if this is not possible. At present, this only supports Line2D's and basic collections. """ xy = None if hasattr(artist, 'get_offsets'): xy = artist.get_offsets().T elif hasattr(artist, 'get_xydata'): xy = artist.get_xydata().T return xy
python
def get_xy(artist): xy = None if hasattr(artist, 'get_offsets'): xy = artist.get_offsets().T elif hasattr(artist, 'get_xydata'): xy = artist.get_xydata().T return xy
[ "def", "get_xy", "(", "artist", ")", ":", "xy", "=", "None", "if", "hasattr", "(", "artist", ",", "'get_offsets'", ")", ":", "xy", "=", "artist", ".", "get_offsets", "(", ")", ".", "T", "elif", "hasattr", "(", "artist", ",", "'get_xydata'", ")", ":",...
Attempts to get the x,y data for individual items subitems of the artist. Returns None if this is not possible. At present, this only supports Line2D's and basic collections.
[ "Attempts", "to", "get", "the", "x", "y", "data", "for", "individual", "items", "subitems", "of", "the", "artist", ".", "Returns", "None", "if", "this", "is", "not", "possible", "." ]
7dabc589ed02c35ac5d89de5931f91e0323aa795
https://github.com/joferkington/mpldatacursor/blob/7dabc589ed02c35ac5d89de5931f91e0323aa795/mpldatacursor/pick_info.py#L356-L370
26,954
joferkington/mpldatacursor
mpldatacursor/convenience.py
datacursor
def datacursor(artists=None, axes=None, **kwargs): """ Create an interactive data cursor for the specified artists or specified axes. The data cursor displays information about a selected artist in a "popup" annotation box. If a specific sequence of artists is given, only the specified artists will be interactively selectable. Otherwise, all manually-plotted artists in *axes* will be used (*axes* defaults to all axes in all figures). Parameters ----------- artists : a matplotlib artist or sequence of artists, optional The artists to make selectable and display information for. If this is not specified, then all manually plotted artists in `axes` will be used. axes : a matplotlib axes of sequence of axes, optional The axes to selected artists from if a sequence of artists is not specified. If `axes` is not specified, then all available axes in all figures will be used. tolerance : number, optional The radius (in points) that the mouse click must be within to select the artist. Default: 5 points. formatter : callable, optional A function that accepts arbitrary kwargs and returns a string that will be displayed with annotate. Often, it is convienent to pass in the format method of a template string, e.g. ``formatter="{label}".format``. Keyword arguments passed in to the `formatter` function: `x`, `y` : floats The x and y data coordinates of the clicked point `event` : a matplotlib ``PickEvent`` The pick event that was fired (note that the selected artist can be accessed through ``event.artist``). `label` : string or None The legend label of the selected artist. `ind` : list of ints or None If the artist has "subitems" (e.g. points in a scatter or line plot), this will be a list of the item(s) that were clicked on. If the artist does not have "subitems", this will be None. Note that this is always a list, even when a single item is selected. Some selected artists may supply additional keyword arguments that are not always present, for example: `z` : number The "z" (usually color or array) value, if present. For an ``AxesImage`` (as created by ``imshow``), this will be the uninterpolated array value at the point clicked. For a ``PathCollection`` (as created by ``scatter``) this will be the "c" value if an array was passed to "c". `i`, `j` : ints The row, column indicies of the selected point for an ``AxesImage`` (as created by ``imshow``) `s` : number The size of the selected item in a ``PathCollection`` if a size array is specified. `c` : number The array value displayed as color for a ``PathCollection`` if a "c" array is specified (identical to "z"). `point_label` : list If `point_labels` is given when the data cursor is initialized and the artist has "subitems", this will be a list of the items of `point_labels` that correspond to the selected artists. Note that this is always a list, even when a single artist is selected. `width`, `height`, `top`, `bottom` : numbers The parameters for ``Rectangle`` artists (e.g. bar plots). point_labels : sequence or dict, optional For artists with "subitems" (e.g. Line2D's), the item(s) of `point_labels` corresponding to the selected "subitems" of the artist will be passed into the formatter function as the "point_label" kwarg. If a single sequence is given, it will be used for all artists with "subitems". Alternatively, a dict of artist:sequence pairs may be given to match an artist to the correct series of point labels. display : {"one-per-axes", "single", "multiple"}, optional Controls whether more than one annotation box will be shown. Default: "one-per-axes" draggable : boolean, optional Controls whether or not the annotation box will be interactively draggable to a new location after being displayed. Defaults to False. hover : boolean, optional If True, the datacursor will "pop up" when the mouse hovers over an artist. Defaults to False. Enabling hover also sets `display="single"` and `draggable=False`. props_override : function, optional If specified, this function customizes the parameters passed into the formatter function and the x, y location that the datacursor "pop up" "points" to. This is often useful to make the annotation "point" to a specific side or corner of an artist, regardless of the position clicked. The function is passed the same kwargs as the `formatter` function and is expected to return a dict with at least the keys "x" and "y" (and probably several others). Expected call signature: `props_dict = props_override(**kwargs)` keybindings : boolean or dict, optional By default, the keys "d" and "t" will be bound to deleting/hiding all annotation boxes and toggling interactivity for datacursors, respectively. If keybindings is False, the ability to hide/toggle datacursors interactively will be disabled. Alternatively, a dict of the form {'hide':'somekey', 'toggle':'somekey'} may specified to customize the keyboard shortcuts. date_format : string, optional The strftime-style formatting string for dates. Used only if the x or y axes have been set to display dates. Defaults to "%x %X". display_button: int, optional The mouse button that will triggers displaying an annotation box. Defaults to 1, for left-clicking. (Common options are 1:left-click, 2:middle-click, 3:right-click) hide_button: int or None, optional The mouse button that triggers hiding the selected annotation box. Defaults to 3, for right-clicking. (Common options are 1:left-click, 2:middle-click, 3:right-click, None:hiding disabled) keep_inside : boolean, optional Whether or not to adjust the x,y offset to keep the text box inside the figure. This option has no effect on draggable datacursors. Defaults to True. Note: Currently disabled on OSX and NbAgg/notebook backends. **kwargs : additional keyword arguments, optional Additional keyword arguments are passed on to annotate. Returns ------- dc : A ``mpldatacursor.DataCursor`` instance """ def plotted_artists(ax): artists = (ax.lines + ax.patches + ax.collections + ax.images + ax.containers) return artists # If no axes are specified, get all axes. if axes is None: managers = pylab_helpers.Gcf.get_all_fig_managers() figs = [manager.canvas.figure for manager in managers] axes = [ax for fig in figs for ax in fig.axes] if not cbook.iterable(axes): axes = [axes] # If no artists are specified, get all manually plotted artists in all of # the specified axes. if artists is None: artists = [artist for ax in axes for artist in plotted_artists(ax)] return DataCursor(artists, **kwargs)
python
def datacursor(artists=None, axes=None, **kwargs): def plotted_artists(ax): artists = (ax.lines + ax.patches + ax.collections + ax.images + ax.containers) return artists # If no axes are specified, get all axes. if axes is None: managers = pylab_helpers.Gcf.get_all_fig_managers() figs = [manager.canvas.figure for manager in managers] axes = [ax for fig in figs for ax in fig.axes] if not cbook.iterable(axes): axes = [axes] # If no artists are specified, get all manually plotted artists in all of # the specified axes. if artists is None: artists = [artist for ax in axes for artist in plotted_artists(ax)] return DataCursor(artists, **kwargs)
[ "def", "datacursor", "(", "artists", "=", "None", ",", "axes", "=", "None", ",", "*", "*", "kwargs", ")", ":", "def", "plotted_artists", "(", "ax", ")", ":", "artists", "=", "(", "ax", ".", "lines", "+", "ax", ".", "patches", "+", "ax", ".", "col...
Create an interactive data cursor for the specified artists or specified axes. The data cursor displays information about a selected artist in a "popup" annotation box. If a specific sequence of artists is given, only the specified artists will be interactively selectable. Otherwise, all manually-plotted artists in *axes* will be used (*axes* defaults to all axes in all figures). Parameters ----------- artists : a matplotlib artist or sequence of artists, optional The artists to make selectable and display information for. If this is not specified, then all manually plotted artists in `axes` will be used. axes : a matplotlib axes of sequence of axes, optional The axes to selected artists from if a sequence of artists is not specified. If `axes` is not specified, then all available axes in all figures will be used. tolerance : number, optional The radius (in points) that the mouse click must be within to select the artist. Default: 5 points. formatter : callable, optional A function that accepts arbitrary kwargs and returns a string that will be displayed with annotate. Often, it is convienent to pass in the format method of a template string, e.g. ``formatter="{label}".format``. Keyword arguments passed in to the `formatter` function: `x`, `y` : floats The x and y data coordinates of the clicked point `event` : a matplotlib ``PickEvent`` The pick event that was fired (note that the selected artist can be accessed through ``event.artist``). `label` : string or None The legend label of the selected artist. `ind` : list of ints or None If the artist has "subitems" (e.g. points in a scatter or line plot), this will be a list of the item(s) that were clicked on. If the artist does not have "subitems", this will be None. Note that this is always a list, even when a single item is selected. Some selected artists may supply additional keyword arguments that are not always present, for example: `z` : number The "z" (usually color or array) value, if present. For an ``AxesImage`` (as created by ``imshow``), this will be the uninterpolated array value at the point clicked. For a ``PathCollection`` (as created by ``scatter``) this will be the "c" value if an array was passed to "c". `i`, `j` : ints The row, column indicies of the selected point for an ``AxesImage`` (as created by ``imshow``) `s` : number The size of the selected item in a ``PathCollection`` if a size array is specified. `c` : number The array value displayed as color for a ``PathCollection`` if a "c" array is specified (identical to "z"). `point_label` : list If `point_labels` is given when the data cursor is initialized and the artist has "subitems", this will be a list of the items of `point_labels` that correspond to the selected artists. Note that this is always a list, even when a single artist is selected. `width`, `height`, `top`, `bottom` : numbers The parameters for ``Rectangle`` artists (e.g. bar plots). point_labels : sequence or dict, optional For artists with "subitems" (e.g. Line2D's), the item(s) of `point_labels` corresponding to the selected "subitems" of the artist will be passed into the formatter function as the "point_label" kwarg. If a single sequence is given, it will be used for all artists with "subitems". Alternatively, a dict of artist:sequence pairs may be given to match an artist to the correct series of point labels. display : {"one-per-axes", "single", "multiple"}, optional Controls whether more than one annotation box will be shown. Default: "one-per-axes" draggable : boolean, optional Controls whether or not the annotation box will be interactively draggable to a new location after being displayed. Defaults to False. hover : boolean, optional If True, the datacursor will "pop up" when the mouse hovers over an artist. Defaults to False. Enabling hover also sets `display="single"` and `draggable=False`. props_override : function, optional If specified, this function customizes the parameters passed into the formatter function and the x, y location that the datacursor "pop up" "points" to. This is often useful to make the annotation "point" to a specific side or corner of an artist, regardless of the position clicked. The function is passed the same kwargs as the `formatter` function and is expected to return a dict with at least the keys "x" and "y" (and probably several others). Expected call signature: `props_dict = props_override(**kwargs)` keybindings : boolean or dict, optional By default, the keys "d" and "t" will be bound to deleting/hiding all annotation boxes and toggling interactivity for datacursors, respectively. If keybindings is False, the ability to hide/toggle datacursors interactively will be disabled. Alternatively, a dict of the form {'hide':'somekey', 'toggle':'somekey'} may specified to customize the keyboard shortcuts. date_format : string, optional The strftime-style formatting string for dates. Used only if the x or y axes have been set to display dates. Defaults to "%x %X". display_button: int, optional The mouse button that will triggers displaying an annotation box. Defaults to 1, for left-clicking. (Common options are 1:left-click, 2:middle-click, 3:right-click) hide_button: int or None, optional The mouse button that triggers hiding the selected annotation box. Defaults to 3, for right-clicking. (Common options are 1:left-click, 2:middle-click, 3:right-click, None:hiding disabled) keep_inside : boolean, optional Whether or not to adjust the x,y offset to keep the text box inside the figure. This option has no effect on draggable datacursors. Defaults to True. Note: Currently disabled on OSX and NbAgg/notebook backends. **kwargs : additional keyword arguments, optional Additional keyword arguments are passed on to annotate. Returns ------- dc : A ``mpldatacursor.DataCursor`` instance
[ "Create", "an", "interactive", "data", "cursor", "for", "the", "specified", "artists", "or", "specified", "axes", ".", "The", "data", "cursor", "displays", "information", "about", "a", "selected", "artist", "in", "a", "popup", "annotation", "box", "." ]
7dabc589ed02c35ac5d89de5931f91e0323aa795
https://github.com/joferkington/mpldatacursor/blob/7dabc589ed02c35ac5d89de5931f91e0323aa795/mpldatacursor/convenience.py#L27-L168
26,955
ChristianKuehnel/btlewrap
btlewrap/pygatt.py
wrap_exception
def wrap_exception(func: Callable) -> Callable: """Decorator to wrap pygatt exceptions into BluetoothBackendException.""" try: # only do the wrapping if pygatt is installed. # otherwise it's pointless anyway from pygatt.backends.bgapi.exceptions import BGAPIError from pygatt.exceptions import NotConnectedError except ImportError: return func def _func_wrapper(*args, **kwargs): try: return func(*args, **kwargs) except BGAPIError as exception: raise BluetoothBackendException() from exception except NotConnectedError as exception: raise BluetoothBackendException() from exception return _func_wrapper
python
def wrap_exception(func: Callable) -> Callable: try: # only do the wrapping if pygatt is installed. # otherwise it's pointless anyway from pygatt.backends.bgapi.exceptions import BGAPIError from pygatt.exceptions import NotConnectedError except ImportError: return func def _func_wrapper(*args, **kwargs): try: return func(*args, **kwargs) except BGAPIError as exception: raise BluetoothBackendException() from exception except NotConnectedError as exception: raise BluetoothBackendException() from exception return _func_wrapper
[ "def", "wrap_exception", "(", "func", ":", "Callable", ")", "->", "Callable", ":", "try", ":", "# only do the wrapping if pygatt is installed.", "# otherwise it's pointless anyway", "from", "pygatt", ".", "backends", ".", "bgapi", ".", "exceptions", "import", "BGAPIErro...
Decorator to wrap pygatt exceptions into BluetoothBackendException.
[ "Decorator", "to", "wrap", "pygatt", "exceptions", "into", "BluetoothBackendException", "." ]
1b7aec934529dcf03f5ecdccd0b09c25c389974f
https://github.com/ChristianKuehnel/btlewrap/blob/1b7aec934529dcf03f5ecdccd0b09c25c389974f/btlewrap/pygatt.py#L9-L27
26,956
ChristianKuehnel/btlewrap
btlewrap/pygatt.py
PygattBackend.write_handle
def write_handle(self, handle: int, value: bytes): """Write a handle to the device.""" if not self.is_connected(): raise BluetoothBackendException('Not connected to device!') self._device.char_write_handle(handle, value, True) return True
python
def write_handle(self, handle: int, value: bytes): if not self.is_connected(): raise BluetoothBackendException('Not connected to device!') self._device.char_write_handle(handle, value, True) return True
[ "def", "write_handle", "(", "self", ",", "handle", ":", "int", ",", "value", ":", "bytes", ")", ":", "if", "not", "self", ".", "is_connected", "(", ")", ":", "raise", "BluetoothBackendException", "(", "'Not connected to device!'", ")", "self", ".", "_device"...
Write a handle to the device.
[ "Write", "a", "handle", "to", "the", "device", "." ]
1b7aec934529dcf03f5ecdccd0b09c25c389974f
https://github.com/ChristianKuehnel/btlewrap/blob/1b7aec934529dcf03f5ecdccd0b09c25c389974f/btlewrap/pygatt.py#L81-L86
26,957
ChristianKuehnel/btlewrap
btlewrap/bluepy.py
wrap_exception
def wrap_exception(func: Callable) -> Callable: """Decorator to wrap BTLEExceptions into BluetoothBackendException.""" try: # only do the wrapping if bluepy is installed. # otherwise it's pointless anyway from bluepy.btle import BTLEException except ImportError: return func def _func_wrapper(*args, **kwargs): error_count = 0 last_error = None while error_count < RETRY_LIMIT: try: return func(*args, **kwargs) except BTLEException as exception: error_count += 1 last_error = exception time.sleep(RETRY_DELAY) _LOGGER.debug('Call to %s failed, try %d of %d', func, error_count, RETRY_LIMIT) raise BluetoothBackendException() from last_error return _func_wrapper
python
def wrap_exception(func: Callable) -> Callable: try: # only do the wrapping if bluepy is installed. # otherwise it's pointless anyway from bluepy.btle import BTLEException except ImportError: return func def _func_wrapper(*args, **kwargs): error_count = 0 last_error = None while error_count < RETRY_LIMIT: try: return func(*args, **kwargs) except BTLEException as exception: error_count += 1 last_error = exception time.sleep(RETRY_DELAY) _LOGGER.debug('Call to %s failed, try %d of %d', func, error_count, RETRY_LIMIT) raise BluetoothBackendException() from last_error return _func_wrapper
[ "def", "wrap_exception", "(", "func", ":", "Callable", ")", "->", "Callable", ":", "try", ":", "# only do the wrapping if bluepy is installed.", "# otherwise it's pointless anyway", "from", "bluepy", ".", "btle", "import", "BTLEException", "except", "ImportError", ":", ...
Decorator to wrap BTLEExceptions into BluetoothBackendException.
[ "Decorator", "to", "wrap", "BTLEExceptions", "into", "BluetoothBackendException", "." ]
1b7aec934529dcf03f5ecdccd0b09c25c389974f
https://github.com/ChristianKuehnel/btlewrap/blob/1b7aec934529dcf03f5ecdccd0b09c25c389974f/btlewrap/bluepy.py#L13-L35
26,958
ChristianKuehnel/btlewrap
btlewrap/bluepy.py
BluepyBackend.write_handle
def write_handle(self, handle: int, value: bytes): """Write a handle from the device. You must be connected to do this. """ if self._peripheral is None: raise BluetoothBackendException('not connected to backend') return self._peripheral.writeCharacteristic(handle, value, True)
python
def write_handle(self, handle: int, value: bytes): if self._peripheral is None: raise BluetoothBackendException('not connected to backend') return self._peripheral.writeCharacteristic(handle, value, True)
[ "def", "write_handle", "(", "self", ",", "handle", ":", "int", ",", "value", ":", "bytes", ")", ":", "if", "self", ".", "_peripheral", "is", "None", ":", "raise", "BluetoothBackendException", "(", "'not connected to backend'", ")", "return", "self", ".", "_p...
Write a handle from the device. You must be connected to do this.
[ "Write", "a", "handle", "from", "the", "device", "." ]
1b7aec934529dcf03f5ecdccd0b09c25c389974f
https://github.com/ChristianKuehnel/btlewrap/blob/1b7aec934529dcf03f5ecdccd0b09c25c389974f/btlewrap/bluepy.py#L79-L86
26,959
ChristianKuehnel/btlewrap
btlewrap/bluepy.py
BluepyBackend.check_backend
def check_backend() -> bool: """Check if the backend is available.""" try: import bluepy.btle # noqa: F401 #pylint: disable=unused-import return True except ImportError as importerror: _LOGGER.error('bluepy not found: %s', str(importerror)) return False
python
def check_backend() -> bool: try: import bluepy.btle # noqa: F401 #pylint: disable=unused-import return True except ImportError as importerror: _LOGGER.error('bluepy not found: %s', str(importerror)) return False
[ "def", "check_backend", "(", ")", "->", "bool", ":", "try", ":", "import", "bluepy", ".", "btle", "# noqa: F401 #pylint: disable=unused-import", "return", "True", "except", "ImportError", "as", "importerror", ":", "_LOGGER", ".", "error", "(", "'bluepy not found: %s...
Check if the backend is available.
[ "Check", "if", "the", "backend", "is", "available", "." ]
1b7aec934529dcf03f5ecdccd0b09c25c389974f
https://github.com/ChristianKuehnel/btlewrap/blob/1b7aec934529dcf03f5ecdccd0b09c25c389974f/btlewrap/bluepy.py#L97-L104
26,960
ChristianKuehnel/btlewrap
btlewrap/bluepy.py
BluepyBackend.scan_for_devices
def scan_for_devices(timeout: float) -> List[Tuple[str, str]]: """Scan for bluetooth low energy devices. Note this must be run as root!""" from bluepy.btle import Scanner scanner = Scanner() result = [] for device in scanner.scan(timeout): result.append((device.addr, device.getValueText(9))) return result
python
def scan_for_devices(timeout: float) -> List[Tuple[str, str]]: from bluepy.btle import Scanner scanner = Scanner() result = [] for device in scanner.scan(timeout): result.append((device.addr, device.getValueText(9))) return result
[ "def", "scan_for_devices", "(", "timeout", ":", "float", ")", "->", "List", "[", "Tuple", "[", "str", ",", "str", "]", "]", ":", "from", "bluepy", ".", "btle", "import", "Scanner", "scanner", "=", "Scanner", "(", ")", "result", "=", "[", "]", "for", ...
Scan for bluetooth low energy devices. Note this must be run as root!
[ "Scan", "for", "bluetooth", "low", "energy", "devices", "." ]
1b7aec934529dcf03f5ecdccd0b09c25c389974f
https://github.com/ChristianKuehnel/btlewrap/blob/1b7aec934529dcf03f5ecdccd0b09c25c389974f/btlewrap/bluepy.py#L108-L118
26,961
ChristianKuehnel/btlewrap
btlewrap/gatttool.py
wrap_exception
def wrap_exception(func: Callable) -> Callable: """Wrap all IOErrors to BluetoothBackendException""" def _func_wrapper(*args, **kwargs): try: return func(*args, **kwargs) except IOError as exception: raise BluetoothBackendException() from exception return _func_wrapper
python
def wrap_exception(func: Callable) -> Callable: def _func_wrapper(*args, **kwargs): try: return func(*args, **kwargs) except IOError as exception: raise BluetoothBackendException() from exception return _func_wrapper
[ "def", "wrap_exception", "(", "func", ":", "Callable", ")", "->", "Callable", ":", "def", "_func_wrapper", "(", "*", "args", ",", "*", "*", "kwargs", ")", ":", "try", ":", "return", "func", "(", "*", "args", ",", "*", "*", "kwargs", ")", "except", ...
Wrap all IOErrors to BluetoothBackendException
[ "Wrap", "all", "IOErrors", "to", "BluetoothBackendException" ]
1b7aec934529dcf03f5ecdccd0b09c25c389974f
https://github.com/ChristianKuehnel/btlewrap/blob/1b7aec934529dcf03f5ecdccd0b09c25c389974f/btlewrap/gatttool.py#L19-L27
26,962
ChristianKuehnel/btlewrap
btlewrap/gatttool.py
GatttoolBackend.write_handle
def write_handle(self, handle: int, value: bytes): # noqa: C901 # pylint: disable=arguments-differ """Read from a BLE address. @param: mac - MAC address in format XX:XX:XX:XX:XX:XX @param: handle - BLE characteristics handle in format 0xXX @param: value - value to write to the given handle """ if not self.is_connected(): raise BluetoothBackendException('Not connected to any device.') attempt = 0 delay = 10 _LOGGER.debug("Enter write_ble (%s)", current_thread()) while attempt <= self.retries: cmd = "gatttool --device={} --addr-type={} --char-write-req -a {} -n {} --adapter={}".format( self._mac, self.address_type, self.byte_to_handle(handle), self.bytes_to_string(value), self.adapter) _LOGGER.debug("Running gatttool with a timeout of %d: %s", self.timeout, cmd) with Popen(cmd, shell=True, stdout=PIPE, stderr=PIPE, preexec_fn=os.setsid) as process: try: result = process.communicate(timeout=self.timeout)[0] _LOGGER.debug("Finished gatttool") except TimeoutExpired: # send signal to the process group os.killpg(process.pid, signal.SIGINT) result = process.communicate()[0] _LOGGER.debug("Killed hanging gatttool") result = result.decode("utf-8").strip(' \n\t') if "Write Request failed" in result: raise BluetoothBackendException('Error writing handle to sensor: {}'.format(result)) _LOGGER.debug("Got %s from gatttool", result) # Parse the output if "successfully" in result: _LOGGER.debug( "Exit write_ble with result (%s)", current_thread()) return True attempt += 1 _LOGGER.debug("Waiting for %s seconds before retrying", delay) if attempt < self.retries: time.sleep(delay) delay *= 2 raise BluetoothBackendException("Exit write_ble, no data ({})".format(current_thread()))
python
def write_handle(self, handle: int, value: bytes): # noqa: C901 # pylint: disable=arguments-differ if not self.is_connected(): raise BluetoothBackendException('Not connected to any device.') attempt = 0 delay = 10 _LOGGER.debug("Enter write_ble (%s)", current_thread()) while attempt <= self.retries: cmd = "gatttool --device={} --addr-type={} --char-write-req -a {} -n {} --adapter={}".format( self._mac, self.address_type, self.byte_to_handle(handle), self.bytes_to_string(value), self.adapter) _LOGGER.debug("Running gatttool with a timeout of %d: %s", self.timeout, cmd) with Popen(cmd, shell=True, stdout=PIPE, stderr=PIPE, preexec_fn=os.setsid) as process: try: result = process.communicate(timeout=self.timeout)[0] _LOGGER.debug("Finished gatttool") except TimeoutExpired: # send signal to the process group os.killpg(process.pid, signal.SIGINT) result = process.communicate()[0] _LOGGER.debug("Killed hanging gatttool") result = result.decode("utf-8").strip(' \n\t') if "Write Request failed" in result: raise BluetoothBackendException('Error writing handle to sensor: {}'.format(result)) _LOGGER.debug("Got %s from gatttool", result) # Parse the output if "successfully" in result: _LOGGER.debug( "Exit write_ble with result (%s)", current_thread()) return True attempt += 1 _LOGGER.debug("Waiting for %s seconds before retrying", delay) if attempt < self.retries: time.sleep(delay) delay *= 2 raise BluetoothBackendException("Exit write_ble, no data ({})".format(current_thread()))
[ "def", "write_handle", "(", "self", ",", "handle", ":", "int", ",", "value", ":", "bytes", ")", ":", "# noqa: C901", "# pylint: disable=arguments-differ", "if", "not", "self", ".", "is_connected", "(", ")", ":", "raise", "BluetoothBackendException", "(", "'Not c...
Read from a BLE address. @param: mac - MAC address in format XX:XX:XX:XX:XX:XX @param: handle - BLE characteristics handle in format 0xXX @param: value - value to write to the given handle
[ "Read", "from", "a", "BLE", "address", "." ]
1b7aec934529dcf03f5ecdccd0b09c25c389974f
https://github.com/ChristianKuehnel/btlewrap/blob/1b7aec934529dcf03f5ecdccd0b09c25c389974f/btlewrap/gatttool.py#L62-L116
26,963
ChristianKuehnel/btlewrap
btlewrap/gatttool.py
GatttoolBackend.wait_for_notification
def wait_for_notification(self, handle: int, delegate, notification_timeout: float): """Listen for characteristics changes from a BLE address. @param: mac - MAC address in format XX:XX:XX:XX:XX:XX @param: handle - BLE characteristics handle in format 0xXX a value of 0x0100 is written to register for listening @param: delegate - gatttool receives the --listen argument and the delegate object's handleNotification is called for every returned row @param: notification_timeout """ if not self.is_connected(): raise BluetoothBackendException('Not connected to any device.') attempt = 0 delay = 10 _LOGGER.debug("Enter write_ble (%s)", current_thread()) while attempt <= self.retries: cmd = "gatttool --device={} --addr-type={} --char-write-req -a {} -n {} --adapter={} --listen".format( self._mac, self.address_type, self.byte_to_handle(handle), self.bytes_to_string(self._DATA_MODE_LISTEN), self.adapter) _LOGGER.debug("Running gatttool with a timeout of %d: %s", notification_timeout, cmd) with Popen(cmd, shell=True, stdout=PIPE, stderr=PIPE, preexec_fn=os.setsid) as process: try: result = process.communicate(timeout=notification_timeout)[0] _LOGGER.debug("Finished gatttool") except TimeoutExpired: # send signal to the process group, because listening always hangs os.killpg(process.pid, signal.SIGINT) result = process.communicate()[0] _LOGGER.debug("Listening stopped forcefully after timeout.") result = result.decode("utf-8").strip(' \n\t') if "Write Request failed" in result: raise BluetoothBackendException('Error writing handle to sensor: {}'.format(result)) _LOGGER.debug("Got %s from gatttool", result) # Parse the output to determine success if "successfully" in result: _LOGGER.debug("Exit write_ble with result (%s)", current_thread()) # extract useful data. for element in self.extract_notification_payload(result): delegate.handleNotification(handle, bytes([int(x, 16) for x in element.split()])) return True attempt += 1 _LOGGER.debug("Waiting for %s seconds before retrying", delay) if attempt < self.retries: time.sleep(delay) delay *= 2 raise BluetoothBackendException("Exit write_ble, no data ({})".format(current_thread()))
python
def wait_for_notification(self, handle: int, delegate, notification_timeout: float): if not self.is_connected(): raise BluetoothBackendException('Not connected to any device.') attempt = 0 delay = 10 _LOGGER.debug("Enter write_ble (%s)", current_thread()) while attempt <= self.retries: cmd = "gatttool --device={} --addr-type={} --char-write-req -a {} -n {} --adapter={} --listen".format( self._mac, self.address_type, self.byte_to_handle(handle), self.bytes_to_string(self._DATA_MODE_LISTEN), self.adapter) _LOGGER.debug("Running gatttool with a timeout of %d: %s", notification_timeout, cmd) with Popen(cmd, shell=True, stdout=PIPE, stderr=PIPE, preexec_fn=os.setsid) as process: try: result = process.communicate(timeout=notification_timeout)[0] _LOGGER.debug("Finished gatttool") except TimeoutExpired: # send signal to the process group, because listening always hangs os.killpg(process.pid, signal.SIGINT) result = process.communicate()[0] _LOGGER.debug("Listening stopped forcefully after timeout.") result = result.decode("utf-8").strip(' \n\t') if "Write Request failed" in result: raise BluetoothBackendException('Error writing handle to sensor: {}'.format(result)) _LOGGER.debug("Got %s from gatttool", result) # Parse the output to determine success if "successfully" in result: _LOGGER.debug("Exit write_ble with result (%s)", current_thread()) # extract useful data. for element in self.extract_notification_payload(result): delegate.handleNotification(handle, bytes([int(x, 16) for x in element.split()])) return True attempt += 1 _LOGGER.debug("Waiting for %s seconds before retrying", delay) if attempt < self.retries: time.sleep(delay) delay *= 2 raise BluetoothBackendException("Exit write_ble, no data ({})".format(current_thread()))
[ "def", "wait_for_notification", "(", "self", ",", "handle", ":", "int", ",", "delegate", ",", "notification_timeout", ":", "float", ")", ":", "if", "not", "self", ".", "is_connected", "(", ")", ":", "raise", "BluetoothBackendException", "(", "'Not connected to a...
Listen for characteristics changes from a BLE address. @param: mac - MAC address in format XX:XX:XX:XX:XX:XX @param: handle - BLE characteristics handle in format 0xXX a value of 0x0100 is written to register for listening @param: delegate - gatttool receives the --listen argument and the delegate object's handleNotification is called for every returned row @param: notification_timeout
[ "Listen", "for", "characteristics", "changes", "from", "a", "BLE", "address", "." ]
1b7aec934529dcf03f5ecdccd0b09c25c389974f
https://github.com/ChristianKuehnel/btlewrap/blob/1b7aec934529dcf03f5ecdccd0b09c25c389974f/btlewrap/gatttool.py#L119-L176
26,964
ChristianKuehnel/btlewrap
btlewrap/gatttool.py
GatttoolBackend.check_backend
def check_backend() -> bool: """Check if gatttool is available on the system.""" try: call('gatttool', stdout=PIPE, stderr=PIPE) return True except OSError as os_err: msg = 'gatttool not found: {}'.format(str(os_err)) _LOGGER.error(msg) return False
python
def check_backend() -> bool: try: call('gatttool', stdout=PIPE, stderr=PIPE) return True except OSError as os_err: msg = 'gatttool not found: {}'.format(str(os_err)) _LOGGER.error(msg) return False
[ "def", "check_backend", "(", ")", "->", "bool", ":", "try", ":", "call", "(", "'gatttool'", ",", "stdout", "=", "PIPE", ",", "stderr", "=", "PIPE", ")", "return", "True", "except", "OSError", "as", "os_err", ":", "msg", "=", "'gatttool not found: {}'", "...
Check if gatttool is available on the system.
[ "Check", "if", "gatttool", "is", "available", "on", "the", "system", "." ]
1b7aec934529dcf03f5ecdccd0b09c25c389974f
https://github.com/ChristianKuehnel/btlewrap/blob/1b7aec934529dcf03f5ecdccd0b09c25c389974f/btlewrap/gatttool.py#L260-L268
26,965
ChristianKuehnel/btlewrap
btlewrap/gatttool.py
GatttoolBackend.bytes_to_string
def bytes_to_string(raw_data: bytes, prefix: bool = False) -> str: """Convert a byte array to a hex string.""" prefix_string = '' if prefix: prefix_string = '0x' suffix = ''.join([format(c, "02x") for c in raw_data]) return prefix_string + suffix.upper()
python
def bytes_to_string(raw_data: bytes, prefix: bool = False) -> str: prefix_string = '' if prefix: prefix_string = '0x' suffix = ''.join([format(c, "02x") for c in raw_data]) return prefix_string + suffix.upper()
[ "def", "bytes_to_string", "(", "raw_data", ":", "bytes", ",", "prefix", ":", "bool", "=", "False", ")", "->", "str", ":", "prefix_string", "=", "''", "if", "prefix", ":", "prefix_string", "=", "'0x'", "suffix", "=", "''", ".", "join", "(", "[", "format...
Convert a byte array to a hex string.
[ "Convert", "a", "byte", "array", "to", "a", "hex", "string", "." ]
1b7aec934529dcf03f5ecdccd0b09c25c389974f
https://github.com/ChristianKuehnel/btlewrap/blob/1b7aec934529dcf03f5ecdccd0b09c25c389974f/btlewrap/gatttool.py#L276-L282
26,966
datacamp/antlr-ast
antlr_ast/marshalling.py
decode_ast
def decode_ast(registry, ast_json): """JSON decoder for BaseNodes""" if ast_json.get("@type"): subclass = registry.get_cls(ast_json["@type"], tuple(ast_json["@fields"])) return subclass( ast_json["children"], ast_json["field_references"], ast_json["label_references"], position=ast_json["@position"], ) else: return ast_json
python
def decode_ast(registry, ast_json): if ast_json.get("@type"): subclass = registry.get_cls(ast_json["@type"], tuple(ast_json["@fields"])) return subclass( ast_json["children"], ast_json["field_references"], ast_json["label_references"], position=ast_json["@position"], ) else: return ast_json
[ "def", "decode_ast", "(", "registry", ",", "ast_json", ")", ":", "if", "ast_json", ".", "get", "(", "\"@type\"", ")", ":", "subclass", "=", "registry", ".", "get_cls", "(", "ast_json", "[", "\"@type\"", "]", ",", "tuple", "(", "ast_json", "[", "\"@fields...
JSON decoder for BaseNodes
[ "JSON", "decoder", "for", "BaseNodes" ]
d08d5eb2e663bd40501d0eeddc8a731ac7e96b11
https://github.com/datacamp/antlr-ast/blob/d08d5eb2e663bd40501d0eeddc8a731ac7e96b11/antlr_ast/marshalling.py#L27-L38
26,967
datacamp/antlr-ast
antlr_ast/ast.py
simplify_tree
def simplify_tree(tree, unpack_lists=True, in_list=False): """Recursively unpack single-item lists and objects where fields and labels only reference a single child :param tree: the tree to simplify (mutating!) :param unpack_lists: whether single-item lists should be replaced by that item :param in_list: this is used to prevent unpacking a node in a list as AST visit can't handle nested lists """ # TODO: copy (or (de)serialize)? outside this function? if isinstance(tree, BaseNode) and not isinstance(tree, Terminal): used_fields = [field for field in tree._fields if getattr(tree, field, False)] if len(used_fields) == 1: result = getattr(tree, used_fields[0]) else: result = None if ( len(used_fields) != 1 or isinstance(tree, AliasNode) or (in_list and isinstance(result, list)) ): result = tree for field in tree._fields: old_value = getattr(tree, field, None) if old_value: setattr( result, field, simplify_tree(old_value, unpack_lists=unpack_lists), ) return result assert result is not None elif isinstance(tree, list) and len(tree) == 1 and unpack_lists: result = tree[0] else: if isinstance(tree, list): result = [ simplify_tree(el, unpack_lists=unpack_lists, in_list=True) for el in tree ] else: result = tree return result return simplify_tree(result, unpack_lists=unpack_lists)
python
def simplify_tree(tree, unpack_lists=True, in_list=False): # TODO: copy (or (de)serialize)? outside this function? if isinstance(tree, BaseNode) and not isinstance(tree, Terminal): used_fields = [field for field in tree._fields if getattr(tree, field, False)] if len(used_fields) == 1: result = getattr(tree, used_fields[0]) else: result = None if ( len(used_fields) != 1 or isinstance(tree, AliasNode) or (in_list and isinstance(result, list)) ): result = tree for field in tree._fields: old_value = getattr(tree, field, None) if old_value: setattr( result, field, simplify_tree(old_value, unpack_lists=unpack_lists), ) return result assert result is not None elif isinstance(tree, list) and len(tree) == 1 and unpack_lists: result = tree[0] else: if isinstance(tree, list): result = [ simplify_tree(el, unpack_lists=unpack_lists, in_list=True) for el in tree ] else: result = tree return result return simplify_tree(result, unpack_lists=unpack_lists)
[ "def", "simplify_tree", "(", "tree", ",", "unpack_lists", "=", "True", ",", "in_list", "=", "False", ")", ":", "# TODO: copy (or (de)serialize)? outside this function?", "if", "isinstance", "(", "tree", ",", "BaseNode", ")", "and", "not", "isinstance", "(", "tree"...
Recursively unpack single-item lists and objects where fields and labels only reference a single child :param tree: the tree to simplify (mutating!) :param unpack_lists: whether single-item lists should be replaced by that item :param in_list: this is used to prevent unpacking a node in a list as AST visit can't handle nested lists
[ "Recursively", "unpack", "single", "-", "item", "lists", "and", "objects", "where", "fields", "and", "labels", "only", "reference", "a", "single", "child" ]
d08d5eb2e663bd40501d0eeddc8a731ac7e96b11
https://github.com/datacamp/antlr-ast/blob/d08d5eb2e663bd40501d0eeddc8a731ac7e96b11/antlr_ast/ast.py#L521-L563
26,968
datacamp/antlr-ast
antlr_ast/ast.py
get_field
def get_field(ctx, field): """Helper to get the value of a field""" # field can be a string or a node attribute if isinstance(field, str): field = getattr(ctx, field, None) # when not alias needs to be called if callable(field): field = field() # when alias set on token, need to go from CommonToken -> Terminal Node elif isinstance(field, CommonToken): # giving a name to lexer rules sets it to a token, # rather than the terminal node corresponding to that token # so we need to find it in children field = next( filter(lambda c: getattr(c, "symbol", None) is field, ctx.children) ) return field
python
def get_field(ctx, field): # field can be a string or a node attribute if isinstance(field, str): field = getattr(ctx, field, None) # when not alias needs to be called if callable(field): field = field() # when alias set on token, need to go from CommonToken -> Terminal Node elif isinstance(field, CommonToken): # giving a name to lexer rules sets it to a token, # rather than the terminal node corresponding to that token # so we need to find it in children field = next( filter(lambda c: getattr(c, "symbol", None) is field, ctx.children) ) return field
[ "def", "get_field", "(", "ctx", ",", "field", ")", ":", "# field can be a string or a node attribute", "if", "isinstance", "(", "field", ",", "str", ")", ":", "field", "=", "getattr", "(", "ctx", ",", "field", ",", "None", ")", "# when not alias needs to be call...
Helper to get the value of a field
[ "Helper", "to", "get", "the", "value", "of", "a", "field" ]
d08d5eb2e663bd40501d0eeddc8a731ac7e96b11
https://github.com/datacamp/antlr-ast/blob/d08d5eb2e663bd40501d0eeddc8a731ac7e96b11/antlr_ast/ast.py#L641-L657
26,969
datacamp/antlr-ast
antlr_ast/ast.py
get_field_names
def get_field_names(ctx): """Get fields defined in an ANTLR context for a parser rule""" # this does not include labels and literals, only rule names and token names # TODO: check ANTLR parser template for full exclusion list fields = [ field for field in type(ctx).__dict__ if not field.startswith("__") and field not in ["accept", "enterRule", "exitRule", "getRuleIndex", "copyFrom"] ] return fields
python
def get_field_names(ctx): # this does not include labels and literals, only rule names and token names # TODO: check ANTLR parser template for full exclusion list fields = [ field for field in type(ctx).__dict__ if not field.startswith("__") and field not in ["accept", "enterRule", "exitRule", "getRuleIndex", "copyFrom"] ] return fields
[ "def", "get_field_names", "(", "ctx", ")", ":", "# this does not include labels and literals, only rule names and token names", "# TODO: check ANTLR parser template for full exclusion list", "fields", "=", "[", "field", "for", "field", "in", "type", "(", "ctx", ")", ".", "__d...
Get fields defined in an ANTLR context for a parser rule
[ "Get", "fields", "defined", "in", "an", "ANTLR", "context", "for", "a", "parser", "rule" ]
d08d5eb2e663bd40501d0eeddc8a731ac7e96b11
https://github.com/datacamp/antlr-ast/blob/d08d5eb2e663bd40501d0eeddc8a731ac7e96b11/antlr_ast/ast.py#L707-L717
26,970
datacamp/antlr-ast
antlr_ast/ast.py
get_label_names
def get_label_names(ctx): """Get labels defined in an ANTLR context for a parser rule""" labels = [ label for label in ctx.__dict__ if not label.startswith("_") and label not in [ "children", "exception", "invokingState", "parentCtx", "parser", "start", "stop", ] ] return labels
python
def get_label_names(ctx): labels = [ label for label in ctx.__dict__ if not label.startswith("_") and label not in [ "children", "exception", "invokingState", "parentCtx", "parser", "start", "stop", ] ] return labels
[ "def", "get_label_names", "(", "ctx", ")", ":", "labels", "=", "[", "label", "for", "label", "in", "ctx", ".", "__dict__", "if", "not", "label", ".", "startswith", "(", "\"_\"", ")", "and", "label", "not", "in", "[", "\"children\"", ",", "\"exception\"",...
Get labels defined in an ANTLR context for a parser rule
[ "Get", "labels", "defined", "in", "an", "ANTLR", "context", "for", "a", "parser", "rule" ]
d08d5eb2e663bd40501d0eeddc8a731ac7e96b11
https://github.com/datacamp/antlr-ast/blob/d08d5eb2e663bd40501d0eeddc8a731ac7e96b11/antlr_ast/ast.py#L720-L737
26,971
datacamp/antlr-ast
antlr_ast/ast.py
Speaker.get_info
def get_info(node_cfg): """Return a tuple with the verbal name of a node, and a dict of field names.""" node_cfg = node_cfg if isinstance(node_cfg, dict) else {"name": node_cfg} return node_cfg.get("name"), node_cfg.get("fields", {})
python
def get_info(node_cfg): node_cfg = node_cfg if isinstance(node_cfg, dict) else {"name": node_cfg} return node_cfg.get("name"), node_cfg.get("fields", {})
[ "def", "get_info", "(", "node_cfg", ")", ":", "node_cfg", "=", "node_cfg", "if", "isinstance", "(", "node_cfg", ",", "dict", ")", "else", "{", "\"name\"", ":", "node_cfg", "}", "return", "node_cfg", ".", "get", "(", "\"name\"", ")", ",", "node_cfg", ".",...
Return a tuple with the verbal name of a node, and a dict of field names.
[ "Return", "a", "tuple", "with", "the", "verbal", "name", "of", "a", "node", "and", "a", "dict", "of", "field", "names", "." ]
d08d5eb2e663bd40501d0eeddc8a731ac7e96b11
https://github.com/datacamp/antlr-ast/blob/d08d5eb2e663bd40501d0eeddc8a731ac7e96b11/antlr_ast/ast.py#L143-L148
26,972
datacamp/antlr-ast
antlr_ast/ast.py
BaseNodeRegistry.isinstance
def isinstance(self, instance, class_name): """Check if a BaseNode is an instance of a registered dynamic class""" if isinstance(instance, BaseNode): klass = self.dynamic_node_classes.get(class_name, None) if klass: return isinstance(instance, klass) # Not an instance of a class in the registry return False else: raise TypeError("This function can only be used for BaseNode objects")
python
def isinstance(self, instance, class_name): if isinstance(instance, BaseNode): klass = self.dynamic_node_classes.get(class_name, None) if klass: return isinstance(instance, klass) # Not an instance of a class in the registry return False else: raise TypeError("This function can only be used for BaseNode objects")
[ "def", "isinstance", "(", "self", ",", "instance", ",", "class_name", ")", ":", "if", "isinstance", "(", "instance", ",", "BaseNode", ")", ":", "klass", "=", "self", ".", "dynamic_node_classes", ".", "get", "(", "class_name", ",", "None", ")", "if", "kla...
Check if a BaseNode is an instance of a registered dynamic class
[ "Check", "if", "a", "BaseNode", "is", "an", "instance", "of", "a", "registered", "dynamic", "class" ]
d08d5eb2e663bd40501d0eeddc8a731ac7e96b11
https://github.com/datacamp/antlr-ast/blob/d08d5eb2e663bd40501d0eeddc8a731ac7e96b11/antlr_ast/ast.py#L207-L216
26,973
datacamp/antlr-ast
antlr_ast/ast.py
AliasNode.get_transformer
def get_transformer(cls, method_name): """Get method to bind to visitor""" transform_function = getattr(cls, method_name) assert callable(transform_function) def transformer_method(self, node): kwargs = {} if inspect.signature(transform_function).parameters.get("helper"): kwargs["helper"] = self.helper return transform_function(node, **kwargs) return transformer_method
python
def get_transformer(cls, method_name): transform_function = getattr(cls, method_name) assert callable(transform_function) def transformer_method(self, node): kwargs = {} if inspect.signature(transform_function).parameters.get("helper"): kwargs["helper"] = self.helper return transform_function(node, **kwargs) return transformer_method
[ "def", "get_transformer", "(", "cls", ",", "method_name", ")", ":", "transform_function", "=", "getattr", "(", "cls", ",", "method_name", ")", "assert", "callable", "(", "transform_function", ")", "def", "transformer_method", "(", "self", ",", "node", ")", ":"...
Get method to bind to visitor
[ "Get", "method", "to", "bind", "to", "visitor" ]
d08d5eb2e663bd40501d0eeddc8a731ac7e96b11
https://github.com/datacamp/antlr-ast/blob/d08d5eb2e663bd40501d0eeddc8a731ac7e96b11/antlr_ast/ast.py#L445-L456
26,974
datacamp/antlr-ast
antlr_ast/ast.py
BaseAstVisitor.visitTerminal
def visitTerminal(self, ctx): """Converts case insensitive keywords and identifiers to lowercase""" text = ctx.getText() return Terminal.from_text(text, ctx)
python
def visitTerminal(self, ctx): text = ctx.getText() return Terminal.from_text(text, ctx)
[ "def", "visitTerminal", "(", "self", ",", "ctx", ")", ":", "text", "=", "ctx", ".", "getText", "(", ")", "return", "Terminal", ".", "from_text", "(", "text", ",", "ctx", ")" ]
Converts case insensitive keywords and identifiers to lowercase
[ "Converts", "case", "insensitive", "keywords", "and", "identifiers", "to", "lowercase" ]
d08d5eb2e663bd40501d0eeddc8a731ac7e96b11
https://github.com/datacamp/antlr-ast/blob/d08d5eb2e663bd40501d0eeddc8a731ac7e96b11/antlr_ast/ast.py#L629-L632
26,975
chaoss/grimoirelab-sortinghat
sortinghat/cmd/blacklist.py
Blacklist.run
def run(self, *args): """List, add or delete entries from the blacklist. By default, it prints the list of entries available on the blacklist. """ params = self.parser.parse_args(args) entry = params.entry if params.add: code = self.add(entry) elif params.delete: code = self.delete(entry) else: term = entry code = self.blacklist(term) return code
python
def run(self, *args): params = self.parser.parse_args(args) entry = params.entry if params.add: code = self.add(entry) elif params.delete: code = self.delete(entry) else: term = entry code = self.blacklist(term) return code
[ "def", "run", "(", "self", ",", "*", "args", ")", ":", "params", "=", "self", ".", "parser", ".", "parse_args", "(", "args", ")", "entry", "=", "params", ".", "entry", "if", "params", ".", "add", ":", "code", "=", "self", ".", "add", "(", "entry"...
List, add or delete entries from the blacklist. By default, it prints the list of entries available on the blacklist.
[ "List", "add", "or", "delete", "entries", "from", "the", "blacklist", "." ]
391cd37a75fea26311dc6908bc1c953c540a8e04
https://github.com/chaoss/grimoirelab-sortinghat/blob/391cd37a75fea26311dc6908bc1c953c540a8e04/sortinghat/cmd/blacklist.py#L80-L98
26,976
chaoss/grimoirelab-sortinghat
sortinghat/cmd/blacklist.py
Blacklist.add
def add(self, entry): """Add entries to the blacklist. This method adds the given 'entry' to the blacklist. :param entry: entry to add to the blacklist """ # Empty or None values for organizations are not allowed if not entry: return CMD_SUCCESS try: api.add_to_matching_blacklist(self.db, entry) except InvalidValueError as e: # If the code reaches here, something really wrong has happened # because entry cannot be None or empty raise RuntimeError(str(e)) except AlreadyExistsError as e: msg = "%s already exists in the registry" % entry self.error(msg) return e.code return CMD_SUCCESS
python
def add(self, entry): # Empty or None values for organizations are not allowed if not entry: return CMD_SUCCESS try: api.add_to_matching_blacklist(self.db, entry) except InvalidValueError as e: # If the code reaches here, something really wrong has happened # because entry cannot be None or empty raise RuntimeError(str(e)) except AlreadyExistsError as e: msg = "%s already exists in the registry" % entry self.error(msg) return e.code return CMD_SUCCESS
[ "def", "add", "(", "self", ",", "entry", ")", ":", "# Empty or None values for organizations are not allowed", "if", "not", "entry", ":", "return", "CMD_SUCCESS", "try", ":", "api", ".", "add_to_matching_blacklist", "(", "self", ".", "db", ",", "entry", ")", "ex...
Add entries to the blacklist. This method adds the given 'entry' to the blacklist. :param entry: entry to add to the blacklist
[ "Add", "entries", "to", "the", "blacklist", "." ]
391cd37a75fea26311dc6908bc1c953c540a8e04
https://github.com/chaoss/grimoirelab-sortinghat/blob/391cd37a75fea26311dc6908bc1c953c540a8e04/sortinghat/cmd/blacklist.py#L100-L122
26,977
chaoss/grimoirelab-sortinghat
sortinghat/cmd/blacklist.py
Blacklist.delete
def delete(self, entry): """Remove entries from the blacklist. The method removes the given 'entry' from the blacklist. :param entry: entry to remove from the blacklist """ if not entry: return CMD_SUCCESS try: api.delete_from_matching_blacklist(self.db, entry) except NotFoundError as e: self.error(str(e)) return e.code return CMD_SUCCESS
python
def delete(self, entry): if not entry: return CMD_SUCCESS try: api.delete_from_matching_blacklist(self.db, entry) except NotFoundError as e: self.error(str(e)) return e.code return CMD_SUCCESS
[ "def", "delete", "(", "self", ",", "entry", ")", ":", "if", "not", "entry", ":", "return", "CMD_SUCCESS", "try", ":", "api", ".", "delete_from_matching_blacklist", "(", "self", ".", "db", ",", "entry", ")", "except", "NotFoundError", "as", "e", ":", "sel...
Remove entries from the blacklist. The method removes the given 'entry' from the blacklist. :param entry: entry to remove from the blacklist
[ "Remove", "entries", "from", "the", "blacklist", "." ]
391cd37a75fea26311dc6908bc1c953c540a8e04
https://github.com/chaoss/grimoirelab-sortinghat/blob/391cd37a75fea26311dc6908bc1c953c540a8e04/sortinghat/cmd/blacklist.py#L124-L140
26,978
chaoss/grimoirelab-sortinghat
sortinghat/cmd/blacklist.py
Blacklist.blacklist
def blacklist(self, term=None): """List blacklisted entries. When no term is given, the method will list the entries that exist in the blacklist. If 'term' is set, the method will list only those entries that match with that term. :param term: term to match """ try: bl = api.blacklist(self.db, term) self.display('blacklist.tmpl', blacklist=bl) except NotFoundError as e: self.error(str(e)) return e.code return CMD_SUCCESS
python
def blacklist(self, term=None): try: bl = api.blacklist(self.db, term) self.display('blacklist.tmpl', blacklist=bl) except NotFoundError as e: self.error(str(e)) return e.code return CMD_SUCCESS
[ "def", "blacklist", "(", "self", ",", "term", "=", "None", ")", ":", "try", ":", "bl", "=", "api", ".", "blacklist", "(", "self", ".", "db", ",", "term", ")", "self", ".", "display", "(", "'blacklist.tmpl'", ",", "blacklist", "=", "bl", ")", "excep...
List blacklisted entries. When no term is given, the method will list the entries that exist in the blacklist. If 'term' is set, the method will list only those entries that match with that term. :param term: term to match
[ "List", "blacklisted", "entries", "." ]
391cd37a75fea26311dc6908bc1c953c540a8e04
https://github.com/chaoss/grimoirelab-sortinghat/blob/391cd37a75fea26311dc6908bc1c953c540a8e04/sortinghat/cmd/blacklist.py#L142-L158
26,979
chaoss/grimoirelab-sortinghat
sortinghat/cmd/config.py
Config.run
def run(self, *args): """Get and set configuration parameters. This command gets or sets parameter values from the user configuration file. On Linux systems, configuration will be stored in the file '~/.sortinghat'. """ params = self.parser.parse_args(args) config_file = os.path.expanduser('~/.sortinghat') if params.action == 'get': code = self.get(params.parameter, config_file) elif params.action == 'set': code = self.set(params.parameter, params.value, config_file) else: raise RuntimeError("Not get or set action given") return code
python
def run(self, *args): params = self.parser.parse_args(args) config_file = os.path.expanduser('~/.sortinghat') if params.action == 'get': code = self.get(params.parameter, config_file) elif params.action == 'set': code = self.set(params.parameter, params.value, config_file) else: raise RuntimeError("Not get or set action given") return code
[ "def", "run", "(", "self", ",", "*", "args", ")", ":", "params", "=", "self", ".", "parser", ".", "parse_args", "(", "args", ")", "config_file", "=", "os", ".", "path", ".", "expanduser", "(", "'~/.sortinghat'", ")", "if", "params", ".", "action", "=...
Get and set configuration parameters. This command gets or sets parameter values from the user configuration file. On Linux systems, configuration will be stored in the file '~/.sortinghat'.
[ "Get", "and", "set", "configuration", "parameters", "." ]
391cd37a75fea26311dc6908bc1c953c540a8e04
https://github.com/chaoss/grimoirelab-sortinghat/blob/391cd37a75fea26311dc6908bc1c953c540a8e04/sortinghat/cmd/config.py#L80-L98
26,980
chaoss/grimoirelab-sortinghat
sortinghat/cmd/config.py
Config.get
def get(self, key, filepath): """Get configuration parameter. Reads 'key' configuration parameter from the configuration file given in 'filepath'. Configuration parameter in 'key' must follow the schema <section>.<option> . :param key: key to get :param filepath: configuration file """ if not filepath: raise RuntimeError("Configuration file not given") if not self.__check_config_key(key): raise RuntimeError("%s parameter does not exists" % key) if not os.path.isfile(filepath): raise RuntimeError("%s config file does not exist" % filepath) section, option = key.split('.') config = configparser.SafeConfigParser() config.read(filepath) try: option = config.get(section, option) self.display('config.tmpl', key=key, option=option) except (configparser.NoSectionError, configparser.NoOptionError): pass return CMD_SUCCESS
python
def get(self, key, filepath): if not filepath: raise RuntimeError("Configuration file not given") if not self.__check_config_key(key): raise RuntimeError("%s parameter does not exists" % key) if not os.path.isfile(filepath): raise RuntimeError("%s config file does not exist" % filepath) section, option = key.split('.') config = configparser.SafeConfigParser() config.read(filepath) try: option = config.get(section, option) self.display('config.tmpl', key=key, option=option) except (configparser.NoSectionError, configparser.NoOptionError): pass return CMD_SUCCESS
[ "def", "get", "(", "self", ",", "key", ",", "filepath", ")", ":", "if", "not", "filepath", ":", "raise", "RuntimeError", "(", "\"Configuration file not given\"", ")", "if", "not", "self", ".", "__check_config_key", "(", "key", ")", ":", "raise", "RuntimeErro...
Get configuration parameter. Reads 'key' configuration parameter from the configuration file given in 'filepath'. Configuration parameter in 'key' must follow the schema <section>.<option> . :param key: key to get :param filepath: configuration file
[ "Get", "configuration", "parameter", "." ]
391cd37a75fea26311dc6908bc1c953c540a8e04
https://github.com/chaoss/grimoirelab-sortinghat/blob/391cd37a75fea26311dc6908bc1c953c540a8e04/sortinghat/cmd/config.py#L100-L130
26,981
chaoss/grimoirelab-sortinghat
sortinghat/cmd/config.py
Config.set
def set(self, key, value, filepath): """Set configuration parameter. Writes 'value' on 'key' to the configuration file given in 'filepath'. Configuration parameter in 'key' must follow the schema <section>.<option> . :param key: key to set :param value: value to set :param filepath: configuration file """ if not filepath: raise RuntimeError("Configuration file not given") if not self.__check_config_key(key): raise RuntimeError("%s parameter does not exists or cannot be set" % key) config = configparser.SafeConfigParser() if os.path.isfile(filepath): config.read(filepath) section, option = key.split('.') if section not in config.sections(): config.add_section(section) try: config.set(section, option, value) except TypeError as e: raise RuntimeError(str(e)) try: with open(filepath, 'w') as f: config.write(f) except IOError as e: raise RuntimeError(str(e)) return CMD_SUCCESS
python
def set(self, key, value, filepath): if not filepath: raise RuntimeError("Configuration file not given") if not self.__check_config_key(key): raise RuntimeError("%s parameter does not exists or cannot be set" % key) config = configparser.SafeConfigParser() if os.path.isfile(filepath): config.read(filepath) section, option = key.split('.') if section not in config.sections(): config.add_section(section) try: config.set(section, option, value) except TypeError as e: raise RuntimeError(str(e)) try: with open(filepath, 'w') as f: config.write(f) except IOError as e: raise RuntimeError(str(e)) return CMD_SUCCESS
[ "def", "set", "(", "self", ",", "key", ",", "value", ",", "filepath", ")", ":", "if", "not", "filepath", ":", "raise", "RuntimeError", "(", "\"Configuration file not given\"", ")", "if", "not", "self", ".", "__check_config_key", "(", "key", ")", ":", "rais...
Set configuration parameter. Writes 'value' on 'key' to the configuration file given in 'filepath'. Configuration parameter in 'key' must follow the schema <section>.<option> . :param key: key to set :param value: value to set :param filepath: configuration file
[ "Set", "configuration", "parameter", "." ]
391cd37a75fea26311dc6908bc1c953c540a8e04
https://github.com/chaoss/grimoirelab-sortinghat/blob/391cd37a75fea26311dc6908bc1c953c540a8e04/sortinghat/cmd/config.py#L132-L170
26,982
chaoss/grimoirelab-sortinghat
sortinghat/cmd/config.py
Config.__check_config_key
def __check_config_key(self, key): """Check whether the key is valid. A valid key has the schema <section>.<option>. Keys supported are listed in CONFIG_OPTIONS dict. :param key: <section>.<option> key """ try: section, option = key.split('.') except (AttributeError, ValueError): return False if not section or not option: return False return section in Config.CONFIG_OPTIONS and\ option in Config.CONFIG_OPTIONS[section]
python
def __check_config_key(self, key): try: section, option = key.split('.') except (AttributeError, ValueError): return False if not section or not option: return False return section in Config.CONFIG_OPTIONS and\ option in Config.CONFIG_OPTIONS[section]
[ "def", "__check_config_key", "(", "self", ",", "key", ")", ":", "try", ":", "section", ",", "option", "=", "key", ".", "split", "(", "'.'", ")", "except", "(", "AttributeError", ",", "ValueError", ")", ":", "return", "False", "if", "not", "section", "o...
Check whether the key is valid. A valid key has the schema <section>.<option>. Keys supported are listed in CONFIG_OPTIONS dict. :param key: <section>.<option> key
[ "Check", "whether", "the", "key", "is", "valid", "." ]
391cd37a75fea26311dc6908bc1c953c540a8e04
https://github.com/chaoss/grimoirelab-sortinghat/blob/391cd37a75fea26311dc6908bc1c953c540a8e04/sortinghat/cmd/config.py#L172-L189
26,983
chaoss/grimoirelab-sortinghat
sortinghat/cmd/export.py
Export.run
def run(self, *args): """Export data from the registry. By default, it writes the data to the standard output. If a positional argument is given, it will write the data on that file. """ params = self.parser.parse_args(args) with params.outfile as outfile: if params.identities: code = self.export_identities(outfile, params.source) elif params.orgs: code = self.export_organizations(outfile) else: # The running proccess never should reach this section raise RuntimeError("Unexpected export option") return code
python
def run(self, *args): params = self.parser.parse_args(args) with params.outfile as outfile: if params.identities: code = self.export_identities(outfile, params.source) elif params.orgs: code = self.export_organizations(outfile) else: # The running proccess never should reach this section raise RuntimeError("Unexpected export option") return code
[ "def", "run", "(", "self", ",", "*", "args", ")", ":", "params", "=", "self", ".", "parser", ".", "parse_args", "(", "args", ")", "with", "params", ".", "outfile", "as", "outfile", ":", "if", "params", ".", "identities", ":", "code", "=", "self", "...
Export data from the registry. By default, it writes the data to the standard output. If a positional argument is given, it will write the data on that file.
[ "Export", "data", "from", "the", "registry", "." ]
391cd37a75fea26311dc6908bc1c953c540a8e04
https://github.com/chaoss/grimoirelab-sortinghat/blob/391cd37a75fea26311dc6908bc1c953c540a8e04/sortinghat/cmd/export.py#L82-L100
26,984
chaoss/grimoirelab-sortinghat
sortinghat/cmd/export.py
Export.export_identities
def export_identities(self, outfile, source=None): """Export identities information to a file. The method exports information related to unique identities, to the given 'outfile' output file. When 'source' parameter is given, only those unique identities which have one or more identities from the given source will be exported. :param outfile: destination file object :param source: source of the identities to export """ exporter = SortingHatIdentitiesExporter(self.db) dump = exporter.export(source) try: outfile.write(dump) outfile.write('\n') except IOError as e: raise RuntimeError(str(e)) return CMD_SUCCESS
python
def export_identities(self, outfile, source=None): exporter = SortingHatIdentitiesExporter(self.db) dump = exporter.export(source) try: outfile.write(dump) outfile.write('\n') except IOError as e: raise RuntimeError(str(e)) return CMD_SUCCESS
[ "def", "export_identities", "(", "self", ",", "outfile", ",", "source", "=", "None", ")", ":", "exporter", "=", "SortingHatIdentitiesExporter", "(", "self", ".", "db", ")", "dump", "=", "exporter", ".", "export", "(", "source", ")", "try", ":", "outfile", ...
Export identities information to a file. The method exports information related to unique identities, to the given 'outfile' output file. When 'source' parameter is given, only those unique identities which have one or more identities from the given source will be exported. :param outfile: destination file object :param source: source of the identities to export
[ "Export", "identities", "information", "to", "a", "file", "." ]
391cd37a75fea26311dc6908bc1c953c540a8e04
https://github.com/chaoss/grimoirelab-sortinghat/blob/391cd37a75fea26311dc6908bc1c953c540a8e04/sortinghat/cmd/export.py#L102-L124
26,985
chaoss/grimoirelab-sortinghat
sortinghat/cmd/export.py
Export.export_organizations
def export_organizations(self, outfile): """Export organizations information to a file. The method exports information related to organizations, to the given 'outfile' output file. :param outfile: destination file object """ exporter = SortingHatOrganizationsExporter(self.db) dump = exporter.export() try: outfile.write(dump) outfile.write('\n') except IOError as e: raise RuntimeError(str(e)) return CMD_SUCCESS
python
def export_organizations(self, outfile): exporter = SortingHatOrganizationsExporter(self.db) dump = exporter.export() try: outfile.write(dump) outfile.write('\n') except IOError as e: raise RuntimeError(str(e)) return CMD_SUCCESS
[ "def", "export_organizations", "(", "self", ",", "outfile", ")", ":", "exporter", "=", "SortingHatOrganizationsExporter", "(", "self", ".", "db", ")", "dump", "=", "exporter", ".", "export", "(", ")", "try", ":", "outfile", ".", "write", "(", "dump", ")", ...
Export organizations information to a file. The method exports information related to organizations, to the given 'outfile' output file. :param outfile: destination file object
[ "Export", "organizations", "information", "to", "a", "file", "." ]
391cd37a75fea26311dc6908bc1c953c540a8e04
https://github.com/chaoss/grimoirelab-sortinghat/blob/391cd37a75fea26311dc6908bc1c953c540a8e04/sortinghat/cmd/export.py#L126-L144
26,986
chaoss/grimoirelab-sortinghat
sortinghat/cmd/export.py
SortingHatIdentitiesExporter.export
def export(self, source=None): """Export a set of unique identities. Method to export unique identities from the registry. Identities schema will follow Sorting Hat JSON format. When source parameter is given, only those unique identities which have one or more identities from the given source will be exported. :param source: source of the identities to export :returns: a JSON formatted str """ uidentities = {} uids = api.unique_identities(self.db, source=source) for uid in uids: enrollments = [rol.to_dict() for rol in api.enrollments(self.db, uuid=uid.uuid)] u = uid.to_dict() u['identities'].sort(key=lambda x: x['id']) uidentities[uid.uuid] = u uidentities[uid.uuid]['enrollments'] = enrollments blacklist = [mb.excluded for mb in api.blacklist(self.db)] obj = {'time': str(datetime.datetime.now()), 'source': source, 'blacklist': blacklist, 'organizations': {}, 'uidentities': uidentities} return json.dumps(obj, default=self._json_encoder, indent=4, separators=(',', ': '), sort_keys=True)
python
def export(self, source=None): uidentities = {} uids = api.unique_identities(self.db, source=source) for uid in uids: enrollments = [rol.to_dict() for rol in api.enrollments(self.db, uuid=uid.uuid)] u = uid.to_dict() u['identities'].sort(key=lambda x: x['id']) uidentities[uid.uuid] = u uidentities[uid.uuid]['enrollments'] = enrollments blacklist = [mb.excluded for mb in api.blacklist(self.db)] obj = {'time': str(datetime.datetime.now()), 'source': source, 'blacklist': blacklist, 'organizations': {}, 'uidentities': uidentities} return json.dumps(obj, default=self._json_encoder, indent=4, separators=(',', ': '), sort_keys=True)
[ "def", "export", "(", "self", ",", "source", "=", "None", ")", ":", "uidentities", "=", "{", "}", "uids", "=", "api", ".", "unique_identities", "(", "self", ".", "db", ",", "source", "=", "source", ")", "for", "uid", "in", "uids", ":", "enrollments",...
Export a set of unique identities. Method to export unique identities from the registry. Identities schema will follow Sorting Hat JSON format. When source parameter is given, only those unique identities which have one or more identities from the given source will be exported. :param source: source of the identities to export :returns: a JSON formatted str
[ "Export", "a", "set", "of", "unique", "identities", "." ]
391cd37a75fea26311dc6908bc1c953c540a8e04
https://github.com/chaoss/grimoirelab-sortinghat/blob/391cd37a75fea26311dc6908bc1c953c540a8e04/sortinghat/cmd/export.py#L168-L205
26,987
chaoss/grimoirelab-sortinghat
sortinghat/cmd/export.py
SortingHatOrganizationsExporter.export
def export(self): """Export a set of organizations. Method to export organizations from the registry. Organizations schema will follow Sorting Hat JSON format. :returns: a JSON formatted str """ organizations = {} orgs = api.registry(self.db) for org in orgs: domains = [{'domain': dom.domain, 'is_top': dom.is_top_domain} for dom in org.domains] domains.sort(key=lambda x: x['domain']) organizations[org.name] = domains obj = {'time': str(datetime.datetime.now()), 'blacklist': [], 'organizations': organizations, 'uidentities': {}} return json.dumps(obj, default=self._json_encoder, indent=4, separators=(',', ': '), sort_keys=True)
python
def export(self): organizations = {} orgs = api.registry(self.db) for org in orgs: domains = [{'domain': dom.domain, 'is_top': dom.is_top_domain} for dom in org.domains] domains.sort(key=lambda x: x['domain']) organizations[org.name] = domains obj = {'time': str(datetime.datetime.now()), 'blacklist': [], 'organizations': organizations, 'uidentities': {}} return json.dumps(obj, default=self._json_encoder, indent=4, separators=(',', ': '), sort_keys=True)
[ "def", "export", "(", "self", ")", ":", "organizations", "=", "{", "}", "orgs", "=", "api", ".", "registry", "(", "self", ".", "db", ")", "for", "org", "in", "orgs", ":", "domains", "=", "[", "{", "'domain'", ":", "dom", ".", "domain", ",", "'is_...
Export a set of organizations. Method to export organizations from the registry. Organizations schema will follow Sorting Hat JSON format. :returns: a JSON formatted str
[ "Export", "a", "set", "of", "organizations", "." ]
391cd37a75fea26311dc6908bc1c953c540a8e04
https://github.com/chaoss/grimoirelab-sortinghat/blob/391cd37a75fea26311dc6908bc1c953c540a8e04/sortinghat/cmd/export.py#L237-L264
26,988
chaoss/grimoirelab-sortinghat
sortinghat/cmd/autoprofile.py
AutoProfile.run
def run(self, *args): """Autocomplete profile information.""" params = self.parser.parse_args(args) sources = params.source code = self.autocomplete(sources) return code
python
def run(self, *args): params = self.parser.parse_args(args) sources = params.source code = self.autocomplete(sources) return code
[ "def", "run", "(", "self", ",", "*", "args", ")", ":", "params", "=", "self", ".", "parser", ".", "parse_args", "(", "args", ")", "sources", "=", "params", ".", "source", "code", "=", "self", ".", "autocomplete", "(", "sources", ")", "return", "code"...
Autocomplete profile information.
[ "Autocomplete", "profile", "information", "." ]
391cd37a75fea26311dc6908bc1c953c540a8e04
https://github.com/chaoss/grimoirelab-sortinghat/blob/391cd37a75fea26311dc6908bc1c953c540a8e04/sortinghat/cmd/autoprofile.py#L71-L78
26,989
chaoss/grimoirelab-sortinghat
sortinghat/cmd/autoprofile.py
AutoProfile.autocomplete
def autocomplete(self, sources): """Autocomplete unique identities profiles. Autocomplete unique identities profiles using the information of their identities. The selection of the data used to fill the profile is prioritized using a list of sources. """ email_pattern = re.compile(EMAIL_ADDRESS_REGEX) identities = self.__select_autocomplete_identities(sources) for uuid, ids in identities.items(): # Among the identities (with the same priority) selected # to complete the profile, it will choose the longest 'name'. # If no name is available, it will use the field 'username'. name = None email = None for identity in ids: oldname = name if not name: name = identity.name or identity.username elif identity.name and len(identity.name) > len(name): name = identity.name # Do not set email addresses on the name field if name and email_pattern.match(name): name = oldname if not email and identity.email: email = identity.email kw = { 'name': name, 'email': email } try: api.edit_profile(self.db, uuid, **kw) self.display('autoprofile.tmpl', identity=identity) except (NotFoundError, InvalidValueError) as e: self.error(str(e)) return e.code return CMD_SUCCESS
python
def autocomplete(self, sources): email_pattern = re.compile(EMAIL_ADDRESS_REGEX) identities = self.__select_autocomplete_identities(sources) for uuid, ids in identities.items(): # Among the identities (with the same priority) selected # to complete the profile, it will choose the longest 'name'. # If no name is available, it will use the field 'username'. name = None email = None for identity in ids: oldname = name if not name: name = identity.name or identity.username elif identity.name and len(identity.name) > len(name): name = identity.name # Do not set email addresses on the name field if name and email_pattern.match(name): name = oldname if not email and identity.email: email = identity.email kw = { 'name': name, 'email': email } try: api.edit_profile(self.db, uuid, **kw) self.display('autoprofile.tmpl', identity=identity) except (NotFoundError, InvalidValueError) as e: self.error(str(e)) return e.code return CMD_SUCCESS
[ "def", "autocomplete", "(", "self", ",", "sources", ")", ":", "email_pattern", "=", "re", ".", "compile", "(", "EMAIL_ADDRESS_REGEX", ")", "identities", "=", "self", ".", "__select_autocomplete_identities", "(", "sources", ")", "for", "uuid", ",", "ids", "in",...
Autocomplete unique identities profiles. Autocomplete unique identities profiles using the information of their identities. The selection of the data used to fill the profile is prioritized using a list of sources.
[ "Autocomplete", "unique", "identities", "profiles", "." ]
391cd37a75fea26311dc6908bc1c953c540a8e04
https://github.com/chaoss/grimoirelab-sortinghat/blob/391cd37a75fea26311dc6908bc1c953c540a8e04/sortinghat/cmd/autoprofile.py#L80-L125
26,990
chaoss/grimoirelab-sortinghat
sortinghat/cmd/autoprofile.py
AutoProfile.__select_autocomplete_identities
def __select_autocomplete_identities(self, sources): """Select the identities used for autocompleting""" MIN_PRIORITY = 99999999 checked = {} for source in sources: uids = api.unique_identities(self.db, source=source) for uid in uids: if uid.uuid in checked: continue max_priority = MIN_PRIORITY selected = [] for identity in sorted(uid.identities, key=lambda x: x.id): try: priority = sources.index(identity.source) if priority < max_priority: selected = [identity] max_priority = priority elif priority == max_priority: selected.append(identity) except ValueError: continue checked[uid.uuid] = selected identities = collections.OrderedDict(sorted(checked.items(), key=lambda t: t[0])) return identities
python
def __select_autocomplete_identities(self, sources): MIN_PRIORITY = 99999999 checked = {} for source in sources: uids = api.unique_identities(self.db, source=source) for uid in uids: if uid.uuid in checked: continue max_priority = MIN_PRIORITY selected = [] for identity in sorted(uid.identities, key=lambda x: x.id): try: priority = sources.index(identity.source) if priority < max_priority: selected = [identity] max_priority = priority elif priority == max_priority: selected.append(identity) except ValueError: continue checked[uid.uuid] = selected identities = collections.OrderedDict(sorted(checked.items(), key=lambda t: t[0])) return identities
[ "def", "__select_autocomplete_identities", "(", "self", ",", "sources", ")", ":", "MIN_PRIORITY", "=", "99999999", "checked", "=", "{", "}", "for", "source", "in", "sources", ":", "uids", "=", "api", ".", "unique_identities", "(", "self", ".", "db", ",", "...
Select the identities used for autocompleting
[ "Select", "the", "identities", "used", "for", "autocompleting" ]
391cd37a75fea26311dc6908bc1c953c540a8e04
https://github.com/chaoss/grimoirelab-sortinghat/blob/391cd37a75fea26311dc6908bc1c953c540a8e04/sortinghat/cmd/autoprofile.py#L127-L161
26,991
chaoss/grimoirelab-sortinghat
sortinghat/cmd/show.py
Show.run
def run(self, *args): """Show information about unique identities.""" params = self.parser.parse_args(args) code = self.show(params.uuid, params.term) return code
python
def run(self, *args): params = self.parser.parse_args(args) code = self.show(params.uuid, params.term) return code
[ "def", "run", "(", "self", ",", "*", "args", ")", ":", "params", "=", "self", ".", "parser", ".", "parse_args", "(", "args", ")", "code", "=", "self", ".", "show", "(", "params", ".", "uuid", ",", "params", ".", "term", ")", "return", "code" ]
Show information about unique identities.
[ "Show", "information", "about", "unique", "identities", "." ]
391cd37a75fea26311dc6908bc1c953c540a8e04
https://github.com/chaoss/grimoirelab-sortinghat/blob/391cd37a75fea26311dc6908bc1c953c540a8e04/sortinghat/cmd/show.py#L74-L81
26,992
chaoss/grimoirelab-sortinghat
sortinghat/cmd/show.py
Show.show
def show(self, uuid=None, term=None): """Show the information related to unique identities. This method prints information related to unique identities such as identities or enrollments. When <uuid> is given, it will only show information about the unique identity related to <uuid>. When <term> is set, it will only show information about those unique identities that have any attribute (name, email, username, source) which match with the given term. This parameter does not have any effect when <uuid> is set. :param uuid: unique identifier :param term: term to match with unique identities data """ try: if uuid: uidentities = api.unique_identities(self.db, uuid) elif term: uidentities = api.search_unique_identities(self.db, term) else: uidentities = api.unique_identities(self.db) for uid in uidentities: # Add enrollments to a new property 'roles' enrollments = api.enrollments(self.db, uid.uuid) uid.roles = enrollments self.display('show.tmpl', uidentities=uidentities) except NotFoundError as e: self.error(str(e)) return e.code return CMD_SUCCESS
python
def show(self, uuid=None, term=None): try: if uuid: uidentities = api.unique_identities(self.db, uuid) elif term: uidentities = api.search_unique_identities(self.db, term) else: uidentities = api.unique_identities(self.db) for uid in uidentities: # Add enrollments to a new property 'roles' enrollments = api.enrollments(self.db, uid.uuid) uid.roles = enrollments self.display('show.tmpl', uidentities=uidentities) except NotFoundError as e: self.error(str(e)) return e.code return CMD_SUCCESS
[ "def", "show", "(", "self", ",", "uuid", "=", "None", ",", "term", "=", "None", ")", ":", "try", ":", "if", "uuid", ":", "uidentities", "=", "api", ".", "unique_identities", "(", "self", ".", "db", ",", "uuid", ")", "elif", "term", ":", "uidentitie...
Show the information related to unique identities. This method prints information related to unique identities such as identities or enrollments. When <uuid> is given, it will only show information about the unique identity related to <uuid>. When <term> is set, it will only show information about those unique identities that have any attribute (name, email, username, source) which match with the given term. This parameter does not have any effect when <uuid> is set. :param uuid: unique identifier :param term: term to match with unique identities data
[ "Show", "the", "information", "related", "to", "unique", "identities", "." ]
391cd37a75fea26311dc6908bc1c953c540a8e04
https://github.com/chaoss/grimoirelab-sortinghat/blob/391cd37a75fea26311dc6908bc1c953c540a8e04/sortinghat/cmd/show.py#L83-L118
26,993
chaoss/grimoirelab-sortinghat
sortinghat/parsing/stackalytics.py
StackalyticsParser.__parse_organizations
def __parse_organizations(self, json): """Parse Stackalytics organizations. The Stackalytics organizations format is a JSON document stored under the "companies" key. The next JSON shows the structure of the document: { "companies" : [ { "domains": ["alcatel-lucent.com"], "company_name": "Alcatel-Lucent", "aliases": ["Alcatel Lucent", "Alcatel-Lcuent"] }, { "domains": ["allegrogroup.com", "allegro.pl"], "company_name": "Allegro", "aliases": ["Allegro Group", "Grupa Allegro", "Grupa Allegro Sp. z o.o."] }, { "domains": ["altiscale.com"], "company_name": "Altiscale" }, ] } :param json: JSON object to parse :raises InvalidFormatError: raised when the format of the JSON is not valid. """ try: for company in json['companies']: name = self.__encode(company['company_name']) org = self._organizations.get(name, None) if not org: org = Organization(name=name) self._organizations[name] = org for domain in company['domains']: if not domain: continue dom = Domain(domain=domain) org.domains.append(dom) except KeyError as e: msg = "invalid json format. Attribute %s not found" % e.args raise InvalidFormatError(cause=msg)
python
def __parse_organizations(self, json): try: for company in json['companies']: name = self.__encode(company['company_name']) org = self._organizations.get(name, None) if not org: org = Organization(name=name) self._organizations[name] = org for domain in company['domains']: if not domain: continue dom = Domain(domain=domain) org.domains.append(dom) except KeyError as e: msg = "invalid json format. Attribute %s not found" % e.args raise InvalidFormatError(cause=msg)
[ "def", "__parse_organizations", "(", "self", ",", "json", ")", ":", "try", ":", "for", "company", "in", "json", "[", "'companies'", "]", ":", "name", "=", "self", ".", "__encode", "(", "company", "[", "'company_name'", "]", ")", "org", "=", "self", "."...
Parse Stackalytics organizations. The Stackalytics organizations format is a JSON document stored under the "companies" key. The next JSON shows the structure of the document: { "companies" : [ { "domains": ["alcatel-lucent.com"], "company_name": "Alcatel-Lucent", "aliases": ["Alcatel Lucent", "Alcatel-Lcuent"] }, { "domains": ["allegrogroup.com", "allegro.pl"], "company_name": "Allegro", "aliases": ["Allegro Group", "Grupa Allegro", "Grupa Allegro Sp. z o.o."] }, { "domains": ["altiscale.com"], "company_name": "Altiscale" }, ] } :param json: JSON object to parse :raises InvalidFormatError: raised when the format of the JSON is not valid.
[ "Parse", "Stackalytics", "organizations", "." ]
391cd37a75fea26311dc6908bc1c953c540a8e04
https://github.com/chaoss/grimoirelab-sortinghat/blob/391cd37a75fea26311dc6908bc1c953c540a8e04/sortinghat/parsing/stackalytics.py#L80-L128
26,994
chaoss/grimoirelab-sortinghat
sortinghat/parsing/stackalytics.py
StackalyticsParser.__parse_identities
def __parse_identities(self, json): """Parse identities using Stackalytics format. The Stackalytics identities format is a JSON document under the "users" key. The document should follow the next schema: { "users": [ { "launchpad_id": "0-jsmith", "gerrit_id": "jsmith", "companies": [ { "company_name": "Example", "end_date": null } ], "user_name": "John Smith", "emails": ["jsmith@example.com", "jsmith@example.net"] }, { "companies": [ { "company_name": "Bitergia", "end_date": null }, { "company_name": "Example", "end_date": "2010-Jan-01" } ], "user_name": "John Doe", "emails": ["jdoe@bitergia.com", "jdoe@example.com"] } ] } :parse json: JSON object to parse :raise InvalidFormatError: raised when the format of the JSON is not valid. """ try: for user in json['users']: name = self.__encode(user['user_name']) uuid = name uid = UniqueIdentity(uuid=uuid) identity = Identity(name=name, email=None, username=None, source=self.source, uuid=uuid) uid.identities.append(identity) for email_addr in user['emails']: email = self.__encode(email_addr) identity = Identity(name=name, email=email, username=None, source=self.source, uuid=uuid) uid.identities.append(identity) for site_id in ['gerrit_id', 'launchpad_id']: username = user.get(site_id, None) if not username: continue username = self.__encode(username) source = self.source + ':' + site_id.replace('_id', '') identity = Identity(name=name, email=None, username=username, source=source, uuid=uuid) uid.identities.append(identity) for rol in self.__parse_enrollments(user): uid.enrollments.append(rol) self._identities[uuid] = uid except KeyError as e: msg = "invalid json format. Attribute %s not found" % e.args raise InvalidFormatError(cause=msg)
python
def __parse_identities(self, json): try: for user in json['users']: name = self.__encode(user['user_name']) uuid = name uid = UniqueIdentity(uuid=uuid) identity = Identity(name=name, email=None, username=None, source=self.source, uuid=uuid) uid.identities.append(identity) for email_addr in user['emails']: email = self.__encode(email_addr) identity = Identity(name=name, email=email, username=None, source=self.source, uuid=uuid) uid.identities.append(identity) for site_id in ['gerrit_id', 'launchpad_id']: username = user.get(site_id, None) if not username: continue username = self.__encode(username) source = self.source + ':' + site_id.replace('_id', '') identity = Identity(name=name, email=None, username=username, source=source, uuid=uuid) uid.identities.append(identity) for rol in self.__parse_enrollments(user): uid.enrollments.append(rol) self._identities[uuid] = uid except KeyError as e: msg = "invalid json format. Attribute %s not found" % e.args raise InvalidFormatError(cause=msg)
[ "def", "__parse_identities", "(", "self", ",", "json", ")", ":", "try", ":", "for", "user", "in", "json", "[", "'users'", "]", ":", "name", "=", "self", ".", "__encode", "(", "user", "[", "'user_name'", "]", ")", "uuid", "=", "name", "uid", "=", "U...
Parse identities using Stackalytics format. The Stackalytics identities format is a JSON document under the "users" key. The document should follow the next schema: { "users": [ { "launchpad_id": "0-jsmith", "gerrit_id": "jsmith", "companies": [ { "company_name": "Example", "end_date": null } ], "user_name": "John Smith", "emails": ["jsmith@example.com", "jsmith@example.net"] }, { "companies": [ { "company_name": "Bitergia", "end_date": null }, { "company_name": "Example", "end_date": "2010-Jan-01" } ], "user_name": "John Doe", "emails": ["jdoe@bitergia.com", "jdoe@example.com"] } ] } :parse json: JSON object to parse :raise InvalidFormatError: raised when the format of the JSON is not valid.
[ "Parse", "identities", "using", "Stackalytics", "format", "." ]
391cd37a75fea26311dc6908bc1c953c540a8e04
https://github.com/chaoss/grimoirelab-sortinghat/blob/391cd37a75fea26311dc6908bc1c953c540a8e04/sortinghat/parsing/stackalytics.py#L130-L207
26,995
chaoss/grimoirelab-sortinghat
sortinghat/parsing/stackalytics.py
StackalyticsParser.__parse_enrollments
def __parse_enrollments(self, user): """Parse user enrollments""" enrollments = [] for company in user['companies']: name = company['company_name'] org = self._organizations.get(name, None) if not org: org = Organization(name=name) self._organizations[name] = org start_date = MIN_PERIOD_DATE end_date = MAX_PERIOD_DATE if company['end_date']: end_date = str_to_datetime(company['end_date']) rol = Enrollment(start=start_date, end=end_date, organization=org) enrollments.append(rol) return enrollments
python
def __parse_enrollments(self, user): enrollments = [] for company in user['companies']: name = company['company_name'] org = self._organizations.get(name, None) if not org: org = Organization(name=name) self._organizations[name] = org start_date = MIN_PERIOD_DATE end_date = MAX_PERIOD_DATE if company['end_date']: end_date = str_to_datetime(company['end_date']) rol = Enrollment(start=start_date, end=end_date, organization=org) enrollments.append(rol) return enrollments
[ "def", "__parse_enrollments", "(", "self", ",", "user", ")", ":", "enrollments", "=", "[", "]", "for", "company", "in", "user", "[", "'companies'", "]", ":", "name", "=", "company", "[", "'company_name'", "]", "org", "=", "self", ".", "_organizations", "...
Parse user enrollments
[ "Parse", "user", "enrollments" ]
391cd37a75fea26311dc6908bc1c953c540a8e04
https://github.com/chaoss/grimoirelab-sortinghat/blob/391cd37a75fea26311dc6908bc1c953c540a8e04/sortinghat/parsing/stackalytics.py#L209-L233
26,996
chaoss/grimoirelab-sortinghat
sortinghat/parsing/stackalytics.py
StackalyticsParser.__load_json
def __load_json(self, stream): """Load json stream into a dict object """ import json try: return json.loads(stream) except ValueError as e: cause = "invalid json format. %s" % str(e) raise InvalidFormatError(cause=cause)
python
def __load_json(self, stream): import json try: return json.loads(stream) except ValueError as e: cause = "invalid json format. %s" % str(e) raise InvalidFormatError(cause=cause)
[ "def", "__load_json", "(", "self", ",", "stream", ")", ":", "import", "json", "try", ":", "return", "json", ".", "loads", "(", "stream", ")", "except", "ValueError", "as", "e", ":", "cause", "=", "\"invalid json format. %s\"", "%", "str", "(", "e", ")", ...
Load json stream into a dict object
[ "Load", "json", "stream", "into", "a", "dict", "object" ]
391cd37a75fea26311dc6908bc1c953c540a8e04
https://github.com/chaoss/grimoirelab-sortinghat/blob/391cd37a75fea26311dc6908bc1c953c540a8e04/sortinghat/parsing/stackalytics.py#L235-L244
26,997
chaoss/grimoirelab-sortinghat
sortinghat/parsing/mailmap.py
MailmapParser.__parse
def __parse(self, stream, has_orgs): """Parse identities and organizations using mailmap format. Mailmap format is a text plain document that stores on each line a map between an email address and its aliases. Each line follows any of the next formats: Proper Name <commit@email.xx> <proper@email.xx> <commit@email.xx> Proper Name <proper@email.xx> <commit@email.xx> Proper Name <proper@email.xx> Commit Name <commit@email.xx> When the flag `has_orgs` is set, the stream maps organizations an identities, following the next format: Organization Name <org@email.xx> Proper Name <proper@email.xx> :parse data: mailmap stream to parse :raise InvalidFormatError: raised when the format of the stream is not valid. """ if has_orgs: self.__parse_organizations(stream) else: self.__parse_identities(stream)
python
def __parse(self, stream, has_orgs): if has_orgs: self.__parse_organizations(stream) else: self.__parse_identities(stream)
[ "def", "__parse", "(", "self", ",", "stream", ",", "has_orgs", ")", ":", "if", "has_orgs", ":", "self", ".", "__parse_organizations", "(", "stream", ")", "else", ":", "self", ".", "__parse_identities", "(", "stream", ")" ]
Parse identities and organizations using mailmap format. Mailmap format is a text plain document that stores on each line a map between an email address and its aliases. Each line follows any of the next formats: Proper Name <commit@email.xx> <proper@email.xx> <commit@email.xx> Proper Name <proper@email.xx> <commit@email.xx> Proper Name <proper@email.xx> Commit Name <commit@email.xx> When the flag `has_orgs` is set, the stream maps organizations an identities, following the next format: Organization Name <org@email.xx> Proper Name <proper@email.xx> :parse data: mailmap stream to parse :raise InvalidFormatError: raised when the format of the stream is not valid.
[ "Parse", "identities", "and", "organizations", "using", "mailmap", "format", "." ]
391cd37a75fea26311dc6908bc1c953c540a8e04
https://github.com/chaoss/grimoirelab-sortinghat/blob/391cd37a75fea26311dc6908bc1c953c540a8e04/sortinghat/parsing/mailmap.py#L80-L105
26,998
chaoss/grimoirelab-sortinghat
sortinghat/parsing/mailmap.py
MailmapParser.__parse_organizations
def __parse_organizations(self, stream): """Parse organizations stream""" for aliases in self.__parse_stream(stream): # Parse identity identity = self.__parse_alias(aliases[1]) uuid = identity.email uid = self._identities.get(uuid, None) if not uid: uid = UniqueIdentity(uuid=uuid) identity.uuid = uuid uid.identities.append(identity) self._identities[uuid] = uid # Parse organization mailmap_id = aliases[0] name = self.__encode(mailmap_id[0]) if name in MAILMAP_NO_ORGS: continue org = Organization(name=name) self._organizations[name] = org enrollment = Enrollment(start=MIN_PERIOD_DATE, end=MAX_PERIOD_DATE, organization=org) uid.enrollments.append(enrollment)
python
def __parse_organizations(self, stream): for aliases in self.__parse_stream(stream): # Parse identity identity = self.__parse_alias(aliases[1]) uuid = identity.email uid = self._identities.get(uuid, None) if not uid: uid = UniqueIdentity(uuid=uuid) identity.uuid = uuid uid.identities.append(identity) self._identities[uuid] = uid # Parse organization mailmap_id = aliases[0] name = self.__encode(mailmap_id[0]) if name in MAILMAP_NO_ORGS: continue org = Organization(name=name) self._organizations[name] = org enrollment = Enrollment(start=MIN_PERIOD_DATE, end=MAX_PERIOD_DATE, organization=org) uid.enrollments.append(enrollment)
[ "def", "__parse_organizations", "(", "self", ",", "stream", ")", ":", "for", "aliases", "in", "self", ".", "__parse_stream", "(", "stream", ")", ":", "# Parse identity", "identity", "=", "self", ".", "__parse_alias", "(", "aliases", "[", "1", "]", ")", "uu...
Parse organizations stream
[ "Parse", "organizations", "stream" ]
391cd37a75fea26311dc6908bc1c953c540a8e04
https://github.com/chaoss/grimoirelab-sortinghat/blob/391cd37a75fea26311dc6908bc1c953c540a8e04/sortinghat/parsing/mailmap.py#L107-L135
26,999
chaoss/grimoirelab-sortinghat
sortinghat/parsing/mailmap.py
MailmapParser.__parse_identities
def __parse_identities(self, stream): """Parse identities stream""" for aliases in self.__parse_stream(stream): identity = self.__parse_alias(aliases[0]) uuid = identity.email uid = self._identities.get(uuid, None) if not uid: uid = UniqueIdentity(uuid=uuid) identity.uuid = uuid uid.identities.append(identity) self._identities[uuid] = uid profile = Profile(uuid=uuid, name=identity.name, email=identity.email, is_bot=False) uid.profile = profile # Aliases for alias in aliases[1:]: identity = self.__parse_alias(alias, uuid) uid.identities.append(identity) self._identities[uuid] = uid
python
def __parse_identities(self, stream): for aliases in self.__parse_stream(stream): identity = self.__parse_alias(aliases[0]) uuid = identity.email uid = self._identities.get(uuid, None) if not uid: uid = UniqueIdentity(uuid=uuid) identity.uuid = uuid uid.identities.append(identity) self._identities[uuid] = uid profile = Profile(uuid=uuid, name=identity.name, email=identity.email, is_bot=False) uid.profile = profile # Aliases for alias in aliases[1:]: identity = self.__parse_alias(alias, uuid) uid.identities.append(identity) self._identities[uuid] = uid
[ "def", "__parse_identities", "(", "self", ",", "stream", ")", ":", "for", "aliases", "in", "self", ".", "__parse_stream", "(", "stream", ")", ":", "identity", "=", "self", ".", "__parse_alias", "(", "aliases", "[", "0", "]", ")", "uuid", "=", "identity",...
Parse identities stream
[ "Parse", "identities", "stream" ]
391cd37a75fea26311dc6908bc1c953c540a8e04
https://github.com/chaoss/grimoirelab-sortinghat/blob/391cd37a75fea26311dc6908bc1c953c540a8e04/sortinghat/parsing/mailmap.py#L137-L161