repository_name
stringlengths
7
55
func_path_in_repository
stringlengths
4
223
func_name
stringlengths
1
134
whole_func_string
stringlengths
75
104k
language
stringclasses
1 value
func_code_string
stringlengths
75
104k
func_code_tokens
listlengths
19
28.4k
func_documentation_string
stringlengths
1
46.9k
func_documentation_tokens
listlengths
1
1.97k
split_name
stringclasses
1 value
func_code_url
stringlengths
87
315
cirruscluster/cirruscluster
cirruscluster/ext/ansible/runner/connection_plugins/ssh.py
Connection.put_file
def put_file(self, in_path, out_path): ''' transfer a file from local to remote ''' vvv("PUT %s TO %s" % (in_path, out_path), host=self.host) if not os.path.exists(in_path): raise errors.AnsibleFileNotFound("file or module does not exist: %s" % in_path) cmd = self._password_c...
python
def put_file(self, in_path, out_path): ''' transfer a file from local to remote ''' vvv("PUT %s TO %s" % (in_path, out_path), host=self.host) if not os.path.exists(in_path): raise errors.AnsibleFileNotFound("file or module does not exist: %s" % in_path) cmd = self._password_c...
[ "def", "put_file", "(", "self", ",", "in_path", ",", "out_path", ")", ":", "vvv", "(", "\"PUT %s TO %s\"", "%", "(", "in_path", ",", "out_path", ")", ",", "host", "=", "self", ".", "host", ")", "if", "not", "os", ".", "path", ".", "exists", "(", "i...
transfer a file from local to remote
[ "transfer", "a", "file", "from", "local", "to", "remote" ]
train
https://github.com/cirruscluster/cirruscluster/blob/977409929dd81322d886425cdced10608117d5d7/cirruscluster/ext/ansible/runner/connection_plugins/ssh.py#L159-L180
cirruscluster/cirruscluster
cirruscluster/ext/ansible/runner/connection_plugins/ssh.py
Connection.fetch_file
def fetch_file(self, in_path, out_path): ''' fetch a file from remote to local ''' vvv("FETCH %s TO %s" % (in_path, out_path), host=self.host) cmd = self._password_cmd() if C.DEFAULT_SCP_IF_SSH: cmd += ["scp"] + self.common_args cmd += [self.host + ":" + in_path,...
python
def fetch_file(self, in_path, out_path): ''' fetch a file from remote to local ''' vvv("FETCH %s TO %s" % (in_path, out_path), host=self.host) cmd = self._password_cmd() if C.DEFAULT_SCP_IF_SSH: cmd += ["scp"] + self.common_args cmd += [self.host + ":" + in_path,...
[ "def", "fetch_file", "(", "self", ",", "in_path", ",", "out_path", ")", ":", "vvv", "(", "\"FETCH %s TO %s\"", "%", "(", "in_path", ",", "out_path", ")", ",", "host", "=", "self", ".", "host", ")", "cmd", "=", "self", ".", "_password_cmd", "(", ")", ...
fetch a file from remote to local
[ "fetch", "a", "file", "from", "remote", "to", "local" ]
train
https://github.com/cirruscluster/cirruscluster/blob/977409929dd81322d886425cdced10608117d5d7/cirruscluster/ext/ansible/runner/connection_plugins/ssh.py#L182-L201
minhhoit/yacms
yacms/blog/admin.py
BlogPostAdmin.save_form
def save_form(self, request, form, change): """ Super class ordering is important here - user must get saved first. """ OwnableAdmin.save_form(self, request, form, change) return DisplayableAdmin.save_form(self, request, form, change)
python
def save_form(self, request, form, change): """ Super class ordering is important here - user must get saved first. """ OwnableAdmin.save_form(self, request, form, change) return DisplayableAdmin.save_form(self, request, form, change)
[ "def", "save_form", "(", "self", ",", "request", ",", "form", ",", "change", ")", ":", "OwnableAdmin", ".", "save_form", "(", "self", ",", "request", ",", "form", ",", "change", ")", "return", "DisplayableAdmin", ".", "save_form", "(", "self", ",", "requ...
Super class ordering is important here - user must get saved first.
[ "Super", "class", "ordering", "is", "important", "here", "-", "user", "must", "get", "saved", "first", "." ]
train
https://github.com/minhhoit/yacms/blob/2921b706b7107c6e8c5f2bbf790ff11f85a2167f/yacms/blog/admin.py#L38-L43
minhhoit/yacms
yacms/blog/admin.py
BlogCategoryAdmin.has_module_permission
def has_module_permission(self, request): """ Hide from the admin menu unless explicitly set in ``ADMIN_MENU_ORDER``. """ for (name, items) in settings.ADMIN_MENU_ORDER: if "blog.BlogCategory" in items: return True return False
python
def has_module_permission(self, request): """ Hide from the admin menu unless explicitly set in ``ADMIN_MENU_ORDER``. """ for (name, items) in settings.ADMIN_MENU_ORDER: if "blog.BlogCategory" in items: return True return False
[ "def", "has_module_permission", "(", "self", ",", "request", ")", ":", "for", "(", "name", ",", "items", ")", "in", "settings", ".", "ADMIN_MENU_ORDER", ":", "if", "\"blog.BlogCategory\"", "in", "items", ":", "return", "True", "return", "False" ]
Hide from the admin menu unless explicitly set in ``ADMIN_MENU_ORDER``.
[ "Hide", "from", "the", "admin", "menu", "unless", "explicitly", "set", "in", "ADMIN_MENU_ORDER", "." ]
train
https://github.com/minhhoit/yacms/blob/2921b706b7107c6e8c5f2bbf790ff11f85a2167f/yacms/blog/admin.py#L54-L61
rackerlabs/rackspace-python-neutronclient
neutronclient/common/utils.py
env
def env(*vars, **kwargs): """Returns the first environment variable set. If none are non-empty, defaults to '' or keyword arg default. """ for v in vars: value = os.environ.get(v) if value: return value return kwargs.get('default', '')
python
def env(*vars, **kwargs): """Returns the first environment variable set. If none are non-empty, defaults to '' or keyword arg default. """ for v in vars: value = os.environ.get(v) if value: return value return kwargs.get('default', '')
[ "def", "env", "(", "*", "vars", ",", "*", "*", "kwargs", ")", ":", "for", "v", "in", "vars", ":", "value", "=", "os", ".", "environ", ".", "get", "(", "v", ")", "if", "value", ":", "return", "value", "return", "kwargs", ".", "get", "(", "'defau...
Returns the first environment variable set. If none are non-empty, defaults to '' or keyword arg default.
[ "Returns", "the", "first", "environment", "variable", "set", "." ]
train
https://github.com/rackerlabs/rackspace-python-neutronclient/blob/5a5009a8fe078e3aa1d582176669f1b28ab26bef/neutronclient/common/utils.py#L37-L46
rackerlabs/rackspace-python-neutronclient
neutronclient/common/utils.py
get_client_class
def get_client_class(api_name, version, version_map): """Returns the client class for the requested API version. :param api_name: the name of the API, e.g. 'compute', 'image', etc :param version: the requested API version :param version_map: a dict of client classes keyed by version :rtype: a clien...
python
def get_client_class(api_name, version, version_map): """Returns the client class for the requested API version. :param api_name: the name of the API, e.g. 'compute', 'image', etc :param version: the requested API version :param version_map: a dict of client classes keyed by version :rtype: a clien...
[ "def", "get_client_class", "(", "api_name", ",", "version", ",", "version_map", ")", ":", "try", ":", "client_path", "=", "version_map", "[", "str", "(", "version", ")", "]", "except", "(", "KeyError", ",", "ValueError", ")", ":", "msg", "=", "_", "(", ...
Returns the client class for the requested API version. :param api_name: the name of the API, e.g. 'compute', 'image', etc :param version: the requested API version :param version_map: a dict of client classes keyed by version :rtype: a client class for the requested API version
[ "Returns", "the", "client", "class", "for", "the", "requested", "API", "version", "." ]
train
https://github.com/rackerlabs/rackspace-python-neutronclient/blob/5a5009a8fe078e3aa1d582176669f1b28ab26bef/neutronclient/common/utils.py#L57-L74
rackerlabs/rackspace-python-neutronclient
neutronclient/common/utils.py
get_item_properties
def get_item_properties(item, fields, mixed_case_fields=(), formatters=None): """Return a tuple containing the item properties. :param item: a single item resource (e.g. Server, Tenant, etc) :param fields: tuple of strings with the desired field names :param mixed_case_fields: tuple of field names to p...
python
def get_item_properties(item, fields, mixed_case_fields=(), formatters=None): """Return a tuple containing the item properties. :param item: a single item resource (e.g. Server, Tenant, etc) :param fields: tuple of strings with the desired field names :param mixed_case_fields: tuple of field names to p...
[ "def", "get_item_properties", "(", "item", ",", "fields", ",", "mixed_case_fields", "=", "(", ")", ",", "formatters", "=", "None", ")", ":", "if", "formatters", "is", "None", ":", "formatters", "=", "{", "}", "row", "=", "[", "]", "for", "field", "in",...
Return a tuple containing the item properties. :param item: a single item resource (e.g. Server, Tenant, etc) :param fields: tuple of strings with the desired field names :param mixed_case_fields: tuple of field names to preserve case :param formatters: dictionary mapping field names to callables ...
[ "Return", "a", "tuple", "containing", "the", "item", "properties", "." ]
train
https://github.com/rackerlabs/rackspace-python-neutronclient/blob/5a5009a8fe078e3aa1d582176669f1b28ab26bef/neutronclient/common/utils.py#L77-L106
rackerlabs/rackspace-python-neutronclient
neutronclient/common/utils.py
str2dict
def str2dict(strdict, required_keys=None, optional_keys=None): """Convert key1=value1,key2=value2,... string into dictionary. :param strdict: string in the form of key1=value1,key2=value2 :param required_keys: list of required keys. All keys in this list must be specified. Otherwise ...
python
def str2dict(strdict, required_keys=None, optional_keys=None): """Convert key1=value1,key2=value2,... string into dictionary. :param strdict: string in the form of key1=value1,key2=value2 :param required_keys: list of required keys. All keys in this list must be specified. Otherwise ...
[ "def", "str2dict", "(", "strdict", ",", "required_keys", "=", "None", ",", "optional_keys", "=", "None", ")", ":", "result", "=", "{", "}", "if", "strdict", ":", "for", "kv", "in", "strdict", ".", "split", "(", "','", ")", ":", "key", ",", "sep", "...
Convert key1=value1,key2=value2,... string into dictionary. :param strdict: string in the form of key1=value1,key2=value2 :param required_keys: list of required keys. All keys in this list must be specified. Otherwise ArgumentTypeError will be raised. If this param...
[ "Convert", "key1", "=", "value1", "key2", "=", "value2", "...", "string", "into", "dictionary", "." ]
train
https://github.com/rackerlabs/rackspace-python-neutronclient/blob/5a5009a8fe078e3aa1d582176669f1b28ab26bef/neutronclient/common/utils.py#L115-L153
dossier/dossier.fc
python/dossier/fc/feature_collection.py
FeatureCollection.loads
def loads(cls, data): '''Create a feature collection from a CBOR byte string.''' rep = cbor.loads(data) if not isinstance(rep, Sequence): raise SerializationError('expected a CBOR list') if len(rep) != 2: raise SerializationError('expected a CBOR list of 2 items')...
python
def loads(cls, data): '''Create a feature collection from a CBOR byte string.''' rep = cbor.loads(data) if not isinstance(rep, Sequence): raise SerializationError('expected a CBOR list') if len(rep) != 2: raise SerializationError('expected a CBOR list of 2 items')...
[ "def", "loads", "(", "cls", ",", "data", ")", ":", "rep", "=", "cbor", ".", "loads", "(", "data", ")", "if", "not", "isinstance", "(", "rep", ",", "Sequence", ")", ":", "raise", "SerializationError", "(", "'expected a CBOR list'", ")", "if", "len", "("...
Create a feature collection from a CBOR byte string.
[ "Create", "a", "feature", "collection", "from", "a", "CBOR", "byte", "string", "." ]
train
https://github.com/dossier/dossier.fc/blob/3e969d0cb2592fc06afc1c849d2b22283450b5e2/python/dossier/fc/feature_collection.py#L185-L201
dossier/dossier.fc
python/dossier/fc/feature_collection.py
FeatureCollection.dumps
def dumps(self): '''Create a CBOR byte string from a feature collection.''' metadata = {'v': 'fc01'} if self.read_only: metadata['ro'] = 1 rep = [metadata, self.to_dict()] return cbor.dumps(rep)
python
def dumps(self): '''Create a CBOR byte string from a feature collection.''' metadata = {'v': 'fc01'} if self.read_only: metadata['ro'] = 1 rep = [metadata, self.to_dict()] return cbor.dumps(rep)
[ "def", "dumps", "(", "self", ")", ":", "metadata", "=", "{", "'v'", ":", "'fc01'", "}", "if", "self", ".", "read_only", ":", "metadata", "[", "'ro'", "]", "=", "1", "rep", "=", "[", "metadata", ",", "self", ".", "to_dict", "(", ")", "]", "return"...
Create a CBOR byte string from a feature collection.
[ "Create", "a", "CBOR", "byte", "string", "from", "a", "feature", "collection", "." ]
train
https://github.com/dossier/dossier.fc/blob/3e969d0cb2592fc06afc1c849d2b22283450b5e2/python/dossier/fc/feature_collection.py#L203-L209
dossier/dossier.fc
python/dossier/fc/feature_collection.py
FeatureCollection.from_dict
def from_dict(cls, data, read_only=False): '''Recreate a feature collection from a dictionary. The dictionary is of the format dumped by :meth:`to_dict`. Additional information, such as whether the feature collection should be read-only, is not included in this dictionary, and i...
python
def from_dict(cls, data, read_only=False): '''Recreate a feature collection from a dictionary. The dictionary is of the format dumped by :meth:`to_dict`. Additional information, such as whether the feature collection should be read-only, is not included in this dictionary, and i...
[ "def", "from_dict", "(", "cls", ",", "data", ",", "read_only", "=", "False", ")", ":", "fc", "=", "cls", "(", "read_only", "=", "read_only", ")", "fc", ".", "_features", "=", "{", "}", "fc", ".", "_from_dict_update", "(", "data", ")", "return", "fc" ...
Recreate a feature collection from a dictionary. The dictionary is of the format dumped by :meth:`to_dict`. Additional information, such as whether the feature collection should be read-only, is not included in this dictionary, and is instead passed as parameters to this function.
[ "Recreate", "a", "feature", "collection", "from", "a", "dictionary", "." ]
train
https://github.com/dossier/dossier.fc/blob/3e969d0cb2592fc06afc1c849d2b22283450b5e2/python/dossier/fc/feature_collection.py#L212-L224
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. ''' ...
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", "to_dict", "(", "self", ")", ":", "def", "is_non_native_sc", "(", "ty", ",", "encoded", ")", ":", "return", "(", "ty", "==", "'StringCounter'", "and", "not", "is_native_string_counter", "(", "encoded", ")", ")", "fc", "=", "{", "}", "native", "=",...
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", "." ]
train
https://github.com/dossier/dossier.fc/blob/3e969d0cb2592fc06afc1c849d2b22283450b5e2/python/dossier/fc/feature_collection.py#L256-L283
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 fe...
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 fe...
[ "def", "merge_with", "(", "self", ",", "other", ",", "multiset_op", ",", "other_op", "=", "None", ")", ":", "result", "=", "FeatureCollection", "(", ")", "for", "ms_name", "in", "set", "(", "self", ".", "_counters", "(", ")", ")", "|", "set", "(", "o...
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 i...
[ "Merge", "this", "feature", "collection", "with", "another", "." ]
train
https://github.com/dossier/dossier.fc/blob/3e969d0cb2592fc06afc1c849d2b22283450b5e2/python/dossier/fc/feature_collection.py#L327-L370
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", ...
Returns sum of all counts in all features that are multisets.
[ "Returns", "sum", "of", "all", "counts", "in", "all", "features", "that", "are", "multisets", "." ]
train
https://github.com/dossier/dossier.fc/blob/3e969d0cb2592fc06afc1c849d2b22283450b5e2/python/dossier/fc/feature_collection.py#L451-L456
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: `cons...
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: `cons...
[ "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...
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 c...
[ "Register", "a", "new", "feature", "serializer", "." ]
train
https://github.com/dossier/dossier.fc/blob/3e969d0cb2592fc06afc1c849d2b22283450b5e2/python/dossier/fc/feature_collection.py#L585-L620
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", "." ]
train
https://github.com/nodev-io/nodev.specs/blob/c4740b13f928d2ad39196a4366c98b5f7716ac35/nodev/specs/generic.py#L45-L47
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...
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...
[ "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", "(", "contain...
Extends ``operator.contains`` by trying very hard to find ``item`` inside container.
[ "Extends", "operator", ".", "contains", "by", "trying", "very", "hard", "to", "find", "item", "inside", "container", "." ]
train
https://github.com/nodev-io/nodev.specs/blob/c4740b13f928d2ad39196a4366c98b5f7716ac35/nodev/specs/generic.py#L50-L74
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(brightne...
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(brightne...
[ "def", "set_brightness", "(", "self", ",", "brightness", ")", ":", "brightness", "=", "min", "(", "[", "1.0", ",", "max", "(", "[", "brightness", ",", "0.0", "]", ")", "]", ")", "# enforces range 0 ... 1", "self", ".", "state", ".", "brightness", "=", ...
set general brightness in range 0...1
[ "set", "general", "brightness", "in", "range", "0", "...", "1" ]
train
https://github.com/zaturox/glin/blob/55214a579c4e4b4d74765f3f6aa2eb815bac1c3b/glin/app.py#L47-L54
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" ]
train
https://github.com/zaturox/glin/blob/55214a579c4e4b4d74765f3f6aa2eb815bac1c3b/glin/app.py#L56-L59
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." ...
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." ...
[ "def", "add_scene", "(", "self", ",", "animation_id", ",", "name", ",", "color", ",", "velocity", ",", "config", ")", ":", "# check arguments", "if", "animation_id", "<", "0", "or", "animation_id", ">=", "len", "(", "self", ".", "state", ".", "animationCla...
Add a new scene, returns Scene ID
[ "Add", "a", "new", "scene", "returns", "Scene", "ID" ]
train
https://github.com/zaturox/glin/blob/55214a579c4e4b4d74765f3f6aa2eb815bac1c3b/glin/app.py#L61-L80
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(...
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(...
[ "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", "(", ...
remove a scene by Scene ID
[ "remove", "a", "scene", "by", "Scene", "ID" ]
train
https://github.com/zaturox/glin/blob/55214a579c4e4b4d74765f3f6aa2eb815bac1c3b/glin/app.py#L82-L98
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(F...
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(F...
[ "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\"", ".",...
rename a scene by scene ID
[ "rename", "a", "scene", "by", "scene", "ID" ]
train
https://github.com/zaturox/glin/blob/55214a579c4e4b4d74765f3f6aa2eb815bac1c3b/glin/app.py#L100-L109
zaturox/glin
glin/app.py
GlinApp.set_scene_config
def set_scene_config(self, scene_id, config): """reconfigure a scene by scene ID""" if not scene_id in self.state.scenes: # does that scene_id exist? err_msg = "Requested to reconfigure scene {sceneNum}, which does not exist".format(sceneNum=scene_id) logging.info(err_msg) ...
python
def set_scene_config(self, scene_id, config): """reconfigure a scene by scene ID""" if not scene_id in self.state.scenes: # does that scene_id exist? err_msg = "Requested to reconfigure scene {sceneNum}, which does not exist".format(sceneNum=scene_id) logging.info(err_msg) ...
[ "def", "set_scene_config", "(", "self", ",", "scene_id", ",", "config", ")", ":", "if", "not", "scene_id", "in", "self", ".", "state", ".", "scenes", ":", "# does that scene_id exist?", "err_msg", "=", "\"Requested to reconfigure scene {sceneNum}, which does not exist\"...
reconfigure a scene by scene ID
[ "reconfigure", "a", "scene", "by", "scene", "ID" ]
train
https://github.com/zaturox/glin/blob/55214a579c4e4b4d74765f3f6aa2eb815bac1c3b/glin/app.py#L111-L122
zaturox/glin
glin/app.py
GlinApp.set_scene_color
def set_scene_color(self, scene_id, color): """reconfigure a scene by scene ID""" if not scene_id in self.state.scenes: # does that scene_id exist? err_msg = "Requested to recolor scene {sceneNum}, which does not exist".format(sceneNum=scene_id) logging.info(err_msg) ...
python
def set_scene_color(self, scene_id, color): """reconfigure a scene by scene ID""" if not scene_id in self.state.scenes: # does that scene_id exist? err_msg = "Requested to recolor scene {sceneNum}, which does not exist".format(sceneNum=scene_id) logging.info(err_msg) ...
[ "def", "set_scene_color", "(", "self", ",", "scene_id", ",", "color", ")", ":", "if", "not", "scene_id", "in", "self", ".", "state", ".", "scenes", ":", "# does that scene_id exist?", "err_msg", "=", "\"Requested to recolor scene {sceneNum}, which does not exist\"", "...
reconfigure a scene by scene ID
[ "reconfigure", "a", "scene", "by", "scene", "ID" ]
train
https://github.com/zaturox/glin/blob/55214a579c4e4b4d74765f3f6aa2eb815bac1c3b/glin/app.py#L124-L136
zaturox/glin
glin/app.py
GlinApp.set_scene_velocity
def set_scene_velocity(self, scene_id, velocity): """reconfigure a scene by scene ID""" if not scene_id in self.state.scenes: # does that scene_id exist? err_msg = "Requested to set velocity on scene {sceneNum}, which does not exist".format(sceneNum=scene_id) logging.info(err_msg...
python
def set_scene_velocity(self, scene_id, velocity): """reconfigure a scene by scene ID""" if not scene_id in self.state.scenes: # does that scene_id exist? err_msg = "Requested to set velocity on scene {sceneNum}, which does not exist".format(sceneNum=scene_id) logging.info(err_msg...
[ "def", "set_scene_velocity", "(", "self", ",", "scene_id", ",", "velocity", ")", ":", "if", "not", "scene_id", "in", "self", ".", "state", ".", "scenes", ":", "# does that scene_id exist?", "err_msg", "=", "\"Requested to set velocity on scene {sceneNum}, which does not...
reconfigure a scene by scene ID
[ "reconfigure", "a", "scene", "by", "scene", "ID" ]
train
https://github.com/zaturox/glin/blob/55214a579c4e4b4d74765f3f6aa2eb815bac1c3b/glin/app.py#L138-L150
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.activeS...
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.activeS...
[ "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", ".", ...
sets the active scene by scene ID
[ "sets", "the", "active", "scene", "by", "scene", "ID" ]
train
https://github.com/zaturox/glin/blob/55214a579c4e4b4d74765f3f6aa2eb815bac1c3b/glin/app.py#L152-L164
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 ob...
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 ob...
[ "def", "set_mainswitch_state", "(", "self", ",", "state", ")", ":", "if", "self", ".", "state", ".", "mainswitch", "==", "state", ":", "err_msg", "=", "\"MainSwitch unchanged, already is {sState}\"", ".", "format", "(", "sState", "=", "\"On\"", "if", "state", ...
Turns output on or off. Also turns hardware on ir off
[ "Turns", "output", "on", "or", "off", ".", "Also", "turns", "hardware", "on", "ir", "off" ]
train
https://github.com/zaturox/glin/blob/55214a579c4e4b4d74765f3f6aa2eb815bac1c3b/glin/app.py#L166-L181
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_c...
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_c...
[ "def", "execute", "(", "self", ")", ":", "try", ":", "logging", ".", "debug", "(", "\"Entering IOLoop\"", ")", "self", ".", "loop", ".", "start", "(", ")", "logging", ".", "debug", "(", "\"Leaving IOLoop\"", ")", "except", "KeyboardInterrupt", ":", "loggin...
Execute Main Loop
[ "Execute", "Main", "Loop" ]
train
https://github.com/zaturox/glin/blob/55214a579c4e4b4d74765f3f6aa2eb815bac1c3b/glin/app.py#L238-L247
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", ",", ...
publish changed brightness
[ "publish", "changed", "brightness" ]
train
https://github.com/zaturox/glin/blob/55214a579c4e4b4d74765f3f6aa2eb815bac1c3b/glin/app.py#L263-L267
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", ...
publish changed mainswitch state
[ "publish", "changed", "mainswitch", "state" ]
train
https://github.com/zaturox/glin/blob/55214a579c4e4b4d74765f3f6aa2eb815bac1c3b/glin/app.py#L268-L272
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", ","...
publish changed active scene
[ "publish", "changed", "active", "scene" ]
train
https://github.com/zaturox/glin/blob/55214a579c4e4b4d74765f3f6aa2eb815bac1c3b/glin/app.py#L273-L277
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.se...
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.se...
[ "def", "publish_scene_add", "(", "self", ",", "scene_id", ",", "animation_id", ",", "name", ",", "color", ",", "velocity", ",", "config", ")", ":", "self", ".", "sequence_number", "+=", "1", "self", ".", "publisher", ".", "send_multipart", "(", "msgs", "."...
publish added scene
[ "publish", "added", "scene" ]
train
https://github.com/zaturox/glin/blob/55214a579c4e4b4d74765f3f6aa2eb815bac1c3b/glin/app.py#L278-L282
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", ","...
publish the removal of a scene
[ "publish", "the", "removal", "of", "a", "scene" ]
train
https://github.com/zaturox/glin/blob/55214a579c4e4b4d74765f3f6aa2eb815bac1c3b/glin/app.py#L283-L287
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_n...
publish a changed scene name
[ "publish", "a", "changed", "scene", "name" ]
train
https://github.com/zaturox/glin/blob/55214a579c4e4b4d74765f3f6aa2eb815bac1c3b/glin/app.py#L288-L292
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", ".", "sequ...
publish a changed scene configuration
[ "publish", "a", "changed", "scene", "configuration" ]
train
https://github.com/zaturox/glin/blob/55214a579c4e4b4d74765f3f6aa2eb815bac1c3b/glin/app.py#L293-L297
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", ".", "sequenc...
publish a changed scene color
[ "publish", "a", "changed", "scene", "color" ]
train
https://github.com/zaturox/glin/blob/55214a579c4e4b4d74765f3f6aa2eb815bac1c3b/glin/app.py#L298-L302
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", ".", ...
publish a changed scene velovity
[ "publish", "a", "changed", "scene", "velovity" ]
train
https://github.com/zaturox/glin/blob/55214a579c4e4b4d74765f3f6aa2eb815bac1c3b/glin/app.py#L303-L307
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_m...
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_m...
[ "def", "handle_snapshot", "(", "self", ",", "msg", ")", ":", "logging", ".", "debug", "(", "\"Sending state snapshot request\"", ")", "identity", "=", "msg", "[", "0", "]", "self", ".", "snapshot", ".", "send_multipart", "(", "[", "identity", "]", "+", "ms...
Handles a snapshot request
[ "Handles", "a", "snapshot", "request" ]
train
https://github.com/zaturox/glin/blob/55214a579c4e4b4d74765f3f6aa2eb815bac1c3b/glin/app.py#L309-L321
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...
handle an incoming message
[ "handle", "an", "incoming", "message" ]
train
https://github.com/zaturox/glin/blob/55214a579c4e4b4d74765f3f6aa2eb815bac1c3b/glin/app.py#L335-L338
cogniteev/docido-python-sdk
docido_sdk/loader.py
load_eggs
def load_eggs(entry_point_name): """Loader that loads any eggs in `sys.path`.""" def _load_eggs(env): distributions, errors = working_set.find_plugins( pkg_resources.Environment() ) for dist in distributions: if dist not in working_set: env.log.deb...
python
def load_eggs(entry_point_name): """Loader that loads any eggs in `sys.path`.""" def _load_eggs(env): distributions, errors = working_set.find_plugins( pkg_resources.Environment() ) for dist in distributions: if dist not in working_set: env.log.deb...
[ "def", "load_eggs", "(", "entry_point_name", ")", ":", "def", "_load_eggs", "(", "env", ")", ":", "distributions", ",", "errors", "=", "working_set", ".", "find_plugins", "(", "pkg_resources", ".", "Environment", "(", ")", ")", "for", "dist", "in", "distribu...
Loader that loads any eggs in `sys.path`.
[ "Loader", "that", "loads", "any", "eggs", "in", "sys", ".", "path", "." ]
train
https://github.com/cogniteev/docido-python-sdk/blob/58ecb6c6f5757fd40c0601657ab18368da7ddf33/docido_sdk/loader.py#L18-L58
chatfirst/chatfirst
chatfirst/models.py
ActionResponse.to_json
def to_json(self): """ Serialize object to json dict :return: dict """ res = dict() res['Count'] = self.count res['Messages'] = self.messages res['ForcedState'] = self.forced res['ForcedKeyboard'] = self.keyboard res['Entities'] = list() ...
python
def to_json(self): """ Serialize object to json dict :return: dict """ res = dict() res['Count'] = self.count res['Messages'] = self.messages res['ForcedState'] = self.forced res['ForcedKeyboard'] = self.keyboard res['Entities'] = list() ...
[ "def", "to_json", "(", "self", ")", ":", "res", "=", "dict", "(", ")", "res", "[", "'Count'", "]", "=", "self", ".", "count", "res", "[", "'Messages'", "]", "=", "self", ".", "messages", "res", "[", "'ForcedState'", "]", "=", "self", ".", "forced",...
Serialize object to json dict :return: dict
[ "Serialize", "object", "to", "json", "dict" ]
train
https://github.com/chatfirst/chatfirst/blob/11e023fc372e034dfd3417b61b67759ef8c37ad6/chatfirst/models.py#L35-L50
chatfirst/chatfirst
chatfirst/models.py
LinkedEntity.to_json
def to_json(self): """ Serialize object to json dict :return: dict """ res = dict() res['Handle'] = '' res['Name'] = self.name res['ImageUrl'] = self.url res['Description'] = self.desc res["EntityOptions"] = self.options return res
python
def to_json(self): """ Serialize object to json dict :return: dict """ res = dict() res['Handle'] = '' res['Name'] = self.name res['ImageUrl'] = self.url res['Description'] = self.desc res["EntityOptions"] = self.options return res
[ "def", "to_json", "(", "self", ")", ":", "res", "=", "dict", "(", ")", "res", "[", "'Handle'", "]", "=", "''", "res", "[", "'Name'", "]", "=", "self", ".", "name", "res", "[", "'ImageUrl'", "]", "=", "self", ".", "url", "res", "[", "'Description'...
Serialize object to json dict :return: dict
[ "Serialize", "object", "to", "json", "dict" ]
train
https://github.com/chatfirst/chatfirst/blob/11e023fc372e034dfd3417b61b67759ef8c37ad6/chatfirst/models.py#L87-L99
chatfirst/chatfirst
chatfirst/models.py
Bot.to_json
def to_json(self): """ Serialize object to json dict :return: dict """ data = dict() data['name'] = self.name data['language'] = self.language data['fancy_name'] = self.fancy_name data['scenario'] = self.scenario return data
python
def to_json(self): """ Serialize object to json dict :return: dict """ data = dict() data['name'] = self.name data['language'] = self.language data['fancy_name'] = self.fancy_name data['scenario'] = self.scenario return data
[ "def", "to_json", "(", "self", ")", ":", "data", "=", "dict", "(", ")", "data", "[", "'name'", "]", "=", "self", ".", "name", "data", "[", "'language'", "]", "=", "self", ".", "language", "data", "[", "'fancy_name'", "]", "=", "self", ".", "fancy_n...
Serialize object to json dict :return: dict
[ "Serialize", "object", "to", "json", "dict" ]
train
https://github.com/chatfirst/chatfirst/blob/11e023fc372e034dfd3417b61b67759ef8c37ad6/chatfirst/models.py#L126-L137
chatfirst/chatfirst
chatfirst/models.py
Message.to_json
def to_json(self): """ Serialize object to json dict :return: dict """ data = dict() data['InterlocutorId'] = self.id_ data['Text'] = self.text data['Username'] = self.username data['FirstName'] = self.first_name data['LastName'] = self.la...
python
def to_json(self): """ Serialize object to json dict :return: dict """ data = dict() data['InterlocutorId'] = self.id_ data['Text'] = self.text data['Username'] = self.username data['FirstName'] = self.first_name data['LastName'] = self.la...
[ "def", "to_json", "(", "self", ")", ":", "data", "=", "dict", "(", ")", "data", "[", "'InterlocutorId'", "]", "=", "self", ".", "id_", "data", "[", "'Text'", "]", "=", "self", ".", "text", "data", "[", "'Username'", "]", "=", "self", ".", "username...
Serialize object to json dict :return: dict
[ "Serialize", "object", "to", "json", "dict" ]
train
https://github.com/chatfirst/chatfirst/blob/11e023fc372e034dfd3417b61b67759ef8c37ad6/chatfirst/models.py#L209-L221
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 unavailab...
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 unavailab...
[ "def", "with_uvloop_if_possible", "(", "f", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "try", ":", "import", "uvloop", "import", "asyncio", "asyncio", ".", "set_event_loop_policy", "(", "uvloop", ".", "EventLoopPolicy", "(", ")", ")", "print", "(...
Simple decorator to provide optional uvloop usage
[ "Simple", "decorator", "to", "provide", "optional", "uvloop", "usage" ]
train
https://github.com/opn-oss/opn-oss-py-common/blob/5d449a4328df3b050513eb74e9df4ddaef74caa8/opendna/common/decorators.py#L30-L39
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(" N...
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(" N...
[ "def", "initialize", "(", ")", ":", "NST", ".", "running", "=", "True", "pg", "=", "Page", "(", "\"http://www.neopets.com/\"", ")", "curtime", "=", "pg", ".", "find", "(", "\"td\"", ",", "{", "'id'", ":", "'nst'", "}", ")", ".", "text", "NST", ".", ...
Initializes the global NST instance with the current NST and begins tracking
[ "Initializes", "the", "global", "NST", "instance", "with", "the", "current", "NST", "and", "begins", "tracking" ]
train
https://github.com/jmgilman/Neolib/blob/228fafeaed0f3195676137732384a14820ae285c/neolib/NST.py#L39-L50
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 th...
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 th...
[ "def", "_attach_to_model", "(", "self", ",", "model", ")", ":", "if", "not", "issubclass", "(", "model", ",", "ModelWithDynamicFieldMixin", ")", ":", "raise", "ImplementationError", "(", "'The \"%s\" model does not inherit from ModelWithDynamicFieldMixin '", "'so the \"%s\"...
Check that the model can handle dynamic fields
[ "Check", "that", "the", "model", "can", "handle", "dynamic", "fields" ]
train
https://github.com/limpyd/redis-limpyd-extensions/blob/13f34e39efd2f802761457da30ab2a4213b63934/limpyd_extensions/dynamic/fields.py#L46-L64
limpyd/redis-limpyd-extensions
limpyd_extensions/dynamic/fields.py
DynamicFieldMixin.pattern
def pattern(self): """ Return the pattern used to check if a field name can be accepted by this dynamic field. Use a default one ('^fieldname_(.+)$') if not set when the field was initialized """ if self.dynamic_version_of is not None: return self.dynamic_vers...
python
def pattern(self): """ Return the pattern used to check if a field name can be accepted by this dynamic field. Use a default one ('^fieldname_(.+)$') if not set when the field was initialized """ if self.dynamic_version_of is not None: return self.dynamic_vers...
[ "def", "pattern", "(", "self", ")", ":", "if", "self", ".", "dynamic_version_of", "is", "not", "None", ":", "return", "self", ".", "dynamic_version_of", ".", "pattern", "if", "not", "self", ".", "_pattern", ":", "self", ".", "_pattern", "=", "re", ".", ...
Return the pattern used to check if a field name can be accepted by this dynamic field. Use a default one ('^fieldname_(.+)$') if not set when the field was initialized
[ "Return", "the", "pattern", "used", "to", "check", "if", "a", "field", "name", "can", "be", "accepted", "by", "this", "dynamic", "field", ".", "Use", "a", "default", "one", "(", "^fieldname_", "(", ".", "+", ")", "$", ")", "if", "not", "set", "when",...
train
https://github.com/limpyd/redis-limpyd-extensions/blob/13f34e39efd2f802761457da30ab2a4213b63934/limpyd_extensions/dynamic/fields.py#L67-L78
limpyd/redis-limpyd-extensions
limpyd_extensions/dynamic/fields.py
DynamicFieldMixin.format
def format(self): """ Return the format used to create the name of a variation of the current dynamic field. Use a default one ('fieldname_%s') if not set when the field was initialized """ if self.dynamic_version_of is not None: return self.dynamic_version_of...
python
def format(self): """ Return the format used to create the name of a variation of the current dynamic field. Use a default one ('fieldname_%s') if not set when the field was initialized """ if self.dynamic_version_of is not None: return self.dynamic_version_of...
[ "def", "format", "(", "self", ")", ":", "if", "self", ".", "dynamic_version_of", "is", "not", "None", ":", "return", "self", ".", "dynamic_version_of", ".", "format", "if", "not", "self", ".", "_format", ":", "self", ".", "_format", "=", "'%s_%%s'", "%",...
Return the format used to create the name of a variation of the current dynamic field. Use a default one ('fieldname_%s') if not set when the field was initialized
[ "Return", "the", "format", "used", "to", "create", "the", "name", "of", "a", "variation", "of", "the", "current", "dynamic", "field", ".", "Use", "a", "default", "one", "(", "fieldname_%s", ")", "if", "not", "set", "when", "the", "field", "was", "initial...
train
https://github.com/limpyd/redis-limpyd-extensions/blob/13f34e39efd2f802761457da30ab2a4213b63934/limpyd_extensions/dynamic/fields.py#L81-L92
limpyd/redis-limpyd-extensions
limpyd_extensions/dynamic/fields.py
DynamicFieldMixin._inventory
def _inventory(self): """ Return (and create if needed) the internal inventory field, a SetField used to track all dynamic versions used on a specific instance. """ if self.dynamic_version_of: return self.dynamic_version_of._inventory if not hasattr(self, '_i...
python
def _inventory(self): """ Return (and create if needed) the internal inventory field, a SetField used to track all dynamic versions used on a specific instance. """ if self.dynamic_version_of: return self.dynamic_version_of._inventory if not hasattr(self, '_i...
[ "def", "_inventory", "(", "self", ")", ":", "if", "self", ".", "dynamic_version_of", ":", "return", "self", ".", "dynamic_version_of", ".", "_inventory", "if", "not", "hasattr", "(", "self", ",", "'_inventory_field'", ")", ":", "self", ".", "_inventory_field",...
Return (and create if needed) the internal inventory field, a SetField used to track all dynamic versions used on a specific instance.
[ "Return", "(", "and", "create", "if", "needed", ")", "the", "internal", "inventory", "field", "a", "SetField", "used", "to", "track", "all", "dynamic", "versions", "used", "on", "a", "specific", "instance", "." ]
train
https://github.com/limpyd/redis-limpyd-extensions/blob/13f34e39efd2f802761457da30ab2a4213b63934/limpyd_extensions/dynamic/fields.py#L129-L144
limpyd/redis-limpyd-extensions
limpyd_extensions/dynamic/fields.py
DynamicFieldMixin._call_command
def _call_command(self, name, *args, **kwargs): """ If a command is called for the main field, without dynamic part, an ImplementationError is raised: commands can only be applied on dynamic versions. On dynamic versions, if the command is a modifier, we add the version in ...
python
def _call_command(self, name, *args, **kwargs): """ If a command is called for the main field, without dynamic part, an ImplementationError is raised: commands can only be applied on dynamic versions. On dynamic versions, if the command is a modifier, we add the version in ...
[ "def", "_call_command", "(", "self", ",", "name", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "if", "self", ".", "dynamic_version_of", "is", "None", ":", "raise", "ImplementationError", "(", "'The main version of a dynamic field cannot accept commands'", ...
If a command is called for the main field, without dynamic part, an ImplementationError is raised: commands can only be applied on dynamic versions. On dynamic versions, if the command is a modifier, we add the version in the inventory.
[ "If", "a", "command", "is", "called", "for", "the", "main", "field", "without", "dynamic", "part", "an", "ImplementationError", "is", "raised", ":", "commands", "can", "only", "be", "applied", "on", "dynamic", "versions", ".", "On", "dynamic", "versions", "i...
train
https://github.com/limpyd/redis-limpyd-extensions/blob/13f34e39efd2f802761457da30ab2a4213b63934/limpyd_extensions/dynamic/fields.py#L146-L163
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)....
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)....
[ "def", "delete", "(", "self", ")", ":", "if", "self", ".", "dynamic_version_of", "is", "None", ":", "self", ".", "_delete_dynamic_versions", "(", ")", "else", ":", "super", "(", "DynamicFieldMixin", ",", "self", ")", ".", "delete", "(", ")", "self", ".",...
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", "." ]
train
https://github.com/limpyd/redis-limpyd-extensions/blob/13f34e39efd2f802761457da30ab2a4213b63934/limpyd_extensions/dynamic/fields.py#L165-L174
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 ' ...
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 ' ...
[ "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", ...
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", "." ]
train
https://github.com/limpyd/redis-limpyd-extensions/blob/13f34e39efd2f802761457da30ab2a4213b63934/limpyd_extensions/dynamic/fields.py#L176-L196
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): ...
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): ...
[ "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 d...
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", "." ]
train
https://github.com/limpyd/redis-limpyd-extensions/blob/13f34e39efd2f802761457da30ab2a4213b63934/limpyd_extensions/dynamic/fields.py#L198-L208
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 ...
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 ...
[ "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", ...
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" ]
train
https://github.com/limpyd/redis-limpyd-extensions/blob/13f34e39efd2f802761457da30ab2a4213b63934/limpyd_extensions/dynamic/fields.py#L210-L218
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 decor...
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 decor...
[ "def", "threadsafe_generator", "(", "generator_func", ")", ":", "def", "decoration", "(", "*", "args", ",", "*", "*", "keyword_args", ")", ":", "\"\"\"A thread-safe decoration for a generator function.\"\"\"", "return", "ThreadSafeIter", "(", "generator_func", "(", "*",...
A decorator that takes a generator function and makes it thread-safe.
[ "A", "decorator", "that", "takes", "a", "generator", "function", "and", "makes", "it", "thread", "-", "safe", "." ]
train
https://github.com/shaypal5/decore/blob/460f22f8b9127e6a80b161a626d8827673343afb/decore/decore.py#L24-L30
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 = [] ...
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", "lazy_property", "(", "function", ")", ":", "cached_val", "=", "[", "]", "def", "_wrapper", "(", "*", "args", ")", ":", "try", ":", "return", "cached_val", "[", "0", "]", "except", "IndexError", ":", "ret_val", "=", "function", "(", "*", "args",...
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", "." ]
train
https://github.com/shaypal5/decore/blob/460f22f8b9127e6a80b161a626d8827673343afb/decore/decore.py#L33-L48
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...
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...
[ "def", "cat", "(", "self", ",", "numlines", "=", "None", ")", ":", "if", "len", "(", "self", ".", "titles", ")", "==", "1", ":", "lines", "=", "self", ".", "lines", "(", ")", "if", "numlines", "is", "not", "None", ":", "lines", "=", "lines", "[...
Return a list of lines output by this service.
[ "Return", "a", "list", "of", "lines", "output", "by", "this", "service", "." ]
train
https://github.com/hitchtest/hitchserve/blob/a2def19979264186d283e76f7f0c88f3ed97f2e0/hitchserve/service_logs.py#L162-L173
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): t...
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): t...
[ "def", "_match_service", "(", "self", ",", "line_with_color", ")", ":", "line", "=", "re", ".", "compile", "(", "\"(\\x1b\\[\\d+m)+\"", ")", ".", "sub", "(", "\"\"", ",", "line_with_color", ")", "# Strip color codes", "regexp", "=", "re", ".", "compile", "("...
Return line if line matches this service's name, return None otherwise.
[ "Return", "line", "if", "line", "matches", "this", "service", "s", "name", "return", "None", "otherwise", "." ]
train
https://github.com/hitchtest/hitchserve/blob/a2def19979264186d283e76f7f0c88f3ed97f2e0/hitchserve/service_logs.py#L183-L192
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(...
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(...
[ "def", "json", "(", "self", ")", ":", "lines", "=", "[", "]", "for", "line", "in", "self", ".", "lines", "(", ")", ":", "try", ":", "if", "len", "(", "line", ")", "==", "1", ":", "lines", ".", "append", "(", "json", ".", "loads", "(", "line",...
Return a list of JSON objects output by this service.
[ "Return", "a", "list", "of", "JSON", "objects", "output", "by", "this", "service", "." ]
train
https://github.com/hitchtest/hitchserve/blob/a2def19979264186d283e76f7f0c88f3ed97f2e0/hitchserve/service_logs.py#L216-L227
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. ...
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. ...
[ "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", "=", "...
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", "." ]
train
https://github.com/cogniteev/docido-python-sdk/blob/58ecb6c6f5757fd40c0601657ab18368da7ddf33/docido_sdk/toolbox/contextlib_ext.py#L13-L34
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.kil...
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.kil...
[ "def", "popen", "(", "*", "args", ",", "*", "*", "kwargs", ")", ":", "process", "=", "subprocess", ".", "Popen", "(", "*", "args", ",", "*", "*", "kwargs", ")", "try", ":", "yield", "process", ".", "pid", "finally", ":", "os", ".", "kill", "(", ...
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", "." ]
train
https://github.com/cogniteev/docido-python-sdk/blob/58ecb6c6f5757fd40c0601657ab18368da7ddf33/docido_sdk/toolbox/contextlib_ext.py#L80-L90
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 Line...
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 Line...
[ "def", "coerce", "(", "self", ",", "value", ")", ":", "if", "isinstance", "(", "value", ",", "LinearOrderedCell", ")", "and", "(", "self", ".", "domain", "==", "value", ".", "domain", "or", "list_diff", "(", "self", ".", "domain", ",", "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" ]
train
https://github.com/EventTeam/beliefs/blob/c07d22b61bebeede74a72800030dde770bf64208/src/beliefs/cells/lists.py#L44-L64
EventTeam/beliefs
src/beliefs/cells/lists.py
LinearOrderedCell.is_contradictory
def is_contradictory(self, other): """ Whether other and self can coexist """ other = self.coerce(other) to_i = self.to_i assert to_i(other.low) <= to_i(other.high), "Low must be <= high" if max(map(to_i, [other.low, self.low])) <= min(map(to_i, [other.high, self....
python
def is_contradictory(self, other): """ Whether other and self can coexist """ other = self.coerce(other) to_i = self.to_i assert to_i(other.low) <= to_i(other.high), "Low must be <= high" if max(map(to_i, [other.low, self.low])) <= min(map(to_i, [other.high, self....
[ "def", "is_contradictory", "(", "self", ",", "other", ")", ":", "other", "=", "self", ".", "coerce", "(", "other", ")", "to_i", "=", "self", ".", "to_i", "assert", "to_i", "(", "other", ".", "low", ")", "<=", "to_i", "(", "other", ".", "high", ")",...
Whether other and self can coexist
[ "Whether", "other", "and", "self", "can", "coexist" ]
train
https://github.com/EventTeam/beliefs/blob/c07d22b61bebeede74a72800030dde770bf64208/src/beliefs/cells/lists.py#L72-L82
EventTeam/beliefs
src/beliefs/cells/lists.py
LinearOrderedCell.is_entailed_by
def is_entailed_by(self, other): """ Other is more specific than self. Other is bounded within self. """ other = self.coerce(other) to_i = self.to_i return to_i(other.low) >= to_i(self.low) and \ to_i(other.high) <= to_i(self.high)
python
def is_entailed_by(self, other): """ Other is more specific than self. Other is bounded within self. """ other = self.coerce(other) to_i = self.to_i return to_i(other.low) >= to_i(self.low) and \ to_i(other.high) <= to_i(self.high)
[ "def", "is_entailed_by", "(", "self", ",", "other", ")", ":", "other", "=", "self", ".", "coerce", "(", "other", ")", "to_i", "=", "self", ".", "to_i", "return", "to_i", "(", "other", ".", "low", ")", ">=", "to_i", "(", "self", ".", "low", ")", "...
Other is more specific than self. Other is bounded within self.
[ "Other", "is", "more", "specific", "than", "self", ".", "Other", "is", "bounded", "within", "self", "." ]
train
https://github.com/EventTeam/beliefs/blob/c07d22b61bebeede74a72800030dde770bf64208/src/beliefs/cells/lists.py#L84-L91
EventTeam/beliefs
src/beliefs/cells/lists.py
LinearOrderedCell.is_equal
def is_equal(self, other): """ If two intervals are the same """ other = self.coerce(other) return list_diff(self.domain, other.domain) == [] \ and self.low == other.low \ and self.high == other.high
python
def is_equal(self, other): """ If two intervals are the same """ other = self.coerce(other) return list_diff(self.domain, other.domain) == [] \ and self.low == other.low \ and self.high == other.high
[ "def", "is_equal", "(", "self", ",", "other", ")", ":", "other", "=", "self", ".", "coerce", "(", "other", ")", "return", "list_diff", "(", "self", ".", "domain", ",", "other", ".", "domain", ")", "==", "[", "]", "and", "self", ".", "low", "==", ...
If two intervals are the same
[ "If", "two", "intervals", "are", "the", "same" ]
train
https://github.com/EventTeam/beliefs/blob/c07d22b61bebeede74a72800030dde770bf64208/src/beliefs/cells/lists.py#L93-L100
EventTeam/beliefs
src/beliefs/cells/lists.py
LinearOrderedCell.merge
def merge(self, other): """ Merges the two values """ other = self.coerce(other) if list_diff(self.domain, other.domain) != []: raise Exception("Incomparable orderings. Different domains") if self.is_equal(other): # pick among dependencies ...
python
def merge(self, other): """ Merges the two values """ other = self.coerce(other) if list_diff(self.domain, other.domain) != []: raise Exception("Incomparable orderings. Different domains") if self.is_equal(other): # pick among dependencies ...
[ "def", "merge", "(", "self", ",", "other", ")", ":", "other", "=", "self", ".", "coerce", "(", "other", ")", "if", "list_diff", "(", "self", ".", "domain", ",", "other", ".", "domain", ")", "!=", "[", "]", ":", "raise", "Exception", "(", "\"Incompa...
Merges the two values
[ "Merges", "the", "two", "values" ]
train
https://github.com/EventTeam/beliefs/blob/c07d22b61bebeede74a72800030dde770bf64208/src/beliefs/cells/lists.py#L108-L129
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", ":", "retur...
Turns a value into a list
[ "Turns", "a", "value", "into", "a", "list" ]
train
https://github.com/EventTeam/beliefs/blob/c07d22b61bebeede74a72800030dde770bf64208/src/beliefs/cells/lists.py#L160-L169
EventTeam/beliefs
src/beliefs/cells/lists.py
ListCell.is_contradictory
def is_contradictory(self, other): """ Two lists are contradictory if the shorter one is not a prefix of the other. (Very strict definition -- could be generalized to subsequence) """ if other.size() > self.size(): return other.is_contradictory(self) # ensure ...
python
def is_contradictory(self, other): """ Two lists are contradictory if the shorter one is not a prefix of the other. (Very strict definition -- could be generalized to subsequence) """ if other.size() > self.size(): return other.is_contradictory(self) # ensure ...
[ "def", "is_contradictory", "(", "self", ",", "other", ")", ":", "if", "other", ".", "size", "(", ")", ">", "self", ".", "size", "(", ")", ":", "return", "other", ".", "is_contradictory", "(", "self", ")", "# ensure self is bigger or equal size", "if", "oth...
Two lists are contradictory if the shorter one is not a prefix of the other. (Very strict definition -- could be generalized to subsequence)
[ "Two", "lists", "are", "contradictory", "if", "the", "shorter", "one", "is", "not", "a", "prefix", "of", "the", "other", ".", "(", "Very", "strict", "definition", "--", "could", "be", "generalized", "to", "subsequence", ")" ]
train
https://github.com/EventTeam/beliefs/blob/c07d22b61bebeede74a72800030dde770bf64208/src/beliefs/cells/lists.py#L180-L201
EventTeam/beliefs
src/beliefs/cells/lists.py
ListCell.is_entailed_by
def is_entailed_by(self, other): """ Returns True iff the values in this list can be entailed by the other list (ie, this list is a prefix of the other) """ other = ListCell.coerce(other) if other.size() < self.size(): # other is bigger, can't be entailed ...
python
def is_entailed_by(self, other): """ Returns True iff the values in this list can be entailed by the other list (ie, this list is a prefix of the other) """ other = ListCell.coerce(other) if other.size() < self.size(): # other is bigger, can't be entailed ...
[ "def", "is_entailed_by", "(", "self", ",", "other", ")", ":", "other", "=", "ListCell", ".", "coerce", "(", "other", ")", "if", "other", ".", "size", "(", ")", "<", "self", ".", "size", "(", ")", ":", "# other is bigger, can't be entailed", "return", "Fa...
Returns True iff the values in this list can be entailed by the other list (ie, this list is a prefix of the other)
[ "Returns", "True", "iff", "the", "values", "in", "this", "list", "can", "be", "entailed", "by", "the", "other", "list", "(", "ie", "this", "list", "is", "a", "prefix", "of", "the", "other", ")" ]
train
https://github.com/EventTeam/beliefs/blob/c07d22b61bebeede74a72800030dde770bf64208/src/beliefs/cells/lists.py#L203-L228
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" ]
train
https://github.com/EventTeam/beliefs/blob/c07d22b61bebeede74a72800030dde770bf64208/src/beliefs/cells/lists.py#L268-L275
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): ...
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): ...
[ "def", "merge", "(", "self", ",", "other", ")", ":", "other", "=", "PrefixCell", ".", "coerce", "(", "other", ")", "if", "self", ".", "is_equal", "(", "other", ")", ":", "# pick among dependencies", "return", "self", "elif", "other", ".", "is_entailed_by",...
Merges two prefixes
[ "Merges", "two", "prefixes" ]
train
https://github.com/EventTeam/beliefs/blob/c07d22b61bebeede74a72800030dde770bf64208/src/beliefs/cells/lists.py#L304-L323
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(conte...
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(conte...
[ "def", "get_template", "(", "self", ",", "context", ",", "*", "*", "kwargs", ")", ":", "if", "'template'", "in", "kwargs", "[", "'params'", "]", ":", "self", ".", "template", "=", "kwargs", "[", "'params'", "]", "[", "'template'", "]", "return", "super...
Returns the template to be used for the current context and arguments.
[ "Returns", "the", "template", "to", "be", "used", "for", "the", "current", "context", "and", "arguments", "." ]
train
https://github.com/sternoru/goscalecms/blob/7eee50357c47ebdfe3e573a8b4be3b67892d229e/goscale/templatetags/goscale_tags.py#L27-L33
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....
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....
[ "def", "admin_keywords_submit", "(", "request", ")", ":", "keyword_ids", ",", "titles", "=", "[", "]", ",", "[", "]", "remove", "=", "punctuation", ".", "replace", "(", "\"-\"", ",", "\"\"", ")", "# Strip punctuation, allow dashes.", "for", "title", "in", "r...
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", "." ]
train
https://github.com/minhhoit/yacms/blob/2921b706b7107c6e8c5f2bbf790ff11f85a2167f/yacms/generic/views.py#L26-L43
minhhoit/yacms
yacms/generic/views.py
initial_validation
def initial_validation(request, prefix): """ Returns the related model instance and post data to use in the comment/rating views below. Both comments and ratings have a ``prefix_ACCOUNT_REQUIRED`` setting. If this is ``True`` and the user is unauthenticated, we store their post data in their se...
python
def initial_validation(request, prefix): """ Returns the related model instance and post data to use in the comment/rating views below. Both comments and ratings have a ``prefix_ACCOUNT_REQUIRED`` setting. If this is ``True`` and the user is unauthenticated, we store their post data in their se...
[ "def", "initial_validation", "(", "request", ",", "prefix", ")", ":", "post_data", "=", "request", ".", "POST", "login_required_setting_name", "=", "prefix", ".", "upper", "(", ")", "+", "\"S_ACCOUNT_REQUIRED\"", "posted_session_key", "=", "\"unauthenticated_\"", "+...
Returns the related model instance and post data to use in the comment/rating views below. Both comments and ratings have a ``prefix_ACCOUNT_REQUIRED`` setting. If this is ``True`` and the user is unauthenticated, we store their post data in their session, and redirect to login with the view's url ...
[ "Returns", "the", "related", "model", "instance", "and", "post", "data", "to", "use", "in", "the", "comment", "/", "rating", "views", "below", "." ]
train
https://github.com/minhhoit/yacms/blob/2921b706b7107c6e8c5f2bbf790ff11f85a2167f/yacms/generic/views.py#L46-L88
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_...
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_...
[ "def", "comment", "(", "request", ",", "template", "=", "\"generic/comments.html\"", ",", "extra_context", "=", "None", ")", ":", "response", "=", "initial_validation", "(", "request", ",", "\"comment\"", ")", "if", "isinstance", "(", "response", ",", "HttpRespo...
Handle a ``ThreadedCommentForm`` submission and redirect back to its related object.
[ "Handle", "a", "ThreadedCommentForm", "submission", "and", "redirect", "back", "to", "its", "related", "object", "." ]
train
https://github.com/minhhoit/yacms/blob/2921b706b7107c6e8c5f2bbf790ff11f85a2167f/yacms/generic/views.py#L91-L119
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()...
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()...
[ "def", "rating", "(", "request", ")", ":", "response", "=", "initial_validation", "(", "request", ",", "\"rating\"", ")", "if", "isinstance", "(", "response", ",", "HttpResponse", ")", ":", "return", "response", "obj", ",", "post_data", "=", "response", "url...
Handle a ``RatingForm`` submission and redirect back to its related object.
[ "Handle", "a", "RatingForm", "submission", "and", "redirect", "back", "to", "its", "related", "object", "." ]
train
https://github.com/minhhoit/yacms/blob/2921b706b7107c6e8c5f2bbf790ff11f85a2167f/yacms/generic/views.py#L122-L149
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( ...
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( ...
[ "def", "add", "(", "self", ",", "obj", ",", "metadata", "=", "None", ",", "update", "=", "False", ")", ":", "if", "(", "obj", "not", "in", "self", ")", "or", "update", ":", "self", "[", "obj", ".", "id", "]", "=", "Object", ".", "fromdict", "("...
Add an existing CDSTAR object to the catalog. :param obj: A pycdstar.resource.Object instance
[ "Add", "an", "existing", "CDSTAR", "object", "to", "the", "catalog", "." ]
train
https://github.com/clld/cdstarcat/blob/41f33f59cdde5e30835d2f3accf2d1fbe5332cab/src/cdstarcat/catalog.py#L175-L188
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", "." ]
train
https://github.com/clld/cdstarcat/blob/41f33f59cdde5e30835d2f3accf2d1fbe5332cab/src/cdstarcat/catalog.py#L200-L208
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...
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...
[ "def", "create", "(", "self", ",", "path", ",", "metadata", ",", "filter_", "=", "filter_hidden", ",", "object_class", "=", "None", ")", ":", "path", "=", "Path", "(", "path", ")", "if", "path", ".", "is_file", "(", ")", ":", "fnames", "=", "[", "p...
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`. ...
[ "Create", "objects", "in", "CDSTAR", "and", "register", "them", "in", "the", "catalog", "." ]
train
https://github.com/clld/cdstarcat/blob/41f33f59cdde5e30835d2f3accf2d1fbe5332cab/src/cdstarcat/catalog.py#L210-L233
hawkowl/txctools
txctools/tools.py
parsePyLintWarnings
def parsePyLintWarnings(warnings): """ Turns pyLint/TwistedChecker output into something more useful. @param warnings: The warnings to process. Needs to be in pyLint's 'parseable' format. @return: L{dict} of L{list}s """ warningsDict = {} for line in warnings: match = re...
python
def parsePyLintWarnings(warnings): """ Turns pyLint/TwistedChecker output into something more useful. @param warnings: The warnings to process. Needs to be in pyLint's 'parseable' format. @return: L{dict} of L{list}s """ warningsDict = {} for line in warnings: match = re...
[ "def", "parsePyLintWarnings", "(", "warnings", ")", ":", "warningsDict", "=", "{", "}", "for", "line", "in", "warnings", ":", "match", "=", "re", ".", "search", "(", "P_PYLINT_ERROR", ",", "line", ")", "if", "match", ":", "matchDict", "=", "match", ".", ...
Turns pyLint/TwistedChecker output into something more useful. @param warnings: The warnings to process. Needs to be in pyLint's 'parseable' format. @return: L{dict} of L{list}s
[ "Turns", "pyLint", "/", "TwistedChecker", "output", "into", "something", "more", "useful", "." ]
train
https://github.com/hawkowl/txctools/blob/14cab033ea179211a7bfd88dc202d576fc336ddc/txctools/tools.py#L13-L45
dlancer/django-pages-cms
pages/templatetags/pages_tags.py
get_page_object
def get_page_object(objects, sid): """ **Arguments** ``objects`` all objects ``sid` symbolic id for object selection :return selected object """ selected_object = None for obj in objects: if obj.sid == sid: selected_object = obj break ...
python
def get_page_object(objects, sid): """ **Arguments** ``objects`` all objects ``sid` symbolic id for object selection :return selected object """ selected_object = None for obj in objects: if obj.sid == sid: selected_object = obj break ...
[ "def", "get_page_object", "(", "objects", ",", "sid", ")", ":", "selected_object", "=", "None", "for", "obj", "in", "objects", ":", "if", "obj", ".", "sid", "==", "sid", ":", "selected_object", "=", "obj", "break", "return", "selected_object" ]
**Arguments** ``objects`` all objects ``sid` symbolic id for object selection :return selected object
[ "**", "Arguments", "**" ]
train
https://github.com/dlancer/django-pages-cms/blob/441fad674d5ad4f6e05c953508950525dc0fa789/pages/templatetags/pages_tags.py#L12-L30
dlancer/django-pages-cms
pages/templatetags/pages_tags.py
get_page_object_by_name
def get_page_object_by_name(context, name): """ **Arguments** ``name` name for object selection :return selected object """ selected_object = None try: for obj_type in context['page']['content']: for obj in context['page']['content'][obj_type]: ...
python
def get_page_object_by_name(context, name): """ **Arguments** ``name` name for object selection :return selected object """ selected_object = None try: for obj_type in context['page']['content']: for obj in context['page']['content'][obj_type]: ...
[ "def", "get_page_object_by_name", "(", "context", ",", "name", ")", ":", "selected_object", "=", "None", "try", ":", "for", "obj_type", "in", "context", "[", "'page'", "]", "[", "'content'", "]", ":", "for", "obj", "in", "context", "[", "'page'", "]", "[...
**Arguments** ``name` name for object selection :return selected object
[ "**", "Arguments", "**" ]
train
https://github.com/dlancer/django-pages-cms/blob/441fad674d5ad4f6e05c953508950525dc0fa789/pages/templatetags/pages_tags.py#L34-L59
dlancer/django-pages-cms
pages/templatetags/pages_tags.py
get_page_object_by_id
def get_page_object_by_id(context, object_type, oid): """ **Arguments** ``object_type`` object type ``oid`` id for object selection :return selected object """ if type(oid) != int: raise template.TemplateSyntaxError('page_object_by_id tag requires a integer argumen...
python
def get_page_object_by_id(context, object_type, oid): """ **Arguments** ``object_type`` object type ``oid`` id for object selection :return selected object """ if type(oid) != int: raise template.TemplateSyntaxError('page_object_by_id tag requires a integer argumen...
[ "def", "get_page_object_by_id", "(", "context", ",", "object_type", ",", "oid", ")", ":", "if", "type", "(", "oid", ")", "!=", "int", ":", "raise", "template", ".", "TemplateSyntaxError", "(", "'page_object_by_id tag requires a integer argument'", ")", "selected_obj...
**Arguments** ``object_type`` object type ``oid`` id for object selection :return selected object
[ "**", "Arguments", "**" ]
train
https://github.com/dlancer/django-pages-cms/blob/441fad674d5ad4f6e05c953508950525dc0fa789/pages/templatetags/pages_tags.py#L63-L105
dlancer/django-pages-cms
pages/templatetags/pages_tags.py
get_page_objects_by_type
def get_page_objects_by_type(context, object_type): """ **Arguments** ``object_type`` object type :return selected objects """ try: objects = context['page']['content'][object_type] except KeyError: raise template.TemplateSyntaxError('wrong content type: {0:>s}'.for...
python
def get_page_objects_by_type(context, object_type): """ **Arguments** ``object_type`` object type :return selected objects """ try: objects = context['page']['content'][object_type] except KeyError: raise template.TemplateSyntaxError('wrong content type: {0:>s}'.for...
[ "def", "get_page_objects_by_type", "(", "context", ",", "object_type", ")", ":", "try", ":", "objects", "=", "context", "[", "'page'", "]", "[", "'content'", "]", "[", "object_type", "]", "except", "KeyError", ":", "raise", "template", ".", "TemplateSyntaxErro...
**Arguments** ``object_type`` object type :return selected objects
[ "**", "Arguments", "**" ]
train
https://github.com/dlancer/django-pages-cms/blob/441fad674d5ad4f6e05c953508950525dc0fa789/pages/templatetags/pages_tags.py#L109-L122
dlancer/django-pages-cms
pages/templatetags/pages_tags.py
get_page_objects_by_ext_type
def get_page_objects_by_ext_type(context, object_type): """ **Arguments** ``object_type`` object type :return selected objects """ try: objects = context['page']['ext_content'][object_type] except KeyError: raise template.TemplateSyntaxError('wrong content type: {0:...
python
def get_page_objects_by_ext_type(context, object_type): """ **Arguments** ``object_type`` object type :return selected objects """ try: objects = context['page']['ext_content'][object_type] except KeyError: raise template.TemplateSyntaxError('wrong content type: {0:...
[ "def", "get_page_objects_by_ext_type", "(", "context", ",", "object_type", ")", ":", "try", ":", "objects", "=", "context", "[", "'page'", "]", "[", "'ext_content'", "]", "[", "object_type", "]", "except", "KeyError", ":", "raise", "template", ".", "TemplateSy...
**Arguments** ``object_type`` object type :return selected objects
[ "**", "Arguments", "**" ]
train
https://github.com/dlancer/django-pages-cms/blob/441fad674d5ad4f6e05c953508950525dc0fa789/pages/templatetags/pages_tags.py#L126-L139
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 ...
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 ...
[ "def", "csep_close", "(", "ra", ",", "rb", ")", ":", "seps", "=", "csep", "(", "ra", ",", "rb", ")", "seps_sq", "=", "np", ".", "sum", "(", "np", ".", "square", "(", "seps", ")", ",", "axis", "=", "-", "1", ")", "i_close", "=", "np", ".", "...
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...
[ "Return", "the", "closest", "separation", "vector", "between", "each", "point", "in", "one", "set", "and", "every", "point", "in", "a", "second", "set", "." ]
train
https://github.com/eddiejessup/spatious/blob/b7ae91bec029e85a45a7f303ee184076433723cd/spatious/distance.py#L28-L53
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 ------- ...
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 ------- ...
[ "def", "csep_periodic", "(", "ra", ",", "rb", ",", "L", ")", ":", "seps", "=", "ra", "[", ":", ",", "np", ".", "newaxis", ",", ":", "]", "-", "rb", "[", "np", ".", "newaxis", ",", ":", ",", ":", "]", "for", "i_dim", "in", "range", "(", "ra"...
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...
[ "Return", "separation", "vectors", "between", "each", "pair", "of", "the", "two", "sets", "of", "points", "." ]
train
https://github.com/eddiejessup/spatious/blob/b7ae91bec029e85a45a7f303ee184076433723cd/spatious/distance.py#L56-L77
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 poin...
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 poin...
[ "def", "csep_periodic_close", "(", "ra", ",", "rb", ",", "L", ")", ":", "seps", "=", "csep_periodic", "(", "ra", ",", "rb", ",", "L", ")", "seps_sq", "=", "np", ".", "sum", "(", "np", ".", "square", "(", "seps", ")", ",", "axis", "=", "-", "1",...
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 separatio...
[ "Return", "the", "closest", "separation", "vector", "between", "each", "point", "in", "one", "set", "and", "every", "point", "in", "a", "second", "set", "in", "periodic", "space", "." ]
train
https://github.com/eddiejessup/spatious/blob/b7ae91bec029e85a45a7f303ee184076433723cd/spatious/distance.py#L80-L107
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,) ...
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,) ...
[ "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 ----...
[ "Return", "the", "squared", "distance", "between", "each", "point", "in", "on", "set", "and", "every", "point", "in", "a", "second", "set", "in", "periodic", "space", "." ]
train
https://github.com/eddiejessup/spatious/blob/b7ae91bec029e85a45a7f303ee184076433723cd/spatious/distance.py#L110-L126
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...
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...
[ "def", "pdist_sq_periodic", "(", "r", ",", "L", ")", ":", "d", "=", "csep_periodic", "(", "r", ",", "r", ",", "L", ")", "d", "[", "np", ".", "identity", "(", "len", "(", "r", ")", ",", "dtype", "=", "np", ".", "bool", ")", "]", "=", "np", "...
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) ...
[ "Return", "the", "squared", "distance", "between", "all", "combinations", "of", "a", "set", "of", "points", "in", "periodic", "space", "." ]
train
https://github.com/eddiejessup/spatious/blob/b7ae91bec029e85a45a7f303ee184076433723cd/spatious/distance.py#L129-L148
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...
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...
[ "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", "." ]
train
https://github.com/eddiejessup/spatious/blob/b7ae91bec029e85a45a7f303ee184076433723cd/spatious/distance.py#L151-L165
treycucco/bidon
bidon/field_mapping.py
FieldMapping.get_value
def get_value(self, source): """Apply self.convert to the source. The parameter passed to convert depends on self.source_name. If source_name is given, self.convert(getattr(source, source_name)) is called, otherwise self.convert(source) is called. """ if self.source_name is None: present, valu...
python
def get_value(self, source): """Apply self.convert to the source. The parameter passed to convert depends on self.source_name. If source_name is given, self.convert(getattr(source, source_name)) is called, otherwise self.convert(source) is called. """ if self.source_name is None: present, valu...
[ "def", "get_value", "(", "self", ",", "source", ")", ":", "if", "self", ".", "source_name", "is", "None", ":", "present", ",", "value", "=", "True", ",", "self", ".", "convert", "(", "source", ")", "converted", "=", "True", "else", ":", "present", ",...
Apply self.convert to the source. The parameter passed to convert depends on self.source_name. If source_name is given, self.convert(getattr(source, source_name)) is called, otherwise self.convert(source) is called.
[ "Apply", "self", ".", "convert", "to", "the", "source", ".", "The", "parameter", "passed", "to", "convert", "depends", "on", "self", ".", "source_name", ".", "If", "source_name", "is", "given", "self", ".", "convert", "(", "getattr", "(", "source", "source...
train
https://github.com/treycucco/bidon/blob/d9f24596841d0e69e8ac70a1d1a1deecea95e340/bidon/field_mapping.py#L19-L40
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", "." ]
train
https://github.com/treycucco/bidon/blob/d9f24596841d0e69e8ac70a1d1a1deecea95e340/bidon/field_mapping.py#L43-L45
treycucco/bidon
bidon/field_mapping.py
FieldMapping.get_namedtuple_factory
def get_namedtuple_factory(cls, field_mappings, name="Record"): """Gets a method that will convert a dictionary to a namedtuple, as defined by get_namedtuple(field_mappings). """ ntup = cls.get_namedtuple(field_mappings, name) return lambda data: ntup(**data)
python
def get_namedtuple_factory(cls, field_mappings, name="Record"): """Gets a method that will convert a dictionary to a namedtuple, as defined by get_namedtuple(field_mappings). """ ntup = cls.get_namedtuple(field_mappings, name) return lambda data: ntup(**data)
[ "def", "get_namedtuple_factory", "(", "cls", ",", "field_mappings", ",", "name", "=", "\"Record\"", ")", ":", "ntup", "=", "cls", ".", "get_namedtuple", "(", "field_mappings", ",", "name", ")", "return", "lambda", "data", ":", "ntup", "(", "*", "*", "data"...
Gets a method that will convert a dictionary to a namedtuple, as defined by get_namedtuple(field_mappings).
[ "Gets", "a", "method", "that", "will", "convert", "a", "dictionary", "to", "a", "namedtuple", "as", "defined", "by", "get_namedtuple", "(", "field_mappings", ")", "." ]
train
https://github.com/treycucco/bidon/blob/d9f24596841d0e69e8ac70a1d1a1deecea95e340/bidon/field_mapping.py#L48-L53
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_va...
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_va...
[ "def", "transfer", "(", "cls", ",", "field_mappings", ",", "source", ",", "destination_factory", ")", ":", "data", "=", "dict", "(", ")", "for", "index", ",", "field_mapping", "in", "enumerate", "(", "field_mappings", ")", ":", "try", ":", "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", "." ]
train
https://github.com/treycucco/bidon/blob/d9f24596841d0e69e8ac70a1d1a1deecea95e340/bidon/field_mapping.py#L56-L68
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 E...
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 E...
[ "def", "transfer_all", "(", "cls", ",", "field_mappings", ",", "sources", ",", "destination_factory", "=", "None", ")", ":", "for", "index", ",", "source", "in", "enumerate", "(", "sources", ")", ":", "try", ":", "yield", "cls", ".", "transfer", "(", "fi...
Calls cls.transfer on all records in sources.
[ "Calls", "cls", ".", "transfer", "on", "all", "records", "in", "sources", "." ]
train
https://github.com/treycucco/bidon/blob/d9f24596841d0e69e8ac70a1d1a1deecea95e340/bidon/field_mapping.py#L71-L77
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 lh...
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 lh...
[ "def", "merge_dict", "(", "lhs", ",", "rhs", ")", ":", "assert", "isinstance", "(", "lhs", ",", "dict", ")", "assert", "isinstance", "(", "rhs", ",", "dict", ")", "for", "k", ",", "v", "in", "rhs", ".", "iteritems", "(", ")", ":", "if", "k", "not...
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" ]
train
https://github.com/cogniteev/yamlious/blob/fc6a603367c2135b43ef2356959963d9dccbb25a/yamlious/__init__.py#L21-L36
cogniteev/yamlious
yamlious/__init__.py
from_dict
def from_dict(data): """ Build input parameters of `voluptuous.Schema` constructors from a Python `dict` description. :param :dict: data: same structure than what the YAML loader below loads. :return: tuple of 2 arguments. The first argument is the dict that must be given to `voluptuous.S...
python
def from_dict(data): """ Build input parameters of `voluptuous.Schema` constructors from a Python `dict` description. :param :dict: data: same structure than what the YAML loader below loads. :return: tuple of 2 arguments. The first argument is the dict that must be given to `voluptuous.S...
[ "def", "from_dict", "(", "data", ")", ":", "assert", "isinstance", "(", "data", ",", "dict", ")", "options", "=", "data", ".", "get", "(", "'options'", ",", "{", "}", ")", "content", "=", "data", ".", "get", "(", "'content'", ",", "{", "}", ")", ...
Build input parameters of `voluptuous.Schema` constructors from a Python `dict` description. :param :dict: data: same structure than what the YAML loader below loads. :return: tuple of 2 arguments. The first argument is the dict that must be given to `voluptuous.Schema` class. The second one ...
[ "Build", "input", "parameters", "of", "voluptuous", ".", "Schema", "constructors", "from", "a", "Python", "dict", "description", "." ]
train
https://github.com/cogniteev/yamlious/blob/fc6a603367c2135b43ef2356959963d9dccbb25a/yamlious/__init__.py#L44-L179
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" ]
train
https://github.com/cogniteev/yamlious/blob/fc6a603367c2135b43ef2356959963d9dccbb25a/yamlious/__init__.py#L182-L188