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
nickw444/wtforms-webwidgets
wtforms_webwidgets/bootstrap/util.py
bootstrap_styled
def bootstrap_styled(cls=None, add_meta=True, form_group=True, input_class='form-control'): """ Wrap a widget to conform with Bootstrap's html control design. Args: input_class: Class to give to the rendered <input> control. add_meta: bool: """ def real_decorator(cls...
python
def bootstrap_styled(cls=None, add_meta=True, form_group=True, input_class='form-control'): """ Wrap a widget to conform with Bootstrap's html control design. Args: input_class: Class to give to the rendered <input> control. add_meta: bool: """ def real_decorator(cls...
[ "def", "bootstrap_styled", "(", "cls", "=", "None", ",", "add_meta", "=", "True", ",", "form_group", "=", "True", ",", "input_class", "=", "'form-control'", ")", ":", "def", "real_decorator", "(", "cls", ")", ":", "class", "NewClass", "(", "cls", ")", ":...
Wrap a widget to conform with Bootstrap's html control design. Args: input_class: Class to give to the rendered <input> control. add_meta: bool:
[ "Wrap", "a", "widget", "to", "conform", "with", "Bootstrap", "s", "html", "control", "design", ".", "Args", ":", "input_class", ":", "Class", "to", "give", "to", "the", "rendered", "<input", ">", "control", ".", "add_meta", ":", "bool", ":" ]
train
https://github.com/nickw444/wtforms-webwidgets/blob/88f224b68c0b0f4f5c97de39fe1428b96e12f8db/wtforms_webwidgets/bootstrap/util.py#L69-L104
laysakura/relshell
relshell/base_shelloperator.py
BaseShellOperator._batches_to_tmpfile
def _batches_to_tmpfile(in_record_sep, in_column_sep, in_batches, batch_to_file_s): """Create files to store in-batches contents (if necessary)""" for i, b2f in enumerate(batch_to_file_s): if b2f.is_tmpfile(): input_str = BaseShellOperator._input_str(in_batches[i], in_record_...
python
def _batches_to_tmpfile(in_record_sep, in_column_sep, in_batches, batch_to_file_s): """Create files to store in-batches contents (if necessary)""" for i, b2f in enumerate(batch_to_file_s): if b2f.is_tmpfile(): input_str = BaseShellOperator._input_str(in_batches[i], in_record_...
[ "def", "_batches_to_tmpfile", "(", "in_record_sep", ",", "in_column_sep", ",", "in_batches", ",", "batch_to_file_s", ")", ":", "for", "i", ",", "b2f", "in", "enumerate", "(", "batch_to_file_s", ")", ":", "if", "b2f", ".", "is_tmpfile", "(", ")", ":", "input_...
Create files to store in-batches contents (if necessary)
[ "Create", "files", "to", "store", "in", "-", "batches", "contents", "(", "if", "necessary", ")" ]
train
https://github.com/laysakura/relshell/blob/9ca5c03a34c11cb763a4a75595f18bf4383aa8cc/relshell/base_shelloperator.py#L94-L99
laysakura/relshell
relshell/base_shelloperator.py
BaseShellOperator._batch_to_stdin
def _batch_to_stdin(process, in_record_sep, in_column_sep, in_batches, batch_to_file_s): """Write in-batch contents to `process` 's stdin (if necessary) """ for i, b2f in enumerate(batch_to_file_s): if b2f.is_stdin(): input_str = BaseShellOperator._input_str(in_batche...
python
def _batch_to_stdin(process, in_record_sep, in_column_sep, in_batches, batch_to_file_s): """Write in-batch contents to `process` 's stdin (if necessary) """ for i, b2f in enumerate(batch_to_file_s): if b2f.is_stdin(): input_str = BaseShellOperator._input_str(in_batche...
[ "def", "_batch_to_stdin", "(", "process", ",", "in_record_sep", ",", "in_column_sep", ",", "in_batches", ",", "batch_to_file_s", ")", ":", "for", "i", ",", "b2f", "in", "enumerate", "(", "batch_to_file_s", ")", ":", "if", "b2f", ".", "is_stdin", "(", ")", ...
Write in-batch contents to `process` 's stdin (if necessary)
[ "Write", "in", "-", "batch", "contents", "to", "process", "s", "stdin", "(", "if", "necessary", ")" ]
train
https://github.com/laysakura/relshell/blob/9ca5c03a34c11cb763a4a75595f18bf4383aa8cc/relshell/base_shelloperator.py#L102-L109
tBaxter/django-fretboard
fretboard/helpers.py
update_post_relations
def update_post_relations(user, topic, deleting=False): """ helper function to update user post count and parent topic post_count. """ if deleting: user.post_count = user.post_count - 1 else: user.post_count += 1 user.save(update_fields=['post_count']) topic.modified = d...
python
def update_post_relations(user, topic, deleting=False): """ helper function to update user post count and parent topic post_count. """ if deleting: user.post_count = user.post_count - 1 else: user.post_count += 1 user.save(update_fields=['post_count']) topic.modified = d...
[ "def", "update_post_relations", "(", "user", ",", "topic", ",", "deleting", "=", "False", ")", ":", "if", "deleting", ":", "user", ".", "post_count", "=", "user", ".", "post_count", "-", "1", "else", ":", "user", ".", "post_count", "+=", "1", "user", "...
helper function to update user post count and parent topic post_count.
[ "helper", "function", "to", "update", "user", "post", "count", "and", "parent", "topic", "post_count", "." ]
train
https://github.com/tBaxter/django-fretboard/blob/3c3f9557089821283f315a07f3e5a57a2725ab3b/fretboard/helpers.py#L5-L17
jmgilman/Neolib
neolib/pyamf/adapters/_django_db_models_base.py
getDjangoObjects
def getDjangoObjects(context): """ Returns a reference to the C{django_objects} on the context. If it doesn't exist then it is created. @rtype: Instance of L{DjangoReferenceCollection} @since: 0.5 """ c = context.extra k = 'django_objects' try: return c[k] except KeyErr...
python
def getDjangoObjects(context): """ Returns a reference to the C{django_objects} on the context. If it doesn't exist then it is created. @rtype: Instance of L{DjangoReferenceCollection} @since: 0.5 """ c = context.extra k = 'django_objects' try: return c[k] except KeyErr...
[ "def", "getDjangoObjects", "(", "context", ")", ":", "c", "=", "context", ".", "extra", "k", "=", "'django_objects'", "try", ":", "return", "c", "[", "k", "]", "except", "KeyError", ":", "c", "[", "k", "]", "=", "DjangoReferenceCollection", "(", ")", "...
Returns a reference to the C{django_objects} on the context. If it doesn't exist then it is created. @rtype: Instance of L{DjangoReferenceCollection} @since: 0.5
[ "Returns", "a", "reference", "to", "the", "C", "{", "django_objects", "}", "on", "the", "context", ".", "If", "it", "doesn", "t", "exist", "then", "it", "is", "created", "." ]
train
https://github.com/jmgilman/Neolib/blob/228fafeaed0f3195676137732384a14820ae285c/neolib/pyamf/adapters/_django_db_models_base.py#L225-L241
jmgilman/Neolib
neolib/pyamf/adapters/_django_db_models_base.py
writeDjangoObject
def writeDjangoObject(obj, encoder=None): """ The Django ORM creates new instances of objects for each db request. This is a problem for PyAMF as it uses the C{id(obj)} of the object to do reference checking. We could just ignore the problem, but the objects are conceptually the same so the eff...
python
def writeDjangoObject(obj, encoder=None): """ The Django ORM creates new instances of objects for each db request. This is a problem for PyAMF as it uses the C{id(obj)} of the object to do reference checking. We could just ignore the problem, but the objects are conceptually the same so the eff...
[ "def", "writeDjangoObject", "(", "obj", ",", "encoder", "=", "None", ")", ":", "s", "=", "obj", ".", "pk", "if", "s", "is", "None", ":", "encoder", ".", "writeObject", "(", "obj", ")", "return", "django_objects", "=", "getDjangoObjects", "(", "encoder", ...
The Django ORM creates new instances of objects for each db request. This is a problem for PyAMF as it uses the C{id(obj)} of the object to do reference checking. We could just ignore the problem, but the objects are conceptually the same so the effort should be made to attempt to resolve references fo...
[ "The", "Django", "ORM", "creates", "new", "instances", "of", "objects", "for", "each", "db", "request", ".", "This", "is", "a", "problem", "for", "PyAMF", "as", "it", "uses", "the", "C", "{", "id", "(", "obj", ")", "}", "of", "the", "object", "to", ...
train
https://github.com/jmgilman/Neolib/blob/228fafeaed0f3195676137732384a14820ae285c/neolib/pyamf/adapters/_django_db_models_base.py#L244-L276
jmgilman/Neolib
neolib/pyamf/adapters/_django_db_models_base.py
DjangoReferenceCollection.getClassKey
def getClassKey(self, klass, key): """ Return an instance based on klass/key. If an instance cannot be found then C{KeyError} is raised. @param klass: The class of the instance. @param key: The primary_key of the instance. @return: The instance linked to the C{klass}/C{...
python
def getClassKey(self, klass, key): """ Return an instance based on klass/key. If an instance cannot be found then C{KeyError} is raised. @param klass: The class of the instance. @param key: The primary_key of the instance. @return: The instance linked to the C{klass}/C{...
[ "def", "getClassKey", "(", "self", ",", "klass", ",", "key", ")", ":", "d", "=", "self", ".", "_getClass", "(", "klass", ")", "return", "d", "[", "key", "]" ]
Return an instance based on klass/key. If an instance cannot be found then C{KeyError} is raised. @param klass: The class of the instance. @param key: The primary_key of the instance. @return: The instance linked to the C{klass}/C{key}. @rtype: Instance of C{klass}.
[ "Return", "an", "instance", "based", "on", "klass", "/", "key", "." ]
train
https://github.com/jmgilman/Neolib/blob/228fafeaed0f3195676137732384a14820ae285c/neolib/pyamf/adapters/_django_db_models_base.py#L34-L47
jmgilman/Neolib
neolib/pyamf/adapters/_django_db_models_base.py
DjangoReferenceCollection.addClassKey
def addClassKey(self, klass, key, obj): """ Adds an object to the collection, based on klass and key. @param klass: The class of the object. @param key: The datastore key of the object. @param obj: The loaded instance from the datastore. """ d = self._getClass(kl...
python
def addClassKey(self, klass, key, obj): """ Adds an object to the collection, based on klass and key. @param klass: The class of the object. @param key: The datastore key of the object. @param obj: The loaded instance from the datastore. """ d = self._getClass(kl...
[ "def", "addClassKey", "(", "self", ",", "klass", ",", "key", ",", "obj", ")", ":", "d", "=", "self", ".", "_getClass", "(", "klass", ")", "d", "[", "key", "]", "=", "obj" ]
Adds an object to the collection, based on klass and key. @param klass: The class of the object. @param key: The datastore key of the object. @param obj: The loaded instance from the datastore.
[ "Adds", "an", "object", "to", "the", "collection", "based", "on", "klass", "and", "key", "." ]
train
https://github.com/jmgilman/Neolib/blob/228fafeaed0f3195676137732384a14820ae285c/neolib/pyamf/adapters/_django_db_models_base.py#L49-L59
OldhamMade/PySO8601
PySO8601/durations.py
parse_duration
def parse_duration(duration, start=None, end=None): """ Attepmt to parse an ISO8601 formatted duration. Accepts a ``duration`` and optionally a start or end ``datetime``. ``duration`` must be an ISO8601 formatted string. Returns a ``datetime.timedelta`` object. """ if not start and not end...
python
def parse_duration(duration, start=None, end=None): """ Attepmt to parse an ISO8601 formatted duration. Accepts a ``duration`` and optionally a start or end ``datetime``. ``duration`` must be an ISO8601 formatted string. Returns a ``datetime.timedelta`` object. """ if not start and not end...
[ "def", "parse_duration", "(", "duration", ",", "start", "=", "None", ",", "end", "=", "None", ")", ":", "if", "not", "start", "and", "not", "end", ":", "return", "parse_simple_duration", "(", "duration", ")", "if", "start", ":", "return", "parse_duration_w...
Attepmt to parse an ISO8601 formatted duration. Accepts a ``duration`` and optionally a start or end ``datetime``. ``duration`` must be an ISO8601 formatted string. Returns a ``datetime.timedelta`` object.
[ "Attepmt", "to", "parse", "an", "ISO8601", "formatted", "duration", "." ]
train
https://github.com/OldhamMade/PySO8601/blob/b7d3b3cb3ed3e12eb2a21caa26a3abeab3c96fe4/PySO8601/durations.py#L12-L28
OldhamMade/PySO8601
PySO8601/durations.py
parse_simple_duration
def parse_simple_duration(duration): """ Attepmt to parse an ISO8601 formatted duration, using a naive calculation. Accepts a ``duration`` which must be an ISO8601 formatted string, and assumes 365 days in a year and 30 days in a month for the calculation. Returns a ``datetime.timedelta`` object. ...
python
def parse_simple_duration(duration): """ Attepmt to parse an ISO8601 formatted duration, using a naive calculation. Accepts a ``duration`` which must be an ISO8601 formatted string, and assumes 365 days in a year and 30 days in a month for the calculation. Returns a ``datetime.timedelta`` object. ...
[ "def", "parse_simple_duration", "(", "duration", ")", ":", "elements", "=", "_parse_duration_string", "(", "_clean", "(", "duration", ")", ")", "if", "not", "elements", ":", "raise", "ParseError", "(", ")", "return", "_timedelta_from_elements", "(", "elements", ...
Attepmt to parse an ISO8601 formatted duration, using a naive calculation. Accepts a ``duration`` which must be an ISO8601 formatted string, and assumes 365 days in a year and 30 days in a month for the calculation. Returns a ``datetime.timedelta`` object.
[ "Attepmt", "to", "parse", "an", "ISO8601", "formatted", "duration", "using", "a", "naive", "calculation", "." ]
train
https://github.com/OldhamMade/PySO8601/blob/b7d3b3cb3ed3e12eb2a21caa26a3abeab3c96fe4/PySO8601/durations.py#L31-L45
OldhamMade/PySO8601
PySO8601/durations.py
parse_duration_with_start
def parse_duration_with_start(start, duration): """ Attepmt to parse an ISO8601 formatted duration based on a start datetime. Accepts a ``duration`` and a start ``datetime``. ``duration`` must be an ISO8601 formatted string. Returns a ``datetime.timedelta`` object. """ elements = _parse_du...
python
def parse_duration_with_start(start, duration): """ Attepmt to parse an ISO8601 formatted duration based on a start datetime. Accepts a ``duration`` and a start ``datetime``. ``duration`` must be an ISO8601 formatted string. Returns a ``datetime.timedelta`` object. """ elements = _parse_du...
[ "def", "parse_duration_with_start", "(", "start", ",", "duration", ")", ":", "elements", "=", "_parse_duration_string", "(", "_clean", "(", "duration", ")", ")", "year", ",", "month", "=", "_year_month_delta_from_elements", "(", "elements", ")", "end", "=", "sta...
Attepmt to parse an ISO8601 formatted duration based on a start datetime. Accepts a ``duration`` and a start ``datetime``. ``duration`` must be an ISO8601 formatted string. Returns a ``datetime.timedelta`` object.
[ "Attepmt", "to", "parse", "an", "ISO8601", "formatted", "duration", "based", "on", "a", "start", "datetime", "." ]
train
https://github.com/OldhamMade/PySO8601/blob/b7d3b3cb3ed3e12eb2a21caa26a3abeab3c96fe4/PySO8601/durations.py#L63-L85
wiggzz/siggy
siggy/siggy.py
int_to_var_bytes
def int_to_var_bytes(x): """Converts an integer to a bitcoin variable length integer as a bytearray :param x: the integer to convert """ if x < 253: return intbytes.to_bytes(x, 1) elif x < 65536: return bytearray([253]) + intbytes.to_bytes(x, 2)[::-1] elif x < 4294967296: ...
python
def int_to_var_bytes(x): """Converts an integer to a bitcoin variable length integer as a bytearray :param x: the integer to convert """ if x < 253: return intbytes.to_bytes(x, 1) elif x < 65536: return bytearray([253]) + intbytes.to_bytes(x, 2)[::-1] elif x < 4294967296: ...
[ "def", "int_to_var_bytes", "(", "x", ")", ":", "if", "x", "<", "253", ":", "return", "intbytes", ".", "to_bytes", "(", "x", ",", "1", ")", "elif", "x", "<", "65536", ":", "return", "bytearray", "(", "[", "253", "]", ")", "+", "intbytes", ".", "to...
Converts an integer to a bitcoin variable length integer as a bytearray :param x: the integer to convert
[ "Converts", "an", "integer", "to", "a", "bitcoin", "variable", "length", "integer", "as", "a", "bytearray" ]
train
https://github.com/wiggzz/siggy/blob/bfb67cbc9da3e4545b3e882bf7384fa265e6d6c1/siggy/siggy.py#L36-L48
wiggzz/siggy
siggy/siggy.py
bitcoin_sig_hash
def bitcoin_sig_hash(message): """Bitcoin has a special format for hashing messages for signing. :param message: the encoded message to hash in preparation for verifying """ padded = b'\x18Bitcoin Signed Message:\n' +\ int_to_var_bytes(len(message)) +\ message return double_sha256(p...
python
def bitcoin_sig_hash(message): """Bitcoin has a special format for hashing messages for signing. :param message: the encoded message to hash in preparation for verifying """ padded = b'\x18Bitcoin Signed Message:\n' +\ int_to_var_bytes(len(message)) +\ message return double_sha256(p...
[ "def", "bitcoin_sig_hash", "(", "message", ")", ":", "padded", "=", "b'\\x18Bitcoin Signed Message:\\n'", "+", "int_to_var_bytes", "(", "len", "(", "message", ")", ")", "+", "message", "return", "double_sha256", "(", "padded", ")" ]
Bitcoin has a special format for hashing messages for signing. :param message: the encoded message to hash in preparation for verifying
[ "Bitcoin", "has", "a", "special", "format", "for", "hashing", "messages", "for", "signing", "." ]
train
https://github.com/wiggzz/siggy/blob/bfb67cbc9da3e4545b3e882bf7384fa265e6d6c1/siggy/siggy.py#L51-L59
wiggzz/siggy
siggy/siggy.py
verify_signature
def verify_signature(message, signature, address): """This function verifies a bitcoin signed message. :param message: the plain text of the message to verify :param signature: the signature in base64 format :param address: the signing address """ if (len(signature) != SIGNATURE_LENGTH): ...
python
def verify_signature(message, signature, address): """This function verifies a bitcoin signed message. :param message: the plain text of the message to verify :param signature: the signature in base64 format :param address: the signing address """ if (len(signature) != SIGNATURE_LENGTH): ...
[ "def", "verify_signature", "(", "message", ",", "signature", ",", "address", ")", ":", "if", "(", "len", "(", "signature", ")", "!=", "SIGNATURE_LENGTH", ")", ":", "return", "False", "try", ":", "binsig", "=", "base64", ".", "b64decode", "(", "signature", ...
This function verifies a bitcoin signed message. :param message: the plain text of the message to verify :param signature: the signature in base64 format :param address: the signing address
[ "This", "function", "verifies", "a", "bitcoin", "signed", "message", "." ]
train
https://github.com/wiggzz/siggy/blob/bfb67cbc9da3e4545b3e882bf7384fa265e6d6c1/siggy/siggy.py#L62-L96
boilerroomtv/datastore.cloudfiles
datastore/cloudfiles/__init__.py
CloudFilesDatastore.query
def query(self, query): """Returns an iterable of objects matching criteria expressed in `query`. Implementations of query will be the largest differentiating factor amongst datastores. All datastores **must** implement query, even using query's worst case scenario, see :ref:class:`Quer...
python
def query(self, query): """Returns an iterable of objects matching criteria expressed in `query`. Implementations of query will be the largest differentiating factor amongst datastores. All datastores **must** implement query, even using query's worst case scenario, see :ref:class:`Quer...
[ "def", "query", "(", "self", ",", "query", ")", ":", "return", "query", "(", "(", "self", ".", "_deserialised_value", "(", "x", ")", "for", "x", "in", "self", ".", "container", ".", "get_objects", "(", "prefix", "=", "query", ".", "key", ")", ")", ...
Returns an iterable of objects matching criteria expressed in `query`. Implementations of query will be the largest differentiating factor amongst datastores. All datastores **must** implement query, even using query's worst case scenario, see :ref:class:`Query` for details. :param que...
[ "Returns", "an", "iterable", "of", "objects", "matching", "criteria", "expressed", "in", "query", "." ]
train
https://github.com/boilerroomtv/datastore.cloudfiles/blob/95e430c72078cfeaa4c640cae38315fb551128fa/datastore/cloudfiles/__init__.py#L80-L90
dstufft/crust
crust/resources.py
Resource.save
def save(self, force_insert=False, force_update=False): """ Saves the current instance. Override this in a subclass if you want to control the saving process. The 'force_insert' and 'force_update' parameters can be used to insist that the "save" must be a POST or PUT respectivel...
python
def save(self, force_insert=False, force_update=False): """ Saves the current instance. Override this in a subclass if you want to control the saving process. The 'force_insert' and 'force_update' parameters can be used to insist that the "save" must be a POST or PUT respectivel...
[ "def", "save", "(", "self", ",", "force_insert", "=", "False", ",", "force_update", "=", "False", ")", ":", "if", "force_insert", "and", "force_update", ":", "raise", "ValueError", "(", "\"Cannot force both insert and updating in resource saving.\"", ")", "data", "=...
Saves the current instance. Override this in a subclass if you want to control the saving process. The 'force_insert' and 'force_update' parameters can be used to insist that the "save" must be a POST or PUT respectively. Normally, they should not be set.
[ "Saves", "the", "current", "instance", ".", "Override", "this", "in", "a", "subclass", "if", "you", "want", "to", "control", "the", "saving", "process", "." ]
train
https://github.com/dstufft/crust/blob/5d4011ecace12fd3f68a03a17dbefb78390a9fc0/crust/resources.py#L129-L164
dstufft/crust
crust/resources.py
Resource.delete
def delete(self): """ Deletes the current instance. Override this in a subclass if you want to control the deleting process. """ if self.resource_uri is None: raise ValueError("{0} object cannot be deleted because resource_uri attribute cannot be None".format(self._me...
python
def delete(self): """ Deletes the current instance. Override this in a subclass if you want to control the deleting process. """ if self.resource_uri is None: raise ValueError("{0} object cannot be deleted because resource_uri attribute cannot be None".format(self._me...
[ "def", "delete", "(", "self", ")", ":", "if", "self", ".", "resource_uri", "is", "None", ":", "raise", "ValueError", "(", "\"{0} object cannot be deleted because resource_uri attribute cannot be None\"", ".", "format", "(", "self", ".", "_meta", ".", "resource_name", ...
Deletes the current instance. Override this in a subclass if you want to control the deleting process.
[ "Deletes", "the", "current", "instance", ".", "Override", "this", "in", "a", "subclass", "if", "you", "want", "to", "control", "the", "deleting", "process", "." ]
train
https://github.com/dstufft/crust/blob/5d4011ecace12fd3f68a03a17dbefb78390a9fc0/crust/resources.py#L166-L174
eallik/spinoff
spinoff/actor/cell.py
_BaseCell.spawn_actor
def spawn_actor(self, factory, name=None): """Spawns an actor using the given `factory` with the specified `name`. Returns an immediately usable `Ref` to the newly created actor, regardless of the location of the new actor, or when the actual spawning will take place. """ if nam...
python
def spawn_actor(self, factory, name=None): """Spawns an actor using the given `factory` with the specified `name`. Returns an immediately usable `Ref` to the newly created actor, regardless of the location of the new actor, or when the actual spawning will take place. """ if nam...
[ "def", "spawn_actor", "(", "self", ",", "factory", ",", "name", "=", "None", ")", ":", "if", "name", "and", "'/'", "in", "name", ":", "# pragma: no cover", "raise", "TypeError", "(", "\"Actor names cannot contain slashes\"", ")", "if", "not", "self", ".", "_...
Spawns an actor using the given `factory` with the specified `name`. Returns an immediately usable `Ref` to the newly created actor, regardless of the location of the new actor, or when the actual spawning will take place.
[ "Spawns", "an", "actor", "using", "the", "given", "factory", "with", "the", "specified", "name", "." ]
train
https://github.com/eallik/spinoff/blob/06b00d6b86c7422c9cb8f9a4b2915906e92b7d52/spinoff/actor/cell.py#L48-L69
eallik/spinoff
spinoff/actor/cell.py
_BaseCell.lookup_cell
def lookup_cell(self, uri): """Looks up a local actor by its location relative to this actor.""" steps = uri.steps if steps[0] == '': found = self.root steps.popleft() else: found = self for step in steps: assert step != '' ...
python
def lookup_cell(self, uri): """Looks up a local actor by its location relative to this actor.""" steps = uri.steps if steps[0] == '': found = self.root steps.popleft() else: found = self for step in steps: assert step != '' ...
[ "def", "lookup_cell", "(", "self", ",", "uri", ")", ":", "steps", "=", "uri", ".", "steps", "if", "steps", "[", "0", "]", "==", "''", ":", "found", "=", "self", ".", "root", "steps", ".", "popleft", "(", ")", "else", ":", "found", "=", "self", ...
Looks up a local actor by its location relative to this actor.
[ "Looks", "up", "a", "local", "actor", "by", "its", "location", "relative", "to", "this", "actor", "." ]
train
https://github.com/eallik/spinoff/blob/06b00d6b86c7422c9cb8f9a4b2915906e92b7d52/spinoff/actor/cell.py#L94-L108
amadev/doan
doan/dataset.py
r_num
def r_num(obj): """Read list of numbers.""" if isinstance(obj, (list, tuple)): it = iter else: it = LinesIterator dataset = Dataset([Dataset.FLOAT]) return dataset.load(it(obj))
python
def r_num(obj): """Read list of numbers.""" if isinstance(obj, (list, tuple)): it = iter else: it = LinesIterator dataset = Dataset([Dataset.FLOAT]) return dataset.load(it(obj))
[ "def", "r_num", "(", "obj", ")", ":", "if", "isinstance", "(", "obj", ",", "(", "list", ",", "tuple", ")", ")", ":", "it", "=", "iter", "else", ":", "it", "=", "LinesIterator", "dataset", "=", "Dataset", "(", "[", "Dataset", ".", "FLOAT", "]", ")...
Read list of numbers.
[ "Read", "list", "of", "numbers", "." ]
train
https://github.com/amadev/doan/blob/5adfa983ac547007a688fe7517291a432919aa3e/doan/dataset.py#L150-L157
amadev/doan
doan/dataset.py
r_date_num
def r_date_num(obj, multiple=False): """Read date-value table.""" if isinstance(obj, (list, tuple)): it = iter else: it = LinesIterator if multiple: datasets = {} for line in it(obj): label = line[2] if label not in datasets: datase...
python
def r_date_num(obj, multiple=False): """Read date-value table.""" if isinstance(obj, (list, tuple)): it = iter else: it = LinesIterator if multiple: datasets = {} for line in it(obj): label = line[2] if label not in datasets: datase...
[ "def", "r_date_num", "(", "obj", ",", "multiple", "=", "False", ")", ":", "if", "isinstance", "(", "obj", ",", "(", "list", ",", "tuple", ")", ")", ":", "it", "=", "iter", "else", ":", "it", "=", "LinesIterator", "if", "multiple", ":", "datasets", ...
Read date-value table.
[ "Read", "date", "-", "value", "table", "." ]
train
https://github.com/amadev/doan/blob/5adfa983ac547007a688fe7517291a432919aa3e/doan/dataset.py#L160-L176
sysr-q/rcmd.py
rcmd/parser.py
Regex.command
def command(self, rule, **options): """\ direct=False, override=True, inject=False, flags=0 """ options.setdefault("direct", False) options.setdefault("override", True) options.setdefault("inject", False) options.setdefault("flags", 0) if not options["dire...
python
def command(self, rule, **options): """\ direct=False, override=True, inject=False, flags=0 """ options.setdefault("direct", False) options.setdefault("override", True) options.setdefault("inject", False) options.setdefault("flags", 0) if not options["dire...
[ "def", "command", "(", "self", ",", "rule", ",", "*", "*", "options", ")", ":", "options", ".", "setdefault", "(", "\"direct\"", ",", "False", ")", "options", ".", "setdefault", "(", "\"override\"", ",", "True", ")", "options", ".", "setdefault", "(", ...
\ direct=False, override=True, inject=False, flags=0
[ "\\", "direct", "=", "False", "override", "=", "True", "inject", "=", "False", "flags", "=", "0" ]
train
https://github.com/sysr-q/rcmd.py/blob/0ecce1970164805cedb33d02a9dcf9eb6cd14e0c/rcmd/parser.py#L49-L72
sysr-q/rcmd.py
rcmd/parser.py
Regex.best_guess
def best_guess(self, line, args=None, kwargs=None, multiple=True, **options): """\ Given multiple=False, this will simply return the first matching regexes first handler; otherwise, this will return a list of all the matching handler function(s). If rank_best was set on the pars...
python
def best_guess(self, line, args=None, kwargs=None, multiple=True, **options): """\ Given multiple=False, this will simply return the first matching regexes first handler; otherwise, this will return a list of all the matching handler function(s). If rank_best was set on the pars...
[ "def", "best_guess", "(", "self", ",", "line", ",", "args", "=", "None", ",", "kwargs", "=", "None", ",", "multiple", "=", "True", ",", "*", "*", "options", ")", ":", "cmd", ",", "_args", ",", "_kwargs", "=", "self", ".", "parse", "(", "line", ")...
\ Given multiple=False, this will simply return the first matching regexes first handler; otherwise, this will return a list of all the matching handler function(s). If rank_best was set on the parser, this will attempt to "rank" the regexes, and will return the highest ranked h...
[ "\\", "Given", "multiple", "=", "False", "this", "will", "simply", "return", "the", "first", "matching", "regexes", "first", "handler", ";", "otherwise", "this", "will", "return", "a", "list", "of", "all", "the", "matching", "handler", "function", "(", "s", ...
train
https://github.com/sysr-q/rcmd.py/blob/0ecce1970164805cedb33d02a9dcf9eb6cd14e0c/rcmd/parser.py#L74-L103
sysr-q/rcmd.py
rcmd/parser.py
Regex.parse
def parse(self, line, **options): """\ Parse a line and return (cmd, args, kwargs) - cmd may be False if it wasn't parseable. Relatively simple in the Regex parser - anything can be "parsed", but is not guaranteed to match. """ line = line.strip() if not ...
python
def parse(self, line, **options): """\ Parse a line and return (cmd, args, kwargs) - cmd may be False if it wasn't parseable. Relatively simple in the Regex parser - anything can be "parsed", but is not guaranteed to match. """ line = line.strip() if not ...
[ "def", "parse", "(", "self", ",", "line", ",", "*", "*", "options", ")", ":", "line", "=", "line", ".", "strip", "(", ")", "if", "not", "line", ":", "return", "(", "False", ",", "(", ")", ",", "{", "}", ")", "split", "=", "line", ".", "split"...
\ Parse a line and return (cmd, args, kwargs) - cmd may be False if it wasn't parseable. Relatively simple in the Regex parser - anything can be "parsed", but is not guaranteed to match.
[ "\\", "Parse", "a", "line", "and", "return", "(", "cmd", "args", "kwargs", ")", "-", "cmd", "may", "be", "False", "if", "it", "wasn", "t", "parseable", "." ]
train
https://github.com/sysr-q/rcmd.py/blob/0ecce1970164805cedb33d02a9dcf9eb6cd14e0c/rcmd/parser.py#L113-L126
apiwatcher/apiwatcher-pyclient
apiwatcher_pyclient/client.py
Client.authorize_client_credentials
def authorize_client_credentials( self, client_id, client_secret=None, scope="private_agent" ): """Authorize to platform with client credentials This should be used if you posses client_id/client_secret pair generated by platform. """ self.auth_data = { "...
python
def authorize_client_credentials( self, client_id, client_secret=None, scope="private_agent" ): """Authorize to platform with client credentials This should be used if you posses client_id/client_secret pair generated by platform. """ self.auth_data = { "...
[ "def", "authorize_client_credentials", "(", "self", ",", "client_id", ",", "client_secret", "=", "None", ",", "scope", "=", "\"private_agent\"", ")", ":", "self", ".", "auth_data", "=", "{", "\"grant_type\"", ":", "\"client_credentials\"", ",", "\"scope\"", ":", ...
Authorize to platform with client credentials This should be used if you posses client_id/client_secret pair generated by platform.
[ "Authorize", "to", "platform", "with", "client", "credentials" ]
train
https://github.com/apiwatcher/apiwatcher-pyclient/blob/54b5e659be11447d7bb4a05d182ce772ce74b2dc/apiwatcher_pyclient/client.py#L37-L52
apiwatcher/apiwatcher-pyclient
apiwatcher_pyclient/client.py
Client.authorize_password
def authorize_password(self, client_id, username, password): """Authorize to platform as regular user You must provide a valid client_id (same as web application), your password and your username. Username and password is not stored in client but refresh token is stored. The only valid ...
python
def authorize_password(self, client_id, username, password): """Authorize to platform as regular user You must provide a valid client_id (same as web application), your password and your username. Username and password is not stored in client but refresh token is stored. The only valid ...
[ "def", "authorize_password", "(", "self", ",", "client_id", ",", "username", ",", "password", ")", ":", "self", ".", "auth_data", "=", "{", "\"grant_type\"", ":", "\"password\"", ",", "\"username\"", ":", "username", ",", "\"password\"", ":", "password", ",", ...
Authorize to platform as regular user You must provide a valid client_id (same as web application), your password and your username. Username and password is not stored in client but refresh token is stored. The only valid scope for this authorization is "regular_user". :param ...
[ "Authorize", "to", "platform", "as", "regular", "user" ]
train
https://github.com/apiwatcher/apiwatcher-pyclient/blob/54b5e659be11447d7bb4a05d182ce772ce74b2dc/apiwatcher_pyclient/client.py#L54-L78
apiwatcher/apiwatcher-pyclient
apiwatcher_pyclient/client.py
Client._do_authorize
def _do_authorize(self): """ Perform the authorization """ if self.auth_data is None: raise ApiwatcherClientException("You must provide authorization data.") r = requests.post( "{0}/api/token".format(self.base_url), json=self.auth_data, verify=self.ve...
python
def _do_authorize(self): """ Perform the authorization """ if self.auth_data is None: raise ApiwatcherClientException("You must provide authorization data.") r = requests.post( "{0}/api/token".format(self.base_url), json=self.auth_data, verify=self.ve...
[ "def", "_do_authorize", "(", "self", ")", ":", "if", "self", ".", "auth_data", "is", "None", ":", "raise", "ApiwatcherClientException", "(", "\"You must provide authorization data.\"", ")", "r", "=", "requests", ".", "post", "(", "\"{0}/api/token\"", ".", "format"...
Perform the authorization
[ "Perform", "the", "authorization" ]
train
https://github.com/apiwatcher/apiwatcher-pyclient/blob/54b5e659be11447d7bb4a05d182ce772ce74b2dc/apiwatcher_pyclient/client.py#L80-L113
apiwatcher/apiwatcher-pyclient
apiwatcher_pyclient/client.py
Client._do_request
def _do_request(self, method, endpoint, data=None): """Perform one request, possibly solving unauthorized return code """ # No token - authorize if self.token is None: self._do_authorize() r = requests.request( method, "{0}{1}".format(self.bas...
python
def _do_request(self, method, endpoint, data=None): """Perform one request, possibly solving unauthorized return code """ # No token - authorize if self.token is None: self._do_authorize() r = requests.request( method, "{0}{1}".format(self.bas...
[ "def", "_do_request", "(", "self", ",", "method", ",", "endpoint", ",", "data", "=", "None", ")", ":", "# No token - authorize", "if", "self", ".", "token", "is", "None", ":", "self", ".", "_do_authorize", "(", ")", "r", "=", "requests", ".", "request", ...
Perform one request, possibly solving unauthorized return code
[ "Perform", "one", "request", "possibly", "solving", "unauthorized", "return", "code" ]
train
https://github.com/apiwatcher/apiwatcher-pyclient/blob/54b5e659be11447d7bb4a05d182ce772ce74b2dc/apiwatcher_pyclient/client.py#L115-L148
oubiga/respect
respect/spelling.py
spellchecker
def spellchecker(word): """ Looks for possible typos, i.e., deletion, insertion, transposition and alteration. If the target is 'audreyr': deletion is 'adreyr', insertion is 'audreeyr', transposition is 'aurdeyr' and alteration is 'audriyr'. Returns a list of possible words sorted by matching the s...
python
def spellchecker(word): """ Looks for possible typos, i.e., deletion, insertion, transposition and alteration. If the target is 'audreyr': deletion is 'adreyr', insertion is 'audreeyr', transposition is 'aurdeyr' and alteration is 'audriyr'. Returns a list of possible words sorted by matching the s...
[ "def", "spellchecker", "(", "word", ")", ":", "splits", "=", "[", "(", "word", "[", ":", "i", "]", ",", "word", "[", "i", ":", "]", ")", "for", "i", "in", "range", "(", "len", "(", "word", ")", "+", "1", ")", "]", "deletes", "=", "[", "a", ...
Looks for possible typos, i.e., deletion, insertion, transposition and alteration. If the target is 'audreyr': deletion is 'adreyr', insertion is 'audreeyr', transposition is 'aurdeyr' and alteration is 'audriyr'. Returns a list of possible words sorted by matching the same length.
[ "Looks", "for", "possible", "typos", "i", ".", "e", ".", "deletion", "insertion", "transposition", "and", "alteration", ".", "If", "the", "target", "is", "audreyr", ":", "deletion", "is", "adreyr", "insertion", "is", "audreeyr", "transposition", "is", "aurdeyr...
train
https://github.com/oubiga/respect/blob/550554ec4d3139379d03cb8f82a8cd2d80c3ad62/respect/spelling.py#L15-L31
dustinmm80/healthy
checks.py
check_license
def check_license(package_info, *args): """ Does the package have a license classifier? :param package_info: package_info dictionary :return: Tuple (is the condition True or False?, reason if it is False else None, score to be applied) """ classifiers = package_info.get('classifiers') reason...
python
def check_license(package_info, *args): """ Does the package have a license classifier? :param package_info: package_info dictionary :return: Tuple (is the condition True or False?, reason if it is False else None, score to be applied) """ classifiers = package_info.get('classifiers') reason...
[ "def", "check_license", "(", "package_info", ",", "*", "args", ")", ":", "classifiers", "=", "package_info", ".", "get", "(", "'classifiers'", ")", "reason", "=", "\"No License\"", "result", "=", "False", "if", "len", "(", "[", "c", "for", "c", "in", "cl...
Does the package have a license classifier? :param package_info: package_info dictionary :return: Tuple (is the condition True or False?, reason if it is False else None, score to be applied)
[ "Does", "the", "package", "have", "a", "license", "classifier?", ":", "param", "package_info", ":", "package_info", "dictionary", ":", "return", ":", "Tuple", "(", "is", "the", "condition", "True", "or", "False?", "reason", "if", "it", "is", "False", "else",...
train
https://github.com/dustinmm80/healthy/blob/b59016c3f578ca45b6ce857a2d5c4584b8542288/checks.py#L33-L46
dustinmm80/healthy
checks.py
check_homepage
def check_homepage(package_info, *args): """ Does the package have a homepage listed? :param package_info: package_info dictionary :return: Tuple (is the condition True or False?, reason if it is False else None) """ reason = "Home page missing" result = False if package_info.get('home_...
python
def check_homepage(package_info, *args): """ Does the package have a homepage listed? :param package_info: package_info dictionary :return: Tuple (is the condition True or False?, reason if it is False else None) """ reason = "Home page missing" result = False if package_info.get('home_...
[ "def", "check_homepage", "(", "package_info", ",", "*", "args", ")", ":", "reason", "=", "\"Home page missing\"", "result", "=", "False", "if", "package_info", ".", "get", "(", "'home_page'", ")", "not", "in", "BAD_VALUES", ":", "result", "=", "True", "retur...
Does the package have a homepage listed? :param package_info: package_info dictionary :return: Tuple (is the condition True or False?, reason if it is False else None)
[ "Does", "the", "package", "have", "a", "homepage", "listed?", ":", "param", "package_info", ":", "package_info", "dictionary", ":", "return", ":", "Tuple", "(", "is", "the", "condition", "True", "or", "False?", "reason", "if", "it", "is", "False", "else", ...
train
https://github.com/dustinmm80/healthy/blob/b59016c3f578ca45b6ce857a2d5c4584b8542288/checks.py#L49-L61
dustinmm80/healthy
checks.py
check_summary
def check_summary(package_info, *args): """ Does the package have a summary listed? :param package_info: package_info dictionary :return: Tuple (is the condition True or False?, reason if it is False else None) """ reason = "Summary missing" result = False if package_info.get('summary')...
python
def check_summary(package_info, *args): """ Does the package have a summary listed? :param package_info: package_info dictionary :return: Tuple (is the condition True or False?, reason if it is False else None) """ reason = "Summary missing" result = False if package_info.get('summary')...
[ "def", "check_summary", "(", "package_info", ",", "*", "args", ")", ":", "reason", "=", "\"Summary missing\"", "result", "=", "False", "if", "package_info", ".", "get", "(", "'summary'", ")", "not", "in", "BAD_VALUES", ":", "result", "=", "True", "return", ...
Does the package have a summary listed? :param package_info: package_info dictionary :return: Tuple (is the condition True or False?, reason if it is False else None)
[ "Does", "the", "package", "have", "a", "summary", "listed?", ":", "param", "package_info", ":", "package_info", "dictionary", ":", "return", ":", "Tuple", "(", "is", "the", "condition", "True", "or", "False?", "reason", "if", "it", "is", "False", "else", "...
train
https://github.com/dustinmm80/healthy/blob/b59016c3f578ca45b6ce857a2d5c4584b8542288/checks.py#L64-L76
dustinmm80/healthy
checks.py
check_description
def check_description(package_info, *args): """ Does the package have a description listed? :param package_info: package_info dictionary :return: Tuple (is the condition True or False?, reason if it is False else None) """ reason = "Description missing" result = False if package_info.ge...
python
def check_description(package_info, *args): """ Does the package have a description listed? :param package_info: package_info dictionary :return: Tuple (is the condition True or False?, reason if it is False else None) """ reason = "Description missing" result = False if package_info.ge...
[ "def", "check_description", "(", "package_info", ",", "*", "args", ")", ":", "reason", "=", "\"Description missing\"", "result", "=", "False", "if", "package_info", ".", "get", "(", "'description'", ")", "not", "in", "BAD_VALUES", ":", "result", "=", "True", ...
Does the package have a description listed? :param package_info: package_info dictionary :return: Tuple (is the condition True or False?, reason if it is False else None)
[ "Does", "the", "package", "have", "a", "description", "listed?", ":", "param", "package_info", ":", "package_info", "dictionary", ":", "return", ":", "Tuple", "(", "is", "the", "condition", "True", "or", "False?", "reason", "if", "it", "is", "False", "else",...
train
https://github.com/dustinmm80/healthy/blob/b59016c3f578ca45b6ce857a2d5c4584b8542288/checks.py#L79-L91
dustinmm80/healthy
checks.py
check_python_classifiers
def check_python_classifiers(package_info, *args): """ Does the package have Python classifiers? :param package_info: package_info dictionary :return: Tuple (is the condition True or False?, reason if it is False else None, score to be applied) """ classifiers = package_info.get('classifiers') ...
python
def check_python_classifiers(package_info, *args): """ Does the package have Python classifiers? :param package_info: package_info dictionary :return: Tuple (is the condition True or False?, reason if it is False else None, score to be applied) """ classifiers = package_info.get('classifiers') ...
[ "def", "check_python_classifiers", "(", "package_info", ",", "*", "args", ")", ":", "classifiers", "=", "package_info", ".", "get", "(", "'classifiers'", ")", "reason", "=", "\"Python classifiers missing\"", "result", "=", "False", "if", "len", "(", "[", "c", ...
Does the package have Python classifiers? :param package_info: package_info dictionary :return: Tuple (is the condition True or False?, reason if it is False else None, score to be applied)
[ "Does", "the", "package", "have", "Python", "classifiers?", ":", "param", "package_info", ":", "package_info", "dictionary", ":", "return", ":", "Tuple", "(", "is", "the", "condition", "True", "or", "False?", "reason", "if", "it", "is", "False", "else", "Non...
train
https://github.com/dustinmm80/healthy/blob/b59016c3f578ca45b6ce857a2d5c4584b8542288/checks.py#L94-L107
dustinmm80/healthy
checks.py
check_author_info
def check_author_info(package_info, *args): """ Does the package have author information listed? :param package_info: package_info dictionary :return: Tuple (is the condition True or False?, reason if it is False else None) """ reason = "Author name or email missing" result = False if p...
python
def check_author_info(package_info, *args): """ Does the package have author information listed? :param package_info: package_info dictionary :return: Tuple (is the condition True or False?, reason if it is False else None) """ reason = "Author name or email missing" result = False if p...
[ "def", "check_author_info", "(", "package_info", ",", "*", "args", ")", ":", "reason", "=", "\"Author name or email missing\"", "result", "=", "False", "if", "package_info", ".", "get", "(", "'author'", ")", "not", "in", "BAD_VALUES", "or", "package_info", ".", ...
Does the package have author information listed? :param package_info: package_info dictionary :return: Tuple (is the condition True or False?, reason if it is False else None)
[ "Does", "the", "package", "have", "author", "information", "listed?", ":", "param", "package_info", ":", "package_info", "dictionary", ":", "return", ":", "Tuple", "(", "is", "the", "condition", "True", "or", "False?", "reason", "if", "it", "is", "False", "e...
train
https://github.com/dustinmm80/healthy/blob/b59016c3f578ca45b6ce857a2d5c4584b8542288/checks.py#L110-L122
dustinmm80/healthy
checks.py
check_release_files
def check_release_files(package_info, *args): """ Does the package have release files? :param package_info: package_info dictionary :return: Tuple (is the condition True or False?, reason if it is False else None) """ reason = "No release files uploaded" result = False release_urls = ar...
python
def check_release_files(package_info, *args): """ Does the package have release files? :param package_info: package_info dictionary :return: Tuple (is the condition True or False?, reason if it is False else None) """ reason = "No release files uploaded" result = False release_urls = ar...
[ "def", "check_release_files", "(", "package_info", ",", "*", "args", ")", ":", "reason", "=", "\"No release files uploaded\"", "result", "=", "False", "release_urls", "=", "args", "[", "0", "]", "if", "len", "(", "release_urls", ")", ">", "0", ":", "result",...
Does the package have release files? :param package_info: package_info dictionary :return: Tuple (is the condition True or False?, reason if it is False else None)
[ "Does", "the", "package", "have", "release", "files?", ":", "param", "package_info", ":", "package_info", "dictionary", ":", "return", ":", "Tuple", "(", "is", "the", "condition", "True", "or", "False?", "reason", "if", "it", "is", "False", "else", "None", ...
train
https://github.com/dustinmm80/healthy/blob/b59016c3f578ca45b6ce857a2d5c4584b8542288/checks.py#L125-L138
dustinmm80/healthy
checks.py
check_stale
def check_stale(package_info, *args): """ Is the package stale? :param package_info: package_info dictionary :return: Tuple (is the condition True or False?, reason if it is False else None) """ reason = 'Package not updated in {} days'.format(DAYS_STALE) result = False now = datetime.u...
python
def check_stale(package_info, *args): """ Is the package stale? :param package_info: package_info dictionary :return: Tuple (is the condition True or False?, reason if it is False else None) """ reason = 'Package not updated in {} days'.format(DAYS_STALE) result = False now = datetime.u...
[ "def", "check_stale", "(", "package_info", ",", "*", "args", ")", ":", "reason", "=", "'Package not updated in {} days'", ".", "format", "(", "DAYS_STALE", ")", "result", "=", "False", "now", "=", "datetime", ".", "utcnow", "(", ")", "release_urls", "=", "ar...
Is the package stale? :param package_info: package_info dictionary :return: Tuple (is the condition True or False?, reason if it is False else None)
[ "Is", "the", "package", "stale?", ":", "param", "package_info", ":", "package_info", "dictionary", ":", "return", ":", "Tuple", "(", "is", "the", "condition", "True", "or", "False?", "reason", "if", "it", "is", "False", "else", "None", ")" ]
train
https://github.com/dustinmm80/healthy/blob/b59016c3f578ca45b6ce857a2d5c4584b8542288/checks.py#L141-L158
veltzer/pypitools
pypitools/scripts/upload.py
main
def main(): """ upload a package to pypi or gemfury :return: """ setup_main() config = ConfigData(clean=True) try: config.upload() finally: config.clean_after_if_needed()
python
def main(): """ upload a package to pypi or gemfury :return: """ setup_main() config = ConfigData(clean=True) try: config.upload() finally: config.clean_after_if_needed()
[ "def", "main", "(", ")", ":", "setup_main", "(", ")", "config", "=", "ConfigData", "(", "clean", "=", "True", ")", "try", ":", "config", ".", "upload", "(", ")", "finally", ":", "config", ".", "clean_after_if_needed", "(", ")" ]
upload a package to pypi or gemfury :return:
[ "upload", "a", "package", "to", "pypi", "or", "gemfury", ":", "return", ":" ]
train
https://github.com/veltzer/pypitools/blob/5f097be21e9bc65578eed5b6b7855c1945540701/pypitools/scripts/upload.py#L32-L42
shrubberysoft/homophony
src/homophony/__init__.py
DocFileSuite
def DocFileSuite(*paths, **kwargs): """Extension of the standard DocFileSuite that sets up test browser for use in doctests.""" kwargs.setdefault('setUp', setUpBrowser) kwargs.setdefault('tearDown', tearDownBrowser) kwargs.setdefault('globs', {}).update(Browser=Browser) kwargs.setdefault('option...
python
def DocFileSuite(*paths, **kwargs): """Extension of the standard DocFileSuite that sets up test browser for use in doctests.""" kwargs.setdefault('setUp', setUpBrowser) kwargs.setdefault('tearDown', tearDownBrowser) kwargs.setdefault('globs', {}).update(Browser=Browser) kwargs.setdefault('option...
[ "def", "DocFileSuite", "(", "*", "paths", ",", "*", "*", "kwargs", ")", ":", "kwargs", ".", "setdefault", "(", "'setUp'", ",", "setUpBrowser", ")", "kwargs", ".", "setdefault", "(", "'tearDown'", ",", "tearDownBrowser", ")", "kwargs", ".", "setdefault", "(...
Extension of the standard DocFileSuite that sets up test browser for use in doctests.
[ "Extension", "of", "the", "standard", "DocFileSuite", "that", "sets", "up", "test", "browser", "for", "use", "in", "doctests", "." ]
train
https://github.com/shrubberysoft/homophony/blob/5549371fd6c6fd73b69b3e9b5002d61cf42997f3/src/homophony/__init__.py#L117-L130
shrubberysoft/homophony
src/homophony/__init__.py
Browser.queryHTML
def queryHTML(self, path): """Run an XPath query on the HTML document and print matches.""" if etree is None: raise Exception("lxml not available") document = etree.HTML(self.contents) for node in document.xpath(path): if isinstance(node, basestring): ...
python
def queryHTML(self, path): """Run an XPath query on the HTML document and print matches.""" if etree is None: raise Exception("lxml not available") document = etree.HTML(self.contents) for node in document.xpath(path): if isinstance(node, basestring): ...
[ "def", "queryHTML", "(", "self", ",", "path", ")", ":", "if", "etree", "is", "None", ":", "raise", "Exception", "(", "\"lxml not available\"", ")", "document", "=", "etree", ".", "HTML", "(", "self", ".", "contents", ")", "for", "node", "in", "document",...
Run an XPath query on the HTML document and print matches.
[ "Run", "an", "XPath", "query", "on", "the", "HTML", "document", "and", "print", "matches", "." ]
train
https://github.com/shrubberysoft/homophony/blob/5549371fd6c6fd73b69b3e9b5002d61cf42997f3/src/homophony/__init__.py#L80-L89
veltzer/pypitools
config/helpers.py
array_indented
def array_indented(level: int, l: List[str], quote_char='\'', comma_after=False) -> str: """ return an array indented according to indent level :param level: :param l: :param quote_char: :param comma_after: :return: """ out = "[\n" for x in l: out += (((level+1) * 4) * " ...
python
def array_indented(level: int, l: List[str], quote_char='\'', comma_after=False) -> str: """ return an array indented according to indent level :param level: :param l: :param quote_char: :param comma_after: :return: """ out = "[\n" for x in l: out += (((level+1) * 4) * " ...
[ "def", "array_indented", "(", "level", ":", "int", ",", "l", ":", "List", "[", "str", "]", ",", "quote_char", "=", "'\\''", ",", "comma_after", "=", "False", ")", "->", "str", ":", "out", "=", "\"[\\n\"", "for", "x", "in", "l", ":", "out", "+=", ...
return an array indented according to indent level :param level: :param l: :param quote_char: :param comma_after: :return:
[ "return", "an", "array", "indented", "according", "to", "indent", "level", ":", "param", "level", ":", ":", "param", "l", ":", ":", "param", "quote_char", ":", ":", "param", "comma_after", ":", ":", "return", ":" ]
train
https://github.com/veltzer/pypitools/blob/5f097be21e9bc65578eed5b6b7855c1945540701/config/helpers.py#L6-L21
veltzer/pypitools
config/helpers.py
find_packages
def find_packages(path: str) -> List[str]: """ A better version of find_packages than what setuptools offers :param path: :return: """ for root, _dir, files in os.walk(path): if '__init__.py' in files: yield root.replace("/", ".")
python
def find_packages(path: str) -> List[str]: """ A better version of find_packages than what setuptools offers :param path: :return: """ for root, _dir, files in os.walk(path): if '__init__.py' in files: yield root.replace("/", ".")
[ "def", "find_packages", "(", "path", ":", "str", ")", "->", "List", "[", "str", "]", ":", "for", "root", ",", "_dir", ",", "files", "in", "os", ".", "walk", "(", "path", ")", ":", "if", "'__init__.py'", "in", "files", ":", "yield", "root", ".", "...
A better version of find_packages than what setuptools offers :param path: :return:
[ "A", "better", "version", "of", "find_packages", "than", "what", "setuptools", "offers", ":", "param", "path", ":", ":", "return", ":" ]
train
https://github.com/veltzer/pypitools/blob/5f097be21e9bc65578eed5b6b7855c1945540701/config/helpers.py#L24-L32
emencia/emencia-django-forum
forum/forms/thread.py
ThreadCreateForm.clean_text
def clean_text(self): """ Text content validation """ text = self.cleaned_data.get("text") validation_helper = safe_import_module(settings.FORUM_TEXT_VALIDATOR_HELPER_PATH) if validation_helper is not None: return validation_helper(self, text) else: ...
python
def clean_text(self): """ Text content validation """ text = self.cleaned_data.get("text") validation_helper = safe_import_module(settings.FORUM_TEXT_VALIDATOR_HELPER_PATH) if validation_helper is not None: return validation_helper(self, text) else: ...
[ "def", "clean_text", "(", "self", ")", ":", "text", "=", "self", ".", "cleaned_data", ".", "get", "(", "\"text\"", ")", "validation_helper", "=", "safe_import_module", "(", "settings", ".", "FORUM_TEXT_VALIDATOR_HELPER_PATH", ")", "if", "validation_helper", "is", ...
Text content validation
[ "Text", "content", "validation" ]
train
https://github.com/emencia/emencia-django-forum/blob/cda74ed7e5822675c340ee5ec71548d981bccd3b/forum/forms/thread.py#L43-L52
nivardus/kclboot
kclboot/command.py
main
def main(): ''' Bootstrapper CLI ''' parser = argparse.ArgumentParser(prog='kclboot', description='kclboot - Kinesis Client Library Bootstrapper') subparsers = parser.add_subparsers(title='Subcommands', help='Additional help', dest='subparser') # Common arguments jar_path_parser =...
python
def main(): ''' Bootstrapper CLI ''' parser = argparse.ArgumentParser(prog='kclboot', description='kclboot - Kinesis Client Library Bootstrapper') subparsers = parser.add_subparsers(title='Subcommands', help='Additional help', dest='subparser') # Common arguments jar_path_parser =...
[ "def", "main", "(", ")", ":", "parser", "=", "argparse", ".", "ArgumentParser", "(", "prog", "=", "'kclboot'", ",", "description", "=", "'kclboot - Kinesis Client Library Bootstrapper'", ")", "subparsers", "=", "parser", ".", "add_subparsers", "(", "title", "=", ...
Bootstrapper CLI
[ "Bootstrapper", "CLI" ]
train
https://github.com/nivardus/kclboot/blob/aee054d9186938bec51f19e9ed8deed6ac6fe492/kclboot/command.py#L20-L59
redhog/pieshell
pieshell/pipeline.py
pipeline_repr
def pipeline_repr(obj): """Returns a string representation of an object, including pieshell pipelines.""" if not hasattr(repr_state, 'in_repr'): repr_state.in_repr = 0 repr_state.in_repr += 1 try: return standard_repr(obj) finally: repr_state.in_repr -= 1
python
def pipeline_repr(obj): """Returns a string representation of an object, including pieshell pipelines.""" if not hasattr(repr_state, 'in_repr'): repr_state.in_repr = 0 repr_state.in_repr += 1 try: return standard_repr(obj) finally: repr_state.in_repr -= 1
[ "def", "pipeline_repr", "(", "obj", ")", ":", "if", "not", "hasattr", "(", "repr_state", ",", "'in_repr'", ")", ":", "repr_state", ".", "in_repr", "=", "0", "repr_state", ".", "in_repr", "+=", "1", "try", ":", "return", "standard_repr", "(", "obj", ")", ...
Returns a string representation of an object, including pieshell pipelines.
[ "Returns", "a", "string", "representation", "of", "an", "object", "including", "pieshell", "pipelines", "." ]
train
https://github.com/redhog/pieshell/blob/11cff3b93785ee4446f99b9134be20380edeb767/pieshell/pipeline.py#L28-L38
redhog/pieshell
pieshell/pipeline.py
Pipeline.run
def run(self, redirects = []): """Runs the pipelines with the specified redirects and returns a RunningPipeline instance.""" if not isinstance(redirects, redir.Redirects): redirects = redir.Redirects(self._env._redirects, *redirects) with copy.copy_session() as sess: ...
python
def run(self, redirects = []): """Runs the pipelines with the specified redirects and returns a RunningPipeline instance.""" if not isinstance(redirects, redir.Redirects): redirects = redir.Redirects(self._env._redirects, *redirects) with copy.copy_session() as sess: ...
[ "def", "run", "(", "self", ",", "redirects", "=", "[", "]", ")", ":", "if", "not", "isinstance", "(", "redirects", ",", "redir", ".", "Redirects", ")", ":", "redirects", "=", "redir", ".", "Redirects", "(", "self", ".", "_env", ".", "_redirects", ","...
Runs the pipelines with the specified redirects and returns a RunningPipeline instance.
[ "Runs", "the", "pipelines", "with", "the", "specified", "redirects", "and", "returns", "a", "RunningPipeline", "instance", "." ]
train
https://github.com/redhog/pieshell/blob/11cff3b93785ee4446f99b9134be20380edeb767/pieshell/pipeline.py#L222-L232
eallik/spinoff
spinoff/util/lockfile.py
lock_file
def lock_file(path, maxdelay=.1, lock_cls=LockFile, timeout=10.0): """Cooperative file lock. Uses `lockfile.LockFile` polling under the hood. `maxdelay` defines the interval between individual polls. """ lock = lock_cls(path) max_t = time.time() + timeout while True: if time.time() >= ...
python
def lock_file(path, maxdelay=.1, lock_cls=LockFile, timeout=10.0): """Cooperative file lock. Uses `lockfile.LockFile` polling under the hood. `maxdelay` defines the interval between individual polls. """ lock = lock_cls(path) max_t = time.time() + timeout while True: if time.time() >= ...
[ "def", "lock_file", "(", "path", ",", "maxdelay", "=", ".1", ",", "lock_cls", "=", "LockFile", ",", "timeout", "=", "10.0", ")", ":", "lock", "=", "lock_cls", "(", "path", ")", "max_t", "=", "time", ".", "time", "(", ")", "+", "timeout", "while", "...
Cooperative file lock. Uses `lockfile.LockFile` polling under the hood. `maxdelay` defines the interval between individual polls.
[ "Cooperative", "file", "lock", ".", "Uses", "lockfile", ".", "LockFile", "polling", "under", "the", "hood", "." ]
train
https://github.com/eallik/spinoff/blob/06b00d6b86c7422c9cb8f9a4b2915906e92b7d52/spinoff/util/lockfile.py#L11-L31
sveetch/py-css-styleguide
py_css_styleguide/parser.py
TinycssSourceParser.digest_prelude
def digest_prelude(self, rule): """ Walk on rule prelude (aka CSS selector) tokens to return a string of the value name (from css selector). Actually only simple selector and selector with descendant combinator are supported. Using any other selector kind may leads to unexpected...
python
def digest_prelude(self, rule): """ Walk on rule prelude (aka CSS selector) tokens to return a string of the value name (from css selector). Actually only simple selector and selector with descendant combinator are supported. Using any other selector kind may leads to unexpected...
[ "def", "digest_prelude", "(", "self", ",", "rule", ")", ":", "name", "=", "[", "]", "for", "token", "in", "rule", ".", "prelude", ":", "if", "token", ".", "type", "==", "'ident'", ":", "name", ".", "append", "(", "token", ".", "value", ")", "return...
Walk on rule prelude (aka CSS selector) tokens to return a string of the value name (from css selector). Actually only simple selector and selector with descendant combinator are supported. Using any other selector kind may leads to unexpected issues. Arguments: rul...
[ "Walk", "on", "rule", "prelude", "(", "aka", "CSS", "selector", ")", "tokens", "to", "return", "a", "string", "of", "the", "value", "name", "(", "from", "css", "selector", ")", "." ]
train
https://github.com/sveetch/py-css-styleguide/blob/5acc693f71b2fa7d944d7fed561ae0a7699ccd0f/py_css_styleguide/parser.py#L29-L52
sveetch/py-css-styleguide
py_css_styleguide/parser.py
TinycssSourceParser.digest_content
def digest_content(self, rule): """ Walk on rule content tokens to return a dict of properties. This is pretty naive and will choke/fail on everything that is more evolved than simple ``ident(string):value(string)`` Arguments: rule (tinycss2.ast.QualifiedRule): Qual...
python
def digest_content(self, rule): """ Walk on rule content tokens to return a dict of properties. This is pretty naive and will choke/fail on everything that is more evolved than simple ``ident(string):value(string)`` Arguments: rule (tinycss2.ast.QualifiedRule): Qual...
[ "def", "digest_content", "(", "self", ",", "rule", ")", ":", "data", "=", "OrderedDict", "(", ")", "current_key", "=", "None", "for", "token", "in", "rule", ".", "content", ":", "# Assume first identity token is the property name", "if", "token", ".", "type", ...
Walk on rule content tokens to return a dict of properties. This is pretty naive and will choke/fail on everything that is more evolved than simple ``ident(string):value(string)`` Arguments: rule (tinycss2.ast.QualifiedRule): Qualified rule object as returned by ti...
[ "Walk", "on", "rule", "content", "tokens", "to", "return", "a", "dict", "of", "properties", "." ]
train
https://github.com/sveetch/py-css-styleguide/blob/5acc693f71b2fa7d944d7fed561ae0a7699ccd0f/py_css_styleguide/parser.py#L54-L87
sveetch/py-css-styleguide
py_css_styleguide/parser.py
TinycssSourceParser.consume
def consume(self, source): """ Parse source and consume tokens from tinycss2. Arguments: source (string): Source content to parse. Returns: dict: Retrieved rules. """ manifest = OrderedDict() rules = parse_stylesheet( source,...
python
def consume(self, source): """ Parse source and consume tokens from tinycss2. Arguments: source (string): Source content to parse. Returns: dict: Retrieved rules. """ manifest = OrderedDict() rules = parse_stylesheet( source,...
[ "def", "consume", "(", "self", ",", "source", ")", ":", "manifest", "=", "OrderedDict", "(", ")", "rules", "=", "parse_stylesheet", "(", "source", ",", "skip_comments", "=", "True", ",", "skip_whitespace", "=", "True", ",", ")", "for", "rule", "in", "rul...
Parse source and consume tokens from tinycss2. Arguments: source (string): Source content to parse. Returns: dict: Retrieved rules.
[ "Parse", "source", "and", "consume", "tokens", "from", "tinycss2", "." ]
train
https://github.com/sveetch/py-css-styleguide/blob/5acc693f71b2fa7d944d7fed561ae0a7699ccd0f/py_css_styleguide/parser.py#L89-L118
tBaxter/tango-comments
build/lib/tango_comments/views/comments.py
post_comment
def post_comment(request, next=None, using=None): """ Post a comment. HTTP POST is required. """ # Fill out some initial data fields from an authenticated user, if present data = request.POST.copy() if request.user.is_authenticated: data["user"] = request.user else: retu...
python
def post_comment(request, next=None, using=None): """ Post a comment. HTTP POST is required. """ # Fill out some initial data fields from an authenticated user, if present data = request.POST.copy() if request.user.is_authenticated: data["user"] = request.user else: retu...
[ "def", "post_comment", "(", "request", ",", "next", "=", "None", ",", "using", "=", "None", ")", ":", "# Fill out some initial data fields from an authenticated user, if present", "data", "=", "request", ".", "POST", ".", "copy", "(", ")", "if", "request", ".", ...
Post a comment. HTTP POST is required.
[ "Post", "a", "comment", "." ]
train
https://github.com/tBaxter/tango-comments/blob/1fd335c6fc9e81bba158e42e1483f1a149622ab4/build/lib/tango_comments/views/comments.py#L35-L127
dossier/dossier.web
dossier/web/search_engines.py
streaming_sample
def streaming_sample(seq, k, limit=None): '''Streaming sample. Iterate over seq (once!) keeping k random elements with uniform distribution. As a special case, if ``k`` is ``None``, then ``list(seq)`` is returned. :param seq: iterable of things to sample from :param k: size of desired sam...
python
def streaming_sample(seq, k, limit=None): '''Streaming sample. Iterate over seq (once!) keeping k random elements with uniform distribution. As a special case, if ``k`` is ``None``, then ``list(seq)`` is returned. :param seq: iterable of things to sample from :param k: size of desired sam...
[ "def", "streaming_sample", "(", "seq", ",", "k", ",", "limit", "=", "None", ")", ":", "if", "k", "is", "None", ":", "return", "list", "(", "seq", ")", "seq", "=", "iter", "(", "seq", ")", "if", "limit", "is", "not", "None", ":", "k", "=", "min"...
Streaming sample. Iterate over seq (once!) keeping k random elements with uniform distribution. As a special case, if ``k`` is ``None``, then ``list(seq)`` is returned. :param seq: iterable of things to sample from :param k: size of desired sample :param limit: stop reading ``seq`` after ...
[ "Streaming", "sample", "." ]
train
https://github.com/dossier/dossier.web/blob/1cad1cce3c37d3a4e956abc710a2bc1afe16a092/dossier/web/search_engines.py#L102-L128
minhhoit/yacms
yacms/accounts/__init__.py
get_profile_model
def get_profile_model(): """ Returns the yacms profile model, defined in ``settings.ACCOUNTS_PROFILE_MODEL``, or ``None`` if no profile model is configured. """ if not getattr(settings, "ACCOUNTS_PROFILE_MODEL", None): raise ProfileNotConfigured try: return apps.get_model(s...
python
def get_profile_model(): """ Returns the yacms profile model, defined in ``settings.ACCOUNTS_PROFILE_MODEL``, or ``None`` if no profile model is configured. """ if not getattr(settings, "ACCOUNTS_PROFILE_MODEL", None): raise ProfileNotConfigured try: return apps.get_model(s...
[ "def", "get_profile_model", "(", ")", ":", "if", "not", "getattr", "(", "settings", ",", "\"ACCOUNTS_PROFILE_MODEL\"", ",", "None", ")", ":", "raise", "ProfileNotConfigured", "try", ":", "return", "apps", ".", "get_model", "(", "settings", ".", "ACCOUNTS_PROFILE...
Returns the yacms profile model, defined in ``settings.ACCOUNTS_PROFILE_MODEL``, or ``None`` if no profile model is configured.
[ "Returns", "the", "yacms", "profile", "model", "defined", "in", "settings", ".", "ACCOUNTS_PROFILE_MODEL", "or", "None", "if", "no", "profile", "model", "is", "configured", "." ]
train
https://github.com/minhhoit/yacms/blob/2921b706b7107c6e8c5f2bbf790ff11f85a2167f/yacms/accounts/__init__.py#L22-L40
minhhoit/yacms
yacms/accounts/__init__.py
get_profile_for_user
def get_profile_for_user(user): """ Returns site-specific profile for this user. Raises ``ProfileNotConfigured`` if ``settings.ACCOUNTS_PROFILE_MODEL`` is not set, and ``ImproperlyConfigured`` if the corresponding model can't be found. """ if not hasattr(user, '_yacms_profile'): # Ra...
python
def get_profile_for_user(user): """ Returns site-specific profile for this user. Raises ``ProfileNotConfigured`` if ``settings.ACCOUNTS_PROFILE_MODEL`` is not set, and ``ImproperlyConfigured`` if the corresponding model can't be found. """ if not hasattr(user, '_yacms_profile'): # Ra...
[ "def", "get_profile_for_user", "(", "user", ")", ":", "if", "not", "hasattr", "(", "user", ",", "'_yacms_profile'", ")", ":", "# Raises ProfileNotConfigured if not bool(ACCOUNTS_PROFILE_MODEL)", "profile_model", "=", "get_profile_model", "(", ")", "profile_manager", "=", ...
Returns site-specific profile for this user. Raises ``ProfileNotConfigured`` if ``settings.ACCOUNTS_PROFILE_MODEL`` is not set, and ``ImproperlyConfigured`` if the corresponding model can't be found.
[ "Returns", "site", "-", "specific", "profile", "for", "this", "user", ".", "Raises", "ProfileNotConfigured", "if", "settings", ".", "ACCOUNTS_PROFILE_MODEL", "is", "not", "set", "and", "ImproperlyConfigured", "if", "the", "corresponding", "model", "can", "t", "be"...
train
https://github.com/minhhoit/yacms/blob/2921b706b7107c6e8c5f2bbf790ff11f85a2167f/yacms/accounts/__init__.py#L43-L61
minhhoit/yacms
yacms/accounts/__init__.py
get_profile_form
def get_profile_form(): """ Returns the profile form defined by ``settings.ACCOUNTS_PROFILE_FORM_CLASS``. """ from yacms.conf import settings try: return import_dotted_path(settings.ACCOUNTS_PROFILE_FORM_CLASS) except ImportError: raise ImproperlyConfigured("Value for ACCOUNT...
python
def get_profile_form(): """ Returns the profile form defined by ``settings.ACCOUNTS_PROFILE_FORM_CLASS``. """ from yacms.conf import settings try: return import_dotted_path(settings.ACCOUNTS_PROFILE_FORM_CLASS) except ImportError: raise ImproperlyConfigured("Value for ACCOUNT...
[ "def", "get_profile_form", "(", ")", ":", "from", "yacms", ".", "conf", "import", "settings", "try", ":", "return", "import_dotted_path", "(", "settings", ".", "ACCOUNTS_PROFILE_FORM_CLASS", ")", "except", "ImportError", ":", "raise", "ImproperlyConfigured", "(", ...
Returns the profile form defined by ``settings.ACCOUNTS_PROFILE_FORM_CLASS``.
[ "Returns", "the", "profile", "form", "defined", "by", "settings", ".", "ACCOUNTS_PROFILE_FORM_CLASS", "." ]
train
https://github.com/minhhoit/yacms/blob/2921b706b7107c6e8c5f2bbf790ff11f85a2167f/yacms/accounts/__init__.py#L64-L75
minhhoit/yacms
yacms/accounts/__init__.py
get_profile_user_fieldname
def get_profile_user_fieldname(profile_model=None, user_model=None): """ Returns the name of the first field on the profile model that points to the ``auth.User`` model. """ Profile = profile_model or get_profile_model() User = user_model or get_user_model() for field in Profile._meta.fields...
python
def get_profile_user_fieldname(profile_model=None, user_model=None): """ Returns the name of the first field on the profile model that points to the ``auth.User`` model. """ Profile = profile_model or get_profile_model() User = user_model or get_user_model() for field in Profile._meta.fields...
[ "def", "get_profile_user_fieldname", "(", "profile_model", "=", "None", ",", "user_model", "=", "None", ")", ":", "Profile", "=", "profile_model", "or", "get_profile_model", "(", ")", "User", "=", "user_model", "or", "get_user_model", "(", ")", "for", "field", ...
Returns the name of the first field on the profile model that points to the ``auth.User`` model.
[ "Returns", "the", "name", "of", "the", "first", "field", "on", "the", "profile", "model", "that", "points", "to", "the", "auth", ".", "User", "model", "." ]
train
https://github.com/minhhoit/yacms/blob/2921b706b7107c6e8c5f2bbf790ff11f85a2167f/yacms/accounts/__init__.py#L78-L90
ttinies/sc2common
sc2common/containers.py
RestrictedType.gameValue
def gameValue(self): """identify the correpsonding internal SC2 game value for self.type's value""" allowed = type(self).ALLOWED_TYPES try: if isinstance(allowed, dict): # if ALLOWED_TYPES is not a dict, there is no-internal game value mapping defined return allowed.g...
python
def gameValue(self): """identify the correpsonding internal SC2 game value for self.type's value""" allowed = type(self).ALLOWED_TYPES try: if isinstance(allowed, dict): # if ALLOWED_TYPES is not a dict, there is no-internal game value mapping defined return allowed.g...
[ "def", "gameValue", "(", "self", ")", ":", "allowed", "=", "type", "(", "self", ")", ".", "ALLOWED_TYPES", "try", ":", "if", "isinstance", "(", "allowed", ",", "dict", ")", ":", "# if ALLOWED_TYPES is not a dict, there is no-internal game value mapping defined", "re...
identify the correpsonding internal SC2 game value for self.type's value
[ "identify", "the", "correpsonding", "internal", "SC2", "game", "value", "for", "self", ".", "type", "s", "value" ]
train
https://github.com/ttinies/sc2common/blob/469623c319c7ab7af799551055839ea3b3f87d54/sc2common/containers.py#L86-L93
ttinies/sc2common
sc2common/containers.py
MapPoint.direct2dDistance
def direct2dDistance(self, point): """consider the distance between two mapPoints, ignoring all terrain, pathing issues""" if not isinstance(point, MapPoint): return 0.0 return ((self.x-point.x)**2 + (self.y-point.y)**2)**(0.5) # simple distance formula
python
def direct2dDistance(self, point): """consider the distance between two mapPoints, ignoring all terrain, pathing issues""" if not isinstance(point, MapPoint): return 0.0 return ((self.x-point.x)**2 + (self.y-point.y)**2)**(0.5) # simple distance formula
[ "def", "direct2dDistance", "(", "self", ",", "point", ")", ":", "if", "not", "isinstance", "(", "point", ",", "MapPoint", ")", ":", "return", "0.0", "return", "(", "(", "self", ".", "x", "-", "point", ".", "x", ")", "**", "2", "+", "(", "self", "...
consider the distance between two mapPoints, ignoring all terrain, pathing issues
[ "consider", "the", "distance", "between", "two", "mapPoints", "ignoring", "all", "terrain", "pathing", "issues" ]
train
https://github.com/ttinies/sc2common/blob/469623c319c7ab7af799551055839ea3b3f87d54/sc2common/containers.py#L241-L244
ttinies/sc2common
sc2common/containers.py
MapPoint.midPoint
def midPoint(self, point): """identify the midpoint between two mapPoints""" x = (self.x + point.x)/2.0 y = (self.y + point.y)/2.0 z = (self.z + point.z)/2.0 return MapPoint(x,y,z)
python
def midPoint(self, point): """identify the midpoint between two mapPoints""" x = (self.x + point.x)/2.0 y = (self.y + point.y)/2.0 z = (self.z + point.z)/2.0 return MapPoint(x,y,z)
[ "def", "midPoint", "(", "self", ",", "point", ")", ":", "x", "=", "(", "self", ".", "x", "+", "point", ".", "x", ")", "/", "2.0", "y", "=", "(", "self", ".", "y", "+", "point", ".", "y", ")", "/", "2.0", "z", "=", "(", "self", ".", "z", ...
identify the midpoint between two mapPoints
[ "identify", "the", "midpoint", "between", "two", "mapPoints" ]
train
https://github.com/ttinies/sc2common/blob/469623c319c7ab7af799551055839ea3b3f87d54/sc2common/containers.py#L246-L251
ttinies/sc2common
sc2common/containers.py
MapPoint.magnitude
def magnitude(self, allow3d=True): """determine the magnitude of this location from the origin (presume values represent a Vector)""" ret = self.x**2 + self.y**2 if allow3d: ret += self.z**2 return ret**0.5 # square root
python
def magnitude(self, allow3d=True): """determine the magnitude of this location from the origin (presume values represent a Vector)""" ret = self.x**2 + self.y**2 if allow3d: ret += self.z**2 return ret**0.5 # square root
[ "def", "magnitude", "(", "self", ",", "allow3d", "=", "True", ")", ":", "ret", "=", "self", ".", "x", "**", "2", "+", "self", ".", "y", "**", "2", "if", "allow3d", ":", "ret", "+=", "self", ".", "z", "**", "2", "return", "ret", "**", "0.5", "...
determine the magnitude of this location from the origin (presume values represent a Vector)
[ "determine", "the", "magnitude", "of", "this", "location", "from", "the", "origin", "(", "presume", "values", "represent", "a", "Vector", ")" ]
train
https://github.com/ttinies/sc2common/blob/469623c319c7ab7af799551055839ea3b3f87d54/sc2common/containers.py#L270-L274
ttinies/sc2common
sc2common/containers.py
MapPoint.angle2d
def angle2d(self): """determine the angle of this point on a circle, measured in radians (presume values represent a Vector)""" if self.x==0: if self.y<0: return math.pi/2.0*3 elif self.y>0: return math.pi/2.0 else: return 0 elif self...
python
def angle2d(self): """determine the angle of this point on a circle, measured in radians (presume values represent a Vector)""" if self.x==0: if self.y<0: return math.pi/2.0*3 elif self.y>0: return math.pi/2.0 else: return 0 elif self...
[ "def", "angle2d", "(", "self", ")", ":", "if", "self", ".", "x", "==", "0", ":", "if", "self", ".", "y", "<", "0", ":", "return", "math", ".", "pi", "/", "2.0", "*", "3", "elif", "self", ".", "y", ">", "0", ":", "return", "math", ".", "pi",...
determine the angle of this point on a circle, measured in radians (presume values represent a Vector)
[ "determine", "the", "angle", "of", "this", "point", "on", "a", "circle", "measured", "in", "radians", "(", "presume", "values", "represent", "a", "Vector", ")" ]
train
https://github.com/ttinies/sc2common/blob/469623c319c7ab7af799551055839ea3b3f87d54/sc2common/containers.py#L276-L290
fotonauts/fwissr-python
fwissr/conf.py
merge_conf
def merge_conf(to_hash, other_hash, path=[]): "merges other_hash into to_hash" for key in other_hash: if (key in to_hash and isinstance(to_hash[key], dict) and isinstance(other_hash[key], dict)): merge_conf(to_hash[key], other_hash[key], path + [str(key)]) else: ...
python
def merge_conf(to_hash, other_hash, path=[]): "merges other_hash into to_hash" for key in other_hash: if (key in to_hash and isinstance(to_hash[key], dict) and isinstance(other_hash[key], dict)): merge_conf(to_hash[key], other_hash[key], path + [str(key)]) else: ...
[ "def", "merge_conf", "(", "to_hash", ",", "other_hash", ",", "path", "=", "[", "]", ")", ":", "for", "key", "in", "other_hash", ":", "if", "(", "key", "in", "to_hash", "and", "isinstance", "(", "to_hash", "[", "key", "]", ",", "dict", ")", "and", "...
merges other_hash into to_hash
[ "merges", "other_hash", "into", "to_hash" ]
train
https://github.com/fotonauts/fwissr-python/blob/4314aa53ca45b4534cd312f6343a88596b4416d4/fwissr/conf.py#L7-L15
hmartiniano/faz
faz/task.py
Task.check_inputs
def check_inputs(self): """ Check for the existence of input files """ self.inputs = self.expand_filenames(self.inputs) result = False if len(self.inputs) == 0 or self.files_exist(self.inputs): result = True else: print("Not executing task. Input file(s) d...
python
def check_inputs(self): """ Check for the existence of input files """ self.inputs = self.expand_filenames(self.inputs) result = False if len(self.inputs) == 0 or self.files_exist(self.inputs): result = True else: print("Not executing task. Input file(s) d...
[ "def", "check_inputs", "(", "self", ")", ":", "self", ".", "inputs", "=", "self", ".", "expand_filenames", "(", "self", ".", "inputs", ")", "result", "=", "False", "if", "len", "(", "self", ".", "inputs", ")", "==", "0", "or", "self", ".", "files_exi...
Check for the existence of input files
[ "Check", "for", "the", "existence", "of", "input", "files" ]
train
https://github.com/hmartiniano/faz/blob/36a58c45e8c0718d38cb3c533542c8743e7e7a65/faz/task.py#L51-L59
hmartiniano/faz
faz/task.py
Task.check_outputs
def check_outputs(self): """ Check for the existence of output files """ self.outputs = self.expand_filenames(self.outputs) result = False if self.files_exist(self.outputs): if self.dependencies_are_newer(self.outputs, self.inputs): result = True ...
python
def check_outputs(self): """ Check for the existence of output files """ self.outputs = self.expand_filenames(self.outputs) result = False if self.files_exist(self.outputs): if self.dependencies_are_newer(self.outputs, self.inputs): result = True ...
[ "def", "check_outputs", "(", "self", ")", ":", "self", ".", "outputs", "=", "self", ".", "expand_filenames", "(", "self", ".", "outputs", ")", "result", "=", "False", "if", "self", ".", "files_exist", "(", "self", ".", "outputs", ")", ":", "if", "self"...
Check for the existence of output files
[ "Check", "for", "the", "existence", "of", "output", "files" ]
train
https://github.com/hmartiniano/faz/blob/36a58c45e8c0718d38cb3c533542c8743e7e7a65/faz/task.py#L61-L80
hmartiniano/faz
faz/task.py
Task.expand_variables
def expand_variables(self): """ Expand variables in the task code. Only variables who use the $[<variable name>] format are expanded. Variables using the $<variable name> and ${<variable name>} formats are expanded by the shell (in the cases where bash is the interpreter. ...
python
def expand_variables(self): """ Expand variables in the task code. Only variables who use the $[<variable name>] format are expanded. Variables using the $<variable name> and ${<variable name>} formats are expanded by the shell (in the cases where bash is the interpreter. ...
[ "def", "expand_variables", "(", "self", ")", ":", "self", ".", "environment", "[", "\"INPUTS\"", "]", "=", "\" \"", ".", "join", "(", "self", ".", "inputs", ")", "self", ".", "environment", "[", "\"OUTPUTS\"", "]", "=", "\" \"", ".", "join", "(", "self...
Expand variables in the task code. Only variables who use the $[<variable name>] format are expanded. Variables using the $<variable name> and ${<variable name>} formats are expanded by the shell (in the cases where bash is the interpreter.
[ "Expand", "variables", "in", "the", "task", "code", ".", "Only", "variables", "who", "use", "the", "$", "[", "<variable", "name", ">", "]", "format", "are", "expanded", ".", "Variables", "using", "the", "$<variable", "name", ">", "and", "$", "{", "<varia...
train
https://github.com/hmartiniano/faz/blob/36a58c45e8c0718d38cb3c533542c8743e7e7a65/faz/task.py#L82-L101
hmartiniano/faz
faz/task.py
Task.expand_filenames
def expand_filenames(self, filenames): """ Expand a list of filenames using environment variables, followed by expansion of shell-style wildcards. """ results = [] for filename in filenames: result = filename if "$" in filename: tem...
python
def expand_filenames(self, filenames): """ Expand a list of filenames using environment variables, followed by expansion of shell-style wildcards. """ results = [] for filename in filenames: result = filename if "$" in filename: tem...
[ "def", "expand_filenames", "(", "self", ",", "filenames", ")", ":", "results", "=", "[", "]", "for", "filename", "in", "filenames", ":", "result", "=", "filename", "if", "\"$\"", "in", "filename", ":", "template", "=", "Template", "(", "filename", ")", "...
Expand a list of filenames using environment variables, followed by expansion of shell-style wildcards.
[ "Expand", "a", "list", "of", "filenames", "using", "environment", "variables", "followed", "by", "expansion", "of", "shell", "-", "style", "wildcards", "." ]
train
https://github.com/hmartiniano/faz/blob/36a58c45e8c0718d38cb3c533542c8743e7e7a65/faz/task.py#L103-L126
hmartiniano/faz
faz/task.py
Task.files_exist
def files_exist(self, filenames): """ Check if all files in a given list exist. """ return all([os.path.exists(os.path.abspath(filename)) and os.path.isfile(os.path.abspath(filename)) for filename in filenames])
python
def files_exist(self, filenames): """ Check if all files in a given list exist. """ return all([os.path.exists(os.path.abspath(filename)) and os.path.isfile(os.path.abspath(filename)) for filename in filenames])
[ "def", "files_exist", "(", "self", ",", "filenames", ")", ":", "return", "all", "(", "[", "os", ".", "path", ".", "exists", "(", "os", ".", "path", ".", "abspath", "(", "filename", ")", ")", "and", "os", ".", "path", ".", "isfile", "(", "os", "."...
Check if all files in a given list exist.
[ "Check", "if", "all", "files", "in", "a", "given", "list", "exist", "." ]
train
https://github.com/hmartiniano/faz/blob/36a58c45e8c0718d38cb3c533542c8743e7e7a65/faz/task.py#L128-L131
hmartiniano/faz
faz/task.py
Task.dependencies_are_newer
def dependencies_are_newer(self, files, dependencies): """ For two lists of files, check if any file in the second list is newer than any file of the first. """ dependency_mtimes = [ os.path.getmtime(filename) for filename in dependencies] file_mtimes = [os.pa...
python
def dependencies_are_newer(self, files, dependencies): """ For two lists of files, check if any file in the second list is newer than any file of the first. """ dependency_mtimes = [ os.path.getmtime(filename) for filename in dependencies] file_mtimes = [os.pa...
[ "def", "dependencies_are_newer", "(", "self", ",", "files", ",", "dependencies", ")", ":", "dependency_mtimes", "=", "[", "os", ".", "path", ".", "getmtime", "(", "filename", ")", "for", "filename", "in", "dependencies", "]", "file_mtimes", "=", "[", "os", ...
For two lists of files, check if any file in the second list is newer than any file of the first.
[ "For", "two", "lists", "of", "files", "check", "if", "any", "file", "in", "the", "second", "list", "is", "newer", "than", "any", "file", "of", "the", "first", "." ]
train
https://github.com/hmartiniano/faz/blob/36a58c45e8c0718d38cb3c533542c8743e7e7a65/faz/task.py#L133-L146
hmartiniano/faz
faz/task.py
Task.mktemp_file
def mktemp_file(self): """ Create a temporary file in the '.faz' directory for the code to feed to the interpreter. """ if not(os.path.exists(self.__dirname)): logging.debug("Creating directory {}".format(self.__dirname)) os.mkdir(self.__dirname) elif not(os.p...
python
def mktemp_file(self): """ Create a temporary file in the '.faz' directory for the code to feed to the interpreter. """ if not(os.path.exists(self.__dirname)): logging.debug("Creating directory {}".format(self.__dirname)) os.mkdir(self.__dirname) elif not(os.p...
[ "def", "mktemp_file", "(", "self", ")", ":", "if", "not", "(", "os", ".", "path", ".", "exists", "(", "self", ".", "__dirname", ")", ")", ":", "logging", ".", "debug", "(", "\"Creating directory {}\"", ".", "format", "(", "self", ".", "__dirname", ")",...
Create a temporary file in the '.faz' directory for the code to feed to the interpreter.
[ "Create", "a", "temporary", "file", "in", "the", ".", "faz", "directory", "for", "the", "code", "to", "feed", "to", "the", "interpreter", "." ]
train
https://github.com/hmartiniano/faz/blob/36a58c45e8c0718d38cb3c533542c8743e7e7a65/faz/task.py#L182-L194
edeposit/edeposit.amqp.harvester
src/edeposit/amqp/harvester/scrappers/zonerpress_cz/__init__.py
_get_max_page
def _get_max_page(dom): """ Try to guess how much pages are in book listing. Args: dom (obj): HTMLElement container of the page with book list. Returns: int: Number of pages for given category. """ div = dom.find("div", {"class": "razeniKnihListovani"}) if not div: ...
python
def _get_max_page(dom): """ Try to guess how much pages are in book listing. Args: dom (obj): HTMLElement container of the page with book list. Returns: int: Number of pages for given category. """ div = dom.find("div", {"class": "razeniKnihListovani"}) if not div: ...
[ "def", "_get_max_page", "(", "dom", ")", ":", "div", "=", "dom", ".", "find", "(", "\"div\"", ",", "{", "\"class\"", ":", "\"razeniKnihListovani\"", "}", ")", "if", "not", "div", ":", "return", "1", "# isolate only page numbers from links", "links", "=", "di...
Try to guess how much pages are in book listing. Args: dom (obj): HTMLElement container of the page with book list. Returns: int: Number of pages for given category.
[ "Try", "to", "guess", "how", "much", "pages", "are", "in", "book", "listing", "." ]
train
https://github.com/edeposit/edeposit.amqp.harvester/blob/38cb87ccdf6bf2f550a98460d0a329c4b9dc8e2e/src/edeposit/amqp/harvester/scrappers/zonerpress_cz/__init__.py#L34-L65
edeposit/edeposit.amqp.harvester
src/edeposit/amqp/harvester/scrappers/zonerpress_cz/__init__.py
_parse_book_links
def _parse_book_links(dom): """ Parse links to the details about publications from page with book list. Args: dom (obj): HTMLElement container of the page with book list. Returns: list: List of strings / absolute links to book details. """ links = [] picker = lambda x: x.pa...
python
def _parse_book_links(dom): """ Parse links to the details about publications from page with book list. Args: dom (obj): HTMLElement container of the page with book list. Returns: list: List of strings / absolute links to book details. """ links = [] picker = lambda x: x.pa...
[ "def", "_parse_book_links", "(", "dom", ")", ":", "links", "=", "[", "]", "picker", "=", "lambda", "x", ":", "x", ".", "params", ".", "get", "(", "\"class\"", ",", "\"\"", ")", ".", "startswith", "(", "\"boxProKnihy\"", ")", "for", "el", "in", "dom",...
Parse links to the details about publications from page with book list. Args: dom (obj): HTMLElement container of the page with book list. Returns: list: List of strings / absolute links to book details.
[ "Parse", "links", "to", "the", "details", "about", "publications", "from", "page", "with", "book", "list", "." ]
train
https://github.com/edeposit/edeposit.amqp.harvester/blob/38cb87ccdf6bf2f550a98460d0a329c4b9dc8e2e/src/edeposit/amqp/harvester/scrappers/zonerpress_cz/__init__.py#L68-L89
edeposit/edeposit.amqp.harvester
src/edeposit/amqp/harvester/scrappers/zonerpress_cz/__init__.py
get_book_links
def get_book_links(links): """ Go thru `links` to categories and return list to all publications in all given categories. Args: links (list): List of strings (absolute links to categories). Returns: list: List of strings / absolute links to book details. """ book_links = []...
python
def get_book_links(links): """ Go thru `links` to categories and return list to all publications in all given categories. Args: links (list): List of strings (absolute links to categories). Returns: list: List of strings / absolute links to book details. """ book_links = []...
[ "def", "get_book_links", "(", "links", ")", ":", "book_links", "=", "[", "]", "for", "link", "in", "links", ":", "data", "=", "DOWNER", ".", "download", "(", "link", "+", "\"1\"", ")", "dom", "=", "dhtmlparser", ".", "parseString", "(", "data", ")", ...
Go thru `links` to categories and return list to all publications in all given categories. Args: links (list): List of strings (absolute links to categories). Returns: list: List of strings / absolute links to book details.
[ "Go", "thru", "links", "to", "categories", "and", "return", "list", "to", "all", "publications", "in", "all", "given", "categories", "." ]
train
https://github.com/edeposit/edeposit.amqp.harvester/blob/38cb87ccdf6bf2f550a98460d0a329c4b9dc8e2e/src/edeposit/amqp/harvester/scrappers/zonerpress_cz/__init__.py#L92-L124
edeposit/edeposit.amqp.harvester
src/edeposit/amqp/harvester/scrappers/zonerpress_cz/__init__.py
_parse_authors
def _parse_authors(authors): """ Parse informations about authors of the book. Args: dom (obj): HTMLElement containing slice of the page with details. Returns: list: List of :class:`.Author` objects. Blank if no author \ found. """ link = authors.find("a") lin...
python
def _parse_authors(authors): """ Parse informations about authors of the book. Args: dom (obj): HTMLElement containing slice of the page with details. Returns: list: List of :class:`.Author` objects. Blank if no author \ found. """ link = authors.find("a") lin...
[ "def", "_parse_authors", "(", "authors", ")", ":", "link", "=", "authors", ".", "find", "(", "\"a\"", ")", "link", "=", "link", "[", "0", "]", ".", "params", ".", "get", "(", "\"href\"", ")", "if", "link", "else", "None", "author_list", "=", "_strip_...
Parse informations about authors of the book. Args: dom (obj): HTMLElement containing slice of the page with details. Returns: list: List of :class:`.Author` objects. Blank if no author \ found.
[ "Parse", "informations", "about", "authors", "of", "the", "book", "." ]
train
https://github.com/edeposit/edeposit.amqp.harvester/blob/38cb87ccdf6bf2f550a98460d0a329c4b9dc8e2e/src/edeposit/amqp/harvester/scrappers/zonerpress_cz/__init__.py#L146-L171
edeposit/edeposit.amqp.harvester
src/edeposit/amqp/harvester/scrappers/zonerpress_cz/__init__.py
_process_book
def _process_book(link): """ Download and parse available informations about book from the publishers webpages. Args: link (str): URL of the book at the publishers webpages. Returns: obj: :class:`.Publication` instance with book details. """ # download and parse book info ...
python
def _process_book(link): """ Download and parse available informations about book from the publishers webpages. Args: link (str): URL of the book at the publishers webpages. Returns: obj: :class:`.Publication` instance with book details. """ # download and parse book info ...
[ "def", "_process_book", "(", "link", ")", ":", "# download and parse book info", "data", "=", "DOWNER", ".", "download", "(", "link", ")", "dom", "=", "dhtmlparser", ".", "parseString", "(", "utils", ".", "handle_encodnig", "(", "data", ")", ")", "dhtmlparser"...
Download and parse available informations about book from the publishers webpages. Args: link (str): URL of the book at the publishers webpages. Returns: obj: :class:`.Publication` instance with book details.
[ "Download", "and", "parse", "available", "informations", "about", "book", "from", "the", "publishers", "webpages", "." ]
train
https://github.com/edeposit/edeposit.amqp.harvester/blob/38cb87ccdf6bf2f550a98460d0a329c4b9dc8e2e/src/edeposit/amqp/harvester/scrappers/zonerpress_cz/__init__.py#L174-L238
edeposit/edeposit.amqp.harvester
src/edeposit/amqp/harvester/scrappers/zonerpress_cz/__init__.py
get_publications
def get_publications(): """ Get list of publication offered by ben.cz. Returns: list: List of :class:`structures.Publication` objects. """ books = [] for link in get_book_links(LINKS): books.append( _process_book(link) ) return books
python
def get_publications(): """ Get list of publication offered by ben.cz. Returns: list: List of :class:`structures.Publication` objects. """ books = [] for link in get_book_links(LINKS): books.append( _process_book(link) ) return books
[ "def", "get_publications", "(", ")", ":", "books", "=", "[", "]", "for", "link", "in", "get_book_links", "(", "LINKS", ")", ":", "books", ".", "append", "(", "_process_book", "(", "link", ")", ")", "return", "books" ]
Get list of publication offered by ben.cz. Returns: list: List of :class:`structures.Publication` objects.
[ "Get", "list", "of", "publication", "offered", "by", "ben", ".", "cz", "." ]
train
https://github.com/edeposit/edeposit.amqp.harvester/blob/38cb87ccdf6bf2f550a98460d0a329c4b9dc8e2e/src/edeposit/amqp/harvester/scrappers/zonerpress_cz/__init__.py#L241-L254
thespacedoctor/qubits
qubits/workspace.py
workspace.setup
def setup(self): """ *setup the workspace in the requested location* **Return:** - ``None`` """ self.log.info('starting the ``setup`` method') # RECURSIVELY CREATE MISSING DIRECTORIES if not os.path.exists(self.pathToWorkspace): os.makedi...
python
def setup(self): """ *setup the workspace in the requested location* **Return:** - ``None`` """ self.log.info('starting the ``setup`` method') # RECURSIVELY CREATE MISSING DIRECTORIES if not os.path.exists(self.pathToWorkspace): os.makedi...
[ "def", "setup", "(", "self", ")", ":", "self", ".", "log", ".", "info", "(", "'starting the ``setup`` method'", ")", "# RECURSIVELY CREATE MISSING DIRECTORIES", "if", "not", "os", ".", "path", ".", "exists", "(", "self", ".", "pathToWorkspace", ")", ":", "os",...
*setup the workspace in the requested location* **Return:** - ``None``
[ "*", "setup", "the", "workspace", "in", "the", "requested", "location", "*" ]
train
https://github.com/thespacedoctor/qubits/blob/3c02ace7226389841c6bb838d045c11bed61a3c2/qubits/workspace.py#L63-L123
rorr73/LifeSOSpy
lifesospy/response.py
Response.parse
def parse(text) -> Optional['Response']: """Parse response into an instance of the appropriate child class.""" # Trim the start and end markers, and ensure only lowercase is used if text.startswith(MARKER_START) and text.endswith(MARKER_END): text = text[1:len(text)-1].lower() ...
python
def parse(text) -> Optional['Response']: """Parse response into an instance of the appropriate child class.""" # Trim the start and end markers, and ensure only lowercase is used if text.startswith(MARKER_START) and text.endswith(MARKER_END): text = text[1:len(text)-1].lower() ...
[ "def", "parse", "(", "text", ")", "->", "Optional", "[", "'Response'", "]", ":", "# Trim the start and end markers, and ensure only lowercase is used", "if", "text", ".", "startswith", "(", "MARKER_START", ")", "and", "text", ".", "endswith", "(", "MARKER_END", ")",...
Parse response into an instance of the appropriate child class.
[ "Parse", "response", "into", "an", "instance", "of", "the", "appropriate", "child", "class", "." ]
train
https://github.com/rorr73/LifeSOSpy/blob/62360fbab2e90bf04d52b547093bdab2d4e389b4/lifesospy/response.py#L41-L106
rorr73/LifeSOSpy
lifesospy/response.py
DeviceInfoResponse.is_closed
def is_closed(self) -> Optional[bool]: """For Magnet Sensor; True if Closed, False if Open.""" if self._device_type is not None and self._device_type == DeviceType.DoorMagnet: return bool(self._current_status & 0x01) return None
python
def is_closed(self) -> Optional[bool]: """For Magnet Sensor; True if Closed, False if Open.""" if self._device_type is not None and self._device_type == DeviceType.DoorMagnet: return bool(self._current_status & 0x01) return None
[ "def", "is_closed", "(", "self", ")", "->", "Optional", "[", "bool", "]", ":", "if", "self", ".", "_device_type", "is", "not", "None", "and", "self", ".", "_device_type", "==", "DeviceType", ".", "DoorMagnet", ":", "return", "bool", "(", "self", ".", "...
For Magnet Sensor; True if Closed, False if Open.
[ "For", "Magnet", "Sensor", ";", "True", "if", "Closed", "False", "if", "Open", "." ]
train
https://github.com/rorr73/LifeSOSpy/blob/62360fbab2e90bf04d52b547093bdab2d4e389b4/lifesospy/response.py#L333-L337
rorr73/LifeSOSpy
lifesospy/response.py
DeviceInfoResponse.rssi_bars
def rssi_bars(self) -> int: """Received Signal Strength Indication, from 0 to 4 bars.""" rssi_db = self.rssi_db if rssi_db < 45: return 0 elif rssi_db < 60: return 1 elif rssi_db < 75: return 2 elif rssi_db < 90: return 3 ...
python
def rssi_bars(self) -> int: """Received Signal Strength Indication, from 0 to 4 bars.""" rssi_db = self.rssi_db if rssi_db < 45: return 0 elif rssi_db < 60: return 1 elif rssi_db < 75: return 2 elif rssi_db < 90: return 3 ...
[ "def", "rssi_bars", "(", "self", ")", "->", "int", ":", "rssi_db", "=", "self", ".", "rssi_db", "if", "rssi_db", "<", "45", ":", "return", "0", "elif", "rssi_db", "<", "60", ":", "return", "1", "elif", "rssi_db", "<", "75", ":", "return", "2", "eli...
Received Signal Strength Indication, from 0 to 4 bars.
[ "Received", "Signal", "Strength", "Indication", "from", "0", "to", "4", "bars", "." ]
train
https://github.com/rorr73/LifeSOSpy/blob/62360fbab2e90bf04d52b547093bdab2d4e389b4/lifesospy/response.py#L350-L361
rorr73/LifeSOSpy
lifesospy/response.py
EventLogResponse.zone
def zone(self) -> Optional[str]: """Zone the device is assigned to.""" if self._device_category == DC_BASEUNIT: return None return '{:02x}-{:02x}'.format(self._group_number, self._unit_number)
python
def zone(self) -> Optional[str]: """Zone the device is assigned to.""" if self._device_category == DC_BASEUNIT: return None return '{:02x}-{:02x}'.format(self._group_number, self._unit_number)
[ "def", "zone", "(", "self", ")", "->", "Optional", "[", "str", "]", ":", "if", "self", ".", "_device_category", "==", "DC_BASEUNIT", ":", "return", "None", "return", "'{:02x}-{:02x}'", ".", "format", "(", "self", ".", "_group_number", ",", "self", ".", "...
Zone the device is assigned to.
[ "Zone", "the", "device", "is", "assigned", "to", "." ]
train
https://github.com/rorr73/LifeSOSpy/blob/62360fbab2e90bf04d52b547093bdab2d4e389b4/lifesospy/response.py#L926-L930
ploneintranet/ploneintranet.workspace
src/ploneintranet/workspace/subscribers.py
workspace_state_changed
def workspace_state_changed(ob, event): """ when a workspace is made 'open', we need to give all intranet users the 'Guest' role equally, when the workspace is not open, we need to remove the role again """ workspace = event.object roles = ['Guest', ] if event.new_state.id == 'open'...
python
def workspace_state_changed(ob, event): """ when a workspace is made 'open', we need to give all intranet users the 'Guest' role equally, when the workspace is not open, we need to remove the role again """ workspace = event.object roles = ['Guest', ] if event.new_state.id == 'open'...
[ "def", "workspace_state_changed", "(", "ob", ",", "event", ")", ":", "workspace", "=", "event", ".", "object", "roles", "=", "[", "'Guest'", ",", "]", "if", "event", ".", "new_state", ".", "id", "==", "'open'", ":", "api", ".", "group", ".", "grant_rol...
when a workspace is made 'open', we need to give all intranet users the 'Guest' role equally, when the workspace is not open, we need to remove the role again
[ "when", "a", "workspace", "is", "made", "open", "we", "need", "to", "give", "all", "intranet", "users", "the", "Guest", "role" ]
train
https://github.com/ploneintranet/ploneintranet.workspace/blob/a4fc7a5c61f9c6d4d4ad25478ff5250f342ffbba/src/ploneintranet/workspace/subscribers.py#L13-L36
ploneintranet/ploneintranet.workspace
src/ploneintranet/workspace/subscribers.py
workspace_added
def workspace_added(ob, event): """ when a workspace is created, we add the creator to the admin group. We then setup our placeful workflow """ # Whoever creates the workspace should be added as an Admin creator = ob.Creator() IWorkspace(ob).add_to_team( user=creator, groups...
python
def workspace_added(ob, event): """ when a workspace is created, we add the creator to the admin group. We then setup our placeful workflow """ # Whoever creates the workspace should be added as an Admin creator = ob.Creator() IWorkspace(ob).add_to_team( user=creator, groups...
[ "def", "workspace_added", "(", "ob", ",", "event", ")", ":", "# Whoever creates the workspace should be added as an Admin", "creator", "=", "ob", ".", "Creator", "(", ")", "IWorkspace", "(", "ob", ")", ".", "add_to_team", "(", "user", "=", "creator", ",", "group...
when a workspace is created, we add the creator to the admin group. We then setup our placeful workflow
[ "when", "a", "workspace", "is", "created", "we", "add", "the", "creator", "to", "the", "admin", "group", ".", "We", "then", "setup", "our", "placeful", "workflow" ]
train
https://github.com/ploneintranet/ploneintranet.workspace/blob/a4fc7a5c61f9c6d4d4ad25478ff5250f342ffbba/src/ploneintranet/workspace/subscribers.py#L39-L59
ploneintranet/ploneintranet.workspace
src/ploneintranet/workspace/subscribers.py
participation_policy_changed
def participation_policy_changed(ob, event): """ Move all the existing users to a new group """ workspace = IWorkspace(ob) old_group_name = workspace.group_for_policy(event.old_policy) old_group = api.group.get(old_group_name) for member in old_group.getAllGroupMembers(): groups = workspace....
python
def participation_policy_changed(ob, event): """ Move all the existing users to a new group """ workspace = IWorkspace(ob) old_group_name = workspace.group_for_policy(event.old_policy) old_group = api.group.get(old_group_name) for member in old_group.getAllGroupMembers(): groups = workspace....
[ "def", "participation_policy_changed", "(", "ob", ",", "event", ")", ":", "workspace", "=", "IWorkspace", "(", "ob", ")", "old_group_name", "=", "workspace", ".", "group_for_policy", "(", "event", ".", "old_policy", ")", "old_group", "=", "api", ".", "group", ...
Move all the existing users to a new group
[ "Move", "all", "the", "existing", "users", "to", "a", "new", "group" ]
train
https://github.com/ploneintranet/ploneintranet.workspace/blob/a4fc7a5c61f9c6d4d4ad25478ff5250f342ffbba/src/ploneintranet/workspace/subscribers.py#L62-L70
ploneintranet/ploneintranet.workspace
src/ploneintranet/workspace/subscribers.py
invitation_accepted
def invitation_accepted(event): """ When an invitation is accepted, add the user to the team """ request = getRequest() storage = get_storage() if event.token_id not in storage: return ws_uid, username = storage[event.token_id] storage[event.token_id] acl_users = api.portal....
python
def invitation_accepted(event): """ When an invitation is accepted, add the user to the team """ request = getRequest() storage = get_storage() if event.token_id not in storage: return ws_uid, username = storage[event.token_id] storage[event.token_id] acl_users = api.portal....
[ "def", "invitation_accepted", "(", "event", ")", ":", "request", "=", "getRequest", "(", ")", "storage", "=", "get_storage", "(", ")", "if", "event", ".", "token_id", "not", "in", "storage", ":", "return", "ws_uid", ",", "username", "=", "storage", "[", ...
When an invitation is accepted, add the user to the team
[ "When", "an", "invitation", "is", "accepted", "add", "the", "user", "to", "the", "team" ]
train
https://github.com/ploneintranet/ploneintranet.workspace/blob/a4fc7a5c61f9c6d4d4ad25478ff5250f342ffbba/src/ploneintranet/workspace/subscribers.py#L73-L109
ploneintranet/ploneintranet.workspace
src/ploneintranet/workspace/subscribers.py
user_deleted_from_site_event
def user_deleted_from_site_event(event): """ Remove deleted user from all the workspaces where he is a member """ userid = event.principal catalog = api.portal.get_tool('portal_catalog') query = {'object_provides': WORKSPACE_INTERFACE} query['workspace_members'] = userid workspaces = [ ...
python
def user_deleted_from_site_event(event): """ Remove deleted user from all the workspaces where he is a member """ userid = event.principal catalog = api.portal.get_tool('portal_catalog') query = {'object_provides': WORKSPACE_INTERFACE} query['workspace_members'] = userid workspaces = [ ...
[ "def", "user_deleted_from_site_event", "(", "event", ")", ":", "userid", "=", "event", ".", "principal", "catalog", "=", "api", ".", "portal", ".", "get_tool", "(", "'portal_catalog'", ")", "query", "=", "{", "'object_provides'", ":", "WORKSPACE_INTERFACE", "}",...
Remove deleted user from all the workspaces where he is a member
[ "Remove", "deleted", "user", "from", "all", "the", "workspaces", "where", "he", "is", "a", "member" ]
train
https://github.com/ploneintranet/ploneintranet.workspace/blob/a4fc7a5c61f9c6d4d4ad25478ff5250f342ffbba/src/ploneintranet/workspace/subscribers.py#L112-L126
alexhayes/django-toolkit
django_toolkit/markup/comment_helper.py
get_object_comment_reference
def get_object_comment_reference(instance, title=None): """ Get an object reference for use within a comment so that it can be programatically referenced in the future (by a machine parsing the HTML...). """ span = '<span data-object-type="%s.%s" data-object-pk="%s">%s</span>' % ( instance._...
python
def get_object_comment_reference(instance, title=None): """ Get an object reference for use within a comment so that it can be programatically referenced in the future (by a machine parsing the HTML...). """ span = '<span data-object-type="%s.%s" data-object-pk="%s">%s</span>' % ( instance._...
[ "def", "get_object_comment_reference", "(", "instance", ",", "title", "=", "None", ")", ":", "span", "=", "'<span data-object-type=\"%s.%s\" data-object-pk=\"%s\">%s</span>'", "%", "(", "instance", ".", "__module__", ",", "instance", ".", "__class__", ".", "__name__", ...
Get an object reference for use within a comment so that it can be programatically referenced in the future (by a machine parsing the HTML...).
[ "Get", "an", "object", "reference", "for", "use", "within", "a", "comment", "so", "that", "it", "can", "be", "programatically", "referenced", "in", "the", "future", "(", "by", "a", "machine", "parsing", "the", "HTML", "...", ")", "." ]
train
https://github.com/alexhayes/django-toolkit/blob/b64106392fad596defc915b8235fe6e1d0013b5b/django_toolkit/markup/comment_helper.py#L2-L19
elkan1788/ppytools
ppytools/compresshelper.py
zipFile
def zipFile(source): """Compress file under zip mode when compress failed with return source path :param source: source file path :return: zip file path """ # source = source.decode('UTF-8') target = source[0:source.rindex(".")] + '.zip' try: with zipfile.ZipFile(target, 'w')...
python
def zipFile(source): """Compress file under zip mode when compress failed with return source path :param source: source file path :return: zip file path """ # source = source.decode('UTF-8') target = source[0:source.rindex(".")] + '.zip' try: with zipfile.ZipFile(target, 'w')...
[ "def", "zipFile", "(", "source", ")", ":", "# source = source.decode('UTF-8')", "target", "=", "source", "[", "0", ":", "source", ".", "rindex", "(", "\".\"", ")", "]", "+", "'.zip'", "try", ":", "with", "zipfile", ".", "ZipFile", "(", "target", ",", "'w...
Compress file under zip mode when compress failed with return source path :param source: source file path :return: zip file path
[ "Compress", "file", "under", "zip", "mode", "when", "compress", "failed", "with", "return", "source", "path", ":", "param", "source", ":", "source", "file", "path", ":", "return", ":", "zip", "file", "path" ]
train
https://github.com/elkan1788/ppytools/blob/117aeed9f669ae46e0dd6cb11c5687a5f797816c/ppytools/compresshelper.py#L16-L33
elkan1788/ppytools
ppytools/compresshelper.py
tarFile
def tarFile(source): """Compress file under tar mode which type more popular use in Unix operating system when compress failed with return source path :param source: source file path :return: zip file path """ # source = source.decode('UTF-8') target = source[0:source.rindex('.')...
python
def tarFile(source): """Compress file under tar mode which type more popular use in Unix operating system when compress failed with return source path :param source: source file path :return: zip file path """ # source = source.decode('UTF-8') target = source[0:source.rindex('.')...
[ "def", "tarFile", "(", "source", ")", ":", "# source = source.decode('UTF-8')", "target", "=", "source", "[", "0", ":", "source", ".", "rindex", "(", "'.'", ")", "]", "+", "'.tar.gz'", "try", ":", "with", "tarfile", ".", "open", "(", "target", ",", "\"w:...
Compress file under tar mode which type more popular use in Unix operating system when compress failed with return source path :param source: source file path :return: zip file path
[ "Compress", "file", "under", "tar", "mode", "which", "type", "more", "popular", "use", "in", "Unix", "operating", "system", "when", "compress", "failed", "with", "return", "source", "path", ":", "param", "source", ":", "source", "file", "path", ":", "return"...
train
https://github.com/elkan1788/ppytools/blob/117aeed9f669ae46e0dd6cb11c5687a5f797816c/ppytools/compresshelper.py#L36-L54
Bystroushaak/zeo_connector_defaults
src/zeo_connector_defaults/environment_generator.py
data_context_name
def data_context_name(fn): """ Return the `fn` in absolute path in `template_data` directory. """ return os.path.join(os.path.dirname(__file__), "template_data", fn)
python
def data_context_name(fn): """ Return the `fn` in absolute path in `template_data` directory. """ return os.path.join(os.path.dirname(__file__), "template_data", fn)
[ "def", "data_context_name", "(", "fn", ")", ":", "return", "os", ".", "path", ".", "join", "(", "os", ".", "path", ".", "dirname", "(", "__file__", ")", ",", "\"template_data\"", ",", "fn", ")" ]
Return the `fn` in absolute path in `template_data` directory.
[ "Return", "the", "fn", "in", "absolute", "path", "in", "template_data", "directory", "." ]
train
https://github.com/Bystroushaak/zeo_connector_defaults/blob/b54ecb99ddb4665db00fba183ef1d7252b0ca62b/src/zeo_connector_defaults/environment_generator.py#L24-L28
Bystroushaak/zeo_connector_defaults
src/zeo_connector_defaults/environment_generator.py
data_context
def data_context(fn, mode="r"): """ Return content fo the `fn` from the `template_data` directory. """ with open(data_context_name(fn), mode) as f: return f.read()
python
def data_context(fn, mode="r"): """ Return content fo the `fn` from the `template_data` directory. """ with open(data_context_name(fn), mode) as f: return f.read()
[ "def", "data_context", "(", "fn", ",", "mode", "=", "\"r\"", ")", ":", "with", "open", "(", "data_context_name", "(", "fn", ")", ",", "mode", ")", "as", "f", ":", "return", "f", ".", "read", "(", ")" ]
Return content fo the `fn` from the `template_data` directory.
[ "Return", "content", "fo", "the", "fn", "from", "the", "template_data", "directory", "." ]
train
https://github.com/Bystroushaak/zeo_connector_defaults/blob/b54ecb99ddb4665db00fba183ef1d7252b0ca62b/src/zeo_connector_defaults/environment_generator.py#L31-L36
Bystroushaak/zeo_connector_defaults
src/zeo_connector_defaults/environment_generator.py
tmp_context
def tmp_context(fn, mode="r"): """ Return content fo the `fn` from the temporary directory. """ with open(tmp_context_name(fn), mode) as f: return f.read()
python
def tmp_context(fn, mode="r"): """ Return content fo the `fn` from the temporary directory. """ with open(tmp_context_name(fn), mode) as f: return f.read()
[ "def", "tmp_context", "(", "fn", ",", "mode", "=", "\"r\"", ")", ":", "with", "open", "(", "tmp_context_name", "(", "fn", ")", ",", "mode", ")", "as", "f", ":", "return", "f", ".", "read", "(", ")" ]
Return content fo the `fn` from the temporary directory.
[ "Return", "content", "fo", "the", "fn", "from", "the", "temporary", "directory", "." ]
train
https://github.com/Bystroushaak/zeo_connector_defaults/blob/b54ecb99ddb4665db00fba183ef1d7252b0ca62b/src/zeo_connector_defaults/environment_generator.py#L49-L54
Bystroushaak/zeo_connector_defaults
src/zeo_connector_defaults/environment_generator.py
generate_environment
def generate_environment(): """ Generate the environment in ``/tmp`` and run the ZEO server process in another thread. """ global TMP_PATH TMP_PATH = tempfile.mkdtemp() # write ZEO server config to temp directory zeo_conf_path = os.path.join(TMP_PATH, "zeo.conf") with open(zeo_conf...
python
def generate_environment(): """ Generate the environment in ``/tmp`` and run the ZEO server process in another thread. """ global TMP_PATH TMP_PATH = tempfile.mkdtemp() # write ZEO server config to temp directory zeo_conf_path = os.path.join(TMP_PATH, "zeo.conf") with open(zeo_conf...
[ "def", "generate_environment", "(", ")", ":", "global", "TMP_PATH", "TMP_PATH", "=", "tempfile", ".", "mkdtemp", "(", ")", "# write ZEO server config to temp directory", "zeo_conf_path", "=", "os", ".", "path", ".", "join", "(", "TMP_PATH", ",", "\"zeo.conf\"", "...
Generate the environment in ``/tmp`` and run the ZEO server process in another thread.
[ "Generate", "the", "environment", "in", "/", "tmp", "and", "run", "the", "ZEO", "server", "process", "in", "another", "thread", "." ]
train
https://github.com/Bystroushaak/zeo_connector_defaults/blob/b54ecb99ddb4665db00fba183ef1d7252b0ca62b/src/zeo_connector_defaults/environment_generator.py#L58-L94
Bystroushaak/zeo_connector_defaults
src/zeo_connector_defaults/environment_generator.py
cleanup_environment
def cleanup_environment(): """ Shutdown the ZEO server process running in another thread and cleanup the temporary directory. """ SERV.terminate() shutil.rmtree(TMP_PATH) if os.path.exists(TMP_PATH): os.rmdir(TMP_PATH) global TMP_PATH TMP_PATH = None
python
def cleanup_environment(): """ Shutdown the ZEO server process running in another thread and cleanup the temporary directory. """ SERV.terminate() shutil.rmtree(TMP_PATH) if os.path.exists(TMP_PATH): os.rmdir(TMP_PATH) global TMP_PATH TMP_PATH = None
[ "def", "cleanup_environment", "(", ")", ":", "SERV", ".", "terminate", "(", ")", "shutil", ".", "rmtree", "(", "TMP_PATH", ")", "if", "os", ".", "path", ".", "exists", "(", "TMP_PATH", ")", ":", "os", ".", "rmdir", "(", "TMP_PATH", ")", "global", "TM...
Shutdown the ZEO server process running in another thread and cleanup the temporary directory.
[ "Shutdown", "the", "ZEO", "server", "process", "running", "in", "another", "thread", "and", "cleanup", "the", "temporary", "directory", "." ]
train
https://github.com/Bystroushaak/zeo_connector_defaults/blob/b54ecb99ddb4665db00fba183ef1d7252b0ca62b/src/zeo_connector_defaults/environment_generator.py#L97-L108
minhhoit/yacms
yacms/twitter/__init__.py
get_auth_settings
def get_auth_settings(): """ Returns all the key/secret settings for Twitter access, only if they're all defined. """ from yacms.conf import settings try: auth_settings = (settings.TWITTER_CONSUMER_KEY, settings.TWITTER_CONSUMER_SECRET, s...
python
def get_auth_settings(): """ Returns all the key/secret settings for Twitter access, only if they're all defined. """ from yacms.conf import settings try: auth_settings = (settings.TWITTER_CONSUMER_KEY, settings.TWITTER_CONSUMER_SECRET, s...
[ "def", "get_auth_settings", "(", ")", ":", "from", "yacms", ".", "conf", "import", "settings", "try", ":", "auth_settings", "=", "(", "settings", ".", "TWITTER_CONSUMER_KEY", ",", "settings", ".", "TWITTER_CONSUMER_SECRET", ",", "settings", ".", "TWITTER_ACCESS_TO...
Returns all the key/secret settings for Twitter access, only if they're all defined.
[ "Returns", "all", "the", "key", "/", "secret", "settings", "for", "Twitter", "access", "only", "if", "they", "re", "all", "defined", "." ]
train
https://github.com/minhhoit/yacms/blob/2921b706b7107c6e8c5f2bbf790ff11f85a2167f/yacms/twitter/__init__.py#L23-L37
dave-shawley/coercion
coercion.py
stringify
def stringify(obj): """ Return the string representation of an object. :param obj: object to get the representation of :returns: unicode string representation of `obj` or `obj` unchanged This function returns a string representation for many of the types from the standard library. It does not...
python
def stringify(obj): """ Return the string representation of an object. :param obj: object to get the representation of :returns: unicode string representation of `obj` or `obj` unchanged This function returns a string representation for many of the types from the standard library. It does not...
[ "def", "stringify", "(", "obj", ")", ":", "out", "=", "obj", "if", "isinstance", "(", "obj", ",", "uuid", ".", "UUID", ")", ":", "out", "=", "str", "(", "obj", ")", "elif", "hasattr", "(", "obj", ",", "'strftime'", ")", ":", "out", "=", "obj", ...
Return the string representation of an object. :param obj: object to get the representation of :returns: unicode string representation of `obj` or `obj` unchanged This function returns a string representation for many of the types from the standard library. It does not convert numeric or Boolean ...
[ "Return", "the", "string", "representation", "of", "an", "object", "." ]
train
https://github.com/dave-shawley/coercion/blob/152c91b99310364a7198020090d7d2197ebea94d/coercion.py#L15-L62
dave-shawley/coercion
coercion.py
normalize_collection
def normalize_collection(coll): """ Normalize all elements in a collection. :param coll: the collection to normalize. This is required to implement one of the following protocols: :class:`collections.Mapping`, :class:`collections.Sequence`, or :class:`collections.Set`. :return...
python
def normalize_collection(coll): """ Normalize all elements in a collection. :param coll: the collection to normalize. This is required to implement one of the following protocols: :class:`collections.Mapping`, :class:`collections.Sequence`, or :class:`collections.Set`. :return...
[ "def", "normalize_collection", "(", "coll", ")", ":", "#", "# The recursive version of this algorithm is something like:", "#", "# if isinstance(coll, dict):", "# return dict((stringify(k), normalize_collection(v))", "# for k, v in coll.items())", "# if isinst...
Normalize all elements in a collection. :param coll: the collection to normalize. This is required to implement one of the following protocols: :class:`collections.Mapping`, :class:`collections.Sequence`, or :class:`collections.Set`. :returns: a new instance of the input class with th...
[ "Normalize", "all", "elements", "in", "a", "collection", "." ]
train
https://github.com/dave-shawley/coercion/blob/152c91b99310364a7198020090d7d2197ebea94d/coercion.py#L65-L146
klmitch/vobj
vobj/version.py
SmartVersion.available
def available(self): """ Returns a set of the available versions. :returns: A set of integers giving the available versions. """ # Short-circuit if not self._schema: return set() # Build up the set of available versions avail = set(self._sch...
python
def available(self): """ Returns a set of the available versions. :returns: A set of integers giving the available versions. """ # Short-circuit if not self._schema: return set() # Build up the set of available versions avail = set(self._sch...
[ "def", "available", "(", "self", ")", ":", "# Short-circuit", "if", "not", "self", ".", "_schema", ":", "return", "set", "(", ")", "# Build up the set of available versions", "avail", "=", "set", "(", "self", ".", "_schema", ".", "__vers_downgraders__", ".", "...
Returns a set of the available versions. :returns: A set of integers giving the available versions.
[ "Returns", "a", "set", "of", "the", "available", "versions", "." ]
train
https://github.com/klmitch/vobj/blob/4952658dc0914fe92afb2ef6e5ccca2829de6cb2/vobj/version.py#L101-L116
rackerlabs/rackspace-python-neutronclient
neutronclient/neutron/v2_0/__init__.py
parse_args_to_dict
def parse_args_to_dict(values_specs): """It is used to analyze the extra command options to command. Besides known options and arguments, our commands also support user to put more options to the end of command line. For example, list_nets -- --tag x y --key1 value1, where '-- --tag x y --key1 value1' ...
python
def parse_args_to_dict(values_specs): """It is used to analyze the extra command options to command. Besides known options and arguments, our commands also support user to put more options to the end of command line. For example, list_nets -- --tag x y --key1 value1, where '-- --tag x y --key1 value1' ...
[ "def", "parse_args_to_dict", "(", "values_specs", ")", ":", "# values_specs for example: '-- --tag x y --key1 type=int value1'", "# -- is a pseudo argument", "values_specs_copy", "=", "values_specs", "[", ":", "]", "if", "values_specs_copy", "and", "values_specs_copy", "[", "0"...
It is used to analyze the extra command options to command. Besides known options and arguments, our commands also support user to put more options to the end of command line. For example, list_nets -- --tag x y --key1 value1, where '-- --tag x y --key1 value1' is extra options to our list_nets. This f...
[ "It", "is", "used", "to", "analyze", "the", "extra", "command", "options", "to", "command", "." ]
train
https://github.com/rackerlabs/rackspace-python-neutronclient/blob/5a5009a8fe078e3aa1d582176669f1b28ab26bef/neutronclient/neutron/v2_0/__init__.py#L229-L342
rackerlabs/rackspace-python-neutronclient
neutronclient/neutron/v2_0/__init__.py
_merge_args
def _merge_args(qCmd, parsed_args, _extra_values, value_specs): """Merge arguments from _extra_values into parsed_args. If an argument value are provided in both and it is a list, the values in _extra_values will be merged into parsed_args. @param parsed_args: the parsed args from known options @p...
python
def _merge_args(qCmd, parsed_args, _extra_values, value_specs): """Merge arguments from _extra_values into parsed_args. If an argument value are provided in both and it is a list, the values in _extra_values will be merged into parsed_args. @param parsed_args: the parsed args from known options @p...
[ "def", "_merge_args", "(", "qCmd", ",", "parsed_args", ",", "_extra_values", ",", "value_specs", ")", ":", "temp_values", "=", "_extra_values", ".", "copy", "(", ")", "for", "key", ",", "value", "in", "six", ".", "iteritems", "(", "temp_values", ")", ":", ...
Merge arguments from _extra_values into parsed_args. If an argument value are provided in both and it is a list, the values in _extra_values will be merged into parsed_args. @param parsed_args: the parsed args from known options @param _extra_values: the other parsed arguments in unknown parts @pa...
[ "Merge", "arguments", "from", "_extra_values", "into", "parsed_args", "." ]
train
https://github.com/rackerlabs/rackspace-python-neutronclient/blob/5a5009a8fe078e3aa1d582176669f1b28ab26bef/neutronclient/neutron/v2_0/__init__.py#L345-L365
rackerlabs/rackspace-python-neutronclient
neutronclient/neutron/v2_0/__init__.py
update_dict
def update_dict(obj, dict, attributes): """Update dict with fields from obj.attributes. :param obj: the object updated into dict :param dict: the result dictionary :param attributes: a list of attributes belonging to obj """ for attribute in attributes: if hasattr(obj, attribute) and ge...
python
def update_dict(obj, dict, attributes): """Update dict with fields from obj.attributes. :param obj: the object updated into dict :param dict: the result dictionary :param attributes: a list of attributes belonging to obj """ for attribute in attributes: if hasattr(obj, attribute) and ge...
[ "def", "update_dict", "(", "obj", ",", "dict", ",", "attributes", ")", ":", "for", "attribute", "in", "attributes", ":", "if", "hasattr", "(", "obj", ",", "attribute", ")", "and", "getattr", "(", "obj", ",", "attribute", ")", "is", "not", "None", ":", ...
Update dict with fields from obj.attributes. :param obj: the object updated into dict :param dict: the result dictionary :param attributes: a list of attributes belonging to obj
[ "Update", "dict", "with", "fields", "from", "obj", ".", "attributes", "." ]
train
https://github.com/rackerlabs/rackspace-python-neutronclient/blob/5a5009a8fe078e3aa1d582176669f1b28ab26bef/neutronclient/neutron/v2_0/__init__.py#L368-L377