text stringlengths 89 104k | code_tokens list | avg_line_len float64 7.91 980 | score float64 0 630 |
|---|---|---|---|
def get_pg_core(connection_string, *, cursor_factory=None, edit_connection=None):
"""Creates a simple PostgreSQL core. Requires the psycopg2 library."""
import psycopg2 as pq
from psycopg2.extras import NamedTupleCursor
def opener():
"""Opens a single PostgreSQL connection with the scope-captured connectio... | [
"def",
"get_pg_core",
"(",
"connection_string",
",",
"*",
",",
"cursor_factory",
"=",
"None",
",",
"edit_connection",
"=",
"None",
")",
":",
"import",
"psycopg2",
"as",
"pq",
"from",
"psycopg2",
".",
"extras",
"import",
"NamedTupleCursor",
"def",
"opener",
"("... | 34.045455 | 15.545455 |
def errors(self):
"""
Computes and returns the error and standard deviation of the
filter at this time step.
Returns
-------
error : np.array size 1xorder+1
std : np.array size 1xorder+1
"""
n = self.n
dt = self.dt
order = self._... | [
"def",
"errors",
"(",
"self",
")",
":",
"n",
"=",
"self",
".",
"n",
"dt",
"=",
"self",
".",
"dt",
"order",
"=",
"self",
".",
"_order",
"sigma",
"=",
"self",
".",
"sigma",
"error",
"=",
"np",
".",
"zeros",
"(",
"order",
"+",
"1",
")",
"std",
"... | 29.959184 | 22.285714 |
def show_progress(self, message=None):
"""If we are in a progress scope, and no log messages have been
shown, write out another '.'"""
if self.in_progress_hanging:
if message is None:
sys.stdout.write('.')
sys.stdout.flush()
else:
... | [
"def",
"show_progress",
"(",
"self",
",",
"message",
"=",
"None",
")",
":",
"if",
"self",
".",
"in_progress_hanging",
":",
"if",
"message",
"is",
"None",
":",
"sys",
".",
"stdout",
".",
"write",
"(",
"'.'",
")",
"sys",
".",
"stdout",
".",
"flush",
"(... | 43.4 | 12.466667 |
def fn_from_str(name: str) -> Callable[..., Any]:
"""Returns a function object with the name given in string."""
try:
module_name, fn_name = name.split(':')
except ValueError:
raise ConfigError('Expected function description in a `module.submodules:function_name` form, but got `{}`'
... | [
"def",
"fn_from_str",
"(",
"name",
":",
"str",
")",
"->",
"Callable",
"[",
"...",
",",
"Any",
"]",
":",
"try",
":",
"module_name",
",",
"fn_name",
"=",
"name",
".",
"split",
"(",
"':'",
")",
"except",
"ValueError",
":",
"raise",
"ConfigError",
"(",
"... | 45.666667 | 22.777778 |
def _transform_snapshot(raw_snapshot: str) -> str:
"""
The transformation step does the following:
1. Add `allocated_fee` to all initiator tasks
2. Adds `mediation_fee` to all channels
3. Populates tokennetworkaddresses_to_paymentnetworkaddresses in chain state
"""
snapshot = json.loads(raw_... | [
"def",
"_transform_snapshot",
"(",
"raw_snapshot",
":",
"str",
")",
"->",
"str",
":",
"snapshot",
"=",
"json",
".",
"loads",
"(",
"raw_snapshot",
")",
"for",
"task",
"in",
"snapshot",
"[",
"'payment_mapping'",
"]",
"[",
"'secrethashes_to_task'",
"]",
".",
"v... | 54.0625 | 27.6875 |
def get_search_fields(cls):
"""
Returns search fields in sfdict
"""
sfdict = {}
for klass in tuple(cls.__bases__) + (cls, ):
if hasattr(klass, 'search_fields'):
sfdict.update(klass.search_fields)
return sfdict | [
"def",
"get_search_fields",
"(",
"cls",
")",
":",
"sfdict",
"=",
"{",
"}",
"for",
"klass",
"in",
"tuple",
"(",
"cls",
".",
"__bases__",
")",
"+",
"(",
"cls",
",",
")",
":",
"if",
"hasattr",
"(",
"klass",
",",
"'search_fields'",
")",
":",
"sfdict",
... | 30.777778 | 9.222222 |
def from_model(cls, model, *fields, **named_fields):
"""
Work-in-progress constructor,
consuming fields and values from django model instance.
"""
d = ModelDict()
if not (fields or named_fields):
# Default to all fields
fields = [f.attname for f i... | [
"def",
"from_model",
"(",
"cls",
",",
"model",
",",
"*",
"fields",
",",
"*",
"*",
"named_fields",
")",
":",
"d",
"=",
"ModelDict",
"(",
")",
"if",
"not",
"(",
"fields",
"or",
"named_fields",
")",
":",
"# Default to all fields",
"fields",
"=",
"[",
"f",... | 34.906977 | 17.697674 |
def get_time(self, instance):
"""
Return the current mission time for the specified instance.
:rtype: ~datetime.datetime
"""
url = '/instances/{}'.format(instance)
response = self.get_proto(url)
message = yamcsManagement_pb2.YamcsInstance()
message.ParseF... | [
"def",
"get_time",
"(",
"self",
",",
"instance",
")",
":",
"url",
"=",
"'/instances/{}'",
".",
"format",
"(",
"instance",
")",
"response",
"=",
"self",
".",
"get_proto",
"(",
"url",
")",
"message",
"=",
"yamcsManagement_pb2",
".",
"YamcsInstance",
"(",
")"... | 35 | 11.769231 |
def compare_digests(digest_1, digest_2, is_hex_1=True, is_hex_2=True, threshold=None):
"""
computes bit difference between two nilsisa digests
takes params for format, default is hex string but can accept list
of 32 length ints
Optimized method originally from https://gist.github.com/michelp/6255490... | [
"def",
"compare_digests",
"(",
"digest_1",
",",
"digest_2",
",",
"is_hex_1",
"=",
"True",
",",
"is_hex_2",
"=",
"True",
",",
"threshold",
"=",
"None",
")",
":",
"# if we have both hexes use optimized method",
"if",
"threshold",
"is",
"not",
"None",
":",
"thresho... | 43.666667 | 21.545455 |
def ParseFileSystemsStruct(struct_class, fs_count, data):
"""Take the struct type and parse it into a list of structs."""
results = []
cstr = lambda x: x.split(b"\x00", 1)[0]
for count in range(0, fs_count):
struct_size = struct_class.GetSize()
s_data = data[count * struct_size:(count + 1) * struct_size... | [
"def",
"ParseFileSystemsStruct",
"(",
"struct_class",
",",
"fs_count",
",",
"data",
")",
":",
"results",
"=",
"[",
"]",
"cstr",
"=",
"lambda",
"x",
":",
"x",
".",
"split",
"(",
"b\"\\x00\"",
",",
"1",
")",
"[",
"0",
"]",
"for",
"count",
"in",
"range"... | 38.692308 | 10.307692 |
def installed(name, target="LocalSystem", dmg=False, store=False, app=False, mpkg=False, user=None, onlyif=None,
unless=None, force=False, allow_untrusted=False, version_check=None):
'''
Install a Mac OS Package from a pkg or dmg file, if given a dmg file it
will first be mounted in a temporar... | [
"def",
"installed",
"(",
"name",
",",
"target",
"=",
"\"LocalSystem\"",
",",
"dmg",
"=",
"False",
",",
"store",
"=",
"False",
",",
"app",
"=",
"False",
",",
"mpkg",
"=",
"False",
",",
"user",
"=",
"None",
",",
"onlyif",
"=",
"None",
",",
"unless",
... | 33.045685 | 24.213198 |
def _to_dict(self):
"""Return a json dictionary representing this model."""
_dict = {}
if hasattr(self, 'dialog_nodes') and self.dialog_nodes is not None:
_dict['dialog_nodes'] = [x._to_dict() for x in self.dialog_nodes]
if hasattr(self, 'pagination') and self.pagination is n... | [
"def",
"_to_dict",
"(",
"self",
")",
":",
"_dict",
"=",
"{",
"}",
"if",
"hasattr",
"(",
"self",
",",
"'dialog_nodes'",
")",
"and",
"self",
".",
"dialog_nodes",
"is",
"not",
"None",
":",
"_dict",
"[",
"'dialog_nodes'",
"]",
"=",
"[",
"x",
".",
"_to_di... | 50.375 | 23.25 |
def _recurse(data, obj):
"""Iterates over all children of the current object, gathers the contents
contributing to the resulting PGFPlots file, and returns those.
"""
content = _ContentManager()
for child in obj.get_children():
# Some patches are Spines, too; skip those entirely.
# S... | [
"def",
"_recurse",
"(",
"data",
",",
"obj",
")",
":",
"content",
"=",
"_ContentManager",
"(",
")",
"for",
"child",
"in",
"obj",
".",
"get_children",
"(",
")",
":",
"# Some patches are Spines, too; skip those entirely.",
"# See <https://github.com/nschloe/matplotlib2tikz... | 45.075949 | 19.202532 |
def dump_to_stream(self, cnf, stream, **kwargs):
"""
Dump config 'cnf' to a file or file-like object 'stream'.
:param cnf: Shell variables data to dump
:param stream: Shell script file or file like object
:param kwargs: backend-specific optional keyword parameters :: dict
... | [
"def",
"dump_to_stream",
"(",
"self",
",",
"cnf",
",",
"stream",
",",
"*",
"*",
"kwargs",
")",
":",
"for",
"key",
",",
"val",
"in",
"anyconfig",
".",
"compat",
".",
"iteritems",
"(",
"cnf",
")",
":",
"stream",
".",
"write",
"(",
"\"%s='%s'%s\"",
"%",... | 43.6 | 17.4 |
def _get_smallest_set_not_on_axis(self, axis):
"""
Returns the smallest list of atoms with the same species and
distance from origin AND does not lie on the specified axis. This
maximal set limits the possible rotational symmetry operations,
since atoms lying on a test axis is i... | [
"def",
"_get_smallest_set_not_on_axis",
"(",
"self",
",",
"axis",
")",
":",
"def",
"not_on_axis",
"(",
"site",
")",
":",
"v",
"=",
"np",
".",
"cross",
"(",
"site",
".",
"coords",
",",
"axis",
")",
"return",
"np",
".",
"linalg",
".",
"norm",
"(",
"v",... | 40.095238 | 18.666667 |
def setPointSize(self, pointSize):
"""
Sets the point size for this widget to the inputed size.
:param pointSize | <int>
"""
self.uiSizeSPN.blockSignals(True)
self.uiSizeSPN.setValue(pointSize)
self.uiSizeSPN.blockSignals(False)
... | [
"def",
"setPointSize",
"(",
"self",
",",
"pointSize",
")",
":",
"self",
".",
"uiSizeSPN",
".",
"blockSignals",
"(",
"True",
")",
"self",
".",
"uiSizeSPN",
".",
"setValue",
"(",
"pointSize",
")",
"self",
".",
"uiSizeSPN",
".",
"blockSignals",
"(",
"False",
... | 35.066667 | 10 |
def abort (self):
"""Print still-active URLs and empty the URL queue."""
self.print_active_threads()
self.cancel()
timeout = self.config["aborttimeout"]
try:
self.urlqueue.join(timeout=timeout)
except urlqueue.Timeout:
log.warn(LOG_CHECK, "Abort ti... | [
"def",
"abort",
"(",
"self",
")",
":",
"self",
".",
"print_active_threads",
"(",
")",
"self",
".",
"cancel",
"(",
")",
"timeout",
"=",
"self",
".",
"config",
"[",
"\"aborttimeout\"",
"]",
"try",
":",
"self",
".",
"urlqueue",
".",
"join",
"(",
"timeout"... | 40.8 | 15.8 |
def prepare_request(self, request):
"""Include the request ID, if available, in the outgoing request"""
try:
request_id = local.request_id
except AttributeError:
request_id = NO_REQUEST_ID
if self.request_id_header and request_id != NO_REQUEST_ID:
req... | [
"def",
"prepare_request",
"(",
"self",
",",
"request",
")",
":",
"try",
":",
"request_id",
"=",
"local",
".",
"request_id",
"except",
"AttributeError",
":",
"request_id",
"=",
"NO_REQUEST_ID",
"if",
"self",
".",
"request_id_header",
"and",
"request_id",
"!=",
... | 38.272727 | 17.818182 |
def bq(line, cell=None):
"""Implements the bq cell magic for ipython notebooks.
The supported syntax is:
%%bq <command> [<args>]
<cell>
or:
%bq <command> [<args>]
Use %bq --help for a list of commands, or %bq <command> --help for help
on a specific command.
"""
return google.datalab.utils... | [
"def",
"bq",
"(",
"line",
",",
"cell",
"=",
"None",
")",
":",
"return",
"google",
".",
"datalab",
".",
"utils",
".",
"commands",
".",
"handle_magic_line",
"(",
"line",
",",
"cell",
",",
"_bigquery_parser",
")"
] | 22.625 | 26.0625 |
def _prepare_output(partitions, verbose):
"""Returns dict with 'raw' and 'message' keys filled."""
out = {}
partitions_count = len(partitions)
out['raw'] = {
'not_enough_replicas_count': partitions_count,
}
if partitions_count == 0:
out['message'] = 'All replicas in sync.'
e... | [
"def",
"_prepare_output",
"(",
"partitions",
",",
"verbose",
")",
":",
"out",
"=",
"{",
"}",
"partitions_count",
"=",
"len",
"(",
"partitions",
")",
"out",
"[",
"'raw'",
"]",
"=",
"{",
"'not_enough_replicas_count'",
":",
"partitions_count",
",",
"}",
"if",
... | 31.28125 | 18.21875 |
def preprocess_dataset(dataset, labels):
""" Preprocess and prepare a dataset"""
start = time.time()
with mp.Pool() as pool:
# Each sample is processed in an asynchronous manner.
dataset = gluon.data.SimpleDataset(list(zip(dataset, labels)))
lengths = gluon.data.SimpleDataset(pool.ma... | [
"def",
"preprocess_dataset",
"(",
"dataset",
",",
"labels",
")",
":",
"start",
"=",
"time",
".",
"time",
"(",
")",
"with",
"mp",
".",
"Pool",
"(",
")",
"as",
"pool",
":",
"# Each sample is processed in an asynchronous manner.",
"dataset",
"=",
"gluon",
".",
... | 45.727273 | 16.727273 |
def chunked(iterable, n):
"""Returns chunks of n length of iterable
If len(iterable) % n != 0, then the last chunk will have length
less than n.
Example:
>>> chunked([1, 2, 3, 4, 5], 2)
[(1, 2), (3, 4), (5,)]
"""
iterable = iter(iterable)
while 1:
t = tuple(islice(iterab... | [
"def",
"chunked",
"(",
"iterable",
",",
"n",
")",
":",
"iterable",
"=",
"iter",
"(",
"iterable",
")",
"while",
"1",
":",
"t",
"=",
"tuple",
"(",
"islice",
"(",
"iterable",
",",
"n",
")",
")",
"if",
"t",
":",
"yield",
"t",
"else",
":",
"return"
] | 18.75 | 22.55 |
def GetValuesForAttribute(self, attribute, only_one=False):
"""Returns a list of values from this attribute."""
if not only_one and self.age_policy == NEWEST_TIME:
raise ValueError("Attempting to read all attribute versions for an "
"object opened for NEWEST_TIME. This is probably "... | [
"def",
"GetValuesForAttribute",
"(",
"self",
",",
"attribute",
",",
"only_one",
"=",
"False",
")",
":",
"if",
"not",
"only_one",
"and",
"self",
".",
"age_policy",
"==",
"NEWEST_TIME",
":",
"raise",
"ValueError",
"(",
"\"Attempting to read all attribute versions for ... | 38.428571 | 20.785714 |
def info_parking_poi(self, **kwargs):
"""Obtain generic information on POIs and parkings.
This returns a list of elements in a given radius from the coordinates.
Args:
radius (int): Radius of the search (in meters).
latitude (double): Latitude in decimal degrees.
... | [
"def",
"info_parking_poi",
"(",
"self",
",",
"*",
"*",
"kwargs",
")",
":",
"# Endpoint parameters",
"date",
"=",
"util",
".",
"datetime_string",
"(",
"kwargs",
".",
"get",
"(",
"'day'",
",",
"1",
")",
",",
"kwargs",
".",
"get",
"(",
"'month'",
",",
"1"... | 38.712644 | 19.149425 |
def wheel_check(self, auth_list, fun, args):
'''
Check special API permissions
'''
return self.spec_check(auth_list, fun, args, 'wheel') | [
"def",
"wheel_check",
"(",
"self",
",",
"auth_list",
",",
"fun",
",",
"args",
")",
":",
"return",
"self",
".",
"spec_check",
"(",
"auth_list",
",",
"fun",
",",
"args",
",",
"'wheel'",
")"
] | 32.8 | 17.2 |
def get_or_create_instance(self, id=None, application=None, revision=None, environment=None, name=None, parameters=None, submodules=None,
destroyInterval=None):
""" Get instance by id or name.
If not found: create with given parameters
"""
try:
... | [
"def",
"get_or_create_instance",
"(",
"self",
",",
"id",
"=",
"None",
",",
"application",
"=",
"None",
",",
"revision",
"=",
"None",
",",
"environment",
"=",
"None",
",",
"name",
"=",
"None",
",",
"parameters",
"=",
"None",
",",
"submodules",
"=",
"None"... | 51.076923 | 21.384615 |
def free(self, kind, name):
"""
Mark a node name as no longer in use.
It could thus be recycled to name a new node.
"""
try:
params = self._parse(name)
index = int(params['index'], 10)
self._free[kind].add(index)
assert index <= se... | [
"def",
"free",
"(",
"self",
",",
"kind",
",",
"name",
")",
":",
"try",
":",
"params",
"=",
"self",
".",
"_parse",
"(",
"name",
")",
"index",
"=",
"int",
"(",
"params",
"[",
"'index'",
"]",
",",
"10",
")",
"self",
".",
"_free",
"[",
"kind",
"]",... | 30.4375 | 9.8125 |
def load_from_stream(self, group):
"""Load a Group from an NCStream object."""
self._unpack_attrs(group.atts)
self.name = group.name
for dim in group.dims:
new_dim = Dimension(self, dim.name)
self.dimensions[dim.name] = new_dim
new_dim.load_from_strea... | [
"def",
"load_from_stream",
"(",
"self",
",",
"group",
")",
":",
"self",
".",
"_unpack_attrs",
"(",
"group",
".",
"atts",
")",
"self",
".",
"name",
"=",
"group",
".",
"name",
"for",
"dim",
"in",
"group",
".",
"dims",
":",
"new_dim",
"=",
"Dimension",
... | 35.344828 | 13.586207 |
def iwslt_dataset(
directory='data/iwslt/',
train=False,
dev=False,
test=False,
language_extensions=['en', 'de'],
train_filename='{source}-{target}/train.{source}-{target}.{lang}',
dev_filename='{source}-{target}/IWSLT16.TED.tst2013.{source}-{target}.{lang}',
... | [
"def",
"iwslt_dataset",
"(",
"directory",
"=",
"'data/iwslt/'",
",",
"train",
"=",
"False",
",",
"dev",
"=",
"False",
",",
"test",
"=",
"False",
",",
"language_extensions",
"=",
"[",
"'en'",
",",
"'de'",
"]",
",",
"train_filename",
"=",
"'{source}-{target}/t... | 48.598039 | 31.284314 |
def state_nums():
"""
Get a dictionary of state names mapped to their 'legend' value.
Returns:
dictionary of state names mapped to their numeric value
"""
st_nums = {}
fname = pkg_resources.resource_filename(__name__, 'resources/States.csv')
with open(fname, 'rU') as csvfile:
reader = csv.reader(... | [
"def",
"state_nums",
"(",
")",
":",
"st_nums",
"=",
"{",
"}",
"fname",
"=",
"pkg_resources",
".",
"resource_filename",
"(",
"__name__",
",",
"'resources/States.csv'",
")",
"with",
"open",
"(",
"fname",
",",
"'rU'",
")",
"as",
"csvfile",
":",
"reader",
"=",... | 26.375 | 20.25 |
def update_feed_view(self, view, feed_id, view_id, project=None):
"""UpdateFeedView.
[Preview API] Update a view.
:param :class:`<FeedView> <azure.devops.v5_1.feed.models.FeedView>` view: New settings to apply to the specified view.
:param str feed_id: Name or Id of the feed.
:pa... | [
"def",
"update_feed_view",
"(",
"self",
",",
"view",
",",
"feed_id",
",",
"view_id",
",",
"project",
"=",
"None",
")",
":",
"route_values",
"=",
"{",
"}",
"if",
"project",
"is",
"not",
"None",
":",
"route_values",
"[",
"'project'",
"]",
"=",
"self",
".... | 54.826087 | 20.695652 |
def unshorten(self, uri: str) -> str:
""" http://j.gs/AXr9 """
res = self.get(uri)
ysmm = re.findall(r'var ysmm =.*\;?', res.text)
if len(ysmm) == 0:
raise UnshortenFailed('No ysmm variable found.')
# Decode the ysmm variable and extract the actual link
ysm... | [
"def",
"unshorten",
"(",
"self",
",",
"uri",
":",
"str",
")",
"->",
"str",
":",
"res",
"=",
"self",
".",
"get",
"(",
"uri",
")",
"ysmm",
"=",
"re",
".",
"findall",
"(",
"r'var ysmm =.*\\;?'",
",",
"res",
".",
"text",
")",
"if",
"len",
"(",
"ysmm"... | 32.575758 | 22.636364 |
def create(args):
"""
cdstarcat create PATH
Create objects in CDSTAR specified by PATH.
When PATH is a file, a single object (possibly with multiple bitstreams) is created;
When PATH is a directory, an object will be created for each file in the directory
(recursing into subdirectories).
""... | [
"def",
"create",
"(",
"args",
")",
":",
"with",
"_catalog",
"(",
"args",
")",
"as",
"cat",
":",
"for",
"fname",
",",
"created",
",",
"obj",
"in",
"cat",
".",
"create",
"(",
"args",
".",
"args",
"[",
"0",
"]",
",",
"{",
"}",
")",
":",
"args",
... | 40.769231 | 19.846154 |
def set(self, value):
"""
Sets the value of the string
:param value:
A unicode string
"""
if not isinstance(value, str_cls):
raise TypeError(unwrap(
'''
%s value must be a unicode string, not %s
''',
... | [
"def",
"set",
"(",
"self",
",",
"value",
")",
":",
"if",
"not",
"isinstance",
"(",
"value",
",",
"str_cls",
")",
":",
"raise",
"TypeError",
"(",
"unwrap",
"(",
"'''\n %s value must be a unicode string, not %s\n '''",
",",
"type_name",
"... | 27.482759 | 16.310345 |
def _parse_show_output(cmd_ret):
'''
Parse the output of an aptly show command.
:param str cmd_ret: The text of the command output that needs to be parsed.
:return: A dictionary containing the configuration data.
:rtype: dict
'''
parsed_data = dict()
list_key = None
for line in cm... | [
"def",
"_parse_show_output",
"(",
"cmd_ret",
")",
":",
"parsed_data",
"=",
"dict",
"(",
")",
"list_key",
"=",
"None",
"for",
"line",
"in",
"cmd_ret",
".",
"splitlines",
"(",
")",
":",
"# Skip empty lines.",
"if",
"not",
"line",
".",
"strip",
"(",
")",
":... | 30.446809 | 25.255319 |
def invoke_command (self, cmd, args, **kwargs):
"""This function mainly exists to be overridden by subclasses."""
new_kwargs = kwargs.copy ()
new_kwargs['argv0'] = kwargs['argv0'] + ' ' + cmd.name
new_kwargs['parent'] = self
new_kwargs['parent_kwargs'] = kwargs
return cmd... | [
"def",
"invoke_command",
"(",
"self",
",",
"cmd",
",",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"new_kwargs",
"=",
"kwargs",
".",
"copy",
"(",
")",
"new_kwargs",
"[",
"'argv0'",
"]",
"=",
"kwargs",
"[",
"'argv0'",
"]",
"+",
"' '",
"+",
"cmd",
"."... | 50.428571 | 8.571429 |
def get_norm(self):
"""Return square length: x*x + y*y."""
return self.x * self.x + self.y * self.y | [
"def",
"get_norm",
"(",
"self",
")",
":",
"return",
"self",
".",
"x",
"*",
"self",
".",
"x",
"+",
"self",
".",
"y",
"*",
"self",
".",
"y"
] | 28.25 | 17.25 |
def currentMode( self ):
"""
Returns the current mode for this widget.
:return <XOrbBrowserWidget.Mode>
"""
if ( self.uiCardACT.isChecked() ):
return XOrbBrowserWidget.Mode.Card
elif ( self.uiDetailsACT.isChecked() ):
return X... | [
"def",
"currentMode",
"(",
"self",
")",
":",
"if",
"(",
"self",
".",
"uiCardACT",
".",
"isChecked",
"(",
")",
")",
":",
"return",
"XOrbBrowserWidget",
".",
"Mode",
".",
"Card",
"elif",
"(",
"self",
".",
"uiDetailsACT",
".",
"isChecked",
"(",
")",
")",
... | 33.75 | 10.416667 |
def connect(self):
"Connects to the Redis server if not already connected"
if self._sock:
return
try:
sock = self._connect()
except socket.timeout:
raise TimeoutError("Timeout connecting to server")
except socket.error:
e = sys.exc_... | [
"def",
"connect",
"(",
"self",
")",
":",
"if",
"self",
".",
"_sock",
":",
"return",
"try",
":",
"sock",
"=",
"self",
".",
"_connect",
"(",
")",
"except",
"socket",
".",
"timeout",
":",
"raise",
"TimeoutError",
"(",
"\"Timeout connecting to server\"",
")",
... | 32.44 | 18.12 |
def stage_tc_create_attribute(self, attribute_type, attribute_value, resource):
"""Add an attribute to a resource.
Args:
attribute_type (str): The attribute type (e.g., Description).
attribute_value (str): The attribute value.
resource (obj): An instance of tcex reso... | [
"def",
"stage_tc_create_attribute",
"(",
"self",
",",
"attribute_type",
",",
"attribute_value",
",",
"resource",
")",
":",
"attribute_data",
"=",
"{",
"'type'",
":",
"str",
"(",
"attribute_type",
")",
",",
"'value'",
":",
"str",
"(",
"attribute_value",
")",
"}... | 42.4 | 21.16 |
def frequencies_iter(self):
"""
Iterates over all non-zero frequencies of logical conjunction mappings in this list
Yields
------
tuple[caspo.core.mapping.Mapping, float]
The next pair (mapping,frequency)
"""
f = self.__matrix.mean(axis=0)
for... | [
"def",
"frequencies_iter",
"(",
"self",
")",
":",
"f",
"=",
"self",
".",
"__matrix",
".",
"mean",
"(",
"axis",
"=",
"0",
")",
"for",
"i",
",",
"m",
"in",
"self",
".",
"mappings",
".",
"iteritems",
"(",
")",
":",
"yield",
"m",
",",
"f",
"[",
"i"... | 30.833333 | 16 |
def query(query):
'''
Send an ADQL query to the Gaia archive,
wait for a response,
and hang on to the results.
'''
# send the query to the Gaia archive
with warnings.catch_warnings() :
warnings.filterwarnings("ignore")
_gaia_job = astroquery.gaia.Gaia.launch_job(query)
... | [
"def",
"query",
"(",
"query",
")",
":",
"# send the query to the Gaia archive",
"with",
"warnings",
".",
"catch_warnings",
"(",
")",
":",
"warnings",
".",
"filterwarnings",
"(",
"\"ignore\"",
")",
"_gaia_job",
"=",
"astroquery",
".",
"gaia",
".",
"Gaia",
".",
... | 25.266667 | 17.666667 |
def snapshot_create(repository, snapshot, body=None, hosts=None, profile=None):
'''
.. versionadded:: 2017.7.0
Create snapshot in specified repository by supplied definition.
repository
Repository name
snapshot
Snapshot name
body
Snapshot definition as in https://www.el... | [
"def",
"snapshot_create",
"(",
"repository",
",",
"snapshot",
",",
"body",
"=",
"None",
",",
"hosts",
"=",
"None",
",",
"profile",
"=",
"None",
")",
":",
"es",
"=",
"_get_instance",
"(",
"hosts",
",",
"profile",
")",
"try",
":",
"response",
"=",
"es",
... | 38.84 | 38.44 |
def interleave_planes(ipixels, apixels, ipsize, apsize):
"""
Interleave (colour) planes, e.g. RGB + A = RGBA.
Return an array of pixels consisting of the `ipsize` elements of
data from each pixel in `ipixels` followed by the `apsize` elements
of data from each pixel in `apixels`. Conventionally `i... | [
"def",
"interleave_planes",
"(",
"ipixels",
",",
"apixels",
",",
"ipsize",
",",
"apsize",
")",
":",
"itotal",
"=",
"len",
"(",
"ipixels",
")",
"atotal",
"=",
"len",
"(",
"apixels",
")",
"newtotal",
"=",
"itotal",
"+",
"atotal",
"newpsize",
"=",
"ipsize",... | 39.37931 | 18.965517 |
def remove_router_from_hosting_device(self, context, hosting_device_id,
router_id):
"""Remove the router from hosting device.
After removal, the router will be non-hosted until there is update
which leads to re-schedule or be added to another hosting de... | [
"def",
"remove_router_from_hosting_device",
"(",
"self",
",",
"context",
",",
"hosting_device_id",
",",
"router_id",
")",
":",
"e_context",
"=",
"context",
".",
"elevated",
"(",
")",
"r_hd_binding_db",
"=",
"self",
".",
"_get_router_binding_info",
"(",
"e_context",
... | 54.357143 | 21.142857 |
def unzip(i):
"""
Input: {
(data_uoa) - repo UOA where to unzip (default, if not specified)
zip - path to zipfile (local or remote http/ftp)
(overwrite) - if 'yes', overwrite files when unarchiving
}
Output: {
return ... | [
"def",
"unzip",
"(",
"i",
")",
":",
"o",
"=",
"i",
".",
"get",
"(",
"'out'",
",",
"''",
")",
"duoa",
"=",
"i",
".",
"get",
"(",
"'data_uoa'",
",",
"''",
")",
"if",
"duoa",
"==",
"''",
":",
"duoa",
"=",
"'local'",
"overwrite",
"=",
"i",
".",
... | 24.810811 | 24.432432 |
def equally_spaced_points(self, point, distance):
"""
Compute the set of points equally spaced between this point
and the given point.
:param point:
Destination point.
:type point:
Instance of :class:`Point`
:param distance:
Distance b... | [
"def",
"equally_spaced_points",
"(",
"self",
",",
"point",
",",
"distance",
")",
":",
"lons",
",",
"lats",
",",
"depths",
"=",
"geodetic",
".",
"intervals_between",
"(",
"self",
".",
"longitude",
",",
"self",
".",
"latitude",
",",
"self",
".",
"depth",
"... | 33.478261 | 15.652174 |
def fetch(self, endpoint=None, page=1, **kwargs):
"""Returns the results of an API call.
This is the main work horse of the class. It builds the API query
string and sends the request to MetaSmoke. If there are multiple
pages of results, and we've configured `max_pages` to b... | [
"def",
"fetch",
"(",
"self",
",",
"endpoint",
"=",
"None",
",",
"page",
"=",
"1",
",",
"*",
"*",
"kwargs",
")",
":",
"if",
"not",
"endpoint",
":",
"raise",
"ValueError",
"(",
"'No endpoint provided.'",
")",
"self",
".",
"_endpoint",
"=",
"endpoint",
"p... | 39.07377 | 25.557377 |
def get(self, doc_id):
"""Retrieve the specified document."""
resp_dict = self._get_query(q='id:{}'.format(doc_id))
if resp_dict['response']['numFound'] > 0:
return resp_dict['response']['docs'][0] | [
"def",
"get",
"(",
"self",
",",
"doc_id",
")",
":",
"resp_dict",
"=",
"self",
".",
"_get_query",
"(",
"q",
"=",
"'id:{}'",
".",
"format",
"(",
"doc_id",
")",
")",
"if",
"resp_dict",
"[",
"'response'",
"]",
"[",
"'numFound'",
"]",
">",
"0",
":",
"re... | 45.8 | 11.8 |
def get(self, file_id):
"""Get a file from GridFS by ``"_id"``.
Returns an instance of :class:`~gridfs.grid_file.GridOut`,
which provides a file-like interface for reading.
:Parameters:
- `file_id`: ``"_id"`` of the file to get
.. versionadded:: 1.6
"""
... | [
"def",
"get",
"(",
"self",
",",
"file_id",
")",
":",
"def",
"ok",
"(",
"doc",
")",
":",
"if",
"doc",
"is",
"None",
":",
"raise",
"NoFile",
"(",
"\"TxMongo: no file in gridfs with _id {0}\"",
".",
"format",
"(",
"repr",
"(",
"file_id",
")",
")",
")",
"r... | 33.823529 | 23.470588 |
def wait_for_consumers(self, timeout):
"""Wait until some consumer shows up (without wasting resources).
Returns True if the wait was successful, False if the timeout expired.
"""
return bool(lib.lsl_wait_for_consumers(self.obj, c_double(timeout))) | [
"def",
"wait_for_consumers",
"(",
"self",
",",
"timeout",
")",
":",
"return",
"bool",
"(",
"lib",
".",
"lsl_wait_for_consumers",
"(",
"self",
".",
"obj",
",",
"c_double",
"(",
"timeout",
")",
")",
")"
] | 39.428571 | 22.285714 |
def get_info(self):
"""Get current configuration info from 'v' command."""
re_info = re.compile(r'\[.*\]')
self._write_cmd('v')
while True:
line = self._serial.readline()
try:
line = line.encode().decode('utf-8')
except AttributeError:... | [
"def",
"get_info",
"(",
"self",
")",
":",
"re_info",
"=",
"re",
".",
"compile",
"(",
"r'\\[.*\\]'",
")",
"self",
".",
"_write_cmd",
"(",
"'v'",
")",
"while",
"True",
":",
"line",
"=",
"self",
".",
"_serial",
".",
"readline",
"(",
")",
"try",
":",
"... | 30.6 | 13.8 |
def setVerCrossPlotAutoRangeOn(self, axisNumber):
""" Sets the vertical cross-hair plot's auto-range on for the axis with number axisNumber.
:param axisNumber: 0 (X-axis), 1 (Y-axis), 2, (Both X and Y axes).
"""
setXYAxesAutoRangeOn(self, self.verCrossPlotRangeCti, self.yAxisRangeCt... | [
"def",
"setVerCrossPlotAutoRangeOn",
"(",
"self",
",",
"axisNumber",
")",
":",
"setXYAxesAutoRangeOn",
"(",
"self",
",",
"self",
".",
"verCrossPlotRangeCti",
",",
"self",
".",
"yAxisRangeCti",
",",
"axisNumber",
")"
] | 54.833333 | 23.333333 |
def _local_info(self, args):
'''
List info for a package file
'''
if len(args) < 2:
raise SPMInvocationError('A package filename must be specified')
pkg_file = args[1]
if not os.path.exists(pkg_file):
raise SPMInvocationError('Package file {0} no... | [
"def",
"_local_info",
"(",
"self",
",",
"args",
")",
":",
"if",
"len",
"(",
"args",
")",
"<",
"2",
":",
"raise",
"SPMInvocationError",
"(",
"'A package filename must be specified'",
")",
"pkg_file",
"=",
"args",
"[",
"1",
"]",
"if",
"not",
"os",
".",
"pa... | 32.090909 | 22.727273 |
def load_steps_impl(self, registry, path, module_names=None):
"""
Load the step implementations at the given path, with the given module names. If
module_names is None then the module 'steps' is searched by default.
"""
if not module_names:
module_names = ['steps']
... | [
"def",
"load_steps_impl",
"(",
"self",
",",
"registry",
",",
"path",
",",
"module_names",
"=",
"None",
")",
":",
"if",
"not",
"module_names",
":",
"module_names",
"=",
"[",
"'steps'",
"]",
"path",
"=",
"os",
".",
"path",
".",
"abspath",
"(",
"path",
")... | 41.875 | 20.708333 |
def _all_queue_names(self):
"""
Return a list of all unique queue names in our config.
:return: list of all queue names (str)
:rtype: :std:term:`list`
"""
queues = set()
endpoints = self.config.get('endpoints')
for e in endpoints:
for q in end... | [
"def",
"_all_queue_names",
"(",
"self",
")",
":",
"queues",
"=",
"set",
"(",
")",
"endpoints",
"=",
"self",
".",
"config",
".",
"get",
"(",
"'endpoints'",
")",
"for",
"e",
"in",
"endpoints",
":",
"for",
"q",
"in",
"endpoints",
"[",
"e",
"]",
"[",
"... | 29.846154 | 11.846154 |
def _stack_effect3(op_code, oparg):
"""Compute the effect an op_code and oparg have on the stack. See python/compile.c."""
if op_code == 'UNPACK_SEQUENCE':
return oparg - 1
if op_code == 'UNPACK_EX':
return (oparg & 0xFF) + (oparg >> 8)
if op_code == 'BUILD_TUPLE':
return -oparg # Was 1 - oparg
... | [
"def",
"_stack_effect3",
"(",
"op_code",
",",
"oparg",
")",
":",
"if",
"op_code",
"==",
"'UNPACK_SEQUENCE'",
":",
"return",
"oparg",
"-",
"1",
"if",
"op_code",
"==",
"'UNPACK_EX'",
":",
"return",
"(",
"oparg",
"&",
"0xFF",
")",
"+",
"(",
"oparg",
">>",
... | 38.061224 | 12.408163 |
def add_metric_group_definition(self, definition):
"""
Add a faked metric group definition.
The definition will be used:
* For later addition of faked metrics responses.
* For returning the metric-group-info objects in the response of the
Create Metrics Context operat... | [
"def",
"add_metric_group_definition",
"(",
"self",
",",
"definition",
")",
":",
"assert",
"isinstance",
"(",
"definition",
",",
"FakedMetricGroupDefinition",
")",
"group_name",
"=",
"definition",
".",
"name",
"if",
"group_name",
"in",
"self",
".",
"_metric_group_def... | 36.310345 | 22.103448 |
def flush(self, dispatch = True):
"""Read all events currently in the queue and dispatch them to the
handlers unless `dispatch` is `False`.
Note: If the queue contains `QUIT` the events after it won't be
removed.
:Parameters:
- `dispatch`: if the events should be ha... | [
"def",
"flush",
"(",
"self",
",",
"dispatch",
"=",
"True",
")",
":",
"if",
"dispatch",
":",
"while",
"True",
":",
"event",
"=",
"self",
".",
"dispatch",
"(",
"False",
")",
"if",
"event",
"in",
"(",
"None",
",",
"QUIT",
")",
":",
"return",
"event",
... | 31.25 | 16.958333 |
def all(self, list_id, **queryparams):
"""
returns the first 10 segments for a specific list.
"""
return self._mc_client._get(url=self._build_path(list_id, 'segments'), **queryparams) | [
"def",
"all",
"(",
"self",
",",
"list_id",
",",
"*",
"*",
"queryparams",
")",
":",
"return",
"self",
".",
"_mc_client",
".",
"_get",
"(",
"url",
"=",
"self",
".",
"_build_path",
"(",
"list_id",
",",
"'segments'",
")",
",",
"*",
"*",
"queryparams",
")... | 42.2 | 14.6 |
def _strip_top_comments(lines: Sequence[str], line_separator: str) -> str:
"""Strips # comments that exist at the top of the given lines"""
lines = copy.copy(lines)
while lines and lines[0].startswith("#"):
lines = lines[1:]
return line_separator.join(lines) | [
"def",
"_strip_top_comments",
"(",
"lines",
":",
"Sequence",
"[",
"str",
"]",
",",
"line_separator",
":",
"str",
")",
"->",
"str",
":",
"lines",
"=",
"copy",
".",
"copy",
"(",
"lines",
")",
"while",
"lines",
"and",
"lines",
"[",
"0",
"]",
".",
"start... | 49.5 | 10.5 |
def can_process_shell(self, entry):
""":return: True when shell can be executed."""
count = 0
condition = render(entry['when'], variables=self.pipeline.variables,
model=self.pipeline.model, env=self.get_merged_env(include_os=True))
if Condition.evaluate("" if ... | [
"def",
"can_process_shell",
"(",
"self",
",",
"entry",
")",
":",
"count",
"=",
"0",
"condition",
"=",
"render",
"(",
"entry",
"[",
"'when'",
"]",
",",
"variables",
"=",
"self",
".",
"pipeline",
".",
"variables",
",",
"model",
"=",
"self",
".",
"pipelin... | 38.375 | 21.4375 |
def cache_data(self, request, data, key='params'):
"""
Cache data in the session store.
:param request: :attr:`django.http.HttpRequest`
:param data: Arbitrary data to store.
:param key: `str` The key under which to store the data.
"""
request.session['%s:%s' % (c... | [
"def",
"cache_data",
"(",
"self",
",",
"request",
",",
"data",
",",
"key",
"=",
"'params'",
")",
":",
"request",
".",
"session",
"[",
"'%s:%s'",
"%",
"(",
"constants",
".",
"SESSION_KEY",
",",
"key",
")",
"]",
"=",
"data"
] | 38.444444 | 13.777778 |
def flatten(d):
"""Return a dict as a list of lists.
>>> flatten({"a": "b"})
[['a', 'b']]
>>> flatten({"a": [1, 2, 3]})
[['a', [1, 2, 3]]]
>>> flatten({"a": {"b": "c"}})
[['a', 'b', 'c']]
>>> flatten({"a": {"b": {"c": "e"}}})
[['a', 'b', 'c', 'e']]
>>> flatten({"a": {"b": "c", "... | [
"def",
"flatten",
"(",
"d",
")",
":",
"if",
"not",
"isinstance",
"(",
"d",
",",
"dict",
")",
":",
"return",
"[",
"[",
"d",
"]",
"]",
"returned",
"=",
"[",
"]",
"for",
"key",
",",
"value",
"in",
"d",
".",
"items",
"(",
")",
":",
"# Each key, val... | 26.129032 | 15.83871 |
def parse_querystring(self, req, name, field):
"""Pull a querystring value from the request."""
return core.get_value(req.params, name, field) | [
"def",
"parse_querystring",
"(",
"self",
",",
"req",
",",
"name",
",",
"field",
")",
":",
"return",
"core",
".",
"get_value",
"(",
"req",
".",
"params",
",",
"name",
",",
"field",
")"
] | 52 | 6.666667 |
def _reference_rmvs(self, removes):
"""Prints all removed packages
"""
print("")
self.msg.template(78)
msg_pkg = "package"
if len(removes) > 1:
msg_pkg = "packages"
print("| Total {0} {1} removed".format(len(removes), msg_pkg))
self.msg.templat... | [
"def",
"_reference_rmvs",
"(",
"self",
",",
"removes",
")",
":",
"print",
"(",
"\"\"",
")",
"self",
".",
"msg",
".",
"template",
"(",
"78",
")",
"msg_pkg",
"=",
"\"package\"",
"if",
"len",
"(",
"removes",
")",
">",
"1",
":",
"msg_pkg",
"=",
"\"packag... | 33.647059 | 13.470588 |
def ignore_path(path):
"""
Verify whether to ignore a path.
Args:
path (str): path to check.
Returns:
bool: True when to ignore given path.
"""
ignore = False
for name in ['.tox', 'dist', 'build', 'node_modules', 'htmlcov']:
i... | [
"def",
"ignore_path",
"(",
"path",
")",
":",
"ignore",
"=",
"False",
"for",
"name",
"in",
"[",
"'.tox'",
",",
"'dist'",
",",
"'build'",
",",
"'node_modules'",
",",
"'htmlcov'",
"]",
":",
"if",
"path",
".",
"find",
"(",
"name",
")",
">=",
"0",
":",
... | 25.125 | 16.5 |
def copy_channel(self, channel, owner, to_channel):
'''
Tag all files in channel <channel> also as channel <to_channel>
:param channel: channel to copy
:param owner: Perform this operation on all packages of this user
:param to_channel: Destination name (may be a channe... | [
"def",
"copy_channel",
"(",
"self",
",",
"channel",
",",
"owner",
",",
"to_channel",
")",
":",
"url",
"=",
"'%s/channels/%s/%s/copy/%s'",
"%",
"(",
"self",
".",
"domain",
",",
"owner",
",",
"channel",
",",
"to_channel",
")",
"res",
"=",
"self",
".",
"ses... | 43 | 24.166667 |
def reraise(error):
"""Re-raises the error that was processed by prepare_for_reraise earlier."""
if hasattr(error, "_type_"):
six.reraise(type(error), error, error._traceback)
raise error | [
"def",
"reraise",
"(",
"error",
")",
":",
"if",
"hasattr",
"(",
"error",
",",
"\"_type_\"",
")",
":",
"six",
".",
"reraise",
"(",
"type",
"(",
"error",
")",
",",
"error",
",",
"error",
".",
"_traceback",
")",
"raise",
"error"
] | 40.6 | 14.2 |
def write_text(self, text: str, *, encoding='utf-8', append=True):
''' write text into the file. '''
mode = 'a' if append else 'w'
return self.write(text, mode=mode, encoding=encoding) | [
"def",
"write_text",
"(",
"self",
",",
"text",
":",
"str",
",",
"*",
",",
"encoding",
"=",
"'utf-8'",
",",
"append",
"=",
"True",
")",
":",
"mode",
"=",
"'a'",
"if",
"append",
"else",
"'w'",
"return",
"self",
".",
"write",
"(",
"text",
",",
"mode",... | 51.25 | 12.75 |
def trace3D(self):
"""Give a 3D representation of the traceroute.
right button: rotate the scene
middle button: zoom
left button: move the scene
left button on a ball: toggle IP displaying
ctrl-left button on a ball: scan ports 21,22,23,25,80 and 443 and display the resul... | [
"def",
"trace3D",
"(",
"self",
")",
":",
"trace",
"=",
"self",
".",
"get_trace",
"(",
")",
"import",
"visual",
"class",
"IPsphere",
"(",
"visual",
".",
"sphere",
")",
":",
"def",
"__init__",
"(",
"self",
",",
"ip",
",",
"*",
"*",
"kargs",
")",
":",... | 39.545455 | 13.827273 |
def create_typestr2type_dicts(dont_include_in_type2typestr=["lambda"]):
"""Return dictionaries mapping lower case typename (e.g. 'tuple') to type
objects from the types package, and vice versa."""
typenamelist = [tname for tname in dir(types) if tname.endswith("Type")]
typestr2type, type2typestr = {}, {... | [
"def",
"create_typestr2type_dicts",
"(",
"dont_include_in_type2typestr",
"=",
"[",
"\"lambda\"",
"]",
")",
":",
"typenamelist",
"=",
"[",
"tname",
"for",
"tname",
"in",
"dir",
"(",
"types",
")",
"if",
"tname",
".",
"endswith",
"(",
"\"Type\"",
")",
"]",
"typ... | 47.538462 | 14.538462 |
def set_errors(self, errors):
"""Set parameter error estimate """
if errors is None:
self.__errors__ = None
return
self.__errors__ = [asscalar(e) for e in errors] | [
"def",
"set_errors",
"(",
"self",
",",
"errors",
")",
":",
"if",
"errors",
"is",
"None",
":",
"self",
".",
"__errors__",
"=",
"None",
"return",
"self",
".",
"__errors__",
"=",
"[",
"asscalar",
"(",
"e",
")",
"for",
"e",
"in",
"errors",
"]"
] | 34.166667 | 11.333333 |
def _set_query_data_fast_1(self, page):
"""
set less expensive action=query response data PART 1
"""
self.data['pageid'] = page.get('pageid')
assessments = page.get('pageassessments')
if assessments:
self.data['assessments'] = assessments
extract = p... | [
"def",
"_set_query_data_fast_1",
"(",
"self",
",",
"page",
")",
":",
"self",
".",
"data",
"[",
"'pageid'",
"]",
"=",
"page",
".",
"get",
"(",
"'pageid'",
")",
"assessments",
"=",
"page",
".",
"get",
"(",
"'pageassessments'",
")",
"if",
"assessments",
":"... | 32.461538 | 17.948718 |
def position_result_list(change_list):
"""
Returns a template which iters through the models and appends a new
position column.
"""
result = result_list(change_list)
# Remove sortable attributes
for x in range(0, len(result['result_headers'])):
result['result_headers'][x]['sorted'] ... | [
"def",
"position_result_list",
"(",
"change_list",
")",
":",
"result",
"=",
"result_list",
"(",
"change_list",
")",
"# Remove sortable attributes",
"for",
"x",
"in",
"range",
"(",
"0",
",",
"len",
"(",
"result",
"[",
"'result_headers'",
"]",
")",
")",
":",
"... | 39.880952 | 15.880952 |
def create(self, tables, version):
"""Do the actual work of creating the database, filling its tables with
values, creating indices, and setting the datacache version metadata.
Parameters
----------
tables : list
List of datacache.DatabaseTable objects
versi... | [
"def",
"create",
"(",
"self",
",",
"tables",
",",
"version",
")",
":",
"for",
"table",
"in",
"tables",
":",
"self",
".",
"_create_table",
"(",
"table_name",
"=",
"table",
".",
"name",
",",
"column_types",
"=",
"table",
".",
"column_types",
",",
"primary"... | 34.761905 | 14.190476 |
def set_pending_symbol(self, pending_symbol=None):
"""Sets the context's ``pending_symbol`` with the given unicode sequence and resets the context's ``value``.
If the input is None, an empty :class:`CodePointArray` is used.
"""
if pending_symbol is None:
pending_symbol = Cod... | [
"def",
"set_pending_symbol",
"(",
"self",
",",
"pending_symbol",
"=",
"None",
")",
":",
"if",
"pending_symbol",
"is",
"None",
":",
"pending_symbol",
"=",
"CodePointArray",
"(",
")",
"self",
".",
"value",
"=",
"bytearray",
"(",
")",
"# reset value",
"self",
"... | 42.727273 | 11.909091 |
def error_catcher(self, extra_info: Optional[str] = None):
"""
Context manager to catch, print and record InstaloaderExceptions.
:param extra_info: String to prefix error message with."""
try:
yield
except InstaloaderException as err:
if extra_info:
... | [
"def",
"error_catcher",
"(",
"self",
",",
"extra_info",
":",
"Optional",
"[",
"str",
"]",
"=",
"None",
")",
":",
"try",
":",
"yield",
"except",
"InstaloaderException",
"as",
"err",
":",
"if",
"extra_info",
":",
"self",
".",
"error",
"(",
"'{}: {}'",
".",... | 34.642857 | 16.285714 |
def randset(self):
""" -> a #set of random integers """
return {
self._map_type(int)
for x in range(self.random.randint(3, 10))} | [
"def",
"randset",
"(",
"self",
")",
":",
"return",
"{",
"self",
".",
"_map_type",
"(",
"int",
")",
"for",
"x",
"in",
"range",
"(",
"self",
".",
"random",
".",
"randint",
"(",
"3",
",",
"10",
")",
")",
"}"
] | 32.8 | 14 |
def edit(request):
"""
Process the inline editing form.
"""
model = apps.get_model(request.POST["app"], request.POST["model"])
obj = model.objects.get(id=request.POST["id"])
form = get_edit_form(obj, request.POST["fields"], data=request.POST,
files=request.FILES)
if ... | [
"def",
"edit",
"(",
"request",
")",
":",
"model",
"=",
"apps",
".",
"get_model",
"(",
"request",
".",
"POST",
"[",
"\"app\"",
"]",
",",
"request",
".",
"POST",
"[",
"\"model\"",
"]",
")",
"obj",
"=",
"model",
".",
"objects",
".",
"get",
"(",
"id",
... | 40 | 16 |
def add_state(self, name: str, state: State, initial: bool = False):
""" Adds a new state to the FSM.
Args:
name (str): the name of the state, which is used as its identifier.
state (spade.behaviour.State): The state class
initial (bool, optional): wether the state is the ... | [
"def",
"add_state",
"(",
"self",
",",
"name",
":",
"str",
",",
"state",
":",
"State",
",",
"initial",
":",
"bool",
"=",
"False",
")",
":",
"if",
"not",
"issubclass",
"(",
"state",
".",
"__class__",
",",
"State",
")",
":",
"raise",
"AttributeError",
"... | 44.928571 | 26.571429 |
def _expand(self, pos):
"""Splits sublists that are more than double the load level.
Updates the index when the sublist length is less than double the load
level. This requires incrementing the nodes in a traversal from the
leaf node to the root. For an example traversal see self._loc.
... | [
"def",
"_expand",
"(",
"self",
",",
"pos",
")",
":",
"_lists",
"=",
"self",
".",
"_lists",
"_index",
"=",
"self",
".",
"_index",
"if",
"len",
"(",
"_lists",
"[",
"pos",
"]",
")",
">",
"self",
".",
"_dual",
":",
"_maxes",
"=",
"self",
".",
"_maxes... | 30.870968 | 16.451613 |
def _build_query_dict(self, formdata=None):
"""
Take submitted data from form and create a query dict to be
used in a Q object (or filter)
"""
if self.is_valid() and formdata is None:
formdata = self.cleaned_data
key = "{field}__{operator}".format(**formdata)
... | [
"def",
"_build_query_dict",
"(",
"self",
",",
"formdata",
"=",
"None",
")",
":",
"if",
"self",
".",
"is_valid",
"(",
")",
"and",
"formdata",
"is",
"None",
":",
"formdata",
"=",
"self",
".",
"cleaned_data",
"key",
"=",
"\"{field}__{operator}\"",
".",
"forma... | 40.466667 | 6.066667 |
def load(self, value):
"""Load a value, converting it to the proper type if validation_type exists."""
if self.property_type is None:
return value
elif not isinstance(self.property_type, BaseType):
raise TypeError('property_type must be schematics BaseType')
else:... | [
"def",
"load",
"(",
"self",
",",
"value",
")",
":",
"if",
"self",
".",
"property_type",
"is",
"None",
":",
"return",
"value",
"elif",
"not",
"isinstance",
"(",
"self",
".",
"property_type",
",",
"BaseType",
")",
":",
"raise",
"TypeError",
"(",
"'property... | 46 | 15.7 |
def _image_url(path, only_path=False, cache_buster=True, dst_color=None, src_color=None, inline=False, mime_type=None, spacing=None, collapse_x=None, collapse_y=None):
"""
src_color - a list of or a single color to be replaced by each corresponding dst_color colors
spacing - spaces to be added to the image
... | [
"def",
"_image_url",
"(",
"path",
",",
"only_path",
"=",
"False",
",",
"cache_buster",
"=",
"True",
",",
"dst_color",
"=",
"None",
",",
"src_color",
"=",
"None",
",",
"inline",
"=",
"False",
",",
"mime_type",
"=",
"None",
",",
"spacing",
"=",
"None",
"... | 41.801325 | 19.562914 |
def _select_vs(v, p):
# This one is is about 30 times faster than
# the generic algorithm it is replacing.
"""returns the points to use for interpolating v"""
if v >= 120.:
return 60, 120, inf
elif v >= 60.:
return 40, 60, 120
elif v >= 40.:
return 30, 40, 60
elif v ... | [
"def",
"_select_vs",
"(",
"v",
",",
"p",
")",
":",
"# This one is is about 30 times faster than",
"# the generic algorithm it is replacing.",
"if",
"v",
">=",
"120.",
":",
"return",
"60",
",",
"120",
",",
"inf",
"elif",
"v",
">=",
"60.",
":",
"return",
"40",
"... | 21.962963 | 19.407407 |
def zip(i):
"""
Input: {
data_uoa - repo UOA
(archive_path) - if '' create inside repo path
(archive_name) - if !='' use it for zip name
(auto_name) - if 'yes', generate name name from data_uoa: ckr-<repo_uoa>.zip
(bittorent) -... | [
"def",
"zip",
"(",
"i",
")",
":",
"o",
"=",
"i",
".",
"get",
"(",
"'out'",
",",
"''",
")",
"duoa1",
"=",
"i",
".",
"get",
"(",
"'data_uoa'",
",",
"''",
")",
"duid",
"=",
"''",
"path",
"=",
"''",
"if",
"duoa1",
"!=",
"''",
":",
"# Find path to... | 27.487342 | 23.158228 |
def _connection(username=None, password=None, host=None, port=None, db=None):
"returns a connected cursor to the database-server."
c_opts = {}
if username: c_opts['user'] = username
if password: c_opts['password'] = password
if host: c_opts['host'] = host
if port: c_opts['port'] = port
if ... | [
"def",
"_connection",
"(",
"username",
"=",
"None",
",",
"password",
"=",
"None",
",",
"host",
"=",
"None",
",",
"port",
"=",
"None",
",",
"db",
"=",
"None",
")",
":",
"c_opts",
"=",
"{",
"}",
"if",
"username",
":",
"c_opts",
"[",
"'user'",
"]",
... | 29.5 | 19.214286 |
def get_feature_set_all():
"""
Return a list of entire features.
A set of entire features regardless of being used to train a model or
predict a class.
Returns
-------
feature_names : list
A list of features' names.
"""
features = get_feature_set()
features.append('cu... | [
"def",
"get_feature_set_all",
"(",
")",
":",
"features",
"=",
"get_feature_set",
"(",
")",
"features",
".",
"append",
"(",
"'cusum'",
")",
"features",
".",
"append",
"(",
"'eta'",
")",
"features",
".",
"append",
"(",
"'n_points'",
")",
"features",
".",
"ap... | 21.777778 | 18.296296 |
def add_layer2image(grid2d, x_pos, y_pos, kernel, order=1):
"""
adds a kernel on the grid2d image at position x_pos, y_pos with an interpolated subgrid pixel shift of order=order
:param grid2d: 2d pixel grid (i.e. image)
:param x_pos: x-position center (pixel coordinate) of the layer to be added
:pa... | [
"def",
"add_layer2image",
"(",
"grid2d",
",",
"x_pos",
",",
"y_pos",
",",
"kernel",
",",
"order",
"=",
"1",
")",
":",
"x_int",
"=",
"int",
"(",
"round",
"(",
"x_pos",
")",
")",
"y_int",
"=",
"int",
"(",
"round",
"(",
"y_pos",
")",
")",
"shift_x",
... | 49.588235 | 23.823529 |
def set_password(self, password):
"""Set password for the MUC request.
:Parameters:
- `password`: password
:Types:
- `password`: `unicode`"""
for child in xml_element_iter(self.xmlnode.children):
if get_node_ns_uri(child) == MUC_NS and child.name == "... | [
"def",
"set_password",
"(",
"self",
",",
"password",
")",
":",
"for",
"child",
"in",
"xml_element_iter",
"(",
"self",
".",
"xmlnode",
".",
"children",
")",
":",
"if",
"get_node_ns_uri",
"(",
"child",
")",
"==",
"MUC_NS",
"and",
"child",
".",
"name",
"=="... | 35.2 | 18.933333 |
def ancestral_likelihood(self):
"""
Calculate the likelihood of the given realization of the sequences in
the tree
Returns
-------
log_lh : float
The tree likelihood given the sequences
"""
log_lh = np.zeros(self.multiplicity.shape[0])
... | [
"def",
"ancestral_likelihood",
"(",
"self",
")",
":",
"log_lh",
"=",
"np",
".",
"zeros",
"(",
"self",
".",
"multiplicity",
".",
"shape",
"[",
"0",
"]",
")",
"for",
"node",
"in",
"self",
".",
"tree",
".",
"find_clades",
"(",
"order",
"=",
"'postorder'",... | 32.969697 | 22 |
def pprint_arg(vnames, value):
"""
pretty print argument
:param vnames:
:param value:
:return:
"""
ret = ''
for name, v in zip(vnames, value):
ret += '%s=%s;' % (name, str(v))
return ret; | [
"def",
"pprint_arg",
"(",
"vnames",
",",
"value",
")",
":",
"ret",
"=",
"''",
"for",
"name",
",",
"v",
"in",
"zip",
"(",
"vnames",
",",
"value",
")",
":",
"ret",
"+=",
"'%s=%s;'",
"%",
"(",
"name",
",",
"str",
"(",
"v",
")",
")",
"return",
"ret... | 20.090909 | 13.909091 |
def id(self):
"""
Computes the signature of the record, a SHA-512 of significant values
:return: SHa-512 Hex string
"""
h = hashlib.new('sha512')
for value in (self.machine.name, self.machine.os, self.user, self.application.name,
self.application.pa... | [
"def",
"id",
"(",
"self",
")",
":",
"h",
"=",
"hashlib",
".",
"new",
"(",
"'sha512'",
")",
"for",
"value",
"in",
"(",
"self",
".",
"machine",
".",
"name",
",",
"self",
".",
"machine",
".",
"os",
",",
"self",
".",
"user",
",",
"self",
".",
"appl... | 44.071429 | 21.214286 |
def _rebuffer(self):
"""
(internal) refill the repeat buffer
"""
# collect a stride worth of results(result lists) or exceptions
results = []
exceptions = []
for i in xrange(self.stride):
try:
results.append(self.iterable.next(... | [
"def",
"_rebuffer",
"(",
"self",
")",
":",
"# collect a stride worth of results(result lists) or exceptions",
"results",
"=",
"[",
"]",
"exceptions",
"=",
"[",
"]",
"for",
"i",
"in",
"xrange",
"(",
"self",
".",
"stride",
")",
":",
"try",
":",
"results",
".",
... | 35.214286 | 11.214286 |
def var_cov_var_normal(P, c, mu=0, sigma=1):
"""
Variance-covariance calculation of daily Value-at-Risk in a
portfolio.
Parameters
----------
P : float
Portfolio value.
c : float
Confidence level.
mu : float, optional
Mean.
Returns
-------
float
... | [
"def",
"var_cov_var_normal",
"(",
"P",
",",
"c",
",",
"mu",
"=",
"0",
",",
"sigma",
"=",
"1",
")",
":",
"alpha",
"=",
"sp",
".",
"stats",
".",
"norm",
".",
"ppf",
"(",
"1",
"-",
"c",
",",
"mu",
",",
"sigma",
")",
"return",
"P",
"-",
"P",
"*... | 18.681818 | 21.409091 |
def _skip(self, cnt):
"""Read and discard data"""
while cnt > 0:
if cnt > 8192:
buf = self.read(8192)
else:
buf = self.read(cnt)
if not buf:
break
cnt -= len(buf) | [
"def",
"_skip",
"(",
"self",
",",
"cnt",
")",
":",
"while",
"cnt",
">",
"0",
":",
"if",
"cnt",
">",
"8192",
":",
"buf",
"=",
"self",
".",
"read",
"(",
"8192",
")",
"else",
":",
"buf",
"=",
"self",
".",
"read",
"(",
"cnt",
")",
"if",
"not",
... | 26.5 | 13 |
def ExpireObject(self, key):
"""Expire a specific object from cache."""
node = self._hash.pop(key, None)
if node:
self._age.Unlink(node)
self.KillObject(node.data)
return node.data | [
"def",
"ExpireObject",
"(",
"self",
",",
"key",
")",
":",
"node",
"=",
"self",
".",
"_hash",
".",
"pop",
"(",
"key",
",",
"None",
")",
"if",
"node",
":",
"self",
".",
"_age",
".",
"Unlink",
"(",
"node",
")",
"self",
".",
"KillObject",
"(",
"node"... | 25.5 | 15.25 |
def flatten_colors(colors):
"""Prepare colors to be exported.
Flatten dicts and convert colors to util.Color()"""
all_colors = {"wallpaper": colors["wallpaper"],
"alpha": colors["alpha"],
**colors["special"],
**colors["colors"]}
return {k: util.Co... | [
"def",
"flatten_colors",
"(",
"colors",
")",
":",
"all_colors",
"=",
"{",
"\"wallpaper\"",
":",
"colors",
"[",
"\"wallpaper\"",
"]",
",",
"\"alpha\"",
":",
"colors",
"[",
"\"alpha\"",
"]",
",",
"*",
"*",
"colors",
"[",
"\"special\"",
"]",
",",
"*",
"*",
... | 43.875 | 6.5 |
def get_address_details(address, coin_symbol='btc', txn_limit=None, api_key=None, before_bh=None, after_bh=None, unspent_only=False, show_confidence=False, confirmations=0, include_script=False):
'''
Takes an address and coin_symbol and returns the address details
Optional:
- txn_limit: # transaction... | [
"def",
"get_address_details",
"(",
"address",
",",
"coin_symbol",
"=",
"'btc'",
",",
"txn_limit",
"=",
"None",
",",
"api_key",
"=",
"None",
",",
"before_bh",
"=",
"None",
",",
"after_bh",
"=",
"None",
",",
"unspent_only",
"=",
"False",
",",
"show_confidence"... | 36.255319 | 24.042553 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.