text stringlengths 75 104k | code_tokens list | avg_line_len float64 7.91 980 | score float64 0 0.18 |
|---|---|---|---|
def get_type_lookup_session(self):
"""Gets the OsidSession associated with the type lookup service.
return: (osid.type.TypeLookupSession) - a TypeLookupSession
raise: OperationFailed - unable to complete request
raise: Unimplemented - supports_type_lookup() is false
compliance... | [
"def",
"get_type_lookup_session",
"(",
"self",
")",
":",
"if",
"not",
"self",
".",
"supports_type_lookup",
"(",
")",
":",
"raise",
"Unimplemented",
"(",
")",
"try",
":",
"from",
".",
"import",
"sessions",
"except",
"ImportError",
":",
"raise",
"# OperationFail... | 37.285714 | 0.002491 |
def process_sample(job, inputs, tar_id):
"""
Converts sample.tar(.gz) into two fastq files.
Due to edge conditions... BEWARE: HERE BE DRAGONS
:param JobFunctionWrappingJob job: passed by Toil automatically
:param Namespace inputs: Stores input arguments (see main)
:param str tar_id: FileStore I... | [
"def",
"process_sample",
"(",
"job",
",",
"inputs",
",",
"tar_id",
")",
":",
"job",
".",
"fileStore",
".",
"logToMaster",
"(",
"'Processing sample into read pairs: {}'",
".",
"format",
"(",
"inputs",
".",
"uuid",
")",
")",
"work_dir",
"=",
"job",
".",
"fileS... | 45.829787 | 0.002273 |
def _log_http_response(method, url, status, headers=None, content=None):
"""
Log the HTTP response of an HMC REST API call, at the debug level.
Parameters:
method (:term:`string`): HTTP method name in upper case, e.g. 'GET'
url (:term:`string`): HTTP URL (base URL and oper... | [
"def",
"_log_http_response",
"(",
"method",
",",
"url",
",",
"status",
",",
"headers",
"=",
"None",
",",
"content",
"=",
"None",
")",
":",
"if",
"method",
"==",
"'POST'",
"and",
"url",
".",
"endswith",
"(",
"'/api/sessions'",
")",
":",
"# In Python 3 up to... | 42.810811 | 0.001235 |
def get_num_names_in_namespace( self, namespace_id ):
"""
Get the number of names in a namespace
"""
cur = self.db.cursor()
return namedb_get_num_names_in_namespace( cur, namespace_id, self.lastblock ) | [
"def",
"get_num_names_in_namespace",
"(",
"self",
",",
"namespace_id",
")",
":",
"cur",
"=",
"self",
".",
"db",
".",
"cursor",
"(",
")",
"return",
"namedb_get_num_names_in_namespace",
"(",
"cur",
",",
"namespace_id",
",",
"self",
".",
"lastblock",
")"
] | 39.333333 | 0.029046 |
def publish(tgt,
fun,
arg=None,
tgt_type='glob',
returner='',
timeout=5,
roster=None):
'''
Publish a command "from the minion out to other minions". In reality, the
minion does not execute this function, it is executed by the master. Th... | [
"def",
"publish",
"(",
"tgt",
",",
"fun",
",",
"arg",
"=",
"None",
",",
"tgt_type",
"=",
"'glob'",
",",
"returner",
"=",
"''",
",",
"timeout",
"=",
"5",
",",
"roster",
"=",
"None",
")",
":",
"return",
"_publish",
"(",
"tgt",
",",
"fun",
",",
"arg... | 28.863014 | 0.001836 |
def load_tt_file(self, locale, path_func=None, encoding=None):
"""
Load a tt file's tt dict into |self.tt_dd|.
|tt| means text transform.
locale: locale key into |self.tt_dd|.
path_func: tt file path func
encoding: tt file encoding
"""
#/... | [
"def",
"load_tt_file",
"(",
"self",
",",
"locale",
",",
"path_func",
"=",
"None",
",",
"encoding",
"=",
"None",
")",
":",
"#/",
"path_func",
"=",
"path_func",
"or",
"self",
".",
"path_func",
"encoding",
"=",
"encoding",
"or",
"self",
".",
"file_encoding",
... | 31.225 | 0.020186 |
def _serialise_posts_and_tags_from_joined_rows(cls, joined_rows):
"""
Translates multiple rows of joined post and tag information
into the dictionary format expected by flask-blogging.
There will be one row per post/tag pairing.
"""
posts_by_id = OrderedDict()
tag... | [
"def",
"_serialise_posts_and_tags_from_joined_rows",
"(",
"cls",
",",
"joined_rows",
")",
":",
"posts_by_id",
"=",
"OrderedDict",
"(",
")",
"tags_by_post_id",
"=",
"defaultdict",
"(",
"list",
")",
"for",
"joined_row",
"in",
"joined_rows",
":",
"post_id",
"=",
"joi... | 39.35 | 0.002481 |
def solve_ideal(n,c,t,segments):
"""solve_ideal: use ideal point for finding set of solutions for two-objective TSP
Parameters:
- n: number of cities
- c,t: alternative edge weights, to compute two objective functions
- segments: number of segments for finding various non-dominated solut... | [
"def",
"solve_ideal",
"(",
"n",
",",
"c",
",",
"t",
",",
"segments",
")",
":",
"model",
"=",
"base_model",
"(",
"n",
",",
"c",
",",
"t",
")",
"# base model for minimizing cost or time",
"x",
",",
"u",
",",
"C",
",",
"T",
"=",
"model",
".",
"data",
... | 35.553191 | 0.011066 |
def check_yaml_configs(configs, key):
"""Get a diagnostic for the yaml *configs*.
*key* is the section to look for to get a name for the config at hand.
"""
diagnostic = {}
for i in configs:
for fname in i:
with open(fname) as stream:
try:
res... | [
"def",
"check_yaml_configs",
"(",
"configs",
",",
"key",
")",
":",
"diagnostic",
"=",
"{",
"}",
"for",
"i",
"in",
"configs",
":",
"for",
"fname",
"in",
"i",
":",
"with",
"open",
"(",
"fname",
")",
"as",
"stream",
":",
"try",
":",
"res",
"=",
"yaml"... | 37.038462 | 0.001012 |
def get_drake_data(steps):
"""
Returns: a dictionary of outputs mapped to inputs
Note that an output is either a target or a leaf node in the
step tree
"""
output_inputs = {}
if len(steps) == 0:
return output_inputs
for step in steps:
output_inputs[step] = get_inputs... | [
"def",
"get_drake_data",
"(",
"steps",
")",
":",
"output_inputs",
"=",
"{",
"}",
"if",
"len",
"(",
"steps",
")",
"==",
"0",
":",
"return",
"output_inputs",
"for",
"step",
"in",
"steps",
":",
"output_inputs",
"[",
"step",
"]",
"=",
"get_inputs",
"(",
"s... | 27.105263 | 0.001876 |
def cc_to_local_params(pitch, radius, oligo):
"""Returns local parameters for an oligomeric assembly.
Parameters
----------
pitch : float
Pitch of assembly
radius : float
Radius of assembly
oligo : int
Oligomeric state of assembly
Returns
-------
pitchloc : ... | [
"def",
"cc_to_local_params",
"(",
"pitch",
",",
"radius",
",",
"oligo",
")",
":",
"rloc",
"=",
"numpy",
".",
"sin",
"(",
"numpy",
".",
"pi",
"/",
"oligo",
")",
"*",
"radius",
"alpha",
"=",
"numpy",
".",
"arctan",
"(",
"(",
"2",
"*",
"numpy",
".",
... | 29.846154 | 0.001248 |
def migrate():
'''
Migrate zones from old to new ids in datasets.
Should only be run once with the new version of geozones w/ geohisto.
'''
counter = Counter()
drom_zone = GeoZone.objects(id='country-subset:fr:drom').first()
dromcom_zone = GeoZone.objects(id='country-subset:fr:dromcom').fir... | [
"def",
"migrate",
"(",
")",
":",
"counter",
"=",
"Counter",
"(",
")",
"drom_zone",
"=",
"GeoZone",
".",
"objects",
"(",
"id",
"=",
"'country-subset:fr:drom'",
")",
".",
"first",
"(",
")",
"dromcom_zone",
"=",
"GeoZone",
".",
"objects",
"(",
"id",
"=",
... | 39.488372 | 0.000287 |
def list_upgrades(bin_env=None,
user=None,
cwd=None):
'''
Check whether or not an upgrade is available for all packages
CLI Example:
.. code-block:: bash
salt '*' pip.list_upgrades
'''
cmd = _get_pip_bin(bin_env)
cmd.extend(['list', '--outdated'... | [
"def",
"list_upgrades",
"(",
"bin_env",
"=",
"None",
",",
"user",
"=",
"None",
",",
"cwd",
"=",
"None",
")",
":",
"cmd",
"=",
"_get_pip_bin",
"(",
"bin_env",
")",
"cmd",
".",
"extend",
"(",
"[",
"'list'",
",",
"'--outdated'",
"]",
")",
"pip_version",
... | 36.223684 | 0.000707 |
def drag_and_drop(self, source_selector, destination_selector, **kwargs):
"""Drag and drop
Args:
source_selector: (str)
destination_selector: (str)
Kwargs:
use_javascript_dnd: bool; default:
config proxy_driver:use_javascript_dnd
"""
... | [
"def",
"drag_and_drop",
"(",
"self",
",",
"source_selector",
",",
"destination_selector",
",",
"*",
"*",
"kwargs",
")",
":",
"self",
".",
"info_log",
"(",
"\"Drag and drop: source (%s); destination (%s)\"",
"%",
"(",
"source_selector",
",",
"destination_selector",
")"... | 47.686275 | 0.000806 |
def _try_get_string(dev, index, langid = None, default_str_i0 = "",
default_access_error = "Error Accessing String"):
""" try to get a string, but return a string no matter what
"""
if index == 0 :
string = default_str_i0
else:
try:
if langid is None:
... | [
"def",
"_try_get_string",
"(",
"dev",
",",
"index",
",",
"langid",
"=",
"None",
",",
"default_str_i0",
"=",
"\"\"",
",",
"default_access_error",
"=",
"\"Error Accessing String\"",
")",
":",
"if",
"index",
"==",
"0",
":",
"string",
"=",
"default_str_i0",
"else"... | 33.2 | 0.021484 |
def _cls_lookup_dist(cls):
"""
Attempt to resolve the distribution from the provided class in the
most naive way - this assumes the Python module path to the class
contains the name of the package that provided the module and class.
"""
frags = cls.__module__.split('.')
for name in ('.'.joi... | [
"def",
"_cls_lookup_dist",
"(",
"cls",
")",
":",
"frags",
"=",
"cls",
".",
"__module__",
".",
"split",
"(",
"'.'",
")",
"for",
"name",
"in",
"(",
"'.'",
".",
"join",
"(",
"frags",
"[",
":",
"x",
"]",
")",
"for",
"x",
"in",
"range",
"(",
"len",
... | 36.083333 | 0.002252 |
def get_samples_with_constraints(self, init_points_count):
"""
Draw random samples and only save those that satisfy constraints
Finish when required number of samples is generated
"""
samples = np.empty((0, self.space.dimensionality))
while samples.shape[0] < init_points... | [
"def",
"get_samples_with_constraints",
"(",
"self",
",",
"init_points_count",
")",
":",
"samples",
"=",
"np",
".",
"empty",
"(",
"(",
"0",
",",
"self",
".",
"space",
".",
"dimensionality",
")",
")",
"while",
"samples",
".",
"shape",
"[",
"0",
"]",
"<",
... | 46.866667 | 0.009763 |
def get_process(cmd):
"""Get a command process."""
if sys.platform.startswith('win'):
startupinfo = subprocess.STARTUPINFO()
startupinfo.dwFlags |= subprocess.STARTF_USESHOWWINDOW
process = subprocess.Popen(
cmd,
startupinfo=startupinfo,
stdout=subpro... | [
"def",
"get_process",
"(",
"cmd",
")",
":",
"if",
"sys",
".",
"platform",
".",
"startswith",
"(",
"'win'",
")",
":",
"startupinfo",
"=",
"subprocess",
".",
"STARTUPINFO",
"(",
")",
"startupinfo",
".",
"dwFlags",
"|=",
"subprocess",
".",
"STARTF_USESHOWWINDOW... | 27.826087 | 0.001511 |
def is_paired(text, open='(', close=')'):
"""Check if the text only contains:
1. blackslash escaped parentheses, or
2. parentheses paired.
"""
count = 0
escape = False
for c in text:
if escape:
escape = False
elif c == '\\':
escape = True
elif ... | [
"def",
"is_paired",
"(",
"text",
",",
"open",
"=",
"'('",
",",
"close",
"=",
"')'",
")",
":",
"count",
"=",
"0",
"escape",
"=",
"False",
"for",
"c",
"in",
"text",
":",
"if",
"escape",
":",
"escape",
"=",
"False",
"elif",
"c",
"==",
"'\\\\'",
":",... | 24.263158 | 0.002088 |
def wrap_tuple_streams(unwrapped, kdims, streams):
"""
Fills in tuple keys with dimensioned stream values as appropriate.
"""
param_groups = [(s.contents.keys(), s) for s in streams]
pairs = [(name,s) for (group, s) in param_groups for name in group]
substituted = []
for pos,el in enumerate... | [
"def",
"wrap_tuple_streams",
"(",
"unwrapped",
",",
"kdims",
",",
"streams",
")",
":",
"param_groups",
"=",
"[",
"(",
"s",
".",
"contents",
".",
"keys",
"(",
")",
",",
"s",
")",
"for",
"s",
"in",
"streams",
"]",
"pairs",
"=",
"[",
"(",
"name",
",",... | 42.4 | 0.010769 |
def set_cycle_mrkr(self, epoch_start, end=False):
"""Mark epoch start as cycle start or end.
Parameters
----------
epoch_start: int
start time of the epoch, in seconds
end : bool
If True, marked as cycle end; otherwise, marks cycle start
"""
... | [
"def",
"set_cycle_mrkr",
"(",
"self",
",",
"epoch_start",
",",
"end",
"=",
"False",
")",
":",
"if",
"self",
".",
"rater",
"is",
"None",
":",
"raise",
"IndexError",
"(",
"'You need to have at least one rater'",
")",
"bound",
"=",
"'start'",
"if",
"end",
":",
... | 33.925926 | 0.002123 |
def _dimensions(self):
"""tuple of dimension objects in this collection.
This composed tuple is the source for the dimension objects in this
collection.
"""
return tuple(d for d in self._all_dimensions if d.dimension_type != DT.MR_CAT) | [
"def",
"_dimensions",
"(",
"self",
")",
":",
"return",
"tuple",
"(",
"d",
"for",
"d",
"in",
"self",
".",
"_all_dimensions",
"if",
"d",
".",
"dimension_type",
"!=",
"DT",
".",
"MR_CAT",
")"
] | 38.571429 | 0.01087 |
def make_reader_task(self, stream, callback):
"""
Create a reader executor task for a stream.
"""
return self.loop.create_task(self.executor_wrapper(background_reader, stream, self.loop, callback)) | [
"def",
"make_reader_task",
"(",
"self",
",",
"stream",
",",
"callback",
")",
":",
"return",
"self",
".",
"loop",
".",
"create_task",
"(",
"self",
".",
"executor_wrapper",
"(",
"background_reader",
",",
"stream",
",",
"self",
".",
"loop",
",",
"callback",
"... | 37.5 | 0.013043 |
def unassign_comment_from_book(self, comment_id, book_id):
"""Removes a ``Comment`` from a ``Book``.
arg: comment_id (osid.id.Id): the ``Id`` of the ``Comment``
arg: book_id (osid.id.Id): the ``Id`` of the ``Book``
raise: NotFound - ``comment_id`` or ``book_id`` not found or
... | [
"def",
"unassign_comment_from_book",
"(",
"self",
",",
"comment_id",
",",
"book_id",
")",
":",
"# Implemented from template for",
"# osid.resource.ResourceBinAssignmentSession.unassign_resource_from_bin",
"mgr",
"=",
"self",
".",
"_get_provider_manager",
"(",
"'COMMENTING'",
",... | 53.315789 | 0.00194 |
def remove_actor(self, actor, reset_camera=False):
"""
Removes an actor from the Renderer.
Parameters
----------
actor : vtk.vtkActor
Actor that has previously added to the Renderer.
reset_camera : bool, optional
Resets camera so all actors can b... | [
"def",
"remove_actor",
"(",
"self",
",",
"actor",
",",
"reset_camera",
"=",
"False",
")",
":",
"name",
"=",
"None",
"if",
"isinstance",
"(",
"actor",
",",
"str",
")",
":",
"name",
"=",
"actor",
"keys",
"=",
"list",
"(",
"self",
".",
"_actors",
".",
... | 31.466667 | 0.001027 |
def json2paramater(self, ss_spec):
'''
generate all possible configs for hyperparameters from hyperparameter space.
ss_spec: hyperparameter space
'''
if isinstance(ss_spec, dict):
if '_type' in ss_spec.keys():
_type = ss_spec['_type']
_... | [
"def",
"json2paramater",
"(",
"self",
",",
"ss_spec",
")",
":",
"if",
"isinstance",
"(",
"ss_spec",
",",
"dict",
")",
":",
"if",
"'_type'",
"in",
"ss_spec",
".",
"keys",
"(",
")",
":",
"_type",
"=",
"ss_spec",
"[",
"'_type'",
"]",
"_value",
"=",
"ss_... | 42.194444 | 0.001931 |
def GT(self, a, b):
"""Greater-than comparison"""
return Operators.ITEBV(256, Operators.UGT(a, b), 1, 0) | [
"def",
"GT",
"(",
"self",
",",
"a",
",",
"b",
")",
":",
"return",
"Operators",
".",
"ITEBV",
"(",
"256",
",",
"Operators",
".",
"UGT",
"(",
"a",
",",
"b",
")",
",",
"1",
",",
"0",
")"
] | 39.333333 | 0.016667 |
def generate_join_docs_list(self, left_collection_list, right_collection_list):
"""
Helper function for merge_join_docs
:param left_collection_list: Left Collection to be joined
:type left_collection_list: MongoCollection
:param right_collection_list: Right Coll... | [
"def",
"generate_join_docs_list",
"(",
"self",
",",
"left_collection_list",
",",
"right_collection_list",
")",
":",
"joined_docs",
"=",
"[",
"]",
"if",
"(",
"len",
"(",
"left_collection_list",
")",
"!=",
"0",
")",
"and",
"(",
"len",
"(",
"right_collection_list",... | 43.740741 | 0.002486 |
def default_scopes(self, scopes):
"""Set default scopes for client."""
validate_scopes(scopes)
self._default_scopes = " ".join(set(scopes)) if scopes else "" | [
"def",
"default_scopes",
"(",
"self",
",",
"scopes",
")",
":",
"validate_scopes",
"(",
"scopes",
")",
"self",
".",
"_default_scopes",
"=",
"\" \"",
".",
"join",
"(",
"set",
"(",
"scopes",
")",
")",
"if",
"scopes",
"else",
"\"\""
] | 44.5 | 0.01105 |
def main() -> None:
"""
Command-line handler for the ``grep_in_openxml`` tool.
Use the ``--help`` option for help.
"""
parser = ArgumentParser(
formatter_class=RawDescriptionHelpFormatter,
description="""
Performs a grep (global-regular-expression-print) search of files in OpenXML
fo... | [
"def",
"main",
"(",
")",
"->",
"None",
":",
"parser",
"=",
"ArgumentParser",
"(",
"formatter_class",
"=",
"RawDescriptionHelpFormatter",
",",
"description",
"=",
"\"\"\"\nPerforms a grep (global-regular-expression-print) search of files in OpenXML\nformat, which is to say inside ZI... | 36.731092 | 0.000223 |
def svd_convolution(inp, outmaps, kernel, r, pad=None, stride=None,
dilation=None, uv_init=None, b_init=None, base_axis=1,
fix_parameters=False, rng=None, with_bias=True):
"""SVD convolution is a low rank approximation of the convolution
layer. It can be seen as a depth w... | [
"def",
"svd_convolution",
"(",
"inp",
",",
"outmaps",
",",
"kernel",
",",
"r",
",",
"pad",
"=",
"None",
",",
"stride",
"=",
"None",
",",
"dilation",
"=",
"None",
",",
"uv_init",
"=",
"None",
",",
"b_init",
"=",
"None",
",",
"base_axis",
"=",
"1",
"... | 39.22449 | 0.001184 |
def import_task_to_graph(diagram_graph, process_id, process_attributes, task_element):
"""
Adds to graph the new element that represents BPMN task.
In our representation tasks have only basic attributes and elements, inherited from Activity type,
so this method only needs to call add_flo... | [
"def",
"import_task_to_graph",
"(",
"diagram_graph",
",",
"process_id",
",",
"process_attributes",
",",
"task_element",
")",
":",
"BpmnDiagramGraphImport",
".",
"import_activity_to_graph",
"(",
"diagram_graph",
",",
"process_id",
",",
"process_attributes",
",",
"task_elem... | 64.538462 | 0.009401 |
def snapshot(self, mode):
'''
Take a snapshot of the system.
'''
self._init_env()
self._save_cfg_packages(self._get_changed_cfg_pkgs(self._get_cfg_pkgs()))
self._save_payload(*self._scan_payload()) | [
"def",
"snapshot",
"(",
"self",
",",
"mode",
")",
":",
"self",
".",
"_init_env",
"(",
")",
"self",
".",
"_save_cfg_packages",
"(",
"self",
".",
"_get_changed_cfg_pkgs",
"(",
"self",
".",
"_get_cfg_pkgs",
"(",
")",
")",
")",
"self",
".",
"_save_payload",
... | 29.875 | 0.012195 |
def lookup_job_tasks(self,
statuses,
user_ids=None,
job_ids=None,
job_names=None,
task_ids=None,
task_attempts=None,
labels=None,
create... | [
"def",
"lookup_job_tasks",
"(",
"self",
",",
"statuses",
",",
"user_ids",
"=",
"None",
",",
"job_ids",
"=",
"None",
",",
"job_names",
"=",
"None",
",",
"task_ids",
"=",
"None",
",",
"task_attempts",
"=",
"None",
",",
"labels",
"=",
"None",
",",
"create_t... | 44.222222 | 0.008605 |
def send(self, dispatcher):
"""Sends this outgoing packet to dispatcher's socket"""
if self.sent_complete:
return
sent = dispatcher.send(self.to_send)
self.to_send = self.to_send[sent:] | [
"def",
"send",
"(",
"self",
",",
"dispatcher",
")",
":",
"if",
"self",
".",
"sent_complete",
":",
"return",
"sent",
"=",
"dispatcher",
".",
"send",
"(",
"self",
".",
"to_send",
")",
"self",
".",
"to_send",
"=",
"self",
".",
"to_send",
"[",
"sent",
":... | 28.857143 | 0.009615 |
def get_libsodium():
'''Locate the libsodium C library'''
__SONAMES = (13, 10, 5, 4)
# Import libsodium from system
sys_sodium = ctypes.util.find_library('sodium')
if sys_sodium is None:
sys_sodium = ctypes.util.find_library('libsodium')
if sys_sodium:
try:
return c... | [
"def",
"get_libsodium",
"(",
")",
":",
"__SONAMES",
"=",
"(",
"13",
",",
"10",
",",
"5",
",",
"4",
")",
"# Import libsodium from system",
"sys_sodium",
"=",
"ctypes",
".",
"util",
".",
"find_library",
"(",
"'sodium'",
")",
"if",
"sys_sodium",
"is",
"None",... | 28.377358 | 0.000643 |
def load_extra_emacs_page_navigation_bindings():
"""
Key bindings, for scrolling up and down through pages.
This are separate bindings, because GNU readline doesn't have them.
"""
registry = ConditionalRegistry(Registry(), EmacsMode())
handle = registry.add_binding
handle(Keys.ControlV)(scr... | [
"def",
"load_extra_emacs_page_navigation_bindings",
"(",
")",
":",
"registry",
"=",
"ConditionalRegistry",
"(",
"Registry",
"(",
")",
",",
"EmacsMode",
"(",
")",
")",
"handle",
"=",
"registry",
".",
"add_binding",
"handle",
"(",
"Keys",
".",
"ControlV",
")",
"... | 33.642857 | 0.002066 |
def _calc_dist2root(self):
"""
For each node in the tree, set its root-to-node distance as dist2root
attribute
"""
self.tree.root.dist2root = 0.0
for clade in self.tree.get_nonterminals(order='preorder'): # parents first
for c in clade.clades:
... | [
"def",
"_calc_dist2root",
"(",
"self",
")",
":",
"self",
".",
"tree",
".",
"root",
".",
"dist2root",
"=",
"0.0",
"for",
"clade",
"in",
"self",
".",
"tree",
".",
"get_nonterminals",
"(",
"order",
"=",
"'preorder'",
")",
":",
"# parents first",
"for",
"c",... | 42.363636 | 0.010504 |
def plot_sites(calc_id=-1):
"""
Plot the sites
"""
# NB: matplotlib is imported inside since it is a costly import
import matplotlib.pyplot as p
dstore = util.read(calc_id)
sitecol = dstore['sitecol']
lons, lats = sitecol.lons, sitecol.lats
if len(lons) > 1 and cross_idl(*lons):
... | [
"def",
"plot_sites",
"(",
"calc_id",
"=",
"-",
"1",
")",
":",
"# NB: matplotlib is imported inside since it is a costly import",
"import",
"matplotlib",
".",
"pyplot",
"as",
"p",
"dstore",
"=",
"util",
".",
"read",
"(",
"calc_id",
")",
"sitecol",
"=",
"dstore",
... | 30.363636 | 0.001451 |
def _advapi32_sign(private_key, data, hash_algorithm, rsa_pss_padding=False):
"""
Generates an RSA, DSA or ECDSA signature via CryptoAPI
:param private_key:
The PrivateKey to generate the signature with
:param data:
A byte string of the data the signature is for
:param hash_algori... | [
"def",
"_advapi32_sign",
"(",
"private_key",
",",
"data",
",",
"hash_algorithm",
",",
"rsa_pss_padding",
"=",
"False",
")",
":",
"algo",
"=",
"private_key",
".",
"algorithm",
"if",
"algo",
"==",
"'rsa'",
"and",
"hash_algorithm",
"==",
"'raw'",
":",
"padded_dat... | 29.915966 | 0.001088 |
def save_dependencies(self, instance, schema):
"""Save data: and list:data: references as parents."""
def add_dependency(value):
"""Add parent Data dependency."""
try:
DataDependency.objects.update_or_create(
parent=Data.objects.get(pk=value),
... | [
"def",
"save_dependencies",
"(",
"self",
",",
"instance",
",",
"schema",
")",
":",
"def",
"add_dependency",
"(",
"value",
")",
":",
"\"\"\"Add parent Data dependency.\"\"\"",
"try",
":",
"DataDependency",
".",
"objects",
".",
"update_or_create",
"(",
"parent",
"="... | 39.363636 | 0.002255 |
def sync_hooks(user_id, repositories):
"""Sync repository hooks for a user."""
from .api import GitHubAPI
try:
# Sync hooks
gh = GitHubAPI(user_id=user_id)
for repo_id in repositories:
try:
with db.session.begin_nested():
gh.sync_repo_... | [
"def",
"sync_hooks",
"(",
"user_id",
",",
"repositories",
")",
":",
"from",
".",
"api",
"import",
"GitHubAPI",
"try",
":",
"# Sync hooks",
"gh",
"=",
"GitHubAPI",
"(",
"user_id",
"=",
"user_id",
")",
"for",
"repo_id",
"in",
"repositories",
":",
"try",
":",... | 37.3 | 0.001307 |
def create_plane(width=1, height=1, width_segments=1, height_segments=1,
direction='+z'):
""" Generate vertices & indices for a filled and outlined plane.
Parameters
----------
width : float
Plane width.
height : float
Plane height.
width_segments : int
... | [
"def",
"create_plane",
"(",
"width",
"=",
"1",
",",
"height",
"=",
"1",
",",
"width_segments",
"=",
"1",
",",
"height_segments",
"=",
"1",
",",
"direction",
"=",
"'+z'",
")",
":",
"x_grid",
"=",
"width_segments",
"y_grid",
"=",
"height_segments",
"x_grid1"... | 31.682243 | 0.000286 |
def stratHeun(f, G, y0, tspan, dW=None):
"""Use the Stratonovich Heun algorithm to integrate Stratonovich equation
dy = f(y,t)dt + G(y,t) \circ dW(t)
where y is the d-dimensional state vector, f is a vector-valued function,
G is an d x m matrix-valued function giving the noise coefficients and
dW(t... | [
"def",
"stratHeun",
"(",
"f",
",",
"G",
",",
"y0",
",",
"tspan",
",",
"dW",
"=",
"None",
")",
":",
"(",
"d",
",",
"m",
",",
"f",
",",
"G",
",",
"y0",
",",
"tspan",
",",
"dW",
",",
"__",
")",
"=",
"_check_args",
"(",
"f",
",",
"G",
",",
... | 40.789474 | 0.00168 |
def resolve(self):
""" Resolve differences between the target and the source configuration """
if self.source and self.target:
for key in self.source.keys():
if (key not in self.dont_carry_over_options
and not self.target.has(key)):
... | [
"def",
"resolve",
"(",
"self",
")",
":",
"if",
"self",
".",
"source",
"and",
"self",
".",
"target",
":",
"for",
"key",
"in",
"self",
".",
"source",
".",
"keys",
"(",
")",
":",
"if",
"(",
"key",
"not",
"in",
"self",
".",
"dont_carry_over_options",
"... | 51 | 0.008264 |
def delete_message(queue, region, receipthandle, opts=None, user=None):
'''
Delete one or more messages from a queue in a region
queue
The name of the queue to delete messages from
region
Region where SQS queues exists
receipthandle
The ReceiptHandle of the message to dele... | [
"def",
"delete_message",
"(",
"queue",
",",
"region",
",",
"receipthandle",
",",
"opts",
"=",
"None",
",",
"user",
"=",
"None",
")",
":",
"queues",
"=",
"list_queues",
"(",
"region",
",",
"opts",
",",
"user",
")",
"url_map",
"=",
"_parse_queue_list",
"("... | 26.973684 | 0.001883 |
def est_propensity_s(self, lin_B=None, C_lin=1, C_qua=2.71):
"""
Estimates the propensity score with covariates selected using
the algorithm suggested by [1]_.
The propensity score is the conditional probability of
receiving the treatment given the observed covariates.
Estimation is done via a logistic r... | [
"def",
"est_propensity_s",
"(",
"self",
",",
"lin_B",
"=",
"None",
",",
"C_lin",
"=",
"1",
",",
"C_qua",
"=",
"2.71",
")",
":",
"lin_basic",
"=",
"parse_lin_terms",
"(",
"self",
".",
"raw_data",
"[",
"'K'",
"]",
",",
"lin_B",
")",
"self",
".",
"prope... | 31.727273 | 0.028492 |
def reshape_bar_plot(df, x, y, bars):
"""Reshape data from long form to "bar plot form".
Bar plot form has x value as the index with one column for bar grouping.
Table values come from y values.
"""
idx = [bars, x]
if df.duplicated(idx).any():
warnings.warn('Duplicated index found.')
... | [
"def",
"reshape_bar_plot",
"(",
"df",
",",
"x",
",",
"y",
",",
"bars",
")",
":",
"idx",
"=",
"[",
"bars",
",",
"x",
"]",
"if",
"df",
".",
"duplicated",
"(",
"idx",
")",
".",
"any",
"(",
")",
":",
"warnings",
".",
"warn",
"(",
"'Duplicated index f... | 34.416667 | 0.002358 |
def shorten(string, max_length=80, trailing_chars=3):
''' trims the 'string' argument down to 'max_length' to make previews to long string values '''
assert type(string).__name__ in {'str', 'unicode'}, 'shorten needs string to be a string, not {}'.format(type(string))
assert type(max_length) == int, 'shorte... | [
"def",
"shorten",
"(",
"string",
",",
"max_length",
"=",
"80",
",",
"trailing_chars",
"=",
"3",
")",
":",
"assert",
"type",
"(",
"string",
")",
".",
"__name__",
"in",
"{",
"'str'",
",",
"'unicode'",
"}",
",",
"'shorten needs string to be a string, not {}'",
... | 60.625 | 0.008122 |
def clear_dns_cache(self,
host: Optional[str]=None,
port: Optional[int]=None) -> None:
"""Remove specified host/port or clear all dns local cache."""
if host is not None and port is not None:
self._cached_hosts.remove((host, port))
elif... | [
"def",
"clear_dns_cache",
"(",
"self",
",",
"host",
":",
"Optional",
"[",
"str",
"]",
"=",
"None",
",",
"port",
":",
"Optional",
"[",
"int",
"]",
"=",
"None",
")",
"->",
"None",
":",
"if",
"host",
"is",
"not",
"None",
"and",
"port",
"is",
"not",
... | 47.181818 | 0.015123 |
def interpolate(self, df):
"""Interpolate this `FrequencySeries` to a new resolution.
Parameters
----------
df : `float`
desired frequency resolution of the interpolated `FrequencySeries`,
in Hz
Returns
-------
out : `FrequencySeries`
... | [
"def",
"interpolate",
"(",
"self",
",",
"df",
")",
":",
"f0",
"=",
"self",
".",
"f0",
".",
"decompose",
"(",
")",
".",
"value",
"N",
"=",
"(",
"self",
".",
"size",
"-",
"1",
")",
"*",
"(",
"self",
".",
"df",
".",
"decompose",
"(",
")",
".",
... | 31.821429 | 0.002179 |
def plot_daily_volume(returns, transactions, ax=None, **kwargs):
"""
Plots trading volume per day vs. date.
Also displays all-time daily average.
Parameters
----------
returns : pd.Series
Daily returns of the strategy, noncumulative.
- See full explanation in tears.create_full... | [
"def",
"plot_daily_volume",
"(",
"returns",
",",
"transactions",
",",
"ax",
"=",
"None",
",",
"*",
"*",
"kwargs",
")",
":",
"if",
"ax",
"is",
"None",
":",
"ax",
"=",
"plt",
".",
"gca",
"(",
")",
"daily_txn",
"=",
"txn",
".",
"get_txn_vol",
"(",
"tr... | 31.333333 | 0.00086 |
def _get_mount_methods(self, disk_type):
"""Finds which mount methods are suitable for the specified disk type. Returns a list of all suitable mount
methods.
"""
if self.disk_mounter == 'auto':
methods = []
def add_method_if_exists(method):
if (me... | [
"def",
"_get_mount_methods",
"(",
"self",
",",
"disk_type",
")",
":",
"if",
"self",
".",
"disk_mounter",
"==",
"'auto'",
":",
"methods",
"=",
"[",
"]",
"def",
"add_method_if_exists",
"(",
"method",
")",
":",
"if",
"(",
"method",
"==",
"'avfs'",
"and",
"_... | 40.21875 | 0.002276 |
def draw_court(ax=None, color='gray', lw=1, outer_lines=False):
"""Returns an axes with a basketball court drawn onto to it.
This function draws a court based on the x and y-axis values that the NBA
stats API provides for the shot chart data. For example the center of the
hoop is located at the (0,0) ... | [
"def",
"draw_court",
"(",
"ax",
"=",
"None",
",",
"color",
"=",
"'gray'",
",",
"lw",
"=",
"1",
",",
"outer_lines",
"=",
"False",
")",
":",
"if",
"ax",
"is",
"None",
":",
"ax",
"=",
"plt",
".",
"gca",
"(",
")",
"# Create the various parts of an NBA bask... | 40.561798 | 0.00027 |
def import_locations(self, gpx_file):
"""Import GPX data files.
``import_locations()`` returns a series of lists representing track
segments with :class:`Trackpoint` objects as contents.
It expects data files in GPX format, as specified in `GPX 1.1 Schema
Documentation`_, which... | [
"def",
"import_locations",
"(",
"self",
",",
"gpx_file",
")",
":",
"self",
".",
"_gpx_file",
"=",
"gpx_file",
"data",
"=",
"utils",
".",
"prepare_xml_read",
"(",
"gpx_file",
",",
"objectify",
"=",
"True",
")",
"try",
":",
"self",
".",
"metadata",
".",
"i... | 38.426667 | 0.001691 |
def ValidOptions(cls):
"""Returns a list of valid option names."""
valid_options = []
for obj_name in dir(cls):
obj = getattr(cls, obj_name)
if inspect.isclass(obj) and issubclass(obj, cls.OptionBase):
valid_options.append(obj_name)
return valid_options | [
"def",
"ValidOptions",
"(",
"cls",
")",
":",
"valid_options",
"=",
"[",
"]",
"for",
"obj_name",
"in",
"dir",
"(",
"cls",
")",
":",
"obj",
"=",
"getattr",
"(",
"cls",
",",
"obj_name",
")",
"if",
"inspect",
".",
"isclass",
"(",
"obj",
")",
"and",
"is... | 35.25 | 0.010381 |
def import_from_json(self, data):
"""
Replace the current roster with the :meth:`export_as_json`-compatible
dictionary in `data`.
No events are fired during this activity. After this method completes,
the whole roster contents are exchanged with the contents from `data`.
... | [
"def",
"import_from_json",
"(",
"self",
",",
"data",
")",
":",
"self",
".",
"version",
"=",
"data",
".",
"get",
"(",
"\"ver\"",
",",
"None",
")",
"self",
".",
"items",
".",
"clear",
"(",
")",
"self",
".",
"groups",
".",
"clear",
"(",
")",
"for",
... | 38.217391 | 0.00222 |
async def set_gpio_mode(self, gpio_id, mode, timeout=OTGW_DEFAULT_TIMEOUT):
"""
Configure the functions of the two GPIO pins of the gateway.
The following functions are available:
0 No function, default for both ports on a freshly flashed chip
1 Ground - A permanently low output... | [
"async",
"def",
"set_gpio_mode",
"(",
"self",
",",
"gpio_id",
",",
"mode",
",",
"timeout",
"=",
"OTGW_DEFAULT_TIMEOUT",
")",
":",
"if",
"gpio_id",
"in",
"\"AB\"",
"and",
"mode",
"in",
"range",
"(",
"8",
")",
":",
"if",
"mode",
"==",
"7",
"and",
"gpio_i... | 43.906977 | 0.001036 |
def return_api_response(formatter=None):
"""
Decorator, which Applies the referenced formatter (if available) to the
function output and adds it to the APIResponse Object's `formatted`
attribute.
:param formatter: bitex.formatters.Formatter() obj
:return: bitex.api.response.APIResponse()
"""... | [
"def",
"return_api_response",
"(",
"formatter",
"=",
"None",
")",
":",
"def",
"decorator",
"(",
"func",
")",
":",
"@",
"wraps",
"(",
"func",
")",
"def",
"wrapper",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"try",
":",
"r",
"=",
"func",
... | 35.489796 | 0.001679 |
def SetHighlight( self, node, point=None, propagate=True ):
"""Set the currently-highlighted node"""
if node == self.highlightedNode:
return
self.highlightedNode = node
# TODO: restrict refresh to the squares for previous node and new node...
self.UpdateDrawing()
... | [
"def",
"SetHighlight",
"(",
"self",
",",
"node",
",",
"point",
"=",
"None",
",",
"propagate",
"=",
"True",
")",
":",
"if",
"node",
"==",
"self",
".",
"highlightedNode",
":",
"return",
"self",
".",
"highlightedNode",
"=",
"node",
"# TODO: restrict refresh to ... | 47.666667 | 0.022883 |
def mpool(self,
k_height,
k_width,
d_height=2,
d_width=2,
mode="VALID",
input_layer=None,
num_channels_in=None):
"""Construct a max pooling layer."""
return self._pool("mpool", pooling_layers.max_pooling2d,... | [
"def",
"mpool",
"(",
"self",
",",
"k_height",
",",
"k_width",
",",
"d_height",
"=",
"2",
",",
"d_width",
"=",
"2",
",",
"mode",
"=",
"\"VALID\"",
",",
"input_layer",
"=",
"None",
",",
"num_channels_in",
"=",
"None",
")",
":",
"return",
"self",
".",
"... | 36.25 | 0.020179 |
def destroy(name, conn=None, call=None):
'''
Delete a single VM
'''
if call == 'function':
raise SaltCloudSystemExit(
'The destroy action must be called with -d, --destroy, '
'-a or --action.'
)
__utils__['cloud.fire_event'](
'event',
'destroy... | [
"def",
"destroy",
"(",
"name",
",",
"conn",
"=",
"None",
",",
"call",
"=",
"None",
")",
":",
"if",
"call",
"==",
"'function'",
":",
"raise",
"SaltCloudSystemExit",
"(",
"'The destroy action must be called with -d, --destroy, '",
"'-a or --action.'",
")",
"__utils__"... | 35.870968 | 0.001751 |
def decode_body(body, content_type):
"""Decode event body"""
if isinstance(body, dict):
return body
else:
try:
decoded_body = base64.b64decode(body)
except:
return body
if content_type == 'application/json':
... | [
"def",
"decode_body",
"(",
"body",
",",
"content_type",
")",
":",
"if",
"isinstance",
"(",
"body",
",",
"dict",
")",
":",
"return",
"body",
"else",
":",
"try",
":",
"decoded_body",
"=",
"base64",
".",
"b64decode",
"(",
"body",
")",
"except",
":",
"retu... | 25.055556 | 0.008547 |
def conjugate(self):
"""Complex conjugate of of the product"""
return self.__class__.create(
*[arg.conjugate() for arg in reversed(self.args)]) | [
"def",
"conjugate",
"(",
"self",
")",
":",
"return",
"self",
".",
"__class__",
".",
"create",
"(",
"*",
"[",
"arg",
".",
"conjugate",
"(",
")",
"for",
"arg",
"in",
"reversed",
"(",
"self",
".",
"args",
")",
"]",
")"
] | 42 | 0.011696 |
def residual_resample(weights):
""" Performs the residual resampling algorithm used by particle filters.
Based on observation that we don't need to use random numbers to select
most of the weights. Take int(N*w^i) samples of each particle i, and then
resample any remaining using a standard resampling a... | [
"def",
"residual_resample",
"(",
"weights",
")",
":",
"N",
"=",
"len",
"(",
"weights",
")",
"indexes",
"=",
"np",
".",
"zeros",
"(",
"N",
",",
"'i'",
")",
"# take int(N*w) copies of each weight, which ensures particles with the",
"# same weight are drawn uniformly",
"... | 31.74 | 0.002445 |
def add_value_event(self, event_value, func, event_type=None, parameters=None, **kwargs):
"""
Add a function that is called when the value reach or pass the event_value.
:param event_value:
A single value or range specified as a tuple.
If it is a range the function spec... | [
"def",
"add_value_event",
"(",
"self",
",",
"event_value",
",",
"func",
",",
"event_type",
"=",
"None",
",",
"parameters",
"=",
"None",
",",
"*",
"*",
"kwargs",
")",
":",
"self",
".",
"_sensor_value",
".",
"add_value_event",
"(",
"event_value",
",",
"func"... | 40.130435 | 0.008466 |
def run_query_segments(doc, proc_id, engine, gps_start_time, gps_end_time, included_segments_string, excluded_segments_string = None, write_segments = True, start_pad = 0, end_pad = 0):
"""Runs a segment query. This was originally part of ligolw_query_segments, but now is also
used by ligolw_segments_from_cats... | [
"def",
"run_query_segments",
"(",
"doc",
",",
"proc_id",
",",
"engine",
",",
"gps_start_time",
",",
"gps_end_time",
",",
"included_segments_string",
",",
"excluded_segments_string",
"=",
"None",
",",
"write_segments",
"=",
"True",
",",
"start_pad",
"=",
"0",
",",
... | 41.369565 | 0.012834 |
def from_credentials(cls: Type[SigningKeyType], salt: Union[str, bytes], password: Union[str, bytes],
scrypt_params: Optional[ScryptParams] = None) -> SigningKeyType:
"""
Create a SigningKey object from credentials
:param salt: Secret salt passphrase credential
... | [
"def",
"from_credentials",
"(",
"cls",
":",
"Type",
"[",
"SigningKeyType",
"]",
",",
"salt",
":",
"Union",
"[",
"str",
",",
"bytes",
"]",
",",
"password",
":",
"Union",
"[",
"str",
",",
"bytes",
"]",
",",
"scrypt_params",
":",
"Optional",
"[",
"ScryptP... | 41.588235 | 0.008299 |
def _ScheduleTasks(self, storage_writer):
"""Schedules tasks.
Args:
storage_writer (StorageWriter): storage writer for a session storage.
"""
logger.debug('Task scheduler started')
self._status = definitions.STATUS_INDICATOR_RUNNING
# TODO: make tasks persistent.
# TODO: protect ta... | [
"def",
"_ScheduleTasks",
"(",
"self",
",",
"storage_writer",
")",
":",
"logger",
".",
"debug",
"(",
"'Task scheduler started'",
")",
"self",
".",
"_status",
"=",
"definitions",
".",
"STATUS_INDICATOR_RUNNING",
"# TODO: make tasks persistent.",
"# TODO: protect task schedu... | 29.795181 | 0.008219 |
def ulocalized_time(time, long_format=None, time_only=None, context=None,
request=None):
"""
This function gets ans string as time or a DateTime objects and returns a
string with the time formatted
:param time: The time to process
:type time: str/DateTime
:param long_format:... | [
"def",
"ulocalized_time",
"(",
"time",
",",
"long_format",
"=",
"None",
",",
"time_only",
"=",
"None",
",",
"context",
"=",
"None",
",",
"request",
"=",
"None",
")",
":",
"# if time is a string, we'll try pass it through strptime with the various",
"# formats defined.",... | 35.868421 | 0.001429 |
def _parse_members(self, contents, module):
"""Extracts any module-level members from the code. They must appear before
any type declalations."""
#We need to get hold of the text before the module's main CONTAINS keyword
#so that we don't find variables from executables and claim them as... | [
"def",
"_parse_members",
"(",
"self",
",",
"contents",
",",
"module",
")",
":",
"#We need to get hold of the text before the module's main CONTAINS keyword",
"#so that we don't find variables from executables and claim them as",
"#belonging to the module.",
"icontains",
"=",
"module",
... | 47.829787 | 0.010898 |
def load_metadata_from_desc_file(self, desc_file, partition='train',
max_duration=16.0,):
""" Read metadata from the description file
(possibly takes long, depending on the filesize)
Params:
desc_file (str): Path to a JSON-line file that cont... | [
"def",
"load_metadata_from_desc_file",
"(",
"self",
",",
"desc_file",
",",
"partition",
"=",
"'train'",
",",
"max_duration",
"=",
"16.0",
",",
")",
":",
"logger",
"=",
"logUtil",
".",
"getlogger",
"(",
")",
"logger",
".",
"info",
"(",
"'Reading description fil... | 46.408163 | 0.001292 |
def find_bin(self, value):
"""Index of bin corresponding to a value.
Parameters
----------
value: float
Value to be searched for.
Returns
-------
int
index of bin to which value belongs
(-1=underflow, N=overflow, None=not foun... | [
"def",
"find_bin",
"(",
"self",
",",
"value",
")",
":",
"ixbin",
"=",
"np",
".",
"searchsorted",
"(",
"self",
".",
"bin_left_edges",
",",
"value",
",",
"side",
"=",
"\"right\"",
")",
"if",
"ixbin",
"==",
"0",
":",
"return",
"-",
"1",
"elif",
"ixbin",... | 29 | 0.002384 |
def invert(color):
"""Returns the inverse (negative) of a color. The red, green, and blue
values are inverted, while the opacity is left alone.
"""
if isinstance(color, Number):
# invert(n) and invert(n%) are CSS3 filters and should be left
# intact
return String.unquoted("inver... | [
"def",
"invert",
"(",
"color",
")",
":",
"if",
"isinstance",
"(",
"color",
",",
"Number",
")",
":",
"# invert(n) and invert(n%) are CSS3 filters and should be left",
"# intact",
"return",
"String",
".",
"unquoted",
"(",
"\"invert(%s)\"",
"%",
"(",
"color",
".",
"r... | 37.583333 | 0.002165 |
def extract_zip(filename, extract_dir):
""" Extract the sources in a temporary folder.
:arg filename, name of the zip file containing the data from MapQTL
which will be extracted
:arg extract_dir, folder in which to extract the archive.
"""
LOG.info("Extracting %s in %s " % (filename, extract_di... | [
"def",
"extract_zip",
"(",
"filename",
",",
"extract_dir",
")",
":",
"LOG",
".",
"info",
"(",
"\"Extracting %s in %s \"",
"%",
"(",
"filename",
",",
"extract_dir",
")",
")",
"if",
"not",
"os",
".",
"path",
".",
"exists",
"(",
"extract_dir",
")",
":",
"tr... | 39.833333 | 0.000583 |
def set_name_lists(ethnicity=None):
"""Set three globally available lists of names."""
if not ethnicity: ethnicity = random.choice(get_ethnicities())
print("Loading names from: " + ethnicity)
filename = names_dir + ethnicity + '.json'
try:
with open(filename, 'r') as injson:
dat... | [
"def",
"set_name_lists",
"(",
"ethnicity",
"=",
"None",
")",
":",
"if",
"not",
"ethnicity",
":",
"ethnicity",
"=",
"random",
".",
"choice",
"(",
"get_ethnicities",
"(",
")",
")",
"print",
"(",
"\"Loading names from: \"",
"+",
"ethnicity",
")",
"filename",
"=... | 35.043478 | 0.014493 |
def prepare(self):
"""
does some basic validation
"""
try:
assert(type(self.sender) is Channel)
assert(type(self.receiver) is Channel)
return True
except:
return False | [
"def",
"prepare",
"(",
"self",
")",
":",
"try",
":",
"assert",
"(",
"type",
"(",
"self",
".",
"sender",
")",
"is",
"Channel",
")",
"assert",
"(",
"type",
"(",
"self",
".",
"receiver",
")",
"is",
"Channel",
")",
"return",
"True",
"except",
":",
"ret... | 24.6 | 0.011765 |
def convert_boxed_text_elements(self):
"""
Textual material that is part of the body of text but outside the
flow of the narrative text, for example, a sidebar, marginalia, text
insert (whether enclosed in a box or not), caution, tip, note box, etc.
<boxed-text> elements for PLo... | [
"def",
"convert_boxed_text_elements",
"(",
"self",
")",
":",
"for",
"boxed_text",
"in",
"self",
".",
"main",
".",
"getroot",
"(",
")",
".",
"findall",
"(",
"'.//boxed-text'",
")",
":",
"sec_el",
"=",
"boxed_text",
".",
"find",
"(",
"'sec'",
")",
"if",
"s... | 48.321429 | 0.001449 |
def stem(self, word):
"""Return Lovins stem.
Parameters
----------
word : str
The word to stem
Returns
-------
str
Word stem
Examples
--------
>>> stmr = Lovins()
>>> stmr.stem('reading')
'read'
... | [
"def",
"stem",
"(",
"self",
",",
"word",
")",
":",
"# lowercase, normalize, and compose",
"word",
"=",
"normalize",
"(",
"'NFC'",
",",
"text_type",
"(",
"word",
".",
"lower",
"(",
")",
")",
")",
"for",
"suffix_len",
"in",
"range",
"(",
"11",
",",
"0",
... | 22.935484 | 0.001349 |
def format_exception(etype, value, tback, limit=None):
"""
Python 2 compatible version of traceback.format_exception
Accepts negative limits like the Python 3 version
"""
rtn = ['Traceback (most recent call last):\n']
if limit is None or limit >= 0:
rtn.extend(traceback.format_tb(tback... | [
"def",
"format_exception",
"(",
"etype",
",",
"value",
",",
"tback",
",",
"limit",
"=",
"None",
")",
":",
"rtn",
"=",
"[",
"'Traceback (most recent call last):\\n'",
"]",
"if",
"limit",
"is",
"None",
"or",
"limit",
">=",
"0",
":",
"rtn",
".",
"extend",
"... | 30.125 | 0.002012 |
def startswith(string, prefix):
"""
Like str.startswith, but also checks that the string starts with the given prefixes sequence of graphemes.
str.startswith may return true for a prefix that is not visually represented as a prefix if a grapheme cluster
is continued after the prefix ends.
>>> grap... | [
"def",
"startswith",
"(",
"string",
",",
"prefix",
")",
":",
"return",
"string",
".",
"startswith",
"(",
"prefix",
")",
"and",
"safe_split_index",
"(",
"string",
",",
"len",
"(",
"prefix",
")",
")",
"==",
"len",
"(",
"prefix",
")"
] | 37.230769 | 0.008065 |
def list_flavors(self, retrieve_all=True, **_params):
"""Fetches a list of all Neutron service flavors for a project."""
return self.list('flavors', self.flavors_path, retrieve_all,
**_params) | [
"def",
"list_flavors",
"(",
"self",
",",
"retrieve_all",
"=",
"True",
",",
"*",
"*",
"_params",
")",
":",
"return",
"self",
".",
"list",
"(",
"'flavors'",
",",
"self",
".",
"flavors_path",
",",
"retrieve_all",
",",
"*",
"*",
"_params",
")"
] | 57.5 | 0.008584 |
def maximum(self, node):
"""
find the max node when node regard as a root node
:param node:
:return: max node
"""
temp_node = node
while temp_node.right is not None:
temp_node = temp_node.right
return temp_node | [
"def",
"maximum",
"(",
"self",
",",
"node",
")",
":",
"temp_node",
"=",
"node",
"while",
"temp_node",
".",
"right",
"is",
"not",
"None",
":",
"temp_node",
"=",
"temp_node",
".",
"right",
"return",
"temp_node"
] | 28.2 | 0.017182 |
def size(cls, pid):
"""Return the number of connections in the pool
:param str pid: The pool id
:rtype int
"""
with cls._lock:
cls._ensure_pool_exists(pid)
return len(cls._pools[pid]) | [
"def",
"size",
"(",
"cls",
",",
"pid",
")",
":",
"with",
"cls",
".",
"_lock",
":",
"cls",
".",
"_ensure_pool_exists",
"(",
"pid",
")",
"return",
"len",
"(",
"cls",
".",
"_pools",
"[",
"pid",
"]",
")"
] | 24 | 0.008032 |
def __calculate_score(self, index_point, index_cluster):
"""!
@brief Calculates Silhouette score for the specific object defined by index_point.
@param[in] index_point (uint): Index point from input data for which Silhouette score should be calculated.
@param[in] index_cluster (uin... | [
"def",
"__calculate_score",
"(",
"self",
",",
"index_point",
",",
"index_cluster",
")",
":",
"difference",
"=",
"self",
".",
"__calculate_dataset_difference",
"(",
"index_point",
")",
"a_score",
"=",
"self",
".",
"__calculate_within_cluster_score",
"(",
"index_cluster... | 46.3125 | 0.009259 |
def success(self):
"""Return boolean indicating whether a solution was found."""
self._check_valid()
return self._problem._p.Status == gurobipy.GRB.OPTIMAL | [
"def",
"success",
"(",
"self",
")",
":",
"self",
".",
"_check_valid",
"(",
")",
"return",
"self",
".",
"_problem",
".",
"_p",
".",
"Status",
"==",
"gurobipy",
".",
"GRB",
".",
"OPTIMAL"
] | 44 | 0.011173 |
def calculate_category_probability(self):
"""
Caches the individual probabilities for each category
"""
total_tally = 0.0
probs = {}
for category, bayes_category in \
self.categories.get_categories().items():
count = bayes_category.get_tally()
... | [
"def",
"calculate_category_probability",
"(",
"self",
")",
":",
"total_tally",
"=",
"0.0",
"probs",
"=",
"{",
"}",
"for",
"category",
",",
"bayes_category",
"in",
"self",
".",
"categories",
".",
"get_categories",
"(",
")",
".",
"items",
"(",
")",
":",
"cou... | 36.692308 | 0.002043 |
def run_query(db, query):
'''
Run SQL query and return result
CLI Example:
.. code-block:: bash
salt '*' oracle.run_query my_db "select * from my_table"
'''
if db in [x.keys()[0] for x in show_dbs()]:
conn = _connect(show_dbs(db)[db]['uri'])
else:
log.debug('No uri... | [
"def",
"run_query",
"(",
"db",
",",
"query",
")",
":",
"if",
"db",
"in",
"[",
"x",
".",
"keys",
"(",
")",
"[",
"0",
"]",
"for",
"x",
"in",
"show_dbs",
"(",
")",
"]",
":",
"conn",
"=",
"_connect",
"(",
"show_dbs",
"(",
"db",
")",
"[",
"db",
... | 30.5 | 0.001767 |
def write(*args, **kwargs):
"""Redirectable wrapper for print statements."""
debug = kwargs.pop("debug", None)
warning = kwargs.pop("warning", None)
if _logger:
kwargs.pop("end", None)
kwargs.pop("file", None)
if debug:
_logger.debug(*args, **kwargs)
elif warn... | [
"def",
"write",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"debug",
"=",
"kwargs",
".",
"pop",
"(",
"\"debug\"",
",",
"None",
")",
"warning",
"=",
"kwargs",
".",
"pop",
"(",
"\"warning\"",
",",
"None",
")",
"if",
"_logger",
":",
"kwargs",... | 30.133333 | 0.002146 |
def make_date(df:DataFrame, date_field:str):
"Make sure `df[field_name]` is of the right date type."
field_dtype = df[date_field].dtype
if isinstance(field_dtype, pd.core.dtypes.dtypes.DatetimeTZDtype):
field_dtype = np.datetime64
if not np.issubdtype(field_dtype, np.datetime64):
df[date... | [
"def",
"make_date",
"(",
"df",
":",
"DataFrame",
",",
"date_field",
":",
"str",
")",
":",
"field_dtype",
"=",
"df",
"[",
"date_field",
"]",
".",
"dtype",
"if",
"isinstance",
"(",
"field_dtype",
",",
"pd",
".",
"core",
".",
"dtypes",
".",
"dtypes",
".",... | 54.571429 | 0.010309 |
def ip_addrs(interface=None, include_loopback=False, cidr=None, type=None):
'''
Returns a list of IPv4 addresses assigned to the host.
interface
Only IP addresses from that interface will be returned.
include_loopback : False
Include loopback 127.0.0.1 IPv4 address.
cidr
D... | [
"def",
"ip_addrs",
"(",
"interface",
"=",
"None",
",",
"include_loopback",
"=",
"False",
",",
"cidr",
"=",
"None",
",",
"type",
"=",
"None",
")",
":",
"addrs",
"=",
"salt",
".",
"utils",
".",
"network",
".",
"ip_addrs",
"(",
"interface",
"=",
"interfac... | 30.195122 | 0.001565 |
def get_google_links(limit, params, headers):
"""
function to fetch links equal to limit
every Google search result page has a start index.
every page contains 10 search results.
"""
links = []
for start_index in range(0, limit, 10):
params['start'] = start_index
resp = s.get("https://www.google.com/search"... | [
"def",
"get_google_links",
"(",
"limit",
",",
"params",
",",
"headers",
")",
":",
"links",
"=",
"[",
"]",
"for",
"start_index",
"in",
"range",
"(",
"0",
",",
"limit",
",",
"10",
")",
":",
"params",
"[",
"'start'",
"]",
"=",
"start_index",
"resp",
"="... | 32.071429 | 0.04329 |
def add_star(self, component=None, **kwargs):
"""
Shortcut to :meth:`add_component` but with kind='star'
"""
kwargs.setdefault('component', component)
return self.add_component('star', **kwargs) | [
"def",
"add_star",
"(",
"self",
",",
"component",
"=",
"None",
",",
"*",
"*",
"kwargs",
")",
":",
"kwargs",
".",
"setdefault",
"(",
"'component'",
",",
"component",
")",
"return",
"self",
".",
"add_component",
"(",
"'star'",
",",
"*",
"*",
"kwargs",
")... | 38.166667 | 0.008547 |
def estimate(data, fit_offset="mean", fit_profile="tilt",
border_px=0, from_mask=None, ret_mask=False):
"""Estimate the background value of an image
Parameters
----------
data: np.ndarray
Data from which to compute the background value
fit_profile: str
The type of backg... | [
"def",
"estimate",
"(",
"data",
",",
"fit_offset",
"=",
"\"mean\"",
",",
"fit_profile",
"=",
"\"tilt\"",
",",
"border_px",
"=",
"0",
",",
"from_mask",
"=",
"None",
",",
"ret_mask",
"=",
"False",
")",
":",
"if",
"fit_profile",
"not",
"in",
"VALID_FIT_PROFIL... | 34.266667 | 0.000315 |
def run_step(context):
"""Get $ENVs, allowing a default if not found.
Set context properties from environment variables, and specify a default
if the environment variable is not found.
This differs from pypyr.steps.env get, which raises an error if attempting
to read an $ENV that doesn't exist.
... | [
"def",
"run_step",
"(",
"context",
")",
":",
"logger",
".",
"debug",
"(",
"\"started\"",
")",
"assert",
"context",
",",
"f\"context must have value for {__name__}\"",
"context",
".",
"assert_key_has_value",
"(",
"'envGet'",
",",
"__name__",
")",
"# allow a list OR a s... | 31.852941 | 0.000448 |
def truncate(self, date):
"""Truncate data beyond this date in all ctables."""
truncate_slice_end = self.data_len_for_day(date)
glob_path = os.path.join(self._rootdir, "*", "*", "*.bcolz")
sid_paths = sorted(glob(glob_path))
for sid_path in sid_paths:
file_name = os... | [
"def",
"truncate",
"(",
"self",
",",
"date",
")",
":",
"truncate_slice_end",
"=",
"self",
".",
"data_len_for_day",
"(",
"date",
")",
"glob_path",
"=",
"os",
".",
"path",
".",
"join",
"(",
"self",
".",
"_rootdir",
",",
"\"*\"",
",",
"\"*\"",
",",
"\"*.b... | 33.285714 | 0.002086 |
def database_add_tags(object_id, input_params={}, always_retry=True, **kwargs):
"""
Invokes the /database-xxxx/addTags API method.
For more info, see: https://wiki.dnanexus.com/API-Specification-v1.0.0/Tags#API-method%3A-%2Fclass-xxxx%2FaddTags
"""
return DXHTTPRequest('/%s/addTags' % object_id, in... | [
"def",
"database_add_tags",
"(",
"object_id",
",",
"input_params",
"=",
"{",
"}",
",",
"always_retry",
"=",
"True",
",",
"*",
"*",
"kwargs",
")",
":",
"return",
"DXHTTPRequest",
"(",
"'/%s/addTags'",
"%",
"object_id",
",",
"input_params",
",",
"always_retry",
... | 51.714286 | 0.008152 |
def wash_line(line):
"""Wash a text line of certain punctuation errors, replacing them with
more correct alternatives. E.g.: the string 'Yes , I like python.'
will be transformed into 'Yes, I like python.'
@param line: (string) the line to be washed.
@return: (string) the washed line.
... | [
"def",
"wash_line",
"(",
"line",
")",
":",
"line",
"=",
"re_space_comma",
".",
"sub",
"(",
"','",
",",
"line",
")",
"line",
"=",
"re_space_semicolon",
".",
"sub",
"(",
"';'",
",",
"line",
")",
"line",
"=",
"re_space_period",
".",
"sub",
"(",
"'.'",
"... | 43.823529 | 0.001314 |
async def initialize(bot: Bot, host, password, rest_port, ws_port, timeout=30):
"""
Initializes the websocket connection to the lavalink player.
.. important::
This function must only be called AFTER the bot has received its
"on_ready" event!
Parameters
----------
bot : Bot
... | [
"async",
"def",
"initialize",
"(",
"bot",
":",
"Bot",
",",
"host",
",",
"password",
",",
"rest_port",
",",
"ws_port",
",",
"timeout",
"=",
"30",
")",
":",
"global",
"_loop",
"_loop",
"=",
"bot",
".",
"loop",
"player_manager",
".",
"user_id",
"=",
"bot"... | 28.32 | 0.001365 |
def run():
"""CLI endpoint."""
sys.path.insert(0, os.getcwd())
logging.basicConfig(level=logging.INFO, handlers=[logging.StreamHandler()])
parser = argparse.ArgumentParser(description="Manage Application", add_help=False)
parser.add_argument('app', metavar='app',
type=str, h... | [
"def",
"run",
"(",
")",
":",
"sys",
".",
"path",
".",
"insert",
"(",
"0",
",",
"os",
".",
"getcwd",
"(",
")",
")",
"logging",
".",
"basicConfig",
"(",
"level",
"=",
"logging",
".",
"INFO",
",",
"handlers",
"=",
"[",
"logging",
".",
"StreamHandler",... | 35.137931 | 0.00191 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.