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 |
|---|---|---|---|---|---|---|---|---|---|
consbio/gis-metadata-parser | gis_metadata/utils.py | https://github.com/consbio/gis-metadata-parser/blob/59eefb2e51cd4d8cc3e94623a2167499ca9ef70f/gis_metadata/utils.py#L262-L275 | def has_property(elem_to_parse, xpath):
"""
Parse xpath for any attribute reference "path/@attr" and check for root and presence of attribute.
:return: True if xpath is present in the element along with any attribute referenced, otherwise False
"""
xroot, attr = get_xpath_tuple(xpath)
if not x... | [
"def",
"has_property",
"(",
"elem_to_parse",
",",
"xpath",
")",
":",
"xroot",
",",
"attr",
"=",
"get_xpath_tuple",
"(",
"xpath",
")",
"if",
"not",
"xroot",
"and",
"not",
"attr",
":",
"return",
"False",
"elif",
"not",
"attr",
":",
"return",
"bool",
"(",
... | Parse xpath for any attribute reference "path/@attr" and check for root and presence of attribute.
:return: True if xpath is present in the element along with any attribute referenced, otherwise False | [
"Parse",
"xpath",
"for",
"any",
"attribute",
"reference",
"path",
"/"
] | python | train | 36.357143 |
google/grumpy | third_party/stdlib/fpformat.py | https://github.com/google/grumpy/blob/3ec87959189cfcdeae82eb68a47648ac25ceb10b/third_party/stdlib/fpformat.py#L106-L136 | def sci(x, digs):
"""Format x as [-]d.dddE[+-]ddd with 'digs' digits after the point
and exactly one digit before.
If digs is <= 0, one digit is kept and the point is suppressed."""
if type(x) != type(''): x = repr(x)
sign, intpart, fraction, expo = extract(x)
if not intpart:
while fract... | [
"def",
"sci",
"(",
"x",
",",
"digs",
")",
":",
"if",
"type",
"(",
"x",
")",
"!=",
"type",
"(",
"''",
")",
":",
"x",
"=",
"repr",
"(",
"x",
")",
"sign",
",",
"intpart",
",",
"fraction",
",",
"expo",
"=",
"extract",
"(",
"x",
")",
"if",
"not"... | Format x as [-]d.dddE[+-]ddd with 'digs' digits after the point
and exactly one digit before.
If digs is <= 0, one digit is kept and the point is suppressed. | [
"Format",
"x",
"as",
"[",
"-",
"]",
"d",
".",
"dddE",
"[",
"+",
"-",
"]",
"ddd",
"with",
"digs",
"digits",
"after",
"the",
"point",
"and",
"exactly",
"one",
"digit",
"before",
".",
"If",
"digs",
"is",
"<",
"=",
"0",
"one",
"digit",
"is",
"kept",
... | python | valid | 34.290323 |
atztogo/phonopy | phonopy/api_phonopy.py | https://github.com/atztogo/phonopy/blob/869cc2ba9e7d495d5f4cf6942415ab3fc9e2a10f/phonopy/api_phonopy.py#L1252-L1277 | def set_iter_mesh(self,
mesh,
shift=None,
is_time_reversal=True,
is_mesh_symmetry=True,
is_eigenvectors=False,
is_gamma_center=False):
"""Create an IterMesh instancer
Attr... | [
"def",
"set_iter_mesh",
"(",
"self",
",",
"mesh",
",",
"shift",
"=",
"None",
",",
"is_time_reversal",
"=",
"True",
",",
"is_mesh_symmetry",
"=",
"True",
",",
"is_eigenvectors",
"=",
"False",
",",
"is_gamma_center",
"=",
"False",
")",
":",
"warnings",
".",
... | Create an IterMesh instancer
Attributes
----------
See set_mesh method. | [
"Create",
"an",
"IterMesh",
"instancer"
] | python | train | 33.653846 |
bluekeyes/sphinx-javalink | javalink/__init__.py | https://github.com/bluekeyes/sphinx-javalink/blob/490e37506efa53e95ad88a665e347536e75b6254/javalink/__init__.py#L61-L95 | def find_rt_jar(javahome=None):
"""Find the path to the Java standard library jar.
The jar is expected to exist at the path 'jre/lib/rt.jar' inside a
standard Java installation directory. The directory is found using
the following procedure:
1. If the javehome argument is provided, use the value a... | [
"def",
"find_rt_jar",
"(",
"javahome",
"=",
"None",
")",
":",
"if",
"not",
"javahome",
":",
"if",
"'JAVA_HOME'",
"in",
"os",
".",
"environ",
":",
"javahome",
"=",
"os",
".",
"environ",
"[",
"'JAVA_HOME'",
"]",
"elif",
"sys",
".",
"platform",
"==",
"'da... | Find the path to the Java standard library jar.
The jar is expected to exist at the path 'jre/lib/rt.jar' inside a
standard Java installation directory. The directory is found using
the following procedure:
1. If the javehome argument is provided, use the value as the
directory.
2. If the J... | [
"Find",
"the",
"path",
"to",
"the",
"Java",
"standard",
"library",
"jar",
"."
] | python | train | 37.485714 |
brocade/pynos | pynos/versions/ver_6/ver_6_0_1/yang/brocade_ras_ext.py | https://github.com/brocade/pynos/blob/bd8a34e98f322de3fc06750827d8bbc3a0c00380/pynos/versions/ver_6/ver_6_0_1/yang/brocade_ras_ext.py#L171-L184 | def show_raslog_output_show_all_raslog_raslog_entries_log_type(self, **kwargs):
"""Auto Generated Code
"""
config = ET.Element("config")
show_raslog = ET.Element("show_raslog")
config = show_raslog
output = ET.SubElement(show_raslog, "output")
show_all_raslog = ET... | [
"def",
"show_raslog_output_show_all_raslog_raslog_entries_log_type",
"(",
"self",
",",
"*",
"*",
"kwargs",
")",
":",
"config",
"=",
"ET",
".",
"Element",
"(",
"\"config\"",
")",
"show_raslog",
"=",
"ET",
".",
"Element",
"(",
"\"show_raslog\"",
")",
"config",
"="... | Auto Generated Code | [
"Auto",
"Generated",
"Code"
] | python | train | 44.142857 |
pydata/xarray | xarray/core/alignment.py | https://github.com/pydata/xarray/blob/6d93a95d05bdbfc33fff24064f67d29dd891ab58/xarray/core/alignment.py#L172-L228 | def deep_align(objects, join='inner', copy=True, indexes=None,
exclude=frozenset(), raise_on_invalid=True):
"""Align objects for merging, recursing into dictionary values.
This function is not public API.
"""
from .dataarray import DataArray
from .dataset import Dataset
if index... | [
"def",
"deep_align",
"(",
"objects",
",",
"join",
"=",
"'inner'",
",",
"copy",
"=",
"True",
",",
"indexes",
"=",
"None",
",",
"exclude",
"=",
"frozenset",
"(",
")",
",",
"raise_on_invalid",
"=",
"True",
")",
":",
"from",
".",
"dataarray",
"import",
"Da... | Align objects for merging, recursing into dictionary values.
This function is not public API. | [
"Align",
"objects",
"for",
"merging",
"recursing",
"into",
"dictionary",
"values",
"."
] | python | train | 33.754386 |
openstack/networking-cisco | networking_cisco/ml2_drivers/nexus/nexus_restapi_network_driver.py | https://github.com/openstack/networking-cisco/blob/aa58a30aec25b86f9aa5952b0863045975debfa9/networking_cisco/ml2_drivers/nexus/nexus_restapi_network_driver.py#L254-L264 | def _apply_user_port_channel_config(self, nexus_host, vpc_nbr):
"""Adds STP and no lacp suspend config to port channel. """
cli_cmds = self._get_user_port_channel_config(nexus_host, vpc_nbr)
if cli_cmds:
self._send_cli_conf_string(nexus_host, cli_cmds)
else:
vpc_... | [
"def",
"_apply_user_port_channel_config",
"(",
"self",
",",
"nexus_host",
",",
"vpc_nbr",
")",
":",
"cli_cmds",
"=",
"self",
".",
"_get_user_port_channel_config",
"(",
"nexus_host",
",",
"vpc_nbr",
")",
"if",
"cli_cmds",
":",
"self",
".",
"_send_cli_conf_string",
... | Adds STP and no lacp suspend config to port channel. | [
"Adds",
"STP",
"and",
"no",
"lacp",
"suspend",
"config",
"to",
"port",
"channel",
"."
] | python | train | 46 |
PonteIneptique/collatinus-python | pycollatinus/parser.py | https://github.com/PonteIneptique/collatinus-python/blob/fca37b0b77bc60f47d3c24ab42f6d0bdca6ba0f5/pycollatinus/parser.py#L380-L397 | def ajModeles(self):
""" Lecture des modèles, et enregistrement de leurs désinences
"""
sl = []
lines = [line for line in lignesFichier(self.path("modeles.la"))]
max = len(lines) - 1
for i, l in enumerate(lines):
if l.startswith('$'):
varname, ... | [
"def",
"ajModeles",
"(",
"self",
")",
":",
"sl",
"=",
"[",
"]",
"lines",
"=",
"[",
"line",
"for",
"line",
"in",
"lignesFichier",
"(",
"self",
".",
"path",
"(",
"\"modeles.la\"",
")",
")",
"]",
"max",
"=",
"len",
"(",
"lines",
")",
"-",
"1",
"for"... | Lecture des modèles, et enregistrement de leurs désinences | [
"Lecture",
"des",
"modèles",
"et",
"enregistrement",
"de",
"leurs",
"désinences"
] | python | train | 36.111111 |
census-instrumentation/opencensus-python | opencensus/trace/propagation/binary_format.py | https://github.com/census-instrumentation/opencensus-python/blob/992b223f7e34c5dcb65922b7d5c827e7a1351e7d/opencensus/trace/propagation/binary_format.py#L95-L136 | def from_header(self, binary):
"""Generate a SpanContext object using the trace context header.
The value of enabled parsed from header is int. Need to convert to
bool.
:type binary: bytes
:param binary: Trace context header which was extracted from the
re... | [
"def",
"from_header",
"(",
"self",
",",
"binary",
")",
":",
"# If no binary provided, generate a new SpanContext",
"if",
"binary",
"is",
"None",
":",
"return",
"span_context_module",
".",
"SpanContext",
"(",
"from_header",
"=",
"False",
")",
"# If cannot parse, return a... | Generate a SpanContext object using the trace context header.
The value of enabled parsed from header is int. Need to convert to
bool.
:type binary: bytes
:param binary: Trace context header which was extracted from the
request headers.
:rtype: :class:`~o... | [
"Generate",
"a",
"SpanContext",
"object",
"using",
"the",
"trace",
"context",
"header",
".",
"The",
"value",
"of",
"enabled",
"parsed",
"from",
"header",
"is",
"int",
".",
"Need",
"to",
"convert",
"to",
"bool",
"."
] | python | train | 40.238095 |
f3at/feat | src/feat/models/utils.py | https://github.com/f3at/feat/blob/15da93fc9d6ec8154f52a9172824e25821195ef8/src/feat/models/utils.py#L26-L31 | def mk_class_name(*parts):
"""Create a valid class name from a list of strings."""
cap = lambda s: s and (s[0].capitalize() + s[1:])
return "".join(["".join([cap(i)
for i in re.split("[\ \-\_\.]", str(p))])
for p in parts]) | [
"def",
"mk_class_name",
"(",
"*",
"parts",
")",
":",
"cap",
"=",
"lambda",
"s",
":",
"s",
"and",
"(",
"s",
"[",
"0",
"]",
".",
"capitalize",
"(",
")",
"+",
"s",
"[",
"1",
":",
"]",
")",
"return",
"\"\"",
".",
"join",
"(",
"[",
"\"\"",
".",
... | Create a valid class name from a list of strings. | [
"Create",
"a",
"valid",
"class",
"name",
"from",
"a",
"list",
"of",
"strings",
"."
] | python | train | 46.5 |
xenadevel/PyXenaManager | xenamanager/api/xena_rest.py | https://github.com/xenadevel/PyXenaManager/blob/384ca265f73044b8a8b471f5dd7a6103fc54f4df/xenamanager/api/xena_rest.py#L69-L78 | def send_command_return(self, obj, command, *arguments):
""" Send command with single line output.
:param obj: requested object.
:param command: command to send.
:param arguments: list of command arguments.
:return: command output.
"""
return self._perform_comman... | [
"def",
"send_command_return",
"(",
"self",
",",
"obj",
",",
"command",
",",
"*",
"arguments",
")",
":",
"return",
"self",
".",
"_perform_command",
"(",
"'{}/{}'",
".",
"format",
"(",
"self",
".",
"session_url",
",",
"obj",
".",
"ref",
")",
",",
"command"... | Send command with single line output.
:param obj: requested object.
:param command: command to send.
:param arguments: list of command arguments.
:return: command output. | [
"Send",
"command",
"with",
"single",
"line",
"output",
"."
] | python | train | 44.8 |
dereneaton/ipyrad | ipyrad/analysis/structure.py | https://github.com/dereneaton/ipyrad/blob/5eeb8a178160f45faf71bf47cec4abe998a575d1/ipyrad/analysis/structure.py#L626-L690 | def _get_clumpp_table(self, kpop, max_var_multiple, quiet):
""" private function to clumpp results"""
## concat results for k=x
reps, excluded = _concat_reps(self, kpop, max_var_multiple, quiet)
if reps:
ninds = reps[0].inds
nreps = len(reps)
else:
ninds = nreps = 0
if n... | [
"def",
"_get_clumpp_table",
"(",
"self",
",",
"kpop",
",",
"max_var_multiple",
",",
"quiet",
")",
":",
"## concat results for k=x",
"reps",
",",
"excluded",
"=",
"_concat_reps",
"(",
"self",
",",
"kpop",
",",
"max_var_multiple",
",",
"quiet",
")",
"if",
"reps"... | private function to clumpp results | [
"private",
"function",
"to",
"clumpp",
"results"
] | python | valid | 33.461538 |
SoCo/SoCo | soco/data_structures.py | https://github.com/SoCo/SoCo/blob/671937e07d7973b78c0cbee153d4f3ad68ec48c6/soco/data_structures.py#L619-L668 | def to_element(self, include_namespaces=False):
"""Return an ElementTree Element representing this instance.
Args:
include_namespaces (bool, optional): If True, include xml
namespace attributes on the root element
Return:
~xml.etree.ElementTree.Element: ... | [
"def",
"to_element",
"(",
"self",
",",
"include_namespaces",
"=",
"False",
")",
":",
"elt_attrib",
"=",
"{",
"}",
"if",
"include_namespaces",
":",
"elt_attrib",
".",
"update",
"(",
"{",
"'xmlns'",
":",
"\"urn:schemas-upnp-org:metadata-1-0/DIDL-Lite/\"",
",",
"'xml... | Return an ElementTree Element representing this instance.
Args:
include_namespaces (bool, optional): If True, include xml
namespace attributes on the root element
Return:
~xml.etree.ElementTree.Element: an Element. | [
"Return",
"an",
"ElementTree",
"Element",
"representing",
"this",
"instance",
"."
] | python | train | 40.04 |
tensorflow/tensor2tensor | tensor2tensor/utils/optimize.py | https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/utils/optimize.py#L301-L327 | def log_variable_sizes(var_list=None, tag=None, verbose=False):
"""Log the sizes and shapes of variables, and the total size.
Args:
var_list: a list of variables; defaults to trainable_variables
tag: a string; defaults to "Trainable Variables"
verbose: bool, if True, log every weight; otherwise, log to... | [
"def",
"log_variable_sizes",
"(",
"var_list",
"=",
"None",
",",
"tag",
"=",
"None",
",",
"verbose",
"=",
"False",
")",
":",
"if",
"var_list",
"is",
"None",
":",
"var_list",
"=",
"tf",
".",
"trainable_variables",
"(",
")",
"if",
"tag",
"is",
"None",
":"... | Log the sizes and shapes of variables, and the total size.
Args:
var_list: a list of variables; defaults to trainable_variables
tag: a string; defaults to "Trainable Variables"
verbose: bool, if True, log every weight; otherwise, log total size only. | [
"Log",
"the",
"sizes",
"and",
"shapes",
"of",
"variables",
"and",
"the",
"total",
"size",
"."
] | python | train | 33.592593 |
SheffieldML/GPy | GPy/likelihoods/student_t.py | https://github.com/SheffieldML/GPy/blob/54c32d79d289d622fb18b898aee65a2a431d90cf/GPy/likelihoods/student_t.py#L71-L97 | def logpdf_link(self, inv_link_f, y, Y_metadata=None):
"""
Log Likelihood Function given link(f)
.. math::
\\ln p(y_{i}|\lambda(f_{i})) = \\ln \\Gamma\\left(\\frac{v+1}{2}\\right) - \\ln \\Gamma\\left(\\frac{v}{2}\\right) - \\ln \\sqrt{v \\pi\\sigma^{2}} - \\frac{v+1}{2}\\ln \\left(... | [
"def",
"logpdf_link",
"(",
"self",
",",
"inv_link_f",
",",
"y",
",",
"Y_metadata",
"=",
"None",
")",
":",
"e",
"=",
"y",
"-",
"inv_link_f",
"#FIXME:",
"#Why does np.log(1 + (1/self.v)*((y-inv_link_f)**2)/self.sigma2) suppress the divide by zero?!",
"#But np.log(1 + (1/float... | Log Likelihood Function given link(f)
.. math::
\\ln p(y_{i}|\lambda(f_{i})) = \\ln \\Gamma\\left(\\frac{v+1}{2}\\right) - \\ln \\Gamma\\left(\\frac{v}{2}\\right) - \\ln \\sqrt{v \\pi\\sigma^{2}} - \\frac{v+1}{2}\\ln \\left(1 + \\frac{1}{v}\\left(\\frac{(y_{i} - \lambda(f_{i}))^{2}}{\\sigma^{2}}\\r... | [
"Log",
"Likelihood",
"Function",
"given",
"link",
"(",
"f",
")"
] | python | train | 48.925926 |
saltstack/salt | salt/cloud/clouds/opennebula.py | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/cloud/clouds/opennebula.py#L2429-L2485 | def template_delete(call=None, kwargs=None):
'''
Deletes the given template from OpenNebula. Either a name or a template_id must
be supplied.
.. versionadded:: 2016.3.0
name
The name of the template to delete. Can be used instead of ``template_id``.
template_id
The ID of the t... | [
"def",
"template_delete",
"(",
"call",
"=",
"None",
",",
"kwargs",
"=",
"None",
")",
":",
"if",
"call",
"!=",
"'function'",
":",
"raise",
"SaltCloudSystemExit",
"(",
"'The template_delete function must be called with -f or --function.'",
")",
"if",
"kwargs",
"is",
"... | Deletes the given template from OpenNebula. Either a name or a template_id must
be supplied.
.. versionadded:: 2016.3.0
name
The name of the template to delete. Can be used instead of ``template_id``.
template_id
The ID of the template to delete. Can be used instead of ``name``.
... | [
"Deletes",
"the",
"given",
"template",
"from",
"OpenNebula",
".",
"Either",
"a",
"name",
"or",
"a",
"template_id",
"must",
"be",
"supplied",
"."
] | python | train | 27.77193 |
PyCQA/astroid | astroid/scoped_nodes.py | https://github.com/PyCQA/astroid/blob/e0a298df55b15abcb77c2a93253f5ab7be52d0fb/astroid/scoped_nodes.py#L2240-L2252 | def instance_attr_ancestors(self, name, context=None):
"""Iterate over the parents that define the given name as an attribute.
:param name: The name to find definitions for.
:type name: str
:returns: The parents that define the given name as
an instance attribute.
:... | [
"def",
"instance_attr_ancestors",
"(",
"self",
",",
"name",
",",
"context",
"=",
"None",
")",
":",
"for",
"astroid",
"in",
"self",
".",
"ancestors",
"(",
"context",
"=",
"context",
")",
":",
"if",
"name",
"in",
"astroid",
".",
"instance_attrs",
":",
"yie... | Iterate over the parents that define the given name as an attribute.
:param name: The name to find definitions for.
:type name: str
:returns: The parents that define the given name as
an instance attribute.
:rtype: iterable(NodeNG) | [
"Iterate",
"over",
"the",
"parents",
"that",
"define",
"the",
"given",
"name",
"as",
"an",
"attribute",
"."
] | python | train | 36.615385 |
manns/pyspread | pyspread/src/gui/_toolbars.py | https://github.com/manns/pyspread/blob/0e2fd44c2e0f06605efc3058c20a43a8c1f9e7e0/pyspread/src/gui/_toolbars.py#L225-L253 | def OnUpdate(self, event):
"""Updates the toolbar states"""
# Gray out undo and redo id not available
undo_toolid = self.label2id["Undo"]
redo_toolid = self.label2id["Redo"]
self.EnableTool(undo_toolid, undo.stack().canundo())
self.EnableTool(redo_toolid, undo.stack().... | [
"def",
"OnUpdate",
"(",
"self",
",",
"event",
")",
":",
"# Gray out undo and redo id not available",
"undo_toolid",
"=",
"self",
".",
"label2id",
"[",
"\"Undo\"",
"]",
"redo_toolid",
"=",
"self",
".",
"label2id",
"[",
"\"Redo\"",
"]",
"self",
".",
"EnableTool",
... | Updates the toolbar states | [
"Updates",
"the",
"toolbar",
"states"
] | python | train | 31.275862 |
googleapis/google-cloud-python | firestore/google/cloud/firestore_v1beta1/collection.py | https://github.com/googleapis/google-cloud-python/blob/85e80125a59cb10f8cb105f25ecc099e4b940b50/firestore/google/cloud/firestore_v1beta1/collection.py#L468-L477 | def _item_to_document_ref(iterator, item):
"""Convert Document resource to document ref.
Args:
iterator (google.api_core.page_iterator.GRPCIterator):
iterator response
item (dict): document resource
"""
document_id = item.name.split(_helpers.DOCUMENT_PATH_DELIMITER)[-1]
... | [
"def",
"_item_to_document_ref",
"(",
"iterator",
",",
"item",
")",
":",
"document_id",
"=",
"item",
".",
"name",
".",
"split",
"(",
"_helpers",
".",
"DOCUMENT_PATH_DELIMITER",
")",
"[",
"-",
"1",
"]",
"return",
"iterator",
".",
"collection",
".",
"document",... | Convert Document resource to document ref.
Args:
iterator (google.api_core.page_iterator.GRPCIterator):
iterator response
item (dict): document resource | [
"Convert",
"Document",
"resource",
"to",
"document",
"ref",
"."
] | python | train | 35.9 |
Azure/msrest-for-python | msrest/serialization.py | https://github.com/Azure/msrest-for-python/blob/0732bc90bdb290e5f58c675ffdd7dbfa9acefc93/msrest/serialization.py#L1688-L1703 | def deserialize_duration(attr):
"""Deserialize ISO-8601 formatted string into TimeDelta object.
:param str attr: response string to be deserialized.
:rtype: TimeDelta
:raises: DeserializationError if string format invalid.
"""
if isinstance(attr, ET.Element):
... | [
"def",
"deserialize_duration",
"(",
"attr",
")",
":",
"if",
"isinstance",
"(",
"attr",
",",
"ET",
".",
"Element",
")",
":",
"attr",
"=",
"attr",
".",
"text",
"try",
":",
"duration",
"=",
"isodate",
".",
"parse_duration",
"(",
"attr",
")",
"except",
"("... | Deserialize ISO-8601 formatted string into TimeDelta object.
:param str attr: response string to be deserialized.
:rtype: TimeDelta
:raises: DeserializationError if string format invalid. | [
"Deserialize",
"ISO",
"-",
"8601",
"formatted",
"string",
"into",
"TimeDelta",
"object",
"."
] | python | train | 38.5 |
AlecAivazis/graphql-over-kafka | nautilus/api/util/create_model_schema.py | https://github.com/AlecAivazis/graphql-over-kafka/blob/70e2acef27a2f87355590be1a6ca60ce3ab4d09c/nautilus/api/util/create_model_schema.py#L9-L48 | def create_model_schema(target_model):
""" This function creates a graphql schema that provides a single model """
from nautilus.database import db
# create the schema instance
schema = graphene.Schema(auto_camelcase=False)
# grab the primary key from the model
primary_key = target_model.prim... | [
"def",
"create_model_schema",
"(",
"target_model",
")",
":",
"from",
"nautilus",
".",
"database",
"import",
"db",
"# create the schema instance",
"schema",
"=",
"graphene",
".",
"Schema",
"(",
"auto_camelcase",
"=",
"False",
")",
"# grab the primary key from the model",... | This function creates a graphql schema that provides a single model | [
"This",
"function",
"creates",
"a",
"graphql",
"schema",
"that",
"provides",
"a",
"single",
"model"
] | python | train | 29.725 |
pypa/pipenv | pipenv/vendor/requests/utils.py | https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/vendor/requests/utils.py#L648-L669 | def is_valid_cidr(string_network):
"""
Very simple check of the cidr format in no_proxy variable.
:rtype: bool
"""
if string_network.count('/') == 1:
try:
mask = int(string_network.split('/')[1])
except ValueError:
return False
if mask < 1 or mask > ... | [
"def",
"is_valid_cidr",
"(",
"string_network",
")",
":",
"if",
"string_network",
".",
"count",
"(",
"'/'",
")",
"==",
"1",
":",
"try",
":",
"mask",
"=",
"int",
"(",
"string_network",
".",
"split",
"(",
"'/'",
")",
"[",
"1",
"]",
")",
"except",
"Value... | Very simple check of the cidr format in no_proxy variable.
:rtype: bool | [
"Very",
"simple",
"check",
"of",
"the",
"cidr",
"format",
"in",
"no_proxy",
"variable",
"."
] | python | train | 22.772727 |
brocade/pynos | pynos/versions/ver_6/ver_6_0_1/yang/brocade_vlan.py | https://github.com/brocade/pynos/blob/bd8a34e98f322de3fc06750827d8bbc3a0c00380/pynos/versions/ver_6/ver_6_0_1/yang/brocade_vlan.py#L155-L165 | def vlan_dot1q_tag_native(self, **kwargs):
"""Auto Generated Code
"""
config = ET.Element("config")
vlan = ET.SubElement(config, "vlan", xmlns="urn:brocade.com:mgmt:brocade-vlan")
dot1q = ET.SubElement(vlan, "dot1q")
tag = ET.SubElement(dot1q, "tag")
native = ET.S... | [
"def",
"vlan_dot1q_tag_native",
"(",
"self",
",",
"*",
"*",
"kwargs",
")",
":",
"config",
"=",
"ET",
".",
"Element",
"(",
"\"config\"",
")",
"vlan",
"=",
"ET",
".",
"SubElement",
"(",
"config",
",",
"\"vlan\"",
",",
"xmlns",
"=",
"\"urn:brocade.com:mgmt:br... | Auto Generated Code | [
"Auto",
"Generated",
"Code"
] | python | train | 38.636364 |
rsheftel/raccoon | raccoon/dataframe.py | https://github.com/rsheftel/raccoon/blob/e5c4b5fb933b51f33aff11e8168c39790e9a7c75/raccoon/dataframe.py#L1027-L1047 | def append(self, data_frame):
"""
Append another DataFrame to this DataFrame. If the new data_frame has columns that are not in the current
DataFrame then new columns will be created. All of the indexes in the data_frame must be different from the
current indexes or will raise an error.
... | [
"def",
"append",
"(",
"self",
",",
"data_frame",
")",
":",
"if",
"len",
"(",
"data_frame",
")",
"==",
"0",
":",
"# empty DataFrame, do nothing",
"return",
"data_frame_index",
"=",
"data_frame",
".",
"index",
"combined_index",
"=",
"self",
".",
"_index",
"+",
... | Append another DataFrame to this DataFrame. If the new data_frame has columns that are not in the current
DataFrame then new columns will be created. All of the indexes in the data_frame must be different from the
current indexes or will raise an error.
:param data_frame: DataFrame to append
... | [
"Append",
"another",
"DataFrame",
"to",
"this",
"DataFrame",
".",
"If",
"the",
"new",
"data_frame",
"has",
"columns",
"that",
"are",
"not",
"in",
"the",
"current",
"DataFrame",
"then",
"new",
"columns",
"will",
"be",
"created",
".",
"All",
"of",
"the",
"in... | python | train | 47.047619 |
pyviz/geoviews | geoviews/element/geo.py | https://github.com/pyviz/geoviews/blob/cc70ac2d5a96307769bc6192eaef8576c3d24b30/geoviews/element/geo.py#L142-L184 | def geoms(self, scale=None, bounds=None, as_element=True):
"""
Returns the geometries held by the Feature.
Parameters
----------
scale: str
Scale of the geometry to return expressed as string.
Available scales depends on the Feature type.
NaturalEa... | [
"def",
"geoms",
"(",
"self",
",",
"scale",
"=",
"None",
",",
"bounds",
"=",
"None",
",",
"as_element",
"=",
"True",
")",
":",
"feature",
"=",
"self",
".",
"data",
"if",
"scale",
"is",
"not",
"None",
":",
"feature",
"=",
"feature",
".",
"with_scale",
... | Returns the geometries held by the Feature.
Parameters
----------
scale: str
Scale of the geometry to return expressed as string.
Available scales depends on the Feature type.
NaturalEarthFeature:
'10m', '50m', '110m'
GSHHSFeature:
... | [
"Returns",
"the",
"geometries",
"held",
"by",
"the",
"Feature",
"."
] | python | train | 31.837209 |
seequent/properties | properties/basic.py | https://github.com/seequent/properties/blob/096b07012fff86b0a880c8c018320c3b512751b9/properties/basic.py#L521-L535 | def setter(self, func):
"""Register a set function for the DynamicProperty
This function must take two arguments, self and the new value.
Input value to the function is validated with prop validation prior to
execution.
"""
if not callable(func):
raise TypeEr... | [
"def",
"setter",
"(",
"self",
",",
"func",
")",
":",
"if",
"not",
"callable",
"(",
"func",
")",
":",
"raise",
"TypeError",
"(",
"'setter must be callable function'",
")",
"if",
"hasattr",
"(",
"func",
",",
"'__code__'",
")",
"and",
"func",
".",
"__code__",... | Register a set function for the DynamicProperty
This function must take two arguments, self and the new value.
Input value to the function is validated with prop validation prior to
execution. | [
"Register",
"a",
"set",
"function",
"for",
"the",
"DynamicProperty"
] | python | train | 44 |
iterative/dvc | dvc/analytics.py | https://github.com/iterative/dvc/blob/8bb21261e34c9632453e09090de7ebe50e38d341/dvc/analytics.py#L247-L261 | def send_cmd(cmd, args, ret):
"""Collect and send analytics for CLI command.
Args:
args (list): parsed args for the CLI command.
ret (int): return value of the CLI command.
"""
from dvc.daemon import daemon
if not Analytics._is_enabled(cmd):
... | [
"def",
"send_cmd",
"(",
"cmd",
",",
"args",
",",
"ret",
")",
":",
"from",
"dvc",
".",
"daemon",
"import",
"daemon",
"if",
"not",
"Analytics",
".",
"_is_enabled",
"(",
"cmd",
")",
":",
"return",
"analytics",
"=",
"Analytics",
"(",
")",
"analytics",
".",... | Collect and send analytics for CLI command.
Args:
args (list): parsed args for the CLI command.
ret (int): return value of the CLI command. | [
"Collect",
"and",
"send",
"analytics",
"for",
"CLI",
"command",
"."
] | python | train | 28.933333 |
Cog-Creators/Red-Lavalink | lavalink/player_manager.py | https://github.com/Cog-Creators/Red-Lavalink/blob/5b3fc6eb31ee5db8bd2b633a523cf69749957111/lavalink/player_manager.py#L265-L277 | async def stop(self):
"""
Stops playback from lavalink.
.. important::
This method will clear the queue.
"""
await self.node.stop(self.channel.guild.id)
self.queue = []
self.current = None
self.position = 0
self._paused = False | [
"async",
"def",
"stop",
"(",
"self",
")",
":",
"await",
"self",
".",
"node",
".",
"stop",
"(",
"self",
".",
"channel",
".",
"guild",
".",
"id",
")",
"self",
".",
"queue",
"=",
"[",
"]",
"self",
".",
"current",
"=",
"None",
"self",
".",
"position"... | Stops playback from lavalink.
.. important::
This method will clear the queue. | [
"Stops",
"playback",
"from",
"lavalink",
"."
] | python | train | 23.153846 |
apache/spark | python/pyspark/rdd.py | https://github.com/apache/spark/blob/618d6bff71073c8c93501ab7392c3cc579730f0b/python/pyspark/rdd.py#L2186-L2204 | def zipWithUniqueId(self):
"""
Zips this RDD with generated unique Long ids.
Items in the kth partition will get ids k, n+k, 2*n+k, ..., where
n is the number of partitions. So there may exist gaps, but this
method won't trigger a spark job, which is different from
L{zip... | [
"def",
"zipWithUniqueId",
"(",
"self",
")",
":",
"n",
"=",
"self",
".",
"getNumPartitions",
"(",
")",
"def",
"func",
"(",
"k",
",",
"it",
")",
":",
"for",
"i",
",",
"v",
"in",
"enumerate",
"(",
"it",
")",
":",
"yield",
"v",
",",
"i",
"*",
"n",
... | Zips this RDD with generated unique Long ids.
Items in the kth partition will get ids k, n+k, 2*n+k, ..., where
n is the number of partitions. So there may exist gaps, but this
method won't trigger a spark job, which is different from
L{zipWithIndex}
>>> sc.parallelize(["a", "b... | [
"Zips",
"this",
"RDD",
"with",
"generated",
"unique",
"Long",
"ids",
"."
] | python | train | 34.473684 |
fhcrc/nestly | nestly/scons.py | https://github.com/fhcrc/nestly/blob/4d7818b5950f405d2067a6b8577d5afb7527c9ff/nestly/scons.py#L37-L47 | def name_targets(func):
"""
Wrap a function such that returning ``'a', 'b', 'c', [1, 2, 3]`` transforms
the value into ``dict(a=1, b=2, c=3)``.
This is useful in the case where the last parameter is an SCons command.
"""
def wrap(*a, **kw):
ret = func(*a, **kw)
return dict(zip(r... | [
"def",
"name_targets",
"(",
"func",
")",
":",
"def",
"wrap",
"(",
"*",
"a",
",",
"*",
"*",
"kw",
")",
":",
"ret",
"=",
"func",
"(",
"*",
"a",
",",
"*",
"*",
"kw",
")",
"return",
"dict",
"(",
"zip",
"(",
"ret",
"[",
":",
"-",
"1",
"]",
","... | Wrap a function such that returning ``'a', 'b', 'c', [1, 2, 3]`` transforms
the value into ``dict(a=1, b=2, c=3)``.
This is useful in the case where the last parameter is an SCons command. | [
"Wrap",
"a",
"function",
"such",
"that",
"returning",
"a",
"b",
"c",
"[",
"1",
"2",
"3",
"]",
"transforms",
"the",
"value",
"into",
"dict",
"(",
"a",
"=",
"1",
"b",
"=",
"2",
"c",
"=",
"3",
")",
"."
] | python | train | 31.272727 |
jxtech/wechatpy | wechatpy/client/api/device.py | https://github.com/jxtech/wechatpy/blob/4df0da795618c0895a10f1c2cde9e9d5c0a93aaa/wechatpy/client/api/device.py#L96-L114 | def bind(self, ticket, device_id, user_id):
"""
绑定设备
详情请参考
https://iot.weixin.qq.com/wiki/new/index.html?page=3-4-7
:param ticket: 绑定操作合法性的凭证(由微信后台生成,第三方H5通过客户端jsapi获得)
:param device_id: 设备id
:param user_id: 用户对应的openid
:return: 返回的 JSON 数据包
"""
... | [
"def",
"bind",
"(",
"self",
",",
"ticket",
",",
"device_id",
",",
"user_id",
")",
":",
"return",
"self",
".",
"_post",
"(",
"'bind'",
",",
"data",
"=",
"{",
"'ticket'",
":",
"ticket",
",",
"'device_id'",
":",
"device_id",
",",
"'openid'",
":",
"user_id... | 绑定设备
详情请参考
https://iot.weixin.qq.com/wiki/new/index.html?page=3-4-7
:param ticket: 绑定操作合法性的凭证(由微信后台生成,第三方H5通过客户端jsapi获得)
:param device_id: 设备id
:param user_id: 用户对应的openid
:return: 返回的 JSON 数据包 | [
"绑定设备",
"详情请参考",
"https",
":",
"//",
"iot",
".",
"weixin",
".",
"qq",
".",
"com",
"/",
"wiki",
"/",
"new",
"/",
"index",
".",
"html?page",
"=",
"3",
"-",
"4",
"-",
"7"
] | python | train | 26.210526 |
swistakm/python-gmaps | src/gmaps/client.py | https://github.com/swistakm/python-gmaps/blob/ef3bdea6f02277200f21a09f99d4e2aebad762b9/src/gmaps/client.py#L36-L53 | def _serialize_parameters(parameters):
"""Serialize some parameters to match python native types with formats
specified in google api docs like:
* True/False -> "true"/"false",
* {"a": 1, "b":2} -> "a:1|b:2"
:type parameters: dict oif query parameters
"""
for ke... | [
"def",
"_serialize_parameters",
"(",
"parameters",
")",
":",
"for",
"key",
",",
"value",
"in",
"parameters",
".",
"items",
"(",
")",
":",
"if",
"isinstance",
"(",
"value",
",",
"bool",
")",
":",
"parameters",
"[",
"key",
"]",
"=",
"\"true\"",
"if",
"va... | Serialize some parameters to match python native types with formats
specified in google api docs like:
* True/False -> "true"/"false",
* {"a": 1, "b":2} -> "a:1|b:2"
:type parameters: dict oif query parameters | [
"Serialize",
"some",
"parameters",
"to",
"match",
"python",
"native",
"types",
"with",
"formats",
"specified",
"in",
"google",
"api",
"docs",
"like",
":",
"*",
"True",
"/",
"False",
"-",
">",
"true",
"/",
"false",
"*",
"{",
"a",
":",
"1",
"b",
":",
"... | python | train | 39.777778 |
mdgoldberg/sportsref | sportsref/nba/pbp.py | https://github.com/mdgoldberg/sportsref/blob/09f11ac856a23c96d666d1d510bb35d6f050b5c3/sportsref/nba/pbp.py#L26-L379 | def parse_play(boxscore_id, details, is_hm):
"""Parse play details from a play-by-play string describing a play.
Assuming valid input, this function returns structured data in a dictionary
describing the play. If the play detail string was invalid, this function
returns None.
:param boxscore_id: t... | [
"def",
"parse_play",
"(",
"boxscore_id",
",",
"details",
",",
"is_hm",
")",
":",
"# if input isn't a string, return None",
"if",
"not",
"details",
"or",
"not",
"isinstance",
"(",
"details",
",",
"basestring",
")",
":",
"return",
"None",
"bs",
"=",
"sportsref",
... | Parse play details from a play-by-play string describing a play.
Assuming valid input, this function returns structured data in a dictionary
describing the play. If the play detail string was invalid, this function
returns None.
:param boxscore_id: the boxscore ID of the play
:param details: detai... | [
"Parse",
"play",
"details",
"from",
"a",
"play",
"-",
"by",
"-",
"play",
"string",
"describing",
"a",
"play",
"."
] | python | test | 37.336158 |
bitesofcode/projexui | projexui/widgets/xtreewidget/xtreewidget.py | https://github.com/bitesofcode/projexui/blob/f18a73bec84df90b034ca69b9deea118dbedfc4d/projexui/widgets/xtreewidget/xtreewidget.py#L1014-L1026 | def hiddenColumns( self ):
"""
Returns a list of the hidden columns for this tree.
:return [<str>, ..]
"""
output = []
columns = self.columns()
for c, column in enumerate(columns):
if ( not self.isColumnHidden(c) ):
... | [
"def",
"hiddenColumns",
"(",
"self",
")",
":",
"output",
"=",
"[",
"]",
"columns",
"=",
"self",
".",
"columns",
"(",
")",
"for",
"c",
",",
"column",
"in",
"enumerate",
"(",
"columns",
")",
":",
"if",
"(",
"not",
"self",
".",
"isColumnHidden",
"(",
... | Returns a list of the hidden columns for this tree.
:return [<str>, ..] | [
"Returns",
"a",
"list",
"of",
"the",
"hidden",
"columns",
"for",
"this",
"tree",
".",
":",
"return",
"[",
"<str",
">",
"..",
"]"
] | python | train | 29.076923 |
googledatalab/pydatalab | google/datalab/bigquery/_sampling.py | https://github.com/googledatalab/pydatalab/blob/d9031901d5bca22fe0d5925d204e6698df9852e1/google/datalab/bigquery/_sampling.py#L76-L97 | def hashed(field_name, percent, fields=None, count=0):
"""Provides a sampling strategy based on hashing and selecting a percentage of data.
Args:
field_name: the name of the field to hash.
percent: the percentage of the resulting hashes to select.
fields: an optional list of field names to re... | [
"def",
"hashed",
"(",
"field_name",
",",
"percent",
",",
"fields",
"=",
"None",
",",
"count",
"=",
"0",
")",
":",
"if",
"field_name",
"is",
"None",
":",
"raise",
"Exception",
"(",
"'Hash field must be specified'",
")",
"def",
"_hashed_sampling",
"(",
"sql",
... | Provides a sampling strategy based on hashing and selecting a percentage of data.
Args:
field_name: the name of the field to hash.
percent: the percentage of the resulting hashes to select.
fields: an optional list of field names to retrieve.
count: optional maximum count of rows to pick.
... | [
"Provides",
"a",
"sampling",
"strategy",
"based",
"on",
"hashing",
"and",
"selecting",
"a",
"percentage",
"of",
"data",
"."
] | python | train | 40.227273 |
openstack/networking-cisco | networking_cisco/apps/saf/server/services/firewall/native/fw_mgr.py | https://github.com/openstack/networking-cisco/blob/aa58a30aec25b86f9aa5952b0863045975debfa9/networking_cisco/apps/saf/server/services/firewall/native/fw_mgr.py#L185-L210 | def is_fw_complete(self):
"""This API returns the completion status of FW.
This returns True if a FW is created with a active policy that has
more than one rule associated with it and if a driver init is done
successfully.
"""
LOG.info("In fw_complete needed %(fw_created... | [
"def",
"is_fw_complete",
"(",
"self",
")",
":",
"LOG",
".",
"info",
"(",
"\"In fw_complete needed %(fw_created)s \"",
"\"%(active_policy_id)s %(is_fw_drvr_created)s \"",
"\"%(pol_present)s %(fw_type)s\"",
",",
"{",
"'fw_created'",
":",
"self",
".",
"fw_created",
",",
"'acti... | This API returns the completion status of FW.
This returns True if a FW is created with a active policy that has
more than one rule associated with it and if a driver init is done
successfully. | [
"This",
"API",
"returns",
"the",
"completion",
"status",
"of",
"FW",
"."
] | python | train | 51.307692 |
cloudflare/sqlalchemy-clickhouse | connector.py | https://github.com/cloudflare/sqlalchemy-clickhouse/blob/fc46142445d4510566f6412964df2fb9d2f4bd2e/connector.py#L260-L283 | def fetchmany(self, size=None):
"""Fetch the next set of rows of a query result, returning a sequence of sequences (e.g. a
list of tuples). An empty sequence is returned when no more rows are available.
The number of rows to fetch per call is specified by the parameter. If it is not given, the
... | [
"def",
"fetchmany",
"(",
"self",
",",
"size",
"=",
"None",
")",
":",
"if",
"self",
".",
"_state",
"==",
"self",
".",
"_STATE_NONE",
":",
"raise",
"Exception",
"(",
"\"No query yet\"",
")",
"if",
"size",
"is",
"None",
":",
"size",
"=",
"1",
"if",
"not... | Fetch the next set of rows of a query result, returning a sequence of sequences (e.g. a
list of tuples). An empty sequence is returned when no more rows are available.
The number of rows to fetch per call is specified by the parameter. If it is not given, the
cursor's arraysize determines the n... | [
"Fetch",
"the",
"next",
"set",
"of",
"rows",
"of",
"a",
"query",
"result",
"returning",
"a",
"sequence",
"of",
"sequences",
"(",
"e",
".",
"g",
".",
"a",
"list",
"of",
"tuples",
")",
".",
"An",
"empty",
"sequence",
"is",
"returned",
"when",
"no",
"mo... | python | train | 43.166667 |
ejeschke/ginga | ginga/ImageView.py | https://github.com/ejeschke/ginga/blob/a78c893ec6f37a837de851947e9bb4625c597915/ginga/ImageView.py#L1965-L1983 | def get_pixel_distance(self, x1, y1, x2, y2):
"""Calculate distance between the given pixel positions.
Parameters
----------
x1, y1, x2, y2 : number
Pixel coordinates.
Returns
-------
dist : float
Rounded distance.
"""
dx... | [
"def",
"get_pixel_distance",
"(",
"self",
",",
"x1",
",",
"y1",
",",
"x2",
",",
"y2",
")",
":",
"dx",
"=",
"abs",
"(",
"x2",
"-",
"x1",
")",
"dy",
"=",
"abs",
"(",
"y2",
"-",
"y1",
")",
"dist",
"=",
"np",
".",
"sqrt",
"(",
"dx",
"*",
"dx",
... | Calculate distance between the given pixel positions.
Parameters
----------
x1, y1, x2, y2 : number
Pixel coordinates.
Returns
-------
dist : float
Rounded distance. | [
"Calculate",
"distance",
"between",
"the",
"given",
"pixel",
"positions",
"."
] | python | train | 22.894737 |
Workiva/furious | furious/async.py | https://github.com/Workiva/furious/blob/c29823ec8b98549e7439d7273aa064d1e5830632/furious/async.py#L305-L327 | def to_task(self):
"""Return a task object representing this async job."""
from google.appengine.api.taskqueue import Task
from google.appengine.api.taskqueue import TaskRetryOptions
self._increment_recursion_level()
self.check_recursion_depth()
url = "%s/%s" % (ASYNC_E... | [
"def",
"to_task",
"(",
"self",
")",
":",
"from",
"google",
".",
"appengine",
".",
"api",
".",
"taskqueue",
"import",
"Task",
"from",
"google",
".",
"appengine",
".",
"api",
".",
"taskqueue",
"import",
"TaskRetryOptions",
"self",
".",
"_increment_recursion_leve... | Return a task object representing this async job. | [
"Return",
"a",
"task",
"object",
"representing",
"this",
"async",
"job",
"."
] | python | train | 34.478261 |
Genida/archan | src/archan/config.py | https://github.com/Genida/archan/blob/a026d3105c7e86f30e6c9507b93ceb736684bfdc/src/archan/config.py#L315-L335 | def inflate_plugins(self, plugins_definition, inflate_method):
"""
Inflate multiple plugins based on a list/dict definition.
Args:
plugins_definition (list/dict): the plugins definitions.
inflate_method (method): the method to indlate each plugin.
Returns:
... | [
"def",
"inflate_plugins",
"(",
"self",
",",
"plugins_definition",
",",
"inflate_method",
")",
":",
"if",
"isinstance",
"(",
"plugins_definition",
",",
"list",
")",
":",
"return",
"self",
".",
"inflate_plugin_list",
"(",
"plugins_definition",
",",
"inflate_method",
... | Inflate multiple plugins based on a list/dict definition.
Args:
plugins_definition (list/dict): the plugins definitions.
inflate_method (method): the method to indlate each plugin.
Returns:
list: a list of plugin instances.
Raises:
ValueError: w... | [
"Inflate",
"multiple",
"plugins",
"based",
"on",
"a",
"list",
"/",
"dict",
"definition",
"."
] | python | train | 41.190476 |
inasafe/inasafe | safe/utilities/styling.py | https://github.com/inasafe/inasafe/blob/831d60abba919f6d481dc94a8d988cc205130724/safe/utilities/styling.py#L38-L74 | def mmi_ramp_roman(raster_layer):
"""Generate an mmi ramp using range of 1-10 on roman.
A standarised range is used so that two shakemaps of different
intensities can be properly compared visually with colours stretched
accross the same range.
The colours used are the 'standard' colours commonly s... | [
"def",
"mmi_ramp_roman",
"(",
"raster_layer",
")",
":",
"items",
"=",
"[",
"]",
"sorted_mmi_scale",
"=",
"sorted",
"(",
"earthquake_mmi_scale",
"[",
"'classes'",
"]",
",",
"key",
"=",
"itemgetter",
"(",
"'value'",
")",
")",
"for",
"class_max",
"in",
"sorted_... | Generate an mmi ramp using range of 1-10 on roman.
A standarised range is used so that two shakemaps of different
intensities can be properly compared visually with colours stretched
accross the same range.
The colours used are the 'standard' colours commonly shown for the
mercalli scale e.g. on w... | [
"Generate",
"an",
"mmi",
"ramp",
"using",
"range",
"of",
"1",
"-",
"10",
"on",
"roman",
"."
] | python | train | 34.675676 |
pypa/pipenv | pipenv/vendor/distlib/_backport/tarfile.py | https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/vendor/distlib/_backport/tarfile.py#L2372-L2392 | def chown(self, tarinfo, targetpath):
"""Set owner of targetpath according to tarinfo.
"""
if pwd and hasattr(os, "geteuid") and os.geteuid() == 0:
# We have to be root to do so.
try:
g = grp.getgrnam(tarinfo.gname)[2]
except KeyError:
... | [
"def",
"chown",
"(",
"self",
",",
"tarinfo",
",",
"targetpath",
")",
":",
"if",
"pwd",
"and",
"hasattr",
"(",
"os",
",",
"\"geteuid\"",
")",
"and",
"os",
".",
"geteuid",
"(",
")",
"==",
"0",
":",
"# We have to be root to do so.",
"try",
":",
"g",
"=",
... | Set owner of targetpath according to tarinfo. | [
"Set",
"owner",
"of",
"targetpath",
"according",
"to",
"tarinfo",
"."
] | python | train | 38.285714 |
twosigma/beakerx | beakerx/setupbase.py | https://github.com/twosigma/beakerx/blob/404de61ed627d9daaf6b77eb4859e7cb6f37413f/beakerx/setupbase.py#L296-L320 | def run_gradle(path=kernel_path, cmd='build', skip_tests=False):
"""Return a Command for running gradle scripts.
Parameters
----------
path: str, optional
The base path of the node package. Defaults to the repo root.
cmd: str, optional
The command to run with gradlew.
"""
... | [
"def",
"run_gradle",
"(",
"path",
"=",
"kernel_path",
",",
"cmd",
"=",
"'build'",
",",
"skip_tests",
"=",
"False",
")",
":",
"class",
"Gradle",
"(",
"BaseCommand",
")",
":",
"description",
"=",
"'Run gradle script'",
"def",
"skip_test_option",
"(",
"self",
"... | Return a Command for running gradle scripts.
Parameters
----------
path: str, optional
The base path of the node package. Defaults to the repo root.
cmd: str, optional
The command to run with gradlew. | [
"Return",
"a",
"Command",
"for",
"running",
"gradle",
"scripts",
"."
] | python | train | 29.24 |
joke2k/django-environ | environ/environ.py | https://github.com/joke2k/django-environ/blob/c2620021614557abe197578f99deeef42af3e082/environ/environ.py#L495-L537 | def email_url_config(cls, url, backend=None):
"""Parses an email URL."""
config = {}
url = urlparse(url) if not isinstance(url, cls.URL_CLASS) else url
# Remove query strings
path = url.path[1:]
path = unquote_plus(path.split('?', 2)[0])
# Update with environm... | [
"def",
"email_url_config",
"(",
"cls",
",",
"url",
",",
"backend",
"=",
"None",
")",
":",
"config",
"=",
"{",
"}",
"url",
"=",
"urlparse",
"(",
"url",
")",
"if",
"not",
"isinstance",
"(",
"url",
",",
"cls",
".",
"URL_CLASS",
")",
"else",
"url",
"# ... | Parses an email URL. | [
"Parses",
"an",
"email",
"URL",
"."
] | python | train | 33.813953 |
rhayes777/PyAutoFit | autofit/conf.py | https://github.com/rhayes777/PyAutoFit/blob/a9e6144abb08edfc6a6906c4030d7119bf8d3e14/autofit/conf.py#L128-L153 | def get_for_nearest_ancestor(self, cls, attribute_name):
"""
Find a prior with the attribute analysis_path from the config for this class or one of its ancestors
Parameters
----------
cls: class
The class of interest
attribute_name: String
The ana... | [
"def",
"get_for_nearest_ancestor",
"(",
"self",
",",
"cls",
",",
"attribute_name",
")",
":",
"for",
"family_cls",
"in",
"family",
"(",
"cls",
")",
":",
"if",
"self",
".",
"has",
"(",
"family_cls",
".",
"__module__",
",",
"family_cls",
".",
"__name__",
",",... | Find a prior with the attribute analysis_path from the config for this class or one of its ancestors
Parameters
----------
cls: class
The class of interest
attribute_name: String
The analysis_path of the attribute
Returns
-------
prior_arr... | [
"Find",
"a",
"prior",
"with",
"the",
"attribute",
"analysis_path",
"from",
"the",
"config",
"for",
"this",
"class",
"or",
"one",
"of",
"its",
"ancestors"
] | python | train | 48.807692 |
buruzaemon/natto-py | natto/environment.py | https://github.com/buruzaemon/natto-py/blob/018fe004c47c45c66bdf2e03fe24e981ae089b76/natto/environment.py#L164-L199 | def __regkey_value(self, path, name='', start_key=None):
r'''Return the data of value mecabrc at MeCab HKEY node.
On Windows, the path to the mecabrc as set in the Windows Registry is
used to deduce the path to libmecab.dll.
Returns:
The full path to the mecabrc on W... | [
"def",
"__regkey_value",
"(",
"self",
",",
"path",
",",
"name",
"=",
"''",
",",
"start_key",
"=",
"None",
")",
":",
"if",
"sys",
".",
"version",
"<",
"'3'",
":",
"import",
"_winreg",
"as",
"reg",
"else",
":",
"import",
"winreg",
"as",
"reg",
"def",
... | r'''Return the data of value mecabrc at MeCab HKEY node.
On Windows, the path to the mecabrc as set in the Windows Registry is
used to deduce the path to libmecab.dll.
Returns:
The full path to the mecabrc on Windows.
Raises:
WindowsError: A problem wa... | [
"r",
"Return",
"the",
"data",
"of",
"value",
"mecabrc",
"at",
"MeCab",
"HKEY",
"node",
".",
"On",
"Windows",
"the",
"path",
"to",
"the",
"mecabrc",
"as",
"set",
"in",
"the",
"Windows",
"Registry",
"is",
"used",
"to",
"deduce",
"the",
"path",
"to",
"lib... | python | train | 37.138889 |
mitsei/dlkit | dlkit/json_/assessment/mixins.py | https://github.com/mitsei/dlkit/blob/445f968a175d61c8d92c0f617a3c17dc1dc7c584/dlkit/json_/assessment/mixins.py#L494-L529 | def get_questions(self, answered=None, honor_sequential=True, update=True):
"""gets all available questions for this section
if answered == False: only return next unanswered question
if answered == True: only return next answered question
if answered in None: return next question wheth... | [
"def",
"get_questions",
"(",
"self",
",",
"answered",
"=",
"None",
",",
"honor_sequential",
"=",
"True",
",",
"update",
"=",
"True",
")",
":",
"def",
"update_question_list",
"(",
")",
":",
"\"\"\"Supportive function to aid readability of _get_questions.\"\"\"",
"lates... | gets all available questions for this section
if answered == False: only return next unanswered question
if answered == True: only return next answered question
if answered in None: return next question whether answered or not
if honor_sequential == True: only return questions if sectio... | [
"gets",
"all",
"available",
"questions",
"for",
"this",
"section"
] | python | train | 48 |
d0c-s4vage/pfp | pfp/interp.py | https://github.com/d0c-s4vage/pfp/blob/32f2d34fdec1c70019fa83c7006d5e3be0f92fcd/pfp/interp.py#L353-L364 | def add_local(self, field_name, field):
"""Add a local variable in the current scope
:field_name: The field's name
:field: The field
:returns: None
"""
self._dlog("adding local '{}'".format(field_name))
field._pfp__name = field_name
# TODO do we allow cl... | [
"def",
"add_local",
"(",
"self",
",",
"field_name",
",",
"field",
")",
":",
"self",
".",
"_dlog",
"(",
"\"adding local '{}'\"",
".",
"format",
"(",
"field_name",
")",
")",
"field",
".",
"_pfp__name",
"=",
"field_name",
"# TODO do we allow clobbering of locals???",... | Add a local variable in the current scope
:field_name: The field's name
:field: The field
:returns: None | [
"Add",
"a",
"local",
"variable",
"in",
"the",
"current",
"scope"
] | python | train | 31.916667 |
potash/drain | drain/data.py | https://github.com/potash/drain/blob/ddd62081cb9317beb5d21f86c8b4bb196ca3d222/drain/data.py#L44-L56 | def apply(self, df):
"""Takes a pd.DataFrame and returns the newly defined column, i.e.
a pd.Series that has the same index as `df`.
"""
if hasattr(self.definition, '__call__'):
r = self.definition(df)
elif self.definition in df.columns:
r = df[self.defini... | [
"def",
"apply",
"(",
"self",
",",
"df",
")",
":",
"if",
"hasattr",
"(",
"self",
".",
"definition",
",",
"'__call__'",
")",
":",
"r",
"=",
"self",
".",
"definition",
"(",
"df",
")",
"elif",
"self",
".",
"definition",
"in",
"df",
".",
"columns",
":",... | Takes a pd.DataFrame and returns the newly defined column, i.e.
a pd.Series that has the same index as `df`. | [
"Takes",
"a",
"pd",
".",
"DataFrame",
"and",
"returns",
"the",
"newly",
"defined",
"column",
"i",
".",
"e",
".",
"a",
"pd",
".",
"Series",
"that",
"has",
"the",
"same",
"index",
"as",
"df",
"."
] | python | train | 45.384615 |
readbeyond/aeneas | aeneas/validator.py | https://github.com/readbeyond/aeneas/blob/9d95535ad63eef4a98530cfdff033b8c35315ee1/aeneas/validator.py#L380-L410 | def check_config_xml(self, contents):
"""
Check whether the given XML config file contents
is well-formed and it has all the required parameters.
:param string contents: the XML config file contents or XML config string
:param bool is_config_string: if ``True``, contents is a co... | [
"def",
"check_config_xml",
"(",
"self",
",",
"contents",
")",
":",
"self",
".",
"log",
"(",
"u\"Checking contents XML config file\"",
")",
"self",
".",
"result",
"=",
"ValidatorResult",
"(",
")",
"if",
"self",
".",
"_are_safety_checks_disabled",
"(",
"u\"check_con... | Check whether the given XML config file contents
is well-formed and it has all the required parameters.
:param string contents: the XML config file contents or XML config string
:param bool is_config_string: if ``True``, contents is a config string
:rtype: :class:`~aeneas.validator.Vali... | [
"Check",
"whether",
"the",
"given",
"XML",
"config",
"file",
"contents",
"is",
"well",
"-",
"formed",
"and",
"it",
"has",
"all",
"the",
"required",
"parameters",
"."
] | python | train | 50.193548 |
pycontribs/jira | jira/client.py | https://github.com/pycontribs/jira/blob/397db5d78441ed6a680a9b7db4c62030ade1fd8a/jira/client.py#L3426-L3498 | def create_project(self, key, name=None, assignee=None, type="Software", template_name=None):
"""Create a project with the specified parameters.
:param key: Mandatory. Must match JIRA project key requirements, usually only 2-10 uppercase characters.
:type: str
:param name: If not specif... | [
"def",
"create_project",
"(",
"self",
",",
"key",
",",
"name",
"=",
"None",
",",
"assignee",
"=",
"None",
",",
"type",
"=",
"\"Software\"",
",",
"template_name",
"=",
"None",
")",
":",
"if",
"assignee",
"is",
"None",
":",
"assignee",
"=",
"self",
".",
... | Create a project with the specified parameters.
:param key: Mandatory. Must match JIRA project key requirements, usually only 2-10 uppercase characters.
:type: str
:param name: If not specified it will use the key value.
:type name: Optional[str]
:param assignee: If not specifie... | [
"Create",
"a",
"project",
"with",
"the",
"specified",
"parameters",
"."
] | python | train | 43.69863 |
python-diamond/Diamond | src/collectors/onewire/onewire.py | https://github.com/python-diamond/Diamond/blob/0f3eb04327d6d3ed5e53a9967d6c9d2c09714a47/src/collectors/onewire/onewire.py#L36-L47 | def get_default_config(self):
"""
Returns the default collector settings
"""
config = super(OneWireCollector, self).get_default_config()
config.update({
'path': 'owfs',
'owfs': '/mnt/1wire',
# 'scan': {'temperature': 't'},
# 'id:24.... | [
"def",
"get_default_config",
"(",
"self",
")",
":",
"config",
"=",
"super",
"(",
"OneWireCollector",
",",
"self",
")",
".",
"get_default_config",
"(",
")",
"config",
".",
"update",
"(",
"{",
"'path'",
":",
"'owfs'",
",",
"'owfs'",
":",
"'/mnt/1wire'",
",",... | Returns the default collector settings | [
"Returns",
"the",
"default",
"collector",
"settings"
] | python | train | 31.833333 |
nirum/descent | descent/proxops.py | https://github.com/nirum/descent/blob/074c8452f15a0da638668a4fe139fde06ccfae7f/descent/proxops.py#L269-L300 | def fantope(x, rho, dim, tol=1e-4):
"""
Projection onto the fantope [1]_
.. [1] Vu, Vincent Q., et al. "Fantope projection and selection: A
near-optimal convex relaxation of sparse PCA." Advances in
neural information processing systems. 2013.
"""
U, V = np.linalg.eigh(x)
... | [
"def",
"fantope",
"(",
"x",
",",
"rho",
",",
"dim",
",",
"tol",
"=",
"1e-4",
")",
":",
"U",
",",
"V",
"=",
"np",
".",
"linalg",
".",
"eigh",
"(",
"x",
")",
"minval",
",",
"maxval",
"=",
"np",
".",
"maximum",
"(",
"U",
".",
"min",
"(",
")",
... | Projection onto the fantope [1]_
.. [1] Vu, Vincent Q., et al. "Fantope projection and selection: A
near-optimal convex relaxation of sparse PCA." Advances in
neural information processing systems. 2013. | [
"Projection",
"onto",
"the",
"fantope",
"[",
"1",
"]",
"_"
] | python | valid | 25.0625 |
tyiannak/pyAudioAnalysis | pyAudioAnalysis/audioBasicIO.py | https://github.com/tyiannak/pyAudioAnalysis/blob/e3da991e7247492deba50648a4c7c0f41e684af4/pyAudioAnalysis/audioBasicIO.py#L5-L38 | def convertDirMP3ToWav(dirName, Fs, nC, useMp3TagsAsName = False):
'''
This function converts the MP3 files stored in a folder to WAV. If required, the output names of the WAV files are based on MP3 tags, otherwise the same names are used.
ARGUMENTS:
- dirName: the path of the folder where the MP3s... | [
"def",
"convertDirMP3ToWav",
"(",
"dirName",
",",
"Fs",
",",
"nC",
",",
"useMp3TagsAsName",
"=",
"False",
")",
":",
"types",
"=",
"(",
"dirName",
"+",
"os",
".",
"sep",
"+",
"'*.mp3'",
",",
")",
"# the tuple of file types",
"filesToProcess",
"=",
"[",
"]",... | This function converts the MP3 files stored in a folder to WAV. If required, the output names of the WAV files are based on MP3 tags, otherwise the same names are used.
ARGUMENTS:
- dirName: the path of the folder where the MP3s are stored
- Fs: the sampling rate of the generated WAV files
... | [
"This",
"function",
"converts",
"the",
"MP3",
"files",
"stored",
"in",
"a",
"folder",
"to",
"WAV",
".",
"If",
"required",
"the",
"output",
"names",
"of",
"the",
"WAV",
"files",
"are",
"based",
"on",
"MP3",
"tags",
"otherwise",
"the",
"same",
"names",
"ar... | python | train | 48.117647 |
MostAwesomeDude/gentleman | gentleman/base.py | https://github.com/MostAwesomeDude/gentleman/blob/17fb8ffb922aa4af9d8bcab85e452c9311d41805/gentleman/base.py#L1236-L1253 | def DeleteGroup(r, group, dry_run=False):
"""
Deletes a node group.
@type group: str
@param group: the node group to delete
@type dry_run: bool
@param dry_run: whether to peform a dry run
@rtype: int
@return: job id
"""
query = {
"dry-run": dry_run,
}
return r... | [
"def",
"DeleteGroup",
"(",
"r",
",",
"group",
",",
"dry_run",
"=",
"False",
")",
":",
"query",
"=",
"{",
"\"dry-run\"",
":",
"dry_run",
",",
"}",
"return",
"r",
".",
"request",
"(",
"\"delete\"",
",",
"\"/2/groups/%s\"",
"%",
"group",
",",
"query",
"="... | Deletes a node group.
@type group: str
@param group: the node group to delete
@type dry_run: bool
@param dry_run: whether to peform a dry run
@rtype: int
@return: job id | [
"Deletes",
"a",
"node",
"group",
"."
] | python | train | 19.888889 |
ucsb-cs/submit | submit/helpers.py | https://github.com/ucsb-cs/submit/blob/92810c81255a4fc6bbebac1ac8aae856fd576ffe/submit/helpers.py#L434-L470 | def prepare_renderable(request, test_case_result, is_admin):
"""Return a completed Renderable."""
test_case = test_case_result.test_case
file_directory = request.registry.settings['file_directory']
sha1 = test_case_result.diff.sha1 if test_case_result.diff else None
kwargs = {'number': test_case.id,... | [
"def",
"prepare_renderable",
"(",
"request",
",",
"test_case_result",
",",
"is_admin",
")",
":",
"test_case",
"=",
"test_case_result",
".",
"test_case",
"file_directory",
"=",
"request",
".",
"registry",
".",
"settings",
"[",
"'file_directory'",
"]",
"sha1",
"=",
... | Return a completed Renderable. | [
"Return",
"a",
"completed",
"Renderable",
"."
] | python | train | 44.810811 |
ARMmbed/mbed-cloud-sdk-python | scripts/tag_and_release.py | https://github.com/ARMmbed/mbed-cloud-sdk-python/blob/c0af86fb2cdd4dc7ed26f236139241067d293509/scripts/tag_and_release.py#L32-L45 | def git_url_ssh_to_https(url):
"""Convert a git url
url will look like
https://github.com/ARMmbed/mbed-cloud-sdk-python.git
or
git@github.com:ARMmbed/mbed-cloud-sdk-python.git
we want:
https://${GITHUB_TOKEN}@github.com/ARMmbed/mbed-cloud-sdk-python-private.git
"""
path = url.split(... | [
"def",
"git_url_ssh_to_https",
"(",
"url",
")",
":",
"path",
"=",
"url",
".",
"split",
"(",
"'github.com'",
",",
"1",
")",
"[",
"1",
"]",
"[",
"1",
":",
"]",
".",
"strip",
"(",
")",
"new",
"=",
"'https://{GITHUB_TOKEN}@github.com/%s'",
"%",
"path",
"pr... | Convert a git url
url will look like
https://github.com/ARMmbed/mbed-cloud-sdk-python.git
or
git@github.com:ARMmbed/mbed-cloud-sdk-python.git
we want:
https://${GITHUB_TOKEN}@github.com/ARMmbed/mbed-cloud-sdk-python-private.git | [
"Convert",
"a",
"git",
"url"
] | python | train | 35.714286 |
chaddotson/noaa_radar | noaa_radar/radar.py | https://github.com/chaddotson/noaa_radar/blob/ebb1e8d87d4b35b8942867446deced74b22a47cc/noaa_radar/radar.py#L112-L141 | def get_composite_reflectivity(self, tower_id, background='#000000', include_legend=True, include_counties=True,
include_warnings=True, include_highways=True, include_cities=True,
include_rivers=True, include_topography=True):
"""
Get... | [
"def",
"get_composite_reflectivity",
"(",
"self",
",",
"tower_id",
",",
"background",
"=",
"'#000000'",
",",
"include_legend",
"=",
"True",
",",
"include_counties",
"=",
"True",
",",
"include_warnings",
"=",
"True",
",",
"include_highways",
"=",
"True",
",",
"in... | Get the composite reflectivity for a noaa radar site.
:param tower_id: The noaa tower id. Ex Huntsville, Al -> 'HTX'.
:type tower_id: str
:param background: The hex background color.
:type background: str
:param include_legend: True - include legend.
:type include_legend... | [
"Get",
"the",
"composite",
"reflectivity",
"for",
"a",
"noaa",
"radar",
"site",
".",
":",
"param",
"tower_id",
":",
"The",
"noaa",
"tower",
"id",
".",
"Ex",
"Huntsville",
"Al",
"-",
">",
"HTX",
".",
":",
"type",
"tower_id",
":",
"str",
":",
"param",
... | python | train | 57.933333 |
willkg/everett | everett/manager.py | https://github.com/willkg/everett/blob/5653134af59f439d2b33f3939fab2b8544428f11/everett/manager.py#L199-L214 | def get_key_from_envs(envs, key):
"""Return the value of a key from the given dict respecting namespaces.
Data can also be a list of data dicts.
"""
# if it barks like a dict, make it a list have to use `get` since dicts and
# lists both have __getitem__
if hasattr(envs, 'get'):
envs =... | [
"def",
"get_key_from_envs",
"(",
"envs",
",",
"key",
")",
":",
"# if it barks like a dict, make it a list have to use `get` since dicts and",
"# lists both have __getitem__",
"if",
"hasattr",
"(",
"envs",
",",
"'get'",
")",
":",
"envs",
"=",
"[",
"envs",
"]",
"for",
"... | Return the value of a key from the given dict respecting namespaces.
Data can also be a list of data dicts. | [
"Return",
"the",
"value",
"of",
"a",
"key",
"from",
"the",
"given",
"dict",
"respecting",
"namespaces",
"."
] | python | train | 25.375 |
huyingxi/Synonyms | synonyms/utils.py | https://github.com/huyingxi/Synonyms/blob/fe7450d51d9ad825fdba86b9377da9dc76ae26a4/synonyms/utils.py#L222-L227 | def any2utf8(text, errors='strict', encoding='utf8'):
"""Convert a string (unicode or bytestring in `encoding`), to bytestring in utf8."""
if isinstance(text, unicode):
return text.encode('utf8')
# do bytestring -> unicode -> utf8 full circle, to ensure valid utf8
return unicode(text, encoding, ... | [
"def",
"any2utf8",
"(",
"text",
",",
"errors",
"=",
"'strict'",
",",
"encoding",
"=",
"'utf8'",
")",
":",
"if",
"isinstance",
"(",
"text",
",",
"unicode",
")",
":",
"return",
"text",
".",
"encode",
"(",
"'utf8'",
")",
"# do bytestring -> unicode -> utf8 full... | Convert a string (unicode or bytestring in `encoding`), to bytestring in utf8. | [
"Convert",
"a",
"string",
"(",
"unicode",
"or",
"bytestring",
"in",
"encoding",
")",
"to",
"bytestring",
"in",
"utf8",
"."
] | python | train | 57.333333 |
kubernetes-client/python | kubernetes/client/apis/apps_v1_api.py | https://github.com/kubernetes-client/python/blob/5e512ff564c244c50cab780d821542ed56aa965a/kubernetes/client/apis/apps_v1_api.py#L3100-L3126 | def list_stateful_set_for_all_namespaces(self, **kwargs):
"""
list or watch objects of kind StatefulSet
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please pass async_req=True
>>> thread = api.list_stateful_set_for_all_namespaces(... | [
"def",
"list_stateful_set_for_all_namespaces",
"(",
"self",
",",
"*",
"*",
"kwargs",
")",
":",
"kwargs",
"[",
"'_return_http_data_only'",
"]",
"=",
"True",
"if",
"kwargs",
".",
"get",
"(",
"'async_req'",
")",
":",
"return",
"self",
".",
"list_stateful_set_for_al... | list or watch objects of kind StatefulSet
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please pass async_req=True
>>> thread = api.list_stateful_set_for_all_namespaces(async_req=True)
>>> result = thread.get()
:param async_req bo... | [
"list",
"or",
"watch",
"objects",
"of",
"kind",
"StatefulSet",
"This",
"method",
"makes",
"a",
"synchronous",
"HTTP",
"request",
"by",
"default",
".",
"To",
"make",
"an",
"asynchronous",
"HTTP",
"request",
"please",
"pass",
"async_req",
"=",
"True",
">>>",
"... | python | train | 169.222222 |
mlperf/training | reinforcement/tensorflow/minigo/ml_perf/reference_implementation.py | https://github.com/mlperf/training/blob/1c6ae725a81d15437a2b2df05cac0673fde5c3a4/reinforcement/tensorflow/minigo/ml_perf/reference_implementation.py#L348-L357 | async def evaluate_trained_model(state):
"""Evaluate the most recently trained model against the current best model.
Args:
state: the RL loop State instance.
"""
return await evaluate_model(
state.train_model_path, state.best_model_path,
os.path.join(fsdb.eval_dir(), state.train_model_name), s... | [
"async",
"def",
"evaluate_trained_model",
"(",
"state",
")",
":",
"return",
"await",
"evaluate_model",
"(",
"state",
".",
"train_model_path",
",",
"state",
".",
"best_model_path",
",",
"os",
".",
"path",
".",
"join",
"(",
"fsdb",
".",
"eval_dir",
"(",
")",
... | Evaluate the most recently trained model against the current best model.
Args:
state: the RL loop State instance. | [
"Evaluate",
"the",
"most",
"recently",
"trained",
"model",
"against",
"the",
"current",
"best",
"model",
"."
] | python | train | 32.1 |
kwikteam/phy | phy/io/array.py | https://github.com/kwikteam/phy/blob/7e9313dc364304b7d2bd03b92938347343703003/phy/io/array.py#L414-L425 | def excerpts(n_samples, n_excerpts=None, excerpt_size=None):
"""Yield (start, end) where start is included and end is excluded."""
assert n_excerpts >= 2
step = _excerpt_step(n_samples,
n_excerpts=n_excerpts,
excerpt_size=excerpt_size)
for i in range(n_e... | [
"def",
"excerpts",
"(",
"n_samples",
",",
"n_excerpts",
"=",
"None",
",",
"excerpt_size",
"=",
"None",
")",
":",
"assert",
"n_excerpts",
">=",
"2",
"step",
"=",
"_excerpt_step",
"(",
"n_samples",
",",
"n_excerpts",
"=",
"n_excerpts",
",",
"excerpt_size",
"="... | Yield (start, end) where start is included and end is excluded. | [
"Yield",
"(",
"start",
"end",
")",
"where",
"start",
"is",
"included",
"and",
"end",
"is",
"excluded",
"."
] | python | train | 39 |
agamdua/mixtures | mixtures/mixtures.py | https://github.com/agamdua/mixtures/blob/9c67f3684ddac53d8a636a4353a266e98d09e54c/mixtures/mixtures.py#L50-L61 | def get_fields(model_class):
"""
Pass in a mongo model class and extract all the attributes which
are mongoengine fields
Returns:
list of strings of field attributes
"""
return [
attr for attr, value in model_class.__dict__.items()
if issubclass(type(value), (mongo.base.... | [
"def",
"get_fields",
"(",
"model_class",
")",
":",
"return",
"[",
"attr",
"for",
"attr",
",",
"value",
"in",
"model_class",
".",
"__dict__",
".",
"items",
"(",
")",
"if",
"issubclass",
"(",
"type",
"(",
"value",
")",
",",
"(",
"mongo",
".",
"base",
"... | Pass in a mongo model class and extract all the attributes which
are mongoengine fields
Returns:
list of strings of field attributes | [
"Pass",
"in",
"a",
"mongo",
"model",
"class",
"and",
"extract",
"all",
"the",
"attributes",
"which",
"are",
"mongoengine",
"fields"
] | python | train | 30.25 |
datadesk/django-bakery | bakery/static_views.py | https://github.com/datadesk/django-bakery/blob/e2feb13a66552a388fbcfaaacdd504bba08d3c69/bakery/static_views.py#L19-L83 | def serve(request, path, document_root=None, show_indexes=False, default=''):
"""
Serve static files below a given point in the directory structure.
To use, put a URL pattern such as::
(r'^(?P<path>.*)$', 'django.views.static.serve',
{'document_root' : '/path/to/my/files/'})
in yo... | [
"def",
"serve",
"(",
"request",
",",
"path",
",",
"document_root",
"=",
"None",
",",
"show_indexes",
"=",
"False",
",",
"default",
"=",
"''",
")",
":",
"# Clean up given path to only allow serving files below document_root.",
"path",
"=",
"posixpath",
".",
"normpath... | Serve static files below a given point in the directory structure.
To use, put a URL pattern such as::
(r'^(?P<path>.*)$', 'django.views.static.serve',
{'document_root' : '/path/to/my/files/'})
in your URLconf. You must provide the ``document_root`` param. You may
also set ``show_inde... | [
"Serve",
"static",
"files",
"below",
"a",
"given",
"point",
"in",
"the",
"directory",
"structure",
"."
] | python | train | 41.6 |
googlefonts/ufo2ft | Lib/ufo2ft/featureWriters/__init__.py | https://github.com/googlefonts/ufo2ft/blob/915b986558e87bee288765d9218cc1cd4ebf7f4c/Lib/ufo2ft/featureWriters/__init__.py#L34-L59 | def isValidFeatureWriter(klass):
"""Return True if 'klass' is a valid feature writer class.
A valid feature writer class is a class (of type 'type'), that has
two required attributes:
1) 'tableTag' (str), which can be "GSUB", "GPOS", or other similar tags.
2) 'write' (bound method), with the signatu... | [
"def",
"isValidFeatureWriter",
"(",
"klass",
")",
":",
"if",
"not",
"isclass",
"(",
"klass",
")",
":",
"logger",
".",
"error",
"(",
"\"%r is not a class\"",
",",
"klass",
")",
"return",
"False",
"if",
"not",
"hasattr",
"(",
"klass",
",",
"\"tableTag\"",
")... | Return True if 'klass' is a valid feature writer class.
A valid feature writer class is a class (of type 'type'), that has
two required attributes:
1) 'tableTag' (str), which can be "GSUB", "GPOS", or other similar tags.
2) 'write' (bound method), with the signature matching the same method
from ... | [
"Return",
"True",
"if",
"klass",
"is",
"a",
"valid",
"feature",
"writer",
"class",
".",
"A",
"valid",
"feature",
"writer",
"class",
"is",
"a",
"class",
"(",
"of",
"type",
"type",
")",
"that",
"has",
"two",
"required",
"attributes",
":",
"1",
")",
"tabl... | python | train | 38.846154 |
flowersteam/explauto | explauto/sensorimotor_model/inverse/cma.py | https://github.com/flowersteam/explauto/blob/cf0f81ecb9f6412f7276a95bd27359000e1e26b6/explauto/sensorimotor_model/inverse/cma.py#L6659-L6730 | def disp(self, idx=100): # r_[0:5,1e2:1e9:1e2,-10:0]):
"""displays selected data from (files written by) the class `CMADataLogger`.
Arguments
---------
`idx`
indices corresponding to rows in the data file;
if idx is a scalar (int), the first two, then e... | [
"def",
"disp",
"(",
"self",
",",
"idx",
"=",
"100",
")",
":",
"# r_[0:5,1e2:1e9:1e2,-10:0]):",
"filenameprefix",
"=",
"self",
".",
"name_prefix",
"def",
"printdatarow",
"(",
"dat",
",",
"iteration",
")",
":",
"\"\"\"print data of iteration i\"\"\"",
"i",
"=",
"n... | displays selected data from (files written by) the class `CMADataLogger`.
Arguments
---------
`idx`
indices corresponding to rows in the data file;
if idx is a scalar (int), the first two, then every idx-th,
and the last three rows are displayed. ... | [
"displays",
"selected",
"data",
"from",
"(",
"files",
"written",
"by",
")",
"the",
"class",
"CMADataLogger",
"."
] | python | train | 36.597222 |
kejbaly2/metrique | metrique/result.py | https://github.com/kejbaly2/metrique/blob/a10b076097441b7dde687949139f702f5c1e1b35/metrique/result.py#L227-L275 | def get_dates_range(self, scale='auto', start=None, end=None,
date_max='2010-01-01'):
'''
Returns a list of dates sampled according to the specified parameters.
:param scale: {'auto', 'maximum', 'daily', 'weekly', 'monthly',
'quarterly', 'yearly'}
... | [
"def",
"get_dates_range",
"(",
"self",
",",
"scale",
"=",
"'auto'",
",",
"start",
"=",
"None",
",",
"end",
"=",
"None",
",",
"date_max",
"=",
"'2010-01-01'",
")",
":",
"if",
"scale",
"not",
"in",
"[",
"'auto'",
",",
"'maximum'",
",",
"'daily'",
",",
... | Returns a list of dates sampled according to the specified parameters.
:param scale: {'auto', 'maximum', 'daily', 'weekly', 'monthly',
'quarterly', 'yearly'}
Scale specifies the sampling intervals.
'auto' will heuristically choose a scale for quick processing
:param ... | [
"Returns",
"a",
"list",
"of",
"dates",
"sampled",
"according",
"to",
"the",
"specified",
"parameters",
"."
] | python | train | 50.204082 |
cmaugg/pystatemachine | pystatemachine.py | https://github.com/cmaugg/pystatemachine/blob/5a6cd9cbd88180a86569cda1e564331753299c6c/pystatemachine.py#L151-L182 | def acts_as_state_machine(cls):
"""
a decorator which sets two properties on a class:
* the 'current_state' property: a read-only property, returning the state machine's current state, as 'State' object
* the 'states' property: a tuple of all valid state machine states, as 'State' objects
cl... | [
"def",
"acts_as_state_machine",
"(",
"cls",
")",
":",
"assert",
"not",
"hasattr",
"(",
"cls",
",",
"'current_state'",
")",
",",
"'{0} already has a \"current_state\" attribute!'",
".",
"format",
"(",
"cls",
")",
"assert",
"not",
"hasattr",
"(",
"cls",
",",
"'sta... | a decorator which sets two properties on a class:
* the 'current_state' property: a read-only property, returning the state machine's current state, as 'State' object
* the 'states' property: a tuple of all valid state machine states, as 'State' objects
class objects may use current_state and states... | [
"a",
"decorator",
"which",
"sets",
"two",
"properties",
"on",
"a",
"class",
":",
"*",
"the",
"current_state",
"property",
":",
"a",
"read",
"-",
"only",
"property",
"returning",
"the",
"state",
"machine",
"s",
"current",
"state",
"as",
"State",
"object",
"... | python | train | 44.03125 |
saltstack/salt | salt/utils/vmware.py | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/utils/vmware.py#L3475-L3523 | def power_cycle_vm(virtual_machine, action='on'):
'''
Powers on/off a virtual machine specified by it's name.
virtual_machine
vim.VirtualMachine object to power on/off virtual machine
action
Operation option to power on/off the machine
'''
if action == 'on':
try:
... | [
"def",
"power_cycle_vm",
"(",
"virtual_machine",
",",
"action",
"=",
"'on'",
")",
":",
"if",
"action",
"==",
"'on'",
":",
"try",
":",
"task",
"=",
"virtual_machine",
".",
"PowerOn",
"(",
")",
"task_name",
"=",
"'power on'",
"except",
"vim",
".",
"fault",
... | Powers on/off a virtual machine specified by it's name.
virtual_machine
vim.VirtualMachine object to power on/off virtual machine
action
Operation option to power on/off the machine | [
"Powers",
"on",
"/",
"off",
"a",
"virtual",
"machine",
"specified",
"by",
"it",
"s",
"name",
"."
] | python | train | 39.061224 |
chaoss/grimoirelab-elk | grimoire_elk/enriched/git.py | https://github.com/chaoss/grimoirelab-elk/blob/64e08b324b36d9f6909bf705145d6451c8d34e65/grimoire_elk/enriched/git.py#L425-L434 | def __fix_field_date(self, item, attribute):
"""Fix possible errors in the field date"""
field_date = str_to_datetime(item[attribute])
try:
_ = int(field_date.strftime("%z")[0:3])
except ValueError:
logger.warning("%s in commit %s has a wrong format", attribute,... | [
"def",
"__fix_field_date",
"(",
"self",
",",
"item",
",",
"attribute",
")",
":",
"field_date",
"=",
"str_to_datetime",
"(",
"item",
"[",
"attribute",
"]",
")",
"try",
":",
"_",
"=",
"int",
"(",
"field_date",
".",
"strftime",
"(",
"\"%z\"",
")",
"[",
"0... | Fix possible errors in the field date | [
"Fix",
"possible",
"errors",
"in",
"the",
"field",
"date"
] | python | train | 40.1 |
mila/pyoo | pyoo.py | https://github.com/mila/pyoo/blob/1e024999f608c87ea72cd443e39c89eb0ba3cc62/pyoo.py#L1767-L1774 | def date_from_number(self, value):
"""
Converts a float value to corresponding datetime instance.
"""
if not isinstance(value, numbers.Real):
return None
delta = datetime.timedelta(days=value)
return self._null_date + delta | [
"def",
"date_from_number",
"(",
"self",
",",
"value",
")",
":",
"if",
"not",
"isinstance",
"(",
"value",
",",
"numbers",
".",
"Real",
")",
":",
"return",
"None",
"delta",
"=",
"datetime",
".",
"timedelta",
"(",
"days",
"=",
"value",
")",
"return",
"sel... | Converts a float value to corresponding datetime instance. | [
"Converts",
"a",
"float",
"value",
"to",
"corresponding",
"datetime",
"instance",
"."
] | python | train | 34.5 |
numenta/htmresearch | htmresearch/algorithms/TM.py | https://github.com/numenta/htmresearch/blob/70c096b09a577ea0432c3f3bfff4442d4871b7aa/htmresearch/algorithms/TM.py#L1036-L1079 | def computePhase2(self, doLearn=False):
"""
This is the phase 2 of learning, inference and multistep prediction. During
this phase, all the cell with lateral support have their predictedState
turned on and the firing segments are queued up for updates.
Parameters:
------------------------------... | [
"def",
"computePhase2",
"(",
"self",
",",
"doLearn",
"=",
"False",
")",
":",
"# Phase 2: compute predicted state for each cell",
"# - if a segment has enough horizontal connections firing because of",
"# bottomUpInput, it's set to be predicting, and we queue up the segment",
"# for rei... | This is the phase 2 of learning, inference and multistep prediction. During
this phase, all the cell with lateral support have their predictedState
turned on and the firing segments are queued up for updates.
Parameters:
--------------------------------------------
doLearn: Boolean flag to que... | [
"This",
"is",
"the",
"phase",
"2",
"of",
"learning",
"inference",
"and",
"multistep",
"prediction",
".",
"During",
"this",
"phase",
"all",
"the",
"cell",
"with",
"lateral",
"support",
"have",
"their",
"predictedState",
"turned",
"on",
"and",
"the",
"firing",
... | python | train | 42 |
cloud-custodian/cloud-custodian | tools/sandbox/zerodark/zerodark/utils.py | https://github.com/cloud-custodian/cloud-custodian/blob/52ef732eb3d7bc939d1579faf519314814695c08/tools/sandbox/zerodark/zerodark/utils.py#L25-L30 | def row_factory(cursor, row):
"""Returns a sqlite row factory that returns a dictionary"""
d = {}
for idx, col in enumerate(cursor.description):
d[col[0]] = row[idx]
return d | [
"def",
"row_factory",
"(",
"cursor",
",",
"row",
")",
":",
"d",
"=",
"{",
"}",
"for",
"idx",
",",
"col",
"in",
"enumerate",
"(",
"cursor",
".",
"description",
")",
":",
"d",
"[",
"col",
"[",
"0",
"]",
"]",
"=",
"row",
"[",
"idx",
"]",
"return",... | Returns a sqlite row factory that returns a dictionary | [
"Returns",
"a",
"sqlite",
"row",
"factory",
"that",
"returns",
"a",
"dictionary"
] | python | train | 32.166667 |
astropy/photutils | photutils/psf/epsf.py | https://github.com/astropy/photutils/blob/cc9bb4534ab76bac98cb5f374a348a2573d10401/photutils/psf/epsf.py#L862-L916 | def _interpolate_missing_data(data, mask, method='cubic'):
"""
Interpolate missing data as identified by the ``mask`` keyword.
Parameters
----------
data : 2D `~numpy.ndarray`
An array containing the 2D image.
mask : 2D bool `~numpy.ndarray`
A 2D booleen mask array with the sam... | [
"def",
"_interpolate_missing_data",
"(",
"data",
",",
"mask",
",",
"method",
"=",
"'cubic'",
")",
":",
"from",
"scipy",
"import",
"interpolate",
"data_interp",
"=",
"np",
".",
"array",
"(",
"data",
",",
"copy",
"=",
"True",
")",
"if",
"len",
"(",
"data_i... | Interpolate missing data as identified by the ``mask`` keyword.
Parameters
----------
data : 2D `~numpy.ndarray`
An array containing the 2D image.
mask : 2D bool `~numpy.ndarray`
A 2D booleen mask array with the same shape as the input
``data``, where a `True` value indicates t... | [
"Interpolate",
"missing",
"data",
"as",
"identified",
"by",
"the",
"mask",
"keyword",
"."
] | python | train | 30.709091 |
moderngl/moderngl | moderngl/context.py | https://github.com/moderngl/moderngl/blob/a8f5dce8dc72ae84a2f9523887fb5f6b620049b9/moderngl/context.py#L521-L537 | def copy_framebuffer(self, dst, src) -> None:
'''
Copy framebuffer content.
Use this method to:
- blit framebuffers.
- copy framebuffer content into a texture.
- downsample framebuffers. (it will allow to read the framebuffer's content)
... | [
"def",
"copy_framebuffer",
"(",
"self",
",",
"dst",
",",
"src",
")",
"->",
"None",
":",
"self",
".",
"mglo",
".",
"copy_framebuffer",
"(",
"dst",
".",
"mglo",
",",
"src",
".",
"mglo",
")"
] | Copy framebuffer content.
Use this method to:
- blit framebuffers.
- copy framebuffer content into a texture.
- downsample framebuffers. (it will allow to read the framebuffer's content)
- downsample a framebuffer directly to a texture.
... | [
"Copy",
"framebuffer",
"content",
"."
] | python | train | 34.823529 |
ming060/robotframework-uiautomatorlibrary | uiautomatorlibrary/Mobile.py | https://github.com/ming060/robotframework-uiautomatorlibrary/blob/b70202b6a8aa68b4efd9d029c2845407fb33451a/uiautomatorlibrary/Mobile.py#L296-L302 | def swipe_bottom(self, steps=10, *args, **selectors):
"""
Swipe the UI object with *selectors* from center to bottom
See `Swipe Left` for more details.
"""
self.device(**selectors).swipe.down(steps=steps) | [
"def",
"swipe_bottom",
"(",
"self",
",",
"steps",
"=",
"10",
",",
"*",
"args",
",",
"*",
"*",
"selectors",
")",
":",
"self",
".",
"device",
"(",
"*",
"*",
"selectors",
")",
".",
"swipe",
".",
"down",
"(",
"steps",
"=",
"steps",
")"
] | Swipe the UI object with *selectors* from center to bottom
See `Swipe Left` for more details. | [
"Swipe",
"the",
"UI",
"object",
"with",
"*",
"selectors",
"*",
"from",
"center",
"to",
"bottom"
] | python | train | 34.142857 |
dailymotion/cloudkey-py | cloudkey.py | https://github.com/dailymotion/cloudkey-py/blob/81334553e0737b87c66b12ad2f1eb8e26ef68a96/cloudkey.py#L92-L135 | def normalize(arg=None):
"""Normalizes an argument for signing purpose.
This is used for normalizing the arguments of RPC method calls.
:param arg: The argument to normalize
:return: A string representating the normalized argument.
.. doctest::
>>> from cloud.rpc import normalize
>>> ... | [
"def",
"normalize",
"(",
"arg",
"=",
"None",
")",
":",
"res",
"=",
"''",
"t_arg",
"=",
"type",
"(",
"arg",
")",
"if",
"t_arg",
"in",
"(",
"list",
",",
"tuple",
")",
":",
"for",
"i",
"in",
"arg",
":",
"res",
"+=",
"normalize",
"(",
"i",
")",
"... | Normalizes an argument for signing purpose.
This is used for normalizing the arguments of RPC method calls.
:param arg: The argument to normalize
:return: A string representating the normalized argument.
.. doctest::
>>> from cloud.rpc import normalize
>>> normalize(['foo', 42, 'bar'])
... | [
"Normalizes",
"an",
"argument",
"for",
"signing",
"purpose",
"."
] | python | train | 25.590909 |
mar10/pyftpsync | ftpsync/targets.py | https://github.com/mar10/pyftpsync/blob/bbdc94186975cdc1cc4f678474bdce08bce7bb76/ftpsync/targets.py#L480-L483 | def set_mtime(self, name, mtime, size):
"""Set modification time on file."""
self.check_write(name)
os.utime(os.path.join(self.cur_dir, name), (-1, mtime)) | [
"def",
"set_mtime",
"(",
"self",
",",
"name",
",",
"mtime",
",",
"size",
")",
":",
"self",
".",
"check_write",
"(",
"name",
")",
"os",
".",
"utime",
"(",
"os",
".",
"path",
".",
"join",
"(",
"self",
".",
"cur_dir",
",",
"name",
")",
",",
"(",
"... | Set modification time on file. | [
"Set",
"modification",
"time",
"on",
"file",
"."
] | python | train | 44 |
thomasdelaet/python-velbus | velbus/messages/push_button_status.py | https://github.com/thomasdelaet/python-velbus/blob/af2f8af43f1a24bf854eff9f3126fd7b5c41b3dd/velbus/messages/push_button_status.py#L42-L50 | def to_json(self):
"""
:return: str
"""
json_dict = self.to_json_basic()
json_dict['closed_channels'] = self.closed
json_dict['opened_channels'] = self.opened
json_dict['closed_long_channels'] = self.closed_long
return json.dumps(json_dict) | [
"def",
"to_json",
"(",
"self",
")",
":",
"json_dict",
"=",
"self",
".",
"to_json_basic",
"(",
")",
"json_dict",
"[",
"'closed_channels'",
"]",
"=",
"self",
".",
"closed",
"json_dict",
"[",
"'opened_channels'",
"]",
"=",
"self",
".",
"opened",
"json_dict",
... | :return: str | [
":",
"return",
":",
"str"
] | python | train | 32.888889 |
fumitoh/modelx | modelx/core/formula.py | https://github.com/fumitoh/modelx/blob/0180da34d052c44fb94dab9e115e218bbebfc9c3/modelx/core/formula.py#L406-L443 | def _reload(self, module=None):
"""Reload the source function from the source module.
**Internal use only**
Update the source function of the formula.
This method is used to updated the underlying formula
when the source code of the module in which the source function
is... | [
"def",
"_reload",
"(",
"self",
",",
"module",
"=",
"None",
")",
":",
"if",
"self",
".",
"module",
"is",
"None",
":",
"raise",
"RuntimeError",
"elif",
"module",
"is",
"None",
":",
"import",
"importlib",
"module",
"=",
"ModuleSource",
"(",
"importlib",
"."... | Reload the source function from the source module.
**Internal use only**
Update the source function of the formula.
This method is used to updated the underlying formula
when the source code of the module in which the source function
is read from is modified.
If the for... | [
"Reload",
"the",
"source",
"function",
"from",
"the",
"source",
"module",
"."
] | python | valid | 33.131579 |
django-danceschool/django-danceschool | danceschool/core/models.py | https://github.com/django-danceschool/django-danceschool/blob/bb08cbf39017a812a5a94bdb4ea34170bf1a30ba/danceschool/core/models.py#L317-L324 | def lastOfferedMonth(self):
'''
Sometimes a Series is associated with a month other than the one
in which the first class begins, so this returns a (year,month) tuple
that can be used in admin instead.
'''
lastOfferedSeries = self.event_set.order_by('-startTime').first()
... | [
"def",
"lastOfferedMonth",
"(",
"self",
")",
":",
"lastOfferedSeries",
"=",
"self",
".",
"event_set",
".",
"order_by",
"(",
"'-startTime'",
")",
".",
"first",
"(",
")",
"return",
"(",
"lastOfferedSeries",
".",
"year",
",",
"lastOfferedSeries",
".",
"month",
... | Sometimes a Series is associated with a month other than the one
in which the first class begins, so this returns a (year,month) tuple
that can be used in admin instead. | [
"Sometimes",
"a",
"Series",
"is",
"associated",
"with",
"a",
"month",
"other",
"than",
"the",
"one",
"in",
"which",
"the",
"first",
"class",
"begins",
"so",
"this",
"returns",
"a",
"(",
"year",
"month",
")",
"tuple",
"that",
"can",
"be",
"used",
"in",
... | python | train | 47 |
mingchen/django-cas-ng | django_cas_ng/backends.py | https://github.com/mingchen/django-cas-ng/blob/202ca92cd770d9679bfe4e9e20b41fd19b81c311/django_cas_ng/backends.py#L155-L172 | def clean_username(self, username):
"""
Performs any cleaning on the "username" prior to using it to get or
create the user object. Returns the cleaned username.
By default, changes the username case according to
`settings.CAS_FORCE_CHANGE_USERNAME_CASE`.
"""
us... | [
"def",
"clean_username",
"(",
"self",
",",
"username",
")",
":",
"username_case",
"=",
"settings",
".",
"CAS_FORCE_CHANGE_USERNAME_CASE",
"if",
"username_case",
"==",
"'lower'",
":",
"username",
"=",
"username",
".",
"lower",
"(",
")",
"elif",
"username_case",
"... | Performs any cleaning on the "username" prior to using it to get or
create the user object. Returns the cleaned username.
By default, changes the username case according to
`settings.CAS_FORCE_CHANGE_USERNAME_CASE`. | [
"Performs",
"any",
"cleaning",
"on",
"the",
"username",
"prior",
"to",
"using",
"it",
"to",
"get",
"or",
"create",
"the",
"user",
"object",
".",
"Returns",
"the",
"cleaned",
"username",
"."
] | python | train | 42.611111 |
Locu/chronology | kronos/kronos/storage/cassandra/client.py | https://github.com/Locu/chronology/blob/0edf3ee3286c76e242cbf92436ffa9c836b428e2/kronos/kronos/storage/cassandra/client.py#L107-L131 | def _retrieve(self, namespace, stream, start_id, end_time, order, limit,
configuration):
"""
Retrieve events for `stream` between `start_id` and `end_time`.
`stream` : The stream to return events for.
`start_id` : Return events with id > `start_id`.
`end_time` : Return events ending ... | [
"def",
"_retrieve",
"(",
"self",
",",
"namespace",
",",
"stream",
",",
"start_id",
",",
"end_time",
",",
"order",
",",
"limit",
",",
"configuration",
")",
":",
"stream",
"=",
"self",
".",
"get_stream",
"(",
"namespace",
",",
"stream",
",",
"configuration",... | Retrieve events for `stream` between `start_id` and `end_time`.
`stream` : The stream to return events for.
`start_id` : Return events with id > `start_id`.
`end_time` : Return events ending <= `end_time`.
`order` : Whether to return the results in ResultOrder.ASCENDING
or ResultOrder.DESC... | [
"Retrieve",
"events",
"for",
"stream",
"between",
"start_id",
"and",
"end_time",
".",
"stream",
":",
"The",
"stream",
"to",
"return",
"events",
"for",
".",
"start_id",
":",
"Return",
"events",
"with",
"id",
">",
"start_id",
".",
"end_time",
":",
"Return",
... | python | train | 45.64 |
xtuml/pyxtuml | bridgepoint/gen_xsd_schema.py | https://github.com/xtuml/pyxtuml/blob/7dd9343b9a0191d1db1887ab9288d0a026608d9a/bridgepoint/gen_xsd_schema.py#L126-L142 | def build_struct_type(s_sdt):
'''
Build an xsd complexType out of a S_SDT.
'''
s_dt = nav_one(s_sdt).S_DT[17]()
struct = ET.Element('xs:complexType', name=s_dt.name)
first_filter = lambda selected: not nav_one(selected).S_MBR[46, 'succeeds']()
s_mbr = nav_any(s_sdt).S_MBR[44](first... | [
"def",
"build_struct_type",
"(",
"s_sdt",
")",
":",
"s_dt",
"=",
"nav_one",
"(",
"s_sdt",
")",
".",
"S_DT",
"[",
"17",
"]",
"(",
")",
"struct",
"=",
"ET",
".",
"Element",
"(",
"'xs:complexType'",
",",
"name",
"=",
"s_dt",
".",
"name",
")",
"first_fil... | Build an xsd complexType out of a S_SDT. | [
"Build",
"an",
"xsd",
"complexType",
"out",
"of",
"a",
"S_SDT",
"."
] | python | test | 33.352941 |
gc3-uzh-ch/elasticluster | elasticluster/cluster.py | https://github.com/gc3-uzh-ch/elasticluster/blob/e6345633308c76de13b889417df572815aabe744/elasticluster/cluster.py#L294-L370 | def add_node(self, kind, image_id, image_user, flavor,
security_group, image_userdata='', name=None, **extra):
"""
Adds a new node to the cluster. This factory method provides an
easy way to add a new node to the cluster by specifying all relevant
parameters. The node do... | [
"def",
"add_node",
"(",
"self",
",",
"kind",
",",
"image_id",
",",
"image_user",
",",
"flavor",
",",
"security_group",
",",
"image_userdata",
"=",
"''",
",",
"name",
"=",
"None",
",",
"*",
"*",
"extra",
")",
":",
"if",
"not",
"self",
".",
"_NODE_KIND_R... | Adds a new node to the cluster. This factory method provides an
easy way to add a new node to the cluster by specifying all relevant
parameters. The node does not get started nor setup automatically,
this has to be done manually afterwards.
:param str kind: kind of node to start. this r... | [
"Adds",
"a",
"new",
"node",
"to",
"the",
"cluster",
".",
"This",
"factory",
"method",
"provides",
"an",
"easy",
"way",
"to",
"add",
"a",
"new",
"node",
"to",
"the",
"cluster",
"by",
"specifying",
"all",
"relevant",
"parameters",
".",
"The",
"node",
"does... | python | train | 37.272727 |
oasis-open/cti-taxii-client | taxii2client/__init__.py | https://github.com/oasis-open/cti-taxii-client/blob/b4c037fb61d8b8892af34423e2c67c81218d6f8e/taxii2client/__init__.py#L708-L711 | def refresh(self, accept=MEDIA_TYPE_TAXII_V20):
"""Update the API Root's information and list of Collections"""
self.refresh_information(accept)
self.refresh_collections(accept) | [
"def",
"refresh",
"(",
"self",
",",
"accept",
"=",
"MEDIA_TYPE_TAXII_V20",
")",
":",
"self",
".",
"refresh_information",
"(",
"accept",
")",
"self",
".",
"refresh_collections",
"(",
"accept",
")"
] | Update the API Root's information and list of Collections | [
"Update",
"the",
"API",
"Root",
"s",
"information",
"and",
"list",
"of",
"Collections"
] | python | valid | 49.5 |
raamana/mrivis | mrivis/base.py | https://github.com/raamana/mrivis/blob/199ad096b8a1d825f69109e7218a81b2f1cec756/mrivis/base.py#L1082-L1091 | def _summarize_in_roi(self, label_mask, num_clusters_per_roi=1, metric='minkowski'):
"""returns a single row summarizing (typically via mean) all rows in an ROI."""
this_label = self.carpet[label_mask.flatten(), :]
if num_clusters_per_roi == 1:
out_matrix = self._summary_func(this_l... | [
"def",
"_summarize_in_roi",
"(",
"self",
",",
"label_mask",
",",
"num_clusters_per_roi",
"=",
"1",
",",
"metric",
"=",
"'minkowski'",
")",
":",
"this_label",
"=",
"self",
".",
"carpet",
"[",
"label_mask",
".",
"flatten",
"(",
")",
",",
":",
"]",
"if",
"n... | returns a single row summarizing (typically via mean) all rows in an ROI. | [
"returns",
"a",
"single",
"row",
"summarizing",
"(",
"typically",
"via",
"mean",
")",
"all",
"rows",
"in",
"an",
"ROI",
"."
] | python | train | 45.2 |
bradmontgomery/django-redis-metrics | redis_metrics/management/commands/system_metric.py | https://github.com/bradmontgomery/django-redis-metrics/blob/2c92332920113d28c39234b949aa496b39a091d1/redis_metrics/management/commands/system_metric.py#L89-L93 | def _mem(self):
"""Record Memory usage."""
value = int(psutil.virtual_memory().percent)
set_metric("memory", value, category=self.category)
gauge("memory", value) | [
"def",
"_mem",
"(",
"self",
")",
":",
"value",
"=",
"int",
"(",
"psutil",
".",
"virtual_memory",
"(",
")",
".",
"percent",
")",
"set_metric",
"(",
"\"memory\"",
",",
"value",
",",
"category",
"=",
"self",
".",
"category",
")",
"gauge",
"(",
"\"memory\"... | Record Memory usage. | [
"Record",
"Memory",
"usage",
"."
] | python | train | 38 |
openstack/proliantutils | proliantutils/ilo/ribcl.py | https://github.com/openstack/proliantutils/blob/86ef3b47b4eca97c221577e3570b0240d6a25f22/proliantutils/ilo/ribcl.py#L858-L887 | def _parse_processor_embedded_health(self, data):
"""Parse the get_host_health_data() for essential properties
:param data: the output returned by get_host_health_data()
:returns: processor details like cpu arch and number of cpus.
"""
processor = self.get_value_as_list((data['... | [
"def",
"_parse_processor_embedded_health",
"(",
"self",
",",
"data",
")",
":",
"processor",
"=",
"self",
".",
"get_value_as_list",
"(",
"(",
"data",
"[",
"'GET_EMBEDDED_HEALTH_DATA'",
"]",
"[",
"'PROCESSORS'",
"]",
")",
",",
"'PROCESSOR'",
")",
"if",
"processor"... | Parse the get_host_health_data() for essential properties
:param data: the output returned by get_host_health_data()
:returns: processor details like cpu arch and number of cpus. | [
"Parse",
"the",
"get_host_health_data",
"()",
"for",
"essential",
"properties"
] | python | train | 45.366667 |
libtcod/python-tcod | tcod/libtcodpy.py | https://github.com/libtcod/python-tcod/blob/8ba10c5cfb813eaf3e834de971ba2d6acb7838e4/tcod/libtcodpy.py#L3377-L3383 | def noise_set_type(n: tcod.noise.Noise, typ: int) -> None:
"""Set a Noise objects default noise algorithm.
Args:
typ (int): Any NOISE_* constant.
"""
n.algorithm = typ | [
"def",
"noise_set_type",
"(",
"n",
":",
"tcod",
".",
"noise",
".",
"Noise",
",",
"typ",
":",
"int",
")",
"->",
"None",
":",
"n",
".",
"algorithm",
"=",
"typ"
] | Set a Noise objects default noise algorithm.
Args:
typ (int): Any NOISE_* constant. | [
"Set",
"a",
"Noise",
"objects",
"default",
"noise",
"algorithm",
"."
] | python | train | 26.571429 |
Scifabric/pbs | pbs.py | https://github.com/Scifabric/pbs/blob/3e5d5f3f0f5d20f740eaacc4d6e872a0c9fb8b38/pbs.py#L141-L150 | def update_project(config, task_presenter, results,
long_description, tutorial, watch): # pragma: no cover
"""Update project templates and information."""
if watch:
res = _update_project_watch(config, task_presenter, results,
long_description, tutor... | [
"def",
"update_project",
"(",
"config",
",",
"task_presenter",
",",
"results",
",",
"long_description",
",",
"tutorial",
",",
"watch",
")",
":",
"# pragma: no cover",
"if",
"watch",
":",
"res",
"=",
"_update_project_watch",
"(",
"config",
",",
"task_presenter",
... | Update project templates and information. | [
"Update",
"project",
"templates",
"and",
"information",
"."
] | python | train | 47 |
Cymmetria/honeycomb | honeycomb/integrationmanager/tasks.py | https://github.com/Cymmetria/honeycomb/blob/33ea91b5cf675000e4e85dd02efe580ea6e95c86/honeycomb/integrationmanager/tasks.py#L104-L167 | def send_alert_to_configured_integration(integration_alert):
"""Send IntegrationAlert to configured integration."""
try:
alert = integration_alert.alert
configured_integration = integration_alert.configured_integration
integration = configured_integration.integration
integration_... | [
"def",
"send_alert_to_configured_integration",
"(",
"integration_alert",
")",
":",
"try",
":",
"alert",
"=",
"integration_alert",
".",
"alert",
"configured_integration",
"=",
"integration_alert",
".",
"configured_integration",
"integration",
"=",
"configured_integration",
"... | Send IntegrationAlert to configured integration. | [
"Send",
"IntegrationAlert",
"to",
"configured",
"integration",
"."
] | python | train | 48 |
dossier/dossier.fc | python/dossier/fc/string_counter.py | https://github.com/dossier/dossier.fc/blob/3e969d0cb2592fc06afc1c849d2b22283450b5e2/python/dossier/fc/string_counter.py#L137-L145 | def _fix_key(key):
'''Normalize keys to Unicode strings.'''
if isinstance(key, unicode):
return key
if isinstance(key, str):
# On my system, the default encoding is `ascii`, so let's
# explicitly say UTF-8?
return unicode(key, 'utf-8')
rais... | [
"def",
"_fix_key",
"(",
"key",
")",
":",
"if",
"isinstance",
"(",
"key",
",",
"unicode",
")",
":",
"return",
"key",
"if",
"isinstance",
"(",
"key",
",",
"str",
")",
":",
"# On my system, the default encoding is `ascii`, so let's",
"# explicitly say UTF-8?",
"retur... | Normalize keys to Unicode strings. | [
"Normalize",
"keys",
"to",
"Unicode",
"strings",
"."
] | python | train | 36.444444 |
sixty-north/asq | asq/queryables.py | https://github.com/sixty-north/asq/blob/db0c4cbcf2118435136d4b63c62a12711441088e/asq/queryables.py#L240-L289 | def select_with_correspondence(
self,
selector,
result_selector=KeyedElement):
'''Apply a callable to each element in an input sequence, generating a new
sequence of 2-tuples where the first element is the input value and the
second is the transformed input va... | [
"def",
"select_with_correspondence",
"(",
"self",
",",
"selector",
",",
"result_selector",
"=",
"KeyedElement",
")",
":",
"if",
"self",
".",
"closed",
"(",
")",
":",
"raise",
"ValueError",
"(",
"\"Attempt to call select_with_correspondence() on a \"",
"\"closed Queryabl... | Apply a callable to each element in an input sequence, generating a new
sequence of 2-tuples where the first element is the input value and the
second is the transformed input value.
The generated sequence is lazily evaluated.
Note: This method uses deferred execution.
Args:
... | [
"Apply",
"a",
"callable",
"to",
"each",
"element",
"in",
"an",
"input",
"sequence",
"generating",
"a",
"new",
"sequence",
"of",
"2",
"-",
"tuples",
"where",
"the",
"first",
"element",
"is",
"the",
"input",
"value",
"and",
"the",
"second",
"is",
"the",
"t... | python | train | 45.02 |
chovanecm/sacredboard | sacredboard/app/data/pymongo/metricsdao.py | https://github.com/chovanecm/sacredboard/blob/47e1c99e3be3c1b099d3772bc077f5666020eb0b/sacredboard/app/data/pymongo/metricsdao.py#L57-L65 | def delete(self, run_id):
"""
Delete all metrics belonging to the given run.
:param run_id: ID of the Run that the metric belongs to.
"""
self.generic_dao.delete_record(
self.metrics_collection_name,
{"run_id": self._parse_run_id(run_id)}) | [
"def",
"delete",
"(",
"self",
",",
"run_id",
")",
":",
"self",
".",
"generic_dao",
".",
"delete_record",
"(",
"self",
".",
"metrics_collection_name",
",",
"{",
"\"run_id\"",
":",
"self",
".",
"_parse_run_id",
"(",
"run_id",
")",
"}",
")"
] | Delete all metrics belonging to the given run.
:param run_id: ID of the Run that the metric belongs to. | [
"Delete",
"all",
"metrics",
"belonging",
"to",
"the",
"given",
"run",
"."
] | python | train | 32.555556 |
knipknap/exscript | Exscript/account.py | https://github.com/knipknap/exscript/blob/72718eee3e87b345d5a5255be9824e867e42927b/Exscript/account.py#L105-L121 | def acquire(self, signal=True):
"""
Locks the account.
Method has no effect if the constructor argument `needs_lock`
wsa set to False.
:type signal: bool
:param signal: Whether to emit the acquired_event signal.
"""
if not self.needs_lock:
ret... | [
"def",
"acquire",
"(",
"self",
",",
"signal",
"=",
"True",
")",
":",
"if",
"not",
"self",
".",
"needs_lock",
":",
"return",
"with",
"self",
".",
"synclock",
":",
"while",
"not",
"self",
".",
"lock",
".",
"acquire",
"(",
"False",
")",
":",
"self",
"... | Locks the account.
Method has no effect if the constructor argument `needs_lock`
wsa set to False.
:type signal: bool
:param signal: Whether to emit the acquired_event signal. | [
"Locks",
"the",
"account",
".",
"Method",
"has",
"no",
"effect",
"if",
"the",
"constructor",
"argument",
"needs_lock",
"wsa",
"set",
"to",
"False",
"."
] | python | train | 30.823529 |
pydata/xarray | xarray/core/indexing.py | https://github.com/pydata/xarray/blob/6d93a95d05bdbfc33fff24064f67d29dd891ab58/xarray/core/indexing.py#L716-L740 | def _combine_indexers(old_key, shape, new_key):
""" Combine two indexers.
Parameters
----------
old_key: ExplicitIndexer
The first indexer for the original array
shape: tuple of ints
Shape of the original array to be indexed by old_key
new_key:
The second indexer for ind... | [
"def",
"_combine_indexers",
"(",
"old_key",
",",
"shape",
",",
"new_key",
")",
":",
"if",
"not",
"isinstance",
"(",
"old_key",
",",
"VectorizedIndexer",
")",
":",
"old_key",
"=",
"_outer_to_vectorized_indexer",
"(",
"old_key",
",",
"shape",
")",
"if",
"len",
... | Combine two indexers.
Parameters
----------
old_key: ExplicitIndexer
The first indexer for the original array
shape: tuple of ints
Shape of the original array to be indexed by old_key
new_key:
The second indexer for indexing original[old_key] | [
"Combine",
"two",
"indexers",
"."
] | python | train | 34.96 |
praekeltfoundation/seaworthy | seaworthy/definitions.py | https://github.com/praekeltfoundation/seaworthy/blob/6f10a19b45d4ea1dc3bd0553cc4d0438696c079c/seaworthy/definitions.py#L297-L306 | def stop(self, timeout=5):
"""
Stop the container. The container must have been created.
:param timeout:
Timeout in seconds to wait for the container to stop before sending
a ``SIGKILL``. Default: 5 (half the Docker default)
"""
self.inner().stop(timeout=... | [
"def",
"stop",
"(",
"self",
",",
"timeout",
"=",
"5",
")",
":",
"self",
".",
"inner",
"(",
")",
".",
"stop",
"(",
"timeout",
"=",
"timeout",
")",
"self",
".",
"inner",
"(",
")",
".",
"reload",
"(",
")"
] | Stop the container. The container must have been created.
:param timeout:
Timeout in seconds to wait for the container to stop before sending
a ``SIGKILL``. Default: 5 (half the Docker default) | [
"Stop",
"the",
"container",
".",
"The",
"container",
"must",
"have",
"been",
"created",
"."
] | python | train | 34.9 |
PmagPy/PmagPy | pmagpy/pmag.py | https://github.com/PmagPy/PmagPy/blob/c7984f8809bf40fe112e53dcc311a33293b62d0b/pmagpy/pmag.py#L7447-L7573 | def doigrf(lon, lat, alt, date, **kwargs):
"""
Calculates the interpolated (<2015) or extrapolated (>2015) main field and
secular variation coefficients and passes them to the Malin and Barraclough
routine (function pmag.magsyn) to calculate the field from the coefficients.
Parameters:
--------... | [
"def",
"doigrf",
"(",
"lon",
",",
"lat",
",",
"alt",
",",
"date",
",",
"*",
"*",
"kwargs",
")",
":",
"from",
".",
"import",
"coefficients",
"as",
"cf",
"gh",
",",
"sv",
"=",
"[",
"]",
",",
"[",
"]",
"colat",
"=",
"90.",
"-",
"lat",
"#! convert ... | Calculates the interpolated (<2015) or extrapolated (>2015) main field and
secular variation coefficients and passes them to the Malin and Barraclough
routine (function pmag.magsyn) to calculate the field from the coefficients.
Parameters:
-----------
lon : east longitude in degrees (0 to 360 or -... | [
"Calculates",
"the",
"interpolated",
"(",
"<2015",
")",
"or",
"extrapolated",
"(",
">",
"2015",
")",
"main",
"field",
"and",
"secular",
"variation",
"coefficients",
"and",
"passes",
"them",
"to",
"the",
"Malin",
"and",
"Barraclough",
"routine",
"(",
"function"... | python | train | 39.818898 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.