text stringlengths 75 104k | code_tokens list | avg_line_len float64 7.91 980 | score float64 0 0.18 |
|---|---|---|---|
def checkArgs(args):
"""Checks the arguments and options.
:param args: an object containing the options of the program.
:type args: argparse.Namespace
:returns: ``True`` if everything was OK.
If there is a problem with an option, an exception is raised using the
:py:class:`ProgramError` clas... | [
"def",
"checkArgs",
"(",
"args",
")",
":",
"# Check if we have the tped and the tfam files",
"for",
"filename",
"in",
"[",
"args",
".",
"bfile",
"+",
"i",
"for",
"i",
"in",
"[",
"\".bed\"",
",",
"\".bim\"",
",",
"\".fam\"",
"]",
"]",
":",
"if",
"not",
"os"... | 33.5 | 0.001209 |
def use_sequestered_assessment_part_view(self):
"""Pass through to provider AssessmentPartLookupSession.use_sequestered_assessment_part_view"""
# Does this need to be re-implemented to match the other non-sub-package view setters?
self._containable_views['assessment_part'] = SEQUESTERED
... | [
"def",
"use_sequestered_assessment_part_view",
"(",
"self",
")",
":",
"# Does this need to be re-implemented to match the other non-sub-package view setters?",
"self",
".",
"_containable_views",
"[",
"'assessment_part'",
"]",
"=",
"SEQUESTERED",
"self",
".",
"_get_sub_package_provi... | 63.5 | 0.007762 |
def solve(self, value, attribute, args=None, kwargs=None):
"""Try to get the given attribute/function result for the given value.
If ``args`` or ``kwargs`` are passed, the attribute got from ``value`` must be callable.
They will be passed anyway (using ``[]`` and ``{}`` as default values) if th... | [
"def",
"solve",
"(",
"self",
",",
"value",
",",
"attribute",
",",
"args",
"=",
"None",
",",
"kwargs",
"=",
"None",
")",
":",
"if",
"not",
"isinstance",
"(",
"value",
",",
"self",
".",
"source",
")",
"and",
"(",
"not",
"self",
".",
"allow_class",
"o... | 37.171053 | 0.003448 |
def select_relevant_id_columns(rows):
"""
Find out which of the entries in Row.id are equal for all given rows.
@return: A list of True/False values according to whether the i-th part of the id is always equal.
"""
relevant_id_columns = [True] # first column (file name) is always relevant
if row... | [
"def",
"select_relevant_id_columns",
"(",
"rows",
")",
":",
"relevant_id_columns",
"=",
"[",
"True",
"]",
"# first column (file name) is always relevant",
"if",
"rows",
":",
"prototype_id",
"=",
"rows",
"[",
"0",
"]",
".",
"id",
"for",
"column",
"in",
"range",
"... | 43.857143 | 0.00638 |
def update_alias_mapping(settings, alias, new_mapping):
"""
Override `alias` mapping in the user configuration file with the given `new_mapping`, which should be a tuple with
2 or 3 elements (in the form `(project_id, activity_id, role_id)`).
"""
mapping = aliases_database[alias]
new_mapping = M... | [
"def",
"update_alias_mapping",
"(",
"settings",
",",
"alias",
",",
"new_mapping",
")",
":",
"mapping",
"=",
"aliases_database",
"[",
"alias",
"]",
"new_mapping",
"=",
"Mapping",
"(",
"mapping",
"=",
"new_mapping",
",",
"backend",
"=",
"mapping",
".",
"backend"... | 47.6 | 0.004124 |
def unkown_field(self, value=None):
"""Corresponds to IDD Field `unkown_field` Empty field in data.
Args:
value (str): value for IDD Field `unkown_field`
if `value` is None it will not be checked against the
specification and is assumed to be a missing value
... | [
"def",
"unkown_field",
"(",
"self",
",",
"value",
"=",
"None",
")",
":",
"if",
"value",
"is",
"not",
"None",
":",
"try",
":",
"value",
"=",
"str",
"(",
"value",
")",
"except",
"ValueError",
":",
"raise",
"ValueError",
"(",
"'value {} need to be of type str... | 36.26087 | 0.002336 |
def get(self, path, default=None):
"""
Returns given path value.
:param path: Path name.
:type path: unicode
:param default: Default value if path is not found.
:type default: object
:return: Action.
:rtype: QAction
"""
try:
r... | [
"def",
"get",
"(",
"self",
",",
"path",
",",
"default",
"=",
"None",
")",
":",
"try",
":",
"return",
"self",
".",
"__getitem__",
"(",
"path",
")",
"except",
"KeyError",
"as",
"error",
":",
"return",
"default"
] | 24.625 | 0.00489 |
def extract_arguments(arguments, long_keys, key_prefix='--'):
"""
:param arguments: dict of command line arguments
"""
long_arguments = extract(arguments, long_keys)
return dict(
[(key.replace(key_prefix, ''), value) for key, value in long_arguments.items()]
) | [
"def",
"extract_arguments",
"(",
"arguments",
",",
"long_keys",
",",
"key_prefix",
"=",
"'--'",
")",
":",
"long_arguments",
"=",
"extract",
"(",
"arguments",
",",
"long_keys",
")",
"return",
"dict",
"(",
"[",
"(",
"key",
".",
"replace",
"(",
"key_prefix",
... | 31.666667 | 0.006826 |
def computeScaledProbabilities(
listOfScales=[1.0, 1.5, 2.0, 2.5, 3.0, 3.5, 4.0],
listofkValues=[64, 128, 256],
kw=32,
n=1000,
numWorkers=10,
nTrials=1000,
):
"""
Compute the impact of S on match probabilities for a fixed value of n.
"""
# Create arguments for t... | [
"def",
"computeScaledProbabilities",
"(",
"listOfScales",
"=",
"[",
"1.0",
",",
"1.5",
",",
"2.0",
",",
"2.5",
",",
"3.0",
",",
"3.5",
",",
"4.0",
"]",
",",
"listofkValues",
"=",
"[",
"64",
",",
"128",
",",
"256",
"]",
",",
"kw",
"=",
"32",
",",
... | 31.9375 | 0.013295 |
def t_css_string(self, t):
r'"[^"@]*"|\'[^\'@]*\''
t.lexer.lineno += t.value.count('\n')
return t | [
"def",
"t_css_string",
"(",
"self",
",",
"t",
")",
":",
"t",
".",
"lexer",
".",
"lineno",
"+=",
"t",
".",
"value",
".",
"count",
"(",
"'\\n'",
")",
"return",
"t"
] | 29.5 | 0.016529 |
def get_license(id):
"""
Get a specific License by either ID or fullname
"""
response = utils.checked_api_call(
pnc_api.licenses, 'get_specific', id= id)
if response:
return utils.format_json(response.content) | [
"def",
"get_license",
"(",
"id",
")",
":",
"response",
"=",
"utils",
".",
"checked_api_call",
"(",
"pnc_api",
".",
"licenses",
",",
"'get_specific'",
",",
"id",
"=",
"id",
")",
"if",
"response",
":",
"return",
"utils",
".",
"format_json",
"(",
"response",
... | 29.75 | 0.008163 |
def solve(self, printmat=0, sendback=0, silent=False):
'''Compute solution'''
# Initialize elements
self.initialize()
# Compute number of equations
self.neq = np.sum([e.nunknowns for e in self.elementlist])
if self.neq == 0: return
if silent is False:
... | [
"def",
"solve",
"(",
"self",
",",
"printmat",
"=",
"0",
",",
"sendback",
"=",
"0",
",",
"silent",
"=",
"False",
")",
":",
"# Initialize elements",
"self",
".",
"initialize",
"(",
")",
"# Compute number of equations",
"self",
".",
"neq",
"=",
"np",
".",
"... | 36.846154 | 0.00339 |
def cpu_times(per_cpu=False):
'''
Return the percent of time the CPU spends in each state,
e.g. user, system, idle, nice, iowait, irq, softirq.
per_cpu
if True return an array of percents for each CPU, otherwise aggregate
all percents into one number
CLI Example:
.. code-block... | [
"def",
"cpu_times",
"(",
"per_cpu",
"=",
"False",
")",
":",
"if",
"per_cpu",
":",
"result",
"=",
"[",
"dict",
"(",
"times",
".",
"_asdict",
"(",
")",
")",
"for",
"times",
"in",
"psutil",
".",
"cpu_times",
"(",
"True",
")",
"]",
"else",
":",
"result... | 26.35 | 0.001832 |
def register_to_xmldoc(xmldoc, program, paramdict, **kwargs):
"""
Register the current process and params to an XML document.
program is the name of the program. paramdict is a dictionary of
name/value pairs that will be used to populate the process_params
table; see process_params_from_dict() for information on... | [
"def",
"register_to_xmldoc",
"(",
"xmldoc",
",",
"program",
",",
"paramdict",
",",
"*",
"*",
"kwargs",
")",
":",
"process",
"=",
"append_process",
"(",
"xmldoc",
",",
"program",
"=",
"program",
",",
"*",
"*",
"kwargs",
")",
"append_process_params",
"(",
"x... | 48.230769 | 0.023474 |
def solvers(config_file, profile, solver_def, list_solvers):
"""Get solver details.
Unless solver name/id specified, fetch and display details for
all online solvers available on the configured endpoint.
"""
with Client.from_config(
config_file=config_file, profile=profile, solver=solv... | [
"def",
"solvers",
"(",
"config_file",
",",
"profile",
",",
"solver_def",
",",
"list_solvers",
")",
":",
"with",
"Client",
".",
"from_config",
"(",
"config_file",
"=",
"config_file",
",",
"profile",
"=",
"profile",
",",
"solver",
"=",
"solver_def",
")",
"as",... | 39.228571 | 0.002843 |
def rownumbers(self, table=None):
"""Return a list containing the row numbers of this table.
This method can be useful after a selection or a sort.
It returns the row numbers of the rows in this table with respect
to the given table. If no table is given, the original table is used.
... | [
"def",
"rownumbers",
"(",
"self",
",",
"table",
"=",
"None",
")",
":",
"if",
"table",
"is",
"None",
":",
"return",
"self",
".",
"_rownumbers",
"(",
"Table",
"(",
")",
")",
"return",
"self",
".",
"_rownumbers",
"(",
"table",
")"
] | 37.310345 | 0.001802 |
def commatize(leafs):
"""
Accepts/turns: (Name, Name, ..., Name, Name)
Returns/into: (Name, Comma, Name, Comma, ..., Name, Comma, Name)
"""
new_leafs = []
for leaf in leafs:
new_leafs.append(leaf)
new_leafs.append(Comma())
del new_leafs[-1]
return new_leafs | [
"def",
"commatize",
"(",
"leafs",
")",
":",
"new_leafs",
"=",
"[",
"]",
"for",
"leaf",
"in",
"leafs",
":",
"new_leafs",
".",
"append",
"(",
"leaf",
")",
"new_leafs",
".",
"append",
"(",
"Comma",
"(",
")",
")",
"del",
"new_leafs",
"[",
"-",
"1",
"]"... | 26.818182 | 0.003279 |
def retrieve_dcnm_subnet_info(self, tenant_id, direc):
"""Retrieves the DCNM subnet info for a tenant. """
serv_obj = self.get_service_obj(tenant_id)
subnet_dict = serv_obj.get_dcnm_subnet_dict(direc)
return subnet_dict | [
"def",
"retrieve_dcnm_subnet_info",
"(",
"self",
",",
"tenant_id",
",",
"direc",
")",
":",
"serv_obj",
"=",
"self",
".",
"get_service_obj",
"(",
"tenant_id",
")",
"subnet_dict",
"=",
"serv_obj",
".",
"get_dcnm_subnet_dict",
"(",
"direc",
")",
"return",
"subnet_d... | 49.4 | 0.007968 |
def horz_offset(self):
"""
The float value in ./c:x@val when ./c:xMode@val == "factor". 0.0 when
./c:x is not present or ./c:xMode@val != "factor".
"""
x, xMode = self.x, self.xMode
if x is None or xMode is None or xMode.val != ST_LayoutMode.FACTOR:
return 0.0... | [
"def",
"horz_offset",
"(",
"self",
")",
":",
"x",
",",
"xMode",
"=",
"self",
".",
"x",
",",
"self",
".",
"xMode",
"if",
"x",
"is",
"None",
"or",
"xMode",
"is",
"None",
"or",
"xMode",
".",
"val",
"!=",
"ST_LayoutMode",
".",
"FACTOR",
":",
"return",
... | 37 | 0.005865 |
def _escape_str_id(id_str):
"""make a single string id SBML compliant"""
for c in ("'", '"'):
if id_str.startswith(c) and id_str.endswith(c) \
and id_str.count(c) == 2:
id_str = id_str.strip(c)
for char, escaped_char in _renames:
id_str = id_str.replace(char, esca... | [
"def",
"_escape_str_id",
"(",
"id_str",
")",
":",
"for",
"c",
"in",
"(",
"\"'\"",
",",
"'\"'",
")",
":",
"if",
"id_str",
".",
"startswith",
"(",
"c",
")",
"and",
"id_str",
".",
"endswith",
"(",
"c",
")",
"and",
"id_str",
".",
"count",
"(",
"c",
"... | 37.666667 | 0.002882 |
def closest(args):
"""
%prog closest candidates.bed gaps.bed fastafile
Identify the nearest gaps flanking suggested regions.
"""
p = OptionParser(closest.__doc__)
p.add_option("--om", default=False, action="store_true",
help="The bedfile is OM blocks [default: %default]")
o... | [
"def",
"closest",
"(",
"args",
")",
":",
"p",
"=",
"OptionParser",
"(",
"closest",
".",
"__doc__",
")",
"p",
".",
"add_option",
"(",
"\"--om\"",
",",
"default",
"=",
"False",
",",
"action",
"=",
"\"store_true\"",
",",
"help",
"=",
"\"The bedfile is OM bloc... | 28.8 | 0.00084 |
def _set_object_view(self, session):
"""Sets the underlying object views to match current view"""
for obj_name in self._object_views:
if self._object_views[obj_name] == PLENARY:
try:
getattr(session, 'use_plenary_' + obj_name + '_view')()
e... | [
"def",
"_set_object_view",
"(",
"self",
",",
"session",
")",
":",
"for",
"obj_name",
"in",
"self",
".",
"_object_views",
":",
"if",
"self",
".",
"_object_views",
"[",
"obj_name",
"]",
"==",
"PLENARY",
":",
"try",
":",
"getattr",
"(",
"session",
",",
"'us... | 41.307692 | 0.003643 |
def is_symbol_hooked(self, symbol_name):
"""
Check if a symbol is already hooked.
:param str symbol_name: Name of the symbol.
:return: True if the symbol can be resolved and is hooked, False otherwise.
:rtype: bool
"""
sym = self.loader.find_symbol(symbol_name)
... | [
"def",
"is_symbol_hooked",
"(",
"self",
",",
"symbol_name",
")",
":",
"sym",
"=",
"self",
".",
"loader",
".",
"find_symbol",
"(",
"symbol_name",
")",
"if",
"sym",
"is",
"None",
":",
"l",
".",
"warning",
"(",
"\"Could not find symbol %s\"",
",",
"symbol_name"... | 39.857143 | 0.007005 |
def NTU_from_P_J(P1, R1, Ntp):
r'''Returns the number of transfer units of a TEMA J type heat exchanger
with a specified (for side 1) thermal effectiveness `P1`, heat capacity
ratio `R1`, and the number of tube passes `Ntp`. The supported cases are
as follows:
* One tube pass (shell fluid... | [
"def",
"NTU_from_P_J",
"(",
"P1",
",",
"R1",
",",
"Ntp",
")",
":",
"NTU_min",
"=",
"1E-11",
"function",
"=",
"temperature_effectiveness_TEMA_J",
"if",
"Ntp",
"==",
"1",
":",
"# Very often failes because at NTU=1000, there is no variation in P1",
"# for instance at NTU=40,... | 41.164384 | 0.004225 |
def get_categories(self, parent_aliases=None, target_object=None, tied_only=True):
"""Returns subcategories (or ties if `target_object` is set)
for the given parent category.
:param str|None|list parent_aliases:
:param ModelWithCategory|Model target_object:
:param bool tied_only... | [
"def",
"get_categories",
"(",
"self",
",",
"parent_aliases",
"=",
"None",
",",
"target_object",
"=",
"None",
",",
"tied_only",
"=",
"True",
")",
":",
"single_mode",
"=",
"False",
"if",
"not",
"isinstance",
"(",
"parent_aliases",
",",
"list",
")",
":",
"sin... | 37.078431 | 0.003091 |
def check_new_version_available(this_version):
"""
Checks if a newer version of Zappa is available.
Returns True is updateable, else False.
"""
import requests
pypi_url = 'https://pypi.python.org/pypi/Zappa/json'
resp = requests.get(pypi_url, timeout=1.5)
top_version = resp.json()['in... | [
"def",
"check_new_version_available",
"(",
"this_version",
")",
":",
"import",
"requests",
"pypi_url",
"=",
"'https://pypi.python.org/pypi/Zappa/json'",
"resp",
"=",
"requests",
".",
"get",
"(",
"pypi_url",
",",
"timeout",
"=",
"1.5",
")",
"top_version",
"=",
"resp"... | 25.857143 | 0.002667 |
def getoutput(cmd):
"""Return standard output of executing cmd in a shell.
Accepts the same arguments as os.system().
Parameters
----------
cmd : str
A command to be executed in the system shell.
Returns
-------
stdout : str
"""
out = process_handler(cmd, lambda p: p.co... | [
"def",
"getoutput",
"(",
"cmd",
")",
":",
"out",
"=",
"process_handler",
"(",
"cmd",
",",
"lambda",
"p",
":",
"p",
".",
"communicate",
"(",
")",
"[",
"0",
"]",
",",
"subprocess",
".",
"STDOUT",
")",
"if",
"out",
"is",
"None",
":",
"return",
"''",
... | 21.736842 | 0.00232 |
def split_spec(spec, sep):
"""Split a spec by separator and return stripped start and end parts."""
parts = spec.rsplit(sep, 1)
spec_start = parts[0].strip()
spec_end = ''
if len(parts) == 2:
spec_end = parts[-1].strip()
return spec_start, spec_end | [
"def",
"split_spec",
"(",
"spec",
",",
"sep",
")",
":",
"parts",
"=",
"spec",
".",
"rsplit",
"(",
"sep",
",",
"1",
")",
"spec_start",
"=",
"parts",
"[",
"0",
"]",
".",
"strip",
"(",
")",
"spec_end",
"=",
"''",
"if",
"len",
"(",
"parts",
")",
"=... | 34.125 | 0.003571 |
def wait(self, cond, timeout=None):
"""
Blocks until ``cond(self.state)`` is ``True``. The condition is
checked when there is an I/O event related to the ``state`` attribute.
Exits early when ``timeout`` (in milliseconds) is reached.
Returns ``True`` if the condition is met, an... | [
"def",
"wait",
"(",
"self",
",",
"cond",
",",
"timeout",
"=",
"None",
")",
":",
"tic",
"=",
"time",
".",
"time",
"(",
")",
"if",
"self",
".",
"_poll",
"is",
"None",
":",
"if",
"self",
".",
"_state",
"is",
"None",
":",
"self",
".",
"_state",
"="... | 34.942857 | 0.002387 |
def _move_layers(self, layers, src, dest):
"""
This moves all the layers that should be copied as-is.
In other words - all layers that are not meant to be squashed will be
moved from the old image to the new image untouched.
"""
for layer in layers:
layer_id =... | [
"def",
"_move_layers",
"(",
"self",
",",
"layers",
",",
"src",
",",
"dest",
")",
":",
"for",
"layer",
"in",
"layers",
":",
"layer_id",
"=",
"layer",
".",
"replace",
"(",
"'sha256:'",
",",
"''",
")",
"self",
".",
"log",
".",
"debug",
"(",
"\"Moving un... | 42.909091 | 0.004149 |
def map(**kwargs):
"""Returns a dictionary of the given keyword arguments mapped to their
values from the environment, with input keys lower cased.
"""
d = {}
e = lower_dict(environ.copy())
for k, v in kwargs.items():
d[k] = e.get(v.lower())
return d | [
"def",
"map",
"(",
"*",
"*",
"kwargs",
")",
":",
"d",
"=",
"{",
"}",
"e",
"=",
"lower_dict",
"(",
"environ",
".",
"copy",
"(",
")",
")",
"for",
"k",
",",
"v",
"in",
"kwargs",
".",
"items",
"(",
")",
":",
"d",
"[",
"k",
"]",
"=",
"e",
".",... | 23.166667 | 0.00346 |
def merge_into_nodeset(target, source):
"""Place all the nodes from the source node-set into the target
node-set, preserving document order. Both node-sets must be in
document order to begin with.
"""
if len(target) == 0:
target.extend(source)
return
source = [n for n in sourc... | [
"def",
"merge_into_nodeset",
"(",
"target",
",",
"source",
")",
":",
"if",
"len",
"(",
"target",
")",
"==",
"0",
":",
"target",
".",
"extend",
"(",
"source",
")",
"return",
"source",
"=",
"[",
"n",
"for",
"n",
"in",
"source",
"if",
"n",
"not",
"in"... | 36.583333 | 0.00111 |
def filter_transform_response(get_response, params):
"""
This filter process the returned response. It does 3 things:
- If the response is a ``sanic.response.HTTPResponse`` and not a
:class:`rafter.http.Response`, return it immediately.
- If the response is not a :class:`rafter.http.Response` ins... | [
"def",
"filter_transform_response",
"(",
"get_response",
",",
"params",
")",
":",
"async",
"def",
"decorated_filter",
"(",
"request",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"response",
"=",
"await",
"get_response",
"(",
"request",
",",
"*",
"... | 35.392857 | 0.000982 |
def render(self, name, value, attrs={}):
"""Render the Quill WYSIWYG."""
if value is None:
value = ''
final_attrs = self.build_attrs(attrs, name=name)
quill_app = apps.get_app_config('quill')
quill_config = getattr(quill_app, self.config)
return mark_safe(ren... | [
"def",
"render",
"(",
"self",
",",
"name",
",",
"value",
",",
"attrs",
"=",
"{",
"}",
")",
":",
"if",
"value",
"is",
"None",
":",
"value",
"=",
"''",
"final_attrs",
"=",
"self",
".",
"build_attrs",
"(",
"attrs",
",",
"name",
"=",
"name",
")",
"qu... | 36.357143 | 0.003831 |
def fun_inverse(fun=None, y=0, x0=None, args=(), disp=False, method='Nelder-Mead', **kwargs):
r"""Find the threshold level that accomplishes the desired specificity
Call indicated function repeatedly to find answer to the inverse function evaluation
Arguments:
fun (function): function to be calculate ... | [
"def",
"fun_inverse",
"(",
"fun",
"=",
"None",
",",
"y",
"=",
"0",
",",
"x0",
"=",
"None",
",",
"args",
"=",
"(",
")",
",",
"disp",
"=",
"False",
",",
"method",
"=",
"'Nelder-Mead'",
",",
"*",
"*",
"kwargs",
")",
":",
"fun_inverse",
".",
"fun",
... | 49.942857 | 0.005612 |
def cross_successors(state, last_action=None):
"""
Successors function for solving the cross.
"""
centres, edges = state
acts = sum([
[s, s.inverse(), s * 2] for s in
map(Step, "RUFDRB".replace(last_action.face if last_action else "", "", 1))
]... | [
"def",
"cross_successors",
"(",
"state",
",",
"last_action",
"=",
"None",
")",
":",
"centres",
",",
"edges",
"=",
"state",
"acts",
"=",
"sum",
"(",
"[",
"[",
"s",
",",
"s",
".",
"inverse",
"(",
")",
",",
"s",
"*",
"2",
"]",
"for",
"s",
"in",
"m... | 37.181818 | 0.00716 |
def get_sphinx_doc(
self,
name,
depth=None,
exclude=None,
width=72,
error=False,
raised=False,
no_comment=False,
):
r"""
Return an exception list marked up in `reStructuredText`_.
:param name: Name of the callable (method, func... | [
"def",
"get_sphinx_doc",
"(",
"self",
",",
"name",
",",
"depth",
"=",
"None",
",",
"exclude",
"=",
"None",
",",
"width",
"=",
"72",
",",
"error",
"=",
"False",
",",
"raised",
"=",
"False",
",",
"no_comment",
"=",
"False",
",",
")",
":",
"# pylint: di... | 44.407115 | 0.001306 |
def delete(self, subscription_id, data=None):
"""Cancel subscription and return the subscription object.
Deleting a subscription causes the subscription status to changed to 'canceled'.
The updated subscription object is returned.
"""
if not subscription_id or not subscription_i... | [
"def",
"delete",
"(",
"self",
",",
"subscription_id",
",",
"data",
"=",
"None",
")",
":",
"if",
"not",
"subscription_id",
"or",
"not",
"subscription_id",
".",
"startswith",
"(",
"self",
".",
"RESOURCE_ID_PREFIX",
")",
":",
"raise",
"IdentifierError",
"(",
"\... | 54.153846 | 0.00838 |
def get_title(self):
"""Title is either the chart header for a cable ratings page or above
the opening description for a broadcast ratings page.
"""
if self.category == 'cable':
strings = get_strings(self.soup, 'strong')
else:
strings = get_strings(self.so... | [
"def",
"get_title",
"(",
"self",
")",
":",
"if",
"self",
".",
"category",
"==",
"'cable'",
":",
"strings",
"=",
"get_strings",
"(",
"self",
".",
"soup",
",",
"'strong'",
")",
"else",
":",
"strings",
"=",
"get_strings",
"(",
"self",
".",
"soup",
",",
... | 33.722222 | 0.003205 |
def get_component(self, name):
"""
Retrieve a child component given its name.
:param name: The name of the component.
:returns: The component.
"""
return [c for c in self.components if c.name == name][0] | [
"def",
"get_component",
"(",
"self",
",",
"name",
")",
":",
"return",
"[",
"c",
"for",
"c",
"in",
"self",
".",
"components",
"if",
"c",
".",
"name",
"==",
"name",
"]",
"[",
"0",
"]"
] | 24.5 | 0.007874 |
def load_tpf(self):
'''
Loads the target pixel file.
'''
if not self.loaded:
if self._data is not None:
data = self._data
else:
data = self._mission.GetData(
self.ID, season=self.season,
... | [
"def",
"load_tpf",
"(",
"self",
")",
":",
"if",
"not",
"self",
".",
"loaded",
":",
"if",
"self",
".",
"_data",
"is",
"not",
"None",
":",
"data",
"=",
"self",
".",
"_data",
"else",
":",
"data",
"=",
"self",
".",
"_mission",
".",
"GetData",
"(",
"s... | 37.888889 | 0.000953 |
def urls(self):
""" Provide URLconf details for the ``Api``.
And all registered ``Resources`` beneath it.
:return list: URL's patterns
"""
urls = []
for url_name in sorted(self.resources.keys()):
resource = self.resources[url_name]
urls.ap... | [
"def",
"urls",
"(",
"self",
")",
":",
"urls",
"=",
"[",
"]",
"for",
"url_name",
"in",
"sorted",
"(",
"self",
".",
"resources",
".",
"keys",
"(",
")",
")",
":",
"resource",
"=",
"self",
".",
"resources",
"[",
"url_name",
"]",
"urls",
".",
"append",
... | 26.380952 | 0.003484 |
def handle_database_error(cls, session, exception):
"""Rollback changes made and handle any type of error raised by the DBMS."""
session.rollback()
if isinstance(exception, IntegrityError):
cls.handle_integrity_error(exception)
elif isinstance(exception, FlushError):
... | [
"def",
"handle_database_error",
"(",
"cls",
",",
"session",
",",
"exception",
")",
":",
"session",
".",
"rollback",
"(",
")",
"if",
"isinstance",
"(",
"exception",
",",
"IntegrityError",
")",
":",
"cls",
".",
"handle_integrity_error",
"(",
"exception",
")",
... | 35.545455 | 0.007481 |
def pattern(self):
"""
Regular expression describing valid objects.
.. note::
JSON schema specifications says that this value SHOULD
follow the ``EMCA 262/Perl 5`` format. We cannot support
this so we support python regular expressions instead. This
... | [
"def",
"pattern",
"(",
"self",
")",
":",
"value",
"=",
"self",
".",
"_schema",
".",
"get",
"(",
"\"pattern\"",
",",
"None",
")",
"if",
"value",
"is",
"None",
":",
"return",
"try",
":",
"return",
"re",
".",
"compile",
"(",
"value",
")",
"except",
"r... | 34.318182 | 0.002577 |
def _process_plan_lines(self, final_line_count):
"""Process plan line rules."""
if not self._lines_seen["plan"]:
self._add_error(_("Missing a plan."))
return
if len(self._lines_seen["plan"]) > 1:
self._add_error(_("Only one plan line is permitted per file."))... | [
"def",
"_process_plan_lines",
"(",
"self",
",",
"final_line_count",
")",
":",
"if",
"not",
"self",
".",
"_lines_seen",
"[",
"\"plan\"",
"]",
":",
"self",
".",
"_add_error",
"(",
"_",
"(",
"\"Missing a plan.\"",
")",
")",
"return",
"if",
"len",
"(",
"self",... | 37.458333 | 0.003254 |
def send(self, topic, message):
"""Publishes a pulse message to the proper exchange."""
if not message:
Log.error("Expecting a message")
message._prepare()
if not self.connection:
self.connect()
producer = Producer(
channel=self.connection,... | [
"def",
"send",
"(",
"self",
",",
"topic",
",",
"message",
")",
":",
"if",
"not",
"message",
":",
"Log",
".",
"error",
"(",
"\"Expecting a message\"",
")",
"message",
".",
"_prepare",
"(",
")",
"if",
"not",
"self",
".",
"connection",
":",
"self",
".",
... | 32.8125 | 0.0037 |
def get_driver(self, name, version):
"""Authenticates and creates new API driver to perform scope stuff
:param name: Name of driver
:param version: Version of driver
:return: driver
"""
user_credentials = self.get_user_credentials() # get credentials
return disc... | [
"def",
"get_driver",
"(",
"self",
",",
"name",
",",
"version",
")",
":",
"user_credentials",
"=",
"self",
".",
"get_user_credentials",
"(",
")",
"# get credentials",
"return",
"discovery",
".",
"build",
"(",
"name",
",",
"version",
",",
"http",
"=",
"self",
... | 34.25 | 0.004739 |
def _log(self, s):
r"""Log a string. It flushes but doesn't append \n, so do that yourself."""
# TODO(tewalds): Should this be using logging.info instead? How to see them
# outside of google infrastructure?
sys.stderr.write(s)
sys.stderr.flush() | [
"def",
"_log",
"(",
"self",
",",
"s",
")",
":",
"# TODO(tewalds): Should this be using logging.info instead? How to see them",
"# outside of google infrastructure?",
"sys",
".",
"stderr",
".",
"write",
"(",
"s",
")",
"sys",
".",
"stderr",
".",
"flush",
"(",
")"
] | 43.333333 | 0.003774 |
def patch(self):
"""
monkey patches django.db.models.sql.compiler.SQL*Compiler series
"""
from django.db.models.sql import compiler
self._read_compilers = (
compiler.SQLCompiler,
compiler.SQLAggregateCompiler,
compiler.SQLDateCompiler,
... | [
"def",
"patch",
"(",
"self",
")",
":",
"from",
"django",
".",
"db",
".",
"models",
".",
"sql",
"import",
"compiler",
"self",
".",
"_read_compilers",
"=",
"(",
"compiler",
".",
"SQLCompiler",
",",
"compiler",
".",
"SQLAggregateCompiler",
",",
"compiler",
".... | 37.185185 | 0.001942 |
def _set_with_height(self, fig, opts):
"""
Set the width and height of a Matplotlib figure
"""
h = 5
if "height" in opts:
h = opts["height"]
w = 12
if "width" in opts:
w = opts["width"]
try:
fig.figure.set_size_inches((w... | [
"def",
"_set_with_height",
"(",
"self",
",",
"fig",
",",
"opts",
")",
":",
"h",
"=",
"5",
"if",
"\"height\"",
"in",
"opts",
":",
"h",
"=",
"opts",
"[",
"\"height\"",
"]",
"w",
"=",
"12",
"if",
"\"width\"",
"in",
"opts",
":",
"w",
"=",
"opts",
"["... | 30.75 | 0.004732 |
def from_content(cls, content):
"""Parses a Tibia.com response into a House object.
Parameters
----------
content: :class:`str`
HTML content of the page.
Returns
-------
:class:`House`
The house contained in the page, or None if the house... | [
"def",
"from_content",
"(",
"cls",
",",
"content",
")",
":",
"parsed_content",
"=",
"parse_tibiacom_content",
"(",
"content",
")",
"image_column",
",",
"desc_column",
",",
"",
"*",
"_",
"=",
"parsed_content",
".",
"find_all",
"(",
"'td'",
")",
"if",
"\"Error... | 33.846154 | 0.003865 |
def update(cls):
"""
Update rows to include known network interfaces
"""
ifaddrs = getifaddrs()
# Create new interfaces
for ifname in ifaddrs.keys():
if filter(ifname.startswith, cls.NAME_FILTER):
cls.objects.get_or_create(name=ifname)
... | [
"def",
"update",
"(",
"cls",
")",
":",
"ifaddrs",
"=",
"getifaddrs",
"(",
")",
"# Create new interfaces",
"for",
"ifname",
"in",
"ifaddrs",
".",
"keys",
"(",
")",
":",
"if",
"filter",
"(",
"ifname",
".",
"startswith",
",",
"cls",
".",
"NAME_FILTER",
")",... | 33.666667 | 0.004819 |
def parallel_snr_func(num, binary_args, phenomdwave, signal_type,
noise_interpolants, prefactor, verbose):
"""SNR calulation with PhenomDWaveforms
Generate PhenomDWaveforms and calculate their SNR against sensitivity curves.
Args:
num (int): Process number. If only a single p... | [
"def",
"parallel_snr_func",
"(",
"num",
",",
"binary_args",
",",
"phenomdwave",
",",
"signal_type",
",",
"noise_interpolants",
",",
"prefactor",
",",
"verbose",
")",
":",
"wave",
"=",
"phenomdwave",
"(",
"*",
"binary_args",
")",
"out_vals",
"=",
"{",
"}",
"f... | 40.093023 | 0.002265 |
def spawn_viewer(viewer, img, filename, grace):
"""Launch an external program to view an image.
``img`` is an Image object.
``viewer`` is a command name. Arguments are not allowed; exactly one
argument will be passed: the name of the image file.
``filename`` is the suggested filename for a tempo... | [
"def",
"spawn_viewer",
"(",
"viewer",
",",
"img",
",",
"filename",
",",
"grace",
")",
":",
"tempdir",
"=",
"tempfile",
".",
"mkdtemp",
"(",
"prefix",
"=",
"'imgdiff-'",
")",
"try",
":",
"imgfile",
"=",
"os",
".",
"path",
".",
"join",
"(",
"tempdir",
... | 38.678571 | 0.000901 |
def next(self):
"""Returns the next batch of data."""
if self.curr_idx == len(self.idx):
raise StopIteration
i, j = self.idx[self.curr_idx]
self.curr_idx += 1
audio_paths = []
texts = []
for duration, audio_path, text in self.data[i][j:j+self.batch_si... | [
"def",
"next",
"(",
"self",
")",
":",
"if",
"self",
".",
"curr_idx",
"==",
"len",
"(",
"self",
".",
"idx",
")",
":",
"raise",
"StopIteration",
"i",
",",
"j",
"=",
"self",
".",
"idx",
"[",
"self",
".",
"curr_idx",
"]",
"self",
".",
"curr_idx",
"+=... | 49.088235 | 0.006463 |
def render(template, extra={}, **kwargs):
"""Return the template rendered using Python's str.format()."""
context = hookenv.execution_environment()
context.update(extra)
context.update(kwargs)
return template.format(**context) | [
"def",
"render",
"(",
"template",
",",
"extra",
"=",
"{",
"}",
",",
"*",
"*",
"kwargs",
")",
":",
"context",
"=",
"hookenv",
".",
"execution_environment",
"(",
")",
"context",
".",
"update",
"(",
"extra",
")",
"context",
".",
"update",
"(",
"kwargs",
... | 40.166667 | 0.004065 |
def _highlight_caret_scope(self):
"""
Highlight the scope of the current caret position.
This get called only if :attr:`
spyder.widgets.panels.FoldingPanel.highlight_care_scope` is True.
"""
cursor = self.editor.textCursor()
block_nbr = cursor.blockNumber()
... | [
"def",
"_highlight_caret_scope",
"(",
"self",
")",
":",
"cursor",
"=",
"self",
".",
"editor",
".",
"textCursor",
"(",
")",
"block_nbr",
"=",
"cursor",
".",
"blockNumber",
"(",
")",
"if",
"self",
".",
"_block_nbr",
"!=",
"block_nbr",
":",
"block",
"=",
"F... | 37.285714 | 0.002491 |
def delete_profile(hostname, username, password, profile_type, name):
'''
A function to connect to a bigip device and delete an existing profile.
hostname
The host/address of the bigip device
username
The iControl REST username
password
The iControl REST password
profile... | [
"def",
"delete_profile",
"(",
"hostname",
",",
"username",
",",
"password",
",",
"profile_type",
",",
"name",
")",
":",
"#build sessions",
"bigip_session",
"=",
"_build_session",
"(",
"username",
",",
"password",
")",
"#delete to REST",
"try",
":",
"response",
"... | 28 | 0.004061 |
def createPortForm(self, req, tag):
"""
Create and return a L{LiveForm} for adding a new L{TCPPort} or
L{SSLPort} to the site store.
"""
def port(s):
n = int(s)
if n < 0 or n > 65535:
raise ValueError(s)
return n
factor... | [
"def",
"createPortForm",
"(",
"self",
",",
"req",
",",
"tag",
")",
":",
"def",
"port",
"(",
"s",
")",
":",
"n",
"=",
"int",
"(",
"s",
")",
"if",
"n",
"<",
"0",
"or",
"n",
">",
"65535",
":",
"raise",
"ValueError",
"(",
"s",
")",
"return",
"n",... | 40.324324 | 0.002618 |
def regraft(self, edge, node, length=None):
""" Grafts a node onto an edge of the Tree, at a point specified by
length (defaults to middle of edge). """
rootcheck(edge, 'SPR regraft is not allowed on the root edge')
length = length or edge.length / 2. # Length measured from head to tai... | [
"def",
"regraft",
"(",
"self",
",",
"edge",
",",
"node",
",",
"length",
"=",
"None",
")",
":",
"rootcheck",
"(",
"edge",
",",
"'SPR regraft is not allowed on the root edge'",
")",
"length",
"=",
"length",
"or",
"edge",
".",
"length",
"/",
"2.",
"# Length mea... | 39.588235 | 0.005806 |
def _create_make_unique(inputs):
"""Replaces the lower bits of each element with iota.
The iota is used to derive the index, and also serves the purpose to
make each element unique to break ties.
Args:
inputs: A tensor with rank of 2 and dtype of tf.float32.
[batch_size, original_size].
Returns:
... | [
"def",
"_create_make_unique",
"(",
"inputs",
")",
":",
"if",
"inputs",
".",
"shape",
".",
"ndims",
"!=",
"2",
":",
"raise",
"ValueError",
"(",
"\"Input of top_k_with_unique must be rank-2 \"",
"\"but got: %s\"",
"%",
"inputs",
".",
"shape",
")",
"height",
"=",
"... | 37.790323 | 0.014559 |
def bookmark(ctx):
"""Bookmark group.
Uses [Caching](/references/polyaxon-cli/#caching)
Examples:
\b
```bash
$ polyaxon group bookmark
```
\b
```bash
$ polyaxon group -g 2 bookmark
```
"""
user, project_name, _group = get_project_group_or_local(ctx.obj.get('projec... | [
"def",
"bookmark",
"(",
"ctx",
")",
":",
"user",
",",
"project_name",
",",
"_group",
"=",
"get_project_group_or_local",
"(",
"ctx",
".",
"obj",
".",
"get",
"(",
"'project'",
")",
",",
"ctx",
".",
"obj",
".",
"get",
"(",
"'group'",
")",
")",
"try",
":... | 27.714286 | 0.004981 |
def generate_exercises_from_importstudioid(self, args, options):
"""
Create rows in Exercises.csv and ExerciseQuestions.csv from a Studio channel,
specified based on a studio_id (e.g. studio_id of main_tree for some channel)'
"""
print('Generating Exercises.csv and ExerciseQuesti... | [
"def",
"generate_exercises_from_importstudioid",
"(",
"self",
",",
"args",
",",
"options",
")",
":",
"print",
"(",
"'Generating Exercises.csv and ExerciseQuestions.csv from a Studio channel'",
")",
"self",
".",
"studioapi",
"=",
"StudioApi",
"(",
"token",
"=",
"args",
"... | 47.461538 | 0.006352 |
def register_ops_if_needed(graph_ops):
"""Register graph ops absent in op_def_registry, if present in c++ registry.
Args:
graph_ops: set with graph op names to register.
Raises:
RuntimeError: if `graph_ops` contains ops that are not in either python or
c++ registry.
"""
missing_ops = graph_ops... | [
"def",
"register_ops_if_needed",
"(",
"graph_ops",
")",
":",
"missing_ops",
"=",
"graph_ops",
"-",
"set",
"(",
"op_def_registry",
".",
"get_registered_ops",
"(",
")",
".",
"keys",
"(",
")",
")",
"if",
"not",
"missing_ops",
":",
"return",
"p_buffer",
"=",
"c_... | 34.595238 | 0.012048 |
def __train(self, n_clusters=4):
"""
Calculate cluster's centroids and standard deviations. If there are at least the number of threshold rows \
then:
* Observations will be normalised.
* Standard deviations will be returned.
* Clusters will be retu... | [
"def",
"__train",
"(",
"self",
",",
"n_clusters",
"=",
"4",
")",
":",
"try",
":",
"for",
"obs",
"in",
"self",
".",
"observations",
":",
"features",
",",
"ids",
"=",
"self",
".",
"__get_features_for_observation",
"(",
"observation",
"=",
"obs",
",",
"last... | 42.82 | 0.006393 |
def _call(callable_obj, arg_names, namespace):
"""Actually calls the callable with the namespace parsed from the command
line.
Args:
callable_obj: a callable object
arg_names: name of the function arguments
namespace: the namespace object parsed from the command line
"""
arg... | [
"def",
"_call",
"(",
"callable_obj",
",",
"arg_names",
",",
"namespace",
")",
":",
"arguments",
"=",
"{",
"arg_name",
":",
"getattr",
"(",
"namespace",
",",
"arg_name",
")",
"for",
"arg_name",
"in",
"arg_names",
"}",
"return",
"callable_obj",
"(",
"*",
"*"... | 36.5 | 0.002227 |
def _get_setter_fun(object_type, # type: Type
parameter, # type: Parameter
private_property_name # type: str
):
"""
Utility method to find the overridden setter function for a given property, or generate a new one
:param obj... | [
"def",
"_get_setter_fun",
"(",
"object_type",
",",
"# type: Type",
"parameter",
",",
"# type: Parameter",
"private_property_name",
"# type: str",
")",
":",
"# the property will have the same name than the constructor argument",
"property_name",
"=",
"parameter",
".",
"name",
"o... | 38.534483 | 0.00349 |
def _clean_java_out(version_str):
"""Remove extra environmental information reported in java when querying for versions.
Java will report information like _JAVA_OPTIONS environmental variables in the output.
"""
out = []
for line in version_str.decode().split("\n"):
if line.startswith("Pick... | [
"def",
"_clean_java_out",
"(",
"version_str",
")",
":",
"out",
"=",
"[",
"]",
"for",
"line",
"in",
"version_str",
".",
"decode",
"(",
")",
".",
"split",
"(",
"\"\\n\"",
")",
":",
"if",
"line",
".",
"startswith",
"(",
"\"Picked up\"",
")",
":",
"pass",
... | 32.642857 | 0.006383 |
def comment(self, institute, case, user, link, variant=None,
content="", comment_level="specific"):
"""Add a comment to a variant or a case.
This function will create an Event to log that a user have commented on
a variant. If a variant id is given it will be a variant comment.
... | [
"def",
"comment",
"(",
"self",
",",
"institute",
",",
"case",
",",
"user",
",",
"link",
",",
"variant",
"=",
"None",
",",
"content",
"=",
"\"\"",
",",
"comment_level",
"=",
"\"specific\"",
")",
":",
"if",
"not",
"comment_level",
"in",
"COMMENT_LEVELS",
"... | 37.017241 | 0.002269 |
def argmin(self):
"""
Get the index of the minimum numeric value in SArray.
Returns None on an empty SArray. Raises an exception if called on an
SArray with non-numeric type.
Returns
-------
out : int
index of the minimum value of SArray
See... | [
"def",
"argmin",
"(",
"self",
")",
":",
"from",
".",
"sframe",
"import",
"SFrame",
"as",
"_SFrame",
"if",
"len",
"(",
"self",
")",
"==",
"0",
":",
"return",
"None",
"if",
"not",
"any",
"(",
"[",
"isinstance",
"(",
"self",
"[",
"0",
"]",
",",
"i",... | 28.870968 | 0.008649 |
def html_state(self):
"""Display state in HTML format for the admin form."""
ret = ""
state = json.loads(self.state)
for (app, appstate) in state.items():
for (model, modelstate) in appstate.items():
ret += "<p>%s.models.%s</p>" % (app, model,)
... | [
"def",
"html_state",
"(",
"self",
")",
":",
"ret",
"=",
"\"\"",
"state",
"=",
"json",
".",
"loads",
"(",
"self",
".",
"state",
")",
"for",
"(",
"app",
",",
"appstate",
")",
"in",
"state",
".",
"items",
"(",
")",
":",
"for",
"(",
"model",
",",
"... | 42.428571 | 0.003295 |
def get_blockchain_fee_estimates(coin_symbol='btc', api_key=None):
"""
Returns high, medium, and low fee estimates for a given blockchain.
"""
overview = get_blockchain_overview(coin_symbol=coin_symbol, api_key=api_key)
return {
'high_fee_per_kb': overview['high_fee_per_kb'],
... | [
"def",
"get_blockchain_fee_estimates",
"(",
"coin_symbol",
"=",
"'btc'",
",",
"api_key",
"=",
"None",
")",
":",
"overview",
"=",
"get_blockchain_overview",
"(",
"coin_symbol",
"=",
"coin_symbol",
",",
"api_key",
"=",
"api_key",
")",
"return",
"{",
"'high_fee_per_k... | 43.5 | 0.004505 |
def get_forecast_fromstr(self, reply):
"""
Gets the weather data from a darksky api response string
and stores it in the respective dictionaries if available.
This function should be used to fetch weather information.
"""
self.forecast = json.loads(reply)
for ite... | [
"def",
"get_forecast_fromstr",
"(",
"self",
",",
"reply",
")",
":",
"self",
".",
"forecast",
"=",
"json",
".",
"loads",
"(",
"reply",
")",
"for",
"item",
"in",
"self",
".",
"forecast",
".",
"keys",
"(",
")",
":",
"setattr",
"(",
"self",
",",
"item",
... | 39 | 0.005013 |
def cmap_from_text(filename, norm=False, transparency=False, hex=False):
'''
cmap_from_text takes as input a file that contains a colormap in text format
composed by lines with 3 values in the range [0,255] or [00,FF]
and returns a tuple of integers. If the parameters cat and tot are given,
the func... | [
"def",
"cmap_from_text",
"(",
"filename",
",",
"norm",
"=",
"False",
",",
"transparency",
"=",
"False",
",",
"hex",
"=",
"False",
")",
":",
"lines",
"=",
"[",
"line",
".",
"rstrip",
"(",
"'\\n'",
")",
"for",
"line",
"in",
"open",
"(",
"filename",
")"... | 43.545455 | 0.012257 |
def qteMakeAppletActive(self, applet: (QtmacsApplet, str)):
"""
Make ``applet`` visible and give it the focus.
If ``applet`` is not yet visible it will replace the
currently active applet, otherwise only the focus will shift.
The ``applet`` parameter can either be an instance o... | [
"def",
"qteMakeAppletActive",
"(",
"self",
",",
"applet",
":",
"(",
"QtmacsApplet",
",",
"str",
")",
")",
":",
"# If ``applet`` was specified by its ID (ie. a string) then",
"# fetch the associated ``QtmacsApplet`` instance. If",
"# ``applet`` is already an instance of ``QtmacsApplet... | 37.672414 | 0.000892 |
def createMultipleL4L2ColumnsWithTopology(network, networkConfig):
"""
Create a network consisting of multiple columns. Each column contains one
L4 and one L2, is identical in structure to the network created by
createL4L2Column. In addition the L2 columns are connected to each
other through their lateral in... | [
"def",
"createMultipleL4L2ColumnsWithTopology",
"(",
"network",
",",
"networkConfig",
")",
":",
"numCorticalColumns",
"=",
"networkConfig",
"[",
"\"numCorticalColumns\"",
"]",
"output_lateral_connections",
"=",
"[",
"[",
"]",
"for",
"i",
"in",
"xrange",
"(",
"numCorti... | 39.921569 | 0.008387 |
def _template(node_id, value=None):
"Check if a template is assigned to it and render that with the value"
result = []
select_template_from_node = fetch_query_string('select_template_from_node.sql')
try:
result = db.execute(text(select_template_from_node), node_id=node_id)
template_resul... | [
"def",
"_template",
"(",
"node_id",
",",
"value",
"=",
"None",
")",
":",
"result",
"=",
"[",
"]",
"select_template_from_node",
"=",
"fetch_query_string",
"(",
"'select_template_from_node.sql'",
")",
"try",
":",
"result",
"=",
"db",
".",
"execute",
"(",
"text",... | 40.1 | 0.002436 |
def CDQ(cpu):
"""
EDX:EAX = sign-extend of EAX
"""
cpu.EDX = Operators.EXTRACT(Operators.SEXTEND(cpu.EAX, 32, 64), 32, 32) | [
"def",
"CDQ",
"(",
"cpu",
")",
":",
"cpu",
".",
"EDX",
"=",
"Operators",
".",
"EXTRACT",
"(",
"Operators",
".",
"SEXTEND",
"(",
"cpu",
".",
"EAX",
",",
"32",
",",
"64",
")",
",",
"32",
",",
"32",
")"
] | 30 | 0.012987 |
def parse(cls, backend, ik, spk, spk_signature, otpks):
"""
Use this method when creating a bundle from data you retrieved directly from some
PEP node. This method applies an additional decoding step to the public keys in
the bundle. Pass the same structure as the constructor expects.
... | [
"def",
"parse",
"(",
"cls",
",",
"backend",
",",
"ik",
",",
"spk",
",",
"spk_signature",
",",
"otpks",
")",
":",
"ik",
"=",
"backend",
".",
"decodePublicKey",
"(",
"ik",
")",
"[",
"0",
"]",
"spk",
"[",
"\"key\"",
"]",
"=",
"backend",
".",
"decodePu... | 36.588235 | 0.009404 |
def _distribution_info(self):
"""Creates the distribution name and the expected extension for the
CSPICE package and returns it.
:return (distribution, extension) tuple where distribution is the best
guess from the strings available within the platform_urls list
... | [
"def",
"_distribution_info",
"(",
"self",
")",
":",
"print",
"(",
"'Gathering information...'",
")",
"system",
"=",
"platform",
".",
"system",
"(",
")",
"# Cygwin system is CYGWIN-NT-xxx.",
"system",
"=",
"'cygwin'",
"if",
"'CYGWIN'",
"in",
"system",
"else",
"syst... | 38 | 0.001833 |
def find_all(self, table, limit=10):
'''
从数据库里查询所有记录
Args:
table: 表名字 str
limit: 限制数量
return:
成功: [dict] 保存的记录
失败: -1 并打印返回报错信息
'''
sql = "select * from {} limit 0,{}".format(table, limit)
res = self.query(sql)
... | [
"def",
"find_all",
"(",
"self",
",",
"table",
",",
"limit",
"=",
"10",
")",
":",
"sql",
"=",
"\"select * from {} limit 0,{}\"",
".",
"format",
"(",
"table",
",",
"limit",
")",
"res",
"=",
"self",
".",
"query",
"(",
"sql",
")",
"return",
"res"
] | 24.692308 | 0.006006 |
def set_log_file_maximum_size(self, logFileMaxSize):
"""
Set the log file maximum size in megabytes
:Parameters:
#. logFileMaxSize (number): The maximum size in Megabytes of a logging file.
Once exceeded, another logging file as logFileBasename_N.logFileExtension
... | [
"def",
"set_log_file_maximum_size",
"(",
"self",
",",
"logFileMaxSize",
")",
":",
"assert",
"_is_number",
"(",
"logFileMaxSize",
")",
",",
"\"logFileMaxSize must be a number\"",
"logFileMaxSize",
"=",
"float",
"(",
"logFileMaxSize",
")",
"assert",
"logFileMaxSize",
">="... | 49.384615 | 0.007645 |
def tree(self, sha):
"""Get a tree.
:param str sha: (required), sha of the object for this tree
:returns: :class:`Tree <github3.git.Tree>`
"""
json = None
if sha:
url = self._build_url('git', 'trees', sha, base_url=self._api)
json = self._json(sel... | [
"def",
"tree",
"(",
"self",
",",
"sha",
")",
":",
"json",
"=",
"None",
"if",
"sha",
":",
"url",
"=",
"self",
".",
"_build_url",
"(",
"'git'",
",",
"'trees'",
",",
"sha",
",",
"base_url",
"=",
"self",
".",
"_api",
")",
"json",
"=",
"self",
".",
... | 34.272727 | 0.005168 |
def col_isdt(df,col_name = None):
""" Returns a list of columns that are of type 'datetime'. If col_name is specified, returns
whether the column in the DataFrame is of type 'datetime' instead.
Parameters:
df - DataFrame
DataFrame to check
col_name - string, default None
If specifie... | [
"def",
"col_isdt",
"(",
"df",
",",
"col_name",
"=",
"None",
")",
":",
"col_list",
"=",
"df",
".",
"select_dtypes",
"(",
"include",
"=",
"'datetime'",
")",
".",
"columns",
"if",
"col_name",
"is",
"None",
":",
"return",
"col_list",
"else",
":",
"return",
... | 38.285714 | 0.016393 |
def publish_extension_events(self, extension_events):
"""PublishExtensionEvents.
[Preview API] API endpoint to publish extension install/uninstall events. This is meant to be invoked by EMS only for sending us data related to install/uninstall of an extension.
:param [ExtensionEvents] extension_... | [
"def",
"publish_extension_events",
"(",
"self",
",",
"extension_events",
")",
":",
"content",
"=",
"self",
".",
"_serialize",
".",
"body",
"(",
"extension_events",
",",
"'[ExtensionEvents]'",
")",
"self",
".",
"_send",
"(",
"http_method",
"=",
"'POST'",
",",
"... | 59.8 | 0.004942 |
def defer_function(self, callable):
"""Schedule a function handler to be called just before completion.
This is used for handling function bodies, which must be deferred because code later in the file might modify
the global scope. When 'callable' is called, the scope at the time this is called... | [
"def",
"defer_function",
"(",
"self",
",",
"callable",
")",
":",
"self",
".",
"_deferred_functions",
".",
"append",
"(",
"(",
"callable",
",",
"self",
".",
"scope_stack",
"[",
":",
"]",
",",
"self",
".",
"offset",
")",
")"
] | 54.555556 | 0.01002 |
def get_last_id(self, cur, table='reaction'):
"""
Get the id of the last written row in table
Parameters
----------
cur: database connection().cursor() object
table: str
'reaction', 'publication', 'publication_system', 'reaction_system'
Returns: id
... | [
"def",
"get_last_id",
"(",
"self",
",",
"cur",
",",
"table",
"=",
"'reaction'",
")",
":",
"cur",
".",
"execute",
"(",
"\"SELECT seq FROM sqlite_sequence WHERE name='{0}'\"",
".",
"format",
"(",
"table",
")",
")",
"result",
"=",
"cur",
".",
"fetchone",
"(",
"... | 27.95 | 0.00346 |
def has_credentials(self):
"""
Does this session have valid credentials
:rtype: bool
"""
return all([
getattr(self, '_%s' % field, None) is not None
for field in self.CredentialMap.get(self.provider_name)]) | [
"def",
"has_credentials",
"(",
"self",
")",
":",
"return",
"all",
"(",
"[",
"getattr",
"(",
"self",
",",
"'_%s'",
"%",
"field",
",",
"None",
")",
"is",
"not",
"None",
"for",
"field",
"in",
"self",
".",
"CredentialMap",
".",
"get",
"(",
"self",
".",
... | 30.111111 | 0.010753 |
def partition_metadata(self, partition_key):
"""
Retrieves the metadata dictionary for the remote database partition.
:param str partition_key: Partition key.
:returns: Metadata dictionary for the database partition.
:rtype: dict
"""
resp = self.r_session.get(sel... | [
"def",
"partition_metadata",
"(",
"self",
",",
"partition_key",
")",
":",
"resp",
"=",
"self",
".",
"r_session",
".",
"get",
"(",
"self",
".",
"database_partition_url",
"(",
"partition_key",
")",
")",
"resp",
".",
"raise_for_status",
"(",
")",
"return",
"res... | 38.636364 | 0.004598 |
def do_GET(self):
"""
Accepts GET requests to http://localhost:6500/, and stores the query
params in the global dict. If shutdown_on_request is true, stop the
server after the first successful request.
The http request may contain the following query params:
- state ... | [
"def",
"do_GET",
"(",
"self",
")",
":",
"parsed_path",
"=",
"urlparse",
"(",
"self",
".",
"path",
")",
"if",
"parsed_path",
".",
"path",
"!=",
"'/'",
":",
"self",
".",
"send_error",
"(",
"404",
")",
"qs",
"=",
"parse_qs",
"(",
"parsed_path",
".",
"qu... | 39.027027 | 0.001351 |
def add_random_tile(self):
"""Adds a random tile to the grid. Assumes that it has empty fields."""
x_pos, y_pos = np.where(self._state == 0)
assert len(x_pos) != 0
empty_index = np.random.choice(len(x_pos))
value = np.random.choice([1, 2], p=[0.9, 0.1])
self._state[x_po... | [
"def",
"add_random_tile",
"(",
"self",
")",
":",
"x_pos",
",",
"y_pos",
"=",
"np",
".",
"where",
"(",
"self",
".",
"_state",
"==",
"0",
")",
"assert",
"len",
"(",
"x_pos",
")",
"!=",
"0",
"empty_index",
"=",
"np",
".",
"random",
".",
"choice",
"(",... | 39.444444 | 0.00551 |
def remove_acl(cursor, uuid_, permissions):
"""Given a ``uuid`` and a set of permissions given as a tuple
of ``uid`` and ``permission``, remove these entries from the database.
"""
if not isinstance(permissions, (list, set, tuple,)):
raise TypeError("``permissions`` is an invalid type: {}"
... | [
"def",
"remove_acl",
"(",
"cursor",
",",
"uuid_",
",",
"permissions",
")",
":",
"if",
"not",
"isinstance",
"(",
"permissions",
",",
"(",
"list",
",",
"set",
",",
"tuple",
",",
")",
")",
":",
"raise",
"TypeError",
"(",
"\"``permissions`` is an invalid type: {... | 38.625 | 0.00158 |
def getSets(self):
"""
Get all the sets declared.
"""
sets = lock_and_call(
lambda: self._impl.getSets(),
self._lock
)
return EntityMap(sets, Set) | [
"def",
"getSets",
"(",
"self",
")",
":",
"sets",
"=",
"lock_and_call",
"(",
"lambda",
":",
"self",
".",
"_impl",
".",
"getSets",
"(",
")",
",",
"self",
".",
"_lock",
")",
"return",
"EntityMap",
"(",
"sets",
",",
"Set",
")"
] | 23.333333 | 0.009174 |
async def get_first_search_result(self, term: str):
"""Get first search result.
This function will parse the information from the link that search_novel_updates returns
and then return it as a dictionary
:param term: The novel to search for and parse
"""
# Uses the othe... | [
"async",
"def",
"get_first_search_result",
"(",
"self",
",",
"term",
":",
"str",
")",
":",
"# Uses the other method in the class",
"# to search the search page for the actual page that we want",
"to_parse",
"=",
"await",
"self",
".",
"get_search_page",
"(",
"term",
")",
"... | 49.944954 | 0.003422 |
def altaz(self, temperature_C=None, pressure_mbar='standard'):
"""Compute (alt, az, distance) relative to the observer's horizon
The altitude returned is an `Angle` in degrees above the
horizon, while the azimuth is the compass direction in degrees
with north being 0 degrees and east be... | [
"def",
"altaz",
"(",
"self",
",",
"temperature_C",
"=",
"None",
",",
"pressure_mbar",
"=",
"'standard'",
")",
":",
"return",
"_to_altaz",
"(",
"self",
".",
"position",
".",
"au",
",",
"self",
".",
"observer_data",
",",
"temperature_C",
",",
"pressure_mbar",
... | 45.7 | 0.004292 |
def _set_name(self):
"""Set device name."""
try:
self._name = pretty(self.machine_name)
self._serial = self.serial_number
except AttributeError:
self._name = None
self._serial = None | [
"def",
"_set_name",
"(",
"self",
")",
":",
"try",
":",
"self",
".",
"_name",
"=",
"pretty",
"(",
"self",
".",
"machine_name",
")",
"self",
".",
"_serial",
"=",
"self",
".",
"serial_number",
"except",
"AttributeError",
":",
"self",
".",
"_name",
"=",
"N... | 30.875 | 0.007874 |
def get_matrix(self):
""" Use numpy to create a real matrix object from the data
:return: the matrix representation of the fvm
"""
return np.array([ self.get_row_list(i) for i in range(self.row_count()) ]) | [
"def",
"get_matrix",
"(",
"self",
")",
":",
"return",
"np",
".",
"array",
"(",
"[",
"self",
".",
"get_row_list",
"(",
"i",
")",
"for",
"i",
"in",
"range",
"(",
"self",
".",
"row_count",
"(",
")",
")",
"]",
")"
] | 39 | 0.020921 |
async def get(self, key):
"""Decode the value."""
value = await self.conn.get(key)
if self.cfg.jsonpickle:
if isinstance(value, bytes):
return jsonpickle.decode(value.decode('utf-8'))
if isinstance(value, str):
return jsonpickle.decode(val... | [
"async",
"def",
"get",
"(",
"self",
",",
"key",
")",
":",
"value",
"=",
"await",
"self",
".",
"conn",
".",
"get",
"(",
"key",
")",
"if",
"self",
".",
"cfg",
".",
"jsonpickle",
":",
"if",
"isinstance",
"(",
"value",
",",
"bytes",
")",
":",
"return... | 30.454545 | 0.005797 |
def train_df(self, df):
"""
Train scale from a dataframe
"""
aesthetics = sorted(set(self.aesthetics) & set(df.columns))
for ae in aesthetics:
self.train(df[ae]) | [
"def",
"train_df",
"(",
"self",
",",
"df",
")",
":",
"aesthetics",
"=",
"sorted",
"(",
"set",
"(",
"self",
".",
"aesthetics",
")",
"&",
"set",
"(",
"df",
".",
"columns",
")",
")",
"for",
"ae",
"in",
"aesthetics",
":",
"self",
".",
"train",
"(",
"... | 29.571429 | 0.00939 |
def demo(self, *args, **kwargs):
"""
Simple run method
"""
print('* calling: self.dp.qprint("Why hello there, world!"):')
self.dp.qprint("Why hello there, world!")
print('* calling: self.dp2.qprint("Why hello there, world! In a debugging file!"):')
self.dp2.qpri... | [
"def",
"demo",
"(",
"self",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"print",
"(",
"'* calling: self.dp.qprint(\"Why hello there, world!\"):'",
")",
"self",
".",
"dp",
".",
"qprint",
"(",
"\"Why hello there, world!\"",
")",
"print",
"(",
"'* calling:... | 41.277778 | 0.012492 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.