text stringlengths 89 104k | code_tokens list | avg_line_len float64 7.91 980 | score float64 0 630 |
|---|---|---|---|
def get(self, container):
"""
Returns a Container matching the specified container name. If no such
container exists, a NoSuchContainer exception is raised.
"""
name = utils.get_name(container)
uri = "/%s" % name
resp, resp_body = self.api.method_head(uri)
... | [
"def",
"get",
"(",
"self",
",",
"container",
")",
":",
"name",
"=",
"utils",
".",
"get_name",
"(",
"container",
")",
"uri",
"=",
"\"/%s\"",
"%",
"name",
"resp",
",",
"resp_body",
"=",
"self",
".",
"api",
".",
"method_head",
"(",
"uri",
")",
"hdrs",
... | 43.538462 | 16.153846 |
def get_authn_contexts(self):
"""
Gets the authentication contexts
:returns: The authentication classes for the SAML Response
:rtype: list
"""
authn_context_nodes = self.__query_assertion('/saml:AuthnStatement/saml:AuthnContext/saml:AuthnContextClassRef')
return ... | [
"def",
"get_authn_contexts",
"(",
"self",
")",
":",
"authn_context_nodes",
"=",
"self",
".",
"__query_assertion",
"(",
"'/saml:AuthnStatement/saml:AuthnContext/saml:AuthnContextClassRef'",
")",
"return",
"[",
"OneLogin_Saml2_XML",
".",
"element_text",
"(",
"node",
")",
"f... | 42.555556 | 24.777778 |
def from_stream(cls, stream, marker_code, offset):
"""
Return an |_SofMarker| instance for the SOFn marker at *offset* in
stream.
"""
# field off type notes
# ------------------ --- ----- ----------------------------
# segment length 0 ... | [
"def",
"from_stream",
"(",
"cls",
",",
"stream",
",",
"marker_code",
",",
"offset",
")",
":",
"# field off type notes",
"# ------------------ --- ----- ----------------------------",
"# segment length 0 short",
"# Data precision 2 byte",
"# Verti... | 46.9375 | 13.8125 |
def collate(self):
"""Unpacks DynamicMap into container of DynamicMaps
Collation allows unpacking DynamicMaps which return Layout,
NdLayout or GridSpace objects into a single such object
containing DynamicMaps. Assumes that the items in the layout
or grid that is returned do not... | [
"def",
"collate",
"(",
"self",
")",
":",
"# Initialize",
"if",
"self",
".",
"last",
"is",
"not",
"None",
":",
"initialized",
"=",
"self",
"else",
":",
"initialized",
"=",
"self",
".",
"clone",
"(",
")",
"initialized",
"[",
"initialized",
".",
"_initial_k... | 43.020202 | 17.868687 |
def bdplotter(task, **kwargs):
'''
bdplotter is based on the fact that phonon DOS/bands and
electron DOS/bands are the objects of the same kind.
1) DOS is formatted precomputed / smeared according to a normal distribution
2) bands are formatted precomputed / interpolated through natural cubic spline... | [
"def",
"bdplotter",
"(",
"task",
",",
"*",
"*",
"kwargs",
")",
":",
"if",
"task",
"==",
"'bands'",
":",
"# CRYSTAL, \"VASP\", EXCITING",
"results",
"=",
"[",
"]",
"if",
"'precomputed'",
"in",
"kwargs",
":",
"for",
"n",
"in",
"range",
"(",
"len",
"(",
"... | 44.95082 | 27.459016 |
def update_mutation_inputs(service):
"""
Args:
service : The service being updated by the mutation
Returns:
(list) : a list of all of the fields availible for the service. Pk
is a required field in order to filter the results
"""
# grab the default lis... | [
"def",
"update_mutation_inputs",
"(",
"service",
")",
":",
"# grab the default list of field summaries",
"inputs",
"=",
"_service_mutation_summaries",
"(",
"service",
")",
"# visit each field",
"for",
"field",
"in",
"inputs",
":",
"# if we're looking at the id field",
"if",
... | 30.041667 | 15.875 |
def run_migrations_offline():
"""Run migrations in 'offline' mode.
This configures the context with just a URL
and not an Engine, though an Engine is acceptable
here as well. By skipping the Engine creation
we don't even need a DBAPI to be available.
Calls to context.execute() here emit the g... | [
"def",
"run_migrations_offline",
"(",
")",
":",
"context",
".",
"configure",
"(",
"url",
"=",
"neutron_config",
".",
"database",
".",
"connection",
")",
"with",
"context",
".",
"begin_transaction",
"(",
")",
":",
"context",
".",
"run_migrations",
"(",
")"
] | 30.3125 | 17.875 |
def write(library, session, data):
"""Writes data to device or interface synchronously.
Corresponds to viWrite function of the VISA library.
:param library: the visa library wrapped by ctypes.
:param session: Unique logical identifier to a session.
:param data: data to be written.
:type data: ... | [
"def",
"write",
"(",
"library",
",",
"session",
",",
"data",
")",
":",
"return_count",
"=",
"ViUInt32",
"(",
")",
"# [ViSession, ViBuf, ViUInt32, ViPUInt32]",
"ret",
"=",
"library",
".",
"viWrite",
"(",
"session",
",",
"data",
",",
"len",
"(",
"data",
")",
... | 39.9375 | 17 |
def GetArtifactCollectorArgs(flow_args, knowledge_base):
"""Prepare bundle of artifacts and their dependencies for the client.
Args:
flow_args: An `ArtifactCollectorFlowArgs` instance.
knowledge_base: contains information about the client
Returns:
rdf value object containing a list of extended artif... | [
"def",
"GetArtifactCollectorArgs",
"(",
"flow_args",
",",
"knowledge_base",
")",
":",
"args",
"=",
"rdf_artifacts",
".",
"ClientArtifactCollectorArgs",
"(",
")",
"args",
".",
"knowledge_base",
"=",
"knowledge_base",
"args",
".",
"apply_parsers",
"=",
"flow_args",
".... | 38.837838 | 20.945946 |
def get_text(self):
"""
Get the data in text form (i.e. human readable)
"""
t = "==== " + str(self.last_data_timestamp) + " ====\n"
for k in self.data:
t += k + " " + str(self.data[k][self.value_key])
u = ""
if self.unit_key in self.data[k]:
... | [
"def",
"get_text",
"(",
"self",
")",
":",
"t",
"=",
"\"==== \"",
"+",
"str",
"(",
"self",
".",
"last_data_timestamp",
")",
"+",
"\" ====\\n\"",
"for",
"k",
"in",
"self",
".",
"data",
":",
"t",
"+=",
"k",
"+",
"\" \"",
"+",
"str",
"(",
"self",
".",
... | 41.26087 | 16.130435 |
def editfile(fpath, verbose=True): # nocover
"""
DEPRICATED: This has been ported to xdev, please use that version.
Opens a file or code corresponding to a live python object in your
preferred visual editor. This function is mainly useful in an interactive
IPython session.
The visual editor i... | [
"def",
"editfile",
"(",
"fpath",
",",
"verbose",
"=",
"True",
")",
":",
"# nocover",
"from",
"six",
"import",
"types",
"from",
"ubelt",
"import",
"util_cmd",
"import",
"warnings",
"warnings",
".",
"warn",
"(",
"'Please use xdev.editfile instead'",
",",
"Deprecat... | 34.186047 | 20.372093 |
def p_example_field(self, p):
"""example_field : ID EQ primitive NL
| ID EQ ex_list NL
| ID EQ ex_map NL"""
if p[3] is NullToken:
p[0] = AstExampleField(
self.path, p.lineno(1), p.lexpos(1), p[1], None)
else:
... | [
"def",
"p_example_field",
"(",
"self",
",",
"p",
")",
":",
"if",
"p",
"[",
"3",
"]",
"is",
"NullToken",
":",
"p",
"[",
"0",
"]",
"=",
"AstExampleField",
"(",
"self",
".",
"path",
",",
"p",
".",
"lineno",
"(",
"1",
")",
",",
"p",
".",
"lexpos",
... | 40.2 | 11 |
def cat(fname, fallback=_DEFAULT, binary=True):
"""Return file content.
fallback: the value returned in case the file does not exist or
cannot be read
binary: whether to open the file in binary or text mode.
"""
try:
with _open_binary(fname) if binary else _open_text(fname) as ... | [
"def",
"cat",
"(",
"fname",
",",
"fallback",
"=",
"_DEFAULT",
",",
"binary",
"=",
"True",
")",
":",
"try",
":",
"with",
"_open_binary",
"(",
"fname",
")",
"if",
"binary",
"else",
"_open_text",
"(",
"fname",
")",
"as",
"f_d",
":",
"return",
"f_d",
"."... | 35.384615 | 14.461538 |
def _check_for_single_nested(target, items_by_key, input_order):
"""Check for single nested inputs that match our target count and unnest.
Handles complex var inputs where some have an extra layer of nesting.
"""
out = utils.deepish_copy(items_by_key)
for (k, t) in input_order.items():
if t... | [
"def",
"_check_for_single_nested",
"(",
"target",
",",
"items_by_key",
",",
"input_order",
")",
":",
"out",
"=",
"utils",
".",
"deepish_copy",
"(",
"items_by_key",
")",
"for",
"(",
"k",
",",
"t",
")",
"in",
"input_order",
".",
"items",
"(",
")",
":",
"if... | 39.916667 | 13.916667 |
def set_position_i(self, ivalue):
""" Set the I gain of the position PID
Args:
ivalue (int): I value
"""
ivalue_msb = int(ivalue) >> 8
ivalue_lsb = int(ivalue) & 0xff
data = []
data.append(0x0B)
data.append(self.servoid)
data.append(R... | [
"def",
"set_position_i",
"(",
"self",
",",
"ivalue",
")",
":",
"ivalue_msb",
"=",
"int",
"(",
"ivalue",
")",
">>",
"8",
"ivalue_lsb",
"=",
"int",
"(",
"ivalue",
")",
"&",
"0xff",
"data",
"=",
"[",
"]",
"data",
".",
"append",
"(",
"0x0B",
")",
"data... | 26 | 12.722222 |
def arcsin_sqrt(biom_tbl):
"""
Applies the arcsine square root transform to the
given BIOM-format table
"""
arcsint = lambda data, id_, md: np.arcsin(np.sqrt(data))
tbl_relabd = relative_abd(biom_tbl)
tbl_asin = tbl_relabd.transform(arcsint, inplace=False)
return tbl_asin | [
"def",
"arcsin_sqrt",
"(",
"biom_tbl",
")",
":",
"arcsint",
"=",
"lambda",
"data",
",",
"id_",
",",
"md",
":",
"np",
".",
"arcsin",
"(",
"np",
".",
"sqrt",
"(",
"data",
")",
")",
"tbl_relabd",
"=",
"relative_abd",
"(",
"biom_tbl",
")",
"tbl_asin",
"=... | 26.909091 | 16.363636 |
def Unregister(self, name):
"""Unregisters a constructor.
Args:
name: A name of the constructor to unregister.
Raises:
ValueError: If constructor with specified name has never been registered.
"""
precondition.AssertType(name, Text)
try:
del self._constructors[name]
exce... | [
"def",
"Unregister",
"(",
"self",
",",
"name",
")",
":",
"precondition",
".",
"AssertType",
"(",
"name",
",",
"Text",
")",
"try",
":",
"del",
"self",
".",
"_constructors",
"[",
"name",
"]",
"except",
"KeyError",
":",
"raise",
"ValueError",
"(",
"\"Constr... | 26.4 | 22.666667 |
def absolute_charindex(self, string, start, end):
"""Finds the absolute character index of the specified regex match
start and end indices in the *buffer* refstring."""
search = string[start:end]
abs_start = self.refstring.index(search)
return abs_start, (end - start) + abs_start | [
"def",
"absolute_charindex",
"(",
"self",
",",
"string",
",",
"start",
",",
"end",
")",
":",
"search",
"=",
"string",
"[",
"start",
":",
"end",
"]",
"abs_start",
"=",
"self",
".",
"refstring",
".",
"index",
"(",
"search",
")",
"return",
"abs_start",
",... | 52.5 | 5.666667 |
def _get_part_url(api, url, upload, part):
"""
Used by the worker to fetch url for the part that is to be uploaded.
:param api: Api instance.
:param url: Part url.
:param upload: Upload identifier.
:param part: Part number.
:return: Storage generated URL for the part.
"""
try:
... | [
"def",
"_get_part_url",
"(",
"api",
",",
"url",
",",
"upload",
",",
"part",
")",
":",
"try",
":",
"response",
"=",
"api",
".",
"get",
"(",
"url",
".",
"format",
"(",
"upload_id",
"=",
"upload",
",",
"part_number",
"=",
"part",
")",
")",
"return",
"... | 33.625 | 15.5 |
def connect(com, peers, tree, pub_url, root_id):
"""this function will be called on the engines"""
com.connect(peers, tree, pub_url, root_id) | [
"def",
"connect",
"(",
"com",
",",
"peers",
",",
"tree",
",",
"pub_url",
",",
"root_id",
")",
":",
"com",
".",
"connect",
"(",
"peers",
",",
"tree",
",",
"pub_url",
",",
"root_id",
")"
] | 49 | 4.666667 |
def name_changed(self, changed_item):
"""
checks if name has been changed and ignores the name change if the changed_item is an existing script
Args:
changed_item:
"""
name = str(changed_item.text())
# if the item has been moved we ignore this because the ite... | [
"def",
"name_changed",
"(",
"self",
",",
"changed_item",
")",
":",
"name",
"=",
"str",
"(",
"changed_item",
".",
"text",
"(",
")",
")",
"# if the item has been moved we ignore this because the item only went from one tree to the other without changing names",
"if",
"name",
... | 47.428571 | 26.428571 |
def read_array(fname, sep=','):
r"""
Convert a CSV file without header into a numpy array of floats.
>>> from openquake.baselib.general import gettemp
>>> print(read_array(gettemp('.1 .2, .3 .4, .5 .6\n')))
[[[0.1 0.2]
[0.3 0.4]
[0.5 0.6]]]
"""
with open(fname) as f:
rec... | [
"def",
"read_array",
"(",
"fname",
",",
"sep",
"=",
"','",
")",
":",
"with",
"open",
"(",
"fname",
")",
"as",
"f",
":",
"records",
"=",
"[",
"]",
"for",
"line",
"in",
"f",
":",
"row",
"=",
"line",
".",
"split",
"(",
"sep",
")",
"record",
"=",
... | 29.941176 | 16.352941 |
def mock_decorator_with_params(*oargs, **okwargs): # pylint: disable=unused-argument
'''
Optionally mock a decorator that takes parameters
E.g.:
@blah(stuff=True)
def things():
pass
'''
def inner(fn, *iargs, **ikwargs): # pylint: disable=unused-argument
if hasattr(fn, '__... | [
"def",
"mock_decorator_with_params",
"(",
"*",
"oargs",
",",
"*",
"*",
"okwargs",
")",
":",
"# pylint: disable=unused-argument",
"def",
"inner",
"(",
"fn",
",",
"*",
"iargs",
",",
"*",
"*",
"ikwargs",
")",
":",
"# pylint: disable=unused-argument",
"if",
"hasattr... | 25.066667 | 26.933333 |
def simplex_find_cycle(self):
'''
API:
simplex_find_cycle(self)
Description:
Returns a cycle (list of nodes) if the graph has one, returns None
otherwise. Uses DFS. During DFS checks existence of arcs to lower
depth regions. Note that direction of ... | [
"def",
"simplex_find_cycle",
"(",
"self",
")",
":",
"# make a dfs, if you identify an arc to a lower depth node we have a",
"# cycle",
"nl",
"=",
"self",
".",
"get_node_list",
"(",
")",
"q",
"=",
"[",
"nl",
"[",
"0",
"]",
"]",
"visited",
"=",
"[",
"]",
"depth",
... | 38.014706 | 13.602941 |
def get(self, name_or_klass):
"""
Gets a mode by name (or class)
:param name_or_klass: The name or the class of the mode to get
:type name_or_klass: str or type
:rtype: pyqode.core.api.Mode
"""
if not isinstance(name_or_klass, str):
name_or_klass = na... | [
"def",
"get",
"(",
"self",
",",
"name_or_klass",
")",
":",
"if",
"not",
"isinstance",
"(",
"name_or_klass",
",",
"str",
")",
":",
"name_or_klass",
"=",
"name_or_klass",
".",
"__name__",
"return",
"self",
".",
"_modes",
"[",
"name_or_klass",
"]"
] | 33.818182 | 9.454545 |
def human_bytes(value):
"""
Convert a byte value into a human-readable format.
"""
value = float(value)
if value >= 1073741824:
gigabytes = value / 1073741824
size = '%.2f GB' % gigabytes
elif value >= 1048576:
megabytes = value / 1048576
size = '%.2f MB' % megaby... | [
"def",
"human_bytes",
"(",
"value",
")",
":",
"value",
"=",
"float",
"(",
"value",
")",
"if",
"value",
">=",
"1073741824",
":",
"gigabytes",
"=",
"value",
"/",
"1073741824",
"size",
"=",
"'%.2f GB'",
"%",
"gigabytes",
"elif",
"value",
">=",
"1048576",
":... | 27 | 10.764706 |
def GET_AUTH(self, courseid, taskid): # pylint: disable=arguments-differ
""" GET request """
course, task = self.get_course_and_check_rights(courseid, taskid)
return self.page(course, task) | [
"def",
"GET_AUTH",
"(",
"self",
",",
"courseid",
",",
"taskid",
")",
":",
"# pylint: disable=arguments-differ",
"course",
",",
"task",
"=",
"self",
".",
"get_course_and_check_rights",
"(",
"courseid",
",",
"taskid",
")",
"return",
"self",
".",
"page",
"(",
"co... | 52.75 | 17 |
def disconnect(self, slot, *extra_args):
"""
Disconnect @slot from the signal
"""
slot = Slot(slot, *extra_args)
if slot in self._functions:
self._functions.remove(slot)
elif slot in self._after_functions:
self._after_functions.remove(slot) | [
"def",
"disconnect",
"(",
"self",
",",
"slot",
",",
"*",
"extra_args",
")",
":",
"slot",
"=",
"Slot",
"(",
"slot",
",",
"*",
"extra_args",
")",
"if",
"slot",
"in",
"self",
".",
"_functions",
":",
"self",
".",
"_functions",
".",
"remove",
"(",
"slot",... | 33.777778 | 1.777778 |
def _plot_categories_as_colorblocks(groupby_ax, obs_tidy, colors=None, orientation='left', cmap_name='tab20'):
"""
Plots categories as colored blocks. If orientation is 'left', the categories are plotted vertically, otherwise
they are plotted horizontally.
Parameters
----------
groupby_ax : mat... | [
"def",
"_plot_categories_as_colorblocks",
"(",
"groupby_ax",
",",
"obs_tidy",
",",
"colors",
"=",
"None",
",",
"orientation",
"=",
"'left'",
",",
"cmap_name",
"=",
"'tab20'",
")",
":",
"groupby",
"=",
"obs_tidy",
".",
"index",
".",
"name",
"from",
"matplotlib"... | 37.929412 | 22.752941 |
def undobutton_action(self):
""" when undo is clicked, revert the thematic map to the previous state"""
if len(self.history) > 1:
old = self.history.pop(-1)
self.selection_array = old
self.mask.set_data(old)
self.fig.canvas.draw_idle() | [
"def",
"undobutton_action",
"(",
"self",
")",
":",
"if",
"len",
"(",
"self",
".",
"history",
")",
">",
"1",
":",
"old",
"=",
"self",
".",
"history",
".",
"pop",
"(",
"-",
"1",
")",
"self",
".",
"selection_array",
"=",
"old",
"self",
".",
"mask",
... | 41.857143 | 4.142857 |
def discovery_zookeeper(self):
"""
Installs the ZooKeeper discovery bundles and instantiates components
"""
# Install the bundle
self.context.install_bundle("pelix.remote.discovery.zookeeper").start()
with use_waiting_list(self.context) as ipopo:
# Instantiat... | [
"def",
"discovery_zookeeper",
"(",
"self",
")",
":",
"# Install the bundle",
"self",
".",
"context",
".",
"install_bundle",
"(",
"\"pelix.remote.discovery.zookeeper\"",
")",
".",
"start",
"(",
")",
"with",
"use_waiting_list",
"(",
"self",
".",
"context",
")",
"as"... | 37 | 17.222222 |
async def _handle_container_hard_timeout(self, container_id, hard_timeout):
"""
Kills a container (should be called with loop.call_later(hard_timeout, ...)) and displays a message on the log
:param container_id:
:param hard_timeout:
:return:
"""
if container_id in... | [
"async",
"def",
"_handle_container_hard_timeout",
"(",
"self",
",",
"container_id",
",",
"hard_timeout",
")",
":",
"if",
"container_id",
"in",
"self",
".",
"_watching",
":",
"self",
".",
"_logger",
".",
"info",
"(",
"\"Killing container %s as it used its %i wall time ... | 48.181818 | 22.181818 |
def move_old_profile(self, locale_minimum_needs_dir):
"""Move old minimum needs profile under user profile/minimum_needs.
This function is to get rid the old min needs profile came
from InaSAFE < 4.0.
:param locale_minimum_needs_dir: User local minimum needs profile path.
... | [
"def",
"move_old_profile",
"(",
"self",
",",
"locale_minimum_needs_dir",
")",
":",
"old_profile_path",
"=",
"os",
".",
"path",
".",
"join",
"(",
"QgsApplication",
".",
"qgisSettingsDirPath",
"(",
")",
",",
"'minimum_needs'",
")",
"if",
"os",
".",
"path",
".",
... | 46.272727 | 14.818182 |
def set_pkg_verif_code(self, doc, code):
"""Sets the package verification code, if not already set.
code - A string.
Raises CardinalityError if already defined.
Raises OrderError if no package previously defined.
"""
self.assert_package_exists()
if not self.packag... | [
"def",
"set_pkg_verif_code",
"(",
"self",
",",
"doc",
",",
"code",
")",
":",
"self",
".",
"assert_package_exists",
"(",
")",
"if",
"not",
"self",
".",
"package_verif_set",
":",
"self",
".",
"package_verif_set",
"=",
"True",
"doc",
".",
"package",
".",
"ver... | 40.25 | 8.666667 |
def create_hierarchy(hierarchy, level):
"""Create an OrderedDict
:param hierarchy: a dictionary
:param level: single key
:return: deeper dictionary
"""
if level not in hierarchy:
hierarchy[level] = OrderedDict()
return hierarchy[level] | [
"def",
"create_hierarchy",
"(",
"hierarchy",
",",
"level",
")",
":",
"if",
"level",
"not",
"in",
"hierarchy",
":",
"hierarchy",
"[",
"level",
"]",
"=",
"OrderedDict",
"(",
")",
"return",
"hierarchy",
"[",
"level",
"]"
] | 26.3 | 9.2 |
def ndarr2str(arr, encoding='ascii'):
""" This is used to ensure that the return value of arr.tostring()
is actually a string. This will prevent lots of if-checks in calling
code. As of numpy v1.6.1 (in Python 3.2.3), the tostring() function
still returns type 'bytes', not 'str' as it advertises. """
... | [
"def",
"ndarr2str",
"(",
"arr",
",",
"encoding",
"=",
"'ascii'",
")",
":",
"# be fast, don't check - just assume 'arr' is a numpy array - the tostring",
"# call will fail anyway if not",
"retval",
"=",
"arr",
".",
"tostring",
"(",
")",
"# would rather check \"if isinstance(retv... | 51 | 16.5 |
def waliki_box(context, slug, show_edit=True, *args, **kwargs):
"""
A templatetag to render a wiki page content as a box in any webpage,
and allow rapid edition if you have permission.
It's inspired in `django-boxes`_
.. _django-boxes: https://github.com/eldarion/django-boxes
"""
request ... | [
"def",
"waliki_box",
"(",
"context",
",",
"slug",
",",
"show_edit",
"=",
"True",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"request",
"=",
"context",
"[",
"\"request\"",
"]",
"try",
":",
"page",
"=",
"Page",
".",
"objects",
".",
"get",
"... | 29.21875 | 21.28125 |
def _execute_migrations(self, current_version, destination_version):
"""
passed a version:
this version don't exists in the database and is younger than the last version -> do migrations up until this version
this version don't exists in the database and is older than the last ve... | [
"def",
"_execute_migrations",
"(",
"self",
",",
"current_version",
",",
"destination_version",
")",
":",
"is_migration_up",
"=",
"True",
"# check if a version was passed to the program",
"if",
"self",
".",
"config",
".",
"get",
"(",
"\"schema_version\"",
")",
":",
"# ... | 60.064935 | 40.506494 |
def timeout(delay, call, *args, **kwargs):
"""Run a function call for `delay` seconds, and raise a RuntimeError
if the operation didn't complete."""
return_value = None
def target():
nonlocal return_value
return_value = call(*args, **kwargs)
t = Thread(target=target)
t.start()
... | [
"def",
"timeout",
"(",
"delay",
",",
"call",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"return_value",
"=",
"None",
"def",
"target",
"(",
")",
":",
"nonlocal",
"return_value",
"return_value",
"=",
"call",
"(",
"*",
"args",
",",
"*",
"*",
... | 27.375 | 19 |
def process_form(self, instance, field, form, empty_marker=None,
emptyReturnsMarker=False):
"""Return a UID so that ReferenceField understands.
"""
fieldName = field.getName()
if fieldName + "_uid" in form:
uid = form.get(fieldName + "_uid", '')
... | [
"def",
"process_form",
"(",
"self",
",",
"instance",
",",
"field",
",",
"form",
",",
"empty_marker",
"=",
"None",
",",
"emptyReturnsMarker",
"=",
"False",
")",
":",
"fieldName",
"=",
"field",
".",
"getName",
"(",
")",
"if",
"fieldName",
"+",
"\"_uid\"",
... | 40.055556 | 10.944444 |
def from_isodatetime(value, strict=False):
"""Convert an ISO formatted datetime into a Date object.
:param value: The ISO formatted datetime.
:param strict: If value is ``None``, then if strict is ``True`` it returns
the Date object of today, otherwise it returns ``None``.
(Default: ``False... | [
"def",
"from_isodatetime",
"(",
"value",
",",
"strict",
"=",
"False",
")",
":",
"if",
"value",
"or",
"strict",
":",
"return",
"arrow",
".",
"get",
"(",
"value",
")",
".",
"datetime"
] | 39 | 12.727273 |
def add_data_dict(self, dd): # pragma: no cover - never used...
"""
dd must be a dictionary where keys are the metric name,
each key contains a dictionary which at least must have 'value' key (optionally 'ts')
dd = {'experiment1.subsystem.block.metric1': {'value': 12.3, 'ts': 137949160... | [
"def",
"add_data_dict",
"(",
"self",
",",
"dd",
")",
":",
"# pragma: no cover - never used...",
"if",
"self",
".",
"__data_lock",
".",
"acquire",
"(",
")",
":",
"for",
"k",
",",
"v",
"in",
"list",
"(",
"dd",
".",
"items",
"(",
")",
")",
":",
"ts",
"=... | 41.941176 | 17.823529 |
def configure_root(self, config, incremental=False):
"""Configure a root logger from a dictionary."""
root = logging.getLogger()
self.common_logger_config(root, config, incremental) | [
"def",
"configure_root",
"(",
"self",
",",
"config",
",",
"incremental",
"=",
"False",
")",
":",
"root",
"=",
"logging",
".",
"getLogger",
"(",
")",
"self",
".",
"common_logger_config",
"(",
"root",
",",
"config",
",",
"incremental",
")"
] | 50.5 | 9.5 |
def get_display_label(choices, status):
"""Get a display label for resource status.
This method is used in places where a resource's status or
admin state labels need to assigned before they are sent to the
view template.
"""
for (value, label) in choices:
if value == (status or '').lo... | [
"def",
"get_display_label",
"(",
"choices",
",",
"status",
")",
":",
"for",
"(",
"value",
",",
"label",
")",
"in",
"choices",
":",
"if",
"value",
"==",
"(",
"status",
"or",
"''",
")",
".",
"lower",
"(",
")",
":",
"display_label",
"=",
"label",
"break... | 26.875 | 18 |
def potential_energy(self, potential=None):
r"""
The potential energy *per unit mass*:
.. math::
E_\Phi = \Phi(\boldsymbol{q})
Returns
-------
E : :class:`~astropy.units.Quantity`
The potential energy.
"""
if self.hamiltonian is ... | [
"def",
"potential_energy",
"(",
"self",
",",
"potential",
"=",
"None",
")",
":",
"if",
"self",
".",
"hamiltonian",
"is",
"None",
"and",
"potential",
"is",
"None",
":",
"raise",
"ValueError",
"(",
"\"To compute the potential energy, a potential\"",
"\" object must be... | 30.25 | 18.2 |
def set(self):
"""Set event flag to true and resolve future(s) returned by until_set()
Notes
-----
A call to set() may result in control being transferred to
done_callbacks attached to the future returned by until_set().
"""
self._flag = True
old_future ... | [
"def",
"set",
"(",
"self",
")",
":",
"self",
".",
"_flag",
"=",
"True",
"old_future",
"=",
"self",
".",
"_waiting_future",
"# Replace _waiting_future with a fresh one incase someone woken up by set_result()",
"# sets this AsyncEvent to False before waiting on it to be set again.",
... | 38.733333 | 22.066667 |
async def send_http_response(writer,
http_code: int,
headers: List[Tuple[str, str]],
content: bytes,
http_status: str= None
) -> None:
"""
generate http response paylo... | [
"async",
"def",
"send_http_response",
"(",
"writer",
",",
"http_code",
":",
"int",
",",
"headers",
":",
"List",
"[",
"Tuple",
"[",
"str",
",",
"str",
"]",
"]",
",",
"content",
":",
"bytes",
",",
"http_status",
":",
"str",
"=",
"None",
")",
"->",
"Non... | 32.227273 | 14.590909 |
def is_appendable_to(self, group):
"""Return True if features are appendable to a HDF5 group"""
return (group.attrs['format'] == self.dformat and
group[self.name].dtype == self.dtype and
# We use a method because dim differs in dense and sparse.
self._grou... | [
"def",
"is_appendable_to",
"(",
"self",
",",
"group",
")",
":",
"return",
"(",
"group",
".",
"attrs",
"[",
"'format'",
"]",
"==",
"self",
".",
"dformat",
"and",
"group",
"[",
"self",
".",
"name",
"]",
".",
"dtype",
"==",
"self",
".",
"dtype",
"and",
... | 56.666667 | 14 |
def _compute_first(self):
"""Computes the FIRST set for every symbol in the grammar.
Tenatively based on _compute_first in PLY.
"""
for terminal in self.terminals:
self._first[terminal].add(terminal)
self._first[END_OF_INPUT].add(END_OF_INPUT)
while True:
... | [
"def",
"_compute_first",
"(",
"self",
")",
":",
"for",
"terminal",
"in",
"self",
".",
"terminals",
":",
"self",
".",
"_first",
"[",
"terminal",
"]",
".",
"add",
"(",
"terminal",
")",
"self",
".",
"_first",
"[",
"END_OF_INPUT",
"]",
".",
"add",
"(",
"... | 34.095238 | 17.47619 |
def set_all_ylims(self, ylim, dy, yscale, fontsize=None):
"""Set limits and ticks for y axis for whole figure.
This will set y axis limits and tick marks for the entire figure.
It can be overridden in the SinglePlot class.
Args:
ylim (len-2 list of floats): The limits for t... | [
"def",
"set_all_ylims",
"(",
"self",
",",
"ylim",
",",
"dy",
",",
"yscale",
",",
"fontsize",
"=",
"None",
")",
":",
"self",
".",
"_set_all_lims",
"(",
"'y'",
",",
"ylim",
",",
"dy",
",",
"yscale",
",",
"fontsize",
")",
"return"
] | 40.1875 | 23.375 |
def mavlink_packet(self, msg):
'''handle an incoming mavlink packet'''
msgType = msg.get_type()
master = self.master
if msgType == 'HEARTBEAT':
# Update state and mode information
if type(master.motors_armed()) == type(True):
self.armed = ma... | [
"def",
"mavlink_packet",
"(",
"self",
",",
"msg",
")",
":",
"msgType",
"=",
"msg",
".",
"get_type",
"(",
")",
"master",
"=",
"self",
".",
"master",
"if",
"msgType",
"==",
"'HEARTBEAT'",
":",
"# Update state and mode information",
"if",
"type",
"(",
"master",... | 49.054054 | 14.891892 |
def complete_io(self, iocb, msg):
"""Called by a handler to return data to the client."""
if _debug: IOQController._debug("complete_io %r %r", iocb, msg)
# check to see if it is completing the active one
if iocb is not self.active_iocb:
raise RuntimeError("not the current io... | [
"def",
"complete_io",
"(",
"self",
",",
"iocb",
",",
"msg",
")",
":",
"if",
"_debug",
":",
"IOQController",
".",
"_debug",
"(",
"\"complete_io %r %r\"",
",",
"iocb",
",",
"msg",
")",
"# check to see if it is completing the active one",
"if",
"iocb",
"is",
"not",... | 34.483871 | 19.032258 |
def node_has_edge_with_label(self, node_name, edge_label):
"""Looks for an edge from node_name to some other node with the specified
label. Returns the node to which this edge points if it exists, or None
if it doesn't.
Parameters
----------
G :
The graph obj... | [
"def",
"node_has_edge_with_label",
"(",
"self",
",",
"node_name",
",",
"edge_label",
")",
":",
"G",
"=",
"self",
".",
"G",
"for",
"edge",
"in",
"G",
".",
"edges",
"(",
"node_name",
")",
":",
"to",
"=",
"edge",
"[",
"1",
"]",
"relation_name",
"=",
"G"... | 31.454545 | 18.090909 |
def _get_perez_coefficients(perezmodel):
'''
Find coefficients for the Perez model
Parameters
----------
perezmodel : string (optional, default='allsitescomposite1990')
a character string which selects the desired set of Perez
coefficients. If model is not provided as an input... | [
"def",
"_get_perez_coefficients",
"(",
"perezmodel",
")",
":",
"coeffdict",
"=",
"{",
"'allsitescomposite1990'",
":",
"[",
"[",
"-",
"0.0080",
",",
"0.5880",
",",
"-",
"0.0620",
",",
"-",
"0.0600",
",",
"0.0720",
",",
"-",
"0.0220",
"]",
",",
"[",
"0.130... | 54.822785 | 29.227848 |
def group_channels(self, group):
"""Returns a list of channel objects for the given group
:param group: Name of the group to get channels for.
:rtype: List of :class:`TdmsObject` objects.
"""
path = self._path(group)
return [
self.objects[p]
for... | [
"def",
"group_channels",
"(",
"self",
",",
"group",
")",
":",
"path",
"=",
"self",
".",
"_path",
"(",
"group",
")",
"return",
"[",
"self",
".",
"objects",
"[",
"p",
"]",
"for",
"p",
"in",
"self",
".",
"objects",
"if",
"p",
".",
"startswith",
"(",
... | 28.230769 | 16.307692 |
def updateAppInfo(self, appInfo):
"""
This operation allows you to update the OAuth-specific properties
associated with an application. Use the Get App Info operation to
obtain the existing OAuth properties that can be edited.
"""
params = {"f" : "json",
... | [
"def",
"updateAppInfo",
"(",
"self",
",",
"appInfo",
")",
":",
"params",
"=",
"{",
"\"f\"",
":",
"\"json\"",
",",
"\"appInfo\"",
":",
"appInfo",
"}",
"url",
"=",
"self",
".",
"_url",
"+",
"\"/oauth/updateAppInfo\"",
"return",
"self",
".",
"_post",
"(",
"... | 43.538462 | 11.692308 |
def slice(self, start_time, end_time, strict=False):
'''
Slice every annotation contained in the annotation array using
`Annotation.slice`
and return as a new AnnotationArray
See `Annotation.slice` for details about slicing. This function does
not modify the annotations ... | [
"def",
"slice",
"(",
"self",
",",
"start_time",
",",
"end_time",
",",
"strict",
"=",
"False",
")",
":",
"sliced_array",
"=",
"AnnotationArray",
"(",
")",
"for",
"ann",
"in",
"self",
":",
"sliced_array",
".",
"append",
"(",
"ann",
".",
"slice",
"(",
"st... | 39.264706 | 25.382353 |
def match_request_type(self, entry, request_type, regex=True):
"""
Helper function that returns entries with a request type
matching the given `request_type` argument.
:param entry: entry object to analyze
:param request_type: ``str`` of request type to match
:param rege... | [
"def",
"match_request_type",
"(",
"self",
",",
"entry",
",",
"request_type",
",",
"regex",
"=",
"True",
")",
":",
"if",
"regex",
":",
"return",
"re",
".",
"search",
"(",
"request_type",
",",
"entry",
"[",
"'request'",
"]",
"[",
"'method'",
"]",
",",
"f... | 43.357143 | 20.357143 |
def create(self, data):
""" Create object from the given data.
The given data may or may not have been validated prior to calling
this function. This function will try its best in creating the object.
If the resulting object cannot be produced, raises ``ValidationError``.
The s... | [
"def",
"create",
"(",
"self",
",",
"data",
")",
":",
"# todo: copy-paste code from representation.validate -> refactor",
"if",
"data",
"is",
"None",
":",
"return",
"None",
"prototype",
"=",
"{",
"}",
"errors",
"=",
"{",
"}",
"# create and populate the prototype",
"f... | 37.694915 | 21.542373 |
def fn_getma(fn, bnum=1, return_ds=False):
"""Get masked array from input filename
Parameters
----------
fn : str
Input filename string
bnum : int, optional
Band number
Returns
-------
np.ma.array
Masked array containing raster values
"""
#Add ch... | [
"def",
"fn_getma",
"(",
"fn",
",",
"bnum",
"=",
"1",
",",
"return_ds",
"=",
"False",
")",
":",
"#Add check for filename existence",
"ds",
"=",
"fn_getds",
"(",
"fn",
")",
"out",
"=",
"ds_getma",
"(",
"ds",
",",
"bnum",
"=",
"bnum",
")",
"if",
"return_d... | 20.904762 | 18.333333 |
def get_parameters_by_location(self, locations=None, excludes=None):
""" Get parameters list by location
:param locations: list of locations
:type locations: list or None
:param excludes: list of excludes locations
:type excludes: list or None
:return: list of Parameter
... | [
"def",
"get_parameters_by_location",
"(",
"self",
",",
"locations",
"=",
"None",
",",
"excludes",
"=",
"None",
")",
":",
"result",
"=",
"self",
".",
"parameters",
"if",
"locations",
":",
"result",
"=",
"filter",
"(",
"lambda",
"x",
":",
"x",
".",
"locati... | 37 | 15.25 |
def get_field_to_observations_map(generator, query_for_tag=''):
"""Return a field to `Observations` dict for the event generator.
Args:
generator: A generator over event protos.
query_for_tag: A string that if specified, only create observations for
events with this tag name.
Returns:
A dict m... | [
"def",
"get_field_to_observations_map",
"(",
"generator",
",",
"query_for_tag",
"=",
"''",
")",
":",
"def",
"increment",
"(",
"stat",
",",
"event",
",",
"tag",
"=",
"''",
")",
":",
"assert",
"stat",
"in",
"TRACKED_FIELDS",
"field_to_obs",
"[",
"stat",
"]",
... | 37.536585 | 17.682927 |
def dot(self, y, t=None, A=None, U=None, V=None, kernel=None,
check_sorted=True):
"""
Dot the covariance matrix into a vector or matrix
Compute ``K.y`` where ``K`` is the covariance matrix of the GP without
the white noise or ``yerr`` values on the diagonal.
Args:
... | [
"def",
"dot",
"(",
"self",
",",
"y",
",",
"t",
"=",
"None",
",",
"A",
"=",
"None",
",",
"U",
"=",
"None",
",",
"V",
"=",
"None",
",",
"kernel",
"=",
"None",
",",
"check_sorted",
"=",
"True",
")",
":",
"if",
"kernel",
"is",
"None",
":",
"kerne... | 36.203704 | 21.722222 |
def main():
"""Main function"""
parser = argparse.ArgumentParser()
parser.add_argument('-u', '--username',
required=True, help='Fido username')
parser.add_argument('-n', '--number', default=None,
required=False, help='Fido phone number')
parser.add_arg... | [
"def",
"main",
"(",
")",
":",
"parser",
"=",
"argparse",
".",
"ArgumentParser",
"(",
")",
"parser",
".",
"add_argument",
"(",
"'-u'",
",",
"'--username'",
",",
"required",
"=",
"True",
",",
"help",
"=",
"'Fido username'",
")",
"parser",
".",
"add_argument"... | 40.5 | 15.972222 |
def popFile(title="Lackey Open File"):
""" Creates a file selection dialog with the specified message and options.
Returns the selected file. """
root = tk.Tk()
root.withdraw()
return str(tkFileDialog.askopenfilename(title=title)) | [
"def",
"popFile",
"(",
"title",
"=",
"\"Lackey Open File\"",
")",
":",
"root",
"=",
"tk",
".",
"Tk",
"(",
")",
"root",
".",
"withdraw",
"(",
")",
"return",
"str",
"(",
"tkFileDialog",
".",
"askopenfilename",
"(",
"title",
"=",
"title",
")",
")"
] | 35 | 14.571429 |
def build_and_trace(algo, init, limit=100, **kwargs):
'''Run an optimizer on the rosenbrock function. Return xs, ys, and losses.
In downhill, optimization algorithms can be iterated over to progressively
minimize the loss. At each iteration, the optimizer yields a dictionary of
monitor values that were... | [
"def",
"build_and_trace",
"(",
"algo",
",",
"init",
",",
"limit",
"=",
"100",
",",
"*",
"*",
"kwargs",
")",
":",
"kw",
"=",
"dict",
"(",
"min_improvement",
"=",
"0",
",",
"patience",
"=",
"0",
",",
"max_gradient_norm",
"=",
"100",
")",
"kw",
".",
"... | 43.35 | 21.55 |
def _to_json(self, strip, to_serialize=None):
"""Utility function that creates JSON repr. of a credentials object.
Over-ride is needed since PKCS#12 keys will not in general be JSON
serializable.
Args:
strip: array, An array of names of members to exclude from the
... | [
"def",
"_to_json",
"(",
"self",
",",
"strip",
",",
"to_serialize",
"=",
"None",
")",
":",
"if",
"to_serialize",
"is",
"None",
":",
"to_serialize",
"=",
"copy",
".",
"copy",
"(",
"self",
".",
"__dict__",
")",
"pkcs12_val",
"=",
"to_serialize",
".",
"get",... | 41.583333 | 20.958333 |
def gifs_gif_id_get(self, api_key, gif_id, **kwargs):
"""
Get GIF by ID Endpoint
Returns a GIF given that GIF's unique ID
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please define a `callback` function
to be invoked when ... | [
"def",
"gifs_gif_id_get",
"(",
"self",
",",
"api_key",
",",
"gif_id",
",",
"*",
"*",
"kwargs",
")",
":",
"kwargs",
"[",
"'_return_http_data_only'",
"]",
"=",
"True",
"if",
"kwargs",
".",
"get",
"(",
"'callback'",
")",
":",
"return",
"self",
".",
"gifs_gi... | 44.846154 | 18 |
def parameters_changed(self):
"""Update the gradients of parameters for warping function
This method is called when having new values of parameters for warping function, kernels
and other parameters in a normal GP
"""
# using the warped X to update
self.X = self.transfor... | [
"def",
"parameters_changed",
"(",
"self",
")",
":",
"# using the warped X to update",
"self",
".",
"X",
"=",
"self",
".",
"transform_data",
"(",
"self",
".",
"X_untransformed",
")",
"super",
"(",
"InputWarpedGP",
",",
"self",
")",
".",
"parameters_changed",
"(",... | 53 | 22.083333 |
def lv_to_pypsa(network):
"""
Convert LV grid topology to PyPSA representation
Includes grid topology of all LV grids of :attr:`~.grid.grid.Grid.lv_grids`
Parameters
----------
network : Network
eDisGo grid container
Returns
-------
dict of :pandas:`pandas.DataFrame<datafr... | [
"def",
"lv_to_pypsa",
"(",
"network",
")",
":",
"generators",
"=",
"[",
"]",
"loads",
"=",
"[",
"]",
"branch_tees",
"=",
"[",
"]",
"lines",
"=",
"[",
"]",
"lv_stations",
"=",
"[",
"]",
"storages",
"=",
"[",
"]",
"for",
"lv_grid",
"in",
"network",
"... | 30.914474 | 18.677632 |
def ModelBasedReflexAgentProgram(rules, update_state):
"This agent takes action based on the percept and state. [Fig. 2.12]"
def program(percept):
program.state = update_state(program.state, program.action, percept)
rule = rule_match(program.state, rules)
action = rule.action
ret... | [
"def",
"ModelBasedReflexAgentProgram",
"(",
"rules",
",",
"update_state",
")",
":",
"def",
"program",
"(",
"percept",
")",
":",
"program",
".",
"state",
"=",
"update_state",
"(",
"program",
".",
"state",
",",
"program",
".",
"action",
",",
"percept",
")",
... | 42.555556 | 17.666667 |
def sign_message(message, wif, hashfn=hashlib.sha256):
""" Sign a digest with a wif key
:param str wif: Private key in
"""
if not isinstance(message, bytes):
message = bytes(message, "utf-8")
digest = hashfn(message).digest()
priv_key = PrivateKey(wif)
p = bytes(priv_key)
... | [
"def",
"sign_message",
"(",
"message",
",",
"wif",
",",
"hashfn",
"=",
"hashlib",
".",
"sha256",
")",
":",
"if",
"not",
"isinstance",
"(",
"message",
",",
"bytes",
")",
":",
"message",
"=",
"bytes",
"(",
"message",
",",
"\"utf-8\"",
")",
"digest",
"=",... | 34.726496 | 17.811966 |
def _add_interface(self, interface_id, **kw):
"""
Create a tunnel interface. Kw argument list is as follows
"""
base_interface = ElementCache()
base_interface.update(
interface_id=str(interface_id),
interfaces=[])
if 'zone_ref' in kw:
... | [
"def",
"_add_interface",
"(",
"self",
",",
"interface_id",
",",
"*",
"*",
"kw",
")",
":",
"base_interface",
"=",
"ElementCache",
"(",
")",
"base_interface",
".",
"update",
"(",
"interface_id",
"=",
"str",
"(",
"interface_id",
")",
",",
"interfaces",
"=",
"... | 40.944444 | 16.5 |
def remove_query_parameters(request, query_parameters_to_remove):
"""
Wrap replace_query_parameters() for API backward compatibility.
"""
replacements = [(k, None) for k in query_parameters_to_remove]
return replace_query_parameters(request, replacements) | [
"def",
"remove_query_parameters",
"(",
"request",
",",
"query_parameters_to_remove",
")",
":",
"replacements",
"=",
"[",
"(",
"k",
",",
"None",
")",
"for",
"k",
"in",
"query_parameters_to_remove",
"]",
"return",
"replace_query_parameters",
"(",
"request",
",",
"re... | 45 | 16 |
def confidential_interval(x, alpha=0.98):
"""
Return a numpy array of column confidential interval
Parameters
----------
x : ndarray
A numpy array instance
alpha : float
Alpha value of confidential interval
Returns
-------
ndarray
A 1 x n numpy array which i... | [
"def",
"confidential_interval",
"(",
"x",
",",
"alpha",
"=",
"0.98",
")",
":",
"from",
"scipy",
".",
"stats",
"import",
"t",
"if",
"x",
".",
"ndim",
"==",
"1",
":",
"df",
"=",
"len",
"(",
"x",
")",
"-",
"1",
"# calculate positive critical value of studen... | 30.235294 | 16.647059 |
def _generate_arg_types(coordlist_length, shape_name):
"""Find coordinate types based on shape name and coordlist length
This function returns a list of coordinate types based on which
coordinates can be repeated for a given type of shap
Parameters
----------
coordlist_length : int
The... | [
"def",
"_generate_arg_types",
"(",
"coordlist_length",
",",
"shape_name",
")",
":",
"from",
".",
"ds9_region_parser",
"import",
"ds9_shape_defs",
"from",
".",
"ds9_attr_parser",
"import",
"ds9_shape_in_comment_defs",
"if",
"shape_name",
"in",
"ds9_shape_defs",
":",
"sha... | 31.023256 | 20.744186 |
def load_file(self, currency_file):
"""To be subclassed if alternate methods of loading data.
"""
if currency_file.startswith(('http://', 'https://')):
content = urlopen(currency_file).read()
else:
with open(currency_file, 'rb') as f:
content = f.r... | [
"def",
"load_file",
"(",
"self",
",",
"currency_file",
")",
":",
"if",
"currency_file",
".",
"startswith",
"(",
"(",
"'http://'",
",",
"'https://'",
")",
")",
":",
"content",
"=",
"urlopen",
"(",
"currency_file",
")",
".",
"read",
"(",
")",
"else",
":",
... | 38 | 14.461538 |
def template_exists_db(self, template):
"""
Receives a template and checks if it exists in the database
using the template name and language
"""
name = utils.camel_to_snake(template[0]).upper()
language = utils.camel_to_snake(template[3])
try:
models.E... | [
"def",
"template_exists_db",
"(",
"self",
",",
"template",
")",
":",
"name",
"=",
"utils",
".",
"camel_to_snake",
"(",
"template",
"[",
"0",
"]",
")",
".",
"upper",
"(",
")",
"language",
"=",
"utils",
".",
"camel_to_snake",
"(",
"template",
"[",
"3",
"... | 38.166667 | 14 |
def CountClientVersionStringsByLabel(self, day_buckets):
"""Computes client-activity stats for all GRR versions in the DB."""
def ExtractVersion(client_info):
return client_info.last_snapshot.GetGRRVersionString()
return self._CountClientStatisticByLabel(day_buckets, ExtractVersion) | [
"def",
"CountClientVersionStringsByLabel",
"(",
"self",
",",
"day_buckets",
")",
":",
"def",
"ExtractVersion",
"(",
"client_info",
")",
":",
"return",
"client_info",
".",
"last_snapshot",
".",
"GetGRRVersionString",
"(",
")",
"return",
"self",
".",
"_CountClientStat... | 42.428571 | 21.857143 |
def import_object_ns(name_space, import_str, *args, **kwargs):
"""Tries to import object from default namespace.
Imports a class and return an instance of it, first by trying
to find the class in a default namespace, then failing back to
a full path if not found in the default namespace.
"""
im... | [
"def",
"import_object_ns",
"(",
"name_space",
",",
"import_str",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"import_value",
"=",
"\"%s.%s\"",
"%",
"(",
"name_space",
",",
"import_str",
")",
"try",
":",
"return",
"import_class",
"(",
"import_value",... | 42.083333 | 18.583333 |
def extract_classifier_and_extension(pkg_name, filename):
"""
Returns a PEP425-compliant classifier (or 'py2.py3-none-any' if it cannot be extracted),
and the file extension
TODO: return a classifier 3-members namedtuple instead of a single string
"""
basename, _, extension = filename.rpartition... | [
"def",
"extract_classifier_and_extension",
"(",
"pkg_name",
",",
"filename",
")",
":",
"basename",
",",
"_",
",",
"extension",
"=",
"filename",
".",
"rpartition",
"(",
"'.'",
")",
"if",
"extension",
"==",
"'gz'",
"and",
"filename",
".",
"endswith",
"(",
"'.t... | 45.315789 | 13.736842 |
def plot_covariance_ellipse(
mean, cov=None, variance=1.0, std=None,
ellipse=None, title=None, axis_equal=True, show_semiaxis=False,
facecolor=None, edgecolor=None,
fc='none', ec='#004080',
alpha=1.0, xlim=None, ylim=None,
ls='solid'):
"""
Deprecated function to p... | [
"def",
"plot_covariance_ellipse",
"(",
"mean",
",",
"cov",
"=",
"None",
",",
"variance",
"=",
"1.0",
",",
"std",
"=",
"None",
",",
"ellipse",
"=",
"None",
",",
"title",
"=",
"None",
",",
"axis_equal",
"=",
"True",
",",
"show_semiaxis",
"=",
"False",
",... | 35.73913 | 21.73913 |
def build_kernel_to_data(self, Y, knn=None, bandwidth=None, bandwidth_scale=None):
"""Build transition matrix from new data to the graph
Creates a transition matrix such that `Y` can be approximated by
a linear combination of landmarks. Any
transformation of the landmarks can be trivial... | [
"def",
"build_kernel_to_data",
"(",
"self",
",",
"Y",
",",
"knn",
"=",
"None",
",",
"bandwidth",
"=",
"None",
",",
"bandwidth_scale",
"=",
"None",
")",
":",
"if",
"knn",
"is",
"None",
":",
"knn",
"=",
"self",
".",
"knn",
"if",
"bandwidth",
"is",
"Non... | 35.418182 | 18.872727 |
def solveFashion(solution_next,DiscFac,conformUtilityFunc,punk_utility,jock_utility,switchcost_J2P,switchcost_P2J,pGrid,pEvolution,pref_shock_mag):
'''
Solves a single period of the fashion victim model.
Parameters
----------
solution_next: FashionSolution
A representation of the solution t... | [
"def",
"solveFashion",
"(",
"solution_next",
",",
"DiscFac",
",",
"conformUtilityFunc",
",",
"punk_utility",
",",
"jock_utility",
",",
"switchcost_J2P",
",",
"switchcost_P2J",
",",
"pGrid",
",",
"pEvolution",
",",
"pref_shock_mag",
")",
":",
"# Unpack next period's so... | 44.25 | 21.869048 |
def ilwd_as_int(true_or_false=None):
"""Similar to lstring_as_obj, sets whether or not ilwd:chars should be
treated as strings or as ints. Default is True.
"""
if true_or_false is not None:
_default_types_status['ilwd_as_int'] = true_or_false
numpy.typeDict[u'ilwd:char'] = int \
... | [
"def",
"ilwd_as_int",
"(",
"true_or_false",
"=",
"None",
")",
":",
"if",
"true_or_false",
"is",
"not",
"None",
":",
"_default_types_status",
"[",
"'ilwd_as_int'",
"]",
"=",
"true_or_false",
"numpy",
".",
"typeDict",
"[",
"u'ilwd:char'",
"]",
"=",
"int",
"if",
... | 44.4 | 6.7 |
def cmd_signing_remove(self, args):
'''remove signing from server'''
if not self.master.mavlink20():
print("You must be using MAVLink2 for signing")
return
self.master.mav.setup_signing_send(self.target_system, self.target_component, [0]*32, 0)
self.master.disable... | [
"def",
"cmd_signing_remove",
"(",
"self",
",",
"args",
")",
":",
"if",
"not",
"self",
".",
"master",
".",
"mavlink20",
"(",
")",
":",
"print",
"(",
"\"You must be using MAVLink2 for signing\"",
")",
"return",
"self",
".",
"master",
".",
"mav",
".",
"setup_si... | 44.5 | 14.25 |
def _split_generators(self, dl_manager):
"""Returns SplitGenerators."""
cifar_path = dl_manager.download_and_extract(self._cifar_info.url)
cifar_info = self._cifar_info
cifar_path = os.path.join(cifar_path, cifar_info.prefix)
# Load the label names
for label_key, label_file in zip(cifar_info.l... | [
"def",
"_split_generators",
"(",
"self",
",",
"dl_manager",
")",
":",
"cifar_path",
"=",
"dl_manager",
".",
"download_and_extract",
"(",
"self",
".",
"_cifar_info",
".",
"url",
")",
"cifar_info",
"=",
"self",
".",
"_cifar_info",
"cifar_path",
"=",
"os",
".",
... | 36.6 | 19.4 |
def get_file(self, path):
"""
Returns VPKFile instance for the given path
"""
metadata = self.get_file_meta(path)
return self.get_vpkfile_instance(path, metadata) | [
"def",
"get_file",
"(",
"self",
",",
"path",
")",
":",
"metadata",
"=",
"self",
".",
"get_file_meta",
"(",
"path",
")",
"return",
"self",
".",
"get_vpkfile_instance",
"(",
"path",
",",
"metadata",
")"
] | 32.833333 | 7.5 |
def starter(cls):
"""Return last gallery link."""
url = 'http://www.hagardunor.net/comics.php'
data = cls.getPage(url)
pattern = compile(tagre("a", "href", cls.prevUrl))
for starturl in cls.fetchUrls(url, data, pattern):
pass
return starturl | [
"def",
"starter",
"(",
"cls",
")",
":",
"url",
"=",
"'http://www.hagardunor.net/comics.php'",
"data",
"=",
"cls",
".",
"getPage",
"(",
"url",
")",
"pattern",
"=",
"compile",
"(",
"tagre",
"(",
"\"a\"",
",",
"\"href\"",
",",
"cls",
".",
"prevUrl",
")",
")... | 36.75 | 15.125 |
def get_all_requisite_objectives(self, objective_id=None):
"""Gets a list of Objectives that are the requisites for the given
Objective including the requistes of the requisites, and so on.
In plenary mode, the returned list contains all of the immediate
requisites, or an error results ... | [
"def",
"get_all_requisite_objectives",
"(",
"self",
",",
"objective_id",
"=",
"None",
")",
":",
"# This should be re-implemented if and when handcar supports",
"# getting all requisites directly",
"requisites",
"=",
"list",
"(",
")",
"requisite_ids",
"=",
"list",
"(",
")",
... | 49.230769 | 21.576923 |
def convert_to_json_with_mac(self, md5digest, hmacdigest):
# type: (EncryptionMetadata, str, str) -> dict
"""Constructs metadata for encryption
:param EncryptionMetadata self: this
:param str md5digest: md5 digest
:param str hmacdigest: hmac-sha256 digest (data)
:rtype: d... | [
"def",
"convert_to_json_with_mac",
"(",
"self",
",",
"md5digest",
",",
"hmacdigest",
")",
":",
"# type: (EncryptionMetadata, str, str) -> dict",
"# encrypt keys",
"enc_content_key",
"=",
"blobxfer",
".",
"operations",
".",
"crypto",
".",
"rsa_encrypt_key_base64_encoded",
"(... | 46.380282 | 18.014085 |
def add_all(self, items, overflow_policy=OVERFLOW_POLICY_OVERWRITE):
"""
Adds all of the item in the specified collection to the tail of the Ringbuffer. An add_all is likely to
outperform multiple calls to add(object) due to better io utilization and a reduced number of executed
operatio... | [
"def",
"add_all",
"(",
"self",
",",
"items",
",",
"overflow_policy",
"=",
"OVERFLOW_POLICY_OVERWRITE",
")",
":",
"check_not_empty",
"(",
"items",
",",
"\"items can't be empty\"",
")",
"if",
"len",
"(",
"items",
")",
">",
"MAX_BATCH_SIZE",
":",
"raise",
"Assertio... | 61.809524 | 37.428571 |
def distill_resnet_32_to_15_cifar20x5():
"""Set of hyperparameters."""
hparams = distill_base()
hparams.teacher_model = "resnet"
hparams.teacher_hparams = "resnet_cifar_32"
hparams.student_model = "resnet"
hparams.student_hparams = "resnet_cifar_15"
hparams.optimizer_momentum_nesterov = True
# (base_lr... | [
"def",
"distill_resnet_32_to_15_cifar20x5",
"(",
")",
":",
"hparams",
"=",
"distill_base",
"(",
")",
"hparams",
".",
"teacher_model",
"=",
"\"resnet\"",
"hparams",
".",
"teacher_hparams",
"=",
"\"resnet_cifar_32\"",
"hparams",
".",
"student_model",
"=",
"\"resnet\"",
... | 35.363636 | 17.590909 |
def as_unordered(self, inplace=False):
"""
Set the Categorical to be unordered.
Parameters
----------
inplace : bool, default False
Whether or not to set the ordered attribute in-place or return
a copy of this categorical with ordered set to False.
... | [
"def",
"as_unordered",
"(",
"self",
",",
"inplace",
"=",
"False",
")",
":",
"inplace",
"=",
"validate_bool_kwarg",
"(",
"inplace",
",",
"'inplace'",
")",
"return",
"self",
".",
"set_ordered",
"(",
"False",
",",
"inplace",
"=",
"inplace",
")"
] | 35.5 | 15.166667 |
def insert_secnos_factory(f):
"""Returns insert_secnos(key, value, fmt, meta) action that inserts
section numbers into the attributes of elements of type f.
"""
# Get the name and standard length
name = f.__closure__[0].cell_contents
n = f.__closure__[1].cell_contents
def insert_secnos(key... | [
"def",
"insert_secnos_factory",
"(",
"f",
")",
":",
"# Get the name and standard length",
"name",
"=",
"f",
".",
"__closure__",
"[",
"0",
"]",
".",
"cell_contents",
"n",
"=",
"f",
".",
"__closure__",
"[",
"1",
"]",
".",
"cell_contents",
"def",
"insert_secnos",... | 37.431818 | 16.954545 |
def complete_acquaintance_strategy(qubit_order: Sequence[ops.Qid],
acquaintance_size: int=0,
) -> circuits.Circuit:
"""
Returns an acquaintance strategy capable of executing a gate corresponding
to any set of at most acquaintance_size qub... | [
"def",
"complete_acquaintance_strategy",
"(",
"qubit_order",
":",
"Sequence",
"[",
"ops",
".",
"Qid",
"]",
",",
"acquaintance_size",
":",
"int",
"=",
"0",
",",
")",
"->",
"circuits",
".",
"Circuit",
":",
"if",
"acquaintance_size",
"<",
"0",
":",
"raise",
"... | 41 | 20.028571 |
def value(self):
"""
Normalise the Attribute value and return
.. note: `datetime` objects are normalised to ISO datestring, `bool` objects are normalised to Yes or No
:rtype: str
:return: The normalised value
"""
if isinstance(self.raw_value, (datetime.datetime, ... | [
"def",
"value",
"(",
"self",
")",
":",
"if",
"isinstance",
"(",
"self",
".",
"raw_value",
",",
"(",
"datetime",
".",
"datetime",
",",
"datetime",
".",
"date",
")",
")",
":",
"return",
"self",
".",
"raw_value",
".",
"isoformat",
"(",
")",
"elif",
"isi... | 38.692308 | 18.384615 |
def launch_workflow(seqs_fp, working_dir, mean_error, error_dist,
indel_prob, indel_max, trim_length, left_trim_length,
min_size, ref_fp, ref_db_fp, threads_per_sample=1,
sim_thresh=None, coverage_thresh=None):
"""Launch full deblur workflow for a single p... | [
"def",
"launch_workflow",
"(",
"seqs_fp",
",",
"working_dir",
",",
"mean_error",
",",
"error_dist",
",",
"indel_prob",
",",
"indel_max",
",",
"trim_length",
",",
"left_trim_length",
",",
"min_size",
",",
"ref_fp",
",",
"ref_db_fp",
",",
"threads_per_sample",
"=",
... | 45.588235 | 18.848739 |
def plot(self, show=True, plot_raw=True, plot_gp=True,
plot_bad=True, plot_out=True, plot_cbv=True,
simple=False):
'''
Plots the final de-trended light curve.
:param bool show: Show the plot or return the `(fig, ax)` instance? \
Default :py:obj:`True`
... | [
"def",
"plot",
"(",
"self",
",",
"show",
"=",
"True",
",",
"plot_raw",
"=",
"True",
",",
"plot_gp",
"=",
"True",
",",
"plot_bad",
"=",
"True",
",",
"plot_out",
"=",
"True",
",",
"plot_cbv",
"=",
"True",
",",
"simple",
"=",
"False",
")",
":",
"log",... | 39.515625 | 18.088542 |
def call_adam(job, master_ip, arguments,
memory=None,
override_parameters=None,
run_local=False,
native_adam_path=None):
"""
Invokes the ADAM container. Find ADAM at https://github.com/bigdatagenomics/adam.
:param toil.Job.job job: The Toil Job callin... | [
"def",
"call_adam",
"(",
"job",
",",
"master_ip",
",",
"arguments",
",",
"memory",
"=",
"None",
",",
"override_parameters",
"=",
"None",
",",
"run_local",
"=",
"False",
",",
"native_adam_path",
"=",
"None",
")",
":",
"if",
"run_local",
":",
"master",
"=",
... | 49.095238 | 23.507937 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.