text stringlengths 89 104k | code_tokens list | avg_line_len float64 7.91 980 | score float64 0 630 |
|---|---|---|---|
def aggregationDivide(dividend, divisor):
"""
Return the result from dividing two dicts that represent date and time.
Both dividend and divisor are dicts that contain one or more of the following
keys: 'years', 'months', 'weeks', 'days', 'hours', 'minutes', seconds',
'milliseconds', 'microseconds'.
For ex... | [
"def",
"aggregationDivide",
"(",
"dividend",
",",
"divisor",
")",
":",
"# Convert each into microseconds",
"dividendMonthSec",
"=",
"aggregationToMonthsSeconds",
"(",
"dividend",
")",
"divisorMonthSec",
"=",
"aggregationToMonthsSeconds",
"(",
"divisor",
")",
"# It is a usag... | 35.702703 | 28.459459 |
def _assign_work_unit(self, node):
"""Assign a work unit to a node."""
assert self.workqueue
# Grab a unit of work
scope, work_unit = self.workqueue.popitem(last=False)
# Keep track of the assigned work
assigned_to_node = self.assigned_work.setdefault(node, default=Orde... | [
"def",
"_assign_work_unit",
"(",
"self",
",",
"node",
")",
":",
"assert",
"self",
".",
"workqueue",
"# Grab a unit of work",
"scope",
",",
"work_unit",
"=",
"self",
".",
"workqueue",
".",
"popitem",
"(",
"last",
"=",
"False",
")",
"# Keep track of the assigned w... | 34 | 18.25 |
def register(func=None, name=None):
"""
Expose compiler to factory.
:param func: the callable to expose
:type func: callable
:param name: name of format
:type name: str
It can be used as a decorator::
@register(name='my:validator')
def my_validator(obj):
if obj... | [
"def",
"register",
"(",
"func",
"=",
"None",
",",
"name",
"=",
"None",
")",
":",
"if",
"not",
"name",
":",
"raise",
"CompilationError",
"(",
"'Name is required'",
")",
"if",
"not",
"func",
":",
"return",
"partial",
"(",
"register",
",",
"name",
"=",
"n... | 23.96875 | 16.65625 |
def _connected(client):
"""
Connected to AMP server, start listening locally, and give the AMP
client a reference to the local listening factory.
"""
log.msg("Connected to AMP server, starting to listen locally...")
localFactory = multiplexing.ProxyingFactory(client, "hello")
return listenin... | [
"def",
"_connected",
"(",
"client",
")",
":",
"log",
".",
"msg",
"(",
"\"Connected to AMP server, starting to listen locally...\"",
")",
"localFactory",
"=",
"multiplexing",
".",
"ProxyingFactory",
"(",
"client",
",",
"\"hello\"",
")",
"return",
"listeningEndpoint",
"... | 42.875 | 15.375 |
def get_global_rate_limit(self):
"""Get the global rate limit per client.
:rtype: int
:returns: The global rate limit for each client.
"""
r = urllib.request.urlopen('https://archive.org/metadata/iamine-rate-limiter')
j = json.loads(r.read().decode('utf-8'))
retu... | [
"def",
"get_global_rate_limit",
"(",
"self",
")",
":",
"r",
"=",
"urllib",
".",
"request",
".",
"urlopen",
"(",
"'https://archive.org/metadata/iamine-rate-limiter'",
")",
"j",
"=",
"json",
".",
"loads",
"(",
"r",
".",
"read",
"(",
")",
".",
"decode",
"(",
... | 41 | 18.666667 |
def power(self, n):
"""The matrix power of the channel.
Args:
n (int): compute the matrix power of the superoperator matrix.
Returns:
PTM: the matrix power of the SuperOp converted to a PTM channel.
Raises:
QiskitError: if the input and output dimen... | [
"def",
"power",
"(",
"self",
",",
"n",
")",
":",
"if",
"n",
">",
"0",
":",
"return",
"super",
"(",
")",
".",
"power",
"(",
"n",
")",
"return",
"PTM",
"(",
"SuperOp",
"(",
"self",
")",
".",
"power",
"(",
"n",
")",
")"
] | 31.25 | 23.5 |
def sanitize(name):
"""
Sanitize the specified ``name`` for use with breathe directives.
**Parameters**
``name`` (:class:`python:str`)
The name to be sanitized.
**Return**
:class:`python:str`
The input ``name`` sanitized to use with breathe directives (primarily for use
... | [
"def",
"sanitize",
"(",
"name",
")",
":",
"return",
"name",
".",
"replace",
"(",
"\"<\"",
",",
"\"<\"",
")",
".",
"replace",
"(",
"\">\"",
",",
"\">\"",
")",
".",
"replace",
"(",
"\"&\"",
",",
"\"&\"",
")",
".",
"replace",
"(",
"\"< \"",
",... | 24.25 | 25.0625 |
def route(
self,
uri,
methods=frozenset({"GET"}),
host=None,
strict_slashes=None,
stream=False,
version=None,
name=None,
):
"""Create a blueprint route from a decorated function.
:param uri: endpoint at which the route will be accessib... | [
"def",
"route",
"(",
"self",
",",
"uri",
",",
"methods",
"=",
"frozenset",
"(",
"{",
"\"GET\"",
"}",
")",
",",
"host",
"=",
"None",
",",
"strict_slashes",
"=",
"None",
",",
"stream",
"=",
"False",
",",
"version",
"=",
"None",
",",
"name",
"=",
"Non... | 29.857143 | 19.02381 |
def health_check(self):
""" Pull health and alarm information from the device.
Purpose: Grab the cpu/mem usage, system/chassis alarms, top 5
| processes, and states if the primary/backup partitions are on
| different versions.
@returns: The output that should be s... | [
"def",
"health_check",
"(",
"self",
")",
":",
"output",
"=",
"'Chassis Alarms:\\n\\t'",
"# Grab chassis alarms, system alarms, show chassis routing-engine,",
"# 'show system processes extensive', and also xpath to the",
"# relevant nodes on each.",
"chassis_alarms",
"=",
"self",
".",
... | 50.382979 | 20.446809 |
def pseudo_peripheral_node(A):
"""Find a pseudo peripheral node.
Parameters
----------
A : sparse matrix
Sparse matrix
Returns
-------
x : int
Locaiton of the node
order : array
BFS ordering
level : array
BFS levels
Notes
-----
Algorithm... | [
"def",
"pseudo_peripheral_node",
"(",
"A",
")",
":",
"from",
"pyamg",
".",
"graph",
"import",
"breadth_first_search",
"n",
"=",
"A",
".",
"shape",
"[",
"0",
"]",
"valence",
"=",
"np",
".",
"diff",
"(",
"A",
".",
"indptr",
")",
"# select an initial node x, ... | 22.591837 | 21.040816 |
def build_additional_match(self, ident, node_set):
"""
handle additional matches supplied by 'has()' calls
"""
source_ident = ident
for key, value in node_set.must_match.items():
if isinstance(value, dict):
label = ':' + value['node_class'].__labe... | [
"def",
"build_additional_match",
"(",
"self",
",",
"ident",
",",
"node_set",
")",
":",
"source_ident",
"=",
"ident",
"for",
"key",
",",
"value",
"in",
"node_set",
".",
"must_match",
".",
"items",
"(",
")",
":",
"if",
"isinstance",
"(",
"value",
",",
"dic... | 42.761905 | 19.047619 |
def bigquery_type(o, timestamp_parser=default_timestamp_parser):
"""Given a value, return the matching BigQuery type of that value. Must be
one of str/unicode/int/float/datetime/record, where record is a dict
containing value which have matching BigQuery types.
Parameters
----------
o : object
... | [
"def",
"bigquery_type",
"(",
"o",
",",
"timestamp_parser",
"=",
"default_timestamp_parser",
")",
":",
"t",
"=",
"type",
"(",
"o",
")",
"if",
"t",
"in",
"six",
".",
"integer_types",
":",
"return",
"\"integer\"",
"elif",
"(",
"t",
"==",
"six",
".",
"binary... | 26.777778 | 21.555556 |
def _replace_keyword(self, keyword, replacement, count=0):
"""
replace_keyword(keyword, replacement[, count])
Walk through the element and its children
and look for Str() objects that contains
exactly the keyword. Then, replace it.
Usually applied to an entire document (a :class:`.Doc` element... | [
"def",
"_replace_keyword",
"(",
"self",
",",
"keyword",
",",
"replacement",
",",
"count",
"=",
"0",
")",
":",
"def",
"replace_with_inline",
"(",
"e",
",",
"doc",
")",
":",
"if",
"type",
"(",
"e",
")",
"==",
"Str",
"and",
"e",
".",
"text",
"==",
"ke... | 38.724638 | 18.57971 |
def predict_local(self, X, batch_size = -1):
"""
:param X: X can be a ndarray or list of ndarray if the model has multiple inputs.
The first dimension of X should be batch.
:param batch_size: total batch size of prediction.
:return: a ndarray as the prediction result.
... | [
"def",
"predict_local",
"(",
"self",
",",
"X",
",",
"batch_size",
"=",
"-",
"1",
")",
":",
"jresults",
"=",
"callBigDlFunc",
"(",
"self",
".",
"bigdl_type",
",",
"\"predictLocal\"",
",",
"self",
".",
"value",
",",
"self",
".",
"_to_jtensors",
"(",
"X",
... | 40.733333 | 15.266667 |
def reference_pix_from_wcs(frames, pixref, origin=1):
"""Compute reference pixels between frames using WCS information.
The sky world coordinates are computed on *pixref* using
the WCS of the first frame in the sequence. Then, the
pixel coordinates of the reference sky world-coordinates
are compute... | [
"def",
"reference_pix_from_wcs",
"(",
"frames",
",",
"pixref",
",",
"origin",
"=",
"1",
")",
":",
"result",
"=",
"[",
"]",
"with",
"frames",
"[",
"0",
"]",
".",
"open",
"(",
")",
"as",
"hdulist",
":",
"wcsh",
"=",
"wcs",
".",
"WCS",
"(",
"hdulist",... | 31.444444 | 18.851852 |
def get_all(self, api_method, collection_name, **kwargs):
"""
Return all objects in an api_method, handle pagination, and pass
kwargs on to the method being called.
For example, "users.list" returns an object like:
{
"members": [{<member_obj>}, {<member_obj_2>}],
... | [
"def",
"get_all",
"(",
"self",
",",
"api_method",
",",
"collection_name",
",",
"*",
"*",
"kwargs",
")",
":",
"objs",
"=",
"[",
"]",
"limit",
"=",
"250",
"# if you don't provide a limit, the slack API won't return a cursor to you",
"page",
"=",
"json",
".",
"loads"... | 35.386364 | 22.159091 |
def items(self):
"""
:return: a list of name/value attribute pairs sorted by attribute name.
"""
sorted_keys = sorted(self.keys())
return [(k, self[k]) for k in sorted_keys] | [
"def",
"items",
"(",
"self",
")",
":",
"sorted_keys",
"=",
"sorted",
"(",
"self",
".",
"keys",
"(",
")",
")",
"return",
"[",
"(",
"k",
",",
"self",
"[",
"k",
"]",
")",
"for",
"k",
"in",
"sorted_keys",
"]"
] | 34.666667 | 12.333333 |
def send_request(self, request):
'''Send a Request. Return a (message, event) pair.
The message is an unframed message to send over the network.
Wait on the event for the response; which will be in the
"result" attribute.
Raises: ProtocolError if the request violates the proto... | [
"def",
"send_request",
"(",
"self",
",",
"request",
")",
":",
"request_id",
"=",
"next",
"(",
"self",
".",
"_id_counter",
")",
"message",
"=",
"self",
".",
"_protocol",
".",
"request_message",
"(",
"request",
",",
"request_id",
")",
"return",
"message",
",... | 39.692308 | 22.615385 |
def execute_ssh(cls, command, *args, **kwargs):
"""execute_ssh(command, arguments..., pty=False, echo=False)
Execute `command` on a remote server. It first calls
:meth:`Flow.connect_ssh` using all positional and keyword
arguments, then calls :meth:`SSHClient.execute` with the command
... | [
"def",
"execute_ssh",
"(",
"cls",
",",
"command",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"pty",
"=",
"kwargs",
".",
"pop",
"(",
"'pty'",
",",
"False",
")",
"echo",
"=",
"kwargs",
".",
"pop",
"(",
"'echo'",
",",
"False",
")",
"client... | 39.875 | 21.666667 |
def one_of(inners, arg):
"""At least one of the inner validators must pass"""
for inner in inners:
with suppress(com.IbisTypeError, ValueError):
return inner(arg)
rules_formatted = ', '.join(map(repr, inners))
raise com.IbisTypeError(
'Arg passes neither of the following rul... | [
"def",
"one_of",
"(",
"inners",
",",
"arg",
")",
":",
"for",
"inner",
"in",
"inners",
":",
"with",
"suppress",
"(",
"com",
".",
"IbisTypeError",
",",
"ValueError",
")",
":",
"return",
"inner",
"(",
"arg",
")",
"rules_formatted",
"=",
"', '",
".",
"join... | 34.8 | 19.2 |
def conllu2json(input_data, n_sents=10, use_morphology=False, lang=None):
"""
Convert conllu files into JSON format for use with train cli.
use_morphology parameter enables appending morphology to tags, which is
useful for languages such as Spanish, where UD tags are not so rich.
Extract NER tags i... | [
"def",
"conllu2json",
"(",
"input_data",
",",
"n_sents",
"=",
"10",
",",
"use_morphology",
"=",
"False",
",",
"lang",
"=",
"None",
")",
":",
"# by @dvsrepo, via #11 explosion/spacy-dev-resources",
"# by @katarkor",
"docs",
"=",
"[",
"]",
"sentences",
"=",
"[",
"... | 40 | 18.068966 |
def update_offer(self, offer_id, offer_dict):
"""
Updates an offer
:param offer_id: the offer id
:param offer_dict: dict
:return: dict
"""
return self._create_put_request(resource=OFFERS, billomat_id=offer_id, send_data=offer_dict) | [
"def",
"update_offer",
"(",
"self",
",",
"offer_id",
",",
"offer_dict",
")",
":",
"return",
"self",
".",
"_create_put_request",
"(",
"resource",
"=",
"OFFERS",
",",
"billomat_id",
"=",
"offer_id",
",",
"send_data",
"=",
"offer_dict",
")"
] | 31.111111 | 16.888889 |
def load(self):
""" Return the model from the store """
if self.rid and not self.is_loaded:
store = goldman.sess.store
self._is_loaded = True
self.model = store.find(self.rtype, self.field, self.rid)
return self.model | [
"def",
"load",
"(",
"self",
")",
":",
"if",
"self",
".",
"rid",
"and",
"not",
"self",
".",
"is_loaded",
":",
"store",
"=",
"goldman",
".",
"sess",
".",
"store",
"self",
".",
"_is_loaded",
"=",
"True",
"self",
".",
"model",
"=",
"store",
".",
"find"... | 27.1 | 20 |
def remove_child(self, rhs):
"""Remove a given child element, specified by name or as element."""
if type(rhs) is XMLElement:
lib.lsl_remove_child(self.e, rhs.e)
else:
lib.lsl_remove_child_n(self.e, rhs) | [
"def",
"remove_child",
"(",
"self",
",",
"rhs",
")",
":",
"if",
"type",
"(",
"rhs",
")",
"is",
"XMLElement",
":",
"lib",
".",
"lsl_remove_child",
"(",
"self",
".",
"e",
",",
"rhs",
".",
"e",
")",
"else",
":",
"lib",
".",
"lsl_remove_child_n",
"(",
... | 41 | 9.666667 |
def _random_mutation_operator(self, individual, allow_shrink=True):
"""Perform a replacement, insertion, or shrink mutation on an individual.
Parameters
----------
individual: DEAP individual
A list of pipeline operators and model parameters that can be
compiled ... | [
"def",
"_random_mutation_operator",
"(",
"self",
",",
"individual",
",",
"allow_shrink",
"=",
"True",
")",
":",
"if",
"self",
".",
"tree_structure",
":",
"mutation_techniques",
"=",
"[",
"partial",
"(",
"gp",
".",
"mutInsert",
",",
"pset",
"=",
"self",
".",
... | 49.316667 | 28.25 |
def is_cell_empty(self, cell):
"""Checks if the cell is empty."""
if cell is None:
return True
elif self._is_cell_empty:
return self._is_cell_empty(cell)
else:
return cell is None | [
"def",
"is_cell_empty",
"(",
"self",
",",
"cell",
")",
":",
"if",
"cell",
"is",
"None",
":",
"return",
"True",
"elif",
"self",
".",
"_is_cell_empty",
":",
"return",
"self",
".",
"_is_cell_empty",
"(",
"cell",
")",
"else",
":",
"return",
"cell",
"is",
"... | 25.75 | 14 |
def create_filebase_name(self, group_info, extension='gz', file_name=None):
"""
Return tuple of resolved destination folder name and file name
"""
dirname = self.filebase.formatted_dirname(groups=group_info)
if not file_name:
file_name = self.filebase.prefix_template ... | [
"def",
"create_filebase_name",
"(",
"self",
",",
"group_info",
",",
"extension",
"=",
"'gz'",
",",
"file_name",
"=",
"None",
")",
":",
"dirname",
"=",
"self",
".",
"filebase",
".",
"formatted_dirname",
"(",
"groups",
"=",
"group_info",
")",
"if",
"not",
"f... | 45.5 | 18.25 |
def start_update(self, draw=None, queues=None, update_shared=True):
"""
Conduct the registered plot updates
This method starts the updates from what has been registered by the
:meth:`update` method. You can call this method if you did not set the
`auto_update` parameter to True ... | [
"def",
"start_update",
"(",
"self",
",",
"draw",
"=",
"None",
",",
"queues",
"=",
"None",
",",
"update_shared",
"=",
"True",
")",
":",
"def",
"update_the_others",
"(",
")",
":",
"for",
"fmto",
"in",
"fmtos",
":",
"for",
"other_fmto",
"in",
"fmto",
".",... | 38.31 | 17.29 |
def generate(self, blueprint, context, interactive=True):
"""Generate a blueprint within this application."""
if not isinstance(blueprint, Blueprint):
bp = self.blueprints.get(blueprint)
if not bp:
raise ValueError('%s is not a valid blueprint' % blueprint)
... | [
"def",
"generate",
"(",
"self",
",",
"blueprint",
",",
"context",
",",
"interactive",
"=",
"True",
")",
":",
"if",
"not",
"isinstance",
"(",
"blueprint",
",",
"Blueprint",
")",
":",
"bp",
"=",
"self",
".",
"blueprints",
".",
"get",
"(",
"blueprint",
")... | 30.76 | 15.36 |
def create_storage_policy(policy_name, policy_dict, service_instance=None):
'''
Creates a storage policy.
Supported capability types: scalar, set, range.
policy_name
Name of the policy to create.
The value of the argument will override any existing name in
``policy_dict``.
... | [
"def",
"create_storage_policy",
"(",
"policy_name",
",",
"policy_dict",
",",
"service_instance",
"=",
"None",
")",
":",
"log",
".",
"trace",
"(",
"'create storage policy \\'%s\\', dict = %s'",
",",
"policy_name",
",",
"policy_dict",
")",
"profile_manager",
"=",
"salt"... | 37.805556 | 23.583333 |
def get_as_dataframe(worksheet,
evaluate_formulas=False,
**options):
"""
Returns the worksheet contents as a DataFrame.
:param worksheet: the worksheet.
:param evaluate_formulas: if True, get the value of a cell after
formula evaluation; otherwise g... | [
"def",
"get_as_dataframe",
"(",
"worksheet",
",",
"evaluate_formulas",
"=",
"False",
",",
"*",
"*",
"options",
")",
":",
"all_values",
"=",
"_get_all_values",
"(",
"worksheet",
",",
"evaluate_formulas",
")",
"return",
"TextParser",
"(",
"all_values",
",",
"*",
... | 42.888889 | 16.666667 |
def get_tile(self, codepoint: int) -> np.array:
"""Return a copy of a tile for the given codepoint.
If the tile does not exist yet then a blank array will be returned.
The tile will have a shape of (height, width, rgba) and a dtype of
uint8. Note that most grey-scale tiles will only u... | [
"def",
"get_tile",
"(",
"self",
",",
"codepoint",
":",
"int",
")",
"->",
"np",
".",
"array",
":",
"tile",
"=",
"np",
".",
"zeros",
"(",
"self",
".",
"tile_shape",
"+",
"(",
"4",
",",
")",
",",
"dtype",
"=",
"np",
".",
"uint8",
")",
"lib",
".",
... | 40.25 | 21.75 |
def verify_any(df, check, *args, **kwargs):
"""
Verify that any of the entries in ``check(df, *args, **kwargs)``
is true
"""
result = check(df, *args, **kwargs)
try:
assert np.any(result)
except AssertionError as e:
msg = '{} not true for any'.format(check.__name__)
e... | [
"def",
"verify_any",
"(",
"df",
",",
"check",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"result",
"=",
"check",
"(",
"df",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
"try",
":",
"assert",
"np",
".",
"any",
"(",
"result",
")",
... | 27.153846 | 15.307692 |
def extract_flask_settings(self):
"""
Copies SCOUT_* settings in the app into Scout's config lookup
"""
configs = {}
configs["application_root"] = self.app.instance_path
for name in current_app.config:
if name.startswith("SCOUT_"):
value = curr... | [
"def",
"extract_flask_settings",
"(",
"self",
")",
":",
"configs",
"=",
"{",
"}",
"configs",
"[",
"\"application_root\"",
"]",
"=",
"self",
".",
"app",
".",
"instance_path",
"for",
"name",
"in",
"current_app",
".",
"config",
":",
"if",
"name",
".",
"starts... | 39.333333 | 9.833333 |
def super_kls(self):
"""
Determine what kls this group inherits from
If default kls should be used, then None is returned
"""
if not self.kls and self.parent and self.parent.name:
return self.parent.kls_name
return self.kls | [
"def",
"super_kls",
"(",
"self",
")",
":",
"if",
"not",
"self",
".",
"kls",
"and",
"self",
".",
"parent",
"and",
"self",
".",
"parent",
".",
"name",
":",
"return",
"self",
".",
"parent",
".",
"kls_name",
"return",
"self",
".",
"kls"
] | 35.5 | 12.25 |
def __init(self):
""" initializes the service """
params = {
"f" : "json",
}
json_dict = self._get(self._url, params,
securityHandler=self._securityHandler,
proxy_port=self._proxy_port,
... | [
"def",
"__init",
"(",
"self",
")",
":",
"params",
"=",
"{",
"\"f\"",
":",
"\"json\"",
",",
"}",
"json_dict",
"=",
"self",
".",
"_get",
"(",
"self",
".",
"_url",
",",
"params",
",",
"securityHandler",
"=",
"self",
".",
"_securityHandler",
",",
"proxy_po... | 39.333333 | 15.416667 |
def resolve_resource_id_refs(self, input_dict, supported_resource_id_refs):
"""
Resolve resource references within a GetAtt dict.
Example:
{ "Fn::GetAtt": ["LogicalId", "Arn"] } => {"Fn::GetAtt": ["ResolvedLogicalId", "Arn"]}
Theoretically, only the first element of the... | [
"def",
"resolve_resource_id_refs",
"(",
"self",
",",
"input_dict",
",",
"supported_resource_id_refs",
")",
":",
"if",
"not",
"self",
".",
"can_handle",
"(",
"input_dict",
")",
":",
"return",
"input_dict",
"key",
"=",
"self",
".",
"intrinsic_name",
"value",
"=",
... | 43.952381 | 31.809524 |
def _map_order_to_ticks(start, end, order, reverse=False):
"""Map elements from given `order` array to bins ranging from `start`
to `end`.
"""
size = len(order)
bounds = np.linspace(start, end, size + 1)
if reverse:
bounds = bounds[::-1]
mapping = list... | [
"def",
"_map_order_to_ticks",
"(",
"start",
",",
"end",
",",
"order",
",",
"reverse",
"=",
"False",
")",
":",
"size",
"=",
"len",
"(",
"order",
")",
"bounds",
"=",
"np",
".",
"linspace",
"(",
"start",
",",
"end",
",",
"size",
"+",
"1",
")",
"if",
... | 36.9 | 12.9 |
def validate_get_dbs(connection):
"""
validates the connection object is capable of read access to rethink
should be at least one test database by default
:param connection: <rethinkdb.net.DefaultConnection>
:return: <set> list of databases
:raises: ReqlDriverError AssertionError
"""
r... | [
"def",
"validate_get_dbs",
"(",
"connection",
")",
":",
"remote_dbs",
"=",
"set",
"(",
"rethinkdb",
".",
"db_list",
"(",
")",
".",
"run",
"(",
"connection",
")",
")",
"assert",
"remote_dbs",
"return",
"remote_dbs"
] | 31.076923 | 16 |
def authenticate_credentials(self, payload):
"""
Returns an active user that matches the payload's user id and email.
"""
User = get_user_model()
username = jwt_get_username_from_payload(payload)
if not username:
msg = _('Invalid payload.')
raise ... | [
"def",
"authenticate_credentials",
"(",
"self",
",",
"payload",
")",
":",
"User",
"=",
"get_user_model",
"(",
")",
"username",
"=",
"jwt_get_username_from_payload",
"(",
"payload",
")",
"if",
"not",
"username",
":",
"msg",
"=",
"_",
"(",
"'Invalid payload.'",
... | 31.727273 | 17.272727 |
def spawn(self, parameters=None, arguments=None, stderr=None, timeout=None, short_option_prefix="-", long_option_prefix="--"):
"""
Spawn the process defined in `cmd`
parameters is converted to options the short and long option prefixes
if a list is given as the value, the parameter is r... | [
"def",
"spawn",
"(",
"self",
",",
"parameters",
"=",
"None",
",",
"arguments",
"=",
"None",
",",
"stderr",
"=",
"None",
",",
"timeout",
"=",
"None",
",",
"short_option_prefix",
"=",
"\"-\"",
",",
"long_option_prefix",
"=",
"\"--\"",
")",
":",
"stderr",
"... | 40.066667 | 25.311111 |
def sim(self, src, tar, qval=2):
r"""Return the cosine similarity of two strings.
Parameters
----------
src : str
Source string (or QGrams/Counter objects) for comparison
tar : str
Target string (or QGrams/Counter objects) for comparison
qval : in... | [
"def",
"sim",
"(",
"self",
",",
"src",
",",
"tar",
",",
"qval",
"=",
"2",
")",
":",
"if",
"src",
"==",
"tar",
":",
"return",
"1.0",
"if",
"not",
"src",
"or",
"not",
"tar",
":",
"return",
"0.0",
"q_src",
",",
"q_tar",
"=",
"self",
".",
"_get_qgr... | 26.512195 | 19.853659 |
def bind(self, extension: Extension) -> 'DictMentor':
"""
Add any predefined or custom extension.
Args:
extension: Extension to add to the processor.
Returns:
The DictMentor itself for chaining.
"""
if not Extension.is_valid_extension(extension):... | [
"def",
"bind",
"(",
"self",
",",
"extension",
":",
"Extension",
")",
"->",
"'DictMentor'",
":",
"if",
"not",
"Extension",
".",
"is_valid_extension",
"(",
"extension",
")",
":",
"raise",
"ValueError",
"(",
"\"Cannot bind extension due to missing interface requirements\... | 30.8 | 20.266667 |
def _add_section_default(self, section, parameters):
''' Add the given section with the given paramters to the config. The
parameters must be a dictionary with all the keys to add. Each key
must be specified as an other dictionary with the following
parameters: default, descr... | [
"def",
"_add_section_default",
"(",
"self",
",",
"section",
",",
"parameters",
")",
":",
"section",
"=",
"section",
".",
"lower",
"(",
")",
"if",
"not",
"self",
".",
"has_section",
"(",
"section",
")",
":",
"self",
".",
"add_section",
"(",
"section",
")"... | 45.407407 | 18 |
def accessible_organisms(user, orgs):
"""Get the list of organisms accessible to a user, filtered by `orgs`"""
permission_map = {
x['organism']: x['permissions']
for x in user.organismPermissions
if 'WRITE' in x['permissions'] or
'READ' in x['permissions'] or
'ADMINISTRAT... | [
"def",
"accessible_organisms",
"(",
"user",
",",
"orgs",
")",
":",
"permission_map",
"=",
"{",
"x",
"[",
"'organism'",
"]",
":",
"x",
"[",
"'permissions'",
"]",
"for",
"x",
"in",
"user",
".",
"organismPermissions",
"if",
"'WRITE'",
"in",
"x",
"[",
"'perm... | 34.105263 | 16.631579 |
def gettrace(self, burn=0, thin=1, chain=-1, slicing=None):
"""Return the trace (last by default).
Input:
- burn (int): The number of transient steps to skip.
- thin (int): Keep one in thin.
- chain (int): The index of the chain to fetch. If None, return all
ch... | [
"def",
"gettrace",
"(",
"self",
",",
"burn",
"=",
"0",
",",
"thin",
"=",
"1",
",",
"chain",
"=",
"-",
"1",
",",
"slicing",
"=",
"None",
")",
":",
"# warnings.warn('Use Sampler.trace method instead.',",
"# DeprecationWarning)",
"if",
"not",
"slicing",
":",
"s... | 40.516129 | 15.193548 |
def clean():
""" Remove all of the files contained in workdir.options.path """
if os.path.isdir(options.path):
logger.info('cleaning working directory: ' + options.path)
for filename in os.listdir(options.path):
filepath = os.path.join(options.path, filename)
if os.path.i... | [
"def",
"clean",
"(",
")",
":",
"if",
"os",
".",
"path",
".",
"isdir",
"(",
"options",
".",
"path",
")",
":",
"logger",
".",
"info",
"(",
"'cleaning working directory: '",
"+",
"options",
".",
"path",
")",
"for",
"filename",
"in",
"os",
".",
"listdir",
... | 44.8 | 14.3 |
def get_as_integer_with_default(self, index, default_value):
"""
Converts array element into an integer or returns default value if conversion is not possible.
:param index: an index of element to get.
:param default_value: the default value
:return: integer value ot the eleme... | [
"def",
"get_as_integer_with_default",
"(",
"self",
",",
"index",
",",
"default_value",
")",
":",
"value",
"=",
"self",
"[",
"index",
"]",
"return",
"IntegerConverter",
".",
"to_integer_with_default",
"(",
"value",
",",
"default_value",
")"
] | 39.833333 | 26.833333 |
def translate(self):
"""Compile the variable lookup."""
ident = self.ident
expr = ex_rvalue(VARIABLE_PREFIX + ident)
return [expr], set([ident]), set() | [
"def",
"translate",
"(",
"self",
")",
":",
"ident",
"=",
"self",
".",
"ident",
"expr",
"=",
"ex_rvalue",
"(",
"VARIABLE_PREFIX",
"+",
"ident",
")",
"return",
"[",
"expr",
"]",
",",
"set",
"(",
"[",
"ident",
"]",
")",
",",
"set",
"(",
")"
] | 35.8 | 9 |
def main():
"""Install or upgrade setuptools and EasyInstall."""
options = _parse_args()
archive = download_setuptools(**_download_args(options))
return _install(archive, _build_install_args(options)) | [
"def",
"main",
"(",
")",
":",
"options",
"=",
"_parse_args",
"(",
")",
"archive",
"=",
"download_setuptools",
"(",
"*",
"*",
"_download_args",
"(",
"options",
")",
")",
"return",
"_install",
"(",
"archive",
",",
"_build_install_args",
"(",
"options",
")",
... | 42.4 | 16 |
def _ParseKey(self, knowledge_base, registry_key, value_name):
"""Parses a Windows Registry key for a preprocessing attribute.
Args:
knowledge_base (KnowledgeBase): to fill with preprocessing information.
registry_key (dfwinreg.WinRegistryKey): Windows Registry key.
value_name (str): name of ... | [
"def",
"_ParseKey",
"(",
"self",
",",
"knowledge_base",
",",
"registry_key",
",",
"value_name",
")",
":",
"try",
":",
"registry_value",
"=",
"registry_key",
".",
"GetValueByName",
"(",
"value_name",
")",
"except",
"IOError",
"as",
"exception",
":",
"raise",
"e... | 37.652174 | 20.782609 |
def has_hints(self):
"""
True if self provides hints on the cutoff energy.
"""
for acc in ["low", "normal", "high"]:
try:
if self.hint_for_accuracy(acc) is None:
return False
except KeyError:
return False
... | [
"def",
"has_hints",
"(",
"self",
")",
":",
"for",
"acc",
"in",
"[",
"\"low\"",
",",
"\"normal\"",
",",
"\"high\"",
"]",
":",
"try",
":",
"if",
"self",
".",
"hint_for_accuracy",
"(",
"acc",
")",
"is",
"None",
":",
"return",
"False",
"except",
"KeyError"... | 29.272727 | 12.181818 |
def fromfilenames(filenames, coltype = int):
"""
Return a segmentlist describing the intervals spanned by the files
whose names are given in the list filenames. The segmentlist is
constructed by parsing the file names, and the boundaries of each
segment are coerced to type coltype.
The file names are parsed usi... | [
"def",
"fromfilenames",
"(",
"filenames",
",",
"coltype",
"=",
"int",
")",
":",
"pattern",
"=",
"re",
".",
"compile",
"(",
"r\"-([\\d.]+)-([\\d.]+)\\.[\\w_+#]+\\Z\"",
")",
"l",
"=",
"segments",
".",
"segmentlist",
"(",
")",
"for",
"name",
"in",
"filenames",
... | 39.56 | 20.04 |
def reduceByKeyAndWindow(self, func, invFunc, windowDuration, slideDuration=None,
numPartitions=None, filterFunc=None):
"""
Return a new DStream by applying incremental `reduceByKey` over a sliding window.
The reduced value of over a new window is calculated using t... | [
"def",
"reduceByKeyAndWindow",
"(",
"self",
",",
"func",
",",
"invFunc",
",",
"windowDuration",
",",
"slideDuration",
"=",
"None",
",",
"numPartitions",
"=",
"None",
",",
"filterFunc",
"=",
"None",
")",
":",
"self",
".",
"_validate_window_param",
"(",
"windowD... | 53.517857 | 28.089286 |
def IsValidLanguageCode(lang):
"""
Checks the validity of a language code value:
- checks whether the code, as lower case, is well formed and valid BCP47
using the pybcp47 module
"""
bcp47_obj = parser.ParseLanguage(str(lang.lower()))
return bcp47_obj.IsWellformed() and bcp47_obj.IsValid() | [
"def",
"IsValidLanguageCode",
"(",
"lang",
")",
":",
"bcp47_obj",
"=",
"parser",
".",
"ParseLanguage",
"(",
"str",
"(",
"lang",
".",
"lower",
"(",
")",
")",
")",
"return",
"bcp47_obj",
".",
"IsWellformed",
"(",
")",
"and",
"bcp47_obj",
".",
"IsValid",
"(... | 37.875 | 11.625 |
def update_build(self, build, project, build_id, retry=None):
"""UpdateBuild.
Updates a build.
:param :class:`<Build> <azure.devops.v5_0.build.models.Build>` build: The build.
:param str project: Project ID or project name
:param int build_id: The ID of the build.
:param ... | [
"def",
"update_build",
"(",
"self",
",",
"build",
",",
"project",
",",
"build_id",
",",
"retry",
"=",
"None",
")",
":",
"route_values",
"=",
"{",
"}",
"if",
"project",
"is",
"not",
"None",
":",
"route_values",
"[",
"'project'",
"]",
"=",
"self",
".",
... | 50.16 | 18.72 |
def fletcher_checksum(data, offset):
"""
Fletcher Checksum -- Refer to RFC1008
calling with offset == _FLETCHER_CHECKSUM_VALIDATE will validate the
checksum without modifying the buffer; a valid checksum returns 0.
"""
c0 = 0
c1 = 0
pos = 0
length = len(data)
data = bytearray(da... | [
"def",
"fletcher_checksum",
"(",
"data",
",",
"offset",
")",
":",
"c0",
"=",
"0",
"c1",
"=",
"0",
"pos",
"=",
"0",
"length",
"=",
"len",
"(",
"data",
")",
"data",
"=",
"bytearray",
"(",
"data",
")",
"data",
"[",
"offset",
":",
"offset",
"+",
"2",... | 22.575758 | 19.666667 |
def consultar_sat(retorno):
"""Constrói uma :class:`RespostaSAT` para o retorno (unicode) da função
:meth:`~satcfe.base.FuncoesSAT.consultar_sat`.
"""
resposta = analisar_retorno(forcar_unicode(retorno),
funcao='ConsultarSAT')
if resposta.EEEEE not in ('08000',):
... | [
"def",
"consultar_sat",
"(",
"retorno",
")",
":",
"resposta",
"=",
"analisar_retorno",
"(",
"forcar_unicode",
"(",
"retorno",
")",
",",
"funcao",
"=",
"'ConsultarSAT'",
")",
"if",
"resposta",
".",
"EEEEE",
"not",
"in",
"(",
"'08000'",
",",
")",
":",
"raise... | 42.444444 | 8.444444 |
def _handleBulletWidth(bulletText, style, maxWidths):
"""
work out bullet width and adjust maxWidths[0] if neccessary
"""
if bulletText:
if isinstance(bulletText, basestring):
bulletWidth = stringWidth(bulletText, style.bulletFontName, style.bulletFontSize)
else:
... | [
"def",
"_handleBulletWidth",
"(",
"bulletText",
",",
"style",
",",
"maxWidths",
")",
":",
"if",
"bulletText",
":",
"if",
"isinstance",
"(",
"bulletText",
",",
"basestring",
")",
":",
"bulletWidth",
"=",
"stringWidth",
"(",
"bulletText",
",",
"style",
".",
"b... | 45.882353 | 19.294118 |
def add_controller(self, key, controller):
"""Add child controller
The passed controller is registered as child of self. The register_actions method of the child controller is
called, allowing the child controller to register shortcut callbacks.
:param key: Name of the controller (uniq... | [
"def",
"add_controller",
"(",
"self",
",",
"key",
",",
"controller",
")",
":",
"assert",
"isinstance",
"(",
"controller",
",",
"ExtendedController",
")",
"controller",
".",
"parent",
"=",
"self",
"self",
".",
"__child_controllers",
"[",
"key",
"]",
"=",
"con... | 54.6 | 28.866667 |
def _scalar_power(self, f, p, out):
"""Compute ``p``-th power of ``f`` for ``p`` scalar."""
# Avoid infinite recursions by making a copy of the function
f_copy = f.copy()
def pow_posint(x, n):
"""Power function for positive integer ``n``, out-of-place."""
if isin... | [
"def",
"_scalar_power",
"(",
"self",
",",
"f",
",",
"p",
",",
"out",
")",
":",
"# Avoid infinite recursions by making a copy of the function",
"f_copy",
"=",
"f",
".",
"copy",
"(",
")",
"def",
"pow_posint",
"(",
"x",
",",
"n",
")",
":",
"\"\"\"Power function f... | 35.581395 | 15.069767 |
def numberize(string):
'''Turns a string into a number (``int`` or ``float``) if it's only a number (ignoring spaces), otherwise returns the string.
For example, ``"5 "`` becomes ``5`` and ``"2 ton"`` remains ``"2 ton"``'''
if not isinstance(string,basestring):
return string
just_int = r'^\s*[-+... | [
"def",
"numberize",
"(",
"string",
")",
":",
"if",
"not",
"isinstance",
"(",
"string",
",",
"basestring",
")",
":",
"return",
"string",
"just_int",
"=",
"r'^\\s*[-+]?\\d+\\s*$'",
"just_float",
"=",
"r'^\\s*[-+]?\\d+\\.(\\d+)?\\s*$'",
"if",
"re",
".",
"match",
"(... | 42.333333 | 19.666667 |
def get_rgb_from_xy_and_brightness(self, x, y, bri=1):
"""Inverse of `get_xy_point_from_rgb`. Returns (r, g, b) for given x, y values.
Implementation of the instructions found on the Philips Hue iOS SDK docs: http://goo.gl/kWKXKl
"""
# The xy to color conversion is almost the same, but i... | [
"def",
"get_rgb_from_xy_and_brightness",
"(",
"self",
",",
"x",
",",
"y",
",",
"bri",
"=",
"1",
")",
":",
"# The xy to color conversion is almost the same, but in reverse order.",
"# Check if the xy value is within the color gamut of the lamp.",
"# If not continue with step 2, otherw... | 45.069767 | 25.674419 |
def notebook_to_md(notebook):
"""Convert a notebook to its Markdown representation, using Pandoc"""
tmp_file = tempfile.NamedTemporaryFile(delete=False)
tmp_file.write(ipynb_writes(notebook).encode('utf-8'))
tmp_file.close()
pandoc(u'--from ipynb --to markdown -s --atx-headers --wrap=preserve --pre... | [
"def",
"notebook_to_md",
"(",
"notebook",
")",
":",
"tmp_file",
"=",
"tempfile",
".",
"NamedTemporaryFile",
"(",
"delete",
"=",
"False",
")",
"tmp_file",
".",
"write",
"(",
"ipynb_writes",
"(",
"notebook",
")",
".",
"encode",
"(",
"'utf-8'",
")",
")",
"tmp... | 39.846154 | 23.615385 |
def ts_to_dt_str(ts, dt_format='%Y-%m-%d %H:%M:%S'):
"""
时间戳转换为日期字符串
Args:
ts: 待转换的时间戳
dt_format: 目标日期字符串格式
Returns: 日期字符串
"""
return datetime.datetime.fromtimestamp(int(ts)).strftime(dt_format) | [
"def",
"ts_to_dt_str",
"(",
"ts",
",",
"dt_format",
"=",
"'%Y-%m-%d %H:%M:%S'",
")",
":",
"return",
"datetime",
".",
"datetime",
".",
"fromtimestamp",
"(",
"int",
"(",
"ts",
")",
")",
".",
"strftime",
"(",
"dt_format",
")"
] | 20.545455 | 21.272727 |
def classify_intersection9(s, curve1, curve2):
"""Image for :func:`._surface_helpers.classify_intersection` docstring."""
if NO_IMAGES:
return
surface1 = bezier.Surface.from_nodes(
np.asfortranarray(
[
[0.0, 20.0, 40.0, 10.0, 30.0, 20.0],
[0.0, 40... | [
"def",
"classify_intersection9",
"(",
"s",
",",
"curve1",
",",
"curve2",
")",
":",
"if",
"NO_IMAGES",
":",
"return",
"surface1",
"=",
"bezier",
".",
"Surface",
".",
"from_nodes",
"(",
"np",
".",
"asfortranarray",
"(",
"[",
"[",
"0.0",
",",
"20.0",
",",
... | 37.627907 | 16.232558 |
def augment(self, dct: NonAugmentedDict,
document: Optional[YamlDocument] = None) -> AugmentedDict:
"""
Augments the given dictionary by using all the bound extensions.
Args:
dct: Dictionary to augment.
document: The document the dictionary was loaded fro... | [
"def",
"augment",
"(",
"self",
",",
"dct",
":",
"NonAugmentedDict",
",",
"document",
":",
"Optional",
"[",
"YamlDocument",
"]",
"=",
"None",
")",
"->",
"AugmentedDict",
":",
"Validator",
".",
"instance_of",
"(",
"dict",
",",
"raise_ex",
"=",
"True",
",",
... | 33.40625 | 14.65625 |
def has_annotation(self, annotation: str) -> bool:
"""Check if this annotation is defined."""
return (
self.has_enumerated_annotation(annotation) or
self.has_regex_annotation(annotation) or
self.has_local_annotation(annotation)
) | [
"def",
"has_annotation",
"(",
"self",
",",
"annotation",
":",
"str",
")",
"->",
"bool",
":",
"return",
"(",
"self",
".",
"has_enumerated_annotation",
"(",
"annotation",
")",
"or",
"self",
".",
"has_regex_annotation",
"(",
"annotation",
")",
"or",
"self",
"."... | 40.428571 | 14.714286 |
def has_all_changes_covered(self):
"""
Return `True` if all changes have been covered, `False` otherwise.
"""
for filename in self.files():
for hunk in self.file_source_hunks(filename):
for line in hunk:
if line.reason is None:
... | [
"def",
"has_all_changes_covered",
"(",
"self",
")",
":",
"for",
"filename",
"in",
"self",
".",
"files",
"(",
")",
":",
"for",
"hunk",
"in",
"self",
".",
"file_source_hunks",
"(",
"filename",
")",
":",
"for",
"line",
"in",
"hunk",
":",
"if",
"line",
"."... | 39.083333 | 10.083333 |
def strip_querystring(url):
"""Remove the querystring from the end of a URL."""
p = six.moves.urllib.parse.urlparse(url)
return p.scheme + "://" + p.netloc + p.path | [
"def",
"strip_querystring",
"(",
"url",
")",
":",
"p",
"=",
"six",
".",
"moves",
".",
"urllib",
".",
"parse",
".",
"urlparse",
"(",
"url",
")",
"return",
"p",
".",
"scheme",
"+",
"\"://\"",
"+",
"p",
".",
"netloc",
"+",
"p",
".",
"path"
] | 43.25 | 6 |
def R(self, value):
""" measurement uncertainty"""
self._R = value
self._R1_2 = cholesky(self._R, lower=True) | [
"def",
"R",
"(",
"self",
",",
"value",
")",
":",
"self",
".",
"_R",
"=",
"value",
"self",
".",
"_R1_2",
"=",
"cholesky",
"(",
"self",
".",
"_R",
",",
"lower",
"=",
"True",
")"
] | 32.5 | 12 |
def matches_video_filename(self, video):
"""
Detect whether the filename of videofile matches with this SubtitleFile.
:param video: VideoFile instance
:return: True if match
"""
vid_fn = video.get_filename()
vid_base, _ = os.path.splitext(vid_fn)
vid_base... | [
"def",
"matches_video_filename",
"(",
"self",
",",
"video",
")",
":",
"vid_fn",
"=",
"video",
".",
"get_filename",
"(",
")",
"vid_base",
",",
"_",
"=",
"os",
".",
"path",
".",
"splitext",
"(",
"vid_fn",
")",
"vid_base",
"=",
"vid_base",
".",
"lower",
"... | 33.871795 | 16.641026 |
def slice_reStructuredText(input, output):
"""
Slices given reStructuredText file.
:param input: ReStructuredText file to slice.
:type input: unicode
:param output: Directory to output sliced reStructuredText files.
:type output: unicode
:return: Definition success.
:rtype: bool
"""... | [
"def",
"slice_reStructuredText",
"(",
"input",
",",
"output",
")",
":",
"LOGGER",
".",
"info",
"(",
"\"{0} | Slicing '{1}' file!\"",
".",
"format",
"(",
"slice_reStructuredText",
".",
"__name__",
",",
"input",
")",
")",
"file",
"=",
"File",
"(",
"input",
")",
... | 40.206897 | 26.103448 |
async def verify_chain_of_trust(chain):
"""Build and verify the chain of trust.
Args:
chain (ChainOfTrust): the chain we're operating on
Raises:
CoTError: on failure
"""
log_path = os.path.join(chain.context.config["task_log_dir"], "chain_of_trust.log")
scriptworker_log = logg... | [
"async",
"def",
"verify_chain_of_trust",
"(",
"chain",
")",
":",
"log_path",
"=",
"os",
".",
"path",
".",
"join",
"(",
"chain",
".",
"context",
".",
"config",
"[",
"\"task_log_dir\"",
"]",
",",
"\"chain_of_trust.log\"",
")",
"scriptworker_log",
"=",
"logging",... | 39.804878 | 18.04878 |
def count(self):
""" Compute count of group, excluding missing values """
from pandas.core.dtypes.missing import _isna_ndarraylike as _isna
data, _ = self._get_data_to_aggregate()
ids, _, ngroups = self.grouper.group_info
mask = ids != -1
val = ((mask & ~_isna(np.atleas... | [
"def",
"count",
"(",
"self",
")",
":",
"from",
"pandas",
".",
"core",
".",
"dtypes",
".",
"missing",
"import",
"_isna_ndarraylike",
"as",
"_isna",
"data",
",",
"_",
"=",
"self",
".",
"_get_data_to_aggregate",
"(",
")",
"ids",
",",
"_",
",",
"ngroups",
... | 37.235294 | 21.235294 |
def iter_regions(self):
"""
Return an iterable list of all region files. Use this function if you only
want to loop through each region files once, and do not want to cache the results.
"""
# TODO: Implement BoundingBox
# TODO: Implement sort order
for x,z in self... | [
"def",
"iter_regions",
"(",
"self",
")",
":",
"# TODO: Implement BoundingBox",
"# TODO: Implement sort order",
"for",
"x",
",",
"z",
"in",
"self",
".",
"regionfiles",
".",
"keys",
"(",
")",
":",
"close_after_use",
"=",
"False",
"if",
"(",
"x",
",",
"z",
")",... | 40.454545 | 13.727273 |
def base_url(klass, space_id, parent_resource_id, resource_url='entries', resource_id=None, environment_id=None):
"""
Returns the URI for the snapshot.
"""
return "spaces/{0}{1}/{2}/{3}/snapshots/{4}".format(
space_id,
'/environments/{0}'.format(environment_id) i... | [
"def",
"base_url",
"(",
"klass",
",",
"space_id",
",",
"parent_resource_id",
",",
"resource_url",
"=",
"'entries'",
",",
"resource_id",
"=",
"None",
",",
"environment_id",
"=",
"None",
")",
":",
"return",
"\"spaces/{0}{1}/{2}/{3}/snapshots/{4}\"",
".",
"format",
"... | 39.416667 | 23.25 |
def impersonate_user(self, username, password):
"""delegate to personate_user method
"""
if self.personate_user:
self.personate_user.impersonate_user(username, password) | [
"def",
"impersonate_user",
"(",
"self",
",",
"username",
",",
"password",
")",
":",
"if",
"self",
".",
"personate_user",
":",
"self",
".",
"personate_user",
".",
"impersonate_user",
"(",
"username",
",",
"password",
")"
] | 40.2 | 8.8 |
def get_target_transcript(self,min_intron=1):
"""Get the mapping of to the target strand
:returns: Transcript mapped to target
:rtype: Transcript
"""
if min_intron < 1:
sys.stderr.write("ERROR minimum intron should be 1 base or longer\n")
sys.exit()
#tx = Transcript()
rngs = [... | [
"def",
"get_target_transcript",
"(",
"self",
",",
"min_intron",
"=",
"1",
")",
":",
"if",
"min_intron",
"<",
"1",
":",
"sys",
".",
"stderr",
".",
"write",
"(",
"\"ERROR minimum intron should be 1 base or longer\\n\"",
")",
"sys",
".",
"exit",
"(",
")",
"#tx = ... | 37.125 | 15.40625 |
def exit(self, signal=None, frame=None):
"""
Properly close the AMQP connections
"""
self.input_channel.close()
self.client_queue.close()
self.connection.close()
log.info("Worker exiting")
sys.exit(0) | [
"def",
"exit",
"(",
"self",
",",
"signal",
"=",
"None",
",",
"frame",
"=",
"None",
")",
":",
"self",
".",
"input_channel",
".",
"close",
"(",
")",
"self",
".",
"client_queue",
".",
"close",
"(",
")",
"self",
".",
"connection",
".",
"close",
"(",
")... | 28.444444 | 5.777778 |
def _CalculateDOWDelta(self, wd, wkdy, offset, style, currentDayStyle):
"""
Based on the C{style} and C{currentDayStyle} determine what
day-of-week value is to be returned.
@type wd: integer
@param wd: day-of-week value for the current day
@typ... | [
"def",
"_CalculateDOWDelta",
"(",
"self",
",",
"wd",
",",
"wkdy",
",",
"offset",
",",
"style",
",",
"currentDayStyle",
")",
":",
"diffBase",
"=",
"wkdy",
"-",
"wd",
"origOffset",
"=",
"offset",
"if",
"offset",
"==",
"2",
":",
"# no modifier is present.",
"... | 37.307692 | 15.769231 |
def delete_fixed_rate_shipping_by_id(cls, fixed_rate_shipping_id, **kwargs):
"""Delete FixedRateShipping
Delete an instance of FixedRateShipping by its ID.
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please pass async=True
>>> t... | [
"def",
"delete_fixed_rate_shipping_by_id",
"(",
"cls",
",",
"fixed_rate_shipping_id",
",",
"*",
"*",
"kwargs",
")",
":",
"kwargs",
"[",
"'_return_http_data_only'",
"]",
"=",
"True",
"if",
"kwargs",
".",
"get",
"(",
"'async'",
")",
":",
"return",
"cls",
".",
... | 47.52381 | 25.714286 |
def add_data_point(self, x, y):
"""Adds a data point to the series.
:param x: The numerical x value to be added.
:param y: The numerical y value to be added."""
if not is_numeric(x):
raise TypeError("x value must be numeric, not '%s'" % str(x))
if not is_numeric(y):... | [
"def",
"add_data_point",
"(",
"self",
",",
"x",
",",
"y",
")",
":",
"if",
"not",
"is_numeric",
"(",
"x",
")",
":",
"raise",
"TypeError",
"(",
"\"x value must be numeric, not '%s'\"",
"%",
"str",
"(",
"x",
")",
")",
"if",
"not",
"is_numeric",
"(",
"y",
... | 39.5 | 16.5 |
def _sendmsg(self,method,url,headers):
'''发送消息'''
msg = '%s %s %s'%(method,url,RTSP_VERSION)
headers['User-Agent'] = DEFAULT_USERAGENT
cseq = self._next_seq()
self._cseq_map[cseq] = method
headers['CSeq'] = str(cseq)
if self._session_id: headers['Session'] = self.... | [
"def",
"_sendmsg",
"(",
"self",
",",
"method",
",",
"url",
",",
"headers",
")",
":",
"msg",
"=",
"'%s %s %s'",
"%",
"(",
"method",
",",
"url",
",",
"RTSP_VERSION",
")",
"headers",
"[",
"'User-Agent'",
"]",
"=",
"DEFAULT_USERAGENT",
"cseq",
"=",
"self",
... | 41.647059 | 12.117647 |
def pprint(walker):
"""Pretty printer for tree walkers
Takes a TreeWalker instance and pretty prints the output of walking the tree.
:arg walker: a TreeWalker instance
"""
output = []
indent = 0
for token in concatenateCharacterTokens(walker):
type = token["type"]
if type ... | [
"def",
"pprint",
"(",
"walker",
")",
":",
"output",
"=",
"[",
"]",
"indent",
"=",
"0",
"for",
"token",
"in",
"concatenateCharacterTokens",
"(",
"walker",
")",
":",
"type",
"=",
"token",
"[",
"\"type\"",
"]",
"if",
"type",
"in",
"(",
"\"StartTag\"",
","... | 37.92 | 19.186667 |
def set_description(self, id, **kwargs): # noqa: E501
"""Set description associated with a specific source # noqa: E501
# noqa: E501
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please pass async_req=True
>>> thread = api.set... | [
"def",
"set_description",
"(",
"self",
",",
"id",
",",
"*",
"*",
"kwargs",
")",
":",
"# noqa: E501",
"kwargs",
"[",
"'_return_http_data_only'",
"]",
"=",
"True",
"if",
"kwargs",
".",
"get",
"(",
"'async_req'",
")",
":",
"return",
"self",
".",
"set_descript... | 40.636364 | 18.045455 |
def calculate_euc_distance(a, b):
"""Calculates Eclidian distances from two points a and b
Args
----
a : (:obj:`float`, :obj:`float`)
Two-dimension tuple (x1,y1)
b : (:obj:`float`, :obj:`float`)
Two-dimension tuple (x2,y2)
Returns
-------
float
the distance.... | [
"def",
"calculate_euc_distance",
"(",
"a",
",",
"b",
")",
":",
"x1",
",",
"y1",
"=",
"a",
"x2",
",",
"y2",
"=",
"b",
"return",
"int",
"(",
"round",
"(",
"math",
".",
"sqrt",
"(",
"(",
"(",
"x1",
"-",
"x2",
")",
"**",
"2",
")",
"+",
"(",
"("... | 21.736842 | 20.842105 |
def pg_dsn(settings: Settings) -> str:
"""
:param settings: settings including connection settings
:return: DSN url suitable for sqlalchemy and aiopg.
"""
return str(URL(
database=settings.DB_NAME,
password=settings.DB_PASSWORD,
host=settings.DB_HOST,
port=settings.DB... | [
"def",
"pg_dsn",
"(",
"settings",
":",
"Settings",
")",
"->",
"str",
":",
"return",
"str",
"(",
"URL",
"(",
"database",
"=",
"settings",
".",
"DB_NAME",
",",
"password",
"=",
"settings",
".",
"DB_PASSWORD",
",",
"host",
"=",
"settings",
".",
"DB_HOST",
... | 29.769231 | 10.384615 |
def register(self, name):
"""Return decorator to register item with a specific name."""
def decorator(func):
"""Register decorated function."""
self[name] = func
return func
return decorator | [
"def",
"register",
"(",
"self",
",",
"name",
")",
":",
"def",
"decorator",
"(",
"func",
")",
":",
"\"\"\"Register decorated function.\"\"\"",
"self",
"[",
"name",
"]",
"=",
"func",
"return",
"func",
"return",
"decorator"
] | 30.5 | 13.875 |
def deserialize(encoded, **kwargs):
'''Construct a muda transformation from a JSON encoded string.
Parameters
----------
encoded : str
JSON encoding of the transformation or pipeline
kwargs
Additional keyword arguments to `jsonpickle.decode()`
Returns
-------
obj
... | [
"def",
"deserialize",
"(",
"encoded",
",",
"*",
"*",
"kwargs",
")",
":",
"params",
"=",
"jsonpickle",
".",
"decode",
"(",
"encoded",
",",
"*",
"*",
"kwargs",
")",
"return",
"__reconstruct",
"(",
"params",
")"
] | 19.8125 | 25.125 |
def be_array_from_bytes(fmt, data):
"""
Reads an array from bytestring with big-endian data.
"""
arr = array.array(str(fmt), data)
return fix_byteorder(arr) | [
"def",
"be_array_from_bytes",
"(",
"fmt",
",",
"data",
")",
":",
"arr",
"=",
"array",
".",
"array",
"(",
"str",
"(",
"fmt",
")",
",",
"data",
")",
"return",
"fix_byteorder",
"(",
"arr",
")"
] | 28.5 | 5.833333 |
def initialize_repo(self):
"""
Clones repository & sets up usernames.
"""
logging.info('Repo {} doesn\'t exist. Cloning...'.format(self.repo_dir))
clone_args = ['git', 'clone']
if self.depth and self.depth > 0:
clone_args.extend(['--depth', str(self.depth)])
... | [
"def",
"initialize_repo",
"(",
"self",
")",
":",
"logging",
".",
"info",
"(",
"'Repo {} doesn\\'t exist. Cloning...'",
".",
"format",
"(",
"self",
".",
"repo_dir",
")",
")",
"clone_args",
"=",
"[",
"'git'",
",",
"'clone'",
"]",
"if",
"self",
".",
"depth",
... | 49.066667 | 20.533333 |
def api_key_from_file(url):
""" Check bugzillarc for an API key for this Bugzilla URL. """
path = os.path.expanduser('~/.config/python-bugzilla/bugzillarc')
cfg = SafeConfigParser()
cfg.read(path)
domain = urlparse(url)[1]
if domain not in cfg.sections():
return None
if not cfg.has_o... | [
"def",
"api_key_from_file",
"(",
"url",
")",
":",
"path",
"=",
"os",
".",
"path",
".",
"expanduser",
"(",
"'~/.config/python-bugzilla/bugzillarc'",
")",
"cfg",
"=",
"SafeConfigParser",
"(",
")",
"cfg",
".",
"read",
"(",
"path",
")",
"domain",
"=",
"urlparse"... | 35.727273 | 12.818182 |
def add_shapes(self,**kwargs):
"""
Add a shape to the QuantFigure.
kwargs :
hline : int, list or dict
Draws a horizontal line at the
indicated y position(s)
Extra parameters can be passed in
the form of a dictionary (see shapes)
vline : int, list or dict
Draws a vertical line at the
... | [
"def",
"add_shapes",
"(",
"self",
",",
"*",
"*",
"kwargs",
")",
":",
"kwargs",
"=",
"utils",
".",
"check_kwargs",
"(",
"kwargs",
",",
"get_shapes_kwargs",
"(",
")",
",",
"{",
"}",
",",
"clean_origin",
"=",
"True",
")",
"for",
"k",
",",
"v",
"in",
"... | 29.853659 | 10.731707 |
def rename(self, **kwargs):
'''Rename series in the group.'''
for old, new in kwargs.iteritems():
if old in self.groups:
self.groups[new] = self.groups[old]
del self.groups[old] | [
"def",
"rename",
"(",
"self",
",",
"*",
"*",
"kwargs",
")",
":",
"for",
"old",
",",
"new",
"in",
"kwargs",
".",
"iteritems",
"(",
")",
":",
"if",
"old",
"in",
"self",
".",
"groups",
":",
"self",
".",
"groups",
"[",
"new",
"]",
"=",
"self",
".",... | 38.666667 | 6.333333 |
def N50(arr):
"""N50 often used in assessing denovo assembly.
:param arr: list of numbers
:type arr: number[] a number array
:return: N50
:rtype: float
"""
if len(arr) == 0:
sys.stderr.write("ERROR: no content in array to take N50\n")
sys.exit()
tot = sum(arr)
half = float(tot)/float(2)
cu... | [
"def",
"N50",
"(",
"arr",
")",
":",
"if",
"len",
"(",
"arr",
")",
"==",
"0",
":",
"sys",
".",
"stderr",
".",
"write",
"(",
"\"ERROR: no content in array to take N50\\n\"",
")",
"sys",
".",
"exit",
"(",
")",
"tot",
"=",
"sum",
"(",
"arr",
")",
"half",... | 22.47619 | 19.52381 |
def member_add(self, stream_id, user_id):
''' add a user to a stream '''
req_hook = 'pod/v1/room/' + str(stream_id) + '/membership/add'
req_args = '{ "id": %s }' % user_id
status_code, response = self.__rest__.POST_query(req_hook, req_args)
self.logger.debug('%s: %s' % (status_co... | [
"def",
"member_add",
"(",
"self",
",",
"stream_id",
",",
"user_id",
")",
":",
"req_hook",
"=",
"'pod/v1/room/'",
"+",
"str",
"(",
"stream_id",
")",
"+",
"'/membership/add'",
"req_args",
"=",
"'{ \"id\": %s }'",
"%",
"user_id",
"status_code",
",",
"response",
"... | 52.142857 | 13.857143 |
def Lines(startPoints, endPoints=None, scale=1, lw=1, c=None, alpha=1, dotted=False):
"""
Build the line segments between two lists of points `startPoints` and `endPoints`.
`startPoints` can be also passed in the form ``[[point1, point2], ...]``.
:param float scale: apply a rescaling factor to the leng... | [
"def",
"Lines",
"(",
"startPoints",
",",
"endPoints",
"=",
"None",
",",
"scale",
"=",
"1",
",",
"lw",
"=",
"1",
",",
"c",
"=",
"None",
",",
"alpha",
"=",
"1",
",",
"dotted",
"=",
"False",
")",
":",
"if",
"endPoints",
"is",
"not",
"None",
":",
"... | 31.216216 | 21 |
def get_assessment_ids(self):
"""Gets the Ids of any assessments associated with this activity.
return: (osid.id.IdList) - list of assessment Ids
raise: IllegalState - is_assessment_based_activity() is false
compliance: mandatory - This method must be implemented.
"""
... | [
"def",
"get_assessment_ids",
"(",
"self",
")",
":",
"if",
"not",
"self",
".",
"is_assessment_based_activity",
"(",
")",
":",
"raise",
"IllegalState",
"(",
")",
"else",
":",
"return",
"[",
"Id",
"(",
"a",
")",
"for",
"a",
"in",
"self",
".",
"_my_map",
"... | 38.75 | 19.416667 |
def get_readable_string(integer):
r"""
Convert an integer to a readable 2-character representation. This is useful for reversing
examples: 41 == ".A", 13 == "\n", 20 (space) == "__"
Returns a readable 2-char representation of an int.
"""
if integer == 9: #\t
readable_strin... | [
"def",
"get_readable_string",
"(",
"integer",
")",
":",
"if",
"integer",
"==",
"9",
":",
"#\\t",
"readable_string",
"=",
"\"\\\\t\"",
"elif",
"integer",
"==",
"10",
":",
"#\\r",
"readable_string",
"=",
"\"\\\\r\"",
"elif",
"integer",
"==",
"13",
":",
"#\\n",... | 35.75 | 15.7 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.