repo stringlengths 7 54 | path stringlengths 4 192 | url stringlengths 87 284 | code stringlengths 78 104k | code_tokens list | docstring stringlengths 1 46.9k | docstring_tokens list | language stringclasses 1
value | partition stringclasses 3
values |
|---|---|---|---|---|---|---|---|---|
gofed/gofedlib | gofedlib/distribution/packagenamegenerator.py | https://github.com/gofed/gofedlib/blob/0674c248fe3d8706f98f912996b65af469f96b10/gofedlib/distribution/packagenamegenerator.py#L9-L59 | def generate(self, project):
"""
Package name construction is based on provider, not on prefix.
Prefix does not have to equal provider_prefix.
"""
for assignment in self.s2n_mapping:
if assignment["ipprefix"] == project:
self._name = assignment["package"]
return self
#
# github.com -> github
... | [
"def",
"generate",
"(",
"self",
",",
"project",
")",
":",
"for",
"assignment",
"in",
"self",
".",
"s2n_mapping",
":",
"if",
"assignment",
"[",
"\"ipprefix\"",
"]",
"==",
"project",
":",
"self",
".",
"_name",
"=",
"assignment",
"[",
"\"package\"",
"]",
"r... | Package name construction is based on provider, not on prefix.
Prefix does not have to equal provider_prefix. | [
"Package",
"name",
"construction",
"is",
"based",
"on",
"provider",
"not",
"on",
"prefix",
".",
"Prefix",
"does",
"not",
"have",
"to",
"equal",
"provider_prefix",
"."
] | python | train |
openthread/openthread | tools/harness-thci/OpenThread.py | https://github.com/openthread/openthread/blob/0208d10563aa21c518092985c78ecf9cd223ab74/tools/harness-thci/OpenThread.py#L2567-L2580 | def setUdpJoinerPort(self, portNumber):
"""set Joiner UDP Port
Args:
portNumber: Joiner UDP Port number
Returns:
True: successful to set Joiner UDP Port
False: fail to set Joiner UDP Port
"""
print '%s call setUdpJoinerPort' % self.port
... | [
"def",
"setUdpJoinerPort",
"(",
"self",
",",
"portNumber",
")",
":",
"print",
"'%s call setUdpJoinerPort'",
"%",
"self",
".",
"port",
"cmd",
"=",
"'joinerport %d'",
"%",
"portNumber",
"print",
"cmd",
"return",
"self",
".",
"__sendCommand",
"(",
"cmd",
")",
"["... | set Joiner UDP Port
Args:
portNumber: Joiner UDP Port number
Returns:
True: successful to set Joiner UDP Port
False: fail to set Joiner UDP Port | [
"set",
"Joiner",
"UDP",
"Port"
] | python | train |
brentpayne/phrase | phrase/noun_phrase_dictionary.py | https://github.com/brentpayne/phrase/blob/2c25e202eff0f284cb724a36cec1b22a1169e7a2/phrase/noun_phrase_dictionary.py#L31-L54 | def convert_noun_phrases(self, id_run, pos_run):
"""
Converts any identified phrases in the run into phrase_ids. The dictionary provides all acceptable phrases
:param id_run: a run of token ids
:param dictionary: a dictionary of acceptable phrases described as there component token ids
... | [
"def",
"convert_noun_phrases",
"(",
"self",
",",
"id_run",
",",
"pos_run",
")",
":",
"i",
"=",
"0",
"rv",
"=",
"[",
"]",
"while",
"i",
"<",
"len",
"(",
"id_run",
")",
":",
"phrase_id",
",",
"offset",
"=",
"PhraseDictionary",
".",
"return_max_phrase",
"... | Converts any identified phrases in the run into phrase_ids. The dictionary provides all acceptable phrases
:param id_run: a run of token ids
:param dictionary: a dictionary of acceptable phrases described as there component token ids
:return: a run of token and phrase ids. | [
"Converts",
"any",
"identified",
"phrases",
"in",
"the",
"run",
"into",
"phrase_ids",
".",
"The",
"dictionary",
"provides",
"all",
"acceptable",
"phrases",
":",
"param",
"id_run",
":",
"a",
"run",
"of",
"token",
"ids",
":",
"param",
"dictionary",
":",
"a",
... | python | train |
CellProfiler/centrosome | centrosome/lapjv.py | https://github.com/CellProfiler/centrosome/blob/7bd9350a2d4ae1b215b81eabcecfe560bbb1f32a/centrosome/lapjv.py#L237-L360 | def slow_augment(n, ii, jj, idx, count, x, y, u, v, c):
'''Perform the augmentation step to assign unassigned i and j
n - the # of i and j, also the marker of unassigned x and y
ii - the unassigned i
jj - the ragged arrays of j for each i
idx - the index of the first j for each i
count - th... | [
"def",
"slow_augment",
"(",
"n",
",",
"ii",
",",
"jj",
",",
"idx",
",",
"count",
",",
"x",
",",
"y",
",",
"u",
",",
"v",
",",
"c",
")",
":",
"##################################################",
"#",
"# Augment procedure: from the Jonker paper.",
"#",
"# Note:... | Perform the augmentation step to assign unassigned i and j
n - the # of i and j, also the marker of unassigned x and y
ii - the unassigned i
jj - the ragged arrays of j for each i
idx - the index of the first j for each i
count - the number of j for each i
x - the assignments of j for each ... | [
"Perform",
"the",
"augmentation",
"step",
"to",
"assign",
"unassigned",
"i",
"and",
"j",
"n",
"-",
"the",
"#",
"of",
"i",
"and",
"j",
"also",
"the",
"marker",
"of",
"unassigned",
"x",
"and",
"y",
"ii",
"-",
"the",
"unassigned",
"i",
"jj",
"-",
"the",... | python | train |
singnet/snet-cli | snet_cli/mpe_service_metadata.py | https://github.com/singnet/snet-cli/blob/1b5ac98cb9a64211c861ead9fcfe6208f2749032/snet_cli/mpe_service_metadata.py#L75-L83 | def add_group(self, group_name, payment_address):
""" Return new group_id in base64 """
if (self.is_group_name_exists(group_name)):
raise Exception("the group \"%s\" is already present"%str(group_name))
group_id_base64 = base64.b64encode(secrets.token_bytes(32))
self.m["group... | [
"def",
"add_group",
"(",
"self",
",",
"group_name",
",",
"payment_address",
")",
":",
"if",
"(",
"self",
".",
"is_group_name_exists",
"(",
"group_name",
")",
")",
":",
"raise",
"Exception",
"(",
"\"the group \\\"%s\\\" is already present\"",
"%",
"str",
"(",
"gr... | Return new group_id in base64 | [
"Return",
"new",
"group_id",
"in",
"base64"
] | python | train |
GPflow/GPflow | gpflow/models/sgpmc.py | https://github.com/GPflow/GPflow/blob/549394f0b1b0696c7b521a065e49bdae6e7acf27/gpflow/models/sgpmc.py#L80-L86 | def _build_likelihood(self):
"""
This function computes the optimal density for v, q*(v), up to a constant
"""
# get the (marginals of) q(f): exactly predicting!
fmean, fvar = self._build_predict(self.X, full_cov=False)
return tf.reduce_sum(self.likelihood.variational_exp... | [
"def",
"_build_likelihood",
"(",
"self",
")",
":",
"# get the (marginals of) q(f): exactly predicting!",
"fmean",
",",
"fvar",
"=",
"self",
".",
"_build_predict",
"(",
"self",
".",
"X",
",",
"full_cov",
"=",
"False",
")",
"return",
"tf",
".",
"reduce_sum",
"(",
... | This function computes the optimal density for v, q*(v), up to a constant | [
"This",
"function",
"computes",
"the",
"optimal",
"density",
"for",
"v",
"q",
"*",
"(",
"v",
")",
"up",
"to",
"a",
"constant"
] | python | train |
klahnakoski/pyLibrary | mo_math/vendor/strangman/stats.py | https://github.com/klahnakoski/pyLibrary/blob/fa2dcbc48fda8d26999baef400e9a98149e0b982/mo_math/vendor/strangman/stats.py#L443-L460 | def scoreatpercentile(inlist, percent):
"""
Returns the score at a given percentile relative to the distribution
given by inlist.
Usage: lscoreatpercentile(inlist,percent)
"""
if percent > 1:
print("\nDividing percent>1 by 100 in lscoreatpercentile().\n")
percent = percent / 100.0
targetc... | [
"def",
"scoreatpercentile",
"(",
"inlist",
",",
"percent",
")",
":",
"if",
"percent",
">",
"1",
":",
"print",
"(",
"\"\\nDividing percent>1 by 100 in lscoreatpercentile().\\n\"",
")",
"percent",
"=",
"percent",
"/",
"100.0",
"targetcf",
"=",
"percent",
"*",
"len",... | Returns the score at a given percentile relative to the distribution
given by inlist.
Usage: lscoreatpercentile(inlist,percent) | [
"Returns",
"the",
"score",
"at",
"a",
"given",
"percentile",
"relative",
"to",
"the",
"distribution",
"given",
"by",
"inlist",
"."
] | python | train |
titusjan/argos | argos/repo/repotreemodel.py | https://github.com/titusjan/argos/blob/20d0a3cae26c36ea789a5d219c02ca7df21279dd/argos/repo/repotreemodel.py#L53-L113 | def itemData(self, treeItem, column, role=Qt.DisplayRole):
""" Returns the data stored under the given role for the item. O
"""
if role == Qt.DisplayRole:
if column == self.COL_NODE_NAME:
return treeItem.nodeName
elif column == self.COL_NODE_PATH:
... | [
"def",
"itemData",
"(",
"self",
",",
"treeItem",
",",
"column",
",",
"role",
"=",
"Qt",
".",
"DisplayRole",
")",
":",
"if",
"role",
"==",
"Qt",
".",
"DisplayRole",
":",
"if",
"column",
"==",
"self",
".",
"COL_NODE_NAME",
":",
"return",
"treeItem",
".",... | Returns the data stored under the given role for the item. O | [
"Returns",
"the",
"data",
"stored",
"under",
"the",
"given",
"role",
"for",
"the",
"item",
".",
"O"
] | python | train |
SCIP-Interfaces/PySCIPOpt | examples/finished/prodmix_soco.py | https://github.com/SCIP-Interfaces/PySCIPOpt/blob/9c960b40d94a48b0304d73dbe28b467b9c065abe/examples/finished/prodmix_soco.py#L8-L35 | def prodmix(I,K,a,p,epsilon,LB):
"""prodmix: robust production planning using soco
Parameters:
I - set of materials
K - set of components
a[i][k] - coef. matrix
p[i] - price of material i
LB[k] - amount needed for k
Returns a model, ready to be solved.
"""
... | [
"def",
"prodmix",
"(",
"I",
",",
"K",
",",
"a",
",",
"p",
",",
"epsilon",
",",
"LB",
")",
":",
"model",
"=",
"Model",
"(",
"\"robust product mix\"",
")",
"x",
",",
"rhs",
"=",
"{",
"}",
",",
"{",
"}",
"for",
"i",
"in",
"I",
":",
"x",
"[",
"... | prodmix: robust production planning using soco
Parameters:
I - set of materials
K - set of components
a[i][k] - coef. matrix
p[i] - price of material i
LB[k] - amount needed for k
Returns a model, ready to be solved. | [
"prodmix",
":",
"robust",
"production",
"planning",
"using",
"soco",
"Parameters",
":",
"I",
"-",
"set",
"of",
"materials",
"K",
"-",
"set",
"of",
"components",
"a",
"[",
"i",
"]",
"[",
"k",
"]",
"-",
"coef",
".",
"matrix",
"p",
"[",
"i",
"]",
"-",... | python | train |
Fantomas42/django-blog-zinnia | zinnia/views/channels.py | https://github.com/Fantomas42/django-blog-zinnia/blob/b4949304b104a8e1a7a7a0773cbfd024313c3a15/zinnia/views/channels.py#L25-L31 | def get_context_data(self, **kwargs):
"""
Add query in context.
"""
context = super(BaseEntryChannel, self).get_context_data(**kwargs)
context.update({'query': self.query})
return context | [
"def",
"get_context_data",
"(",
"self",
",",
"*",
"*",
"kwargs",
")",
":",
"context",
"=",
"super",
"(",
"BaseEntryChannel",
",",
"self",
")",
".",
"get_context_data",
"(",
"*",
"*",
"kwargs",
")",
"context",
".",
"update",
"(",
"{",
"'query'",
":",
"s... | Add query in context. | [
"Add",
"query",
"in",
"context",
"."
] | python | train |
mlperf/training | reinforcement/tensorflow/minigo/dual_net.py | https://github.com/mlperf/training/blob/1c6ae725a81d15437a2b2df05cac0673fde5c3a4/reinforcement/tensorflow/minigo/dual_net.py#L182-L188 | def initialize_weights(self, save_file):
"""Initialize the weights from the given save_file.
Assumes that the graph has been constructed, and the
save_file contains weights that match the graph. Used
to set the weights to a different version of the player
without redifining the e... | [
"def",
"initialize_weights",
"(",
"self",
",",
"save_file",
")",
":",
"tf",
".",
"train",
".",
"Saver",
"(",
")",
".",
"restore",
"(",
"self",
".",
"sess",
",",
"save_file",
")"
] | Initialize the weights from the given save_file.
Assumes that the graph has been constructed, and the
save_file contains weights that match the graph. Used
to set the weights to a different version of the player
without redifining the entire graph. | [
"Initialize",
"the",
"weights",
"from",
"the",
"given",
"save_file",
".",
"Assumes",
"that",
"the",
"graph",
"has",
"been",
"constructed",
"and",
"the",
"save_file",
"contains",
"weights",
"that",
"match",
"the",
"graph",
".",
"Used",
"to",
"set",
"the",
"we... | python | train |
CellProfiler/centrosome | centrosome/filter.py | https://github.com/CellProfiler/centrosome/blob/7bd9350a2d4ae1b215b81eabcecfe560bbb1f32a/centrosome/filter.py#L1387-L1425 | def dot_n(x, y):
'''given two tensors N x I x K and N x K x J return N dot products
If either x or y is 2-dimensional, broadcast it over all N.
Dot products are size N x I x J.
Example:
x = np.array([[[1,2], [3,4], [5,6]],[[7,8], [9,10],[11,12]]])
y = np.array([[[1,2,3], [4,5,6]],[[7,8,9],[10,... | [
"def",
"dot_n",
"(",
"x",
",",
"y",
")",
":",
"if",
"x",
".",
"ndim",
"==",
"2",
":",
"if",
"y",
".",
"ndim",
"==",
"2",
":",
"return",
"np",
".",
"dot",
"(",
"x",
",",
"y",
")",
"x3",
"=",
"False",
"y3",
"=",
"True",
"nlen",
"=",
"y",
... | given two tensors N x I x K and N x K x J return N dot products
If either x or y is 2-dimensional, broadcast it over all N.
Dot products are size N x I x J.
Example:
x = np.array([[[1,2], [3,4], [5,6]],[[7,8], [9,10],[11,12]]])
y = np.array([[[1,2,3], [4,5,6]],[[7,8,9],[10,11,12]]])
print dot_... | [
"given",
"two",
"tensors",
"N",
"x",
"I",
"x",
"K",
"and",
"N",
"x",
"K",
"x",
"J",
"return",
"N",
"dot",
"products"
] | python | train |
project-rig/rig | rig/machine_control/scp_connection.py | https://github.com/project-rig/rig/blob/3a3e053d3214899b6d68758685835de0afd5542b/rig/machine_control/scp_connection.py#L372-L419 | def write(self, buffer_size, window_size, x, y, p, address, data):
"""Write a bytestring to an address in memory.
..note::
This method is included here to maintain API compatibility with an
`alternative implementation of SCP
<https://github.com/project-rig/rig-scp>`_... | [
"def",
"write",
"(",
"self",
",",
"buffer_size",
",",
"window_size",
",",
"x",
",",
"y",
",",
"p",
",",
"address",
",",
"data",
")",
":",
"# While there is still data perform a write: get the block to write",
"# this time around, determine the data type, perform the write a... | Write a bytestring to an address in memory.
..note::
This method is included here to maintain API compatibility with an
`alternative implementation of SCP
<https://github.com/project-rig/rig-scp>`_.
Parameters
----------
buffer_size : int
... | [
"Write",
"a",
"bytestring",
"to",
"an",
"address",
"in",
"memory",
"."
] | python | train |
ynop/audiomate | audiomate/corpus/corpus.py | https://github.com/ynop/audiomate/blob/61727920b23a708293c3d526fa3000d4de9c6c21/audiomate/corpus/corpus.py#L168-L196 | def import_tracks(self, import_tracks):
"""
Add the given tracks/track to the corpus.
If any of the given track-ids already exists, a suffix is appended so it is unique.
Args:
import_tracks (list): Either a list of or a single :py:class:`audiomate.tracks.Track`.
Ret... | [
"def",
"import_tracks",
"(",
"self",
",",
"import_tracks",
")",
":",
"if",
"isinstance",
"(",
"import_tracks",
",",
"tracks",
".",
"Track",
")",
":",
"import_tracks",
"=",
"[",
"import_tracks",
"]",
"idx_mapping",
"=",
"{",
"}",
"for",
"track",
"in",
"impo... | Add the given tracks/track to the corpus.
If any of the given track-ids already exists, a suffix is appended so it is unique.
Args:
import_tracks (list): Either a list of or a single :py:class:`audiomate.tracks.Track`.
Returns:
dict: A dictionary containing track-idx ma... | [
"Add",
"the",
"given",
"tracks",
"/",
"track",
"to",
"the",
"corpus",
".",
"If",
"any",
"of",
"the",
"given",
"track",
"-",
"ids",
"already",
"exists",
"a",
"suffix",
"is",
"appended",
"so",
"it",
"is",
"unique",
"."
] | python | train |
Opentrons/opentrons | api/src/opentrons/legacy_api/robot/robot.py | https://github.com/Opentrons/opentrons/blob/a7c15cc2636ecb64ab56c7edc1d8a57163aaeadf/api/src/opentrons/legacy_api/robot/robot.py#L162-L174 | def clear_tips(self):
"""
If reset is called with a tip attached, the tip must be removed
before the poses and _instruments members are cleared. If the tip is
not removed, the effective length of the pipette remains increased by
the length of the tip, and subsequent `_add_tip` ca... | [
"def",
"clear_tips",
"(",
"self",
")",
":",
"for",
"instrument",
"in",
"self",
".",
"_instruments",
".",
"values",
"(",
")",
":",
"if",
"instrument",
".",
"tip_attached",
":",
"instrument",
".",
"_remove_tip",
"(",
"instrument",
".",
"_tip_length",
")"
] | If reset is called with a tip attached, the tip must be removed
before the poses and _instruments members are cleared. If the tip is
not removed, the effective length of the pipette remains increased by
the length of the tip, and subsequent `_add_tip` calls will increase
the length in ad... | [
"If",
"reset",
"is",
"called",
"with",
"a",
"tip",
"attached",
"the",
"tip",
"must",
"be",
"removed",
"before",
"the",
"poses",
"and",
"_instruments",
"members",
"are",
"cleared",
".",
"If",
"the",
"tip",
"is",
"not",
"removed",
"the",
"effective",
"length... | python | train |
pywbem/pywbem | pywbem/tupleparse.py | https://github.com/pywbem/pywbem/blob/e54ecb82c2211e289a268567443d60fdd489f1e4/pywbem/tupleparse.py#L1772-L1781 | def parse_multirsp(self, tup_tree):
# pylint: disable=unused-argument
"""
This function not implemented. Because this request is generally not
implemented. It will probably never be implemented.
"""
raise CIMXMLParseError(
_format("Internal Error: Parsing supp... | [
"def",
"parse_multirsp",
"(",
"self",
",",
"tup_tree",
")",
":",
"# pylint: disable=unused-argument",
"raise",
"CIMXMLParseError",
"(",
"_format",
"(",
"\"Internal Error: Parsing support for element {0!A} is not \"",
"\"implemented\"",
",",
"name",
"(",
"tup_tree",
")",
")"... | This function not implemented. Because this request is generally not
implemented. It will probably never be implemented. | [
"This",
"function",
"not",
"implemented",
".",
"Because",
"this",
"request",
"is",
"generally",
"not",
"implemented",
".",
"It",
"will",
"probably",
"never",
"be",
"implemented",
"."
] | python | train |
QualiSystems/vCenterShell | package/cloudshell/cp/vcenter/common/vcenter/vmomi_service.py | https://github.com/QualiSystems/vCenterShell/blob/e2e24cd938a92a68f4a8e6a860810d3ef72aae6d/package/cloudshell/cp/vcenter/common/vcenter/vmomi_service.py#L245-L304 | def get_folder(self, si, path, root=None):
"""
Finds folder in the vCenter or returns "None"
:param si: pyvmomi 'ServiceInstance'
:param path: the path to find the object ('dc' or 'dc/folder' or 'dc/folder/folder/etc...')
"""
search_index = si.content.sear... | [
"def",
"get_folder",
"(",
"self",
",",
"si",
",",
"path",
",",
"root",
"=",
"None",
")",
":",
"search_index",
"=",
"si",
".",
"content",
".",
"searchIndex",
"sub_folder",
"=",
"root",
"if",
"root",
"else",
"si",
".",
"content",
".",
"rootFolder",
"if",... | Finds folder in the vCenter or returns "None"
:param si: pyvmomi 'ServiceInstance'
:param path: the path to find the object ('dc' or 'dc/folder' or 'dc/folder/folder/etc...') | [
"Finds",
"folder",
"in",
"the",
"vCenter",
"or",
"returns",
"None"
] | python | train |
rsgalloway/grit | grit/repo/version.py | https://github.com/rsgalloway/grit/blob/e6434ad8a1f4ac5d0903ebad630c81f8a5164d78/grit/repo/version.py#L224-L231 | def versions(self, rev=None, index=None):
""":return: List of Versions for this Item"""
raise NotImplementedError
_revisions = [line.split()[0] for line in self.log.split('\n') if line]
_versions = [Version(self.obj.repo.commit(r)) for r in _revisions if rev is None or r.startswith(rev)]... | [
"def",
"versions",
"(",
"self",
",",
"rev",
"=",
"None",
",",
"index",
"=",
"None",
")",
":",
"raise",
"NotImplementedError",
"_revisions",
"=",
"[",
"line",
".",
"split",
"(",
")",
"[",
"0",
"]",
"for",
"line",
"in",
"self",
".",
"log",
".",
"spli... | :return: List of Versions for this Item | [
":",
"return",
":",
"List",
"of",
"Versions",
"for",
"this",
"Item"
] | python | train |
saltstack/salt | salt/modules/napalm_mod.py | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/napalm_mod.py#L1533-L1571 | def config_merge_tree(source='running',
merge_config=None,
merge_path=None,
saltenv='base'):
'''
.. versionadded:: 2019.2.0
Return the merge tree of the ``initial_config`` with the ``merge_config``,
as a Python dictionary.
source: `... | [
"def",
"config_merge_tree",
"(",
"source",
"=",
"'running'",
",",
"merge_config",
"=",
"None",
",",
"merge_path",
"=",
"None",
",",
"saltenv",
"=",
"'base'",
")",
":",
"config_txt",
"=",
"__salt__",
"[",
"'net.config'",
"]",
"(",
"source",
"=",
"source",
"... | .. versionadded:: 2019.2.0
Return the merge tree of the ``initial_config`` with the ``merge_config``,
as a Python dictionary.
source: ``running``
The configuration type to retrieve from the network device. Default:
``running``. Available options: ``running``, ``startup``, ``candidate``.
... | [
"..",
"versionadded",
"::",
"2019",
".",
"2",
".",
"0"
] | python | train |
uw-it-aca/uw-restclients | restclients/trumba/calendar.py | https://github.com/uw-it-aca/uw-restclients/blob/e12dcd32bf5296b6ebdf71798031594afb7852cb/restclients/trumba/calendar.py#L249-L265 | def _process_get_perm_resp(url, post_response, campus, calendarid):
"""
:return: a list of trumba.Permission objects
sorted by descending level and ascending uwnetid
None if error, [] if not exists
If the response is successful, process the response data
and load into the retur... | [
"def",
"_process_get_perm_resp",
"(",
"url",
",",
"post_response",
",",
"campus",
",",
"calendarid",
")",
":",
"request_id",
"=",
"\"%s %s CalendarID:%s\"",
"%",
"(",
"campus",
",",
"url",
",",
"calendarid",
")",
"data",
"=",
"_load_json",
"(",
"request_id",
"... | :return: a list of trumba.Permission objects
sorted by descending level and ascending uwnetid
None if error, [] if not exists
If the response is successful, process the response data
and load into the return objects
otherwise raise DataFailureException | [
":",
"return",
":",
"a",
"list",
"of",
"trumba",
".",
"Permission",
"objects",
"sorted",
"by",
"descending",
"level",
"and",
"ascending",
"uwnetid",
"None",
"if",
"error",
"[]",
"if",
"not",
"exists",
"If",
"the",
"response",
"is",
"successful",
"process",
... | python | train |
KelSolaar/Umbra | umbra/ui/delegates.py | https://github.com/KelSolaar/Umbra/blob/66f45f08d9d723787f1191989f8b0dda84b412ce/umbra/ui/delegates.py#L156-L175 | def paint(self, painter, option, index):
"""
Reimplements the :meth:`QStyledItemDelegate.paint` method.
"""
if option.state & QStyle.State_MouseOver:
styleSheet = self.__style.hover
elif option.state & QStyle.State_Selected:
styleSheet = self.__style.high... | [
"def",
"paint",
"(",
"self",
",",
"painter",
",",
"option",
",",
"index",
")",
":",
"if",
"option",
".",
"state",
"&",
"QStyle",
".",
"State_MouseOver",
":",
"styleSheet",
"=",
"self",
".",
"__style",
".",
"hover",
"elif",
"option",
".",
"state",
"&",
... | Reimplements the :meth:`QStyledItemDelegate.paint` method. | [
"Reimplements",
"the",
":",
"meth",
":",
"QStyledItemDelegate",
".",
"paint",
"method",
"."
] | python | train |
Alignak-monitoring/alignak | alignak/external_command.py | https://github.com/Alignak-monitoring/alignak/blob/f3c145207e83159b799d3714e4241399c7740a64/alignak/external_command.py#L2789-L2803 | def enable_host_notifications(self, host):
"""Enable notifications for a host
Format of the line that triggers function call::
ENABLE_HOST_NOTIFICATIONS;<host_name>
:param host: host to edit
:type host: alignak.objects.host.Host
:return: None
"""
if not ... | [
"def",
"enable_host_notifications",
"(",
"self",
",",
"host",
")",
":",
"if",
"not",
"host",
".",
"notifications_enabled",
":",
"host",
".",
"modified_attributes",
"|=",
"DICT_MODATTR",
"[",
"\"MODATTR_NOTIFICATIONS_ENABLED\"",
"]",
".",
"value",
"host",
".",
"not... | Enable notifications for a host
Format of the line that triggers function call::
ENABLE_HOST_NOTIFICATIONS;<host_name>
:param host: host to edit
:type host: alignak.objects.host.Host
:return: None | [
"Enable",
"notifications",
"for",
"a",
"host",
"Format",
"of",
"the",
"line",
"that",
"triggers",
"function",
"call",
"::"
] | python | train |
vcatalano/py-authorize | authorize/apis/authorize_api.py | https://github.com/vcatalano/py-authorize/blob/4d000b5a1ff2d8e7e955b83dab9d6c6a495c2851/authorize/apis/authorize_api.py#L46-L51 | def _base_request(self, method):
"""Factory method for generating the base XML requests."""
request = E.Element(method)
request.set('xmlns', 'AnetApi/xml/v1/schema/AnetApiSchema.xsd')
request.append(self.client_auth)
return request | [
"def",
"_base_request",
"(",
"self",
",",
"method",
")",
":",
"request",
"=",
"E",
".",
"Element",
"(",
"method",
")",
"request",
".",
"set",
"(",
"'xmlns'",
",",
"'AnetApi/xml/v1/schema/AnetApiSchema.xsd'",
")",
"request",
".",
"append",
"(",
"self",
".",
... | Factory method for generating the base XML requests. | [
"Factory",
"method",
"for",
"generating",
"the",
"base",
"XML",
"requests",
"."
] | python | train |
priestc/moneywagon | moneywagon/__init__.py | https://github.com/priestc/moneywagon/blob/00518f1f557dcca8b3031f46d3564c2baa0227a3/moneywagon/__init__.py#L414-L438 | def guess_currency_from_address(address):
"""
Given a crypto address, find which currency it likely belongs to.
Raises an exception if it can't find a match. Raises exception if address
is invalid.
"""
if is_py2:
fixer = lambda x: int(x.encode('hex'), 16)
else:
fixer = lambda... | [
"def",
"guess_currency_from_address",
"(",
"address",
")",
":",
"if",
"is_py2",
":",
"fixer",
"=",
"lambda",
"x",
":",
"int",
"(",
"x",
".",
"encode",
"(",
"'hex'",
")",
",",
"16",
")",
"else",
":",
"fixer",
"=",
"lambda",
"x",
":",
"x",
"# does noth... | Given a crypto address, find which currency it likely belongs to.
Raises an exception if it can't find a match. Raises exception if address
is invalid. | [
"Given",
"a",
"crypto",
"address",
"find",
"which",
"currency",
"it",
"likely",
"belongs",
"to",
".",
"Raises",
"an",
"exception",
"if",
"it",
"can",
"t",
"find",
"a",
"match",
".",
"Raises",
"exception",
"if",
"address",
"is",
"invalid",
"."
] | python | train |
broadinstitute/fiss | firecloud/api.py | https://github.com/broadinstitute/fiss/blob/dddf91547479506dbbafb69ec84d44dcc4a94ab4/firecloud/api.py#L1235-L1269 | def clone_workspace(from_namespace, from_workspace, to_namespace, to_workspace,
authorizationDomain=""):
"""Clone a FireCloud workspace.
A clone is a shallow copy of a FireCloud workspace, enabling
easy sharing of data, such as TCGA data, without duplication.
Args:
from_nam... | [
"def",
"clone_workspace",
"(",
"from_namespace",
",",
"from_workspace",
",",
"to_namespace",
",",
"to_workspace",
",",
"authorizationDomain",
"=",
"\"\"",
")",
":",
"if",
"authorizationDomain",
":",
"if",
"isinstance",
"(",
"authorizationDomain",
",",
"string_types",
... | Clone a FireCloud workspace.
A clone is a shallow copy of a FireCloud workspace, enabling
easy sharing of data, such as TCGA data, without duplication.
Args:
from_namespace (str): project (namespace) to which source workspace belongs
from_workspace (str): Source workspace's name
t... | [
"Clone",
"a",
"FireCloud",
"workspace",
"."
] | python | train |
nosegae/NoseGAE | examples/modules_example/printenv.py | https://github.com/nosegae/NoseGAE/blob/fca9fab22b480bb9721ecaa0967a636107648d92/examples/modules_example/printenv.py#L33-L43 | def html_for_env_var(key):
"""Returns an HTML snippet for an environment variable.
Args:
key: A string representing an environment variable name.
Returns:
String HTML representing the value and variable.
"""
value = os.getenv(key)
return KEY_VALUE_TEMPLATE.format(key, value) | [
"def",
"html_for_env_var",
"(",
"key",
")",
":",
"value",
"=",
"os",
".",
"getenv",
"(",
"key",
")",
"return",
"KEY_VALUE_TEMPLATE",
".",
"format",
"(",
"key",
",",
"value",
")"
] | Returns an HTML snippet for an environment variable.
Args:
key: A string representing an environment variable name.
Returns:
String HTML representing the value and variable. | [
"Returns",
"an",
"HTML",
"snippet",
"for",
"an",
"environment",
"variable",
"."
] | python | train |
wandb/client | wandb/vendor/prompt_toolkit/interface.py | https://github.com/wandb/client/blob/7d08954ed5674fee223cd85ed0d8518fe47266b2/wandb/vendor/prompt_toolkit/interface.py#L350-L361 | def _redraw(self):
"""
Render the command line again. (Not thread safe!) (From other threads,
or if unsure, use :meth:`.CommandLineInterface.invalidate`.)
"""
# Only draw when no sub application was started.
if self._is_running and self._sub_cli is None:
self.... | [
"def",
"_redraw",
"(",
"self",
")",
":",
"# Only draw when no sub application was started.",
"if",
"self",
".",
"_is_running",
"and",
"self",
".",
"_sub_cli",
"is",
"None",
":",
"self",
".",
"render_counter",
"+=",
"1",
"self",
".",
"renderer",
".",
"render",
... | Render the command line again. (Not thread safe!) (From other threads,
or if unsure, use :meth:`.CommandLineInterface.invalidate`.) | [
"Render",
"the",
"command",
"line",
"again",
".",
"(",
"Not",
"thread",
"safe!",
")",
"(",
"From",
"other",
"threads",
"or",
"if",
"unsure",
"use",
":",
"meth",
":",
".",
"CommandLineInterface",
".",
"invalidate",
".",
")"
] | python | train |
bkg/django-spillway | spillway/query.py | https://github.com/bkg/django-spillway/blob/c488a62642430b005f1e0d4a19e160d8d5964b67/spillway/query.py#L265-L284 | def zipfiles(self, path=None, arcdirname='data'):
"""Returns a .zip archive of selected rasters."""
if path:
fp = open(path, 'w+b')
else:
prefix = '%s-' % arcdirname
fp = tempfile.NamedTemporaryFile(prefix=prefix, suffix='.zip')
with zipfile.ZipFile(fp... | [
"def",
"zipfiles",
"(",
"self",
",",
"path",
"=",
"None",
",",
"arcdirname",
"=",
"'data'",
")",
":",
"if",
"path",
":",
"fp",
"=",
"open",
"(",
"path",
",",
"'w+b'",
")",
"else",
":",
"prefix",
"=",
"'%s-'",
"%",
"arcdirname",
"fp",
"=",
"tempfile... | Returns a .zip archive of selected rasters. | [
"Returns",
"a",
".",
"zip",
"archive",
"of",
"selected",
"rasters",
"."
] | python | train |
iotile/coretools | transport_plugins/native_ble/iotile_transport_native_ble/device_adapter.py | https://github.com/iotile/coretools/blob/2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec/transport_plugins/native_ble/iotile_transport_native_ble/device_adapter.py#L649-L675 | def _on_interface_opened(self, success, result, failure_reason, context, next_characteristic=None):
"""Callback function called when the notification related to an interface has been enabled.
It is executed in the baBLE working thread: should not be blocking.
Args:
success (bool): A... | [
"def",
"_on_interface_opened",
"(",
"self",
",",
"success",
",",
"result",
",",
"failure_reason",
",",
"context",
",",
"next_characteristic",
"=",
"None",
")",
":",
"if",
"not",
"success",
":",
"self",
".",
"connections",
".",
"finish_operation",
"(",
"context... | Callback function called when the notification related to an interface has been enabled.
It is executed in the baBLE working thread: should not be blocking.
Args:
success (bool): A bool indicating that the operation is successful or not
result (dict): Information (if successful)... | [
"Callback",
"function",
"called",
"when",
"the",
"notification",
"related",
"to",
"an",
"interface",
"has",
"been",
"enabled",
".",
"It",
"is",
"executed",
"in",
"the",
"baBLE",
"working",
"thread",
":",
"should",
"not",
"be",
"blocking",
"."
] | python | train |
sdispater/orator | orator/query/grammars/mysql_grammar.py | https://github.com/sdispater/orator/blob/bd90bf198ee897751848f9a92e49d18e60a74136/orator/query/grammars/mysql_grammar.py#L25-L40 | def compile_select(self, query):
"""
Compile a select query into SQL
:param query: A QueryBuilder instance
:type query: QueryBuilder
:return: The compiled sql
:rtype: str
"""
sql = super(MySQLQueryGrammar, self).compile_select(query)
if query.un... | [
"def",
"compile_select",
"(",
"self",
",",
"query",
")",
":",
"sql",
"=",
"super",
"(",
"MySQLQueryGrammar",
",",
"self",
")",
".",
"compile_select",
"(",
"query",
")",
"if",
"query",
".",
"unions",
":",
"sql",
"=",
"\"(%s) %s\"",
"%",
"(",
"sql",
",",... | Compile a select query into SQL
:param query: A QueryBuilder instance
:type query: QueryBuilder
:return: The compiled sql
:rtype: str | [
"Compile",
"a",
"select",
"query",
"into",
"SQL"
] | python | train |
inasafe/inasafe | safe/gui/widgets/dock.py | https://github.com/inasafe/inasafe/blob/831d60abba919f6d481dc94a8d988cc205130724/safe/gui/widgets/dock.py#L1265-L1282 | def _search_inasafe_layer(self):
"""Search for an inasafe layer in an active group.
:returns: A valid layer.
:rtype: QgsMapLayer
.. versionadded:: 4.3
"""
selected_nodes = self.iface.layerTreeView().selectedNodes()
for selected_node in selected_nodes:
... | [
"def",
"_search_inasafe_layer",
"(",
"self",
")",
":",
"selected_nodes",
"=",
"self",
".",
"iface",
".",
"layerTreeView",
"(",
")",
".",
"selectedNodes",
"(",
")",
"for",
"selected_node",
"in",
"selected_nodes",
":",
"tree_layers",
"=",
"[",
"child",
"for",
... | Search for an inasafe layer in an active group.
:returns: A valid layer.
:rtype: QgsMapLayer
.. versionadded:: 4.3 | [
"Search",
"for",
"an",
"inasafe",
"layer",
"in",
"an",
"active",
"group",
"."
] | python | train |
pklaus/brother_ql | brother_ql/cli.py | https://github.com/pklaus/brother_ql/blob/b551b1fc944873f3a2ead7032d144dfd81011e79/brother_ql/cli.py#L134-L147 | def print_cmd(ctx, *args, **kwargs):
""" Print a label of the provided IMAGE. """
backend = ctx.meta.get('BACKEND', 'pyusb')
model = ctx.meta.get('MODEL')
printer = ctx.meta.get('PRINTER')
from brother_ql.conversion import convert
from brother_ql.backends.helpers import send
from brother_ql.... | [
"def",
"print_cmd",
"(",
"ctx",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"backend",
"=",
"ctx",
".",
"meta",
".",
"get",
"(",
"'BACKEND'",
",",
"'pyusb'",
")",
"model",
"=",
"ctx",
".",
"meta",
".",
"get",
"(",
"'MODEL'",
")",
"printe... | Print a label of the provided IMAGE. | [
"Print",
"a",
"label",
"of",
"the",
"provided",
"IMAGE",
"."
] | python | train |
ContinuumIO/flask-ldap-login | flask_ldap_login/__init__.py | https://github.com/ContinuumIO/flask-ldap-login/blob/09a08be45f861823cb08f95883ee1e092a618c37/flask_ldap_login/__init__.py#L236-L262 | def connect(self):
'initialize ldap connection and set options'
log.debug("Connecting to ldap server %s" % self.config['URI'])
self.conn = ldap.initialize(self.config['URI'])
# There are some settings that can't be changed at runtime without a context restart.
# It's possible to... | [
"def",
"connect",
"(",
"self",
")",
":",
"log",
".",
"debug",
"(",
"\"Connecting to ldap server %s\"",
"%",
"self",
".",
"config",
"[",
"'URI'",
"]",
")",
"self",
".",
"conn",
"=",
"ldap",
".",
"initialize",
"(",
"self",
".",
"config",
"[",
"'URI'",
"]... | initialize ldap connection and set options | [
"initialize",
"ldap",
"connection",
"and",
"set",
"options"
] | python | train |
richardkiss/pycoin | pycoin/encoding/b58.py | https://github.com/richardkiss/pycoin/blob/1e8d0d9fe20ce0347b97847bb529cd1bd84c7442/pycoin/encoding/b58.py#L22-L25 | def a2b_base58(s):
"""Convert base58 to binary using BASE58_ALPHABET."""
v, prefix = to_long(BASE58_BASE, lambda c: BASE58_LOOKUP[c], s.encode("utf8"))
return from_long(v, prefix, 256, lambda x: x) | [
"def",
"a2b_base58",
"(",
"s",
")",
":",
"v",
",",
"prefix",
"=",
"to_long",
"(",
"BASE58_BASE",
",",
"lambda",
"c",
":",
"BASE58_LOOKUP",
"[",
"c",
"]",
",",
"s",
".",
"encode",
"(",
"\"utf8\"",
")",
")",
"return",
"from_long",
"(",
"v",
",",
"pre... | Convert base58 to binary using BASE58_ALPHABET. | [
"Convert",
"base58",
"to",
"binary",
"using",
"BASE58_ALPHABET",
"."
] | python | train |
protream/iquery | iquery/hospitals.py | https://github.com/protream/iquery/blob/7272e68af610f1dd63cf695209cfa44b75adc0e6/iquery/hospitals.py#L67-L99 | def query(params):
"""`params` is a city name or a city name + hospital name.
CLI:
1. query all putian hospitals in a city:
$ iquery -p 南京
+------+
| 南京 |
+------+
|... |
+------+
|... |
+------+
...
2. query if the... | [
"def",
"query",
"(",
"params",
")",
":",
"r",
"=",
"requests_get",
"(",
"QUERY_URL",
",",
"verify",
"=",
"True",
")",
"return",
"HospitalCollection",
"(",
"r",
".",
"json",
"(",
")",
",",
"params",
")"
] | `params` is a city name or a city name + hospital name.
CLI:
1. query all putian hospitals in a city:
$ iquery -p 南京
+------+
| 南京 |
+------+
|... |
+------+
|... |
+------+
...
2. query if the hospital in the city is p... | [
"params",
"is",
"a",
"city",
"name",
"or",
"a",
"city",
"name",
"+",
"hospital",
"name",
"."
] | python | train |
angr/angr | angr/analyses/bindiff.py | https://github.com/angr/angr/blob/4e2f97d56af5419ee73bdb30482c8dd8ff5f3e40/angr/analyses/bindiff.py#L104-L128 | def _normalized_levenshtein_distance(s1, s2, acceptable_differences):
"""
This function calculates the levenshtein distance but allows for elements in the lists to be different by any number
in the set acceptable_differences.
:param s1: A list.
:param s2: A... | [
"def",
"_normalized_levenshtein_distance",
"(",
"s1",
",",
"s2",
",",
"acceptable_differences",
")",
":",
"if",
"len",
"(",
"s1",
")",
">",
"len",
"(",
"s2",
")",
":",
"s1",
",",
"s2",
"=",
"s2",
",",
"s1",
"acceptable_differences",
"=",
"set",
"(",
"-... | This function calculates the levenshtein distance but allows for elements in the lists to be different by any number
in the set acceptable_differences.
:param s1: A list.
:param s2: Another list.
:param acceptable_differences: A set of numbers. If (s2[i]-s1[i]... | [
"This",
"function",
"calculates",
"the",
"levenshtein",
"distance",
"but",
"allows",
"for",
"elements",
"in",
"the",
"lists",
"to",
"be",
"different",
"by",
"any",
"number",
"in",
"the",
"set",
"acceptable_differences",
"."
] | python | train |
rosenbrockc/acorn | acorn/logging/diff.py | https://github.com/rosenbrockc/acorn/blob/9a44d1a1ad8bfc2c54a6b56d9efe54433a797820/acorn/logging/diff.py#L5-L30 | def cascade(sequence, full=False):
"""Restores a sequence of string definitions using the first entry as the
original and then applying a series of :func:`~acorn.logging.diff.restore`
calls.
Args:
sequence (list): of results returned by
:func:`~acorn.logging.diff.compress`, except tha... | [
"def",
"cascade",
"(",
"sequence",
",",
"full",
"=",
"False",
")",
":",
"if",
"len",
"(",
"sequence",
")",
"==",
"1",
":",
"return",
"sequence",
"[",
"0",
"]",
"left",
"=",
"sequence",
"[",
"0",
"]",
"if",
"full",
":",
"intermed",
"=",
"[",
"]",
... | Restores a sequence of string definitions using the first entry as the
original and then applying a series of :func:`~acorn.logging.diff.restore`
calls.
Args:
sequence (list): of results returned by
:func:`~acorn.logging.diff.compress`, except that the first entry should
be a li... | [
"Restores",
"a",
"sequence",
"of",
"string",
"definitions",
"using",
"the",
"first",
"entry",
"as",
"the",
"original",
"and",
"then",
"applying",
"a",
"series",
"of",
":",
"func",
":",
"~acorn",
".",
"logging",
".",
"diff",
".",
"restore",
"calls",
"."
] | python | train |
ActivisionGameScience/assertpy | assertpy/assertpy.py | https://github.com/ActivisionGameScience/assertpy/blob/08d799cdb01f9a25d3e20672efac991c7bc26d79/assertpy/assertpy.py#L451-L457 | def is_not_inf(self):
"""Asserts that val is real number and not Inf (infinity)."""
self._validate_number()
self._validate_real()
if math.isinf(self.val):
self._err('Expected not <Inf>, but was.')
return self | [
"def",
"is_not_inf",
"(",
"self",
")",
":",
"self",
".",
"_validate_number",
"(",
")",
"self",
".",
"_validate_real",
"(",
")",
"if",
"math",
".",
"isinf",
"(",
"self",
".",
"val",
")",
":",
"self",
".",
"_err",
"(",
"'Expected not <Inf>, but was.'",
")"... | Asserts that val is real number and not Inf (infinity). | [
"Asserts",
"that",
"val",
"is",
"real",
"number",
"and",
"not",
"Inf",
"(",
"infinity",
")",
"."
] | python | valid |
neithere/monk | monk/validators.py | https://github.com/neithere/monk/blob/4b2ee5152b081ac288ce8568422a027b5e7d2b1c/monk/validators.py#L699-L753 | def translate(value):
"""
Translates given schema from "pythonic" syntax to a validator.
Usage::
>>> translate(str)
IsA(str)
>>> translate('hello')
IsA(str, default='hello')
"""
if isinstance(value, BaseValidator):
return value
if value is None:
... | [
"def",
"translate",
"(",
"value",
")",
":",
"if",
"isinstance",
"(",
"value",
",",
"BaseValidator",
")",
":",
"return",
"value",
"if",
"value",
"is",
"None",
":",
"return",
"Anything",
"(",
")",
"if",
"isinstance",
"(",
"value",
",",
"type",
")",
":",
... | Translates given schema from "pythonic" syntax to a validator.
Usage::
>>> translate(str)
IsA(str)
>>> translate('hello')
IsA(str, default='hello') | [
"Translates",
"given",
"schema",
"from",
"pythonic",
"syntax",
"to",
"a",
"validator",
"."
] | python | train |
mezz64/pyEmby | pyemby/helpers.py | https://github.com/mezz64/pyEmby/blob/6bb621e4e25bf1b9b0aba2c38b588e68f8816226/pyemby/helpers.py#L10-L22 | def deprecated_name(name):
"""Allow old method names for backwards compatability. """
def decorator(func):
"""Decorator function."""
def func_wrapper(self):
"""Wrapper for original function."""
if hasattr(self, name):
# Return the old property
... | [
"def",
"deprecated_name",
"(",
"name",
")",
":",
"def",
"decorator",
"(",
"func",
")",
":",
"\"\"\"Decorator function.\"\"\"",
"def",
"func_wrapper",
"(",
"self",
")",
":",
"\"\"\"Wrapper for original function.\"\"\"",
"if",
"hasattr",
"(",
"self",
",",
"name",
")... | Allow old method names for backwards compatability. | [
"Allow",
"old",
"method",
"names",
"for",
"backwards",
"compatability",
"."
] | python | train |
tensorflow/cleverhans | cleverhans/utils_tf.py | https://github.com/tensorflow/cleverhans/blob/97488e215760547b81afc53f5e5de8ba7da5bd98/cleverhans/utils_tf.py#L358-L392 | def clip_eta(eta, ord, eps):
"""
Helper function to clip the perturbation to epsilon norm ball.
:param eta: A tensor with the current perturbation.
:param ord: Order of the norm (mimics Numpy).
Possible values: np.inf, 1 or 2.
:param eps: Epsilon, bound of the perturbation.
"""
# Clipping p... | [
"def",
"clip_eta",
"(",
"eta",
",",
"ord",
",",
"eps",
")",
":",
"# Clipping perturbation eta to self.ord norm ball",
"if",
"ord",
"not",
"in",
"[",
"np",
".",
"inf",
",",
"1",
",",
"2",
"]",
":",
"raise",
"ValueError",
"(",
"'ord must be np.inf, 1, or 2.'",
... | Helper function to clip the perturbation to epsilon norm ball.
:param eta: A tensor with the current perturbation.
:param ord: Order of the norm (mimics Numpy).
Possible values: np.inf, 1 or 2.
:param eps: Epsilon, bound of the perturbation. | [
"Helper",
"function",
"to",
"clip",
"the",
"perturbation",
"to",
"epsilon",
"norm",
"ball",
".",
":",
"param",
"eta",
":",
"A",
"tensor",
"with",
"the",
"current",
"perturbation",
".",
":",
"param",
"ord",
":",
"Order",
"of",
"the",
"norm",
"(",
"mimics"... | python | train |
pypa/pipenv | pipenv/vendor/distlib/util.py | https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/vendor/distlib/util.py#L145-L263 | def parse_requirement(req):
"""
Parse a requirement passed in as a string. Return a Container
whose attributes contain the various parts of the requirement.
"""
remaining = req.strip()
if not remaining or remaining.startswith('#'):
return None
m = IDENTIFIER.match(remaining)
if n... | [
"def",
"parse_requirement",
"(",
"req",
")",
":",
"remaining",
"=",
"req",
".",
"strip",
"(",
")",
"if",
"not",
"remaining",
"or",
"remaining",
".",
"startswith",
"(",
"'#'",
")",
":",
"return",
"None",
"m",
"=",
"IDENTIFIER",
".",
"match",
"(",
"remai... | Parse a requirement passed in as a string. Return a Container
whose attributes contain the various parts of the requirement. | [
"Parse",
"a",
"requirement",
"passed",
"in",
"as",
"a",
"string",
".",
"Return",
"a",
"Container",
"whose",
"attributes",
"contain",
"the",
"various",
"parts",
"of",
"the",
"requirement",
"."
] | python | train |
tensorpack/tensorpack | tensorpack/models/registry.py | https://github.com/tensorpack/tensorpack/blob/d7a13cb74c9066bc791d7aafc3b744b60ee79a9f/tensorpack/models/registry.py#L39-L49 | def get_registered_layer(name):
"""
Args:
name (str): the name of the layer, e.g. 'Conv2D'
Returns:
the wrapped layer function, or None if not registered.
"""
ret = _LAYER_REGISTRY.get(name, None)
if ret == _NameConflict:
raise KeyError("Layer named '{}' is registered wit... | [
"def",
"get_registered_layer",
"(",
"name",
")",
":",
"ret",
"=",
"_LAYER_REGISTRY",
".",
"get",
"(",
"name",
",",
"None",
")",
"if",
"ret",
"==",
"_NameConflict",
":",
"raise",
"KeyError",
"(",
"\"Layer named '{}' is registered with `@layer_register` more than once!\... | Args:
name (str): the name of the layer, e.g. 'Conv2D'
Returns:
the wrapped layer function, or None if not registered. | [
"Args",
":",
"name",
"(",
"str",
")",
":",
"the",
"name",
"of",
"the",
"layer",
"e",
".",
"g",
".",
"Conv2D",
"Returns",
":",
"the",
"wrapped",
"layer",
"function",
"or",
"None",
"if",
"not",
"registered",
"."
] | python | train |
raymondEhlers/pachyderm | pachyderm/projectors.py | https://github.com/raymondEhlers/pachyderm/blob/aaa1d8374fd871246290ce76f1796f2f7582b01d/pachyderm/projectors.py#L380-L420 | def _project_TH3(self, hist: Hist) -> Any:
""" Perform the actual TH3 -> TH1 projection.
This projection could be to 1D or 2D.
Args:
hist (ROOT.TH3): Histogram from which the projections should be performed.
Returns:
ROOT.TH1: The projected histogram.
""... | [
"def",
"_project_TH3",
"(",
"self",
",",
"hist",
":",
"Hist",
")",
"->",
"Any",
":",
"# Axis length validation",
"if",
"len",
"(",
"self",
".",
"projection_axes",
")",
"<",
"1",
"or",
"len",
"(",
"self",
".",
"projection_axes",
")",
">",
"2",
":",
"rai... | Perform the actual TH3 -> TH1 projection.
This projection could be to 1D or 2D.
Args:
hist (ROOT.TH3): Histogram from which the projections should be performed.
Returns:
ROOT.TH1: The projected histogram. | [
"Perform",
"the",
"actual",
"TH3",
"-",
">",
"TH1",
"projection",
"."
] | python | train |
jobovy/galpy | galpy/util/bovy_coords.py | https://github.com/jobovy/galpy/blob/9c5b9fe65d58835624dffe432be282060918ee08/galpy/util/bovy_coords.py#L1039-L1062 | def cyl_to_rect(R,phi,Z):
"""
NAME:
cyl_to_rect
PURPOSE:
convert from cylindrical to rectangular coordinates
INPUT:
R, phi, Z - cylindrical coordinates
OUTPUT:
X,Y,Z
HISTORY:
2011-02-23 - Written - Bovy (NYU)
"""
return (R*sc.cos(phi),R*sc.sin... | [
"def",
"cyl_to_rect",
"(",
"R",
",",
"phi",
",",
"Z",
")",
":",
"return",
"(",
"R",
"*",
"sc",
".",
"cos",
"(",
"phi",
")",
",",
"R",
"*",
"sc",
".",
"sin",
"(",
"phi",
")",
",",
"Z",
")"
] | NAME:
cyl_to_rect
PURPOSE:
convert from cylindrical to rectangular coordinates
INPUT:
R, phi, Z - cylindrical coordinates
OUTPUT:
X,Y,Z
HISTORY:
2011-02-23 - Written - Bovy (NYU) | [
"NAME",
":"
] | python | train |
PyPSA/PyPSA | pypsa/pf.py | https://github.com/PyPSA/PyPSA/blob/46954b1b3c21460550f7104681517065279a53b7/pypsa/pf.py#L579-L611 | def find_bus_controls(sub_network):
"""Find slack and all PV and PQ buses for a sub_network.
This function also fixes sub_network.buses_o, a DataFrame
ordered by control type."""
network = sub_network.network
find_slack_bus(sub_network)
gens = sub_network.generators()
buses_i = sub_networ... | [
"def",
"find_bus_controls",
"(",
"sub_network",
")",
":",
"network",
"=",
"sub_network",
".",
"network",
"find_slack_bus",
"(",
"sub_network",
")",
"gens",
"=",
"sub_network",
".",
"generators",
"(",
")",
"buses_i",
"=",
"sub_network",
".",
"buses_i",
"(",
")"... | Find slack and all PV and PQ buses for a sub_network.
This function also fixes sub_network.buses_o, a DataFrame
ordered by control type. | [
"Find",
"slack",
"and",
"all",
"PV",
"and",
"PQ",
"buses",
"for",
"a",
"sub_network",
".",
"This",
"function",
"also",
"fixes",
"sub_network",
".",
"buses_o",
"a",
"DataFrame",
"ordered",
"by",
"control",
"type",
"."
] | python | train |
acorg/dark-matter | dark/reads.py | https://github.com/acorg/dark-matter/blob/c78a1bf262667fa5db3548fa7066c4ec14d0551d/dark/reads.py#L1221-L1235 | def filterRead(self, read):
"""
Filter a read, according to our set of filters.
@param read: A C{Read} instance or one of its subclasses.
@return: C{False} if the read fails any of our filters, else the
C{Read} instance returned by our list of filters.
"""
fo... | [
"def",
"filterRead",
"(",
"self",
",",
"read",
")",
":",
"for",
"filterFunc",
"in",
"self",
".",
"_filters",
":",
"filteredRead",
"=",
"filterFunc",
"(",
"read",
")",
"if",
"filteredRead",
"is",
"False",
":",
"return",
"False",
"else",
":",
"read",
"=",
... | Filter a read, according to our set of filters.
@param read: A C{Read} instance or one of its subclasses.
@return: C{False} if the read fails any of our filters, else the
C{Read} instance returned by our list of filters. | [
"Filter",
"a",
"read",
"according",
"to",
"our",
"set",
"of",
"filters",
"."
] | python | train |
sporsh/carnifex | carnifex/endpoint.py | https://github.com/sporsh/carnifex/blob/82dd3bd2bc134dfb69a78f43171e227f2127060b/carnifex/endpoint.py#L149-L156 | def childDataReceived(self, childFD, data):
"""Relay data received on any file descriptor to the process
"""
protocol = getattr(self, 'protocol', None)
if protocol:
protocol.dataReceived(data)
else:
self.data.append((childFD, data)) | [
"def",
"childDataReceived",
"(",
"self",
",",
"childFD",
",",
"data",
")",
":",
"protocol",
"=",
"getattr",
"(",
"self",
",",
"'protocol'",
",",
"None",
")",
"if",
"protocol",
":",
"protocol",
".",
"dataReceived",
"(",
"data",
")",
"else",
":",
"self",
... | Relay data received on any file descriptor to the process | [
"Relay",
"data",
"received",
"on",
"any",
"file",
"descriptor",
"to",
"the",
"process"
] | python | train |
hvac/hvac | hvac/api/secrets_engines/identity.py | https://github.com/hvac/hvac/blob/cce5b86889193f622c2a72a4a1b7e1c9c8aff1ce/hvac/api/secrets_engines/identity.py#L887-L919 | def update_group_alias(self, entity_id, name, mount_accessor="", canonical_id="", mount_point=DEFAULT_MOUNT_POINT):
"""Update an existing group alias.
Supported methods:
POST: /{mount_point}/group-alias/id/{id}. Produces: 200 application/json
:param entity_id: ID of the group alias... | [
"def",
"update_group_alias",
"(",
"self",
",",
"entity_id",
",",
"name",
",",
"mount_accessor",
"=",
"\"\"",
",",
"canonical_id",
"=",
"\"\"",
",",
"mount_point",
"=",
"DEFAULT_MOUNT_POINT",
")",
":",
"params",
"=",
"{",
"'name'",
":",
"name",
",",
"'mount_a... | Update an existing group alias.
Supported methods:
POST: /{mount_point}/group-alias/id/{id}. Produces: 200 application/json
:param entity_id: ID of the group alias.
:type entity_id: str | unicode
:param name: Name of the group alias.
:type name: str | unicode
... | [
"Update",
"an",
"existing",
"group",
"alias",
"."
] | python | train |
fabioz/PyDev.Debugger | _pydevd_bundle/pydevd_vars.py | https://github.com/fabioz/PyDev.Debugger/blob/ed9c4307662a5593b8a7f1f3389ecd0e79b8c503/_pydevd_bundle/pydevd_vars.py#L243-L279 | def evaluate_expression(dbg, frame, expression, is_exec):
'''returns the result of the evaluated expression
@param is_exec: determines if we should do an exec or an eval
'''
if frame is None:
return
# Not using frame.f_globals because of https://sourceforge.net/tracker2/?func=detail&aid=254... | [
"def",
"evaluate_expression",
"(",
"dbg",
",",
"frame",
",",
"expression",
",",
"is_exec",
")",
":",
"if",
"frame",
"is",
"None",
":",
"return",
"# Not using frame.f_globals because of https://sourceforge.net/tracker2/?func=detail&aid=2541355&group_id=85796&atid=577329",
"# (Na... | returns the result of the evaluated expression
@param is_exec: determines if we should do an exec or an eval | [
"returns",
"the",
"result",
"of",
"the",
"evaluated",
"expression"
] | python | train |
GeorgeArgyros/sfalearn | sfalearn/angluin_fst.py | https://github.com/GeorgeArgyros/sfalearn/blob/68a93f507e2fb7d89ca04bd8a8f0da2d6c680443/sfalearn/angluin_fst.py#L255-L282 | def _process_counter_example(self, mma, w_string):
""""
Process a counterexample in the Rivest-Schapire way.
Args:
mma (DFA): The hypothesis automaton
w_string (str): The examined string to be consumed
Returns:
None
"""
w_string = self._find_... | [
"def",
"_process_counter_example",
"(",
"self",
",",
"mma",
",",
"w_string",
")",
":",
"w_string",
"=",
"self",
".",
"_find_bad_transition",
"(",
"mma",
",",
"w_string",
")",
"diff",
"=",
"len",
"(",
"w_string",
")",
"same",
"=",
"0",
"while",
"True",
":... | Process a counterexample in the Rivest-Schapire way.
Args:
mma (DFA): The hypothesis automaton
w_string (str): The examined string to be consumed
Returns:
None | [
"Process",
"a",
"counterexample",
"in",
"the",
"Rivest",
"-",
"Schapire",
"way",
".",
"Args",
":",
"mma",
"(",
"DFA",
")",
":",
"The",
"hypothesis",
"automaton",
"w_string",
"(",
"str",
")",
":",
"The",
"examined",
"string",
"to",
"be",
"consumed",
"Retu... | python | train |
brocade/pynos | pynos/versions/ver_6/ver_6_0_1/yang/brocade_lag.py | https://github.com/brocade/pynos/blob/bd8a34e98f322de3fc06750827d8bbc3a0c00380/pynos/versions/ver_6/ver_6_0_1/yang/brocade_lag.py#L27-L40 | def get_port_channel_detail_input_request_type_get_next_request_last_aggregator_id(self, **kwargs):
"""Auto Generated Code
"""
config = ET.Element("config")
get_port_channel_detail = ET.Element("get_port_channel_detail")
config = get_port_channel_detail
input = ET.SubElem... | [
"def",
"get_port_channel_detail_input_request_type_get_next_request_last_aggregator_id",
"(",
"self",
",",
"*",
"*",
"kwargs",
")",
":",
"config",
"=",
"ET",
".",
"Element",
"(",
"\"config\"",
")",
"get_port_channel_detail",
"=",
"ET",
".",
"Element",
"(",
"\"get_port... | Auto Generated Code | [
"Auto",
"Generated",
"Code"
] | python | train |
jilljenn/tryalgo | tryalgo/eulerian_tour.py | https://github.com/jilljenn/tryalgo/blob/89a4dd9655e7b6b0a176f72b4c60d0196420dfe1/tryalgo/eulerian_tour.py#L104-L119 | def is_eulerian_tour(graph, tour):
"""Eulerian tour on an undirected graph
:param graph: directed graph in listlist format, cannot be listdict
:param tour: vertex list
:returns: test if tour is eulerian
:complexity: `O(|V|*|E|)` under the assumption that set membership is in constant ti... | [
"def",
"is_eulerian_tour",
"(",
"graph",
",",
"tour",
")",
":",
"m",
"=",
"len",
"(",
"tour",
")",
"-",
"1",
"arcs",
"=",
"set",
"(",
"(",
"tour",
"[",
"i",
"]",
",",
"tour",
"[",
"i",
"+",
"1",
"]",
")",
"for",
"i",
"in",
"range",
"(",
"m"... | Eulerian tour on an undirected graph
:param graph: directed graph in listlist format, cannot be listdict
:param tour: vertex list
:returns: test if tour is eulerian
:complexity: `O(|V|*|E|)` under the assumption that set membership is in constant time | [
"Eulerian",
"tour",
"on",
"an",
"undirected",
"graph"
] | python | train |
gmr/helper | helper/__init__.py | https://github.com/gmr/helper/blob/fe8e45fc8eabf619429b2940c682c252ee33c082/helper/__init__.py#L149-L171 | def start(controller_class):
"""Start the Helper controller either in the foreground or as a daemon
process.
:param controller_class: The controller class handle to create and run
:type controller_class: callable
"""
args = parser.parse()
obj = controller_class(args, platform.operating_sys... | [
"def",
"start",
"(",
"controller_class",
")",
":",
"args",
"=",
"parser",
".",
"parse",
"(",
")",
"obj",
"=",
"controller_class",
"(",
"args",
",",
"platform",
".",
"operating_system",
"(",
")",
")",
"if",
"args",
".",
"foreground",
":",
"try",
":",
"o... | Start the Helper controller either in the foreground or as a daemon
process.
:param controller_class: The controller class handle to create and run
:type controller_class: callable | [
"Start",
"the",
"Helper",
"controller",
"either",
"in",
"the",
"foreground",
"or",
"as",
"a",
"daemon",
"process",
"."
] | python | train |
isogeo/isogeo-api-py-minsdk | isogeo_pysdk/checker.py | https://github.com/isogeo/isogeo-api-py-minsdk/blob/57a604be92c7767b26abd247012cc1a584b386a0/isogeo_pysdk/checker.py#L283-L306 | def check_is_uuid(self, uuid_str: str):
"""Check if it's an Isogeo UUID handling specific form.
:param str uuid_str: UUID string to check
"""
# check uuid type
if not isinstance(uuid_str, str):
raise TypeError("'uuid_str' expected a str value.")
else:
... | [
"def",
"check_is_uuid",
"(",
"self",
",",
"uuid_str",
":",
"str",
")",
":",
"# check uuid type",
"if",
"not",
"isinstance",
"(",
"uuid_str",
",",
"str",
")",
":",
"raise",
"TypeError",
"(",
"\"'uuid_str' expected a str value.\"",
")",
"else",
":",
"pass",
"# h... | Check if it's an Isogeo UUID handling specific form.
:param str uuid_str: UUID string to check | [
"Check",
"if",
"it",
"s",
"an",
"Isogeo",
"UUID",
"handling",
"specific",
"form",
"."
] | python | train |
openatx/facebook-wda | wda/__init__.py | https://github.com/openatx/facebook-wda/blob/aa644204620c6d5c7705a9c7452d8c0cc39330d5/wda/__init__.py#L707-L721 | def _add_escape_character_for_quote_prime_character(self, text):
"""
Fix for https://github.com/openatx/facebook-wda/issues/33
Returns:
string with properly formated quotes, or non changed text
"""
if text is not None:
if "'" in text:
return text... | [
"def",
"_add_escape_character_for_quote_prime_character",
"(",
"self",
",",
"text",
")",
":",
"if",
"text",
"is",
"not",
"None",
":",
"if",
"\"'\"",
"in",
"text",
":",
"return",
"text",
".",
"replace",
"(",
"\"'\"",
",",
"\"\\\\'\"",
")",
"elif",
"'\"'",
"... | Fix for https://github.com/openatx/facebook-wda/issues/33
Returns:
string with properly formated quotes, or non changed text | [
"Fix",
"for",
"https",
":",
"//",
"github",
".",
"com",
"/",
"openatx",
"/",
"facebook",
"-",
"wda",
"/",
"issues",
"/",
"33",
"Returns",
":",
"string",
"with",
"properly",
"formated",
"quotes",
"or",
"non",
"changed",
"text"
] | python | train |
pypa/pipenv | pipenv/patched/notpip/_internal/utils/misc.py | https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/patched/notpip/_internal/utils/misc.py#L313-L323 | def is_local(path):
# type: (str) -> bool
"""
Return True if path is within sys.prefix, if we're running in a virtualenv.
If we're not in a virtualenv, all paths are considered "local."
"""
if not running_under_virtualenv():
return True
return normalize_path(path).startswith(normal... | [
"def",
"is_local",
"(",
"path",
")",
":",
"# type: (str) -> bool",
"if",
"not",
"running_under_virtualenv",
"(",
")",
":",
"return",
"True",
"return",
"normalize_path",
"(",
"path",
")",
".",
"startswith",
"(",
"normalize_path",
"(",
"sys",
".",
"prefix",
")",... | Return True if path is within sys.prefix, if we're running in a virtualenv.
If we're not in a virtualenv, all paths are considered "local." | [
"Return",
"True",
"if",
"path",
"is",
"within",
"sys",
".",
"prefix",
"if",
"we",
"re",
"running",
"in",
"a",
"virtualenv",
"."
] | python | train |
kata198/AdvancedHTMLParser | AdvancedHTMLParser/Parser.py | https://github.com/kata198/AdvancedHTMLParser/blob/06aeea5d8e2ea86e155aae0fc237623d3e9b7f9d/AdvancedHTMLParser/Parser.py#L1183-L1202 | def getElementsByTagName(self, tagName, root='root', useIndex=True):
'''
getElementsByTagName - Searches and returns all elements with a specific tag name.
@param tagName <lowercase str> - A lowercase string of the tag name.
@param root <AdvancedTag/'... | [
"def",
"getElementsByTagName",
"(",
"self",
",",
"tagName",
",",
"root",
"=",
"'root'",
",",
"useIndex",
"=",
"True",
")",
":",
"(",
"root",
",",
"isFromRoot",
")",
"=",
"self",
".",
"_handleRootArg",
"(",
"root",
")",
"if",
"useIndex",
"is",
"True",
"... | getElementsByTagName - Searches and returns all elements with a specific tag name.
@param tagName <lowercase str> - A lowercase string of the tag name.
@param root <AdvancedTag/'root'> - Search starting at a specific node, if provided. if string 'root', the root of the p... | [
"getElementsByTagName",
"-",
"Searches",
"and",
"returns",
"all",
"elements",
"with",
"a",
"specific",
"tag",
"name",
"."
] | python | train |
infothrill/python-dyndnsc | dyndnsc/conf.py | https://github.com/infothrill/python-dyndnsc/blob/2196d48aa6098da9835a7611fbdb0b5f0fbf51e4/dyndnsc/conf.py#L48-L73 | def _iraw_client_configs(cfg):
"""
Generate (client_name, client_cfg_dict) tuples from the configuration.
Conflates the presets and removes traces of the preset configuration
so that the returned dict can be used directly on a dyndnsc factory.
:param cfg: ConfigParser
"""
client_names = cf... | [
"def",
"_iraw_client_configs",
"(",
"cfg",
")",
":",
"client_names",
"=",
"cfg",
".",
"get",
"(",
"\"dyndnsc\"",
",",
"\"configs\"",
")",
".",
"split",
"(",
"\",\"",
")",
"_preset_prefix",
"=",
"\"preset:\"",
"_use_preset",
"=",
"\"use_preset\"",
"for",
"clien... | Generate (client_name, client_cfg_dict) tuples from the configuration.
Conflates the presets and removes traces of the preset configuration
so that the returned dict can be used directly on a dyndnsc factory.
:param cfg: ConfigParser | [
"Generate",
"(",
"client_name",
"client_cfg_dict",
")",
"tuples",
"from",
"the",
"configuration",
"."
] | python | train |
hazelcast/hazelcast-python-client | hazelcast/proxy/multi_map.py | https://github.com/hazelcast/hazelcast-python-client/blob/3f6639443c23d6d036aa343f8e094f052250d2c1/hazelcast/proxy/multi_map.py#L271-L284 | def value_count(self, key):
"""
Returns the number of values that match the given key in the multimap.
**Warning: This method uses __hash__ and __eq__ methods of binary form of the key, not the actual implementations
of __hash__ and __eq__ defined in key's class.**
:param key: ... | [
"def",
"value_count",
"(",
"self",
",",
"key",
")",
":",
"check_not_none",
"(",
"key",
",",
"\"key can't be None\"",
")",
"key_data",
"=",
"self",
".",
"_to_data",
"(",
"key",
")",
"return",
"self",
".",
"_encode_invoke_on_key",
"(",
"multi_map_value_count_codec... | Returns the number of values that match the given key in the multimap.
**Warning: This method uses __hash__ and __eq__ methods of binary form of the key, not the actual implementations
of __hash__ and __eq__ defined in key's class.**
:param key: (object), the key whose values count is to be re... | [
"Returns",
"the",
"number",
"of",
"values",
"that",
"match",
"the",
"given",
"key",
"in",
"the",
"multimap",
"."
] | python | train |
SUNCAT-Center/CatHub | cathub/cathubsqlite.py | https://github.com/SUNCAT-Center/CatHub/blob/324625d1d8e740673f139658b2de4c9e1059739e/cathub/cathubsqlite.py#L353-L372 | def get_last_id(self, cur, table='reaction'):
"""
Get the id of the last written row in table
Parameters
----------
cur: database connection().cursor() object
table: str
'reaction', 'publication', 'publication_system', 'reaction_system'
Returns: id
... | [
"def",
"get_last_id",
"(",
"self",
",",
"cur",
",",
"table",
"=",
"'reaction'",
")",
":",
"cur",
".",
"execute",
"(",
"\"SELECT seq FROM sqlite_sequence WHERE name='{0}'\"",
".",
"format",
"(",
"table",
")",
")",
"result",
"=",
"cur",
".",
"fetchone",
"(",
"... | Get the id of the last written row in table
Parameters
----------
cur: database connection().cursor() object
table: str
'reaction', 'publication', 'publication_system', 'reaction_system'
Returns: id | [
"Get",
"the",
"id",
"of",
"the",
"last",
"written",
"row",
"in",
"table"
] | python | train |
fishtown-analytics/dbt | core/dbt/adapters/cache.py | https://github.com/fishtown-analytics/dbt/blob/aa4f771df28b307af0cf9fe2fc24432f10a8236b/core/dbt/adapters/cache.py#L116-L135 | def rename(self, new_relation):
"""Rename this cached relation to new_relation.
Note that this will change the output of key(), all refs must be
updated!
:param _CachedRelation new_relation: The new name to apply to the
relation
"""
# Relations store this stu... | [
"def",
"rename",
"(",
"self",
",",
"new_relation",
")",
":",
"# Relations store this stuff inside their `path` dict. But they",
"# also store a table_name, and usually use it in their .render(),",
"# so we need to update that as well. It doesn't appear that",
"# table_name is ever anything bu... | Rename this cached relation to new_relation.
Note that this will change the output of key(), all refs must be
updated!
:param _CachedRelation new_relation: The new name to apply to the
relation | [
"Rename",
"this",
"cached",
"relation",
"to",
"new_relation",
".",
"Note",
"that",
"this",
"will",
"change",
"the",
"output",
"of",
"key",
"()",
"all",
"refs",
"must",
"be",
"updated!"
] | python | train |
dcaune/perseus-lib-python-common | exifread/utils.py | https://github.com/dcaune/perseus-lib-python-common/blob/ba48fe0fd9bb4a75b53e7d10c41ada36a72d4496/exifread/utils.py#L12-L27 | def make_string(seq):
"""
Don't throw an exception when given an out of range character.
"""
string = ''
for c in seq:
# Screen out non-printing characters
try:
if 32 <= c and c < 256:
string += chr(c)
except TypeError:
pass
# I... | [
"def",
"make_string",
"(",
"seq",
")",
":",
"string",
"=",
"''",
"for",
"c",
"in",
"seq",
":",
"# Screen out non-printing characters",
"try",
":",
"if",
"32",
"<=",
"c",
"and",
"c",
"<",
"256",
":",
"string",
"+=",
"chr",
"(",
"c",
")",
"except",
"Ty... | Don't throw an exception when given an out of range character. | [
"Don",
"t",
"throw",
"an",
"exception",
"when",
"given",
"an",
"out",
"of",
"range",
"character",
"."
] | python | train |
openthread/openthread | tools/harness-thci/OpenThread_WpanCtl.py | https://github.com/openthread/openthread/blob/0208d10563aa21c518092985c78ecf9cd223ab74/tools/harness-thci/OpenThread_WpanCtl.py#L2238-L2269 | def MGMT_ACTIVE_GET(self, Addr='', TLVs=[]):
"""send MGMT_ACTIVE_GET command
Returns:
True: successful to send MGMT_ACTIVE_GET
False: fail to send MGMT_ACTIVE_GET
"""
print '%s call MGMT_ACTIVE_GET' % self.port
try:
cmd = WPANCTL_CMD + 'datas... | [
"def",
"MGMT_ACTIVE_GET",
"(",
"self",
",",
"Addr",
"=",
"''",
",",
"TLVs",
"=",
"[",
"]",
")",
":",
"print",
"'%s call MGMT_ACTIVE_GET'",
"%",
"self",
".",
"port",
"try",
":",
"cmd",
"=",
"WPANCTL_CMD",
"+",
"'dataset mgmt-get-active'",
"if",
"len",
"(",
... | send MGMT_ACTIVE_GET command
Returns:
True: successful to send MGMT_ACTIVE_GET
False: fail to send MGMT_ACTIVE_GET | [
"send",
"MGMT_ACTIVE_GET",
"command"
] | python | train |
saltstack/salt | salt/cloud/clouds/ec2.py | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/cloud/clouds/ec2.py#L4696-L4736 | def copy_snapshot(kwargs=None, call=None):
'''
Copy a snapshot
'''
if call != 'function':
log.error(
'The copy_snapshot function must be called with -f or --function.'
)
return False
if 'source_region' not in kwargs:
log.error('A source_region must be spe... | [
"def",
"copy_snapshot",
"(",
"kwargs",
"=",
"None",
",",
"call",
"=",
"None",
")",
":",
"if",
"call",
"!=",
"'function'",
":",
"log",
".",
"error",
"(",
"'The copy_snapshot function must be called with -f or --function.'",
")",
"return",
"False",
"if",
"'source_re... | Copy a snapshot | [
"Copy",
"a",
"snapshot"
] | python | train |
datastax/python-driver | cassandra/concurrent.py | https://github.com/datastax/python-driver/blob/30a80d0b798b1f45f8cb77163b1fa791f3e3ca29/cassandra/concurrent.py#L226-L238 | def execute_concurrent_with_args(session, statement, parameters, *args, **kwargs):
"""
Like :meth:`~cassandra.concurrent.execute_concurrent()`, but takes a single
statement and a sequence of parameters. Each item in ``parameters``
should be a sequence or :const:`None`.
Example usage::
sta... | [
"def",
"execute_concurrent_with_args",
"(",
"session",
",",
"statement",
",",
"parameters",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"return",
"execute_concurrent",
"(",
"session",
",",
"zip",
"(",
"cycle",
"(",
"(",
"statement",
",",
")",
")",... | Like :meth:`~cassandra.concurrent.execute_concurrent()`, but takes a single
statement and a sequence of parameters. Each item in ``parameters``
should be a sequence or :const:`None`.
Example usage::
statement = session.prepare("INSERT INTO mytable (a, b) VALUES (1, ?)")
parameters = [(x,)... | [
"Like",
":",
"meth",
":",
"~cassandra",
".",
"concurrent",
".",
"execute_concurrent",
"()",
"but",
"takes",
"a",
"single",
"statement",
"and",
"a",
"sequence",
"of",
"parameters",
".",
"Each",
"item",
"in",
"parameters",
"should",
"be",
"a",
"sequence",
"or"... | python | train |
sods/ods | pods/datasets.py | https://github.com/sods/ods/blob/3995c659f25a0a640f6009ed7fcc2559ce659b1d/pods/datasets.py#L1122-L1155 | def airline_delay(data_set='airline_delay', num_train=700000, num_test=100000, seed=default_seed):
"""Airline delay data used in Gaussian Processes for Big Data by Hensman, Fusi and Lawrence"""
if not data_available(data_set):
download_data(data_set)
dir_path = os.path.join(data_path, data_set)
... | [
"def",
"airline_delay",
"(",
"data_set",
"=",
"'airline_delay'",
",",
"num_train",
"=",
"700000",
",",
"num_test",
"=",
"100000",
",",
"seed",
"=",
"default_seed",
")",
":",
"if",
"not",
"data_available",
"(",
"data_set",
")",
":",
"download_data",
"(",
"dat... | Airline delay data used in Gaussian Processes for Big Data by Hensman, Fusi and Lawrence | [
"Airline",
"delay",
"data",
"used",
"in",
"Gaussian",
"Processes",
"for",
"Big",
"Data",
"by",
"Hensman",
"Fusi",
"and",
"Lawrence"
] | python | train |
Opentrons/opentrons | api/src/opentrons/drivers/smoothie_drivers/driver_3_0.py | https://github.com/Opentrons/opentrons/blob/a7c15cc2636ecb64ab56c7edc1d8a57163aaeadf/api/src/opentrons/drivers/smoothie_drivers/driver_3_0.py#L501-L511 | def position(self):
"""
Instead of sending M114.2 we are storing target values in
self._position since movement and home commands are blocking and
assumed to go the correct place.
Cases where Smoothie would not be in the correct place (such as if a
belt slips) would not ... | [
"def",
"position",
"(",
"self",
")",
":",
"return",
"{",
"k",
".",
"upper",
"(",
")",
":",
"v",
"for",
"k",
",",
"v",
"in",
"self",
".",
"_position",
".",
"items",
"(",
")",
"}"
] | Instead of sending M114.2 we are storing target values in
self._position since movement and home commands are blocking and
assumed to go the correct place.
Cases where Smoothie would not be in the correct place (such as if a
belt slips) would not be corrected by getting position with M1... | [
"Instead",
"of",
"sending",
"M114",
".",
"2",
"we",
"are",
"storing",
"target",
"values",
"in",
"self",
".",
"_position",
"since",
"movement",
"and",
"home",
"commands",
"are",
"blocking",
"and",
"assumed",
"to",
"go",
"the",
"correct",
"place",
"."
] | python | train |
pyviz/holoviews | holoviews/plotting/bokeh/styles.py | https://github.com/pyviz/holoviews/blob/ae0dd2f3de448b0ca5e9065aabd6ef8d84c7e655/holoviews/plotting/bokeh/styles.py#L115-L140 | def validate(style, value, scalar=False):
"""
Validates a style and associated value.
Arguments
---------
style: str
The style to validate (e.g. 'color', 'size' or 'marker')
value:
The style value to validate
scalar: bool
Returns
-------
valid: boolean or None
... | [
"def",
"validate",
"(",
"style",
",",
"value",
",",
"scalar",
"=",
"False",
")",
":",
"validator",
"=",
"get_validator",
"(",
"style",
")",
"if",
"validator",
"is",
"None",
":",
"return",
"None",
"if",
"isinstance",
"(",
"value",
",",
"(",
"np",
".",
... | Validates a style and associated value.
Arguments
---------
style: str
The style to validate (e.g. 'color', 'size' or 'marker')
value:
The style value to validate
scalar: bool
Returns
-------
valid: boolean or None
If validation is supported returns boolean, othe... | [
"Validates",
"a",
"style",
"and",
"associated",
"value",
"."
] | python | train |
vertexproject/synapse | synapse/lib/msgpack.py | https://github.com/vertexproject/synapse/blob/22e67c5a8f6d7caddbcf34b39ab1bd2d6c4a6e0b/synapse/lib/msgpack.py#L168-L180 | def dumpfile(item, path):
'''
Dump an object to a file by path.
Args:
item (object): The object to serialize.
path (str): The file path to save.
Returns:
None
'''
with io.open(path, 'wb') as fd:
fd.write(en(item)) | [
"def",
"dumpfile",
"(",
"item",
",",
"path",
")",
":",
"with",
"io",
".",
"open",
"(",
"path",
",",
"'wb'",
")",
"as",
"fd",
":",
"fd",
".",
"write",
"(",
"en",
"(",
"item",
")",
")"
] | Dump an object to a file by path.
Args:
item (object): The object to serialize.
path (str): The file path to save.
Returns:
None | [
"Dump",
"an",
"object",
"to",
"a",
"file",
"by",
"path",
"."
] | python | train |
wbond/asn1crypto | asn1crypto/core.py | https://github.com/wbond/asn1crypto/blob/ecda20176f55d37021cbca1f6da9083a8e491197/asn1crypto/core.py#L4224-L4258 | def _parse_children(self, recurse=False):
"""
Parses the contents and generates Asn1Value objects based on the
definitions from _child_spec.
:param recurse:
If child objects that are Sequence or SequenceOf objects should
be recursively parsed
:raises:
... | [
"def",
"_parse_children",
"(",
"self",
",",
"recurse",
"=",
"False",
")",
":",
"try",
":",
"self",
".",
"children",
"=",
"[",
"]",
"if",
"self",
".",
"_contents",
"is",
"None",
":",
"return",
"contents_length",
"=",
"len",
"(",
"self",
".",
"_contents"... | Parses the contents and generates Asn1Value objects based on the
definitions from _child_spec.
:param recurse:
If child objects that are Sequence or SequenceOf objects should
be recursively parsed
:raises:
ValueError - when an error occurs parsing child obje... | [
"Parses",
"the",
"contents",
"and",
"generates",
"Asn1Value",
"objects",
"based",
"on",
"the",
"definitions",
"from",
"_child_spec",
"."
] | python | train |
openstack/hacking | hacking/checks/docstrings.py | https://github.com/openstack/hacking/blob/10e58f907181cac91d3b2af422c2458b04a1ec79/hacking/checks/docstrings.py#L103-L125 | def hacking_docstring_summary(physical_line, previous_logical, tokens):
r"""Check multi line docstring summary is separated with empty line.
OpenStack HACKING guide recommendation for docstring:
Docstring should start with a one-line summary, less than 80 characters.
Okay: def foo():\n a = '''\nnot... | [
"def",
"hacking_docstring_summary",
"(",
"physical_line",
",",
"previous_logical",
",",
"tokens",
")",
":",
"docstring",
"=",
"is_docstring",
"(",
"tokens",
",",
"previous_logical",
")",
"if",
"docstring",
":",
"if",
"'\\n'",
"not",
"in",
"docstring",
":",
"# no... | r"""Check multi line docstring summary is separated with empty line.
OpenStack HACKING guide recommendation for docstring:
Docstring should start with a one-line summary, less than 80 characters.
Okay: def foo():\n a = '''\nnot\na docstring\n'''
Okay: '''foobar\n\nfoo\nbar\n'''
H405: def foo():... | [
"r",
"Check",
"multi",
"line",
"docstring",
"summary",
"is",
"separated",
"with",
"empty",
"line",
"."
] | python | train |
openstack/proliantutils | proliantutils/redfish/redfish.py | https://github.com/openstack/proliantutils/blob/86ef3b47b4eca97c221577e3570b0240d6a25f22/proliantutils/redfish/redfish.py#L1042-L1053 | def get_host_post_state(self):
"""Get the current state of system POST.
Retrieves current state of system POST.
:returns: POST state of the server. The valida states are:-
null, Unknown, Reset, PowerOff, InPost,
InPostDiscoveryComplete and FinishedPost.
... | [
"def",
"get_host_post_state",
"(",
"self",
")",
":",
"sushy_system",
"=",
"self",
".",
"_get_sushy_system",
"(",
"PROLIANT_SYSTEM_ID",
")",
"return",
"GET_POST_STATE_MAP",
".",
"get",
"(",
"sushy_system",
".",
"post_state",
")"
] | Get the current state of system POST.
Retrieves current state of system POST.
:returns: POST state of the server. The valida states are:-
null, Unknown, Reset, PowerOff, InPost,
InPostDiscoveryComplete and FinishedPost.
:raises: IloError, on an error from iL... | [
"Get",
"the",
"current",
"state",
"of",
"system",
"POST",
"."
] | python | train |
PmagPy/PmagPy | pmagpy/pmagplotlib.py | https://github.com/PmagPy/PmagPy/blob/c7984f8809bf40fe112e53dcc311a33293b62d0b/pmagpy/pmagplotlib.py#L3674-L3722 | def plot_ts(ax, agemin, agemax, timescale='gts12', ylabel="Age (Ma)"):
"""
Make a time scale plot between specified ages.
Parameters:
------------
ax : figure object
agemin : Minimum age for timescale
agemax : Maximum age for timescale
timescale : Time Scale [ default is Gradstein et al... | [
"def",
"plot_ts",
"(",
"ax",
",",
"agemin",
",",
"agemax",
",",
"timescale",
"=",
"'gts12'",
",",
"ylabel",
"=",
"\"Age (Ma)\"",
")",
":",
"ax",
".",
"set_title",
"(",
"timescale",
".",
"upper",
"(",
")",
")",
"ax",
".",
"axis",
"(",
"[",
"-",
".25... | Make a time scale plot between specified ages.
Parameters:
------------
ax : figure object
agemin : Minimum age for timescale
agemax : Maximum age for timescale
timescale : Time Scale [ default is Gradstein et al., (2012)]
for other options see pmag.get_ts()
ylabel : if set, plot as ... | [
"Make",
"a",
"time",
"scale",
"plot",
"between",
"specified",
"ages",
"."
] | python | train |
pgmpy/pgmpy | pgmpy/models/MarkovChain.py | https://github.com/pgmpy/pgmpy/blob/9381a66aba3c3871d3ccd00672b148d17d63239e/pgmpy/models/MarkovChain.py#L440-L469 | def copy(self):
"""
Returns a copy of Markov Chain Model.
Return Type:
------------
MarkovChain : Copy of MarkovChain.
Examples:
---------
>>> from pgmpy.models import MarkovChain
>>> from pgmpy.factors.discrete import State
>>> model = M... | [
"def",
"copy",
"(",
"self",
")",
":",
"markovchain_copy",
"=",
"MarkovChain",
"(",
"variables",
"=",
"list",
"(",
"self",
".",
"cardinalities",
".",
"keys",
"(",
")",
")",
",",
"card",
"=",
"list",
"(",
"self",
".",
"cardinalities",
".",
"values",
"(",... | Returns a copy of Markov Chain Model.
Return Type:
------------
MarkovChain : Copy of MarkovChain.
Examples:
---------
>>> from pgmpy.models import MarkovChain
>>> from pgmpy.factors.discrete import State
>>> model = MarkovChain()
>>> model.add_v... | [
"Returns",
"a",
"copy",
"of",
"Markov",
"Chain",
"Model",
"."
] | python | train |
marcinn/sqltemplate | sqltemplate/contrib/django/loader.py | https://github.com/marcinn/sqltemplate/blob/28d26ebcc474b8c37942218adfa9f54e89327ce0/sqltemplate/contrib/django/loader.py#L53-L62 | def render_to_string(template_name, context=None, request=None, using=None):
"""
Loads a template and renders it with a context. Returns a string.
template_name may be a string or a list of strings.
"""
if isinstance(template_name, (list, tuple)):
template = select_template(template_name, us... | [
"def",
"render_to_string",
"(",
"template_name",
",",
"context",
"=",
"None",
",",
"request",
"=",
"None",
",",
"using",
"=",
"None",
")",
":",
"if",
"isinstance",
"(",
"template_name",
",",
"(",
"list",
",",
"tuple",
")",
")",
":",
"template",
"=",
"s... | Loads a template and renders it with a context. Returns a string.
template_name may be a string or a list of strings. | [
"Loads",
"a",
"template",
"and",
"renders",
"it",
"with",
"a",
"context",
".",
"Returns",
"a",
"string",
".",
"template_name",
"may",
"be",
"a",
"string",
"or",
"a",
"list",
"of",
"strings",
"."
] | python | train |
UCBerkeleySETI/blimpy | blimpy/filterbank.py | https://github.com/UCBerkeleySETI/blimpy/blob/b8822d3e3e911944370d84371a91fa0c29e9772e/blimpy/filterbank.py#L968-L974 | def calibrate_band_pass_N1(self):
""" One way to calibrate the band pass is to take the median value
for every frequency fine channel, and divide by it.
"""
band_pass = np.median(self.data.squeeze(),axis=0)
self.data = self.data/band_pass | [
"def",
"calibrate_band_pass_N1",
"(",
"self",
")",
":",
"band_pass",
"=",
"np",
".",
"median",
"(",
"self",
".",
"data",
".",
"squeeze",
"(",
")",
",",
"axis",
"=",
"0",
")",
"self",
".",
"data",
"=",
"self",
".",
"data",
"/",
"band_pass"
] | One way to calibrate the band pass is to take the median value
for every frequency fine channel, and divide by it. | [
"One",
"way",
"to",
"calibrate",
"the",
"band",
"pass",
"is",
"to",
"take",
"the",
"median",
"value",
"for",
"every",
"frequency",
"fine",
"channel",
"and",
"divide",
"by",
"it",
"."
] | python | test |
inasafe/inasafe | safe/gui/tools/wizard/step_fc00_functions1.py | https://github.com/inasafe/inasafe/blob/831d60abba919f6d481dc94a8d988cc205130724/safe/gui/tools/wizard/step_fc00_functions1.py#L159-L166 | def set_widgets(self):
"""Set widgets on the Impact Functions Table 1 tab."""
self.tblFunctions1.horizontalHeader().setSectionResizeMode(
QHeaderView.Stretch)
self.tblFunctions1.verticalHeader().setSectionResizeMode(
QHeaderView.Stretch)
self.populate_function_ta... | [
"def",
"set_widgets",
"(",
"self",
")",
":",
"self",
".",
"tblFunctions1",
".",
"horizontalHeader",
"(",
")",
".",
"setSectionResizeMode",
"(",
"QHeaderView",
".",
"Stretch",
")",
"self",
".",
"tblFunctions1",
".",
"verticalHeader",
"(",
")",
".",
"setSectionR... | Set widgets on the Impact Functions Table 1 tab. | [
"Set",
"widgets",
"on",
"the",
"Impact",
"Functions",
"Table",
"1",
"tab",
"."
] | python | train |
CivicSpleen/ambry | ambry/orm/column.py | https://github.com/CivicSpleen/ambry/blob/d7f2be4bf1f7ffd086f3fadd4fcae60c32473e42/ambry/orm/column.py#L285-L295 | def label(self):
""""Return first child of the column that is marked as a label. Returns self if the column is a label"""
if self.valuetype_class.is_label():
return self
for c in self.table.columns:
if c.parent == self.name and c.valuetype_class.is_label():
... | [
"def",
"label",
"(",
"self",
")",
":",
"if",
"self",
".",
"valuetype_class",
".",
"is_label",
"(",
")",
":",
"return",
"self",
"for",
"c",
"in",
"self",
".",
"table",
".",
"columns",
":",
"if",
"c",
".",
"parent",
"==",
"self",
".",
"name",
"and",
... | Return first child of the column that is marked as a label. Returns self if the column is a label | [
"Return",
"first",
"child",
"of",
"the",
"column",
"that",
"is",
"marked",
"as",
"a",
"label",
".",
"Returns",
"self",
"if",
"the",
"column",
"is",
"a",
"label"
] | python | train |
nmdp-bioinformatics/SeqAnn | seqann/util.py | https://github.com/nmdp-bioinformatics/SeqAnn/blob/5ce91559b0a4fbe4fb7758e034eb258202632463/seqann/util.py#L36-L45 | def checkseq(sequence: str=None, code="ATGC") -> bool:
"""
:param sequence: The input sequence.
:type sequence: Seq
:rtype: bool
"""
for base in sequence:
if base not in code:
return False
return True | [
"def",
"checkseq",
"(",
"sequence",
":",
"str",
"=",
"None",
",",
"code",
"=",
"\"ATGC\"",
")",
"->",
"bool",
":",
"for",
"base",
"in",
"sequence",
":",
"if",
"base",
"not",
"in",
"code",
":",
"return",
"False",
"return",
"True"
] | :param sequence: The input sequence.
:type sequence: Seq
:rtype: bool | [
":",
"param",
"sequence",
":",
"The",
"input",
"sequence",
".",
":",
"type",
"sequence",
":",
"Seq",
":",
"rtype",
":",
"bool"
] | python | train |
Autodesk/aomi | aomi/cli.py | https://github.com/Autodesk/aomi/blob/84da2dfb0424837adf9c4ddc1aa352e942bb7a4a/aomi/cli.py#L370-L385 | def template_runner(client, parser, args):
"""Executes template related operations"""
if args.builtin_list:
aomi.template.builtin_list()
elif args.builtin_info:
aomi.template.builtin_info(args.builtin_info)
elif args.template and args.destination and args.vault_paths:
aomi.render... | [
"def",
"template_runner",
"(",
"client",
",",
"parser",
",",
"args",
")",
":",
"if",
"args",
".",
"builtin_list",
":",
"aomi",
".",
"template",
".",
"builtin_list",
"(",
")",
"elif",
"args",
".",
"builtin_info",
":",
"aomi",
".",
"template",
".",
"builti... | Executes template related operations | [
"Executes",
"template",
"related",
"operations"
] | python | train |
JohnDoee/thomas | thomas/outputs/http.py | https://github.com/JohnDoee/thomas/blob/51916dd110098b189a1c2fbcb71794fd9ec94832/thomas/outputs/http.py#L316-L334 | def render_GET(self, request):
"""
Begin sending the contents of this L{File} (or a subset of the
contents, based on the 'range' header) to the given request.
"""
request.setHeader(b'accept-ranges', b'bytes')
producer = self.makeProducer(request, self.fileObject)
... | [
"def",
"render_GET",
"(",
"self",
",",
"request",
")",
":",
"request",
".",
"setHeader",
"(",
"b'accept-ranges'",
",",
"b'bytes'",
")",
"producer",
"=",
"self",
".",
"makeProducer",
"(",
"request",
",",
"self",
".",
"fileObject",
")",
"if",
"request",
".",... | Begin sending the contents of this L{File} (or a subset of the
contents, based on the 'range' header) to the given request. | [
"Begin",
"sending",
"the",
"contents",
"of",
"this",
"L",
"{",
"File",
"}",
"(",
"or",
"a",
"subset",
"of",
"the",
"contents",
"based",
"on",
"the",
"range",
"header",
")",
"to",
"the",
"given",
"request",
"."
] | python | train |
BD2KGenomics/protect | docker/pipelineWrapper.py | https://github.com/BD2KGenomics/protect/blob/06310682c50dcf8917b912c8e551299ff7ee41ce/docker/pipelineWrapper.py#L170-L188 | def get_args(self):
"""
Use this context manager to add arguments to an argparse object with the add_argument
method. Arguments must be defined before the command is defined. Note that
no-clean and resume are added upon exit and should not be added in the context manager. For
mor... | [
"def",
"get_args",
"(",
"self",
")",
":",
"parser",
"=",
"argparse",
".",
"ArgumentParser",
"(",
"description",
"=",
"self",
".",
"_desc",
",",
"formatter_class",
"=",
"MyUniversalHelpFormatter",
")",
"# default args",
"if",
"self",
".",
"_no_clean",
":",
"par... | Use this context manager to add arguments to an argparse object with the add_argument
method. Arguments must be defined before the command is defined. Note that
no-clean and resume are added upon exit and should not be added in the context manager. For
more info about these default arguments see... | [
"Use",
"this",
"context",
"manager",
"to",
"add",
"arguments",
"to",
"an",
"argparse",
"object",
"with",
"the",
"add_argument",
"method",
".",
"Arguments",
"must",
"be",
"defined",
"before",
"the",
"command",
"is",
"defined",
".",
"Note",
"that",
"no",
"-",
... | python | train |
marrow/WebCore | web/server/fcgi.py | https://github.com/marrow/WebCore/blob/38d50f8022ca62976a1e5ff23f7714bd647b6532/web/server/fcgi.py#L18-L31 | def serve(application, host='127.0.0.1', port=8080, socket=None, **options):
"""Basic FastCGI support via flup.
This web server has many, many options. Please see the Flup project documentation for details.
"""
# Allow either on-disk socket (recommended) or TCP/IP socket use.
if not socket:
bindAddress = (ho... | [
"def",
"serve",
"(",
"application",
",",
"host",
"=",
"'127.0.0.1'",
",",
"port",
"=",
"8080",
",",
"socket",
"=",
"None",
",",
"*",
"*",
"options",
")",
":",
"# Allow either on-disk socket (recommended) or TCP/IP socket use.",
"if",
"not",
"socket",
":",
"bindA... | Basic FastCGI support via flup.
This web server has many, many options. Please see the Flup project documentation for details. | [
"Basic",
"FastCGI",
"support",
"via",
"flup",
".",
"This",
"web",
"server",
"has",
"many",
"many",
"options",
".",
"Please",
"see",
"the",
"Flup",
"project",
"documentation",
"for",
"details",
"."
] | python | train |
draperjames/qtpandas | qtpandas/ui/fallback/easygui/boxes/base_boxes.py | https://github.com/draperjames/qtpandas/blob/64294fb69f1839e53dee5ea453337266bfaf24f4/qtpandas/ui/fallback/easygui/boxes/base_boxes.py#L828-L916 | def fileopenbox(msg=None, title=None, default='*', filetypes=None, multiple=False):
"""
A dialog to get a file name.
**About the "default" argument**
The "default" argument specifies a filepath that (normally)
contains one or more wildcards.
fileopenbox will display only files that match the d... | [
"def",
"fileopenbox",
"(",
"msg",
"=",
"None",
",",
"title",
"=",
"None",
",",
"default",
"=",
"'*'",
",",
"filetypes",
"=",
"None",
",",
"multiple",
"=",
"False",
")",
":",
"localRoot",
"=",
"Tk",
"(",
")",
"localRoot",
".",
"withdraw",
"(",
")",
... | A dialog to get a file name.
**About the "default" argument**
The "default" argument specifies a filepath that (normally)
contains one or more wildcards.
fileopenbox will display only files that match the default filepath.
If omitted, defaults to "\*" (all files in the current directory).
WIN... | [
"A",
"dialog",
"to",
"get",
"a",
"file",
"name",
"."
] | python | train |
brian-rose/climlab | climlab/domain/xarray.py | https://github.com/brian-rose/climlab/blob/eae188a2ae9308229b8cbb8fe0b65f51b50ee1e6/climlab/domain/xarray.py#L32-L60 | def state_to_xarray(state):
'''Convert a dictionary of climlab.Field objects to xarray.Dataset
Input: dictionary of climlab.Field objects
(e.g. process.state or process.diagnostics dictionary)
Output: xarray.Dataset object with all spatial axes,
including 'bounds' axes indicating cell boundaries i... | [
"def",
"state_to_xarray",
"(",
"state",
")",
":",
"from",
"climlab",
".",
"domain",
".",
"field",
"import",
"Field",
"ds",
"=",
"Dataset",
"(",
")",
"for",
"name",
",",
"field",
"in",
"state",
".",
"items",
"(",
")",
":",
"if",
"isinstance",
"(",
"fi... | Convert a dictionary of climlab.Field objects to xarray.Dataset
Input: dictionary of climlab.Field objects
(e.g. process.state or process.diagnostics dictionary)
Output: xarray.Dataset object with all spatial axes,
including 'bounds' axes indicating cell boundaries in each spatial dimension.
Any ... | [
"Convert",
"a",
"dictionary",
"of",
"climlab",
".",
"Field",
"objects",
"to",
"xarray",
".",
"Dataset"
] | python | train |
PMEAL/OpenPNM | openpnm/core/Base.py | https://github.com/PMEAL/OpenPNM/blob/0547b5724ffedc0a593aae48639d36fe10e0baed/openpnm/core/Base.py#L327-L395 | def keys(self, element=None, mode=None):
r"""
This subclass works exactly like ``keys`` when no arguments are passed,
but optionally accepts an ``element`` and/or a ``mode``, which filters
the output to only the requested keys.
The default behavior is exactly equivalent to the n... | [
"def",
"keys",
"(",
"self",
",",
"element",
"=",
"None",
",",
"mode",
"=",
"None",
")",
":",
"if",
"mode",
"is",
"None",
":",
"return",
"super",
"(",
")",
".",
"keys",
"(",
")",
"element",
"=",
"self",
".",
"_parse_element",
"(",
"element",
"=",
... | r"""
This subclass works exactly like ``keys`` when no arguments are passed,
but optionally accepts an ``element`` and/or a ``mode``, which filters
the output to only the requested keys.
The default behavior is exactly equivalent to the normal ``keys``
method.
Parameter... | [
"r",
"This",
"subclass",
"works",
"exactly",
"like",
"keys",
"when",
"no",
"arguments",
"are",
"passed",
"but",
"optionally",
"accepts",
"an",
"element",
"and",
"/",
"or",
"a",
"mode",
"which",
"filters",
"the",
"output",
"to",
"only",
"the",
"requested",
... | python | train |
pywbem/pywbem | wbemcli.py | https://github.com/pywbem/pywbem/blob/e54ecb82c2211e289a268567443d60fdd489f1e4/wbemcli.py#L173-L241 | def _remote_connection(server, opts, argparser_):
"""Initiate a remote connection, via PyWBEM. Arguments for
the request are part of the command line arguments and include
user name, password, namespace, etc.
"""
global CONN # pylint: disable=global-statement
if opts.timeout is not N... | [
"def",
"_remote_connection",
"(",
"server",
",",
"opts",
",",
"argparser_",
")",
":",
"global",
"CONN",
"# pylint: disable=global-statement",
"if",
"opts",
".",
"timeout",
"is",
"not",
"None",
":",
"if",
"opts",
".",
"timeout",
"<",
"0",
"or",
"opts",
".",
... | Initiate a remote connection, via PyWBEM. Arguments for
the request are part of the command line arguments and include
user name, password, namespace, etc. | [
"Initiate",
"a",
"remote",
"connection",
"via",
"PyWBEM",
".",
"Arguments",
"for",
"the",
"request",
"are",
"part",
"of",
"the",
"command",
"line",
"arguments",
"and",
"include",
"user",
"name",
"password",
"namespace",
"etc",
"."
] | python | train |
nats-io/asyncio-nats | nats/aio/client.py | https://github.com/nats-io/asyncio-nats/blob/39e840be0b12ce326edac0bba69aeb1be930dcb8/nats/aio/client.py#L338-L380 | def drain(self, sid=None):
"""
Drain will put a connection into a drain state. All subscriptions will
immediately be put into a drain state. Upon completion, the publishers
will be drained and can not publish any additional messages. Upon draining
of the publishers, the connectio... | [
"def",
"drain",
"(",
"self",
",",
"sid",
"=",
"None",
")",
":",
"if",
"self",
".",
"is_draining",
":",
"return",
"if",
"self",
".",
"is_closed",
":",
"raise",
"ErrConnectionClosed",
"if",
"self",
".",
"is_connecting",
"or",
"self",
".",
"is_reconnecting",
... | Drain will put a connection into a drain state. All subscriptions will
immediately be put into a drain state. Upon completion, the publishers
will be drained and can not publish any additional messages. Upon draining
of the publishers, the connection will be closed. Use the `closed_cb'
o... | [
"Drain",
"will",
"put",
"a",
"connection",
"into",
"a",
"drain",
"state",
".",
"All",
"subscriptions",
"will",
"immediately",
"be",
"put",
"into",
"a",
"drain",
"state",
".",
"Upon",
"completion",
"the",
"publishers",
"will",
"be",
"drained",
"and",
"can",
... | python | test |
skulumani/kinematics | kinematics/attitude.py | https://github.com/skulumani/kinematics/blob/e8cb45efb40539982025ed0f85d6561f9f10fef0/kinematics/attitude.py#L388-L509 | def normalize(num_in, lower=0, upper=360, b=False):
"""Normalize number to range [lower, upper) or [lower, upper].
Parameters
----------
num : float
The number to be normalized.
lower : int
Lower limit of range. Default is 0.
upper : int
Upper limit of range. Default is ... | [
"def",
"normalize",
"(",
"num_in",
",",
"lower",
"=",
"0",
",",
"upper",
"=",
"360",
",",
"b",
"=",
"False",
")",
":",
"if",
"lower",
">=",
"upper",
":",
"ValueError",
"(",
"\"lower must be lesser than upper\"",
")",
"if",
"not",
"b",
":",
"if",
"not",... | Normalize number to range [lower, upper) or [lower, upper].
Parameters
----------
num : float
The number to be normalized.
lower : int
Lower limit of range. Default is 0.
upper : int
Upper limit of range. Default is 360.
b : bool
Type of normalization. Default is... | [
"Normalize",
"number",
"to",
"range",
"[",
"lower",
"upper",
")",
"or",
"[",
"lower",
"upper",
"]",
"."
] | python | train |
InfoAgeTech/django-core | django_core/forms/mixins/common.py | https://github.com/InfoAgeTech/django-core/blob/9664a145473b75120bf71e1644e9c8086e7e8955/django_core/forms/mixins/common.py#L36-L58 | def get_default_prefix(self, instance=None):
"""Gets the prefix for this form.
:param instance: the form model instance. When calling this method
directly this should almost always stay None so it looks for
self.instance.
"""
if instance is None and hasattr(self... | [
"def",
"get_default_prefix",
"(",
"self",
",",
"instance",
"=",
"None",
")",
":",
"if",
"instance",
"is",
"None",
"and",
"hasattr",
"(",
"self",
",",
"'instance'",
")",
":",
"instance",
"=",
"self",
".",
"instance",
"if",
"instance",
"and",
"instance",
"... | Gets the prefix for this form.
:param instance: the form model instance. When calling this method
directly this should almost always stay None so it looks for
self.instance. | [
"Gets",
"the",
"prefix",
"for",
"this",
"form",
"."
] | python | train |
dwavesystems/dwave_networkx | dwave_networkx/drawing/qubit_layout.py | https://github.com/dwavesystems/dwave_networkx/blob/9ea1223ddbc7e86db2f90b8b23e250e6642c3d68/dwave_networkx/drawing/qubit_layout.py#L44-L148 | def draw_qubit_graph(G, layout, linear_biases={}, quadratic_biases={},
nodelist=None, edgelist=None, cmap=None, edge_cmap=None, vmin=None, vmax=None,
edge_vmin=None, edge_vmax=None,
**kwargs):
"""Draws graph G according to layout.
If `linear_biases... | [
"def",
"draw_qubit_graph",
"(",
"G",
",",
"layout",
",",
"linear_biases",
"=",
"{",
"}",
",",
"quadratic_biases",
"=",
"{",
"}",
",",
"nodelist",
"=",
"None",
",",
"edgelist",
"=",
"None",
",",
"cmap",
"=",
"None",
",",
"edge_cmap",
"=",
"None",
",",
... | Draws graph G according to layout.
If `linear_biases` and/or `quadratic_biases` are provided, these
are visualized on the plot.
Parameters
----------
G : NetworkX graph
The graph to be drawn
layout : dict
A dict of coordinates associated with each node in G. Should
be... | [
"Draws",
"graph",
"G",
"according",
"to",
"layout",
"."
] | python | train |
senaite/senaite.jsonapi | src/senaite/jsonapi/api.py | https://github.com/senaite/senaite.jsonapi/blob/871959f4b1c9edbb477e9456325527ca78e13ec6/src/senaite/jsonapi/api.py#L1447-L1463 | def validate_object(brain_or_object, data):
"""Validate the entire object
:param brain_or_object: A single catalog brain or content object
:type brain_or_object: ATContentType/DexterityContentType/CatalogBrain
:param data: The sharing dictionary as returned from the API
:type data: dict
:return... | [
"def",
"validate_object",
"(",
"brain_or_object",
",",
"data",
")",
":",
"obj",
"=",
"get_object",
"(",
"brain_or_object",
")",
"# Call the validator of AT Content Types",
"if",
"is_at_content",
"(",
"obj",
")",
":",
"return",
"obj",
".",
"validate",
"(",
"data",
... | Validate the entire object
:param brain_or_object: A single catalog brain or content object
:type brain_or_object: ATContentType/DexterityContentType/CatalogBrain
:param data: The sharing dictionary as returned from the API
:type data: dict
:returns: invalidity status
:rtype: dict | [
"Validate",
"the",
"entire",
"object"
] | python | train |
andycasey/sick | sick/models/base.py | https://github.com/andycasey/sick/blob/6c37686182794c4cafea45abf7062b30b789b1a2/sick/models/base.py#L250-L265 | def _overlapping_channels(self, wavelengths):
"""
Return the channels that match the given wavelength array.
"""
sizes = self.meta["channel_sizes"]
min_a, max_a = wavelengths.min(), wavelengths.max()
matched_channel_names = []
for i, (name, size) in enumerate(zi... | [
"def",
"_overlapping_channels",
"(",
"self",
",",
"wavelengths",
")",
":",
"sizes",
"=",
"self",
".",
"meta",
"[",
"\"channel_sizes\"",
"]",
"min_a",
",",
"max_a",
"=",
"wavelengths",
".",
"min",
"(",
")",
",",
"wavelengths",
".",
"max",
"(",
")",
"match... | Return the channels that match the given wavelength array. | [
"Return",
"the",
"channels",
"that",
"match",
"the",
"given",
"wavelength",
"array",
"."
] | python | train |
materialsproject/pymatgen | pymatgen/core/molecular_orbitals.py | https://github.com/materialsproject/pymatgen/blob/4ca558cf72f8d5f8a1f21dfdfc0181a971c186da/pymatgen/core/molecular_orbitals.py#L83-L119 | def obtain_band_edges(self):
'''
Fill up the atomic orbitals with available electrons.
Return HOMO, LUMO, and whether it's a metal.
'''
orbitals = self.aos_as_list()
electrons = Composition(self.composition).total_electrons
partial_filled = []
for orbital ... | [
"def",
"obtain_band_edges",
"(",
"self",
")",
":",
"orbitals",
"=",
"self",
".",
"aos_as_list",
"(",
")",
"electrons",
"=",
"Composition",
"(",
"self",
".",
"composition",
")",
".",
"total_electrons",
"partial_filled",
"=",
"[",
"]",
"for",
"orbital",
"in",
... | Fill up the atomic orbitals with available electrons.
Return HOMO, LUMO, and whether it's a metal. | [
"Fill",
"up",
"the",
"atomic",
"orbitals",
"with",
"available",
"electrons",
".",
"Return",
"HOMO",
"LUMO",
"and",
"whether",
"it",
"s",
"a",
"metal",
"."
] | python | train |
rycus86/prometheus_flask_exporter | prometheus_flask_exporter/__init__.py | https://github.com/rycus86/prometheus_flask_exporter/blob/678dbf3097e82a0ddb697268406004cc1f4a26bc/prometheus_flask_exporter/__init__.py#L353-L370 | def gauge(self, name, description, labels=None, **kwargs):
"""
Use a Gauge to track the number of invocations in progress
for the method.
:param name: the name of the metric
:param description: the description of the metric
:param labels: a dictionary of `{labelname: cal... | [
"def",
"gauge",
"(",
"self",
",",
"name",
",",
"description",
",",
"labels",
"=",
"None",
",",
"*",
"*",
"kwargs",
")",
":",
"return",
"self",
".",
"_track",
"(",
"Gauge",
",",
"lambda",
"metric",
",",
"time",
":",
"metric",
".",
"dec",
"(",
")",
... | Use a Gauge to track the number of invocations in progress
for the method.
:param name: the name of the metric
:param description: the description of the metric
:param labels: a dictionary of `{labelname: callable_or_value}` for labels
:param kwargs: additional keyword arguments... | [
"Use",
"a",
"Gauge",
"to",
"track",
"the",
"number",
"of",
"invocations",
"in",
"progress",
"for",
"the",
"method",
"."
] | python | train |
line/line-bot-sdk-python | linebot/api.py | https://github.com/line/line-bot-sdk-python/blob/1b38bfc2497ff3e3c75be4b50e0f1b7425a07ce0/linebot/api.py#L293-L314 | def get_message_content(self, message_id, timeout=None):
"""Call get content API.
https://devdocs.line.me/en/#get-content
Retrieve image, video, and audio data sent by users.
:param str message_id: Message ID
:param timeout: (optional) How long to wait for the server
... | [
"def",
"get_message_content",
"(",
"self",
",",
"message_id",
",",
"timeout",
"=",
"None",
")",
":",
"response",
"=",
"self",
".",
"_get",
"(",
"'/v2/bot/message/{message_id}/content'",
".",
"format",
"(",
"message_id",
"=",
"message_id",
")",
",",
"stream",
"... | Call get content API.
https://devdocs.line.me/en/#get-content
Retrieve image, video, and audio data sent by users.
:param str message_id: Message ID
:param timeout: (optional) How long to wait for the server
to send data before giving up, as a float,
or a (conn... | [
"Call",
"get",
"content",
"API",
"."
] | python | train |
christophertbrown/bioscripts | ctbBio/16SfromHMM.py | https://github.com/christophertbrown/bioscripts/blob/83b2566b3a5745437ec651cd6cafddd056846240/ctbBio/16SfromHMM.py#L51-L61 | def check_overlap(current, hit, overlap = 200):
"""
determine if sequence has already hit the same part of the model,
indicating that this hit is for another 16S rRNA gene
"""
for prev in current:
p_coords = prev[2:4]
coords = hit[2:4]
if get_overlap(coords, p_coords) >= over... | [
"def",
"check_overlap",
"(",
"current",
",",
"hit",
",",
"overlap",
"=",
"200",
")",
":",
"for",
"prev",
"in",
"current",
":",
"p_coords",
"=",
"prev",
"[",
"2",
":",
"4",
"]",
"coords",
"=",
"hit",
"[",
"2",
":",
"4",
"]",
"if",
"get_overlap",
"... | determine if sequence has already hit the same part of the model,
indicating that this hit is for another 16S rRNA gene | [
"determine",
"if",
"sequence",
"has",
"already",
"hit",
"the",
"same",
"part",
"of",
"the",
"model",
"indicating",
"that",
"this",
"hit",
"is",
"for",
"another",
"16S",
"rRNA",
"gene"
] | python | train |
archman/beamline | beamline/lattice.py | https://github.com/archman/beamline/blob/417bc5dc13e754bc89d246427984590fced64d07/beamline/lattice.py#L165-L211 | def getKw(self, kw):
""" Extract doc snippet for element configuration,
:param kw: element name
:return: instance itself
1 call getKwAsDict() to return config as a dict
2 call getKwAsJson() to return config as json string
3 call getKwAsStri... | [
"def",
"getKw",
"(",
"self",
",",
"kw",
")",
":",
"ikw",
"=",
"kw",
".",
"lower",
"(",
")",
"line_continue_flag",
"=",
"''",
"appendflag",
"=",
"False",
"try",
":",
"for",
"line",
"in",
"self",
".",
"file_lines",
":",
"if",
"line",
".",
"strip",
"(... | Extract doc snippet for element configuration,
:param kw: element name
:return: instance itself
1 call getKwAsDict() to return config as a dict
2 call getKwAsJson() to return config as json string
3 call getKwAsString() to return config as a raw st... | [
"Extract",
"doc",
"snippet",
"for",
"element",
"configuration",
":",
"param",
"kw",
":",
"element",
"name",
":",
"return",
":",
"instance",
"itself",
"1",
"call",
"getKwAsDict",
"()",
"to",
"return",
"config",
"as",
"a",
"dict",
"2",
"call",
"getKwAsJson",
... | python | train |
mhe/pynrrd | nrrd/reader.py | https://github.com/mhe/pynrrd/blob/96dd875b302031ea27e2d3aaa611dc6f2dfc7979/nrrd/reader.py#L301-L466 | def read_data(header, fh=None, filename=None, index_order='F'):
"""Read data from file into :class:`numpy.ndarray`
The two parameters :obj:`fh` and :obj:`filename` are optional depending on the parameters but it never hurts to
specify both. The file handle (:obj:`fh`) is necessary if the header is attached... | [
"def",
"read_data",
"(",
"header",
",",
"fh",
"=",
"None",
",",
"filename",
"=",
"None",
",",
"index_order",
"=",
"'F'",
")",
":",
"if",
"index_order",
"not",
"in",
"[",
"'F'",
",",
"'C'",
"]",
":",
"raise",
"NRRDError",
"(",
"'Invalid index order'",
"... | Read data from file into :class:`numpy.ndarray`
The two parameters :obj:`fh` and :obj:`filename` are optional depending on the parameters but it never hurts to
specify both. The file handle (:obj:`fh`) is necessary if the header is attached with the NRRD data. However, if
the NRRD data is detached from the... | [
"Read",
"data",
"from",
"file",
"into",
":",
"class",
":",
"numpy",
".",
"ndarray"
] | python | train |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.