repo stringlengths 7 55 | path stringlengths 4 223 | url stringlengths 87 315 | code stringlengths 75 104k | code_tokens list | docstring stringlengths 1 46.9k | docstring_tokens list | language stringclasses 1
value | partition stringclasses 3
values | avg_line_len float64 7.91 980 |
|---|---|---|---|---|---|---|---|---|---|
formwork-io/lazarus | lazarus/__init__.py | https://github.com/formwork-io/lazarus/blob/b2b6120fe06d69c23b4f41d55b6d71860a9fdeaa/lazarus/__init__.py#L119-L210 | def default(restart_cb=None, restart_func=None, close_fds=True):
'''Sets up lazarus in default mode.
See the :py:func:`custom` function for a more powerful mode of use.
The default mode of lazarus is to watch all modules rooted at
``PYTHONPATH`` for changes and restart when they take place.
Keywo... | [
"def",
"default",
"(",
"restart_cb",
"=",
"None",
",",
"restart_func",
"=",
"None",
",",
"close_fds",
"=",
"True",
")",
":",
"if",
"_active",
":",
"msg",
"=",
"'lazarus is already active'",
"raise",
"RuntimeWarning",
"(",
"msg",
")",
"_python_path",
"=",
"os... | Sets up lazarus in default mode.
See the :py:func:`custom` function for a more powerful mode of use.
The default mode of lazarus is to watch all modules rooted at
``PYTHONPATH`` for changes and restart when they take place.
Keyword arguments:
restart_cb -- Callback invoked prior to restartin... | [
"Sets",
"up",
"lazarus",
"in",
"default",
"mode",
"."
] | python | train | 28.858696 |
juiceinc/recipe | recipe/shelf.py | https://github.com/juiceinc/recipe/blob/2e60c2242aeaea3029a2274b31bc3a937761e568/recipe/shelf.py#L774-L784 | def introspect_table(table):
"""Given a SQLAlchemy Table object, return a Shelf description suitable
for passing to Shelf.from_config.
"""
d = {}
for c in table.columns:
if isinstance(c.type, String):
d[c.name] = {'kind': 'Dimension', 'field': c.name}
if isinstance(c.type... | [
"def",
"introspect_table",
"(",
"table",
")",
":",
"d",
"=",
"{",
"}",
"for",
"c",
"in",
"table",
".",
"columns",
":",
"if",
"isinstance",
"(",
"c",
".",
"type",
",",
"String",
")",
":",
"d",
"[",
"c",
".",
"name",
"]",
"=",
"{",
"'kind'",
":",... | Given a SQLAlchemy Table object, return a Shelf description suitable
for passing to Shelf.from_config. | [
"Given",
"a",
"SQLAlchemy",
"Table",
"object",
"return",
"a",
"Shelf",
"description",
"suitable",
"for",
"passing",
"to",
"Shelf",
".",
"from_config",
"."
] | python | train | 36.636364 |
FactoryBoy/factory_boy | factory/base.py | https://github.com/FactoryBoy/factory_boy/blob/edaa7c7f5a14065b229927903bd7989cc93cd069/factory/base.py#L342-L366 | def _check_parameter_dependencies(self, parameters):
"""Find out in what order parameters should be called."""
# Warning: parameters only provide reverse dependencies; we reverse them into standard dependencies.
# deep_revdeps: set of fields a field depend indirectly upon
deep_revdeps = ... | [
"def",
"_check_parameter_dependencies",
"(",
"self",
",",
"parameters",
")",
":",
"# Warning: parameters only provide reverse dependencies; we reverse them into standard dependencies.",
"# deep_revdeps: set of fields a field depend indirectly upon",
"deep_revdeps",
"=",
"collections",
".",... | Find out in what order parameters should be called. | [
"Find",
"out",
"in",
"what",
"order",
"parameters",
"should",
"be",
"called",
"."
] | python | train | 49.16 |
icometrix/dicom2nifti | dicom2nifti/compressed_dicom.py | https://github.com/icometrix/dicom2nifti/blob/1462ae5dd979fa3f276fe7a78ceb9b028121536f/dicom2nifti/compressed_dicom.py#L119-L127 | def _decompress_dicom(dicom_file, output_file):
"""
This function can be used to convert a jpeg compressed image to an uncompressed one for further conversion
:param input_file: single dicom file to decompress
"""
gdcmconv_executable = _get_gdcmconv()
subprocess.check_output([gdcmconv_executab... | [
"def",
"_decompress_dicom",
"(",
"dicom_file",
",",
"output_file",
")",
":",
"gdcmconv_executable",
"=",
"_get_gdcmconv",
"(",
")",
"subprocess",
".",
"check_output",
"(",
"[",
"gdcmconv_executable",
",",
"'-w'",
",",
"dicom_file",
",",
"output_file",
"]",
")"
] | This function can be used to convert a jpeg compressed image to an uncompressed one for further conversion
:param input_file: single dicom file to decompress | [
"This",
"function",
"can",
"be",
"used",
"to",
"convert",
"a",
"jpeg",
"compressed",
"image",
"to",
"an",
"uncompressed",
"one",
"for",
"further",
"conversion"
] | python | train | 38.555556 |
jaredLunde/redis_structures | redis_structures/__init__.py | https://github.com/jaredLunde/redis_structures/blob/b9cce5f5c85db5e12c292633ff8d04e3ae053294/redis_structures/__init__.py#L2126-L2147 | def iter(self, start=0, stop=-1, withscores=False, reverse=None):
""" Return a range of values from sorted set name between
@start and @end sorted in ascending order unless @reverse or
:prop:reversed.
@start and @end: #int, can be negative, indicating the end of
... | [
"def",
"iter",
"(",
"self",
",",
"start",
"=",
"0",
",",
"stop",
"=",
"-",
"1",
",",
"withscores",
"=",
"False",
",",
"reverse",
"=",
"None",
")",
":",
"reverse",
"=",
"reverse",
"if",
"reverse",
"is",
"not",
"None",
"else",
"self",
".",
"reversed"... | Return a range of values from sorted set name between
@start and @end sorted in ascending order unless @reverse or
:prop:reversed.
@start and @end: #int, can be negative, indicating the end of
the range.
@withscores: #bool indicates to return the scores a... | [
"Return",
"a",
"range",
"of",
"values",
"from",
"sorted",
"set",
"name",
"between",
"@start",
"and",
"@end",
"sorted",
"in",
"ascending",
"order",
"unless",
"@reverse",
"or",
":",
"prop",
":",
"reversed",
"."
] | python | train | 46.454545 |
lrq3000/pyFileFixity | pyFileFixity/lib/profilers/visual/pympler/web.py | https://github.com/lrq3000/pyFileFixity/blob/fd5ef23bb13835faf1e3baa773619b86a1cc9bdf/pyFileFixity/lib/profilers/visual/pympler/web.py#L107-L111 | def process():
"""Get process overview."""
pmi = ProcessMemoryInfo()
threads = get_current_threads()
return dict(info=pmi, threads=threads) | [
"def",
"process",
"(",
")",
":",
"pmi",
"=",
"ProcessMemoryInfo",
"(",
")",
"threads",
"=",
"get_current_threads",
"(",
")",
"return",
"dict",
"(",
"info",
"=",
"pmi",
",",
"threads",
"=",
"threads",
")"
] | Get process overview. | [
"Get",
"process",
"overview",
"."
] | python | train | 30.2 |
pypa/pipenv | pipenv/vendor/requests/cookies.py | https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/vendor/requests/cookies.py#L201-L216 | def set(self, name, value, **kwargs):
"""Dict-like set() that also supports optional domain and path args in
order to resolve naming collisions from using one cookie jar over
multiple domains.
"""
# support client code that unsets cookies by assignment of a None value:
if... | [
"def",
"set",
"(",
"self",
",",
"name",
",",
"value",
",",
"*",
"*",
"kwargs",
")",
":",
"# support client code that unsets cookies by assignment of a None value:",
"if",
"value",
"is",
"None",
":",
"remove_cookie_by_name",
"(",
"self",
",",
"name",
",",
"domain",... | Dict-like set() that also supports optional domain and path args in
order to resolve naming collisions from using one cookie jar over
multiple domains. | [
"Dict",
"-",
"like",
"set",
"()",
"that",
"also",
"supports",
"optional",
"domain",
"and",
"path",
"args",
"in",
"order",
"to",
"resolve",
"naming",
"collisions",
"from",
"using",
"one",
"cookie",
"jar",
"over",
"multiple",
"domains",
"."
] | python | train | 39.3125 |
thombashi/SimpleSQLite | simplesqlite/core.py | https://github.com/thombashi/SimpleSQLite/blob/b16f212132b9b98773e68bf7395abc2f60f56fe5/simplesqlite/core.py#L447-L469 | def select_as_dict(self, table_name, columns=None, where=None, extra=None):
"""
Get data in the database and return fetched data as a
|OrderedDict| list.
:param str table_name: |arg_select_table_name|
:param list columns: |arg_select_as_xx_columns|
:param where: |arg_sel... | [
"def",
"select_as_dict",
"(",
"self",
",",
"table_name",
",",
"columns",
"=",
"None",
",",
"where",
"=",
"None",
",",
"extra",
"=",
"None",
")",
":",
"return",
"self",
".",
"select_as_tabledata",
"(",
"table_name",
",",
"columns",
",",
"where",
",",
"ext... | Get data in the database and return fetched data as a
|OrderedDict| list.
:param str table_name: |arg_select_table_name|
:param list columns: |arg_select_as_xx_columns|
:param where: |arg_select_where|
:type where: |arg_where_type|
:param str extra: |arg_select_extra|
... | [
"Get",
"data",
"in",
"the",
"database",
"and",
"return",
"fetched",
"data",
"as",
"a",
"|OrderedDict|",
"list",
"."
] | python | train | 40.217391 |
opengisch/pum | pum/core/upgrader.py | https://github.com/opengisch/pum/blob/eaf6af92d723ace60b9e982d7f69b98e00606959/pum/core/upgrader.py#L156-L173 | def __run_pre_all(self):
"""Execute the pre-all.py and pre-all.sql files if they exist"""
# if the list of delta dirs is [delta1, delta2] the pre scripts of delta2 are
# executed before the pre scripts of delta1
for d in reversed(self.dirs):
pre_all_py_path = os.path.join(d... | [
"def",
"__run_pre_all",
"(",
"self",
")",
":",
"# if the list of delta dirs is [delta1, delta2] the pre scripts of delta2 are",
"# executed before the pre scripts of delta1",
"for",
"d",
"in",
"reversed",
"(",
"self",
".",
"dirs",
")",
":",
"pre_all_py_path",
"=",
"os",
"."... | Execute the pre-all.py and pre-all.sql files if they exist | [
"Execute",
"the",
"pre",
"-",
"all",
".",
"py",
"and",
"pre",
"-",
"all",
".",
"sql",
"files",
"if",
"they",
"exist"
] | python | train | 43.111111 |
glue-viz/glue-vispy-viewers | glue_vispy_viewers/extern/vispy/gloo/glir.py | https://github.com/glue-viz/glue-vispy-viewers/blob/54a4351d98c1f90dfb1a557d1b447c1f57470eea/glue_vispy_viewers/extern/vispy/gloo/glir.py#L705-L731 | def _get_error(self, code, errors, indentation=0):
"""Get error and show the faulty line + some context
Other GLIR implementations may omit this.
"""
# Init
results = []
lines = None
if code is not None:
lines = [line.strip() for line in code.split('\n... | [
"def",
"_get_error",
"(",
"self",
",",
"code",
",",
"errors",
",",
"indentation",
"=",
"0",
")",
":",
"# Init",
"results",
"=",
"[",
"]",
"lines",
"=",
"None",
"if",
"code",
"is",
"not",
"None",
":",
"lines",
"=",
"[",
"line",
".",
"strip",
"(",
... | Get error and show the faulty line + some context
Other GLIR implementations may omit this. | [
"Get",
"error",
"and",
"show",
"the",
"faulty",
"line",
"+",
"some",
"context",
"Other",
"GLIR",
"implementations",
"may",
"omit",
"this",
"."
] | python | train | 36.925926 |
DataONEorg/d1_python | client_cli/src/d1_cli/impl/command_parser.py | https://github.com/DataONEorg/d1_python/blob/3ac4d4f3ca052d3e8641a6a329cab526c8ddcb0d/client_cli/src/d1_cli/impl/command_parser.py#L419-L428 | def do_archive(self, line):
"""archive <identifier> [identifier ...] Mark one or more existing Science
Objects as archived."""
pids = self._split_args(line, 1, -1)
self._command_processor.science_object_archive(pids)
self._print_info_if_verbose(
"Added archive operati... | [
"def",
"do_archive",
"(",
"self",
",",
"line",
")",
":",
"pids",
"=",
"self",
".",
"_split_args",
"(",
"line",
",",
"1",
",",
"-",
"1",
")",
"self",
".",
"_command_processor",
".",
"science_object_archive",
"(",
"pids",
")",
"self",
".",
"_print_info_if_... | archive <identifier> [identifier ...] Mark one or more existing Science
Objects as archived. | [
"archive",
"<identifier",
">",
"[",
"identifier",
"...",
"]",
"Mark",
"one",
"or",
"more",
"existing",
"Science",
"Objects",
"as",
"archived",
"."
] | python | train | 41.4 |
hotdoc/hotdoc | hotdoc/extensions/c/clang/cindex.py | https://github.com/hotdoc/hotdoc/blob/1067cdc8482b585b364a38fb52ca5d904e486280/hotdoc/extensions/c/clang/cindex.py#L1641-L1646 | def lexical_parent(self):
"""Return the lexical parent for this cursor."""
if not hasattr(self, '_lexical_parent'):
self._lexical_parent = conf.lib.clang_getCursorLexicalParent(self)
return self._lexical_parent | [
"def",
"lexical_parent",
"(",
"self",
")",
":",
"if",
"not",
"hasattr",
"(",
"self",
",",
"'_lexical_parent'",
")",
":",
"self",
".",
"_lexical_parent",
"=",
"conf",
".",
"lib",
".",
"clang_getCursorLexicalParent",
"(",
"self",
")",
"return",
"self",
".",
... | Return the lexical parent for this cursor. | [
"Return",
"the",
"lexical",
"parent",
"for",
"this",
"cursor",
"."
] | python | train | 40.333333 |
OCA/knowledge | document_page_approval/models/document_page_history.py | https://github.com/OCA/knowledge/blob/77fa06019c989b56ce34839e9f6343577184223a/document_page_approval/models/document_page_history.py#L95-L129 | def action_approve(self):
"""Set a change request as approved."""
for rec in self:
if rec.state not in ['draft', 'to approve']:
raise UserError(
_("Can't approve page in '%s' state.") % rec.state)
if not rec.am_i_approver:
raise... | [
"def",
"action_approve",
"(",
"self",
")",
":",
"for",
"rec",
"in",
"self",
":",
"if",
"rec",
".",
"state",
"not",
"in",
"[",
"'draft'",
",",
"'to approve'",
"]",
":",
"raise",
"UserError",
"(",
"_",
"(",
"\"Can't approve page in '%s' state.\"",
")",
"%",
... | Set a change request as approved. | [
"Set",
"a",
"change",
"request",
"as",
"approved",
"."
] | python | train | 40.057143 |
googleapis/google-cloud-python | bigtable/google/cloud/bigtable/row_set.py | https://github.com/googleapis/google-cloud-python/blob/85e80125a59cb10f8cb105f25ecc099e4b940b50/bigtable/google/cloud/bigtable/row_set.py#L112-L123 | def _update_message_request(self, message):
"""Add row keys and row range to given request message
:type message: class:`data_messages_v2_pb2.ReadRowsRequest`
:param message: The ``ReadRowsRequest`` protobuf
"""
for each in self.row_keys:
message.rows.row_keys.append... | [
"def",
"_update_message_request",
"(",
"self",
",",
"message",
")",
":",
"for",
"each",
"in",
"self",
".",
"row_keys",
":",
"message",
".",
"rows",
".",
"row_keys",
".",
"append",
"(",
"_to_bytes",
"(",
"each",
")",
")",
"for",
"each",
"in",
"self",
".... | Add row keys and row range to given request message
:type message: class:`data_messages_v2_pb2.ReadRowsRequest`
:param message: The ``ReadRowsRequest`` protobuf | [
"Add",
"row",
"keys",
"and",
"row",
"range",
"to",
"given",
"request",
"message"
] | python | train | 38.583333 |
lmjohns3/theanets | theanets/trainer.py | https://github.com/lmjohns3/theanets/blob/79db9f878ef2071f2f576a1cf5d43a752a55894a/theanets/trainer.py#L93-L158 | def itertrain(self, train, valid=None, **kwargs):
'''Train a model using a training and validation set.
This method yields a series of monitor values to the caller. After every
iteration, a pair of monitor dictionaries is generated: one evaluated on
the training dataset, and another eva... | [
"def",
"itertrain",
"(",
"self",
",",
"train",
",",
"valid",
"=",
"None",
",",
"*",
"*",
"kwargs",
")",
":",
"ifci",
"=",
"itertools",
".",
"chain",
".",
"from_iterable",
"def",
"first",
"(",
"x",
")",
":",
"return",
"x",
"[",
"0",
"]",
"if",
"is... | Train a model using a training and validation set.
This method yields a series of monitor values to the caller. After every
iteration, a pair of monitor dictionaries is generated: one evaluated on
the training dataset, and another evaluated on the validation dataset.
The validation moni... | [
"Train",
"a",
"model",
"using",
"a",
"training",
"and",
"validation",
"set",
"."
] | python | test | 42.484848 |
tmux-python/libtmux | libtmux/window.py | https://github.com/tmux-python/libtmux/blob/8eb2f8bbea3a025c1567b1516653414dbc24e1fc/libtmux/window.py#L153-L187 | def set_window_option(self, option, value):
"""
Wrapper for ``$ tmux set-window-option <option> <value>``.
Parameters
----------
option : str
option to set, e.g. 'aggressive-resize'
value : str
window option value. True/False will turn in 'on' and... | [
"def",
"set_window_option",
"(",
"self",
",",
"option",
",",
"value",
")",
":",
"self",
".",
"server",
".",
"_update_windows",
"(",
")",
"if",
"isinstance",
"(",
"value",
",",
"bool",
")",
"and",
"value",
":",
"value",
"=",
"'on'",
"elif",
"isinstance",
... | Wrapper for ``$ tmux set-window-option <option> <value>``.
Parameters
----------
option : str
option to set, e.g. 'aggressive-resize'
value : str
window option value. True/False will turn in 'on' and 'off',
also accepts string of 'on' or 'off' directl... | [
"Wrapper",
"for",
"$",
"tmux",
"set",
"-",
"window",
"-",
"option",
"<option",
">",
"<value",
">",
"."
] | python | train | 28.942857 |
tariqdaouda/pyGeno | pyGeno/Exon.py | https://github.com/tariqdaouda/pyGeno/blob/474b1250bf78ce5c7e7c3bbbfdbad9635d5a7d14/pyGeno/Exon.py#L152-L161 | def previousExon(self) :
"""Returns the previous exon of the transcript, or None if there is none"""
if self.number == 0 :
return None
try :
return self.transcript.exons[self.number-1]
except IndexError :
return None | [
"def",
"previousExon",
"(",
"self",
")",
":",
"if",
"self",
".",
"number",
"==",
"0",
":",
"return",
"None",
"try",
":",
"return",
"self",
".",
"transcript",
".",
"exons",
"[",
"self",
".",
"number",
"-",
"1",
"]",
"except",
"IndexError",
":",
"retur... | Returns the previous exon of the transcript, or None if there is none | [
"Returns",
"the",
"previous",
"exon",
"of",
"the",
"transcript",
"or",
"None",
"if",
"there",
"is",
"none"
] | python | train | 23 |
jenanwise/codequality | codequality/main.py | https://github.com/jenanwise/codequality/blob/8a2bd767fd73091c49a5318fdbfb2b4fff77533d/codequality/main.py#L203-L210 | def _should_ignore(self, path):
"""
Return True iff path should be ignored.
"""
for ignore in self.options.ignores:
if fnmatch.fnmatch(path, ignore):
return True
return False | [
"def",
"_should_ignore",
"(",
"self",
",",
"path",
")",
":",
"for",
"ignore",
"in",
"self",
".",
"options",
".",
"ignores",
":",
"if",
"fnmatch",
".",
"fnmatch",
"(",
"path",
",",
"ignore",
")",
":",
"return",
"True",
"return",
"False"
] | Return True iff path should be ignored. | [
"Return",
"True",
"iff",
"path",
"should",
"be",
"ignored",
"."
] | python | train | 29.375 |
Fantomas42/django-blog-zinnia | zinnia/sitemaps.py | https://github.com/Fantomas42/django-blog-zinnia/blob/b4949304b104a8e1a7a7a0773cbfd024313c3a15/zinnia/sitemaps.py#L96-L101 | def priority(self, item):
"""
The priority of the item depends of the number of entries published
in the cache divided by the maximum of entries.
"""
return '%.1f' % max(self.cache[item.pk][0] / self.max_entries, 0.1) | [
"def",
"priority",
"(",
"self",
",",
"item",
")",
":",
"return",
"'%.1f'",
"%",
"max",
"(",
"self",
".",
"cache",
"[",
"item",
".",
"pk",
"]",
"[",
"0",
"]",
"/",
"self",
".",
"max_entries",
",",
"0.1",
")"
] | The priority of the item depends of the number of entries published
in the cache divided by the maximum of entries. | [
"The",
"priority",
"of",
"the",
"item",
"depends",
"of",
"the",
"number",
"of",
"entries",
"published",
"in",
"the",
"cache",
"divided",
"by",
"the",
"maximum",
"of",
"entries",
"."
] | python | train | 42 |
aio-libs/aioftp | aioftp/common.py | https://github.com/aio-libs/aioftp/blob/b45395b1aba41301b898040acade7010e6878a08/aioftp/common.py#L489-L499 | async def read(self, count=-1):
"""
:py:func:`asyncio.coroutine`
:py:meth:`aioftp.StreamIO.read` proxy
"""
await self.wait("read")
start = _now()
data = await super().read(count)
self.append("read", data, start)
return data | [
"async",
"def",
"read",
"(",
"self",
",",
"count",
"=",
"-",
"1",
")",
":",
"await",
"self",
".",
"wait",
"(",
"\"read\"",
")",
"start",
"=",
"_now",
"(",
")",
"data",
"=",
"await",
"super",
"(",
")",
".",
"read",
"(",
"count",
")",
"self",
"."... | :py:func:`asyncio.coroutine`
:py:meth:`aioftp.StreamIO.read` proxy | [
":",
"py",
":",
"func",
":",
"asyncio",
".",
"coroutine"
] | python | valid | 26 |
ceph/ceph-deploy | vendor.py | https://github.com/ceph/ceph-deploy/blob/86943fcc454cd4c99a86e3493e9e93a59c661fef/vendor.py#L93-L112 | def vendorize(vendor_requirements):
"""
This is the main entry point for vendorizing requirements. It expects
a list of tuples that should contain the name of the library and the
version.
For example, a library ``foo`` with version ``0.0.1`` would look like::
vendor_requirements = [
... | [
"def",
"vendorize",
"(",
"vendor_requirements",
")",
":",
"for",
"library",
"in",
"vendor_requirements",
":",
"if",
"len",
"(",
"library",
")",
"==",
"2",
":",
"name",
",",
"version",
"=",
"library",
"cmd",
"=",
"None",
"elif",
"len",
"(",
"library",
")"... | This is the main entry point for vendorizing requirements. It expects
a list of tuples that should contain the name of the library and the
version.
For example, a library ``foo`` with version ``0.0.1`` would look like::
vendor_requirements = [
('foo', '0.0.1'),
] | [
"This",
"is",
"the",
"main",
"entry",
"point",
"for",
"vendorizing",
"requirements",
".",
"It",
"expects",
"a",
"list",
"of",
"tuples",
"that",
"should",
"contain",
"the",
"name",
"of",
"the",
"library",
"and",
"the",
"version",
"."
] | python | train | 31.05 |
Diaoul/subliminal | subliminal/providers/addic7ed.py | https://github.com/Diaoul/subliminal/blob/a952dfb2032eb0fd6eb1eb89f04080923c11c4cf/subliminal/providers/addic7ed.py#L148-L184 | def _search_show_id(self, series, year=None):
"""Search the show id from the `series` and `year`.
:param str series: series of the episode.
:param year: year of the series, if any.
:type year: int
:return: the show id, if found.
:rtype: int
"""
# addic7e... | [
"def",
"_search_show_id",
"(",
"self",
",",
"series",
",",
"year",
"=",
"None",
")",
":",
"# addic7ed doesn't support search with quotes",
"series",
"=",
"series",
".",
"replace",
"(",
"'\\''",
",",
"' '",
")",
"# build the params",
"series_year",
"=",
"'%s %d'",
... | Search the show id from the `series` and `year`.
:param str series: series of the episode.
:param year: year of the series, if any.
:type year: int
:return: the show id, if found.
:rtype: int | [
"Search",
"the",
"show",
"id",
"from",
"the",
"series",
"and",
"year",
"."
] | python | train | 37.783784 |
rodynnz/xccdf | src/xccdf/models/description.py | https://github.com/rodynnz/xccdf/blob/1b9dc2f06b5cce8db2a54c5f95a8f6bcf5cb6981/src/xccdf/models/description.py#L51-L67 | def update_xml_element(self):
"""
Updates the xml element contents to matches the instance contents.
:returns: Updated XML element.
:rtype: lxml.etree._Element
"""
super(Description, self).update_xml_element()
if hasattr(self, 'lang'):
self.xml_elem... | [
"def",
"update_xml_element",
"(",
"self",
")",
":",
"super",
"(",
"Description",
",",
"self",
")",
".",
"update_xml_element",
"(",
")",
"if",
"hasattr",
"(",
"self",
",",
"'lang'",
")",
":",
"self",
".",
"xml_element",
".",
"set",
"(",
"'{http://www.w3.org... | Updates the xml element contents to matches the instance contents.
:returns: Updated XML element.
:rtype: lxml.etree._Element | [
"Updates",
"the",
"xml",
"element",
"contents",
"to",
"matches",
"the",
"instance",
"contents",
"."
] | python | train | 30.647059 |
awslabs/sockeye | sockeye/inference.py | https://github.com/awslabs/sockeye/blob/5d64a1ee1ef3cbba17c6d1d94bc061020c43f6ab/sockeye/inference.py#L1748-L1770 | def _translate_nd(self,
source: mx.nd.NDArray,
source_length: int,
restrict_lexicon: Optional[lexicon.TopKLexicon],
raw_constraints: List[Optional[constrained.RawConstraintList]],
raw_avoid_list: List[Optional[... | [
"def",
"_translate_nd",
"(",
"self",
",",
"source",
":",
"mx",
".",
"nd",
".",
"NDArray",
",",
"source_length",
":",
"int",
",",
"restrict_lexicon",
":",
"Optional",
"[",
"lexicon",
".",
"TopKLexicon",
"]",
",",
"raw_constraints",
":",
"List",
"[",
"Option... | Translates source of source_length, given a bucket_key.
:param source: Source ids. Shape: (batch_size, bucket_key, num_factors).
:param source_length: Bucket key.
:param restrict_lexicon: Lexicon to use for vocabulary restriction.
:param raw_constraints: A list of optional constraint li... | [
"Translates",
"source",
"of",
"source_length",
"given",
"a",
"bucket_key",
"."
] | python | train | 54.73913 |
brocade/pynos | pynos/versions/ver_7/ver_7_1_0/yang/brocade_fabric_service.py | https://github.com/brocade/pynos/blob/bd8a34e98f322de3fc06750827d8bbc3a0c00380/pynos/versions/ver_7/ver_7_1_0/yang/brocade_fabric_service.py#L797-L808 | def show_fabric_trunk_info_input_rbridge_id(self, **kwargs):
"""Auto Generated Code
"""
config = ET.Element("config")
show_fabric_trunk_info = ET.Element("show_fabric_trunk_info")
config = show_fabric_trunk_info
input = ET.SubElement(show_fabric_trunk_info, "input")
... | [
"def",
"show_fabric_trunk_info_input_rbridge_id",
"(",
"self",
",",
"*",
"*",
"kwargs",
")",
":",
"config",
"=",
"ET",
".",
"Element",
"(",
"\"config\"",
")",
"show_fabric_trunk_info",
"=",
"ET",
".",
"Element",
"(",
"\"show_fabric_trunk_info\"",
")",
"config",
... | Auto Generated Code | [
"Auto",
"Generated",
"Code"
] | python | train | 41.75 |
marcomusy/vtkplotter | vtkplotter/addons.py | https://github.com/marcomusy/vtkplotter/blob/692c3396782722ec525bc1346a26999868c650c6/vtkplotter/addons.py#L133-L245 | def addScalarBar3D(
obj=None,
at=0,
pos=(0, 0, 0),
normal=(0, 0, 1),
sx=0.1,
sy=2,
nlabels=9,
ncols=256,
cmap=None,
c=None,
alpha=1,
):
"""Draw a 3D scalar bar.
``obj`` input can be:
- a list of numbers,
- a list of two numbers in the form `(min, max)... | [
"def",
"addScalarBar3D",
"(",
"obj",
"=",
"None",
",",
"at",
"=",
"0",
",",
"pos",
"=",
"(",
"0",
",",
"0",
",",
"0",
")",
",",
"normal",
"=",
"(",
"0",
",",
"0",
",",
"1",
")",
",",
"sx",
"=",
"0.1",
",",
"sy",
"=",
"2",
",",
"nlabels",
... | Draw a 3D scalar bar.
``obj`` input can be:
- a list of numbers,
- a list of two numbers in the form `(min, max)`,
- a ``vtkActor`` already containing a set of scalars associated to vertices or cells,
- if ``None`` the last actor in the list of actors will be used.
.. hint:: |s... | [
"Draw",
"a",
"3D",
"scalar",
"bar",
"."
] | python | train | 32.646018 |
a1ezzz/wasp-general | wasp_general/task/dependency.py | https://github.com/a1ezzz/wasp-general/blob/1029839d33eb663f8dec76c1c46754d53c1de4a9/wasp_general/task/dependency.py#L323-L335 | def registry_storage(cls):
""" Get registry storage
:return: WTaskDependencyRegistryStorage
"""
if cls.__registry_storage__ is None:
raise ValueError('__registry_storage__ must be defined')
if isinstance(cls.__registry_storage__, WTaskDependencyRegistryStorage) is False:
raise TypeError(
"Property ... | [
"def",
"registry_storage",
"(",
"cls",
")",
":",
"if",
"cls",
".",
"__registry_storage__",
"is",
"None",
":",
"raise",
"ValueError",
"(",
"'__registry_storage__ must be defined'",
")",
"if",
"isinstance",
"(",
"cls",
".",
"__registry_storage__",
",",
"WTaskDependenc... | Get registry storage
:return: WTaskDependencyRegistryStorage | [
"Get",
"registry",
"storage"
] | python | train | 32.307692 |
balloob/pychromecast | pychromecast/controllers/multizone.py | https://github.com/balloob/pychromecast/blob/831b09c4fed185a7bffe0ea330b7849d5f4e36b6/pychromecast/controllers/multizone.py#L200-L247 | def receive_message(self, message, data): # noqa: E501 pylint: disable=too-many-return-statements
""" Called when a multizone message is received. """
if data[MESSAGE_TYPE] == TYPE_DEVICE_ADDED:
uuid = data['device']['deviceId']
name = data['device']['name']
self._ad... | [
"def",
"receive_message",
"(",
"self",
",",
"message",
",",
"data",
")",
":",
"# noqa: E501 pylint: disable=too-many-return-statements",
"if",
"data",
"[",
"MESSAGE_TYPE",
"]",
"==",
"TYPE_DEVICE_ADDED",
":",
"uuid",
"=",
"data",
"[",
"'device'",
"]",
"[",
"'devic... | Called when a multizone message is received. | [
"Called",
"when",
"a",
"multizone",
"message",
"is",
"received",
"."
] | python | train | 37.291667 |
inspirehep/inspire-utils | inspire_utils/logging.py | https://github.com/inspirehep/inspire-utils/blob/b0b5983c58700735dfde75e4c8bd32834f2473d4/inspire_utils/logging.py#L36-L42 | def error(self, message, *args, **kwargs):
"""Log error with stack trace and locals information.
By default, enables stack trace information in logging messages, so that stacktrace and locals appear in Sentry.
"""
kwargs.setdefault('extra', {}).setdefault('stack', True)
return s... | [
"def",
"error",
"(",
"self",
",",
"message",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"kwargs",
".",
"setdefault",
"(",
"'extra'",
",",
"{",
"}",
")",
".",
"setdefault",
"(",
"'stack'",
",",
"True",
")",
"return",
"self",
".",
"logger",... | Log error with stack trace and locals information.
By default, enables stack trace information in logging messages, so that stacktrace and locals appear in Sentry. | [
"Log",
"error",
"with",
"stack",
"trace",
"and",
"locals",
"information",
"."
] | python | train | 50.857143 |
ella/ella | ella/photos/formatter.py | https://github.com/ella/ella/blob/4a1414991f649dc21c4b777dc6b41a922a13faa7/ella/photos/formatter.py#L180-L189 | def resize(self):
"""
Get target size for a cropped image and do the resizing if we got
anything usable.
"""
resized_size = self.get_resized_size()
if not resized_size:
return
self.image = self.image.resize(resized_size, Image.ANTIALIAS) | [
"def",
"resize",
"(",
"self",
")",
":",
"resized_size",
"=",
"self",
".",
"get_resized_size",
"(",
")",
"if",
"not",
"resized_size",
":",
"return",
"self",
".",
"image",
"=",
"self",
".",
"image",
".",
"resize",
"(",
"resized_size",
",",
"Image",
".",
... | Get target size for a cropped image and do the resizing if we got
anything usable. | [
"Get",
"target",
"size",
"for",
"a",
"cropped",
"image",
"and",
"do",
"the",
"resizing",
"if",
"we",
"got",
"anything",
"usable",
"."
] | python | train | 29.7 |
ironfroggy/django-better-cache | bettercache/utils.py | https://github.com/ironfroggy/django-better-cache/blob/5350e8c646cef1c1ca74eab176f856ddd9eaf5c3/bettercache/utils.py#L198-L205 | def strip_wsgi(request):
"""Strip WSGI data out of the request META data."""
meta = copy(request.META)
for key in meta:
if key[:4] == 'wsgi':
meta[key] = None
return meta | [
"def",
"strip_wsgi",
"(",
"request",
")",
":",
"meta",
"=",
"copy",
"(",
"request",
".",
"META",
")",
"for",
"key",
"in",
"meta",
":",
"if",
"key",
"[",
":",
"4",
"]",
"==",
"'wsgi'",
":",
"meta",
"[",
"key",
"]",
"=",
"None",
"return",
"meta"
] | Strip WSGI data out of the request META data. | [
"Strip",
"WSGI",
"data",
"out",
"of",
"the",
"request",
"META",
"data",
"."
] | python | train | 25 |
jssimporter/python-jss | jss/jssobject.py | https://github.com/jssimporter/python-jss/blob/b95185d74e0c0531b0b563f280d4129e21d5fe5d/jss/jssobject.py#L369-L389 | def _handle_location(self, location):
"""Return an element located at location with flexible args.
Args:
location: String xpath to use in an Element.find search OR
an Element (which is simply returned).
Returns:
The found Element.
Raises:
... | [
"def",
"_handle_location",
"(",
"self",
",",
"location",
")",
":",
"if",
"not",
"isinstance",
"(",
"location",
",",
"ElementTree",
".",
"Element",
")",
":",
"element",
"=",
"self",
".",
"find",
"(",
"location",
")",
"if",
"element",
"is",
"None",
":",
... | Return an element located at location with flexible args.
Args:
location: String xpath to use in an Element.find search OR
an Element (which is simply returned).
Returns:
The found Element.
Raises:
ValueError if the location is a string that... | [
"Return",
"an",
"element",
"located",
"at",
"location",
"with",
"flexible",
"args",
"."
] | python | train | 30.952381 |
PythonicNinja/pydrill | pydrill/connection/base.py | https://github.com/PythonicNinja/pydrill/blob/0713e78c84d44cd438018e4ba1588a8e242f78c4/pydrill/connection/base.py#L85-L97 | def log_request_fail(self, method, full_url, body, duration, status_code=None, exception=None):
"""
Log an unsuccessful API call.
"""
logger.warning(
'%s %s [status:%s request:%.3fs]', method, full_url,
status_code or 'N/A', duration, exc_info=exception is not Non... | [
"def",
"log_request_fail",
"(",
"self",
",",
"method",
",",
"full_url",
",",
"body",
",",
"duration",
",",
"status_code",
"=",
"None",
",",
"exception",
"=",
"None",
")",
":",
"logger",
".",
"warning",
"(",
"'%s %s [status:%s request:%.3fs]'",
",",
"method",
... | Log an unsuccessful API call. | [
"Log",
"an",
"unsuccessful",
"API",
"call",
"."
] | python | train | 34.153846 |
dead-beef/markovchain | markovchain/text/util.py | https://github.com/dead-beef/markovchain/blob/9bd10b2f01089341c4a875a0fa569d50caba22c7/markovchain/text/util.py#L198-L220 | def re_flags_str(flags, custom_flags):
"""Convert regexp flags to string.
Parameters
----------
flags : `int`
Flags.
custom_flags : `int`
Custom flags.
Returns
-------
`str`
Flag string.
"""
res = ''
for flag in RE_FLAGS:
if flags & getattr(r... | [
"def",
"re_flags_str",
"(",
"flags",
",",
"custom_flags",
")",
":",
"res",
"=",
"''",
"for",
"flag",
"in",
"RE_FLAGS",
":",
"if",
"flags",
"&",
"getattr",
"(",
"re",
",",
"flag",
")",
":",
"res",
"+=",
"flag",
"for",
"flag",
"in",
"RE_CUSTOM_FLAGS",
... | Convert regexp flags to string.
Parameters
----------
flags : `int`
Flags.
custom_flags : `int`
Custom flags.
Returns
-------
`str`
Flag string. | [
"Convert",
"regexp",
"flags",
"to",
"string",
"."
] | python | train | 19.695652 |
tensorflow/tensor2tensor | tensor2tensor/data_generators/librispeech.py | https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/data_generators/librispeech.py#L63-L85 | def _collect_data(directory, input_ext, transcription_ext):
"""Traverses directory collecting input and target files."""
# Directory from string to tuple pair of strings
# key: the filepath to a datafile including the datafile's basename. Example,
# if the datafile was "/path/to/datafile.wav" then the key wou... | [
"def",
"_collect_data",
"(",
"directory",
",",
"input_ext",
",",
"transcription_ext",
")",
":",
"# Directory from string to tuple pair of strings",
"# key: the filepath to a datafile including the datafile's basename. Example,",
"# if the datafile was \"/path/to/datafile.wav\" then the key... | Traverses directory collecting input and target files. | [
"Traverses",
"directory",
"collecting",
"input",
"and",
"target",
"files",
"."
] | python | train | 49.304348 |
robinandeer/puzzle | puzzle/models/variant.py | https://github.com/robinandeer/puzzle/blob/9476f05b416d3a5135d25492cb31411fdf831c58/puzzle/models/variant.py#L159-L170 | def add_compound(self, compound):
"""Add the information of a compound variant
This adds a compound dict to variant['compounds']
Args:
compound (dict): A compound dictionary
"""
logger.debug("Adding compound {0} to variant {1}".format(
compo... | [
"def",
"add_compound",
"(",
"self",
",",
"compound",
")",
":",
"logger",
".",
"debug",
"(",
"\"Adding compound {0} to variant {1}\"",
".",
"format",
"(",
"compound",
",",
"self",
"[",
"'variant_id'",
"]",
")",
")",
"self",
"[",
"'compounds'",
"]",
".",
"appe... | Add the information of a compound variant
This adds a compound dict to variant['compounds']
Args:
compound (dict): A compound dictionary | [
"Add",
"the",
"information",
"of",
"a",
"compound",
"variant"
] | python | train | 31.416667 |
priestc/moneywagon | moneywagon/__init__.py | https://github.com/priestc/moneywagon/blob/00518f1f557dcca8b3031f46d3564c2baa0227a3/moneywagon/__init__.py#L637-L661 | def service_table(format='simple', authenticated=False):
"""
Returns a string depicting all services currently installed.
"""
if authenticated:
all_services = ExchangeUniverse.get_authenticated_services()
else:
all_services = ALL_SERVICES
if format == 'html':
linkify = l... | [
"def",
"service_table",
"(",
"format",
"=",
"'simple'",
",",
"authenticated",
"=",
"False",
")",
":",
"if",
"authenticated",
":",
"all_services",
"=",
"ExchangeUniverse",
".",
"get_authenticated_services",
"(",
")",
"else",
":",
"all_services",
"=",
"ALL_SERVICES"... | Returns a string depicting all services currently installed. | [
"Returns",
"a",
"string",
"depicting",
"all",
"services",
"currently",
"installed",
"."
] | python | train | 33.68 |
UCL-INGI/INGInious | inginious/frontend/pages/course.py | https://github.com/UCL-INGI/INGInious/blob/cbda9a9c7f2b8e8eb1e6d7d51f0d18092086300c/inginious/frontend/pages/course.py#L24-L33 | def POST(self, courseid): # pylint: disable=arguments-differ
""" POST request """
course = self.get_course(courseid)
user_input = web.input()
if "unregister" in user_input and course.allow_unregister():
self.user_manager.course_unregister_user(course, self.user_manager.sess... | [
"def",
"POST",
"(",
"self",
",",
"courseid",
")",
":",
"# pylint: disable=arguments-differ",
"course",
"=",
"self",
".",
"get_course",
"(",
"courseid",
")",
"user_input",
"=",
"web",
".",
"input",
"(",
")",
"if",
"\"unregister\"",
"in",
"user_input",
"and",
... | POST request | [
"POST",
"request"
] | python | train | 43.6 |
chrisjsewell/jsonextended | jsonextended/edict.py | https://github.com/chrisjsewell/jsonextended/blob/c3a7a880cc09789b3c61204265dcbb127be76c8a/jsonextended/edict.py#L66-L73 | def is_list_of_dict_like(obj, attr=('keys', 'items')):
"""test if object is a list only containing dict like items """
try:
if len(obj) == 0:
return False
return all([is_dict_like(i, attr) for i in obj])
except Exception:
return False | [
"def",
"is_list_of_dict_like",
"(",
"obj",
",",
"attr",
"=",
"(",
"'keys'",
",",
"'items'",
")",
")",
":",
"try",
":",
"if",
"len",
"(",
"obj",
")",
"==",
"0",
":",
"return",
"False",
"return",
"all",
"(",
"[",
"is_dict_like",
"(",
"i",
",",
"attr"... | test if object is a list only containing dict like items | [
"test",
"if",
"object",
"is",
"a",
"list",
"only",
"containing",
"dict",
"like",
"items"
] | python | train | 34.375 |
BlueBrain/NeuroM | neurom/geom/transform.py | https://github.com/BlueBrain/NeuroM/blob/254bb73535b20053d175bc4725bade662177d12b/neurom/geom/transform.py#L128-L146 | def rotate(obj, axis, angle, origin=None):
'''
Rotation around unit vector following the right hand rule
Parameters:
obj : obj to be rotated (e.g. neurite, neuron).
Must implement a transform method.
axis : unit vector for the axis of rotation
angle : rotation angle in r... | [
"def",
"rotate",
"(",
"obj",
",",
"axis",
",",
"angle",
",",
"origin",
"=",
"None",
")",
":",
"R",
"=",
"_rodrigues_to_dcm",
"(",
"axis",
",",
"angle",
")",
"try",
":",
"return",
"obj",
".",
"transform",
"(",
"PivotRotation",
"(",
"R",
",",
"origin",... | Rotation around unit vector following the right hand rule
Parameters:
obj : obj to be rotated (e.g. neurite, neuron).
Must implement a transform method.
axis : unit vector for the axis of rotation
angle : rotation angle in rads
Returns:
A copy of the object with the... | [
"Rotation",
"around",
"unit",
"vector",
"following",
"the",
"right",
"hand",
"rule"
] | python | train | 29 |
openid/JWTConnect-Python-CryptoJWT | src/cryptojwt/key_jar.py | https://github.com/openid/JWTConnect-Python-CryptoJWT/blob/8863cfbfe77ca885084870b234a66b55bd52930c/src/cryptojwt/key_jar.py#L148-L230 | def get(self, key_use, key_type="", owner="", kid=None, **kwargs):
"""
Get all keys that matches a set of search criteria
:param key_use: A key useful for this usage (enc, dec, sig, ver)
:param key_type: Type of key (rsa, ec, oct, ..)
:param owner: Who is the owner of the keys, ... | [
"def",
"get",
"(",
"self",
",",
"key_use",
",",
"key_type",
"=",
"\"\"",
",",
"owner",
"=",
"\"\"",
",",
"kid",
"=",
"None",
",",
"*",
"*",
"kwargs",
")",
":",
"if",
"key_use",
"in",
"[",
"\"dec\"",
",",
"\"enc\"",
"]",
":",
"use",
"=",
"\"enc\""... | Get all keys that matches a set of search criteria
:param key_use: A key useful for this usage (enc, dec, sig, ver)
:param key_type: Type of key (rsa, ec, oct, ..)
:param owner: Who is the owner of the keys, "" == me (default)
:param kid: A Key Identifier
:return: A possibly emp... | [
"Get",
"all",
"keys",
"that",
"matches",
"a",
"set",
"of",
"search",
"criteria"
] | python | train | 32.638554 |
gitpython-developers/GitPython | git/index/base.py | https://github.com/gitpython-developers/GitPython/blob/1f66e25c25cde2423917ee18c4704fff83b837d1/git/index/base.py#L557-L566 | def _to_relative_path(self, path):
""":return: Version of path relative to our git directory or raise ValueError
if it is not within our git direcotory"""
if not osp.isabs(path):
return path
if self.repo.bare:
raise InvalidGitRepositoryError("require non-bare repo... | [
"def",
"_to_relative_path",
"(",
"self",
",",
"path",
")",
":",
"if",
"not",
"osp",
".",
"isabs",
"(",
"path",
")",
":",
"return",
"path",
"if",
"self",
".",
"repo",
".",
"bare",
":",
"raise",
"InvalidGitRepositoryError",
"(",
"\"require non-bare repository\... | :return: Version of path relative to our git directory or raise ValueError
if it is not within our git direcotory | [
":",
"return",
":",
"Version",
"of",
"path",
"relative",
"to",
"our",
"git",
"directory",
"or",
"raise",
"ValueError",
"if",
"it",
"is",
"not",
"within",
"our",
"git",
"direcotory"
] | python | train | 56.1 |
ARMmbed/icetea | icetea_lib/ResourceProvider/ResourceConfig.py | https://github.com/ARMmbed/icetea/blob/b2b97ac607429830cf7d62dae2e3903692c7c778/icetea_lib/ResourceProvider/ResourceConfig.py#L41-L47 | def _hardware_count(self):
"""
Amount of hardware resources.
:return: integer
"""
return self._counts.get("hardware") + self._counts.get("serial") + self._counts.get("mbed") | [
"def",
"_hardware_count",
"(",
"self",
")",
":",
"return",
"self",
".",
"_counts",
".",
"get",
"(",
"\"hardware\"",
")",
"+",
"self",
".",
"_counts",
".",
"get",
"(",
"\"serial\"",
")",
"+",
"self",
".",
"_counts",
".",
"get",
"(",
"\"mbed\"",
")"
] | Amount of hardware resources.
:return: integer | [
"Amount",
"of",
"hardware",
"resources",
"."
] | python | train | 29.714286 |
googleads/googleads-python-lib | examples/adwords/v201809/advanced_operations/add_dynamic_page_feed.py | https://github.com/googleads/googleads-python-lib/blob/aa3b1b474b0f9789ca55ca46f4b2b57aeae38874/examples/adwords/v201809/advanced_operations/add_dynamic_page_feed.py#L98-L131 | def _CreateFeedMapping(client, feed_details):
"""Creates the feed mapping for DSA page feeds.
Args:
client: an AdWordsClient instance.
feed_details: a _DSAFeedDetails instance.
"""
# Get the FeedMappingService.
feed_mapping_service = client.GetService('FeedMappingService',
... | [
"def",
"_CreateFeedMapping",
"(",
"client",
",",
"feed_details",
")",
":",
"# Get the FeedMappingService.",
"feed_mapping_service",
"=",
"client",
".",
"GetService",
"(",
"'FeedMappingService'",
",",
"version",
"=",
"'v201809'",
")",
"# Create the operation.",
"operation"... | Creates the feed mapping for DSA page feeds.
Args:
client: an AdWordsClient instance.
feed_details: a _DSAFeedDetails instance. | [
"Creates",
"the",
"feed",
"mapping",
"for",
"DSA",
"page",
"feeds",
"."
] | python | train | 30.529412 |
sporteasy/python-poeditor | poeditor/client.py | https://github.com/sporteasy/python-poeditor/blob/e9c0a8ab08816903122f730b73ffaab46601076c/poeditor/client.py#L723-L732 | def list_contributors(self, project_id=None, language_code=None):
"""
Returns the list of contributors
"""
data = self._run(
url_path="contributors/list",
id=project_id,
language=language_code
)
return data['result'].get('contributors',... | [
"def",
"list_contributors",
"(",
"self",
",",
"project_id",
"=",
"None",
",",
"language_code",
"=",
"None",
")",
":",
"data",
"=",
"self",
".",
"_run",
"(",
"url_path",
"=",
"\"contributors/list\"",
",",
"id",
"=",
"project_id",
",",
"language",
"=",
"lang... | Returns the list of contributors | [
"Returns",
"the",
"list",
"of",
"contributors"
] | python | train | 31.5 |
google/apitools | apitools/base/py/transfer.py | https://github.com/google/apitools/blob/f3745a7ea535aa0e88b0650c16479b696d6fd446/apitools/base/py/transfer.py#L299-L332 | def InitializeDownload(self, http_request, http=None, client=None):
"""Initialize this download by making a request.
Args:
http_request: The HttpRequest to use to initialize this download.
http: The httplib2.Http instance for this request.
client: If provided, let this cli... | [
"def",
"InitializeDownload",
"(",
"self",
",",
"http_request",
",",
"http",
"=",
"None",
",",
"client",
"=",
"None",
")",
":",
"self",
".",
"EnsureUninitialized",
"(",
")",
"if",
"http",
"is",
"None",
"and",
"client",
"is",
"None",
":",
"raise",
"excepti... | Initialize this download by making a request.
Args:
http_request: The HttpRequest to use to initialize this download.
http: The httplib2.Http instance for this request.
client: If provided, let this client process the final URL before
sending any additional requests.... | [
"Initialize",
"this",
"download",
"by",
"making",
"a",
"request",
"."
] | python | train | 47.882353 |
Robpol86/libnl | libnl/genl/mngt.py | https://github.com/Robpol86/libnl/blob/274e9fdaa39822d06ef70b799ed4a95937a4d923/libnl/genl/mngt.py#L151-L163 | def lookup_family_by_name(name):
"""https://github.com/thom311/libnl/blob/libnl3_2_25/lib/genl/mngt.c#L106.
Positional arguments:
name -- string.
Returns:
genl_ops class instance or None.
"""
for ops in nl_list_for_each_entry(genl_ops(), genl_ops_list, 'o_list'):
if ops.o_name == n... | [
"def",
"lookup_family_by_name",
"(",
"name",
")",
":",
"for",
"ops",
"in",
"nl_list_for_each_entry",
"(",
"genl_ops",
"(",
")",
",",
"genl_ops_list",
",",
"'o_list'",
")",
":",
"if",
"ops",
".",
"o_name",
"==",
"name",
":",
"return",
"ops",
"return",
"None... | https://github.com/thom311/libnl/blob/libnl3_2_25/lib/genl/mngt.c#L106.
Positional arguments:
name -- string.
Returns:
genl_ops class instance or None. | [
"https",
":",
"//",
"github",
".",
"com",
"/",
"thom311",
"/",
"libnl",
"/",
"blob",
"/",
"libnl3_2_25",
"/",
"lib",
"/",
"genl",
"/",
"mngt",
".",
"c#L106",
"."
] | python | train | 27 |
ioos/compliance-checker | compliance_checker/cfutil.py | https://github.com/ioos/compliance-checker/blob/ee89c27b0daade58812489a2da3aa3b6859eafd9/compliance_checker/cfutil.py#L152-L163 | def is_unitless(ds, variable):
'''
Returns true if the variable is unitless
Note units of '1' are considered whole numbers or parts but still represent
physical units and not the absence of units.
:param netCDF4.Dataset ds: An open netCDF dataset
:param str variable: Name of the variable
'... | [
"def",
"is_unitless",
"(",
"ds",
",",
"variable",
")",
":",
"units",
"=",
"getattr",
"(",
"ds",
".",
"variables",
"[",
"variable",
"]",
",",
"'units'",
",",
"None",
")",
"return",
"units",
"is",
"None",
"or",
"units",
"==",
"''"
] | Returns true if the variable is unitless
Note units of '1' are considered whole numbers or parts but still represent
physical units and not the absence of units.
:param netCDF4.Dataset ds: An open netCDF dataset
:param str variable: Name of the variable | [
"Returns",
"true",
"if",
"the",
"variable",
"is",
"unitless"
] | python | train | 34.166667 |
rasguanabana/ytfs | ytfs/actions.py | https://github.com/rasguanabana/ytfs/blob/67dd9536a1faea09c8394f697529124f78e77cfa/ytfs/actions.py#L113-L141 | def __getChannelId(self):
"""
Obtain channel id for channel name, if present in ``self.search_params``.
"""
if not self.search_params.get("channelId"):
return
api_fixed_url = "https://www.googleapis.com/youtube/v3/channels?part=id&maxResults=1&fields=items%2Fid&"
... | [
"def",
"__getChannelId",
"(",
"self",
")",
":",
"if",
"not",
"self",
".",
"search_params",
".",
"get",
"(",
"\"channelId\"",
")",
":",
"return",
"api_fixed_url",
"=",
"\"https://www.googleapis.com/youtube/v3/channels?part=id&maxResults=1&fields=items%2Fid&\"",
"url",
"=",... | Obtain channel id for channel name, if present in ``self.search_params``. | [
"Obtain",
"channel",
"id",
"for",
"channel",
"name",
"if",
"present",
"in",
"self",
".",
"search_params",
"."
] | python | train | 36.068966 |
gmr/tinman | tinman/handlers/rabbitmq.py | https://github.com/gmr/tinman/blob/98f0acd15a228d752caa1864cdf02aaa3d492a9f/tinman/handlers/rabbitmq.py#L59-L69 | def _add_to_publish_stack(self, exchange, routing_key, message, properties):
"""Temporarily add the message to the stack to publish to RabbitMQ
:param str exchange: The exchange to publish to
:param str routing_key: The routing key to publish with
:param str message: The message body
... | [
"def",
"_add_to_publish_stack",
"(",
"self",
",",
"exchange",
",",
"routing_key",
",",
"message",
",",
"properties",
")",
":",
"global",
"message_stack",
"message_stack",
".",
"append",
"(",
"(",
"exchange",
",",
"routing_key",
",",
"message",
",",
"properties",... | Temporarily add the message to the stack to publish to RabbitMQ
:param str exchange: The exchange to publish to
:param str routing_key: The routing key to publish with
:param str message: The message body
:param pika.BasicProperties: The message properties | [
"Temporarily",
"add",
"the",
"message",
"to",
"the",
"stack",
"to",
"publish",
"to",
"RabbitMQ"
] | python | train | 44 |
kgori/treeCl | treeCl/plotter.py | https://github.com/kgori/treeCl/blob/fed624b3db1c19cc07175ca04e3eda6905a8d305/treeCl/plotter.py#L151-L230 | def plot_embedding(coordinates, partition=None, add_sphere=False, point_size=8,
colours=None, labels=None, legend=True, outfile=False, **kwargs):
""" plot_embedding(coordinates, partition=None, add_sphere=False, point_size=8,
colours=None, labels=None, legend=True, outfile=False, **kwargs):
Plo... | [
"def",
"plot_embedding",
"(",
"coordinates",
",",
"partition",
"=",
"None",
",",
"add_sphere",
"=",
"False",
",",
"point_size",
"=",
"8",
",",
"colours",
"=",
"None",
",",
"labels",
"=",
"None",
",",
"legend",
"=",
"True",
",",
"outfile",
"=",
"False",
... | plot_embedding(coordinates, partition=None, add_sphere=False, point_size=8,
colours=None, labels=None, legend=True, outfile=False, **kwargs):
Plot a 2D / 3D scatterplot of coordinates, optionally
coloured by group membership.
Args:
coordinates: numpy array or treeCl.CoordinateMatrix -
... | [
"plot_embedding",
"(",
"coordinates",
"partition",
"=",
"None",
"add_sphere",
"=",
"False",
"point_size",
"=",
"8",
"colours",
"=",
"None",
"labels",
"=",
"None",
"legend",
"=",
"True",
"outfile",
"=",
"False",
"**",
"kwargs",
")",
":",
"Plot",
"a",
"2D",
... | python | train | 35.175 |
agoragames/haigha | haigha/connections/rabbit_connection.py | https://github.com/agoragames/haigha/blob/7b004e1c0316ec14b94fec1c54554654c38b1a25/haigha/connections/rabbit_connection.py#L219-L225 | def nack(self, delivery_tag, multiple=False, requeue=False):
'''Send a nack to the broker.'''
args = Writer()
args.write_longlong(delivery_tag).\
write_bits(multiple, requeue)
self.send_frame(MethodFrame(self.channel_id, 60, 120, args)) | [
"def",
"nack",
"(",
"self",
",",
"delivery_tag",
",",
"multiple",
"=",
"False",
",",
"requeue",
"=",
"False",
")",
":",
"args",
"=",
"Writer",
"(",
")",
"args",
".",
"write_longlong",
"(",
"delivery_tag",
")",
".",
"write_bits",
"(",
"multiple",
",",
"... | Send a nack to the broker. | [
"Send",
"a",
"nack",
"to",
"the",
"broker",
"."
] | python | train | 39.285714 |
jidn/flask-resteasy | flask_resteasy.py | https://github.com/jidn/flask-resteasy/blob/79d4a50705d4300c91ab3bafefac23782768be2a/flask_resteasy.py#L104-L124 | def init_app(self, app):
"""Initialize actions with the app or blueprint.
:param app: the Flask application or blueprint object
:type app: :class:`~flask.Flask` or :class:`~flask.Blueprint`
Examples::
api = Api()
api.add_resource(...)
api.init_app(b... | [
"def",
"init_app",
"(",
"self",
",",
"app",
")",
":",
"try",
":",
"# Assume this is a blueprint and defer initialization",
"if",
"app",
".",
"_got_registered_once",
"is",
"True",
":",
"raise",
"ValueError",
"(",
"\"\"\"Blueprint is already registered with an app.\"\"\"",
... | Initialize actions with the app or blueprint.
:param app: the Flask application or blueprint object
:type app: :class:`~flask.Flask` or :class:`~flask.Blueprint`
Examples::
api = Api()
api.add_resource(...)
api.init_app(blueprint) | [
"Initialize",
"actions",
"with",
"the",
"app",
"or",
"blueprint",
"."
] | python | train | 33.238095 |
twitterdev/tweet_parser | tweet_parser/tweet.py | https://github.com/twitterdev/tweet_parser/blob/3435de8367d36b483a6cfd8d46cc28694ee8a42e/tweet_parser/tweet.py#L530-L552 | def retweeted_tweet(self):
"""
The retweeted Tweet as a Tweet object
If the Tweet is not a Retweet, return None
If the Retweet payload cannot be loaded as a Tweet, this will
raise a `NotATweetError`
Returns:
Tweet: A Tweet representing the retweeted status (o... | [
"def",
"retweeted_tweet",
"(",
"self",
")",
":",
"retweet",
"=",
"tweet_embeds",
".",
"get_retweeted_tweet",
"(",
"self",
")",
"if",
"retweet",
"is",
"not",
"None",
":",
"try",
":",
"return",
"Tweet",
"(",
"retweet",
")",
"except",
"NotATweetError",
"as",
... | The retweeted Tweet as a Tweet object
If the Tweet is not a Retweet, return None
If the Retweet payload cannot be loaded as a Tweet, this will
raise a `NotATweetError`
Returns:
Tweet: A Tweet representing the retweeted status (or None)
(see tweet_embeds.get_retwe... | [
"The",
"retweeted",
"Tweet",
"as",
"a",
"Tweet",
"object",
"If",
"the",
"Tweet",
"is",
"not",
"a",
"Retweet",
"return",
"None",
"If",
"the",
"Retweet",
"payload",
"cannot",
"be",
"loaded",
"as",
"a",
"Tweet",
"this",
"will",
"raise",
"a",
"NotATweetError"
... | python | train | 36.73913 |
merll/docker-map | dockermap/map/input.py | https://github.com/merll/docker-map/blob/e14fe86a6ff5c33d121eb2f9157e9359cb80dd02/dockermap/map/input.py#L365-L384 | def get_healthcheck(value):
"""
Converts input into a :class:`HealthCheck` tuple. Input can be passed as string, tuple, list, or a dictionary. If
set to ``None``, the health check will be set to ``NONE``, i.e. override an existing configuration from the image.
:param value: Health check input.
:typ... | [
"def",
"get_healthcheck",
"(",
"value",
")",
":",
"if",
"isinstance",
"(",
"value",
",",
"HealthCheck",
")",
":",
"return",
"value",
"elif",
"isinstance",
"(",
"value",
",",
"six",
".",
"string_types",
"+",
"(",
"lazy_type",
",",
")",
")",
"or",
"uses_ty... | Converts input into a :class:`HealthCheck` tuple. Input can be passed as string, tuple, list, or a dictionary. If
set to ``None``, the health check will be set to ``NONE``, i.e. override an existing configuration from the image.
:param value: Health check input.
:type value: unicode | str | tuple | list | ... | [
"Converts",
"input",
"into",
"a",
":",
"class",
":",
"HealthCheck",
"tuple",
".",
"Input",
"can",
"be",
"passed",
"as",
"string",
"tuple",
"list",
"or",
"a",
"dictionary",
".",
"If",
"set",
"to",
"None",
"the",
"health",
"check",
"will",
"be",
"set",
"... | python | train | 43.85 |
Azure/azure-sdk-for-python | azure-servicebus/azure/servicebus/common/mixins.py | https://github.com/Azure/azure-sdk-for-python/blob/d7306fde32f60a293a7567678692bdad31e4b667/azure-servicebus/azure/servicebus/common/mixins.py#L174-L222 | def create_subscription(
self, topic_name, subscription_name,
lock_duration=30, requires_session=None,
default_message_time_to_live=None,
dead_lettering_on_message_expiration=None,
dead_lettering_on_filter_evaluation_exceptions=None,
enable_batched... | [
"def",
"create_subscription",
"(",
"self",
",",
"topic_name",
",",
"subscription_name",
",",
"lock_duration",
"=",
"30",
",",
"requires_session",
"=",
"None",
",",
"default_message_time_to_live",
"=",
"None",
",",
"dead_lettering_on_message_expiration",
"=",
"None",
"... | Create a subscription entity.
:param topic_name: The name of the topic under which to create the subscription.
:param subscription_name: The name of the new subscription.
:type subscription_name: str
:param lock_duration: The lock durection in seconds for each message in the subscriptio... | [
"Create",
"a",
"subscription",
"entity",
"."
] | python | test | 61.714286 |
phoebe-project/phoebe2 | phoebe/backend/oc_geometry.py | https://github.com/phoebe-project/phoebe2/blob/e64b8be683977064e2d55dd1b3ac400f64c3e379/phoebe/backend/oc_geometry.py#L118-L184 | def nekmin(omega_in,q,x0=0.5,z0=0.5):
'''Computes the position of the neck (minimal radius) in an contact_binary star1'''
def Omega_xz(q,x,z):
return 1./np.sqrt(x**2+z**2)+q/np.sqrt((1-x)**2+z**2)+(q+1)*x**2/2.-q*x
def Omega_xy(q,x,y):
return 1./np.sqrt(x**2+y**2)+q/np.sqrt((1-x)**2+y**2)... | [
"def",
"nekmin",
"(",
"omega_in",
",",
"q",
",",
"x0",
"=",
"0.5",
",",
"z0",
"=",
"0.5",
")",
":",
"def",
"Omega_xz",
"(",
"q",
",",
"x",
",",
"z",
")",
":",
"return",
"1.",
"/",
"np",
".",
"sqrt",
"(",
"x",
"**",
"2",
"+",
"z",
"**",
"2... | Computes the position of the neck (minimal radius) in an contact_binary star1 | [
"Computes",
"the",
"position",
"of",
"the",
"neck",
"(",
"minimal",
"radius",
")",
"in",
"an",
"contact_binary",
"star1"
] | python | train | 30.58209 |
ponty/confduino | confduino/examples/board.py | https://github.com/ponty/confduino/blob/f4c261e5e84997f145a8bdd001f471db74c9054b/confduino/examples/board.py#L17-L40 | def install_board_with_programmer(mcu,
programmer,
f_cpu=16000000,
core='arduino',
replace_existing=False,
):
"""install board with programmer."""... | [
"def",
"install_board_with_programmer",
"(",
"mcu",
",",
"programmer",
",",
"f_cpu",
"=",
"16000000",
",",
"core",
"=",
"'arduino'",
",",
"replace_existing",
"=",
"False",
",",
")",
":",
"bunch",
"=",
"AutoBunch",
"(",
")",
"board_id",
"=",
"'{mcu}_{f_cpu}_{pr... | install board with programmer. | [
"install",
"board",
"with",
"programmer",
"."
] | python | train | 42.75 |
dropbox/stone | stone/frontend/parser.py | https://github.com/dropbox/stone/blob/2e95cbcd1c48e05cca68c919fd8d24adec6b0f58/stone/frontend/parser.py#L318-L327 | def p_annotation_type(self, p):
"""annotation_type : ANNOTATION_TYPE ID NL \
INDENT docsection field_list DEDENT"""
p[0] = AstAnnotationTypeDef(
path=self.path,
lineno=p.lineno(1),
lexpos=p.lexpos(1),
name=p[2],
do... | [
"def",
"p_annotation_type",
"(",
"self",
",",
"p",
")",
":",
"p",
"[",
"0",
"]",
"=",
"AstAnnotationTypeDef",
"(",
"path",
"=",
"self",
".",
"path",
",",
"lineno",
"=",
"p",
".",
"lineno",
"(",
"1",
")",
",",
"lexpos",
"=",
"p",
".",
"lexpos",
"(... | annotation_type : ANNOTATION_TYPE ID NL \
INDENT docsection field_list DEDENT | [
"annotation_type",
":",
"ANNOTATION_TYPE",
"ID",
"NL",
"\\",
"INDENT",
"docsection",
"field_list",
"DEDENT"
] | python | train | 34.3 |
Duke-QCD/hic | hic/flow.py | https://github.com/Duke-QCD/hic/blob/9afb141735b1ac228d296a2349225d2bdcdb68f0/hic/flow.py#L13-L36 | def qn(phi, *n):
"""
Calculate the complex flow vector `Q_n`.
:param array-like phi: Azimuthal angles.
:param int n: One or more harmonics to calculate.
:returns:
A single complex number if only one ``n`` was given or a complex array
for multiple ``n``.
"""
phi = np.ravel... | [
"def",
"qn",
"(",
"phi",
",",
"*",
"n",
")",
":",
"phi",
"=",
"np",
".",
"ravel",
"(",
"phi",
")",
"n",
"=",
"np",
".",
"asarray",
"(",
"n",
")",
"i_n_phi",
"=",
"np",
".",
"zeros",
"(",
"(",
"n",
".",
"size",
",",
"phi",
".",
"size",
")"... | Calculate the complex flow vector `Q_n`.
:param array-like phi: Azimuthal angles.
:param int n: One or more harmonics to calculate.
:returns:
A single complex number if only one ``n`` was given or a complex array
for multiple ``n``. | [
"Calculate",
"the",
"complex",
"flow",
"vector",
"Q_n",
"."
] | python | train | 22 |
pyviz/holoviews | holoviews/core/pprint.py | https://github.com/pyviz/holoviews/blob/ae0dd2f3de448b0ca5e9065aabd6ef8d84c7e655/holoviews/core/pprint.py#L354-L364 | def element_info(cls_or_slf, node, siblings, level, value_dims):
"""
Return the information summary for an Element. This consists
of the dotted name followed by an value dimension names.
"""
info = cls_or_slf.component_type(node)
if len(node.kdims) >= 1:
info ... | [
"def",
"element_info",
"(",
"cls_or_slf",
",",
"node",
",",
"siblings",
",",
"level",
",",
"value_dims",
")",
":",
"info",
"=",
"cls_or_slf",
".",
"component_type",
"(",
"node",
")",
"if",
"len",
"(",
"node",
".",
"kdims",
")",
">=",
"1",
":",
"info",
... | Return the information summary for an Element. This consists
of the dotted name followed by an value dimension names. | [
"Return",
"the",
"information",
"summary",
"for",
"an",
"Element",
".",
"This",
"consists",
"of",
"the",
"dotted",
"name",
"followed",
"by",
"an",
"value",
"dimension",
"names",
"."
] | python | train | 49.454545 |
tanghaibao/goatools | goatools/wr_tbl_class.py | https://github.com/tanghaibao/goatools/blob/407682e573a108864a79031f8ca19ee3bf377626/goatools/wr_tbl_class.py#L64-L97 | def wr_data(self, xlsx_data, row_i, worksheet):
"""Write data into xlsx worksheet."""
fld2fmt = self.vars.fld2fmt
# User may specify to skip rows based on values in row
prt_if = self.vars.prt_if
# User may specify a subset of columns to print or
# a column ordering differ... | [
"def",
"wr_data",
"(",
"self",
",",
"xlsx_data",
",",
"row_i",
",",
"worksheet",
")",
":",
"fld2fmt",
"=",
"self",
".",
"vars",
".",
"fld2fmt",
"# User may specify to skip rows based on values in row",
"prt_if",
"=",
"self",
".",
"vars",
".",
"prt_if",
"# User m... | Write data into xlsx worksheet. | [
"Write",
"data",
"into",
"xlsx",
"worksheet",
"."
] | python | train | 54.529412 |
waqasbhatti/astrobase | astrobase/varclass/varfeatures.py | https://github.com/waqasbhatti/astrobase/blob/2922a14619d183fb28005fa7d02027ac436f2265/astrobase/varclass/varfeatures.py#L68-L131 | def stetson_jindex(ftimes, fmags, ferrs, weightbytimediff=False):
'''This calculates the Stetson index for the magseries, based on consecutive
pairs of observations.
Based on Nicole Loncke's work for her Planets and Life certificate at
Princeton in 2014.
Parameters
----------
ftimes,fmags... | [
"def",
"stetson_jindex",
"(",
"ftimes",
",",
"fmags",
",",
"ferrs",
",",
"weightbytimediff",
"=",
"False",
")",
":",
"ndet",
"=",
"len",
"(",
"fmags",
")",
"if",
"ndet",
">",
"9",
":",
"# get the median and ndet",
"medmag",
"=",
"npmedian",
"(",
"fmags",
... | This calculates the Stetson index for the magseries, based on consecutive
pairs of observations.
Based on Nicole Loncke's work for her Planets and Life certificate at
Princeton in 2014.
Parameters
----------
ftimes,fmags,ferrs : np.array
The input mag/flux time-series with all non-fin... | [
"This",
"calculates",
"the",
"Stetson",
"index",
"for",
"the",
"magseries",
"based",
"on",
"consecutive",
"pairs",
"of",
"observations",
"."
] | python | valid | 26.6875 |
icgood/pysasl | pysasl/__init__.py | https://github.com/icgood/pysasl/blob/241bdd349577cc99f05c4239755c307e6a46018c/pysasl/__init__.py#L393-L405 | def get_client(self, name):
"""Like :meth:`.get`, but only mechanisms inheriting
:class:`ClientMechanism` will be returned.
Args:
name: The SASL mechanism name.
Returns:
The mechanism object or ``None``
"""
mech = self.get(name)
return m... | [
"def",
"get_client",
"(",
"self",
",",
"name",
")",
":",
"mech",
"=",
"self",
".",
"get",
"(",
"name",
")",
"return",
"mech",
"if",
"isinstance",
"(",
"mech",
",",
"ClientMechanism",
")",
"else",
"None"
] | Like :meth:`.get`, but only mechanisms inheriting
:class:`ClientMechanism` will be returned.
Args:
name: The SASL mechanism name.
Returns:
The mechanism object or ``None`` | [
"Like",
":",
"meth",
":",
".",
"get",
"but",
"only",
"mechanisms",
"inheriting",
":",
"class",
":",
"ClientMechanism",
"will",
"be",
"returned",
"."
] | python | train | 27.538462 |
LISE-B26/pylabcontrol | build/lib/pylabcontrol/src/core/read_write_functions.py | https://github.com/LISE-B26/pylabcontrol/blob/67482e5157fcd1c40705e5c2cacfb93564703ed0/build/lib/pylabcontrol/src/core/read_write_functions.py#L95-L160 | def save_b26_file(filename, instruments=None, scripts=None, probes=None, overwrite=False, verbose=False):
"""
save instruments, scripts and probes as a json file
Args:
filename:
instruments:
scripts:
probes: dictionary of the form {instrument_name : probe_1_of_intrument, prob... | [
"def",
"save_b26_file",
"(",
"filename",
",",
"instruments",
"=",
"None",
",",
"scripts",
"=",
"None",
",",
"probes",
"=",
"None",
",",
"overwrite",
"=",
"False",
",",
"verbose",
"=",
"False",
")",
":",
"# if overwrite is false load existing data and append to new... | save instruments, scripts and probes as a json file
Args:
filename:
instruments:
scripts:
probes: dictionary of the form {instrument_name : probe_1_of_intrument, probe_2_of_intrument, ...}
Returns: | [
"save",
"instruments",
"scripts",
"and",
"probes",
"as",
"a",
"json",
"file",
"Args",
":",
"filename",
":",
"instruments",
":",
"scripts",
":",
"probes",
":",
"dictionary",
"of",
"the",
"form",
"{",
"instrument_name",
":",
"probe_1_of_intrument",
"probe_2_of_int... | python | train | 35.454545 |
catch22/pw | pw/__main__.py | https://github.com/catch22/pw/blob/2452924bbdccad28b21290b6ce062809c3d1c5f2/pw/__main__.py#L91-L182 | def pw(
ctx,
key_pattern,
user_pattern,
mode,
strict_flag,
user_flag,
file,
edit_subcommand,
gen_subcommand,
):
"""Search for USER and KEY in GPG-encrypted password file."""
# install silent Ctrl-C handler
def handle_sigint(*_):
click.echo()
ctx.exit(1)
... | [
"def",
"pw",
"(",
"ctx",
",",
"key_pattern",
",",
"user_pattern",
",",
"mode",
",",
"strict_flag",
",",
"user_flag",
",",
"file",
",",
"edit_subcommand",
",",
"gen_subcommand",
",",
")",
":",
"# install silent Ctrl-C handler",
"def",
"handle_sigint",
"(",
"*",
... | Search for USER and KEY in GPG-encrypted password file. | [
"Search",
"for",
"USER",
"and",
"KEY",
"in",
"GPG",
"-",
"encrypted",
"password",
"file",
"."
] | python | train | 30.163043 |
gbowerman/azurerm | azurerm/restfns.py | https://github.com/gbowerman/azurerm/blob/79d40431d3b13f8a36aadbff5029888383d72674/azurerm/restfns.py#L214-L249 | def do_ams_post(endpoint, path, body, access_token, rformat="json", ds_min_version="3.0;NetFx"):
'''Do a AMS HTTP POST request and return JSON.
Args:
endpoint (str): Azure Media Services Initial Endpoint.
path (str): Azure Media Services Endpoint Path.
body (str): Azure Media Services C... | [
"def",
"do_ams_post",
"(",
"endpoint",
",",
"path",
",",
"body",
",",
"access_token",
",",
"rformat",
"=",
"\"json\"",
",",
"ds_min_version",
"=",
"\"3.0;NetFx\"",
")",
":",
"min_ds",
"=",
"dsversion_min",
"content_acceptformat",
"=",
"json_acceptformat",
"acceptf... | Do a AMS HTTP POST request and return JSON.
Args:
endpoint (str): Azure Media Services Initial Endpoint.
path (str): Azure Media Services Endpoint Path.
body (str): Azure Media Services Content Body.
access_token (str): A valid Azure authentication token.
rformat (str): A re... | [
"Do",
"a",
"AMS",
"HTTP",
"POST",
"request",
"and",
"return",
"JSON",
".",
"Args",
":",
"endpoint",
"(",
"str",
")",
":",
"Azure",
"Media",
"Services",
"Initial",
"Endpoint",
".",
"path",
"(",
"str",
")",
":",
"Azure",
"Media",
"Services",
"Endpoint",
... | python | train | 45.638889 |
vtkiorg/vtki | vtki/filters.py | https://github.com/vtkiorg/vtki/blob/5ccad7ae6d64a03e9594c9c7474c8aab3eb22dd1/vtki/filters.py#L786-L811 | def split_bodies(dataset, label=False):
"""Find, label, and split connected bodies/volumes. This splits
different connected bodies into blocks in a MultiBlock dataset.
Parameters
----------
label : bool
A flag on whether to keep the ID arrays given by the
... | [
"def",
"split_bodies",
"(",
"dataset",
",",
"label",
"=",
"False",
")",
":",
"# Get the connectivity and label different bodies",
"labeled",
"=",
"dataset",
".",
"connectivity",
"(",
")",
"classifier",
"=",
"labeled",
".",
"cell_arrays",
"[",
"'RegionId'",
"]",
"b... | Find, label, and split connected bodies/volumes. This splits
different connected bodies into blocks in a MultiBlock dataset.
Parameters
----------
label : bool
A flag on whether to keep the ID arrays given by the
``connectivity`` filter. | [
"Find",
"label",
"and",
"split",
"connected",
"bodies",
"/",
"volumes",
".",
"This",
"splits",
"different",
"connected",
"bodies",
"into",
"blocks",
"in",
"a",
"MultiBlock",
"dataset",
"."
] | python | train | 38.807692 |
IBM/ibm-cos-sdk-python-s3transfer | ibm_s3transfer/aspera/manager.py | https://github.com/IBM/ibm-cos-sdk-python-s3transfer/blob/24ba53137213e26e6b8fc2c3ec1e8198d507d22b/ibm_s3transfer/aspera/manager.py#L245-L254 | def _raw_aspera_metadata(self, bucket):
''' get the Aspera connection details on Aspera enabled buckets '''
response = self._client.get_bucket_aspera(Bucket=bucket)
# Parse metadata from response
aspera_access_key = response['AccessKey']['Id']
aspera_secret_key = response['Acces... | [
"def",
"_raw_aspera_metadata",
"(",
"self",
",",
"bucket",
")",
":",
"response",
"=",
"self",
".",
"_client",
".",
"get_bucket_aspera",
"(",
"Bucket",
"=",
"bucket",
")",
"# Parse metadata from response",
"aspera_access_key",
"=",
"response",
"[",
"'AccessKey'",
"... | get the Aspera connection details on Aspera enabled buckets | [
"get",
"the",
"Aspera",
"connection",
"details",
"on",
"Aspera",
"enabled",
"buckets"
] | python | train | 44.1 |
koszullab/metaTOR | metator/scripts/hicstuff.py | https://github.com/koszullab/metaTOR/blob/0c1203d1dffedfa5ea380c0335b4baa9cfb7e89a/metator/scripts/hicstuff.py#L1452-L1480 | def positions_to_contigs(positions):
"""Label contigs according to relative positions
Given a list of positions, return an ordered list
of labels reflecting where the positions array started
over (and presumably a new contig began).
Parameters
----------
positions : list or array_like
... | [
"def",
"positions_to_contigs",
"(",
"positions",
")",
":",
"contig_labels",
"=",
"np",
".",
"zeros_like",
"(",
"positions",
")",
"contig_index",
"=",
"0",
"for",
"i",
",",
"p",
"in",
"enumerate",
"(",
"positions",
")",
":",
"if",
"p",
"==",
"0",
":",
"... | Label contigs according to relative positions
Given a list of positions, return an ordered list
of labels reflecting where the positions array started
over (and presumably a new contig began).
Parameters
----------
positions : list or array_like
A piece-wise ordered list of integers re... | [
"Label",
"contigs",
"according",
"to",
"relative",
"positions"
] | python | train | 23.689655 |
rwl/pylon | pylon/io/psse.py | https://github.com/rwl/pylon/blob/916514255db1ae1661406f0283df756baf960d14/pylon/io/psse.py#L387-L397 | def write_case_data(self, file):
""" Writes case data to file.
"""
change_code = 0
s_base = self.case.base_mva
timestr = time.strftime("%Y%m%d%H%M", time.gmtime())
file.write("%d, %8.2f, 30 / PSS(tm)E-30 RAW created by Pylon (%s).\n" %
(change_co... | [
"def",
"write_case_data",
"(",
"self",
",",
"file",
")",
":",
"change_code",
"=",
"0",
"s_base",
"=",
"self",
".",
"case",
".",
"base_mva",
"timestr",
"=",
"time",
".",
"strftime",
"(",
"\"%Y%m%d%H%M\"",
",",
"time",
".",
"gmtime",
"(",
")",
")",
"file... | Writes case data to file. | [
"Writes",
"case",
"data",
"to",
"file",
"."
] | python | train | 48.181818 |
eht16/django-axes-login-actions | axes_login_actions/signals.py | https://github.com/eht16/django-axes-login-actions/blob/1478e85831583eef8b4cb628a9744e5a16f9ef5a/axes_login_actions/signals.py#L15-L26 | def import_dotted_path(path):
"""
Takes a dotted path to a member name in a module, and returns
the member after importing it.
"""
# stolen from Mezzanine (mezzanine.utils.importing.import_dotted_path)
try:
module_path, member_name = path.rsplit(".", 1)
module = import_module(mod... | [
"def",
"import_dotted_path",
"(",
"path",
")",
":",
"# stolen from Mezzanine (mezzanine.utils.importing.import_dotted_path)",
"try",
":",
"module_path",
",",
"member_name",
"=",
"path",
".",
"rsplit",
"(",
"\".\"",
",",
"1",
")",
"module",
"=",
"import_module",
"(",
... | Takes a dotted path to a member name in a module, and returns
the member after importing it. | [
"Takes",
"a",
"dotted",
"path",
"to",
"a",
"member",
"name",
"in",
"a",
"module",
"and",
"returns",
"the",
"member",
"after",
"importing",
"it",
"."
] | python | train | 41.666667 |
helixyte/everest | everest/representers/base.py | https://github.com/helixyte/everest/blob/70c9b93c3061db5cb62428349d18b8fb8566411b/everest/representers/base.py#L215-L224 | def create_from_resource_class(cls, resource_class):
"""
Creates a new representer for the given resource class.
The representer obtains a reference to the (freshly created or looked
up) mapping for the resource class.
"""
mp_reg = get_mapping_registry(cls.content_type)
... | [
"def",
"create_from_resource_class",
"(",
"cls",
",",
"resource_class",
")",
":",
"mp_reg",
"=",
"get_mapping_registry",
"(",
"cls",
".",
"content_type",
")",
"mp",
"=",
"mp_reg",
".",
"find_or_create_mapping",
"(",
"resource_class",
")",
"return",
"cls",
"(",
"... | Creates a new representer for the given resource class.
The representer obtains a reference to the (freshly created or looked
up) mapping for the resource class. | [
"Creates",
"a",
"new",
"representer",
"for",
"the",
"given",
"resource",
"class",
"."
] | python | train | 40.8 |
django-extensions/django-extensions | django_extensions/management/commands/merge_model_instances.py | https://github.com/django-extensions/django-extensions/blob/7e0bef97ea6cb7f9eea5e2528e3a985a83a7b9b8/django_extensions/management/commands/merge_model_instances.py#L132-L222 | def merge_model_instances(self, primary_object, alias_objects):
"""
Merge several model instances into one, the `primary_object`.
Use this function to merge model objects and migrate all of the related
fields from the alias objects the primary object.
"""
generic_fields =... | [
"def",
"merge_model_instances",
"(",
"self",
",",
"primary_object",
",",
"alias_objects",
")",
":",
"generic_fields",
"=",
"get_generic_fields",
"(",
")",
"# get related fields",
"related_fields",
"=",
"list",
"(",
"filter",
"(",
"lambda",
"x",
":",
"x",
".",
"i... | Merge several model instances into one, the `primary_object`.
Use this function to merge model objects and migrate all of the related
fields from the alias objects the primary object. | [
"Merge",
"several",
"model",
"instances",
"into",
"one",
"the",
"primary_object",
".",
"Use",
"this",
"function",
"to",
"merge",
"model",
"objects",
"and",
"migrate",
"all",
"of",
"the",
"related",
"fields",
"from",
"the",
"alias",
"objects",
"the",
"primary",... | python | train | 50.89011 |
JoelBender/bacpypes | py34/bacpypes/service/object.py | https://github.com/JoelBender/bacpypes/blob/4111b8604a16fa2b7f80d8104a43b9f3e28dfc78/py34/bacpypes/service/object.py#L193-L223 | def read_property_to_result_element(obj, propertyIdentifier, propertyArrayIndex=None):
"""Read the specified property of the object, with the optional array index,
and cast the result into an Any object."""
if _debug: read_property_to_result_element._debug("read_property_to_result_element %s %r %r", obj, pr... | [
"def",
"read_property_to_result_element",
"(",
"obj",
",",
"propertyIdentifier",
",",
"propertyArrayIndex",
"=",
"None",
")",
":",
"if",
"_debug",
":",
"read_property_to_result_element",
".",
"_debug",
"(",
"\"read_property_to_result_element %s %r %r\"",
",",
"obj",
",",
... | Read the specified property of the object, with the optional array index,
and cast the result into an Any object. | [
"Read",
"the",
"specified",
"property",
"of",
"the",
"object",
"with",
"the",
"optional",
"array",
"index",
"and",
"cast",
"the",
"result",
"into",
"an",
"Any",
"object",
"."
] | python | train | 50.516129 |
CxAalto/gtfspy | gtfspy/routing/node_profile_analyzer_time_and_veh_legs.py | https://github.com/CxAalto/gtfspy/blob/bddba4b74faae6c1b91202f19184811e326547e5/gtfspy/routing/node_profile_analyzer_time_and_veh_legs.py#L47-L56 | def _truncate_colormap(cmap, minval=0.0, maxval=1.0, n=100):
"""
Truncates a colormap to use.
Code originall from http://stackoverflow.com/questions/18926031/how-to-extract-a-subset-of-a-colormap-as-a-new-colormap-in-matplotlib
"""
new_cmap = LinearSegmentedColormap.from_list(
'trunc({n},{a:... | [
"def",
"_truncate_colormap",
"(",
"cmap",
",",
"minval",
"=",
"0.0",
",",
"maxval",
"=",
"1.0",
",",
"n",
"=",
"100",
")",
":",
"new_cmap",
"=",
"LinearSegmentedColormap",
".",
"from_list",
"(",
"'trunc({n},{a:.2f},{b:.2f})'",
".",
"format",
"(",
"n",
"=",
... | Truncates a colormap to use.
Code originall from http://stackoverflow.com/questions/18926031/how-to-extract-a-subset-of-a-colormap-as-a-new-colormap-in-matplotlib | [
"Truncates",
"a",
"colormap",
"to",
"use",
".",
"Code",
"originall",
"from",
"http",
":",
"//",
"stackoverflow",
".",
"com",
"/",
"questions",
"/",
"18926031",
"/",
"how",
"-",
"to",
"-",
"extract",
"-",
"a",
"-",
"subset",
"-",
"of",
"-",
"a",
"-",
... | python | valid | 44 |
ThreatConnect-Inc/tcex | tcex/tcex.py | https://github.com/ThreatConnect-Inc/tcex/blob/dd4d7a1ef723af1561687120191886b9a2fd4b47/tcex/tcex.py#L964-L980 | def safe_tag(self, tag, errors='strict'):
"""URL Encode and truncate tag to match limit (128 characters) of ThreatConnect API.
Args:
tag (string): The tag to be truncated
Returns:
(string): The truncated tag
"""
if tag is not None:
try:
... | [
"def",
"safe_tag",
"(",
"self",
",",
"tag",
",",
"errors",
"=",
"'strict'",
")",
":",
"if",
"tag",
"is",
"not",
"None",
":",
"try",
":",
"# handle unicode characters and url encode tag value",
"tag",
"=",
"quote",
"(",
"self",
".",
"s",
"(",
"tag",
",",
... | URL Encode and truncate tag to match limit (128 characters) of ThreatConnect API.
Args:
tag (string): The tag to be truncated
Returns:
(string): The truncated tag | [
"URL",
"Encode",
"and",
"truncate",
"tag",
"to",
"match",
"limit",
"(",
"128",
"characters",
")",
"of",
"ThreatConnect",
"API",
"."
] | python | train | 35.470588 |
LinuxChristian/pyW215 | pyW215/pyW215.py | https://github.com/LinuxChristian/pyW215/blob/63e50b8ee11bc38ed66554f9b92429b552dda550/pyW215/pyW215.py#L199-L222 | def current_consumption(self):
"""Get the current power consumption in Watt."""
res = 'N/A'
if self.use_legacy_protocol:
# Use /my_cgi.cgi to retrieve current consumption
try:
res = self.fetchMyCgi()['Meter Watt']
except:
return... | [
"def",
"current_consumption",
"(",
"self",
")",
":",
"res",
"=",
"'N/A'",
"if",
"self",
".",
"use_legacy_protocol",
":",
"# Use /my_cgi.cgi to retrieve current consumption",
"try",
":",
"res",
"=",
"self",
".",
"fetchMyCgi",
"(",
")",
"[",
"'Meter Watt'",
"]",
"... | Get the current power consumption in Watt. | [
"Get",
"the",
"current",
"power",
"consumption",
"in",
"Watt",
"."
] | python | train | 30.416667 |
openvax/mhcflurry | mhcflurry/parallelism.py | https://github.com/openvax/mhcflurry/blob/deb7c1629111254b484a2711619eb2347db36524/mhcflurry/parallelism.py#L115-L188 | def make_worker_pool(
processes=None,
initializer=None,
initializer_kwargs_per_process=None,
max_tasks_per_worker=None):
"""
Convenience wrapper to create a multiprocessing.Pool.
This function adds support for per-worker initializer arguments, which are
not natively supp... | [
"def",
"make_worker_pool",
"(",
"processes",
"=",
"None",
",",
"initializer",
"=",
"None",
",",
"initializer_kwargs_per_process",
"=",
"None",
",",
"max_tasks_per_worker",
"=",
"None",
")",
":",
"if",
"not",
"processes",
":",
"processes",
"=",
"cpu_count",
"(",
... | Convenience wrapper to create a multiprocessing.Pool.
This function adds support for per-worker initializer arguments, which are
not natively supported by the multiprocessing module. The motivation for
this feature is to support allocating each worker to a (different) GPU.
IMPLEMENTATION NOTE:
... | [
"Convenience",
"wrapper",
"to",
"create",
"a",
"multiprocessing",
".",
"Pool",
"."
] | python | train | 37.135135 |
clusterpoint/python-client-api | pycps/response.py | https://github.com/clusterpoint/python-client-api/blob/fabf9bd8355aa54ba08fd6649e48f16e2c35eacd/pycps/response.py#L324-L335 | def get_words(self):
""" Get words matching the request search terms.
Returns:
A dict in form:
{<search term>: {<matching word>: <number of times this word is found in the Storage>
} // Repeated for every matching word.
... | [
"def",
"get_words",
"(",
"self",
")",
":",
"return",
"dict",
"(",
"[",
"(",
"word_list",
".",
"attrib",
"[",
"'to'",
"]",
",",
"dict",
"(",
"[",
"(",
"word",
".",
"text",
",",
"word",
".",
"attrib",
"[",
"'count'",
"]",
")",
"for",
"word",
"in",
... | Get words matching the request search terms.
Returns:
A dict in form:
{<search term>: {<matching word>: <number of times this word is found in the Storage>
} // Repeated for every matching word.
} // Repeated for ev... | [
"Get",
"words",
"matching",
"the",
"request",
"search",
"terms",
"."
] | python | train | 51.583333 |
rhelmot/nclib | nclib/netcat.py | https://github.com/rhelmot/nclib/blob/6147779766557ee4fafcbae683bdd2f74157e825/nclib/netcat.py#L697-L710 | def send(self, s):
"""
Sends all the given data to the socket.
Aliases: write, put, sendall, send_all
"""
self._print_header('======== Sending ({0}) ========'.format(len(s)))
self._log_send(s)
out = len(s)
while s:
s = s[self._send(s):]
... | [
"def",
"send",
"(",
"self",
",",
"s",
")",
":",
"self",
".",
"_print_header",
"(",
"'======== Sending ({0}) ========'",
".",
"format",
"(",
"len",
"(",
"s",
")",
")",
")",
"self",
".",
"_log_send",
"(",
"s",
")",
"out",
"=",
"len",
"(",
"s",
")",
"... | Sends all the given data to the socket.
Aliases: write, put, sendall, send_all | [
"Sends",
"all",
"the",
"given",
"data",
"to",
"the",
"socket",
"."
] | python | train | 22.928571 |
stevepeak/inquiry | inquiry/garden.py | https://github.com/stevepeak/inquiry/blob/f6ea435c302560ba19985b5d4ce2c97e2f321508/inquiry/garden.py#L98-L256 | def _harvest_validate(self, userkwargs):
"""Validate and Plant user provided arguments
- Go through and plants the seedlings
for any user arguments provided.
- Validate the arguments, cleaning and adapting (valideer wise)
- Extract negatives "!" arguments
"""
# ... | [
"def",
"_harvest_validate",
"(",
"self",
",",
"userkwargs",
")",
":",
"# the valideer to parse the",
"# user arguemnts when watering",
"parser",
"=",
"{",
"}",
"userkwargs",
".",
"update",
"(",
"self",
".",
"network_kwargs",
")",
"# a simple set of original provided argum... | Validate and Plant user provided arguments
- Go through and plants the seedlings
for any user arguments provided.
- Validate the arguments, cleaning and adapting (valideer wise)
- Extract negatives "!" arguments | [
"Validate",
"and",
"Plant",
"user",
"provided",
"arguments",
"-",
"Go",
"through",
"and",
"plants",
"the",
"seedlings",
"for",
"any",
"user",
"arguments",
"provided",
".",
"-",
"Validate",
"the",
"arguments",
"cleaning",
"and",
"adapting",
"(",
"valideer",
"wi... | python | train | 40.874214 |
mcocdawc/chemcoord | src/chemcoord/cartesian_coordinates/_cartesian_class_get_zmat.py | https://github.com/mcocdawc/chemcoord/blob/95561ce387c142227c38fb14a1d182179aef8f5f/src/chemcoord/cartesian_coordinates/_cartesian_class_get_zmat.py#L637-L739 | def get_grad_zmat(self, construction_table, as_function=True):
r"""Return the gradient for the transformation to a Zmatrix.
If ``as_function`` is True, a function is returned that can be directly
applied onto instances of :class:`~Cartesian`, which contain the
applied distortions in car... | [
"def",
"get_grad_zmat",
"(",
"self",
",",
"construction_table",
",",
"as_function",
"=",
"True",
")",
":",
"if",
"(",
"construction_table",
".",
"index",
"!=",
"self",
".",
"index",
")",
".",
"any",
"(",
")",
":",
"message",
"=",
"\"construction_table and se... | r"""Return the gradient for the transformation to a Zmatrix.
If ``as_function`` is True, a function is returned that can be directly
applied onto instances of :class:`~Cartesian`, which contain the
applied distortions in cartesian space.
In this case the user does not have to worry abou... | [
"r",
"Return",
"the",
"gradient",
"for",
"the",
"transformation",
"to",
"a",
"Zmatrix",
"."
] | python | train | 37.805825 |
inasafe/inasafe | safe/definitions/utilities.py | https://github.com/inasafe/inasafe/blob/831d60abba919f6d481dc94a8d988cc205130724/safe/definitions/utilities.py#L297-L320 | def get_name(key):
"""Given a keyword, try to get the name of it.
.. versionadded:: 4.2
Definition dicts are defined in keywords.py. We try to return
the name if present, otherwise we return none.
keyword = 'layer_purpose'
kio = safe.utilities.keyword_io.Keyword_IO()
name = kio.get_name(k... | [
"def",
"get_name",
"(",
"key",
")",
":",
"definition_dict",
"=",
"definition",
"(",
"key",
")",
"if",
"definition_dict",
":",
"return",
"definition_dict",
".",
"get",
"(",
"'name'",
",",
"key",
")",
"# Else, return the keyword",
"return",
"key"
] | Given a keyword, try to get the name of it.
.. versionadded:: 4.2
Definition dicts are defined in keywords.py. We try to return
the name if present, otherwise we return none.
keyword = 'layer_purpose'
kio = safe.utilities.keyword_io.Keyword_IO()
name = kio.get_name(keyword)
print name
... | [
"Given",
"a",
"keyword",
"try",
"to",
"get",
"the",
"name",
"of",
"it",
"."
] | python | train | 24.541667 |
cjdrake/pyeda | pyeda/parsing/boolexpr.py | https://github.com/cjdrake/pyeda/blob/554ee53aa678f4b61bcd7e07ba2c74ddc749d665/pyeda/parsing/boolexpr.py#L622-L627 | def _names(lexer):
"""Return a tuple of names."""
first = _expect_token(lexer, {NameToken}).value
rest = _zom_name(lexer)
rnames = (first, ) + rest
return rnames[::-1] | [
"def",
"_names",
"(",
"lexer",
")",
":",
"first",
"=",
"_expect_token",
"(",
"lexer",
",",
"{",
"NameToken",
"}",
")",
".",
"value",
"rest",
"=",
"_zom_name",
"(",
"lexer",
")",
"rnames",
"=",
"(",
"first",
",",
")",
"+",
"rest",
"return",
"rnames",
... | Return a tuple of names. | [
"Return",
"a",
"tuple",
"of",
"names",
"."
] | python | train | 30.333333 |
pyroscope/auvyon | src/auvyon/imaging/waveforms.py | https://github.com/pyroscope/auvyon/blob/5115c26f966df03df92a9934580b66c72e23d4e8/src/auvyon/imaging/waveforms.py#L23-L42 | def waveform_image(mediafile, xy_size, outdir=None, center_color=None, outer_color=None, bg_color=None):
""" Create waveform image from audio data.
Return path to created image file.
"""
try:
import waveform
except ImportError, exc:
raise ImportError("%s [get it at https://github... | [
"def",
"waveform_image",
"(",
"mediafile",
",",
"xy_size",
",",
"outdir",
"=",
"None",
",",
"center_color",
"=",
"None",
",",
"outer_color",
"=",
"None",
",",
"bg_color",
"=",
"None",
")",
":",
"try",
":",
"import",
"waveform",
"except",
"ImportError",
","... | Create waveform image from audio data.
Return path to created image file. | [
"Create",
"waveform",
"image",
"from",
"audio",
"data",
".",
"Return",
"path",
"to",
"created",
"image",
"file",
"."
] | python | train | 40.3 |
nicolargo/glances | glances/processes.py | https://github.com/nicolargo/glances/blob/5bd4d587a736e0d2b03170b56926841d2a3eb7ee/glances/processes.py#L89-L102 | def update_processcount(self, plist):
"""Update the global process count from the current processes list"""
# Update the maximum process ID (pid) number
self.processcount['pid_max'] = self.pid_max
# For each key in the processcount dict
# count the number of processes with the sa... | [
"def",
"update_processcount",
"(",
"self",
",",
"plist",
")",
":",
"# Update the maximum process ID (pid) number",
"self",
".",
"processcount",
"[",
"'pid_max'",
"]",
"=",
"self",
".",
"pid_max",
"# For each key in the processcount dict",
"# count the number of processes with... | Update the global process count from the current processes list | [
"Update",
"the",
"global",
"process",
"count",
"from",
"the",
"current",
"processes",
"list"
] | python | train | 53.357143 |
google/grr | grr/server/grr_response_server/aff4.py | https://github.com/google/grr/blob/5cef4e8e2f0d5df43ea4877e9c798e0bf60bfe74/grr/server/grr_response_server/aff4.py#L1843-L1867 | def UpdateLease(self, duration):
"""Updates the lease and flushes the object.
The lease is set to expire after the "duration" time from the present
moment.
This method is supposed to be used when operation that requires locking
may run for a time that exceeds the lease time specified in OpenWithLoc... | [
"def",
"UpdateLease",
"(",
"self",
",",
"duration",
")",
":",
"if",
"not",
"self",
".",
"locked",
":",
"raise",
"LockError",
"(",
"\"Object must be locked to update the lease: %s.\"",
"%",
"self",
".",
"urn",
")",
"if",
"self",
".",
"CheckLease",
"(",
")",
"... | Updates the lease and flushes the object.
The lease is set to expire after the "duration" time from the present
moment.
This method is supposed to be used when operation that requires locking
may run for a time that exceeds the lease time specified in OpenWithLock().
See flows/hunts locking for an ... | [
"Updates",
"the",
"lease",
"and",
"flushes",
"the",
"object",
"."
] | python | train | 33.24 |
tensorflow/probability | tensorflow_probability/python/glm/fisher_scoring.py | https://github.com/tensorflow/probability/blob/e87fe34111d68c35db0f9eeb4935f1ece9e1a8f5/tensorflow_probability/python/glm/fisher_scoring.py#L517-L620 | def prepare_args(model_matrix,
response,
model_coefficients,
predicted_linear_response,
offset,
name=None):
"""Helper to `fit` which sanitizes input args.
Args:
model_matrix: (Batch of) `float`-like, matrix-shaped `Tensor` whe... | [
"def",
"prepare_args",
"(",
"model_matrix",
",",
"response",
",",
"model_coefficients",
",",
"predicted_linear_response",
",",
"offset",
",",
"name",
"=",
"None",
")",
":",
"graph_deps",
"=",
"[",
"model_matrix",
",",
"response",
",",
"model_coefficients",
",",
... | Helper to `fit` which sanitizes input args.
Args:
model_matrix: (Batch of) `float`-like, matrix-shaped `Tensor` where each row
represents a sample's features.
response: (Batch of) vector-shaped `Tensor` where each element represents a
sample's observed response (to the corresponding row of featur... | [
"Helper",
"to",
"fit",
"which",
"sanitizes",
"input",
"args",
"."
] | python | test | 43.692308 |
bcbio/bcbio-nextgen | bcbio/pipeline/region.py | https://github.com/bcbio/bcbio-nextgen/blob/6a9348c0054ccd5baffd22f1bb7d0422f6978b20/bcbio/pipeline/region.py#L143-L164 | def parallel_prep_region(samples, run_parallel):
"""Perform full pre-variant calling BAM prep work on regions.
"""
file_key = "work_bam"
split_fn = _split_by_regions("bamprep", "-prep.bam", file_key)
# identify samples that do not need preparation -- no recalibration or realignment
extras = []
... | [
"def",
"parallel_prep_region",
"(",
"samples",
",",
"run_parallel",
")",
":",
"file_key",
"=",
"\"work_bam\"",
"split_fn",
"=",
"_split_by_regions",
"(",
"\"bamprep\"",
",",
"\"-prep.bam\"",
",",
"file_key",
")",
"# identify samples that do not need preparation -- no recali... | Perform full pre-variant calling BAM prep work on regions. | [
"Perform",
"full",
"pre",
"-",
"variant",
"calling",
"BAM",
"prep",
"work",
"on",
"regions",
"."
] | python | train | 48.045455 |
yamcs/yamcs-python | yamcs-client/examples/parameter_subscription.py | https://github.com/yamcs/yamcs-python/blob/1082fee8a299010cc44416bbb7518fac0ef08b48/yamcs-client/examples/parameter_subscription.py#L34-L61 | def manage_subscription():
"""Shows how to interact with a parameter subscription."""
subscription = processor.create_parameter_subscription([
'/YSS/SIMULATOR/BatteryVoltage1'
])
sleep(5)
print('Adding extra items to the existing subscription...')
subscription.add([
'/YSS/SIMUL... | [
"def",
"manage_subscription",
"(",
")",
":",
"subscription",
"=",
"processor",
".",
"create_parameter_subscription",
"(",
"[",
"'/YSS/SIMULATOR/BatteryVoltage1'",
"]",
")",
"sleep",
"(",
"5",
")",
"print",
"(",
"'Adding extra items to the existing subscription...'",
")",
... | Shows how to interact with a parameter subscription. | [
"Shows",
"how",
"to",
"interact",
"with",
"a",
"parameter",
"subscription",
"."
] | python | train | 31.607143 |
tensorflow/tensor2tensor | tensor2tensor/layers/common_layers.py | https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/layers/common_layers.py#L3985-L4004 | def kl_divergence(mu, log_var, mu_p=0.0, log_var_p=0.0):
"""KL divergence of diagonal gaussian N(mu,exp(log_var)) and N(0,1).
Args:
mu: mu parameter of the distribution.
log_var: log(var) parameter of the distribution.
mu_p: optional mu from a learned prior distribution
log_var_p: optional log(var)... | [
"def",
"kl_divergence",
"(",
"mu",
",",
"log_var",
",",
"mu_p",
"=",
"0.0",
",",
"log_var_p",
"=",
"0.0",
")",
":",
"batch_size",
"=",
"shape_list",
"(",
"mu",
")",
"[",
"0",
"]",
"prior_distribution",
"=",
"tfp",
".",
"distributions",
".",
"Normal",
"... | KL divergence of diagonal gaussian N(mu,exp(log_var)) and N(0,1).
Args:
mu: mu parameter of the distribution.
log_var: log(var) parameter of the distribution.
mu_p: optional mu from a learned prior distribution
log_var_p: optional log(var) from a learned prior distribution
Returns:
the KL loss. | [
"KL",
"divergence",
"of",
"diagonal",
"gaussian",
"N",
"(",
"mu",
"exp",
"(",
"log_var",
"))",
"and",
"N",
"(",
"0",
"1",
")",
"."
] | python | train | 38.7 |
Microsoft/azure-devops-python-api | azure-devops/azure/devops/v5_0/core/core_client.py | https://github.com/Microsoft/azure-devops-python-api/blob/4777ffda2f5052fabbaddb2abe9cb434e0cf1aa8/azure-devops/azure/devops/v5_0/core/core_client.py#L64-L82 | def get_connected_services(self, project_id, kind=None):
"""GetConnectedServices.
[Preview API]
:param str project_id:
:param str kind:
:rtype: [WebApiConnectedService]
"""
route_values = {}
if project_id is not None:
route_values['projectId'] ... | [
"def",
"get_connected_services",
"(",
"self",
",",
"project_id",
",",
"kind",
"=",
"None",
")",
":",
"route_values",
"=",
"{",
"}",
"if",
"project_id",
"is",
"not",
"None",
":",
"route_values",
"[",
"'projectId'",
"]",
"=",
"self",
".",
"_serialize",
".",
... | GetConnectedServices.
[Preview API]
:param str project_id:
:param str kind:
:rtype: [WebApiConnectedService] | [
"GetConnectedServices",
".",
"[",
"Preview",
"API",
"]",
":",
"param",
"str",
"project_id",
":",
":",
"param",
"str",
"kind",
":",
":",
"rtype",
":",
"[",
"WebApiConnectedService",
"]"
] | python | train | 47.421053 |
timeyyy/apptools | peasoup/peasoup.py | https://github.com/timeyyy/apptools/blob/d3c0f324b0c2689c35f5601348276f4efd6cb240/peasoup/peasoup.py#L106-L142 | def create_cfg(self, cfg_file, defaults=None, mode='json'):
'''
set mode to json or yaml? probably remove this option..Todo
Creates the config file for your app with default values
The file will only be created if it doesn't exits
also sets up the first_run attribute.
... | [
"def",
"create_cfg",
"(",
"self",
",",
"cfg_file",
",",
"defaults",
"=",
"None",
",",
"mode",
"=",
"'json'",
")",
":",
"assert",
"mode",
"in",
"(",
"'json'",
",",
"'yaml'",
")",
"self",
".",
"cfg_mode",
"=",
"mode",
"self",
".",
"cfg_file",
"=",
"cfg... | set mode to json or yaml? probably remove this option..Todo
Creates the config file for your app with default values
The file will only be created if it doesn't exits
also sets up the first_run attribute.
also sets correct windows permissions
you can add custom stuff to the c... | [
"set",
"mode",
"to",
"json",
"or",
"yaml?",
"probably",
"remove",
"this",
"option",
"..",
"Todo"
] | python | train | 33.297297 |
aio-libs/aiohttp | aiohttp/web_request.py | https://github.com/aio-libs/aiohttp/blob/9504fe2affaaff673fa4f3754c1c44221f8ba47d/aiohttp/web_request.py#L476-L484 | def cookies(self) -> Mapping[str, str]:
"""Return request cookies.
A read-only dictionary-like object.
"""
raw = self.headers.get(hdrs.COOKIE, '')
parsed = SimpleCookie(raw)
return MappingProxyType(
{key: val.value for key, val in parsed.items()}) | [
"def",
"cookies",
"(",
"self",
")",
"->",
"Mapping",
"[",
"str",
",",
"str",
"]",
":",
"raw",
"=",
"self",
".",
"headers",
".",
"get",
"(",
"hdrs",
".",
"COOKIE",
",",
"''",
")",
"parsed",
"=",
"SimpleCookie",
"(",
"raw",
")",
"return",
"MappingPro... | Return request cookies.
A read-only dictionary-like object. | [
"Return",
"request",
"cookies",
"."
] | python | train | 33.333333 |
facebook/watchman | python/pywatchman_aio/__init__.py | https://github.com/facebook/watchman/blob/d416c249dd8f463dc69fc2691d0f890598c045a9/python/pywatchman_aio/__init__.py#L240-L246 | async def receive_bilateral_response(self):
"""Receive the response to a request made to the Watchman service."""
self._check_receive_loop()
resp = await self.bilateral_response_queue.get()
self._check_error(resp)
return resp | [
"async",
"def",
"receive_bilateral_response",
"(",
"self",
")",
":",
"self",
".",
"_check_receive_loop",
"(",
")",
"resp",
"=",
"await",
"self",
".",
"bilateral_response_queue",
".",
"get",
"(",
")",
"self",
".",
"_check_error",
"(",
"resp",
")",
"return",
"... | Receive the response to a request made to the Watchman service. | [
"Receive",
"the",
"response",
"to",
"a",
"request",
"made",
"to",
"the",
"Watchman",
"service",
"."
] | python | train | 37.142857 |
shmuelamar/cbox | cbox/__main__.py | https://github.com/shmuelamar/cbox/blob/2d0cda5b3f61a55e530251430bf3d460dcd3732e/cbox/__main__.py#L77-L95 | def get_inline_func(inline_str, modules=None, **stream_kwargs):
"""returns a function decorated by `cbox.stream` decorator.
:param str inline_str: the inline function to execute,
can use `s` - local variable as the input line/char/raw
(according to `input_type` param).
:param str modules: comma... | [
"def",
"get_inline_func",
"(",
"inline_str",
",",
"modules",
"=",
"None",
",",
"*",
"*",
"stream_kwargs",
")",
":",
"if",
"not",
"_is_compilable",
"(",
"inline_str",
")",
":",
"raise",
"ValueError",
"(",
"'cannot compile the inline expression - \"%s\"'",
"%",
"inl... | returns a function decorated by `cbox.stream` decorator.
:param str inline_str: the inline function to execute,
can use `s` - local variable as the input line/char/raw
(according to `input_type` param).
:param str modules: comma separated list of modules to import before
running the inline fu... | [
"returns",
"a",
"function",
"decorated",
"by",
"cbox",
".",
"stream",
"decorator",
"."
] | python | train | 40.578947 |
bfrog/whizzer | whizzer/defer.py | https://github.com/bfrog/whizzer/blob/a1e43084b3ac8c1f3fb4ada081777cdbf791fd77/whizzer/defer.py#L172-L175 | def add_callback(self, callback, *callback_args, **callback_kwargs):
"""Add a callback without an associated errback."""
return self.add_callbacks(callback, callback_args=callback_args,
callback_kwargs=callback_kwargs) | [
"def",
"add_callback",
"(",
"self",
",",
"callback",
",",
"*",
"callback_args",
",",
"*",
"*",
"callback_kwargs",
")",
":",
"return",
"self",
".",
"add_callbacks",
"(",
"callback",
",",
"callback_args",
"=",
"callback_args",
",",
"callback_kwargs",
"=",
"callb... | Add a callback without an associated errback. | [
"Add",
"a",
"callback",
"without",
"an",
"associated",
"errback",
"."
] | python | train | 64.5 |
timothydmorton/isochrones | isochrones/starmodel_old.py | https://github.com/timothydmorton/isochrones/blob/d84495573044c66db2fd6b959fe69e370757ea14/isochrones/starmodel_old.py#L1095-L1140 | def load_hdf(cls, filename, path='', name=None):
"""
A class method to load a saved StarModel from an HDF5 file.
File must have been created by a call to :func:`StarModel.save_hdf`.
:param filename:
H5 file to load.
:param path: (optional)
Path within H... | [
"def",
"load_hdf",
"(",
"cls",
",",
"filename",
",",
"path",
"=",
"''",
",",
"name",
"=",
"None",
")",
":",
"store",
"=",
"pd",
".",
"HDFStore",
"(",
"filename",
")",
"try",
":",
"samples",
"=",
"store",
"[",
"'{}/samples'",
".",
"format",
"(",
"pa... | A class method to load a saved StarModel from an HDF5 file.
File must have been created by a call to :func:`StarModel.save_hdf`.
:param filename:
H5 file to load.
:param path: (optional)
Path within HDF file.
:return:
:class:`StarModel` object. | [
"A",
"class",
"method",
"to",
"load",
"a",
"saved",
"StarModel",
"from",
"an",
"HDF5",
"file",
"."
] | python | train | 28.217391 |
hanguokai/youku | youku/youku_playlists.py | https://github.com/hanguokai/youku/blob/b2df060c7dccfad990bcfa289fff68bb77d1e69b/youku/youku_playlists.py#L33-L43 | def find_playlists_by_ids(self, playlist_ids):
"""doc: http://open.youku.com/docs/doc?id=67
"""
url = 'https://openapi.youku.com/v2/playlists/show_batch.json'
params = {
'client_id': self.client_id,
'playlist_ids': playlist_ids
}
r = requests.get(u... | [
"def",
"find_playlists_by_ids",
"(",
"self",
",",
"playlist_ids",
")",
":",
"url",
"=",
"'https://openapi.youku.com/v2/playlists/show_batch.json'",
"params",
"=",
"{",
"'client_id'",
":",
"self",
".",
"client_id",
",",
"'playlist_ids'",
":",
"playlist_ids",
"}",
"r",
... | doc: http://open.youku.com/docs/doc?id=67 | [
"doc",
":",
"http",
":",
"//",
"open",
".",
"youku",
".",
"com",
"/",
"docs",
"/",
"doc?id",
"=",
"67"
] | python | train | 34.090909 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.