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 |
|---|---|---|---|---|---|---|---|---|---|---|
thisfred/val | val/tp.py | _translate_struct | def _translate_struct(inner_dict):
"""Translate a teleport Struct into a val subschema."""
try:
optional = inner_dict['optional'].items()
required = inner_dict['required'].items()
except KeyError as ex:
raise DeserializationError("Missing key: {}".format(ex))
except AttributeErro... | python | def _translate_struct(inner_dict):
"""Translate a teleport Struct into a val subschema."""
try:
optional = inner_dict['optional'].items()
required = inner_dict['required'].items()
except KeyError as ex:
raise DeserializationError("Missing key: {}".format(ex))
except AttributeErro... | [
"def",
"_translate_struct",
"(",
"inner_dict",
")",
":",
"try",
":",
"optional",
"=",
"inner_dict",
"[",
"'optional'",
"]",
".",
"items",
"(",
")",
"required",
"=",
"inner_dict",
"[",
"'required'",
"]",
".",
"items",
"(",
")",
"except",
"KeyError",
"as",
... | Translate a teleport Struct into a val subschema. | [
"Translate",
"a",
"teleport",
"Struct",
"into",
"a",
"val",
"subschema",
"."
] | train | https://github.com/thisfred/val/blob/ba022e0c6c47acb3b8a45e7c44c84cc0f495c41c/val/tp.py#L76-L89 |
thisfred/val | val/tp.py | _translate_composite | def _translate_composite(teleport_value):
"""Translate a composite teleport value into a val subschema."""
for key in ("Array", "Map", "Struct"):
value = teleport_value.get(key)
if value is None:
continue
return COMPOSITES[key](value)
raise DeserializationError(
... | python | def _translate_composite(teleport_value):
"""Translate a composite teleport value into a val subschema."""
for key in ("Array", "Map", "Struct"):
value = teleport_value.get(key)
if value is None:
continue
return COMPOSITES[key](value)
raise DeserializationError(
... | [
"def",
"_translate_composite",
"(",
"teleport_value",
")",
":",
"for",
"key",
"in",
"(",
"\"Array\"",
",",
"\"Map\"",
",",
"\"Struct\"",
")",
":",
"value",
"=",
"teleport_value",
".",
"get",
"(",
"key",
")",
"if",
"value",
"is",
"None",
":",
"continue",
... | Translate a composite teleport value into a val subschema. | [
"Translate",
"a",
"composite",
"teleport",
"value",
"into",
"a",
"val",
"subschema",
"."
] | train | https://github.com/thisfred/val/blob/ba022e0c6c47acb3b8a45e7c44c84cc0f495c41c/val/tp.py#L98-L107 |
thisfred/val | val/tp.py | _translate | def _translate(teleport_value):
"""Translate a teleport value in to a val subschema."""
if isinstance(teleport_value, dict):
return _translate_composite(teleport_value)
if teleport_value in PRIMITIVES:
return PRIMITIVES[teleport_value]
raise DeserializationError(
"Could not int... | python | def _translate(teleport_value):
"""Translate a teleport value in to a val subschema."""
if isinstance(teleport_value, dict):
return _translate_composite(teleport_value)
if teleport_value in PRIMITIVES:
return PRIMITIVES[teleport_value]
raise DeserializationError(
"Could not int... | [
"def",
"_translate",
"(",
"teleport_value",
")",
":",
"if",
"isinstance",
"(",
"teleport_value",
",",
"dict",
")",
":",
"return",
"_translate_composite",
"(",
"teleport_value",
")",
"if",
"teleport_value",
"in",
"PRIMITIVES",
":",
"return",
"PRIMITIVES",
"[",
"t... | Translate a teleport value in to a val subschema. | [
"Translate",
"a",
"teleport",
"value",
"in",
"to",
"a",
"val",
"subschema",
"."
] | train | https://github.com/thisfred/val/blob/ba022e0c6c47acb3b8a45e7c44c84cc0f495c41c/val/tp.py#L110-L119 |
thisfred/val | val/tp.py | to_val | def to_val(teleport_schema):
"""Convert a parsed teleport schema to a val schema."""
translated = _translate(teleport_schema)
if isinstance(translated, BaseSchema):
return translated
return Schema(translated) | python | def to_val(teleport_schema):
"""Convert a parsed teleport schema to a val schema."""
translated = _translate(teleport_schema)
if isinstance(translated, BaseSchema):
return translated
return Schema(translated) | [
"def",
"to_val",
"(",
"teleport_schema",
")",
":",
"translated",
"=",
"_translate",
"(",
"teleport_schema",
")",
"if",
"isinstance",
"(",
"translated",
",",
"BaseSchema",
")",
":",
"return",
"translated",
"return",
"Schema",
"(",
"translated",
")"
] | Convert a parsed teleport schema to a val schema. | [
"Convert",
"a",
"parsed",
"teleport",
"schema",
"to",
"a",
"val",
"schema",
"."
] | train | https://github.com/thisfred/val/blob/ba022e0c6c47acb3b8a45e7c44c84cc0f495c41c/val/tp.py#L122-L128 |
thisfred/val | val/tp.py | _dict_to_teleport | def _dict_to_teleport(dict_value):
"""Convert a val schema dictionary to teleport."""
if len(dict_value) == 1:
for key, value in dict_value.items():
if key is str:
return {"Map": from_val(value)}
optional = {}
required = {}
for key, value in dict_value.items():
... | python | def _dict_to_teleport(dict_value):
"""Convert a val schema dictionary to teleport."""
if len(dict_value) == 1:
for key, value in dict_value.items():
if key is str:
return {"Map": from_val(value)}
optional = {}
required = {}
for key, value in dict_value.items():
... | [
"def",
"_dict_to_teleport",
"(",
"dict_value",
")",
":",
"if",
"len",
"(",
"dict_value",
")",
"==",
"1",
":",
"for",
"key",
",",
"value",
"in",
"dict_value",
".",
"items",
"(",
")",
":",
"if",
"key",
"is",
"str",
":",
"return",
"{",
"\"Map\"",
":",
... | Convert a val schema dictionary to teleport. | [
"Convert",
"a",
"val",
"schema",
"dictionary",
"to",
"teleport",
"."
] | train | https://github.com/thisfred/val/blob/ba022e0c6c47acb3b8a45e7c44c84cc0f495c41c/val/tp.py#L131-L148 |
thisfred/val | val/tp.py | from_val | def from_val(val_schema):
"""Serialize a val schema to teleport."""
definition = getattr(val_schema, "definition", val_schema) if isinstance(
val_schema, BaseSchema) else val_schema
if isinstance(definition, dict):
return _dict_to_teleport(definition)
if isinstance(definition, list):
... | python | def from_val(val_schema):
"""Serialize a val schema to teleport."""
definition = getattr(val_schema, "definition", val_schema) if isinstance(
val_schema, BaseSchema) else val_schema
if isinstance(definition, dict):
return _dict_to_teleport(definition)
if isinstance(definition, list):
... | [
"def",
"from_val",
"(",
"val_schema",
")",
":",
"definition",
"=",
"getattr",
"(",
"val_schema",
",",
"\"definition\"",
",",
"val_schema",
")",
"if",
"isinstance",
"(",
"val_schema",
",",
"BaseSchema",
")",
"else",
"val_schema",
"if",
"isinstance",
"(",
"defin... | Serialize a val schema to teleport. | [
"Serialize",
"a",
"val",
"schema",
"to",
"teleport",
"."
] | train | https://github.com/thisfred/val/blob/ba022e0c6c47acb3b8a45e7c44c84cc0f495c41c/val/tp.py#L151-L167 |
thisfred/val | val/tp.py | document | def document(schema):
"""Print a documented teleport version of the schema."""
teleport_schema = from_val(schema)
return json.dumps(teleport_schema, sort_keys=True, indent=2) | python | def document(schema):
"""Print a documented teleport version of the schema."""
teleport_schema = from_val(schema)
return json.dumps(teleport_schema, sort_keys=True, indent=2) | [
"def",
"document",
"(",
"schema",
")",
":",
"teleport_schema",
"=",
"from_val",
"(",
"schema",
")",
"return",
"json",
".",
"dumps",
"(",
"teleport_schema",
",",
"sort_keys",
"=",
"True",
",",
"indent",
"=",
"2",
")"
] | Print a documented teleport version of the schema. | [
"Print",
"a",
"documented",
"teleport",
"version",
"of",
"the",
"schema",
"."
] | train | https://github.com/thisfred/val/blob/ba022e0c6c47acb3b8a45e7c44c84cc0f495c41c/val/tp.py#L170-L173 |
diffeo/rejester | rejester/_registry.py | nice_identifier | def nice_identifier():
'do not use uuid.uuid4, because it can block'
big = reduce(mul, struct.unpack('<LLLL', os.urandom(16)), 1)
big = big % 2**128
return uuid.UUID(int=big).hex | python | def nice_identifier():
'do not use uuid.uuid4, because it can block'
big = reduce(mul, struct.unpack('<LLLL', os.urandom(16)), 1)
big = big % 2**128
return uuid.UUID(int=big).hex | [
"def",
"nice_identifier",
"(",
")",
":",
"big",
"=",
"reduce",
"(",
"mul",
",",
"struct",
".",
"unpack",
"(",
"'<LLLL'",
",",
"os",
".",
"urandom",
"(",
"16",
")",
")",
",",
"1",
")",
"big",
"=",
"big",
"%",
"2",
"**",
"128",
"return",
"uuid",
... | do not use uuid.uuid4, because it can block | [
"do",
"not",
"use",
"uuid",
".",
"uuid4",
"because",
"it",
"can",
"block"
] | train | https://github.com/diffeo/rejester/blob/5438a4a18be2801d7826c46e2079ba9639d2ecb4/rejester/_registry.py#L30-L34 |
diffeo/rejester | rejester/_registry.py | Registry._acquire_lock | def _acquire_lock(self, identifier, atime=30, ltime=5):
'''Acquire a lock for a given identifier.
If the lock cannot be obtained immediately, keep trying at random
intervals, up to 3 seconds, until `atime` has passed. Once the
lock has been obtained, continue to hold it for `ltime`.
... | python | def _acquire_lock(self, identifier, atime=30, ltime=5):
'''Acquire a lock for a given identifier.
If the lock cannot be obtained immediately, keep trying at random
intervals, up to 3 seconds, until `atime` has passed. Once the
lock has been obtained, continue to hold it for `ltime`.
... | [
"def",
"_acquire_lock",
"(",
"self",
",",
"identifier",
",",
"atime",
"=",
"30",
",",
"ltime",
"=",
"5",
")",
":",
"conn",
"=",
"redis",
".",
"Redis",
"(",
"connection_pool",
"=",
"self",
".",
"pool",
")",
"end",
"=",
"time",
".",
"time",
"(",
")",... | Acquire a lock for a given identifier.
If the lock cannot be obtained immediately, keep trying at random
intervals, up to 3 seconds, until `atime` has passed. Once the
lock has been obtained, continue to hold it for `ltime`.
:param str identifier: lock token to write
:param in... | [
"Acquire",
"a",
"lock",
"for",
"a",
"given",
"identifier",
"."
] | train | https://github.com/diffeo/rejester/blob/5438a4a18be2801d7826c46e2079ba9639d2ecb4/rejester/_registry.py#L104-L129 |
diffeo/rejester | rejester/_registry.py | Registry.re_acquire_lock | def re_acquire_lock(self, ltime=5):
'''Re-acquire the lock.
You must already own the lock; this is best called from
within a :meth:`lock` block.
:param int ltime: maximum time (in seconds) to own lock
:return: the session lock identifier
:raise rejester.exceptions.Envir... | python | def re_acquire_lock(self, ltime=5):
'''Re-acquire the lock.
You must already own the lock; this is best called from
within a :meth:`lock` block.
:param int ltime: maximum time (in seconds) to own lock
:return: the session lock identifier
:raise rejester.exceptions.Envir... | [
"def",
"re_acquire_lock",
"(",
"self",
",",
"ltime",
"=",
"5",
")",
":",
"conn",
"=",
"redis",
".",
"Redis",
"(",
"connection_pool",
"=",
"self",
".",
"pool",
")",
"script",
"=",
"conn",
".",
"register_script",
"(",
"'''\n if redis.call(\"get\", KEYS[1]... | Re-acquire the lock.
You must already own the lock; this is best called from
within a :meth:`lock` block.
:param int ltime: maximum time (in seconds) to own lock
:return: the session lock identifier
:raise rejester.exceptions.EnvironmentError:
if we didn't already own... | [
"Re",
"-",
"acquire",
"the",
"lock",
"."
] | train | https://github.com/diffeo/rejester/blob/5438a4a18be2801d7826c46e2079ba9639d2ecb4/rejester/_registry.py#L131-L158 |
diffeo/rejester | rejester/_registry.py | Registry._release_lock | def _release_lock(self, identifier):
'''Release the lock.
This requires you to actually have owned the lock. On return
you definitely do not own it, but if somebody else owned it
before calling this function, they still do.
:param str identifier: the session lock identifier
... | python | def _release_lock(self, identifier):
'''Release the lock.
This requires you to actually have owned the lock. On return
you definitely do not own it, but if somebody else owned it
before calling this function, they still do.
:param str identifier: the session lock identifier
... | [
"def",
"_release_lock",
"(",
"self",
",",
"identifier",
")",
":",
"conn",
"=",
"redis",
".",
"Redis",
"(",
"connection_pool",
"=",
"self",
".",
"pool",
")",
"script",
"=",
"conn",
".",
"register_script",
"(",
"'''\n if redis.call(\"get\", KEYS[1]) == ARGV[1... | Release the lock.
This requires you to actually have owned the lock. On return
you definitely do not own it, but if somebody else owned it
before calling this function, they still do.
:param str identifier: the session lock identifier
:return: :const:`True` if you actually did... | [
"Release",
"the",
"lock",
"."
] | train | https://github.com/diffeo/rejester/blob/5438a4a18be2801d7826c46e2079ba9639d2ecb4/rejester/_registry.py#L160-L183 |
diffeo/rejester | rejester/_registry.py | Registry.lock | def lock(self, atime=30, ltime=5, identifier=None):
'''Context manager to acquire the namespace global lock.
This is typically used for multi-step registry operations,
such as a read-modify-write sequence::
with registry.lock() as session:
d = session.get('dict', 'k... | python | def lock(self, atime=30, ltime=5, identifier=None):
'''Context manager to acquire the namespace global lock.
This is typically used for multi-step registry operations,
such as a read-modify-write sequence::
with registry.lock() as session:
d = session.get('dict', 'k... | [
"def",
"lock",
"(",
"self",
",",
"atime",
"=",
"30",
",",
"ltime",
"=",
"5",
",",
"identifier",
"=",
"None",
")",
":",
"if",
"identifier",
"is",
"None",
":",
"identifier",
"=",
"nice_identifier",
"(",
")",
"if",
"self",
".",
"_acquire_lock",
"(",
"id... | Context manager to acquire the namespace global lock.
This is typically used for multi-step registry operations,
such as a read-modify-write sequence::
with registry.lock() as session:
d = session.get('dict', 'key')
del d['traceback']
session... | [
"Context",
"manager",
"to",
"acquire",
"the",
"namespace",
"global",
"lock",
"."
] | train | https://github.com/diffeo/rejester/blob/5438a4a18be2801d7826c46e2079ba9639d2ecb4/rejester/_registry.py#L186-L216 |
diffeo/rejester | rejester/_registry.py | Registry.read_lock | def read_lock(self):
'''Find out who currently owns the namespace global lock.
This is purely a diagnostic tool. If you are trying to get
the global lock, it is better to just call :meth:`lock`, which
will atomically get the lock if possible and retry.
:return: session identif... | python | def read_lock(self):
'''Find out who currently owns the namespace global lock.
This is purely a diagnostic tool. If you are trying to get
the global lock, it is better to just call :meth:`lock`, which
will atomically get the lock if possible and retry.
:return: session identif... | [
"def",
"read_lock",
"(",
"self",
")",
":",
"return",
"redis",
".",
"Redis",
"(",
"connection_pool",
"=",
"self",
".",
"pool",
")",
".",
"get",
"(",
"self",
".",
"_lock_name",
")"
] | Find out who currently owns the namespace global lock.
This is purely a diagnostic tool. If you are trying to get
the global lock, it is better to just call :meth:`lock`, which
will atomically get the lock if possible and retry.
:return: session identifier of the lock holder, or :cons... | [
"Find",
"out",
"who",
"currently",
"owns",
"the",
"namespace",
"global",
"lock",
"."
] | train | https://github.com/diffeo/rejester/blob/5438a4a18be2801d7826c46e2079ba9639d2ecb4/rejester/_registry.py#L218-L228 |
diffeo/rejester | rejester/_registry.py | Registry.force_clear_lock | def force_clear_lock(self):
'''Kick out whoever currently owns the namespace global lock.
This is intended as purely a last-resort tool. If another
process has managed to get the global lock for a very long time,
or if it requested the lock with a long expiration and then
crash... | python | def force_clear_lock(self):
'''Kick out whoever currently owns the namespace global lock.
This is intended as purely a last-resort tool. If another
process has managed to get the global lock for a very long time,
or if it requested the lock with a long expiration and then
crash... | [
"def",
"force_clear_lock",
"(",
"self",
")",
":",
"return",
"redis",
".",
"Redis",
"(",
"connection_pool",
"=",
"self",
".",
"pool",
")",
".",
"delete",
"(",
"self",
".",
"_lock_name",
")"
] | Kick out whoever currently owns the namespace global lock.
This is intended as purely a last-resort tool. If another
process has managed to get the global lock for a very long time,
or if it requested the lock with a long expiration and then
crashed, this can make the system functional... | [
"Kick",
"out",
"whoever",
"currently",
"owns",
"the",
"namespace",
"global",
"lock",
"."
] | train | https://github.com/diffeo/rejester/blob/5438a4a18be2801d7826c46e2079ba9639d2ecb4/rejester/_registry.py#L230-L241 |
diffeo/rejester | rejester/_registry.py | Registry.update | def update(self, dict_name, mapping=None, priorities=None, expire=None,
locks=None):
'''Add mapping to a dictionary, replacing previous values
Can be called with only dict_name and expire to refresh the
expiration time.
NB: locks are only enforced if present, so nothing ... | python | def update(self, dict_name, mapping=None, priorities=None, expire=None,
locks=None):
'''Add mapping to a dictionary, replacing previous values
Can be called with only dict_name and expire to refresh the
expiration time.
NB: locks are only enforced if present, so nothing ... | [
"def",
"update",
"(",
"self",
",",
"dict_name",
",",
"mapping",
"=",
"None",
",",
"priorities",
"=",
"None",
",",
"expire",
"=",
"None",
",",
"locks",
"=",
"None",
")",
":",
"if",
"self",
".",
"_session_lock_identifier",
"is",
"None",
":",
"raise",
"Pr... | Add mapping to a dictionary, replacing previous values
Can be called with only dict_name and expire to refresh the
expiration time.
NB: locks are only enforced if present, so nothing prevents
another caller from coming in an modifying data without using
locks.
:param m... | [
"Add",
"mapping",
"to",
"a",
"dictionary",
"replacing",
"previous",
"values"
] | train | https://github.com/diffeo/rejester/blob/5438a4a18be2801d7826c46e2079ba9639d2ecb4/rejester/_registry.py#L263-L350 |
diffeo/rejester | rejester/_registry.py | Registry.reset_priorities | def reset_priorities(self, dict_name, priority):
'''set all priorities in dict_name to priority
:type priority: float or int
'''
if self._session_lock_identifier is None:
raise ProgrammerError('must acquire lock first')
## see comment above for script in update
... | python | def reset_priorities(self, dict_name, priority):
'''set all priorities in dict_name to priority
:type priority: float or int
'''
if self._session_lock_identifier is None:
raise ProgrammerError('must acquire lock first')
## see comment above for script in update
... | [
"def",
"reset_priorities",
"(",
"self",
",",
"dict_name",
",",
"priority",
")",
":",
"if",
"self",
".",
"_session_lock_identifier",
"is",
"None",
":",
"raise",
"ProgrammerError",
"(",
"'must acquire lock first'",
")",
"## see comment above for script in update",
"conn",... | set all priorities in dict_name to priority
:type priority: float or int | [
"set",
"all",
"priorities",
"in",
"dict_name",
"to",
"priority"
] | train | https://github.com/diffeo/rejester/blob/5438a4a18be2801d7826c46e2079ba9639d2ecb4/rejester/_registry.py#L353-L383 |
diffeo/rejester | rejester/_registry.py | Registry.len | def len(self, dict_name, priority_min='-inf', priority_max='+inf'):
'''Get the number of items in (part of) a dictionary.
Returns number of items in `dict_name` within
[`priority_min`, `priority_max`]. This is similar to
``len(filter(dict_name, priority_min, priority_max))`` but
... | python | def len(self, dict_name, priority_min='-inf', priority_max='+inf'):
'''Get the number of items in (part of) a dictionary.
Returns number of items in `dict_name` within
[`priority_min`, `priority_max`]. This is similar to
``len(filter(dict_name, priority_min, priority_max))`` but
... | [
"def",
"len",
"(",
"self",
",",
"dict_name",
",",
"priority_min",
"=",
"'-inf'",
",",
"priority_max",
"=",
"'+inf'",
")",
":",
"dict_name",
"=",
"self",
".",
"_namespace",
"(",
"dict_name",
")",
"conn",
"=",
"redis",
".",
"Redis",
"(",
"connection_pool",
... | Get the number of items in (part of) a dictionary.
Returns number of items in `dict_name` within
[`priority_min`, `priority_max`]. This is similar to
``len(filter(dict_name, priority_min, priority_max))`` but
does not actually retrieve the items.
This is a read-only operation ... | [
"Get",
"the",
"number",
"of",
"items",
"in",
"(",
"part",
"of",
")",
"a",
"dictionary",
"."
] | train | https://github.com/diffeo/rejester/blob/5438a4a18be2801d7826c46e2079ba9639d2ecb4/rejester/_registry.py#L433-L450 |
diffeo/rejester | rejester/_registry.py | Registry.popitem | def popitem(self, dict_name, priority_min='-inf', priority_max='+inf'):
'''Select an item and remove it.
The item comes from `dict_name`, and has the lowest score
at least `priority_min` and at most `priority_max`. If some
item is found, remove it from `dict_name` and return it.
... | python | def popitem(self, dict_name, priority_min='-inf', priority_max='+inf'):
'''Select an item and remove it.
The item comes from `dict_name`, and has the lowest score
at least `priority_min` and at most `priority_max`. If some
item is found, remove it from `dict_name` and return it.
... | [
"def",
"popitem",
"(",
"self",
",",
"dict_name",
",",
"priority_min",
"=",
"'-inf'",
",",
"priority_max",
"=",
"'+inf'",
")",
":",
"if",
"self",
".",
"_session_lock_identifier",
"is",
"None",
":",
"raise",
"ProgrammerError",
"(",
"'must acquire lock first'",
")"... | Select an item and remove it.
The item comes from `dict_name`, and has the lowest score
at least `priority_min` and at most `priority_max`. If some
item is found, remove it from `dict_name` and return it.
This runs as a single atomic operation but still requires a
session lock... | [
"Select",
"an",
"item",
"and",
"remove",
"it",
"."
] | train | https://github.com/diffeo/rejester/blob/5438a4a18be2801d7826c46e2079ba9639d2ecb4/rejester/_registry.py#L524-L579 |
diffeo/rejester | rejester/_registry.py | Registry.popitem_move | def popitem_move(self, from_dict, to_dict,
priority_min='-inf', priority_max='+inf'):
'''Select an item and move it to another dictionary.
The item comes from `from_dict`, and has the lowest score
at least `priority_min` and at most `priority_max`. If some
item is ... | python | def popitem_move(self, from_dict, to_dict,
priority_min='-inf', priority_max='+inf'):
'''Select an item and move it to another dictionary.
The item comes from `from_dict`, and has the lowest score
at least `priority_min` and at most `priority_max`. If some
item is ... | [
"def",
"popitem_move",
"(",
"self",
",",
"from_dict",
",",
"to_dict",
",",
"priority_min",
"=",
"'-inf'",
",",
"priority_max",
"=",
"'+inf'",
")",
":",
"if",
"self",
".",
"_session_lock_identifier",
"is",
"None",
":",
"raise",
"ProgrammerError",
"(",
"'must ac... | Select an item and move it to another dictionary.
The item comes from `from_dict`, and has the lowest score
at least `priority_min` and at most `priority_max`. If some
item is found, remove it from `from_dict`, add it to `to_dict`,
and return it.
This runs as a single atomic o... | [
"Select",
"an",
"item",
"and",
"move",
"it",
"to",
"another",
"dictionary",
"."
] | train | https://github.com/diffeo/rejester/blob/5438a4a18be2801d7826c46e2079ba9639d2ecb4/rejester/_registry.py#L581-L650 |
diffeo/rejester | rejester/_registry.py | Registry.move | def move(self, from_dict, to_dict, mapping, priority=None):
'''Move keys between dictionaries, possibly with changes.
Every key in `mapping` is removed from `from_dict`, and added to
`to_dict` with its corresponding value. The priority will be
`priority`, if specified, or else its curr... | python | def move(self, from_dict, to_dict, mapping, priority=None):
'''Move keys between dictionaries, possibly with changes.
Every key in `mapping` is removed from `from_dict`, and added to
`to_dict` with its corresponding value. The priority will be
`priority`, if specified, or else its curr... | [
"def",
"move",
"(",
"self",
",",
"from_dict",
",",
"to_dict",
",",
"mapping",
",",
"priority",
"=",
"None",
")",
":",
"items",
"=",
"[",
"]",
"## This flattens the dictionary into a list",
"for",
"key",
",",
"value",
"in",
"mapping",
".",
"iteritems",
"(",
... | Move keys between dictionaries, possibly with changes.
Every key in `mapping` is removed from `from_dict`, and added to
`to_dict` with its corresponding value. The priority will be
`priority`, if specified, or else its current priority.
This operation on its own is atomic and does not... | [
"Move",
"keys",
"between",
"dictionaries",
"possibly",
"with",
"changes",
"."
] | train | https://github.com/diffeo/rejester/blob/5438a4a18be2801d7826c46e2079ba9639d2ecb4/rejester/_registry.py#L652-L725 |
diffeo/rejester | rejester/_registry.py | Registry.move_all | def move_all(self, from_dict, to_dict):
'''Move everything from one dictionary to another.
This can be expensive if the source dictionary is large.
This always requires a session lock.
:param str from_dict: source dictionary
:param str to_dict: destination dictionary
... | python | def move_all(self, from_dict, to_dict):
'''Move everything from one dictionary to another.
This can be expensive if the source dictionary is large.
This always requires a session lock.
:param str from_dict: source dictionary
:param str to_dict: destination dictionary
... | [
"def",
"move_all",
"(",
"self",
",",
"from_dict",
",",
"to_dict",
")",
":",
"if",
"self",
".",
"_session_lock_identifier",
"is",
"None",
":",
"raise",
"ProgrammerError",
"(",
"'must acquire lock first'",
")",
"conn",
"=",
"redis",
".",
"Redis",
"(",
"connectio... | Move everything from one dictionary to another.
This can be expensive if the source dictionary is large.
This always requires a session lock.
:param str from_dict: source dictionary
:param str to_dict: destination dictionary | [
"Move",
"everything",
"from",
"one",
"dictionary",
"to",
"another",
"."
] | train | https://github.com/diffeo/rejester/blob/5438a4a18be2801d7826c46e2079ba9639d2ecb4/rejester/_registry.py#L728-L772 |
diffeo/rejester | rejester/_registry.py | Registry.pull | def pull(self, dict_name):
'''Get the entire contents of a single dictionary.
This operates without a session lock, but is still atomic. In
particular this will run even if someone else holds a session
lock and you do not.
This is only suitable for "small" dictionaries; if you... | python | def pull(self, dict_name):
'''Get the entire contents of a single dictionary.
This operates without a session lock, but is still atomic. In
particular this will run even if someone else holds a session
lock and you do not.
This is only suitable for "small" dictionaries; if you... | [
"def",
"pull",
"(",
"self",
",",
"dict_name",
")",
":",
"dict_name",
"=",
"self",
".",
"_namespace",
"(",
"dict_name",
")",
"conn",
"=",
"redis",
".",
"Redis",
"(",
"connection_pool",
"=",
"self",
".",
"pool",
")",
"res",
"=",
"conn",
".",
"hgetall",
... | Get the entire contents of a single dictionary.
This operates without a session lock, but is still atomic. In
particular this will run even if someone else holds a session
lock and you do not.
This is only suitable for "small" dictionaries; if you have
hundreds of thousands of... | [
"Get",
"the",
"entire",
"contents",
"of",
"a",
"single",
"dictionary",
"."
] | train | https://github.com/diffeo/rejester/blob/5438a4a18be2801d7826c46e2079ba9639d2ecb4/rejester/_registry.py#L775-L796 |
diffeo/rejester | rejester/_registry.py | Registry.filter | def filter(self, dict_name, priority_min='-inf', priority_max='+inf',
start=0, limit=None):
'''Get a subset of a dictionary.
This retrieves only keys with priority scores greater than or
equal to `priority_min` and less than or equal to `priority_max`.
Of those keys, it s... | python | def filter(self, dict_name, priority_min='-inf', priority_max='+inf',
start=0, limit=None):
'''Get a subset of a dictionary.
This retrieves only keys with priority scores greater than or
equal to `priority_min` and less than or equal to `priority_max`.
Of those keys, it s... | [
"def",
"filter",
"(",
"self",
",",
"dict_name",
",",
"priority_min",
"=",
"'-inf'",
",",
"priority_max",
"=",
"'+inf'",
",",
"start",
"=",
"0",
",",
"limit",
"=",
"None",
")",
":",
"conn",
"=",
"redis",
".",
"Redis",
"(",
"connection_pool",
"=",
"self"... | Get a subset of a dictionary.
This retrieves only keys with priority scores greater than or
equal to `priority_min` and less than or equal to `priority_max`.
Of those keys, it skips the first `start` ones, and then returns
at most `limit` keys.
With default parameters, this ret... | [
"Get",
"a",
"subset",
"of",
"a",
"dictionary",
"."
] | train | https://github.com/diffeo/rejester/blob/5438a4a18be2801d7826c46e2079ba9639d2ecb4/rejester/_registry.py#L798-L865 |
diffeo/rejester | rejester/_registry.py | Registry.set_1to1 | def set_1to1(self, dict_name, key1, key2):
'''Set two keys to be equal in a 1-to-1 mapping.
Within `dict_name`, `key1` is set to `key2`, and `key2` is set
to `key1`.
This always requires a session lock.
:param str dict_name: dictionary to update
:param str key1: first ... | python | def set_1to1(self, dict_name, key1, key2):
'''Set two keys to be equal in a 1-to-1 mapping.
Within `dict_name`, `key1` is set to `key2`, and `key2` is set
to `key1`.
This always requires a session lock.
:param str dict_name: dictionary to update
:param str key1: first ... | [
"def",
"set_1to1",
"(",
"self",
",",
"dict_name",
",",
"key1",
",",
"key2",
")",
":",
"if",
"self",
".",
"_session_lock_identifier",
"is",
"None",
":",
"raise",
"ProgrammerError",
"(",
"'must acquire lock first'",
")",
"conn",
"=",
"redis",
".",
"Redis",
"("... | Set two keys to be equal in a 1-to-1 mapping.
Within `dict_name`, `key1` is set to `key2`, and `key2` is set
to `key1`.
This always requires a session lock.
:param str dict_name: dictionary to update
:param str key1: first key/value
:param str key2: second key/value | [
"Set",
"two",
"keys",
"to",
"be",
"equal",
"in",
"a",
"1",
"-",
"to",
"-",
"1",
"mapping",
"."
] | train | https://github.com/diffeo/rejester/blob/5438a4a18be2801d7826c46e2079ba9639d2ecb4/rejester/_registry.py#L867-L899 |
diffeo/rejester | rejester/_registry.py | Registry.get | def get(self, dict_name, key, default=None, include_priority=False):
'''Get the value for a specific key in a specific dictionary.
If `include_priority` is false (default), returns the value
for that key, or `default` (defaults to :const:`None`) if it
is absent. If `include_priority` i... | python | def get(self, dict_name, key, default=None, include_priority=False):
'''Get the value for a specific key in a specific dictionary.
If `include_priority` is false (default), returns the value
for that key, or `default` (defaults to :const:`None`) if it
is absent. If `include_priority` i... | [
"def",
"get",
"(",
"self",
",",
"dict_name",
",",
"key",
",",
"default",
"=",
"None",
",",
"include_priority",
"=",
"False",
")",
":",
"dict_name",
"=",
"self",
".",
"_namespace",
"(",
"dict_name",
")",
"key",
"=",
"self",
".",
"_encode",
"(",
"key",
... | Get the value for a specific key in a specific dictionary.
If `include_priority` is false (default), returns the value
for that key, or `default` (defaults to :const:`None`) if it
is absent. If `include_priority` is true, returns a pair of
the value and its priority, or of `default` an... | [
"Get",
"the",
"value",
"for",
"a",
"specific",
"key",
"in",
"a",
"specific",
"dictionary",
"."
] | train | https://github.com/diffeo/rejester/blob/5438a4a18be2801d7826c46e2079ba9639d2ecb4/rejester/_registry.py#L901-L934 |
diffeo/rejester | rejester/_registry.py | Registry.set | def set(self, dict_name, key, value, priority=None):
'''Set a single value for a single key.
This requires a session lock.
:param str dict_name: name of the dictionary to update
:param str key: key to update
:param str value: value to assign to `key`
:param int priority... | python | def set(self, dict_name, key, value, priority=None):
'''Set a single value for a single key.
This requires a session lock.
:param str dict_name: name of the dictionary to update
:param str key: key to update
:param str value: value to assign to `key`
:param int priority... | [
"def",
"set",
"(",
"self",
",",
"dict_name",
",",
"key",
",",
"value",
",",
"priority",
"=",
"None",
")",
":",
"if",
"priority",
"is",
"not",
"None",
":",
"priorities",
"=",
"{",
"key",
":",
"priority",
"}",
"else",
":",
"priorities",
"=",
"None",
... | Set a single value for a single key.
This requires a session lock.
:param str dict_name: name of the dictionary to update
:param str key: key to update
:param str value: value to assign to `key`
:param int priority: priority score for the value (if any) | [
"Set",
"a",
"single",
"value",
"for",
"a",
"single",
"key",
"."
] | train | https://github.com/diffeo/rejester/blob/5438a4a18be2801d7826c46e2079ba9639d2ecb4/rejester/_registry.py#L936-L951 |
diffeo/rejester | rejester/_registry.py | Registry.delete | def delete(self, dict_name):
'''Delete an entire dictionary.
This operation on its own is atomic and does not require a
session lock, but a session lock is honored.
:param str dict_name: name of the dictionary to delete
:raises rejester.exceptions.LockError: if called with a se... | python | def delete(self, dict_name):
'''Delete an entire dictionary.
This operation on its own is atomic and does not require a
session lock, but a session lock is honored.
:param str dict_name: name of the dictionary to delete
:raises rejester.exceptions.LockError: if called with a se... | [
"def",
"delete",
"(",
"self",
",",
"dict_name",
")",
":",
"conn",
"=",
"redis",
".",
"Redis",
"(",
"connection_pool",
"=",
"self",
".",
"pool",
")",
"script",
"=",
"conn",
".",
"register_script",
"(",
"'''\n if redis.call(\"get\", KEYS[1]) == ARGV[1]\n ... | Delete an entire dictionary.
This operation on its own is atomic and does not require a
session lock, but a session lock is honored.
:param str dict_name: name of the dictionary to delete
:raises rejester.exceptions.LockError: if called with a session
lock, but the system doe... | [
"Delete",
"an",
"entire",
"dictionary",
"."
] | train | https://github.com/diffeo/rejester/blob/5438a4a18be2801d7826c46e2079ba9639d2ecb4/rejester/_registry.py#L953-L979 |
diffeo/rejester | rejester/_registry.py | Registry.direct_call | def direct_call(self, *args):
'''execute a direct redis call against this Registry instances
namespaced keys. This is low level is should only be used for
prototyping.
arg[0] = redis function
arg[1] = key --- will be namespaced before execution
args[2:] = args to functi... | python | def direct_call(self, *args):
'''execute a direct redis call against this Registry instances
namespaced keys. This is low level is should only be used for
prototyping.
arg[0] = redis function
arg[1] = key --- will be namespaced before execution
args[2:] = args to functi... | [
"def",
"direct_call",
"(",
"self",
",",
"*",
"args",
")",
":",
"conn",
"=",
"redis",
".",
"Redis",
"(",
"connection_pool",
"=",
"self",
".",
"pool",
")",
"command",
"=",
"args",
"[",
"0",
"]",
"key",
"=",
"self",
".",
"_namespace",
"(",
"args",
"["... | execute a direct redis call against this Registry instances
namespaced keys. This is low level is should only be used for
prototyping.
arg[0] = redis function
arg[1] = key --- will be namespaced before execution
args[2:] = args to function
:returns raw return value of ... | [
"execute",
"a",
"direct",
"redis",
"call",
"against",
"this",
"Registry",
"instances",
"namespaced",
"keys",
".",
"This",
"is",
"low",
"level",
"is",
"should",
"only",
"be",
"used",
"for",
"prototyping",
"."
] | train | https://github.com/diffeo/rejester/blob/5438a4a18be2801d7826c46e2079ba9639d2ecb4/rejester/_registry.py#L981-L999 |
tslight/yorn | yorn/ask.py | ask | def ask(question):
'''
Infinite loop to get yes or no answer or quit the script.
'''
while True:
ans = input(question)
al = ans.lower()
if match('^y(es)?$', al):
return True
elif match('^n(o)?$', al):
return False
elif match('^q(uit)?$', al... | python | def ask(question):
'''
Infinite loop to get yes or no answer or quit the script.
'''
while True:
ans = input(question)
al = ans.lower()
if match('^y(es)?$', al):
return True
elif match('^n(o)?$', al):
return False
elif match('^q(uit)?$', al... | [
"def",
"ask",
"(",
"question",
")",
":",
"while",
"True",
":",
"ans",
"=",
"input",
"(",
"question",
")",
"al",
"=",
"ans",
".",
"lower",
"(",
")",
"if",
"match",
"(",
"'^y(es)?$'",
",",
"al",
")",
":",
"return",
"True",
"elif",
"match",
"(",
"'^... | Infinite loop to get yes or no answer or quit the script. | [
"Infinite",
"loop",
"to",
"get",
"yes",
"or",
"no",
"answer",
"or",
"quit",
"the",
"script",
"."
] | train | https://github.com/tslight/yorn/blob/be577261065a53d3f4a585038c597c72950aa5ce/yorn/ask.py#L13-L32 |
fangpenlin/pyramid-handy | pyramid_handy/tweens/basic_auth.py | get_remote_user | def get_remote_user(request):
"""Parse basic HTTP_AUTHORIZATION and return user name
"""
if 'HTTP_AUTHORIZATION' not in request.environ:
return
authorization = request.environ['HTTP_AUTHORIZATION']
try:
authmeth, auth = authorization.split(' ', 1)
except ValueError: # not enoug... | python | def get_remote_user(request):
"""Parse basic HTTP_AUTHORIZATION and return user name
"""
if 'HTTP_AUTHORIZATION' not in request.environ:
return
authorization = request.environ['HTTP_AUTHORIZATION']
try:
authmeth, auth = authorization.split(' ', 1)
except ValueError: # not enoug... | [
"def",
"get_remote_user",
"(",
"request",
")",
":",
"if",
"'HTTP_AUTHORIZATION'",
"not",
"in",
"request",
".",
"environ",
":",
"return",
"authorization",
"=",
"request",
".",
"environ",
"[",
"'HTTP_AUTHORIZATION'",
"]",
"try",
":",
"authmeth",
",",
"auth",
"="... | Parse basic HTTP_AUTHORIZATION and return user name | [
"Parse",
"basic",
"HTTP_AUTHORIZATION",
"and",
"return",
"user",
"name"
] | train | https://github.com/fangpenlin/pyramid-handy/blob/e3cbc19224ab1f0a14aab556990bceabd2d1f658/pyramid_handy/tweens/basic_auth.py#L7-L28 |
fangpenlin/pyramid-handy | pyramid_handy/tweens/basic_auth.py | basic_auth_tween_factory | def basic_auth_tween_factory(handler, registry):
"""Do basic authentication, parse HTTP_AUTHORIZATION and set remote_user
variable to request
"""
def basic_auth_tween(request):
remote_user = get_remote_user(request)
if remote_user is not None:
request.environ['REMOTE_USER'] ... | python | def basic_auth_tween_factory(handler, registry):
"""Do basic authentication, parse HTTP_AUTHORIZATION and set remote_user
variable to request
"""
def basic_auth_tween(request):
remote_user = get_remote_user(request)
if remote_user is not None:
request.environ['REMOTE_USER'] ... | [
"def",
"basic_auth_tween_factory",
"(",
"handler",
",",
"registry",
")",
":",
"def",
"basic_auth_tween",
"(",
"request",
")",
":",
"remote_user",
"=",
"get_remote_user",
"(",
"request",
")",
"if",
"remote_user",
"is",
"not",
"None",
":",
"request",
".",
"envir... | Do basic authentication, parse HTTP_AUTHORIZATION and set remote_user
variable to request | [
"Do",
"basic",
"authentication",
"parse",
"HTTP_AUTHORIZATION",
"and",
"set",
"remote_user",
"variable",
"to",
"request"
] | train | https://github.com/fangpenlin/pyramid-handy/blob/e3cbc19224ab1f0a14aab556990bceabd2d1f658/pyramid_handy/tweens/basic_auth.py#L31-L41 |
ryanjdillon/pylleo | pylleo/calapp/main.py | plot_triaxial | def plot_triaxial(height, width, tools):
'''Plot pandas dataframe containing an x, y, and z column'''
import bokeh.plotting
p = bokeh.plotting.figure(x_axis_type='datetime',
plot_height=height,
plot_width=width,
title... | python | def plot_triaxial(height, width, tools):
'''Plot pandas dataframe containing an x, y, and z column'''
import bokeh.plotting
p = bokeh.plotting.figure(x_axis_type='datetime',
plot_height=height,
plot_width=width,
title... | [
"def",
"plot_triaxial",
"(",
"height",
",",
"width",
",",
"tools",
")",
":",
"import",
"bokeh",
".",
"plotting",
"p",
"=",
"bokeh",
".",
"plotting",
".",
"figure",
"(",
"x_axis_type",
"=",
"'datetime'",
",",
"plot_height",
"=",
"height",
",",
"plot_width",... | Plot pandas dataframe containing an x, y, and z column | [
"Plot",
"pandas",
"dataframe",
"containing",
"an",
"x",
"y",
"and",
"z",
"column"
] | train | https://github.com/ryanjdillon/pylleo/blob/b9b999fef19eaeccce4f207ab1b6198287c1bfec/pylleo/calapp/main.py#L18-L43 |
ryanjdillon/pylleo | pylleo/calapp/main.py | load_data | def load_data(path_dir):
'''Load data, directory parameters, and accelerometer parameter names
Args
----
path_dir: str
Path to the data directory
Returns
-------
data: pandas.DataFrame
Experiment data
params_tag: dict
A dictionary of parameters parsed from the d... | python | def load_data(path_dir):
'''Load data, directory parameters, and accelerometer parameter names
Args
----
path_dir: str
Path to the data directory
Returns
-------
data: pandas.DataFrame
Experiment data
params_tag: dict
A dictionary of parameters parsed from the d... | [
"def",
"load_data",
"(",
"path_dir",
")",
":",
"import",
"os",
"import",
"pylleo",
"exp_name",
"=",
"os",
".",
"path",
".",
"split",
"(",
"path_dir",
")",
"[",
"1",
"]",
"params_tag",
"=",
"pylleo",
".",
"utils",
".",
"parse_experiment_params",
"(",
"exp... | Load data, directory parameters, and accelerometer parameter names
Args
----
path_dir: str
Path to the data directory
Returns
-------
data: pandas.DataFrame
Experiment data
params_tag: dict
A dictionary of parameters parsed from the directory name
params_data: l... | [
"Load",
"data",
"directory",
"parameters",
"and",
"accelerometer",
"parameter",
"names"
] | train | https://github.com/ryanjdillon/pylleo/blob/b9b999fef19eaeccce4f207ab1b6198287c1bfec/pylleo/calapp/main.py#L46-L79 |
ryanjdillon/pylleo | pylleo/calapp/main.py | callback_parent | def callback_parent(attr, old, new):
'''Update data directories drop down with new parent directory'''
import os
# Remove accidental white space if copy/pasted
new = new.strip()
parent_input.value = new
# Verify new parent path exists and update `datadirs_select` widget
if os.path.exists(n... | python | def callback_parent(attr, old, new):
'''Update data directories drop down with new parent directory'''
import os
# Remove accidental white space if copy/pasted
new = new.strip()
parent_input.value = new
# Verify new parent path exists and update `datadirs_select` widget
if os.path.exists(n... | [
"def",
"callback_parent",
"(",
"attr",
",",
"old",
",",
"new",
")",
":",
"import",
"os",
"# Remove accidental white space if copy/pasted",
"new",
"=",
"new",
".",
"strip",
"(",
")",
"parent_input",
".",
"value",
"=",
"new",
"# Verify new parent path exists and updat... | Update data directories drop down with new parent directory | [
"Update",
"data",
"directories",
"drop",
"down",
"with",
"new",
"parent",
"directory"
] | train | https://github.com/ryanjdillon/pylleo/blob/b9b999fef19eaeccce4f207ab1b6198287c1bfec/pylleo/calapp/main.py#L82-L109 |
ryanjdillon/pylleo | pylleo/calapp/main.py | callback_datadirs | def callback_datadirs(attr, old, new):
'''Update source and controls with data loaded from selected directory'''
import os
global data
try:
# Load data from new data directory
path_dir = os.path.join(parent_input.value, new)
data, params_tag, params_data = load_data(path_dir)
... | python | def callback_datadirs(attr, old, new):
'''Update source and controls with data loaded from selected directory'''
import os
global data
try:
# Load data from new data directory
path_dir = os.path.join(parent_input.value, new)
data, params_tag, params_data = load_data(path_dir)
... | [
"def",
"callback_datadirs",
"(",
"attr",
",",
"old",
",",
"new",
")",
":",
"import",
"os",
"global",
"data",
"try",
":",
"# Load data from new data directory",
"path_dir",
"=",
"os",
".",
"path",
".",
"join",
"(",
"parent_input",
".",
"value",
",",
"new",
... | Update source and controls with data loaded from selected directory | [
"Update",
"source",
"and",
"controls",
"with",
"data",
"loaded",
"from",
"selected",
"directory"
] | train | https://github.com/ryanjdillon/pylleo/blob/b9b999fef19eaeccce4f207ab1b6198287c1bfec/pylleo/calapp/main.py#L112-L156 |
ryanjdillon/pylleo | pylleo/calapp/main.py | callback_box_select | def callback_box_select(attr, old, new):
'''Update TextInput start/end entries from BoxSelectTool selection'''
# Get indices of selection
ind = sorted(new['1d']['indices'])
if new is None:
start_input.value = '0'
end_input.value = '0'
else:
start_input.value = str(source.da... | python | def callback_box_select(attr, old, new):
'''Update TextInput start/end entries from BoxSelectTool selection'''
# Get indices of selection
ind = sorted(new['1d']['indices'])
if new is None:
start_input.value = '0'
end_input.value = '0'
else:
start_input.value = str(source.da... | [
"def",
"callback_box_select",
"(",
"attr",
",",
"old",
",",
"new",
")",
":",
"# Get indices of selection",
"ind",
"=",
"sorted",
"(",
"new",
"[",
"'1d'",
"]",
"[",
"'indices'",
"]",
")",
"if",
"new",
"is",
"None",
":",
"start_input",
".",
"value",
"=",
... | Update TextInput start/end entries from BoxSelectTool selection | [
"Update",
"TextInput",
"start",
"/",
"end",
"entries",
"from",
"BoxSelectTool",
"selection"
] | train | https://github.com/ryanjdillon/pylleo/blob/b9b999fef19eaeccce4f207ab1b6198287c1bfec/pylleo/calapp/main.py#L159-L176 |
ryanjdillon/pylleo | pylleo/calapp/main.py | callback_checkbox | def callback_checkbox(attr, old, new):
'''Update visible data from parameters selectin in the CheckboxSelect'''
import numpy
for i in range(len(lines)):
lines[i].visible = i in param_checkbox.active
scats[i].visible = i in param_checkbox.active
return None | python | def callback_checkbox(attr, old, new):
'''Update visible data from parameters selectin in the CheckboxSelect'''
import numpy
for i in range(len(lines)):
lines[i].visible = i in param_checkbox.active
scats[i].visible = i in param_checkbox.active
return None | [
"def",
"callback_checkbox",
"(",
"attr",
",",
"old",
",",
"new",
")",
":",
"import",
"numpy",
"for",
"i",
"in",
"range",
"(",
"len",
"(",
"lines",
")",
")",
":",
"lines",
"[",
"i",
"]",
".",
"visible",
"=",
"i",
"in",
"param_checkbox",
".",
"active... | Update visible data from parameters selectin in the CheckboxSelect | [
"Update",
"visible",
"data",
"from",
"parameters",
"selectin",
"in",
"the",
"CheckboxSelect"
] | train | https://github.com/ryanjdillon/pylleo/blob/b9b999fef19eaeccce4f207ab1b6198287c1bfec/pylleo/calapp/main.py#L179-L187 |
ryanjdillon/pylleo | pylleo/calapp/main.py | callback_save_indices | def callback_save_indices():
'''Save index from bokeh textinput'''
import datetime
import os
import pylleo
import yamlord
if datadirs_select.value != 'None':
path_dir = os.path.join(parent_input.value, datadirs_select.value)
cal_yaml_path = os.path.join(path_dir, 'cal.yml')
... | python | def callback_save_indices():
'''Save index from bokeh textinput'''
import datetime
import os
import pylleo
import yamlord
if datadirs_select.value != 'None':
path_dir = os.path.join(parent_input.value, datadirs_select.value)
cal_yaml_path = os.path.join(path_dir, 'cal.yml')
... | [
"def",
"callback_save_indices",
"(",
")",
":",
"import",
"datetime",
"import",
"os",
"import",
"pylleo",
"import",
"yamlord",
"if",
"datadirs_select",
".",
"value",
"!=",
"'None'",
":",
"path_dir",
"=",
"os",
".",
"path",
".",
"join",
"(",
"parent_input",
".... | Save index from bokeh textinput | [
"Save",
"index",
"from",
"bokeh",
"textinput"
] | train | https://github.com/ryanjdillon/pylleo/blob/b9b999fef19eaeccce4f207ab1b6198287c1bfec/pylleo/calapp/main.py#L190-L227 |
ryanjdillon/pylleo | pylleo/calapp/main.py | callback_save_poly | def callback_save_poly():
'''Perform polyfit once regions selected
Globals: cal_fname, data (read-only, so no declaration)
'''
import datetime
import pylleo
import yamlord
import itertools
def _check_param_regions(param, regions, cal_dict):
msg = '''
<b>{}</b> was... | python | def callback_save_poly():
'''Perform polyfit once regions selected
Globals: cal_fname, data (read-only, so no declaration)
'''
import datetime
import pylleo
import yamlord
import itertools
def _check_param_regions(param, regions, cal_dict):
msg = '''
<b>{}</b> was... | [
"def",
"callback_save_poly",
"(",
")",
":",
"import",
"datetime",
"import",
"pylleo",
"import",
"yamlord",
"import",
"itertools",
"def",
"_check_param_regions",
"(",
"param",
",",
"regions",
",",
"cal_dict",
")",
":",
"msg",
"=",
"'''\n <b>{}</b> was no... | Perform polyfit once regions selected
Globals: cal_fname, data (read-only, so no declaration) | [
"Perform",
"polyfit",
"once",
"regions",
"selected"
] | train | https://github.com/ryanjdillon/pylleo/blob/b9b999fef19eaeccce4f207ab1b6198287c1bfec/pylleo/calapp/main.py#L230-L323 |
pablorecio/Cobaya | src/cobaya/password.py | get_password | def get_password(config):
"""Returns the password for a remote server
It tries to fetch the password from the following
locations in this order:
1. config file [remote] section, password option
2. GNOME keyring
3. interactively, from the user
"""
password = config.get_option('remote... | python | def get_password(config):
"""Returns the password for a remote server
It tries to fetch the password from the following
locations in this order:
1. config file [remote] section, password option
2. GNOME keyring
3. interactively, from the user
"""
password = config.get_option('remote... | [
"def",
"get_password",
"(",
"config",
")",
":",
"password",
"=",
"config",
".",
"get_option",
"(",
"'remote.password'",
")",
"if",
"password",
"==",
"''",
":",
"user",
"=",
"config",
".",
"get_option",
"(",
"'remote.user'",
")",
"url",
"=",
"config",
".",
... | Returns the password for a remote server
It tries to fetch the password from the following
locations in this order:
1. config file [remote] section, password option
2. GNOME keyring
3. interactively, from the user | [
"Returns",
"the",
"password",
"for",
"a",
"remote",
"server"
] | train | https://github.com/pablorecio/Cobaya/blob/70b107dea5f31f51e7b6738da3c2a1df5b9f3f20/src/cobaya/password.py#L34-L61 |
gear11/pypelogs | pypelogs.py | process | def process(specs):
"""
Executes the passed in list of specs
"""
pout, pin = chain_specs(specs)
LOG.info("Processing")
sw = StopWatch().start()
r = pout.process(pin)
if r:
print(r)
LOG.info("Finished in %s", sw.read()) | python | def process(specs):
"""
Executes the passed in list of specs
"""
pout, pin = chain_specs(specs)
LOG.info("Processing")
sw = StopWatch().start()
r = pout.process(pin)
if r:
print(r)
LOG.info("Finished in %s", sw.read()) | [
"def",
"process",
"(",
"specs",
")",
":",
"pout",
",",
"pin",
"=",
"chain_specs",
"(",
"specs",
")",
"LOG",
".",
"info",
"(",
"\"Processing\"",
")",
"sw",
"=",
"StopWatch",
"(",
")",
".",
"start",
"(",
")",
"r",
"=",
"pout",
".",
"process",
"(",
... | Executes the passed in list of specs | [
"Executes",
"the",
"passed",
"in",
"list",
"of",
"specs"
] | train | https://github.com/gear11/pypelogs/blob/da5dc0fee5373a4be294798b5e32cd0a803d8bbe/pypelogs.py#L33-L43 |
gear11/pypelogs | pypelogs.py | chain_specs | def chain_specs(specs):
"""
Parses the incoming list of specs and produces a tuple (pout, pin) that can be invoked with:
<pre>
result = pout.process(pin)
</pre>
"""
LOG.info("Parsing %s specs", len(specs))
# First spec is always an input
pin = pypein.input_for(specs[0])._... | python | def chain_specs(specs):
"""
Parses the incoming list of specs and produces a tuple (pout, pin) that can be invoked with:
<pre>
result = pout.process(pin)
</pre>
"""
LOG.info("Parsing %s specs", len(specs))
# First spec is always an input
pin = pypein.input_for(specs[0])._... | [
"def",
"chain_specs",
"(",
"specs",
")",
":",
"LOG",
".",
"info",
"(",
"\"Parsing %s specs\"",
",",
"len",
"(",
"specs",
")",
")",
"# First spec is always an input",
"pin",
"=",
"pypein",
".",
"input_for",
"(",
"specs",
"[",
"0",
"]",
")",
".",
"__iter__",... | Parses the incoming list of specs and produces a tuple (pout, pin) that can be invoked with:
<pre>
result = pout.process(pin)
</pre> | [
"Parses",
"the",
"incoming",
"list",
"of",
"specs",
"and",
"produces",
"a",
"tuple",
"(",
"pout",
"pin",
")",
"that",
"can",
"be",
"invoked",
"with",
":",
"<pre",
">",
"result",
"=",
"pout",
".",
"process",
"(",
"pin",
")",
"<",
"/",
"pre",
">"
] | train | https://github.com/gear11/pypelogs/blob/da5dc0fee5373a4be294798b5e32cd0a803d8bbe/pypelogs.py#L46-L70 |
EnigmaBridge/client.py | ebclient/errors.py | Error.load | def load(self, cause=None, do_message=True):
"""
Loads exception data from the current exception frame - should be called inside the except block
:return:
"""
if cause is not None:
self.cause = cause
if do_message:
self.message = error_mess... | python | def load(self, cause=None, do_message=True):
"""
Loads exception data from the current exception frame - should be called inside the except block
:return:
"""
if cause is not None:
self.cause = cause
if do_message:
self.message = error_mess... | [
"def",
"load",
"(",
"self",
",",
"cause",
"=",
"None",
",",
"do_message",
"=",
"True",
")",
":",
"if",
"cause",
"is",
"not",
"None",
":",
"self",
".",
"cause",
"=",
"cause",
"if",
"do_message",
":",
"self",
".",
"message",
"=",
"error_message",
"(",
... | Loads exception data from the current exception frame - should be called inside the except block
:return: | [
"Loads",
"exception",
"data",
"from",
"the",
"current",
"exception",
"frame",
"-",
"should",
"be",
"called",
"inside",
"the",
"except",
"block",
":",
"return",
":"
] | train | https://github.com/EnigmaBridge/client.py/blob/0fafe3902da394da88e9f960751d695ca65bbabd/ebclient/errors.py#L42-L54 |
unfoldingWord-dev/tx-shared-tools | general_tools/smartquotes.py | smartquotes | def smartquotes(text):
"""
Runs text through pandoc for smartquote correction.
"""
command = shlex.split('pandoc --smart -t plain')
com = Popen(command, shell=False, stdin=PIPE, stdout=PIPE, stderr=PIPE)
out, err = com.communicate(text.encode('utf-8'))
com_out = out.decode('utf-8')
text ... | python | def smartquotes(text):
"""
Runs text through pandoc for smartquote correction.
"""
command = shlex.split('pandoc --smart -t plain')
com = Popen(command, shell=False, stdin=PIPE, stdout=PIPE, stderr=PIPE)
out, err = com.communicate(text.encode('utf-8'))
com_out = out.decode('utf-8')
text ... | [
"def",
"smartquotes",
"(",
"text",
")",
":",
"command",
"=",
"shlex",
".",
"split",
"(",
"'pandoc --smart -t plain'",
")",
"com",
"=",
"Popen",
"(",
"command",
",",
"shell",
"=",
"False",
",",
"stdin",
"=",
"PIPE",
",",
"stdout",
"=",
"PIPE",
",",
"std... | Runs text through pandoc for smartquote correction. | [
"Runs",
"text",
"through",
"pandoc",
"for",
"smartquote",
"correction",
"."
] | train | https://github.com/unfoldingWord-dev/tx-shared-tools/blob/6ff5cd024e1ab54c53dd1bc788bbc78e2358772e/general_tools/smartquotes.py#L22-L31 |
MacHu-GWU/angora-project | angora/text/rerecipe.py | ReParser.extract_by_prefix_surfix | def extract_by_prefix_surfix(prefix, surfix, maxlen, text):
"""Extract the text in between a prefix and surfix.
:param prefix: the prefix
:type prefix: str
:param surfix: the surfix
:type surfix: str
:param maxlen: the max matched string length
... | python | def extract_by_prefix_surfix(prefix, surfix, maxlen, text):
"""Extract the text in between a prefix and surfix.
:param prefix: the prefix
:type prefix: str
:param surfix: the surfix
:type surfix: str
:param maxlen: the max matched string length
... | [
"def",
"extract_by_prefix_surfix",
"(",
"prefix",
",",
"surfix",
",",
"maxlen",
",",
"text",
")",
":",
"pattern",
"=",
"r\"\"\"(?<=%s)[\\s\\S]{1,%s}(?=%s)\"\"\"",
"%",
"(",
"prefix",
",",
"maxlen",
",",
"surfix",
")",
"return",
"re",
".",
"findall",
"(",
"patt... | Extract the text in between a prefix and surfix.
:param prefix: the prefix
:type prefix: str
:param surfix: the surfix
:type surfix: str
:param maxlen: the max matched string length
:type maxlen: int
:param text: text body
... | [
"Extract",
"the",
"text",
"in",
"between",
"a",
"prefix",
"and",
"surfix",
".",
":",
"param",
"prefix",
":",
"the",
"prefix",
":",
"type",
"prefix",
":",
"str",
":",
"param",
"surfix",
":",
"the",
"surfix",
":",
"type",
"surfix",
":",
"str",
":",
"pa... | train | https://github.com/MacHu-GWU/angora-project/blob/689a60da51cd88680ddbe26e28dbe81e6b01d275/angora/text/rerecipe.py#L35-L51 |
GreenBankObservatory/django-resetdb | django_resetdb/util.py | shell | def shell(cmd, **kwargs):
"""Execute cmd, check exit code, return stdout"""
logger.debug("$ %s", cmd)
return subprocess.check_output(cmd, shell=True, **kwargs) | python | def shell(cmd, **kwargs):
"""Execute cmd, check exit code, return stdout"""
logger.debug("$ %s", cmd)
return subprocess.check_output(cmd, shell=True, **kwargs) | [
"def",
"shell",
"(",
"cmd",
",",
"*",
"*",
"kwargs",
")",
":",
"logger",
".",
"debug",
"(",
"\"$ %s\"",
",",
"cmd",
")",
"return",
"subprocess",
".",
"check_output",
"(",
"cmd",
",",
"shell",
"=",
"True",
",",
"*",
"*",
"kwargs",
")"
] | Execute cmd, check exit code, return stdout | [
"Execute",
"cmd",
"check",
"exit",
"code",
"return",
"stdout"
] | train | https://github.com/GreenBankObservatory/django-resetdb/blob/767bddacb53823bb003e2abebfe8139a14b843f7/django_resetdb/util.py#L16-L19 |
vinu76jsr/pipsort | deploy.py | _cmdline | def _cmdline(argv=None):
""" Parse command line arguments.
By default, sys.argv is parsed.
"""
parser = ArgumentParser()
parser.add_argument("--checkout", default="HEAD",
help="branch, tag, or commit to use [HEAD]")
parser.add_argument("--name", default=_NAME,
... | python | def _cmdline(argv=None):
""" Parse command line arguments.
By default, sys.argv is parsed.
"""
parser = ArgumentParser()
parser.add_argument("--checkout", default="HEAD",
help="branch, tag, or commit to use [HEAD]")
parser.add_argument("--name", default=_NAME,
... | [
"def",
"_cmdline",
"(",
"argv",
"=",
"None",
")",
":",
"parser",
"=",
"ArgumentParser",
"(",
")",
"parser",
".",
"add_argument",
"(",
"\"--checkout\"",
",",
"default",
"=",
"\"HEAD\"",
",",
"help",
"=",
"\"branch, tag, or commit to use [HEAD]\"",
")",
"parser",
... | Parse command line arguments.
By default, sys.argv is parsed. | [
"Parse",
"command",
"line",
"arguments",
"."
] | train | https://github.com/vinu76jsr/pipsort/blob/71ead1269de85ee0255741390bf1da85d81b7d16/deploy.py#L25-L41 |
vinu76jsr/pipsort | deploy.py | main | def main(argv=None):
""" Script execution.
The project repo will be cloned to a temporary directory, and the desired
branch, tag, or commit will be checked out. Then, the application will be
installed into a self-contained virtualenv environment.
"""
@contextmanager
def tmpdir():
"... | python | def main(argv=None):
""" Script execution.
The project repo will be cloned to a temporary directory, and the desired
branch, tag, or commit will be checked out. Then, the application will be
installed into a self-contained virtualenv environment.
"""
@contextmanager
def tmpdir():
"... | [
"def",
"main",
"(",
"argv",
"=",
"None",
")",
":",
"@",
"contextmanager",
"def",
"tmpdir",
"(",
")",
":",
"\"\"\" Create a self-deleting temporary directory. \"\"\"",
"path",
"=",
"mkdtemp",
"(",
")",
"try",
":",
"yield",
"path",
"finally",
":",
"rmtree",
"(",... | Script execution.
The project repo will be cloned to a temporary directory, and the desired
branch, tag, or commit will be checked out. Then, the application will be
installed into a self-contained virtualenv environment. | [
"Script",
"execution",
"."
] | train | https://github.com/vinu76jsr/pipsort/blob/71ead1269de85ee0255741390bf1da85d81b7d16/deploy.py#L44-L88 |
krukas/Trionyx | trionyx/trionyx/models.py | UserManager._create_user | def _create_user(self, email, password, is_superuser, **extra_fields):
"""Create new user"""
now = timezone.now()
if not email:
raise ValueError('The given email must be set')
email = self.normalize_email(email)
user = self.model(
email=email,
... | python | def _create_user(self, email, password, is_superuser, **extra_fields):
"""Create new user"""
now = timezone.now()
if not email:
raise ValueError('The given email must be set')
email = self.normalize_email(email)
user = self.model(
email=email,
... | [
"def",
"_create_user",
"(",
"self",
",",
"email",
",",
"password",
",",
"is_superuser",
",",
"*",
"*",
"extra_fields",
")",
":",
"now",
"=",
"timezone",
".",
"now",
"(",
")",
"if",
"not",
"email",
":",
"raise",
"ValueError",
"(",
"'The given email must be ... | Create new user | [
"Create",
"new",
"user"
] | train | https://github.com/krukas/Trionyx/blob/edac132cc0797190153f2e60bc7e88cb50e80da6/trionyx/trionyx/models.py#L19-L35 |
krukas/Trionyx | trionyx/trionyx/models.py | User.get_full_name | def get_full_name(self):
"""Get full username if no name is set email is given"""
if self.first_name and self.last_name:
return "{} {}".format(self.first_name, self.last_name)
return self.email | python | def get_full_name(self):
"""Get full username if no name is set email is given"""
if self.first_name and self.last_name:
return "{} {}".format(self.first_name, self.last_name)
return self.email | [
"def",
"get_full_name",
"(",
"self",
")",
":",
"if",
"self",
".",
"first_name",
"and",
"self",
".",
"last_name",
":",
"return",
"\"{} {}\"",
".",
"format",
"(",
"self",
".",
"first_name",
",",
"self",
".",
"last_name",
")",
"return",
"self",
".",
"email"... | Get full username if no name is set email is given | [
"Get",
"full",
"username",
"if",
"no",
"name",
"is",
"set",
"email",
"is",
"given"
] | train | https://github.com/krukas/Trionyx/blob/edac132cc0797190153f2e60bc7e88cb50e80da6/trionyx/trionyx/models.py#L64-L68 |
krukas/Trionyx | trionyx/trionyx/models.py | UserAttributeManager.set_attribute | def set_attribute(self, code, value):
"""Set attribute for user"""
attr, _ = self.get_or_create(code=code)
attr.value = value
attr.save() | python | def set_attribute(self, code, value):
"""Set attribute for user"""
attr, _ = self.get_or_create(code=code)
attr.value = value
attr.save() | [
"def",
"set_attribute",
"(",
"self",
",",
"code",
",",
"value",
")",
":",
"attr",
",",
"_",
"=",
"self",
".",
"get_or_create",
"(",
"code",
"=",
"code",
")",
"attr",
".",
"value",
"=",
"value",
"attr",
".",
"save",
"(",
")"
] | Set attribute for user | [
"Set",
"attribute",
"for",
"user"
] | train | https://github.com/krukas/Trionyx/blob/edac132cc0797190153f2e60bc7e88cb50e80da6/trionyx/trionyx/models.py#L84-L88 |
krukas/Trionyx | trionyx/trionyx/models.py | UserAttributeManager.get_attribute | def get_attribute(self, code, default=None):
"""Get attribute for user"""
try:
return self.get(code=code).value
except models.ObjectDoesNotExist:
return default | python | def get_attribute(self, code, default=None):
"""Get attribute for user"""
try:
return self.get(code=code).value
except models.ObjectDoesNotExist:
return default | [
"def",
"get_attribute",
"(",
"self",
",",
"code",
",",
"default",
"=",
"None",
")",
":",
"try",
":",
"return",
"self",
".",
"get",
"(",
"code",
"=",
"code",
")",
".",
"value",
"except",
"models",
".",
"ObjectDoesNotExist",
":",
"return",
"default"
] | Get attribute for user | [
"Get",
"attribute",
"for",
"user"
] | train | https://github.com/krukas/Trionyx/blob/edac132cc0797190153f2e60bc7e88cb50e80da6/trionyx/trionyx/models.py#L90-L95 |
musicmetric/mmpy | src/chart.py | Chart.next | def next(self):
"""
fetch the chart identified by this chart's next_id attribute
if the next_id is either null or not present for this chart return None
returns the new chart instance on sucess"""
try:
if self.next_id:
return Chart(self.next_id)
... | python | def next(self):
"""
fetch the chart identified by this chart's next_id attribute
if the next_id is either null or not present for this chart return None
returns the new chart instance on sucess"""
try:
if self.next_id:
return Chart(self.next_id)
... | [
"def",
"next",
"(",
"self",
")",
":",
"try",
":",
"if",
"self",
".",
"next_id",
":",
"return",
"Chart",
"(",
"self",
".",
"next_id",
")",
"else",
":",
"log",
".",
"debug",
"(",
"'attempted to get next chart, but none was found'",
")",
"return",
"except",
"... | fetch the chart identified by this chart's next_id attribute
if the next_id is either null or not present for this chart return None
returns the new chart instance on sucess | [
"fetch",
"the",
"chart",
"identified",
"by",
"this",
"chart",
"s",
"next_id",
"attribute",
"if",
"the",
"next_id",
"is",
"either",
"null",
"or",
"not",
"present",
"for",
"this",
"chart",
"return",
"None",
"returns",
"the",
"new",
"chart",
"instance",
"on",
... | train | https://github.com/musicmetric/mmpy/blob/2b5d975c61f9ea8c7f19f76a90b59771833ef881/src/chart.py#L69-L83 |
musicmetric/mmpy | src/chart.py | Chart.previous | def previous(self):
"""
fetch the chart identified by this chart's previous_id attribute
if the previous_id is either null or not present for this chart return None
returns the new chart instance on sucess"""
try:
if self.previous_id:
return Ch... | python | def previous(self):
"""
fetch the chart identified by this chart's previous_id attribute
if the previous_id is either null or not present for this chart return None
returns the new chart instance on sucess"""
try:
if self.previous_id:
return Ch... | [
"def",
"previous",
"(",
"self",
")",
":",
"try",
":",
"if",
"self",
".",
"previous_id",
":",
"return",
"Chart",
"(",
"self",
".",
"previous_id",
")",
"else",
":",
"log",
".",
"debug",
"(",
"'attempted to get previous chart, but none was found'",
")",
"return",... | fetch the chart identified by this chart's previous_id attribute
if the previous_id is either null or not present for this chart return None
returns the new chart instance on sucess | [
"fetch",
"the",
"chart",
"identified",
"by",
"this",
"chart",
"s",
"previous_id",
"attribute",
"if",
"the",
"previous_id",
"is",
"either",
"null",
"or",
"not",
"present",
"for",
"this",
"chart",
"return",
"None",
"returns",
"the",
"new",
"chart",
"instance",
... | train | https://github.com/musicmetric/mmpy/blob/2b5d975c61f9ea8c7f19f76a90b59771833ef881/src/chart.py#L85-L99 |
musicmetric/mmpy | src/chart.py | Chart.now | def now(self):
"""
fetch the chart identified by this chart's now_id attribute
if the now_id is either null or not present for this chart return None
returns the new chart instance on sucess"""
try:
if self.now_id:
return Chart(self.now_id)
... | python | def now(self):
"""
fetch the chart identified by this chart's now_id attribute
if the now_id is either null or not present for this chart return None
returns the new chart instance on sucess"""
try:
if self.now_id:
return Chart(self.now_id)
... | [
"def",
"now",
"(",
"self",
")",
":",
"try",
":",
"if",
"self",
".",
"now_id",
":",
"return",
"Chart",
"(",
"self",
".",
"now_id",
")",
"else",
":",
"log",
".",
"debug",
"(",
"'attempted to get current chart, but none was found'",
")",
"return",
"except",
"... | fetch the chart identified by this chart's now_id attribute
if the now_id is either null or not present for this chart return None
returns the new chart instance on sucess | [
"fetch",
"the",
"chart",
"identified",
"by",
"this",
"chart",
"s",
"now_id",
"attribute",
"if",
"the",
"now_id",
"is",
"either",
"null",
"or",
"not",
"present",
"for",
"this",
"chart",
"return",
"None",
"returns",
"the",
"new",
"chart",
"instance",
"on",
"... | train | https://github.com/musicmetric/mmpy/blob/2b5d975c61f9ea8c7f19f76a90b59771833ef881/src/chart.py#L101-L115 |
MacHu-GWU/angora-project | angora/dtypes/dicttree.py | DictTree.initial | def initial(key, **kwarg):
"""Create an empty dicttree.
The root node has a special attribute "_rootname".
Because root node is the only dictionary doesn't have key.
So we assign the key as a special attribute.
Usage::
>>> from weatherlab.lib.dtypes.dicttree impor... | python | def initial(key, **kwarg):
"""Create an empty dicttree.
The root node has a special attribute "_rootname".
Because root node is the only dictionary doesn't have key.
So we assign the key as a special attribute.
Usage::
>>> from weatherlab.lib.dtypes.dicttree impor... | [
"def",
"initial",
"(",
"key",
",",
"*",
"*",
"kwarg",
")",
":",
"d",
"=",
"dict",
"(",
")",
"DictTree",
".",
"setattr",
"(",
"d",
",",
"_rootname",
"=",
"key",
",",
"*",
"*",
"kwarg",
")",
"return",
"d"
] | Create an empty dicttree.
The root node has a special attribute "_rootname".
Because root node is the only dictionary doesn't have key.
So we assign the key as a special attribute.
Usage::
>>> from weatherlab.lib.dtypes.dicttree import DictTree as DT
>>> d = D... | [
"Create",
"an",
"empty",
"dicttree",
"."
] | train | https://github.com/MacHu-GWU/angora-project/blob/689a60da51cd88680ddbe26e28dbe81e6b01d275/angora/dtypes/dicttree.py#L149-L165 |
MacHu-GWU/angora-project | angora/dtypes/dicttree.py | DictTree.setattr | def setattr(d, **kwarg):
"""Set an attribute.
set attributes is actually add a special key, value pair in this dict
under key = "_meta".
Usage::
>>> DT.setattr(d, population=27800000)
>>> d
{'_meta': {'population': 27800000, '_rootname': 'US'}}
... | python | def setattr(d, **kwarg):
"""Set an attribute.
set attributes is actually add a special key, value pair in this dict
under key = "_meta".
Usage::
>>> DT.setattr(d, population=27800000)
>>> d
{'_meta': {'population': 27800000, '_rootname': 'US'}}
... | [
"def",
"setattr",
"(",
"d",
",",
"*",
"*",
"kwarg",
")",
":",
"if",
"_meta",
"not",
"in",
"d",
":",
"d",
"[",
"_meta",
"]",
"=",
"dict",
"(",
")",
"for",
"k",
",",
"v",
"in",
"kwarg",
".",
"items",
"(",
")",
":",
"d",
"[",
"_meta",
"]",
"... | Set an attribute.
set attributes is actually add a special key, value pair in this dict
under key = "_meta".
Usage::
>>> DT.setattr(d, population=27800000)
>>> d
{'_meta': {'population': 27800000, '_rootname': 'US'}} | [
"Set",
"an",
"attribute",
"."
] | train | https://github.com/MacHu-GWU/angora-project/blob/689a60da51cd88680ddbe26e28dbe81e6b01d275/angora/dtypes/dicttree.py#L168-L183 |
MacHu-GWU/angora-project | angora/dtypes/dicttree.py | DictTree.add_children | def add_children(d, key, **kwarg):
"""Add a children with key and attributes. If children already EXISTS,
OVERWRITE it.
Usage::
>>> from pprint import pprint as ppt
>>> DT.add_children(d, "VA", name="virginia", population=100*1000)
>>> DT.add_children(d, "M... | python | def add_children(d, key, **kwarg):
"""Add a children with key and attributes. If children already EXISTS,
OVERWRITE it.
Usage::
>>> from pprint import pprint as ppt
>>> DT.add_children(d, "VA", name="virginia", population=100*1000)
>>> DT.add_children(d, "M... | [
"def",
"add_children",
"(",
"d",
",",
"key",
",",
"*",
"*",
"kwarg",
")",
":",
"if",
"kwarg",
":",
"d",
"[",
"key",
"]",
"=",
"{",
"_meta",
":",
"kwarg",
"}",
"else",
":",
"d",
"[",
"key",
"]",
"=",
"dict",
"(",
")"
] | Add a children with key and attributes. If children already EXISTS,
OVERWRITE it.
Usage::
>>> from pprint import pprint as ppt
>>> DT.add_children(d, "VA", name="virginia", population=100*1000)
>>> DT.add_children(d, "MD", name="maryland", population=200*1000)
... | [
"Add",
"a",
"children",
"with",
"key",
"and",
"attributes",
".",
"If",
"children",
"already",
"EXISTS",
"OVERWRITE",
"it",
"."
] | train | https://github.com/MacHu-GWU/angora-project/blob/689a60da51cd88680ddbe26e28dbe81e6b01d275/angora/dtypes/dicttree.py#L197-L248 |
MacHu-GWU/angora-project | angora/dtypes/dicttree.py | DictTree.ac | def ac(d, key, **kwarg):
"""Alias of :meth:`self.add_children()<DictTree.add_children>`.
"""
if kwarg:
d[key] = {_meta: kwarg}
else:
d[key] = dict() | python | def ac(d, key, **kwarg):
"""Alias of :meth:`self.add_children()<DictTree.add_children>`.
"""
if kwarg:
d[key] = {_meta: kwarg}
else:
d[key] = dict() | [
"def",
"ac",
"(",
"d",
",",
"key",
",",
"*",
"*",
"kwarg",
")",
":",
"if",
"kwarg",
":",
"d",
"[",
"key",
"]",
"=",
"{",
"_meta",
":",
"kwarg",
"}",
"else",
":",
"d",
"[",
"key",
"]",
"=",
"dict",
"(",
")"
] | Alias of :meth:`self.add_children()<DictTree.add_children>`. | [
"Alias",
"of",
":",
"meth",
":",
"self",
".",
"add_children",
"()",
"<DictTree",
".",
"add_children",
">",
"."
] | train | https://github.com/MacHu-GWU/angora-project/blob/689a60da51cd88680ddbe26e28dbe81e6b01d275/angora/dtypes/dicttree.py#L251-L257 |
MacHu-GWU/angora-project | angora/dtypes/dicttree.py | DictTree.kv | def kv(d):
"""Equivalent to dict.items().
Usage::
>>> for key, node in DictTree.kv(d):
>>> print(key, DictTree.getattr(node, "population"))
MD 200000
VA 100000
"""
return ((key, value) for key, value in iteritems(d) ... | python | def kv(d):
"""Equivalent to dict.items().
Usage::
>>> for key, node in DictTree.kv(d):
>>> print(key, DictTree.getattr(node, "population"))
MD 200000
VA 100000
"""
return ((key, value) for key, value in iteritems(d) ... | [
"def",
"kv",
"(",
"d",
")",
":",
"return",
"(",
"(",
"key",
",",
"value",
")",
"for",
"key",
",",
"value",
"in",
"iteritems",
"(",
"d",
")",
"if",
"key",
"!=",
"_meta",
")"
] | Equivalent to dict.items().
Usage::
>>> for key, node in DictTree.kv(d):
>>> print(key, DictTree.getattr(node, "population"))
MD 200000
VA 100000 | [
"Equivalent",
"to",
"dict",
".",
"items",
"()",
".",
"Usage",
"::",
">>>",
"for",
"key",
"node",
"in",
"DictTree",
".",
"kv",
"(",
"d",
")",
":",
">>>",
"print",
"(",
"key",
"DictTree",
".",
"getattr",
"(",
"node",
"population",
"))",
"MD",
"200000",... | train | https://github.com/MacHu-GWU/angora-project/blob/689a60da51cd88680ddbe26e28dbe81e6b01d275/angora/dtypes/dicttree.py#L274-L284 |
MacHu-GWU/angora-project | angora/dtypes/dicttree.py | DictTree.k_depth | def k_depth(d, depth, _counter=1):
"""Iterate keys on specific depth.
depth has to be greater equal than 0.
Usage reference see :meth:`DictTree.kv_depth()<DictTree.kv_depth>`
"""
if depth == 0:
yield d[_meta]["_rootname"]
else:
if _counter == dept... | python | def k_depth(d, depth, _counter=1):
"""Iterate keys on specific depth.
depth has to be greater equal than 0.
Usage reference see :meth:`DictTree.kv_depth()<DictTree.kv_depth>`
"""
if depth == 0:
yield d[_meta]["_rootname"]
else:
if _counter == dept... | [
"def",
"k_depth",
"(",
"d",
",",
"depth",
",",
"_counter",
"=",
"1",
")",
":",
"if",
"depth",
"==",
"0",
":",
"yield",
"d",
"[",
"_meta",
"]",
"[",
"\"_rootname\"",
"]",
"else",
":",
"if",
"_counter",
"==",
"depth",
":",
"for",
"key",
"in",
"Dict... | Iterate keys on specific depth.
depth has to be greater equal than 0.
Usage reference see :meth:`DictTree.kv_depth()<DictTree.kv_depth>` | [
"Iterate",
"keys",
"on",
"specific",
"depth",
".",
"depth",
"has",
"to",
"be",
"greater",
"equal",
"than",
"0",
".",
"Usage",
"reference",
"see",
":",
"meth",
":",
"DictTree",
".",
"kv_depth",
"()",
"<DictTree",
".",
"kv_depth",
">"
] | train | https://github.com/MacHu-GWU/angora-project/blob/689a60da51cd88680ddbe26e28dbe81e6b01d275/angora/dtypes/dicttree.py#L287-L302 |
MacHu-GWU/angora-project | angora/dtypes/dicttree.py | DictTree.v_depth | def v_depth(d, depth):
"""Iterate values on specific depth.
depth has to be greater equal than 0.
Usage reference see :meth:`DictTree.kv_depth()<DictTree.kv_depth>`
"""
if depth == 0:
yield d
else:
for node in DictTree.v(d):
for nod... | python | def v_depth(d, depth):
"""Iterate values on specific depth.
depth has to be greater equal than 0.
Usage reference see :meth:`DictTree.kv_depth()<DictTree.kv_depth>`
"""
if depth == 0:
yield d
else:
for node in DictTree.v(d):
for nod... | [
"def",
"v_depth",
"(",
"d",
",",
"depth",
")",
":",
"if",
"depth",
"==",
"0",
":",
"yield",
"d",
"else",
":",
"for",
"node",
"in",
"DictTree",
".",
"v",
"(",
"d",
")",
":",
"for",
"node1",
"in",
"DictTree",
".",
"v_depth",
"(",
"node",
",",
"de... | Iterate values on specific depth.
depth has to be greater equal than 0.
Usage reference see :meth:`DictTree.kv_depth()<DictTree.kv_depth>` | [
"Iterate",
"values",
"on",
"specific",
"depth",
".",
"depth",
"has",
"to",
"be",
"greater",
"equal",
"than",
"0",
".",
"Usage",
"reference",
"see",
":",
"meth",
":",
"DictTree",
".",
"kv_depth",
"()",
"<DictTree",
".",
"kv_depth",
">"
] | train | https://github.com/MacHu-GWU/angora-project/blob/689a60da51cd88680ddbe26e28dbe81e6b01d275/angora/dtypes/dicttree.py#L305-L315 |
MacHu-GWU/angora-project | angora/dtypes/dicttree.py | DictTree.kv_depth | def kv_depth(d, depth, _counter=1):
"""Iterate items on specific depth.
depth has to be greater equal than 0.
Usage::
>>> for key, node in DictTree.kv_depth(d, 2):
>>> print(key, DictTree.getattr(node, "population"))
bethesta 5800
... | python | def kv_depth(d, depth, _counter=1):
"""Iterate items on specific depth.
depth has to be greater equal than 0.
Usage::
>>> for key, node in DictTree.kv_depth(d, 2):
>>> print(key, DictTree.getattr(node, "population"))
bethesta 5800
... | [
"def",
"kv_depth",
"(",
"d",
",",
"depth",
",",
"_counter",
"=",
"1",
")",
":",
"if",
"depth",
"==",
"0",
":",
"yield",
"d",
"[",
"_meta",
"]",
"[",
"\"_rootname\"",
"]",
",",
"d",
"else",
":",
"if",
"_counter",
"==",
"depth",
":",
"for",
"key",
... | Iterate items on specific depth.
depth has to be greater equal than 0.
Usage::
>>> for key, node in DictTree.kv_depth(d, 2):
>>> print(key, DictTree.getattr(node, "population"))
bethesta 5800
germentown 1400
vienna 1500... | [
"Iterate",
"items",
"on",
"specific",
"depth",
".",
"depth",
"has",
"to",
"be",
"greater",
"equal",
"than",
"0",
".",
"Usage",
"::",
">>>",
"for",
"key",
"node",
"in",
"DictTree",
".",
"kv_depth",
"(",
"d",
"2",
")",
":",
">>>",
"print",
"(",
"key",
... | train | https://github.com/MacHu-GWU/angora-project/blob/689a60da51cd88680ddbe26e28dbe81e6b01d275/angora/dtypes/dicttree.py#L318-L341 |
MacHu-GWU/angora-project | angora/dtypes/dicttree.py | DictTree.len_on_depth | def len_on_depth(d, depth):
"""Get the number of nodes on specific depth.
"""
counter = 0
for node in DictTree.v_depth(d, depth-1):
counter += DictTree.length(node)
return counter | python | def len_on_depth(d, depth):
"""Get the number of nodes on specific depth.
"""
counter = 0
for node in DictTree.v_depth(d, depth-1):
counter += DictTree.length(node)
return counter | [
"def",
"len_on_depth",
"(",
"d",
",",
"depth",
")",
":",
"counter",
"=",
"0",
"for",
"node",
"in",
"DictTree",
".",
"v_depth",
"(",
"d",
",",
"depth",
"-",
"1",
")",
":",
"counter",
"+=",
"DictTree",
".",
"length",
"(",
"node",
")",
"return",
"coun... | Get the number of nodes on specific depth. | [
"Get",
"the",
"number",
"of",
"nodes",
"on",
"specific",
"depth",
"."
] | train | https://github.com/MacHu-GWU/angora-project/blob/689a60da51cd88680ddbe26e28dbe81e6b01d275/angora/dtypes/dicttree.py#L353-L359 |
MacHu-GWU/angora-project | angora/dtypes/dicttree.py | DictTree.del_depth | def del_depth(d, depth):
"""Delete all the nodes on specific depth in this dict
"""
for node in DictTree.v_depth(d, depth-1):
for key in [key for key in DictTree.k(node)]:
del node[key] | python | def del_depth(d, depth):
"""Delete all the nodes on specific depth in this dict
"""
for node in DictTree.v_depth(d, depth-1):
for key in [key for key in DictTree.k(node)]:
del node[key] | [
"def",
"del_depth",
"(",
"d",
",",
"depth",
")",
":",
"for",
"node",
"in",
"DictTree",
".",
"v_depth",
"(",
"d",
",",
"depth",
"-",
"1",
")",
":",
"for",
"key",
"in",
"[",
"key",
"for",
"key",
"in",
"DictTree",
".",
"k",
"(",
"node",
")",
"]",
... | Delete all the nodes on specific depth in this dict | [
"Delete",
"all",
"the",
"nodes",
"on",
"specific",
"depth",
"in",
"this",
"dict"
] | train | https://github.com/MacHu-GWU/angora-project/blob/689a60da51cd88680ddbe26e28dbe81e6b01d275/angora/dtypes/dicttree.py#L370-L375 |
MacHu-GWU/angora-project | angora/dtypes/dicttree.py | DictTree.prettyprint | def prettyprint(d):
"""Print dicttree in Json-like format. keys are sorted
"""
print(json.dumps(d, sort_keys=True,
indent=4, separators=("," , ": "))) | python | def prettyprint(d):
"""Print dicttree in Json-like format. keys are sorted
"""
print(json.dumps(d, sort_keys=True,
indent=4, separators=("," , ": "))) | [
"def",
"prettyprint",
"(",
"d",
")",
":",
"print",
"(",
"json",
".",
"dumps",
"(",
"d",
",",
"sort_keys",
"=",
"True",
",",
"indent",
"=",
"4",
",",
"separators",
"=",
"(",
"\",\"",
",",
"\": \"",
")",
")",
")"
] | Print dicttree in Json-like format. keys are sorted | [
"Print",
"dicttree",
"in",
"Json",
"-",
"like",
"format",
".",
"keys",
"are",
"sorted"
] | train | https://github.com/MacHu-GWU/angora-project/blob/689a60da51cd88680ddbe26e28dbe81e6b01d275/angora/dtypes/dicttree.py#L378-L382 |
MacHu-GWU/angora-project | angora/dtypes/dicttree.py | DictTree.stats_on_depth | def stats_on_depth(d, depth):
"""Display the node stats info on specific depth in this dict
"""
root_nodes, leaf_nodes = 0, 0
for _, node in DictTree.kv_depth(d, depth):
if DictTree.length(node) == 0:
leaf_nodes += 1
else:
root_node... | python | def stats_on_depth(d, depth):
"""Display the node stats info on specific depth in this dict
"""
root_nodes, leaf_nodes = 0, 0
for _, node in DictTree.kv_depth(d, depth):
if DictTree.length(node) == 0:
leaf_nodes += 1
else:
root_node... | [
"def",
"stats_on_depth",
"(",
"d",
",",
"depth",
")",
":",
"root_nodes",
",",
"leaf_nodes",
"=",
"0",
",",
"0",
"for",
"_",
",",
"node",
"in",
"DictTree",
".",
"kv_depth",
"(",
"d",
",",
"depth",
")",
":",
"if",
"DictTree",
".",
"length",
"(",
"nod... | Display the node stats info on specific depth in this dict | [
"Display",
"the",
"node",
"stats",
"info",
"on",
"specific",
"depth",
"in",
"this",
"dict"
] | train | https://github.com/MacHu-GWU/angora-project/blob/689a60da51cd88680ddbe26e28dbe81e6b01d275/angora/dtypes/dicttree.py#L385-L396 |
hobson/pug-dj | pug/dj/db_routers.py | AppRouter.db_for_read | def db_for_read(self, model, **hints):
"""
If the app has its own database, use it for reads
"""
if model._meta.app_label in self._apps:
return getattr(model, '_db_alias', model._meta.app_label)
return None | python | def db_for_read(self, model, **hints):
"""
If the app has its own database, use it for reads
"""
if model._meta.app_label in self._apps:
return getattr(model, '_db_alias', model._meta.app_label)
return None | [
"def",
"db_for_read",
"(",
"self",
",",
"model",
",",
"*",
"*",
"hints",
")",
":",
"if",
"model",
".",
"_meta",
".",
"app_label",
"in",
"self",
".",
"_apps",
":",
"return",
"getattr",
"(",
"model",
",",
"'_db_alias'",
",",
"model",
".",
"_meta",
".",... | If the app has its own database, use it for reads | [
"If",
"the",
"app",
"has",
"its",
"own",
"database",
"use",
"it",
"for",
"reads"
] | train | https://github.com/hobson/pug-dj/blob/55678b08755a55366ce18e7d3b8ea8fa4491ab04/pug/dj/db_routers.py#L20-L26 |
hobson/pug-dj | pug/dj/db_routers.py | AppRouter.db_for_write | def db_for_write(self, model, **hints):
"""
If the app has its own database, use it for writes
"""
if model._meta.app_label in self._apps:
return getattr(model, '_db_alias', model._meta.app_label)
return None | python | def db_for_write(self, model, **hints):
"""
If the app has its own database, use it for writes
"""
if model._meta.app_label in self._apps:
return getattr(model, '_db_alias', model._meta.app_label)
return None | [
"def",
"db_for_write",
"(",
"self",
",",
"model",
",",
"*",
"*",
"hints",
")",
":",
"if",
"model",
".",
"_meta",
".",
"app_label",
"in",
"self",
".",
"_apps",
":",
"return",
"getattr",
"(",
"model",
",",
"'_db_alias'",
",",
"model",
".",
"_meta",
"."... | If the app has its own database, use it for writes | [
"If",
"the",
"app",
"has",
"its",
"own",
"database",
"use",
"it",
"for",
"writes"
] | train | https://github.com/hobson/pug-dj/blob/55678b08755a55366ce18e7d3b8ea8fa4491ab04/pug/dj/db_routers.py#L28-L34 |
hobson/pug-dj | pug/dj/db_routers.py | AppRouter.allow_migrate | def allow_migrate(self, db, model):
"""
Make sure self._apps go to their own db
"""
if model._meta.app_label in self._apps:
return getattr(model, '_db_alias', model._meta.app_label) == db
return None | python | def allow_migrate(self, db, model):
"""
Make sure self._apps go to their own db
"""
if model._meta.app_label in self._apps:
return getattr(model, '_db_alias', model._meta.app_label) == db
return None | [
"def",
"allow_migrate",
"(",
"self",
",",
"db",
",",
"model",
")",
":",
"if",
"model",
".",
"_meta",
".",
"app_label",
"in",
"self",
".",
"_apps",
":",
"return",
"getattr",
"(",
"model",
",",
"'_db_alias'",
",",
"model",
".",
"_meta",
".",
"app_label",... | Make sure self._apps go to their own db | [
"Make",
"sure",
"self",
".",
"_apps",
"go",
"to",
"their",
"own",
"db"
] | train | https://github.com/hobson/pug-dj/blob/55678b08755a55366ce18e7d3b8ea8fa4491ab04/pug/dj/db_routers.py#L44-L50 |
hobson/pug-dj | pug/dj/db_routers.py | MSRouter.db_for_write | def db_for_write(self, model, **hints):
"""Do not allow writes to BigData (Orig) database"""
if model._meta.app_label in MS_apps:
return model._meta.app_label
# if is_warranty(model):
# return 'warranty'
return None | python | def db_for_write(self, model, **hints):
"""Do not allow writes to BigData (Orig) database"""
if model._meta.app_label in MS_apps:
return model._meta.app_label
# if is_warranty(model):
# return 'warranty'
return None | [
"def",
"db_for_write",
"(",
"self",
",",
"model",
",",
"*",
"*",
"hints",
")",
":",
"if",
"model",
".",
"_meta",
".",
"app_label",
"in",
"MS_apps",
":",
"return",
"model",
".",
"_meta",
".",
"app_label",
"# if is_warranty(model):",
"# return 'warranty'",
... | Do not allow writes to BigData (Orig) database | [
"Do",
"not",
"allow",
"writes",
"to",
"BigData",
"(",
"Orig",
")",
"database"
] | train | https://github.com/hobson/pug-dj/blob/55678b08755a55366ce18e7d3b8ea8fa4491ab04/pug/dj/db_routers.py#L100-L106 |
joaopcanario/imports | imports/imports.py | check | def check(path_dir, requirements_name='requirements.txt'):
'''Look for unused packages listed on project requirements'''
requirements = _load_requirements(requirements_name, path_dir)
imported_modules = _iter_modules(path_dir)
installed_packages = _list_installed_packages()
imported_modules.update(... | python | def check(path_dir, requirements_name='requirements.txt'):
'''Look for unused packages listed on project requirements'''
requirements = _load_requirements(requirements_name, path_dir)
imported_modules = _iter_modules(path_dir)
installed_packages = _list_installed_packages()
imported_modules.update(... | [
"def",
"check",
"(",
"path_dir",
",",
"requirements_name",
"=",
"'requirements.txt'",
")",
":",
"requirements",
"=",
"_load_requirements",
"(",
"requirements_name",
",",
"path_dir",
")",
"imported_modules",
"=",
"_iter_modules",
"(",
"path_dir",
")",
"installed_packag... | Look for unused packages listed on project requirements | [
"Look",
"for",
"unused",
"packages",
"listed",
"on",
"project",
"requirements"
] | train | https://github.com/joaopcanario/imports/blob/46db0d3d2aa55427027bf0e91d61a24d52730337/imports/imports.py#L94-L112 |
jhorman/pledge | pledge/__init__.py | pre | def pre(cond):
"""
Add a precondition check to the annotated method. The condition
is passed the arguments from the annotated method. It does not
need to accept all of the methods parameters. The condition
is inspected to figure out which parameters to pass.
"""
cond_args, cond_varargs, ... | python | def pre(cond):
"""
Add a precondition check to the annotated method. The condition
is passed the arguments from the annotated method. It does not
need to accept all of the methods parameters. The condition
is inspected to figure out which parameters to pass.
"""
cond_args, cond_varargs, ... | [
"def",
"pre",
"(",
"cond",
")",
":",
"cond_args",
",",
"cond_varargs",
",",
"cond_varkw",
",",
"cond_defaults",
"=",
"inspect",
".",
"getargspec",
"(",
"cond",
")",
"source",
"=",
"inspect",
".",
"getsource",
"(",
"cond",
")",
".",
"strip",
"(",
")",
"... | Add a precondition check to the annotated method. The condition
is passed the arguments from the annotated method. It does not
need to accept all of the methods parameters. The condition
is inspected to figure out which parameters to pass. | [
"Add",
"a",
"precondition",
"check",
"to",
"the",
"annotated",
"method",
".",
"The",
"condition",
"is",
"passed",
"the",
"arguments",
"from",
"the",
"annotated",
"method",
".",
"It",
"does",
"not",
"need",
"to",
"accept",
"all",
"of",
"the",
"methods",
"pa... | train | https://github.com/jhorman/pledge/blob/062ba5b788aeb15e68c85a329374a50b4618544d/pledge/__init__.py#L24-L76 |
jhorman/pledge | pledge/__init__.py | post | def post(cond):
"""
Add a postcondition check to the annotated method. The condition
is passed the return value of the annotated method.
"""
source = inspect.getsource(cond).strip()
def inner(f):
if enabled:
# deal with the real function, not a wrapper
f = geta... | python | def post(cond):
"""
Add a postcondition check to the annotated method. The condition
is passed the return value of the annotated method.
"""
source = inspect.getsource(cond).strip()
def inner(f):
if enabled:
# deal with the real function, not a wrapper
f = geta... | [
"def",
"post",
"(",
"cond",
")",
":",
"source",
"=",
"inspect",
".",
"getsource",
"(",
"cond",
")",
".",
"strip",
"(",
")",
"def",
"inner",
"(",
"f",
")",
":",
"if",
"enabled",
":",
"# deal with the real function, not a wrapper",
"f",
"=",
"getattr",
"("... | Add a postcondition check to the annotated method. The condition
is passed the return value of the annotated method. | [
"Add",
"a",
"postcondition",
"check",
"to",
"the",
"annotated",
"method",
".",
"The",
"condition",
"is",
"passed",
"the",
"return",
"value",
"of",
"the",
"annotated",
"method",
"."
] | train | https://github.com/jhorman/pledge/blob/062ba5b788aeb15e68c85a329374a50b4618544d/pledge/__init__.py#L78-L103 |
jhorman/pledge | pledge/__init__.py | takes | def takes(*type_list):
"""
Decorates a function with type checks. Examples
@takes(int): take an int as the first param
@takes(int, str): take and int as first, string as 2nd
@takes(int, (int, None)): take an int as first, and an int or None as second
"""
def inner(f):
if enabled:
... | python | def takes(*type_list):
"""
Decorates a function with type checks. Examples
@takes(int): take an int as the first param
@takes(int, str): take and int as first, string as 2nd
@takes(int, (int, None)): take an int as first, and an int or None as second
"""
def inner(f):
if enabled:
... | [
"def",
"takes",
"(",
"*",
"type_list",
")",
":",
"def",
"inner",
"(",
"f",
")",
":",
"if",
"enabled",
":",
"# deal with the real function, not a wrapper",
"f",
"=",
"getattr",
"(",
"f",
",",
"'wrapped_fn'",
",",
"f",
")",
"# need to check if 'self' is the first ... | Decorates a function with type checks. Examples
@takes(int): take an int as the first param
@takes(int, str): take and int as first, string as 2nd
@takes(int, (int, None)): take an int as first, and an int or None as second | [
"Decorates",
"a",
"function",
"with",
"type",
"checks",
".",
"Examples"
] | train | https://github.com/jhorman/pledge/blob/062ba5b788aeb15e68c85a329374a50b4618544d/pledge/__init__.py#L105-L153 |
jhorman/pledge | pledge/__init__.py | check | def check(f):
"""
Wraps the function with a decorator that runs all of the
pre/post conditions.
"""
if hasattr(f, 'wrapped_fn'):
return f
else:
@wraps(f)
def decorated(*args, **kwargs):
return check_conditions(f, args, kwargs)
decorated.wrapped_fn = f
... | python | def check(f):
"""
Wraps the function with a decorator that runs all of the
pre/post conditions.
"""
if hasattr(f, 'wrapped_fn'):
return f
else:
@wraps(f)
def decorated(*args, **kwargs):
return check_conditions(f, args, kwargs)
decorated.wrapped_fn = f
... | [
"def",
"check",
"(",
"f",
")",
":",
"if",
"hasattr",
"(",
"f",
",",
"'wrapped_fn'",
")",
":",
"return",
"f",
"else",
":",
"@",
"wraps",
"(",
"f",
")",
"def",
"decorated",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"return",
"check_condi... | Wraps the function with a decorator that runs all of the
pre/post conditions. | [
"Wraps",
"the",
"function",
"with",
"a",
"decorator",
"that",
"runs",
"all",
"of",
"the",
"pre",
"/",
"post",
"conditions",
"."
] | train | https://github.com/jhorman/pledge/blob/062ba5b788aeb15e68c85a329374a50b4618544d/pledge/__init__.py#L171-L183 |
jhorman/pledge | pledge/__init__.py | check_conditions | def check_conditions(f, args, kwargs):
"""
This is what runs all of the conditions attached to a method,
along with the conditions on the superclasses.
"""
member_function = is_member_function(f)
# check the functions direct pre conditions
check_preconditions(f, args, kwargs)
# for mem... | python | def check_conditions(f, args, kwargs):
"""
This is what runs all of the conditions attached to a method,
along with the conditions on the superclasses.
"""
member_function = is_member_function(f)
# check the functions direct pre conditions
check_preconditions(f, args, kwargs)
# for mem... | [
"def",
"check_conditions",
"(",
"f",
",",
"args",
",",
"kwargs",
")",
":",
"member_function",
"=",
"is_member_function",
"(",
"f",
")",
"# check the functions direct pre conditions",
"check_preconditions",
"(",
"f",
",",
"args",
",",
"kwargs",
")",
"# for member fun... | This is what runs all of the conditions attached to a method,
along with the conditions on the superclasses. | [
"This",
"is",
"what",
"runs",
"all",
"of",
"the",
"conditions",
"attached",
"to",
"a",
"method",
"along",
"with",
"the",
"conditions",
"on",
"the",
"superclasses",
"."
] | train | https://github.com/jhorman/pledge/blob/062ba5b788aeb15e68c85a329374a50b4618544d/pledge/__init__.py#L185-L215 |
jhorman/pledge | pledge/__init__.py | check_preconditions | def check_preconditions(f, args, kwargs):
""" Runs all of the preconditions. """
f = getattr(f, 'wrapped_fn', f)
if f and hasattr(f, 'preconditions'):
for cond in f.preconditions:
cond(args, kwargs) | python | def check_preconditions(f, args, kwargs):
""" Runs all of the preconditions. """
f = getattr(f, 'wrapped_fn', f)
if f and hasattr(f, 'preconditions'):
for cond in f.preconditions:
cond(args, kwargs) | [
"def",
"check_preconditions",
"(",
"f",
",",
"args",
",",
"kwargs",
")",
":",
"f",
"=",
"getattr",
"(",
"f",
",",
"'wrapped_fn'",
",",
"f",
")",
"if",
"f",
"and",
"hasattr",
"(",
"f",
",",
"'preconditions'",
")",
":",
"for",
"cond",
"in",
"f",
".",... | Runs all of the preconditions. | [
"Runs",
"all",
"of",
"the",
"preconditions",
"."
] | train | https://github.com/jhorman/pledge/blob/062ba5b788aeb15e68c85a329374a50b4618544d/pledge/__init__.py#L217-L222 |
jhorman/pledge | pledge/__init__.py | check_postconditions | def check_postconditions(f, return_value):
""" Runs all of the postconditions. """
f = getattr(f, 'wrapped_fn', f)
if f and hasattr(f, 'postconditions'):
for cond in f.postconditions:
cond(return_value) | python | def check_postconditions(f, return_value):
""" Runs all of the postconditions. """
f = getattr(f, 'wrapped_fn', f)
if f and hasattr(f, 'postconditions'):
for cond in f.postconditions:
cond(return_value) | [
"def",
"check_postconditions",
"(",
"f",
",",
"return_value",
")",
":",
"f",
"=",
"getattr",
"(",
"f",
",",
"'wrapped_fn'",
",",
"f",
")",
"if",
"f",
"and",
"hasattr",
"(",
"f",
",",
"'postconditions'",
")",
":",
"for",
"cond",
"in",
"f",
".",
"postc... | Runs all of the postconditions. | [
"Runs",
"all",
"of",
"the",
"postconditions",
"."
] | train | https://github.com/jhorman/pledge/blob/062ba5b788aeb15e68c85a329374a50b4618544d/pledge/__init__.py#L224-L229 |
jhorman/pledge | pledge/__init__.py | is_member_function | def is_member_function(f):
""" Checks if the first argument to the method is 'self'. """
f_args, f_varargs, f_varkw, f_defaults = inspect.getargspec(f)
return 1 if 'self' in f_args else 0 | python | def is_member_function(f):
""" Checks if the first argument to the method is 'self'. """
f_args, f_varargs, f_varkw, f_defaults = inspect.getargspec(f)
return 1 if 'self' in f_args else 0 | [
"def",
"is_member_function",
"(",
"f",
")",
":",
"f_args",
",",
"f_varargs",
",",
"f_varkw",
",",
"f_defaults",
"=",
"inspect",
".",
"getargspec",
"(",
"f",
")",
"return",
"1",
"if",
"'self'",
"in",
"f_args",
"else",
"0"
] | Checks if the first argument to the method is 'self'. | [
"Checks",
"if",
"the",
"first",
"argument",
"to",
"the",
"method",
"is",
"self",
"."
] | train | https://github.com/jhorman/pledge/blob/062ba5b788aeb15e68c85a329374a50b4618544d/pledge/__init__.py#L231-L234 |
jhorman/pledge | pledge/__init__.py | list_of | def list_of(cls):
"""
Returns a function that checks that each element in a
list is of a specific type.
"""
return lambda l: isinstance(l, list) and all(isinstance(x, cls) for x in l) | python | def list_of(cls):
"""
Returns a function that checks that each element in a
list is of a specific type.
"""
return lambda l: isinstance(l, list) and all(isinstance(x, cls) for x in l) | [
"def",
"list_of",
"(",
"cls",
")",
":",
"return",
"lambda",
"l",
":",
"isinstance",
"(",
"l",
",",
"list",
")",
"and",
"all",
"(",
"isinstance",
"(",
"x",
",",
"cls",
")",
"for",
"x",
"in",
"l",
")"
] | Returns a function that checks that each element in a
list is of a specific type. | [
"Returns",
"a",
"function",
"that",
"checks",
"that",
"each",
"element",
"in",
"a",
"list",
"is",
"of",
"a",
"specific",
"type",
"."
] | train | https://github.com/jhorman/pledge/blob/062ba5b788aeb15e68c85a329374a50b4618544d/pledge/__init__.py#L243-L248 |
jhorman/pledge | pledge/__init__.py | set_of | def set_of(cls):
"""
Returns a function that checks that each element in a
set is of a specific type.
"""
return lambda l: isinstance(l, set) and all(isinstance(x, cls) for x in l) | python | def set_of(cls):
"""
Returns a function that checks that each element in a
set is of a specific type.
"""
return lambda l: isinstance(l, set) and all(isinstance(x, cls) for x in l) | [
"def",
"set_of",
"(",
"cls",
")",
":",
"return",
"lambda",
"l",
":",
"isinstance",
"(",
"l",
",",
"set",
")",
"and",
"all",
"(",
"isinstance",
"(",
"x",
",",
"cls",
")",
"for",
"x",
"in",
"l",
")"
] | Returns a function that checks that each element in a
set is of a specific type. | [
"Returns",
"a",
"function",
"that",
"checks",
"that",
"each",
"element",
"in",
"a",
"set",
"is",
"of",
"a",
"specific",
"type",
"."
] | train | https://github.com/jhorman/pledge/blob/062ba5b788aeb15e68c85a329374a50b4618544d/pledge/__init__.py#L250-L255 |
jalanb/pysyte | pysyte/streams.py | swallow_stdout | def swallow_stdout(stream=None):
"""Divert stdout into the given stream
>>> string = StringIO()
>>> with swallow_stdout(string):
... print('hello')
>>> assert string.getvalue().rstrip() == 'hello'
"""
saved = sys.stdout
if stream is None:
stream = StringIO()
sys.stdout =... | python | def swallow_stdout(stream=None):
"""Divert stdout into the given stream
>>> string = StringIO()
>>> with swallow_stdout(string):
... print('hello')
>>> assert string.getvalue().rstrip() == 'hello'
"""
saved = sys.stdout
if stream is None:
stream = StringIO()
sys.stdout =... | [
"def",
"swallow_stdout",
"(",
"stream",
"=",
"None",
")",
":",
"saved",
"=",
"sys",
".",
"stdout",
"if",
"stream",
"is",
"None",
":",
"stream",
"=",
"StringIO",
"(",
")",
"sys",
".",
"stdout",
"=",
"stream",
"try",
":",
"yield",
"finally",
":",
"sys"... | Divert stdout into the given stream
>>> string = StringIO()
>>> with swallow_stdout(string):
... print('hello')
>>> assert string.getvalue().rstrip() == 'hello' | [
"Divert",
"stdout",
"into",
"the",
"given",
"stream"
] | train | https://github.com/jalanb/pysyte/blob/4e278101943d1ceb1a6bcaf6ddc72052ecf13114/pysyte/streams.py#L11-L26 |
cdeboever3/cdpybio | cdpybio/star.py | read_sj_out_tab | def read_sj_out_tab(filename):
"""Read an SJ.out.tab file as produced by the RNA-STAR aligner into a
pandas Dataframe.
Parameters
----------
filename : str of filename or file handle
Filename of the SJ.out.tab file you want to read in
Returns
-------
sj : pandas.DataFrame
... | python | def read_sj_out_tab(filename):
"""Read an SJ.out.tab file as produced by the RNA-STAR aligner into a
pandas Dataframe.
Parameters
----------
filename : str of filename or file handle
Filename of the SJ.out.tab file you want to read in
Returns
-------
sj : pandas.DataFrame
... | [
"def",
"read_sj_out_tab",
"(",
"filename",
")",
":",
"def",
"int_to_intron_motif",
"(",
"n",
")",
":",
"if",
"n",
"==",
"0",
":",
"return",
"'non-canonical'",
"if",
"n",
"==",
"1",
":",
"return",
"'GT/AG'",
"if",
"n",
"==",
"2",
":",
"return",
"'CT/AC'... | Read an SJ.out.tab file as produced by the RNA-STAR aligner into a
pandas Dataframe.
Parameters
----------
filename : str of filename or file handle
Filename of the SJ.out.tab file you want to read in
Returns
-------
sj : pandas.DataFrame
Dataframe of splice junctions | [
"Read",
"an",
"SJ",
".",
"out",
".",
"tab",
"file",
"as",
"produced",
"by",
"the",
"RNA",
"-",
"STAR",
"aligner",
"into",
"a",
"pandas",
"Dataframe",
"."
] | train | https://github.com/cdeboever3/cdpybio/blob/38efdf0e11d01bc00a135921cb91a19c03db5d5c/cdpybio/star.py#L47-L87 |
cdeboever3/cdpybio | cdpybio/star.py | _make_sj_out_dict | def _make_sj_out_dict(fns, jxns=None, define_sample_name=None):
"""Read multiple sj_outs, return dict with keys as sample names and values
as sj_out dataframes.
Parameters
----------
fns : list of strs of filenames or file handles
List of filename of the SJ.out.tab files to read in
jxn... | python | def _make_sj_out_dict(fns, jxns=None, define_sample_name=None):
"""Read multiple sj_outs, return dict with keys as sample names and values
as sj_out dataframes.
Parameters
----------
fns : list of strs of filenames or file handles
List of filename of the SJ.out.tab files to read in
jxn... | [
"def",
"_make_sj_out_dict",
"(",
"fns",
",",
"jxns",
"=",
"None",
",",
"define_sample_name",
"=",
"None",
")",
":",
"if",
"define_sample_name",
"==",
"None",
":",
"define_sample_name",
"=",
"lambda",
"x",
":",
"x",
"else",
":",
"assert",
"len",
"(",
"set",... | Read multiple sj_outs, return dict with keys as sample names and values
as sj_out dataframes.
Parameters
----------
fns : list of strs of filenames or file handles
List of filename of the SJ.out.tab files to read in
jxns : set
If provided, only keep junctions in this set.
defi... | [
"Read",
"multiple",
"sj_outs",
"return",
"dict",
"with",
"keys",
"as",
"sample",
"names",
"and",
"values",
"as",
"sj_out",
"dataframes",
"."
] | train | https://github.com/cdeboever3/cdpybio/blob/38efdf0e11d01bc00a135921cb91a19c03db5d5c/cdpybio/star.py#L89-L135 |
cdeboever3/cdpybio | cdpybio/star.py | _make_sj_out_panel | def _make_sj_out_panel(sj_outD, total_jxn_cov_cutoff=20):
"""Filter junctions from many sj_out files and make panel.
Parameters
----------
sj_outD : dict
Dict whose keys are sample names and values are sj_out dataframes
total_jxn_cov_cutoff : int
If the unique read coverage of a ju... | python | def _make_sj_out_panel(sj_outD, total_jxn_cov_cutoff=20):
"""Filter junctions from many sj_out files and make panel.
Parameters
----------
sj_outD : dict
Dict whose keys are sample names and values are sj_out dataframes
total_jxn_cov_cutoff : int
If the unique read coverage of a ju... | [
"def",
"_make_sj_out_panel",
"(",
"sj_outD",
",",
"total_jxn_cov_cutoff",
"=",
"20",
")",
":",
"# num_jxns = dict()",
"# # set of all junctions",
"# jxnS = reduce(lambda x,y: set(x) | set(y),",
"# [ sj_outD[k].index for k in sj_outD.keys() ])",
"# jxn_keepS = set()",
"# j... | Filter junctions from many sj_out files and make panel.
Parameters
----------
sj_outD : dict
Dict whose keys are sample names and values are sj_out dataframes
total_jxn_cov_cutoff : int
If the unique read coverage of a junction summed over all samples is not
greater than or equ... | [
"Filter",
"junctions",
"from",
"many",
"sj_out",
"files",
"and",
"make",
"panel",
"."
] | train | https://github.com/cdeboever3/cdpybio/blob/38efdf0e11d01bc00a135921cb91a19c03db5d5c/cdpybio/star.py#L137-L200 |
cdeboever3/cdpybio | cdpybio/star.py | read_external_annotation | def read_external_annotation(fn):
"""Read file with junctions from some database. This does not have to be the
same splice junction database used with STAR.
Parameters
----------
fn : filename str
File with splice junctions from annotation. The file should have a
header and contain ... | python | def read_external_annotation(fn):
"""Read file with junctions from some database. This does not have to be the
same splice junction database used with STAR.
Parameters
----------
fn : filename str
File with splice junctions from annotation. The file should have a
header and contain ... | [
"def",
"read_external_annotation",
"(",
"fn",
")",
":",
"assert",
"os",
".",
"path",
".",
"exists",
"(",
"fn",
")",
"extDF",
"=",
"pd",
".",
"read_table",
"(",
"fn",
",",
"index_col",
"=",
"0",
",",
"header",
"=",
"0",
")",
"total_num",
"=",
"extDF",... | Read file with junctions from some database. This does not have to be the
same splice junction database used with STAR.
Parameters
----------
fn : filename str
File with splice junctions from annotation. The file should have a
header and contain the following columns: 'gene', 'chrom', '... | [
"Read",
"file",
"with",
"junctions",
"from",
"some",
"database",
".",
"This",
"does",
"not",
"have",
"to",
"be",
"the",
"same",
"splice",
"junction",
"database",
"used",
"with",
"STAR",
"."
] | train | https://github.com/cdeboever3/cdpybio/blob/38efdf0e11d01bc00a135921cb91a19c03db5d5c/cdpybio/star.py#L202-L242 |
cdeboever3/cdpybio | cdpybio/star.py | _filter_jxns_donor_acceptor | def _filter_jxns_donor_acceptor(sj_outP, annotDF, extDF):
"""Remove junctions that do not use an annotated donor or acceptor according
to external junction annotation. Add strand and gene information for
junctions according to external annoation (STAR strand ignored).
Parameters
----------
sj_o... | python | def _filter_jxns_donor_acceptor(sj_outP, annotDF, extDF):
"""Remove junctions that do not use an annotated donor or acceptor according
to external junction annotation. Add strand and gene information for
junctions according to external annoation (STAR strand ignored).
Parameters
----------
sj_o... | [
"def",
"_filter_jxns_donor_acceptor",
"(",
"sj_outP",
",",
"annotDF",
",",
"extDF",
")",
":",
"import",
"re",
"sjRE",
"=",
"re",
".",
"compile",
"(",
"'(.*:.*-.*):(\\+|-)'",
")",
"juncRE",
"=",
"re",
".",
"compile",
"(",
"'(.*):(\\d*)-(\\d*):'",
")",
"# Add co... | Remove junctions that do not use an annotated donor or acceptor according
to external junction annotation. Add strand and gene information for
junctions according to external annoation (STAR strand ignored).
Parameters
----------
sj_outP : pandas.Panel
Panel where each dataframe(?) correspo... | [
"Remove",
"junctions",
"that",
"do",
"not",
"use",
"an",
"annotated",
"donor",
"or",
"acceptor",
"according",
"to",
"external",
"junction",
"annotation",
".",
"Add",
"strand",
"and",
"gene",
"information",
"for",
"junctions",
"according",
"to",
"external",
"anno... | train | https://github.com/cdeboever3/cdpybio/blob/38efdf0e11d01bc00a135921cb91a19c03db5d5c/cdpybio/star.py#L244-L449 |
cdeboever3/cdpybio | cdpybio/star.py | combine_sj_out | def combine_sj_out(
fns,
external_db,
total_jxn_cov_cutoff=20,
define_sample_name=None,
verbose=False,
):
"""Combine SJ.out.tab files from STAR by filtering based on coverage and
comparing to an external annotation to discover novel junctions.
Parameters
----------
fns : list... | python | def combine_sj_out(
fns,
external_db,
total_jxn_cov_cutoff=20,
define_sample_name=None,
verbose=False,
):
"""Combine SJ.out.tab files from STAR by filtering based on coverage and
comparing to an external annotation to discover novel junctions.
Parameters
----------
fns : list... | [
"def",
"combine_sj_out",
"(",
"fns",
",",
"external_db",
",",
"total_jxn_cov_cutoff",
"=",
"20",
",",
"define_sample_name",
"=",
"None",
",",
"verbose",
"=",
"False",
",",
")",
":",
"if",
"verbose",
":",
"import",
"sys",
"# I'll start by figuring out which junctio... | Combine SJ.out.tab files from STAR by filtering based on coverage and
comparing to an external annotation to discover novel junctions.
Parameters
----------
fns : list of strings
Filenames of SJ.out.tab files to combine.
external_db : str
Filename of splice junction information fr... | [
"Combine",
"SJ",
".",
"out",
".",
"tab",
"files",
"from",
"STAR",
"by",
"filtering",
"based",
"on",
"coverage",
"and",
"comparing",
"to",
"an",
"external",
"annotation",
"to",
"discover",
"novel",
"junctions",
"."
] | train | https://github.com/cdeboever3/cdpybio/blob/38efdf0e11d01bc00a135921cb91a19c03db5d5c/cdpybio/star.py#L451-L533 |
cdeboever3/cdpybio | cdpybio/star.py | _total_jxn_counts | def _total_jxn_counts(fns):
"""Count the total unique coverage junction for junctions in a set of
SJ.out.tab files."""
df = pd.read_table(fns[0], header=None, names=COLUMN_NAMES)
df.index = (df.chrom + ':' + df.start.astype(int).astype(str) + '-' +
df.end.astype(int).astype(str))
cou... | python | def _total_jxn_counts(fns):
"""Count the total unique coverage junction for junctions in a set of
SJ.out.tab files."""
df = pd.read_table(fns[0], header=None, names=COLUMN_NAMES)
df.index = (df.chrom + ':' + df.start.astype(int).astype(str) + '-' +
df.end.astype(int).astype(str))
cou... | [
"def",
"_total_jxn_counts",
"(",
"fns",
")",
":",
"df",
"=",
"pd",
".",
"read_table",
"(",
"fns",
"[",
"0",
"]",
",",
"header",
"=",
"None",
",",
"names",
"=",
"COLUMN_NAMES",
")",
"df",
".",
"index",
"=",
"(",
"df",
".",
"chrom",
"+",
"':'",
"+"... | Count the total unique coverage junction for junctions in a set of
SJ.out.tab files. | [
"Count",
"the",
"total",
"unique",
"coverage",
"junction",
"for",
"junctions",
"in",
"a",
"set",
"of",
"SJ",
".",
"out",
".",
"tab",
"files",
"."
] | train | https://github.com/cdeboever3/cdpybio/blob/38efdf0e11d01bc00a135921cb91a19c03db5d5c/cdpybio/star.py#L535-L547 |
cdeboever3/cdpybio | cdpybio/star.py | _make_splice_targets_dict | def _make_splice_targets_dict(df, feature, strand):
"""Make dict mapping each donor to the location of all acceptors it splices
to or each acceptor to all donors it splices from.
Parameters
----------
df : pandas.DataFrame
Dataframe with splice junction information from external database
... | python | def _make_splice_targets_dict(df, feature, strand):
"""Make dict mapping each donor to the location of all acceptors it splices
to or each acceptor to all donors it splices from.
Parameters
----------
df : pandas.DataFrame
Dataframe with splice junction information from external database
... | [
"def",
"_make_splice_targets_dict",
"(",
"df",
",",
"feature",
",",
"strand",
")",
":",
"g",
"=",
"df",
"[",
"df",
".",
"strand",
"==",
"strand",
"]",
".",
"groupby",
"(",
"feature",
")",
"d",
"=",
"dict",
"(",
")",
"if",
"strand",
"==",
"'+'",
":"... | Make dict mapping each donor to the location of all acceptors it splices
to or each acceptor to all donors it splices from.
Parameters
----------
df : pandas.DataFrame
Dataframe with splice junction information from external database
containing columns 'gene', 'chrom', 'start', 'end', ... | [
"Make",
"dict",
"mapping",
"each",
"donor",
"to",
"the",
"location",
"of",
"all",
"acceptors",
"it",
"splices",
"to",
"or",
"each",
"acceptor",
"to",
"all",
"donors",
"it",
"splices",
"from",
"."
] | train | https://github.com/cdeboever3/cdpybio/blob/38efdf0e11d01bc00a135921cb91a19c03db5d5c/cdpybio/star.py#L549-L593 |
cdeboever3/cdpybio | cdpybio/star.py | _find_novel_donor_acceptor_dist | def _find_novel_donor_acceptor_dist(annot, ext):
"""Find nearest annotated upstream/downstream donor/acceptor for novel
donor/acceptors.
Parameters
----------
annot : pandas.DataFrame
Dataframe with observed splice junctions (novel and known) with columns
'chrom', 'first_bp_intron',... | python | def _find_novel_donor_acceptor_dist(annot, ext):
"""Find nearest annotated upstream/downstream donor/acceptor for novel
donor/acceptors.
Parameters
----------
annot : pandas.DataFrame
Dataframe with observed splice junctions (novel and known) with columns
'chrom', 'first_bp_intron',... | [
"def",
"_find_novel_donor_acceptor_dist",
"(",
"annot",
",",
"ext",
")",
":",
"pos_donor_to_acceptors",
"=",
"_make_splice_targets_dict",
"(",
"ext",
",",
"'donor'",
",",
"'+'",
")",
"pos_acceptor_to_donors",
"=",
"_make_splice_targets_dict",
"(",
"ext",
",",
"'accept... | Find nearest annotated upstream/downstream donor/acceptor for novel
donor/acceptors.
Parameters
----------
annot : pandas.DataFrame
Dataframe with observed splice junctions (novel and known) with columns
'chrom', 'first_bp_intron', 'last_bp_intron', 'strand', 'intron_motif',
'an... | [
"Find",
"nearest",
"annotated",
"upstream",
"/",
"downstream",
"donor",
"/",
"acceptor",
"for",
"novel",
"donor",
"/",
"acceptors",
"."
] | train | https://github.com/cdeboever3/cdpybio/blob/38efdf0e11d01bc00a135921cb91a19c03db5d5c/cdpybio/star.py#L595-L661 |
cdeboever3/cdpybio | cdpybio/star.py | _dist_to_annot_donor_acceptor | def _dist_to_annot_donor_acceptor(df, d, strand, novel_feature):
"""Find nearest annotated upstream/downstream donor/acceptor for novel
donor/acceptors.
Parameters
----------
df : pandas.DataFrame
Dataframe with observed splice junctions (novel and known) with columns
'chrom', 'firs... | python | def _dist_to_annot_donor_acceptor(df, d, strand, novel_feature):
"""Find nearest annotated upstream/downstream donor/acceptor for novel
donor/acceptors.
Parameters
----------
df : pandas.DataFrame
Dataframe with observed splice junctions (novel and known) with columns
'chrom', 'firs... | [
"def",
"_dist_to_annot_donor_acceptor",
"(",
"df",
",",
"d",
",",
"strand",
",",
"novel_feature",
")",
":",
"if",
"df",
".",
"shape",
"[",
"0",
"]",
">",
"0",
":",
"assert",
"len",
"(",
"set",
"(",
"df",
".",
"strand",
")",
")",
"==",
"1",
"if",
... | Find nearest annotated upstream/downstream donor/acceptor for novel
donor/acceptors.
Parameters
----------
df : pandas.DataFrame
Dataframe with observed splice junctions (novel and known) with columns
'chrom', 'first_bp_intron', 'last_bp_intron', 'strand', 'intron_motif',
'annot... | [
"Find",
"nearest",
"annotated",
"upstream",
"/",
"downstream",
"donor",
"/",
"acceptor",
"for",
"novel",
"donor",
"/",
"acceptors",
"."
] | train | https://github.com/cdeboever3/cdpybio/blob/38efdf0e11d01bc00a135921cb91a19c03db5d5c/cdpybio/star.py#L663-L753 |
cdeboever3/cdpybio | cdpybio/star.py | _read_log | def _read_log(fn, define_sample_name=None):
"""Read STAR Log.final.out file.
Parameters
----------
fn : string
Path to Log.final.out file.
define_sample_name : function that takes string as input
Function mapping filename to sample name. For instance, you may have the
sampl... | python | def _read_log(fn, define_sample_name=None):
"""Read STAR Log.final.out file.
Parameters
----------
fn : string
Path to Log.final.out file.
define_sample_name : function that takes string as input
Function mapping filename to sample name. For instance, you may have the
sampl... | [
"def",
"_read_log",
"(",
"fn",
",",
"define_sample_name",
"=",
"None",
")",
":",
"if",
"define_sample_name",
"==",
"None",
":",
"define_sample_name",
"=",
"lambda",
"x",
":",
"x",
"df",
"=",
"pd",
".",
"read_table",
"(",
"fn",
",",
"'|'",
",",
"header",
... | Read STAR Log.final.out file.
Parameters
----------
fn : string
Path to Log.final.out file.
define_sample_name : function that takes string as input
Function mapping filename to sample name. For instance, you may have the
sample name in the path and use a regex to extract it. ... | [
"Read",
"STAR",
"Log",
".",
"final",
".",
"out",
"file",
"."
] | train | https://github.com/cdeboever3/cdpybio/blob/38efdf0e11d01bc00a135921cb91a19c03db5d5c/cdpybio/star.py#L755-L784 |
cdeboever3/cdpybio | cdpybio/star.py | make_logs_df | def make_logs_df(fns, define_sample_name=None):
"""Make pandas DataFrame from multiple STAR Log.final.out files.
Parameters
----------
fns : string
List of paths to Log.final.out files.
define_sample_name : function that takes string as input
Function mapping filename to sample nam... | python | def make_logs_df(fns, define_sample_name=None):
"""Make pandas DataFrame from multiple STAR Log.final.out files.
Parameters
----------
fns : string
List of paths to Log.final.out files.
define_sample_name : function that takes string as input
Function mapping filename to sample nam... | [
"def",
"make_logs_df",
"(",
"fns",
",",
"define_sample_name",
"=",
"None",
")",
":",
"dfs",
"=",
"[",
"]",
"for",
"fn",
"in",
"fns",
":",
"dfs",
".",
"append",
"(",
"_read_log",
"(",
"fn",
",",
"define_sample_name",
"=",
"define_sample_name",
")",
")",
... | Make pandas DataFrame from multiple STAR Log.final.out files.
Parameters
----------
fns : string
List of paths to Log.final.out files.
define_sample_name : function that takes string as input
Function mapping filename to sample name. For instance, you may have the
sample name i... | [
"Make",
"pandas",
"DataFrame",
"from",
"multiple",
"STAR",
"Log",
".",
"final",
".",
"out",
"files",
"."
] | train | https://github.com/cdeboever3/cdpybio/blob/38efdf0e11d01bc00a135921cb91a19c03db5d5c/cdpybio/star.py#L786-L838 |
zeromake/aiko | aiko/server.py | ServerProtocol.data_received | def data_received(self, data: bytes) -> None:
"""
socket 收到数据
"""
# print(data)
if self._request is None:
# future = self._loop.create_future()
self._request = Request(
cast(asyncio.AbstractEventLoop, self._loop),
self.compl... | python | def data_received(self, data: bytes) -> None:
"""
socket 收到数据
"""
# print(data)
if self._request is None:
# future = self._loop.create_future()
self._request = Request(
cast(asyncio.AbstractEventLoop, self._loop),
self.compl... | [
"def",
"data_received",
"(",
"self",
",",
"data",
":",
"bytes",
")",
"->",
"None",
":",
"# print(data)",
"if",
"self",
".",
"_request",
"is",
"None",
":",
"# future = self._loop.create_future()",
"self",
".",
"_request",
"=",
"Request",
"(",
"cast",
"(",
"as... | socket 收到数据 | [
"socket",
"收到数据"
] | train | https://github.com/zeromake/aiko/blob/53b246fa88652466a9e38ac3d1a99a6198195b0f/aiko/server.py#L62-L76 |
zeromake/aiko | aiko/server.py | ServerProtocol.complete_handle | def complete_handle(self) -> Generator[Any, None, None]:
"""
完成回调
"""
if self._request is None:
return
self._response = Response(
self._loop,
cast(asyncio.Transport, self._transport),
self._request.version or DEFAULT_HTTP_VERSION,
... | python | def complete_handle(self) -> Generator[Any, None, None]:
"""
完成回调
"""
if self._request is None:
return
self._response = Response(
self._loop,
cast(asyncio.Transport, self._transport),
self._request.version or DEFAULT_HTTP_VERSION,
... | [
"def",
"complete_handle",
"(",
"self",
")",
"->",
"Generator",
"[",
"Any",
",",
"None",
",",
"None",
"]",
":",
"if",
"self",
".",
"_request",
"is",
"None",
":",
"return",
"self",
".",
"_response",
"=",
"Response",
"(",
"self",
".",
"_loop",
",",
"cas... | 完成回调 | [
"完成回调"
] | train | https://github.com/zeromake/aiko/blob/53b246fa88652466a9e38ac3d1a99a6198195b0f/aiko/server.py#L79-L99 |
mariocesar/pengbot | examples/bob.py | uptime | def uptime():
"""Uptime of the host machine"""
from datetime import timedelta
with open('/proc/uptime', 'r') as f:
uptime_seconds = float(f.readline().split()[0])
uptime_string = str(timedelta(seconds=uptime_seconds))
bob.says(uptime_string) | python | def uptime():
"""Uptime of the host machine"""
from datetime import timedelta
with open('/proc/uptime', 'r') as f:
uptime_seconds = float(f.readline().split()[0])
uptime_string = str(timedelta(seconds=uptime_seconds))
bob.says(uptime_string) | [
"def",
"uptime",
"(",
")",
":",
"from",
"datetime",
"import",
"timedelta",
"with",
"open",
"(",
"'/proc/uptime'",
",",
"'r'",
")",
"as",
"f",
":",
"uptime_seconds",
"=",
"float",
"(",
"f",
".",
"readline",
"(",
")",
".",
"split",
"(",
")",
"[",
"0",
... | Uptime of the host machine | [
"Uptime",
"of",
"the",
"host",
"machine"
] | train | https://github.com/mariocesar/pengbot/blob/070854f92ac1314ee56f7f6cb9d27430b8f0fda8/examples/bob.py#L112-L120 |
firstprayer/monsql | monsql/query.py | value_to_sql_str | def value_to_sql_str(v):
"""
transform a python variable to the appropriate representation in SQL
"""
if v is None:
return 'null'
if type(v) in (types.IntType, types.FloatType, types.LongType):
return str(v)
if type(v) in (types.StringType, types.UnicodeType):
return "'... | python | def value_to_sql_str(v):
"""
transform a python variable to the appropriate representation in SQL
"""
if v is None:
return 'null'
if type(v) in (types.IntType, types.FloatType, types.LongType):
return str(v)
if type(v) in (types.StringType, types.UnicodeType):
return "'... | [
"def",
"value_to_sql_str",
"(",
"v",
")",
":",
"if",
"v",
"is",
"None",
":",
"return",
"'null'",
"if",
"type",
"(",
"v",
")",
"in",
"(",
"types",
".",
"IntType",
",",
"types",
".",
"FloatType",
",",
"types",
".",
"LongType",
")",
":",
"return",
"st... | transform a python variable to the appropriate representation in SQL | [
"transform",
"a",
"python",
"variable",
"to",
"the",
"appropriate",
"representation",
"in",
"SQL"
] | train | https://github.com/firstprayer/monsql/blob/6285c15b574c8664046eae2edfeb548c7b173efd/monsql/query.py#L51-L70 |
firstprayer/monsql | monsql/query.py | QueryCondition.to_sql | def to_sql(self):
"""
This function build a sql condition string (those used in the 'WHERE' clause) based on given condition
Supported match pattern:
{a: 1} -> a == 1
{a: {$gt: 1}} -> a > 1
{a: {$gte: 1}} ... | python | def to_sql(self):
"""
This function build a sql condition string (those used in the 'WHERE' clause) based on given condition
Supported match pattern:
{a: 1} -> a == 1
{a: {$gt: 1}} -> a > 1
{a: {$gte: 1}} ... | [
"def",
"to_sql",
"(",
"self",
")",
":",
"condition",
"=",
"self",
".",
"condition",
"if",
"condition",
":",
"# If the condition is not None nor empty",
"if",
"len",
"(",
"condition",
".",
"keys",
"(",
")",
")",
">",
"1",
":",
"# If in the form of {'a': 1, 'b': 2... | This function build a sql condition string (those used in the 'WHERE' clause) based on given condition
Supported match pattern:
{a: 1} -> a == 1
{a: {$gt: 1}} -> a > 1
{a: {$gte: 1}} -> a >= 1
{a: {$lt: 1}} ... | [
"This",
"function",
"build",
"a",
"sql",
"condition",
"string",
"(",
"those",
"used",
"in",
"the",
"WHERE",
"clause",
")",
"based",
"on",
"given",
"condition",
"Supported",
"match",
"pattern",
":"
] | train | https://github.com/firstprayer/monsql/blob/6285c15b574c8664046eae2edfeb548c7b173efd/monsql/query.py#L85-L193 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.