text stringlengths 89 104k | code_tokens list | avg_line_len float64 7.91 980 | score float64 0 630 |
|---|---|---|---|
def clean_error(err):
"""
Take stderr bytes returned from MicroPython and attempt to create a
non-verbose error message.
"""
if err:
decoded = err.decode('utf-8')
try:
return decoded.split('\r\n')[-2]
except Exception:
return decoded
return 'There ... | [
"def",
"clean_error",
"(",
"err",
")",
":",
"if",
"err",
":",
"decoded",
"=",
"err",
".",
"decode",
"(",
"'utf-8'",
")",
"try",
":",
"return",
"decoded",
".",
"split",
"(",
"'\\r\\n'",
")",
"[",
"-",
"2",
"]",
"except",
"Exception",
":",
"return",
... | 26.916667 | 13.416667 |
def list(cls, params=None):
"""
Retrieves a list of the model
:param params: params as dictionary
:type params: dict
:return: the list of the parsed xml objects
:rtype: list
"""
return fields.ListField(name=cls.ENDPOINT, init_class=cls).decode(
... | [
"def",
"list",
"(",
"cls",
",",
"params",
"=",
"None",
")",
":",
"return",
"fields",
".",
"ListField",
"(",
"name",
"=",
"cls",
".",
"ENDPOINT",
",",
"init_class",
"=",
"cls",
")",
".",
"decode",
"(",
"cls",
".",
"element_from_string",
"(",
"cls",
".... | 31.833333 | 16.833333 |
def _init_dflt(self):
"""Get a list of namedtuples, one for each annotation."""
nts = []
ntobj = cx.namedtuple('ntanno', self.flds)
for itemid, gos in self.id2gos.items():
for goid in gos:
nts.append(ntobj(DB_ID=itemid, GO_ID=goid))
return nts | [
"def",
"_init_dflt",
"(",
"self",
")",
":",
"nts",
"=",
"[",
"]",
"ntobj",
"=",
"cx",
".",
"namedtuple",
"(",
"'ntanno'",
",",
"self",
".",
"flds",
")",
"for",
"itemid",
",",
"gos",
"in",
"self",
".",
"id2gos",
".",
"items",
"(",
")",
":",
"for",... | 38 | 14.125 |
def update_contact_of_client(self, contact_id, contact_dict):
"""
Updates a contact
:param contact_id: the id of the contact
:param contact_dict: dict
:return: dict
"""
return self._create_put_request(resource=CONTACTS, billomat_id=contact_id, send_data=contact_d... | [
"def",
"update_contact_of_client",
"(",
"self",
",",
"contact_id",
",",
"contact_dict",
")",
":",
"return",
"self",
".",
"_create_put_request",
"(",
"resource",
"=",
"CONTACTS",
",",
"billomat_id",
"=",
"contact_id",
",",
"send_data",
"=",
"contact_dict",
")"
] | 35.111111 | 19.555556 |
def snapshot_table(
self,
name,
cluster,
snapshot_id,
description,
ttl=None,
retry=google.api_core.gapic_v1.method.DEFAULT,
timeout=google.api_core.gapic_v1.method.DEFAULT,
metadata=None,
):
"""
Creates a new snapshot in the spe... | [
"def",
"snapshot_table",
"(",
"self",
",",
"name",
",",
"cluster",
",",
"snapshot_id",
",",
"description",
",",
"ttl",
"=",
"None",
",",
"retry",
"=",
"google",
".",
"api_core",
".",
"gapic_v1",
".",
"method",
".",
"DEFAULT",
",",
"timeout",
"=",
"google... | 43.728 | 25.36 |
def make_request(url, data, on_complete):
"""
Make AJAX request to `url` with given POST `data`. Call `on_complete`
callback when complete.
Args:
url (str): URL.
data (dict): Dictionary with POST data.
on_complete (ref): Reference to function / method which will be called
... | [
"def",
"make_request",
"(",
"url",
",",
"data",
",",
"on_complete",
")",
":",
"req",
"=",
"ajax",
".",
"ajax",
"(",
")",
"req",
".",
"bind",
"(",
"'complete'",
",",
"on_complete",
")",
"req",
".",
"open",
"(",
"'POST'",
",",
"url",
",",
"True",
")"... | 32.9375 | 16.6875 |
async def initialize(bot: Bot, host, password, rest_port, ws_port, timeout=30):
"""
Initializes the websocket connection to the lavalink player.
.. important::
This function must only be called AFTER the bot has received its
"on_ready" event!
Parameters
----------
bot : Bot
... | [
"async",
"def",
"initialize",
"(",
"bot",
":",
"Bot",
",",
"host",
",",
"password",
",",
"rest_port",
",",
"ws_port",
",",
"timeout",
"=",
"30",
")",
":",
"global",
"_loop",
"_loop",
"=",
"bot",
".",
"loop",
"player_manager",
".",
"user_id",
"=",
"bot"... | 28.32 | 21.36 |
def add_item(self, sqla_col_type, item, key_specific=None):
"""
Add an item to the registry
"""
if key_specific is not None:
self.setdefault(key_specific, {})[sqla_col_type] = item
else:
self[sqla_col_type] = item | [
"def",
"add_item",
"(",
"self",
",",
"sqla_col_type",
",",
"item",
",",
"key_specific",
"=",
"None",
")",
":",
"if",
"key_specific",
"is",
"not",
"None",
":",
"self",
".",
"setdefault",
"(",
"key_specific",
",",
"{",
"}",
")",
"[",
"sqla_col_type",
"]",
... | 33.75 | 10.5 |
def wrap_str(self, text, strchar, multiline=False):
"""Wrap a string."""
if multiline:
strchar *= 3
return strwrapper + self.add_ref("str", (text, strchar)) + unwrapper | [
"def",
"wrap_str",
"(",
"self",
",",
"text",
",",
"strchar",
",",
"multiline",
"=",
"False",
")",
":",
"if",
"multiline",
":",
"strchar",
"*=",
"3",
"return",
"strwrapper",
"+",
"self",
".",
"add_ref",
"(",
"\"str\"",
",",
"(",
"text",
",",
"strchar",
... | 40 | 16.4 |
def resolved_path(path, base=None):
"""
Args:
path (str | unicode | None): Path to resolve
base (str | unicode | None): Base path to use to resolve relative paths (default: current working dir)
Returns:
(str): Absolute path
"""
if not path or path.startswith(SYMBOLIC_TMP):
... | [
"def",
"resolved_path",
"(",
"path",
",",
"base",
"=",
"None",
")",
":",
"if",
"not",
"path",
"or",
"path",
".",
"startswith",
"(",
"SYMBOLIC_TMP",
")",
":",
"return",
"path",
"path",
"=",
"os",
".",
"path",
".",
"expanduser",
"(",
"path",
")",
"if",... | 28.764706 | 19.705882 |
def for_web(self, data):
"""
Convert data to web output (raster only).
Parameters
----------
data : array
Returns
-------
web data : array
"""
return memory_file(
prepare_array(
data, masked=True, nodata=self.n... | [
"def",
"for_web",
"(",
"self",
",",
"data",
")",
":",
"return",
"memory_file",
"(",
"prepare_array",
"(",
"data",
",",
"masked",
"=",
"True",
",",
"nodata",
"=",
"self",
".",
"nodata",
",",
"dtype",
"=",
"self",
".",
"profile",
"(",
")",
"[",
"\"dtyp... | 22.5 | 20.166667 |
def create_layout_params(self, child, layout):
""" Override as there is no (width, height) constructor.
"""
from .android_fragment import AndroidFragment
if isinstance(child, AndroidFragment):
return super(AndroidViewPager, self).create_layout_params(child,
... | [
"def",
"create_layout_params",
"(",
"self",
",",
"child",
",",
"layout",
")",
":",
"from",
".",
"android_fragment",
"import",
"AndroidFragment",
"if",
"isinstance",
"(",
"child",
",",
"AndroidFragment",
")",
":",
"return",
"super",
"(",
"AndroidViewPager",
",",
... | 40.7 | 13.95 |
def fw_rule_delete(self, data, fw_name=None):
"""Top level rule delete function. """
LOG.debug("FW Rule delete %s", data)
self._fw_rule_delete(fw_name, data) | [
"def",
"fw_rule_delete",
"(",
"self",
",",
"data",
",",
"fw_name",
"=",
"None",
")",
":",
"LOG",
".",
"debug",
"(",
"\"FW Rule delete %s\"",
",",
"data",
")",
"self",
".",
"_fw_rule_delete",
"(",
"fw_name",
",",
"data",
")"
] | 44.5 | 3 |
def requirements(ctx):
"""Write the `requirements-agent-release.txt` file at the root of the repo
listing all the Agent-based integrations pinned at the version they currently
have in HEAD.
"""
echo_info('Freezing check releases')
checks = get_valid_checks()
checks.remove('datadog_checks_dev... | [
"def",
"requirements",
"(",
"ctx",
")",
":",
"echo_info",
"(",
"'Freezing check releases'",
")",
"checks",
"=",
"get_valid_checks",
"(",
")",
"checks",
".",
"remove",
"(",
"'datadog_checks_dev'",
")",
"entries",
"=",
"[",
"]",
"for",
"check",
"in",
"checks",
... | 34.407407 | 20.222222 |
def instruction_BSR_JSR(self, opcode, ea):
"""
Program control is transferred to the effective address after storing
the return address on the hardware stack.
A return from subroutine (RTS) instruction is used to reverse this
process and must be the last instruction executed in ... | [
"def",
"instruction_BSR_JSR",
"(",
"self",
",",
"opcode",
",",
"ea",
")",
":",
"# log.info(\"%x|\\tJSR/BSR to $%x \\t| %s\" % (",
"# self.last_op_address,",
"# ea, self.cfg.mem_info.get_shortest(ea)",
"# ))",
"self",
".",
"push_word",
"(",
"sel... | 37.722222 | 19.722222 |
def fetch(self):
"""
Fetch the recent refs from the remotes.
Unless git-up.fetch.all is set to true, all remotes with
locally existent branches will be fetched.
"""
fetch_kwargs = {'multiple': True}
fetch_args = []
if self.is_prune():
... | [
"def",
"fetch",
"(",
"self",
")",
":",
"fetch_kwargs",
"=",
"{",
"'multiple'",
":",
"True",
"}",
"fetch_args",
"=",
"[",
"]",
"if",
"self",
".",
"is_prune",
"(",
")",
":",
"fetch_kwargs",
"[",
"'prune'",
"]",
"=",
"True",
"if",
"self",
".",
"settings... | 29.129032 | 15.645161 |
def levels(self):
"""
Get the factor levels.
:returns: A list of lists, one list per column, of levels.
"""
lol = H2OFrame._expr(expr=ExprNode("levels", self)).as_data_frame(False)
lol.pop(0) # Remove column headers
lol = list(zip(*lol))
return [[ll for ... | [
"def",
"levels",
"(",
"self",
")",
":",
"lol",
"=",
"H2OFrame",
".",
"_expr",
"(",
"expr",
"=",
"ExprNode",
"(",
"\"levels\"",
",",
"self",
")",
")",
".",
"as_data_frame",
"(",
"False",
")",
"lol",
".",
"pop",
"(",
"0",
")",
"# Remove column headers",
... | 34.5 | 17.1 |
def normalize_timedelta(timedelta):
"""
Given a string like "1w" or "-5d", convert it to an integer in milliseconds.
Integers without a suffix are interpreted as seconds.
Note: not related to the datetime timedelta class.
"""
try:
return int(timedelta) * 1000
except ValueError as e:
... | [
"def",
"normalize_timedelta",
"(",
"timedelta",
")",
":",
"try",
":",
"return",
"int",
"(",
"timedelta",
")",
"*",
"1000",
"except",
"ValueError",
"as",
"e",
":",
"t",
",",
"suffix",
"=",
"timedelta",
"[",
":",
"-",
"1",
"]",
",",
"timedelta",
"[",
"... | 44.933333 | 17.866667 |
def _set_labels(node, apiserver_url, labels):
'''Replace labels dict by a new one'''
# Prepare URL
url = "{0}/api/v1/nodes/{1}".format(apiserver_url, node)
# Prepare data
data = [{"op": "replace", "path": "/metadata/labels", "value": labels}]
# Make request
ret = _kpatch(url, data)
if re... | [
"def",
"_set_labels",
"(",
"node",
",",
"apiserver_url",
",",
"labels",
")",
":",
"# Prepare URL",
"url",
"=",
"\"{0}/api/v1/nodes/{1}\"",
".",
"format",
"(",
"apiserver_url",
",",
"node",
")",
"# Prepare data",
"data",
"=",
"[",
"{",
"\"op\"",
":",
"\"replace... | 36.454545 | 17 |
def resize_lazy(image, width=None, height=None, crop=False, force=False,
namespace="resized", storage=default_storage,
as_url=False):
"""
Returns the name of the resized file. Returns the url if as_url is True
"""
# First normalize params to determine which file to get
... | [
"def",
"resize_lazy",
"(",
"image",
",",
"width",
"=",
"None",
",",
"height",
"=",
"None",
",",
"crop",
"=",
"False",
",",
"force",
"=",
"False",
",",
"namespace",
"=",
"\"resized\"",
",",
"storage",
"=",
"default_storage",
",",
"as_url",
"=",
"False",
... | 33.129032 | 20.419355 |
def queue(self, queue, message, params={}, uids=[]):
"""
Queue a job in Rhumba
"""
d = {
'id': uuid.uuid1().get_hex(),
'version': 1,
'message': message,
'params': params
}
if uids:
for uid in uids:
... | [
"def",
"queue",
"(",
"self",
",",
"queue",
",",
"message",
",",
"params",
"=",
"{",
"}",
",",
"uids",
"=",
"[",
"]",
")",
":",
"d",
"=",
"{",
"'id'",
":",
"uuid",
".",
"uuid1",
"(",
")",
".",
"get_hex",
"(",
")",
",",
"'version'",
":",
"1",
... | 27.473684 | 17.263158 |
def do_set_logical_switch_config(self, line):
"""set_logical_switch_config <peer> <logical switch> <key> <value>
eg. set_logical_switch_config sw1 running LogicalSwitch7 \
lost-connection-behavior failStandaloneMode
"""
def f(p, args):
try:
target, lsw, key, ... | [
"def",
"do_set_logical_switch_config",
"(",
"self",
",",
"line",
")",
":",
"def",
"f",
"(",
"p",
",",
"args",
")",
":",
"try",
":",
"target",
",",
"lsw",
",",
"key",
",",
"value",
"=",
"args",
"except",
":",
"print",
"(",
"\"argument error\"",
")",
"... | 31.583333 | 15.5 |
def wrap_tuple_streams(unwrapped, kdims, streams):
"""
Fills in tuple keys with dimensioned stream values as appropriate.
"""
param_groups = [(s.contents.keys(), s) for s in streams]
pairs = [(name,s) for (group, s) in param_groups for name in group]
substituted = []
for pos,el in enumerate... | [
"def",
"wrap_tuple_streams",
"(",
"unwrapped",
",",
"kdims",
",",
"streams",
")",
":",
"param_groups",
"=",
"[",
"(",
"s",
".",
"contents",
".",
"keys",
"(",
")",
",",
"s",
")",
"for",
"s",
"in",
"streams",
"]",
"pairs",
"=",
"[",
"(",
"name",
",",... | 42.4 | 13.2 |
def set_router_id(self, value=None, default=False, disable=False):
"""Controls the router id property for the OSPF Proccess
Args:
value (str): The router-id value
default (bool): Controls the use of the default keyword
disable (bool): Controls the use of ... | [
"def",
"set_router_id",
"(",
"self",
",",
"value",
"=",
"None",
",",
"default",
"=",
"False",
",",
"disable",
"=",
"False",
")",
":",
"cmd",
"=",
"self",
".",
"command_builder",
"(",
"'router-id'",
",",
"value",
"=",
"value",
",",
"default",
"=",
"defa... | 45.615385 | 19.230769 |
def _build_vars_dict(vars_file='', variables=None):
"""Merge variables into a single dictionary
Applies to CLI provided variables only
"""
repex_vars = {}
if vars_file:
with open(vars_file) as varsfile:
repex_vars = yaml.safe_load(varsfile.read())
for var in variables:
... | [
"def",
"_build_vars_dict",
"(",
"vars_file",
"=",
"''",
",",
"variables",
"=",
"None",
")",
":",
"repex_vars",
"=",
"{",
"}",
"if",
"vars_file",
":",
"with",
"open",
"(",
"vars_file",
")",
"as",
"varsfile",
":",
"repex_vars",
"=",
"yaml",
".",
"safe_load... | 31.538462 | 12.461538 |
def save_svg(string, parent=None):
""" Prompts the user to save an SVG document to disk.
Parameters:
-----------
string : basestring
A Python string containing a SVG document.
parent : QWidget, optional
The parent to use for the file dialog.
Returns:
--------
The name ... | [
"def",
"save_svg",
"(",
"string",
",",
"parent",
"=",
"None",
")",
":",
"if",
"isinstance",
"(",
"string",
",",
"unicode",
")",
":",
"string",
"=",
"string",
".",
"encode",
"(",
"'utf-8'",
")",
"dialog",
"=",
"QtGui",
".",
"QFileDialog",
"(",
"parent",... | 27.375 | 18.25 |
def get_queryset(self):
"""
This view should return a list of all the addresses the identity has
for the supplied query parameters.
Currently only supports address_type and default params
Always excludes addresses with optedout = True
"""
identity_id = self.kwargs... | [
"def",
"get_queryset",
"(",
"self",
")",
":",
"identity_id",
"=",
"self",
".",
"kwargs",
"[",
"\"identity_id\"",
"]",
"address_type",
"=",
"self",
".",
"kwargs",
"[",
"\"address_type\"",
"]",
"use_ct",
"=",
"\"use_communicate_through\"",
"in",
"self",
".",
"re... | 45.857143 | 18.428571 |
def _extalg(xarr, alpha=100, axis=None):
'''Given an array xarr of values, smoothly return the max/min'''
return (np.sum(xarr * np.exp(alpha*xarr), axis=axis, keepdims=True)/
np.sum(np.exp(alpha*xarr), axis=axis, keepdims=True)) | [
"def",
"_extalg",
"(",
"xarr",
",",
"alpha",
"=",
"100",
",",
"axis",
"=",
"None",
")",
":",
"return",
"(",
"np",
".",
"sum",
"(",
"xarr",
"*",
"np",
".",
"exp",
"(",
"alpha",
"*",
"xarr",
")",
",",
"axis",
"=",
"axis",
",",
"keepdims",
"=",
... | 62.25 | 22.25 |
def execute_request(server_url, creds, namespace, classname):
""" Open a connection with the server_url and creds, and
enumerate instances defined by the functions namespace and
classname arguments.
Displays either the error return or the mof for instances
returned.
"""
prin... | [
"def",
"execute_request",
"(",
"server_url",
",",
"creds",
",",
"namespace",
",",
"classname",
")",
":",
"print",
"(",
"'Requesting url=%s, ns=%s, class=%s'",
"%",
"(",
"server_url",
",",
"namespace",
",",
"classname",
")",
")",
"try",
":",
"# Create a connection"... | 37.324324 | 18.594595 |
def _dbus_get_object(bus_name, object_name):
""" Fetches DBUS proxy object given the specified parameters.
`bus_name`
Name of the bus interface.
`object_name`
Object path related to the interface.
Returns object or ``None``.
"""
try:
bus = dbus.... | [
"def",
"_dbus_get_object",
"(",
"bus_name",
",",
"object_name",
")",
":",
"try",
":",
"bus",
"=",
"dbus",
".",
"SessionBus",
"(",
")",
"obj",
"=",
"bus",
".",
"get_object",
"(",
"bus_name",
",",
"object_name",
")",
"return",
"obj",
"except",
"(",
"NameEr... | 25.666667 | 18.333333 |
def artifact_mime_type(instance):
"""Ensure the 'mime_type' property of artifact objects comes from the
Template column in the IANA media type registry.
"""
for key, obj in instance['objects'].items():
if ('type' in obj and obj['type'] == 'artifact' and 'mime_type' in obj):
if enums.... | [
"def",
"artifact_mime_type",
"(",
"instance",
")",
":",
"for",
"key",
",",
"obj",
"in",
"instance",
"[",
"'objects'",
"]",
".",
"items",
"(",
")",
":",
"if",
"(",
"'type'",
"in",
"obj",
"and",
"obj",
"[",
"'type'",
"]",
"==",
"'artifact'",
"and",
"'m... | 59.090909 | 25.909091 |
def _render_bar(self, bar, value, max_value, label_width, bar_width, **settings):
"""
Render single chart bar.
"""
percent = value / max_value
barstr = ""
barstr += str(settings[self.SETTING_BAR_CHAR]) * int(bar_width * percent)
s = {k: settings[k] for k in (self.... | [
"def",
"_render_bar",
"(",
"self",
",",
"bar",
",",
"value",
",",
"max_value",
",",
"label_width",
",",
"bar_width",
",",
"*",
"*",
"settings",
")",
":",
"percent",
"=",
"value",
"/",
"max_value",
"barstr",
"=",
"\"\"",
"barstr",
"+=",
"str",
"(",
"set... | 46.307692 | 16 |
def cal_g_bm3(p, g, k):
"""
calculate shear modulus at given pressure
:param p: pressure
:param g: [g0, g0p]
:param k: [v0, k0, k0p]
:return: shear modulus at high pressure
"""
v = cal_v_bm3(p, k)
v0 = k[0]
k0 = k[1]
kp = k[2]
g0 = g[0]
gp = g[1]
f = 0.5 * ((v / ... | [
"def",
"cal_g_bm3",
"(",
"p",
",",
"g",
",",
"k",
")",
":",
"v",
"=",
"cal_v_bm3",
"(",
"p",
",",
"k",
")",
"v0",
"=",
"k",
"[",
"0",
"]",
"k0",
"=",
"k",
"[",
"1",
"]",
"kp",
"=",
"k",
"[",
"2",
"]",
"g0",
"=",
"g",
"[",
"0",
"]",
... | 28.578947 | 19.105263 |
def augmentTextWithCONLLstr( conll_str_array, text ):
''' Augments given Text object with the information from Maltparser's output.
More specifically, adds information about SYNTAX_LABEL, SYNTAX_HEAD and
DEPREL to each token in the Text object;
'''
j = 0
for sentence in text.divide( laye... | [
"def",
"augmentTextWithCONLLstr",
"(",
"conll_str_array",
",",
"text",
")",
":",
"j",
"=",
"0",
"for",
"sentence",
"in",
"text",
".",
"divide",
"(",
"layer",
"=",
"WORDS",
",",
"by",
"=",
"SENTENCES",
")",
":",
"sentence",
"=",
"__sort_analyses",
"(",
"s... | 51.166667 | 22.25 |
def api_secret(self, api_secret):
"""
Sets the api_secret of this GlobalSignCredentials.
API Secret matching the API key (provided by GlobalSign).
:param api_secret: The api_secret of this GlobalSignCredentials.
:type: str
"""
if api_secret is None:
... | [
"def",
"api_secret",
"(",
"self",
",",
"api_secret",
")",
":",
"if",
"api_secret",
"is",
"None",
":",
"raise",
"ValueError",
"(",
"\"Invalid value for `api_secret`, must not be `None`\"",
")",
"if",
"api_secret",
"is",
"not",
"None",
"and",
"len",
"(",
"api_secret... | 41.714286 | 23.285714 |
def to_tnw(orbit):
"""In the TNW Local Orbital Reference Frame, x is oriented along the velocity vector,
z along the angular momentum, and y complete the frame.
Args:
orbit (list): Array of length 6
Return:
numpy.ndarray: matrix to convert from inertial frame to TNW.
>>> delta_tnw ... | [
"def",
"to_tnw",
"(",
"orbit",
")",
":",
"pos",
",",
"vel",
"=",
"_split",
"(",
"orbit",
")",
"t",
"=",
"vel",
"/",
"norm",
"(",
"vel",
")",
"w",
"=",
"np",
".",
"cross",
"(",
"pos",
",",
"vel",
")",
"/",
"(",
"norm",
"(",
"pos",
")",
"*",
... | 27.538462 | 19.461538 |
def tmDiff(tm1, tm2, verbosity = 0, relaxSegmentTests =True):
"""
Given two TM instances, list the difference between them and returns False
if there is a difference. This function checks the major parameters. If this
passes (and checkLearn is true) it checks the number of segments on
each cell. If this passe... | [
"def",
"tmDiff",
"(",
"tm1",
",",
"tm2",
",",
"verbosity",
"=",
"0",
",",
"relaxSegmentTests",
"=",
"True",
")",
":",
"# First check basic parameters. If we fail here, don't continue",
"if",
"sameTMParams",
"(",
"tm1",
",",
"tm2",
")",
"==",
"False",
":",
"print... | 37.839506 | 23.246914 |
def get_value(self, dictionary):
"""
Given the input dictionary, return the field value.
"""
# We override the default field access in order to support
# lists in HTML forms.
if html.is_html_input(dictionary):
return html.parse_html_list(dictionary, prefix=sel... | [
"def",
"get_value",
"(",
"self",
",",
"dictionary",
")",
":",
"# We override the default field access in order to support",
"# lists in HTML forms.",
"if",
"html",
".",
"is_html_input",
"(",
"dictionary",
")",
":",
"return",
"html",
".",
"parse_html_list",
"(",
"diction... | 42.111111 | 12.555556 |
def remove_incomplete_upload(self, bucket_name, object_name):
"""
Remove all in-complete uploads for a given bucket_name and object_name.
:param bucket_name: Bucket to drop incomplete uploads
:param object_name: Name of object to remove incomplete uploads
:return: None
"... | [
"def",
"remove_incomplete_upload",
"(",
"self",
",",
"bucket_name",
",",
"object_name",
")",
":",
"is_valid_bucket_name",
"(",
"bucket_name",
")",
"is_non_empty_string",
"(",
"object_name",
")",
"recursive",
"=",
"True",
"uploads",
"=",
"self",
".",
"_list_incomplet... | 44.105263 | 20.315789 |
def stop(self):
"""Stop the sensor.
"""
# Check that everything is running
if not self._running:
logging.warning('PhoXi not running. Aborting stop')
return False
# Stop the subscribers
self._color_im_sub.unregister()
self._depth_im_sub.unr... | [
"def",
"stop",
"(",
"self",
")",
":",
"# Check that everything is running",
"if",
"not",
"self",
".",
"_running",
":",
"logging",
".",
"warning",
"(",
"'PhoXi not running. Aborting stop'",
")",
"return",
"False",
"# Stop the subscribers",
"self",
".",
"_color_im_sub",... | 27 | 16.578947 |
def add_query_params(self, query_params):
'''Overwrite the given query parameters.
This is the same as :meth:`Queryable.set_query_params`,
except it overwrites existing parameters individually
whereas ``set_query_params`` deletes all existing key in
``query_params``.
'''... | [
"def",
"add_query_params",
"(",
"self",
",",
"query_params",
")",
":",
"query_params",
"=",
"as_multi_dict",
"(",
"query_params",
")",
"for",
"k",
"in",
"query_params",
":",
"self",
".",
"query_params",
".",
"pop",
"(",
"k",
",",
"None",
")",
"for",
"v",
... | 38.133333 | 14.4 |
def from_header(cls, header, beam=None, lat=None):
"""
Create a new WCSHelper class from the given header.
Parameters
----------
header : `astropy.fits.HDUHeader` or string
The header to be used to create the WCS helper
beam : :class:`AegeanTools.fits_image.... | [
"def",
"from_header",
"(",
"cls",
",",
"header",
",",
"beam",
"=",
"None",
",",
"lat",
"=",
"None",
")",
":",
"try",
":",
"wcs",
"=",
"pywcs",
".",
"WCS",
"(",
"header",
",",
"naxis",
"=",
"2",
")",
"except",
":",
"# TODO: figure out what error is bein... | 30.833333 | 21.111111 |
def register_timer(period, target=None):
"""Add timer.
Can be used as a decorator:
.. code-block:: python
@register_timer(3)
def repeat():
do()
:param int period: The interval (seconds) at which to raise the signal.
:param int|Signal|str|unicode targe... | [
"def",
"register_timer",
"(",
"period",
",",
"target",
"=",
"None",
")",
":",
"return",
"_automate_signal",
"(",
"target",
",",
"func",
"=",
"lambda",
"sig",
":",
"uwsgi",
".",
"add_timer",
"(",
"int",
"(",
"sig",
")",
",",
"period",
")",
")"
] | 36.6 | 28.657143 |
def get_default(parser, section, option, default):
"""helper to get config settings with a default if not present"""
try:
result = parser.get(section, option)
except (ConfigParser.NoSectionError, ConfigParser.NoOptionError):
result = default
return result | [
"def",
"get_default",
"(",
"parser",
",",
"section",
",",
"option",
",",
"default",
")",
":",
"try",
":",
"result",
"=",
"parser",
".",
"get",
"(",
"section",
",",
"option",
")",
"except",
"(",
"ConfigParser",
".",
"NoSectionError",
",",
"ConfigParser",
... | 40.142857 | 16.285714 |
def via_scan():
""" IP scan - now implemented """
import socket
import ipaddress
import httpfind
bridges_from_scan = []
hosts = socket.gethostbyname_ex(socket.gethostname())[2]
for host in hosts:
bridges_from_scan += httpfind.survey(
# TODO: how do we determine subnet con... | [
"def",
"via_scan",
"(",
")",
":",
"import",
"socket",
"import",
"ipaddress",
"import",
"httpfind",
"bridges_from_scan",
"=",
"[",
"]",
"hosts",
"=",
"socket",
".",
"gethostbyname_ex",
"(",
"socket",
".",
"gethostname",
"(",
")",
")",
"[",
"2",
"]",
"for",
... | 37.107143 | 17.357143 |
def all_minutes(self):
"""
Returns a DatetimeIndex representing all the minutes in this calendar.
"""
opens_in_ns = self._opens.values.astype(
'datetime64[ns]',
).view('int64')
closes_in_ns = self._closes.values.astype(
'datetime64[ns]',
)... | [
"def",
"all_minutes",
"(",
"self",
")",
":",
"opens_in_ns",
"=",
"self",
".",
"_opens",
".",
"values",
".",
"astype",
"(",
"'datetime64[ns]'",
",",
")",
".",
"view",
"(",
"'int64'",
")",
"closes_in_ns",
"=",
"self",
".",
"_closes",
".",
"values",
".",
... | 27.5 | 18.25 |
def strings(self):
""" Return lat/lon as strings. """
return [
toString(self.lat, LAT),
toString(self.lon, LON)
] | [
"def",
"strings",
"(",
"self",
")",
":",
"return",
"[",
"toString",
"(",
"self",
".",
"lat",
",",
"LAT",
")",
",",
"toString",
"(",
"self",
".",
"lon",
",",
"LON",
")",
"]"
] | 26 | 14.333333 |
def persist(self, container: Container, image_name: str) -> None:
"""
Persists the state of a given container as a Docker image on the
server.
Parameters:
container: the container that should be persisted.
image_name: the name of the Docker image that should be c... | [
"def",
"persist",
"(",
"self",
",",
"container",
":",
"Container",
",",
"image_name",
":",
"str",
")",
"->",
"None",
":",
"logger",
".",
"debug",
"(",
"\"attempting to persist container (%s) to image (%s).\"",
",",
"container",
".",
"id",
",",
"image_name",
")",... | 40.5 | 20.5625 |
def make_library(self, diffuse_yaml, catalog_yaml, binning_yaml):
""" Build up the library of all the components
Parameters
----------
diffuse_yaml : str
Name of the yaml file with the library of diffuse component definitions
catalog_yaml : str
Name of t... | [
"def",
"make_library",
"(",
"self",
",",
"diffuse_yaml",
",",
"catalog_yaml",
",",
"binning_yaml",
")",
":",
"ret_dict",
"=",
"{",
"}",
"#catalog_dict = yaml.safe_load(open(catalog_yaml))",
"components_dict",
"=",
"Component",
".",
"build_from_yamlfile",
"(",
"binning_y... | 49 | 25.269231 |
def set(context="notebook", style="darkgrid", palette="deep",
font="sans-serif", font_scale=1, color_codes=False, rc=None):
"""Set aesthetic parameters in one step.
Each set of parameters can be set directly or temporarily, see the
referenced functions below for more information.
Parameters
... | [
"def",
"set",
"(",
"context",
"=",
"\"notebook\"",
",",
"style",
"=",
"\"darkgrid\"",
",",
"palette",
"=",
"\"deep\"",
",",
"font",
"=",
"\"sans-serif\"",
",",
"font_scale",
"=",
"1",
",",
"color_codes",
"=",
"False",
",",
"rc",
"=",
"None",
")",
":",
... | 40.566667 | 17.466667 |
def state_probability(self, direction, repertoire, purview,):
"""Compute the probability of the purview in its current state given
the repertoire.
Collapses the dimensions of the repertoire that correspond to the
purview nodes onto their state. All other dimension are already
si... | [
"def",
"state_probability",
"(",
"self",
",",
"direction",
",",
"repertoire",
",",
"purview",
",",
")",
":",
"purview_state",
"=",
"self",
".",
"purview_state",
"(",
"direction",
")",
"index",
"=",
"tuple",
"(",
"node_state",
"if",
"node",
"in",
"purview",
... | 40.375 | 21.1875 |
def update_state(self):
"""Find out whether the media box is turned on/off."""
sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
sock.settimeout(self._timeout)
try:
if sock.connect_ex((self._ip, self._port['state'])) == 0:
self.state = True
... | [
"def",
"update_state",
"(",
"self",
")",
":",
"sock",
"=",
"socket",
".",
"socket",
"(",
"socket",
".",
"AF_INET",
",",
"socket",
".",
"SOCK_STREAM",
")",
"sock",
".",
"settimeout",
"(",
"self",
".",
"_timeout",
")",
"try",
":",
"if",
"sock",
".",
"c... | 35.083333 | 15.583333 |
def delete_countries_geo_zone_by_id(cls, countries_geo_zone_id, **kwargs):
"""Delete CountriesGeoZone
Delete an instance of CountriesGeoZone by its ID.
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please pass async=True
>>> threa... | [
"def",
"delete_countries_geo_zone_by_id",
"(",
"cls",
",",
"countries_geo_zone_id",
",",
"*",
"*",
"kwargs",
")",
":",
"kwargs",
"[",
"'_return_http_data_only'",
"]",
"=",
"True",
"if",
"kwargs",
".",
"get",
"(",
"'async'",
")",
":",
"return",
"cls",
".",
"_... | 46.952381 | 25.190476 |
def banner(text, border='=', width=80):
"""Center _text_ in a banner _width_ wide with _border_ characters.
Args:
text (str): What to write in the banner
border (str): Border character
width (int): How long the border should be
"""
text_padding = '{0:^%d}' % (width)
LOG.info... | [
"def",
"banner",
"(",
"text",
",",
"border",
"=",
"'='",
",",
"width",
"=",
"80",
")",
":",
"text_padding",
"=",
"'{0:^%d}'",
"%",
"(",
"width",
")",
"LOG",
".",
"info",
"(",
"border",
"*",
"width",
")",
"LOG",
".",
"info",
"(",
"text_padding",
"."... | 32.833333 | 9.833333 |
def plot(self):
"""
Visualize the state.
:return: The generated figure.
:rtype: matplotlib.Figure
"""
width = 10
# The pleasing golden ratio.
height = width / 1.618
f = plt.figure(figsize=(width, height))
ax = f.add_subplot(111, projection... | [
"def",
"plot",
"(",
"self",
")",
":",
"width",
"=",
"10",
"# The pleasing golden ratio.",
"height",
"=",
"width",
"/",
"1.618",
"f",
"=",
"plt",
".",
"figure",
"(",
"figsize",
"=",
"(",
"width",
",",
"height",
")",
")",
"ax",
"=",
"f",
".",
"add_subp... | 24.533333 | 13.6 |
def rm_crypttab(name, config='/etc/crypttab'):
'''
Remove the named mapping from the crypttab. If the described entry does not
exist, nothing is changed, but the command succeeds by returning
``'absent'``. If a line is removed, it returns ``'change'``.
CLI Example:
.. code-block:: bash
... | [
"def",
"rm_crypttab",
"(",
"name",
",",
"config",
"=",
"'/etc/crypttab'",
")",
":",
"modified",
"=",
"False",
"criteria",
"=",
"_crypttab_entry",
"(",
"name",
"=",
"name",
")",
"# For each line in the config that does not match the criteria, add it to",
"# the list. At th... | 34.8 | 21.777778 |
def onRightUp(self, event=None):
""" right button up: put back to cursor mode"""
if event is None:
return
self.cursor_mode_action('rightup', event=event)
self.ForwardEvent(event=event.guiEvent) | [
"def",
"onRightUp",
"(",
"self",
",",
"event",
"=",
"None",
")",
":",
"if",
"event",
"is",
"None",
":",
"return",
"self",
".",
"cursor_mode_action",
"(",
"'rightup'",
",",
"event",
"=",
"event",
")",
"self",
".",
"ForwardEvent",
"(",
"event",
"=",
"eve... | 38.666667 | 11.166667 |
def _get_connection(self):
"""
Returns our cached LDAPObject, which may or may not be bound.
"""
if self._connection is None:
uri = self.settings.SERVER_URI
if callable(uri):
uri = uri()
self._connection = self.backend.ldap.initialize(... | [
"def",
"_get_connection",
"(",
"self",
")",
":",
"if",
"self",
".",
"_connection",
"is",
"None",
":",
"uri",
"=",
"self",
".",
"settings",
".",
"SERVER_URI",
"if",
"callable",
"(",
"uri",
")",
":",
"uri",
"=",
"uri",
"(",
")",
"self",
".",
"_connecti... | 31.736842 | 17.105263 |
def hysteresis_magic2(path_to_file='.', hyst_file="rmag_hysteresis.txt",
save=False, save_folder='.',
fmt="svg", plots=True):
"""
Calculates hysteresis parameters, saves them in rmag_hysteresis format file.
If selected, this function also plots hysteresis loops, d... | [
"def",
"hysteresis_magic2",
"(",
"path_to_file",
"=",
"'.'",
",",
"hyst_file",
"=",
"\"rmag_hysteresis.txt\"",
",",
"save",
"=",
"False",
",",
"save_folder",
"=",
"'.'",
",",
"fmt",
"=",
"\"svg\"",
",",
"plots",
"=",
"True",
")",
":",
"user",
",",
"meas_fi... | 45.827225 | 17.722513 |
def describe_snapshots(self, *snapshot_ids):
"""Describe available snapshots.
TODO: ownerSet, restorableBySet
"""
snapshot_set = {}
for pos, snapshot_id in enumerate(snapshot_ids):
snapshot_set["SnapshotId.%d" % (pos + 1)] = snapshot_id
query = self.query_fac... | [
"def",
"describe_snapshots",
"(",
"self",
",",
"*",
"snapshot_ids",
")",
":",
"snapshot_set",
"=",
"{",
"}",
"for",
"pos",
",",
"snapshot_id",
"in",
"enumerate",
"(",
"snapshot_ids",
")",
":",
"snapshot_set",
"[",
"\"SnapshotId.%d\"",
"%",
"(",
"pos",
"+",
... | 39.461538 | 13.230769 |
def _sigma_pi_loE(self, Tp):
"""
inclusive cross section for Tth < Tp < 2 GeV
Fit from experimental data
"""
m_p = self._m_p
m_pi = self._m_pi
Mres = 1.1883 # GeV
Gres = 0.2264 # GeV
s = 2 * m_p * (Tp + 2 * m_p) # center of mass energy
g... | [
"def",
"_sigma_pi_loE",
"(",
"self",
",",
"Tp",
")",
":",
"m_p",
"=",
"self",
".",
"_m_p",
"m_pi",
"=",
"self",
".",
"_m_pi",
"Mres",
"=",
"1.1883",
"# GeV",
"Gres",
"=",
"0.2264",
"# GeV",
"s",
"=",
"2",
"*",
"m_p",
"*",
"(",
"Tp",
"+",
"2",
"... | 28.888889 | 18.222222 |
def _process_patch_operation(cls, operation, obj, state):
"""
Args:
operation (dict): one patch operation in RFC 6902 format.
obj (object): an instance which is needed to be patched.
state (dict): inter-operations state storage
Returns:
processing... | [
"def",
"_process_patch_operation",
"(",
"cls",
",",
"operation",
",",
"obj",
",",
"state",
")",
":",
"field_operaion",
"=",
"operation",
"[",
"'op'",
"]",
"if",
"field_operaion",
"==",
"cls",
".",
"OP_REPLACE",
":",
"return",
"cls",
".",
"replace",
"(",
"o... | 39.677419 | 26.774194 |
def csv_tolist(path_to_file, **kwargs):
"""
Parse the csv file to a list of rows.
"""
result = []
encoding = kwargs.get('encoding', 'utf-8')
delimiter = kwargs.get('delimiter', ',')
dialect = kwargs.get('dialect', csv.excel)
_, _ext = path_to_file.split('.', 1)
try:
file... | [
"def",
"csv_tolist",
"(",
"path_to_file",
",",
"*",
"*",
"kwargs",
")",
":",
"result",
"=",
"[",
"]",
"encoding",
"=",
"kwargs",
".",
"get",
"(",
"'encoding'",
",",
"'utf-8'",
")",
"delimiter",
"=",
"kwargs",
".",
"get",
"(",
"'delimiter'",
",",
"','",... | 24.5 | 21.642857 |
def Read(self):
"""Reads a string from the input.
Returns:
str: input.
"""
encoded_string = self._file_object.readline()
if isinstance(encoded_string, py2to3.UNICODE_TYPE):
return encoded_string
try:
string = codecs.decode(encoded_string, self._encoding, self._errors)
ex... | [
"def",
"Read",
"(",
"self",
")",
":",
"encoded_string",
"=",
"self",
".",
"_file_object",
".",
"readline",
"(",
")",
"if",
"isinstance",
"(",
"encoded_string",
",",
"py2to3",
".",
"UNICODE_TYPE",
")",
":",
"return",
"encoded_string",
"try",
":",
"string",
... | 29.8 | 23.4 |
def main():
"""
Run autosub as a command-line program.
"""
parser = argparse.ArgumentParser()
parser.add_argument('source_path', help="Path to the video or audio file to subtitle",
nargs='?')
parser.add_argument('-C', '--concurrency', help="Number of concurrent API reques... | [
"def",
"main",
"(",
")",
":",
"parser",
"=",
"argparse",
".",
"ArgumentParser",
"(",
")",
"parser",
".",
"add_argument",
"(",
"'source_path'",
",",
"help",
"=",
"\"Path to the video or audio file to subtitle\"",
",",
"nargs",
"=",
"'?'",
")",
"parser",
".",
"a... | 41.275862 | 21.413793 |
def write_journal(self, journal_file_path):
"""Write the constructed journal in to the provided file.
Args:
journal_file_path (str): full path to output journal file
"""
# TODO: assert the extension is txt and not other
with open(journal_file_path, "w") as jrn_file:
... | [
"def",
"write_journal",
"(",
"self",
",",
"journal_file_path",
")",
":",
"# TODO: assert the extension is txt and not other",
"with",
"open",
"(",
"journal_file_path",
",",
"\"w\"",
")",
"as",
"jrn_file",
":",
"jrn_file",
".",
"write",
"(",
"self",
".",
"_journal_co... | 40.222222 | 15.555556 |
def NoExclusions(self):
"""Determine that there are no exclusion criterion in play
:return: True if there is no real boundary specification of any kind.
Simple method allowing parsers to short circuit the determination of
missingness, which can be moderately compute intensive.
... | [
"def",
"NoExclusions",
"(",
"self",
")",
":",
"if",
"len",
"(",
"self",
".",
"start_bounds",
")",
"+",
"len",
"(",
"self",
".",
"target_rs",
")",
"+",
"len",
"(",
"self",
".",
"ignored_rs",
")",
"==",
"0",
":",
"return",
"BoundaryCheck",
".",
"chrom"... | 42.181818 | 23.727273 |
def make_writeable(filename):
"""
Make sure that the file is writeable.
Useful if our source is read-only.
"""
if not os.access(filename, os.W_OK):
st = os.stat(filename)
new_permissions = stat.S_IMODE(st.st_mode) | stat.S_IWUSR
os.chmod(filename, new_permissions) | [
"def",
"make_writeable",
"(",
"filename",
")",
":",
"if",
"not",
"os",
".",
"access",
"(",
"filename",
",",
"os",
".",
"W_OK",
")",
":",
"st",
"=",
"os",
".",
"stat",
"(",
"filename",
")",
"new_permissions",
"=",
"stat",
".",
"S_IMODE",
"(",
"st",
... | 33.333333 | 5.777778 |
def _start_local_queue_process(self):
""" Starts the interchange process locally
Starts the interchange process locally and uses an internal command queue to
get the worker task and result ports that the interchange has bound to.
"""
comm_q = Queue(maxsize=10)
self.queue... | [
"def",
"_start_local_queue_process",
"(",
"self",
")",
":",
"comm_q",
"=",
"Queue",
"(",
"maxsize",
"=",
"10",
")",
"self",
".",
"queue_proc",
"=",
"Process",
"(",
"target",
"=",
"interchange",
".",
"starter",
",",
"args",
"=",
"(",
"comm_q",
",",
")",
... | 59.5 | 31.733333 |
def get_repository_config(namespace, config, snapshot_id):
"""Get a method configuration from the methods repository.
Args:
namespace (str): Methods namespace
config (str): config name
snapshot_id (int): snapshot_id of the method
Swagger:
https://api.firecloud.org/#!/Method... | [
"def",
"get_repository_config",
"(",
"namespace",
",",
"config",
",",
"snapshot_id",
")",
":",
"uri",
"=",
"\"configurations/{0}/{1}/{2}\"",
".",
"format",
"(",
"namespace",
",",
"config",
",",
"snapshot_id",
")",
"return",
"__get",
"(",
"uri",
")"
] | 35.384615 | 21.615385 |
def __deprecate_defaults(
self,
new_func: str,
bg_blend: Any,
alignment: Any = ...,
clear: Any = ...,
) -> None:
"""Return the parameters needed to recreate the current default state.
"""
if not __debug__:
return
fg = self.default_... | [
"def",
"__deprecate_defaults",
"(",
"self",
",",
"new_func",
":",
"str",
",",
"bg_blend",
":",
"Any",
",",
"alignment",
":",
"Any",
"=",
"...",
",",
"clear",
":",
"Any",
"=",
"...",
",",
")",
"->",
"None",
":",
"if",
"not",
"__debug__",
":",
"return"... | 32.881356 | 15.508475 |
def template(ctx, url, no_input, role_name): # pragma: no cover
""" Initialize a new role from a Cookiecutter URL. """
command_args = {
'role_name': role_name,
'subcommand': __name__,
'url': url,
'no_input': no_input,
}
t = Template(command_args)
t.execute() | [
"def",
"template",
"(",
"ctx",
",",
"url",
",",
"no_input",
",",
"role_name",
")",
":",
"# pragma: no cover",
"command_args",
"=",
"{",
"'role_name'",
":",
"role_name",
",",
"'subcommand'",
":",
"__name__",
",",
"'url'",
":",
"url",
",",
"'no_input'",
":",
... | 27.454545 | 18.545455 |
def load_cz2010_hourly_temp_data(
self, start, end, read_from_cache=True, write_to_cache=True
):
""" Load hourly CZ2010 temperature data from start date to end date (inclusive).
This is the primary convenience method for loading hourly CZ2010 temperature data.
Parameters
--... | [
"def",
"load_cz2010_hourly_temp_data",
"(",
"self",
",",
"start",
",",
"end",
",",
"read_from_cache",
"=",
"True",
",",
"write_to_cache",
"=",
"True",
")",
":",
"return",
"load_cz2010_hourly_temp_data",
"(",
"self",
".",
"usaf_id",
",",
"start",
",",
"end",
",... | 34.92 | 17.68 |
def _m2crypto_sign(message, ssldir=None, certname=None, **config):
""" Insert two new fields into the message dict and return it.
Those fields are:
- 'signature' - the computed RSA message digest of the JSON repr.
- 'certificate' - the base64 X509 certificate of the sending host.
"""
i... | [
"def",
"_m2crypto_sign",
"(",
"message",
",",
"ssldir",
"=",
"None",
",",
"certname",
"=",
"None",
",",
"*",
"*",
"config",
")",
":",
"if",
"ssldir",
"is",
"None",
"or",
"certname",
"is",
"None",
":",
"error",
"=",
"\"You must set the ssldir and certname key... | 37.064516 | 20.967742 |
async def stoplisten(self, connmark = -1):
'''
Can call without delegate
'''
if connmark is None:
connmark = self.connmark
self.scheduler.emergesend(ConnectionControlEvent(self, ConnectionControlEvent.STOPLISTEN, True, connmark)) | [
"async",
"def",
"stoplisten",
"(",
"self",
",",
"connmark",
"=",
"-",
"1",
")",
":",
"if",
"connmark",
"is",
"None",
":",
"connmark",
"=",
"self",
".",
"connmark",
"self",
".",
"scheduler",
".",
"emergesend",
"(",
"ConnectionControlEvent",
"(",
"self",
"... | 39.285714 | 22.428571 |
def variables(self, value):
"""
Setter for **self.__variables** attribute.
:param value: Attribute value.
:type value: dict
"""
if value is not None:
assert type(value) is dict, "'{0}' attribute: '{1}' type is not 'dict'!".format("variables", value)
... | [
"def",
"variables",
"(",
"self",
",",
"value",
")",
":",
"if",
"value",
"is",
"not",
"None",
":",
"assert",
"type",
"(",
"value",
")",
"is",
"dict",
",",
"\"'{0}' attribute: '{1}' type is not 'dict'!\"",
".",
"format",
"(",
"\"variables\"",
",",
"value",
")"... | 41.625 | 21.75 |
def write(self, data):
"""Write single record.
Args:
data: record data to write as string, byte array or byte sequence.
"""
block_remaining = _BLOCK_SIZE - self.__position % _BLOCK_SIZE
if block_remaining < _HEADER_LENGTH:
# Header won't fit into remainder
self.__writer.write('\x... | [
"def",
"write",
"(",
"self",
",",
"data",
")",
":",
"block_remaining",
"=",
"_BLOCK_SIZE",
"-",
"self",
".",
"__position",
"%",
"_BLOCK_SIZE",
"if",
"block_remaining",
"<",
"_HEADER_LENGTH",
":",
"# Header won't fit into remainder",
"self",
".",
"__writer",
".",
... | 34.8 | 18.4 |
def save_metadata(self, phase, data_name):
"""
Save metadata associated with the phase, such as the name of the pipeline, the name of the phase and the name
of the data being fit
"""
with open("{}/.metadata".format(make_path(phase)), "w+") as f:
f.write("pipeline={}\n... | [
"def",
"save_metadata",
"(",
"self",
",",
"phase",
",",
"data_name",
")",
":",
"with",
"open",
"(",
"\"{}/.metadata\"",
".",
"format",
"(",
"make_path",
"(",
"phase",
")",
")",
",",
"\"w+\"",
")",
"as",
"f",
":",
"f",
".",
"write",
"(",
"\"pipeline={}\... | 56 | 26 |
def set_default_viewport(self):
"""
Calculates the viewport based on the configured aspect ratio.
Will add black borders and center the viewport if the window
do not match the configured viewport.
If aspect ratio is None the viewport will be scaled
to the entire w... | [
"def",
"set_default_viewport",
"(",
"self",
")",
":",
"if",
"self",
".",
"aspect_ratio",
":",
"expected_width",
"=",
"int",
"(",
"self",
".",
"buffer_height",
"*",
"self",
".",
"aspect_ratio",
")",
"expected_height",
"=",
"int",
"(",
"expected_width",
"/",
"... | 39.75 | 19.964286 |
def get_perf_task(task_name, auth, url):
"""
function takes the a str object containing the name of an existing performance tasks and
issues a RESTFUL call to the IMC REST service. It will return a list
:param task_name: str containing the name of the performance task
:param auth: ... | [
"def",
"get_perf_task",
"(",
"task_name",
",",
"auth",
",",
"url",
")",
":",
"get_perf_task_url",
"=",
"\"/imcrs/perf/task?name=\"",
"+",
"task_name",
"+",
"\"&orderBy=taskId&desc=false\"",
"f_url",
"=",
"url",
"+",
"get_perf_task_url",
"response",
"=",
"requests",
... | 37.625 | 26.625 |
def delete(name,
purge=False,
force=False):
'''
Remove a user from the minion
Args:
name (str): The name of the user to delete
purge (bool, optional): Boolean value indicating that the user profile
should also be removed when the user account is deleted. I... | [
"def",
"delete",
"(",
"name",
",",
"purge",
"=",
"False",
",",
"force",
"=",
"False",
")",
":",
"if",
"six",
".",
"PY2",
":",
"name",
"=",
"_to_unicode",
"(",
"name",
")",
"# Check if the user exists",
"try",
":",
"user_info",
"=",
"win32net",
".",
"Ne... | 32.24 | 19.04 |
def export_to_file(request):
"""
Export a part of this source site's page tree to a JSON file
on this user's filesystem for subsequent import in a destination
site's Wagtail Admin
"""
if request.method == 'POST':
form = ExportForm(request.POST)
if form.is_valid():
pay... | [
"def",
"export_to_file",
"(",
"request",
")",
":",
"if",
"request",
".",
"method",
"==",
"'POST'",
":",
"form",
"=",
"ExportForm",
"(",
"request",
".",
"POST",
")",
"if",
"form",
".",
"is_valid",
"(",
")",
":",
"payload",
"=",
"export_pages",
"(",
"for... | 35.473684 | 20 |
def translate(patterns, *, flags=0):
"""Translate `fnmatch` pattern."""
flags = _flag_transform(flags)
return _wcparse.translate(_wcparse.split(patterns, flags), flags) | [
"def",
"translate",
"(",
"patterns",
",",
"*",
",",
"flags",
"=",
"0",
")",
":",
"flags",
"=",
"_flag_transform",
"(",
"flags",
")",
"return",
"_wcparse",
".",
"translate",
"(",
"_wcparse",
".",
"split",
"(",
"patterns",
",",
"flags",
")",
",",
"flags"... | 35.4 | 15.8 |
def query_disease():
"""
Returns list of diseases by query parameters
---
tags:
- Query functions
parameters:
- name: identifier
in: query
type: string
required: false
description: Disease identifier
default: DI-03832
- name: ref_id
... | [
"def",
"query_disease",
"(",
")",
":",
"allowed_str_args",
"=",
"[",
"'identifier'",
",",
"'ref_id'",
",",
"'ref_type'",
",",
"'name'",
",",
"'acronym'",
",",
"'description'",
"]",
"args",
"=",
"get_args",
"(",
"request_args",
"=",
"request",
".",
"args",
",... | 20.573529 | 20.779412 |
def ensure_dir(path):
"""
:param path: path to directory to be created
Create a directory if it does not already exist.
"""
if not os.path.exists(path):
# path does not exist, create the directory
os.mkdir(path)
else:
# The path exists, check that it is not a file
... | [
"def",
"ensure_dir",
"(",
"path",
")",
":",
"if",
"not",
"os",
".",
"path",
".",
"exists",
"(",
"path",
")",
":",
"# path does not exist, create the directory",
"os",
".",
"mkdir",
"(",
"path",
")",
"else",
":",
"# The path exists, check that it is not a file",
... | 33.076923 | 17.230769 |
def best_diff(img1, img2, opts):
"""Find the best alignment of two images that minimizes the differences.
Returns (diff, alignments) where ``diff`` is a difference map, and
``alignments`` is a tuple ((x1, y2), (x2, y2)).
See ``diff()`` for the description of the alignment numbers.
"""
w1, h1 =... | [
"def",
"best_diff",
"(",
"img1",
",",
"img2",
",",
"opts",
")",
":",
"w1",
",",
"h1",
"=",
"img1",
".",
"size",
"w2",
",",
"h2",
"=",
"img2",
".",
"size",
"w",
",",
"h",
"=",
"min",
"(",
"w1",
",",
"w2",
")",
",",
"min",
"(",
"h1",
",",
"... | 29.055556 | 16.305556 |
def get( self, instance, **kwargs ):
"""Return an attribute from an object using the Ref path.
instance
The object instance to traverse.
"""
target = instance
for attr in self._path:
target = getattr( target, attr )
return target | [
"def",
"get",
"(",
"self",
",",
"instance",
",",
"*",
"*",
"kwargs",
")",
":",
"target",
"=",
"instance",
"for",
"attr",
"in",
"self",
".",
"_path",
":",
"target",
"=",
"getattr",
"(",
"target",
",",
"attr",
")",
"return",
"target"
] | 29.3 | 11.9 |
def Sens_m2(poly, dist, **kws):
"""
Variance-based decomposition/Sobol' indices.
Second order sensitivity indices.
Args:
poly (Poly):
Polynomial to find second order Sobol indices on.
dist (Dist):
The distributions of the input used in ``poly``.
Returns:
... | [
"def",
"Sens_m2",
"(",
"poly",
",",
"dist",
",",
"*",
"*",
"kws",
")",
":",
"dim",
"=",
"len",
"(",
"dist",
")",
"if",
"poly",
".",
"dim",
"<",
"dim",
":",
"poly",
"=",
"chaospy",
".",
"poly",
".",
"setdim",
"(",
"poly",
",",
"len",
"(",
"dis... | 29.180328 | 21.04918 |
def atlasdb_get_zonefile_bits( zonefile_hash, con=None, path=None ):
"""
What bit(s) in a zonefile inventory does a zonefile hash correspond to?
Return their indexes in the bit field.
"""
with AtlasDBOpen(con=con, path=path) as dbcon:
sql = "SELECT inv_index FROM zonefiles WHERE zonefile_ha... | [
"def",
"atlasdb_get_zonefile_bits",
"(",
"zonefile_hash",
",",
"con",
"=",
"None",
",",
"path",
"=",
"None",
")",
":",
"with",
"AtlasDBOpen",
"(",
"con",
"=",
"con",
",",
"path",
"=",
"path",
")",
"as",
"dbcon",
":",
"sql",
"=",
"\"SELECT inv_index FROM zo... | 29.263158 | 20.315789 |
def record_magic(dct, magic_kind, magic_name, func):
"""Utility function to store a function as a magic of a specific kind.
Parameters
----------
dct : dict
A dictionary with 'line' and 'cell' subdicts.
magic_kind : str
Kind of magic to be stored.
magic_name : str
Key to sto... | [
"def",
"record_magic",
"(",
"dct",
",",
"magic_kind",
",",
"magic_name",
",",
"func",
")",
":",
"if",
"magic_kind",
"==",
"'line_cell'",
":",
"dct",
"[",
"'line'",
"]",
"[",
"magic_name",
"]",
"=",
"dct",
"[",
"'cell'",
"]",
"[",
"magic_name",
"]",
"="... | 25.190476 | 19.52381 |
def set_center_freq(self, center_freq):
"""Set center frequency and clear averaged PSD data"""
psd_state = {
'repeats': 0,
'freq_array': self._base_freq_array + self._lnb_lo + center_freq,
'pwr_array': None,
'update_lock': threading.Lock(),
'fu... | [
"def",
"set_center_freq",
"(",
"self",
",",
"center_freq",
")",
":",
"psd_state",
"=",
"{",
"'repeats'",
":",
"0",
",",
"'freq_array'",
":",
"self",
".",
"_base_freq_array",
"+",
"self",
".",
"_lnb_lo",
"+",
"center_freq",
",",
"'pwr_array'",
":",
"None",
... | 35.7 | 14.7 |
def _converttobitstring(cls, bs, offset=0, cache={}):
"""Convert bs to a bitstring and return it.
offset gives the suggested bit offset of first significant
bit, to optimise append etc.
"""
if isinstance(bs, Bits):
return bs
try:
return cache[(bs... | [
"def",
"_converttobitstring",
"(",
"cls",
",",
"bs",
",",
"offset",
"=",
"0",
",",
"cache",
"=",
"{",
"}",
")",
":",
"if",
"isinstance",
"(",
"bs",
",",
"Bits",
")",
":",
"return",
"bs",
"try",
":",
"return",
"cache",
"[",
"(",
"bs",
",",
"offset... | 35.25 | 14 |
def incver(self):
"""Increment all of the version numbers"""
d = {}
for p in self.__mapper__.attrs:
if p.key in ['vid','vname','fqname', 'version', 'cache_key']:
continue
if p.key == 'revision':
d[p.key] = self.revision + 1
else... | [
"def",
"incver",
"(",
"self",
")",
":",
"d",
"=",
"{",
"}",
"for",
"p",
"in",
"self",
".",
"__mapper__",
".",
"attrs",
":",
"if",
"p",
".",
"key",
"in",
"[",
"'vid'",
",",
"'vname'",
",",
"'fqname'",
",",
"'version'",
",",
"'cache_key'",
"]",
":"... | 28.642857 | 18.357143 |
def _docx_to_epub(
self):
"""*convert docx file to epub*
"""
self.log.debug('starting the ``_docx_to_epub`` method')
if self.footer:
footer = self._tmp_html_file(self.footer)
footer = '"%(footer)s"' % locals()
else:
footer = ""
... | [
"def",
"_docx_to_epub",
"(",
"self",
")",
":",
"self",
".",
"log",
".",
"debug",
"(",
"'starting the ``_docx_to_epub`` method'",
")",
"if",
"self",
".",
"footer",
":",
"footer",
"=",
"self",
".",
"_tmp_html_file",
"(",
"self",
".",
"footer",
")",
"footer",
... | 34.149425 | 19.08046 |
def handle_get_account(self, req):
"""Handles the GET v2/<account> call for getting account information.
Can only be called by an account .admin.
On success, a JSON dictionary will be returned containing the keys
`account_id`, `services`, and `users`. The `account_id` is the value
... | [
"def",
"handle_get_account",
"(",
"self",
",",
"req",
")",
":",
"account",
"=",
"req",
".",
"path_info_pop",
"(",
")",
"if",
"req",
".",
"path_info",
"or",
"not",
"account",
"or",
"account",
"[",
"0",
"]",
"==",
"'.'",
":",
"return",
"HTTPBadRequest",
... | 49.758621 | 17.931034 |
def matlab_compatible(name):
""" make a channel name compatible with Matlab variable naming
Parameters
----------
name : str
channel name
Returns
-------
compatible_name : str
channel name compatible with Matlab
"""
compatible_name = [ch if ch in ALLOWED_MATLAB_CH... | [
"def",
"matlab_compatible",
"(",
"name",
")",
":",
"compatible_name",
"=",
"[",
"ch",
"if",
"ch",
"in",
"ALLOWED_MATLAB_CHARS",
"else",
"\"_\"",
"for",
"ch",
"in",
"name",
"]",
"compatible_name",
"=",
"\"\"",
".",
"join",
"(",
"compatible_name",
")",
"if",
... | 26.416667 | 22.708333 |
def read(self, length, skip=False):
"""Consumes the first ``length`` bytes from the accumulator."""
if length > self.__size:
raise IndexError(
'Cannot pop %d bytes, %d bytes in buffer queue' % (length, self.__size))
self.position += length
self.__size -= lengt... | [
"def",
"read",
"(",
"self",
",",
"length",
",",
"skip",
"=",
"False",
")",
":",
"if",
"length",
">",
"self",
".",
"__size",
":",
"raise",
"IndexError",
"(",
"'Cannot pop %d bytes, %d bytes in buffer queue'",
"%",
"(",
"length",
",",
"self",
".",
"__size",
... | 36.021739 | 14.26087 |
def boolean(value):
"""
Configuration-friendly boolean type converter.
Supports both boolean-valued and string-valued inputs (e.g. from env vars).
"""
if isinstance(value, bool):
return value
if value == "":
return False
return strtobool(value) | [
"def",
"boolean",
"(",
"value",
")",
":",
"if",
"isinstance",
"(",
"value",
",",
"bool",
")",
":",
"return",
"value",
"if",
"value",
"==",
"\"\"",
":",
"return",
"False",
"return",
"strtobool",
"(",
"value",
")"
] | 19.928571 | 22.357143 |
def _fetch_all(self):
"""
Internal helper that fetches the ring from Redis, including any
inactive nodes/replicas. Returns a list of tuples (start, replica,
heartbeat, expired), where
* start: start of the range for which the replica is responsible
* replica: name of the ... | [
"def",
"_fetch_all",
"(",
"self",
")",
":",
"now",
"=",
"time",
".",
"time",
"(",
")",
"expiry_time",
"=",
"now",
"-",
"NODE_TIMEOUT",
"data",
"=",
"self",
".",
"conn",
".",
"zrange",
"(",
"self",
".",
"key",
",",
"0",
",",
"-",
"1",
",",
"withsc... | 34.16 | 22.56 |
def milestones(self):
'''Array of all milestones'''
if self.cache['milestones']: return self.cache['milestones']
milestone_xml = self.bc.list_milestones(self.id)
milestones = []
for node in ET.fromstring(milestone_xml).findall("milestone"):
milestones.append(Milestone... | [
"def",
"milestones",
"(",
"self",
")",
":",
"if",
"self",
".",
"cache",
"[",
"'milestones'",
"]",
":",
"return",
"self",
".",
"cache",
"[",
"'milestones'",
"]",
"milestone_xml",
"=",
"self",
".",
"bc",
".",
"list_milestones",
"(",
"self",
".",
"id",
")... | 38.166667 | 16 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.