repo stringlengths 7 54 | path stringlengths 4 192 | url stringlengths 87 284 | code stringlengths 78 104k | code_tokens list | docstring stringlengths 1 46.9k | docstring_tokens list | language stringclasses 1
value | partition stringclasses 3
values |
|---|---|---|---|---|---|---|---|---|
gazpachoking/jsonref | jsonref.py | https://github.com/gazpachoking/jsonref/blob/066132e527f8115f75bcadfd0eca12f8973a6309/jsonref.py#L413-L424 | def dumps(obj, **kwargs):
"""
Serialize `obj`, which may contain :class:`JsonRef` objects, to a JSON
formatted string. `JsonRef` objects will be dumped as the original
reference object they were created from.
:param obj: Object to serialize
:param kwargs: Keyword arguments are the same as to :f... | [
"def",
"dumps",
"(",
"obj",
",",
"*",
"*",
"kwargs",
")",
":",
"kwargs",
"[",
"\"cls\"",
"]",
"=",
"_ref_encoder_factory",
"(",
"kwargs",
".",
"get",
"(",
"\"cls\"",
",",
"json",
".",
"JSONEncoder",
")",
")",
"return",
"json",
".",
"dumps",
"(",
"obj... | Serialize `obj`, which may contain :class:`JsonRef` objects, to a JSON
formatted string. `JsonRef` objects will be dumped as the original
reference object they were created from.
:param obj: Object to serialize
:param kwargs: Keyword arguments are the same as to :func:`json.dumps` | [
"Serialize",
"obj",
"which",
"may",
"contain",
":",
"class",
":",
"JsonRef",
"objects",
"to",
"a",
"JSON",
"formatted",
"string",
".",
"JsonRef",
"objects",
"will",
"be",
"dumped",
"as",
"the",
"original",
"reference",
"object",
"they",
"were",
"created",
"f... | python | train |
SmokinCaterpillar/pypet | pypet/naturalnaming.py | https://github.com/SmokinCaterpillar/pypet/blob/97ad3e80d46dbdea02deeb98ea41f05a19565826/pypet/naturalnaming.py#L3172-L3186 | def f_get_children(self, copy=True):
"""Returns a children dictionary.
:param copy:
Whether the group's original dictionary or a shallow copy is returned.
If you want the real dictionary please do not modify it at all!
:returns: Dictionary of nodes
"""
... | [
"def",
"f_get_children",
"(",
"self",
",",
"copy",
"=",
"True",
")",
":",
"if",
"copy",
":",
"return",
"self",
".",
"_children",
".",
"copy",
"(",
")",
"else",
":",
"return",
"self",
".",
"_children"
] | Returns a children dictionary.
:param copy:
Whether the group's original dictionary or a shallow copy is returned.
If you want the real dictionary please do not modify it at all!
:returns: Dictionary of nodes | [
"Returns",
"a",
"children",
"dictionary",
"."
] | python | test |
ryanpetrello/cleaver | cleaver/experiment.py | https://github.com/ryanpetrello/cleaver/blob/0ef266e1a0603c6d414df4b9926ce2a59844db35/cleaver/experiment.py#L167-L187 | def confidence_level(self):
"""
Based on the variant's Z-Score, returns a human-readable string that
describes the confidence with which we can say the results are
statistically significant.
"""
z = self.z_score
if isinstance(z, string_types):
return z... | [
"def",
"confidence_level",
"(",
"self",
")",
":",
"z",
"=",
"self",
".",
"z_score",
"if",
"isinstance",
"(",
"z",
",",
"string_types",
")",
":",
"return",
"z",
"z",
"=",
"abs",
"(",
"round",
"(",
"z",
",",
"3",
")",
")",
"if",
"z",
"==",
"0.0",
... | Based on the variant's Z-Score, returns a human-readable string that
describes the confidence with which we can say the results are
statistically significant. | [
"Based",
"on",
"the",
"variant",
"s",
"Z",
"-",
"Score",
"returns",
"a",
"human",
"-",
"readable",
"string",
"that",
"describes",
"the",
"confidence",
"with",
"which",
"we",
"can",
"say",
"the",
"results",
"are",
"statistically",
"significant",
"."
] | python | train |
AtteqCom/zsl | src/zsl/utils/xml_helper.py | https://github.com/AtteqCom/zsl/blob/ab51a96da1780ff642912396d4b85bdcb72560c1/src/zsl/utils/xml_helper.py#L111-L123 | def element_to_int(element, attribute=None):
"""Convert ``element`` object to int. If attribute is not given, convert ``element.text``.
:param element: ElementTree element
:param attribute: attribute name
:type attribute: str
:returns: integer
:rtype: int
"""
if attribute is not None:
... | [
"def",
"element_to_int",
"(",
"element",
",",
"attribute",
"=",
"None",
")",
":",
"if",
"attribute",
"is",
"not",
"None",
":",
"return",
"int",
"(",
"element",
".",
"get",
"(",
"attribute",
")",
")",
"else",
":",
"return",
"int",
"(",
"element",
".",
... | Convert ``element`` object to int. If attribute is not given, convert ``element.text``.
:param element: ElementTree element
:param attribute: attribute name
:type attribute: str
:returns: integer
:rtype: int | [
"Convert",
"element",
"object",
"to",
"int",
".",
"If",
"attribute",
"is",
"not",
"given",
"convert",
"element",
".",
"text",
"."
] | python | train |
onnx/onnxmltools | onnxutils/onnxconverter_common/topology.py | https://github.com/onnx/onnxmltools/blob/d4e4c31990fc2d9fd1f92139f497d360914c9df2/onnxutils/onnxconverter_common/topology.py#L281-L306 | def _generate_unique_name(seed, existing_names):
'''
Produce an unique string based on the seed
:param seed: a string
:param existing_names: a set containing strings which cannot be produced
:return: a string similar to the seed
'''
if seed == '':
rais... | [
"def",
"_generate_unique_name",
"(",
"seed",
",",
"existing_names",
")",
":",
"if",
"seed",
"==",
"''",
":",
"raise",
"ValueError",
"(",
"'Name seed must be an non-empty string'",
")",
"# Make the seed meet C-style naming convention",
"seed",
"=",
"re",
".",
"sub",
"(... | Produce an unique string based on the seed
:param seed: a string
:param existing_names: a set containing strings which cannot be produced
:return: a string similar to the seed | [
"Produce",
"an",
"unique",
"string",
"based",
"on",
"the",
"seed",
":",
"param",
"seed",
":",
"a",
"string",
":",
"param",
"existing_names",
":",
"a",
"set",
"containing",
"strings",
"which",
"cannot",
"be",
"produced",
":",
"return",
":",
"a",
"string",
... | python | train |
sensu-plugins/sensu-plugin-python | sensu_plugin/handler.py | https://github.com/sensu-plugins/sensu-plugin-python/blob/bd43a5ea4d191e5e63494c8679aab02ac072d9ed/sensu_plugin/handler.py#L76-L87 | def read_event(self, check_result):
'''
Convert the piped check result (json) into a global 'event' dict
'''
try:
event = json.loads(check_result)
event['occurrences'] = event.get('occurrences', 1)
event['check'] = event.get('check', {})
ev... | [
"def",
"read_event",
"(",
"self",
",",
"check_result",
")",
":",
"try",
":",
"event",
"=",
"json",
".",
"loads",
"(",
"check_result",
")",
"event",
"[",
"'occurrences'",
"]",
"=",
"event",
".",
"get",
"(",
"'occurrences'",
",",
"1",
")",
"event",
"[",
... | Convert the piped check result (json) into a global 'event' dict | [
"Convert",
"the",
"piped",
"check",
"result",
"(",
"json",
")",
"into",
"a",
"global",
"event",
"dict"
] | python | train |
koriakin/binflakes | binflakes/types/word.py | https://github.com/koriakin/binflakes/blob/f059cecadf1c605802a713c62375b5bd5606d53f/binflakes/types/word.py#L242-L249 | def sext(self, width):
"""Sign-extends a word to a larger width. It is an error to specify
a smaller width (use ``extract`` instead to crop off the extra bits).
"""
width = operator.index(width)
if width < self._width:
raise ValueError('sign extending to a smaller wi... | [
"def",
"sext",
"(",
"self",
",",
"width",
")",
":",
"width",
"=",
"operator",
".",
"index",
"(",
"width",
")",
"if",
"width",
"<",
"self",
".",
"_width",
":",
"raise",
"ValueError",
"(",
"'sign extending to a smaller width'",
")",
"return",
"BinWord",
"(",... | Sign-extends a word to a larger width. It is an error to specify
a smaller width (use ``extract`` instead to crop off the extra bits). | [
"Sign",
"-",
"extends",
"a",
"word",
"to",
"a",
"larger",
"width",
".",
"It",
"is",
"an",
"error",
"to",
"specify",
"a",
"smaller",
"width",
"(",
"use",
"extract",
"instead",
"to",
"crop",
"off",
"the",
"extra",
"bits",
")",
"."
] | python | train |
TestInABox/stackInABox | stackinabox/util/requests_mock/core.py | https://github.com/TestInABox/stackInABox/blob/63ee457401e9a88d987f85f513eb512dcb12d984/stackinabox/util/requests_mock/core.py#L78-L101 | def split_status(status):
"""Split a HTTP Status and Reason code string into a tuple.
:param status string containing the status and reason text or
the integer of the status code
:returns: tuple - (int, string) containing the integer status code
... | [
"def",
"split_status",
"(",
"status",
")",
":",
"# If the status is an integer, then lookup the reason text",
"if",
"isinstance",
"(",
"status",
",",
"int",
")",
":",
"return",
"(",
"status",
",",
"RequestMockCallable",
".",
"get_reason_for_status",
"(",
"status",
")"... | Split a HTTP Status and Reason code string into a tuple.
:param status string containing the status and reason text or
the integer of the status code
:returns: tuple - (int, string) containing the integer status code
and reason text string | [
"Split",
"a",
"HTTP",
"Status",
"and",
"Reason",
"code",
"string",
"into",
"a",
"tuple",
"."
] | python | train |
bastikr/boolean.py | boolean/boolean.py | https://github.com/bastikr/boolean.py/blob/e984df480afc60605e9501a0d3d54d667e8f7dbf/boolean/boolean.py#L505-L527 | def normalize(self, expr, operation):
"""
Return a normalized expression transformed to its normal form in the
given AND or OR operation.
The new expression arguments will satisfy these conditions:
- operation(*args) == expr (here mathematical equality is meant)
- the op... | [
"def",
"normalize",
"(",
"self",
",",
"expr",
",",
"operation",
")",
":",
"# ensure that the operation is not NOT",
"assert",
"operation",
"in",
"(",
"self",
".",
"AND",
",",
"self",
".",
"OR",
",",
")",
"# Move NOT inwards.",
"expr",
"=",
"expr",
".",
"lite... | Return a normalized expression transformed to its normal form in the
given AND or OR operation.
The new expression arguments will satisfy these conditions:
- operation(*args) == expr (here mathematical equality is meant)
- the operation does not occur in any of its arg.
- NOT is... | [
"Return",
"a",
"normalized",
"expression",
"transformed",
"to",
"its",
"normal",
"form",
"in",
"the",
"given",
"AND",
"or",
"OR",
"operation",
"."
] | python | train |
inasafe/inasafe | safe/gui/tools/batch/batch_dialog.py | https://github.com/inasafe/inasafe/blob/831d60abba919f6d481dc94a8d988cc205130724/safe/gui/tools/batch/batch_dialog.py#L849-L905 | def read_scenarios(filename):
"""Read keywords dictionary from file.
:param filename: Name of file holding scenarios .
:return Dictionary of with structure like this
{{ 'foo' : { 'a': 'b', 'c': 'd'},
{ 'bar' : { 'd': 'e', 'f': 'g'}}
A scenarios file may look like this:
[j... | [
"def",
"read_scenarios",
"(",
"filename",
")",
":",
"# Input checks",
"filename",
"=",
"os",
".",
"path",
".",
"abspath",
"(",
"filename",
")",
"blocks",
"=",
"{",
"}",
"parser",
"=",
"ConfigParser",
"(",
")",
"# Parse the file content.",
"# if the content don't... | Read keywords dictionary from file.
:param filename: Name of file holding scenarios .
:return Dictionary of with structure like this
{{ 'foo' : { 'a': 'b', 'c': 'd'},
{ 'bar' : { 'd': 'e', 'f': 'g'}}
A scenarios file may look like this:
[jakarta_flood]
hazard: /path/t... | [
"Read",
"keywords",
"dictionary",
"from",
"file",
"."
] | python | train |
synw/dataswim | dataswim/data/select.py | https://github.com/synw/dataswim/blob/4a4a53f80daa7cd8e8409d76a19ce07296269da2/dataswim/data/select.py#L13-L21 | def first_(self):
"""
Select the first row
"""
try:
val = self.df.iloc[0]
return val
except Exception as e:
self.err(e, "Can not select first row") | [
"def",
"first_",
"(",
"self",
")",
":",
"try",
":",
"val",
"=",
"self",
".",
"df",
".",
"iloc",
"[",
"0",
"]",
"return",
"val",
"except",
"Exception",
"as",
"e",
":",
"self",
".",
"err",
"(",
"e",
",",
"\"Can not select first row\"",
")"
] | Select the first row | [
"Select",
"the",
"first",
"row"
] | python | train |
brainiak/brainiak | brainiak/factoranalysis/tfa.py | https://github.com/brainiak/brainiak/blob/408f12dec2ff56559a26873a848a09e4c8facfeb/brainiak/factoranalysis/tfa.py#L908-L969 | def _fit_tfa_inner(
self,
data,
R,
template_centers,
template_widths,
template_centers_mean_cov,
template_widths_mean_var_reci):
"""Fit TFA model, the inner loop part
Parameters
----------
data: 2D arra... | [
"def",
"_fit_tfa_inner",
"(",
"self",
",",
"data",
",",
"R",
",",
"template_centers",
",",
"template_widths",
",",
"template_centers_mean_cov",
",",
"template_widths_mean_var_reci",
")",
":",
"nfeature",
"=",
"data",
".",
"shape",
"[",
"0",
"]",
"nsample",
"=",
... | Fit TFA model, the inner loop part
Parameters
----------
data: 2D array, in shape [n_voxel, n_tr]
The fMRI data of a subject
R : 2D array, in shape [n_voxel, n_dim]
The voxel coordinate matrix of fMRI data
template_centers: 1D array
The tem... | [
"Fit",
"TFA",
"model",
"the",
"inner",
"loop",
"part"
] | python | train |
ThreatConnect-Inc/tcex | tcex/tcex_bin_run.py | https://github.com/ThreatConnect-Inc/tcex/blob/dd4d7a1ef723af1561687120191886b9a2fd4b47/tcex/tcex_bin_run.py#L1468-L1514 | def stage_tc_associations(self, entity1, entity2):
"""Add an attribute to a resource.
Args:
entity1 (str): A Redis variable containing a TCEntity.
entity2 (str): A Redis variable containing a TCEntity.
"""
# resource 1
entity1 = self.tcex.playbook.read(en... | [
"def",
"stage_tc_associations",
"(",
"self",
",",
"entity1",
",",
"entity2",
")",
":",
"# resource 1",
"entity1",
"=",
"self",
".",
"tcex",
".",
"playbook",
".",
"read",
"(",
"entity1",
")",
"entity1_id",
"=",
"entity1",
".",
"get",
"(",
"'id'",
")",
"en... | Add an attribute to a resource.
Args:
entity1 (str): A Redis variable containing a TCEntity.
entity2 (str): A Redis variable containing a TCEntity. | [
"Add",
"an",
"attribute",
"to",
"a",
"resource",
"."
] | python | train |
arne-cl/discoursegraphs | src/discoursegraphs/discoursegraph.py | https://github.com/arne-cl/discoursegraphs/blob/842f0068a3190be2c75905754521b176b25a54fb/src/discoursegraphs/discoursegraph.py#L1048-L1078 | def select_neighbors_by_layer(docgraph, node, layer, data=False):
"""
Get all neighboring nodes belonging to (any of) the given layer(s),
A neighboring node is a node that the given node connects to with an
outgoing edge.
Parameters
----------
docgraph : DiscourseDocumentGraph
docum... | [
"def",
"select_neighbors_by_layer",
"(",
"docgraph",
",",
"node",
",",
"layer",
",",
"data",
"=",
"False",
")",
":",
"for",
"node_id",
"in",
"docgraph",
".",
"neighbors_iter",
"(",
"node",
")",
":",
"node_layers",
"=",
"docgraph",
".",
"node",
"[",
"node_i... | Get all neighboring nodes belonging to (any of) the given layer(s),
A neighboring node is a node that the given node connects to with an
outgoing edge.
Parameters
----------
docgraph : DiscourseDocumentGraph
document graph from which the nodes will be extracted
layer : str or collection... | [
"Get",
"all",
"neighboring",
"nodes",
"belonging",
"to",
"(",
"any",
"of",
")",
"the",
"given",
"layer",
"(",
"s",
")",
"A",
"neighboring",
"node",
"is",
"a",
"node",
"that",
"the",
"given",
"node",
"connects",
"to",
"with",
"an",
"outgoing",
"edge",
"... | python | train |
jbloomlab/phydms | phydmslib/weblogo.py | https://github.com/jbloomlab/phydms/blob/9cdebc10bafbe543c552d79486c7f950780ed3c0/phydmslib/weblogo.py#L561-L705 | def _my_eps_formatter(logodata, format, ordered_alphabets) :
""" Generate a logo in Encapsulated Postscript (EPS)
Modified from weblogo version 3.4 source code.
*ordered_alphabets* is a dictionary keyed by zero-indexed
consecutive sites, with values giving order of characters
from bottom to t... | [
"def",
"_my_eps_formatter",
"(",
"logodata",
",",
"format",
",",
"ordered_alphabets",
")",
":",
"substitutions",
"=",
"{",
"}",
"from_format",
"=",
"[",
"\"creation_date\"",
",",
"\"logo_width\"",
",",
"\"logo_height\"",
",",
"\"lines_per_logo\"",
",",
"\"line_width... | Generate a logo in Encapsulated Postscript (EPS)
Modified from weblogo version 3.4 source code.
*ordered_alphabets* is a dictionary keyed by zero-indexed
consecutive sites, with values giving order of characters
from bottom to top. | [
"Generate",
"a",
"logo",
"in",
"Encapsulated",
"Postscript",
"(",
"EPS",
")",
"Modified",
"from",
"weblogo",
"version",
"3",
".",
"4",
"source",
"code",
"."
] | python | train |
unt-libraries/pyuntl | pyuntl/util.py | https://github.com/unt-libraries/pyuntl/blob/f92413302897dab948aac18ee9e482ace0187bd4/pyuntl/util.py#L19-L23 | def normalize_UNTL(subject):
"""Normalize a UNTL subject heading for consistency."""
subject = subject.strip()
subject = re.sub(r'[\s]+', ' ', subject)
return subject | [
"def",
"normalize_UNTL",
"(",
"subject",
")",
":",
"subject",
"=",
"subject",
".",
"strip",
"(",
")",
"subject",
"=",
"re",
".",
"sub",
"(",
"r'[\\s]+'",
",",
"' '",
",",
"subject",
")",
"return",
"subject"
] | Normalize a UNTL subject heading for consistency. | [
"Normalize",
"a",
"UNTL",
"subject",
"heading",
"for",
"consistency",
"."
] | python | train |
SHTOOLS/SHTOOLS | pyshtools/shclasses/shgravcoeffs.py | https://github.com/SHTOOLS/SHTOOLS/blob/9a115cf83002df2ddec6b7f41aeb6be688e285de/pyshtools/shclasses/shgravcoeffs.py#L1243-L1336 | def spectrum(self, function='geoid', lmax=None, unit='per_l', base=10.):
"""
Return the spectrum as a function of spherical harmonic degree.
Usage
-----
spectrum, [error_spectrum] = x.spectrum([function, lmax, unit, base])
Returns
-------
spectrum : ndar... | [
"def",
"spectrum",
"(",
"self",
",",
"function",
"=",
"'geoid'",
",",
"lmax",
"=",
"None",
",",
"unit",
"=",
"'per_l'",
",",
"base",
"=",
"10.",
")",
":",
"if",
"function",
".",
"lower",
"(",
")",
"not",
"in",
"(",
"'potential'",
",",
"'geoid'",
",... | Return the spectrum as a function of spherical harmonic degree.
Usage
-----
spectrum, [error_spectrum] = x.spectrum([function, lmax, unit, base])
Returns
-------
spectrum : ndarray, shape (lmax+1)
1-D numpy ndarray of the spectrum, where lmax is the maximum
... | [
"Return",
"the",
"spectrum",
"as",
"a",
"function",
"of",
"spherical",
"harmonic",
"degree",
"."
] | python | train |
log2timeline/dfvfs | dfvfs/vfs/vshadow_file_system.py | https://github.com/log2timeline/dfvfs/blob/2b3ccd115f9901d89f383397d4a1376a873c83c4/dfvfs/vfs/vshadow_file_system.py#L123-L131 | def GetRootFileEntry(self):
"""Retrieves the root file entry.
Returns:
VShadowFileEntry: file entry or None if not available.
"""
path_spec = vshadow_path_spec.VShadowPathSpec(
location=self.LOCATION_ROOT, parent=self._path_spec.parent)
return self.GetFileEntryByPathSpec(path_spec) | [
"def",
"GetRootFileEntry",
"(",
"self",
")",
":",
"path_spec",
"=",
"vshadow_path_spec",
".",
"VShadowPathSpec",
"(",
"location",
"=",
"self",
".",
"LOCATION_ROOT",
",",
"parent",
"=",
"self",
".",
"_path_spec",
".",
"parent",
")",
"return",
"self",
".",
"Ge... | Retrieves the root file entry.
Returns:
VShadowFileEntry: file entry or None if not available. | [
"Retrieves",
"the",
"root",
"file",
"entry",
"."
] | python | train |
poppy-project/pypot | pypot/vrep/remoteApiBindings/vrep.py | https://github.com/poppy-project/pypot/blob/d9c6551bbc87d45d9d1f0bc15e35b616d0002afd/pypot/vrep/remoteApiBindings/vrep.py#L169-L174 | def simxSetJointPosition(clientID, jointHandle, position, operationMode):
'''
Please have a look at the function description/documentation in the V-REP user manual
'''
return c_SetJointPosition(clientID, jointHandle, position, operationMode) | [
"def",
"simxSetJointPosition",
"(",
"clientID",
",",
"jointHandle",
",",
"position",
",",
"operationMode",
")",
":",
"return",
"c_SetJointPosition",
"(",
"clientID",
",",
"jointHandle",
",",
"position",
",",
"operationMode",
")"
] | Please have a look at the function description/documentation in the V-REP user manual | [
"Please",
"have",
"a",
"look",
"at",
"the",
"function",
"description",
"/",
"documentation",
"in",
"the",
"V",
"-",
"REP",
"user",
"manual"
] | python | train |
EelcoHoogendoorn/Numpy_arraysetops_EP | numpy_indexed/funcs.py | https://github.com/EelcoHoogendoorn/Numpy_arraysetops_EP/blob/84dc8114bf8a79c3acb3f7f59128247b9fc97243/numpy_indexed/funcs.py#L199-L216 | def rank(keys, axis=semantics.axis_default):
"""where each item is in the pecking order.
Parameters
----------
keys : indexable object
Returns
-------
ndarray, [keys.size], int
unique integers, ranking the sorting order
Notes
-----
we should have that index.sorted[inde... | [
"def",
"rank",
"(",
"keys",
",",
"axis",
"=",
"semantics",
".",
"axis_default",
")",
":",
"index",
"=",
"as_index",
"(",
"keys",
",",
"axis",
")",
"return",
"index",
".",
"rank"
] | where each item is in the pecking order.
Parameters
----------
keys : indexable object
Returns
-------
ndarray, [keys.size], int
unique integers, ranking the sorting order
Notes
-----
we should have that index.sorted[index.rank] == keys | [
"where",
"each",
"item",
"is",
"in",
"the",
"pecking",
"order",
"."
] | python | train |
delfick/harpoon | harpoon/ship/runner.py | https://github.com/delfick/harpoon/blob/a2d39311d6127b7da2e15f40468bf320d598e461/harpoon/ship/runner.py#L578-L594 | def intervention(self, commit, conf):
"""Ask the user if they want to commit this container and run sh in it"""
if not conf.harpoon.interactive or conf.harpoon.no_intervention:
yield
return
hp.write_to(conf.harpoon.stdout, "!!!!\n")
hp.write_to(conf.harpoon.stdou... | [
"def",
"intervention",
"(",
"self",
",",
"commit",
",",
"conf",
")",
":",
"if",
"not",
"conf",
".",
"harpoon",
".",
"interactive",
"or",
"conf",
".",
"harpoon",
".",
"no_intervention",
":",
"yield",
"return",
"hp",
".",
"write_to",
"(",
"conf",
".",
"h... | Ask the user if they want to commit this container and run sh in it | [
"Ask",
"the",
"user",
"if",
"they",
"want",
"to",
"commit",
"this",
"container",
"and",
"run",
"sh",
"in",
"it"
] | python | train |
wonambi-python/wonambi | wonambi/widgets/notes.py | https://github.com/wonambi-python/wonambi/blob/1d8e3d7e53df8017c199f703bcab582914676e76/wonambi/widgets/notes.py#L1185-L1290 | def import_staging(self, source, staging_start=None, as_qual=False,
test_filename=None, test_rater=None):
"""Action: import an external sleep staging file.
Parameters
----------
source : str
Name of program where staging was exported. One of 'alice',
... | [
"def",
"import_staging",
"(",
"self",
",",
"source",
",",
"staging_start",
"=",
"None",
",",
"as_qual",
"=",
"False",
",",
"test_filename",
"=",
"None",
",",
"test_rater",
"=",
"None",
")",
":",
"if",
"self",
".",
"annot",
"is",
"None",
":",
"# remove if... | Action: import an external sleep staging file.
Parameters
----------
source : str
Name of program where staging was exported. One of 'alice',
'compumedics', 'domino', 'remlogic', 'sandman'.
staging_start : datetime, optional
Absolute time when staging... | [
"Action",
":",
"import",
"an",
"external",
"sleep",
"staging",
"file",
"."
] | python | train |
data-8/datascience | datascience/maps.py | https://github.com/data-8/datascience/blob/4cee38266903ca169cea4a53b8cc39502d85c464/datascience/maps.py#L335-L352 | def _read_geojson_features(data, features=None, prefix=""):
"""Return a dict of features keyed by ID."""
if features is None:
features = collections.OrderedDict()
for i, feature in enumerate(data['features']):
key = feature.get('id', prefix + str(i))
feature_t... | [
"def",
"_read_geojson_features",
"(",
"data",
",",
"features",
"=",
"None",
",",
"prefix",
"=",
"\"\"",
")",
":",
"if",
"features",
"is",
"None",
":",
"features",
"=",
"collections",
".",
"OrderedDict",
"(",
")",
"for",
"i",
",",
"feature",
"in",
"enumer... | Return a dict of features keyed by ID. | [
"Return",
"a",
"dict",
"of",
"features",
"keyed",
"by",
"ID",
"."
] | python | train |
tnkteja/myhelp | virtualEnvironment/lib/python2.7/site-packages/coverage/files.py | https://github.com/tnkteja/myhelp/blob/fb3a4809d448ad14d5b2e6ddf2e7e89ad52b71cb/virtualEnvironment/lib/python2.7/site-packages/coverage/files.py#L163-L173 | def match(self, fpath):
"""Does `fpath` indicate a file in one of our trees?"""
for d in self.dirs:
if fpath.startswith(d):
if fpath == d:
# This is the same file!
return True
if fpath[len(d)] == os.sep:
... | [
"def",
"match",
"(",
"self",
",",
"fpath",
")",
":",
"for",
"d",
"in",
"self",
".",
"dirs",
":",
"if",
"fpath",
".",
"startswith",
"(",
"d",
")",
":",
"if",
"fpath",
"==",
"d",
":",
"# This is the same file!",
"return",
"True",
"if",
"fpath",
"[",
... | Does `fpath` indicate a file in one of our trees? | [
"Does",
"fpath",
"indicate",
"a",
"file",
"in",
"one",
"of",
"our",
"trees?"
] | python | test |
gruns/icecream | icecream/icecream.py | https://github.com/gruns/icecream/blob/cb4f3d50ec747637721fe58b80f2cc2a2baedabf/icecream/icecream.py#L369-L384 | def splitExpressionsOntoSeparateLines(source):
"""
Split every expression onto its own line so any preceding and/or trailing
expressions, like 'foo(1); ' and '; foo(2)' of
foo(1); ic(1); foo(2)
are properly separated from ic(1) for dis.findlinestarts(). Otherwise, any
preceding and/or traili... | [
"def",
"splitExpressionsOntoSeparateLines",
"(",
"source",
")",
":",
"indices",
"=",
"[",
"expr",
".",
"col_offset",
"for",
"expr",
"in",
"ast",
".",
"parse",
"(",
"source",
")",
".",
"body",
"]",
"lines",
"=",
"[",
"s",
".",
"strip",
"(",
")",
"for",
... | Split every expression onto its own line so any preceding and/or trailing
expressions, like 'foo(1); ' and '; foo(2)' of
foo(1); ic(1); foo(2)
are properly separated from ic(1) for dis.findlinestarts(). Otherwise, any
preceding and/or trailing expressions break ic(1)'s bytecode offset
calculatio... | [
"Split",
"every",
"expression",
"onto",
"its",
"own",
"line",
"so",
"any",
"preceding",
"and",
"/",
"or",
"trailing",
"expressions",
"like",
"foo",
"(",
"1",
")",
";",
"and",
";",
"foo",
"(",
"2",
")",
"of"
] | python | train |
HttpRunner/HttpRunner | httprunner/parser.py | https://github.com/HttpRunner/HttpRunner/blob/f259551bf9c8ba905eae5c1afcf2efea20ae0871/httprunner/parser.py#L556-L610 | def prepare_lazy_data(content, functions_mapping=None, check_variables_set=None, cached=False):
""" make string in content as lazy object with functions_mapping
Raises:
exceptions.VariableNotFound: if any variable undefined in check_variables_set
"""
# TODO: refactor type check
if content ... | [
"def",
"prepare_lazy_data",
"(",
"content",
",",
"functions_mapping",
"=",
"None",
",",
"check_variables_set",
"=",
"None",
",",
"cached",
"=",
"False",
")",
":",
"# TODO: refactor type check",
"if",
"content",
"is",
"None",
"or",
"isinstance",
"(",
"content",
"... | make string in content as lazy object with functions_mapping
Raises:
exceptions.VariableNotFound: if any variable undefined in check_variables_set | [
"make",
"string",
"in",
"content",
"as",
"lazy",
"object",
"with",
"functions_mapping"
] | python | train |
aitjcize/cppman | cppman/main.py | https://github.com/aitjcize/cppman/blob/7b48e81b2cd3baa912d73dfe977ecbaff945a93c/cppman/main.py#L160-L193 | def parse_title(self, title):
"""
split of the last parenthesis operator==,!=,<,<=(std::vector)
tested with
```
operator==,!=,<,<=,>,>=(std::vector)
operator==,!=,<,<=,>,>=(std::vector)
operator==,!=,<,<=,>,>=
operator... | [
"def",
"parse_title",
"(",
"self",
",",
"title",
")",
":",
"m",
"=",
"re",
".",
"match",
"(",
"r'^\\s*((?:\\(size_type\\)|(?:.|\\(\\))*?)*)((?:\\([^)]+\\))?)\\s*$'",
",",
"title",
")",
"postfix",
"=",
"m",
".",
"group",
"(",
"2",
")",
"t_names",
"=",
"m",
".... | split of the last parenthesis operator==,!=,<,<=(std::vector)
tested with
```
operator==,!=,<,<=,>,>=(std::vector)
operator==,!=,<,<=,>,>=(std::vector)
operator==,!=,<,<=,>,>=
operator==,!=,<,<=,>,>=
std::rel_ops::operator!=,... | [
"split",
"of",
"the",
"last",
"parenthesis",
"operator",
"==",
"!",
"=",
"<",
"<",
"=",
"(",
"std",
"::",
"vector",
")",
"tested",
"with",
"operator",
"==",
"!",
"=",
"<",
"<",
"=",
">",
">",
"=",
"(",
"std",
"::",
"vector",
")",
"operator",
"=="... | python | train |
todddeluca/dones | dones.py | https://github.com/todddeluca/dones/blob/6ef56565556987e701fed797a405f0825fe2e15a/dones.py#L324-L339 | def doTransaction(conn, start=True, startSQL='START TRANSACTION'):
'''
wrap a connection in a transaction. starts a transaction, yields the conn, and then if an exception occurs, calls rollback(). otherwise calls commit().
start: if True, executes 'START TRANSACTION' sql before yielding conn. Useful for ... | [
"def",
"doTransaction",
"(",
"conn",
",",
"start",
"=",
"True",
",",
"startSQL",
"=",
"'START TRANSACTION'",
")",
":",
"try",
":",
"if",
"start",
":",
"executeSQL",
"(",
"conn",
",",
"startSQL",
")",
"yield",
"conn",
"except",
":",
"if",
"conn",
"is",
... | wrap a connection in a transaction. starts a transaction, yields the conn, and then if an exception occurs, calls rollback(). otherwise calls commit().
start: if True, executes 'START TRANSACTION' sql before yielding conn. Useful for connections that are autocommit by default.
startSQL: override if 'START TR... | [
"wrap",
"a",
"connection",
"in",
"a",
"transaction",
".",
"starts",
"a",
"transaction",
"yields",
"the",
"conn",
"and",
"then",
"if",
"an",
"exception",
"occurs",
"calls",
"rollback",
"()",
".",
"otherwise",
"calls",
"commit",
"()",
".",
"start",
":",
"if"... | python | train |
bitesofcode/projexui | projexui/xsettings.py | https://github.com/bitesofcode/projexui/blob/f18a73bec84df90b034ca69b9deea118dbedfc4d/projexui/xsettings.py#L557-L563 | def load(self):
"""
Loads the settings from disk for this XSettings object, if it is a custom format.
"""
# load the custom format
if self._customFormat and os.path.exists(self.fileName()):
self._customFormat.load(self.fileName()) | [
"def",
"load",
"(",
"self",
")",
":",
"# load the custom format\r",
"if",
"self",
".",
"_customFormat",
"and",
"os",
".",
"path",
".",
"exists",
"(",
"self",
".",
"fileName",
"(",
")",
")",
":",
"self",
".",
"_customFormat",
".",
"load",
"(",
"self",
"... | Loads the settings from disk for this XSettings object, if it is a custom format. | [
"Loads",
"the",
"settings",
"from",
"disk",
"for",
"this",
"XSettings",
"object",
"if",
"it",
"is",
"a",
"custom",
"format",
"."
] | python | train |
Alignak-monitoring/alignak | alignak/external_command.py | https://github.com/Alignak-monitoring/alignak/blob/f3c145207e83159b799d3714e4241399c7740a64/alignak/external_command.py#L3395-L3410 | def schedule_and_propagate_host_downtime(self, host, start_time, end_time,
fixed, trigger_id, duration, author, comment):
"""DOES NOTHING (Should create host downtime and start it?)
Format of the line that triggers function call::
SCHEDULE_AND_PROPAG... | [
"def",
"schedule_and_propagate_host_downtime",
"(",
"self",
",",
"host",
",",
"start_time",
",",
"end_time",
",",
"fixed",
",",
"trigger_id",
",",
"duration",
",",
"author",
",",
"comment",
")",
":",
"logger",
".",
"warning",
"(",
"\"The external command 'SCHEDULE... | DOES NOTHING (Should create host downtime and start it?)
Format of the line that triggers function call::
SCHEDULE_AND_PROPAGATE_HOST_DOWNTIME;<host_name>;<start_time>;<end_time>;
<fixed>;<trigger_id>;<duration>;<author>;<comment>
:return: None | [
"DOES",
"NOTHING",
"(",
"Should",
"create",
"host",
"downtime",
"and",
"start",
"it?",
")",
"Format",
"of",
"the",
"line",
"that",
"triggers",
"function",
"call",
"::"
] | python | train |
python-openxml/python-docx | docx/oxml/xmlchemy.py | https://github.com/python-openxml/python-docx/blob/6756f6cd145511d3eb6d1d188beea391b1ddfd53/docx/oxml/xmlchemy.py#L469-L477 | def _prop_name(self):
"""
Calculate property name from tag name, e.g. a:schemeClr -> schemeClr.
"""
if ':' in self._nsptagname:
start = self._nsptagname.index(':') + 1
else:
start = 0
return self._nsptagname[start:] | [
"def",
"_prop_name",
"(",
"self",
")",
":",
"if",
"':'",
"in",
"self",
".",
"_nsptagname",
":",
"start",
"=",
"self",
".",
"_nsptagname",
".",
"index",
"(",
"':'",
")",
"+",
"1",
"else",
":",
"start",
"=",
"0",
"return",
"self",
".",
"_nsptagname",
... | Calculate property name from tag name, e.g. a:schemeClr -> schemeClr. | [
"Calculate",
"property",
"name",
"from",
"tag",
"name",
"e",
".",
"g",
".",
"a",
":",
"schemeClr",
"-",
">",
"schemeClr",
"."
] | python | train |
limpyd/redis-limpyd | limpyd/fields.py | https://github.com/limpyd/redis-limpyd/blob/3c745dde1390a0bd09690b77a089dcc08c6c7e43/limpyd/fields.py#L735-L744 | def _pop(self, command, *args, **kwargs):
"""
Shortcut for commands that pop a value from the field, returning it while
removing it.
The returned value will be deindexed
"""
result = self._traverse_command(command, *args, **kwargs)
if self.indexable:
s... | [
"def",
"_pop",
"(",
"self",
",",
"command",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"result",
"=",
"self",
".",
"_traverse_command",
"(",
"command",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
"if",
"self",
".",
"indexable",
":",
... | Shortcut for commands that pop a value from the field, returning it while
removing it.
The returned value will be deindexed | [
"Shortcut",
"for",
"commands",
"that",
"pop",
"a",
"value",
"from",
"the",
"field",
"returning",
"it",
"while",
"removing",
"it",
".",
"The",
"returned",
"value",
"will",
"be",
"deindexed"
] | python | train |
keybase/python-triplesec | triplesec/__init__.py | https://github.com/keybase/python-triplesec/blob/0a73e18cfe542d0cd5ee57bd823a67412b4b717e/triplesec/__init__.py#L91-L110 | def encrypt_ascii(self, data, key=None, v=None, extra_bytes=0,
digest="hex"):
"""
Encrypt data and return as ascii string. Hexadecimal digest as default.
Avaiable digests:
hex: Hexadecimal
base64: Base 64
hqx: hexbin4
"""
... | [
"def",
"encrypt_ascii",
"(",
"self",
",",
"data",
",",
"key",
"=",
"None",
",",
"v",
"=",
"None",
",",
"extra_bytes",
"=",
"0",
",",
"digest",
"=",
"\"hex\"",
")",
":",
"digests",
"=",
"{",
"\"hex\"",
":",
"binascii",
".",
"b2a_hex",
",",
"\"base64\"... | Encrypt data and return as ascii string. Hexadecimal digest as default.
Avaiable digests:
hex: Hexadecimal
base64: Base 64
hqx: hexbin4 | [
"Encrypt",
"data",
"and",
"return",
"as",
"ascii",
"string",
".",
"Hexadecimal",
"digest",
"as",
"default",
"."
] | python | train |
instaloader/instaloader | instaloader/structures.py | https://github.com/instaloader/instaloader/blob/87d877e650cd8020b04b8b51be120599a441fd5b/instaloader/structures.py#L228-L233 | def caption(self) -> Optional[str]:
"""Caption."""
if "edge_media_to_caption" in self._node and self._node["edge_media_to_caption"]["edges"]:
return self._node["edge_media_to_caption"]["edges"][0]["node"]["text"]
elif "caption" in self._node:
return self._node["caption"] | [
"def",
"caption",
"(",
"self",
")",
"->",
"Optional",
"[",
"str",
"]",
":",
"if",
"\"edge_media_to_caption\"",
"in",
"self",
".",
"_node",
"and",
"self",
".",
"_node",
"[",
"\"edge_media_to_caption\"",
"]",
"[",
"\"edges\"",
"]",
":",
"return",
"self",
"."... | Caption. | [
"Caption",
"."
] | python | train |
tobgu/pyrsistent | pyrsistent/_plist.py | https://github.com/tobgu/pyrsistent/blob/c84dab0daaa44973cbe83830d14888827b307632/pyrsistent/_plist.py#L199-L219 | def remove(self, elem):
"""
Return new list with first element equal to elem removed. O(k) where k is the position
of the element that is removed.
Raises ValueError if no matching element is found.
>>> plist([1, 2, 1]).remove(1)
plist([2, 1])
"""
builde... | [
"def",
"remove",
"(",
"self",
",",
"elem",
")",
":",
"builder",
"=",
"_PListBuilder",
"(",
")",
"head",
"=",
"self",
"while",
"head",
":",
"if",
"head",
".",
"first",
"==",
"elem",
":",
"return",
"builder",
".",
"append_plist",
"(",
"head",
".",
"res... | Return new list with first element equal to elem removed. O(k) where k is the position
of the element that is removed.
Raises ValueError if no matching element is found.
>>> plist([1, 2, 1]).remove(1)
plist([2, 1]) | [
"Return",
"new",
"list",
"with",
"first",
"element",
"equal",
"to",
"elem",
"removed",
".",
"O",
"(",
"k",
")",
"where",
"k",
"is",
"the",
"position",
"of",
"the",
"element",
"that",
"is",
"removed",
"."
] | python | train |
cloud9ers/gurumate | environment/lib/python2.7/site-packages/IPython/zmq/zmqshell.py | https://github.com/cloud9ers/gurumate/blob/075dc74d1ee62a8c6b7a8bf2b271364f01629d1e/environment/lib/python2.7/site-packages/IPython/zmq/zmqshell.py#L511-L522 | def auto_rewrite_input(self, cmd):
"""Called to show the auto-rewritten input for autocall and friends.
FIXME: this payload is currently not correctly processed by the
frontend.
"""
new = self.prompt_manager.render('rewrite') + cmd
payload = dict(
source='IPy... | [
"def",
"auto_rewrite_input",
"(",
"self",
",",
"cmd",
")",
":",
"new",
"=",
"self",
".",
"prompt_manager",
".",
"render",
"(",
"'rewrite'",
")",
"+",
"cmd",
"payload",
"=",
"dict",
"(",
"source",
"=",
"'IPython.zmq.zmqshell.ZMQInteractiveShell.auto_rewrite_input'"... | Called to show the auto-rewritten input for autocall and friends.
FIXME: this payload is currently not correctly processed by the
frontend. | [
"Called",
"to",
"show",
"the",
"auto",
"-",
"rewritten",
"input",
"for",
"autocall",
"and",
"friends",
"."
] | python | test |
nerdvegas/rez | src/rez/resolved_context.py | https://github.com/nerdvegas/rez/blob/1d3b846d53b5b5404edfe8ddb9083f9ceec8c5e7/src/rez/resolved_context.py#L545-L555 | def get_current(cls):
"""Get the context for the current env, if there is one.
Returns:
`ResolvedContext`: Current context, or None if not in a resolved env.
"""
filepath = os.getenv("REZ_RXT_FILE")
if not filepath or not os.path.exists(filepath):
return ... | [
"def",
"get_current",
"(",
"cls",
")",
":",
"filepath",
"=",
"os",
".",
"getenv",
"(",
"\"REZ_RXT_FILE\"",
")",
"if",
"not",
"filepath",
"or",
"not",
"os",
".",
"path",
".",
"exists",
"(",
"filepath",
")",
":",
"return",
"None",
"return",
"cls",
".",
... | Get the context for the current env, if there is one.
Returns:
`ResolvedContext`: Current context, or None if not in a resolved env. | [
"Get",
"the",
"context",
"for",
"the",
"current",
"env",
"if",
"there",
"is",
"one",
"."
] | python | train |
brandon-rhodes/logging_tree | logging_tree/format.py | https://github.com/brandon-rhodes/logging_tree/blob/8513cf85b3bf8ff1b58e54c73718a41ef6524a4c/logging_tree/format.py#L144-L170 | def describe_handler(h):
"""Yield one or more lines describing the logging handler `h`."""
t = h.__class__ # using type() breaks in Python <= 2.6
format = handler_formats.get(t)
if format is not None:
yield format % h.__dict__
else:
yield repr(h)
level = getattr(h, 'level', logg... | [
"def",
"describe_handler",
"(",
"h",
")",
":",
"t",
"=",
"h",
".",
"__class__",
"# using type() breaks in Python <= 2.6",
"format",
"=",
"handler_formats",
".",
"get",
"(",
"t",
")",
"if",
"format",
"is",
"not",
"None",
":",
"yield",
"format",
"%",
"h",
".... | Yield one or more lines describing the logging handler `h`. | [
"Yield",
"one",
"or",
"more",
"lines",
"describing",
"the",
"logging",
"handler",
"h",
"."
] | python | train |
blha303/DO-runin | runin/runin.py | https://github.com/blha303/DO-runin/blob/4e725165e79f8bc0a2e1cb07a83f414686570e90/runin/runin.py#L13-L29 | def match_keys(inp, p=False):
"""Takes a comma-separated string of key ids or fingerprints and returns a list of key ids"""
_keys = []
ssh_keys = DO.get_ssh_keys()
for k in inp.split(","):
done = False
if k.isdigit():
for _ in [s for s in ssh_keys if s["id"] == int(k)]:
... | [
"def",
"match_keys",
"(",
"inp",
",",
"p",
"=",
"False",
")",
":",
"_keys",
"=",
"[",
"]",
"ssh_keys",
"=",
"DO",
".",
"get_ssh_keys",
"(",
")",
"for",
"k",
"in",
"inp",
".",
"split",
"(",
"\",\"",
")",
":",
"done",
"=",
"False",
"if",
"k",
"."... | Takes a comma-separated string of key ids or fingerprints and returns a list of key ids | [
"Takes",
"a",
"comma",
"-",
"separated",
"string",
"of",
"key",
"ids",
"or",
"fingerprints",
"and",
"returns",
"a",
"list",
"of",
"key",
"ids"
] | python | train |
Datary/scrapbag | scrapbag/csvs.py | https://github.com/Datary/scrapbag/blob/3a4f9824ab6fe21121214ba9963690618da2c9de/scrapbag/csvs.py#L264-L278 | def row_iter_limiter(rows, begin_row, way, c_value):
"""
Alghoritm to detect row limits when row have more that one column.
Depending the init params find from the begin or behind.
NOT SURE THAT IT WORKS WELL..
"""
limit = None
for index in range(begin_row, len(rows)):
if not len(ex... | [
"def",
"row_iter_limiter",
"(",
"rows",
",",
"begin_row",
",",
"way",
",",
"c_value",
")",
":",
"limit",
"=",
"None",
"for",
"index",
"in",
"range",
"(",
"begin_row",
",",
"len",
"(",
"rows",
")",
")",
":",
"if",
"not",
"len",
"(",
"exclude_empty_value... | Alghoritm to detect row limits when row have more that one column.
Depending the init params find from the begin or behind.
NOT SURE THAT IT WORKS WELL.. | [
"Alghoritm",
"to",
"detect",
"row",
"limits",
"when",
"row",
"have",
"more",
"that",
"one",
"column",
".",
"Depending",
"the",
"init",
"params",
"find",
"from",
"the",
"begin",
"or",
"behind",
".",
"NOT",
"SURE",
"THAT",
"IT",
"WORKS",
"WELL",
".."
] | python | train |
saltstack/salt | salt/pillar/__init__.py | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/pillar/__init__.py#L333-L374 | def compile_pillar(self, *args, **kwargs): # Will likely just be pillar_dirs
'''
Compile pillar and set it to the cache, if not found.
:param args:
:param kwargs:
:return:
'''
log.debug('Scanning pillar cache for information about minion %s and pillarenv %s', se... | [
"def",
"compile_pillar",
"(",
"self",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"# Will likely just be pillar_dirs",
"log",
".",
"debug",
"(",
"'Scanning pillar cache for information about minion %s and pillarenv %s'",
",",
"self",
".",
"minion_id",
",",
"s... | Compile pillar and set it to the cache, if not found.
:param args:
:param kwargs:
:return: | [
"Compile",
"pillar",
"and",
"set",
"it",
"to",
"the",
"cache",
"if",
"not",
"found",
"."
] | python | train |
LeastAuthority/txkube | src/txkube/_exception.py | https://github.com/LeastAuthority/txkube/blob/a7e555d00535ff787d4b1204c264780da40cf736/src/txkube/_exception.py#L11-L21 | def _full_kind(details):
"""
Determine the full kind (including a group if applicable) for some failure
details.
:see: ``v1.Status.details``
"""
kind = details[u"kind"]
if details.get(u"group") is not None:
kind += u"." + details[u"group"]
return kind | [
"def",
"_full_kind",
"(",
"details",
")",
":",
"kind",
"=",
"details",
"[",
"u\"kind\"",
"]",
"if",
"details",
".",
"get",
"(",
"u\"group\"",
")",
"is",
"not",
"None",
":",
"kind",
"+=",
"u\".\"",
"+",
"details",
"[",
"u\"group\"",
"]",
"return",
"kind... | Determine the full kind (including a group if applicable) for some failure
details.
:see: ``v1.Status.details`` | [
"Determine",
"the",
"full",
"kind",
"(",
"including",
"a",
"group",
"if",
"applicable",
")",
"for",
"some",
"failure",
"details",
"."
] | python | train |
Grunny/zap-cli | zapcli/commands/policies.py | https://github.com/Grunny/zap-cli/blob/d58d4850ecfc5467badfac5e5bcc841d064bd419/zapcli/commands/policies.py#L96-L99 | def _get_all_policy_ids(zap_helper):
"""Get all policy IDs."""
policies = zap_helper.zap.ascan.policies()
return [p['id'] for p in policies] | [
"def",
"_get_all_policy_ids",
"(",
"zap_helper",
")",
":",
"policies",
"=",
"zap_helper",
".",
"zap",
".",
"ascan",
".",
"policies",
"(",
")",
"return",
"[",
"p",
"[",
"'id'",
"]",
"for",
"p",
"in",
"policies",
"]"
] | Get all policy IDs. | [
"Get",
"all",
"policy",
"IDs",
"."
] | python | train |
poppy-project/pypot | pypot/vrep/remoteApiBindings/vrep.py | https://github.com/poppy-project/pypot/blob/d9c6551bbc87d45d9d1f0bc15e35b616d0002afd/pypot/vrep/remoteApiBindings/vrep.py#L395-L402 | def simxLoadScene(clientID, scenePathAndName, options, operationMode):
'''
Please have a look at the function description/documentation in the V-REP user manual
'''
if (sys.version_info[0] == 3) and (type(scenePathAndName) is str):
scenePathAndName=scenePathAndName.encode('utf-8')
return c_... | [
"def",
"simxLoadScene",
"(",
"clientID",
",",
"scenePathAndName",
",",
"options",
",",
"operationMode",
")",
":",
"if",
"(",
"sys",
".",
"version_info",
"[",
"0",
"]",
"==",
"3",
")",
"and",
"(",
"type",
"(",
"scenePathAndName",
")",
"is",
"str",
")",
... | Please have a look at the function description/documentation in the V-REP user manual | [
"Please",
"have",
"a",
"look",
"at",
"the",
"function",
"description",
"/",
"documentation",
"in",
"the",
"V",
"-",
"REP",
"user",
"manual"
] | python | train |
chrisrink10/basilisp | src/basilisp/lang/compiler/generator.py | https://github.com/chrisrink10/basilisp/blob/3d82670ee218ec64eb066289c82766d14d18cc92/src/basilisp/lang/compiler/generator.py#L748-L808 | def _deftype_to_py_ast( # pylint: disable=too-many-branches
ctx: GeneratorContext, node: DefType
) -> GeneratedPyAST:
"""Return a Python AST Node for a `deftype*` expression."""
assert node.op == NodeOp.DEFTYPE
type_name = munge(node.name)
ctx.symbol_table.new_symbol(sym.symbol(node.name), type_nam... | [
"def",
"_deftype_to_py_ast",
"(",
"# pylint: disable=too-many-branches",
"ctx",
":",
"GeneratorContext",
",",
"node",
":",
"DefType",
")",
"->",
"GeneratedPyAST",
":",
"assert",
"node",
".",
"op",
"==",
"NodeOp",
".",
"DEFTYPE",
"type_name",
"=",
"munge",
"(",
"... | Return a Python AST Node for a `deftype*` expression. | [
"Return",
"a",
"Python",
"AST",
"Node",
"for",
"a",
"deftype",
"*",
"expression",
"."
] | python | test |
rochacbruno/flasgger | examples/restful.py | https://github.com/rochacbruno/flasgger/blob/fef154f61d7afca548067be0c758c3dd71cc4c97/examples/restful.py#L84-L109 | def put(self, todo_id):
"""
This is an example
---
tags:
- restful
parameters:
- in: body
name: body
schema:
$ref: '#/definitions/Task'
- in: path
name: todo_id
required: true
... | [
"def",
"put",
"(",
"self",
",",
"todo_id",
")",
":",
"args",
"=",
"parser",
".",
"parse_args",
"(",
")",
"task",
"=",
"{",
"'task'",
":",
"args",
"[",
"'task'",
"]",
"}",
"TODOS",
"[",
"todo_id",
"]",
"=",
"task",
"return",
"task",
",",
"201"
] | This is an example
---
tags:
- restful
parameters:
- in: body
name: body
schema:
$ref: '#/definitions/Task'
- in: path
name: todo_id
required: true
description: The ID of the task, try 42!
... | [
"This",
"is",
"an",
"example",
"---",
"tags",
":",
"-",
"restful",
"parameters",
":",
"-",
"in",
":",
"body",
"name",
":",
"body",
"schema",
":",
"$ref",
":",
"#",
"/",
"definitions",
"/",
"Task",
"-",
"in",
":",
"path",
"name",
":",
"todo_id",
"re... | python | train |
BerkeleyAutomation/perception | perception/ensenso_sensor.py | https://github.com/BerkeleyAutomation/perception/blob/03d9b37dd6b66896cdfe173905c9413c8c3c5df6/perception/ensenso_sensor.py#L124-L135 | def stop(self):
""" Stop the sensor """
# check that everything is running
if not self._running:
logging.warning('Ensenso not running. Aborting stop')
return False
# stop subs
self._pointcloud_sub.unregister()
self._camera_info_sub.unregister()
... | [
"def",
"stop",
"(",
"self",
")",
":",
"# check that everything is running",
"if",
"not",
"self",
".",
"_running",
":",
"logging",
".",
"warning",
"(",
"'Ensenso not running. Aborting stop'",
")",
"return",
"False",
"# stop subs",
"self",
".",
"_pointcloud_sub",
".",... | Stop the sensor | [
"Stop",
"the",
"sensor"
] | python | train |
DistrictDataLabs/yellowbrick | yellowbrick/features/manifold.py | https://github.com/DistrictDataLabs/yellowbrick/blob/59b67236a3862c73363e8edad7cd86da5b69e3b2/yellowbrick/features/manifold.py#L232-L260 | def manifold(self, transformer):
"""
Creates the manifold estimator if a string value is passed in,
validates other objects passed in.
"""
if not is_estimator(transformer):
if transformer not in self.ALGORITHMS:
raise YellowbrickValueError(
... | [
"def",
"manifold",
"(",
"self",
",",
"transformer",
")",
":",
"if",
"not",
"is_estimator",
"(",
"transformer",
")",
":",
"if",
"transformer",
"not",
"in",
"self",
".",
"ALGORITHMS",
":",
"raise",
"YellowbrickValueError",
"(",
"\"could not create manifold for '%s'\... | Creates the manifold estimator if a string value is passed in,
validates other objects passed in. | [
"Creates",
"the",
"manifold",
"estimator",
"if",
"a",
"string",
"value",
"is",
"passed",
"in",
"validates",
"other",
"objects",
"passed",
"in",
"."
] | python | train |
dade-ai/snipy | snipy/img/imageutil.py | https://github.com/dade-ai/snipy/blob/408520867179f99b3158b57520e2619f3fecd69b/snipy/img/imageutil.py#L151-L163 | def snoise2dvec(size, *params, **kwargs): #, vlacunarity):
"""
vector parameters
:param size:
:param vz:
:param vscale:
:param voctave:
:param vpersistence:
:param vlacunarity:
:return:
"""
data = (snoise2d(size, *p, **kwargs) for p in zip(*params)) # , vlacunarity))
re... | [
"def",
"snoise2dvec",
"(",
"size",
",",
"*",
"params",
",",
"*",
"*",
"kwargs",
")",
":",
"#, vlacunarity):",
"data",
"=",
"(",
"snoise2d",
"(",
"size",
",",
"*",
"p",
",",
"*",
"*",
"kwargs",
")",
"for",
"p",
"in",
"zip",
"(",
"*",
"params",
")"... | vector parameters
:param size:
:param vz:
:param vscale:
:param voctave:
:param vpersistence:
:param vlacunarity:
:return: | [
"vector",
"parameters",
":",
"param",
"size",
":",
":",
"param",
"vz",
":",
":",
"param",
"vscale",
":",
":",
"param",
"voctave",
":",
":",
"param",
"vpersistence",
":",
":",
"param",
"vlacunarity",
":",
":",
"return",
":"
] | python | valid |
mdsol/rwslib | rwslib/builders/metadata.py | https://github.com/mdsol/rwslib/blob/1a86bc072d408c009ed1de8bf6e98a1769f54d18/rwslib/builders/metadata.py#L1462-L1475 | def build(self, builder):
"""Build XML by appending to builder"""
params = dict(OID=self.oid, Name=self.name, DataType=self.datatype.value)
if self.sas_format_name is not None:
params["SASFormatName"] = self.sas_format_name
builder.start("CodeList", params)
for item ... | [
"def",
"build",
"(",
"self",
",",
"builder",
")",
":",
"params",
"=",
"dict",
"(",
"OID",
"=",
"self",
".",
"oid",
",",
"Name",
"=",
"self",
".",
"name",
",",
"DataType",
"=",
"self",
".",
"datatype",
".",
"value",
")",
"if",
"self",
".",
"sas_fo... | Build XML by appending to builder | [
"Build",
"XML",
"by",
"appending",
"to",
"builder"
] | python | train |
saltstack/salt | salt/pillar/s3.py | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/pillar/s3.py#L352-L362 | def _read_buckets_cache_file(cache_file):
'''
Return the contents of the buckets cache file
'''
log.debug('Reading buckets cache file')
with salt.utils.files.fopen(cache_file, 'rb') as fp_:
data = pickle.load(fp_)
return data | [
"def",
"_read_buckets_cache_file",
"(",
"cache_file",
")",
":",
"log",
".",
"debug",
"(",
"'Reading buckets cache file'",
")",
"with",
"salt",
".",
"utils",
".",
"files",
".",
"fopen",
"(",
"cache_file",
",",
"'rb'",
")",
"as",
"fp_",
":",
"data",
"=",
"pi... | Return the contents of the buckets cache file | [
"Return",
"the",
"contents",
"of",
"the",
"buckets",
"cache",
"file"
] | python | train |
django-danceschool/django-danceschool | danceschool/core/models.py | https://github.com/django-danceschool/django-danceschool/blob/bb08cbf39017a812a5a94bdb4ea34170bf1a30ba/danceschool/core/models.py#L2340-L2359 | def warningFlag(self):
'''
When viewing individual event registrations, there are a large number of potential
issues that can arise that may warrant scrutiny. This property just checks all of
these conditions and indicates if anything is amiss so that the template need not
check ... | [
"def",
"warningFlag",
"(",
"self",
")",
":",
"if",
"not",
"hasattr",
"(",
"self",
",",
"'invoiceitem'",
")",
":",
"return",
"True",
"if",
"apps",
".",
"is_installed",
"(",
"'danceschool.financial'",
")",
":",
"'''\n If the financial app is installed, then... | When viewing individual event registrations, there are a large number of potential
issues that can arise that may warrant scrutiny. This property just checks all of
these conditions and indicates if anything is amiss so that the template need not
check each of these conditions individually repea... | [
"When",
"viewing",
"individual",
"event",
"registrations",
"there",
"are",
"a",
"large",
"number",
"of",
"potential",
"issues",
"that",
"can",
"arise",
"that",
"may",
"warrant",
"scrutiny",
".",
"This",
"property",
"just",
"checks",
"all",
"of",
"these",
"cond... | python | train |
metakirby5/colorz | colorz.py | https://github.com/metakirby5/colorz/blob/11fd47a28d7a4af5b91d29978524335c8fef8cc9/colorz.py#L56-L61 | def get_colors(img):
"""
Returns a list of all the image's colors.
"""
w, h = img.size
return [color[:3] for count, color in img.convert('RGB').getcolors(w * h)] | [
"def",
"get_colors",
"(",
"img",
")",
":",
"w",
",",
"h",
"=",
"img",
".",
"size",
"return",
"[",
"color",
"[",
":",
"3",
"]",
"for",
"count",
",",
"color",
"in",
"img",
".",
"convert",
"(",
"'RGB'",
")",
".",
"getcolors",
"(",
"w",
"*",
"h",
... | Returns a list of all the image's colors. | [
"Returns",
"a",
"list",
"of",
"all",
"the",
"image",
"s",
"colors",
"."
] | python | train |
karjaljo/hiisi | hiisi/hiisi.py | https://github.com/karjaljo/hiisi/blob/de6a64df5dcbcb37d5d3d5468663e65a7794f9a8/hiisi/hiisi.py#L135-L181 | def create_from_filedict(self, filedict):
"""
Creates h5 file from dictionary containing the file structure.
Filedict is a regular dictinary whose keys are hdf5 paths and whose
values are dictinaries containing the metadata and datasets. Metadata
is given as normal key-v... | [
"def",
"create_from_filedict",
"(",
"self",
",",
"filedict",
")",
":",
"if",
"self",
".",
"mode",
"in",
"[",
"'r+'",
",",
"'w'",
",",
"'w-'",
",",
"'x'",
",",
"'a'",
"]",
":",
"for",
"h5path",
",",
"path_content",
"in",
"filedict",
".",
"iteritems",
... | Creates h5 file from dictionary containing the file structure.
Filedict is a regular dictinary whose keys are hdf5 paths and whose
values are dictinaries containing the metadata and datasets. Metadata
is given as normal key-value -pairs and dataset arrays are given using
'DATASE... | [
"Creates",
"h5",
"file",
"from",
"dictionary",
"containing",
"the",
"file",
"structure",
".",
"Filedict",
"is",
"a",
"regular",
"dictinary",
"whose",
"keys",
"are",
"hdf5",
"paths",
"and",
"whose",
"values",
"are",
"dictinaries",
"containing",
"the",
"metadata",... | python | train |
timothydmorton/isochrones | isochrones/yapsi/grid.py | https://github.com/timothydmorton/isochrones/blob/d84495573044c66db2fd6b959fe69e370757ea14/isochrones/yapsi/grid.py#L45-L54 | def get_feh(cls, filename):
"""
example filename: yapsi_w_X0p602357_Z0p027643.dat
"""
X,Y,Z = cls._get_XYZ(filename)
Xsun = 0.703812
Zsun = 0.016188
return np.log10((Z/X) / (Zsun/Xsun)) | [
"def",
"get_feh",
"(",
"cls",
",",
"filename",
")",
":",
"X",
",",
"Y",
",",
"Z",
"=",
"cls",
".",
"_get_XYZ",
"(",
"filename",
")",
"Xsun",
"=",
"0.703812",
"Zsun",
"=",
"0.016188",
"return",
"np",
".",
"log10",
"(",
"(",
"Z",
"/",
"X",
")",
"... | example filename: yapsi_w_X0p602357_Z0p027643.dat | [
"example",
"filename",
":",
"yapsi_w_X0p602357_Z0p027643",
".",
"dat"
] | python | train |
pyupio/pyup | pyup/providers/gitlab.py | https://github.com/pyupio/pyup/blob/b20fa88e03cfdf5dc409a9f00d27629188171c31/pyup/providers/gitlab.py#L131-L140 | def delete_branch(self, repo, branch, prefix):
"""
Deletes a branch.
:param repo: github.Repository
:param branch: string name of the branch to delete
"""
# make sure that the name of the branch begins with pyup.
assert branch.startswith(prefix)
obj = repo... | [
"def",
"delete_branch",
"(",
"self",
",",
"repo",
",",
"branch",
",",
"prefix",
")",
":",
"# make sure that the name of the branch begins with pyup.",
"assert",
"branch",
".",
"startswith",
"(",
"prefix",
")",
"obj",
"=",
"repo",
".",
"branches",
".",
"get",
"("... | Deletes a branch.
:param repo: github.Repository
:param branch: string name of the branch to delete | [
"Deletes",
"a",
"branch",
".",
":",
"param",
"repo",
":",
"github",
".",
"Repository",
":",
"param",
"branch",
":",
"string",
"name",
"of",
"the",
"branch",
"to",
"delete"
] | python | train |
datastax/python-driver | cassandra/cqlengine/connection.py | https://github.com/datastax/python-driver/blob/30a80d0b798b1f45f8cb77163b1fa791f3e3ca29/cassandra/cqlengine/connection.py#L266-L296 | def set_session(s):
"""
Configures the default connection with a preexisting :class:`cassandra.cluster.Session`
Note: the mapper presently requires a Session :attr:`~.row_factory` set to ``dict_factory``.
This may be relaxed in the future
"""
try:
conn = get_connection()
except CQL... | [
"def",
"set_session",
"(",
"s",
")",
":",
"try",
":",
"conn",
"=",
"get_connection",
"(",
")",
"except",
"CQLEngineException",
":",
"# no default connection set; initalize one",
"register_connection",
"(",
"'default'",
",",
"session",
"=",
"s",
",",
"default",
"="... | Configures the default connection with a preexisting :class:`cassandra.cluster.Session`
Note: the mapper presently requires a Session :attr:`~.row_factory` set to ``dict_factory``.
This may be relaxed in the future | [
"Configures",
"the",
"default",
"connection",
"with",
"a",
"preexisting",
":",
"class",
":",
"cassandra",
".",
"cluster",
".",
"Session"
] | python | train |
Holzhaus/python-cmuclmtk | cmuclmtk/__init__.py | https://github.com/Holzhaus/python-cmuclmtk/blob/67a5c6713c497ca644ea1c697a70e8d930c9d4b4/cmuclmtk/__init__.py#L477-L490 | def text2vocab(text, output_file, text2wfreq_kwargs={}, wfreq2vocab_kwargs={}):
"""
Convienience function that uses text2wfreq and wfreq2vocab to create a vocabulary file from text.
"""
with tempfile.NamedTemporaryFile(suffix='.wfreq', delete=False) as f:
wfreq_file = f.name
try:
... | [
"def",
"text2vocab",
"(",
"text",
",",
"output_file",
",",
"text2wfreq_kwargs",
"=",
"{",
"}",
",",
"wfreq2vocab_kwargs",
"=",
"{",
"}",
")",
":",
"with",
"tempfile",
".",
"NamedTemporaryFile",
"(",
"suffix",
"=",
"'.wfreq'",
",",
"delete",
"=",
"False",
"... | Convienience function that uses text2wfreq and wfreq2vocab to create a vocabulary file from text. | [
"Convienience",
"function",
"that",
"uses",
"text2wfreq",
"and",
"wfreq2vocab",
"to",
"create",
"a",
"vocabulary",
"file",
"from",
"text",
"."
] | python | train |
wandb/client | wandb/history.py | https://github.com/wandb/client/blob/7d08954ed5674fee223cd85ed0d8518fe47266b2/wandb/history.py#L84-L94 | def stream(self, name):
"""Stream can be used to record different time series:
run.history.stream("batch").add({"gradients": 1})
"""
if self.stream_name != "default":
raise ValueError("Nested streams aren't supported")
if self._streams.get(name) == None:
... | [
"def",
"stream",
"(",
"self",
",",
"name",
")",
":",
"if",
"self",
".",
"stream_name",
"!=",
"\"default\"",
":",
"raise",
"ValueError",
"(",
"\"Nested streams aren't supported\"",
")",
"if",
"self",
".",
"_streams",
".",
"get",
"(",
"name",
")",
"==",
"Non... | Stream can be used to record different time series:
run.history.stream("batch").add({"gradients": 1}) | [
"Stream",
"can",
"be",
"used",
"to",
"record",
"different",
"time",
"series",
":"
] | python | train |
uber/doubles | doubles/method_double.py | https://github.com/uber/doubles/blob/15e68dcf98f709b19a581915fa6af5ef49ebdd8a/doubles/method_double.py#L133-L144 | def _verify_method(self):
"""Verify that a method may be doubled.
Verifies that the target object has a method matching the name the user is attempting to
double.
:raise: ``VerifyingDoubleError`` if no matching method is found.
"""
class_level = self._target.is_class_o... | [
"def",
"_verify_method",
"(",
"self",
")",
":",
"class_level",
"=",
"self",
".",
"_target",
".",
"is_class_or_module",
"(",
")",
"verify_method",
"(",
"self",
".",
"_target",
",",
"self",
".",
"_method_name",
",",
"class_level",
"=",
"class_level",
")"
] | Verify that a method may be doubled.
Verifies that the target object has a method matching the name the user is attempting to
double.
:raise: ``VerifyingDoubleError`` if no matching method is found. | [
"Verify",
"that",
"a",
"method",
"may",
"be",
"doubled",
"."
] | python | train |
ryanjdillon/pyotelem | pyotelem/physio_seal.py | https://github.com/ryanjdillon/pyotelem/blob/816563a9c3feb3fa416f1c2921c6b75db34111ad/pyotelem/physio_seal.py#L203-L254 | def lip2dens(perc_lipid, dens_lipid=0.9007, dens_prot=1.34, dens_water=0.994,
dens_ash=2.3):
'''Derive tissue density from lipids
The equation calculating animal density is from Biuw et al. (2003), and
default values for component densities are from human studies collected in
the book by Moore ... | [
"def",
"lip2dens",
"(",
"perc_lipid",
",",
"dens_lipid",
"=",
"0.9007",
",",
"dens_prot",
"=",
"1.34",
",",
"dens_water",
"=",
"0.994",
",",
"dens_ash",
"=",
"2.3",
")",
":",
"import",
"numpy",
"# Cast iterables to numpy array",
"if",
"numpy",
".",
"iterable",... | Derive tissue density from lipids
The equation calculating animal density is from Biuw et al. (2003), and
default values for component densities are from human studies collected in
the book by Moore et al. (1963).
Args
----
perc_lipid: float or ndarray
Percent lipid of body composition... | [
"Derive",
"tissue",
"density",
"from",
"lipids"
] | python | train |
taskcluster/taskcluster-client.py | taskcluster/aio/secrets.py | https://github.com/taskcluster/taskcluster-client.py/blob/bcc95217f8bf80bed2ae5885a19fa0035da7ebc9/taskcluster/aio/secrets.py#L56-L65 | async def remove(self, *args, **kwargs):
"""
Delete Secret
Delete the secret associated with some key.
This method is ``stable``
"""
return await self._makeApiCall(self.funcinfo["remove"], *args, **kwargs) | [
"async",
"def",
"remove",
"(",
"self",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"return",
"await",
"self",
".",
"_makeApiCall",
"(",
"self",
".",
"funcinfo",
"[",
"\"remove\"",
"]",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")"
] | Delete Secret
Delete the secret associated with some key.
This method is ``stable`` | [
"Delete",
"Secret"
] | python | train |
scanny/python-pptx | pptx/parts/presentation.py | https://github.com/scanny/python-pptx/blob/d6ab8234f8b03953d2f831ff9394b1852db34130/pptx/parts/presentation.py#L62-L74 | def notes_master_part(self):
"""
Return the |NotesMasterPart| object for this presentation. If the
presentation does not have a notes master, one is created from
a default template. The same single instance is returned on each
call.
"""
try:
return sel... | [
"def",
"notes_master_part",
"(",
"self",
")",
":",
"try",
":",
"return",
"self",
".",
"part_related_by",
"(",
"RT",
".",
"NOTES_MASTER",
")",
"except",
"KeyError",
":",
"notes_master_part",
"=",
"NotesMasterPart",
".",
"create_default",
"(",
"self",
".",
"pack... | Return the |NotesMasterPart| object for this presentation. If the
presentation does not have a notes master, one is created from
a default template. The same single instance is returned on each
call. | [
"Return",
"the",
"|NotesMasterPart|",
"object",
"for",
"this",
"presentation",
".",
"If",
"the",
"presentation",
"does",
"not",
"have",
"a",
"notes",
"master",
"one",
"is",
"created",
"from",
"a",
"default",
"template",
".",
"The",
"same",
"single",
"instance"... | python | train |
Becksteinlab/GromacsWrapper | gromacs/cbook.py | https://github.com/Becksteinlab/GromacsWrapper/blob/d4f9a8cb6f48292732cf7c7e4ef4a6d2ccbc51b9/gromacs/cbook.py#L1575-L1594 | def _translate_residue(self, selection, default_atomname='CA'):
"""Translate selection for a single res to make_ndx syntax."""
m = self.RESIDUE.match(selection)
if not m:
errmsg = "Selection {selection!r} is not valid.".format(**vars())
logger.error(errmsg)
ra... | [
"def",
"_translate_residue",
"(",
"self",
",",
"selection",
",",
"default_atomname",
"=",
"'CA'",
")",
":",
"m",
"=",
"self",
".",
"RESIDUE",
".",
"match",
"(",
"selection",
")",
"if",
"not",
"m",
":",
"errmsg",
"=",
"\"Selection {selection!r} is not valid.\""... | Translate selection for a single res to make_ndx syntax. | [
"Translate",
"selection",
"for",
"a",
"single",
"res",
"to",
"make_ndx",
"syntax",
"."
] | python | valid |
llimllib/limbo | limbo/plugins/gif.py | https://github.com/llimllib/limbo/blob/f0980f20f733b670debcae454b167da32c57a044/limbo/plugins/gif.py#L19-L38 | def gif(search, unsafe=False):
"""given a search string, return a gif URL via google search"""
searchb = quote(search.encode("utf8"))
safe = "&safe=" if unsafe else "&safe=active"
searchurl = "https://www.google.com/search?tbs=itp:animated&tbm=isch&q={0}{1}" \
.format(searchb, safe)
# this... | [
"def",
"gif",
"(",
"search",
",",
"unsafe",
"=",
"False",
")",
":",
"searchb",
"=",
"quote",
"(",
"search",
".",
"encode",
"(",
"\"utf8\"",
")",
")",
"safe",
"=",
"\"&safe=\"",
"if",
"unsafe",
"else",
"\"&safe=active\"",
"searchurl",
"=",
"\"https://www.go... | given a search string, return a gif URL via google search | [
"given",
"a",
"search",
"string",
"return",
"a",
"gif",
"URL",
"via",
"google",
"search"
] | python | train |
mdsol/rwslib | rwslib/builders/modm.py | https://github.com/mdsol/rwslib/blob/1a86bc072d408c009ed1de8bf6e98a1769f54d18/rwslib/builders/modm.py#L122-L131 | def mixin_params(self, params):
"""
Merge in the MdsolAttribute for the passed parameter
:param dict params: dictionary of object parameters
"""
if not isinstance(params, (dict,)):
raise AttributeError("Cannot mixin to object of type {}".format(type(params)))
... | [
"def",
"mixin_params",
"(",
"self",
",",
"params",
")",
":",
"if",
"not",
"isinstance",
"(",
"params",
",",
"(",
"dict",
",",
")",
")",
":",
"raise",
"AttributeError",
"(",
"\"Cannot mixin to object of type {}\"",
".",
"format",
"(",
"type",
"(",
"params",
... | Merge in the MdsolAttribute for the passed parameter
:param dict params: dictionary of object parameters | [
"Merge",
"in",
"the",
"MdsolAttribute",
"for",
"the",
"passed",
"parameter"
] | python | train |
csparpa/pyowm | pyowm/weatherapi25/historian.py | https://github.com/csparpa/pyowm/blob/cdd59eb72f32f7238624ceef9b2e2329a5ebd472/pyowm/weatherapi25/historian.py#L102-L123 | def max_temperature(self, unit='kelvin'):
"""Returns a tuple containing the max value in the temperature
series preceeded by its timestamp
:param unit: the unit of measure for the temperature values. May be
among: '*kelvin*' (default), '*celsius*' or '*fahrenheit*'
... | [
"def",
"max_temperature",
"(",
"self",
",",
"unit",
"=",
"'kelvin'",
")",
":",
"if",
"unit",
"not",
"in",
"(",
"'kelvin'",
",",
"'celsius'",
",",
"'fahrenheit'",
")",
":",
"raise",
"ValueError",
"(",
"\"Invalid value for parameter 'unit'\"",
")",
"maximum",
"=... | Returns a tuple containing the max value in the temperature
series preceeded by its timestamp
:param unit: the unit of measure for the temperature values. May be
among: '*kelvin*' (default), '*celsius*' or '*fahrenheit*'
:type unit: str
:returns: a tuple
:rai... | [
"Returns",
"a",
"tuple",
"containing",
"the",
"max",
"value",
"in",
"the",
"temperature",
"series",
"preceeded",
"by",
"its",
"timestamp",
":",
"param",
"unit",
":",
"the",
"unit",
"of",
"measure",
"for",
"the",
"temperature",
"values",
".",
"May",
"be",
"... | python | train |
F-Secure/see | see/environment.py | https://github.com/F-Secure/see/blob/3e053e52a45229f96a12db9e98caf7fb3880e811/see/environment.py#L102-L108 | def load_configuration(configuration):
"""Returns a dictionary, accepts a dictionary or a path to a JSON file."""
if isinstance(configuration, dict):
return configuration
else:
with open(configuration) as configfile:
return json.load(configfile) | [
"def",
"load_configuration",
"(",
"configuration",
")",
":",
"if",
"isinstance",
"(",
"configuration",
",",
"dict",
")",
":",
"return",
"configuration",
"else",
":",
"with",
"open",
"(",
"configuration",
")",
"as",
"configfile",
":",
"return",
"json",
".",
"... | Returns a dictionary, accepts a dictionary or a path to a JSON file. | [
"Returns",
"a",
"dictionary",
"accepts",
"a",
"dictionary",
"or",
"a",
"path",
"to",
"a",
"JSON",
"file",
"."
] | python | train |
KelSolaar/Umbra | umbra/components/factory/script_editor/nodes.py | https://github.com/KelSolaar/Umbra/blob/66f45f08d9d723787f1191989f8b0dda84b412ce/umbra/components/factory/script_editor/nodes.py#L107-L117 | def editor(self, value):
"""
Setter for **self.__editor** attribute.
:param value: Attribute value.
:type value: Editor
"""
if value is not None:
assert type(value) is Editor, "'{0}' attribute: '{1}' type is not 'Editor'!".format("editor", value)
sel... | [
"def",
"editor",
"(",
"self",
",",
"value",
")",
":",
"if",
"value",
"is",
"not",
"None",
":",
"assert",
"type",
"(",
"value",
")",
"is",
"Editor",
",",
"\"'{0}' attribute: '{1}' type is not 'Editor'!\"",
".",
"format",
"(",
"\"editor\"",
",",
"value",
")",
... | Setter for **self.__editor** attribute.
:param value: Attribute value.
:type value: Editor | [
"Setter",
"for",
"**",
"self",
".",
"__editor",
"**",
"attribute",
"."
] | python | train |
jmgilman/Neolib | neolib/pyamf/codec.py | https://github.com/jmgilman/Neolib/blob/228fafeaed0f3195676137732384a14820ae285c/neolib/pyamf/codec.py#L423-L478 | def getTypeFunc(self, data):
"""
Returns a callable that will encode C{data} to C{self.stream}. If
C{data} is unencodable, then C{None} is returned.
"""
if data is None:
return self.writeNull
t = type(data)
# try types that we know will work
... | [
"def",
"getTypeFunc",
"(",
"self",
",",
"data",
")",
":",
"if",
"data",
"is",
"None",
":",
"return",
"self",
".",
"writeNull",
"t",
"=",
"type",
"(",
"data",
")",
"# try types that we know will work",
"if",
"t",
"is",
"str",
"or",
"issubclass",
"(",
"t",... | Returns a callable that will encode C{data} to C{self.stream}. If
C{data} is unencodable, then C{None} is returned. | [
"Returns",
"a",
"callable",
"that",
"will",
"encode",
"C",
"{",
"data",
"}",
"to",
"C",
"{",
"self",
".",
"stream",
"}",
".",
"If",
"C",
"{",
"data",
"}",
"is",
"unencodable",
"then",
"C",
"{",
"None",
"}",
"is",
"returned",
"."
] | python | train |
markchil/gptools | gptools/utils.py | https://github.com/markchil/gptools/blob/225db52bfe6baef1516529ad22177aa2cf7b71e4/gptools/utils.py#L2032-L2439 | def plot_sampler(
sampler, suptitle=None, labels=None, bins=50,
plot_samples=False, plot_hist=True, plot_chains=True,
burn=0, chain_mask=None, temp_idx=0, weights=None, cutoff_weight=None,
cmap='gray_r', hist_color='k', chain_alpha=0.1,
points=None, covs=None, colors=None, ci=[0.... | [
"def",
"plot_sampler",
"(",
"sampler",
",",
"suptitle",
"=",
"None",
",",
"labels",
"=",
"None",
",",
"bins",
"=",
"50",
",",
"plot_samples",
"=",
"False",
",",
"plot_hist",
"=",
"True",
",",
"plot_chains",
"=",
"True",
",",
"burn",
"=",
"0",
",",
"c... | Plot the results of MCMC sampler (posterior and chains).
Loosely based on triangle.py. Provides extensive options to format the plot.
Parameters
----------
sampler : :py:class:`emcee.Sampler` instance or array, (`n_temps`, `n_chains`, `n_samp`, `n_dim`), (`n_chains`, `n_samp`, `n_dim`) or (`n_... | [
"Plot",
"the",
"results",
"of",
"MCMC",
"sampler",
"(",
"posterior",
"and",
"chains",
")",
".",
"Loosely",
"based",
"on",
"triangle",
".",
"py",
".",
"Provides",
"extensive",
"options",
"to",
"format",
"the",
"plot",
".",
"Parameters",
"----------",
"sampler... | python | train |
rigetti/grove | grove/alpha/arbitrary_state/arbitrary_state.py | https://github.com/rigetti/grove/blob/dc6bf6ec63e8c435fe52b1e00f707d5ce4cdb9b3/grove/alpha/arbitrary_state/arbitrary_state.py#L65-L120 | def get_rotation_parameters(phases, magnitudes):
"""
Simulates one step of rotations.
Given lists of phases and magnitudes of the same length :math:`N`,
such that :math:`N=2^n` for some positive integer :math:`n`,
finds the rotation angles required for one step of phase and magnitude
unificatio... | [
"def",
"get_rotation_parameters",
"(",
"phases",
",",
"magnitudes",
")",
":",
"# will hold the angles for controlled rotations",
"# in the phase unification and probability unification steps,",
"# respectively",
"z_thetas",
"=",
"[",
"]",
"y_thetas",
"=",
"[",
"]",
"# will hold... | Simulates one step of rotations.
Given lists of phases and magnitudes of the same length :math:`N`,
such that :math:`N=2^n` for some positive integer :math:`n`,
finds the rotation angles required for one step of phase and magnitude
unification.
:param list phases: real valued phases from :math:`-\... | [
"Simulates",
"one",
"step",
"of",
"rotations",
"."
] | python | train |
DataDog/integrations-core | tokumx/datadog_checks/tokumx/vendor/pymongo/bulk.py | https://github.com/DataDog/integrations-core/blob/ebd41c873cf9f97a8c51bf9459bc6a7536af8acd/tokumx/datadog_checks/tokumx/vendor/pymongo/bulk.py#L145-L198 | def _merge_command(run, full_result, results):
"""Merge a group of results from write commands into the full result.
"""
for offset, result in results:
affected = result.get("n", 0)
if run.op_type == _INSERT:
full_result["nInserted"] += affected
elif run.op_type == _DE... | [
"def",
"_merge_command",
"(",
"run",
",",
"full_result",
",",
"results",
")",
":",
"for",
"offset",
",",
"result",
"in",
"results",
":",
"affected",
"=",
"result",
".",
"get",
"(",
"\"n\"",
",",
"0",
")",
"if",
"run",
".",
"op_type",
"==",
"_INSERT",
... | Merge a group of results from write commands into the full result. | [
"Merge",
"a",
"group",
"of",
"results",
"from",
"write",
"commands",
"into",
"the",
"full",
"result",
"."
] | python | train |
zeroSteiner/AdvancedHTTPServer | advancedhttpserver.py | https://github.com/zeroSteiner/AdvancedHTTPServer/blob/8c53cf7e1ddbf7ae9f573c82c5fe5f6992db7b5a/advancedhttpserver.py#L1020-L1030 | def respond_unauthorized(self, request_authentication=False):
"""
Respond to the client that the request is unauthorized.
:param bool request_authentication: Whether to request basic authentication information by sending a WWW-Authenticate header.
"""
headers = {}
if request_authentication:
headers['WWW... | [
"def",
"respond_unauthorized",
"(",
"self",
",",
"request_authentication",
"=",
"False",
")",
":",
"headers",
"=",
"{",
"}",
"if",
"request_authentication",
":",
"headers",
"[",
"'WWW-Authenticate'",
"]",
"=",
"'Basic realm=\"'",
"+",
"self",
".",
"__config",
"[... | Respond to the client that the request is unauthorized.
:param bool request_authentication: Whether to request basic authentication information by sending a WWW-Authenticate header. | [
"Respond",
"to",
"the",
"client",
"that",
"the",
"request",
"is",
"unauthorized",
"."
] | python | train |
facetoe/zenpy | zenpy/lib/cache.py | https://github.com/facetoe/zenpy/blob/34c54c7e408b9ed01604ddf8b3422204c8bf31ea/zenpy/lib/cache.py#L27-L36 | def set_cache_impl(self, cache_impl, maxsize, **kwargs):
"""
Change cache implementation. The contents of the old cache will
be transferred to the new one.
:param cache_impl: Name of cache implementation, must exist in AVAILABLE_CACHES
"""
new_cache = self._get_cache_imp... | [
"def",
"set_cache_impl",
"(",
"self",
",",
"cache_impl",
",",
"maxsize",
",",
"*",
"*",
"kwargs",
")",
":",
"new_cache",
"=",
"self",
".",
"_get_cache_impl",
"(",
"cache_impl",
",",
"maxsize",
",",
"*",
"*",
"kwargs",
")",
"self",
".",
"_populate_new_cache... | Change cache implementation. The contents of the old cache will
be transferred to the new one.
:param cache_impl: Name of cache implementation, must exist in AVAILABLE_CACHES | [
"Change",
"cache",
"implementation",
".",
"The",
"contents",
"of",
"the",
"old",
"cache",
"will",
"be",
"transferred",
"to",
"the",
"new",
"one",
"."
] | python | train |
edx/edx-django-utils | edx_django_utils/monitoring/middleware.py | https://github.com/edx/edx-django-utils/blob/16cb4ac617e53c572bf68ccd19d24afeff1ca769/edx_django_utils/monitoring/middleware.py#L177-L202 | def _log_diff_memory_data(self, prefix, new_memory_data, old_memory_data):
"""
Computes and logs the difference in memory utilization
between the given old and new memory data.
"""
def _vmem_used(memory_data):
return memory_data['machine_data'].used
def _proc... | [
"def",
"_log_diff_memory_data",
"(",
"self",
",",
"prefix",
",",
"new_memory_data",
",",
"old_memory_data",
")",
":",
"def",
"_vmem_used",
"(",
"memory_data",
")",
":",
"return",
"memory_data",
"[",
"'machine_data'",
"]",
".",
"used",
"def",
"_process_mem_percent"... | Computes and logs the difference in memory utilization
between the given old and new memory data. | [
"Computes",
"and",
"logs",
"the",
"difference",
"in",
"memory",
"utilization",
"between",
"the",
"given",
"old",
"and",
"new",
"memory",
"data",
"."
] | python | train |
rochacbruno/flasgger | flasgger/utils.py | https://github.com/rochacbruno/flasgger/blob/fef154f61d7afca548067be0c758c3dd71cc4c97/flasgger/utils.py#L730-L739 | def get_vendor_extension_fields(mapping):
"""
Identify vendor extension fields and extract them into a new dictionary.
Examples:
>>> get_vendor_extension_fields({'test': 1})
{}
>>> get_vendor_extension_fields({'test': 1, 'x-test': 2})
{'x-test': 2}
"""
return {k: v fo... | [
"def",
"get_vendor_extension_fields",
"(",
"mapping",
")",
":",
"return",
"{",
"k",
":",
"v",
"for",
"k",
",",
"v",
"in",
"mapping",
".",
"items",
"(",
")",
"if",
"k",
".",
"startswith",
"(",
"'x-'",
")",
"}"
] | Identify vendor extension fields and extract them into a new dictionary.
Examples:
>>> get_vendor_extension_fields({'test': 1})
{}
>>> get_vendor_extension_fields({'test': 1, 'x-test': 2})
{'x-test': 2} | [
"Identify",
"vendor",
"extension",
"fields",
"and",
"extract",
"them",
"into",
"a",
"new",
"dictionary",
".",
"Examples",
":",
">>>",
"get_vendor_extension_fields",
"(",
"{",
"test",
":",
"1",
"}",
")",
"{}",
">>>",
"get_vendor_extension_fields",
"(",
"{",
"te... | python | train |
codelv/enaml-native | src/enamlnative/core/hotswap/core.py | https://github.com/codelv/enaml-native/blob/c33986e9eda468c508806e0a3e73c771401e5718/src/enamlnative/core/hotswap/core.py#L79-L83 | def update_class_by_type(old, new):
""" Update declarative classes or fallback on default """
autoreload.update_class(old, new)
if isinstance2(old, new, AtomMeta):
update_atom_members(old, new) | [
"def",
"update_class_by_type",
"(",
"old",
",",
"new",
")",
":",
"autoreload",
".",
"update_class",
"(",
"old",
",",
"new",
")",
"if",
"isinstance2",
"(",
"old",
",",
"new",
",",
"AtomMeta",
")",
":",
"update_atom_members",
"(",
"old",
",",
"new",
")"
] | Update declarative classes or fallback on default | [
"Update",
"declarative",
"classes",
"or",
"fallback",
"on",
"default"
] | python | train |
mandeep/Travis-Encrypt | travis/orderer.py | https://github.com/mandeep/Travis-Encrypt/blob/0dd2da1c71feaadcb84bdeb26827e6dfe1bd3b41/travis/orderer.py#L27-L37 | def ordered_dump(data, stream=None, Dumper=yaml.SafeDumper, **kwds):
"""Dump a yaml configuration as an OrderedDict."""
class OrderedDumper(Dumper):
pass
def dict_representer(dumper, data):
return dumper.represent_mapping(yaml.resolver.BaseResolver.DEFAULT_MAPPING_TAG, data.items())
Or... | [
"def",
"ordered_dump",
"(",
"data",
",",
"stream",
"=",
"None",
",",
"Dumper",
"=",
"yaml",
".",
"SafeDumper",
",",
"*",
"*",
"kwds",
")",
":",
"class",
"OrderedDumper",
"(",
"Dumper",
")",
":",
"pass",
"def",
"dict_representer",
"(",
"dumper",
",",
"d... | Dump a yaml configuration as an OrderedDict. | [
"Dump",
"a",
"yaml",
"configuration",
"as",
"an",
"OrderedDict",
"."
] | python | train |
UCSBarchlab/PyRTL | pyrtl/helperfuncs.py | https://github.com/UCSBarchlab/PyRTL/blob/0988e5c9c10ededd5e1f58d5306603f9edf4b3e2/pyrtl/helperfuncs.py#L277-L323 | def val_to_formatted_str(val, format, enum_set=None):
""" Return a string representation of the value given format specified.
:param val: a string holding an unsigned integer to convert
:param format: a string holding a format which will be used to convert the data string
:param enum_set: an iterable o... | [
"def",
"val_to_formatted_str",
"(",
"val",
",",
"format",
",",
"enum_set",
"=",
"None",
")",
":",
"type",
"=",
"format",
"[",
"0",
"]",
"bitwidth",
"=",
"int",
"(",
"format",
"[",
"1",
":",
"]",
".",
"split",
"(",
"'/'",
")",
"[",
"0",
"]",
")",
... | Return a string representation of the value given format specified.
:param val: a string holding an unsigned integer to convert
:param format: a string holding a format which will be used to convert the data string
:param enum_set: an iterable of enums which are used as part of the converstion process
... | [
"Return",
"a",
"string",
"representation",
"of",
"the",
"value",
"given",
"format",
"specified",
"."
] | python | train |
TDG-Platform/cloud-harness | gbdx_cloud_harness/services/task_service.py | https://github.com/TDG-Platform/cloud-harness/blob/1d8f972f861816b90785a484e9bec5bd4bc2f569/gbdx_cloud_harness/services/task_service.py#L35-L47 | def delete_task(self, task_name):
'''
Delete a task from the platforms regoistry
:param task_name: name of the task to delete
'''
response = self.session.delete('%s/%s' % (self.task_url, task_name))
if response.status_code == 200:
return response.status_code,... | [
"def",
"delete_task",
"(",
"self",
",",
"task_name",
")",
":",
"response",
"=",
"self",
".",
"session",
".",
"delete",
"(",
"'%s/%s'",
"%",
"(",
"self",
".",
"task_url",
",",
"task_name",
")",
")",
"if",
"response",
".",
"status_code",
"==",
"200",
":"... | Delete a task from the platforms regoistry
:param task_name: name of the task to delete | [
"Delete",
"a",
"task",
"from",
"the",
"platforms",
"regoistry",
":",
"param",
"task_name",
":",
"name",
"of",
"the",
"task",
"to",
"delete"
] | python | test |
mickybart/python-atlasbroker | atlasbroker/storage.py | https://github.com/mickybart/python-atlasbroker/blob/5b741c1348a6d33b342e0852a8a8900fa9ebf00a/atlasbroker/storage.py#L109-L145 | def store(self, obj):
""" Store
Store an object into the MongoDB storage for caching
Args:
obj (AtlasServiceBinding.Binding or AtlasServiceInstance.Instance): instance or binding
Returns:
ObjectId: MongoDB _id
Raise... | [
"def",
"store",
"(",
"self",
",",
"obj",
")",
":",
"# query",
"if",
"type",
"(",
"obj",
")",
"is",
"AtlasServiceInstance",
".",
"Instance",
":",
"query",
"=",
"{",
"\"instance_id\"",
":",
"obj",
".",
"instance_id",
",",
"\"database\"",
":",
"obj",
".",
... | Store
Store an object into the MongoDB storage for caching
Args:
obj (AtlasServiceBinding.Binding or AtlasServiceInstance.Instance): instance or binding
Returns:
ObjectId: MongoDB _id
Raises:
ErrStorageMongoConn... | [
"Store",
"Store",
"an",
"object",
"into",
"the",
"MongoDB",
"storage",
"for",
"caching",
"Args",
":",
"obj",
"(",
"AtlasServiceBinding",
".",
"Binding",
"or",
"AtlasServiceInstance",
".",
"Instance",
")",
":",
"instance",
"or",
"binding",
"Returns",
":",
"Obje... | python | train |
andreagrandi/toshl-python | toshl/client.py | https://github.com/andreagrandi/toshl-python/blob/16a2aef8a0d389db73db3253b0bea3fcc33cc2bf/toshl/client.py#L11-L47 | def _make_request(
self, api_resource, method='GET', params=None, **kwargs):
"""
Shortcut for a generic request to the Toshl API
:param url: The URL resource part
:param method: REST method
:param parameters: Querystring parameters
:return: requests.Response
... | [
"def",
"_make_request",
"(",
"self",
",",
"api_resource",
",",
"method",
"=",
"'GET'",
",",
"params",
"=",
"None",
",",
"*",
"*",
"kwargs",
")",
":",
"if",
"kwargs",
".",
"get",
"(",
"'json'",
")",
":",
"headers",
"=",
"{",
"'Authorization'",
":",
"'... | Shortcut for a generic request to the Toshl API
:param url: The URL resource part
:param method: REST method
:param parameters: Querystring parameters
:return: requests.Response | [
"Shortcut",
"for",
"a",
"generic",
"request",
"to",
"the",
"Toshl",
"API",
":",
"param",
"url",
":",
"The",
"URL",
"resource",
"part",
":",
"param",
"method",
":",
"REST",
"method",
":",
"param",
"parameters",
":",
"Querystring",
"parameters",
":",
"return... | python | train |
payu-org/payu | payu/calendar.py | https://github.com/payu-org/payu/blob/1442a9a226012eff248b8097cc1eaabc3e224867/payu/calendar.py#L41-L55 | def date_plus_seconds(init_date, seconds, caltype):
"""
Get a new_date = date + seconds.
Ignores Feb 29 for no-leap days.
"""
end_date = init_date + datetime.timedelta(seconds=seconds)
if caltype == NOLEAP:
end_date += get_leapdays(init_date, end_date)
if end_date.month == 2 a... | [
"def",
"date_plus_seconds",
"(",
"init_date",
",",
"seconds",
",",
"caltype",
")",
":",
"end_date",
"=",
"init_date",
"+",
"datetime",
".",
"timedelta",
"(",
"seconds",
"=",
"seconds",
")",
"if",
"caltype",
"==",
"NOLEAP",
":",
"end_date",
"+=",
"get_leapday... | Get a new_date = date + seconds.
Ignores Feb 29 for no-leap days. | [
"Get",
"a",
"new_date",
"=",
"date",
"+",
"seconds",
"."
] | python | train |
vingd/vingd-api-python | vingd/client.py | https://github.com/vingd/vingd-api-python/blob/7548a49973a472f7277c8ef847563faa7b6f3706/vingd/client.py#L627-L691 | def create_voucher(self, amount, expires=None, message='', gid=None):
"""
CREATES a new preallocated voucher with ``amount`` vingd cents reserved
until ``expires``.
:type amount: ``bigint``
:param amount:
Voucher amount in vingd cents.
:type expires: ... | [
"def",
"create_voucher",
"(",
"self",
",",
"amount",
",",
"expires",
"=",
"None",
",",
"message",
"=",
"''",
",",
"gid",
"=",
"None",
")",
":",
"expires",
"=",
"absdatetime",
"(",
"expires",
",",
"default",
"=",
"self",
".",
"EXP_VOUCHER",
")",
".",
... | CREATES a new preallocated voucher with ``amount`` vingd cents reserved
until ``expires``.
:type amount: ``bigint``
:param amount:
Voucher amount in vingd cents.
:type expires: ``datetime``/``dict``
:param expires:
Voucher expiry timestamp, absolu... | [
"CREATES",
"a",
"new",
"preallocated",
"voucher",
"with",
"amount",
"vingd",
"cents",
"reserved",
"until",
"expires",
".",
":",
"type",
"amount",
":",
"bigint",
":",
"param",
"amount",
":",
"Voucher",
"amount",
"in",
"vingd",
"cents",
".",
":",
"type",
"ex... | python | train |
aboSamoor/polyglot | polyglot/mapping/embeddings.py | https://github.com/aboSamoor/polyglot/blob/d0d2aa8d06cec4e03bd96618ae960030f7069a17/polyglot/mapping/embeddings.py#L80-L88 | def most_frequent(self, k, inplace=False):
"""Only most frequent k words to be included in the embeddings."""
vocabulary = self.vocabulary.most_frequent(k)
vectors = np.asarray([self[w] for w in vocabulary])
if inplace:
self.vocabulary = vocabulary
self.vectors = vectors
return self
... | [
"def",
"most_frequent",
"(",
"self",
",",
"k",
",",
"inplace",
"=",
"False",
")",
":",
"vocabulary",
"=",
"self",
".",
"vocabulary",
".",
"most_frequent",
"(",
"k",
")",
"vectors",
"=",
"np",
".",
"asarray",
"(",
"[",
"self",
"[",
"w",
"]",
"for",
... | Only most frequent k words to be included in the embeddings. | [
"Only",
"most",
"frequent",
"k",
"words",
"to",
"be",
"included",
"in",
"the",
"embeddings",
"."
] | python | train |
digidotcom/python-devicecloud | devicecloud/streams.py | https://github.com/digidotcom/python-devicecloud/blob/32529684a348a7830a269c32601604c78036bcb8/devicecloud/streams.py#L224-L283 | def bulk_write_datapoints(self, datapoints):
"""Perform a bulk write (or set of writes) of a collection of data points
This method takes a list (or other iterable) of datapoints and writes them
to Device Cloud in an efficient manner, minimizing the number of HTTP
requests that need to b... | [
"def",
"bulk_write_datapoints",
"(",
"self",
",",
"datapoints",
")",
":",
"datapoints",
"=",
"list",
"(",
"datapoints",
")",
"# effectively performs validation that we have the right type",
"for",
"dp",
"in",
"datapoints",
":",
"if",
"not",
"isinstance",
"(",
"dp",
... | Perform a bulk write (or set of writes) of a collection of data points
This method takes a list (or other iterable) of datapoints and writes them
to Device Cloud in an efficient manner, minimizing the number of HTTP
requests that need to be made.
As this call is performed from outside ... | [
"Perform",
"a",
"bulk",
"write",
"(",
"or",
"set",
"of",
"writes",
")",
"of",
"a",
"collection",
"of",
"data",
"points"
] | python | train |
dustinmm80/healthy | package_utils.py | https://github.com/dustinmm80/healthy/blob/b59016c3f578ca45b6ce857a2d5c4584b8542288/package_utils.py#L60-L70 | def main():
"""
Main function for this module
"""
sandbox = create_sandbox()
directory = download_package_to_sandbox(
sandbox,
'https://pypi.python.org/packages/source/c/checkmyreqs/checkmyreqs-0.1.6.tar.gz'
)
print(directory)
destroy_sandbox(sandbox) | [
"def",
"main",
"(",
")",
":",
"sandbox",
"=",
"create_sandbox",
"(",
")",
"directory",
"=",
"download_package_to_sandbox",
"(",
"sandbox",
",",
"'https://pypi.python.org/packages/source/c/checkmyreqs/checkmyreqs-0.1.6.tar.gz'",
")",
"print",
"(",
"directory",
")",
"destro... | Main function for this module | [
"Main",
"function",
"for",
"this",
"module"
] | python | train |
LEMS/pylems | lems/parser/LEMS.py | https://github.com/LEMS/pylems/blob/4eeb719d2f23650fe16c38626663b69b5c83818b/lems/parser/LEMS.py#L614-L632 | def parse_data_display(self, node):
"""
Parses <DataDisplay>
@param node: Node containing the <DataDisplay> element
@type node: xml.etree.Element
"""
if 'title' in node.lattrib:
title = node.lattrib['title']
else:
self.raise_error('<DataD... | [
"def",
"parse_data_display",
"(",
"self",
",",
"node",
")",
":",
"if",
"'title'",
"in",
"node",
".",
"lattrib",
":",
"title",
"=",
"node",
".",
"lattrib",
"[",
"'title'",
"]",
"else",
":",
"self",
".",
"raise_error",
"(",
"'<DataDisplay> must have a title.'"... | Parses <DataDisplay>
@param node: Node containing the <DataDisplay> element
@type node: xml.etree.Element | [
"Parses",
"<DataDisplay",
">"
] | python | train |
wright-group/WrightTools | WrightTools/artists/_helpers.py | https://github.com/wright-group/WrightTools/blob/80d3ddd5074d8d5c1bc03fd5a0e0f10d4b424aeb/WrightTools/artists/_helpers.py#L1010-L1045 | def stitch_to_animation(images, outpath=None, *, duration=0.5, palettesize=256, verbose=True):
"""Stitch a series of images into an animation.
Currently supports animated gifs, other formats coming as needed.
Parameters
----------
images : list of strings
Filepaths to the images to stitch ... | [
"def",
"stitch_to_animation",
"(",
"images",
",",
"outpath",
"=",
"None",
",",
"*",
",",
"duration",
"=",
"0.5",
",",
"palettesize",
"=",
"256",
",",
"verbose",
"=",
"True",
")",
":",
"# parse filename",
"if",
"outpath",
"is",
"None",
":",
"outpath",
"="... | Stitch a series of images into an animation.
Currently supports animated gifs, other formats coming as needed.
Parameters
----------
images : list of strings
Filepaths to the images to stitch together, in order of apperence.
outpath : string (optional)
Path of output, including ext... | [
"Stitch",
"a",
"series",
"of",
"images",
"into",
"an",
"animation",
"."
] | python | train |
cogeotiff/rio-tiler | rio_tiler/cbers.py | https://github.com/cogeotiff/rio-tiler/blob/09bb0fc6cee556410477f016abbae172b12c46a6/rio_tiler/cbers.py#L148-L195 | def metadata(sceneid, pmin=2, pmax=98, **kwargs):
"""
Return band bounds and statistics.
Attributes
----------
sceneid : str
CBERS sceneid.
pmin : int, optional, (default: 2)
Histogram minimum cut.
pmax : int, optional, (default: 98)
Histogram maximum cut.
kwargs... | [
"def",
"metadata",
"(",
"sceneid",
",",
"pmin",
"=",
"2",
",",
"pmax",
"=",
"98",
",",
"*",
"*",
"kwargs",
")",
":",
"scene_params",
"=",
"_cbers_parse_scene_id",
"(",
"sceneid",
")",
"cbers_address",
"=",
"\"{}/{}\"",
".",
"format",
"(",
"CBERS_BUCKET",
... | Return band bounds and statistics.
Attributes
----------
sceneid : str
CBERS sceneid.
pmin : int, optional, (default: 2)
Histogram minimum cut.
pmax : int, optional, (default: 98)
Histogram maximum cut.
kwargs : optional
These are passed to 'rio_tiler.utils.raste... | [
"Return",
"band",
"bounds",
"and",
"statistics",
"."
] | python | train |
jilljenn/tryalgo | tryalgo/rabin_karp.py | https://github.com/jilljenn/tryalgo/blob/89a4dd9655e7b6b0a176f72b4c60d0196420dfe1/tryalgo/rabin_karp.py#L30-L57 | def rabin_karp_matching(s, t):
"""Find a substring by Rabin-Karp
:param s: the haystack string
:param t: the needle string
:returns: index i such that s[i: i + len(t)] == t, or -1
:complexity: O(len(s) + len(t)) in expected time,
and O(len(s) * len(t)) in worst case
"""
has... | [
"def",
"rabin_karp_matching",
"(",
"s",
",",
"t",
")",
":",
"hash_s",
"=",
"0",
"hash_t",
"=",
"0",
"len_s",
"=",
"len",
"(",
"s",
")",
"len_t",
"=",
"len",
"(",
"t",
")",
"last_pos",
"=",
"pow",
"(",
"DOMAIN",
",",
"len_t",
"-",
"1",
")",
"%",... | Find a substring by Rabin-Karp
:param s: the haystack string
:param t: the needle string
:returns: index i such that s[i: i + len(t)] == t, or -1
:complexity: O(len(s) + len(t)) in expected time,
and O(len(s) * len(t)) in worst case | [
"Find",
"a",
"substring",
"by",
"Rabin",
"-",
"Karp"
] | python | train |
erkghlerngm44/malaffinity | malaffinity/__init__.py | https://github.com/erkghlerngm44/malaffinity/blob/d866b9198b668333f0b86567b2faebdb20587e30/malaffinity/__init__.py#L29-L44 | def calculate_affinity(user1, user2, round=False): # pragma: no cover
"""
Quick one-off affinity calculations.
Creates an instance of the ``MALAffinity`` class with ``user1``,
then calculates affinity with ``user2``.
:param str user1: First user
:param str user2: Second user
:param round:... | [
"def",
"calculate_affinity",
"(",
"user1",
",",
"user2",
",",
"round",
"=",
"False",
")",
":",
"# pragma: no cover",
"return",
"MALAffinity",
"(",
"base_user",
"=",
"user1",
",",
"round",
"=",
"round",
")",
".",
"calculate_affinity",
"(",
"user2",
")"
] | Quick one-off affinity calculations.
Creates an instance of the ``MALAffinity`` class with ``user1``,
then calculates affinity with ``user2``.
:param str user1: First user
:param str user2: Second user
:param round: Decimal places to round affinity values to.
Specify ``False`` for no round... | [
"Quick",
"one",
"-",
"off",
"affinity",
"calculations",
"."
] | python | train |
bitesofcode/projexui | projexui/widgets/xchart/xchartscene.py | https://github.com/bitesofcode/projexui/blob/f18a73bec84df90b034ca69b9deea118dbedfc4d/projexui/widgets/xchart/xchartscene.py#L60-L68 | def drawBackground(self, painter, rect):
"""
Draws the background for the chart scene.
:param painter | <QPainter>
rect | <QRect>
"""
chart = self.chart()
chart._drawBackground(self, painter, rect) | [
"def",
"drawBackground",
"(",
"self",
",",
"painter",
",",
"rect",
")",
":",
"chart",
"=",
"self",
".",
"chart",
"(",
")",
"chart",
".",
"_drawBackground",
"(",
"self",
",",
"painter",
",",
"rect",
")"
] | Draws the background for the chart scene.
:param painter | <QPainter>
rect | <QRect> | [
"Draws",
"the",
"background",
"for",
"the",
"chart",
"scene",
".",
":",
"param",
"painter",
"|",
"<QPainter",
">",
"rect",
"|",
"<QRect",
">"
] | python | train |
apache/airflow | airflow/contrib/operators/mssql_to_gcs.py | https://github.com/apache/airflow/blob/b69c686ad8a0c89b9136bb4b31767257eb7b2597/airflow/contrib/operators/mssql_to_gcs.py#L214-L222 | def convert_types(cls, value):
"""
Takes a value from MSSQL, and converts it to a value that's safe for
JSON/Google Cloud Storage/BigQuery.
"""
if isinstance(value, decimal.Decimal):
return float(value)
else:
return value | [
"def",
"convert_types",
"(",
"cls",
",",
"value",
")",
":",
"if",
"isinstance",
"(",
"value",
",",
"decimal",
".",
"Decimal",
")",
":",
"return",
"float",
"(",
"value",
")",
"else",
":",
"return",
"value"
] | Takes a value from MSSQL, and converts it to a value that's safe for
JSON/Google Cloud Storage/BigQuery. | [
"Takes",
"a",
"value",
"from",
"MSSQL",
"and",
"converts",
"it",
"to",
"a",
"value",
"that",
"s",
"safe",
"for",
"JSON",
"/",
"Google",
"Cloud",
"Storage",
"/",
"BigQuery",
"."
] | python | test |
ggravlingen/pytradfri | pytradfri/smart_task.py | https://github.com/ggravlingen/pytradfri/blob/63750fa8fb27158c013d24865cdaa7fb82b3ab53/pytradfri/smart_task.py#L255-L262 | def item_controller(self):
"""Method to control a task."""
return StartActionItemController(
self,
self.raw,
self.state,
self.path,
self.devices_dict) | [
"def",
"item_controller",
"(",
"self",
")",
":",
"return",
"StartActionItemController",
"(",
"self",
",",
"self",
".",
"raw",
",",
"self",
".",
"state",
",",
"self",
".",
"path",
",",
"self",
".",
"devices_dict",
")"
] | Method to control a task. | [
"Method",
"to",
"control",
"a",
"task",
"."
] | python | train |
rnwolf/jira-metrics-extract | jira_metrics_extract/cycletime.py | https://github.com/rnwolf/jira-metrics-extract/blob/56443211b3e1200f3def79173a21e0232332ae17/jira_metrics_extract/cycletime.py#L658-L679 | def throughput_data(self, cycle_data, frequency='1D',pointscolumn= None):
"""Return a data frame with columns `completed_timestamp` of the
given frequency, either
`count`, where count is the number of items
'sum', where sum is the sum of value specified by pointscolumn. Expected to be 'S... | [
"def",
"throughput_data",
"(",
"self",
",",
"cycle_data",
",",
"frequency",
"=",
"'1D'",
",",
"pointscolumn",
"=",
"None",
")",
":",
"if",
"len",
"(",
"cycle_data",
")",
"<",
"1",
":",
"return",
"None",
"# Note completed items yet, return None",
"if",
"pointsc... | Return a data frame with columns `completed_timestamp` of the
given frequency, either
`count`, where count is the number of items
'sum', where sum is the sum of value specified by pointscolumn. Expected to be 'StoryPoints'
completed at that timestamp (e.g. daily). | [
"Return",
"a",
"data",
"frame",
"with",
"columns",
"completed_timestamp",
"of",
"the",
"given",
"frequency",
"either",
"count",
"where",
"count",
"is",
"the",
"number",
"of",
"items",
"sum",
"where",
"sum",
"is",
"the",
"sum",
"of",
"value",
"specified",
"by... | python | train |
aouyar/PyMunin | pymunin/__init__.py | https://github.com/aouyar/PyMunin/blob/4f58a64b6b37c85a84cc7e1e07aafaa0321b249d/pymunin/__init__.py#L448-L464 | def saveState(self, stateObj):
"""Utility methos to save plugin state stored in stateObj to persistent
storage to permit access to previous state in subsequent plugin runs.
Any object that can be pickled and unpickled can be used to store the
plugin state.
@p... | [
"def",
"saveState",
"(",
"self",
",",
"stateObj",
")",
":",
"try",
":",
"fp",
"=",
"open",
"(",
"self",
".",
"_stateFile",
",",
"'w'",
")",
"pickle",
".",
"dump",
"(",
"stateObj",
",",
"fp",
")",
"except",
":",
"raise",
"IOError",
"(",
"\"Failure in ... | Utility methos to save plugin state stored in stateObj to persistent
storage to permit access to previous state in subsequent plugin runs.
Any object that can be pickled and unpickled can be used to store the
plugin state.
@param stateObj: Object that stores plugin st... | [
"Utility",
"methos",
"to",
"save",
"plugin",
"state",
"stored",
"in",
"stateObj",
"to",
"persistent",
"storage",
"to",
"permit",
"access",
"to",
"previous",
"state",
"in",
"subsequent",
"plugin",
"runs",
".",
"Any",
"object",
"that",
"can",
"be",
"pickled",
... | python | train |
samghelms/mathviz | mathviz_hopper/src/bottle.py | https://github.com/samghelms/mathviz/blob/30fe89537379faea4de8c8b568ac6e52e4d15353/mathviz_hopper/src/bottle.py#L954-L974 | def error(self, code=500, callback=None):
""" Register an output handler for a HTTP error code. Can
be used as a decorator or called directly ::
def error_handler_500(error):
return 'error_handler_500'
app.error(code=500, callback=error_handler_5... | [
"def",
"error",
"(",
"self",
",",
"code",
"=",
"500",
",",
"callback",
"=",
"None",
")",
":",
"def",
"decorator",
"(",
"callback",
")",
":",
"if",
"isinstance",
"(",
"callback",
",",
"basestring",
")",
":",
"callback",
"=",
"load",
"(",
"callback",
"... | Register an output handler for a HTTP error code. Can
be used as a decorator or called directly ::
def error_handler_500(error):
return 'error_handler_500'
app.error(code=500, callback=error_handler_500)
@app.error(404)
d... | [
"Register",
"an",
"output",
"handler",
"for",
"a",
"HTTP",
"error",
"code",
".",
"Can",
"be",
"used",
"as",
"a",
"decorator",
"or",
"called",
"directly",
"::"
] | python | train |
keon/algorithms | algorithms/calculator/math_parser.py | https://github.com/keon/algorithms/blob/4d6569464a62a75c1357acc97e2dd32ee2f9f4a3/algorithms/calculator/math_parser.py#L68-L75 | def apply_operation(op_stack, out_stack):
"""
Apply operation to the first 2 items of the output queue
op_stack Deque (reference)
out_stack Deque (reference)
"""
out_stack.append(calc(out_stack.pop(), out_stack.pop(), op_stack.pop())) | [
"def",
"apply_operation",
"(",
"op_stack",
",",
"out_stack",
")",
":",
"out_stack",
".",
"append",
"(",
"calc",
"(",
"out_stack",
".",
"pop",
"(",
")",
",",
"out_stack",
".",
"pop",
"(",
")",
",",
"op_stack",
".",
"pop",
"(",
")",
")",
")"
] | Apply operation to the first 2 items of the output queue
op_stack Deque (reference)
out_stack Deque (reference) | [
"Apply",
"operation",
"to",
"the",
"first",
"2",
"items",
"of",
"the",
"output",
"queue",
"op_stack",
"Deque",
"(",
"reference",
")",
"out_stack",
"Deque",
"(",
"reference",
")"
] | python | train |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.