text stringlengths 89 104k | code_tokens list | avg_line_len float64 7.91 980 | score float64 0 630 |
|---|---|---|---|
def Bidirectional(l2r, r2l):
"""Stitch two RNN models into a bidirectional layer."""
nO = l2r.nO
def birnn_fwd(Xs, drop=0.0):
l2r_Zs, bp_l2r_Zs = l2r.begin_update(Xs, drop=drop)
r2l_Zs, bp_r2l_Zs = r2l.begin_update(
[l2r.ops.xp.ascontiguousarray(X[::-1]) for X in Xs]
)
... | [
"def",
"Bidirectional",
"(",
"l2r",
",",
"r2l",
")",
":",
"nO",
"=",
"l2r",
".",
"nO",
"def",
"birnn_fwd",
"(",
"Xs",
",",
"drop",
"=",
"0.0",
")",
":",
"l2r_Zs",
",",
"bp_l2r_Zs",
"=",
"l2r",
".",
"begin_update",
"(",
"Xs",
",",
"drop",
"=",
"dr... | 36.37037 | 19.740741 |
def python_version(i):
"""
Input: {}
Output: {
version - sys.version
version_info - sys.version_info
}
"""
import sys
o=i.get('out','')
v1=sys.version
v2=sys.version_info
if o=='con':
out(v1)
return {'return':0, 'version':v... | [
"def",
"python_version",
"(",
"i",
")",
":",
"import",
"sys",
"o",
"=",
"i",
".",
"get",
"(",
"'out'",
",",
"''",
")",
"v1",
"=",
"sys",
".",
"version",
"v2",
"=",
"sys",
".",
"version_info",
"if",
"o",
"==",
"'con'",
":",
"out",
"(",
"v1",
")"... | 14.545455 | 24.454545 |
def parse_buf(self, encoding="unicode"):
"""
Since TCP is a stream-orientated protocol, responses aren't guaranteed
to be complete when they arrive. The buffer stores all the data and
this function splits the data into replies based on the new line
delimiter.
"""
... | [
"def",
"parse_buf",
"(",
"self",
",",
"encoding",
"=",
"\"unicode\"",
")",
":",
"buf_len",
"=",
"len",
"(",
"self",
".",
"buf",
")",
"replies",
"=",
"[",
"]",
"reply",
"=",
"b\"\"",
"chop",
"=",
"0",
"skip",
"=",
"0",
"i",
"=",
"0",
"buf_len",
"=... | 29 | 18.702128 |
def truncate(self, rev: int) -> None:
"""Delete everything after the given revision."""
self.seek(rev)
self._keys.difference_update(map(get0, self._future))
self._future = []
if not self._past:
self._beginning = None | [
"def",
"truncate",
"(",
"self",
",",
"rev",
":",
"int",
")",
"->",
"None",
":",
"self",
".",
"seek",
"(",
"rev",
")",
"self",
".",
"_keys",
".",
"difference_update",
"(",
"map",
"(",
"get0",
",",
"self",
".",
"_future",
")",
")",
"self",
".",
"_f... | 37.428571 | 11 |
def __find_column(self, column_names, part_first_line):
"""
Finds the column for the column_name in sar type definition,
and returns its index.
:param column_names: Names of the column we look for (regex) put in
the list
:param part_first_line: First line ... | [
"def",
"__find_column",
"(",
"self",
",",
"column_names",
",",
"part_first_line",
")",
":",
"part_parts",
"=",
"part_first_line",
".",
"split",
"(",
")",
"### DEBUG",
"# print(\"Parts: %s\" % (part_parts))",
"return_dict",
"=",
"{",
"}",
"counter",
"=",
"0",
"for"... | 32.542857 | 17.685714 |
def notification_preference(obj_type, profile):
'''Display two radio buttons for turning notifications on or off.
The default value is is have alerts_on = True.
'''
default_alert_value = True
if not profile:
alerts_on = True
else:
notifications = profile.get('notifications', {})
... | [
"def",
"notification_preference",
"(",
"obj_type",
",",
"profile",
")",
":",
"default_alert_value",
"=",
"True",
"if",
"not",
"profile",
":",
"alerts_on",
"=",
"True",
"else",
":",
"notifications",
"=",
"profile",
".",
"get",
"(",
"'notifications'",
",",
"{",
... | 39.454545 | 19.636364 |
def main(path, pid, queue):
"""
Standalone PSQ worker.
The queue argument must be the full importable path to a psq.Queue
instance.
Example usage:
psqworker config.q
psqworker --path /opt/app queues.fast
"""
setup_logging()
if pid:
with open(os.path.expandus... | [
"def",
"main",
"(",
"path",
",",
"pid",
",",
"queue",
")",
":",
"setup_logging",
"(",
")",
"if",
"pid",
":",
"with",
"open",
"(",
"os",
".",
"path",
".",
"expanduser",
"(",
"pid",
")",
",",
"\"w\"",
")",
"as",
"f",
":",
"f",
".",
"write",
"(",
... | 16.53125 | 24.40625 |
def parse_ssois_return(ssois_return, object_name, imagetype, camera_filter='r.MP9601',
telescope_instrument='CFHT/MegaCam'):
"""
Parse through objects in ssois query and filter out images of desired filter, type, exposure time, and instrument
"""
assert camera_filter in ['r.MP960... | [
"def",
"parse_ssois_return",
"(",
"ssois_return",
",",
"object_name",
",",
"imagetype",
",",
"camera_filter",
"=",
"'r.MP9601'",
",",
"telescope_instrument",
"=",
"'CFHT/MegaCam'",
")",
":",
"assert",
"camera_filter",
"in",
"[",
"'r.MP9601'",
",",
"'u.MP9301'",
"]",... | 35.69697 | 22.181818 |
def bottleneck_matching(I1, I2, matchidx, D, labels=["dgm1", "dgm2"], ax=None):
""" Visualize bottleneck matching between two diagrams
Parameters
===========
I1: array
A diagram
I2: array
A diagram
matchidx: tuples of matched indices
if input `matching=True`, then retur... | [
"def",
"bottleneck_matching",
"(",
"I1",
",",
"I2",
",",
"matchidx",
",",
"D",
",",
"labels",
"=",
"[",
"\"dgm1\"",
",",
"\"dgm2\"",
"]",
",",
"ax",
"=",
"None",
")",
":",
"plot_diagrams",
"(",
"[",
"I1",
",",
"I2",
"]",
",",
"labels",
"=",
"labels... | 30.866667 | 17.555556 |
def add(self, value):
"""Add element *value* to the set."""
# Raise TypeError if value is not hashable
hash(value)
self.redis.sadd(self.key, self._pickle(value)) | [
"def",
"add",
"(",
"self",
",",
"value",
")",
":",
"# Raise TypeError if value is not hashable",
"hash",
"(",
"value",
")",
"self",
".",
"redis",
".",
"sadd",
"(",
"self",
".",
"key",
",",
"self",
".",
"_pickle",
"(",
"value",
")",
")"
] | 31.5 | 17.333333 |
def resizeColumnsToContents(self, startCol=None, stopCol=None):
""" Resizes all columns to the contents
"""
numCols = self.model().columnCount()
startCol = 0 if startCol is None else max(startCol, 0)
stopCol = numCols if stopCol is None else min(stopCol, numCols)
row = ... | [
"def",
"resizeColumnsToContents",
"(",
"self",
",",
"startCol",
"=",
"None",
",",
"stopCol",
"=",
"None",
")",
":",
"numCols",
"=",
"self",
".",
"model",
"(",
")",
".",
"columnCount",
"(",
")",
"startCol",
"=",
"0",
"if",
"startCol",
"is",
"None",
"els... | 38.882353 | 21.470588 |
def uinit(self, ushape):
"""Return initialiser for working variable U."""
if self.opt['Y0'] is None:
return np.zeros(ushape, dtype=self.dtype)
else:
# If initial Y is non-zero, initial U is chosen so that
# the relevant dual optimality criterion (see (3.10) i... | [
"def",
"uinit",
"(",
"self",
",",
"ushape",
")",
":",
"if",
"self",
".",
"opt",
"[",
"'Y0'",
"]",
"is",
"None",
":",
"return",
"np",
".",
"zeros",
"(",
"ushape",
",",
"dtype",
"=",
"self",
".",
"dtype",
")",
"else",
":",
"# If initial Y is non-zero, ... | 41.8 | 18 |
def __initialize_ui(self):
"""
Initializes the Widget ui.
"""
umbra.ui.common.set_window_default_icon(self)
for model, settings_key, combo_box in \
(("_SearchAndReplace__search_patterns_model", "recent_search_patterns", self.Search_comboBox),
("... | [
"def",
"__initialize_ui",
"(",
"self",
")",
":",
"umbra",
".",
"ui",
".",
"common",
".",
"set_window_default_icon",
"(",
"self",
")",
"for",
"model",
",",
"settings_key",
",",
"combo_box",
"in",
"(",
"(",
"\"_SearchAndReplace__search_patterns_model\"",
",",
"\"r... | 51.805556 | 31.416667 |
def arrayuniqify(X, retainorder=False):
"""
Very fast uniqify routine for numpy arrays.
**Parameters**
**X** : numpy array
Determine the unique elements of this numpy array.
**retainorder** : Boolean, optional
Whether or not to return in... | [
"def",
"arrayuniqify",
"(",
"X",
",",
"retainorder",
"=",
"False",
")",
":",
"s",
"=",
"X",
".",
"argsort",
"(",
")",
"X",
"=",
"X",
"[",
"s",
"]",
"D",
"=",
"np",
".",
"append",
"(",
"[",
"True",
"]",
",",
"X",
"[",
"1",
":",
"]",
"!=",
... | 28.210526 | 25.473684 |
def obj_to_str(self, file_path=None, deliminator=None, tab=None,
quote_numbers=True, quote_empty_str=False):
"""
This will return a simple str table.
:param file_path: str of the path to the file
:param keys: list of str of the order of keys to use
... | [
"def",
"obj_to_str",
"(",
"self",
",",
"file_path",
"=",
"None",
",",
"deliminator",
"=",
"None",
",",
"tab",
"=",
"None",
",",
"quote_numbers",
"=",
"True",
",",
"quote_empty_str",
"=",
"False",
")",
":",
"deliminator",
"=",
"self",
".",
"deliminator",
... | 47.769231 | 18.923077 |
def rebuildGrid( self ):
"""
Rebuilds the ruler data.
"""
vruler = self.verticalRuler()
hruler = self.horizontalRuler()
rect = self._buildData['grid_rect']
# process the vertical ruler
h_lines = []
h_alt = [... | [
"def",
"rebuildGrid",
"(",
"self",
")",
":",
"vruler",
"=",
"self",
".",
"verticalRuler",
"(",
")",
"hruler",
"=",
"self",
".",
"horizontalRuler",
"(",
")",
"rect",
"=",
"self",
".",
"_buildData",
"[",
"'grid_rect'",
"]",
"# process the vertical ruler\r",
"h... | 35.473684 | 13.978947 |
def wr_ann_file(self, write_fs, write_dir=''):
"""
Calculate the bytes used to encode an annotation set and
write them to an annotation file
"""
# Calculate the fs bytes to write if present and desired to write
if write_fs:
fs_bytes = self.calc_fs_bytes()
... | [
"def",
"wr_ann_file",
"(",
"self",
",",
"write_fs",
",",
"write_dir",
"=",
"''",
")",
":",
"# Calculate the fs bytes to write if present and desired to write",
"if",
"write_fs",
":",
"fs_bytes",
"=",
"self",
".",
"calc_fs_bytes",
"(",
")",
"else",
":",
"fs_bytes",
... | 38.9 | 21.433333 |
def run_program(self, name, arguments=[], timeout=30, exclusive=False):
"""Runs a program in the working directory to completion.
Args:
name (str): The name of the program to be executed.
arguments (tuple): Command-line arguments for the program.
timeout (int)... | [
"def",
"run_program",
"(",
"self",
",",
"name",
",",
"arguments",
"=",
"[",
"]",
",",
"timeout",
"=",
"30",
",",
"exclusive",
"=",
"False",
")",
":",
"logger",
".",
"debug",
"(",
"\"Running program ...\"",
")",
"if",
"exclusive",
":",
"kill_longrunning",
... | 43.571429 | 22.619048 |
def init_parser():
""" Initialize the arguments parser. """
parser = argparse.ArgumentParser(
description="Automated development environment initialization")
parser.add_argument('--version', action='version',
version='%(prog)s ' + __version__)
subparsers = parser.add_subparsers(title="... | [
"def",
"init_parser",
"(",
")",
":",
"parser",
"=",
"argparse",
".",
"ArgumentParser",
"(",
"description",
"=",
"\"Automated development environment initialization\"",
")",
"parser",
".",
"add_argument",
"(",
"'--version'",
",",
"action",
"=",
"'version'",
",",
"ver... | 36.756757 | 22.432432 |
def iter_poll(self, query_id=None, sequence_no=None, params=None,
**kwargs): # pragma: no cover
"""Retrieve pages iteratively in a non-greedy manner.
Automatically increments the sequenceNo as it continues to poll
for results until the endpoint reports JOB_FINISHED or
... | [
"def",
"iter_poll",
"(",
"self",
",",
"query_id",
"=",
"None",
",",
"sequence_no",
"=",
"None",
",",
"params",
"=",
"None",
",",
"*",
"*",
"kwargs",
")",
":",
"# pragma: no cover",
"while",
"True",
":",
"r",
"=",
"self",
".",
"poll",
"(",
"query_id",
... | 35.844444 | 20.377778 |
def pdfdump(self, filename=None, **kargs):
"""pdfdump(filename=None, layer_shift=0, rebuild=1)
Creates a PDF file describing a packet. If filename is not provided a temporary file is created and xpdf is called."""
canvas = self.canvas_dump(**kargs)
if filename is None:
fname ... | [
"def",
"pdfdump",
"(",
"self",
",",
"filename",
"=",
"None",
",",
"*",
"*",
"kargs",
")",
":",
"canvas",
"=",
"self",
".",
"canvas_dump",
"(",
"*",
"*",
"kargs",
")",
"if",
"filename",
"is",
"None",
":",
"fname",
"=",
"get_temp_file",
"(",
"autoext",... | 50.3 | 8 |
def h2o_explained_variance_score(y_actual, y_predicted, weights=None):
"""
Explained variance regression score function.
:param y_actual: H2OFrame of actual response.
:param y_predicted: H2OFrame of predicted response.
:param weights: (Optional) sample weights
:returns: the explained variance s... | [
"def",
"h2o_explained_variance_score",
"(",
"y_actual",
",",
"y_predicted",
",",
"weights",
"=",
"None",
")",
":",
"ModelBase",
".",
"_check_targets",
"(",
"y_actual",
",",
"y_predicted",
")",
"_",
",",
"numerator",
"=",
"_mean_var",
"(",
"y_actual",
"-",
"y_p... | 38.6875 | 14.8125 |
def paintEvent( self, event ):
"""
Overloads the paint event for this group box if it is currently
collpased.
:param event | <QPaintEvent>
"""
if ( self.isCollapsed() ):
self.setFlat(True)
elif ( self.isCollapsible() ):... | [
"def",
"paintEvent",
"(",
"self",
",",
"event",
")",
":",
"if",
"(",
"self",
".",
"isCollapsed",
"(",
")",
")",
":",
"self",
".",
"setFlat",
"(",
"True",
")",
"elif",
"(",
"self",
".",
"isCollapsible",
"(",
")",
")",
":",
"self",
".",
"setFlat",
... | 28.857143 | 13.142857 |
def p_moduleComplianceClause(self, p):
"""moduleComplianceClause : LOWERCASE_IDENTIFIER MODULE_COMPLIANCE STATUS Status DESCRIPTION Text ReferPart ComplianceModulePart COLON_COLON_EQUAL '{' objectIdentifier '}'"""
p[0] = ('moduleComplianceClause',
p[1], # id
# p[2], # M... | [
"def",
"p_moduleComplianceClause",
"(",
"self",
",",
"p",
")",
":",
"p",
"[",
"0",
"]",
"=",
"(",
"'moduleComplianceClause'",
",",
"p",
"[",
"1",
"]",
",",
"# id",
"# p[2], # MODULE_COMPLIANCE",
"p",
"[",
"4",
"]",
",",
"# status",
"(",
"p",
"[",
"5",... | 50.5 | 5.9 |
def crop_or_pad(im, size, value=0):
"""
Crops an image in the center.
Parameters
----------
size : tuple, (height, width)
Finally size after cropping.
"""
diff = [im.shape[index] - size[index] for index in (0, 1)]
im2 = im[diff[0]//2:diff[0]//2 + size[0], diff[1]//2:diff[1]//2 +... | [
"def",
"crop_or_pad",
"(",
"im",
",",
"size",
",",
"value",
"=",
"0",
")",
":",
"diff",
"=",
"[",
"im",
".",
"shape",
"[",
"index",
"]",
"-",
"size",
"[",
"index",
"]",
"for",
"index",
"in",
"(",
"0",
",",
"1",
")",
"]",
"im2",
"=",
"im",
"... | 27.75 | 16.75 |
def use_isolated_vault_view(self):
"""Pass through to provider AuthorizationLookupSession.use_isolated_vault_view"""
self._vault_view = ISOLATED
# self._get_provider_session('authorization_lookup_session') # To make sure the session is tracked
for session in self._get_provider_sessions()... | [
"def",
"use_isolated_vault_view",
"(",
"self",
")",
":",
"self",
".",
"_vault_view",
"=",
"ISOLATED",
"# self._get_provider_session('authorization_lookup_session') # To make sure the session is tracked",
"for",
"session",
"in",
"self",
".",
"_get_provider_sessions",
"(",
")",
... | 48.444444 | 16.555556 |
def sens_from_spec(spec, labels, scores, *args, **kwargs):
r"""Find the sensitivity that corresponds to the indicated specificity (ROC function)
sensitivity = Num_True_Positive / (Num_True_Postive + Num_False_Negative)
specificity = Num_True_Negative / (Num_True_Negative + Num_False_Positive)
"""
th... | [
"def",
"sens_from_spec",
"(",
"spec",
",",
"labels",
",",
"scores",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"thresh",
"=",
"thresh_from_spec",
"(",
"spec",
",",
"labels",
",",
"scores",
")",
"df",
"=",
"pd",
".",
"DataFrame",
"(",
"list"... | 56.333333 | 16.777778 |
def _init_client(self, from_archive=False):
"""Init client"""
return ConduitClient(self.url, self.api_token,
self.max_retries, self.sleep_time,
self.archive, from_archive) | [
"def",
"_init_client",
"(",
"self",
",",
"from_archive",
"=",
"False",
")",
":",
"return",
"ConduitClient",
"(",
"self",
".",
"url",
",",
"self",
".",
"api_token",
",",
"self",
".",
"max_retries",
",",
"self",
".",
"sleep_time",
",",
"self",
".",
"archiv... | 40.166667 | 16 |
def set_status(self, action, target):
"""
Sets query status with format: "{domain} ({action}) {target}"
"""
try:
target = unquote(target)
except (AttributeError, TypeError):
pass
status = "%s (%s) %s" % (self.domain, action, target)
status... | [
"def",
"set_status",
"(",
"self",
",",
"action",
",",
"target",
")",
":",
"try",
":",
"target",
"=",
"unquote",
"(",
"target",
")",
"except",
"(",
"AttributeError",
",",
"TypeError",
")",
":",
"pass",
"status",
"=",
"\"%s (%s) %s\"",
"%",
"(",
"self",
... | 31.222222 | 15.555556 |
def GetPluginObjects(cls, plugin_names):
"""Retrieves the plugin objects.
Args:
plugin_names (list[str]): names of plugins that should be retrieved.
Returns:
dict[str, AnalysisPlugin]: analysis plugins per name.
"""
plugin_objects = {}
for plugin_name, plugin_class in iter(cls._plu... | [
"def",
"GetPluginObjects",
"(",
"cls",
",",
"plugin_names",
")",
":",
"plugin_objects",
"=",
"{",
"}",
"for",
"plugin_name",
",",
"plugin_class",
"in",
"iter",
"(",
"cls",
".",
"_plugin_classes",
".",
"items",
"(",
")",
")",
":",
"if",
"plugin_name",
"not"... | 27.235294 | 21.764706 |
def request_name(self):
"""Generate the name of the request."""
if self.static and not self.uses_request:
return 'Empty'
if not self.uses_request:
return None
if isinstance(self.uses_request, str):
return self.uses_request
return to_camel_ca... | [
"def",
"request_name",
"(",
"self",
")",
":",
"if",
"self",
".",
"static",
"and",
"not",
"self",
".",
"uses_request",
":",
"return",
"'Empty'",
"if",
"not",
"self",
".",
"uses_request",
":",
"return",
"None",
"if",
"isinstance",
"(",
"self",
".",
"uses_r... | 27.833333 | 17.083333 |
def caption_hashtags(self) -> List[str]:
"""List of all lowercased hashtags (without preceeding #) that occur in the Post's caption."""
if not self.caption:
return []
# This regular expression is from jStassen, adjusted to use Python's \w to support Unicode
# http://blog.jsta... | [
"def",
"caption_hashtags",
"(",
"self",
")",
"->",
"List",
"[",
"str",
"]",
":",
"if",
"not",
"self",
".",
"caption",
":",
"return",
"[",
"]",
"# This regular expression is from jStassen, adjusted to use Python's \\w to support Unicode",
"# http://blog.jstassen.com/2016/03/... | 65.625 | 25.625 |
def convert_environment(datadir, version, always_yes):
"""
Converts an environment TO the version specified by `version`.
:param datadir: The datadir to convert.
:param version: The version to convert TO.
:param always_yes: True if the user shouldn't be prompted about the migration.
"""
# Si... | [
"def",
"convert_environment",
"(",
"datadir",
",",
"version",
",",
"always_yes",
")",
":",
"# Since we don't call either load() or new() we have to call require_images ourselves.",
"require_images",
"(",
")",
"inp",
"=",
"None",
"old_version",
"=",
"_get_current_format",
"(",... | 35.615385 | 22.230769 |
def tspace_type(space, impl, dtype=None):
"""Select the correct corresponding tensor space.
Parameters
----------
space : `LinearSpace`
Template space from which to infer an adequate tensor space. If
it has a ``field`` attribute, ``dtype`` must be consistent with it.
impl : string
... | [
"def",
"tspace_type",
"(",
"space",
",",
"impl",
",",
"dtype",
"=",
"None",
")",
":",
"field_type",
"=",
"type",
"(",
"getattr",
"(",
"space",
",",
"'field'",
",",
"None",
")",
")",
"if",
"dtype",
"is",
"None",
":",
"pass",
"elif",
"is_real_floating_dt... | 41.291667 | 22.125 |
def _z2deriv(self,R,z,phi=0.,t=0.): #pragma: no cover
"""
NAME:
_z2deriv
PURPOSE:
evaluate the second vertical derivative for this potential
INPUT:
R - Galactocentric cylindrical radius
z - vertical height
phi - azimuth
t ... | [
"def",
"_z2deriv",
"(",
"self",
",",
"R",
",",
"z",
",",
"phi",
"=",
"0.",
",",
"t",
"=",
"0.",
")",
":",
"#pragma: no cover",
"raise",
"AttributeError",
"# Implementation above does not work bc SCF.z2deriv is not implemented",
"r",
"=",
"numpy",
".",
"sqrt",
"(... | 38.5 | 18.730769 |
def create(verbose):
"""Create tables."""
click.secho('Creating all tables!', fg='yellow', bold=True)
with click.progressbar(_db.metadata.sorted_tables) as bar:
for table in bar:
if verbose:
click.echo(' Creating table {0}'.format(table))
table.create(bind=_db... | [
"def",
"create",
"(",
"verbose",
")",
":",
"click",
".",
"secho",
"(",
"'Creating all tables!'",
",",
"fg",
"=",
"'yellow'",
",",
"bold",
"=",
"True",
")",
"with",
"click",
".",
"progressbar",
"(",
"_db",
".",
"metadata",
".",
"sorted_tables",
")",
"as",... | 42.2 | 15.4 |
def range(self, start=0, end=None, predicate=None, index=None):
"""
Retrieves a set of Match objects that are available in given range, sorted from start to end.
:param start: the starting index
:type start: int
:param end: the ending index
:type end: int
:param p... | [
"def",
"range",
"(",
"self",
",",
"start",
"=",
"0",
",",
"end",
"=",
"None",
",",
"predicate",
"=",
"None",
",",
"index",
"=",
"None",
")",
":",
"if",
"end",
"is",
"None",
":",
"end",
"=",
"self",
".",
"max_end",
"else",
":",
"end",
"=",
"min"... | 33.521739 | 13.434783 |
def run_filter_calculation(self):
"""Run the CifFilterCalculation on the CifData input node."""
inputs = {
'cif': self.inputs.cif,
'code': self.inputs.cif_filter,
'parameters': self.inputs.cif_filter_parameters,
'metadata': {
'options': sel... | [
"def",
"run_filter_calculation",
"(",
"self",
")",
":",
"inputs",
"=",
"{",
"'cif'",
":",
"self",
".",
"inputs",
".",
"cif",
",",
"'code'",
":",
"self",
".",
"inputs",
".",
"cif_filter",
",",
"'parameters'",
":",
"self",
".",
"inputs",
".",
"cif_filter_p... | 38.066667 | 21.066667 |
def concurrent_slots(slots):
"""
Yields all concurrent slot indices.
"""
for i, slot in enumerate(slots):
for j, other_slot in enumerate(slots[i + 1:]):
if slots_overlap(slot, other_slot):
yield (i, j + i + 1) | [
"def",
"concurrent_slots",
"(",
"slots",
")",
":",
"for",
"i",
",",
"slot",
"in",
"enumerate",
"(",
"slots",
")",
":",
"for",
"j",
",",
"other_slot",
"in",
"enumerate",
"(",
"slots",
"[",
"i",
"+",
"1",
":",
"]",
")",
":",
"if",
"slots_overlap",
"(... | 31.75 | 5.25 |
def process_next_message(self, timeout):
"""Processes the next message coming from the workers."""
message = self.worker_manager.receive(timeout)
if isinstance(message, Acknowledgement):
self.task_manager.task_start(message.task, message.worker)
elif isinstance(message, Resu... | [
"def",
"process_next_message",
"(",
"self",
",",
"timeout",
")",
":",
"message",
"=",
"self",
".",
"worker_manager",
".",
"receive",
"(",
"timeout",
")",
"if",
"isinstance",
"(",
"message",
",",
"Acknowledgement",
")",
":",
"self",
".",
"task_manager",
".",
... | 48.375 | 15.25 |
def tmpl_alphanum(self, text):
"""
* synopsis: ``%alphanum{text}``
* description: This function first ASCIIfies the given text, then all \
non alpanumeric characters are replaced with whitespaces.
"""
text = self.tmpl_asciify(text)
text = re.sub(r'[^a-zA-Z0-9]... | [
"def",
"tmpl_alphanum",
"(",
"self",
",",
"text",
")",
":",
"text",
"=",
"self",
".",
"tmpl_asciify",
"(",
"text",
")",
"text",
"=",
"re",
".",
"sub",
"(",
"r'[^a-zA-Z0-9]+'",
",",
"' '",
",",
"text",
")",
"return",
"re",
".",
"sub",
"(",
"r'\\s+'",
... | 40.777778 | 10.111111 |
def make_middleware_stack(middleware, base):
"""
Given a list of in-order middleware callable objects `middleware` and a base function `base`, chains them
together so each middleware is fed the function below, and returns the top level ready to call.
:param middleware: The middleware st... | [
"def",
"make_middleware_stack",
"(",
"middleware",
",",
"base",
")",
":",
"for",
"ware",
"in",
"reversed",
"(",
"middleware",
")",
":",
"base",
"=",
"ware",
"(",
"base",
")",
"return",
"base"
] | 44.529412 | 24.411765 |
def unnest_children(data, parent_name='', pk_name=None, force_pk=False):
"""
For each ``key`` in each row of ``data`` (which must be a list of dicts),
unnest any dict values into ``parent``, and remove list values into separate lists.
Return (``data``, ``pk_name``, ``children``, ``child_fk_names``) whe... | [
"def",
"unnest_children",
"(",
"data",
",",
"parent_name",
"=",
"''",
",",
"pk_name",
"=",
"None",
",",
"force_pk",
"=",
"False",
")",
":",
"possible_fk_names",
"=",
"[",
"'%s_id'",
"%",
"parent_name",
",",
"'_%s_id'",
"%",
"parent_name",
",",
"'parent_id'",... | 45.517857 | 22.232143 |
def inserir(self, id_script_type, script, model, description):
"""Inserts a new Script and returns its identifier.
:param id_script_type: Identifier of the Script Type. Integer value and greater than zero.
:param script: Script name. String with a minimum 3 and maximum of 40 characters
... | [
"def",
"inserir",
"(",
"self",
",",
"id_script_type",
",",
"script",
",",
"model",
",",
"description",
")",
":",
"script_map",
"=",
"dict",
"(",
")",
"script_map",
"[",
"'id_script_type'",
"]",
"=",
"id_script_type",
"script_map",
"[",
"'script'",
"]",
"=",
... | 44.571429 | 28.642857 |
def _render_conditions(conditions):
"""Render the conditions part of a query.
Parameters
----------
conditions : list
A list of dictionary items to filter a table.
Returns
-------
str
A string that represents the "where" part of a query
See Also
--------
render... | [
"def",
"_render_conditions",
"(",
"conditions",
")",
":",
"if",
"not",
"conditions",
":",
"return",
"\"\"",
"rendered_conditions",
"=",
"[",
"]",
"for",
"condition",
"in",
"conditions",
":",
"field",
"=",
"condition",
".",
"get",
"(",
"'field'",
")",
"field_... | 24.717949 | 23.538462 |
def stepper_step(self, motor_speed, number_of_steps):
"""
Move a stepper motor for the number of steps at the specified speed
:param motor_speed: 21 bits of data to set motor speed
:param number_of_steps: 14 bits for number of steps & direction
positive ... | [
"def",
"stepper_step",
"(",
"self",
",",
"motor_speed",
",",
"number_of_steps",
")",
":",
"if",
"number_of_steps",
">",
"0",
":",
"direction",
"=",
"1",
"else",
":",
"direction",
"=",
"0",
"abs_number_of_steps",
"=",
"abs",
"(",
"number_of_steps",
")",
"data... | 45.823529 | 26.411765 |
def set_main_fan(self, main_fan):
"""Set the main fan config.
:param main_fan: Value to set the main fan
:type main_fan: int [0-10]
:returns: None
:raises: InvalidInput
"""
if type(main_fan) != int and main_fan not in range(0, 11):
raise InvalidInput(... | [
"def",
"set_main_fan",
"(",
"self",
",",
"main_fan",
")",
":",
"if",
"type",
"(",
"main_fan",
")",
"!=",
"int",
"and",
"main_fan",
"not",
"in",
"range",
"(",
"0",
",",
"11",
")",
":",
"raise",
"InvalidInput",
"(",
"\"Main fan value must be int between 0-10\"... | 35.75 | 13.416667 |
def do_serialize(self, line):
"""Serialize an entity into an RDF flavour"""
opts = self.SERIALIZE_OPTS
if not self.current:
self._help_noontology()
return
line = line.split()
g = self.current['graph']
if not line:
line = ['turtle']
... | [
"def",
"do_serialize",
"(",
"self",
",",
"line",
")",
":",
"opts",
"=",
"self",
".",
"SERIALIZE_OPTS",
"if",
"not",
"self",
".",
"current",
":",
"self",
".",
"_help_noontology",
"(",
")",
"return",
"line",
"=",
"line",
".",
"split",
"(",
")",
"g",
"=... | 23.913043 | 19.869565 |
def writeCommit(self, varBind, **context):
"""Commit new value of the Managed Object Instance.
Implements the second of the multi-step workflow of the SNMP SET
command processing (:RFC:`1905#section-4.2.5`).
The goal of the second phase is to actually modify the requested Managed
... | [
"def",
"writeCommit",
"(",
"self",
",",
"varBind",
",",
"*",
"*",
"context",
")",
":",
"name",
",",
"val",
"=",
"varBind",
"(",
"debug",
".",
"logger",
"&",
"debug",
".",
"FLAG_INS",
"and",
"debug",
".",
"logger",
"(",
"'%s: writeCommit(%s, %r)'",
"%",
... | 37.393939 | 27.606061 |
def basic_set_of_users_exists_in_the_database(context):
"""
:type context: behave.runner.Context
"""
user_model = get_user_model()
user_model.objects.create(
username='administrator',
is_staff=True
)
user_model.objects.create(
username='allowed_user'
)
... | [
"def",
"basic_set_of_users_exists_in_the_database",
"(",
"context",
")",
":",
"user_model",
"=",
"get_user_model",
"(",
")",
"user_model",
".",
"objects",
".",
"create",
"(",
"username",
"=",
"'administrator'",
",",
"is_staff",
"=",
"True",
")",
"user_model",
".",... | 25.266667 | 12.733333 |
def insert_column(self, index, header, column):
"""Insert a column before `index` in the table.
If length of column is bigger than number of rows, lets say
`k`, only the first `k` values of `column` is considered.
If column is shorter than 'k', ValueError is raised.
Note that T... | [
"def",
"insert_column",
"(",
"self",
",",
"index",
",",
"header",
",",
"column",
")",
":",
"if",
"self",
".",
"_column_count",
"==",
"0",
":",
"self",
".",
"column_headers",
"=",
"HeaderData",
"(",
"self",
",",
"[",
"header",
"]",
")",
"self",
".",
"... | 40.259259 | 21.444444 |
def make_inaturalist_api_get_call(endpoint: str, params: Dict, **kwargs) -> requests.Response:
"""Make an API call to iNaturalist.
endpoint is a string such as 'observations' !! do not put / in front
method: 'GET', 'HEAD', 'POST', 'PUT', 'PATCH', 'DELETE'
kwargs are passed to requests.request
Retur... | [
"def",
"make_inaturalist_api_get_call",
"(",
"endpoint",
":",
"str",
",",
"params",
":",
"Dict",
",",
"*",
"*",
"kwargs",
")",
"->",
"requests",
".",
"Response",
":",
"headers",
"=",
"{",
"'Accept'",
":",
"'application/json'",
"}",
"response",
"=",
"requests... | 43.166667 | 23.166667 |
def physical_name(self):
"""The physical name of the seat.
For libinput contexts created from udev, this is always the same value
as passed into :meth:`~libinput.LibInputUdev.assign_seat` and all
seats from that context will have the same physical name.
The physical name of the seat is one that is usually s... | [
"def",
"physical_name",
"(",
"self",
")",
":",
"pchar",
"=",
"self",
".",
"_libinput",
".",
"libinput_seat_get_physical_name",
"(",
"self",
".",
"_handle",
")",
"return",
"string_at",
"(",
"pchar",
")",
".",
"decode",
"(",
")"
] | 36.722222 | 23.388889 |
def set_group_kick(self, *, group_id, user_id, reject_add_request=False):
"""
群组踢人
------------
:param int group_id: 群号
:param int user_id: 要踢的 QQ 号
:param bool reject_add_request: 拒绝此人的加群请求
:return: None
:rtype: None
"""
return super()._... | [
"def",
"set_group_kick",
"(",
"self",
",",
"*",
",",
"group_id",
",",
"user_id",
",",
"reject_add_request",
"=",
"False",
")",
":",
"return",
"super",
"(",
")",
".",
"__getattr__",
"(",
"'set_group_kick'",
")",
"(",
"group_id",
"=",
"group_id",
",",
"user_... | 30.357143 | 20.214286 |
def drawSector(self, center, point, beta, fullSector=True):
"""Draw a circle sector.
"""
center = Point(center)
point = Point(point)
l3 = "%g %g m\n"
l4 = "%g %g %g %g %g %g c\n"
l5 = "%g %g l\n"
betar = math.radians(-beta)
w360 = math.radians(math... | [
"def",
"drawSector",
"(",
"self",
",",
"center",
",",
"point",
",",
"beta",
",",
"fullSector",
"=",
"True",
")",
":",
"center",
"=",
"Point",
"(",
"center",
")",
"point",
"=",
"Point",
"(",
"point",
")",
"l3",
"=",
"\"%g %g m\\n\"",
"l4",
"=",
"\"%g ... | 50.441176 | 20.75 |
def clear_muc_child(self):
"""
Remove the MUC specific stanza payload element.
"""
if self.muc_child:
self.muc_child.free_borrowed()
self.muc_child=None
if not self.xmlnode.children:
return
n=self.xmlnode.children
while n:
... | [
"def",
"clear_muc_child",
"(",
"self",
")",
":",
"if",
"self",
".",
"muc_child",
":",
"self",
".",
"muc_child",
".",
"free_borrowed",
"(",
")",
"self",
".",
"muc_child",
"=",
"None",
"if",
"not",
"self",
".",
"xmlnode",
".",
"children",
":",
"return",
... | 29.130435 | 12.869565 |
def great_circle_vec(lat1, lng1, lat2, lng2, earth_radius=6371009):
"""
Vectorized function to calculate the great-circle distance between two
points or between vectors of points, using haversine.
Parameters
----------
lat1 : float or array of float
lng1 : float or array of float
lat2 :... | [
"def",
"great_circle_vec",
"(",
"lat1",
",",
"lng1",
",",
"lat2",
",",
"lng2",
",",
"earth_radius",
"=",
"6371009",
")",
":",
"phi1",
"=",
"np",
".",
"deg2rad",
"(",
"lat1",
")",
"phi2",
"=",
"np",
".",
"deg2rad",
"(",
"lat2",
")",
"d_phi",
"=",
"p... | 29.315789 | 21.210526 |
def asdict(self):
"""Encode the data in this reading into a dictionary.
Returns:
dict: A dictionary containing the information from this reading.
"""
timestamp_str = None
if self.reading_time is not None:
timestamp_str = self.reading_time.isoformat()
... | [
"def",
"asdict",
"(",
"self",
")",
":",
"timestamp_str",
"=",
"None",
"if",
"self",
".",
"reading_time",
"is",
"not",
"None",
":",
"timestamp_str",
"=",
"self",
".",
"reading_time",
".",
"isoformat",
"(",
")",
"return",
"{",
"'stream'",
":",
"self",
".",... | 29.5 | 17.722222 |
def create(self, data):
"""Create a new component
"""
response = self.http.post(str(self), json=data, auth=self.auth)
response.raise_for_status()
return response.json() | [
"def",
"create",
"(",
"self",
",",
"data",
")",
":",
"response",
"=",
"self",
".",
"http",
".",
"post",
"(",
"str",
"(",
"self",
")",
",",
"json",
"=",
"data",
",",
"auth",
"=",
"self",
".",
"auth",
")",
"response",
".",
"raise_for_status",
"(",
... | 33.833333 | 10.5 |
def auto_update_attrs_from_kwargs(method):
""" this decorator will update the attributes of an
instance object with all the kwargs of the decorated
method, updated with the kwargs of the actual call.
This saves you from boring typing:
self.xxxx = xxxx
self.yyyy = yyyy
...
in the d... | [
"def",
"auto_update_attrs_from_kwargs",
"(",
"method",
")",
":",
"def",
"wrapped",
"(",
"self",
",",
"*",
"*",
"kwargs",
")",
":",
"# method signature introspection",
"argspec",
"=",
"inspect",
".",
"getargspec",
"(",
"method",
")",
"defaults",
"=",
"argspec",
... | 36.36 | 13.48 |
def logical_not(f): # function factory
'''Logical not from functions.
Parameters
----------
f1, f2 : function
Function that takes array and returns true or false for each item in array.
Returns
-------
Function.
'''
def f(value):
return np.logical_not(... | [
"def",
"logical_not",
"(",
"f",
")",
":",
"# function factory\r",
"def",
"f",
"(",
"value",
")",
":",
"return",
"np",
".",
"logical_not",
"(",
"f",
"(",
"value",
")",
")",
"f",
".",
"__name__",
"=",
"\"not_\"",
"+",
"f",
".",
"__name__",
"return",
"f... | 22.875 | 22.625 |
def from_string(cls, string):
"""
Parse ``string`` into a CPPType instance
"""
cls.TYPE.setParseAction(cls.make)
try:
return cls.TYPE.parseString(string, parseAll=True)[0]
except ParseException:
log.error("Failed to parse '{0}'".format(string))
... | [
"def",
"from_string",
"(",
"cls",
",",
"string",
")",
":",
"cls",
".",
"TYPE",
".",
"setParseAction",
"(",
"cls",
".",
"make",
")",
"try",
":",
"return",
"cls",
".",
"TYPE",
".",
"parseString",
"(",
"string",
",",
"parseAll",
"=",
"True",
")",
"[",
... | 32.5 | 12.7 |
def inTrace(self, func: callable): # decorator
"""将被修饰函数的进入和退出写入日志"""
@wraps(func)
def call(*args, **kwargs):
self.TRACE("Enter " + func.__qualname__ + "()")
result = func(*args, **kwargs)
self.TRACE("Leave " + func.__qualname__ + "()")
return res... | [
"def",
"inTrace",
"(",
"self",
",",
"func",
":",
"callable",
")",
":",
"# decorator",
"@",
"wraps",
"(",
"func",
")",
"def",
"call",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"self",
".",
"TRACE",
"(",
"\"Enter \"",
"+",
"func",
".",
"... | 37.222222 | 12.111111 |
def hostname():
'''
Return fqdn, hostname, domainname
'''
# This is going to need some work
# Provides:
# fqdn
# host
# localhost
# domain
global __FQDN__
grains = {}
if salt.utils.platform.is_proxy():
return grains
grains['localhost'] = socket.getho... | [
"def",
"hostname",
"(",
")",
":",
"# This is going to need some work",
"# Provides:",
"# fqdn",
"# host",
"# localhost",
"# domain",
"global",
"__FQDN__",
"grains",
"=",
"{",
"}",
"if",
"salt",
".",
"utils",
".",
"platform",
".",
"is_proxy",
"(",
")",
":... | 31.21875 | 23.03125 |
def generate(variables, steps, final_outputs):
"""Generate all of the components of a CWL workflow from input steps.
file_vs and std_vs are the list of world variables, split into those that
reference files (and need declaration at each step) and those that don't
and can be safely passed to each step. ... | [
"def",
"generate",
"(",
"variables",
",",
"steps",
",",
"final_outputs",
")",
":",
"file_vs",
",",
"std_vs",
"=",
"_split_variables",
"(",
"[",
"_flatten_nested_input",
"(",
"v",
")",
"for",
"v",
"in",
"variables",
"]",
")",
"parallel_ids",
"=",
"[",
"]",
... | 63.125 | 30.339286 |
def solve(self):
"""Start (or re-start) optimisation. This method implements the
framework for the alternation between `X` and `D` updates in a
dictionary learning algorithm. There is sufficient flexibility
in specifying the two updates that it calls that it is
usually not necess... | [
"def",
"solve",
"(",
"self",
")",
":",
"# Print header and separator strings",
"if",
"self",
".",
"opt",
"[",
"'Verbose'",
"]",
"and",
"self",
".",
"opt",
"[",
"'StatusHeader'",
"]",
":",
"self",
".",
"isc",
".",
"printheader",
"(",
")",
"# Reset timer",
"... | 36.786517 | 21.775281 |
def send_msg_to_clients(client_ids, msg, error=False):
"""Send message to all clients"""
if error:
stream = "stderr"
else:
stream = "stdout"
response = [{"message": None, "type": "console", "payload": msg, "stream": stream}]
for client_id in client_ids:
logger.info("emiting... | [
"def",
"send_msg_to_clients",
"(",
"client_ids",
",",
"msg",
",",
"error",
"=",
"False",
")",
":",
"if",
"error",
":",
"stream",
"=",
"\"stderr\"",
"else",
":",
"stream",
"=",
"\"stdout\"",
"response",
"=",
"[",
"{",
"\"message\"",
":",
"None",
",",
"\"t... | 33.285714 | 25.642857 |
def NHot(n, *xs, simplify=True):
"""
Return an expression that means
"exactly N input functions are true".
If *simplify* is ``True``, return a simplified expression.
"""
if not isinstance(n, int):
raise TypeError("expected n to be an int")
if not 0 <= n <= len(xs):
fstr = "e... | [
"def",
"NHot",
"(",
"n",
",",
"*",
"xs",
",",
"simplify",
"=",
"True",
")",
":",
"if",
"not",
"isinstance",
"(",
"n",
",",
"int",
")",
":",
"raise",
"TypeError",
"(",
"\"expected n to be an int\"",
")",
"if",
"not",
"0",
"<=",
"n",
"<=",
"len",
"("... | 31.36 | 13.6 |
def _serialize(self, include_run_logs=False, strict_json=False):
""" Serialize a representation of this Task to a Python dict. """
result = {'command': self.command,
'name': self.name,
'started_at': self.started_at,
'completed_at': self.completed_at... | [
"def",
"_serialize",
"(",
"self",
",",
"include_run_logs",
"=",
"False",
",",
"strict_json",
"=",
"False",
")",
":",
"result",
"=",
"{",
"'command'",
":",
"self",
".",
"command",
",",
"'name'",
":",
"self",
".",
"name",
",",
"'started_at'",
":",
"self",
... | 41.956522 | 18 |
def default_blockstack_api_opts(working_dir, config_file=None):
"""
Get our default blockstack RESTful API opts from a config file,
or from sane defaults.
"""
from .util import url_to_host_port, url_protocol
if config_file is None:
config_file = virtualchain.get_config_filename(get_default_vir... | [
"def",
"default_blockstack_api_opts",
"(",
"working_dir",
",",
"config_file",
"=",
"None",
")",
":",
"from",
".",
"util",
"import",
"url_to_host_port",
",",
"url_protocol",
"if",
"config_file",
"is",
"None",
":",
"config_file",
"=",
"virtualchain",
".",
"get_confi... | 31.8 | 23.4 |
def create_user_permission(self,
name,
vhost,
configure=None,
write=None,
read=None):
"""
Create a user permission
:param name: The user's na... | [
"def",
"create_user_permission",
"(",
"self",
",",
"name",
",",
"vhost",
",",
"configure",
"=",
"None",
",",
"write",
"=",
"None",
",",
"read",
"=",
"None",
")",
":",
"data",
"=",
"{",
"'configure'",
":",
"configure",
"or",
"'.*'",
",",
"'write'",
":",... | 33.28125 | 14.21875 |
def _HasId(self, schedule, entity_id):
"""Check if the schedule has an entity with the given id.
Args:
schedule: The transitfeed.Schedule instance to look in.
entity_id: The id of the entity.
Returns:
True if the schedule has an entity with the id or False if not.
"""
try:
... | [
"def",
"_HasId",
"(",
"self",
",",
"schedule",
",",
"entity_id",
")",
":",
"try",
":",
"self",
".",
"_GetById",
"(",
"schedule",
",",
"entity_id",
")",
"has",
"=",
"True",
"except",
"KeyError",
":",
"has",
"=",
"False",
"return",
"has"
] | 25.625 | 19.875 |
def get_user_choice(items):
'''Returns the selected item from provided items or None if 'q' was
entered for quit.
'''
choice = raw_input('Choose an item or "q" to quit: ')
while choice != 'q':
try:
item = items[int(choice)]
print # Blank line for readability between ... | [
"def",
"get_user_choice",
"(",
"items",
")",
":",
"choice",
"=",
"raw_input",
"(",
"'Choose an item or \"q\" to quit: '",
")",
"while",
"choice",
"!=",
"'q'",
":",
"try",
":",
"item",
"=",
"items",
"[",
"int",
"(",
"choice",
")",
"]",
"print",
"# Blank line ... | 43.631579 | 22.789474 |
def convert(self, request, response, data):
"""
Performs the desired Conversion.
:param request: The webob Request object describing the
request.
:param response: The webob Response object describing the
response.
:param data: The... | [
"def",
"convert",
"(",
"self",
",",
"request",
",",
"response",
",",
"data",
")",
":",
"size",
"=",
"response",
".",
"content_length",
"if",
"not",
"size",
":",
"size",
"=",
"\"-\"",
"if",
"self",
".",
"conv_chr",
"==",
"'b'",
"else",
"0",
"return",
... | 31.05 | 17.45 |
def ClientCertFromCSR(cls, csr):
"""Creates a new cert for the given common name.
Args:
csr: A CertificateSigningRequest.
Returns:
The signed cert.
"""
builder = x509.CertificateBuilder()
# Use the client CN for a cert serial_id. This will ensure we do
# not have clashing cert ... | [
"def",
"ClientCertFromCSR",
"(",
"cls",
",",
"csr",
")",
":",
"builder",
"=",
"x509",
".",
"CertificateBuilder",
"(",
")",
"# Use the client CN for a cert serial_id. This will ensure we do",
"# not have clashing cert id.",
"common_name",
"=",
"csr",
".",
"GetCN",
"(",
"... | 36.046512 | 14.767442 |
def custom_to_radec(phi1,phi2,T=None,degree=False):
"""
NAME:
custom_to_radec
PURPOSE:
rotate a custom set of sky coordinates (phi1, phi2) to (ra, dec)
given the rotation matrix T for (ra, dec) -> (phi1, phi2)
INPUT:
phi1 - custom sky coord
phi2 - custom sky c... | [
"def",
"custom_to_radec",
"(",
"phi1",
",",
"phi2",
",",
"T",
"=",
"None",
",",
"degree",
"=",
"False",
")",
":",
"if",
"T",
"is",
"None",
":",
"raise",
"ValueError",
"(",
"\"Must set T= for custom_to_radec\"",
")",
"return",
"radec_to_custom",
"(",
"phi1",
... | 23.484848 | 25.666667 |
def unicast(self, socket_id, event, data):
"""Sends an event to a single socket. Returns `True` if that
worked or `False` if not.
"""
payload = self._server.serialize_event(event, data)
rv = self._server.sockets.get(socket_id)
if rv is not None:
rv.socket.sen... | [
"def",
"unicast",
"(",
"self",
",",
"socket_id",
",",
"event",
",",
"data",
")",
":",
"payload",
"=",
"self",
".",
"_server",
".",
"serialize_event",
"(",
"event",
",",
"data",
")",
"rv",
"=",
"self",
".",
"_server",
".",
"sockets",
".",
"get",
"(",
... | 36.6 | 9.2 |
def drop_keyspace(name, connections=None):
"""
Drops a keyspace, if it exists.
*There are plans to guard schema-modifying functions with an environment-driven conditional.*
**This function should be used with caution, especially in production environments.
Take care to execute schema modifications... | [
"def",
"drop_keyspace",
"(",
"name",
",",
"connections",
"=",
"None",
")",
":",
"if",
"not",
"_allow_schema_modification",
"(",
")",
":",
"return",
"if",
"connections",
":",
"if",
"not",
"isinstance",
"(",
"connections",
",",
"(",
"list",
",",
"tuple",
")"... | 36.241379 | 23.206897 |
def readin():
"""Reading from stdin and displaying menu"""
selection = sys.stdin.readline().strip("\n")
MyBulbs.bulbs.sort(key=lambda x: x.label or x.mac_addr)
lov=[ x for x in selection.split(" ") if x != ""]
if lov:
if MyBulbs.boi:
#try:
if True:
if... | [
"def",
"readin",
"(",
")",
":",
"selection",
"=",
"sys",
".",
"stdin",
".",
"readline",
"(",
")",
".",
"strip",
"(",
"\"\\n\"",
")",
"MyBulbs",
".",
"bulbs",
".",
"sort",
"(",
"key",
"=",
"lambda",
"x",
":",
"x",
".",
"label",
"or",
"x",
".",
"... | 49.401869 | 23.53271 |
def contextMenuEvent(self, event):
"""Reimplement Qt method"""
if self.model.showndata:
self.refresh_menu()
self.menu.popup(event.globalPos())
event.accept()
else:
self.empty_ws_menu.popup(event.globalPos())
event.accept() | [
"def",
"contextMenuEvent",
"(",
"self",
",",
"event",
")",
":",
"if",
"self",
".",
"model",
".",
"showndata",
":",
"self",
".",
"refresh_menu",
"(",
")",
"self",
".",
"menu",
".",
"popup",
"(",
"event",
".",
"globalPos",
"(",
")",
")",
"event",
".",
... | 34 | 10.666667 |
def remove_resource_file(issue, filepath, ignore_layouts):
"""
Delete a file from the filesystem
"""
if os.path.exists(filepath) and (ignore_layouts is False or issue.elements[0][0] != 'layout'):
print('removing resource: {0}'.format(filepath))
os.remove(os.path.abspath(filepath)) | [
"def",
"remove_resource_file",
"(",
"issue",
",",
"filepath",
",",
"ignore_layouts",
")",
":",
"if",
"os",
".",
"path",
".",
"exists",
"(",
"filepath",
")",
"and",
"(",
"ignore_layouts",
"is",
"False",
"or",
"issue",
".",
"elements",
"[",
"0",
"]",
"[",
... | 43.857143 | 14.142857 |
def sign(self, response):
"""Sign a response.
I take a L{OpenIDResponse}, create a signature for everything
in its L{signed<OpenIDResponse.signed>} list, and return a new
copy of the response object with that signature included.
@param response: A response to sign.
@typ... | [
"def",
"sign",
"(",
"self",
",",
"response",
")",
":",
"signed_response",
"=",
"deepcopy",
"(",
"response",
")",
"assoc_handle",
"=",
"response",
".",
"request",
".",
"assoc_handle",
"if",
"assoc_handle",
":",
"# normal mode",
"# disabling expiration check because e... | 43.325581 | 19.651163 |
def writePathogenIndex(self, fp):
"""
Write a file of pathogen indices and names, sorted by index.
@param fp: A file-like object, opened for writing.
"""
print('\n'.join(
'%d %s' % (index, name) for (index, name) in
sorted((index, name) for (name, index) ... | [
"def",
"writePathogenIndex",
"(",
"self",
",",
"fp",
")",
":",
"print",
"(",
"'\\n'",
".",
"join",
"(",
"'%d %s'",
"%",
"(",
"index",
",",
"name",
")",
"for",
"(",
"index",
",",
"name",
")",
"in",
"sorted",
"(",
"(",
"index",
",",
"name",
")",
"f... | 35.8 | 18.4 |
def mark_as_consumed(self, name, new_node):
"""
Mark the name as consumed and delete it from
the to_consume dictionary
"""
self.consumed[name] = new_node
del self.to_consume[name] | [
"def",
"mark_as_consumed",
"(",
"self",
",",
"name",
",",
"new_node",
")",
":",
"self",
".",
"consumed",
"[",
"name",
"]",
"=",
"new_node",
"del",
"self",
".",
"to_consume",
"[",
"name",
"]"
] | 31.571429 | 4.428571 |
def number(self, assignment_class=None, namespace='d'):
"""
Return a new number.
:param assignment_class: Determines the length of the number. Possible values are 'authority' (3 characters) ,
'registered' (5) , 'unregistered' (7) and 'self' (9). Self assigned numbers are random and... | [
"def",
"number",
"(",
"self",
",",
"assignment_class",
"=",
"None",
",",
"namespace",
"=",
"'d'",
")",
":",
"if",
"assignment_class",
"==",
"'self'",
":",
"# When 'self' is explicit, don't look for number server config",
"return",
"str",
"(",
"DatasetNumber",
"(",
"... | 40.712121 | 27.984848 |
def heartbeat(self):
"""
Watch our counters--as long as things are incrementing, send a ping to
statuscake sayin we are alive and okay.
"""
self.thread_debug("heartbeat")
# check stats -- should be incrementing
if self.last_stats:
if self.stats.http_... | [
"def",
"heartbeat",
"(",
"self",
")",
":",
"self",
".",
"thread_debug",
"(",
"\"heartbeat\"",
")",
"# check stats -- should be incrementing",
"if",
"self",
".",
"last_stats",
":",
"if",
"self",
".",
"stats",
".",
"http_run",
"<=",
"self",
".",
"last_stats",
".... | 40.56 | 21.6 |
def _register_trade(self, order):
""" constructs trade info from order data """
if order['id'] in self.orders.recent:
orderId = order['id']
else:
orderId = order['parentId']
# entry / exit?
symbol = order["symbol"]
order_data = self.orders.recent[o... | [
"def",
"_register_trade",
"(",
"self",
",",
"order",
")",
":",
"if",
"order",
"[",
"'id'",
"]",
"in",
"self",
".",
"orders",
".",
"recent",
":",
"orderId",
"=",
"order",
"[",
"'id'",
"]",
"else",
":",
"orderId",
"=",
"order",
"[",
"'parentId'",
"]",
... | 39.945736 | 18.620155 |
def _paramstr(ins):
""" Pushes an 16 bit unsigned value, which points
to a string. For indirect values, it will push
the pointer to the pointer :-)
"""
(tmp, output) = _str_oper(ins.quad[1])
output.pop() # Remove a register flag (useless here)
tmp = ins.quad[1][0] in ('#', '_') # Determine... | [
"def",
"_paramstr",
"(",
"ins",
")",
":",
"(",
"tmp",
",",
"output",
")",
"=",
"_str_oper",
"(",
"ins",
".",
"quad",
"[",
"1",
"]",
")",
"output",
".",
"pop",
"(",
")",
"# Remove a register flag (useless here)",
"tmp",
"=",
"ins",
".",
"quad",
"[",
"... | 33.2 | 18 |
def rsa_pkcs1v15_sign(private_key, data, hash_algorithm):
"""
Generates an RSASSA-PKCS-v1.5 signature.
When the hash_algorithm is "raw", the operation is identical to RSA
private key encryption. That is: the data is not hashed and no ASN.1
structure with an algorithm identifier of the hash algorith... | [
"def",
"rsa_pkcs1v15_sign",
"(",
"private_key",
",",
"data",
",",
"hash_algorithm",
")",
":",
"if",
"private_key",
".",
"algorithm",
"!=",
"'rsa'",
":",
"raise",
"ValueError",
"(",
"'The key specified is not an RSA private key'",
")",
"return",
"_sign",
"(",
"privat... | 33.774194 | 24.612903 |
def get(self, *args, **kwargs):
"""Perform a get request."""
if 'convert' in kwargs:
conversion = kwargs.pop('convert')
else:
conversion = True
kwargs = self._get_keywords(**kwargs)
url = self._create_path(*args)
request = self.session.get(url, par... | [
"def",
"get",
"(",
"self",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"if",
"'convert'",
"in",
"kwargs",
":",
"conversion",
"=",
"kwargs",
".",
"pop",
"(",
"'convert'",
")",
"else",
":",
"conversion",
"=",
"True",
"kwargs",
"=",
"self",
"... | 36.25 | 8.916667 |
def _ecc_encode_compressed_point(private_key):
"""Encodes a compressed elliptic curve point
as described in SEC-1 v2 section 2.3.3
http://www.secg.org/sec1-v2.pdf
:param private_key: Private key from which to extract point data
:type private_key: cryptography.hazmat.primitives.asymmetric.ec... | [
"def",
"_ecc_encode_compressed_point",
"(",
"private_key",
")",
":",
"# key_size is in bits. Convert to bytes and round up",
"byte_length",
"=",
"(",
"private_key",
".",
"curve",
".",
"key_size",
"+",
"7",
")",
"//",
"8",
"public_numbers",
"=",
"private_key",
".",
"pu... | 43.681818 | 16.727273 |
def getControls(self):
'''
Calculates consumption for each consumer of this type using the consumption functions.
Parameters
----------
None
Returns
-------
None
'''
cNrmNow = np.zeros(self.AgentCount) + np.nan
for t in range(self... | [
"def",
"getControls",
"(",
"self",
")",
":",
"cNrmNow",
"=",
"np",
".",
"zeros",
"(",
"self",
".",
"AgentCount",
")",
"+",
"np",
".",
"nan",
"for",
"t",
"in",
"range",
"(",
"self",
".",
"T_cycle",
")",
":",
"for",
"j",
"in",
"range",
"(",
"self",... | 30.315789 | 26.105263 |
def _match_nodes(self, validators, obj):
"""Apply each validator in validators to each node in obj.
Return each node in obj which matches all validators.
"""
results = []
for node in object_iter(obj):
if all([validate(node) for validate in validators]):
... | [
"def",
"_match_nodes",
"(",
"self",
",",
"validators",
",",
"obj",
")",
":",
"results",
"=",
"[",
"]",
"for",
"node",
"in",
"object_iter",
"(",
"obj",
")",
":",
"if",
"all",
"(",
"[",
"validate",
"(",
"node",
")",
"for",
"validate",
"in",
"validators... | 32.454545 | 15.454545 |
def update_document_indicators(self, doc_id, citations, accesses):
"""
Atualiza os indicadores de acessos e citações de um determinado
doc_id.
exemplo de doc_id: S0021-25712009000400007-spa
"""
headers = {'content-type': 'application/json'}
data = {
... | [
"def",
"update_document_indicators",
"(",
"self",
",",
"doc_id",
",",
"citations",
",",
"accesses",
")",
":",
"headers",
"=",
"{",
"'content-type'",
":",
"'application/json'",
"}",
"data",
"=",
"{",
"\"add\"",
":",
"{",
"\"doc\"",
":",
"{",
"\"id\"",
":",
... | 26.555556 | 23.111111 |
def translate_github_exception(func):
"""
Decorator to catch GitHub-specific exceptions and raise them as GitClientError exceptions.
"""
@functools.wraps(func)
def _wrapper(*args, **kwargs):
try:
return func(*args, **kwargs)
except UnknownObjectException as e:
... | [
"def",
"translate_github_exception",
"(",
"func",
")",
":",
"@",
"functools",
".",
"wraps",
"(",
"func",
")",
"def",
"_wrapper",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"try",
":",
"return",
"func",
"(",
"*",
"args",
",",
"*",
"*",
"kw... | 31.882353 | 14.235294 |
def run(self):
"""
Copy libraries from the bin directory and place them as appropriate
"""
self.announce("Moving library files", level=3)
# We have already built the libraries in the previous build_ext step
self.skip_build = True
bin_dir = self.distribution.bi... | [
"def",
"run",
"(",
"self",
")",
":",
"self",
".",
"announce",
"(",
"\"Moving library files\"",
",",
"level",
"=",
"3",
")",
"# We have already built the libraries in the previous build_ext step",
"self",
".",
"skip_build",
"=",
"True",
"bin_dir",
"=",
"self",
".",
... | 37.911111 | 27.155556 |
def update_object_from_dictionary_representation(dictionary, instance):
"""Given a dictionary and an object instance, will set all object attributes equal to the dictionary's keys and
values. Assumes dictionary does not have any keys for which object does not have attributes
@type dictionary: d... | [
"def",
"update_object_from_dictionary_representation",
"(",
"dictionary",
",",
"instance",
")",
":",
"for",
"key",
",",
"value",
"in",
"dictionary",
".",
"iteritems",
"(",
")",
":",
"if",
"hasattr",
"(",
"instance",
",",
"key",
")",
":",
"setattr",
"(",
"ins... | 44.571429 | 19.285714 |
def simulate_moment_steps(
self,
circuit: circuits.Circuit,
param_resolver: 'study.ParamResolverOrSimilarType' = None,
qubit_order: ops.QubitOrderOrList = ops.QubitOrder.DEFAULT,
initial_state: Any = None
) -> Iterator:
"""Returns an iterator of StepResults for each m... | [
"def",
"simulate_moment_steps",
"(",
"self",
",",
"circuit",
":",
"circuits",
".",
"Circuit",
",",
"param_resolver",
":",
"'study.ParamResolverOrSimilarType'",
"=",
"None",
",",
"qubit_order",
":",
"ops",
".",
"QubitOrderOrList",
"=",
"ops",
".",
"QubitOrder",
"."... | 43.516129 | 22.580645 |
def Zabransky_quasi_polynomial_integral_over_T(T, Tc, a1, a2, a3, a4, a5, a6):
r'''Calculates the integral of liquid heat capacity over T using the
quasi-polynomial model developed in [1]_.
Parameters
----------
T : float
Temperature [K]
a1-a6 : float
Coefficients
Returns... | [
"def",
"Zabransky_quasi_polynomial_integral_over_T",
"(",
"T",
",",
"Tc",
",",
"a1",
",",
"a2",
",",
"a3",
",",
"a4",
",",
"a5",
",",
"a6",
")",
":",
"term",
"=",
"T",
"-",
"Tc",
"logT",
"=",
"log",
"(",
"T",
")",
"Tc2",
"=",
"Tc",
"*",
"Tc",
"... | 33.090909 | 27.727273 |
def get_element(self, line, column):
"""Gets the instance of the element who owns the specified line
and column."""
ichar = self.charindex(line, column)
icontains = self.contains_index
result = None
if line < icontains:
#We only need to search through the typ... | [
"def",
"get_element",
"(",
"self",
",",
"line",
",",
"column",
")",
":",
"ichar",
"=",
"self",
".",
"charindex",
"(",
"line",
",",
"column",
")",
"icontains",
"=",
"self",
".",
"contains_index",
"result",
"=",
"None",
"if",
"line",
"<",
"icontains",
":... | 40.653061 | 18.22449 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.