text stringlengths 89 104k | code_tokens list | avg_line_len float64 7.91 980 | score float64 0 630 |
|---|---|---|---|
def render_html_attributes(**kwargs):
"""Returns a string representation of attributes for html entities
:param kwargs: attributes and values
:return: a well-formed string representation of attributes"""
attr = list()
if kwargs:
attr = ['{}="{}"'.format(key, val) for key, val in kwargs.items... | [
"def",
"render_html_attributes",
"(",
"*",
"*",
"kwargs",
")",
":",
"attr",
"=",
"list",
"(",
")",
"if",
"kwargs",
":",
"attr",
"=",
"[",
"'{}=\"{}\"'",
".",
"format",
"(",
"key",
",",
"val",
")",
"for",
"key",
",",
"val",
"in",
"kwargs",
".",
"ite... | 46.5 | 12.625 |
def validate(self, obj, pointer=None):
"""
Validate object against validator
:param obj: the object to validate
"""
pointer = pointer or '#'
validator = deepcopy(self)
validator.errors = []
validator.fail_fast = False
obj = deepcopy(obj)
... | [
"def",
"validate",
"(",
"self",
",",
"obj",
",",
"pointer",
"=",
"None",
")",
":",
"pointer",
"=",
"pointer",
"or",
"'#'",
"validator",
"=",
"deepcopy",
"(",
"self",
")",
"validator",
".",
"errors",
"=",
"[",
"]",
"validator",
".",
"fail_fast",
"=",
... | 40.204082 | 17.387755 |
def rmdir(self, target_directory, allow_symlink=False):
"""Remove a leaf Fake directory.
Args:
target_directory: (str) Name of directory to remove.
allow_symlink: (bool) if `target_directory` is a symlink,
the function just returns, otherwise it raises (Posix onl... | [
"def",
"rmdir",
"(",
"self",
",",
"target_directory",
",",
"allow_symlink",
"=",
"False",
")",
":",
"if",
"target_directory",
"in",
"(",
"b'.'",
",",
"u'.'",
")",
":",
"error_nr",
"=",
"errno",
".",
"EACCES",
"if",
"self",
".",
"is_windows_fs",
"else",
"... | 45.818182 | 20.878788 |
def fill_row(self, forward, items, idx, row, ro, ri, overlap,lengths):
"Fill the row with tokens from the ragged array. --OBS-- overlap != 1 has not been implemented"
ibuf = n = 0
ro -= 1
while ibuf < row.size:
ro += 1
ix = idx[ro]
rag = items[... | [
"def",
"fill_row",
"(",
"self",
",",
"forward",
",",
"items",
",",
"idx",
",",
"row",
",",
"ro",
",",
"ri",
",",
"overlap",
",",
"lengths",
")",
":",
"ibuf",
"=",
"n",
"=",
"0",
"ro",
"-=",
"1",
"while",
"ibuf",
"<",
"row",
".",
"size",
":",
... | 40.722222 | 18.277778 |
def multipart_parse_json(api_url, data):
"""
Send a post request and parse the JSON response (potentially containing
non-ascii characters).
@param api_url: the url endpoint to post to.
@param data: a dictionary that will be passed to requests.post
"""
headers = {'Content-Type': 'application/... | [
"def",
"multipart_parse_json",
"(",
"api_url",
",",
"data",
")",
":",
"headers",
"=",
"{",
"'Content-Type'",
":",
"'application/x-www-form-urlencoded'",
"}",
"response_text",
"=",
"requests",
".",
"post",
"(",
"api_url",
",",
"data",
"=",
"data",
",",
"headers",... | 41.583333 | 16.083333 |
def timeInfo(self):
"""Return the time info for this Map Service"""
time_info = self._json_struct.get('timeInfo', {})
if not time_info:
return None
time_info = time_info.copy()
if 'timeExtent' in time_info:
time_info['timeExtent'] = utils.timetopythonvalue... | [
"def",
"timeInfo",
"(",
"self",
")",
":",
"time_info",
"=",
"self",
".",
"_json_struct",
".",
"get",
"(",
"'timeInfo'",
",",
"{",
"}",
")",
"if",
"not",
"time_info",
":",
"return",
"None",
"time_info",
"=",
"time_info",
".",
"copy",
"(",
")",
"if",
"... | 41.4 | 15.1 |
def verify_schema(self, dataset_id, table_id, schema):
"""Indicate whether schemas match exactly
Compare the BigQuery table identified in the parameters with
the schema passed in and indicate whether all fields in the former
are present in the latter. Order is not considered.
P... | [
"def",
"verify_schema",
"(",
"self",
",",
"dataset_id",
",",
"table_id",
",",
"schema",
")",
":",
"fields_remote",
"=",
"self",
".",
"_clean_schema_fields",
"(",
"self",
".",
"schema",
"(",
"dataset_id",
",",
"table_id",
")",
")",
"fields_local",
"=",
"self"... | 30.931034 | 20.103448 |
def get_localized_property(context, field=None, language=None):
'''
When accessing to the name of the field itself, the value
in the current language will be returned. Unless it's set,
the value in the default language will be returned.
'''
if language:
return getattr(context, get_real_f... | [
"def",
"get_localized_property",
"(",
"context",
",",
"field",
"=",
"None",
",",
"language",
"=",
"None",
")",
":",
"if",
"language",
":",
"return",
"getattr",
"(",
"context",
",",
"get_real_fieldname",
"(",
"field",
",",
"language",
")",
")",
"if",
"hasat... | 34.125 | 20.041667 |
def append_result(self, results, num_matches):
"""Real-time update of search results"""
filename, lineno, colno, match_end, line = results
if filename not in self.files:
file_item = FileMatchItem(self, filename, self.sorting,
self.text_col... | [
"def",
"append_result",
"(",
"self",
",",
"results",
",",
"num_matches",
")",
":",
"filename",
",",
"lineno",
",",
"colno",
",",
"match_end",
",",
"line",
"=",
"results",
"if",
"filename",
"not",
"in",
"self",
".",
"files",
":",
"file_item",
"=",
"FileMa... | 40.137931 | 13.482759 |
def _read_eeprom(self, address, size):
'''Read EEPROM
'''
self._intf.write(self._base_addr + self.CAL_EEPROM_ADD, array('B', pack('>H', address & 0x3FFF))) # 14-bit address, 16384 bytes
n_pages, n_bytes = divmod(size, self.CAL_EEPROM_PAGE_SIZE)
data = array('B')
for _ i... | [
"def",
"_read_eeprom",
"(",
"self",
",",
"address",
",",
"size",
")",
":",
"self",
".",
"_intf",
".",
"write",
"(",
"self",
".",
"_base_addr",
"+",
"self",
".",
"CAL_EEPROM_ADD",
",",
"array",
"(",
"'B'",
",",
"pack",
"(",
"'>H'",
",",
"address",
"&"... | 41.714286 | 34.571429 |
def _extend_breaks(self, major):
"""
Append 2 extra breaks at either end of major
If breaks of transform space are non-equidistant,
:func:`minor_breaks` add minor breaks beyond the first
and last major breaks. The solutions is to extend those
breaks (in transformed space... | [
"def",
"_extend_breaks",
"(",
"self",
",",
"major",
")",
":",
"trans",
"=",
"self",
".",
"trans",
"trans",
"=",
"trans",
"if",
"isinstance",
"(",
"trans",
",",
"type",
")",
"else",
"trans",
".",
"__class__",
"# so far we are only certain about this extending stu... | 42.25 | 16.25 |
def keys(self, prefix=None, delimiter=None):
"""
:param prefix: NOT A STRING PREFIX, RATHER PATH ID PREFIX (MUST MATCH TO NEXT "." OR ":")
:param delimiter: TO GET Prefix OBJECTS, RATHER THAN WHOLE KEYS
:return: SET OF KEYS IN BUCKET, OR
"""
if delimiter:
# ... | [
"def",
"keys",
"(",
"self",
",",
"prefix",
"=",
"None",
",",
"delimiter",
"=",
"None",
")",
":",
"if",
"delimiter",
":",
"# WE REALLY DO NOT GET KEYS, BUT RATHER Prefix OBJECTS",
"# AT LEAST THEY ARE UNIQUE",
"candidates",
"=",
"[",
"k",
".",
"name",
".",
"rstrip"... | 49.411765 | 28 |
def _update_data(self, data):
# type: (Any) -> Dict[str, List]
"""Set our data and notify any subscribers of children what has changed
Args:
data (object): The new data
Returns:
dict: {child_name: [path_list, optional child_data]} of the change
t... | [
"def",
"_update_data",
"(",
"self",
",",
"data",
")",
":",
"# type: (Any) -> Dict[str, List]",
"self",
".",
"data",
"=",
"data",
"child_change_dict",
"=",
"{",
"}",
"# Reflect change of data to children",
"for",
"name",
"in",
"self",
".",
"children",
":",
"child_d... | 34.521739 | 15.130435 |
def allocate(n, dtype=numpy.float32):
""" allocate context-portable pinned host memory """
return drv.pagelocked_empty(int(n), dtype, order='C', mem_flags=drv.host_alloc_flags.PORTABLE) | [
"def",
"allocate",
"(",
"n",
",",
"dtype",
"=",
"numpy",
".",
"float32",
")",
":",
"return",
"drv",
".",
"pagelocked_empty",
"(",
"int",
"(",
"n",
")",
",",
"dtype",
",",
"order",
"=",
"'C'",
",",
"mem_flags",
"=",
"drv",
".",
"host_alloc_flags",
"."... | 63.666667 | 20.333333 |
def maelstrom(args):
"""Run the maelstrom method."""
infile = args.inputfile
genome = args.genome
outdir = args.outdir
pwmfile = args.pwmfile
methods = args.methods
ncpus = args.ncpus
if not os.path.exists(infile):
raise ValueError("file {} does not exist".format(infile))
... | [
"def",
"maelstrom",
"(",
"args",
")",
":",
"infile",
"=",
"args",
".",
"inputfile",
"genome",
"=",
"args",
".",
"genome",
"outdir",
"=",
"args",
".",
"outdir",
"pwmfile",
"=",
"args",
".",
"pwmfile",
"methods",
"=",
"args",
".",
"methods",
"ncpus",
"="... | 28.6875 | 21.25 |
def oauth_scope(*scope_names):
""" Return a decorator that restricts requests to those authorized with
a certain scope or scopes.
For example, to restrict access to a given endpoint like this:
.. code-block:: python
@require_login
def secret_attribute_endpoint(request, *args, **kwargs):
... | [
"def",
"oauth_scope",
"(",
"*",
"scope_names",
")",
":",
"authenticator",
"=",
"AccessTokenAuthenticator",
"(",
"required_scope_names",
"=",
"scope_names",
")",
"def",
"scope_decorator",
"(",
"view_func",
")",
":",
"@",
"wraps",
"(",
"view_func",
")",
"def",
"wr... | 34.436364 | 25.309091 |
def gen_weights(self, f_target):
"""Generate a set of weights over the basis functions such
that the target forcing term trajectory is matched.
f_target np.array: the desired forcing term trajectory
"""
# calculate x and psi
x_track = self.cs.rollout()
... | [
"def",
"gen_weights",
"(",
"self",
",",
"f_target",
")",
":",
"# calculate x and psi ",
"x_track",
"=",
"self",
".",
"cs",
".",
"rollout",
"(",
")",
"psi_track",
"=",
"self",
".",
"gen_psi",
"(",
"x_track",
")",
"#efficiently calculate weights for BFs using weig... | 40.25 | 15.15 |
def plot(self, format='segments', bits=None, **kwargs):
"""Plot the data for this `StateVector`
Parameters
----------
format : `str`, optional, default: ``'segments'``
The type of plot to make, either 'segments' to plot the
SegmentList for each bit, or 'timeserie... | [
"def",
"plot",
"(",
"self",
",",
"format",
"=",
"'segments'",
",",
"bits",
"=",
"None",
",",
"*",
"*",
"kwargs",
")",
":",
"if",
"format",
"==",
"'timeseries'",
":",
"return",
"super",
"(",
"StateVector",
",",
"self",
")",
".",
"plot",
"(",
"*",
"*... | 36.574468 | 18.531915 |
def encode(self, raw_string, add_eos=False):
"""Encodes a string into a list of int subtoken ids."""
ret = []
tokens = _split_string_to_tokens(_native_to_unicode(raw_string))
for token in tokens:
ret.extend(self._token_to_subtoken_ids(token))
if add_eos:
ret.append(EOS_ID)
return ret | [
"def",
"encode",
"(",
"self",
",",
"raw_string",
",",
"add_eos",
"=",
"False",
")",
":",
"ret",
"=",
"[",
"]",
"tokens",
"=",
"_split_string_to_tokens",
"(",
"_native_to_unicode",
"(",
"raw_string",
")",
")",
"for",
"token",
"in",
"tokens",
":",
"ret",
"... | 34.666667 | 17.222222 |
def block_create(
self,
type,
account,
wallet=None,
representative=None,
key=None,
destination=None,
amount=None,
balance=None,
previous=None,
source=None,
work=None,
):
"""
Creates a json representations... | [
"def",
"block_create",
"(",
"self",
",",
"type",
",",
"account",
",",
"wallet",
"=",
"None",
",",
"representative",
"=",
"None",
",",
"key",
"=",
"None",
",",
"destination",
"=",
"None",
",",
"amount",
"=",
"None",
",",
"balance",
"=",
"None",
",",
"... | 41.514451 | 30.057803 |
def _labeledInput(activeInputs, cellsPerCol=32):
"""Print the list of [column, cellIdx] indices for each of the active
cells in activeInputs.
"""
if cellsPerCol == 0:
cellsPerCol = 1
cols = activeInputs.size / cellsPerCol
activeInputs = activeInputs.reshape(cols, cellsPerCol)
(cols, cellIdxs) = active... | [
"def",
"_labeledInput",
"(",
"activeInputs",
",",
"cellsPerCol",
"=",
"32",
")",
":",
"if",
"cellsPerCol",
"==",
"0",
":",
"cellsPerCol",
"=",
"1",
"cols",
"=",
"activeInputs",
".",
"size",
"/",
"cellsPerCol",
"activeInputs",
"=",
"activeInputs",
".",
"resha... | 25.346154 | 16.807692 |
def IsCppString(line):
"""Does line terminate so, that the next symbol is in string constant.
This function does not consider single-line nor multi-line comments.
Args:
line: is a partial line of code starting from the 0..n.
Returns:
True, if next character appended to 'line' is inside a
string c... | [
"def",
"IsCppString",
"(",
"line",
")",
":",
"line",
"=",
"line",
".",
"replace",
"(",
"r'\\\\'",
",",
"'XX'",
")",
"# after this, \\\\\" does not match to \\\"",
"return",
"(",
"(",
"line",
".",
"count",
"(",
"'\"'",
")",
"-",
"line",
".",
"count",
"(",
... | 31.666667 | 26.666667 |
def combine(path1, path2):
# type: (Text, Text) -> Text
"""Join two paths together.
This is faster than :func:`~fs.path.join`, but only works when the
second path is relative, and there are no back references in either
path.
Arguments:
path1 (str): A PyFilesytem path.
path2 (st... | [
"def",
"combine",
"(",
"path1",
",",
"path2",
")",
":",
"# type: (Text, Text) -> Text",
"if",
"not",
"path1",
":",
"return",
"path2",
".",
"lstrip",
"(",
")",
"return",
"\"{}/{}\"",
".",
"format",
"(",
"path1",
".",
"rstrip",
"(",
"\"/\"",
")",
",",
"pat... | 24.304348 | 21.173913 |
def cancel_all_builds_in_group(self, id, **kwargs):
"""
Cancel all builds running in the build group
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please define a `callback` function
to be invoked when receiving the respon... | [
"def",
"cancel_all_builds_in_group",
"(",
"self",
",",
"id",
",",
"*",
"*",
"kwargs",
")",
":",
"kwargs",
"[",
"'_return_http_data_only'",
"]",
"=",
"True",
"if",
"kwargs",
".",
"get",
"(",
"'callback'",
")",
":",
"return",
"self",
".",
"cancel_all_builds_in... | 42.36 | 18.92 |
def generate_run_info():
"""
获取当前运行状态
"""
uptime = datetime.datetime.now() - datetime.datetime.fromtimestamp(glb.run_info.create_time())
memory_usage = glb.run_info.memory_info().rss
msg = '[当前时间] {now:%H:%M:%S}\n[运行时间] {uptime}\n[内存占用] {memory}\n[发送消息] {messages}'.format(
now=datetime.d... | [
"def",
"generate_run_info",
"(",
")",
":",
"uptime",
"=",
"datetime",
".",
"datetime",
".",
"now",
"(",
")",
"-",
"datetime",
".",
"datetime",
".",
"fromtimestamp",
"(",
"glb",
".",
"run_info",
".",
"create_time",
"(",
")",
")",
"memory_usage",
"=",
"glb... | 37.769231 | 19.615385 |
def _DeepCopy(self, obj):
"""Creates an object copy by serializing/deserializing it.
RDFStruct.Copy() doesn't deep-copy repeated fields which may lead to
hard to catch bugs.
Args:
obj: RDFValue to be copied.
Returns:
A deep copy of the passed RDFValue.
"""
precondition.AssertT... | [
"def",
"_DeepCopy",
"(",
"self",
",",
"obj",
")",
":",
"precondition",
".",
"AssertType",
"(",
"obj",
",",
"rdfvalue",
".",
"RDFValue",
")",
"return",
"obj",
".",
"__class__",
".",
"FromSerializedString",
"(",
"obj",
".",
"SerializeToString",
"(",
")",
")"... | 27 | 22.133333 |
def robust_init(stochclass, tries, *args, **kwds):
"""Robust initialization of a Stochastic.
If the evaluation of the log-probability returns a ZeroProbability
error, due for example to a parent being outside of the support for
this Stochastic, the values of parents are randomly sampled until
a val... | [
"def",
"robust_init",
"(",
"stochclass",
",",
"tries",
",",
"*",
"args",
",",
"*",
"*",
"kwds",
")",
":",
"# Find the direct parents",
"stochs",
"=",
"[",
"arg",
"for",
"arg",
"in",
"(",
"list",
"(",
"args",
")",
"+",
"list",
"(",
"kwds",
".",
"value... | 33.192308 | 21 |
def to_json(self):
"""
:return: str
"""
json_dict = self.to_json_basic()
json_dict['wday'] = self._wday
json_dict['hour'] = self._hour
json_dict['min'] = self._min
return json.dumps(json_dict) | [
"def",
"to_json",
"(",
"self",
")",
":",
"json_dict",
"=",
"self",
".",
"to_json_basic",
"(",
")",
"json_dict",
"[",
"'wday'",
"]",
"=",
"self",
".",
"_wday",
"json_dict",
"[",
"'hour'",
"]",
"=",
"self",
".",
"_hour",
"json_dict",
"[",
"'min'",
"]",
... | 27.666667 | 5.888889 |
def get_pixel(framebuf, x, y):
"""Get the color of a given pixel"""
index = (y >> 3) * framebuf.stride + x
offset = y & 0x07
return (framebuf.buf[index] >> offset) & 0x01 | [
"def",
"get_pixel",
"(",
"framebuf",
",",
"x",
",",
"y",
")",
":",
"index",
"=",
"(",
"y",
">>",
"3",
")",
"*",
"framebuf",
".",
"stride",
"+",
"x",
"offset",
"=",
"y",
"&",
"0x07",
"return",
"(",
"framebuf",
".",
"buf",
"[",
"index",
"]",
">>"... | 39.6 | 8.8 |
def name(self):
"""
The name for the window as displayed in the title bar and status bar.
"""
# Name, explicitely set for the pane.
if self.chosen_name:
return self.chosen_name
else:
# Name from the process running inside the pane.
name... | [
"def",
"name",
"(",
"self",
")",
":",
"# Name, explicitely set for the pane.",
"if",
"self",
".",
"chosen_name",
":",
"return",
"self",
".",
"chosen_name",
"else",
":",
"# Name from the process running inside the pane.",
"name",
"=",
"self",
".",
"process",
".",
"ge... | 29.928571 | 15.785714 |
def schedule(self):
"""Schedule the test items on the nodes
If the node's pending list is empty it is a new node which
needs to run all the tests. If the pending list is already
populated (by ``.add_node_collection()``) then it replaces a
dead node and we only need to run those... | [
"def",
"schedule",
"(",
"self",
")",
":",
"assert",
"self",
".",
"collection_is_completed",
"for",
"node",
",",
"pending",
"in",
"self",
".",
"node2pending",
".",
"items",
"(",
")",
":",
"if",
"node",
"in",
"self",
".",
"_started",
":",
"continue",
"if",... | 39.842105 | 14.473684 |
def populateFromFile(self, dataUrls, indexFiles):
"""
Populates this variant set using the specified lists of data
files and indexes. These must be in the same order, such that
the jth index file corresponds to the jth data file.
"""
assert len(dataUrls) == len(indexFiles... | [
"def",
"populateFromFile",
"(",
"self",
",",
"dataUrls",
",",
"indexFiles",
")",
":",
"assert",
"len",
"(",
"dataUrls",
")",
"==",
"len",
"(",
"indexFiles",
")",
"for",
"dataUrl",
",",
"indexFile",
"in",
"zip",
"(",
"dataUrls",
",",
"indexFiles",
")",
":... | 45.384615 | 18 |
def boundless_vrt_doc(
src_dataset, nodata=None, background=None, hidenodata=False,
width=None, height=None, transform=None, bands=None):
"""Make a VRT XML document.
Parameters
----------
src_dataset : Dataset
The dataset to wrap.
background : Dataset, optional
A data... | [
"def",
"boundless_vrt_doc",
"(",
"src_dataset",
",",
"nodata",
"=",
"None",
",",
"background",
"=",
"None",
",",
"hidenodata",
"=",
"False",
",",
"width",
"=",
"None",
",",
"height",
"=",
"None",
",",
"transform",
"=",
"None",
",",
"bands",
"=",
"None",
... | 46.85 | 25.45 |
def _enable_read_access(self):
"""! @brief Ensure flash is accessible by initing the algo for verify.
Not all flash memories are always accessible. For instance, external QSPI. Initing the
flash algo for the VERIFY operation is the canonical way to ensure that the flash is
memor... | [
"def",
"_enable_read_access",
"(",
"self",
")",
":",
"if",
"not",
"self",
".",
"algo_inited_for_read",
":",
"self",
".",
"flash",
".",
"init",
"(",
"self",
".",
"flash",
".",
"Operation",
".",
"VERIFY",
")",
"self",
".",
"algo_inited_for_read",
"=",
"True"... | 49.1 | 17.2 |
def heartbeat(self):
'''Record the current worker state in the registry.
This records the worker's current mode, plus the contents of
:meth:`environment`, in the data store for inspection by others.
:returns mode: Current mode, as :meth:`TaskMaster.get_mode`
'''
mode =... | [
"def",
"heartbeat",
"(",
"self",
")",
":",
"mode",
"=",
"self",
".",
"task_master",
".",
"get_mode",
"(",
")",
"self",
".",
"task_master",
".",
"worker_heartbeat",
"(",
"self",
".",
"worker_id",
",",
"mode",
",",
"self",
".",
"lifetime",
",",
"self",
"... | 39.857143 | 27 |
def read_info(self):
'''
:rtype: :class:`~kitty.data.data_manager.SessionInfo`
:return: current session info
'''
self.select('*')
row = self._cursor.fetchone()
if not row:
return None
info_d = self.row_to_dict(row)
return SessionInfo.fr... | [
"def",
"read_info",
"(",
"self",
")",
":",
"self",
".",
"select",
"(",
"'*'",
")",
"row",
"=",
"self",
".",
"_cursor",
".",
"fetchone",
"(",
")",
"if",
"not",
"row",
":",
"return",
"None",
"info_d",
"=",
"self",
".",
"row_to_dict",
"(",
"row",
")",... | 29.545455 | 15 |
def apply(self, function: "function", *cols, axis=1, **kwargs):
"""
Apply a function on columns values
:param function: a function to apply to the columns
:type function: function
:param cols: columns names
:type cols: name of columns
:param axis: index (0) or co... | [
"def",
"apply",
"(",
"self",
",",
"function",
":",
"\"function\"",
",",
"*",
"cols",
",",
"axis",
"=",
"1",
",",
"*",
"*",
"kwargs",
")",
":",
"try",
":",
"if",
"len",
"(",
"cols",
")",
"==",
"0",
":",
"self",
".",
"df",
"=",
"self",
".",
"df... | 34.741935 | 17.903226 |
def _get_cu_and_fu_status(self):
"""Submit GET request to update information."""
# adjust headers
headers = HEADERS.copy()
headers['Accept'] = '*/*'
headers['X-Requested-With'] = 'XMLHttpRequest'
headers['X-CSRFToken'] = self._parent.csrftoken
args = '?controller... | [
"def",
"_get_cu_and_fu_status",
"(",
"self",
")",
":",
"# adjust headers",
"headers",
"=",
"HEADERS",
".",
"copy",
"(",
")",
"headers",
"[",
"'Accept'",
"]",
"=",
"'*/*'",
"headers",
"[",
"'X-Requested-With'",
"]",
"=",
"'XMLHttpRequest'",
"headers",
"[",
"'X-... | 34.954545 | 14.727273 |
def only(self, *fields):
"""
Essentially, the opposite of defer. Only the fields passed into this
method and that are not already specified as deferred are loaded
immediately when the queryset is evaluated.
"""
clone = self._clone()
clone._fields=fields
re... | [
"def",
"only",
"(",
"self",
",",
"*",
"fields",
")",
":",
"clone",
"=",
"self",
".",
"_clone",
"(",
")",
"clone",
".",
"_fields",
"=",
"fields",
"return",
"clone"
] | 35.777778 | 15.333333 |
def ansi_len(string):
"""Extra length due to any ANSI sequences in the string."""
return len(string) - wcswidth(re.compile(r'\x1b[^m]*m').sub('', string)) | [
"def",
"ansi_len",
"(",
"string",
")",
":",
"return",
"len",
"(",
"string",
")",
"-",
"wcswidth",
"(",
"re",
".",
"compile",
"(",
"r'\\x1b[^m]*m'",
")",
".",
"sub",
"(",
"''",
",",
"string",
")",
")"
] | 53.333333 | 18.333333 |
def simulate(protocol_file,
propagate_logs=False,
log_level='warning') -> List[Mapping[str, Any]]:
"""
Simulate the protocol itself.
This is a one-stop function to simulate a protocol, whether python or json,
no matter the api version, from external (i.e. not bound up in other... | [
"def",
"simulate",
"(",
"protocol_file",
",",
"propagate_logs",
"=",
"False",
",",
"log_level",
"=",
"'warning'",
")",
"->",
"List",
"[",
"Mapping",
"[",
"str",
",",
"Any",
"]",
"]",
":",
"stack_logger",
"=",
"logging",
".",
"getLogger",
"(",
"'opentrons'"... | 46.291667 | 22.652778 |
def _compute_intensity(ccube, bexpcube):
""" Compute the intensity map
"""
bexp_data = np.sqrt(bexpcube.data[0:-1, 0:] * bexpcube.data[1:, 0:])
intensity_data = ccube.data / bexp_data
intensity_map = HpxMap(intensity_data, ccube.hpx)
return intensity_map | [
"def",
"_compute_intensity",
"(",
"ccube",
",",
"bexpcube",
")",
":",
"bexp_data",
"=",
"np",
".",
"sqrt",
"(",
"bexpcube",
".",
"data",
"[",
"0",
":",
"-",
"1",
",",
"0",
":",
"]",
"*",
"bexpcube",
".",
"data",
"[",
"1",
":",
",",
"0",
":",
"]... | 42.285714 | 10.285714 |
def from_ofxparse(data, institution):
"""Instantiate :py:class:`ofxclient.Account` subclass from ofxparse
module
:param data: an ofxparse account
:type data: An :py:class:`ofxparse.Account` object
:param institution: The parent institution of the account
:type institutio... | [
"def",
"from_ofxparse",
"(",
"data",
",",
"institution",
")",
":",
"description",
"=",
"data",
".",
"desc",
"if",
"hasattr",
"(",
"data",
",",
"'desc'",
")",
"else",
"None",
"if",
"data",
".",
"type",
"==",
"AccountType",
".",
"Bank",
":",
"return",
"B... | 41.166667 | 9.5 |
def get_yml_content(file_path):
'''Load yaml file content'''
try:
with open(file_path, 'r') as file:
return yaml.load(file, Loader=yaml.Loader)
except yaml.scanner.ScannerError as err:
print_error('yaml file format error!')
exit(1)
except Exception as exception:
... | [
"def",
"get_yml_content",
"(",
"file_path",
")",
":",
"try",
":",
"with",
"open",
"(",
"file_path",
",",
"'r'",
")",
"as",
"file",
":",
"return",
"yaml",
".",
"load",
"(",
"file",
",",
"Loader",
"=",
"yaml",
".",
"Loader",
")",
"except",
"yaml",
".",... | 31.909091 | 12.818182 |
def ensure_ndarray(ndarray_or_adjusted_array):
"""
Return the input as a numpy ndarray.
This is a no-op if the input is already an ndarray. If the input is an
adjusted_array, this extracts a read-only view of its internal data buffer.
Parameters
----------
ndarray_or_adjusted_array : nump... | [
"def",
"ensure_ndarray",
"(",
"ndarray_or_adjusted_array",
")",
":",
"if",
"isinstance",
"(",
"ndarray_or_adjusted_array",
",",
"ndarray",
")",
":",
"return",
"ndarray_or_adjusted_array",
"elif",
"isinstance",
"(",
"ndarray_or_adjusted_array",
",",
"AdjustedArray",
")",
... | 31.75 | 20.166667 |
def join_room(self, room_id_or_alias):
""" Join a room.
Args:
room_id_or_alias (str): Room ID or an alias.
Returns:
Room
Raises:
MatrixRequestError
"""
response = self.api.join_room(room_id_or_alias)
room_id = (
r... | [
"def",
"join_room",
"(",
"self",
",",
"room_id_or_alias",
")",
":",
"response",
"=",
"self",
".",
"api",
".",
"join_room",
"(",
"room_id_or_alias",
")",
"room_id",
"=",
"(",
"response",
"[",
"\"room_id\"",
"]",
"if",
"\"room_id\"",
"in",
"response",
"else",
... | 24.470588 | 21 |
async def _connect(self) -> "Connection":
"""Connect to the actual sqlite database."""
if self._connection is None:
self._connection = await self._execute(self._connector)
return self | [
"async",
"def",
"_connect",
"(",
"self",
")",
"->",
"\"Connection\"",
":",
"if",
"self",
".",
"_connection",
"is",
"None",
":",
"self",
".",
"_connection",
"=",
"await",
"self",
".",
"_execute",
"(",
"self",
".",
"_connector",
")",
"return",
"self"
] | 43 | 10.6 |
def from_url(cls, url):
"""
Construct a PostgresConfig from a URL.
"""
parsed = urlparse(url)
return cls(
username=parsed.username,
password=parsed.password,
hostname=parsed.hostname,
port=parsed.port,
database=parsed.pa... | [
"def",
"from_url",
"(",
"cls",
",",
"url",
")",
":",
"parsed",
"=",
"urlparse",
"(",
"url",
")",
"return",
"cls",
"(",
"username",
"=",
"parsed",
".",
"username",
",",
"password",
"=",
"parsed",
".",
"password",
",",
"hostname",
"=",
"parsed",
".",
"... | 35.0625 | 11.5625 |
def handle(self):
"""
Executes the actual Stratum program.
"""
self.output = PyStratumStyle(self.input, self.output)
command = self.get_application().find('constants')
ret = command.execute(self.input, self.output)
if ret:
return ret
command ... | [
"def",
"handle",
"(",
"self",
")",
":",
"self",
".",
"output",
"=",
"PyStratumStyle",
"(",
"self",
".",
"input",
",",
"self",
".",
"output",
")",
"command",
"=",
"self",
".",
"get_application",
"(",
")",
".",
"find",
"(",
"'constants'",
")",
"ret",
"... | 27.181818 | 20.727273 |
def align_cell(fmt, elem, width):
"""Returns an aligned element."""
if fmt == "<":
return elem + ' ' * (width - len(elem))
if fmt == ">":
return ' ' * (width - len(elem)) + elem
return elem | [
"def",
"align_cell",
"(",
"fmt",
",",
"elem",
",",
"width",
")",
":",
"if",
"fmt",
"==",
"\"<\"",
":",
"return",
"elem",
"+",
"' '",
"*",
"(",
"width",
"-",
"len",
"(",
"elem",
")",
")",
"if",
"fmt",
"==",
"\">\"",
":",
"return",
"' '",
"*",
"(... | 30.714286 | 12.857143 |
def version_tuple(self):
"""tuple[int]: version tuple or None if version is not set or invalid."""
try:
return tuple([int(digit, 10) for digit in self.version.split('.')])
except (AttributeError, TypeError, ValueError):
return None | [
"def",
"version_tuple",
"(",
"self",
")",
":",
"try",
":",
"return",
"tuple",
"(",
"[",
"int",
"(",
"digit",
",",
"10",
")",
"for",
"digit",
"in",
"self",
".",
"version",
".",
"split",
"(",
"'.'",
")",
"]",
")",
"except",
"(",
"AttributeError",
","... | 41.666667 | 19.166667 |
def draw_variable(loc, scale, shape, skewness, nsims):
""" Draws random variables from Skew t distribution
Parameters
----------
loc : float
location parameter for the distribution
scale : float
scale parameter for the distribution
shape : float... | [
"def",
"draw_variable",
"(",
"loc",
",",
"scale",
",",
"shape",
",",
"skewness",
",",
"nsims",
")",
":",
"return",
"loc",
"+",
"scale",
"*",
"Skewt",
".",
"rvs",
"(",
"shape",
",",
"skewness",
",",
"nsims",
")"
] | 26.92 | 20.84 |
def _set_mpls_interface(self, v, load=False):
"""
Setter method for mpls_interface, mapped from YANG variable /mpls_config/router/mpls/mpls_cmds_holder/mpls_interface (list)
If this variable is read-only (config: false) in the
source YANG file, then _set_mpls_interface is considered as a private
met... | [
"def",
"_set_mpls_interface",
"(",
"self",
",",
"v",
",",
"load",
"=",
"False",
")",
":",
"if",
"hasattr",
"(",
"v",
",",
"\"_utype\"",
")",
":",
"v",
"=",
"v",
".",
"_utype",
"(",
"v",
")",
"try",
":",
"t",
"=",
"YANGDynClass",
"(",
"v",
",",
... | 131.636364 | 63.954545 |
def forced_insert(self):
"""
Insert tokens if self.insert_till hasn't been reached yet
Will respect self.inserted_line and make sure token is inserted before it
Returns True if it appends anything or if it reached the insert_till token
"""
# If we have any tok... | [
"def",
"forced_insert",
"(",
"self",
")",
":",
"# If we have any tokens we are waiting for",
"if",
"self",
".",
"insert_till",
":",
"# Determine where to append this token",
"append_at",
"=",
"-",
"1",
"if",
"self",
".",
"inserted_line",
":",
"append_at",
"=",
"-",
... | 44.037037 | 22.185185 |
def getOrCreateForeignKey(self, model_class, field_name):
"""
Return related random object to set as ForeignKey.
"""
# Getting related object type
# Eg: <django.db.models.fields.related.ForeignKey: test_ForeignKey>
instance = getattr(model_class, field_name).field
... | [
"def",
"getOrCreateForeignKey",
"(",
"self",
",",
"model_class",
",",
"field_name",
")",
":",
"# Getting related object type",
"# Eg: <django.db.models.fields.related.ForeignKey: test_ForeignKey>",
"instance",
"=",
"getattr",
"(",
"model_class",
",",
"field_name",
")",
".",
... | 41.315789 | 18.578947 |
def nscolor_from_hex(hex_string):
"""
Convert given hex color to NSColor.
:hex_string: Hex code of the color as #RGB or #RRGGBB
"""
hex_string = hex_string[1:] # Remove leading hash
if len(hex_string) == 3:
hex_string = ''.join([c*2 for c in hex_string])... | [
"def",
"nscolor_from_hex",
"(",
"hex_string",
")",
":",
"hex_string",
"=",
"hex_string",
"[",
"1",
":",
"]",
"# Remove leading hash",
"if",
"len",
"(",
"hex_string",
")",
"==",
"3",
":",
"hex_string",
"=",
"''",
".",
"join",
"(",
"[",
"c",
"*",
"2",
"f... | 35.65 | 21.95 |
def p_function(self, p):
'function : FUNCTION width ID SEMICOLON function_statement ENDFUNCTION'
p[0] = Function(p[3], p[2], p[5], lineno=p.lineno(1))
p.set_lineno(0, p.lineno(1)) | [
"def",
"p_function",
"(",
"self",
",",
"p",
")",
":",
"p",
"[",
"0",
"]",
"=",
"Function",
"(",
"p",
"[",
"3",
"]",
",",
"p",
"[",
"2",
"]",
",",
"p",
"[",
"5",
"]",
",",
"lineno",
"=",
"p",
".",
"lineno",
"(",
"1",
")",
")",
"p",
".",
... | 50 | 20 |
def explode_contact_groups_into_contacts(item, contactgroups):
"""
Get all contacts of contact_groups and put them in contacts container
:param item: item where have contact_groups property
:type item: object
:param contactgroups: all contactgroups object
:type contactgr... | [
"def",
"explode_contact_groups_into_contacts",
"(",
"item",
",",
"contactgroups",
")",
":",
"if",
"not",
"hasattr",
"(",
"item",
",",
"'contact_groups'",
")",
":",
"return",
"# TODO : See if we can remove this if",
"cgnames",
"=",
"''",
"if",
"item",
".",
"contact_g... | 41.388889 | 17.333333 |
def combine_files(self, f1, f2, f3):
"""
Combines the files 1 and 2 into 3.
"""
with open(os.path.join(self.datadir, f3), 'wb') as new_file:
with open(os.path.join(self.datadir, f1), 'rb') as file_1:
new_file.write(file_1.read())
with open(os.p... | [
"def",
"combine_files",
"(",
"self",
",",
"f1",
",",
"f2",
",",
"f3",
")",
":",
"with",
"open",
"(",
"os",
".",
"path",
".",
"join",
"(",
"self",
".",
"datadir",
",",
"f3",
")",
",",
"'wb'",
")",
"as",
"new_file",
":",
"with",
"open",
"(",
"os"... | 44.666667 | 12 |
def rfft2d_freqs(h, w):
"""Computes 2D spectrum frequencies."""
fy = np.fft.fftfreq(h)[:, None]
# when we have an odd input dimension we need to keep one additional
# frequency and later cut off 1 pixel
if w % 2 == 1:
fx = np.fft.fftfreq(w)[: w // 2 + 2]
else:
fx = np.fft.fftfre... | [
"def",
"rfft2d_freqs",
"(",
"h",
",",
"w",
")",
":",
"fy",
"=",
"np",
".",
"fft",
".",
"fftfreq",
"(",
"h",
")",
"[",
":",
",",
"None",
"]",
"# when we have an odd input dimension we need to keep one additional",
"# frequency and later cut off 1 pixel",
"if",
"w",... | 33.272727 | 14.454545 |
def _calculate(self, startingPercentage, endPercentage, startDate, endDate):
"""This is the error calculation function that gets called by :py:meth:`BaseErrorMeasure.get_error`.
Both parameters will be correct at this time.
:param float startingPercentage: Defines the start of the interval. Th... | [
"def",
"_calculate",
"(",
"self",
",",
"startingPercentage",
",",
"endPercentage",
",",
"startDate",
",",
"endDate",
")",
":",
"# get the defined subset of error values",
"errorValues",
"=",
"self",
".",
"_get_error_values",
"(",
"startingPercentage",
",",
"endPercentag... | 62.318182 | 36.818182 |
def connect(self):
"""Connect to the chatroom's server, sets up handlers, invites members as needed."""
for m in self.params['MEMBERS']:
m['ONLINE'] = 0
m.setdefault('STATUS', 'INVITED')
self.client = xmpp.Client(self.jid.getDomain(), debug=[])
conn = self.client... | [
"def",
"connect",
"(",
"self",
")",
":",
"for",
"m",
"in",
"self",
".",
"params",
"[",
"'MEMBERS'",
"]",
":",
"m",
"[",
"'ONLINE'",
"]",
"=",
"0",
"m",
".",
"setdefault",
"(",
"'STATUS'",
",",
"'INVITED'",
")",
"self",
".",
"client",
"=",
"xmpp",
... | 42 | 20.173913 |
def dispatch():
"""
This methods runs the wheel. It is used to connect signal with their handlers, based on the aliases.
:return:
"""
aliases = SignalDispatcher.signals.keys()
for alias in aliases:
handlers = SignalDispatcher.handlers.get(alias)
... | [
"def",
"dispatch",
"(",
")",
":",
"aliases",
"=",
"SignalDispatcher",
".",
"signals",
".",
"keys",
"(",
")",
"for",
"alias",
"in",
"aliases",
":",
"handlers",
"=",
"SignalDispatcher",
".",
"handlers",
".",
"get",
"(",
"alias",
")",
"signal",
"=",
"Signal... | 30 | 21.764706 |
def in_unit_of(self, unit, as_quantity=False):
"""
Return the current value transformed to the new units
:param unit: either an astropy.Unit instance, or a string which can be converted to an astropy.Unit
instance, like "1 / (erg cm**2 s)"
:param as_quantity: if True, the me... | [
"def",
"in_unit_of",
"(",
"self",
",",
"unit",
",",
"as_quantity",
"=",
"False",
")",
":",
"new_unit",
"=",
"u",
".",
"Unit",
"(",
"unit",
")",
"new_quantity",
"=",
"self",
".",
"as_quantity",
".",
"to",
"(",
"new_unit",
")",
"if",
"as_quantity",
":",
... | 32.409091 | 27.5 |
def get_missing_required_annotations(self) -> List[str]:
"""Return missing required annotations."""
return [
required_annotation
for required_annotation in self.required_annotations
if required_annotation not in self.annotations
] | [
"def",
"get_missing_required_annotations",
"(",
"self",
")",
"->",
"List",
"[",
"str",
"]",
":",
"return",
"[",
"required_annotation",
"for",
"required_annotation",
"in",
"self",
".",
"required_annotations",
"if",
"required_annotation",
"not",
"in",
"self",
".",
"... | 40.571429 | 17.428571 |
def p_fromitem_list(self,t):
"""fromitem_list : fromitem_list ',' fromitem
| fromitem
"""
if len(t)==2: t[0] = [t[1]]
elif len(t)==4: t[0] = t[1] + [t[3]]
else: raise NotImplementedError('unk_len', len(t)) # pragma: no cover | [
"def",
"p_fromitem_list",
"(",
"self",
",",
"t",
")",
":",
"if",
"len",
"(",
"t",
")",
"==",
"2",
":",
"t",
"[",
"0",
"]",
"=",
"[",
"t",
"[",
"1",
"]",
"]",
"elif",
"len",
"(",
"t",
")",
"==",
"4",
":",
"t",
"[",
"0",
"]",
"=",
"t",
... | 37 | 9 |
def gnu_getopt(args, shortopts, longopts=[]):
"""getopt(args, options[, long_options]) -> opts, args
This function works like getopt(), except that GNU style scanning
mode is used by default. This means that option and non-option
arguments may be intermixed. The getopt() function stops
processing o... | [
"def",
"gnu_getopt",
"(",
"args",
",",
"shortopts",
",",
"longopts",
"=",
"[",
"]",
")",
":",
"opts",
"=",
"[",
"]",
"prog_args",
"=",
"[",
"]",
"if",
"type",
"(",
"''",
")",
"==",
"type",
"(",
"longopts",
")",
":",
"longopts",
"=",
"[",
"longopt... | 31.088889 | 19.511111 |
def EnablePlugins(self, plugin_includes):
"""Enables parser plugins.
Args:
plugin_includes (list[str]): names of the plugins to enable, where None
or an empty list represents all plugins. Note that the default plugin
is handled separately.
"""
super(SyslogParser, self).EnableP... | [
"def",
"EnablePlugins",
"(",
"self",
",",
"plugin_includes",
")",
":",
"super",
"(",
"SyslogParser",
",",
"self",
")",
".",
"EnablePlugins",
"(",
"plugin_includes",
")",
"self",
".",
"_plugin_by_reporter",
"=",
"{",
"}",
"for",
"plugin",
"in",
"self",
".",
... | 35.076923 | 19 |
def features(self, other_start, other_end):
"""
return e.g. "intron;exon" if the other_start, end overlap introns and
exons
"""
# completely encases gene.
if other_start <= self.start and other_end >= self.end:
return ['gene' if self.cdsStart != self.cdsEnd el... | [
"def",
"features",
"(",
"self",
",",
"other_start",
",",
"other_end",
")",
":",
"# completely encases gene.",
"if",
"other_start",
"<=",
"self",
".",
"start",
"and",
"other_end",
">=",
"self",
".",
"end",
":",
"return",
"[",
"'gene'",
"if",
"self",
".",
"c... | 45.583333 | 16.5 |
def is_velar(c,lang):
"""
Is the character a velar
"""
o=get_offset(c,lang)
return (o>=VELAR_RANGE[0] and o<=VELAR_RANGE[1]) | [
"def",
"is_velar",
"(",
"c",
",",
"lang",
")",
":",
"o",
"=",
"get_offset",
"(",
"c",
",",
"lang",
")",
"return",
"(",
"o",
">=",
"VELAR_RANGE",
"[",
"0",
"]",
"and",
"o",
"<=",
"VELAR_RANGE",
"[",
"1",
"]",
")"
] | 23.333333 | 9.666667 |
def absent(name,
vhost='/',
runas=None):
'''
Ensure the named policy is absent
Reference: http://www.rabbitmq.com/ha.html
name
The name of the policy to remove
runas
Name of the user to run the command as
'''
ret = {'name': name, 'result': True, 'comme... | [
"def",
"absent",
"(",
"name",
",",
"vhost",
"=",
"'/'",
",",
"runas",
"=",
"None",
")",
":",
"ret",
"=",
"{",
"'name'",
":",
"name",
",",
"'result'",
":",
"True",
",",
"'comment'",
":",
"''",
",",
"'changes'",
":",
"{",
"}",
"}",
"policy_exists",
... | 28.333333 | 22.538462 |
def ref2names2commdct(ref2names, commdct):
"""embed ref2names into commdct"""
for comm in commdct:
for cdct in comm:
try:
refs = cdct['object-list'][0]
validobjects = ref2names[refs]
cdct.update({'validobjects':validobjects})
except... | [
"def",
"ref2names2commdct",
"(",
"ref2names",
",",
"commdct",
")",
":",
"for",
"comm",
"in",
"commdct",
":",
"for",
"cdct",
"in",
"comm",
":",
"try",
":",
"refs",
"=",
"cdct",
"[",
"'object-list'",
"]",
"[",
"0",
"]",
"validobjects",
"=",
"ref2names",
... | 33.545455 | 11.909091 |
def execute_ccm_remotely(remote_options, ccm_args):
"""
Execute CCM operation(s) remotely
:return A tuple defining the execution of the command
* output - The output of the execution if the output was not displayed
* exit_status - The exit status of remotely executed script... | [
"def",
"execute_ccm_remotely",
"(",
"remote_options",
",",
"ccm_args",
")",
":",
"if",
"not",
"PARAMIKO_IS_AVAILABLE",
":",
"logging",
".",
"warn",
"(",
"\"Paramiko is not Availble: Skipping remote execution of CCM command\"",
")",
"return",
"None",
",",
"None",
"# Create... | 46.448276 | 22.37931 |
def is_geographic(element, kdims=None):
"""
Utility to determine whether the supplied element optionally
a subset of its key dimensions represent a geographic coordinate
system.
"""
if isinstance(element, (Overlay, NdOverlay)):
return any(element.traverse(is_geographic, [_Element]))
... | [
"def",
"is_geographic",
"(",
"element",
",",
"kdims",
"=",
"None",
")",
":",
"if",
"isinstance",
"(",
"element",
",",
"(",
"Overlay",
",",
"NdOverlay",
")",
")",
":",
"return",
"any",
"(",
"element",
".",
"traverse",
"(",
"is_geographic",
",",
"[",
"_E... | 33.318182 | 21.045455 |
def extract_file_name(content_dispo):
"""Extract file name from the input request body"""
# print type(content_dispo)
# print repr(content_dispo)
# convertion of escape string (str type) from server
# to unicode object
content_dispo = content_dispo.decode('unicode-escape').strip('"')
file_na... | [
"def",
"extract_file_name",
"(",
"content_dispo",
")",
":",
"# print type(content_dispo)",
"# print repr(content_dispo)",
"# convertion of escape string (str type) from server",
"# to unicode object",
"content_dispo",
"=",
"content_dispo",
".",
"decode",
"(",
"'unicode-escape'",
")... | 37.142857 | 11.642857 |
def opacity(self, value):
"""
Setter for **self.__opacity** attribute.
:param value: Attribute value.
:type value: float
"""
if value is not None:
assert type(value) in (int, float), "'{0}' attribute: '{1}' type is not 'int' or 'float'!".format("opacity",
... | [
"def",
"opacity",
"(",
"self",
",",
"value",
")",
":",
"if",
"value",
"is",
"not",
"None",
":",
"assert",
"type",
"(",
"value",
")",
"in",
"(",
"int",
",",
"float",
")",
",",
"\"'{0}' attribute: '{1}' type is not 'int' or 'float'!\"",
".",
"format",
"(",
"... | 32.166667 | 22.833333 |
def _get_single_page(self, url_suffix, data, page_num):
"""
Send GET request to API at url_suffix with post_data adding page and per_page parameters to
retrieve a single page. Page size is determined by config.page_size.
:param url_suffix: str URL path we are sending a GET to
:pa... | [
"def",
"_get_single_page",
"(",
"self",
",",
"url_suffix",
",",
"data",
",",
"page_num",
")",
":",
"data_with_per_page",
"=",
"dict",
"(",
"data",
")",
"data_with_per_page",
"[",
"'page'",
"]",
"=",
"page_num",
"data_with_per_page",
"[",
"'per_page'",
"]",
"="... | 57.5625 | 21.3125 |
def convert2wavenumber(self):
"""
Convert from wavelengths to wavenumber.
Units:
Wavelength: micro meters (1e-6 m)
Wavenumber: cm-1
"""
self.wavenumber = 1. / (1e-4 * self.wavelength[::-1])
self.irradiance = (self.irradiance[::-1] *
... | [
"def",
"convert2wavenumber",
"(",
"self",
")",
":",
"self",
".",
"wavenumber",
"=",
"1.",
"/",
"(",
"1e-4",
"*",
"self",
".",
"wavelength",
"[",
":",
":",
"-",
"1",
"]",
")",
"self",
".",
"irradiance",
"=",
"(",
"self",
".",
"irradiance",
"[",
":",... | 33.416667 | 15.083333 |
def set_segs_names(self):
"""Return a single array that stores integer segment labels."""
segs_names = np.zeros(self._adata.shape[0], dtype=np.int8)
self.segs_names_unique = []
for iseg, seg in enumerate(self.segs):
segs_names[seg] = iseg
self.segs_names_unique.ap... | [
"def",
"set_segs_names",
"(",
"self",
")",
":",
"segs_names",
"=",
"np",
".",
"zeros",
"(",
"self",
".",
"_adata",
".",
"shape",
"[",
"0",
"]",
",",
"dtype",
"=",
"np",
".",
"int8",
")",
"self",
".",
"segs_names_unique",
"=",
"[",
"]",
"for",
"iseg... | 45 | 8.625 |
def _check_version():
"""Check renku version."""
from ._config import APP_NAME
if VersionCache.load(APP_NAME).is_fresh:
return
from pkg_resources import parse_version
from renku.version import __version__
version = parse_version(__version__)
allow_prereleases = version.is_prerelea... | [
"def",
"_check_version",
"(",
")",
":",
"from",
".",
"_config",
"import",
"APP_NAME",
"if",
"VersionCache",
".",
"load",
"(",
"APP_NAME",
")",
".",
"is_fresh",
":",
"return",
"from",
"pkg_resources",
"import",
"parse_version",
"from",
"renku",
".",
"version",
... | 28.233333 | 18.566667 |
def recover_model_from_data(model_class, original_data, modified_data, deleted_data):
"""
Function to reconstruct a model from DirtyModel basic information: original data, the modified and deleted
fields.
Necessary for pickle an object
"""
model = model_class()
return set_model_internal_data... | [
"def",
"recover_model_from_data",
"(",
"model_class",
",",
"original_data",
",",
"modified_data",
",",
"deleted_data",
")",
":",
"model",
"=",
"model_class",
"(",
")",
"return",
"set_model_internal_data",
"(",
"model",
",",
"original_data",
",",
"modified_data",
","... | 45.5 | 26.25 |
def getFieldsColumnLengths(self):
"""
Gets the maximum length of each column in the field table
"""
nameLen = 0
descLen = 0
for f in self.fields:
nameLen = max(nameLen, len(f['title']))
descLen = max(descLen, len(f['description']))
return (... | [
"def",
"getFieldsColumnLengths",
"(",
"self",
")",
":",
"nameLen",
"=",
"0",
"descLen",
"=",
"0",
"for",
"f",
"in",
"self",
".",
"fields",
":",
"nameLen",
"=",
"max",
"(",
"nameLen",
",",
"len",
"(",
"f",
"[",
"'title'",
"]",
")",
")",
"descLen",
"... | 32.8 | 12 |
def editUsageReportSettings(self, samplingInterval,
enabled=True, maxHistory=0):
"""
The usage reports settings are applied to the entire site. A POST
request updates the usage reports settings.
Inputs:
samplingInterval - Defines the duration (... | [
"def",
"editUsageReportSettings",
"(",
"self",
",",
"samplingInterval",
",",
"enabled",
"=",
"True",
",",
"maxHistory",
"=",
"0",
")",
":",
"params",
"=",
"{",
"\"f\"",
":",
"\"json\"",
",",
"\"maxHistory\"",
":",
"maxHistory",
",",
"\"enabled\"",
":",
"enab... | 47.677419 | 19.16129 |
def store_vector(self, hash_name, bucket_key, v, data):
"""
Stores vector and JSON-serializable data in bucket with specified key.
"""
self._add_vector(hash_name, bucket_key, v, data, self.redis_object) | [
"def",
"store_vector",
"(",
"self",
",",
"hash_name",
",",
"bucket_key",
",",
"v",
",",
"data",
")",
":",
"self",
".",
"_add_vector",
"(",
"hash_name",
",",
"bucket_key",
",",
"v",
",",
"data",
",",
"self",
".",
"redis_object",
")"
] | 46 | 17.6 |
def signmessage(self, address, message):
"""Sign a message with the private key of an address.
Cryptographically signs a message using ECDSA. Since this requires
an address's private key, the wallet must be unlocked first.
Args:
address (str): address used to sign the messag... | [
"def",
"signmessage",
"(",
"self",
",",
"address",
",",
"message",
")",
":",
"signature",
"=",
"self",
".",
"rpc",
".",
"call",
"(",
"\"signmessage\"",
",",
"address",
",",
"message",
")",
"self",
".",
"logger",
".",
"debug",
"(",
"\"Signature: %s\"",
"%... | 35.470588 | 22.647059 |
def asyncStarMap(asyncCallable, iterable):
"""itertools.starmap for deferred callables
"""
deferreds = starmap(asyncCallable, iterable)
return gatherResults(deferreds, consumeErrors=True) | [
"def",
"asyncStarMap",
"(",
"asyncCallable",
",",
"iterable",
")",
":",
"deferreds",
"=",
"starmap",
"(",
"asyncCallable",
",",
"iterable",
")",
"return",
"gatherResults",
"(",
"deferreds",
",",
"consumeErrors",
"=",
"True",
")"
] | 39.8 | 5 |
def normalize(expr):
"""Normalize both sides, but don't eliminate the expression."""
lhs = normalize(expr.lhs)
rhs = normalize(expr.rhs)
return type(expr)(lhs, rhs, start=lhs.start, end=rhs.end) | [
"def",
"normalize",
"(",
"expr",
")",
":",
"lhs",
"=",
"normalize",
"(",
"expr",
".",
"lhs",
")",
"rhs",
"=",
"normalize",
"(",
"expr",
".",
"rhs",
")",
"return",
"type",
"(",
"expr",
")",
"(",
"lhs",
",",
"rhs",
",",
"start",
"=",
"lhs",
".",
... | 41.2 | 12.6 |
def get_contract_by_hash(self, contract_hash):
"""get mapped contract_address by its hash, if not found try
indexing."""
contract_address = self.db.reader._get_address_by_hash(contract_hash)
if contract_address is not None:
return contract_address
else:
r... | [
"def",
"get_contract_by_hash",
"(",
"self",
",",
"contract_hash",
")",
":",
"contract_address",
"=",
"self",
".",
"db",
".",
"reader",
".",
"_get_address_by_hash",
"(",
"contract_hash",
")",
"if",
"contract_address",
"is",
"not",
"None",
":",
"return",
"contract... | 37.444444 | 13 |
def handle_json_GET_triprows(self, params):
"""Return a list of rows from the feed file that are related to this
trip."""
schedule = self.server.schedule
try:
trip = schedule.GetTrip(params.get('trip', None))
except KeyError:
# if a non-existent trip is searched for, the return nothing
... | [
"def",
"handle_json_GET_triprows",
"(",
"self",
",",
"params",
")",
":",
"schedule",
"=",
"self",
".",
"server",
".",
"schedule",
"try",
":",
"trip",
"=",
"schedule",
".",
"GetTrip",
"(",
"params",
".",
"get",
"(",
"'trip'",
",",
"None",
")",
")",
"exc... | 38.923077 | 12.307692 |
def _additions_remove_use_cd(**kwargs):
'''
Remove VirtualBox Guest Additions.
It uses the CD, connected by VirtualBox.
'''
with _additions_mounted() as mount_point:
kernel = __grains__.get('kernel', '')
if kernel == 'Linux':
return _additions_remove_linux_use_cd(mount_... | [
"def",
"_additions_remove_use_cd",
"(",
"*",
"*",
"kwargs",
")",
":",
"with",
"_additions_mounted",
"(",
")",
"as",
"mount_point",
":",
"kernel",
"=",
"__grains__",
".",
"get",
"(",
"'kernel'",
",",
"''",
")",
"if",
"kernel",
"==",
"'Linux'",
":",
"return"... | 29.636364 | 18.727273 |
def get_best_answer(self, query):
"""Get best answer to a question.
:param query: A question to get an answer
:type query: :class:`str`
:returns: An answer to a question
:rtype: :class:`str`
:raises: :class:`NoAnswerError` when can not found answer to a question
... | [
"def",
"get_best_answer",
"(",
"self",
",",
"query",
")",
":",
"query",
"=",
"to_unicode",
"(",
"query",
")",
"session",
"=",
"self",
".",
"Session",
"(",
")",
"grams",
"=",
"self",
".",
"_get_grams",
"(",
"session",
",",
"query",
")",
"if",
"not",
"... | 30.522727 | 21.295455 |
def create_file(self, path, fp, force=False, update=False):
"""Store a new file at `path` in this storage.
The contents of the file descriptor `fp` (opened in 'rb' mode)
will be uploaded to `path` which is the full path at
which to store the file.
To force overwrite of an exist... | [
"def",
"create_file",
"(",
"self",
",",
"path",
",",
"fp",
",",
"force",
"=",
"False",
",",
"update",
"=",
"False",
")",
":",
"if",
"'b'",
"not",
"in",
"fp",
".",
"mode",
":",
"raise",
"ValueError",
"(",
"\"File has to be opened in binary mode.\"",
")",
... | 45.282051 | 20.987179 |
def _hcn_func(self):
"""Eq. 56 from Barack and Cutler 2004
"""
self.hc = 1./(np.pi*self.dist)*np.sqrt(2.*self._dEndfr())
return | [
"def",
"_hcn_func",
"(",
"self",
")",
":",
"self",
".",
"hc",
"=",
"1.",
"/",
"(",
"np",
".",
"pi",
"*",
"self",
".",
"dist",
")",
"*",
"np",
".",
"sqrt",
"(",
"2.",
"*",
"self",
".",
"_dEndfr",
"(",
")",
")",
"return"
] | 25.833333 | 18.5 |
def minimal_residual(A, b, x0=None, tol=1e-5, maxiter=None, xtype=None, M=None,
callback=None, residuals=None):
"""Minimal residual (MR) algorithm.
Solves the linear system Ax = b. Left preconditioning is supported.
Parameters
----------
A : array, matrix, sparse matrix, Linea... | [
"def",
"minimal_residual",
"(",
"A",
",",
"b",
",",
"x0",
"=",
"None",
",",
"tol",
"=",
"1e-5",
",",
"maxiter",
"=",
"None",
",",
"xtype",
"=",
"None",
",",
"M",
"=",
"None",
",",
"callback",
"=",
"None",
",",
"residuals",
"=",
"None",
")",
":",
... | 29.676056 | 21.028169 |
def has_children(self):
"""
Checks if there are children tab widgets.
:return: True if there is at least one tab in the children tab widget.
"""
for splitter in self.child_splitters:
if splitter.has_children():
return splitter
return self.main_... | [
"def",
"has_children",
"(",
"self",
")",
":",
"for",
"splitter",
"in",
"self",
".",
"child_splitters",
":",
"if",
"splitter",
".",
"has_children",
"(",
")",
":",
"return",
"splitter",
"return",
"self",
".",
"main_tab_widget",
".",
"count",
"(",
")",
"!=",
... | 37.222222 | 9.666667 |
def _proxy(self):
"""
Generate an instance context for the instance, the context is capable of
performing various actions. All instance actions are proxied to the context
:returns: AssignedAddOnContext for this AssignedAddOnInstance
:rtype: twilio.rest.api.v2010.account.incomin... | [
"def",
"_proxy",
"(",
"self",
")",
":",
"if",
"self",
".",
"_context",
"is",
"None",
":",
"self",
".",
"_context",
"=",
"AssignedAddOnContext",
"(",
"self",
".",
"_version",
",",
"account_sid",
"=",
"self",
".",
"_solution",
"[",
"'account_sid'",
"]",
",... | 43.0625 | 21.5625 |
def _set_l2traceroute(self, v, load=False):
"""
Setter method for l2traceroute, mapped from YANG variable /brocade_trilloam_rpc/l2traceroute (rpc)
If this variable is read-only (config: false) in the
source YANG file, then _set_l2traceroute is considered as a private
method. Backends looking to popu... | [
"def",
"_set_l2traceroute",
"(",
"self",
",",
"v",
",",
"load",
"=",
"False",
")",
":",
"if",
"hasattr",
"(",
"v",
",",
"\"_utype\"",
")",
":",
"v",
"=",
"v",
".",
"_utype",
"(",
"v",
")",
"try",
":",
"t",
"=",
"YANGDynClass",
"(",
"v",
",",
"b... | 71.208333 | 35.416667 |
def requeue(rq, ctx, all, job_ids):
"Requeue failed jobs."
return ctx.invoke(
rq_cli.requeue,
all=all,
job_ids=job_ids,
**shared_options(rq)
) | [
"def",
"requeue",
"(",
"rq",
",",
"ctx",
",",
"all",
",",
"job_ids",
")",
":",
"return",
"ctx",
".",
"invoke",
"(",
"rq_cli",
".",
"requeue",
",",
"all",
"=",
"all",
",",
"job_ids",
"=",
"job_ids",
",",
"*",
"*",
"shared_options",
"(",
"rq",
")",
... | 22.375 | 17.625 |
def view(self, request, **kwargs):
'''
allow a file to be viewed as opposed to download. This is particularly needed when a video file is stored
in the fileservice and user wants to be able to use a view the video as opposed to having to download it
first. It passes the serving of the fi... | [
"def",
"view",
"(",
"self",
",",
"request",
",",
"*",
"*",
"kwargs",
")",
":",
"# method check to avoid bad requests",
"self",
".",
"method_check",
"(",
"request",
",",
"allowed",
"=",
"[",
"'get'",
"]",
")",
"# Must be done otherwise endpoint will be wide open",
... | 43.659574 | 28.425532 |
def sanitize_dict(input_dict):
r"""
Given a nested dictionary, ensures that all nested dicts are normal
Python dicts. This is necessary for pickling, or just converting
an 'auto-vivifying' dict to something that acts normal.
"""
plain_dict = dict()
for key in input_dict.keys():
valu... | [
"def",
"sanitize_dict",
"(",
"input_dict",
")",
":",
"plain_dict",
"=",
"dict",
"(",
")",
"for",
"key",
"in",
"input_dict",
".",
"keys",
"(",
")",
":",
"value",
"=",
"input_dict",
"[",
"key",
"]",
"if",
"hasattr",
"(",
"value",
",",
"'keys'",
")",
":... | 34.571429 | 13.5 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.