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 |
|---|---|---|---|---|---|---|---|---|---|
jcushman/pdfquery | pdfquery/pdfquery.py | https://github.com/jcushman/pdfquery/blob/f1c05d15e0c1b7c523a0971bc89b5610d8560f79/pdfquery/pdfquery.py#L114-L146 | def smart_unicode_decode(encoded_string):
"""
Given an encoded string of unknown format, detect the format with
chardet and return the unicode version.
Example input from bug #11:
('\xfe\xff\x00I\x00n\x00s\x00p\x00e\x00c\x00t\x00i\x00o\x00n\x00'
'\x00R\x00e\x00p\x00o... | [
"def",
"smart_unicode_decode",
"(",
"encoded_string",
")",
":",
"if",
"not",
"encoded_string",
":",
"return",
"u''",
"# optimization -- first try ascii\r",
"try",
":",
"return",
"encoded_string",
".",
"decode",
"(",
"'ascii'",
")",
"except",
"UnicodeDecodeError",
":",... | Given an encoded string of unknown format, detect the format with
chardet and return the unicode version.
Example input from bug #11:
('\xfe\xff\x00I\x00n\x00s\x00p\x00e\x00c\x00t\x00i\x00o\x00n\x00'
'\x00R\x00e\x00p\x00o\x00r\x00t\x00 \x00v\x002\x00.\x002') | [
"Given",
"an",
"encoded",
"string",
"of",
"unknown",
"format",
"detect",
"the",
"format",
"with",
"chardet",
"and",
"return",
"the",
"unicode",
"version",
".",
"Example",
"input",
"from",
"bug",
"#11",
":",
"(",
"\\",
"xfe",
"\\",
"xff",
"\\",
"x00I",
"\... | python | train | 37.69697 |
hirmeos/entity-fishing-client-python | nerd/nerd_client.py | https://github.com/hirmeos/entity-fishing-client-python/blob/cd5c6e10c6c4e653669e11d735d5773766986bda/nerd/nerd_client.py#L39-L133 | def _process_query(self, query, prepared=False):
""" Process query recursively, if the text is too long,
it is split and processed bit a bit.
Args:
query (sdict): Text to be processed.
prepared (bool): True when the query is ready to be submitted via
POST req... | [
"def",
"_process_query",
"(",
"self",
",",
"query",
",",
"prepared",
"=",
"False",
")",
":",
"# Exit condition and POST",
"if",
"prepared",
"is",
"True",
":",
"files",
"=",
"{",
"'query'",
":",
"str",
"(",
"query",
")",
"}",
"logger",
".",
"debug",
"(",
... | Process query recursively, if the text is too long,
it is split and processed bit a bit.
Args:
query (sdict): Text to be processed.
prepared (bool): True when the query is ready to be submitted via
POST request.
Returns:
str: Body ready to be subm... | [
"Process",
"query",
"recursively",
"if",
"the",
"text",
"is",
"too",
"long",
"it",
"is",
"split",
"and",
"processed",
"bit",
"a",
"bit",
"."
] | python | test | 32.452632 |
tnkteja/myhelp | virtualEnvironment/lib/python2.7/site-packages/pip/_vendor/pkg_resources/__init__.py | https://github.com/tnkteja/myhelp/blob/fb3a4809d448ad14d5b2e6ddf2e7e89ad52b71cb/virtualEnvironment/lib/python2.7/site-packages/pip/_vendor/pkg_resources/__init__.py#L1328-L1337 | def is_invalid_marker(cls, text):
"""
Validate text as a PEP 426 environment marker; return an exception
if invalid or False otherwise.
"""
try:
cls.evaluate_marker(text)
except SyntaxError:
return cls.normalize_exception(sys.exc_info()[1])
... | [
"def",
"is_invalid_marker",
"(",
"cls",
",",
"text",
")",
":",
"try",
":",
"cls",
".",
"evaluate_marker",
"(",
"text",
")",
"except",
"SyntaxError",
":",
"return",
"cls",
".",
"normalize_exception",
"(",
"sys",
".",
"exc_info",
"(",
")",
"[",
"1",
"]",
... | Validate text as a PEP 426 environment marker; return an exception
if invalid or False otherwise. | [
"Validate",
"text",
"as",
"a",
"PEP",
"426",
"environment",
"marker",
";",
"return",
"an",
"exception",
"if",
"invalid",
"or",
"False",
"otherwise",
"."
] | python | test | 32.4 |
xnuinside/clifier | clifier/clifier.py | https://github.com/xnuinside/clifier/blob/3d704a30dc985bea3b876216accc53c19dc8b0df/clifier/clifier.py#L48-L57 | def apply_defaults(self, commands):
""" apply default settings to commands
not static, shadow "self" in eval
"""
for command in commands:
if 'action' in command and "()" in command['action']:
command['action'] = eval("self.{}".format(command['action']))
... | [
"def",
"apply_defaults",
"(",
"self",
",",
"commands",
")",
":",
"for",
"command",
"in",
"commands",
":",
"if",
"'action'",
"in",
"command",
"and",
"\"()\"",
"in",
"command",
"[",
"'action'",
"]",
":",
"command",
"[",
"'action'",
"]",
"=",
"eval",
"(",
... | apply default settings to commands
not static, shadow "self" in eval | [
"apply",
"default",
"settings",
"to",
"commands",
"not",
"static",
"shadow",
"self",
"in",
"eval"
] | python | valid | 45.3 |
readbeyond/aeneas | aeneas/audiofile.py | https://github.com/readbeyond/aeneas/blob/9d95535ad63eef4a98530cfdff033b8c35315ee1/aeneas/audiofile.py#L607-L630 | def write(self, file_path):
"""
Write the audio data to file.
Return ``True`` on success, or ``False`` otherwise.
:param string file_path: the path of the output file to be written
:raises: :class:`~aeneas.audiofile.AudioFileNotInitializedError`: if the audio file is not initial... | [
"def",
"write",
"(",
"self",
",",
"file_path",
")",
":",
"if",
"self",
".",
"__samples",
"is",
"None",
":",
"if",
"self",
".",
"file_path",
"is",
"None",
":",
"self",
".",
"log_exc",
"(",
"u\"AudioFile object not initialized\"",
",",
"None",
",",
"True",
... | Write the audio data to file.
Return ``True`` on success, or ``False`` otherwise.
:param string file_path: the path of the output file to be written
:raises: :class:`~aeneas.audiofile.AudioFileNotInitializedError`: if the audio file is not initialized yet
.. versionadded:: 1.2.0 | [
"Write",
"the",
"audio",
"data",
"to",
"file",
".",
"Return",
"True",
"on",
"success",
"or",
"False",
"otherwise",
"."
] | python | train | 47.25 |
dmlc/gluon-nlp | scripts/parsing/common/k_means.py | https://github.com/dmlc/gluon-nlp/blob/4b83eb6bcc8881e5f1081a3675adaa19fac5c0ba/scripts/parsing/common/k_means.py#L147-L155 | def _reindex(self):
"""
Index every sentence into a cluster
"""
self._len2split_idx = {}
last_split = -1
for split_idx, split in enumerate(self._splits):
self._len2split_idx.update(
dict(list(zip(list(range(last_split + 1, split)), [split_idx] ... | [
"def",
"_reindex",
"(",
"self",
")",
":",
"self",
".",
"_len2split_idx",
"=",
"{",
"}",
"last_split",
"=",
"-",
"1",
"for",
"split_idx",
",",
"split",
"in",
"enumerate",
"(",
"self",
".",
"_splits",
")",
":",
"self",
".",
"_len2split_idx",
".",
"update... | Index every sentence into a cluster | [
"Index",
"every",
"sentence",
"into",
"a",
"cluster"
] | python | train | 38.222222 |
iotile/coretools | iotilebuild/iotile/build/config/scons-local-3.0.1/SCons/Tool/FortranCommon.py | https://github.com/iotile/coretools/blob/2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec/iotilebuild/iotile/build/config/scons-local-3.0.1/SCons/Tool/FortranCommon.py#L218-L232 | def add_f95_to_env(env):
"""Add Builders and construction variables for f95 to an Environment."""
try:
F95Suffixes = env['F95FILESUFFIXES']
except KeyError:
F95Suffixes = ['.f95']
#print("Adding %s to f95 suffixes" % F95Suffixes)
try:
F95PPSuffixes = env['F95PPFILESUFFIXES']... | [
"def",
"add_f95_to_env",
"(",
"env",
")",
":",
"try",
":",
"F95Suffixes",
"=",
"env",
"[",
"'F95FILESUFFIXES'",
"]",
"except",
"KeyError",
":",
"F95Suffixes",
"=",
"[",
"'.f95'",
"]",
"#print(\"Adding %s to f95 suffixes\" % F95Suffixes)",
"try",
":",
"F95PPSuffixes"... | Add Builders and construction variables for f95 to an Environment. | [
"Add",
"Builders",
"and",
"construction",
"variables",
"for",
"f95",
"to",
"an",
"Environment",
"."
] | python | train | 30.333333 |
log2timeline/dfvfs | dfvfs/helpers/source_scanner.py | https://github.com/log2timeline/dfvfs/blob/2b3ccd115f9901d89f383397d4a1376a873c83c4/dfvfs/helpers/source_scanner.py#L540-L582 | def _ScanEncryptedVolumeNode(self, scan_context, scan_node):
"""Scans an encrypted volume node for supported formats.
Args:
scan_context (SourceScannerContext): source scanner context.
scan_node (SourceScanNode): source scan node.
Raises:
BackEndError: if the scan node cannot be unlocked... | [
"def",
"_ScanEncryptedVolumeNode",
"(",
"self",
",",
"scan_context",
",",
"scan_node",
")",
":",
"if",
"scan_node",
".",
"type_indicator",
"==",
"definitions",
".",
"TYPE_INDICATOR_APFS_CONTAINER",
":",
"# TODO: consider changes this when upstream changes have been made.",
"#... | Scans an encrypted volume node for supported formats.
Args:
scan_context (SourceScannerContext): source scanner context.
scan_node (SourceScanNode): source scan node.
Raises:
BackEndError: if the scan node cannot be unlocked.
ValueError: if the scan context or scan node is invalid. | [
"Scans",
"an",
"encrypted",
"volume",
"node",
"for",
"supported",
"formats",
"."
] | python | train | 44.27907 |
Bogdanp/anom-py | anom/query.py | https://github.com/Bogdanp/anom-py/blob/519078b6d1570fa63c5f17cf98817c7bb5588136/anom/query.py#L46-L54 | def batch_size(self):
"""int: The number of results to fetch per batch. Clamped to
limit if limit is set and is smaller than the given batch
size.
"""
batch_size = self.get("batch_size", DEFAULT_BATCH_SIZE)
if self.limit is not None:
return min(self.limit, ba... | [
"def",
"batch_size",
"(",
"self",
")",
":",
"batch_size",
"=",
"self",
".",
"get",
"(",
"\"batch_size\"",
",",
"DEFAULT_BATCH_SIZE",
")",
"if",
"self",
".",
"limit",
"is",
"not",
"None",
":",
"return",
"min",
"(",
"self",
".",
"limit",
",",
"batch_size",... | int: The number of results to fetch per batch. Clamped to
limit if limit is set and is smaller than the given batch
size. | [
"int",
":",
"The",
"number",
"of",
"results",
"to",
"fetch",
"per",
"batch",
".",
"Clamped",
"to",
"limit",
"if",
"limit",
"is",
"set",
"and",
"is",
"smaller",
"than",
"the",
"given",
"batch",
"size",
"."
] | python | train | 38.555556 |
markokr/rarfile | dumprar.py | https://github.com/markokr/rarfile/blob/2704344e8d7a1658c96c8ed8f449d7ba01bedea3/dumprar.py#L358-L366 | def check_crc(f, inf, desc):
"""Compare result crc to expected value.
"""
exp = inf._md_expect
if exp is None:
return
ucrc = f._md_context.digest()
if ucrc != exp:
print('crc error - %s - exp=%r got=%r' % (desc, exp, ucrc)) | [
"def",
"check_crc",
"(",
"f",
",",
"inf",
",",
"desc",
")",
":",
"exp",
"=",
"inf",
".",
"_md_expect",
"if",
"exp",
"is",
"None",
":",
"return",
"ucrc",
"=",
"f",
".",
"_md_context",
".",
"digest",
"(",
")",
"if",
"ucrc",
"!=",
"exp",
":",
"print... | Compare result crc to expected value. | [
"Compare",
"result",
"crc",
"to",
"expected",
"value",
"."
] | python | train | 28.333333 |
bio2bel/bio2bel | src/bio2bel/cli.py | https://github.com/bio2bel/bio2bel/blob/d80762d891fa18b248709ff0b0f97ebb65ec64c2/src/bio2bel/cli.py#L236-L255 | def write(connection, skip, directory, force):
"""Write all as BEL."""
os.makedirs(directory, exist_ok=True)
from .manager.bel_manager import BELManagerMixin
import pybel
for idx, name, manager in _iterate_managers(connection, skip):
if not isinstance(manager, BELManagerMixin):
c... | [
"def",
"write",
"(",
"connection",
",",
"skip",
",",
"directory",
",",
"force",
")",
":",
"os",
".",
"makedirs",
"(",
"directory",
",",
"exist_ok",
"=",
"True",
")",
"from",
".",
"manager",
".",
"bel_manager",
"import",
"BELManagerMixin",
"import",
"pybel"... | Write all as BEL. | [
"Write",
"all",
"as",
"BEL",
"."
] | python | valid | 39.25 |
gmichaeljaison/cv-utils | cv_utils/bbox.py | https://github.com/gmichaeljaison/cv-utils/blob/a8251c870165a7428d8c468a6436aa41d0cf7c09/cv_utils/bbox.py#L121-L131 | def overlaps(self, box, th=0.0001):
"""
Check whether this box and given box overlaps at least by given threshold.
:param box: Box to compare with
:param th: Threshold above which overlapping should be considered
:returns: True if overlaps
"""
int_box = Box.inter... | [
"def",
"overlaps",
"(",
"self",
",",
"box",
",",
"th",
"=",
"0.0001",
")",
":",
"int_box",
"=",
"Box",
".",
"intersection_box",
"(",
"self",
",",
"box",
")",
"small_box",
"=",
"self",
"if",
"self",
".",
"smaller",
"(",
"box",
")",
"else",
"box",
"r... | Check whether this box and given box overlaps at least by given threshold.
:param box: Box to compare with
:param th: Threshold above which overlapping should be considered
:returns: True if overlaps | [
"Check",
"whether",
"this",
"box",
"and",
"given",
"box",
"overlaps",
"at",
"least",
"by",
"given",
"threshold",
"."
] | python | train | 41.909091 |
lk-geimfari/mimesis | mimesis/providers/date.py | https://github.com/lk-geimfari/mimesis/blob/4b16ee7a8dba6281a904654a88dbb4b052869fc5/mimesis/providers/date.py#L161-L172 | def time(self) -> Time:
"""Generate a random time object.
:return: ``datetime.time`` object.
"""
random_time = time(
self.random.randint(0, 23),
self.random.randint(0, 59),
self.random.randint(0, 59),
self.random.randint(0, 999999),
... | [
"def",
"time",
"(",
"self",
")",
"->",
"Time",
":",
"random_time",
"=",
"time",
"(",
"self",
".",
"random",
".",
"randint",
"(",
"0",
",",
"23",
")",
",",
"self",
".",
"random",
".",
"randint",
"(",
"0",
",",
"59",
")",
",",
"self",
".",
"rando... | Generate a random time object.
:return: ``datetime.time`` object. | [
"Generate",
"a",
"random",
"time",
"object",
"."
] | python | train | 28.25 |
bigchaindb/bigchaindb | bigchaindb/utils.py | https://github.com/bigchaindb/bigchaindb/blob/835fdfcf598918f76139e3b88ee33dd157acaaa7/bigchaindb/utils.py#L107-L133 | def condition_details_has_owner(condition_details, owner):
"""Check if the public_key of owner is in the condition details
as an Ed25519Fulfillment.public_key
Args:
condition_details (dict): dict with condition details
owner (str): base58 public key of owner
Returns:
bool: True... | [
"def",
"condition_details_has_owner",
"(",
"condition_details",
",",
"owner",
")",
":",
"if",
"'subconditions'",
"in",
"condition_details",
":",
"result",
"=",
"condition_details_has_owner",
"(",
"condition_details",
"[",
"'subconditions'",
"]",
",",
"owner",
")",
"if... | Check if the public_key of owner is in the condition details
as an Ed25519Fulfillment.public_key
Args:
condition_details (dict): dict with condition details
owner (str): base58 public key of owner
Returns:
bool: True if the public key is found in the condition details, False otherw... | [
"Check",
"if",
"the",
"public_key",
"of",
"owner",
"is",
"in",
"the",
"condition",
"details",
"as",
"an",
"Ed25519Fulfillment",
".",
"public_key"
] | python | train | 34.185185 |
saltstack/salt | salt/modules/azurearm_network.py | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/azurearm_network.py#L853-L877 | def virtual_networks_list_all(**kwargs):
'''
.. versionadded:: 2019.2.0
List all virtual networks within a subscription.
CLI Example:
.. code-block:: bash
salt-call azurearm_network.virtual_networks_list_all
'''
result = {}
netconn = __utils__['azurearm.get_client']('network... | [
"def",
"virtual_networks_list_all",
"(",
"*",
"*",
"kwargs",
")",
":",
"result",
"=",
"{",
"}",
"netconn",
"=",
"__utils__",
"[",
"'azurearm.get_client'",
"]",
"(",
"'network'",
",",
"*",
"*",
"kwargs",
")",
"try",
":",
"vnets",
"=",
"__utils__",
"[",
"'... | .. versionadded:: 2019.2.0
List all virtual networks within a subscription.
CLI Example:
.. code-block:: bash
salt-call azurearm_network.virtual_networks_list_all | [
"..",
"versionadded",
"::",
"2019",
".",
"2",
".",
"0"
] | python | train | 25.76 |
gwastro/pycbc | pycbc/events/triggers.py | https://github.com/gwastro/pycbc/blob/7a64cdd104d263f1b6ea0b01e6841837d05a4cb3/pycbc/events/triggers.py#L259-L300 | def get_param(par, args, m1, m2, s1z, s2z):
"""
Helper function
Parameters
----------
par : string
Name of parameter to calculate
args : Namespace object returned from ArgumentParser instance
Calling code command line options, used for f_lower value
m1 : float or array of fl... | [
"def",
"get_param",
"(",
"par",
",",
"args",
",",
"m1",
",",
"m2",
",",
"s1z",
",",
"s2z",
")",
":",
"if",
"par",
"==",
"'mchirp'",
":",
"parvals",
"=",
"conversions",
".",
"mchirp_from_mass1_mass2",
"(",
"m1",
",",
"m2",
")",
"elif",
"par",
"==",
... | Helper function
Parameters
----------
par : string
Name of parameter to calculate
args : Namespace object returned from ArgumentParser instance
Calling code command line options, used for f_lower value
m1 : float or array of floats
First binary component mass (etc.)
Ret... | [
"Helper",
"function"
] | python | train | 36.619048 |
polysquare/jobstamps | jobstamps/jobstamp_cmd_main.py | https://github.com/polysquare/jobstamps/blob/49b4dec93b38c9db55643226a9788c675a53ef25/jobstamps/jobstamp_cmd_main.py#L36-L52 | def _run_cmd(cmd):
"""Run command specified by :cmd: and return stdout, stderr and code."""
if not os.path.exists(cmd[0]):
cmd[0] = shutil.which(cmd[0])
assert cmd[0] is not None
shebang_parts = parseshebang.parse(cmd[0])
proc = subprocess.Popen(shebang_parts + cmd,
... | [
"def",
"_run_cmd",
"(",
"cmd",
")",
":",
"if",
"not",
"os",
".",
"path",
".",
"exists",
"(",
"cmd",
"[",
"0",
"]",
")",
":",
"cmd",
"[",
"0",
"]",
"=",
"shutil",
".",
"which",
"(",
"cmd",
"[",
"0",
"]",
")",
"assert",
"cmd",
"[",
"0",
"]",
... | Run command specified by :cmd: and return stdout, stderr and code. | [
"Run",
"command",
"specified",
"by",
":",
"cmd",
":",
"and",
"return",
"stdout",
"stderr",
"and",
"code",
"."
] | python | train | 31.235294 |
non-Jedi/gyr | gyr/resources.py | https://github.com/non-Jedi/gyr/blob/9f7bfe033b9d3bbfd3a9e8aea02e35526b53125e/gyr/resources.py#L61-L81 | def on_put(self, request, response, txn_id=None):
"""Responds to PUT request containing events."""
response.body = "{}"
# Check whether repeat txn_id
if not self._is_new(txn_id):
response.status = falcon.HTTP_200
return
request.context["body"] = request.... | [
"def",
"on_put",
"(",
"self",
",",
"request",
",",
"response",
",",
"txn_id",
"=",
"None",
")",
":",
"response",
".",
"body",
"=",
"\"{}\"",
"# Check whether repeat txn_id",
"if",
"not",
"self",
".",
"_is_new",
"(",
"txn_id",
")",
":",
"response",
".",
"... | Responds to PUT request containing events. | [
"Responds",
"to",
"PUT",
"request",
"containing",
"events",
"."
] | python | train | 35.619048 |
cherrypy/cheroot | cheroot/server.py | https://github.com/cherrypy/cheroot/blob/2af3b1798d66da697957480d3a8b4831a405770b/cheroot/server.py#L541-L582 | def readline(self, size=None):
"""Read a single line from rfile buffer and return it.
Args:
size (int): minimum amount of data to read
Returns:
bytes: One line from rfile.
"""
data = EMPTY
if size == 0:
return data
while Tr... | [
"def",
"readline",
"(",
"self",
",",
"size",
"=",
"None",
")",
":",
"data",
"=",
"EMPTY",
"if",
"size",
"==",
"0",
":",
"return",
"data",
"while",
"True",
":",
"if",
"size",
"and",
"len",
"(",
"data",
")",
">=",
"size",
":",
"return",
"data",
"if... | Read a single line from rfile buffer and return it.
Args:
size (int): minimum amount of data to read
Returns:
bytes: One line from rfile. | [
"Read",
"a",
"single",
"line",
"from",
"rfile",
"buffer",
"and",
"return",
"it",
"."
] | python | train | 29.690476 |
bwhite/hadoopy | hadoopy/thirdparty/pyinstaller/PyInstaller/lib/altgraph/ObjectGraph.py | https://github.com/bwhite/hadoopy/blob/ff39b4e6d4e6efaf1f571cf0f2c0e0d7ab28c2d6/hadoopy/thirdparty/pyinstaller/PyInstaller/lib/altgraph/ObjectGraph.py#L148-L158 | def createReference(self, fromnode, tonode, edge_data=None):
"""
Create a reference from fromnode to tonode
"""
if fromnode is None:
fromnode = self
fromident, toident = self.getIdent(fromnode), self.getIdent(tonode)
if fromident is None or toident is None:
... | [
"def",
"createReference",
"(",
"self",
",",
"fromnode",
",",
"tonode",
",",
"edge_data",
"=",
"None",
")",
":",
"if",
"fromnode",
"is",
"None",
":",
"fromnode",
"=",
"self",
"fromident",
",",
"toident",
"=",
"self",
".",
"getIdent",
"(",
"fromnode",
")",... | Create a reference from fromnode to tonode | [
"Create",
"a",
"reference",
"from",
"fromnode",
"to",
"tonode"
] | python | train | 42.090909 |
OSSOS/MOP | src/jjk/preproc/scrample.py | https://github.com/OSSOS/MOP/blob/94f91d32ad5ec081d5a1ebd67604a838003465af/src/jjk/preproc/scrample.py#L89-L266 | def searchTriples(filenames,plant=False):
"""Given a list of exposure numbers, find all the KBOs in that set of exposures"""
print filenames
if opt.none :
return
import MOPfits,os
import MOPdbaccess
import string
import os.path
import pyfits
if len(filenames)!=3:
... | [
"def",
"searchTriples",
"(",
"filenames",
",",
"plant",
"=",
"False",
")",
":",
"print",
"filenames",
"if",
"opt",
".",
"none",
":",
"return",
"import",
"MOPfits",
",",
"os",
"import",
"MOPdbaccess",
"import",
"string",
"import",
"os",
".",
"path",
"import... | Given a list of exposure numbers, find all the KBOs in that set of exposures | [
"Given",
"a",
"list",
"of",
"exposure",
"numbers",
"find",
"all",
"the",
"KBOs",
"in",
"that",
"set",
"of",
"exposures"
] | python | train | 28.258427 |
esterhui/pypu | pypu/service_flickr.py | https://github.com/esterhui/pypu/blob/cc3e259d59f024c2c4c0fbb9c8a1547e51de75ec/pypu/service_flickr.py#L574-L608 | def _remove_media(self,directory,files=None):
"""Removes specified files from flickr"""
# Connect if we aren't already
if not self._connectToFlickr():
logger.error("%s - Couldn't connect to flickr")
return False
db=self._loadDB(directory)
# If no files gi... | [
"def",
"_remove_media",
"(",
"self",
",",
"directory",
",",
"files",
"=",
"None",
")",
":",
"# Connect if we aren't already",
"if",
"not",
"self",
".",
"_connectToFlickr",
"(",
")",
":",
"logger",
".",
"error",
"(",
"\"%s - Couldn't connect to flickr\"",
")",
"r... | Removes specified files from flickr | [
"Removes",
"specified",
"files",
"from",
"flickr"
] | python | train | 33.6 |
JdeRobot/base | src/drivers/MAVLinkServer/MAVProxy/modules/lib/mp_menu.py | https://github.com/JdeRobot/base/blob/303b18992785b2fe802212f2d758a60873007f1f/src/drivers/MAVLinkServer/MAVProxy/modules/lib/mp_menu.py#L201-L205 | def _append(self, menu):
'''append this menu item to a menu'''
from wx_loader import wx
menu.AppendMenu(-1, self.name, self.wx_menu()) | [
"def",
"_append",
"(",
"self",
",",
"menu",
")",
":",
"from",
"wx_loader",
"import",
"wx",
"menu",
".",
"AppendMenu",
"(",
"-",
"1",
",",
"self",
".",
"name",
",",
"self",
".",
"wx_menu",
"(",
")",
")"
] | append this menu item to a menu | [
"append",
"this",
"menu",
"item",
"to",
"a",
"menu"
] | python | train | 31 |
cjdrake/pyeda | pyeda/boolalg/bfarray.py | https://github.com/cjdrake/pyeda/blob/554ee53aa678f4b61bcd7e07ba2c74ddc749d665/pyeda/boolalg/bfarray.py#L680-L694 | def to_uint(self):
"""Convert vector to an unsigned integer, if possible.
This is only useful for arrays filled with zero/one entries.
"""
num = 0
for i, f in enumerate(self._items):
if f.is_zero():
pass
elif f.is_one():
nu... | [
"def",
"to_uint",
"(",
"self",
")",
":",
"num",
"=",
"0",
"for",
"i",
",",
"f",
"in",
"enumerate",
"(",
"self",
".",
"_items",
")",
":",
"if",
"f",
".",
"is_zero",
"(",
")",
":",
"pass",
"elif",
"f",
".",
"is_one",
"(",
")",
":",
"num",
"+=",... | Convert vector to an unsigned integer, if possible.
This is only useful for arrays filled with zero/one entries. | [
"Convert",
"vector",
"to",
"an",
"unsigned",
"integer",
"if",
"possible",
"."
] | python | train | 31.466667 |
linkedin/luminol | src/luminol/modules/time_series.py | https://github.com/linkedin/luminol/blob/42e4ab969b774ff98f902d064cb041556017f635/src/luminol/modules/time_series.py#L248-L272 | def smooth(self, smoothing_factor):
"""
return a new time series which is a exponential smoothed version of the original data series.
soomth forward once, backward once, and then take the average.
:param float smoothing_factor: smoothing factor
:return: :class:`TimeSeries` objec... | [
"def",
"smooth",
"(",
"self",
",",
"smoothing_factor",
")",
":",
"forward_smooth",
"=",
"{",
"}",
"backward_smooth",
"=",
"{",
"}",
"output",
"=",
"{",
"}",
"if",
"self",
":",
"pre",
"=",
"self",
".",
"values",
"[",
"0",
"]",
"next",
"=",
"self",
"... | return a new time series which is a exponential smoothed version of the original data series.
soomth forward once, backward once, and then take the average.
:param float smoothing_factor: smoothing factor
:return: :class:`TimeSeries` object. | [
"return",
"a",
"new",
"time",
"series",
"which",
"is",
"a",
"exponential",
"smoothed",
"version",
"of",
"the",
"original",
"data",
"series",
".",
"soomth",
"forward",
"once",
"backward",
"once",
"and",
"then",
"take",
"the",
"average",
"."
] | python | train | 40.28 |
pantsbuild/pants | src/python/pants/pantsd/pailgun_server.py | https://github.com/pantsbuild/pants/blob/b72e650da0df685824ffdcc71988b8c282d0962d/src/python/pants/pantsd/pailgun_server.py#L56-L58 | def _run_pants(self, sock, arguments, environment):
"""Execute a given run with a pants runner."""
self.server.runner_factory(sock, arguments, environment).run() | [
"def",
"_run_pants",
"(",
"self",
",",
"sock",
",",
"arguments",
",",
"environment",
")",
":",
"self",
".",
"server",
".",
"runner_factory",
"(",
"sock",
",",
"arguments",
",",
"environment",
")",
".",
"run",
"(",
")"
] | Execute a given run with a pants runner. | [
"Execute",
"a",
"given",
"run",
"with",
"a",
"pants",
"runner",
"."
] | python | train | 55.666667 |
ff0000/scarlet | scarlet/cms/actions.py | https://github.com/ff0000/scarlet/blob/6c37befd810916a2d7ffff2cdb2dab57bcb6d12e/scarlet/cms/actions.py#L421-L428 | def get_object_url(self):
"""
Returns the url to link to the object
The get_view_url will be called on the current bundle using
'edit` as the view name.
"""
return self.bundle.get_view_url('edit',
self.request.user, {}, self.kwargs) | [
"def",
"get_object_url",
"(",
"self",
")",
":",
"return",
"self",
".",
"bundle",
".",
"get_view_url",
"(",
"'edit'",
",",
"self",
".",
"request",
".",
"user",
",",
"{",
"}",
",",
"self",
".",
"kwargs",
")"
] | Returns the url to link to the object
The get_view_url will be called on the current bundle using
'edit` as the view name. | [
"Returns",
"the",
"url",
"to",
"link",
"to",
"the",
"object",
"The",
"get_view_url",
"will",
"be",
"called",
"on",
"the",
"current",
"bundle",
"using",
"edit",
"as",
"the",
"view",
"name",
"."
] | python | train | 39.125 |
humilis/humilis-lambdautils | lambdautils/state.py | https://github.com/humilis/humilis-lambdautils/blob/58f75eb5ace23523c283708d56a9193181ea7e8e/lambdautils/state.py#L78-L134 | def _get_secret_from_vault(
key, environment=None, stage=None, namespace=None,
wait_exponential_multiplier=50, wait_exponential_max=5000,
stop_max_delay=10000):
"""Retrieves a secret from the secrets vault."""
# Get the encrypted secret from DynamoDB
table_name = _secrets_table_name(... | [
"def",
"_get_secret_from_vault",
"(",
"key",
",",
"environment",
"=",
"None",
",",
"stage",
"=",
"None",
",",
"namespace",
"=",
"None",
",",
"wait_exponential_multiplier",
"=",
"50",
",",
"wait_exponential_max",
"=",
"5000",
",",
"stop_max_delay",
"=",
"10000",
... | Retrieves a secret from the secrets vault. | [
"Retrieves",
"a",
"secret",
"from",
"the",
"secrets",
"vault",
"."
] | python | train | 31.368421 |
ga4gh/ga4gh-server | ga4gh/server/datamodel/variants.py | https://github.com/ga4gh/ga4gh-server/blob/1aa18922ef136db8604f6f098cb1732cba6f2a76/ga4gh/server/datamodel/variants.py#L484-L496 | def populateFromFile(self, dataUrls, indexFiles):
"""
Populates this variant set using the specified lists of data
files and indexes. These must be in the same order, such that
the jth index file corresponds to the jth data file.
"""
assert len(dataUrls) == len(indexFiles... | [
"def",
"populateFromFile",
"(",
"self",
",",
"dataUrls",
",",
"indexFiles",
")",
":",
"assert",
"len",
"(",
"dataUrls",
")",
"==",
"len",
"(",
"indexFiles",
")",
"for",
"dataUrl",
",",
"indexFile",
"in",
"zip",
"(",
"dataUrls",
",",
"indexFiles",
")",
":... | Populates this variant set using the specified lists of data
files and indexes. These must be in the same order, such that
the jth index file corresponds to the jth data file. | [
"Populates",
"this",
"variant",
"set",
"using",
"the",
"specified",
"lists",
"of",
"data",
"files",
"and",
"indexes",
".",
"These",
"must",
"be",
"in",
"the",
"same",
"order",
"such",
"that",
"the",
"jth",
"index",
"file",
"corresponds",
"to",
"the",
"jth"... | python | train | 45.384615 |
TriOptima/tri.declarative | lib/tri/declarative/__init__.py | https://github.com/TriOptima/tri.declarative/blob/13d90d4c2a10934e37a4139e63d51a859fb3e303/lib/tri/declarative/__init__.py#L704-L715 | def getattr_path(obj, path):
"""
Get an attribute path, as defined by a string separated by '__'.
getattr_path(foo, 'a__b__c') is roughly equivalent to foo.a.b.c but
will short circuit to return None if something on the path is None.
"""
path = path.split('__')
for name in path:
obj ... | [
"def",
"getattr_path",
"(",
"obj",
",",
"path",
")",
":",
"path",
"=",
"path",
".",
"split",
"(",
"'__'",
")",
"for",
"name",
"in",
"path",
":",
"obj",
"=",
"getattr",
"(",
"obj",
",",
"name",
")",
"if",
"obj",
"is",
"None",
":",
"return",
"None"... | Get an attribute path, as defined by a string separated by '__'.
getattr_path(foo, 'a__b__c') is roughly equivalent to foo.a.b.c but
will short circuit to return None if something on the path is None. | [
"Get",
"an",
"attribute",
"path",
"as",
"defined",
"by",
"a",
"string",
"separated",
"by",
"__",
".",
"getattr_path",
"(",
"foo",
"a__b__c",
")",
"is",
"roughly",
"equivalent",
"to",
"foo",
".",
"a",
".",
"b",
".",
"c",
"but",
"will",
"short",
"circuit... | python | train | 32.666667 |
saltstack/salt | salt/modules/boto_iam.py | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/boto_iam.py#L1123-L1145 | def get_role_policy(role_name, policy_name, region=None, key=None,
keyid=None, profile=None):
'''
Get a role policy.
CLI Example:
.. code-block:: bash
salt myminion boto_iam.get_role_policy myirole mypolicy
'''
conn = _get_conn(region=region, key=key, keyid=keyid, ... | [
"def",
"get_role_policy",
"(",
"role_name",
",",
"policy_name",
",",
"region",
"=",
"None",
",",
"key",
"=",
"None",
",",
"keyid",
"=",
"None",
",",
"profile",
"=",
"None",
")",
":",
"conn",
"=",
"_get_conn",
"(",
"region",
"=",
"region",
",",
"key",
... | Get a role policy.
CLI Example:
.. code-block:: bash
salt myminion boto_iam.get_role_policy myirole mypolicy | [
"Get",
"a",
"role",
"policy",
"."
] | python | train | 32.565217 |
callowayproject/Calloway | calloway/apps/django_ext/templatetags/listutil.py | https://github.com/callowayproject/Calloway/blob/d22e98d41fbd298ab6393ba7bd84a75528be9f81/calloway/apps/django_ext/templatetags/listutil.py#L77-L103 | def partition_horizontal_twice(thelist, numbers):
"""
numbers is split on a comma to n and n2.
Break a list into peices each peice alternating between n and n2 items long
``partition_horizontal_twice(range(14), "3,4")`` gives::
[[0, 1, 2],
[3, 4, 5, 6],
[7, 8, 9],
... | [
"def",
"partition_horizontal_twice",
"(",
"thelist",
",",
"numbers",
")",
":",
"n",
",",
"n2",
"=",
"numbers",
".",
"split",
"(",
"','",
")",
"try",
":",
"n",
"=",
"int",
"(",
"n",
")",
"n2",
"=",
"int",
"(",
"n2",
")",
"thelist",
"=",
"list",
"(... | numbers is split on a comma to n and n2.
Break a list into peices each peice alternating between n and n2 items long
``partition_horizontal_twice(range(14), "3,4")`` gives::
[[0, 1, 2],
[3, 4, 5, 6],
[7, 8, 9],
[10, 11, 12, 13]]
Clear as mud? | [
"numbers",
"is",
"split",
"on",
"a",
"comma",
"to",
"n",
"and",
"n2",
".",
"Break",
"a",
"list",
"into",
"peices",
"each",
"peice",
"alternating",
"between",
"n",
"and",
"n2",
"items",
"long",
"partition_horizontal_twice",
"(",
"range",
"(",
"14",
")",
"... | python | train | 26.37037 |
Xion/taipan | taipan/objective/modifiers.py | https://github.com/Xion/taipan/blob/f333f0287c8bd0915182c7d5308e5f05ef0cca78/taipan/objective/modifiers.py#L50-L80 | def abstract(class_):
"""Mark the class as _abstract_ base class, forbidding its instantiation.
.. note::
Unlike other modifiers, ``@abstract`` can be applied
to all Python classes, not just subclasses of :class:`Object`.
.. versionadded:: 0.0.3
"""
if not inspect.isclass(class_):... | [
"def",
"abstract",
"(",
"class_",
")",
":",
"if",
"not",
"inspect",
".",
"isclass",
"(",
"class_",
")",
":",
"raise",
"TypeError",
"(",
"\"@abstract can only be applied to classes\"",
")",
"abc_meta",
"=",
"None",
"# if the class is not already using a metaclass specifi... | Mark the class as _abstract_ base class, forbidding its instantiation.
.. note::
Unlike other modifiers, ``@abstract`` can be applied
to all Python classes, not just subclasses of :class:`Object`.
.. versionadded:: 0.0.3 | [
"Mark",
"the",
"class",
"as",
"_abstract_",
"base",
"class",
"forbidding",
"its",
"instantiation",
"."
] | python | train | 37.193548 |
manns/pyspread | pyspread/src/lib/vlc.py | https://github.com/manns/pyspread/blob/0e2fd44c2e0f06605efc3058c20a43a8c1f9e7e0/pyspread/src/lib/vlc.py#L5619-L5628 | def libvlc_video_get_size(p_mi, num):
'''Get the pixel dimensions of a video.
@param p_mi: media player.
@param num: number of the video (starting from, and most commonly 0).
@return: px pixel width, py pixel height.
'''
f = _Cfunctions.get('libvlc_video_get_size', None) or \
_Cfunction(... | [
"def",
"libvlc_video_get_size",
"(",
"p_mi",
",",
"num",
")",
":",
"f",
"=",
"_Cfunctions",
".",
"get",
"(",
"'libvlc_video_get_size'",
",",
"None",
")",
"or",
"_Cfunction",
"(",
"'libvlc_video_get_size'",
",",
"(",
"(",
"1",
",",
")",
",",
"(",
"1",
","... | Get the pixel dimensions of a video.
@param p_mi: media player.
@param num: number of the video (starting from, and most commonly 0).
@return: px pixel width, py pixel height. | [
"Get",
"the",
"pixel",
"dimensions",
"of",
"a",
"video",
"."
] | python | train | 51.6 |
kejbaly2/metrique | metrique/utils.py | https://github.com/kejbaly2/metrique/blob/a10b076097441b7dde687949139f702f5c1e1b35/metrique/utils.py#L197-L227 | def clear_stale_pids(pids, pid_dir='/tmp', prefix='', multi=False):
'check for and remove any pids which have no corresponding process'
if isinstance(pids, (int, float, long)):
pids = [pids]
pids = str2list(pids, map_=unicode)
procs = map(unicode, os.listdir('/proc'))
running = [pid for pid ... | [
"def",
"clear_stale_pids",
"(",
"pids",
",",
"pid_dir",
"=",
"'/tmp'",
",",
"prefix",
"=",
"''",
",",
"multi",
"=",
"False",
")",
":",
"if",
"isinstance",
"(",
"pids",
",",
"(",
"int",
",",
"float",
",",
"long",
")",
")",
":",
"pids",
"=",
"[",
"... | check for and remove any pids which have no corresponding process | [
"check",
"for",
"and",
"remove",
"any",
"pids",
"which",
"have",
"no",
"corresponding",
"process"
] | python | train | 34.935484 |
LionelR/pyair | pyair/stats.py | https://github.com/LionelR/pyair/blob/467e8a843ca9f882f8bb2958805b7293591996ad/pyair/stats.py#L31-L36 | def mean(a, rep=0.75, **kwargs):
"""Compute the average along a 1D array like ma.mean,
but with a representativity coefficient : if ma.count(a)/ma.size(a)>=rep,
then the result is a masked value
"""
return rfunc(a, ma.mean, rep, **kwargs) | [
"def",
"mean",
"(",
"a",
",",
"rep",
"=",
"0.75",
",",
"*",
"*",
"kwargs",
")",
":",
"return",
"rfunc",
"(",
"a",
",",
"ma",
".",
"mean",
",",
"rep",
",",
"*",
"*",
"kwargs",
")"
] | Compute the average along a 1D array like ma.mean,
but with a representativity coefficient : if ma.count(a)/ma.size(a)>=rep,
then the result is a masked value | [
"Compute",
"the",
"average",
"along",
"a",
"1D",
"array",
"like",
"ma",
".",
"mean",
"but",
"with",
"a",
"representativity",
"coefficient",
":",
"if",
"ma",
".",
"count",
"(",
"a",
")",
"/",
"ma",
".",
"size",
"(",
"a",
")",
">",
"=",
"rep",
"then"... | python | valid | 42.166667 |
ace0/pyrelic | pyrelic/vpopProfile.py | https://github.com/ace0/pyrelic/blob/f23d4e6586674675f72304d5938548267d6413bf/pyrelic/vpopProfile.py#L99-L132 | def verifyG1(x, tTilde, y, pi, errorOnFail=True):
"""
Verifies a zero-knowledge proof where p \in G1.
@errorOnFail: Raise an exception if the proof does not hold.
"""
# Unpack the proof
p,c,u = pi
# Verify types
assertType(x, G1Element)
assertType(tTilde, G2Element)
assertType(y... | [
"def",
"verifyG1",
"(",
"x",
",",
"tTilde",
",",
"y",
",",
"pi",
",",
"errorOnFail",
"=",
"True",
")",
":",
"# Unpack the proof",
"p",
",",
"c",
",",
"u",
"=",
"pi",
"# Verify types",
"assertType",
"(",
"x",
",",
"G1Element",
")",
"assertType",
"(",
... | Verifies a zero-knowledge proof where p \in G1.
@errorOnFail: Raise an exception if the proof does not hold. | [
"Verifies",
"a",
"zero",
"-",
"knowledge",
"proof",
"where",
"p",
"\\",
"in",
"G1",
"."
] | python | train | 23.117647 |
PmagPy/PmagPy | pmagpy/pmag.py | https://github.com/PmagPy/PmagPy/blob/c7984f8809bf40fe112e53dcc311a33293b62d0b/pmagpy/pmag.py#L3994-L4047 | def fisher_mean(data):
"""
Calculates the Fisher mean and associated parameter from a di_block
Parameters
----------
di_block : a nested list of [dec,inc] or [dec,inc,intensity]
Returns
-------
fpars : dictionary containing the Fisher mean and statistics
dec : mean declination
... | [
"def",
"fisher_mean",
"(",
"data",
")",
":",
"R",
",",
"Xbar",
",",
"X",
",",
"fpars",
"=",
"0",
",",
"[",
"0",
",",
"0",
",",
"0",
"]",
",",
"[",
"]",
",",
"{",
"}",
"N",
"=",
"len",
"(",
"data",
")",
"if",
"N",
"<",
"2",
":",
"return"... | Calculates the Fisher mean and associated parameter from a di_block
Parameters
----------
di_block : a nested list of [dec,inc] or [dec,inc,intensity]
Returns
-------
fpars : dictionary containing the Fisher mean and statistics
dec : mean declination
inc : mean inclination
... | [
"Calculates",
"the",
"Fisher",
"mean",
"and",
"associated",
"parameter",
"from",
"a",
"di_block"
] | python | train | 24.62963 |
apache/airflow | airflow/hooks/oracle_hook.py | https://github.com/apache/airflow/blob/b69c686ad8a0c89b9136bb4b31767257eb7b2597/airflow/hooks/oracle_hook.py#L184-L231 | def bulk_insert_rows(self, table, rows, target_fields=None, commit_every=5000):
"""
A performant bulk insert for cx_Oracle
that uses prepared statements via `executemany()`.
For best performance, pass in `rows` as an iterator.
:param table: target Oracle table, use dot notation ... | [
"def",
"bulk_insert_rows",
"(",
"self",
",",
"table",
",",
"rows",
",",
"target_fields",
"=",
"None",
",",
"commit_every",
"=",
"5000",
")",
":",
"if",
"not",
"rows",
":",
"raise",
"ValueError",
"(",
"\"parameter rows could not be None or empty iterable\"",
")",
... | A performant bulk insert for cx_Oracle
that uses prepared statements via `executemany()`.
For best performance, pass in `rows` as an iterator.
:param table: target Oracle table, use dot notation to target a
specific database
:type table: str
:param rows: the rows to ... | [
"A",
"performant",
"bulk",
"insert",
"for",
"cx_Oracle",
"that",
"uses",
"prepared",
"statements",
"via",
"executemany",
"()",
".",
"For",
"best",
"performance",
"pass",
"in",
"rows",
"as",
"an",
"iterator",
"."
] | python | test | 43.895833 |
bcbio/bcbio-nextgen | bcbio/qc/chipseq.py | https://github.com/bcbio/bcbio-nextgen/blob/6a9348c0054ccd5baffd22f1bb7d0422f6978b20/bcbio/qc/chipseq.py#L34-L47 | def chipqc(bam_file, sample, out_dir):
"""Attempt code to run ChIPQC bioconductor packate in one sample"""
sample_name = dd.get_sample_name(sample)
logger.warning("ChIPQC is unstable right now, if it breaks, turn off the tool.")
if utils.file_exists(out_dir):
return _get_output(out_dir)
with... | [
"def",
"chipqc",
"(",
"bam_file",
",",
"sample",
",",
"out_dir",
")",
":",
"sample_name",
"=",
"dd",
".",
"get_sample_name",
"(",
"sample",
")",
"logger",
".",
"warning",
"(",
"\"ChIPQC is unstable right now, if it breaks, turn off the tool.\"",
")",
"if",
"utils",
... | Attempt code to run ChIPQC bioconductor packate in one sample | [
"Attempt",
"code",
"to",
"run",
"ChIPQC",
"bioconductor",
"packate",
"in",
"one",
"sample"
] | python | train | 47.357143 |
vmware/pyvmomi | pyVmomi/SoapAdapter.py | https://github.com/vmware/pyvmomi/blob/3ffcb23bf77d757175c0d5216ba9a25345d824cd/pyVmomi/SoapAdapter.py#L276-L281 | def _NSPrefix(self, ns):
""" Get xml ns prefix. self.nsMap must be set """
if ns == self.defaultNS:
return ''
prefix = self.nsMap[ns]
return prefix and prefix + ':' or '' | [
"def",
"_NSPrefix",
"(",
"self",
",",
"ns",
")",
":",
"if",
"ns",
"==",
"self",
".",
"defaultNS",
":",
"return",
"''",
"prefix",
"=",
"self",
".",
"nsMap",
"[",
"ns",
"]",
"return",
"prefix",
"and",
"prefix",
"+",
"':'",
"or",
"''"
] | Get xml ns prefix. self.nsMap must be set | [
"Get",
"xml",
"ns",
"prefix",
".",
"self",
".",
"nsMap",
"must",
"be",
"set"
] | python | train | 33 |
spyder-ide/spyder | spyder/plugins/editor/widgets/editor.py | https://github.com/spyder-ide/spyder/blob/f76836ce1b924bcc4efd3f74f2960d26a4e528e0/spyder/plugins/editor/widgets/editor.py#L128-L158 | def update_queue(self):
"""Update queue"""
started = 0
for parent_id, threadlist in list(self.started_threads.items()):
still_running = []
for thread in threadlist:
if thread.isFinished():
end_callback = self.end_callbacks.pop(id... | [
"def",
"update_queue",
"(",
"self",
")",
":",
"started",
"=",
"0",
"for",
"parent_id",
",",
"threadlist",
"in",
"list",
"(",
"self",
".",
"started_threads",
".",
"items",
"(",
")",
")",
":",
"still_running",
"=",
"[",
"]",
"for",
"thread",
"in",
"threa... | Update queue | [
"Update",
"queue"
] | python | train | 46.032258 |
blockstack/blockstack-core | blockstack/lib/subdomains.py | https://github.com/blockstack/blockstack-core/blob/1dcfdd39b152d29ce13e736a6a1a0981401a0505/blockstack/lib/subdomains.py#L1130-L1150 | def get_subdomain_entry(self, fqn, accepted=True, cur=None):
"""
Given a fully-qualified subdomain, get its (latest) subdomain record.
Raises SubdomainNotFound if there is no such subdomain
"""
get_cmd = "SELECT * FROM {} WHERE fully_qualified_subdomain=? {} ORDER BY sequence DES... | [
"def",
"get_subdomain_entry",
"(",
"self",
",",
"fqn",
",",
"accepted",
"=",
"True",
",",
"cur",
"=",
"None",
")",
":",
"get_cmd",
"=",
"\"SELECT * FROM {} WHERE fully_qualified_subdomain=? {} ORDER BY sequence DESC, parent_zonefile_index DESC LIMIT 1;\"",
".",
"format",
"(... | Given a fully-qualified subdomain, get its (latest) subdomain record.
Raises SubdomainNotFound if there is no such subdomain | [
"Given",
"a",
"fully",
"-",
"qualified",
"subdomain",
"get",
"its",
"(",
"latest",
")",
"subdomain",
"record",
".",
"Raises",
"SubdomainNotFound",
"if",
"there",
"is",
"no",
"such",
"subdomain"
] | python | train | 37.333333 |
bram85/topydo | topydo/lib/Recurrence.py | https://github.com/bram85/topydo/blob/b59fcfca5361869a6b78d4c9808c7c6cd0a18b58/topydo/lib/Recurrence.py#L30-L73 | def advance_recurring_todo(p_todo, p_offset=None, p_strict=False):
"""
Given a Todo item, return a new instance of a Todo item with the dates
shifted according to the recurrence rule.
Strict means that the real due date is taken as a offset, not today or a
future date to determine the offset.
... | [
"def",
"advance_recurring_todo",
"(",
"p_todo",
",",
"p_offset",
"=",
"None",
",",
"p_strict",
"=",
"False",
")",
":",
"todo",
"=",
"Todo",
"(",
"p_todo",
".",
"source",
"(",
")",
")",
"pattern",
"=",
"todo",
".",
"tag_value",
"(",
"'rec'",
")",
"if",
... | Given a Todo item, return a new instance of a Todo item with the dates
shifted according to the recurrence rule.
Strict means that the real due date is taken as a offset, not today or a
future date to determine the offset.
When the todo item has no due date, then the date is used passed by the
cal... | [
"Given",
"a",
"Todo",
"item",
"return",
"a",
"new",
"instance",
"of",
"a",
"Todo",
"item",
"with",
"the",
"dates",
"shifted",
"according",
"to",
"the",
"recurrence",
"rule",
"."
] | python | train | 28.545455 |
ThreatConnect-Inc/tcex | tcex/tcex_ti_group.py | https://github.com/ThreatConnect-Inc/tcex/blob/dd4d7a1ef723af1561687120191886b9a2fd4b47/tcex/tcex_ti_group.py#L81-L104 | def add_key_value(self, key, value):
"""Add custom field to Group object.
.. note:: The key must be the exact name required by the batch schema.
Example::
document = tcex.batch.group('Document', 'My Document')
document.add_key_value('fileName', 'something.pdf')
... | [
"def",
"add_key_value",
"(",
"self",
",",
"key",
",",
"value",
")",
":",
"key",
"=",
"self",
".",
"_metadata_map",
".",
"get",
"(",
"key",
",",
"key",
")",
"if",
"key",
"in",
"[",
"'dateAdded'",
",",
"'eventDate'",
",",
"'firstSeen'",
",",
"'publishDat... | Add custom field to Group object.
.. note:: The key must be the exact name required by the batch schema.
Example::
document = tcex.batch.group('Document', 'My Document')
document.add_key_value('fileName', 'something.pdf')
Args:
key (str): The field key to ... | [
"Add",
"custom",
"field",
"to",
"Group",
"object",
"."
] | python | train | 36.583333 |
tritemio/PyBroMo | pybromo/timestamps.py | https://github.com/tritemio/PyBroMo/blob/b75f82a4551ff37e7c7a7e6954c536451f3e6d06/pybromo/timestamps.py#L244-L266 | def run_da(self, rs, overwrite=True, skip_existing=False, path=None,
chunksize=None):
"""Compute timestamps for current populations."""
if path is None:
path = str(self.S.store.filepath.parent)
kwargs = dict(rs=rs, overwrite=overwrite, path=path,
... | [
"def",
"run_da",
"(",
"self",
",",
"rs",
",",
"overwrite",
"=",
"True",
",",
"skip_existing",
"=",
"False",
",",
"path",
"=",
"None",
",",
"chunksize",
"=",
"None",
")",
":",
"if",
"path",
"is",
"None",
":",
"path",
"=",
"str",
"(",
"self",
".",
... | Compute timestamps for current populations. | [
"Compute",
"timestamps",
"for",
"current",
"populations",
"."
] | python | valid | 43.826087 |
CygnusNetworks/pypureomapi | pypureomapi.py | https://github.com/CygnusNetworks/pypureomapi/blob/ff4459678ec023fd56e64ce518a86860efec26bf/pypureomapi.py#L224-L233 | def consume(self, length):
"""
>>> OutBuffer().add(b"spam").consume(2).getvalue() == b"am"
True
@type length: int
@returns: self
"""
self.buff = io.BytesIO(self.getvalue()[length:])
return self | [
"def",
"consume",
"(",
"self",
",",
"length",
")",
":",
"self",
".",
"buff",
"=",
"io",
".",
"BytesIO",
"(",
"self",
".",
"getvalue",
"(",
")",
"[",
"length",
":",
"]",
")",
"return",
"self"
] | >>> OutBuffer().add(b"spam").consume(2).getvalue() == b"am"
True
@type length: int
@returns: self | [
">>>",
"OutBuffer",
"()",
".",
"add",
"(",
"b",
"spam",
")",
".",
"consume",
"(",
"2",
")",
".",
"getvalue",
"()",
"==",
"b",
"am",
"True"
] | python | train | 20.1 |
calmjs/calmjs.parse | src/calmjs/parse/unparsers/walker.py | https://github.com/calmjs/calmjs.parse/blob/369f0ee346c5a84c4d5c35a7733a0e63b02eac59/src/calmjs/parse/unparsers/walker.py#L226-L365 | def walk(dispatcher, node, definition=None):
"""
The default, standalone walk function following the standard
argument ordering for the unparsing walkers.
Arguments:
dispatcher
a Dispatcher instance, defined earlier in this module. This
instance will dispatch out the correct calla... | [
"def",
"walk",
"(",
"dispatcher",
",",
"node",
",",
"definition",
"=",
"None",
")",
":",
"# The inner walk function - this is actually exposed to the token",
"# rule objects so they can also make use of it to process the node",
"# with the dispatcher.",
"nodes",
"=",
"[",
"]",
... | The default, standalone walk function following the standard
argument ordering for the unparsing walkers.
Arguments:
dispatcher
a Dispatcher instance, defined earlier in this module. This
instance will dispatch out the correct callable for the various
object types encountered thro... | [
"The",
"default",
"standalone",
"walk",
"function",
"following",
"the",
"standard",
"argument",
"ordering",
"for",
"the",
"unparsing",
"walkers",
"."
] | python | train | 38.135714 |
rgs1/zk_shell | zk_shell/xclient.py | https://github.com/rgs1/zk_shell/blob/bbf34fdfcf1f81100e2a5816fad8af6afc782a54/zk_shell/xclient.py#L309-L348 | def diff(self, path_a, path_b):
""" Performs a deep comparison of path_a/ and path_b/
For each child, it yields (rv, child) where rv:
-1 if doesn't exist in path_b (destination)
0 if they are different
1 if it doesn't exist in path_a (source)
"""
... | [
"def",
"diff",
"(",
"self",
",",
"path_a",
",",
"path_b",
")",
":",
"path_a",
"=",
"path_a",
".",
"rstrip",
"(",
"\"/\"",
")",
"path_b",
"=",
"path_b",
".",
"rstrip",
"(",
"\"/\"",
")",
"if",
"not",
"self",
".",
"exists",
"(",
"path_a",
")",
"or",
... | Performs a deep comparison of path_a/ and path_b/
For each child, it yields (rv, child) where rv:
-1 if doesn't exist in path_b (destination)
0 if they are different
1 if it doesn't exist in path_a (source) | [
"Performs",
"a",
"deep",
"comparison",
"of",
"path_a",
"/",
"and",
"path_b",
"/"
] | python | train | 30.7 |
Peter-Slump/python-keycloak-client | src/keycloak/uma.py | https://github.com/Peter-Slump/python-keycloak-client/blob/379ae58f3c65892327b0c98c06d4982aa83f357e/src/keycloak/uma.py#L123-L140 | def resource_create_ticket(self, token, id, scopes, **kwargs):
"""
Create a ticket form permission to resource.
https://www.keycloak.org/docs/latest/authorization_services/index.html#_service_protection_permission_api_papi
:param str token: user access token
:param str id: reso... | [
"def",
"resource_create_ticket",
"(",
"self",
",",
"token",
",",
"id",
",",
"scopes",
",",
"*",
"*",
"kwargs",
")",
":",
"data",
"=",
"dict",
"(",
"resource_id",
"=",
"id",
",",
"resource_scopes",
"=",
"scopes",
",",
"*",
"*",
"kwargs",
")",
"return",
... | Create a ticket form permission to resource.
https://www.keycloak.org/docs/latest/authorization_services/index.html#_service_protection_permission_api_papi
:param str token: user access token
:param str id: resource id
:param list scopes: scopes access is wanted
:param dict cla... | [
"Create",
"a",
"ticket",
"form",
"permission",
"to",
"resource",
"."
] | python | train | 38.222222 |
WalletGuild/desw | desw/server.py | https://github.com/WalletGuild/desw/blob/f966c612e675961d9dbd8268749e349ba10a47c2/desw/server.py#L27-L48 | def get_last_nonce(app, key, nonce):
"""
Get the last_nonce used by the given key from the SQLAlchemy database.
Update the last_nonce to nonce at the same time.
:param str key: the public key the nonce belongs to
:param int nonce: the last nonce used by this key
"""
uk = ses.query(um.UserKe... | [
"def",
"get_last_nonce",
"(",
"app",
",",
"key",
",",
"nonce",
")",
":",
"uk",
"=",
"ses",
".",
"query",
"(",
"um",
".",
"UserKey",
")",
".",
"filter",
"(",
"um",
".",
"UserKey",
".",
"key",
"==",
"key",
")",
".",
"filter",
"(",
"um",
".",
"Use... | Get the last_nonce used by the given key from the SQLAlchemy database.
Update the last_nonce to nonce at the same time.
:param str key: the public key the nonce belongs to
:param int nonce: the last nonce used by this key | [
"Get",
"the",
"last_nonce",
"used",
"by",
"the",
"given",
"key",
"from",
"the",
"SQLAlchemy",
"database",
".",
"Update",
"the",
"last_nonce",
"to",
"nonce",
"at",
"the",
"same",
"time",
"."
] | python | train | 33.090909 |
Azure/azure-sdk-for-python | azure-mgmt-eventhub/azure/mgmt/eventhub/event_hub_management_client.py | https://github.com/Azure/azure-sdk-for-python/blob/d7306fde32f60a293a7567678692bdad31e4b667/azure-mgmt-eventhub/azure/mgmt/eventhub/event_hub_management_client.py#L128-L138 | def clusters(self):
"""Instance depends on the API version:
* 2018-01-01-preview: :class:`ClustersOperations<azure.mgmt.eventhub.v2018_01_01_preview.operations.ClustersOperations>`
"""
api_version = self._get_api_version('clusters')
if api_version == '2018-01-01-preview':
... | [
"def",
"clusters",
"(",
"self",
")",
":",
"api_version",
"=",
"self",
".",
"_get_api_version",
"(",
"'clusters'",
")",
"if",
"api_version",
"==",
"'2018-01-01-preview'",
":",
"from",
".",
"v2018_01_01_preview",
".",
"operations",
"import",
"ClustersOperations",
"a... | Instance depends on the API version:
* 2018-01-01-preview: :class:`ClustersOperations<azure.mgmt.eventhub.v2018_01_01_preview.operations.ClustersOperations>` | [
"Instance",
"depends",
"on",
"the",
"API",
"version",
":"
] | python | test | 59.272727 |
saltstack/salt | salt/pillar/vault.py | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/pillar/vault.py#L142-L172 | def ext_pillar(minion_id, # pylint: disable=W0613
pillar, # pylint: disable=W0613
conf,
nesting_key=None):
'''
Get pillar data from Vault for the configuration ``conf``.
'''
comps = conf.split()
paths = [comp for comp in comps if comp.startswith('path=... | [
"def",
"ext_pillar",
"(",
"minion_id",
",",
"# pylint: disable=W0613",
"pillar",
",",
"# pylint: disable=W0613",
"conf",
",",
"nesting_key",
"=",
"None",
")",
":",
"comps",
"=",
"conf",
".",
"split",
"(",
")",
"paths",
"=",
"[",
"comp",
"for",
"comp",
"in",
... | Get pillar data from Vault for the configuration ``conf``. | [
"Get",
"pillar",
"data",
"from",
"Vault",
"for",
"the",
"configuration",
"conf",
"."
] | python | train | 31.387097 |
hsolbrig/PyShEx | pyshex/shape_expressions_language/p5_4_node_constraints.py | https://github.com/hsolbrig/PyShEx/blob/9d659cc36e808afd66d4a6d60e8ea21cb12eb744/pyshex/shape_expressions_language/p5_4_node_constraints.py#L200-L213 | def nodeSatisfiesValues(cntxt: Context, n: Node, nc: ShExJ.NodeConstraint, _c: DebugContext) -> bool:
""" `5.4.5 Values Constraint <http://shex.io/shex-semantics/#values>`_
For a node n and constraint value v, nodeSatisfies(n, v) if n matches some valueSetValue vsv in v.
"""
if nc.values is None:
... | [
"def",
"nodeSatisfiesValues",
"(",
"cntxt",
":",
"Context",
",",
"n",
":",
"Node",
",",
"nc",
":",
"ShExJ",
".",
"NodeConstraint",
",",
"_c",
":",
"DebugContext",
")",
"->",
"bool",
":",
"if",
"nc",
".",
"values",
"is",
"None",
":",
"return",
"True",
... | `5.4.5 Values Constraint <http://shex.io/shex-semantics/#values>`_
For a node n and constraint value v, nodeSatisfies(n, v) if n matches some valueSetValue vsv in v. | [
"5",
".",
"4",
".",
"5",
"Values",
"Constraint",
"<http",
":",
"//",
"shex",
".",
"io",
"/",
"shex",
"-",
"semantics",
"/",
"#values",
">",
"_"
] | python | train | 44.928571 |
peri-source/peri | peri/states.py | https://github.com/peri-source/peri/blob/61beed5deaaf978ab31ed716e8470d86ba639867/peri/states.py#L569-L594 | def set_image(self, image):
"""
Update the current comparison (real) image
"""
if isinstance(image, np.ndarray):
image = util.Image(image)
if isinstance(image, util.NullImage):
self.model_as_data = True
else:
self.model_as_data = False... | [
"def",
"set_image",
"(",
"self",
",",
"image",
")",
":",
"if",
"isinstance",
"(",
"image",
",",
"np",
".",
"ndarray",
")",
":",
"image",
"=",
"util",
".",
"Image",
"(",
"image",
")",
"if",
"isinstance",
"(",
"image",
",",
"util",
".",
"NullImage",
... | Update the current comparison (real) image | [
"Update",
"the",
"current",
"comparison",
"(",
"real",
")",
"image"
] | python | valid | 32.653846 |
stephanepechard/projy | projy/templates/DjangoProjectTemplate.py | https://github.com/stephanepechard/projy/blob/3146b0e3c207b977e1b51fcb33138746dae83c23/projy/templates/DjangoProjectTemplate.py#L23-L30 | def directories(self):
""" Return the names of directories to be created. """
directories_description = [
self.project_name,
self.project_name + '/conf',
self.project_name + '/static',
]
return directories_description | [
"def",
"directories",
"(",
"self",
")",
":",
"directories_description",
"=",
"[",
"self",
".",
"project_name",
",",
"self",
".",
"project_name",
"+",
"'/conf'",
",",
"self",
".",
"project_name",
"+",
"'/static'",
",",
"]",
"return",
"directories_description"
] | Return the names of directories to be created. | [
"Return",
"the",
"names",
"of",
"directories",
"to",
"be",
"created",
"."
] | python | train | 34.75 |
inveniosoftware/invenio-migrator | invenio_migrator/legacy/records.py | https://github.com/inveniosoftware/invenio-migrator/blob/6902c6968a39b747d15e32363f43b7dffe2622c2/invenio_migrator/legacy/records.py#L57-L85 | def _get_collection_restrictions(collection):
"""Get all restrictions for a given collection, users and fireroles."""
try:
from invenio.dbquery import run_sql
from invenio.access_control_firerole import compile_role_definition
except ImportError:
from invenio.modules.access.firerole ... | [
"def",
"_get_collection_restrictions",
"(",
"collection",
")",
":",
"try",
":",
"from",
"invenio",
".",
"dbquery",
"import",
"run_sql",
"from",
"invenio",
".",
"access_control_firerole",
"import",
"compile_role_definition",
"except",
"ImportError",
":",
"from",
"inven... | Get all restrictions for a given collection, users and fireroles. | [
"Get",
"all",
"restrictions",
"for",
"a",
"given",
"collection",
"users",
"and",
"fireroles",
"."
] | python | test | 36.965517 |
loli/medpy | medpy/filter/IntensityRangeStandardization.py | https://github.com/loli/medpy/blob/95216b9e22e7ce301f0edf953ee2a2f1b6c6aee5/medpy/filter/IntensityRangeStandardization.py#L497-L506 | def is_in_interval(n, l, r, border = 'included'):
"""
Checks whether a number is inside the interval l, r.
"""
if 'included' == border:
return (n >= l) and (n <= r)
elif 'excluded' == border:
return (n > l) and (n < r)
else:
raise Value... | [
"def",
"is_in_interval",
"(",
"n",
",",
"l",
",",
"r",
",",
"border",
"=",
"'included'",
")",
":",
"if",
"'included'",
"==",
"border",
":",
"return",
"(",
"n",
">=",
"l",
")",
"and",
"(",
"n",
"<=",
"r",
")",
"elif",
"'excluded'",
"==",
"border",
... | Checks whether a number is inside the interval l, r. | [
"Checks",
"whether",
"a",
"number",
"is",
"inside",
"the",
"interval",
"l",
"r",
"."
] | python | train | 37.1 |
Netflix-Skunkworks/swag-client | swag_client/backends/file.py | https://github.com/Netflix-Skunkworks/swag-client/blob/e43816a85c4f48011cf497a4eae14f9df71fee0f/swag_client/backends/file.py#L33-L42 | def save_file(data_file, data, dry_run=None):
"""Writes JSON data to data file."""
if dry_run:
return
with open(data_file, 'w', encoding='utf-8') as f:
if sys.version_info > (3, 0):
f.write(json.dumps(data))
else:
f.write(json.dumps(data).decode('utf-8')) | [
"def",
"save_file",
"(",
"data_file",
",",
"data",
",",
"dry_run",
"=",
"None",
")",
":",
"if",
"dry_run",
":",
"return",
"with",
"open",
"(",
"data_file",
",",
"'w'",
",",
"encoding",
"=",
"'utf-8'",
")",
"as",
"f",
":",
"if",
"sys",
".",
"version_i... | Writes JSON data to data file. | [
"Writes",
"JSON",
"data",
"to",
"data",
"file",
"."
] | python | train | 30.7 |
sigmaris/python-gssapi | gssapi/names.py | https://github.com/sigmaris/python-gssapi/blob/a8ca577b3ccf9d9fa48f16f4954a1eddd5896236/gssapi/names.py#L198-L225 | def export(self):
"""
Returns a representation of the Mechanism Name which is suitable for direct string
comparison against other exported Mechanism Names. Its form is defined in the GSSAPI
specification (RFC 2743). It can also be re-imported by constructing a :class:`Name` with
... | [
"def",
"export",
"(",
"self",
")",
":",
"minor_status",
"=",
"ffi",
".",
"new",
"(",
"'OM_uint32[1]'",
")",
"output_buffer",
"=",
"ffi",
".",
"new",
"(",
"'gss_buffer_desc[1]'",
")",
"retval",
"=",
"C",
".",
"gss_export_name",
"(",
"minor_status",
",",
"se... | Returns a representation of the Mechanism Name which is suitable for direct string
comparison against other exported Mechanism Names. Its form is defined in the GSSAPI
specification (RFC 2743). It can also be re-imported by constructing a :class:`Name` with
the `name_type` param set to :const:`g... | [
"Returns",
"a",
"representation",
"of",
"the",
"Mechanism",
"Name",
"which",
"is",
"suitable",
"for",
"direct",
"string",
"comparison",
"against",
"other",
"exported",
"Mechanism",
"Names",
".",
"Its",
"form",
"is",
"defined",
"in",
"the",
"GSSAPI",
"specificati... | python | test | 41.464286 |
Erotemic/utool | utool/Preferences.py | https://github.com/Erotemic/utool/blob/3b27e1f4e6e6fb23cd8744af7b7195b57d99e03a/utool/Preferences.py#L143-L147 | def toggle(self, key):
""" Toggles a boolean key """
val = self[key]
assert isinstance(val, bool), 'key[%r] = %r is not a bool' % (key, val)
self.pref_update(key, not val) | [
"def",
"toggle",
"(",
"self",
",",
"key",
")",
":",
"val",
"=",
"self",
"[",
"key",
"]",
"assert",
"isinstance",
"(",
"val",
",",
"bool",
")",
",",
"'key[%r] = %r is not a bool'",
"%",
"(",
"key",
",",
"val",
")",
"self",
".",
"pref_update",
"(",
"ke... | Toggles a boolean key | [
"Toggles",
"a",
"boolean",
"key"
] | python | train | 39.8 |
RRZE-HPC/kerncraft | kerncraft/kernel.py | https://github.com/RRZE-HPC/kerncraft/blob/c60baf8043e4da8d8d66da7575021c2f4c6c78af/kerncraft/kernel.py#L307-L322 | def access_to_sympy(self, var_name, access):
"""
Transform a (multidimensional) variable access to a flattend sympy expression.
Also works with flat array accesses.
"""
base_sizes = self.variables[var_name][1]
expr = sympy.Number(0)
for dimension, a in enumerat... | [
"def",
"access_to_sympy",
"(",
"self",
",",
"var_name",
",",
"access",
")",
":",
"base_sizes",
"=",
"self",
".",
"variables",
"[",
"var_name",
"]",
"[",
"1",
"]",
"expr",
"=",
"sympy",
".",
"Number",
"(",
"0",
")",
"for",
"dimension",
",",
"a",
"in",... | Transform a (multidimensional) variable access to a flattend sympy expression.
Also works with flat array accesses. | [
"Transform",
"a",
"(",
"multidimensional",
")",
"variable",
"access",
"to",
"a",
"flattend",
"sympy",
"expression",
"."
] | python | test | 28.625 |
pydata/xarray | xarray/core/dataset.py | https://github.com/pydata/xarray/blob/6d93a95d05bdbfc33fff24064f67d29dd891ab58/xarray/core/dataset.py#L2150-L2205 | def interp_like(self, other, method='linear', assume_sorted=False,
kwargs={}):
"""Interpolate this object onto the coordinates of another object,
filling the out of range values with NaN.
Parameters
----------
other : Dataset or DataArray
Object w... | [
"def",
"interp_like",
"(",
"self",
",",
"other",
",",
"method",
"=",
"'linear'",
",",
"assume_sorted",
"=",
"False",
",",
"kwargs",
"=",
"{",
"}",
")",
":",
"coords",
"=",
"alignment",
".",
"reindex_like_indexers",
"(",
"self",
",",
"other",
")",
"numeri... | Interpolate this object onto the coordinates of another object,
filling the out of range values with NaN.
Parameters
----------
other : Dataset or DataArray
Object with an 'indexes' attribute giving a mapping from dimension
names to an 1d array-like, which provid... | [
"Interpolate",
"this",
"object",
"onto",
"the",
"coordinates",
"of",
"another",
"object",
"filling",
"the",
"out",
"of",
"range",
"values",
"with",
"NaN",
"."
] | python | train | 37.928571 |
coleifer/peewee | playhouse/sqlite_ext.py | https://github.com/coleifer/peewee/blob/ea9403b01acb039adb3a2472186d795c796b77a0/playhouse/sqlite_ext.py#L615-L640 | def search_bm25(cls, term, weights=None, with_score=False,
score_alias='score', explicit_ordering=False):
"""Full-text search using selected `term`."""
if not weights:
rank = SQL('rank')
elif isinstance(weights, dict):
weight_args = []
for ... | [
"def",
"search_bm25",
"(",
"cls",
",",
"term",
",",
"weights",
"=",
"None",
",",
"with_score",
"=",
"False",
",",
"score_alias",
"=",
"'score'",
",",
"explicit_ordering",
"=",
"False",
")",
":",
"if",
"not",
"weights",
":",
"rank",
"=",
"SQL",
"(",
"'r... | Full-text search using selected `term`. | [
"Full",
"-",
"text",
"search",
"using",
"selected",
"term",
"."
] | python | train | 39.115385 |
saltstack/salt | salt/states/lxd_image.py | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/states/lxd_image.py#L52-L298 | def present(name,
source,
aliases=None,
public=None,
auto_update=None,
remote_addr=None,
cert=None,
key=None,
verify_cert=True):
'''
Ensure an image exists, copy it else from source
name :
An alias of th... | [
"def",
"present",
"(",
"name",
",",
"source",
",",
"aliases",
"=",
"None",
",",
"public",
"=",
"None",
",",
"auto_update",
"=",
"None",
",",
"remote_addr",
"=",
"None",
",",
"cert",
"=",
"None",
",",
"key",
"=",
"None",
",",
"verify_cert",
"=",
"True... | Ensure an image exists, copy it else from source
name :
An alias of the image, this is used to check if the image exists and
it will be added as alias to the image on copy/create.
source :
Source dict.
For an LXD to LXD copy:
.. code-block: yaml
source:
... | [
"Ensure",
"an",
"image",
"exists",
"copy",
"it",
"else",
"from",
"source"
] | python | train | 29.919028 |
mattsolo1/hmmerclust | hmmerclust/hmmerclust.py | https://github.com/mattsolo1/hmmerclust/blob/471596043a660097ed8b11430d42118a8fd25798/hmmerclust/hmmerclust.py#L209-L259 | def add_protein_to_organisms(self, orgprot_list):
'''
Protein factory method.
Iterates through a list of SearchIO hit objects, matches
the accession against SeqRecord features for each organism.
If there is a match, the new Protein object is created and
stored in the pr... | [
"def",
"add_protein_to_organisms",
"(",
"self",
",",
"orgprot_list",
")",
":",
"for",
"org",
"in",
"self",
".",
"organisms",
":",
"handle",
"=",
"open",
"(",
"org",
".",
"genome_path",
",",
"\"rU\"",
")",
"print",
"'adding proteins to organism'",
",",
"org",
... | Protein factory method.
Iterates through a list of SearchIO hit objects, matches
the accession against SeqRecord features for each organism.
If there is a match, the new Protein object is created and
stored in the protein list of that Organism.
Args
orgprot_list: a ... | [
"Protein",
"factory",
"method",
"."
] | python | train | 33 |
SeattleTestbed/seash | pyreadline/rlmain.py | https://github.com/SeattleTestbed/seash/blob/40f9d2285662ff8b61e0468b4196acee089b273b/pyreadline/rlmain.py#L254-L259 | def callback_handler_install(self, prompt, callback):
u'''bool readline_callback_handler_install ( string prompt, callback callback)
Initializes the readline callback interface and terminal, prints the prompt and returns immediately
'''
self.callback = callback
self.readline_setu... | [
"def",
"callback_handler_install",
"(",
"self",
",",
"prompt",
",",
"callback",
")",
":",
"self",
".",
"callback",
"=",
"callback",
"self",
".",
"readline_setup",
"(",
"prompt",
")"
] | u'''bool readline_callback_handler_install ( string prompt, callback callback)
Initializes the readline callback interface and terminal, prints the prompt and returns immediately | [
"u",
"bool",
"readline_callback_handler_install",
"(",
"string",
"prompt",
"callback",
"callback",
")",
"Initializes",
"the",
"readline",
"callback",
"interface",
"and",
"terminal",
"prints",
"the",
"prompt",
"and",
"returns",
"immediately"
] | python | train | 54 |
glue-viz/glue-vispy-viewers | glue_vispy_viewers/extern/vispy/gloo/gl/pyopengl2.py | https://github.com/glue-viz/glue-vispy-viewers/blob/54a4351d98c1f90dfb1a557d1b447c1f57470eea/glue_vispy_viewers/extern/vispy/gloo/gl/pyopengl2.py#L82-L88 | def _inject():
""" Copy functions from OpenGL.GL into _pyopengl namespace.
"""
NS = _pyopengl2.__dict__
for glname, ourname in _pyopengl2._functions_to_import:
func = _get_function_from_pyopengl(glname)
NS[ourname] = func | [
"def",
"_inject",
"(",
")",
":",
"NS",
"=",
"_pyopengl2",
".",
"__dict__",
"for",
"glname",
",",
"ourname",
"in",
"_pyopengl2",
".",
"_functions_to_import",
":",
"func",
"=",
"_get_function_from_pyopengl",
"(",
"glname",
")",
"NS",
"[",
"ourname",
"]",
"=",
... | Copy functions from OpenGL.GL into _pyopengl namespace. | [
"Copy",
"functions",
"from",
"OpenGL",
".",
"GL",
"into",
"_pyopengl",
"namespace",
"."
] | python | train | 35.285714 |
brocade/pynos | pynos/versions/ver_6/ver_6_0_1/yang/brocade_system_monitor_ext.py | https://github.com/brocade/pynos/blob/bd8a34e98f322de3fc06750827d8bbc3a0c00380/pynos/versions/ver_6/ver_6_0_1/yang/brocade_system_monitor_ext.py#L81-L93 | def show_system_monitor_output_switch_status_switch_state(self, **kwargs):
"""Auto Generated Code
"""
config = ET.Element("config")
show_system_monitor = ET.Element("show_system_monitor")
config = show_system_monitor
output = ET.SubElement(show_system_monitor, "output")
... | [
"def",
"show_system_monitor_output_switch_status_switch_state",
"(",
"self",
",",
"*",
"*",
"kwargs",
")",
":",
"config",
"=",
"ET",
".",
"Element",
"(",
"\"config\"",
")",
"show_system_monitor",
"=",
"ET",
".",
"Element",
"(",
"\"show_system_monitor\"",
")",
"con... | Auto Generated Code | [
"Auto",
"Generated",
"Code"
] | python | train | 44.846154 |
saltstack/salt | salt/modules/zabbix.py | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/zabbix.py#L2143-L2175 | def usermacro_updateglobal(globalmacroid, value, **kwargs):
'''
Update existing global usermacro.
:param globalmacroid: id of the host usermacro
:param value: new value of the host usermacro
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
... | [
"def",
"usermacro_updateglobal",
"(",
"globalmacroid",
",",
"value",
",",
"*",
"*",
"kwargs",
")",
":",
"conn_args",
"=",
"_login",
"(",
"*",
"*",
"kwargs",
")",
"ret",
"=",
"{",
"}",
"try",
":",
"if",
"conn_args",
":",
"params",
"=",
"{",
"}",
"meth... | Update existing global usermacro.
:param globalmacroid: id of the host usermacro
:param value: new value of the host usermacro
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be... | [
"Update",
"existing",
"global",
"usermacro",
"."
] | python | train | 36.575758 |
minhhoit/yacms | yacms/boot/__init__.py | https://github.com/minhhoit/yacms/blob/2921b706b7107c6e8c5f2bbf790ff11f85a2167f/yacms/boot/__init__.py#L55-L74 | def parse_extra_model_fields(extra_model_fields):
"""
Parses the value of EXTRA_MODEL_FIELDS, grouping the entries by model
and instantiating the extra fields. Returns a sequence of tuples of
the form (model_key, fields) where model_key is a pair of app_label,
model_name and fields is a list of (fie... | [
"def",
"parse_extra_model_fields",
"(",
"extra_model_fields",
")",
":",
"fields",
"=",
"defaultdict",
"(",
"list",
")",
"for",
"entry",
"in",
"extra_model_fields",
":",
"model_key",
",",
"field_name",
"=",
"parse_field_path",
"(",
"entry",
"[",
"0",
"]",
")",
... | Parses the value of EXTRA_MODEL_FIELDS, grouping the entries by model
and instantiating the extra fields. Returns a sequence of tuples of
the form (model_key, fields) where model_key is a pair of app_label,
model_name and fields is a list of (field_name, field_instance) pairs. | [
"Parses",
"the",
"value",
"of",
"EXTRA_MODEL_FIELDS",
"grouping",
"the",
"entries",
"by",
"model",
"and",
"instantiating",
"the",
"extra",
"fields",
".",
"Returns",
"a",
"sequence",
"of",
"tuples",
"of",
"the",
"form",
"(",
"model_key",
"fields",
")",
"where",... | python | train | 46.4 |
glitchassassin/lackey | lackey/RegionMatching.py | https://github.com/glitchassassin/lackey/blob/7adadfacd7f45d81186710be992f5668b15399fe/lackey/RegionMatching.py#L331-L343 | def offset(self, location, dy=0):
""" Returns a new ``Region`` offset from this one by ``location``
Width and height remain the same
"""
if not isinstance(location, Location):
# Assume variables passed were dx,dy
location = Location(location, dy)
r = Regi... | [
"def",
"offset",
"(",
"self",
",",
"location",
",",
"dy",
"=",
"0",
")",
":",
"if",
"not",
"isinstance",
"(",
"location",
",",
"Location",
")",
":",
"# Assume variables passed were dx,dy",
"location",
"=",
"Location",
"(",
"location",
",",
"dy",
")",
"r",
... | Returns a new ``Region`` offset from this one by ``location``
Width and height remain the same | [
"Returns",
"a",
"new",
"Region",
"offset",
"from",
"this",
"one",
"by",
"location"
] | python | train | 40.461538 |
sangoma/pysensu | pysensu/api.py | https://github.com/sangoma/pysensu/blob/dc6799edbf2635247aec61fcf45b04ddec1beb49/pysensu/api.py#L165-L174 | def post_check_request(self, check, subscribers):
"""
Issues a check execution request.
"""
data = {
'check': check,
'subscribers': [subscribers]
}
self._request('POST', '/request', data=json.dumps(data))
return True | [
"def",
"post_check_request",
"(",
"self",
",",
"check",
",",
"subscribers",
")",
":",
"data",
"=",
"{",
"'check'",
":",
"check",
",",
"'subscribers'",
":",
"[",
"subscribers",
"]",
"}",
"self",
".",
"_request",
"(",
"'POST'",
",",
"'/request'",
",",
"dat... | Issues a check execution request. | [
"Issues",
"a",
"check",
"execution",
"request",
"."
] | python | train | 28.7 |
rossant/ipymd | ipymd/formats/python.py | https://github.com/rossant/ipymd/blob/d87c9ebc59d67fe78b0139ee00e0e5307682e303/ipymd/formats/python.py#L122-L126 | def _add_hash(source):
"""Add a leading hash '#' at the beginning of every line in the source."""
source = '\n'.join('# ' + line.rstrip()
for line in source.splitlines())
return source | [
"def",
"_add_hash",
"(",
"source",
")",
":",
"source",
"=",
"'\\n'",
".",
"join",
"(",
"'# '",
"+",
"line",
".",
"rstrip",
"(",
")",
"for",
"line",
"in",
"source",
".",
"splitlines",
"(",
")",
")",
"return",
"source"
] | Add a leading hash '#' at the beginning of every line in the source. | [
"Add",
"a",
"leading",
"hash",
"#",
"at",
"the",
"beginning",
"of",
"every",
"line",
"in",
"the",
"source",
"."
] | python | train | 43 |
proycon/pynlpl | pynlpl/formats/folia.py | https://github.com/proycon/pynlpl/blob/7707f69a91caaa6cde037f0d0379f1d42500a68b/pynlpl/formats/folia.py#L5051-L5070 | def text(self, cls = 'current', retaintokenisation=False, previousdelimiter="",strict=False, correctionhandling=CorrectionHandling.CURRENT, normalize_spaces=False):
"""See :meth:`AbstractElement.text`"""
if cls == 'original': correctionhandling = CorrectionHandling.ORIGINAL #backward compatibility
... | [
"def",
"text",
"(",
"self",
",",
"cls",
"=",
"'current'",
",",
"retaintokenisation",
"=",
"False",
",",
"previousdelimiter",
"=",
"\"\"",
",",
"strict",
"=",
"False",
",",
"correctionhandling",
"=",
"CorrectionHandling",
".",
"CURRENT",
",",
"normalize_spaces",
... | See :meth:`AbstractElement.text` | [
"See",
":",
"meth",
":",
"AbstractElement",
".",
"text"
] | python | train | 58.55 |
saltstack/salt | salt/states/neutron_secgroup_rule.py | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/states/neutron_secgroup_rule.py#L44-L53 | def _rule_compare(rule1, rule2):
'''
Compare the common keys between security group rules against eachother
'''
commonkeys = set(rule1.keys()).intersection(rule2.keys())
for key in commonkeys:
if rule1[key] != rule2[key]:
return False
return True | [
"def",
"_rule_compare",
"(",
"rule1",
",",
"rule2",
")",
":",
"commonkeys",
"=",
"set",
"(",
"rule1",
".",
"keys",
"(",
")",
")",
".",
"intersection",
"(",
"rule2",
".",
"keys",
"(",
")",
")",
"for",
"key",
"in",
"commonkeys",
":",
"if",
"rule1",
"... | Compare the common keys between security group rules against eachother | [
"Compare",
"the",
"common",
"keys",
"between",
"security",
"group",
"rules",
"against",
"eachother"
] | python | train | 28.2 |
sentinel-hub/eo-learn | core/eolearn/core/eoworkflow.py | https://github.com/sentinel-hub/eo-learn/blob/b8c390b9f553c561612fe9eb64e720611633a035/core/eolearn/core/eoworkflow.py#L264-L275 | def get_tasks(self):
"""Returns an ordered dictionary {task_name: task} of all tasks within this workflow.
:return: Ordered dictionary with key being task_name (str) and an instance of a corresponding task from this
workflow
:rtype: OrderedDict
"""
tasks = collect... | [
"def",
"get_tasks",
"(",
"self",
")",
":",
"tasks",
"=",
"collections",
".",
"OrderedDict",
"(",
")",
"for",
"dep",
"in",
"self",
".",
"ordered_dependencies",
":",
"tasks",
"[",
"dep",
".",
"name",
"]",
"=",
"dep",
".",
"task",
"return",
"tasks"
] | Returns an ordered dictionary {task_name: task} of all tasks within this workflow.
:return: Ordered dictionary with key being task_name (str) and an instance of a corresponding task from this
workflow
:rtype: OrderedDict | [
"Returns",
"an",
"ordered",
"dictionary",
"{",
"task_name",
":",
"task",
"}",
"of",
"all",
"tasks",
"within",
"this",
"workflow",
".",
":",
"return",
":",
"Ordered",
"dictionary",
"with",
"key",
"being",
"task_name",
"(",
"str",
")",
"and",
"an",
"instance... | python | train | 36.5 |
rabitt/pysox | sox/transform.py | https://github.com/rabitt/pysox/blob/eae89bde74567136ec3f723c3e6b369916d9b837/sox/transform.py#L1662-L1699 | def loudness(self, gain_db=-10.0, reference_level=65.0):
'''Loudness control. Similar to the gain effect, but provides
equalisation for the human auditory system.
The gain is adjusted by gain_db and the signal is equalised according
to ISO 226 w.r.t. reference_level.
Parameters... | [
"def",
"loudness",
"(",
"self",
",",
"gain_db",
"=",
"-",
"10.0",
",",
"reference_level",
"=",
"65.0",
")",
":",
"if",
"not",
"is_number",
"(",
"gain_db",
")",
":",
"raise",
"ValueError",
"(",
"'gain_db must be a number.'",
")",
"if",
"not",
"is_number",
"... | Loudness control. Similar to the gain effect, but provides
equalisation for the human auditory system.
The gain is adjusted by gain_db and the signal is equalised according
to ISO 226 w.r.t. reference_level.
Parameters
----------
gain_db : float, default=-10.0
... | [
"Loudness",
"control",
".",
"Similar",
"to",
"the",
"gain",
"effect",
"but",
"provides",
"equalisation",
"for",
"the",
"human",
"auditory",
"system",
"."
] | python | valid | 31.473684 |
timgabets/bpc8583 | bpc8583/transaction.py | https://github.com/timgabets/bpc8583/blob/1b8e95d73ad273ad9d11bff40d1af3f06f0f3503/bpc8583/transaction.py#L244-L253 | def set_amount(self, amount):
"""
Set transaction amount
"""
if amount:
try:
self.IsoMessage.FieldData(4, int(amount))
except ValueError:
self.IsoMessage.FieldData(4, 0)
self.rebuild() | [
"def",
"set_amount",
"(",
"self",
",",
"amount",
")",
":",
"if",
"amount",
":",
"try",
":",
"self",
".",
"IsoMessage",
".",
"FieldData",
"(",
"4",
",",
"int",
"(",
"amount",
")",
")",
"except",
"ValueError",
":",
"self",
".",
"IsoMessage",
".",
"Fiel... | Set transaction amount | [
"Set",
"transaction",
"amount"
] | python | train | 27.5 |
raiden-network/raiden | raiden/transfer/merkle_tree.py | https://github.com/raiden-network/raiden/blob/407ba15c72074e9de88771d6b9661ff4dc36bef5/raiden/transfer/merkle_tree.py#L16-L33 | def hash_pair(first: Keccak256, second: Optional[Keccak256]) -> Keccak256:
""" Computes the keccak hash of the elements ordered topologically.
Since a merkle proof will not include all the elements, but only the path
starting from the leaves up to the root, the order of the elements is not
known by the... | [
"def",
"hash_pair",
"(",
"first",
":",
"Keccak256",
",",
"second",
":",
"Optional",
"[",
"Keccak256",
"]",
")",
"->",
"Keccak256",
":",
"assert",
"first",
"is",
"not",
"None",
"if",
"second",
"is",
"None",
":",
"return",
"first",
"if",
"first",
">",
"s... | Computes the keccak hash of the elements ordered topologically.
Since a merkle proof will not include all the elements, but only the path
starting from the leaves up to the root, the order of the elements is not
known by the proof checker. The topological order is used as a
deterministic way of orderin... | [
"Computes",
"the",
"keccak",
"hash",
"of",
"the",
"elements",
"ordered",
"topologically",
"."
] | python | train | 36.611111 |
apple/turicreate | src/external/coremltools_wrap/coremltools/coremltools/converters/keras/_layers.py | https://github.com/apple/turicreate/blob/74514c3f99e25b46f22c6e02977fe3da69221c2e/src/external/coremltools_wrap/coremltools/coremltools/converters/keras/_layers.py#L651-L705 | def convert_gru(builder, layer, input_names, output_names, keras_layer):
"""Convert a GRU layer from keras to coreml.
Parameters
----------
keras_layer: layer
A keras layer object.
builder: NeuralNetworkBuilder
A neural network builder object.
"""
hidden_size = keras_layer... | [
"def",
"convert_gru",
"(",
"builder",
",",
"layer",
",",
"input_names",
",",
"output_names",
",",
"keras_layer",
")",
":",
"hidden_size",
"=",
"keras_layer",
".",
"output_dim",
"input_size",
"=",
"keras_layer",
".",
"input_shape",
"[",
"-",
"1",
"]",
"output_a... | Convert a GRU layer from keras to coreml.
Parameters
----------
keras_layer: layer
A keras layer object.
builder: NeuralNetworkBuilder
A neural network builder object. | [
"Convert",
"a",
"GRU",
"layer",
"from",
"keras",
"to",
"coreml",
"."
] | python | train | 32.690909 |
BlueBrain/NeuroM | neurom/fst/_bifurcationfunc.py | https://github.com/BlueBrain/NeuroM/blob/254bb73535b20053d175bc4725bade662177d12b/neurom/fst/_bifurcationfunc.py#L80-L91 | def bifurcation_partition(bif_point):
'''Calculate the partition at a bifurcation point
We first ensure that the input point has only two children.
The number of nodes in each child tree is counted. The partition is
defined as the ratio of the largest number to the smallest number.'''
assert len(b... | [
"def",
"bifurcation_partition",
"(",
"bif_point",
")",
":",
"assert",
"len",
"(",
"bif_point",
".",
"children",
")",
"==",
"2",
",",
"'A bifurcation point must have exactly 2 children'",
"n",
"=",
"float",
"(",
"sum",
"(",
"1",
"for",
"_",
"in",
"bif_point",
"... | Calculate the partition at a bifurcation point
We first ensure that the input point has only two children.
The number of nodes in each child tree is counted. The partition is
defined as the ratio of the largest number to the smallest number. | [
"Calculate",
"the",
"partition",
"at",
"a",
"bifurcation",
"point"
] | python | train | 45.666667 |
django-cumulus/django-cumulus | cumulus/management/commands/syncfiles.py | https://github.com/django-cumulus/django-cumulus/blob/64feb07b857af28f226be4899e875c29405e261d/cumulus/management/commands/syncfiles.py#L258-L266 | def print_tally(self):
"""
Prints the final tally to stdout.
"""
self.update_count = self.upload_count - self.create_count
if self.test_run:
print("Test run complete with the following results:")
print("Skipped {0}. Created {1}. Updated {2}. Deleted {3}.".form... | [
"def",
"print_tally",
"(",
"self",
")",
":",
"self",
".",
"update_count",
"=",
"self",
".",
"upload_count",
"-",
"self",
".",
"create_count",
"if",
"self",
".",
"test_run",
":",
"print",
"(",
"\"Test run complete with the following results:\"",
")",
"print",
"("... | Prints the final tally to stdout. | [
"Prints",
"the",
"final",
"tally",
"to",
"stdout",
"."
] | python | train | 44.666667 |
hazelcast/hazelcast-python-client | hazelcast/proxy/replicated_map.py | https://github.com/hazelcast/hazelcast-python-client/blob/3f6639443c23d6d036aa343f8e094f052250d2c1/hazelcast/proxy/replicated_map.py#L99-L107 | def contains_value(self, value):
"""
Determines whether this map contains one or more keys for the specified value.
:param value: (object), the specified value.
:return: (bool), ``true`` if this map contains an entry for the specified value.
"""
check_not_none(value, "va... | [
"def",
"contains_value",
"(",
"self",
",",
"value",
")",
":",
"check_not_none",
"(",
"value",
",",
"\"value can't be None\"",
")",
"return",
"self",
".",
"_encode_invoke_on_target_partition",
"(",
"replicated_map_contains_value_codec",
",",
"value",
"=",
"self",
".",
... | Determines whether this map contains one or more keys for the specified value.
:param value: (object), the specified value.
:return: (bool), ``true`` if this map contains an entry for the specified value. | [
"Determines",
"whether",
"this",
"map",
"contains",
"one",
"or",
"more",
"keys",
"for",
"the",
"specified",
"value",
"."
] | python | train | 50.111111 |
jtwhite79/pyemu | pyemu/utils/geostats.py | https://github.com/jtwhite79/pyemu/blob/c504d8e7a4097cec07655a6318d275739bd8148a/pyemu/utils/geostats.py#L1509-L1527 | def _h_function(self,h):
""" private method for the spherical variogram "h" function
Parameters
----------
h : (float or numpy.ndarray)
distance(s)
Returns
-------
h_function : float or numpy.ndarray
the value of the "h" function implied ... | [
"def",
"_h_function",
"(",
"self",
",",
"h",
")",
":",
"hh",
"=",
"h",
"/",
"self",
".",
"a",
"h",
"=",
"self",
".",
"contribution",
"*",
"(",
"1.0",
"-",
"(",
"hh",
"*",
"(",
"1.5",
"-",
"(",
"0.5",
"*",
"hh",
"*",
"hh",
")",
")",
")",
"... | private method for the spherical variogram "h" function
Parameters
----------
h : (float or numpy.ndarray)
distance(s)
Returns
-------
h_function : float or numpy.ndarray
the value of the "h" function implied by the SphVario | [
"private",
"method",
"for",
"the",
"spherical",
"variogram",
"h",
"function"
] | python | train | 24.684211 |
kensho-technologies/graphql-compiler | graphql_compiler/compiler/expressions.py | https://github.com/kensho-technologies/graphql-compiler/blob/f6079c6d10f64932f6b3af309b79bcea2123ca8f/graphql_compiler/compiler/expressions.py#L769-L779 | def validate(self):
"""Validate that the BinaryComposition is correctly representable."""
_validate_operator_name(self.operator, BinaryComposition.SUPPORTED_OPERATORS)
if not isinstance(self.left, Expression):
raise TypeError(u'Expected Expression left, got: {} {} {}'.format(
... | [
"def",
"validate",
"(",
"self",
")",
":",
"_validate_operator_name",
"(",
"self",
".",
"operator",
",",
"BinaryComposition",
".",
"SUPPORTED_OPERATORS",
")",
"if",
"not",
"isinstance",
"(",
"self",
".",
"left",
",",
"Expression",
")",
":",
"raise",
"TypeError"... | Validate that the BinaryComposition is correctly representable. | [
"Validate",
"that",
"the",
"BinaryComposition",
"is",
"correctly",
"representable",
"."
] | python | train | 49.818182 |
Synerty/peek-plugin-base | peek_plugin_base/storage/StorageUtil.py | https://github.com/Synerty/peek-plugin-base/blob/276101d028e1ee0678af514c761b74cce5a5cda9/peek_plugin_base/storage/StorageUtil.py#L46-L62 | def makeCoreValuesSubqueryCondition(engine, column, values: List[Union[int, str]]):
""" Make Core Values Subquery
:param engine: The database engine, used to determine the dialect
:param column: The column, eg TableItem.__table__.c.colName
:param values: A list of string or int values
"""
if i... | [
"def",
"makeCoreValuesSubqueryCondition",
"(",
"engine",
",",
"column",
",",
"values",
":",
"List",
"[",
"Union",
"[",
"int",
",",
"str",
"]",
"]",
")",
":",
"if",
"isPostGreSQLDialect",
"(",
"engine",
")",
":",
"return",
"column",
".",
"in_",
"(",
"valu... | Make Core Values Subquery
:param engine: The database engine, used to determine the dialect
:param column: The column, eg TableItem.__table__.c.colName
:param values: A list of string or int values | [
"Make",
"Core",
"Values",
"Subquery"
] | python | train | 29.647059 |
bennylope/django-organizations | organizations/utils.py | https://github.com/bennylope/django-organizations/blob/85f753a8f7a8f0f31636c9209fb69e7030a5c79a/organizations/utils.py#L115-L120 | def model_field_attr(model, model_field, attr):
"""
Returns the specified attribute for the specified field on the model class.
"""
fields = dict([(field.name, field) for field in model._meta.fields])
return getattr(fields[model_field], attr) | [
"def",
"model_field_attr",
"(",
"model",
",",
"model_field",
",",
"attr",
")",
":",
"fields",
"=",
"dict",
"(",
"[",
"(",
"field",
".",
"name",
",",
"field",
")",
"for",
"field",
"in",
"model",
".",
"_meta",
".",
"fields",
"]",
")",
"return",
"getatt... | Returns the specified attribute for the specified field on the model class. | [
"Returns",
"the",
"specified",
"attribute",
"for",
"the",
"specified",
"field",
"on",
"the",
"model",
"class",
"."
] | python | train | 42.833333 |
Karaage-Cluster/python-tldap | tldap/database/helpers.py | https://github.com/Karaage-Cluster/python-tldap/blob/61f1af74a3648cb6491e7eeb1ee2eb395d67bf59/tldap/database/helpers.py#L38-L66 | def rdn_to_dn(changes: Changeset, name: str, base_dn: str) -> Changeset:
""" Convert the rdn to a fully qualified DN for the specified LDAP
connection.
:param changes: The changes object to lookup.
:param name: rdn to convert.
:param base_dn: The base_dn to lookup.
:return: fully qualified DN.
... | [
"def",
"rdn_to_dn",
"(",
"changes",
":",
"Changeset",
",",
"name",
":",
"str",
",",
"base_dn",
":",
"str",
")",
"->",
"Changeset",
":",
"dn",
"=",
"changes",
".",
"get_value_as_single",
"(",
"'dn'",
")",
"if",
"dn",
"is",
"not",
"None",
":",
"return",
... | Convert the rdn to a fully qualified DN for the specified LDAP
connection.
:param changes: The changes object to lookup.
:param name: rdn to convert.
:param base_dn: The base_dn to lookup.
:return: fully qualified DN. | [
"Convert",
"the",
"rdn",
"to",
"a",
"fully",
"qualified",
"DN",
"for",
"the",
"specified",
"LDAP",
"connection",
"."
] | python | train | 30.724138 |
mwouts/jupytext | jupytext/cell_to_text.py | https://github.com/mwouts/jupytext/blob/eb7d6aee889f80ad779cfc53441c648f0db9246d/jupytext/cell_to_text.py#L277-L300 | def remove_eoc_marker(self, text, next_text):
"""Remove end of cell marker when next cell has an explicit start marker"""
if self.cell_marker_start:
return text
if self.is_code() and text[-1] == self.comment + ' -':
# remove end of cell marker when redundant with next ex... | [
"def",
"remove_eoc_marker",
"(",
"self",
",",
"text",
",",
"next_text",
")",
":",
"if",
"self",
".",
"cell_marker_start",
":",
"return",
"text",
"if",
"self",
".",
"is_code",
"(",
")",
"and",
"text",
"[",
"-",
"1",
"]",
"==",
"self",
".",
"comment",
... | Remove end of cell marker when next cell has an explicit start marker | [
"Remove",
"end",
"of",
"cell",
"marker",
"when",
"next",
"cell",
"has",
"an",
"explicit",
"start",
"marker"
] | python | train | 58 |
google/grr | grr/core/grr_response_core/lib/parsers/linux_service_parser.py | https://github.com/google/grr/blob/5cef4e8e2f0d5df43ea4877e9c798e0bf60bfe74/grr/core/grr_response_core/lib/parsers/linux_service_parser.py#L77-L85 | def _LogInvalidRunLevels(states, valid):
"""Log any invalid run states found."""
invalid = set()
for state in states:
if state not in valid:
invalid.add(state)
if invalid:
logging.warning("Invalid init runlevel(s) encountered: %s",
", ".join(invalid)) | [
"def",
"_LogInvalidRunLevels",
"(",
"states",
",",
"valid",
")",
":",
"invalid",
"=",
"set",
"(",
")",
"for",
"state",
"in",
"states",
":",
"if",
"state",
"not",
"in",
"valid",
":",
"invalid",
".",
"add",
"(",
"state",
")",
"if",
"invalid",
":",
"log... | Log any invalid run states found. | [
"Log",
"any",
"invalid",
"run",
"states",
"found",
"."
] | python | train | 31.666667 |
tdryer/hangups | docs/generate_proto_docs.py | https://github.com/tdryer/hangups/blob/85c0bf0a57698d077461283895707260f9dbf931/docs/generate_proto_docs.py#L202-L229 | def main():
"""Parse arguments and print generated documentation to stdout."""
parser = argparse.ArgumentParser()
parser.add_argument('protofilepath')
args = parser.parse_args()
out_file = compile_protofile(args.protofilepath)
with open(out_file, 'rb') as proto_file:
# pylint: disable=n... | [
"def",
"main",
"(",
")",
":",
"parser",
"=",
"argparse",
".",
"ArgumentParser",
"(",
")",
"parser",
".",
"add_argument",
"(",
"'protofilepath'",
")",
"args",
"=",
"parser",
".",
"parse_args",
"(",
")",
"out_file",
"=",
"compile_protofile",
"(",
"args",
"."... | Parse arguments and print generated documentation to stdout. | [
"Parse",
"arguments",
"and",
"print",
"generated",
"documentation",
"to",
"stdout",
"."
] | python | valid | 43.892857 |
openearth/mmi-python | mmi/runner.py | https://github.com/openearth/mmi-python/blob/a2f4ac96b1e7f2fa903f668b3e05c4e86ad42e8d/mmi/runner.py#L123-L146 | def create_bmi_model(self, engine, bmi_class=None, wrapper_kwargs=None):
"""initialize a bmi mode using an optional class"""
if wrapper_kwargs is None:
wrapper_kwargs = {}
if bmi_class is None:
wrapper_class = bmi.wrapper.BMIWrapper
else:
wrapper_class... | [
"def",
"create_bmi_model",
"(",
"self",
",",
"engine",
",",
"bmi_class",
"=",
"None",
",",
"wrapper_kwargs",
"=",
"None",
")",
":",
"if",
"wrapper_kwargs",
"is",
"None",
":",
"wrapper_kwargs",
"=",
"{",
"}",
"if",
"bmi_class",
"is",
"None",
":",
"wrapper_c... | initialize a bmi mode using an optional class | [
"initialize",
"a",
"bmi",
"mode",
"using",
"an",
"optional",
"class"
] | python | train | 36.75 |
Julian/jsonschema | jsonschema/validators.py | https://github.com/Julian/jsonschema/blob/a72332004cdc3ba456de7918bc32059822b2f69a/jsonschema/validators.py#L154-L364 | def create(
meta_schema,
validators=(),
version=None,
default_types=None,
type_checker=None,
id_of=_id_of,
):
"""
Create a new validator class.
Arguments:
meta_schema (collections.Mapping):
the meta schema for the new validator class
validators (collec... | [
"def",
"create",
"(",
"meta_schema",
",",
"validators",
"=",
"(",
")",
",",
"version",
"=",
"None",
",",
"default_types",
"=",
"None",
",",
"type_checker",
"=",
"None",
",",
"id_of",
"=",
"_id_of",
",",
")",
":",
"if",
"default_types",
"is",
"not",
"No... | Create a new validator class.
Arguments:
meta_schema (collections.Mapping):
the meta schema for the new validator class
validators (collections.Mapping):
a mapping from names to callables, where each callable will
validate the schema property with the given n... | [
"Create",
"a",
"new",
"validator",
"class",
"."
] | python | train | 32.398104 |
maas/python-libmaas | maas/client/flesh/__init__.py | https://github.com/maas/python-libmaas/blob/4092c68ef7fb1753efc843569848e2bcc3415002/maas/client/flesh/__init__.py#L409-L437 | def print_all_commands(self, *, no_pager=False):
"""Print help for all commands.
Commands are sorted in alphabetical order and wrapping is done
based on the width of the terminal.
"""
formatter = self.parent_parser._get_formatter()
command_names = sorted(self.parent_pars... | [
"def",
"print_all_commands",
"(",
"self",
",",
"*",
",",
"no_pager",
"=",
"False",
")",
":",
"formatter",
"=",
"self",
".",
"parent_parser",
".",
"_get_formatter",
"(",
")",
"command_names",
"=",
"sorted",
"(",
"self",
".",
"parent_parser",
".",
"subparsers"... | Print help for all commands.
Commands are sorted in alphabetical order and wrapping is done
based on the width of the terminal. | [
"Print",
"help",
"for",
"all",
"commands",
"."
] | python | train | 43.068966 |
hyperledger/indy-sdk | wrappers/python/indy/anoncreds.py | https://github.com/hyperledger/indy-sdk/blob/55240dc170308d7883c48f03f308130a6d077be6/wrappers/python/indy/anoncreds.py#L252-L332 | async def issuer_create_credential(wallet_handle: int,
cred_offer_json: str,
cred_req_json: str,
cred_values_json: str,
rev_reg_id: Optional[str],
... | [
"async",
"def",
"issuer_create_credential",
"(",
"wallet_handle",
":",
"int",
",",
"cred_offer_json",
":",
"str",
",",
"cred_req_json",
":",
"str",
",",
"cred_values_json",
":",
"str",
",",
"rev_reg_id",
":",
"Optional",
"[",
"str",
"]",
",",
"blob_storage_reade... | Check Cred Request for the given Cred Offer and issue Credential for the given Cred Request.
Cred Request must match Cred Offer. The credential definition and revocation registry definition
referenced in Cred Offer and Cred Request must be already created and stored into the wallet.
Information for this c... | [
"Check",
"Cred",
"Request",
"for",
"the",
"given",
"Cred",
"Offer",
"and",
"issue",
"Credential",
"for",
"the",
"given",
"Cred",
"Request",
"."
] | python | train | 55.469136 |
data61/clkhash | clkhash/clk.py | https://github.com/data61/clkhash/blob/ec6398d6708a063de83f7c3d6286587bff8e7121/clkhash/clk.py#L179-L186 | def chunks(seq, chunk_size):
# type: (Sequence[T], int) -> Iterable[Sequence[T]]
""" Split seq into chunk_size-sized chunks.
:param seq: A sequence to chunk.
:param chunk_size: The size of chunk.
"""
return (seq[i:i + chunk_size] for i in range(0, len(seq), chunk_size)) | [
"def",
"chunks",
"(",
"seq",
",",
"chunk_size",
")",
":",
"# type: (Sequence[T], int) -> Iterable[Sequence[T]]",
"return",
"(",
"seq",
"[",
"i",
":",
"i",
"+",
"chunk_size",
"]",
"for",
"i",
"in",
"range",
"(",
"0",
",",
"len",
"(",
"seq",
")",
",",
"chu... | Split seq into chunk_size-sized chunks.
:param seq: A sequence to chunk.
:param chunk_size: The size of chunk. | [
"Split",
"seq",
"into",
"chunk_size",
"-",
"sized",
"chunks",
"."
] | python | train | 37 |
JoshAshby/pyRethinkORM | rethinkORM/rethinkCollection.py | https://github.com/JoshAshby/pyRethinkORM/blob/92158d146dea6cfe9022d7de2537403f5f2c1e02/rethinkORM/rethinkCollection.py#L84-L92 | def offset(self, value):
"""
Allows for skipping a specified number of results in query. Useful
for pagination.
"""
self._query = self._query.skip(value)
return self | [
"def",
"offset",
"(",
"self",
",",
"value",
")",
":",
"self",
".",
"_query",
"=",
"self",
".",
"_query",
".",
"skip",
"(",
"value",
")",
"return",
"self"
] | Allows for skipping a specified number of results in query. Useful
for pagination. | [
"Allows",
"for",
"skipping",
"a",
"specified",
"number",
"of",
"results",
"in",
"query",
".",
"Useful",
"for",
"pagination",
"."
] | python | train | 23 |
Opentrons/opentrons | update-server/otupdate/buildroot/update.py | https://github.com/Opentrons/opentrons/blob/a7c15cc2636ecb64ab56c7edc1d8a57163aaeadf/update-server/otupdate/buildroot/update.py#L86-L104 | def _begin_write(session: UpdateSession,
loop: asyncio.AbstractEventLoop,
rootfs_file_path: str):
""" Start the write process. """
session.set_progress(0)
session.set_stage(Stages.WRITING)
write_future = asyncio.ensure_future(loop.run_in_executor(
None, file_act... | [
"def",
"_begin_write",
"(",
"session",
":",
"UpdateSession",
",",
"loop",
":",
"asyncio",
".",
"AbstractEventLoop",
",",
"rootfs_file_path",
":",
"str",
")",
":",
"session",
".",
"set_progress",
"(",
"0",
")",
"session",
".",
"set_stage",
"(",
"Stages",
".",... | Start the write process. | [
"Start",
"the",
"write",
"process",
"."
] | python | train | 34.473684 |
maximkulkin/lollipop | lollipop/types.py | https://github.com/maximkulkin/lollipop/blob/042e8a24508cc3b28630863253c38ffbfc52c882/lollipop/types.py#L1450-L1532 | def load_into(self, obj, data, inplace=True, *args, **kwargs):
"""Load data and update existing object.
:param obj: Object to update with deserialized data.
:param data: Raw data to get value to deserialize from.
:param bool inplace: If True update data inplace;
otherwise - ... | [
"def",
"load_into",
"(",
"self",
",",
"obj",
",",
"data",
",",
"inplace",
"=",
"True",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"if",
"obj",
"is",
"None",
":",
"raise",
"ValueError",
"(",
"'Load target should not be None'",
")",
"if",
"data... | Load data and update existing object.
:param obj: Object to update with deserialized data.
:param data: Raw data to get value to deserialize from.
:param bool inplace: If True update data inplace;
otherwise - create new data.
:param kwargs: Same keyword arguments as for :met... | [
"Load",
"data",
"and",
"update",
"existing",
"object",
"."
] | python | train | 37.036145 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.