text stringlengths 75 104k | code_tokens list | avg_line_len float64 7.91 980 | score float64 0 0.18 |
|---|---|---|---|
def map_concepts_to_indicators(
self, n: int = 1, min_temporal_res: Optional[str] = None
):
""" Map each concept node in the AnalysisGraph instance to one or more
tangible quantities, known as 'indicators'.
Args:
n: Number of matches to keep
min_temporal_res:... | [
"def",
"map_concepts_to_indicators",
"(",
"self",
",",
"n",
":",
"int",
"=",
"1",
",",
"min_temporal_res",
":",
"Optional",
"[",
"str",
"]",
"=",
"None",
")",
":",
"for",
"node",
"in",
"self",
".",
"nodes",
"(",
"data",
"=",
"True",
")",
":",
"query_... | 35.8 | 0.001813 |
def vcf_writer(parser, keep, extract, args):
"""Writes the data in VCF format."""
# The output
output = sys.stdout if args.output == "-" else open(args.output, "w")
try:
# Getting the samples
samples = np.array(parser.get_samples(), dtype=str)
k = _get_sample_select(samples=samp... | [
"def",
"vcf_writer",
"(",
"parser",
",",
"keep",
",",
"extract",
",",
"args",
")",
":",
"# The output",
"output",
"=",
"sys",
".",
"stdout",
"if",
"args",
".",
"output",
"==",
"\"-\"",
"else",
"open",
"(",
"args",
".",
"output",
",",
"\"w\"",
")",
"t... | 32.346154 | 0.000577 |
def _wrapper_find_one(self, filter_=None, *args, **kwargs):
"""Convert record to a dict that has no key error
"""
return self.__collect.find_one(filter_, *args, **kwargs) | [
"def",
"_wrapper_find_one",
"(",
"self",
",",
"filter_",
"=",
"None",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"return",
"self",
".",
"__collect",
".",
"find_one",
"(",
"filter_",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")"
] | 47.75 | 0.010309 |
def reverse(
self,
query,
exactly_one=DEFAULT_SENTINEL,
timeout=DEFAULT_SENTINEL,
feature_code=None,
lang=None,
find_nearby_type='findNearbyPlaceName',
):
"""
Return an address by location point.
.. vers... | [
"def",
"reverse",
"(",
"self",
",",
"query",
",",
"exactly_one",
"=",
"DEFAULT_SENTINEL",
",",
"timeout",
"=",
"DEFAULT_SENTINEL",
",",
"feature_code",
"=",
"None",
",",
"lang",
"=",
"None",
",",
"find_nearby_type",
"=",
"'findNearbyPlaceName'",
",",
")",
":",... | 39.686275 | 0.001928 |
async def run_handler(self, request: RPCRequest) -> Union[RPCReply, RPCError]:
"""
Process a JSON RPC request
:param RPCRequest request: JSON RPC request
:return: JSON RPC reply
"""
with catch_warnings(record=True) as warnings:
try:
rpc_handle... | [
"async",
"def",
"run_handler",
"(",
"self",
",",
"request",
":",
"RPCRequest",
")",
"->",
"Union",
"[",
"RPCReply",
",",
"RPCError",
"]",
":",
"with",
"catch_warnings",
"(",
"record",
"=",
"True",
")",
"as",
"warnings",
":",
"try",
":",
"rpc_handler",
"=... | 38.029412 | 0.002262 |
def current(self):
"""Returns the current (token, position) or (EndOfFile, EndOfFile)"""
if self.index >= self.len:
self._fill((self.index - self.len) + 1)
return self.index < self.len and self.buffer[self.index] or (EndOfFile, EndOfFile) | [
"def",
"current",
"(",
"self",
")",
":",
"if",
"self",
".",
"index",
">=",
"self",
".",
"len",
":",
"self",
".",
"_fill",
"(",
"(",
"self",
".",
"index",
"-",
"self",
".",
"len",
")",
"+",
"1",
")",
"return",
"self",
".",
"index",
"<",
"self",
... | 54 | 0.010949 |
def split_docstring(value):
"""
Splits the docstring of the given value into it's summary and body.
:returns: a 2-tuple of the format ``(summary, body)``
"""
docstring = textwrap.dedent(getattr(value, '__doc__', ''))
if not docstring:
return None
pieces = docstring.strip().split('\... | [
"def",
"split_docstring",
"(",
"value",
")",
":",
"docstring",
"=",
"textwrap",
".",
"dedent",
"(",
"getattr",
"(",
"value",
",",
"'__doc__'",
",",
"''",
")",
")",
"if",
"not",
"docstring",
":",
"return",
"None",
"pieces",
"=",
"docstring",
".",
"strip",... | 25.176471 | 0.002252 |
def cmbuild_from_alignment(aln, structure_string, refine=False, \
return_alignment=False,params=None):
"""Uses cmbuild to build a CM file given an alignment and structure string.
- aln: an Alignment object or something that can be used to construct
one. All sequences must be the same lengt... | [
"def",
"cmbuild_from_alignment",
"(",
"aln",
",",
"structure_string",
",",
"refine",
"=",
"False",
",",
"return_alignment",
"=",
"False",
",",
"params",
"=",
"None",
")",
":",
"aln",
"=",
"Alignment",
"(",
"aln",
")",
"if",
"len",
"(",
"structure_string",
... | 39.672414 | 0.009754 |
def get_abbreviation_of(self, name):
"""Get abbreviation of a language."""
for language in self.user_data.languages:
if language['language_string'] == name:
return language['language']
return None | [
"def",
"get_abbreviation_of",
"(",
"self",
",",
"name",
")",
":",
"for",
"language",
"in",
"self",
".",
"user_data",
".",
"languages",
":",
"if",
"language",
"[",
"'language_string'",
"]",
"==",
"name",
":",
"return",
"language",
"[",
"'language'",
"]",
"r... | 40.5 | 0.008065 |
def pull(image,
insecure_registry=False,
api_response=False,
client_timeout=salt.utils.docker.CLIENT_TIMEOUT):
'''
.. versionchanged:: 2018.3.0
If no tag is specified in the ``image`` argument, all tags for the
image will be pulled. For this reason is it recommended to... | [
"def",
"pull",
"(",
"image",
",",
"insecure_registry",
"=",
"False",
",",
"api_response",
"=",
"False",
",",
"client_timeout",
"=",
"salt",
".",
"utils",
".",
"docker",
".",
"CLIENT_TIMEOUT",
")",
":",
"_prep_pull",
"(",
")",
"kwargs",
"=",
"{",
"'stream'"... | 30.680412 | 0.000326 |
def __parse_entry(entry_line):
"""Parse the SOFT file entry name line that starts with '^', '!' or '#'.
Args:
entry_line (:obj:`str`): Line from SOFT to be parsed.
Returns:
:obj:`2-tuple`: Type of entry, value of entry.
"""
if entry_line.startswith("!"):
entry_line = sub(... | [
"def",
"__parse_entry",
"(",
"entry_line",
")",
":",
"if",
"entry_line",
".",
"startswith",
"(",
"\"!\"",
")",
":",
"entry_line",
"=",
"sub",
"(",
"r\"!\\w*?_\"",
",",
"''",
",",
"entry_line",
")",
"else",
":",
"entry_line",
"=",
"entry_line",
".",
"strip"... | 31 | 0.001565 |
def __calculate_changes(self, updated_centers):
"""!
@brief Calculate changes between centers.
@return (float) Maximum change between centers.
"""
changes = numpy.sum(numpy.square(self.__centers - updated_centers), axis=1).T
return numpy.max(changes) | [
"def",
"__calculate_changes",
"(",
"self",
",",
"updated_centers",
")",
":",
"changes",
"=",
"numpy",
".",
"sum",
"(",
"numpy",
".",
"square",
"(",
"self",
".",
"__centers",
"-",
"updated_centers",
")",
",",
"axis",
"=",
"1",
")",
".",
"T",
"return",
"... | 33.333333 | 0.00974 |
def purge_existing_ovb(nova_api, neutron):
"""Purge any trace of an existing OVB deployment.
"""
LOG.info('Cleaning up OVB environment from the tenant.')
for server in nova_api.servers.list():
if server.name in ('bmc', 'undercloud'):
server.delete()
if server.name.startswith(... | [
"def",
"purge_existing_ovb",
"(",
"nova_api",
",",
"neutron",
")",
":",
"LOG",
".",
"info",
"(",
"'Cleaning up OVB environment from the tenant.'",
")",
"for",
"server",
"in",
"nova_api",
".",
"servers",
".",
"list",
"(",
")",
":",
"if",
"server",
".",
"name",
... | 45.339286 | 0.001928 |
def optplot(modes=('absorption',), filenames=None, prefix=None, directory=None,
gaussian=None, band_gaps=None, labels=None, average=True, height=6,
width=6, xmin=0, xmax=None, ymin=0, ymax=1e5, colours=None,
style=None, no_base_style=None,
image_format='pdf', dpi=400, plt... | [
"def",
"optplot",
"(",
"modes",
"=",
"(",
"'absorption'",
",",
")",
",",
"filenames",
"=",
"None",
",",
"prefix",
"=",
"None",
",",
"directory",
"=",
"None",
",",
"gaussian",
"=",
"None",
",",
"band_gaps",
"=",
"None",
",",
"labels",
"=",
"None",
","... | 47.480315 | 0.000325 |
def in6_get_common_plen(a, b):
"""
Return common prefix length of IPv6 addresses a and b.
"""
def matching_bits(byte1, byte2):
for i in range(8):
cur_mask = 0x80 >> i
if (byte1 & cur_mask) != (byte2 & cur_mask):
return i
return 8
tmpA = inet_p... | [
"def",
"in6_get_common_plen",
"(",
"a",
",",
"b",
")",
":",
"def",
"matching_bits",
"(",
"byte1",
",",
"byte2",
")",
":",
"for",
"i",
"in",
"range",
"(",
"8",
")",
":",
"cur_mask",
"=",
"0x80",
">>",
"i",
"if",
"(",
"byte1",
"&",
"cur_mask",
")",
... | 28.888889 | 0.001862 |
def if_features(self, stmt: Statement, mid: ModuleId) -> bool:
"""Evaluate ``if-feature`` substatements on a statement, if any.
Args:
stmt: Yang statement that is tested on if-features.
mid: Identifier of the module in which `stmt` is present.
Raises:
Module... | [
"def",
"if_features",
"(",
"self",
",",
"stmt",
":",
"Statement",
",",
"mid",
":",
"ModuleId",
")",
"->",
"bool",
":",
"iffs",
"=",
"stmt",
".",
"find_all",
"(",
"\"if-feature\"",
")",
"if",
"not",
"iffs",
":",
"return",
"True",
"for",
"i",
"in",
"if... | 38.666667 | 0.002404 |
def make_common_parser():
"""
Creates an argument parser (argparse module) with the options that should
be common to all shells.
The result can be used as a parent parser (``parents`` argument in
``argparse.ArgumentParser``)
:return: An ArgumentParser object
"""
parser = argparse.Argum... | [
"def",
"make_common_parser",
"(",
")",
":",
"parser",
"=",
"argparse",
".",
"ArgumentParser",
"(",
"add_help",
"=",
"False",
")",
"# Version number",
"parser",
".",
"add_argument",
"(",
"\"--version\"",
",",
"action",
"=",
"\"version\"",
",",
"version",
"=",
"... | 26.423077 | 0.000468 |
def _remote_connection(server, opts, argparser_):
"""Initiate a remote connection, via PyWBEM. Arguments for
the request are part of the command line arguments and include
user name, password, namespace, etc.
"""
global CONN # pylint: disable=global-statement
if opts.timeout is not N... | [
"def",
"_remote_connection",
"(",
"server",
",",
"opts",
",",
"argparser_",
")",
":",
"global",
"CONN",
"# pylint: disable=global-statement",
"if",
"opts",
".",
"timeout",
"is",
"not",
"None",
":",
"if",
"opts",
".",
"timeout",
"<",
"0",
"or",
"opts",
".",
... | 33.608696 | 0.000419 |
def block(self, userId, minute):
"""
封禁用户方法(每秒钟限 100 次) 方法
@param userId:用户 Id。(必传)
@param minute:封禁时长,单位为分钟,最大值为43200分钟。(必传)
@return code:返回码,200 为正常。
@return errorMessage:错误信息。
"""
desc = {
"name": "CodeSuccessReslut",
"desc": ... | [
"def",
"block",
"(",
"self",
",",
"userId",
",",
"minute",
")",
":",
"desc",
"=",
"{",
"\"name\"",
":",
"\"CodeSuccessReslut\"",
",",
"\"desc\"",
":",
"\" http 成功返回结果\",",
"",
"\"fields\"",
":",
"[",
"{",
"\"name\"",
":",
"\"code\"",
",",
"\"type\"",
":",
... | 28.793103 | 0.00927 |
def genrows(cursor: Cursor, arraysize: int = 1000) \
-> Generator[List[Any], None, None]:
"""
Generate all rows from a cursor.
Args:
cursor: the cursor
arraysize: split fetches into chunks of this many records
Yields:
each row
"""
# http://code.activestate.com/r... | [
"def",
"genrows",
"(",
"cursor",
":",
"Cursor",
",",
"arraysize",
":",
"int",
"=",
"1000",
")",
"->",
"Generator",
"[",
"List",
"[",
"Any",
"]",
",",
"None",
",",
"None",
"]",
":",
"# http://code.activestate.com/recipes/137270-use-generators-for-fetching-large-db-... | 28.052632 | 0.001815 |
def rotate(compound, theta, around):
"""Rotate a compound around an arbitrary vector.
Parameters
----------
compound : mb.Compound
The compound being rotated.
theta : float
The angle by which to rotate the compound, in radians.
around : np.ndarray, shape=(3,), dtype=float
... | [
"def",
"rotate",
"(",
"compound",
",",
"theta",
",",
"around",
")",
":",
"around",
"=",
"np",
".",
"asarray",
"(",
"around",
")",
".",
"reshape",
"(",
"3",
")",
"if",
"np",
".",
"array_equal",
"(",
"around",
",",
"np",
".",
"zeros",
"(",
"3",
")"... | 35.210526 | 0.001456 |
def path_param(name, ns):
"""
Build a path parameter definition.
"""
if ns.identifier_type == "uuid":
param_type = "string"
param_format = "uuid"
else:
param_type = "string"
param_format = None
kwargs = {
"name": name,
"in": "path",
"requ... | [
"def",
"path_param",
"(",
"name",
",",
"ns",
")",
":",
"if",
"ns",
".",
"identifier_type",
"==",
"\"uuid\"",
":",
"param_type",
"=",
"\"string\"",
"param_format",
"=",
"\"uuid\"",
"else",
":",
"param_type",
"=",
"\"string\"",
"param_format",
"=",
"None",
"kw... | 21.857143 | 0.002088 |
def zambretti_code(params, hourly_data):
"""Simple implementation of Zambretti forecaster algorithm.
Inspired by beteljuice.com Java algorithm, as converted to Python by
honeysucklecottage.me.uk, and further information
from http://www.meteormetrics.com/zambretti.htm"""
north = literal_eval(params.g... | [
"def",
"zambretti_code",
"(",
"params",
",",
"hourly_data",
")",
":",
"north",
"=",
"literal_eval",
"(",
"params",
".",
"get",
"(",
"'Zambretti'",
",",
"'north'",
",",
"'True'",
")",
")",
"baro_upper",
"=",
"float",
"(",
"params",
".",
"get",
"(",
"'Zamb... | 40.446429 | 0.001293 |
def replySocket(self, port, host='*'):
'''
Create a REP-style socket for servers
'''
try:
socket = self._context.socket(zmq.REP)
socket.bind(self.tcpAddress(host, port))
except Exception as e:
newMsg= str("%s %s:%d" % (str(e), host, port))
... | [
"def",
"replySocket",
"(",
"self",
",",
"port",
",",
"host",
"=",
"'*'",
")",
":",
"try",
":",
"socket",
"=",
"self",
".",
"_context",
".",
"socket",
"(",
"zmq",
".",
"REP",
")",
"socket",
".",
"bind",
"(",
"self",
".",
"tcpAddress",
"(",
"host",
... | 33 | 0.008043 |
def _module_iterator(root, recursive=True):
"""Iterate over modules."""
yield root
stack = collections.deque((root,))
while stack:
package = stack.popleft()
# The '__path__' attribute of a package might return a list of paths if
# the package is referenced as a namespace.
... | [
"def",
"_module_iterator",
"(",
"root",
",",
"recursive",
"=",
"True",
")",
":",
"yield",
"root",
"stack",
"=",
"collections",
".",
"deque",
"(",
"(",
"root",
",",
")",
")",
"while",
"stack",
":",
"package",
"=",
"stack",
".",
"popleft",
"(",
")",
"#... | 38.692308 | 0.00097 |
def replace_pattern(pattern,
repl,
count=0,
flags=8,
bufsize=1,
append_if_not_found=False,
prepend_if_not_found=False,
not_found_content=None,
search_only=False... | [
"def",
"replace_pattern",
"(",
"pattern",
",",
"repl",
",",
"count",
"=",
"0",
",",
"flags",
"=",
"8",
",",
"bufsize",
"=",
"1",
",",
"append_if_not_found",
"=",
"False",
",",
"prepend_if_not_found",
"=",
"False",
",",
"not_found_content",
"=",
"None",
","... | 41.156028 | 0.001178 |
def read_k2sff_lightcurve(lcfits):
'''This reads a K2 SFF (Vandenberg+ 2014) light curve into an `lcdict`.
Use this with the light curves from the K2 SFF project at MAST.
Parameters
----------
lcfits : str
The filename of the FITS light curve file downloaded from MAST.
Returns
--... | [
"def",
"read_k2sff_lightcurve",
"(",
"lcfits",
")",
":",
"# read the fits file",
"hdulist",
"=",
"pyfits",
".",
"open",
"(",
"lcfits",
")",
"lchdr",
",",
"lcdata",
"=",
"hdulist",
"[",
"1",
"]",
".",
"header",
",",
"hdulist",
"[",
"1",
"]",
".",
"data",
... | 33.315385 | 0.012108 |
def _query(self, request, filter=None):
""" Build a query based on the filter and the request params,
and send the query to the database. """
limit = None
offset = None
if 'maxfeatures' in request.params:
limit = int(request.params['maxfeatures'])
if 'limi... | [
"def",
"_query",
"(",
"self",
",",
"request",
",",
"filter",
"=",
"None",
")",
":",
"limit",
"=",
"None",
"offset",
"=",
"None",
"if",
"'maxfeatures'",
"in",
"request",
".",
"params",
":",
"limit",
"=",
"int",
"(",
"request",
".",
"params",
"[",
"'ma... | 42.666667 | 0.002183 |
def invalid_characters(self, text):
"""Give simple list of invalid characters present in text."""
return ''.join(sorted(set([c for c in text if c not in self.alphabet]))) | [
"def",
"invalid_characters",
"(",
"self",
",",
"text",
")",
":",
"return",
"''",
".",
"join",
"(",
"sorted",
"(",
"set",
"(",
"[",
"c",
"for",
"c",
"in",
"text",
"if",
"c",
"not",
"in",
"self",
".",
"alphabet",
"]",
")",
")",
")"
] | 61.333333 | 0.016129 |
def usb(self, state):
"""Sets the monsoon's USB passthrough mode. This is specific to the
USB port in front of the monsoon box which connects to the powered
device, NOT the USB that is used to talk to the monsoon itself.
"Off" means USB always off.
"On" means USB always on.
... | [
"def",
"usb",
"(",
"self",
",",
"state",
")",
":",
"state_lookup",
"=",
"{",
"\"off\"",
":",
"0",
",",
"\"on\"",
":",
"1",
",",
"\"auto\"",
":",
"2",
"}",
"state",
"=",
"state",
".",
"lower",
"(",
")",
"if",
"state",
"in",
"state_lookup",
":",
"c... | 39.384615 | 0.001907 |
def __bind(self):
'''
Binds the reply server
'''
if self.log_queue is not None:
salt.log.setup.set_multiprocessing_logging_queue(self.log_queue)
if self.log_queue_level is not None:
salt.log.setup.set_multiprocessing_logging_level(self.log_queue_level)
... | [
"def",
"__bind",
"(",
"self",
")",
":",
"if",
"self",
".",
"log_queue",
"is",
"not",
"None",
":",
"salt",
".",
"log",
".",
"setup",
".",
"set_multiprocessing_logging_queue",
"(",
"self",
".",
"log_queue",
")",
"if",
"self",
".",
"log_queue_level",
"is",
... | 48.064516 | 0.001973 |
def to_native_units(self, motor):
"""
Return the native speed measurement required to achieve desired rotations-per-minute
"""
assert abs(self.rotations_per_minute) <= motor.max_rpm,\
"invalid rotations-per-minute: {} max RPM is {}, {} was requested".format(
motor... | [
"def",
"to_native_units",
"(",
"self",
",",
"motor",
")",
":",
"assert",
"abs",
"(",
"self",
".",
"rotations_per_minute",
")",
"<=",
"motor",
".",
"max_rpm",
",",
"\"invalid rotations-per-minute: {} max RPM is {}, {} was requested\"",
".",
"format",
"(",
"motor",
",... | 53.625 | 0.009174 |
def get_char_weights(doc_weighted_spans, preserve_density=None):
# type: (DocWeightedSpans, Optional[bool]) -> np.ndarray
""" Return character weights for a text document with highlighted features.
If preserve_density is True, then color for longer fragments will be
less intensive than for shorter fragm... | [
"def",
"get_char_weights",
"(",
"doc_weighted_spans",
",",
"preserve_density",
"=",
"None",
")",
":",
"# type: (DocWeightedSpans, Optional[bool]) -> np.ndarray",
"if",
"preserve_density",
"is",
"None",
":",
"preserve_density",
"=",
"doc_weighted_spans",
".",
"preserve_density... | 50.772727 | 0.000879 |
def send_buffered_messages(self):
"""Send messages in out_stream to the Stream Manager"""
while not self.out_stream.is_empty() and self._stmgr_client.is_registered:
tuple_set = self.out_stream.poll()
if isinstance(tuple_set, tuple_pb2.HeronTupleSet):
tuple_set.src_task_id = self.my_pplan_hel... | [
"def",
"send_buffered_messages",
"(",
"self",
")",
":",
"while",
"not",
"self",
".",
"out_stream",
".",
"is_empty",
"(",
")",
"and",
"self",
".",
"_stmgr_client",
".",
"is_registered",
":",
"tuple_set",
"=",
"self",
".",
"out_stream",
".",
"poll",
"(",
")"... | 55.75 | 0.00883 |
def add_dependency(self, p_from_todo, p_to_todo):
""" Adds a dependency from task 1 to task 2. """
def find_next_id():
"""
Find a new unused ID.
Unused means that no task has it as an 'id' value or as a 'p'
value.
"""
def id_exists(... | [
"def",
"add_dependency",
"(",
"self",
",",
"p_from_todo",
",",
"p_to_todo",
")",
":",
"def",
"find_next_id",
"(",
")",
":",
"\"\"\"\n Find a new unused ID.\n Unused means that no task has it as an 'id' value or as a 'p'\n value.\n \"\"\"",
... | 35.448276 | 0.000947 |
def fit(self, X, y, **kwargs):
"""
Fits the learning curve with the wrapped model to the specified data.
Draws training and test score curves and saves the scores to the
estimator.
Parameters
----------
X : array-like, shape (n_samples, n_features)
Tr... | [
"def",
"fit",
"(",
"self",
",",
"X",
",",
"y",
",",
"*",
"*",
"kwargs",
")",
":",
"self",
".",
"cv_scores_",
"=",
"cross_val_score",
"(",
"self",
".",
"estimator",
",",
"X",
",",
"y",
",",
"cv",
"=",
"self",
".",
"cv",
",",
"scoring",
"=",
"sel... | 30.275862 | 0.002208 |
def iter_configurations(kafka_topology_base_path=None):
"""Cluster topology iterator.
Iterate over all the topologies available in config.
"""
if not kafka_topology_base_path:
config_dirs = get_conf_dirs()
else:
config_dirs = [kafka_topology_base_path]
types = set()
for conf... | [
"def",
"iter_configurations",
"(",
"kafka_topology_base_path",
"=",
"None",
")",
":",
"if",
"not",
"kafka_topology_base_path",
":",
"config_dirs",
"=",
"get_conf_dirs",
"(",
")",
"else",
":",
"config_dirs",
"=",
"[",
"kafka_topology_base_path",
"]",
"types",
"=",
... | 32.2 | 0.001206 |
def _get_default_value_to_cache(self, xblock):
"""
Perform special logic to provide a field's default value for caching.
"""
try:
# pylint: disable=protected-access
return self.from_json(xblock._field_data.default(xblock, self.name))
except KeyError:
... | [
"def",
"_get_default_value_to_cache",
"(",
"self",
",",
"xblock",
")",
":",
"try",
":",
"# pylint: disable=protected-access",
"return",
"self",
".",
"from_json",
"(",
"xblock",
".",
"_field_data",
".",
"default",
"(",
"xblock",
",",
"self",
".",
"name",
")",
"... | 40.5 | 0.008048 |
def determine_scale(scale, img, mark):
"""
Scales an image using a specified ratio, 'F' or 'R'. If `scale` is
'F', the image is scaled to be as big as possible to fit in `img`
without falling off the edges. If `scale` is 'R', the watermark
resizes to a percentage of minimum size of source image. R... | [
"def",
"determine_scale",
"(",
"scale",
",",
"img",
",",
"mark",
")",
":",
"if",
"scale",
":",
"try",
":",
"scale",
"=",
"float",
"(",
"scale",
")",
"except",
"(",
"ValueError",
",",
"TypeError",
")",
":",
"pass",
"if",
"isinstance",
"(",
"scale",
",... | 40.95122 | 0.002327 |
def list_outbox_faxes(self, **kwargs): # noqa: E501
"""Get outbox records # noqa: E501
Get outbox fax records information # noqa: E501
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please pass async=True
>>> thread = api.list_o... | [
"def",
"list_outbox_faxes",
"(",
"self",
",",
"*",
"*",
"kwargs",
")",
":",
"# noqa: E501",
"kwargs",
"[",
"'_return_http_data_only'",
"]",
"=",
"True",
"if",
"kwargs",
".",
"get",
"(",
"'async'",
")",
":",
"return",
"self",
".",
"list_outbox_faxes_with_http_i... | 40.85 | 0.002392 |
def __calculate_nearest_distance(self, index_cluster1, index_cluster2):
"""!
@brief Finds two nearest objects in two specified clusters and returns distance between them.
@param[in] (uint) Index of the first cluster.
@param[in] (uint) Index of the second cluster.
... | [
"def",
"__calculate_nearest_distance",
"(",
"self",
",",
"index_cluster1",
",",
"index_cluster2",
")",
":",
"candidate_minimum_distance",
"=",
"float",
"(",
"'Inf'",
")",
"for",
"index_object1",
"in",
"self",
".",
"__clusters",
"[",
"index_cluster1",
"]",
":",
"fo... | 45.789474 | 0.01464 |
def tensorrt_bind(symbol, ctx, all_params, type_dict=None, stype_dict=None, group2ctx=None,
**kwargs):
"""Bind current symbol to get an optimized trt executor.
Parameters
----------
symbol : Symbol
The symbol you wish to bind, and optimize with TensorRT.
ctx : Context
... | [
"def",
"tensorrt_bind",
"(",
"symbol",
",",
"ctx",
",",
"all_params",
",",
"type_dict",
"=",
"None",
",",
"stype_dict",
"=",
"None",
",",
"group2ctx",
"=",
"None",
",",
"*",
"*",
"kwargs",
")",
":",
"kwargs",
"[",
"'shared_buffer'",
"]",
"=",
"all_params... | 32.114286 | 0.001727 |
async def fetchone(self):
""" Fetch next row """
self._check_executed()
row = await self._read_next()
if row is None:
return
self._rownumber += 1
return row | [
"async",
"def",
"fetchone",
"(",
"self",
")",
":",
"self",
".",
"_check_executed",
"(",
")",
"row",
"=",
"await",
"self",
".",
"_read_next",
"(",
")",
"if",
"row",
"is",
"None",
":",
"return",
"self",
".",
"_rownumber",
"+=",
"1",
"return",
"row"
] | 26.125 | 0.009259 |
def _set_scores(self):
"""
Compute anomaly scores for the time series
This algorithm just takes the diff of threshold with current value as anomaly score
"""
anom_scores = {}
for timestamp, value in self.time_series.items():
anom_scores[timestamp] = 0.0
... | [
"def",
"_set_scores",
"(",
"self",
")",
":",
"anom_scores",
"=",
"{",
"}",
"for",
"timestamp",
",",
"value",
"in",
"self",
".",
"time_series",
".",
"items",
"(",
")",
":",
"anom_scores",
"[",
"timestamp",
"]",
"=",
"0.0",
"if",
"self",
".",
"absolute_t... | 57.230769 | 0.009259 |
def retrieve_file_from_RCSB(http_connection, resource, silent = True):
'''Retrieve a file from the RCSB.'''
if not silent:
colortext.printf("Retrieving %s from RCSB" % os.path.split(resource)[1], color = "aqua")
return http_connection.get(resource) | [
"def",
"retrieve_file_from_RCSB",
"(",
"http_connection",
",",
"resource",
",",
"silent",
"=",
"True",
")",
":",
"if",
"not",
"silent",
":",
"colortext",
".",
"printf",
"(",
"\"Retrieving %s from RCSB\"",
"%",
"os",
".",
"path",
".",
"split",
"(",
"resource",
... | 52.8 | 0.022388 |
def is_nash(self, action_profile, tol=None):
"""
Return True if `action_profile` is a Nash equilibrium.
Parameters
----------
action_profile : array_like(int or array_like(float))
An array of N objects, where each object must be an integer
(pure action) o... | [
"def",
"is_nash",
"(",
"self",
",",
"action_profile",
",",
"tol",
"=",
"None",
")",
":",
"if",
"self",
".",
"N",
"==",
"2",
":",
"for",
"i",
",",
"player",
"in",
"enumerate",
"(",
"self",
".",
"players",
")",
":",
"own_action",
",",
"opponent_action"... | 35.755556 | 0.00121 |
def find_file(path, filename, max_depth=5):
"""Returns full filepath if the file is in path or a subdirectory."""
for root, dirs, files in os.walk(path):
if filename in files:
return os.path.join(root, filename)
# Don't search past max_depth
depth = root[len(path) + 1:].count(os.sep)
if depth... | [
"def",
"find_file",
"(",
"path",
",",
"filename",
",",
"max_depth",
"=",
"5",
")",
":",
"for",
"root",
",",
"dirs",
",",
"files",
"in",
"os",
".",
"walk",
"(",
"path",
")",
":",
"if",
"filename",
"in",
"files",
":",
"return",
"os",
".",
"path",
"... | 33.545455 | 0.015831 |
def connect(
self, login, password, authz_id=b"", starttls=False,
authmech=None):
"""Establish a connection with the server.
This function must be used. It read the server capabilities
and wraps calls to STARTTLS and AUTHENTICATE commands.
:param login: username... | [
"def",
"connect",
"(",
"self",
",",
"login",
",",
"password",
",",
"authz_id",
"=",
"b\"\"",
",",
"starttls",
"=",
"False",
",",
"authmech",
"=",
"None",
")",
":",
"try",
":",
"self",
".",
"sock",
"=",
"socket",
".",
"create_connection",
"(",
"(",
"s... | 38.074074 | 0.001898 |
def get_ca_signed_key(ca_name,
CN='localhost',
as_text=False,
cacert_path=None,
key_filename=None):
'''
Get the certificate path or content
ca_name
name of the CA
CN
common name of the certificate
... | [
"def",
"get_ca_signed_key",
"(",
"ca_name",
",",
"CN",
"=",
"'localhost'",
",",
"as_text",
"=",
"False",
",",
"cacert_path",
"=",
"None",
",",
"key_filename",
"=",
"None",
")",
":",
"set_ca_path",
"(",
"cacert_path",
")",
"if",
"not",
"key_filename",
":",
... | 26.404255 | 0.000777 |
def set_default_command(self, command):
"""Sets a command function as the default command."""
cmd_name = command.name
self.add_command(command)
self.default_cmd_name = cmd_name | [
"def",
"set_default_command",
"(",
"self",
",",
"command",
")",
":",
"cmd_name",
"=",
"command",
".",
"name",
"self",
".",
"add_command",
"(",
"command",
")",
"self",
".",
"default_cmd_name",
"=",
"cmd_name"
] | 40.8 | 0.009615 |
def collapse_segments (path):
"""Remove all redundant segments from the given URL path.
Precondition: path is an unquoted url path"""
# replace backslashes
# note: this is _against_ the specification (which would require
# backslashes to be left alone, and finally quoted with '%5C')
# But replac... | [
"def",
"collapse_segments",
"(",
"path",
")",
":",
"# replace backslashes",
"# note: this is _against_ the specification (which would require",
"# backslashes to be left alone, and finally quoted with '%5C')",
"# But replacing has several positive effects:",
"# - Prevents path attacks on Windows... | 43.870968 | 0.001439 |
def set_profiling_level(self, level, slow_ms=None, session=None):
"""Set the database's profiling level.
:Parameters:
- `level`: Specifies a profiling level, see list of possible values
below.
- `slow_ms`: Optionally modify the threshold for the profile to
co... | [
"def",
"set_profiling_level",
"(",
"self",
",",
"level",
",",
"slow_ms",
"=",
"None",
",",
"session",
"=",
"None",
")",
":",
"if",
"not",
"isinstance",
"(",
"level",
",",
"int",
")",
"or",
"level",
"<",
"0",
"or",
"level",
">",
"2",
":",
"raise",
"... | 45.255814 | 0.001006 |
def plot_spectrum(self, filename=None, plot_db=True):
""" Do a (slow) numpy FFT and take power of data """
header, data = self.read_next_data_block()
print("Computing FFT...")
d_xx_fft = np.abs(np.fft.fft(data[..., 0]))
d_xx_fft = d_xx_fft.flatten()
# Rebin to max numbe... | [
"def",
"plot_spectrum",
"(",
"self",
",",
"filename",
"=",
"None",
",",
"plot_db",
"=",
"True",
")",
":",
"header",
",",
"data",
"=",
"self",
".",
"read_next_data_block",
"(",
")",
"print",
"(",
"\"Computing FFT...\"",
")",
"d_xx_fft",
"=",
"np",
".",
"a... | 30.777778 | 0.002334 |
def select(cls, *args, **kwargs):
"""Support read slaves."""
query = super(Model, cls).select(*args, **kwargs)
query.database = cls._get_read_database()
return query | [
"def",
"select",
"(",
"cls",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"query",
"=",
"super",
"(",
"Model",
",",
"cls",
")",
".",
"select",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
"query",
".",
"database",
"=",
"cls",
".",
... | 38.6 | 0.010152 |
def _iter_ns_range(self):
"""Iterates over self._ns_range, delegating to self._iter_key_range()."""
while True:
if self._current_key_range is None:
query = self._ns_range.make_datastore_query()
namespace_result = query.Get(1)
if not namespace_result:
break
namesp... | [
"def",
"_iter_ns_range",
"(",
"self",
")",
":",
"while",
"True",
":",
"if",
"self",
".",
"_current_key_range",
"is",
"None",
":",
"query",
"=",
"self",
".",
"_ns_range",
".",
"make_datastore_query",
"(",
")",
"namespace_result",
"=",
"query",
".",
"Get",
"... | 37.740741 | 0.008612 |
def _print(self, *args):
""" internal print to self.fobj """
string = u" ".join(args) + '\n'
self.fobj.write(string) | [
"def",
"_print",
"(",
"self",
",",
"*",
"args",
")",
":",
"string",
"=",
"u\" \"",
".",
"join",
"(",
"args",
")",
"+",
"'\\n'",
"self",
".",
"fobj",
".",
"write",
"(",
"string",
")"
] | 34.25 | 0.014286 |
def run(self):
"""Runs the build extension."""
compiler = new_compiler(compiler=self.compiler)
if compiler.compiler_type == "msvc":
self.define = [
("UNICODE", ""),
]
else:
command = "sh configure --disable-shared-libs"
output = self._RunCommand(command)
print_l... | [
"def",
"run",
"(",
"self",
")",
":",
"compiler",
"=",
"new_compiler",
"(",
"compiler",
"=",
"self",
".",
"compiler",
")",
"if",
"compiler",
".",
"compiler_type",
"==",
"\"msvc\"",
":",
"self",
".",
"define",
"=",
"[",
"(",
"\"UNICODE\"",
",",
"\"\"",
"... | 22.888889 | 0.013975 |
def field_specific_errors(self):
"""Returns a dictionary of field-specific validation errors for this row."""
return {
key: value for key, value in self.error_dict.items()
if key != NON_FIELD_ERRORS
} | [
"def",
"field_specific_errors",
"(",
"self",
")",
":",
"return",
"{",
"key",
":",
"value",
"for",
"key",
",",
"value",
"in",
"self",
".",
"error_dict",
".",
"items",
"(",
")",
"if",
"key",
"!=",
"NON_FIELD_ERRORS",
"}"
] | 40.5 | 0.012097 |
def randtuple(self):
""" -> a #tuple of random #int """
return tuple(
self.randint
for x in range(0, self.random.randint(3, 10))) | [
"def",
"randtuple",
"(",
"self",
")",
":",
"return",
"tuple",
"(",
"self",
".",
"randint",
"for",
"x",
"in",
"range",
"(",
"0",
",",
"self",
".",
"random",
".",
"randint",
"(",
"3",
",",
"10",
")",
")",
")"
] | 33 | 0.011834 |
def start_engines(opts, proc_mgr, proxy=None):
'''
Fire up the configured engines!
'''
utils = salt.loader.utils(opts, proxy=proxy)
if opts['__role'] == 'master':
runners = salt.loader.runner(opts, utils=utils)
else:
runners = []
funcs = salt.loader.minion_mods(opts, utils=ut... | [
"def",
"start_engines",
"(",
"opts",
",",
"proc_mgr",
",",
"proxy",
"=",
"None",
")",
":",
"utils",
"=",
"salt",
".",
"loader",
".",
"utils",
"(",
"opts",
",",
"proxy",
"=",
"proxy",
")",
"if",
"opts",
"[",
"'__role'",
"]",
"==",
"'master'",
":",
"... | 36.482759 | 0.00046 |
def submit(self, fn, *args, **kwargs):
"""Submit an operation"""
corofn = asyncio.coroutine(lambda: fn(*args, **kwargs))
return run_coroutine_threadsafe(corofn(), self.loop) | [
"def",
"submit",
"(",
"self",
",",
"fn",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"corofn",
"=",
"asyncio",
".",
"coroutine",
"(",
"lambda",
":",
"fn",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
")",
"return",
"run_coroutine_thread... | 48.5 | 0.010152 |
def get_formatted_content(self, pyobj):
'''typecode data --> text
'''
u = urlencode(pyobj, self.reserved)
return String.get_formatted_content(self,
u) | [
"def",
"get_formatted_content",
"(",
"self",
",",
"pyobj",
")",
":",
"u",
"=",
"urlencode",
"(",
"pyobj",
",",
"self",
".",
"reserved",
")",
"return",
"String",
".",
"get_formatted_content",
"(",
"self",
",",
"u",
")"
] | 31.666667 | 0.020513 |
def rename(self, new_relation):
"""Rename this cached relation to new_relation.
Note that this will change the output of key(), all refs must be
updated!
:param _CachedRelation new_relation: The new name to apply to the
relation
"""
# Relations store this stu... | [
"def",
"rename",
"(",
"self",
",",
"new_relation",
")",
":",
"# Relations store this stuff inside their `path` dict. But they",
"# also store a table_name, and usually use it in their .render(),",
"# so we need to update that as well. It doesn't appear that",
"# table_name is ever anything bu... | 43.3 | 0.00226 |
def delete(self):
"""Get rid of this, starting now.
Apart from deleting the node, this also informs all its users
that it doesn't exist and therefore can't be their avatar
anymore.
"""
if self.name in self.character.portal:
del self.character.portal[self.nam... | [
"def",
"delete",
"(",
"self",
")",
":",
"if",
"self",
".",
"name",
"in",
"self",
".",
"character",
".",
"portal",
":",
"del",
"self",
".",
"character",
".",
"portal",
"[",
"self",
".",
"name",
"]",
"if",
"self",
".",
"name",
"in",
"self",
".",
"c... | 37.5 | 0.002 |
def schedule_in(self, job, timedelta):
""" Schedule job to run at datetime.timedelta from now."""
now = long(self._now() * 1e6)
when = now + timedelta.total_seconds() * 1e6
self.schedule(job, when) | [
"def",
"schedule_in",
"(",
"self",
",",
"job",
",",
"timedelta",
")",
":",
"now",
"=",
"long",
"(",
"self",
".",
"_now",
"(",
")",
"*",
"1e6",
")",
"when",
"=",
"now",
"+",
"timedelta",
".",
"total_seconds",
"(",
")",
"*",
"1e6",
"self",
".",
"sc... | 45 | 0.008734 |
async def _rank_text(self, choices):
"""
Try to match the TextLayer with choice's intents.
"""
tl = self.request.get_layer(l.RawText)
best = 0.0
for slug, params in choices.items():
strings = []
if params['intent']:
intent = geta... | [
"async",
"def",
"_rank_text",
"(",
"self",
",",
"choices",
")",
":",
"tl",
"=",
"self",
".",
"request",
".",
"get_layer",
"(",
"l",
".",
"RawText",
")",
"best",
"=",
"0.0",
"for",
"slug",
",",
"params",
"in",
"choices",
".",
"items",
"(",
")",
":",... | 29.714286 | 0.002328 |
def update_validators():
"""
Call this to updade the global nrml.validators
"""
validators.update({
'fragilityFunction.id': valid.utf8, # taxonomy
'vulnerabilityFunction.id': valid.utf8, # taxonomy
'consequenceFunction.id': valid.utf8, # taxonomy
'asset.id': valid.asse... | [
"def",
"update_validators",
"(",
")",
":",
"validators",
".",
"update",
"(",
"{",
"'fragilityFunction.id'",
":",
"valid",
".",
"utf8",
",",
"# taxonomy",
"'vulnerabilityFunction.id'",
":",
"valid",
".",
"utf8",
",",
"# taxonomy",
"'consequenceFunction.id'",
":",
"... | 41.203704 | 0.000439 |
def _split_fit_score_trial(self, X, y, idx=0):
"""
Splits the dataset, fits a clone of the estimator, then scores it
according to the required metrics.
The index of the split is added to the random_state if the
random_state is not None; this ensures that every split is shuffled
... | [
"def",
"_split_fit_score_trial",
"(",
"self",
",",
"X",
",",
"y",
",",
"idx",
"=",
"0",
")",
":",
"random_state",
"=",
"self",
".",
"random_state",
"if",
"random_state",
"is",
"not",
"None",
":",
"random_state",
"+=",
"idx",
"splitter",
"=",
"self",
".",... | 39.25 | 0.001657 |
def response(credentials, password, request):
"""Compile digest auth response
If the qop directive's value is "auth" or "auth-int" , then compute the response as follows:
RESPONSE = MD5(HA1:nonce:nonceCount:clienNonce:qop:HA2)
Else if the qop directive is unspecified, then compute the response as fo... | [
"def",
"response",
"(",
"credentials",
",",
"password",
",",
"request",
")",
":",
"response",
"=",
"None",
"algorithm",
"=",
"credentials",
".",
"get",
"(",
"'algorithm'",
")",
"HA1_value",
"=",
"HA1",
"(",
"credentials",
".",
"get",
"(",
"'realm'",
")",
... | 39.738095 | 0.002339 |
def iter_extensions(prefix, event_id):
"""Return extension (prefix + event_id) with an optional suffix which is
incremented step by step in case of collision
"""
extension = '{prefix}{event_id}'.format(prefix=prefix, event_id=event_id)
yield extension
suffix = 1
while True:
yield ... | [
"def",
"iter_extensions",
"(",
"prefix",
",",
"event_id",
")",
":",
"extension",
"=",
"'{prefix}{event_id}'",
".",
"format",
"(",
"prefix",
"=",
"prefix",
",",
"event_id",
"=",
"event_id",
")",
"yield",
"extension",
"suffix",
"=",
"1",
"while",
"True",
":",
... | 39.5 | 0.002475 |
def _get_file(self, path, prepend=False):
'''Extracts a file from dap to a file-like object'''
if prepend:
path = os.path.join(self._dirname(), path)
extracted = self._tar.extractfile(path)
if extracted:
return extracted
raise DapFileError(('Could not read... | [
"def",
"_get_file",
"(",
"self",
",",
"path",
",",
"prepend",
"=",
"False",
")",
":",
"if",
"prepend",
":",
"path",
"=",
"os",
".",
"path",
".",
"join",
"(",
"self",
".",
"_dirname",
"(",
")",
",",
"path",
")",
"extracted",
"=",
"self",
".",
"_ta... | 47.777778 | 0.009132 |
def _dens(self,R,z,phi=0.,t=0.):
"""
NAME:
_dens
PURPOSE:
evaluate the density for this potential
INPUT:
R - Galactocentric cylindrical radius
z - vertical height
phi - azimuth
t - time
OUTPUT:
the densi... | [
"def",
"_dens",
"(",
"self",
",",
"R",
",",
"z",
",",
"phi",
"=",
"0.",
",",
"t",
"=",
"0.",
")",
":",
"r",
"=",
"nu",
".",
"sqrt",
"(",
"R",
"**",
"2.",
"+",
"z",
"**",
"2.",
")",
"return",
"1.",
"/",
"r",
"**",
"self",
".",
"alpha",
"... | 26 | 0.014433 |
def gru(num_hidden, indata, prev_state, param, seqidx, layeridx, dropout=0., is_batchnorm=False, gamma=None, beta=None, name=None):
"""
GRU Cell symbol
Reference:
* Chung, Junyoung, et al. "Empirical evaluation of gated recurrent neural
networks on sequence modeling." arXiv preprint arXiv:1412.3... | [
"def",
"gru",
"(",
"num_hidden",
",",
"indata",
",",
"prev_state",
",",
"param",
",",
"seqidx",
",",
"layeridx",
",",
"dropout",
"=",
"0.",
",",
"is_batchnorm",
"=",
"False",
",",
"gamma",
"=",
"None",
",",
"beta",
"=",
"None",
",",
"name",
"=",
"Non... | 54.130435 | 0.002367 |
def posterior(self, x, Sigma=None):
"""Posterior for model: X1, ..., Xn ~ N(theta, Sigma).
Parameters
----------
x: (n, d) ndarray
data
Sigma: (d, d) ndarray
(fixed) covariance matrix in the model
"""
n = x.shape[0]
Sigma... | [
"def",
"posterior",
"(",
"self",
",",
"x",
",",
"Sigma",
"=",
"None",
")",
":",
"n",
"=",
"x",
".",
"shape",
"[",
"0",
"]",
"Sigma",
"=",
"np",
".",
"eye",
"(",
"self",
".",
"dim",
")",
"if",
"Sigma",
"is",
"None",
"else",
"Sigma",
"Siginv",
... | 33.555556 | 0.009662 |
def user_present(name,
password,
email,
tenant=None,
enabled=True,
roles=None,
profile=None,
password_reset=True,
project=None,
**connection_args):
'''
Ensure ... | [
"def",
"user_present",
"(",
"name",
",",
"password",
",",
"email",
",",
"tenant",
"=",
"None",
",",
"enabled",
"=",
"True",
",",
"roles",
"=",
"None",
",",
"profile",
"=",
"None",
",",
"password_reset",
"=",
"True",
",",
"project",
"=",
"None",
",",
... | 40.691542 | 0.001193 |
def retry(*dargs, **dkwargs):
"""
The retry decorator. Can be passed all the arguments that are accepted by
Retry.__init__.
"""
# support both @retry and @retry() as valid syntax
if len(dargs) == 1 and callable(dargs[0]):
def wrap_simple(f):
@_wraps(f)
def wrappe... | [
"def",
"retry",
"(",
"*",
"dargs",
",",
"*",
"*",
"dkwargs",
")",
":",
"# support both @retry and @retry() as valid syntax",
"if",
"len",
"(",
"dargs",
")",
"==",
"1",
"and",
"callable",
"(",
"dargs",
"[",
"0",
"]",
")",
":",
"def",
"wrap_simple",
"(",
"... | 23.592593 | 0.001508 |
def deployment_delete(name, resource_group, **kwargs):
'''
.. versionadded:: 2019.2.0
Delete a deployment.
:param name: The name of the deployment to delete.
:param resource_group: The resource group name assigned to the
deployment.
CLI Example:
.. code-block:: bash
sal... | [
"def",
"deployment_delete",
"(",
"name",
",",
"resource_group",
",",
"*",
"*",
"kwargs",
")",
":",
"result",
"=",
"False",
"resconn",
"=",
"__utils__",
"[",
"'azurearm.get_client'",
"]",
"(",
"'resource'",
",",
"*",
"*",
"kwargs",
")",
"try",
":",
"deploy"... | 24.709677 | 0.001256 |
def bind_to(self, table, name):
"""
Bind this column to a table, and assign it a name. This method
can only be called once per instance, because a Column cannot be
bound to multiple tables. (The sort order would be ambiguous.)
"""
if self.bound_to is not None:
... | [
"def",
"bind_to",
"(",
"self",
",",
"table",
",",
"name",
")",
":",
"if",
"self",
".",
"bound_to",
"is",
"not",
"None",
":",
"raise",
"AttributeError",
"(",
"\"Column is already bound to '%s' as '%s'\"",
"%",
"self",
".",
"bound_to",
")",
"self",
".",
"bound... | 38.833333 | 0.008386 |
def get_driver_script_catalog(name): # noqa: E501
"""Retrieve the script catalog
Retrieve the script catalog # noqa: E501
:param name: Get status of a driver with this name
:type name: str
:rtype: Response
"""
response = errorIfUnauthorized(role='user')
if response:
return r... | [
"def",
"get_driver_script_catalog",
"(",
"name",
")",
":",
"# noqa: E501",
"response",
"=",
"errorIfUnauthorized",
"(",
"role",
"=",
"'user'",
")",
"if",
"response",
":",
"return",
"response",
"else",
":",
"response",
"=",
"ApitaxResponse",
"(",
")",
"driver",
... | 24.181818 | 0.001808 |
def percent_pareto_durations(records, percentage=0.8):
"""
The percentage of user's contacts that account for 80% of its total time
spend on the phone. Optionally takes a percentage argument as a decimal
(e.g., .8 for 80%).
"""
if len(records) == 0:
return None
user_count = defaultd... | [
"def",
"percent_pareto_durations",
"(",
"records",
",",
"percentage",
"=",
"0.8",
")",
":",
"if",
"len",
"(",
"records",
")",
"==",
"0",
":",
"return",
"None",
"user_count",
"=",
"defaultdict",
"(",
"int",
")",
"for",
"r",
"in",
"records",
":",
"if",
"... | 33.909091 | 0.001304 |
def lines_to_path(lines):
"""
Turn line segments into a Path2D or Path3D object.
Parameters
------------
lines : (n, 2, dimension) or (n, dimension) float
Line segments or connected polyline curve in 2D or 3D
Returns
-----------
kwargs : dict
kwargs for Path constructor
... | [
"def",
"lines_to_path",
"(",
"lines",
")",
":",
"lines",
"=",
"np",
".",
"asanyarray",
"(",
"lines",
",",
"dtype",
"=",
"np",
".",
"float64",
")",
"if",
"util",
".",
"is_shape",
"(",
"lines",
",",
"(",
"-",
"1",
",",
"(",
"2",
",",
"3",
")",
")... | 35.783784 | 0.000735 |
def get_project(self, project_id):
""" http://confluence.jetbrains.net/display/YTD2/GET+project
"""
return youtrack.Project(self._get("/admin/project/" + urlquote(project_id)), self) | [
"def",
"get_project",
"(",
"self",
",",
"project_id",
")",
":",
"return",
"youtrack",
".",
"Project",
"(",
"self",
".",
"_get",
"(",
"\"/admin/project/\"",
"+",
"urlquote",
"(",
"project_id",
")",
")",
",",
"self",
")"
] | 50.75 | 0.014563 |
def list_download_tasks(self, need_task_info="1", asc="0", start=0, create_time=None, limit=1000, status="255",
source_url=None, remote_path=None, **kwargs):
"""查询离线下载任务ID列表及任务信息.
:param need_task_info: 是否需要返回任务信息:
* 0:不需要
... | [
"def",
"list_download_tasks",
"(",
"self",
",",
"need_task_info",
"=",
"\"1\"",
",",
"asc",
"=",
"\"0\"",
",",
"start",
"=",
"0",
",",
"create_time",
"=",
"None",
",",
"limit",
"=",
"1000",
",",
"status",
"=",
"\"255\"",
",",
"source_url",
"=",
"None",
... | 27.536082 | 0.001807 |
def simpleAttrs(self):
"""provide a copy of this player's attributes as a dictionary, but with objects flattened into a string representation of the object"""
simpleAttrs = {}
for k,v in iteritems(self.attrs):
if k in ["_matches"]: continue # attributes to specifically ignore
... | [
"def",
"simpleAttrs",
"(",
"self",
")",
":",
"simpleAttrs",
"=",
"{",
"}",
"for",
"k",
",",
"v",
"in",
"iteritems",
"(",
"self",
".",
"attrs",
")",
":",
"if",
"k",
"in",
"[",
"\"_matches\"",
"]",
":",
"continue",
"# attributes to specifically ignore",
"t... | 51.875 | 0.021327 |
def job_listener(event):
'''Listens to completed job'''
job_id = event.job.args[0]
if event.code == events.EVENT_JOB_MISSED:
db.mark_job_as_missed(job_id)
elif event.exception:
if isinstance(event.exception, util.JobError):
error_object = event.exception.as_dict()
el... | [
"def",
"job_listener",
"(",
"event",
")",
":",
"job_id",
"=",
"event",
".",
"job",
".",
"args",
"[",
"0",
"]",
"if",
"event",
".",
"code",
"==",
"events",
".",
"EVENT_JOB_MISSED",
":",
"db",
".",
"mark_job_as_missed",
"(",
"job_id",
")",
"elif",
"event... | 34.68 | 0.002245 |
def endure(self, key, persist_to=-1, replicate_to=-1, cas=0,
check_removed=False, timeout=5.0, interval=0.010):
"""Wait until a key has been distributed to one or more nodes
By default, when items are stored to Couchbase, the operation is
considered successful if the vBucket mast... | [
"def",
"endure",
"(",
"self",
",",
"key",
",",
"persist_to",
"=",
"-",
"1",
",",
"replicate_to",
"=",
"-",
"1",
",",
"cas",
"=",
"0",
",",
"check_removed",
"=",
"False",
",",
"timeout",
"=",
"5.0",
",",
"interval",
"=",
"0.010",
")",
":",
"# We rea... | 50.301205 | 0.000705 |
def oom_components(Ct, C2t, rank_ind=None, lcc=None, tol_one=1e-2):
"""
Compute OOM components and eigenvalues from count matrices:
Parameters
----------
Ct : ndarray(N, N)
count matrix from data
C2t : sparse csc-matrix (N*N, N)
two-step count matrix from data for all states, co... | [
"def",
"oom_components",
"(",
"Ct",
",",
"C2t",
",",
"rank_ind",
"=",
"None",
",",
"lcc",
"=",
"None",
",",
"tol_one",
"=",
"1e-2",
")",
":",
"import",
"msmtools",
".",
"estimation",
"as",
"me",
"# Decompose count matrix by SVD:",
"if",
"lcc",
"is",
"not",... | 31.025 | 0.001171 |
def assertFileSizeNotAlmostEqual(
self, filename, size, places=None, msg=None, delta=None):
'''Fail unless ``filename`` does not have the given ``size``
as determined by their difference rounded to the given number
ofdecimal ``places`` (default 7) and comparing to zero, or if
... | [
"def",
"assertFileSizeNotAlmostEqual",
"(",
"self",
",",
"filename",
",",
"size",
",",
"places",
"=",
"None",
",",
"msg",
"=",
"None",
",",
"delta",
"=",
"None",
")",
":",
"fsize",
"=",
"self",
".",
"_get_file_size",
"(",
"filename",
")",
"self",
".",
... | 35.961538 | 0.002083 |
def makeLeu(segID, N, CA, C, O, geo):
'''Creates a Leucine residue'''
##R-Group
CA_CB_length=geo.CA_CB_length
C_CA_CB_angle=geo.C_CA_CB_angle
N_C_CA_CB_diangle=geo.N_C_CA_CB_diangle
CB_CG_length=geo.CB_CG_length
CA_CB_CG_angle= geo.CA_CB_CG_angle
N_CA_CB_CG_diangle=geo.N_CA_CB_CG_diangl... | [
"def",
"makeLeu",
"(",
"segID",
",",
"N",
",",
"CA",
",",
"C",
",",
"O",
",",
"geo",
")",
":",
"##R-Group",
"CA_CB_length",
"=",
"geo",
".",
"CA_CB_length",
"C_CA_CB_angle",
"=",
"geo",
".",
"C_CA_CB_angle",
"N_C_CA_CB_diangle",
"=",
"geo",
".",
"N_C_CA_... | 36.153846 | 0.02279 |
def insertRnaQuantificationSet(self, rnaQuantificationSet):
"""
Inserts a the specified rnaQuantificationSet into this repository.
"""
try:
models.Rnaquantificationset.create(
id=rnaQuantificationSet.getId(),
datasetid=rnaQuantificationSet.getP... | [
"def",
"insertRnaQuantificationSet",
"(",
"self",
",",
"rnaQuantificationSet",
")",
":",
"try",
":",
"models",
".",
"Rnaquantificationset",
".",
"create",
"(",
"id",
"=",
"rnaQuantificationSet",
".",
"getId",
"(",
")",
",",
"datasetid",
"=",
"rnaQuantificationSet"... | 50.1875 | 0.002445 |
def result(self, timeout=None):
"""Gets the result of the task.
Arguments:
timeout: Maximum seconds to wait for a result before raising a
TimeoutError. If set to None, this will wait forever. If the
queue doesn't store results and timeout is None, this call w... | [
"def",
"result",
"(",
"self",
",",
"timeout",
"=",
"None",
")",
":",
"start",
"=",
"time",
".",
"time",
"(",
")",
"while",
"True",
":",
"task",
"=",
"self",
".",
"get_task",
"(",
")",
"if",
"not",
"task",
"or",
"task",
".",
"status",
"not",
"in",... | 33.375 | 0.002427 |
def _generate_notebooks(table, timestamp_column,
engine, crypto_factory, min_dt, max_dt, logger):
"""
See docstrings for `generate_files` and `generate_checkpoints`.
Parameters
----------
table : SQLAlchemy.Table
Table to fetch notebooks from, `files` or `remote_chec... | [
"def",
"_generate_notebooks",
"(",
"table",
",",
"timestamp_column",
",",
"engine",
",",
"crypto_factory",
",",
"min_dt",
",",
"max_dt",
",",
"logger",
")",
":",
"where_conds",
"=",
"[",
"]",
"if",
"min_dt",
"is",
"not",
"None",
":",
"where_conds",
".",
"a... | 40.641791 | 0.000359 |
def asHdl(cls, obj, ctx: HwtSerializerCtx):
"""
Convert object to HDL string
:param obj: object to serialize
:param ctx: HwtSerializerCtx instance
"""
if isinstance(obj, RtlSignalBase):
return cls.SignalItem(obj, ctx)
elif isinstance(obj, Value):
... | [
"def",
"asHdl",
"(",
"cls",
",",
"obj",
",",
"ctx",
":",
"HwtSerializerCtx",
")",
":",
"if",
"isinstance",
"(",
"obj",
",",
"RtlSignalBase",
")",
":",
"return",
"cls",
".",
"SignalItem",
"(",
"obj",
",",
"ctx",
")",
"elif",
"isinstance",
"(",
"obj",
... | 29.25 | 0.002364 |
def forward_word_end_extend_selection(self, e): #
u"""Move forward to the end of the next word. Words are composed of
letters and digits."""
self.l_buffer.forward_word_end_extend_selection(self.argument_reset)
self.finalize() | [
"def",
"forward_word_end_extend_selection",
"(",
"self",
",",
"e",
")",
":",
"# \r",
"self",
".",
"l_buffer",
".",
"forward_word_end_extend_selection",
"(",
"self",
".",
"argument_reset",
")",
"self",
".",
"finalize",
"(",
")"
] | 51.6 | 0.015267 |
def prepare(_next, self):
"""Hook after prepare and set 'portrait' as image widget to
``self.form``.
"""
_next(self)
if not self.portrait_support:
return
model = self.model
request = self.request
if request.has_permission('edit_user', model.par... | [
"def",
"prepare",
"(",
"_next",
",",
"self",
")",
":",
"_next",
"(",
"self",
")",
"if",
"not",
"self",
".",
"portrait_support",
":",
"return",
"model",
"=",
"self",
".",
"model",
"request",
"=",
"self",
".",
"request",
"if",
"request",
".",
"has_permis... | 37.5625 | 0.001081 |
def get_all_invitations(self, **kwargs): # noqa: E501
"""Get the details of all the user invitations. # noqa: E501
An endpoint for retrieving the details of all the active user invitations sent for new or existing users to join the account. **Example usage:** `curl https://api.us-east-1.mbedcloud.c... | [
"def",
"get_all_invitations",
"(",
"self",
",",
"*",
"*",
"kwargs",
")",
":",
"# noqa: E501",
"kwargs",
"[",
"'_return_http_data_only'",
"]",
"=",
"True",
"if",
"kwargs",
".",
"get",
"(",
"'asynchronous'",
")",
":",
"return",
"self",
".",
"get_all_invitations_... | 58.521739 | 0.001462 |
def do_mailfy(self, query, **kwargs):
"""
Verifying a mailfy query in this platform.
This might be redefined in any class inheriting from Platform. The only
condition is that any of this should return an equivalent array.
Args:
-----
query: The element to be... | [
"def",
"do_mailfy",
"(",
"self",
",",
"query",
",",
"*",
"*",
"kwargs",
")",
":",
"if",
"self",
".",
"check_mailfy",
"(",
"query",
",",
"kwargs",
")",
":",
"expandedEntities",
"=",
"general",
".",
"expandEntitiesFromEmail",
"(",
"query",
")",
"r",
"=",
... | 31.672414 | 0.001584 |
def bounce_local(drain=False):
'''
Bounce Traffic Server on the local node. Bouncing Traffic Server shuts down
and immediately restarts the Traffic Server node.
drain
This option modifies the restart behavior such that traffic_server
is not shut down until the number of active client co... | [
"def",
"bounce_local",
"(",
"drain",
"=",
"False",
")",
":",
"if",
"_TRAFFICCTL",
":",
"cmd",
"=",
"_traffic_ctl",
"(",
"'server'",
",",
"'restart'",
")",
"else",
":",
"cmd",
"=",
"_traffic_line",
"(",
"'-b'",
")",
"if",
"drain",
":",
"cmd",
"=",
"cmd"... | 28.923077 | 0.001287 |
async def reportCompleted(self, *args, **kwargs):
"""
Report Run Completed
Report a task completed, resolving the run as `completed`.
This method gives output: ``v1/task-status-response.json#``
This method is ``stable``
"""
return await self._makeApiCall(self.... | [
"async",
"def",
"reportCompleted",
"(",
"self",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"return",
"await",
"self",
".",
"_makeApiCall",
"(",
"self",
".",
"funcinfo",
"[",
"\"reportCompleted\"",
"]",
",",
"*",
"args",
",",
"*",
"*",
"kwargs... | 29.5 | 0.008219 |
def download(self, storagemodel:object, modeldefinition = None):
""" load blob from storage into StorageBlobModelInstance """
if (storagemodel.name is None):
# No content to download
raise AzureStorageWrapException(storagemodel, "StorageBlobModel does not contain content nor con... | [
"def",
"download",
"(",
"self",
",",
"storagemodel",
":",
"object",
",",
"modeldefinition",
"=",
"None",
")",
":",
"if",
"(",
"storagemodel",
".",
"name",
"is",
"None",
")",
":",
"# No content to download",
"raise",
"AzureStorageWrapException",
"(",
"storagemode... | 45.32 | 0.009507 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.