repo stringlengths 7 55 | path stringlengths 4 127 | func_name stringlengths 1 88 | original_string stringlengths 75 19.8k | language stringclasses 1
value | code stringlengths 75 19.8k | code_tokens listlengths 20 707 | docstring stringlengths 3 17.3k | docstring_tokens listlengths 3 222 | sha stringlengths 40 40 | url stringlengths 87 242 | partition stringclasses 1
value | idx int64 0 252k |
|---|---|---|---|---|---|---|---|---|---|---|---|---|
kevinconway/confpy | confpy/core/config.py | Configuration.register | def register(self, name, namespace):
"""Register a new namespace with the Configuration object.
Args:
name (str): The name of the section/namespace.
namespace (namespace.Namespace): The Namespace object to store.
Raises:
TypeError: If the namespace is not a ... | python | def register(self, name, namespace):
"""Register a new namespace with the Configuration object.
Args:
name (str): The name of the section/namespace.
namespace (namespace.Namespace): The Namespace object to store.
Raises:
TypeError: If the namespace is not a ... | [
"def",
"register",
"(",
"self",
",",
"name",
",",
"namespace",
")",
":",
"if",
"name",
"in",
"self",
".",
"_NAMESPACES",
":",
"raise",
"ValueError",
"(",
"\"Namespace {0} already exists.\"",
".",
"format",
"(",
"name",
")",
")",
"if",
"not",
"isinstance",
... | Register a new namespace with the Configuration object.
Args:
name (str): The name of the section/namespace.
namespace (namespace.Namespace): The Namespace object to store.
Raises:
TypeError: If the namespace is not a Namespace object.
ValueError: If the... | [
"Register",
"a",
"new",
"namespace",
"with",
"the",
"Configuration",
"object",
"."
] | 1ee8afcab46ac6915a5ff4184180434ac7b84a60 | https://github.com/kevinconway/confpy/blob/1ee8afcab46ac6915a5ff4184180434ac7b84a60/confpy/core/config.py#L53-L72 | train | 56,300 |
abakan-zz/napi | napi/transformers.py | napi_compare | def napi_compare(left, ops, comparators, **kwargs):
"""Make pairwise comparisons of comparators."""
values = []
for op, right in zip(ops, comparators):
value = COMPARE[op](left, right)
values.append(value)
left = right
result = napi_and(values, **kwargs)
if isinstance(result... | python | def napi_compare(left, ops, comparators, **kwargs):
"""Make pairwise comparisons of comparators."""
values = []
for op, right in zip(ops, comparators):
value = COMPARE[op](left, right)
values.append(value)
left = right
result = napi_and(values, **kwargs)
if isinstance(result... | [
"def",
"napi_compare",
"(",
"left",
",",
"ops",
",",
"comparators",
",",
"*",
"*",
"kwargs",
")",
":",
"values",
"=",
"[",
"]",
"for",
"op",
",",
"right",
"in",
"zip",
"(",
"ops",
",",
"comparators",
")",
":",
"value",
"=",
"COMPARE",
"[",
"op",
... | Make pairwise comparisons of comparators. | [
"Make",
"pairwise",
"comparisons",
"of",
"comparators",
"."
] | 314da65bd78e2c716b7efb6deaf3816d8f38f7fd | https://github.com/abakan-zz/napi/blob/314da65bd78e2c716b7efb6deaf3816d8f38f7fd/napi/transformers.py#L145-L157 | train | 56,301 |
diamondman/proteusisc | proteusisc/jtagStateMachine.py | JTAGStateMachine.calc_transition_to_state | def calc_transition_to_state(self, newstate):
"""Given a target state, generate the sequence of transitions that would move this state machine instance to that target state.
Args:
newstate: A str state name to calculate the path to.
Returns:
A bitarray containing the bi... | python | def calc_transition_to_state(self, newstate):
"""Given a target state, generate the sequence of transitions that would move this state machine instance to that target state.
Args:
newstate: A str state name to calculate the path to.
Returns:
A bitarray containing the bi... | [
"def",
"calc_transition_to_state",
"(",
"self",
",",
"newstate",
")",
":",
"cached_val",
"=",
"JTAGStateMachine",
".",
"_lookup_cache",
".",
"get",
"(",
"(",
"self",
".",
"state",
",",
"newstate",
")",
")",
"if",
"cached_val",
":",
"return",
"cached_val",
"i... | Given a target state, generate the sequence of transitions that would move this state machine instance to that target state.
Args:
newstate: A str state name to calculate the path to.
Returns:
A bitarray containing the bits that would transition this
state machine t... | [
"Given",
"a",
"target",
"state",
"generate",
"the",
"sequence",
"of",
"transitions",
"that",
"would",
"move",
"this",
"state",
"machine",
"instance",
"to",
"that",
"target",
"state",
"."
] | 7622b7b04e63f9dc0f5a04429ff78d9a490c9c5c | https://github.com/diamondman/proteusisc/blob/7622b7b04e63f9dc0f5a04429ff78d9a490c9c5c/proteusisc/jtagStateMachine.py#L86-L114 | train | 56,302 |
bitesofcode/projex | projex/hooks.py | setup | def setup():
"""
Initializes the hook queues for the sys module. This method will
automatically be called on the first registration for a hook to the system
by either the registerDisplay or registerExcept functions.
"""
global _displayhooks, _excepthooks
if _displayhooks is not None:
... | python | def setup():
"""
Initializes the hook queues for the sys module. This method will
automatically be called on the first registration for a hook to the system
by either the registerDisplay or registerExcept functions.
"""
global _displayhooks, _excepthooks
if _displayhooks is not None:
... | [
"def",
"setup",
"(",
")",
":",
"global",
"_displayhooks",
",",
"_excepthooks",
"if",
"_displayhooks",
"is",
"not",
"None",
":",
"return",
"_displayhooks",
"=",
"[",
"]",
"_excepthooks",
"=",
"[",
"]",
"# store any current hooks",
"if",
"sys",
".",
"displayhook... | Initializes the hook queues for the sys module. This method will
automatically be called on the first registration for a hook to the system
by either the registerDisplay or registerExcept functions. | [
"Initializes",
"the",
"hook",
"queues",
"for",
"the",
"sys",
"module",
".",
"This",
"method",
"will",
"automatically",
"be",
"called",
"on",
"the",
"first",
"registration",
"for",
"a",
"hook",
"to",
"the",
"system",
"by",
"either",
"the",
"registerDisplay",
... | d31743ec456a41428709968ab11a2cf6c6c76247 | https://github.com/bitesofcode/projex/blob/d31743ec456a41428709968ab11a2cf6c6c76247/projex/hooks.py#L188-L210 | train | 56,303 |
LeastAuthority/txkube | src/txkube/_swagger.py | _parse_iso8601 | def _parse_iso8601(text):
"""
Maybe parse an ISO8601 datetime string into a datetime.
:param text: Either a ``unicode`` string to parse or any other object
(ideally a ``datetime`` instance) to pass through.
:return: A ``datetime.datetime`` representing ``text``. Or ``text`` if it
was ... | python | def _parse_iso8601(text):
"""
Maybe parse an ISO8601 datetime string into a datetime.
:param text: Either a ``unicode`` string to parse or any other object
(ideally a ``datetime`` instance) to pass through.
:return: A ``datetime.datetime`` representing ``text``. Or ``text`` if it
was ... | [
"def",
"_parse_iso8601",
"(",
"text",
")",
":",
"if",
"isinstance",
"(",
"text",
",",
"unicode",
")",
":",
"try",
":",
"return",
"parse_iso8601",
"(",
"text",
")",
"except",
"ValueError",
":",
"raise",
"CheckedValueTypeError",
"(",
"None",
",",
"(",
"datet... | Maybe parse an ISO8601 datetime string into a datetime.
:param text: Either a ``unicode`` string to parse or any other object
(ideally a ``datetime`` instance) to pass through.
:return: A ``datetime.datetime`` representing ``text``. Or ``text`` if it
was anything but a ``unicode`` string. | [
"Maybe",
"parse",
"an",
"ISO8601",
"datetime",
"string",
"into",
"a",
"datetime",
"."
] | a7e555d00535ff787d4b1204c264780da40cf736 | https://github.com/LeastAuthority/txkube/blob/a7e555d00535ff787d4b1204c264780da40cf736/src/txkube/_swagger.py#L578-L596 | train | 56,304 |
LeastAuthority/txkube | src/txkube/_swagger.py | Swagger.from_path | def from_path(cls, spec_path):
"""
Load a specification from a path.
:param FilePath spec_path: The location of the specification to read.
"""
with spec_path.open() as spec_file:
return cls.from_document(load(spec_file)) | python | def from_path(cls, spec_path):
"""
Load a specification from a path.
:param FilePath spec_path: The location of the specification to read.
"""
with spec_path.open() as spec_file:
return cls.from_document(load(spec_file)) | [
"def",
"from_path",
"(",
"cls",
",",
"spec_path",
")",
":",
"with",
"spec_path",
".",
"open",
"(",
")",
"as",
"spec_file",
":",
"return",
"cls",
".",
"from_document",
"(",
"load",
"(",
"spec_file",
")",
")"
] | Load a specification from a path.
:param FilePath spec_path: The location of the specification to read. | [
"Load",
"a",
"specification",
"from",
"a",
"path",
"."
] | a7e555d00535ff787d4b1204c264780da40cf736 | https://github.com/LeastAuthority/txkube/blob/a7e555d00535ff787d4b1204c264780da40cf736/src/txkube/_swagger.py#L98-L105 | train | 56,305 |
LeastAuthority/txkube | src/txkube/_swagger.py | Swagger.to_document | def to_document(self):
"""
Serialize this specification to a JSON-compatible object representing a
Swagger specification.
"""
return dict(
info=thaw(self.info),
paths=thaw(self.paths),
definitions=thaw(self.definitions),
securityDef... | python | def to_document(self):
"""
Serialize this specification to a JSON-compatible object representing a
Swagger specification.
"""
return dict(
info=thaw(self.info),
paths=thaw(self.paths),
definitions=thaw(self.definitions),
securityDef... | [
"def",
"to_document",
"(",
"self",
")",
":",
"return",
"dict",
"(",
"info",
"=",
"thaw",
"(",
"self",
".",
"info",
")",
",",
"paths",
"=",
"thaw",
"(",
"self",
".",
"paths",
")",
",",
"definitions",
"=",
"thaw",
"(",
"self",
".",
"definitions",
")"... | Serialize this specification to a JSON-compatible object representing a
Swagger specification. | [
"Serialize",
"this",
"specification",
"to",
"a",
"JSON",
"-",
"compatible",
"object",
"representing",
"a",
"Swagger",
"specification",
"."
] | a7e555d00535ff787d4b1204c264780da40cf736 | https://github.com/LeastAuthority/txkube/blob/a7e555d00535ff787d4b1204c264780da40cf736/src/txkube/_swagger.py#L143-L155 | train | 56,306 |
LeastAuthority/txkube | src/txkube/_swagger.py | Swagger.pclass_for_definition | def pclass_for_definition(self, name):
"""
Get a ``pyrsistent.PClass`` subclass representing the Swagger definition
in this specification which corresponds to the given name.
:param unicode name: The name of the definition to use.
:return: A Python class which can be used to re... | python | def pclass_for_definition(self, name):
"""
Get a ``pyrsistent.PClass`` subclass representing the Swagger definition
in this specification which corresponds to the given name.
:param unicode name: The name of the definition to use.
:return: A Python class which can be used to re... | [
"def",
"pclass_for_definition",
"(",
"self",
",",
"name",
")",
":",
"while",
"True",
":",
"try",
":",
"cls",
"=",
"self",
".",
"_pclasses",
"[",
"name",
"]",
"except",
"KeyError",
":",
"try",
":",
"original_definition",
"=",
"self",
".",
"definitions",
"... | Get a ``pyrsistent.PClass`` subclass representing the Swagger definition
in this specification which corresponds to the given name.
:param unicode name: The name of the definition to use.
:return: A Python class which can be used to represent the Swagger
definition of the given nam... | [
"Get",
"a",
"pyrsistent",
".",
"PClass",
"subclass",
"representing",
"the",
"Swagger",
"definition",
"in",
"this",
"specification",
"which",
"corresponds",
"to",
"the",
"given",
"name",
"."
] | a7e555d00535ff787d4b1204c264780da40cf736 | https://github.com/LeastAuthority/txkube/blob/a7e555d00535ff787d4b1204c264780da40cf736/src/txkube/_swagger.py#L158-L197 | train | 56,307 |
LeastAuthority/txkube | src/txkube/_swagger.py | Swagger._model_for_CLASS | def _model_for_CLASS(self, name, definition):
"""
Model a Swagger definition that is like a Python class.
:param unicode name: The name of the definition from the
specification.
:param pyrsistent.PMap definition: A Swagger definition to categorize.
This will be ... | python | def _model_for_CLASS(self, name, definition):
"""
Model a Swagger definition that is like a Python class.
:param unicode name: The name of the definition from the
specification.
:param pyrsistent.PMap definition: A Swagger definition to categorize.
This will be ... | [
"def",
"_model_for_CLASS",
"(",
"self",
",",
"name",
",",
"definition",
")",
":",
"return",
"_ClassModel",
".",
"from_swagger",
"(",
"self",
".",
"pclass_for_definition",
",",
"name",
",",
"definition",
",",
")"
] | Model a Swagger definition that is like a Python class.
:param unicode name: The name of the definition from the
specification.
:param pyrsistent.PMap definition: A Swagger definition to categorize.
This will be a value like the one found at
``spec["definitions"][na... | [
"Model",
"a",
"Swagger",
"definition",
"that",
"is",
"like",
"a",
"Python",
"class",
"."
] | a7e555d00535ff787d4b1204c264780da40cf736 | https://github.com/LeastAuthority/txkube/blob/a7e555d00535ff787d4b1204c264780da40cf736/src/txkube/_swagger.py#L220-L235 | train | 56,308 |
LeastAuthority/txkube | src/txkube/_swagger.py | _ClassModel.from_swagger | def from_swagger(cls, pclass_for_definition, name, definition):
"""
Create a new ``_ClassModel`` from a single Swagger definition.
:param pclass_for_definition: A callable like
``Swagger.pclass_for_definition`` which can be used to resolve
type references encountered in ... | python | def from_swagger(cls, pclass_for_definition, name, definition):
"""
Create a new ``_ClassModel`` from a single Swagger definition.
:param pclass_for_definition: A callable like
``Swagger.pclass_for_definition`` which can be used to resolve
type references encountered in ... | [
"def",
"from_swagger",
"(",
"cls",
",",
"pclass_for_definition",
",",
"name",
",",
"definition",
")",
":",
"return",
"cls",
"(",
"name",
"=",
"name",
",",
"doc",
"=",
"definition",
".",
"get",
"(",
"u\"description\"",
",",
"name",
")",
",",
"attributes",
... | Create a new ``_ClassModel`` from a single Swagger definition.
:param pclass_for_definition: A callable like
``Swagger.pclass_for_definition`` which can be used to resolve
type references encountered in the definition.
:param unicode name: The name of the definition.
:... | [
"Create",
"a",
"new",
"_ClassModel",
"from",
"a",
"single",
"Swagger",
"definition",
"."
] | a7e555d00535ff787d4b1204c264780da40cf736 | https://github.com/LeastAuthority/txkube/blob/a7e555d00535ff787d4b1204c264780da40cf736/src/txkube/_swagger.py#L736-L758 | train | 56,309 |
LeastAuthority/txkube | src/txkube/_swagger.py | _ClassModel.pclass | def pclass(self, bases):
"""
Create a ``pyrsistent.PClass`` subclass representing this class.
:param tuple bases: Additional base classes to give the resulting
class. These will appear to the left of ``PClass``.
"""
def discard_constant_fields(cls, **kwargs):
... | python | def pclass(self, bases):
"""
Create a ``pyrsistent.PClass`` subclass representing this class.
:param tuple bases: Additional base classes to give the resulting
class. These will appear to the left of ``PClass``.
"""
def discard_constant_fields(cls, **kwargs):
... | [
"def",
"pclass",
"(",
"self",
",",
"bases",
")",
":",
"def",
"discard_constant_fields",
"(",
"cls",
",",
"*",
"*",
"kwargs",
")",
":",
"def",
"ctor",
"(",
")",
":",
"return",
"super",
"(",
"huh",
",",
"cls",
")",
".",
"__new__",
"(",
"cls",
",",
... | Create a ``pyrsistent.PClass`` subclass representing this class.
:param tuple bases: Additional base classes to give the resulting
class. These will appear to the left of ``PClass``. | [
"Create",
"a",
"pyrsistent",
".",
"PClass",
"subclass",
"representing",
"this",
"class",
"."
] | a7e555d00535ff787d4b1204c264780da40cf736 | https://github.com/LeastAuthority/txkube/blob/a7e555d00535ff787d4b1204c264780da40cf736/src/txkube/_swagger.py#L761-L806 | train | 56,310 |
LeastAuthority/txkube | src/txkube/_compat.py | dumps_bytes | def dumps_bytes(obj):
"""
Serialize ``obj`` to JSON formatted ``bytes``.
"""
b = dumps(obj)
if isinstance(b, unicode):
b = b.encode("ascii")
return b | python | def dumps_bytes(obj):
"""
Serialize ``obj`` to JSON formatted ``bytes``.
"""
b = dumps(obj)
if isinstance(b, unicode):
b = b.encode("ascii")
return b | [
"def",
"dumps_bytes",
"(",
"obj",
")",
":",
"b",
"=",
"dumps",
"(",
"obj",
")",
"if",
"isinstance",
"(",
"b",
",",
"unicode",
")",
":",
"b",
"=",
"b",
".",
"encode",
"(",
"\"ascii\"",
")",
"return",
"b"
] | Serialize ``obj`` to JSON formatted ``bytes``. | [
"Serialize",
"obj",
"to",
"JSON",
"formatted",
"bytes",
"."
] | a7e555d00535ff787d4b1204c264780da40cf736 | https://github.com/LeastAuthority/txkube/blob/a7e555d00535ff787d4b1204c264780da40cf736/src/txkube/_compat.py#L12-L19 | train | 56,311 |
LeastAuthority/txkube | src/txkube/_compat.py | native_string_to_bytes | def native_string_to_bytes(s, encoding="ascii", errors="strict"):
"""
Ensure that the native string ``s`` is converted to ``bytes``.
"""
if not isinstance(s, str):
raise TypeError("{} must be type str, not {}".format(s, type(s)))
if str is bytes:
# Python 2
return s
else:... | python | def native_string_to_bytes(s, encoding="ascii", errors="strict"):
"""
Ensure that the native string ``s`` is converted to ``bytes``.
"""
if not isinstance(s, str):
raise TypeError("{} must be type str, not {}".format(s, type(s)))
if str is bytes:
# Python 2
return s
else:... | [
"def",
"native_string_to_bytes",
"(",
"s",
",",
"encoding",
"=",
"\"ascii\"",
",",
"errors",
"=",
"\"strict\"",
")",
":",
"if",
"not",
"isinstance",
"(",
"s",
",",
"str",
")",
":",
"raise",
"TypeError",
"(",
"\"{} must be type str, not {}\"",
".",
"format",
... | Ensure that the native string ``s`` is converted to ``bytes``. | [
"Ensure",
"that",
"the",
"native",
"string",
"s",
"is",
"converted",
"to",
"bytes",
"."
] | a7e555d00535ff787d4b1204c264780da40cf736 | https://github.com/LeastAuthority/txkube/blob/a7e555d00535ff787d4b1204c264780da40cf736/src/txkube/_compat.py#L23-L34 | train | 56,312 |
LeastAuthority/txkube | src/txkube/_compat.py | native_string_to_unicode | def native_string_to_unicode(s, encoding="ascii", errors="strict"):
"""
Ensure that the native string ``s`` is converted to ``unicode``.
"""
if not isinstance(s, str):
raise TypeError("{} must be type str, not {}".format(s, type(s)))
if str is unicode:
# Python 3
return s
... | python | def native_string_to_unicode(s, encoding="ascii", errors="strict"):
"""
Ensure that the native string ``s`` is converted to ``unicode``.
"""
if not isinstance(s, str):
raise TypeError("{} must be type str, not {}".format(s, type(s)))
if str is unicode:
# Python 3
return s
... | [
"def",
"native_string_to_unicode",
"(",
"s",
",",
"encoding",
"=",
"\"ascii\"",
",",
"errors",
"=",
"\"strict\"",
")",
":",
"if",
"not",
"isinstance",
"(",
"s",
",",
"str",
")",
":",
"raise",
"TypeError",
"(",
"\"{} must be type str, not {}\"",
".",
"format",
... | Ensure that the native string ``s`` is converted to ``unicode``. | [
"Ensure",
"that",
"the",
"native",
"string",
"s",
"is",
"converted",
"to",
"unicode",
"."
] | a7e555d00535ff787d4b1204c264780da40cf736 | https://github.com/LeastAuthority/txkube/blob/a7e555d00535ff787d4b1204c264780da40cf736/src/txkube/_compat.py#L38-L49 | train | 56,313 |
pauleveritt/kaybee | kaybee/utils/datetime_handler.py | datetime_handler | def datetime_handler(x):
""" Allow serializing datetime objects to JSON """
if isinstance(x, datetime.datetime) or isinstance(x, datetime.date):
return x.isoformat()
raise TypeError("Unknown type") | python | def datetime_handler(x):
""" Allow serializing datetime objects to JSON """
if isinstance(x, datetime.datetime) or isinstance(x, datetime.date):
return x.isoformat()
raise TypeError("Unknown type") | [
"def",
"datetime_handler",
"(",
"x",
")",
":",
"if",
"isinstance",
"(",
"x",
",",
"datetime",
".",
"datetime",
")",
"or",
"isinstance",
"(",
"x",
",",
"datetime",
".",
"date",
")",
":",
"return",
"x",
".",
"isoformat",
"(",
")",
"raise",
"TypeError",
... | Allow serializing datetime objects to JSON | [
"Allow",
"serializing",
"datetime",
"objects",
"to",
"JSON"
] | a00a718aaaa23b2d12db30dfacb6b2b6ec84459c | https://github.com/pauleveritt/kaybee/blob/a00a718aaaa23b2d12db30dfacb6b2b6ec84459c/kaybee/utils/datetime_handler.py#L4-L8 | train | 56,314 |
kevinconway/confpy | confpy/loaders/pyfile.py | PythonFile.parsed | def parsed(self):
"""Get the code object which represents the compiled Python file.
This property is cached and only parses the content once.
"""
if not self._parsed:
self._parsed = compile(self.content, self.path, 'exec')
return self._parsed | python | def parsed(self):
"""Get the code object which represents the compiled Python file.
This property is cached and only parses the content once.
"""
if not self._parsed:
self._parsed = compile(self.content, self.path, 'exec')
return self._parsed | [
"def",
"parsed",
"(",
"self",
")",
":",
"if",
"not",
"self",
".",
"_parsed",
":",
"self",
".",
"_parsed",
"=",
"compile",
"(",
"self",
".",
"content",
",",
"self",
".",
"path",
",",
"'exec'",
")",
"return",
"self",
".",
"_parsed"
] | Get the code object which represents the compiled Python file.
This property is cached and only parses the content once. | [
"Get",
"the",
"code",
"object",
"which",
"represents",
"the",
"compiled",
"Python",
"file",
"."
] | 1ee8afcab46ac6915a5ff4184180434ac7b84a60 | https://github.com/kevinconway/confpy/blob/1ee8afcab46ac6915a5ff4184180434ac7b84a60/confpy/loaders/pyfile.py#L26-L35 | train | 56,315 |
chrisbouchard/braillegraph | braillegraph/braillegraph.py | _chunk | def _chunk(iterable, size):
"""Split an iterable into chunks of a fixed size."""
# We're going to use some star magic to chunk the iterable. We create a
# copy of the iterator size times, then pull a value from each to form a
# chunk. The last chunk may have some trailing Nones if the length of the
... | python | def _chunk(iterable, size):
"""Split an iterable into chunks of a fixed size."""
# We're going to use some star magic to chunk the iterable. We create a
# copy of the iterator size times, then pull a value from each to form a
# chunk. The last chunk may have some trailing Nones if the length of the
... | [
"def",
"_chunk",
"(",
"iterable",
",",
"size",
")",
":",
"# We're going to use some star magic to chunk the iterable. We create a",
"# copy of the iterator size times, then pull a value from each to form a",
"# chunk. The last chunk may have some trailing Nones if the length of the",
"# iterab... | Split an iterable into chunks of a fixed size. | [
"Split",
"an",
"iterable",
"into",
"chunks",
"of",
"a",
"fixed",
"size",
"."
] | 744ca8394676579cfb11e5c297c9bd794ab5bd78 | https://github.com/chrisbouchard/braillegraph/blob/744ca8394676579cfb11e5c297c9bd794ab5bd78/braillegraph/braillegraph.py#L73-L86 | train | 56,316 |
chrisbouchard/braillegraph | braillegraph/braillegraph.py | _matrix_add_column | def _matrix_add_column(matrix, column, default=0):
"""Given a matrix as a list of lists, add a column to the right, filling in
with a default value if necessary.
"""
height_difference = len(column) - len(matrix)
# The width of the matrix is the length of its longest row.
width = max(len(row) fo... | python | def _matrix_add_column(matrix, column, default=0):
"""Given a matrix as a list of lists, add a column to the right, filling in
with a default value if necessary.
"""
height_difference = len(column) - len(matrix)
# The width of the matrix is the length of its longest row.
width = max(len(row) fo... | [
"def",
"_matrix_add_column",
"(",
"matrix",
",",
"column",
",",
"default",
"=",
"0",
")",
":",
"height_difference",
"=",
"len",
"(",
"column",
")",
"-",
"len",
"(",
"matrix",
")",
"# The width of the matrix is the length of its longest row.",
"width",
"=",
"max",
... | Given a matrix as a list of lists, add a column to the right, filling in
with a default value if necessary. | [
"Given",
"a",
"matrix",
"as",
"a",
"list",
"of",
"lists",
"add",
"a",
"column",
"to",
"the",
"right",
"filling",
"in",
"with",
"a",
"default",
"value",
"if",
"necessary",
"."
] | 744ca8394676579cfb11e5c297c9bd794ab5bd78 | https://github.com/chrisbouchard/braillegraph/blob/744ca8394676579cfb11e5c297c9bd794ab5bd78/braillegraph/braillegraph.py#L89-L120 | train | 56,317 |
chrisbouchard/braillegraph | braillegraph/braillegraph.py | vertical_graph | def vertical_graph(*args, sep='\n'):
r"""Consume an iterable of integers and produce a vertical bar graph using
braille characters.
The graph is vertical in that its dependent axis is the vertical axis. Thus
each value is represented as a row running left to right, and values are
listed top to bott... | python | def vertical_graph(*args, sep='\n'):
r"""Consume an iterable of integers and produce a vertical bar graph using
braille characters.
The graph is vertical in that its dependent axis is the vertical axis. Thus
each value is represented as a row running left to right, and values are
listed top to bott... | [
"def",
"vertical_graph",
"(",
"*",
"args",
",",
"sep",
"=",
"'\\n'",
")",
":",
"lines",
"=",
"[",
"]",
"# If the arguments were passed as a single iterable, pull it out.",
"# Otherwise, just use them as-is.",
"if",
"len",
"(",
"args",
")",
"==",
"1",
":",
"bars",
... | r"""Consume an iterable of integers and produce a vertical bar graph using
braille characters.
The graph is vertical in that its dependent axis is the vertical axis. Thus
each value is represented as a row running left to right, and values are
listed top to bottom.
If the iterable contains more th... | [
"r",
"Consume",
"an",
"iterable",
"of",
"integers",
"and",
"produce",
"a",
"vertical",
"bar",
"graph",
"using",
"braille",
"characters",
"."
] | 744ca8394676579cfb11e5c297c9bd794ab5bd78 | https://github.com/chrisbouchard/braillegraph/blob/744ca8394676579cfb11e5c297c9bd794ab5bd78/braillegraph/braillegraph.py#L123-L204 | train | 56,318 |
chrisbouchard/braillegraph | braillegraph/braillegraph.py | horizontal_graph | def horizontal_graph(*args):
r"""Consume an iterable of integers and produce a horizontal bar graph using
braille characters.
The graph is horizontal in that its dependent axis is the horizontal axis.
Thus each value is represented as a column running bottom to top, and
values are listed left to ri... | python | def horizontal_graph(*args):
r"""Consume an iterable of integers and produce a horizontal bar graph using
braille characters.
The graph is horizontal in that its dependent axis is the horizontal axis.
Thus each value is represented as a column running bottom to top, and
values are listed left to ri... | [
"def",
"horizontal_graph",
"(",
"*",
"args",
")",
":",
"lines",
"=",
"[",
"]",
"# If the arguments were passed as a single iterable, pull it out.",
"# Otherwise, just use them as-is.",
"if",
"len",
"(",
"args",
")",
"==",
"1",
":",
"bars",
"=",
"args",
"[",
"0",
"... | r"""Consume an iterable of integers and produce a horizontal bar graph using
braille characters.
The graph is horizontal in that its dependent axis is the horizontal axis.
Thus each value is represented as a column running bottom to top, and
values are listed left to right.
The graph is anchored t... | [
"r",
"Consume",
"an",
"iterable",
"of",
"integers",
"and",
"produce",
"a",
"horizontal",
"bar",
"graph",
"using",
"braille",
"characters",
"."
] | 744ca8394676579cfb11e5c297c9bd794ab5bd78 | https://github.com/chrisbouchard/braillegraph/blob/744ca8394676579cfb11e5c297c9bd794ab5bd78/braillegraph/braillegraph.py#L207-L283 | train | 56,319 |
kevinconway/confpy | confpy/example.py | generate_example | def generate_example(config, ext='json'):
"""Generate an example file based on the given Configuration object.
Args:
config (confpy.core.configuration.Configuration): The configuration
object on which to base the example.
ext (str): The file extension to render. Choices: JSON and IN... | python | def generate_example(config, ext='json'):
"""Generate an example file based on the given Configuration object.
Args:
config (confpy.core.configuration.Configuration): The configuration
object on which to base the example.
ext (str): The file extension to render. Choices: JSON and IN... | [
"def",
"generate_example",
"(",
"config",
",",
"ext",
"=",
"'json'",
")",
":",
"template_name",
"=",
"'example.{0}'",
".",
"format",
"(",
"ext",
".",
"lower",
"(",
")",
")",
"template",
"=",
"ENV",
".",
"get_template",
"(",
"template_name",
")",
"return",
... | Generate an example file based on the given Configuration object.
Args:
config (confpy.core.configuration.Configuration): The configuration
object on which to base the example.
ext (str): The file extension to render. Choices: JSON and INI.
Returns:
str: The text of the exa... | [
"Generate",
"an",
"example",
"file",
"based",
"on",
"the",
"given",
"Configuration",
"object",
"."
] | 1ee8afcab46ac6915a5ff4184180434ac7b84a60 | https://github.com/kevinconway/confpy/blob/1ee8afcab46ac6915a5ff4184180434ac7b84a60/confpy/example.py#L60-L73 | train | 56,320 |
hollenstein/maspy | maspy/_proteindb_refactoring.py | _removeHeaderTag | def _removeHeaderTag(header, tag):
"""Removes a tag from the beginning of a header string.
:param header: str
:param tag: str
:returns: (str, bool), header without the tag and a bool that indicates
wheter the tag was present.
"""
if header.startswith(tag):
tagPresent = True
... | python | def _removeHeaderTag(header, tag):
"""Removes a tag from the beginning of a header string.
:param header: str
:param tag: str
:returns: (str, bool), header without the tag and a bool that indicates
wheter the tag was present.
"""
if header.startswith(tag):
tagPresent = True
... | [
"def",
"_removeHeaderTag",
"(",
"header",
",",
"tag",
")",
":",
"if",
"header",
".",
"startswith",
"(",
"tag",
")",
":",
"tagPresent",
"=",
"True",
"header",
"=",
"header",
"[",
"len",
"(",
"tag",
")",
":",
"]",
"else",
":",
"tagPresent",
"=",
"False... | Removes a tag from the beginning of a header string.
:param header: str
:param tag: str
:returns: (str, bool), header without the tag and a bool that indicates
wheter the tag was present. | [
"Removes",
"a",
"tag",
"from",
"the",
"beginning",
"of",
"a",
"header",
"string",
"."
] | f15fcfd24df306d8420540460d902aa3073ec133 | https://github.com/hollenstein/maspy/blob/f15fcfd24df306d8420540460d902aa3073ec133/maspy/_proteindb_refactoring.py#L448-L461 | train | 56,321 |
hollenstein/maspy | maspy/_proteindb_refactoring.py | _idFromHeaderInfo | def _idFromHeaderInfo(headerInfo, isDecoy, decoyTag):
"""Generates a protein id from headerInfo. If "isDecoy" is True, the
"decoyTag" is added to beginning of the generated protein id.
:param headerInfo: dict, must contain a key "id"
:param isDecoy: bool, determines if the "decoyTag" is added or not.
... | python | def _idFromHeaderInfo(headerInfo, isDecoy, decoyTag):
"""Generates a protein id from headerInfo. If "isDecoy" is True, the
"decoyTag" is added to beginning of the generated protein id.
:param headerInfo: dict, must contain a key "id"
:param isDecoy: bool, determines if the "decoyTag" is added or not.
... | [
"def",
"_idFromHeaderInfo",
"(",
"headerInfo",
",",
"isDecoy",
",",
"decoyTag",
")",
":",
"proteinId",
"=",
"headerInfo",
"[",
"'id'",
"]",
"if",
"isDecoy",
":",
"proteinId",
"=",
"''",
".",
"join",
"(",
"(",
"decoyTag",
",",
"proteinId",
")",
")",
"retu... | Generates a protein id from headerInfo. If "isDecoy" is True, the
"decoyTag" is added to beginning of the generated protein id.
:param headerInfo: dict, must contain a key "id"
:param isDecoy: bool, determines if the "decoyTag" is added or not.
:param decoyTag: str, a tag that identifies decoy / revers... | [
"Generates",
"a",
"protein",
"id",
"from",
"headerInfo",
".",
"If",
"isDecoy",
"is",
"True",
"the",
"decoyTag",
"is",
"added",
"to",
"beginning",
"of",
"the",
"generated",
"protein",
"id",
"."
] | f15fcfd24df306d8420540460d902aa3073ec133 | https://github.com/hollenstein/maspy/blob/f15fcfd24df306d8420540460d902aa3073ec133/maspy/_proteindb_refactoring.py#L496-L509 | train | 56,322 |
hollenstein/maspy | maspy/_proteindb_refactoring.py | _nameFromHeaderInfo | def _nameFromHeaderInfo(headerInfo, isDecoy, decoyTag):
"""Generates a protein name from headerInfo. If "isDecoy" is True, the
"decoyTag" is added to beginning of the generated protein name.
:param headerInfo: dict, must contain a key "name" or "id"
:param isDecoy: bool, determines if the "decoyTag" is... | python | def _nameFromHeaderInfo(headerInfo, isDecoy, decoyTag):
"""Generates a protein name from headerInfo. If "isDecoy" is True, the
"decoyTag" is added to beginning of the generated protein name.
:param headerInfo: dict, must contain a key "name" or "id"
:param isDecoy: bool, determines if the "decoyTag" is... | [
"def",
"_nameFromHeaderInfo",
"(",
"headerInfo",
",",
"isDecoy",
",",
"decoyTag",
")",
":",
"if",
"'name'",
"in",
"headerInfo",
":",
"proteinName",
"=",
"headerInfo",
"[",
"'name'",
"]",
"else",
":",
"proteinName",
"=",
"headerInfo",
"[",
"'id'",
"]",
"if",
... | Generates a protein name from headerInfo. If "isDecoy" is True, the
"decoyTag" is added to beginning of the generated protein name.
:param headerInfo: dict, must contain a key "name" or "id"
:param isDecoy: bool, determines if the "decoyTag" is added or not.
:param decoyTag: str, a tag that identifies ... | [
"Generates",
"a",
"protein",
"name",
"from",
"headerInfo",
".",
"If",
"isDecoy",
"is",
"True",
"the",
"decoyTag",
"is",
"added",
"to",
"beginning",
"of",
"the",
"generated",
"protein",
"name",
"."
] | f15fcfd24df306d8420540460d902aa3073ec133 | https://github.com/hollenstein/maspy/blob/f15fcfd24df306d8420540460d902aa3073ec133/maspy/_proteindb_refactoring.py#L512-L528 | train | 56,323 |
hollenstein/maspy | maspy/_proteindb_refactoring.py | ProteinDatabase._addPeptide | def _addPeptide(self, sequence, proteinId, digestInfo):
"""Add a peptide to the protein database.
:param sequence: str, amino acid sequence
:param proteinId: str, proteinId
:param digestInfo: dict, contains information about the in silico digest
must contain the keys 'missed... | python | def _addPeptide(self, sequence, proteinId, digestInfo):
"""Add a peptide to the protein database.
:param sequence: str, amino acid sequence
:param proteinId: str, proteinId
:param digestInfo: dict, contains information about the in silico digest
must contain the keys 'missed... | [
"def",
"_addPeptide",
"(",
"self",
",",
"sequence",
",",
"proteinId",
",",
"digestInfo",
")",
":",
"stdSequence",
"=",
"self",
".",
"getStdSequence",
"(",
"sequence",
")",
"if",
"stdSequence",
"not",
"in",
"self",
".",
"peptides",
":",
"self",
".",
"peptid... | Add a peptide to the protein database.
:param sequence: str, amino acid sequence
:param proteinId: str, proteinId
:param digestInfo: dict, contains information about the in silico digest
must contain the keys 'missedCleavage', 'startPos' and 'endPos' | [
"Add",
"a",
"peptide",
"to",
"the",
"protein",
"database",
"."
] | f15fcfd24df306d8420540460d902aa3073ec133 | https://github.com/hollenstein/maspy/blob/f15fcfd24df306d8420540460d902aa3073ec133/maspy/_proteindb_refactoring.py#L113-L137 | train | 56,324 |
Nextdoor/dutch-boy | dutch_boy/nose/plugin.py | LeakDetectorPlugin.configure | def configure(self, options, conf):
"""
Configure plugin.
"""
super(LeakDetectorPlugin, self).configure(options, conf)
if options.leak_detector_level:
self.reporting_level = int(options.leak_detector_level)
self.report_delta = options.leak_detector_report_delt... | python | def configure(self, options, conf):
"""
Configure plugin.
"""
super(LeakDetectorPlugin, self).configure(options, conf)
if options.leak_detector_level:
self.reporting_level = int(options.leak_detector_level)
self.report_delta = options.leak_detector_report_delt... | [
"def",
"configure",
"(",
"self",
",",
"options",
",",
"conf",
")",
":",
"super",
"(",
"LeakDetectorPlugin",
",",
"self",
")",
".",
"configure",
"(",
"options",
",",
"conf",
")",
"if",
"options",
".",
"leak_detector_level",
":",
"self",
".",
"reporting_leve... | Configure plugin. | [
"Configure",
"plugin",
"."
] | 5e95538e99355d458dcb19299a2d2f0c04c42603 | https://github.com/Nextdoor/dutch-boy/blob/5e95538e99355d458dcb19299a2d2f0c04c42603/dutch_boy/nose/plugin.py#L126-L137 | train | 56,325 |
botstory/botstory | botstory/di/injector_service.py | Injector.bind | def bind(self, instance, auto=False):
"""
Bind deps to instance
:param instance:
:param auto: follow update of DI and refresh binds once we will get something new
:return:
"""
methods = [
(m, cls.__dict__[m])
for cls in inspect.getmro(type... | python | def bind(self, instance, auto=False):
"""
Bind deps to instance
:param instance:
:param auto: follow update of DI and refresh binds once we will get something new
:return:
"""
methods = [
(m, cls.__dict__[m])
for cls in inspect.getmro(type... | [
"def",
"bind",
"(",
"self",
",",
"instance",
",",
"auto",
"=",
"False",
")",
":",
"methods",
"=",
"[",
"(",
"m",
",",
"cls",
".",
"__dict__",
"[",
"m",
"]",
")",
"for",
"cls",
"in",
"inspect",
".",
"getmro",
"(",
"type",
"(",
"instance",
")",
"... | Bind deps to instance
:param instance:
:param auto: follow update of DI and refresh binds once we will get something new
:return: | [
"Bind",
"deps",
"to",
"instance"
] | 9c5b2fc7f7a14dbd467d70f60d5ba855ef89dac3 | https://github.com/botstory/botstory/blob/9c5b2fc7f7a14dbd467d70f60d5ba855ef89dac3/botstory/di/injector_service.py#L175-L202 | train | 56,326 |
leodesouza/pyenty | pyenty/types.py | Entity.as_dict | def as_dict(self):
""" create a dict based on class attributes """
odict = OrderedDict()
for name in self._order:
attr_value = getattr(self, name)
if isinstance(attr_value, List):
_list = []
for item in attr_value:
_list... | python | def as_dict(self):
""" create a dict based on class attributes """
odict = OrderedDict()
for name in self._order:
attr_value = getattr(self, name)
if isinstance(attr_value, List):
_list = []
for item in attr_value:
_list... | [
"def",
"as_dict",
"(",
"self",
")",
":",
"odict",
"=",
"OrderedDict",
"(",
")",
"for",
"name",
"in",
"self",
".",
"_order",
":",
"attr_value",
"=",
"getattr",
"(",
"self",
",",
"name",
")",
"if",
"isinstance",
"(",
"attr_value",
",",
"List",
")",
":"... | create a dict based on class attributes | [
"create",
"a",
"dict",
"based",
"on",
"class",
"attributes"
] | 20d2834eada4b971208e816b387479c4fb6ffe61 | https://github.com/leodesouza/pyenty/blob/20d2834eada4b971208e816b387479c4fb6ffe61/pyenty/types.py#L145-L159 | train | 56,327 |
leodesouza/pyenty | pyenty/types.py | Entity.map | def map(cls, dict_entity):
""" staticmethod which will be used in recursive mode in order to map dict to instance """
for key, value in dict_entity.items():
if hasattr(cls, key):
if isinstance(value, list):
_list = getattr(cls, key)
if ... | python | def map(cls, dict_entity):
""" staticmethod which will be used in recursive mode in order to map dict to instance """
for key, value in dict_entity.items():
if hasattr(cls, key):
if isinstance(value, list):
_list = getattr(cls, key)
if ... | [
"def",
"map",
"(",
"cls",
",",
"dict_entity",
")",
":",
"for",
"key",
",",
"value",
"in",
"dict_entity",
".",
"items",
"(",
")",
":",
"if",
"hasattr",
"(",
"cls",
",",
"key",
")",
":",
"if",
"isinstance",
"(",
"value",
",",
"list",
")",
":",
"_li... | staticmethod which will be used in recursive mode in order to map dict to instance | [
"staticmethod",
"which",
"will",
"be",
"used",
"in",
"recursive",
"mode",
"in",
"order",
"to",
"map",
"dict",
"to",
"instance"
] | 20d2834eada4b971208e816b387479c4fb6ffe61 | https://github.com/leodesouza/pyenty/blob/20d2834eada4b971208e816b387479c4fb6ffe61/pyenty/types.py#L162-L179 | train | 56,328 |
hollenstein/maspy | maspy_resources/pparse.py | generateParams | def generateParams(rawfilepath, outputpath, isolationWindow, coElute):
"""Generates a string containing the parameters for a pParse parameter file
but doesn't write any file yet.
:param rawfilepath: location of the thermo ".raw" file
:param outputpath: path to the output directory of pParse
:param ... | python | def generateParams(rawfilepath, outputpath, isolationWindow, coElute):
"""Generates a string containing the parameters for a pParse parameter file
but doesn't write any file yet.
:param rawfilepath: location of the thermo ".raw" file
:param outputpath: path to the output directory of pParse
:param ... | [
"def",
"generateParams",
"(",
"rawfilepath",
",",
"outputpath",
",",
"isolationWindow",
",",
"coElute",
")",
":",
"output",
"=",
"str",
"(",
")",
"#Basic options",
"output",
"=",
"'\\n'",
".",
"join",
"(",
"[",
"output",
",",
"' = '",
".",
"join",
"(",
"... | Generates a string containing the parameters for a pParse parameter file
but doesn't write any file yet.
:param rawfilepath: location of the thermo ".raw" file
:param outputpath: path to the output directory of pParse
:param isolationWindow: MSn isolation window that was used for the
aquisition... | [
"Generates",
"a",
"string",
"containing",
"the",
"parameters",
"for",
"a",
"pParse",
"parameter",
"file",
"but",
"doesn",
"t",
"write",
"any",
"file",
"yet",
"."
] | f15fcfd24df306d8420540460d902aa3073ec133 | https://github.com/hollenstein/maspy/blob/f15fcfd24df306d8420540460d902aa3073ec133/maspy_resources/pparse.py#L41-L117 | train | 56,329 |
hollenstein/maspy | maspy_resources/pparse.py | writeParams | def writeParams(rawfilepath, outputpath, isolationWindow, coElute=0):
"""Generate and write a pParse parameter file.
:param rawfilepath: location of the thermo ".raw" file
:param outputpath: path to the output directory of pParse
:param isolationWindow: MSn isolation window that was used for the
... | python | def writeParams(rawfilepath, outputpath, isolationWindow, coElute=0):
"""Generate and write a pParse parameter file.
:param rawfilepath: location of the thermo ".raw" file
:param outputpath: path to the output directory of pParse
:param isolationWindow: MSn isolation window that was used for the
... | [
"def",
"writeParams",
"(",
"rawfilepath",
",",
"outputpath",
",",
"isolationWindow",
",",
"coElute",
"=",
"0",
")",
":",
"paramText",
"=",
"generateParams",
"(",
"rawfilepath",
",",
"outputpath",
",",
"isolationWindow",
",",
"coElute",
")",
"filename",
",",
"f... | Generate and write a pParse parameter file.
:param rawfilepath: location of the thermo ".raw" file
:param outputpath: path to the output directory of pParse
:param isolationWindow: MSn isolation window that was used for the
aquisition of the specified thermo raw file
:param coElute:
:retur... | [
"Generate",
"and",
"write",
"a",
"pParse",
"parameter",
"file",
"."
] | f15fcfd24df306d8420540460d902aa3073ec133 | https://github.com/hollenstein/maspy/blob/f15fcfd24df306d8420540460d902aa3073ec133/maspy_resources/pparse.py#L120-L137 | train | 56,330 |
hollenstein/maspy | maspy_resources/pparse.py | execute | def execute(paramPath, executable='pParse.exe'):
"""Execute pParse with the specified parameter file.
:param paramPath: location of the pParse parameter file
:param executable: must specify the complete file path of the pParse.exe
if its location is not in the ``PATH`` environment variable.
:r... | python | def execute(paramPath, executable='pParse.exe'):
"""Execute pParse with the specified parameter file.
:param paramPath: location of the pParse parameter file
:param executable: must specify the complete file path of the pParse.exe
if its location is not in the ``PATH`` environment variable.
:r... | [
"def",
"execute",
"(",
"paramPath",
",",
"executable",
"=",
"'pParse.exe'",
")",
":",
"procArgs",
"=",
"[",
"executable",
",",
"paramPath",
"]",
"## run it ##",
"proc",
"=",
"subprocess",
".",
"Popen",
"(",
"procArgs",
",",
"stderr",
"=",
"subprocess",
".",
... | Execute pParse with the specified parameter file.
:param paramPath: location of the pParse parameter file
:param executable: must specify the complete file path of the pParse.exe
if its location is not in the ``PATH`` environment variable.
:returns: :func:`subprocess.Popen` return code, 0 if pPars... | [
"Execute",
"pParse",
"with",
"the",
"specified",
"parameter",
"file",
"."
] | f15fcfd24df306d8420540460d902aa3073ec133 | https://github.com/hollenstein/maspy/blob/f15fcfd24df306d8420540460d902aa3073ec133/maspy_resources/pparse.py#L140-L164 | train | 56,331 |
hollenstein/maspy | maspy_resources/pparse.py | cleanUpPparse | def cleanUpPparse(outputpath, rawfilename, mgf=False):
"""Delete temporary files generated by pparse, including the filetypes
".csv", ".ms1", ".ms2", ".xtract", the files "pParsePlusLog.txt" and
"pParse.para" and optionally also the ".mgf" file generated by pParse.
.. warning:
When the paramet... | python | def cleanUpPparse(outputpath, rawfilename, mgf=False):
"""Delete temporary files generated by pparse, including the filetypes
".csv", ".ms1", ".ms2", ".xtract", the files "pParsePlusLog.txt" and
"pParse.para" and optionally also the ".mgf" file generated by pParse.
.. warning:
When the paramet... | [
"def",
"cleanUpPparse",
"(",
"outputpath",
",",
"rawfilename",
",",
"mgf",
"=",
"False",
")",
":",
"extensions",
"=",
"[",
"'csv'",
",",
"'ms1'",
",",
"'ms2'",
",",
"'xtract'",
"]",
"filename",
",",
"fileext",
"=",
"os",
".",
"path",
".",
"splitext",
"... | Delete temporary files generated by pparse, including the filetypes
".csv", ".ms1", ".ms2", ".xtract", the files "pParsePlusLog.txt" and
"pParse.para" and optionally also the ".mgf" file generated by pParse.
.. warning:
When the parameter "mgf" is set to "True" all files ending with ".mgf"
... | [
"Delete",
"temporary",
"files",
"generated",
"by",
"pparse",
"including",
"the",
"filetypes",
".",
"csv",
".",
"ms1",
".",
"ms2",
".",
"xtract",
"the",
"files",
"pParsePlusLog",
".",
"txt",
"and",
"pParse",
".",
"para",
"and",
"optionally",
"also",
"the",
... | f15fcfd24df306d8420540460d902aa3073ec133 | https://github.com/hollenstein/maspy/blob/f15fcfd24df306d8420540460d902aa3073ec133/maspy_resources/pparse.py#L167-L205 | train | 56,332 |
dturanski/springcloudstream | springcloudstream/tcp/tcp.py | StreamHandler.create_handler | def create_handler(cls, message_handler, buffer_size, logger):
"""
Class variables used here since the framework creates an instance for each connection
:param message_handler: the MessageHandler used to process each message.
:param buffer_size: the TCP buffer size.
:param logge... | python | def create_handler(cls, message_handler, buffer_size, logger):
"""
Class variables used here since the framework creates an instance for each connection
:param message_handler: the MessageHandler used to process each message.
:param buffer_size: the TCP buffer size.
:param logge... | [
"def",
"create_handler",
"(",
"cls",
",",
"message_handler",
",",
"buffer_size",
",",
"logger",
")",
":",
"cls",
".",
"BUFFER_SIZE",
"=",
"buffer_size",
"cls",
".",
"message_handler",
"=",
"message_handler",
"cls",
".",
"logger",
"=",
"logger",
"cls",
".",
"... | Class variables used here since the framework creates an instance for each connection
:param message_handler: the MessageHandler used to process each message.
:param buffer_size: the TCP buffer size.
:param logger: the global logger.
:return: this class. | [
"Class",
"variables",
"used",
"here",
"since",
"the",
"framework",
"creates",
"an",
"instance",
"for",
"each",
"connection"
] | 208b542f9eba82e97882d52703af8e965a62a980 | https://github.com/dturanski/springcloudstream/blob/208b542f9eba82e97882d52703af8e965a62a980/springcloudstream/tcp/tcp.py#L97-L112 | train | 56,333 |
dturanski/springcloudstream | springcloudstream/tcp/tcp.py | StreamHandler.handle | def handle(self):
"""
The required handle method.
"""
logger = StreamHandler.logger
logger.debug("handling requests with message handler %s " % StreamHandler.message_handler.__class__.__name__)
message_handler = StreamHandler.message_handler
try:
whi... | python | def handle(self):
"""
The required handle method.
"""
logger = StreamHandler.logger
logger.debug("handling requests with message handler %s " % StreamHandler.message_handler.__class__.__name__)
message_handler = StreamHandler.message_handler
try:
whi... | [
"def",
"handle",
"(",
"self",
")",
":",
"logger",
"=",
"StreamHandler",
".",
"logger",
"logger",
".",
"debug",
"(",
"\"handling requests with message handler %s \"",
"%",
"StreamHandler",
".",
"message_handler",
".",
"__class__",
".",
"__name__",
")",
"message_handl... | The required handle method. | [
"The",
"required",
"handle",
"method",
"."
] | 208b542f9eba82e97882d52703af8e965a62a980 | https://github.com/dturanski/springcloudstream/blob/208b542f9eba82e97882d52703af8e965a62a980/springcloudstream/tcp/tcp.py#L114-L134 | train | 56,334 |
sporsh/carnifex | carnifex/ssh/client.py | SSHTransport.receiveError | def receiveError(self, reasonCode, description):
"""
Called when we receive a disconnect error message from the other
side.
"""
error = disconnectErrors.get(reasonCode, DisconnectError)
self.connectionClosed(error(reasonCode, description))
SSHClientTransport.recei... | python | def receiveError(self, reasonCode, description):
"""
Called when we receive a disconnect error message from the other
side.
"""
error = disconnectErrors.get(reasonCode, DisconnectError)
self.connectionClosed(error(reasonCode, description))
SSHClientTransport.recei... | [
"def",
"receiveError",
"(",
"self",
",",
"reasonCode",
",",
"description",
")",
":",
"error",
"=",
"disconnectErrors",
".",
"get",
"(",
"reasonCode",
",",
"DisconnectError",
")",
"self",
".",
"connectionClosed",
"(",
"error",
"(",
"reasonCode",
",",
"descripti... | Called when we receive a disconnect error message from the other
side. | [
"Called",
"when",
"we",
"receive",
"a",
"disconnect",
"error",
"message",
"from",
"the",
"other",
"side",
"."
] | 82dd3bd2bc134dfb69a78f43171e227f2127060b | https://github.com/sporsh/carnifex/blob/82dd3bd2bc134dfb69a78f43171e227f2127060b/carnifex/ssh/client.py#L44-L51 | train | 56,335 |
invinst/ResponseBot | responsebot/handlers/event.py | BaseEventHandler.handle | def handle(self, event):
"""
Entry point to handle user events.
:param event: Received event. See a full list `here <https://dev.twitter.com/streaming/overview/messages-types#Events_event>`_.
"""
callback = getattr(self, 'on_{event}'.format(event=event.event), None)
call... | python | def handle(self, event):
"""
Entry point to handle user events.
:param event: Received event. See a full list `here <https://dev.twitter.com/streaming/overview/messages-types#Events_event>`_.
"""
callback = getattr(self, 'on_{event}'.format(event=event.event), None)
call... | [
"def",
"handle",
"(",
"self",
",",
"event",
")",
":",
"callback",
"=",
"getattr",
"(",
"self",
",",
"'on_{event}'",
".",
"format",
"(",
"event",
"=",
"event",
".",
"event",
")",
",",
"None",
")",
"callback",
"(",
"event",
")"
] | Entry point to handle user events.
:param event: Received event. See a full list `here <https://dev.twitter.com/streaming/overview/messages-types#Events_event>`_. | [
"Entry",
"point",
"to",
"handle",
"user",
"events",
"."
] | a6b1a431a343007f7ae55a193e432a61af22253f | https://github.com/invinst/ResponseBot/blob/a6b1a431a343007f7ae55a193e432a61af22253f/responsebot/handlers/event.py#L13-L20 | train | 56,336 |
standage/tag | tag/transcript.py | _emplace_pmrna | def _emplace_pmrna(mrnas, parent, strict=False):
"""Retrieve the primary mRNA and discard all others."""
mrnas.sort(key=lambda m: (m.cdslen, m.get_attribute('ID')))
pmrna = mrnas.pop()
if strict:
parent.children = [pmrna]
else:
parent.children = [c for c in parent.children if c not i... | python | def _emplace_pmrna(mrnas, parent, strict=False):
"""Retrieve the primary mRNA and discard all others."""
mrnas.sort(key=lambda m: (m.cdslen, m.get_attribute('ID')))
pmrna = mrnas.pop()
if strict:
parent.children = [pmrna]
else:
parent.children = [c for c in parent.children if c not i... | [
"def",
"_emplace_pmrna",
"(",
"mrnas",
",",
"parent",
",",
"strict",
"=",
"False",
")",
":",
"mrnas",
".",
"sort",
"(",
"key",
"=",
"lambda",
"m",
":",
"(",
"m",
".",
"cdslen",
",",
"m",
".",
"get_attribute",
"(",
"'ID'",
")",
")",
")",
"pmrna",
... | Retrieve the primary mRNA and discard all others. | [
"Retrieve",
"the",
"primary",
"mRNA",
"and",
"discard",
"all",
"others",
"."
] | 94686adf57115cea1c5235e99299e691f80ba10b | https://github.com/standage/tag/blob/94686adf57115cea1c5235e99299e691f80ba10b/tag/transcript.py#L29-L36 | train | 56,337 |
standage/tag | tag/transcript.py | _emplace_transcript | def _emplace_transcript(transcripts, parent):
"""Retrieve the primary transcript and discard all others."""
transcripts.sort(key=lambda t: (len(t), t.get_attribute('ID')))
pt = transcripts.pop()
parent.children = [pt] | python | def _emplace_transcript(transcripts, parent):
"""Retrieve the primary transcript and discard all others."""
transcripts.sort(key=lambda t: (len(t), t.get_attribute('ID')))
pt = transcripts.pop()
parent.children = [pt] | [
"def",
"_emplace_transcript",
"(",
"transcripts",
",",
"parent",
")",
":",
"transcripts",
".",
"sort",
"(",
"key",
"=",
"lambda",
"t",
":",
"(",
"len",
"(",
"t",
")",
",",
"t",
".",
"get_attribute",
"(",
"'ID'",
")",
")",
")",
"pt",
"=",
"transcripts... | Retrieve the primary transcript and discard all others. | [
"Retrieve",
"the",
"primary",
"transcript",
"and",
"discard",
"all",
"others",
"."
] | 94686adf57115cea1c5235e99299e691f80ba10b | https://github.com/standage/tag/blob/94686adf57115cea1c5235e99299e691f80ba10b/tag/transcript.py#L39-L43 | train | 56,338 |
standage/tag | tag/transcript.py | primary_mrna | def primary_mrna(entrystream, parenttype='gene'):
"""
Select a single mRNA as a representative for each protein-coding gene.
The primary mRNA is the one with the longest translation product. In cases
where multiple isoforms have the same translated length, the feature ID is
used for sorting.
T... | python | def primary_mrna(entrystream, parenttype='gene'):
"""
Select a single mRNA as a representative for each protein-coding gene.
The primary mRNA is the one with the longest translation product. In cases
where multiple isoforms have the same translated length, the feature ID is
used for sorting.
T... | [
"def",
"primary_mrna",
"(",
"entrystream",
",",
"parenttype",
"=",
"'gene'",
")",
":",
"for",
"entry",
"in",
"entrystream",
":",
"if",
"not",
"isinstance",
"(",
"entry",
",",
"tag",
".",
"Feature",
")",
":",
"yield",
"entry",
"continue",
"for",
"parent",
... | Select a single mRNA as a representative for each protein-coding gene.
The primary mRNA is the one with the longest translation product. In cases
where multiple isoforms have the same translated length, the feature ID is
used for sorting.
This function **does not** return only mRNA features, it return... | [
"Select",
"a",
"single",
"mRNA",
"as",
"a",
"representative",
"for",
"each",
"protein",
"-",
"coding",
"gene",
"."
] | 94686adf57115cea1c5235e99299e691f80ba10b | https://github.com/standage/tag/blob/94686adf57115cea1c5235e99299e691f80ba10b/tag/transcript.py#L46-L74 | train | 56,339 |
standage/tag | tag/transcript.py | _get_primary_type | def _get_primary_type(ttypes, parent, logstream=stderr):
"""Check for multiple transcript types and, if possible, select one."""
if len(ttypes) > 1:
if logstream: # pragma: no branch
message = '[tag::transcript::primary_transcript]'
message += ' WARNING: feature {:s}'.format(par... | python | def _get_primary_type(ttypes, parent, logstream=stderr):
"""Check for multiple transcript types and, if possible, select one."""
if len(ttypes) > 1:
if logstream: # pragma: no branch
message = '[tag::transcript::primary_transcript]'
message += ' WARNING: feature {:s}'.format(par... | [
"def",
"_get_primary_type",
"(",
"ttypes",
",",
"parent",
",",
"logstream",
"=",
"stderr",
")",
":",
"if",
"len",
"(",
"ttypes",
")",
">",
"1",
":",
"if",
"logstream",
":",
"# pragma: no branch",
"message",
"=",
"'[tag::transcript::primary_transcript]'",
"messag... | Check for multiple transcript types and, if possible, select one. | [
"Check",
"for",
"multiple",
"transcript",
"types",
"and",
"if",
"possible",
"select",
"one",
"."
] | 94686adf57115cea1c5235e99299e691f80ba10b | https://github.com/standage/tag/blob/94686adf57115cea1c5235e99299e691f80ba10b/tag/transcript.py#L77-L93 | train | 56,340 |
standage/tag | tag/transcript.py | primary_transcript | def primary_transcript(entrystream, parenttype='gene', logstream=stderr):
"""
Select a single transcript as a representative for each gene.
This function is a generalization of the `primary_mrna` function that
attempts, under certain conditions, to select a single transcript as a
representative for... | python | def primary_transcript(entrystream, parenttype='gene', logstream=stderr):
"""
Select a single transcript as a representative for each gene.
This function is a generalization of the `primary_mrna` function that
attempts, under certain conditions, to select a single transcript as a
representative for... | [
"def",
"primary_transcript",
"(",
"entrystream",
",",
"parenttype",
"=",
"'gene'",
",",
"logstream",
"=",
"stderr",
")",
":",
"for",
"entry",
"in",
"entrystream",
":",
"if",
"not",
"isinstance",
"(",
"entry",
",",
"tag",
".",
"Feature",
")",
":",
"yield",
... | Select a single transcript as a representative for each gene.
This function is a generalization of the `primary_mrna` function that
attempts, under certain conditions, to select a single transcript as a
representative for each gene. If a gene encodes multiple transcript types,
one of those types must b... | [
"Select",
"a",
"single",
"transcript",
"as",
"a",
"representative",
"for",
"each",
"gene",
"."
] | 94686adf57115cea1c5235e99299e691f80ba10b | https://github.com/standage/tag/blob/94686adf57115cea1c5235e99299e691f80ba10b/tag/transcript.py#L96-L154 | train | 56,341 |
pauleveritt/kaybee | kaybee/plugins/resources/base_resource.py | parse_parent | def parse_parent(docname):
""" Given a docname path, pick apart and return name of parent """
lineage = docname.split('/')
lineage_count = len(lineage)
if docname == 'index':
# This is the top of the Sphinx project
parent = None
elif lineage_count == 1:
# This is a non-inde... | python | def parse_parent(docname):
""" Given a docname path, pick apart and return name of parent """
lineage = docname.split('/')
lineage_count = len(lineage)
if docname == 'index':
# This is the top of the Sphinx project
parent = None
elif lineage_count == 1:
# This is a non-inde... | [
"def",
"parse_parent",
"(",
"docname",
")",
":",
"lineage",
"=",
"docname",
".",
"split",
"(",
"'/'",
")",
"lineage_count",
"=",
"len",
"(",
"lineage",
")",
"if",
"docname",
"==",
"'index'",
":",
"# This is the top of the Sphinx project",
"parent",
"=",
"None"... | Given a docname path, pick apart and return name of parent | [
"Given",
"a",
"docname",
"path",
"pick",
"apart",
"and",
"return",
"name",
"of",
"parent"
] | a00a718aaaa23b2d12db30dfacb6b2b6ec84459c | https://github.com/pauleveritt/kaybee/blob/a00a718aaaa23b2d12db30dfacb6b2b6ec84459c/kaybee/plugins/resources/base_resource.py#L8-L33 | train | 56,342 |
pauleveritt/kaybee | kaybee/plugins/resources/base_resource.py | BaseResource.parents | def parents(self, resources):
""" Split the path in name and get parents """
if self.docname == 'index':
# The root has no parents
return []
parents = []
parent = resources.get(self.parent)
while parent is not None:
parents.append(parent)
... | python | def parents(self, resources):
""" Split the path in name and get parents """
if self.docname == 'index':
# The root has no parents
return []
parents = []
parent = resources.get(self.parent)
while parent is not None:
parents.append(parent)
... | [
"def",
"parents",
"(",
"self",
",",
"resources",
")",
":",
"if",
"self",
".",
"docname",
"==",
"'index'",
":",
"# The root has no parents",
"return",
"[",
"]",
"parents",
"=",
"[",
"]",
"parent",
"=",
"resources",
".",
"get",
"(",
"self",
".",
"parent",
... | Split the path in name and get parents | [
"Split",
"the",
"path",
"in",
"name",
"and",
"get",
"parents"
] | a00a718aaaa23b2d12db30dfacb6b2b6ec84459c | https://github.com/pauleveritt/kaybee/blob/a00a718aaaa23b2d12db30dfacb6b2b6ec84459c/kaybee/plugins/resources/base_resource.py#L63-L74 | train | 56,343 |
pauleveritt/kaybee | kaybee/plugins/resources/base_resource.py | BaseResource.acquire | def acquire(self, resources, prop_name):
""" Starting with self, walk until you find prop or None """
# Instance
custom_prop = getattr(self.props, prop_name, None)
if custom_prop:
return custom_prop
# Parents...can't use acquire as have to keep going on acquireds
... | python | def acquire(self, resources, prop_name):
""" Starting with self, walk until you find prop or None """
# Instance
custom_prop = getattr(self.props, prop_name, None)
if custom_prop:
return custom_prop
# Parents...can't use acquire as have to keep going on acquireds
... | [
"def",
"acquire",
"(",
"self",
",",
"resources",
",",
"prop_name",
")",
":",
"# Instance",
"custom_prop",
"=",
"getattr",
"(",
"self",
".",
"props",
",",
"prop_name",
",",
"None",
")",
"if",
"custom_prop",
":",
"return",
"custom_prop",
"# Parents...can't use a... | Starting with self, walk until you find prop or None | [
"Starting",
"with",
"self",
"walk",
"until",
"you",
"find",
"prop",
"or",
"None"
] | a00a718aaaa23b2d12db30dfacb6b2b6ec84459c | https://github.com/pauleveritt/kaybee/blob/a00a718aaaa23b2d12db30dfacb6b2b6ec84459c/kaybee/plugins/resources/base_resource.py#L76-L102 | train | 56,344 |
pauleveritt/kaybee | kaybee/plugins/resources/base_resource.py | BaseResource.find_prop_item | def find_prop_item(self, prop_name, prop_key, prop_value):
""" Look for a list prop with an item where key == value """
# Image props are a sequence of dicts. We often need one of them.
# Where one of the items has a dict key matching a value, and if
# nothing matches, return None
... | python | def find_prop_item(self, prop_name, prop_key, prop_value):
""" Look for a list prop with an item where key == value """
# Image props are a sequence of dicts. We often need one of them.
# Where one of the items has a dict key matching a value, and if
# nothing matches, return None
... | [
"def",
"find_prop_item",
"(",
"self",
",",
"prop_name",
",",
"prop_key",
",",
"prop_value",
")",
":",
"# Image props are a sequence of dicts. We often need one of them.",
"# Where one of the items has a dict key matching a value, and if",
"# nothing matches, return None",
"prop",
"="... | Look for a list prop with an item where key == value | [
"Look",
"for",
"a",
"list",
"prop",
"with",
"an",
"item",
"where",
"key",
"==",
"value"
] | a00a718aaaa23b2d12db30dfacb6b2b6ec84459c | https://github.com/pauleveritt/kaybee/blob/a00a718aaaa23b2d12db30dfacb6b2b6ec84459c/kaybee/plugins/resources/base_resource.py#L120-L134 | train | 56,345 |
Prev/shaman | shamanld/shaman.py | Shaman.detect | def detect(self, code) :
""" Detect language with code
"""
keywords = KeywordFetcher.fetch( code )
probabilities = {}
for keyword in keywords :
if keyword not in self.trained_set['keywords'] :
continue
data = self.trained_set['keywords'][keyword]
p_avg = sum(data.values()) / len(data) # Aver... | python | def detect(self, code) :
""" Detect language with code
"""
keywords = KeywordFetcher.fetch( code )
probabilities = {}
for keyword in keywords :
if keyword not in self.trained_set['keywords'] :
continue
data = self.trained_set['keywords'][keyword]
p_avg = sum(data.values()) / len(data) # Aver... | [
"def",
"detect",
"(",
"self",
",",
"code",
")",
":",
"keywords",
"=",
"KeywordFetcher",
".",
"fetch",
"(",
"code",
")",
"probabilities",
"=",
"{",
"}",
"for",
"keyword",
"in",
"keywords",
":",
"if",
"keyword",
"not",
"in",
"self",
".",
"trained_set",
"... | Detect language with code | [
"Detect",
"language",
"with",
"code"
] | 82891c17c6302f7f9881a215789856d460a85f9c | https://github.com/Prev/shaman/blob/82891c17c6302f7f9881a215789856d460a85f9c/shamanld/shaman.py#L43-L84 | train | 56,346 |
Prev/shaman | shamanld/shaman.py | KeywordFetcher.fetch | def fetch(code) :
""" Fetch keywords by Code
"""
ret = {}
code = KeywordFetcher._remove_strings(code)
result = KeywordFetcher.prog.findall(code)
for keyword in result :
if len(keyword) <= 1: continue # Ignore single-length word
if keyword.isdigit(): continue # Ignore number
if keyword[0] == '-' ... | python | def fetch(code) :
""" Fetch keywords by Code
"""
ret = {}
code = KeywordFetcher._remove_strings(code)
result = KeywordFetcher.prog.findall(code)
for keyword in result :
if len(keyword) <= 1: continue # Ignore single-length word
if keyword.isdigit(): continue # Ignore number
if keyword[0] == '-' ... | [
"def",
"fetch",
"(",
"code",
")",
":",
"ret",
"=",
"{",
"}",
"code",
"=",
"KeywordFetcher",
".",
"_remove_strings",
"(",
"code",
")",
"result",
"=",
"KeywordFetcher",
".",
"prog",
".",
"findall",
"(",
"code",
")",
"for",
"keyword",
"in",
"result",
":",... | Fetch keywords by Code | [
"Fetch",
"keywords",
"by",
"Code"
] | 82891c17c6302f7f9881a215789856d460a85f9c | https://github.com/Prev/shaman/blob/82891c17c6302f7f9881a215789856d460a85f9c/shamanld/shaman.py#L92-L111 | train | 56,347 |
Prev/shaman | shamanld/shaman.py | KeywordFetcher._remove_strings | def _remove_strings(code) :
""" Remove strings in code
"""
removed_string = ""
is_string_now = None
for i in range(0, len(code)-1) :
append_this_turn = False
if code[i] == "'" and (i == 0 or code[i-1] != '\\') :
if is_string_now == "'" :
is_string_now = None
elif is_string_now == None ... | python | def _remove_strings(code) :
""" Remove strings in code
"""
removed_string = ""
is_string_now = None
for i in range(0, len(code)-1) :
append_this_turn = False
if code[i] == "'" and (i == 0 or code[i-1] != '\\') :
if is_string_now == "'" :
is_string_now = None
elif is_string_now == None ... | [
"def",
"_remove_strings",
"(",
"code",
")",
":",
"removed_string",
"=",
"\"\"",
"is_string_now",
"=",
"None",
"for",
"i",
"in",
"range",
"(",
"0",
",",
"len",
"(",
"code",
")",
"-",
"1",
")",
":",
"append_this_turn",
"=",
"False",
"if",
"code",
"[",
... | Remove strings in code | [
"Remove",
"strings",
"in",
"code"
] | 82891c17c6302f7f9881a215789856d460a85f9c | https://github.com/Prev/shaman/blob/82891c17c6302f7f9881a215789856d460a85f9c/shamanld/shaman.py#L115-L144 | train | 56,348 |
Prev/shaman | shamanld/shaman.py | PatternMatcher.getratio | def getratio(self, code) :
""" Get ratio of code and pattern matched
"""
if len(code) == 0 : return 0
code_replaced = self.prog.sub('', code)
return (len(code) - len(code_replaced)) / len(code) | python | def getratio(self, code) :
""" Get ratio of code and pattern matched
"""
if len(code) == 0 : return 0
code_replaced = self.prog.sub('', code)
return (len(code) - len(code_replaced)) / len(code) | [
"def",
"getratio",
"(",
"self",
",",
"code",
")",
":",
"if",
"len",
"(",
"code",
")",
"==",
"0",
":",
"return",
"0",
"code_replaced",
"=",
"self",
".",
"prog",
".",
"sub",
"(",
"''",
",",
"code",
")",
"return",
"(",
"len",
"(",
"code",
")",
"-"... | Get ratio of code and pattern matched | [
"Get",
"ratio",
"of",
"code",
"and",
"pattern",
"matched"
] | 82891c17c6302f7f9881a215789856d460a85f9c | https://github.com/Prev/shaman/blob/82891c17c6302f7f9881a215789856d460a85f9c/shamanld/shaman.py#L167-L173 | train | 56,349 |
bitesofcode/projex | projex/xmlutil.py | XmlObject.loadXmlProperty | def loadXmlProperty(self, xprop):
"""
Loads an XML property that is a child of the root data being loaded.
:param xprop | <xml.etree.ElementTree.Element>
"""
if xprop.tag == 'property':
value = self.dataInterface().fromXml(xprop[0])
self._xmlData[xpr... | python | def loadXmlProperty(self, xprop):
"""
Loads an XML property that is a child of the root data being loaded.
:param xprop | <xml.etree.ElementTree.Element>
"""
if xprop.tag == 'property':
value = self.dataInterface().fromXml(xprop[0])
self._xmlData[xpr... | [
"def",
"loadXmlProperty",
"(",
"self",
",",
"xprop",
")",
":",
"if",
"xprop",
".",
"tag",
"==",
"'property'",
":",
"value",
"=",
"self",
".",
"dataInterface",
"(",
")",
".",
"fromXml",
"(",
"xprop",
"[",
"0",
"]",
")",
"self",
".",
"_xmlData",
"[",
... | Loads an XML property that is a child of the root data being loaded.
:param xprop | <xml.etree.ElementTree.Element> | [
"Loads",
"an",
"XML",
"property",
"that",
"is",
"a",
"child",
"of",
"the",
"root",
"data",
"being",
"loaded",
"."
] | d31743ec456a41428709968ab11a2cf6c6c76247 | https://github.com/bitesofcode/projex/blob/d31743ec456a41428709968ab11a2cf6c6c76247/projex/xmlutil.py#L38-L46 | train | 56,350 |
bitesofcode/projex | projex/xmlutil.py | XmlObject.toXml | def toXml(self, xparent=None):
"""
Converts this object to XML.
:param xparent | <xml.etree.ElementTree.Element> || None
:return <xml.etree.ElementTree.Element>
"""
if xparent is None:
xml = ElementTree.Element('object')
else:
xm... | python | def toXml(self, xparent=None):
"""
Converts this object to XML.
:param xparent | <xml.etree.ElementTree.Element> || None
:return <xml.etree.ElementTree.Element>
"""
if xparent is None:
xml = ElementTree.Element('object')
else:
xm... | [
"def",
"toXml",
"(",
"self",
",",
"xparent",
"=",
"None",
")",
":",
"if",
"xparent",
"is",
"None",
":",
"xml",
"=",
"ElementTree",
".",
"Element",
"(",
"'object'",
")",
"else",
":",
"xml",
"=",
"ElementTree",
".",
"SubElement",
"(",
"xparent",
",",
"... | Converts this object to XML.
:param xparent | <xml.etree.ElementTree.Element> || None
:return <xml.etree.ElementTree.Element> | [
"Converts",
"this",
"object",
"to",
"XML",
"."
] | d31743ec456a41428709968ab11a2cf6c6c76247 | https://github.com/bitesofcode/projex/blob/d31743ec456a41428709968ab11a2cf6c6c76247/projex/xmlutil.py#L57-L75 | train | 56,351 |
bitesofcode/projex | projex/xmlutil.py | XmlObject.fromXml | def fromXml(cls, xml):
"""
Restores an object from XML.
:param xml | <xml.etree.ElementTree.Element>
:return subclass of <XmlObject>
"""
clsname = xml.get('class')
if clsname:
subcls = XmlObject.byName(clsname)
if subcls is None:... | python | def fromXml(cls, xml):
"""
Restores an object from XML.
:param xml | <xml.etree.ElementTree.Element>
:return subclass of <XmlObject>
"""
clsname = xml.get('class')
if clsname:
subcls = XmlObject.byName(clsname)
if subcls is None:... | [
"def",
"fromXml",
"(",
"cls",
",",
"xml",
")",
":",
"clsname",
"=",
"xml",
".",
"get",
"(",
"'class'",
")",
"if",
"clsname",
":",
"subcls",
"=",
"XmlObject",
".",
"byName",
"(",
"clsname",
")",
"if",
"subcls",
"is",
"None",
":",
"inst",
"=",
"Missi... | Restores an object from XML.
:param xml | <xml.etree.ElementTree.Element>
:return subclass of <XmlObject> | [
"Restores",
"an",
"object",
"from",
"XML",
"."
] | d31743ec456a41428709968ab11a2cf6c6c76247 | https://github.com/bitesofcode/projex/blob/d31743ec456a41428709968ab11a2cf6c6c76247/projex/xmlutil.py#L86-L105 | train | 56,352 |
e7dal/bubble3 | behave4cmd0/textutil.py | template_substitute | def template_substitute(text, **kwargs):
"""
Replace placeholders in text by using the data mapping.
Other placeholders that is not represented by data is left untouched.
:param text: Text to search and replace placeholders.
:param data: Data mapping/dict for placeholder key and values.
:re... | python | def template_substitute(text, **kwargs):
"""
Replace placeholders in text by using the data mapping.
Other placeholders that is not represented by data is left untouched.
:param text: Text to search and replace placeholders.
:param data: Data mapping/dict for placeholder key and values.
:re... | [
"def",
"template_substitute",
"(",
"text",
",",
"*",
"*",
"kwargs",
")",
":",
"for",
"name",
",",
"value",
"in",
"kwargs",
".",
"items",
"(",
")",
":",
"placeholder_pattern",
"=",
"\"{%s}\"",
"%",
"name",
"if",
"placeholder_pattern",
"in",
"text",
":",
"... | Replace placeholders in text by using the data mapping.
Other placeholders that is not represented by data is left untouched.
:param text: Text to search and replace placeholders.
:param data: Data mapping/dict for placeholder key and values.
:return: Potentially modified text with replaced placeho... | [
"Replace",
"placeholders",
"in",
"text",
"by",
"using",
"the",
"data",
"mapping",
".",
"Other",
"placeholders",
"that",
"is",
"not",
"represented",
"by",
"data",
"is",
"left",
"untouched",
"."
] | 59c735281a95b44f6263a25f4d6ce24fca520082 | https://github.com/e7dal/bubble3/blob/59c735281a95b44f6263a25f4d6ce24fca520082/behave4cmd0/textutil.py#L148-L161 | train | 56,353 |
SteemData/steemdata | steemdata/markets.py | Tickers._wva | def _wva(values, weights):
""" Calculates a weighted average
"""
assert len(values) == len(weights) and len(weights) > 0
return sum([mul(*x) for x in zip(values, weights)]) / sum(weights) | python | def _wva(values, weights):
""" Calculates a weighted average
"""
assert len(values) == len(weights) and len(weights) > 0
return sum([mul(*x) for x in zip(values, weights)]) / sum(weights) | [
"def",
"_wva",
"(",
"values",
",",
"weights",
")",
":",
"assert",
"len",
"(",
"values",
")",
"==",
"len",
"(",
"weights",
")",
"and",
"len",
"(",
"weights",
")",
">",
"0",
"return",
"sum",
"(",
"[",
"mul",
"(",
"*",
"x",
")",
"for",
"x",
"in",
... | Calculates a weighted average | [
"Calculates",
"a",
"weighted",
"average"
] | 64dfc6d795deeb922e9041fa53e0946f07708ea1 | https://github.com/SteemData/steemdata/blob/64dfc6d795deeb922e9041fa53e0946f07708ea1/steemdata/markets.py#L113-L117 | train | 56,354 |
MacHu-GWU/crawlib-project | crawlib/spider.py | execute_one_to_many_job | def execute_one_to_many_job(parent_class=None,
get_unfinished_kwargs=None,
get_unfinished_limit=None,
parser_func=None,
parser_func_kwargs=None,
build_url_func_kwargs=None,
... | python | def execute_one_to_many_job(parent_class=None,
get_unfinished_kwargs=None,
get_unfinished_limit=None,
parser_func=None,
parser_func_kwargs=None,
build_url_func_kwargs=None,
... | [
"def",
"execute_one_to_many_job",
"(",
"parent_class",
"=",
"None",
",",
"get_unfinished_kwargs",
"=",
"None",
",",
"get_unfinished_limit",
"=",
"None",
",",
"parser_func",
"=",
"None",
",",
"parser_func_kwargs",
"=",
"None",
",",
"build_url_func_kwargs",
"=",
"None... | A standard one-to-many crawling workflow.
:param parent_class:
:param get_unfinished_kwargs:
:param get_unfinished_limit:
:param parser_func: html parser function.
:param parser_func_kwargs: other keyword arguments for ``parser_func``
:param build_url_func_kwargs: other keyword arguments for
... | [
"A",
"standard",
"one",
"-",
"to",
"-",
"many",
"crawling",
"workflow",
"."
] | 241516f2a7a0a32c692f7af35a1f44064e8ce1ab | https://github.com/MacHu-GWU/crawlib-project/blob/241516f2a7a0a32c692f7af35a1f44064e8ce1ab/crawlib/spider.py#L24-L114 | train | 56,355 |
sparknetworks/pgpm | pgpm/lib/utils/db.py | SqlScriptsHelper.create_db_schema | def create_db_schema(cls, cur, schema_name):
"""
Create Postgres schema script and execute it on cursor
"""
create_schema_script = "CREATE SCHEMA {0} ;\n".format(schema_name)
cur.execute(create_schema_script) | python | def create_db_schema(cls, cur, schema_name):
"""
Create Postgres schema script and execute it on cursor
"""
create_schema_script = "CREATE SCHEMA {0} ;\n".format(schema_name)
cur.execute(create_schema_script) | [
"def",
"create_db_schema",
"(",
"cls",
",",
"cur",
",",
"schema_name",
")",
":",
"create_schema_script",
"=",
"\"CREATE SCHEMA {0} ;\\n\"",
".",
"format",
"(",
"schema_name",
")",
"cur",
".",
"execute",
"(",
"create_schema_script",
")"
] | Create Postgres schema script and execute it on cursor | [
"Create",
"Postgres",
"schema",
"script",
"and",
"execute",
"it",
"on",
"cursor"
] | 1a060df46a886095181f692ea870a73a32510a2e | https://github.com/sparknetworks/pgpm/blob/1a060df46a886095181f692ea870a73a32510a2e/pgpm/lib/utils/db.py#L152-L157 | train | 56,356 |
sparknetworks/pgpm | pgpm/lib/utils/db.py | SqlScriptsHelper.revoke_all | def revoke_all(cls, cur, schema_name, roles):
"""
Revoke all privileges from schema, tables, sequences and functions for a specific role
"""
cur.execute('REVOKE ALL ON SCHEMA {0} FROM {1};'
'REVOKE ALL ON ALL TABLES IN SCHEMA {0} FROM {1};'
'REVOKE... | python | def revoke_all(cls, cur, schema_name, roles):
"""
Revoke all privileges from schema, tables, sequences and functions for a specific role
"""
cur.execute('REVOKE ALL ON SCHEMA {0} FROM {1};'
'REVOKE ALL ON ALL TABLES IN SCHEMA {0} FROM {1};'
'REVOKE... | [
"def",
"revoke_all",
"(",
"cls",
",",
"cur",
",",
"schema_name",
",",
"roles",
")",
":",
"cur",
".",
"execute",
"(",
"'REVOKE ALL ON SCHEMA {0} FROM {1};'",
"'REVOKE ALL ON ALL TABLES IN SCHEMA {0} FROM {1};'",
"'REVOKE ALL ON ALL SEQUENCES IN SCHEMA {0} FROM {1};'",
"'REVOKE A... | Revoke all privileges from schema, tables, sequences and functions for a specific role | [
"Revoke",
"all",
"privileges",
"from",
"schema",
"tables",
"sequences",
"and",
"functions",
"for",
"a",
"specific",
"role"
] | 1a060df46a886095181f692ea870a73a32510a2e | https://github.com/sparknetworks/pgpm/blob/1a060df46a886095181f692ea870a73a32510a2e/pgpm/lib/utils/db.py#L191-L198 | train | 56,357 |
sparknetworks/pgpm | pgpm/lib/utils/db.py | SqlScriptsHelper.schema_exists | def schema_exists(cls, cur, schema_name):
"""
Check if schema exists
"""
cur.execute("SELECT EXISTS (SELECT schema_name FROM information_schema.schemata WHERE schema_name = '{0}');"
.format(schema_name))
return cur.fetchone()[0] | python | def schema_exists(cls, cur, schema_name):
"""
Check if schema exists
"""
cur.execute("SELECT EXISTS (SELECT schema_name FROM information_schema.schemata WHERE schema_name = '{0}');"
.format(schema_name))
return cur.fetchone()[0] | [
"def",
"schema_exists",
"(",
"cls",
",",
"cur",
",",
"schema_name",
")",
":",
"cur",
".",
"execute",
"(",
"\"SELECT EXISTS (SELECT schema_name FROM information_schema.schemata WHERE schema_name = '{0}');\"",
".",
"format",
"(",
"schema_name",
")",
")",
"return",
"cur",
... | Check if schema exists | [
"Check",
"if",
"schema",
"exists"
] | 1a060df46a886095181f692ea870a73a32510a2e | https://github.com/sparknetworks/pgpm/blob/1a060df46a886095181f692ea870a73a32510a2e/pgpm/lib/utils/db.py#L209-L215 | train | 56,358 |
jplusplus/statscraper | statscraper/base_scraper.py | ResultSet.pandas | def pandas(self):
"""Return a Pandas dataframe."""
if self._pandas is None:
self._pandas = pd.DataFrame().from_records(self.list_of_dicts)
return self._pandas | python | def pandas(self):
"""Return a Pandas dataframe."""
if self._pandas is None:
self._pandas = pd.DataFrame().from_records(self.list_of_dicts)
return self._pandas | [
"def",
"pandas",
"(",
"self",
")",
":",
"if",
"self",
".",
"_pandas",
"is",
"None",
":",
"self",
".",
"_pandas",
"=",
"pd",
".",
"DataFrame",
"(",
")",
".",
"from_records",
"(",
"self",
".",
"list_of_dicts",
")",
"return",
"self",
".",
"_pandas"
] | Return a Pandas dataframe. | [
"Return",
"a",
"Pandas",
"dataframe",
"."
] | 932ec048b23d15b3dbdaf829facc55fd78ec0109 | https://github.com/jplusplus/statscraper/blob/932ec048b23d15b3dbdaf829facc55fd78ec0109/statscraper/base_scraper.py#L72-L76 | train | 56,359 |
jplusplus/statscraper | statscraper/base_scraper.py | ResultSet.translate | def translate(self, dialect):
"""Return a copy of this ResultSet in a different dialect."""
new_resultset = copy(self)
new_resultset.dialect = dialect
for result in new_resultset:
for dimensionvalue in result.dimensionvalues:
dimensionvalue.value = dimensionv... | python | def translate(self, dialect):
"""Return a copy of this ResultSet in a different dialect."""
new_resultset = copy(self)
new_resultset.dialect = dialect
for result in new_resultset:
for dimensionvalue in result.dimensionvalues:
dimensionvalue.value = dimensionv... | [
"def",
"translate",
"(",
"self",
",",
"dialect",
")",
":",
"new_resultset",
"=",
"copy",
"(",
"self",
")",
"new_resultset",
".",
"dialect",
"=",
"dialect",
"for",
"result",
"in",
"new_resultset",
":",
"for",
"dimensionvalue",
"in",
"result",
".",
"dimensionv... | Return a copy of this ResultSet in a different dialect. | [
"Return",
"a",
"copy",
"of",
"this",
"ResultSet",
"in",
"a",
"different",
"dialect",
"."
] | 932ec048b23d15b3dbdaf829facc55fd78ec0109 | https://github.com/jplusplus/statscraper/blob/932ec048b23d15b3dbdaf829facc55fd78ec0109/statscraper/base_scraper.py#L78-L86 | train | 56,360 |
jplusplus/statscraper | statscraper/base_scraper.py | ResultSet.append | def append(self, val):
"""Connect any new results to the resultset.
This is where all the heavy lifting is done for creating results:
- We add a datatype here, so that each result can handle
validation etc independently. This is so that scraper authors
don't need to worry about... | python | def append(self, val):
"""Connect any new results to the resultset.
This is where all the heavy lifting is done for creating results:
- We add a datatype here, so that each result can handle
validation etc independently. This is so that scraper authors
don't need to worry about... | [
"def",
"append",
"(",
"self",
",",
"val",
")",
":",
"val",
".",
"resultset",
"=",
"self",
"val",
".",
"dataset",
"=",
"self",
".",
"dataset",
"# Check result dimensions against available dimensions for this dataset",
"if",
"val",
".",
"dataset",
":",
"dataset_dime... | Connect any new results to the resultset.
This is where all the heavy lifting is done for creating results:
- We add a datatype here, so that each result can handle
validation etc independently. This is so that scraper authors
don't need to worry about creating and passing around datat... | [
"Connect",
"any",
"new",
"results",
"to",
"the",
"resultset",
"."
] | 932ec048b23d15b3dbdaf829facc55fd78ec0109 | https://github.com/jplusplus/statscraper/blob/932ec048b23d15b3dbdaf829facc55fd78ec0109/statscraper/base_scraper.py#L88-L140 | train | 56,361 |
jplusplus/statscraper | statscraper/base_scraper.py | Dimension.allowed_values | def allowed_values(self):
"""Return a list of allowed values."""
if self._allowed_values is None:
self._allowed_values = ValueList()
for val in self.scraper._fetch_allowed_values(self):
if isinstance(val, DimensionValue):
self._allowed_values.a... | python | def allowed_values(self):
"""Return a list of allowed values."""
if self._allowed_values is None:
self._allowed_values = ValueList()
for val in self.scraper._fetch_allowed_values(self):
if isinstance(val, DimensionValue):
self._allowed_values.a... | [
"def",
"allowed_values",
"(",
"self",
")",
":",
"if",
"self",
".",
"_allowed_values",
"is",
"None",
":",
"self",
".",
"_allowed_values",
"=",
"ValueList",
"(",
")",
"for",
"val",
"in",
"self",
".",
"scraper",
".",
"_fetch_allowed_values",
"(",
"self",
")",... | Return a list of allowed values. | [
"Return",
"a",
"list",
"of",
"allowed",
"values",
"."
] | 932ec048b23d15b3dbdaf829facc55fd78ec0109 | https://github.com/jplusplus/statscraper/blob/932ec048b23d15b3dbdaf829facc55fd78ec0109/statscraper/base_scraper.py#L240-L250 | train | 56,362 |
jplusplus/statscraper | statscraper/base_scraper.py | ItemList.append | def append(self, val):
"""Connect any new items to the scraper."""
val.scraper = self.scraper
val._collection_path = copy(self.collection._collection_path)
val._collection_path.append(val)
super(ItemList, self).append(val) | python | def append(self, val):
"""Connect any new items to the scraper."""
val.scraper = self.scraper
val._collection_path = copy(self.collection._collection_path)
val._collection_path.append(val)
super(ItemList, self).append(val) | [
"def",
"append",
"(",
"self",
",",
"val",
")",
":",
"val",
".",
"scraper",
"=",
"self",
".",
"scraper",
"val",
".",
"_collection_path",
"=",
"copy",
"(",
"self",
".",
"collection",
".",
"_collection_path",
")",
"val",
".",
"_collection_path",
".",
"appen... | Connect any new items to the scraper. | [
"Connect",
"any",
"new",
"items",
"to",
"the",
"scraper",
"."
] | 932ec048b23d15b3dbdaf829facc55fd78ec0109 | https://github.com/jplusplus/statscraper/blob/932ec048b23d15b3dbdaf829facc55fd78ec0109/statscraper/base_scraper.py#L272-L277 | train | 56,363 |
jplusplus/statscraper | statscraper/base_scraper.py | Item._move_here | def _move_here(self):
"""Move the cursor to this item."""
cu = self.scraper.current_item
# Already here?
if self is cu:
return
# A child?
if cu.items and self in cu.items:
self.scraper.move_to(self)
return
# A parent?
if... | python | def _move_here(self):
"""Move the cursor to this item."""
cu = self.scraper.current_item
# Already here?
if self is cu:
return
# A child?
if cu.items and self in cu.items:
self.scraper.move_to(self)
return
# A parent?
if... | [
"def",
"_move_here",
"(",
"self",
")",
":",
"cu",
"=",
"self",
".",
"scraper",
".",
"current_item",
"# Already here?",
"if",
"self",
"is",
"cu",
":",
"return",
"# A child?",
"if",
"cu",
".",
"items",
"and",
"self",
"in",
"cu",
".",
"items",
":",
"self"... | Move the cursor to this item. | [
"Move",
"the",
"cursor",
"to",
"this",
"item",
"."
] | 932ec048b23d15b3dbdaf829facc55fd78ec0109 | https://github.com/jplusplus/statscraper/blob/932ec048b23d15b3dbdaf829facc55fd78ec0109/statscraper/base_scraper.py#L298-L319 | train | 56,364 |
jplusplus/statscraper | statscraper/base_scraper.py | Collection.items | def items(self):
"""ItemList of children."""
if self.scraper.current_item is not self:
self._move_here()
if self._items is None:
self._items = ItemList()
self._items.scraper = self.scraper
self._items.collection = self
for i in self.sc... | python | def items(self):
"""ItemList of children."""
if self.scraper.current_item is not self:
self._move_here()
if self._items is None:
self._items = ItemList()
self._items.scraper = self.scraper
self._items.collection = self
for i in self.sc... | [
"def",
"items",
"(",
"self",
")",
":",
"if",
"self",
".",
"scraper",
".",
"current_item",
"is",
"not",
"self",
":",
"self",
".",
"_move_here",
"(",
")",
"if",
"self",
".",
"_items",
"is",
"None",
":",
"self",
".",
"_items",
"=",
"ItemList",
"(",
")... | ItemList of children. | [
"ItemList",
"of",
"children",
"."
] | 932ec048b23d15b3dbdaf829facc55fd78ec0109 | https://github.com/jplusplus/statscraper/blob/932ec048b23d15b3dbdaf829facc55fd78ec0109/statscraper/base_scraper.py#L361-L375 | train | 56,365 |
jplusplus/statscraper | statscraper/base_scraper.py | Dataset._hash | def _hash(self):
"""Return a hash for the current query.
This hash is _not_ a unique representation of the dataset!
"""
dump = dumps(self.query, sort_keys=True)
if isinstance(dump, str):
dump = dump.encode('utf-8')
return md5(dump).hexdigest() | python | def _hash(self):
"""Return a hash for the current query.
This hash is _not_ a unique representation of the dataset!
"""
dump = dumps(self.query, sort_keys=True)
if isinstance(dump, str):
dump = dump.encode('utf-8')
return md5(dump).hexdigest() | [
"def",
"_hash",
"(",
"self",
")",
":",
"dump",
"=",
"dumps",
"(",
"self",
".",
"query",
",",
"sort_keys",
"=",
"True",
")",
"if",
"isinstance",
"(",
"dump",
",",
"str",
")",
":",
"dump",
"=",
"dump",
".",
"encode",
"(",
"'utf-8'",
")",
"return",
... | Return a hash for the current query.
This hash is _not_ a unique representation of the dataset! | [
"Return",
"a",
"hash",
"for",
"the",
"current",
"query",
"."
] | 932ec048b23d15b3dbdaf829facc55fd78ec0109 | https://github.com/jplusplus/statscraper/blob/932ec048b23d15b3dbdaf829facc55fd78ec0109/statscraper/base_scraper.py#L413-L421 | train | 56,366 |
jplusplus/statscraper | statscraper/base_scraper.py | Dataset.dimensions | def dimensions(self):
"""Available dimensions, if defined."""
# First of all: Select this dataset
if self.scraper.current_item is not self:
self._move_here()
if self._dimensions is None:
self._dimensions = DimensionList()
for d in self.scraper._fetch_... | python | def dimensions(self):
"""Available dimensions, if defined."""
# First of all: Select this dataset
if self.scraper.current_item is not self:
self._move_here()
if self._dimensions is None:
self._dimensions = DimensionList()
for d in self.scraper._fetch_... | [
"def",
"dimensions",
"(",
"self",
")",
":",
"# First of all: Select this dataset",
"if",
"self",
".",
"scraper",
".",
"current_item",
"is",
"not",
"self",
":",
"self",
".",
"_move_here",
"(",
")",
"if",
"self",
".",
"_dimensions",
"is",
"None",
":",
"self",
... | Available dimensions, if defined. | [
"Available",
"dimensions",
"if",
"defined",
"."
] | 932ec048b23d15b3dbdaf829facc55fd78ec0109 | https://github.com/jplusplus/statscraper/blob/932ec048b23d15b3dbdaf829facc55fd78ec0109/statscraper/base_scraper.py#L478-L490 | train | 56,367 |
jplusplus/statscraper | statscraper/base_scraper.py | BaseScraper.on | def on(cls, hook):
"""Hook decorator."""
def decorator(function_):
cls._hooks[hook].append(function_)
return function_
return decorator | python | def on(cls, hook):
"""Hook decorator."""
def decorator(function_):
cls._hooks[hook].append(function_)
return function_
return decorator | [
"def",
"on",
"(",
"cls",
",",
"hook",
")",
":",
"def",
"decorator",
"(",
"function_",
")",
":",
"cls",
".",
"_hooks",
"[",
"hook",
"]",
".",
"append",
"(",
"function_",
")",
"return",
"function_",
"return",
"decorator"
] | Hook decorator. | [
"Hook",
"decorator",
"."
] | 932ec048b23d15b3dbdaf829facc55fd78ec0109 | https://github.com/jplusplus/statscraper/blob/932ec048b23d15b3dbdaf829facc55fd78ec0109/statscraper/base_scraper.py#L514-L519 | train | 56,368 |
jplusplus/statscraper | statscraper/base_scraper.py | BaseScraper.move_to_top | def move_to_top(self):
"""Move to root item."""
self.current_item = self.root
for f in self._hooks["top"]:
f(self)
return self | python | def move_to_top(self):
"""Move to root item."""
self.current_item = self.root
for f in self._hooks["top"]:
f(self)
return self | [
"def",
"move_to_top",
"(",
"self",
")",
":",
"self",
".",
"current_item",
"=",
"self",
".",
"root",
"for",
"f",
"in",
"self",
".",
"_hooks",
"[",
"\"top\"",
"]",
":",
"f",
"(",
"self",
")",
"return",
"self"
] | Move to root item. | [
"Move",
"to",
"root",
"item",
"."
] | 932ec048b23d15b3dbdaf829facc55fd78ec0109 | https://github.com/jplusplus/statscraper/blob/932ec048b23d15b3dbdaf829facc55fd78ec0109/statscraper/base_scraper.py#L560-L565 | train | 56,369 |
jplusplus/statscraper | statscraper/base_scraper.py | BaseScraper.move_up | def move_up(self):
"""Move up one level in the hierarchy, unless already on top."""
if self.current_item.parent is not None:
self.current_item = self.current_item.parent
for f in self._hooks["up"]:
f(self)
if self.current_item is self.root:
for f in s... | python | def move_up(self):
"""Move up one level in the hierarchy, unless already on top."""
if self.current_item.parent is not None:
self.current_item = self.current_item.parent
for f in self._hooks["up"]:
f(self)
if self.current_item is self.root:
for f in s... | [
"def",
"move_up",
"(",
"self",
")",
":",
"if",
"self",
".",
"current_item",
".",
"parent",
"is",
"not",
"None",
":",
"self",
".",
"current_item",
"=",
"self",
".",
"current_item",
".",
"parent",
"for",
"f",
"in",
"self",
".",
"_hooks",
"[",
"\"up\"",
... | Move up one level in the hierarchy, unless already on top. | [
"Move",
"up",
"one",
"level",
"in",
"the",
"hierarchy",
"unless",
"already",
"on",
"top",
"."
] | 932ec048b23d15b3dbdaf829facc55fd78ec0109 | https://github.com/jplusplus/statscraper/blob/932ec048b23d15b3dbdaf829facc55fd78ec0109/statscraper/base_scraper.py#L567-L577 | train | 56,370 |
jplusplus/statscraper | statscraper/base_scraper.py | BaseScraper.descendants | def descendants(self):
"""Recursively return every dataset below current item."""
for i in self.current_item.items:
self.move_to(i)
if i.type == TYPE_COLLECTION:
for c in self.children:
yield c
else:
yield i
... | python | def descendants(self):
"""Recursively return every dataset below current item."""
for i in self.current_item.items:
self.move_to(i)
if i.type == TYPE_COLLECTION:
for c in self.children:
yield c
else:
yield i
... | [
"def",
"descendants",
"(",
"self",
")",
":",
"for",
"i",
"in",
"self",
".",
"current_item",
".",
"items",
":",
"self",
".",
"move_to",
"(",
"i",
")",
"if",
"i",
".",
"type",
"==",
"TYPE_COLLECTION",
":",
"for",
"c",
"in",
"self",
".",
"children",
"... | Recursively return every dataset below current item. | [
"Recursively",
"return",
"every",
"dataset",
"below",
"current",
"item",
"."
] | 932ec048b23d15b3dbdaf829facc55fd78ec0109 | https://github.com/jplusplus/statscraper/blob/932ec048b23d15b3dbdaf829facc55fd78ec0109/statscraper/base_scraper.py#L626-L635 | train | 56,371 |
jplusplus/statscraper | statscraper/base_scraper.py | BaseScraper.children | def children(self):
"""Former, misleading name for descendants."""
from warnings import warn
warn("Deprecated. Use Scraper.descendants.", DeprecationWarning)
for descendant in self.descendants:
yield descendant | python | def children(self):
"""Former, misleading name for descendants."""
from warnings import warn
warn("Deprecated. Use Scraper.descendants.", DeprecationWarning)
for descendant in self.descendants:
yield descendant | [
"def",
"children",
"(",
"self",
")",
":",
"from",
"warnings",
"import",
"warn",
"warn",
"(",
"\"Deprecated. Use Scraper.descendants.\"",
",",
"DeprecationWarning",
")",
"for",
"descendant",
"in",
"self",
".",
"descendants",
":",
"yield",
"descendant"
] | Former, misleading name for descendants. | [
"Former",
"misleading",
"name",
"for",
"descendants",
"."
] | 932ec048b23d15b3dbdaf829facc55fd78ec0109 | https://github.com/jplusplus/statscraper/blob/932ec048b23d15b3dbdaf829facc55fd78ec0109/statscraper/base_scraper.py#L638-L643 | train | 56,372 |
orbeckst/RecSQL | recsql/csv_table.py | make_python_name | def make_python_name(s, default=None, number_prefix='N',encoding="utf-8"):
"""Returns a unicode string that can be used as a legal python identifier.
:Arguments:
*s*
string
*default*
use *default* if *s* is ``None``
*number_prefix*
string to prepend if *s* starts wi... | python | def make_python_name(s, default=None, number_prefix='N',encoding="utf-8"):
"""Returns a unicode string that can be used as a legal python identifier.
:Arguments:
*s*
string
*default*
use *default* if *s* is ``None``
*number_prefix*
string to prepend if *s* starts wi... | [
"def",
"make_python_name",
"(",
"s",
",",
"default",
"=",
"None",
",",
"number_prefix",
"=",
"'N'",
",",
"encoding",
"=",
"\"utf-8\"",
")",
":",
"if",
"s",
"in",
"(",
"''",
",",
"None",
")",
":",
"s",
"=",
"default",
"s",
"=",
"str",
"(",
"s",
")... | Returns a unicode string that can be used as a legal python identifier.
:Arguments:
*s*
string
*default*
use *default* if *s* is ``None``
*number_prefix*
string to prepend if *s* starts with a number | [
"Returns",
"a",
"unicode",
"string",
"that",
"can",
"be",
"used",
"as",
"a",
"legal",
"python",
"identifier",
"."
] | 6acbf821022361719391697c9c2f0822f9f8022a | https://github.com/orbeckst/RecSQL/blob/6acbf821022361719391697c9c2f0822f9f8022a/recsql/csv_table.py#L75-L92 | train | 56,373 |
tradenity/python-sdk | tradenity/resources/option.py | Option.data_type | def data_type(self, data_type):
"""Sets the data_type of this Option.
:param data_type: The data_type of this Option.
:type: str
"""
allowed_values = ["string", "number", "date", "color"]
if data_type is not None and data_type not in allowed_values:
raise Va... | python | def data_type(self, data_type):
"""Sets the data_type of this Option.
:param data_type: The data_type of this Option.
:type: str
"""
allowed_values = ["string", "number", "date", "color"]
if data_type is not None and data_type not in allowed_values:
raise Va... | [
"def",
"data_type",
"(",
"self",
",",
"data_type",
")",
":",
"allowed_values",
"=",
"[",
"\"string\"",
",",
"\"number\"",
",",
"\"date\"",
",",
"\"color\"",
"]",
"if",
"data_type",
"is",
"not",
"None",
"and",
"data_type",
"not",
"in",
"allowed_values",
":",
... | Sets the data_type of this Option.
:param data_type: The data_type of this Option.
:type: str | [
"Sets",
"the",
"data_type",
"of",
"this",
"Option",
"."
] | d13fbe23f4d6ff22554c6d8d2deaf209371adaf1 | https://github.com/tradenity/python-sdk/blob/d13fbe23f4d6ff22554c6d8d2deaf209371adaf1/tradenity/resources/option.py#L214-L228 | train | 56,374 |
inveniosoftware-attic/invenio-utils | invenio_utils/autodiscovery/helpers.py | get_callable_signature_as_string | def get_callable_signature_as_string(the_callable):
"""Return a string representing a callable.
It is executed as if it would have been declared on the prompt.
>>> def foo(arg1, arg2, arg3='val1', arg4='val2', *args, **argd):
... pass
>>> get_callable_signature_as_string(foo)
def foo(arg1,... | python | def get_callable_signature_as_string(the_callable):
"""Return a string representing a callable.
It is executed as if it would have been declared on the prompt.
>>> def foo(arg1, arg2, arg3='val1', arg4='val2', *args, **argd):
... pass
>>> get_callable_signature_as_string(foo)
def foo(arg1,... | [
"def",
"get_callable_signature_as_string",
"(",
"the_callable",
")",
":",
"args",
",",
"varargs",
",",
"varkw",
",",
"defaults",
"=",
"inspect",
".",
"getargspec",
"(",
"the_callable",
")",
"tmp_args",
"=",
"list",
"(",
"args",
")",
"args_dict",
"=",
"{",
"}... | Return a string representing a callable.
It is executed as if it would have been declared on the prompt.
>>> def foo(arg1, arg2, arg3='val1', arg4='val2', *args, **argd):
... pass
>>> get_callable_signature_as_string(foo)
def foo(arg1, arg2, arg3='val1', arg4='val2', *args, **argd)
:param... | [
"Return",
"a",
"string",
"representing",
"a",
"callable",
"."
] | 9a1c6db4e3f1370901f329f510480dd8df188296 | https://github.com/inveniosoftware-attic/invenio-utils/blob/9a1c6db4e3f1370901f329f510480dd8df188296/invenio_utils/autodiscovery/helpers.py#L27-L69 | train | 56,375 |
inveniosoftware-attic/invenio-utils | invenio_utils/autodiscovery/helpers.py | get_callable_documentation | def get_callable_documentation(the_callable):
"""Return a string with the callable signature and its docstring.
:param the_callable: the callable to be analyzed.
:type the_callable: function/callable.
:return: the signature.
"""
return wrap_text_in_a_box(
title=get_callable_signature_as... | python | def get_callable_documentation(the_callable):
"""Return a string with the callable signature and its docstring.
:param the_callable: the callable to be analyzed.
:type the_callable: function/callable.
:return: the signature.
"""
return wrap_text_in_a_box(
title=get_callable_signature_as... | [
"def",
"get_callable_documentation",
"(",
"the_callable",
")",
":",
"return",
"wrap_text_in_a_box",
"(",
"title",
"=",
"get_callable_signature_as_string",
"(",
"the_callable",
")",
",",
"body",
"=",
"(",
"getattr",
"(",
"the_callable",
",",
"'__doc__'",
")",
"or",
... | Return a string with the callable signature and its docstring.
:param the_callable: the callable to be analyzed.
:type the_callable: function/callable.
:return: the signature. | [
"Return",
"a",
"string",
"with",
"the",
"callable",
"signature",
"and",
"its",
"docstring",
"."
] | 9a1c6db4e3f1370901f329f510480dd8df188296 | https://github.com/inveniosoftware-attic/invenio-utils/blob/9a1c6db4e3f1370901f329f510480dd8df188296/invenio_utils/autodiscovery/helpers.py#L72-L83 | train | 56,376 |
objectrocket/python-client | objectrocket/util.py | register_extension_class | def register_extension_class(ext, base, *args, **kwargs):
"""Instantiate the given extension class and register as a public attribute of the given base.
README: The expected protocol here is to instantiate the given extension and pass the base
object as the first positional argument, then unpack args and k... | python | def register_extension_class(ext, base, *args, **kwargs):
"""Instantiate the given extension class and register as a public attribute of the given base.
README: The expected protocol here is to instantiate the given extension and pass the base
object as the first positional argument, then unpack args and k... | [
"def",
"register_extension_class",
"(",
"ext",
",",
"base",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"ext_instance",
"=",
"ext",
".",
"plugin",
"(",
"base",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
"setattr",
"(",
"base",
",",
"e... | Instantiate the given extension class and register as a public attribute of the given base.
README: The expected protocol here is to instantiate the given extension and pass the base
object as the first positional argument, then unpack args and kwargs as additional arguments to
the extension's constructor. | [
"Instantiate",
"the",
"given",
"extension",
"class",
"and",
"register",
"as",
"a",
"public",
"attribute",
"of",
"the",
"given",
"base",
"."
] | a65868c7511ff49a5fbe304e53bf592b7fc6d5ef | https://github.com/objectrocket/python-client/blob/a65868c7511ff49a5fbe304e53bf592b7fc6d5ef/objectrocket/util.py#L12-L20 | train | 56,377 |
objectrocket/python-client | objectrocket/util.py | register_extension_method | def register_extension_method(ext, base, *args, **kwargs):
"""Register the given extension method as a public attribute of the given base.
README: The expected protocol here is that the given extension method is an unbound function.
It will be bound to the specified base as a method, and then set as a publ... | python | def register_extension_method(ext, base, *args, **kwargs):
"""Register the given extension method as a public attribute of the given base.
README: The expected protocol here is that the given extension method is an unbound function.
It will be bound to the specified base as a method, and then set as a publ... | [
"def",
"register_extension_method",
"(",
"ext",
",",
"base",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"bound_method",
"=",
"create_bound_method",
"(",
"ext",
".",
"plugin",
",",
"base",
")",
"setattr",
"(",
"base",
",",
"ext",
".",
"name",
... | Register the given extension method as a public attribute of the given base.
README: The expected protocol here is that the given extension method is an unbound function.
It will be bound to the specified base as a method, and then set as a public attribute of that
base. | [
"Register",
"the",
"given",
"extension",
"method",
"as",
"a",
"public",
"attribute",
"of",
"the",
"given",
"base",
"."
] | a65868c7511ff49a5fbe304e53bf592b7fc6d5ef | https://github.com/objectrocket/python-client/blob/a65868c7511ff49a5fbe304e53bf592b7fc6d5ef/objectrocket/util.py#L23-L31 | train | 56,378 |
objectrocket/python-client | objectrocket/util.py | token_auto_auth | def token_auto_auth(func):
"""Wrap class methods with automatic token re-authentication.
This wrapper will detect authentication failures coming from its wrapped method. When one is
caught, it will request a new token, and simply replay the original request.
The one constraint that this wrapper has is... | python | def token_auto_auth(func):
"""Wrap class methods with automatic token re-authentication.
This wrapper will detect authentication failures coming from its wrapped method. When one is
caught, it will request a new token, and simply replay the original request.
The one constraint that this wrapper has is... | [
"def",
"token_auto_auth",
"(",
"func",
")",
":",
"@",
"functools",
".",
"wraps",
"(",
"func",
")",
"def",
"wrapper",
"(",
"self",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"try",
":",
"response",
"=",
"func",
"(",
"self",
",",
"*",
"ar... | Wrap class methods with automatic token re-authentication.
This wrapper will detect authentication failures coming from its wrapped method. When one is
caught, it will request a new token, and simply replay the original request.
The one constraint that this wrapper has is that the wrapped method's class m... | [
"Wrap",
"class",
"methods",
"with",
"automatic",
"token",
"re",
"-",
"authentication",
"."
] | a65868c7511ff49a5fbe304e53bf592b7fc6d5ef | https://github.com/objectrocket/python-client/blob/a65868c7511ff49a5fbe304e53bf592b7fc6d5ef/objectrocket/util.py#L34-L62 | train | 56,379 |
jkitzes/macroeco | doc/_ext/juliadoc/juliadoc/__init__.py | get_theme_dir | def get_theme_dir():
"""
Returns path to directory containing this package's theme.
This is designed to be used when setting the ``html_theme_path``
option within Sphinx's ``conf.py`` file.
"""
return os.path.abspath(os.path.join(os.path.dirname(__file__), "theme")) | python | def get_theme_dir():
"""
Returns path to directory containing this package's theme.
This is designed to be used when setting the ``html_theme_path``
option within Sphinx's ``conf.py`` file.
"""
return os.path.abspath(os.path.join(os.path.dirname(__file__), "theme")) | [
"def",
"get_theme_dir",
"(",
")",
":",
"return",
"os",
".",
"path",
".",
"abspath",
"(",
"os",
".",
"path",
".",
"join",
"(",
"os",
".",
"path",
".",
"dirname",
"(",
"__file__",
")",
",",
"\"theme\"",
")",
")"
] | Returns path to directory containing this package's theme.
This is designed to be used when setting the ``html_theme_path``
option within Sphinx's ``conf.py`` file. | [
"Returns",
"path",
"to",
"directory",
"containing",
"this",
"package",
"s",
"theme",
".",
"This",
"is",
"designed",
"to",
"be",
"used",
"when",
"setting",
"the",
"html_theme_path",
"option",
"within",
"Sphinx",
"s",
"conf",
".",
"py",
"file",
"."
] | ee5fac5560a2d64de3a64738b5bc6833e2d7ff2e | https://github.com/jkitzes/macroeco/blob/ee5fac5560a2d64de3a64738b5bc6833e2d7ff2e/doc/_ext/juliadoc/juliadoc/__init__.py#L3-L10 | train | 56,380 |
trevisanj/a99 | a99/conversion.py | seconds2str | def seconds2str(seconds):
"""Returns string such as 1h 05m 55s."""
if seconds < 0:
return "{0:.3g}s".format(seconds)
elif math.isnan(seconds):
return "NaN"
elif math.isinf(seconds):
return "Inf"
m, s = divmod(seconds, 60)
h, m = divmod(m, 60)
if h >= 1:
... | python | def seconds2str(seconds):
"""Returns string such as 1h 05m 55s."""
if seconds < 0:
return "{0:.3g}s".format(seconds)
elif math.isnan(seconds):
return "NaN"
elif math.isinf(seconds):
return "Inf"
m, s = divmod(seconds, 60)
h, m = divmod(m, 60)
if h >= 1:
... | [
"def",
"seconds2str",
"(",
"seconds",
")",
":",
"if",
"seconds",
"<",
"0",
":",
"return",
"\"{0:.3g}s\"",
".",
"format",
"(",
"seconds",
")",
"elif",
"math",
".",
"isnan",
"(",
"seconds",
")",
":",
"return",
"\"NaN\"",
"elif",
"math",
".",
"isinf",
"("... | Returns string such as 1h 05m 55s. | [
"Returns",
"string",
"such",
"as",
"1h",
"05m",
"55s",
"."
] | 193e6e3c9b3e4f4a0ba7eb3eece846fe7045c539 | https://github.com/trevisanj/a99/blob/193e6e3c9b3e4f4a0ba7eb3eece846fe7045c539/a99/conversion.py#L105-L122 | train | 56,381 |
trevisanj/a99 | a99/conversion.py | eval_fieldnames | def eval_fieldnames(string_, varname="fieldnames"):
"""Evaluates string_, must evaluate to list of strings. Also converts field names to uppercase"""
ff = eval(string_)
if not isinstance(ff, list):
raise RuntimeError("{0!s} must be a list".format(varname))
if not all([isinstance(x, str) for... | python | def eval_fieldnames(string_, varname="fieldnames"):
"""Evaluates string_, must evaluate to list of strings. Also converts field names to uppercase"""
ff = eval(string_)
if not isinstance(ff, list):
raise RuntimeError("{0!s} must be a list".format(varname))
if not all([isinstance(x, str) for... | [
"def",
"eval_fieldnames",
"(",
"string_",
",",
"varname",
"=",
"\"fieldnames\"",
")",
":",
"ff",
"=",
"eval",
"(",
"string_",
")",
"if",
"not",
"isinstance",
"(",
"ff",
",",
"list",
")",
":",
"raise",
"RuntimeError",
"(",
"\"{0!s} must be a list\"",
".",
"... | Evaluates string_, must evaluate to list of strings. Also converts field names to uppercase | [
"Evaluates",
"string_",
"must",
"evaluate",
"to",
"list",
"of",
"strings",
".",
"Also",
"converts",
"field",
"names",
"to",
"uppercase"
] | 193e6e3c9b3e4f4a0ba7eb3eece846fe7045c539 | https://github.com/trevisanj/a99/blob/193e6e3c9b3e4f4a0ba7eb3eece846fe7045c539/a99/conversion.py#L184-L192 | train | 56,382 |
kgaughan/dbkit | examples/notary/notary.py | strip_accents | def strip_accents(s):
"""
Strip accents to prepare for slugification.
"""
nfkd = unicodedata.normalize('NFKD', unicode(s))
return u''.join(ch for ch in nfkd if not unicodedata.combining(ch)) | python | def strip_accents(s):
"""
Strip accents to prepare for slugification.
"""
nfkd = unicodedata.normalize('NFKD', unicode(s))
return u''.join(ch for ch in nfkd if not unicodedata.combining(ch)) | [
"def",
"strip_accents",
"(",
"s",
")",
":",
"nfkd",
"=",
"unicodedata",
".",
"normalize",
"(",
"'NFKD'",
",",
"unicode",
"(",
"s",
")",
")",
"return",
"u''",
".",
"join",
"(",
"ch",
"for",
"ch",
"in",
"nfkd",
"if",
"not",
"unicodedata",
".",
"combini... | Strip accents to prepare for slugification. | [
"Strip",
"accents",
"to",
"prepare",
"for",
"slugification",
"."
] | 2aef6376a60965d7820c91692046f4bcf7d43640 | https://github.com/kgaughan/dbkit/blob/2aef6376a60965d7820c91692046f4bcf7d43640/examples/notary/notary.py#L35-L40 | train | 56,383 |
kgaughan/dbkit | examples/notary/notary.py | slugify | def slugify(s):
"""
Converts the given string to a URL slug.
"""
s = strip_accents(s.replace("'", '').lower())
return re.sub('[^a-z0-9]+', ' ', s).strip().replace(' ', '-') | python | def slugify(s):
"""
Converts the given string to a URL slug.
"""
s = strip_accents(s.replace("'", '').lower())
return re.sub('[^a-z0-9]+', ' ', s).strip().replace(' ', '-') | [
"def",
"slugify",
"(",
"s",
")",
":",
"s",
"=",
"strip_accents",
"(",
"s",
".",
"replace",
"(",
"\"'\"",
",",
"''",
")",
".",
"lower",
"(",
")",
")",
"return",
"re",
".",
"sub",
"(",
"'[^a-z0-9]+'",
",",
"' '",
",",
"s",
")",
".",
"strip",
"(",... | Converts the given string to a URL slug. | [
"Converts",
"the",
"given",
"string",
"to",
"a",
"URL",
"slug",
"."
] | 2aef6376a60965d7820c91692046f4bcf7d43640 | https://github.com/kgaughan/dbkit/blob/2aef6376a60965d7820c91692046f4bcf7d43640/examples/notary/notary.py#L43-L48 | train | 56,384 |
kellerza/pyqwikswitch | pyqwikswitch/qwikswitch.py | _legacy_status | def _legacy_status(stat):
"""Legacy status method from the 'qsmobile.js' library.
Pass in the 'val' from &devices or the
'data' received after calling a specific ID.
"""
# 2d0c00002a0000
if stat[:2] == '30' or stat[:2] == '47': # RX1 CT
ooo = stat[4:5]
# console.log("legstat. "... | python | def _legacy_status(stat):
"""Legacy status method from the 'qsmobile.js' library.
Pass in the 'val' from &devices or the
'data' received after calling a specific ID.
"""
# 2d0c00002a0000
if stat[:2] == '30' or stat[:2] == '47': # RX1 CT
ooo = stat[4:5]
# console.log("legstat. "... | [
"def",
"_legacy_status",
"(",
"stat",
")",
":",
"# 2d0c00002a0000",
"if",
"stat",
"[",
":",
"2",
"]",
"==",
"'30'",
"or",
"stat",
"[",
":",
"2",
"]",
"==",
"'47'",
":",
"# RX1 CT",
"ooo",
"=",
"stat",
"[",
"4",
":",
"5",
"]",
"# console.log(\"legstat... | Legacy status method from the 'qsmobile.js' library.
Pass in the 'val' from &devices or the
'data' received after calling a specific ID. | [
"Legacy",
"status",
"method",
"from",
"the",
"qsmobile",
".",
"js",
"library",
"."
] | 9d4f080048221eaee93e3eefcf641919ff1af586 | https://github.com/kellerza/pyqwikswitch/blob/9d4f080048221eaee93e3eefcf641919ff1af586/pyqwikswitch/qwikswitch.py#L55-L98 | train | 56,385 |
kellerza/pyqwikswitch | pyqwikswitch/qwikswitch.py | decode_door | def decode_door(packet, channel=1):
"""Decode a door sensor."""
val = str(packet.get(QSDATA, ''))
if len(val) == 6 and val.startswith('46') and channel == 1:
return val[-1] == '0'
return None | python | def decode_door(packet, channel=1):
"""Decode a door sensor."""
val = str(packet.get(QSDATA, ''))
if len(val) == 6 and val.startswith('46') and channel == 1:
return val[-1] == '0'
return None | [
"def",
"decode_door",
"(",
"packet",
",",
"channel",
"=",
"1",
")",
":",
"val",
"=",
"str",
"(",
"packet",
".",
"get",
"(",
"QSDATA",
",",
"''",
")",
")",
"if",
"len",
"(",
"val",
")",
"==",
"6",
"and",
"val",
".",
"startswith",
"(",
"'46'",
")... | Decode a door sensor. | [
"Decode",
"a",
"door",
"sensor",
"."
] | 9d4f080048221eaee93e3eefcf641919ff1af586 | https://github.com/kellerza/pyqwikswitch/blob/9d4f080048221eaee93e3eefcf641919ff1af586/pyqwikswitch/qwikswitch.py#L211-L216 | train | 56,386 |
kellerza/pyqwikswitch | pyqwikswitch/qwikswitch.py | decode_imod | def decode_imod(packet, channel=1):
"""Decode an 4 channel imod. May support 6 channels."""
val = str(packet.get(QSDATA, ''))
if len(val) == 8 and val.startswith('4e'):
try:
_map = ((5, 1), (5, 2), (5, 4), (4, 1), (5, 1), (5, 2))[
channel - 1]
return (int(val[... | python | def decode_imod(packet, channel=1):
"""Decode an 4 channel imod. May support 6 channels."""
val = str(packet.get(QSDATA, ''))
if len(val) == 8 and val.startswith('4e'):
try:
_map = ((5, 1), (5, 2), (5, 4), (4, 1), (5, 1), (5, 2))[
channel - 1]
return (int(val[... | [
"def",
"decode_imod",
"(",
"packet",
",",
"channel",
"=",
"1",
")",
":",
"val",
"=",
"str",
"(",
"packet",
".",
"get",
"(",
"QSDATA",
",",
"''",
")",
")",
"if",
"len",
"(",
"val",
")",
"==",
"8",
"and",
"val",
".",
"startswith",
"(",
"'4e'",
")... | Decode an 4 channel imod. May support 6 channels. | [
"Decode",
"an",
"4",
"channel",
"imod",
".",
"May",
"support",
"6",
"channels",
"."
] | 9d4f080048221eaee93e3eefcf641919ff1af586 | https://github.com/kellerza/pyqwikswitch/blob/9d4f080048221eaee93e3eefcf641919ff1af586/pyqwikswitch/qwikswitch.py#L228-L238 | train | 56,387 |
kellerza/pyqwikswitch | pyqwikswitch/qwikswitch.py | decode_pir | def decode_pir(packet, channel=1):
"""Decode a PIR."""
val = str(packet.get(QSDATA, ''))
if len(val) == 8 and val.startswith('0f') and channel == 1:
return int(val[-4:], 16) > 0
return None | python | def decode_pir(packet, channel=1):
"""Decode a PIR."""
val = str(packet.get(QSDATA, ''))
if len(val) == 8 and val.startswith('0f') and channel == 1:
return int(val[-4:], 16) > 0
return None | [
"def",
"decode_pir",
"(",
"packet",
",",
"channel",
"=",
"1",
")",
":",
"val",
"=",
"str",
"(",
"packet",
".",
"get",
"(",
"QSDATA",
",",
"''",
")",
")",
"if",
"len",
"(",
"val",
")",
"==",
"8",
"and",
"val",
".",
"startswith",
"(",
"'0f'",
")"... | Decode a PIR. | [
"Decode",
"a",
"PIR",
"."
] | 9d4f080048221eaee93e3eefcf641919ff1af586 | https://github.com/kellerza/pyqwikswitch/blob/9d4f080048221eaee93e3eefcf641919ff1af586/pyqwikswitch/qwikswitch.py#L246-L251 | train | 56,388 |
kellerza/pyqwikswitch | pyqwikswitch/qwikswitch.py | decode_temperature | def decode_temperature(packet, channel=1):
"""Decode the temperature."""
val = str(packet.get(QSDATA, ''))
if len(val) == 12 and val.startswith('34') and channel == 1:
temperature = int(val[-4:], 16)
return round(float((-46.85 + (175.72 * (temperature / pow(2, 16))))))
return None | python | def decode_temperature(packet, channel=1):
"""Decode the temperature."""
val = str(packet.get(QSDATA, ''))
if len(val) == 12 and val.startswith('34') and channel == 1:
temperature = int(val[-4:], 16)
return round(float((-46.85 + (175.72 * (temperature / pow(2, 16))))))
return None | [
"def",
"decode_temperature",
"(",
"packet",
",",
"channel",
"=",
"1",
")",
":",
"val",
"=",
"str",
"(",
"packet",
".",
"get",
"(",
"QSDATA",
",",
"''",
")",
")",
"if",
"len",
"(",
"val",
")",
"==",
"12",
"and",
"val",
".",
"startswith",
"(",
"'34... | Decode the temperature. | [
"Decode",
"the",
"temperature",
"."
] | 9d4f080048221eaee93e3eefcf641919ff1af586 | https://github.com/kellerza/pyqwikswitch/blob/9d4f080048221eaee93e3eefcf641919ff1af586/pyqwikswitch/qwikswitch.py#L259-L265 | train | 56,389 |
kellerza/pyqwikswitch | pyqwikswitch/qwikswitch.py | decode_humidity | def decode_humidity(packet, channel=1):
"""Decode the humidity."""
val = str(packet.get(QSDATA, ''))
if len(val) == 12 and val.startswith('34') and channel == 1:
humidity = int(val[4:-4], 16)
return round(float(-6 + (125 * (humidity / pow(2, 16)))))
return None | python | def decode_humidity(packet, channel=1):
"""Decode the humidity."""
val = str(packet.get(QSDATA, ''))
if len(val) == 12 and val.startswith('34') and channel == 1:
humidity = int(val[4:-4], 16)
return round(float(-6 + (125 * (humidity / pow(2, 16)))))
return None | [
"def",
"decode_humidity",
"(",
"packet",
",",
"channel",
"=",
"1",
")",
":",
"val",
"=",
"str",
"(",
"packet",
".",
"get",
"(",
"QSDATA",
",",
"''",
")",
")",
"if",
"len",
"(",
"val",
")",
"==",
"12",
"and",
"val",
".",
"startswith",
"(",
"'34'",... | Decode the humidity. | [
"Decode",
"the",
"humidity",
"."
] | 9d4f080048221eaee93e3eefcf641919ff1af586 | https://github.com/kellerza/pyqwikswitch/blob/9d4f080048221eaee93e3eefcf641919ff1af586/pyqwikswitch/qwikswitch.py#L268-L274 | train | 56,390 |
kellerza/pyqwikswitch | pyqwikswitch/qwikswitch.py | QSDevices.update_devices | def update_devices(self, devices):
"""Update values from response of URL_DEVICES, callback if changed."""
for qspacket in devices:
try:
qsid = qspacket[QS_ID]
except KeyError:
_LOGGER.debug("Device without ID: %s", qspacket)
continu... | python | def update_devices(self, devices):
"""Update values from response of URL_DEVICES, callback if changed."""
for qspacket in devices:
try:
qsid = qspacket[QS_ID]
except KeyError:
_LOGGER.debug("Device without ID: %s", qspacket)
continu... | [
"def",
"update_devices",
"(",
"self",
",",
"devices",
")",
":",
"for",
"qspacket",
"in",
"devices",
":",
"try",
":",
"qsid",
"=",
"qspacket",
"[",
"QS_ID",
"]",
"except",
"KeyError",
":",
"_LOGGER",
".",
"debug",
"(",
"\"Device without ID: %s\"",
",",
"qsp... | Update values from response of URL_DEVICES, callback if changed. | [
"Update",
"values",
"from",
"response",
"of",
"URL_DEVICES",
"callback",
"if",
"changed",
"."
] | 9d4f080048221eaee93e3eefcf641919ff1af586 | https://github.com/kellerza/pyqwikswitch/blob/9d4f080048221eaee93e3eefcf641919ff1af586/pyqwikswitch/qwikswitch.py#L175-L198 | train | 56,391 |
ten10solutions/Geist | geist/backends/replay.py | geist_replay | def geist_replay(wrapped, instance, args, kwargs):
"""Wraps a test of other function and injects a Geist GUI which will
enable replay (set environment variable GEIST_REPLAY_MODE to 'record' to
active record mode."""
path_parts = []
file_parts = []
if hasattr(wrapped, '__module__'):
modu... | python | def geist_replay(wrapped, instance, args, kwargs):
"""Wraps a test of other function and injects a Geist GUI which will
enable replay (set environment variable GEIST_REPLAY_MODE to 'record' to
active record mode."""
path_parts = []
file_parts = []
if hasattr(wrapped, '__module__'):
modu... | [
"def",
"geist_replay",
"(",
"wrapped",
",",
"instance",
",",
"args",
",",
"kwargs",
")",
":",
"path_parts",
"=",
"[",
"]",
"file_parts",
"=",
"[",
"]",
"if",
"hasattr",
"(",
"wrapped",
",",
"'__module__'",
")",
":",
"module",
"=",
"wrapped",
".",
"__mo... | Wraps a test of other function and injects a Geist GUI which will
enable replay (set environment variable GEIST_REPLAY_MODE to 'record' to
active record mode. | [
"Wraps",
"a",
"test",
"of",
"other",
"function",
"and",
"injects",
"a",
"Geist",
"GUI",
"which",
"will",
"enable",
"replay",
"(",
"set",
"environment",
"variable",
"GEIST_REPLAY_MODE",
"to",
"record",
"to",
"active",
"record",
"mode",
"."
] | a1ef16d8b4c3777735008b671a50acfde3ce7bf1 | https://github.com/ten10solutions/Geist/blob/a1ef16d8b4c3777735008b671a50acfde3ce7bf1/geist/backends/replay.py#L51-L84 | train | 56,392 |
jkitzes/macroeco | macroeco/models/_distributions.py | _nbinom_ztrunc_p | def _nbinom_ztrunc_p(mu, k_agg):
""" Calculates p parameter for truncated negative binomial
Function given in Sampford 1955, equation 4
Note that omega = 1 / 1 + p in Sampford
"""
p_eq = lambda p, mu, k_agg: (k_agg * p) / (1 - (1 + p)**-k_agg) - mu
# The upper bound n... | python | def _nbinom_ztrunc_p(mu, k_agg):
""" Calculates p parameter for truncated negative binomial
Function given in Sampford 1955, equation 4
Note that omega = 1 / 1 + p in Sampford
"""
p_eq = lambda p, mu, k_agg: (k_agg * p) / (1 - (1 + p)**-k_agg) - mu
# The upper bound n... | [
"def",
"_nbinom_ztrunc_p",
"(",
"mu",
",",
"k_agg",
")",
":",
"p_eq",
"=",
"lambda",
"p",
",",
"mu",
",",
"k_agg",
":",
"(",
"k_agg",
"*",
"p",
")",
"/",
"(",
"1",
"-",
"(",
"1",
"+",
"p",
")",
"**",
"-",
"k_agg",
")",
"-",
"mu",
"# The upper... | Calculates p parameter for truncated negative binomial
Function given in Sampford 1955, equation 4
Note that omega = 1 / 1 + p in Sampford | [
"Calculates",
"p",
"parameter",
"for",
"truncated",
"negative",
"binomial"
] | ee5fac5560a2d64de3a64738b5bc6833e2d7ff2e | https://github.com/jkitzes/macroeco/blob/ee5fac5560a2d64de3a64738b5bc6833e2d7ff2e/macroeco/models/_distributions.py#L879-L892 | train | 56,393 |
jkitzes/macroeco | macroeco/models/_distributions.py | _ln_choose | def _ln_choose(n, k_agg):
'''
log binomial coefficient with extended gamma factorials. n and k_agg may be
int or array - if both array, must be the same length.
'''
gammaln = special.gammaln
return gammaln(n + 1) - (gammaln(k_agg + 1) + gammaln(n - k_agg + 1)) | python | def _ln_choose(n, k_agg):
'''
log binomial coefficient with extended gamma factorials. n and k_agg may be
int or array - if both array, must be the same length.
'''
gammaln = special.gammaln
return gammaln(n + 1) - (gammaln(k_agg + 1) + gammaln(n - k_agg + 1)) | [
"def",
"_ln_choose",
"(",
"n",
",",
"k_agg",
")",
":",
"gammaln",
"=",
"special",
".",
"gammaln",
"return",
"gammaln",
"(",
"n",
"+",
"1",
")",
"-",
"(",
"gammaln",
"(",
"k_agg",
"+",
"1",
")",
"+",
"gammaln",
"(",
"n",
"-",
"k_agg",
"+",
"1",
... | log binomial coefficient with extended gamma factorials. n and k_agg may be
int or array - if both array, must be the same length. | [
"log",
"binomial",
"coefficient",
"with",
"extended",
"gamma",
"factorials",
".",
"n",
"and",
"k_agg",
"may",
"be",
"int",
"or",
"array",
"-",
"if",
"both",
"array",
"must",
"be",
"the",
"same",
"length",
"."
] | ee5fac5560a2d64de3a64738b5bc6833e2d7ff2e | https://github.com/jkitzes/macroeco/blob/ee5fac5560a2d64de3a64738b5bc6833e2d7ff2e/macroeco/models/_distributions.py#L1023-L1030 | train | 56,394 |
jkitzes/macroeco | macroeco/models/_distributions.py | _solve_k_from_mu | def _solve_k_from_mu(data, k_array, nll, *args):
"""
For given args, return k_agg from searching some k_range.
Parameters
----------
data : array
k_range : array
nll : function
args :
Returns
--------
:float
Minimum k_agg
"""
# TODO: See if a root finder l... | python | def _solve_k_from_mu(data, k_array, nll, *args):
"""
For given args, return k_agg from searching some k_range.
Parameters
----------
data : array
k_range : array
nll : function
args :
Returns
--------
:float
Minimum k_agg
"""
# TODO: See if a root finder l... | [
"def",
"_solve_k_from_mu",
"(",
"data",
",",
"k_array",
",",
"nll",
",",
"*",
"args",
")",
":",
"# TODO: See if a root finder like fminbound would work with Decimal used in",
"# logpmf method (will this work with arrays?)",
"nll_array",
"=",
"np",
".",
"zeros",
"(",
"len",
... | For given args, return k_agg from searching some k_range.
Parameters
----------
data : array
k_range : array
nll : function
args :
Returns
--------
:float
Minimum k_agg | [
"For",
"given",
"args",
"return",
"k_agg",
"from",
"searching",
"some",
"k_range",
"."
] | ee5fac5560a2d64de3a64738b5bc6833e2d7ff2e | https://github.com/jkitzes/macroeco/blob/ee5fac5560a2d64de3a64738b5bc6833e2d7ff2e/macroeco/models/_distributions.py#L1033-L1061 | train | 56,395 |
jkitzes/macroeco | macroeco/models/_distributions.py | _expon_solve_lam_from_mu | def _expon_solve_lam_from_mu(mu, b):
"""
For the expon_uptrunc, given mu and b, return lam.
Similar to geom_uptrunc
"""
def lam_eq(lam, mu, b):
# Small offset added to denominator to avoid 0/0 erors
lam, mu, b = Decimal(lam), Decimal(mu), Decimal(b)
return ( (1 - (lam*b + 1)... | python | def _expon_solve_lam_from_mu(mu, b):
"""
For the expon_uptrunc, given mu and b, return lam.
Similar to geom_uptrunc
"""
def lam_eq(lam, mu, b):
# Small offset added to denominator to avoid 0/0 erors
lam, mu, b = Decimal(lam), Decimal(mu), Decimal(b)
return ( (1 - (lam*b + 1)... | [
"def",
"_expon_solve_lam_from_mu",
"(",
"mu",
",",
"b",
")",
":",
"def",
"lam_eq",
"(",
"lam",
",",
"mu",
",",
"b",
")",
":",
"# Small offset added to denominator to avoid 0/0 erors",
"lam",
",",
"mu",
",",
"b",
"=",
"Decimal",
"(",
"lam",
")",
",",
"Decim... | For the expon_uptrunc, given mu and b, return lam.
Similar to geom_uptrunc | [
"For",
"the",
"expon_uptrunc",
"given",
"mu",
"and",
"b",
"return",
"lam",
".",
"Similar",
"to",
"geom_uptrunc"
] | ee5fac5560a2d64de3a64738b5bc6833e2d7ff2e | https://github.com/jkitzes/macroeco/blob/ee5fac5560a2d64de3a64738b5bc6833e2d7ff2e/macroeco/models/_distributions.py#L1823-L1835 | train | 56,396 |
jkitzes/macroeco | macroeco/models/_distributions.py | _make_rank | def _make_rank(dist_obj, n, mu, sigma, crit=0.5, upper=10000, xtol=1):
"""
Make rank distribution using both ppf and brute force.
Setting crit = 1 is equivalent to just using the ppf
Parameters
----------
{0}
"""
qs = (np.arange(1, n + 1) - 0.5) / n
rank = np.empty(len(qs))
b... | python | def _make_rank(dist_obj, n, mu, sigma, crit=0.5, upper=10000, xtol=1):
"""
Make rank distribution using both ppf and brute force.
Setting crit = 1 is equivalent to just using the ppf
Parameters
----------
{0}
"""
qs = (np.arange(1, n + 1) - 0.5) / n
rank = np.empty(len(qs))
b... | [
"def",
"_make_rank",
"(",
"dist_obj",
",",
"n",
",",
"mu",
",",
"sigma",
",",
"crit",
"=",
"0.5",
",",
"upper",
"=",
"10000",
",",
"xtol",
"=",
"1",
")",
":",
"qs",
"=",
"(",
"np",
".",
"arange",
"(",
"1",
",",
"n",
"+",
"1",
")",
"-",
"0.5... | Make rank distribution using both ppf and brute force.
Setting crit = 1 is equivalent to just using the ppf
Parameters
----------
{0} | [
"Make",
"rank",
"distribution",
"using",
"both",
"ppf",
"and",
"brute",
"force",
"."
] | ee5fac5560a2d64de3a64738b5bc6833e2d7ff2e | https://github.com/jkitzes/macroeco/blob/ee5fac5560a2d64de3a64738b5bc6833e2d7ff2e/macroeco/models/_distributions.py#L1976-L2014 | train | 56,397 |
jkitzes/macroeco | macroeco/models/_distributions.py | _mean_var | def _mean_var(vals, pmf):
"""
Calculates the mean and variance from vals and pmf
Parameters
----------
vals : ndarray
Value range for a distribution
pmf : ndarray
pmf values corresponding with vals
Returns
-------
: tuple
(mean, variance)
"""
mean ... | python | def _mean_var(vals, pmf):
"""
Calculates the mean and variance from vals and pmf
Parameters
----------
vals : ndarray
Value range for a distribution
pmf : ndarray
pmf values corresponding with vals
Returns
-------
: tuple
(mean, variance)
"""
mean ... | [
"def",
"_mean_var",
"(",
"vals",
",",
"pmf",
")",
":",
"mean",
"=",
"np",
".",
"sum",
"(",
"vals",
"*",
"pmf",
")",
"var",
"=",
"np",
".",
"sum",
"(",
"vals",
"**",
"2",
"*",
"pmf",
")",
"-",
"mean",
"**",
"2",
"return",
"mean",
",",
"var"
] | Calculates the mean and variance from vals and pmf
Parameters
----------
vals : ndarray
Value range for a distribution
pmf : ndarray
pmf values corresponding with vals
Returns
-------
: tuple
(mean, variance) | [
"Calculates",
"the",
"mean",
"and",
"variance",
"from",
"vals",
"and",
"pmf"
] | ee5fac5560a2d64de3a64738b5bc6833e2d7ff2e | https://github.com/jkitzes/macroeco/blob/ee5fac5560a2d64de3a64738b5bc6833e2d7ff2e/macroeco/models/_distributions.py#L2017-L2037 | train | 56,398 |
jkitzes/macroeco | macroeco/models/_distributions.py | lognorm_gen._pdf_w_mean | def _pdf_w_mean(self, x, mean, sigma):
"""
Calculates the pdf of a lognormal distribution with parameters mean
and sigma
Parameters
----------
mean : float or ndarray
Mean of the lognormal distribution
sigma : float or ndarray
Sigma parame... | python | def _pdf_w_mean(self, x, mean, sigma):
"""
Calculates the pdf of a lognormal distribution with parameters mean
and sigma
Parameters
----------
mean : float or ndarray
Mean of the lognormal distribution
sigma : float or ndarray
Sigma parame... | [
"def",
"_pdf_w_mean",
"(",
"self",
",",
"x",
",",
"mean",
",",
"sigma",
")",
":",
"# Lognorm pmf with mean for optimization",
"mu",
",",
"sigma",
"=",
"self",
".",
"translate_args",
"(",
"mean",
",",
"sigma",
")",
"return",
"self",
".",
"logpdf",
"(",
"x",... | Calculates the pdf of a lognormal distribution with parameters mean
and sigma
Parameters
----------
mean : float or ndarray
Mean of the lognormal distribution
sigma : float or ndarray
Sigma parameter of the lognormal distribution
Returns
... | [
"Calculates",
"the",
"pdf",
"of",
"a",
"lognormal",
"distribution",
"with",
"parameters",
"mean",
"and",
"sigma"
] | ee5fac5560a2d64de3a64738b5bc6833e2d7ff2e | https://github.com/jkitzes/macroeco/blob/ee5fac5560a2d64de3a64738b5bc6833e2d7ff2e/macroeco/models/_distributions.py#L1935-L1955 | train | 56,399 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.