repo stringlengths 7 55 | path stringlengths 4 223 | url stringlengths 87 315 | code stringlengths 75 104k | code_tokens list | docstring stringlengths 1 46.9k | docstring_tokens list | language stringclasses 1
value | partition stringclasses 3
values | avg_line_len float64 7.91 980 |
|---|---|---|---|---|---|---|---|---|---|
pyviz/holoviews | holoviews/core/data/interface.py | https://github.com/pyviz/holoviews/blob/ae0dd2f3de448b0ca5e9065aabd6ef8d84c7e655/holoviews/core/data/interface.py#L278-L314 | def select_mask(cls, dataset, selection):
"""
Given a Dataset object and a dictionary with dimension keys and
selection keys (i.e tuple ranges, slices, sets, lists or literals)
return a boolean mask over the rows in the Dataset object that
have been selected.
"""
... | [
"def",
"select_mask",
"(",
"cls",
",",
"dataset",
",",
"selection",
")",
":",
"mask",
"=",
"np",
".",
"ones",
"(",
"len",
"(",
"dataset",
")",
",",
"dtype",
"=",
"np",
".",
"bool",
")",
"for",
"dim",
",",
"k",
"in",
"selection",
".",
"items",
"("... | Given a Dataset object and a dictionary with dimension keys and
selection keys (i.e tuple ranges, slices, sets, lists or literals)
return a boolean mask over the rows in the Dataset object that
have been selected. | [
"Given",
"a",
"Dataset",
"object",
"and",
"a",
"dictionary",
"with",
"dimension",
"keys",
"and",
"selection",
"keys",
"(",
"i",
".",
"e",
"tuple",
"ranges",
"slices",
"sets",
"lists",
"or",
"literals",
")",
"return",
"a",
"boolean",
"mask",
"over",
"the",
... | python | train | 43.594595 |
django-treebeard/django-treebeard | treebeard/mp_tree.py | https://github.com/django-treebeard/django-treebeard/blob/8042ee939cb45394909237da447f8925e3cc6aa3/treebeard/mp_tree.py#L159-L260 | def reorder_nodes_before_add_or_move(self, pos, newpos, newdepth, target,
siblings, oldpath=None,
movebranch=False):
"""
Handles the reordering of nodes and branches when adding/moving
nodes.
:returns: A t... | [
"def",
"reorder_nodes_before_add_or_move",
"(",
"self",
",",
"pos",
",",
"newpos",
",",
"newdepth",
",",
"target",
",",
"siblings",
",",
"oldpath",
"=",
"None",
",",
"movebranch",
"=",
"False",
")",
":",
"if",
"(",
"(",
"pos",
"==",
"'last-sibling'",
")",
... | Handles the reordering of nodes and branches when adding/moving
nodes.
:returns: A tuple containing the old path and the new path. | [
"Handles",
"the",
"reordering",
"of",
"nodes",
"and",
"branches",
"when",
"adding",
"/",
"moving",
"nodes",
"."
] | python | train | 44.539216 |
tsnaomi/finnsyll | finnsyll/prev/v02.py | https://github.com/tsnaomi/finnsyll/blob/6a42740311688c946a636a3e2304866c7aa041b3/finnsyll/prev/v02.py#L201-L226 | def apply_T6(word):
'''If a VVV-sequence contains a long vowel, there is a syllable boundary
between it and the third vowel, e.g. [kor.ke.aa], [yh.ti.öön], [ruu.an],
[mää.yt.te].'''
T6 = ''
WORD = word.split('.')
for i, v in enumerate(WORD):
if contains_VVV(v):
VV = [v.find... | [
"def",
"apply_T6",
"(",
"word",
")",
":",
"T6",
"=",
"''",
"WORD",
"=",
"word",
".",
"split",
"(",
"'.'",
")",
"for",
"i",
",",
"v",
"in",
"enumerate",
"(",
"WORD",
")",
":",
"if",
"contains_VVV",
"(",
"v",
")",
":",
"VV",
"=",
"[",
"v",
".",... | If a VVV-sequence contains a long vowel, there is a syllable boundary
between it and the third vowel, e.g. [kor.ke.aa], [yh.ti.öön], [ruu.an],
[mää.yt.te]. | [
"If",
"a",
"VVV",
"-",
"sequence",
"contains",
"a",
"long",
"vowel",
"there",
"is",
"a",
"syllable",
"boundary",
"between",
"it",
"and",
"the",
"third",
"vowel",
"e",
".",
"g",
".",
"[",
"kor",
".",
"ke",
".",
"aa",
"]",
"[",
"yh",
".",
"ti",
"."... | python | train | 26.576923 |
jeffh/sniffer | sniffer/scanner/base.py | https://github.com/jeffh/sniffer/blob/8e4c3e77743aef08109ea0225b4a6536d4e60270/sniffer/scanner/base.py#L39-L44 | def trigger_modified(self, filepath):
"""Triggers modified event if the given filepath mod time is newer."""
mod_time = self._get_modified_time(filepath)
if mod_time > self._watched_files.get(filepath, 0):
self._trigger('modified', filepath)
self._watched_files[filepath] ... | [
"def",
"trigger_modified",
"(",
"self",
",",
"filepath",
")",
":",
"mod_time",
"=",
"self",
".",
"_get_modified_time",
"(",
"filepath",
")",
"if",
"mod_time",
">",
"self",
".",
"_watched_files",
".",
"get",
"(",
"filepath",
",",
"0",
")",
":",
"self",
".... | Triggers modified event if the given filepath mod time is newer. | [
"Triggers",
"modified",
"event",
"if",
"the",
"given",
"filepath",
"mod",
"time",
"is",
"newer",
"."
] | python | train | 54.166667 |
chaoss/grimoirelab-cereslib | cereslib/dfutils/format.py | https://github.com/chaoss/grimoirelab-cereslib/blob/5110e6ca490a4f24bec3124286ebf51fd4e08bdd/cereslib/dfutils/format.py#L61-L77 | def update_field_names(self, data, matching):
""" This method updates the names of the fields according to matching
:param data: original Pandas dataframe
:param matching: dictionary of matchings between old and new values
:type data: pandas.DataFrame
:type matching: dictionary
... | [
"def",
"update_field_names",
"(",
"self",
",",
"data",
",",
"matching",
")",
":",
"for",
"key",
"in",
"matching",
".",
"keys",
"(",
")",
":",
"if",
"key",
"in",
"data",
".",
"columns",
":",
"data",
".",
"rename",
"(",
"columns",
"=",
"{",
"key",
":... | This method updates the names of the fields according to matching
:param data: original Pandas dataframe
:param matching: dictionary of matchings between old and new values
:type data: pandas.DataFrame
:type matching: dictionary
:returns: Pandas dataframe with updated names
... | [
"This",
"method",
"updates",
"the",
"names",
"of",
"the",
"fields",
"according",
"to",
"matching"
] | python | train | 32.588235 |
iotile/coretools | iotilecore/iotile/core/hw/debug/flash_board_step.py | https://github.com/iotile/coretools/blob/2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec/iotilecore/iotile/core/hw/debug/flash_board_step.py#L26-L38 | def run(self, resources):
"""Runs the flash step
Args:
resources (dict): A dictionary containing the required resources that
we needed access to in order to perform this step.
"""
if not resources['connection']._port.startswith('jlink'):
raise Arg... | [
"def",
"run",
"(",
"self",
",",
"resources",
")",
":",
"if",
"not",
"resources",
"[",
"'connection'",
"]",
".",
"_port",
".",
"startswith",
"(",
"'jlink'",
")",
":",
"raise",
"ArgumentError",
"(",
"\"FlashBoardStep is currently only possible through jlink\"",
",",... | Runs the flash step
Args:
resources (dict): A dictionary containing the required resources that
we needed access to in order to perform this step. | [
"Runs",
"the",
"flash",
"step"
] | python | train | 40.846154 |
awslabs/aws-sam-cli | samcli/commands/local/lib/swagger/integration_uri.py | https://github.com/awslabs/aws-sam-cli/blob/c05af5e7378c6f05f7d82ad3f0bca17204177db6/samcli/commands/local/lib/swagger/integration_uri.py#L131-L170 | def _get_function_name_from_arn(function_arn):
"""
Given the integration ARN, extract the Lambda function name from the ARN. If there
are stage variables, or other unsupported formats, this function will return None.
Parameters
----------
function_arn : basestring or Non... | [
"def",
"_get_function_name_from_arn",
"(",
"function_arn",
")",
":",
"if",
"not",
"function_arn",
":",
"return",
"None",
"matches",
"=",
"re",
".",
"match",
"(",
"LambdaUri",
".",
"_REGEX_GET_FUNCTION_NAME",
",",
"function_arn",
")",
"if",
"not",
"matches",
"or"... | Given the integration ARN, extract the Lambda function name from the ARN. If there
are stage variables, or other unsupported formats, this function will return None.
Parameters
----------
function_arn : basestring or None
Function ARN from the swagger document
Retur... | [
"Given",
"the",
"integration",
"ARN",
"extract",
"the",
"Lambda",
"function",
"name",
"from",
"the",
"ARN",
".",
"If",
"there",
"are",
"stage",
"variables",
"or",
"other",
"unsupported",
"formats",
"this",
"function",
"will",
"return",
"None",
"."
] | python | train | 39.625 |
pgmpy/pgmpy | pgmpy/readwrite/XMLBeliefNetwork.py | https://github.com/pgmpy/pgmpy/blob/9381a66aba3c3871d3ccd00672b148d17d63239e/pgmpy/readwrite/XMLBeliefNetwork.py#L137-L184 | def get_distributions(self):
"""
Returns a dictionary of name and its distribution. Distribution is a ndarray.
The ndarray is stored in the standard way such that the rightmost variable changes most often.
Consider a CPD of variable 'd' which has parents 'b' and 'c' (distribution['CONDS... | [
"def",
"get_distributions",
"(",
"self",
")",
":",
"distribution",
"=",
"{",
"}",
"for",
"dist",
"in",
"self",
".",
"bnmodel",
".",
"find",
"(",
"'DISTRIBUTIONS'",
")",
":",
"variable_name",
"=",
"dist",
".",
"find",
"(",
"'PRIVATE'",
")",
".",
"get",
... | Returns a dictionary of name and its distribution. Distribution is a ndarray.
The ndarray is stored in the standard way such that the rightmost variable changes most often.
Consider a CPD of variable 'd' which has parents 'b' and 'c' (distribution['CONDSET'] = ['b', 'c'])
| d_0 ... | [
"Returns",
"a",
"dictionary",
"of",
"name",
"and",
"its",
"distribution",
".",
"Distribution",
"is",
"a",
"ndarray",
"."
] | python | train | 50.229167 |
remram44/rpaths | rpaths.py | https://github.com/remram44/rpaths/blob/e4ff55d985c4d643d9fd214539d45af39ae5a7cd/rpaths.py#L1087-L1094 | def may_contain_matches(self, path):
"""Tests whether it's possible for paths under the given one to match.
If this method returns None, no path under the given one will match the
pattern.
"""
path = self._prepare_path(path)
return self.int_regex.search(path) is not None | [
"def",
"may_contain_matches",
"(",
"self",
",",
"path",
")",
":",
"path",
"=",
"self",
".",
"_prepare_path",
"(",
"path",
")",
"return",
"self",
".",
"int_regex",
".",
"search",
"(",
"path",
")",
"is",
"not",
"None"
] | Tests whether it's possible for paths under the given one to match.
If this method returns None, no path under the given one will match the
pattern. | [
"Tests",
"whether",
"it",
"s",
"possible",
"for",
"paths",
"under",
"the",
"given",
"one",
"to",
"match",
"."
] | python | train | 39.125 |
marcinmiklitz/pywindow | pywindow/utilities.py | https://github.com/marcinmiklitz/pywindow/blob/e5264812157224f22a691741ca2e0aefdc9bd2eb/pywindow/utilities.py#L1095-L1113 | def vector_analysis(vector, coordinates, elements_vdw, increment=1.0):
"""Analyse a sampling vector's path for window analysis purpose."""
# Calculate number of chunks if vector length is divided by increment.
chunks = int(np.linalg.norm(vector) // increment)
# Create a single chunk.
chunk = vector ... | [
"def",
"vector_analysis",
"(",
"vector",
",",
"coordinates",
",",
"elements_vdw",
",",
"increment",
"=",
"1.0",
")",
":",
"# Calculate number of chunks if vector length is divided by increment.",
"chunks",
"=",
"int",
"(",
"np",
".",
"linalg",
".",
"norm",
"(",
"vec... | Analyse a sampling vector's path for window analysis purpose. | [
"Analyse",
"a",
"sampling",
"vector",
"s",
"path",
"for",
"window",
"analysis",
"purpose",
"."
] | python | train | 47.789474 |
ellmetha/django-machina | machina/apps/forum_member/receivers.py | https://github.com/ellmetha/django-machina/blob/89ac083c1eaf1cfdeae6686ee094cc86362e8c69/machina/apps/forum_member/receivers.py#L25-L54 | def increase_posts_count(sender, instance, **kwargs):
""" Increases the member's post count after a post save.
This receiver handles the update of the profile related to the user who is the poster of the
forum post being created or updated.
"""
if instance.poster is None:
# An anonymous po... | [
"def",
"increase_posts_count",
"(",
"sender",
",",
"instance",
",",
"*",
"*",
"kwargs",
")",
":",
"if",
"instance",
".",
"poster",
"is",
"None",
":",
"# An anonymous post is considered. No profile can be updated in",
"# that case.",
"return",
"profile",
",",
"dummy",
... | Increases the member's post count after a post save.
This receiver handles the update of the profile related to the user who is the poster of the
forum post being created or updated. | [
"Increases",
"the",
"member",
"s",
"post",
"count",
"after",
"a",
"post",
"save",
"."
] | python | train | 36.8 |
sorend/sshconf | sshconf.py | https://github.com/sorend/sshconf/blob/59f3fc165b1ba9e76ba23444b1205d88462938f3/sshconf.py#L260-L278 | def rename(self, old_host, new_host):
"""
Renames a host configuration.
Parameters
----------
old_host : the host to rename.
new_host : the new host value
"""
if new_host in self.hosts_:
raise ValueError("Host %s: already exists." % new_host)
... | [
"def",
"rename",
"(",
"self",
",",
"old_host",
",",
"new_host",
")",
":",
"if",
"new_host",
"in",
"self",
".",
"hosts_",
":",
"raise",
"ValueError",
"(",
"\"Host %s: already exists.\"",
"%",
"new_host",
")",
"for",
"line",
"in",
"self",
".",
"lines_",
":",... | Renames a host configuration.
Parameters
----------
old_host : the host to rename.
new_host : the new host value | [
"Renames",
"a",
"host",
"configuration",
"."
] | python | train | 34.684211 |
acutesoftware/virtual-AI-simulator | vais/examples/game_incremental.py | https://github.com/acutesoftware/virtual-AI-simulator/blob/57de679a5b1a58c38fefe6aea58af1f3a7e79c58/vais/examples/game_incremental.py#L224-L232 | def get_skill_by_name(nme, character):
"""
returns the skill by name in a character
"""
for ndx, sk in enumerate(character["skills"]):
if sk["name"] == nme:
return ndx
return 0 | [
"def",
"get_skill_by_name",
"(",
"nme",
",",
"character",
")",
":",
"for",
"ndx",
",",
"sk",
"in",
"enumerate",
"(",
"character",
"[",
"\"skills\"",
"]",
")",
":",
"if",
"sk",
"[",
"\"name\"",
"]",
"==",
"nme",
":",
"return",
"ndx",
"return",
"0"
] | returns the skill by name in a character | [
"returns",
"the",
"skill",
"by",
"name",
"in",
"a",
"character"
] | python | train | 23.222222 |
marcomusy/vtkplotter | vtkplotter/actors.py | https://github.com/marcomusy/vtkplotter/blob/692c3396782722ec525bc1346a26999868c650c6/vtkplotter/actors.py#L1137-L1156 | def clone(self, transformed=True):
"""
Clone a ``Actor(vtkActor)`` and make an exact copy of it.
:param transformed: if `False` ignore any previous trasformation applied to the mesh.
.. hint:: |carcrash| |carcrash.py|_
"""
poly = self.polydata(transformed=transformed)
... | [
"def",
"clone",
"(",
"self",
",",
"transformed",
"=",
"True",
")",
":",
"poly",
"=",
"self",
".",
"polydata",
"(",
"transformed",
"=",
"transformed",
")",
"polyCopy",
"=",
"vtk",
".",
"vtkPolyData",
"(",
")",
"polyCopy",
".",
"DeepCopy",
"(",
"poly",
"... | Clone a ``Actor(vtkActor)`` and make an exact copy of it.
:param transformed: if `False` ignore any previous trasformation applied to the mesh.
.. hint:: |carcrash| |carcrash.py|_ | [
"Clone",
"a",
"Actor",
"(",
"vtkActor",
")",
"and",
"make",
"an",
"exact",
"copy",
"of",
"it",
"."
] | python | train | 33.55 |
pyviz/holoviews | holoviews/util/__init__.py | https://github.com/pyviz/holoviews/blob/ae0dd2f3de448b0ca5e9065aabd6ef8d84c7e655/holoviews/util/__init__.py#L363-L408 | def _options_error(cls, opt, objtype, backend, valid_options):
"""
Generates an error message for an invalid option suggesting
similar options through fuzzy matching.
"""
current_backend = Store.current_backend
loaded_backends = Store.loaded_backends()
kws = Keywo... | [
"def",
"_options_error",
"(",
"cls",
",",
"opt",
",",
"objtype",
",",
"backend",
",",
"valid_options",
")",
":",
"current_backend",
"=",
"Store",
".",
"current_backend",
"loaded_backends",
"=",
"Store",
".",
"loaded_backends",
"(",
")",
"kws",
"=",
"Keywords",... | Generates an error message for an invalid option suggesting
similar options through fuzzy matching. | [
"Generates",
"an",
"error",
"message",
"for",
"an",
"invalid",
"option",
"suggesting",
"similar",
"options",
"through",
"fuzzy",
"matching",
"."
] | python | train | 46.413043 |
MakerReduxCorp/PLOD | PLOD/__init__.py | https://github.com/MakerReduxCorp/PLOD/blob/707502cd928e5be6bd5e46d7f6de7da0e188cf1e/PLOD/__init__.py#L793-L872 | def contains(self, key, value, findAll=False, exclude=False, includeMissing=False):
'''Return entries that:
* have the key
* key points to a list, and
* value is found in the list.
If value is also a list itself, then the list entry is selected if any of
the val... | [
"def",
"contains",
"(",
"self",
",",
"key",
",",
"value",
",",
"findAll",
"=",
"False",
",",
"exclude",
"=",
"False",
",",
"includeMissing",
"=",
"False",
")",
":",
"result",
"=",
"[",
"]",
"result_index",
"=",
"[",
"]",
"for",
"counter",
",",
"row",... | Return entries that:
* have the key
* key points to a list, and
* value is found in the list.
If value is also a list itself, then the list entry is selected if any of
the values match. If findAll is set to True, then all the entries
must be found.
Exa... | [
"Return",
"entries",
"that",
":",
"*",
"have",
"the",
"key",
"*",
"key",
"points",
"to",
"a",
"list",
"and",
"*",
"value",
"is",
"found",
"in",
"the",
"list",
"."
] | python | train | 39.0375 |
gwastro/pycbc | pycbc/conversions.py | https://github.com/gwastro/pycbc/blob/7a64cdd104d263f1b6ea0b01e6841837d05a4cb3/pycbc/conversions.py#L434-L440 | def phi_a(mass1, mass2, spin1x, spin1y, spin2x, spin2y):
""" Returns the angle between the in-plane perpendicular spins."""
phi1 = phi_from_spinx_spiny(primary_spin(mass1, mass2, spin1x, spin2x),
primary_spin(mass1, mass2, spin1y, spin2y))
phi2 = phi_from_spinx_spiny(secondar... | [
"def",
"phi_a",
"(",
"mass1",
",",
"mass2",
",",
"spin1x",
",",
"spin1y",
",",
"spin2x",
",",
"spin2y",
")",
":",
"phi1",
"=",
"phi_from_spinx_spiny",
"(",
"primary_spin",
"(",
"mass1",
",",
"mass2",
",",
"spin1x",
",",
"spin2x",
")",
",",
"primary_spin"... | Returns the angle between the in-plane perpendicular spins. | [
"Returns",
"the",
"angle",
"between",
"the",
"in",
"-",
"plane",
"perpendicular",
"spins",
"."
] | python | train | 67.285714 |
gwastro/pycbc-glue | pycbc_glue/ligolw/lsctables.py | https://github.com/gwastro/pycbc-glue/blob/a3e906bae59fbfd707c3ff82e5d008d939ec5e24/pycbc_glue/ligolw/lsctables.py#L874-L884 | def get_row_from_id(self, experiment_id):
"""
Returns row in matching the given experiment_id.
"""
row = [row for row in self if row.experiment_id == experiment_id]
if len(row) > 1:
raise ValueError("duplicate ids in experiment table")
if len(row) == 0:
raise ValueError("id '%s' not found in table" % ... | [
"def",
"get_row_from_id",
"(",
"self",
",",
"experiment_id",
")",
":",
"row",
"=",
"[",
"row",
"for",
"row",
"in",
"self",
"if",
"row",
".",
"experiment_id",
"==",
"experiment_id",
"]",
"if",
"len",
"(",
"row",
")",
">",
"1",
":",
"raise",
"ValueError"... | Returns row in matching the given experiment_id. | [
"Returns",
"row",
"in",
"matching",
"the",
"given",
"experiment_id",
"."
] | python | train | 31 |
datamachine/twx | twx/twx.py | https://github.com/datamachine/twx/blob/d9633f12f3647b1e54ba87b70b39df3b7e02b4eb/twx/twx.py#L171-L183 | def send_video(self, video: str, reply: Message=None,
on_success: callable=None, reply_markup: botapi.ReplyMarkup=None):
"""
Send video to this peer.
:param video: File path to video to send.
:param reply: Message object.
:param on_success: Callback to call whe... | [
"def",
"send_video",
"(",
"self",
",",
"video",
":",
"str",
",",
"reply",
":",
"Message",
"=",
"None",
",",
"on_success",
":",
"callable",
"=",
"None",
",",
"reply_markup",
":",
"botapi",
".",
"ReplyMarkup",
"=",
"None",
")",
":",
"self",
".",
"twx",
... | Send video to this peer.
:param video: File path to video to send.
:param reply: Message object.
:param on_success: Callback to call when call is complete.
:type reply: int or Message | [
"Send",
"video",
"to",
"this",
"peer",
".",
":",
"param",
"video",
":",
"File",
"path",
"to",
"video",
"to",
"send",
".",
":",
"param",
"reply",
":",
"Message",
"object",
".",
":",
"param",
"on_success",
":",
"Callback",
"to",
"call",
"when",
"call",
... | python | train | 41.076923 |
aio-libs/aiohttp | aiohttp/connector.py | https://github.com/aio-libs/aiohttp/blob/9504fe2affaaff673fa4f3754c1c44221f8ba47d/aiohttp/connector.py#L575-L597 | def _release_waiter(self) -> None:
"""
Iterates over all waiters till found one that is not finsihed and
belongs to a host that has available connections.
"""
if not self._waiters:
return
# Having the dict keys ordered this avoids to iterate
# at the ... | [
"def",
"_release_waiter",
"(",
"self",
")",
"->",
"None",
":",
"if",
"not",
"self",
".",
"_waiters",
":",
"return",
"# Having the dict keys ordered this avoids to iterate",
"# at the same order at each call.",
"queues",
"=",
"list",
"(",
"self",
".",
"_waiters",
".",
... | Iterates over all waiters till found one that is not finsihed and
belongs to a host that has available connections. | [
"Iterates",
"over",
"all",
"waiters",
"till",
"found",
"one",
"that",
"is",
"not",
"finsihed",
"and",
"belongs",
"to",
"a",
"host",
"that",
"has",
"available",
"connections",
"."
] | python | train | 31.478261 |
molmod/molmod | molmod/pairff.py | https://github.com/molmod/molmod/blob/a7b5b4364ed514ad4c465856c05b5eda1cb561e0/molmod/pairff.py#L432-L437 | def yield_pair_gradients(self, index1, index2):
"""Yields pairs ((s'(r_ij), grad_i v(bar{r}_ij))"""
A = self.As[index1, index2]
B = self.Bs[index1, index2]
distance = self.distances[index1, index2]
yield -B*A*np.exp(-B*distance), np.zeros(3) | [
"def",
"yield_pair_gradients",
"(",
"self",
",",
"index1",
",",
"index2",
")",
":",
"A",
"=",
"self",
".",
"As",
"[",
"index1",
",",
"index2",
"]",
"B",
"=",
"self",
".",
"Bs",
"[",
"index1",
",",
"index2",
"]",
"distance",
"=",
"self",
".",
"dista... | Yields pairs ((s'(r_ij), grad_i v(bar{r}_ij)) | [
"Yields",
"pairs",
"((",
"s",
"(",
"r_ij",
")",
"grad_i",
"v",
"(",
"bar",
"{",
"r",
"}",
"_ij",
"))"
] | python | train | 46 |
dhermes/bezier | scripts/rewrite_package_rst.py | https://github.com/dhermes/bezier/blob/4f941f82637a8e70a5b159a9203132192e23406b/scripts/rewrite_package_rst.py#L69-L120 | def get_public_members():
"""Get public members in :mod:`bezier` package.
Also validates the contents of ``bezier.__all__``.
Returns:
list: List of all public members **defined** in the
main package (i.e. in ``__init__.py``).
Raises:
ValueError: If ``__all__`` has repeated ele... | [
"def",
"get_public_members",
"(",
")",
":",
"if",
"bezier",
"is",
"None",
":",
"return",
"[",
"]",
"local_members",
"=",
"[",
"]",
"all_members",
"=",
"set",
"(",
")",
"for",
"name",
"in",
"dir",
"(",
"bezier",
")",
":",
"# Filter out non-public.",
"if",... | Get public members in :mod:`bezier` package.
Also validates the contents of ``bezier.__all__``.
Returns:
list: List of all public members **defined** in the
main package (i.e. in ``__init__.py``).
Raises:
ValueError: If ``__all__`` has repeated elements.
ValueError: If the... | [
"Get",
"public",
"members",
"in",
":",
"mod",
":",
"bezier",
"package",
"."
] | python | train | 29.288462 |
s1s1ty/py-jsonq | pyjsonq/query.py | https://github.com/s1s1ty/py-jsonq/blob/9625597a2578bddcbed4e540174d5253b1fc3b75/pyjsonq/query.py#L190-L203 | def or_where(self, key, operator, value):
"""Make or_where clause
:@param key
:@param operator
:@param value
:@type key, operator, value: string
:@return self
"""
if len(self._queries) > 0:
self._current_query_index += 1
self.__store_... | [
"def",
"or_where",
"(",
"self",
",",
"key",
",",
"operator",
",",
"value",
")",
":",
"if",
"len",
"(",
"self",
".",
"_queries",
")",
">",
"0",
":",
"self",
".",
"_current_query_index",
"+=",
"1",
"self",
".",
"__store_query",
"(",
"{",
"\"key\"",
":"... | Make or_where clause
:@param key
:@param operator
:@param value
:@type key, operator, value: string
:@return self | [
"Make",
"or_where",
"clause"
] | python | train | 27.428571 |
bwohlberg/sporco | sporco/admm/spline.py | https://github.com/bwohlberg/sporco/blob/8946a04331106f4e39904fbdf2dc7351900baa04/sporco/admm/spline.py#L222-L230 | def obfn_gvar(self):
"""Variable to be evaluated in computing regularisation term,
depending on 'gEvalY' option value.
"""
if self.opt['gEvalY']:
return self.Y
else:
return self.cnst_A(self.X) - self.cnst_c() | [
"def",
"obfn_gvar",
"(",
"self",
")",
":",
"if",
"self",
".",
"opt",
"[",
"'gEvalY'",
"]",
":",
"return",
"self",
".",
"Y",
"else",
":",
"return",
"self",
".",
"cnst_A",
"(",
"self",
".",
"X",
")",
"-",
"self",
".",
"cnst_c",
"(",
")"
] | Variable to be evaluated in computing regularisation term,
depending on 'gEvalY' option value. | [
"Variable",
"to",
"be",
"evaluated",
"in",
"computing",
"regularisation",
"term",
"depending",
"on",
"gEvalY",
"option",
"value",
"."
] | python | train | 29.444444 |
rackerlabs/yoke | examples/api_gateway_with_authorizer/authorizer/src/policy.py | https://github.com/rackerlabs/yoke/blob/00c01d6217b77f9ce14233a0f3686ac6f7b1c247/examples/api_gateway_with_authorizer/authorizer/src/policy.py#L87-L109 | def _get_effect_statement(self, effect, methods):
"""
This function loops over an array of objects containing
a resourceArn and conditions statement and generates
the array of statements for the policy.
"""
statements = []
if len(methods) > 0:
stateme... | [
"def",
"_get_effect_statement",
"(",
"self",
",",
"effect",
",",
"methods",
")",
":",
"statements",
"=",
"[",
"]",
"if",
"len",
"(",
"methods",
")",
">",
"0",
":",
"statement",
"=",
"self",
".",
"_get_empty_statement",
"(",
"effect",
")",
"for",
"method"... | This function loops over an array of objects containing
a resourceArn and conditions statement and generates
the array of statements for the policy. | [
"This",
"function",
"loops",
"over",
"an",
"array",
"of",
"objects",
"containing",
"a",
"resourceArn",
"and",
"conditions",
"statement",
"and",
"generates",
"the",
"array",
"of",
"statements",
"for",
"the",
"policy",
"."
] | python | valid | 39.913043 |
kgori/treeCl | treeCl/distance_matrix.py | https://github.com/kgori/treeCl/blob/fed624b3db1c19cc07175ca04e3eda6905a8d305/treeCl/distance_matrix.py#L339-L355 | def _embedding_tsne(matrix, dimensions=3, early_exaggeration=12.0,
method='barnes_hut', perplexity=30, learning_rate=200,
n_iter=1000):
"""
Private method to perform tSNE embedding
:param matrix: treeCl Distance Matrix
:param dimensions: Number of dimensions in wh... | [
"def",
"_embedding_tsne",
"(",
"matrix",
",",
"dimensions",
"=",
"3",
",",
"early_exaggeration",
"=",
"12.0",
",",
"method",
"=",
"'barnes_hut'",
",",
"perplexity",
"=",
"30",
",",
"learning_rate",
"=",
"200",
",",
"n_iter",
"=",
"1000",
")",
":",
"tsne",
... | Private method to perform tSNE embedding
:param matrix: treeCl Distance Matrix
:param dimensions: Number of dimensions in which to embed points
:return: treeCl CoordinateMatrix | [
"Private",
"method",
"to",
"perform",
"tSNE",
"embedding",
":",
"param",
"matrix",
":",
"treeCl",
"Distance",
"Matrix",
":",
"param",
"dimensions",
":",
"Number",
"of",
"dimensions",
"in",
"which",
"to",
"embed",
"points",
":",
"return",
":",
"treeCl",
"Coor... | python | train | 47.235294 |
brandon-rhodes/python-sgp4 | sgp4/io.py | https://github.com/brandon-rhodes/python-sgp4/blob/a1e19e32831d6814b3ab34f55b39b8520d291c4e/sgp4/io.py#L261-L263 | def compute_checksum(line):
"""Compute the TLE checksum for the given line."""
return sum((int(c) if c.isdigit() else c == '-') for c in line[0:68]) % 10 | [
"def",
"compute_checksum",
"(",
"line",
")",
":",
"return",
"sum",
"(",
"(",
"int",
"(",
"c",
")",
"if",
"c",
".",
"isdigit",
"(",
")",
"else",
"c",
"==",
"'-'",
")",
"for",
"c",
"in",
"line",
"[",
"0",
":",
"68",
"]",
")",
"%",
"10"
] | Compute the TLE checksum for the given line. | [
"Compute",
"the",
"TLE",
"checksum",
"for",
"the",
"given",
"line",
"."
] | python | train | 53 |
PatrikValkovic/grammpy | grammpy/parsers/CYK/cyk.py | https://github.com/PatrikValkovic/grammpy/blob/879ce0ef794ac2823acc19314fcd7a8aba53e50f/grammpy/parsers/CYK/cyk.py#L59-L127 | def cyk(grammar, parse_sequence):
# type: (Grammar, Iterable[Any]) -> Nonterminal
"""
Perform CYK algorithm.
:param grammar: Grammar to use in Chomsky Normal Form.
:param parse_sequence: Input sequence to parse.
:return: Instance of root Nonterminal in parsed tree.
"""
# check start symb... | [
"def",
"cyk",
"(",
"grammar",
",",
"parse_sequence",
")",
":",
"# type: (Grammar, Iterable[Any]) -> Nonterminal",
"# check start symbol",
"if",
"grammar",
".",
"start",
"is",
"None",
":",
"raise",
"StartSymbolNotSetException",
"(",
")",
"# create variables",
"parse_sequen... | Perform CYK algorithm.
:param grammar: Grammar to use in Chomsky Normal Form.
:param parse_sequence: Input sequence to parse.
:return: Instance of root Nonterminal in parsed tree. | [
"Perform",
"CYK",
"algorithm",
".",
":",
"param",
"grammar",
":",
"Grammar",
"to",
"use",
"in",
"Chomsky",
"Normal",
"Form",
".",
":",
"param",
"parse_sequence",
":",
"Input",
"sequence",
"to",
"parse",
".",
":",
"return",
":",
"Instance",
"of",
"root",
... | python | train | 44.072464 |
aouyar/PyMunin | pymunin/plugins/memcachedstats.py | https://github.com/aouyar/PyMunin/blob/4f58a64b6b37c85a84cc7e1e07aafaa0321b249d/pymunin/plugins/memcachedstats.py#L305-L440 | def retrieveVals(self):
"""Retrieve values for graphs."""
if self._stats is None:
serverInfo = MemcachedInfo(self._host, self._port, self._socket_file)
stats = serverInfo.getStats()
else:
stats = self._stats
if stats is None:
raise Excepti... | [
"def",
"retrieveVals",
"(",
"self",
")",
":",
"if",
"self",
".",
"_stats",
"is",
"None",
":",
"serverInfo",
"=",
"MemcachedInfo",
"(",
"self",
".",
"_host",
",",
"self",
".",
"_port",
",",
"self",
".",
"_socket_file",
")",
"stats",
"=",
"serverInfo",
"... | Retrieve values for graphs. | [
"Retrieve",
"values",
"for",
"graphs",
"."
] | python | train | 55.816176 |
bitcraze/crazyflie-lib-python | cflib/crazyflie/swarm.py | https://github.com/bitcraze/crazyflie-lib-python/blob/f6ebb4eb315bbe6e02db518936ac17fb615b2af8/cflib/crazyflie/swarm.py#L94-L101 | def close_links(self):
"""
Close all open links
"""
for uri, cf in self._cfs.items():
cf.close_link()
self._is_open = False | [
"def",
"close_links",
"(",
"self",
")",
":",
"for",
"uri",
",",
"cf",
"in",
"self",
".",
"_cfs",
".",
"items",
"(",
")",
":",
"cf",
".",
"close_link",
"(",
")",
"self",
".",
"_is_open",
"=",
"False"
] | Close all open links | [
"Close",
"all",
"open",
"links"
] | python | train | 21.125 |
pandas-dev/pandas | pandas/core/algorithms.py | https://github.com/pandas-dev/pandas/blob/9feb3ad92cc0397a04b665803a49299ee7aa1037/pandas/core/algorithms.py#L1672-L1737 | def take_2d_multi(arr, indexer, out=None, fill_value=np.nan, mask_info=None,
allow_fill=True):
"""
Specialized Cython take which sets NaN values in one pass
"""
if indexer is None or (indexer[0] is None and indexer[1] is None):
row_idx = np.arange(arr.shape[0], dtype=np.int64)
... | [
"def",
"take_2d_multi",
"(",
"arr",
",",
"indexer",
",",
"out",
"=",
"None",
",",
"fill_value",
"=",
"np",
".",
"nan",
",",
"mask_info",
"=",
"None",
",",
"allow_fill",
"=",
"True",
")",
":",
"if",
"indexer",
"is",
"None",
"or",
"(",
"indexer",
"[",
... | Specialized Cython take which sets NaN values in one pass | [
"Specialized",
"Cython",
"take",
"which",
"sets",
"NaN",
"values",
"in",
"one",
"pass"
] | python | train | 44.318182 |
buriburisuri/sugartensor | sugartensor/sg_train.py | https://github.com/buriburisuri/sugartensor/blob/d2c039954777c7fbe3eb0c2ae40c45c9854deb40/sugartensor/sg_train.py#L83-L121 | def sg_print(tensor_list):
r"""Simple tensor printing function for debugging.
Prints the value, shape, and data type of each tensor in the list.
Args:
tensor_list: A list/tuple of tensors or a single tensor.
Returns:
The value of the tensors.
For example,
```p... | [
"def",
"sg_print",
"(",
"tensor_list",
")",
":",
"# to list",
"if",
"type",
"(",
"tensor_list",
")",
"is",
"not",
"list",
"and",
"type",
"(",
"tensor_list",
")",
"is",
"not",
"tuple",
":",
"tensor_list",
"=",
"[",
"tensor_list",
"]",
"# evaluate tensor list ... | r"""Simple tensor printing function for debugging.
Prints the value, shape, and data type of each tensor in the list.
Args:
tensor_list: A list/tuple of tensors or a single tensor.
Returns:
The value of the tensors.
For example,
```python
import sugartensor as... | [
"r",
"Simple",
"tensor",
"printing",
"function",
"for",
"debugging",
".",
"Prints",
"the",
"value",
"shape",
"and",
"data",
"type",
"of",
"each",
"tensor",
"in",
"the",
"list",
".",
"Args",
":",
"tensor_list",
":",
"A",
"list",
"/",
"tuple",
"of",
"tenso... | python | train | 27.512821 |
tensorflow/tensor2tensor | tensor2tensor/data_generators/tokenizer.py | https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/data_generators/tokenizer.py#L148-L171 | def corpus_token_counts(
text_filepattern, corpus_max_lines, split_on_newlines=True):
"""Read the corpus and compute a dictionary of token counts.
Args:
text_filepattern: A pattern matching one or more files.
corpus_max_lines: An integer; maximum total lines to read.
split_on_newlines: A boolean. I... | [
"def",
"corpus_token_counts",
"(",
"text_filepattern",
",",
"corpus_max_lines",
",",
"split_on_newlines",
"=",
"True",
")",
":",
"counts",
"=",
"collections",
".",
"Counter",
"(",
")",
"for",
"doc",
"in",
"_read_filepattern",
"(",
"text_filepattern",
",",
"max_lin... | Read the corpus and compute a dictionary of token counts.
Args:
text_filepattern: A pattern matching one or more files.
corpus_max_lines: An integer; maximum total lines to read.
split_on_newlines: A boolean. If true, then split files by lines and strip
leading and trailing whitespace from each l... | [
"Read",
"the",
"corpus",
"and",
"compute",
"a",
"dictionary",
"of",
"token",
"counts",
"."
] | python | train | 34.875 |
JdeRobot/base | src/drivers/MAVLinkServer/MAVProxy/pymavlink/mavutil.py | https://github.com/JdeRobot/base/blob/303b18992785b2fe802212f2d758a60873007f1f/src/drivers/MAVLinkServer/MAVProxy/pymavlink/mavutil.py#L1755-L1763 | def flushInput(self):
'''flush any pending input'''
self.buf = ''
saved_timeout = self.timeout
self.timeout = 0.5
self._recv()
self.timeout = saved_timeout
self.buf = ''
self.debug("flushInput... | [
"def",
"flushInput",
"(",
"self",
")",
":",
"self",
".",
"buf",
"=",
"''",
"saved_timeout",
"=",
"self",
".",
"timeout",
"self",
".",
"timeout",
"=",
"0.5",
"self",
".",
"_recv",
"(",
")",
"self",
".",
"timeout",
"=",
"saved_timeout",
"self",
".",
"b... | flush any pending input | [
"flush",
"any",
"pending",
"input"
] | python | train | 34.888889 |
glue-viz/glue-vispy-viewers | glue_vispy_viewers/extern/vispy/ext/_bundled/png.py | https://github.com/glue-viz/glue-vispy-viewers/blob/54a4351d98c1f90dfb1a557d1b447c1f57470eea/glue_vispy_viewers/extern/vispy/ext/_bundled/png.py#L786-L820 | def array_scanlines_interlace(self, pixels):
"""
Generator for interlaced scanlines from an array. `pixels` is
the full source image in flat row flat pixel format. The
generator yields each scanline of the reduced passes in turn, in
boxed row flat pixel format.
"""
... | [
"def",
"array_scanlines_interlace",
"(",
"self",
",",
"pixels",
")",
":",
"# http://www.w3.org/TR/PNG/#8InterlaceMethods",
"# Array type.",
"fmt",
"=",
"'BH'",
"[",
"self",
".",
"bitdepth",
">",
"8",
"]",
"# Value per row",
"vpr",
"=",
"self",
".",
"width",
"*",
... | Generator for interlaced scanlines from an array. `pixels` is
the full source image in flat row flat pixel format. The
generator yields each scanline of the reduced passes in turn, in
boxed row flat pixel format. | [
"Generator",
"for",
"interlaced",
"scanlines",
"from",
"an",
"array",
".",
"pixels",
"is",
"the",
"full",
"source",
"image",
"in",
"flat",
"row",
"flat",
"pixel",
"format",
".",
"The",
"generator",
"yields",
"each",
"scanline",
"of",
"the",
"reduced",
"passe... | python | train | 42.228571 |
lsbardel/python-stdnet | stdnet/odm/models.py | https://github.com/lsbardel/python-stdnet/blob/78db5320bdedc3f28c5e4f38cda13a4469e35db7/stdnet/odm/models.py#L121-L136 | def clone(self, **data):
'''Utility method for cloning the instance as a new object.
:parameter data: additional which override field data.
:rtype: a new instance of this class.
'''
meta = self._meta
session = self.session
pkname = meta.pkname()
pkvalue = data.pop(pkname, None)
... | [
"def",
"clone",
"(",
"self",
",",
"*",
"*",
"data",
")",
":",
"meta",
"=",
"self",
".",
"_meta",
"session",
"=",
"self",
".",
"session",
"pkname",
"=",
"meta",
".",
"pkname",
"(",
")",
"pkvalue",
"=",
"data",
".",
"pop",
"(",
"pkname",
",",
"None... | Utility method for cloning the instance as a new object.
:parameter data: additional which override field data.
:rtype: a new instance of this class. | [
"Utility",
"method",
"for",
"cloning",
"the",
"instance",
"as",
"a",
"new",
"object",
"."
] | python | train | 33.1875 |
onecodex/onecodex | onecodex/viz/_bargraph.py | https://github.com/onecodex/onecodex/blob/326a0a1af140e3a57ccf31c3c9c5e17a5775c13d/onecodex/viz/_bargraph.py#L6-L202 | def plot_bargraph(
self,
rank="auto",
normalize="auto",
top_n="auto",
threshold="auto",
title=None,
xlabel=None,
ylabel=None,
tooltip=None,
return_chart=False,
haxis=None,
legend="auto",
label=None,
):
""... | [
"def",
"plot_bargraph",
"(",
"self",
",",
"rank",
"=",
"\"auto\"",
",",
"normalize",
"=",
"\"auto\"",
",",
"top_n",
"=",
"\"auto\"",
",",
"threshold",
"=",
"\"auto\"",
",",
"title",
"=",
"None",
",",
"xlabel",
"=",
"None",
",",
"ylabel",
"=",
"None",
"... | Plot a bargraph of relative abundance of taxa for multiple samples.
Parameters
----------
rank : {'auto', 'kingdom', 'phylum', 'class', 'order', 'family', 'genus', 'species'}, optional
Analysis will be restricted to abundances of taxa at the specified level.
normalize : 'aut... | [
"Plot",
"a",
"bargraph",
"of",
"relative",
"abundance",
"of",
"taxa",
"for",
"multiple",
"samples",
"."
] | python | train | 38.020305 |
nfcpy/nfcpy | src/nfc/tag/tt1.py | https://github.com/nfcpy/nfcpy/blob/6649146d1afdd5e82b2b6b1ea00aa58d50785117/src/nfc/tag/tt1.py#L403-L410 | def read_block(self, block):
"""Read an 8-byte data block at address (block * 8).
"""
if block < 0 or block > 255:
raise ValueError("invalid block number")
log.debug("read block {0}".format(block))
cmd = "\x02" + chr(block) + 8 * chr(0) + self.uid
return self.... | [
"def",
"read_block",
"(",
"self",
",",
"block",
")",
":",
"if",
"block",
"<",
"0",
"or",
"block",
">",
"255",
":",
"raise",
"ValueError",
"(",
"\"invalid block number\"",
")",
"log",
".",
"debug",
"(",
"\"read block {0}\"",
".",
"format",
"(",
"block",
"... | Read an 8-byte data block at address (block * 8). | [
"Read",
"an",
"8",
"-",
"byte",
"data",
"block",
"at",
"address",
"(",
"block",
"*",
"8",
")",
"."
] | python | train | 41.625 |
saltstack/salt | salt/_compat.py | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/_compat.py#L183-L197 | def _is_packed_binary(self, data):
'''
Check if data is hexadecimal packed
:param data:
:return:
'''
packed = False
if isinstance(data, bytes) and len(data) == 16 and b':' not in data:
try:
packed = bool(int(binascii.hexlify(data), 16)... | [
"def",
"_is_packed_binary",
"(",
"self",
",",
"data",
")",
":",
"packed",
"=",
"False",
"if",
"isinstance",
"(",
"data",
",",
"bytes",
")",
"and",
"len",
"(",
"data",
")",
"==",
"16",
"and",
"b':'",
"not",
"in",
"data",
":",
"try",
":",
"packed",
"... | Check if data is hexadecimal packed
:param data:
:return: | [
"Check",
"if",
"data",
"is",
"hexadecimal",
"packed"
] | python | train | 26.333333 |
ontio/ontology-python-sdk | ontology/network/rpc.py | https://github.com/ontio/ontology-python-sdk/blob/ac88bdda941896c5d2ced08422a9c5179d3f9b19/ontology/network/rpc.py#L219-L230 | def get_block_by_height(self, height: int, is_full: bool = False) -> dict:
"""
This interface is used to get the block information by block height in current network.
Return:
the decimal total number of blocks in current network.
"""
payload = self.generate_json_rpc_... | [
"def",
"get_block_by_height",
"(",
"self",
",",
"height",
":",
"int",
",",
"is_full",
":",
"bool",
"=",
"False",
")",
"->",
"dict",
":",
"payload",
"=",
"self",
".",
"generate_json_rpc_payload",
"(",
"RpcMethod",
".",
"GET_BLOCK",
",",
"[",
"height",
",",
... | This interface is used to get the block information by block height in current network.
Return:
the decimal total number of blocks in current network. | [
"This",
"interface",
"is",
"used",
"to",
"get",
"the",
"block",
"information",
"by",
"block",
"height",
"in",
"current",
"network",
"."
] | python | train | 40.333333 |
inveniosoftware/invenio-oauthclient | invenio_oauthclient/contrib/cern.py | https://github.com/inveniosoftware/invenio-oauthclient/blob/2500dc6935738107617aeade79e050d7608004bb/invenio_oauthclient/contrib/cern.py#L219-L229 | def fetch_extra_data(resource):
"""Return a dict with extra data retrieved from cern oauth."""
person_id = resource.get('PersonID', [None])[0]
identity_class = resource.get('IdentityClass', [None])[0]
department = resource.get('Department', [None])[0]
return dict(
person_id=person_id,
... | [
"def",
"fetch_extra_data",
"(",
"resource",
")",
":",
"person_id",
"=",
"resource",
".",
"get",
"(",
"'PersonID'",
",",
"[",
"None",
"]",
")",
"[",
"0",
"]",
"identity_class",
"=",
"resource",
".",
"get",
"(",
"'IdentityClass'",
",",
"[",
"None",
"]",
... | Return a dict with extra data retrieved from cern oauth. | [
"Return",
"a",
"dict",
"with",
"extra",
"data",
"retrieved",
"from",
"cern",
"oauth",
"."
] | python | train | 34.454545 |
napalm-automation/napalm-yang | napalm_yang/jinja_filters/ip_filters.py | https://github.com/napalm-automation/napalm-yang/blob/998e8a933171d010b8544bcc5dc448e2b68051e2/napalm_yang/jinja_filters/ip_filters.py#L73-L84 | def prefix_to_addrmask(value, sep=" "):
"""
Converts a CIDR formatted prefix into an address netmask representation.
Argument sep specifies the separator between the address and netmask parts.
By default it's a single space.
Examples:
>>> "{{ '192.168.0.1/24|prefix_to_addrmask }}" -> "192.1... | [
"def",
"prefix_to_addrmask",
"(",
"value",
",",
"sep",
"=",
"\" \"",
")",
":",
"prefix",
"=",
"netaddr",
".",
"IPNetwork",
"(",
"value",
")",
"return",
"\"{}{}{}\"",
".",
"format",
"(",
"prefix",
".",
"ip",
",",
"sep",
",",
"prefix",
".",
"netmask",
")... | Converts a CIDR formatted prefix into an address netmask representation.
Argument sep specifies the separator between the address and netmask parts.
By default it's a single space.
Examples:
>>> "{{ '192.168.0.1/24|prefix_to_addrmask }}" -> "192.168.0.1 255.255.255.0"
>>> "{{ '192.168.0.1/2... | [
"Converts",
"a",
"CIDR",
"formatted",
"prefix",
"into",
"an",
"address",
"netmask",
"representation",
".",
"Argument",
"sep",
"specifies",
"the",
"separator",
"between",
"the",
"address",
"and",
"netmask",
"parts",
".",
"By",
"default",
"it",
"s",
"a",
"single... | python | test | 43.833333 |
RockFeng0/rtsf-web | webuidriver/actions.py | https://github.com/RockFeng0/rtsf-web/blob/ceabcf62ddf1c969a97b5c7a4a4c547198b6ea71/webuidriver/actions.py#L647-L653 | def Alt(cls, key):
""" 在指定元素上执行alt组合事件
@note: key event -> alt + key
@param key: 如'X'
"""
element = cls._element()
element.send_keys(Keys.ALT, key) | [
"def",
"Alt",
"(",
"cls",
",",
"key",
")",
":",
"element",
"=",
"cls",
".",
"_element",
"(",
")",
"element",
".",
"send_keys",
"(",
"Keys",
".",
"ALT",
",",
"key",
")"
] | 在指定元素上执行alt组合事件
@note: key event -> alt + key
@param key: 如'X' | [
"在指定元素上执行alt组合事件"
] | python | train | 28.428571 |
mlperf/training | object_detection/pytorch/maskrcnn_benchmark/utils/cv2_util.py | https://github.com/mlperf/training/blob/1c6ae725a81d15437a2b2df05cac0673fde5c3a4/object_detection/pytorch/maskrcnn_benchmark/utils/cv2_util.py#L8-L24 | def findContours(*args, **kwargs):
"""
Wraps cv2.findContours to maintain compatiblity between versions
3 and 4
Returns:
contours, hierarchy
"""
if cv2.__version__.startswith('4'):
contours, hierarchy = cv2.findContours(*args, **kwargs)
elif cv2.__version__.startswith('3'):
... | [
"def",
"findContours",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"if",
"cv2",
".",
"__version__",
".",
"startswith",
"(",
"'4'",
")",
":",
"contours",
",",
"hierarchy",
"=",
"cv2",
".",
"findContours",
"(",
"*",
"args",
",",
"*",
"*",
"k... | Wraps cv2.findContours to maintain compatiblity between versions
3 and 4
Returns:
contours, hierarchy | [
"Wraps",
"cv2",
".",
"findContours",
"to",
"maintain",
"compatiblity",
"between",
"versions",
"3",
"and",
"4"
] | python | train | 30.058824 |
mrcagney/gtfstk | gtfstk/miscellany.py | https://github.com/mrcagney/gtfstk/blob/c91494e6fefc02523889655a0dc92d1c0eee8d03/gtfstk/miscellany.py#L736-L805 | def restrict_to_routes(feed: "Feed", route_ids: List[str]) -> "Feed":
"""
Build a new feed by restricting this one to only the stops,
trips, shapes, etc. used by the routes with the given list of
route IDs.
Return the resulting feed.
"""
# Initialize the new feed as the old feed.
# Restr... | [
"def",
"restrict_to_routes",
"(",
"feed",
":",
"\"Feed\"",
",",
"route_ids",
":",
"List",
"[",
"str",
"]",
")",
"->",
"\"Feed\"",
":",
"# Initialize the new feed as the old feed.",
"# Restrict its DataFrames below.",
"feed",
"=",
"feed",
".",
"copy",
"(",
")",
"# ... | Build a new feed by restricting this one to only the stops,
trips, shapes, etc. used by the routes with the given list of
route IDs.
Return the resulting feed. | [
"Build",
"a",
"new",
"feed",
"by",
"restricting",
"this",
"one",
"to",
"only",
"the",
"stops",
"trips",
"shapes",
"etc",
".",
"used",
"by",
"the",
"routes",
"with",
"the",
"given",
"list",
"of",
"route",
"IDs",
".",
"Return",
"the",
"resulting",
"feed",
... | python | train | 30.957143 |
amperser/proselint | proselint/checks/typography/symbols.py | https://github.com/amperser/proselint/blob/cb619ee4023cc7856f5fb96aec2a33a2c9f1a2e2/proselint/checks/typography/symbols.py#L34-L41 | def check_trademark_symbol(text):
"""Use the trademark symbol instead of (TM)."""
err = "typography.symbols.trademark"
msg = u"(TM) is a goofy alphabetic approximation, use the symbol ™."
regex = "\(TM\)"
return existence_check(
text, [regex], err, msg, max_errors=3, require_padding=False) | [
"def",
"check_trademark_symbol",
"(",
"text",
")",
":",
"err",
"=",
"\"typography.symbols.trademark\"",
"msg",
"=",
"u\"(TM) is a goofy alphabetic approximation, use the symbol ™.\"",
"regex",
"=",
"\"\\(TM\\)\"",
"return",
"existence_check",
"(",
"text",
",",
"[",
"regex",... | Use the trademark symbol instead of (TM). | [
"Use",
"the",
"trademark",
"symbol",
"instead",
"of",
"(",
"TM",
")",
"."
] | python | train | 39 |
epfl-lts2/pygsp | pygsp/graphs/_io.py | https://github.com/epfl-lts2/pygsp/blob/8ce5bde39206129287375af24fdbcd7edddca8c5/pygsp/graphs/_io.py#L252-L330 | def from_networkx(cls, graph, weight='weight'):
r"""Import a graph from NetworkX.
Edge weights are retrieved as an edge attribute,
under the name specified by the ``weight`` parameter.
Signals are retrieved from node attributes,
and stored in the :attr:`signals` dictionary unde... | [
"def",
"from_networkx",
"(",
"cls",
",",
"graph",
",",
"weight",
"=",
"'weight'",
")",
":",
"nx",
"=",
"_import_networkx",
"(",
")",
"from",
".",
"graph",
"import",
"Graph",
"adjacency",
"=",
"nx",
".",
"to_scipy_sparse_matrix",
"(",
"graph",
",",
"weight"... | r"""Import a graph from NetworkX.
Edge weights are retrieved as an edge attribute,
under the name specified by the ``weight`` parameter.
Signals are retrieved from node attributes,
and stored in the :attr:`signals` dictionary under the attribute name.
`N`-dimensional signals th... | [
"r",
"Import",
"a",
"graph",
"from",
"NetworkX",
"."
] | python | train | 33.063291 |
aganezov/bg | bg/tree.py | https://github.com/aganezov/bg/blob/1ec758193441e49e7b34e0da09571480f4c24455/bg/tree.py#L139-L148 | def get_distance(self, node1_name, node2_name):
""" Returns a length of an edge / path, if exists, from the current tree
:param node1_name: a first node name in current tree
:param node2_name: a second node name in current tree
:return: a length of specified by a pair of vertices edge /... | [
"def",
"get_distance",
"(",
"self",
",",
"node1_name",
",",
"node2_name",
")",
":",
"return",
"self",
".",
"__root",
".",
"get_distance",
"(",
"target",
"=",
"node1_name",
",",
"target2",
"=",
"node2_name",
")"
] | Returns a length of an edge / path, if exists, from the current tree
:param node1_name: a first node name in current tree
:param node2_name: a second node name in current tree
:return: a length of specified by a pair of vertices edge / path
:rtype: `Number`
:raises: ValueError, ... | [
"Returns",
"a",
"length",
"of",
"an",
"edge",
"/",
"path",
"if",
"exists",
"from",
"the",
"current",
"tree"
] | python | train | 53.1 |
ThreatConnect-Inc/tcex | tcex/tcex_resources.py | https://github.com/ThreatConnect-Inc/tcex/blob/dd4d7a1ef723af1561687120191886b9a2fd4b47/tcex/tcex_resources.py#L807-L835 | def security_label_pivot(self, security_label_resource):
"""Pivot point on security labels for this resource.
This method will return all *resources* (group, indicators, task,
victims, etc) for this resource that have the provided security
label applied.
**Example Endpoints URI... | [
"def",
"security_label_pivot",
"(",
"self",
",",
"security_label_resource",
")",
":",
"resource",
"=",
"self",
".",
"copy",
"(",
")",
"resource",
".",
"_request_uri",
"=",
"'{}/{}'",
".",
"format",
"(",
"security_label_resource",
".",
"request_uri",
",",
"resour... | Pivot point on security labels for this resource.
This method will return all *resources* (group, indicators, task,
victims, etc) for this resource that have the provided security
label applied.
**Example Endpoints URI's**
+--------------+--------------------------------------... | [
"Pivot",
"point",
"on",
"security",
"labels",
"for",
"this",
"resource",
"."
] | python | train | 56.655172 |
log2timeline/plaso | plaso/cli/log2timeline_tool.py | https://github.com/log2timeline/plaso/blob/9c564698d2da3ffbe23607a3c54c0582ea18a6cc/plaso/cli/log2timeline_tool.py#L454-L466 | def ShowInfo(self):
"""Shows information about available hashers, parsers, plugins, etc."""
self._output_writer.Write(
'{0:=^80s}\n'.format(' log2timeline/plaso information '))
plugin_list = self._GetPluginData()
for header, data in plugin_list.items():
table_view = views.ViewsFactory.Get... | [
"def",
"ShowInfo",
"(",
"self",
")",
":",
"self",
".",
"_output_writer",
".",
"Write",
"(",
"'{0:=^80s}\\n'",
".",
"format",
"(",
"' log2timeline/plaso information '",
")",
")",
"plugin_list",
"=",
"self",
".",
"_GetPluginData",
"(",
")",
"for",
"header",
",",... | Shows information about available hashers, parsers, plugins, etc. | [
"Shows",
"information",
"about",
"available",
"hashers",
"parsers",
"plugins",
"etc",
"."
] | python | train | 43.461538 |
DiamondLightSource/python-workflows | workflows/transport/stomp_transport.py | https://github.com/DiamondLightSource/python-workflows/blob/7ef47b457655b96f4d2ef7ee9863cf1b6d20e023/workflows/transport/stomp_transport.py#L466-L475 | def _nack(self, message_id, subscription_id, **kwargs):
"""Reject receipt of a message. This only makes sense when the
'acknowledgement' flag was set for the relevant subscription.
:param message_id: ID of the message to be rejected
:param subscription: ID of the relevant subscriptiong
... | [
"def",
"_nack",
"(",
"self",
",",
"message_id",
",",
"subscription_id",
",",
"*",
"*",
"kwargs",
")",
":",
"self",
".",
"_conn",
".",
"nack",
"(",
"message_id",
",",
"subscription_id",
",",
"*",
"*",
"kwargs",
")"
] | Reject receipt of a message. This only makes sense when the
'acknowledgement' flag was set for the relevant subscription.
:param message_id: ID of the message to be rejected
:param subscription: ID of the relevant subscriptiong
:param **kwargs: Further parameters for the transport layer.... | [
"Reject",
"receipt",
"of",
"a",
"message",
".",
"This",
"only",
"makes",
"sense",
"when",
"the",
"acknowledgement",
"flag",
"was",
"set",
"for",
"the",
"relevant",
"subscription",
".",
":",
"param",
"message_id",
":",
"ID",
"of",
"the",
"message",
"to",
"b... | python | train | 58.1 |
Telefonica/toolium | toolium/driver_wrapper.py | https://github.com/Telefonica/toolium/blob/56847c243b3a98876df74c184b75e43f8810e475/toolium/driver_wrapper.py#L325-L341 | def should_reuse_driver(self, scope, test_passed, context=None):
"""Check if the driver should be reused
:param scope: execution scope (function, module, class or session)
:param test_passed: True if the test has passed
:param context: behave context
:returns: True if the driver... | [
"def",
"should_reuse_driver",
"(",
"self",
",",
"scope",
",",
"test_passed",
",",
"context",
"=",
"None",
")",
":",
"reuse_driver",
"=",
"self",
".",
"config",
".",
"getboolean_optional",
"(",
"'Driver'",
",",
"'reuse_driver'",
")",
"reuse_driver_session",
"=",
... | Check if the driver should be reused
:param scope: execution scope (function, module, class or session)
:param test_passed: True if the test has passed
:param context: behave context
:returns: True if the driver should be reused | [
"Check",
"if",
"the",
"driver",
"should",
"be",
"reused"
] | python | train | 66 |
rahul13ramesh/hidden_markov | hidden_markov/hmm_class.py | https://github.com/rahul13ramesh/hidden_markov/blob/6ba6012665f9e09c980ff70901604d051ba57dcc/hidden_markov/hmm_class.py#L194-L277 | def viterbi(self,observations):
""" The probability of occurence of the observation sequence
**Arguments**:
:param observations: The observation sequence, where each element belongs to 'observations' variable declared with __init__ object.
:type observations: A list or tuple
... | [
"def",
"viterbi",
"(",
"self",
",",
"observations",
")",
":",
"# Find total states,observations",
"total_stages",
"=",
"len",
"(",
"observations",
")",
"num_states",
"=",
"len",
"(",
"self",
".",
"states",
")",
"# initialize data",
"# Path stores the state sequence gi... | The probability of occurence of the observation sequence
**Arguments**:
:param observations: The observation sequence, where each element belongs to 'observations' variable declared with __init__ object.
:type observations: A list or tuple
:return: Returns a list of hidden states.
... | [
"The",
"probability",
"of",
"occurence",
"of",
"the",
"observation",
"sequence"
] | python | train | 37.25 |
Richienb/quilt | src/quilt_lang/__init__.py | https://github.com/Richienb/quilt/blob/4a659cac66f5286ad046d54a12fd850be5606643/src/quilt_lang/__init__.py#L1575-L1597 | def convertbase(number, base=10):
"""
Convert a number in base 10 to another base
:type number: number
:param number: The number to convert
:type base: integer
:param base: The base to convert to.
"""
integer = number
if not integer:
return '0'
sign = 1 if integer > 0 ... | [
"def",
"convertbase",
"(",
"number",
",",
"base",
"=",
"10",
")",
":",
"integer",
"=",
"number",
"if",
"not",
"integer",
":",
"return",
"'0'",
"sign",
"=",
"1",
"if",
"integer",
">",
"0",
"else",
"-",
"1",
"alphanum",
"=",
"string",
".",
"digits",
... | Convert a number in base 10 to another base
:type number: number
:param number: The number to convert
:type base: integer
:param base: The base to convert to. | [
"Convert",
"a",
"number",
"in",
"base",
"10",
"to",
"another",
"base"
] | python | train | 24.26087 |
Aluriak/ACCC | accc/langspec/langspec.py | https://github.com/Aluriak/ACCC/blob/9092f985bef7ed784264c86bc19c980f4ce2309f/accc/langspec/langspec.py#L149-L163 | def cpp_spec():
"""C++ specification, provided for example, and java compatible."""
return {
INDENTATION : '\t',
BEG_BLOCK : '{',
END_BLOCK : '}',
BEG_LINE : '',
END_LINE : '\n',
BEG_ACTION : '',
END_ACTION : ';',
B... | [
"def",
"cpp_spec",
"(",
")",
":",
"return",
"{",
"INDENTATION",
":",
"'\\t'",
",",
"BEG_BLOCK",
":",
"'{'",
",",
"END_BLOCK",
":",
"'}'",
",",
"BEG_LINE",
":",
"''",
",",
"END_LINE",
":",
"'\\n'",
",",
"BEG_ACTION",
":",
"''",
",",
"END_ACTION",
":",
... | C++ specification, provided for example, and java compatible. | [
"C",
"++",
"specification",
"provided",
"for",
"example",
"and",
"java",
"compatible",
"."
] | python | train | 28.6 |
knipknap/SpiffWorkflow | SpiffWorkflow/util/event.py | https://github.com/knipknap/SpiffWorkflow/blob/f0af7f59a332e0619e4f3c00a7d4a3d230760e00/SpiffWorkflow/util/event.py#L219-L237 | def disconnect(self, callback):
"""
Disconnects the signal from the given function.
:type callback: object
:param callback: The callback function.
"""
if self.weak_subscribers is not None:
with self.lock:
index = self._weakly_connected_index(... | [
"def",
"disconnect",
"(",
"self",
",",
"callback",
")",
":",
"if",
"self",
".",
"weak_subscribers",
"is",
"not",
"None",
":",
"with",
"self",
".",
"lock",
":",
"index",
"=",
"self",
".",
"_weakly_connected_index",
"(",
"callback",
")",
"if",
"index",
"is... | Disconnects the signal from the given function.
:type callback: object
:param callback: The callback function. | [
"Disconnects",
"the",
"signal",
"from",
"the",
"given",
"function",
"."
] | python | valid | 34.210526 |
ktbyers/netmiko | netmiko/cisco_base_connection.py | https://github.com/ktbyers/netmiko/blob/54e6116c0b4664de2123081937e0a9a27bdfdfea/netmiko/cisco_base_connection.py#L53-L57 | def exit_config_mode(self, exit_config="end", pattern="#"):
"""Exit from configuration mode."""
return super(CiscoBaseConnection, self).exit_config_mode(
exit_config=exit_config, pattern=pattern
) | [
"def",
"exit_config_mode",
"(",
"self",
",",
"exit_config",
"=",
"\"end\"",
",",
"pattern",
"=",
"\"#\"",
")",
":",
"return",
"super",
"(",
"CiscoBaseConnection",
",",
"self",
")",
".",
"exit_config_mode",
"(",
"exit_config",
"=",
"exit_config",
",",
"pattern"... | Exit from configuration mode. | [
"Exit",
"from",
"configuration",
"mode",
"."
] | python | train | 45.6 |
pvlib/pvlib-python | pvlib/forecast.py | https://github.com/pvlib/pvlib-python/blob/2e844a595b820b43d1170269781fa66bd0ccc8a3/pvlib/forecast.py#L393-L428 | def cloud_cover_to_ghi_linear(self, cloud_cover, ghi_clear, offset=35,
**kwargs):
"""
Convert cloud cover to GHI using a linear relationship.
0% cloud cover returns ghi_clear.
100% cloud cover returns offset*ghi_clear.
Parameters
-----... | [
"def",
"cloud_cover_to_ghi_linear",
"(",
"self",
",",
"cloud_cover",
",",
"ghi_clear",
",",
"offset",
"=",
"35",
",",
"*",
"*",
"kwargs",
")",
":",
"offset",
"=",
"offset",
"/",
"100.",
"cloud_cover",
"=",
"cloud_cover",
"/",
"100.",
"ghi",
"=",
"(",
"of... | Convert cloud cover to GHI using a linear relationship.
0% cloud cover returns ghi_clear.
100% cloud cover returns offset*ghi_clear.
Parameters
----------
cloud_cover: numeric
Cloud cover in %.
ghi_clear: numeric
GHI under clear sky conditions.
... | [
"Convert",
"cloud",
"cover",
"to",
"GHI",
"using",
"a",
"linear",
"relationship",
"."
] | python | train | 27.722222 |
napalm-automation/napalm | napalm/nxos_ssh/nxos_ssh.py | https://github.com/napalm-automation/napalm/blob/c11ae8bb5ce395698704a0051cdf8d144fbb150d/napalm/nxos_ssh/nxos_ssh.py#L279-L347 | def bgp_table_parser(bgp_table):
"""Generator that parses a line of bgp summary table and returns a dict compatible with NAPALM
Example line:
10.2.1.14 4 10 472516 472238 361 0 0 3w1d 9
"""
bgp_table = bgp_table.strip()
for bgp_entry in bgp_table.splitlines():
... | [
"def",
"bgp_table_parser",
"(",
"bgp_table",
")",
":",
"bgp_table",
"=",
"bgp_table",
".",
"strip",
"(",
")",
"for",
"bgp_entry",
"in",
"bgp_table",
".",
"splitlines",
"(",
")",
":",
"bgp_table_fields",
"=",
"bgp_entry",
".",
"split",
"(",
")",
"try",
":",... | Generator that parses a line of bgp summary table and returns a dict compatible with NAPALM
Example line:
10.2.1.14 4 10 472516 472238 361 0 0 3w1d 9 | [
"Generator",
"that",
"parses",
"a",
"line",
"of",
"bgp",
"summary",
"table",
"and",
"returns",
"a",
"dict",
"compatible",
"with",
"NAPALM"
] | python | train | 29.463768 |
TissueMAPS/TmDeploy | elasticluster/elasticluster/providers/ansible_provider.py | https://github.com/TissueMAPS/TmDeploy/blob/f891b4ffb21431988bc4a063ae871da3bf284a45/elasticluster/elasticluster/providers/ansible_provider.py#L148-L277 | def setup_cluster(self, cluster, extra_args=tuple()):
"""
Configure the cluster by running an Ansible playbook.
The ElastiCluster configuration attribute `<kind>_groups`
determines, for each node kind, what Ansible groups nodes of
that kind are assigned to.
:param clust... | [
"def",
"setup_cluster",
"(",
"self",
",",
"cluster",
",",
"extra_args",
"=",
"tuple",
"(",
")",
")",
":",
"inventory_path",
"=",
"self",
".",
"_build_inventory",
"(",
"cluster",
")",
"if",
"inventory_path",
"is",
"None",
":",
"# No inventory file has been create... | Configure the cluster by running an Ansible playbook.
The ElastiCluster configuration attribute `<kind>_groups`
determines, for each node kind, what Ansible groups nodes of
that kind are assigned to.
:param cluster: cluster to configure
:type cluster: :py:class:`elasticluster.c... | [
"Configure",
"the",
"cluster",
"by",
"running",
"an",
"Ansible",
"playbook",
"."
] | python | train | 43.2 |
arviz-devs/arviz | arviz/plots/plot_utils.py | https://github.com/arviz-devs/arviz/blob/d04d8da07f029fd2931f48d2f7f324cf393e5277/arviz/plots/plot_utils.py#L312-L344 | def xarray_to_ndarray(data, *, var_names=None, combined=True):
"""Take xarray data and unpacks into variables and data into list and numpy array respectively.
Assumes that chain and draw are in coordinates
Parameters
----------
data: xarray.DataSet
Data in an xarray from an InferenceData o... | [
"def",
"xarray_to_ndarray",
"(",
"data",
",",
"*",
",",
"var_names",
"=",
"None",
",",
"combined",
"=",
"True",
")",
":",
"unpacked_data",
",",
"unpacked_var_names",
",",
"=",
"[",
"]",
",",
"[",
"]",
"# Merge chains and variables",
"for",
"var_name",
",",
... | Take xarray data and unpacks into variables and data into list and numpy array respectively.
Assumes that chain and draw are in coordinates
Parameters
----------
data: xarray.DataSet
Data in an xarray from an InferenceData object. Examples include posterior or sample_stats
var_names: iter... | [
"Take",
"xarray",
"data",
"and",
"unpacks",
"into",
"variables",
"and",
"data",
"into",
"list",
"and",
"numpy",
"array",
"respectively",
"."
] | python | train | 31.060606 |
DataDog/integrations-core | vsphere/datadog_checks/vsphere/cache_config.py | https://github.com/DataDog/integrations-core/blob/ebd41c873cf9f97a8c51bf9459bc6a7536af8acd/vsphere/datadog_checks/vsphere/cache_config.py#L29-L37 | def clear(self):
"""
Reset the config object to its initial state
"""
with self._lock:
self._config = {
CacheConfig.Morlist: {'last': defaultdict(float), 'intl': {}},
CacheConfig.Metadata: {'last': defaultdict(float), 'intl': {}},
} | [
"def",
"clear",
"(",
"self",
")",
":",
"with",
"self",
".",
"_lock",
":",
"self",
".",
"_config",
"=",
"{",
"CacheConfig",
".",
"Morlist",
":",
"{",
"'last'",
":",
"defaultdict",
"(",
"float",
")",
",",
"'intl'",
":",
"{",
"}",
"}",
",",
"CacheConf... | Reset the config object to its initial state | [
"Reset",
"the",
"config",
"object",
"to",
"its",
"initial",
"state"
] | python | train | 34.666667 |
nerdvegas/rez | src/rez/vendor/pygraph/classes/digraph.py | https://github.com/nerdvegas/rez/blob/1d3b846d53b5b5404edfe8ddb9083f9ceec8c5e7/src/rez/vendor/pygraph/classes/digraph.py#L178-L198 | def del_node(self, node):
"""
Remove a node from the graph.
@type node: node
@param node: Node identifier.
"""
for each in list(self.incidents(node)):
# Delete all the edges incident on this node
self.del_edge((each, node))
... | [
"def",
"del_node",
"(",
"self",
",",
"node",
")",
":",
"for",
"each",
"in",
"list",
"(",
"self",
".",
"incidents",
"(",
"node",
")",
")",
":",
"# Delete all the edges incident on this node",
"self",
".",
"del_edge",
"(",
"(",
"each",
",",
"node",
")",
")... | Remove a node from the graph.
@type node: node
@param node: Node identifier. | [
"Remove",
"a",
"node",
"from",
"the",
"graph",
"."
] | python | train | 33.142857 |
saltstack/salt | salt/states/boto_ec2.py | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/states/boto_ec2.py#L1221-L1309 | def volumes_tagged(name, tag_maps, authoritative=False, region=None, key=None,
keyid=None, profile=None):
'''
Ensure EC2 volume(s) matching the given filters have the defined tags.
.. versionadded:: 2016.11.0
name
State definition name.
tag_maps
List of dicts of... | [
"def",
"volumes_tagged",
"(",
"name",
",",
"tag_maps",
",",
"authoritative",
"=",
"False",
",",
"region",
"=",
"None",
",",
"key",
"=",
"None",
",",
"keyid",
"=",
"None",
",",
"profile",
"=",
"None",
")",
":",
"ret",
"=",
"{",
"'name'",
":",
"name",
... | Ensure EC2 volume(s) matching the given filters have the defined tags.
.. versionadded:: 2016.11.0
name
State definition name.
tag_maps
List of dicts of filters and tags, where 'filters' is a dict suitable for passing
to the 'filters' argument of boto_ec2.get_all_volumes(), and 't... | [
"Ensure",
"EC2",
"volume",
"(",
"s",
")",
"matching",
"the",
"given",
"filters",
"have",
"the",
"defined",
"tags",
"."
] | python | train | 32.314607 |
Autodesk/aomi | aomi/template.py | https://github.com/Autodesk/aomi/blob/84da2dfb0424837adf9c4ddc1aa352e942bb7a4a/aomi/template.py#L104-L116 | def missing_vars(template_vars, parsed_content, obj):
"""If we find missing variables when rendering a template
we want to give the user a friendly error"""
missing = []
default_vars = grok_vars(parsed_content)
for var in template_vars:
if var not in default_vars and var not in obj:
... | [
"def",
"missing_vars",
"(",
"template_vars",
",",
"parsed_content",
",",
"obj",
")",
":",
"missing",
"=",
"[",
"]",
"default_vars",
"=",
"grok_vars",
"(",
"parsed_content",
")",
"for",
"var",
"in",
"template_vars",
":",
"if",
"var",
"not",
"in",
"default_var... | If we find missing variables when rendering a template
we want to give the user a friendly error | [
"If",
"we",
"find",
"missing",
"variables",
"when",
"rendering",
"a",
"template",
"we",
"want",
"to",
"give",
"the",
"user",
"a",
"friendly",
"error"
] | python | train | 36.538462 |
googleapis/google-cloud-python | firestore/google/cloud/firestore_v1beta1/gapic/firestore_client.py | https://github.com/googleapis/google-cloud-python/blob/85e80125a59cb10f8cb105f25ecc099e4b940b50/firestore/google/cloud/firestore_v1beta1/gapic/firestore_client.py#L669-L742 | def delete_document(
self,
name,
current_document=None,
retry=google.api_core.gapic_v1.method.DEFAULT,
timeout=google.api_core.gapic_v1.method.DEFAULT,
metadata=None,
):
"""
Deletes a document.
Example:
>>> from google.cloud import... | [
"def",
"delete_document",
"(",
"self",
",",
"name",
",",
"current_document",
"=",
"None",
",",
"retry",
"=",
"google",
".",
"api_core",
".",
"gapic_v1",
".",
"method",
".",
"DEFAULT",
",",
"timeout",
"=",
"google",
".",
"api_core",
".",
"gapic_v1",
".",
... | Deletes a document.
Example:
>>> from google.cloud import firestore_v1beta1
>>>
>>> client = firestore_v1beta1.FirestoreClient()
>>>
>>> name = client.any_path_path('[PROJECT]', '[DATABASE]', '[DOCUMENT]', '[ANY_PATH]')
>>>
>>>... | [
"Deletes",
"a",
"document",
"."
] | python | train | 42.648649 |
idlesign/django-sitegate | sitegate/flows_base.py | https://github.com/idlesign/django-sitegate/blob/0e58de91605071833d75a7c21f2d0de2f2e3c896/sitegate/flows_base.py#L82-L88 | def login_generic(request, username, password):
"""Helper method. Generic login with username and password."""
user = authenticate(username=username, password=password)
if user is not None and user.is_active:
login(request, user)
return True
return False | [
"def",
"login_generic",
"(",
"request",
",",
"username",
",",
"password",
")",
":",
"user",
"=",
"authenticate",
"(",
"username",
"=",
"username",
",",
"password",
"=",
"password",
")",
"if",
"user",
"is",
"not",
"None",
"and",
"user",
".",
"is_active",
... | Helper method. Generic login with username and password. | [
"Helper",
"method",
".",
"Generic",
"login",
"with",
"username",
"and",
"password",
"."
] | python | train | 43.428571 |
instana/python-sensor | instana/meter.py | https://github.com/instana/python-sensor/blob/58aecb90924c48bafcbc4f93bd9b7190980918bc/instana/meter.py#L191-L207 | def handle_agent_tasks(self, task):
"""
When request(s) are received by the host agent, it is sent here
for handling & processing.
"""
logger.debug("Received agent request with messageId: %s" % task["messageId"])
if "action" in task:
if task["action"] == "pyth... | [
"def",
"handle_agent_tasks",
"(",
"self",
",",
"task",
")",
":",
"logger",
".",
"debug",
"(",
"\"Received agent request with messageId: %s\"",
"%",
"task",
"[",
"\"messageId\"",
"]",
")",
"if",
"\"action\"",
"in",
"task",
":",
"if",
"task",
"[",
"\"action\"",
... | When request(s) are received by the host agent, it is sent here
for handling & processing. | [
"When",
"request",
"(",
"s",
")",
"are",
"received",
"by",
"the",
"host",
"agent",
"it",
"is",
"sent",
"here",
"for",
"handling",
"&",
"processing",
"."
] | python | train | 46.588235 |
numenta/nupic | src/nupic/algorithms/knn_classifier.py | https://github.com/numenta/nupic/blob/5922fafffdccc8812e72b3324965ad2f7d4bbdad/src/nupic/algorithms/knn_classifier.py#L226-L257 | def clear(self):
"""Clears the state of the KNNClassifier."""
self._Memory = None
self._numPatterns = 0
self._M = None
self._categoryList = []
self._partitionIdList = []
self._partitionIdMap = {}
self._finishedLearning = False
self._iterationIdx = -1
# Fixed capacity KNN
if ... | [
"def",
"clear",
"(",
"self",
")",
":",
"self",
".",
"_Memory",
"=",
"None",
"self",
".",
"_numPatterns",
"=",
"0",
"self",
".",
"_M",
"=",
"None",
"self",
".",
"_categoryList",
"=",
"[",
"]",
"self",
".",
"_partitionIdList",
"=",
"[",
"]",
"self",
... | Clears the state of the KNNClassifier. | [
"Clears",
"the",
"state",
"of",
"the",
"KNNClassifier",
"."
] | python | valid | 26.75 |
jaredLunde/redis_structures | redis_structures/__init__.py | https://github.com/jaredLunde/redis_structures/blob/b9cce5f5c85db5e12c292633ff8d04e3ae053294/redis_structures/__init__.py#L1045-L1048 | def mget(self, *keys):
""" -> #list of values at the specified @keys """
return list(map(
self._loads, self._client.hmget(self.key_prefix, *keys))) | [
"def",
"mget",
"(",
"self",
",",
"*",
"keys",
")",
":",
"return",
"list",
"(",
"map",
"(",
"self",
".",
"_loads",
",",
"self",
".",
"_client",
".",
"hmget",
"(",
"self",
".",
"key_prefix",
",",
"*",
"keys",
")",
")",
")"
] | -> #list of values at the specified @keys | [
"-",
">",
"#list",
"of",
"values",
"at",
"the",
"specified"
] | python | train | 43 |
marcelcaraciolo/foursquare | examples/django/example/djfoursquare/views.py | https://github.com/marcelcaraciolo/foursquare/blob/a8bda33cc2d61e25aa8df72011246269fd98aa13/examples/django/example/djfoursquare/views.py#L73-L85 | def check_key(request):
"""
Check to see if we already have an access_key stored,
if we do then we have already gone through
OAuth. If not then we haven't and we probably need to.
"""
try:
access_key = request.session.get('oauth_token', None)
if not access_key:
return... | [
"def",
"check_key",
"(",
"request",
")",
":",
"try",
":",
"access_key",
"=",
"request",
".",
"session",
".",
"get",
"(",
"'oauth_token'",
",",
"None",
")",
"if",
"not",
"access_key",
":",
"return",
"False",
"except",
"KeyError",
":",
"return",
"False",
"... | Check to see if we already have an access_key stored,
if we do then we have already gone through
OAuth. If not then we haven't and we probably need to. | [
"Check",
"to",
"see",
"if",
"we",
"already",
"have",
"an",
"access_key",
"stored",
"if",
"we",
"do",
"then",
"we",
"have",
"already",
"gone",
"through",
"OAuth",
".",
"If",
"not",
"then",
"we",
"haven",
"t",
"and",
"we",
"probably",
"need",
"to",
"."
] | python | train | 28.615385 |
nickfrostatx/walls | walls.py | https://github.com/nickfrostatx/walls/blob/866f33335cf410565d6e51fdcd880770e6d089b0/walls.py#L73-L78 | def clear_dir(path):
"""Empty out the image directory."""
for f in os.listdir(path):
f_path = os.path.join(path, f)
if os.path.isfile(f_path) or os.path.islink(f_path):
os.unlink(f_path) | [
"def",
"clear_dir",
"(",
"path",
")",
":",
"for",
"f",
"in",
"os",
".",
"listdir",
"(",
"path",
")",
":",
"f_path",
"=",
"os",
".",
"path",
".",
"join",
"(",
"path",
",",
"f",
")",
"if",
"os",
".",
"path",
".",
"isfile",
"(",
"f_path",
")",
"... | Empty out the image directory. | [
"Empty",
"out",
"the",
"image",
"directory",
"."
] | python | train | 36.166667 |
wavycloud/pyboto3 | pyboto3/s3.py | https://github.com/wavycloud/pyboto3/blob/924957ccf994303713a4eed90b775ff2ab95b2e5/pyboto3/s3.py#L209-L390 | def copy_object(ACL=None, Bucket=None, CacheControl=None, ContentDisposition=None, ContentEncoding=None, ContentLanguage=None, ContentType=None, CopySource=None, CopySourceIfMatch=None, CopySourceIfModifiedSince=None, CopySourceIfNoneMatch=None, CopySourceIfUnmodifiedSince=None, Expires=None, GrantFullControl=None, Gra... | [
"def",
"copy_object",
"(",
"ACL",
"=",
"None",
",",
"Bucket",
"=",
"None",
",",
"CacheControl",
"=",
"None",
",",
"ContentDisposition",
"=",
"None",
",",
"ContentEncoding",
"=",
"None",
",",
"ContentLanguage",
"=",
"None",
",",
"ContentType",
"=",
"None",
... | Creates a copy of an object that is already stored in Amazon S3.
See also: AWS API Documentation
:example: response = client.copy_object(
ACL='private'|'public-read'|'public-read-write'|'authenticated-read'|'aws-exec-read'|'bucket-owner-read'|'bucket-owner-full-control',
Bucket='string... | [
"Creates",
"a",
"copy",
"of",
"an",
"object",
"that",
"is",
"already",
"stored",
"in",
"Amazon",
"S3",
".",
"See",
"also",
":",
"AWS",
"API",
"Documentation",
":",
"example",
":",
"response",
"=",
"client",
".",
"copy_object",
"(",
"ACL",
"=",
"private",... | python | train | 56.879121 |
Robpol86/etaprogress | etaprogress/eta.py | https://github.com/Robpol86/etaprogress/blob/224e8a248c2bf820bad218763281914ad3983fff/etaprogress/eta.py#L90-L96 | def rate_unstable(self):
"""Returns an unstable rate based on the last two entries in the timing data. Less intensive to compute."""
if not self.started or self.stalled:
return 0.0
x1, y1 = self._timing_data[-2]
x2, y2 = self._timing_data[-1]
return (y2 - y1) / (x2 - ... | [
"def",
"rate_unstable",
"(",
"self",
")",
":",
"if",
"not",
"self",
".",
"started",
"or",
"self",
".",
"stalled",
":",
"return",
"0.0",
"x1",
",",
"y1",
"=",
"self",
".",
"_timing_data",
"[",
"-",
"2",
"]",
"x2",
",",
"y2",
"=",
"self",
".",
"_ti... | Returns an unstable rate based on the last two entries in the timing data. Less intensive to compute. | [
"Returns",
"an",
"unstable",
"rate",
"based",
"on",
"the",
"last",
"two",
"entries",
"in",
"the",
"timing",
"data",
".",
"Less",
"intensive",
"to",
"compute",
"."
] | python | train | 45.285714 |
mattja/nsim | nsim/timeseries.py | https://github.com/mattja/nsim/blob/ed62c41cd56b918fd97e09f7ad73c12c76a8c3e0/nsim/timeseries.py#L517-L540 | def reshape(self, newshape, order='C'):
"""If axis 0 is unaffected by the reshape, then returns a Timeseries,
otherwise returns an ndarray. Preserves labels of axis j only if all
axes<=j are unaffected by the reshape.
See ``numpy.ndarray.reshape()`` for more information
"""
... | [
"def",
"reshape",
"(",
"self",
",",
"newshape",
",",
"order",
"=",
"'C'",
")",
":",
"oldshape",
"=",
"self",
".",
"shape",
"ar",
"=",
"np",
".",
"asarray",
"(",
"self",
")",
".",
"reshape",
"(",
"newshape",
",",
"order",
"=",
"order",
")",
"if",
... | If axis 0 is unaffected by the reshape, then returns a Timeseries,
otherwise returns an ndarray. Preserves labels of axis j only if all
axes<=j are unaffected by the reshape.
See ``numpy.ndarray.reshape()`` for more information | [
"If",
"axis",
"0",
"is",
"unaffected",
"by",
"the",
"reshape",
"then",
"returns",
"a",
"Timeseries",
"otherwise",
"returns",
"an",
"ndarray",
".",
"Preserves",
"labels",
"of",
"axis",
"j",
"only",
"if",
"all",
"axes<",
"=",
"j",
"are",
"unaffected",
"by",
... | python | train | 48.458333 |
MoseleyBioinformaticsLab/nmrstarlib | nmrstarlib/bmrblex.py | https://github.com/MoseleyBioinformaticsLab/nmrstarlib/blob/f2adabbca04d5a134ce6ba3211099d1457787ff2/nmrstarlib/bmrblex.py#L97-L206 | def bmrblex(text):
"""A lexical analyzer for the BMRB NMR-STAR format syntax.
:param text: Input text.
:type text: :py:class:`str` or :py:class:`bytes`
:return: Current token.
:rtype: :py:class:`str`
"""
stream = transform_text(text)
wordchars = (u"abcdfeghijklmnopqrstuvwxyz"
... | [
"def",
"bmrblex",
"(",
"text",
")",
":",
"stream",
"=",
"transform_text",
"(",
"text",
")",
"wordchars",
"=",
"(",
"u\"abcdfeghijklmnopqrstuvwxyz\"",
"u\"ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789_\"",
"u\"ßàáâãäåæçèéêëìíîïðñòóôõöøùúûüýþÿ\"",
"u\"ÀÁÂÃÄÅÆÇÈÉÊËÌÍÎÏÐÑÒÓÔÕÖØÙÚÛÜÝÞ\"",
"u... | A lexical analyzer for the BMRB NMR-STAR format syntax.
:param text: Input text.
:type text: :py:class:`str` or :py:class:`bytes`
:return: Current token.
:rtype: :py:class:`str` | [
"A",
"lexical",
"analyzer",
"for",
"the",
"BMRB",
"NMR",
"-",
"STAR",
"format",
"syntax",
"."
] | python | train | 29.818182 |
reanahub/reana-commons | reana_commons/tasks.py | https://github.com/reanahub/reana-commons/blob/abf31d9f495e0d93171c43fc4a414cd292091b11/reana_commons/tasks.py#L54-L65 | def check_running_job_count():
"""Check upper limit on running jobs."""
try:
job_list = current_k8s_batchv1_api_client.\
list_job_for_all_namespaces()
if len(job_list.items) > K8S_MAXIMUM_CONCURRENT_JOBS:
return False
except ApiException as e:
log.error('Somet... | [
"def",
"check_running_job_count",
"(",
")",
":",
"try",
":",
"job_list",
"=",
"current_k8s_batchv1_api_client",
".",
"list_job_for_all_namespaces",
"(",
")",
"if",
"len",
"(",
"job_list",
".",
"items",
")",
">",
"K8S_MAXIMUM_CONCURRENT_JOBS",
":",
"return",
"False",... | Check upper limit on running jobs. | [
"Check",
"upper",
"limit",
"on",
"running",
"jobs",
"."
] | python | train | 34.666667 |
tensorflow/tensor2tensor | tensor2tensor/layers/common_image_attention.py | https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/layers/common_image_attention.py#L72-L79 | def maybe_reshape_4d_to_3d(x):
"""Reshape input from 4D to 3D if necessary."""
x_shape = common_layers.shape_list(x)
is_4d = False
if len(x_shape) == 4:
x = tf.reshape(x, [x_shape[0], x_shape[1]*x_shape[2], x_shape[3]])
is_4d = True
return x, x_shape, is_4d | [
"def",
"maybe_reshape_4d_to_3d",
"(",
"x",
")",
":",
"x_shape",
"=",
"common_layers",
".",
"shape_list",
"(",
"x",
")",
"is_4d",
"=",
"False",
"if",
"len",
"(",
"x_shape",
")",
"==",
"4",
":",
"x",
"=",
"tf",
".",
"reshape",
"(",
"x",
",",
"[",
"x_... | Reshape input from 4D to 3D if necessary. | [
"Reshape",
"input",
"from",
"4D",
"to",
"3D",
"if",
"necessary",
"."
] | python | train | 33.5 |
tensorflow/tensorboard | tensorboard/notebook.py | https://github.com/tensorflow/tensorboard/blob/8e5f497b48e40f2a774f85416b8a35ac0693c35e/tensorboard/notebook.py#L118-L207 | def start(args_string):
"""Launch and display a TensorBoard instance as if at the command line.
Args:
args_string: Command-line arguments to TensorBoard, to be
interpreted by `shlex.split`: e.g., "--logdir ./logs --port 0".
Shell metacharacters are not supported: e.g., "--logdir 2>&1" will
po... | [
"def",
"start",
"(",
"args_string",
")",
":",
"context",
"=",
"_get_context",
"(",
")",
"try",
":",
"import",
"IPython",
"import",
"IPython",
".",
"display",
"except",
"ImportError",
":",
"IPython",
"=",
"None",
"if",
"context",
"==",
"_CONTEXT_NONE",
":",
... | Launch and display a TensorBoard instance as if at the command line.
Args:
args_string: Command-line arguments to TensorBoard, to be
interpreted by `shlex.split`: e.g., "--logdir ./logs --port 0".
Shell metacharacters are not supported: e.g., "--logdir 2>&1" will
point the logdir at the literal... | [
"Launch",
"and",
"display",
"a",
"TensorBoard",
"instance",
"as",
"if",
"at",
"the",
"command",
"line",
"."
] | python | train | 28.366667 |
Pylons/hupper | src/hupper/reloader.py | https://github.com/Pylons/hupper/blob/197173c09e775b66c148468b6299c571e736c381/src/hupper/reloader.py#L123-L138 | def run_once(self):
"""
Execute the worker once.
This method will return after a file change is detected.
"""
self._capture_signals()
self._start_monitor()
try:
self._run_worker()
except KeyboardInterrupt:
return
finally:
... | [
"def",
"run_once",
"(",
"self",
")",
":",
"self",
".",
"_capture_signals",
"(",
")",
"self",
".",
"_start_monitor",
"(",
")",
"try",
":",
"self",
".",
"_run_worker",
"(",
")",
"except",
"KeyboardInterrupt",
":",
"return",
"finally",
":",
"self",
".",
"_s... | Execute the worker once.
This method will return after a file change is detected. | [
"Execute",
"the",
"worker",
"once",
"."
] | python | train | 23.3125 |
androguard/androguard | androguard/core/analysis/analysis.py | https://github.com/androguard/androguard/blob/984c0d981be2950cf0451e484f7b0d4d53bc4911/androguard/core/analysis/analysis.py#L916-L942 | def is_android_api(self):
"""
Tries to guess if the current class is an Android API class.
This might be not very precise unless an apilist is given, with classes that
are in fact known APIs.
Such a list might be generated by using the android.jar files.
:return: boolea... | [
"def",
"is_android_api",
"(",
"self",
")",
":",
"# Packages found at https://developer.android.com/reference/packages.html",
"api_candidates",
"=",
"[",
"\"Landroid/\"",
",",
"\"Lcom/android/internal/util\"",
",",
"\"Ldalvik/\"",
",",
"\"Ljava/\"",
",",
"\"Ljavax/\"",
",",
"\... | Tries to guess if the current class is an Android API class.
This might be not very precise unless an apilist is given, with classes that
are in fact known APIs.
Such a list might be generated by using the android.jar files.
:return: boolean | [
"Tries",
"to",
"guess",
"if",
"the",
"current",
"class",
"is",
"an",
"Android",
"API",
"class",
"."
] | python | train | 36.222222 |
log2timeline/dfdatetime | dfdatetime/delphi_date_time.py | https://github.com/log2timeline/dfdatetime/blob/141ca4ef1eff3d354b5deaac3d81cb08506f98d6/dfdatetime/delphi_date_time.py#L56-L71 | def _GetNormalizedTimestamp(self):
"""Retrieves the normalized timestamp.
Returns:
decimal.Decimal: normalized timestamp, which contains the number of
seconds since January 1, 1970 00:00:00 and a fraction of second used
for increased precision, or None if the normalized timestamp cann... | [
"def",
"_GetNormalizedTimestamp",
"(",
"self",
")",
":",
"if",
"self",
".",
"_normalized_timestamp",
"is",
"None",
":",
"if",
"self",
".",
"_timestamp",
"is",
"not",
"None",
":",
"self",
".",
"_normalized_timestamp",
"=",
"(",
"decimal",
".",
"Decimal",
"(",... | Retrieves the normalized timestamp.
Returns:
decimal.Decimal: normalized timestamp, which contains the number of
seconds since January 1, 1970 00:00:00 and a fraction of second used
for increased precision, or None if the normalized timestamp cannot be
determined. | [
"Retrieves",
"the",
"normalized",
"timestamp",
"."
] | python | train | 40 |
saltstack/salt | salt/modules/cyg.py | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/cyg.py#L106-L134 | def check_valid_package(package,
cyg_arch='x86_64',
mirrors=None):
'''
Check if the package is valid on the given mirrors.
Args:
package: The name of the package
cyg_arch: The cygwin architecture
mirrors: any mirrors to check
Retu... | [
"def",
"check_valid_package",
"(",
"package",
",",
"cyg_arch",
"=",
"'x86_64'",
",",
"mirrors",
"=",
"None",
")",
":",
"if",
"mirrors",
"is",
"None",
":",
"mirrors",
"=",
"[",
"{",
"DEFAULT_MIRROR",
":",
"DEFAULT_MIRROR_KEY",
"}",
"]",
"LOG",
".",
"debug",... | Check if the package is valid on the given mirrors.
Args:
package: The name of the package
cyg_arch: The cygwin architecture
mirrors: any mirrors to check
Returns (bool): True if Valid, otherwise False
CLI Example:
.. code-block:: bash
salt '*' cyg.check_valid_packag... | [
"Check",
"if",
"the",
"package",
"is",
"valid",
"on",
"the",
"given",
"mirrors",
"."
] | python | train | 26.37931 |
MillionIntegrals/vel | vel/phase/cycle.py | https://github.com/MillionIntegrals/vel/blob/e0726e1f63742b728966ccae0c8b825ea0ba491a/vel/phase/cycle.py#L119-L132 | def set_up_phase(self, training_info, model, source):
""" Prepare the phase for learning """
# To parameter groups handles properly filtering parameters that don't require gradient
self._optimizer_instance = self.optimizer_factory.instantiate(model)
self._source = source
self.sp... | [
"def",
"set_up_phase",
"(",
"self",
",",
"training_info",
",",
"model",
",",
"source",
")",
":",
"# To parameter groups handles properly filtering parameters that don't require gradient",
"self",
".",
"_optimizer_instance",
"=",
"self",
".",
"optimizer_factory",
".",
"insta... | Prepare the phase for learning | [
"Prepare",
"the",
"phase",
"for",
"learning"
] | python | train | 46.714286 |
Hackerfleet/hfos | hfos/tool/create_module.py | https://github.com/Hackerfleet/hfos/blob/b6df14eacaffb6be5c844108873ff8763ec7f0c9/hfos/tool/create_module.py#L148-L170 | def create_module(clear_target, target):
"""Creates a new template HFOS plugin module"""
if os.path.exists(target):
if clear_target:
shutil.rmtree(target)
else:
log("Target exists! Use --clear to delete it first.",
emitter='MANAGE')
sys.exit(2... | [
"def",
"create_module",
"(",
"clear_target",
",",
"target",
")",
":",
"if",
"os",
".",
"path",
".",
"exists",
"(",
"target",
")",
":",
"if",
"clear_target",
":",
"shutil",
".",
"rmtree",
"(",
"target",
")",
"else",
":",
"log",
"(",
"\"Target exists! Use ... | Creates a new template HFOS plugin module | [
"Creates",
"a",
"new",
"template",
"HFOS",
"plugin",
"module"
] | python | train | 27.347826 |
mila-iqia/fuel | fuel/server.py | https://github.com/mila-iqia/fuel/blob/1d6292dc25e3a115544237e392e61bff6631d23c/fuel/server.py#L84-L131 | def start_server(data_stream, port=5557, hwm=10):
"""Start a data processing server.
This command starts a server in the current process that performs the
actual data processing (by retrieving data from the given data stream).
It also starts a second process, the broker, which mediates between the
... | [
"def",
"start_server",
"(",
"data_stream",
",",
"port",
"=",
"5557",
",",
"hwm",
"=",
"10",
")",
":",
"logging",
".",
"basicConfig",
"(",
"level",
"=",
"'INFO'",
")",
"context",
"=",
"zmq",
".",
"Context",
"(",
")",
"socket",
"=",
"context",
".",
"so... | Start a data processing server.
This command starts a server in the current process that performs the
actual data processing (by retrieving data from the given data stream).
It also starts a second process, the broker, which mediates between the
server and the client. The broker also keeps a buffer of ... | [
"Start",
"a",
"data",
"processing",
"server",
"."
] | python | train | 36.645833 |
davenquinn/Attitude | attitude/stereonet.py | https://github.com/davenquinn/Attitude/blob/2ce97b9aba0aa5deedc6617c2315e07e6396d240/attitude/stereonet.py#L114-L154 | def plane_errors(axes, covariance_matrix, sheet='upper',**kwargs):
"""
kwargs:
traditional_layout boolean [True]
Lay the stereonet out traditionally, with north at the pole of
the diagram. The default is a more natural and intuitive visualization
with vertical at the pole and the co... | [
"def",
"plane_errors",
"(",
"axes",
",",
"covariance_matrix",
",",
"sheet",
"=",
"'upper'",
",",
"*",
"*",
"kwargs",
")",
":",
"level",
"=",
"kwargs",
".",
"pop",
"(",
"'level'",
",",
"1",
")",
"traditional_layout",
"=",
"kwargs",
".",
"pop",
"(",
"'tr... | kwargs:
traditional_layout boolean [True]
Lay the stereonet out traditionally, with north at the pole of
the diagram. The default is a more natural and intuitive visualization
with vertical at the pole and the compass points of strike around the equator.
Thus, longitude at the equat... | [
"kwargs",
":",
"traditional_layout",
"boolean",
"[",
"True",
"]",
"Lay",
"the",
"stereonet",
"out",
"traditionally",
"with",
"north",
"at",
"the",
"pole",
"of",
"the",
"diagram",
".",
"The",
"default",
"is",
"a",
"more",
"natural",
"and",
"intuitive",
"visua... | python | train | 28.195122 |
hyperledger/indy-plenum | plenum/server/monitor.py | https://github.com/hyperledger/indy-plenum/blob/dcd144e238af7f17a869ffc9412f13dc488b7020/plenum/server/monitor.py#L456-L466 | def instance_throughput_ratio(self, inst_id):
"""
The relative throughput of an instance compared to the backup
instances.
"""
inst_thrp, otherThrp = self.getThroughputs(inst_id)
# Backup throughput may be 0 so moving ahead only if it is not 0
r = inst_thrp / oth... | [
"def",
"instance_throughput_ratio",
"(",
"self",
",",
"inst_id",
")",
":",
"inst_thrp",
",",
"otherThrp",
"=",
"self",
".",
"getThroughputs",
"(",
"inst_id",
")",
"# Backup throughput may be 0 so moving ahead only if it is not 0",
"r",
"=",
"inst_thrp",
"/",
"otherThrp"... | The relative throughput of an instance compared to the backup
instances. | [
"The",
"relative",
"throughput",
"of",
"an",
"instance",
"compared",
"to",
"the",
"backup",
"instances",
"."
] | python | train | 36 |
CityOfZion/neo-python-rpc | neorpc/Client.py | https://github.com/CityOfZion/neo-python-rpc/blob/89d22c4043654b2941bf26b15a1c09082901d9ef/neorpc/Client.py#L298-L308 | def get_validators(self, id=None, endpoint=None):
"""
Returns the current NEO consensus nodes information and voting status.
Args:
id: (int, optional) id to use for response tracking
endpoint: (RPCEndpoint, optional) endpoint to specify to use
Returns:
... | [
"def",
"get_validators",
"(",
"self",
",",
"id",
"=",
"None",
",",
"endpoint",
"=",
"None",
")",
":",
"return",
"self",
".",
"_call_endpoint",
"(",
"GET_VALIDATORS",
",",
"id",
"=",
"id",
",",
"endpoint",
"=",
"endpoint",
")"
] | Returns the current NEO consensus nodes information and voting status.
Args:
id: (int, optional) id to use for response tracking
endpoint: (RPCEndpoint, optional) endpoint to specify to use
Returns:
json object of the result or the error encountered in the RPC call | [
"Returns",
"the",
"current",
"NEO",
"consensus",
"nodes",
"information",
"and",
"voting",
"status",
".",
"Args",
":",
"id",
":",
"(",
"int",
"optional",
")",
"id",
"to",
"use",
"for",
"response",
"tracking",
"endpoint",
":",
"(",
"RPCEndpoint",
"optional",
... | python | train | 42.454545 |
pivotal-energy-solutions/django-datatable-view | datatableview/cache.py | https://github.com/pivotal-energy-solutions/django-datatable-view/blob/00b77a9b5051c34e258c51b06c020e92edf15034/datatableview/cache.py#L54-L98 | def get_cache_key(datatable_class, view=None, user=None, **kwargs):
"""
Returns a cache key unique to the current table, and (if available) the request user.
The ``view`` argument should be the class reference itself, since it is easily obtainable
in contexts where the instance is not available.
""... | [
"def",
"get_cache_key",
"(",
"datatable_class",
",",
"view",
"=",
"None",
",",
"user",
"=",
"None",
",",
"*",
"*",
"kwargs",
")",
":",
"datatable_name",
"=",
"datatable_class",
".",
"__name__",
"if",
"datatable_name",
".",
"endswith",
"(",
"'_Synthesized'",
... | Returns a cache key unique to the current table, and (if available) the request user.
The ``view`` argument should be the class reference itself, since it is easily obtainable
in contexts where the instance is not available. | [
"Returns",
"a",
"cache",
"key",
"unique",
"to",
"the",
"current",
"table",
"and",
"(",
"if",
"available",
")",
"the",
"request",
"user",
"."
] | python | train | 35.2 |
mpg-age-bioinformatics/AGEpy | AGEpy/cytoscape.py | https://github.com/mpg-age-bioinformatics/AGEpy/blob/887808a7a2c1504f39ce8d8cb36c15c1721cd29f/AGEpy/cytoscape.py#L117-L171 | def getTableColumns(table, columns, namespace = "default", network = "current", host=cytoscape_host,port=cytoscape_port,verbose=False):
"""
Gets tables from cytoscape
:param table: table to retrieve eg. node
:param columns: columns to retrieve in list format
:param namespace: namepsace, default... | [
"def",
"getTableColumns",
"(",
"table",
",",
"columns",
",",
"namespace",
"=",
"\"default\"",
",",
"network",
"=",
"\"current\"",
",",
"host",
"=",
"cytoscape_host",
",",
"port",
"=",
"cytoscape_port",
",",
"verbose",
"=",
"False",
")",
":",
"if",
"type",
... | Gets tables from cytoscape
:param table: table to retrieve eg. node
:param columns: columns to retrieve in list format
:param namespace: namepsace, default="default"
:param network: a network name or id, default="current"
:param host: cytoscape host address, default=cytoscape_host
:param po... | [
"Gets",
"tables",
"from",
"cytoscape",
":",
"param",
"table",
":",
"table",
"to",
"retrieve",
"eg",
".",
"node",
":",
"param",
"columns",
":",
"columns",
"to",
"retrieve",
"in",
"list",
"format",
":",
"param",
"namespace",
":",
"namepsace",
"default",
"=",... | python | train | 30.890909 |
ktbyers/netmiko | netmiko/hp/hp_procurve.py | https://github.com/ktbyers/netmiko/blob/54e6116c0b4664de2123081937e0a9a27bdfdfea/netmiko/hp/hp_procurve.py#L66-L86 | def cleanup(self):
"""Gracefully exit the SSH session."""
self.exit_config_mode()
self.write_channel("logout" + self.RETURN)
count = 0
while count <= 5:
time.sleep(0.5)
output = self.read_channel()
if "Do you want to log out" in output:
... | [
"def",
"cleanup",
"(",
"self",
")",
":",
"self",
".",
"exit_config_mode",
"(",
")",
"self",
".",
"write_channel",
"(",
"\"logout\"",
"+",
"self",
".",
"RETURN",
")",
"count",
"=",
"0",
"while",
"count",
"<=",
"5",
":",
"time",
".",
"sleep",
"(",
"0.5... | Gracefully exit the SSH session. | [
"Gracefully",
"exit",
"the",
"SSH",
"session",
"."
] | python | train | 36.666667 |
mikedh/trimesh | trimesh/proximity.py | https://github.com/mikedh/trimesh/blob/25e059bf6d4caa74f62ffd58ce4f61a90ee4e518/trimesh/proximity.py#L352-L465 | def max_tangent_sphere(mesh,
points,
inwards=True,
normals=None,
threshold=1e-6,
max_iter=100):
"""
Find the center and radius of the sphere which is tangent to
the mesh at the given point and ... | [
"def",
"max_tangent_sphere",
"(",
"mesh",
",",
"points",
",",
"inwards",
"=",
"True",
",",
"normals",
"=",
"None",
",",
"threshold",
"=",
"1e-6",
",",
"max_iter",
"=",
"100",
")",
":",
"points",
"=",
"np",
".",
"asanyarray",
"(",
"points",
",",
"dtype"... | Find the center and radius of the sphere which is tangent to
the mesh at the given point and at least one more point with no
non-tangential intersections with the mesh.
Masatomo Inui, Nobuyuki Umezu & Ryohei Shimane (2016)
Shrinking sphere:
A parallel algorithm for computing the thickness of 3D obj... | [
"Find",
"the",
"center",
"and",
"radius",
"of",
"the",
"sphere",
"which",
"is",
"tangent",
"to",
"the",
"mesh",
"at",
"the",
"given",
"point",
"and",
"at",
"least",
"one",
"more",
"point",
"with",
"no",
"non",
"-",
"tangential",
"intersections",
"with",
... | python | train | 39.578947 |
openvax/mhcflurry | mhcflurry/encodable_sequences.py | https://github.com/openvax/mhcflurry/blob/deb7c1629111254b484a2711619eb2347db36524/mhcflurry/encodable_sequences.py#L53-L87 | def variable_length_to_fixed_length_categorical(
self, left_edge=4, right_edge=4, max_length=15):
"""
Encode variable-length sequences using a fixed-length encoding designed
for preserving the anchor positions of class I peptides.
The sequences must be of length at l... | [
"def",
"variable_length_to_fixed_length_categorical",
"(",
"self",
",",
"left_edge",
"=",
"4",
",",
"right_edge",
"=",
"4",
",",
"max_length",
"=",
"15",
")",
":",
"cache_key",
"=",
"(",
"\"fixed_length_categorical\"",
",",
"left_edge",
",",
"right_edge",
",",
"... | Encode variable-length sequences using a fixed-length encoding designed
for preserving the anchor positions of class I peptides.
The sequences must be of length at least left_edge + right_edge, and at
most max_length.
Parameters
----------
left_edge : in... | [
"Encode",
"variable",
"-",
"length",
"sequences",
"using",
"a",
"fixed",
"-",
"length",
"encoding",
"designed",
"for",
"preserving",
"the",
"anchor",
"positions",
"of",
"class",
"I",
"peptides",
".",
"The",
"sequences",
"must",
"be",
"of",
"length",
"at",
"l... | python | train | 36.085714 |
bethgelab/foolbox | foolbox/attacks/adef_attack.py | https://github.com/bethgelab/foolbox/blob/8ab54248c70e45d8580a7d9ee44c9c0fb5755c4a/foolbox/attacks/adef_attack.py#L120-L163 | def _create_vec_field(fval, gradf, d1x, d2x, color_axis, smooth=0):
"""Calculate the deformation vector field
In:
fval: float
gradf: numpy.ndarray
of shape C x h x w with C = 3 or C = 1
(color channels), h, w >= 1.
d1x: numpy.ndarray
of shape C x h x w and [type] = 'Float' or... | [
"def",
"_create_vec_field",
"(",
"fval",
",",
"gradf",
",",
"d1x",
",",
"d2x",
",",
"color_axis",
",",
"smooth",
"=",
"0",
")",
":",
"if",
"color_axis",
"==",
"2",
":",
"gradf",
"=",
"_transpose_image",
"(",
"gradf",
")",
"c",
",",
"h",
",",
"w",
"... | Calculate the deformation vector field
In:
fval: float
gradf: numpy.ndarray
of shape C x h x w with C = 3 or C = 1
(color channels), h, w >= 1.
d1x: numpy.ndarray
of shape C x h x w and [type] = 'Float' or 'Double'.
d2x: numpy.ndarray
of shape C x h x w and [type] = '... | [
"Calculate",
"the",
"deformation",
"vector",
"field",
"In",
":",
"fval",
":",
"float",
"gradf",
":",
"numpy",
".",
"ndarray",
"of",
"shape",
"C",
"x",
"h",
"x",
"w",
"with",
"C",
"=",
"3",
"or",
"C",
"=",
"1",
"(",
"color",
"channels",
")",
"h",
... | python | valid | 31.954545 |
iotile/coretools | transport_plugins/bled112/iotile_transport_bled112/bled112.py | https://github.com/iotile/coretools/blob/2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec/transport_plugins/bled112/iotile_transport_bled112/bled112.py#L181-L184 | def start_scan(self, active):
"""Start the scanning task"""
self._command_task.sync_command(['_start_scan', active])
self.scanning = True | [
"def",
"start_scan",
"(",
"self",
",",
"active",
")",
":",
"self",
".",
"_command_task",
".",
"sync_command",
"(",
"[",
"'_start_scan'",
",",
"active",
"]",
")",
"self",
".",
"scanning",
"=",
"True"
] | Start the scanning task | [
"Start",
"the",
"scanning",
"task"
] | python | train | 39.5 |
jtwhite79/pyemu | pyemu/pst/pst_handler.py | https://github.com/jtwhite79/pyemu/blob/c504d8e7a4097cec07655a6318d275739bd8148a/pyemu/pst/pst_handler.py#L2605-L2620 | def greater_than_pi_constraints(self):
"""get the names of the prior information eqs that
are listed as greater than inequality constraints. Zero-
weighted pi are skipped
Returns
-------
pandas.Series : pilbl of prior information that are non-zero weighted
... | [
"def",
"greater_than_pi_constraints",
"(",
"self",
")",
":",
"pi",
"=",
"self",
".",
"prior_information",
"gt_pi",
"=",
"pi",
".",
"loc",
"[",
"pi",
".",
"apply",
"(",
"lambda",
"x",
":",
"self",
".",
"_is_greater_const",
"(",
"x",
".",
"obgnme",
")",
... | get the names of the prior information eqs that
are listed as greater than inequality constraints. Zero-
weighted pi are skipped
Returns
-------
pandas.Series : pilbl of prior information that are non-zero weighted
greater than constraints | [
"get",
"the",
"names",
"of",
"the",
"prior",
"information",
"eqs",
"that",
"are",
"listed",
"as",
"greater",
"than",
"inequality",
"constraints",
".",
"Zero",
"-",
"weighted",
"pi",
"are",
"skipped"
] | python | train | 35.5625 |
genialis/resolwe | resolwe/flow/executors/local/run.py | https://github.com/genialis/resolwe/blob/f7bb54932c81ec0cfc5b5e80d238fceaeaa48d86/resolwe/flow/executors/local/run.py#L45-L50 | async def run_script(self, script):
"""Execute the script and save results."""
script = os.linesep.join(['set -x', 'set +B', script, 'exit']) + os.linesep
self.proc.stdin.write(script.encode('utf-8'))
await self.proc.stdin.drain()
self.proc.stdin.close() | [
"async",
"def",
"run_script",
"(",
"self",
",",
"script",
")",
":",
"script",
"=",
"os",
".",
"linesep",
".",
"join",
"(",
"[",
"'set -x'",
",",
"'set +B'",
",",
"script",
",",
"'exit'",
"]",
")",
"+",
"os",
".",
"linesep",
"self",
".",
"proc",
"."... | Execute the script and save results. | [
"Execute",
"the",
"script",
"and",
"save",
"results",
"."
] | python | train | 48.166667 |
Jammy2211/PyAutoLens | autolens/data/array/grids.py | https://github.com/Jammy2211/PyAutoLens/blob/91e50369c7a9c048c83d217625578b72423cd5a7/autolens/data/array/grids.py#L460-L469 | def array_2d_from_array_1d(self, array_1d):
""" Map a 1D array the same dimension as the grid to its original masked 2D array.
Parameters
-----------
array_1d : ndarray
The 1D array which is mapped to its masked 2D array.
"""
return mapping_util.map_masked_1d... | [
"def",
"array_2d_from_array_1d",
"(",
"self",
",",
"array_1d",
")",
":",
"return",
"mapping_util",
".",
"map_masked_1d_array_to_2d_array_from_array_1d_shape_and_one_to_two",
"(",
"array_1d",
"=",
"array_1d",
",",
"shape",
"=",
"self",
".",
"mask",
".",
"shape",
",",
... | Map a 1D array the same dimension as the grid to its original masked 2D array.
Parameters
-----------
array_1d : ndarray
The 1D array which is mapped to its masked 2D array. | [
"Map",
"a",
"1D",
"array",
"the",
"same",
"dimension",
"as",
"the",
"grid",
"to",
"its",
"original",
"masked",
"2D",
"array",
"."
] | python | valid | 46.8 |
mesowx/MesoPy | MesoPy.py | https://github.com/mesowx/MesoPy/blob/cd1e837e108ed7a110d81cf789f19afcdd52145b/MesoPy.py#L127-L173 | def _get_response(self, endpoint, request_dict):
""" Returns a dictionary of data requested by each function.
Arguments:
----------
endpoint: string, mandatory
Set in all other methods, this is the API endpoint specific to each function.
request_dict: string, mandato... | [
"def",
"_get_response",
"(",
"self",
",",
"endpoint",
",",
"request_dict",
")",
":",
"http_error",
"=",
"'Could not connect to the API. This could be because you have no internet connection, a parameter'",
"' was input incorrectly, or the API is currently down. Please try again.'",
"json... | Returns a dictionary of data requested by each function.
Arguments:
----------
endpoint: string, mandatory
Set in all other methods, this is the API endpoint specific to each function.
request_dict: string, mandatory
A dictionary of parameters that are formatted ... | [
"Returns",
"a",
"dictionary",
"of",
"data",
"requested",
"by",
"each",
"function",
"."
] | python | train | 41.468085 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.