text stringlengths 89 104k | code_tokens list | avg_line_len float64 7.91 980 | score float64 0 630 |
|---|---|---|---|
def run(self):
"""
Monitors if the config file or plugins are updated. Also outputs the
JSON data generated by the plugins, without needing to poll the threads.
"""
self.run_plugins()
while True:
# Reload plugins and config if either the config file or plugin
... | [
"def",
"run",
"(",
"self",
")",
":",
"self",
".",
"run_plugins",
"(",
")",
"while",
"True",
":",
"# Reload plugins and config if either the config file or plugin",
"# directory are modified.",
"if",
"self",
".",
"_config_mod_time",
"!=",
"os",
".",
"path",
".",
"get... | 46.941176 | 19.882353 |
def side_effect(self, func, *args, **kwargs):
'''
Wrap side effects for spies.
'''
self._spy_side_effect = func
self._spy_side_effect_args = args
self._spy_side_effect_kwargs = kwargs
return self | [
"def",
"side_effect",
"(",
"self",
",",
"func",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"self",
".",
"_spy_side_effect",
"=",
"func",
"self",
".",
"_spy_side_effect_args",
"=",
"args",
"self",
".",
"_spy_side_effect_kwargs",
"=",
"kwargs",
"re... | 30.5 | 12.25 |
def add_resource_context(
app: web.Application, module=None,
url_prefix: str=None, name_prefix: str=None, make_resource=lambda cls: cls()
):
"""Context manager which yields a function for adding multiple resources from a given module
to an app using `ResourceRouter <aiohttp_utils.routing.ResourceRouter>... | [
"def",
"add_resource_context",
"(",
"app",
":",
"web",
".",
"Application",
",",
"module",
"=",
"None",
",",
"url_prefix",
":",
"str",
"=",
"None",
",",
"name_prefix",
":",
"str",
"=",
"None",
",",
"make_resource",
"=",
"lambda",
"cls",
":",
"cls",
"(",
... | 36.885714 | 22.647619 |
def report(mount):
'''
Report on quotas for a specific volume
CLI Example:
.. code-block:: bash
salt '*' quota.report /media/data
'''
ret = {mount: {}}
ret[mount]['User Quotas'] = _parse_quota(mount, '-u')
ret[mount]['Group Quotas'] = _parse_quota(mount, '-g')
return ret | [
"def",
"report",
"(",
"mount",
")",
":",
"ret",
"=",
"{",
"mount",
":",
"{",
"}",
"}",
"ret",
"[",
"mount",
"]",
"[",
"'User Quotas'",
"]",
"=",
"_parse_quota",
"(",
"mount",
",",
"'-u'",
")",
"ret",
"[",
"mount",
"]",
"[",
"'Group Quotas'",
"]",
... | 21.785714 | 23.642857 |
def conjugate(self):
"""The element-wise conjugate matrix
This is defined only if all the entries in the matrix have a defined
conjugate (i.e., they have a `conjugate` method). This is *not* the
case for a matrix of operators. In such a case, only an
:meth:`elementwise` :func:`a... | [
"def",
"conjugate",
"(",
"self",
")",
":",
"try",
":",
"return",
"Matrix",
"(",
"np_conjugate",
"(",
"self",
".",
"matrix",
")",
")",
"except",
"AttributeError",
":",
"raise",
"NoConjugateMatrix",
"(",
"\"Matrix %s contains entries that have no defined \"",
"\"conju... | 41.444444 | 21.388889 |
def get_file_info(hash, context=None):
"""Returns information about the file, identified by ``hash``.
If the `context` (an ident-hash) is supplied,
the information returned will be specific to that context.
"""
if context is None:
stmt = _get_sql('get-file-info.sql')
args = dict(has... | [
"def",
"get_file_info",
"(",
"hash",
",",
"context",
"=",
"None",
")",
":",
"if",
"context",
"is",
"None",
":",
"stmt",
"=",
"_get_sql",
"(",
"'get-file-info.sql'",
")",
"args",
"=",
"dict",
"(",
"hash",
"=",
"hash",
")",
"else",
":",
"stmt",
"=",
"_... | 34.863636 | 12.727273 |
def _parse_scalars(scalars):
"""Parse the scalars from the YAML file content to a dictionary of ScalarType(s).
:return: A dictionary { 'full.scalar.label': ScalarType }
"""
scalar_dict = {}
# Scalars are defined in a fixed two-level hierarchy within the definition file.
... | [
"def",
"_parse_scalars",
"(",
"scalars",
")",
":",
"scalar_dict",
"=",
"{",
"}",
"# Scalars are defined in a fixed two-level hierarchy within the definition file.",
"# The first level contains the category name, while the second level contains the",
"# probe name (e.g. \"category.name: probe... | 50.045455 | 24.227273 |
def split_by_files(self, valid_names:'ItemList')->'ItemLists':
"Split the data by using the names in `valid_names` for validation."
if isinstance(self.items[0], Path): return self.split_by_valid_func(lambda o: o.name in valid_names)
else: return self.split_by_valid_func(lambda o: os.path.basenam... | [
"def",
"split_by_files",
"(",
"self",
",",
"valid_names",
":",
"'ItemList'",
")",
"->",
"'ItemLists'",
":",
"if",
"isinstance",
"(",
"self",
".",
"items",
"[",
"0",
"]",
",",
"Path",
")",
":",
"return",
"self",
".",
"split_by_valid_func",
"(",
"lambda",
... | 84.25 | 44.25 |
def match_file(apikey, path, metadata=None):
"""Uses the audioread library to decode an audio file and match it.
"""
import audioread
with audioread.audio_open(path) as f:
return match(apikey, iter(f), f.samplerate, int(f.duration),
f.channels, metadata) | [
"def",
"match_file",
"(",
"apikey",
",",
"path",
",",
"metadata",
"=",
"None",
")",
":",
"import",
"audioread",
"with",
"audioread",
".",
"audio_open",
"(",
"path",
")",
"as",
"f",
":",
"return",
"match",
"(",
"apikey",
",",
"iter",
"(",
"f",
")",
",... | 41.857143 | 7.857143 |
def _instantiateFont(self, path):
"""
Return a instance of a font object
with all the given subclasses
"""
return self._fontClass(path,
libClass=self._libClass,
kerningClass=self._kerningClass,
groupsClass=self._groupsClass,
infoCla... | [
"def",
"_instantiateFont",
"(",
"self",
",",
"path",
")",
":",
"return",
"self",
".",
"_fontClass",
"(",
"path",
",",
"libClass",
"=",
"self",
".",
"_libClass",
",",
"kerningClass",
"=",
"self",
".",
"_kerningClass",
",",
"groupsClass",
"=",
"self",
".",
... | 39.375 | 5.5 |
def create_closure_model(cls):
"""Creates a <Model>Closure model in the same module as the model."""
meta_vals = {
'unique_together': (("parent", "child"),)
}
if getattr(cls._meta, 'db_table', None):
meta_vals['db_table'] = '%sclosure' % getattr(cls._meta, 'db_table')
model = type('... | [
"def",
"create_closure_model",
"(",
"cls",
")",
":",
"meta_vals",
"=",
"{",
"'unique_together'",
":",
"(",
"(",
"\"parent\"",
",",
"\"child\"",
")",
",",
")",
"}",
"if",
"getattr",
"(",
"cls",
".",
"_meta",
",",
"'db_table'",
",",
"None",
")",
":",
"me... | 36.173913 | 14.478261 |
def make(self, analyte):
"""
Make filter for specified analyte(s).
Filter specified in filt.switches.
Parameters
----------
analyte : str or array_like
Name or list of names of analytes.
Returns
-------
array_like
boolean... | [
"def",
"make",
"(",
"self",
",",
"analyte",
")",
":",
"if",
"analyte",
"is",
"None",
":",
"analyte",
"=",
"self",
".",
"analytes",
"elif",
"isinstance",
"(",
"analyte",
",",
"str",
")",
":",
"analyte",
"=",
"[",
"analyte",
"]",
"out",
"=",
"[",
"]"... | 24.7 | 14.233333 |
def remove_backslash_r(filename, encoding):
"""
A helpful utility to remove Carriage Return from any file.
This will read a file into memory,
and overwrite the contents of the original file.
TODO: This function may be a liability
:param filename:
:return:
... | [
"def",
"remove_backslash_r",
"(",
"filename",
",",
"encoding",
")",
":",
"with",
"open",
"(",
"filename",
",",
"'r'",
",",
"encoding",
"=",
"encoding",
",",
"newline",
"=",
"r'\\n'",
")",
"as",
"filereader",
":",
"contents",
"=",
"filereader",
".",
"read",... | 30 | 17.8 |
def encoded(string, encoding='utf-8'):
"""Cast string to binary_type.
:param string: six.binary_type or six.text_type
:param encoding: encoding which the object is forced to
:return: six.binary_type
"""
assert isinstance(string, string_types) or isinstance(string, binary_type)
if isinstance... | [
"def",
"encoded",
"(",
"string",
",",
"encoding",
"=",
"'utf-8'",
")",
":",
"assert",
"isinstance",
"(",
"string",
",",
"string_types",
")",
"or",
"isinstance",
"(",
"string",
",",
"binary_type",
")",
"if",
"isinstance",
"(",
"string",
",",
"text_type",
")... | 38.611111 | 17.333333 |
def __setLock(self, command):
"""Set lock on requests."""
if command in (TURN_ON, TURN_OFF):
self._operation = command
elif command in INV_SOURCES:
self._operation = SOURCE
else:
self._operation = ALL
self._isLocked = True
self._timer =... | [
"def",
"__setLock",
"(",
"self",
",",
"command",
")",
":",
"if",
"command",
"in",
"(",
"TURN_ON",
",",
"TURN_OFF",
")",
":",
"self",
".",
"_operation",
"=",
"command",
"elif",
"command",
"in",
"INV_SOURCES",
":",
"self",
".",
"_operation",
"=",
"SOURCE",... | 32.3 | 7.6 |
def send_worker_queue_message(self, *, batch_id, job_name, entry_point, worker_args, retry_count=0):
"""Send a message to the `worker_queue` for a worker to execute the requests job
Args:
batch_id (`str`): Unique ID of the batch the job belongs to
job_name (`str`): Non-unique ID... | [
"def",
"send_worker_queue_message",
"(",
"self",
",",
"*",
",",
"batch_id",
",",
"job_name",
",",
"entry_point",
",",
"worker_args",
",",
"retry_count",
"=",
"0",
")",
":",
"try",
":",
"job_id",
"=",
"str",
"(",
"uuid4",
"(",
")",
")",
"self",
".",
"jo... | 40.708333 | 20.395833 |
def by_median_household_income(self,
lower=-1,
upper=2 ** 31,
zipcode_type=ZipcodeType.Standard,
sort_by=SimpleZipcode.median_household_income.name,
... | [
"def",
"by_median_household_income",
"(",
"self",
",",
"lower",
"=",
"-",
"1",
",",
"upper",
"=",
"2",
"**",
"31",
",",
"zipcode_type",
"=",
"ZipcodeType",
".",
"Standard",
",",
"sort_by",
"=",
"SimpleZipcode",
".",
"median_household_income",
".",
"name",
",... | 44.5 | 14.25 |
def random(self, num_bytes):
"""
Get random bytes from YubiHSM.
The random data is DRBG_CTR seeded on each startup by a hardware TRNG,
so it should be of very good quality.
@type num_bytes: integer
@return: Bytes with random data
@rtype: string
@see: L... | [
"def",
"random",
"(",
"self",
",",
"num_bytes",
")",
":",
"return",
"pyhsm",
".",
"basic_cmd",
".",
"YHSM_Cmd_Random",
"(",
"self",
".",
"stick",
",",
"num_bytes",
")",
".",
"execute",
"(",
")"
] | 28.733333 | 19.4 |
def _extract(self, in_tile=None, in_data=None, out_tile=None):
"""Extract data from tile."""
return self.config.output.extract_subset(
input_data_tiles=[(in_tile, in_data)],
out_tile=out_tile
) | [
"def",
"_extract",
"(",
"self",
",",
"in_tile",
"=",
"None",
",",
"in_data",
"=",
"None",
",",
"out_tile",
"=",
"None",
")",
":",
"return",
"self",
".",
"config",
".",
"output",
".",
"extract_subset",
"(",
"input_data_tiles",
"=",
"[",
"(",
"in_tile",
... | 39.333333 | 13.833333 |
def do_list(self, arg):
"""l(ist) [first [,last] | .]
List source code for the current file. Without arguments,
list 11 lines around the current line or continue the previous
listing. With . as argument, list 11 lines around the current
line. With one argument, list 11 lines ... | [
"def",
"do_list",
"(",
"self",
",",
"arg",
")",
":",
"self",
".",
"lastcmd",
"=",
"'list'",
"last",
"=",
"None",
"if",
"arg",
"and",
"arg",
"!=",
"'.'",
":",
"try",
":",
"if",
"','",
"in",
"arg",
":",
"first",
",",
"last",
"=",
"arg",
".",
"spl... | 40.469388 | 15.489796 |
def create_random_seq(character, action_metadata, direction, length=8):
"""Creates a random sequence."""
start = tf.random.uniform([], maxval=action_metadata[1], dtype=tf.int32)
return create_seq(character, action_metadata, direction, length, start) | [
"def",
"create_random_seq",
"(",
"character",
",",
"action_metadata",
",",
"direction",
",",
"length",
"=",
"8",
")",
":",
"start",
"=",
"tf",
".",
"random",
".",
"uniform",
"(",
"[",
"]",
",",
"maxval",
"=",
"action_metadata",
"[",
"1",
"]",
",",
"dty... | 63 | 24.5 |
def command(cmd):
"""Execute command and raise an exception upon an error.
>>> 'README' in command('ls')
True
>>> command('nonexistingcommand') #doctest: +ELLIPSIS
Traceback (most recent call last):
...
SdistCreationError
"""
status, out = commands.getstatusoutput(cmd)... | [
"def",
"command",
"(",
"cmd",
")",
":",
"status",
",",
"out",
"=",
"commands",
".",
"getstatusoutput",
"(",
"cmd",
")",
"if",
"status",
"is",
"not",
"0",
":",
"logger",
".",
"error",
"(",
"\"Something went wrong:\"",
")",
"logger",
".",
"error",
"(",
"... | 26.470588 | 16.529412 |
def convert_shortcut_quick_reply(items):
"""
support shortcut [{'title':'title', 'payload':'payload'}]
"""
if items is not None and isinstance(items, list):
result = []
for item in items:
if isinstance(item, QuickReply):
result.... | [
"def",
"convert_shortcut_quick_reply",
"(",
"items",
")",
":",
"if",
"items",
"is",
"not",
"None",
"and",
"isinstance",
"(",
"items",
",",
"list",
")",
":",
"result",
"=",
"[",
"]",
"for",
"item",
"in",
"items",
":",
"if",
"isinstance",
"(",
"item",
",... | 38.8125 | 15.5625 |
def load_lines(filename):
"""
Load a text file as an array of lines.
Args:
filename: Path to the input file.
Returns:
An array of strings, each representing an individual line.
"""
with open(filename, 'r', encoding='utf-8') as f:
return [line.rstrip('\n') for line in f... | [
"def",
"load_lines",
"(",
"filename",
")",
":",
"with",
"open",
"(",
"filename",
",",
"'r'",
",",
"encoding",
"=",
"'utf-8'",
")",
"as",
"f",
":",
"return",
"[",
"line",
".",
"rstrip",
"(",
"'\\n'",
")",
"for",
"line",
"in",
"f",
".",
"readlines",
... | 24.692308 | 19.615385 |
def abspath(myPath):
import sys, os
""" Get absolute path to resource, works for dev and for PyInstaller """
try:
# PyInstaller creates a temp folder and stores path in _MEIPASS
base_path = sys._MEIPASS
return os.path.join(base_path, os.path.basename(myPath))
except Exception:
... | [
"def",
"abspath",
"(",
"myPath",
")",
":",
"import",
"sys",
",",
"os",
"try",
":",
"# PyInstaller creates a temp folder and stores path in _MEIPASS",
"base_path",
"=",
"sys",
".",
"_MEIPASS",
"return",
"os",
".",
"path",
".",
"join",
"(",
"base_path",
",",
"os",... | 41.8 | 18.4 |
def parse_with_retrieved(self, retrieved):
"""
Receives in input a dictionary of retrieved nodes.
Does all the logic here.
"""
from aiida.common.exceptions import InvalidOperation
import os
output_path = None
error_path = None
try:
out... | [
"def",
"parse_with_retrieved",
"(",
"self",
",",
"retrieved",
")",
":",
"from",
"aiida",
".",
"common",
".",
"exceptions",
"import",
"InvalidOperation",
"import",
"os",
"output_path",
"=",
"None",
"error_path",
"=",
"None",
"try",
":",
"output_path",
",",
"err... | 31.130435 | 17.565217 |
def visit_FunctionDef(self, node):
"""Visit a function node."""
node = self.get_function_node(node)
if node is not None:
node._async = False | [
"def",
"visit_FunctionDef",
"(",
"self",
",",
"node",
")",
":",
"node",
"=",
"self",
".",
"get_function_node",
"(",
"node",
")",
"if",
"node",
"is",
"not",
"None",
":",
"node",
".",
"_async",
"=",
"False"
] | 34.4 | 6 |
def generate_certificates(base_dir, *peer_names, pubKeyDir=None,
secKeyDir=None, sigKeyDir=None,
verkeyDir=None, clean=True):
''' Generate client and server CURVE certificate files'''
pubKeyDir = pubKeyDir or 'public_keys'
secKeyDir = secKeyDir or 'private... | [
"def",
"generate_certificates",
"(",
"base_dir",
",",
"*",
"peer_names",
",",
"pubKeyDir",
"=",
"None",
",",
"secKeyDir",
"=",
"None",
",",
"sigKeyDir",
"=",
"None",
",",
"verkeyDir",
"=",
"None",
",",
"clean",
"=",
"True",
")",
":",
"pubKeyDir",
"=",
"p... | 39.976744 | 17 |
def role_get(name, user=None, host=None, port=None, maintenance_db=None,
password=None, runas=None, return_password=False):
'''
Return a dict with information about users of a Postgres server.
Set return_password to True to get password hash in the result.
CLI Example:
.. code-block:... | [
"def",
"role_get",
"(",
"name",
",",
"user",
"=",
"None",
",",
"host",
"=",
"None",
",",
"port",
"=",
"None",
",",
"maintenance_db",
"=",
"None",
",",
"password",
"=",
"None",
",",
"runas",
"=",
"None",
",",
"return_password",
"=",
"False",
")",
":",... | 33.56 | 21.32 |
def is_storage(url, storage=None):
"""
Check if file is a local file or a storage file.
File is considered local if:
- URL is a local path.
- URL starts by "file://"
- a "storage" is provided.
Args:
url (str): file path or URL
storage (str): Storage name.
R... | [
"def",
"is_storage",
"(",
"url",
",",
"storage",
"=",
"None",
")",
":",
"if",
"storage",
":",
"return",
"True",
"split_url",
"=",
"url",
".",
"split",
"(",
"'://'",
",",
"1",
")",
"if",
"len",
"(",
"split_url",
")",
"==",
"2",
"and",
"split_url",
"... | 24.090909 | 16.272727 |
def define_from_values(cls, xdtu, ydtu, zdtu, xdtu_0, ydtu_0, zdtu_0):
"""Define class object from from provided values.
Parameters
----------
xdtu : float
XDTU fits keyword value.
ydtu : float
YDTU fits keyword value.
zdtu : float
ZDT... | [
"def",
"define_from_values",
"(",
"cls",
",",
"xdtu",
",",
"ydtu",
",",
"zdtu",
",",
"xdtu_0",
",",
"ydtu_0",
",",
"zdtu_0",
")",
":",
"self",
"=",
"DtuConfiguration",
"(",
")",
"# define DTU variables",
"self",
".",
"xdtu",
"=",
"xdtu",
"self",
".",
"yd... | 26.206897 | 15.448276 |
def replay_scope(self, sess):
"""Enters a replay scope that unsets it at the end."""
current_replay = self.replay(sess)
try:
self.set_replay(sess, True)
yield
finally:
self.set_replay(sess, current_replay) | [
"def",
"replay_scope",
"(",
"self",
",",
"sess",
")",
":",
"current_replay",
"=",
"self",
".",
"replay",
"(",
"sess",
")",
"try",
":",
"self",
".",
"set_replay",
"(",
"sess",
",",
"True",
")",
"yield",
"finally",
":",
"self",
".",
"set_replay",
"(",
... | 29 | 14 |
def _load_plugins(self):
'''
Sets up all plugins, defaults and settings.py
'''
plugins = self.settings['PLUGINS']
self.plugins_dict = {}
for key in plugins:
# skip loading the plugin if its value is None
if plugins[key] is None:
co... | [
"def",
"_load_plugins",
"(",
"self",
")",
":",
"plugins",
"=",
"self",
".",
"settings",
"[",
"'PLUGINS'",
"]",
"self",
".",
"plugins_dict",
"=",
"{",
"}",
"for",
"key",
"in",
"plugins",
":",
"# skip loading the plugin if its value is None",
"if",
"plugins",
"[... | 39.166667 | 17.9 |
def highres_imu_encode(self, time_usec, xacc, yacc, zacc, xgyro, ygyro, zgyro, xmag, ymag, zmag, abs_pressure, diff_pressure, pressure_alt, temperature, fields_updated):
'''
The IMU readings in SI units in NED body frame
time_usec : Timestamp (microsecond... | [
"def",
"highres_imu_encode",
"(",
"self",
",",
"time_usec",
",",
"xacc",
",",
"yacc",
",",
"zacc",
",",
"xgyro",
",",
"ygyro",
",",
"zgyro",
",",
"xmag",
",",
"ymag",
",",
"zmag",
",",
"abs_pressure",
",",
"diff_pressure",
",",
"pressure_alt",
",",
"temp... | 80.954545 | 52.045455 |
def remove_from_group(self, group, user):
"""
Remove a user from a group
:type user: str
:param user: User's email
:type group: str
:param group: Group name
:rtype: dict
:return: an empty dictionary
"""
data = {'group': group, 'user': us... | [
"def",
"remove_from_group",
"(",
"self",
",",
"group",
",",
"user",
")",
":",
"data",
"=",
"{",
"'group'",
":",
"group",
",",
"'user'",
":",
"user",
"}",
"return",
"self",
".",
"post",
"(",
"'removeUserFromGroup'",
",",
"data",
")"
] | 24.2 | 14.466667 |
def log_level(io_handler, level=None, name=None):
"""
Prints/Changes log level
"""
# Get the logger
logger = logging.getLogger(name)
# Normalize the name
if not name:
name = "Root"
if not level:
# Level not given: print the logger... | [
"def",
"log_level",
"(",
"io_handler",
",",
"level",
"=",
"None",
",",
"name",
"=",
"None",
")",
":",
"# Get the logger",
"logger",
"=",
"logging",
".",
"getLogger",
"(",
"name",
")",
"# Normalize the name",
"if",
"not",
"name",
":",
"name",
"=",
"\"Root\"... | 32 | 16.461538 |
def only_for(theme, redirect_to='/', raise_error=None):
""" Decorator for restrict access to views according by list of themes.
Params:
* ``theme`` - string or list of themes where decorated view must be
* ``redirect_to`` - url or name of url pattern for redirect
if CURRENT_THEME n... | [
"def",
"only_for",
"(",
"theme",
",",
"redirect_to",
"=",
"'/'",
",",
"raise_error",
"=",
"None",
")",
":",
"def",
"check_theme",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"if",
"isinstance",
"(",
"theme",
",",
"six",
".",
"string_types",
... | 25.076923 | 22.205128 |
def create_sdb(self, name, category_id, owner, description="", user_group_permissions=None,
iam_principal_permissions=None):
"""Create a safe deposit box.
You need to refresh your token before the iam role is granted permission to the new safe deposit box.
Keyword arguments:
... | [
"def",
"create_sdb",
"(",
"self",
",",
"name",
",",
"category_id",
",",
"owner",
",",
"description",
"=",
"\"\"",
",",
"user_group_permissions",
"=",
"None",
",",
"iam_principal_permissions",
"=",
"None",
")",
":",
"# Do some sanity checking",
"if",
"user_group_pe... | 51.384615 | 25.025641 |
def execute(self):
""" This function Executes the program with set arguments. """
prog_cmd = self.get_cmd().strip()
if prog_cmd == '':
self.status = 'Failure'
debug.log("Error: No program to execute for %s!"%self.name)
debug.log(("Could not combine path and arguments into cm... | [
"def",
"execute",
"(",
"self",
")",
":",
"prog_cmd",
"=",
"self",
".",
"get_cmd",
"(",
")",
".",
"strip",
"(",
")",
"if",
"prog_cmd",
"==",
"''",
":",
"self",
".",
"status",
"=",
"'Failure'",
"debug",
".",
"log",
"(",
"\"Error: No program to execute for ... | 41.775 | 15.4 |
def bind(self, args, kwargs):
"""
Bind arguments and keyword arguments to the encapsulated function.
Returns a dictionary of parameters (named according to function
parameters) with the values that were bound to each name.
"""
spec = self._spec
resolution = self.... | [
"def",
"bind",
"(",
"self",
",",
"args",
",",
"kwargs",
")",
":",
"spec",
"=",
"self",
".",
"_spec",
"resolution",
"=",
"self",
".",
"resolve",
"(",
"args",
",",
"kwargs",
")",
"params",
"=",
"dict",
"(",
"zip",
"(",
"spec",
".",
"args",
",",
"re... | 37.176471 | 16.117647 |
def _pin_mongos(self, server):
"""Pin this session to the given mongos Server."""
self._transaction.sharded = True
self._transaction.pinned_address = server.description.address | [
"def",
"_pin_mongos",
"(",
"self",
",",
"server",
")",
":",
"self",
".",
"_transaction",
".",
"sharded",
"=",
"True",
"self",
".",
"_transaction",
".",
"pinned_address",
"=",
"server",
".",
"description",
".",
"address"
] | 49.25 | 9.75 |
def read_ipv6(self, length):
"""Read Internet Protocol version 6 (IPv6).
Structure of IPv6 header [RFC 2460]:
0 1 2 3
0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1
+-+-+-+-+-+-+-+-+-+-+-+-+-+-... | [
"def",
"read_ipv6",
"(",
"self",
",",
"length",
")",
":",
"if",
"length",
"is",
"None",
":",
"length",
"=",
"len",
"(",
"self",
")",
"_htet",
"=",
"self",
".",
"_read_ip_hextet",
"(",
")",
"_plen",
"=",
"self",
".",
"_read_unpack",
"(",
"2",
")",
"... | 48.954545 | 26.651515 |
def left(self, num=None):
"""
NOT REQUIRED, BUT EXISTS AS OPPOSITE OF right()
"""
if num == None:
return FlatList([_get_list(self)[0]])
if num <= 0:
return Null
return FlatList(_get_list(self)[:num]) | [
"def",
"left",
"(",
"self",
",",
"num",
"=",
"None",
")",
":",
"if",
"num",
"==",
"None",
":",
"return",
"FlatList",
"(",
"[",
"_get_list",
"(",
"self",
")",
"[",
"0",
"]",
"]",
")",
"if",
"num",
"<=",
"0",
":",
"return",
"Null",
"return",
"Fla... | 26.3 | 13.9 |
def plot_fit(self,**kwargs):
""" Plots the fit of the model
Returns
----------
None (plots data and the fit)
"""
import matplotlib.pyplot as plt
import seaborn as sns
figsize = kwargs.get('figsize',(10,7))
if self.latent_variables.estimated is F... | [
"def",
"plot_fit",
"(",
"self",
",",
"*",
"*",
"kwargs",
")",
":",
"import",
"matplotlib",
".",
"pyplot",
"as",
"plt",
"import",
"seaborn",
"as",
"sns",
"figsize",
"=",
"kwargs",
".",
"get",
"(",
"'figsize'",
",",
"(",
"10",
",",
"7",
")",
")",
"if... | 36.75 | 18.291667 |
def PopEvent(self):
"""Pops an event from the heap.
Returns:
tuple: containing:
int: event timestamp or None if the heap is empty
bytes: serialized event or None if the heap is empty
"""
try:
timestamp, serialized_event = heapq.heappop(self._heap)
self.data_size -= l... | [
"def",
"PopEvent",
"(",
"self",
")",
":",
"try",
":",
"timestamp",
",",
"serialized_event",
"=",
"heapq",
".",
"heappop",
"(",
"self",
".",
"_heap",
")",
"self",
".",
"data_size",
"-=",
"len",
"(",
"serialized_event",
")",
"return",
"timestamp",
",",
"se... | 24.294118 | 20.882353 |
def move_to(self, folder):
"""Moves the email to the folder specified by the folder parameter.
Args:
folder: A string containing the folder ID the message should be moved to, or a Folder instance
"""
if isinstance(folder, Folder):
self.move_to(folder.id)
... | [
"def",
"move_to",
"(",
"self",
",",
"folder",
")",
":",
"if",
"isinstance",
"(",
"folder",
",",
"Folder",
")",
":",
"self",
".",
"move_to",
"(",
"folder",
".",
"id",
")",
"else",
":",
"self",
".",
"_move_to",
"(",
"folder",
")"
] | 31.818182 | 20.727273 |
def removecolkeyword(self, columnname, keyword):
"""Remove a column keyword.
It is similar to :func:`removekeyword`.
"""
if isinstance(keyword, str):
self._removekeyword(columnname, keyword, -1)
else:
self._removekeyword(columnname, '', keyword) | [
"def",
"removecolkeyword",
"(",
"self",
",",
"columnname",
",",
"keyword",
")",
":",
"if",
"isinstance",
"(",
"keyword",
",",
"str",
")",
":",
"self",
".",
"_removekeyword",
"(",
"columnname",
",",
"keyword",
",",
"-",
"1",
")",
"else",
":",
"self",
".... | 30.2 | 15.8 |
def stats_evaluation(stats):
"""Generate an evaluation for the given pylint ``stats``."""
statement = stats.get('statement')
error = stats.get('error', 0)
warning = stats.get('warning', 0)
refactor = stats.get('refactor', 0)
convention = stats.get('convention', 0)
if not statement or statem... | [
"def",
"stats_evaluation",
"(",
"stats",
")",
":",
"statement",
"=",
"stats",
".",
"get",
"(",
"'statement'",
")",
"error",
"=",
"stats",
".",
"get",
"(",
"'error'",
",",
"0",
")",
"warning",
"=",
"stats",
".",
"get",
"(",
"'warning'",
",",
"0",
")",... | 33.785714 | 11.5 |
def translate(self):
"""Compile the variable lookup."""
ident = self.ident
expr = ex_rvalue(VARIABLE_PREFIX + ident)
return [expr], set([ident]), set() | [
"def",
"translate",
"(",
"self",
")",
":",
"ident",
"=",
"self",
".",
"ident",
"expr",
"=",
"ex_rvalue",
"(",
"VARIABLE_PREFIX",
"+",
"ident",
")",
"return",
"[",
"expr",
"]",
",",
"set",
"(",
"[",
"ident",
"]",
")",
",",
"set",
"(",
")"
] | 35.8 | 9 |
def parse_cov(cov_table, scaffold2genome):
"""
calculate genome coverage from scaffold coverage table
"""
size = {} # size[genome] = genome size
mapped = {} # mapped[genome][sample] = mapped bases
# parse coverage files
for line in open(cov_table):
line = line.strip().split('\t')
... | [
"def",
"parse_cov",
"(",
"cov_table",
",",
"scaffold2genome",
")",
":",
"size",
"=",
"{",
"}",
"# size[genome] = genome size",
"mapped",
"=",
"{",
"}",
"# mapped[genome][sample] = mapped bases",
"# parse coverage files",
"for",
"line",
"in",
"open",
"(",
"cov_table",
... | 40.473684 | 9.736842 |
def gsea_edb_parser(results_path, index=0):
"""Parse results.edb file stored under **edb** file folder.
:param results_path: the .results file located inside edb folder.
:param index: gene_set index of gmt database, used for iterating items.
:return: enrichment_term, hit_index,nes, pval, fdr.
"""
... | [
"def",
"gsea_edb_parser",
"(",
"results_path",
",",
"index",
"=",
"0",
")",
":",
"from",
"bs4",
"import",
"BeautifulSoup",
"soup",
"=",
"BeautifulSoup",
"(",
"open",
"(",
"results_path",
")",
",",
"features",
"=",
"'xml'",
")",
"tag",
"=",
"soup",
".",
"... | 40.133333 | 14.933333 |
def to_json(self):
"""Return a JSON-serializable representation."""
return {
'network': self.network,
'state': self.state,
'nodes': self.node_indices,
'cut': self.cut,
} | [
"def",
"to_json",
"(",
"self",
")",
":",
"return",
"{",
"'network'",
":",
"self",
".",
"network",
",",
"'state'",
":",
"self",
".",
"state",
",",
"'nodes'",
":",
"self",
".",
"node_indices",
",",
"'cut'",
":",
"self",
".",
"cut",
",",
"}"
] | 29.25 | 12.75 |
def write_geno(data, sidx):
"""
write the geno output formerly used by admixture, still supported by
adegenet, perhaps. Also, sNMF still likes .geno.
"""
## grab snp and bis data from tmparr
start = time.time()
tmparrs = os.path.join(data.dirs.outfiles, "tmp-{}.h5".format(data.name))
... | [
"def",
"write_geno",
"(",
"data",
",",
"sidx",
")",
":",
"## grab snp and bis data from tmparr",
"start",
"=",
"time",
".",
"time",
"(",
")",
"tmparrs",
"=",
"os",
".",
"path",
".",
"join",
"(",
"data",
".",
"dirs",
".",
"outfiles",
",",
"\"tmp-{}.h5\"",
... | 39.849315 | 23.465753 |
def parse_backend(backend):
"""Converts the "backend" into the database connection parameters.
It returns a (scheme, host, params) tuple."""
r = urlparse.urlsplit(backend)
scheme, host = r.scheme, r.netloc
path, query = r.path, r.query
if path and not query:
query, path = path, ''
... | [
"def",
"parse_backend",
"(",
"backend",
")",
":",
"r",
"=",
"urlparse",
".",
"urlsplit",
"(",
"backend",
")",
"scheme",
",",
"host",
"=",
"r",
".",
"scheme",
",",
"r",
".",
"netloc",
"path",
",",
"query",
"=",
"r",
".",
"path",
",",
"r",
".",
"qu... | 29.789474 | 13.105263 |
def threshold_monitor_hidden_threshold_monitor_Memory_high_limit(self, **kwargs):
"""Auto Generated Code
"""
config = ET.Element("config")
threshold_monitor_hidden = ET.SubElement(config, "threshold-monitor-hidden", xmlns="urn:brocade.com:mgmt:brocade-threshold-monitor")
threshol... | [
"def",
"threshold_monitor_hidden_threshold_monitor_Memory_high_limit",
"(",
"self",
",",
"*",
"*",
"kwargs",
")",
":",
"config",
"=",
"ET",
".",
"Element",
"(",
"\"config\"",
")",
"threshold_monitor_hidden",
"=",
"ET",
".",
"SubElement",
"(",
"config",
",",
"\"thr... | 53.333333 | 25.25 |
def enterEvent(self, event):
""" Reimplemented to cancel the hide timer.
"""
super(CallTipWidget, self).enterEvent(event)
self._hide_timer.stop() | [
"def",
"enterEvent",
"(",
"self",
",",
"event",
")",
":",
"super",
"(",
"CallTipWidget",
",",
"self",
")",
".",
"enterEvent",
"(",
"event",
")",
"self",
".",
"_hide_timer",
".",
"stop",
"(",
")"
] | 34.6 | 6.6 |
def operations(self):
"""Instance depends on the API version:
* 2018-03-31: :class:`Operations<azure.mgmt.containerservice.v2018_03_31.operations.Operations>`
* 2018-08-01-preview: :class:`Operations<azure.mgmt.containerservice.v2018_08_01_preview.operations.Operations>`
* 2019... | [
"def",
"operations",
"(",
"self",
")",
":",
"api_version",
"=",
"self",
".",
"_get_api_version",
"(",
"'operations'",
")",
"if",
"api_version",
"==",
"'2018-03-31'",
":",
"from",
".",
"v2018_03_31",
".",
"operations",
"import",
"Operations",
"as",
"OperationClas... | 64 | 35.529412 |
def query_total_cat_recent(cat_id_arr, label=None, num=8, kind='1'):
'''
:param cat_id_arr: list of categories. ['0101', '0102']
:param label: the additional label
'''
if label:
return MPost.__query_with_label(
cat_id_arr,
label=label... | [
"def",
"query_total_cat_recent",
"(",
"cat_id_arr",
",",
"label",
"=",
"None",
",",
"num",
"=",
"8",
",",
"kind",
"=",
"'1'",
")",
":",
"if",
"label",
":",
"return",
"MPost",
".",
"__query_with_label",
"(",
"cat_id_arr",
",",
"label",
"=",
"label",
",",
... | 35.307692 | 20.538462 |
def gene_ids(self):
"""
Return IDs of all genes which overlap this variant. Calling
this method is significantly cheaper than calling `Variant.genes()`,
which has to issue many more queries to construct each Gene object.
"""
return self.ensembl.gene_ids_at_locus(
... | [
"def",
"gene_ids",
"(",
"self",
")",
":",
"return",
"self",
".",
"ensembl",
".",
"gene_ids_at_locus",
"(",
"self",
".",
"contig",
",",
"self",
".",
"start",
",",
"self",
".",
"end",
")"
] | 43.875 | 16.375 |
def lub(self, other):
"""
Return the least upper bound for given intervals.
:param other: AbstractInterval instance
"""
return self.__class__(
[
max(self.lower, other.lower),
max(self.upper, other.upper),
],
low... | [
"def",
"lub",
"(",
"self",
",",
"other",
")",
":",
"return",
"self",
".",
"__class__",
"(",
"[",
"max",
"(",
"self",
".",
"lower",
",",
"other",
".",
"lower",
")",
",",
"max",
"(",
"self",
".",
"upper",
",",
"other",
".",
"upper",
")",
",",
"]"... | 32.214286 | 18.214286 |
def _get_auto_rank(self, rank):
"""Tries to figure out what rank we should use for analyses"""
if rank == "auto":
# if we're an accessor for a ClassificationsDataFrame, use its _rank property
if self.__class__.__name__ == "OneCodexAccessor":
return self._rank
... | [
"def",
"_get_auto_rank",
"(",
"self",
",",
"rank",
")",
":",
"if",
"rank",
"==",
"\"auto\"",
":",
"# if we're an accessor for a ClassificationsDataFrame, use its _rank property",
"if",
"self",
".",
"__class__",
".",
"__name__",
"==",
"\"OneCodexAccessor\"",
":",
"return... | 33.357143 | 19.071429 |
def get_table_options(self, connection, table_name, schema, **kw):
"""
Return a dictionary of options specified when the table of the
given name was created.
Overrides interface
:meth:`~sqlalchemy.engine.Inspector.get_table_options`.
"""
def keyfunc(column):
... | [
"def",
"get_table_options",
"(",
"self",
",",
"connection",
",",
"table_name",
",",
"schema",
",",
"*",
"*",
"kw",
")",
":",
"def",
"keyfunc",
"(",
"column",
")",
":",
"num",
"=",
"int",
"(",
"column",
".",
"sortkey",
")",
"# If sortkey is interleaved, col... | 43.121212 | 15.909091 |
def toner_status(self, filter_supported: bool = True) -> Dict[str, Any]:
"""Return the state of all toners cartridges."""
toner_status = {}
for color in self.COLOR_NAMES:
try:
toner_stat = self.data.get(
'{}_{}'.format(SyncThru.TONER, color),... | [
"def",
"toner_status",
"(",
"self",
",",
"filter_supported",
":",
"bool",
"=",
"True",
")",
"->",
"Dict",
"[",
"str",
",",
"Any",
"]",
":",
"toner_status",
"=",
"{",
"}",
"for",
"color",
"in",
"self",
".",
"COLOR_NAMES",
":",
"try",
":",
"toner_stat",
... | 43.5 | 13.714286 |
def generate_license(template, context):
""" Generate a license by extracting variables from the template and
replacing them with the corresponding values in the given context.
"""
out = StringIO()
content = template.getvalue()
for key in extract_vars(template):
if key not in context... | [
"def",
"generate_license",
"(",
"template",
",",
"context",
")",
":",
"out",
"=",
"StringIO",
"(",
")",
"content",
"=",
"template",
".",
"getvalue",
"(",
")",
"for",
"key",
"in",
"extract_vars",
"(",
"template",
")",
":",
"if",
"key",
"not",
"in",
"con... | 43.461538 | 16.307692 |
def create_component(self, name, description=None):
"""
Create a sub component in the business component.
:param name: The new component's name.
:param description: The new component's description.
:returns: The created component.
"""
new_comp = Component(name,... | [
"def",
"create_component",
"(",
"self",
",",
"name",
",",
"description",
"=",
"None",
")",
":",
"new_comp",
"=",
"Component",
"(",
"name",
",",
"self",
".",
"gl",
",",
"description",
"=",
"description",
")",
"new_comp",
".",
"set_parent_path",
"(",
"self",... | 32.142857 | 15.857143 |
def get_file_annotate(self, path):
"""
Returns a generator of four element tuples with
lineno, sha, changeset lazy loader and line
TODO: This function now uses os underlying 'git' command which is
generally not good. Should be replaced with algorithm iterating
commit... | [
"def",
"get_file_annotate",
"(",
"self",
",",
"path",
")",
":",
"cmd",
"=",
"'blame -l --root -r %s -- \"%s\"'",
"%",
"(",
"self",
".",
"id",
",",
"path",
")",
"# -l ==> outputs long shas (and we need all 40 characters)",
"# --root ==> doesn't put '^' character for bounde... | 44.263158 | 20.473684 |
def inverse(self):
""" Inverts image (all nonzeros become zeros and vice verse)
Returns
-------
:obj:`BinaryImage`
inverse of this binary image
"""
data = np.zeros(self.shape).astype(np.uint8)
ind = np.where(self.data == 0)
data[ind[0], ind[1],... | [
"def",
"inverse",
"(",
"self",
")",
":",
"data",
"=",
"np",
".",
"zeros",
"(",
"self",
".",
"shape",
")",
".",
"astype",
"(",
"np",
".",
"uint8",
")",
"ind",
"=",
"np",
".",
"where",
"(",
"self",
".",
"data",
"==",
"0",
")",
"data",
"[",
"ind... | 34.636364 | 10.727273 |
def update_frame(self, key, ranges=None):
"""
Update the internal state of the Plot to represent the given
key tuple (where integers represent frames). Returns this
state.
"""
ranges = self.compute_ranges(self.layout, key, ranges)
for r, c in self.coords:
... | [
"def",
"update_frame",
"(",
"self",
",",
"key",
",",
"ranges",
"=",
"None",
")",
":",
"ranges",
"=",
"self",
".",
"compute_ranges",
"(",
"self",
".",
"layout",
",",
"key",
",",
"ranges",
")",
"for",
"r",
",",
"c",
"in",
"self",
".",
"coords",
":",
... | 38.5 | 11.5 |
def iter_options(grouped_choices, cutoff=None, cutoff_text=None):
"""
Helper function for options and option groups in templates.
"""
class StartOptionGroup(object):
start_option_group = True
end_option_group = False
def __init__(self, label):
self.label = label
... | [
"def",
"iter_options",
"(",
"grouped_choices",
",",
"cutoff",
"=",
"None",
",",
"cutoff_text",
"=",
"None",
")",
":",
"class",
"StartOptionGroup",
"(",
"object",
")",
":",
"start_option_group",
"=",
"True",
"end_option_group",
"=",
"False",
"def",
"__init__",
... | 30.688889 | 16.955556 |
def xcorr(x1,x2,Nlags):
"""
r12, k = xcorr(x1,x2,Nlags), r12 and k are ndarray's
Compute the energy normalized cross correlation between the sequences
x1 and x2. If x1 = x2 the cross correlation is the autocorrelation.
The number of lags sets how many lags to return centered about zero
"""
K... | [
"def",
"xcorr",
"(",
"x1",
",",
"x2",
",",
"Nlags",
")",
":",
"K",
"=",
"2",
"*",
"(",
"int",
"(",
"np",
".",
"floor",
"(",
"len",
"(",
"x1",
")",
"/",
"2",
")",
")",
")",
"X1",
"=",
"fft",
".",
"fft",
"(",
"x1",
"[",
":",
"K",
"]",
"... | 37.941176 | 13.588235 |
def parse_cache(self, full_df):
"""
Format the cached data model into a dictionary of DataFrames
and a criteria map DataFrame.
Parameters
----------
full_df : DataFrame
result of self.get_dm_offline()
Returns
----------
data_model : d... | [
"def",
"parse_cache",
"(",
"self",
",",
"full_df",
")",
":",
"data_model",
"=",
"{",
"}",
"levels",
"=",
"[",
"'specimens'",
",",
"'samples'",
",",
"'sites'",
",",
"'locations'",
",",
"'ages'",
",",
"'measurements'",
",",
"'criteria'",
",",
"'contribution'",... | 35.192308 | 17.192308 |
def list_dataset_uris(cls, base_uri, config_path):
"""Return list containing URIs with base URI."""
storage_account_name = generous_parse_uri(base_uri).netloc
blobservice = get_blob_service(storage_account_name, config_path)
containers = blobservice.list_containers(include_metadata=True... | [
"def",
"list_dataset_uris",
"(",
"cls",
",",
"base_uri",
",",
"config_path",
")",
":",
"storage_account_name",
"=",
"generous_parse_uri",
"(",
"base_uri",
")",
".",
"netloc",
"blobservice",
"=",
"get_blob_service",
"(",
"storage_account_name",
",",
"config_path",
")... | 33.833333 | 18.166667 |
def github_belspec_files(spec_dir, force: bool = False):
"""Get belspec files from Github repo
Args:
spec_dir: directory to store the BEL Specification and derived files
force: force update of BEL Specifications from Github - skipped if local files less than 1 day old
"""
if not force... | [
"def",
"github_belspec_files",
"(",
"spec_dir",
",",
"force",
":",
"bool",
"=",
"False",
")",
":",
"if",
"not",
"force",
":",
"dtnow",
"=",
"datetime",
".",
"datetime",
".",
"utcnow",
"(",
")",
"delta",
"=",
"datetime",
".",
"timedelta",
"(",
"1",
")",... | 36.956522 | 25.391304 |
def _parse_sod_segment(self, fptr):
"""Parse the SOD (start-of-data) segment.
Parameters
----------
fptr : file
Open file object.
Returns
-------
SODSegment
The current SOD segment.
"""
offset = fptr.tell() - 2
len... | [
"def",
"_parse_sod_segment",
"(",
"self",
",",
"fptr",
")",
":",
"offset",
"=",
"fptr",
".",
"tell",
"(",
")",
"-",
"2",
"length",
"=",
"0",
"return",
"SODsegment",
"(",
"length",
",",
"offset",
")"
] | 20.823529 | 18.117647 |
def _verifyDiscoveredServices(self, claimed_id, services,
to_match_endpoints):
"""See @L{_discoverAndVerify}"""
# Search the services resulting from discovery to find one
# that matches the information from the assertion
failure_messages = []
fo... | [
"def",
"_verifyDiscoveredServices",
"(",
"self",
",",
"claimed_id",
",",
"services",
",",
"to_match_endpoints",
")",
":",
"# Search the services resulting from discovery to find one",
"# that matches the information from the assertion",
"failure_messages",
"=",
"[",
"]",
"for",
... | 43.923077 | 17.538462 |
def send(self, packet, recalculate_checksum=True):
"""
Injects a packet into the network stack.
Recalculates the checksum before sending unless recalculate_checksum=False is passed.
The injected packet may be one received from recv(), or a modified version, or a completely new packet.
... | [
"def",
"send",
"(",
"self",
",",
"packet",
",",
"recalculate_checksum",
"=",
"True",
")",
":",
"if",
"recalculate_checksum",
":",
"packet",
".",
"recalculate_checksums",
"(",
")",
"send_len",
"=",
"c_uint",
"(",
"0",
")",
"if",
"PY2",
":",
"# .from_buffer(me... | 39.057143 | 23 |
def month_crumb(date):
"""
Crumb for a month.
"""
year = date.strftime('%Y')
month = date.strftime('%m')
month_text = DateFormat(date).format('F').capitalize()
return Crumb(month_text, reverse('zinnia:entry_archive_month',
args=[year, month])) | [
"def",
"month_crumb",
"(",
"date",
")",
":",
"year",
"=",
"date",
".",
"strftime",
"(",
"'%Y'",
")",
"month",
"=",
"date",
".",
"strftime",
"(",
"'%m'",
")",
"month_text",
"=",
"DateFormat",
"(",
"date",
")",
".",
"format",
"(",
"'F'",
")",
".",
"c... | 33.333333 | 12.888889 |
def widths_in_range_mm(
self,
minwidth=EMIR_MINIMUM_SLITLET_WIDTH_MM,
maxwidth=EMIR_MAXIMUM_SLITLET_WIDTH_MM
):
"""Return list of slitlets which width is within given range
Parameters
----------
minwidth : float
Minimum slit width (mm)... | [
"def",
"widths_in_range_mm",
"(",
"self",
",",
"minwidth",
"=",
"EMIR_MINIMUM_SLITLET_WIDTH_MM",
",",
"maxwidth",
"=",
"EMIR_MAXIMUM_SLITLET_WIDTH_MM",
")",
":",
"list_ok",
"=",
"[",
"]",
"for",
"i",
"in",
"range",
"(",
"EMIR_NBARS",
")",
":",
"slitlet_ok",
"=",... | 26.068966 | 19.62069 |
def get_canonical_transaction(self, transaction_hash: Hash32) -> BaseTransaction:
"""
Returns the requested transaction as specified by the transaction hash
from the canonical chain.
Raises TransactionNotFound if no transaction with the specified hash is
found in the main chain.... | [
"def",
"get_canonical_transaction",
"(",
"self",
",",
"transaction_hash",
":",
"Hash32",
")",
"->",
"BaseTransaction",
":",
"(",
"block_num",
",",
"index",
")",
"=",
"self",
".",
"chaindb",
".",
"get_transaction_index",
"(",
"transaction_hash",
")",
"VM_class",
... | 37.192308 | 22.576923 |
def _releaseId(self, msgId):
"""
Release message ID to the pool.
@param msgId: message ID, no longer on the wire
@type msgId: C{str}
"""
self._uuids.append(msgId)
if len(self._uuids) > 2 * self.UUID_POOL_GEN_SIZE:
self._uuids[-self.UUID_POOL_GEN_SIZE:... | [
"def",
"_releaseId",
"(",
"self",
",",
"msgId",
")",
":",
"self",
".",
"_uuids",
".",
"append",
"(",
"msgId",
")",
"if",
"len",
"(",
"self",
".",
"_uuids",
")",
">",
"2",
"*",
"self",
".",
"UUID_POOL_GEN_SIZE",
":",
"self",
".",
"_uuids",
"[",
"-",... | 31.7 | 12.1 |
def task_done(self):
"""Mark a task as done."""
with self._lock:
unfinished = self._unfinished_tasks - 1
if unfinished < 0:
raise RuntimeError('task_done() called too many times')
elif unfinished == 0:
self._alldone.notify()
... | [
"def",
"task_done",
"(",
"self",
")",
":",
"with",
"self",
".",
"_lock",
":",
"unfinished",
"=",
"self",
".",
"_unfinished_tasks",
"-",
"1",
"if",
"unfinished",
"<",
"0",
":",
"raise",
"RuntimeError",
"(",
"'task_done() called too many times'",
")",
"elif",
... | 38.666667 | 11.555556 |
def tupleize(
rows,
alphabetize_columns=getattr(
settings,
'ALPHABETIZE_COLUMNS',
False)):
"""Also alphabetizes columns and returns a tuple of tuples"""
# define a blank list as our return object
l = []
for r in rows:
row = []
row = list(r.val... | [
"def",
"tupleize",
"(",
"rows",
",",
"alphabetize_columns",
"=",
"getattr",
"(",
"settings",
",",
"'ALPHABETIZE_COLUMNS'",
",",
"False",
")",
")",
":",
"# define a blank list as our return object\r",
"l",
"=",
"[",
"]",
"for",
"r",
"in",
"rows",
":",
"row",
"=... | 22.227273 | 19.590909 |
def stats_tube(self, tube: str) -> Stats:
"""Returns tube statistics.
:param tube: The tube to return statistics for.
"""
return self._stats_cmd(b'stats-tube %b' % tube.encode('ascii')) | [
"def",
"stats_tube",
"(",
"self",
",",
"tube",
":",
"str",
")",
"->",
"Stats",
":",
"return",
"self",
".",
"_stats_cmd",
"(",
"b'stats-tube %b'",
"%",
"tube",
".",
"encode",
"(",
"'ascii'",
")",
")"
] | 35.5 | 14.5 |
def docSetRootElement(self, doc):
"""Set the root element of the document (doc->children is a
list containing possibly comments, PIs, etc ...). """
if doc is None: doc__o = None
else: doc__o = doc._o
ret = libxml2mod.xmlDocSetRootElement(doc__o, self._o)
if ret is None... | [
"def",
"docSetRootElement",
"(",
"self",
",",
"doc",
")",
":",
"if",
"doc",
"is",
"None",
":",
"doc__o",
"=",
"None",
"else",
":",
"doc__o",
"=",
"doc",
".",
"_o",
"ret",
"=",
"libxml2mod",
".",
"xmlDocSetRootElement",
"(",
"doc__o",
",",
"self",
".",
... | 42.111111 | 8.444444 |
def is_draft_version(self):
""" Return if this version is the draft version of a layer """
pub_ver = getattr(self, 'published_version', None)
latest_ver = getattr(self, 'latest_version', None)
this_ver = getattr(self, 'this_version', None)
return this_ver and latest_ver and (this... | [
"def",
"is_draft_version",
"(",
"self",
")",
":",
"pub_ver",
"=",
"getattr",
"(",
"self",
",",
"'published_version'",
",",
"None",
")",
"latest_ver",
"=",
"getattr",
"(",
"self",
",",
"'latest_version'",
",",
"None",
")",
"this_ver",
"=",
"getattr",
"(",
"... | 60.333333 | 19.666667 |
def to_bool(x):
""""Converts to a boolean in a semantically meaningful way."""
if isinstance(x, bool):
return x
elif isinstance(x, str):
return False if x.lower() in _FALSES else True
else:
return bool(x) | [
"def",
"to_bool",
"(",
"x",
")",
":",
"if",
"isinstance",
"(",
"x",
",",
"bool",
")",
":",
"return",
"x",
"elif",
"isinstance",
"(",
"x",
",",
"str",
")",
":",
"return",
"False",
"if",
"x",
".",
"lower",
"(",
")",
"in",
"_FALSES",
"else",
"True",... | 29.625 | 17.125 |
def execute_fragment_under_context(self, ctx, start_label, end_label):
''' just like run but returns if moved outside of the specified fragment
# 4 different exectution results
# 0=normal, 1=return, 2=jump_outside, 3=errors
# execute_fragment_under_context returns:
... | [
"def",
"execute_fragment_under_context",
"(",
"self",
",",
"ctx",
",",
"start_label",
",",
"end_label",
")",
":",
"old_curr_ctx",
"=",
"self",
".",
"current_ctx",
"self",
".",
"ctx_depth",
"+=",
"1",
"old_stack_len",
"=",
"len",
"(",
"ctx",
".",
"stack",
")"... | 45.655172 | 14.689655 |
def delete_chat_photo(chat_id, **kwargs):
"""
Use this method to delete a chat photo. Photos can't be changed for private chats. The bot must be an administrator in the chat
for this to work and must have the appropriate admin rights.
:param chat_id: Unique identifier for the target chat or username of... | [
"def",
"delete_chat_photo",
"(",
"chat_id",
",",
"*",
"*",
"kwargs",
")",
":",
"# required args",
"params",
"=",
"dict",
"(",
"chat_id",
"=",
"chat_id",
")",
"return",
"TelegramBotRPCRequest",
"(",
"'deleteChatPhoto'",
",",
"params",
"=",
"params",
",",
"on_re... | 47.642857 | 31.5 |
def create_key(file_):
"""
Create a key and save it into ``file_``.
Note that ``file`` must be opened in binary mode.
"""
pkey = crypto.PKey()
pkey.generate_key(crypto.TYPE_RSA, 2048)
file_.write(crypto.dump_privatekey(crypto.FILETYPE_PEM, pkey))
file_.flush() | [
"def",
"create_key",
"(",
"file_",
")",
":",
"pkey",
"=",
"crypto",
".",
"PKey",
"(",
")",
"pkey",
".",
"generate_key",
"(",
"crypto",
".",
"TYPE_RSA",
",",
"2048",
")",
"file_",
".",
"write",
"(",
"crypto",
".",
"dump_privatekey",
"(",
"crypto",
".",
... | 25.818182 | 16.727273 |
def create_embedded_class(self, method):
"""
Build the estimator class.
Returns
-------
:return : string
The built class as string.
"""
temp_class = self.temp('embedded.class')
return temp_class.format(class_name=self.class_name,
... | [
"def",
"create_embedded_class",
"(",
"self",
",",
"method",
")",
":",
"temp_class",
"=",
"self",
".",
"temp",
"(",
"'embedded.class'",
")",
"return",
"temp_class",
".",
"format",
"(",
"class_name",
"=",
"self",
".",
"class_name",
",",
"method_name",
"=",
"se... | 33.307692 | 15.307692 |
def get_doc_lengths(self):
'''
Returns a list of document lengths in words
Returns
-------
np.array
'''
idx_to_delete_list = self._build_term_index_list(True, self._get_non_unigrams())
unigram_X, _ = self._get_X_after_delete_terms(idx_to_delete_list)
... | [
"def",
"get_doc_lengths",
"(",
"self",
")",
":",
"idx_to_delete_list",
"=",
"self",
".",
"_build_term_index_list",
"(",
"True",
",",
"self",
".",
"_get_non_unigrams",
"(",
")",
")",
"unigram_X",
",",
"_",
"=",
"self",
".",
"_get_X_after_delete_terms",
"(",
"id... | 31.363636 | 25.363636 |
def rm_job(name):
'''
Remove the specified job from the server.
CLI Example:
.. code-block:: bash
salt chronos-minion-id chronos.rm_job my-job
'''
response = salt.utils.http.query(
"{0}/scheduler/job/{1}".format(_base_url(), name),
method='DELETE',
)
return Tru... | [
"def",
"rm_job",
"(",
"name",
")",
":",
"response",
"=",
"salt",
".",
"utils",
".",
"http",
".",
"query",
"(",
"\"{0}/scheduler/job/{1}\"",
".",
"format",
"(",
"_base_url",
"(",
")",
",",
"name",
")",
",",
"method",
"=",
"'DELETE'",
",",
")",
"return",... | 20.466667 | 24.2 |
def _aggregations_config(self):
"""Load aggregation configurations."""
result = {}
for ep in iter_entry_points(
group=self.entry_point_group_aggs):
for cfg in ep.load()():
if cfg['aggregation_name'] not in self.enabled_aggregations:
... | [
"def",
"_aggregations_config",
"(",
"self",
")",
":",
"result",
"=",
"{",
"}",
"for",
"ep",
"in",
"iter_entry_points",
"(",
"group",
"=",
"self",
".",
"entry_point_group_aggs",
")",
":",
"for",
"cfg",
"in",
"ep",
".",
"load",
"(",
")",
"(",
")",
":",
... | 46.111111 | 17.555556 |
def __chopStringDict(self, data):
'''Returns a dictionary of the provided raw service/host check string.'''
r = {}
d = data.split('\t')
for item in d:
item_parts = item.split('::')
if len(item_parts) == 2:
(name, value) = item_parts
e... | [
"def",
"__chopStringDict",
"(",
"self",
",",
"data",
")",
":",
"r",
"=",
"{",
"}",
"d",
"=",
"data",
".",
"split",
"(",
"'\\t'",
")",
"for",
"item",
"in",
"d",
":",
"item_parts",
"=",
"item",
".",
"split",
"(",
"'::'",
")",
"if",
"len",
"(",
"i... | 33.064516 | 20.419355 |
def run(self):
'''
Execute the runner sequence
'''
# Print documentation only
if self.opts.get('doc', False):
self.print_docs()
else:
return self._run_runner() | [
"def",
"run",
"(",
"self",
")",
":",
"# Print documentation only",
"if",
"self",
".",
"opts",
".",
"get",
"(",
"'doc'",
",",
"False",
")",
":",
"self",
".",
"print_docs",
"(",
")",
"else",
":",
"return",
"self",
".",
"_run_runner",
"(",
")"
] | 24.777778 | 15.222222 |
def tile_coord(self, xtile, ytile, zoom):
"""
This returns the NW-corner of the square. Use the function
with xtile+1 and/or ytile+1 to get the other corners.
With xtile+0.5 & ytile+0.5 it will return the center of the tile.
http://wiki.openstreetmap.org/wiki/Slippy_map_tilenames... | [
"def",
"tile_coord",
"(",
"self",
",",
"xtile",
",",
"ytile",
",",
"zoom",
")",
":",
"assert",
"self",
".",
"tile_srid",
"==",
"3857",
",",
"'Custom tile projection not supported yet'",
"n",
"=",
"2.0",
"**",
"zoom",
"lon_deg",
"=",
"xtile",
"/",
"n",
"*",... | 49.538462 | 17.846154 |
def ilike_helper(default):
"""Helper function that performs an `ilike` query if a string value
is passed, otherwise the normal default operation."""
@functools.wraps(default)
def wrapped(x, y):
# String values should use ILIKE queries.
if isinstance(y, six.string_types) and not isinstanc... | [
"def",
"ilike_helper",
"(",
"default",
")",
":",
"@",
"functools",
".",
"wraps",
"(",
"default",
")",
"def",
"wrapped",
"(",
"x",
",",
"y",
")",
":",
"# String values should use ILIKE queries.",
"if",
"isinstance",
"(",
"y",
",",
"six",
".",
"string_types",
... | 39.727273 | 13.545455 |
def _strategy(codes, context):
"""
Convert SRE regex parse tree to strategy that generates strings matching that
regex represented by that parse tree.
`codes` is either a list of SRE regex elements representations or a particular
element representation. Each element is a tuple of element code (as s... | [
"def",
"_strategy",
"(",
"codes",
",",
"context",
")",
":",
"if",
"not",
"isinstance",
"(",
"codes",
",",
"tuple",
")",
":",
"# List of codes",
"strategies",
"=",
"[",
"]",
"i",
"=",
"0",
"while",
"i",
"<",
"len",
"(",
"codes",
")",
":",
"if",
"cod... | 36.225 | 20.2875 |
def fastaAlignmentRead(fasta, mapFn=(lambda x : x), l=None):
"""
reads in columns of multiple alignment and returns them iteratively
"""
if l is None:
l = _getMultiFastaOffsets(fasta)
else:
l = l[:]
seqNo = len(l)
for i in xrange(0, seqNo):
j = open(fasta, 'r')
... | [
"def",
"fastaAlignmentRead",
"(",
"fasta",
",",
"mapFn",
"=",
"(",
"lambda",
"x",
":",
"x",
")",
",",
"l",
"=",
"None",
")",
":",
"if",
"l",
"is",
"None",
":",
"l",
"=",
"_getMultiFastaOffsets",
"(",
"fasta",
")",
"else",
":",
"l",
"=",
"l",
"[",... | 30.709677 | 14.322581 |
def _update_data_dict(self, data_dict, back_or_front):
"""
Adds spct if relevant, adds service
"""
data_dict['back_or_front'] = back_or_front
# The percentage of used sessions based on 'scur' and 'slim'
if 'slim' in data_dict and 'scur' in data_dict:
try:
... | [
"def",
"_update_data_dict",
"(",
"self",
",",
"data_dict",
",",
"back_or_front",
")",
":",
"data_dict",
"[",
"'back_or_front'",
"]",
"=",
"back_or_front",
"# The percentage of used sessions based on 'scur' and 'slim'",
"if",
"'slim'",
"in",
"data_dict",
"and",
"'scur'",
... | 41.727273 | 15 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.