text stringlengths 89 104k | code_tokens list | avg_line_len float64 7.91 980 | score float64 0 630 |
|---|---|---|---|
def prepare_timestamp_micros(data, schema):
"""Converts datetime.datetime to int timestamp with microseconds"""
if isinstance(data, datetime.datetime):
if data.tzinfo is not None:
delta = (data - epoch)
return int(delta.total_seconds() * MCS_PER_SECOND)
t = int(time.mktim... | [
"def",
"prepare_timestamp_micros",
"(",
"data",
",",
"schema",
")",
":",
"if",
"isinstance",
"(",
"data",
",",
"datetime",
".",
"datetime",
")",
":",
"if",
"data",
".",
"tzinfo",
"is",
"not",
"None",
":",
"delta",
"=",
"(",
"data",
"-",
"epoch",
")",
... | 38.818182 | 14 |
def remap_overlapping_column_names(table_op, root_table, data_columns):
"""Return an ``OrderedDict`` mapping possibly suffixed column names to
column names without suffixes.
Parameters
----------
table_op : TableNode
The ``TableNode`` we're selecting from.
root_table : TableNode
... | [
"def",
"remap_overlapping_column_names",
"(",
"table_op",
",",
"root_table",
",",
"data_columns",
")",
":",
"if",
"not",
"isinstance",
"(",
"table_op",
",",
"ops",
".",
"Join",
")",
":",
"return",
"None",
"left_root",
",",
"right_root",
"=",
"ops",
".",
"dis... | 30.783784 | 19.351351 |
def get_section_relations(Section):
"""Find every relationship between section and the item model."""
all_rels = (Section._meta.get_all_related_objects() +
Section._meta.get_all_related_many_to_many_objects())
return filter_item_rels(all_rels) | [
"def",
"get_section_relations",
"(",
"Section",
")",
":",
"all_rels",
"=",
"(",
"Section",
".",
"_meta",
".",
"get_all_related_objects",
"(",
")",
"+",
"Section",
".",
"_meta",
".",
"get_all_related_many_to_many_objects",
"(",
")",
")",
"return",
"filter_item_rels... | 53.4 | 10.8 |
def messageReceived(self, value, sender, target):
"""
An AMP-formatted message was received. Dispatch to the appropriate
command responder, i.e. a method on this object exposed with
L{commandMethod.expose}.
@see IMessageReceiver.messageReceived
"""
if value.type... | [
"def",
"messageReceived",
"(",
"self",
",",
"value",
",",
"sender",
",",
"target",
")",
":",
"if",
"value",
".",
"type",
"!=",
"AMP_MESSAGE_TYPE",
":",
"raise",
"UnknownMessageType",
"(",
")",
"inputBox",
"=",
"self",
".",
"_boxFromData",
"(",
"value",
"."... | 45.56 | 16.92 |
def expect_loop(self, searcher, timeout=-1, searchwindowsize=-1):
'''This is the common loop used inside expect. The 'searcher' should be
an instance of searcher_re or searcher_string, which describes how and
what to search for in the input.
See expect() for other arguments, return valu... | [
"def",
"expect_loop",
"(",
"self",
",",
"searcher",
",",
"timeout",
"=",
"-",
"1",
",",
"searchwindowsize",
"=",
"-",
"1",
")",
":",
"exp",
"=",
"Expecter",
"(",
"self",
",",
"searcher",
",",
"searchwindowsize",
")",
"return",
"exp",
".",
"expect_loop",
... | 47.888889 | 25.888889 |
def unregister_checker(self, checker):
"""Unregister a checker instance."""
if checker in self._checkers:
self._checkers.remove(checker) | [
"def",
"unregister_checker",
"(",
"self",
",",
"checker",
")",
":",
"if",
"checker",
"in",
"self",
".",
"_checkers",
":",
"self",
".",
"_checkers",
".",
"remove",
"(",
"checker",
")"
] | 40.25 | 1.75 |
def delete(cls, session, record, endpoint_override=None, out_type=None):
"""Delete a record.
Args:
session (requests.sessions.Session): Authenticated session.
record (helpscout.BaseModel): The record to be deleted.
endpoint_override (str, optional): Override the defa... | [
"def",
"delete",
"(",
"cls",
",",
"session",
",",
"record",
",",
"endpoint_override",
"=",
"None",
",",
"out_type",
"=",
"None",
")",
":",
"cls",
".",
"_check_implements",
"(",
"'delete'",
")",
"return",
"cls",
"(",
"endpoint_override",
"or",
"'/%s/%s.json'"... | 35.68 | 19.52 |
def reconfigure_bird(cmd):
"""Reconfigure BIRD daemon.
Arguments:
cmd (string): A command to trigger a reconfiguration of Bird daemon
Notes:
Runs 'birdc configure' to reconfigure BIRD. Some useful information on
how birdc tool works:
-- Returns a non-zero exit code only... | [
"def",
"reconfigure_bird",
"(",
"cmd",
")",
":",
"log",
"=",
"logging",
".",
"getLogger",
"(",
"PROGRAM_NAME",
")",
"cmd",
"=",
"shlex",
".",
"split",
"(",
"cmd",
")",
"log",
".",
"info",
"(",
"\"reconfiguring BIRD by running %s\"",
",",
"' '",
".",
"join"... | 42.574074 | 21.388889 |
def __extract_model_summary_value(model, value):
"""
Extract a model summary field value
"""
field_value = None
if isinstance(value, _precomputed_field):
field_value = value.field
else:
field_value = model._get(value)
if isinstance(field_value, float):
try:
... | [
"def",
"__extract_model_summary_value",
"(",
"model",
",",
"value",
")",
":",
"field_value",
"=",
"None",
"if",
"isinstance",
"(",
"value",
",",
"_precomputed_field",
")",
":",
"field_value",
"=",
"value",
".",
"field",
"else",
":",
"field_value",
"=",
"model"... | 26.6 | 11.666667 |
def is_repository(self, path):
"""
Check if there is a Repository in path.
:Parameters:
#. path (string): The real path of the directory where to check if there is a repository.
:Returns:
#. result (boolean): Whether its a repository or not.
"""
... | [
"def",
"is_repository",
"(",
"self",
",",
"path",
")",
":",
"realPath",
"=",
"os",
".",
"path",
".",
"realpath",
"(",
"os",
".",
"path",
".",
"expanduser",
"(",
"path",
")",
")",
"if",
"not",
"os",
".",
"path",
".",
"isdir",
"(",
"realPath",
")",
... | 32.6875 | 19.6875 |
def decompress_G1(z: G1Compressed) -> G1Uncompressed:
"""
Recovers x and y coordinates from the compressed point.
"""
# b_flag == 1 indicates the infinity point
b_flag = (z % POW_2_383) // POW_2_382
if b_flag == 1:
return Z1
x = z % POW_2_381
# Try solving y coordinate from the ... | [
"def",
"decompress_G1",
"(",
"z",
":",
"G1Compressed",
")",
"->",
"G1Uncompressed",
":",
"# b_flag == 1 indicates the infinity point",
"b_flag",
"=",
"(",
"z",
"%",
"POW_2_383",
")",
"//",
"POW_2_382",
"if",
"b_flag",
"==",
"1",
":",
"return",
"Z1",
"x",
"=",
... | 31.304348 | 15.130435 |
def iter_bitstream(self, iter_duration_generator):
"""
iterate over self.iter_trigger() and
yield the bits
"""
assert self.half_sinus == False # Allways trigger full sinus cycle
# build min/max Hz values
bit_nul_min_hz = self.cfg.BIT_NUL_HZ - self.cfg.HZ_VARIATIO... | [
"def",
"iter_bitstream",
"(",
"self",
",",
"iter_duration_generator",
")",
":",
"assert",
"self",
".",
"half_sinus",
"==",
"False",
"# Allways trigger full sinus cycle",
"# build min/max Hz values",
"bit_nul_min_hz",
"=",
"self",
".",
"cfg",
".",
"BIT_NUL_HZ",
"-",
"s... | 38.916667 | 22 |
def _dihed_cos_low(a, b, c, deriv):
"""Similar to dihed_cos, but with relative vectors"""
a = Vector3(9, deriv, a, (0, 1, 2))
b = Vector3(9, deriv, b, (3, 4, 5))
c = Vector3(9, deriv, c, (6, 7, 8))
b /= b.norm()
tmp = b.copy()
tmp *= dot(a, b)
a -= tmp
tmp = b.copy()
tmp *= dot(c... | [
"def",
"_dihed_cos_low",
"(",
"a",
",",
"b",
",",
"c",
",",
"deriv",
")",
":",
"a",
"=",
"Vector3",
"(",
"9",
",",
"deriv",
",",
"a",
",",
"(",
"0",
",",
"1",
",",
"2",
")",
")",
"b",
"=",
"Vector3",
"(",
"9",
",",
"deriv",
",",
"b",
",",... | 26 | 15.133333 |
def main():
'''Main routine.'''
# validate command line arguments
arg_parser = argparse.ArgumentParser()
arg_parser.add_argument('--name', '-n', required=True, action='store', help='Name')
arg_parser.add_argument('--rgname', '-g', required=True, action='store',
help='Res... | [
"def",
"main",
"(",
")",
":",
"# validate command line arguments",
"arg_parser",
"=",
"argparse",
".",
"ArgumentParser",
"(",
")",
"arg_parser",
".",
"add_argument",
"(",
"'--name'",
",",
"'-n'",
",",
"required",
"=",
"True",
",",
"action",
"=",
"'store'",
","... | 37.9375 | 23.705357 |
def get_sample(self, res, resMode='abs', DL=None, method='sum', ind=None,
compact=False):
""" Return a linear sampling of the LOS
The LOS is sampled into a series a points and segments lengths
The resolution (segments length) is <= res
The sampling can be done accordin... | [
"def",
"get_sample",
"(",
"self",
",",
"res",
",",
"resMode",
"=",
"'abs'",
",",
"DL",
"=",
"None",
",",
"method",
"=",
"'sum'",
",",
"ind",
"=",
"None",
",",
"compact",
"=",
"False",
")",
":",
"ind",
"=",
"self",
".",
"_check_indch",
"(",
"ind",
... | 43.125 | 21.443182 |
def _unfuse(self):
"""Unfuses the fused RNN in to a stack of rnn cells."""
assert not self._projection_size, "_unfuse does not support projection layer yet!"
assert not self._lstm_state_clip_min and not self._lstm_state_clip_max, \
"_unfuse does not support state clipping yet!"
... | [
"def",
"_unfuse",
"(",
"self",
")",
":",
"assert",
"not",
"self",
".",
"_projection_size",
",",
"\"_unfuse does not support projection layer yet!\"",
"assert",
"not",
"self",
".",
"_lstm_state_clip_min",
"and",
"not",
"self",
".",
"_lstm_state_clip_max",
",",
"\"_unfu... | 57.289474 | 29.421053 |
def _get_signature_type_and_params(self, request):
"""Extracts parameters from query, headers and body. Signature type
is set to the source in which parameters were found.
"""
# Per RFC5849, only the Authorization header may contain the 'realm'
# optional parameter.
heade... | [
"def",
"_get_signature_type_and_params",
"(",
"self",
",",
"request",
")",
":",
"# Per RFC5849, only the Authorization header may contain the 'realm'",
"# optional parameter.",
"header_params",
"=",
"signature",
".",
"collect_parameters",
"(",
"headers",
"=",
"request",
".",
... | 47.853659 | 22.341463 |
def mail_sent_content(self, text, part):
"""
Test an email contains (assert text in) the given text in the relevant
message part (accessible as an attribute on the email object).
This step strictly applies whitespace.
Syntax:
I have sent an email with "`text`" in the `part`
Example:
... | [
"def",
"mail_sent_content",
"(",
"self",
",",
"text",
",",
"part",
")",
":",
"if",
"not",
"any",
"(",
"text",
"in",
"getattr",
"(",
"email",
",",
"part",
")",
"for",
"email",
"in",
"mail",
".",
"outbox",
")",
":",
"dump_emails",
"(",
"part",
")",
"... | 28.428571 | 23.571429 |
def generate_code(max_length, max_nest, ops):
"""Generates code samples.
Args:
max_length: int. max literal length.
max_nest: int. max nesting level.
ops: CodeOp. set of allowable operations.
Returns:
1. (str) output value.
2. (str) Code operation.
"""
stack = []
def fetch_one():
... | [
"def",
"generate_code",
"(",
"max_length",
",",
"max_nest",
",",
"ops",
")",
":",
"stack",
"=",
"[",
"]",
"def",
"fetch_one",
"(",
")",
":",
"# Always use an existing nested value for one of the operands.",
"if",
"stack",
":",
"return",
"stack",
".",
"pop",
"(",... | 29.25641 | 17.025641 |
def _get_metadata(self, key='', default=None, builtin=True):
"""
get_metadata([key, default, simple])
Retrieve metadata with nested keys separated by dots.
This is useful to avoid repeatedly checking if a dict exists, as
the frontmatter might not have the keys that we expect.
With ``builtin=T... | [
"def",
"_get_metadata",
"(",
"self",
",",
"key",
"=",
"''",
",",
"default",
"=",
"None",
",",
"builtin",
"=",
"True",
")",
":",
"# Retrieve metadata",
"assert",
"isinstance",
"(",
"key",
",",
"str",
")",
"meta",
"=",
"self",
".",
"metadata",
"# Retrieve ... | 35.8 | 27.15 |
def encodeMessage(self, events):
"""Encode a list of Tensor events with protobuf"""
message = proto_pb2.Msg(
events=[self.encodeEvent(e) for e in events if e._type=='riemann']
)
return message.SerializeToString() | [
"def",
"encodeMessage",
"(",
"self",
",",
"events",
")",
":",
"message",
"=",
"proto_pb2",
".",
"Msg",
"(",
"events",
"=",
"[",
"self",
".",
"encodeEvent",
"(",
"e",
")",
"for",
"e",
"in",
"events",
"if",
"e",
".",
"_type",
"==",
"'riemann'",
"]",
... | 31.375 | 20.875 |
def pop(self, count):
"""Returns new context stack, which doesn't contain few levels
"""
if len(self._contexts) - 1 < count:
_logger.error("#pop value is too big %d", len(self._contexts))
if len(self._contexts) > 1:
return ContextStack(self._contexts[:1], ... | [
"def",
"pop",
"(",
"self",
",",
"count",
")",
":",
"if",
"len",
"(",
"self",
".",
"_contexts",
")",
"-",
"1",
"<",
"count",
":",
"_logger",
".",
"error",
"(",
"\"#pop value is too big %d\"",
",",
"len",
"(",
"self",
".",
"_contexts",
")",
")",
"if",
... | 40.545455 | 17.909091 |
def serverUrl(self, value):
"""gets/sets the server url"""
if value.lower() != self._serverUrl.lower():
self._serverUrl = value | [
"def",
"serverUrl",
"(",
"self",
",",
"value",
")",
":",
"if",
"value",
".",
"lower",
"(",
")",
"!=",
"self",
".",
"_serverUrl",
".",
"lower",
"(",
")",
":",
"self",
".",
"_serverUrl",
"=",
"value"
] | 38 | 7.5 |
def PauseHunt(hunt_id, reason=None):
"""Pauses a hunt with a given id."""
hunt_obj = data_store.REL_DB.ReadHuntObject(hunt_id)
if hunt_obj.hunt_state != hunt_obj.HuntState.STARTED:
raise OnlyStartedHuntCanBePausedError(hunt_obj)
data_store.REL_DB.UpdateHuntObject(
hunt_id, hunt_state=hunt_obj.HuntSt... | [
"def",
"PauseHunt",
"(",
"hunt_id",
",",
"reason",
"=",
"None",
")",
":",
"hunt_obj",
"=",
"data_store",
".",
"REL_DB",
".",
"ReadHuntObject",
"(",
"hunt_id",
")",
"if",
"hunt_obj",
".",
"hunt_state",
"!=",
"hunt_obj",
".",
"HuntState",
".",
"STARTED",
":"... | 38.583333 | 19.916667 |
def _split_sched_block_instance(self, scheduling_block):
"""Split the scheduling block data into multiple names
before adding to the configuration database"""
# Initialise empty list
_scheduling_block_data = {}
_processing_block_data = {}
_processing_block_id = []
... | [
"def",
"_split_sched_block_instance",
"(",
"self",
",",
"scheduling_block",
")",
":",
"# Initialise empty list",
"_scheduling_block_data",
"=",
"{",
"}",
"_processing_block_data",
"=",
"{",
"}",
"_processing_block_id",
"=",
"[",
"]",
"for",
"block",
"in",
"scheduling_... | 40.1875 | 19.0625 |
def applications(self):
"""returns all the group applications to join"""
url = self._url + "/applications"
params = {"f" : "json"}
res = self._get(url=url,
param_dict=params,
proxy_url=self._proxy_url,
proxy... | [
"def",
"applications",
"(",
"self",
")",
":",
"url",
"=",
"self",
".",
"_url",
"+",
"\"/applications\"",
"params",
"=",
"{",
"\"f\"",
":",
"\"json\"",
"}",
"res",
"=",
"self",
".",
"_get",
"(",
"url",
"=",
"url",
",",
"param_dict",
"=",
"params",
","... | 43.777778 | 15.111111 |
async def _on_progress_notification(self, progress):
"""Callback function called when a progress notification is received.
Args:
progress (dict): The received notification containing the progress information
"""
conn_string = progress.get('connection_string')
done =... | [
"async",
"def",
"_on_progress_notification",
"(",
"self",
",",
"progress",
")",
":",
"conn_string",
"=",
"progress",
".",
"get",
"(",
"'connection_string'",
")",
"done",
"=",
"progress",
".",
"get",
"(",
"'done_count'",
")",
"total",
"=",
"progress",
".",
"g... | 39.153846 | 21.153846 |
def delete_bams(job, bams, patient_id):
"""
Delete the bams from the job Store once their purpose has been achieved (i.e. after all
mutation calling steps). Will also delete the chimeric junction file from Star.
:param dict bams: Dict of bam and bai files
:param str patient_id: The ID of the patien... | [
"def",
"delete_bams",
"(",
"job",
",",
"bams",
",",
"patient_id",
")",
":",
"bams",
"=",
"{",
"b",
":",
"v",
"for",
"b",
",",
"v",
"in",
"bams",
".",
"items",
"(",
")",
"if",
"(",
"b",
".",
"endswith",
"(",
"'.bam'",
")",
"or",
"b",
".",
"end... | 49.041667 | 23.541667 |
def pop( self, *args, **kwargs):
"""
Removes and returns item at specified index (default= ``last``).
Supports both ``list`` and ``dict`` semantics for ``pop()``. If
passed no argument or an integer argument, it will use ``list``
semantics and pop tokens from the list of parsed t... | [
"def",
"pop",
"(",
"self",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"if",
"not",
"args",
":",
"args",
"=",
"[",
"-",
"1",
"]",
"for",
"k",
",",
"v",
"in",
"kwargs",
".",
"items",
"(",
")",
":",
"if",
"k",
"==",
"'default'",
":",... | 37.611111 | 20.981481 |
def fastMean(img, f=10, inplace=False):
'''
for bigger ksizes it if often faster to resize an image
rather than blur it...
'''
s0,s1 = img.shape[:2]
ss0 = int(round(s0/f))
ss1 = int(round(s1/f))
small = cv2.resize(img,(ss1,ss0), interpolation=cv2.INTER_AREA)
#bigger
... | [
"def",
"fastMean",
"(",
"img",
",",
"f",
"=",
"10",
",",
"inplace",
"=",
"False",
")",
":",
"s0",
",",
"s1",
"=",
"img",
".",
"shape",
"[",
":",
"2",
"]",
"ss0",
"=",
"int",
"(",
"round",
"(",
"s0",
"/",
"f",
")",
")",
"ss1",
"=",
"int",
... | 28.6 | 18.333333 |
def get_ec2_info(instance_id,
region,
access_key_id,
secret_access_key,
username):
""" queries EC2 for details about a particular instance_id
"""
conn = connect_to_ec2(region, access_key_id, secret_access_key)
instance = conn.get_only_i... | [
"def",
"get_ec2_info",
"(",
"instance_id",
",",
"region",
",",
"access_key_id",
",",
"secret_access_key",
",",
"username",
")",
":",
"conn",
"=",
"connect_to_ec2",
"(",
"region",
",",
"access_key_id",
",",
"secret_access_key",
")",
"instance",
"=",
"conn",
".",
... | 35.333333 | 16.230769 |
def get(self, query, *parameters, **kwparameters):
"""Returns the first row returned for the given query."""
rows = self._query(query, parameters, kwparameters)
if not rows:
return None
elif not isinstance(rows, list):
raise MySQLError("Query is not a select query... | [
"def",
"get",
"(",
"self",
",",
"query",
",",
"*",
"parameters",
",",
"*",
"*",
"kwparameters",
")",
":",
"rows",
"=",
"self",
".",
"_query",
"(",
"query",
",",
"parameters",
",",
"kwparameters",
")",
"if",
"not",
"rows",
":",
"return",
"None",
"elif... | 41.909091 | 16.181818 |
def present(name,
tablespace=None,
encoding=None,
lc_collate=None,
lc_ctype=None,
owner=None,
owner_recurse=False,
template=None,
user=None,
maintenance_db=None,
db_password=None,
db_host=... | [
"def",
"present",
"(",
"name",
",",
"tablespace",
"=",
"None",
",",
"encoding",
"=",
"None",
",",
"lc_collate",
"=",
"None",
",",
"lc_ctype",
"=",
"None",
",",
"owner",
"=",
"None",
",",
"owner_recurse",
"=",
"False",
",",
"template",
"=",
"None",
",",... | 30.411765 | 22.735294 |
async def _retrieve_messages_around_strategy(self, retrieve):
"""Retrieve messages using around parameter."""
if self.around:
around = self.around.id if self.around else None
data = await self.logs_from(self.channel.id, retrieve, around=around)
self.around = None
... | [
"async",
"def",
"_retrieve_messages_around_strategy",
"(",
"self",
",",
"retrieve",
")",
":",
"if",
"self",
".",
"around",
":",
"around",
"=",
"self",
".",
"around",
".",
"id",
"if",
"self",
".",
"around",
"else",
"None",
"data",
"=",
"await",
"self",
".... | 43.75 | 18.625 |
def degree(self, vertex):
"""
Return the degree of a vertex
"""
try:
return len(self.vertices[vertex])
except KeyError:
raise GraphInsertError("Vertex %s doesn't exist." % (vertex,)) | [
"def",
"degree",
"(",
"self",
",",
"vertex",
")",
":",
"try",
":",
"return",
"len",
"(",
"self",
".",
"vertices",
"[",
"vertex",
"]",
")",
"except",
"KeyError",
":",
"raise",
"GraphInsertError",
"(",
"\"Vertex %s doesn't exist.\"",
"%",
"(",
"vertex",
",",... | 30.75 | 12.25 |
def word_break(s, word_dict):
"""
:type s: str
:type word_dict: Set[str]
:rtype: bool
"""
dp = [False] * (len(s)+1)
dp[0] = True
for i in range(1, len(s)+1):
for j in range(0, i):
if dp[j] and s[j:i] in word_dict:
dp[i] = True
break
... | [
"def",
"word_break",
"(",
"s",
",",
"word_dict",
")",
":",
"dp",
"=",
"[",
"False",
"]",
"*",
"(",
"len",
"(",
"s",
")",
"+",
"1",
")",
"dp",
"[",
"0",
"]",
"=",
"True",
"for",
"i",
"in",
"range",
"(",
"1",
",",
"len",
"(",
"s",
")",
"+",... | 22.928571 | 13.071429 |
def keyReleaseEvent(self, event):
"""Override Qt method."""
if event.key() == Qt.Key_Alt:
self._alt_key_is_down = False
self.update() | [
"def",
"keyReleaseEvent",
"(",
"self",
",",
"event",
")",
":",
"if",
"event",
".",
"key",
"(",
")",
"==",
"Qt",
".",
"Key_Alt",
":",
"self",
".",
"_alt_key_is_down",
"=",
"False",
"self",
".",
"update",
"(",
")"
] | 33.8 | 5.2 |
def generate_type_docs(types):
"""Parse an object of types and generate RAML documentation for them.
Expects each type to be either a regular type or a list/array. If a type is a list,
it must specify what type to use for each item.
"""
output = StringIO()
indent = " " # 2
# loop through... | [
"def",
"generate_type_docs",
"(",
"types",
")",
":",
"output",
"=",
"StringIO",
"(",
")",
"indent",
"=",
"\" \"",
"# 2",
"# loop through the basic types and add them to the RAML formatted output",
"for",
"type_name",
"in",
"types",
":",
"if",
"types",
"[",
"type_name... | 35.439024 | 24.073171 |
def build_database_sortmerna(fasta_path,
max_pos=None,
output_dir=None,
temp_dir=tempfile.gettempdir(),
HALT_EXEC=False):
""" Build sortmerna db from fasta_path; return db name
and list of fil... | [
"def",
"build_database_sortmerna",
"(",
"fasta_path",
",",
"max_pos",
"=",
"None",
",",
"output_dir",
"=",
"None",
",",
"temp_dir",
"=",
"tempfile",
".",
"gettempdir",
"(",
")",
",",
"HALT_EXEC",
"=",
"False",
")",
":",
"if",
"fasta_path",
"is",
"None",
":... | 33.985915 | 17.464789 |
def mkconstraints():
"""
Make constraint list for binary constraint problem.
"""
constraints = []
for j in range(1, 10):
vars = ["%s%d" % (i, j) for i in uppercase[:9]]
constraints.extend((c, const_different) for c in combinations(vars, 2))
for i in uppercase[:9]:
vars ... | [
"def",
"mkconstraints",
"(",
")",
":",
"constraints",
"=",
"[",
"]",
"for",
"j",
"in",
"range",
"(",
"1",
",",
"10",
")",
":",
"vars",
"=",
"[",
"\"%s%d\"",
"%",
"(",
"i",
",",
"j",
")",
"for",
"i",
"in",
"uppercase",
"[",
":",
"9",
"]",
"]",... | 33.571429 | 21.095238 |
def add_path(self, nodes, **attr):
"""In replacement for Deprecated add_path method"""
if nx.__version__[0] == "1":
return super().add_path(nodes, **attr)
else:
return nx.add_path(self, nodes, **attr) | [
"def",
"add_path",
"(",
"self",
",",
"nodes",
",",
"*",
"*",
"attr",
")",
":",
"if",
"nx",
".",
"__version__",
"[",
"0",
"]",
"==",
"\"1\"",
":",
"return",
"super",
"(",
")",
".",
"add_path",
"(",
"nodes",
",",
"*",
"*",
"attr",
")",
"else",
":... | 40.5 | 9.666667 |
def delete_report(server, report_number, timeout=HQ_DEFAULT_TIMEOUT):
"""
Delete a specific crash report from the server.
:param report_number: Report Number
:return: server response
"""
try:
r = requests.post(server + "/reports/delete/%d" % report_number, timeout=timeout)
except Exc... | [
"def",
"delete_report",
"(",
"server",
",",
"report_number",
",",
"timeout",
"=",
"HQ_DEFAULT_TIMEOUT",
")",
":",
"try",
":",
"r",
"=",
"requests",
".",
"post",
"(",
"server",
"+",
"\"/reports/delete/%d\"",
"%",
"report_number",
",",
"timeout",
"=",
"timeout",... | 29.230769 | 19.384615 |
async def set(self, *args, **kwargs):
"""
Set Secret
Set the secret associated with some key. If the secret already exists, it is
updated instead.
This method takes input: ``v1/secret.json#``
This method is ``stable``
"""
return await self._makeApiCal... | [
"async",
"def",
"set",
"(",
"self",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"return",
"await",
"self",
".",
"_makeApiCall",
"(",
"self",
".",
"funcinfo",
"[",
"\"set\"",
"]",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")"
] | 26.769231 | 23.230769 |
def _get_style_of_faulting_term(self, C, rup):
"""
Returns the style-of-faulting scaling term defined in equations 4 to 6
"""
if (rup.rake > 30.0) and (rup.rake < 150.):
frv = 1.0
fnm = 0.0
elif (rup.rake > -150.0) and (rup.rake < -30.0):
fnm =... | [
"def",
"_get_style_of_faulting_term",
"(",
"self",
",",
"C",
",",
"rup",
")",
":",
"if",
"(",
"rup",
".",
"rake",
">",
"30.0",
")",
"and",
"(",
"rup",
".",
"rake",
"<",
"150.",
")",
":",
"frv",
"=",
"1.0",
"fnm",
"=",
"0.0",
"elif",
"(",
"rup",
... | 28.636364 | 17 |
def _thread_loop(self):
"""Background thread used when Sender is in asynchronous/interval mode."""
last_check_time = time.time()
messages = []
while True:
# Get first message from queue, blocking until the next time we
# should be sending
time_since_la... | [
"def",
"_thread_loop",
"(",
"self",
")",
":",
"last_check_time",
"=",
"time",
".",
"time",
"(",
")",
"messages",
"=",
"[",
"]",
"while",
"True",
":",
"# Get first message from queue, blocking until the next time we",
"# should be sending",
"time_since_last_check",
"=",
... | 41.382979 | 16.659574 |
def _print_SCALAR_TYPES(self, expr, *args, **kwargs):
"""Render scalars"""
adjoint = kwargs.get('adjoint', False)
if adjoint:
expr = expr.conjugate()
if isinstance(expr, SympyBasic):
self._sympy_printer._print_level = self._print_level + 1
res = self._... | [
"def",
"_print_SCALAR_TYPES",
"(",
"self",
",",
"expr",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"adjoint",
"=",
"kwargs",
".",
"get",
"(",
"'adjoint'",
",",
"False",
")",
"if",
"adjoint",
":",
"expr",
"=",
"expr",
".",
"conjugate",
"(",
... | 41.434783 | 15.173913 |
def _cloglog_utility_transform(systematic_utilities,
alt_IDs,
rows_to_alts,
shape_params,
intercept_params,
intercept_ref_pos=None,
*a... | [
"def",
"_cloglog_utility_transform",
"(",
"systematic_utilities",
",",
"alt_IDs",
",",
"rows_to_alts",
",",
"shape_params",
",",
"intercept_params",
",",
"intercept_ref_pos",
"=",
"None",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"# Calculate the data dep... | 49.946237 | 21.989247 |
def get(ctx):
"""Get build job.
Uses [Caching](/references/polyaxon-cli/#caching)
Examples:
\b
```bash
$ polyaxon build -b 1 get
```
\b
```bash
$ polyaxon build --build=1 --project=project_name get
```
"""
user, project_name, _build = get_build_or_local(ctx.obj.ge... | [
"def",
"get",
"(",
"ctx",
")",
":",
"user",
",",
"project_name",
",",
"_build",
"=",
"get_build_or_local",
"(",
"ctx",
".",
"obj",
".",
"get",
"(",
"'project'",
")",
",",
"ctx",
".",
"obj",
".",
"get",
"(",
"'build'",
")",
")",
"try",
":",
"respons... | 28.518519 | 28.888889 |
def list_installed_files(self):
"""
Iterates over the ``installed-files.txt`` entries and returns a tuple
``(path, hash, size)`` for each line.
:returns: a list of (path, hash, size)
"""
def _md5(path):
f = open(path, 'rb')
try:
c... | [
"def",
"list_installed_files",
"(",
"self",
")",
":",
"def",
"_md5",
"(",
"path",
")",
":",
"f",
"=",
"open",
"(",
"path",
",",
"'rb'",
")",
"try",
":",
"content",
"=",
"f",
".",
"read",
"(",
")",
"finally",
":",
"f",
".",
"close",
"(",
")",
"r... | 37.432432 | 16.891892 |
def get_reference_types(self):
"""Return the reference types.
Zotero.item_types() caches data after the first API call.
"""
item_types = self._zotero_lib.item_types()
return sorted([x["itemType"] for x in item_types]) | [
"def",
"get_reference_types",
"(",
"self",
")",
":",
"item_types",
"=",
"self",
".",
"_zotero_lib",
".",
"item_types",
"(",
")",
"return",
"sorted",
"(",
"[",
"x",
"[",
"\"itemType\"",
"]",
"for",
"x",
"in",
"item_types",
"]",
")"
] | 36 | 14.714286 |
def disassemble(self, data, address, architecture_mode=None):
"""Disassemble the data into an instruction.
"""
# TODO: Improve this code!
if architecture_mode is None:
if self._arch_mode is None:
architecture_mode = ARCH_ARM_MODE_THUMB
else:
... | [
"def",
"disassemble",
"(",
"self",
",",
"data",
",",
"address",
",",
"architecture_mode",
"=",
"None",
")",
":",
"# TODO: Improve this code!",
"if",
"architecture_mode",
"is",
"None",
":",
"if",
"self",
".",
"_arch_mode",
"is",
"None",
":",
"architecture_mode",
... | 30.833333 | 17.791667 |
def setup_default_permissions(session, instance):
"""Setup default permissions on newly created entities according to.
:attr:`Entity.__default_permissions__`.
"""
if instance not in session.new or not isinstance(instance, Entity):
return
if not current_app:
# working outside app_co... | [
"def",
"setup_default_permissions",
"(",
"session",
",",
"instance",
")",
":",
"if",
"instance",
"not",
"in",
"session",
".",
"new",
"or",
"not",
"isinstance",
"(",
"instance",
",",
"Entity",
")",
":",
"return",
"if",
"not",
"current_app",
":",
"# working ou... | 30.384615 | 19.538462 |
def field(self, type, field, default=None):
'''convenient function for returning an arbitrary MAVLink
field with a default'''
if not type in self.messages:
return default
return getattr(self.messages[type], field, default) | [
"def",
"field",
"(",
"self",
",",
"type",
",",
"field",
",",
"default",
"=",
"None",
")",
":",
"if",
"not",
"type",
"in",
"self",
".",
"messages",
":",
"return",
"default",
"return",
"getattr",
"(",
"self",
".",
"messages",
"[",
"type",
"]",
",",
"... | 44 | 11.666667 |
def print_loop(self, sf, sftag, f=sys.stdout, file_format="nmrstar", tw=3):
"""Print loop into a file or stdout.
:param str sf: Saveframe name.
:param str sftag: Saveframe tag, i.e. field name.
:param io.StringIO f: writable file-like stream.
:param str file_format: Format to us... | [
"def",
"print_loop",
"(",
"self",
",",
"sf",
",",
"sftag",
",",
"f",
"=",
"sys",
".",
"stdout",
",",
"file_format",
"=",
"\"nmrstar\"",
",",
"tw",
"=",
"3",
")",
":",
"if",
"file_format",
"==",
"\"nmrstar\"",
":",
"# First print the fields",
"for",
"fiel... | 48.52 | 23.6 |
def on_mouse_event(self, event):
'''handle mouse events'''
pos = event.GetPosition()
if event.RightDown() and self.popup_menu is not None:
self.show_popup_menu(pos)
return
if event.Leaving():
self.mouse_pos = None
else:
self.mouse_p... | [
"def",
"on_mouse_event",
"(",
"self",
",",
"event",
")",
":",
"pos",
"=",
"event",
".",
"GetPosition",
"(",
")",
"if",
"event",
".",
"RightDown",
"(",
")",
"and",
"self",
".",
"popup_menu",
"is",
"not",
"None",
":",
"self",
".",
"show_popup_menu",
"(",... | 34.066667 | 15 |
def format(self, record):
"""
The formatting function
:param record: The record object
:return: The string representation of the record
"""
try:
n = record.n
except AttributeError:
n = 'default'
try:
message = record.... | [
"def",
"format",
"(",
"self",
",",
"record",
")",
":",
"try",
":",
"n",
"=",
"record",
".",
"n",
"except",
"AttributeError",
":",
"n",
"=",
"'default'",
"try",
":",
"message",
"=",
"record",
".",
"message",
"except",
"AttributeError",
":",
"message",
"... | 24.461538 | 18 |
def open(self, **params):
"""Open telnet connection
Args:
params (dict), must contain two parameters "ip" - ip address or hostname and "port" - port number
Example:
params = {'port': 23, 'ip': 'localhost'}
"""
logger.info('opening telnet')
self.p... | [
"def",
"open",
"(",
"self",
",",
"*",
"*",
"params",
")",
":",
"logger",
".",
"info",
"(",
"'opening telnet'",
")",
"self",
".",
"port",
"=",
"params",
"[",
"'port'",
"]",
"self",
".",
"ip",
"=",
"params",
"[",
"'ip'",
"]",
"self",
".",
"tn",
"="... | 28.714286 | 20.285714 |
def _pretty_format(self, statement, result):
""" Format the return value of a query for humans """
if result is None:
return "Success"
ret = result
if statement.action in ("SELECT", "SCAN"):
if statement.save_file:
filename = statement.save_file[0]... | [
"def",
"_pretty_format",
"(",
"self",
",",
"statement",
",",
"result",
")",
":",
"if",
"result",
"is",
"None",
":",
"return",
"\"Success\"",
"ret",
"=",
"result",
"if",
"statement",
".",
"action",
"in",
"(",
"\"SELECT\"",
",",
"\"SCAN\"",
")",
":",
"if",... | 45.105263 | 13.815789 |
def load_cufflinks_dict(*args, **kwargs):
"""
Returns dictionary mapping feature identifier (either transcript or gene ID)
to a DataFrame row with fields:
id : str
novel : bool
fpkm : float
chr : str
start : int
end : int
gene_names : str list
"""
... | [
"def",
"load_cufflinks_dict",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"return",
"{",
"row",
".",
"id",
":",
"row",
"for",
"(",
"_",
",",
"row",
")",
"in",
"load_cufflinks_dataframe",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
".",... | 25.117647 | 18.529412 |
def folderitem(self, obj, item, index):
"""Service triggered each time an item is iterated in folderitems.
The use of this service prevents the extra-loops in child objects.
:obj: the instance of the class to be foldered
:item: dict containing the properties of the object to be used by... | [
"def",
"folderitem",
"(",
"self",
",",
"obj",
",",
"item",
",",
"index",
")",
":",
"title",
"=",
"obj",
".",
"Title",
"(",
")",
"description",
"=",
"obj",
".",
"Description",
"(",
")",
"url",
"=",
"obj",
".",
"absolute_url",
"(",
")",
"item",
"[",
... | 34.657895 | 18.263158 |
def save(self, filename, binary=True):
"""
Writes a rectilinear grid to disk.
Parameters
----------
filename : str
Filename of grid to be written. The file extension will select the
type of writer to use. ".vtk" will use the legacy writer, while
... | [
"def",
"save",
"(",
"self",
",",
"filename",
",",
"binary",
"=",
"True",
")",
":",
"filename",
"=",
"os",
".",
"path",
".",
"abspath",
"(",
"os",
".",
"path",
".",
"expanduser",
"(",
"filename",
")",
")",
"# Use legacy writer if vtk is in filename",
"if",
... | 34.051282 | 19.641026 |
def fromimage(im, flatten=False, mode=None):
"""
Return a copy of a PIL image as a numpy array.
Parameters
----------
im : PIL image
Input image.
flatten : bool
If true, convert the output to grey-scale.
mode : str, optional
Mode to convert image to, e.g. ``'RGB'``. ... | [
"def",
"fromimage",
"(",
"im",
",",
"flatten",
"=",
"False",
",",
"mode",
"=",
"None",
")",
":",
"if",
"not",
"Image",
".",
"isImageType",
"(",
"im",
")",
":",
"raise",
"TypeError",
"(",
"\"Input is not a PIL image.\"",
")",
"if",
"mode",
"is",
"not",
... | 31.705882 | 20.215686 |
def cf_to_proj(var):
r"""Convert a Variable with projection information to a Proj.4 Projection instance.
The attributes of this Variable must conform to the Climate and Forecasting (CF)
netCDF conventions.
Parameters
----------
var : Variable
The projection variable with appropriate at... | [
"def",
"cf_to_proj",
"(",
"var",
")",
":",
"import",
"pyproj",
"kwargs",
"=",
"{",
"'lat_0'",
":",
"var",
".",
"latitude_of_projection_origin",
",",
"'a'",
":",
"var",
".",
"earth_radius",
",",
"'b'",
":",
"var",
".",
"earth_radius",
"}",
"if",
"var",
".... | 38.314286 | 16.942857 |
def chinese_remainder(n, a):
"""
Solves CRT for moduli and remainders
:param n:
:param a:
:return:
"""
sum = 0
prod = reduce(lambda a, b: a * b, n)
for n_i, a_i in zip(n, a):
p = prod // n_i
sum += a_i * DlogFprint.mul_inv(... | [
"def",
"chinese_remainder",
"(",
"n",
",",
"a",
")",
":",
"sum",
"=",
"0",
"prod",
"=",
"reduce",
"(",
"lambda",
"a",
",",
"b",
":",
"a",
"*",
"b",
",",
"n",
")",
"for",
"n_i",
",",
"a_i",
"in",
"zip",
"(",
"n",
",",
"a",
")",
":",
"p",
"... | 24.571429 | 14.571429 |
def get_configurable_by_name(self, name):
"""
Returns the registered configurable with the specified name or ``None`` if no
such configurator exists.
"""
l = [c for c in self.configurables if c.name == name]
if l:
return l[0] | [
"def",
"get_configurable_by_name",
"(",
"self",
",",
"name",
")",
":",
"l",
"=",
"[",
"c",
"for",
"c",
"in",
"self",
".",
"configurables",
"if",
"c",
".",
"name",
"==",
"name",
"]",
"if",
"l",
":",
"return",
"l",
"[",
"0",
"]"
] | 34.75 | 14.75 |
def unique(lst):
"""Unique with keeping sort/order
["a", "c", "b", "c", "c", ["d", "e"]]
Results in
["a", "c", "b", "d", "e"]
"""
nl = []
[(nl.append(e) if type(e) is not list else nl.extend(e)) \
for e in lst if e not in nl]
return nl | [
"def",
"unique",
"(",
"lst",
")",
":",
"nl",
"=",
"[",
"]",
"[",
"(",
"nl",
".",
"append",
"(",
"e",
")",
"if",
"type",
"(",
"e",
")",
"is",
"not",
"list",
"else",
"nl",
".",
"extend",
"(",
"e",
")",
")",
"for",
"e",
"in",
"lst",
"if",
"e... | 24.636364 | 17 |
async def unsubscribe(self, topic: str):
"""Unsubscribe from a topic
:param topic: required
:returns: None
Sample ws response
.. code-block:: python
{
"id": "1545910840805",
"type": "ack"
}
"""
req_msg... | [
"async",
"def",
"unsubscribe",
"(",
"self",
",",
"topic",
":",
"str",
")",
":",
"req_msg",
"=",
"{",
"'type'",
":",
"'unsubscribe'",
",",
"'topic'",
":",
"topic",
",",
"'response'",
":",
"True",
"}",
"await",
"self",
".",
"_conn",
".",
"send_message",
... | 18 | 21.12 |
def get_activity(self, name):
"""
Retrieve an activity given its name.
:param name: The name of the activity.
:returns: The activity.
"""
return [a for a in self.activities if a.name == name][0] | [
"def",
"get_activity",
"(",
"self",
",",
"name",
")",
":",
"return",
"[",
"a",
"for",
"a",
"in",
"self",
".",
"activities",
"if",
"a",
".",
"name",
"==",
"name",
"]",
"[",
"0",
"]"
] | 23.6 | 17.4 |
def run(self):
"""
Start monitoring operation policy files.
"""
self.initialize_tracking_structures()
if self.live_monitoring:
self.logger.info("Starting up the operation policy file monitor.")
while not self.halt_trigger.is_set():
time.sl... | [
"def",
"run",
"(",
"self",
")",
":",
"self",
".",
"initialize_tracking_structures",
"(",
")",
"if",
"self",
".",
"live_monitoring",
":",
"self",
".",
"logger",
".",
"info",
"(",
"\"Starting up the operation policy file monitor.\"",
")",
"while",
"not",
"self",
"... | 33.785714 | 15.642857 |
def patch_compat(config):
"""
Support older config values.
"""
if 'web_host' in config:
config['host'] = config.pop('web_host')
if 'web_port' in config:
config['port'] = config.pop('web_port') | [
"def",
"patch_compat",
"(",
"config",
")",
":",
"if",
"'web_host'",
"in",
"config",
":",
"config",
"[",
"'host'",
"]",
"=",
"config",
".",
"pop",
"(",
"'web_host'",
")",
"if",
"'web_port'",
"in",
"config",
":",
"config",
"[",
"'port'",
"]",
"=",
"confi... | 24.25 | 7.25 |
def stationarystate(self, k):
"""See docs for `Model` abstract base class."""
assert 0 <= k < self.ncats
return self._models[k].stationarystate | [
"def",
"stationarystate",
"(",
"self",
",",
"k",
")",
":",
"assert",
"0",
"<=",
"k",
"<",
"self",
".",
"ncats",
"return",
"self",
".",
"_models",
"[",
"k",
"]",
".",
"stationarystate"
] | 41 | 5.75 |
def main():
"""
%prog database.fa query.fa [options]
Wrapper for NCBI BLAST+.
"""
p = OptionParser(main.__doc__)
p.add_option("--format", default=" \'6 qseqid sseqid pident length " \
"mismatch gapopen qstart qend sstart send evalue bitscore\' ",
help="0-11, learn more ... | [
"def",
"main",
"(",
")",
":",
"p",
"=",
"OptionParser",
"(",
"main",
".",
"__doc__",
")",
"p",
".",
"add_option",
"(",
"\"--format\"",
",",
"default",
"=",
"\" \\'6 qseqid sseqid pident length \"",
"\"mismatch gapopen qstart qend sstart send evalue bitscore\\' \"",
",",... | 33.373494 | 19.879518 |
def registerEditor(self,
name,
op,
cls=None,
defaultValue=None,
flags=0):
"""
Registers an editor for the given operator as the given name. If no
editor class is supplied, ... | [
"def",
"registerEditor",
"(",
"self",
",",
"name",
",",
"op",
",",
"cls",
"=",
"None",
",",
"defaultValue",
"=",
"None",
",",
"flags",
"=",
"0",
")",
":",
"registry",
"=",
"XEditorRegistry",
"(",
"op",
"=",
"op",
",",
"cls",
"=",
"cls",
",",
"defau... | 41.5 | 14.5 |
def _prop_name(self):
"""
Calculate property name from tag name, e.g. a:schemeClr -> schemeClr.
"""
if ':' in self._nsptagname:
start = self._nsptagname.index(':') + 1
else:
start = 0
return self._nsptagname[start:] | [
"def",
"_prop_name",
"(",
"self",
")",
":",
"if",
"':'",
"in",
"self",
".",
"_nsptagname",
":",
"start",
"=",
"self",
".",
"_nsptagname",
".",
"index",
"(",
"':'",
")",
"+",
"1",
"else",
":",
"start",
"=",
"0",
"return",
"self",
".",
"_nsptagname",
... | 31 | 13.222222 |
def construct_request(self, request_args=None, **kwargs):
"""
The method where everything is setup for sending the request.
The request information is gathered and the where and how of sending the
request is decided.
:param request_args: Initial request arguments
:param ... | [
"def",
"construct_request",
"(",
"self",
",",
"request_args",
"=",
"None",
",",
"*",
"*",
"kwargs",
")",
":",
"if",
"request_args",
"is",
"None",
":",
"request_args",
"=",
"{",
"}",
"# remove arguments that should not be included in the request",
"# _args = dict(",
... | 39.842105 | 21.105263 |
def refresh_all_state_machines(self):
""" Refreshes all state machine tabs
"""
self.refresh_state_machines(list(self.model.state_machine_manager.state_machines.keys())) | [
"def",
"refresh_all_state_machines",
"(",
"self",
")",
":",
"self",
".",
"refresh_state_machines",
"(",
"list",
"(",
"self",
".",
"model",
".",
"state_machine_manager",
".",
"state_machines",
".",
"keys",
"(",
")",
")",
")"
] | 47.25 | 15 |
def threadpooled(
func: None = None,
*,
loop_getter: typing.Union[None, typing.Callable[..., asyncio.AbstractEventLoop], asyncio.AbstractEventLoop] = None,
loop_getter_need_context: bool = False,
) -> ThreadPooled:
"""Overload: No function.""" | [
"def",
"threadpooled",
"(",
"func",
":",
"None",
"=",
"None",
",",
"*",
",",
"loop_getter",
":",
"typing",
".",
"Union",
"[",
"None",
",",
"typing",
".",
"Callable",
"[",
"...",
",",
"asyncio",
".",
"AbstractEventLoop",
"]",
",",
"asyncio",
".",
"Abstr... | 36.714286 | 25.571429 |
def register_parameters(self, *parameters):
"""
Register parameters.
"""
for param in parameters:
self.parameter_count += np.prod(param.get_value().shape)
self.parameters.extend(parameters) | [
"def",
"register_parameters",
"(",
"self",
",",
"*",
"parameters",
")",
":",
"for",
"param",
"in",
"parameters",
":",
"self",
".",
"parameter_count",
"+=",
"np",
".",
"prod",
"(",
"param",
".",
"get_value",
"(",
")",
".",
"shape",
")",
"self",
".",
"pa... | 33.571429 | 7.571429 |
def cache(self, CachableItem):
"""Updates cache area with latest information
"""
_cachedItem = self.get(CachableItem)
if not _cachedItem:
_dirtyCachedItem = self.mapper.get(CachableItem)
logger.debug("new cachable item added to sql cache area {id: %s, type: %s}", ... | [
"def",
"cache",
"(",
"self",
",",
"CachableItem",
")",
":",
"_cachedItem",
"=",
"self",
".",
"get",
"(",
"CachableItem",
")",
"if",
"not",
"_cachedItem",
":",
"_dirtyCachedItem",
"=",
"self",
".",
"mapper",
".",
"get",
"(",
"CachableItem",
")",
"logger",
... | 54.333333 | 24.777778 |
def disassemble(self, lineno_width=3,
mark_as_current=False,
asm_format=False,
show_bytes=False):
"""Format instruction details for inclusion in disassembly output
*lineno_width* sets the width of the line number field (0 omits it)
*ma... | [
"def",
"disassemble",
"(",
"self",
",",
"lineno_width",
"=",
"3",
",",
"mark_as_current",
"=",
"False",
",",
"asm_format",
"=",
"False",
",",
"show_bytes",
"=",
"False",
")",
":",
"fields",
"=",
"[",
"]",
"if",
"asm_format",
":",
"indexed_operand",
"=",
... | 38.543478 | 13.021739 |
def main_hrun():
""" parse command line options and run commands."""
parser = argparse.ArgumentParser(description="Tools for http(s) test. Base on rtsf.")
parser.add_argument(
'--log-level', default='INFO',
help="Specify logging level, default is INFO.")
p... | [
"def",
"main_hrun",
"(",
")",
":",
"parser",
"=",
"argparse",
".",
"ArgumentParser",
"(",
"description",
"=",
"\"Tools for http(s) test. Base on rtsf.\"",
")",
"parser",
".",
"add_argument",
"(",
"'--log-level'",
",",
"default",
"=",
"'INFO'",
",",
"help",
"=",
... | 33.75 | 19.833333 |
def contents(self):
"""Get svg string
"""
c = self._header[:]
c.append(' font-weight="{}"'.format(self.font_weight))
c.append(' font-family="{}"'.format(self.font_family))
c.append(' width="{}" height="{}"'.format(*self.screen_size))
sclw = self.original_size[0] *... | [
"def",
"contents",
"(",
"self",
")",
":",
"c",
"=",
"self",
".",
"_header",
"[",
":",
"]",
"c",
".",
"append",
"(",
"' font-weight=\"{}\"'",
".",
"format",
"(",
"self",
".",
"font_weight",
")",
")",
"c",
".",
"append",
"(",
"' font-family=\"{}\"'",
"."... | 45.772727 | 15.227273 |
def from_directory_as_inmemory_db(cls, gtfs_directory):
"""
Instantiate a GTFS object by computing
Parameters
----------
gtfs_directory: str
path to the directory for importing the database
"""
# this import is here to avoid circular imports (which tu... | [
"def",
"from_directory_as_inmemory_db",
"(",
"cls",
",",
"gtfs_directory",
")",
":",
"# this import is here to avoid circular imports (which turned out to be a problem)",
"from",
"gtfspy",
".",
"import_gtfs",
"import",
"import_gtfs",
"conn",
"=",
"sqlite3",
".",
"connect",
"(... | 35.176471 | 14.235294 |
def p_new_expr_nobf(self, p):
"""new_expr_nobf : member_expr_nobf
| NEW new_expr
"""
if len(p) == 2:
p[0] = p[1]
else:
p[0] = self.asttypes.NewExpr(p[2])
p[0].setpos(p) | [
"def",
"p_new_expr_nobf",
"(",
"self",
",",
"p",
")",
":",
"if",
"len",
"(",
"p",
")",
"==",
"2",
":",
"p",
"[",
"0",
"]",
"=",
"p",
"[",
"1",
"]",
"else",
":",
"p",
"[",
"0",
"]",
"=",
"self",
".",
"asttypes",
".",
"NewExpr",
"(",
"p",
"... | 28.111111 | 10.333333 |
def to_seconds(value, time_unit):
"""
:param value: (Number), value to be translated to seconds
:param time_unit: Time duration in seconds
:return: Value of the value in seconds
"""
if isinstance(value, bool):
# bool is a subclass of int. Don't let bool and fl... | [
"def",
"to_seconds",
"(",
"value",
",",
"time_unit",
")",
":",
"if",
"isinstance",
"(",
"value",
",",
"bool",
")",
":",
"# bool is a subclass of int. Don't let bool and float multiplication.",
"raise",
"TypeError",
"return",
"float",
"(",
"value",
")",
"*",
"time_un... | 39.8 | 10.8 |
def __calculate_weight(self, stimulus1, stimulus2):
"""!
@brief Calculate weight between neurons that have external stimulus1 and stimulus2.
@param[in] stimulus1 (list): External stimulus of the first neuron.
@param[in] stimulus2 (list): External stimulus of the second neur... | [
"def",
"__calculate_weight",
"(",
"self",
",",
"stimulus1",
",",
"stimulus2",
")",
":",
"distance",
"=",
"euclidean_distance_square",
"(",
"stimulus1",
",",
"stimulus2",
")",
"return",
"math",
".",
"exp",
"(",
"-",
"distance",
"/",
"(",
"2.0",
"*",
"self",
... | 44.307692 | 27.615385 |
def clean(dry_run='n'):
"""Wipes compiled and cached python files. To simulate: pynt clean[dry_run=y]"""
file_patterns = ['*.pyc', '*.pyo', '*~']
dir_patterns = ['__pycache__']
recursive_pattern_delete(project_paths.root, file_patterns, dir_patterns, dry_run=bool(dry_run.lower() == 'y')) | [
"def",
"clean",
"(",
"dry_run",
"=",
"'n'",
")",
":",
"file_patterns",
"=",
"[",
"'*.pyc'",
",",
"'*.pyo'",
",",
"'*~'",
"]",
"dir_patterns",
"=",
"[",
"'__pycache__'",
"]",
"recursive_pattern_delete",
"(",
"project_paths",
".",
"root",
",",
"file_patterns",
... | 60 | 20.4 |
def create_routes(routes: Tuple[HTTPMethod], handle_http: Callable,
default_base_handler_class: Any) -> List[Tuple[str, Any]]:
"""Creates handler routes from the provided routes.
:param routes: A tuple containing the route and another tuple with
all http methods allowed for the route.... | [
"def",
"create_routes",
"(",
"routes",
":",
"Tuple",
"[",
"HTTPMethod",
"]",
",",
"handle_http",
":",
"Callable",
",",
"default_base_handler_class",
":",
"Any",
")",
"->",
"List",
"[",
"Tuple",
"[",
"str",
",",
"Any",
"]",
"]",
":",
"created_routes",
"=",
... | 44.446429 | 18.125 |
def wait_for_host(port, interval=1, timeout=30, to_start=True, queue=None,
ssl_pymongo_options=None):
"""
Ping server and wait for response.
Ping a mongod or mongos every `interval` seconds until it responds, or
`timeout` seconds have passed. If `to_start` is set to False, will wait f... | [
"def",
"wait_for_host",
"(",
"port",
",",
"interval",
"=",
"1",
",",
"timeout",
"=",
"30",
",",
"to_start",
"=",
"True",
",",
"queue",
"=",
"None",
",",
"ssl_pymongo_options",
"=",
"None",
")",
":",
"host",
"=",
"'localhost:%i'",
"%",
"port",
"start_time... | 34.421053 | 18.210526 |
def param_to_array(*param):
"""
Convert an arbitrary number of parameters to :class:ndarray class objects.
This is for converting parameter objects to numpy arrays, when using
scipy.weave.inline routine. In scipy.weave.blitz there is no automatic
array detection (even when the array inherits from :... | [
"def",
"param_to_array",
"(",
"*",
"param",
")",
":",
"import",
"warnings",
"warnings",
".",
"warn",
"(",
"\"Please use param.values, as this function will be deprecated in the next release.\"",
",",
"DeprecationWarning",
")",
"assert",
"len",
"(",
"param",
")",
">",
"0... | 49.538462 | 22.461538 |
def also_restrict_to(self, restriction):
"""
Works like restict_to but offers an additional restriction. Playbooks use this
to implement serial behavior.
"""
if type(restriction) != list:
restriction = [ restriction ]
self._also_restriction = restriction | [
"def",
"also_restrict_to",
"(",
"self",
",",
"restriction",
")",
":",
"if",
"type",
"(",
"restriction",
")",
"!=",
"list",
":",
"restriction",
"=",
"[",
"restriction",
"]",
"self",
".",
"_also_restriction",
"=",
"restriction"
] | 38.5 | 7.25 |
def deblur(input_seqs, mean_error=0.005,
error_dist=None,
indel_prob=0.01, indel_max=3):
"""Deblur the reads
Parameters
----------
input_seqs : iterable of (str, str)
The list of input sequences in (label, sequence) format. The label
should include the sequence cou... | [
"def",
"deblur",
"(",
"input_seqs",
",",
"mean_error",
"=",
"0.005",
",",
"error_dist",
"=",
"None",
",",
"indel_prob",
"=",
"0.01",
",",
"indel_max",
"=",
"3",
")",
":",
"logger",
"=",
"logging",
".",
"getLogger",
"(",
"__name__",
")",
"if",
"error_dist... | 37.773109 | 22.176471 |
def write_file(fname, *lines):
'write lines to a file'
yield 'touch {}'.format(fname)
for line in lines:
yield "echo {} >> {}".format(line, fname) | [
"def",
"write_file",
"(",
"fname",
",",
"*",
"lines",
")",
":",
"yield",
"'touch {}'",
".",
"format",
"(",
"fname",
")",
"for",
"line",
"in",
"lines",
":",
"yield",
"\"echo {} >> {}\"",
".",
"format",
"(",
"line",
",",
"fname",
")"
] | 32.4 | 11.2 |
def validateStr(value, blank=False, strip=None, allowlistRegexes=None, blocklistRegexes=None, excMsg=None):
"""Raises ValidationException if value is not a string. This function
is identical to the built-in input() function, but also offers the
PySimpleValidate features of not allowing blank values by defau... | [
"def",
"validateStr",
"(",
"value",
",",
"blank",
"=",
"False",
",",
"strip",
"=",
"None",
",",
"allowlistRegexes",
"=",
"None",
",",
"blocklistRegexes",
"=",
"None",
",",
"excMsg",
"=",
"None",
")",
":",
"# Validate parameters.",
"_validateGenericParameters",
... | 49.326087 | 32.456522 |
def delete(instance, disconnect=True):
'''
Delete an *instance* from its metaclass instance pool and optionally
*disconnect* it from any links it might be connected to.
'''
if not isinstance(instance, Class):
raise DeleteException("the provided argument is not an xtuml instance")
... | [
"def",
"delete",
"(",
"instance",
",",
"disconnect",
"=",
"True",
")",
":",
"if",
"not",
"isinstance",
"(",
"instance",
",",
"Class",
")",
":",
"raise",
"DeleteException",
"(",
"\"the provided argument is not an xtuml instance\"",
")",
"return",
"get_metaclass",
"... | 41.888889 | 23.444444 |
def p_statement_namespace(self, p):
""" statement : css_namespace t_ws word css_string t_semicolon
"""
p[0] = Statement(list(p)[1:], p.lineno(1))
p[0].parse(None) | [
"def",
"p_statement_namespace",
"(",
"self",
",",
"p",
")",
":",
"p",
"[",
"0",
"]",
"=",
"Statement",
"(",
"list",
"(",
"p",
")",
"[",
"1",
":",
"]",
",",
"p",
".",
"lineno",
"(",
"1",
")",
")",
"p",
"[",
"0",
"]",
".",
"parse",
"(",
"None... | 40.2 | 6.2 |
def parse_text(infile, xpath=None, filter_words=None, attributes=None):
"""Filter text using XPath, regex keywords, and tag attributes.
Keyword arguments:
infile -- HTML or text content to parse (list)
xpath -- an XPath expression (str)
filter_words -- regex keywords (list)
attributes -- HTML t... | [
"def",
"parse_text",
"(",
"infile",
",",
"xpath",
"=",
"None",
",",
"filter_words",
"=",
"None",
",",
"attributes",
"=",
"None",
")",
":",
"infiles",
"=",
"[",
"]",
"text",
"=",
"[",
"]",
"if",
"xpath",
"is",
"not",
"None",
":",
"infile",
"=",
"par... | 34.75 | 17.25 |
def validate_arg(f,
arg_name,
*validation_func, # type: ValidationFuncs
**kwargs
):
# type: (...) -> Callable
"""
A decorator to apply function input validation for the given argument name, with the provided base validation
function(s)... | [
"def",
"validate_arg",
"(",
"f",
",",
"arg_name",
",",
"*",
"validation_func",
",",
"# type: ValidationFuncs",
"*",
"*",
"kwargs",
")",
":",
"# type: (...) -> Callable",
"return",
"decorate_with_validation",
"(",
"f",
",",
"arg_name",
",",
"*",
"validation_func",
... | 67.464286 | 40.392857 |
def senses(self, bestonly=False):
"""Returns a list of all predicted senses"""
l = []
for word_id, senses,distance in self:
for sense, confidence in senses:
if not sense in l: l.append(sense)
if bestonly:
break
return l | [
"def",
"senses",
"(",
"self",
",",
"bestonly",
"=",
"False",
")",
":",
"l",
"=",
"[",
"]",
"for",
"word_id",
",",
"senses",
",",
"distance",
"in",
"self",
":",
"for",
"sense",
",",
"confidence",
"in",
"senses",
":",
"if",
"not",
"sense",
"in",
"l",... | 34.111111 | 11.444444 |
def stream(self):
"""Iterate over the messages from the computation's output.
Control and metadata messages are intercepted and interpreted to
enhance this Computation's object knowledge of the computation's
context. Data and event messages are yielded back to the caller as a
ge... | [
"def",
"stream",
"(",
"self",
")",
":",
"iterator",
"=",
"iter",
"(",
"self",
".",
"_stream",
")",
"while",
"self",
".",
"_state",
"<",
"Computation",
".",
"STATE_COMPLETED",
":",
"try",
":",
"message",
"=",
"next",
"(",
"iterator",
")",
"except",
"Sto... | 39.946809 | 21.031915 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.