repository_name stringlengths 7 55 | func_path_in_repository stringlengths 4 223 | func_name stringlengths 1 134 | whole_func_string stringlengths 75 104k | language stringclasses 1
value | func_code_string stringlengths 75 104k | func_code_tokens listlengths 19 28.4k | func_documentation_string stringlengths 1 46.9k | func_documentation_tokens listlengths 1 1.97k | split_name stringclasses 1
value | func_code_url stringlengths 87 315 |
|---|---|---|---|---|---|---|---|---|---|---|
rosenbrockc/acorn | acorn/logging/decoration.py | _fqdn | def _fqdn(o, oset=True, recheck=False, pmodule=None):
"""Returns the fully qualified name of the object.
Args:
o (type): instance of the object's type.
oset (bool): when True, the fqdn will also be set on the object as attribute
`__fqdn__`.
recheck (bool): for sub-classes, som... | python | def _fqdn(o, oset=True, recheck=False, pmodule=None):
"""Returns the fully qualified name of the object.
Args:
o (type): instance of the object's type.
oset (bool): when True, the fqdn will also be set on the object as attribute
`__fqdn__`.
recheck (bool): for sub-classes, som... | [
"def",
"_fqdn",
"(",
"o",
",",
"oset",
"=",
"True",
",",
"recheck",
"=",
"False",
",",
"pmodule",
"=",
"None",
")",
":",
"if",
"id",
"(",
"o",
")",
"in",
"_set_failures",
"or",
"o",
"is",
"None",
":",
"return",
"None",
"if",
"recheck",
"or",
"not... | Returns the fully qualified name of the object.
Args:
o (type): instance of the object's type.
oset (bool): when True, the fqdn will also be set on the object as attribute
`__fqdn__`.
recheck (bool): for sub-classes, sometimes the super class has already had
its __fqdn__... | [
"Returns",
"the",
"fully",
"qualified",
"name",
"of",
"the",
"object",
"."
] | train | https://github.com/rosenbrockc/acorn/blob/9a44d1a1ad8bfc2c54a6b56d9efe54433a797820/acorn/logging/decoration.py#L1063-L1118 |
rosenbrockc/acorn | acorn/logging/decoration.py | _get_stack_depth | def _get_stack_depth(package, fqdn, defdepth=_def_stackdepth):
"""Loads the stack depth settings from the config file for the specified
package.
Args:
package (str): name of the package to get stack depth info for.
fqdn (str): fully qualified domain name of the member in the package.
... | python | def _get_stack_depth(package, fqdn, defdepth=_def_stackdepth):
"""Loads the stack depth settings from the config file for the specified
package.
Args:
package (str): name of the package to get stack depth info for.
fqdn (str): fully qualified domain name of the member in the package.
... | [
"def",
"_get_stack_depth",
"(",
"package",
",",
"fqdn",
",",
"defdepth",
"=",
"_def_stackdepth",
")",
":",
"global",
"_stack_config",
"if",
"package",
"not",
"in",
"_stack_config",
":",
"from",
"acorn",
".",
"config",
"import",
"settings",
"spack",
"=",
"setti... | Loads the stack depth settings from the config file for the specified
package.
Args:
package (str): name of the package to get stack depth info for.
fqdn (str): fully qualified domain name of the member in the package.
defdepth (int): default depth when one has not been configured. | [
"Loads",
"the",
"stack",
"depth",
"settings",
"from",
"the",
"config",
"file",
"for",
"the",
"specified",
"package",
"."
] | train | https://github.com/rosenbrockc/acorn/blob/9a44d1a1ad8bfc2c54a6b56d9efe54433a797820/acorn/logging/decoration.py#L1124-L1156 |
rosenbrockc/acorn | acorn/logging/decoration.py | decorate_obj | def decorate_obj(parent, n, o, otype, recurse=True, redecorate=False):
"""Adds the decoration for automated logging to the specified object, if it
hasn't already been done.
Args:
parent: object that `o` belongs to.
n (str): name in the parent's dictionary.
o (type): instance of the ... | python | def decorate_obj(parent, n, o, otype, recurse=True, redecorate=False):
"""Adds the decoration for automated logging to the specified object, if it
hasn't already been done.
Args:
parent: object that `o` belongs to.
n (str): name in the parent's dictionary.
o (type): instance of the ... | [
"def",
"decorate_obj",
"(",
"parent",
",",
"n",
",",
"o",
",",
"otype",
",",
"recurse",
"=",
"True",
",",
"redecorate",
"=",
"False",
")",
":",
"global",
"_decor_count",
",",
"_decorated_o",
"from",
"inspect",
"import",
"isclass",
",",
"isfunction",
",",
... | Adds the decoration for automated logging to the specified object, if it
hasn't already been done.
Args:
parent: object that `o` belongs to.
n (str): name in the parent's dictionary.
o (type): instance of the object's type.
otype (str): one of ['classes', 'functions', 'methods',... | [
"Adds",
"the",
"decoration",
"for",
"automated",
"logging",
"to",
"the",
"specified",
"object",
"if",
"it",
"hasn",
"t",
"already",
"been",
"done",
"."
] | train | https://github.com/rosenbrockc/acorn/blob/9a44d1a1ad8bfc2c54a6b56d9efe54433a797820/acorn/logging/decoration.py#L1170-L1272 |
rosenbrockc/acorn | acorn/logging/decoration.py | _load_subclasses | def _load_subclasses(package):
"""Loads the subclass settings for the specified package so that we can
decorate the classes correctly.
"""
global _explicit_subclasses
from acorn.config import settings
spack = settings(package)
if spack is not None:
if spack.has_section("subclass"):
... | python | def _load_subclasses(package):
"""Loads the subclass settings for the specified package so that we can
decorate the classes correctly.
"""
global _explicit_subclasses
from acorn.config import settings
spack = settings(package)
if spack is not None:
if spack.has_section("subclass"):
... | [
"def",
"_load_subclasses",
"(",
"package",
")",
":",
"global",
"_explicit_subclasses",
"from",
"acorn",
".",
"config",
"import",
"settings",
"spack",
"=",
"settings",
"(",
"package",
")",
"if",
"spack",
"is",
"not",
"None",
":",
"if",
"spack",
".",
"has_sect... | Loads the subclass settings for the specified package so that we can
decorate the classes correctly. | [
"Loads",
"the",
"subclass",
"settings",
"for",
"the",
"specified",
"package",
"so",
"that",
"we",
"can",
"decorate",
"the",
"classes",
"correctly",
"."
] | train | https://github.com/rosenbrockc/acorn/blob/9a44d1a1ad8bfc2c54a6b56d9efe54433a797820/acorn/logging/decoration.py#L1278-L1287 |
rosenbrockc/acorn | acorn/logging/decoration.py | _load_generic | def _load_generic(packname, package, section, target):
"""Loads the settings for generic options that take FQDN and a boolean value
(1 or 0).
Args:
packname (str): name of the package to get config settings for.
package: actual package object.
"""
from acorn.config import settings
... | python | def _load_generic(packname, package, section, target):
"""Loads the settings for generic options that take FQDN and a boolean value
(1 or 0).
Args:
packname (str): name of the package to get config settings for.
package: actual package object.
"""
from acorn.config import settings
... | [
"def",
"_load_generic",
"(",
"packname",
",",
"package",
",",
"section",
",",
"target",
")",
":",
"from",
"acorn",
".",
"config",
"import",
"settings",
"spack",
"=",
"settings",
"(",
"packname",
")",
"if",
"spack",
".",
"has_section",
"(",
"section",
")",
... | Loads the settings for generic options that take FQDN and a boolean value
(1 or 0).
Args:
packname (str): name of the package to get config settings for.
package: actual package object. | [
"Loads",
"the",
"settings",
"for",
"generic",
"options",
"that",
"take",
"FQDN",
"and",
"a",
"boolean",
"value",
"(",
"1",
"or",
"0",
")",
"."
] | train | https://github.com/rosenbrockc/acorn/blob/9a44d1a1ad8bfc2c54a6b56d9efe54433a797820/acorn/logging/decoration.py#L1289-L1302 |
rosenbrockc/acorn | acorn/logging/decoration.py | _load_callwraps | def _load_callwraps(packname, package):
"""Loads the special call wrapping settings for functions in the specified
package. This allows the result of the original method call to be cast as a
different type, or passed to a different constructor before returning from
the wrapped function.
Args:
... | python | def _load_callwraps(packname, package):
"""Loads the special call wrapping settings for functions in the specified
package. This allows the result of the original method call to be cast as a
different type, or passed to a different constructor before returning from
the wrapped function.
Args:
... | [
"def",
"_load_callwraps",
"(",
"packname",
",",
"package",
")",
":",
"global",
"_callwraps",
"from",
"acorn",
".",
"config",
"import",
"settings",
"from",
"acorn",
".",
"logging",
".",
"descriptors",
"import",
"_obj_getattr",
"spack",
"=",
"settings",
"(",
"pa... | Loads the special call wrapping settings for functions in the specified
package. This allows the result of the original method call to be cast as a
different type, or passed to a different constructor before returning from
the wrapped function.
Args:
packname (str): name of the package to get c... | [
"Loads",
"the",
"special",
"call",
"wrapping",
"settings",
"for",
"functions",
"in",
"the",
"specified",
"package",
".",
"This",
"allows",
"the",
"result",
"of",
"the",
"original",
"method",
"call",
"to",
"be",
"cast",
"as",
"a",
"different",
"type",
"or",
... | train | https://github.com/rosenbrockc/acorn/blob/9a44d1a1ad8bfc2c54a6b56d9efe54433a797820/acorn/logging/decoration.py#L1342-L1361 |
rosenbrockc/acorn | acorn/logging/decoration.py | decorate | def decorate(package):
"""Decorates all the methods in the specified package to have logging
enabled according to the configuration for the package.
"""
from os import sep
global _decor_count, _decorated_packs, _decorated_o, _pack_paths
global decorating
if "acorn" not in _decorated_packs:
... | python | def decorate(package):
"""Decorates all the methods in the specified package to have logging
enabled according to the configuration for the package.
"""
from os import sep
global _decor_count, _decorated_packs, _decorated_o, _pack_paths
global decorating
if "acorn" not in _decorated_packs:
... | [
"def",
"decorate",
"(",
"package",
")",
":",
"from",
"os",
"import",
"sep",
"global",
"_decor_count",
",",
"_decorated_packs",
",",
"_decorated_o",
",",
"_pack_paths",
"global",
"decorating",
"if",
"\"acorn\"",
"not",
"in",
"_decorated_packs",
":",
"_decorated_pac... | Decorates all the methods in the specified package to have logging
enabled according to the configuration for the package. | [
"Decorates",
"all",
"the",
"methods",
"in",
"the",
"specified",
"package",
"to",
"have",
"logging",
"enabled",
"according",
"to",
"the",
"configuration",
"for",
"the",
"package",
"."
] | train | https://github.com/rosenbrockc/acorn/blob/9a44d1a1ad8bfc2c54a6b56d9efe54433a797820/acorn/logging/decoration.py#L1375-L1417 |
rosenbrockc/acorn | acorn/logging/decoration.py | postfix | def postfix(package):
"""Makes sure that any additional imported names in the specified package
that were decorated in the context of a *different* package still get
redirected to the decorated objects.
Args:
package: package object to examine for compliance.
Examples:
When `scipy` is ... | python | def postfix(package):
"""Makes sure that any additional imported names in the specified package
that were decorated in the context of a *different* package still get
redirected to the decorated objects.
Args:
package: package object to examine for compliance.
Examples:
When `scipy` is ... | [
"def",
"postfix",
"(",
"package",
")",
":",
"#This time we don't have to go recursively; we can just look at top-level",
"#objects in the package.",
"global",
"decorating",
"origdecor",
"=",
"decorating",
"decorating",
"=",
"True",
"packsplit",
"=",
"_split_object",
"(",
"pac... | Makes sure that any additional imported names in the specified package
that were decorated in the context of a *different* package still get
redirected to the decorated objects.
Args:
package: package object to examine for compliance.
Examples:
When `scipy` is imported, it imports most of ... | [
"Makes",
"sure",
"that",
"any",
"additional",
"imported",
"names",
"in",
"the",
"specified",
"package",
"that",
"were",
"decorated",
"in",
"the",
"context",
"of",
"a",
"*",
"different",
"*",
"package",
"still",
"get",
"redirected",
"to",
"the",
"decorated",
... | train | https://github.com/rosenbrockc/acorn/blob/9a44d1a1ad8bfc2c54a6b56d9efe54433a797820/acorn/logging/decoration.py#L1419-L1479 |
minorg/pastpy | py/src/pastpy/gen/database/impl/dummy/dummy_database_configuration.py | DummyDatabaseConfiguration.read | def read(cls, iprot):
'''
Read a new object from the given input protocol and return the object.
:type iprot: thryft.protocol._input_protocol._InputProtocol
:rtype: pastpy.gen.database.impl.dummy.dummy_database_configuration.DummyDatabaseConfiguration
'''
init_kwds = {}... | python | def read(cls, iprot):
'''
Read a new object from the given input protocol and return the object.
:type iprot: thryft.protocol._input_protocol._InputProtocol
:rtype: pastpy.gen.database.impl.dummy.dummy_database_configuration.DummyDatabaseConfiguration
'''
init_kwds = {}... | [
"def",
"read",
"(",
"cls",
",",
"iprot",
")",
":",
"init_kwds",
"=",
"{",
"}",
"iprot",
".",
"read_struct_begin",
"(",
")",
"while",
"True",
":",
"ifield_name",
",",
"ifield_type",
",",
"_ifield_id",
"=",
"iprot",
".",
"read_field_begin",
"(",
")",
"if",... | Read a new object from the given input protocol and return the object.
:type iprot: thryft.protocol._input_protocol._InputProtocol
:rtype: pastpy.gen.database.impl.dummy.dummy_database_configuration.DummyDatabaseConfiguration | [
"Read",
"a",
"new",
"object",
"from",
"the",
"given",
"input",
"protocol",
"and",
"return",
"the",
"object",
"."
] | train | https://github.com/minorg/pastpy/blob/7d5d6d511629481850216565e7451b5dcb8027a9/py/src/pastpy/gen/database/impl/dummy/dummy_database_configuration.py#L184-L206 |
minorg/pastpy | py/src/pastpy/gen/database/impl/dummy/dummy_database_configuration.py | DummyDatabaseConfiguration.write | def write(self, oprot):
'''
Write this object to the given output protocol and return self.
:type oprot: thryft.protocol._output_protocol._OutputProtocol
:rtype: pastpy.gen.database.impl.dummy.dummy_database_configuration.DummyDatabaseConfiguration
'''
oprot.write_struc... | python | def write(self, oprot):
'''
Write this object to the given output protocol and return self.
:type oprot: thryft.protocol._output_protocol._OutputProtocol
:rtype: pastpy.gen.database.impl.dummy.dummy_database_configuration.DummyDatabaseConfiguration
'''
oprot.write_struc... | [
"def",
"write",
"(",
"self",
",",
"oprot",
")",
":",
"oprot",
".",
"write_struct_begin",
"(",
"'DummyDatabaseConfiguration'",
")",
"oprot",
".",
"write_field_begin",
"(",
"name",
"=",
"'images_per_object'",
",",
"type",
"=",
"8",
",",
"id",
"=",
"None",
")",... | Write this object to the given output protocol and return self.
:type oprot: thryft.protocol._output_protocol._OutputProtocol
:rtype: pastpy.gen.database.impl.dummy.dummy_database_configuration.DummyDatabaseConfiguration | [
"Write",
"this",
"object",
"to",
"the",
"given",
"output",
"protocol",
"and",
"return",
"self",
"."
] | train | https://github.com/minorg/pastpy/blob/7d5d6d511629481850216565e7451b5dcb8027a9/py/src/pastpy/gen/database/impl/dummy/dummy_database_configuration.py#L217-L239 |
csvsoundsystem/pytreasuryio | treasuryio/query.py | query | def query(sql, format='df'):
'''
Submit an `sql` query (string) to treasury.io and return a pandas DataFrame.
For example::
print('Operating cash balances for May 22, 2013')
print(treasuryio.query('SELECT * FROM "t1" WHERE "date" = \'2013-05-22\';'))
Return a dict::
treasuryi... | python | def query(sql, format='df'):
'''
Submit an `sql` query (string) to treasury.io and return a pandas DataFrame.
For example::
print('Operating cash balances for May 22, 2013')
print(treasuryio.query('SELECT * FROM "t1" WHERE "date" = \'2013-05-22\';'))
Return a dict::
treasuryi... | [
"def",
"query",
"(",
"sql",
",",
"format",
"=",
"'df'",
")",
":",
"url",
"=",
"'http://api.treasury.io/cc7znvq/47d80ae900e04f2/sql/'",
"query_string",
"=",
"urlencode",
"(",
"{",
"'q'",
":",
"sql",
"}",
")",
"handle",
"=",
"urlopen",
"(",
"url",
"+",
"'?'",
... | Submit an `sql` query (string) to treasury.io and return a pandas DataFrame.
For example::
print('Operating cash balances for May 22, 2013')
print(treasuryio.query('SELECT * FROM "t1" WHERE "date" = \'2013-05-22\';'))
Return a dict::
treasuryio.query('SELECT * FROM "t1" WHERE "date" ... | [
"Submit",
"an",
"sql",
"query",
"(",
"string",
")",
"to",
"treasury",
".",
"io",
"and",
"return",
"a",
"pandas",
"DataFrame",
"."
] | train | https://github.com/csvsoundsystem/pytreasuryio/blob/728caf815d16cd2f3548d8b67c84313de76f9be7/treasuryio/query.py#L7-L33 |
twidi/py-dataql | dataql/parsers/mixins.py | NamedArgsParserMixin.visit_named_arg | def visit_named_arg(self, _, children):
"""Named argument of a filter.
Arguments
---------
_ (node) : parsimonious.nodes.Node.
children : list
- 0: name of the arg
- 1: for ``WS`` (whitespace): ``None``.
- 2: operator
- 3: for ``WS... | python | def visit_named_arg(self, _, children):
"""Named argument of a filter.
Arguments
---------
_ (node) : parsimonious.nodes.Node.
children : list
- 0: name of the arg
- 1: for ``WS`` (whitespace): ``None``.
- 2: operator
- 3: for ``WS... | [
"def",
"visit_named_arg",
"(",
"self",
",",
"_",
",",
"children",
")",
":",
"return",
"self",
".",
"NamedArg",
"(",
"arg",
"=",
"children",
"[",
"0",
"]",
",",
"arg_type",
"=",
"children",
"[",
"2",
"]",
",",
"value",
"=",
"children",
"[",
"4",
"]"... | Named argument of a filter.
Arguments
---------
_ (node) : parsimonious.nodes.Node.
children : list
- 0: name of the arg
- 1: for ``WS`` (whitespace): ``None``.
- 2: operator
- 3: for ``WS`` (whitespace): ``None``.
- 4: value o... | [
"Named",
"argument",
"of",
"a",
"filter",
"."
] | train | https://github.com/twidi/py-dataql/blob/5841a3fd559829193ed709c255166085bdde1c52/dataql/parsers/mixins.py#L179-L217 |
twidi/py-dataql | dataql/parsers/mixins.py | FiltersParserMixin.visit_filter | def visit_filter(self, _, children):
"""A filter, with optional arguments.
Arguments
---------
_ (node) : parsimonious.nodes.Node.
children : list
- 0: string, name of the filter.
- 1: list of instances of ``.resources.NamedArg``
Returns
... | python | def visit_filter(self, _, children):
"""A filter, with optional arguments.
Arguments
---------
_ (node) : parsimonious.nodes.Node.
children : list
- 0: string, name of the filter.
- 1: list of instances of ``.resources.NamedArg``
Returns
... | [
"def",
"visit_filter",
"(",
"self",
",",
"_",
",",
"children",
")",
":",
"return",
"self",
".",
"Filter",
"(",
"name",
"=",
"children",
"[",
"0",
"]",
",",
"args",
"=",
"children",
"[",
"1",
"]",
",",
")"
] | A filter, with optional arguments.
Arguments
---------
_ (node) : parsimonious.nodes.Node.
children : list
- 0: string, name of the filter.
- 1: list of instances of ``.resources.NamedArg``
Returns
-------
.resources.Filter
An... | [
"A",
"filter",
"with",
"optional",
"arguments",
"."
] | train | https://github.com/twidi/py-dataql/blob/5841a3fd559829193ed709c255166085bdde1c52/dataql/parsers/mixins.py#L855-L888 |
kmedian/kfactor | kfactor/kfactor_func.py | kfactor | def kfactor(R, k=2, algorithm='COBYLA'):
"""k-Factor Nearest Correlation Matrix Fit
Parameters:
-----------
R : ndarray
an illconditioned <d x d> correlation matrix,
e.g. oxyba.illcond_corrmat
k : int
Number of factors (Default: 2)
algorithm : str
'COBYLA' (Def... | python | def kfactor(R, k=2, algorithm='COBYLA'):
"""k-Factor Nearest Correlation Matrix Fit
Parameters:
-----------
R : ndarray
an illconditioned <d x d> correlation matrix,
e.g. oxyba.illcond_corrmat
k : int
Number of factors (Default: 2)
algorithm : str
'COBYLA' (Def... | [
"def",
"kfactor",
"(",
"R",
",",
"k",
"=",
"2",
",",
"algorithm",
"=",
"'COBYLA'",
")",
":",
"# subfunctions",
"def",
"corradjusteigen",
"(",
"C",
")",
":",
"\"\"\"Reset negative diagonal elements 'D' to +1e-308\n This trick ensures that C semipositive definite.\... | k-Factor Nearest Correlation Matrix Fit
Parameters:
-----------
R : ndarray
an illconditioned <d x d> correlation matrix,
e.g. oxyba.illcond_corrmat
k : int
Number of factors (Default: 2)
algorithm : str
'COBYLA' (Default) or 'SLSQP'.
Use 'COBYLA' because i... | [
"k",
"-",
"Factor",
"Nearest",
"Correlation",
"Matrix",
"Fit"
] | train | https://github.com/kmedian/kfactor/blob/812daab3d9bbd3c06e223601085e8ec40aeeceba/kfactor/kfactor_func.py#L6-L145 |
jmoiron/gaspar | gaspar/producers.py | Producer.setup_zmq | def setup_zmq(self):
"""Set up a PUSH and a PULL socket. The PUSH socket will push out
requests to the workers. The PULL socket will receive responses from
the workers and reply through the server socket."""
self.context = zmq.Context()
self.push = self.context.socket(zmq.PUSH)... | python | def setup_zmq(self):
"""Set up a PUSH and a PULL socket. The PUSH socket will push out
requests to the workers. The PULL socket will receive responses from
the workers and reply through the server socket."""
self.context = zmq.Context()
self.push = self.context.socket(zmq.PUSH)... | [
"def",
"setup_zmq",
"(",
"self",
")",
":",
"self",
".",
"context",
"=",
"zmq",
".",
"Context",
"(",
")",
"self",
".",
"push",
"=",
"self",
".",
"context",
".",
"socket",
"(",
"zmq",
".",
"PUSH",
")",
"self",
".",
"push_port",
"=",
"self",
".",
"p... | Set up a PUSH and a PULL socket. The PUSH socket will push out
requests to the workers. The PULL socket will receive responses from
the workers and reply through the server socket. | [
"Set",
"up",
"a",
"PUSH",
"and",
"a",
"PULL",
"socket",
".",
"The",
"PUSH",
"socket",
"will",
"push",
"out",
"requests",
"to",
"the",
"workers",
".",
"The",
"PULL",
"socket",
"will",
"receive",
"responses",
"from",
"the",
"workers",
"and",
"reply",
"thro... | train | https://github.com/jmoiron/gaspar/blob/cc9d7403a4d86382b10a7e96c6d0a020cc5e1b12/gaspar/producers.py#L50-L59 |
jmoiron/gaspar | gaspar/producers.py | Producer.start | def start(self, blocking=True):
"""Start the producer. This will eventually fire the ``server_start``
and ``running`` events in sequence, which signify that the incoming
TCP request socket is running and the workers have been forked,
respectively. If ``blocking`` is False, control ."""... | python | def start(self, blocking=True):
"""Start the producer. This will eventually fire the ``server_start``
and ``running`` events in sequence, which signify that the incoming
TCP request socket is running and the workers have been forked,
respectively. If ``blocking`` is False, control ."""... | [
"def",
"start",
"(",
"self",
",",
"blocking",
"=",
"True",
")",
":",
"self",
".",
"setup_zmq",
"(",
")",
"if",
"blocking",
":",
"self",
".",
"serve",
"(",
")",
"else",
":",
"eventlet",
".",
"spawn",
"(",
"self",
".",
"serve",
")",
"# ensure that self... | Start the producer. This will eventually fire the ``server_start``
and ``running`` events in sequence, which signify that the incoming
TCP request socket is running and the workers have been forked,
respectively. If ``blocking`` is False, control . | [
"Start",
"the",
"producer",
".",
"This",
"will",
"eventually",
"fire",
"the",
"server_start",
"and",
"running",
"events",
"in",
"sequence",
"which",
"signify",
"that",
"the",
"incoming",
"TCP",
"request",
"socket",
"is",
"running",
"and",
"the",
"workers",
"ha... | train | https://github.com/jmoiron/gaspar/blob/cc9d7403a4d86382b10a7e96c6d0a020cc5e1b12/gaspar/producers.py#L93-L105 |
emory-libraries/eulcommon | eulcommon/djangoextras/taskresult/models.py | TaskResult.status_icon | def status_icon(self):
'glyphicon for task status; requires bootstrap'
icon = self.status_icon_map.get(self.status.lower(),
self.unknown_icon)
style = self.status_style.get(self.status.lower(), '')
return mark_safe(
'<span class="glyphi... | python | def status_icon(self):
'glyphicon for task status; requires bootstrap'
icon = self.status_icon_map.get(self.status.lower(),
self.unknown_icon)
style = self.status_style.get(self.status.lower(), '')
return mark_safe(
'<span class="glyphi... | [
"def",
"status_icon",
"(",
"self",
")",
":",
"icon",
"=",
"self",
".",
"status_icon_map",
".",
"get",
"(",
"self",
".",
"status",
".",
"lower",
"(",
")",
",",
"self",
".",
"unknown_icon",
")",
"style",
"=",
"self",
".",
"status_style",
".",
"get",
"(... | glyphicon for task status; requires bootstrap | [
"glyphicon",
"for",
"task",
"status",
";",
"requires",
"bootstrap"
] | train | https://github.com/emory-libraries/eulcommon/blob/dc63a9b3b5e38205178235e0d716d1b28158d3a9/eulcommon/djangoextras/taskresult/models.py#L76-L83 |
pip-services3-python/pip-services3-components-python | pip_services3_components/count/CompositeCounters.py | CompositeCounters.set_references | def set_references(self, references):
"""
Sets references to dependent components.
:param references: references to locate the component dependencies.
"""
descriptor = Descriptor(None, "counters", None, None, None)
counters = references.get_optional(descriptor)
f... | python | def set_references(self, references):
"""
Sets references to dependent components.
:param references: references to locate the component dependencies.
"""
descriptor = Descriptor(None, "counters", None, None, None)
counters = references.get_optional(descriptor)
f... | [
"def",
"set_references",
"(",
"self",
",",
"references",
")",
":",
"descriptor",
"=",
"Descriptor",
"(",
"None",
",",
"\"counters\"",
",",
"None",
",",
"None",
",",
"None",
")",
"counters",
"=",
"references",
".",
"get_optional",
"(",
"descriptor",
")",
"f... | Sets references to dependent components.
:param references: references to locate the component dependencies. | [
"Sets",
"references",
"to",
"dependent",
"components",
"."
] | train | https://github.com/pip-services3-python/pip-services3-components-python/blob/1de9c1bb544cf1891111e9a5f5d67653f62c9b52/pip_services3_components/count/CompositeCounters.py#L55-L65 |
pip-services3-python/pip-services3-components-python | pip_services3_components/count/CompositeCounters.py | CompositeCounters.end_timing | def end_timing(self, name, elapsed):
"""
Ends measurement of execution elapsed time and updates specified counter.
:param name: a counter name
:param elapsed: execution elapsed time in milliseconds to update the counter.
"""
for counter in self._counters:
if... | python | def end_timing(self, name, elapsed):
"""
Ends measurement of execution elapsed time and updates specified counter.
:param name: a counter name
:param elapsed: execution elapsed time in milliseconds to update the counter.
"""
for counter in self._counters:
if... | [
"def",
"end_timing",
"(",
"self",
",",
"name",
",",
"elapsed",
")",
":",
"for",
"counter",
"in",
"self",
".",
"_counters",
":",
"if",
"isinstance",
"(",
"counter",
",",
"ITimingCallback",
")",
":",
"counter",
".",
"end_timing",
"(",
"name",
",",
"elapsed... | Ends measurement of execution elapsed time and updates specified counter.
:param name: a counter name
:param elapsed: execution elapsed time in milliseconds to update the counter. | [
"Ends",
"measurement",
"of",
"execution",
"elapsed",
"time",
"and",
"updates",
"specified",
"counter",
"."
] | train | https://github.com/pip-services3-python/pip-services3-components-python/blob/1de9c1bb544cf1891111e9a5f5d67653f62c9b52/pip_services3_components/count/CompositeCounters.py#L79-L89 |
pip-services3-python/pip-services3-components-python | pip_services3_components/count/CompositeCounters.py | CompositeCounters.stats | def stats(self, name, value):
"""
Calculates min/average/max statistics based on the current and previous values.
:param name: a counter name of Statistics type
:param value: a value to update statistics
"""
for counter in self._counters:
counter.stats(name,... | python | def stats(self, name, value):
"""
Calculates min/average/max statistics based on the current and previous values.
:param name: a counter name of Statistics type
:param value: a value to update statistics
"""
for counter in self._counters:
counter.stats(name,... | [
"def",
"stats",
"(",
"self",
",",
"name",
",",
"value",
")",
":",
"for",
"counter",
"in",
"self",
".",
"_counters",
":",
"counter",
".",
"stats",
"(",
"name",
",",
"value",
")"
] | Calculates min/average/max statistics based on the current and previous values.
:param name: a counter name of Statistics type
:param value: a value to update statistics | [
"Calculates",
"min",
"/",
"average",
"/",
"max",
"statistics",
"based",
"on",
"the",
"current",
"and",
"previous",
"values",
"."
] | train | https://github.com/pip-services3-python/pip-services3-components-python/blob/1de9c1bb544cf1891111e9a5f5d67653f62c9b52/pip_services3_components/count/CompositeCounters.py#L91-L100 |
pip-services3-python/pip-services3-components-python | pip_services3_components/count/CompositeCounters.py | CompositeCounters.last | def last(self, name, value):
"""
Records the last calculated measurement value.
Usually this method is used by metrics calculated externally.
:param name: a counter name of Last type.
:param value: a last value to record.
"""
for counter in self._counters:
... | python | def last(self, name, value):
"""
Records the last calculated measurement value.
Usually this method is used by metrics calculated externally.
:param name: a counter name of Last type.
:param value: a last value to record.
"""
for counter in self._counters:
... | [
"def",
"last",
"(",
"self",
",",
"name",
",",
"value",
")",
":",
"for",
"counter",
"in",
"self",
".",
"_counters",
":",
"counter",
".",
"last",
"(",
"name",
",",
"value",
")"
] | Records the last calculated measurement value.
Usually this method is used by metrics calculated externally.
:param name: a counter name of Last type.
:param value: a last value to record. | [
"Records",
"the",
"last",
"calculated",
"measurement",
"value",
".",
"Usually",
"this",
"method",
"is",
"used",
"by",
"metrics",
"calculated",
"externally",
"."
] | train | https://github.com/pip-services3-python/pip-services3-components-python/blob/1de9c1bb544cf1891111e9a5f5d67653f62c9b52/pip_services3_components/count/CompositeCounters.py#L102-L112 |
pip-services3-python/pip-services3-components-python | pip_services3_components/count/CompositeCounters.py | CompositeCounters.timestamp | def timestamp(self, name, value):
"""
Records the given timestamp.
:param name: a counter name of Timestamp type.
:param value: a timestamp to record.
"""
for counter in self._counters:
counter.timestamp(name, value) | python | def timestamp(self, name, value):
"""
Records the given timestamp.
:param name: a counter name of Timestamp type.
:param value: a timestamp to record.
"""
for counter in self._counters:
counter.timestamp(name, value) | [
"def",
"timestamp",
"(",
"self",
",",
"name",
",",
"value",
")",
":",
"for",
"counter",
"in",
"self",
".",
"_counters",
":",
"counter",
".",
"timestamp",
"(",
"name",
",",
"value",
")"
] | Records the given timestamp.
:param name: a counter name of Timestamp type.
:param value: a timestamp to record. | [
"Records",
"the",
"given",
"timestamp",
"."
] | train | https://github.com/pip-services3-python/pip-services3-components-python/blob/1de9c1bb544cf1891111e9a5f5d67653f62c9b52/pip_services3_components/count/CompositeCounters.py#L123-L132 |
pip-services3-python/pip-services3-components-python | pip_services3_components/count/CompositeCounters.py | CompositeCounters.increment | def increment(self, name, value):
"""
Increments counter by given value.
:param name: a counter name of Increment type.
:param value: a value to add to the counter.
"""
for counter in self._counters:
counter.increment(name, value) | python | def increment(self, name, value):
"""
Increments counter by given value.
:param name: a counter name of Increment type.
:param value: a value to add to the counter.
"""
for counter in self._counters:
counter.increment(name, value) | [
"def",
"increment",
"(",
"self",
",",
"name",
",",
"value",
")",
":",
"for",
"counter",
"in",
"self",
".",
"_counters",
":",
"counter",
".",
"increment",
"(",
"name",
",",
"value",
")"
] | Increments counter by given value.
:param name: a counter name of Increment type.
:param value: a value to add to the counter. | [
"Increments",
"counter",
"by",
"given",
"value",
"."
] | train | https://github.com/pip-services3-python/pip-services3-components-python/blob/1de9c1bb544cf1891111e9a5f5d67653f62c9b52/pip_services3_components/count/CompositeCounters.py#L143-L152 |
ronaldguillen/wave | wave/utils/formatting.py | remove_trailing_string | def remove_trailing_string(content, trailing):
"""
Strip trailing component `trailing` from `content` if it exists.
Used when generating names from view classes.
"""
if content.endswith(trailing) and content != trailing:
return content[:-len(trailing)]
return content | python | def remove_trailing_string(content, trailing):
"""
Strip trailing component `trailing` from `content` if it exists.
Used when generating names from view classes.
"""
if content.endswith(trailing) and content != trailing:
return content[:-len(trailing)]
return content | [
"def",
"remove_trailing_string",
"(",
"content",
",",
"trailing",
")",
":",
"if",
"content",
".",
"endswith",
"(",
"trailing",
")",
"and",
"content",
"!=",
"trailing",
":",
"return",
"content",
"[",
":",
"-",
"len",
"(",
"trailing",
")",
"]",
"return",
"... | Strip trailing component `trailing` from `content` if it exists.
Used when generating names from view classes. | [
"Strip",
"trailing",
"component",
"trailing",
"from",
"content",
"if",
"it",
"exists",
".",
"Used",
"when",
"generating",
"names",
"from",
"view",
"classes",
"."
] | train | https://github.com/ronaldguillen/wave/blob/20bb979c917f7634d8257992e6d449dc751256a9/wave/utils/formatting.py#L15-L22 |
ronaldguillen/wave | wave/utils/formatting.py | dedent | def dedent(content):
"""
Remove leading indent from a block of text.
Used when generating descriptions from docstrings.
Note that python's `textwrap.dedent` doesn't quite cut it,
as it fails to dedent multiline docstrings that include
unindented text on the initial line.
"""
content = f... | python | def dedent(content):
"""
Remove leading indent from a block of text.
Used when generating descriptions from docstrings.
Note that python's `textwrap.dedent` doesn't quite cut it,
as it fails to dedent multiline docstrings that include
unindented text on the initial line.
"""
content = f... | [
"def",
"dedent",
"(",
"content",
")",
":",
"content",
"=",
"force_text",
"(",
"content",
")",
"whitespace_counts",
"=",
"[",
"len",
"(",
"line",
")",
"-",
"len",
"(",
"line",
".",
"lstrip",
"(",
"' '",
")",
")",
"for",
"line",
"in",
"content",
".",
... | Remove leading indent from a block of text.
Used when generating descriptions from docstrings.
Note that python's `textwrap.dedent` doesn't quite cut it,
as it fails to dedent multiline docstrings that include
unindented text on the initial line. | [
"Remove",
"leading",
"indent",
"from",
"a",
"block",
"of",
"text",
".",
"Used",
"when",
"generating",
"descriptions",
"from",
"docstrings",
"."
] | train | https://github.com/ronaldguillen/wave/blob/20bb979c917f7634d8257992e6d449dc751256a9/wave/utils/formatting.py#L25-L43 |
ronaldguillen/wave | wave/utils/formatting.py | camelcase_to_spaces | def camelcase_to_spaces(content):
"""
Translate 'CamelCaseNames' to 'Camel Case Names'.
Used when generating names from view classes.
"""
camelcase_boundry = '(((?<=[a-z])[A-Z])|([A-Z](?![A-Z]|$)))'
content = re.sub(camelcase_boundry, ' \\1', content).strip()
return ' '.join(content.split('_... | python | def camelcase_to_spaces(content):
"""
Translate 'CamelCaseNames' to 'Camel Case Names'.
Used when generating names from view classes.
"""
camelcase_boundry = '(((?<=[a-z])[A-Z])|([A-Z](?![A-Z]|$)))'
content = re.sub(camelcase_boundry, ' \\1', content).strip()
return ' '.join(content.split('_... | [
"def",
"camelcase_to_spaces",
"(",
"content",
")",
":",
"camelcase_boundry",
"=",
"'(((?<=[a-z])[A-Z])|([A-Z](?![A-Z]|$)))'",
"content",
"=",
"re",
".",
"sub",
"(",
"camelcase_boundry",
",",
"' \\\\1'",
",",
"content",
")",
".",
"strip",
"(",
")",
"return",
"' '",... | Translate 'CamelCaseNames' to 'Camel Case Names'.
Used when generating names from view classes. | [
"Translate",
"CamelCaseNames",
"to",
"Camel",
"Case",
"Names",
".",
"Used",
"when",
"generating",
"names",
"from",
"view",
"classes",
"."
] | train | https://github.com/ronaldguillen/wave/blob/20bb979c917f7634d8257992e6d449dc751256a9/wave/utils/formatting.py#L46-L53 |
ronaldguillen/wave | wave/utils/formatting.py | markup_description | def markup_description(description):
"""
Apply HTML markup to the given description.
"""
if apply_markdown:
description = apply_markdown(description)
else:
description = escape(description).replace('\n', '<br />')
description = '<p>' + description + '</p>'
return mark_saf... | python | def markup_description(description):
"""
Apply HTML markup to the given description.
"""
if apply_markdown:
description = apply_markdown(description)
else:
description = escape(description).replace('\n', '<br />')
description = '<p>' + description + '</p>'
return mark_saf... | [
"def",
"markup_description",
"(",
"description",
")",
":",
"if",
"apply_markdown",
":",
"description",
"=",
"apply_markdown",
"(",
"description",
")",
"else",
":",
"description",
"=",
"escape",
"(",
"description",
")",
".",
"replace",
"(",
"'\\n'",
",",
"'<br ... | Apply HTML markup to the given description. | [
"Apply",
"HTML",
"markup",
"to",
"the",
"given",
"description",
"."
] | train | https://github.com/ronaldguillen/wave/blob/20bb979c917f7634d8257992e6d449dc751256a9/wave/utils/formatting.py#L56-L65 |
limpyd/redis-limpyd-jobs | limpyd_jobs/utils.py | get_delta | def get_delta(value):
"""
Return a timedelta object based on the value which can be a timedelta
or a number of seconds (int or float).
Raise an exception in all other cases.
"""
if isinstance(value, (int, float)):
return timedelta(seconds=value)
elif isinstance(value, timedelta):
... | python | def get_delta(value):
"""
Return a timedelta object based on the value which can be a timedelta
or a number of seconds (int or float).
Raise an exception in all other cases.
"""
if isinstance(value, (int, float)):
return timedelta(seconds=value)
elif isinstance(value, timedelta):
... | [
"def",
"get_delta",
"(",
"value",
")",
":",
"if",
"isinstance",
"(",
"value",
",",
"(",
"int",
",",
"float",
")",
")",
":",
"return",
"timedelta",
"(",
"seconds",
"=",
"value",
")",
"elif",
"isinstance",
"(",
"value",
",",
"timedelta",
")",
":",
"ret... | Return a timedelta object based on the value which can be a timedelta
or a number of seconds (int or float).
Raise an exception in all other cases. | [
"Return",
"a",
"timedelta",
"object",
"based",
"on",
"the",
"value",
"which",
"can",
"be",
"a",
"timedelta",
"or",
"a",
"number",
"of",
"seconds",
"(",
"int",
"or",
"float",
")",
".",
"Raise",
"an",
"exception",
"in",
"all",
"other",
"cases",
"."
] | train | https://github.com/limpyd/redis-limpyd-jobs/blob/264c71029bad4377d6132bf8bb9c55c44f3b03a2/limpyd_jobs/utils.py#L17-L27 |
limpyd/redis-limpyd-jobs | limpyd_jobs/utils.py | compute_delayed_until | def compute_delayed_until(delayed_for=None, delayed_until=None):
"""
Return a datetime object based on either the `delayed_for` argument
(int/float/timedelta), which wille be added to the current datetime
(`datetime.utcnow`), or the `delayed_until` one which must be a
datetime object.
Raise a `V... | python | def compute_delayed_until(delayed_for=None, delayed_until=None):
"""
Return a datetime object based on either the `delayed_for` argument
(int/float/timedelta), which wille be added to the current datetime
(`datetime.utcnow`), or the `delayed_until` one which must be a
datetime object.
Raise a `V... | [
"def",
"compute_delayed_until",
"(",
"delayed_for",
"=",
"None",
",",
"delayed_until",
"=",
"None",
")",
":",
"if",
"delayed_until",
":",
"if",
"delayed_for",
":",
"raise",
"ValueError",
"(",
"'delayed_until and delayed_for arguments are exclusive'",
")",
"if",
"not",... | Return a datetime object based on either the `delayed_for` argument
(int/float/timedelta), which wille be added to the current datetime
(`datetime.utcnow`), or the `delayed_until` one which must be a
datetime object.
Raise a `ValueError` exception if both are set, or a invalid type is
used.
Retu... | [
"Return",
"a",
"datetime",
"object",
"based",
"on",
"either",
"the",
"delayed_for",
"argument",
"(",
"int",
"/",
"float",
"/",
"timedelta",
")",
"which",
"wille",
"be",
"added",
"to",
"the",
"current",
"datetime",
"(",
"datetime",
".",
"utcnow",
")",
"or",... | train | https://github.com/limpyd/redis-limpyd-jobs/blob/264c71029bad4377d6132bf8bb9c55c44f3b03a2/limpyd_jobs/utils.py#L30-L52 |
limpyd/redis-limpyd-jobs | limpyd_jobs/utils.py | import_class | def import_class(class_uri):
"""
Import a class by string 'from.path.module.class'
"""
parts = class_uri.split('.')
class_name = parts.pop()
module_uri = '.'.join(parts)
try:
module = import_module(module_uri)
except ImportError as e:
# maybe we are still in a module, t... | python | def import_class(class_uri):
"""
Import a class by string 'from.path.module.class'
"""
parts = class_uri.split('.')
class_name = parts.pop()
module_uri = '.'.join(parts)
try:
module = import_module(module_uri)
except ImportError as e:
# maybe we are still in a module, t... | [
"def",
"import_class",
"(",
"class_uri",
")",
":",
"parts",
"=",
"class_uri",
".",
"split",
"(",
"'.'",
")",
"class_name",
"=",
"parts",
".",
"pop",
"(",
")",
"module_uri",
"=",
"'.'",
".",
"join",
"(",
"parts",
")",
"try",
":",
"module",
"=",
"impor... | Import a class by string 'from.path.module.class' | [
"Import",
"a",
"class",
"by",
"string",
"from",
".",
"path",
".",
"module",
".",
"class"
] | train | https://github.com/limpyd/redis-limpyd-jobs/blob/264c71029bad4377d6132bf8bb9c55c44f3b03a2/limpyd_jobs/utils.py#L55-L74 |
SeabornGames/Meta | seaborn_meta/class_name.py | class_name_to_instant_name | def class_name_to_instant_name(name):
""" This will convert from 'ParentName_ChildName' to
'parent_name.child_name' """
name = name.replace('/', '_')
ret = name[0].lower()
for i in range(1, len(name)):
if name[i] == '_':
ret += '.'
elif '9' < name[i] < 'a' and name[i - 1]... | python | def class_name_to_instant_name(name):
""" This will convert from 'ParentName_ChildName' to
'parent_name.child_name' """
name = name.replace('/', '_')
ret = name[0].lower()
for i in range(1, len(name)):
if name[i] == '_':
ret += '.'
elif '9' < name[i] < 'a' and name[i - 1]... | [
"def",
"class_name_to_instant_name",
"(",
"name",
")",
":",
"name",
"=",
"name",
".",
"replace",
"(",
"'/'",
",",
"'_'",
")",
"ret",
"=",
"name",
"[",
"0",
"]",
".",
"lower",
"(",
")",
"for",
"i",
"in",
"range",
"(",
"1",
",",
"len",
"(",
"name",... | This will convert from 'ParentName_ChildName' to
'parent_name.child_name' | [
"This",
"will",
"convert",
"from",
"ParentName_ChildName",
"to",
"parent_name",
".",
"child_name"
] | train | https://github.com/SeabornGames/Meta/blob/f2a38ad8bcc5ac177e537645853593225895df46/seaborn_meta/class_name.py#L8-L20 |
SeabornGames/Meta | seaborn_meta/class_name.py | instant_name_to_class_name | def instant_name_to_class_name(name):
"""
This will convert from 'parent_name.child_name' to
'ParentName_ChildName'
:param name: str of the name to convert
:return: str of the converted name
"""
name2 = ''.join([e.title() for e in name.split('_')])
return '_'.join([e[0].upper() +... | python | def instant_name_to_class_name(name):
"""
This will convert from 'parent_name.child_name' to
'ParentName_ChildName'
:param name: str of the name to convert
:return: str of the converted name
"""
name2 = ''.join([e.title() for e in name.split('_')])
return '_'.join([e[0].upper() +... | [
"def",
"instant_name_to_class_name",
"(",
"name",
")",
":",
"name2",
"=",
"''",
".",
"join",
"(",
"[",
"e",
".",
"title",
"(",
")",
"for",
"e",
"in",
"name",
".",
"split",
"(",
"'_'",
")",
"]",
")",
"return",
"'_'",
".",
"join",
"(",
"[",
"e",
... | This will convert from 'parent_name.child_name' to
'ParentName_ChildName'
:param name: str of the name to convert
:return: str of the converted name | [
"This",
"will",
"convert",
"from",
"parent_name",
".",
"child_name",
"to",
"ParentName_ChildName",
":",
"param",
"name",
":",
"str",
"of",
"the",
"name",
"to",
"convert",
":",
"return",
":",
"str",
"of",
"the",
"converted",
"name"
] | train | https://github.com/SeabornGames/Meta/blob/f2a38ad8bcc5ac177e537645853593225895df46/seaborn_meta/class_name.py#L23-L31 |
SeabornGames/Meta | seaborn_meta/class_name.py | create_init_files | def create_init_files(path):
"""
This will create __init__.py for a module path and every subdirectory
:param path: str of the path to start adding __init__.py to
:return: None
"""
python_files = sorted([os.path.basename(file_)[:-3] for file_ in
glob.glob(os.path.j... | python | def create_init_files(path):
"""
This will create __init__.py for a module path and every subdirectory
:param path: str of the path to start adding __init__.py to
:return: None
"""
python_files = sorted([os.path.basename(file_)[:-3] for file_ in
glob.glob(os.path.j... | [
"def",
"create_init_files",
"(",
"path",
")",
":",
"python_files",
"=",
"sorted",
"(",
"[",
"os",
".",
"path",
".",
"basename",
"(",
"file_",
")",
"[",
":",
"-",
"3",
"]",
"for",
"file_",
"in",
"glob",
".",
"glob",
"(",
"os",
".",
"path",
".",
"j... | This will create __init__.py for a module path and every subdirectory
:param path: str of the path to start adding __init__.py to
:return: None | [
"This",
"will",
"create",
"__init__",
".",
"py",
"for",
"a",
"module",
"path",
"and",
"every",
"subdirectory",
":",
"param",
"path",
":",
"str",
"of",
"the",
"path",
"to",
"start",
"adding",
"__init__",
".",
"py",
"to",
":",
"return",
":",
"None"
] | train | https://github.com/SeabornGames/Meta/blob/f2a38ad8bcc5ac177e537645853593225895df46/seaborn_meta/class_name.py#L44-L61 |
Othernet-Project/chainable-validators | validators/helpers.py | OR | def OR(*fns):
""" Validate with any of the chainable valdator functions """
if len(fns) < 2:
raise TypeError('At least two functions must be passed')
@chainable
def validator(v):
for fn in fns:
last = None
try:
return fn(v)
except Valu... | python | def OR(*fns):
""" Validate with any of the chainable valdator functions """
if len(fns) < 2:
raise TypeError('At least two functions must be passed')
@chainable
def validator(v):
for fn in fns:
last = None
try:
return fn(v)
except Valu... | [
"def",
"OR",
"(",
"*",
"fns",
")",
":",
"if",
"len",
"(",
"fns",
")",
"<",
"2",
":",
"raise",
"TypeError",
"(",
"'At least two functions must be passed'",
")",
"@",
"chainable",
"def",
"validator",
"(",
"v",
")",
":",
"for",
"fn",
"in",
"fns",
":",
"... | Validate with any of the chainable valdator functions | [
"Validate",
"with",
"any",
"of",
"the",
"chainable",
"valdator",
"functions"
] | train | https://github.com/Othernet-Project/chainable-validators/blob/8c0afebfaaa131440ffb2a960b9b38978f00d88f/validators/helpers.py#L16-L31 |
Othernet-Project/chainable-validators | validators/helpers.py | NOT | def NOT(fn):
""" Reverse the effect of a chainable validator function """
@chainable
def validator(v):
try:
fn(v)
except ValueError:
return v
raise ValueError('invalid')
return validator | python | def NOT(fn):
""" Reverse the effect of a chainable validator function """
@chainable
def validator(v):
try:
fn(v)
except ValueError:
return v
raise ValueError('invalid')
return validator | [
"def",
"NOT",
"(",
"fn",
")",
":",
"@",
"chainable",
"def",
"validator",
"(",
"v",
")",
":",
"try",
":",
"fn",
"(",
"v",
")",
"except",
"ValueError",
":",
"return",
"v",
"raise",
"ValueError",
"(",
"'invalid'",
")",
"return",
"validator"
] | Reverse the effect of a chainable validator function | [
"Reverse",
"the",
"effect",
"of",
"a",
"chainable",
"validator",
"function"
] | train | https://github.com/Othernet-Project/chainable-validators/blob/8c0afebfaaa131440ffb2a960b9b38978f00d88f/validators/helpers.py#L34-L43 |
Othernet-Project/chainable-validators | validators/helpers.py | spec_validator | def spec_validator(spec, key=operator.itemgetter):
""" Take a spec in dict form, and return a function that validates objects
The spec maps each object's key to a chain of validator functions.
The ``key`` argument can be used to customize the way value matching a spec
key from the object. By default, ... | python | def spec_validator(spec, key=operator.itemgetter):
""" Take a spec in dict form, and return a function that validates objects
The spec maps each object's key to a chain of validator functions.
The ``key`` argument can be used to customize the way value matching a spec
key from the object. By default, ... | [
"def",
"spec_validator",
"(",
"spec",
",",
"key",
"=",
"operator",
".",
"itemgetter",
")",
":",
"spec",
"=",
"{",
"k",
":",
"(",
"key",
"(",
"k",
")",
",",
"make_chain",
"(",
"v",
")",
")",
"for",
"k",
",",
"v",
"in",
"spec",
".",
"items",
"(",... | Take a spec in dict form, and return a function that validates objects
The spec maps each object's key to a chain of validator functions.
The ``key`` argument can be used to customize the way value matching a spec
key from the object. By default, it uses ``operator.itemgetter``. It should
be assigned ... | [
"Take",
"a",
"spec",
"in",
"dict",
"form",
"and",
"return",
"a",
"function",
"that",
"validates",
"objects"
] | train | https://github.com/Othernet-Project/chainable-validators/blob/8c0afebfaaa131440ffb2a960b9b38978f00d88f/validators/helpers.py#L46-L69 |
CS207-Final-Project-Group-10/cs207-FinalProject | fluxions/fluxion_jacobian.py | jacobian | def jacobian(f, v, v_mapping):
"""
f: single fluxion object or an array or list of fluxions, representing a scalar or vector function
v: vector of variables in f with respect to which the Jacobian will be calculated
v_mapping: dict mapping variables in f to scalar or vector of values
""... | python | def jacobian(f, v, v_mapping):
"""
f: single fluxion object or an array or list of fluxions, representing a scalar or vector function
v: vector of variables in f with respect to which the Jacobian will be calculated
v_mapping: dict mapping variables in f to scalar or vector of values
""... | [
"def",
"jacobian",
"(",
"f",
",",
"v",
",",
"v_mapping",
")",
":",
"# make sure f is in the form np.array([fl1, ...])",
"if",
"isinstance",
"(",
"f",
",",
"Fluxion",
")",
":",
"f",
"=",
"[",
"f",
"]",
"f",
"=",
"np",
".",
"asarray",
"(",
"f",
")",
"v",... | f: single fluxion object or an array or list of fluxions, representing a scalar or vector function
v: vector of variables in f with respect to which the Jacobian will be calculated
v_mapping: dict mapping variables in f to scalar or vector of values | [
"f",
":",
"single",
"fluxion",
"object",
"or",
"an",
"array",
"or",
"list",
"of",
"fluxions",
"representing",
"a",
"scalar",
"or",
"vector",
"function",
"v",
":",
"vector",
"of",
"variables",
"in",
"f",
"with",
"respect",
"to",
"which",
"the",
"Jacobian",
... | train | https://github.com/CS207-Final-Project-Group-10/cs207-FinalProject/blob/842e9c2d3ca1490cef18c086dfde81856d8d3a82/fluxions/fluxion_jacobian.py#L49-L74 |
matthewdeanmartin/jiggle_version | jiggle_version/main.py | process_docopts | def process_docopts(test=None): # type: (Optional[Dict[str,Any]])->None
"""
Just process the command line options and commands
:return:
"""
if test:
arguments = test
else:
arguments = docopt(__doc__, version="Jiggle Version {0}".format(__version__))
logger.debug(arguments)
... | python | def process_docopts(test=None): # type: (Optional[Dict[str,Any]])->None
"""
Just process the command line options and commands
:return:
"""
if test:
arguments = test
else:
arguments = docopt(__doc__, version="Jiggle Version {0}".format(__version__))
logger.debug(arguments)
... | [
"def",
"process_docopts",
"(",
"test",
"=",
"None",
")",
":",
"# type: (Optional[Dict[str,Any]])->None",
"if",
"test",
":",
"arguments",
"=",
"test",
"else",
":",
"arguments",
"=",
"docopt",
"(",
"__doc__",
",",
"version",
"=",
"\"Jiggle Version {0}\"",
".",
"fo... | Just process the command line options and commands
:return: | [
"Just",
"process",
"the",
"command",
"line",
"options",
"and",
"commands",
":",
"return",
":"
] | train | https://github.com/matthewdeanmartin/jiggle_version/blob/963656a0a47b7162780a5f6c8f4b8bbbebc148f5/jiggle_version/main.py#L86-L150 |
collectiveacuity/labPack | labpack/platforms/apscheduler.py | apschedulerClient.list_jobs | def list_jobs(self, argument_filters=None):
'''
a method to list jobs in the scheduler
:param argument_filters: list of query criteria dictionaries for class argument keys
:return: list of jobs (which satisfy the filters)
NOTE: query criteria architecture
... | python | def list_jobs(self, argument_filters=None):
'''
a method to list jobs in the scheduler
:param argument_filters: list of query criteria dictionaries for class argument keys
:return: list of jobs (which satisfy the filters)
NOTE: query criteria architecture
... | [
"def",
"list_jobs",
"(",
"self",
",",
"argument_filters",
"=",
"None",
")",
":",
"title",
"=",
"'%s.list_jobs'",
"%",
"self",
".",
"__class__",
".",
"__name__",
"# validate inputs\r",
"if",
"argument_filters",
":",
"self",
".",
"fields",
".",
"validate",
"(",
... | a method to list jobs in the scheduler
:param argument_filters: list of query criteria dictionaries for class argument keys
:return: list of jobs (which satisfy the filters)
NOTE: query criteria architecture
each item in the argument filters list must be a dictionary
... | [
"a",
"method",
"to",
"list",
"jobs",
"in",
"the",
"scheduler",
":",
"param",
"argument_filters",
":",
"list",
"of",
"query",
"criteria",
"dictionaries",
"for",
"class",
"argument",
"keys",
":",
"return",
":",
"list",
"of",
"jobs",
"(",
"which",
"satisfy",
... | train | https://github.com/collectiveacuity/labPack/blob/52949ece35e72e3cc308f54d9ffa6bfbd96805b8/labpack/platforms/apscheduler.py#L329-L446 |
deformio/python-deform | pydeform/client.py | Client.auth | def auth(self, auth_type, auth_key, project_id=None):
"""Creates authenticated client.
Parameters:
* `auth_type` - Authentication type. Use `session` for auth
by session key. Use `token` for auth by token.
* `auth_key` - Authentication `session key` or `token`.
* `pro... | python | def auth(self, auth_type, auth_key, project_id=None):
"""Creates authenticated client.
Parameters:
* `auth_type` - Authentication type. Use `session` for auth
by session key. Use `token` for auth by token.
* `auth_key` - Authentication `session key` or `token`.
* `pro... | [
"def",
"auth",
"(",
"self",
",",
"auth_type",
",",
"auth_key",
",",
"project_id",
"=",
"None",
")",
":",
"if",
"auth_type",
"==",
"'session'",
":",
"return",
"SessionAuthClient",
"(",
"auth_header",
"=",
"get_session_http_auth_header",
"(",
"auth_key",
")",
",... | Creates authenticated client.
Parameters:
* `auth_type` - Authentication type. Use `session` for auth
by session key. Use `token` for auth by token.
* `auth_key` - Authentication `session key` or `token`.
* `project_id` - Project identifier. Must be provided for
`to... | [
"Creates",
"authenticated",
"client",
"."
] | train | https://github.com/deformio/python-deform/blob/c1edc7572881b83a4981b2dd39898527e518bd1f/pydeform/client.py#L85-L165 |
deformio/python-deform | pydeform/client.py | SessionAuthClient.use_project | def use_project(self, project_id):
"""Creates an instance of [ProjectClient](#projectclient),
providing session authentication.
Parameters:
* `project_id` - project identifier.
Returns:
Instance of [ProjectClient](#projectclient) with
session authentication.
... | python | def use_project(self, project_id):
"""Creates an instance of [ProjectClient](#projectclient),
providing session authentication.
Parameters:
* `project_id` - project identifier.
Returns:
Instance of [ProjectClient](#projectclient) with
session authentication.
... | [
"def",
"use_project",
"(",
"self",
",",
"project_id",
")",
":",
"return",
"ProjectClient",
"(",
"base_uri",
"=",
"get_base_uri",
"(",
"project",
"=",
"project_id",
",",
"host",
"=",
"self",
".",
"host",
",",
"port",
"=",
"self",
".",
"port",
",",
"secure... | Creates an instance of [ProjectClient](#projectclient),
providing session authentication.
Parameters:
* `project_id` - project identifier.
Returns:
Instance of [ProjectClient](#projectclient) with
session authentication.
Example:
```python
cl... | [
"Creates",
"an",
"instance",
"of",
"[",
"ProjectClient",
"]",
"(",
"#projectclient",
")",
"providing",
"session",
"authentication",
"."
] | train | https://github.com/deformio/python-deform/blob/c1edc7572881b83a4981b2dd39898527e518bd1f/pydeform/client.py#L206-L242 |
kolypto/py-exdoc | exdoc/py/__init__.py | getdoc | def getdoc(obj):
""" Get object docstring
:rtype: str
"""
inspect_got_doc = inspect.getdoc(obj)
if inspect_got_doc in (object.__init__.__doc__, object.__doc__):
return '' # We never want this builtin stuff
return (inspect_got_doc or '').strip() | python | def getdoc(obj):
""" Get object docstring
:rtype: str
"""
inspect_got_doc = inspect.getdoc(obj)
if inspect_got_doc in (object.__init__.__doc__, object.__doc__):
return '' # We never want this builtin stuff
return (inspect_got_doc or '').strip() | [
"def",
"getdoc",
"(",
"obj",
")",
":",
"inspect_got_doc",
"=",
"inspect",
".",
"getdoc",
"(",
"obj",
")",
"if",
"inspect_got_doc",
"in",
"(",
"object",
".",
"__init__",
".",
"__doc__",
",",
"object",
".",
"__doc__",
")",
":",
"return",
"''",
"# We never ... | Get object docstring
:rtype: str | [
"Get",
"object",
"docstring"
] | train | https://github.com/kolypto/py-exdoc/blob/516526c01c203271410e7d7340024ef9f0bfa46a/exdoc/py/__init__.py#L11-L19 |
kolypto/py-exdoc | exdoc/py/__init__.py | _get_callable | def _get_callable(obj, of_class = None):
""" Get callable for an object and its full name.
Supports:
* functions
* classes (jumps to __init__())
* methods
* @classmethod
* @property
:param obj: function|class
:type obj: Callable
:param of_class: Class that this method is a mem... | python | def _get_callable(obj, of_class = None):
""" Get callable for an object and its full name.
Supports:
* functions
* classes (jumps to __init__())
* methods
* @classmethod
* @property
:param obj: function|class
:type obj: Callable
:param of_class: Class that this method is a mem... | [
"def",
"_get_callable",
"(",
"obj",
",",
"of_class",
"=",
"None",
")",
":",
"# Cases",
"o",
"=",
"obj",
"if",
"inspect",
".",
"isclass",
"(",
"obj",
")",
":",
"try",
":",
"o",
"=",
"obj",
".",
"__init__",
"of_class",
"=",
"obj",
"except",
"AttributeE... | Get callable for an object and its full name.
Supports:
* functions
* classes (jumps to __init__())
* methods
* @classmethod
* @property
:param obj: function|class
:type obj: Callable
:param of_class: Class that this method is a member of
:type of_class: class|None
:return... | [
"Get",
"callable",
"for",
"an",
"object",
"and",
"its",
"full",
"name",
"."
] | train | https://github.com/kolypto/py-exdoc/blob/516526c01c203271410e7d7340024ef9f0bfa46a/exdoc/py/__init__.py#L22-L51 |
kolypto/py-exdoc | exdoc/py/__init__.py | _doc_parse | def _doc_parse(doc, module=None, qualname=None):
""" Parse docstring into a dict
:rtype: data.FDocstring
"""
# Build the rex
known_tags = {
'param': 'arg',
'type': 'arg-type',
'return': 'ret',
'returns': 'ret',
'rtype': 'ret-type',
'exception': 'exc'... | python | def _doc_parse(doc, module=None, qualname=None):
""" Parse docstring into a dict
:rtype: data.FDocstring
"""
# Build the rex
known_tags = {
'param': 'arg',
'type': 'arg-type',
'return': 'ret',
'returns': 'ret',
'rtype': 'ret-type',
'exception': 'exc'... | [
"def",
"_doc_parse",
"(",
"doc",
",",
"module",
"=",
"None",
",",
"qualname",
"=",
"None",
")",
":",
"# Build the rex",
"known_tags",
"=",
"{",
"'param'",
":",
"'arg'",
",",
"'type'",
":",
"'arg-type'",
",",
"'return'",
":",
"'ret'",
",",
"'returns'",
":... | Parse docstring into a dict
:rtype: data.FDocstring | [
"Parse",
"docstring",
"into",
"a",
"dict"
] | train | https://github.com/kolypto/py-exdoc/blob/516526c01c203271410e7d7340024ef9f0bfa46a/exdoc/py/__init__.py#L54-L109 |
kolypto/py-exdoc | exdoc/py/__init__.py | _argspec | def _argspec(func):
""" For a callable, get the full argument spec
:type func: Callable
:rtype: list[data.ArgumentSpec]
"""
assert isinstance(func, collections.Callable), 'Argument must be a callable'
try: sp = inspect.getargspec(func) if six.PY2 else inspect.getfullargspec(func)
except T... | python | def _argspec(func):
""" For a callable, get the full argument spec
:type func: Callable
:rtype: list[data.ArgumentSpec]
"""
assert isinstance(func, collections.Callable), 'Argument must be a callable'
try: sp = inspect.getargspec(func) if six.PY2 else inspect.getfullargspec(func)
except T... | [
"def",
"_argspec",
"(",
"func",
")",
":",
"assert",
"isinstance",
"(",
"func",
",",
"collections",
".",
"Callable",
")",
",",
"'Argument must be a callable'",
"try",
":",
"sp",
"=",
"inspect",
".",
"getargspec",
"(",
"func",
")",
"if",
"six",
".",
"PY2",
... | For a callable, get the full argument spec
:type func: Callable
:rtype: list[data.ArgumentSpec] | [
"For",
"a",
"callable",
"get",
"the",
"full",
"argument",
"spec"
] | train | https://github.com/kolypto/py-exdoc/blob/516526c01c203271410e7d7340024ef9f0bfa46a/exdoc/py/__init__.py#L121-L156 |
kolypto/py-exdoc | exdoc/py/__init__.py | _docspec | def _docspec(func, module=None, qualname=None, of_class=None):
""" For a callable, get the full spec by merging doc_parse() and argspec()
:type func: Callable
:rtype: data.FDocstring
"""
sp = _argspec(func)
doc = _doc_parse(getdoc(func), module=module, qualname=qualname)
# Merge args
d... | python | def _docspec(func, module=None, qualname=None, of_class=None):
""" For a callable, get the full spec by merging doc_parse() and argspec()
:type func: Callable
:rtype: data.FDocstring
"""
sp = _argspec(func)
doc = _doc_parse(getdoc(func), module=module, qualname=qualname)
# Merge args
d... | [
"def",
"_docspec",
"(",
"func",
",",
"module",
"=",
"None",
",",
"qualname",
"=",
"None",
",",
"of_class",
"=",
"None",
")",
":",
"sp",
"=",
"_argspec",
"(",
"func",
")",
"doc",
"=",
"_doc_parse",
"(",
"getdoc",
"(",
"func",
")",
",",
"module",
"="... | For a callable, get the full spec by merging doc_parse() and argspec()
:type func: Callable
:rtype: data.FDocstring | [
"For",
"a",
"callable",
"get",
"the",
"full",
"spec",
"by",
"merging",
"doc_parse",
"()",
"and",
"argspec",
"()"
] | train | https://github.com/kolypto/py-exdoc/blob/516526c01c203271410e7d7340024ef9f0bfa46a/exdoc/py/__init__.py#L159-L181 |
kolypto/py-exdoc | exdoc/py/__init__.py | doc | def doc(obj, of_class=None):
""" Get parsed documentation for an object as a dict.
This includes arguments spec, as well as the parsed data from the docstring.
```python
from exdoc import doc
```
The `doc()` function simply fetches documentation for an object, which can be
* Module
*... | python | def doc(obj, of_class=None):
""" Get parsed documentation for an object as a dict.
This includes arguments spec, as well as the parsed data from the docstring.
```python
from exdoc import doc
```
The `doc()` function simply fetches documentation for an object, which can be
* Module
*... | [
"def",
"doc",
"(",
"obj",
",",
"of_class",
"=",
"None",
")",
":",
"# Special care about properties",
"if",
"isinstance",
"(",
"obj",
",",
"property",
")",
":",
"docstr",
"=",
"doc",
"(",
"obj",
".",
"fget",
")",
"# Some hacks for properties",
"docstr",
".",
... | Get parsed documentation for an object as a dict.
This includes arguments spec, as well as the parsed data from the docstring.
```python
from exdoc import doc
```
The `doc()` function simply fetches documentation for an object, which can be
* Module
* Class
* Function or method
*... | [
"Get",
"parsed",
"documentation",
"for",
"an",
"object",
"as",
"a",
"dict",
"."
] | train | https://github.com/kolypto/py-exdoc/blob/516526c01c203271410e7d7340024ef9f0bfa46a/exdoc/py/__init__.py#L184-L306 |
kolypto/py-exdoc | exdoc/py/__init__.py | getmembers | def getmembers(obj, *predicates):
""" Return all the members of an object as a list of `(key, value)` tuples, sorted by name.
The optional list of predicates can be used to filter the members.
The default predicate drops members whose name starts with '_'. To disable it, pass `None` as the first predicate... | python | def getmembers(obj, *predicates):
""" Return all the members of an object as a list of `(key, value)` tuples, sorted by name.
The optional list of predicates can be used to filter the members.
The default predicate drops members whose name starts with '_'. To disable it, pass `None` as the first predicate... | [
"def",
"getmembers",
"(",
"obj",
",",
"*",
"predicates",
")",
":",
"# Add default",
"if",
"not",
"predicates",
"or",
"predicates",
"[",
"0",
"]",
"is",
"not",
"None",
":",
"predicates",
"=",
"(",
"lambda",
"key",
",",
"value",
":",
"not",
"key",
".",
... | Return all the members of an object as a list of `(key, value)` tuples, sorted by name.
The optional list of predicates can be used to filter the members.
The default predicate drops members whose name starts with '_'. To disable it, pass `None` as the first predicate.
:param obj: Object to list the memb... | [
"Return",
"all",
"the",
"members",
"of",
"an",
"object",
"as",
"a",
"list",
"of",
"(",
"key",
"value",
")",
"tuples",
"sorted",
"by",
"name",
"."
] | train | https://github.com/kolypto/py-exdoc/blob/516526c01c203271410e7d7340024ef9f0bfa46a/exdoc/py/__init__.py#L309-L336 |
kolypto/py-exdoc | exdoc/py/__init__.py | subclasses | def subclasses(cls, leaves=False):
""" List all subclasses of the given class, including itself.
If `leaves=True`, only returns classes which have no subclasses themselves.
:type cls: type
:param leaves: Only return leaf classes
:type leaves: bool
:rtype: list[type]
"""
stack = [cls]
... | python | def subclasses(cls, leaves=False):
""" List all subclasses of the given class, including itself.
If `leaves=True`, only returns classes which have no subclasses themselves.
:type cls: type
:param leaves: Only return leaf classes
:type leaves: bool
:rtype: list[type]
"""
stack = [cls]
... | [
"def",
"subclasses",
"(",
"cls",
",",
"leaves",
"=",
"False",
")",
":",
"stack",
"=",
"[",
"cls",
"]",
"subcls",
"=",
"[",
"]",
"while",
"stack",
":",
"c",
"=",
"stack",
".",
"pop",
"(",
")",
"c_subs",
"=",
"c",
".",
"__subclasses__",
"(",
")",
... | List all subclasses of the given class, including itself.
If `leaves=True`, only returns classes which have no subclasses themselves.
:type cls: type
:param leaves: Only return leaf classes
:type leaves: bool
:rtype: list[type] | [
"List",
"all",
"subclasses",
"of",
"the",
"given",
"class",
"including",
"itself",
"."
] | train | https://github.com/kolypto/py-exdoc/blob/516526c01c203271410e7d7340024ef9f0bfa46a/exdoc/py/__init__.py#L339-L357 |
RonenNess/Fileter | fileter/sources/files_pattern.py | PatternSource.match_pattern | def match_pattern(self, path):
"""
Return if given path match the pattern(s).
:param path: path to check.
:return: True if match, False otherwise.
"""
for pattern in self.__pattern:
if len(fnmatch.filter([path], pattern)) > 0:
return True
... | python | def match_pattern(self, path):
"""
Return if given path match the pattern(s).
:param path: path to check.
:return: True if match, False otherwise.
"""
for pattern in self.__pattern:
if len(fnmatch.filter([path], pattern)) > 0:
return True
... | [
"def",
"match_pattern",
"(",
"self",
",",
"path",
")",
":",
"for",
"pattern",
"in",
"self",
".",
"__pattern",
":",
"if",
"len",
"(",
"fnmatch",
".",
"filter",
"(",
"[",
"path",
"]",
",",
"pattern",
")",
")",
">",
"0",
":",
"return",
"True",
"return... | Return if given path match the pattern(s).
:param path: path to check.
:return: True if match, False otherwise. | [
"Return",
"if",
"given",
"path",
"match",
"the",
"pattern",
"(",
"s",
")",
"."
] | train | https://github.com/RonenNess/Fileter/blob/5372221b4049d5d46a9926573b91af17681c81f3/fileter/sources/files_pattern.py#L69-L79 |
GemHQ/round-py | round/wallets.py | generate | def generate(passphrase, trees=['primary']):
"""Generate a seed for the primary tree of a Gem wallet.
You may choose to store the passphrase for a user so the user doesn't have
to type it in every time. This is okay (although the security risks should
be obvious) but Gem strongly discourages storing ev... | python | def generate(passphrase, trees=['primary']):
"""Generate a seed for the primary tree of a Gem wallet.
You may choose to store the passphrase for a user so the user doesn't have
to type it in every time. This is okay (although the security risks should
be obvious) but Gem strongly discourages storing ev... | [
"def",
"generate",
"(",
"passphrase",
",",
"trees",
"=",
"[",
"'primary'",
"]",
")",
":",
"seeds",
",",
"multi_wallet",
"=",
"MultiWallet",
".",
"generate",
"(",
"trees",
",",
"entropy",
"=",
"True",
")",
"result",
"=",
"{",
"}",
"for",
"tree",
"in",
... | Generate a seed for the primary tree of a Gem wallet.
You may choose to store the passphrase for a user so the user doesn't have
to type it in every time. This is okay (although the security risks should
be obvious) but Gem strongly discourages storing even the encrypted private
seed, and storing both ... | [
"Generate",
"a",
"seed",
"for",
"the",
"primary",
"tree",
"of",
"a",
"Gem",
"wallet",
"."
] | train | https://github.com/GemHQ/round-py/blob/d0838f849cd260b1eb5df67ed3c6f2fe56c91c21/round/wallets.py#L26-L55 |
GemHQ/round-py | round/wallets.py | Wallets.create | def create(self, name, passphrase=None, wallet_data=None):
"""Create a new Wallet object and add it to this Wallets collection.
This is only available in this library for Application wallets. Users
must add additional wallets in their User Console
Args:
name (str): wallet name... | python | def create(self, name, passphrase=None, wallet_data=None):
"""Create a new Wallet object and add it to this Wallets collection.
This is only available in this library for Application wallets. Users
must add additional wallets in their User Console
Args:
name (str): wallet name... | [
"def",
"create",
"(",
"self",
",",
"name",
",",
"passphrase",
"=",
"None",
",",
"wallet_data",
"=",
"None",
")",
":",
"if",
"not",
"self",
".",
"application",
":",
"raise",
"RoundError",
"(",
"\"User accounts are limited to one wallet. Make an \"",
"\"account or s... | Create a new Wallet object and add it to this Wallets collection.
This is only available in this library for Application wallets. Users
must add additional wallets in their User Console
Args:
name (str): wallet name
passphrase (str, optional): A passphrase with which to encr... | [
"Create",
"a",
"new",
"Wallet",
"object",
"and",
"add",
"it",
"to",
"this",
"Wallets",
"collection",
".",
"This",
"is",
"only",
"available",
"in",
"this",
"library",
"for",
"Application",
"wallets",
".",
"Users",
"must",
"add",
"additional",
"wallets",
"in",... | train | https://github.com/GemHQ/round-py/blob/d0838f849cd260b1eb5df67ed3c6f2fe56c91c21/round/wallets.py#L78-L116 |
GemHQ/round-py | round/wallets.py | Wallet.unlock | def unlock(self, passphrase, encrypted_seed=None):
"""Unlock the Wallet by decrypting the primary_private_seed with the
supplied passphrase. Once unlocked, the private seed is accessible in
memory and calls to `account.pay` will succeed. This is a necessary step
for creating transactions... | python | def unlock(self, passphrase, encrypted_seed=None):
"""Unlock the Wallet by decrypting the primary_private_seed with the
supplied passphrase. Once unlocked, the private seed is accessible in
memory and calls to `account.pay` will succeed. This is a necessary step
for creating transactions... | [
"def",
"unlock",
"(",
"self",
",",
"passphrase",
",",
"encrypted_seed",
"=",
"None",
")",
":",
"wallet",
"=",
"self",
".",
"resource",
"if",
"not",
"encrypted_seed",
":",
"encrypted_seed",
"=",
"wallet",
".",
"primary_private_seed",
"try",
":",
"if",
"encryp... | Unlock the Wallet by decrypting the primary_private_seed with the
supplied passphrase. Once unlocked, the private seed is accessible in
memory and calls to `account.pay` will succeed. This is a necessary step
for creating transactions.
Args:
passphrase (str): The passphrase th... | [
"Unlock",
"the",
"Wallet",
"by",
"decrypting",
"the",
"primary_private_seed",
"with",
"the",
"supplied",
"passphrase",
".",
"Once",
"unlocked",
"the",
"private",
"seed",
"is",
"accessible",
"in",
"memory",
"and",
"calls",
"to",
"account",
".",
"pay",
"will",
"... | train | https://github.com/GemHQ/round-py/blob/d0838f849cd260b1eb5df67ed3c6f2fe56c91c21/round/wallets.py#L165-L204 |
GemHQ/round-py | round/wallets.py | Wallet.balances_at | def balances_at(self, utxo_confirmations=6, network=None):
"""Return the confirmed, claimed (reserved for a pending, unsigned
transaction), and available balances, where the threshold for
confirmed is the value of `utxo_confirmations`.
Args:
utxo_confirmations (int): the # of ... | python | def balances_at(self, utxo_confirmations=6, network=None):
"""Return the confirmed, claimed (reserved for a pending, unsigned
transaction), and available balances, where the threshold for
confirmed is the value of `utxo_confirmations`.
Args:
utxo_confirmations (int): the # of ... | [
"def",
"balances_at",
"(",
"self",
",",
"utxo_confirmations",
"=",
"6",
",",
"network",
"=",
"None",
")",
":",
"if",
"not",
"network",
"in",
"SUPPORTED_NETWORKS",
":",
"raise",
"ValueError",
"(",
"'Network not valid!'",
")",
"return",
"self",
".",
"resource",
... | Return the confirmed, claimed (reserved for a pending, unsigned
transaction), and available balances, where the threshold for
confirmed is the value of `utxo_confirmations`.
Args:
utxo_confirmations (int): the # of confirmations to use when computing
balances.
ne... | [
"Return",
"the",
"confirmed",
"claimed",
"(",
"reserved",
"for",
"a",
"pending",
"unsigned",
"transaction",
")",
"and",
"available",
"balances",
"where",
"the",
"threshold",
"for",
"confirmed",
"is",
"the",
"value",
"of",
"utxo_confirmations",
"."
] | train | https://github.com/GemHQ/round-py/blob/d0838f849cd260b1eb5df67ed3c6f2fe56c91c21/round/wallets.py#L206-L226 |
GemHQ/round-py | round/wallets.py | Wallet.get_accounts | def get_accounts(self, fetch=False):
"""Return this Wallet's accounts object, populating it if fetch is True."""
return Accounts(self.resource.accounts, self.client, wallet=self, populate=fetch) | python | def get_accounts(self, fetch=False):
"""Return this Wallet's accounts object, populating it if fetch is True."""
return Accounts(self.resource.accounts, self.client, wallet=self, populate=fetch) | [
"def",
"get_accounts",
"(",
"self",
",",
"fetch",
"=",
"False",
")",
":",
"return",
"Accounts",
"(",
"self",
".",
"resource",
".",
"accounts",
",",
"self",
".",
"client",
",",
"wallet",
"=",
"self",
",",
"populate",
"=",
"fetch",
")"
] | Return this Wallet's accounts object, populating it if fetch is True. | [
"Return",
"this",
"Wallet",
"s",
"accounts",
"object",
"populating",
"it",
"if",
"fetch",
"is",
"True",
"."
] | train | https://github.com/GemHQ/round-py/blob/d0838f849cd260b1eb5df67ed3c6f2fe56c91c21/round/wallets.py#L234-L236 |
GemHQ/round-py | round/wallets.py | Wallet.account | def account(self, key=None, address=None, name=None):
"""Query for an account by key, address, or name."""
if key:
return self.client.account(key, wallet=self)
if address:
q = dict(address=address)
elif name:
q = dict(name=name)
else:
... | python | def account(self, key=None, address=None, name=None):
"""Query for an account by key, address, or name."""
if key:
return self.client.account(key, wallet=self)
if address:
q = dict(address=address)
elif name:
q = dict(name=name)
else:
... | [
"def",
"account",
"(",
"self",
",",
"key",
"=",
"None",
",",
"address",
"=",
"None",
",",
"name",
"=",
"None",
")",
":",
"if",
"key",
":",
"return",
"self",
".",
"client",
".",
"account",
"(",
"key",
",",
"wallet",
"=",
"self",
")",
"if",
"addres... | Query for an account by key, address, or name. | [
"Query",
"for",
"an",
"account",
"by",
"key",
"address",
"or",
"name",
"."
] | train | https://github.com/GemHQ/round-py/blob/d0838f849cd260b1eb5df67ed3c6f2fe56c91c21/round/wallets.py#L242-L254 |
GemHQ/round-py | round/wallets.py | Wallet.dump_addresses | def dump_addresses(self, network, filename=None):
"""Return a list of address dictionaries for each address in all of the
accounts in this wallet of the network specified by `network`
"""
addrs = [addr.data for a in self.accounts.values() if a.network == network
... | python | def dump_addresses(self, network, filename=None):
"""Return a list of address dictionaries for each address in all of the
accounts in this wallet of the network specified by `network`
"""
addrs = [addr.data for a in self.accounts.values() if a.network == network
... | [
"def",
"dump_addresses",
"(",
"self",
",",
"network",
",",
"filename",
"=",
"None",
")",
":",
"addrs",
"=",
"[",
"addr",
".",
"data",
"for",
"a",
"in",
"self",
".",
"accounts",
".",
"values",
"(",
")",
"if",
"a",
".",
"network",
"==",
"network",
"f... | Return a list of address dictionaries for each address in all of the
accounts in this wallet of the network specified by `network` | [
"Return",
"a",
"list",
"of",
"address",
"dictionaries",
"for",
"each",
"address",
"in",
"all",
"of",
"the",
"accounts",
"in",
"this",
"wallet",
"of",
"the",
"network",
"specified",
"by",
"network"
] | train | https://github.com/GemHQ/round-py/blob/d0838f849cd260b1eb5df67ed3c6f2fe56c91c21/round/wallets.py#L256-L267 |
GemHQ/round-py | round/wallets.py | Wallet.get_subscriptions | def get_subscriptions(self, fetch=False):
"""Return this Wallet's subscriptions object, populating it if fetch is True."""
return Subscriptions(
self.resource.subscriptions, self.client, populate=fetch) | python | def get_subscriptions(self, fetch=False):
"""Return this Wallet's subscriptions object, populating it if fetch is True."""
return Subscriptions(
self.resource.subscriptions, self.client, populate=fetch) | [
"def",
"get_subscriptions",
"(",
"self",
",",
"fetch",
"=",
"False",
")",
":",
"return",
"Subscriptions",
"(",
"self",
".",
"resource",
".",
"subscriptions",
",",
"self",
".",
"client",
",",
"populate",
"=",
"fetch",
")"
] | Return this Wallet's subscriptions object, populating it if fetch is True. | [
"Return",
"this",
"Wallet",
"s",
"subscriptions",
"object",
"populating",
"it",
"if",
"fetch",
"is",
"True",
"."
] | train | https://github.com/GemHQ/round-py/blob/d0838f849cd260b1eb5df67ed3c6f2fe56c91c21/round/wallets.py#L275-L278 |
GemHQ/round-py | round/wallets.py | Wallet.signatures | def signatures(self, transaction):
"""Sign a transaction.
Args:
transaction (coinop.Transaction)
Returns:
A list of signature dicts of the form
[ {'primary': 'base58signaturestring'},
... ]
"""
# TODO: output.metadata['type']['chang... | python | def signatures(self, transaction):
"""Sign a transaction.
Args:
transaction (coinop.Transaction)
Returns:
A list of signature dicts of the form
[ {'primary': 'base58signaturestring'},
... ]
"""
# TODO: output.metadata['type']['chang... | [
"def",
"signatures",
"(",
"self",
",",
"transaction",
")",
":",
"# TODO: output.metadata['type']['change']",
"if",
"not",
"self",
".",
"multi_wallet",
":",
"raise",
"DecryptionError",
"(",
"\"This wallet must be unlocked with \"",
"\"wallet.unlock(passphrase)\"",
")",
"retu... | Sign a transaction.
Args:
transaction (coinop.Transaction)
Returns:
A list of signature dicts of the form
[ {'primary': 'base58signaturestring'},
... ] | [
"Sign",
"a",
"transaction",
"."
] | train | https://github.com/GemHQ/round-py/blob/d0838f849cd260b1eb5df67ed3c6f2fe56c91c21/round/wallets.py#L431-L447 |
basvandenbroek/gcloud_taskqueue | gcloud_taskqueue/connection.py | Connection.build_api_url | def build_api_url(self, path, query_params=None,
api_base_url=None, api_version=None):
"""Construct an API url given a few components, some optional.
Typically, you shouldn't need to use this method.
:type path: string
:param path: The path to the resource.
... | python | def build_api_url(self, path, query_params=None,
api_base_url=None, api_version=None):
"""Construct an API url given a few components, some optional.
Typically, you shouldn't need to use this method.
:type path: string
:param path: The path to the resource.
... | [
"def",
"build_api_url",
"(",
"self",
",",
"path",
",",
"query_params",
"=",
"None",
",",
"api_base_url",
"=",
"None",
",",
"api_version",
"=",
"None",
")",
":",
"if",
"api_base_url",
"is",
"None",
":",
"api_base_url",
"=",
"self",
".",
"api_base_url",
"ret... | Construct an API url given a few components, some optional.
Typically, you shouldn't need to use this method.
:type path: string
:param path: The path to the resource.
:type query_params: dict
:param query_params: A dictionary of keys and values to insert into
... | [
"Construct",
"an",
"API",
"url",
"given",
"a",
"few",
"components",
"some",
"optional",
"."
] | train | https://github.com/basvandenbroek/gcloud_taskqueue/blob/b147b57f7c0ad9e8030ee9797d6526a448aa5007/gcloud_taskqueue/connection.py#L53-L81 |
quasipedia/swaggery | swaggery/utils.py | map_exception_codes | def map_exception_codes():
'''Helper function to intialise CODES_TO_EXCEPTIONS.'''
werkex = inspect.getmembers(exceptions, lambda x: getattr(x, 'code', None))
return {e.code: e for _, e in werkex} | python | def map_exception_codes():
'''Helper function to intialise CODES_TO_EXCEPTIONS.'''
werkex = inspect.getmembers(exceptions, lambda x: getattr(x, 'code', None))
return {e.code: e for _, e in werkex} | [
"def",
"map_exception_codes",
"(",
")",
":",
"werkex",
"=",
"inspect",
".",
"getmembers",
"(",
"exceptions",
",",
"lambda",
"x",
":",
"getattr",
"(",
"x",
",",
"'code'",
",",
"None",
")",
")",
"return",
"{",
"e",
".",
"code",
":",
"e",
"for",
"_",
... | Helper function to intialise CODES_TO_EXCEPTIONS. | [
"Helper",
"function",
"to",
"intialise",
"CODES_TO_EXCEPTIONS",
"."
] | train | https://github.com/quasipedia/swaggery/blob/89a2e1b2bebbc511c781c9e63972f65aef73cc2f/swaggery/utils.py#L98-L101 |
quasipedia/swaggery | swaggery/utils.py | parse_return_annotation | def parse_return_annotation(callback):
'''Parses the annotation return tuples. Ruturn a dictinary {code: info}.'''
# This has been implemented as a function as the parsing need to be
# accessible from a decorator used on the function's class method
responses = {}
for data in callback.__annotations__... | python | def parse_return_annotation(callback):
'''Parses the annotation return tuples. Ruturn a dictinary {code: info}.'''
# This has been implemented as a function as the parsing need to be
# accessible from a decorator used on the function's class method
responses = {}
for data in callback.__annotations__... | [
"def",
"parse_return_annotation",
"(",
"callback",
")",
":",
"# This has been implemented as a function as the parsing need to be",
"# accessible from a decorator used on the function's class method",
"responses",
"=",
"{",
"}",
"for",
"data",
"in",
"callback",
".",
"__annotations_... | Parses the annotation return tuples. Ruturn a dictinary {code: info}. | [
"Parses",
"the",
"annotation",
"return",
"tuples",
".",
"Ruturn",
"a",
"dictinary",
"{",
"code",
":",
"info",
"}",
"."
] | train | https://github.com/quasipedia/swaggery/blob/89a2e1b2bebbc511c781c9e63972f65aef73cc2f/swaggery/utils.py#L104-L114 |
quasipedia/swaggery | swaggery/utils.py | extract_pathvars | def extract_pathvars(callback):
'''Extract the path variables from an Resource operation.
Return {'mandatory': [<list-of-pnames>], 'optional': [<list-of-pnames>]}
'''
mandatory = []
optional = []
# We loop on the signature because the order of the parameters is
# important, and signature is... | python | def extract_pathvars(callback):
'''Extract the path variables from an Resource operation.
Return {'mandatory': [<list-of-pnames>], 'optional': [<list-of-pnames>]}
'''
mandatory = []
optional = []
# We loop on the signature because the order of the parameters is
# important, and signature is... | [
"def",
"extract_pathvars",
"(",
"callback",
")",
":",
"mandatory",
"=",
"[",
"]",
"optional",
"=",
"[",
"]",
"# We loop on the signature because the order of the parameters is",
"# important, and signature is an OrderedDict, while annotations is a",
"# regular dictionary",
"for",
... | Extract the path variables from an Resource operation.
Return {'mandatory': [<list-of-pnames>], 'optional': [<list-of-pnames>]} | [
"Extract",
"the",
"path",
"variables",
"from",
"an",
"Resource",
"operation",
"."
] | train | https://github.com/quasipedia/swaggery/blob/89a2e1b2bebbc511c781c9e63972f65aef73cc2f/swaggery/utils.py#L117-L141 |
quasipedia/swaggery | swaggery/utils.py | parse_docstring | def parse_docstring(whatever_has_docstring):
'''Parse a docstring into a semmary (first line) and notes (rest of it).'''
try:
summary, notes = whatever_has_docstring.__doc__.split('\n', 1)
notes = dedent(notes).replace('\n', ' ')
except ValueError:
summary = whatever_has_docstring.__... | python | def parse_docstring(whatever_has_docstring):
'''Parse a docstring into a semmary (first line) and notes (rest of it).'''
try:
summary, notes = whatever_has_docstring.__doc__.split('\n', 1)
notes = dedent(notes).replace('\n', ' ')
except ValueError:
summary = whatever_has_docstring.__... | [
"def",
"parse_docstring",
"(",
"whatever_has_docstring",
")",
":",
"try",
":",
"summary",
",",
"notes",
"=",
"whatever_has_docstring",
".",
"__doc__",
".",
"split",
"(",
"'\\n'",
",",
"1",
")",
"notes",
"=",
"dedent",
"(",
"notes",
")",
".",
"replace",
"("... | Parse a docstring into a semmary (first line) and notes (rest of it). | [
"Parse",
"a",
"docstring",
"into",
"a",
"semmary",
"(",
"first",
"line",
")",
"and",
"notes",
"(",
"rest",
"of",
"it",
")",
"."
] | train | https://github.com/quasipedia/swaggery/blob/89a2e1b2bebbc511c781c9e63972f65aef73cc2f/swaggery/utils.py#L144-L152 |
quasipedia/swaggery | swaggery/utils.py | inject_extra_args | def inject_extra_args(callback, request, kwargs):
'''Inject extra arguments from header, body, form.'''
# TODO: this is a temporary pach, should be managed via honouring the
# mimetype in the request header....
annots = dict(callback.__annotations__)
del annots['return']
for param_name, (param_t... | python | def inject_extra_args(callback, request, kwargs):
'''Inject extra arguments from header, body, form.'''
# TODO: this is a temporary pach, should be managed via honouring the
# mimetype in the request header....
annots = dict(callback.__annotations__)
del annots['return']
for param_name, (param_t... | [
"def",
"inject_extra_args",
"(",
"callback",
",",
"request",
",",
"kwargs",
")",
":",
"# TODO: this is a temporary pach, should be managed via honouring the",
"# mimetype in the request header....",
"annots",
"=",
"dict",
"(",
"callback",
".",
"__annotations__",
")",
"del",
... | Inject extra arguments from header, body, form. | [
"Inject",
"extra",
"arguments",
"from",
"header",
"body",
"form",
"."
] | train | https://github.com/quasipedia/swaggery/blob/89a2e1b2bebbc511c781c9e63972f65aef73cc2f/swaggery/utils.py#L155-L173 |
quasipedia/swaggery | swaggery/utils.py | filter_annotations_by_ptype | def filter_annotations_by_ptype(function, ptype):
'''Filter an annotation by only leaving the parameters of type "ptype".'''
ret = {}
for k, v in function.__annotations__.items():
if k == 'return':
continue
pt, _ = v
if pt == ptype:
ret[k] = v
return ret | python | def filter_annotations_by_ptype(function, ptype):
'''Filter an annotation by only leaving the parameters of type "ptype".'''
ret = {}
for k, v in function.__annotations__.items():
if k == 'return':
continue
pt, _ = v
if pt == ptype:
ret[k] = v
return ret | [
"def",
"filter_annotations_by_ptype",
"(",
"function",
",",
"ptype",
")",
":",
"ret",
"=",
"{",
"}",
"for",
"k",
",",
"v",
"in",
"function",
".",
"__annotations__",
".",
"items",
"(",
")",
":",
"if",
"k",
"==",
"'return'",
":",
"continue",
"pt",
",",
... | Filter an annotation by only leaving the parameters of type "ptype". | [
"Filter",
"an",
"annotation",
"by",
"only",
"leaving",
"the",
"parameters",
"of",
"type",
"ptype",
"."
] | train | https://github.com/quasipedia/swaggery/blob/89a2e1b2bebbc511c781c9e63972f65aef73cc2f/swaggery/utils.py#L183-L192 |
Tsjerk/simopt | simopt.py | option2tuple | def option2tuple(opt):
"""Return a tuple of option, taking possible presence of level into account"""
if isinstance(opt[0], int):
tup = opt[1], opt[2:]
else:
tup = opt[0], opt[1:]
return tup | python | def option2tuple(opt):
"""Return a tuple of option, taking possible presence of level into account"""
if isinstance(opt[0], int):
tup = opt[1], opt[2:]
else:
tup = opt[0], opt[1:]
return tup | [
"def",
"option2tuple",
"(",
"opt",
")",
":",
"if",
"isinstance",
"(",
"opt",
"[",
"0",
"]",
",",
"int",
")",
":",
"tup",
"=",
"opt",
"[",
"1",
"]",
",",
"opt",
"[",
"2",
":",
"]",
"else",
":",
"tup",
"=",
"opt",
"[",
"0",
"]",
",",
"opt",
... | Return a tuple of option, taking possible presence of level into account | [
"Return",
"a",
"tuple",
"of",
"option",
"taking",
"possible",
"presence",
"of",
"level",
"into",
"account"
] | train | https://github.com/Tsjerk/simopt/blob/fa63360492af35ccb92116000325b2bbf5961703/simopt.py#L191-L199 |
Tsjerk/simopt | simopt.py | opt_func | def opt_func(options, check_mandatory=True):
"""
Restore argument checks for functions that takes options dicts as arguments
Functions that take the option dictionary produced by :meth:`Options.parse`
as `kwargs` loose the argument checking usually performed by the python
interpretor. They also loo... | python | def opt_func(options, check_mandatory=True):
"""
Restore argument checks for functions that takes options dicts as arguments
Functions that take the option dictionary produced by :meth:`Options.parse`
as `kwargs` loose the argument checking usually performed by the python
interpretor. They also loo... | [
"def",
"opt_func",
"(",
"options",
",",
"check_mandatory",
"=",
"True",
")",
":",
"# A function `my_function` decorated with `opt_func` is replaced by",
"# `opt_func(options)(my_function)`. This is equivalent to",
"# `validate_arguments(my_function)` using the `options` argument provided",
... | Restore argument checks for functions that takes options dicts as arguments
Functions that take the option dictionary produced by :meth:`Options.parse`
as `kwargs` loose the argument checking usually performed by the python
interpretor. They also loose the ability to take default values for
their keywo... | [
"Restore",
"argument",
"checks",
"for",
"functions",
"that",
"takes",
"options",
"dicts",
"as",
"arguments"
] | train | https://github.com/Tsjerk/simopt/blob/fa63360492af35ccb92116000325b2bbf5961703/simopt.py#L202-L283 |
Tsjerk/simopt | simopt.py | Options._default_dict | def _default_dict(self):
"""Return a dictionary with the default for each option."""
options = {}
for attr, _, _, default, multi, _ in self._optiondict.values():
if multi and default is None:
options[attr] = []
else:
options[attr] = default... | python | def _default_dict(self):
"""Return a dictionary with the default for each option."""
options = {}
for attr, _, _, default, multi, _ in self._optiondict.values():
if multi and default is None:
options[attr] = []
else:
options[attr] = default... | [
"def",
"_default_dict",
"(",
"self",
")",
":",
"options",
"=",
"{",
"}",
"for",
"attr",
",",
"_",
",",
"_",
",",
"default",
",",
"multi",
",",
"_",
"in",
"self",
".",
"_optiondict",
".",
"values",
"(",
")",
":",
"if",
"multi",
"and",
"default",
"... | Return a dictionary with the default for each option. | [
"Return",
"a",
"dictionary",
"with",
"the",
"default",
"for",
"each",
"option",
"."
] | train | https://github.com/Tsjerk/simopt/blob/fa63360492af35ccb92116000325b2bbf5961703/simopt.py#L87-L95 |
Tsjerk/simopt | simopt.py | Options.help | def help(self, args=None, userlevel=9):
"""Make a string from the option list"""
out = [main.__file__+"\n"]
if args is not None:
parsed = self.parse(args, ignore_help=True)
else:
parsed = self._default_dict()
for thing in self.options:
if typ... | python | def help(self, args=None, userlevel=9):
"""Make a string from the option list"""
out = [main.__file__+"\n"]
if args is not None:
parsed = self.parse(args, ignore_help=True)
else:
parsed = self._default_dict()
for thing in self.options:
if typ... | [
"def",
"help",
"(",
"self",
",",
"args",
"=",
"None",
",",
"userlevel",
"=",
"9",
")",
":",
"out",
"=",
"[",
"main",
".",
"__file__",
"+",
"\"\\n\"",
"]",
"if",
"args",
"is",
"not",
"None",
":",
"parsed",
"=",
"self",
".",
"parse",
"(",
"args",
... | Make a string from the option list | [
"Make",
"a",
"string",
"from",
"the",
"option",
"list"
] | train | https://github.com/Tsjerk/simopt/blob/fa63360492af35ccb92116000325b2bbf5961703/simopt.py#L118-L133 |
Tsjerk/simopt | simopt.py | Options.parse | def parse(self, args, ignore_help=False):
"""Parse the (command-line) arguments."""
options = self._default_dict()
seen = set()
# Do not alter the arguments. We may need them later.
args = copy.copy(args)
while args:
opt = args.pop(0)
seen.add(o... | python | def parse(self, args, ignore_help=False):
"""Parse the (command-line) arguments."""
options = self._default_dict()
seen = set()
# Do not alter the arguments. We may need them later.
args = copy.copy(args)
while args:
opt = args.pop(0)
seen.add(o... | [
"def",
"parse",
"(",
"self",
",",
"args",
",",
"ignore_help",
"=",
"False",
")",
":",
"options",
"=",
"self",
".",
"_default_dict",
"(",
")",
"seen",
"=",
"set",
"(",
")",
"# Do not alter the arguments. We may need them later.",
"args",
"=",
"copy",
".",
"co... | Parse the (command-line) arguments. | [
"Parse",
"the",
"(",
"command",
"-",
"line",
")",
"arguments",
"."
] | train | https://github.com/Tsjerk/simopt/blob/fa63360492af35ccb92116000325b2bbf5961703/simopt.py#L136-L188 |
collectiveacuity/labPack | labpack/parsing/shell.py | convert_table | def convert_table(shell_output, delimiter='\t|\s{2,}', output='dict'):
'''
a method to convert a STDOUT shell table into a python data structure
:param shell_output: string from STDOUT with headers
:param delimiter: string with regex pattern delimiting headers
:param output: string wit... | python | def convert_table(shell_output, delimiter='\t|\s{2,}', output='dict'):
'''
a method to convert a STDOUT shell table into a python data structure
:param shell_output: string from STDOUT with headers
:param delimiter: string with regex pattern delimiting headers
:param output: string wit... | [
"def",
"convert_table",
"(",
"shell_output",
",",
"delimiter",
"=",
"'\\t|\\s{2,}'",
",",
"output",
"=",
"'dict'",
")",
":",
"# retrieve header columns ",
"import",
"re",
"gap_pattern",
"=",
"re",
".",
"compile",
"(",
"delimiter",
")",
"output_lines",
"=",
"shel... | a method to convert a STDOUT shell table into a python data structure
:param shell_output: string from STDOUT with headers
:param delimiter: string with regex pattern delimiting headers
:param output: string with type of structure to output (dict, list or csv)
:return: list of dictionaries or l... | [
"a",
"method",
"to",
"convert",
"a",
"STDOUT",
"shell",
"table",
"into",
"a",
"python",
"data",
"structure",
":",
"param",
"shell_output",
":",
"string",
"from",
"STDOUT",
"with",
"headers",
":",
"param",
"delimiter",
":",
"string",
"with",
"regex",
"pattern... | train | https://github.com/collectiveacuity/labPack/blob/52949ece35e72e3cc308f54d9ffa6bfbd96805b8/labpack/parsing/shell.py#L6-L78 |
tlatsas/wigiki | wigiki/builder.py | Builder.gist | def gist(cls, gistid):
"""gistid must be in a username/id form"""
url = "https://gist.github.com/{}.js".format(gistid)
script = "<script src=\"{}\"></script>".format(url)
return script | python | def gist(cls, gistid):
"""gistid must be in a username/id form"""
url = "https://gist.github.com/{}.js".format(gistid)
script = "<script src=\"{}\"></script>".format(url)
return script | [
"def",
"gist",
"(",
"cls",
",",
"gistid",
")",
":",
"url",
"=",
"\"https://gist.github.com/{}.js\"",
".",
"format",
"(",
"gistid",
")",
"script",
"=",
"\"<script src=\\\"{}\\\"></script>\"",
".",
"format",
"(",
"url",
")",
"return",
"script"
] | gistid must be in a username/id form | [
"gistid",
"must",
"be",
"in",
"a",
"username",
"/",
"id",
"form"
] | train | https://github.com/tlatsas/wigiki/blob/baf9c5a6523a9b90db7572330d04e3e199391273/wigiki/builder.py#L6-L10 |
tlatsas/wigiki | wigiki/builder.py | Builder.page_list | def page_list(cls, pages, base_url='/'):
"""transform a list of page titles in a list of html links"""
plist = []
for page in pages:
url = "<a href=\"{}{}\">{}</a>".format(base_url, cls.slugify(page), page)
plist.append(url)
return plist | python | def page_list(cls, pages, base_url='/'):
"""transform a list of page titles in a list of html links"""
plist = []
for page in pages:
url = "<a href=\"{}{}\">{}</a>".format(base_url, cls.slugify(page), page)
plist.append(url)
return plist | [
"def",
"page_list",
"(",
"cls",
",",
"pages",
",",
"base_url",
"=",
"'/'",
")",
":",
"plist",
"=",
"[",
"]",
"for",
"page",
"in",
"pages",
":",
"url",
"=",
"\"<a href=\\\"{}{}\\\">{}</a>\"",
".",
"format",
"(",
"base_url",
",",
"cls",
".",
"slugify",
"... | transform a list of page titles in a list of html links | [
"transform",
"a",
"list",
"of",
"page",
"titles",
"in",
"a",
"list",
"of",
"html",
"links"
] | train | https://github.com/tlatsas/wigiki/blob/baf9c5a6523a9b90db7572330d04e3e199391273/wigiki/builder.py#L14-L20 |
tlatsas/wigiki | wigiki/builder.py | Builder.slugify | def slugify(cls, s):
"""Return the slug version of the string ``s``"""
slug = re.sub("[^0-9a-zA-Z-]", "-", s)
return re.sub("-{2,}", "-", slug).strip('-') | python | def slugify(cls, s):
"""Return the slug version of the string ``s``"""
slug = re.sub("[^0-9a-zA-Z-]", "-", s)
return re.sub("-{2,}", "-", slug).strip('-') | [
"def",
"slugify",
"(",
"cls",
",",
"s",
")",
":",
"slug",
"=",
"re",
".",
"sub",
"(",
"\"[^0-9a-zA-Z-]\"",
",",
"\"-\"",
",",
"s",
")",
"return",
"re",
".",
"sub",
"(",
"\"-{2,}\"",
",",
"\"-\"",
",",
"slug",
")",
".",
"strip",
"(",
"'-'",
")"
] | Return the slug version of the string ``s`` | [
"Return",
"the",
"slug",
"version",
"of",
"the",
"string",
"s"
] | train | https://github.com/tlatsas/wigiki/blob/baf9c5a6523a9b90db7572330d04e3e199391273/wigiki/builder.py#L24-L27 |
disqus/nose-socket-whitelist | src/socketwhitelist/plugins.py | SocketWhitelistPlugin.is_whitelisted | def is_whitelisted(self, addrinfo):
"""
Returns if a result of ``socket.getaddrinfo`` is in the socket address
whitelist.
"""
# For details about the ``getaddrinfo`` struct, see the Python docs:
# http://docs.python.org/library/socket.html#socket.getaddrinfo
famil... | python | def is_whitelisted(self, addrinfo):
"""
Returns if a result of ``socket.getaddrinfo`` is in the socket address
whitelist.
"""
# For details about the ``getaddrinfo`` struct, see the Python docs:
# http://docs.python.org/library/socket.html#socket.getaddrinfo
famil... | [
"def",
"is_whitelisted",
"(",
"self",
",",
"addrinfo",
")",
":",
"# For details about the ``getaddrinfo`` struct, see the Python docs:",
"# http://docs.python.org/library/socket.html#socket.getaddrinfo",
"family",
",",
"socktype",
",",
"proto",
",",
"canonname",
",",
"sockaddr",
... | Returns if a result of ``socket.getaddrinfo`` is in the socket address
whitelist. | [
"Returns",
"if",
"a",
"result",
"of",
"socket",
".",
"getaddrinfo",
"is",
"in",
"the",
"socket",
"address",
"whitelist",
"."
] | train | https://github.com/disqus/nose-socket-whitelist/blob/062f9bac079a01f74a94abda977c9a28ad472f39/src/socketwhitelist/plugins.py#L94-L103 |
disqus/nose-socket-whitelist | src/socketwhitelist/plugins.py | LoggingSocketWhitelistPlugin.report | def report(self):
"""
Performs rollups, prints report of sockets opened.
"""
aggregations = dict(
(test, Counter().rollup(values))
for test, values in self.socket_warnings.items()
)
total = sum(
len(warnings)
for warnings in... | python | def report(self):
"""
Performs rollups, prints report of sockets opened.
"""
aggregations = dict(
(test, Counter().rollup(values))
for test, values in self.socket_warnings.items()
)
total = sum(
len(warnings)
for warnings in... | [
"def",
"report",
"(",
"self",
")",
":",
"aggregations",
"=",
"dict",
"(",
"(",
"test",
",",
"Counter",
"(",
")",
".",
"rollup",
"(",
"values",
")",
")",
"for",
"test",
",",
"values",
"in",
"self",
".",
"socket_warnings",
".",
"items",
"(",
")",
")"... | Performs rollups, prints report of sockets opened. | [
"Performs",
"rollups",
"prints",
"report",
"of",
"sockets",
"opened",
"."
] | train | https://github.com/disqus/nose-socket-whitelist/blob/062f9bac079a01f74a94abda977c9a28ad472f39/src/socketwhitelist/plugins.py#L146-L182 |
pip-services3-python/pip-services3-components-python | pip_services3_components/count/CachedCounters.py | CachedCounters.clear | def clear(self, name):
"""
Clears (resets) a counter specified by its name.
:param name: a counter name to clear.
"""
self._lock.acquire()
try:
del self._cache[name]
finally:
self._lock.release() | python | def clear(self, name):
"""
Clears (resets) a counter specified by its name.
:param name: a counter name to clear.
"""
self._lock.acquire()
try:
del self._cache[name]
finally:
self._lock.release() | [
"def",
"clear",
"(",
"self",
",",
"name",
")",
":",
"self",
".",
"_lock",
".",
"acquire",
"(",
")",
"try",
":",
"del",
"self",
".",
"_cache",
"[",
"name",
"]",
"finally",
":",
"self",
".",
"_lock",
".",
"release",
"(",
")"
] | Clears (resets) a counter specified by its name.
:param name: a counter name to clear. | [
"Clears",
"(",
"resets",
")",
"a",
"counter",
"specified",
"by",
"its",
"name",
"."
] | train | https://github.com/pip-services3-python/pip-services3-components-python/blob/1de9c1bb544cf1891111e9a5f5d67653f62c9b52/pip_services3_components/count/CachedCounters.py#L72-L82 |
pip-services3-python/pip-services3-components-python | pip_services3_components/count/CachedCounters.py | CachedCounters.clear_all | def clear_all(self):
"""
Clears (resets) all counters.
"""
self._lock.acquire()
try:
self._cache = {}
self._updated = False
finally:
self._lock.release() | python | def clear_all(self):
"""
Clears (resets) all counters.
"""
self._lock.acquire()
try:
self._cache = {}
self._updated = False
finally:
self._lock.release() | [
"def",
"clear_all",
"(",
"self",
")",
":",
"self",
".",
"_lock",
".",
"acquire",
"(",
")",
"try",
":",
"self",
".",
"_cache",
"=",
"{",
"}",
"self",
".",
"_updated",
"=",
"False",
"finally",
":",
"self",
".",
"_lock",
".",
"release",
"(",
")"
] | Clears (resets) all counters. | [
"Clears",
"(",
"resets",
")",
"all",
"counters",
"."
] | train | https://github.com/pip-services3-python/pip-services3-components-python/blob/1de9c1bb544cf1891111e9a5f5d67653f62c9b52/pip_services3_components/count/CachedCounters.py#L85-L94 |
pip-services3-python/pip-services3-components-python | pip_services3_components/count/CachedCounters.py | CachedCounters.dump | def dump(self):
"""
Dumps (saves) the current values of counters.
"""
if self._updated:
messages = self.get_all()
self._save(messages)
self._lock.acquire()
try:
self._updated = False
current_time = time.perf... | python | def dump(self):
"""
Dumps (saves) the current values of counters.
"""
if self._updated:
messages = self.get_all()
self._save(messages)
self._lock.acquire()
try:
self._updated = False
current_time = time.perf... | [
"def",
"dump",
"(",
"self",
")",
":",
"if",
"self",
".",
"_updated",
":",
"messages",
"=",
"self",
".",
"get_all",
"(",
")",
"self",
".",
"_save",
"(",
"messages",
")",
"self",
".",
"_lock",
".",
"acquire",
"(",
")",
"try",
":",
"self",
".",
"_up... | Dumps (saves) the current values of counters. | [
"Dumps",
"(",
"saves",
")",
"the",
"current",
"values",
"of",
"counters",
"."
] | train | https://github.com/pip-services3-python/pip-services3-components-python/blob/1de9c1bb544cf1891111e9a5f5d67653f62c9b52/pip_services3_components/count/CachedCounters.py#L97-L111 |
pip-services3-python/pip-services3-components-python | pip_services3_components/count/CachedCounters.py | CachedCounters.get_all | def get_all(self):
"""
Gets all captured counters.
:return: a list with counters.
"""
self._lock.acquire()
try:
return list(self._cache.values())
finally:
self._lock.release() | python | def get_all(self):
"""
Gets all captured counters.
:return: a list with counters.
"""
self._lock.acquire()
try:
return list(self._cache.values())
finally:
self._lock.release() | [
"def",
"get_all",
"(",
"self",
")",
":",
"self",
".",
"_lock",
".",
"acquire",
"(",
")",
"try",
":",
"return",
"list",
"(",
"self",
".",
"_cache",
".",
"values",
"(",
")",
")",
"finally",
":",
"self",
".",
"_lock",
".",
"release",
"(",
")"
] | Gets all captured counters.
:return: a list with counters. | [
"Gets",
"all",
"captured",
"counters",
"."
] | train | https://github.com/pip-services3-python/pip-services3-components-python/blob/1de9c1bb544cf1891111e9a5f5d67653f62c9b52/pip_services3_components/count/CachedCounters.py#L129-L139 |
pip-services3-python/pip-services3-components-python | pip_services3_components/count/CachedCounters.py | CachedCounters.get | def get(self, name, typ):
"""
Gets a counter specified by its name.
It counter does not exist or its type doesn't match the specified type
it creates a new one.
:param name: a counter name to retrieve.
:param typ: a counter type.
:return: an existing or newly c... | python | def get(self, name, typ):
"""
Gets a counter specified by its name.
It counter does not exist or its type doesn't match the specified type
it creates a new one.
:param name: a counter name to retrieve.
:param typ: a counter type.
:return: an existing or newly c... | [
"def",
"get",
"(",
"self",
",",
"name",
",",
"typ",
")",
":",
"if",
"name",
"==",
"None",
"or",
"len",
"(",
"name",
")",
"==",
"0",
":",
"raise",
"Exception",
"(",
"\"Counter name was not set\"",
")",
"self",
".",
"_lock",
".",
"acquire",
"(",
")",
... | Gets a counter specified by its name.
It counter does not exist or its type doesn't match the specified type
it creates a new one.
:param name: a counter name to retrieve.
:param typ: a counter type.
:return: an existing or newly created counter of the specified type. | [
"Gets",
"a",
"counter",
"specified",
"by",
"its",
"name",
".",
"It",
"counter",
"does",
"not",
"exist",
"or",
"its",
"type",
"doesn",
"t",
"match",
"the",
"specified",
"type",
"it",
"creates",
"a",
"new",
"one",
"."
] | train | https://github.com/pip-services3-python/pip-services3-components-python/blob/1de9c1bb544cf1891111e9a5f5d67653f62c9b52/pip_services3_components/count/CachedCounters.py#L142-L167 |
pip-services3-python/pip-services3-components-python | pip_services3_components/count/CachedCounters.py | CachedCounters.end_timing | def end_timing(self, name, elapsed):
"""
Ends measurement of execution elapsed time and updates specified counter.
:param name: a counter name
:param elapsed: execution elapsed time in milliseconds to update the counter.
"""
counter = self.get(name, CounterType.Interval... | python | def end_timing(self, name, elapsed):
"""
Ends measurement of execution elapsed time and updates specified counter.
:param name: a counter name
:param elapsed: execution elapsed time in milliseconds to update the counter.
"""
counter = self.get(name, CounterType.Interval... | [
"def",
"end_timing",
"(",
"self",
",",
"name",
",",
"elapsed",
")",
":",
"counter",
"=",
"self",
".",
"get",
"(",
"name",
",",
"CounterType",
".",
"Interval",
")",
"self",
".",
"_calculate_stats",
"(",
"counter",
",",
"elapsed",
")",
"self",
".",
"_upd... | Ends measurement of execution elapsed time and updates specified counter.
:param name: a counter name
:param elapsed: execution elapsed time in milliseconds to update the counter. | [
"Ends",
"measurement",
"of",
"execution",
"elapsed",
"time",
"and",
"updates",
"specified",
"counter",
"."
] | train | https://github.com/pip-services3-python/pip-services3-components-python/blob/1de9c1bb544cf1891111e9a5f5d67653f62c9b52/pip_services3_components/count/CachedCounters.py#L194-L204 |
pip-services3-python/pip-services3-components-python | pip_services3_components/count/CachedCounters.py | CachedCounters.stats | def stats(self, name, value):
"""
Calculates min/average/max statistics based on the current and previous values.
:param name: a counter name of Statistics type
:param value: a value to update statistics
"""
counter = self.get(name, CounterType.Statistics)
self.... | python | def stats(self, name, value):
"""
Calculates min/average/max statistics based on the current and previous values.
:param name: a counter name of Statistics type
:param value: a value to update statistics
"""
counter = self.get(name, CounterType.Statistics)
self.... | [
"def",
"stats",
"(",
"self",
",",
"name",
",",
"value",
")",
":",
"counter",
"=",
"self",
".",
"get",
"(",
"name",
",",
"CounterType",
".",
"Statistics",
")",
"self",
".",
"_calculate_stats",
"(",
"counter",
",",
"value",
")",
"self",
".",
"_update",
... | Calculates min/average/max statistics based on the current and previous values.
:param name: a counter name of Statistics type
:param value: a value to update statistics | [
"Calculates",
"min",
"/",
"average",
"/",
"max",
"statistics",
"based",
"on",
"the",
"current",
"and",
"previous",
"values",
"."
] | train | https://github.com/pip-services3-python/pip-services3-components-python/blob/1de9c1bb544cf1891111e9a5f5d67653f62c9b52/pip_services3_components/count/CachedCounters.py#L207-L217 |
pip-services3-python/pip-services3-components-python | pip_services3_components/count/CachedCounters.py | CachedCounters.last | def last(self, name, value):
"""
Records the last calculated measurement value.
Usually this method is used by metrics calculated externally.
:param name: a counter name of Last type.
:param value: a last value to record.
"""
counter = self.get(name, CounterType... | python | def last(self, name, value):
"""
Records the last calculated measurement value.
Usually this method is used by metrics calculated externally.
:param name: a counter name of Last type.
:param value: a last value to record.
"""
counter = self.get(name, CounterType... | [
"def",
"last",
"(",
"self",
",",
"name",
",",
"value",
")",
":",
"counter",
"=",
"self",
".",
"get",
"(",
"name",
",",
"CounterType",
".",
"LastValue",
")",
"counter",
".",
"last",
"=",
"value",
"self",
".",
"_update",
"(",
")"
] | Records the last calculated measurement value.
Usually this method is used by metrics calculated externally.
:param name: a counter name of Last type.
:param value: a last value to record. | [
"Records",
"the",
"last",
"calculated",
"measurement",
"value",
".",
"Usually",
"this",
"method",
"is",
"used",
"by",
"metrics",
"calculated",
"externally",
"."
] | train | https://github.com/pip-services3-python/pip-services3-components-python/blob/1de9c1bb544cf1891111e9a5f5d67653f62c9b52/pip_services3_components/count/CachedCounters.py#L220-L231 |
pip-services3-python/pip-services3-components-python | pip_services3_components/count/CachedCounters.py | CachedCounters.timestamp | def timestamp(self, name, value):
"""
Records the given timestamp.
:param name: a counter name of Timestamp type.
:param value: a timestamp to record.
"""
counter = self.get(name, CounterType.Timestamp)
counter.time = value if value != None else datetime.datetim... | python | def timestamp(self, name, value):
"""
Records the given timestamp.
:param name: a counter name of Timestamp type.
:param value: a timestamp to record.
"""
counter = self.get(name, CounterType.Timestamp)
counter.time = value if value != None else datetime.datetim... | [
"def",
"timestamp",
"(",
"self",
",",
"name",
",",
"value",
")",
":",
"counter",
"=",
"self",
".",
"get",
"(",
"name",
",",
"CounterType",
".",
"Timestamp",
")",
"counter",
".",
"time",
"=",
"value",
"if",
"value",
"!=",
"None",
"else",
"datetime",
"... | Records the given timestamp.
:param name: a counter name of Timestamp type.
:param value: a timestamp to record. | [
"Records",
"the",
"given",
"timestamp",
"."
] | train | https://github.com/pip-services3-python/pip-services3-components-python/blob/1de9c1bb544cf1891111e9a5f5d67653f62c9b52/pip_services3_components/count/CachedCounters.py#L243-L253 |
pip-services3-python/pip-services3-components-python | pip_services3_components/count/CachedCounters.py | CachedCounters.increment | def increment(self, name, value):
"""
Increments counter by given value.
:param name: a counter name of Increment type.
:param value: a value to add to the counter.
"""
counter = self.get(name, CounterType.Increment)
counter.count = counter.count + value if coun... | python | def increment(self, name, value):
"""
Increments counter by given value.
:param name: a counter name of Increment type.
:param value: a value to add to the counter.
"""
counter = self.get(name, CounterType.Increment)
counter.count = counter.count + value if coun... | [
"def",
"increment",
"(",
"self",
",",
"name",
",",
"value",
")",
":",
"counter",
"=",
"self",
".",
"get",
"(",
"name",
",",
"CounterType",
".",
"Increment",
")",
"counter",
".",
"count",
"=",
"counter",
".",
"count",
"+",
"value",
"if",
"counter",
".... | Increments counter by given value.
:param name: a counter name of Increment type.
:param value: a value to add to the counter. | [
"Increments",
"counter",
"by",
"given",
"value",
"."
] | train | https://github.com/pip-services3-python/pip-services3-components-python/blob/1de9c1bb544cf1891111e9a5f5d67653f62c9b52/pip_services3_components/count/CachedCounters.py#L265-L275 |
lambdalisue/maidenhair | src/maidenhair/parsers/base.py | BaseParser.load | def load(self, filename, **kwargs):
"""
Parse a file specified with the filename and return an numpy array
Parameters
----------
filename : string
A path of a file
Returns
-------
ndarray
An instance of numpy array
... | python | def load(self, filename, **kwargs):
"""
Parse a file specified with the filename and return an numpy array
Parameters
----------
filename : string
A path of a file
Returns
-------
ndarray
An instance of numpy array
... | [
"def",
"load",
"(",
"self",
",",
"filename",
",",
"*",
"*",
"kwargs",
")",
":",
"with",
"open",
"(",
"filename",
",",
"'r'",
")",
"as",
"f",
":",
"return",
"self",
".",
"parse",
"(",
"f",
",",
"*",
"*",
"kwargs",
")"
] | Parse a file specified with the filename and return an numpy array
Parameters
----------
filename : string
A path of a file
Returns
-------
ndarray
An instance of numpy array | [
"Parse",
"a",
"file",
"specified",
"with",
"the",
"filename",
"and",
"return",
"an",
"numpy",
"array"
] | train | https://github.com/lambdalisue/maidenhair/blob/d5095c1087d1f4d71cc57410492151d2803a9f0d/src/maidenhair/parsers/base.py#L33-L49 |
madisona/django-image-helper | image_helper/fields.py | _get_thumbnail_filename | def _get_thumbnail_filename(filename, append_text="-thumbnail"):
"""
Returns a thumbnail version of the file name.
"""
name, ext = os.path.splitext(filename)
return ''.join([name, append_text, ext]) | python | def _get_thumbnail_filename(filename, append_text="-thumbnail"):
"""
Returns a thumbnail version of the file name.
"""
name, ext = os.path.splitext(filename)
return ''.join([name, append_text, ext]) | [
"def",
"_get_thumbnail_filename",
"(",
"filename",
",",
"append_text",
"=",
"\"-thumbnail\"",
")",
":",
"name",
",",
"ext",
"=",
"os",
".",
"path",
".",
"splitext",
"(",
"filename",
")",
"return",
"''",
".",
"join",
"(",
"[",
"name",
",",
"append_text",
... | Returns a thumbnail version of the file name. | [
"Returns",
"a",
"thumbnail",
"version",
"of",
"the",
"file",
"name",
"."
] | train | https://github.com/madisona/django-image-helper/blob/2dbad297486bf5e50d86f12f85e51da31e50ac22/image_helper/fields.py#L16-L21 |
madisona/django-image-helper | image_helper/fields.py | SizedImageField._get_resize_options | def _get_resize_options(self, dimensions):
"""
:param dimensions:
A tuple of (width, height, force_size).
'force_size' can be left off and will default to False.
"""
if dimensions and isinstance(dimensions, (tuple, list)):
if len(dimensions) < 3:
... | python | def _get_resize_options(self, dimensions):
"""
:param dimensions:
A tuple of (width, height, force_size).
'force_size' can be left off and will default to False.
"""
if dimensions and isinstance(dimensions, (tuple, list)):
if len(dimensions) < 3:
... | [
"def",
"_get_resize_options",
"(",
"self",
",",
"dimensions",
")",
":",
"if",
"dimensions",
"and",
"isinstance",
"(",
"dimensions",
",",
"(",
"tuple",
",",
"list",
")",
")",
":",
"if",
"len",
"(",
"dimensions",
")",
"<",
"3",
":",
"dimensions",
"=",
"t... | :param dimensions:
A tuple of (width, height, force_size).
'force_size' can be left off and will default to False. | [
":",
"param",
"dimensions",
":",
"A",
"tuple",
"of",
"(",
"width",
"height",
"force_size",
")",
".",
"force_size",
"can",
"be",
"left",
"off",
"and",
"will",
"default",
"to",
"False",
"."
] | train | https://github.com/madisona/django-image-helper/blob/2dbad297486bf5e50d86f12f85e51da31e50ac22/image_helper/fields.py#L86-L95 |
madisona/django-image-helper | image_helper/fields.py | SizedImageField.contribute_to_class | def contribute_to_class(self, cls, name):
"""
Makes sure thumbnail gets set when image field initialized.
"""
super(SizedImageField, self).contribute_to_class(cls, name)
signals.post_init.connect(self._set_thumbnail, sender=cls) | python | def contribute_to_class(self, cls, name):
"""
Makes sure thumbnail gets set when image field initialized.
"""
super(SizedImageField, self).contribute_to_class(cls, name)
signals.post_init.connect(self._set_thumbnail, sender=cls) | [
"def",
"contribute_to_class",
"(",
"self",
",",
"cls",
",",
"name",
")",
":",
"super",
"(",
"SizedImageField",
",",
"self",
")",
".",
"contribute_to_class",
"(",
"cls",
",",
"name",
")",
"signals",
".",
"post_init",
".",
"connect",
"(",
"self",
".",
"_se... | Makes sure thumbnail gets set when image field initialized. | [
"Makes",
"sure",
"thumbnail",
"gets",
"set",
"when",
"image",
"field",
"initialized",
"."
] | train | https://github.com/madisona/django-image-helper/blob/2dbad297486bf5e50d86f12f85e51da31e50ac22/image_helper/fields.py#L97-L102 |
madisona/django-image-helper | image_helper/fields.py | SizedImageField.pre_save | def pre_save(self, model_instance, add):
"""
Resizes, commits image to storage, and returns field's value just before saving.
"""
file = getattr(model_instance, self.attname)
if file and not file._committed:
file.name = self._clean_file_name(model_instance, file.name)... | python | def pre_save(self, model_instance, add):
"""
Resizes, commits image to storage, and returns field's value just before saving.
"""
file = getattr(model_instance, self.attname)
if file and not file._committed:
file.name = self._clean_file_name(model_instance, file.name)... | [
"def",
"pre_save",
"(",
"self",
",",
"model_instance",
",",
"add",
")",
":",
"file",
"=",
"getattr",
"(",
"model_instance",
",",
"self",
".",
"attname",
")",
"if",
"file",
"and",
"not",
"file",
".",
"_committed",
":",
"file",
".",
"name",
"=",
"self",
... | Resizes, commits image to storage, and returns field's value just before saving. | [
"Resizes",
"commits",
"image",
"to",
"storage",
"and",
"returns",
"field",
"s",
"value",
"just",
"before",
"saving",
"."
] | train | https://github.com/madisona/django-image-helper/blob/2dbad297486bf5e50d86f12f85e51da31e50ac22/image_helper/fields.py#L104-L113 |
madisona/django-image-helper | image_helper/fields.py | SizedImageField._clean_file_name | def _clean_file_name(self, model_instance, filename):
"""
We need to make sure we know the full file name before we save the thumbnail so
we can be sure the name doesn't change on save.
This method gets the available filename and returns just the file part.
"""
available... | python | def _clean_file_name(self, model_instance, filename):
"""
We need to make sure we know the full file name before we save the thumbnail so
we can be sure the name doesn't change on save.
This method gets the available filename and returns just the file part.
"""
available... | [
"def",
"_clean_file_name",
"(",
"self",
",",
"model_instance",
",",
"filename",
")",
":",
"available_name",
"=",
"self",
".",
"storage",
".",
"get_available_name",
"(",
"self",
".",
"generate_filename",
"(",
"model_instance",
",",
"filename",
")",
")",
"return",... | We need to make sure we know the full file name before we save the thumbnail so
we can be sure the name doesn't change on save.
This method gets the available filename and returns just the file part. | [
"We",
"need",
"to",
"make",
"sure",
"we",
"know",
"the",
"full",
"file",
"name",
"before",
"we",
"save",
"the",
"thumbnail",
"so",
"we",
"can",
"be",
"sure",
"the",
"name",
"doesn",
"t",
"change",
"on",
"save",
"."
] | train | https://github.com/madisona/django-image-helper/blob/2dbad297486bf5e50d86f12f85e51da31e50ac22/image_helper/fields.py#L115-L124 |
madisona/django-image-helper | image_helper/fields.py | SizedImageField._create_thumbnail | def _create_thumbnail(self, model_instance, thumbnail, image_name):
"""
Resizes and saves the thumbnail image
"""
thumbnail = self._do_resize(thumbnail, self.thumbnail_size)
full_image_name = self.generate_filename(model_instance, image_name)
thumbnail_filename = _get_thu... | python | def _create_thumbnail(self, model_instance, thumbnail, image_name):
"""
Resizes and saves the thumbnail image
"""
thumbnail = self._do_resize(thumbnail, self.thumbnail_size)
full_image_name = self.generate_filename(model_instance, image_name)
thumbnail_filename = _get_thu... | [
"def",
"_create_thumbnail",
"(",
"self",
",",
"model_instance",
",",
"thumbnail",
",",
"image_name",
")",
":",
"thumbnail",
"=",
"self",
".",
"_do_resize",
"(",
"thumbnail",
",",
"self",
".",
"thumbnail_size",
")",
"full_image_name",
"=",
"self",
".",
"generat... | Resizes and saves the thumbnail image | [
"Resizes",
"and",
"saves",
"the",
"thumbnail",
"image"
] | train | https://github.com/madisona/django-image-helper/blob/2dbad297486bf5e50d86f12f85e51da31e50ac22/image_helper/fields.py#L126-L134 |
madisona/django-image-helper | image_helper/fields.py | SizedImageField._set_thumbnail | def _set_thumbnail(self, instance=None, **kwargs):
"""
Sets a `thumbnail` attribute on the image field class.
On thumbnail you can access name, url, path attributes
"""
image_field = getattr(instance, self.name)
if image_field:
thumbnail_filename = _get_thumbn... | python | def _set_thumbnail(self, instance=None, **kwargs):
"""
Sets a `thumbnail` attribute on the image field class.
On thumbnail you can access name, url, path attributes
"""
image_field = getattr(instance, self.name)
if image_field:
thumbnail_filename = _get_thumbn... | [
"def",
"_set_thumbnail",
"(",
"self",
",",
"instance",
"=",
"None",
",",
"*",
"*",
"kwargs",
")",
":",
"image_field",
"=",
"getattr",
"(",
"instance",
",",
"self",
".",
"name",
")",
"if",
"image_field",
":",
"thumbnail_filename",
"=",
"_get_thumbnail_filenam... | Sets a `thumbnail` attribute on the image field class.
On thumbnail you can access name, url, path attributes | [
"Sets",
"a",
"thumbnail",
"attribute",
"on",
"the",
"image",
"field",
"class",
".",
"On",
"thumbnail",
"you",
"can",
"access",
"name",
"url",
"path",
"attributes"
] | train | https://github.com/madisona/django-image-helper/blob/2dbad297486bf5e50d86f12f85e51da31e50ac22/image_helper/fields.py#L160-L170 |
madisona/django-image-helper | image_helper/fields.py | SizedImageField._get_simple_uploaded_file | def _get_simple_uploaded_file(self, image, file_name):
"""
:param image:
a python PIL ``Image`` instance.
:param file_name:
The file name of the image.
:returns:
A django ``SimpleUploadedFile`` instance ready to be saved.
"""
extensio... | python | def _get_simple_uploaded_file(self, image, file_name):
"""
:param image:
a python PIL ``Image`` instance.
:param file_name:
The file name of the image.
:returns:
A django ``SimpleUploadedFile`` instance ready to be saved.
"""
extensio... | [
"def",
"_get_simple_uploaded_file",
"(",
"self",
",",
"image",
",",
"file_name",
")",
":",
"extension",
"=",
"os",
".",
"path",
".",
"splitext",
"(",
"file_name",
")",
"[",
"1",
"]",
"mimetype",
",",
"encoding",
"=",
"mimetypes",
".",
"guess_type",
"(",
... | :param image:
a python PIL ``Image`` instance.
:param file_name:
The file name of the image.
:returns:
A django ``SimpleUploadedFile`` instance ready to be saved. | [
":",
"param",
"image",
":",
"a",
"python",
"PIL",
"Image",
"instance",
"."
] | train | https://github.com/madisona/django-image-helper/blob/2dbad297486bf5e50d86f12f85e51da31e50ac22/image_helper/fields.py#L172-L197 |
GemHQ/round-py | round/applications.py | Applications.create | def create(self, **kwargs):
"""Create a new Application.
Args:
**kwargs: Arbitrary keyword arguments, including:
name (str): A name for the new Application.
Returns:
A round.Application object if successful.
"""
resource = self.resource.create(kwa... | python | def create(self, **kwargs):
"""Create a new Application.
Args:
**kwargs: Arbitrary keyword arguments, including:
name (str): A name for the new Application.
Returns:
A round.Application object if successful.
"""
resource = self.resource.create(kwa... | [
"def",
"create",
"(",
"self",
",",
"*",
"*",
"kwargs",
")",
":",
"resource",
"=",
"self",
".",
"resource",
".",
"create",
"(",
"kwargs",
")",
"if",
"'admin_token'",
"in",
"kwargs",
":",
"resource",
".",
"context",
".",
"authorize",
"(",
"'Gem-Application... | Create a new Application.
Args:
**kwargs: Arbitrary keyword arguments, including:
name (str): A name for the new Application.
Returns:
A round.Application object if successful. | [
"Create",
"a",
"new",
"Application",
"."
] | train | https://github.com/GemHQ/round-py/blob/d0838f849cd260b1eb5df67ed3c6f2fe56c91c21/round/applications.py#L21-L37 |
GemHQ/round-py | round/applications.py | Application.get_mfa | def get_mfa(self):
"""Return the currently-valid MFA token for this application."""
token = str(self.totp.now())
# PyOTP doesn't pre-pad tokens shorter than 6 characters
# ROTP does, so we have to.
while len(token) < 6:
token = '0{}'.format(token)
return token | python | def get_mfa(self):
"""Return the currently-valid MFA token for this application."""
token = str(self.totp.now())
# PyOTP doesn't pre-pad tokens shorter than 6 characters
# ROTP does, so we have to.
while len(token) < 6:
token = '0{}'.format(token)
return token | [
"def",
"get_mfa",
"(",
"self",
")",
":",
"token",
"=",
"str",
"(",
"self",
".",
"totp",
".",
"now",
"(",
")",
")",
"# PyOTP doesn't pre-pad tokens shorter than 6 characters",
"# ROTP does, so we have to.",
"while",
"len",
"(",
"token",
")",
"<",
"6",
":",
"tok... | Return the currently-valid MFA token for this application. | [
"Return",
"the",
"currently",
"-",
"valid",
"MFA",
"token",
"for",
"this",
"application",
"."
] | train | https://github.com/GemHQ/round-py/blob/d0838f849cd260b1eb5df67ed3c6f2fe56c91c21/round/applications.py#L63-L70 |
GemHQ/round-py | round/applications.py | Application.reset | def reset(self, *args):
"""Resets any of the tokens for this Application.
Note that you may have to reauthenticate afterwards.
Usage:
application.reset('api_token')
application.reset('api_token', 'totp_secret')
Args:
*args (list of str): one or more of
... | python | def reset(self, *args):
"""Resets any of the tokens for this Application.
Note that you may have to reauthenticate afterwards.
Usage:
application.reset('api_token')
application.reset('api_token', 'totp_secret')
Args:
*args (list of str): one or more of
... | [
"def",
"reset",
"(",
"self",
",",
"*",
"args",
")",
":",
"self",
".",
"resource",
"=",
"self",
".",
"resource",
".",
"reset",
"(",
"list",
"(",
"args",
")",
")",
"return",
"self"
] | Resets any of the tokens for this Application.
Note that you may have to reauthenticate afterwards.
Usage:
application.reset('api_token')
application.reset('api_token', 'totp_secret')
Args:
*args (list of str): one or more of
['api_token', 'subscriptio... | [
"Resets",
"any",
"of",
"the",
"tokens",
"for",
"this",
"Application",
".",
"Note",
"that",
"you",
"may",
"have",
"to",
"reauthenticate",
"afterwards",
"."
] | train | https://github.com/GemHQ/round-py/blob/d0838f849cd260b1eb5df67ed3c6f2fe56c91c21/round/applications.py#L72-L88 |
GemHQ/round-py | round/applications.py | Application.get_users | def get_users(self, fetch=True):
"""Return this Applications's users object, populating it if fetch
is True."""
return Users(self.resource.users, self.client, populate=fetch) | python | def get_users(self, fetch=True):
"""Return this Applications's users object, populating it if fetch
is True."""
return Users(self.resource.users, self.client, populate=fetch) | [
"def",
"get_users",
"(",
"self",
",",
"fetch",
"=",
"True",
")",
":",
"return",
"Users",
"(",
"self",
".",
"resource",
".",
"users",
",",
"self",
".",
"client",
",",
"populate",
"=",
"fetch",
")"
] | Return this Applications's users object, populating it if fetch
is True. | [
"Return",
"this",
"Applications",
"s",
"users",
"object",
"populating",
"it",
"if",
"fetch",
"is",
"True",
"."
] | train | https://github.com/GemHQ/round-py/blob/d0838f849cd260b1eb5df67ed3c6f2fe56c91c21/round/applications.py#L96-L99 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.