repo stringlengths 7 55 | path stringlengths 4 223 | url stringlengths 87 315 | code stringlengths 75 104k | code_tokens list | docstring stringlengths 1 46.9k | docstring_tokens list | language stringclasses 1
value | partition stringclasses 3
values | avg_line_len float64 7.91 980 |
|---|---|---|---|---|---|---|---|---|---|
marshmallow-code/apispec-webframeworks | src/apispec_webframeworks/tornado.py | https://github.com/marshmallow-code/apispec-webframeworks/blob/21b0b4135c073d2ada47a4228377e63bc03ac7f9/src/apispec_webframeworks/tornado.py#L59-L81 | def tornadopath2openapi(urlspec, method):
"""Convert Tornado URLSpec to OpenAPI-compliant path.
:param urlspec:
:type urlspec: URLSpec
:param method: Handler http method
:type method: function
"""
if sys.version_info >= (3, 3):
args = list(inspect.sig... | [
"def",
"tornadopath2openapi",
"(",
"urlspec",
",",
"method",
")",
":",
"if",
"sys",
".",
"version_info",
">=",
"(",
"3",
",",
"3",
")",
":",
"args",
"=",
"list",
"(",
"inspect",
".",
"signature",
"(",
"method",
")",
".",
"parameters",
".",
"keys",
"(... | Convert Tornado URLSpec to OpenAPI-compliant path.
:param urlspec:
:type urlspec: URLSpec
:param method: Handler http method
:type method: function | [
"Convert",
"Tornado",
"URLSpec",
"to",
"OpenAPI",
"-",
"compliant",
"path",
"."
] | python | train | 36.478261 |
fracpete/python-weka-wrapper3 | python/weka/core/database.py | https://github.com/fracpete/python-weka-wrapper3/blob/d850ab1bdb25fbd5a8d86e99f34a397975425838/python/weka/core/database.py#L182-L195 | def retrieve_instances(self, query=None):
"""
Executes either the supplied query or the one set via options (or the 'query' property).
:param query: query to execute if not the currently set one
:type query: str
:return: the generated dataq
:rtype: Instances
"""
... | [
"def",
"retrieve_instances",
"(",
"self",
",",
"query",
"=",
"None",
")",
":",
"if",
"query",
"is",
"None",
":",
"data",
"=",
"javabridge",
".",
"call",
"(",
"self",
".",
"jobject",
",",
"\"retrieveInstances\"",
",",
"\"()Lweka/core/Instances;\"",
")",
"else... | Executes either the supplied query or the one set via options (or the 'query' property).
:param query: query to execute if not the currently set one
:type query: str
:return: the generated dataq
:rtype: Instances | [
"Executes",
"either",
"the",
"supplied",
"query",
"or",
"the",
"one",
"set",
"via",
"options",
"(",
"or",
"the",
"query",
"property",
")",
"."
] | python | train | 42.071429 |
cackharot/suds-py3 | suds/xsd/doctor.py | https://github.com/cackharot/suds-py3/blob/7387ec7806e9be29aad0a711bea5cb3c9396469c/suds/xsd/doctor.py#L142-L159 | def apply(self, root):
"""
Apply the import (rule) to the specified schema.
If the schema does not already contain an import for the
I{namespace} specified here, it is added.
@param root: A schema root.
@type root: L{Element}
"""
if not self.filter.match(r... | [
"def",
"apply",
"(",
"self",
",",
"root",
")",
":",
"if",
"not",
"self",
".",
"filter",
".",
"match",
"(",
"root",
",",
"self",
".",
"ns",
")",
":",
"return",
"if",
"self",
".",
"exists",
"(",
"root",
")",
":",
"return",
"node",
"=",
"Element",
... | Apply the import (rule) to the specified schema.
If the schema does not already contain an import for the
I{namespace} specified here, it is added.
@param root: A schema root.
@type root: L{Element} | [
"Apply",
"the",
"import",
"(",
"rule",
")",
"to",
"the",
"specified",
"schema",
".",
"If",
"the",
"schema",
"does",
"not",
"already",
"contain",
"an",
"import",
"for",
"the",
"I",
"{",
"namespace",
"}",
"specified",
"here",
"it",
"is",
"added",
"."
] | python | train | 35.055556 |
jashort/SmartFileSorter | smartfilesorter/ruleset.py | https://github.com/jashort/SmartFileSorter/blob/77faf09e5a737da93e16e71a64707366b8307910/smartfilesorter/ruleset.py#L67-L82 | def add_rule(self, config_name, value, plugins, destination):
"""
Adds a rule. Use add_action_rule or add_match_rule instead
:param rule_wrapper: Rule wrapper class (ActionRule or MatchRule)
:param config_name: config_name of the plugin to add
:param value: configuration informat... | [
"def",
"add_rule",
"(",
"self",
",",
"config_name",
",",
"value",
",",
"plugins",
",",
"destination",
")",
":",
"if",
"config_name",
"in",
"plugins",
":",
"rule",
"=",
"plugins",
"[",
"config_name",
"]",
"(",
"value",
")",
"destination",
".",
"append",
"... | Adds a rule. Use add_action_rule or add_match_rule instead
:param rule_wrapper: Rule wrapper class (ActionRule or MatchRule)
:param config_name: config_name of the plugin to add
:param value: configuration information for the rule
:param plugins: list of all available plugins
:pa... | [
"Adds",
"a",
"rule",
".",
"Use",
"add_action_rule",
"or",
"add_match_rule",
"instead",
":",
"param",
"rule_wrapper",
":",
"Rule",
"wrapper",
"class",
"(",
"ActionRule",
"or",
"MatchRule",
")",
":",
"param",
"config_name",
":",
"config_name",
"of",
"the",
"plug... | python | train | 50.6875 |
gem/oq-engine | openquake/hazardlib/geo/line.py | https://github.com/gem/oq-engine/blob/8294553a0b8aba33fd96437a35065d03547d0040/openquake/hazardlib/geo/line.py#L205-L243 | def resample_to_num_points(self, num_points):
"""
Resample the line to a specified number of points.
:param num_points:
Integer number of points the resulting line should have.
:returns:
A new line with that many points as requested.
"""
assert le... | [
"def",
"resample_to_num_points",
"(",
"self",
",",
"num_points",
")",
":",
"assert",
"len",
"(",
"self",
".",
"points",
")",
">",
"1",
",",
"\"can not resample the line of one point\"",
"section_length",
"=",
"self",
".",
"get_length",
"(",
")",
"/",
"(",
"num... | Resample the line to a specified number of points.
:param num_points:
Integer number of points the resulting line should have.
:returns:
A new line with that many points as requested. | [
"Resample",
"the",
"line",
"to",
"a",
"specified",
"number",
"of",
"points",
"."
] | python | train | 40.025641 |
dwavesystems/dwave_networkx | dwave_networkx/algorithms/elimination_ordering.py | https://github.com/dwavesystems/dwave_networkx/blob/9ea1223ddbc7e86db2f90b8b23e250e6642c3d68/dwave_networkx/algorithms/elimination_ordering.py#L703-L727 | def _theorem5p4(adj, ub):
"""By Theorem 5.4, if any two vertices have ub + 1 common neighbors
then we can add an edge between them.
"""
new_edges = set()
for u, v in itertools.combinations(adj, 2):
if u in adj[v]:
# already an edge
continue
if len(adj[u].inte... | [
"def",
"_theorem5p4",
"(",
"adj",
",",
"ub",
")",
":",
"new_edges",
"=",
"set",
"(",
")",
"for",
"u",
",",
"v",
"in",
"itertools",
".",
"combinations",
"(",
"adj",
",",
"2",
")",
":",
"if",
"u",
"in",
"adj",
"[",
"v",
"]",
":",
"# already an edge... | By Theorem 5.4, if any two vertices have ub + 1 common neighbors
then we can add an edge between them. | [
"By",
"Theorem",
"5",
".",
"4",
"if",
"any",
"two",
"vertices",
"have",
"ub",
"+",
"1",
"common",
"neighbors",
"then",
"we",
"can",
"add",
"an",
"edge",
"between",
"them",
"."
] | python | train | 27.32 |
openstack/horizon | openstack_dashboard/api/keystone.py | https://github.com/openstack/horizon/blob/5601ea9477323e599d9b766fcac1f8be742935b2/openstack_dashboard/api/keystone.py#L843-L851 | def remove_tenant_user_role(request, project=None, user=None, role=None,
group=None, domain=None):
"""Removes a given single role for a user from a tenant."""
manager = keystoneclient(request, admin=True).roles
if VERSIONS.active < 3:
return manager.remove_user_role(user,... | [
"def",
"remove_tenant_user_role",
"(",
"request",
",",
"project",
"=",
"None",
",",
"user",
"=",
"None",
",",
"role",
"=",
"None",
",",
"group",
"=",
"None",
",",
"domain",
"=",
"None",
")",
":",
"manager",
"=",
"keystoneclient",
"(",
"request",
",",
"... | Removes a given single role for a user from a tenant. | [
"Removes",
"a",
"given",
"single",
"role",
"for",
"a",
"user",
"from",
"a",
"tenant",
"."
] | python | train | 51 |
wummel/linkchecker | linkcheck/fileutil.py | https://github.com/wummel/linkchecker/blob/c2ce810c3fb00b895a841a7be6b2e78c64e7b042/linkcheck/fileutil.py#L176-L184 | def has_changed (filename):
"""Check if filename has changed since the last check. If this
is the first check, assume the file is changed."""
key = os.path.abspath(filename)
mtime = get_mtime(key)
if key not in _mtime_cache:
_mtime_cache[key] = mtime
return True
return mtime > _m... | [
"def",
"has_changed",
"(",
"filename",
")",
":",
"key",
"=",
"os",
".",
"path",
".",
"abspath",
"(",
"filename",
")",
"mtime",
"=",
"get_mtime",
"(",
"key",
")",
"if",
"key",
"not",
"in",
"_mtime_cache",
":",
"_mtime_cache",
"[",
"key",
"]",
"=",
"mt... | Check if filename has changed since the last check. If this
is the first check, assume the file is changed. | [
"Check",
"if",
"filename",
"has",
"changed",
"since",
"the",
"last",
"check",
".",
"If",
"this",
"is",
"the",
"first",
"check",
"assume",
"the",
"file",
"is",
"changed",
"."
] | python | train | 36.333333 |
crackinglandia/pype32 | tools/readpe.py | https://github.com/crackinglandia/pype32/blob/192fd14dfc0dd36d953739a81c17fbaf5e3d6076/tools/readpe.py#L64-L70 | def showFileHeaderData(peInstance):
""" Prints IMAGE_FILE_HEADER fields. """
fileHeaderFields = peInstance.ntHeaders.fileHeader.getFields()
print "[+] IMAGE_FILE_HEADER values:\n"
for field in fileHeaderFields:
print "--> %s = 0x%08x" % (field, fileHeaderFields[field].value) | [
"def",
"showFileHeaderData",
"(",
"peInstance",
")",
":",
"fileHeaderFields",
"=",
"peInstance",
".",
"ntHeaders",
".",
"fileHeader",
".",
"getFields",
"(",
")",
"print",
"\"[+] IMAGE_FILE_HEADER values:\\n\"",
"for",
"field",
"in",
"fileHeaderFields",
":",
"print",
... | Prints IMAGE_FILE_HEADER fields. | [
"Prints",
"IMAGE_FILE_HEADER",
"fields",
"."
] | python | train | 43.285714 |
kata198/AdvancedHTMLParser | AdvancedHTMLParser/Tags.py | https://github.com/kata198/AdvancedHTMLParser/blob/06aeea5d8e2ea86e155aae0fc237623d3e9b7f9d/AdvancedHTMLParser/Tags.py#L1200-L1220 | def getAllChildNodes(self):
'''
getAllChildNodes - Gets all the children, and their children,
and their children, and so on, all the way to the end as a TagCollection.
Use .childNodes for a regular list
@return TagCollection<AdvancedTag> - ... | [
"def",
"getAllChildNodes",
"(",
"self",
")",
":",
"ret",
"=",
"TagCollection",
"(",
")",
"# Scan all the children of this node",
"for",
"child",
"in",
"self",
".",
"children",
":",
"# Append each child",
"ret",
".",
"append",
"(",
"child",
")",
"# Append children'... | getAllChildNodes - Gets all the children, and their children,
and their children, and so on, all the way to the end as a TagCollection.
Use .childNodes for a regular list
@return TagCollection<AdvancedTag> - A TagCollection of all children (and their children ... | [
"getAllChildNodes",
"-",
"Gets",
"all",
"the",
"children",
"and",
"their",
"children",
"and",
"their",
"children",
"and",
"so",
"on",
"all",
"the",
"way",
"to",
"the",
"end",
"as",
"a",
"TagCollection",
".",
"Use",
".",
"childNodes",
"for",
"a",
"regular",... | python | train | 31.666667 |
secdev/scapy | scapy/utils.py | https://github.com/secdev/scapy/blob/3ffe757c184017dd46464593a8f80f85abc1e79a/scapy/utils.py#L72-L85 | def get_temp_dir(keep=False):
"""Creates a temporary file, and returns its name.
:param keep: If False (default), the directory will be recursively
deleted when Scapy exits.
:return: A full path to a temporary directory.
"""
dname = tempfile.mkdtemp(prefix="scapy")
if not kee... | [
"def",
"get_temp_dir",
"(",
"keep",
"=",
"False",
")",
":",
"dname",
"=",
"tempfile",
".",
"mkdtemp",
"(",
"prefix",
"=",
"\"scapy\"",
")",
"if",
"not",
"keep",
":",
"conf",
".",
"temp_files",
".",
"append",
"(",
"dname",
")",
"return",
"dname"
] | Creates a temporary file, and returns its name.
:param keep: If False (default), the directory will be recursively
deleted when Scapy exits.
:return: A full path to a temporary directory. | [
"Creates",
"a",
"temporary",
"file",
"and",
"returns",
"its",
"name",
"."
] | python | train | 26.071429 |
hosford42/xcs | xcs/framework.py | https://github.com/hosford42/xcs/blob/183bdd0dd339e19ded3be202f86e1b38bdb9f1e5/xcs/framework.py#L430-L451 | def _compute_prediction(self):
"""Compute the combined prediction and prediction weight for this
action set. The combined prediction is the weighted average of the
individual predictions of the classifiers. The combined prediction
weight is the sum of the individual prediction weights of... | [
"def",
"_compute_prediction",
"(",
"self",
")",
":",
"total_weight",
"=",
"0",
"total_prediction",
"=",
"0",
"for",
"rule",
"in",
"self",
".",
"_rules",
".",
"values",
"(",
")",
":",
"total_weight",
"+=",
"rule",
".",
"prediction_weight",
"total_prediction",
... | Compute the combined prediction and prediction weight for this
action set. The combined prediction is the weighted average of the
individual predictions of the classifiers. The combined prediction
weight is the sum of the individual prediction weights of the
classifiers.
Usage:
... | [
"Compute",
"the",
"combined",
"prediction",
"and",
"prediction",
"weight",
"for",
"this",
"action",
"set",
".",
"The",
"combined",
"prediction",
"is",
"the",
"weighted",
"average",
"of",
"the",
"individual",
"predictions",
"of",
"the",
"classifiers",
".",
"The",... | python | train | 40.363636 |
odlgroup/odl | odl/solvers/smooth/newton.py | https://github.com/odlgroup/odl/blob/b8443f6aca90e191ba36c91d32253c5a36249a6c/odl/solvers/smooth/newton.py#L21-L71 | def _bfgs_direction(s, y, x, hessinv_estimate=None):
r"""Compute ``Hn^-1(x)`` for the L-BFGS method.
Parameters
----------
s : sequence of `LinearSpaceElement`
The ``s`` coefficients in the BFGS update, see Notes.
y : sequence of `LinearSpaceElement`
The ``y`` coefficients in the BF... | [
"def",
"_bfgs_direction",
"(",
"s",
",",
"y",
",",
"x",
",",
"hessinv_estimate",
"=",
"None",
")",
":",
"assert",
"len",
"(",
"s",
")",
"==",
"len",
"(",
"y",
")",
"r",
"=",
"x",
".",
"copy",
"(",
")",
"alphas",
"=",
"np",
".",
"zeros",
"(",
... | r"""Compute ``Hn^-1(x)`` for the L-BFGS method.
Parameters
----------
s : sequence of `LinearSpaceElement`
The ``s`` coefficients in the BFGS update, see Notes.
y : sequence of `LinearSpaceElement`
The ``y`` coefficients in the BFGS update, see Notes.
x : `LinearSpaceElement`
... | [
"r",
"Compute",
"Hn^",
"-",
"1",
"(",
"x",
")",
"for",
"the",
"L",
"-",
"BFGS",
"method",
"."
] | python | train | 26.764706 |
jantman/awslimitchecker | docs/examples/multi-region_multi-account/alc_multi_account.py | https://github.com/jantman/awslimitchecker/blob/e50197f70f3d0abcc5cfc7fde6336f548b790e34/docs/examples/multi-region_multi-account/alc_multi_account.py#L124-L135 | def _load_region(self, acct_id, region_name, path):
"""load config from a single per-region subdirectory of an account"""
lim_path = os.path.join(path, 'limit_overrides.json')
thresh_path = os.path.join(path, 'threshold_overrides.json')
res = {'limit_overrides': {}, 'threshold_overrides'... | [
"def",
"_load_region",
"(",
"self",
",",
"acct_id",
",",
"region_name",
",",
"path",
")",
":",
"lim_path",
"=",
"os",
".",
"path",
".",
"join",
"(",
"path",
",",
"'limit_overrides.json'",
")",
"thresh_path",
"=",
"os",
".",
"path",
".",
"join",
"(",
"p... | load config from a single per-region subdirectory of an account | [
"load",
"config",
"from",
"a",
"single",
"per",
"-",
"region",
"subdirectory",
"of",
"an",
"account"
] | python | train | 56 |
coldfix/udiskie | udiskie/cli.py | https://github.com/coldfix/udiskie/blob/804c9d27df6f7361fec3097c432398f2d702f911/udiskie/cli.py#L204-L214 | def run(self):
"""Run the main loop. Returns exit code."""
self.exit_code = 1
self.mainloop = GLib.MainLoop()
try:
future = ensure_future(self._start_async_tasks())
future.callbacks.append(self.set_exit_code)
self.mainloop.run()
return self... | [
"def",
"run",
"(",
"self",
")",
":",
"self",
".",
"exit_code",
"=",
"1",
"self",
".",
"mainloop",
"=",
"GLib",
".",
"MainLoop",
"(",
")",
"try",
":",
"future",
"=",
"ensure_future",
"(",
"self",
".",
"_start_async_tasks",
"(",
")",
")",
"future",
"."... | Run the main loop. Returns exit code. | [
"Run",
"the",
"main",
"loop",
".",
"Returns",
"exit",
"code",
"."
] | python | train | 34.090909 |
Hackerfleet/hfos | hfos/schemata/defaultform.py | https://github.com/Hackerfleet/hfos/blob/b6df14eacaffb6be5c844108873ff8763ec7f0c9/hfos/schemata/defaultform.py#L92-L114 | def lookup_field(key, lookup_type=None, placeholder=None, html_class="div",
select_type="strapselect", mapping="uuid"):
"""Generates a lookup field for form definitions"""
if lookup_type is None:
lookup_type = key
if placeholder is None:
placeholder = "Select a " + lookup_... | [
"def",
"lookup_field",
"(",
"key",
",",
"lookup_type",
"=",
"None",
",",
"placeholder",
"=",
"None",
",",
"html_class",
"=",
"\"div\"",
",",
"select_type",
"=",
"\"strapselect\"",
",",
"mapping",
"=",
"\"uuid\"",
")",
":",
"if",
"lookup_type",
"is",
"None",
... | Generates a lookup field for form definitions | [
"Generates",
"a",
"lookup",
"field",
"for",
"form",
"definitions"
] | python | train | 28.043478 |
Qiskit/qiskit-terra | qiskit/tools/jupyter/backend_overview.py | https://github.com/Qiskit/qiskit-terra/blob/d4f58d903bc96341b816f7c35df936d6421267d1/qiskit/tools/jupyter/backend_overview.py#L112-L167 | def backend_widget(backend):
"""Creates a backend widget.
"""
config = backend.configuration().to_dict()
props = backend.properties().to_dict()
name = widgets.HTML(value="<h4>{name}</h4>".format(name=backend.name()),
layout=widgets.Layout())
n_qubits = config['n_qubits'... | [
"def",
"backend_widget",
"(",
"backend",
")",
":",
"config",
"=",
"backend",
".",
"configuration",
"(",
")",
".",
"to_dict",
"(",
")",
"props",
"=",
"backend",
".",
"properties",
"(",
")",
".",
"to_dict",
"(",
")",
"name",
"=",
"widgets",
".",
"HTML",
... | Creates a backend widget. | [
"Creates",
"a",
"backend",
"widget",
"."
] | python | test | 42.964286 |
dlecocq/nsq-py | nsq/util.py | https://github.com/dlecocq/nsq-py/blob/3ecacf6ab7719d38031179277113d875554a0c16/nsq/util.py#L31-L40 | def hexify(message):
'''Print out printable characters, but others in hex'''
import string
hexified = []
for char in message:
if (char in '\n\r \t') or (char not in string.printable):
hexified.append('\\x%02x' % ord(char))
else:
hexified.append(char)
return ''... | [
"def",
"hexify",
"(",
"message",
")",
":",
"import",
"string",
"hexified",
"=",
"[",
"]",
"for",
"char",
"in",
"message",
":",
"if",
"(",
"char",
"in",
"'\\n\\r \\t'",
")",
"or",
"(",
"char",
"not",
"in",
"string",
".",
"printable",
")",
":",
"hexifi... | Print out printable characters, but others in hex | [
"Print",
"out",
"printable",
"characters",
"but",
"others",
"in",
"hex"
] | python | train | 32.6 |
totokaka/pySpaceGDN | pyspacegdn/spacegdn.py | https://github.com/totokaka/pySpaceGDN/blob/55c8be8d751e24873e0a7f7e99d2b715442ec878/pyspacegdn/spacegdn.py#L64-L72 | def _create_user_agent(self):
""" Create the user agent and return it as a string. """
user_agent = '{}/{} {}'.format(pyspacegdn.__title__,
pyspacegdn.__version__,
default_user_agent())
if self.client_name:
... | [
"def",
"_create_user_agent",
"(",
"self",
")",
":",
"user_agent",
"=",
"'{}/{} {}'",
".",
"format",
"(",
"pyspacegdn",
".",
"__title__",
",",
"pyspacegdn",
".",
"__version__",
",",
"default_user_agent",
"(",
")",
")",
"if",
"self",
".",
"client_name",
":",
"... | Create the user agent and return it as a string. | [
"Create",
"the",
"user",
"agent",
"and",
"return",
"it",
"as",
"a",
"string",
"."
] | python | train | 51.444444 |
b3j0f/conf | b3j0f/conf/configurable/log.py | https://github.com/b3j0f/conf/blob/18dd6d5d6560f9b202793739e2330a2181163511/b3j0f/conf/configurable/log.py#L51-L57 | def _filehandler(configurable):
"""Default logging file handler."""
filename = configurable.log_name.replace('.', sep)
path = join(configurable.log_path, '{0}.log'.format(filename))
return FileHandler(path, mode='a+') | [
"def",
"_filehandler",
"(",
"configurable",
")",
":",
"filename",
"=",
"configurable",
".",
"log_name",
".",
"replace",
"(",
"'.'",
",",
"sep",
")",
"path",
"=",
"join",
"(",
"configurable",
".",
"log_path",
",",
"'{0}.log'",
".",
"format",
"(",
"filename"... | Default logging file handler. | [
"Default",
"logging",
"file",
"handler",
"."
] | python | train | 32.714286 |
brocade/pynos | pynos/versions/ver_6/ver_6_0_1/yang/brocade_ha.py | https://github.com/brocade/pynos/blob/bd8a34e98f322de3fc06750827d8bbc3a0c00380/pynos/versions/ver_6/ver_6_0_1/yang/brocade_ha.py#L12-L23 | def reload_input_rbridge_id(self, **kwargs):
"""Auto Generated Code
"""
config = ET.Element("config")
reload = ET.Element("reload")
config = reload
input = ET.SubElement(reload, "input")
rbridge_id = ET.SubElement(input, "rbridge-id")
rbridge_id.text = kwa... | [
"def",
"reload_input_rbridge_id",
"(",
"self",
",",
"*",
"*",
"kwargs",
")",
":",
"config",
"=",
"ET",
".",
"Element",
"(",
"\"config\"",
")",
"reload",
"=",
"ET",
".",
"Element",
"(",
"\"reload\"",
")",
"config",
"=",
"reload",
"input",
"=",
"ET",
"."... | Auto Generated Code | [
"Auto",
"Generated",
"Code"
] | python | train | 35.083333 |
graphql-python/graphql-core | graphql/validation/rules/overlapping_fields_can_be_merged.py | https://github.com/graphql-python/graphql-core/blob/d8e9d3abe7c209eb2f51cf001402783bfd480596/graphql/validation/rules/overlapping_fields_can_be_merged.py#L609-L630 | def _get_referenced_fields_and_fragment_names(
context, # ValidationContext
cached_fields_and_fragment_names, # type: Dict[SelectionSet, Tuple[Dict[str, List[Tuple[Union[GraphQLInterfaceType, GraphQLObjectType, None], Field, GraphQLField]]], List[str]]]
fragment, # type: InlineFragment
):
# type: (..... | [
"def",
"_get_referenced_fields_and_fragment_names",
"(",
"context",
",",
"# ValidationContext",
"cached_fields_and_fragment_names",
",",
"# type: Dict[SelectionSet, Tuple[Dict[str, List[Tuple[Union[GraphQLInterfaceType, GraphQLObjectType, None], Field, GraphQLField]]], List[str]]]",
"fragment",
... | Given a reference to a fragment, return the represented collection of fields as well as a list of
nested fragment names referenced via fragment spreads. | [
"Given",
"a",
"reference",
"to",
"a",
"fragment",
"return",
"the",
"represented",
"collection",
"of",
"fields",
"as",
"well",
"as",
"a",
"list",
"of",
"nested",
"fragment",
"names",
"referenced",
"via",
"fragment",
"spreads",
"."
] | python | train | 46.818182 |
tensorflow/tensor2tensor | tensor2tensor/models/research/lm_experiments.py | https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/models/research/lm_experiments.py#L104-L110 | def lmx_relative():
"""Language model using relative attention."""
hparams = lmx_base()
hparams.self_attention_type = "dot_product_relative_v2"
hparams.activation_dtype = "float32"
hparams.weight_dtype = "float32"
return hparams | [
"def",
"lmx_relative",
"(",
")",
":",
"hparams",
"=",
"lmx_base",
"(",
")",
"hparams",
".",
"self_attention_type",
"=",
"\"dot_product_relative_v2\"",
"hparams",
".",
"activation_dtype",
"=",
"\"float32\"",
"hparams",
".",
"weight_dtype",
"=",
"\"float32\"",
"return... | Language model using relative attention. | [
"Language",
"model",
"using",
"relative",
"attention",
"."
] | python | train | 33.428571 |
brainiak/brainiak | brainiak/fcma/voxelselector.py | https://github.com/brainiak/brainiak/blob/408f12dec2ff56559a26873a848a09e4c8facfeb/brainiak/fcma/voxelselector.py#L423-L465 | def _do_cross_validation(self, clf, data, task):
"""Run voxelwise cross validation based on correlation vectors.
clf: classification function
the classifier to be used in cross validation
data: 3D numpy array
If using sklearn.svm.SVC with precomputed kernel,
... | [
"def",
"_do_cross_validation",
"(",
"self",
",",
"clf",
",",
"data",
",",
"task",
")",
":",
"time1",
"=",
"time",
".",
"time",
"(",
")",
"if",
"isinstance",
"(",
"clf",
",",
"sklearn",
".",
"svm",
".",
"SVC",
")",
"and",
"clf",
".",
"kernel",
"==",... | Run voxelwise cross validation based on correlation vectors.
clf: classification function
the classifier to be used in cross validation
data: 3D numpy array
If using sklearn.svm.SVC with precomputed kernel,
it is in shape [num_processed_voxels, num_epochs, num_epochs... | [
"Run",
"voxelwise",
"cross",
"validation",
"based",
"on",
"correlation",
"vectors",
"."
] | python | train | 43.837209 |
atlassian-api/atlassian-python-api | examples/confluence-draft-page-cleaner.py | https://github.com/atlassian-api/atlassian-python-api/blob/540d269905c3e7547b666fe30c647b2d512cf358/examples/confluence-draft-page-cleaner.py#L13-L33 | def clean_draft_pages_from_space(confluence, space_key, count, date_now):
"""
Remove draft pages from space using datetime.now
:param confluence:
:param space_key:
:param count:
:param date_now:
:return: int counter
"""
pages = confluence.get_all_draft_pages_from_space(space=space_ke... | [
"def",
"clean_draft_pages_from_space",
"(",
"confluence",
",",
"space_key",
",",
"count",
",",
"date_now",
")",
":",
"pages",
"=",
"confluence",
".",
"get_all_draft_pages_from_space",
"(",
"space",
"=",
"space_key",
",",
"start",
"=",
"0",
",",
"limit",
"=",
"... | Remove draft pages from space using datetime.now
:param confluence:
:param space_key:
:param count:
:param date_now:
:return: int counter | [
"Remove",
"draft",
"pages",
"from",
"space",
"using",
"datetime",
".",
"now",
":",
"param",
"confluence",
":",
":",
"param",
"space_key",
":",
":",
"param",
"count",
":",
":",
"param",
"date_now",
":",
":",
"return",
":",
"int",
"counter"
] | python | train | 43.333333 |
google/grr | grr/client/grr_response_client/client_actions/linux/linux.py | https://github.com/google/grr/blob/5cef4e8e2f0d5df43ea4877e9c798e0bf60bfe74/grr/client/grr_response_client/client_actions/linux/linux.py#L282-L292 | def CheckMounts(filename):
"""Parses the currently mounted devices."""
with io.open(filename, "r") as fd:
for line in fd:
try:
device, mnt_point, fs_type, _ = line.split(" ", 3)
except ValueError:
continue
if fs_type in ACCEPTABLE_FILESYSTEMS:
if os.path.exists(device):... | [
"def",
"CheckMounts",
"(",
"filename",
")",
":",
"with",
"io",
".",
"open",
"(",
"filename",
",",
"\"r\"",
")",
"as",
"fd",
":",
"for",
"line",
"in",
"fd",
":",
"try",
":",
"device",
",",
"mnt_point",
",",
"fs_type",
",",
"_",
"=",
"line",
".",
"... | Parses the currently mounted devices. | [
"Parses",
"the",
"currently",
"mounted",
"devices",
"."
] | python | train | 32.090909 |
robotools/fontParts | Lib/fontParts/base/font.py | https://github.com/robotools/fontParts/blob/d2ff106fe95f9d566161d936a645157626568712/Lib/fontParts/base/font.py#L255-L300 | def generateFormatToExtension(format, fallbackFormat):
"""
+--------------+--------------------------------------------------------------------+
| mactype1 | Mac Type 1 font (generates suitcase and LWFN file) |
+--------------+-----------------------------------------... | [
"def",
"generateFormatToExtension",
"(",
"format",
",",
"fallbackFormat",
")",
":",
"formatToExtension",
"=",
"dict",
"(",
"# mactype1=None,",
"macttf",
"=",
"\".ttf\"",
",",
"macttdfont",
"=",
"\".dfont\"",
",",
"otfcff",
"=",
"\".otf\"",
",",
"otfttf",
"=",
"\... | +--------------+--------------------------------------------------------------------+
| mactype1 | Mac Type 1 font (generates suitcase and LWFN file) |
+--------------+--------------------------------------------------------------------+
| macttf | Mac TrueType font (ge... | [
"+",
"--------------",
"+",
"--------------------------------------------------------------------",
"+",
"|",
"mactype1",
"|",
"Mac",
"Type",
"1",
"font",
"(",
"generates",
"suitcase",
"and",
"LWFN",
"file",
")",
"|",
"+",
"--------------",
"+",
"-----------------------... | python | train | 66.086957 |
radjkarl/fancyTools | fancytools/math/rotation.py | https://github.com/radjkarl/fancyTools/blob/4c4d961003dc4ed6e46429a0c24f7e2bb52caa8b/fancytools/math/rotation.py#L10-L29 | def rotMatrix2AxisAndAngle(R):
"""
stackoverflow.com/questions/12463487/obtain-rotation-axis-from-rotation-matrix-and-translation-vector-in-opencv
R : 3x3 rotation matrix
returns axis, angle
"""
angle = np.arccos((R[0, 0] + R[1, 1] + R[2, 2] - 1)/ 2)
axis = np.array([
# x
(... | [
"def",
"rotMatrix2AxisAndAngle",
"(",
"R",
")",
":",
"angle",
"=",
"np",
".",
"arccos",
"(",
"(",
"R",
"[",
"0",
",",
"0",
"]",
"+",
"R",
"[",
"1",
",",
"1",
"]",
"+",
"R",
"[",
"2",
",",
"2",
"]",
"-",
"1",
")",
"/",
"2",
")",
"axis",
... | stackoverflow.com/questions/12463487/obtain-rotation-axis-from-rotation-matrix-and-translation-vector-in-opencv
R : 3x3 rotation matrix
returns axis, angle | [
"stackoverflow",
".",
"com",
"/",
"questions",
"/",
"12463487",
"/",
"obtain",
"-",
"rotation",
"-",
"axis",
"-",
"from",
"-",
"rotation",
"-",
"matrix",
"-",
"and",
"-",
"translation",
"-",
"vector",
"-",
"in",
"-",
"opencv"
] | python | train | 41.2 |
quantopian/pgcontents | pgcontents/hybridmanager.py | https://github.com/quantopian/pgcontents/blob/ed36268b7917332d16868208e1e565742a8753e1/pgcontents/hybridmanager.py#L18-L41 | def _resolve_path(path, manager_dict):
"""
Resolve a path based on a dictionary of manager prefixes.
Returns a triple of (prefix, manager, manager_relative_path).
"""
path = normalize_api_path(path)
parts = path.split('/')
# Try to find a sub-manager for the first subdirectory.
mgr = m... | [
"def",
"_resolve_path",
"(",
"path",
",",
"manager_dict",
")",
":",
"path",
"=",
"normalize_api_path",
"(",
"path",
")",
"parts",
"=",
"path",
".",
"split",
"(",
"'/'",
")",
"# Try to find a sub-manager for the first subdirectory.",
"mgr",
"=",
"manager_dict",
"."... | Resolve a path based on a dictionary of manager prefixes.
Returns a triple of (prefix, manager, manager_relative_path). | [
"Resolve",
"a",
"path",
"based",
"on",
"a",
"dictionary",
"of",
"manager",
"prefixes",
"."
] | python | test | 28.458333 |
tr00st/insult_generator | insultgenerator/phrases.py | https://github.com/tr00st/insult_generator/blob/a4496b29ea4beae6b82a4119e8dfbd871be75dbb/insultgenerator/phrases.py#L4-L14 | def _unpack_bytes(bytes):
"""
Unpack a set of bytes into an integer. First pads to 4 bytes.
Little endian.
"""
if bytes == b'':
return 0
int_length = 4
len_diff = int_length - len(bytes)
bytes = bytes + len_diff * b'\x00'
return struct.unpack("<L", bytes)[0] | [
"def",
"_unpack_bytes",
"(",
"bytes",
")",
":",
"if",
"bytes",
"==",
"b''",
":",
"return",
"0",
"int_length",
"=",
"4",
"len_diff",
"=",
"int_length",
"-",
"len",
"(",
"bytes",
")",
"bytes",
"=",
"bytes",
"+",
"len_diff",
"*",
"b'\\x00'",
"return",
"st... | Unpack a set of bytes into an integer. First pads to 4 bytes.
Little endian. | [
"Unpack",
"a",
"set",
"of",
"bytes",
"into",
"an",
"integer",
".",
"First",
"pads",
"to",
"4",
"bytes",
".",
"Little",
"endian",
"."
] | python | train | 27.454545 |
DataBiosphere/toil | src/toil/provisioners/clusterScaler.py | https://github.com/DataBiosphere/toil/blob/a8252277ff814e7bee0971139c2344f88e44b644/src/toil/provisioners/clusterScaler.py#L417-L437 | def addCompletedJob(self, job, wallTime):
"""
Adds the shape of a completed job to the queue, allowing the scalar to use the last N
completed jobs in factoring how many nodes are required in the cluster.
:param toil.job.JobNode job: The memory, core and disk requirements of the completed... | [
"def",
"addCompletedJob",
"(",
"self",
",",
"job",
",",
"wallTime",
")",
":",
"#Adjust average runtimes to include this job.",
"if",
"job",
".",
"jobName",
"in",
"self",
".",
"jobNameToAvgRuntime",
":",
"prevAvg",
"=",
"self",
".",
"jobNameToAvgRuntime",
"[",
"job... | Adds the shape of a completed job to the queue, allowing the scalar to use the last N
completed jobs in factoring how many nodes are required in the cluster.
:param toil.job.JobNode job: The memory, core and disk requirements of the completed job
:param int wallTime: The wall-time taken to compl... | [
"Adds",
"the",
"shape",
"of",
"a",
"completed",
"job",
"to",
"the",
"queue",
"allowing",
"the",
"scalar",
"to",
"use",
"the",
"last",
"N",
"completed",
"jobs",
"in",
"factoring",
"how",
"many",
"nodes",
"are",
"required",
"in",
"the",
"cluster",
".",
":"... | python | train | 53.190476 |
StackStorm/pybind | pybind/slxos/v17s_1_02/openflow_state/__init__.py | https://github.com/StackStorm/pybind/blob/44c467e71b2b425be63867aba6e6fa28b2cfe7fb/pybind/slxos/v17s_1_02/openflow_state/__init__.py#L503-L524 | def _set_queues_interface(self, v, load=False):
"""
Setter method for queues_interface, mapped from YANG variable /openflow_state/queues_interface (container)
If this variable is read-only (config: false) in the
source YANG file, then _set_queues_interface is considered as a private
method. Backends... | [
"def",
"_set_queues_interface",
"(",
"self",
",",
"v",
",",
"load",
"=",
"False",
")",
":",
"if",
"hasattr",
"(",
"v",
",",
"\"_utype\"",
")",
":",
"v",
"=",
"v",
".",
"_utype",
"(",
"v",
")",
"try",
":",
"t",
"=",
"YANGDynClass",
"(",
"v",
",",
... | Setter method for queues_interface, mapped from YANG variable /openflow_state/queues_interface (container)
If this variable is read-only (config: false) in the
source YANG file, then _set_queues_interface is considered as a private
method. Backends looking to populate this variable should
do so via call... | [
"Setter",
"method",
"for",
"queues_interface",
"mapped",
"from",
"YANG",
"variable",
"/",
"openflow_state",
"/",
"queues_interface",
"(",
"container",
")",
"If",
"this",
"variable",
"is",
"read",
"-",
"only",
"(",
"config",
":",
"false",
")",
"in",
"the",
"s... | python | train | 81.590909 |
merll/docker-map | dockermap/map/runner/base.py | https://github.com/merll/docker-map/blob/e14fe86a6ff5c33d121eb2f9157e9359cb80dd02/dockermap/map/runner/base.py#L48-L62 | def create_network(self, action, n_name, **kwargs):
"""
Creates a configured network.
:param action: Action configuration.
:type action: dockermap.map.runner.ActionConfig
:param n_name: Network name.
:type n_name: unicode | str
:param kwargs: Additional keyword a... | [
"def",
"create_network",
"(",
"self",
",",
"action",
",",
"n_name",
",",
"*",
"*",
"kwargs",
")",
":",
"c_kwargs",
"=",
"self",
".",
"get_network_create_kwargs",
"(",
"action",
",",
"n_name",
",",
"*",
"*",
"kwargs",
")",
"res",
"=",
"action",
".",
"cl... | Creates a configured network.
:param action: Action configuration.
:type action: dockermap.map.runner.ActionConfig
:param n_name: Network name.
:type n_name: unicode | str
:param kwargs: Additional keyword arguments to complement or override the configuration-based values.
... | [
"Creates",
"a",
"configured",
"network",
"."
] | python | train | 42.4 |
pudo/jsongraph | jsongraph/query.py | https://github.com/pudo/jsongraph/blob/35e4f397dbe69cd5553cf9cb9ab98859c3620f03/jsongraph/query.py#L56-L66 | def get_name(self, data):
""" For non-specific queries, this will return the actual name in the
result. """
if self.node.specific_attribute:
return self.node.name
name = data.get(self.predicate_var)
if str(RDF.type) in [self.node.name, name]:
return '$sche... | [
"def",
"get_name",
"(",
"self",
",",
"data",
")",
":",
"if",
"self",
".",
"node",
".",
"specific_attribute",
":",
"return",
"self",
".",
"node",
".",
"name",
"name",
"=",
"data",
".",
"get",
"(",
"self",
".",
"predicate_var",
")",
"if",
"str",
"(",
... | For non-specific queries, this will return the actual name in the
result. | [
"For",
"non",
"-",
"specific",
"queries",
"this",
"will",
"return",
"the",
"actual",
"name",
"in",
"the",
"result",
"."
] | python | train | 36.636364 |
safarijv/sbo-selenium | sbo_selenium/management/commands/selenium.py | https://github.com/safarijv/sbo-selenium/blob/16539f1b17cda18270033db3b64ab25bc05c5664/sbo_selenium/management/commands/selenium.py#L73-L140 | def handle(self, *args, **options):
"""
Run the specified Selenium test(s) the indicated number of times in
the specified browser.
"""
browser_name = options['browser_name']
count = options['count']
if len(args) > 0:
tests = list(args)
else:
... | [
"def",
"handle",
"(",
"self",
",",
"*",
"args",
",",
"*",
"*",
"options",
")",
":",
"browser_name",
"=",
"options",
"[",
"'browser_name'",
"]",
"count",
"=",
"options",
"[",
"'count'",
"]",
"if",
"len",
"(",
"args",
")",
">",
"0",
":",
"tests",
"="... | Run the specified Selenium test(s) the indicated number of times in
the specified browser. | [
"Run",
"the",
"specified",
"Selenium",
"test",
"(",
"s",
")",
"the",
"indicated",
"number",
"of",
"times",
"in",
"the",
"specified",
"browser",
"."
] | python | train | 37.544118 |
data61/clkhash | clkhash/schema.py | https://github.com/data61/clkhash/blob/ec6398d6708a063de83f7c3d6286587bff8e7121/clkhash/schema.py#L181-L198 | def from_json_file(schema_file, validate=True):
# type: (TextIO, bool) -> Schema
""" Load a Schema object from a json file.
:param schema_file: A JSON file containing the schema.
:param validate: (default True) Raise an exception if the
schema does not conform to the master schema.
... | [
"def",
"from_json_file",
"(",
"schema_file",
",",
"validate",
"=",
"True",
")",
":",
"# type: (TextIO, bool) -> Schema",
"try",
":",
"schema_dict",
"=",
"json",
".",
"load",
"(",
"schema_file",
")",
"except",
"ValueError",
"as",
"e",
":",
"# In Python 3 we can be ... | Load a Schema object from a json file.
:param schema_file: A JSON file containing the schema.
:param validate: (default True) Raise an exception if the
schema does not conform to the master schema.
:raises SchemaError: When the schema is invalid.
:return: the Schema | [
"Load",
"a",
"Schema",
"object",
"from",
"a",
"json",
"file",
".",
":",
"param",
"schema_file",
":",
"A",
"JSON",
"file",
"containing",
"the",
"schema",
".",
":",
"param",
"validate",
":",
"(",
"default",
"True",
")",
"Raise",
"an",
"exception",
"if",
... | python | train | 42.111111 |
twisted/txaws | txaws/server/registry.py | https://github.com/twisted/txaws/blob/5c3317376cd47e536625027e38c3b37840175ce0/txaws/server/registry.py#L46-L54 | def scan(self, module, onerror=None, ignore=None):
"""Scan the given module object for L{Method}s and register them."""
from venusian import Scanner
scanner = Scanner(registry=self)
kwargs = {"onerror": onerror, "categories": ["method"]}
if ignore is not None:
# Only ... | [
"def",
"scan",
"(",
"self",
",",
"module",
",",
"onerror",
"=",
"None",
",",
"ignore",
"=",
"None",
")",
":",
"from",
"venusian",
"import",
"Scanner",
"scanner",
"=",
"Scanner",
"(",
"registry",
"=",
"self",
")",
"kwargs",
"=",
"{",
"\"onerror\"",
":",... | Scan the given module object for L{Method}s and register them. | [
"Scan",
"the",
"given",
"module",
"object",
"for",
"L",
"{",
"Method",
"}",
"s",
"and",
"register",
"them",
"."
] | python | train | 48.555556 |
zyga/python-glibc | pyglibc/_subreaper.py | https://github.com/zyga/python-glibc/blob/d6fdb306b123a995471584a5201155c60a34448a/pyglibc/_subreaper.py#L103-L143 | def enabled(self):
"""
read or write the child sub-reaper flag of the current process
This property behaves in the following manner:
* If a read is attempted and a prior read or write has determined that
this feature is unavailable (status is equal to ``SR_UNSUPPORTED``)
... | [
"def",
"enabled",
"(",
"self",
")",
":",
"if",
"self",
".",
"_status",
"==",
"self",
".",
"SR_UNSUPPORTED",
":",
"return",
"False",
"status",
"=",
"c_int",
"(",
")",
"try",
":",
"prctl",
"(",
"PR_GET_CHILD_SUBREAPER",
",",
"addressof",
"(",
"status",
")"... | read or write the child sub-reaper flag of the current process
This property behaves in the following manner:
* If a read is attempted and a prior read or write has determined that
this feature is unavailable (status is equal to ``SR_UNSUPPORTED``)
then no further attempts are made... | [
"read",
"or",
"write",
"the",
"child",
"sub",
"-",
"reaper",
"flag",
"of",
"the",
"current",
"process"
] | python | train | 53.780488 |
duniter/duniter-python-api | duniterpy/api/bma/wot.py | https://github.com/duniter/duniter-python-api/blob/3a1e5d61a2f72f5afaf29d010c6cf4dff3648165/duniterpy/api/bma/wot.py#L404-L412 | async def identity_of(client: Client, search: str) -> dict:
"""
GET Identity data written in the blockchain
:param client: Client to connect to the api
:param search: UID or public key
:return:
"""
return await client.get(MODULE + '/identity-of/%s' % search, schema=IDENTITY_OF_SCHEMA) | [
"async",
"def",
"identity_of",
"(",
"client",
":",
"Client",
",",
"search",
":",
"str",
")",
"->",
"dict",
":",
"return",
"await",
"client",
".",
"get",
"(",
"MODULE",
"+",
"'/identity-of/%s'",
"%",
"search",
",",
"schema",
"=",
"IDENTITY_OF_SCHEMA",
")"
] | GET Identity data written in the blockchain
:param client: Client to connect to the api
:param search: UID or public key
:return: | [
"GET",
"Identity",
"data",
"written",
"in",
"the",
"blockchain"
] | python | train | 34 |
candango/firenado | firenado/launcher.py | https://github.com/candango/firenado/blob/4b1f628e485b521e161d64169c46a9818f26949f/firenado/launcher.py#L208-L223 | def sig_handler(self, sig, _):
""" Handle the signal sent to the process
:param sig: Signal set to the process
:param _: Frame is not being used
"""
import tornado.ioloop
from tornado.process import task_id
tid = task_id()
pid = os.getpid()
if tid... | [
"def",
"sig_handler",
"(",
"self",
",",
"sig",
",",
"_",
")",
":",
"import",
"tornado",
".",
"ioloop",
"from",
"tornado",
".",
"process",
"import",
"task_id",
"tid",
"=",
"task_id",
"(",
")",
"pid",
"=",
"os",
".",
"getpid",
"(",
")",
"if",
"tid",
... | Handle the signal sent to the process
:param sig: Signal set to the process
:param _: Frame is not being used | [
"Handle",
"the",
"signal",
"sent",
"to",
"the",
"process",
":",
"param",
"sig",
":",
"Signal",
"set",
"to",
"the",
"process",
":",
"param",
"_",
":",
"Frame",
"is",
"not",
"being",
"used"
] | python | train | 38.5625 |
orb-framework/orb | orb/core/column_types/string.py | https://github.com/orb-framework/orb/blob/575be2689cb269e65a0a2678232ff940acc19e5a/orb/core/column_types/string.py#L392-L408 | def generate(self):
"""
Generates a new token for this column based on its bit length. This method
will not ensure uniqueness in the model itself, that should be checked against
the model records in the database first.
:return: <str>
"""
try:
mode... | [
"def",
"generate",
"(",
"self",
")",
":",
"try",
":",
"model",
"=",
"self",
".",
"schema",
"(",
")",
".",
"model",
"(",
")",
"except",
"AttributeError",
":",
"return",
"os",
".",
"urandom",
"(",
"self",
".",
"__bits",
")",
".",
"encode",
"(",
"'hex... | Generates a new token for this column based on its bit length. This method
will not ensure uniqueness in the model itself, that should be checked against
the model records in the database first.
:return: <str> | [
"Generates",
"a",
"new",
"token",
"for",
"this",
"column",
"based",
"on",
"its",
"bit",
"length",
".",
"This",
"method",
"will",
"not",
"ensure",
"uniqueness",
"in",
"the",
"model",
"itself",
"that",
"should",
"be",
"checked",
"against",
"the",
"model",
"r... | python | train | 36.941176 |
ray-project/ray | python/ray/tune/suggest/bayesopt.py | https://github.com/ray-project/ray/blob/4eade036a0505e244c976f36aaa2d64386b5129b/python/ray/tune/suggest/bayesopt.py#L79-L90 | def on_trial_complete(self,
trial_id,
result=None,
error=False,
early_terminated=False):
"""Passes the result to BayesOpt unless early terminated or errored"""
if result:
self.optimizer.re... | [
"def",
"on_trial_complete",
"(",
"self",
",",
"trial_id",
",",
"result",
"=",
"None",
",",
"error",
"=",
"False",
",",
"early_terminated",
"=",
"False",
")",
":",
"if",
"result",
":",
"self",
".",
"optimizer",
".",
"register",
"(",
"params",
"=",
"self",... | Passes the result to BayesOpt unless early terminated or errored | [
"Passes",
"the",
"result",
"to",
"BayesOpt",
"unless",
"early",
"terminated",
"or",
"errored"
] | python | train | 39.416667 |
kytos/kytos-utils | kytos/utils/napps.py | https://github.com/kytos/kytos-utils/blob/b4750c618d15cff75970ea6124bda4d2b9a33578/kytos/utils/napps.py#L292-L307 | def install_remote(self):
"""Download, extract and install NApp."""
package, pkg_folder = None, None
try:
package = self._download()
pkg_folder = self._extract(package)
napp_folder = self._get_local_folder(pkg_folder)
dst = self._installed / self.u... | [
"def",
"install_remote",
"(",
"self",
")",
":",
"package",
",",
"pkg_folder",
"=",
"None",
",",
"None",
"try",
":",
"package",
"=",
"self",
".",
"_download",
"(",
")",
"pkg_folder",
"=",
"self",
".",
"_extract",
"(",
"package",
")",
"napp_folder",
"=",
... | Download, extract and install NApp. | [
"Download",
"extract",
"and",
"install",
"NApp",
"."
] | python | train | 39.375 |
mitsei/dlkit | dlkit/records/assessment/basic/multi_choice_records.py | https://github.com/mitsei/dlkit/blob/445f968a175d61c8d92c0f617a3c17dc1dc7c584/dlkit/records/assessment/basic/multi_choice_records.py#L141-L149 | def clear_choice(self, choice):
"""stub"""
if len(self.my_osid_object_form._my_map['choices']) == 0:
raise IllegalState('there are currently no choices defined for this question')
if (len(self.my_osid_object_form._my_map['choices']) == 1 and
choice in self.my_osid_obj... | [
"def",
"clear_choice",
"(",
"self",
",",
"choice",
")",
":",
"if",
"len",
"(",
"self",
".",
"my_osid_object_form",
".",
"_my_map",
"[",
"'choices'",
"]",
")",
"==",
"0",
":",
"raise",
"IllegalState",
"(",
"'there are currently no choices defined for this question'... | stub | [
"stub"
] | python | train | 57.111111 |
developmentseed/landsat-util | landsat/utils.py | https://github.com/developmentseed/landsat-util/blob/92dc81771ddaa64a8a9124a89a6516b52485374b/landsat/utils.py#L167-L188 | def three_digit(number):
""" Add 0s to inputs that their length is less than 3.
:param number:
The number to convert
:type number:
int
:returns:
String
:example:
>>> three_digit(1)
'001'
"""
number = str(number)
if len(number) == 1:
retu... | [
"def",
"three_digit",
"(",
"number",
")",
":",
"number",
"=",
"str",
"(",
"number",
")",
"if",
"len",
"(",
"number",
")",
"==",
"1",
":",
"return",
"u'00%s'",
"%",
"number",
"elif",
"len",
"(",
"number",
")",
"==",
"2",
":",
"return",
"u'0%s'",
"%"... | Add 0s to inputs that their length is less than 3.
:param number:
The number to convert
:type number:
int
:returns:
String
:example:
>>> three_digit(1)
'001' | [
"Add",
"0s",
"to",
"inputs",
"that",
"their",
"length",
"is",
"less",
"than",
"3",
"."
] | python | train | 18.545455 |
gccxml/pygccxml | pygccxml/declarations/pointer_traits.py | https://github.com/gccxml/pygccxml/blob/2b1efbb9e37ceb2ae925c7f3ce1570f476db9e1e/pygccxml/declarations/pointer_traits.py#L116-L129 | def _search_in_bases(type_):
"""Implementation detail."""
found = False
for base_type in type_.declaration.bases:
try:
found = internal_type_traits.get_by_name(
base_type.related_class, "element_type")
except runtime_errors.declaration_not_found_t:
pas... | [
"def",
"_search_in_bases",
"(",
"type_",
")",
":",
"found",
"=",
"False",
"for",
"base_type",
"in",
"type_",
".",
"declaration",
".",
"bases",
":",
"try",
":",
"found",
"=",
"internal_type_traits",
".",
"get_by_name",
"(",
"base_type",
".",
"related_class",
... | Implementation detail. | [
"Implementation",
"detail",
"."
] | python | train | 34.285714 |
SmokinCaterpillar/pypet | pypet/pypetlogging.py | https://github.com/SmokinCaterpillar/pypet/blob/97ad3e80d46dbdea02deeb98ea41f05a19565826/pypet/pypetlogging.py#L417-L445 | def _check_and_replace_parser_args(parser, section, option, rename_func, make_dirs=True):
""" Searches for parser settings that define filenames.
If such settings are found, they are renamed according to the wildcard
rules. Moreover, it is also tried to create the corresponding folders.
... | [
"def",
"_check_and_replace_parser_args",
"(",
"parser",
",",
"section",
",",
"option",
",",
"rename_func",
",",
"make_dirs",
"=",
"True",
")",
":",
"args",
"=",
"parser",
".",
"get",
"(",
"section",
",",
"option",
",",
"raw",
"=",
"True",
")",
"strings",
... | Searches for parser settings that define filenames.
If such settings are found, they are renamed according to the wildcard
rules. Moreover, it is also tried to create the corresponding folders.
:param parser: A config parser
:param section: A config section
:param option: The ... | [
"Searches",
"for",
"parser",
"settings",
"that",
"define",
"filenames",
"."
] | python | test | 44.482759 |
pyviz/holoviews | holoviews/__init__.py | https://github.com/pyviz/holoviews/blob/ae0dd2f3de448b0ca5e9065aabd6ef8d84c7e655/holoviews/__init__.py#L66-L88 | def help(obj, visualization=True, ansi=True, backend=None,
recursive=False, pattern=None):
"""
Extended version of the built-in help that supports parameterized
functions and objects. A pattern (regular expression) may be used to
filter the output and if recursive is set to True, documentation ... | [
"def",
"help",
"(",
"obj",
",",
"visualization",
"=",
"True",
",",
"ansi",
"=",
"True",
",",
"backend",
"=",
"None",
",",
"recursive",
"=",
"False",
",",
"pattern",
"=",
"None",
")",
":",
"backend",
"=",
"backend",
"if",
"backend",
"else",
"Store",
"... | Extended version of the built-in help that supports parameterized
functions and objects. A pattern (regular expression) may be used to
filter the output and if recursive is set to True, documentation for
the supplied object is shown. Note that the recursive option will
only work with an object instance ... | [
"Extended",
"version",
"of",
"the",
"built",
"-",
"in",
"help",
"that",
"supports",
"parameterized",
"functions",
"and",
"objects",
".",
"A",
"pattern",
"(",
"regular",
"expression",
")",
"may",
"be",
"used",
"to",
"filter",
"the",
"output",
"and",
"if",
"... | python | train | 44.086957 |
DataONEorg/d1_python | lib_common/src/d1_common/utils/filesystem.py | https://github.com/DataONEorg/d1_python/blob/3ac4d4f3ca052d3e8641a6a329cab526c8ddcb0d/lib_common/src/d1_common/utils/filesystem.py#L115-L130 | def abs_path(rel_path):
"""Convert a path that is relative to the module from which this function is called,
to an absolute path.
Args:
rel_path: str
Path relative to the location of the module file from which this function is called.
Returns:
str : Absolute path to the location ... | [
"def",
"abs_path",
"(",
"rel_path",
")",
":",
"# noinspection PyProtectedMember",
"return",
"os",
".",
"path",
".",
"abspath",
"(",
"os",
".",
"path",
".",
"join",
"(",
"os",
".",
"path",
".",
"dirname",
"(",
"sys",
".",
"_getframe",
"(",
"1",
")",
"."... | Convert a path that is relative to the module from which this function is called,
to an absolute path.
Args:
rel_path: str
Path relative to the location of the module file from which this function is called.
Returns:
str : Absolute path to the location specified by ``rel_path``. | [
"Convert",
"a",
"path",
"that",
"is",
"relative",
"to",
"the",
"module",
"from",
"which",
"this",
"function",
"is",
"called",
"to",
"an",
"absolute",
"path",
"."
] | python | train | 31 |
argaen/python-google-distance-matrix | google_distance_matrix/core.py | https://github.com/argaen/python-google-distance-matrix/blob/20c07bf7d560180ef380b3148616f67f55246a5c/google_distance_matrix/core.py#L112-L130 | def get_closest_points(self, max_distance=None, origin_index=0, origin_raw=None):
"""
Get closest points to a given origin. Returns a list of 2 element tuples where first element is the destination and the second is the distance.
"""
if not self.dict_response['distance']['value']:
... | [
"def",
"get_closest_points",
"(",
"self",
",",
"max_distance",
"=",
"None",
",",
"origin_index",
"=",
"0",
",",
"origin_raw",
"=",
"None",
")",
":",
"if",
"not",
"self",
".",
"dict_response",
"[",
"'distance'",
"]",
"[",
"'value'",
"]",
":",
"self",
".",... | Get closest points to a given origin. Returns a list of 2 element tuples where first element is the destination and the second is the distance. | [
"Get",
"closest",
"points",
"to",
"a",
"given",
"origin",
".",
"Returns",
"a",
"list",
"of",
"2",
"element",
"tuples",
"where",
"first",
"element",
"is",
"the",
"destination",
"and",
"the",
"second",
"is",
"the",
"distance",
"."
] | python | train | 42.684211 |
idlesign/uwsgiconf | uwsgiconf/options/routing_routers.py | https://github.com/idlesign/uwsgiconf/blob/475407acb44199edbf7e0a66261bfeb51de1afae/uwsgiconf/options/routing_routers.py#L726-L747 | def set_connections_params(
self, harakiri=None, timeout_socket=None, retry_delay=None, retry_max=None, use_xclient=None):
"""Sets connection-related parameters.
:param int harakiri: Set gateway harakiri timeout (seconds).
:param int timeout_socket: Node socket timeout (seconds). ... | [
"def",
"set_connections_params",
"(",
"self",
",",
"harakiri",
"=",
"None",
",",
"timeout_socket",
"=",
"None",
",",
"retry_delay",
"=",
"None",
",",
"retry_max",
"=",
"None",
",",
"use_xclient",
"=",
"None",
")",
":",
"super",
"(",
"RouterRaw",
",",
"self... | Sets connection-related parameters.
:param int harakiri: Set gateway harakiri timeout (seconds).
:param int timeout_socket: Node socket timeout (seconds). Default: 60.
:param int retry_delay: Retry connections to dead static nodes after the specified
amount of seconds. Default: 3... | [
"Sets",
"connection",
"-",
"related",
"parameters",
"."
] | python | train | 39.863636 |
opencobra/cobrapy | cobra/core/gene.py | https://github.com/opencobra/cobrapy/blob/9d1987cdb3a395cf4125a3439c3b002ff2be2009/cobra/core/gene.py#L206-L216 | def knock_out(self):
"""Knockout gene by marking it as non-functional and setting all
associated reactions bounds to zero.
The change is reverted upon exit if executed within the model as
context.
"""
self.functional = False
for reaction in self.reactions:
... | [
"def",
"knock_out",
"(",
"self",
")",
":",
"self",
".",
"functional",
"=",
"False",
"for",
"reaction",
"in",
"self",
".",
"reactions",
":",
"if",
"not",
"reaction",
".",
"functional",
":",
"reaction",
".",
"bounds",
"=",
"(",
"0",
",",
"0",
")"
] | Knockout gene by marking it as non-functional and setting all
associated reactions bounds to zero.
The change is reverted upon exit if executed within the model as
context. | [
"Knockout",
"gene",
"by",
"marking",
"it",
"as",
"non",
"-",
"functional",
"and",
"setting",
"all",
"associated",
"reactions",
"bounds",
"to",
"zero",
"."
] | python | valid | 34.909091 |
iotile/coretools | iotilebuild/iotile/build/config/scons-local-3.0.1/SCons/Node/__init__.py | https://github.com/iotile/coretools/blob/2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec/iotilebuild/iotile/build/config/scons-local-3.0.1/SCons/Node/__init__.py#L1232-L1242 | def add_dependency(self, depend):
"""Adds dependencies."""
try:
self._add_child(self.depends, self.depends_set, depend)
except TypeError as e:
e = e.args[0]
if SCons.Util.is_List(e):
s = list(map(str, e))
else:
s = s... | [
"def",
"add_dependency",
"(",
"self",
",",
"depend",
")",
":",
"try",
":",
"self",
".",
"_add_child",
"(",
"self",
".",
"depends",
",",
"self",
".",
"depends_set",
",",
"depend",
")",
"except",
"TypeError",
"as",
"e",
":",
"e",
"=",
"e",
".",
"args",... | Adds dependencies. | [
"Adds",
"dependencies",
"."
] | python | train | 41.545455 |
dunovank/jupyter-themes | jupyterthemes/jtplot.py | https://github.com/dunovank/jupyter-themes/blob/421016c2e4fed75fa1830d664c10478d9bd25ed1/jupyterthemes/jtplot.py#L215-L223 | def figsize(x=8, y=7., aspect=1.):
""" manually set the default figure size of plots
::Arguments::
x (float): x-axis size
y (float): y-axis size
aspect (float): aspect ratio scalar
"""
# update rcparams with adjusted figsize params
mpl.rcParams.update({'figure.figsize': (x*as... | [
"def",
"figsize",
"(",
"x",
"=",
"8",
",",
"y",
"=",
"7.",
",",
"aspect",
"=",
"1.",
")",
":",
"# update rcparams with adjusted figsize params",
"mpl",
".",
"rcParams",
".",
"update",
"(",
"{",
"'figure.figsize'",
":",
"(",
"x",
"*",
"aspect",
",",
"y",
... | manually set the default figure size of plots
::Arguments::
x (float): x-axis size
y (float): y-axis size
aspect (float): aspect ratio scalar | [
"manually",
"set",
"the",
"default",
"figure",
"size",
"of",
"plots",
"::",
"Arguments",
"::",
"x",
"(",
"float",
")",
":",
"x",
"-",
"axis",
"size",
"y",
"(",
"float",
")",
":",
"y",
"-",
"axis",
"size",
"aspect",
"(",
"float",
")",
":",
"aspect",... | python | train | 35.777778 |
housecanary/hc-api-python | housecanary/object.py | https://github.com/housecanary/hc-api-python/blob/2bb9e2208b34e8617575de45934357ee33b8531c/housecanary/object.py#L243-L259 | def create_from_json(cls, json_data):
"""Deserialize msa json data into a Msa object
Args:
json_data (dict): The json data for this msa
Returns:
Msa object
"""
msa = Msa()
msa.msa = json_data["msa_info"]["msa"]
msa.meta = json_data["meta... | [
"def",
"create_from_json",
"(",
"cls",
",",
"json_data",
")",
":",
"msa",
"=",
"Msa",
"(",
")",
"msa",
".",
"msa",
"=",
"json_data",
"[",
"\"msa_info\"",
"]",
"[",
"\"msa\"",
"]",
"msa",
".",
"meta",
"=",
"json_data",
"[",
"\"meta\"",
"]",
"if",
"\"m... | Deserialize msa json data into a Msa object
Args:
json_data (dict): The json data for this msa
Returns:
Msa object | [
"Deserialize",
"msa",
"json",
"data",
"into",
"a",
"Msa",
"object"
] | python | train | 25.941176 |
tortoise/tortoise-orm | tortoise/queryset.py | https://github.com/tortoise/tortoise-orm/blob/7d16457731905e19d4d06ccd5b4ea16d4a9447b2/tortoise/queryset.py#L351-L358 | def first(self) -> "QuerySet":
"""
Limit queryset to one object and return one object instead of list.
"""
queryset = self._clone()
queryset._limit = 1
queryset._single = True
return queryset | [
"def",
"first",
"(",
"self",
")",
"->",
"\"QuerySet\"",
":",
"queryset",
"=",
"self",
".",
"_clone",
"(",
")",
"queryset",
".",
"_limit",
"=",
"1",
"queryset",
".",
"_single",
"=",
"True",
"return",
"queryset"
] | Limit queryset to one object and return one object instead of list. | [
"Limit",
"queryset",
"to",
"one",
"object",
"and",
"return",
"one",
"object",
"instead",
"of",
"list",
"."
] | python | train | 30 |
wummel/linkchecker | linkcheck/updater.py | https://github.com/wummel/linkchecker/blob/c2ce810c3fb00b895a841a7be6b2e78c64e7b042/linkcheck/updater.py#L57-L71 | def get_online_version ():
"""Download update info and parse it."""
# prevent getting a cached answer
headers = {'Pragma': 'no-cache', 'Cache-Control': 'no-cache'}
content, info = get_content(UPDATE_URL, addheaders=headers)
if content is None:
return content, info
version, url = None, No... | [
"def",
"get_online_version",
"(",
")",
":",
"# prevent getting a cached answer",
"headers",
"=",
"{",
"'Pragma'",
":",
"'no-cache'",
",",
"'Cache-Control'",
":",
"'no-cache'",
"}",
"content",
",",
"info",
"=",
"get_content",
"(",
"UPDATE_URL",
",",
"addheaders",
"... | Download update info and parse it. | [
"Download",
"update",
"info",
"and",
"parse",
"it",
"."
] | python | train | 40.2 |
MartinThoma/hwrt | hwrt/handwritten_data.py | https://github.com/MartinThoma/hwrt/blob/725c21a3d0f5a30b8492cbc184b3688ceb364e1c/hwrt/handwritten_data.py#L299-L311 | def get_center_of_mass(self):
"""
Get a tuple (x,y) that is the center of mass. The center of mass is not
necessarily the same as the center of the bounding box. Imagine a black
square and a single dot wide outside of the square.
"""
xsum, ysum, counter = 0., 0., 0
... | [
"def",
"get_center_of_mass",
"(",
"self",
")",
":",
"xsum",
",",
"ysum",
",",
"counter",
"=",
"0.",
",",
"0.",
",",
"0",
"for",
"stroke",
"in",
"self",
".",
"get_pointlist",
"(",
")",
":",
"for",
"point",
"in",
"stroke",
":",
"xsum",
"+=",
"point",
... | Get a tuple (x,y) that is the center of mass. The center of mass is not
necessarily the same as the center of the bounding box. Imagine a black
square and a single dot wide outside of the square. | [
"Get",
"a",
"tuple",
"(",
"x",
"y",
")",
"that",
"is",
"the",
"center",
"of",
"mass",
".",
"The",
"center",
"of",
"mass",
"is",
"not",
"necessarily",
"the",
"same",
"as",
"the",
"center",
"of",
"the",
"bounding",
"box",
".",
"Imagine",
"a",
"black",
... | python | train | 40.384615 |
Miserlou/django-knockout-modeler | knockout_modeler/ko.py | https://github.com/Miserlou/django-knockout-modeler/blob/714d21cc5ed008f132cea01dbae9f214c2bf1b76/knockout_modeler/ko.py#L18-L37 | def get_fields(model):
"""
Returns a Model's knockout_fields,
or the default set of field names.
"""
try:
if hasattr(model, "knockout_fields"):
fields = model.knockout_fields()
else:
try:
fields = model_to_dict(model).keys()
except... | [
"def",
"get_fields",
"(",
"model",
")",
":",
"try",
":",
"if",
"hasattr",
"(",
"model",
",",
"\"knockout_fields\"",
")",
":",
"fields",
"=",
"model",
".",
"knockout_fields",
"(",
")",
"else",
":",
"try",
":",
"fields",
"=",
"model_to_dict",
"(",
"model",... | Returns a Model's knockout_fields,
or the default set of field names. | [
"Returns",
"a",
"Model",
"s",
"knockout_fields",
"or",
"the",
"default",
"set",
"of",
"field",
"names",
"."
] | python | train | 24.2 |
swharden/SWHLab | swhlab/core.py | https://github.com/swharden/SWHLab/blob/a86c3c65323cec809a4bd4f81919644927094bf5/swhlab/core.py#L109-L169 | def setsweep(self, sweep=0, channel=0):
"""set the sweep and channel of an ABF. Both start at 0."""
try:
sweep=int(sweep)
except:
self.log.error("trying to set sweep to [%s]",sweep)
return
if sweep<0:
sweep=self.sweeps-1-sweep # if negative... | [
"def",
"setsweep",
"(",
"self",
",",
"sweep",
"=",
"0",
",",
"channel",
"=",
"0",
")",
":",
"try",
":",
"sweep",
"=",
"int",
"(",
"sweep",
")",
"except",
":",
"self",
".",
"log",
".",
"error",
"(",
"\"trying to set sweep to [%s]\"",
",",
"sweep",
")"... | set the sweep and channel of an ABF. Both start at 0. | [
"set",
"the",
"sweep",
"and",
"channel",
"of",
"an",
"ABF",
".",
"Both",
"start",
"at",
"0",
"."
] | python | valid | 52.721311 |
JoseAntFer/pyny3d | pyny3d/geoms.py | https://github.com/JoseAntFer/pyny3d/blob/fb81684935a24f7e50c975cb4383c81a63ab56df/pyny3d/geoms.py#L876-L947 | def melt(self, plot=False):
"""
Find and merge groups of polygons in the surface that meet the
following criteria:
* Are coplanars.
* Are contiguous.
* The result is convex.
This method is very useful at reducing the num... | [
"def",
"melt",
"(",
"self",
",",
"plot",
"=",
"False",
")",
":",
"from",
"pyny3d",
".",
"utils",
"import",
"bool2index",
"from",
"scipy",
".",
"spatial",
"import",
"ConvexHull",
"# First, coplanarity\r",
"## Normalize parametric equations\r",
"para",
"=",
"[",
"... | Find and merge groups of polygons in the surface that meet the
following criteria:
* Are coplanars.
* Are contiguous.
* The result is convex.
This method is very useful at reducing the number the items and,
therefore, the shadowi... | [
"Find",
"and",
"merge",
"groups",
"of",
"polygons",
"in",
"the",
"surface",
"that",
"meet",
"the",
"following",
"criteria",
":",
"*",
"Are",
"coplanars",
".",
"*",
"Are",
"contiguous",
".",
"*",
"The",
"result",
"is",
"convex",
".",
"This",
"method",
"is... | python | train | 38.611111 |
StanfordBioinformatics/loom | server/loomengine_server/api/async.py | https://github.com/StanfordBioinformatics/loom/blob/db2031a1a87124fee1aeb7414a668c03d774a698/server/loomengine_server/api/async.py#L66-L81 | def check_for_missed_cleanup():
"""Check for TaskAttempts that were never cleaned up
"""
if get_setting('PRESERVE_ALL'):
return
from api.models.tasks import TaskAttempt
if get_setting('PRESERVE_ON_FAILURE'):
for task_attempt in TaskAttempt.objects.filter(
status_is_ru... | [
"def",
"check_for_missed_cleanup",
"(",
")",
":",
"if",
"get_setting",
"(",
"'PRESERVE_ALL'",
")",
":",
"return",
"from",
"api",
".",
"models",
".",
"tasks",
"import",
"TaskAttempt",
"if",
"get_setting",
"(",
"'PRESERVE_ON_FAILURE'",
")",
":",
"for",
"task_attem... | Check for TaskAttempts that were never cleaned up | [
"Check",
"for",
"TaskAttempts",
"that",
"were",
"never",
"cleaned",
"up"
] | python | train | 40.1875 |
AguaClara/aguaclara | aguaclara/core/physchem.py | https://github.com/AguaClara/aguaclara/blob/8dd4e734768b166a7fc2b60388a24df2f93783fc/aguaclara/core/physchem.py#L681-L685 | def vel_horizontal(HeightWaterCritical):
"""Return the horizontal velocity."""
#Checking input validity
ut.check_range([HeightWaterCritical, ">0", "Critical height of water"])
return np.sqrt(gravity.magnitude * HeightWaterCritical) | [
"def",
"vel_horizontal",
"(",
"HeightWaterCritical",
")",
":",
"#Checking input validity",
"ut",
".",
"check_range",
"(",
"[",
"HeightWaterCritical",
",",
"\">0\"",
",",
"\"Critical height of water\"",
"]",
")",
"return",
"np",
".",
"sqrt",
"(",
"gravity",
".",
"m... | Return the horizontal velocity. | [
"Return",
"the",
"horizontal",
"velocity",
"."
] | python | train | 48.6 |
saltstack/salt | salt/modules/event.py | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/event.py#L27-L31 | def _dict_subset(keys, master_dict):
'''
Return a dictionary of only the subset of keys/values specified in keys
'''
return dict([(k, v) for k, v in six.iteritems(master_dict) if k in keys]) | [
"def",
"_dict_subset",
"(",
"keys",
",",
"master_dict",
")",
":",
"return",
"dict",
"(",
"[",
"(",
"k",
",",
"v",
")",
"for",
"k",
",",
"v",
"in",
"six",
".",
"iteritems",
"(",
"master_dict",
")",
"if",
"k",
"in",
"keys",
"]",
")"
] | Return a dictionary of only the subset of keys/values specified in keys | [
"Return",
"a",
"dictionary",
"of",
"only",
"the",
"subset",
"of",
"keys",
"/",
"values",
"specified",
"in",
"keys"
] | python | train | 40.4 |
libtcod/python-tcod | tcod/libtcodpy.py | https://github.com/libtcod/python-tcod/blob/8ba10c5cfb813eaf3e834de971ba2d6acb7838e4/tcod/libtcodpy.py#L1934-L1950 | def console_list_load_xp(
filename: str
) -> Optional[List[tcod.console.Console]]:
"""Return a list of consoles from a REXPaint `.xp` file."""
tcod_list = lib.TCOD_console_list_from_xp(filename.encode("utf-8"))
if tcod_list == ffi.NULL:
return None
try:
python_list = []
lib.T... | [
"def",
"console_list_load_xp",
"(",
"filename",
":",
"str",
")",
"->",
"Optional",
"[",
"List",
"[",
"tcod",
".",
"console",
".",
"Console",
"]",
"]",
":",
"tcod_list",
"=",
"lib",
".",
"TCOD_console_list_from_xp",
"(",
"filename",
".",
"encode",
"(",
"\"u... | Return a list of consoles from a REXPaint `.xp` file. | [
"Return",
"a",
"list",
"of",
"consoles",
"from",
"a",
"REXPaint",
".",
"xp",
"file",
"."
] | python | train | 34.647059 |
ofir123/py-printer | pyprinter/printer.py | https://github.com/ofir123/py-printer/blob/876c83b32120f3b6a7b06989b2cd9b86915d1a50/pyprinter/printer.py#L181-L233 | def write(self, text: str):
"""
Prints text to the screen.
Supports colors by using the color constants.
To use colors, add the color before the text you want to print.
:param text: The text to print.
"""
# Default color is NORMAL.
last_color = (self._DAR... | [
"def",
"write",
"(",
"self",
",",
"text",
":",
"str",
")",
":",
"# Default color is NORMAL.",
"last_color",
"=",
"(",
"self",
".",
"_DARK_CODE",
",",
"0",
")",
"# We use splitlines with keepends in order to keep the line breaks.",
"# Then we split by using the console width... | Prints text to the screen.
Supports colors by using the color constants.
To use colors, add the color before the text you want to print.
:param text: The text to print. | [
"Prints",
"text",
"to",
"the",
"screen",
".",
"Supports",
"colors",
"by",
"using",
"the",
"color",
"constants",
".",
"To",
"use",
"colors",
"add",
"the",
"color",
"before",
"the",
"text",
"you",
"want",
"to",
"print",
"."
] | python | train | 45.811321 |
cggh/scikit-allel | allel/model/ndarray.py | https://github.com/cggh/scikit-allel/blob/3c979a57a100240ba959dd13f98839349530f215/allel/model/ndarray.py#L156-L173 | def query(self, expression, vm='python'):
"""Evaluate expression and then use it to extract rows from the table.
Parameters
----------
expression : string
Expression to evaluate.
vm : {'numexpr', 'python'}
Virtual machine to use.
Returns
... | [
"def",
"query",
"(",
"self",
",",
"expression",
",",
"vm",
"=",
"'python'",
")",
":",
"condition",
"=",
"self",
".",
"eval",
"(",
"expression",
",",
"vm",
"=",
"vm",
")",
"return",
"self",
".",
"compress",
"(",
"condition",
")"
] | Evaluate expression and then use it to extract rows from the table.
Parameters
----------
expression : string
Expression to evaluate.
vm : {'numexpr', 'python'}
Virtual machine to use.
Returns
-------
result : structured array | [
"Evaluate",
"expression",
"and",
"then",
"use",
"it",
"to",
"extract",
"rows",
"from",
"the",
"table",
"."
] | python | train | 24.833333 |
fermiPy/fermipy | fermipy/wcs_utils.py | https://github.com/fermiPy/fermipy/blob/9df5e7e3728307fd58c5bba36fd86783c39fbad4/fermipy/wcs_utils.py#L68-L91 | def distance_to_edge(self, skydir):
"""Return the angular distance from the given direction and
the edge of the projection."""
xpix, ypix = skydir.to_pixel(self.wcs, origin=0)
deltax = np.array((xpix - self._pix_center[0]) * self._pix_size[0],
ndmin=1)
... | [
"def",
"distance_to_edge",
"(",
"self",
",",
"skydir",
")",
":",
"xpix",
",",
"ypix",
"=",
"skydir",
".",
"to_pixel",
"(",
"self",
".",
"wcs",
",",
"origin",
"=",
"0",
")",
"deltax",
"=",
"np",
".",
"array",
"(",
"(",
"xpix",
"-",
"self",
".",
"_... | Return the angular distance from the given direction and
the edge of the projection. | [
"Return",
"the",
"angular",
"distance",
"from",
"the",
"given",
"direction",
"and",
"the",
"edge",
"of",
"the",
"projection",
"."
] | python | train | 41 |
ampl/amplpy | amplpy/parameter.py | https://github.com/ampl/amplpy/blob/39df6954049a11a8f666aed26853259b4687099a/amplpy/parameter.py#L98-L138 | def setValues(self, values):
"""
Assign the values (string or float) to the parameter instances with the
specified indices, equivalent to the AMPL code:
.. code-block:: ampl
let {i in indices} par[i] := values[i];
Args:
values: list, dictionary or :clas... | [
"def",
"setValues",
"(",
"self",
",",
"values",
")",
":",
"if",
"isinstance",
"(",
"values",
",",
"dict",
")",
":",
"indices",
",",
"values",
"=",
"list",
"(",
"zip",
"(",
"*",
"values",
".",
"items",
"(",
")",
")",
")",
"indices",
"=",
"Utils",
... | Assign the values (string or float) to the parameter instances with the
specified indices, equivalent to the AMPL code:
.. code-block:: ampl
let {i in indices} par[i] := values[i];
Args:
values: list, dictionary or :class:`~amplpy.DataFrame` with the
indice... | [
"Assign",
"the",
"values",
"(",
"string",
"or",
"float",
")",
"to",
"the",
"parameter",
"instances",
"with",
"the",
"specified",
"indices",
"equivalent",
"to",
"the",
"AMPL",
"code",
":"
] | python | train | 41.121951 |
proteanhq/protean | src/protean/core/queryset.py | https://github.com/proteanhq/protean/blob/0e29873f4aa634aa93cc08ed675dd749c7ed4b0f/src/protean/core/queryset.py#L243-L264 | def update_all(self, *args, **kwargs):
"""Updates all objects with details given if they match a set of conditions supplied.
This method forwards filters and updates directly to the repository. It does not
instantiate entities and it does not trigger Entity callbacks or validations.
Up... | [
"def",
"update_all",
"(",
"self",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"updated_item_count",
"=",
"0",
"repository",
"=",
"repo_factory",
".",
"get_repository",
"(",
"self",
".",
"_entity_cls",
")",
"try",
":",
"updated_item_count",
"=",
"r... | Updates all objects with details given if they match a set of conditions supplied.
This method forwards filters and updates directly to the repository. It does not
instantiate entities and it does not trigger Entity callbacks or validations.
Update values can be specified either as a dict, or ... | [
"Updates",
"all",
"objects",
"with",
"details",
"given",
"if",
"they",
"match",
"a",
"set",
"of",
"conditions",
"supplied",
"."
] | python | train | 38.818182 |
dmlc/gluon-nlp | scripts/bert/run_pretraining_hvd.py | https://github.com/dmlc/gluon-nlp/blob/4b83eb6bcc8881e5f1081a3675adaa19fac5c0ba/scripts/bert/run_pretraining_hvd.py#L71-L204 | def train(data_train, model, nsp_loss, mlm_loss, vocab_size, ctx):
"""Training function."""
hvd.broadcast_parameters(model.collect_params(), root_rank=0)
mlm_metric = nlp.metric.MaskedAccuracy()
nsp_metric = nlp.metric.MaskedAccuracy()
mlm_metric.reset()
nsp_metric.reset()
logging.debug('C... | [
"def",
"train",
"(",
"data_train",
",",
"model",
",",
"nsp_loss",
",",
"mlm_loss",
",",
"vocab_size",
",",
"ctx",
")",
":",
"hvd",
".",
"broadcast_parameters",
"(",
"model",
".",
"collect_params",
"(",
")",
",",
"root_rank",
"=",
"0",
")",
"mlm_metric",
... | Training function. | [
"Training",
"function",
"."
] | python | train | 42.507463 |
secdev/scapy | scapy/layers/l2.py | https://github.com/secdev/scapy/blob/3ffe757c184017dd46464593a8f80f85abc1e79a/scapy/layers/l2.py#L70-L102 | def getmacbyip(ip, chainCC=0):
"""Return MAC address corresponding to a given IP address"""
if isinstance(ip, Net):
ip = next(iter(ip))
ip = inet_ntoa(inet_aton(ip or "0.0.0.0"))
tmp = [orb(e) for e in inet_aton(ip)]
if (tmp[0] & 0xf0) == 0xe0: # mcast @
return "01:00:5e:%.2x:%.2x:%... | [
"def",
"getmacbyip",
"(",
"ip",
",",
"chainCC",
"=",
"0",
")",
":",
"if",
"isinstance",
"(",
"ip",
",",
"Net",
")",
":",
"ip",
"=",
"next",
"(",
"iter",
"(",
"ip",
")",
")",
"ip",
"=",
"inet_ntoa",
"(",
"inet_aton",
"(",
"ip",
"or",
"\"0.0.0.0\""... | Return MAC address corresponding to a given IP address | [
"Return",
"MAC",
"address",
"corresponding",
"to",
"a",
"given",
"IP",
"address"
] | python | train | 32.272727 |
blockstack/blockstack-core | blockstack/lib/client.py | https://github.com/blockstack/blockstack-core/blob/1dcfdd39b152d29ce13e736a6a1a0981401a0505/blockstack/lib/client.py#L3100-L3138 | def get_name_history(name, hostport=None, proxy=None, history_page=None):
"""
Get the full history of a name
Returns {'status': True, 'history': ...} on success, where history is grouped by block
Returns {'error': ...} on error
"""
assert hostport or proxy, 'Need hostport or proxy'
if proxy ... | [
"def",
"get_name_history",
"(",
"name",
",",
"hostport",
"=",
"None",
",",
"proxy",
"=",
"None",
",",
"history_page",
"=",
"None",
")",
":",
"assert",
"hostport",
"or",
"proxy",
",",
"'Need hostport or proxy'",
"if",
"proxy",
"is",
"None",
":",
"proxy",
"=... | Get the full history of a name
Returns {'status': True, 'history': ...} on success, where history is grouped by block
Returns {'error': ...} on error | [
"Get",
"the",
"full",
"history",
"of",
"a",
"name",
"Returns",
"{",
"status",
":",
"True",
"history",
":",
"...",
"}",
"on",
"success",
"where",
"history",
"is",
"grouped",
"by",
"block",
"Returns",
"{",
"error",
":",
"...",
"}",
"on",
"error"
] | python | train | 31.025641 |
oceanprotocol/oceandb-elasticsearch-driver | oceandb_elasticsearch_driver/plugin.py | https://github.com/oceanprotocol/oceandb-elasticsearch-driver/blob/11901e8396252b9dbb70fd48debcfa82f1dd1ff2/oceandb_elasticsearch_driver/plugin.py#L136-L170 | def query(self, search_model: QueryModel):
"""Query elasticsearch for objects.
:param search_model: object of QueryModel.
:return: list of objects that match the query.
"""
query_parsed = query_parser(search_model.query)
self.logger.debug(f'elasticsearch::query::{query_pa... | [
"def",
"query",
"(",
"self",
",",
"search_model",
":",
"QueryModel",
")",
":",
"query_parsed",
"=",
"query_parser",
"(",
"search_model",
".",
"query",
")",
"self",
".",
"logger",
".",
"debug",
"(",
"f'elasticsearch::query::{query_parsed[0]}'",
")",
"if",
"search... | Query elasticsearch for objects.
:param search_model: object of QueryModel.
:return: list of objects that match the query. | [
"Query",
"elasticsearch",
"for",
"objects",
".",
":",
"param",
"search_model",
":",
"object",
"of",
"QueryModel",
".",
":",
"return",
":",
"list",
"of",
"objects",
"that",
"match",
"the",
"query",
"."
] | python | test | 32.171429 |
mitsei/dlkit | dlkit/json_/osid/metadata.py | https://github.com/mitsei/dlkit/blob/445f968a175d61c8d92c0f617a3c17dc1dc7c584/dlkit/json_/osid/metadata.py#L578-L593 | def supports_calendar_type(self, calendar_type):
"""Tests if the given calendar type is supported.
arg: calendar_type (osid.type.Type): a calendar Type
return: (boolean) - ``true`` if the type is supported, ``false``
otherwise
raise: IllegalState - syntax is not a ``... | [
"def",
"supports_calendar_type",
"(",
"self",
",",
"calendar_type",
")",
":",
"# Implemented from template for osid.Metadata.supports_coordinate_type",
"if",
"self",
".",
"_kwargs",
"[",
"'syntax'",
"]",
"not",
"in",
"[",
"'``DATETIME``'",
",",
"'``DURATION``'",
"]",
":... | Tests if the given calendar type is supported.
arg: calendar_type (osid.type.Type): a calendar Type
return: (boolean) - ``true`` if the type is supported, ``false``
otherwise
raise: IllegalState - syntax is not a ``DATETIME`` or
``DURATION``
raise: N... | [
"Tests",
"if",
"the",
"given",
"calendar",
"type",
"is",
"supported",
"."
] | python | train | 46.1875 |
numenta/nupic | src/nupic/datafiles/extra/gym/raw/makeDataset.py | https://github.com/numenta/nupic/blob/5922fafffdccc8812e72b3324965ad2f7d4bbdad/src/nupic/datafiles/extra/gym/raw/makeDataset.py#L124-L156 | def processClubAttendance(f, clubs):
"""Process the attendance data of one club
If the club already exists in the list update its data.
If the club is new create a new Club object and add it to the dict
The next step is to iterate over all the lines and add a record for each line.
When reaching an empty... | [
"def",
"processClubAttendance",
"(",
"f",
",",
"clubs",
")",
":",
"try",
":",
"# Skip as many empty lines as necessary (file format inconsistent)",
"line",
"=",
"f",
".",
"next",
"(",
")",
"while",
"line",
"==",
"',,,,,,,,,,,,,,,,,,,\\n'",
":",
"line",
"=",
"f",
"... | Process the attendance data of one club
If the club already exists in the list update its data.
If the club is new create a new Club object and add it to the dict
The next step is to iterate over all the lines and add a record for each line.
When reaching an empty line it means there are no more records f... | [
"Process",
"the",
"attendance",
"data",
"of",
"one",
"club",
"If",
"the",
"club",
"already",
"exists",
"in",
"the",
"list",
"update",
"its",
"data",
".",
"If",
"the",
"club",
"is",
"new",
"create",
"a",
"new",
"Club",
"object",
"and",
"add",
"it",
"to"... | python | valid | 33.363636 |
ssato/python-anytemplate | anytemplate/engines/cheetah.py | https://github.com/ssato/python-anytemplate/blob/3e56baa914bd47f044083b20e33100f836443596/anytemplate/engines/cheetah.py#L68-L76 | def supports(cls, template_file=None):
"""
:return: Whether the engine can process given template file or not.
"""
if anytemplate.compat.IS_PYTHON_3:
cls._priority = 99
return False # Always as it's not ported to python 3.
return super(Engine, cls).suppo... | [
"def",
"supports",
"(",
"cls",
",",
"template_file",
"=",
"None",
")",
":",
"if",
"anytemplate",
".",
"compat",
".",
"IS_PYTHON_3",
":",
"cls",
".",
"_priority",
"=",
"99",
"return",
"False",
"# Always as it's not ported to python 3.",
"return",
"super",
"(",
... | :return: Whether the engine can process given template file or not. | [
":",
"return",
":",
"Whether",
"the",
"engine",
"can",
"process",
"given",
"template",
"file",
"or",
"not",
"."
] | python | train | 38.222222 |
petl-developers/petl | petl/transform/intervals.py | https://github.com/petl-developers/petl/blob/1d33ca055f7e04e0d28a772041c9fd30c8d415d6/petl/transform/intervals.py#L91-L108 | def facetrecordtrees(table, key, start='start', stop='stop'):
"""
Construct faceted interval trees for the given table, where each node in
the tree is a record.
"""
import intervaltree
getstart = attrgetter(start)
getstop = attrgetter(stop)
getkey = attrgetter(key)
trees = dict()
... | [
"def",
"facetrecordtrees",
"(",
"table",
",",
"key",
",",
"start",
"=",
"'start'",
",",
"stop",
"=",
"'stop'",
")",
":",
"import",
"intervaltree",
"getstart",
"=",
"attrgetter",
"(",
"start",
")",
"getstop",
"=",
"attrgetter",
"(",
"stop",
")",
"getkey",
... | Construct faceted interval trees for the given table, where each node in
the tree is a record. | [
"Construct",
"faceted",
"interval",
"trees",
"for",
"the",
"given",
"table",
"where",
"each",
"node",
"in",
"the",
"tree",
"is",
"a",
"record",
"."
] | python | train | 28.222222 |
niolabs/python-xbee | xbee/thread/base.py | https://github.com/niolabs/python-xbee/blob/b91be3d0ee7ccaa1990120b5b5490999d8e6cbc7/xbee/thread/base.py#L67-L77 | def halt(self):
"""
halt: None -> None
If this instance has a separate thread running, it will be
halted. This method will wait until the thread has cleaned
up before returning.
"""
if self._callback:
self._thread_continue = False
self._th... | [
"def",
"halt",
"(",
"self",
")",
":",
"if",
"self",
".",
"_callback",
":",
"self",
".",
"_thread_continue",
"=",
"False",
"self",
".",
"_thread",
".",
"join",
"(",
")"
] | halt: None -> None
If this instance has a separate thread running, it will be
halted. This method will wait until the thread has cleaned
up before returning. | [
"halt",
":",
"None",
"-",
">",
"None"
] | python | train | 29.181818 |
twilio/twilio-python | twilio/rest/api/v2010/account/available_phone_number/__init__.py | https://github.com/twilio/twilio-python/blob/c867895f55dcc29f522e6e8b8868d0d18483132f/twilio/rest/api/v2010/account/available_phone_number/__init__.py#L410-L424 | 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: AvailablePhoneNumberCountryContext for this AvailablePhoneNumberCountryInstance
:rtype: twilio.re... | [
"def",
"_proxy",
"(",
"self",
")",
":",
"if",
"self",
".",
"_context",
"is",
"None",
":",
"self",
".",
"_context",
"=",
"AvailablePhoneNumberCountryContext",
"(",
"self",
".",
"_version",
",",
"account_sid",
"=",
"self",
".",
"_solution",
"[",
"'account_sid'... | Generate an instance context for the instance, the context is capable of
performing various actions. All instance actions are proxied to the context
:returns: AvailablePhoneNumberCountryContext for this AvailablePhoneNumberCountryInstance
:rtype: twilio.rest.api.v2010.account.available_phone_n... | [
"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 | 45.866667 |
kamikaze/webdav | src/webdav/client.py | https://github.com/kamikaze/webdav/blob/6facff7224023d3e28c8e1592f3c58401c91a0e6/src/webdav/client.py#L554-L570 | def copy(self, remote_path_from, remote_path_to):
"""Copies resource from one place to another on WebDAV server.
More information you can find by link http://webdav.org/specs/rfc4918.html#METHOD_COPY
:param remote_path_from: the path to resource which will be copied,
:param remote_path_... | [
"def",
"copy",
"(",
"self",
",",
"remote_path_from",
",",
"remote_path_to",
")",
":",
"urn_from",
"=",
"Urn",
"(",
"remote_path_from",
")",
"if",
"not",
"self",
".",
"check",
"(",
"urn_from",
".",
"path",
"(",
")",
")",
":",
"raise",
"RemoteResourceNotFoun... | Copies resource from one place to another on WebDAV server.
More information you can find by link http://webdav.org/specs/rfc4918.html#METHOD_COPY
:param remote_path_from: the path to resource which will be copied,
:param remote_path_to: the path where resource will be copied. | [
"Copies",
"resource",
"from",
"one",
"place",
"to",
"another",
"on",
"WebDAV",
"server",
".",
"More",
"information",
"you",
"can",
"find",
"by",
"link",
"http",
":",
"//",
"webdav",
".",
"org",
"/",
"specs",
"/",
"rfc4918",
".",
"html#METHOD_COPY"
] | python | train | 47.882353 |
django-userena-ce/django-userena-ce | userena/forms.py | https://github.com/django-userena-ce/django-userena-ce/blob/2d8b745eed25128134e961ca96c270802e730256/userena/forms.py#L110-L119 | def save(self):
""" Generate a random username before falling back to parent signup form """
while True:
username = sha1(str(random.random()).encode('utf-8')).hexdigest()[:5]
try:
get_user_model().objects.get(username__iexact=username)
except get_user_... | [
"def",
"save",
"(",
"self",
")",
":",
"while",
"True",
":",
"username",
"=",
"sha1",
"(",
"str",
"(",
"random",
".",
"random",
"(",
")",
")",
".",
"encode",
"(",
"'utf-8'",
")",
")",
".",
"hexdigest",
"(",
")",
"[",
":",
"5",
"]",
"try",
":",
... | Generate a random username before falling back to parent signup form | [
"Generate",
"a",
"random",
"username",
"before",
"falling",
"back",
"to",
"parent",
"signup",
"form"
] | python | train | 44.3 |
singularityhub/sregistry-cli | sregistry/main/base/settings.py | https://github.com/singularityhub/sregistry-cli/blob/abc96140a1d15b5e96d83432e1e0e1f4f8f36331/sregistry/main/base/settings.py#L62-L89 | def get_and_update_setting(self, name, default=None):
'''Look for a setting in the environment (first priority) and then
the settings file (second). If something is found, the settings
file is updated. The order of operations works as follows:
1. The .sregistry settings file is used as a cache... | [
"def",
"get_and_update_setting",
"(",
"self",
",",
"name",
",",
"default",
"=",
"None",
")",
":",
"setting",
"=",
"self",
".",
"_get_setting",
"(",
"name",
")",
"if",
"setting",
"is",
"None",
"and",
"default",
"is",
"not",
"None",
":",
"setting",
"=",
... | Look for a setting in the environment (first priority) and then
the settings file (second). If something is found, the settings
file is updated. The order of operations works as follows:
1. The .sregistry settings file is used as a cache for the variable
2. the environment variable always t... | [
"Look",
"for",
"a",
"setting",
"in",
"the",
"environment",
"(",
"first",
"priority",
")",
"and",
"then",
"the",
"settings",
"file",
"(",
"second",
")",
".",
"If",
"something",
"is",
"found",
"the",
"settings",
"file",
"is",
"updated",
".",
"The",
"order"... | python | test | 39.464286 |
aio-libs/aioredis | aioredis/commands/sorted_set.py | https://github.com/aio-libs/aioredis/blob/e8c33e39558d4cc91cf70dde490d8b330c97dc2e/aioredis/commands/sorted_set.py#L51-L66 | def zcount(self, key, min=float('-inf'), max=float('inf'),
*, exclude=None):
"""Count the members in a sorted set with scores
within the given values.
:raises TypeError: min or max is not float or int
:raises ValueError: if min greater than max
"""
if not ... | [
"def",
"zcount",
"(",
"self",
",",
"key",
",",
"min",
"=",
"float",
"(",
"'-inf'",
")",
",",
"max",
"=",
"float",
"(",
"'inf'",
")",
",",
"*",
",",
"exclude",
"=",
"None",
")",
":",
"if",
"not",
"isinstance",
"(",
"min",
",",
"(",
"int",
",",
... | Count the members in a sorted set with scores
within the given values.
:raises TypeError: min or max is not float or int
:raises ValueError: if min greater than max | [
"Count",
"the",
"members",
"in",
"a",
"sorted",
"set",
"with",
"scores",
"within",
"the",
"given",
"values",
"."
] | python | train | 44.25 |
Accelize/pycosio | pycosio/storage/azure.py | https://github.com/Accelize/pycosio/blob/1cc1f8fdf5394d92918b7bae2bfa682169ccc48c/pycosio/storage/azure.py#L199-L217 | def _model_to_dict(obj):
"""
Convert object model to dict.
Args:
obj: Object model.
Returns:
dict: Converted model.
"""
result = _properties_model_to_dict(obj.properties)
for attribute in ('metadata', 'snapshot'):
try:
... | [
"def",
"_model_to_dict",
"(",
"obj",
")",
":",
"result",
"=",
"_properties_model_to_dict",
"(",
"obj",
".",
"properties",
")",
"for",
"attribute",
"in",
"(",
"'metadata'",
",",
"'snapshot'",
")",
":",
"try",
":",
"value",
"=",
"getattr",
"(",
"obj",
",",
... | Convert object model to dict.
Args:
obj: Object model.
Returns:
dict: Converted model. | [
"Convert",
"object",
"model",
"to",
"dict",
"."
] | python | train | 25.684211 |
cmcginty/PyWeather | weather/units/temp.py | https://github.com/cmcginty/PyWeather/blob/8c25d9cd1fa921e0a6e460d523656279cac045cb/weather/units/temp.py#L101-L115 | def calc_humidity(temp, dewpoint):
'''
calculates the humidity via the formula from weatherwise.org
return the relative humidity
'''
t = fahrenheit_to_celsius(temp)
td = fahrenheit_to_celsius(dewpoint)
num = 112 - (0.1 * t) + td
denom = 112 + (0.9 * t)
rh = math.pow((num / denom),... | [
"def",
"calc_humidity",
"(",
"temp",
",",
"dewpoint",
")",
":",
"t",
"=",
"fahrenheit_to_celsius",
"(",
"temp",
")",
"td",
"=",
"fahrenheit_to_celsius",
"(",
"dewpoint",
")",
"num",
"=",
"112",
"-",
"(",
"0.1",
"*",
"t",
")",
"+",
"td",
"denom",
"=",
... | calculates the humidity via the formula from weatherwise.org
return the relative humidity | [
"calculates",
"the",
"humidity",
"via",
"the",
"formula",
"from",
"weatherwise",
".",
"org",
"return",
"the",
"relative",
"humidity"
] | python | test | 21.866667 |
materialsproject/pymatgen | pymatgen/core/tensors.py | https://github.com/materialsproject/pymatgen/blob/4ca558cf72f8d5f8a1f21dfdfc0181a971c186da/pymatgen/core/tensors.py#L315-L326 | def voigt_symmetrized(self):
"""
Returns a "voigt"-symmetrized tensor, i. e. a voigt-notation
tensor such that it is invariant wrt permutation of indices
"""
if not (self.rank % 2 == 0 and self.rank >= 2):
raise ValueError("V-symmetrization requires rank even and >= 2... | [
"def",
"voigt_symmetrized",
"(",
"self",
")",
":",
"if",
"not",
"(",
"self",
".",
"rank",
"%",
"2",
"==",
"0",
"and",
"self",
".",
"rank",
">=",
"2",
")",
":",
"raise",
"ValueError",
"(",
"\"V-symmetrization requires rank even and >= 2\"",
")",
"v",
"=",
... | Returns a "voigt"-symmetrized tensor, i. e. a voigt-notation
tensor such that it is invariant wrt permutation of indices | [
"Returns",
"a",
"voigt",
"-",
"symmetrized",
"tensor",
"i",
".",
"e",
".",
"a",
"voigt",
"-",
"notation",
"tensor",
"such",
"that",
"it",
"is",
"invariant",
"wrt",
"permutation",
"of",
"indices"
] | python | train | 43.583333 |
jmcgeheeiv/pyfakefs | pyfakefs/fake_filesystem.py | https://github.com/jmcgeheeiv/pyfakefs/blob/6c36fb8987108107fc861fc3013620d46c7d2f9c/pyfakefs/fake_filesystem.py#L3795-L3811 | def umask(self, new_mask):
"""Change the current umask.
Args:
new_mask: (int) The new umask value.
Returns:
The old umask.
Raises:
TypeError: if new_mask is of an invalid type.
"""
if not is_int_type(new_mask):
raise Type... | [
"def",
"umask",
"(",
"self",
",",
"new_mask",
")",
":",
"if",
"not",
"is_int_type",
"(",
"new_mask",
")",
":",
"raise",
"TypeError",
"(",
"'an integer is required'",
")",
"old_umask",
"=",
"self",
".",
"filesystem",
".",
"umask",
"self",
".",
"filesystem",
... | Change the current umask.
Args:
new_mask: (int) The new umask value.
Returns:
The old umask.
Raises:
TypeError: if new_mask is of an invalid type. | [
"Change",
"the",
"current",
"umask",
"."
] | python | train | 26.058824 |
UCL-INGI/INGInious | inginious/frontend/pages/aggregation.py | https://github.com/UCL-INGI/INGInious/blob/cbda9a9c7f2b8e8eb1e6d7d51f0d18092086300c/inginious/frontend/pages/aggregation.py#L21-L115 | def GET_AUTH(self, courseid): # pylint: disable=arguments-differ
""" GET request """
course = self.course_factory.get_course(courseid)
username = self.user_manager.session_username()
error = False
change = False
msg = ""
data = web.input()
if self.user_... | [
"def",
"GET_AUTH",
"(",
"self",
",",
"courseid",
")",
":",
"# pylint: disable=arguments-differ",
"course",
"=",
"self",
".",
"course_factory",
".",
"get_course",
"(",
"courseid",
")",
"username",
"=",
"self",
".",
"user_manager",
".",
"session_username",
"(",
")... | GET request | [
"GET",
"request"
] | python | train | 58.8 |
numenta/htmresearch | htmresearch/algorithms/apical_dependent_temporal_memory.py | https://github.com/numenta/htmresearch/blob/70c096b09a577ea0432c3f3bfff4442d4871b7aa/htmresearch/algorithms/apical_dependent_temporal_memory.py#L530-L552 | def _learnOnNewSegments(connections, rng, newSegmentCells, growthCandidates,
initialPermanence, sampleSize, maxSynapsesPerSegment):
"""
Create new segments, and grow synapses on them.
@param connections (SparseMatrixConnections)
@param rng (Random)
@param newSegmentCells (... | [
"def",
"_learnOnNewSegments",
"(",
"connections",
",",
"rng",
",",
"newSegmentCells",
",",
"growthCandidates",
",",
"initialPermanence",
",",
"sampleSize",
",",
"maxSynapsesPerSegment",
")",
":",
"numNewSynapses",
"=",
"len",
"(",
"growthCandidates",
")",
"if",
"sam... | Create new segments, and grow synapses on them.
@param connections (SparseMatrixConnections)
@param rng (Random)
@param newSegmentCells (numpy array)
@param growthCandidates (numpy array) | [
"Create",
"new",
"segments",
"and",
"grow",
"synapses",
"on",
"them",
"."
] | python | train | 36.217391 |
sci-bots/svg-model | svg_model/plot.py | https://github.com/sci-bots/svg-model/blob/2d119650f995e62b29ce0b3151a23f3b957cb072/svg_model/plot.py#L138-L169 | def plot_color_map_bars(values, vmin=None, vmax=None, color_map=None,
axis=None, **kwargs):
'''
Plot bar for each value in `values`, colored based on values mapped onto
the specified color map.
Args
----
values (pandas.Series) : Numeric values to plot one bar per va... | [
"def",
"plot_color_map_bars",
"(",
"values",
",",
"vmin",
"=",
"None",
",",
"vmax",
"=",
"None",
",",
"color_map",
"=",
"None",
",",
"axis",
"=",
"None",
",",
"*",
"*",
"kwargs",
")",
":",
"if",
"axis",
"is",
"None",
":",
"fig",
",",
"axis",
"=",
... | Plot bar for each value in `values`, colored based on values mapped onto
the specified color map.
Args
----
values (pandas.Series) : Numeric values to plot one bar per value.
axis : A matplotlib axis. If `None`, an axis is created.
vmin : Minimum value to clip values at.
v... | [
"Plot",
"bar",
"for",
"each",
"value",
"in",
"values",
"colored",
"based",
"on",
"values",
"mapped",
"onto",
"the",
"specified",
"color",
"map",
"."
] | python | train | 32.625 |
kristianfoerster/melodist | melodist/temperature.py | https://github.com/kristianfoerster/melodist/blob/ddc155c77b65f791be0021dbbaf68c6bac42ecbd/melodist/temperature.py#L33-L212 | def disaggregate_temperature(data_daily,
method='sine_min_max',
min_max_time='fix',
mod_nighttime=False,
max_delta=None,
mean_course=None,
sun_tim... | [
"def",
"disaggregate_temperature",
"(",
"data_daily",
",",
"method",
"=",
"'sine_min_max'",
",",
"min_max_time",
"=",
"'fix'",
",",
"mod_nighttime",
"=",
"False",
",",
"max_delta",
"=",
"None",
",",
"mean_course",
"=",
"None",
",",
"sun_times",
"=",
"None",
")... | The disaggregation function for temperature
Parameters
----
data_daily : daily data
method : method to disaggregate
min_max_time: "fix" - min/max temperature at fixed times 7h/14h,
"sun_loc" - min/max calculated by sunrise/sunnoon + 2h,
... | [
"The",
"disaggregation",
"function",
"for",
"temperature"
] | python | train | 54.094444 |
wmayner/pyphi | pyphi/distribution.py | https://github.com/wmayner/pyphi/blob/deeca69a084d782a6fde7bf26f59e93b593c5d77/pyphi/distribution.py#L81-L93 | def purview(repertoire):
"""The purview of the repertoire.
Args:
repertoire (np.ndarray): A repertoire
Returns:
tuple[int]: The purview that the repertoire was computed over.
"""
if repertoire is None:
return None
return tuple(i for i, dim in enumerate(repertoire.shape... | [
"def",
"purview",
"(",
"repertoire",
")",
":",
"if",
"repertoire",
"is",
"None",
":",
"return",
"None",
"return",
"tuple",
"(",
"i",
"for",
"i",
",",
"dim",
"in",
"enumerate",
"(",
"repertoire",
".",
"shape",
")",
"if",
"dim",
"==",
"2",
")"
] | The purview of the repertoire.
Args:
repertoire (np.ndarray): A repertoire
Returns:
tuple[int]: The purview that the repertoire was computed over. | [
"The",
"purview",
"of",
"the",
"repertoire",
"."
] | python | train | 24.769231 |
ArchiveTeam/wpull | wpull/network/pool.py | https://github.com/ArchiveTeam/wpull/blob/ddf051aa3322479325ba20aa778cb2cb97606bf5/wpull/network/pool.py#L328-L333 | def get_preferred(self, addr_1, addr_2):
'''Return the preferred address.'''
if addr_1 > addr_2:
addr_1, addr_2 = addr_2, addr_1
return self._cache.get((addr_1, addr_2)) | [
"def",
"get_preferred",
"(",
"self",
",",
"addr_1",
",",
"addr_2",
")",
":",
"if",
"addr_1",
">",
"addr_2",
":",
"addr_1",
",",
"addr_2",
"=",
"addr_2",
",",
"addr_1",
"return",
"self",
".",
"_cache",
".",
"get",
"(",
"(",
"addr_1",
",",
"addr_2",
")... | Return the preferred address. | [
"Return",
"the",
"preferred",
"address",
"."
] | python | train | 33.5 |
djtaylor/python-lsbinit | lsbinit/__init__.py | https://github.com/djtaylor/python-lsbinit/blob/a41fc551226f61ac2bf1b8b0f3f5395db85e75a2/lsbinit/__init__.py#L51-L70 | def _colorize(self, msg, color=None, encode=False):
"""
Colorize a string.
"""
# Valid colors
colors = {
'red': '31',
'green': '32',
'yellow': '33'
}
# No color specified or unsupported color
if not... | [
"def",
"_colorize",
"(",
"self",
",",
"msg",
",",
"color",
"=",
"None",
",",
"encode",
"=",
"False",
")",
":",
"# Valid colors",
"colors",
"=",
"{",
"'red'",
":",
"'31'",
",",
"'green'",
":",
"'32'",
",",
"'yellow'",
":",
"'33'",
"}",
"# No color speci... | Colorize a string. | [
"Colorize",
"a",
"string",
"."
] | python | train | 27.3 |
bukun/TorCMS | torcms/model/log_model.py | https://github.com/bukun/TorCMS/blob/6567c7fe2604a1d646d4570c017840958630ed2b/torcms/model/log_model.py#L20-L35 | def add(data_dic):
'''
Insert new record.
'''
uid = data_dic['uid']
TabLog.create(
uid=uid,
current_url=data_dic['url'],
refer_url=data_dic['refer'],
user_id=data_dic['user_id'],
time_create=data_dic['timein'],
... | [
"def",
"add",
"(",
"data_dic",
")",
":",
"uid",
"=",
"data_dic",
"[",
"'uid'",
"]",
"TabLog",
".",
"create",
"(",
"uid",
"=",
"uid",
",",
"current_url",
"=",
"data_dic",
"[",
"'url'",
"]",
",",
"refer_url",
"=",
"data_dic",
"[",
"'refer'",
"]",
",",
... | Insert new record. | [
"Insert",
"new",
"record",
"."
] | python | train | 25.1875 |
ff0000/scarlet | scarlet/assets/models.py | https://github.com/ff0000/scarlet/blob/6c37befd810916a2d7ffff2cdb2dab57bcb6d12e/scarlet/assets/models.py#L100-L114 | def ensure_crops(self, *required_crops):
"""
Make sure a crop exists for each crop in required_crops.
Existing crops will not be changed.
If settings.ASSET_CELERY is specified then
the task will be run async
"""
if self._can_crop():
if settings.CELERY... | [
"def",
"ensure_crops",
"(",
"self",
",",
"*",
"required_crops",
")",
":",
"if",
"self",
".",
"_can_crop",
"(",
")",
":",
"if",
"settings",
".",
"CELERY",
"or",
"settings",
".",
"USE_CELERY_DECORATOR",
":",
"# this means that we are using celery",
"args",
"=",
... | Make sure a crop exists for each crop in required_crops.
Existing crops will not be changed.
If settings.ASSET_CELERY is specified then
the task will be run async | [
"Make",
"sure",
"a",
"crop",
"exists",
"for",
"each",
"crop",
"in",
"required_crops",
".",
"Existing",
"crops",
"will",
"not",
"be",
"changed",
"."
] | python | train | 40.466667 |
pgmpy/pgmpy | pgmpy/readwrite/BIF.py | https://github.com/pgmpy/pgmpy/blob/9381a66aba3c3871d3ccd00672b148d17d63239e/pgmpy/readwrite/BIF.py#L87-L103 | def get_probability_grammar(self):
"""
A method that returns probability grammar
"""
# Creating valid word expression for probability, it is of the format
# wor1 | var2 , var3 or var1 var2 var3 or simply var
word_expr = Word(alphanums + '-' + '_') + Suppress(Optional("|")... | [
"def",
"get_probability_grammar",
"(",
"self",
")",
":",
"# Creating valid word expression for probability, it is of the format",
"# wor1 | var2 , var3 or var1 var2 var3 or simply var",
"word_expr",
"=",
"Word",
"(",
"alphanums",
"+",
"'-'",
"+",
"'_'",
")",
"+",
"Suppress",
... | A method that returns probability grammar | [
"A",
"method",
"that",
"returns",
"probability",
"grammar"
] | python | train | 58.117647 |
gem/oq-engine | openquake/hazardlib/gsim/abrahamson_2015.py | https://github.com/gem/oq-engine/blob/8294553a0b8aba33fd96437a35065d03547d0040/openquake/hazardlib/gsim/abrahamson_2015.py#L134-L148 | def _compute_magnitude_term(self, C, dc1, mag):
"""
Computes the magnitude scaling term given by equation (2)
"""
base = C['theta1'] + (self.CONSTS['theta4'] * dc1)
dmag = self.CONSTS["C1"] + dc1
if mag > dmag:
f_mag = (self.CONSTS['theta5'] * (mag - dmag)) +\... | [
"def",
"_compute_magnitude_term",
"(",
"self",
",",
"C",
",",
"dc1",
",",
"mag",
")",
":",
"base",
"=",
"C",
"[",
"'theta1'",
"]",
"+",
"(",
"self",
".",
"CONSTS",
"[",
"'theta4'",
"]",
"*",
"dc1",
")",
"dmag",
"=",
"self",
".",
"CONSTS",
"[",
"\... | Computes the magnitude scaling term given by equation (2) | [
"Computes",
"the",
"magnitude",
"scaling",
"term",
"given",
"by",
"equation",
"(",
"2",
")"
] | python | train | 34.266667 |
noxdafox/vminspect | vminspect/comparator.py | https://github.com/noxdafox/vminspect/blob/e685282564877e2d1950f1e09b292f4f4db1dbcd/vminspect/comparator.py#L345-L356 | def compare_hives(fs0, fs1):
"""Compares all the windows registry hive files
returning those which differ.
"""
registries = []
for path in chain(registries_path(fs0.fsroot), user_registries(fs0, fs1)):
if fs0.checksum(path) != fs1.checksum(path):
registries.append(path)
re... | [
"def",
"compare_hives",
"(",
"fs0",
",",
"fs1",
")",
":",
"registries",
"=",
"[",
"]",
"for",
"path",
"in",
"chain",
"(",
"registries_path",
"(",
"fs0",
".",
"fsroot",
")",
",",
"user_registries",
"(",
"fs0",
",",
"fs1",
")",
")",
":",
"if",
"fs0",
... | Compares all the windows registry hive files
returning those which differ. | [
"Compares",
"all",
"the",
"windows",
"registry",
"hive",
"files",
"returning",
"those",
"which",
"differ",
"."
] | python | train | 27 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.