text stringlengths 75 104k | code_tokens list | avg_line_len float64 7.91 980 | score float64 0 0.18 |
|---|---|---|---|
def _serialize_xml(self, root):
"""Serialize XML data into string
It serializes the dynamic xml created and converts
it to a string. This is done before sending the
xml to the ILO.
:param root: root of the dynamic xml.
"""
if hasattr(etree, 'tostringlist'):
... | [
"def",
"_serialize_xml",
"(",
"self",
",",
"root",
")",
":",
"if",
"hasattr",
"(",
"etree",
",",
"'tostringlist'",
")",
":",
"if",
"six",
".",
"PY3",
":",
"xml_content_list",
"=",
"[",
"x",
".",
"decode",
"(",
"\"utf-8\"",
")",
"for",
"x",
"in",
"etr... | 33.083333 | 0.002448 |
def to_json(model, sort=False, **kwargs):
"""
Return the model as a JSON document.
``kwargs`` are passed on to ``json.dumps``.
Parameters
----------
model : cobra.Model
The cobra model to represent.
sort : bool, optional
Whether to sort the metabolites, reactions, and genes... | [
"def",
"to_json",
"(",
"model",
",",
"sort",
"=",
"False",
",",
"*",
"*",
"kwargs",
")",
":",
"obj",
"=",
"model_to_dict",
"(",
"model",
",",
"sort",
"=",
"sort",
")",
"obj",
"[",
"u\"version\"",
"]",
"=",
"JSON_SPEC",
"return",
"json",
".",
"dumps",... | 25.592593 | 0.001395 |
def bytes_to_string(data, headers, **_):
"""Convert all *data* and *headers* bytes to strings.
Binary data that cannot be decoded is converted to a hexadecimal
representation via :func:`binascii.hexlify`.
:param iterable data: An :term:`iterable` (e.g. list) of rows.
:param iterable headers: The c... | [
"def",
"bytes_to_string",
"(",
"data",
",",
"headers",
",",
"*",
"*",
"_",
")",
":",
"return",
"(",
"(",
"[",
"utils",
".",
"bytes_to_string",
"(",
"v",
")",
"for",
"v",
"in",
"row",
"]",
"for",
"row",
"in",
"data",
")",
",",
"[",
"utils",
".",
... | 37.214286 | 0.001873 |
def _get_asym_hel(self,d):
"""
Find the asymmetry of each helicity.
"""
# get data 1+ 2+ 1- 2-
d0 = d[0]; d1 = d[2]; d2 = d[1]; d3 = d[3]
# pre-calcs
denom1 = d0+d1;
denom2 = d2+d3
# check for div by zero
denom1[den... | [
"def",
"_get_asym_hel",
"(",
"self",
",",
"d",
")",
":",
"# get data 1+ 2+ 1- 2-",
"d0",
"=",
"d",
"[",
"0",
"]",
"d1",
"=",
"d",
"[",
"2",
"]",
"d2",
"=",
"d",
"[",
"1",
"]",
"d3",
"=",
"d",
"[",
"3",
"]",
"# pre-calcs",
"denom1",
"=",
"d0",
... | 34.545455 | 0.020478 |
def flatten_dictionary(nested_dict, separator):
"""Flattens a nested dictionary.
New keys are concatenations of nested keys with the `separator` in between.
"""
flat_dict = {}
for key, val in nested_dict.items():
if isinstance(val, dict):
new_flat_dict = flatten_dictionary(val,... | [
"def",
"flatten_dictionary",
"(",
"nested_dict",
",",
"separator",
")",
":",
"flat_dict",
"=",
"{",
"}",
"for",
"key",
",",
"val",
"in",
"nested_dict",
".",
"items",
"(",
")",
":",
"if",
"isinstance",
"(",
"val",
",",
"dict",
")",
":",
"new_flat_dict",
... | 31.647059 | 0.001805 |
def bisect(f, a, b, args=(), xtol=_xtol,
rtol=_rtol, maxiter=_iter, disp=True):
"""
Find root of a function within an interval adapted from Scipy's bisect.
Basic bisection routine to find a zero of the function `f` between the
arguments `a` and `b`. `f(a)` and `f(b)` cannot have the same sig... | [
"def",
"bisect",
"(",
"f",
",",
"a",
",",
"b",
",",
"args",
"=",
"(",
")",
",",
"xtol",
"=",
"_xtol",
",",
"rtol",
"=",
"_rtol",
",",
"maxiter",
"=",
"_iter",
",",
"disp",
"=",
"True",
")",
":",
"if",
"xtol",
"<=",
"0",
":",
"raise",
"ValueEr... | 29.24359 | 0.000424 |
def make_postcard(self, npix=300, shape=(1070, 1132), buffer_size=15):
"""
Develop a "postcard" region around the target star.
Other stars in this postcard will be used as possible reference stars.
Args:
npix: The size of the postcard region. The region will be a sq... | [
"def",
"make_postcard",
"(",
"self",
",",
"npix",
"=",
"300",
",",
"shape",
"=",
"(",
"1070",
",",
"1132",
")",
",",
"buffer_size",
"=",
"15",
")",
":",
"source",
"=",
"self",
".",
"kic",
"client",
"=",
"kplr",
".",
"API",
"(",
")",
"targ",
"=",
... | 36.747126 | 0.013402 |
def generate_hash(data, algorithm='chd_ph', hash_fns=(), chd_keys_per_bin=1,
chd_load_factor=None, fch_bits_per_key=None,
num_graph_vertices=None, brz_memory_size=8,
brz_temp_dir=None, brz_max_keys_per_bucket=128,
bdz_precomputed_rank=7, chd_avg_ke... | [
"def",
"generate_hash",
"(",
"data",
",",
"algorithm",
"=",
"'chd_ph'",
",",
"hash_fns",
"=",
"(",
")",
",",
"chd_keys_per_bin",
"=",
"1",
",",
"chd_load_factor",
"=",
"None",
",",
"fch_bits_per_key",
"=",
"None",
",",
"num_graph_vertices",
"=",
"None",
",",... | 44.477778 | 0.000122 |
def _get_m2m_field(model, sender):
"""
Get the field name from a model and a sender from m2m_changed signal.
"""
for field in getattr(model, '_tracked_fields', []):
if isinstance(model._meta.get_field(field), ManyToManyField):
if getattr(model, field).through == sender:
... | [
"def",
"_get_m2m_field",
"(",
"model",
",",
"sender",
")",
":",
"for",
"field",
"in",
"getattr",
"(",
"model",
",",
"'_tracked_fields'",
",",
"[",
"]",
")",
":",
"if",
"isinstance",
"(",
"model",
".",
"_meta",
".",
"get_field",
"(",
"field",
")",
",",
... | 45.833333 | 0.001783 |
def drag_sphere(Re, Method=None, AvailableMethods=False):
r'''This function handles calculation of drag coefficient on spheres.
Twenty methods are available, all requiring only the Reynolds number of the
sphere. Most methods are valid from Re=0 to Re=200,000. A correlation will
be automatically selected... | [
"def",
"drag_sphere",
"(",
"Re",
",",
"Method",
"=",
"None",
",",
"AvailableMethods",
"=",
"False",
")",
":",
"def",
"list_methods",
"(",
")",
":",
"methods",
"=",
"[",
"]",
"for",
"key",
",",
"(",
"func",
",",
"Re_min",
",",
"Re_max",
")",
"in",
"... | 37.648649 | 0.001399 |
def _get_parent_timestamp(dirname, mtime):
"""
Get the timestamps up the directory tree. All the way to root.
Because they affect every subdirectory.
"""
parent_pathname = os.path.dirname(dirname)
# max between the parent timestamp the one passed in
mtime = _max_timestamps(parent_pathname,... | [
"def",
"_get_parent_timestamp",
"(",
"dirname",
",",
"mtime",
")",
":",
"parent_pathname",
"=",
"os",
".",
"path",
".",
"dirname",
"(",
"dirname",
")",
"# max between the parent timestamp the one passed in",
"mtime",
"=",
"_max_timestamps",
"(",
"parent_pathname",
","... | 31.6875 | 0.001916 |
def after(self, value):
"""
Sets the operator type to Query.Op.After and sets the value to
the amount that this query should be lower than. This is functionally
the same as doing the lessThan operation, but is useful for visual
queries for things like dates.
:p... | [
"def",
"after",
"(",
"self",
",",
"value",
")",
":",
"newq",
"=",
"self",
".",
"copy",
"(",
")",
"newq",
".",
"setOp",
"(",
"Query",
".",
"Op",
".",
"After",
")",
"newq",
".",
"setValue",
"(",
"value",
")",
"return",
"newq"
] | 35.2 | 0.008299 |
def store_traces(self, value):
"""
Setter for _store_traces. _store_traces controls in memory storing of received lines.
Also logs the change for the user.
:param value: Boolean
:return: Nothing
"""
if not value:
self.logger.debug("Stopping storing re... | [
"def",
"store_traces",
"(",
"self",
",",
"value",
")",
":",
"if",
"not",
"value",
":",
"self",
".",
"logger",
".",
"debug",
"(",
"\"Stopping storing received lines for dut %d\"",
",",
"self",
".",
"index",
")",
"self",
".",
"_store_traces",
"=",
"False",
"el... | 37.357143 | 0.009328 |
def SpamsumDistance(ssA, ssB):
'''
returns the spamsum distance between ssA and ssB
if they use a different block size, assume maximum distance
otherwise returns the LevDistance
'''
mA = re.match('^(\d+)[:](.*)$', ssA)
mB = re.match('^(\d+)[:](.*)$', ssB)
if mA == None or mB == None:
... | [
"def",
"SpamsumDistance",
"(",
"ssA",
",",
"ssB",
")",
":",
"mA",
"=",
"re",
".",
"match",
"(",
"'^(\\d+)[:](.*)$'",
",",
"ssA",
")",
"mB",
"=",
"re",
".",
"match",
"(",
"'^(\\d+)[:](.*)$'",
",",
"ssB",
")",
"if",
"mA",
"==",
"None",
"or",
"mB",
"=... | 31.6875 | 0.015326 |
def get(self, param, default=EMPTY):
"""
Returns the nparam value, and returns the default if it doesn't exist.
If default is none, an exception will be raised instead.
the returned parameter will have been specialized against the global context
"""
if not self.has(param... | [
"def",
"get",
"(",
"self",
",",
"param",
",",
"default",
"=",
"EMPTY",
")",
":",
"if",
"not",
"self",
".",
"has",
"(",
"param",
")",
":",
"if",
"default",
"is",
"not",
"EMPTY",
":",
"return",
"default",
"raise",
"ParamNotFoundException",
"(",
"\"value ... | 45.714286 | 0.00204 |
def ttr(self, kloc, acc=10**3, verbose=1):
"""
Three terms relation's coefficient generator
Args:
k (numpy.ndarray, int):
The order of the coefficients.
acc (int):
Accuracy of discretized Stieltjes if analytical methods are
... | [
"def",
"ttr",
"(",
"self",
",",
"kloc",
",",
"acc",
"=",
"10",
"**",
"3",
",",
"verbose",
"=",
"1",
")",
":",
"kloc",
"=",
"numpy",
".",
"asarray",
"(",
"kloc",
",",
"dtype",
"=",
"int",
")",
"shape",
"=",
"kloc",
".",
"shape",
"kloc",
"=",
"... | 34.125 | 0.002375 |
def count_alleles(self, max_allele=None, subpop=None):
"""Count the number of calls of each allele per variant.
Parameters
----------
max_allele : int, optional
The highest allele index to count. Alleles greater than this
index will be ignored.
subpop : a... | [
"def",
"count_alleles",
"(",
"self",
",",
"max_allele",
"=",
"None",
",",
"subpop",
"=",
"None",
")",
":",
"# check inputs",
"subpop",
"=",
"_normalize_subpop_arg",
"(",
"subpop",
",",
"self",
".",
"shape",
"[",
"1",
"]",
")",
"# determine alleles to count",
... | 28.531915 | 0.002163 |
def neg(self):
"""Negative value of all components."""
self.x = -self.x
self.y = -self.y
self.z = -self.z | [
"def",
"neg",
"(",
"self",
")",
":",
"self",
".",
"x",
"=",
"-",
"self",
".",
"x",
"self",
".",
"y",
"=",
"-",
"self",
".",
"y",
"self",
".",
"z",
"=",
"-",
"self",
".",
"z"
] | 26.6 | 0.014599 |
def _get_axis_mode(self, axis):
"will get the axis mode for the current series"
if all([isinstance(getattr(s, axis), TimeVariable) for s in self._series]):
return 'time'
return None | [
"def",
"_get_axis_mode",
"(",
"self",
",",
"axis",
")",
":",
"if",
"all",
"(",
"[",
"isinstance",
"(",
"getattr",
"(",
"s",
",",
"axis",
")",
",",
"TimeVariable",
")",
"for",
"s",
"in",
"self",
".",
"_series",
"]",
")",
":",
"return",
"'time'",
"re... | 42.6 | 0.013825 |
def cluster_nodes(self):
"""Each node in a Redis Cluster has its view of the current cluster
configuration, given by the set of known nodes, the state of the
connection we have with such nodes, their flags, properties and
assigned slots, and so forth.
``CLUSTER NODES`` provides ... | [
"def",
"cluster_nodes",
"(",
"self",
")",
":",
"def",
"format_response",
"(",
"result",
")",
":",
"values",
"=",
"[",
"]",
"for",
"row",
"in",
"result",
".",
"decode",
"(",
"'utf-8'",
")",
".",
"split",
"(",
"'\\n'",
")",
":",
"if",
"not",
"row",
"... | 45.319149 | 0.000919 |
def set_done(self):
""" set_done: records progress after Ricecooker process has been completed
Args: None
Returns: None
"""
self.__record_progress(Status.DONE)
# Delete restoration point for last step to indicate process has been completed
os.remove(self.... | [
"def",
"set_done",
"(",
"self",
")",
":",
"self",
".",
"__record_progress",
"(",
"Status",
".",
"DONE",
")",
"# Delete restoration point for last step to indicate process has been completed",
"os",
".",
"remove",
"(",
"self",
".",
"get_restore_path",
"(",
"Status",
".... | 38 | 0.011429 |
def _load_11_6(self, **kwargs):
"""Must check if rule actually exists before proceeding with load."""
if self._check_existence_by_collection(self._meta_data['container'], kwargs['name']):
return super(Protocol_Sip, self)._load(**kwargs)
msg = 'The application resource named, {}, does... | [
"def",
"_load_11_6",
"(",
"self",
",",
"*",
"*",
"kwargs",
")",
":",
"if",
"self",
".",
"_check_existence_by_collection",
"(",
"self",
".",
"_meta_data",
"[",
"'container'",
"]",
",",
"kwargs",
"[",
"'name'",
"]",
")",
":",
"return",
"super",
"(",
"Proto... | 53.111111 | 0.00823 |
def _task_to_dict(task):
"""Converts a WorkQueue to a JSON-able dictionary."""
payload = task.payload
if payload and task.content_type == 'application/json':
payload = json.loads(payload)
return dict(
task_id=task.task_id,
queue_name=task.queue_name,
eta=_datetime_to_epo... | [
"def",
"_task_to_dict",
"(",
"task",
")",
":",
"payload",
"=",
"task",
".",
"payload",
"if",
"payload",
"and",
"task",
".",
"content_type",
"==",
"'application/json'",
":",
"payload",
"=",
"json",
".",
"loads",
"(",
"payload",
")",
"return",
"dict",
"(",
... | 36.5625 | 0.001667 |
def decompose_code(code):
"""
Decomposes a MARC "code" into tag, ind1, ind2, subcode
"""
code = "%-6s" % code
ind1 = code[3:4]
if ind1 == " ": ind1 = "_"
ind2 = code[4:5]
if ind2 == " ": ind2 = "_"
subcode = code[5:6]
if subcode == " ": subcode = None
return (code[0:3], ind1,... | [
"def",
"decompose_code",
"(",
"code",
")",
":",
"code",
"=",
"\"%-6s\"",
"%",
"code",
"ind1",
"=",
"code",
"[",
"3",
":",
"4",
"]",
"if",
"ind1",
"==",
"\" \"",
":",
"ind1",
"=",
"\"_\"",
"ind2",
"=",
"code",
"[",
"4",
":",
"5",
"]",
"if",
"ind... | 27 | 0.01194 |
def send(self, msg):
"""Send `data` to `handle`, and tell the broker we have output. May
be called from any thread."""
self._router.broker.defer(self._send, msg) | [
"def",
"send",
"(",
"self",
",",
"msg",
")",
":",
"self",
".",
"_router",
".",
"broker",
".",
"defer",
"(",
"self",
".",
"_send",
",",
"msg",
")"
] | 45.5 | 0.010811 |
def _verifyReturnToArgs(query):
"""Verify that the arguments in the return_to URL are present in this
response.
"""
message = Message.fromPostArgs(query)
return_to = message.getArg(OPENID_NS, 'return_to')
if return_to is None:
raise ProtocolError('Response ha... | [
"def",
"_verifyReturnToArgs",
"(",
"query",
")",
":",
"message",
"=",
"Message",
".",
"fromPostArgs",
"(",
"query",
")",
"return_to",
"=",
"message",
".",
"getArg",
"(",
"OPENID_NS",
",",
"'return_to'",
")",
"if",
"return_to",
"is",
"None",
":",
"raise",
"... | 40.258065 | 0.002347 |
def set_margins(self, top=None, bottom=None):
"""Select top and bottom margins for the scrolling region.
:param int top: the smallest line number that is scrolled.
:param int bottom: the biggest line number that is scrolled.
"""
# XXX 0 corresponds to the CSI with no parameters.... | [
"def",
"set_margins",
"(",
"self",
",",
"top",
"=",
"None",
",",
"bottom",
"=",
"None",
")",
":",
"# XXX 0 corresponds to the CSI with no parameters.",
"if",
"(",
"top",
"is",
"None",
"or",
"top",
"==",
"0",
")",
"and",
"bottom",
"is",
"None",
":",
"self",... | 40.176471 | 0.00143 |
def process(self, salt_data, token, opts):
'''
Process events and publish data
'''
parts = salt_data['tag'].split('/')
if len(parts) < 2:
return
# TBD: Simplify these conditional expressions
if parts[1] == 'job':
if parts[3] == 'new':
... | [
"def",
"process",
"(",
"self",
",",
"salt_data",
",",
"token",
",",
"opts",
")",
":",
"parts",
"=",
"salt_data",
"[",
"'tag'",
"]",
".",
"split",
"(",
"'/'",
")",
"if",
"len",
"(",
"parts",
")",
"<",
"2",
":",
"return",
"# TBD: Simplify these condition... | 38 | 0.002334 |
def setCovariance(self, cov):
""" makes lowrank approximation of cov """
assert cov.shape[0]==self.dim, 'Dimension mismatch.'
S, U = la.eigh(cov)
U = U[:,::-1]
S = S[::-1]
_X = U[:, :self.rank] * sp.sqrt(S[:self.rank])
self.X = _X | [
"def",
"setCovariance",
"(",
"self",
",",
"cov",
")",
":",
"assert",
"cov",
".",
"shape",
"[",
"0",
"]",
"==",
"self",
".",
"dim",
",",
"'Dimension mismatch.'",
"S",
",",
"U",
"=",
"la",
".",
"eigh",
"(",
"cov",
")",
"U",
"=",
"U",
"[",
":",
",... | 34.875 | 0.013986 |
def requote_uri(uri):
"""Re-quote the given URI.
This function passes the given URI through an unquote/quote cycle to
ensure that it is fully and consistently quoted.
:rtype: str
"""
safe_with_percent = "!#$%&'()*+,/:;=?@[]~"
safe_without_percent = "!#$&'()*+,/:;=?@[]~"
try:
# Un... | [
"def",
"requote_uri",
"(",
"uri",
")",
":",
"safe_with_percent",
"=",
"\"!#$%&'()*+,/:;=?@[]~\"",
"safe_without_percent",
"=",
"\"!#$&'()*+,/:;=?@[]~\"",
"try",
":",
"# Unquote only the unreserved characters",
"# Then quote only illegal characters (do not quote reserved,",
"# unreser... | 44.5 | 0.001222 |
def main() -> None:
"""
Command-line processor. See ``--help`` for details.
"""
main_only_quicksetup_rootlogger()
wdcd_suffix = "_with_drop_create_database"
timeformat = "%Y%m%dT%H%M%S"
parser = argparse.ArgumentParser(
description="""
Back up a specific MySQL database. The r... | [
"def",
"main",
"(",
")",
"->",
"None",
":",
"main_only_quicksetup_rootlogger",
"(",
")",
"wdcd_suffix",
"=",
"\"_with_drop_create_database\"",
"timeformat",
"=",
"\"%Y%m%dT%H%M%S\"",
"parser",
"=",
"argparse",
".",
"ArgumentParser",
"(",
"description",
"=",
"\"\"\"\n ... | 39.959184 | 0.000249 |
def _write_scalar(self, name:str, scalar_value, iteration:int)->None:
"Writes single scalar value to Tensorboard."
tag = self.metrics_root + name
self.tbwriter.add_scalar(tag=tag, scalar_value=scalar_value, global_step=iteration) | [
"def",
"_write_scalar",
"(",
"self",
",",
"name",
":",
"str",
",",
"scalar_value",
",",
"iteration",
":",
"int",
")",
"->",
"None",
":",
"tag",
"=",
"self",
".",
"metrics_root",
"+",
"name",
"self",
".",
"tbwriter",
".",
"add_scalar",
"(",
"tag",
"=",
... | 62.5 | 0.023715 |
def Tags(self):
"""Return all tags found in the value stream.
Returns:
A `{tagType: ['list', 'of', 'tags']}` dictionary.
"""
return {
IMAGES: self.images.Keys(),
AUDIO: self.audios.Keys(),
HISTOGRAMS: self.histograms.Keys(),
SCALARS: self.scalars.Keys(),
CO... | [
"def",
"Tags",
"(",
"self",
")",
":",
"return",
"{",
"IMAGES",
":",
"self",
".",
"images",
".",
"Keys",
"(",
")",
",",
"AUDIO",
":",
"self",
".",
"audios",
".",
"Keys",
"(",
")",
",",
"HISTOGRAMS",
":",
"self",
".",
"histograms",
".",
"Keys",
"("... | 35.947368 | 0.001427 |
def destroy(name, stop=False, path=None):
'''
Destroy the named container.
.. warning::
Destroys all data associated with the container.
path
path to the container parent directory (default: /var/lib/lxc)
.. versionadded:: 2015.8.0
stop : False
If ``True``, the c... | [
"def",
"destroy",
"(",
"name",
",",
"stop",
"=",
"False",
",",
"path",
"=",
"None",
")",
":",
"_ensure_exists",
"(",
"name",
",",
"path",
"=",
"path",
")",
"if",
"not",
"stop",
"and",
"state",
"(",
"name",
",",
"path",
"=",
"path",
")",
"!=",
"'s... | 29.388889 | 0.000915 |
def pypy_version_monkeypatch():
"""Patch Tox to work with non-default PyPy 3 versions."""
# Travis virtualenv do not provide `pypy3`, which tox tries to execute.
# This doesnt affect Travis python version `pypy3`, as the pyenv pypy3
# is in the PATH.
# https://github.com/travis-ci/travis-ci/issues/6... | [
"def",
"pypy_version_monkeypatch",
"(",
")",
":",
"# Travis virtualenv do not provide `pypy3`, which tox tries to execute.",
"# This doesnt affect Travis python version `pypy3`, as the pyenv pypy3",
"# is in the PATH.",
"# https://github.com/travis-ci/travis-ci/issues/6304",
"# Force use of the vi... | 52.7 | 0.001866 |
def handle(self):
"""Handles the real time update of some code from the cached representation
of the module.
"""
#If we have more statements in the buffer than the cached, it doesn't matter,
#we just run the first few replacements of the cache concurrently and do
#what'... | [
"def",
"handle",
"(",
"self",
")",
":",
"#If we have more statements in the buffer than the cached, it doesn't matter, ",
"#we just run the first few replacements of the cache concurrently and do ",
"#what's left over from the buffer.",
"#REVIEW",
"if",
"self",
".",
"mode",
"==",
"\"in... | 44 | 0.013589 |
def face_colors(self, values):
"""
Set the colors for each face of a mesh.
This will apply these colors and delete any previously specified
color information.
Parameters
------------
colors: (len(mesh.faces), 3), set each face to the specified color
... | [
"def",
"face_colors",
"(",
"self",
",",
"values",
")",
":",
"if",
"values",
"is",
"None",
":",
"if",
"'face_colors'",
"in",
"self",
".",
"_data",
":",
"self",
".",
"_data",
".",
"data",
".",
"pop",
"(",
"'face_colors'",
")",
"return",
"colors",
"=",
... | 32.666667 | 0.001982 |
def create_configuration(raid_config):
"""Create a RAID configuration on this server.
This method creates the given RAID configuration on the
server based on the input passed.
:param raid_config: The dictionary containing the requested
RAID configuration. This data structure should be as follow... | [
"def",
"create_configuration",
"(",
"raid_config",
")",
":",
"server",
"=",
"objects",
".",
"Server",
"(",
")",
"select_controllers",
"=",
"lambda",
"x",
":",
"not",
"x",
".",
"properties",
".",
"get",
"(",
"'HBA Mode Enabled'",
",",
"False",
")",
"_select_c... | 44.224299 | 0.000413 |
def _pyside2():
"""Initialise PySide2
These functions serve to test the existence of a binding
along with set it up in such a way that it aligns with
the final step; adding members from the original binding
to Qt.py
"""
import PySide2 as module
_setup(module, ["QtUiTools"])
Qt.__... | [
"def",
"_pyside2",
"(",
")",
":",
"import",
"PySide2",
"as",
"module",
"_setup",
"(",
"module",
",",
"[",
"\"QtUiTools\"",
"]",
")",
"Qt",
".",
"__binding_version__",
"=",
"module",
".",
"__version__",
"try",
":",
"try",
":",
"# Before merge of PySide and shib... | 28.978723 | 0.00071 |
def download(client, target_dir):
"""Download listing files from play and saves them into folder herachy."""
print('')
print('download store listings')
print('---------------------')
listings = client.list('listings')
for listing in listings:
path = os.path.join(target_dir, 'listings', l... | [
"def",
"download",
"(",
"client",
",",
"target_dir",
")",
":",
"print",
"(",
"''",
")",
"print",
"(",
"'download store listings'",
")",
"print",
"(",
"'---------------------'",
")",
"listings",
"=",
"client",
".",
"list",
"(",
"'listings'",
")",
"for",
"list... | 43.714286 | 0.0016 |
def _apply_color(code, content):
"""
Apply a color code to text
"""
normal = u'\x1B[0m'
seq = u'\x1B[%sm' % code
# Replace any normal sequences with this sequence to support nested colors
return seq + (normal + seq).join(content.split(normal)) + normal | [
"def",
"_apply_color",
"(",
"code",
",",
"content",
")",
":",
"normal",
"=",
"u'\\x1B[0m'",
"seq",
"=",
"u'\\x1B[%sm'",
"%",
"code",
"# Replace any normal sequences with this sequence to support nested colors",
"return",
"seq",
"+",
"(",
"normal",
"+",
"seq",
")",
"... | 30.1 | 0.009677 |
def calcparams_desoto(self, effective_irradiance, temp_cell, **kwargs):
"""
Use the :py:func:`calcparams_desoto` function, the input
parameters and ``self.module_parameters`` to calculate the
module currents and resistances.
Parameters
----------
effective_irradi... | [
"def",
"calcparams_desoto",
"(",
"self",
",",
"effective_irradiance",
",",
"temp_cell",
",",
"*",
"*",
"kwargs",
")",
":",
"kwargs",
"=",
"_build_kwargs",
"(",
"[",
"'a_ref'",
",",
"'I_L_ref'",
",",
"'I_o_ref'",
",",
"'R_sh_ref'",
",",
"'R_s'",
",",
"'alpha_... | 35.321429 | 0.001969 |
def loadDolfin(filename, c="gold", alpha=0.5, wire=None, bc=None):
"""Reads a `Fenics/Dolfin` file format. Return an ``Actor(vtkActor)`` object."""
if not os.path.exists(filename):
colors.printc("~noentry Error in loadDolfin: Cannot find", filename, c=1)
return None
import xml.etree.ElementT... | [
"def",
"loadDolfin",
"(",
"filename",
",",
"c",
"=",
"\"gold\"",
",",
"alpha",
"=",
"0.5",
",",
"wire",
"=",
"None",
",",
"bc",
"=",
"None",
")",
":",
"if",
"not",
"os",
".",
"path",
".",
"exists",
"(",
"filename",
")",
":",
"colors",
".",
"print... | 34.816327 | 0.00171 |
def clear_imgs(self) -> None:
"Clear the widget's images preview pane."
self._preview_header.value = self._heading
self._img_pane.children = tuple() | [
"def",
"clear_imgs",
"(",
"self",
")",
"->",
"None",
":",
"self",
".",
"_preview_header",
".",
"value",
"=",
"self",
".",
"_heading",
"self",
".",
"_img_pane",
".",
"children",
"=",
"tuple",
"(",
")"
] | 42.25 | 0.011628 |
def random_word(self, length, prefix=0, start=False, end=False,
flatten=False):
"""
Generate a random word of length from this table.
:param length: the length of the generated word; >= 1;
:param prefix: if greater than 0, the maximum length of the prefix to
... | [
"def",
"random_word",
"(",
"self",
",",
"length",
",",
"prefix",
"=",
"0",
",",
"start",
"=",
"False",
",",
"end",
"=",
"False",
",",
"flatten",
"=",
"False",
")",
":",
"if",
"start",
":",
"word",
"=",
"\">\"",
"length",
"+=",
"1",
"return",
"self"... | 47.172414 | 0.002149 |
def rouge_l_sentence_level(evaluated_sentences, reference_sentences):
"""
Computes ROUGE-L (sentence level) of two text collections of sentences.
http://research.microsoft.com/en-us/um/people/cyl/download/papers/
rouge-working-note-v1.3.1.pdf
Calculated according to:
R_lcs = LCS(X,Y)/m
P_lc... | [
"def",
"rouge_l_sentence_level",
"(",
"evaluated_sentences",
",",
"reference_sentences",
")",
":",
"if",
"len",
"(",
"evaluated_sentences",
")",
"<=",
"0",
"or",
"len",
"(",
"reference_sentences",
")",
"<=",
"0",
":",
"raise",
"(",
"ValueError",
"(",
"\"Collecti... | 37.0625 | 0.000822 |
def pkg_blacklist(self):
"""Manage blacklist packages
"""
blacklist = BlackList()
options = [
"-b",
"--blacklist"
]
flag = [
"--add",
"--remove"
]
command = ["list"]
if (len(self.args) == 2 and self.a... | [
"def",
"pkg_blacklist",
"(",
"self",
")",
":",
"blacklist",
"=",
"BlackList",
"(",
")",
"options",
"=",
"[",
"\"-b\"",
",",
"\"--blacklist\"",
"]",
"flag",
"=",
"[",
"\"--add\"",
",",
"\"--remove\"",
"]",
"command",
"=",
"[",
"\"list\"",
"]",
"if",
"(",
... | 33.7 | 0.001923 |
def _latex_item_to_string(item, *, escape=False, as_content=False):
"""Use the render method when possible, otherwise uses str.
Args
----
item: object
An object that needs to be converted to a string
escape: bool
Flag that indicates if escaping is needed
as_content: bool
... | [
"def",
"_latex_item_to_string",
"(",
"item",
",",
"*",
",",
"escape",
"=",
"False",
",",
"as_content",
"=",
"False",
")",
":",
"if",
"isinstance",
"(",
"item",
",",
"pylatex",
".",
"base_classes",
".",
"LatexObject",
")",
":",
"if",
"as_content",
":",
"r... | 23.903226 | 0.001297 |
def datacenter(self, name):
"""
:param name: location key
:type name: :py:class:`basestring`
:Returns: a new DataCenter object
This method treats the 'name' argument as a location key (on the
`known_locations` attribute dict) or FQDN, and keeps existing... | [
"def",
"datacenter",
"(",
"self",
",",
"name",
")",
":",
"# The base form of this, as below, simply sets up a redirect. ",
"# j, _ = self.request('GET', 'datacenters/' + str(name))",
"if",
"name",
"not",
"in",
"self",
".",
"known_locations",
"and",
"'.'",
"not",
"in",
"name... | 42.9 | 0.012543 |
def values(self):
"""Returns a list of all values in the dictionary.
Returns:
list of str: [value1,value2,...,valueN]
"""
all_values = [v.decode('utf-8') for k,v in self.rdb.hgetall(self.session_hash).items()]
return all_values | [
"def",
"values",
"(",
"self",
")",
":",
"all_values",
"=",
"[",
"v",
".",
"decode",
"(",
"'utf-8'",
")",
"for",
"k",
",",
"v",
"in",
"self",
".",
"rdb",
".",
"hgetall",
"(",
"self",
".",
"session_hash",
")",
".",
"items",
"(",
")",
"]",
"return",... | 34.125 | 0.014286 |
def get(self, key, default=None):
""" Gets @key from :prop:key_prefix, defaulting to @default """
try:
return self[key]
except KeyError:
return default or self._default | [
"def",
"get",
"(",
"self",
",",
"key",
",",
"default",
"=",
"None",
")",
":",
"try",
":",
"return",
"self",
"[",
"key",
"]",
"except",
"KeyError",
":",
"return",
"default",
"or",
"self",
".",
"_default"
] | 35.166667 | 0.009259 |
def document_is_multiline_python(document):
"""
Determine whether this is a multiline Python document.
"""
def ends_in_multiline_string():
"""
``True`` if we're inside a multiline string at the end of the text.
"""
delims = _multiline_string_delims.findall(document.text)
... | [
"def",
"document_is_multiline_python",
"(",
"document",
")",
":",
"def",
"ends_in_multiline_string",
"(",
")",
":",
"\"\"\"\n ``True`` if we're inside a multiline string at the end of the text.\n \"\"\"",
"delims",
"=",
"_multiline_string_delims",
".",
"findall",
"(",... | 32.527778 | 0.001658 |
def _check_open_dir(self, fs, path, info):
# type: (FS, Text, Info) -> bool
"""Check if a directory should be considered in the walk.
"""
if self.exclude_dirs is not None and fs.match(self.exclude_dirs, info.name):
return False
if self.filter_dirs is not None and not ... | [
"def",
"_check_open_dir",
"(",
"self",
",",
"fs",
",",
"path",
",",
"info",
")",
":",
"# type: (FS, Text, Info) -> bool",
"if",
"self",
".",
"exclude_dirs",
"is",
"not",
"None",
"and",
"fs",
".",
"match",
"(",
"self",
".",
"exclude_dirs",
",",
"info",
".",... | 47.333333 | 0.011521 |
def info(self):
"""Execute an HTTP request to get details on a queue, and
return it.
"""
url = "queues/%s" % (self.name,)
result = self.client.get(url)
return result['body']['queue'] | [
"def",
"info",
"(",
"self",
")",
":",
"url",
"=",
"\"queues/%s\"",
"%",
"(",
"self",
".",
"name",
",",
")",
"result",
"=",
"self",
".",
"client",
".",
"get",
"(",
"url",
")",
"return",
"result",
"[",
"'body'",
"]",
"[",
"'queue'",
"]"
] | 28 | 0.008658 |
def _add_job_from_spec(self, job_json, use_job_id=True):
""" Add a single job to the Dagobah from a spec. """
job_id = (job_json['job_id']
if use_job_id
else self.backend.get_new_job_id())
self.add_job(str(job_json['name']), job_id)
job = self.get_job... | [
"def",
"_add_job_from_spec",
"(",
"self",
",",
"job_json",
",",
"use_job_id",
"=",
"True",
")",
":",
"job_id",
"=",
"(",
"job_json",
"[",
"'job_id'",
"]",
"if",
"use_job_id",
"else",
"self",
".",
"backend",
".",
"get_new_job_id",
"(",
")",
")",
"self",
"... | 43.423077 | 0.001733 |
def _steal_content(self, other_page):
"""
Call ImgDoc.steal_page() instead
"""
other_doc = other_page.doc
other_doc_pages = other_doc.pages[:]
other_doc_nb_pages = other_doc.nb_pages
other_page_nb = other_page.page_nb
to_move = [
(other_page._... | [
"def",
"_steal_content",
"(",
"self",
",",
"other_page",
")",
":",
"other_doc",
"=",
"other_page",
".",
"doc",
"other_doc_pages",
"=",
"other_doc",
".",
"pages",
"[",
":",
"]",
"other_doc_nb_pages",
"=",
"other_doc",
".",
"nb_pages",
"other_page_nb",
"=",
"oth... | 35.896552 | 0.001871 |
def get_last_documents(self):
"""Return the most recently parsed list of ``Documents``.
:rtype: A list of the most recently parsed ``Documents`` ordered by name.
"""
return (
self.session.query(Document)
.filter(Document.name.in_(self.last_docs))
.ord... | [
"def",
"get_last_documents",
"(",
"self",
")",
":",
"return",
"(",
"self",
".",
"session",
".",
"query",
"(",
"Document",
")",
".",
"filter",
"(",
"Document",
".",
"name",
".",
"in_",
"(",
"self",
".",
"last_docs",
")",
")",
".",
"order_by",
"(",
"Do... | 32.636364 | 0.00813 |
def get_token_status(token, serializer, max_age=None, return_data=False):
"""Get the status of a token.
:param token: The token to check
:param serializer: The name of the seriailzer. Can be one of the
following: ``confirm``, ``login``, ``reset``
:param max_age: The name of the m... | [
"def",
"get_token_status",
"(",
"token",
",",
"serializer",
",",
"max_age",
"=",
"None",
",",
"return_data",
"=",
"False",
")",
":",
"serializer",
"=",
"getattr",
"(",
"_security",
",",
"serializer",
"+",
"'_serializer'",
")",
"max_age",
"=",
"get_max_age",
... | 33.09375 | 0.000917 |
def get_mailcap_entry(self, url):
"""
Search through the mime handlers list and attempt to find the
appropriate command to open the provided url with.
Will raise a MailcapEntryNotFound exception if no valid command exists.
Params:
url (text): URL that will be checke... | [
"def",
"get_mailcap_entry",
"(",
"self",
",",
"url",
")",
":",
"for",
"parser",
"in",
"mime_parsers",
".",
"parsers",
":",
"if",
"parser",
".",
"pattern",
".",
"match",
"(",
"url",
")",
":",
"# modified_url may be the same as the original url, but it",
"# could al... | 44.957447 | 0.00139 |
def asgate(self) -> Gate:
"""
Return the action of this circuit as a gate
"""
gate = identity_gate(self.qubits)
for elem in self.elements:
gate = elem.asgate() @ gate
return gate | [
"def",
"asgate",
"(",
"self",
")",
"->",
"Gate",
":",
"gate",
"=",
"identity_gate",
"(",
"self",
".",
"qubits",
")",
"for",
"elem",
"in",
"self",
".",
"elements",
":",
"gate",
"=",
"elem",
".",
"asgate",
"(",
")",
"@",
"gate",
"return",
"gate"
] | 28.875 | 0.008403 |
def _process_interaction(self, source_id, interaction, text, pmid,
extra_annotations):
"""Process an interaction JSON tuple from the ISI output, and adds up
to one statement to the list of extracted statements.
Parameters
----------
source_id : str
... | [
"def",
"_process_interaction",
"(",
"self",
",",
"source_id",
",",
"interaction",
",",
"text",
",",
"pmid",
",",
"extra_annotations",
")",
":",
"verb",
"=",
"interaction",
"[",
"0",
"]",
".",
"lower",
"(",
")",
"subj",
"=",
"interaction",
"[",
"-",
"2",
... | 43.715909 | 0.000763 |
def find_rings(self, including=None):
"""
Find ring structures in the MoleculeGraph.
:param including: list of site indices. If
including is not None, then find_rings will
only return those rings including the specified
sites. By default, this parameter is None, and
... | [
"def",
"find_rings",
"(",
"self",
",",
"including",
"=",
"None",
")",
":",
"# Copies self.graph such that all edges (u, v) matched by edges (v, u)",
"undirected",
"=",
"self",
".",
"graph",
".",
"to_undirected",
"(",
")",
"directed",
"=",
"undirected",
".",
"to_direct... | 35.469388 | 0.00112 |
def get_user_stats_for_game(self, steamID, appID, format=None):
"""Request the user stats for a given game.
steamID: The users ID
appID: The app id
format: Return format. None defaults to json. (json, xml, vdf)
"""
parameters = {'steamid' : steamID, 'appid' : appID}
... | [
"def",
"get_user_stats_for_game",
"(",
"self",
",",
"steamID",
",",
"appID",
",",
"format",
"=",
"None",
")",
":",
"parameters",
"=",
"{",
"'steamid'",
":",
"steamID",
",",
"'appid'",
":",
"appID",
"}",
"if",
"format",
"is",
"not",
"None",
":",
"paramete... | 38.266667 | 0.008503 |
def link(self, oldpath, newpath, dir_fd=None):
"""Create a hard link at new_path, pointing at old_path.
Args:
oldpath: An existing link to the target file.
newpath: The destination path to create a new link at.
dir_fd: If not `None`, the file descriptor of a director... | [
"def",
"link",
"(",
"self",
",",
"oldpath",
",",
"newpath",
",",
"dir_fd",
"=",
"None",
")",
":",
"oldpath",
"=",
"self",
".",
"_path_with_dir_fd",
"(",
"oldpath",
",",
"self",
".",
"link",
",",
"dir_fd",
")",
"self",
".",
"filesystem",
".",
"link",
... | 40.15 | 0.002433 |
def run(self):
""" Called by the process, it runs it.
NEVER call this method directly. Instead call start() to start the separate process.
If you don't want to use a second process, then call fetch() directly on this istance.
To stop, call terminate()
"""
if not self._q... | [
"def",
"run",
"(",
"self",
")",
":",
"if",
"not",
"self",
".",
"_queue",
":",
"raise",
"Exception",
"(",
"\"No queue available to send messages\"",
")",
"while",
"True",
":",
"self",
".",
"fetch",
"(",
")",
"time",
".",
"sleep",
"(",
"self",
".",
"_pause... | 32.928571 | 0.008439 |
def plot_fullcalib(dio_cross,feedtype='l',**kwargs):
'''
Generates and shows five plots: Uncalibrated diode, calibrated diode, fold information,
phase offsets, and gain offsets for a noise diode measurement. Most useful diagnostic plot to
make sure calibration proceeds correctly.
'''
plt.figure... | [
"def",
"plot_fullcalib",
"(",
"dio_cross",
",",
"feedtype",
"=",
"'l'",
",",
"*",
"*",
"kwargs",
")",
":",
"plt",
".",
"figure",
"(",
"\"Multiple Calibration Plots\"",
",",
"figsize",
"=",
"(",
"12",
",",
"9",
")",
")",
"left",
",",
"width",
"=",
"0.07... | 37.469388 | 0.032378 |
def callback(self, name, before=None, after=None):
"""Add a callback pair to this spectator.
You can specify, with keywords, whether each callback should be triggered
before, and/or or after a given method is called - hereafter refered to as
"beforebacks" and "afterbacks" respectively.
... | [
"def",
"callback",
"(",
"self",
",",
"name",
",",
"before",
"=",
"None",
",",
"after",
"=",
"None",
")",
":",
"if",
"isinstance",
"(",
"name",
",",
"(",
"list",
",",
"tuple",
")",
")",
":",
"for",
"name",
"in",
"name",
":",
"self",
".",
"callback... | 51.954545 | 0.002147 |
def copy_all(self, ctxt):
'''
copies all values into the current context from given context
:param ctxt:
'''
for key, value in ctxt.iteritems:
self.set_attribute(key, value) | [
"def",
"copy_all",
"(",
"self",
",",
"ctxt",
")",
":",
"for",
"key",
",",
"value",
"in",
"ctxt",
".",
"iteritems",
":",
"self",
".",
"set_attribute",
"(",
"key",
",",
"value",
")"
] | 31.571429 | 0.013216 |
def make_data(self):
"""Return data of the field in a format that can be converted to JSON
Returns:
data (dict): A dictionary of dictionaries, such that for a given x, y pair,
data[x][y] = {"dx": dx, "dy": dy}. Note that this is transposed from the
matrix repre... | [
"def",
"make_data",
"(",
"self",
")",
":",
"X",
",",
"Y",
",",
"DX",
",",
"DY",
"=",
"self",
".",
"_calc_partials",
"(",
")",
"data",
"=",
"{",
"}",
"import",
"pdb",
"for",
"x",
"in",
"self",
".",
"xrange",
":",
"data",
"[",
"x",
"]",
"=",
"{... | 37 | 0.008237 |
def _send_splunk(event, index_override=None, sourcetype_override=None):
'''
Send the results to Splunk.
Requires the Splunk HTTP Event Collector running on port 8088.
This is available on Splunk Enterprise version 6.3 or higher.
'''
# Get Splunk Options
opts = _get_options()
log.info(st... | [
"def",
"_send_splunk",
"(",
"event",
",",
"index_override",
"=",
"None",
",",
"sourcetype_override",
"=",
"None",
")",
":",
"# Get Splunk Options",
"opts",
"=",
"_get_options",
"(",
")",
"log",
".",
"info",
"(",
"str",
"(",
"'Options: %s'",
")",
",",
"# futu... | 35.057143 | 0.001586 |
def prt_summary_code(self, prt=sys.stdout):
"""Print summary of codes and groups that can be inputs to get_evcodes."""
prt.write('EVIDENCE GROUP AND CODES:\n')
for grp, c2nt in self.grp2code2nt.items():
prt.write(' {GRP:19}: {CODES}\n'.format(GRP=grp, CODES=' '.join(c2nt.keys()))) | [
"def",
"prt_summary_code",
"(",
"self",
",",
"prt",
"=",
"sys",
".",
"stdout",
")",
":",
"prt",
".",
"write",
"(",
"'EVIDENCE GROUP AND CODES:\\n'",
")",
"for",
"grp",
",",
"c2nt",
"in",
"self",
".",
"grp2code2nt",
".",
"items",
"(",
")",
":",
"prt",
"... | 63.2 | 0.0125 |
def from_variant_and_transcript(
cls, variant, transcript, context_size):
"""
Extracts the reference sequence around a variant locus on a particular
transcript.
Parameters
----------
variant : varcode.Variant
transcript : pyensembl.Transcript
... | [
"def",
"from_variant_and_transcript",
"(",
"cls",
",",
"variant",
",",
"transcript",
",",
"context_size",
")",
":",
"full_transcript_sequence",
"=",
"transcript",
".",
"sequence",
"if",
"full_transcript_sequence",
"is",
"None",
":",
"logger",
".",
"warn",
"(",
"\"... | 33.782051 | 0.001106 |
def get_metrics_collector(self):
"""Returns this context's metrics collector"""
if self.metrics_collector is None or not isinstance(self.metrics_collector, MetricsCollector):
raise RuntimeError("Metrics collector is not registered in this context")
return self.metrics_collector | [
"def",
"get_metrics_collector",
"(",
"self",
")",
":",
"if",
"self",
".",
"metrics_collector",
"is",
"None",
"or",
"not",
"isinstance",
"(",
"self",
".",
"metrics_collector",
",",
"MetricsCollector",
")",
":",
"raise",
"RuntimeError",
"(",
"\"Metrics collector is ... | 58.4 | 0.010135 |
def _apply_rules_no_recurse(expr, rules):
"""Non-recursively match expr again all rules"""
try:
# `rules` is an OrderedDict key => (pattern, replacement)
items = rules.items()
except AttributeError:
# `rules` is a list of (pattern, replacement) tuples
items = enumerate(rules)... | [
"def",
"_apply_rules_no_recurse",
"(",
"expr",
",",
"rules",
")",
":",
"try",
":",
"# `rules` is an OrderedDict key => (pattern, replacement)",
"items",
"=",
"rules",
".",
"items",
"(",
")",
"except",
"AttributeError",
":",
"# `rules` is a list of (pattern, replacement) tup... | 33.5 | 0.001815 |
def _make_table_formatter(f, offset=None):
""" A closure-izer for table arguments that include a format and possibly an offset. """
format = f
delta = offset
return lambda v: _resolve_table(v, format, delta) | [
"def",
"_make_table_formatter",
"(",
"f",
",",
"offset",
"=",
"None",
")",
":",
"format",
"=",
"f",
"delta",
"=",
"offset",
"return",
"lambda",
"v",
":",
"_resolve_table",
"(",
"v",
",",
"format",
",",
"delta",
")"
] | 42.2 | 0.027907 |
def setNewPassword(self, url, username, password):
"""
Public method to manually set the credentials for a url in the browser.
"""
self.br.add_password(url, username, password) | [
"def",
"setNewPassword",
"(",
"self",
",",
"url",
",",
"username",
",",
"password",
")",
":",
"self",
".",
"br",
".",
"add_password",
"(",
"url",
",",
"username",
",",
"password",
")"
] | 41.6 | 0.014151 |
def convert(self, value, units, newunits):
"""
Converts a value expressed in certain *units* to a new units.
"""
return value * self._units[units] / self._units[newunits] | [
"def",
"convert",
"(",
"self",
",",
"value",
",",
"units",
",",
"newunits",
")",
":",
"return",
"value",
"*",
"self",
".",
"_units",
"[",
"units",
"]",
"/",
"self",
".",
"_units",
"[",
"newunits",
"]"
] | 39.6 | 0.009901 |
def _normalize_coerce_to_field_dict(self, v):
""" coerces strings to a dict {'value': str} """
def tokenize(s):
""" Tokenize a string by splitting it by + and -
>>> tokenize('this + that')
['this', '+', 'that']
>>> tokenize('this+that')
['th... | [
"def",
"_normalize_coerce_to_field_dict",
"(",
"self",
",",
"v",
")",
":",
"def",
"tokenize",
"(",
"s",
")",
":",
"\"\"\" Tokenize a string by splitting it by + and -\n\n >>> tokenize('this + that')\n ['this', '+', 'that']\n\n >>> tokenize('this+that')\n ... | 35.288889 | 0.001225 |
def migrate(migrator, database, **kwargs):
""" Write your migrations here.
> Model = migrator.orm['name']
> migrator.sql(sql)
> migrator.create_table(Model)
> migrator.drop_table(Model, cascade=True)
> migrator.add_columns(Model, **fields)
> migrator.change_columns(Model, **fields)
> m... | [
"def",
"migrate",
"(",
"migrator",
",",
"database",
",",
"*",
"*",
"kwargs",
")",
":",
"@",
"migrator",
".",
"create_table",
"class",
"DataItem",
"(",
"pw",
".",
"Model",
")",
":",
"created",
"=",
"pw",
".",
"DateTimeField",
"(",
"default",
"=",
"dt",
... | 36.916667 | 0.0011 |
async def execute(query):
"""Execute *SELECT*, *INSERT*, *UPDATE* or *DELETE* query asyncronously.
:param query: peewee query instance created with ``Model.select()``,
``Model.update()`` etc.
:return: result depends on query type, it's the same as for sync
``query.execute()``
... | [
"async",
"def",
"execute",
"(",
"query",
")",
":",
"if",
"isinstance",
"(",
"query",
",",
"(",
"peewee",
".",
"Select",
",",
"peewee",
".",
"ModelCompoundSelectQuery",
")",
")",
":",
"coroutine",
"=",
"select",
"elif",
"isinstance",
"(",
"query",
",",
"p... | 34.7 | 0.001403 |
def __get_segment_types(self, element):
"""
given a <segment> or <group> element, returns its segment type and the
segment type of its parent (i.e. its dominating node)
Parameters
----------
element : ??? etree Element
Returns
-------
segment_typ... | [
"def",
"__get_segment_types",
"(",
"self",
",",
"element",
")",
":",
"if",
"not",
"'parent'",
"in",
"element",
".",
"attrib",
":",
"if",
"element",
".",
"tag",
"==",
"'segment'",
":",
"segment_type",
"=",
"'isolated'",
"parent_segment_type",
"=",
"None",
"el... | 41.58 | 0.00188 |
def average_azimuth(self):
"""
Calculate and return weighted average azimuth of all line's segments
in decimal degrees.
Uses formula from
http://en.wikipedia.org/wiki/Mean_of_circular_quantities
>>> from openquake.hazardlib.geo.point import Point as P
>>> '%.1f'... | [
"def",
"average_azimuth",
"(",
"self",
")",
":",
"if",
"len",
"(",
"self",
".",
"points",
")",
"==",
"2",
":",
"return",
"self",
".",
"points",
"[",
"0",
"]",
".",
"azimuth",
"(",
"self",
".",
"points",
"[",
"1",
"]",
")",
"lons",
"=",
"numpy",
... | 44.352941 | 0.001947 |
def G(self, v, t):
"""Aburn2012 equations right hand side, noise term
Args:
v: (8,) array
state vector
t: number
scalar time
Returns:
(8,1) array
Only one matrix column, meaning that in this example we are modelling
th... | [
"def",
"G",
"(",
"self",
",",
"v",
",",
"t",
")",
":",
"ret",
"=",
"np",
".",
"zeros",
"(",
"(",
"8",
",",
"1",
")",
")",
"ret",
"[",
"4",
",",
"0",
"]",
"=",
"self",
".",
"ke1",
"*",
"self",
".",
"He1",
"*",
"self",
".",
"u_sdev",
"ret... | 38.111111 | 0.009957 |
def getDPI(filepath):
"""
Return (width, height) for a given img file content
no requirements
"""
xDPI = -1
yDPI = -1
with open(filepath, 'rb') as fhandle:
head = fhandle.read(24)
size = len(head)
# handle GIFs
# GIFs doesn't have density
if size >= 10... | [
"def",
"getDPI",
"(",
"filepath",
")",
":",
"xDPI",
"=",
"-",
"1",
"yDPI",
"=",
"-",
"1",
"with",
"open",
"(",
"filepath",
",",
"'rb'",
")",
"as",
"fhandle",
":",
"head",
"=",
"fhandle",
".",
"read",
"(",
"24",
")",
"size",
"=",
"len",
"(",
"he... | 42.678899 | 0.00105 |
def _shutdown(self, libvirt_cmd, ssh_cmd, msg):
"""
Choose the invoking method (using libvirt or ssh)
to shutdown / poweroff the domain.
If acpi is defined in the domain use libvirt, otherwise use ssh.
Args:
libvirt_cmd (function): Libvirt function the invoke
... | [
"def",
"_shutdown",
"(",
"self",
",",
"libvirt_cmd",
",",
"ssh_cmd",
",",
"msg",
")",
":",
"if",
"not",
"self",
".",
"alive",
"(",
")",
":",
"return",
"with",
"LogTask",
"(",
"'{} VM {}'",
".",
"format",
"(",
"msg",
",",
"self",
".",
"vm",
".",
"na... | 34.578947 | 0.00148 |
def report_to_list(queryset, display_fields, user):
""" Create list from a report with all data filtering.
queryset: initial queryset to generate results
display_fields: list of field references or DisplayField models
user: requesting user
Returns list, message in case of issues.
"""
model... | [
"def",
"report_to_list",
"(",
"queryset",
",",
"display_fields",
",",
"user",
")",
":",
"model_class",
"=",
"queryset",
".",
"model",
"objects",
"=",
"queryset",
"message",
"=",
"\"\"",
"if",
"not",
"_can_change_or_view",
"(",
"model_class",
",",
"user",
")",
... | 30 | 0.000621 |
def date_from_quarter(base_date, ordinal, year):
"""
Extract date from quarter of a year
"""
interval = 3
month_start = interval * (ordinal - 1)
if month_start < 0:
month_start = 9
month_end = month_start + interval
if month_start == 0:
month_start = 1
return [
... | [
"def",
"date_from_quarter",
"(",
"base_date",
",",
"ordinal",
",",
"year",
")",
":",
"interval",
"=",
"3",
"month_start",
"=",
"interval",
"*",
"(",
"ordinal",
"-",
"1",
")",
"if",
"month_start",
"<",
"0",
":",
"month_start",
"=",
"9",
"month_end",
"=",
... | 28 | 0.002304 |
def upgrade_many(upgrade=True, create_examples_all=True):
"""upgrade many libs.
source: http://arduino.cc/playground/Main/LibraryList
you can set your arduino path if it is not default
os.environ['ARDUINO_HOME'] = '/home/...'
"""
urls = set()
def inst(url):
print('upgrading %s' %... | [
"def",
"upgrade_many",
"(",
"upgrade",
"=",
"True",
",",
"create_examples_all",
"=",
"True",
")",
":",
"urls",
"=",
"set",
"(",
")",
"def",
"inst",
"(",
"url",
")",
":",
"print",
"(",
"'upgrading %s'",
"%",
"url",
")",
"assert",
"url",
"not",
"in",
"... | 41.850575 | 0.001476 |
def get_episode_name(self, series, episode_numbers, season_number):
"""Perform lookup for name of episode numbers for a given series.
:param object series: instance of a series
:param list episode_numbers: the episode sequence number
:param int season_number: numeric season of series
... | [
"def",
"get_episode_name",
"(",
"self",
",",
"series",
",",
"episode_numbers",
",",
"season_number",
")",
":",
"ids",
"=",
"series",
".",
"to_identifier",
"(",
")",
"series_id",
"=",
"ids",
"[",
"'ids'",
"]",
"[",
"'trakt'",
"]",
"epnames",
"=",
"[",
"]"... | 37.44 | 0.002083 |
def make_link_node(rawtext, app, name, options):
"""
Create a link to the TL reference.
:param rawtext: Text being replaced with link node.
:param app: Sphinx application context
:param name: Name of the object to link to
:param options: Options dictionary passed to role func.
"""
try:
... | [
"def",
"make_link_node",
"(",
"rawtext",
",",
"app",
",",
"name",
",",
"options",
")",
":",
"try",
":",
"base",
"=",
"app",
".",
"config",
".",
"tl_ref_url",
"if",
"not",
"base",
":",
"raise",
"AttributeError",
"except",
"AttributeError",
"as",
"e",
":",... | 30.666667 | 0.001318 |
def _print(self, msg, flush=False, end="\n"):
"""Helper function to print connection status messages when in verbose mode."""
if self._verbose:
print2(msg, end=end, flush=flush) | [
"def",
"_print",
"(",
"self",
",",
"msg",
",",
"flush",
"=",
"False",
",",
"end",
"=",
"\"\\n\"",
")",
":",
"if",
"self",
".",
"_verbose",
":",
"print2",
"(",
"msg",
",",
"end",
"=",
"end",
",",
"flush",
"=",
"flush",
")"
] | 50.5 | 0.014634 |
def cybox_csv_handler(self, enrichment, fact, attr_info, add_fact_kargs):
"""
Handler for dealing with comma-separated values.
Unfortunately, CybOX et al. sometimes use comma-separated
value lists. Or rather, since Cybox 2.0.1, '##comma##'-separated lists.
At least now we can ... | [
"def",
"cybox_csv_handler",
"(",
"self",
",",
"enrichment",
",",
"fact",
",",
"attr_info",
",",
"add_fact_kargs",
")",
":",
"# Since Cybox 2.0.1, '##comma##' is to be used instead of ','. So,",
"# we first check whether '##comma##' occurs -- if so, we take",
"# that as separator; if ... | 33.517241 | 0.002 |
def _add_method_setting(self, conn, api_id, stage_name, path, key, value,
op):
"""
Update a single method setting on the specified stage. This uses the
'add' operation to PATCH the resource.
:param conn: APIGateway API connection
:type conn: :py:class... | [
"def",
"_add_method_setting",
"(",
"self",
",",
"conn",
",",
"api_id",
",",
"stage_name",
",",
"path",
",",
"key",
",",
"value",
",",
"op",
")",
":",
"logger",
".",
"debug",
"(",
"'update_stage PATCH %s on %s; value=%s'",
",",
"op",
",",
"path",
",",
"str"... | 38.731707 | 0.002457 |
def subscribe(self, topics=(), pattern=None, listener=None):
"""Subscribe to a list of topics, or a topic regex pattern.
Partitions will be dynamically assigned via a group coordinator.
Topic subscriptions are not incremental: this list will replace the
current assignment (if there is o... | [
"def",
"subscribe",
"(",
"self",
",",
"topics",
"=",
"(",
")",
",",
"pattern",
"=",
"None",
",",
"listener",
"=",
"None",
")",
":",
"if",
"self",
".",
"_user_assignment",
"or",
"(",
"topics",
"and",
"pattern",
")",
":",
"raise",
"IllegalStateError",
"(... | 49.571429 | 0.002019 |
def reducer_init_output(self):
""" establish connection to MongoDB """
try:
self.mongo = MongoGeo(db=DB, collection=COLLECTION, timeout=MONGO_TIMEOUT)
except ServerSelectionTimeoutError:
# failed to connect to running MongoDB instance
self.mongo = None | [
"def",
"reducer_init_output",
"(",
"self",
")",
":",
"try",
":",
"self",
".",
"mongo",
"=",
"MongoGeo",
"(",
"db",
"=",
"DB",
",",
"collection",
"=",
"COLLECTION",
",",
"timeout",
"=",
"MONGO_TIMEOUT",
")",
"except",
"ServerSelectionTimeoutError",
":",
"# fa... | 43.714286 | 0.009615 |
def priority(var):
"""Prioritizes resource position in the final HTML. To be fed into sorted(key=).
Javascript consoles throw errors if Bootstrap's js file is mentioned before jQuery. Using this function such errors
can be avoided. Used internally.
Positional arguments:
var -- value sent by list.s... | [
"def",
"priority",
"(",
"var",
")",
":",
"order",
"=",
"dict",
"(",
"JQUERY",
"=",
"'0'",
",",
"BOOTSTRAP",
"=",
"'1'",
")",
"return",
"order",
".",
"get",
"(",
"var",
",",
"var",
")"
] | 39.214286 | 0.008897 |
def validate_client_properties(props):
"""
Validate the client properties setting.
This will add the "version", "information", and "product" keys if they are
missing. All other keys are application-specific.
Raises:
exceptions.ConfigurationException: If any of the basic keys are overridden... | [
"def",
"validate_client_properties",
"(",
"props",
")",
":",
"for",
"key",
"in",
"(",
"\"version\"",
",",
"\"information\"",
",",
"\"product\"",
")",
":",
"# Nested dictionaries are not merged so key can be missing",
"if",
"key",
"not",
"in",
"props",
":",
"props",
... | 42.421053 | 0.002427 |
def mrcompletion(A, reordered=True):
"""
Minimum rank positive semidefinite completion. The routine takes a
positive semidefinite cspmatrix :math:`A` and returns a dense
matrix :math:`Y` with :math:`r` columns that satisfies
.. math::
P( YY^T ) = A
where
.. math::
r = ... | [
"def",
"mrcompletion",
"(",
"A",
",",
"reordered",
"=",
"True",
")",
":",
"assert",
"isinstance",
"(",
"A",
",",
"cspmatrix",
")",
"and",
"A",
".",
"is_factor",
"is",
"False",
",",
"\"A must be a cspmatrix\"",
"symb",
"=",
"A",
".",
"symb",
"n",
"=",
"... | 33.699029 | 0.028547 |
def _do_request(self, method, endpoint, data=None):
"""Perform one request, possibly solving unauthorized return code
"""
# No token - authorize
if self.token is None:
self._do_authorize()
r = requests.request(
method,
"{0}{1}".format(self.bas... | [
"def",
"_do_request",
"(",
"self",
",",
"method",
",",
"endpoint",
",",
"data",
"=",
"None",
")",
":",
"# No token - authorize",
"if",
"self",
".",
"token",
"is",
"None",
":",
"self",
".",
"_do_authorize",
"(",
")",
"r",
"=",
"requests",
".",
"request",
... | 31.323529 | 0.001821 |
def add_rfile(self, name, help, required=True, default=None):
"""
Add a new option with a type of a readable file. This is the same
as the string option with the exception that the default value
will have the following variables replaced within it:
$USER_DATA The path to the users data directory
$DATA_PAT... | [
"def",
"add_rfile",
"(",
"self",
",",
"name",
",",
"help",
",",
"required",
"=",
"True",
",",
"default",
"=",
"None",
")",
":",
"if",
"isinstance",
"(",
"default",
",",
"str",
")",
":",
"default",
"=",
"default",
".",
"replace",
"(",
"'$DATA_PATH '",
... | 58.666667 | 0.020503 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.