text stringlengths 75 104k | code_tokens list | avg_line_len float64 7.91 980 | score float64 0 0.18 |
|---|---|---|---|
def accel_move_tab_left(self, *args):
# TODO KEYBINDINGS ONLY
""" Callback to move a tab to the left """
pos = self.get_notebook().get_current_page()
if pos != 0:
self.move_tab(pos, pos - 1)
return True | [
"def",
"accel_move_tab_left",
"(",
"self",
",",
"*",
"args",
")",
":",
"# TODO KEYBINDINGS ONLY",
"pos",
"=",
"self",
".",
"get_notebook",
"(",
")",
".",
"get_current_page",
"(",
")",
"if",
"pos",
"!=",
"0",
":",
"self",
".",
"move_tab",
"(",
"pos",
",",... | 35.428571 | 0.011811 |
def get_account_certificate(self, account_id, cert_id, **kwargs): # noqa: E501
"""Get trusted certificate by ID. # noqa: E501
An endpoint for retrieving a trusted certificate by ID. **Example usage:** `curl https://api.us-east-1.mbedcloud.com/v3/accounts/{accountID}/trusted-certificates/{cert-id} -... | [
"def",
"get_account_certificate",
"(",
"self",
",",
"account_id",
",",
"cert_id",
",",
"*",
"*",
"kwargs",
")",
":",
"# noqa: E501",
"kwargs",
"[",
"'_return_http_data_only'",
"]",
"=",
"True",
"if",
"kwargs",
".",
"get",
"(",
"'asynchronous'",
")",
":",
"re... | 58.818182 | 0.001521 |
def run_script(self, description):
"""
Run an existing script using its description to look it up
Usage: C{engine.run_script(description)}
@param description: description of the script to run
@raise Exception: if the specified script does not exist
"""
... | [
"def",
"run_script",
"(",
"self",
",",
"description",
")",
":",
"targetScript",
"=",
"None",
"for",
"item",
"in",
"self",
".",
"configManager",
".",
"allItems",
":",
"if",
"item",
".",
"description",
"==",
"description",
"and",
"isinstance",
"(",
"item",
"... | 38 | 0.008559 |
def get_inline_expression(self, text):
"""Extract an inline expression from the given text."""
text = text.strip()
if not text.startswith(self.inline_tags[0]) or not text.endswith(self.inline_tags[1]):
return
return text[2:-2] | [
"def",
"get_inline_expression",
"(",
"self",
",",
"text",
")",
":",
"text",
"=",
"text",
".",
"strip",
"(",
")",
"if",
"not",
"text",
".",
"startswith",
"(",
"self",
".",
"inline_tags",
"[",
"0",
"]",
")",
"or",
"not",
"text",
".",
"endswith",
"(",
... | 37.857143 | 0.01107 |
def createWindow(self,cls=None,caption_t=None,*args,**kwargs):
"""
createWindow(cls=window.PengWindow, *args, **kwargs)
Creates a new window using the supplied ``cls``\ .
If ``cls`` is not given, :py:class:`peng3d.window.PengWindow()` will be used.
Any ... | [
"def",
"createWindow",
"(",
"self",
",",
"cls",
"=",
"None",
",",
"caption_t",
"=",
"None",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"if",
"cls",
"is",
"None",
":",
"from",
".",
"import",
"window",
"cls",
"=",
"window",
".",
"PengWindow... | 46.72093 | 0.023403 |
def batch_iterable(iterable, count):
"""
Yield batches of `count` items from the given iterable.
>>> for x in batch([1, 2, 3, 4, 5, 6, 7], 3):
>>> print(x)
[1, 2, 3]
[4, 5, 6]
[7]
:param iterable: An iterable
:type iterable: Iterable
:param count: Number of items per batch. I... | [
"def",
"batch_iterable",
"(",
"iterable",
",",
"count",
")",
":",
"if",
"count",
"<=",
"0",
":",
"return",
"current_batch",
"=",
"[",
"]",
"for",
"item",
"in",
"iterable",
":",
"if",
"len",
"(",
"current_batch",
")",
"==",
"count",
":",
"yield",
"curre... | 25.777778 | 0.001385 |
def split_by_rand_pct(self, valid_pct:float=0.2, seed:int=None)->'ItemLists':
"Split the items randomly by putting `valid_pct` in the validation set, optional `seed` can be passed."
if valid_pct==0.: return self.split_none()
if seed is not None: np.random.seed(seed)
rand_idx = np.random.... | [
"def",
"split_by_rand_pct",
"(",
"self",
",",
"valid_pct",
":",
"float",
"=",
"0.2",
",",
"seed",
":",
"int",
"=",
"None",
")",
"->",
"'ItemLists'",
":",
"if",
"valid_pct",
"==",
"0.",
":",
"return",
"self",
".",
"split_none",
"(",
")",
"if",
"seed",
... | 61.571429 | 0.029748 |
def get_fileset(self, fileset):
"""
Caches a single fileset (if the 'path' attribute is accessed
and it has not been previously cached for example
Parameters
----------
fileset : Fileset
The fileset to cache
prev_login : xnat.XNATSession
A... | [
"def",
"get_fileset",
"(",
"self",
",",
"fileset",
")",
":",
"if",
"fileset",
".",
"format",
"is",
"None",
":",
"raise",
"ArcanaUsageError",
"(",
"\"Attempting to download {}, which has not been assigned a \"",
"\"file format (see Fileset.formatted)\"",
".",
"format",
"("... | 45.990826 | 0.000781 |
def replace_pyof_version(module_fullname, version):
"""Replace the OF Version of a module fullname.
Get's a module name (eg. 'pyof.v0x01.common.header') and returns it on
a new 'version' (eg. 'pyof.v0x02.common.header').
Args:
module_fullname (str): The fullname of the modu... | [
"def",
"replace_pyof_version",
"(",
"module_fullname",
",",
"version",
")",
":",
"module_version",
"=",
"MetaStruct",
".",
"get_pyof_version",
"(",
"module_fullname",
")",
"if",
"not",
"module_version",
"or",
"module_version",
"==",
"version",
":",
"return",
"None",... | 42.32 | 0.001848 |
def command_line():
"""Command-line tool for Midas gas detector communication."""
import argparse
import asyncio
import json
parser = argparse.ArgumentParser(description="Read a Honeywell Midas gas "
"detector state from the command line.")
parser.add_argume... | [
"def",
"command_line",
"(",
")",
":",
"import",
"argparse",
"import",
"asyncio",
"import",
"json",
"parser",
"=",
"argparse",
".",
"ArgumentParser",
"(",
"description",
"=",
"\"Read a Honeywell Midas gas \"",
"\"detector state from the command line.\"",
")",
"parser",
"... | 35.444444 | 0.001527 |
def binary_stdout():
"""
A sys.stdout that accepts bytes.
"""
# First there is a Python3 issue.
try:
stdout = sys.stdout.buffer
except AttributeError:
# Probably Python 2, where bytes are strings.
stdout = sys.stdout
# On Windows the C runtime file orientation needs... | [
"def",
"binary_stdout",
"(",
")",
":",
"# First there is a Python3 issue.",
"try",
":",
"stdout",
"=",
"sys",
".",
"stdout",
".",
"buffer",
"except",
"AttributeError",
":",
"# Probably Python 2, where bytes are strings.",
"stdout",
"=",
"sys",
".",
"stdout",
"# On Win... | 24.210526 | 0.002092 |
def qtaax(mt, x, t, q, m=1):
""" geometrica """
q = float(q)
j = (mt.i - q) / (1 + q)
mtj = Actuarial(nt=mt.nt, i=j)
return taax(mtj, x, t) - ((float(m - 1) / float(m * 2)) * (1 - nEx(mt, x, t))) | [
"def",
"qtaax",
"(",
"mt",
",",
"x",
",",
"t",
",",
"q",
",",
"m",
"=",
"1",
")",
":",
"q",
"=",
"float",
"(",
"q",
")",
"j",
"=",
"(",
"mt",
".",
"i",
"-",
"q",
")",
"/",
"(",
"1",
"+",
"q",
")",
"mtj",
"=",
"Actuarial",
"(",
"nt",
... | 35 | 0.009302 |
def reserve(self, amount, account=None, **kwargs):
""" Reserve/Burn an amount of this shares
This removes the shares from the supply
:param bitshares.amount.Amount amount: The amount to be burned.
:param str account: (optional) the account to allow access
to... | [
"def",
"reserve",
"(",
"self",
",",
"amount",
",",
"account",
"=",
"None",
",",
"*",
"*",
"kwargs",
")",
":",
"assert",
"isinstance",
"(",
"amount",
",",
"Amount",
")",
"if",
"not",
"account",
":",
"if",
"\"default_account\"",
"in",
"self",
".",
"confi... | 38.964286 | 0.001789 |
def build_alexnet(self, weights, output_layer=None):
""" Connects graph of alexnet from weights """
if output_layer is None:
output_layer = self._output_layer
#conv1
#conv(11, 11, 96, 4, 4, padding='VALID', name='conv1')
k_h = 11; k_w = 11; c_o = 96; s_h = 4; s_w = 4... | [
"def",
"build_alexnet",
"(",
"self",
",",
"weights",
",",
"output_layer",
"=",
"None",
")",
":",
"if",
"output_layer",
"is",
"None",
":",
"output_layer",
"=",
"self",
".",
"_output_layer",
"#conv1",
"#conv(11, 11, 96, 4, 4, padding='VALID', name='conv1')",
"k_h",
"=... | 43.88 | 0.021395 |
def install_bash_completion(self, script_name=None, dest="~/.bashrc"):
'''add line to activate bash_completion for given script_name into dest
You can use this for letting the user install bash_completion::
from argdeco import command, main
@command("install-bash-completion",
... | [
"def",
"install_bash_completion",
"(",
"self",
",",
"script_name",
"=",
"None",
",",
"dest",
"=",
"\"~/.bashrc\"",
")",
":",
"if",
"'USERPROFILE'",
"in",
"os",
".",
"environ",
"and",
"'HOME'",
"not",
"in",
"os",
".",
"environ",
":",
"os",
".",
"environ",
... | 39.956522 | 0.002125 |
def is_indexed(self, partition):
""" Returns True if partition is already indexed. Otherwise returns False. """
query = text("""
SELECT vid
FROM partition_index
WHERE vid = :vid;
""")
result = self.execute(query, vid=partition.vid)
return bool(... | [
"def",
"is_indexed",
"(",
"self",
",",
"partition",
")",
":",
"query",
"=",
"text",
"(",
"\"\"\"\n SELECT vid\n FROM partition_index\n WHERE vid = :vid;\n \"\"\"",
")",
"result",
"=",
"self",
".",
"execute",
"(",
"query",
",",
"vid"... | 36.666667 | 0.008876 |
def upload_delete(self, token, **kwargs):
"https://developer.zendesk.com/rest_api/docs/core/attachments#delete-upload"
api_path = "/api/v2/uploads/{token}.json"
api_path = api_path.format(token=token)
return self.call(api_path, method="DELETE", **kwargs) | [
"def",
"upload_delete",
"(",
"self",
",",
"token",
",",
"*",
"*",
"kwargs",
")",
":",
"api_path",
"=",
"\"/api/v2/uploads/{token}.json\"",
"api_path",
"=",
"api_path",
".",
"format",
"(",
"token",
"=",
"token",
")",
"return",
"self",
".",
"call",
"(",
"api... | 56.4 | 0.01049 |
def remove_graphic(self, graphic: Graphics.Graphic, *, safe: bool=False) -> typing.Optional[typing.Sequence]:
"""Remove a graphic, but do it through the container, so dependencies can be tracked."""
return self.remove_model_item(self, "graphics", graphic, safe=safe) | [
"def",
"remove_graphic",
"(",
"self",
",",
"graphic",
":",
"Graphics",
".",
"Graphic",
",",
"*",
",",
"safe",
":",
"bool",
"=",
"False",
")",
"->",
"typing",
".",
"Optional",
"[",
"typing",
".",
"Sequence",
"]",
":",
"return",
"self",
".",
"remove_mode... | 93.333333 | 0.021277 |
def levelorder(self):
"""Return the nodes in the binary tree using level-order_ traversal.
A level-order_ traversal visits nodes left to right, level by level.
.. _level-order:
https://en.wikipedia.org/wiki/Tree_traversal#Breadth-first_search
:return: List of nodes.
... | [
"def",
"levelorder",
"(",
"self",
")",
":",
"current_nodes",
"=",
"[",
"self",
"]",
"result",
"=",
"[",
"]",
"while",
"len",
"(",
"current_nodes",
")",
">",
"0",
":",
"next_nodes",
"=",
"[",
"]",
"for",
"node",
"in",
"current_nodes",
":",
"result",
"... | 27.604167 | 0.001458 |
def add_vlan_int(self, vlan_id):
"""
Add VLAN Interface. VLAN interfaces are required for VLANs even when
not wanting to use the interface for any L3 features.
Args:
vlan_id: ID for the VLAN interface being created. Value of 2-4096.
Returns:
True if comm... | [
"def",
"add_vlan_int",
"(",
"self",
",",
"vlan_id",
")",
":",
"config",
"=",
"ET",
".",
"Element",
"(",
"'config'",
")",
"vlinterface",
"=",
"ET",
".",
"SubElement",
"(",
"config",
",",
"'interface-vlan'",
",",
"xmlns",
"=",
"(",
"\"urn:brocade.com:mgmt:\"",... | 34.931034 | 0.001921 |
def hasLogger(self, logger):
"""
Returns whether or not the inputed logger is tracked by this widget.
:param logger | <str> || <logging.Logger>
"""
if isinstance(logger, logging.Logger):
logger = logging.name
return logger in se... | [
"def",
"hasLogger",
"(",
"self",
",",
"logger",
")",
":",
"if",
"isinstance",
"(",
"logger",
",",
"logging",
".",
"Logger",
")",
":",
"logger",
"=",
"logging",
".",
"name",
"return",
"logger",
"in",
"self",
".",
"_loggers"
] | 32.2 | 0.012085 |
def CheckStyle(filename, clean_lines, linenum, file_extension, nesting_state,
error):
"""Checks rules from the 'C++ style rules' section of cppguide.html.
Most of these rules are hard to test (naming, comment style), but we
do what we can. In particular we check for 2-space indents, line lengths,... | [
"def",
"CheckStyle",
"(",
"filename",
",",
"clean_lines",
",",
"linenum",
",",
"file_extension",
",",
"nesting_state",
",",
"error",
")",
":",
"# Don't use \"elided\" lines here, otherwise we can't check commented lines.",
"# Don't want to use \"raw\" either, because we don't want ... | 47.042735 | 0.01121 |
def _track_change(self, name, value, formatter=None):
"""Track that a change happened.
This function is only needed for manually recording changes that are
not captured by changes to properties of this object that are tracked
automatically. Classes that inherit from `emulation_mixin` s... | [
"def",
"_track_change",
"(",
"self",
",",
"name",
",",
"value",
",",
"formatter",
"=",
"None",
")",
":",
"self",
".",
"_emulation_log",
".",
"track_change",
"(",
"self",
".",
"_emulation_address",
",",
"name",
",",
"value",
",",
"formatter",
")"
] | 52.925926 | 0.002062 |
def eli_hanley_dense(T, MW, Tc, Vc, Zc, omega, Cvm, Vm):
r'''Estimates the thermal conductivity of a gas at high pressure as a
function of temperature using the reference fluid method of Eli and
Hanley [1]_ as shown in [2]_.
.. math::
Tr = min(Tr, 2)
Vr = min(Vr, 2)
f = \frac{... | [
"def",
"eli_hanley_dense",
"(",
"T",
",",
"MW",
",",
"Tc",
",",
"Vc",
",",
"Zc",
",",
"omega",
",",
"Cvm",
",",
"Vm",
")",
":",
"Cs",
"=",
"[",
"2.907741307E6",
",",
"-",
"3.312874033E6",
",",
"1.608101838E6",
",",
"-",
"4.331904871E5",
",",
"7.06248... | 30.868966 | 0.001082 |
def _proxy(self):
"""
Generate an instance context for the instance, the context is capable of
performing various actions. All instance actions are proxied to the context
:returns: WorkersStatisticsContext for this WorkersStatisticsInstance
:rtype: twilio.rest.taskrouter.v1.wor... | [
"def",
"_proxy",
"(",
"self",
")",
":",
"if",
"self",
".",
"_context",
"is",
"None",
":",
"self",
".",
"_context",
"=",
"WorkersStatisticsContext",
"(",
"self",
".",
"_version",
",",
"workspace_sid",
"=",
"self",
".",
"_solution",
"[",
"'workspace_sid'",
"... | 42.928571 | 0.008143 |
def find_closest_match(target_track, tracks):
"""
Return closest match to target track
"""
track = None
# Get a list of (track, artist match ratio, name match ratio)
tracks_with_match_ratio = [(
track,
get_similarity(target_track.artist, track.artist),
get_similarity(targ... | [
"def",
"find_closest_match",
"(",
"target_track",
",",
"tracks",
")",
":",
"track",
"=",
"None",
"# Get a list of (track, artist match ratio, name match ratio)",
"tracks_with_match_ratio",
"=",
"[",
"(",
"track",
",",
"get_similarity",
"(",
"target_track",
".",
"artist",
... | 32.8 | 0.001481 |
def process(self, metrics, config):
"""Processes metrics.
This method is called by the Snap deamon during the process phase
of the execution of a Snap workflow. Examples of processing metrics
include applying filtering, max, min, average functions as well as
adding additional c... | [
"def",
"process",
"(",
"self",
",",
"metrics",
",",
"config",
")",
":",
"LOG",
".",
"debug",
"(",
"\"Process called\"",
")",
"for",
"metric",
"in",
"metrics",
":",
"metric",
".",
"tags",
"[",
"\"instance-id\"",
"]",
"=",
"config",
"[",
"\"instance-id\"",
... | 37.363636 | 0.002372 |
def sentences(self):
"""Iterate over all sentences (sentence_id, sentence) in the document, sentence is a list of 4-tuples (word,id,pos,lemma)"""
prevp = 0
prevs = 0
sentence = [];
sentence_id = ""
for word, id, pos, lemma in iter(self):
try:
d... | [
"def",
"sentences",
"(",
"self",
")",
":",
"prevp",
"=",
"0",
"prevs",
"=",
"0",
"sentence",
"=",
"[",
"]",
"sentence_id",
"=",
"\"\"",
"for",
"word",
",",
"id",
",",
"pos",
",",
"lemma",
"in",
"iter",
"(",
"self",
")",
":",
"try",
":",
"doc_id",... | 44.916667 | 0.029973 |
def _set_text(self, value):
""" set text at current working_index. Return whether it changed. """
working_index = self.working_index
working_lines = self._working_lines
original_value = working_lines[working_index]
working_lines[working_index] = value
# Return True when... | [
"def",
"_set_text",
"(",
"self",
",",
"value",
")",
":",
"working_index",
"=",
"self",
".",
"working_index",
"working_lines",
"=",
"self",
".",
"_working_lines",
"original_value",
"=",
"working_lines",
"[",
"working_index",
"]",
"working_lines",
"[",
"working_inde... | 43.631579 | 0.002361 |
def com_daltonmaag_check_ufolint(font):
"""Run ufolint on UFO source directory."""
import subprocess
ufolint_cmd = ["ufolint", font]
try:
subprocess.check_output(ufolint_cmd, stderr=subprocess.STDOUT)
except subprocess.CalledProcessError as e:
yield FAIL, ("ufolint failed the UFO source. Output follo... | [
"def",
"com_daltonmaag_check_ufolint",
"(",
"font",
")",
":",
"import",
"subprocess",
"ufolint_cmd",
"=",
"[",
"\"ufolint\"",
",",
"font",
"]",
"try",
":",
"subprocess",
".",
"check_output",
"(",
"ufolint_cmd",
",",
"stderr",
"=",
"subprocess",
".",
"STDOUT",
... | 34.785714 | 0.016 |
def fbeta_score(
gold, pred, pos_label=1, beta=1.0, ignore_in_gold=[], ignore_in_pred=[]
):
"""
Calculate recall for a single class.
Args:
gold: A 1d array-like of gold labels
pred: A 1d array-like of predicted labels (assuming abstain = 0)
ignore_in_gold: A list of labels for wh... | [
"def",
"fbeta_score",
"(",
"gold",
",",
"pred",
",",
"pos_label",
"=",
"1",
",",
"beta",
"=",
"1.0",
",",
"ignore_in_gold",
"=",
"[",
"]",
",",
"ignore_in_pred",
"=",
"[",
"]",
")",
":",
"gold",
",",
"pred",
"=",
"_preprocess",
"(",
"gold",
",",
"p... | 35.285714 | 0.000985 |
def visitLexerBlock(self, ctx: jsgParser.LexerBlockContext):
""" lexerBlock: OPREN lexeraltList CPREN """
self._rulePattern += '('
self.visitChildren(ctx)
self._rulePattern += ')' | [
"def",
"visitLexerBlock",
"(",
"self",
",",
"ctx",
":",
"jsgParser",
".",
"LexerBlockContext",
")",
":",
"self",
".",
"_rulePattern",
"+=",
"'('",
"self",
".",
"visitChildren",
"(",
"ctx",
")",
"self",
".",
"_rulePattern",
"+=",
"')'"
] | 41.4 | 0.009479 |
def execute(self, style, xpoints, ypoints, zpoints, mask=None,
backend='vectorized', specified_drift_arrays=None):
"""Calculates a kriged grid and the associated variance.
This is now the method that performs the main kriging calculation.
Note that currently measurements (i.e., ... | [
"def",
"execute",
"(",
"self",
",",
"style",
",",
"xpoints",
",",
"ypoints",
",",
"zpoints",
",",
"mask",
"=",
"None",
",",
"backend",
"=",
"'vectorized'",
",",
"specified_drift_arrays",
"=",
"None",
")",
":",
"if",
"self",
".",
"verbose",
":",
"print",
... | 54.608108 | 0.001539 |
def find_macro_by_name(self, name, package):
"""Find a macro in the graph by its name and package name, or None for
any package.
"""
return self._find_by_name(name, package, 'macros', [NodeType.Macro]) | [
"def",
"find_macro_by_name",
"(",
"self",
",",
"name",
",",
"package",
")",
":",
"return",
"self",
".",
"_find_by_name",
"(",
"name",
",",
"package",
",",
"'macros'",
",",
"[",
"NodeType",
".",
"Macro",
"]",
")"
] | 45.8 | 0.008584 |
def add_worksheet(self, name=None):
""" Adds a new worksheet """
url = self.build_url(self._endpoints.get('get_worksheets'))
response = self.session.post(url, data={'name': name} if name else None)
if not response:
return None
data = response.json()
return sel... | [
"def",
"add_worksheet",
"(",
"self",
",",
"name",
"=",
"None",
")",
":",
"url",
"=",
"self",
".",
"build_url",
"(",
"self",
".",
"_endpoints",
".",
"get",
"(",
"'get_worksheets'",
")",
")",
"response",
"=",
"self",
".",
"session",
".",
"post",
"(",
"... | 47.625 | 0.010309 |
def uniform_partition_fromgrid(grid, min_pt=None, max_pt=None):
"""Return a partition of an interval product based on a given grid.
This method is complementary to `uniform_partition_fromintv` in that
it infers the set to be partitioned from a given grid and optional
parameters for ``min_pt`` and ``max... | [
"def",
"uniform_partition_fromgrid",
"(",
"grid",
",",
"min_pt",
"=",
"None",
",",
"max_pt",
"=",
"None",
")",
":",
"# Make dictionaries from `min_pt` and `max_pt` and fill with `None` where",
"# no value is given (taking negative indices into account)",
"if",
"min_pt",
"is",
"... | 38.054054 | 0.000231 |
def get_object(self, *args, **kwargs):
"""
Should memoize the object to avoid multiple query if get_object is used many times in the view
"""
self.category_instance = get_object_or_404(Category, slug=self.kwargs['category_slug'])
return get_object_or_404(Post, thread__id=self.kwa... | [
"def",
"get_object",
"(",
"self",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"self",
".",
"category_instance",
"=",
"get_object_or_404",
"(",
"Category",
",",
"slug",
"=",
"self",
".",
"kwargs",
"[",
"'category_slug'",
"]",
")",
"return",
"get_... | 66.666667 | 0.012346 |
def pipe_fetch(context=None, _INPUT=None, conf=None, **kwargs):
"""A source that fetches and parses one or more feeds to return the
entries. Loopable.
Parameters
----------
context : pipe2py.Context object
_INPUT : pipeforever pipe or an iterable of items or fields
conf : {
'URL': [... | [
"def",
"pipe_fetch",
"(",
"context",
"=",
"None",
",",
"_INPUT",
"=",
"None",
",",
"conf",
"=",
"None",
",",
"*",
"*",
"kwargs",
")",
":",
"splits",
"=",
"get_splits",
"(",
"_INPUT",
",",
"conf",
"[",
"'URL'",
"]",
",",
"*",
"*",
"cdicts",
"(",
"... | 28.5 | 0.001414 |
def cons(collection, value):
"""Extends a collection with a value."""
if isinstance(value, collections.Mapping):
if collection is None:
collection = {}
collection.update(**value)
elif isinstance(value, six.string_types):
if collection is None:
collection = []... | [
"def",
"cons",
"(",
"collection",
",",
"value",
")",
":",
"if",
"isinstance",
"(",
"value",
",",
"collections",
".",
"Mapping",
")",
":",
"if",
"collection",
"is",
"None",
":",
"collection",
"=",
"{",
"}",
"collection",
".",
"update",
"(",
"*",
"*",
... | 26.086957 | 0.001608 |
def get_next_occurrence(self) -> date:
""" Returns the next occurrence date for transaction """
result = get_next_occurrence(self.transaction)
assert isinstance(result, date)
return result | [
"def",
"get_next_occurrence",
"(",
"self",
")",
"->",
"date",
":",
"result",
"=",
"get_next_occurrence",
"(",
"self",
".",
"transaction",
")",
"assert",
"isinstance",
"(",
"result",
",",
"date",
")",
"return",
"result"
] | 43.2 | 0.009091 |
def error(self, *args):
"""Log an error. By default this will also raise an exception."""
if _canShortcutLogging(self.logCategory, ERROR):
return
errorObject(self.logObjectName(), self.logCategory,
*self.logFunction(*args)) | [
"def",
"error",
"(",
"self",
",",
"*",
"args",
")",
":",
"if",
"_canShortcutLogging",
"(",
"self",
".",
"logCategory",
",",
"ERROR",
")",
":",
"return",
"errorObject",
"(",
"self",
".",
"logObjectName",
"(",
")",
",",
"self",
".",
"logCategory",
",",
"... | 44.5 | 0.011029 |
def get_active_lineage():
"""
Query the lineage of the current timer level. Provides only timer names,
not stamp names (as these have not been decided yet!).
Returns:
str: Formatted sequence of timer names in one string.
"""
lin_str = ''
for active_timer in f.timer_stack:
l... | [
"def",
"get_active_lineage",
"(",
")",
":",
"lin_str",
"=",
"''",
"for",
"active_timer",
"in",
"f",
".",
"timer_stack",
":",
"lin_str",
"+=",
"\"{}-->\"",
".",
"format",
"(",
"active_timer",
".",
"name",
")",
"try",
":",
"return",
"lin_str",
"[",
":",
"-... | 28.133333 | 0.002294 |
def check_integrity(sakefile, settings):
"""
Checks the format of the sakefile dictionary
to ensure it conforms to specification
Args:
A dictionary that is the parsed Sakefile (from sake.py)
The setting dictionary (for print functions)
Returns:
True if the Sakefile is confor... | [
"def",
"check_integrity",
"(",
"sakefile",
",",
"settings",
")",
":",
"sprint",
"=",
"settings",
"[",
"\"sprint\"",
"]",
"error",
"=",
"settings",
"[",
"\"error\"",
"]",
"sprint",
"(",
"\"Call to check_integrity issued\"",
",",
"level",
"=",
"\"verbose\"",
")",
... | 39.4 | 0.000495 |
def load_topology(self,topology):
"""
Loads the topology file (e.g. GRO,PDB,INPCRD) as a MDAnalysis Universe,
checks if it can be loaded. Needs to be run before the equivalent function
topol.load_trajectory() and provides the snapshot that is going to be used
for final residue pl... | [
"def",
"load_topology",
"(",
"self",
",",
"topology",
")",
":",
"try",
":",
"self",
".",
"universe",
"=",
"MDAnalysis",
".",
"Universe",
"(",
"topology",
")",
"except",
"ValueError",
":",
"print",
"\"Check your topology file - it is either missing or misspelled.\"",
... | 43.166667 | 0.008816 |
def cdx_clamp(cdx_iter, from_ts, to_ts):
"""
Clamp by start and end ts
"""
if from_ts and len(from_ts) < 14:
from_ts = pad_timestamp(from_ts, PAD_14_DOWN)
if to_ts and len(to_ts) < 14:
to_ts = pad_timestamp(to_ts, PAD_14_UP)
for cdx in cdx_iter:
if from_ts and cdx[TIMES... | [
"def",
"cdx_clamp",
"(",
"cdx_iter",
",",
"from_ts",
",",
"to_ts",
")",
":",
"if",
"from_ts",
"and",
"len",
"(",
"from_ts",
")",
"<",
"14",
":",
"from_ts",
"=",
"pad_timestamp",
"(",
"from_ts",
",",
"PAD_14_DOWN",
")",
"if",
"to_ts",
"and",
"len",
"(",... | 23.666667 | 0.002257 |
def get(self, sys_id=None, limit=100):
"""Returns a list of attachments
:param sys_id: record sys_id to list attachments for
:param limit: override the default limit of 100
:return: list of attachments
"""
if sys_id:
return self.resource.get(query={'table_sy... | [
"def",
"get",
"(",
"self",
",",
"sys_id",
"=",
"None",
",",
"limit",
"=",
"100",
")",
":",
"if",
"sys_id",
":",
"return",
"self",
".",
"resource",
".",
"get",
"(",
"query",
"=",
"{",
"'table_sys_id'",
":",
"sys_id",
",",
"'table_name'",
":",
"self",
... | 37.75 | 0.008621 |
def tplot_save(names, filename=None):
"""
This function will save tplot variables into a single file by using the python "pickle" function.
This file can then be "restored" using tplot_restore. This is useful if you want to end the pytplot session,
but save all of your data/options. All variables and ... | [
"def",
"tplot_save",
"(",
"names",
",",
"filename",
"=",
"None",
")",
":",
"if",
"isinstance",
"(",
"names",
",",
"int",
")",
":",
"names",
"=",
"list",
"(",
"data_quants",
".",
"keys",
"(",
")",
")",
"[",
"names",
"-",
"1",
"]",
"if",
"not",
"is... | 33.684211 | 0.01417 |
def merge(self, other):
"""Merges a set of build file aliases and returns a new set of aliases containing both.
Any duplicate aliases from `other` will trump.
:API: public
:param other: The BuildFileAliases to merge in.
:type other: :class:`BuildFileAliases`
:returns: A new BuildFileAliases c... | [
"def",
"merge",
"(",
"self",
",",
"other",
")",
":",
"if",
"not",
"isinstance",
"(",
"other",
",",
"BuildFileAliases",
")",
":",
"raise",
"TypeError",
"(",
"'Can only merge other BuildFileAliases, given {0}'",
".",
"format",
"(",
"other",
")",
")",
"def",
"mer... | 40 | 0.008418 |
def Reynolds_valve(nu, Q, D1, FL, Fd, C):
r'''Calculates Reynolds number of a control valve for a liquid or gas
flowing through it at a specified Q, for a specified D1, FL, Fd, C, and
with kinematic viscosity `nu` according to IEC 60534 calculations.
.. math::
Re_v = \frac{N_4 F_d Q}{\nu \sqrt{... | [
"def",
"Reynolds_valve",
"(",
"nu",
",",
"Q",
",",
"D1",
",",
"FL",
",",
"Fd",
",",
"C",
")",
":",
"return",
"N4",
"*",
"Fd",
"*",
"Q",
"/",
"nu",
"/",
"(",
"C",
"*",
"FL",
")",
"**",
"0.5",
"*",
"(",
"FL",
"**",
"2",
"*",
"C",
"**",
"2... | 28.902439 | 0.002449 |
def ConnectionUpdate(self, settings):
'''Update settings on a connection.
settings is a String String Variant Map Map. See
https://developer.gnome.org/NetworkManager/0.9/spec.html
#type-String_String_Variant_Map_Map
'''
connection_path = self.connection_path
NM = dbusmock.get_object(MA... | [
"def",
"ConnectionUpdate",
"(",
"self",
",",
"settings",
")",
":",
"connection_path",
"=",
"self",
".",
"connection_path",
"NM",
"=",
"dbusmock",
".",
"get_object",
"(",
"MANAGER_OBJ",
")",
"settings_obj",
"=",
"dbusmock",
".",
"get_object",
"(",
"SETTINGS_OBJ",... | 30.711111 | 0.000701 |
def _find_players(self, boxscore):
"""
Find all players for each team.
Iterate through every player for both teams as found in the boxscore
tables and create a list of instances of the BoxscorePlayer class for
each player. Return lists of player instances comprising the away and... | [
"def",
"_find_players",
"(",
"self",
",",
"boxscore",
")",
":",
"player_dict",
"=",
"{",
"}",
"table_count",
"=",
"0",
"tables",
"=",
"self",
".",
"_find_boxscore_tables",
"(",
"boxscore",
")",
"for",
"table",
"in",
"tables",
":",
"home_or_away",
"=",
"HOM... | 38.162162 | 0.001381 |
def read_data(archive, arc_type, day, stachans, length=86400):
"""
Function to read the appropriate data from an archive for a day.
:type archive: str
:param archive:
The archive source - if arc_type is seishub, this should be a url,
if the arc_type is FDSN then this can be either a url... | [
"def",
"read_data",
"(",
"archive",
",",
"arc_type",
",",
"day",
",",
"stachans",
",",
"length",
"=",
"86400",
")",
":",
"st",
"=",
"[",
"]",
"available_stations",
"=",
"_check_available_data",
"(",
"archive",
",",
"arc_type",
",",
"day",
")",
"for",
"st... | 42.045455 | 0.000211 |
def chain(cmd_list):
"""
Feed output of one command to the next and return final output
Returns string output of chained application of commands.
"""
command = ' | '.join(map(lambda x: ' '.join(x), cmd_list))
chained_proc = functools.reduce(pipe, [None] + cmd_list)
stdout_builder = proc.async_stdout_build... | [
"def",
"chain",
"(",
"cmd_list",
")",
":",
"command",
"=",
"' | '",
".",
"join",
"(",
"map",
"(",
"lambda",
"x",
":",
"' '",
".",
"join",
"(",
"x",
")",
",",
"cmd_list",
")",
")",
"chained_proc",
"=",
"functools",
".",
"reduce",
"(",
"pipe",
",",
... | 32.846154 | 0.015945 |
def prepare_payload(op, method, uri, data):
"""Return the URI (modified perhaps) and body and headers.
- For GET requests, encode parameters in the query string.
- Otherwise always encode parameters in the request body.
- Except op; this can always go in the query string.
:param method: The HTTP... | [
"def",
"prepare_payload",
"(",
"op",
",",
"method",
",",
"uri",
",",
"data",
")",
":",
"query",
"=",
"[",
"]",
"if",
"op",
"is",
"None",
"else",
"[",
"(",
"\"op\"",
",",
"op",
")",
"]",
"def",
"slurp",
"(",
"opener",
")",
":",
"with",
"opener",
... | 35.235294 | 0.000812 |
def delete(self, id):
"""Delete a file.
Parameters:
* id: The Puush ID of the file to delete.
"""
res = self._api_request('del', data={'i': id})[0]
if res[0] == '-1':
raise PuushError("File deletion failed.") | [
"def",
"delete",
"(",
"self",
",",
"id",
")",
":",
"res",
"=",
"self",
".",
"_api_request",
"(",
"'del'",
",",
"data",
"=",
"{",
"'i'",
":",
"id",
"}",
")",
"[",
"0",
"]",
"if",
"res",
"[",
"0",
"]",
"==",
"'-1'",
":",
"raise",
"PuushError",
... | 30.333333 | 0.010676 |
def write(self,output):
"""Writes the data to be output to the device buffer
:param output: data to output
:type output: numpy.ndarray
"""
w = c_int32()
self.WriteAnalogF64(self.npoints, 0, 10.0, DAQmx_Val_GroupByChannel,
output, w, No... | [
"def",
"write",
"(",
"self",
",",
"output",
")",
":",
"w",
"=",
"c_int32",
"(",
")",
"self",
".",
"WriteAnalogF64",
"(",
"self",
".",
"npoints",
",",
"0",
",",
"10.0",
",",
"DAQmx_Val_GroupByChannel",
",",
"output",
",",
"w",
",",
"None",
")"
] | 35.111111 | 0.015432 |
def assert_almost_eq(arr_test, arr_target, thresh=1E-11):
r"""
Args:
arr_test (ndarray or list):
arr_target (ndarray or list):
thresh (scalar or ndarray or list):
"""
if util_arg.NO_ASSERTS:
return
import utool as ut
arr1 = np.array(arr_test)
arr2 = np.array(a... | [
"def",
"assert_almost_eq",
"(",
"arr_test",
",",
"arr_target",
",",
"thresh",
"=",
"1E-11",
")",
":",
"if",
"util_arg",
".",
"NO_ASSERTS",
":",
"return",
"import",
"utool",
"as",
"ut",
"arr1",
"=",
"np",
".",
"array",
"(",
"arr_test",
")",
"arr2",
"=",
... | 33.896552 | 0.000989 |
def show_gene_expression(self, gene, avg=True, axes=None, **kwargs):
"""Display a gene's expressions.
Displays a scatter plot using the SAM projection or another input
projection with a particular gene's expressions overlaid.
Parameters
----------
gene - string
... | [
"def",
"show_gene_expression",
"(",
"self",
",",
"gene",
",",
"avg",
"=",
"True",
",",
"axes",
"=",
"None",
",",
"*",
"*",
"kwargs",
")",
":",
"all_gene_names",
"=",
"np",
".",
"array",
"(",
"list",
"(",
"self",
".",
"adata",
".",
"var_names",
")",
... | 34.927273 | 0.001519 |
def _check_user(self, user):
"""
Checks to make sure that a user is valid. First, checks that the user
is not None. If this check fails, a MissingUserError is raised. Next,
checks if the user has a validation method. If the method does not
exist, the check passes. If the method e... | [
"def",
"_check_user",
"(",
"self",
",",
"user",
")",
":",
"MissingUserError",
".",
"require_condition",
"(",
"user",
"is",
"not",
"None",
",",
"'Could not find the requested user'",
",",
")",
"user_validate_method",
"=",
"getattr",
"(",
"user",
",",
"self",
".",... | 41.190476 | 0.00226 |
def ancestors(self):
"""Returns a list consisting of this workunit and those enclosing it, up to the root.
:API: public
"""
ret = []
workunit = self
while workunit is not None:
ret.append(workunit)
workunit = workunit.parent
return ret | [
"def",
"ancestors",
"(",
"self",
")",
":",
"ret",
"=",
"[",
"]",
"workunit",
"=",
"self",
"while",
"workunit",
"is",
"not",
"None",
":",
"ret",
".",
"append",
"(",
"workunit",
")",
"workunit",
"=",
"workunit",
".",
"parent",
"return",
"ret"
] | 24.181818 | 0.014493 |
def sendline(self, data, linesep=os.linesep):
'''
Send the provided data to the terminal appending a line feed.
'''
return self.send('{0}{1}'.format(data, linesep)) | [
"def",
"sendline",
"(",
"self",
",",
"data",
",",
"linesep",
"=",
"os",
".",
"linesep",
")",
":",
"return",
"self",
".",
"send",
"(",
"'{0}{1}'",
".",
"format",
"(",
"data",
",",
"linesep",
")",
")"
] | 38.4 | 0.010204 |
def update(self, other=None, **kwargs):
"""D.update([other, ]**kwargs) -> None.
Update D From dict/iterable ``other`` and ``kwargs``.
If ``other`` present and has a .keys() method, does:
for k in other: D[k] = other[k]
If ``other`` present and lacks .keys() method, does:
... | [
"def",
"update",
"(",
"self",
",",
"other",
"=",
"None",
",",
"*",
"*",
"kwargs",
")",
":",
"logger",
".",
"debug",
"(",
"'call update %s'",
",",
"other",
")",
"if",
"other",
":",
"if",
"hasattr",
"(",
"other",
",",
"'keys'",
")",
":",
"for",
"key"... | 34.764706 | 0.001646 |
def exec_start(self, exec_id, detach=False, tty=False, stream=False,
socket=False, demux=False):
"""
Start a previously set up exec instance.
Args:
exec_id (str): ID of the exec instance
detach (bool): If true, detach from the exec command.
... | [
"def",
"exec_start",
"(",
"self",
",",
"exec_id",
",",
"detach",
"=",
"False",
",",
"tty",
"=",
"False",
",",
"stream",
"=",
"False",
",",
"socket",
"=",
"False",
",",
"demux",
"=",
"False",
")",
":",
"# we want opened socket if socket == True",
"data",
"=... | 33.5 | 0.00174 |
def attach_video(self, video: String, caption: String = None, width: Integer = None,
height: Integer = None, duration: Integer = None):
"""
Attach video
:param video:
:param caption:
:param width:
:param height:
:param duration:
:retu... | [
"def",
"attach_video",
"(",
"self",
",",
"video",
":",
"String",
",",
"caption",
":",
"String",
"=",
"None",
",",
"width",
":",
"Integer",
"=",
"None",
",",
"height",
":",
"Integer",
"=",
"None",
",",
"duration",
":",
"Integer",
"=",
"None",
")",
":"... | 31.571429 | 0.010989 |
def batch_map_mean(func, batch_iter, progress_iter_func=None, sum_axis=None,
n_batches=None, prepend_args=None):
"""
Apply a function to all the samples that are accessed as mini-batches
obtained from an iterator.
Returns the across-samples mean of the results returned by `func`
... | [
"def",
"batch_map_mean",
"(",
"func",
",",
"batch_iter",
",",
"progress_iter_func",
"=",
"None",
",",
"sum_axis",
"=",
"None",
",",
"n_batches",
"=",
"None",
",",
"prepend_args",
"=",
"None",
")",
":",
"# Accumulator for results and number of samples",
"results_accu... | 44.151685 | 0.000124 |
def _point_scalar(self, name=None):
"""
Returns point scalars of a vtk object
Parameters
----------
name : str
Name of point scalars to retrive.
Returns
-------
scalars : np.ndarray
Numpy array of scalars
"""
if n... | [
"def",
"_point_scalar",
"(",
"self",
",",
"name",
"=",
"None",
")",
":",
"if",
"name",
"is",
"None",
":",
"# use active scalar array",
"field",
",",
"name",
"=",
"self",
".",
"active_scalar_info",
"if",
"field",
"!=",
"POINT_DATA_FIELD",
":",
"raise",
"Runti... | 32.323529 | 0.001767 |
def get_properties_of_kind(kind, start=None, end=None):
"""Return all properties of kind in the specified range.
NOTE: This function does not return unindexed properties.
Args:
kind: name of kind whose properties you want.
start: only return properties >= start if start is not None.
end: only return... | [
"def",
"get_properties_of_kind",
"(",
"kind",
",",
"start",
"=",
"None",
",",
"end",
"=",
"None",
")",
":",
"q",
"=",
"Property",
".",
"query",
"(",
"ancestor",
"=",
"Property",
".",
"key_for_kind",
"(",
"kind",
")",
")",
"if",
"start",
"is",
"not",
... | 35.173913 | 0.008424 |
def add_haproxy_checks(nrpe, unit_name):
"""
Add checks for each service in list
:param NRPE nrpe: NRPE object to add check to
:param str unit_name: Unit name to use in check description
"""
nrpe.add_check(
shortname='haproxy_servers',
description='Check HAProxy {%s}' % unit_nam... | [
"def",
"add_haproxy_checks",
"(",
"nrpe",
",",
"unit_name",
")",
":",
"nrpe",
".",
"add_check",
"(",
"shortname",
"=",
"'haproxy_servers'",
",",
"description",
"=",
"'Check HAProxy {%s}'",
"%",
"unit_name",
",",
"check_cmd",
"=",
"'check_haproxy.sh'",
")",
"nrpe",... | 34.466667 | 0.001883 |
def get_transport_target(cls, instance, timeout, retries):
'''
Generate a Transport target object based on the instance's configuration
'''
if "ip_address" not in instance:
raise Exception("An IP address needs to be specified")
ip_address = instance["ip_address"]
... | [
"def",
"get_transport_target",
"(",
"cls",
",",
"instance",
",",
"timeout",
",",
"retries",
")",
":",
"if",
"\"ip_address\"",
"not",
"in",
"instance",
":",
"raise",
"Exception",
"(",
"\"An IP address needs to be specified\"",
")",
"ip_address",
"=",
"instance",
"[... | 52 | 0.008403 |
def searchInAleph(base, phrase, considerSimilar, field):
"""
Send request to the aleph search engine.
Request itself is pretty useless, but it can be later used as parameter
for :func:`getDocumentIDs`, which can fetch records from Aleph.
Args:
base (str): which database you want to use
... | [
"def",
"searchInAleph",
"(",
"base",
",",
"phrase",
",",
"considerSimilar",
",",
"field",
")",
":",
"downer",
"=",
"Downloader",
"(",
")",
"if",
"field",
".",
"lower",
"(",
")",
"not",
"in",
"VALID_ALEPH_FIELDS",
":",
"raise",
"InvalidAlephFieldException",
"... | 32.684932 | 0.000407 |
def set_deserializer_by_mime_type(self, mime_type):
"""
:param mime_type:
:return:
Used by content_type_set to set get a reference to the serializer object
"""
for deserializer in self._deserializers:
if deserializer.content_type() == mime_type:
... | [
"def",
"set_deserializer_by_mime_type",
"(",
"self",
",",
"mime_type",
")",
":",
"for",
"deserializer",
"in",
"self",
".",
"_deserializers",
":",
"if",
"deserializer",
".",
"content_type",
"(",
")",
"==",
"mime_type",
":",
"self",
".",
"_selected_deserializer",
... | 33.642857 | 0.008264 |
def overview(index, start, end):
"""Compute metrics in the overview section for enriched github issues
indexes.
Returns a dictionary. Each key in the dictionary is the name of
a metric, the value is the value of that metric. Value can be
a complex object (eg, a time series).
:param index: index... | [
"def",
"overview",
"(",
"index",
",",
"start",
",",
"end",
")",
":",
"results",
"=",
"{",
"\"activity_metrics\"",
":",
"[",
"OpenedIssues",
"(",
"index",
",",
"start",
",",
"end",
")",
",",
"ClosedIssues",
"(",
"index",
",",
"start",
",",
"end",
")",
... | 35.391304 | 0.001196 |
def correlation_matvec(P, obs1, obs2=None, times=[1]):
r"""Time-correlation for equilibrium experiment - via matrix vector products.
Parameters
----------
P : (M, M) ndarray
Transition matrix
obs1 : (M,) ndarray
Observable, represented as vector on state space
obs2 : (M,) ndarra... | [
"def",
"correlation_matvec",
"(",
"P",
",",
"obs1",
",",
"obs2",
"=",
"None",
",",
"times",
"=",
"[",
"1",
"]",
")",
":",
"if",
"obs2",
"is",
"None",
":",
"obs2",
"=",
"obs1",
"\"\"\"Compute stationary vector\"\"\"",
"mu",
"=",
"statdist",
"(",
"P",
")... | 25.596154 | 0.001447 |
def t_CHAR(self, t):
r"'.'" # A single char
t.value = ord(t.value[1])
t.type = 'INTEGER'
return t | [
"def",
"t_CHAR",
"(",
"self",
",",
"t",
")",
":",
"# A single char",
"t",
".",
"value",
"=",
"ord",
"(",
"t",
".",
"value",
"[",
"1",
"]",
")",
"t",
".",
"type",
"=",
"'INTEGER'",
"return",
"t"
] | 21 | 0.015267 |
def check_entry(self, entries, *args, **kwargs):
"""
With a list of entries, check each entry against every other
"""
verbosity = kwargs.get('verbosity', 1)
user_total_overlaps = 0
user = ''
for index_a, entry_a in enumerate(entries):
# Show the name t... | [
"def",
"check_entry",
"(",
"self",
",",
"entries",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"verbosity",
"=",
"kwargs",
".",
"get",
"(",
"'verbosity'",
",",
"1",
")",
"user_total_overlaps",
"=",
"0",
"user",
"=",
"''",
"for",
"index_a",
"... | 43.777778 | 0.001656 |
def clear( self ):
"""
Clears the current settings for the current action.
"""
item = self.uiActionTREE.currentItem()
if ( not item ):
return
self.uiShortcutTXT.setText('')
item.setText(1, '') | [
"def",
"clear",
"(",
"self",
")",
":",
"item",
"=",
"self",
".",
"uiActionTREE",
".",
"currentItem",
"(",
")",
"if",
"(",
"not",
"item",
")",
":",
"return",
"self",
".",
"uiShortcutTXT",
".",
"setText",
"(",
"''",
")",
"item",
".",
"setText",
"(",
... | 26 | 0.026022 |
def _execCommand(Argv, collect_missing):
r"""Worker of execCommand.
"""
if not Argv:
raise HandledException('Please specify a command!')
RouteParts = Argv[0].split('/')
Args, KwArgs = getDigestableArgs(Argv[1:])
ResolvedMember = getDescendant(BaseGroup, RouteParts[:])
if isinstance(Resol... | [
"def",
"_execCommand",
"(",
"Argv",
",",
"collect_missing",
")",
":",
"if",
"not",
"Argv",
":",
"raise",
"HandledException",
"(",
"'Please specify a command!'",
")",
"RouteParts",
"=",
"Argv",
"[",
"0",
"]",
".",
"split",
"(",
"'/'",
")",
"Args",
",",
"KwA... | 34.777778 | 0.015552 |
def draw_math(str, x, y, alpha=1.0):
""" Uses mimetex to generate a GIF-image from the LaTeX equation.
"""
try: from web import _ctx
except: pass
str = re.sub("</{0,1}math>", "", str.strip())
img = mimetex.gif(str)
w, h = _ctx.imagesize(img)
_ctx.image(img, x, y, alpha=alp... | [
"def",
"draw_math",
"(",
"str",
",",
"x",
",",
"y",
",",
"alpha",
"=",
"1.0",
")",
":",
"try",
":",
"from",
"web",
"import",
"_ctx",
"except",
":",
"pass",
"str",
"=",
"re",
".",
"sub",
"(",
"\"</{0,1}math>\"",
",",
"\"\"",
",",
"str",
".",
"stri... | 25.153846 | 0.020649 |
def parse(self):
"""
Parse file specified by constructor.
"""
f = open(self.parse_log_path, "r")
self.parse2(f)
f.close() | [
"def",
"parse",
"(",
"self",
")",
":",
"f",
"=",
"open",
"(",
"self",
".",
"parse_log_path",
",",
"\"r\"",
")",
"self",
".",
"parse2",
"(",
"f",
")",
"f",
".",
"close",
"(",
")"
] | 23.285714 | 0.011834 |
def handle_get_reseller(self, req):
"""Handles the GET v2 call for getting general reseller information
(currently just a list of accounts). Can only be called by a
.reseller_admin.
On success, a JSON dictionary will be returned with a single `accounts`
key whose value is list o... | [
"def",
"handle_get_reseller",
"(",
"self",
",",
"req",
")",
":",
"if",
"not",
"self",
".",
"is_reseller_admin",
"(",
"req",
")",
":",
"return",
"self",
".",
"denied_response",
"(",
"req",
")",
"listing",
"=",
"[",
"]",
"marker",
"=",
"''",
"while",
"Tr... | 45.891892 | 0.001153 |
def load_ext(self):
"""Read time series data like method |IOSequence.load_ext| of class
|IOSequence|, but with special handling of missing data.
When reading incomplete time series data, *HydPy* usually raises
a |RuntimeError| to prevent from performing erroneous calculations.
F... | [
"def",
"load_ext",
"(",
"self",
")",
":",
"try",
":",
"super",
"(",
")",
".",
"load_ext",
"(",
")",
"except",
"OSError",
":",
"del",
"self",
".",
"memoryflag",
"if",
"hydpy",
".",
"pub",
".",
"options",
".",
"warnmissingobsfile",
":",
"warnings",
".",
... | 40.405941 | 0.000478 |
def drawBackground( self, painter, opt, rect, brush ):
"""
Make sure the background extends to 0 for the first item.
:param painter | <QtGui.QPainter>
rect | <QtCore.QRect>
brush | <QtGui.QBrush>
"""
if not brush:... | [
"def",
"drawBackground",
"(",
"self",
",",
"painter",
",",
"opt",
",",
"rect",
",",
"brush",
")",
":",
"if",
"not",
"brush",
":",
"return",
"painter",
".",
"setPen",
"(",
"QtCore",
".",
"Qt",
".",
"NoPen",
")",
"painter",
".",
"setBrush",
"(",
"brush... | 31.642857 | 0.013158 |
def unroll_option_legs(cls, client, option_orders):
'''
unroll option orders like this,
https://github.com/joshfraser/robinhood-to-csv/blob/master/csv-options-export.py
'''
#
# @TODO write this with python threats to make concurrent HTTP requests
#
resul... | [
"def",
"unroll_option_legs",
"(",
"cls",
",",
"client",
",",
"option_orders",
")",
":",
"#",
"# @TODO write this with python threats to make concurrent HTTP requests",
"#",
"results",
"=",
"[",
"]",
"for",
"oo",
"in",
"option_orders",
":",
"for",
"index",
",",
"leg"... | 38.627907 | 0.001174 |
def __diff(self, level, parents_ids=frozenset({})):
"""The main diff method"""
if level.t1 is level.t2:
return
if self.__skip_this(level):
return
if get_type(level.t1) != get_type(level.t2):
report_type_change = True
for type_group in sel... | [
"def",
"__diff",
"(",
"self",
",",
"level",
",",
"parents_ids",
"=",
"frozenset",
"(",
"{",
"}",
")",
")",
":",
"if",
"level",
".",
"t1",
"is",
"level",
".",
"t2",
":",
"return",
"if",
"self",
".",
"__skip_this",
"(",
"level",
")",
":",
"return",
... | 32 | 0.002219 |
def ksum(p, K=2):
"""From
T. Ogita, S.M. Rump, and S. Oishi.
Accurate Sum and Dot Product,
SIAM J. Sci. Comput., 26(6), 1955–1988 (34 pages).
<https://doi.org/10.1137/030601818>.
Algorithm 4.8. Summation as in K-fold precision by (K−1)-fold error-free
vector transformation.
"""
# D... | [
"def",
"ksum",
"(",
"p",
",",
"K",
"=",
"2",
")",
":",
"# Don't override the input data.",
"q",
"=",
"p",
".",
"copy",
"(",
")",
"distill",
"(",
"q",
",",
"K",
"-",
"1",
")",
"return",
"numpy",
".",
"sum",
"(",
"q",
"[",
":",
"-",
"1",
"]",
"... | 27.933333 | 0.002309 |
def _check_deprecated(self, dest, kwargs):
"""Checks option for deprecation and issues a warning/error if necessary."""
removal_version = kwargs.get('removal_version', None)
if removal_version is not None:
warn_or_error(
removal_version=removal_version,
deprecated_entity_description="o... | [
"def",
"_check_deprecated",
"(",
"self",
",",
"dest",
",",
"kwargs",
")",
":",
"removal_version",
"=",
"kwargs",
".",
"get",
"(",
"'removal_version'",
",",
"None",
")",
"if",
"removal_version",
"is",
"not",
"None",
":",
"warn_or_error",
"(",
"removal_version",... | 51.4 | 0.00956 |
def indentation_pre_event_input_accelerators(editor, event):
"""
Implements indentation pre event input accelerators.
:param editor: Document editor.
:type editor: QWidget
:param event: Event being handled.
:type event: QEvent
:return: Process event.
:rtype: bool
"""
process_ev... | [
"def",
"indentation_pre_event_input_accelerators",
"(",
"editor",
",",
"event",
")",
":",
"process_event",
"=",
"True",
"if",
"not",
"hasattr",
"(",
"editor",
",",
"\"indent\"",
")",
":",
"return",
"process_event",
"if",
"event",
".",
"key",
"(",
")",
"==",
... | 27.571429 | 0.001669 |
def _print_SCALAR_TYPES(self, expr, *args, **kwargs):
"""Render scalars"""
adjoint = kwargs.get('adjoint', False)
if adjoint:
expr = expr.conjugate()
if isinstance(expr, SympyBasic):
self._sympy_printer._print_level = self._print_level + 1
res = self._... | [
"def",
"_print_SCALAR_TYPES",
"(",
"self",
",",
"expr",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"adjoint",
"=",
"kwargs",
".",
"get",
"(",
"'adjoint'",
",",
"False",
")",
"if",
"adjoint",
":",
"expr",
"=",
"expr",
".",
"conjugate",
"(",
... | 41.434783 | 0.002051 |
def _do_validate_resourcescenario(resourcescenario, template_id=None):
"""
Perform a check to ensure a resource scenario's datasets are correct given what the
definition of that resource (its type) specifies.
"""
res = resourcescenario.resourceattr.get_resource()
types = res.types
... | [
"def",
"_do_validate_resourcescenario",
"(",
"resourcescenario",
",",
"template_id",
"=",
"None",
")",
":",
"res",
"=",
"resourcescenario",
".",
"resourceattr",
".",
"get_resource",
"(",
")",
"types",
"=",
"res",
".",
"types",
"dataset",
"=",
"resourcescenario",
... | 44.216216 | 0.008373 |
def grid_to_eccentric_radii(self, grid):
"""Convert a grid of (y,x) coordinates to an eccentric radius, which is (1.0/axis_ratio) * elliptical radius \
and used to define light profile half-light radii using circular radii.
If the coordinates have not been transformed to the profile's geometry,... | [
"def",
"grid_to_eccentric_radii",
"(",
"self",
",",
"grid",
")",
":",
"return",
"np",
".",
"multiply",
"(",
"np",
".",
"sqrt",
"(",
"self",
".",
"axis_ratio",
")",
",",
"self",
".",
"grid_to_elliptical_radii",
"(",
"grid",
")",
")",
".",
"view",
"(",
"... | 52.083333 | 0.009434 |
def construct_exc_class(cls):
"""Constructs proxy class for the exception."""
class ProxyException(cls, BaseException):
__pep3134__ = True
@property
def __traceback__(self):
if self.__fixed_traceback__:
return self.__fixed_traceback__
current_ex... | [
"def",
"construct_exc_class",
"(",
"cls",
")",
":",
"class",
"ProxyException",
"(",
"cls",
",",
"BaseException",
")",
":",
"__pep3134__",
"=",
"True",
"@",
"property",
"def",
"__traceback__",
"(",
"self",
")",
":",
"if",
"self",
".",
"__fixed_traceback__",
"... | 29.222222 | 0.00092 |
def is_subdir(base_path, test_path, trailing_slash=False, wildcards=False):
'''Return whether the a path is a subpath of another.
Args:
base_path: The base path
test_path: The path which we are testing
trailing_slash: If True, the trailing slash is treated with importance.
F... | [
"def",
"is_subdir",
"(",
"base_path",
",",
"test_path",
",",
"trailing_slash",
"=",
"False",
",",
"wildcards",
"=",
"False",
")",
":",
"if",
"trailing_slash",
":",
"base_path",
"=",
"base_path",
".",
"rsplit",
"(",
"'/'",
",",
"1",
")",
"[",
"0",
"]",
... | 34.8 | 0.001119 |
def _get_dopants(substitutions, num_dopants, match_oxi_sign):
"""
Utility method to get n- and p-type dopants from a list of substitutions.
"""
n_type = [pred for pred in substitutions
if pred['dopant_species'].oxi_state >
pred['original_species'].oxi_state
and ... | [
"def",
"_get_dopants",
"(",
"substitutions",
",",
"num_dopants",
",",
"match_oxi_sign",
")",
":",
"n_type",
"=",
"[",
"pred",
"for",
"pred",
"in",
"substitutions",
"if",
"pred",
"[",
"'dopant_species'",
"]",
".",
"oxi_state",
">",
"pred",
"[",
"'original_speci... | 47.055556 | 0.001157 |
def scrypt_mcf_check(mcf, password):
"""Returns True if the password matches the given MCF hash"""
if isinstance(password, unicode):
password = password.encode('utf8')
elif not isinstance(password, bytes):
raise TypeError('password must be a unicode or byte string')
if not isinstance(mcf... | [
"def",
"scrypt_mcf_check",
"(",
"mcf",
",",
"password",
")",
":",
"if",
"isinstance",
"(",
"password",
",",
"unicode",
")",
":",
"password",
"=",
"password",
".",
"encode",
"(",
"'utf8'",
")",
"elif",
"not",
"isinstance",
"(",
"password",
",",
"bytes",
"... | 51.181818 | 0.001745 |
def get_messages(self, count=1, block=True, timeout=10):
"""
Fetch the specified number of messages
Keyword Arguments:
count: Indicates the maximum number of messages to be fetched
block: If True, the API will block till all messages are fetched.
If block... | [
"def",
"get_messages",
"(",
"self",
",",
"count",
"=",
"1",
",",
"block",
"=",
"True",
",",
"timeout",
"=",
"10",
")",
":",
"messages",
"=",
"[",
"]",
"# Give a size hint to the consumers. Each consumer process will fetch",
"# a maximum of \"count\" messages. This will ... | 39.241379 | 0.000857 |
def accept_all(self):
'''
Accept all keys in pre
'''
keys = self.list_keys()
for key in keys[self.PEND]:
try:
shutil.move(
os.path.join(
self.opts['pki_dir'],
self.PEND,
... | [
"def",
"accept_all",
"(",
"self",
")",
":",
"keys",
"=",
"self",
".",
"list_keys",
"(",
")",
"for",
"key",
"in",
"keys",
"[",
"self",
".",
"PEND",
"]",
":",
"try",
":",
"shutil",
".",
"move",
"(",
"os",
".",
"path",
".",
"join",
"(",
"self",
".... | 33.8 | 0.002301 |
def merge(x, y):
"""
Merge two dictionaries and raise an error for inconsistencies.
Parameters
----------
x : dict
dictionary x
y : dict
dictionary y
Returns
-------
x : dict
merged dictionary
Raises
------
ValueError
if `x` and `y` are ... | [
"def",
"merge",
"(",
"x",
",",
"y",
")",
":",
"keys_x",
"=",
"set",
"(",
"x",
")",
"keys_y",
"=",
"set",
"(",
"y",
")",
"for",
"key",
"in",
"keys_y",
"-",
"keys_x",
":",
"x",
"[",
"key",
"]",
"=",
"y",
"[",
"key",
"]",
"for",
"key",
"in",
... | 18.236842 | 0.00137 |
def find_state(self, state, best_match=True, min_similarity=70):
"""
Fuzzy search correct state.
:param best_match: bool, when True, only the best matched state
will be return. otherwise, will return all matching states.
"""
result_state_short_list = list()
... | [
"def",
"find_state",
"(",
"self",
",",
"state",
",",
"best_match",
"=",
"True",
",",
"min_similarity",
"=",
"70",
")",
":",
"result_state_short_list",
"=",
"list",
"(",
")",
"# check if it is a abbreviate name",
"if",
"state",
".",
"upper",
"(",
")",
"in",
"... | 41.40625 | 0.001475 |
def GetDirections(self, origin, destination, sensor = False, mode = None, waypoints = None, alternatives = None, avoid = None, language = None, units = None,
region = None, departure_time = None, arrival_time = None):
'''Get Directions Service
Pls refer to the Google Maps Web ... | [
"def",
"GetDirections",
"(",
"self",
",",
"origin",
",",
"destination",
",",
"sensor",
"=",
"False",
",",
"mode",
"=",
"None",
",",
"waypoints",
"=",
"None",
",",
"alternatives",
"=",
"None",
",",
"avoid",
"=",
"None",
",",
"language",
"=",
"None",
","... | 28.914894 | 0.030605 |
def from_structure(cls, structure, ff_elements=None, atom_style="charge"):
"""
Simple constructor building LammpsData from a structure without
force field parameters and topologies.
Args:
structure (Structure): Input structure.
ff_elements ([str]): List of string... | [
"def",
"from_structure",
"(",
"cls",
",",
"structure",
",",
"ff_elements",
"=",
"None",
",",
"atom_style",
"=",
"\"charge\"",
")",
":",
"s",
"=",
"structure",
".",
"get_sorted_structure",
"(",
")",
"box",
",",
"symmop",
"=",
"lattice_2_lmpbox",
"(",
"s",
"... | 46.472222 | 0.001171 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.