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 75
19.8k
| code_tokens
sequence | docstring
stringlengths 3
17.3k
| docstring_tokens
sequence | sha
stringlengths 40
40
| url
stringlengths 87
242
|
---|---|---|---|---|---|---|---|---|---|---|---|
249,300 | dossier/dossier.fc | python/dossier/fc/feature_collection.py | FeatureCollection.to_dict | def to_dict(self):
'''Dump a feature collection's features to a dictionary.
This does not include additional data, such as whether
or not the collection is read-only. The returned dictionary
is suitable for serialization into JSON, CBOR, or similar
data formats.
'''
def is_non_native_sc(ty, encoded):
return (ty == 'StringCounter'
and not is_native_string_counter(encoded))
fc = {}
native = ('StringCounter', 'Unicode')
for name, feat in self._features.iteritems():
if name.startswith(self.EPHEMERAL_PREFIX):
continue
if not isinstance(name, unicode):
name = name.decode('utf-8')
tyname = registry.feature_type_name(name, feat)
encoded = registry.get(tyname).dumps(feat)
# This tomfoolery is to support *native untagged* StringCounters.
if tyname not in native or is_non_native_sc(tyname, encoded):
encoded = cbor.Tag(cbor_names_to_tags[tyname], encoded)
fc[name] = encoded
return fc | python | def to_dict(self):
'''Dump a feature collection's features to a dictionary.
This does not include additional data, such as whether
or not the collection is read-only. The returned dictionary
is suitable for serialization into JSON, CBOR, or similar
data formats.
'''
def is_non_native_sc(ty, encoded):
return (ty == 'StringCounter'
and not is_native_string_counter(encoded))
fc = {}
native = ('StringCounter', 'Unicode')
for name, feat in self._features.iteritems():
if name.startswith(self.EPHEMERAL_PREFIX):
continue
if not isinstance(name, unicode):
name = name.decode('utf-8')
tyname = registry.feature_type_name(name, feat)
encoded = registry.get(tyname).dumps(feat)
# This tomfoolery is to support *native untagged* StringCounters.
if tyname not in native or is_non_native_sc(tyname, encoded):
encoded = cbor.Tag(cbor_names_to_tags[tyname], encoded)
fc[name] = encoded
return fc | [
"def",
"to_dict",
"(",
"self",
")",
":",
"def",
"is_non_native_sc",
"(",
"ty",
",",
"encoded",
")",
":",
"return",
"(",
"ty",
"==",
"'StringCounter'",
"and",
"not",
"is_native_string_counter",
"(",
"encoded",
")",
")",
"fc",
"=",
"{",
"}",
"native",
"=",
"(",
"'StringCounter'",
",",
"'Unicode'",
")",
"for",
"name",
",",
"feat",
"in",
"self",
".",
"_features",
".",
"iteritems",
"(",
")",
":",
"if",
"name",
".",
"startswith",
"(",
"self",
".",
"EPHEMERAL_PREFIX",
")",
":",
"continue",
"if",
"not",
"isinstance",
"(",
"name",
",",
"unicode",
")",
":",
"name",
"=",
"name",
".",
"decode",
"(",
"'utf-8'",
")",
"tyname",
"=",
"registry",
".",
"feature_type_name",
"(",
"name",
",",
"feat",
")",
"encoded",
"=",
"registry",
".",
"get",
"(",
"tyname",
")",
".",
"dumps",
"(",
"feat",
")",
"# This tomfoolery is to support *native untagged* StringCounters.",
"if",
"tyname",
"not",
"in",
"native",
"or",
"is_non_native_sc",
"(",
"tyname",
",",
"encoded",
")",
":",
"encoded",
"=",
"cbor",
".",
"Tag",
"(",
"cbor_names_to_tags",
"[",
"tyname",
"]",
",",
"encoded",
")",
"fc",
"[",
"name",
"]",
"=",
"encoded",
"return",
"fc"
] | Dump a feature collection's features to a dictionary.
This does not include additional data, such as whether
or not the collection is read-only. The returned dictionary
is suitable for serialization into JSON, CBOR, or similar
data formats. | [
"Dump",
"a",
"feature",
"collection",
"s",
"features",
"to",
"a",
"dictionary",
"."
] | 3e969d0cb2592fc06afc1c849d2b22283450b5e2 | https://github.com/dossier/dossier.fc/blob/3e969d0cb2592fc06afc1c849d2b22283450b5e2/python/dossier/fc/feature_collection.py#L256-L283 |
249,301 | dossier/dossier.fc | python/dossier/fc/feature_collection.py | FeatureCollection.merge_with | def merge_with(self, other, multiset_op, other_op=None):
'''Merge this feature collection with another.
Merges two feature collections using the given ``multiset_op``
on each corresponding multiset and returns a new
:class:`FeatureCollection`. The contents of the two original
feature collections are not modified.
For each feature name in both feature sets, if either feature
collection being merged has a :class:`collections.Counter`
instance as its value, then the two values are merged by
calling `multiset_op` with both values as parameters. If
either feature collection has something other than a
:class:`collections.Counter`, and `other_op` is not
:const:`None`, then `other_op` is called with both values to
merge them. If `other_op` is :const:`None` and a feature
is not present in either feature collection with a counter
value, then the feature will not be present in the result.
:param other: The feature collection to merge into ``self``.
:type other: :class:`FeatureCollection`
:param multiset_op: Function to merge two counters
:type multiset_op: fun(Counter, Counter) -> Counter
:param other_op: Function to merge two non-counters
:type other_op: fun(object, object) -> object
:rtype: :class:`FeatureCollection`
'''
result = FeatureCollection()
for ms_name in set(self._counters()) | set(other._counters()):
c1 = self.get(ms_name, None)
c2 = other.get(ms_name, None)
if c1 is None and c2 is not None:
c1 = c2.__class__()
if c2 is None and c1 is not None:
c2 = c1.__class__()
result[ms_name] = multiset_op(c1, c2)
if other_op is not None:
for o_name in (set(self._not_counters()) |
set(other._not_counters())):
v = other_op(self.get(o_name, None), other.get(o_name, None))
if v is not None:
result[o_name] = v
return result | python | def merge_with(self, other, multiset_op, other_op=None):
'''Merge this feature collection with another.
Merges two feature collections using the given ``multiset_op``
on each corresponding multiset and returns a new
:class:`FeatureCollection`. The contents of the two original
feature collections are not modified.
For each feature name in both feature sets, if either feature
collection being merged has a :class:`collections.Counter`
instance as its value, then the two values are merged by
calling `multiset_op` with both values as parameters. If
either feature collection has something other than a
:class:`collections.Counter`, and `other_op` is not
:const:`None`, then `other_op` is called with both values to
merge them. If `other_op` is :const:`None` and a feature
is not present in either feature collection with a counter
value, then the feature will not be present in the result.
:param other: The feature collection to merge into ``self``.
:type other: :class:`FeatureCollection`
:param multiset_op: Function to merge two counters
:type multiset_op: fun(Counter, Counter) -> Counter
:param other_op: Function to merge two non-counters
:type other_op: fun(object, object) -> object
:rtype: :class:`FeatureCollection`
'''
result = FeatureCollection()
for ms_name in set(self._counters()) | set(other._counters()):
c1 = self.get(ms_name, None)
c2 = other.get(ms_name, None)
if c1 is None and c2 is not None:
c1 = c2.__class__()
if c2 is None and c1 is not None:
c2 = c1.__class__()
result[ms_name] = multiset_op(c1, c2)
if other_op is not None:
for o_name in (set(self._not_counters()) |
set(other._not_counters())):
v = other_op(self.get(o_name, None), other.get(o_name, None))
if v is not None:
result[o_name] = v
return result | [
"def",
"merge_with",
"(",
"self",
",",
"other",
",",
"multiset_op",
",",
"other_op",
"=",
"None",
")",
":",
"result",
"=",
"FeatureCollection",
"(",
")",
"for",
"ms_name",
"in",
"set",
"(",
"self",
".",
"_counters",
"(",
")",
")",
"|",
"set",
"(",
"other",
".",
"_counters",
"(",
")",
")",
":",
"c1",
"=",
"self",
".",
"get",
"(",
"ms_name",
",",
"None",
")",
"c2",
"=",
"other",
".",
"get",
"(",
"ms_name",
",",
"None",
")",
"if",
"c1",
"is",
"None",
"and",
"c2",
"is",
"not",
"None",
":",
"c1",
"=",
"c2",
".",
"__class__",
"(",
")",
"if",
"c2",
"is",
"None",
"and",
"c1",
"is",
"not",
"None",
":",
"c2",
"=",
"c1",
".",
"__class__",
"(",
")",
"result",
"[",
"ms_name",
"]",
"=",
"multiset_op",
"(",
"c1",
",",
"c2",
")",
"if",
"other_op",
"is",
"not",
"None",
":",
"for",
"o_name",
"in",
"(",
"set",
"(",
"self",
".",
"_not_counters",
"(",
")",
")",
"|",
"set",
"(",
"other",
".",
"_not_counters",
"(",
")",
")",
")",
":",
"v",
"=",
"other_op",
"(",
"self",
".",
"get",
"(",
"o_name",
",",
"None",
")",
",",
"other",
".",
"get",
"(",
"o_name",
",",
"None",
")",
")",
"if",
"v",
"is",
"not",
"None",
":",
"result",
"[",
"o_name",
"]",
"=",
"v",
"return",
"result"
] | Merge this feature collection with another.
Merges two feature collections using the given ``multiset_op``
on each corresponding multiset and returns a new
:class:`FeatureCollection`. The contents of the two original
feature collections are not modified.
For each feature name in both feature sets, if either feature
collection being merged has a :class:`collections.Counter`
instance as its value, then the two values are merged by
calling `multiset_op` with both values as parameters. If
either feature collection has something other than a
:class:`collections.Counter`, and `other_op` is not
:const:`None`, then `other_op` is called with both values to
merge them. If `other_op` is :const:`None` and a feature
is not present in either feature collection with a counter
value, then the feature will not be present in the result.
:param other: The feature collection to merge into ``self``.
:type other: :class:`FeatureCollection`
:param multiset_op: Function to merge two counters
:type multiset_op: fun(Counter, Counter) -> Counter
:param other_op: Function to merge two non-counters
:type other_op: fun(object, object) -> object
:rtype: :class:`FeatureCollection` | [
"Merge",
"this",
"feature",
"collection",
"with",
"another",
"."
] | 3e969d0cb2592fc06afc1c849d2b22283450b5e2 | https://github.com/dossier/dossier.fc/blob/3e969d0cb2592fc06afc1c849d2b22283450b5e2/python/dossier/fc/feature_collection.py#L327-L370 |
249,302 | dossier/dossier.fc | python/dossier/fc/feature_collection.py | FeatureCollection.total | def total(self):
'''
Returns sum of all counts in all features that are multisets.
'''
feats = imap(lambda name: self[name], self._counters())
return sum(chain(*map(lambda mset: map(abs, mset.values()), feats))) | python | def total(self):
'''
Returns sum of all counts in all features that are multisets.
'''
feats = imap(lambda name: self[name], self._counters())
return sum(chain(*map(lambda mset: map(abs, mset.values()), feats))) | [
"def",
"total",
"(",
"self",
")",
":",
"feats",
"=",
"imap",
"(",
"lambda",
"name",
":",
"self",
"[",
"name",
"]",
",",
"self",
".",
"_counters",
"(",
")",
")",
"return",
"sum",
"(",
"chain",
"(",
"*",
"map",
"(",
"lambda",
"mset",
":",
"map",
"(",
"abs",
",",
"mset",
".",
"values",
"(",
")",
")",
",",
"feats",
")",
")",
")"
] | Returns sum of all counts in all features that are multisets. | [
"Returns",
"sum",
"of",
"all",
"counts",
"in",
"all",
"features",
"that",
"are",
"multisets",
"."
] | 3e969d0cb2592fc06afc1c849d2b22283450b5e2 | https://github.com/dossier/dossier.fc/blob/3e969d0cb2592fc06afc1c849d2b22283450b5e2/python/dossier/fc/feature_collection.py#L451-L456 |
249,303 | dossier/dossier.fc | python/dossier/fc/feature_collection.py | FeatureTypeRegistry.add | def add(self, name, obj):
'''Register a new feature serializer.
The feature type should be one of the fixed set of feature
representations, and `name` should be one of ``StringCounter``,
``SparseVector``, or ``DenseVector``. `obj` is a describing
object with three fields: `constructor` is a callable that
creates an empty instance of the representation; `dumps` is
a callable that takes an instance of the representation and
returns a JSON-compatible form made of purely primitive
objects (lists, dictionaries, strings, numbers); and `loads`
is a callable that takes the response from `dumps` and recreates
the original representation.
Note that ``obj.constructor()`` *must* return an
object that is an instance of one of the following
types: ``unicode``, :class:`dossier.fc.StringCounter`,
:class:`dossier.fc.SparseVector` or
:class:`dossier.fc.DenseVector`. If it isn't, a
:exc:`ValueError` is raised.
'''
ro = obj.constructor()
if name not in cbor_names_to_tags:
print(name)
raise ValueError(
'Unsupported feature type name: "%s". '
'Allowed feature type names: %r'
% (name, cbor_names_to_tags.keys()))
if not is_valid_feature_instance(ro):
raise ValueError(
'Constructor for "%s" returned "%r" which has an unknown '
'sub type "%r". (mro: %r). Object must be an instance of '
'one of the allowed types: %r'
% (name, ro, type(ro), type(ro).mro(), ALLOWED_FEATURE_TYPES))
self._registry[name] = {'obj': obj, 'ro': obj.constructor()}
self._inverse[obj.constructor] = name | python | def add(self, name, obj):
'''Register a new feature serializer.
The feature type should be one of the fixed set of feature
representations, and `name` should be one of ``StringCounter``,
``SparseVector``, or ``DenseVector``. `obj` is a describing
object with three fields: `constructor` is a callable that
creates an empty instance of the representation; `dumps` is
a callable that takes an instance of the representation and
returns a JSON-compatible form made of purely primitive
objects (lists, dictionaries, strings, numbers); and `loads`
is a callable that takes the response from `dumps` and recreates
the original representation.
Note that ``obj.constructor()`` *must* return an
object that is an instance of one of the following
types: ``unicode``, :class:`dossier.fc.StringCounter`,
:class:`dossier.fc.SparseVector` or
:class:`dossier.fc.DenseVector`. If it isn't, a
:exc:`ValueError` is raised.
'''
ro = obj.constructor()
if name not in cbor_names_to_tags:
print(name)
raise ValueError(
'Unsupported feature type name: "%s". '
'Allowed feature type names: %r'
% (name, cbor_names_to_tags.keys()))
if not is_valid_feature_instance(ro):
raise ValueError(
'Constructor for "%s" returned "%r" which has an unknown '
'sub type "%r". (mro: %r). Object must be an instance of '
'one of the allowed types: %r'
% (name, ro, type(ro), type(ro).mro(), ALLOWED_FEATURE_TYPES))
self._registry[name] = {'obj': obj, 'ro': obj.constructor()}
self._inverse[obj.constructor] = name | [
"def",
"add",
"(",
"self",
",",
"name",
",",
"obj",
")",
":",
"ro",
"=",
"obj",
".",
"constructor",
"(",
")",
"if",
"name",
"not",
"in",
"cbor_names_to_tags",
":",
"print",
"(",
"name",
")",
"raise",
"ValueError",
"(",
"'Unsupported feature type name: \"%s\". '",
"'Allowed feature type names: %r'",
"%",
"(",
"name",
",",
"cbor_names_to_tags",
".",
"keys",
"(",
")",
")",
")",
"if",
"not",
"is_valid_feature_instance",
"(",
"ro",
")",
":",
"raise",
"ValueError",
"(",
"'Constructor for \"%s\" returned \"%r\" which has an unknown '",
"'sub type \"%r\". (mro: %r). Object must be an instance of '",
"'one of the allowed types: %r'",
"%",
"(",
"name",
",",
"ro",
",",
"type",
"(",
"ro",
")",
",",
"type",
"(",
"ro",
")",
".",
"mro",
"(",
")",
",",
"ALLOWED_FEATURE_TYPES",
")",
")",
"self",
".",
"_registry",
"[",
"name",
"]",
"=",
"{",
"'obj'",
":",
"obj",
",",
"'ro'",
":",
"obj",
".",
"constructor",
"(",
")",
"}",
"self",
".",
"_inverse",
"[",
"obj",
".",
"constructor",
"]",
"=",
"name"
] | Register a new feature serializer.
The feature type should be one of the fixed set of feature
representations, and `name` should be one of ``StringCounter``,
``SparseVector``, or ``DenseVector``. `obj` is a describing
object with three fields: `constructor` is a callable that
creates an empty instance of the representation; `dumps` is
a callable that takes an instance of the representation and
returns a JSON-compatible form made of purely primitive
objects (lists, dictionaries, strings, numbers); and `loads`
is a callable that takes the response from `dumps` and recreates
the original representation.
Note that ``obj.constructor()`` *must* return an
object that is an instance of one of the following
types: ``unicode``, :class:`dossier.fc.StringCounter`,
:class:`dossier.fc.SparseVector` or
:class:`dossier.fc.DenseVector`. If it isn't, a
:exc:`ValueError` is raised. | [
"Register",
"a",
"new",
"feature",
"serializer",
"."
] | 3e969d0cb2592fc06afc1c849d2b22283450b5e2 | https://github.com/dossier/dossier.fc/blob/3e969d0cb2592fc06afc1c849d2b22283450b5e2/python/dossier/fc/feature_collection.py#L585-L620 |
249,304 | nodev-io/nodev.specs | nodev/specs/generic.py | instance_contains | def instance_contains(container, item):
"""Search into instance attributes, properties and return values of no-args methods."""
return item in (member for _, member in inspect.getmembers(container)) | python | def instance_contains(container, item):
"""Search into instance attributes, properties and return values of no-args methods."""
return item in (member for _, member in inspect.getmembers(container)) | [
"def",
"instance_contains",
"(",
"container",
",",
"item",
")",
":",
"return",
"item",
"in",
"(",
"member",
"for",
"_",
",",
"member",
"in",
"inspect",
".",
"getmembers",
"(",
"container",
")",
")"
] | Search into instance attributes, properties and return values of no-args methods. | [
"Search",
"into",
"instance",
"attributes",
"properties",
"and",
"return",
"values",
"of",
"no",
"-",
"args",
"methods",
"."
] | c4740b13f928d2ad39196a4366c98b5f7716ac35 | https://github.com/nodev-io/nodev.specs/blob/c4740b13f928d2ad39196a4366c98b5f7716ac35/nodev/specs/generic.py#L45-L47 |
249,305 | nodev-io/nodev.specs | nodev/specs/generic.py | contains | def contains(container, item):
"""Extends ``operator.contains`` by trying very hard to find ``item`` inside container."""
# equality counts as containment and is usually non destructive
if container == item:
return True
# testing mapping containment is usually non destructive
if isinstance(container, abc.Mapping) and mapping_contains(container, item):
return True
# standard containment except special cases
if isinstance(container, str):
# str __contains__ includes substring match that we don't count as containment
if strict_contains(container, item):
return True
else:
try:
if item in container:
return True
except Exception:
pass
# search matches in generic instances
return instance_contains(container, item) | python | def contains(container, item):
"""Extends ``operator.contains`` by trying very hard to find ``item`` inside container."""
# equality counts as containment and is usually non destructive
if container == item:
return True
# testing mapping containment is usually non destructive
if isinstance(container, abc.Mapping) and mapping_contains(container, item):
return True
# standard containment except special cases
if isinstance(container, str):
# str __contains__ includes substring match that we don't count as containment
if strict_contains(container, item):
return True
else:
try:
if item in container:
return True
except Exception:
pass
# search matches in generic instances
return instance_contains(container, item) | [
"def",
"contains",
"(",
"container",
",",
"item",
")",
":",
"# equality counts as containment and is usually non destructive",
"if",
"container",
"==",
"item",
":",
"return",
"True",
"# testing mapping containment is usually non destructive",
"if",
"isinstance",
"(",
"container",
",",
"abc",
".",
"Mapping",
")",
"and",
"mapping_contains",
"(",
"container",
",",
"item",
")",
":",
"return",
"True",
"# standard containment except special cases",
"if",
"isinstance",
"(",
"container",
",",
"str",
")",
":",
"# str __contains__ includes substring match that we don't count as containment",
"if",
"strict_contains",
"(",
"container",
",",
"item",
")",
":",
"return",
"True",
"else",
":",
"try",
":",
"if",
"item",
"in",
"container",
":",
"return",
"True",
"except",
"Exception",
":",
"pass",
"# search matches in generic instances",
"return",
"instance_contains",
"(",
"container",
",",
"item",
")"
] | Extends ``operator.contains`` by trying very hard to find ``item`` inside container. | [
"Extends",
"operator",
".",
"contains",
"by",
"trying",
"very",
"hard",
"to",
"find",
"item",
"inside",
"container",
"."
] | c4740b13f928d2ad39196a4366c98b5f7716ac35 | https://github.com/nodev-io/nodev.specs/blob/c4740b13f928d2ad39196a4366c98b5f7716ac35/nodev/specs/generic.py#L50-L74 |
249,306 | zaturox/glin | glin/app.py | GlinApp.set_brightness | def set_brightness(self, brightness):
"""set general brightness in range 0...1"""
brightness = min([1.0, max([brightness, 0.0])]) # enforces range 0 ... 1
self.state.brightness = brightness
self._repeat_last_frame()
sequence_number = self.zmq_publisher.publish_brightness(brightness)
logging.debug("Set brightness to {brightPercent:05.1f}%".format(brightPercent=brightness*100))
return (True, sequence_number, "OK") | python | def set_brightness(self, brightness):
"""set general brightness in range 0...1"""
brightness = min([1.0, max([brightness, 0.0])]) # enforces range 0 ... 1
self.state.brightness = brightness
self._repeat_last_frame()
sequence_number = self.zmq_publisher.publish_brightness(brightness)
logging.debug("Set brightness to {brightPercent:05.1f}%".format(brightPercent=brightness*100))
return (True, sequence_number, "OK") | [
"def",
"set_brightness",
"(",
"self",
",",
"brightness",
")",
":",
"brightness",
"=",
"min",
"(",
"[",
"1.0",
",",
"max",
"(",
"[",
"brightness",
",",
"0.0",
"]",
")",
"]",
")",
"# enforces range 0 ... 1",
"self",
".",
"state",
".",
"brightness",
"=",
"brightness",
"self",
".",
"_repeat_last_frame",
"(",
")",
"sequence_number",
"=",
"self",
".",
"zmq_publisher",
".",
"publish_brightness",
"(",
"brightness",
")",
"logging",
".",
"debug",
"(",
"\"Set brightness to {brightPercent:05.1f}%\"",
".",
"format",
"(",
"brightPercent",
"=",
"brightness",
"*",
"100",
")",
")",
"return",
"(",
"True",
",",
"sequence_number",
",",
"\"OK\"",
")"
] | set general brightness in range 0...1 | [
"set",
"general",
"brightness",
"in",
"range",
"0",
"...",
"1"
] | 55214a579c4e4b4d74765f3f6aa2eb815bac1c3b | https://github.com/zaturox/glin/blob/55214a579c4e4b4d74765f3f6aa2eb815bac1c3b/glin/app.py#L47-L54 |
249,307 | zaturox/glin | glin/app.py | GlinApp.register_animation | def register_animation(self, animation_class):
"""Add a new animation"""
self.state.animationClasses.append(animation_class)
return len(self.state.animationClasses) - 1 | python | def register_animation(self, animation_class):
"""Add a new animation"""
self.state.animationClasses.append(animation_class)
return len(self.state.animationClasses) - 1 | [
"def",
"register_animation",
"(",
"self",
",",
"animation_class",
")",
":",
"self",
".",
"state",
".",
"animationClasses",
".",
"append",
"(",
"animation_class",
")",
"return",
"len",
"(",
"self",
".",
"state",
".",
"animationClasses",
")",
"-",
"1"
] | Add a new animation | [
"Add",
"a",
"new",
"animation"
] | 55214a579c4e4b4d74765f3f6aa2eb815bac1c3b | https://github.com/zaturox/glin/blob/55214a579c4e4b4d74765f3f6aa2eb815bac1c3b/glin/app.py#L56-L59 |
249,308 | zaturox/glin | glin/app.py | GlinApp.add_scene | def add_scene(self, animation_id, name, color, velocity, config):
"""Add a new scene, returns Scene ID"""
# check arguments
if animation_id < 0 or animation_id >= len(self.state.animationClasses):
err_msg = "Requested to register scene with invalid Animation ID. Out of range."
logging.info(err_msg)
return(False, 0, err_msg)
if self.state.animationClasses[animation_id].check_config(config) is False:
err_msg = "Requested to register scene with invalid configuration."
logging.info(err_msg)
return(False, 0, err_msg)
self.state.sceneIdCtr += 1
self.state.scenes[self.state.sceneIdCtr] = Scene(animation_id, name, color, velocity, config)
sequence_number = self.zmq_publisher.publish_scene_add(self.state.sceneIdCtr, animation_id, name, color, velocity, config)
logging.debug("Registered new scene.")
# set this scene as active scene if none is configured yet
if self.state.activeSceneId is None:
self.set_scene_active(self.state.sceneIdCtr)
return (True, sequence_number, "OK") | python | def add_scene(self, animation_id, name, color, velocity, config):
"""Add a new scene, returns Scene ID"""
# check arguments
if animation_id < 0 or animation_id >= len(self.state.animationClasses):
err_msg = "Requested to register scene with invalid Animation ID. Out of range."
logging.info(err_msg)
return(False, 0, err_msg)
if self.state.animationClasses[animation_id].check_config(config) is False:
err_msg = "Requested to register scene with invalid configuration."
logging.info(err_msg)
return(False, 0, err_msg)
self.state.sceneIdCtr += 1
self.state.scenes[self.state.sceneIdCtr] = Scene(animation_id, name, color, velocity, config)
sequence_number = self.zmq_publisher.publish_scene_add(self.state.sceneIdCtr, animation_id, name, color, velocity, config)
logging.debug("Registered new scene.")
# set this scene as active scene if none is configured yet
if self.state.activeSceneId is None:
self.set_scene_active(self.state.sceneIdCtr)
return (True, sequence_number, "OK") | [
"def",
"add_scene",
"(",
"self",
",",
"animation_id",
",",
"name",
",",
"color",
",",
"velocity",
",",
"config",
")",
":",
"# check arguments",
"if",
"animation_id",
"<",
"0",
"or",
"animation_id",
">=",
"len",
"(",
"self",
".",
"state",
".",
"animationClasses",
")",
":",
"err_msg",
"=",
"\"Requested to register scene with invalid Animation ID. Out of range.\"",
"logging",
".",
"info",
"(",
"err_msg",
")",
"return",
"(",
"False",
",",
"0",
",",
"err_msg",
")",
"if",
"self",
".",
"state",
".",
"animationClasses",
"[",
"animation_id",
"]",
".",
"check_config",
"(",
"config",
")",
"is",
"False",
":",
"err_msg",
"=",
"\"Requested to register scene with invalid configuration.\"",
"logging",
".",
"info",
"(",
"err_msg",
")",
"return",
"(",
"False",
",",
"0",
",",
"err_msg",
")",
"self",
".",
"state",
".",
"sceneIdCtr",
"+=",
"1",
"self",
".",
"state",
".",
"scenes",
"[",
"self",
".",
"state",
".",
"sceneIdCtr",
"]",
"=",
"Scene",
"(",
"animation_id",
",",
"name",
",",
"color",
",",
"velocity",
",",
"config",
")",
"sequence_number",
"=",
"self",
".",
"zmq_publisher",
".",
"publish_scene_add",
"(",
"self",
".",
"state",
".",
"sceneIdCtr",
",",
"animation_id",
",",
"name",
",",
"color",
",",
"velocity",
",",
"config",
")",
"logging",
".",
"debug",
"(",
"\"Registered new scene.\"",
")",
"# set this scene as active scene if none is configured yet",
"if",
"self",
".",
"state",
".",
"activeSceneId",
"is",
"None",
":",
"self",
".",
"set_scene_active",
"(",
"self",
".",
"state",
".",
"sceneIdCtr",
")",
"return",
"(",
"True",
",",
"sequence_number",
",",
"\"OK\"",
")"
] | Add a new scene, returns Scene ID | [
"Add",
"a",
"new",
"scene",
"returns",
"Scene",
"ID"
] | 55214a579c4e4b4d74765f3f6aa2eb815bac1c3b | https://github.com/zaturox/glin/blob/55214a579c4e4b4d74765f3f6aa2eb815bac1c3b/glin/app.py#L61-L80 |
249,309 | zaturox/glin | glin/app.py | GlinApp.remove_scene | def remove_scene(self, scene_id):
"""remove a scene by Scene ID"""
if self.state.activeSceneId == scene_id:
err_msg = "Requested to delete scene {sceneNum}, which is currently active. Cannot delete active scene.".format(sceneNum=scene_id)
logging.info(err_msg)
return(False, 0, err_msg)
try:
del self.state.scenes[scene_id]
logging.debug("Deleted scene {sceneNum}".format(sceneNum=scene_id))
except KeyError:
err_msg = "Requested to delete scene {sceneNum}, which does not exist".format(sceneNum=scene_id)
logging.info(err_msg)
return(False, 0, err_msg)
# if we are here, we deleted a scene, so publish it
sequence_number = self.zmq_publisher.publish_scene_remove(scene_id)
logging.debug("Removed scene {sceneNum}".format(sceneNum=scene_id))
return (True, sequence_number, "OK") | python | def remove_scene(self, scene_id):
"""remove a scene by Scene ID"""
if self.state.activeSceneId == scene_id:
err_msg = "Requested to delete scene {sceneNum}, which is currently active. Cannot delete active scene.".format(sceneNum=scene_id)
logging.info(err_msg)
return(False, 0, err_msg)
try:
del self.state.scenes[scene_id]
logging.debug("Deleted scene {sceneNum}".format(sceneNum=scene_id))
except KeyError:
err_msg = "Requested to delete scene {sceneNum}, which does not exist".format(sceneNum=scene_id)
logging.info(err_msg)
return(False, 0, err_msg)
# if we are here, we deleted a scene, so publish it
sequence_number = self.zmq_publisher.publish_scene_remove(scene_id)
logging.debug("Removed scene {sceneNum}".format(sceneNum=scene_id))
return (True, sequence_number, "OK") | [
"def",
"remove_scene",
"(",
"self",
",",
"scene_id",
")",
":",
"if",
"self",
".",
"state",
".",
"activeSceneId",
"==",
"scene_id",
":",
"err_msg",
"=",
"\"Requested to delete scene {sceneNum}, which is currently active. Cannot delete active scene.\"",
".",
"format",
"(",
"sceneNum",
"=",
"scene_id",
")",
"logging",
".",
"info",
"(",
"err_msg",
")",
"return",
"(",
"False",
",",
"0",
",",
"err_msg",
")",
"try",
":",
"del",
"self",
".",
"state",
".",
"scenes",
"[",
"scene_id",
"]",
"logging",
".",
"debug",
"(",
"\"Deleted scene {sceneNum}\"",
".",
"format",
"(",
"sceneNum",
"=",
"scene_id",
")",
")",
"except",
"KeyError",
":",
"err_msg",
"=",
"\"Requested to delete scene {sceneNum}, which does not exist\"",
".",
"format",
"(",
"sceneNum",
"=",
"scene_id",
")",
"logging",
".",
"info",
"(",
"err_msg",
")",
"return",
"(",
"False",
",",
"0",
",",
"err_msg",
")",
"# if we are here, we deleted a scene, so publish it",
"sequence_number",
"=",
"self",
".",
"zmq_publisher",
".",
"publish_scene_remove",
"(",
"scene_id",
")",
"logging",
".",
"debug",
"(",
"\"Removed scene {sceneNum}\"",
".",
"format",
"(",
"sceneNum",
"=",
"scene_id",
")",
")",
"return",
"(",
"True",
",",
"sequence_number",
",",
"\"OK\"",
")"
] | remove a scene by Scene ID | [
"remove",
"a",
"scene",
"by",
"Scene",
"ID"
] | 55214a579c4e4b4d74765f3f6aa2eb815bac1c3b | https://github.com/zaturox/glin/blob/55214a579c4e4b4d74765f3f6aa2eb815bac1c3b/glin/app.py#L82-L98 |
249,310 | zaturox/glin | glin/app.py | GlinApp.set_scene_name | def set_scene_name(self, scene_id, name):
"""rename a scene by scene ID"""
if not scene_id in self.state.scenes: # does that scene_id exist?
err_msg = "Requested to rename scene {sceneNum}, which does not exist".format(sceneNum=scene_id)
logging.info(err_msg)
return(False, 0, err_msg)
self.state.scenes[scene_id] = self.state.scenes[scene_id]._replace(name=name) # TODO: is there a better solution?
sequence_number = self.zmq_publisher.publish_scene_name(scene_id, name)
logging.debug("Renamed scene {sceneNum}".format(sceneNum=scene_id))
return (True, sequence_number, "OK") | python | def set_scene_name(self, scene_id, name):
"""rename a scene by scene ID"""
if not scene_id in self.state.scenes: # does that scene_id exist?
err_msg = "Requested to rename scene {sceneNum}, which does not exist".format(sceneNum=scene_id)
logging.info(err_msg)
return(False, 0, err_msg)
self.state.scenes[scene_id] = self.state.scenes[scene_id]._replace(name=name) # TODO: is there a better solution?
sequence_number = self.zmq_publisher.publish_scene_name(scene_id, name)
logging.debug("Renamed scene {sceneNum}".format(sceneNum=scene_id))
return (True, sequence_number, "OK") | [
"def",
"set_scene_name",
"(",
"self",
",",
"scene_id",
",",
"name",
")",
":",
"if",
"not",
"scene_id",
"in",
"self",
".",
"state",
".",
"scenes",
":",
"# does that scene_id exist?",
"err_msg",
"=",
"\"Requested to rename scene {sceneNum}, which does not exist\"",
".",
"format",
"(",
"sceneNum",
"=",
"scene_id",
")",
"logging",
".",
"info",
"(",
"err_msg",
")",
"return",
"(",
"False",
",",
"0",
",",
"err_msg",
")",
"self",
".",
"state",
".",
"scenes",
"[",
"scene_id",
"]",
"=",
"self",
".",
"state",
".",
"scenes",
"[",
"scene_id",
"]",
".",
"_replace",
"(",
"name",
"=",
"name",
")",
"# TODO: is there a better solution?",
"sequence_number",
"=",
"self",
".",
"zmq_publisher",
".",
"publish_scene_name",
"(",
"scene_id",
",",
"name",
")",
"logging",
".",
"debug",
"(",
"\"Renamed scene {sceneNum}\"",
".",
"format",
"(",
"sceneNum",
"=",
"scene_id",
")",
")",
"return",
"(",
"True",
",",
"sequence_number",
",",
"\"OK\"",
")"
] | rename a scene by scene ID | [
"rename",
"a",
"scene",
"by",
"scene",
"ID"
] | 55214a579c4e4b4d74765f3f6aa2eb815bac1c3b | https://github.com/zaturox/glin/blob/55214a579c4e4b4d74765f3f6aa2eb815bac1c3b/glin/app.py#L100-L109 |
249,311 | zaturox/glin | glin/app.py | GlinApp.set_scene_active | def set_scene_active(self, scene_id):
"""sets the active scene by scene ID"""
if self.state.activeSceneId != scene_id: # do nothing if scene has not changed
self._deactivate_scene()
sequence_number = self.zmq_publisher.publish_active_scene(scene_id)
self.state.activeSceneId = scene_id
if self.state.mainswitch is True: # activate scene only if we are switched on
self._activate_scene()
logging.debug("Set scene {sceneNum} as active scene".format(sceneNum=scene_id))
return (True, sequence_number, "OK")
else:
logging.debug("Scene {sceneNum} already is active scene".format(sceneNum=scene_id))
return (False, 0, "This already is the activated scene.") | python | def set_scene_active(self, scene_id):
"""sets the active scene by scene ID"""
if self.state.activeSceneId != scene_id: # do nothing if scene has not changed
self._deactivate_scene()
sequence_number = self.zmq_publisher.publish_active_scene(scene_id)
self.state.activeSceneId = scene_id
if self.state.mainswitch is True: # activate scene only if we are switched on
self._activate_scene()
logging.debug("Set scene {sceneNum} as active scene".format(sceneNum=scene_id))
return (True, sequence_number, "OK")
else:
logging.debug("Scene {sceneNum} already is active scene".format(sceneNum=scene_id))
return (False, 0, "This already is the activated scene.") | [
"def",
"set_scene_active",
"(",
"self",
",",
"scene_id",
")",
":",
"if",
"self",
".",
"state",
".",
"activeSceneId",
"!=",
"scene_id",
":",
"# do nothing if scene has not changed",
"self",
".",
"_deactivate_scene",
"(",
")",
"sequence_number",
"=",
"self",
".",
"zmq_publisher",
".",
"publish_active_scene",
"(",
"scene_id",
")",
"self",
".",
"state",
".",
"activeSceneId",
"=",
"scene_id",
"if",
"self",
".",
"state",
".",
"mainswitch",
"is",
"True",
":",
"# activate scene only if we are switched on",
"self",
".",
"_activate_scene",
"(",
")",
"logging",
".",
"debug",
"(",
"\"Set scene {sceneNum} as active scene\"",
".",
"format",
"(",
"sceneNum",
"=",
"scene_id",
")",
")",
"return",
"(",
"True",
",",
"sequence_number",
",",
"\"OK\"",
")",
"else",
":",
"logging",
".",
"debug",
"(",
"\"Scene {sceneNum} already is active scene\"",
".",
"format",
"(",
"sceneNum",
"=",
"scene_id",
")",
")",
"return",
"(",
"False",
",",
"0",
",",
"\"This already is the activated scene.\"",
")"
] | sets the active scene by scene ID | [
"sets",
"the",
"active",
"scene",
"by",
"scene",
"ID"
] | 55214a579c4e4b4d74765f3f6aa2eb815bac1c3b | https://github.com/zaturox/glin/blob/55214a579c4e4b4d74765f3f6aa2eb815bac1c3b/glin/app.py#L152-L164 |
249,312 | zaturox/glin | glin/app.py | GlinApp.set_mainswitch_state | def set_mainswitch_state(self, state):
"""Turns output on or off. Also turns hardware on ir off"""
if self.state.mainswitch == state:
err_msg = "MainSwitch unchanged, already is {sState}".format(sState="On" if state else "Off") # fo obar lorem ipsum
logging.debug(err_msg) # fo obar lorem ipsum
return (False, 0, err_msg) # because nothing changed
self.state.mainswitch = state
sequence_number = self.zmq_publisher.publish_mainswitch_state(state)
logging.debug("MainSwitch toggled, new state is {sState}".format(sState="On" if state else "Off")) # fo obar lorem ipsum
if state is True:
self.hw_communication.switch_on()
self._activate_scene() # reinit scene
else:
self._deactivate_scene()
self.hw_communication.switch_off()
return (True, sequence_number, "OK") | python | def set_mainswitch_state(self, state):
"""Turns output on or off. Also turns hardware on ir off"""
if self.state.mainswitch == state:
err_msg = "MainSwitch unchanged, already is {sState}".format(sState="On" if state else "Off") # fo obar lorem ipsum
logging.debug(err_msg) # fo obar lorem ipsum
return (False, 0, err_msg) # because nothing changed
self.state.mainswitch = state
sequence_number = self.zmq_publisher.publish_mainswitch_state(state)
logging.debug("MainSwitch toggled, new state is {sState}".format(sState="On" if state else "Off")) # fo obar lorem ipsum
if state is True:
self.hw_communication.switch_on()
self._activate_scene() # reinit scene
else:
self._deactivate_scene()
self.hw_communication.switch_off()
return (True, sequence_number, "OK") | [
"def",
"set_mainswitch_state",
"(",
"self",
",",
"state",
")",
":",
"if",
"self",
".",
"state",
".",
"mainswitch",
"==",
"state",
":",
"err_msg",
"=",
"\"MainSwitch unchanged, already is {sState}\"",
".",
"format",
"(",
"sState",
"=",
"\"On\"",
"if",
"state",
"else",
"\"Off\"",
")",
"# fo obar lorem ipsum",
"logging",
".",
"debug",
"(",
"err_msg",
")",
"# fo obar lorem ipsum",
"return",
"(",
"False",
",",
"0",
",",
"err_msg",
")",
"# because nothing changed",
"self",
".",
"state",
".",
"mainswitch",
"=",
"state",
"sequence_number",
"=",
"self",
".",
"zmq_publisher",
".",
"publish_mainswitch_state",
"(",
"state",
")",
"logging",
".",
"debug",
"(",
"\"MainSwitch toggled, new state is {sState}\"",
".",
"format",
"(",
"sState",
"=",
"\"On\"",
"if",
"state",
"else",
"\"Off\"",
")",
")",
"# fo obar lorem ipsum",
"if",
"state",
"is",
"True",
":",
"self",
".",
"hw_communication",
".",
"switch_on",
"(",
")",
"self",
".",
"_activate_scene",
"(",
")",
"# reinit scene",
"else",
":",
"self",
".",
"_deactivate_scene",
"(",
")",
"self",
".",
"hw_communication",
".",
"switch_off",
"(",
")",
"return",
"(",
"True",
",",
"sequence_number",
",",
"\"OK\"",
")"
] | Turns output on or off. Also turns hardware on ir off | [
"Turns",
"output",
"on",
"or",
"off",
".",
"Also",
"turns",
"hardware",
"on",
"ir",
"off"
] | 55214a579c4e4b4d74765f3f6aa2eb815bac1c3b | https://github.com/zaturox/glin/blob/55214a579c4e4b4d74765f3f6aa2eb815bac1c3b/glin/app.py#L166-L181 |
249,313 | zaturox/glin | glin/app.py | GlinApp.execute | def execute(self):
"""Execute Main Loop"""
try:
logging.debug("Entering IOLoop")
self.loop.start()
logging.debug("Leaving IOLoop")
except KeyboardInterrupt:
logging.debug("Leaving IOLoop by KeyboardInterrupt")
finally:
self.hw_communication.disconnect() | python | def execute(self):
"""Execute Main Loop"""
try:
logging.debug("Entering IOLoop")
self.loop.start()
logging.debug("Leaving IOLoop")
except KeyboardInterrupt:
logging.debug("Leaving IOLoop by KeyboardInterrupt")
finally:
self.hw_communication.disconnect() | [
"def",
"execute",
"(",
"self",
")",
":",
"try",
":",
"logging",
".",
"debug",
"(",
"\"Entering IOLoop\"",
")",
"self",
".",
"loop",
".",
"start",
"(",
")",
"logging",
".",
"debug",
"(",
"\"Leaving IOLoop\"",
")",
"except",
"KeyboardInterrupt",
":",
"logging",
".",
"debug",
"(",
"\"Leaving IOLoop by KeyboardInterrupt\"",
")",
"finally",
":",
"self",
".",
"hw_communication",
".",
"disconnect",
"(",
")"
] | Execute Main Loop | [
"Execute",
"Main",
"Loop"
] | 55214a579c4e4b4d74765f3f6aa2eb815bac1c3b | https://github.com/zaturox/glin/blob/55214a579c4e4b4d74765f3f6aa2eb815bac1c3b/glin/app.py#L238-L247 |
249,314 | zaturox/glin | glin/app.py | GlinAppZmqPublisher.publish_brightness | def publish_brightness(self, brightness):
"""publish changed brightness"""
self.sequence_number += 1
self.publisher.send_multipart(msgs.MessageBuilder.brightness(self.sequence_number, brightness))
return self.sequence_number | python | def publish_brightness(self, brightness):
"""publish changed brightness"""
self.sequence_number += 1
self.publisher.send_multipart(msgs.MessageBuilder.brightness(self.sequence_number, brightness))
return self.sequence_number | [
"def",
"publish_brightness",
"(",
"self",
",",
"brightness",
")",
":",
"self",
".",
"sequence_number",
"+=",
"1",
"self",
".",
"publisher",
".",
"send_multipart",
"(",
"msgs",
".",
"MessageBuilder",
".",
"brightness",
"(",
"self",
".",
"sequence_number",
",",
"brightness",
")",
")",
"return",
"self",
".",
"sequence_number"
] | publish changed brightness | [
"publish",
"changed",
"brightness"
] | 55214a579c4e4b4d74765f3f6aa2eb815bac1c3b | https://github.com/zaturox/glin/blob/55214a579c4e4b4d74765f3f6aa2eb815bac1c3b/glin/app.py#L263-L267 |
249,315 | zaturox/glin | glin/app.py | GlinAppZmqPublisher.publish_mainswitch_state | def publish_mainswitch_state(self, state):
"""publish changed mainswitch state"""
self.sequence_number += 1
self.publisher.send_multipart(msgs.MessageBuilder.mainswitch_state(self.sequence_number, state))
return self.sequence_number | python | def publish_mainswitch_state(self, state):
"""publish changed mainswitch state"""
self.sequence_number += 1
self.publisher.send_multipart(msgs.MessageBuilder.mainswitch_state(self.sequence_number, state))
return self.sequence_number | [
"def",
"publish_mainswitch_state",
"(",
"self",
",",
"state",
")",
":",
"self",
".",
"sequence_number",
"+=",
"1",
"self",
".",
"publisher",
".",
"send_multipart",
"(",
"msgs",
".",
"MessageBuilder",
".",
"mainswitch_state",
"(",
"self",
".",
"sequence_number",
",",
"state",
")",
")",
"return",
"self",
".",
"sequence_number"
] | publish changed mainswitch state | [
"publish",
"changed",
"mainswitch",
"state"
] | 55214a579c4e4b4d74765f3f6aa2eb815bac1c3b | https://github.com/zaturox/glin/blob/55214a579c4e4b4d74765f3f6aa2eb815bac1c3b/glin/app.py#L268-L272 |
249,316 | zaturox/glin | glin/app.py | GlinAppZmqPublisher.publish_active_scene | def publish_active_scene(self, scene_id):
"""publish changed active scene"""
self.sequence_number += 1
self.publisher.send_multipart(msgs.MessageBuilder.scene_active(self.sequence_number, scene_id))
return self.sequence_number | python | def publish_active_scene(self, scene_id):
"""publish changed active scene"""
self.sequence_number += 1
self.publisher.send_multipart(msgs.MessageBuilder.scene_active(self.sequence_number, scene_id))
return self.sequence_number | [
"def",
"publish_active_scene",
"(",
"self",
",",
"scene_id",
")",
":",
"self",
".",
"sequence_number",
"+=",
"1",
"self",
".",
"publisher",
".",
"send_multipart",
"(",
"msgs",
".",
"MessageBuilder",
".",
"scene_active",
"(",
"self",
".",
"sequence_number",
",",
"scene_id",
")",
")",
"return",
"self",
".",
"sequence_number"
] | publish changed active scene | [
"publish",
"changed",
"active",
"scene"
] | 55214a579c4e4b4d74765f3f6aa2eb815bac1c3b | https://github.com/zaturox/glin/blob/55214a579c4e4b4d74765f3f6aa2eb815bac1c3b/glin/app.py#L273-L277 |
249,317 | zaturox/glin | glin/app.py | GlinAppZmqPublisher.publish_scene_add | def publish_scene_add(self, scene_id, animation_id, name, color, velocity, config):
"""publish added scene"""
self.sequence_number += 1
self.publisher.send_multipart(msgs.MessageBuilder.scene_add(self.sequence_number, scene_id, animation_id, name, color, velocity, config))
return self.sequence_number | python | def publish_scene_add(self, scene_id, animation_id, name, color, velocity, config):
"""publish added scene"""
self.sequence_number += 1
self.publisher.send_multipart(msgs.MessageBuilder.scene_add(self.sequence_number, scene_id, animation_id, name, color, velocity, config))
return self.sequence_number | [
"def",
"publish_scene_add",
"(",
"self",
",",
"scene_id",
",",
"animation_id",
",",
"name",
",",
"color",
",",
"velocity",
",",
"config",
")",
":",
"self",
".",
"sequence_number",
"+=",
"1",
"self",
".",
"publisher",
".",
"send_multipart",
"(",
"msgs",
".",
"MessageBuilder",
".",
"scene_add",
"(",
"self",
".",
"sequence_number",
",",
"scene_id",
",",
"animation_id",
",",
"name",
",",
"color",
",",
"velocity",
",",
"config",
")",
")",
"return",
"self",
".",
"sequence_number"
] | publish added scene | [
"publish",
"added",
"scene"
] | 55214a579c4e4b4d74765f3f6aa2eb815bac1c3b | https://github.com/zaturox/glin/blob/55214a579c4e4b4d74765f3f6aa2eb815bac1c3b/glin/app.py#L278-L282 |
249,318 | zaturox/glin | glin/app.py | GlinAppZmqPublisher.publish_scene_remove | def publish_scene_remove(self, scene_id):
"""publish the removal of a scene"""
self.sequence_number += 1
self.publisher.send_multipart(msgs.MessageBuilder.scene_remove(self.sequence_number, scene_id))
return self.sequence_number | python | def publish_scene_remove(self, scene_id):
"""publish the removal of a scene"""
self.sequence_number += 1
self.publisher.send_multipart(msgs.MessageBuilder.scene_remove(self.sequence_number, scene_id))
return self.sequence_number | [
"def",
"publish_scene_remove",
"(",
"self",
",",
"scene_id",
")",
":",
"self",
".",
"sequence_number",
"+=",
"1",
"self",
".",
"publisher",
".",
"send_multipart",
"(",
"msgs",
".",
"MessageBuilder",
".",
"scene_remove",
"(",
"self",
".",
"sequence_number",
",",
"scene_id",
")",
")",
"return",
"self",
".",
"sequence_number"
] | publish the removal of a scene | [
"publish",
"the",
"removal",
"of",
"a",
"scene"
] | 55214a579c4e4b4d74765f3f6aa2eb815bac1c3b | https://github.com/zaturox/glin/blob/55214a579c4e4b4d74765f3f6aa2eb815bac1c3b/glin/app.py#L283-L287 |
249,319 | zaturox/glin | glin/app.py | GlinAppZmqPublisher.publish_scene_name | def publish_scene_name(self, scene_id, name):
"""publish a changed scene name"""
self.sequence_number += 1
self.publisher.send_multipart(msgs.MessageBuilder.scene_name(self.sequence_number, scene_id, name))
return self.sequence_number | python | def publish_scene_name(self, scene_id, name):
"""publish a changed scene name"""
self.sequence_number += 1
self.publisher.send_multipart(msgs.MessageBuilder.scene_name(self.sequence_number, scene_id, name))
return self.sequence_number | [
"def",
"publish_scene_name",
"(",
"self",
",",
"scene_id",
",",
"name",
")",
":",
"self",
".",
"sequence_number",
"+=",
"1",
"self",
".",
"publisher",
".",
"send_multipart",
"(",
"msgs",
".",
"MessageBuilder",
".",
"scene_name",
"(",
"self",
".",
"sequence_number",
",",
"scene_id",
",",
"name",
")",
")",
"return",
"self",
".",
"sequence_number"
] | publish a changed scene name | [
"publish",
"a",
"changed",
"scene",
"name"
] | 55214a579c4e4b4d74765f3f6aa2eb815bac1c3b | https://github.com/zaturox/glin/blob/55214a579c4e4b4d74765f3f6aa2eb815bac1c3b/glin/app.py#L288-L292 |
249,320 | zaturox/glin | glin/app.py | GlinAppZmqPublisher.publish_scene_config | def publish_scene_config(self, scene_id, config):
"""publish a changed scene configuration"""
self.sequence_number += 1
self.publisher.send_multipart(msgs.MessageBuilder.scene_config(self.sequence_number, scene_id, config))
return self.sequence_number | python | def publish_scene_config(self, scene_id, config):
"""publish a changed scene configuration"""
self.sequence_number += 1
self.publisher.send_multipart(msgs.MessageBuilder.scene_config(self.sequence_number, scene_id, config))
return self.sequence_number | [
"def",
"publish_scene_config",
"(",
"self",
",",
"scene_id",
",",
"config",
")",
":",
"self",
".",
"sequence_number",
"+=",
"1",
"self",
".",
"publisher",
".",
"send_multipart",
"(",
"msgs",
".",
"MessageBuilder",
".",
"scene_config",
"(",
"self",
".",
"sequence_number",
",",
"scene_id",
",",
"config",
")",
")",
"return",
"self",
".",
"sequence_number"
] | publish a changed scene configuration | [
"publish",
"a",
"changed",
"scene",
"configuration"
] | 55214a579c4e4b4d74765f3f6aa2eb815bac1c3b | https://github.com/zaturox/glin/blob/55214a579c4e4b4d74765f3f6aa2eb815bac1c3b/glin/app.py#L293-L297 |
249,321 | zaturox/glin | glin/app.py | GlinAppZmqPublisher.publish_scene_color | def publish_scene_color(self, scene_id, color):
"""publish a changed scene color"""
self.sequence_number += 1
self.publisher.send_multipart(msgs.MessageBuilder.scene_color(self.sequence_number, scene_id, color))
return self.sequence_number | python | def publish_scene_color(self, scene_id, color):
"""publish a changed scene color"""
self.sequence_number += 1
self.publisher.send_multipart(msgs.MessageBuilder.scene_color(self.sequence_number, scene_id, color))
return self.sequence_number | [
"def",
"publish_scene_color",
"(",
"self",
",",
"scene_id",
",",
"color",
")",
":",
"self",
".",
"sequence_number",
"+=",
"1",
"self",
".",
"publisher",
".",
"send_multipart",
"(",
"msgs",
".",
"MessageBuilder",
".",
"scene_color",
"(",
"self",
".",
"sequence_number",
",",
"scene_id",
",",
"color",
")",
")",
"return",
"self",
".",
"sequence_number"
] | publish a changed scene color | [
"publish",
"a",
"changed",
"scene",
"color"
] | 55214a579c4e4b4d74765f3f6aa2eb815bac1c3b | https://github.com/zaturox/glin/blob/55214a579c4e4b4d74765f3f6aa2eb815bac1c3b/glin/app.py#L298-L302 |
249,322 | zaturox/glin | glin/app.py | GlinAppZmqPublisher.publish_scene_velocity | def publish_scene_velocity(self, scene_id, velocity):
"""publish a changed scene velovity"""
self.sequence_number += 1
self.publisher.send_multipart(msgs.MessageBuilder.scene_velocity(self.sequence_number, scene_id, velocity))
return self.sequence_number | python | def publish_scene_velocity(self, scene_id, velocity):
"""publish a changed scene velovity"""
self.sequence_number += 1
self.publisher.send_multipart(msgs.MessageBuilder.scene_velocity(self.sequence_number, scene_id, velocity))
return self.sequence_number | [
"def",
"publish_scene_velocity",
"(",
"self",
",",
"scene_id",
",",
"velocity",
")",
":",
"self",
".",
"sequence_number",
"+=",
"1",
"self",
".",
"publisher",
".",
"send_multipart",
"(",
"msgs",
".",
"MessageBuilder",
".",
"scene_velocity",
"(",
"self",
".",
"sequence_number",
",",
"scene_id",
",",
"velocity",
")",
")",
"return",
"self",
".",
"sequence_number"
] | publish a changed scene velovity | [
"publish",
"a",
"changed",
"scene",
"velovity"
] | 55214a579c4e4b4d74765f3f6aa2eb815bac1c3b | https://github.com/zaturox/glin/blob/55214a579c4e4b4d74765f3f6aa2eb815bac1c3b/glin/app.py#L303-L307 |
249,323 | zaturox/glin | glin/app.py | GlinAppZmqPublisher.handle_snapshot | def handle_snapshot(self, msg):
"""Handles a snapshot request"""
logging.debug("Sending state snapshot request")
identity = msg[0]
self.snapshot.send_multipart([identity] + msgs.MessageBuilder.mainswitch_state(self.sequence_number, self.app.state.mainswitch))
self.snapshot.send_multipart([identity] + msgs.MessageBuilder.brightness(self.sequence_number, self.app.state.brightness))
for animation_id, anim in enumerate(self.app.state.animationClasses):
self.snapshot.send_multipart([identity] + msgs.MessageBuilder.animation_add(self.sequence_number, animation_id, anim.name))
for scene_id, scene in self.app.state.scenes.items():
self.snapshot.send_multipart([identity] + msgs.MessageBuilder.scene_add(
self.sequence_number, scene_id, scene.animation_id, scene.name, scene.color, scene.velocity, scene.config))
self.snapshot.send_multipart([identity] + msgs.MessageBuilder.scene_active(
self.sequence_number, 0 if self.app.state.activeSceneId is None else self.app.state.activeSceneId)) | python | def handle_snapshot(self, msg):
"""Handles a snapshot request"""
logging.debug("Sending state snapshot request")
identity = msg[0]
self.snapshot.send_multipart([identity] + msgs.MessageBuilder.mainswitch_state(self.sequence_number, self.app.state.mainswitch))
self.snapshot.send_multipart([identity] + msgs.MessageBuilder.brightness(self.sequence_number, self.app.state.brightness))
for animation_id, anim in enumerate(self.app.state.animationClasses):
self.snapshot.send_multipart([identity] + msgs.MessageBuilder.animation_add(self.sequence_number, animation_id, anim.name))
for scene_id, scene in self.app.state.scenes.items():
self.snapshot.send_multipart([identity] + msgs.MessageBuilder.scene_add(
self.sequence_number, scene_id, scene.animation_id, scene.name, scene.color, scene.velocity, scene.config))
self.snapshot.send_multipart([identity] + msgs.MessageBuilder.scene_active(
self.sequence_number, 0 if self.app.state.activeSceneId is None else self.app.state.activeSceneId)) | [
"def",
"handle_snapshot",
"(",
"self",
",",
"msg",
")",
":",
"logging",
".",
"debug",
"(",
"\"Sending state snapshot request\"",
")",
"identity",
"=",
"msg",
"[",
"0",
"]",
"self",
".",
"snapshot",
".",
"send_multipart",
"(",
"[",
"identity",
"]",
"+",
"msgs",
".",
"MessageBuilder",
".",
"mainswitch_state",
"(",
"self",
".",
"sequence_number",
",",
"self",
".",
"app",
".",
"state",
".",
"mainswitch",
")",
")",
"self",
".",
"snapshot",
".",
"send_multipart",
"(",
"[",
"identity",
"]",
"+",
"msgs",
".",
"MessageBuilder",
".",
"brightness",
"(",
"self",
".",
"sequence_number",
",",
"self",
".",
"app",
".",
"state",
".",
"brightness",
")",
")",
"for",
"animation_id",
",",
"anim",
"in",
"enumerate",
"(",
"self",
".",
"app",
".",
"state",
".",
"animationClasses",
")",
":",
"self",
".",
"snapshot",
".",
"send_multipart",
"(",
"[",
"identity",
"]",
"+",
"msgs",
".",
"MessageBuilder",
".",
"animation_add",
"(",
"self",
".",
"sequence_number",
",",
"animation_id",
",",
"anim",
".",
"name",
")",
")",
"for",
"scene_id",
",",
"scene",
"in",
"self",
".",
"app",
".",
"state",
".",
"scenes",
".",
"items",
"(",
")",
":",
"self",
".",
"snapshot",
".",
"send_multipart",
"(",
"[",
"identity",
"]",
"+",
"msgs",
".",
"MessageBuilder",
".",
"scene_add",
"(",
"self",
".",
"sequence_number",
",",
"scene_id",
",",
"scene",
".",
"animation_id",
",",
"scene",
".",
"name",
",",
"scene",
".",
"color",
",",
"scene",
".",
"velocity",
",",
"scene",
".",
"config",
")",
")",
"self",
".",
"snapshot",
".",
"send_multipart",
"(",
"[",
"identity",
"]",
"+",
"msgs",
".",
"MessageBuilder",
".",
"scene_active",
"(",
"self",
".",
"sequence_number",
",",
"0",
"if",
"self",
".",
"app",
".",
"state",
".",
"activeSceneId",
"is",
"None",
"else",
"self",
".",
"app",
".",
"state",
".",
"activeSceneId",
")",
")"
] | Handles a snapshot request | [
"Handles",
"a",
"snapshot",
"request"
] | 55214a579c4e4b4d74765f3f6aa2eb815bac1c3b | https://github.com/zaturox/glin/blob/55214a579c4e4b4d74765f3f6aa2eb815bac1c3b/glin/app.py#L309-L321 |
249,324 | zaturox/glin | glin/app.py | GlinAppZmqCollector.handle_collect | def handle_collect(self, msg):
"""handle an incoming message"""
(success, sequence_number, comment) = self._handle_collect(msg)
self.collector.send_multipart(msgs.MessageWriter().bool(success).uint64(sequence_number).string(comment).get()) | python | def handle_collect(self, msg):
"""handle an incoming message"""
(success, sequence_number, comment) = self._handle_collect(msg)
self.collector.send_multipart(msgs.MessageWriter().bool(success).uint64(sequence_number).string(comment).get()) | [
"def",
"handle_collect",
"(",
"self",
",",
"msg",
")",
":",
"(",
"success",
",",
"sequence_number",
",",
"comment",
")",
"=",
"self",
".",
"_handle_collect",
"(",
"msg",
")",
"self",
".",
"collector",
".",
"send_multipart",
"(",
"msgs",
".",
"MessageWriter",
"(",
")",
".",
"bool",
"(",
"success",
")",
".",
"uint64",
"(",
"sequence_number",
")",
".",
"string",
"(",
"comment",
")",
".",
"get",
"(",
")",
")"
] | handle an incoming message | [
"handle",
"an",
"incoming",
"message"
] | 55214a579c4e4b4d74765f3f6aa2eb815bac1c3b | https://github.com/zaturox/glin/blob/55214a579c4e4b4d74765f3f6aa2eb815bac1c3b/glin/app.py#L335-L338 |
249,325 | opn-oss/opn-oss-py-common | opendna/common/decorators.py | with_uvloop_if_possible | def with_uvloop_if_possible(f, *args, **kwargs):
""" Simple decorator to provide optional uvloop usage"""
try:
import uvloop
import asyncio
asyncio.set_event_loop_policy(uvloop.EventLoopPolicy())
print('uvloop will be used')
except ImportError:
print('uvloop unavailable')
return f(*args, **kwargs) | python | def with_uvloop_if_possible(f, *args, **kwargs):
""" Simple decorator to provide optional uvloop usage"""
try:
import uvloop
import asyncio
asyncio.set_event_loop_policy(uvloop.EventLoopPolicy())
print('uvloop will be used')
except ImportError:
print('uvloop unavailable')
return f(*args, **kwargs) | [
"def",
"with_uvloop_if_possible",
"(",
"f",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"try",
":",
"import",
"uvloop",
"import",
"asyncio",
"asyncio",
".",
"set_event_loop_policy",
"(",
"uvloop",
".",
"EventLoopPolicy",
"(",
")",
")",
"print",
"(",
"'uvloop will be used'",
")",
"except",
"ImportError",
":",
"print",
"(",
"'uvloop unavailable'",
")",
"return",
"f",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")"
] | Simple decorator to provide optional uvloop usage | [
"Simple",
"decorator",
"to",
"provide",
"optional",
"uvloop",
"usage"
] | 5d449a4328df3b050513eb74e9df4ddaef74caa8 | https://github.com/opn-oss/opn-oss-py-common/blob/5d449a4328df3b050513eb74e9df4ddaef74caa8/opendna/common/decorators.py#L30-L39 |
249,326 | jmgilman/Neolib | neolib/NST.py | NST.initialize | def initialize():
""" Initializes the global NST instance with the current NST and begins tracking
"""
NST.running = True
pg = Page("http://www.neopets.com/")
curtime = pg.find("td", {'id': 'nst'}).text
NST.curTime = datetime.datetime.strptime(curtime.replace(" NST", ""), "%I:%M:%S %p") + datetime.timedelta(0,2)
NST.inst = NST()
NST.daemon = True # Ensures the thread is properly destroyed when the master thread terminates
NST.inst.start() | python | def initialize():
""" Initializes the global NST instance with the current NST and begins tracking
"""
NST.running = True
pg = Page("http://www.neopets.com/")
curtime = pg.find("td", {'id': 'nst'}).text
NST.curTime = datetime.datetime.strptime(curtime.replace(" NST", ""), "%I:%M:%S %p") + datetime.timedelta(0,2)
NST.inst = NST()
NST.daemon = True # Ensures the thread is properly destroyed when the master thread terminates
NST.inst.start() | [
"def",
"initialize",
"(",
")",
":",
"NST",
".",
"running",
"=",
"True",
"pg",
"=",
"Page",
"(",
"\"http://www.neopets.com/\"",
")",
"curtime",
"=",
"pg",
".",
"find",
"(",
"\"td\"",
",",
"{",
"'id'",
":",
"'nst'",
"}",
")",
".",
"text",
"NST",
".",
"curTime",
"=",
"datetime",
".",
"datetime",
".",
"strptime",
"(",
"curtime",
".",
"replace",
"(",
"\" NST\"",
",",
"\"\"",
")",
",",
"\"%I:%M:%S %p\"",
")",
"+",
"datetime",
".",
"timedelta",
"(",
"0",
",",
"2",
")",
"NST",
".",
"inst",
"=",
"NST",
"(",
")",
"NST",
".",
"daemon",
"=",
"True",
"# Ensures the thread is properly destroyed when the master thread terminates",
"NST",
".",
"inst",
".",
"start",
"(",
")"
] | Initializes the global NST instance with the current NST and begins tracking | [
"Initializes",
"the",
"global",
"NST",
"instance",
"with",
"the",
"current",
"NST",
"and",
"begins",
"tracking"
] | 228fafeaed0f3195676137732384a14820ae285c | https://github.com/jmgilman/Neolib/blob/228fafeaed0f3195676137732384a14820ae285c/neolib/NST.py#L39-L50 |
249,327 | limpyd/redis-limpyd-extensions | limpyd_extensions/dynamic/fields.py | DynamicFieldMixin._attach_to_model | def _attach_to_model(self, model):
"""
Check that the model can handle dynamic fields
"""
if not issubclass(model, ModelWithDynamicFieldMixin):
raise ImplementationError(
'The "%s" model does not inherit from ModelWithDynamicFieldMixin '
'so the "%s" DynamicField cannot be attached to it' % (
model.__name__, self.name))
super(DynamicFieldMixin, self)._attach_to_model(model)
if self.dynamic_version_of is not None:
return
if hasattr(model, self.name):
return
setattr(model, self.name, self) | python | def _attach_to_model(self, model):
"""
Check that the model can handle dynamic fields
"""
if not issubclass(model, ModelWithDynamicFieldMixin):
raise ImplementationError(
'The "%s" model does not inherit from ModelWithDynamicFieldMixin '
'so the "%s" DynamicField cannot be attached to it' % (
model.__name__, self.name))
super(DynamicFieldMixin, self)._attach_to_model(model)
if self.dynamic_version_of is not None:
return
if hasattr(model, self.name):
return
setattr(model, self.name, self) | [
"def",
"_attach_to_model",
"(",
"self",
",",
"model",
")",
":",
"if",
"not",
"issubclass",
"(",
"model",
",",
"ModelWithDynamicFieldMixin",
")",
":",
"raise",
"ImplementationError",
"(",
"'The \"%s\" model does not inherit from ModelWithDynamicFieldMixin '",
"'so the \"%s\" DynamicField cannot be attached to it'",
"%",
"(",
"model",
".",
"__name__",
",",
"self",
".",
"name",
")",
")",
"super",
"(",
"DynamicFieldMixin",
",",
"self",
")",
".",
"_attach_to_model",
"(",
"model",
")",
"if",
"self",
".",
"dynamic_version_of",
"is",
"not",
"None",
":",
"return",
"if",
"hasattr",
"(",
"model",
",",
"self",
".",
"name",
")",
":",
"return",
"setattr",
"(",
"model",
",",
"self",
".",
"name",
",",
"self",
")"
] | Check that the model can handle dynamic fields | [
"Check",
"that",
"the",
"model",
"can",
"handle",
"dynamic",
"fields"
] | 13f34e39efd2f802761457da30ab2a4213b63934 | https://github.com/limpyd/redis-limpyd-extensions/blob/13f34e39efd2f802761457da30ab2a4213b63934/limpyd_extensions/dynamic/fields.py#L46-L64 |
249,328 | limpyd/redis-limpyd-extensions | limpyd_extensions/dynamic/fields.py | DynamicFieldMixin.delete | def delete(self):
"""
If a dynamic version, delete it the standard way and remove it from the
inventory, else delete all dynamic versions.
"""
if self.dynamic_version_of is None:
self._delete_dynamic_versions()
else:
super(DynamicFieldMixin, self).delete()
self._inventory.srem(self.dynamic_part) | python | def delete(self):
"""
If a dynamic version, delete it the standard way and remove it from the
inventory, else delete all dynamic versions.
"""
if self.dynamic_version_of is None:
self._delete_dynamic_versions()
else:
super(DynamicFieldMixin, self).delete()
self._inventory.srem(self.dynamic_part) | [
"def",
"delete",
"(",
"self",
")",
":",
"if",
"self",
".",
"dynamic_version_of",
"is",
"None",
":",
"self",
".",
"_delete_dynamic_versions",
"(",
")",
"else",
":",
"super",
"(",
"DynamicFieldMixin",
",",
"self",
")",
".",
"delete",
"(",
")",
"self",
".",
"_inventory",
".",
"srem",
"(",
"self",
".",
"dynamic_part",
")"
] | If a dynamic version, delete it the standard way and remove it from the
inventory, else delete all dynamic versions. | [
"If",
"a",
"dynamic",
"version",
"delete",
"it",
"the",
"standard",
"way",
"and",
"remove",
"it",
"from",
"the",
"inventory",
"else",
"delete",
"all",
"dynamic",
"versions",
"."
] | 13f34e39efd2f802761457da30ab2a4213b63934 | https://github.com/limpyd/redis-limpyd-extensions/blob/13f34e39efd2f802761457da30ab2a4213b63934/limpyd_extensions/dynamic/fields.py#L165-L174 |
249,329 | limpyd/redis-limpyd-extensions | limpyd_extensions/dynamic/fields.py | DynamicFieldMixin._delete_dynamic_versions | def _delete_dynamic_versions(self):
"""
Call the `delete` method of all dynamic versions of the current field
found in the inventory then clean the inventory.
"""
if self.dynamic_version_of:
raise ImplementationError(u'"_delete_dynamic_versions" can only be '
u'executed on the base field')
inventory = self._inventory
for dynamic_part in inventory.smembers():
name = self.get_name_for(dynamic_part)
# create the field
new_field = self._create_dynamic_version()
new_field.name = name
new_field._dynamic_part = dynamic_part # avoid useless computation
new_field._attach_to_model(self._model)
new_field._attach_to_instance(self._instance)
# and delete its content
new_field.delete()
inventory.delete() | python | def _delete_dynamic_versions(self):
"""
Call the `delete` method of all dynamic versions of the current field
found in the inventory then clean the inventory.
"""
if self.dynamic_version_of:
raise ImplementationError(u'"_delete_dynamic_versions" can only be '
u'executed on the base field')
inventory = self._inventory
for dynamic_part in inventory.smembers():
name = self.get_name_for(dynamic_part)
# create the field
new_field = self._create_dynamic_version()
new_field.name = name
new_field._dynamic_part = dynamic_part # avoid useless computation
new_field._attach_to_model(self._model)
new_field._attach_to_instance(self._instance)
# and delete its content
new_field.delete()
inventory.delete() | [
"def",
"_delete_dynamic_versions",
"(",
"self",
")",
":",
"if",
"self",
".",
"dynamic_version_of",
":",
"raise",
"ImplementationError",
"(",
"u'\"_delete_dynamic_versions\" can only be '",
"u'executed on the base field'",
")",
"inventory",
"=",
"self",
".",
"_inventory",
"for",
"dynamic_part",
"in",
"inventory",
".",
"smembers",
"(",
")",
":",
"name",
"=",
"self",
".",
"get_name_for",
"(",
"dynamic_part",
")",
"# create the field",
"new_field",
"=",
"self",
".",
"_create_dynamic_version",
"(",
")",
"new_field",
".",
"name",
"=",
"name",
"new_field",
".",
"_dynamic_part",
"=",
"dynamic_part",
"# avoid useless computation",
"new_field",
".",
"_attach_to_model",
"(",
"self",
".",
"_model",
")",
"new_field",
".",
"_attach_to_instance",
"(",
"self",
".",
"_instance",
")",
"# and delete its content",
"new_field",
".",
"delete",
"(",
")",
"inventory",
".",
"delete",
"(",
")"
] | Call the `delete` method of all dynamic versions of the current field
found in the inventory then clean the inventory. | [
"Call",
"the",
"delete",
"method",
"of",
"all",
"dynamic",
"versions",
"of",
"the",
"current",
"field",
"found",
"in",
"the",
"inventory",
"then",
"clean",
"the",
"inventory",
"."
] | 13f34e39efd2f802761457da30ab2a4213b63934 | https://github.com/limpyd/redis-limpyd-extensions/blob/13f34e39efd2f802761457da30ab2a4213b63934/limpyd_extensions/dynamic/fields.py#L176-L196 |
249,330 | limpyd/redis-limpyd-extensions | limpyd_extensions/dynamic/fields.py | DynamicFieldMixin.get_name_for | def get_name_for(self, dynamic_part):
"""
Compute the name of the variation of the current dynamic field based on
the given dynamic part. Use the "format" attribute to create the final
name.
"""
name = self.format % dynamic_part
if not self._accept_name(name):
raise ImplementationError('It seems that pattern and format do not '
'match for the field "%s"' % self.name)
return name | python | def get_name_for(self, dynamic_part):
"""
Compute the name of the variation of the current dynamic field based on
the given dynamic part. Use the "format" attribute to create the final
name.
"""
name = self.format % dynamic_part
if not self._accept_name(name):
raise ImplementationError('It seems that pattern and format do not '
'match for the field "%s"' % self.name)
return name | [
"def",
"get_name_for",
"(",
"self",
",",
"dynamic_part",
")",
":",
"name",
"=",
"self",
".",
"format",
"%",
"dynamic_part",
"if",
"not",
"self",
".",
"_accept_name",
"(",
"name",
")",
":",
"raise",
"ImplementationError",
"(",
"'It seems that pattern and format do not '",
"'match for the field \"%s\"'",
"%",
"self",
".",
"name",
")",
"return",
"name"
] | Compute the name of the variation of the current dynamic field based on
the given dynamic part. Use the "format" attribute to create the final
name. | [
"Compute",
"the",
"name",
"of",
"the",
"variation",
"of",
"the",
"current",
"dynamic",
"field",
"based",
"on",
"the",
"given",
"dynamic",
"part",
".",
"Use",
"the",
"format",
"attribute",
"to",
"create",
"the",
"final",
"name",
"."
] | 13f34e39efd2f802761457da30ab2a4213b63934 | https://github.com/limpyd/redis-limpyd-extensions/blob/13f34e39efd2f802761457da30ab2a4213b63934/limpyd_extensions/dynamic/fields.py#L198-L208 |
249,331 | limpyd/redis-limpyd-extensions | limpyd_extensions/dynamic/fields.py | DynamicFieldMixin.get_for | def get_for(self, dynamic_part):
"""
Return a variation of the current dynamic field based on the given
dynamic part. Use the "format" attribute to create the final name
"""
if not hasattr(self, '_instance'):
raise ImplementationError('"get_for" can be used only on a bound field')
name = self.get_name_for(dynamic_part)
return self._instance.get_field(name) | python | def get_for(self, dynamic_part):
"""
Return a variation of the current dynamic field based on the given
dynamic part. Use the "format" attribute to create the final name
"""
if not hasattr(self, '_instance'):
raise ImplementationError('"get_for" can be used only on a bound field')
name = self.get_name_for(dynamic_part)
return self._instance.get_field(name) | [
"def",
"get_for",
"(",
"self",
",",
"dynamic_part",
")",
":",
"if",
"not",
"hasattr",
"(",
"self",
",",
"'_instance'",
")",
":",
"raise",
"ImplementationError",
"(",
"'\"get_for\" can be used only on a bound field'",
")",
"name",
"=",
"self",
".",
"get_name_for",
"(",
"dynamic_part",
")",
"return",
"self",
".",
"_instance",
".",
"get_field",
"(",
"name",
")"
] | Return a variation of the current dynamic field based on the given
dynamic part. Use the "format" attribute to create the final name | [
"Return",
"a",
"variation",
"of",
"the",
"current",
"dynamic",
"field",
"based",
"on",
"the",
"given",
"dynamic",
"part",
".",
"Use",
"the",
"format",
"attribute",
"to",
"create",
"the",
"final",
"name"
] | 13f34e39efd2f802761457da30ab2a4213b63934 | https://github.com/limpyd/redis-limpyd-extensions/blob/13f34e39efd2f802761457da30ab2a4213b63934/limpyd_extensions/dynamic/fields.py#L210-L218 |
249,332 | shaypal5/decore | decore/decore.py | threadsafe_generator | def threadsafe_generator(generator_func):
"""A decorator that takes a generator function and makes it thread-safe.
"""
def decoration(*args, **keyword_args):
"""A thread-safe decoration for a generator function."""
return ThreadSafeIter(generator_func(*args, **keyword_args))
return decoration | python | def threadsafe_generator(generator_func):
"""A decorator that takes a generator function and makes it thread-safe.
"""
def decoration(*args, **keyword_args):
"""A thread-safe decoration for a generator function."""
return ThreadSafeIter(generator_func(*args, **keyword_args))
return decoration | [
"def",
"threadsafe_generator",
"(",
"generator_func",
")",
":",
"def",
"decoration",
"(",
"*",
"args",
",",
"*",
"*",
"keyword_args",
")",
":",
"\"\"\"A thread-safe decoration for a generator function.\"\"\"",
"return",
"ThreadSafeIter",
"(",
"generator_func",
"(",
"*",
"args",
",",
"*",
"*",
"keyword_args",
")",
")",
"return",
"decoration"
] | A decorator that takes a generator function and makes it thread-safe. | [
"A",
"decorator",
"that",
"takes",
"a",
"generator",
"function",
"and",
"makes",
"it",
"thread",
"-",
"safe",
"."
] | 460f22f8b9127e6a80b161a626d8827673343afb | https://github.com/shaypal5/decore/blob/460f22f8b9127e6a80b161a626d8827673343afb/decore/decore.py#L24-L30 |
249,333 | shaypal5/decore | decore/decore.py | lazy_property | def lazy_property(function):
"""Cache the first return value of a function for all subsequent calls.
This decorator is usefull for argument-less functions that behave more
like a global or static property that should be calculated once, but
lazily (i.e. only if requested).
"""
cached_val = []
def _wrapper(*args):
try:
return cached_val[0]
except IndexError:
ret_val = function(*args)
cached_val.append(ret_val)
return ret_val
return _wrapper | python | def lazy_property(function):
"""Cache the first return value of a function for all subsequent calls.
This decorator is usefull for argument-less functions that behave more
like a global or static property that should be calculated once, but
lazily (i.e. only if requested).
"""
cached_val = []
def _wrapper(*args):
try:
return cached_val[0]
except IndexError:
ret_val = function(*args)
cached_val.append(ret_val)
return ret_val
return _wrapper | [
"def",
"lazy_property",
"(",
"function",
")",
":",
"cached_val",
"=",
"[",
"]",
"def",
"_wrapper",
"(",
"*",
"args",
")",
":",
"try",
":",
"return",
"cached_val",
"[",
"0",
"]",
"except",
"IndexError",
":",
"ret_val",
"=",
"function",
"(",
"*",
"args",
")",
"cached_val",
".",
"append",
"(",
"ret_val",
")",
"return",
"ret_val",
"return",
"_wrapper"
] | Cache the first return value of a function for all subsequent calls.
This decorator is usefull for argument-less functions that behave more
like a global or static property that should be calculated once, but
lazily (i.e. only if requested). | [
"Cache",
"the",
"first",
"return",
"value",
"of",
"a",
"function",
"for",
"all",
"subsequent",
"calls",
"."
] | 460f22f8b9127e6a80b161a626d8827673343afb | https://github.com/shaypal5/decore/blob/460f22f8b9127e6a80b161a626d8827673343afb/decore/decore.py#L33-L48 |
249,334 | hitchtest/hitchserve | hitchserve/service_logs.py | Tail.cat | def cat(self, numlines=None):
"""Return a list of lines output by this service."""
if len(self.titles) == 1:
lines = self.lines()
if numlines is not None:
lines = lines[len(lines)-numlines:]
log("\n".join(lines))
else:
lines = [self._printtuple(line[0], line[1]) for line in self.lines()]
if numlines is not None:
lines = lines[len(lines)-numlines:]
log("".join(lines)) | python | def cat(self, numlines=None):
"""Return a list of lines output by this service."""
if len(self.titles) == 1:
lines = self.lines()
if numlines is not None:
lines = lines[len(lines)-numlines:]
log("\n".join(lines))
else:
lines = [self._printtuple(line[0], line[1]) for line in self.lines()]
if numlines is not None:
lines = lines[len(lines)-numlines:]
log("".join(lines)) | [
"def",
"cat",
"(",
"self",
",",
"numlines",
"=",
"None",
")",
":",
"if",
"len",
"(",
"self",
".",
"titles",
")",
"==",
"1",
":",
"lines",
"=",
"self",
".",
"lines",
"(",
")",
"if",
"numlines",
"is",
"not",
"None",
":",
"lines",
"=",
"lines",
"[",
"len",
"(",
"lines",
")",
"-",
"numlines",
":",
"]",
"log",
"(",
"\"\\n\"",
".",
"join",
"(",
"lines",
")",
")",
"else",
":",
"lines",
"=",
"[",
"self",
".",
"_printtuple",
"(",
"line",
"[",
"0",
"]",
",",
"line",
"[",
"1",
"]",
")",
"for",
"line",
"in",
"self",
".",
"lines",
"(",
")",
"]",
"if",
"numlines",
"is",
"not",
"None",
":",
"lines",
"=",
"lines",
"[",
"len",
"(",
"lines",
")",
"-",
"numlines",
":",
"]",
"log",
"(",
"\"\"",
".",
"join",
"(",
"lines",
")",
")"
] | Return a list of lines output by this service. | [
"Return",
"a",
"list",
"of",
"lines",
"output",
"by",
"this",
"service",
"."
] | a2def19979264186d283e76f7f0c88f3ed97f2e0 | https://github.com/hitchtest/hitchserve/blob/a2def19979264186d283e76f7f0c88f3ed97f2e0/hitchserve/service_logs.py#L162-L173 |
249,335 | hitchtest/hitchserve | hitchserve/service_logs.py | SubLog._match_service | def _match_service(self, line_with_color):
"""Return line if line matches this service's name, return None otherwise."""
line = re.compile("(\x1b\[\d+m)+").sub("", line_with_color) # Strip color codes
regexp = re.compile(r"^\[(.*?)\]\s(.*?)$")
if regexp.match(line):
title = regexp.match(line).group(1).strip()
if title in self.titles:
return (title, regexp.match(line).group(2))
return None | python | def _match_service(self, line_with_color):
"""Return line if line matches this service's name, return None otherwise."""
line = re.compile("(\x1b\[\d+m)+").sub("", line_with_color) # Strip color codes
regexp = re.compile(r"^\[(.*?)\]\s(.*?)$")
if regexp.match(line):
title = regexp.match(line).group(1).strip()
if title in self.titles:
return (title, regexp.match(line).group(2))
return None | [
"def",
"_match_service",
"(",
"self",
",",
"line_with_color",
")",
":",
"line",
"=",
"re",
".",
"compile",
"(",
"\"(\\x1b\\[\\d+m)+\"",
")",
".",
"sub",
"(",
"\"\"",
",",
"line_with_color",
")",
"# Strip color codes",
"regexp",
"=",
"re",
".",
"compile",
"(",
"r\"^\\[(.*?)\\]\\s(.*?)$\"",
")",
"if",
"regexp",
".",
"match",
"(",
"line",
")",
":",
"title",
"=",
"regexp",
".",
"match",
"(",
"line",
")",
".",
"group",
"(",
"1",
")",
".",
"strip",
"(",
")",
"if",
"title",
"in",
"self",
".",
"titles",
":",
"return",
"(",
"title",
",",
"regexp",
".",
"match",
"(",
"line",
")",
".",
"group",
"(",
"2",
")",
")",
"return",
"None"
] | Return line if line matches this service's name, return None otherwise. | [
"Return",
"line",
"if",
"line",
"matches",
"this",
"service",
"s",
"name",
"return",
"None",
"otherwise",
"."
] | a2def19979264186d283e76f7f0c88f3ed97f2e0 | https://github.com/hitchtest/hitchserve/blob/a2def19979264186d283e76f7f0c88f3ed97f2e0/hitchserve/service_logs.py#L183-L192 |
249,336 | hitchtest/hitchserve | hitchserve/service_logs.py | SubLog.json | def json(self):
"""Return a list of JSON objects output by this service."""
lines = []
for line in self.lines():
try:
if len(line) == 1:
lines.append(json.loads(line, strict=False))
else:
lines.append(json.loads(line[1], strict=False))
except ValueError:
pass
return lines | python | def json(self):
"""Return a list of JSON objects output by this service."""
lines = []
for line in self.lines():
try:
if len(line) == 1:
lines.append(json.loads(line, strict=False))
else:
lines.append(json.loads(line[1], strict=False))
except ValueError:
pass
return lines | [
"def",
"json",
"(",
"self",
")",
":",
"lines",
"=",
"[",
"]",
"for",
"line",
"in",
"self",
".",
"lines",
"(",
")",
":",
"try",
":",
"if",
"len",
"(",
"line",
")",
"==",
"1",
":",
"lines",
".",
"append",
"(",
"json",
".",
"loads",
"(",
"line",
",",
"strict",
"=",
"False",
")",
")",
"else",
":",
"lines",
".",
"append",
"(",
"json",
".",
"loads",
"(",
"line",
"[",
"1",
"]",
",",
"strict",
"=",
"False",
")",
")",
"except",
"ValueError",
":",
"pass",
"return",
"lines"
] | Return a list of JSON objects output by this service. | [
"Return",
"a",
"list",
"of",
"JSON",
"objects",
"output",
"by",
"this",
"service",
"."
] | a2def19979264186d283e76f7f0c88f3ed97f2e0 | https://github.com/hitchtest/hitchserve/blob/a2def19979264186d283e76f7f0c88f3ed97f2e0/hitchserve/service_logs.py#L216-L227 |
249,337 | cogniteev/docido-python-sdk | docido_sdk/toolbox/contextlib_ext.py | restore_dict_kv | def restore_dict_kv(a_dict, key, copy_func=copy.deepcopy):
"""Backup an object in a with context and restore it when leaving
the scope.
:param a_dict:
associative table
:param: key
key whose value has to be backed up
:param copy_func: callbable object used to create an object copy.
default is `copy.deepcopy`
"""
exists = False
if key in a_dict:
backup = copy_func(a_dict[key])
exists = True
try:
yield
finally:
if exists:
a_dict[key] = backup
else:
a_dict.pop(key, None) | python | def restore_dict_kv(a_dict, key, copy_func=copy.deepcopy):
"""Backup an object in a with context and restore it when leaving
the scope.
:param a_dict:
associative table
:param: key
key whose value has to be backed up
:param copy_func: callbable object used to create an object copy.
default is `copy.deepcopy`
"""
exists = False
if key in a_dict:
backup = copy_func(a_dict[key])
exists = True
try:
yield
finally:
if exists:
a_dict[key] = backup
else:
a_dict.pop(key, None) | [
"def",
"restore_dict_kv",
"(",
"a_dict",
",",
"key",
",",
"copy_func",
"=",
"copy",
".",
"deepcopy",
")",
":",
"exists",
"=",
"False",
"if",
"key",
"in",
"a_dict",
":",
"backup",
"=",
"copy_func",
"(",
"a_dict",
"[",
"key",
"]",
")",
"exists",
"=",
"True",
"try",
":",
"yield",
"finally",
":",
"if",
"exists",
":",
"a_dict",
"[",
"key",
"]",
"=",
"backup",
"else",
":",
"a_dict",
".",
"pop",
"(",
"key",
",",
"None",
")"
] | Backup an object in a with context and restore it when leaving
the scope.
:param a_dict:
associative table
:param: key
key whose value has to be backed up
:param copy_func: callbable object used to create an object copy.
default is `copy.deepcopy` | [
"Backup",
"an",
"object",
"in",
"a",
"with",
"context",
"and",
"restore",
"it",
"when",
"leaving",
"the",
"scope",
"."
] | 58ecb6c6f5757fd40c0601657ab18368da7ddf33 | https://github.com/cogniteev/docido-python-sdk/blob/58ecb6c6f5757fd40c0601657ab18368da7ddf33/docido_sdk/toolbox/contextlib_ext.py#L13-L34 |
249,338 | cogniteev/docido-python-sdk | docido_sdk/toolbox/contextlib_ext.py | popen | def popen(*args, **kwargs):
"""Run a process in background in a `with` context. Parameters given
to this function are passed to `subprocess.Popen`. Process is kill
when exiting the context.
"""
process = subprocess.Popen(*args, **kwargs)
try:
yield process.pid
finally:
os.kill(process.pid, signal.SIGTERM)
os.waitpid(process.pid, 0) | python | def popen(*args, **kwargs):
"""Run a process in background in a `with` context. Parameters given
to this function are passed to `subprocess.Popen`. Process is kill
when exiting the context.
"""
process = subprocess.Popen(*args, **kwargs)
try:
yield process.pid
finally:
os.kill(process.pid, signal.SIGTERM)
os.waitpid(process.pid, 0) | [
"def",
"popen",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"process",
"=",
"subprocess",
".",
"Popen",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
"try",
":",
"yield",
"process",
".",
"pid",
"finally",
":",
"os",
".",
"kill",
"(",
"process",
".",
"pid",
",",
"signal",
".",
"SIGTERM",
")",
"os",
".",
"waitpid",
"(",
"process",
".",
"pid",
",",
"0",
")"
] | Run a process in background in a `with` context. Parameters given
to this function are passed to `subprocess.Popen`. Process is kill
when exiting the context. | [
"Run",
"a",
"process",
"in",
"background",
"in",
"a",
"with",
"context",
".",
"Parameters",
"given",
"to",
"this",
"function",
"are",
"passed",
"to",
"subprocess",
".",
"Popen",
".",
"Process",
"is",
"kill",
"when",
"exiting",
"the",
"context",
"."
] | 58ecb6c6f5757fd40c0601657ab18368da7ddf33 | https://github.com/cogniteev/docido-python-sdk/blob/58ecb6c6f5757fd40c0601657ab18368da7ddf33/docido_sdk/toolbox/contextlib_ext.py#L80-L90 |
249,339 | EventTeam/beliefs | src/beliefs/cells/lists.py | LinearOrderedCell.coerce | def coerce(self, value):
"""
Takes one or two values in the domain and returns a LinearOrderedCell
with the same domain
"""
if isinstance(value, LinearOrderedCell) and (self.domain == value.domain or \
list_diff(self.domain, value.domain) == []):
# is LinearOrderedCell with same domain
return value
elif value in self.domain:
return LinearOrderedCell(self.domain, value, value)
elif isinstance(value, (list, tuple)) and all(map(value in self.domain, value)):
if len(value) == 1:
return LinearOrderedCell(self.domain, value[0], value[0])
elif len(value) == 2:
return LinearOrderedCell(self.domain, *value)
else:
sorted_vals = sorted(value, key=lambda x: self.to_i(x))
return LinearOrderedCell(self.domain, sorted_vals[0], sorted_vals[-1])
else:
raise Exception("Cannot coerce %s into LinearOrderedCell" % (str(value))) | python | def coerce(self, value):
"""
Takes one or two values in the domain and returns a LinearOrderedCell
with the same domain
"""
if isinstance(value, LinearOrderedCell) and (self.domain == value.domain or \
list_diff(self.domain, value.domain) == []):
# is LinearOrderedCell with same domain
return value
elif value in self.domain:
return LinearOrderedCell(self.domain, value, value)
elif isinstance(value, (list, tuple)) and all(map(value in self.domain, value)):
if len(value) == 1:
return LinearOrderedCell(self.domain, value[0], value[0])
elif len(value) == 2:
return LinearOrderedCell(self.domain, *value)
else:
sorted_vals = sorted(value, key=lambda x: self.to_i(x))
return LinearOrderedCell(self.domain, sorted_vals[0], sorted_vals[-1])
else:
raise Exception("Cannot coerce %s into LinearOrderedCell" % (str(value))) | [
"def",
"coerce",
"(",
"self",
",",
"value",
")",
":",
"if",
"isinstance",
"(",
"value",
",",
"LinearOrderedCell",
")",
"and",
"(",
"self",
".",
"domain",
"==",
"value",
".",
"domain",
"or",
"list_diff",
"(",
"self",
".",
"domain",
",",
"value",
".",
"domain",
")",
"==",
"[",
"]",
")",
":",
"# is LinearOrderedCell with same domain",
"return",
"value",
"elif",
"value",
"in",
"self",
".",
"domain",
":",
"return",
"LinearOrderedCell",
"(",
"self",
".",
"domain",
",",
"value",
",",
"value",
")",
"elif",
"isinstance",
"(",
"value",
",",
"(",
"list",
",",
"tuple",
")",
")",
"and",
"all",
"(",
"map",
"(",
"value",
"in",
"self",
".",
"domain",
",",
"value",
")",
")",
":",
"if",
"len",
"(",
"value",
")",
"==",
"1",
":",
"return",
"LinearOrderedCell",
"(",
"self",
".",
"domain",
",",
"value",
"[",
"0",
"]",
",",
"value",
"[",
"0",
"]",
")",
"elif",
"len",
"(",
"value",
")",
"==",
"2",
":",
"return",
"LinearOrderedCell",
"(",
"self",
".",
"domain",
",",
"*",
"value",
")",
"else",
":",
"sorted_vals",
"=",
"sorted",
"(",
"value",
",",
"key",
"=",
"lambda",
"x",
":",
"self",
".",
"to_i",
"(",
"x",
")",
")",
"return",
"LinearOrderedCell",
"(",
"self",
".",
"domain",
",",
"sorted_vals",
"[",
"0",
"]",
",",
"sorted_vals",
"[",
"-",
"1",
"]",
")",
"else",
":",
"raise",
"Exception",
"(",
"\"Cannot coerce %s into LinearOrderedCell\"",
"%",
"(",
"str",
"(",
"value",
")",
")",
")"
] | Takes one or two values in the domain and returns a LinearOrderedCell
with the same domain | [
"Takes",
"one",
"or",
"two",
"values",
"in",
"the",
"domain",
"and",
"returns",
"a",
"LinearOrderedCell",
"with",
"the",
"same",
"domain"
] | c07d22b61bebeede74a72800030dde770bf64208 | https://github.com/EventTeam/beliefs/blob/c07d22b61bebeede74a72800030dde770bf64208/src/beliefs/cells/lists.py#L44-L64 |
249,340 | EventTeam/beliefs | src/beliefs/cells/lists.py | ListCell.coerce | def coerce(value):
"""
Turns a value into a list
"""
if isinstance(value, ListCell):
return value
elif isinstance(value, (list)):
return ListCell(value)
else:
return ListCell([value]) | python | def coerce(value):
"""
Turns a value into a list
"""
if isinstance(value, ListCell):
return value
elif isinstance(value, (list)):
return ListCell(value)
else:
return ListCell([value]) | [
"def",
"coerce",
"(",
"value",
")",
":",
"if",
"isinstance",
"(",
"value",
",",
"ListCell",
")",
":",
"return",
"value",
"elif",
"isinstance",
"(",
"value",
",",
"(",
"list",
")",
")",
":",
"return",
"ListCell",
"(",
"value",
")",
"else",
":",
"return",
"ListCell",
"(",
"[",
"value",
"]",
")"
] | Turns a value into a list | [
"Turns",
"a",
"value",
"into",
"a",
"list"
] | c07d22b61bebeede74a72800030dde770bf64208 | https://github.com/EventTeam/beliefs/blob/c07d22b61bebeede74a72800030dde770bf64208/src/beliefs/cells/lists.py#L160-L169 |
249,341 | EventTeam/beliefs | src/beliefs/cells/lists.py | ListCell.append | def append(self, el):
"""
Idiosynractic method for adding an element to a list
"""
if self.value is None:
self.value = [el]
else:
self.value.append(el) | python | def append(self, el):
"""
Idiosynractic method for adding an element to a list
"""
if self.value is None:
self.value = [el]
else:
self.value.append(el) | [
"def",
"append",
"(",
"self",
",",
"el",
")",
":",
"if",
"self",
".",
"value",
"is",
"None",
":",
"self",
".",
"value",
"=",
"[",
"el",
"]",
"else",
":",
"self",
".",
"value",
".",
"append",
"(",
"el",
")"
] | Idiosynractic method for adding an element to a list | [
"Idiosynractic",
"method",
"for",
"adding",
"an",
"element",
"to",
"a",
"list"
] | c07d22b61bebeede74a72800030dde770bf64208 | https://github.com/EventTeam/beliefs/blob/c07d22b61bebeede74a72800030dde770bf64208/src/beliefs/cells/lists.py#L268-L275 |
249,342 | EventTeam/beliefs | src/beliefs/cells/lists.py | PrefixCell.merge | def merge(self, other):
"""
Merges two prefixes
"""
other = PrefixCell.coerce(other)
if self.is_equal(other):
# pick among dependencies
return self
elif other.is_entailed_by(self):
return self
elif self.is_entailed_by(other):
self.value = other.value
elif self.is_contradictory(other):
raise Contradiction("Cannot merge prefix '%s' with '%s'" % \
(self, other))
else:
if len(self.value) > len(other.value):
self.value = other.value[:]
# otherwise, return self
return self | python | def merge(self, other):
"""
Merges two prefixes
"""
other = PrefixCell.coerce(other)
if self.is_equal(other):
# pick among dependencies
return self
elif other.is_entailed_by(self):
return self
elif self.is_entailed_by(other):
self.value = other.value
elif self.is_contradictory(other):
raise Contradiction("Cannot merge prefix '%s' with '%s'" % \
(self, other))
else:
if len(self.value) > len(other.value):
self.value = other.value[:]
# otherwise, return self
return self | [
"def",
"merge",
"(",
"self",
",",
"other",
")",
":",
"other",
"=",
"PrefixCell",
".",
"coerce",
"(",
"other",
")",
"if",
"self",
".",
"is_equal",
"(",
"other",
")",
":",
"# pick among dependencies",
"return",
"self",
"elif",
"other",
".",
"is_entailed_by",
"(",
"self",
")",
":",
"return",
"self",
"elif",
"self",
".",
"is_entailed_by",
"(",
"other",
")",
":",
"self",
".",
"value",
"=",
"other",
".",
"value",
"elif",
"self",
".",
"is_contradictory",
"(",
"other",
")",
":",
"raise",
"Contradiction",
"(",
"\"Cannot merge prefix '%s' with '%s'\"",
"%",
"(",
"self",
",",
"other",
")",
")",
"else",
":",
"if",
"len",
"(",
"self",
".",
"value",
")",
">",
"len",
"(",
"other",
".",
"value",
")",
":",
"self",
".",
"value",
"=",
"other",
".",
"value",
"[",
":",
"]",
"# otherwise, return self",
"return",
"self"
] | Merges two prefixes | [
"Merges",
"two",
"prefixes"
] | c07d22b61bebeede74a72800030dde770bf64208 | https://github.com/EventTeam/beliefs/blob/c07d22b61bebeede74a72800030dde770bf64208/src/beliefs/cells/lists.py#L304-L323 |
249,343 | sternoru/goscalecms | goscale/templatetags/goscale_tags.py | GoscaleTemplateInclusionTag.get_template | def get_template(self, context, **kwargs):
"""
Returns the template to be used for the current context and arguments.
"""
if 'template' in kwargs['params']:
self.template = kwargs['params']['template']
return super(GoscaleTemplateInclusionTag, self).get_template(context, **kwargs) | python | def get_template(self, context, **kwargs):
"""
Returns the template to be used for the current context and arguments.
"""
if 'template' in kwargs['params']:
self.template = kwargs['params']['template']
return super(GoscaleTemplateInclusionTag, self).get_template(context, **kwargs) | [
"def",
"get_template",
"(",
"self",
",",
"context",
",",
"*",
"*",
"kwargs",
")",
":",
"if",
"'template'",
"in",
"kwargs",
"[",
"'params'",
"]",
":",
"self",
".",
"template",
"=",
"kwargs",
"[",
"'params'",
"]",
"[",
"'template'",
"]",
"return",
"super",
"(",
"GoscaleTemplateInclusionTag",
",",
"self",
")",
".",
"get_template",
"(",
"context",
",",
"*",
"*",
"kwargs",
")"
] | Returns the template to be used for the current context and arguments. | [
"Returns",
"the",
"template",
"to",
"be",
"used",
"for",
"the",
"current",
"context",
"and",
"arguments",
"."
] | 7eee50357c47ebdfe3e573a8b4be3b67892d229e | https://github.com/sternoru/goscalecms/blob/7eee50357c47ebdfe3e573a8b4be3b67892d229e/goscale/templatetags/goscale_tags.py#L27-L33 |
249,344 | minhhoit/yacms | yacms/generic/views.py | admin_keywords_submit | def admin_keywords_submit(request):
"""
Adds any new given keywords from the custom keywords field in the
admin, and returns their IDs for use when saving a model with a
keywords field.
"""
keyword_ids, titles = [], []
remove = punctuation.replace("-", "") # Strip punctuation, allow dashes.
for title in request.POST.get("text_keywords", "").split(","):
title = "".join([c for c in title if c not in remove]).strip()
if title:
kw, created = Keyword.objects.get_or_create_iexact(title=title)
keyword_id = str(kw.id)
if keyword_id not in keyword_ids:
keyword_ids.append(keyword_id)
titles.append(title)
return HttpResponse("%s|%s" % (",".join(keyword_ids), ", ".join(titles)),
content_type='text/plain') | python | def admin_keywords_submit(request):
"""
Adds any new given keywords from the custom keywords field in the
admin, and returns their IDs for use when saving a model with a
keywords field.
"""
keyword_ids, titles = [], []
remove = punctuation.replace("-", "") # Strip punctuation, allow dashes.
for title in request.POST.get("text_keywords", "").split(","):
title = "".join([c for c in title if c not in remove]).strip()
if title:
kw, created = Keyword.objects.get_or_create_iexact(title=title)
keyword_id = str(kw.id)
if keyword_id not in keyword_ids:
keyword_ids.append(keyword_id)
titles.append(title)
return HttpResponse("%s|%s" % (",".join(keyword_ids), ", ".join(titles)),
content_type='text/plain') | [
"def",
"admin_keywords_submit",
"(",
"request",
")",
":",
"keyword_ids",
",",
"titles",
"=",
"[",
"]",
",",
"[",
"]",
"remove",
"=",
"punctuation",
".",
"replace",
"(",
"\"-\"",
",",
"\"\"",
")",
"# Strip punctuation, allow dashes.",
"for",
"title",
"in",
"request",
".",
"POST",
".",
"get",
"(",
"\"text_keywords\"",
",",
"\"\"",
")",
".",
"split",
"(",
"\",\"",
")",
":",
"title",
"=",
"\"\"",
".",
"join",
"(",
"[",
"c",
"for",
"c",
"in",
"title",
"if",
"c",
"not",
"in",
"remove",
"]",
")",
".",
"strip",
"(",
")",
"if",
"title",
":",
"kw",
",",
"created",
"=",
"Keyword",
".",
"objects",
".",
"get_or_create_iexact",
"(",
"title",
"=",
"title",
")",
"keyword_id",
"=",
"str",
"(",
"kw",
".",
"id",
")",
"if",
"keyword_id",
"not",
"in",
"keyword_ids",
":",
"keyword_ids",
".",
"append",
"(",
"keyword_id",
")",
"titles",
".",
"append",
"(",
"title",
")",
"return",
"HttpResponse",
"(",
"\"%s|%s\"",
"%",
"(",
"\",\"",
".",
"join",
"(",
"keyword_ids",
")",
",",
"\", \"",
".",
"join",
"(",
"titles",
")",
")",
",",
"content_type",
"=",
"'text/plain'",
")"
] | Adds any new given keywords from the custom keywords field in the
admin, and returns their IDs for use when saving a model with a
keywords field. | [
"Adds",
"any",
"new",
"given",
"keywords",
"from",
"the",
"custom",
"keywords",
"field",
"in",
"the",
"admin",
"and",
"returns",
"their",
"IDs",
"for",
"use",
"when",
"saving",
"a",
"model",
"with",
"a",
"keywords",
"field",
"."
] | 2921b706b7107c6e8c5f2bbf790ff11f85a2167f | https://github.com/minhhoit/yacms/blob/2921b706b7107c6e8c5f2bbf790ff11f85a2167f/yacms/generic/views.py#L26-L43 |
249,345 | minhhoit/yacms | yacms/generic/views.py | comment | def comment(request, template="generic/comments.html", extra_context=None):
"""
Handle a ``ThreadedCommentForm`` submission and redirect back to its
related object.
"""
response = initial_validation(request, "comment")
if isinstance(response, HttpResponse):
return response
obj, post_data = response
form_class = import_dotted_path(settings.COMMENT_FORM_CLASS)
form = form_class(request, obj, post_data)
if form.is_valid():
url = obj.get_absolute_url()
if is_spam(request, form, url):
return redirect(url)
comment = form.save(request)
response = redirect(add_cache_bypass(comment.get_absolute_url()))
# Store commenter's details in a cookie for 90 days.
for field in ThreadedCommentForm.cookie_fields:
cookie_name = ThreadedCommentForm.cookie_prefix + field
cookie_value = post_data.get(field, "")
set_cookie(response, cookie_name, cookie_value)
return response
elif request.is_ajax() and form.errors:
return HttpResponse(dumps({"errors": form.errors}))
# Show errors with stand-alone comment form.
context = {"obj": obj, "posted_comment_form": form}
context.update(extra_context or {})
return TemplateResponse(request, template, context) | python | def comment(request, template="generic/comments.html", extra_context=None):
"""
Handle a ``ThreadedCommentForm`` submission and redirect back to its
related object.
"""
response = initial_validation(request, "comment")
if isinstance(response, HttpResponse):
return response
obj, post_data = response
form_class = import_dotted_path(settings.COMMENT_FORM_CLASS)
form = form_class(request, obj, post_data)
if form.is_valid():
url = obj.get_absolute_url()
if is_spam(request, form, url):
return redirect(url)
comment = form.save(request)
response = redirect(add_cache_bypass(comment.get_absolute_url()))
# Store commenter's details in a cookie for 90 days.
for field in ThreadedCommentForm.cookie_fields:
cookie_name = ThreadedCommentForm.cookie_prefix + field
cookie_value = post_data.get(field, "")
set_cookie(response, cookie_name, cookie_value)
return response
elif request.is_ajax() and form.errors:
return HttpResponse(dumps({"errors": form.errors}))
# Show errors with stand-alone comment form.
context = {"obj": obj, "posted_comment_form": form}
context.update(extra_context or {})
return TemplateResponse(request, template, context) | [
"def",
"comment",
"(",
"request",
",",
"template",
"=",
"\"generic/comments.html\"",
",",
"extra_context",
"=",
"None",
")",
":",
"response",
"=",
"initial_validation",
"(",
"request",
",",
"\"comment\"",
")",
"if",
"isinstance",
"(",
"response",
",",
"HttpResponse",
")",
":",
"return",
"response",
"obj",
",",
"post_data",
"=",
"response",
"form_class",
"=",
"import_dotted_path",
"(",
"settings",
".",
"COMMENT_FORM_CLASS",
")",
"form",
"=",
"form_class",
"(",
"request",
",",
"obj",
",",
"post_data",
")",
"if",
"form",
".",
"is_valid",
"(",
")",
":",
"url",
"=",
"obj",
".",
"get_absolute_url",
"(",
")",
"if",
"is_spam",
"(",
"request",
",",
"form",
",",
"url",
")",
":",
"return",
"redirect",
"(",
"url",
")",
"comment",
"=",
"form",
".",
"save",
"(",
"request",
")",
"response",
"=",
"redirect",
"(",
"add_cache_bypass",
"(",
"comment",
".",
"get_absolute_url",
"(",
")",
")",
")",
"# Store commenter's details in a cookie for 90 days.",
"for",
"field",
"in",
"ThreadedCommentForm",
".",
"cookie_fields",
":",
"cookie_name",
"=",
"ThreadedCommentForm",
".",
"cookie_prefix",
"+",
"field",
"cookie_value",
"=",
"post_data",
".",
"get",
"(",
"field",
",",
"\"\"",
")",
"set_cookie",
"(",
"response",
",",
"cookie_name",
",",
"cookie_value",
")",
"return",
"response",
"elif",
"request",
".",
"is_ajax",
"(",
")",
"and",
"form",
".",
"errors",
":",
"return",
"HttpResponse",
"(",
"dumps",
"(",
"{",
"\"errors\"",
":",
"form",
".",
"errors",
"}",
")",
")",
"# Show errors with stand-alone comment form.",
"context",
"=",
"{",
"\"obj\"",
":",
"obj",
",",
"\"posted_comment_form\"",
":",
"form",
"}",
"context",
".",
"update",
"(",
"extra_context",
"or",
"{",
"}",
")",
"return",
"TemplateResponse",
"(",
"request",
",",
"template",
",",
"context",
")"
] | Handle a ``ThreadedCommentForm`` submission and redirect back to its
related object. | [
"Handle",
"a",
"ThreadedCommentForm",
"submission",
"and",
"redirect",
"back",
"to",
"its",
"related",
"object",
"."
] | 2921b706b7107c6e8c5f2bbf790ff11f85a2167f | https://github.com/minhhoit/yacms/blob/2921b706b7107c6e8c5f2bbf790ff11f85a2167f/yacms/generic/views.py#L91-L119 |
249,346 | minhhoit/yacms | yacms/generic/views.py | rating | def rating(request):
"""
Handle a ``RatingForm`` submission and redirect back to its
related object.
"""
response = initial_validation(request, "rating")
if isinstance(response, HttpResponse):
return response
obj, post_data = response
url = add_cache_bypass(obj.get_absolute_url().split("#")[0])
response = redirect(url + "#rating-%s" % obj.id)
rating_form = RatingForm(request, obj, post_data)
if rating_form.is_valid():
rating_form.save()
if request.is_ajax():
# Reload the object and return the rating fields as json.
obj = obj.__class__.objects.get(id=obj.id)
rating_name = obj.get_ratingfield_name()
json = {}
for f in ("average", "count", "sum"):
json["rating_" + f] = getattr(obj, "%s_%s" % (rating_name, f))
response = HttpResponse(dumps(json))
if rating_form.undoing:
ratings = set(rating_form.previous) ^ set([rating_form.current])
else:
ratings = rating_form.previous + [rating_form.current]
set_cookie(response, "yacms-rating", ",".join(ratings))
return response | python | def rating(request):
"""
Handle a ``RatingForm`` submission and redirect back to its
related object.
"""
response = initial_validation(request, "rating")
if isinstance(response, HttpResponse):
return response
obj, post_data = response
url = add_cache_bypass(obj.get_absolute_url().split("#")[0])
response = redirect(url + "#rating-%s" % obj.id)
rating_form = RatingForm(request, obj, post_data)
if rating_form.is_valid():
rating_form.save()
if request.is_ajax():
# Reload the object and return the rating fields as json.
obj = obj.__class__.objects.get(id=obj.id)
rating_name = obj.get_ratingfield_name()
json = {}
for f in ("average", "count", "sum"):
json["rating_" + f] = getattr(obj, "%s_%s" % (rating_name, f))
response = HttpResponse(dumps(json))
if rating_form.undoing:
ratings = set(rating_form.previous) ^ set([rating_form.current])
else:
ratings = rating_form.previous + [rating_form.current]
set_cookie(response, "yacms-rating", ",".join(ratings))
return response | [
"def",
"rating",
"(",
"request",
")",
":",
"response",
"=",
"initial_validation",
"(",
"request",
",",
"\"rating\"",
")",
"if",
"isinstance",
"(",
"response",
",",
"HttpResponse",
")",
":",
"return",
"response",
"obj",
",",
"post_data",
"=",
"response",
"url",
"=",
"add_cache_bypass",
"(",
"obj",
".",
"get_absolute_url",
"(",
")",
".",
"split",
"(",
"\"#\"",
")",
"[",
"0",
"]",
")",
"response",
"=",
"redirect",
"(",
"url",
"+",
"\"#rating-%s\"",
"%",
"obj",
".",
"id",
")",
"rating_form",
"=",
"RatingForm",
"(",
"request",
",",
"obj",
",",
"post_data",
")",
"if",
"rating_form",
".",
"is_valid",
"(",
")",
":",
"rating_form",
".",
"save",
"(",
")",
"if",
"request",
".",
"is_ajax",
"(",
")",
":",
"# Reload the object and return the rating fields as json.",
"obj",
"=",
"obj",
".",
"__class__",
".",
"objects",
".",
"get",
"(",
"id",
"=",
"obj",
".",
"id",
")",
"rating_name",
"=",
"obj",
".",
"get_ratingfield_name",
"(",
")",
"json",
"=",
"{",
"}",
"for",
"f",
"in",
"(",
"\"average\"",
",",
"\"count\"",
",",
"\"sum\"",
")",
":",
"json",
"[",
"\"rating_\"",
"+",
"f",
"]",
"=",
"getattr",
"(",
"obj",
",",
"\"%s_%s\"",
"%",
"(",
"rating_name",
",",
"f",
")",
")",
"response",
"=",
"HttpResponse",
"(",
"dumps",
"(",
"json",
")",
")",
"if",
"rating_form",
".",
"undoing",
":",
"ratings",
"=",
"set",
"(",
"rating_form",
".",
"previous",
")",
"^",
"set",
"(",
"[",
"rating_form",
".",
"current",
"]",
")",
"else",
":",
"ratings",
"=",
"rating_form",
".",
"previous",
"+",
"[",
"rating_form",
".",
"current",
"]",
"set_cookie",
"(",
"response",
",",
"\"yacms-rating\"",
",",
"\",\"",
".",
"join",
"(",
"ratings",
")",
")",
"return",
"response"
] | Handle a ``RatingForm`` submission and redirect back to its
related object. | [
"Handle",
"a",
"RatingForm",
"submission",
"and",
"redirect",
"back",
"to",
"its",
"related",
"object",
"."
] | 2921b706b7107c6e8c5f2bbf790ff11f85a2167f | https://github.com/minhhoit/yacms/blob/2921b706b7107c6e8c5f2bbf790ff11f85a2167f/yacms/generic/views.py#L122-L149 |
249,347 | clld/cdstarcat | src/cdstarcat/catalog.py | Catalog.add | def add(self, obj, metadata=None, update=False):
"""
Add an existing CDSTAR object to the catalog.
:param obj: A pycdstar.resource.Object instance
"""
if (obj not in self) or update:
self[obj.id] = Object.fromdict(
obj.id,
dict(
metadata=obj.metadata.read() if metadata is None else metadata,
bitstreams=[bs._properties for bs in obj.bitstreams]))
time.sleep(0.1)
return self.objects[obj.id] | python | def add(self, obj, metadata=None, update=False):
"""
Add an existing CDSTAR object to the catalog.
:param obj: A pycdstar.resource.Object instance
"""
if (obj not in self) or update:
self[obj.id] = Object.fromdict(
obj.id,
dict(
metadata=obj.metadata.read() if metadata is None else metadata,
bitstreams=[bs._properties for bs in obj.bitstreams]))
time.sleep(0.1)
return self.objects[obj.id] | [
"def",
"add",
"(",
"self",
",",
"obj",
",",
"metadata",
"=",
"None",
",",
"update",
"=",
"False",
")",
":",
"if",
"(",
"obj",
"not",
"in",
"self",
")",
"or",
"update",
":",
"self",
"[",
"obj",
".",
"id",
"]",
"=",
"Object",
".",
"fromdict",
"(",
"obj",
".",
"id",
",",
"dict",
"(",
"metadata",
"=",
"obj",
".",
"metadata",
".",
"read",
"(",
")",
"if",
"metadata",
"is",
"None",
"else",
"metadata",
",",
"bitstreams",
"=",
"[",
"bs",
".",
"_properties",
"for",
"bs",
"in",
"obj",
".",
"bitstreams",
"]",
")",
")",
"time",
".",
"sleep",
"(",
"0.1",
")",
"return",
"self",
".",
"objects",
"[",
"obj",
".",
"id",
"]"
] | Add an existing CDSTAR object to the catalog.
:param obj: A pycdstar.resource.Object instance | [
"Add",
"an",
"existing",
"CDSTAR",
"object",
"to",
"the",
"catalog",
"."
] | 41f33f59cdde5e30835d2f3accf2d1fbe5332cab | https://github.com/clld/cdstarcat/blob/41f33f59cdde5e30835d2f3accf2d1fbe5332cab/src/cdstarcat/catalog.py#L175-L188 |
249,348 | clld/cdstarcat | src/cdstarcat/catalog.py | Catalog.delete | def delete(self, obj):
"""
Delete an object in CDSTAR and remove it from the catalog.
:param obj: An object ID or an Object instance.
"""
obj = self.api.get_object(getattr(obj, 'id', obj))
obj.delete()
self.remove(obj.id) | python | def delete(self, obj):
"""
Delete an object in CDSTAR and remove it from the catalog.
:param obj: An object ID or an Object instance.
"""
obj = self.api.get_object(getattr(obj, 'id', obj))
obj.delete()
self.remove(obj.id) | [
"def",
"delete",
"(",
"self",
",",
"obj",
")",
":",
"obj",
"=",
"self",
".",
"api",
".",
"get_object",
"(",
"getattr",
"(",
"obj",
",",
"'id'",
",",
"obj",
")",
")",
"obj",
".",
"delete",
"(",
")",
"self",
".",
"remove",
"(",
"obj",
".",
"id",
")"
] | Delete an object in CDSTAR and remove it from the catalog.
:param obj: An object ID or an Object instance. | [
"Delete",
"an",
"object",
"in",
"CDSTAR",
"and",
"remove",
"it",
"from",
"the",
"catalog",
"."
] | 41f33f59cdde5e30835d2f3accf2d1fbe5332cab | https://github.com/clld/cdstarcat/blob/41f33f59cdde5e30835d2f3accf2d1fbe5332cab/src/cdstarcat/catalog.py#L200-L208 |
249,349 | clld/cdstarcat | src/cdstarcat/catalog.py | Catalog.create | def create(self, path, metadata, filter_=filter_hidden, object_class=None):
"""
Create objects in CDSTAR and register them in the catalog.
Note that we guess the mimetype based on the filename extension, using
`mimetypes.guess_type`. Thus, it is the caller's responsibility to add custom or
otherwise uncommon types to the list of known types using `mimetypes.add_type`.
:param path:
:param metadata:
:param filter_:
:return:
"""
path = Path(path)
if path.is_file():
fnames = [path]
elif path.is_dir():
fnames = list(walk(path, mode='files'))
else:
raise ValueError('path must be a file or directory') # pragma: no cover
for fname in fnames:
if not filter_ or filter_(fname):
created, obj = self._create(fname, metadata, object_class=object_class)
yield fname, created, obj | python | def create(self, path, metadata, filter_=filter_hidden, object_class=None):
"""
Create objects in CDSTAR and register them in the catalog.
Note that we guess the mimetype based on the filename extension, using
`mimetypes.guess_type`. Thus, it is the caller's responsibility to add custom or
otherwise uncommon types to the list of known types using `mimetypes.add_type`.
:param path:
:param metadata:
:param filter_:
:return:
"""
path = Path(path)
if path.is_file():
fnames = [path]
elif path.is_dir():
fnames = list(walk(path, mode='files'))
else:
raise ValueError('path must be a file or directory') # pragma: no cover
for fname in fnames:
if not filter_ or filter_(fname):
created, obj = self._create(fname, metadata, object_class=object_class)
yield fname, created, obj | [
"def",
"create",
"(",
"self",
",",
"path",
",",
"metadata",
",",
"filter_",
"=",
"filter_hidden",
",",
"object_class",
"=",
"None",
")",
":",
"path",
"=",
"Path",
"(",
"path",
")",
"if",
"path",
".",
"is_file",
"(",
")",
":",
"fnames",
"=",
"[",
"path",
"]",
"elif",
"path",
".",
"is_dir",
"(",
")",
":",
"fnames",
"=",
"list",
"(",
"walk",
"(",
"path",
",",
"mode",
"=",
"'files'",
")",
")",
"else",
":",
"raise",
"ValueError",
"(",
"'path must be a file or directory'",
")",
"# pragma: no cover",
"for",
"fname",
"in",
"fnames",
":",
"if",
"not",
"filter_",
"or",
"filter_",
"(",
"fname",
")",
":",
"created",
",",
"obj",
"=",
"self",
".",
"_create",
"(",
"fname",
",",
"metadata",
",",
"object_class",
"=",
"object_class",
")",
"yield",
"fname",
",",
"created",
",",
"obj"
] | Create objects in CDSTAR and register them in the catalog.
Note that we guess the mimetype based on the filename extension, using
`mimetypes.guess_type`. Thus, it is the caller's responsibility to add custom or
otherwise uncommon types to the list of known types using `mimetypes.add_type`.
:param path:
:param metadata:
:param filter_:
:return: | [
"Create",
"objects",
"in",
"CDSTAR",
"and",
"register",
"them",
"in",
"the",
"catalog",
"."
] | 41f33f59cdde5e30835d2f3accf2d1fbe5332cab | https://github.com/clld/cdstarcat/blob/41f33f59cdde5e30835d2f3accf2d1fbe5332cab/src/cdstarcat/catalog.py#L210-L233 |
249,350 | eddiejessup/spatious | spatious/distance.py | csep_close | def csep_close(ra, rb):
"""Return the closest separation vector between each point in one set,
and every point in a second set.
Parameters
----------
ra, rb: float array-like, shape (n, d) and (m, d) in d dimensions.
Two sets of points. `ra` is the set of points from which the closest
separation vectors to points `rb` are calculated.
Returns
-------
csep_close: float array-like, shape (n, m, d)
csep[i] is the closest separation vector from point ra[j]
to any point rb[i].
Note the un-intuitive vector direction.
"""
seps = csep(ra, rb)
seps_sq = np.sum(np.square(seps), axis=-1)
i_close = np.argmin(seps_sq, axis=-1)
i_all = list(range(len(seps)))
sep = seps[i_all, i_close]
sep_sq = seps_sq[i_all, i_close]
return sep, sep_sq | python | def csep_close(ra, rb):
"""Return the closest separation vector between each point in one set,
and every point in a second set.
Parameters
----------
ra, rb: float array-like, shape (n, d) and (m, d) in d dimensions.
Two sets of points. `ra` is the set of points from which the closest
separation vectors to points `rb` are calculated.
Returns
-------
csep_close: float array-like, shape (n, m, d)
csep[i] is the closest separation vector from point ra[j]
to any point rb[i].
Note the un-intuitive vector direction.
"""
seps = csep(ra, rb)
seps_sq = np.sum(np.square(seps), axis=-1)
i_close = np.argmin(seps_sq, axis=-1)
i_all = list(range(len(seps)))
sep = seps[i_all, i_close]
sep_sq = seps_sq[i_all, i_close]
return sep, sep_sq | [
"def",
"csep_close",
"(",
"ra",
",",
"rb",
")",
":",
"seps",
"=",
"csep",
"(",
"ra",
",",
"rb",
")",
"seps_sq",
"=",
"np",
".",
"sum",
"(",
"np",
".",
"square",
"(",
"seps",
")",
",",
"axis",
"=",
"-",
"1",
")",
"i_close",
"=",
"np",
".",
"argmin",
"(",
"seps_sq",
",",
"axis",
"=",
"-",
"1",
")",
"i_all",
"=",
"list",
"(",
"range",
"(",
"len",
"(",
"seps",
")",
")",
")",
"sep",
"=",
"seps",
"[",
"i_all",
",",
"i_close",
"]",
"sep_sq",
"=",
"seps_sq",
"[",
"i_all",
",",
"i_close",
"]",
"return",
"sep",
",",
"sep_sq"
] | Return the closest separation vector between each point in one set,
and every point in a second set.
Parameters
----------
ra, rb: float array-like, shape (n, d) and (m, d) in d dimensions.
Two sets of points. `ra` is the set of points from which the closest
separation vectors to points `rb` are calculated.
Returns
-------
csep_close: float array-like, shape (n, m, d)
csep[i] is the closest separation vector from point ra[j]
to any point rb[i].
Note the un-intuitive vector direction. | [
"Return",
"the",
"closest",
"separation",
"vector",
"between",
"each",
"point",
"in",
"one",
"set",
"and",
"every",
"point",
"in",
"a",
"second",
"set",
"."
] | b7ae91bec029e85a45a7f303ee184076433723cd | https://github.com/eddiejessup/spatious/blob/b7ae91bec029e85a45a7f303ee184076433723cd/spatious/distance.py#L28-L53 |
249,351 | eddiejessup/spatious | spatious/distance.py | csep_periodic | def csep_periodic(ra, rb, L):
"""Return separation vectors between each pair of the two sets of points.
Parameters
----------
ra, rb: float array-like, shape (n, d) and (m, d) in d dimensions.
Two sets of points.
L: float array, shape (d,)
System lengths.
Returns
-------
csep: float array-like, shape (n, m, d)
csep[i, j] is the separation vector from point j to point i.
Note the un-intuitive vector direction.
"""
seps = ra[:, np.newaxis, :] - rb[np.newaxis, :, :]
for i_dim in range(ra.shape[1]):
seps_dim = seps[:, :, i_dim]
seps_dim[seps_dim > L[i_dim] / 2.0] -= L[i_dim]
seps_dim[seps_dim < -L[i_dim] / 2.0] += L[i_dim]
return seps | python | def csep_periodic(ra, rb, L):
"""Return separation vectors between each pair of the two sets of points.
Parameters
----------
ra, rb: float array-like, shape (n, d) and (m, d) in d dimensions.
Two sets of points.
L: float array, shape (d,)
System lengths.
Returns
-------
csep: float array-like, shape (n, m, d)
csep[i, j] is the separation vector from point j to point i.
Note the un-intuitive vector direction.
"""
seps = ra[:, np.newaxis, :] - rb[np.newaxis, :, :]
for i_dim in range(ra.shape[1]):
seps_dim = seps[:, :, i_dim]
seps_dim[seps_dim > L[i_dim] / 2.0] -= L[i_dim]
seps_dim[seps_dim < -L[i_dim] / 2.0] += L[i_dim]
return seps | [
"def",
"csep_periodic",
"(",
"ra",
",",
"rb",
",",
"L",
")",
":",
"seps",
"=",
"ra",
"[",
":",
",",
"np",
".",
"newaxis",
",",
":",
"]",
"-",
"rb",
"[",
"np",
".",
"newaxis",
",",
":",
",",
":",
"]",
"for",
"i_dim",
"in",
"range",
"(",
"ra",
".",
"shape",
"[",
"1",
"]",
")",
":",
"seps_dim",
"=",
"seps",
"[",
":",
",",
":",
",",
"i_dim",
"]",
"seps_dim",
"[",
"seps_dim",
">",
"L",
"[",
"i_dim",
"]",
"/",
"2.0",
"]",
"-=",
"L",
"[",
"i_dim",
"]",
"seps_dim",
"[",
"seps_dim",
"<",
"-",
"L",
"[",
"i_dim",
"]",
"/",
"2.0",
"]",
"+=",
"L",
"[",
"i_dim",
"]",
"return",
"seps"
] | Return separation vectors between each pair of the two sets of points.
Parameters
----------
ra, rb: float array-like, shape (n, d) and (m, d) in d dimensions.
Two sets of points.
L: float array, shape (d,)
System lengths.
Returns
-------
csep: float array-like, shape (n, m, d)
csep[i, j] is the separation vector from point j to point i.
Note the un-intuitive vector direction. | [
"Return",
"separation",
"vectors",
"between",
"each",
"pair",
"of",
"the",
"two",
"sets",
"of",
"points",
"."
] | b7ae91bec029e85a45a7f303ee184076433723cd | https://github.com/eddiejessup/spatious/blob/b7ae91bec029e85a45a7f303ee184076433723cd/spatious/distance.py#L56-L77 |
249,352 | eddiejessup/spatious | spatious/distance.py | csep_periodic_close | def csep_periodic_close(ra, rb, L):
"""Return the closest separation vector between each point in one set,
and every point in a second set, in periodic space.
Parameters
----------
ra, rb: float array-like, shape (n, d) and (m, d) in d dimensions.
Two sets of points. `ra` is the set of points from which the closest
separation vectors to points `rb` are calculated.
L: float array, shape (d,)
System lengths.
Returns
-------
csep_close: float array-like, shape (n, m, d)
csep[i] is the closest separation vector from point ra[j]
to any point rb[i].
Note the un-intuitive vector direction.
"""
seps = csep_periodic(ra, rb, L)
seps_sq = np.sum(np.square(seps), axis=-1)
i_close = np.argmin(seps_sq, axis=-1)
i_all = list(range(len(seps)))
sep = seps[i_all, i_close]
sep_sq = seps_sq[i_all, i_close]
return sep, sep_sq | python | def csep_periodic_close(ra, rb, L):
"""Return the closest separation vector between each point in one set,
and every point in a second set, in periodic space.
Parameters
----------
ra, rb: float array-like, shape (n, d) and (m, d) in d dimensions.
Two sets of points. `ra` is the set of points from which the closest
separation vectors to points `rb` are calculated.
L: float array, shape (d,)
System lengths.
Returns
-------
csep_close: float array-like, shape (n, m, d)
csep[i] is the closest separation vector from point ra[j]
to any point rb[i].
Note the un-intuitive vector direction.
"""
seps = csep_periodic(ra, rb, L)
seps_sq = np.sum(np.square(seps), axis=-1)
i_close = np.argmin(seps_sq, axis=-1)
i_all = list(range(len(seps)))
sep = seps[i_all, i_close]
sep_sq = seps_sq[i_all, i_close]
return sep, sep_sq | [
"def",
"csep_periodic_close",
"(",
"ra",
",",
"rb",
",",
"L",
")",
":",
"seps",
"=",
"csep_periodic",
"(",
"ra",
",",
"rb",
",",
"L",
")",
"seps_sq",
"=",
"np",
".",
"sum",
"(",
"np",
".",
"square",
"(",
"seps",
")",
",",
"axis",
"=",
"-",
"1",
")",
"i_close",
"=",
"np",
".",
"argmin",
"(",
"seps_sq",
",",
"axis",
"=",
"-",
"1",
")",
"i_all",
"=",
"list",
"(",
"range",
"(",
"len",
"(",
"seps",
")",
")",
")",
"sep",
"=",
"seps",
"[",
"i_all",
",",
"i_close",
"]",
"sep_sq",
"=",
"seps_sq",
"[",
"i_all",
",",
"i_close",
"]",
"return",
"sep",
",",
"sep_sq"
] | Return the closest separation vector between each point in one set,
and every point in a second set, in periodic space.
Parameters
----------
ra, rb: float array-like, shape (n, d) and (m, d) in d dimensions.
Two sets of points. `ra` is the set of points from which the closest
separation vectors to points `rb` are calculated.
L: float array, shape (d,)
System lengths.
Returns
-------
csep_close: float array-like, shape (n, m, d)
csep[i] is the closest separation vector from point ra[j]
to any point rb[i].
Note the un-intuitive vector direction. | [
"Return",
"the",
"closest",
"separation",
"vector",
"between",
"each",
"point",
"in",
"one",
"set",
"and",
"every",
"point",
"in",
"a",
"second",
"set",
"in",
"periodic",
"space",
"."
] | b7ae91bec029e85a45a7f303ee184076433723cd | https://github.com/eddiejessup/spatious/blob/b7ae91bec029e85a45a7f303ee184076433723cd/spatious/distance.py#L80-L107 |
249,353 | eddiejessup/spatious | spatious/distance.py | cdist_sq_periodic | def cdist_sq_periodic(ra, rb, L):
"""Return the squared distance between each point in on set,
and every point in a second set, in periodic space.
Parameters
----------
ra, rb: float array-like, shape (n, d) and (m, d) in d dimensions.
Two sets of points.
L: float array, shape (d,)
System lengths.
Returns
-------
cdist_sq: float array-like, shape (n, m, d)
cdist_sq[i, j] is the squared distance between point j and point i.
"""
return np.sum(np.square(csep_periodic(ra, rb, L)), axis=-1) | python | def cdist_sq_periodic(ra, rb, L):
"""Return the squared distance between each point in on set,
and every point in a second set, in periodic space.
Parameters
----------
ra, rb: float array-like, shape (n, d) and (m, d) in d dimensions.
Two sets of points.
L: float array, shape (d,)
System lengths.
Returns
-------
cdist_sq: float array-like, shape (n, m, d)
cdist_sq[i, j] is the squared distance between point j and point i.
"""
return np.sum(np.square(csep_periodic(ra, rb, L)), axis=-1) | [
"def",
"cdist_sq_periodic",
"(",
"ra",
",",
"rb",
",",
"L",
")",
":",
"return",
"np",
".",
"sum",
"(",
"np",
".",
"square",
"(",
"csep_periodic",
"(",
"ra",
",",
"rb",
",",
"L",
")",
")",
",",
"axis",
"=",
"-",
"1",
")"
] | Return the squared distance between each point in on set,
and every point in a second set, in periodic space.
Parameters
----------
ra, rb: float array-like, shape (n, d) and (m, d) in d dimensions.
Two sets of points.
L: float array, shape (d,)
System lengths.
Returns
-------
cdist_sq: float array-like, shape (n, m, d)
cdist_sq[i, j] is the squared distance between point j and point i. | [
"Return",
"the",
"squared",
"distance",
"between",
"each",
"point",
"in",
"on",
"set",
"and",
"every",
"point",
"in",
"a",
"second",
"set",
"in",
"periodic",
"space",
"."
] | b7ae91bec029e85a45a7f303ee184076433723cd | https://github.com/eddiejessup/spatious/blob/b7ae91bec029e85a45a7f303ee184076433723cd/spatious/distance.py#L110-L126 |
249,354 | eddiejessup/spatious | spatious/distance.py | pdist_sq_periodic | def pdist_sq_periodic(r, L):
"""Return the squared distance between all combinations of
a set of points, in periodic space.
Parameters
----------
r: shape (n, d) for n points in d dimensions.
Set of points
L: float array, shape (d,)
System lengths.
Returns
-------
d_sq: float array, shape (n, n, d)
Squared distances
"""
d = csep_periodic(r, r, L)
d[np.identity(len(r), dtype=np.bool)] = np.inf
d_sq = np.sum(np.square(d), axis=-1)
return d_sq | python | def pdist_sq_periodic(r, L):
"""Return the squared distance between all combinations of
a set of points, in periodic space.
Parameters
----------
r: shape (n, d) for n points in d dimensions.
Set of points
L: float array, shape (d,)
System lengths.
Returns
-------
d_sq: float array, shape (n, n, d)
Squared distances
"""
d = csep_periodic(r, r, L)
d[np.identity(len(r), dtype=np.bool)] = np.inf
d_sq = np.sum(np.square(d), axis=-1)
return d_sq | [
"def",
"pdist_sq_periodic",
"(",
"r",
",",
"L",
")",
":",
"d",
"=",
"csep_periodic",
"(",
"r",
",",
"r",
",",
"L",
")",
"d",
"[",
"np",
".",
"identity",
"(",
"len",
"(",
"r",
")",
",",
"dtype",
"=",
"np",
".",
"bool",
")",
"]",
"=",
"np",
".",
"inf",
"d_sq",
"=",
"np",
".",
"sum",
"(",
"np",
".",
"square",
"(",
"d",
")",
",",
"axis",
"=",
"-",
"1",
")",
"return",
"d_sq"
] | Return the squared distance between all combinations of
a set of points, in periodic space.
Parameters
----------
r: shape (n, d) for n points in d dimensions.
Set of points
L: float array, shape (d,)
System lengths.
Returns
-------
d_sq: float array, shape (n, n, d)
Squared distances | [
"Return",
"the",
"squared",
"distance",
"between",
"all",
"combinations",
"of",
"a",
"set",
"of",
"points",
"in",
"periodic",
"space",
"."
] | b7ae91bec029e85a45a7f303ee184076433723cd | https://github.com/eddiejessup/spatious/blob/b7ae91bec029e85a45a7f303ee184076433723cd/spatious/distance.py#L129-L148 |
249,355 | eddiejessup/spatious | spatious/distance.py | angular_distance | def angular_distance(n1, n2):
"""Return the angular separation between two 3 dimensional vectors.
Parameters
----------
n1, n2: array-like, shape (3,)
Coordinates of two vectors.
Their magnitude does not matter.
Returns
-------
d_sigma: float
Angle between n1 and n2 in radians.
"""
return np.arctan2(vector.vector_mag(np.cross(n1, n2)), np.dot(n1, n2)) | python | def angular_distance(n1, n2):
"""Return the angular separation between two 3 dimensional vectors.
Parameters
----------
n1, n2: array-like, shape (3,)
Coordinates of two vectors.
Their magnitude does not matter.
Returns
-------
d_sigma: float
Angle between n1 and n2 in radians.
"""
return np.arctan2(vector.vector_mag(np.cross(n1, n2)), np.dot(n1, n2)) | [
"def",
"angular_distance",
"(",
"n1",
",",
"n2",
")",
":",
"return",
"np",
".",
"arctan2",
"(",
"vector",
".",
"vector_mag",
"(",
"np",
".",
"cross",
"(",
"n1",
",",
"n2",
")",
")",
",",
"np",
".",
"dot",
"(",
"n1",
",",
"n2",
")",
")"
] | Return the angular separation between two 3 dimensional vectors.
Parameters
----------
n1, n2: array-like, shape (3,)
Coordinates of two vectors.
Their magnitude does not matter.
Returns
-------
d_sigma: float
Angle between n1 and n2 in radians. | [
"Return",
"the",
"angular",
"separation",
"between",
"two",
"3",
"dimensional",
"vectors",
"."
] | b7ae91bec029e85a45a7f303ee184076433723cd | https://github.com/eddiejessup/spatious/blob/b7ae91bec029e85a45a7f303ee184076433723cd/spatious/distance.py#L151-L165 |
249,356 | treycucco/bidon | bidon/field_mapping.py | FieldMapping.get_namedtuple | def get_namedtuple(cls, field_mappings, name="Record"):
"""Gets a namedtuple class that matches the destination_names in the list of field_mappings."""
return namedtuple(name, [fm.destination_name for fm in field_mappings]) | python | def get_namedtuple(cls, field_mappings, name="Record"):
"""Gets a namedtuple class that matches the destination_names in the list of field_mappings."""
return namedtuple(name, [fm.destination_name for fm in field_mappings]) | [
"def",
"get_namedtuple",
"(",
"cls",
",",
"field_mappings",
",",
"name",
"=",
"\"Record\"",
")",
":",
"return",
"namedtuple",
"(",
"name",
",",
"[",
"fm",
".",
"destination_name",
"for",
"fm",
"in",
"field_mappings",
"]",
")"
] | Gets a namedtuple class that matches the destination_names in the list of field_mappings. | [
"Gets",
"a",
"namedtuple",
"class",
"that",
"matches",
"the",
"destination_names",
"in",
"the",
"list",
"of",
"field_mappings",
"."
] | d9f24596841d0e69e8ac70a1d1a1deecea95e340 | https://github.com/treycucco/bidon/blob/d9f24596841d0e69e8ac70a1d1a1deecea95e340/bidon/field_mapping.py#L43-L45 |
249,357 | treycucco/bidon | bidon/field_mapping.py | FieldMapping.transfer | def transfer(cls, field_mappings, source, destination_factory):
"""Convert a record to a dictionary via field_mappings, and pass that to destination_factory."""
data = dict()
for index, field_mapping in enumerate(field_mappings):
try:
data[field_mapping.destination_name] = field_mapping.get_value(source)
except Exception as ex:
raise Exception(
"Error with mapping #{0} '{1}'->'{2}': {3}".format(
index,
field_mapping.source_name,
field_mapping.destination_name, ex)) from ex
return destination_factory(data) | python | def transfer(cls, field_mappings, source, destination_factory):
"""Convert a record to a dictionary via field_mappings, and pass that to destination_factory."""
data = dict()
for index, field_mapping in enumerate(field_mappings):
try:
data[field_mapping.destination_name] = field_mapping.get_value(source)
except Exception as ex:
raise Exception(
"Error with mapping #{0} '{1}'->'{2}': {3}".format(
index,
field_mapping.source_name,
field_mapping.destination_name, ex)) from ex
return destination_factory(data) | [
"def",
"transfer",
"(",
"cls",
",",
"field_mappings",
",",
"source",
",",
"destination_factory",
")",
":",
"data",
"=",
"dict",
"(",
")",
"for",
"index",
",",
"field_mapping",
"in",
"enumerate",
"(",
"field_mappings",
")",
":",
"try",
":",
"data",
"[",
"field_mapping",
".",
"destination_name",
"]",
"=",
"field_mapping",
".",
"get_value",
"(",
"source",
")",
"except",
"Exception",
"as",
"ex",
":",
"raise",
"Exception",
"(",
"\"Error with mapping #{0} '{1}'->'{2}': {3}\"",
".",
"format",
"(",
"index",
",",
"field_mapping",
".",
"source_name",
",",
"field_mapping",
".",
"destination_name",
",",
"ex",
")",
")",
"from",
"ex",
"return",
"destination_factory",
"(",
"data",
")"
] | Convert a record to a dictionary via field_mappings, and pass that to destination_factory. | [
"Convert",
"a",
"record",
"to",
"a",
"dictionary",
"via",
"field_mappings",
"and",
"pass",
"that",
"to",
"destination_factory",
"."
] | d9f24596841d0e69e8ac70a1d1a1deecea95e340 | https://github.com/treycucco/bidon/blob/d9f24596841d0e69e8ac70a1d1a1deecea95e340/bidon/field_mapping.py#L56-L68 |
249,358 | treycucco/bidon | bidon/field_mapping.py | FieldMapping.transfer_all | def transfer_all(cls, field_mappings, sources, destination_factory=None):
"""Calls cls.transfer on all records in sources."""
for index, source in enumerate(sources):
try:
yield cls.transfer(field_mappings, source, destination_factory or (lambda x: x))
except Exception as ex:
raise Exception("Error with source #{0}: {1}".format(index, ex)) from ex | python | def transfer_all(cls, field_mappings, sources, destination_factory=None):
"""Calls cls.transfer on all records in sources."""
for index, source in enumerate(sources):
try:
yield cls.transfer(field_mappings, source, destination_factory or (lambda x: x))
except Exception as ex:
raise Exception("Error with source #{0}: {1}".format(index, ex)) from ex | [
"def",
"transfer_all",
"(",
"cls",
",",
"field_mappings",
",",
"sources",
",",
"destination_factory",
"=",
"None",
")",
":",
"for",
"index",
",",
"source",
"in",
"enumerate",
"(",
"sources",
")",
":",
"try",
":",
"yield",
"cls",
".",
"transfer",
"(",
"field_mappings",
",",
"source",
",",
"destination_factory",
"or",
"(",
"lambda",
"x",
":",
"x",
")",
")",
"except",
"Exception",
"as",
"ex",
":",
"raise",
"Exception",
"(",
"\"Error with source #{0}: {1}\"",
".",
"format",
"(",
"index",
",",
"ex",
")",
")",
"from",
"ex"
] | Calls cls.transfer on all records in sources. | [
"Calls",
"cls",
".",
"transfer",
"on",
"all",
"records",
"in",
"sources",
"."
] | d9f24596841d0e69e8ac70a1d1a1deecea95e340 | https://github.com/treycucco/bidon/blob/d9f24596841d0e69e8ac70a1d1a1deecea95e340/bidon/field_mapping.py#L71-L77 |
249,359 | cogniteev/yamlious | yamlious/__init__.py | merge_dict | def merge_dict(lhs, rhs):
""" Merge content of a dict in another
:param: dict: lhs
dict where is merged the second one
:param: dict: rhs
dict whose content is merged
"""
assert isinstance(lhs, dict)
assert isinstance(rhs, dict)
for k, v in rhs.iteritems():
if k not in lhs:
lhs[k] = v
else:
lhs[k] = merge_dict(lhs[k], v)
return lhs | python | def merge_dict(lhs, rhs):
""" Merge content of a dict in another
:param: dict: lhs
dict where is merged the second one
:param: dict: rhs
dict whose content is merged
"""
assert isinstance(lhs, dict)
assert isinstance(rhs, dict)
for k, v in rhs.iteritems():
if k not in lhs:
lhs[k] = v
else:
lhs[k] = merge_dict(lhs[k], v)
return lhs | [
"def",
"merge_dict",
"(",
"lhs",
",",
"rhs",
")",
":",
"assert",
"isinstance",
"(",
"lhs",
",",
"dict",
")",
"assert",
"isinstance",
"(",
"rhs",
",",
"dict",
")",
"for",
"k",
",",
"v",
"in",
"rhs",
".",
"iteritems",
"(",
")",
":",
"if",
"k",
"not",
"in",
"lhs",
":",
"lhs",
"[",
"k",
"]",
"=",
"v",
"else",
":",
"lhs",
"[",
"k",
"]",
"=",
"merge_dict",
"(",
"lhs",
"[",
"k",
"]",
",",
"v",
")",
"return",
"lhs"
] | Merge content of a dict in another
:param: dict: lhs
dict where is merged the second one
:param: dict: rhs
dict whose content is merged | [
"Merge",
"content",
"of",
"a",
"dict",
"in",
"another"
] | fc6a603367c2135b43ef2356959963d9dccbb25a | https://github.com/cogniteev/yamlious/blob/fc6a603367c2135b43ef2356959963d9dccbb25a/yamlious/__init__.py#L21-L36 |
249,360 | cogniteev/yamlious | yamlious/__init__.py | from_yaml | def from_yaml(*streams):
""" Build voluptuous.Schema function parameters from a streams of YAMLs
"""
return from_dict(merge_dicts(*map(
lambda f: yaml.load(f, Loader=Loader),
list(streams)
))) | python | def from_yaml(*streams):
""" Build voluptuous.Schema function parameters from a streams of YAMLs
"""
return from_dict(merge_dicts(*map(
lambda f: yaml.load(f, Loader=Loader),
list(streams)
))) | [
"def",
"from_yaml",
"(",
"*",
"streams",
")",
":",
"return",
"from_dict",
"(",
"merge_dicts",
"(",
"*",
"map",
"(",
"lambda",
"f",
":",
"yaml",
".",
"load",
"(",
"f",
",",
"Loader",
"=",
"Loader",
")",
",",
"list",
"(",
"streams",
")",
")",
")",
")"
] | Build voluptuous.Schema function parameters from a streams of YAMLs | [
"Build",
"voluptuous",
".",
"Schema",
"function",
"parameters",
"from",
"a",
"streams",
"of",
"YAMLs"
] | fc6a603367c2135b43ef2356959963d9dccbb25a | https://github.com/cogniteev/yamlious/blob/fc6a603367c2135b43ef2356959963d9dccbb25a/yamlious/__init__.py#L182-L188 |
249,361 | etcher-be/elib_config | elib_config/_validate.py | validate_config | def validate_config(raise_=True):
"""
Verifies that all configuration values have a valid setting
"""
ELIBConfig.check()
known_paths = set()
duplicate_values = set()
missing_values = set()
for config_value in ConfigValue.config_values:
if config_value.path not in known_paths:
known_paths.add(config_value.path)
else:
duplicate_values.add(config_value.name)
try:
config_value()
except MissingValueError:
missing_values.add(config_value.name)
if raise_ and duplicate_values:
raise DuplicateConfigValueError(str(duplicate_values))
if raise_ and missing_values:
raise MissingValueError(str(missing_values), 'missing config value(s)')
return duplicate_values, missing_values | python | def validate_config(raise_=True):
"""
Verifies that all configuration values have a valid setting
"""
ELIBConfig.check()
known_paths = set()
duplicate_values = set()
missing_values = set()
for config_value in ConfigValue.config_values:
if config_value.path not in known_paths:
known_paths.add(config_value.path)
else:
duplicate_values.add(config_value.name)
try:
config_value()
except MissingValueError:
missing_values.add(config_value.name)
if raise_ and duplicate_values:
raise DuplicateConfigValueError(str(duplicate_values))
if raise_ and missing_values:
raise MissingValueError(str(missing_values), 'missing config value(s)')
return duplicate_values, missing_values | [
"def",
"validate_config",
"(",
"raise_",
"=",
"True",
")",
":",
"ELIBConfig",
".",
"check",
"(",
")",
"known_paths",
"=",
"set",
"(",
")",
"duplicate_values",
"=",
"set",
"(",
")",
"missing_values",
"=",
"set",
"(",
")",
"for",
"config_value",
"in",
"ConfigValue",
".",
"config_values",
":",
"if",
"config_value",
".",
"path",
"not",
"in",
"known_paths",
":",
"known_paths",
".",
"add",
"(",
"config_value",
".",
"path",
")",
"else",
":",
"duplicate_values",
".",
"add",
"(",
"config_value",
".",
"name",
")",
"try",
":",
"config_value",
"(",
")",
"except",
"MissingValueError",
":",
"missing_values",
".",
"add",
"(",
"config_value",
".",
"name",
")",
"if",
"raise_",
"and",
"duplicate_values",
":",
"raise",
"DuplicateConfigValueError",
"(",
"str",
"(",
"duplicate_values",
")",
")",
"if",
"raise_",
"and",
"missing_values",
":",
"raise",
"MissingValueError",
"(",
"str",
"(",
"missing_values",
")",
",",
"'missing config value(s)'",
")",
"return",
"duplicate_values",
",",
"missing_values"
] | Verifies that all configuration values have a valid setting | [
"Verifies",
"that",
"all",
"configuration",
"values",
"have",
"a",
"valid",
"setting"
] | 5d8c839e84d70126620ab0186dc1f717e5868bd0 | https://github.com/etcher-be/elib_config/blob/5d8c839e84d70126620ab0186dc1f717e5868bd0/elib_config/_validate.py#L13-L35 |
249,362 | alexandershov/mess | mess/dicts.py | groupby | def groupby(iterable, key=None):
"""
Group items from iterable by key and return a dictionary where values are
the lists of items from the iterable having the same key.
:param key: function to apply to each element of the iterable.
If not specified or is None key defaults to identity function and
returns the element unchanged.
:Example:
>>> groupby([0, 1, 2, 3], key=lambda x: x % 2 == 0)
{True: [0, 2], False: [1, 3]}
"""
groups = {}
for item in iterable:
if key is None:
key_value = item
else:
key_value = key(item)
groups.setdefault(key_value, []).append(item)
return groups | python | def groupby(iterable, key=None):
"""
Group items from iterable by key and return a dictionary where values are
the lists of items from the iterable having the same key.
:param key: function to apply to each element of the iterable.
If not specified or is None key defaults to identity function and
returns the element unchanged.
:Example:
>>> groupby([0, 1, 2, 3], key=lambda x: x % 2 == 0)
{True: [0, 2], False: [1, 3]}
"""
groups = {}
for item in iterable:
if key is None:
key_value = item
else:
key_value = key(item)
groups.setdefault(key_value, []).append(item)
return groups | [
"def",
"groupby",
"(",
"iterable",
",",
"key",
"=",
"None",
")",
":",
"groups",
"=",
"{",
"}",
"for",
"item",
"in",
"iterable",
":",
"if",
"key",
"is",
"None",
":",
"key_value",
"=",
"item",
"else",
":",
"key_value",
"=",
"key",
"(",
"item",
")",
"groups",
".",
"setdefault",
"(",
"key_value",
",",
"[",
"]",
")",
".",
"append",
"(",
"item",
")",
"return",
"groups"
] | Group items from iterable by key and return a dictionary where values are
the lists of items from the iterable having the same key.
:param key: function to apply to each element of the iterable.
If not specified or is None key defaults to identity function and
returns the element unchanged.
:Example:
>>> groupby([0, 1, 2, 3], key=lambda x: x % 2 == 0)
{True: [0, 2], False: [1, 3]} | [
"Group",
"items",
"from",
"iterable",
"by",
"key",
"and",
"return",
"a",
"dictionary",
"where",
"values",
"are",
"the",
"lists",
"of",
"items",
"from",
"the",
"iterable",
"having",
"the",
"same",
"key",
"."
] | 7b0d956c1fd39cca2e4adcd5dc35952ec3ed3fd5 | https://github.com/alexandershov/mess/blob/7b0d956c1fd39cca2e4adcd5dc35952ec3ed3fd5/mess/dicts.py#L1-L21 |
249,363 | corydodt/Crosscap | crosscap/tree.py | enter | def enter(clsQname):
"""
Delegate a rule to another class which instantiates a Klein app
This also memoizes the resource instance on the handler function itself
"""
def wrapper(routeHandler):
@functools.wraps(routeHandler)
def inner(self, request, *a, **kw):
if getattr(inner, '_subKlein', None) is None:
cls = namedAny(clsQname)
inner._subKlein = cls().app.resource()
return routeHandler(self, request, inner._subKlein, *a, **kw)
inner._subKleinQname = clsQname
return inner
return wrapper | python | def enter(clsQname):
"""
Delegate a rule to another class which instantiates a Klein app
This also memoizes the resource instance on the handler function itself
"""
def wrapper(routeHandler):
@functools.wraps(routeHandler)
def inner(self, request, *a, **kw):
if getattr(inner, '_subKlein', None) is None:
cls = namedAny(clsQname)
inner._subKlein = cls().app.resource()
return routeHandler(self, request, inner._subKlein, *a, **kw)
inner._subKleinQname = clsQname
return inner
return wrapper | [
"def",
"enter",
"(",
"clsQname",
")",
":",
"def",
"wrapper",
"(",
"routeHandler",
")",
":",
"@",
"functools",
".",
"wraps",
"(",
"routeHandler",
")",
"def",
"inner",
"(",
"self",
",",
"request",
",",
"*",
"a",
",",
"*",
"*",
"kw",
")",
":",
"if",
"getattr",
"(",
"inner",
",",
"'_subKlein'",
",",
"None",
")",
"is",
"None",
":",
"cls",
"=",
"namedAny",
"(",
"clsQname",
")",
"inner",
".",
"_subKlein",
"=",
"cls",
"(",
")",
".",
"app",
".",
"resource",
"(",
")",
"return",
"routeHandler",
"(",
"self",
",",
"request",
",",
"inner",
".",
"_subKlein",
",",
"*",
"a",
",",
"*",
"*",
"kw",
")",
"inner",
".",
"_subKleinQname",
"=",
"clsQname",
"return",
"inner",
"return",
"wrapper"
] | Delegate a rule to another class which instantiates a Klein app
This also memoizes the resource instance on the handler function itself | [
"Delegate",
"a",
"rule",
"to",
"another",
"class",
"which",
"instantiates",
"a",
"Klein",
"app"
] | 388a2ec36b8aa85e8f1ed692bb6e43474ba76c8e | https://github.com/corydodt/Crosscap/blob/388a2ec36b8aa85e8f1ed692bb6e43474ba76c8e/crosscap/tree.py#L35-L50 |
249,364 | corydodt/Crosscap | crosscap/tree.py | openAPIDoc | def openAPIDoc(**kwargs):
"""
Update a function's docstring to include the OpenAPI Yaml generated by running the openAPIGraph object
"""
s = yaml.dump(kwargs, default_flow_style=False)
def deco(routeHandler):
# Wrap routeHandler, retaining name and __doc__, then edit __doc__.
# The only reason we need to do this is so we can be certain
# that __doc__ will be modifiable. partial() objects have
# a modifiable __doc__, but native function objects do not.
ret = functools.wraps(routeHandler)(routeHandler)
if not ret.__doc__:
ret.__doc__ = ''
ret.__doc__ = cleandoc(ret.__doc__) + '\n---\n' + s
return ret
return deco | python | def openAPIDoc(**kwargs):
"""
Update a function's docstring to include the OpenAPI Yaml generated by running the openAPIGraph object
"""
s = yaml.dump(kwargs, default_flow_style=False)
def deco(routeHandler):
# Wrap routeHandler, retaining name and __doc__, then edit __doc__.
# The only reason we need to do this is so we can be certain
# that __doc__ will be modifiable. partial() objects have
# a modifiable __doc__, but native function objects do not.
ret = functools.wraps(routeHandler)(routeHandler)
if not ret.__doc__:
ret.__doc__ = ''
ret.__doc__ = cleandoc(ret.__doc__) + '\n---\n' + s
return ret
return deco | [
"def",
"openAPIDoc",
"(",
"*",
"*",
"kwargs",
")",
":",
"s",
"=",
"yaml",
".",
"dump",
"(",
"kwargs",
",",
"default_flow_style",
"=",
"False",
")",
"def",
"deco",
"(",
"routeHandler",
")",
":",
"# Wrap routeHandler, retaining name and __doc__, then edit __doc__.",
"# The only reason we need to do this is so we can be certain",
"# that __doc__ will be modifiable. partial() objects have",
"# a modifiable __doc__, but native function objects do not.",
"ret",
"=",
"functools",
".",
"wraps",
"(",
"routeHandler",
")",
"(",
"routeHandler",
")",
"if",
"not",
"ret",
".",
"__doc__",
":",
"ret",
".",
"__doc__",
"=",
"''",
"ret",
".",
"__doc__",
"=",
"cleandoc",
"(",
"ret",
".",
"__doc__",
")",
"+",
"'\\n---\\n'",
"+",
"s",
"return",
"ret",
"return",
"deco"
] | Update a function's docstring to include the OpenAPI Yaml generated by running the openAPIGraph object | [
"Update",
"a",
"function",
"s",
"docstring",
"to",
"include",
"the",
"OpenAPI",
"Yaml",
"generated",
"by",
"running",
"the",
"openAPIGraph",
"object"
] | 388a2ec36b8aa85e8f1ed692bb6e43474ba76c8e | https://github.com/corydodt/Crosscap/blob/388a2ec36b8aa85e8f1ed692bb6e43474ba76c8e/crosscap/tree.py#L53-L69 |
249,365 | artisanofcode/python-broadway | broadway/errors.py | init_app | def init_app(application):
"""
Associates the error handler
"""
for code in werkzeug.exceptions.default_exceptions:
application.register_error_handler(code, handle_http_exception) | python | def init_app(application):
"""
Associates the error handler
"""
for code in werkzeug.exceptions.default_exceptions:
application.register_error_handler(code, handle_http_exception) | [
"def",
"init_app",
"(",
"application",
")",
":",
"for",
"code",
"in",
"werkzeug",
".",
"exceptions",
".",
"default_exceptions",
":",
"application",
".",
"register_error_handler",
"(",
"code",
",",
"handle_http_exception",
")"
] | Associates the error handler | [
"Associates",
"the",
"error",
"handler"
] | a051ca5a922ecb38a541df59e8740e2a047d9a4a | https://github.com/artisanofcode/python-broadway/blob/a051ca5a922ecb38a541df59e8740e2a047d9a4a/broadway/errors.py#L40-L45 |
249,366 | mixmastamyk/out | out/__init__.py | _find_palettes | def _find_palettes(stream):
''' Need to configure palettes manually, since we are checking stderr. '''
chosen = choose_palette(stream=stream)
palettes = get_available_palettes(chosen)
fg = ForegroundPalette(palettes=palettes)
fx = EffectsPalette(palettes=palettes)
return fg, fx, chosen | python | def _find_palettes(stream):
''' Need to configure palettes manually, since we are checking stderr. '''
chosen = choose_palette(stream=stream)
palettes = get_available_palettes(chosen)
fg = ForegroundPalette(palettes=palettes)
fx = EffectsPalette(palettes=palettes)
return fg, fx, chosen | [
"def",
"_find_palettes",
"(",
"stream",
")",
":",
"chosen",
"=",
"choose_palette",
"(",
"stream",
"=",
"stream",
")",
"palettes",
"=",
"get_available_palettes",
"(",
"chosen",
")",
"fg",
"=",
"ForegroundPalette",
"(",
"palettes",
"=",
"palettes",
")",
"fx",
"=",
"EffectsPalette",
"(",
"palettes",
"=",
"palettes",
")",
"return",
"fg",
",",
"fx",
",",
"chosen"
] | Need to configure palettes manually, since we are checking stderr. | [
"Need",
"to",
"configure",
"palettes",
"manually",
"since",
"we",
"are",
"checking",
"stderr",
"."
] | f5e02a783ed529e21753c7e6233d0c5550241fd9 | https://github.com/mixmastamyk/out/blob/f5e02a783ed529e21753c7e6233d0c5550241fd9/out/__init__.py#L22-L28 |
249,367 | mixmastamyk/out | out/__init__.py | Logger.configure | def configure(self, **kwargs):
''' Convenience function to set a number of parameters on this logger
and associated handlers and formatters.
'''
for kwarg in kwargs:
value = kwargs[kwarg]
if kwarg == 'level':
self.set_level(value)
elif kwarg == 'default_level':
self.default_level = level_map.get(value, value)
elif kwarg == 'datefmt':
self.handlers[0].formatter.datefmt = value
elif kwarg == 'msgfmt':
self.handlers[0].formatter._style._fmt = value
elif kwarg == 'stream':
global fg, fx, _CHOSEN_PALETTE
self.handlers[0].stream = value
fg, fx, _CHOSEN_PALETTE = _find_palettes(value)
elif kwarg == 'theme':
if type(value) is str:
theme = _themes[value]
if value == 'plain':
fmtr = logging.Formatter(style='{', **theme)
elif value == 'json':
fmtr = _JSONFormatter(**theme)
else:
fmtr = _ColorFormatter(tty=_is_a_tty, **theme)
elif type(value) is dict:
if 'style' in value or 'icons' in value:
fmtr = _ColorFormatter(tty=_is_a_tty, **theme)
else:
fmtr = logging.Formatter(style='{', **theme)
self.handlers[0].setFormatter(fmtr)
elif kwarg == 'icons':
if type(value) is str:
value = _icons[value]
self.handlers[0].formatter._theme_icons = value
elif kwarg == 'style':
if type(value) is str:
value = _styles[value]
self.handlers[0].formatter._theme_style = value
elif kwarg == 'lexer':
try:
self.handlers[0].formatter.set_lexer(value)
except AttributeError as err:
self.error('lexer: ColorFormatter not available.')
else:
raise NameError('unknown keyword argument: %s' % kwarg) | python | def configure(self, **kwargs):
''' Convenience function to set a number of parameters on this logger
and associated handlers and formatters.
'''
for kwarg in kwargs:
value = kwargs[kwarg]
if kwarg == 'level':
self.set_level(value)
elif kwarg == 'default_level':
self.default_level = level_map.get(value, value)
elif kwarg == 'datefmt':
self.handlers[0].formatter.datefmt = value
elif kwarg == 'msgfmt':
self.handlers[0].formatter._style._fmt = value
elif kwarg == 'stream':
global fg, fx, _CHOSEN_PALETTE
self.handlers[0].stream = value
fg, fx, _CHOSEN_PALETTE = _find_palettes(value)
elif kwarg == 'theme':
if type(value) is str:
theme = _themes[value]
if value == 'plain':
fmtr = logging.Formatter(style='{', **theme)
elif value == 'json':
fmtr = _JSONFormatter(**theme)
else:
fmtr = _ColorFormatter(tty=_is_a_tty, **theme)
elif type(value) is dict:
if 'style' in value or 'icons' in value:
fmtr = _ColorFormatter(tty=_is_a_tty, **theme)
else:
fmtr = logging.Formatter(style='{', **theme)
self.handlers[0].setFormatter(fmtr)
elif kwarg == 'icons':
if type(value) is str:
value = _icons[value]
self.handlers[0].formatter._theme_icons = value
elif kwarg == 'style':
if type(value) is str:
value = _styles[value]
self.handlers[0].formatter._theme_style = value
elif kwarg == 'lexer':
try:
self.handlers[0].formatter.set_lexer(value)
except AttributeError as err:
self.error('lexer: ColorFormatter not available.')
else:
raise NameError('unknown keyword argument: %s' % kwarg) | [
"def",
"configure",
"(",
"self",
",",
"*",
"*",
"kwargs",
")",
":",
"for",
"kwarg",
"in",
"kwargs",
":",
"value",
"=",
"kwargs",
"[",
"kwarg",
"]",
"if",
"kwarg",
"==",
"'level'",
":",
"self",
".",
"set_level",
"(",
"value",
")",
"elif",
"kwarg",
"==",
"'default_level'",
":",
"self",
".",
"default_level",
"=",
"level_map",
".",
"get",
"(",
"value",
",",
"value",
")",
"elif",
"kwarg",
"==",
"'datefmt'",
":",
"self",
".",
"handlers",
"[",
"0",
"]",
".",
"formatter",
".",
"datefmt",
"=",
"value",
"elif",
"kwarg",
"==",
"'msgfmt'",
":",
"self",
".",
"handlers",
"[",
"0",
"]",
".",
"formatter",
".",
"_style",
".",
"_fmt",
"=",
"value",
"elif",
"kwarg",
"==",
"'stream'",
":",
"global",
"fg",
",",
"fx",
",",
"_CHOSEN_PALETTE",
"self",
".",
"handlers",
"[",
"0",
"]",
".",
"stream",
"=",
"value",
"fg",
",",
"fx",
",",
"_CHOSEN_PALETTE",
"=",
"_find_palettes",
"(",
"value",
")",
"elif",
"kwarg",
"==",
"'theme'",
":",
"if",
"type",
"(",
"value",
")",
"is",
"str",
":",
"theme",
"=",
"_themes",
"[",
"value",
"]",
"if",
"value",
"==",
"'plain'",
":",
"fmtr",
"=",
"logging",
".",
"Formatter",
"(",
"style",
"=",
"'{'",
",",
"*",
"*",
"theme",
")",
"elif",
"value",
"==",
"'json'",
":",
"fmtr",
"=",
"_JSONFormatter",
"(",
"*",
"*",
"theme",
")",
"else",
":",
"fmtr",
"=",
"_ColorFormatter",
"(",
"tty",
"=",
"_is_a_tty",
",",
"*",
"*",
"theme",
")",
"elif",
"type",
"(",
"value",
")",
"is",
"dict",
":",
"if",
"'style'",
"in",
"value",
"or",
"'icons'",
"in",
"value",
":",
"fmtr",
"=",
"_ColorFormatter",
"(",
"tty",
"=",
"_is_a_tty",
",",
"*",
"*",
"theme",
")",
"else",
":",
"fmtr",
"=",
"logging",
".",
"Formatter",
"(",
"style",
"=",
"'{'",
",",
"*",
"*",
"theme",
")",
"self",
".",
"handlers",
"[",
"0",
"]",
".",
"setFormatter",
"(",
"fmtr",
")",
"elif",
"kwarg",
"==",
"'icons'",
":",
"if",
"type",
"(",
"value",
")",
"is",
"str",
":",
"value",
"=",
"_icons",
"[",
"value",
"]",
"self",
".",
"handlers",
"[",
"0",
"]",
".",
"formatter",
".",
"_theme_icons",
"=",
"value",
"elif",
"kwarg",
"==",
"'style'",
":",
"if",
"type",
"(",
"value",
")",
"is",
"str",
":",
"value",
"=",
"_styles",
"[",
"value",
"]",
"self",
".",
"handlers",
"[",
"0",
"]",
".",
"formatter",
".",
"_theme_style",
"=",
"value",
"elif",
"kwarg",
"==",
"'lexer'",
":",
"try",
":",
"self",
".",
"handlers",
"[",
"0",
"]",
".",
"formatter",
".",
"set_lexer",
"(",
"value",
")",
"except",
"AttributeError",
"as",
"err",
":",
"self",
".",
"error",
"(",
"'lexer: ColorFormatter not available.'",
")",
"else",
":",
"raise",
"NameError",
"(",
"'unknown keyword argument: %s'",
"%",
"kwarg",
")"
] | Convenience function to set a number of parameters on this logger
and associated handlers and formatters. | [
"Convenience",
"function",
"to",
"set",
"a",
"number",
"of",
"parameters",
"on",
"this",
"logger",
"and",
"associated",
"handlers",
"and",
"formatters",
"."
] | f5e02a783ed529e21753c7e6233d0c5550241fd9 | https://github.com/mixmastamyk/out/blob/f5e02a783ed529e21753c7e6233d0c5550241fd9/out/__init__.py#L59-L115 |
249,368 | mixmastamyk/out | out/__init__.py | Logger.log_config | def log_config(self):
''' Log the current logging configuration. '''
level = self.level
debug = self.debug
debug('Logging config:')
debug('/ name: {}, id: {}', self.name, id(self))
debug(' .level: %s (%s)', level_map_int[level], level)
debug(' .default_level: %s (%s)',
level_map_int[self.default_level], self.default_level)
for i, handler in enumerate(self.handlers):
fmtr = handler.formatter
debug(' + Handler: %s %r', i, handler)
debug(' + Formatter: %r', fmtr)
debug(' .datefmt: %r', fmtr.datefmt)
debug(' .msgfmt: %r', fmtr._fmt)
debug(' fmt_style: %r', fmtr._style)
try:
debug(' theme styles: %r', fmtr._theme_style)
debug(' theme icons:\n%r', fmtr._theme_icons)
debug(' lexer: %r\n', fmtr._lexer)
except AttributeError:
pass | python | def log_config(self):
''' Log the current logging configuration. '''
level = self.level
debug = self.debug
debug('Logging config:')
debug('/ name: {}, id: {}', self.name, id(self))
debug(' .level: %s (%s)', level_map_int[level], level)
debug(' .default_level: %s (%s)',
level_map_int[self.default_level], self.default_level)
for i, handler in enumerate(self.handlers):
fmtr = handler.formatter
debug(' + Handler: %s %r', i, handler)
debug(' + Formatter: %r', fmtr)
debug(' .datefmt: %r', fmtr.datefmt)
debug(' .msgfmt: %r', fmtr._fmt)
debug(' fmt_style: %r', fmtr._style)
try:
debug(' theme styles: %r', fmtr._theme_style)
debug(' theme icons:\n%r', fmtr._theme_icons)
debug(' lexer: %r\n', fmtr._lexer)
except AttributeError:
pass | [
"def",
"log_config",
"(",
"self",
")",
":",
"level",
"=",
"self",
".",
"level",
"debug",
"=",
"self",
".",
"debug",
"debug",
"(",
"'Logging config:'",
")",
"debug",
"(",
"'/ name: {}, id: {}'",
",",
"self",
".",
"name",
",",
"id",
"(",
"self",
")",
")",
"debug",
"(",
"' .level: %s (%s)'",
",",
"level_map_int",
"[",
"level",
"]",
",",
"level",
")",
"debug",
"(",
"' .default_level: %s (%s)'",
",",
"level_map_int",
"[",
"self",
".",
"default_level",
"]",
",",
"self",
".",
"default_level",
")",
"for",
"i",
",",
"handler",
"in",
"enumerate",
"(",
"self",
".",
"handlers",
")",
":",
"fmtr",
"=",
"handler",
".",
"formatter",
"debug",
"(",
"' + Handler: %s %r'",
",",
"i",
",",
"handler",
")",
"debug",
"(",
"' + Formatter: %r'",
",",
"fmtr",
")",
"debug",
"(",
"' .datefmt: %r'",
",",
"fmtr",
".",
"datefmt",
")",
"debug",
"(",
"' .msgfmt: %r'",
",",
"fmtr",
".",
"_fmt",
")",
"debug",
"(",
"' fmt_style: %r'",
",",
"fmtr",
".",
"_style",
")",
"try",
":",
"debug",
"(",
"' theme styles: %r'",
",",
"fmtr",
".",
"_theme_style",
")",
"debug",
"(",
"' theme icons:\\n%r'",
",",
"fmtr",
".",
"_theme_icons",
")",
"debug",
"(",
"' lexer: %r\\n'",
",",
"fmtr",
".",
"_lexer",
")",
"except",
"AttributeError",
":",
"pass"
] | Log the current logging configuration. | [
"Log",
"the",
"current",
"logging",
"configuration",
"."
] | f5e02a783ed529e21753c7e6233d0c5550241fd9 | https://github.com/mixmastamyk/out/blob/f5e02a783ed529e21753c7e6233d0c5550241fd9/out/__init__.py#L117-L139 |
249,369 | adminMesfix/validations | validations/dsl.py | is_valid_timestamp | def is_valid_timestamp(date, unit='millis'):
"""
Checks that a number that represents a date as milliseconds is correct.
"""
assert isinstance(date, int), "Input is not instance of int"
if unit is 'millis':
return is_positive(date) and len(str(date)) == 13
elif unit is 'seconds':
return is_positive(date) and len(str(date)) == 10
else:
raise ValueError('Unknown unit "%s"' % unit) | python | def is_valid_timestamp(date, unit='millis'):
"""
Checks that a number that represents a date as milliseconds is correct.
"""
assert isinstance(date, int), "Input is not instance of int"
if unit is 'millis':
return is_positive(date) and len(str(date)) == 13
elif unit is 'seconds':
return is_positive(date) and len(str(date)) == 10
else:
raise ValueError('Unknown unit "%s"' % unit) | [
"def",
"is_valid_timestamp",
"(",
"date",
",",
"unit",
"=",
"'millis'",
")",
":",
"assert",
"isinstance",
"(",
"date",
",",
"int",
")",
",",
"\"Input is not instance of int\"",
"if",
"unit",
"is",
"'millis'",
":",
"return",
"is_positive",
"(",
"date",
")",
"and",
"len",
"(",
"str",
"(",
"date",
")",
")",
"==",
"13",
"elif",
"unit",
"is",
"'seconds'",
":",
"return",
"is_positive",
"(",
"date",
")",
"and",
"len",
"(",
"str",
"(",
"date",
")",
")",
"==",
"10",
"else",
":",
"raise",
"ValueError",
"(",
"'Unknown unit \"%s\"'",
"%",
"unit",
")"
] | Checks that a number that represents a date as milliseconds is correct. | [
"Checks",
"that",
"a",
"number",
"that",
"represents",
"a",
"date",
"as",
"milliseconds",
"is",
"correct",
"."
] | a2fe04514c7aa1894b20eddbb1e848678ca08861 | https://github.com/adminMesfix/validations/blob/a2fe04514c7aa1894b20eddbb1e848678ca08861/validations/dsl.py#L66-L77 |
249,370 | chartbeat-labs/swailing | swailing/logger.py | Logger.debug | def debug(self, msg=None, *args, **kwargs):
"""Write log at DEBUG level. Same arguments as Python's built-in
Logger.
"""
return self._log(logging.DEBUG, msg, args, kwargs) | python | def debug(self, msg=None, *args, **kwargs):
"""Write log at DEBUG level. Same arguments as Python's built-in
Logger.
"""
return self._log(logging.DEBUG, msg, args, kwargs) | [
"def",
"debug",
"(",
"self",
",",
"msg",
"=",
"None",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"return",
"self",
".",
"_log",
"(",
"logging",
".",
"DEBUG",
",",
"msg",
",",
"args",
",",
"kwargs",
")"
] | Write log at DEBUG level. Same arguments as Python's built-in
Logger. | [
"Write",
"log",
"at",
"DEBUG",
"level",
".",
"Same",
"arguments",
"as",
"Python",
"s",
"built",
"-",
"in",
"Logger",
"."
] | d55e0dd7af59a2ba93f7c9c46ff56f6a4080b222 | https://github.com/chartbeat-labs/swailing/blob/d55e0dd7af59a2ba93f7c9c46ff56f6a4080b222/swailing/logger.py#L67-L73 |
249,371 | chartbeat-labs/swailing | swailing/logger.py | Logger.info | def info(self, msg=None, *args, **kwargs):
"""Similar to DEBUG but at INFO level."""
return self._log(logging.INFO, msg, args, kwargs) | python | def info(self, msg=None, *args, **kwargs):
"""Similar to DEBUG but at INFO level."""
return self._log(logging.INFO, msg, args, kwargs) | [
"def",
"info",
"(",
"self",
",",
"msg",
"=",
"None",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"return",
"self",
".",
"_log",
"(",
"logging",
".",
"INFO",
",",
"msg",
",",
"args",
",",
"kwargs",
")"
] | Similar to DEBUG but at INFO level. | [
"Similar",
"to",
"DEBUG",
"but",
"at",
"INFO",
"level",
"."
] | d55e0dd7af59a2ba93f7c9c46ff56f6a4080b222 | https://github.com/chartbeat-labs/swailing/blob/d55e0dd7af59a2ba93f7c9c46ff56f6a4080b222/swailing/logger.py#L75-L78 |
249,372 | chartbeat-labs/swailing | swailing/logger.py | Logger.exception | def exception(self, msg=None, *args, **kwargs):
"""Similar to DEBUG but at ERROR level with exc_info set.
https://github.com/python/cpython/blob/2.7/Lib/logging/__init__.py#L1472
"""
kwargs['exc_info'] = 1
return self._log(logging.ERROR, msg, args, kwargs) | python | def exception(self, msg=None, *args, **kwargs):
"""Similar to DEBUG but at ERROR level with exc_info set.
https://github.com/python/cpython/blob/2.7/Lib/logging/__init__.py#L1472
"""
kwargs['exc_info'] = 1
return self._log(logging.ERROR, msg, args, kwargs) | [
"def",
"exception",
"(",
"self",
",",
"msg",
"=",
"None",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"kwargs",
"[",
"'exc_info'",
"]",
"=",
"1",
"return",
"self",
".",
"_log",
"(",
"logging",
".",
"ERROR",
",",
"msg",
",",
"args",
",",
"kwargs",
")"
] | Similar to DEBUG but at ERROR level with exc_info set.
https://github.com/python/cpython/blob/2.7/Lib/logging/__init__.py#L1472 | [
"Similar",
"to",
"DEBUG",
"but",
"at",
"ERROR",
"level",
"with",
"exc_info",
"set",
"."
] | d55e0dd7af59a2ba93f7c9c46ff56f6a4080b222 | https://github.com/chartbeat-labs/swailing/blob/d55e0dd7af59a2ba93f7c9c46ff56f6a4080b222/swailing/logger.py#L90-L96 |
249,373 | chartbeat-labs/swailing | swailing/logger.py | Logger.log | def log(self, level, msg=None, *args, **kwargs):
"""Writes log out at any arbitray level."""
return self._log(level, msg, args, kwargs) | python | def log(self, level, msg=None, *args, **kwargs):
"""Writes log out at any arbitray level."""
return self._log(level, msg, args, kwargs) | [
"def",
"log",
"(",
"self",
",",
"level",
",",
"msg",
"=",
"None",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"return",
"self",
".",
"_log",
"(",
"level",
",",
"msg",
",",
"args",
",",
"kwargs",
")"
] | Writes log out at any arbitray level. | [
"Writes",
"log",
"out",
"at",
"any",
"arbitray",
"level",
"."
] | d55e0dd7af59a2ba93f7c9c46ff56f6a4080b222 | https://github.com/chartbeat-labs/swailing/blob/d55e0dd7af59a2ba93f7c9c46ff56f6a4080b222/swailing/logger.py#L103-L106 |
249,374 | chartbeat-labs/swailing | swailing/logger.py | Logger._log | def _log(self, level, msg, args, kwargs):
"""Throttled log output."""
with self._tb_lock:
if self._tb is None:
throttled = 0
should_log = True
else:
throttled = self._tb.throttle_count
should_log = self._tb.check_and_consume()
if should_log:
if throttled > 0:
self._logger.log(level, "")
self._logger.log(
level,
"(... throttled %d messages ...)",
throttled,
)
self._logger.log(level, "")
if msg is not None:
self._logger.log(level, msg, *args, **kwargs)
return FancyLogContext(self._logger,
level,
self._verbosity,
self._structured_detail,
self._with_prefix)
else:
return NoopLogContext() | python | def _log(self, level, msg, args, kwargs):
"""Throttled log output."""
with self._tb_lock:
if self._tb is None:
throttled = 0
should_log = True
else:
throttled = self._tb.throttle_count
should_log = self._tb.check_and_consume()
if should_log:
if throttled > 0:
self._logger.log(level, "")
self._logger.log(
level,
"(... throttled %d messages ...)",
throttled,
)
self._logger.log(level, "")
if msg is not None:
self._logger.log(level, msg, *args, **kwargs)
return FancyLogContext(self._logger,
level,
self._verbosity,
self._structured_detail,
self._with_prefix)
else:
return NoopLogContext() | [
"def",
"_log",
"(",
"self",
",",
"level",
",",
"msg",
",",
"args",
",",
"kwargs",
")",
":",
"with",
"self",
".",
"_tb_lock",
":",
"if",
"self",
".",
"_tb",
"is",
"None",
":",
"throttled",
"=",
"0",
"should_log",
"=",
"True",
"else",
":",
"throttled",
"=",
"self",
".",
"_tb",
".",
"throttle_count",
"should_log",
"=",
"self",
".",
"_tb",
".",
"check_and_consume",
"(",
")",
"if",
"should_log",
":",
"if",
"throttled",
">",
"0",
":",
"self",
".",
"_logger",
".",
"log",
"(",
"level",
",",
"\"\"",
")",
"self",
".",
"_logger",
".",
"log",
"(",
"level",
",",
"\"(... throttled %d messages ...)\"",
",",
"throttled",
",",
")",
"self",
".",
"_logger",
".",
"log",
"(",
"level",
",",
"\"\"",
")",
"if",
"msg",
"is",
"not",
"None",
":",
"self",
".",
"_logger",
".",
"log",
"(",
"level",
",",
"msg",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
"return",
"FancyLogContext",
"(",
"self",
".",
"_logger",
",",
"level",
",",
"self",
".",
"_verbosity",
",",
"self",
".",
"_structured_detail",
",",
"self",
".",
"_with_prefix",
")",
"else",
":",
"return",
"NoopLogContext",
"(",
")"
] | Throttled log output. | [
"Throttled",
"log",
"output",
"."
] | d55e0dd7af59a2ba93f7c9c46ff56f6a4080b222 | https://github.com/chartbeat-labs/swailing/blob/d55e0dd7af59a2ba93f7c9c46ff56f6a4080b222/swailing/logger.py#L112-L142 |
249,375 | shaypal5/utilitime | utilitime/timestamp/timestamp.py | timestamp_to_local_time | def timestamp_to_local_time(timestamp, timezone_name):
"""Convert epoch timestamp to a localized Delorean datetime object.
Arguments
---------
timestamp : int
The timestamp to convert.
timezone_name : datetime.timezone
The timezone of the desired local time.
Returns
-------
delorean.Delorean
A localized Delorean datetime object.
"""
# first convert timestamp to UTC
utc_time = datetime.utcfromtimestamp(float(timestamp))
delo = Delorean(utc_time, timezone='UTC')
# shift d according to input timezone
localized_d = delo.shift(timezone_name)
return localized_d | python | def timestamp_to_local_time(timestamp, timezone_name):
"""Convert epoch timestamp to a localized Delorean datetime object.
Arguments
---------
timestamp : int
The timestamp to convert.
timezone_name : datetime.timezone
The timezone of the desired local time.
Returns
-------
delorean.Delorean
A localized Delorean datetime object.
"""
# first convert timestamp to UTC
utc_time = datetime.utcfromtimestamp(float(timestamp))
delo = Delorean(utc_time, timezone='UTC')
# shift d according to input timezone
localized_d = delo.shift(timezone_name)
return localized_d | [
"def",
"timestamp_to_local_time",
"(",
"timestamp",
",",
"timezone_name",
")",
":",
"# first convert timestamp to UTC",
"utc_time",
"=",
"datetime",
".",
"utcfromtimestamp",
"(",
"float",
"(",
"timestamp",
")",
")",
"delo",
"=",
"Delorean",
"(",
"utc_time",
",",
"timezone",
"=",
"'UTC'",
")",
"# shift d according to input timezone",
"localized_d",
"=",
"delo",
".",
"shift",
"(",
"timezone_name",
")",
"return",
"localized_d"
] | Convert epoch timestamp to a localized Delorean datetime object.
Arguments
---------
timestamp : int
The timestamp to convert.
timezone_name : datetime.timezone
The timezone of the desired local time.
Returns
-------
delorean.Delorean
A localized Delorean datetime object. | [
"Convert",
"epoch",
"timestamp",
"to",
"a",
"localized",
"Delorean",
"datetime",
"object",
"."
] | 554ca05fa83c2dbf5d6cf9c9cfa6b03ee6cdb609 | https://github.com/shaypal5/utilitime/blob/554ca05fa83c2dbf5d6cf9c9cfa6b03ee6cdb609/utilitime/timestamp/timestamp.py#L12-L32 |
249,376 | shaypal5/utilitime | utilitime/timestamp/timestamp.py | timestamp_to_local_time_str | def timestamp_to_local_time_str(
timestamp, timezone_name, fmt="yyyy-MM-dd HH:mm:ss"):
"""Convert epoch timestamp to a localized datetime string.
Arguments
---------
timestamp : int
The timestamp to convert.
timezone_name : datetime.timezone
The timezone of the desired local time.
fmt : str
The format of the output string.
Returns
-------
str
The localized datetime string.
"""
localized_d = timestamp_to_local_time(timestamp, timezone_name)
localized_datetime_str = localized_d.format_datetime(fmt)
return localized_datetime_str | python | def timestamp_to_local_time_str(
timestamp, timezone_name, fmt="yyyy-MM-dd HH:mm:ss"):
"""Convert epoch timestamp to a localized datetime string.
Arguments
---------
timestamp : int
The timestamp to convert.
timezone_name : datetime.timezone
The timezone of the desired local time.
fmt : str
The format of the output string.
Returns
-------
str
The localized datetime string.
"""
localized_d = timestamp_to_local_time(timestamp, timezone_name)
localized_datetime_str = localized_d.format_datetime(fmt)
return localized_datetime_str | [
"def",
"timestamp_to_local_time_str",
"(",
"timestamp",
",",
"timezone_name",
",",
"fmt",
"=",
"\"yyyy-MM-dd HH:mm:ss\"",
")",
":",
"localized_d",
"=",
"timestamp_to_local_time",
"(",
"timestamp",
",",
"timezone_name",
")",
"localized_datetime_str",
"=",
"localized_d",
".",
"format_datetime",
"(",
"fmt",
")",
"return",
"localized_datetime_str"
] | Convert epoch timestamp to a localized datetime string.
Arguments
---------
timestamp : int
The timestamp to convert.
timezone_name : datetime.timezone
The timezone of the desired local time.
fmt : str
The format of the output string.
Returns
-------
str
The localized datetime string. | [
"Convert",
"epoch",
"timestamp",
"to",
"a",
"localized",
"datetime",
"string",
"."
] | 554ca05fa83c2dbf5d6cf9c9cfa6b03ee6cdb609 | https://github.com/shaypal5/utilitime/blob/554ca05fa83c2dbf5d6cf9c9cfa6b03ee6cdb609/utilitime/timestamp/timestamp.py#L35-L55 |
249,377 | shaypal5/utilitime | utilitime/timestamp/timestamp.py | get_timestamp | def get_timestamp(timezone_name, year, month, day, hour=0, minute=0):
"""Epoch timestamp from timezone, year, month, day, hour and minute."""
tz = pytz.timezone(timezone_name)
tz_datetime = tz.localize(datetime(year, month, day, hour, minute))
timestamp = calendar.timegm(tz_datetime.utctimetuple())
return timestamp | python | def get_timestamp(timezone_name, year, month, day, hour=0, minute=0):
"""Epoch timestamp from timezone, year, month, day, hour and minute."""
tz = pytz.timezone(timezone_name)
tz_datetime = tz.localize(datetime(year, month, day, hour, minute))
timestamp = calendar.timegm(tz_datetime.utctimetuple())
return timestamp | [
"def",
"get_timestamp",
"(",
"timezone_name",
",",
"year",
",",
"month",
",",
"day",
",",
"hour",
"=",
"0",
",",
"minute",
"=",
"0",
")",
":",
"tz",
"=",
"pytz",
".",
"timezone",
"(",
"timezone_name",
")",
"tz_datetime",
"=",
"tz",
".",
"localize",
"(",
"datetime",
"(",
"year",
",",
"month",
",",
"day",
",",
"hour",
",",
"minute",
")",
")",
"timestamp",
"=",
"calendar",
".",
"timegm",
"(",
"tz_datetime",
".",
"utctimetuple",
"(",
")",
")",
"return",
"timestamp"
] | Epoch timestamp from timezone, year, month, day, hour and minute. | [
"Epoch",
"timestamp",
"from",
"timezone",
"year",
"month",
"day",
"hour",
"and",
"minute",
"."
] | 554ca05fa83c2dbf5d6cf9c9cfa6b03ee6cdb609 | https://github.com/shaypal5/utilitime/blob/554ca05fa83c2dbf5d6cf9c9cfa6b03ee6cdb609/utilitime/timestamp/timestamp.py#L58-L63 |
249,378 | nir0s/serv | serv/init/systemd.py | SystemD.generate | def generate(self, overwrite=False):
"""Generate service files and returns a list of them.
Note that env var names will be capitalized using a Jinja filter.
This is template dependent.
Even though a param might be named `key` and have value `value`,
it will be rendered as `KEY=value`.
We retrieve the names of the template files and see the paths
where the generated files will be deployed. These are files
a user can just take and use.
If the service is also installed, those files will be moved
to the relevant location on the system.
Note that the parameters required to generate the file are
propagated automatically which is why we don't pass them explicitly
to the generating function.
`self.template_prefix` and `self.generate_into_prefix` are set in
`base.py`
`self.files` is an automatically generated list of the files that
were generated during the process. It should be returned so that
the generated files could be printed out for the user.
"""
super(SystemD, self).generate(overwrite=overwrite)
self._validate_init_system_specific_params()
svc_file_template = self.template_prefix + '.service'
env_file_template = self.template_prefix
self.svc_file_path = self.generate_into_prefix + '.service'
self.env_file_path = self.generate_into_prefix
self.generate_file_from_template(svc_file_template, self.svc_file_path)
self.generate_file_from_template(env_file_template, self.env_file_path)
return self.files | python | def generate(self, overwrite=False):
"""Generate service files and returns a list of them.
Note that env var names will be capitalized using a Jinja filter.
This is template dependent.
Even though a param might be named `key` and have value `value`,
it will be rendered as `KEY=value`.
We retrieve the names of the template files and see the paths
where the generated files will be deployed. These are files
a user can just take and use.
If the service is also installed, those files will be moved
to the relevant location on the system.
Note that the parameters required to generate the file are
propagated automatically which is why we don't pass them explicitly
to the generating function.
`self.template_prefix` and `self.generate_into_prefix` are set in
`base.py`
`self.files` is an automatically generated list of the files that
were generated during the process. It should be returned so that
the generated files could be printed out for the user.
"""
super(SystemD, self).generate(overwrite=overwrite)
self._validate_init_system_specific_params()
svc_file_template = self.template_prefix + '.service'
env_file_template = self.template_prefix
self.svc_file_path = self.generate_into_prefix + '.service'
self.env_file_path = self.generate_into_prefix
self.generate_file_from_template(svc_file_template, self.svc_file_path)
self.generate_file_from_template(env_file_template, self.env_file_path)
return self.files | [
"def",
"generate",
"(",
"self",
",",
"overwrite",
"=",
"False",
")",
":",
"super",
"(",
"SystemD",
",",
"self",
")",
".",
"generate",
"(",
"overwrite",
"=",
"overwrite",
")",
"self",
".",
"_validate_init_system_specific_params",
"(",
")",
"svc_file_template",
"=",
"self",
".",
"template_prefix",
"+",
"'.service'",
"env_file_template",
"=",
"self",
".",
"template_prefix",
"self",
".",
"svc_file_path",
"=",
"self",
".",
"generate_into_prefix",
"+",
"'.service'",
"self",
".",
"env_file_path",
"=",
"self",
".",
"generate_into_prefix",
"self",
".",
"generate_file_from_template",
"(",
"svc_file_template",
",",
"self",
".",
"svc_file_path",
")",
"self",
".",
"generate_file_from_template",
"(",
"env_file_template",
",",
"self",
".",
"env_file_path",
")",
"return",
"self",
".",
"files"
] | Generate service files and returns a list of them.
Note that env var names will be capitalized using a Jinja filter.
This is template dependent.
Even though a param might be named `key` and have value `value`,
it will be rendered as `KEY=value`.
We retrieve the names of the template files and see the paths
where the generated files will be deployed. These are files
a user can just take and use.
If the service is also installed, those files will be moved
to the relevant location on the system.
Note that the parameters required to generate the file are
propagated automatically which is why we don't pass them explicitly
to the generating function.
`self.template_prefix` and `self.generate_into_prefix` are set in
`base.py`
`self.files` is an automatically generated list of the files that
were generated during the process. It should be returned so that
the generated files could be printed out for the user. | [
"Generate",
"service",
"files",
"and",
"returns",
"a",
"list",
"of",
"them",
"."
] | 7af724ed49c0eb766c37c4b5287b043a8cf99e9c | https://github.com/nir0s/serv/blob/7af724ed49c0eb766c37c4b5287b043a8cf99e9c/serv/init/systemd.py#L35-L70 |
249,379 | nir0s/serv | serv/init/systemd.py | SystemD.install | def install(self):
"""Install the service on the local machine
This is where we deploy the service files to their relevant
locations and perform any other required actions to configure
the service and make it ready to be `start`ed.
"""
super(SystemD, self).install()
self.deploy_service_file(self.svc_file_path, self.svc_file_dest)
self.deploy_service_file(self.env_file_path, self.env_file_dest)
sh.systemctl.enable(self.name)
sh.systemctl('daemon-reload') | python | def install(self):
"""Install the service on the local machine
This is where we deploy the service files to their relevant
locations and perform any other required actions to configure
the service and make it ready to be `start`ed.
"""
super(SystemD, self).install()
self.deploy_service_file(self.svc_file_path, self.svc_file_dest)
self.deploy_service_file(self.env_file_path, self.env_file_dest)
sh.systemctl.enable(self.name)
sh.systemctl('daemon-reload') | [
"def",
"install",
"(",
"self",
")",
":",
"super",
"(",
"SystemD",
",",
"self",
")",
".",
"install",
"(",
")",
"self",
".",
"deploy_service_file",
"(",
"self",
".",
"svc_file_path",
",",
"self",
".",
"svc_file_dest",
")",
"self",
".",
"deploy_service_file",
"(",
"self",
".",
"env_file_path",
",",
"self",
".",
"env_file_dest",
")",
"sh",
".",
"systemctl",
".",
"enable",
"(",
"self",
".",
"name",
")",
"sh",
".",
"systemctl",
"(",
"'daemon-reload'",
")"
] | Install the service on the local machine
This is where we deploy the service files to their relevant
locations and perform any other required actions to configure
the service and make it ready to be `start`ed. | [
"Install",
"the",
"service",
"on",
"the",
"local",
"machine"
] | 7af724ed49c0eb766c37c4b5287b043a8cf99e9c | https://github.com/nir0s/serv/blob/7af724ed49c0eb766c37c4b5287b043a8cf99e9c/serv/init/systemd.py#L72-L84 |
249,380 | nir0s/serv | serv/init/systemd.py | SystemD.stop | def stop(self):
"""Stop the service.
"""
try:
sh.systemctl.stop(self.name)
except sh.ErrorReturnCode_5:
self.logger.debug('Service not running.') | python | def stop(self):
"""Stop the service.
"""
try:
sh.systemctl.stop(self.name)
except sh.ErrorReturnCode_5:
self.logger.debug('Service not running.') | [
"def",
"stop",
"(",
"self",
")",
":",
"try",
":",
"sh",
".",
"systemctl",
".",
"stop",
"(",
"self",
".",
"name",
")",
"except",
"sh",
".",
"ErrorReturnCode_5",
":",
"self",
".",
"logger",
".",
"debug",
"(",
"'Service not running.'",
")"
] | Stop the service. | [
"Stop",
"the",
"service",
"."
] | 7af724ed49c0eb766c37c4b5287b043a8cf99e9c | https://github.com/nir0s/serv/blob/7af724ed49c0eb766c37c4b5287b043a8cf99e9c/serv/init/systemd.py#L91-L97 |
249,381 | nir0s/serv | serv/init/systemd.py | SystemD.uninstall | def uninstall(self):
"""Uninstall the service.
This is supposed to perform any cleanup operations required to
remove the service. Files, links, whatever else should be removed.
This method should also run when implementing cleanup in case of
failures. As such, idempotence should be considered.
"""
sh.systemctl.disable(self.name)
sh.systemctl('daemon-reload')
if os.path.isfile(self.svc_file_dest):
os.remove(self.svc_file_dest)
if os.path.isfile(self.env_file_dest):
os.remove(self.env_file_dest) | python | def uninstall(self):
"""Uninstall the service.
This is supposed to perform any cleanup operations required to
remove the service. Files, links, whatever else should be removed.
This method should also run when implementing cleanup in case of
failures. As such, idempotence should be considered.
"""
sh.systemctl.disable(self.name)
sh.systemctl('daemon-reload')
if os.path.isfile(self.svc_file_dest):
os.remove(self.svc_file_dest)
if os.path.isfile(self.env_file_dest):
os.remove(self.env_file_dest) | [
"def",
"uninstall",
"(",
"self",
")",
":",
"sh",
".",
"systemctl",
".",
"disable",
"(",
"self",
".",
"name",
")",
"sh",
".",
"systemctl",
"(",
"'daemon-reload'",
")",
"if",
"os",
".",
"path",
".",
"isfile",
"(",
"self",
".",
"svc_file_dest",
")",
":",
"os",
".",
"remove",
"(",
"self",
".",
"svc_file_dest",
")",
"if",
"os",
".",
"path",
".",
"isfile",
"(",
"self",
".",
"env_file_dest",
")",
":",
"os",
".",
"remove",
"(",
"self",
".",
"env_file_dest",
")"
] | Uninstall the service.
This is supposed to perform any cleanup operations required to
remove the service. Files, links, whatever else should be removed.
This method should also run when implementing cleanup in case of
failures. As such, idempotence should be considered. | [
"Uninstall",
"the",
"service",
"."
] | 7af724ed49c0eb766c37c4b5287b043a8cf99e9c | https://github.com/nir0s/serv/blob/7af724ed49c0eb766c37c4b5287b043a8cf99e9c/serv/init/systemd.py#L101-L114 |
249,382 | nir0s/serv | serv/init/systemd.py | SystemD.status | def status(self, name=''):
"""Return a list of the statuses of the `name` service, or
if name is omitted, a list of the status of all services for this
specific init system.
There should be a standardization around the status fields.
There currently isn't.
`self.services` is set in `base.py`
"""
super(SystemD, self).status(name=name)
svc_list = sh.systemctl('--no-legend', '--no-pager', t='service')
svcs_info = [self._parse_service_info(svc) for svc in svc_list]
if name:
names = (name, name + '.service')
# return list of one item for specific service
svcs_info = [s for s in svcs_info if s['name'] in names]
self.services['services'] = svcs_info
return self.services | python | def status(self, name=''):
"""Return a list of the statuses of the `name` service, or
if name is omitted, a list of the status of all services for this
specific init system.
There should be a standardization around the status fields.
There currently isn't.
`self.services` is set in `base.py`
"""
super(SystemD, self).status(name=name)
svc_list = sh.systemctl('--no-legend', '--no-pager', t='service')
svcs_info = [self._parse_service_info(svc) for svc in svc_list]
if name:
names = (name, name + '.service')
# return list of one item for specific service
svcs_info = [s for s in svcs_info if s['name'] in names]
self.services['services'] = svcs_info
return self.services | [
"def",
"status",
"(",
"self",
",",
"name",
"=",
"''",
")",
":",
"super",
"(",
"SystemD",
",",
"self",
")",
".",
"status",
"(",
"name",
"=",
"name",
")",
"svc_list",
"=",
"sh",
".",
"systemctl",
"(",
"'--no-legend'",
",",
"'--no-pager'",
",",
"t",
"=",
"'service'",
")",
"svcs_info",
"=",
"[",
"self",
".",
"_parse_service_info",
"(",
"svc",
")",
"for",
"svc",
"in",
"svc_list",
"]",
"if",
"name",
":",
"names",
"=",
"(",
"name",
",",
"name",
"+",
"'.service'",
")",
"# return list of one item for specific service",
"svcs_info",
"=",
"[",
"s",
"for",
"s",
"in",
"svcs_info",
"if",
"s",
"[",
"'name'",
"]",
"in",
"names",
"]",
"self",
".",
"services",
"[",
"'services'",
"]",
"=",
"svcs_info",
"return",
"self",
".",
"services"
] | Return a list of the statuses of the `name` service, or
if name is omitted, a list of the status of all services for this
specific init system.
There should be a standardization around the status fields.
There currently isn't.
`self.services` is set in `base.py` | [
"Return",
"a",
"list",
"of",
"the",
"statuses",
"of",
"the",
"name",
"service",
"or",
"if",
"name",
"is",
"omitted",
"a",
"list",
"of",
"the",
"status",
"of",
"all",
"services",
"for",
"this",
"specific",
"init",
"system",
"."
] | 7af724ed49c0eb766c37c4b5287b043a8cf99e9c | https://github.com/nir0s/serv/blob/7af724ed49c0eb766c37c4b5287b043a8cf99e9c/serv/init/systemd.py#L116-L135 |
249,383 | totokaka/pySpaceGDN | pyspacegdn/requests/find_request.py | FindRequest.sort | def sort(self, *sort):
""" Sort the results.
Define how the results should be sorted. The arguments should be tuples
of string defining the key and direction to sort by. For example
`('name', 'asc')` and `('version', 'desc')`. The first sorte rule is
considered first by the API. See also the API documentation on
`sorting`_.
Arguments:
`*sort` (`tuple`)
The rules to sort by
.. _sorting: https://github.com/XereoNet/SpaceGDN/wiki/API#sorting
"""
self.add_get_param('sort', FILTER_DELIMITER.join(
[ELEMENT_DELIMITER.join(elements) for elements in sort]))
return self | python | def sort(self, *sort):
""" Sort the results.
Define how the results should be sorted. The arguments should be tuples
of string defining the key and direction to sort by. For example
`('name', 'asc')` and `('version', 'desc')`. The first sorte rule is
considered first by the API. See also the API documentation on
`sorting`_.
Arguments:
`*sort` (`tuple`)
The rules to sort by
.. _sorting: https://github.com/XereoNet/SpaceGDN/wiki/API#sorting
"""
self.add_get_param('sort', FILTER_DELIMITER.join(
[ELEMENT_DELIMITER.join(elements) for elements in sort]))
return self | [
"def",
"sort",
"(",
"self",
",",
"*",
"sort",
")",
":",
"self",
".",
"add_get_param",
"(",
"'sort'",
",",
"FILTER_DELIMITER",
".",
"join",
"(",
"[",
"ELEMENT_DELIMITER",
".",
"join",
"(",
"elements",
")",
"for",
"elements",
"in",
"sort",
"]",
")",
")",
"return",
"self"
] | Sort the results.
Define how the results should be sorted. The arguments should be tuples
of string defining the key and direction to sort by. For example
`('name', 'asc')` and `('version', 'desc')`. The first sorte rule is
considered first by the API. See also the API documentation on
`sorting`_.
Arguments:
`*sort` (`tuple`)
The rules to sort by
.. _sorting: https://github.com/XereoNet/SpaceGDN/wiki/API#sorting | [
"Sort",
"the",
"results",
"."
] | 55c8be8d751e24873e0a7f7e99d2b715442ec878 | https://github.com/totokaka/pySpaceGDN/blob/55c8be8d751e24873e0a7f7e99d2b715442ec878/pyspacegdn/requests/find_request.py#L73-L91 |
249,384 | totokaka/pySpaceGDN | pyspacegdn/requests/find_request.py | FindRequest.where | def where(self, *where):
""" Filter the results.
Filter the results by provided rules. The rules should be tuples that
look like this::
('<key>', '<operator>', '<value>')
For example::
('name', '$eq', 'Vanilla Minecraft')
This is also covered in the documentation_ of the SpaceGDN API.
.. _documentation: https://github.com/XereoNet/SpaceGDN/wiki/API#where
"""
filters = list()
for key, operator, value in where:
filters.append(ELEMENT_DELIMITER.join((key, operator, value)))
self.add_get_param('where', FILTER_DELIMITER.join(filters))
return self | python | def where(self, *where):
""" Filter the results.
Filter the results by provided rules. The rules should be tuples that
look like this::
('<key>', '<operator>', '<value>')
For example::
('name', '$eq', 'Vanilla Minecraft')
This is also covered in the documentation_ of the SpaceGDN API.
.. _documentation: https://github.com/XereoNet/SpaceGDN/wiki/API#where
"""
filters = list()
for key, operator, value in where:
filters.append(ELEMENT_DELIMITER.join((key, operator, value)))
self.add_get_param('where', FILTER_DELIMITER.join(filters))
return self | [
"def",
"where",
"(",
"self",
",",
"*",
"where",
")",
":",
"filters",
"=",
"list",
"(",
")",
"for",
"key",
",",
"operator",
",",
"value",
"in",
"where",
":",
"filters",
".",
"append",
"(",
"ELEMENT_DELIMITER",
".",
"join",
"(",
"(",
"key",
",",
"operator",
",",
"value",
")",
")",
")",
"self",
".",
"add_get_param",
"(",
"'where'",
",",
"FILTER_DELIMITER",
".",
"join",
"(",
"filters",
")",
")",
"return",
"self"
] | Filter the results.
Filter the results by provided rules. The rules should be tuples that
look like this::
('<key>', '<operator>', '<value>')
For example::
('name', '$eq', 'Vanilla Minecraft')
This is also covered in the documentation_ of the SpaceGDN API.
.. _documentation: https://github.com/XereoNet/SpaceGDN/wiki/API#where | [
"Filter",
"the",
"results",
"."
] | 55c8be8d751e24873e0a7f7e99d2b715442ec878 | https://github.com/totokaka/pySpaceGDN/blob/55c8be8d751e24873e0a7f7e99d2b715442ec878/pyspacegdn/requests/find_request.py#L93-L114 |
249,385 | totokaka/pySpaceGDN | pyspacegdn/requests/find_request.py | FindRequest.fetch | def fetch(self):
""" Run the request and fetch the results.
This method will compile the request, send it to the SpaceGDN endpoint
defined with the `SpaceGDN` object and wrap the results in a
:class:`pyspacegdn.Response` object.
Returns a :class:`pyspacegdn.Response` object.
"""
response = Response()
has_next = True
while has_next:
resp = self._fetch(default_path='v2')
results = None
if resp.success:
results = resp.data['results']
self.add_get_param('page', resp.data['pagination']['page'] + 1)
has_next = resp.data['pagination']['has_next']
response.add(results, resp.status_code, resp.status_reason)
return response | python | def fetch(self):
""" Run the request and fetch the results.
This method will compile the request, send it to the SpaceGDN endpoint
defined with the `SpaceGDN` object and wrap the results in a
:class:`pyspacegdn.Response` object.
Returns a :class:`pyspacegdn.Response` object.
"""
response = Response()
has_next = True
while has_next:
resp = self._fetch(default_path='v2')
results = None
if resp.success:
results = resp.data['results']
self.add_get_param('page', resp.data['pagination']['page'] + 1)
has_next = resp.data['pagination']['has_next']
response.add(results, resp.status_code, resp.status_reason)
return response | [
"def",
"fetch",
"(",
"self",
")",
":",
"response",
"=",
"Response",
"(",
")",
"has_next",
"=",
"True",
"while",
"has_next",
":",
"resp",
"=",
"self",
".",
"_fetch",
"(",
"default_path",
"=",
"'v2'",
")",
"results",
"=",
"None",
"if",
"resp",
".",
"success",
":",
"results",
"=",
"resp",
".",
"data",
"[",
"'results'",
"]",
"self",
".",
"add_get_param",
"(",
"'page'",
",",
"resp",
".",
"data",
"[",
"'pagination'",
"]",
"[",
"'page'",
"]",
"+",
"1",
")",
"has_next",
"=",
"resp",
".",
"data",
"[",
"'pagination'",
"]",
"[",
"'has_next'",
"]",
"response",
".",
"add",
"(",
"results",
",",
"resp",
".",
"status_code",
",",
"resp",
".",
"status_reason",
")",
"return",
"response"
] | Run the request and fetch the results.
This method will compile the request, send it to the SpaceGDN endpoint
defined with the `SpaceGDN` object and wrap the results in a
:class:`pyspacegdn.Response` object.
Returns a :class:`pyspacegdn.Response` object. | [
"Run",
"the",
"request",
"and",
"fetch",
"the",
"results",
"."
] | 55c8be8d751e24873e0a7f7e99d2b715442ec878 | https://github.com/totokaka/pySpaceGDN/blob/55c8be8d751e24873e0a7f7e99d2b715442ec878/pyspacegdn/requests/find_request.py#L116-L137 |
249,386 | kalekundert/nonstdlib | nonstdlib/meta.py | singleton | def singleton(cls):
""" Decorator function that turns a class into a singleton. """
import inspect
# Create a structure to store instances of any singletons that get
# created.
instances = {}
# Make sure that the constructor for this class doesn't take any
# arguments. Since singletons can only be instantiated once, it doesn't
# make any sense for the constructor to take arguments. If the class
# doesn't implement its own constructor, don't do anything. This case is
# considered specially because it causes a TypeError in python 3.3 but not
# in python 3.4.
if cls.__init__ is not object.__init__:
argspec = inspect.getfullargspec(cls.__init__)
if len(argspec.args) != 1 or argspec.varargs or argspec.varkw:
raise TypeError("Singleton classes cannot accept arguments to the constructor.")
def get_instance():
""" Creates and returns the singleton object. This function is what
gets returned by this decorator. """
# Check to see if an instance of this class has already been
# instantiated. If it hasn't, create one. The `instances` structure
# is technically a global variable, so it will be preserved between
# calls to this function.
if cls not in instances:
instances[cls] = cls()
# Return a previously instantiated object of the requested type.
return instances[cls]
# Return the decorator function.
return get_instance | python | def singleton(cls):
""" Decorator function that turns a class into a singleton. """
import inspect
# Create a structure to store instances of any singletons that get
# created.
instances = {}
# Make sure that the constructor for this class doesn't take any
# arguments. Since singletons can only be instantiated once, it doesn't
# make any sense for the constructor to take arguments. If the class
# doesn't implement its own constructor, don't do anything. This case is
# considered specially because it causes a TypeError in python 3.3 but not
# in python 3.4.
if cls.__init__ is not object.__init__:
argspec = inspect.getfullargspec(cls.__init__)
if len(argspec.args) != 1 or argspec.varargs or argspec.varkw:
raise TypeError("Singleton classes cannot accept arguments to the constructor.")
def get_instance():
""" Creates and returns the singleton object. This function is what
gets returned by this decorator. """
# Check to see if an instance of this class has already been
# instantiated. If it hasn't, create one. The `instances` structure
# is technically a global variable, so it will be preserved between
# calls to this function.
if cls not in instances:
instances[cls] = cls()
# Return a previously instantiated object of the requested type.
return instances[cls]
# Return the decorator function.
return get_instance | [
"def",
"singleton",
"(",
"cls",
")",
":",
"import",
"inspect",
"# Create a structure to store instances of any singletons that get",
"# created.",
"instances",
"=",
"{",
"}",
"# Make sure that the constructor for this class doesn't take any",
"# arguments. Since singletons can only be instantiated once, it doesn't",
"# make any sense for the constructor to take arguments. If the class ",
"# doesn't implement its own constructor, don't do anything. This case is ",
"# considered specially because it causes a TypeError in python 3.3 but not ",
"# in python 3.4.",
"if",
"cls",
".",
"__init__",
"is",
"not",
"object",
".",
"__init__",
":",
"argspec",
"=",
"inspect",
".",
"getfullargspec",
"(",
"cls",
".",
"__init__",
")",
"if",
"len",
"(",
"argspec",
".",
"args",
")",
"!=",
"1",
"or",
"argspec",
".",
"varargs",
"or",
"argspec",
".",
"varkw",
":",
"raise",
"TypeError",
"(",
"\"Singleton classes cannot accept arguments to the constructor.\"",
")",
"def",
"get_instance",
"(",
")",
":",
"\"\"\" Creates and returns the singleton object. This function is what \n gets returned by this decorator. \"\"\"",
"# Check to see if an instance of this class has already been",
"# instantiated. If it hasn't, create one. The `instances` structure",
"# is technically a global variable, so it will be preserved between",
"# calls to this function.",
"if",
"cls",
"not",
"in",
"instances",
":",
"instances",
"[",
"cls",
"]",
"=",
"cls",
"(",
")",
"# Return a previously instantiated object of the requested type.",
"return",
"instances",
"[",
"cls",
"]",
"# Return the decorator function.",
"return",
"get_instance"
] | Decorator function that turns a class into a singleton. | [
"Decorator",
"function",
"that",
"turns",
"a",
"class",
"into",
"a",
"singleton",
"."
] | 3abf4a4680056d6d97f2a5988972eb9392756fb6 | https://github.com/kalekundert/nonstdlib/blob/3abf4a4680056d6d97f2a5988972eb9392756fb6/nonstdlib/meta.py#L40-L75 |
249,387 | heikomuller/sco-engine | scoengine/model.py | ModelOutputFile.from_dict | def from_dict(doc):
"""Create a model output file object from a dictionary.
"""
if 'path' in doc:
path = doc['path']
else:
path = None
return ModelOutputFile(
doc['filename'],
doc['mimeType'],
path=path
) | python | def from_dict(doc):
"""Create a model output file object from a dictionary.
"""
if 'path' in doc:
path = doc['path']
else:
path = None
return ModelOutputFile(
doc['filename'],
doc['mimeType'],
path=path
) | [
"def",
"from_dict",
"(",
"doc",
")",
":",
"if",
"'path'",
"in",
"doc",
":",
"path",
"=",
"doc",
"[",
"'path'",
"]",
"else",
":",
"path",
"=",
"None",
"return",
"ModelOutputFile",
"(",
"doc",
"[",
"'filename'",
"]",
",",
"doc",
"[",
"'mimeType'",
"]",
",",
"path",
"=",
"path",
")"
] | Create a model output file object from a dictionary. | [
"Create",
"a",
"model",
"output",
"file",
"object",
"from",
"a",
"dictionary",
"."
] | 3e7782d059ec808d930f0992794b6f5a8fd73c2c | https://github.com/heikomuller/sco-engine/blob/3e7782d059ec808d930f0992794b6f5a8fd73c2c/scoengine/model.py#L61-L73 |
249,388 | heikomuller/sco-engine | scoengine/model.py | ModelOutputs.from_dict | def from_dict(doc):
"""Create a model output object from a dictionary.
"""
return ModelOutputs(
ModelOutputFile.from_dict(doc['prediction']),
[ModelOutputFile.from_dict(a) for a in doc['attachments']]
) | python | def from_dict(doc):
"""Create a model output object from a dictionary.
"""
return ModelOutputs(
ModelOutputFile.from_dict(doc['prediction']),
[ModelOutputFile.from_dict(a) for a in doc['attachments']]
) | [
"def",
"from_dict",
"(",
"doc",
")",
":",
"return",
"ModelOutputs",
"(",
"ModelOutputFile",
".",
"from_dict",
"(",
"doc",
"[",
"'prediction'",
"]",
")",
",",
"[",
"ModelOutputFile",
".",
"from_dict",
"(",
"a",
")",
"for",
"a",
"in",
"doc",
"[",
"'attachments'",
"]",
"]",
")"
] | Create a model output object from a dictionary. | [
"Create",
"a",
"model",
"output",
"object",
"from",
"a",
"dictionary",
"."
] | 3e7782d059ec808d930f0992794b6f5a8fd73c2c | https://github.com/heikomuller/sco-engine/blob/3e7782d059ec808d930f0992794b6f5a8fd73c2c/scoengine/model.py#L131-L138 |
249,389 | heikomuller/sco-engine | scoengine/model.py | ModelRegistry.to_dict | def to_dict(self, model):
"""Create a dictionary serialization for a model.
Parameters
----------
model : ModelHandle
Returns
-------
dict
Dictionary serialization for a model
"""
# Get the basic Json object from the super class
obj = super(ModelRegistry, self).to_dict(model)
# Add model parameter
obj['parameters'] = [
para.to_dict() for para in model.parameters
]
obj['outputs'] = model.outputs.to_dict()
obj['connector'] = model.connector
return obj | python | def to_dict(self, model):
"""Create a dictionary serialization for a model.
Parameters
----------
model : ModelHandle
Returns
-------
dict
Dictionary serialization for a model
"""
# Get the basic Json object from the super class
obj = super(ModelRegistry, self).to_dict(model)
# Add model parameter
obj['parameters'] = [
para.to_dict() for para in model.parameters
]
obj['outputs'] = model.outputs.to_dict()
obj['connector'] = model.connector
return obj | [
"def",
"to_dict",
"(",
"self",
",",
"model",
")",
":",
"# Get the basic Json object from the super class",
"obj",
"=",
"super",
"(",
"ModelRegistry",
",",
"self",
")",
".",
"to_dict",
"(",
"model",
")",
"# Add model parameter",
"obj",
"[",
"'parameters'",
"]",
"=",
"[",
"para",
".",
"to_dict",
"(",
")",
"for",
"para",
"in",
"model",
".",
"parameters",
"]",
"obj",
"[",
"'outputs'",
"]",
"=",
"model",
".",
"outputs",
".",
"to_dict",
"(",
")",
"obj",
"[",
"'connector'",
"]",
"=",
"model",
".",
"connector",
"return",
"obj"
] | Create a dictionary serialization for a model.
Parameters
----------
model : ModelHandle
Returns
-------
dict
Dictionary serialization for a model | [
"Create",
"a",
"dictionary",
"serialization",
"for",
"a",
"model",
"."
] | 3e7782d059ec808d930f0992794b6f5a8fd73c2c | https://github.com/heikomuller/sco-engine/blob/3e7782d059ec808d930f0992794b6f5a8fd73c2c/scoengine/model.py#L369-L389 |
249,390 | bmweiner/skillful | skillful/interface.py | _snake_to_camel | def _snake_to_camel(name, strict=False):
"""Converts parameter names from snake_case to camelCase.
Args:
name, str. Snake case.
strict: bool, default True. If True, will set name to lowercase before
converting, otherwise assumes original name is proper camel case.
Set to False if name may already be in camelCase.
Returns:
str: CamelCase.
"""
if strict:
name = name.lower()
terms = name.split('_')
return terms[0] + ''.join([term.capitalize() for term in terms[1:]]) | python | def _snake_to_camel(name, strict=False):
"""Converts parameter names from snake_case to camelCase.
Args:
name, str. Snake case.
strict: bool, default True. If True, will set name to lowercase before
converting, otherwise assumes original name is proper camel case.
Set to False if name may already be in camelCase.
Returns:
str: CamelCase.
"""
if strict:
name = name.lower()
terms = name.split('_')
return terms[0] + ''.join([term.capitalize() for term in terms[1:]]) | [
"def",
"_snake_to_camel",
"(",
"name",
",",
"strict",
"=",
"False",
")",
":",
"if",
"strict",
":",
"name",
"=",
"name",
".",
"lower",
"(",
")",
"terms",
"=",
"name",
".",
"split",
"(",
"'_'",
")",
"return",
"terms",
"[",
"0",
"]",
"+",
"''",
".",
"join",
"(",
"[",
"term",
".",
"capitalize",
"(",
")",
"for",
"term",
"in",
"terms",
"[",
"1",
":",
"]",
"]",
")"
] | Converts parameter names from snake_case to camelCase.
Args:
name, str. Snake case.
strict: bool, default True. If True, will set name to lowercase before
converting, otherwise assumes original name is proper camel case.
Set to False if name may already be in camelCase.
Returns:
str: CamelCase. | [
"Converts",
"parameter",
"names",
"from",
"snake_case",
"to",
"camelCase",
"."
] | 8646f54faf62cb63f165f7699b8ace5b4a08233c | https://github.com/bmweiner/skillful/blob/8646f54faf62cb63f165f7699b8ace5b4a08233c/skillful/interface.py#L565-L580 |
249,391 | bmweiner/skillful | skillful/interface.py | DefaultAttrMixin._set_default_attr | def _set_default_attr(self, default_attr):
"""Sets default attributes when None.
Args:
default_attr: dict. Key-val of attr, default-value.
"""
for attr, val in six.iteritems(default_attr):
if getattr(self, attr, None) is None:
setattr(self, attr, val) | python | def _set_default_attr(self, default_attr):
"""Sets default attributes when None.
Args:
default_attr: dict. Key-val of attr, default-value.
"""
for attr, val in six.iteritems(default_attr):
if getattr(self, attr, None) is None:
setattr(self, attr, val) | [
"def",
"_set_default_attr",
"(",
"self",
",",
"default_attr",
")",
":",
"for",
"attr",
",",
"val",
"in",
"six",
".",
"iteritems",
"(",
"default_attr",
")",
":",
"if",
"getattr",
"(",
"self",
",",
"attr",
",",
"None",
")",
"is",
"None",
":",
"setattr",
"(",
"self",
",",
"attr",
",",
"val",
")"
] | Sets default attributes when None.
Args:
default_attr: dict. Key-val of attr, default-value. | [
"Sets",
"default",
"attributes",
"when",
"None",
"."
] | 8646f54faf62cb63f165f7699b8ace5b4a08233c | https://github.com/bmweiner/skillful/blob/8646f54faf62cb63f165f7699b8ace5b4a08233c/skillful/interface.py#L10-L18 |
249,392 | bmweiner/skillful | skillful/interface.py | Body.to_json | def to_json(self, drop_null=True, camel=False, indent=None, sort_keys=False):
"""Serialize self as JSON
Args:
drop_null: bool, default True. Remove 'empty' attributes. See
to_dict.
camel: bool, default True. Convert keys to camelCase.
indent: int, default None. See json built-in.
sort_keys: bool, default False. See json built-in.
Return:
str: object params.
"""
return json.dumps(self.to_dict(drop_null, camel), indent=indent,
sort_keys=sort_keys) | python | def to_json(self, drop_null=True, camel=False, indent=None, sort_keys=False):
"""Serialize self as JSON
Args:
drop_null: bool, default True. Remove 'empty' attributes. See
to_dict.
camel: bool, default True. Convert keys to camelCase.
indent: int, default None. See json built-in.
sort_keys: bool, default False. See json built-in.
Return:
str: object params.
"""
return json.dumps(self.to_dict(drop_null, camel), indent=indent,
sort_keys=sort_keys) | [
"def",
"to_json",
"(",
"self",
",",
"drop_null",
"=",
"True",
",",
"camel",
"=",
"False",
",",
"indent",
"=",
"None",
",",
"sort_keys",
"=",
"False",
")",
":",
"return",
"json",
".",
"dumps",
"(",
"self",
".",
"to_dict",
"(",
"drop_null",
",",
"camel",
")",
",",
"indent",
"=",
"indent",
",",
"sort_keys",
"=",
"sort_keys",
")"
] | Serialize self as JSON
Args:
drop_null: bool, default True. Remove 'empty' attributes. See
to_dict.
camel: bool, default True. Convert keys to camelCase.
indent: int, default None. See json built-in.
sort_keys: bool, default False. See json built-in.
Return:
str: object params. | [
"Serialize",
"self",
"as",
"JSON"
] | 8646f54faf62cb63f165f7699b8ace5b4a08233c | https://github.com/bmweiner/skillful/blob/8646f54faf62cb63f165f7699b8ace5b4a08233c/skillful/interface.py#L29-L43 |
249,393 | bmweiner/skillful | skillful/interface.py | Body.to_dict | def to_dict(self, drop_null=True, camel=False):
"""Serialize self as dict.
Args:
drop_null: bool, default True. Remove 'empty' attributes.
camel: bool, default True. Convert keys to camelCase.
Return:
dict: object params.
"""
#return _to_dict(self, drop_null, camel)
def to_dict(obj, drop_null, camel):
"""Recursively constructs the dict."""
if isinstance(obj, (Body, BodyChild)):
obj = obj.__dict__
if isinstance(obj, dict):
data = {}
for attr, val in six.iteritems(obj):
if camel:
attr = _snake_to_camel(attr)
valid_null = (isinstance(val, bool) or val == 0 or
(val and to_dict(val, drop_null, camel)))
if not drop_null or (drop_null and valid_null):
data[attr] = to_dict(val, drop_null, camel)
return data
elif isinstance(obj, list):
data = []
for val in obj:
valid_null = (isinstance(val, bool) or val == 0 or
(val and to_dict(val, drop_null, camel)))
if not drop_null or (drop_null and valid_null):
data.append(to_dict(val, drop_null, camel))
return data
else:
return obj
return to_dict(self, drop_null, camel) | python | def to_dict(self, drop_null=True, camel=False):
"""Serialize self as dict.
Args:
drop_null: bool, default True. Remove 'empty' attributes.
camel: bool, default True. Convert keys to camelCase.
Return:
dict: object params.
"""
#return _to_dict(self, drop_null, camel)
def to_dict(obj, drop_null, camel):
"""Recursively constructs the dict."""
if isinstance(obj, (Body, BodyChild)):
obj = obj.__dict__
if isinstance(obj, dict):
data = {}
for attr, val in six.iteritems(obj):
if camel:
attr = _snake_to_camel(attr)
valid_null = (isinstance(val, bool) or val == 0 or
(val and to_dict(val, drop_null, camel)))
if not drop_null or (drop_null and valid_null):
data[attr] = to_dict(val, drop_null, camel)
return data
elif isinstance(obj, list):
data = []
for val in obj:
valid_null = (isinstance(val, bool) or val == 0 or
(val and to_dict(val, drop_null, camel)))
if not drop_null or (drop_null and valid_null):
data.append(to_dict(val, drop_null, camel))
return data
else:
return obj
return to_dict(self, drop_null, camel) | [
"def",
"to_dict",
"(",
"self",
",",
"drop_null",
"=",
"True",
",",
"camel",
"=",
"False",
")",
":",
"#return _to_dict(self, drop_null, camel)",
"def",
"to_dict",
"(",
"obj",
",",
"drop_null",
",",
"camel",
")",
":",
"\"\"\"Recursively constructs the dict.\"\"\"",
"if",
"isinstance",
"(",
"obj",
",",
"(",
"Body",
",",
"BodyChild",
")",
")",
":",
"obj",
"=",
"obj",
".",
"__dict__",
"if",
"isinstance",
"(",
"obj",
",",
"dict",
")",
":",
"data",
"=",
"{",
"}",
"for",
"attr",
",",
"val",
"in",
"six",
".",
"iteritems",
"(",
"obj",
")",
":",
"if",
"camel",
":",
"attr",
"=",
"_snake_to_camel",
"(",
"attr",
")",
"valid_null",
"=",
"(",
"isinstance",
"(",
"val",
",",
"bool",
")",
"or",
"val",
"==",
"0",
"or",
"(",
"val",
"and",
"to_dict",
"(",
"val",
",",
"drop_null",
",",
"camel",
")",
")",
")",
"if",
"not",
"drop_null",
"or",
"(",
"drop_null",
"and",
"valid_null",
")",
":",
"data",
"[",
"attr",
"]",
"=",
"to_dict",
"(",
"val",
",",
"drop_null",
",",
"camel",
")",
"return",
"data",
"elif",
"isinstance",
"(",
"obj",
",",
"list",
")",
":",
"data",
"=",
"[",
"]",
"for",
"val",
"in",
"obj",
":",
"valid_null",
"=",
"(",
"isinstance",
"(",
"val",
",",
"bool",
")",
"or",
"val",
"==",
"0",
"or",
"(",
"val",
"and",
"to_dict",
"(",
"val",
",",
"drop_null",
",",
"camel",
")",
")",
")",
"if",
"not",
"drop_null",
"or",
"(",
"drop_null",
"and",
"valid_null",
")",
":",
"data",
".",
"append",
"(",
"to_dict",
"(",
"val",
",",
"drop_null",
",",
"camel",
")",
")",
"return",
"data",
"else",
":",
"return",
"obj",
"return",
"to_dict",
"(",
"self",
",",
"drop_null",
",",
"camel",
")"
] | Serialize self as dict.
Args:
drop_null: bool, default True. Remove 'empty' attributes.
camel: bool, default True. Convert keys to camelCase.
Return:
dict: object params. | [
"Serialize",
"self",
"as",
"dict",
"."
] | 8646f54faf62cb63f165f7699b8ace5b4a08233c | https://github.com/bmweiner/skillful/blob/8646f54faf62cb63f165f7699b8ace5b4a08233c/skillful/interface.py#L45-L80 |
249,394 | bmweiner/skillful | skillful/interface.py | RequestBody.parse | def parse(self, body):
"""Parse JSON request, storing content in object attributes.
Args:
body: str. HTTP request body.
Returns:
self
"""
if isinstance(body, six.string_types):
body = json.loads(body)
# version
version = body['version']
self.version = version
# session
session = body['session']
self.session.new = session['new']
self.session.session_id = session['sessionId']
application_id = session['application']['applicationId']
self.session.application.application_id = application_id
if 'attributes' in session and session['attributes']:
self.session.attributes = session.get('attributes', {})
else:
self.session.attributes = {}
self.session.user.user_id = session['user']['userId']
self.session.user.access_token = session['user'].get('accessToken', 0)
# request
request = body['request']
# launch request
if request['type'] == 'LaunchRequest':
self.request = LaunchRequest()
# intent request
elif request['type'] == 'IntentRequest':
self.request = IntentRequest()
self.request.intent = Intent()
intent = request['intent']
self.request.intent.name = intent['name']
if 'slots' in intent and intent['slots']:
for name, slot in six.iteritems(intent['slots']):
self.request.intent.slots[name] = Slot()
self.request.intent.slots[name].name = slot['name']
self.request.intent.slots[name].value = slot.get('value')
# session ended request
elif request['type'] == 'SessionEndedRequest':
self.request = SessionEndedRequest()
self.request.reason = request['reason']
# common - keep after specific requests to prevent param overwrite
self.request.type = request['type']
self.request.request_id = request['requestId']
self.request.timestamp = request['timestamp']
return self | python | def parse(self, body):
"""Parse JSON request, storing content in object attributes.
Args:
body: str. HTTP request body.
Returns:
self
"""
if isinstance(body, six.string_types):
body = json.loads(body)
# version
version = body['version']
self.version = version
# session
session = body['session']
self.session.new = session['new']
self.session.session_id = session['sessionId']
application_id = session['application']['applicationId']
self.session.application.application_id = application_id
if 'attributes' in session and session['attributes']:
self.session.attributes = session.get('attributes', {})
else:
self.session.attributes = {}
self.session.user.user_id = session['user']['userId']
self.session.user.access_token = session['user'].get('accessToken', 0)
# request
request = body['request']
# launch request
if request['type'] == 'LaunchRequest':
self.request = LaunchRequest()
# intent request
elif request['type'] == 'IntentRequest':
self.request = IntentRequest()
self.request.intent = Intent()
intent = request['intent']
self.request.intent.name = intent['name']
if 'slots' in intent and intent['slots']:
for name, slot in six.iteritems(intent['slots']):
self.request.intent.slots[name] = Slot()
self.request.intent.slots[name].name = slot['name']
self.request.intent.slots[name].value = slot.get('value')
# session ended request
elif request['type'] == 'SessionEndedRequest':
self.request = SessionEndedRequest()
self.request.reason = request['reason']
# common - keep after specific requests to prevent param overwrite
self.request.type = request['type']
self.request.request_id = request['requestId']
self.request.timestamp = request['timestamp']
return self | [
"def",
"parse",
"(",
"self",
",",
"body",
")",
":",
"if",
"isinstance",
"(",
"body",
",",
"six",
".",
"string_types",
")",
":",
"body",
"=",
"json",
".",
"loads",
"(",
"body",
")",
"# version",
"version",
"=",
"body",
"[",
"'version'",
"]",
"self",
".",
"version",
"=",
"version",
"# session",
"session",
"=",
"body",
"[",
"'session'",
"]",
"self",
".",
"session",
".",
"new",
"=",
"session",
"[",
"'new'",
"]",
"self",
".",
"session",
".",
"session_id",
"=",
"session",
"[",
"'sessionId'",
"]",
"application_id",
"=",
"session",
"[",
"'application'",
"]",
"[",
"'applicationId'",
"]",
"self",
".",
"session",
".",
"application",
".",
"application_id",
"=",
"application_id",
"if",
"'attributes'",
"in",
"session",
"and",
"session",
"[",
"'attributes'",
"]",
":",
"self",
".",
"session",
".",
"attributes",
"=",
"session",
".",
"get",
"(",
"'attributes'",
",",
"{",
"}",
")",
"else",
":",
"self",
".",
"session",
".",
"attributes",
"=",
"{",
"}",
"self",
".",
"session",
".",
"user",
".",
"user_id",
"=",
"session",
"[",
"'user'",
"]",
"[",
"'userId'",
"]",
"self",
".",
"session",
".",
"user",
".",
"access_token",
"=",
"session",
"[",
"'user'",
"]",
".",
"get",
"(",
"'accessToken'",
",",
"0",
")",
"# request",
"request",
"=",
"body",
"[",
"'request'",
"]",
"# launch request",
"if",
"request",
"[",
"'type'",
"]",
"==",
"'LaunchRequest'",
":",
"self",
".",
"request",
"=",
"LaunchRequest",
"(",
")",
"# intent request",
"elif",
"request",
"[",
"'type'",
"]",
"==",
"'IntentRequest'",
":",
"self",
".",
"request",
"=",
"IntentRequest",
"(",
")",
"self",
".",
"request",
".",
"intent",
"=",
"Intent",
"(",
")",
"intent",
"=",
"request",
"[",
"'intent'",
"]",
"self",
".",
"request",
".",
"intent",
".",
"name",
"=",
"intent",
"[",
"'name'",
"]",
"if",
"'slots'",
"in",
"intent",
"and",
"intent",
"[",
"'slots'",
"]",
":",
"for",
"name",
",",
"slot",
"in",
"six",
".",
"iteritems",
"(",
"intent",
"[",
"'slots'",
"]",
")",
":",
"self",
".",
"request",
".",
"intent",
".",
"slots",
"[",
"name",
"]",
"=",
"Slot",
"(",
")",
"self",
".",
"request",
".",
"intent",
".",
"slots",
"[",
"name",
"]",
".",
"name",
"=",
"slot",
"[",
"'name'",
"]",
"self",
".",
"request",
".",
"intent",
".",
"slots",
"[",
"name",
"]",
".",
"value",
"=",
"slot",
".",
"get",
"(",
"'value'",
")",
"# session ended request",
"elif",
"request",
"[",
"'type'",
"]",
"==",
"'SessionEndedRequest'",
":",
"self",
".",
"request",
"=",
"SessionEndedRequest",
"(",
")",
"self",
".",
"request",
".",
"reason",
"=",
"request",
"[",
"'reason'",
"]",
"# common - keep after specific requests to prevent param overwrite",
"self",
".",
"request",
".",
"type",
"=",
"request",
"[",
"'type'",
"]",
"self",
".",
"request",
".",
"request_id",
"=",
"request",
"[",
"'requestId'",
"]",
"self",
".",
"request",
".",
"timestamp",
"=",
"request",
"[",
"'timestamp'",
"]",
"return",
"self"
] | Parse JSON request, storing content in object attributes.
Args:
body: str. HTTP request body.
Returns:
self | [
"Parse",
"JSON",
"request",
"storing",
"content",
"in",
"object",
"attributes",
"."
] | 8646f54faf62cb63f165f7699b8ace5b4a08233c | https://github.com/bmweiner/skillful/blob/8646f54faf62cb63f165f7699b8ace5b4a08233c/skillful/interface.py#L112-L170 |
249,395 | bmweiner/skillful | skillful/interface.py | ResponseBody.set_speech_text | def set_speech_text(self, text):
"""Set response output speech as plain text type.
Args:
text: str. Response speech used when type is 'PlainText'. Cannot exceed
8,000 characters.
"""
self.response.outputSpeech.type = 'PlainText'
self.response.outputSpeech.text = text | python | def set_speech_text(self, text):
"""Set response output speech as plain text type.
Args:
text: str. Response speech used when type is 'PlainText'. Cannot exceed
8,000 characters.
"""
self.response.outputSpeech.type = 'PlainText'
self.response.outputSpeech.text = text | [
"def",
"set_speech_text",
"(",
"self",
",",
"text",
")",
":",
"self",
".",
"response",
".",
"outputSpeech",
".",
"type",
"=",
"'PlainText'",
"self",
".",
"response",
".",
"outputSpeech",
".",
"text",
"=",
"text"
] | Set response output speech as plain text type.
Args:
text: str. Response speech used when type is 'PlainText'. Cannot exceed
8,000 characters. | [
"Set",
"response",
"output",
"speech",
"as",
"plain",
"text",
"type",
"."
] | 8646f54faf62cb63f165f7699b8ace5b4a08233c | https://github.com/bmweiner/skillful/blob/8646f54faf62cb63f165f7699b8ace5b4a08233c/skillful/interface.py#L365-L373 |
249,396 | bmweiner/skillful | skillful/interface.py | ResponseBody.set_speech_ssml | def set_speech_ssml(self, ssml):
"""Set response output speech as SSML type.
Args:
ssml: str. Response speech used when type is 'SSML', should be formatted
with Speech Synthesis Markup Language. Cannot exceed 8,000
characters.
"""
self.response.outputSpeech.type = 'SSML'
self.response.outputSpeech.ssml = ssml | python | def set_speech_ssml(self, ssml):
"""Set response output speech as SSML type.
Args:
ssml: str. Response speech used when type is 'SSML', should be formatted
with Speech Synthesis Markup Language. Cannot exceed 8,000
characters.
"""
self.response.outputSpeech.type = 'SSML'
self.response.outputSpeech.ssml = ssml | [
"def",
"set_speech_ssml",
"(",
"self",
",",
"ssml",
")",
":",
"self",
".",
"response",
".",
"outputSpeech",
".",
"type",
"=",
"'SSML'",
"self",
".",
"response",
".",
"outputSpeech",
".",
"ssml",
"=",
"ssml"
] | Set response output speech as SSML type.
Args:
ssml: str. Response speech used when type is 'SSML', should be formatted
with Speech Synthesis Markup Language. Cannot exceed 8,000
characters. | [
"Set",
"response",
"output",
"speech",
"as",
"SSML",
"type",
"."
] | 8646f54faf62cb63f165f7699b8ace5b4a08233c | https://github.com/bmweiner/skillful/blob/8646f54faf62cb63f165f7699b8ace5b4a08233c/skillful/interface.py#L375-L384 |
249,397 | bmweiner/skillful | skillful/interface.py | ResponseBody.set_card_simple | def set_card_simple(self, title, content):
"""Set response card as simple type.
title and content cannot exceed 8,000 characters.
Args:
title: str. Title of Simple or Standard type card.
content: str. Content of Simple type card.
"""
self.response.card.type = 'Simple'
self.response.card.title = title
self.response.card.content = content | python | def set_card_simple(self, title, content):
"""Set response card as simple type.
title and content cannot exceed 8,000 characters.
Args:
title: str. Title of Simple or Standard type card.
content: str. Content of Simple type card.
"""
self.response.card.type = 'Simple'
self.response.card.title = title
self.response.card.content = content | [
"def",
"set_card_simple",
"(",
"self",
",",
"title",
",",
"content",
")",
":",
"self",
".",
"response",
".",
"card",
".",
"type",
"=",
"'Simple'",
"self",
".",
"response",
".",
"card",
".",
"title",
"=",
"title",
"self",
".",
"response",
".",
"card",
".",
"content",
"=",
"content"
] | Set response card as simple type.
title and content cannot exceed 8,000 characters.
Args:
title: str. Title of Simple or Standard type card.
content: str. Content of Simple type card. | [
"Set",
"response",
"card",
"as",
"simple",
"type",
"."
] | 8646f54faf62cb63f165f7699b8ace5b4a08233c | https://github.com/bmweiner/skillful/blob/8646f54faf62cb63f165f7699b8ace5b4a08233c/skillful/interface.py#L386-L397 |
249,398 | bmweiner/skillful | skillful/interface.py | ResponseBody.set_card_standard | def set_card_standard(self, title, text, smallImageUrl=None,
largeImageUrl=None):
"""Set response card as standard type.
title, text, and image cannot exceed 8,000 characters.
Args:
title: str. Title of Simple or Standard type card.
text: str. Content of Standard type card.
smallImageUrl: str. URL of small image. Cannot exceed 2,000
characters. Recommended pixel size: 720w x 480h.
largeImageUrl: str. URL of large image. Cannot exceed 2,000
characters. Recommended pixel size: 1200w x 800h.
"""
self.response.card.type = 'Standard'
self.response.card.title = title
self.response.card.text = text
if smallImageUrl:
self.response.card.image.smallImageUrl = smallImageUrl
if largeImageUrl:
self.response.card.image.largeImageUrl = largeImageUrl | python | def set_card_standard(self, title, text, smallImageUrl=None,
largeImageUrl=None):
"""Set response card as standard type.
title, text, and image cannot exceed 8,000 characters.
Args:
title: str. Title of Simple or Standard type card.
text: str. Content of Standard type card.
smallImageUrl: str. URL of small image. Cannot exceed 2,000
characters. Recommended pixel size: 720w x 480h.
largeImageUrl: str. URL of large image. Cannot exceed 2,000
characters. Recommended pixel size: 1200w x 800h.
"""
self.response.card.type = 'Standard'
self.response.card.title = title
self.response.card.text = text
if smallImageUrl:
self.response.card.image.smallImageUrl = smallImageUrl
if largeImageUrl:
self.response.card.image.largeImageUrl = largeImageUrl | [
"def",
"set_card_standard",
"(",
"self",
",",
"title",
",",
"text",
",",
"smallImageUrl",
"=",
"None",
",",
"largeImageUrl",
"=",
"None",
")",
":",
"self",
".",
"response",
".",
"card",
".",
"type",
"=",
"'Standard'",
"self",
".",
"response",
".",
"card",
".",
"title",
"=",
"title",
"self",
".",
"response",
".",
"card",
".",
"text",
"=",
"text",
"if",
"smallImageUrl",
":",
"self",
".",
"response",
".",
"card",
".",
"image",
".",
"smallImageUrl",
"=",
"smallImageUrl",
"if",
"largeImageUrl",
":",
"self",
".",
"response",
".",
"card",
".",
"image",
".",
"largeImageUrl",
"=",
"largeImageUrl"
] | Set response card as standard type.
title, text, and image cannot exceed 8,000 characters.
Args:
title: str. Title of Simple or Standard type card.
text: str. Content of Standard type card.
smallImageUrl: str. URL of small image. Cannot exceed 2,000
characters. Recommended pixel size: 720w x 480h.
largeImageUrl: str. URL of large image. Cannot exceed 2,000
characters. Recommended pixel size: 1200w x 800h. | [
"Set",
"response",
"card",
"as",
"standard",
"type",
"."
] | 8646f54faf62cb63f165f7699b8ace5b4a08233c | https://github.com/bmweiner/skillful/blob/8646f54faf62cb63f165f7699b8ace5b4a08233c/skillful/interface.py#L399-L419 |
249,399 | bmweiner/skillful | skillful/interface.py | ResponseBody.set_reprompt_text | def set_reprompt_text(self, text):
"""Set response reprompt output speech as plain text type.
Args:
text: str. Response speech used when type is 'PlainText'. Cannot
exceed 8,000 characters.
"""
self.response.reprompt.outputSpeech.type = 'PlainText'
self.response.reprompt.outputSpeech.text = text | python | def set_reprompt_text(self, text):
"""Set response reprompt output speech as plain text type.
Args:
text: str. Response speech used when type is 'PlainText'. Cannot
exceed 8,000 characters.
"""
self.response.reprompt.outputSpeech.type = 'PlainText'
self.response.reprompt.outputSpeech.text = text | [
"def",
"set_reprompt_text",
"(",
"self",
",",
"text",
")",
":",
"self",
".",
"response",
".",
"reprompt",
".",
"outputSpeech",
".",
"type",
"=",
"'PlainText'",
"self",
".",
"response",
".",
"reprompt",
".",
"outputSpeech",
".",
"text",
"=",
"text"
] | Set response reprompt output speech as plain text type.
Args:
text: str. Response speech used when type is 'PlainText'. Cannot
exceed 8,000 characters. | [
"Set",
"response",
"reprompt",
"output",
"speech",
"as",
"plain",
"text",
"type",
"."
] | 8646f54faf62cb63f165f7699b8ace5b4a08233c | https://github.com/bmweiner/skillful/blob/8646f54faf62cb63f165f7699b8ace5b4a08233c/skillful/interface.py#L425-L433 |
Subsets and Splits