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 |
|---|---|---|---|---|---|---|---|---|---|
Qiskit/qiskit-terra | qiskit/qobj/converters/lo_config.py | https://github.com/Qiskit/qiskit-terra/blob/d4f58d903bc96341b816f7c35df936d6421267d1/qiskit/qobj/converters/lo_config.py#L79-L102 | def get_meas_los(self, user_lo_config):
"""Embed default meas LO frequencies from backend and format them to list object.
If configured lo frequency is the same as default, this method returns `None`.
Args:
user_lo_config (LoConfig): A dictionary of LOs to format.
Returns:
... | [
"def",
"get_meas_los",
"(",
"self",
",",
"user_lo_config",
")",
":",
"try",
":",
"_m_los",
"=",
"self",
".",
"default_meas_los",
".",
"copy",
"(",
")",
"except",
"KeyError",
":",
"raise",
"PulseError",
"(",
"'Default measurement frequencies not exist.'",
")",
"f... | Embed default meas LO frequencies from backend and format them to list object.
If configured lo frequency is the same as default, this method returns `None`.
Args:
user_lo_config (LoConfig): A dictionary of LOs to format.
Returns:
list: A list of meas LOs.
Rais... | [
"Embed",
"default",
"meas",
"LO",
"frequencies",
"from",
"backend",
"and",
"format",
"them",
"to",
"list",
"object",
".",
"If",
"configured",
"lo",
"frequency",
"is",
"the",
"same",
"as",
"default",
"this",
"method",
"returns",
"None",
"."
] | python | test | 32.916667 |
idlesign/uwsgiconf | uwsgiconf/utils.py | https://github.com/idlesign/uwsgiconf/blob/475407acb44199edbf7e0a66261bfeb51de1afae/uwsgiconf/utils.py#L287-L302 | def cmd_log(self, reopen=False, rotate=False):
"""Allows managing of uWSGI log related stuff
:param bool reopen: Reopen log file. Could be required after third party rotation.
:param bool rotate: Trigger built-in log rotation.
"""
cmd = b''
if reopen:
cmd +... | [
"def",
"cmd_log",
"(",
"self",
",",
"reopen",
"=",
"False",
",",
"rotate",
"=",
"False",
")",
":",
"cmd",
"=",
"b''",
"if",
"reopen",
":",
"cmd",
"+=",
"b'l'",
"if",
"rotate",
":",
"cmd",
"+=",
"b'L'",
"return",
"self",
".",
"send_command",
"(",
"c... | Allows managing of uWSGI log related stuff
:param bool reopen: Reopen log file. Could be required after third party rotation.
:param bool rotate: Trigger built-in log rotation. | [
"Allows",
"managing",
"of",
"uWSGI",
"log",
"related",
"stuff"
] | python | train | 24.625 |
J535D165/recordlinkage | recordlinkage/algorithms/indexing.py | https://github.com/J535D165/recordlinkage/blob/87a5f4af904e0834047cd07ff1c70146b1e6d693/recordlinkage/algorithms/indexing.py#L27-L44 | def random_pairs_with_replacement(n, shape, random_state=None):
"""make random record pairs"""
if not isinstance(random_state, np.random.RandomState):
random_state = np.random.RandomState(random_state)
n_max = max_pairs(shape)
if n_max <= 0:
raise ValueError('n_max must be larger than... | [
"def",
"random_pairs_with_replacement",
"(",
"n",
",",
"shape",
",",
"random_state",
"=",
"None",
")",
":",
"if",
"not",
"isinstance",
"(",
"random_state",
",",
"np",
".",
"random",
".",
"RandomState",
")",
":",
"random_state",
"=",
"np",
".",
"random",
".... | make random record pairs | [
"make",
"random",
"record",
"pairs"
] | python | train | 28.666667 |
pytroll/trollimage | trollimage/image.py | https://github.com/pytroll/trollimage/blob/d35a7665ad475ff230e457085523e21f2cd3f454/trollimage/image.py#L915-L933 | def invert(self, invert=True):
"""Inverts all the channels of a image according to *invert*. If invert is a tuple or a list, elementwise
invertion is performed, otherwise all channels are inverted if *invert* is true (default).
Note: 'Inverting' means that black becomes white, and vice-versa, n... | [
"def",
"invert",
"(",
"self",
",",
"invert",
"=",
"True",
")",
":",
"if",
"(",
"isinstance",
"(",
"invert",
",",
"(",
"tuple",
",",
"list",
")",
")",
"and",
"len",
"(",
"self",
".",
"channels",
")",
"!=",
"len",
"(",
"invert",
")",
")",
":",
"r... | Inverts all the channels of a image according to *invert*. If invert is a tuple or a list, elementwise
invertion is performed, otherwise all channels are inverted if *invert* is true (default).
Note: 'Inverting' means that black becomes white, and vice-versa, not that the values are negated ! | [
"Inverts",
"all",
"the",
"channels",
"of",
"a",
"image",
"according",
"to",
"*",
"invert",
"*",
".",
"If",
"invert",
"is",
"a",
"tuple",
"or",
"a",
"list",
"elementwise",
"invertion",
"is",
"performed",
"otherwise",
"all",
"channels",
"are",
"inverted",
"i... | python | train | 47.578947 |
sendwithus/sendwithus_python | sendwithus/__init__.py | https://github.com/sendwithus/sendwithus_python/blob/8ae50d514febd44f7d9be3c838b4d92f99412832/sendwithus/__init__.py#L776-L806 | def execute(self, timeout=None):
"""Execute all currently queued batch commands"""
logger.debug(' > Batch API request (length %s)' % len(self._commands))
auth = self._build_http_auth()
headers = self._build_request_headers()
logger.debug('\tbatch headers: %s' % headers)
... | [
"def",
"execute",
"(",
"self",
",",
"timeout",
"=",
"None",
")",
":",
"logger",
".",
"debug",
"(",
"' > Batch API request (length %s)'",
"%",
"len",
"(",
"self",
".",
"_commands",
")",
")",
"auth",
"=",
"self",
".",
"_build_http_auth",
"(",
")",
"headers",... | Execute all currently queued batch commands | [
"Execute",
"all",
"currently",
"queued",
"batch",
"commands"
] | python | valid | 30.16129 |
thespacedoctor/polyglot | polyglot/ebook.py | https://github.com/thespacedoctor/polyglot/blob/98038d746aa67e343b73b3ccee1e02d31dab81ec/polyglot/ebook.py#L144-L186 | def get(self):
"""
*get the ebook object*
**Return:**
- ``ebook``
**Usage:**
See class docstring for usage
"""
self.log.debug('starting the ``get`` method')
if self.format == "epub":
if self.urlOrPath[:4] == "http" or self.u... | [
"def",
"get",
"(",
"self",
")",
":",
"self",
".",
"log",
".",
"debug",
"(",
"'starting the ``get`` method'",
")",
"if",
"self",
".",
"format",
"==",
"\"epub\"",
":",
"if",
"self",
".",
"urlOrPath",
"[",
":",
"4",
"]",
"==",
"\"http\"",
"or",
"self",
... | *get the ebook object*
**Return:**
- ``ebook``
**Usage:**
See class docstring for usage | [
"*",
"get",
"the",
"ebook",
"object",
"*"
] | python | train | 25.255814 |
josiah-wolf-oberholtzer/uqbar | uqbar/sphinx/style.py | https://github.com/josiah-wolf-oberholtzer/uqbar/blob/eca7fefebbbee1e2ae13bf5d6baa838be66b1db6/uqbar/sphinx/style.py#L22-L38 | def handle_class(signature_node, module, object_name, cache):
"""
Styles ``autoclass`` entries.
Adds ``abstract`` prefix to abstract classes.
"""
class_ = getattr(module, object_name, None)
if class_ is None:
return
if class_ not in cache:
cache[class_] = {}
attribut... | [
"def",
"handle_class",
"(",
"signature_node",
",",
"module",
",",
"object_name",
",",
"cache",
")",
":",
"class_",
"=",
"getattr",
"(",
"module",
",",
"object_name",
",",
"None",
")",
"if",
"class_",
"is",
"None",
":",
"return",
"if",
"class_",
"not",
"i... | Styles ``autoclass`` entries.
Adds ``abstract`` prefix to abstract classes. | [
"Styles",
"autoclass",
"entries",
"."
] | python | train | 35.058824 |
ethereum/py-evm | eth/vm/logic/arithmetic.py | https://github.com/ethereum/py-evm/blob/58346848f076116381d3274bbcea96b9e2cfcbdf/eth/vm/logic/arithmetic.py#L96-L106 | def mulmod(computation: BaseComputation) -> None:
"""
Modulo Multiplication
"""
left, right, mod = computation.stack_pop(num_items=3, type_hint=constants.UINT256)
if mod == 0:
result = 0
else:
result = (left * right) % mod
computation.stack_push(result) | [
"def",
"mulmod",
"(",
"computation",
":",
"BaseComputation",
")",
"->",
"None",
":",
"left",
",",
"right",
",",
"mod",
"=",
"computation",
".",
"stack_pop",
"(",
"num_items",
"=",
"3",
",",
"type_hint",
"=",
"constants",
".",
"UINT256",
")",
"if",
"mod",... | Modulo Multiplication | [
"Modulo",
"Multiplication"
] | python | train | 26.181818 |
ralphje/imagemounter | imagemounter/parser.py | https://github.com/ralphje/imagemounter/blob/86213781c366cad65096447d91f522f0a3fb4b93/imagemounter/parser.py#L130-L139 | def init_volumes(self, single=None, only_mount=None, skip_mount=None, swallow_exceptions=True):
"""Detects volumes (as volume system or as single volume) in all disks and yields the volumes. This calls
:func:`Disk.init_volumes` on all disks and should be called after :func:`mount_disks`.
:rtype... | [
"def",
"init_volumes",
"(",
"self",
",",
"single",
"=",
"None",
",",
"only_mount",
"=",
"None",
",",
"skip_mount",
"=",
"None",
",",
"swallow_exceptions",
"=",
"True",
")",
":",
"for",
"disk",
"in",
"self",
".",
"disks",
":",
"logger",
".",
"info",
"("... | Detects volumes (as volume system or as single volume) in all disks and yields the volumes. This calls
:func:`Disk.init_volumes` on all disks and should be called after :func:`mount_disks`.
:rtype: generator | [
"Detects",
"volumes",
"(",
"as",
"volume",
"system",
"or",
"as",
"single",
"volume",
")",
"in",
"all",
"disks",
"and",
"yields",
"the",
"volumes",
".",
"This",
"calls",
":",
"func",
":",
"Disk",
".",
"init_volumes",
"on",
"all",
"disks",
"and",
"should",... | python | train | 56.7 |
hobson/aima | aima/utils.py | https://github.com/hobson/aima/blob/3572b2fb92039b4a1abe384be8545560fbd3d470/aima/utils.py#L521-L535 | def num_or_str(x):
"""The argument is a string; convert to a number if possible, or strip it.
>>> num_or_str('42')
42
>>> num_or_str(' 42x ')
'42x'
"""
if isnumber(x): return x
try:
return int(x)
except ValueError:
try:
return float(x)
except Value... | [
"def",
"num_or_str",
"(",
"x",
")",
":",
"if",
"isnumber",
"(",
"x",
")",
":",
"return",
"x",
"try",
":",
"return",
"int",
"(",
"x",
")",
"except",
"ValueError",
":",
"try",
":",
"return",
"float",
"(",
"x",
")",
"except",
"ValueError",
":",
"retur... | The argument is a string; convert to a number if possible, or strip it.
>>> num_or_str('42')
42
>>> num_or_str(' 42x ')
'42x' | [
"The",
"argument",
"is",
"a",
"string",
";",
"convert",
"to",
"a",
"number",
"if",
"possible",
"or",
"strip",
"it",
".",
">>>",
"num_or_str",
"(",
"42",
")",
"42",
">>>",
"num_or_str",
"(",
"42x",
")",
"42x"
] | python | valid | 23.066667 |
soravux/scoop | scoop/broker/brokerzmq.py | https://github.com/soravux/scoop/blob/d391dfa62f47e49d48328ee9cf08aa114256fd33/scoop/broker/brokerzmq.py#L184-L322 | def run(self):
"""Redirects messages until a shutdown message is received."""
while True:
if not self.task_socket.poll(-1):
continue
msg = self.task_socket.recv_multipart()
msg_type = msg[1]
if self.debug:
self.stats.appen... | [
"def",
"run",
"(",
"self",
")",
":",
"while",
"True",
":",
"if",
"not",
"self",
".",
"task_socket",
".",
"poll",
"(",
"-",
"1",
")",
":",
"continue",
"msg",
"=",
"self",
".",
"task_socket",
".",
"recv_multipart",
"(",
")",
"msg_type",
"=",
"msg",
"... | Redirects messages until a shutdown message is received. | [
"Redirects",
"messages",
"until",
"a",
"shutdown",
"message",
"is",
"received",
"."
] | python | train | 38.374101 |
maas/python-libmaas | maas/client/viscera/maas.py | https://github.com/maas/python-libmaas/blob/4092c68ef7fb1753efc843569848e2bcc3415002/maas/client/viscera/maas.py#L310-L316 | async def set_config(cls, name: str, value):
"""Set a configuration value in MAAS.
Consult your MAAS server for recognised settings. Alternatively, use
the pre-canned functions also defined on this object.
"""
return await cls._handler.set_config(name=[name], value=[value]) | [
"async",
"def",
"set_config",
"(",
"cls",
",",
"name",
":",
"str",
",",
"value",
")",
":",
"return",
"await",
"cls",
".",
"_handler",
".",
"set_config",
"(",
"name",
"=",
"[",
"name",
"]",
",",
"value",
"=",
"[",
"value",
"]",
")"
] | Set a configuration value in MAAS.
Consult your MAAS server for recognised settings. Alternatively, use
the pre-canned functions also defined on this object. | [
"Set",
"a",
"configuration",
"value",
"in",
"MAAS",
"."
] | python | train | 44.142857 |
angr/angr | angr/project.py | https://github.com/angr/angr/blob/4e2f97d56af5419ee73bdb30482c8dd8ff5f3e40/angr/project.py#L701-L707 | def is_java_project(self):
"""
Indicates if the project's main binary is a Java Archive.
"""
if self._is_java_project is None:
self._is_java_project = isinstance(self.arch, ArchSoot)
return self._is_java_project | [
"def",
"is_java_project",
"(",
"self",
")",
":",
"if",
"self",
".",
"_is_java_project",
"is",
"None",
":",
"self",
".",
"_is_java_project",
"=",
"isinstance",
"(",
"self",
".",
"arch",
",",
"ArchSoot",
")",
"return",
"self",
".",
"_is_java_project"
] | Indicates if the project's main binary is a Java Archive. | [
"Indicates",
"if",
"the",
"project",
"s",
"main",
"binary",
"is",
"a",
"Java",
"Archive",
"."
] | python | train | 36.714286 |
sryza/spark-timeseries | python/sparkts/timeseriesrdd.py | https://github.com/sryza/spark-timeseries/blob/280aa887dc08ab114411245268f230fdabb76eec/python/sparkts/timeseriesrdd.py#L106-L115 | def to_instants_dataframe(self, sql_ctx):
"""
Returns a DataFrame of instants, each a horizontal slice of this TimeSeriesRDD at a time.
This essentially transposes the TimeSeriesRDD, producing a DataFrame where each column
is a key form one of the rows in the TimeSeriesRDD.
"""
... | [
"def",
"to_instants_dataframe",
"(",
"self",
",",
"sql_ctx",
")",
":",
"ssql_ctx",
"=",
"sql_ctx",
".",
"_ssql_ctx",
"jdf",
"=",
"self",
".",
"_jtsrdd",
".",
"toInstantsDataFrame",
"(",
"ssql_ctx",
",",
"-",
"1",
")",
"return",
"DataFrame",
"(",
"jdf",
","... | Returns a DataFrame of instants, each a horizontal slice of this TimeSeriesRDD at a time.
This essentially transposes the TimeSeriesRDD, producing a DataFrame where each column
is a key form one of the rows in the TimeSeriesRDD. | [
"Returns",
"a",
"DataFrame",
"of",
"instants",
"each",
"a",
"horizontal",
"slice",
"of",
"this",
"TimeSeriesRDD",
"at",
"a",
"time",
"."
] | python | train | 44.7 |
jic-dtool/dtool-info | dtool_info/dataset.py | https://github.com/jic-dtool/dtool-info/blob/3c6c7755f4c142e548bbfdf3b38230612fd4060a/dtool_info/dataset.py#L193-L231 | def summary(dataset_uri, format):
"""Report summary information about a dataset."""
dataset = dtoolcore.DataSet.from_uri(dataset_uri)
creator_username = dataset._admin_metadata["creator_username"]
frozen_at = dataset._admin_metadata["frozen_at"]
num_items = len(dataset.identifiers)
tot_size = su... | [
"def",
"summary",
"(",
"dataset_uri",
",",
"format",
")",
":",
"dataset",
"=",
"dtoolcore",
".",
"DataSet",
".",
"from_uri",
"(",
"dataset_uri",
")",
"creator_username",
"=",
"dataset",
".",
"_admin_metadata",
"[",
"\"creator_username\"",
"]",
"frozen_at",
"=",
... | Report summary information about a dataset. | [
"Report",
"summary",
"information",
"about",
"a",
"dataset",
"."
] | python | train | 38.615385 |
MolSSI-BSE/basis_set_exchange | basis_set_exchange/validator.py | https://github.com/MolSSI-BSE/basis_set_exchange/blob/e79110aaeb65f392ed5032420322dee3336948f7/basis_set_exchange/validator.py#L106-L128 | def validate_file(file_type, file_path):
"""
Validates a file against a schema
Parameters
----------
file_type : str
Type of file to read. May be 'component', 'element', 'table', or 'references'
file_path:
Full path to the file to be validated
Raises
------
RuntimeE... | [
"def",
"validate_file",
"(",
"file_type",
",",
"file_path",
")",
":",
"file_data",
"=",
"fileio",
".",
"_read_plain_json",
"(",
"file_path",
",",
"False",
")",
"validate_data",
"(",
"file_type",
",",
"file_data",
")"
] | Validates a file against a schema
Parameters
----------
file_type : str
Type of file to read. May be 'component', 'element', 'table', or 'references'
file_path:
Full path to the file to be validated
Raises
------
RuntimeError
If the file_type is not valid (and/or a ... | [
"Validates",
"a",
"file",
"against",
"a",
"schema"
] | python | train | 27.173913 |
wmayner/pyphi | pyphi/distance.py | https://github.com/wmayner/pyphi/blob/deeca69a084d782a6fde7bf26f59e93b593c5d77/pyphi/distance.py#L181-L192 | def kld(d1, d2):
"""Return the Kullback-Leibler Divergence (KLD) between two distributions.
Args:
d1 (np.ndarray): The first distribution.
d2 (np.ndarray): The second distribution.
Returns:
float: The KLD of ``d1`` from ``d2``.
"""
d1, d2 = flatten(d1), flatten(d2)
retu... | [
"def",
"kld",
"(",
"d1",
",",
"d2",
")",
":",
"d1",
",",
"d2",
"=",
"flatten",
"(",
"d1",
")",
",",
"flatten",
"(",
"d2",
")",
"return",
"entropy",
"(",
"d1",
",",
"d2",
",",
"2.0",
")"
] | Return the Kullback-Leibler Divergence (KLD) between two distributions.
Args:
d1 (np.ndarray): The first distribution.
d2 (np.ndarray): The second distribution.
Returns:
float: The KLD of ``d1`` from ``d2``. | [
"Return",
"the",
"Kullback",
"-",
"Leibler",
"Divergence",
"(",
"KLD",
")",
"between",
"two",
"distributions",
"."
] | python | train | 27.666667 |
UCBerkeleySETI/blimpy | blimpy/guppi.py | https://github.com/UCBerkeleySETI/blimpy/blob/b8822d3e3e911944370d84371a91fa0c29e9772e/blimpy/guppi.py#L442-L459 | def cmd_tool(args=None):
""" Command line tool for plotting and viewing info on guppi raw files """
from argparse import ArgumentParser
parser = ArgumentParser(description="Command line utility for creating spectra from GuppiRaw files.")
parser.add_argument('filename', type=str, help='Name of file to... | [
"def",
"cmd_tool",
"(",
"args",
"=",
"None",
")",
":",
"from",
"argparse",
"import",
"ArgumentParser",
"parser",
"=",
"ArgumentParser",
"(",
"description",
"=",
"\"Command line utility for creating spectra from GuppiRaw files.\"",
")",
"parser",
".",
"add_argument",
"("... | Command line tool for plotting and viewing info on guppi raw files | [
"Command",
"line",
"tool",
"for",
"plotting",
"and",
"viewing",
"info",
"on",
"guppi",
"raw",
"files"
] | python | test | 39.888889 |
novopl/peltak | src/peltak/logic/lint.py | https://github.com/novopl/peltak/blob/b627acc019e3665875fe76cdca0a14773b69beaa/src/peltak/logic/lint.py#L118-L152 | def run(self):
# type: () -> bool
""" Run all linters and report results.
Returns:
bool: **True** if all checks were successful, **False** otherwise.
"""
with util.timed_block() as t:
files = self._collect_files()
log.info("Collected <33>{} <32>f... | [
"def",
"run",
"(",
"self",
")",
":",
"# type: () -> bool",
"with",
"util",
".",
"timed_block",
"(",
")",
"as",
"t",
":",
"files",
"=",
"self",
".",
"_collect_files",
"(",
")",
"log",
".",
"info",
"(",
"\"Collected <33>{} <32>files in <33>{}s\"",
".",
"format... | Run all linters and report results.
Returns:
bool: **True** if all checks were successful, **False** otherwise. | [
"Run",
"all",
"linters",
"and",
"report",
"results",
"."
] | python | train | 28.971429 |
juju/charm-helpers | charmhelpers/contrib/openstack/utils.py | https://github.com/juju/charm-helpers/blob/aa785c40c3b7a8c69dbfbc7921d6b9f30142e171/charmhelpers/contrib/openstack/utils.py#L486-L502 | def get_os_version_package(pkg, fatal=True):
'''Derive OpenStack version number from an installed package.'''
codename = get_os_codename_package(pkg, fatal=fatal)
if not codename:
return None
if 'swift' in pkg:
vers_map = SWIFT_CODENAMES
for cname, version in six.iteritems(vers... | [
"def",
"get_os_version_package",
"(",
"pkg",
",",
"fatal",
"=",
"True",
")",
":",
"codename",
"=",
"get_os_codename_package",
"(",
"pkg",
",",
"fatal",
"=",
"fatal",
")",
"if",
"not",
"codename",
":",
"return",
"None",
"if",
"'swift'",
"in",
"pkg",
":",
... | Derive OpenStack version number from an installed package. | [
"Derive",
"OpenStack",
"version",
"number",
"from",
"an",
"installed",
"package",
"."
] | python | train | 32.235294 |
arindampradhan/cheesy | cheesy/ch.py | https://github.com/arindampradhan/cheesy/blob/a7dbc90bba551a562644b1563c595d4ac38f15ed/cheesy/ch.py#L97-L120 | def _release_info(jsn,VERSION):
"""Gives information about a particular package version."""
try:
release_point = jsn['releases'][VERSION][0]
except KeyError:
print "\033[91m\033[1mError: Release not found."
exit(1)
python_version = release_point['python_version']
filename = release_point['filename']
md5 = r... | [
"def",
"_release_info",
"(",
"jsn",
",",
"VERSION",
")",
":",
"try",
":",
"release_point",
"=",
"jsn",
"[",
"'releases'",
"]",
"[",
"VERSION",
"]",
"[",
"0",
"]",
"except",
"KeyError",
":",
"print",
"\"\\033[91m\\033[1mError: Release not found.\"",
"exit",
"("... | Gives information about a particular package version. | [
"Gives",
"information",
"about",
"a",
"particular",
"package",
"version",
"."
] | python | train | 43.958333 |
bcbio/bcbio-nextgen | bcbio/qc/qualimap.py | https://github.com/bcbio/bcbio-nextgen/blob/6a9348c0054ccd5baffd22f1bb7d0422f6978b20/bcbio/qc/qualimap.py#L131-L139 | def _parse_qualimap_globals_inregion(table):
"""Retrieve metrics from the global targeted region table.
"""
out = {}
for row in table.find_all("tr"):
col, val = [x.text for x in row.find_all("td")]
if col == "Mapped reads":
out.update(_parse_num_pct("%s (in regions)" % col, v... | [
"def",
"_parse_qualimap_globals_inregion",
"(",
"table",
")",
":",
"out",
"=",
"{",
"}",
"for",
"row",
"in",
"table",
".",
"find_all",
"(",
"\"tr\"",
")",
":",
"col",
",",
"val",
"=",
"[",
"x",
".",
"text",
"for",
"x",
"in",
"row",
".",
"find_all",
... | Retrieve metrics from the global targeted region table. | [
"Retrieve",
"metrics",
"from",
"the",
"global",
"targeted",
"region",
"table",
"."
] | python | train | 36.777778 |
aestrivex/bctpy | bct/algorithms/modularity.py | https://github.com/aestrivex/bctpy/blob/4cb0e759eb4a038750b07e23bd29958c400684b8/bct/algorithms/modularity.py#L1043-L1171 | def modularity_louvain_und(W, gamma=1, hierarchy=False, seed=None):
'''
The optimal community structure is a subdivision of the network into
nonoverlapping groups of nodes in a way that maximizes the number of
within-group edges, and minimizes the number of between-group edges.
The modularity is a s... | [
"def",
"modularity_louvain_und",
"(",
"W",
",",
"gamma",
"=",
"1",
",",
"hierarchy",
"=",
"False",
",",
"seed",
"=",
"None",
")",
":",
"rng",
"=",
"get_rng",
"(",
"seed",
")",
"n",
"=",
"len",
"(",
"W",
")",
"# number of nodes",
"s",
"=",
"np",
"."... | The optimal community structure is a subdivision of the network into
nonoverlapping groups of nodes in a way that maximizes the number of
within-group edges, and minimizes the number of between-group edges.
The modularity is a statistic that quantifies the degree to which the
network may be subdivided i... | [
"The",
"optimal",
"community",
"structure",
"is",
"a",
"subdivision",
"of",
"the",
"network",
"into",
"nonoverlapping",
"groups",
"of",
"nodes",
"in",
"a",
"way",
"that",
"maximizes",
"the",
"number",
"of",
"within",
"-",
"group",
"edges",
"and",
"minimizes",
... | python | train | 35.697674 |
stephrdev/django-tapeforms | tapeforms/fieldsets.py | https://github.com/stephrdev/django-tapeforms/blob/255602de43777141f18afaf30669d7bdd4f7c323/tapeforms/fieldsets.py#L76-L97 | def visible_fields(self):
"""
Returns the reduced set of visible fields to output from the form.
This method respects the provided ``fields`` configuration _and_ exlcudes
all fields from the ``exclude`` configuration.
If no ``fields`` where provided when configuring this fields... | [
"def",
"visible_fields",
"(",
"self",
")",
":",
"form_visible_fields",
"=",
"self",
".",
"form",
".",
"visible_fields",
"(",
")",
"if",
"self",
".",
"render_fields",
":",
"fields",
"=",
"self",
".",
"render_fields",
"else",
":",
"fields",
"=",
"[",
"field"... | Returns the reduced set of visible fields to output from the form.
This method respects the provided ``fields`` configuration _and_ exlcudes
all fields from the ``exclude`` configuration.
If no ``fields`` where provided when configuring this fieldset, all visible
fields minus the exclu... | [
"Returns",
"the",
"reduced",
"set",
"of",
"visible",
"fields",
"to",
"output",
"from",
"the",
"form",
"."
] | python | train | 38.181818 |
marshmallow-code/apispec | src/apispec/ext/marshmallow/openapi.py | https://github.com/marshmallow-code/apispec/blob/e92ceffd12b2e392b8d199ed314bd2a7e6512dff/src/apispec/ext/marshmallow/openapi.py#L138-L157 | def map_to_openapi_type(self, *args):
"""Decorator to set mapping for custom fields.
``*args`` can be:
- a pair of the form ``(type, format)``
- a core marshmallow field type (in which case we reuse that type's mapping)
"""
if len(args) == 1 and args[0] in self.field_ma... | [
"def",
"map_to_openapi_type",
"(",
"self",
",",
"*",
"args",
")",
":",
"if",
"len",
"(",
"args",
")",
"==",
"1",
"and",
"args",
"[",
"0",
"]",
"in",
"self",
".",
"field_mapping",
":",
"openapi_type_field",
"=",
"self",
".",
"field_mapping",
"[",
"args"... | Decorator to set mapping for custom fields.
``*args`` can be:
- a pair of the form ``(type, format)``
- a core marshmallow field type (in which case we reuse that type's mapping) | [
"Decorator",
"to",
"set",
"mapping",
"for",
"custom",
"fields",
"."
] | python | train | 34.1 |
AshleySetter/optoanalysis | optoanalysis/optoanalysis/thermo/thermo.py | https://github.com/AshleySetter/optoanalysis/blob/9d390acc834d70024d47b574aea14189a5a5714e/optoanalysis/optoanalysis/thermo/thermo.py#L71-L97 | def calc_hamiltonian(self, mass, omega_array):
"""
Calculates the standard (pot+kin) Hamiltonian of your system.
Parameters
----------
mass : float
The mass of the particle in kg
omega_array : array
array which represents omega at every po... | [
"def",
"calc_hamiltonian",
"(",
"self",
",",
"mass",
",",
"omega_array",
")",
":",
"Kappa_t",
"=",
"mass",
"*",
"omega_array",
"**",
"2",
"self",
".",
"E_pot",
"=",
"0.5",
"*",
"Kappa_t",
"*",
"self",
".",
"position_data",
"**",
"2",
"self",
".",
"E_ki... | Calculates the standard (pot+kin) Hamiltonian of your system.
Parameters
----------
mass : float
The mass of the particle in kg
omega_array : array
array which represents omega at every point in your time trace
and should therefore have the sa... | [
"Calculates",
"the",
"standard",
"(",
"pot",
"+",
"kin",
")",
"Hamiltonian",
"of",
"your",
"system",
".",
"Parameters",
"----------",
"mass",
":",
"float",
"The",
"mass",
"of",
"the",
"particle",
"in",
"kg",
"omega_array",
":",
"array",
"array",
"which",
"... | python | train | 37.074074 |
EventRegistry/event-registry-python | eventregistry/TopicPage.py | https://github.com/EventRegistry/event-registry-python/blob/534d20b616de02f5e1cd73665a02d189645dbeb6/eventregistry/TopicPage.py#L224-L231 | def addKeyword(self, keyword, weight):
"""
add a relevant keyword to the topic page
@param keyword: keyword or phrase to be added
@param weight: importance of the provided keyword (typically in range 1 - 50)
"""
assert isinstance(weight, (float, int)), "weight value has t... | [
"def",
"addKeyword",
"(",
"self",
",",
"keyword",
",",
"weight",
")",
":",
"assert",
"isinstance",
"(",
"weight",
",",
"(",
"float",
",",
"int",
")",
")",
",",
"\"weight value has to be a positive or negative integer\"",
"self",
".",
"topicPage",
"[",
"\"keyword... | add a relevant keyword to the topic page
@param keyword: keyword or phrase to be added
@param weight: importance of the provided keyword (typically in range 1 - 50) | [
"add",
"a",
"relevant",
"keyword",
"to",
"the",
"topic",
"page"
] | python | train | 53.5 |
bitlabstudio/django-frequently | frequently/views.py | https://github.com/bitlabstudio/django-frequently/blob/93c76af62325afd1f09487dd1bb527fdd238ec8e/frequently/views.py#L28-L69 | def get_ordered_entries(self, queryset=False):
"""
Custom ordering. First we get the average views and rating for
the categories's entries. Second we created a rank by multiplying
both. Last, we sort categories by this rank from top to bottom.
Example:
- Cat_1
... | [
"def",
"get_ordered_entries",
"(",
"self",
",",
"queryset",
"=",
"False",
")",
":",
"if",
"queryset",
":",
"self",
".",
"queryset",
"=",
"queryset",
"else",
":",
"self",
".",
"queryset",
"=",
"EntryCategory",
".",
"objects",
".",
"all",
"(",
")",
"if",
... | Custom ordering. First we get the average views and rating for
the categories's entries. Second we created a rank by multiplying
both. Last, we sort categories by this rank from top to bottom.
Example:
- Cat_1
- Entry_1 (500 Views, Rating 2)
- Entry_2 (200 Views,... | [
"Custom",
"ordering",
".",
"First",
"we",
"get",
"the",
"average",
"views",
"and",
"rating",
"for",
"the",
"categories",
"s",
"entries",
".",
"Second",
"we",
"created",
"a",
"rank",
"by",
"multiplying",
"both",
".",
"Last",
"we",
"sort",
"categories",
"by"... | python | train | 40.642857 |
rongcloud/server-sdk-python | rongcloud/message.py | https://github.com/rongcloud/server-sdk-python/blob/3daadd8b67c84cc5d2a9419e8d45fd69c9baf976/rongcloud/message.py#L319-L362 | def broadcast(self,
fromUserId,
objectName,
content,
pushContent=None,
pushData=None,
os=None):
"""
发送广播消息方法(发送消息给一个应用下的所有注册用户,如用户未在线会对满足条件(绑定手机终端)的用户发送 Push 信息,单条消息最大 128k,会话类型为 SYSTEM。每小时只能发送 1 ... | [
"def",
"broadcast",
"(",
"self",
",",
"fromUserId",
",",
"objectName",
",",
"content",
",",
"pushContent",
"=",
"None",
",",
"pushData",
"=",
"None",
",",
"os",
"=",
"None",
")",
":",
"desc",
"=",
"{",
"\"name\"",
":",
"\"CodeSuccessReslut\"",
",",
"\"de... | 发送广播消息方法(发送消息给一个应用下的所有注册用户,如用户未在线会对满足条件(绑定手机终端)的用户发送 Push 信息,单条消息最大 128k,会话类型为 SYSTEM。每小时只能发送 1 次,每天最多发送 3 次。) 方法
@param fromUserId:发送人用户 Id。(必传)
@param txtMessage:文本消息。
@param pushContent:定义显示的 Push 内容,如果 objectName 为融云内置消息类型时,则发送后用户一定会收到 Push 信息. 如果为自定义消息,则 pushContent 为自定义消息显示的 Push 内容,如果不... | [
"发送广播消息方法(发送消息给一个应用下的所有注册用户,如用户未在线会对满足条件(绑定手机终端)的用户发送",
"Push",
"信息,单条消息最大",
"128k,会话类型为",
"SYSTEM。每小时只能发送",
"1",
"次,每天最多发送",
"3",
"次。)",
"方法"
] | python | train | 37.431818 |
delfick/harpoon | harpoon/actions.py | https://github.com/delfick/harpoon/blob/a2d39311d6127b7da2e15f40468bf320d598e461/harpoon/actions.py#L226-L243 | def delete_untagged(collector, **kwargs):
"""Find the untagged images and remove them"""
configuration = collector.configuration
docker_api = configuration["harpoon"].docker_api
images = docker_api.images()
found = False
for image in images:
if image["RepoTags"] == ["<none>:<none>"]:
... | [
"def",
"delete_untagged",
"(",
"collector",
",",
"*",
"*",
"kwargs",
")",
":",
"configuration",
"=",
"collector",
".",
"configuration",
"docker_api",
"=",
"configuration",
"[",
"\"harpoon\"",
"]",
".",
"docker_api",
"images",
"=",
"docker_api",
".",
"images",
... | Find the untagged images and remove them | [
"Find",
"the",
"untagged",
"images",
"and",
"remove",
"them"
] | python | train | 39.444444 |
gem/oq-engine | openquake/hazardlib/gsim/dowrickrhoades_2005.py | https://github.com/gem/oq-engine/blob/8294553a0b8aba33fd96437a35065d03547d0040/openquake/hazardlib/gsim/dowrickrhoades_2005.py#L145-L190 | def _get_site_class(self, vs30, mmi_mean):
"""
Return site class flag for:
Class E - Very Soft Soil vs30 < 180
Class D - Deep or Soft Soil vs30 >= 180 and vs30 <= 360
Class C - Shallow Soil vs30 > 360 and vs30 <= 760
Class B - Rock vs3... | [
"def",
"_get_site_class",
"(",
"self",
",",
"vs30",
",",
"mmi_mean",
")",
":",
"if",
"vs30",
"[",
"0",
"]",
"<",
"180",
":",
"c1",
"=",
"1.0",
"c2",
"=",
"-",
"0.25",
"d",
"=",
"0.5",
"elif",
"vs30",
"[",
"0",
"]",
">=",
"180",
"and",
"vs30",
... | Return site class flag for:
Class E - Very Soft Soil vs30 < 180
Class D - Deep or Soft Soil vs30 >= 180 and vs30 <= 360
Class C - Shallow Soil vs30 > 360 and vs30 <= 760
Class B - Rock vs30 > 760 and vs30 <= 1500
Class A - Strong Rock ... | [
"Return",
"site",
"class",
"flag",
"for",
":",
"Class",
"E",
"-",
"Very",
"Soft",
"Soil",
"vs30",
"<",
"180",
"Class",
"D",
"-",
"Deep",
"or",
"Soft",
"Soil",
"vs30",
">",
"=",
"180",
"and",
"vs30",
"<",
"=",
"360",
"Class",
"C",
"-",
"Shallow",
... | python | train | 29.391304 |
fastai/fastai | docs_src/nbval/nbdime_reporter.py | https://github.com/fastai/fastai/blob/9fb84a5cdefe5a766cdb792b8f5d8971737b7e67/docs_src/nbval/nbdime_reporter.py#L76-L107 | def make_report(self, outcome):
"""Make report in form of two notebooks.
Use nbdime diff-web to present the difference between reference
cells and test cells.
"""
failures = self.getreports('failed')
if not failures:
return
for rep in failures:
... | [
"def",
"make_report",
"(",
"self",
",",
"outcome",
")",
":",
"failures",
"=",
"self",
".",
"getreports",
"(",
"'failed'",
")",
"if",
"not",
"failures",
":",
"return",
"for",
"rep",
"in",
"failures",
":",
"# Check if this is a notebook node",
"msg",
"=",
"sel... | Make report in form of two notebooks.
Use nbdime diff-web to present the difference between reference
cells and test cells. | [
"Make",
"report",
"in",
"form",
"of",
"two",
"notebooks",
"."
] | python | train | 38.0625 |
hydpy-dev/hydpy | hydpy/core/filetools.py | https://github.com/hydpy-dev/hydpy/blob/1bc6a82cf30786521d86b36e27900c6717d3348d/hydpy/core/filetools.py#L469-L482 | def currentpath(self) -> str:
"""Absolute path of the current working directory.
>>> from hydpy.core.filetools import FileManager
>>> filemanager = FileManager()
>>> filemanager.BASEDIR = 'basename'
>>> filemanager.projectdir = 'projectname'
>>> from hydpy import repr_, ... | [
"def",
"currentpath",
"(",
"self",
")",
"->",
"str",
":",
"return",
"os",
".",
"path",
".",
"join",
"(",
"self",
".",
"basepath",
",",
"self",
".",
"currentdir",
")"
] | Absolute path of the current working directory.
>>> from hydpy.core.filetools import FileManager
>>> filemanager = FileManager()
>>> filemanager.BASEDIR = 'basename'
>>> filemanager.projectdir = 'projectname'
>>> from hydpy import repr_, TestIO
>>> with TestIO():
... | [
"Absolute",
"path",
"of",
"the",
"current",
"working",
"directory",
"."
] | python | train | 42.714286 |
ladybug-tools/ladybug | ladybug/designday.py | https://github.com/ladybug-tools/ladybug/blob/c08b7308077a48d5612f644943f92d5b5dade583/ladybug/designday.py#L1289-L1294 | def from_analysis_period(cls, analysis_period, clearness=1,
daylight_savings_indicator='No'):
""""Initialize a OriginalClearSkyCondition from an analysis_period"""
_check_analysis_period(analysis_period)
return cls(analysis_period.st_month, analysis_period.st_day, cl... | [
"def",
"from_analysis_period",
"(",
"cls",
",",
"analysis_period",
",",
"clearness",
"=",
"1",
",",
"daylight_savings_indicator",
"=",
"'No'",
")",
":",
"_check_analysis_period",
"(",
"analysis_period",
")",
"return",
"cls",
"(",
"analysis_period",
".",
"st_month",
... | Initialize a OriginalClearSkyCondition from an analysis_period | [
"Initialize",
"a",
"OriginalClearSkyCondition",
"from",
"an",
"analysis_period"
] | python | train | 61.666667 |
zhanglab/psamm | psamm/datasource/native.py | https://github.com/zhanglab/psamm/blob/dc427848c4f9d109ca590f0afa024c63b685b3f4/psamm/datasource/native.py#L1212-L1224 | def parse_model_table_file(path, f):
"""Parse a file as a list of model reactions
Yields reactions IDs. Path can be given as a string or a context.
"""
for line in f:
line, _, comment = line.partition('#')
line = line.strip()
if line == '':
continue
yield l... | [
"def",
"parse_model_table_file",
"(",
"path",
",",
"f",
")",
":",
"for",
"line",
"in",
"f",
":",
"line",
",",
"_",
",",
"comment",
"=",
"line",
".",
"partition",
"(",
"'#'",
")",
"line",
"=",
"line",
".",
"strip",
"(",
")",
"if",
"line",
"==",
"'... | Parse a file as a list of model reactions
Yields reactions IDs. Path can be given as a string or a context. | [
"Parse",
"a",
"file",
"as",
"a",
"list",
"of",
"model",
"reactions"
] | python | train | 23.923077 |
PlaidWeb/Pushl | pushl/entries.py | https://github.com/PlaidWeb/Pushl/blob/5ea92275c37a6c1989e3d5f53e26c6e0ebfb9a8c/pushl/entries.py#L108-L142 | async def get_entry(config, url):
""" Given an entry URL, return the entry
Arguments:
config -- the configuration
url -- the URL of the entry
Returns: 3-tuple of (current, previous, updated) """
previous = config.cache.get(
'entry', url,
schema_version=SCHEMA_VERSION) if conf... | [
"async",
"def",
"get_entry",
"(",
"config",
",",
"url",
")",
":",
"previous",
"=",
"config",
".",
"cache",
".",
"get",
"(",
"'entry'",
",",
"url",
",",
"schema_version",
"=",
"SCHEMA_VERSION",
")",
"if",
"config",
".",
"cache",
"else",
"None",
"headers",... | Given an entry URL, return the entry
Arguments:
config -- the configuration
url -- the URL of the entry
Returns: 3-tuple of (current, previous, updated) | [
"Given",
"an",
"entry",
"URL",
"return",
"the",
"entry"
] | python | train | 28.628571 |
waqasbhatti/astrobase | astrobase/periodbase/spdm.py | https://github.com/waqasbhatti/astrobase/blob/2922a14619d183fb28005fa7d02027ac436f2265/astrobase/periodbase/spdm.py#L145-L182 | def _stellingwerf_pdm_worker(task):
'''
This is a parallel worker for the function below.
Parameters
----------
task : tuple
This is of the form below::
task[0] = times
task[1] = mags
task[2] = errs
task[3] = frequency
task[4] = ... | [
"def",
"_stellingwerf_pdm_worker",
"(",
"task",
")",
":",
"times",
",",
"mags",
",",
"errs",
",",
"frequency",
",",
"binsize",
",",
"minbin",
"=",
"task",
"try",
":",
"theta",
"=",
"stellingwerf_pdm_theta",
"(",
"times",
",",
"mags",
",",
"errs",
",",
"f... | This is a parallel worker for the function below.
Parameters
----------
task : tuple
This is of the form below::
task[0] = times
task[1] = mags
task[2] = errs
task[3] = frequency
task[4] = binsize
task[5] = minbin
Return... | [
"This",
"is",
"a",
"parallel",
"worker",
"for",
"the",
"function",
"below",
"."
] | python | valid | 19.657895 |
PMBio/limix-backup | limix/varDecomp/varianceDecomposition.py | https://github.com/PMBio/limix-backup/blob/1e201fdb5c694d0d5506f207f3de65d8ef66146c/limix/varDecomp/varianceDecomposition.py#L371-L383 | def _init_params_default(self):
"""
Internal method for default parameter initialization
"""
# if there are some nan -> mean impute
Yimp = self.Y.copy()
Inan = sp.isnan(Yimp)
Yimp[Inan] = Yimp[~Inan].mean()
if self.P==1: C = sp.array([[Yimp.var()]])
... | [
"def",
"_init_params_default",
"(",
"self",
")",
":",
"# if there are some nan -> mean impute",
"Yimp",
"=",
"self",
".",
"Y",
".",
"copy",
"(",
")",
"Inan",
"=",
"sp",
".",
"isnan",
"(",
"Yimp",
")",
"Yimp",
"[",
"Inan",
"]",
"=",
"Yimp",
"[",
"~",
"I... | Internal method for default parameter initialization | [
"Internal",
"method",
"for",
"default",
"parameter",
"initialization"
] | python | train | 36.846154 |
santosjorge/cufflinks | cufflinks/tools.py | https://github.com/santosjorge/cufflinks/blob/ca1cbf93998dc793d0b1f8ac30fe1f2bd105f63a/cufflinks/tools.py#L1252-L1361 | def get_shape(kind='line',x=None,y=None,x0=None,y0=None,x1=None,y1=None,span=0,color='red',dash='solid',width=1,
fillcolor=None,fill=False,opacity=1,xref='x',yref='y'):
"""
Returns a plotly shape
Parameters:
-----------
kind : string
Shape kind
line
rect
circle
x : float
x values for the ... | [
"def",
"get_shape",
"(",
"kind",
"=",
"'line'",
",",
"x",
"=",
"None",
",",
"y",
"=",
"None",
",",
"x0",
"=",
"None",
",",
"y0",
"=",
"None",
",",
"x1",
"=",
"None",
",",
"y1",
"=",
"None",
",",
"span",
"=",
"0",
",",
"color",
"=",
"'red'",
... | Returns a plotly shape
Parameters:
-----------
kind : string
Shape kind
line
rect
circle
x : float
x values for the shape.
This assumes x0=x1
x0 : float
x0 value for the shape
x1 : float
x1 value for the shape
y : float
y values for the shape.
This assumes y0=y1
y0 : floa... | [
"Returns",
"a",
"plotly",
"shape"
] | python | train | 16.872727 |
saltstack/salt | salt/states/boto_iam.py | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/states/boto_iam.py#L1668-L1713 | def saml_provider_absent(name, region=None, key=None, keyid=None, profile=None):
'''
.. versionadded:: 2016.11.0
Ensure the SAML provider with the specified name is absent.
name (string)
The name of the SAML provider.
saml_metadata_document (string)
The xml document of the SAML pr... | [
"def",
"saml_provider_absent",
"(",
"name",
",",
"region",
"=",
"None",
",",
"key",
"=",
"None",
",",
"keyid",
"=",
"None",
",",
"profile",
"=",
"None",
")",
":",
"ret",
"=",
"{",
"'name'",
":",
"name",
",",
"'result'",
":",
"True",
",",
"'comment'",... | .. versionadded:: 2016.11.0
Ensure the SAML provider with the specified name is absent.
name (string)
The name of the SAML provider.
saml_metadata_document (string)
The xml document of the SAML provider.
region (string)
Region to connect to.
key (string)
Secret k... | [
"..",
"versionadded",
"::",
"2016",
".",
"11",
".",
"0"
] | python | train | 35.695652 |
PGower/PyCanvas | pycanvas/apis/assignments.py | https://github.com/PGower/PyCanvas/blob/68520005382b440a1e462f9df369f54d364e21e8/pycanvas/apis/assignments.py#L637-L657 | def redirect_to_assignment_override_for_group(self, group_id, assignment_id):
"""
Redirect to the assignment override for a group.
Responds with a redirect to the override for the given group, if any
(404 otherwise).
"""
path = {}
data = {}
param... | [
"def",
"redirect_to_assignment_override_for_group",
"(",
"self",
",",
"group_id",
",",
"assignment_id",
")",
":",
"path",
"=",
"{",
"}",
"data",
"=",
"{",
"}",
"params",
"=",
"{",
"}",
"# REQUIRED - PATH - group_id\r",
"\"\"\"ID\"\"\"",
"path",
"[",
"\"group_id\""... | Redirect to the assignment override for a group.
Responds with a redirect to the override for the given group, if any
(404 otherwise). | [
"Redirect",
"to",
"the",
"assignment",
"override",
"for",
"a",
"group",
".",
"Responds",
"with",
"a",
"redirect",
"to",
"the",
"override",
"for",
"the",
"given",
"group",
"if",
"any",
"(",
"404",
"otherwise",
")",
"."
] | python | train | 41.238095 |
DLR-RM/RAFCON | source/rafcon/gui/controllers/utils/tree_view_controller.py | https://github.com/DLR-RM/RAFCON/blob/24942ef1a904531f49ab8830a1dbb604441be498/source/rafcon/gui/controllers/utils/tree_view_controller.py#L497-L575 | def mouse_click(self, widget, event=None):
"""Implements shift- and control-key handling features for mouse button press events explicit
The method is implements a fully defined mouse pattern to use shift- and control-key for multi-selection in a
TreeView and a ListStore as model. It avoid pr... | [
"def",
"mouse_click",
"(",
"self",
",",
"widget",
",",
"event",
"=",
"None",
")",
":",
"if",
"event",
".",
"type",
"==",
"Gdk",
".",
"EventType",
".",
"BUTTON_PRESS",
":",
"pthinfo",
"=",
"self",
".",
"tree_view",
".",
"get_path_at_pos",
"(",
"int",
"(... | Implements shift- and control-key handling features for mouse button press events explicit
The method is implements a fully defined mouse pattern to use shift- and control-key for multi-selection in a
TreeView and a ListStore as model. It avoid problems caused by special renderer types like the text ... | [
"Implements",
"shift",
"-",
"and",
"control",
"-",
"key",
"handling",
"features",
"for",
"mouse",
"button",
"press",
"events",
"explicit"
] | python | train | 54.35443 |
googleapis/google-cloud-python | firestore/google/cloud/firestore_v1beta1/document.py | https://github.com/googleapis/google-cloud-python/blob/85e80125a59cb10f8cb105f25ecc099e4b940b50/firestore/google/cloud/firestore_v1beta1/document.py#L171-L183 | def collection(self, collection_id):
"""Create a sub-collection underneath the current document.
Args:
collection_id (str): The sub-collection identifier (sometimes
referred to as the "kind").
Returns:
~.firestore_v1beta1.collection.CollectionReference: ... | [
"def",
"collection",
"(",
"self",
",",
"collection_id",
")",
":",
"child_path",
"=",
"self",
".",
"_path",
"+",
"(",
"collection_id",
",",
")",
"return",
"self",
".",
"_client",
".",
"collection",
"(",
"*",
"child_path",
")"
] | Create a sub-collection underneath the current document.
Args:
collection_id (str): The sub-collection identifier (sometimes
referred to as the "kind").
Returns:
~.firestore_v1beta1.collection.CollectionReference: The
child collection. | [
"Create",
"a",
"sub",
"-",
"collection",
"underneath",
"the",
"current",
"document",
"."
] | python | train | 35.076923 |
arcticfoxnv/slackminion | slackminion/plugins/core/core.py | https://github.com/arcticfoxnv/slackminion/blob/62ea77aba5ac5ba582793e578a379a76f7d26cdb/slackminion/plugins/core/core.py#L75-L79 | def shutdown(self, msg, args):
"""Causes the bot to gracefully shutdown."""
self.log.info("Received shutdown from %s", msg.user.username)
self._bot.runnable = False
return "Shutting down..." | [
"def",
"shutdown",
"(",
"self",
",",
"msg",
",",
"args",
")",
":",
"self",
".",
"log",
".",
"info",
"(",
"\"Received shutdown from %s\"",
",",
"msg",
".",
"user",
".",
"username",
")",
"self",
".",
"_bot",
".",
"runnable",
"=",
"False",
"return",
"\"Sh... | Causes the bot to gracefully shutdown. | [
"Causes",
"the",
"bot",
"to",
"gracefully",
"shutdown",
"."
] | python | valid | 43.6 |
mgedmin/findimports | findimports.py | https://github.com/mgedmin/findimports/blob/c20a50b497390fed15aa3835476f4fad57313e8a/findimports.py#L701-L705 | def printImportedNames(self):
"""Produce a report of imported names."""
for module in self.listModules():
print("%s:" % module.modname)
print(" %s" % "\n ".join(imp.name for imp in module.imported_names)) | [
"def",
"printImportedNames",
"(",
"self",
")",
":",
"for",
"module",
"in",
"self",
".",
"listModules",
"(",
")",
":",
"print",
"(",
"\"%s:\"",
"%",
"module",
".",
"modname",
")",
"print",
"(",
"\" %s\"",
"%",
"\"\\n \"",
".",
"join",
"(",
"imp",
".",... | Produce a report of imported names. | [
"Produce",
"a",
"report",
"of",
"imported",
"names",
"."
] | python | train | 48.4 |
fudge-py/fudge | fudge/__init__.py | https://github.com/fudge-py/fudge/blob/b283fbc1a41900f3f5845b10b8c2ef9136a67ebc/fudge/__init__.py#L1359-L1373 | def with_arg_count(self, count):
"""Set the last call to expect an exact argument count.
I.E.::
>>> auth = Fake('auth').provides('login').with_arg_count(2)
>>> auth.login('joe_user') # forgot password
Traceback (most recent call last):
...
As... | [
"def",
"with_arg_count",
"(",
"self",
",",
"count",
")",
":",
"exp",
"=",
"self",
".",
"_get_current_call",
"(",
")",
"exp",
".",
"expected_arg_count",
"=",
"count",
"return",
"self"
] | Set the last call to expect an exact argument count.
I.E.::
>>> auth = Fake('auth').provides('login').with_arg_count(2)
>>> auth.login('joe_user') # forgot password
Traceback (most recent call last):
...
AssertionError: fake:auth.login() was called w... | [
"Set",
"the",
"last",
"call",
"to",
"expect",
"an",
"exact",
"argument",
"count",
"."
] | python | train | 32.533333 |
pyviz/holoviews | holoviews/streams.py | https://github.com/pyviz/holoviews/blob/ae0dd2f3de448b0ca5e9065aabd6ef8d84c7e655/holoviews/streams.py#L128-L171 | def trigger(cls, streams):
"""
Given a list of streams, collect all the stream parameters into
a dictionary and pass it to the union set of subscribers.
Passing multiple streams at once to trigger can be useful when a
subscriber may be set multiple times across streams but only
... | [
"def",
"trigger",
"(",
"cls",
",",
"streams",
")",
":",
"# Union of stream contents",
"items",
"=",
"[",
"stream",
".",
"contents",
".",
"items",
"(",
")",
"for",
"stream",
"in",
"set",
"(",
"streams",
")",
"]",
"union",
"=",
"[",
"kv",
"for",
"kvs",
... | Given a list of streams, collect all the stream parameters into
a dictionary and pass it to the union set of subscribers.
Passing multiple streams at once to trigger can be useful when a
subscriber may be set multiple times across streams but only
needs to be called once. | [
"Given",
"a",
"list",
"of",
"streams",
"collect",
"all",
"the",
"stream",
"parameters",
"into",
"a",
"dictionary",
"and",
"pass",
"it",
"to",
"the",
"union",
"set",
"of",
"subscribers",
"."
] | python | train | 43.431818 |
EpistasisLab/scikit-mdr | mdr/utils/utils.py | https://github.com/EpistasisLab/scikit-mdr/blob/768565deb10467d04a960d27e000ab38b7aa8a62/mdr/utils/utils.py#L220-L243 | def mdr_conditional_entropy(X, Y, labels, base=2):
"""Calculates the MDR conditional entropy, H(XY|labels), in the given base
MDR conditional entropy is calculated by combining variables X and Y into a single MDR model then calculating
the entropy of the resulting model's predictions conditional on the pro... | [
"def",
"mdr_conditional_entropy",
"(",
"X",
",",
"Y",
",",
"labels",
",",
"base",
"=",
"2",
")",
":",
"return",
"conditional_entropy",
"(",
"_mdr_predict",
"(",
"X",
",",
"Y",
",",
"labels",
")",
",",
"labels",
",",
"base",
"=",
"base",
")"
] | Calculates the MDR conditional entropy, H(XY|labels), in the given base
MDR conditional entropy is calculated by combining variables X and Y into a single MDR model then calculating
the entropy of the resulting model's predictions conditional on the provided labels.
Parameters
----------
X: array-... | [
"Calculates",
"the",
"MDR",
"conditional",
"entropy",
"H",
"(",
"XY|labels",
")",
"in",
"the",
"given",
"base"
] | python | test | 41.583333 |
secdev/scapy | scapy/layers/inet6.py | https://github.com/secdev/scapy/blob/3ffe757c184017dd46464593a8f80f85abc1e79a/scapy/layers/inet6.py#L1081-L1168 | def fragment6(pkt, fragSize):
"""
Performs fragmentation of an IPv6 packet. Provided packet ('pkt') must
already contain an IPv6ExtHdrFragment() class. 'fragSize' argument is the
expected maximum size of fragments (MTU). The list of packets is returned.
If packet does not contain an IPv6ExtHdrFragm... | [
"def",
"fragment6",
"(",
"pkt",
",",
"fragSize",
")",
":",
"pkt",
"=",
"pkt",
".",
"copy",
"(",
")",
"if",
"IPv6ExtHdrFragment",
"not",
"in",
"pkt",
":",
"# TODO : automatically add a fragment before upper Layer",
"# at the moment, we do nothing and return initial ... | Performs fragmentation of an IPv6 packet. Provided packet ('pkt') must
already contain an IPv6ExtHdrFragment() class. 'fragSize' argument is the
expected maximum size of fragments (MTU). The list of packets is returned.
If packet does not contain an IPv6ExtHdrFragment class, it is returned in
result li... | [
"Performs",
"fragmentation",
"of",
"an",
"IPv6",
"packet",
".",
"Provided",
"packet",
"(",
"pkt",
")",
"must",
"already",
"contain",
"an",
"IPv6ExtHdrFragment",
"()",
"class",
".",
"fragSize",
"argument",
"is",
"the",
"expected",
"maximum",
"size",
"of",
"frag... | python | train | 37.215909 |
MattBroach/DjangoRestMultipleModels | drf_multiple_model/mixins.py | https://github.com/MattBroach/DjangoRestMultipleModels/blob/893969ed38d614a5e2f060e560824fa7c5c49cfd/drf_multiple_model/mixins.py#L81-L91 | def add_to_results(self, data, label, results):
"""
responsible for updating the running `results` variable with the
data from this queryset/serializer combo
"""
raise NotImplementedError(
'{} must specify how to add data to the running results tally '
'by... | [
"def",
"add_to_results",
"(",
"self",
",",
"data",
",",
"label",
",",
"results",
")",
":",
"raise",
"NotImplementedError",
"(",
"'{} must specify how to add data to the running results tally '",
"'by overriding the `add_to_results` method.'",
".",
"format",
"(",
"self",
"."... | responsible for updating the running `results` variable with the
data from this queryset/serializer combo | [
"responsible",
"for",
"updating",
"the",
"running",
"results",
"variable",
"with",
"the",
"data",
"from",
"this",
"queryset",
"/",
"serializer",
"combo"
] | python | train | 38.454545 |
google/grr | grr/server/grr_response_server/flows/general/collectors.py | https://github.com/google/grr/blob/5cef4e8e2f0d5df43ea4877e9c798e0bf60bfe74/grr/server/grr_response_server/flows/general/collectors.py#L987-L997 | def MeetsConditions(knowledge_base, source):
"""Check conditions on the source."""
source_conditions_met = True
os_conditions = ConvertSupportedOSToConditions(source)
if os_conditions:
source.conditions.append(os_conditions)
for condition in source.conditions:
source_conditions_met &= artifact_utils.C... | [
"def",
"MeetsConditions",
"(",
"knowledge_base",
",",
"source",
")",
":",
"source_conditions_met",
"=",
"True",
"os_conditions",
"=",
"ConvertSupportedOSToConditions",
"(",
"source",
")",
"if",
"os_conditions",
":",
"source",
".",
"conditions",
".",
"append",
"(",
... | Check conditions on the source. | [
"Check",
"conditions",
"on",
"the",
"source",
"."
] | python | train | 35.545455 |
azraq27/neural | neural/stats.py | https://github.com/azraq27/neural/blob/fe91bfeecbf73ad99708cf5dca66cb61fcd529f5/neural/stats.py#L13-L60 | def voxel_count(dset,p=None,positive_only=False,mask=None,ROI=None):
''' returns the number of non-zero voxels
:p: threshold the dataset at the given *p*-value, then count
:positive_only: only count positive values
:mask: count within the given mask
:ROI: only use the... | [
"def",
"voxel_count",
"(",
"dset",
",",
"p",
"=",
"None",
",",
"positive_only",
"=",
"False",
",",
"mask",
"=",
"None",
",",
"ROI",
"=",
"None",
")",
":",
"if",
"p",
":",
"dset",
"=",
"nl",
".",
"thresh",
"(",
"dset",
",",
"p",
",",
"positive_onl... | returns the number of non-zero voxels
:p: threshold the dataset at the given *p*-value, then count
:positive_only: only count positive values
:mask: count within the given mask
:ROI: only use the ROI with the given value (or list of values) within the mask
... | [
"returns",
"the",
"number",
"of",
"non",
"-",
"zero",
"voxels"
] | python | train | 36.333333 |
Cymmetria/honeycomb | honeycomb/integrationmanager/tasks.py | https://github.com/Cymmetria/honeycomb/blob/33ea91b5cf675000e4e85dd02efe580ea6e95c86/honeycomb/integrationmanager/tasks.py#L170-L188 | def poll_integration_information_for_waiting_integration_alerts():
"""poll_integration_information_for_waiting_integration_alerts."""
if not polling_integration_alerts:
return
logger.debug("Polling information for waiting integration alerts")
for integration_alert in polling_integration_alerts... | [
"def",
"poll_integration_information_for_waiting_integration_alerts",
"(",
")",
":",
"if",
"not",
"polling_integration_alerts",
":",
"return",
"logger",
".",
"debug",
"(",
"\"Polling information for waiting integration alerts\"",
")",
"for",
"integration_alert",
"in",
"polling_... | poll_integration_information_for_waiting_integration_alerts. | [
"poll_integration_information_for_waiting_integration_alerts",
"."
] | python | train | 48.052632 |
minio/minio-py | minio/api.py | https://github.com/minio/minio-py/blob/7107c84183cf5fb4deff68c0a16ab9f1c0b4c37e/minio/api.py#L1768-L1789 | def _get_bucket_region(self, bucket_name):
"""
Get region based on the bucket name.
:param bucket_name: Bucket name for which region will be fetched.
:return: Region of bucket name.
"""
# Region set in constructor, return right here.
if self._region:
... | [
"def",
"_get_bucket_region",
"(",
"self",
",",
"bucket_name",
")",
":",
"# Region set in constructor, return right here.",
"if",
"self",
".",
"_region",
":",
"return",
"self",
".",
"_region",
"# get bucket location for Amazon S3.",
"region",
"=",
"'us-east-1'",
"# default... | Get region based on the bucket name.
:param bucket_name: Bucket name for which region will be fetched.
:return: Region of bucket name. | [
"Get",
"region",
"based",
"on",
"the",
"bucket",
"name",
"."
] | python | train | 31.045455 |
saltstack/salt | salt/modules/inspector.py | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/inspector.py#L230-L247 | def snapshots():
'''
List current description snapshots.
CLI Example:
.. code-block:: bash
salt myminion inspector.snapshots
'''
try:
return _("collector").Inspector(cachedir=__opts__['cachedir'],
piddir=os.path.dirname(__opts__['pidfile... | [
"def",
"snapshots",
"(",
")",
":",
"try",
":",
"return",
"_",
"(",
"\"collector\"",
")",
".",
"Inspector",
"(",
"cachedir",
"=",
"__opts__",
"[",
"'cachedir'",
"]",
",",
"piddir",
"=",
"os",
".",
"path",
".",
"dirname",
"(",
"__opts__",
"[",
"'pidfile'... | List current description snapshots.
CLI Example:
.. code-block:: bash
salt myminion inspector.snapshots | [
"List",
"current",
"description",
"snapshots",
"."
] | python | train | 28.055556 |
Cue/scales | src/greplin/scales/formats.py | https://github.com/Cue/scales/blob/0aced26eb050ceb98ee9d5d6cdca8db448666986/src/greplin/scales/formats.py#L91-L96 | def htmlFormat(output, pathParts = (), statDict = None, query = None):
"""Formats as HTML, writing to the given object."""
statDict = statDict or scales.getStats()
if query:
statDict = runQuery(statDict, query)
_htmlRenderDict(pathParts, statDict, output) | [
"def",
"htmlFormat",
"(",
"output",
",",
"pathParts",
"=",
"(",
")",
",",
"statDict",
"=",
"None",
",",
"query",
"=",
"None",
")",
":",
"statDict",
"=",
"statDict",
"or",
"scales",
".",
"getStats",
"(",
")",
"if",
"query",
":",
"statDict",
"=",
"runQ... | Formats as HTML, writing to the given object. | [
"Formats",
"as",
"HTML",
"writing",
"to",
"the",
"given",
"object",
"."
] | python | train | 43.666667 |
HumanCellAtlas/dcp-cli | hca/upload/upload_config.py | https://github.com/HumanCellAtlas/dcp-cli/blob/cc70817bc4e50944c709eaae160de0bf7a19f0f3/hca/upload/upload_config.py#L85-L95 | def area_uri(self, area_uuid):
"""
Return the URI for an Upload Area
:param area_uuid: UUID of area for which we want URI
:return: Upload Area URI object
:rtype: UploadAreaURI
:raises UploadException: if area does not exist
"""
if area_uuid not in self.are... | [
"def",
"area_uri",
"(",
"self",
",",
"area_uuid",
")",
":",
"if",
"area_uuid",
"not",
"in",
"self",
".",
"areas",
":",
"raise",
"UploadException",
"(",
"\"I don't know about area {uuid}\"",
".",
"format",
"(",
"uuid",
"=",
"area_uuid",
")",
")",
"return",
"U... | Return the URI for an Upload Area
:param area_uuid: UUID of area for which we want URI
:return: Upload Area URI object
:rtype: UploadAreaURI
:raises UploadException: if area does not exist | [
"Return",
"the",
"URI",
"for",
"an",
"Upload",
"Area",
":",
"param",
"area_uuid",
":",
"UUID",
"of",
"area",
"for",
"which",
"we",
"want",
"URI",
":",
"return",
":",
"Upload",
"Area",
"URI",
"object",
":",
"rtype",
":",
"UploadAreaURI",
":",
"raises",
... | python | train | 43.454545 |
ray-project/ray | python/ray/node.py | https://github.com/ray-project/ray/blob/4eade036a0505e244c976f36aaa2d64386b5129b/python/ray/node.py#L611-L619 | def kill_log_monitor(self, check_alive=True):
"""Kill the log monitor.
Args:
check_alive (bool): Raise an exception if the process was already
dead.
"""
self._kill_process_type(
ray_constants.PROCESS_TYPE_LOG_MONITOR, check_alive=check_alive) | [
"def",
"kill_log_monitor",
"(",
"self",
",",
"check_alive",
"=",
"True",
")",
":",
"self",
".",
"_kill_process_type",
"(",
"ray_constants",
".",
"PROCESS_TYPE_LOG_MONITOR",
",",
"check_alive",
"=",
"check_alive",
")"
] | Kill the log monitor.
Args:
check_alive (bool): Raise an exception if the process was already
dead. | [
"Kill",
"the",
"log",
"monitor",
"."
] | python | train | 34.111111 |
scheibler/khard | khard/khard.py | https://github.com/scheibler/khard/blob/0f69430c2680f1ff5f073a977a3c5b753b96cc17/khard/khard.py#L26-L38 | def write_temp_file(text=""):
"""Create a new temporary file and write some initial text to it.
:param text: the text to write to the temp file
:type text: str
:returns: the file name of the newly created temp file
:rtype: str
"""
with NamedTemporaryFile(mode='w+t', suffix='.yml', delete=F... | [
"def",
"write_temp_file",
"(",
"text",
"=",
"\"\"",
")",
":",
"with",
"NamedTemporaryFile",
"(",
"mode",
"=",
"'w+t'",
",",
"suffix",
"=",
"'.yml'",
",",
"delete",
"=",
"False",
")",
"as",
"tempfile",
":",
"tempfile",
".",
"write",
"(",
"text",
")",
"r... | Create a new temporary file and write some initial text to it.
:param text: the text to write to the temp file
:type text: str
:returns: the file name of the newly created temp file
:rtype: str | [
"Create",
"a",
"new",
"temporary",
"file",
"and",
"write",
"some",
"initial",
"text",
"to",
"it",
"."
] | python | test | 30.384615 |
gtaylor/python-route53 | route53/hosted_zone.py | https://github.com/gtaylor/python-route53/blob/b9fc7e258a79551c9ed61e4a71668b7f06f9e774/route53/hosted_zone.py#L220-L250 | def create_aaaa_record(self, name, values, ttl=60, weight=None, region=None,
set_identifier=None):
"""
Creates an AAAA record attached to this hosted zone.
:param str name: The fully qualified name of the record to add.
:param list values: A list of value strings... | [
"def",
"create_aaaa_record",
"(",
"self",
",",
"name",
",",
"values",
",",
"ttl",
"=",
"60",
",",
"weight",
"=",
"None",
",",
"region",
"=",
"None",
",",
"set_identifier",
"=",
"None",
")",
":",
"self",
".",
"_halt_if_already_deleted",
"(",
")",
"# Grab ... | Creates an AAAA record attached to this hosted zone.
:param str name: The fully qualified name of the record to add.
:param list values: A list of value strings for the record.
:keyword int ttl: The time-to-live of the record (in seconds).
:keyword int weight: *For weighted record sets ... | [
"Creates",
"an",
"AAAA",
"record",
"attached",
"to",
"this",
"hosted",
"zone",
"."
] | python | test | 49.741935 |
pybel/pybel | src/pybel/manager/cache_manager.py | https://github.com/pybel/pybel/blob/c8a7a1bdae4c475fa2a8c77f3a9a5f6d79556ca0/src/pybel/manager/cache_manager.py#L528-L539 | def get_graph_by_ids(self, network_ids: List[int]) -> BELGraph:
"""Get a combine BEL Graph from a list of network identifiers."""
if len(network_ids) == 1:
return self.get_graph_by_id(network_ids[0])
log.debug('getting graph by identifiers: %s', network_ids)
graphs = self.ge... | [
"def",
"get_graph_by_ids",
"(",
"self",
",",
"network_ids",
":",
"List",
"[",
"int",
"]",
")",
"->",
"BELGraph",
":",
"if",
"len",
"(",
"network_ids",
")",
"==",
"1",
":",
"return",
"self",
".",
"get_graph_by_id",
"(",
"network_ids",
"[",
"0",
"]",
")"... | Get a combine BEL Graph from a list of network identifiers. | [
"Get",
"a",
"combine",
"BEL",
"Graph",
"from",
"a",
"list",
"of",
"network",
"identifiers",
"."
] | python | train | 37.166667 |
lgiordani/dictregister | dictregister/dictregister.py | https://github.com/lgiordani/dictregister/blob/da3d8110d238c7b518811cb7bce65fad6f5cfc19/dictregister/dictregister.py#L50-L78 | def kremove(self, key, value=None):
"""Removes the given key/value from all elements.
If value is not specified, the whole key is removed.
If value is not None and the key is present but with a
different value, or if the key is not present, silently passes.
"""
for item i... | [
"def",
"kremove",
"(",
"self",
",",
"key",
",",
"value",
"=",
"None",
")",
":",
"for",
"item",
"in",
"self",
":",
"if",
"value",
"is",
"None",
":",
"# Just pop the key if present,",
"# otherwise return None",
"# (shortcut to ignore the exception)",
"item",
".",
... | Removes the given key/value from all elements.
If value is not specified, the whole key is removed.
If value is not None and the key is present but with a
different value, or if the key is not present, silently passes. | [
"Removes",
"the",
"given",
"key",
"/",
"value",
"from",
"all",
"elements",
".",
"If",
"value",
"is",
"not",
"specified",
"the",
"whole",
"key",
"is",
"removed",
".",
"If",
"value",
"is",
"not",
"None",
"and",
"the",
"key",
"is",
"present",
"but",
"with... | python | train | 42.37931 |
Jajcus/pyxmpp2 | pyxmpp2/sasl/core.py | https://github.com/Jajcus/pyxmpp2/blob/14a40a3950910a9cd008b55f0d8905aa0186ce18/pyxmpp2/sasl/core.py#L466-L494 | def sasl_mechanism(name, secure, preference = 50):
"""Class decorator generator for `ClientAuthenticator` or
`ServerAuthenticator` subclasses. Adds the class to the pyxmpp.sasl
mechanism registry.
:Parameters:
- `name`: SASL mechanism name
- `secure`: if the mechanims can be considered ... | [
"def",
"sasl_mechanism",
"(",
"name",
",",
"secure",
",",
"preference",
"=",
"50",
")",
":",
"# pylint: disable-msg=W0212",
"def",
"decorator",
"(",
"klass",
")",
":",
"\"\"\"The decorator.\"\"\"",
"klass",
".",
"_pyxmpp_sasl_secure",
"=",
"secure",
"klass",
".",
... | Class decorator generator for `ClientAuthenticator` or
`ServerAuthenticator` subclasses. Adds the class to the pyxmpp.sasl
mechanism registry.
:Parameters:
- `name`: SASL mechanism name
- `secure`: if the mechanims can be considered secure - `True`
if it can be used over plain-tex... | [
"Class",
"decorator",
"generator",
"for",
"ClientAuthenticator",
"or",
"ServerAuthenticator",
"subclasses",
".",
"Adds",
"the",
"class",
"to",
"the",
"pyxmpp",
".",
"sasl",
"mechanism",
"registry",
"."
] | python | valid | 38.793103 |
avinassh/haxor | hackernews/__init__.py | https://github.com/avinassh/haxor/blob/71dbecf87531f7a24bb39c736d53127427aaca84/hackernews/__init__.py#L327-L342 | def show_stories(self, raw=False, limit=None):
"""Returns list of item ids of latest Show HN stories
Args:
limit (int): specifies the number of stories to be returned.
raw (bool): Flag to indicate whether to transform all
objects into raw json.
Returns:
... | [
"def",
"show_stories",
"(",
"self",
",",
"raw",
"=",
"False",
",",
"limit",
"=",
"None",
")",
":",
"show_stories",
"=",
"self",
".",
"_get_stories",
"(",
"'showstories'",
",",
"limit",
")",
"if",
"raw",
":",
"show_stories",
"=",
"[",
"story",
".",
"raw... | Returns list of item ids of latest Show HN stories
Args:
limit (int): specifies the number of stories to be returned.
raw (bool): Flag to indicate whether to transform all
objects into raw json.
Returns:
`list` object containing ids of Show HN storie... | [
"Returns",
"list",
"of",
"item",
"ids",
"of",
"latest",
"Show",
"HN",
"stories"
] | python | train | 34.375 |
numenta/htmresearch | htmresearch/algorithms/faulty_temporal_memory.py | https://github.com/numenta/htmresearch/blob/70c096b09a577ea0432c3f3bfff4442d4871b7aa/htmresearch/algorithms/faulty_temporal_memory.py#L81-L122 | def burstColumn(self, column, columnMatchingSegments, prevActiveCells,
prevWinnerCells, learn):
"""
Activates all of the cells in an unpredicted active column, chooses a winner
cell, and, if learning is turned on, learns on one segment, growing a new
segment if necessary.
@param c... | [
"def",
"burstColumn",
"(",
"self",
",",
"column",
",",
"columnMatchingSegments",
",",
"prevActiveCells",
",",
"prevWinnerCells",
",",
"learn",
")",
":",
"start",
"=",
"self",
".",
"cellsPerColumn",
"*",
"column",
"# Strip out destroyed cells before passing along to base... | Activates all of the cells in an unpredicted active column, chooses a winner
cell, and, if learning is turned on, learns on one segment, growing a new
segment if necessary.
@param column (int)
Index of bursting column.
@param columnMatchingSegments (iter)
Matching segments in this column, or N... | [
"Activates",
"all",
"of",
"the",
"cells",
"in",
"an",
"unpredicted",
"active",
"column",
"chooses",
"a",
"winner",
"cell",
"and",
"if",
"learning",
"is",
"turned",
"on",
"learns",
"on",
"one",
"segment",
"growing",
"a",
"new",
"segment",
"if",
"necessary",
... | python | train | 35.47619 |
saltstack/salt | salt/cloud/clouds/ec2.py | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/cloud/clouds/ec2.py#L1350-L1362 | def get_provider(vm_=None):
'''
Extract the provider name from vm
'''
if vm_ is None:
provider = __active_provider_name__ or 'ec2'
else:
provider = vm_.get('provider', 'ec2')
if ':' in provider:
prov_comps = provider.split(':')
provider = prov_comps[0]
return... | [
"def",
"get_provider",
"(",
"vm_",
"=",
"None",
")",
":",
"if",
"vm_",
"is",
"None",
":",
"provider",
"=",
"__active_provider_name__",
"or",
"'ec2'",
"else",
":",
"provider",
"=",
"vm_",
".",
"get",
"(",
"'provider'",
",",
"'ec2'",
")",
"if",
"':'",
"i... | Extract the provider name from vm | [
"Extract",
"the",
"provider",
"name",
"from",
"vm"
] | python | train | 24.384615 |
bspaans/python-mingus | mingus/containers/composition.py | https://github.com/bspaans/python-mingus/blob/aa5a5d992d45ada61be0f9f86261380731bd7749/mingus/containers/composition.py#L67-L73 | def add_note(self, note):
"""Add a note to the selected tracks.
Everything container.Track supports in __add__ is accepted.
"""
for n in self.selected_tracks:
self.tracks[n] + note | [
"def",
"add_note",
"(",
"self",
",",
"note",
")",
":",
"for",
"n",
"in",
"self",
".",
"selected_tracks",
":",
"self",
".",
"tracks",
"[",
"n",
"]",
"+",
"note"
] | Add a note to the selected tracks.
Everything container.Track supports in __add__ is accepted. | [
"Add",
"a",
"note",
"to",
"the",
"selected",
"tracks",
"."
] | python | train | 31.285714 |
ktdreyer/txkoji | txkoji/connection.py | https://github.com/ktdreyer/txkoji/blob/a7de380f29f745bf11730b27217208f6d4da7733/txkoji/connection.py#L307-L324 | def getTaskInfo(self, task_id, **kwargs):
"""
Load all information about a task and return a custom Task class.
Calls "getTaskInfo" XML-RPC (with request=True to get the full
information.)
:param task_id: ``int``, for example 12345
:returns: deferred that when fired ret... | [
"def",
"getTaskInfo",
"(",
"self",
",",
"task_id",
",",
"*",
"*",
"kwargs",
")",
":",
"kwargs",
"[",
"'request'",
"]",
"=",
"True",
"taskinfo",
"=",
"yield",
"self",
".",
"call",
"(",
"'getTaskInfo'",
",",
"task_id",
",",
"*",
"*",
"kwargs",
")",
"ta... | Load all information about a task and return a custom Task class.
Calls "getTaskInfo" XML-RPC (with request=True to get the full
information.)
:param task_id: ``int``, for example 12345
:returns: deferred that when fired returns a Task (Munch, dict-like)
object repres... | [
"Load",
"all",
"information",
"about",
"a",
"task",
"and",
"return",
"a",
"custom",
"Task",
"class",
"."
] | python | train | 37.333333 |
Knio/dominate | dominate/dom_tag.py | https://github.com/Knio/dominate/blob/1eb88f9fd797658eef83568a548e2ef9b546807d/dominate/dom_tag.py#L434-L445 | def attr(*args, **kwargs):
'''
Set attributes on the current active tag context
'''
ctx = dom_tag._with_contexts[_get_thread_context()]
if ctx and ctx[-1]:
dicts = args + (kwargs,)
for d in dicts:
for attr, value in d.items():
ctx[-1].tag.set_attribute(*dom_tag.clean_pair(attr, value))
... | [
"def",
"attr",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"ctx",
"=",
"dom_tag",
".",
"_with_contexts",
"[",
"_get_thread_context",
"(",
")",
"]",
"if",
"ctx",
"and",
"ctx",
"[",
"-",
"1",
"]",
":",
"dicts",
"=",
"args",
"+",
"(",
"kwar... | Set attributes on the current active tag context | [
"Set",
"attributes",
"on",
"the",
"current",
"active",
"tag",
"context"
] | python | valid | 30 |
tanghaibao/goatools | goatools/rpt/rpt_lev_depth.py | https://github.com/tanghaibao/goatools/blob/407682e573a108864a79031f8ca19ee3bf377626/goatools/rpt/rpt_lev_depth.py#L98-L101 | def write_summary_cnts_goobjs(self, goobjs):
"""Write summary of level and depth counts for active GO Terms."""
cnts = self.get_cnts_levels_depths_recs(goobjs)
self._write_summary_cnts(cnts) | [
"def",
"write_summary_cnts_goobjs",
"(",
"self",
",",
"goobjs",
")",
":",
"cnts",
"=",
"self",
".",
"get_cnts_levels_depths_recs",
"(",
"goobjs",
")",
"self",
".",
"_write_summary_cnts",
"(",
"cnts",
")"
] | Write summary of level and depth counts for active GO Terms. | [
"Write",
"summary",
"of",
"level",
"and",
"depth",
"counts",
"for",
"active",
"GO",
"Terms",
"."
] | python | train | 52.75 |
datamachine/twx.botapi | twx/botapi/botapi.py | https://github.com/datamachine/twx.botapi/blob/c85184da738169e8f9d6d8e62970540f427c486e/twx/botapi/botapi.py#L3047-L3098 | def edit_message_live_location(latitude, longitude,
chat_id=None, message_id=None, inline_message_id=None, reply_markup=None,
**kwargs):
"""
Use this method to edit live location messages sent by the bot or via the bot (for inline bots).
A locati... | [
"def",
"edit_message_live_location",
"(",
"latitude",
",",
"longitude",
",",
"chat_id",
"=",
"None",
",",
"message_id",
"=",
"None",
",",
"inline_message_id",
"=",
"None",
",",
"reply_markup",
"=",
"None",
",",
"*",
"*",
"kwargs",
")",
":",
"if",
"not",
"c... | Use this method to edit live location messages sent by the bot or via the bot (for inline bots).
A location can be edited until its live_period expires or editing is explicitly disabled by a call
to stopMessageLiveLocation.
On success, if the edited message was sent by the bot, the edited Message is returne... | [
"Use",
"this",
"method",
"to",
"edit",
"live",
"location",
"messages",
"sent",
"by",
"the",
"bot",
"or",
"via",
"the",
"bot",
"(",
"for",
"inline",
"bots",
")",
".",
"A",
"location",
"can",
"be",
"edited",
"until",
"its",
"live_period",
"expires",
"or",
... | python | train | 46.115385 |
foremast/foremast | src/foremast/iam/destroy_iam/destroy_iam.py | https://github.com/foremast/foremast/blob/fb70f29b8ce532f061685a17d120486e47b215ba/src/foremast/iam/destroy_iam/destroy_iam.py#L28-L108 | def destroy_iam(app='', env='dev', **_):
"""Destroy IAM Resources.
Args:
app (str): Spinnaker Application name.
env (str): Deployment environment, i.e. dev, stage, prod.
Returns:
True upon successful completion.
"""
session = boto3.Session(profile_name=env)
client = ses... | [
"def",
"destroy_iam",
"(",
"app",
"=",
"''",
",",
"env",
"=",
"'dev'",
",",
"*",
"*",
"_",
")",
":",
"session",
"=",
"boto3",
".",
"Session",
"(",
"profile_name",
"=",
"env",
")",
"client",
"=",
"session",
".",
"client",
"(",
"'iam'",
")",
"generat... | Destroy IAM Resources.
Args:
app (str): Spinnaker Application name.
env (str): Deployment environment, i.e. dev, stage, prod.
Returns:
True upon successful completion. | [
"Destroy",
"IAM",
"Resources",
"."
] | python | train | 35.123457 |
rix0rrr/gcl | gcl/ast.py | https://github.com/rix0rrr/gcl/blob/4e3bccc978a9c60aaaffd20f6f291c4d23775cdf/gcl/ast.py#L75-L79 | def convertAndMake(converter, handler):
"""Convert with location."""
def convertAction(loc, value):
return handler(loc, converter(value))
return convertAction | [
"def",
"convertAndMake",
"(",
"converter",
",",
"handler",
")",
":",
"def",
"convertAction",
"(",
"loc",
",",
"value",
")",
":",
"return",
"handler",
"(",
"loc",
",",
"converter",
"(",
"value",
")",
")",
"return",
"convertAction"
] | Convert with location. | [
"Convert",
"with",
"location",
"."
] | python | train | 32.8 |
saltstack/salt | salt/modules/system.py | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/system.py#L221-L235 | def _offset_to_min(utc_offset):
'''
Helper function that converts the utc offset string into number of minutes
offset. Input is in form "[+-]?HHMM". Example valid inputs are "+0500"
"-0300" and "0800". These would return -300, 180, 480 respectively.
'''
match = re.match(r"^([+-])?(\d\d)(\d\d)$",... | [
"def",
"_offset_to_min",
"(",
"utc_offset",
")",
":",
"match",
"=",
"re",
".",
"match",
"(",
"r\"^([+-])?(\\d\\d)(\\d\\d)$\"",
",",
"utc_offset",
")",
"if",
"not",
"match",
":",
"raise",
"SaltInvocationError",
"(",
"\"Invalid UTC offset\"",
")",
"sign",
"=",
"-"... | Helper function that converts the utc offset string into number of minutes
offset. Input is in form "[+-]?HHMM". Example valid inputs are "+0500"
"-0300" and "0800". These would return -300, 180, 480 respectively. | [
"Helper",
"function",
"that",
"converts",
"the",
"utc",
"offset",
"string",
"into",
"number",
"of",
"minutes",
"offset",
".",
"Input",
"is",
"in",
"form",
"[",
"+",
"-",
"]",
"?HHMM",
".",
"Example",
"valid",
"inputs",
"are",
"+",
"0500",
"-",
"0300",
... | python | train | 40.4 |
adafruit/Adafruit_Blinka | src/adafruit_blinka/microcontroller/bcm283x/pulseio/PulseIn.py | https://github.com/adafruit/Adafruit_Blinka/blob/b4a2b3bf7d8cc88477027b827bd0a8e9b19588ff/src/adafruit_blinka/microcontroller/bcm283x/pulseio/PulseIn.py#L99-L105 | def resume(self, trigger_duration=0):
"""Resumes pulse capture after an optional trigger pulse."""
if trigger_duration != 0:
self._mq.send("t%d" % trigger_duration, True, type=1)
else:
self._mq.send("r", True, type=1)
self._paused = False | [
"def",
"resume",
"(",
"self",
",",
"trigger_duration",
"=",
"0",
")",
":",
"if",
"trigger_duration",
"!=",
"0",
":",
"self",
".",
"_mq",
".",
"send",
"(",
"\"t%d\"",
"%",
"trigger_duration",
",",
"True",
",",
"type",
"=",
"1",
")",
"else",
":",
"self... | Resumes pulse capture after an optional trigger pulse. | [
"Resumes",
"pulse",
"capture",
"after",
"an",
"optional",
"trigger",
"pulse",
"."
] | python | train | 41.142857 |
bokeh/bokeh | bokeh/models/sources.py | https://github.com/bokeh/bokeh/blob/dc8cf49e4e4302fd38537ad089ece81fbcca4737/bokeh/models/sources.py#L325-L343 | def add(self, data, name=None):
''' Appends a new column of data to the data source.
Args:
data (seq) : new data to add
name (str, optional) : column name to use.
If not supplied, generate a name of the form "Series ####"
Returns:
str: the c... | [
"def",
"add",
"(",
"self",
",",
"data",
",",
"name",
"=",
"None",
")",
":",
"if",
"name",
"is",
"None",
":",
"n",
"=",
"len",
"(",
"self",
".",
"data",
")",
"while",
"\"Series %d\"",
"%",
"n",
"in",
"self",
".",
"data",
":",
"n",
"+=",
"1",
"... | Appends a new column of data to the data source.
Args:
data (seq) : new data to add
name (str, optional) : column name to use.
If not supplied, generate a name of the form "Series ####"
Returns:
str: the column name used | [
"Appends",
"a",
"new",
"column",
"of",
"data",
"to",
"the",
"data",
"source",
"."
] | python | train | 28.368421 |
joeyespo/gitpress | gitpress/repository.py | https://github.com/joeyespo/gitpress/blob/a23edb80b6e4a113d167217475344a01c92b5c6d/gitpress/repository.py#L68-L99 | def iterate_presentation_files(path=None, excludes=None, includes=None):
"""Iterates the repository presentation files relative to 'path',
not including themes. Note that 'includes' take priority."""
# Defaults
if includes is None:
includes = []
if excludes is None:
excludes = []
... | [
"def",
"iterate_presentation_files",
"(",
"path",
"=",
"None",
",",
"excludes",
"=",
"None",
",",
"includes",
"=",
"None",
")",
":",
"# Defaults",
"if",
"includes",
"is",
"None",
":",
"includes",
"=",
"[",
"]",
"if",
"excludes",
"is",
"None",
":",
"exclu... | Iterates the repository presentation files relative to 'path',
not including themes. Note that 'includes' take priority. | [
"Iterates",
"the",
"repository",
"presentation",
"files",
"relative",
"to",
"path",
"not",
"including",
"themes",
".",
"Note",
"that",
"includes",
"take",
"priority",
"."
] | python | train | 40.53125 |
hobson/aima | aima/logic.py | https://github.com/hobson/aima/blob/3572b2fb92039b4a1abe384be8545560fbd3d470/aima/logic.py#L339-L347 | def prop_symbols(x):
"Return a list of all propositional symbols in x."
if not isinstance(x, Expr):
return []
elif is_prop_symbol(x.op):
return [x]
else:
return list(set(symbol for arg in x.args
for symbol in prop_symbols(arg))) | [
"def",
"prop_symbols",
"(",
"x",
")",
":",
"if",
"not",
"isinstance",
"(",
"x",
",",
"Expr",
")",
":",
"return",
"[",
"]",
"elif",
"is_prop_symbol",
"(",
"x",
".",
"op",
")",
":",
"return",
"[",
"x",
"]",
"else",
":",
"return",
"list",
"(",
"set"... | Return a list of all propositional symbols in x. | [
"Return",
"a",
"list",
"of",
"all",
"propositional",
"symbols",
"in",
"x",
"."
] | python | valid | 31.555556 |
chrismattmann/tika-python | tika/tika.py | https://github.com/chrismattmann/tika-python/blob/ffd3879ac3eaa9142c0fb6557cc1dc52d458a75a/tika/tika.py#L232-L251 | def getPaths(urlOrPaths):
'''
Determines if the given URL in urlOrPaths is a URL or a file or directory. If it's
a directory, it walks the directory and then finds all file paths in it, and ads them
too. If it's a file, it adds it to the paths. If it's a URL it just adds it to the path.
:param urlOr... | [
"def",
"getPaths",
"(",
"urlOrPaths",
")",
":",
"if",
"isinstance",
"(",
"urlOrPaths",
",",
"basestring",
")",
":",
"#FIXME: basestring is undefined",
"urlOrPaths",
"=",
"[",
"urlOrPaths",
"]",
"# do not recursively walk over letters of a single path which can include \"/\"",... | Determines if the given URL in urlOrPaths is a URL or a file or directory. If it's
a directory, it walks the directory and then finds all file paths in it, and ads them
too. If it's a file, it adds it to the paths. If it's a URL it just adds it to the path.
:param urlOrPaths: the url or path to be scanned
... | [
"Determines",
"if",
"the",
"given",
"URL",
"in",
"urlOrPaths",
"is",
"a",
"URL",
"or",
"a",
"file",
"or",
"directory",
".",
"If",
"it",
"s",
"a",
"directory",
"it",
"walks",
"the",
"directory",
"and",
"then",
"finds",
"all",
"file",
"paths",
"in",
"it"... | python | train | 45.7 |
lsbardel/python-stdnet | stdnet/backends/redisb/client/extensions.py | https://github.com/lsbardel/python-stdnet/blob/78db5320bdedc3f28c5e4f38cda13a4469e35db7/stdnet/backends/redisb/client/extensions.py#L46-L56 | def read_lua_file(dotted_module, path=None, context=None):
'''Load lua script from the stdnet/lib/lua directory'''
path = path or DEFAULT_LUA_PATH
bits = dotted_module.split('.')
bits[-1] += '.lua'
name = os.path.join(path, *bits)
with open(name) as f:
data = f.read()
if cont... | [
"def",
"read_lua_file",
"(",
"dotted_module",
",",
"path",
"=",
"None",
",",
"context",
"=",
"None",
")",
":",
"path",
"=",
"path",
"or",
"DEFAULT_LUA_PATH",
"bits",
"=",
"dotted_module",
".",
"split",
"(",
"'.'",
")",
"bits",
"[",
"-",
"1",
"]",
"+=",... | Load lua script from the stdnet/lib/lua directory | [
"Load",
"lua",
"script",
"from",
"the",
"stdnet",
"/",
"lib",
"/",
"lua",
"directory"
] | python | train | 33.454545 |
fprimex/zdesk | zdesk/zdesk_api.py | https://github.com/fprimex/zdesk/blob/851611c13b4d530e9df31390b3ec709baf0a0188/zdesk/zdesk_api.py#L4343-L4347 | def view_show(self, id, **kwargs):
"https://developer.zendesk.com/rest_api/docs/core/views#show-view"
api_path = "/api/v2/views/{id}.json"
api_path = api_path.format(id=id)
return self.call(api_path, **kwargs) | [
"def",
"view_show",
"(",
"self",
",",
"id",
",",
"*",
"*",
"kwargs",
")",
":",
"api_path",
"=",
"\"/api/v2/views/{id}.json\"",
"api_path",
"=",
"api_path",
".",
"format",
"(",
"id",
"=",
"id",
")",
"return",
"self",
".",
"call",
"(",
"api_path",
",",
"... | https://developer.zendesk.com/rest_api/docs/core/views#show-view | [
"https",
":",
"//",
"developer",
".",
"zendesk",
".",
"com",
"/",
"rest_api",
"/",
"docs",
"/",
"core",
"/",
"views#show",
"-",
"view"
] | python | train | 47.4 |
tanghaibao/goatools | goatools/gosubdag/plot/go_name_shorten.py | https://github.com/tanghaibao/goatools/blob/407682e573a108864a79031f8ca19ee3bf377626/goatools/gosubdag/plot/go_name_shorten.py#L131-L136 | def _keep_this(self, name):
"""Return True if there are to be no modifications to name."""
for keep_name in self.keep:
if name == keep_name:
return True
return False | [
"def",
"_keep_this",
"(",
"self",
",",
"name",
")",
":",
"for",
"keep_name",
"in",
"self",
".",
"keep",
":",
"if",
"name",
"==",
"keep_name",
":",
"return",
"True",
"return",
"False"
] | Return True if there are to be no modifications to name. | [
"Return",
"True",
"if",
"there",
"are",
"to",
"be",
"no",
"modifications",
"to",
"name",
"."
] | python | train | 35.333333 |
Hrabal/TemPy | tempy/widgets.py | https://github.com/Hrabal/TemPy/blob/7d229b73e2ce3ccbb8254deae05c1f758f626ed6/tempy/widgets.py#L209-L213 | def make_caption(self, caption):
"""Adds/Substitutes the table's caption."""
if not hasattr(self, "caption"):
self(caption=Caption())
return self.caption.empty()(caption) | [
"def",
"make_caption",
"(",
"self",
",",
"caption",
")",
":",
"if",
"not",
"hasattr",
"(",
"self",
",",
"\"caption\"",
")",
":",
"self",
"(",
"caption",
"=",
"Caption",
"(",
")",
")",
"return",
"self",
".",
"caption",
".",
"empty",
"(",
")",
"(",
"... | Adds/Substitutes the table's caption. | [
"Adds",
"/",
"Substitutes",
"the",
"table",
"s",
"caption",
"."
] | python | train | 40.4 |
datamachine/twx | twx/twx.py | https://github.com/datamachine/twx/blob/d9633f12f3647b1e54ba87b70b39df3b7e02b4eb/twx/twx.py#L392-L404 | def send_location(self, peer: Peer, latitude: float, longitude: float, reply: int=None, on_success: callable=None,
reply_markup: botapi.ReplyMarkup=None):
"""
Send location to peer.
:param peer: Peer to send message to.
:param latitude: Latitude of the location.
... | [
"def",
"send_location",
"(",
"self",
",",
"peer",
":",
"Peer",
",",
"latitude",
":",
"float",
",",
"longitude",
":",
"float",
",",
"reply",
":",
"int",
"=",
"None",
",",
"on_success",
":",
"callable",
"=",
"None",
",",
"reply_markup",
":",
"botapi",
".... | Send location to peer.
:param peer: Peer to send message to.
:param latitude: Latitude of the location.
:param longitude: Longitude of the location.
:param reply: Message object or message_id to reply to.
:param on_success: Callback to call when call is complete.
:type r... | [
"Send",
"location",
"to",
"peer",
".",
":",
"param",
"peer",
":",
"Peer",
"to",
"send",
"message",
"to",
".",
":",
"param",
"latitude",
":",
"Latitude",
"of",
"the",
"location",
".",
":",
"param",
"longitude",
":",
"Longitude",
"of",
"the",
"location",
... | python | train | 42.307692 |
AndrewAnnex/SpiceyPy | spiceypy/spiceypy.py | https://github.com/AndrewAnnex/SpiceyPy/blob/fc20a9b9de68b58eed5b332f0c051fb343a6e335/spiceypy/spiceypy.py#L13921-L13942 | def tisbod(ref, body, et):
"""
Return a 6x6 matrix that transforms states in inertial coordinates to
states in body-equator-and-prime-meridian coordinates.
http://naif.jpl.nasa.gov/pub/naif/toolkit_docs/C/cspice/tisbod_c.html
:param ref: ID of inertial reference frame to transform from.
:type ... | [
"def",
"tisbod",
"(",
"ref",
",",
"body",
",",
"et",
")",
":",
"ref",
"=",
"stypes",
".",
"stringToCharP",
"(",
"ref",
")",
"body",
"=",
"ctypes",
".",
"c_int",
"(",
"body",
")",
"et",
"=",
"ctypes",
".",
"c_double",
"(",
"et",
")",
"retmatrix",
... | Return a 6x6 matrix that transforms states in inertial coordinates to
states in body-equator-and-prime-meridian coordinates.
http://naif.jpl.nasa.gov/pub/naif/toolkit_docs/C/cspice/tisbod_c.html
:param ref: ID of inertial reference frame to transform from.
:type ref: str
:param body: ID code of bo... | [
"Return",
"a",
"6x6",
"matrix",
"that",
"transforms",
"states",
"in",
"inertial",
"coordinates",
"to",
"states",
"in",
"body",
"-",
"equator",
"-",
"and",
"-",
"prime",
"-",
"meridian",
"coordinates",
"."
] | python | train | 35.090909 |
rochacbruno/dynaconf | dynaconf/loaders/vault_loader.py | https://github.com/rochacbruno/dynaconf/blob/5a7cc8f8252251cbdf4f4112965801f9dfe2831d/dynaconf/loaders/vault_loader.py#L53-L97 | def load(obj, env=None, silent=None, key=None):
"""Reads and loads in to "settings" a single key or all keys from vault
:param obj: the settings instance
:param env: settings env default='DYNACONF'
:param silent: if errors should raise
:param key: if defined load a single key, else load all in env
... | [
"def",
"load",
"(",
"obj",
",",
"env",
"=",
"None",
",",
"silent",
"=",
"None",
",",
"key",
"=",
"None",
")",
":",
"client",
"=",
"get_client",
"(",
"obj",
")",
"env_list",
"=",
"_get_env_list",
"(",
"obj",
",",
"env",
")",
"for",
"env",
"in",
"e... | Reads and loads in to "settings" a single key or all keys from vault
:param obj: the settings instance
:param env: settings env default='DYNACONF'
:param silent: if errors should raise
:param key: if defined load a single key, else load all in env
:return: None | [
"Reads",
"and",
"loads",
"in",
"to",
"settings",
"a",
"single",
"key",
"or",
"all",
"keys",
"from",
"vault"
] | python | train | 35.755556 |
alefnula/tea | tea/shell/__init__.py | https://github.com/alefnula/tea/blob/f5a0a724a425ec4f9dd2c7fe966ef06faf3a15a3/tea/shell/__init__.py#L166-L187 | def __copyfile(source, destination):
"""Copy data and mode bits ("cp source destination").
The destination may be a directory.
Args:
source (str): Source file (file to copy).
destination (str): Destination file or directory (where to copy).
Returns:
bool: True if the operation... | [
"def",
"__copyfile",
"(",
"source",
",",
"destination",
")",
":",
"logger",
".",
"info",
"(",
"\"copyfile: %s -> %s\"",
"%",
"(",
"source",
",",
"destination",
")",
")",
"try",
":",
"__create_destdir",
"(",
"destination",
")",
"shutil",
".",
"copy",
"(",
"... | Copy data and mode bits ("cp source destination").
The destination may be a directory.
Args:
source (str): Source file (file to copy).
destination (str): Destination file or directory (where to copy).
Returns:
bool: True if the operation is successful, False otherwise. | [
"Copy",
"data",
"and",
"mode",
"bits",
"(",
"cp",
"source",
"destination",
")",
"."
] | python | train | 30.181818 |
sethmlarson/virtualbox-python | virtualbox/library.py | https://github.com/sethmlarson/virtualbox-python/blob/706c8e3f6e3aee17eb06458e73cbb4bc2d37878b/virtualbox/library.py#L21550-L21566 | def find_session(self, session_name):
"""Finds guest sessions by their friendly name and returns an interface
array with all found guest sessions.
in session_name of type str
The session's friendly name to find. Wildcards like ? and * are allowed.
return sessions of type :c... | [
"def",
"find_session",
"(",
"self",
",",
"session_name",
")",
":",
"if",
"not",
"isinstance",
"(",
"session_name",
",",
"basestring",
")",
":",
"raise",
"TypeError",
"(",
"\"session_name can only be an instance of type basestring\"",
")",
"sessions",
"=",
"self",
".... | Finds guest sessions by their friendly name and returns an interface
array with all found guest sessions.
in session_name of type str
The session's friendly name to find. Wildcards like ? and * are allowed.
return sessions of type :class:`IGuestSession`
Array with all g... | [
"Finds",
"guest",
"sessions",
"by",
"their",
"friendly",
"name",
"and",
"returns",
"an",
"interface",
"array",
"with",
"all",
"found",
"guest",
"sessions",
"."
] | python | train | 42.411765 |
facelessuser/backrefs | backrefs/_bregex_parse.py | https://github.com/facelessuser/backrefs/blob/3b3d60f5d57b02044f880aa29c9c5add0e31a34f/backrefs/_bregex_parse.py#L202-L231 | def get_posix(self, i):
"""Get POSIX."""
index = i.index
value = ['[']
try:
c = next(i)
if c != ':':
raise ValueError('Not a valid property!')
else:
value.append(c)
c = next(i)
if c == '^... | [
"def",
"get_posix",
"(",
"self",
",",
"i",
")",
":",
"index",
"=",
"i",
".",
"index",
"value",
"=",
"[",
"'['",
"]",
"try",
":",
"c",
"=",
"next",
"(",
"i",
")",
"if",
"c",
"!=",
"':'",
":",
"raise",
"ValueError",
"(",
"'Not a valid property!'",
... | Get POSIX. | [
"Get",
"POSIX",
"."
] | python | train | 31.5 |
apache/incubator-mxnet | example/cnn_text_classification/data_helpers.py | https://github.com/apache/incubator-mxnet/blob/1af29e9c060a4c7d60eeaacba32afdb9a7775ba7/example/cnn_text_classification/data_helpers.py#L79-L89 | def pad_sentences(sentences, padding_word="</s>"):
"""Pads all sentences to the same length. The length is defined by the longest sentence.
Returns padded sentences.
"""
sequence_length = max(len(x) for x in sentences)
padded_sentences = []
for i, sentence in enumerate(sentences):
num_pa... | [
"def",
"pad_sentences",
"(",
"sentences",
",",
"padding_word",
"=",
"\"</s>\"",
")",
":",
"sequence_length",
"=",
"max",
"(",
"len",
"(",
"x",
")",
"for",
"x",
"in",
"sentences",
")",
"padded_sentences",
"=",
"[",
"]",
"for",
"i",
",",
"sentence",
"in",
... | Pads all sentences to the same length. The length is defined by the longest sentence.
Returns padded sentences. | [
"Pads",
"all",
"sentences",
"to",
"the",
"same",
"length",
".",
"The",
"length",
"is",
"defined",
"by",
"the",
"longest",
"sentence",
".",
"Returns",
"padded",
"sentences",
"."
] | python | train | 44.181818 |
pyecore/pyecore | pyecore/ecore.py | https://github.com/pyecore/pyecore/blob/22b67ad8799594f8f44fd8bee497583d4f12ed63/pyecore/ecore.py#L873-L894 | def EMetaclass(cls):
"""Class decorator for creating PyEcore metaclass."""
superclass = cls.__bases__
if not issubclass(cls, EObject):
sclasslist = list(superclass)
if object in superclass:
index = sclasslist.index(object)
sclasslist.insert(index, EObject)
... | [
"def",
"EMetaclass",
"(",
"cls",
")",
":",
"superclass",
"=",
"cls",
".",
"__bases__",
"if",
"not",
"issubclass",
"(",
"cls",
",",
"EObject",
")",
":",
"sclasslist",
"=",
"list",
"(",
"superclass",
")",
"if",
"object",
"in",
"superclass",
":",
"index",
... | Class decorator for creating PyEcore metaclass. | [
"Class",
"decorator",
"for",
"creating",
"PyEcore",
"metaclass",
"."
] | python | train | 35.772727 |
riptano/ccm | ccmlib/dse_node.py | https://github.com/riptano/ccm/blob/275699f79d102b5039b79cc17fa6305dccf18412/ccmlib/dse_node.py#L320-L339 | def export_dse_home_in_dse_env_sh(self):
'''
Due to the way CCM lays out files, separating the repository
from the node(s) confs, the `dse-env.sh` script of each node
needs to have its DSE_HOME var set and exported. Since DSE
4.5.x, the stock `dse-env.sh` file includes a commente... | [
"def",
"export_dse_home_in_dse_env_sh",
"(",
"self",
")",
":",
"with",
"open",
"(",
"self",
".",
"get_bin_dir",
"(",
")",
"+",
"\"/dse-env.sh\"",
",",
"\"r\"",
")",
"as",
"dse_env_sh",
":",
"buf",
"=",
"dse_env_sh",
".",
"readlines",
"(",
")",
"with",
"ope... | Due to the way CCM lays out files, separating the repository
from the node(s) confs, the `dse-env.sh` script of each node
needs to have its DSE_HOME var set and exported. Since DSE
4.5.x, the stock `dse-env.sh` file includes a commented-out
place to do exactly this, intended for installe... | [
"Due",
"to",
"the",
"way",
"CCM",
"lays",
"out",
"files",
"separating",
"the",
"repository",
"from",
"the",
"node",
"(",
"s",
")",
"confs",
"the",
"dse",
"-",
"env",
".",
"sh",
"script",
"of",
"each",
"node",
"needs",
"to",
"have",
"its",
"DSE_HOME",
... | python | train | 51 |
payu-org/payu | payu/experiment.py | https://github.com/payu-org/payu/blob/1442a9a226012eff248b8097cc1eaabc3e224867/payu/experiment.py#L796-L806 | def postprocess(self):
"""Submit a postprocessing script after collation"""
assert self.postscript
envmod.setup()
envmod.module('load', 'pbs')
cmd = 'qsub {script}'.format(script=self.postscript)
cmd = shlex.split(cmd)
rc = sp.call(cmd)
assert rc == 0, '... | [
"def",
"postprocess",
"(",
"self",
")",
":",
"assert",
"self",
".",
"postscript",
"envmod",
".",
"setup",
"(",
")",
"envmod",
".",
"module",
"(",
"'load'",
",",
"'pbs'",
")",
"cmd",
"=",
"'qsub {script}'",
".",
"format",
"(",
"script",
"=",
"self",
"."... | Submit a postprocessing script after collation | [
"Submit",
"a",
"postprocessing",
"script",
"after",
"collation"
] | python | train | 31.909091 |
hardbyte/python-can | can/interfaces/systec/ucan.py | https://github.com/hardbyte/python-can/blob/cdc5254d96072df7739263623f3e920628a7d214/can/interfaces/systec/ucan.py#L893-L903 | def check_support_ucannet(cls, hw_info_ex):
"""
Checks whether the module supports the usage of USB-CANnetwork driver.
:param HardwareInfoEx hw_info_ex:
Extended hardware information structure (see method :meth:`get_hardware_info`).
:return: True when the module does support... | [
"def",
"check_support_ucannet",
"(",
"cls",
",",
"hw_info_ex",
")",
":",
"return",
"cls",
".",
"check_is_systec",
"(",
"hw_info_ex",
")",
"and",
"cls",
".",
"check_version_is_equal_or_higher",
"(",
"hw_info_ex",
".",
"m_dwFwVersionEx",
",",
"3",
",",
"8",
")"
] | Checks whether the module supports the usage of USB-CANnetwork driver.
:param HardwareInfoEx hw_info_ex:
Extended hardware information structure (see method :meth:`get_hardware_info`).
:return: True when the module does support the usage of the USB-CANnetwork driver, otherwise False.
... | [
"Checks",
"whether",
"the",
"module",
"supports",
"the",
"usage",
"of",
"USB",
"-",
"CANnetwork",
"driver",
"."
] | python | train | 49 |
MacHu-GWU/angora-project | angora/math/img2waveform.py | https://github.com/MacHu-GWU/angora-project/blob/689a60da51cd88680ddbe26e28dbe81e6b01d275/angora/math/img2waveform.py#L72-L261 | def img2ascii(img_path, ascii_path, ascii_char="*", pad=0):
"""Convert an image to ascii art text.
Suppose we have an image like that:
.. image:: images/rabbit.png
:align: left
Put some codes::
>>> from weatherlab.math.img2waveform import img2ascii
>>> img2ascii(r"testdata\im... | [
"def",
"img2ascii",
"(",
"img_path",
",",
"ascii_path",
",",
"ascii_char",
"=",
"\"*\"",
",",
"pad",
"=",
"0",
")",
":",
"if",
"len",
"(",
"ascii_char",
")",
"!=",
"1",
":",
"raise",
"Exception",
"(",
"\"ascii_char has to be single character.\"",
")",
"image... | Convert an image to ascii art text.
Suppose we have an image like that:
.. image:: images/rabbit.png
:align: left
Put some codes::
>>> from weatherlab.math.img2waveform import img2ascii
>>> img2ascii(r"testdata\img2waveform\rabbit.png",
... r"testdata\img2wavef... | [
"Convert",
"an",
"image",
"to",
"ascii",
"art",
"text",
"."
] | python | train | 72.510526 |
espressif/esptool | ecdsa/ecdsa.py | https://github.com/espressif/esptool/blob/c583756c118039cfcfe256f7a3285618914d16a5/ecdsa/ecdsa.py#L93-L111 | def verifies( self, hash, signature ):
"""Verify that signature is a valid signature of hash.
Return True if the signature is valid.
"""
# From X9.62 J.3.1.
G = self.generator
n = G.order()
r = signature.r
s = signature.s
if r < 1 or r > n-1: return False
if s < 1 or s > n-1: r... | [
"def",
"verifies",
"(",
"self",
",",
"hash",
",",
"signature",
")",
":",
"# From X9.62 J.3.1.",
"G",
"=",
"self",
".",
"generator",
"n",
"=",
"G",
".",
"order",
"(",
")",
"r",
"=",
"signature",
".",
"r",
"s",
"=",
"signature",
".",
"s",
"if",
"r",
... | Verify that signature is a valid signature of hash.
Return True if the signature is valid. | [
"Verify",
"that",
"signature",
"is",
"a",
"valid",
"signature",
"of",
"hash",
".",
"Return",
"True",
"if",
"the",
"signature",
"is",
"valid",
"."
] | python | train | 24.947368 |
wonambi-python/wonambi | wonambi/detect/spindle.py | https://github.com/wonambi-python/wonambi/blob/1d8e3d7e53df8017c199f703bcab582914676e76/wonambi/detect/spindle.py#L1998-L2026 | def _detect_start_end(true_values):
"""From ndarray of bool values, return intervals of True values.
Parameters
----------
true_values : ndarray (dtype='bool')
array with bool values
Returns
-------
ndarray (dtype='int')
N x 2 matrix with starting and ending times.
"""
... | [
"def",
"_detect_start_end",
"(",
"true_values",
")",
":",
"neg",
"=",
"zeros",
"(",
"(",
"1",
")",
",",
"dtype",
"=",
"'bool'",
")",
"int_values",
"=",
"asarray",
"(",
"concatenate",
"(",
"(",
"neg",
",",
"true_values",
"[",
":",
"-",
"1",
"]",
",",
... | From ndarray of bool values, return intervals of True values.
Parameters
----------
true_values : ndarray (dtype='bool')
array with bool values
Returns
-------
ndarray (dtype='int')
N x 2 matrix with starting and ending times. | [
"From",
"ndarray",
"of",
"bool",
"values",
"return",
"intervals",
"of",
"True",
"values",
"."
] | python | train | 26.310345 |
PyCQA/pyflakes | pyflakes/api.py | https://github.com/PyCQA/pyflakes/blob/232cb1d27ee134bf96adc8f37e53589dc259b159/pyflakes/api.py#L102-L122 | def isPythonFile(filename):
"""Return True if filename points to a Python file."""
if filename.endswith('.py'):
return True
# Avoid obvious Emacs backup files
if filename.endswith("~"):
return False
max_bytes = 128
try:
with open(filename, 'rb') as f:
text ... | [
"def",
"isPythonFile",
"(",
"filename",
")",
":",
"if",
"filename",
".",
"endswith",
"(",
"'.py'",
")",
":",
"return",
"True",
"# Avoid obvious Emacs backup files",
"if",
"filename",
".",
"endswith",
"(",
"\"~\"",
")",
":",
"return",
"False",
"max_bytes",
"=",... | Return True if filename points to a Python file. | [
"Return",
"True",
"if",
"filename",
"points",
"to",
"a",
"Python",
"file",
"."
] | python | train | 23.952381 |
JukeboxPipeline/jukebox-core | src/jukeboxcore/gui/reftrackitemdata.py | https://github.com/JukeboxPipeline/jukebox-core/blob/bac2280ca49940355270e4b69400ce9976ab2e6f/src/jukeboxcore/gui/reftrackitemdata.py#L149-L165 | def reftrack_status_data(rt, role):
"""Return the data for the status
:param rt: the :class:`jukeboxcore.reftrack.Reftrack` holds the data
:type rt: :class:`jukeboxcore.reftrack.Reftrack`
:param role: item data role
:type role: QtCore.Qt.ItemDataRole
:returns: data for the status
:rtype: de... | [
"def",
"reftrack_status_data",
"(",
"rt",
",",
"role",
")",
":",
"status",
"=",
"rt",
".",
"status",
"(",
")",
"if",
"role",
"==",
"QtCore",
".",
"Qt",
".",
"DisplayRole",
"or",
"role",
"==",
"QtCore",
".",
"Qt",
".",
"EditRole",
":",
"if",
"status",... | Return the data for the status
:param rt: the :class:`jukeboxcore.reftrack.Reftrack` holds the data
:type rt: :class:`jukeboxcore.reftrack.Reftrack`
:param role: item data role
:type role: QtCore.Qt.ItemDataRole
:returns: data for the status
:rtype: depending on role
:raises: None | [
"Return",
"the",
"data",
"for",
"the",
"status"
] | python | train | 31.294118 |
UCL-INGI/INGInious | inginious/frontend/session_mongodb.py | https://github.com/UCL-INGI/INGInious/blob/cbda9a9c7f2b8e8eb1e6d7d51f0d18092086300c/inginious/frontend/session_mongodb.py#L22-L71 | def needs_encode(obj):
'''
>>> from re import compile
>>> atomics = (True, 1, 1.0, '', None, compile(''), datetime.now(), b'')
>>> any(needs_encode(i) for i in atomics)
False
>>> needs_encode([1, 2, 3])
False
>>> needs_encode([])
False
>>> needs_encode([1, [2, 3]])
False
... | [
"def",
"needs_encode",
"(",
"obj",
")",
":",
"obtype",
"=",
"type",
"(",
"obj",
")",
"if",
"obtype",
"in",
"atomic_types",
":",
"return",
"False",
"if",
"obtype",
"is",
"list",
":",
"return",
"any",
"(",
"needs_encode",
"(",
"i",
")",
"for",
"i",
"in... | >>> from re import compile
>>> atomics = (True, 1, 1.0, '', None, compile(''), datetime.now(), b'')
>>> any(needs_encode(i) for i in atomics)
False
>>> needs_encode([1, 2, 3])
False
>>> needs_encode([])
False
>>> needs_encode([1, [2, 3]])
False
>>> needs_encode({})
False
... | [
">>>",
"from",
"re",
"import",
"compile",
">>>",
"atomics",
"=",
"(",
"True",
"1",
"1",
".",
"0",
"None",
"compile",
"(",
")",
"datetime",
".",
"now",
"()",
"b",
")",
">>>",
"any",
"(",
"needs_encode",
"(",
"i",
")",
"for",
"i",
"in",
"atomics",
... | python | train | 22.54 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.