text stringlengths 89 104k | code_tokens list | avg_line_len float64 7.91 980 | score float64 0 630 |
|---|---|---|---|
def normalized_energy_at_conditions(self, pH, V):
"""
Energy at an electrochemical condition, compatible with
numpy arrays for pH/V input
Args:
pH (float): pH at condition
V (float): applied potential at condition
Returns:
energy normalized b... | [
"def",
"normalized_energy_at_conditions",
"(",
"self",
",",
"pH",
",",
"V",
")",
":",
"return",
"self",
".",
"energy_at_conditions",
"(",
"pH",
",",
"V",
")",
"*",
"self",
".",
"normalization_factor"
] | 33.384615 | 18.923077 |
def to_md_file(string, filename, out_path="."):
"""Import a module path and create an api doc from it
Args:
string (str): string with line breaks to write to file.
filename (str): filename without the .md
out_path (str): The output directory
"""
md_file = "%s.md" % filename
... | [
"def",
"to_md_file",
"(",
"string",
",",
"filename",
",",
"out_path",
"=",
"\".\"",
")",
":",
"md_file",
"=",
"\"%s.md\"",
"%",
"filename",
"with",
"open",
"(",
"os",
".",
"path",
".",
"join",
"(",
"out_path",
",",
"md_file",
")",
",",
"\"w\"",
")",
... | 35.416667 | 13.083333 |
def to_xdr_object(self):
"""Creates an XDR Operation object that represents this
:class:`ManageData`.
"""
data_name = bytearray(self.data_name, encoding='utf-8')
if self.data_value is not None:
if isinstance(self.data_value, bytes):
data_value = [byt... | [
"def",
"to_xdr_object",
"(",
"self",
")",
":",
"data_name",
"=",
"bytearray",
"(",
"self",
".",
"data_name",
",",
"encoding",
"=",
"'utf-8'",
")",
"if",
"self",
".",
"data_value",
"is",
"not",
"None",
":",
"if",
"isinstance",
"(",
"self",
".",
"data_valu... | 37.5 | 16.944444 |
def register_uri_backend(uri_scheme, create_method, module, c14n_uri_method, escape, cast, is_connected):
"""
This method is intended to be used by backends only.
It lets them register their services, identified by the URI scheme,
at import time. The associated method create_method must take one
pa... | [
"def",
"register_uri_backend",
"(",
"uri_scheme",
",",
"create_method",
",",
"module",
",",
"c14n_uri_method",
",",
"escape",
",",
"cast",
",",
"is_connected",
")",
":",
"try",
":",
"delta_api",
"=",
"__compare_api_level",
"(",
"module",
".",
"apilevel",
",",
... | 57.444444 | 30.422222 |
def parse_ACCT(chunk, encryption_key):
"""
Parses an account chunk, decrypts and creates an Account object.
May return nil when the chunk does not represent an account.
All secure notes are ACCTs but not all of them strore account
information.
"""
# TODO: Make a test case that covers secure ... | [
"def",
"parse_ACCT",
"(",
"chunk",
",",
"encryption_key",
")",
":",
"# TODO: Make a test case that covers secure note account",
"io",
"=",
"BytesIO",
"(",
"chunk",
".",
"payload",
")",
"id",
"=",
"read_item",
"(",
"io",
")",
"name",
"=",
"decode_aes256_plain_auto",
... | 38.645161 | 19.935484 |
def write_autoconf(self, filename,
header="/* Generated by Kconfiglib (https://github.com/ulfalizer/Kconfiglib) */\n"):
r"""
Writes out symbol values as a C header file, matching the format used
by include/generated/autoconf.h in the kernel.
The ordering of the #d... | [
"def",
"write_autoconf",
"(",
"self",
",",
"filename",
",",
"header",
"=",
"\"/* Generated by Kconfiglib (https://github.com/ulfalizer/Kconfiglib) */\\n\"",
")",
":",
"with",
"self",
".",
"_open",
"(",
"filename",
",",
"\"w\"",
")",
"as",
"f",
":",
"f",
".",
"writ... | 46.066667 | 22.933333 |
def get_remote_evb_mode(self, tlv_data):
"""Returns the EVB mode in the TLV. """
ret, parsed_val = self._check_common_tlv_format(
tlv_data, "mode:", "EVB Configuration TLV")
if not ret:
return None
mode_val = parsed_val[1].split()[0].strip()
return mode_va... | [
"def",
"get_remote_evb_mode",
"(",
"self",
",",
"tlv_data",
")",
":",
"ret",
",",
"parsed_val",
"=",
"self",
".",
"_check_common_tlv_format",
"(",
"tlv_data",
",",
"\"mode:\"",
",",
"\"EVB Configuration TLV\"",
")",
"if",
"not",
"ret",
":",
"return",
"None",
"... | 39.25 | 12.125 |
def _imm_trans_setattr(self, name, value):
'''
An immutable's transient setattr allows params to be set, and runs checks as they are.
'''
params = _imm_param_data(self)
dd = object.__getattribute__(self, '__dict__')
if name in params:
(_, tx_fn, arg_lists, check_fns, deps) = params[name]... | [
"def",
"_imm_trans_setattr",
"(",
"self",
",",
"name",
",",
"value",
")",
":",
"params",
"=",
"_imm_param_data",
"(",
"self",
")",
"dd",
"=",
"object",
".",
"__getattribute__",
"(",
"self",
",",
"'__dict__'",
")",
"if",
"name",
"in",
"params",
":",
"(",
... | 45.305556 | 22.916667 |
def add_selector(name):
"""
Builds and registers a :class:`Selector` object with the given name and configuration.
Args:
name (str): The name of the selector.
Yields:
SelectorFactory: The factory that will build the :class:`Selector`.
"""
factory = SelectorFactory(name)
yi... | [
"def",
"add_selector",
"(",
"name",
")",
":",
"factory",
"=",
"SelectorFactory",
"(",
"name",
")",
"yield",
"factory",
"selectors",
"[",
"name",
"]",
"=",
"factory",
".",
"build_selector",
"(",
")"
] | 26.071429 | 22.928571 |
def exists(self):
"""
:return: True if the submodule exists, False otherwise. Please note that
a submodule may exist (in the .gitmodules file) even though its module
doesn't exist on disk"""
# keep attributes for later, and restore them if we have no valid data
# ... | [
"def",
"exists",
"(",
"self",
")",
":",
"# keep attributes for later, and restore them if we have no valid data",
"# this way we do not actually alter the state of the object",
"loc",
"=",
"locals",
"(",
")",
"for",
"attr",
"in",
"self",
".",
"_cache_attrs",
":",
"try",
":"... | 37.433333 | 18.2 |
def detect_r_peaks(ecg_signal, sample_rate, time_units=False, volts=False, resolution=None,
device="biosignalsplux", plot_result=False):
"""
-----
Brief
-----
Python implementation of R peak detection algorithm (proposed by Raja Selvaraj).
-----------
Description
----... | [
"def",
"detect_r_peaks",
"(",
"ecg_signal",
",",
"sample_rate",
",",
"time_units",
"=",
"False",
",",
"volts",
"=",
"False",
",",
"resolution",
"=",
"None",
",",
"device",
"=",
"\"biosignalsplux\"",
",",
"plot_result",
"=",
"False",
")",
":",
"if",
"volts",
... | 37.975 | 28.375 |
def ms_zoom(self, viewer, event, data_x, data_y, msg=True):
"""Zoom the image by dragging the cursor left or right.
"""
if not self.canzoom:
return True
msg = self.settings.get('msg_zoom', msg)
x, y = self.get_win_xy(viewer)
if event.state == 'move':
... | [
"def",
"ms_zoom",
"(",
"self",
",",
"viewer",
",",
"event",
",",
"data_x",
",",
"data_y",
",",
"msg",
"=",
"True",
")",
":",
"if",
"not",
"self",
".",
"canzoom",
":",
"return",
"True",
"msg",
"=",
"self",
".",
"settings",
".",
"get",
"(",
"'msg_zoo... | 30 | 16.285714 |
def _queue_management_worker(executor_reference,
processes,
pending_work_items,
work_ids_queue,
call_queue,
result_queue):
"""Manages the communication between this proces... | [
"def",
"_queue_management_worker",
"(",
"executor_reference",
",",
"processes",
",",
"pending_work_items",
",",
"work_ids_queue",
",",
"call_queue",
",",
"result_queue",
")",
":",
"nb_shutdown_processes",
"=",
"[",
"0",
"]",
"def",
"shutdown_one_process",
"(",
")",
... | 45.769231 | 17.830769 |
def enrich(self,
studyAreas,
dataCollections=None,
analysisVariables=None,
addDerivativeVariables="all",
studyAreasOptions=None,
useData=None,
intersectingGeographies=None,
returnGeometry=False,
... | [
"def",
"enrich",
"(",
"self",
",",
"studyAreas",
",",
"dataCollections",
"=",
"None",
",",
"analysisVariables",
"=",
"None",
",",
"addDerivativeVariables",
"=",
"\"all\"",
",",
"studyAreasOptions",
"=",
"None",
",",
"useData",
"=",
"None",
",",
"intersectingGeog... | 55.064516 | 22.467742 |
def convert_schema(self, nuc_tuple, inner_sat_tuples, outer_sat_tuples):
"""subtrees are represented as (tree, linear tree position) tuples.
returns relation as root node.
"""
nuc_tree, nuc_pos = nuc_tuple
sat_tuples = inner_sat_tuples + outer_sat_tuples
last_sat_tuple_p... | [
"def",
"convert_schema",
"(",
"self",
",",
"nuc_tuple",
",",
"inner_sat_tuples",
",",
"outer_sat_tuples",
")",
":",
"nuc_tree",
",",
"nuc_pos",
"=",
"nuc_tuple",
"sat_tuples",
"=",
"inner_sat_tuples",
"+",
"outer_sat_tuples",
"last_sat_tuple_pos",
"=",
"len",
"(",
... | 42.142857 | 20.52381 |
def _run():
"""Entry point for package and cli uses"""
args = parse_args()
# parse custom parameters
custom_meta = None
if args.custom_meta:
print "Adding custom parameters:"
custom_meta = {}
try:
for item in args.custom_meta.split(','):
key, val... | [
"def",
"_run",
"(",
")",
":",
"args",
"=",
"parse_args",
"(",
")",
"# parse custom parameters",
"custom_meta",
"=",
"None",
"if",
"args",
".",
"custom_meta",
":",
"print",
"\"Adding custom parameters:\"",
"custom_meta",
"=",
"{",
"}",
"try",
":",
"for",
"item"... | 39.454545 | 19.863636 |
def convert_tree_to_newick(tree,
otu_group,
label_key,
leaf_labels,
needs_quotes_pattern=NEWICK_NEEDING_QUOTING,
subtree_id=None,
bracket_ingroup=False):
... | [
"def",
"convert_tree_to_newick",
"(",
"tree",
",",
"otu_group",
",",
"label_key",
",",
"leaf_labels",
",",
"needs_quotes_pattern",
"=",
"NEWICK_NEEDING_QUOTING",
",",
"subtree_id",
"=",
"None",
",",
"bracket_ingroup",
"=",
"False",
")",
":",
"assert",
"(",
"not",
... | 43.7 | 13.975 |
def closest(self, coords=[], **kwargs):
"""Snaps coordinate(s) to closest coordinate in Dataset
Args:
coords: List of coordinates expressed as tuples
**kwargs: Coordinates defined as keyword pairs
Returns:
List of tuples of the snapped coordinates
R... | [
"def",
"closest",
"(",
"self",
",",
"coords",
"=",
"[",
"]",
",",
"*",
"*",
"kwargs",
")",
":",
"if",
"self",
".",
"ndims",
">",
"1",
":",
"raise",
"NotImplementedError",
"(",
"\"Closest method currently only \"",
"\"implemented for 1D Elements\"",
")",
"if",
... | 38.586207 | 21.689655 |
def do_chunked_gzip(infh, outfh, filename):
"""
A memory-friendly way of compressing the data.
"""
import gzip
gzfh = gzip.GzipFile('rawlogs', mode='wb', fileobj=outfh)
if infh.closed:
infh = open(infh.name, 'r')
else:
infh.seek(0)
readsize = 0
sys.stdout.w... | [
"def",
"do_chunked_gzip",
"(",
"infh",
",",
"outfh",
",",
"filename",
")",
":",
"import",
"gzip",
"gzfh",
"=",
"gzip",
".",
"GzipFile",
"(",
"'rawlogs'",
",",
"mode",
"=",
"'wb'",
",",
"fileobj",
"=",
"outfh",
")",
"if",
"infh",
".",
"closed",
":",
"... | 25.705882 | 19.352941 |
def convert_column(data, schemae):
"""Convert known types from primitive to rich."""
ctype = schemae.converted_type
if ctype == parquet_thrift.ConvertedType.DECIMAL:
scale_factor = Decimal("10e-{}".format(schemae.scale))
if schemae.type == parquet_thrift.Type.INT32 or schemae.type == parquet... | [
"def",
"convert_column",
"(",
"data",
",",
"schemae",
")",
":",
"ctype",
"=",
"schemae",
".",
"converted_type",
"if",
"ctype",
"==",
"parquet_thrift",
".",
"ConvertedType",
".",
"DECIMAL",
":",
"scale_factor",
"=",
"Decimal",
"(",
"\"10e-{}\"",
".",
"format",
... | 55.96875 | 19.8125 |
def greplines(lines, regexpr_list, reflags=0):
"""
grepfile - greps a specific file
TODO: move to util_str, rework to be core of grepfile
"""
found_lines = []
found_lxs = []
# Ensure a list
islist = isinstance(regexpr_list, (list, tuple))
islist2 = isinstance(reflags, (list, tuple))... | [
"def",
"greplines",
"(",
"lines",
",",
"regexpr_list",
",",
"reflags",
"=",
"0",
")",
":",
"found_lines",
"=",
"[",
"]",
"found_lxs",
"=",
"[",
"]",
"# Ensure a list",
"islist",
"=",
"isinstance",
"(",
"regexpr_list",
",",
"(",
"list",
",",
"tuple",
")",... | 34.925 | 13.225 |
def biclique_size(self, xmin, xmax, ymin, ymax):
"""Returns the size parameters ``(m,n)`` of the complete bipartite graph
:math:`K_{m,n}` comprised of ``m`` unbroken chains of horizontally-aligned qubits
and ``n`` unbroken chains of vertically-aligned qubits (known as line
bundles)
... | [
"def",
"biclique_size",
"(",
"self",
",",
"xmin",
",",
"xmax",
",",
"ymin",
",",
"ymax",
")",
":",
"try",
":",
"return",
"self",
".",
"_biclique_size",
"[",
"xmin",
",",
"xmax",
",",
"ymin",
",",
"ymax",
"]",
"except",
"KeyError",
":",
"hscore",
"=",... | 45.269231 | 23.923077 |
def _bcrypt_interpret_ec_key_blob(key_type, blob_struct, blob):
"""
Take a CNG BCRYPT_ECCKEY_BLOB and converts it into an ASN.1 structure
:param key_type:
A unicode string of "private" or "public"
:param blob_struct:
An instance of BCRYPT_ECCKEY_BLOB
:param blob:
A byte st... | [
"def",
"_bcrypt_interpret_ec_key_blob",
"(",
"key_type",
",",
"blob_struct",
",",
"blob",
")",
":",
"magic",
"=",
"native",
"(",
"int",
",",
"blob_struct",
".",
"dwMagic",
")",
"key_byte_length",
"=",
"native",
"(",
"int",
",",
"blob_struct",
".",
"cbKey",
"... | 31.594203 | 20.057971 |
def show_dependencies(self, stream=sys.stdout):
"""Writes to the given stream the ASCII representation of the dependency tree."""
def child_iter(node):
return [d.node for d in node.deps]
def text_str(node):
return colored(str(node), color=node.status.color_opts["color"])... | [
"def",
"show_dependencies",
"(",
"self",
",",
"stream",
"=",
"sys",
".",
"stdout",
")",
":",
"def",
"child_iter",
"(",
"node",
")",
":",
"return",
"[",
"d",
".",
"node",
"for",
"d",
"in",
"node",
".",
"deps",
"]",
"def",
"text_str",
"(",
"node",
")... | 42.2 | 18.3 |
def get_vpc_dict():
"""Returns dictionary of named VPCs {name: vpc}
Assert fails if there's more than one VPC with same name."""
client = get_ec2_client()
response = client.describe_vpcs()
assert is_good_response(response)
result = OrderedDict()
ec2 = get_ec2_resource()
for vpc_response in response['... | [
"def",
"get_vpc_dict",
"(",
")",
":",
"client",
"=",
"get_ec2_client",
"(",
")",
"response",
"=",
"client",
".",
"describe_vpcs",
"(",
")",
"assert",
"is_good_response",
"(",
"response",
")",
"result",
"=",
"OrderedDict",
"(",
")",
"ec2",
"=",
"get_ec2_resou... | 28.652174 | 20.086957 |
def increment_error(self, error: Exception):
'''Increment the error counter preferring base exceptions.'''
_logger.debug('Increment error %s', error)
for error_class in ERROR_PRIORITIES:
if isinstance(error, error_class):
self.errors[error_class] += 1
... | [
"def",
"increment_error",
"(",
"self",
",",
"error",
":",
"Exception",
")",
":",
"_logger",
".",
"debug",
"(",
"'Increment error %s'",
",",
"error",
")",
"for",
"error_class",
"in",
"ERROR_PRIORITIES",
":",
"if",
"isinstance",
"(",
"error",
",",
"error_class",... | 35.7 | 15.9 |
def _delete(self, namespace, stream, start_id, end_time, configuration):
"""
Delete events for `stream` between `start_id` and `end_time`.
`stream` : The stream to delete events for.
`start_id` : Delete events with id > `start_id`.
`end_time` : Delete events ending <= `end_time`.
`configuration`... | [
"def",
"_delete",
"(",
"self",
",",
"namespace",
",",
"stream",
",",
"start_id",
",",
"end_time",
",",
"configuration",
")",
":",
"stream",
"=",
"self",
".",
"get_stream",
"(",
"namespace",
",",
"stream",
",",
"configuration",
")",
"return",
"stream",
".",... | 50.071429 | 16.214286 |
def required_attributes(self):
"""tuple: The schema's required attributed.
"""
# Deprecate
warnings.warn(
'Property "package.required_attributes" is deprecated.',
UserWarning)
required = ()
# Get required
try:
if self.profile.... | [
"def",
"required_attributes",
"(",
"self",
")",
":",
"# Deprecate",
"warnings",
".",
"warn",
"(",
"'Property \"package.required_attributes\" is deprecated.'",
",",
"UserWarning",
")",
"required",
"=",
"(",
")",
"# Get required",
"try",
":",
"if",
"self",
".",
"profi... | 25.166667 | 19.611111 |
def string_to_transition(s):
"""s is a string of the form a,b or a,b->c,d"""
from .machines import Transition
s = lexer(s)
lhs = parse_multiple(s, parse_store)
if s.pos < len(s) and s.cur == "->":
s.pos += 1
rhs = parse_multiple(s, parse_store)
else:
rhs = ()
parse_en... | [
"def",
"string_to_transition",
"(",
"s",
")",
":",
"from",
".",
"machines",
"import",
"Transition",
"s",
"=",
"lexer",
"(",
"s",
")",
"lhs",
"=",
"parse_multiple",
"(",
"s",
",",
"parse_store",
")",
"if",
"s",
".",
"pos",
"<",
"len",
"(",
"s",
")",
... | 28.75 | 12.833333 |
def after_run(self, remote_file_data):
"""
Save uuid of file to our LocalFile
:param remote_file_data: dict: DukeDS file data
"""
if self.file_upload_post_processor:
self.file_upload_post_processor.run(self.settings.data_service, remote_file_data)
remote_file_... | [
"def",
"after_run",
"(",
"self",
",",
"remote_file_data",
")",
":",
"if",
"self",
".",
"file_upload_post_processor",
":",
"self",
".",
"file_upload_post_processor",
".",
"run",
"(",
"self",
".",
"settings",
".",
"data_service",
",",
"remote_file_data",
")",
"rem... | 46.8 | 13 |
def visit_Assign(self, node):
"""
In case of assignment assign value depend on r-value type dependencies.
It is valid for subscript, `a[i] = foo()` means `a` type depend on
`foo` return type.
"""
value_deps = self.visit(node.value)
for target in node.targets:
... | [
"def",
"visit_Assign",
"(",
"self",
",",
"node",
")",
":",
"value_deps",
"=",
"self",
".",
"visit",
"(",
"node",
".",
"value",
")",
"for",
"target",
"in",
"node",
".",
"targets",
":",
"name",
"=",
"get_variable",
"(",
"target",
")",
"if",
"isinstance",... | 36.5 | 13.166667 |
def download(url, directory, filename=None):
"""
Download a file and return its filename on the local file system. If the
file is already there, it will not be downloaded again. The filename is
derived from the url if not provided. Return the filepath.
"""
if not filename:
_, filename = ... | [
"def",
"download",
"(",
"url",
",",
"directory",
",",
"filename",
"=",
"None",
")",
":",
"if",
"not",
"filename",
":",
"_",
",",
"filename",
"=",
"os",
".",
"path",
".",
"split",
"(",
"url",
")",
"directory",
"=",
"os",
".",
"path",
".",
"expanduse... | 39.294118 | 13.058824 |
def compute(self, runner_results, setup=False, poll=False, ignore_errors=False):
''' walk through all results and increment stats '''
for (host, value) in runner_results.get('contacted', {}).iteritems():
if not ignore_errors and (('failed' in value and bool(value['failed'])) or
... | [
"def",
"compute",
"(",
"self",
",",
"runner_results",
",",
"setup",
"=",
"False",
",",
"poll",
"=",
"False",
",",
"ignore_errors",
"=",
"False",
")",
":",
"for",
"(",
"host",
",",
"value",
")",
"in",
"runner_results",
".",
"get",
"(",
"'contacted'",
",... | 51.315789 | 22.157895 |
def send_body(self, data):
"""Send the response body.
``data`` should be a bytes-like object or a string.
"""
if type(data) is str:
data = data.encode()
self.connection.writer.write(data)
yield from self.connection.writer.drain() | [
"def",
"send_body",
"(",
"self",
",",
"data",
")",
":",
"if",
"type",
"(",
"data",
")",
"is",
"str",
":",
"data",
"=",
"data",
".",
"encode",
"(",
")",
"self",
".",
"connection",
".",
"writer",
".",
"write",
"(",
"data",
")",
"yield",
"from",
"se... | 28.2 | 14.3 |
def bootstrap_params(rv_cont, data, n_iter=5, **kwargs):
"""Bootstrap the fit params of a distribution.
Parameters
==========
rv_cont: scipy.stats.rv_continuous instance
The distribution which to fit.
data: array-like, 1d
The data on which to fit.
n_iter: int [default=10]
... | [
"def",
"bootstrap_params",
"(",
"rv_cont",
",",
"data",
",",
"n_iter",
"=",
"5",
",",
"*",
"*",
"kwargs",
")",
":",
"fit_res",
"=",
"[",
"]",
"for",
"_",
"in",
"range",
"(",
"n_iter",
")",
":",
"params",
"=",
"rv_cont",
".",
"fit",
"(",
"resample_1... | 29.388889 | 13.777778 |
def OAuthClient(
domain,
consumer_key,
consumer_secret,
token,
token_secret,
user_agent=None,
request_encoder=default_request_encoder,
response_decoder=default_response_decoder
):
"""Creates a Freshbooks client for a freshbooks domain, using
OAuth. Token management is assumed to ... | [
"def",
"OAuthClient",
"(",
"domain",
",",
"consumer_key",
",",
"consumer_secret",
",",
"token",
",",
"token_secret",
",",
"user_agent",
"=",
"None",
",",
"request_encoder",
"=",
"default_request_encoder",
",",
"response_decoder",
"=",
"default_response_decoder",
")",
... | 32.484848 | 21.333333 |
def from_traceback(cls, tb):
""" Construct a Bytecode from the given traceback """
while tb.tb_next:
tb = tb.tb_next
return cls(tb.tb_frame.f_code, current_offset=tb.tb_lasti) | [
"def",
"from_traceback",
"(",
"cls",
",",
"tb",
")",
":",
"while",
"tb",
".",
"tb_next",
":",
"tb",
"=",
"tb",
".",
"tb_next",
"return",
"cls",
"(",
"tb",
".",
"tb_frame",
".",
"f_code",
",",
"current_offset",
"=",
"tb",
".",
"tb_lasti",
")"
] | 41.4 | 13.2 |
def compare_results(save, best_hsp, tmp_results, tmp_gene_split):
''' Function for comparing hits and saving only the best hit '''
# Get data for comparison
hit_id = best_hsp['hit_id']
new_start_query = best_hsp['query_start']
new_end_query = best_hsp['query_end']
new_start_sbjct = int(best_hsp['sbjct... | [
"def",
"compare_results",
"(",
"save",
",",
"best_hsp",
",",
"tmp_results",
",",
"tmp_gene_split",
")",
":",
"# Get data for comparison",
"hit_id",
"=",
"best_hsp",
"[",
"'hit_id'",
"]",
"new_start_query",
"=",
"best_hsp",
"[",
"'query_start'",
"]",
"new_end_query",... | 46.704348 | 22.113043 |
def _handle_for(self, node, scope, ctxt, stream):
"""Handle For nodes
:node: TODO
:scope: TODO
:ctxt: TODO
:stream: TODO
:returns: TODO
"""
self._dlog("handling for")
if node.init is not None:
# perform the init
self._hand... | [
"def",
"_handle_for",
"(",
"self",
",",
"node",
",",
"scope",
",",
"ctxt",
",",
"stream",
")",
":",
"self",
".",
"_dlog",
"(",
"\"handling for\"",
")",
"if",
"node",
".",
"init",
"is",
"not",
"None",
":",
"# perform the init",
"self",
".",
"_handle_node"... | 32.032258 | 17.709677 |
def default_commit_veto(request, response):
"""
When used as a commit veto, the logic in this function will cause the
transaction to be aborted if:
- An ``X-Tm`` response header with the value ``abort`` (or any value
other than ``commit``) exists.
- The response status code starts with ``4``... | [
"def",
"default_commit_veto",
"(",
"request",
",",
"response",
")",
":",
"xtm",
"=",
"response",
".",
"headers",
".",
"get",
"(",
"'x-tm'",
")",
"if",
"xtm",
"is",
"not",
"None",
":",
"return",
"xtm",
"!=",
"'commit'",
"return",
"response",
".",
"status"... | 32.8125 | 16.9375 |
def asString(self):
"""
Returns this query with an AsString function added to it.
:return <Query>
"""
q = self.copy()
q.addFunction(Query.Function.AsString)
return q | [
"def",
"asString",
"(",
"self",
")",
":",
"q",
"=",
"self",
".",
"copy",
"(",
")",
"q",
".",
"addFunction",
"(",
"Query",
".",
"Function",
".",
"AsString",
")",
"return",
"q"
] | 25.111111 | 15.333333 |
def check(self, key, value):
"""Check whether key,value pair is allowed. The key is allowed if
there is a corresponding key in the defaults class attribute
dict. The value is not allowed if it is a dict in the defaults
dict and not a dict in value.
Parameters
----------
... | [
"def",
"check",
"(",
"self",
",",
"key",
",",
"value",
")",
":",
"# This test necessary to avoid unpickling errors in Python 3",
"if",
"hasattr",
"(",
"self",
",",
"'dflt'",
")",
":",
"# Get corresponding node to self, as determined by pth",
"# attribute, of the defaults dict... | 43.777778 | 19.407407 |
def check_reaction(reactants, products):
"""Check the stoichiometry and format of chemical reaction used for
folder structure.
list of reactants -> list of products
"""
reactant_list = [reactant.split('@')[0].strip(
'star').strip('gas') for reactant in reactants]
product_list = [product.... | [
"def",
"check_reaction",
"(",
"reactants",
",",
"products",
")",
":",
"reactant_list",
"=",
"[",
"reactant",
".",
"split",
"(",
"'@'",
")",
"[",
"0",
"]",
".",
"strip",
"(",
"'star'",
")",
".",
"strip",
"(",
"'gas'",
")",
"for",
"reactant",
"in",
"re... | 33.7 | 16.433333 |
def edit(self, **kwargs):
"""
Modify this calendar event.
:calls: `PUT /api/v1/calendar_events/:id \
<https://canvas.instructure.com/doc/api/calendar_events.html#method.calendar_events_api.update>`_
:rtype: :class:`canvasapi.calendar_event.CalendarEvent`
"""
res... | [
"def",
"edit",
"(",
"self",
",",
"*",
"*",
"kwargs",
")",
":",
"response",
"=",
"self",
".",
"_requester",
".",
"request",
"(",
"'PUT'",
",",
"'calendar_events/{}'",
".",
"format",
"(",
"self",
".",
"id",
")",
",",
"_kwargs",
"=",
"combine_kwargs",
"("... | 33.315789 | 21.105263 |
def flavor_access_remove(flavor_id, project_id, profile=None, **kwargs):
'''
Remove a project from the flavor access list
CLI Example:
.. code-block:: bash
salt '*' nova.flavor_access_remove flavor_id=fID project_id=pID
'''
conn = _auth(profile, **kwargs)
return conn.flavor_access... | [
"def",
"flavor_access_remove",
"(",
"flavor_id",
",",
"project_id",
",",
"profile",
"=",
"None",
",",
"*",
"*",
"kwargs",
")",
":",
"conn",
"=",
"_auth",
"(",
"profile",
",",
"*",
"*",
"kwargs",
")",
"return",
"conn",
".",
"flavor_access_remove",
"(",
"f... | 28.25 | 26.75 |
def diff(self, source_path='', target_path='', which=-1):
"""Build the diff between original docstring and proposed docstring.
:type which: int
-> -1 means all the dosctrings of the file
-> >=0 means the index of the docstring to proceed (Default value = -1)
:param source_pa... | [
"def",
"diff",
"(",
"self",
",",
"source_path",
"=",
"''",
",",
"target_path",
"=",
"''",
",",
"which",
"=",
"-",
"1",
")",
":",
"list_from",
",",
"list_to",
"=",
"self",
".",
"compute_before_after",
"(",
")",
"if",
"source_path",
".",
"startswith",
"(... | 43.307692 | 16.346154 |
def _compile_aggregation_expression(self,
expr: Expression,
scope: Dict[str, TensorFluent],
batch_size: Optional[int] = None,
noise: Optional[List[tf.Tensor]] =... | [
"def",
"_compile_aggregation_expression",
"(",
"self",
",",
"expr",
":",
"Expression",
",",
"scope",
":",
"Dict",
"[",
"str",
",",
"TensorFluent",
"]",
",",
"batch_size",
":",
"Optional",
"[",
"int",
"]",
"=",
"None",
",",
"noise",
":",
"Optional",
"[",
... | 35.5 | 23.642857 |
def smallest_flagged(heap, row):
"""Search the heap for the smallest element that is
still flagged.
Parameters
----------
heap: array of shape (3, n_samples, n_neighbors)
The heaps to search
row: int
Which of the heaps to search
Returns
-------
index: int
T... | [
"def",
"smallest_flagged",
"(",
"heap",
",",
"row",
")",
":",
"ind",
"=",
"heap",
"[",
"0",
",",
"row",
"]",
"dist",
"=",
"heap",
"[",
"1",
",",
"row",
"]",
"flag",
"=",
"heap",
"[",
"2",
",",
"row",
"]",
"min_dist",
"=",
"np",
".",
"inf",
"r... | 22.388889 | 19.222222 |
def _simulate_stack(code: list) -> int:
"""
Simulates the actions of the stack, to check safety.
This returns the maximum needed stack.
"""
max_stack = 0
curr_stack = 0
def _check_stack(ins):
if curr_stack < 0:
raise CompileError("Stack turned negative on instruction: ... | [
"def",
"_simulate_stack",
"(",
"code",
":",
"list",
")",
"->",
"int",
":",
"max_stack",
"=",
"0",
"curr_stack",
"=",
"0",
"def",
"_check_stack",
"(",
"ins",
")",
":",
"if",
"curr_stack",
"<",
"0",
":",
"raise",
"CompileError",
"(",
"\"Stack turned negative... | 33.605263 | 19.078947 |
def add_consumer(self, consumer):
"""Add another consumer from a :class:`Consumer` instance."""
consumer.backend = self.backend
self.consumers.append(consumer) | [
"def",
"add_consumer",
"(",
"self",
",",
"consumer",
")",
":",
"consumer",
".",
"backend",
"=",
"self",
".",
"backend",
"self",
".",
"consumers",
".",
"append",
"(",
"consumer",
")"
] | 45 | 2.25 |
def factory(cfg, login, pswd, request_type):
"""
Instantiate ImportRequest
:param cfg: request configuration, should consist of request description (url and parameters) and response for parsing result
:param login:
:param pswd:
:param request_type: TYPE_GET_SINGLE_OBJECT ... | [
"def",
"factory",
"(",
"cfg",
",",
"login",
",",
"pswd",
",",
"request_type",
")",
":",
"if",
"request_type",
"==",
"ImportRequest",
".",
"TYPE_GET_LIST",
":",
"return",
"ListImportRequest",
"(",
"cfg",
",",
"login",
",",
"pswd",
")",
"elif",
"request_type",... | 48.8 | 22.533333 |
def from_dict(config_cls, dictionary, validate=False):
""" Loads an instance of ``config_cls`` from a dictionary.
:param type config_cls: The class to build an instance of
:param dict dictionary: The dictionary to load from
:param bool validate: Preforms validation before building ``config_cls``,
... | [
"def",
"from_dict",
"(",
"config_cls",
",",
"dictionary",
",",
"validate",
"=",
"False",
")",
":",
"return",
"_build",
"(",
"config_cls",
",",
"dictionary",
",",
"validate",
"=",
"validate",
")"
] | 39.25 | 18 |
def _init_glyph(self, plot, mapping, properties, key):
"""
Returns a Bokeh glyph object.
"""
properties = mpl_to_bokeh(properties)
plot_method = '_'.join(key.split('_')[:-1])
renderer = getattr(plot, plot_method)(**dict(properties, **mapping))
return renderer, ren... | [
"def",
"_init_glyph",
"(",
"self",
",",
"plot",
",",
"mapping",
",",
"properties",
",",
"key",
")",
":",
"properties",
"=",
"mpl_to_bokeh",
"(",
"properties",
")",
"plot_method",
"=",
"'_'",
".",
"join",
"(",
"key",
".",
"split",
"(",
"'_'",
")",
"[",
... | 40.5 | 8.75 |
def showinfo(title=None, message=None, **options):
"""Original doc: Show an info message"""
return psidialogs.message(title=title, message=message) | [
"def",
"showinfo",
"(",
"title",
"=",
"None",
",",
"message",
"=",
"None",
",",
"*",
"*",
"options",
")",
":",
"return",
"psidialogs",
".",
"message",
"(",
"title",
"=",
"title",
",",
"message",
"=",
"message",
")"
] | 51 | 9.666667 |
async def __handle_ping(self, _ : Ping):
""" Handle a Ping message. Pong the backend """
self.__last_ping = time.time()
await ZMQUtils.send(self.__backend_socket, Pong()) | [
"async",
"def",
"__handle_ping",
"(",
"self",
",",
"_",
":",
"Ping",
")",
":",
"self",
".",
"__last_ping",
"=",
"time",
".",
"time",
"(",
")",
"await",
"ZMQUtils",
".",
"send",
"(",
"self",
".",
"__backend_socket",
",",
"Pong",
"(",
")",
")"
] | 47.75 | 5 |
def execute(self, compiled=None, path=None, use_eval=False, allow_show=True):
"""Execute compiled code."""
self.check_runner()
if compiled is not None:
if allow_show and self.show:
print(compiled)
if path is not None: # path means header is included, and ... | [
"def",
"execute",
"(",
"self",
",",
"compiled",
"=",
"None",
",",
"path",
"=",
"None",
",",
"use_eval",
"=",
"False",
",",
"allow_show",
"=",
"True",
")",
":",
"self",
".",
"check_runner",
"(",
")",
"if",
"compiled",
"is",
"not",
"None",
":",
"if",
... | 55.3 | 21.7 |
def _create_sequences(self):
'''Get all of the Sequences - Rosetta, ATOM, SEQRES, FASTA, UniParc.'''
# Create the Rosetta sequences and the maps from the Rosetta sequences to the ATOM sequences
try:
self.pdb.construct_pdb_to_rosetta_residue_map(self.rosetta_scripts_path, rosetta_dat... | [
"def",
"_create_sequences",
"(",
"self",
")",
":",
"# Create the Rosetta sequences and the maps from the Rosetta sequences to the ATOM sequences",
"try",
":",
"self",
".",
"pdb",
".",
"construct_pdb_to_rosetta_residue_map",
"(",
"self",
".",
"rosetta_scripts_path",
",",
"rosett... | 55.277778 | 31.240741 |
def what(self):
"""
May return a 'postponed' or 'rescheduled' string depending what
the start and finish time of the event has been changed to.
"""
originalFromDt = dt.datetime.combine(self.except_date,
timeFrom(self.overrides.time_fro... | [
"def",
"what",
"(",
"self",
")",
":",
"originalFromDt",
"=",
"dt",
".",
"datetime",
".",
"combine",
"(",
"self",
".",
"except_date",
",",
"timeFrom",
"(",
"self",
".",
"overrides",
".",
"time_from",
")",
")",
"changedFromDt",
"=",
"dt",
".",
"datetime",
... | 52.05 | 23.05 |
def configure_logging(args):
"""Logging to console"""
log_format = logging.Formatter('%(levelname)s:%(name)s:line %(lineno)s:%(message)s')
log_level = logging.INFO if args.verbose else logging.WARN
log_level = logging.DEBUG if args.debug else log_level
console = logging.StreamHandler()
console.s... | [
"def",
"configure_logging",
"(",
"args",
")",
":",
"log_format",
"=",
"logging",
".",
"Formatter",
"(",
"'%(levelname)s:%(name)s:line %(lineno)s:%(message)s'",
")",
"log_level",
"=",
"logging",
".",
"INFO",
"if",
"args",
".",
"verbose",
"else",
"logging",
".",
"WA... | 42.857143 | 10.571429 |
def downvote(self):
"""
Downvote the currently selected item.
"""
data = self.get_selected_item()
if 'likes' not in data:
self.term.flash()
elif getattr(data['object'], 'archived'):
self.term.show_notification("Voting disabled for archived post", s... | [
"def",
"downvote",
"(",
"self",
")",
":",
"data",
"=",
"self",
".",
"get_selected_item",
"(",
")",
"if",
"'likes'",
"not",
"in",
"data",
":",
"self",
".",
"term",
".",
"flash",
"(",
")",
"elif",
"getattr",
"(",
"data",
"[",
"'object'",
"]",
",",
"'... | 38.631579 | 9.684211 |
def set_public_domain(self, public_domain=None):
"""Sets the public domain flag.
:param public_domain: the public domain status
:type public_domain: ``boolean``
:raise: ``NoAccess`` -- ``Metadata.isReadOnly()`` is ``true``
*compliance: mandatory -- This method must be implement... | [
"def",
"set_public_domain",
"(",
"self",
",",
"public_domain",
"=",
"None",
")",
":",
"if",
"public_domain",
"is",
"None",
":",
"raise",
"NullArgument",
"(",
")",
"metadata",
"=",
"Metadata",
"(",
"*",
"*",
"settings",
".",
"METADATA",
"[",
"'public_domain'"... | 36.578947 | 17.526316 |
def iter_chunks(chunksize, *iterables):
"""Iterates over zipped iterables in chunks."""
iterables = iter(zip(*iterables))
while 1:
chunk = tuple(islice(iterables, chunksize))
if not chunk:
return
yield chunk | [
"def",
"iter_chunks",
"(",
"chunksize",
",",
"*",
"iterables",
")",
":",
"iterables",
"=",
"iter",
"(",
"zip",
"(",
"*",
"iterables",
")",
")",
"while",
"1",
":",
"chunk",
"=",
"tuple",
"(",
"islice",
"(",
"iterables",
",",
"chunksize",
")",
")",
"if... | 22.545455 | 20.454545 |
def formfield(self, **kwargs):
"""
Provide the custom form widget for the admin, since there
isn't a form field mapped to ``GenericRelation`` model fields.
"""
from yacms.generic.forms import KeywordsWidget
kwargs["widget"] = KeywordsWidget
return super(KeywordsFi... | [
"def",
"formfield",
"(",
"self",
",",
"*",
"*",
"kwargs",
")",
":",
"from",
"yacms",
".",
"generic",
".",
"forms",
"import",
"KeywordsWidget",
"kwargs",
"[",
"\"widget\"",
"]",
"=",
"KeywordsWidget",
"return",
"super",
"(",
"KeywordsField",
",",
"self",
")... | 42.875 | 12.625 |
def create(**data):
"""
Create a customer.
:param data: data required to create the customer
:return: The customer resource
:rtype resources.Customer
"""
http_client = HttpClient()
response, _ = http_client.post(routes.url(routes.CUSTOMER_RESOURCE), data... | [
"def",
"create",
"(",
"*",
"*",
"data",
")",
":",
"http_client",
"=",
"HttpClient",
"(",
")",
"response",
",",
"_",
"=",
"http_client",
".",
"post",
"(",
"routes",
".",
"url",
"(",
"routes",
".",
"CUSTOMER_RESOURCE",
")",
",",
"data",
")",
"return",
... | 29.666667 | 16.166667 |
def setShowLanguage(self, state):
"""
Sets the display mode for this widget to the inputed mode.
:param state | <bool>
"""
if state == self._showLanguage:
return
self._showLanguage = state
self.setDirty() | [
"def",
"setShowLanguage",
"(",
"self",
",",
"state",
")",
":",
"if",
"state",
"==",
"self",
".",
"_showLanguage",
":",
"return",
"self",
".",
"_showLanguage",
"=",
"state",
"self",
".",
"setDirty",
"(",
")"
] | 26.818182 | 13 |
def remove(self, path):
"""
Remove the file at the given path. This only works on files; for
removing folders (directories), use L{rmdir}.
@param path: path (absolute or relative) of the file to remove
@type path: str
@raise IOError: if the path refers to a folder (dir... | [
"def",
"remove",
"(",
"self",
",",
"path",
")",
":",
"path",
"=",
"self",
".",
"_adjust_cwd",
"(",
"path",
")",
"self",
".",
"_log",
"(",
"DEBUG",
",",
"'remove(%r)'",
"%",
"path",
")",
"self",
".",
"_request",
"(",
"CMD_REMOVE",
",",
"path",
")"
] | 34.692308 | 17.307692 |
def __validation_callback(self, event):
# type: (str) -> Any
"""
Specific handling for the ``@ValidateComponent`` and
``@InvalidateComponent`` callback, as it requires checking arguments
count and order
:param event: The kind of life-cycle callback (in/validation)
... | [
"def",
"__validation_callback",
"(",
"self",
",",
"event",
")",
":",
"# type: (str) -> Any",
"comp_callback",
"=",
"self",
".",
"context",
".",
"get_callback",
"(",
"event",
")",
"if",
"not",
"comp_callback",
":",
"# No registered callback",
"return",
"True",
"# G... | 34.179487 | 19.769231 |
def make_innermost_setter(setter):
"""Wraps a setter so it applies to the inner-most results in `kernel_results`.
The wrapped setter unwraps `kernel_results` and applies `setter` to the first
results without an `inner_results` attribute.
Args:
setter: A callable that takes the kernel results as well as so... | [
"def",
"make_innermost_setter",
"(",
"setter",
")",
":",
"@",
"functools",
".",
"wraps",
"(",
"setter",
")",
"def",
"_new_setter",
"(",
"kernel_results",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"\"\"\"Wrapped setter.\"\"\"",
"results_stack",
"=",
... | 32.3 | 20.433333 |
def release_job(self, job_id, pri=65536, delay=0):
"""Put a job back on the queue to be processed (indicating that you've aborted it)
You can only release a job which you have reserved using :func:`reserve_job()` or :func:`reserve_iter()`.
:param job_id: Job ID to return
:param pri: Ne... | [
"def",
"release_job",
"(",
"self",
",",
"job_id",
",",
"pri",
"=",
"65536",
",",
"delay",
"=",
"0",
")",
":",
"if",
"hasattr",
"(",
"job_id",
",",
"'job_id'",
")",
":",
"job_id",
"=",
"job_id",
".",
"job_id",
"with",
"self",
".",
"_sock_ctx",
"(",
... | 47.4375 | 21.625 |
def build_ordered_cliques(cliques, next_cliques):
"""Order the new cliques based on the order of their ancestors in the
previous iteration."""
def sort_key(clique):
return -len(clique[1])
if not cliques:
return list(sorted(
list(next_cliques.values())[0].items(),
... | [
"def",
"build_ordered_cliques",
"(",
"cliques",
",",
"next_cliques",
")",
":",
"def",
"sort_key",
"(",
"clique",
")",
":",
"return",
"-",
"len",
"(",
"clique",
"[",
"1",
"]",
")",
"if",
"not",
"cliques",
":",
"return",
"list",
"(",
"sorted",
"(",
"list... | 30.52 | 18.08 |
def load(path, size=None):
"""
Args:
size (int): total number of records. If not provided, the returned dataflow will have no `__len__()`.
It's needed because this metadata is not stored in the TFRecord file.
"""
gen = tf.python_io.tf_record_iterator(path)
... | [
"def",
"load",
"(",
"path",
",",
"size",
"=",
"None",
")",
":",
"gen",
"=",
"tf",
".",
"python_io",
".",
"tf_record_iterator",
"(",
"path",
")",
"ds",
"=",
"DataFromGenerator",
"(",
"gen",
")",
"ds",
"=",
"MapData",
"(",
"ds",
",",
"loads",
")",
"i... | 38.416667 | 18.25 |
def object_url(self, object_t, object_id=None, relation=None, **kwargs):
"""
Helper method to build the url to query to access the object
passed as parameter
:raises TypeError: if the object type is invalid
"""
if object_t not in self.objects_types:
raise Typ... | [
"def",
"object_url",
"(",
"self",
",",
"object_t",
",",
"object_id",
"=",
"None",
",",
"relation",
"=",
"None",
",",
"*",
"*",
"kwargs",
")",
":",
"if",
"object_t",
"not",
"in",
"self",
".",
"objects_types",
":",
"raise",
"TypeError",
"(",
"\"{} is not a... | 41.769231 | 18 |
def get_board_mapping_parent_items(self, team_context, child_backlog_context_category_ref_name, workitem_ids):
"""GetBoardMappingParentItems.
[Preview API] Returns the list of parent field filter model for the given list of workitem ids
:param :class:`<TeamContext> <azure.devops.v5_0.work.models... | [
"def",
"get_board_mapping_parent_items",
"(",
"self",
",",
"team_context",
",",
"child_backlog_context_category_ref_name",
",",
"workitem_ids",
")",
":",
"project",
"=",
"None",
"team",
"=",
"None",
"if",
"team_context",
"is",
"not",
"None",
":",
"if",
"team_context... | 53.918919 | 25.405405 |
def computeMultipleExpectations(self, A_in, u_n, compute_uncertainty=True, compute_covariance=False,
uncertainty_method=None, warning_cutoff=1.0e-10, return_theta=False):
"""Compute the expectations of multiple observables of phase space functions.
Compute the expect... | [
"def",
"computeMultipleExpectations",
"(",
"self",
",",
"A_in",
",",
"u_n",
",",
"compute_uncertainty",
"=",
"True",
",",
"compute_covariance",
"=",
"False",
",",
"uncertainty_method",
"=",
"None",
",",
"warning_cutoff",
"=",
"1.0e-10",
",",
"return_theta",
"=",
... | 47.82 | 28.22 |
def _parse_build(encoded_data, pointer=0, spec=None, spec_params=None, strict=False):
"""
Parses a byte string generically, or using a spec with optional params
:param encoded_data:
A byte string that contains BER-encoded data
:param pointer:
The index in the byte string to parse from
... | [
"def",
"_parse_build",
"(",
"encoded_data",
",",
"pointer",
"=",
"0",
",",
"spec",
"=",
"None",
",",
"spec_params",
"=",
"None",
",",
"strict",
"=",
"False",
")",
":",
"encoded_len",
"=",
"len",
"(",
"encoded_data",
")",
"info",
",",
"new_pointer",
"=",
... | 40.027778 | 26.305556 |
def call_hook(self, name, **kwargs):
""" Call all hooks registered with this name. Returns a list of the returns values of the hooks (in the order the hooks were added)"""
return [y for y in [x(**kwargs) for x, _ in self._hooks.get(name, [])] if y is not None] | [
"def",
"call_hook",
"(",
"self",
",",
"name",
",",
"*",
"*",
"kwargs",
")",
":",
"return",
"[",
"y",
"for",
"y",
"in",
"[",
"x",
"(",
"*",
"*",
"kwargs",
")",
"for",
"x",
",",
"_",
"in",
"self",
".",
"_hooks",
".",
"get",
"(",
"name",
",",
... | 91.333333 | 20 |
def _set_prompt(self):
"""Set prompt so it displays the current working directory."""
self.cwd = os.getcwd()
self.prompt = Fore.CYAN + '{!r} $ '.format(self.cwd) + Fore.RESET | [
"def",
"_set_prompt",
"(",
"self",
")",
":",
"self",
".",
"cwd",
"=",
"os",
".",
"getcwd",
"(",
")",
"self",
".",
"prompt",
"=",
"Fore",
".",
"CYAN",
"+",
"'{!r} $ '",
".",
"format",
"(",
"self",
".",
"cwd",
")",
"+",
"Fore",
".",
"RESET"
] | 48.75 | 15.25 |
def expand_alias(self, line):
""" Expand an alias in the command line
Returns the provided command line, possibly with the first word
(command) translated according to alias expansion rules.
[ipython]|16> _ip.expand_aliases("np myfile.txt")
<16> 'q:/opt/np/notepad++.ex... | [
"def",
"expand_alias",
"(",
"self",
",",
"line",
")",
":",
"pre",
",",
"_",
",",
"fn",
",",
"rest",
"=",
"split_user_input",
"(",
"line",
")",
"res",
"=",
"pre",
"+",
"self",
".",
"expand_aliases",
"(",
"fn",
",",
"rest",
")",
"return",
"res"
] | 34.615385 | 19.846154 |
def output_datacenter(gandi, datacenter, output_keys, justify=14):
""" Helper to output datacenter information."""
output_generic(gandi, datacenter, output_keys, justify)
if 'dc_name' in output_keys:
output_line(gandi, 'datacenter', datacenter['name'], justify)
if 'status' in output_keys:
... | [
"def",
"output_datacenter",
"(",
"gandi",
",",
"datacenter",
",",
"output_keys",
",",
"justify",
"=",
"14",
")",
":",
"output_generic",
"(",
"gandi",
",",
"datacenter",
",",
"output_keys",
",",
"justify",
")",
"if",
"'dc_name'",
"in",
"output_keys",
":",
"ou... | 36.166667 | 20.291667 |
def setup_logging(name):
"""Setup logging according to environment variables."""
logger = logging.getLogger(__name__)
if 'NVIM_PYTHON_LOG_FILE' in os.environ:
prefix = os.environ['NVIM_PYTHON_LOG_FILE'].strip()
major_version = sys.version_info[0]
logfile = '{}_py{}_{}'.format(prefix,... | [
"def",
"setup_logging",
"(",
"name",
")",
":",
"logger",
"=",
"logging",
".",
"getLogger",
"(",
"__name__",
")",
"if",
"'NVIM_PYTHON_LOG_FILE'",
"in",
"os",
".",
"environ",
":",
"prefix",
"=",
"os",
".",
"environ",
"[",
"'NVIM_PYTHON_LOG_FILE'",
"]",
".",
... | 45.4 | 11.35 |
def bundles():
"""Display bundles."""
per_page = int(request.args.get('per_page', 30))
page = int(request.args.get('page', 1))
query = store.bundles()
query_page = query.paginate(page, per_page=per_page)
data = []
for bundle_obj in query_page.items:
bundle_data = bundle_obj.to_dict(... | [
"def",
"bundles",
"(",
")",
":",
"per_page",
"=",
"int",
"(",
"request",
".",
"args",
".",
"get",
"(",
"'per_page'",
",",
"30",
")",
")",
"page",
"=",
"int",
"(",
"request",
".",
"args",
".",
"get",
"(",
"'page'",
",",
"1",
")",
")",
"query",
"... | 33.142857 | 17.428571 |
def enable_cache(self):
""" Enable client-side caching for the current request """
self.set_header('Cache-Control', 'max-age=%d, public' % self.CACHE_TIME)
now = datetime.datetime.now()
expires = now + datetime.timedelta(seconds=self.CACHE_TIME)
self.set_header('Expires', expire... | [
"def",
"enable_cache",
"(",
"self",
")",
":",
"self",
".",
"set_header",
"(",
"'Cache-Control'",
",",
"'max-age=%d, public'",
"%",
"self",
".",
"CACHE_TIME",
")",
"now",
"=",
"datetime",
".",
"datetime",
".",
"now",
"(",
")",
"expires",
"=",
"now",
"+",
... | 46.222222 | 25.555556 |
def get_quality_options(self, channel):
"""Get the available quality options for streams of the given channel
Possible values in the list:
* source
* high
* medium
* low
* mobile
* audio
:param channel: the channel or channel name
... | [
"def",
"get_quality_options",
"(",
"self",
",",
"channel",
")",
":",
"optionmap",
"=",
"{",
"'chunked'",
":",
"'source'",
",",
"'high'",
":",
"'high'",
",",
"'medium'",
":",
"'medium'",
",",
"'low'",
":",
"'low'",
",",
"'mobile'",
":",
"'mobile'",
",",
"... | 31.666667 | 13.2 |
def _discover_params(cls):
"""
Returns a dict where filter keyword is key, and class is value.
To handle param alias (maxRecords or max_records), both versions are
added.
"""
try:
return cls.filters
except AttributeError:
filters... | [
"def",
"_discover_params",
"(",
"cls",
")",
":",
"try",
":",
"return",
"cls",
".",
"filters",
"except",
"AttributeError",
":",
"filters",
"=",
"{",
"}",
"for",
"param_class_name",
"in",
"dir",
"(",
"cls",
")",
":",
"param_class",
"=",
"getattr",
"(",
"cl... | 36.666667 | 17.222222 |
def __split_procedure(self, split_node):
"""!
@brief Starts node splitting procedure in the CF-tree from the specify node.
@param[in] split_node (cfnode): CF-tree node that should be splitted.
"""
if (split_node is self.__root):
self.__root =... | [
"def",
"__split_procedure",
"(",
"self",
",",
"split_node",
")",
":",
"if",
"(",
"split_node",
"is",
"self",
".",
"__root",
")",
":",
"self",
".",
"__root",
"=",
"non_leaf_node",
"(",
"split_node",
".",
"feature",
",",
"None",
",",
"[",
"split_node",
"]"... | 35.896552 | 15.310345 |
def create(self, name, nopassword=None, secret=None, encryption=None):
"""Creates a new user on the local system.
Creating users requires either a secret (password) or the nopassword
keyword to be specified.
Args:
name (str): The name of the user to craete
nopa... | [
"def",
"create",
"(",
"self",
",",
"name",
",",
"nopassword",
"=",
"None",
",",
"secret",
"=",
"None",
",",
"encryption",
"=",
"None",
")",
":",
"if",
"secret",
"is",
"not",
"None",
":",
"return",
"self",
".",
"create_with_secret",
"(",
"name",
",",
... | 37.193548 | 25.032258 |
def add_task(self, cor, name=None, finalizer=None, stop_timeout=1.0, parent=None):
"""Schedule a task to run on the background event loop.
This method will start the given coroutine as a task and keep track
of it so that it can be properly shutdown which the event loop is
stopped.
... | [
"def",
"add_task",
"(",
"self",
",",
"cor",
",",
"name",
"=",
"None",
",",
"finalizer",
"=",
"None",
",",
"stop_timeout",
"=",
"1.0",
",",
"parent",
"=",
"None",
")",
":",
"if",
"self",
".",
"stopping",
":",
"raise",
"LoopStoppingError",
"(",
"\"Cannot... | 47.3125 | 30.65625 |
def DeletePendingNotification(self, timestamp):
"""Deletes the pending notification with the given timestamp.
Args:
timestamp: The timestamp of the notification. Assumed to be unique.
Raises:
UniqueKeyError: Raised if multiple notifications have the timestamp.
"""
shown_notifications =... | [
"def",
"DeletePendingNotification",
"(",
"self",
",",
"timestamp",
")",
":",
"shown_notifications",
"=",
"self",
".",
"Get",
"(",
"self",
".",
"Schema",
".",
"SHOWN_NOTIFICATIONS",
")",
"if",
"not",
"shown_notifications",
":",
"shown_notifications",
"=",
"self",
... | 34.612903 | 22.290323 |
def signRequest(self,
req: Request,
identifier: Identifier=None) -> Request:
"""
Signs request. Modifies reqId and signature. May modify identifier.
:param req: request
:param requestIdStore: request id generator
:param identifier: signer ... | [
"def",
"signRequest",
"(",
"self",
",",
"req",
":",
"Request",
",",
"identifier",
":",
"Identifier",
"=",
"None",
")",
"->",
"Request",
":",
"idr",
"=",
"self",
".",
"requiredIdr",
"(",
"idr",
"=",
"identifier",
"or",
"req",
".",
"_identifier",
")",
"#... | 39.48 | 18.44 |
def cublasCgemv(handle, trans, m, n, alpha, A, lda, x, incx, beta, y, incy):
"""
Matrix-vector product for complex general matrix.
"""
status = _libcublas.cublasCgemv_v2(handle,
_CUBLAS_OP[trans], m, n,
ctypes.byref(cuda.cuF... | [
"def",
"cublasCgemv",
"(",
"handle",
",",
"trans",
",",
"m",
",",
"n",
",",
"alpha",
",",
"A",
",",
"lda",
",",
"x",
",",
"incx",
",",
"beta",
",",
"y",
",",
"incy",
")",
":",
"status",
"=",
"_libcublas",
".",
"cublasCgemv_v2",
"(",
"handle",
","... | 48.8 | 25.333333 |
def _fadn_par(vec, geom):
"""First non-zero Atomic Displacement that is Non-Parallel with Vec
Utility function to identify the first atomic displacement in a geometry
that is both (a) not the zero vector and (b) non-(anti-)parallel with a
reference vector.
Parameters
----------
vec
... | [
"def",
"_fadn_par",
"(",
"vec",
",",
"geom",
")",
":",
"# Imports",
"import",
"numpy",
"as",
"np",
"from",
"scipy",
"import",
"linalg",
"as",
"spla",
"from",
".",
".",
"const",
"import",
"PRM",
"from",
".",
".",
"error",
"import",
"InertiaError",
"from",... | 29.507463 | 21.358209 |
def dict_fun(data, function):
"""
Apply a function to all values in a dictionary, return a dictionary with
results.
Parameters
----------
data : dict
a dictionary whose values are adequate input to the second argument
of this function.
function : function
a function... | [
"def",
"dict_fun",
"(",
"data",
",",
"function",
")",
":",
"return",
"dict",
"(",
"(",
"k",
",",
"function",
"(",
"v",
")",
")",
"for",
"k",
",",
"v",
"in",
"list",
"(",
"data",
".",
"items",
"(",
")",
")",
")"
] | 27.210526 | 21 |
def bin_to_edge_slice(s, n):
"""
Convert a bin slice into a bin edge slice.
"""
s = canonify_slice(s, n)
start = s.start
stop = s.stop
if start > stop:
_stop = start + 1
start = stop + 1
stop = _stop
start = max(start - 1, 0)
step = abs(s.step)
if stop <= ... | [
"def",
"bin_to_edge_slice",
"(",
"s",
",",
"n",
")",
":",
"s",
"=",
"canonify_slice",
"(",
"s",
",",
"n",
")",
"start",
"=",
"s",
".",
"start",
"stop",
"=",
"s",
".",
"stop",
"if",
"start",
">",
"stop",
":",
"_stop",
"=",
"start",
"+",
"1",
"st... | 28.315789 | 12.526316 |
def filter_source(self, source):
# pylint: disable=R0911,R0912
"""
Apply filters to ``source`` and return ``True`` if uncertainty should
be applied to it.
"""
for key, value in self.filters.items():
if key == 'applyToTectonicRegionType':
if val... | [
"def",
"filter_source",
"(",
"self",
",",
"source",
")",
":",
"# pylint: disable=R0911,R0912",
"for",
"key",
",",
"value",
"in",
"self",
".",
"filters",
".",
"items",
"(",
")",
":",
"if",
"key",
"==",
"'applyToTectonicRegionType'",
":",
"if",
"value",
"!=",
... | 44.567568 | 13.27027 |
def screenshot(filename="screenshot.png"):
"""
Save a screenshot of the current rendering window.
"""
if not settings.plotter_instance.window:
colors.printc('~bomb screenshot(): Rendering window is not present, skip.', c=1)
return
w2if = vtk.vtkWindowToImageFilter()
w2if.ShouldRe... | [
"def",
"screenshot",
"(",
"filename",
"=",
"\"screenshot.png\"",
")",
":",
"if",
"not",
"settings",
".",
"plotter_instance",
".",
"window",
":",
"colors",
".",
"printc",
"(",
"'~bomb screenshot(): Rendering window is not present, skip.'",
",",
"c",
"=",
"1",
")",
... | 37.0625 | 12.6875 |
def complete_contexts(self):
'''
Returns a list of context interfaces that yield a complete context.
'''
interfaces = []
[interfaces.extend(i.complete_contexts())
for i in six.itervalues(self.templates)]
return interfaces | [
"def",
"complete_contexts",
"(",
"self",
")",
":",
"interfaces",
"=",
"[",
"]",
"[",
"interfaces",
".",
"extend",
"(",
"i",
".",
"complete_contexts",
"(",
")",
")",
"for",
"i",
"in",
"six",
".",
"itervalues",
"(",
"self",
".",
"templates",
")",
"]",
... | 33.875 | 19.375 |
def human_xor_00(X, y, model_generator, method_name):
""" XOR (false/false)
This tests how well a feature attribution method agrees with human intuition
for an eXclusive OR operation combined with linear effects. This metric deals
specifically with the question of credit allocation for the following fu... | [
"def",
"human_xor_00",
"(",
"X",
",",
"y",
",",
"model_generator",
",",
"method_name",
")",
":",
"return",
"_human_xor",
"(",
"X",
",",
"model_generator",
",",
"method_name",
",",
"False",
",",
"False",
")"
] | 37.733333 | 21.6 |
def tensor_to_6component(tensor, frame='USE'):
'''
Returns a tensor to six component vector [Mrr, Mtt, Mpp, Mrt, Mrp, Mtp]
'''
if 'NED' in frame:
tensor = ned_to_use(tensor)
return [tensor[0, 0], tensor[1, 1], tensor[2, 2], tensor[0, 1],
tensor[0, 2], tensor[1, 2]] | [
"def",
"tensor_to_6component",
"(",
"tensor",
",",
"frame",
"=",
"'USE'",
")",
":",
"if",
"'NED'",
"in",
"frame",
":",
"tensor",
"=",
"ned_to_use",
"(",
"tensor",
")",
"return",
"[",
"tensor",
"[",
"0",
",",
"0",
"]",
",",
"tensor",
"[",
"1",
",",
... | 33.111111 | 22 |
def filter(self):
"""Get the query of this Query.
The device query
:return: The query of this Query.
:rtype: dict
"""
if isinstance(self._filter, str):
return self._decode_query(self._filter)
return self._filter | [
"def",
"filter",
"(",
"self",
")",
":",
"if",
"isinstance",
"(",
"self",
".",
"_filter",
",",
"str",
")",
":",
"return",
"self",
".",
"_decode_query",
"(",
"self",
".",
"_filter",
")",
"return",
"self",
".",
"_filter"
] | 24.636364 | 15 |
def _check_version(self, major, minor):
"""
Check if the detected bugzilla version is >= passed major/minor pair.
"""
if major < self.bz_ver_major:
return True
if (major == self.bz_ver_major and minor <= self.bz_ver_minor):
return True
return False | [
"def",
"_check_version",
"(",
"self",
",",
"major",
",",
"minor",
")",
":",
"if",
"major",
"<",
"self",
".",
"bz_ver_major",
":",
"return",
"True",
"if",
"(",
"major",
"==",
"self",
".",
"bz_ver_major",
"and",
"minor",
"<=",
"self",
".",
"bz_ver_minor",
... | 34.666667 | 14 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.