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 |
|---|---|---|---|---|---|---|---|---|
newville/wxmplot | wxmplot/config.py | https://github.com/newville/wxmplot/blob/8e0dc037453e5cdf18c968dc5a3d29efd761edee/wxmplot/config.py#L401-L409 | def set_gridcolor(self, color):
"""set color for grid"""
self.gridcolor = color
for ax in self.canvas.figure.get_axes():
for i in ax.get_xgridlines()+ax.get_ygridlines():
i.set_color(color)
i.set_zorder(-1)
if callable(self.theme_color_callback... | [
"def",
"set_gridcolor",
"(",
"self",
",",
"color",
")",
":",
"self",
".",
"gridcolor",
"=",
"color",
"for",
"ax",
"in",
"self",
".",
"canvas",
".",
"figure",
".",
"get_axes",
"(",
")",
":",
"for",
"i",
"in",
"ax",
".",
"get_xgridlines",
"(",
")",
"... | set color for grid | [
"set",
"color",
"for",
"grid"
] | python | train |
stephantul/somber | somber/components/initializers.py | https://github.com/stephantul/somber/blob/b7a13e646239500cc393668c01a7169c3e50b7b5/somber/components/initializers.py#L10-L37 | def range_initialization(X, num_weights):
"""
Initialize the weights by calculating the range of the data.
The data range is calculated by reshaping the input matrix to a
2D matrix, and then taking the min and max values over the columns.
Parameters
----------
X : numpy array
The i... | [
"def",
"range_initialization",
"(",
"X",
",",
"num_weights",
")",
":",
"# Randomly initialize weights to cover the range of each feature.",
"X_",
"=",
"X",
".",
"reshape",
"(",
"-",
"1",
",",
"X",
".",
"shape",
"[",
"-",
"1",
"]",
")",
"min_val",
",",
"max_val... | Initialize the weights by calculating the range of the data.
The data range is calculated by reshaping the input matrix to a
2D matrix, and then taking the min and max values over the columns.
Parameters
----------
X : numpy array
The input data. The data range is calculated over the last ... | [
"Initialize",
"the",
"weights",
"by",
"calculating",
"the",
"range",
"of",
"the",
"data",
"."
] | python | train |
saltstack/salt | salt/modules/cpan.py | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/cpan.py#L133-L149 | def list_():
'''
List installed Perl modules, and the version installed
CLI Example:
.. code-block:: bash
salt '*' cpan.list
'''
ret = {}
cmd = 'cpan -l'
out = __salt__['cmd.run'](cmd).splitlines()
for line in out:
comps = line.split()
ret[comps[0]] = comps... | [
"def",
"list_",
"(",
")",
":",
"ret",
"=",
"{",
"}",
"cmd",
"=",
"'cpan -l'",
"out",
"=",
"__salt__",
"[",
"'cmd.run'",
"]",
"(",
"cmd",
")",
".",
"splitlines",
"(",
")",
"for",
"line",
"in",
"out",
":",
"comps",
"=",
"line",
".",
"split",
"(",
... | List installed Perl modules, and the version installed
CLI Example:
.. code-block:: bash
salt '*' cpan.list | [
"List",
"installed",
"Perl",
"modules",
"and",
"the",
"version",
"installed"
] | python | train |
saltstack/salt | salt/modules/boto_cloudfront.py | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/boto_cloudfront.py#L234-L278 | def export_distributions(region=None, key=None, keyid=None, profile=None):
'''
Get details of all CloudFront distributions.
Produces results that can be used to create an SLS file.
CLI Example:
.. code-block:: bash
salt-call boto_cloudfront.export_distributions --out=txt |\
se... | [
"def",
"export_distributions",
"(",
"region",
"=",
"None",
",",
"key",
"=",
"None",
",",
"keyid",
"=",
"None",
",",
"profile",
"=",
"None",
")",
":",
"results",
"=",
"OrderedDict",
"(",
")",
"conn",
"=",
"_get_conn",
"(",
"region",
"=",
"region",
",",
... | Get details of all CloudFront distributions.
Produces results that can be used to create an SLS file.
CLI Example:
.. code-block:: bash
salt-call boto_cloudfront.export_distributions --out=txt |\
sed "s/local: //" > cloudfront_distributions.sls | [
"Get",
"details",
"of",
"all",
"CloudFront",
"distributions",
".",
"Produces",
"results",
"that",
"can",
"be",
"used",
"to",
"create",
"an",
"SLS",
"file",
"."
] | python | train |
KelSolaar/Foundations | foundations/trace.py | https://github.com/KelSolaar/Foundations/blob/5c141330faf09dad70a12bc321f4c564917d0a91/foundations/trace.py#L609-L628 | def untrace_property(cls, accessor):
"""
Untraces given class property.
:param cls: Class of the property.
:type cls: object
:param accessor: Property to untrace.
:type accessor: property
:return: Definition success.
:rtype: bool
"""
if not is_traced(accessor.fget) or not is_tr... | [
"def",
"untrace_property",
"(",
"cls",
",",
"accessor",
")",
":",
"if",
"not",
"is_traced",
"(",
"accessor",
".",
"fget",
")",
"or",
"not",
"is_traced",
"(",
"accessor",
".",
"fset",
")",
"or",
"not",
"is_traced",
"(",
"accessor",
".",
"fdel",
")",
":"... | Untraces given class property.
:param cls: Class of the property.
:type cls: object
:param accessor: Property to untrace.
:type accessor: property
:return: Definition success.
:rtype: bool | [
"Untraces",
"given",
"class",
"property",
"."
] | python | train |
dmsimard/python-cachetclient | cachetclient/cachet.py | https://github.com/dmsimard/python-cachetclient/blob/31bbc6d17ba5de088846e1ffae259b6755e672a0/cachetclient/cachet.py#L306-L313 | def get(self, metric_id=None, **kwargs):
"""
https://docs.cachethq.io/docs/get-metric-points
"""
if metric_id is None:
raise AttributeError('metric_id is required to get metric points.')
return self._get('metrics/%s/points' % metric_id, data=kwargs) | [
"def",
"get",
"(",
"self",
",",
"metric_id",
"=",
"None",
",",
"*",
"*",
"kwargs",
")",
":",
"if",
"metric_id",
"is",
"None",
":",
"raise",
"AttributeError",
"(",
"'metric_id is required to get metric points.'",
")",
"return",
"self",
".",
"_get",
"(",
"'met... | https://docs.cachethq.io/docs/get-metric-points | [
"https",
":",
"//",
"docs",
".",
"cachethq",
".",
"io",
"/",
"docs",
"/",
"get",
"-",
"metric",
"-",
"points"
] | python | train |
DIPSAS/SwarmManagement | SwarmManagement/__init__.py | https://github.com/DIPSAS/SwarmManagement/blob/c9ef1165b240c145d42e2d363925c8200fc19f43/SwarmManagement/__init__.py#L4-L9 | def main():
"""Entry point for the application script"""
arguments = sys.argv[1:]
print('Managing solution with arguments: ')
print(arguments)
SwarmManager.HandleManagement(arguments) | [
"def",
"main",
"(",
")",
":",
"arguments",
"=",
"sys",
".",
"argv",
"[",
"1",
":",
"]",
"print",
"(",
"'Managing solution with arguments: '",
")",
"print",
"(",
"arguments",
")",
"SwarmManager",
".",
"HandleManagement",
"(",
"arguments",
")"
] | Entry point for the application script | [
"Entry",
"point",
"for",
"the",
"application",
"script"
] | python | train |
acrisci/i3ipc-python | examples/stop-application-on-unfocus.py | https://github.com/acrisci/i3ipc-python/blob/243d353434cdd2a93a9ca917c6bbf07b865c39af/examples/stop-application-on-unfocus.py#L31-L40 | def stop_cont(self, cont=True):
"""Send SIGSTOP/SIGCONT to processes called <name>
"""
for proc in psutil.process_iter():
if proc.name() == self.process_name:
sig = psutil.signal.SIGCONT if cont else psutil.signal.SIGSTOP
proc.send_signal(sig)
... | [
"def",
"stop_cont",
"(",
"self",
",",
"cont",
"=",
"True",
")",
":",
"for",
"proc",
"in",
"psutil",
".",
"process_iter",
"(",
")",
":",
"if",
"proc",
".",
"name",
"(",
")",
"==",
"self",
".",
"process_name",
":",
"sig",
"=",
"psutil",
".",
"signal"... | Send SIGSTOP/SIGCONT to processes called <name> | [
"Send",
"SIGSTOP",
"/",
"SIGCONT",
"to",
"processes",
"called",
"<name",
">"
] | python | train |
tensorflow/tensorboard | tensorboard/plugins/interactive_inference/interactive_inference_plugin.py | https://github.com/tensorflow/tensorboard/blob/8e5f497b48e40f2a774f85416b8a35ac0693c35e/tensorboard/plugins/interactive_inference/interactive_inference_plugin.py#L190-L208 | def _duplicate_example(self, request):
"""Duplicates the specified example.
Args:
request: A request that should contain 'index'.
Returns:
An empty response.
"""
index = int(request.args.get('index'))
if index >= len(self.examples):
return http_util.Respond(request, {'error':... | [
"def",
"_duplicate_example",
"(",
"self",
",",
"request",
")",
":",
"index",
"=",
"int",
"(",
"request",
".",
"args",
".",
"get",
"(",
"'index'",
")",
")",
"if",
"index",
">=",
"len",
"(",
"self",
".",
"examples",
")",
":",
"return",
"http_util",
"."... | Duplicates the specified example.
Args:
request: A request that should contain 'index'.
Returns:
An empty response. | [
"Duplicates",
"the",
"specified",
"example",
"."
] | python | train |
CamDavidsonPilon/lifelines | lifelines/fitters/coxph_fitter.py | https://github.com/CamDavidsonPilon/lifelines/blob/bdf6be6f1d10eea4c46365ee0ee6a47d8c30edf8/lifelines/fitters/coxph_fitter.py#L1071-L1084 | def _compute_delta_beta(self, X, T, E, weights, index=None):
"""
approximate change in betas as a result of excluding ith row. Good for finding outliers / specific
subjects that influence the model disproportionately. Good advice: don't drop these outliers, model them.
"""
score_... | [
"def",
"_compute_delta_beta",
"(",
"self",
",",
"X",
",",
"T",
",",
"E",
",",
"weights",
",",
"index",
"=",
"None",
")",
":",
"score_residuals",
"=",
"self",
".",
"_compute_score",
"(",
"X",
",",
"T",
",",
"E",
",",
"weights",
",",
"index",
"=",
"i... | approximate change in betas as a result of excluding ith row. Good for finding outliers / specific
subjects that influence the model disproportionately. Good advice: don't drop these outliers, model them. | [
"approximate",
"change",
"in",
"betas",
"as",
"a",
"result",
"of",
"excluding",
"ith",
"row",
".",
"Good",
"for",
"finding",
"outliers",
"/",
"specific",
"subjects",
"that",
"influence",
"the",
"model",
"disproportionately",
".",
"Good",
"advice",
":",
"don",
... | python | train |
cloud9ers/gurumate | environment/lib/python2.7/site-packages/IPython/parallel/client/remotefunction.py | https://github.com/cloud9ers/gurumate/blob/075dc74d1ee62a8c6b7a8bf2b271364f01629d1e/environment/lib/python2.7/site-packages/IPython/parallel/client/remotefunction.py#L231-L242 | def map(self, *sequences):
"""call a function on each element of a sequence remotely.
This should behave very much like the builtin map, but return an AsyncMapResult
if self.block is False.
"""
# set _map as a flag for use inside self.__call__
self._map = True
try... | [
"def",
"map",
"(",
"self",
",",
"*",
"sequences",
")",
":",
"# set _map as a flag for use inside self.__call__",
"self",
".",
"_map",
"=",
"True",
"try",
":",
"ret",
"=",
"self",
".",
"__call__",
"(",
"*",
"sequences",
")",
"finally",
":",
"del",
"self",
"... | call a function on each element of a sequence remotely.
This should behave very much like the builtin map, but return an AsyncMapResult
if self.block is False. | [
"call",
"a",
"function",
"on",
"each",
"element",
"of",
"a",
"sequence",
"remotely",
".",
"This",
"should",
"behave",
"very",
"much",
"like",
"the",
"builtin",
"map",
"but",
"return",
"an",
"AsyncMapResult",
"if",
"self",
".",
"block",
"is",
"False",
"."
] | python | test |
apache/incubator-mxnet | python/mxnet/gluon/parameter.py | https://github.com/apache/incubator-mxnet/blob/1af29e9c060a4c7d60eeaacba32afdb9a7775ba7/python/mxnet/gluon/parameter.py#L418-L434 | def set_data(self, data):
"""Sets this parameter's value on all contexts."""
self.shape = data.shape
if self._data is None:
assert self._deferred_init, \
"Parameter '%s' has not been initialized"%self.name
self._deferred_init = self._deferred_init[:3] + (... | [
"def",
"set_data",
"(",
"self",
",",
"data",
")",
":",
"self",
".",
"shape",
"=",
"data",
".",
"shape",
"if",
"self",
".",
"_data",
"is",
"None",
":",
"assert",
"self",
".",
"_deferred_init",
",",
"\"Parameter '%s' has not been initialized\"",
"%",
"self",
... | Sets this parameter's value on all contexts. | [
"Sets",
"this",
"parameter",
"s",
"value",
"on",
"all",
"contexts",
"."
] | python | train |
rigetti/quantumflow | quantumflow/gates.py | https://github.com/rigetti/quantumflow/blob/13a66cabbe8aabf6e023cc675f4a4ebe6ccda8fb/quantumflow/gates.py#L71-L83 | def control_gate(control: Qubit, gate: Gate) -> Gate:
"""Return a controlled unitary gate. Given a gate acting on K qubits,
return a new gate on K+1 qubits prepended with a control bit. """
if control in gate.qubits:
raise ValueError('Gate and control qubits overlap')
qubits = [control, *gate.... | [
"def",
"control_gate",
"(",
"control",
":",
"Qubit",
",",
"gate",
":",
"Gate",
")",
"->",
"Gate",
":",
"if",
"control",
"in",
"gate",
".",
"qubits",
":",
"raise",
"ValueError",
"(",
"'Gate and control qubits overlap'",
")",
"qubits",
"=",
"[",
"control",
"... | Return a controlled unitary gate. Given a gate acting on K qubits,
return a new gate on K+1 qubits prepended with a control bit. | [
"Return",
"a",
"controlled",
"unitary",
"gate",
".",
"Given",
"a",
"gate",
"acting",
"on",
"K",
"qubits",
"return",
"a",
"new",
"gate",
"on",
"K",
"+",
"1",
"qubits",
"prepended",
"with",
"a",
"control",
"bit",
"."
] | python | train |
xflr6/graphviz | graphviz/lang.py | https://github.com/xflr6/graphviz/blob/7376095ef1e47abad7e0b0361b6c9720b706e7a0/graphviz/lang.py#L55-L74 | def quote_edge(identifier):
"""Return DOT edge statement node_id from string, quote if needed.
>>> quote_edge('spam')
'spam'
>>> quote_edge('spam spam:eggs eggs')
'"spam spam":"eggs eggs"'
>>> quote_edge('spam:eggs:s')
'spam:eggs:s'
"""
node, _, rest = identifier.partition(':')
... | [
"def",
"quote_edge",
"(",
"identifier",
")",
":",
"node",
",",
"_",
",",
"rest",
"=",
"identifier",
".",
"partition",
"(",
"':'",
")",
"parts",
"=",
"[",
"quote",
"(",
"node",
")",
"]",
"if",
"rest",
":",
"port",
",",
"_",
",",
"compass",
"=",
"r... | Return DOT edge statement node_id from string, quote if needed.
>>> quote_edge('spam')
'spam'
>>> quote_edge('spam spam:eggs eggs')
'"spam spam":"eggs eggs"'
>>> quote_edge('spam:eggs:s')
'spam:eggs:s' | [
"Return",
"DOT",
"edge",
"statement",
"node_id",
"from",
"string",
"quote",
"if",
"needed",
"."
] | python | train |
knipknap/exscript | Exscript/util/daemonize.py | https://github.com/knipknap/exscript/blob/72718eee3e87b345d5a5255be9824e867e42927b/Exscript/util/daemonize.py#L42-L68 | def daemonize():
"""
Forks and daemonizes the current process. Does not automatically track
the process id; to do this, use :class:`Exscript.util.pidutil`.
"""
sys.stdout.flush()
sys.stderr.flush()
# UNIX double-fork magic. We need to fork before any threads are
# created.
pid = os.... | [
"def",
"daemonize",
"(",
")",
":",
"sys",
".",
"stdout",
".",
"flush",
"(",
")",
"sys",
".",
"stderr",
".",
"flush",
"(",
")",
"# UNIX double-fork magic. We need to fork before any threads are",
"# created.",
"pid",
"=",
"os",
".",
"fork",
"(",
")",
"if",
"p... | Forks and daemonizes the current process. Does not automatically track
the process id; to do this, use :class:`Exscript.util.pidutil`. | [
"Forks",
"and",
"daemonizes",
"the",
"current",
"process",
".",
"Does",
"not",
"automatically",
"track",
"the",
"process",
"id",
";",
"to",
"do",
"this",
"use",
":",
"class",
":",
"Exscript",
".",
"util",
".",
"pidutil",
"."
] | python | train |
Yelp/venv-update | pip_faster.py | https://github.com/Yelp/venv-update/blob/6feae7ab09ee870c582b97443cfa8f0dc8626ba7/pip_faster.py#L312-L359 | def trace_requirements(requirements):
"""given an iterable of pip InstallRequirements,
return the set of required packages, given their transitive requirements.
"""
requirements = tuple(pretty_req(r) for r in requirements)
working_set = fresh_working_set()
# breadth-first traversal:
from co... | [
"def",
"trace_requirements",
"(",
"requirements",
")",
":",
"requirements",
"=",
"tuple",
"(",
"pretty_req",
"(",
"r",
")",
"for",
"r",
"in",
"requirements",
")",
"working_set",
"=",
"fresh_working_set",
"(",
")",
"# breadth-first traversal:",
"from",
"collections... | given an iterable of pip InstallRequirements,
return the set of required packages, given their transitive requirements. | [
"given",
"an",
"iterable",
"of",
"pip",
"InstallRequirements",
"return",
"the",
"set",
"of",
"required",
"packages",
"given",
"their",
"transitive",
"requirements",
"."
] | python | train |
saltstack/salt | salt/renderers/pass.py | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/renderers/pass.py#L98-L110 | def _decrypt_object(obj):
'''
Recursively try to find a pass path (string) that can be handed off to pass
'''
if isinstance(obj, six.string_types):
return _fetch_secret(obj)
elif isinstance(obj, dict):
for pass_key, pass_path in six.iteritems(obj):
obj[pass_key] = _decryp... | [
"def",
"_decrypt_object",
"(",
"obj",
")",
":",
"if",
"isinstance",
"(",
"obj",
",",
"six",
".",
"string_types",
")",
":",
"return",
"_fetch_secret",
"(",
"obj",
")",
"elif",
"isinstance",
"(",
"obj",
",",
"dict",
")",
":",
"for",
"pass_key",
",",
"pas... | Recursively try to find a pass path (string) that can be handed off to pass | [
"Recursively",
"try",
"to",
"find",
"a",
"pass",
"path",
"(",
"string",
")",
"that",
"can",
"be",
"handed",
"off",
"to",
"pass"
] | python | train |
totalgood/nlpia | src/nlpia/book_parser.py | https://github.com/totalgood/nlpia/blob/efa01126275e9cd3c3a5151a644f1c798a9ec53f/src/nlpia/book_parser.py#L407-L410 | def filter_lines(input_file, output_file, translate=lambda line: line):
""" Translate all the lines of a single file """
filepath, lines = get_lines([input_file])[0]
return filepath, [(tag, translate(line=line, tag=tag)) for (tag, line) in lines] | [
"def",
"filter_lines",
"(",
"input_file",
",",
"output_file",
",",
"translate",
"=",
"lambda",
"line",
":",
"line",
")",
":",
"filepath",
",",
"lines",
"=",
"get_lines",
"(",
"[",
"input_file",
"]",
")",
"[",
"0",
"]",
"return",
"filepath",
",",
"[",
"... | Translate all the lines of a single file | [
"Translate",
"all",
"the",
"lines",
"of",
"a",
"single",
"file"
] | python | train |
JNRowe/upoints | upoints/cities.py | https://github.com/JNRowe/upoints/blob/1e4b7a53ed2a06cd854523d54c36aabdccea3830/upoints/cities.py#L115-L204 | def import_locations(self, data):
"""Parse `GNU miscfiles`_ cities data files.
``import_locations()`` returns a list containing :class:`City` objects.
It expects data files in the same format that `GNU miscfiles`_
provides, that is::
ID : 1
Type ... | [
"def",
"import_locations",
"(",
"self",
",",
"data",
")",
":",
"self",
".",
"_data",
"=",
"data",
"if",
"hasattr",
"(",
"data",
",",
"'read'",
")",
":",
"data",
"=",
"data",
".",
"read",
"(",
")",
".",
"split",
"(",
"'//\\n'",
")",
"elif",
"isinsta... | Parse `GNU miscfiles`_ cities data files.
``import_locations()`` returns a list containing :class:`City` objects.
It expects data files in the same format that `GNU miscfiles`_
provides, that is::
ID : 1
Type : City
Population : 210700
... | [
"Parse",
"GNU",
"miscfiles",
"_",
"cities",
"data",
"files",
"."
] | python | train |
christophertbrown/bioscripts | ctbBio/rRNA_insertions.py | https://github.com/christophertbrown/bioscripts/blob/83b2566b3a5745437ec651cd6cafddd056846240/ctbBio/rRNA_insertions.py#L318-L330 | def model_length(gene, domain):
"""
get length of model
"""
if gene == '16S':
domain2max = {'E_coli_K12': int(1538), 'bacteria': int(1689), 'archaea': int(1563), 'eukarya': int(2652)}
return domain2max[domain]
elif gene == '23S':
domain2max = {'E_coli_K12': int(2903), 'bacter... | [
"def",
"model_length",
"(",
"gene",
",",
"domain",
")",
":",
"if",
"gene",
"==",
"'16S'",
":",
"domain2max",
"=",
"{",
"'E_coli_K12'",
":",
"int",
"(",
"1538",
")",
",",
"'bacteria'",
":",
"int",
"(",
"1689",
")",
",",
"'archaea'",
":",
"int",
"(",
... | get length of model | [
"get",
"length",
"of",
"model"
] | python | train |
partofthething/ace | ace/validation/validate_smoothers.py | https://github.com/partofthething/ace/blob/1593a49f3c2e845514323e9c36ee253fe77bac3c/ace/validation/validate_smoothers.py#L118-L125 | def run_freidman_supsmu(x, y, bass_enhancement=0.0):
"""Run the FORTRAN supersmoother."""
N = len(x)
weight = numpy.ones(N)
results = numpy.zeros(N)
flags = numpy.zeros((N, 7))
mace.supsmu(x, y, weight, 1, 0.0, bass_enhancement, results, flags)
return results | [
"def",
"run_freidman_supsmu",
"(",
"x",
",",
"y",
",",
"bass_enhancement",
"=",
"0.0",
")",
":",
"N",
"=",
"len",
"(",
"x",
")",
"weight",
"=",
"numpy",
".",
"ones",
"(",
"N",
")",
"results",
"=",
"numpy",
".",
"zeros",
"(",
"N",
")",
"flags",
"=... | Run the FORTRAN supersmoother. | [
"Run",
"the",
"FORTRAN",
"supersmoother",
"."
] | python | train |
dylanaraps/pywal | pywal/sequences.py | https://github.com/dylanaraps/pywal/blob/c823e3c9dbd0100ca09caf824e77d296685a1c1e/pywal/sequences.py#L12-L20 | def set_special(index, color, iterm_name="h", alpha=100):
"""Convert a hex color to a special sequence."""
if OS == "Darwin" and iterm_name:
return "\033]P%s%s\033\\" % (iterm_name, color.strip("#"))
if index in [11, 708] and alpha != "100":
return "\033]%s;[%s]%s\033\\" % (index, alpha, co... | [
"def",
"set_special",
"(",
"index",
",",
"color",
",",
"iterm_name",
"=",
"\"h\"",
",",
"alpha",
"=",
"100",
")",
":",
"if",
"OS",
"==",
"\"Darwin\"",
"and",
"iterm_name",
":",
"return",
"\"\\033]P%s%s\\033\\\\\"",
"%",
"(",
"iterm_name",
",",
"color",
"."... | Convert a hex color to a special sequence. | [
"Convert",
"a",
"hex",
"color",
"to",
"a",
"special",
"sequence",
"."
] | python | train |
boriel/zxbasic | basic.py | https://github.com/boriel/zxbasic/blob/23b28db10e41117805bdb3c0f78543590853b132/basic.py#L143-L158 | def sentence_bytes(self, sentence):
""" Return bytes of a sentence.
This is a very simple parser. Sentence is a list of strings and numbers.
1st element of sentence MUST match a token.
"""
result = [TOKENS[sentence[0]]]
for i in sentence[1:]: # Remaining bytes
... | [
"def",
"sentence_bytes",
"(",
"self",
",",
"sentence",
")",
":",
"result",
"=",
"[",
"TOKENS",
"[",
"sentence",
"[",
"0",
"]",
"]",
"]",
"for",
"i",
"in",
"sentence",
"[",
"1",
":",
"]",
":",
"# Remaining bytes",
"if",
"isinstance",
"(",
"i",
",",
... | Return bytes of a sentence.
This is a very simple parser. Sentence is a list of strings and numbers.
1st element of sentence MUST match a token. | [
"Return",
"bytes",
"of",
"a",
"sentence",
".",
"This",
"is",
"a",
"very",
"simple",
"parser",
".",
"Sentence",
"is",
"a",
"list",
"of",
"strings",
"and",
"numbers",
".",
"1st",
"element",
"of",
"sentence",
"MUST",
"match",
"a",
"token",
"."
] | python | train |
PmagPy/PmagPy | pmagpy/builder2.py | https://github.com/PmagPy/PmagPy/blob/c7984f8809bf40fe112e53dcc311a33293b62d0b/pmagpy/builder2.py#L595-L707 | def get_magic_info(self, child_type, parent_type=None, attr='er',
filename=None, sort_by_file_type=False):
"""
Read er_*.txt or pmag_*.txt file.
If no filename is provided, use er_* or pmag_* file in WD.
If sort_by_file_type, use file header to determine child, par... | [
"def",
"get_magic_info",
"(",
"self",
",",
"child_type",
",",
"parent_type",
"=",
"None",
",",
"attr",
"=",
"'er'",
",",
"filename",
"=",
"None",
",",
"sort_by_file_type",
"=",
"False",
")",
":",
"parent",
"=",
"''",
"grandparent_type",
"=",
"None",
"magic... | Read er_*.txt or pmag_*.txt file.
If no filename is provided, use er_* or pmag_* file in WD.
If sort_by_file_type, use file header to determine child, parent types,
instead of passing those in as arguments.
Once file is open, parse information into dictionaries for each item.
If ... | [
"Read",
"er_",
"*",
".",
"txt",
"or",
"pmag_",
"*",
".",
"txt",
"file",
".",
"If",
"no",
"filename",
"is",
"provided",
"use",
"er_",
"*",
"or",
"pmag_",
"*",
"file",
"in",
"WD",
".",
"If",
"sort_by_file_type",
"use",
"file",
"header",
"to",
"determin... | python | train |
apache/incubator-mxnet | python/mxnet/ndarray/ndarray.py | https://github.com/apache/incubator-mxnet/blob/1af29e9c060a4c7d60eeaacba32afdb9a7775ba7/python/mxnet/ndarray/ndarray.py#L2560-L2610 | def arange(start, stop=None, step=1.0, repeat=1, infer_range=None, ctx=None, dtype=mx_real_t):
"""Returns evenly spaced values within a given interval.
Values are generated within the half-open interval [`start`, `stop`). In other
words, the interval includes `start` but excludes `stop`. The function is
... | [
"def",
"arange",
"(",
"start",
",",
"stop",
"=",
"None",
",",
"step",
"=",
"1.0",
",",
"repeat",
"=",
"1",
",",
"infer_range",
"=",
"None",
",",
"ctx",
"=",
"None",
",",
"dtype",
"=",
"mx_real_t",
")",
":",
"if",
"infer_range",
"is",
"not",
"None",... | Returns evenly spaced values within a given interval.
Values are generated within the half-open interval [`start`, `stop`). In other
words, the interval includes `start` but excludes `stop`. The function is
similar to the built-in Python function `range` and to `numpy.arange`,
but returns an `NDArray`.... | [
"Returns",
"evenly",
"spaced",
"values",
"within",
"a",
"given",
"interval",
"."
] | python | train |
AmesCornish/buttersink | buttersink/ButterStore.py | https://github.com/AmesCornish/buttersink/blob/5cc37e30d9f8071fcf3497dca8b8a91b910321ea/buttersink/ButterStore.py#L335-L342 | def deletePartials(self, dryrun=False):
""" Delete any old partial uploads/downloads in path. """
for (vol, path) in self.extraVolumes.items():
if not path.endswith(".part"):
continue
if self._skipDryRun(logger, 'INFO', dryrun=dryrun)("Delete subvolume %s", path):... | [
"def",
"deletePartials",
"(",
"self",
",",
"dryrun",
"=",
"False",
")",
":",
"for",
"(",
"vol",
",",
"path",
")",
"in",
"self",
".",
"extraVolumes",
".",
"items",
"(",
")",
":",
"if",
"not",
"path",
".",
"endswith",
"(",
"\".part\"",
")",
":",
"con... | Delete any old partial uploads/downloads in path. | [
"Delete",
"any",
"old",
"partial",
"uploads",
"/",
"downloads",
"in",
"path",
"."
] | python | train |
redodo/formats | formats/banks.py | https://github.com/redodo/formats/blob/5bc7a79a2c93ef895534edbbf83f1efe2f62e081/formats/banks.py#L85-L96 | def composer(self, type, **meta):
"""Registers the decorated method as the composer of a format.
:param type: The unique name of the format
:param meta: The extra information associated with the format
"""
def decorator(f):
self.register_composer(type, f)
... | [
"def",
"composer",
"(",
"self",
",",
"type",
",",
"*",
"*",
"meta",
")",
":",
"def",
"decorator",
"(",
"f",
")",
":",
"self",
".",
"register_composer",
"(",
"type",
",",
"f",
")",
"if",
"meta",
":",
"self",
".",
"register_meta",
"(",
"type",
",",
... | Registers the decorated method as the composer of a format.
:param type: The unique name of the format
:param meta: The extra information associated with the format | [
"Registers",
"the",
"decorated",
"method",
"as",
"the",
"composer",
"of",
"a",
"format",
"."
] | python | train |
eaton-lab/toytree | toytree/Toytree.py | https://github.com/eaton-lab/toytree/blob/0347ed2098acc5f707fadf52a0ecd411a6d1859c/toytree/Toytree.py#L363-L386 | def get_tip_labels(self, idx=None):
"""
Returns tip labels in the order they will be plotted on the tree, i.e.,
starting from zero axis and counting up by units of 1 (bottom to top
in right-facing trees; left to right in down-facing). If 'idx' is
indicated then a list of tip la... | [
"def",
"get_tip_labels",
"(",
"self",
",",
"idx",
"=",
"None",
")",
":",
"if",
"not",
"idx",
":",
"return",
"self",
".",
"treenode",
".",
"get_leaf_names",
"(",
")",
"[",
":",
":",
"-",
"1",
"]",
"else",
":",
"treenode",
"=",
"self",
".",
"treenode... | Returns tip labels in the order they will be plotted on the tree, i.e.,
starting from zero axis and counting up by units of 1 (bottom to top
in right-facing trees; left to right in down-facing). If 'idx' is
indicated then a list of tip labels descended from that node will be
returned,... | [
"Returns",
"tip",
"labels",
"in",
"the",
"order",
"they",
"will",
"be",
"plotted",
"on",
"the",
"tree",
"i",
".",
"e",
".",
"starting",
"from",
"zero",
"axis",
"and",
"counting",
"up",
"by",
"units",
"of",
"1",
"(",
"bottom",
"to",
"top",
"in",
"righ... | python | train |
nerdvegas/rez | src/rez/vendor/sortedcontainers/sortedset.py | https://github.com/nerdvegas/rez/blob/1d3b846d53b5b5404edfe8ddb9083f9ceec8c5e7/src/rez/vendor/sortedcontainers/sortedset.py#L248-L257 | def intersection_update(self, *iterables):
"""
Update the set, keeping only elements found in it and all *iterables*.
"""
_set = self._set
_list = self._list
_set.intersection_update(*iterables)
_list.clear()
_list.update(_set)
return self | [
"def",
"intersection_update",
"(",
"self",
",",
"*",
"iterables",
")",
":",
"_set",
"=",
"self",
".",
"_set",
"_list",
"=",
"self",
".",
"_list",
"_set",
".",
"intersection_update",
"(",
"*",
"iterables",
")",
"_list",
".",
"clear",
"(",
")",
"_list",
... | Update the set, keeping only elements found in it and all *iterables*. | [
"Update",
"the",
"set",
"keeping",
"only",
"elements",
"found",
"in",
"it",
"and",
"all",
"*",
"iterables",
"*",
"."
] | python | train |
Contraz/demosys-py | demosys/timers/rocketmusic.py | https://github.com/Contraz/demosys-py/blob/6466128a3029c4d09631420ccce73024025bd5b6/demosys/timers/rocketmusic.py#L13-L17 | def start(self):
"""Start the timer"""
self.music.start()
if not self.start_paused:
self.rocket.start() | [
"def",
"start",
"(",
"self",
")",
":",
"self",
".",
"music",
".",
"start",
"(",
")",
"if",
"not",
"self",
".",
"start_paused",
":",
"self",
".",
"rocket",
".",
"start",
"(",
")"
] | Start the timer | [
"Start",
"the",
"timer"
] | python | valid |
trailofbits/manticore | scripts/verify.py | https://github.com/trailofbits/manticore/blob/54c5a15b1119c523ae54c09972413e8b97f11629/scripts/verify.py#L145-L169 | def initialize(state):
"""
Synchronize the stack and register state (manticore->qemu)
"""
logger.debug(f"Copying {stack_top - state.cpu.SP} bytes in the stack..")
stack_bottom = min(state.cpu.SP, gdb.getR('SP'))
for address in range(stack_bottom, stack_top):
b = state.cpu.read_int(addres... | [
"def",
"initialize",
"(",
"state",
")",
":",
"logger",
".",
"debug",
"(",
"f\"Copying {stack_top - state.cpu.SP} bytes in the stack..\"",
")",
"stack_bottom",
"=",
"min",
"(",
"state",
".",
"cpu",
".",
"SP",
",",
"gdb",
".",
"getR",
"(",
"'SP'",
")",
")",
"f... | Synchronize the stack and register state (manticore->qemu) | [
"Synchronize",
"the",
"stack",
"and",
"register",
"state",
"(",
"manticore",
"-",
">",
"qemu",
")"
] | python | valid |
berdario/pew | pew/pew.py | https://github.com/berdario/pew/blob/37d9ff79342336b8ef6437d9a551008be07afe9b/pew/pew.py#L606-L623 | def mktmpenv_cmd(argv):
"""Create a temporary virtualenv."""
parser = mkvirtualenv_argparser()
env = '.'
while (workon_home / env).exists():
env = hex(random.getrandbits(64))[2:-1]
args, rest = parser.parse_known_args(argv)
mkvirtualenv(env, args.python, args.packages, requirements=arg... | [
"def",
"mktmpenv_cmd",
"(",
"argv",
")",
":",
"parser",
"=",
"mkvirtualenv_argparser",
"(",
")",
"env",
"=",
"'.'",
"while",
"(",
"workon_home",
"/",
"env",
")",
".",
"exists",
"(",
")",
":",
"env",
"=",
"hex",
"(",
"random",
".",
"getrandbits",
"(",
... | Create a temporary virtualenv. | [
"Create",
"a",
"temporary",
"virtualenv",
"."
] | python | train |
AkihikoITOH/capybara | capybara/virtualenv/lib/python2.7/site-packages/pip/_vendor/_markerlib/markers.py | https://github.com/AkihikoITOH/capybara/blob/e86c2173ea386654f4ae061148e8fbe3f25e715c/capybara/virtualenv/lib/python2.7/site-packages/pip/_vendor/_markerlib/markers.py#L94-L116 | def compile(marker):
"""Return compiled marker as a function accepting an environment dict."""
try:
return _cache[marker]
except KeyError:
pass
if not marker.strip():
def marker_fn(environment=None, override=None):
""""""
return True
else:
comp... | [
"def",
"compile",
"(",
"marker",
")",
":",
"try",
":",
"return",
"_cache",
"[",
"marker",
"]",
"except",
"KeyError",
":",
"pass",
"if",
"not",
"marker",
".",
"strip",
"(",
")",
":",
"def",
"marker_fn",
"(",
"environment",
"=",
"None",
",",
"override",
... | Return compiled marker as a function accepting an environment dict. | [
"Return",
"compiled",
"marker",
"as",
"a",
"function",
"accepting",
"an",
"environment",
"dict",
"."
] | python | test |
tensorflow/tensor2tensor | tensor2tensor/trax/models/neural_gpu.py | https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/trax/models/neural_gpu.py#L33-L47 | def DiagonalGate(x, params, **kwargs):
"""Split channels in 3 parts. Shifts 1st and 3rd sections to left/right."""
del params
del kwargs
# x : [batch, 1, length, depth]
x = np.pad(
x, [(0, 0), (0, 0), (1, 1), (0, 0)], mode='constant', constant_values=0.0)
depth = x.shape[-1] // 3
assert 3 * depth ==... | [
"def",
"DiagonalGate",
"(",
"x",
",",
"params",
",",
"*",
"*",
"kwargs",
")",
":",
"del",
"params",
"del",
"kwargs",
"# x : [batch, 1, length, depth]",
"x",
"=",
"np",
".",
"pad",
"(",
"x",
",",
"[",
"(",
"0",
",",
"0",
")",
",",
"(",
"0",
",",
"... | Split channels in 3 parts. Shifts 1st and 3rd sections to left/right. | [
"Split",
"channels",
"in",
"3",
"parts",
".",
"Shifts",
"1st",
"and",
"3rd",
"sections",
"to",
"left",
"/",
"right",
"."
] | python | train |
chrislit/abydos | abydos/phonetic/_fuzzy_soundex.py | https://github.com/chrislit/abydos/blob/165466b3ff6afd8024a4c8660421b0c4e7773db9/abydos/phonetic/_fuzzy_soundex.py#L54-L159 | def encode(self, word, max_length=5, zero_pad=True):
"""Return the Fuzzy Soundex code for a word.
Parameters
----------
word : str
The word to transform
max_length : int
The length of the code returned (defaults to 4)
zero_pad : bool
P... | [
"def",
"encode",
"(",
"self",
",",
"word",
",",
"max_length",
"=",
"5",
",",
"zero_pad",
"=",
"True",
")",
":",
"word",
"=",
"unicode_normalize",
"(",
"'NFKD'",
",",
"text_type",
"(",
"word",
".",
"upper",
"(",
")",
")",
")",
"word",
"=",
"word",
"... | Return the Fuzzy Soundex code for a word.
Parameters
----------
word : str
The word to transform
max_length : int
The length of the code returned (defaults to 4)
zero_pad : bool
Pad the end of the return value with 0s to achieve a max_length
... | [
"Return",
"the",
"Fuzzy",
"Soundex",
"code",
"for",
"a",
"word",
"."
] | python | valid |
h2oai/h2o-3 | h2o-py/h2o/estimators/glm.py | https://github.com/h2oai/h2o-3/blob/dd62aaa1e7f680a8b16ee14bc66b0fb5195c2ad8/h2o-py/h2o/estimators/glm.py#L860-L876 | def getGLMRegularizationPath(model):
"""
Extract full regularization path explored during lambda search from glm model.
:param model: source lambda search model
"""
x = h2o.api("GET /3/GetGLMRegPath", data={"model": model._model_json["model_id"]["name"]})
ns = x.pop("coe... | [
"def",
"getGLMRegularizationPath",
"(",
"model",
")",
":",
"x",
"=",
"h2o",
".",
"api",
"(",
"\"GET /3/GetGLMRegPath\"",
",",
"data",
"=",
"{",
"\"model\"",
":",
"model",
".",
"_model_json",
"[",
"\"model_id\"",
"]",
"[",
"\"name\"",
"]",
"}",
")",
"ns",
... | Extract full regularization path explored during lambda search from glm model.
:param model: source lambda search model | [
"Extract",
"full",
"regularization",
"path",
"explored",
"during",
"lambda",
"search",
"from",
"glm",
"model",
"."
] | python | test |
viralogic/py-enumerable | py_linq/py_linq3.py | https://github.com/viralogic/py-enumerable/blob/63363649bccef223379e1e87056747240c83aa9d/py_linq/py_linq3.py#L259-L265 | def select_many(self, func=lambda x: x):
"""
Flattens an iterable of iterables returning a new Enumerable
:param func: selector as lambda expression
:return: new Enumerable object
"""
return Enumerable3(itertools.chain.from_iterable(self.select(func))) | [
"def",
"select_many",
"(",
"self",
",",
"func",
"=",
"lambda",
"x",
":",
"x",
")",
":",
"return",
"Enumerable3",
"(",
"itertools",
".",
"chain",
".",
"from_iterable",
"(",
"self",
".",
"select",
"(",
"func",
")",
")",
")"
] | Flattens an iterable of iterables returning a new Enumerable
:param func: selector as lambda expression
:return: new Enumerable object | [
"Flattens",
"an",
"iterable",
"of",
"iterables",
"returning",
"a",
"new",
"Enumerable",
":",
"param",
"func",
":",
"selector",
"as",
"lambda",
"expression",
":",
"return",
":",
"new",
"Enumerable",
"object"
] | python | train |
AlejandroFrias/case-conversion | case_conversion/case_parse.py | https://github.com/AlejandroFrias/case-conversion/blob/79ebce1403fbdac949b2da21b8f6fbe3234ddb31/case_conversion/case_parse.py#L150-L164 | def _sanitize_acronyms(unsafe_acronyms):
"""
Check acronyms against regex.
Normalize valid acronyms to upper-case.
If an invalid acronym is encountered raise InvalidAcronymError.
"""
valid_acronym = regex.compile(u'^[\p{Ll}\p{Lu}\p{Nd}]+$')
acronyms = []
for a in unsafe_acronyms:
... | [
"def",
"_sanitize_acronyms",
"(",
"unsafe_acronyms",
")",
":",
"valid_acronym",
"=",
"regex",
".",
"compile",
"(",
"u'^[\\p{Ll}\\p{Lu}\\p{Nd}]+$'",
")",
"acronyms",
"=",
"[",
"]",
"for",
"a",
"in",
"unsafe_acronyms",
":",
"if",
"valid_acronym",
".",
"match",
"("... | Check acronyms against regex.
Normalize valid acronyms to upper-case.
If an invalid acronym is encountered raise InvalidAcronymError. | [
"Check",
"acronyms",
"against",
"regex",
"."
] | python | train |
genialis/genesis-pyapi | genesis/project.py | https://github.com/genialis/genesis-pyapi/blob/dfe9bcc8b332a8b9873db4ab9994b0cc10eb209a/genesis/project.py#L17-L20 | def data_types(self):
"""Return a list of data types."""
data = self.gencloud.project_data(self.id)
return sorted(set(d.type for d in data)) | [
"def",
"data_types",
"(",
"self",
")",
":",
"data",
"=",
"self",
".",
"gencloud",
".",
"project_data",
"(",
"self",
".",
"id",
")",
"return",
"sorted",
"(",
"set",
"(",
"d",
".",
"type",
"for",
"d",
"in",
"data",
")",
")"
] | Return a list of data types. | [
"Return",
"a",
"list",
"of",
"data",
"types",
"."
] | python | test |
gwastro/pycbc | pycbc/distributions/power_law.py | https://github.com/gwastro/pycbc/blob/7a64cdd104d263f1b6ea0b01e6841837d05a4cb3/pycbc/distributions/power_law.py#L214-L238 | def from_config(cls, cp, section, variable_args):
"""Returns a distribution based on a configuration file. The parameters
for the distribution are retrieved from the section titled
"[`section`-`variable_args`]" in the config file.
Parameters
----------
cp : pycbc.workflo... | [
"def",
"from_config",
"(",
"cls",
",",
"cp",
",",
"section",
",",
"variable_args",
")",
":",
"return",
"super",
"(",
"UniformPowerLaw",
",",
"cls",
")",
".",
"from_config",
"(",
"cp",
",",
"section",
",",
"variable_args",
",",
"bounds_required",
"=",
"True... | Returns a distribution based on a configuration file. The parameters
for the distribution are retrieved from the section titled
"[`section`-`variable_args`]" in the config file.
Parameters
----------
cp : pycbc.workflow.WorkflowConfigParser
A parsed configuration fil... | [
"Returns",
"a",
"distribution",
"based",
"on",
"a",
"configuration",
"file",
".",
"The",
"parameters",
"for",
"the",
"distribution",
"are",
"retrieved",
"from",
"the",
"section",
"titled",
"[",
"section",
"-",
"variable_args",
"]",
"in",
"the",
"config",
"file... | python | train |
miguelgrinberg/python-socketio | socketio/asyncio_manager.py | https://github.com/miguelgrinberg/python-socketio/blob/c0c1bf8d21e3597389b18938550a0724dd9676b7/socketio/asyncio_manager.py#L8-L28 | async def emit(self, event, data, namespace, room=None, skip_sid=None,
callback=None, **kwargs):
"""Emit a message to a single client, a room, or all the clients
connected to the namespace.
Note: this method is a coroutine.
"""
if namespace not in self.rooms o... | [
"async",
"def",
"emit",
"(",
"self",
",",
"event",
",",
"data",
",",
"namespace",
",",
"room",
"=",
"None",
",",
"skip_sid",
"=",
"None",
",",
"callback",
"=",
"None",
",",
"*",
"*",
"kwargs",
")",
":",
"if",
"namespace",
"not",
"in",
"self",
".",
... | Emit a message to a single client, a room, or all the clients
connected to the namespace.
Note: this method is a coroutine. | [
"Emit",
"a",
"message",
"to",
"a",
"single",
"client",
"a",
"room",
"or",
"all",
"the",
"clients",
"connected",
"to",
"the",
"namespace",
"."
] | python | train |
coursera-dl/coursera-dl | coursera/api.py | https://github.com/coursera-dl/coursera-dl/blob/9b434bcf3c4011bf3181429fe674633ae5fb7d4d/coursera/api.py#L909-L933 | def _normalize_assets(self, assets):
"""
Perform asset normalization. For some reason, assets that are sometimes
present in lectures, have "@1" at the end of their id. Such "uncut"
asset id when fed to OPENCOURSE_ASSETS_URL results in error that says:
"Routing error: 'get-all' no... | [
"def",
"_normalize_assets",
"(",
"self",
",",
"assets",
")",
":",
"new_assets",
"=",
"[",
"]",
"for",
"asset",
"in",
"assets",
":",
"# For example: giAxucdaEeWJTQ5WTi8YJQ@1",
"if",
"len",
"(",
"asset",
")",
"==",
"24",
":",
"# Turn it into: giAxucdaEeWJTQ5WTi8YJQ"... | Perform asset normalization. For some reason, assets that are sometimes
present in lectures, have "@1" at the end of their id. Such "uncut"
asset id when fed to OPENCOURSE_ASSETS_URL results in error that says:
"Routing error: 'get-all' not implemented". To avoid that, the last
two chara... | [
"Perform",
"asset",
"normalization",
".",
"For",
"some",
"reason",
"assets",
"that",
"are",
"sometimes",
"present",
"in",
"lectures",
"have",
"@1",
"at",
"the",
"end",
"of",
"their",
"id",
".",
"Such",
"uncut",
"asset",
"id",
"when",
"fed",
"to",
"OPENCOUR... | python | train |
maximkulkin/lollipop | lollipop/types.py | https://github.com/maximkulkin/lollipop/blob/042e8a24508cc3b28630863253c38ffbfc52c882/lollipop/types.py#L1767-L1812 | def validated_type(base_type, name=None, validate=None):
"""Convenient way to create a new type by adding validation to existing type.
Example: ::
Ipv4Address = validated_type(
String, 'Ipv4Address',
# regexp simplified for demo purposes
Regexp('^\d+\.\d+\.\d+\.\d+$... | [
"def",
"validated_type",
"(",
"base_type",
",",
"name",
"=",
"None",
",",
"validate",
"=",
"None",
")",
":",
"if",
"validate",
"is",
"None",
":",
"validate",
"=",
"[",
"]",
"if",
"not",
"is_sequence",
"(",
"validate",
")",
":",
"validate",
"=",
"[",
... | Convenient way to create a new type by adding validation to existing type.
Example: ::
Ipv4Address = validated_type(
String, 'Ipv4Address',
# regexp simplified for demo purposes
Regexp('^\d+\.\d+\.\d+\.\d+$', error='Invalid IP address')
)
Percentage = v... | [
"Convenient",
"way",
"to",
"create",
"a",
"new",
"type",
"by",
"adding",
"validation",
"to",
"existing",
"type",
"."
] | python | train |
AnalogJ/lexicon | lexicon/providers/hetzner.py | https://github.com/AnalogJ/lexicon/blob/9330b871988753cad44fe2876a217b4c67b1fa0e/lexicon/providers/hetzner.py#L174-L205 | def _create_record(self, rtype, name, content):
"""
Connects to Hetzner account, adds a new record to the zone and returns a
boolean, if creation was successful or not. Needed record rtype, name and
content for record to create.
"""
with self._session(self.domain, self.do... | [
"def",
"_create_record",
"(",
"self",
",",
"rtype",
",",
"name",
",",
"content",
")",
":",
"with",
"self",
".",
"_session",
"(",
"self",
".",
"domain",
",",
"self",
".",
"domain_id",
")",
"as",
"ddata",
":",
"# Validate method parameters",
"if",
"not",
"... | Connects to Hetzner account, adds a new record to the zone and returns a
boolean, if creation was successful or not. Needed record rtype, name and
content for record to create. | [
"Connects",
"to",
"Hetzner",
"account",
"adds",
"a",
"new",
"record",
"to",
"the",
"zone",
"and",
"returns",
"a",
"boolean",
"if",
"creation",
"was",
"successful",
"or",
"not",
".",
"Needed",
"record",
"rtype",
"name",
"and",
"content",
"for",
"record",
"t... | python | train |
cloud9ers/gurumate | environment/lib/python2.7/site-packages/IPython/frontend/consoleapp.py | https://github.com/cloud9ers/gurumate/blob/075dc74d1ee62a8c6b7a8bf2b271364f01629d1e/environment/lib/python2.7/site-packages/IPython/frontend/consoleapp.py#L202-L246 | def init_connection_file(self):
"""find the connection file, and load the info if found.
The current working directory and the current profile's security
directory will be searched for the file if it is not given by
absolute path.
When attempting to connect to a... | [
"def",
"init_connection_file",
"(",
"self",
")",
":",
"if",
"self",
".",
"existing",
":",
"try",
":",
"cf",
"=",
"find_connection_file",
"(",
"self",
".",
"existing",
")",
"except",
"Exception",
":",
"self",
".",
"log",
".",
"critical",
"(",
"\"Could not f... | find the connection file, and load the info if found.
The current working directory and the current profile's security
directory will be searched for the file if it is not given by
absolute path.
When attempting to connect to an existing kernel and the `--existing`
... | [
"find",
"the",
"connection",
"file",
"and",
"load",
"the",
"info",
"if",
"found",
".",
"The",
"current",
"working",
"directory",
"and",
"the",
"current",
"profile",
"s",
"security",
"directory",
"will",
"be",
"searched",
"for",
"the",
"file",
"if",
"it",
"... | python | test |
klen/muffin-peewee | muffin_peewee/mpeewee.py | https://github.com/klen/muffin-peewee/blob/8e893e3ea1dfc82fbcfc6efe784308c8d4e2852e/muffin_peewee/mpeewee.py#L123-L126 | def init_async(self, loop):
"""Initialize self."""
super(PooledAIODatabase, self).init_async(loop)
self._waiters = collections.deque() | [
"def",
"init_async",
"(",
"self",
",",
"loop",
")",
":",
"super",
"(",
"PooledAIODatabase",
",",
"self",
")",
".",
"init_async",
"(",
"loop",
")",
"self",
".",
"_waiters",
"=",
"collections",
".",
"deque",
"(",
")"
] | Initialize self. | [
"Initialize",
"self",
"."
] | python | valid |
BD2KGenomics/toil-scripts | src/toil_scripts/bwa_alignment/bwa_alignment.py | https://github.com/BD2KGenomics/toil-scripts/blob/f878d863defcdccaabb7fe06f991451b7a198fb7/src/toil_scripts/bwa_alignment/bwa_alignment.py#L215-L292 | def main():
"""
Computational Genomics Lab, Genomics Institute, UC Santa Cruz
Toil BWA pipeline
Alignment of fastq reads via BWA-kit
General usage:
1. Type "toil-bwa generate" to create an editable manifest and config in the current working directory.
2. Parameterize the pipeline by editin... | [
"def",
"main",
"(",
")",
":",
"# Define Parser object and add to Toil",
"parser",
"=",
"argparse",
".",
"ArgumentParser",
"(",
"description",
"=",
"main",
".",
"__doc__",
",",
"formatter_class",
"=",
"argparse",
".",
"RawTextHelpFormatter",
")",
"subparsers",
"=",
... | Computational Genomics Lab, Genomics Institute, UC Santa Cruz
Toil BWA pipeline
Alignment of fastq reads via BWA-kit
General usage:
1. Type "toil-bwa generate" to create an editable manifest and config in the current working directory.
2. Parameterize the pipeline by editing the config.
3. Fil... | [
"Computational",
"Genomics",
"Lab",
"Genomics",
"Institute",
"UC",
"Santa",
"Cruz",
"Toil",
"BWA",
"pipeline"
] | python | train |
not-na/peng3d | peng3d/keybind.py | https://github.com/not-na/peng3d/blob/1151be665b26cc8a479f6307086ba919e4d32d85/peng3d/keybind.py#L129-L143 | def changeKeybind(self,kbname,combo):
"""
Changes a keybind of a specific keybindname.
:param str kbname: Same as kbname of :py:meth:`add()`
:param str combo: New key combination
"""
for key,value in self.keybinds.items():
if kbname in value:
... | [
"def",
"changeKeybind",
"(",
"self",
",",
"kbname",
",",
"combo",
")",
":",
"for",
"key",
",",
"value",
"in",
"self",
".",
"keybinds",
".",
"items",
"(",
")",
":",
"if",
"kbname",
"in",
"value",
":",
"del",
"value",
"[",
"value",
".",
"index",
"(",... | Changes a keybind of a specific keybindname.
:param str kbname: Same as kbname of :py:meth:`add()`
:param str combo: New key combination | [
"Changes",
"a",
"keybind",
"of",
"a",
"specific",
"keybindname",
".",
":",
"param",
"str",
"kbname",
":",
"Same",
"as",
"kbname",
"of",
":",
"py",
":",
"meth",
":",
"add",
"()",
":",
"param",
"str",
"combo",
":",
"New",
"key",
"combination"
] | python | test |
tulir/mautrix-python | mautrix_appservice/intent_api.py | https://github.com/tulir/mautrix-python/blob/21bb0870e4103dd03ecc61396ce02adb9301f382/mautrix_appservice/intent_api.py#L404-L420 | async def download_file(self, url: str) -> bytes:
"""
Download a file from the content repository. See also: `API reference`_
Args:
url: The MXC URI to download.
Returns:
The raw downloaded data.
.. _API reference:
https://matrix.org/docs/spe... | [
"async",
"def",
"download_file",
"(",
"self",
",",
"url",
":",
"str",
")",
"->",
"bytes",
":",
"await",
"self",
".",
"ensure_registered",
"(",
")",
"url",
"=",
"self",
".",
"client",
".",
"get_download_url",
"(",
"url",
")",
"async",
"with",
"self",
".... | Download a file from the content repository. See also: `API reference`_
Args:
url: The MXC URI to download.
Returns:
The raw downloaded data.
.. _API reference:
https://matrix.org/docs/spec/client_server/r0.3.0.html#get-matrix-media-r0-download-servername-me... | [
"Download",
"a",
"file",
"from",
"the",
"content",
"repository",
".",
"See",
"also",
":",
"API",
"reference",
"_"
] | python | train |
angr/angr | angr/keyed_region.py | https://github.com/angr/angr/blob/4e2f97d56af5419ee73bdb30482c8dd8ff5f3e40/angr/keyed_region.py#L307-L319 | def get_objects_by_offset(self, start):
"""
Find objects covering the given region offset.
:param start:
:return:
"""
_, container = self._get_container(start)
if container is None:
return set()
else:
return container.internal_obj... | [
"def",
"get_objects_by_offset",
"(",
"self",
",",
"start",
")",
":",
"_",
",",
"container",
"=",
"self",
".",
"_get_container",
"(",
"start",
")",
"if",
"container",
"is",
"None",
":",
"return",
"set",
"(",
")",
"else",
":",
"return",
"container",
".",
... | Find objects covering the given region offset.
:param start:
:return: | [
"Find",
"objects",
"covering",
"the",
"given",
"region",
"offset",
"."
] | python | train |
sonyxperiadev/pygerrit | pygerrit/rest/__init__.py | https://github.com/sonyxperiadev/pygerrit/blob/756300120b0f4f4af19e0f985566d82bc80b4359/pygerrit/rest/__init__.py#L175-L191 | def review(self, change_id, revision, review):
""" Submit a review.
:arg str change_id: The change ID.
:arg str revision: The revision.
:arg str review: The review details as a :class:`GerritReview`.
:returns:
JSON decoded result.
:raises:
reque... | [
"def",
"review",
"(",
"self",
",",
"change_id",
",",
"revision",
",",
"review",
")",
":",
"endpoint",
"=",
"\"changes/%s/revisions/%s/review\"",
"%",
"(",
"change_id",
",",
"revision",
")",
"self",
".",
"post",
"(",
"endpoint",
",",
"data",
"=",
"str",
"("... | Submit a review.
:arg str change_id: The change ID.
:arg str revision: The revision.
:arg str review: The review details as a :class:`GerritReview`.
:returns:
JSON decoded result.
:raises:
requests.RequestException on timeout or connection error. | [
"Submit",
"a",
"review",
"."
] | python | train |
wummel/linkchecker | linkcheck/logger/__init__.py | https://github.com/wummel/linkchecker/blob/c2ce810c3fb00b895a841a7be6b2e78c64e7b042/linkcheck/logger/__init__.py#L376-L387 | def write_intro (self):
"""Write intro comments."""
self.comment(_("created by %(app)s at %(time)s") %
{"app": configuration.AppName,
"time": strformat.strtime(self.starttime)})
self.comment(_("Get the newest version at %(url)s") %
{'... | [
"def",
"write_intro",
"(",
"self",
")",
":",
"self",
".",
"comment",
"(",
"_",
"(",
"\"created by %(app)s at %(time)s\"",
")",
"%",
"{",
"\"app\"",
":",
"configuration",
".",
"AppName",
",",
"\"time\"",
":",
"strformat",
".",
"strtime",
"(",
"self",
".",
"... | Write intro comments. | [
"Write",
"intro",
"comments",
"."
] | python | train |
kovacsbalu/WazeRouteCalculator | WazeRouteCalculator/WazeRouteCalculator.py | https://github.com/kovacsbalu/WazeRouteCalculator/blob/13ddb064571bb2bc0ceec51b5b317640b2bc3fb2/WazeRouteCalculator/WazeRouteCalculator.py#L82-L86 | def coords_string_parser(self, coords):
"""Pareses the address string into coordinates to match address_to_coords return object"""
lat, lon = coords.split(',')
return {"lat": lat.strip(), "lon": lon.strip(), "bounds": {}} | [
"def",
"coords_string_parser",
"(",
"self",
",",
"coords",
")",
":",
"lat",
",",
"lon",
"=",
"coords",
".",
"split",
"(",
"','",
")",
"return",
"{",
"\"lat\"",
":",
"lat",
".",
"strip",
"(",
")",
",",
"\"lon\"",
":",
"lon",
".",
"strip",
"(",
")",
... | Pareses the address string into coordinates to match address_to_coords return object | [
"Pareses",
"the",
"address",
"string",
"into",
"coordinates",
"to",
"match",
"address_to_coords",
"return",
"object"
] | python | train |
lingfeiwang/findr-python | findr/pij.py | https://github.com/lingfeiwang/findr-python/blob/417f163e658fee6ef311571f7048f96069a0cf1f/findr/pij.py#L606-L648 | def rank_pv(self,dt,dt2,memlimit=-1):
"""Calculates p-values of gene i correlating with gene j by converting log likelihoods into probabilities per A for all B.
dt: numpy.ndarray(nt,ns,dtype=ftype(='=f4' by default)) Gene expression data for A
Entry dt[i,j] is gene i's expression level for sample j.
dt2:numpy.ndar... | [
"def",
"rank_pv",
"(",
"self",
",",
"dt",
",",
"dt2",
",",
"memlimit",
"=",
"-",
"1",
")",
":",
"if",
"self",
".",
"lib",
"is",
"None",
":",
"raise",
"ValueError",
"(",
"\"Not initialized.\"",
")",
"import",
"numpy",
"as",
"np",
"from",
".",
"auto",
... | Calculates p-values of gene i correlating with gene j by converting log likelihoods into probabilities per A for all B.
dt: numpy.ndarray(nt,ns,dtype=ftype(='=f4' by default)) Gene expression data for A
Entry dt[i,j] is gene i's expression level for sample j.
dt2:numpy.ndarray(nt2,ns,dtype=ftype(='=f4' by default))... | [
"Calculates",
"p",
"-",
"values",
"of",
"gene",
"i",
"correlating",
"with",
"gene",
"j",
"by",
"converting",
"log",
"likelihoods",
"into",
"probabilities",
"per",
"A",
"for",
"all",
"B",
".",
"dt",
":",
"numpy",
".",
"ndarray",
"(",
"nt",
"ns",
"dtype",
... | python | train |
bpython/curtsies | curtsies/formatstring.py | https://github.com/bpython/curtsies/blob/223e42b97fbf6c86b479ed4f0963a067333c5a63/curtsies/formatstring.py#L275-L280 | def copy_with_new_str(self, new_str):
"""Copies the current FmtStr's attributes while changing its string."""
# What to do when there are multiple Chunks with conflicting atts?
old_atts = dict((att, value) for bfs in self.chunks
for (att, value) in bfs.atts.items())
r... | [
"def",
"copy_with_new_str",
"(",
"self",
",",
"new_str",
")",
":",
"# What to do when there are multiple Chunks with conflicting atts?",
"old_atts",
"=",
"dict",
"(",
"(",
"att",
",",
"value",
")",
"for",
"bfs",
"in",
"self",
".",
"chunks",
"for",
"(",
"att",
",... | Copies the current FmtStr's attributes while changing its string. | [
"Copies",
"the",
"current",
"FmtStr",
"s",
"attributes",
"while",
"changing",
"its",
"string",
"."
] | python | train |
jxtech/wechatpy | wechatpy/enterprise/client/api/oauth.py | https://github.com/jxtech/wechatpy/blob/4df0da795618c0895a10f1c2cde9e9d5c0a93aaa/wechatpy/enterprise/client/api/oauth.py#L12-L34 | def authorize_url(self, redirect_uri, state=None):
"""
构造网页授权链接
详情请参考
https://work.weixin.qq.com/api/doc#90000/90135/91022
:param redirect_uri: 授权后重定向的回调链接地址
:param state: 重定向后会带上 state 参数
:return: 返回的 JSON 数据包
"""
redirect_uri = six.moves.urllib.... | [
"def",
"authorize_url",
"(",
"self",
",",
"redirect_uri",
",",
"state",
"=",
"None",
")",
":",
"redirect_uri",
"=",
"six",
".",
"moves",
".",
"urllib",
".",
"parse",
".",
"quote",
"(",
"redirect_uri",
",",
"safe",
"=",
"b''",
")",
"url_list",
"=",
"[",... | 构造网页授权链接
详情请参考
https://work.weixin.qq.com/api/doc#90000/90135/91022
:param redirect_uri: 授权后重定向的回调链接地址
:param state: 重定向后会带上 state 参数
:return: 返回的 JSON 数据包 | [
"构造网页授权链接",
"详情请参考",
"https",
":",
"//",
"work",
".",
"weixin",
".",
"qq",
".",
"com",
"/",
"api",
"/",
"doc#90000",
"/",
"90135",
"/",
"91022"
] | python | train |
spyder-ide/spyder | spyder/preferences/shortcuts.py | https://github.com/spyder-ide/spyder/blob/f76836ce1b924bcc4efd3f74f2960d26a4e528e0/spyder/preferences/shortcuts.py#L815-L821 | def next_row(self):
"""Move to next row from currently selected row."""
row = self.currentIndex().row()
rows = self.proxy_model.rowCount()
if row + 1 == rows:
row = -1
self.selectRow(row + 1) | [
"def",
"next_row",
"(",
"self",
")",
":",
"row",
"=",
"self",
".",
"currentIndex",
"(",
")",
".",
"row",
"(",
")",
"rows",
"=",
"self",
".",
"proxy_model",
".",
"rowCount",
"(",
")",
"if",
"row",
"+",
"1",
"==",
"rows",
":",
"row",
"=",
"-",
"1... | Move to next row from currently selected row. | [
"Move",
"to",
"next",
"row",
"from",
"currently",
"selected",
"row",
"."
] | python | train |
twilio/twilio-python | twilio/rest/video/v1/composition/__init__.py | https://github.com/twilio/twilio-python/blob/c867895f55dcc29f522e6e8b8868d0d18483132f/twilio/rest/video/v1/composition/__init__.py#L382-L392 | def _proxy(self):
"""
Generate an instance context for the instance, the context is capable of
performing various actions. All instance actions are proxied to the context
:returns: CompositionContext for this CompositionInstance
:rtype: twilio.rest.video.v1.composition.Composit... | [
"def",
"_proxy",
"(",
"self",
")",
":",
"if",
"self",
".",
"_context",
"is",
"None",
":",
"self",
".",
"_context",
"=",
"CompositionContext",
"(",
"self",
".",
"_version",
",",
"sid",
"=",
"self",
".",
"_solution",
"[",
"'sid'",
"]",
",",
")",
"retur... | Generate an instance context for the instance, the context is capable of
performing various actions. All instance actions are proxied to the context
:returns: CompositionContext for this CompositionInstance
:rtype: twilio.rest.video.v1.composition.CompositionContext | [
"Generate",
"an",
"instance",
"context",
"for",
"the",
"instance",
"the",
"context",
"is",
"capable",
"of",
"performing",
"various",
"actions",
".",
"All",
"instance",
"actions",
"are",
"proxied",
"to",
"the",
"context"
] | python | train |
ultrabug/uhashring | uhashring/ring.py | https://github.com/ultrabug/uhashring/blob/2297471a392e28ed913b3276c2f48d0c01523375/uhashring/ring.py#L232-L235 | def get_points(self):
"""Returns a ketama compatible list of (position, nodename) tuples.
"""
return [(k, self.runtime._ring[k]) for k in self.runtime._keys] | [
"def",
"get_points",
"(",
"self",
")",
":",
"return",
"[",
"(",
"k",
",",
"self",
".",
"runtime",
".",
"_ring",
"[",
"k",
"]",
")",
"for",
"k",
"in",
"self",
".",
"runtime",
".",
"_keys",
"]"
] | Returns a ketama compatible list of (position, nodename) tuples. | [
"Returns",
"a",
"ketama",
"compatible",
"list",
"of",
"(",
"position",
"nodename",
")",
"tuples",
"."
] | python | train |
kiwiz/gkeepapi | gkeepapi/__init__.py | https://github.com/kiwiz/gkeepapi/blob/78aaae8b988b1cf616e3973f7f15d4c6d5e996cc/gkeepapi/__init__.py#L189-L220 | def send(self, **req_kwargs):
"""Send an authenticated request to a Google API.
Automatically retries if the access token has expired.
Args:
**req_kwargs: Arbitrary keyword arguments to pass to Requests.
Return:
dict: The parsed JSON response.
Raises:
... | [
"def",
"send",
"(",
"self",
",",
"*",
"*",
"req_kwargs",
")",
":",
"i",
"=",
"0",
"while",
"True",
":",
"response",
"=",
"self",
".",
"_send",
"(",
"*",
"*",
"req_kwargs",
")",
".",
"json",
"(",
")",
"if",
"'error'",
"not",
"in",
"response",
":",... | Send an authenticated request to a Google API.
Automatically retries if the access token has expired.
Args:
**req_kwargs: Arbitrary keyword arguments to pass to Requests.
Return:
dict: The parsed JSON response.
Raises:
APIException: If the server re... | [
"Send",
"an",
"authenticated",
"request",
"to",
"a",
"Google",
"API",
".",
"Automatically",
"retries",
"if",
"the",
"access",
"token",
"has",
"expired",
"."
] | python | train |
brocade/pynos | pynos/versions/base/interface.py | https://github.com/brocade/pynos/blob/bd8a34e98f322de3fc06750827d8bbc3a0c00380/pynos/versions/base/interface.py#L1789-L1895 | def vrrp_vip(self, **kwargs):
"""Set VRRP VIP.
Args:
int_type (str): Type of interface. (gigabitethernet,
tengigabitethernet, etc).
name (str): Name of interface. (1/0/5, 1/0/10, etc).
vrid (str): VRRPv3 ID.
vip (str): IPv4/IPv6 Virtual IP ... | [
"def",
"vrrp_vip",
"(",
"self",
",",
"*",
"*",
"kwargs",
")",
":",
"int_type",
"=",
"kwargs",
".",
"pop",
"(",
"'int_type'",
")",
".",
"lower",
"(",
")",
"name",
"=",
"kwargs",
".",
"pop",
"(",
"'name'",
")",
"vrid",
"=",
"kwargs",
".",
"pop",
"(... | Set VRRP VIP.
Args:
int_type (str): Type of interface. (gigabitethernet,
tengigabitethernet, etc).
name (str): Name of interface. (1/0/5, 1/0/10, etc).
vrid (str): VRRPv3 ID.
vip (str): IPv4/IPv6 Virtual IP Address.
rbridge_id (str): rb... | [
"Set",
"VRRP",
"VIP",
".",
"Args",
":",
"int_type",
"(",
"str",
")",
":",
"Type",
"of",
"interface",
".",
"(",
"gigabitethernet",
"tengigabitethernet",
"etc",
")",
".",
"name",
"(",
"str",
")",
":",
"Name",
"of",
"interface",
".",
"(",
"1",
"/",
"0",... | python | train |
explosion/spaCy | spacy/cli/package.py | https://github.com/explosion/spaCy/blob/8ee4100f8ffb336886208a1ea827bf4c745e2709/spacy/cli/package.py#L22-L78 | def package(input_dir, output_dir, meta_path=None, create_meta=False, force=False):
"""
Generate Python package for model data, including meta and required
installation files. A new directory will be created in the specified
output directory, and model data will be copied over. If --create-meta is
s... | [
"def",
"package",
"(",
"input_dir",
",",
"output_dir",
",",
"meta_path",
"=",
"None",
",",
"create_meta",
"=",
"False",
",",
"force",
"=",
"False",
")",
":",
"msg",
"=",
"Printer",
"(",
")",
"input_path",
"=",
"util",
".",
"ensure_path",
"(",
"input_dir"... | Generate Python package for model data, including meta and required
installation files. A new directory will be created in the specified
output directory, and model data will be copied over. If --create-meta is
set and a meta.json already exists in the output directory, the existing
values will be used ... | [
"Generate",
"Python",
"package",
"for",
"model",
"data",
"including",
"meta",
"and",
"required",
"installation",
"files",
".",
"A",
"new",
"directory",
"will",
"be",
"created",
"in",
"the",
"specified",
"output",
"directory",
"and",
"model",
"data",
"will",
"b... | python | train |
pip-services3-python/pip-services3-components-python | pip_services3_components/config/YamlConfigReader.py | https://github.com/pip-services3-python/pip-services3-components-python/blob/1de9c1bb544cf1891111e9a5f5d67653f62c9b52/pip_services3_components/config/YamlConfigReader.py#L78-L89 | def read_config(self, correlation_id, parameters):
"""
Reads configuration and parameterize it with given values.
:param correlation_id: (optional) transaction id to trace execution through call chain.
:param parameters: values to parameters the configuration or null to skip parameteri... | [
"def",
"read_config",
"(",
"self",
",",
"correlation_id",
",",
"parameters",
")",
":",
"value",
"=",
"self",
".",
"_read_object",
"(",
"correlation_id",
",",
"parameters",
")",
"return",
"ConfigParams",
".",
"from_value",
"(",
"value",
")"
] | Reads configuration and parameterize it with given values.
:param correlation_id: (optional) transaction id to trace execution through call chain.
:param parameters: values to parameters the configuration or null to skip parameterization.
:return: ConfigParams configuration. | [
"Reads",
"configuration",
"and",
"parameterize",
"it",
"with",
"given",
"values",
"."
] | python | train |
istresearch/scrapy-cluster | rest/rest_service.py | https://github.com/istresearch/scrapy-cluster/blob/13aaed2349af5d792d6bcbfcadc5563158aeb599/rest/rest_service.py#L451-L478 | def _create_ret_object(self, status=SUCCESS, data=None, error=False,
error_message=None, error_cause=None):
"""
Create generic reponse objects.
:param str status: The SUCCESS or FAILURE of the request
:param obj data: The data to return
:param bool err... | [
"def",
"_create_ret_object",
"(",
"self",
",",
"status",
"=",
"SUCCESS",
",",
"data",
"=",
"None",
",",
"error",
"=",
"False",
",",
"error_message",
"=",
"None",
",",
"error_cause",
"=",
"None",
")",
":",
"ret",
"=",
"{",
"}",
"if",
"status",
"==",
"... | Create generic reponse objects.
:param str status: The SUCCESS or FAILURE of the request
:param obj data: The data to return
:param bool error: Set to True to add Error response
:param str error_message: The generic error message
:param str error_cause: The cause of the error
... | [
"Create",
"generic",
"reponse",
"objects",
"."
] | python | train |
PyCQA/astroid | astroid/node_classes.py | https://github.com/PyCQA/astroid/blob/e0a298df55b15abcb77c2a93253f5ab7be52d0fb/astroid/node_classes.py#L1791-L1801 | def postinit(self, test=None, fail=None):
"""Do some setup after initialisation.
:param test: The test that passes or fails the assertion.
:type test: NodeNG or None
:param fail: The message shown when the assertion fails.
:type fail: NodeNG or None
"""
self.fai... | [
"def",
"postinit",
"(",
"self",
",",
"test",
"=",
"None",
",",
"fail",
"=",
"None",
")",
":",
"self",
".",
"fail",
"=",
"fail",
"self",
".",
"test",
"=",
"test"
] | Do some setup after initialisation.
:param test: The test that passes or fails the assertion.
:type test: NodeNG or None
:param fail: The message shown when the assertion fails.
:type fail: NodeNG or None | [
"Do",
"some",
"setup",
"after",
"initialisation",
"."
] | python | train |
ANTsX/ANTsPy | ants/utils/image_similarity.py | https://github.com/ANTsX/ANTsPy/blob/638020af2cdfc5ff4bdb9809ffe67aa505727a3b/ants/utils/image_similarity.py#L8-L62 | def image_similarity(fixed_image, moving_image, metric_type='MeanSquares',
fixed_mask=None, moving_mask=None,
sampling_strategy='regular', sampling_percentage=1.):
"""
Measure similarity between two images
ANTsR function: `imageSimilarity`
Arguments
--... | [
"def",
"image_similarity",
"(",
"fixed_image",
",",
"moving_image",
",",
"metric_type",
"=",
"'MeanSquares'",
",",
"fixed_mask",
"=",
"None",
",",
"moving_mask",
"=",
"None",
",",
"sampling_strategy",
"=",
"'regular'",
",",
"sampling_percentage",
"=",
"1.",
")",
... | Measure similarity between two images
ANTsR function: `imageSimilarity`
Arguments
---------
fixed : ANTsImage
the fixed image
moving : ANTsImage
the moving image
metric_type : string
image metric to calculate
MeanSquares
Correlation... | [
"Measure",
"similarity",
"between",
"two",
"images",
"ANTsR",
"function",
":",
"imageSimilarity"
] | python | train |
Jajcus/pyxmpp2 | pyxmpp2/ext/muc/muc.py | https://github.com/Jajcus/pyxmpp2/blob/14a40a3950910a9cd008b55f0d8905aa0186ce18/pyxmpp2/ext/muc/muc.py#L414-L439 | def get_user(self,nick_or_jid,create=False):
"""
Get a room user with given nick or JID.
:Parameters:
- `nick_or_jid`: the nickname or room JID of the user requested.
- `create`: if `True` and `nick_or_jid` is a JID, then a new
user object will be created i... | [
"def",
"get_user",
"(",
"self",
",",
"nick_or_jid",
",",
"create",
"=",
"False",
")",
":",
"if",
"isinstance",
"(",
"nick_or_jid",
",",
"JID",
")",
":",
"if",
"not",
"nick_or_jid",
".",
"resource",
":",
"return",
"None",
"for",
"u",
"in",
"self",
".",
... | Get a room user with given nick or JID.
:Parameters:
- `nick_or_jid`: the nickname or room JID of the user requested.
- `create`: if `True` and `nick_or_jid` is a JID, then a new
user object will be created if there is no such user in the room.
:Types:
... | [
"Get",
"a",
"room",
"user",
"with",
"given",
"nick",
"or",
"JID",
"."
] | python | valid |
davidchall/topas2numpy | topas2numpy/binned.py | https://github.com/davidchall/topas2numpy/blob/db751dc95c57e530f890118fed407611dbbbdcbc/topas2numpy/binned.py#L103-L157 | def _read_header(self, header_str):
"""Reads metadata from the header."""
# regular expressions
re_float = '[-+]?(\d+(\.\d*)?|\.\d+)([eE][-+]?\d+)?'
re_uint = '\d+'
re_binning = '{d} in (?P<nbins>' + re_uint + ') bin[ s] '
re_binning += 'of (?P<binwidth>' + re_float + ')... | [
"def",
"_read_header",
"(",
"self",
",",
"header_str",
")",
":",
"# regular expressions",
"re_float",
"=",
"'[-+]?(\\d+(\\.\\d*)?|\\.\\d+)([eE][-+]?\\d+)?'",
"re_uint",
"=",
"'\\d+'",
"re_binning",
"=",
"'{d} in (?P<nbins>'",
"+",
"re_uint",
"+",
"') bin[ s] '",
"re_binni... | Reads metadata from the header. | [
"Reads",
"metadata",
"from",
"the",
"header",
"."
] | python | train |
cykl/infoqscraper | infoqscraper/cache.py | https://github.com/cykl/infoqscraper/blob/4fc026b994f98a0a7fe8578e0c9a3a9664982b2e/infoqscraper/cache.py#L113-L147 | def put_path(self, url, path):
"""Puts a resource already on disk into the disk cache.
Args:
url: The original url of the resource
path: The resource already available on disk
Raises:
CacheError: If the file cannot be put in cache
"""
cache_p... | [
"def",
"put_path",
"(",
"self",
",",
"url",
",",
"path",
")",
":",
"cache_path",
"=",
"self",
".",
"_url_to_path",
"(",
"url",
")",
"# Ensure that cache directories exist",
"try",
":",
"dir",
"=",
"os",
".",
"path",
".",
"dirname",
"(",
"cache_path",
")",
... | Puts a resource already on disk into the disk cache.
Args:
url: The original url of the resource
path: The resource already available on disk
Raises:
CacheError: If the file cannot be put in cache | [
"Puts",
"a",
"resource",
"already",
"on",
"disk",
"into",
"the",
"disk",
"cache",
"."
] | python | train |
andymccurdy/redis-py | redis/client.py | https://github.com/andymccurdy/redis-py/blob/cdfe2befbe00db4a3c48c9ddd6d64dea15f6f0db/redis/client.py#L980-L1013 | def migrate(self, host, port, keys, destination_db, timeout,
copy=False, replace=False, auth=None):
"""
Migrate 1 or more keys from the current Redis server to a different
server specified by the ``host``, ``port`` and ``destination_db``.
The ``timeout``, specified in mi... | [
"def",
"migrate",
"(",
"self",
",",
"host",
",",
"port",
",",
"keys",
",",
"destination_db",
",",
"timeout",
",",
"copy",
"=",
"False",
",",
"replace",
"=",
"False",
",",
"auth",
"=",
"None",
")",
":",
"keys",
"=",
"list_or_args",
"(",
"keys",
",",
... | Migrate 1 or more keys from the current Redis server to a different
server specified by the ``host``, ``port`` and ``destination_db``.
The ``timeout``, specified in milliseconds, indicates the maximum
time the connection between the two servers can be idle before the
command is interrup... | [
"Migrate",
"1",
"or",
"more",
"keys",
"from",
"the",
"current",
"Redis",
"server",
"to",
"a",
"different",
"server",
"specified",
"by",
"the",
"host",
"port",
"and",
"destination_db",
"."
] | python | train |
trec-kba/streamcorpus-pipeline | streamcorpus_pipeline/_run_lingpipe.py | https://github.com/trec-kba/streamcorpus-pipeline/blob/8bb82ea1beb83c6b40ed03fa1659df2897c2292a/streamcorpus_pipeline/_run_lingpipe.py#L60-L100 | def make_ner_file(tagger_id, tmp_cleansed_path, tmp_ner_path, pipeline_root):
'''run child process to get OWPL output'''
params = dict(INPUT_FILE=tmp_cleansed_path,
#RAW_OUTPUT_FILE=tmp_ner_raw_path,
OUTPUT_FILE=tmp_ner_path,
PIPELINE_ROOT=pipeline_root)
... | [
"def",
"make_ner_file",
"(",
"tagger_id",
",",
"tmp_cleansed_path",
",",
"tmp_ner_path",
",",
"pipeline_root",
")",
":",
"params",
"=",
"dict",
"(",
"INPUT_FILE",
"=",
"tmp_cleansed_path",
",",
"#RAW_OUTPUT_FILE=tmp_ner_raw_path,",
"OUTPUT_FILE",
"=",
"tmp_ner_path",
... | run child process to get OWPL output | [
"run",
"child",
"process",
"to",
"get",
"OWPL",
"output"
] | python | test |
pymc-devs/pymc | pymc/NormalApproximation.py | https://github.com/pymc-devs/pymc/blob/c6e530210bff4c0d7189b35b2c971bc53f93f7cd/pymc/NormalApproximation.py#L594-L603 | def draw(self):
"""
N.draw()
Sets all N's stochastics to random values drawn from
the normal approximation to the posterior.
"""
devs = normal(size=self._sig.shape[1])
p = inner(self._sig, devs) + self._mu
self._set_stochastics(p) | [
"def",
"draw",
"(",
"self",
")",
":",
"devs",
"=",
"normal",
"(",
"size",
"=",
"self",
".",
"_sig",
".",
"shape",
"[",
"1",
"]",
")",
"p",
"=",
"inner",
"(",
"self",
".",
"_sig",
",",
"devs",
")",
"+",
"self",
".",
"_mu",
"self",
".",
"_set_s... | N.draw()
Sets all N's stochastics to random values drawn from
the normal approximation to the posterior. | [
"N",
".",
"draw",
"()"
] | python | train |
marrow/mongo | marrow/mongo/param/sort.py | https://github.com/marrow/mongo/blob/2066dc73e281b8a46cb5fc965267d6b8e1b18467/marrow/mongo/param/sort.py#L12-L38 | def S(Document, *fields):
"""Generate a MongoDB sort order list using the Django ORM style."""
result = []
for field in fields:
if isinstance(field, tuple): # Unpack existing tuple.
field, direction = field
result.append((field, direction))
continue
direction = ASCENDING
if not field.starts... | [
"def",
"S",
"(",
"Document",
",",
"*",
"fields",
")",
":",
"result",
"=",
"[",
"]",
"for",
"field",
"in",
"fields",
":",
"if",
"isinstance",
"(",
"field",
",",
"tuple",
")",
":",
"# Unpack existing tuple.",
"field",
",",
"direction",
"=",
"field",
"res... | Generate a MongoDB sort order list using the Django ORM style. | [
"Generate",
"a",
"MongoDB",
"sort",
"order",
"list",
"using",
"the",
"Django",
"ORM",
"style",
"."
] | python | train |
gabstopper/smc-python | smc/api/session.py | https://github.com/gabstopper/smc-python/blob/e027b8a5dcfaf884eada32d113d41c1e56b32457/smc/api/session.py#L404-L516 | def login(self, url=None, api_key=None, login=None, pwd=None,
api_version=None, timeout=None, verify=True, alt_filepath=None,
domain=None, **kwargs):
"""
Login to SMC API and retrieve a valid session.
Sessions use a pool connection manager to provide dynamic scalability
... | [
"def",
"login",
"(",
"self",
",",
"url",
"=",
"None",
",",
"api_key",
"=",
"None",
",",
"login",
"=",
"None",
",",
"pwd",
"=",
"None",
",",
"api_version",
"=",
"None",
",",
"timeout",
"=",
"None",
",",
"verify",
"=",
"True",
",",
"alt_filepath",
"=... | Login to SMC API and retrieve a valid session.
Sessions use a pool connection manager to provide dynamic scalability
during times of increased load. Each session is managed by a global
session manager making it possible to have more than one session per
interpreter.
An example l... | [
"Login",
"to",
"SMC",
"API",
"and",
"retrieve",
"a",
"valid",
"session",
".",
"Sessions",
"use",
"a",
"pool",
"connection",
"manager",
"to",
"provide",
"dynamic",
"scalability",
"during",
"times",
"of",
"increased",
"load",
".",
"Each",
"session",
"is",
"man... | python | train |
yinkaisheng/Python-UIAutomation-for-Windows | uiautomation/uiautomation.py | https://github.com/yinkaisheng/Python-UIAutomation-for-Windows/blob/2cc91060982cc8b777152e698d677cc2989bf263/uiautomation/uiautomation.py#L4489-L4506 | def GetBoundingRectangles(self) -> list:
"""
Call IUIAutomationTextRange::GetBoundingRectangles.
textAttributeId: int, a value in class `TextAttributeId`.
Return list, a list of `Rect`.
bounding rectangles for each fully or partially visible line of text in a text range..
... | [
"def",
"GetBoundingRectangles",
"(",
"self",
")",
"->",
"list",
":",
"floats",
"=",
"self",
".",
"textRange",
".",
"GetBoundingRectangles",
"(",
")",
"rects",
"=",
"[",
"]",
"for",
"i",
"in",
"range",
"(",
"len",
"(",
"floats",
")",
"//",
"4",
")",
"... | Call IUIAutomationTextRange::GetBoundingRectangles.
textAttributeId: int, a value in class `TextAttributeId`.
Return list, a list of `Rect`.
bounding rectangles for each fully or partially visible line of text in a text range..
Refer https://docs.microsoft.com/en-us/windows/desktop/a... | [
"Call",
"IUIAutomationTextRange",
"::",
"GetBoundingRectangles",
".",
"textAttributeId",
":",
"int",
"a",
"value",
"in",
"class",
"TextAttributeId",
".",
"Return",
"list",
"a",
"list",
"of",
"Rect",
".",
"bounding",
"rectangles",
"for",
"each",
"fully",
"or",
"p... | python | valid |
PythonCharmers/python-future | src/future/backports/urllib/parse.py | https://github.com/PythonCharmers/python-future/blob/c423752879acc05eebc29b0bb9909327bd5c7308/src/future/backports/urllib/parse.py#L381-L390 | def urlunparse(components):
"""Put a parsed URL back together again. This may result in a
slightly different, but equivalent URL, if the URL that was parsed
originally had redundant delimiters, e.g. a ? with an empty query
(the draft states that these are equivalent)."""
scheme, netloc, url, params... | [
"def",
"urlunparse",
"(",
"components",
")",
":",
"scheme",
",",
"netloc",
",",
"url",
",",
"params",
",",
"query",
",",
"fragment",
",",
"_coerce_result",
"=",
"(",
"_coerce_args",
"(",
"*",
"components",
")",
")",
"if",
"params",
":",
"url",
"=",
"\"... | Put a parsed URL back together again. This may result in a
slightly different, but equivalent URL, if the URL that was parsed
originally had redundant delimiters, e.g. a ? with an empty query
(the draft states that these are equivalent). | [
"Put",
"a",
"parsed",
"URL",
"back",
"together",
"again",
".",
"This",
"may",
"result",
"in",
"a",
"slightly",
"different",
"but",
"equivalent",
"URL",
"if",
"the",
"URL",
"that",
"was",
"parsed",
"originally",
"had",
"redundant",
"delimiters",
"e",
".",
"... | python | train |
cloud9ers/gurumate | environment/lib/python2.7/site-packages/IPython/utils/_process_win32_controller.py | https://github.com/cloud9ers/gurumate/blob/075dc74d1ee62a8c6b7a8bf2b271364f01629d1e/environment/lib/python2.7/site-packages/IPython/utils/_process_win32_controller.py#L492-L495 | def _stdout_raw(self, s):
"""Writes the string to stdout"""
print(s, end='', file=sys.stdout)
sys.stdout.flush() | [
"def",
"_stdout_raw",
"(",
"self",
",",
"s",
")",
":",
"print",
"(",
"s",
",",
"end",
"=",
"''",
",",
"file",
"=",
"sys",
".",
"stdout",
")",
"sys",
".",
"stdout",
".",
"flush",
"(",
")"
] | Writes the string to stdout | [
"Writes",
"the",
"string",
"to",
"stdout"
] | python | test |
optimizely/python-sdk | optimizely/lib/pymmh3.py | https://github.com/optimizely/python-sdk/blob/ec028d9efcf22498c3820f2650fa10f5c30bec90/optimizely/lib/pymmh3.py#L34-L94 | def hash( key, seed = 0x0 ):
''' Implements 32bit murmur3 hash. '''
key = bytearray( xencode(key) )
def fmix( h ):
h ^= h >> 16
h = ( h * 0x85ebca6b ) & 0xFFFFFFFF
h ^= h >> 13
h = ( h * 0xc2b2ae35 ) & 0xFFFFFFFF
h ^= h >> 16
return h
length = len( ke... | [
"def",
"hash",
"(",
"key",
",",
"seed",
"=",
"0x0",
")",
":",
"key",
"=",
"bytearray",
"(",
"xencode",
"(",
"key",
")",
")",
"def",
"fmix",
"(",
"h",
")",
":",
"h",
"^=",
"h",
">>",
"16",
"h",
"=",
"(",
"h",
"*",
"0x85ebca6b",
")",
"&",
"0x... | Implements 32bit murmur3 hash. | [
"Implements",
"32bit",
"murmur3",
"hash",
"."
] | python | train |
klen/aioauth-client | aioauth_client.py | https://github.com/klen/aioauth-client/blob/54f58249496c26965adb4f752f2b24cfe18d0084/aioauth_client.py#L446-L452 | def _request(self, method, url, headers=None, params=None, **aio_kwargs):
"""Setup Authorization Header.."""
access_token = params.pop(self.access_token_key, None)
if access_token:
headers['Authorization'] = "Bearer %s" % access_token
return super(DiscordClient, self)._reques... | [
"def",
"_request",
"(",
"self",
",",
"method",
",",
"url",
",",
"headers",
"=",
"None",
",",
"params",
"=",
"None",
",",
"*",
"*",
"aio_kwargs",
")",
":",
"access_token",
"=",
"params",
".",
"pop",
"(",
"self",
".",
"access_token_key",
",",
"None",
"... | Setup Authorization Header.. | [
"Setup",
"Authorization",
"Header",
".."
] | python | train |
daknuett/py_register_machine2 | tools/assembler/assembler.py | https://github.com/daknuett/py_register_machine2/blob/599c53cd7576297d0d7a53344ed5d9aa98acc751/tools/assembler/assembler.py#L212-L246 | def dereference_run(self, arg_r):
"""
.. _dereference_run:
Converts the commands to opcodes and inserts the (relative or static) references.
"""
wc = 0
der_run = []
for line in arg_r:
args = []
for argument in line[3]:
logging.debug("dereference run: handling argument " + str(argument))
... | [
"def",
"dereference_run",
"(",
"self",
",",
"arg_r",
")",
":",
"wc",
"=",
"0",
"der_run",
"=",
"[",
"]",
"for",
"line",
"in",
"arg_r",
":",
"args",
"=",
"[",
"]",
"for",
"argument",
"in",
"line",
"[",
"3",
"]",
":",
"logging",
".",
"debug",
"(",
... | .. _dereference_run:
Converts the commands to opcodes and inserts the (relative or static) references. | [
"..",
"_dereference_run",
":"
] | python | train |
ray-project/ray | python/ray/tune/trial.py | https://github.com/ray-project/ray/blob/4eade036a0505e244c976f36aaa2d64386b5129b/python/ray/tune/trial.py#L432-L472 | def progress_string(self):
"""Returns a progress message for printing out to the console."""
if not self.last_result:
return self._status_string()
def location_string(hostname, pid):
if hostname == os.uname()[1]:
return "pid={}".format(pid)
e... | [
"def",
"progress_string",
"(",
"self",
")",
":",
"if",
"not",
"self",
".",
"last_result",
":",
"return",
"self",
".",
"_status_string",
"(",
")",
"def",
"location_string",
"(",
"hostname",
",",
"pid",
")",
":",
"if",
"hostname",
"==",
"os",
".",
"uname",... | Returns a progress message for printing out to the console. | [
"Returns",
"a",
"progress",
"message",
"for",
"printing",
"out",
"to",
"the",
"console",
"."
] | python | train |
agile-geoscience/striplog | striplog/legend.py | https://github.com/agile-geoscience/striplog/blob/8033b673a151f96c29802b43763e863519a3124c/striplog/legend.py#L728-L747 | def getattr(self, c, attr, default=None, match_only=None):
"""
Get the attribute of a component.
Args:
c (component): The component to look up.
attr (str): The attribute to get.
default (str): What to return in the event of no match.
match_only (list ... | [
"def",
"getattr",
"(",
"self",
",",
"c",
",",
"attr",
",",
"default",
"=",
"None",
",",
"match_only",
"=",
"None",
")",
":",
"matching_decor",
"=",
"self",
".",
"get_decor",
"(",
"c",
",",
"match_only",
"=",
"match_only",
")",
"try",
":",
"return",
"... | Get the attribute of a component.
Args:
c (component): The component to look up.
attr (str): The attribute to get.
default (str): What to return in the event of no match.
match_only (list of str): The component attributes to include in the
comparison. ... | [
"Get",
"the",
"attribute",
"of",
"a",
"component",
"."
] | python | test |
heitzmann/gdspy | gdspy/__init__.py | https://github.com/heitzmann/gdspy/blob/2c8d1313248c544e2066d19095b7ad7158c79bc9/gdspy/__init__.py#L376-L468 | def fillet(self,
radius,
points_per_2pi=128,
max_points=199,
precision=1e-3):
"""
Round the corners of these polygons and fractures them into
polygons with less vertices if necessary.
Parameters
----------
radiu... | [
"def",
"fillet",
"(",
"self",
",",
"radius",
",",
"points_per_2pi",
"=",
"128",
",",
"max_points",
"=",
"199",
",",
"precision",
"=",
"1e-3",
")",
":",
"two_pi",
"=",
"2",
"*",
"numpy",
".",
"pi",
"fracture",
"=",
"False",
"for",
"jj",
"in",
"range",... | Round the corners of these polygons and fractures them into
polygons with less vertices if necessary.
Parameters
----------
radius : number, list
Radius of the corners. If number: All corners filleted by
that amount. If list: Specify fillet radii on a per-corne... | [
"Round",
"the",
"corners",
"of",
"these",
"polygons",
"and",
"fractures",
"them",
"into",
"polygons",
"with",
"less",
"vertices",
"if",
"necessary",
"."
] | python | train |
ConsenSys/mythril-classic | mythril/ethereum/interface/rpc/base_client.py | https://github.com/ConsenSys/mythril-classic/blob/27af71c34b2ce94f4fae5613ec457f93df1a8f56/mythril/ethereum/interface/rpc/base_client.py#L73-L83 | def eth_getCode(self, address, default_block=BLOCK_TAG_LATEST):
"""TODO: documentation
https://github.com/ethereum/wiki/wiki/JSON-RPC#eth_getcode
NEEDS TESTING
"""
if isinstance(default_block, str):
if default_block not in BLOCK_TAGS:
raise ValueErro... | [
"def",
"eth_getCode",
"(",
"self",
",",
"address",
",",
"default_block",
"=",
"BLOCK_TAG_LATEST",
")",
":",
"if",
"isinstance",
"(",
"default_block",
",",
"str",
")",
":",
"if",
"default_block",
"not",
"in",
"BLOCK_TAGS",
":",
"raise",
"ValueError",
"return",
... | TODO: documentation
https://github.com/ethereum/wiki/wiki/JSON-RPC#eth_getcode
NEEDS TESTING | [
"TODO",
":",
"documentation"
] | python | train |
rsmuc/health_monitoring_plugins | health_monitoring_plugins/check_snmp_eaton_ups/check_snmp_eaton_ups.py | https://github.com/rsmuc/health_monitoring_plugins/blob/7ac29dfb9fe46c055b018cb72ad0d7d8065589b9/health_monitoring_plugins/check_snmp_eaton_ups/check_snmp_eaton_ups.py#L61-L75 | def check_ups_estimated_minutes_remaining(the_session, the_helper, the_snmp_value):
"""
OID .1.3.6.1.2.1.33.1.2.3.0
MIB excerpt
An estimate of the time to battery charge depletion
under the present load conditions if the utility power
is off and remains off, or if it were to be lost and
rema... | [
"def",
"check_ups_estimated_minutes_remaining",
"(",
"the_session",
",",
"the_helper",
",",
"the_snmp_value",
")",
":",
"the_helper",
".",
"add_metric",
"(",
"label",
"=",
"the_helper",
".",
"options",
".",
"type",
",",
"value",
"=",
"the_snmp_value",
",",
"uom",
... | OID .1.3.6.1.2.1.33.1.2.3.0
MIB excerpt
An estimate of the time to battery charge depletion
under the present load conditions if the utility power
is off and remains off, or if it were to be lost and
remain off. | [
"OID",
".",
"1",
".",
"3",
".",
"6",
".",
"1",
".",
"2",
".",
"1",
".",
"33",
".",
"1",
".",
"2",
".",
"3",
".",
"0",
"MIB",
"excerpt",
"An",
"estimate",
"of",
"the",
"time",
"to",
"battery",
"charge",
"depletion",
"under",
"the",
"present",
... | python | train |
juju/python-libjuju | juju/application.py | https://github.com/juju/python-libjuju/blob/58f0011f4c57cd68830258952fa952eaadca6b38/juju/application.py#L276-L293 | async def get_resources(self):
"""Return resources for this application.
Returns a dict mapping resource name to
:class:`~juju._definitions.CharmResource` instances.
"""
facade = client.ResourcesFacade.from_connection(self.connection)
response = await facade.ListResource... | [
"async",
"def",
"get_resources",
"(",
"self",
")",
":",
"facade",
"=",
"client",
".",
"ResourcesFacade",
".",
"from_connection",
"(",
"self",
".",
"connection",
")",
"response",
"=",
"await",
"facade",
".",
"ListResources",
"(",
"[",
"client",
".",
"Entity",... | Return resources for this application.
Returns a dict mapping resource name to
:class:`~juju._definitions.CharmResource` instances. | [
"Return",
"resources",
"for",
"this",
"application",
"."
] | python | train |
SuperCowPowers/bat | bat/utils/cache.py | https://github.com/SuperCowPowers/bat/blob/069e6bc52843dc07760969c531cc442ca7da8e0c/bat/utils/cache.py#L37-L51 | def get(self, key):
"""Get an item from the cache
Args:
key: item key
Returns:
the value of the item or None if the item isn't in the cache
"""
data = self._store.get(key)
if not data:
return None
value, expire = dat... | [
"def",
"get",
"(",
"self",
",",
"key",
")",
":",
"data",
"=",
"self",
".",
"_store",
".",
"get",
"(",
"key",
")",
"if",
"not",
"data",
":",
"return",
"None",
"value",
",",
"expire",
"=",
"data",
"if",
"expire",
"and",
"time",
".",
"time",
"(",
... | Get an item from the cache
Args:
key: item key
Returns:
the value of the item or None if the item isn't in the cache | [
"Get",
"an",
"item",
"from",
"the",
"cache",
"Args",
":",
"key",
":",
"item",
"key",
"Returns",
":",
"the",
"value",
"of",
"the",
"item",
"or",
"None",
"if",
"the",
"item",
"isn",
"t",
"in",
"the",
"cache"
] | python | train |
fracpete/python-weka-wrapper3 | python/weka/flow/control.py | https://github.com/fracpete/python-weka-wrapper3/blob/d850ab1bdb25fbd5a8d86e99f34a397975425838/python/weka/flow/control.py#L105-L123 | def from_dict(cls, d):
"""
Restores an object state from a dictionary, used in de-JSONification.
:param d: the object dictionary
:type d: dict
:return: the object
:rtype: object
"""
result = super(ActorHandler, cls).from_dict(d)
if "actors" in d:
... | [
"def",
"from_dict",
"(",
"cls",
",",
"d",
")",
":",
"result",
"=",
"super",
"(",
"ActorHandler",
",",
"cls",
")",
".",
"from_dict",
"(",
"d",
")",
"if",
"\"actors\"",
"in",
"d",
":",
"l",
"=",
"d",
"[",
"\"actors\"",
"]",
"for",
"e",
"in",
"l",
... | Restores an object state from a dictionary, used in de-JSONification.
:param d: the object dictionary
:type d: dict
:return: the object
:rtype: object | [
"Restores",
"an",
"object",
"state",
"from",
"a",
"dictionary",
"used",
"in",
"de",
"-",
"JSONification",
"."
] | python | train |
bcbio/bcbio-nextgen | bcbio/structural/gatkcnv.py | https://github.com/bcbio/bcbio-nextgen/blob/6a9348c0054ccd5baffd22f1bb7d0422f6978b20/bcbio/structural/gatkcnv.py#L136-L148 | def create_panel_of_normals(items, group_id, work_dir):
"""Create a panel of normals from one or more background read counts.
"""
out_file = os.path.join(work_dir, "%s-%s-pon.hdf5" % (dd.get_sample_name(items[0]), group_id))
if not utils.file_exists(out_file):
with file_transaction(items[0], out... | [
"def",
"create_panel_of_normals",
"(",
"items",
",",
"group_id",
",",
"work_dir",
")",
":",
"out_file",
"=",
"os",
".",
"path",
".",
"join",
"(",
"work_dir",
",",
"\"%s-%s-pon.hdf5\"",
"%",
"(",
"dd",
".",
"get_sample_name",
"(",
"items",
"[",
"0",
"]",
... | Create a panel of normals from one or more background read counts. | [
"Create",
"a",
"panel",
"of",
"normals",
"from",
"one",
"or",
"more",
"background",
"read",
"counts",
"."
] | python | train |
shoebot/shoebot | shoebot/grammar/nodebox.py | https://github.com/shoebot/shoebot/blob/d554c1765c1899fa25727c9fc6805d221585562b/shoebot/grammar/nodebox.py#L608-L618 | def fontsize(self, fontsize=None):
'''
Set or return size of current font.
:param fontsize: Size of font.
:return: Size of font (if fontsize was not specified)
'''
if fontsize is not None:
self._canvas.fontsize = fontsize
else:
return self... | [
"def",
"fontsize",
"(",
"self",
",",
"fontsize",
"=",
"None",
")",
":",
"if",
"fontsize",
"is",
"not",
"None",
":",
"self",
".",
"_canvas",
".",
"fontsize",
"=",
"fontsize",
"else",
":",
"return",
"self",
".",
"_canvas",
".",
"fontsize"
] | Set or return size of current font.
:param fontsize: Size of font.
:return: Size of font (if fontsize was not specified) | [
"Set",
"or",
"return",
"size",
"of",
"current",
"font",
"."
] | python | valid |
urinieto/msaf | msaf/run.py | https://github.com/urinieto/msaf/blob/9dbb57d77a1310465a65cc40f1641d083ca74385/msaf/run.py#L74-L116 | def run_hierarchical(audio_file, bounds_module, labels_module, frame_times,
config, annotator_id=0):
"""Runs hierarchical algorithms with the specified identifiers on the
audio_file. See run_algorithm for more information.
"""
# Sanity check
if bounds_module is None:
rai... | [
"def",
"run_hierarchical",
"(",
"audio_file",
",",
"bounds_module",
",",
"labels_module",
",",
"frame_times",
",",
"config",
",",
"annotator_id",
"=",
"0",
")",
":",
"# Sanity check",
"if",
"bounds_module",
"is",
"None",
":",
"raise",
"NoHierBoundaryError",
"(",
... | Runs hierarchical algorithms with the specified identifiers on the
audio_file. See run_algorithm for more information. | [
"Runs",
"hierarchical",
"algorithms",
"with",
"the",
"specified",
"identifiers",
"on",
"the",
"audio_file",
".",
"See",
"run_algorithm",
"for",
"more",
"information",
"."
] | python | test |
bitesofcode/projexui | projexui/widgets/xchart/renderers/xlinerenderer.py | https://github.com/bitesofcode/projexui/blob/f18a73bec84df90b034ca69b9deea118dbedfc4d/projexui/widgets/xchart/renderers/xlinerenderer.py#L34-L69 | def calculateDatasets(self, scene, axes, datasets):
"""
Builds the datasets for this renderer. Each renderer will need to
subclass and implemenent this method, otherwise, no data will be
shown in the chart.
:param scene | <XChartScene>
ax... | [
"def",
"calculateDatasets",
"(",
"self",
",",
"scene",
",",
"axes",
",",
"datasets",
")",
":",
"items",
"=",
"self",
".",
"calculateDatasetItems",
"(",
"scene",
",",
"datasets",
")",
"if",
"not",
"items",
":",
"scene",
".",
"clear",
"(",
")",
"return",
... | Builds the datasets for this renderer. Each renderer will need to
subclass and implemenent this method, otherwise, no data will be
shown in the chart.
:param scene | <XChartScene>
axes | [<
datasets | [<XChartDataset>, ..] | [
"Builds",
"the",
"datasets",
"for",
"this",
"renderer",
".",
"Each",
"renderer",
"will",
"need",
"to",
"subclass",
"and",
"implemenent",
"this",
"method",
"otherwise",
"no",
"data",
"will",
"be",
"shown",
"in",
"the",
"chart",
".",
":",
"param",
"scene",
"... | python | train |
pjuren/pyokit | src/pyokit/scripts/genomicIntJaccard.py | https://github.com/pjuren/pyokit/blob/fddae123b5d817daa39496183f19c000d9c3791f/src/pyokit/scripts/genomicIntJaccard.py#L80-L110 | def main(args):
"""
main entry point for the GenomicIntJaccard script.
:param args: the arguments for this script, as a list of string. Should
already have had things like the script name stripped. That
is, if there are no args provided, this should be an empty
list.
... | [
"def",
"main",
"(",
"args",
")",
":",
"# get options and arguments",
"ui",
"=",
"getUI",
"(",
"args",
")",
"if",
"ui",
".",
"optionIsSet",
"(",
"\"test\"",
")",
":",
"# just run unit tests",
"unittest",
".",
"main",
"(",
"argv",
"=",
"[",
"sys",
".",
"ar... | main entry point for the GenomicIntJaccard script.
:param args: the arguments for this script, as a list of string. Should
already have had things like the script name stripped. That
is, if there are no args provided, this should be an empty
list. | [
"main",
"entry",
"point",
"for",
"the",
"GenomicIntJaccard",
"script",
"."
] | python | train |
eng-tools/sfsimodels | sfsimodels/models/foundations.py | https://github.com/eng-tools/sfsimodels/blob/65a690ca440d61307f5a9b8478e4704f203a5925/sfsimodels/models/foundations.py#L268-L279 | def i_ww(self):
"""
Second moment of inertia around the width axis.
:return:
"""
d_values = []
for i in range(self.n_pads_l):
d_values.append(self.pad_position_l(i))
d_values = np.array(d_values) - self.length / 2
area_d_sqrd = sum(self.pad_are... | [
"def",
"i_ww",
"(",
"self",
")",
":",
"d_values",
"=",
"[",
"]",
"for",
"i",
"in",
"range",
"(",
"self",
".",
"n_pads_l",
")",
":",
"d_values",
".",
"append",
"(",
"self",
".",
"pad_position_l",
"(",
"i",
")",
")",
"d_values",
"=",
"np",
".",
"ar... | Second moment of inertia around the width axis.
:return: | [
"Second",
"moment",
"of",
"inertia",
"around",
"the",
"width",
"axis",
".",
":",
"return",
":"
] | python | train |
jsommers/switchyard | examples/exercises/router/myrouter.py | https://github.com/jsommers/switchyard/blob/fdcb3869c937dcedbd6ea7a7822ebd412bf1e2b0/examples/exercises/router/myrouter.py#L18-L35 | def router_main(self):
'''
Main method for router; we stay in a loop in this method, receiving
packets until the end of time.
'''
while True:
gotpkt = True
try:
timestamp,dev,pkt = self.net.recv_packet(timeout=1.0)
except No... | [
"def",
"router_main",
"(",
"self",
")",
":",
"while",
"True",
":",
"gotpkt",
"=",
"True",
"try",
":",
"timestamp",
",",
"dev",
",",
"pkt",
"=",
"self",
".",
"net",
".",
"recv_packet",
"(",
"timeout",
"=",
"1.0",
")",
"except",
"NoPackets",
":",
"log_... | Main method for router; we stay in a loop in this method, receiving
packets until the end of time. | [
"Main",
"method",
"for",
"router",
";",
"we",
"stay",
"in",
"a",
"loop",
"in",
"this",
"method",
"receiving",
"packets",
"until",
"the",
"end",
"of",
"time",
"."
] | python | train |
user-cont/colin | colin/core/ruleset/ruleset.py | https://github.com/user-cont/colin/blob/00bb80e6e91522e15361935f813e8cf13d7e76dc/colin/core/ruleset/ruleset.py#L124-L136 | def get_checks_paths(checks_paths=None):
"""
Get path to checks.
:param checks_paths: list of str, directories where the checks are present
:return: list of str (absolute path of directory with checks)
"""
p = os.path.join(__file__, os.pardir, os.pardir, os.pardir, "checks")
p = os.path.abs... | [
"def",
"get_checks_paths",
"(",
"checks_paths",
"=",
"None",
")",
":",
"p",
"=",
"os",
".",
"path",
".",
"join",
"(",
"__file__",
",",
"os",
".",
"pardir",
",",
"os",
".",
"pardir",
",",
"os",
".",
"pardir",
",",
"\"checks\"",
")",
"p",
"=",
"os",
... | Get path to checks.
:param checks_paths: list of str, directories where the checks are present
:return: list of str (absolute path of directory with checks) | [
"Get",
"path",
"to",
"checks",
"."
] | python | train |
orbingol/NURBS-Python | geomdl/exchange.py | https://github.com/orbingol/NURBS-Python/blob/b1c6a8b51cf143ff58761438e93ba6baef470627/geomdl/exchange.py#L826-L844 | def import_vmesh(file):
""" Imports NURBS volume(s) from volume mesh (vmesh) file(s).
:param file: path to a directory containing mesh files or a single mesh file
:type file: str
:return: list of NURBS volumes
:rtype: list
:raises GeomdlException: an error occurred reading the file
"""
... | [
"def",
"import_vmesh",
"(",
"file",
")",
":",
"imported_elements",
"=",
"[",
"]",
"if",
"os",
".",
"path",
".",
"isfile",
"(",
"file",
")",
":",
"imported_elements",
".",
"append",
"(",
"exch",
".",
"import_vol_mesh",
"(",
"file",
")",
")",
"elif",
"os... | Imports NURBS volume(s) from volume mesh (vmesh) file(s).
:param file: path to a directory containing mesh files or a single mesh file
:type file: str
:return: list of NURBS volumes
:rtype: list
:raises GeomdlException: an error occurred reading the file | [
"Imports",
"NURBS",
"volume",
"(",
"s",
")",
"from",
"volume",
"mesh",
"(",
"vmesh",
")",
"file",
"(",
"s",
")",
"."
] | python | train |
10gen/mongo-orchestration | mongo_orchestration/process.py | https://github.com/10gen/mongo-orchestration/blob/81fd2224205922ea2178b08190b53a33aec47261/mongo_orchestration/process.py#L161-L184 | def repair_mongo(name, dbpath):
"""repair mongodb after usafe shutdown"""
log_file = os.path.join(dbpath, 'mongod.log')
cmd = [name, "--dbpath", dbpath, "--logpath", log_file, "--logappend",
"--repair"]
proc = subprocess.Popen(
cmd, universal_newlines=True,
stdout=subprocess.P... | [
"def",
"repair_mongo",
"(",
"name",
",",
"dbpath",
")",
":",
"log_file",
"=",
"os",
".",
"path",
".",
"join",
"(",
"dbpath",
",",
"'mongod.log'",
")",
"cmd",
"=",
"[",
"name",
",",
"\"--dbpath\"",
",",
"dbpath",
",",
"\"--logpath\"",
",",
"log_file",
"... | repair mongodb after usafe shutdown | [
"repair",
"mongodb",
"after",
"usafe",
"shutdown"
] | python | train |
postlund/pyatv | pyatv/convert.py | https://github.com/postlund/pyatv/blob/655dfcda4e2f9d1c501540e18da4f480d8bf0e70/pyatv/convert.py#L74-L82 | def repeat_str(state):
"""Convert internal API repeat state to string."""
if state == const.REPEAT_STATE_OFF:
return 'Off'
if state == const.REPEAT_STATE_TRACK:
return 'Track'
if state == const.REPEAT_STATE_ALL:
return 'All'
return 'Unsupported' | [
"def",
"repeat_str",
"(",
"state",
")",
":",
"if",
"state",
"==",
"const",
".",
"REPEAT_STATE_OFF",
":",
"return",
"'Off'",
"if",
"state",
"==",
"const",
".",
"REPEAT_STATE_TRACK",
":",
"return",
"'Track'",
"if",
"state",
"==",
"const",
".",
"REPEAT_STATE_AL... | Convert internal API repeat state to string. | [
"Convert",
"internal",
"API",
"repeat",
"state",
"to",
"string",
"."
] | python | train |
carpyncho/feets | doc/source/JSAnimation/html_writer.py | https://github.com/carpyncho/feets/blob/53bdfb73b53845561914fc1f756e0c2377b9b76b/doc/source/JSAnimation/html_writer.py#L229-L236 | def _embedded_frames(frame_list, frame_format):
"""frame_list should be a list of base64-encoded png files"""
template = ' frames[{0}] = "data:image/{1};base64,{2}"\n'
embedded = "\n"
for i, frame_data in enumerate(frame_list):
embedded += template.format(i, frame_format,
... | [
"def",
"_embedded_frames",
"(",
"frame_list",
",",
"frame_format",
")",
":",
"template",
"=",
"' frames[{0}] = \"data:image/{1};base64,{2}\"\\n'",
"embedded",
"=",
"\"\\n\"",
"for",
"i",
",",
"frame_data",
"in",
"enumerate",
"(",
"frame_list",
")",
":",
"embedded",
... | frame_list should be a list of base64-encoded png files | [
"frame_list",
"should",
"be",
"a",
"list",
"of",
"base64",
"-",
"encoded",
"png",
"files"
] | python | train |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.