text stringlengths 89 104k | code_tokens list | avg_line_len float64 7.91 980 | score float64 0 630 |
|---|---|---|---|
def _get_roles(self, username):
""" Get roles of a user
@str username: name of the user
@rtype: dict, format { 'roles': [<list of roles>],
'unusedgroups': [<list of groups not matching roles>] }
"""
groups = self._get_groups(username)
user_roles = self.roles.g... | [
"def",
"_get_roles",
"(",
"self",
",",
"username",
")",
":",
"groups",
"=",
"self",
".",
"_get_groups",
"(",
"username",
")",
"user_roles",
"=",
"self",
".",
"roles",
".",
"get_roles",
"(",
"groups",
")",
"cherrypy",
".",
"log",
".",
"error",
"(",
"msg... | 37.923077 | 12.230769 |
def covfilter(args):
"""
%prog covfilter blastfile fastafile
Fastafile is used to get the sizes of the queries. Two filters can be
applied, the id% and cov%.
"""
from jcvi.algorithms.supermap import supermap
from jcvi.utils.range import range_union
allowed_iterby = ("query", "query_sbj... | [
"def",
"covfilter",
"(",
"args",
")",
":",
"from",
"jcvi",
".",
"algorithms",
".",
"supermap",
"import",
"supermap",
"from",
"jcvi",
".",
"utils",
".",
"range",
"import",
"range_union",
"allowed_iterby",
"=",
"(",
"\"query\"",
",",
"\"query_sbjct\"",
")",
"p... | 31.976331 | 19.39645 |
def p_compilerDirective(p):
"""compilerDirective : '#' PRAGMA pragmaName '(' pragmaParameter ')'"""
directive = p[3].lower()
param = p[5]
if directive == 'include':
fname = param
if p.parser.file:
if os.path.dirname(p.parser.file):
fname = os.path.join(os.path... | [
"def",
"p_compilerDirective",
"(",
"p",
")",
":",
"directive",
"=",
"p",
"[",
"3",
"]",
".",
"lower",
"(",
")",
"param",
"=",
"p",
"[",
"5",
"]",
"if",
"directive",
"==",
"'include'",
":",
"fname",
"=",
"param",
"if",
"p",
".",
"parser",
".",
"fi... | 38.294118 | 15.529412 |
def run(self, d, x):
"""
This function filters multiple samples in a row.
**Args:**
* `d` : desired value (1 dimensional array)
* `x` : input matrix (2-dimensional array). Rows are samples,
columns are input arrays.
**Returns:**
* `y` : output value... | [
"def",
"run",
"(",
"self",
",",
"d",
",",
"x",
")",
":",
"# measure the data and check if the dimmension agree",
"N",
"=",
"len",
"(",
"x",
")",
"if",
"not",
"len",
"(",
"d",
")",
"==",
"N",
":",
"raise",
"ValueError",
"(",
"'The length of vector d and matri... | 31.869565 | 19.217391 |
def _get_site_class(self, sites):
"""
Return site class flag (0 if class A or B, that is rock, or 1 if
class C or D).
"""
siteclass = sites.siteclass
S = np.zeros_like(siteclass, dtype=np.float)
S[(siteclass == b'C') | (siteclass == b'D')] = 1
return S | [
"def",
"_get_site_class",
"(",
"self",
",",
"sites",
")",
":",
"siteclass",
"=",
"sites",
".",
"siteclass",
"S",
"=",
"np",
".",
"zeros_like",
"(",
"siteclass",
",",
"dtype",
"=",
"np",
".",
"float",
")",
"S",
"[",
"(",
"siteclass",
"==",
"b'C'",
")"... | 30.8 | 15.4 |
def mirror_stdout_stderr(self):
"""Simple STDOUT and STDERR mirroring used by _init_jupyter"""
# TODO: Ideally we could start collecting logs without pushing
fs_api = self._api.get_file_stream_api()
io_wrap.SimpleTee(sys.stdout, streaming_log.TextStreamPusher(
fs_api, OUTPUT_... | [
"def",
"mirror_stdout_stderr",
"(",
"self",
")",
":",
"# TODO: Ideally we could start collecting logs without pushing",
"fs_api",
"=",
"self",
".",
"_api",
".",
"get_file_stream_api",
"(",
")",
"io_wrap",
".",
"SimpleTee",
"(",
"sys",
".",
"stdout",
",",
"streaming_lo... | 61.875 | 20.375 |
def db_wb020(self, value=None):
""" Corresponds to IDD Field `db_wb020`
mean coincident dry-bulb temperature to
Wet-bulb temperature corresponding to 2.0% annual cumulative frequency of occurrence
Args:
value (float): value for IDD Field `db_wb020`
Unit: C
... | [
"def",
"db_wb020",
"(",
"self",
",",
"value",
"=",
"None",
")",
":",
"if",
"value",
"is",
"not",
"None",
":",
"try",
":",
"value",
"=",
"float",
"(",
"value",
")",
"except",
"ValueError",
":",
"raise",
"ValueError",
"(",
"'value {} need to be of type float... | 36.681818 | 21 |
def folderitem(self, obj, item, index):
"""Augment folder listing item
"""
url = item.get("url")
title = item.get("Title")
calibrator = obj.getCalibrator()
item["getDownFrom"] = self.localize_date(obj.getDownFrom())
item["getDownTo"] = self.localize_date(obj.getD... | [
"def",
"folderitem",
"(",
"self",
",",
"obj",
",",
"item",
",",
"index",
")",
":",
"url",
"=",
"item",
".",
"get",
"(",
"\"url\"",
")",
"title",
"=",
"item",
".",
"get",
"(",
"\"Title\"",
")",
"calibrator",
"=",
"obj",
".",
"getCalibrator",
"(",
")... | 35.666667 | 13.851852 |
def cases(ctx, case_id, to_json):
"""Display cases in the database."""
adapter = ctx.obj['adapter']
cases = []
if case_id:
case_obj = adapter.case({'case_id':case_id})
if not case_obj:
LOG.info("Case {0} does not exist in database".format(case_id))
return
... | [
"def",
"cases",
"(",
"ctx",
",",
"case_id",
",",
"to_json",
")",
":",
"adapter",
"=",
"ctx",
".",
"obj",
"[",
"'adapter'",
"]",
"cases",
"=",
"[",
"]",
"if",
"case_id",
":",
"case_obj",
"=",
"adapter",
".",
"case",
"(",
"{",
"'case_id'",
":",
"case... | 27.333333 | 20.888889 |
def _setup_transport(self):
"""
Wrap the socket in an SSL object, either the
new Python 2.6 version, or the older Python 2.5 and
lower version.
"""
if HAVE_PY26_SSL:
if hasattr(self, 'sslopts'):
self.sslobj = ssl.wrap_socket(self.sock, **self.... | [
"def",
"_setup_transport",
"(",
"self",
")",
":",
"if",
"HAVE_PY26_SSL",
":",
"if",
"hasattr",
"(",
"self",
",",
"'sslopts'",
")",
":",
"self",
".",
"sslobj",
"=",
"ssl",
".",
"wrap_socket",
"(",
"self",
".",
"sock",
",",
"*",
"*",
"self",
".",
"sslo... | 32.666667 | 14.933333 |
def make_complete_url(environ, localUri=None):
"""URL reconstruction according to PEP 333.
@see https://www.python.org/dev/peps/pep-3333/#url-reconstruction
"""
url = environ["wsgi.url_scheme"] + "://"
if environ.get("HTTP_HOST"):
url += environ["HTTP_HOST"]
else:
url += environ... | [
"def",
"make_complete_url",
"(",
"environ",
",",
"localUri",
"=",
"None",
")",
":",
"url",
"=",
"environ",
"[",
"\"wsgi.url_scheme\"",
"]",
"+",
"\"://\"",
"if",
"environ",
".",
"get",
"(",
"\"HTTP_HOST\"",
")",
":",
"url",
"+=",
"environ",
"[",
"\"HTTP_HO... | 32.148148 | 16 |
def ensure_path(path, mode=0o777):
"""Ensure that path exists in a multiprocessing safe way.
If the path does not exist, recursively create it and its parent
directories using the provided mode. If the path already exists,
do nothing. The umask is cleared to enable the mode to be set,
and then re... | [
"def",
"ensure_path",
"(",
"path",
",",
"mode",
"=",
"0o777",
")",
":",
"if",
"path",
":",
"try",
":",
"umask",
"=",
"os",
".",
"umask",
"(",
"000",
")",
"os",
".",
"makedirs",
"(",
"path",
",",
"mode",
")",
"os",
".",
"umask",
"(",
"umask",
")... | 29.21875 | 20.78125 |
def hpa(disks, size=None):
'''
Get/set Host Protected Area settings
T13 INCITS 346-2001 (1367D) defines the BEER (Boot Engineering Extension Record)
and PARTIES (Protected Area Run Time Interface Extension Services), allowing
for a Host Protected Area on a disk.
It's often used by OEMS to hide... | [
"def",
"hpa",
"(",
"disks",
",",
"size",
"=",
"None",
")",
":",
"hpa_data",
"=",
"{",
"}",
"for",
"disk",
",",
"data",
"in",
"hdparms",
"(",
"disks",
",",
"'N'",
")",
".",
"items",
"(",
")",
":",
"visible",
",",
"total",
",",
"status",
"=",
"da... | 28.358491 | 21.754717 |
def _set_TC1(self, v, load=False):
"""
Setter method for TC1, mapped from YANG variable /policy_map/class/scheduler/strict_priority/TC1 (shaping-rate-limit)
If this variable is read-only (config: false) in the
source YANG file, then _set_TC1 is considered as a private
method. Backends looking to pop... | [
"def",
"_set_TC1",
"(",
"self",
",",
"v",
",",
"load",
"=",
"False",
")",
":",
"if",
"hasattr",
"(",
"v",
",",
"\"_utype\"",
")",
":",
"v",
"=",
"v",
".",
"_utype",
"(",
"v",
")",
"try",
":",
"t",
"=",
"YANGDynClass",
"(",
"v",
",",
"base",
"... | 89.772727 | 43.409091 |
def print_meminfo(meminfo, widelayout, incolor):
''' Memory information output function. '''
sep = ' '
# prep Mem numbers
totl = meminfo.memtotal
cach = meminfo.cached + meminfo.buffers
free = meminfo.memfree
used = meminfo.used
usep = float(used) / totl * 100 # % used of tota... | [
"def",
"print_meminfo",
"(",
"meminfo",
",",
"widelayout",
",",
"incolor",
")",
":",
"sep",
"=",
"' '",
"# prep Mem numbers",
"totl",
"=",
"meminfo",
".",
"memtotal",
"cach",
"=",
"meminfo",
".",
"cached",
"+",
"meminfo",
".",
"buffers",
"free",
"=",
"memi... | 34.481818 | 20.427273 |
def lookup_token(self, line, col):
"""Given a minified location, this tries to locate the closest
token that is a match. Returns `None` if no match can be found.
"""
# Silently ignore underflows
if line < 0 or col < 0:
return None
tok_out = _ffi.new('lsm_toke... | [
"def",
"lookup_token",
"(",
"self",
",",
"line",
",",
"col",
")",
":",
"# Silently ignore underflows",
"if",
"line",
"<",
"0",
"or",
"col",
"<",
"0",
":",
"return",
"None",
"tok_out",
"=",
"_ffi",
".",
"new",
"(",
"'lsm_token_t *'",
")",
"if",
"rustcall"... | 42.545455 | 9 |
def is_superuser(self):
"""Evaluates whether this user has admin privileges.
:returns: ``True`` or ``False``.
"""
admin_roles = utils.get_admin_roles()
user_roles = {role['name'].lower() for role in self.roles}
return not admin_roles.isdisjoint(user_roles) | [
"def",
"is_superuser",
"(",
"self",
")",
":",
"admin_roles",
"=",
"utils",
".",
"get_admin_roles",
"(",
")",
"user_roles",
"=",
"{",
"role",
"[",
"'name'",
"]",
".",
"lower",
"(",
")",
"for",
"role",
"in",
"self",
".",
"roles",
"}",
"return",
"not",
... | 37.25 | 12.625 |
def delete(self, data, *args):
"""
Custom handling for deleting orderlines.
Orderlines are deleted by issuing a DELETE on the orders/*/lines endpoint,
with the orderline IDs and quantities in the request body.
"""
path = self.get_resource_name()
result = self.per... | [
"def",
"delete",
"(",
"self",
",",
"data",
",",
"*",
"args",
")",
":",
"path",
"=",
"self",
".",
"get_resource_name",
"(",
")",
"result",
"=",
"self",
".",
"perform_api_call",
"(",
"self",
".",
"REST_DELETE",
",",
"path",
",",
"data",
"=",
"data",
")... | 38.1 | 17.9 |
def update(self, campaign_id, budget, nick=None):
'''xxxxx.xxxxx.campaign.budget.update
===================================
更新一个推广计划的日限额'''
request = TOPRequest('xxxxx.xxxxx.campaign.budget.update')
request['campaign_id'] = campaign_id
request['budget'] = budget
i... | [
"def",
"update",
"(",
"self",
",",
"campaign_id",
",",
"budget",
",",
"nick",
"=",
"None",
")",
":",
"request",
"=",
"TOPRequest",
"(",
"'xxxxx.xxxxx.campaign.budget.update'",
")",
"request",
"[",
"'campaign_id'",
"]",
"=",
"campaign_id",
"request",
"[",
"'bud... | 52.1 | 19.5 |
def _on_state(self, state, client):
"""
Launch forward prediction for the new state given by some client.
"""
def cb(outputs):
try:
distrib, value = outputs.result()
except CancelledError:
logger.info("Client {} cancelled.".format(c... | [
"def",
"_on_state",
"(",
"self",
",",
"state",
",",
"client",
")",
":",
"def",
"cb",
"(",
"outputs",
")",
":",
"try",
":",
"distrib",
",",
"value",
"=",
"outputs",
".",
"result",
"(",
")",
"except",
"CancelledError",
":",
"logger",
".",
"info",
"(",
... | 44.375 | 16.625 |
def optimize(self, method="simplex", verbosity=False, tolerance=1e-9, **kwargs):
"""Run the linprog function on the problem. Returns None."""
c = np.array([self.objective.get(name, 0) for name in self._variables])
if self.direction == "max":
c *= -1
bounds = list(six.iterval... | [
"def",
"optimize",
"(",
"self",
",",
"method",
"=",
"\"simplex\"",
",",
"verbosity",
"=",
"False",
",",
"tolerance",
"=",
"1e-9",
",",
"*",
"*",
"kwargs",
")",
":",
"c",
"=",
"np",
".",
"array",
"(",
"[",
"self",
".",
"objective",
".",
"get",
"(",
... | 44.263158 | 20.157895 |
def log(self, level, prefix = ''):
"""Writes the contents of the Rule to the logging system.
"""
logging.log(level, "%sin interface: %s", prefix, self.in_interface)
logging.log(level, "%sout interface: %s", prefix, self.out_interface)
logging.log(level, "%ssource: %s", prefix, se... | [
"def",
"log",
"(",
"self",
",",
"level",
",",
"prefix",
"=",
"''",
")",
":",
"logging",
".",
"log",
"(",
"level",
",",
"\"%sin interface: %s\"",
",",
"prefix",
",",
"self",
".",
"in_interface",
")",
"logging",
".",
"log",
"(",
"level",
",",
"\"%sout in... | 49.230769 | 14.307692 |
def flags(self, column):
"""Return the item flags for the item
Default is QtCore.Qt.ItemIsEnabled | QtCore.Qt.ItemIsSelectable
:param column: the column to query
:type column: int
:returns: the item flags
:rtype: QtCore.Qt.ItemFlags
:raises: None
"""
... | [
"def",
"flags",
"(",
"self",
",",
"column",
")",
":",
"flags",
"=",
"QtCore",
".",
"Qt",
".",
"ItemIsEnabled",
"|",
"QtCore",
".",
"Qt",
".",
"ItemIsSelectable",
"if",
"self",
".",
"_editable",
":",
"flags",
"=",
"flags",
"|",
"QtCore",
".",
"Qt",
".... | 31.466667 | 16.666667 |
def run_ppm_server(pdb_file, outfile, force_rerun=False):
"""Run the PPM server from OPM to predict transmembrane residues.
Args:
pdb_file (str): Path to PDB file
outfile (str): Path to output HTML results file
force_rerun (bool): Flag to rerun PPM if HTML results file already exists
... | [
"def",
"run_ppm_server",
"(",
"pdb_file",
",",
"outfile",
",",
"force_rerun",
"=",
"False",
")",
":",
"if",
"ssbio",
".",
"utils",
".",
"force_rerun",
"(",
"outfile",
"=",
"outfile",
",",
"flag",
"=",
"force_rerun",
")",
":",
"url",
"=",
"'http://sunshine.... | 33.863014 | 22.273973 |
def get_context_data(self, **kwargs):
"""
Include the name of the sub menu template in the context. This is
purely for backwards compatibility. Any sub menus rendered as part of
this menu will call `sub_menu_template` on the original menu instance
to get an actual `Template`
... | [
"def",
"get_context_data",
"(",
"self",
",",
"*",
"*",
"kwargs",
")",
":",
"data",
"=",
"{",
"}",
"if",
"self",
".",
"_contextual_vals",
".",
"current_level",
"==",
"1",
"and",
"self",
".",
"max_levels",
">",
"1",
":",
"data",
"[",
"'sub_menu_template'",... | 47 | 19.166667 |
def as_dict(self, ordered=False):
"""Returns the row as a dictionary, as ordered."""
items = zip(self.keys(), self.values())
return OrderedDict(items) if ordered else dict(items) | [
"def",
"as_dict",
"(",
"self",
",",
"ordered",
"=",
"False",
")",
":",
"items",
"=",
"zip",
"(",
"self",
".",
"keys",
"(",
")",
",",
"self",
".",
"values",
"(",
")",
")",
"return",
"OrderedDict",
"(",
"items",
")",
"if",
"ordered",
"else",
"dict",
... | 39.8 | 15 |
def write_toml(self, data, path=None):
"""Writes the given data structure out as TOML."""
if path is None:
path = self.pipfile_location
data = convert_toml_outline_tables(data)
try:
formatted_data = tomlkit.dumps(data).rstrip()
except Exception:
... | [
"def",
"write_toml",
"(",
"self",
",",
"data",
",",
"path",
"=",
"None",
")",
":",
"if",
"path",
"is",
"None",
":",
"path",
"=",
"self",
".",
"pipfile_location",
"data",
"=",
"convert_toml_outline_tables",
"(",
"data",
")",
"try",
":",
"formatted_data",
... | 43.151515 | 16.181818 |
def _check_json_data(self, json_data):
"""
Ensure that the request body is both a hash and has a data key.
:param json_data: The json data provided with the request
"""
if not isinstance(json_data, dict):
raise BadRequestError('Request body should be a JSON hash')
... | [
"def",
"_check_json_data",
"(",
"self",
",",
"json_data",
")",
":",
"if",
"not",
"isinstance",
"(",
"json_data",
",",
"dict",
")",
":",
"raise",
"BadRequestError",
"(",
"'Request body should be a JSON hash'",
")",
"if",
"'data'",
"not",
"in",
"json_data",
".",
... | 42 | 16.2 |
def extract_images_jbig2(pike, root, log, options):
"""Extract any bitonal image that we think we can improve as JBIG2"""
jbig2_groups = defaultdict(list)
for pageno, xref, ext in extract_images(
pike, root, log, options, extract_image_jbig2
):
group = pageno // options.jbig2_page_group... | [
"def",
"extract_images_jbig2",
"(",
"pike",
",",
"root",
",",
"log",
",",
"options",
")",
":",
"jbig2_groups",
"=",
"defaultdict",
"(",
"list",
")",
"for",
"pageno",
",",
"xref",
",",
"ext",
"in",
"extract_images",
"(",
"pike",
",",
"root",
",",
"log",
... | 36.9375 | 20.625 |
def accuracy_study(tdm=None, u=None, s=None, vt=None, verbosity=0, **kwargs):
""" Reconstruct the term-document matrix and measure error as SVD terms are truncated
"""
smat = np.zeros((len(u), len(vt)))
np.fill_diagonal(smat, s)
smat = pd.DataFrame(smat, columns=vt.index, index=u.index)
if verbo... | [
"def",
"accuracy_study",
"(",
"tdm",
"=",
"None",
",",
"u",
"=",
"None",
",",
"s",
"=",
"None",
",",
"vt",
"=",
"None",
",",
"verbosity",
"=",
"0",
",",
"*",
"*",
"kwargs",
")",
":",
"smat",
"=",
"np",
".",
"zeros",
"(",
"(",
"len",
"(",
"u",... | 38.066667 | 18.511111 |
def add_method(cls):
"""Attach a method to a class."""
def wrapper(f):
#if hasattr(cls, f.__name__):
# raise AttributeError("{} already has a '{}' attribute".format(
# cls.__name__, f.__name__))
setattr(cls, f.__name__, f)
return f
return wrapper | [
"def",
"add_method",
"(",
"cls",
")",
":",
"def",
"wrapper",
"(",
"f",
")",
":",
"#if hasattr(cls, f.__name__):",
"# raise AttributeError(\"{} already has a '{}' attribute\".format(",
"# cls.__name__, f.__name__))",
"setattr",
"(",
"cls",
",",
"f",
".",
"__name__"... | 33.333333 | 14.777778 |
def fd_sine_gaussian(amp, quality, central_frequency, fmin, fmax, delta_f):
""" Generate a Fourier domain sine-Gaussian
Parameters
----------
amp: float
Amplitude of the sine-Gaussian
quality: float
The quality factor
central_frequency: float
The central frequency of the... | [
"def",
"fd_sine_gaussian",
"(",
"amp",
",",
"quality",
",",
"central_frequency",
",",
"fmin",
",",
"fmax",
",",
"delta_f",
")",
":",
"kmin",
"=",
"int",
"(",
"round",
"(",
"fmin",
"/",
"delta_f",
")",
")",
"kmax",
"=",
"int",
"(",
"round",
"(",
"fmax... | 34.176471 | 16.764706 |
def setup_saver(self):
"""
Creates the tf.train.Saver object and stores it in self.saver.
"""
if self.execution_type == "single":
global_variables = self.get_variables(include_submodules=True, include_nontrainable=True)
else:
global_variables = self.global... | [
"def",
"setup_saver",
"(",
"self",
")",
":",
"if",
"self",
".",
"execution_type",
"==",
"\"single\"",
":",
"global_variables",
"=",
"self",
".",
"get_variables",
"(",
"include_submodules",
"=",
"True",
",",
"include_nontrainable",
"=",
"True",
")",
"else",
":"... | 36.151515 | 18.878788 |
def _get_xml(self, *args, **kwargs):
"""Wrapper around Requests for GET XML requests
Returns:
Response:
A Requests Response object
"""
req = self.session_xml.get(*args, **kwargs)
return req | [
"def",
"_get_xml",
"(",
"self",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"req",
"=",
"self",
".",
"session_xml",
".",
"get",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
"return",
"req"
] | 27.777778 | 13.555556 |
def domain_to_fqdn(domain, proto=None):
""" returns a fully qualified app domain name """
from .generic import get_site_proto
proto = proto or get_site_proto()
fdqn = '{proto}://{domain}'.format(proto=proto, domain=domain)
return fdqn | [
"def",
"domain_to_fqdn",
"(",
"domain",
",",
"proto",
"=",
"None",
")",
":",
"from",
".",
"generic",
"import",
"get_site_proto",
"proto",
"=",
"proto",
"or",
"get_site_proto",
"(",
")",
"fdqn",
"=",
"'{proto}://{domain}'",
".",
"format",
"(",
"proto",
"=",
... | 41.5 | 9.333333 |
def writeUndo(self, varBind, **context):
"""Finalize Managed Object Instance modification.
Implements the third (unsuccessful) step of the multi-step workflow
of the SNMP SET command processing (:RFC:`1905#section-4.2.5`).
The goal of the third phase is to roll the Managed Object Insta... | [
"def",
"writeUndo",
"(",
"self",
",",
"varBind",
",",
"*",
"*",
"context",
")",
":",
"name",
",",
"val",
"=",
"varBind",
"(",
"debug",
".",
"logger",
"&",
"debug",
".",
"FLAG_INS",
"and",
"debug",
".",
"logger",
"(",
"'%s: writeUndo(%s, %r)'",
"%",
"("... | 35.825397 | 27.285714 |
def flattened(value, split=None):
"""
Args:
value: Possibly nested arguments (sequence of lists, nested lists)
split (int | str | unicode | (str | unicode, int) | None): How to split values:
- None: simply flatten, no further processing
- one char string: split() on speci... | [
"def",
"flattened",
"(",
"value",
",",
"split",
"=",
"None",
")",
":",
"result",
"=",
"[",
"]",
"separator",
"=",
"None",
"mode",
"=",
"0",
"if",
"isinstance",
"(",
"split",
",",
"tuple",
")",
":",
"separator",
",",
"mode",
"=",
"split",
"elif",
"i... | 35.52 | 21.6 |
def decrypt(self, key, flags=0):
"""
Decrypts encrypted data message
@param key - symmetic key to decrypt
@param flags - OR-ed combination of Flags constant
"""
bio = Membio()
if libcrypto.CMS_EncryptedData_decrypt(self.ptr, key, len(key), None,
... | [
"def",
"decrypt",
"(",
"self",
",",
"key",
",",
"flags",
"=",
"0",
")",
":",
"bio",
"=",
"Membio",
"(",
")",
"if",
"libcrypto",
".",
"CMS_EncryptedData_decrypt",
"(",
"self",
".",
"ptr",
",",
"key",
",",
"len",
"(",
"key",
")",
",",
"None",
",",
... | 38.818182 | 12.090909 |
def simplex_optimal(self, t):
'''
API:
simplex_optimal(self, t)
Description:
Checks if the current solution is optimal, if yes returns True,
False otherwise.
Pre:
'flow' attributes represents a solution.
Input:
t: Graph ... | [
"def",
"simplex_optimal",
"(",
"self",
",",
"t",
")",
":",
"for",
"e",
"in",
"self",
".",
"edge_attr",
":",
"if",
"e",
"in",
"t",
".",
"edge_attr",
":",
"continue",
"flow_ij",
"=",
"self",
".",
"edge_attr",
"[",
"e",
"]",
"[",
"'flow'",
"]",
"poten... | 36.774194 | 17.225806 |
def create_connection(self):
"""See: https://github.com/python/cpython/blob/40ee9a3640d702bce127e9877c82a99ce817f0d1/Lib/socket.py#L691"""
err = None
try:
for res in socket.getaddrinfo(self._server, self._port, 0, self._sock_type):
af, socktype, proto, canonname, sa =... | [
"def",
"create_connection",
"(",
"self",
")",
":",
"err",
"=",
"None",
"try",
":",
"for",
"res",
"in",
"socket",
".",
"getaddrinfo",
"(",
"self",
".",
"_server",
",",
"self",
".",
"_port",
",",
"0",
",",
"self",
".",
"_sock_type",
")",
":",
"af",
"... | 40.366667 | 19.866667 |
def _euclidean_dist(vector_a, vector_b):
"""
:param vector_a: A list of numbers.
:param vector_b: A list of numbers.
:returns: The euclidean distance between the two vectors.
"""
dist = 0
for (x, y) in zip(vector_a, vector_b):
dist += (x-y)*(x-y)
return math.sqrt(... | [
"def",
"_euclidean_dist",
"(",
"vector_a",
",",
"vector_b",
")",
":",
"dist",
"=",
"0",
"for",
"(",
"x",
",",
"y",
")",
"in",
"zip",
"(",
"vector_a",
",",
"vector_b",
")",
":",
"dist",
"+=",
"(",
"x",
"-",
"y",
")",
"*",
"(",
"x",
"-",
"y",
"... | 31.6 | 9.2 |
def make_certificate_signing_request(pkey, digest='sha512', **name):
"""Make a certificate signing request.
:param OpenSSL.crypto.PKey pkey: A private key.
:param str digest: A valid digest to use. For example, `sha512`.
:param name: Key word arguments containing subject name parts: C, ST, L, O,
OU, CN.
... | [
"def",
"make_certificate_signing_request",
"(",
"pkey",
",",
"digest",
"=",
"'sha512'",
",",
"*",
"*",
"name",
")",
":",
"csr",
"=",
"crypto",
".",
"X509Req",
"(",
")",
"subj",
"=",
"csr",
".",
"get_subject",
"(",
")",
"subj",
".",
"C",
"=",
"name",
... | 31.565217 | 16.130435 |
def x(self):
""" Returns the scaled x positions of the points as doubles
"""
return scale_dimension(self.X, self.header.x_scale, self.header.x_offset) | [
"def",
"x",
"(",
"self",
")",
":",
"return",
"scale_dimension",
"(",
"self",
".",
"X",
",",
"self",
".",
"header",
".",
"x_scale",
",",
"self",
".",
"header",
".",
"x_offset",
")"
] | 42.75 | 17.25 |
def getKeywordsForText(self, retina_name, body, ):
"""Get a list of keywords from the text
Args:
retina_name, str: The retina name (required)
body, str: The text to be evaluated (required)
Returns: Array[str]
"""
resourcePath = '/text/keywords'
... | [
"def",
"getKeywordsForText",
"(",
"self",
",",
"retina_name",
",",
"body",
",",
")",
":",
"resourcePath",
"=",
"'/text/keywords'",
"method",
"=",
"'POST'",
"queryParams",
"=",
"{",
"}",
"headerParams",
"=",
"{",
"'Accept'",
":",
"'Application/json'",
",",
"'Co... | 35.052632 | 20.842105 |
def dst(self):
"""Return 0 if DST is not in effect, or the DST offset (in minutes
eastward) if DST is in effect.
This is purely informational; the DST offset has already been added to
the UTC offset returned by utcoffset() if applicable, so there's no
need to consult dst() unles... | [
"def",
"dst",
"(",
"self",
")",
":",
"if",
"self",
".",
"_tzinfo",
"is",
"None",
":",
"return",
"None",
"offset",
"=",
"self",
".",
"_tzinfo",
".",
"dst",
"(",
"None",
")",
"offset",
"=",
"_check_utc_offset",
"(",
"\"dst\"",
",",
"offset",
")",
"if",... | 39.75 | 18.1875 |
def main():
'''Main routine.'''
# Load Azure app defaults
try:
with open('azurermconfig.json') as config_file:
config_data = json.load(config_file)
except FileNotFoundError:
sys.exit("Error: Expecting azurermconfig.json in current folder")
tenant_id = config_data['tenant... | [
"def",
"main",
"(",
")",
":",
"# Load Azure app defaults",
"try",
":",
"with",
"open",
"(",
"'azurermconfig.json'",
")",
"as",
"config_file",
":",
"config_data",
"=",
"json",
".",
"load",
"(",
"config_file",
")",
"except",
"FileNotFoundError",
":",
"sys",
".",... | 34.5 | 19.416667 |
def auction(self, symbol='btcusd'):
"""Send a request for latest auction info, return the response."""
url = self.base_url + '/v1/auction/' + symbol
return requests.get(url) | [
"def",
"auction",
"(",
"self",
",",
"symbol",
"=",
"'btcusd'",
")",
":",
"url",
"=",
"self",
".",
"base_url",
"+",
"'/v1/auction/'",
"+",
"symbol",
"return",
"requests",
".",
"get",
"(",
"url",
")"
] | 38.8 | 13.2 |
def _new_extension(name, value, critical=0, issuer=None, _pyfree=1):
'''
Create new X509_Extension, This is required because M2Crypto
doesn't support getting the publickeyidentifier from the issuer
to create the authoritykeyidentifier extension.
'''
if name == 'subjectKeyIdentifier' and value.st... | [
"def",
"_new_extension",
"(",
"name",
",",
"value",
",",
"critical",
"=",
"0",
",",
"issuer",
"=",
"None",
",",
"_pyfree",
"=",
"1",
")",
":",
"if",
"name",
"==",
"'subjectKeyIdentifier'",
"and",
"value",
".",
"strip",
"(",
"'0123456789abcdefABCDEF:'",
")"... | 41.594595 | 22.081081 |
def close(self, code=None):
'''return a `close` :class:`Frame`.
'''
code = code or 1000
body = pack('!H', code)
body += self._close_codes.get(code, '').encode('utf-8')
return self.encode(body, opcode=0x8) | [
"def",
"close",
"(",
"self",
",",
"code",
"=",
"None",
")",
":",
"code",
"=",
"code",
"or",
"1000",
"body",
"=",
"pack",
"(",
"'!H'",
",",
"code",
")",
"body",
"+=",
"self",
".",
"_close_codes",
".",
"get",
"(",
"code",
",",
"''",
")",
".",
"en... | 35.142857 | 13.428571 |
def tempo_account_export_accounts(self):
"""
Get csv export file of Accounts from Tempo
:return: csv file
"""
headers = self.form_token_headers
url = 'rest/tempo-accounts/1/export'
return self.get(url, headers=headers, not_json_response=True) | [
"def",
"tempo_account_export_accounts",
"(",
"self",
")",
":",
"headers",
"=",
"self",
".",
"form_token_headers",
"url",
"=",
"'rest/tempo-accounts/1/export'",
"return",
"self",
".",
"get",
"(",
"url",
",",
"headers",
"=",
"headers",
",",
"not_json_response",
"=",... | 36.375 | 7.375 |
def clean():
"take out the trash"
src_dir = easy.options.setdefault("docs", {}).get('src_dir', None)
if src_dir is None:
src_dir = 'src' if easy.path('src').exists() else '.'
with easy.pushd(src_dir):
for pkg in set(easy.options.setup.packages) | set(("tests",)):
for filenam... | [
"def",
"clean",
"(",
")",
":",
"src_dir",
"=",
"easy",
".",
"options",
".",
"setdefault",
"(",
"\"docs\"",
",",
"{",
"}",
")",
".",
"get",
"(",
"'src_dir'",
",",
"None",
")",
"if",
"src_dir",
"is",
"None",
":",
"src_dir",
"=",
"'src'",
"if",
"easy"... | 41.2 | 23.6 |
def affix_stemmer(words, exception_list=exceptions, strip_pref = True, strip_suf = True):
"""
:param words: string list
The affix stemmer works by rule-based stripping. It can work on prefixes,
>>> affix_stemmer(['yesterday', 'yesterdom', 'yisterweek'])
'day dom week'
suffixes,
>>> affix... | [
"def",
"affix_stemmer",
"(",
"words",
",",
"exception_list",
"=",
"exceptions",
",",
"strip_pref",
"=",
"True",
",",
"strip_suf",
"=",
"True",
")",
":",
"for",
"i",
",",
"w",
"in",
"enumerate",
"(",
"words",
")",
":",
"try",
":",
"words",
"[",
"i",
"... | 22.875 | 24.7 |
def skos_hierarchical_mappings(rdf, narrower=True):
"""Infer skos:broadMatch/skos:narrowMatch (S43) and add the super-properties
skos:broader/skos:narrower (S41).
:param bool narrower: If set to False, skos:narrowMatch will not be added,
but rather removed.
"""
for s, o in rdf.subject_objec... | [
"def",
"skos_hierarchical_mappings",
"(",
"rdf",
",",
"narrower",
"=",
"True",
")",
":",
"for",
"s",
",",
"o",
"in",
"rdf",
".",
"subject_objects",
"(",
"SKOS",
".",
"broadMatch",
")",
":",
"rdf",
".",
"add",
"(",
"(",
"s",
",",
"SKOS",
".",
"broader... | 36.55 | 13.1 |
def stop_timer(self, func):
"""
Stops a timer if it hasn't fired yet
* func - the function passed in start_timer
"""
if func in self._timer_callbacks:
t = self._timer_callbacks[func]
t.cancel()
del self._timer_callbacks[func] | [
"def",
"stop_timer",
"(",
"self",
",",
"func",
")",
":",
"if",
"func",
"in",
"self",
".",
"_timer_callbacks",
":",
"t",
"=",
"self",
".",
"_timer_callbacks",
"[",
"func",
"]",
"t",
".",
"cancel",
"(",
")",
"del",
"self",
".",
"_timer_callbacks",
"[",
... | 29.3 | 9.3 |
def off_scheme(self, year):
"""Returns the name of the offensive scheme the team ran in the given
year.
:year: Int representing the season year.
:returns: A string representing the offensive scheme.
"""
scheme_text = self._year_info_pq(year, 'Offensive Scheme').text()
... | [
"def",
"off_scheme",
"(",
"self",
",",
"year",
")",
":",
"scheme_text",
"=",
"self",
".",
"_year_info_pq",
"(",
"year",
",",
"'Offensive Scheme'",
")",
".",
"text",
"(",
")",
"m",
"=",
"re",
".",
"search",
"(",
"r'Offensive Scheme[:\\s]*(.+)\\s*'",
",",
"s... | 35.538462 | 19.846154 |
def bake(self):
"""
Bake an ``ansible-playbook`` command so it's ready to execute and
returns ``None``.
:return: None
"""
# Pass a directory as inventory to let Ansible merge the multiple
# inventory sources located under
self.add_cli_arg('inventory',
... | [
"def",
"bake",
"(",
"self",
")",
":",
"# Pass a directory as inventory to let Ansible merge the multiple",
"# inventory sources located under",
"self",
".",
"add_cli_arg",
"(",
"'inventory'",
",",
"self",
".",
"_config",
".",
"provisioner",
".",
"inventory_directory",
")",
... | 36.787879 | 19.030303 |
def _parse_contract_headers(self, table):
"""
Parse the years on the contract.
The years are listed as the headers on the contract. The first header
contains 'Team' which specifies the player's current team and should
not be included in the years.
Parameters
---... | [
"def",
"_parse_contract_headers",
"(",
"self",
",",
"table",
")",
":",
"years",
"=",
"[",
"i",
".",
"text",
"(",
")",
"for",
"i",
"in",
"table",
"(",
"'th'",
")",
".",
"items",
"(",
")",
"]",
"years",
".",
"remove",
"(",
"'Team'",
")",
"return",
... | 30.5 | 20.136364 |
def _find_header_flat(self):
"""
Find header elements in a table, if possible. This case handles
situations where '<th>' elements are not within a row('<tr>')
"""
nodes = self._node.contents.filter_tags(
matches=ftag('th'), recursive=False)
if not node... | [
"def",
"_find_header_flat",
"(",
"self",
")",
":",
"nodes",
"=",
"self",
".",
"_node",
".",
"contents",
".",
"filter_tags",
"(",
"matches",
"=",
"ftag",
"(",
"'th'",
")",
",",
"recursive",
"=",
"False",
")",
"if",
"not",
"nodes",
":",
"return",
"self",... | 39.181818 | 17.727273 |
def isnap(self):
"""Snapshot index corresponding to time step.
It is set to None if no snapshot exists for the time step.
"""
if self._isnap is UNDETERMINED:
istep = None
isnap = -1
# could be more efficient if do 0 and -1 then bisection
#... | [
"def",
"isnap",
"(",
"self",
")",
":",
"if",
"self",
".",
"_isnap",
"is",
"UNDETERMINED",
":",
"istep",
"=",
"None",
"isnap",
"=",
"-",
"1",
"# could be more efficient if do 0 and -1 then bisection",
"# (but loose intermediate <- would probably use too much",
"# memory fo... | 42.368421 | 17.736842 |
def insert(self, start_time: int, schedule: ScheduleComponent) -> 'ScheduleComponent':
"""Return a new schedule with `schedule` inserted within `self` at `start_time`.
Args:
start_time: time to be inserted
schedule: schedule to be inserted
"""
return ops.insert(s... | [
"def",
"insert",
"(",
"self",
",",
"start_time",
":",
"int",
",",
"schedule",
":",
"ScheduleComponent",
")",
"->",
"'ScheduleComponent'",
":",
"return",
"ops",
".",
"insert",
"(",
"self",
",",
"start_time",
",",
"schedule",
")"
] | 42.375 | 16.75 |
def get_args():
u"""
./main --config /etc/blackbird/etc/default.cfg --debug ...
Return command-line options(arguments).
"""
description = "The Daemon send various value for zabbix_sender."
parser = argparse.ArgumentParser(description)
parser.add_argument('--config', '-c',
... | [
"def",
"get_args",
"(",
")",
":",
"description",
"=",
"\"The Daemon send various value for zabbix_sender.\"",
"parser",
"=",
"argparse",
".",
"ArgumentParser",
"(",
"description",
")",
"parser",
".",
"add_argument",
"(",
"'--config'",
",",
"'-c'",
",",
"default",
"=... | 33.276596 | 14.234043 |
def check_account_address(address):
"""
verify that a string is a valid account address.
Can be a b58-check address, a c32-check address, as well as the string "treasury" or "unallocated" or a string starting with 'not_distributed_'
>>> check_account_address('16EMaNw3pkn3v6f2BgnSSs53zAKH4Q8YJg')
Tr... | [
"def",
"check_account_address",
"(",
"address",
")",
":",
"if",
"address",
"==",
"'treasury'",
"or",
"address",
"==",
"'unallocated'",
":",
"return",
"True",
"if",
"address",
".",
"startswith",
"(",
"'not_distributed_'",
")",
"and",
"len",
"(",
"address",
")",... | 31.7 | 24.65 |
def delete_relationship(manager, relationship_id):
"""
Deletes the relationship.
:param manager: Neo4jDBSessionManager
:param relationship_id: Internal Neo4j relationship id
:return: bool
"""
q = """
MATCH ()-[r]->()
WHERE ID(r) = {relationship_id}
DELETE r
... | [
"def",
"delete_relationship",
"(",
"manager",
",",
"relationship_id",
")",
":",
"q",
"=",
"\"\"\"\n MATCH ()-[r]->()\n WHERE ID(r) = {relationship_id}\n DELETE r\n \"\"\"",
"with",
"manager",
".",
"session",
"as",
"s",
":",
"s",
".",
"run",
"(",
... | 25.9375 | 12.4375 |
def plot_prh_des_asc(p, r, h, asc, des):
'''Plot pitch, roll, and heading during the descent and ascent dive phases
Args
----
p: ndarray
Derived pitch data
r: ndarray
Derived roll data
h: ndarray
Derived heading data
des: ndarray
boolean mask for slicing desc... | [
"def",
"plot_prh_des_asc",
"(",
"p",
",",
"r",
",",
"h",
",",
"asc",
",",
"des",
")",
":",
"import",
"matplotlib",
".",
"pyplot",
"as",
"plt",
"import",
"numpy",
"from",
".",
"import",
"plotutils",
"# Convert boolean mask to indices",
"des_ind",
"=",
"numpy"... | 28.791667 | 25.625 |
def ack(self, id, transaction=None, receipt=None):
"""
Acknowledge 'consumption' of a message by id.
:param str id: identifier of the message
:param str transaction: include the acknowledgement in the specified transaction
"""
assert id is not None, "'id' is required"
... | [
"def",
"ack",
"(",
"self",
",",
"id",
",",
"transaction",
"=",
"None",
",",
"receipt",
"=",
"None",
")",
":",
"assert",
"id",
"is",
"not",
"None",
",",
"\"'id' is required\"",
"headers",
"=",
"{",
"HDR_MESSAGE_ID",
":",
"id",
"}",
"if",
"transaction",
... | 37.357143 | 12.928571 |
def start(self):
"""Start the receiver.
"""
if not self._is_running:
self._do_run = True
self._thread.start()
return self | [
"def",
"start",
"(",
"self",
")",
":",
"if",
"not",
"self",
".",
"_is_running",
":",
"self",
".",
"_do_run",
"=",
"True",
"self",
".",
"_thread",
".",
"start",
"(",
")",
"return",
"self"
] | 24.428571 | 10 |
def _read_next_consuming_comment(ctx: ReaderContext) -> ReaderForm:
"""Read the next full form from the input stream, consuming any
reader comments completely."""
while True:
v = _read_next(ctx)
if v is ctx.eof:
return ctx.eof
if v is COMMENT or isinstance(v, Comment):
... | [
"def",
"_read_next_consuming_comment",
"(",
"ctx",
":",
"ReaderContext",
")",
"->",
"ReaderForm",
":",
"while",
"True",
":",
"v",
"=",
"_read_next",
"(",
"ctx",
")",
"if",
"v",
"is",
"ctx",
".",
"eof",
":",
"return",
"ctx",
".",
"eof",
"if",
"v",
"is",... | 34.6 | 14.9 |
def firmware_download_input_protocol_type_sftp_protocol_sftp_host_key_check(self, **kwargs):
"""Auto Generated Code
"""
config = ET.Element("config")
firmware_download = ET.Element("firmware_download")
config = firmware_download
input = ET.SubElement(firmware_download, "i... | [
"def",
"firmware_download_input_protocol_type_sftp_protocol_sftp_host_key_check",
"(",
"self",
",",
"*",
"*",
"kwargs",
")",
":",
"config",
"=",
"ET",
".",
"Element",
"(",
"\"config\"",
")",
"firmware_download",
"=",
"ET",
".",
"Element",
"(",
"\"firmware_download\"",... | 46.5 | 17.571429 |
def getPatches(self) :
"""get patches as a dictionary"""
if not self.mustValidate :
return self.getStore()
res = {}
res.update(self.patchStore)
for k, v in self.subStores.items() :
res[k] = v.getPatches()
return res | [
"def",
"getPatches",
"(",
"self",
")",
":",
"if",
"not",
"self",
".",
"mustValidate",
":",
"return",
"self",
".",
"getStore",
"(",
")",
"res",
"=",
"{",
"}",
"res",
".",
"update",
"(",
"self",
".",
"patchStore",
")",
"for",
"k",
",",
"v",
"in",
"... | 26.090909 | 14.727273 |
def get_comments(self):
"""
Obtain comments for this bug.
Returns a list of Comment instances.
"""
bug = str(self._bug['id'])
res = self._bugsy.request('bug/%s/comment' % bug)
return [Comment(bugsy=self._bugsy, **comments) for comments
in... | [
"def",
"get_comments",
"(",
"self",
")",
":",
"bug",
"=",
"str",
"(",
"self",
".",
"_bug",
"[",
"'id'",
"]",
")",
"res",
"=",
"self",
".",
"_bugsy",
".",
"request",
"(",
"'bug/%s/comment'",
"%",
"bug",
")",
"return",
"[",
"Comment",
"(",
"bugsy",
"... | 30.909091 | 14.909091 |
def get_volume(self, datacenter_id, volume_id):
"""
Retrieves a single volume by ID.
:param datacenter_id: The unique ID of the data center.
:type datacenter_id: ``str``
:param volume_id: The unique ID of the volume.
:type volume_id: ``str``
... | [
"def",
"get_volume",
"(",
"self",
",",
"datacenter_id",
",",
"volume_id",
")",
":",
"response",
"=",
"self",
".",
"_perform_request",
"(",
"'/datacenters/%s/volumes/%s'",
"%",
"(",
"datacenter_id",
",",
"volume_id",
")",
")",
"return",
"response"
] | 30 | 17.733333 |
def sepBy(p, sep):
'''`sepBy(p, sep)` parses zero or more occurrences of p, separated by `sep`.
Returns a list of values returned by `p`.'''
return separated(p, sep, 0, maxt=float('inf'), end=False) | [
"def",
"sepBy",
"(",
"p",
",",
"sep",
")",
":",
"return",
"separated",
"(",
"p",
",",
"sep",
",",
"0",
",",
"maxt",
"=",
"float",
"(",
"'inf'",
")",
",",
"end",
"=",
"False",
")"
] | 51.75 | 22.75 |
def compose_dynamic_tree(src, target_tree_alias=None, parent_tree_item_alias=None, include_trees=None):
"""Returns a structure describing a dynamic sitetree.utils
The structure can be built from various sources,
:param str|iterable src: If a string is passed to `src`, it'll be treated as the name of an app... | [
"def",
"compose_dynamic_tree",
"(",
"src",
",",
"target_tree_alias",
"=",
"None",
",",
"parent_tree_item_alias",
"=",
"None",
",",
"include_trees",
"=",
"None",
")",
":",
"def",
"result",
"(",
"sitetrees",
"=",
"src",
")",
":",
"if",
"include_trees",
"is",
"... | 40.947368 | 29.078947 |
def enrich_fields(cls, fields, eitem):
"""Enrich the fields property of an issue.
Loops through al properties in issue['fields'],
using those that are relevant to enrich eitem with new properties.
Those properties are user defined, depending on options
configured in Jira. For ex... | [
"def",
"enrich_fields",
"(",
"cls",
",",
"fields",
",",
"eitem",
")",
":",
"for",
"field",
"in",
"fields",
":",
"if",
"field",
".",
"startswith",
"(",
"'customfield_'",
")",
":",
"if",
"type",
"(",
"fields",
"[",
"field",
"]",
")",
"is",
"dict",
":",... | 56.7 | 26.466667 |
def create_canonical_classpath(cls, classpath_products, targets, basedir,
save_classpath_file=False,
internal_classpath_only=True,
excludes=None):
"""Create a stable classpath of symlinks with standardized names.
... | [
"def",
"create_canonical_classpath",
"(",
"cls",
",",
"classpath_products",
",",
"targets",
",",
"basedir",
",",
"save_classpath_file",
"=",
"False",
",",
"internal_classpath_only",
"=",
"True",
",",
"excludes",
"=",
"None",
")",
":",
"def",
"delete_old_target_outpu... | 51.133333 | 27.828571 |
def with_argument_list(*args: List[Callable], preserve_quotes: bool = False) -> Callable[[List], Optional[bool]]:
"""A decorator to alter the arguments passed to a do_* cmd2 method. Default passes a string of whatever the user
typed. With this decorator, the decorated method will receive a list of arguments par... | [
"def",
"with_argument_list",
"(",
"*",
"args",
":",
"List",
"[",
"Callable",
"]",
",",
"preserve_quotes",
":",
"bool",
"=",
"False",
")",
"->",
"Callable",
"[",
"[",
"List",
"]",
",",
"Optional",
"[",
"bool",
"]",
"]",
":",
"import",
"functools",
"def"... | 49.962963 | 30 |
def _create_tag_highlevel(self, tag_name, message=None):
"""Create a tag on the toplevel repo if there is no patch repo,
or a tag on the patch repo and bookmark on the top repo if there is a
patch repo
Returns a list where each entry is a dict for each bookmark or tag
created, w... | [
"def",
"_create_tag_highlevel",
"(",
"self",
",",
"tag_name",
",",
"message",
"=",
"None",
")",
":",
"results",
"=",
"[",
"]",
"if",
"self",
".",
"patch_path",
":",
"# make a tag on the patch queue",
"tagged",
"=",
"self",
".",
"_create_tag_lowlevel",
"(",
"ta... | 45 | 22.2 |
def confluence(ctx, no_publish=False, clean=False, opts=''):
"""Build Sphinx docs and publish to Confluence."""
cfg = config.load()
if clean:
ctx.run("invoke clean --docs")
cmd = ['sphinx-build', '-b', 'confluence']
cmd.extend(['-E', '-a']) # force a full rebuild
if opts:
cmd.... | [
"def",
"confluence",
"(",
"ctx",
",",
"no_publish",
"=",
"False",
",",
"clean",
"=",
"False",
",",
"opts",
"=",
"''",
")",
":",
"cfg",
"=",
"config",
".",
"load",
"(",
")",
"if",
"clean",
":",
"ctx",
".",
"run",
"(",
"\"invoke clean --docs\"",
")",
... | 30.684211 | 16.894737 |
def get_access_token(self):
"""Method to return the current requests' access_token.
:returns: Access token or None
:rtype: str
.. versionadded:: 1.2
"""
try:
credentials = OAuth2Credentials.from_json(
self.credentials_store[g.oidc_id_token['s... | [
"def",
"get_access_token",
"(",
"self",
")",
":",
"try",
":",
"credentials",
"=",
"OAuth2Credentials",
".",
"from_json",
"(",
"self",
".",
"credentials_store",
"[",
"g",
".",
"oidc_id_token",
"[",
"'sub'",
"]",
"]",
")",
"return",
"credentials",
".",
"access... | 31.875 | 15.875 |
def reassembly(self, info):
"""Reassembly procedure.
Positional arguments:
* info -- Info, info dict of packets to be reassembled
"""
BUFID = info.bufid # Buffer Identifier
FO = info.fo # Fragment Offset
IHL = info.ihl # Internet Header Length
... | [
"def",
"reassembly",
"(",
"self",
",",
"info",
")",
":",
"BUFID",
"=",
"info",
".",
"bufid",
"# Buffer Identifier",
"FO",
"=",
"info",
".",
"fo",
"# Fragment Offset",
"IHL",
"=",
"info",
".",
"ihl",
"# Internet Header Length",
"MF",
"=",
"info",
".",
"mf",... | 35.157895 | 18.684211 |
def confd_state_ha_node_id(self, **kwargs):
"""Auto Generated Code
"""
config = ET.Element("config")
confd_state = ET.SubElement(config, "confd-state", xmlns="http://tail-f.com/yang/confd-monitoring")
ha = ET.SubElement(confd_state, "ha")
node_id = ET.SubElement(ha, "node... | [
"def",
"confd_state_ha_node_id",
"(",
"self",
",",
"*",
"*",
"kwargs",
")",
":",
"config",
"=",
"ET",
".",
"Element",
"(",
"\"config\"",
")",
"confd_state",
"=",
"ET",
".",
"SubElement",
"(",
"config",
",",
"\"confd-state\"",
",",
"xmlns",
"=",
"\"http://t... | 41 | 14 |
def __add_jmeter_components(self, jmx, jtl, variables):
""" Genius idea by Alexey Lavrenyuk """
logger.debug("Original JMX: %s", os.path.realpath(jmx))
with open(jmx, 'r') as src_jmx:
source_lines = src_jmx.readlines()
try:
# In new Jmeter version (3.2 as example... | [
"def",
"__add_jmeter_components",
"(",
"self",
",",
"jmx",
",",
"jtl",
",",
"variables",
")",
":",
"logger",
".",
"debug",
"(",
"\"Original JMX: %s\"",
",",
"os",
".",
"path",
".",
"realpath",
"(",
"jmx",
")",
")",
"with",
"open",
"(",
"jmx",
",",
"'r'... | 39.507692 | 17.738462 |
def set_brightness(self, brightness, effect=EFFECT_SUDDEN, transition_time=MIN_TRANSITION_TIME):
"""
This method is used to change the brightness of a smart LED
:param brightness: is the target brightness. The type is integer and ranges from 1 to 100. The
... | [
"def",
"set_brightness",
"(",
"self",
",",
"brightness",
",",
"effect",
"=",
"EFFECT_SUDDEN",
",",
"transition_time",
"=",
"MIN_TRANSITION_TIME",
")",
":",
"# Check bulb state",
"if",
"self",
".",
"is_off",
"(",
")",
":",
"raise",
"Exception",
"(",
"\"set_bright... | 54.111111 | 29.222222 |
def reshape_bar_plot(df, x, y, bars):
"""Reshape data from long form to "bar plot form".
Bar plot form has x value as the index with one column for bar grouping.
Table values come from y values.
"""
idx = [bars, x]
if df.duplicated(idx).any():
warnings.warn('Duplicated index found.')
... | [
"def",
"reshape_bar_plot",
"(",
"df",
",",
"x",
",",
"y",
",",
"bars",
")",
":",
"idx",
"=",
"[",
"bars",
",",
"x",
"]",
"if",
"df",
".",
"duplicated",
"(",
"idx",
")",
".",
"any",
"(",
")",
":",
"warnings",
".",
"warn",
"(",
"'Duplicated index f... | 34.416667 | 13.166667 |
def _from_dict(cls, _dict):
"""Initialize a ClassifyReturn object from a json dictionary."""
args = {}
if 'document' in _dict:
args['document'] = Document._from_dict(_dict.get('document'))
if 'model_id' in _dict:
args['model_id'] = _dict.get('model_id')
if... | [
"def",
"_from_dict",
"(",
"cls",
",",
"_dict",
")",
":",
"args",
"=",
"{",
"}",
"if",
"'document'",
"in",
"_dict",
":",
"args",
"[",
"'document'",
"]",
"=",
"Document",
".",
"_from_dict",
"(",
"_dict",
".",
"get",
"(",
"'document'",
")",
")",
"if",
... | 39.795455 | 14.022727 |
def _get_names(names, types):
"""
Get names, bearing in mind that there might be no name,
no type, and that the `:` separator might be wrongly used.
"""
if types == "":
try:
names, types = names.split(":")
except:
pass
return names.split(","), types | [
"def",
"_get_names",
"(",
"names",
",",
"types",
")",
":",
"if",
"types",
"==",
"\"\"",
":",
"try",
":",
"names",
",",
"types",
"=",
"names",
".",
"split",
"(",
"\":\"",
")",
"except",
":",
"pass",
"return",
"names",
".",
"split",
"(",
"\",\"",
")"... | 27.545455 | 14.454545 |
def load_spacy_rule(file_path: str) -> Dict:
"""
A spacy rule file is a json file.
Args:
file_path (str): path to a text file containing a spacy rule sets.
Returns: Dict as the representation of spacy rules
"""
with open(file_path) as fp:
return ... | [
"def",
"load_spacy_rule",
"(",
"file_path",
":",
"str",
")",
"->",
"Dict",
":",
"with",
"open",
"(",
"file_path",
")",
"as",
"fp",
":",
"return",
"json",
".",
"load",
"(",
"fp",
")"
] | 29.363636 | 16.454545 |
def update_columns(self, field, value_dict, inds=None, computed_type=None):
"""
update the columns of all meshes
:parameter str field: name of the mesh columnname
:parameter value_dict: dictionary with component as keys and new
data as values. If value_dict is not a dictiona... | [
"def",
"update_columns",
"(",
"self",
",",
"field",
",",
"value_dict",
",",
"inds",
"=",
"None",
",",
"computed_type",
"=",
"None",
")",
":",
"if",
"not",
"isinstance",
"(",
"value_dict",
",",
"dict",
")",
":",
"value_dict",
"=",
"{",
"comp_no",
":",
"... | 46.896552 | 24.206897 |
def checkPath(filename):
"""
Check the given path, printing out any warnings detected.
@return: the number of warnings printed
"""
try:
return check(file(filename, 'U').read() + '\n', filename)
except IOError, msg:
sys.stderr.write("%s: %s\n" % (filename, msg.args[1]))
r... | [
"def",
"checkPath",
"(",
"filename",
")",
":",
"try",
":",
"return",
"check",
"(",
"file",
"(",
"filename",
",",
"'U'",
")",
".",
"read",
"(",
")",
"+",
"'\\n'",
",",
"filename",
")",
"except",
"IOError",
",",
"msg",
":",
"sys",
".",
"stderr",
".",... | 28.818182 | 18.090909 |
def order(self):
"""
Finds the polynomial order.
Examples
--------
>>> (x + 4).order
1
>>> (x + 4 - x ** 18).order
18
>>> (x - x).order
0
>>> (x ** -3 + 4).order
Traceback (most recent call last):
...
AttributeError: Power needs to be positive integers
"""... | [
"def",
"order",
"(",
"self",
")",
":",
"if",
"not",
"self",
".",
"is_polynomial",
"(",
")",
":",
"raise",
"AttributeError",
"(",
"\"Power needs to be positive integers\"",
")",
"return",
"max",
"(",
"key",
"for",
"key",
"in",
"self",
".",
"_data",
")",
"if... | 22 | 20.761905 |
def _get_url_parameters(self):
"""
Encode URL parameters
"""
url_parameters = ''
if self._url_parameters is not None:
url_parameters = '?' + urllib.urlencode(self._url_parameters)
return url_parameters | [
"def",
"_get_url_parameters",
"(",
"self",
")",
":",
"url_parameters",
"=",
"''",
"if",
"self",
".",
"_url_parameters",
"is",
"not",
"None",
":",
"url_parameters",
"=",
"'?'",
"+",
"urllib",
".",
"urlencode",
"(",
"self",
".",
"_url_parameters",
")",
"return... | 31.75 | 10.25 |
def company_2_json(self):
"""
transform ariane_clip3 company object to Ariane server JSON obj
:return: Ariane JSON obj
"""
LOGGER.debug("Company.company_2_json")
json_obj = {
'companyID': self.id,
'companyName': self.name,
'companyDescr... | [
"def",
"company_2_json",
"(",
"self",
")",
":",
"LOGGER",
".",
"debug",
"(",
"\"Company.company_2_json\"",
")",
"json_obj",
"=",
"{",
"'companyID'",
":",
"self",
".",
"id",
",",
"'companyName'",
":",
"self",
".",
"name",
",",
"'companyDescription'",
":",
"se... | 34.571429 | 11.428571 |
def round_to_next(x, base):
"""Round float to next multiple of base."""
# Based on: http://stackoverflow.com/a/2272174
return int(base * math.ceil(float(x)/base)) | [
"def",
"round_to_next",
"(",
"x",
",",
"base",
")",
":",
"# Based on: http://stackoverflow.com/a/2272174",
"return",
"int",
"(",
"base",
"*",
"math",
".",
"ceil",
"(",
"float",
"(",
"x",
")",
"/",
"base",
")",
")"
] | 42.75 | 7.5 |
def _generate_main_scripts(self):
"""
Include the scripts used by solutions.
"""
head = self.parser.find('head').first_result()
if head is not None:
common_functions_script = self.parser.find(
'#'
+ AccessibleEventImplementation.ID_SCR... | [
"def",
"_generate_main_scripts",
"(",
"self",
")",
":",
"head",
"=",
"self",
".",
"parser",
".",
"find",
"(",
"'head'",
")",
".",
"first_result",
"(",
")",
"if",
"head",
"is",
"not",
"None",
":",
"common_functions_script",
"=",
"self",
".",
"parser",
"."... | 41.990654 | 18.158879 |
def draw(self):
"""
The master function that is called that draws everything.
"""
self.ax.set_xlim(-self.plot_radius(), self.plot_radius())
self.ax.set_ylim(-self.plot_radius(), self.plot_radius())
self.add_axes_and_nodes()
self.add_edges()
self.ax.axis(... | [
"def",
"draw",
"(",
"self",
")",
":",
"self",
".",
"ax",
".",
"set_xlim",
"(",
"-",
"self",
".",
"plot_radius",
"(",
")",
",",
"self",
".",
"plot_radius",
"(",
")",
")",
"self",
".",
"ax",
".",
"set_ylim",
"(",
"-",
"self",
".",
"plot_radius",
"(... | 28.727273 | 19.636364 |
def decode(cls, line):
"""
Remove backslash escaping from line.value, then split on commas.
"""
if line.encoded:
line.value = stringToTextValues(line.value,
listSeparator=cls.listSeparator)
line.encoded=False | [
"def",
"decode",
"(",
"cls",
",",
"line",
")",
":",
"if",
"line",
".",
"encoded",
":",
"line",
".",
"value",
"=",
"stringToTextValues",
"(",
"line",
".",
"value",
",",
"listSeparator",
"=",
"cls",
".",
"listSeparator",
")",
"line",
".",
"encoded",
"=",... | 34.125 | 12.375 |
def parse_cell(cell, rules):
""" Applies the rules to the bunch of text describing a cell.
@param string cell
A network / cell from iwlist scan.
@param dictionary rules
A dictionary of parse rules.
@return dictionary
parsed networks. """
parsed_cell = {}
for key in rule... | [
"def",
"parse_cell",
"(",
"cell",
",",
"rules",
")",
":",
"parsed_cell",
"=",
"{",
"}",
"for",
"key",
"in",
"rules",
":",
"rule",
"=",
"rules",
"[",
"key",
"]",
"parsed_cell",
".",
"update",
"(",
"{",
"key",
":",
"rule",
"(",
"cell",
")",
"}",
")... | 26.866667 | 14.933333 |
def github_api(self, url, *args):
"""
Connect to the given GitHub API URL template by replacing all
placeholders with the given parameters and return the decoded JSON
result on success. On error, return `None`.
:param url: The path to request from the GitHub API. Contains format... | [
"def",
"github_api",
"(",
"self",
",",
"url",
",",
"*",
"args",
")",
":",
"import",
"requests",
"import",
"urllib",
"github_api_url",
"=",
"os",
".",
"environ",
".",
"get",
"(",
"\"TRAC_GITHUB_API_URL\"",
",",
"\"https://api.github.com/\"",
")",
"formatted_url",... | 48.384615 | 23.871795 |
async def send_script(self, conn_id, data):
"""Send a a script to this IOTile device
Args:
conn_id (int): A unique identifier that will refer to this connection
data (bytes): the script to send to the device
"""
self._ensure_connection(conn_id, True)
con... | [
"async",
"def",
"send_script",
"(",
"self",
",",
"conn_id",
",",
"data",
")",
":",
"self",
".",
"_ensure_connection",
"(",
"conn_id",
",",
"True",
")",
"connection_string",
"=",
"self",
".",
"_get_property",
"(",
"conn_id",
",",
"\"connection_string\"",
")",
... | 43.285714 | 25.785714 |
def create_dn_in_filter(filter_class, filter_value, helper):
""" Creates filter object for given class name, and DN values."""
in_filter = FilterFilter()
in_filter.AddChild(create_dn_wcard_filter(filter_class, filter_value))
return in_filter | [
"def",
"create_dn_in_filter",
"(",
"filter_class",
",",
"filter_value",
",",
"helper",
")",
":",
"in_filter",
"=",
"FilterFilter",
"(",
")",
"in_filter",
".",
"AddChild",
"(",
"create_dn_wcard_filter",
"(",
"filter_class",
",",
"filter_value",
")",
")",
"return",
... | 50.6 | 16.8 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.