text stringlengths 75 104k | code_tokens list | avg_line_len float64 7.91 980 | score float64 0 0.18 |
|---|---|---|---|
def get_arguments(self):
"""
Extracts the specific arguments of this CLI
"""
AlarmModify.get_arguments(self)
self._alarm_id = self.args.alarm_id if self.args.alarm_id is not None else None
self.get_api_parameters() | [
"def",
"get_arguments",
"(",
"self",
")",
":",
"AlarmModify",
".",
"get_arguments",
"(",
"self",
")",
"self",
".",
"_alarm_id",
"=",
"self",
".",
"args",
".",
"alarm_id",
"if",
"self",
".",
"args",
".",
"alarm_id",
"is",
"not",
"None",
"else",
"None",
... | 32 | 0.011407 |
def fidelity(rho0: Density, rho1: Density) -> float:
"""Return the fidelity F(rho0, rho1) between two mixed quantum states.
Note: Fidelity cannot be calculated entirely within the tensor backend.
"""
assert rho0.qubit_nb == rho1.qubit_nb # FIXME
rho1 = rho1.permute(rho0.qubits)
op0 = asarray... | [
"def",
"fidelity",
"(",
"rho0",
":",
"Density",
",",
"rho1",
":",
"Density",
")",
"->",
"float",
":",
"assert",
"rho0",
".",
"qubit_nb",
"==",
"rho1",
".",
"qubit_nb",
"# FIXME",
"rho1",
"=",
"rho1",
".",
"permute",
"(",
"rho0",
".",
"qubits",
")",
"... | 33.3125 | 0.001825 |
def _initEncoder(self, w, minval, maxval, n, radius, resolution):
""" (helper function) There are three different ways of thinking about the representation.
Handle each case here."""
if n != 0:
if (radius !=0 or resolution != 0):
raise ValueError("Only one of n/radius/resolution can be speci... | [
"def",
"_initEncoder",
"(",
"self",
",",
"w",
",",
"minval",
",",
"maxval",
",",
"n",
",",
"radius",
",",
"resolution",
")",
":",
"if",
"n",
"!=",
"0",
":",
"if",
"(",
"radius",
"!=",
"0",
"or",
"resolution",
"!=",
"0",
")",
":",
"raise",
"ValueE... | 36.738095 | 0.013258 |
def _get_process_names(self, con, pid):
"""Returns the input/output process names and output process directives
Parameters
----------
con : dict
Dictionary with the connection information between two processes.
Returns
-------
input_name : str
... | [
"def",
"_get_process_names",
"(",
"self",
",",
"con",
",",
"pid",
")",
":",
"try",
":",
"_p_in_name",
"=",
"con",
"[",
"\"input\"",
"]",
"[",
"\"process\"",
"]",
"p_in_name",
",",
"_",
"=",
"self",
".",
"_parse_process_name",
"(",
"_p_in_name",
")",
"log... | 35.818182 | 0.001647 |
def diagnostics(self):
"""Dictionary access to all diagnostic variables
:type: dict
"""
diag_dict = {}
for key in self._diag_vars:
try:
#diag_dict[key] = getattr(self,key)
# using self.__dict__ doesn't count diagnostics defined ... | [
"def",
"diagnostics",
"(",
"self",
")",
":",
"diag_dict",
"=",
"{",
"}",
"for",
"key",
"in",
"self",
".",
"_diag_vars",
":",
"try",
":",
"#diag_dict[key] = getattr(self,key)",
"# using self.__dict__ doesn't count diagnostics defined as properties",
"diag_dict",
"[",
"k... | 29.133333 | 0.011086 |
def unlock(self, session=None):
"""Unlock a previously locked server.
:Parameters:
- `session` (optional): a
:class:`~pymongo.client_session.ClientSession`.
.. versionchanged:: 3.6
Added ``session`` parameter.
"""
cmd = SON([("fsyncUnlock", 1)])... | [
"def",
"unlock",
"(",
"self",
",",
"session",
"=",
"None",
")",
":",
"cmd",
"=",
"SON",
"(",
"[",
"(",
"\"fsyncUnlock\"",
",",
"1",
")",
"]",
")",
"with",
"self",
".",
"_socket_for_writes",
"(",
"session",
")",
"as",
"sock_info",
":",
"if",
"sock_inf... | 41.192308 | 0.001825 |
def parse_hgnc_line(line, header):
"""Parse an hgnc formated line
Args:
line(list): A list with hgnc gene info
header(list): A list with the header info
Returns:
hgnc_info(dict): A dictionary with the relevant info
"""
hgnc_gene = {}
line = line.rstr... | [
"def",
"parse_hgnc_line",
"(",
"line",
",",
"header",
")",
":",
"hgnc_gene",
"=",
"{",
"}",
"line",
"=",
"line",
".",
"rstrip",
"(",
")",
".",
"split",
"(",
"'\\t'",
")",
"raw_info",
"=",
"dict",
"(",
"zip",
"(",
"header",
",",
"line",
")",
")",
... | 29.936709 | 0.001228 |
def pop_kwargs(kwargs,
names_with_defaults, # type: List[Tuple[str, Any]]
allow_others=False
):
"""
Internal utility method to extract optional arguments from kwargs.
:param kwargs:
:param names_with_defaults:
:param allow_others: if False (default) the... | [
"def",
"pop_kwargs",
"(",
"kwargs",
",",
"names_with_defaults",
",",
"# type: List[Tuple[str, Any]]",
"allow_others",
"=",
"False",
")",
":",
"all_arguments",
"=",
"[",
"]",
"for",
"name",
",",
"default_",
"in",
"names_with_defaults",
":",
"try",
":",
"val",
"="... | 30 | 0.002392 |
def add(name,
password=None,
fullname=None,
description=None,
groups=None,
home=None,
homedrive=None,
profile=None,
logonscript=None):
'''
Add a user to the minion.
Args:
name (str): User name
password (str, optional): User's ... | [
"def",
"add",
"(",
"name",
",",
"password",
"=",
"None",
",",
"fullname",
"=",
"None",
",",
"description",
"=",
"None",
",",
"groups",
"=",
"None",
",",
"home",
"=",
"None",
",",
"homedrive",
"=",
"None",
",",
"profile",
"=",
"None",
",",
"logonscrip... | 27.785714 | 0.000827 |
def update(self,record,**kw):
"""Update the record with new keys and values"""
vals = self._make_sql_params(kw)
sql = "UPDATE %s SET %s WHERE rowid=?" %(self.name,
",".join(vals))
self.cursor.execute(sql,kw.values()+[record['__id__']]) | [
"def",
"update",
"(",
"self",
",",
"record",
",",
"*",
"*",
"kw",
")",
":",
"vals",
"=",
"self",
".",
"_make_sql_params",
"(",
"kw",
")",
"sql",
"=",
"\"UPDATE %s SET %s WHERE rowid=?\"",
"%",
"(",
"self",
".",
"name",
",",
"\",\"",
".",
"join",
"(",
... | 46.5 | 0.024648 |
def impulse_deltav_plummerstream_curvedstream(v,x,t,b,w,x0,v0,GSigma,rs,
galpot,tmin=None,tmax=None):
"""
NAME:
impulse_deltav_plummerstream_curvedstream
PURPOSE:
calculate the delta velocity to due an encounter with a Plummer sphere in the impu... | [
"def",
"impulse_deltav_plummerstream_curvedstream",
"(",
"v",
",",
"x",
",",
"t",
",",
"b",
",",
"w",
",",
"x0",
",",
"v0",
",",
"GSigma",
",",
"rs",
",",
"galpot",
",",
"tmin",
"=",
"None",
",",
"tmax",
"=",
"None",
")",
":",
"galpot",
"=",
"flatt... | 33.603175 | 0.026618 |
def map_blocks(data, f, blen=None, storage=None, create='array', **kwargs):
"""Apply function `f` block-wise over `data`."""
# setup
storage = _util.get_storage(storage)
if isinstance(data, tuple):
blen = max(_util.get_blen_array(d, blen) for d in data)
else:
blen = _util.get_blen_a... | [
"def",
"map_blocks",
"(",
"data",
",",
"f",
",",
"blen",
"=",
"None",
",",
"storage",
"=",
"None",
",",
"create",
"=",
"'array'",
",",
"*",
"*",
"kwargs",
")",
":",
"# setup",
"storage",
"=",
"_util",
".",
"get_storage",
"(",
"storage",
")",
"if",
... | 25.583333 | 0.001046 |
def get_backoff_time(self):
""" Formula for computing the current backoff
:rtype: float
"""
# We want to consider only the last consecutive errors sequence (Ignore redirects).
consecutive_errors_len = len(list(takewhile(lambda x: x.redirect_location is None,
... | [
"def",
"get_backoff_time",
"(",
"self",
")",
":",
"# We want to consider only the last consecutive errors sequence (Ignore redirects).",
"consecutive_errors_len",
"=",
"len",
"(",
"list",
"(",
"takewhile",
"(",
"lambda",
"x",
":",
"x",
".",
"redirect_location",
"is",
"Non... | 43.153846 | 0.008726 |
def apply(diff, recs, strict=True):
"""
Transform the records with the patch. May fail if the records do not
match those expected in the patch.
"""
index_columns = diff['_index']
indexed = records.index(copy.deepcopy(list(recs)), index_columns)
_add_records(indexed, diff['added'], index_colu... | [
"def",
"apply",
"(",
"diff",
",",
"recs",
",",
"strict",
"=",
"True",
")",
":",
"index_columns",
"=",
"diff",
"[",
"'_index'",
"]",
"indexed",
"=",
"records",
".",
"index",
"(",
"copy",
".",
"deepcopy",
"(",
"list",
"(",
"recs",
")",
")",
",",
"ind... | 46.181818 | 0.001931 |
def illmat(D, random_state=None):
"""Generate a <D x D> ill-conditioned correlation matrix
with random coefficients
Parameters:
-----------
D : int
Dimension of the matrix
Return:
-------
cmat : ndarray
DxD matrix with +1 as diagonal elements,
mirrored random nu... | [
"def",
"illmat",
"(",
"D",
",",
"random_state",
"=",
"None",
")",
":",
"if",
"random_state",
":",
"np",
".",
"random",
".",
"seed",
"(",
"random_state",
")",
"uni",
"=",
"np",
".",
"random",
".",
"uniform",
"(",
"size",
"=",
"(",
"D",
",",
"D",
"... | 21.64 | 0.00177 |
def recursion(self, input_energy, mask=None, go_backwards=False, return_sequences=True, return_logZ=True, input_length=None):
"""Forward (alpha) or backward (beta) recursion
If `return_logZ = True`, compute the logZ, the normalization constant:
\[ Z = \sum_{y1, y2, y3} exp(-E) # energy
... | [
"def",
"recursion",
"(",
"self",
",",
"input_energy",
",",
"mask",
"=",
"None",
",",
"go_backwards",
"=",
"False",
",",
"return_sequences",
"=",
"True",
",",
"return_logZ",
"=",
"True",
",",
"input_length",
"=",
"None",
")",
":",
"chain_energy",
"=",
"self... | 49.255814 | 0.010185 |
def determine_optimum_fraction_correct_cutoffs(self, analysis_set, dataframe, stability_classication_x_cutoff):
'''Determines the value of stability_classication_y_cutoff which approximately maximizes the fraction correct
measurement w.r.t. a fixed stability_classication_x_cutoff. This function uses ... | [
"def",
"determine_optimum_fraction_correct_cutoffs",
"(",
"self",
",",
"analysis_set",
",",
"dataframe",
",",
"stability_classication_x_cutoff",
")",
":",
"# Determine the value for the fraction correct y-value (predicted) cutoff which will approximately yield the",
"# maximum fraction-cor... | 70.058824 | 0.012008 |
def _db_filename_from_dataframe(base_filename, df):
"""
Generate database filename for a sqlite3 database we're going to
fill with the contents of a DataFrame, using the DataFrame's
column names and types.
"""
db_filename = base_filename + ("_nrows%d" % len(df))
for column_name in df.columns... | [
"def",
"_db_filename_from_dataframe",
"(",
"base_filename",
",",
"df",
")",
":",
"db_filename",
"=",
"base_filename",
"+",
"(",
"\"_nrows%d\"",
"%",
"len",
"(",
"df",
")",
")",
"for",
"column_name",
"in",
"df",
".",
"columns",
":",
"column_db_type",
"=",
"db... | 42.75 | 0.001908 |
def _equality_check(op):
"""
Shared code for __eq__ and __ne__, parameterized on the actual
comparison operator to use.
"""
def method(self, other):
if isinstance(other, LabelArray):
self_mv = self.missing_value
other_mv = other.missin... | [
"def",
"_equality_check",
"(",
"op",
")",
":",
"def",
"method",
"(",
"self",
",",
"other",
")",
":",
"if",
"isinstance",
"(",
"other",
",",
"LabelArray",
")",
":",
"self_mv",
"=",
"self",
".",
"missing_value",
"other_mv",
"=",
"other",
".",
"missing_valu... | 39.971429 | 0.001396 |
def export(self, path, _sentinel=None, # pylint: disable=invalid-name
checkpoint_path=None, name_transform_fn=None):
"""Exports a ModuleSpec with weights taken from a checkpoint.
This is an helper to export modules directly from a ModuleSpec
without having to create a session and set the vari... | [
"def",
"export",
"(",
"self",
",",
"path",
",",
"_sentinel",
"=",
"None",
",",
"# pylint: disable=invalid-name",
"checkpoint_path",
"=",
"None",
",",
"name_transform_fn",
"=",
"None",
")",
":",
"from",
"tensorflow_hub",
".",
"module",
"import",
"export_module_spec... | 43.594595 | 0.002426 |
def _parse_settings_vlan(opts, iface):
'''
Filters given options and outputs valid settings for a vlan
'''
vlan = {}
if 'reorder_hdr' in opts:
if opts['reorder_hdr'] in _CONFIG_TRUE + _CONFIG_FALSE:
vlan.update({'reorder_hdr': opts['reorder_hdr']})
else:
vali... | [
"def",
"_parse_settings_vlan",
"(",
"opts",
",",
"iface",
")",
":",
"vlan",
"=",
"{",
"}",
"if",
"'reorder_hdr'",
"in",
"opts",
":",
"if",
"opts",
"[",
"'reorder_hdr'",
"]",
"in",
"_CONFIG_TRUE",
"+",
"_CONFIG_FALSE",
":",
"vlan",
".",
"update",
"(",
"{"... | 30.653846 | 0.001217 |
def check_info(info):
""" Validate info dict.
Raise ValueError if validation fails.
"""
if not isinstance(info, dict):
raise ValueError("bad metainfo - not a dictionary")
pieces = info.get("pieces")
if not isinstance(pieces, basestring) or len(pieces) % 20 != 0:
raise Value... | [
"def",
"check_info",
"(",
"info",
")",
":",
"if",
"not",
"isinstance",
"(",
"info",
",",
"dict",
")",
":",
"raise",
"ValueError",
"(",
"\"bad metainfo - not a dictionary\"",
")",
"pieces",
"=",
"info",
".",
"get",
"(",
"\"pieces\"",
")",
"if",
"not",
"isin... | 38.983333 | 0.001668 |
def sites(c):
"""
Build both doc sites w/ maxed nitpicking.
"""
# TODO: This is super lolzy but we haven't actually tackled nontrivial
# in-Python task calling yet, so we do this to get a copy of 'our' context,
# which has been updated with the per-collection config data of the
# docs/www su... | [
"def",
"sites",
"(",
"c",
")",
":",
"# TODO: This is super lolzy but we haven't actually tackled nontrivial",
"# in-Python task calling yet, so we do this to get a copy of 'our' context,",
"# which has been updated with the per-collection config data of the",
"# docs/www subcollections.",
"docs_... | 44.555556 | 0.000814 |
def _register(cls,
app,
base_route=None,
subdomain=None,
route_prefix=None,
trailing_slash=True):
"""Registers a Mocha class for use with a specific instance of a
Flask app. Any methods not prefixes with an undersc... | [
"def",
"_register",
"(",
"cls",
",",
"app",
",",
"base_route",
"=",
"None",
",",
"subdomain",
"=",
"None",
",",
"route_prefix",
"=",
"None",
",",
"trailing_slash",
"=",
"True",
")",
":",
"if",
"cls",
"is",
"Mocha",
":",
"raise",
"TypeError",
"(",
"\"cl... | 40.770492 | 0.001766 |
def _release(self):
"""Destroy self since closures cannot be called again."""
del self.funcs
del self.variables
del self.variable_values
del self.satisfied | [
"def",
"_release",
"(",
"self",
")",
":",
"del",
"self",
".",
"funcs",
"del",
"self",
".",
"variables",
"del",
"self",
".",
"variable_values",
"del",
"self",
".",
"satisfied"
] | 31.666667 | 0.010256 |
def get_cmap(self, arr=None, cmap=None, N=None):
"""Get the :class:`matplotlib.colors.Colormap` for plotting
Parameters
----------
arr: np.ndarray
The array to plot
cmap: str or matplotlib.colors.Colormap
The colormap to use. If None, the :attr:`value` of... | [
"def",
"get_cmap",
"(",
"self",
",",
"arr",
"=",
"None",
",",
"cmap",
"=",
"None",
",",
"N",
"=",
"None",
")",
":",
"N",
"=",
"N",
"or",
"None",
"if",
"cmap",
"is",
"None",
":",
"cmap",
"=",
"self",
".",
"value",
"if",
"N",
"is",
"None",
":",... | 35.096774 | 0.001789 |
def newCharRef(self, name):
"""Creation of a new character reference node. """
ret = libxml2mod.xmlNewCharRef(self._o, name)
if ret is None:raise treeError('xmlNewCharRef() failed')
__tmp = xmlNode(_obj=ret)
return __tmp | [
"def",
"newCharRef",
"(",
"self",
",",
"name",
")",
":",
"ret",
"=",
"libxml2mod",
".",
"xmlNewCharRef",
"(",
"self",
".",
"_o",
",",
"name",
")",
"if",
"ret",
"is",
"None",
":",
"raise",
"treeError",
"(",
"'xmlNewCharRef() failed'",
")",
"__tmp",
"=",
... | 42.5 | 0.015385 |
def word_texts(self):
"""The list of words representing ``words`` layer elements."""
if not self.is_tagged(WORDS):
self.tokenize_words()
return [word[TEXT] for word in self[WORDS]] | [
"def",
"word_texts",
"(",
"self",
")",
":",
"if",
"not",
"self",
".",
"is_tagged",
"(",
"WORDS",
")",
":",
"self",
".",
"tokenize_words",
"(",
")",
"return",
"[",
"word",
"[",
"TEXT",
"]",
"for",
"word",
"in",
"self",
"[",
"WORDS",
"]",
"]"
] | 42.4 | 0.009259 |
def binary_shader_for_rules(self, output_jar, jar, rules, jvm_options=None):
"""Yields an `Executor.Runner` that will perform shading of the binary `jar` when `run()`.
No default rules are applied; only the rules passed in as a parameter will be used.
:param unicode output_jar: The path to dump the shaded... | [
"def",
"binary_shader_for_rules",
"(",
"self",
",",
"output_jar",
",",
"jar",
",",
"rules",
",",
"jvm_options",
"=",
"None",
")",
":",
"with",
"self",
".",
"temporary_rules_file",
"(",
"rules",
")",
"as",
"rules_file",
":",
"logger",
".",
"debug",
"(",
"'R... | 60.894737 | 0.008511 |
def output_datacenter(gandi, datacenter, output_keys, justify=14):
""" Helper to output datacenter information."""
output_generic(gandi, datacenter, output_keys, justify)
if 'dc_name' in output_keys:
output_line(gandi, 'datacenter', datacenter['name'], justify)
if 'status' in output_keys:
... | [
"def",
"output_datacenter",
"(",
"gandi",
",",
"datacenter",
",",
"output_keys",
",",
"justify",
"=",
"14",
")",
":",
"output_generic",
"(",
"gandi",
",",
"datacenter",
",",
"output_keys",
",",
"justify",
")",
"if",
"'dc_name'",
"in",
"output_keys",
":",
"ou... | 36.166667 | 0.001122 |
def DEFINE_boolean(flag_name, default_value, docstring): # pylint: disable=invalid-name
"""Defines a flag of type 'boolean'.
Args:
flag_name: The name of the flag as a string.
default_value: The default value the flag should take as a boolean.
docstring: A helpful message explaining the... | [
"def",
"DEFINE_boolean",
"(",
"flag_name",
",",
"default_value",
",",
"docstring",
")",
":",
"# pylint: disable=invalid-name",
"# Register a custom function for 'bool' so --flag=True works.",
"def",
"str2bool",
"(",
"bool_str",
")",
":",
"\"\"\"Return a boolean value from a give ... | 35.111111 | 0.002053 |
def _get_prompt_cursor(self):
""" Convenience method that returns a cursor for the prompt position.
"""
cursor = self._control.textCursor()
cursor.setPosition(self._prompt_pos)
return cursor | [
"def",
"_get_prompt_cursor",
"(",
"self",
")",
":",
"cursor",
"=",
"self",
".",
"_control",
".",
"textCursor",
"(",
")",
"cursor",
".",
"setPosition",
"(",
"self",
".",
"_prompt_pos",
")",
"return",
"cursor"
] | 37.5 | 0.008696 |
def returner(ret):
'''
Send a slack message with the data through a webhook
:param ret: The Salt return
:return: The result of the post
'''
_options = _get_options(ret)
webhook = _options.get('webhook', None)
show_tasks = _options.get('show_tasks')
author_icon = _options.get('autho... | [
"def",
"returner",
"(",
"ret",
")",
":",
"_options",
"=",
"_get_options",
"(",
"ret",
")",
"webhook",
"=",
"_options",
".",
"get",
"(",
"'webhook'",
",",
"None",
")",
"show_tasks",
"=",
"_options",
".",
"get",
"(",
"'show_tasks'",
")",
"author_icon",
"="... | 25.703704 | 0.001389 |
def ec2_vpc_availabilityzones(self, lookup, default=None):
"""
Args:
lookup: the friendly name of a VPC to look up
default: the optional value to return if lookup failed; returns None if not set
Returns:
A comma-separated list of availability zones in use in the named VPC or default/None i... | [
"def",
"ec2_vpc_availabilityzones",
"(",
"self",
",",
"lookup",
",",
"default",
"=",
"None",
")",
":",
"vpc_id",
"=",
"self",
".",
"ec2_vpc_vpc_id",
"(",
"lookup",
")",
"if",
"vpc_id",
"is",
"None",
":",
"return",
"default",
"subnets",
"=",
"EFAwsResolver",
... | 39.636364 | 0.011198 |
def do_rebootInstance(self,args):
"""Restart specified instance"""
parser = CommandArgumentParser("rebootInstance")
parser.add_argument(dest='instance',help='instance index or name');
args = vars(parser.parse_args(args))
instanceId = args['instance']
try:
ind... | [
"def",
"do_rebootInstance",
"(",
"self",
",",
"args",
")",
":",
"parser",
"=",
"CommandArgumentParser",
"(",
"\"rebootInstance\"",
")",
"parser",
".",
"add_argument",
"(",
"dest",
"=",
"'instance'",
",",
"help",
"=",
"'instance index or name'",
")",
"args",
"=",... | 39.1875 | 0.009346 |
def get_interface_detail_output_interface_port_role(self, **kwargs):
"""Auto Generated Code
"""
config = ET.Element("config")
get_interface_detail = ET.Element("get_interface_detail")
config = get_interface_detail
output = ET.SubElement(get_interface_detail, "output")
... | [
"def",
"get_interface_detail_output_interface_port_role",
"(",
"self",
",",
"*",
"*",
"kwargs",
")",
":",
"config",
"=",
"ET",
".",
"Element",
"(",
"\"config\"",
")",
"get_interface_detail",
"=",
"ET",
".",
"Element",
"(",
"\"get_interface_detail\"",
")",
"config"... | 48.411765 | 0.002384 |
def render(self, name, value, attrs=None, multi=False, renderer=None):
"""
Django <= 1.10 variant.
"""
DJANGO_111_OR_UP = (VERSION[0] == 1 and VERSION[1] >= 11) or (
VERSION[0] >= 2
)
if DJANGO_111_OR_UP:
return super(DynamicRawIDWidget, self).rend... | [
"def",
"render",
"(",
"self",
",",
"name",
",",
"value",
",",
"attrs",
"=",
"None",
",",
"multi",
"=",
"False",
",",
"renderer",
"=",
"None",
")",
":",
"DJANGO_111_OR_UP",
"=",
"(",
"VERSION",
"[",
"0",
"]",
"==",
"1",
"and",
"VERSION",
"[",
"1",
... | 30.777778 | 0.001166 |
def get_unicodes(codepoint):
""" Return list of unicodes for <scanning-codepoints> """
result = re.sub('\s', '', codepoint.text)
return Extension.convert_to_list_of_unicodes(result) | [
"def",
"get_unicodes",
"(",
"codepoint",
")",
":",
"result",
"=",
"re",
".",
"sub",
"(",
"'\\s'",
",",
"''",
",",
"codepoint",
".",
"text",
")",
"return",
"Extension",
".",
"convert_to_list_of_unicodes",
"(",
"result",
")"
] | 50.5 | 0.014634 |
def get_mean_and_stddevs(self, sites, rup, dists, imt, stddev_types):
"""
See :meth:`superclass method
<.base.GroundShakingIntensityModel.get_mean_and_stddevs>`
for spec of input and result values.
"""
# extract dictionaries of coefficients specific to required
# ... | [
"def",
"get_mean_and_stddevs",
"(",
"self",
",",
"sites",
",",
"rup",
",",
"dists",
",",
"imt",
",",
"stddev_types",
")",
":",
"# extract dictionaries of coefficients specific to required",
"# intensity measure type and for PGA",
"C",
"=",
"self",
".",
"COEFFS",
"[",
... | 47.73913 | 0.001786 |
def _find_channel(connection, name, ctype, dtype, sample_rate, unique=False):
"""Internal method to find a single channel
Parameters
----------
connection : `nds2.connection`, optional
open NDS2 connection to use for query
name : `str`
the name of the channel to find
ctype : `... | [
"def",
"_find_channel",
"(",
"connection",
",",
"name",
",",
"ctype",
",",
"dtype",
",",
"sample_rate",
",",
"unique",
"=",
"False",
")",
":",
"# parse channel type from name,",
"# e.g. 'L1:GDS-CALIB_STRAIN,reduced' -> 'L1:GDS-CALIB_STRAIN', 'reduced'",
"name",
",",
"ctyp... | 28.929825 | 0.000587 |
def lookup(self, hostname):
"""
Return a dict (`SSHConfigDict`) of config options for a given hostname.
The host-matching rules of OpenSSH's ``ssh_config`` man page are used:
For each parameter, the first obtained value will be used. The
configuration files contain sections sep... | [
"def",
"lookup",
"(",
"self",
",",
"hostname",
")",
":",
"matches",
"=",
"[",
"config",
"for",
"config",
"in",
"self",
".",
"_config",
"if",
"self",
".",
"_allowed",
"(",
"config",
"[",
"\"host\"",
"]",
",",
"hostname",
")",
"]",
"ret",
"=",
"SSHConf... | 43.019231 | 0.000874 |
def pil_to_rgb(pil):
"""Convert the color from a PIL-compatible integer to RGB.
Parameters:
pil: a PIL compatible color representation (0xBBGGRR)
Returns:
The color as an (r, g, b) tuple in the range:
the range:
r: [0...1]
g: [0...1]
b: [0...1]
>>> '(%g, %g, %g)' % pil_to_rgb(0x0080ff)... | [
"def",
"pil_to_rgb",
"(",
"pil",
")",
":",
"r",
"=",
"0xff",
"&",
"pil",
"g",
"=",
"0xff",
"&",
"(",
"pil",
">>",
"8",
")",
"b",
"=",
"0xff",
"&",
"(",
"pil",
">>",
"16",
")",
"return",
"tuple",
"(",
"(",
"v",
"/",
"255.0",
"for",
"v",
"in"... | 22.1 | 0.013015 |
def handler(self, signum, frame): # pragma: no cover
'''Signal handler for this process'''
if signum in (signal.SIGTERM, signal.SIGINT, signal.SIGQUIT):
self.stop(signum)
os._exit(0) | [
"def",
"handler",
"(",
"self",
",",
"signum",
",",
"frame",
")",
":",
"# pragma: no cover",
"if",
"signum",
"in",
"(",
"signal",
".",
"SIGTERM",
",",
"signal",
".",
"SIGINT",
",",
"signal",
".",
"SIGQUIT",
")",
":",
"self",
".",
"stop",
"(",
"signum",
... | 43.8 | 0.008969 |
def get_feats(self, doc):
'''
Parameters
----------
doc, Spacy Docs
Returns
-------
Counter (unigram, bigram) -> count
'''
ngram_counter = Counter()
for sent in doc.sents:
ngrams = self.phrases[str(sent)]
for subphrases in self.phrases[1:]:
ngrams = subphrases[str(sent)]
for ngram in n... | [
"def",
"get_feats",
"(",
"self",
",",
"doc",
")",
":",
"ngram_counter",
"=",
"Counter",
"(",
")",
"for",
"sent",
"in",
"doc",
".",
"sents",
":",
"ngrams",
"=",
"self",
".",
"phrases",
"[",
"str",
"(",
"sent",
")",
"]",
"for",
"subphrases",
"in",
"s... | 20.111111 | 0.047493 |
def MessageReceived(self, m):
"""
Process a message.
Args:
m (neo.Network.Message):
"""
if m.Command == 'verack':
# only respond with a verack when we connect to another client, not when a client connected to us or
# we might end up in a verac... | [
"def",
"MessageReceived",
"(",
"self",
",",
"m",
")",
":",
"if",
"m",
".",
"Command",
"==",
"'verack'",
":",
"# only respond with a verack when we connect to another client, not when a client connected to us or",
"# we might end up in a verack loop",
"if",
"self",
".",
"incom... | 38.6 | 0.002166 |
def set_meta(target, keys, overwrite=False):
"""Write metadata keys to .md file.
TARGET can be a media file or an album directory. KEYS are key/value pairs.
Ex, to set the title of test.jpg to "My test image":
sigal set_meta test.jpg title "My test image"
"""
if not os.path.exists(target):
... | [
"def",
"set_meta",
"(",
"target",
",",
"keys",
",",
"overwrite",
"=",
"False",
")",
":",
"if",
"not",
"os",
".",
"path",
".",
"exists",
"(",
"target",
")",
":",
"sys",
".",
"stderr",
".",
"write",
"(",
"\"The target {} does not exist.\\n\"",
".",
"format... | 36.548387 | 0.00086 |
def color_scale_HSV(c: Color, scoef: float, vcoef: float) -> None:
"""Scale a color's saturation and value.
Does not return a new Color. ``c`` is modified inplace.
Args:
c (Union[Color, List[int]]): A Color instance, or an [r, g, b] list.
scoef (float): Saturation multiplier, from 0 to 1.... | [
"def",
"color_scale_HSV",
"(",
"c",
":",
"Color",
",",
"scoef",
":",
"float",
",",
"vcoef",
":",
"float",
")",
"->",
"None",
":",
"color_p",
"=",
"ffi",
".",
"new",
"(",
"\"TCOD_color_t*\"",
")",
"color_p",
".",
"r",
",",
"color_p",
".",
"g",
",",
... | 41.375 | 0.001477 |
def convert_tile(node, **kwargs):
"""Map MXNet's Tile operator attributes to onnx's Tile
operator and return the created node.
"""
name, input_nodes, attrs = get_inputs(node, kwargs)
reps_list = convert_string_to_list(attrs["reps"])
initializer = kwargs["initializer"]
reps_shape_np = np.ar... | [
"def",
"convert_tile",
"(",
"node",
",",
"*",
"*",
"kwargs",
")",
":",
"name",
",",
"input_nodes",
",",
"attrs",
"=",
"get_inputs",
"(",
"node",
",",
"kwargs",
")",
"reps_list",
"=",
"convert_string_to_list",
"(",
"attrs",
"[",
"\"reps\"",
"]",
")",
"ini... | 28.285714 | 0.001953 |
def run_experiments(experiments,
search_alg=None,
scheduler=None,
with_server=False,
server_port=TuneServer.DEFAULT_PORT,
verbose=2,
resume=False,
queue_trials=False,
... | [
"def",
"run_experiments",
"(",
"experiments",
",",
"search_alg",
"=",
"None",
",",
"scheduler",
"=",
"None",
",",
"with_server",
"=",
"False",
",",
"server_port",
"=",
"TuneServer",
".",
"DEFAULT_PORT",
",",
"verbose",
"=",
"2",
",",
"resume",
"=",
"False",
... | 33 | 0.000555 |
def _stub_obj(obj):
'''
Stub an object directly.
'''
# Annoying circular reference requires importing here. Would like to see
# this cleaned up. @AW
from .mock import Mock
# Return an existing stub
if isinstance(obj, Stub):
return obj
# If a Mock object, stub its __call__
... | [
"def",
"_stub_obj",
"(",
"obj",
")",
":",
"# Annoying circular reference requires importing here. Would like to see",
"# this cleaned up. @AW",
"from",
".",
"mock",
"import",
"Mock",
"# Return an existing stub",
"if",
"isinstance",
"(",
"obj",
",",
"Stub",
")",
":",
"retu... | 39 | 0.000238 |
def to_abivars(self):
"""Returns a dictionary with the abinit variables."""
abivars = dict(
gwcalctyp=self.gwcalctyp,
ecuteps=self.ecuteps,
ecutsigx=self.ecutsigx,
symsigma=self.symsigma,
gw_qprange=self.gw_qprange,
gwpara=self.gwpa... | [
"def",
"to_abivars",
"(",
"self",
")",
":",
"abivars",
"=",
"dict",
"(",
"gwcalctyp",
"=",
"self",
".",
"gwcalctyp",
",",
"ecuteps",
"=",
"self",
".",
"ecuteps",
",",
"ecutsigx",
"=",
"self",
".",
"ecutsigx",
",",
"symsigma",
"=",
"self",
".",
"symsigm... | 30.08 | 0.009021 |
def insertFromMimeData(self, source):
"""
Inserts the information from the inputed source.
:param source | <QMimeData>
"""
lines = projex.text.nativestring(source.text()).splitlines()
for i in range(1, len(lines)):
if not lines[i].startsw... | [
"def",
"insertFromMimeData",
"(",
"self",
",",
"source",
")",
":",
"lines",
"=",
"projex",
".",
"text",
".",
"nativestring",
"(",
"source",
".",
"text",
"(",
")",
")",
".",
"splitlines",
"(",
")",
"for",
"i",
"in",
"range",
"(",
"1",
",",
"len",
"(... | 32.933333 | 0.009843 |
def gen_rule_payload(pt_rule, results_per_call=None,
from_date=None, to_date=None, count_bucket=None,
tag=None,
stringify=True):
"""
Generates the dict or json payload for a PowerTrack rule.
Args:
pt_rule (str): The string version of a... | [
"def",
"gen_rule_payload",
"(",
"pt_rule",
",",
"results_per_call",
"=",
"None",
",",
"from_date",
"=",
"None",
",",
"to_date",
"=",
"None",
",",
"count_bucket",
"=",
"None",
",",
"tag",
"=",
"None",
",",
"stringify",
"=",
"True",
")",
":",
"pt_rule",
"=... | 41.754717 | 0.001325 |
def total_flux(F, A=None):
r"""Compute the total flux, or turnover flux, that is produced by
the flux sources and consumed by the flux sinks.
Parameters
----------
F : (M, M) ndarray
Matrix of flux values between pairs of states.
A : array_like (optional)
List of integer sta... | [
"def",
"total_flux",
"(",
"F",
",",
"A",
"=",
"None",
")",
":",
"if",
"issparse",
"(",
"F",
")",
":",
"return",
"sparse",
".",
"tpt",
".",
"total_flux",
"(",
"F",
",",
"A",
"=",
"A",
")",
"elif",
"isdense",
"(",
"F",
")",
":",
"return",
"dense"... | 28.633333 | 0.001126 |
def one_way(data, n):
""" One-way chi-square test of independence.
Takes a 1D array as input and compares activation at each voxel to
proportion expected under a uniform distribution throughout the array. Note
that if you're testing activation with this, make sure that only valid
voxels (e.g., in-ma... | [
"def",
"one_way",
"(",
"data",
",",
"n",
")",
":",
"term",
"=",
"data",
".",
"astype",
"(",
"'float64'",
")",
"no_term",
"=",
"n",
"-",
"term",
"t_exp",
"=",
"np",
".",
"mean",
"(",
"term",
",",
"0",
")",
"t_exp",
"=",
"np",
".",
"array",
"(",
... | 41.294118 | 0.001393 |
def to_polar(xyz):
"""Convert ``[x y z]`` into spherical coordinates ``(r, theta, phi)``.
``r`` - vector length
``theta`` - angle above (+) or below (-) the xy-plane
``phi`` - angle around the z-axis
The meaning and order of the three return values is designed to
match both ISO 31-11 and the t... | [
"def",
"to_polar",
"(",
"xyz",
")",
":",
"r",
"=",
"length_of",
"(",
"xyz",
")",
"x",
",",
"y",
",",
"z",
"=",
"xyz",
"theta",
"=",
"arcsin",
"(",
"z",
"/",
"r",
")",
"phi",
"=",
"arctan2",
"(",
"y",
",",
"x",
")",
"%",
"tau",
"return",
"r"... | 35.578947 | 0.001441 |
def get_addresses(self, account_id, **params):
"""https://developers.coinbase.com/api/v2#list-addresses"""
response = self._get('v2', 'accounts', account_id, 'addresses', params=params)
return self._make_api_object(response, Address) | [
"def",
"get_addresses",
"(",
"self",
",",
"account_id",
",",
"*",
"*",
"params",
")",
":",
"response",
"=",
"self",
".",
"_get",
"(",
"'v2'",
",",
"'accounts'",
",",
"account_id",
",",
"'addresses'",
",",
"params",
"=",
"params",
")",
"return",
"self",
... | 63.5 | 0.011673 |
def SA_guppy_head(D, a):
r'''Calculates the surface area of a guppy head according to [1]_.
Some work was involved in combining formulas for the ellipse of the head,
and the conic section on the sides.
.. math::
SA = \frac{\pi D}{4}\sqrt{D^2 + a^2} + \frac{\pi D}{2}a
Parameters
------... | [
"def",
"SA_guppy_head",
"(",
"D",
",",
"a",
")",
":",
"return",
"pi",
"*",
"D",
"/",
"4",
"*",
"(",
"a",
"**",
"2",
"+",
"D",
"**",
"2",
")",
"**",
"0.5",
"+",
"pi",
"*",
"D",
"/",
"2",
"*",
"a"
] | 25.533333 | 0.001258 |
def encode(data):
"""encode the plantuml data which may be compresses in the proper
encoding for the plantuml server
"""
res = ""
for i in range(0,len(data), 3):
if (i+2==len(data)):
res += _encode3bytes(ord(data[i]), ord(data[i+1]), 0)
elif (i+1==len(data)):
... | [
"def",
"encode",
"(",
"data",
")",
":",
"res",
"=",
"\"\"",
"for",
"i",
"in",
"range",
"(",
"0",
",",
"len",
"(",
"data",
")",
",",
"3",
")",
":",
"if",
"(",
"i",
"+",
"2",
"==",
"len",
"(",
"data",
")",
")",
":",
"res",
"+=",
"_encode3byte... | 35.076923 | 0.008547 |
def backwards(self, orm):
"Write your backwards methods here."
for category in Category.objects.all():
category.slug = ''
category.save() | [
"def",
"backwards",
"(",
"self",
",",
"orm",
")",
":",
"for",
"category",
"in",
"Category",
".",
"objects",
".",
"all",
"(",
")",
":",
"category",
".",
"slug",
"=",
"''",
"category",
".",
"save",
"(",
")"
] | 34.6 | 0.011299 |
def ValidateDate(date, column_name=None, problems=None):
"""
Validates a non-required date string value using IsValidDate():
- if invalid adds InvalidValue error (if problems accumulator is provided)
- an empty date string is regarded as valid! Otherwise we might end up
with many duplicate errors beca... | [
"def",
"ValidateDate",
"(",
"date",
",",
"column_name",
"=",
"None",
",",
"problems",
"=",
"None",
")",
":",
"if",
"IsEmpty",
"(",
"date",
")",
"or",
"IsValidDate",
"(",
"date",
")",
":",
"return",
"True",
"else",
":",
"if",
"problems",
":",
"problems"... | 37.923077 | 0.009901 |
def setExpanded(self, state):
"""
Sets whether or not this item is in an expanded state.
:param state | <bool>
"""
if (state and self.testFlag(self.ItemIsExpandable)) or \
(not state and self.testFlag(self.ItemIsCollapsible)):
super(XT... | [
"def",
"setExpanded",
"(",
"self",
",",
"state",
")",
":",
"if",
"(",
"state",
"and",
"self",
".",
"testFlag",
"(",
"self",
".",
"ItemIsExpandable",
")",
")",
"or",
"(",
"not",
"state",
"and",
"self",
".",
"testFlag",
"(",
"self",
".",
"ItemIsCollapsib... | 39 | 0.008357 |
def tiles_are_equal(tile_data_1, tile_data_2, fmt):
"""
Returns True if the tile data is equal in tile_data_1 and tile_data_2. For
most formats, this is a simple byte-wise equality check. For zipped
metatiles, we need to check the contents, as the zip format includes
metadata such as timestamps and ... | [
"def",
"tiles_are_equal",
"(",
"tile_data_1",
",",
"tile_data_2",
",",
"fmt",
")",
":",
"if",
"fmt",
"and",
"fmt",
"==",
"zip_format",
":",
"return",
"metatiles_are_equal",
"(",
"tile_data_1",
",",
"tile_data_2",
")",
"else",
":",
"return",
"tile_data_1",
"=="... | 38.076923 | 0.001972 |
def _prelu(attrs, inputs, proto_obj):
"""PRelu function"""
new_attrs = translation_utils._add_extra_attributes(attrs, {'act_type': 'prelu'})
return 'LeakyReLU', new_attrs, inputs | [
"def",
"_prelu",
"(",
"attrs",
",",
"inputs",
",",
"proto_obj",
")",
":",
"new_attrs",
"=",
"translation_utils",
".",
"_add_extra_attributes",
"(",
"attrs",
",",
"{",
"'act_type'",
":",
"'prelu'",
"}",
")",
"return",
"'LeakyReLU'",
",",
"new_attrs",
",",
"in... | 46.75 | 0.010526 |
def dict_find_other_sameval_keys(dict_, key):
"""
Example:
>>> # DISABLE_DOCTEST
>>> from utool.util_dict import * # NOQA
>>> dict_ = {'default': 1, 'hierarchical': 5, 'linear': 0, 'kdtree': 1,
... 'composite': 3, 'autotuned': 255, 'saved': 254, 'kmeans': 2,
...... | [
"def",
"dict_find_other_sameval_keys",
"(",
"dict_",
",",
"key",
")",
":",
"value",
"=",
"dict_",
"[",
"key",
"]",
"found_dict",
"=",
"dict_find_keys",
"(",
"dict_",
",",
"[",
"value",
"]",
")",
"other_keys",
"=",
"found_dict",
"[",
"value",
"]",
"other_ke... | 37 | 0.001647 |
def _key(self, additional_key: Any=None) -> str:
"""Construct a hashable key from this object's state.
Parameters
----------
additional_key :
Any additional information used to seed random number generation.
Returns
-------
str
A key to s... | [
"def",
"_key",
"(",
"self",
",",
"additional_key",
":",
"Any",
"=",
"None",
")",
"->",
"str",
":",
"return",
"'_'",
".",
"join",
"(",
"[",
"self",
".",
"key",
",",
"str",
"(",
"self",
".",
"clock",
"(",
")",
")",
",",
"str",
"(",
"additional_key"... | 31.428571 | 0.011038 |
def check_database_connected(app_configs, **kwargs):
"""
A Django check to see if connecting to the configured default
database backend succeeds.
"""
errors = []
try:
connection.ensure_connection()
except OperationalError as e:
msg = 'Could not connect to database: {!s}'.for... | [
"def",
"check_database_connected",
"(",
"app_configs",
",",
"*",
"*",
"kwargs",
")",
":",
"errors",
"=",
"[",
"]",
"try",
":",
"connection",
".",
"ensure_connection",
"(",
")",
"except",
"OperationalError",
"as",
"e",
":",
"msg",
"=",
"'Could not connect to da... | 36.956522 | 0.001147 |
def replycomposite(self, rtypes, nodes):
"""
Construct a I{composite} reply. This method is called when it has been
detected that the reply has multiple root nodes.
@param rtypes: A list of known return I{types}.
@type rtypes: [L{suds.xsd.sxbase.SchemaObject},...]
@param... | [
"def",
"replycomposite",
"(",
"self",
",",
"rtypes",
",",
"nodes",
")",
":",
"dictionary",
"=",
"{",
"}",
"for",
"rt",
"in",
"rtypes",
":",
"dictionary",
"[",
"rt",
".",
"name",
"]",
"=",
"rt",
"unmarshaller",
"=",
"self",
".",
"unmarshaller",
"(",
"... | 39.05 | 0.001249 |
def ObtenerTagXml(self, *tags):
"Busca en el Xml analizado y devuelve el tag solicitado"
# convierto el xml a un objeto
try:
if self.xml:
xml = self.xml
# por cada tag, lo busco segun su nombre o posición
for tag in tags:
... | [
"def",
"ObtenerTagXml",
"(",
"self",
",",
"*",
"tags",
")",
":",
"# convierto el xml a un objeto",
"try",
":",
"if",
"self",
".",
"xml",
":",
"xml",
"=",
"self",
".",
"xml",
"# por cada tag, lo busco segun su nombre o posición",
"for",
"tag",
"in",
"tags",
":",
... | 44.769231 | 0.008418 |
def shutdown_kernel(self):
"""Shutdown the kernel of the client."""
kernel_id = self.get_kernel_id()
if kernel_id:
delete_url = self.add_token(url_path_join(self.server_url,
'api/kernels/',
... | [
"def",
"shutdown_kernel",
"(",
"self",
")",
":",
"kernel_id",
"=",
"self",
".",
"get_kernel_id",
"(",
")",
"if",
"kernel_id",
":",
"delete_url",
"=",
"self",
".",
"add_token",
"(",
"url_path_join",
"(",
"self",
".",
"server_url",
",",
"'api/kernels/'",
",",
... | 44.611111 | 0.002439 |
def run_example(self, source):
"""Run commands by executing the given code, returning the lines
of input and output. The code should be a series of the
following functions:
* :meth:`invoke`: Invoke a command, adding env vars, input,
and output to the output.
* ``... | [
"def",
"run_example",
"(",
"self",
",",
"source",
")",
":",
"code",
"=",
"compile",
"(",
"source",
",",
"\"<docs>\"",
",",
"\"exec\"",
")",
"buffer",
"=",
"[",
"]",
"invoke",
"=",
"partial",
"(",
"self",
".",
"invoke",
",",
"_output_lines",
"=",
"buffe... | 33.678571 | 0.002062 |
def folderitem(self, obj, item, index):
"""Service triggered each time an item is iterated in folderitems.
The use of this service prevents the extra-loops in child objects.
:obj: the instance of the class to be foldered
:item: dict containing the properties of the object to be used by... | [
"def",
"folderitem",
"(",
"self",
",",
"obj",
",",
"item",
",",
"index",
")",
":",
"title",
"=",
"obj",
".",
"Title",
"(",
")",
"description",
"=",
"obj",
".",
"Description",
"(",
")",
"url",
"=",
"obj",
".",
"absolute_url",
"(",
")",
"item",
"[",
... | 35.067797 | 0.00094 |
def constant_q(sr, fmin=None, n_bins=84, bins_per_octave=12, tuning=0.0,
window='hann', filter_scale=1, pad_fft=True, norm=1,
dtype=np.complex64, **kwargs):
r'''Construct a constant-Q basis.
This uses the filter bank described by [1]_.
.. [1] McVicar, Matthew.
"A ... | [
"def",
"constant_q",
"(",
"sr",
",",
"fmin",
"=",
"None",
",",
"n_bins",
"=",
"84",
",",
"bins_per_octave",
"=",
"12",
",",
"tuning",
"=",
"0.0",
",",
"window",
"=",
"'hann'",
",",
"filter_scale",
"=",
"1",
",",
"pad_fft",
"=",
"True",
",",
"norm",
... | 31.69281 | 0.0004 |
def simple_transpile_modname_source_target(
self, spec, modname, source, target):
"""
The original simple transpile method called by compile_transpile
on each target.
"""
opener = self.opener
bd_target = self._generate_transpile_target(spec, target)
l... | [
"def",
"simple_transpile_modname_source_target",
"(",
"self",
",",
"spec",
",",
"modname",
",",
"source",
",",
"target",
")",
":",
"opener",
"=",
"self",
".",
"opener",
"bd_target",
"=",
"self",
".",
"_generate_transpile_target",
"(",
"spec",
",",
"target",
")... | 42.407407 | 0.001708 |
def bed(args):
"""
%prog bed del.txt
Convert `del.txt` to BED format. DELLY manual here:
<http://www.embl.de/~rausch/delly.html>
Deletion:
chr, start, end, size, #supporting_pairs, avg._mapping_quality, deletion_id
chr1, 10180, 10509, 329, 75, 15.8667, Deletion_Sample_00000000
"""
... | [
"def",
"bed",
"(",
"args",
")",
":",
"p",
"=",
"OptionParser",
"(",
"bed",
".",
"__doc__",
")",
"opts",
",",
"args",
"=",
"p",
".",
"parse_args",
"(",
"args",
")",
"if",
"len",
"(",
"args",
")",
"!=",
"1",
":",
"sys",
".",
"exit",
"(",
"not",
... | 24.7 | 0.001949 |
def cut_cuboid(
self,
a=20,
b=None,
c=None,
origin=None,
outside_sliced=True,
preserve_bonds=False):
"""Cut a cuboid specified by edge and radius.
Args:
a (float): Value of the a edge.
b (float):... | [
"def",
"cut_cuboid",
"(",
"self",
",",
"a",
"=",
"20",
",",
"b",
"=",
"None",
",",
"c",
"=",
"None",
",",
"origin",
"=",
"None",
",",
"outside_sliced",
"=",
"True",
",",
"preserve_bonds",
"=",
"False",
")",
":",
"if",
"origin",
"is",
"None",
":",
... | 34.209302 | 0.001322 |
def network_info(host=None,
admin_username=None,
admin_password=None,
module=None):
'''
Return Network Configuration
CLI Example:
.. code-block:: bash
salt dell dracr.network_info
'''
inv = inventory(host=host, admin_username=admin_u... | [
"def",
"network_info",
"(",
"host",
"=",
"None",
",",
"admin_username",
"=",
"None",
",",
"admin_password",
"=",
"None",
",",
"module",
"=",
"None",
")",
":",
"inv",
"=",
"inventory",
"(",
"host",
"=",
"host",
",",
"admin_username",
"=",
"admin_username",
... | 28.948718 | 0.000857 |
def detect_view_name(self, environ: Dict[str, Any]) -> str:
""" detect view name from environ """
script_name = environ.get('SCRIPT_NAME', '')
path_info = environ.get('PATH_INFO', '')
match = self.urlmapper.lookup(path_info)
if match is None:
return None
spli... | [
"def",
"detect_view_name",
"(",
"self",
",",
"environ",
":",
"Dict",
"[",
"str",
",",
"Any",
"]",
")",
"->",
"str",
":",
"script_name",
"=",
"environ",
".",
"get",
"(",
"'SCRIPT_NAME'",
",",
"''",
")",
"path_info",
"=",
"environ",
".",
"get",
"(",
"'... | 41.708333 | 0.001953 |
def close(self):
''' Close the network connection and perform any other required cleanup
Note:
Auto closed when using goose as a context manager or when garbage collected '''
if self.fetcher is not None:
self.shutdown_network()
self.finalizer.atexit = Fal... | [
"def",
"close",
"(",
"self",
")",
":",
"if",
"self",
".",
"fetcher",
"is",
"not",
"None",
":",
"self",
".",
"shutdown_network",
"(",
")",
"self",
".",
"finalizer",
".",
"atexit",
"=",
"False"
] | 39.375 | 0.009317 |
def merge(self, b, a=DEFAULT):
"""Merges b into a recursively, if a is not given: merges into self.
also merges lists and:
* merge({a:a},{a:b}) = {a:[a,b]}
* merge({a:[a]},{a:b}) = {a:[a,b]}
* merge({a:a},{a:[b]}) = {a:[a,b]}
* merge({a:[a]},{a:[b]}) = {a... | [
"def",
"merge",
"(",
"self",
",",
"b",
",",
"a",
"=",
"DEFAULT",
")",
":",
"if",
"a",
"is",
"DEFAULT",
":",
"a",
"=",
"self",
"for",
"key",
"in",
"b",
":",
"if",
"key",
"in",
"a",
":",
"if",
"isinstance",
"(",
"a",
"[",
"key",
"]",
",",
"di... | 40.962963 | 0.001767 |
def run(input=sys.stdin, output=sys.stdout):
r"""CouchDB view function handler implementation for Python.
:param input: the readable file-like object to read input from
:param output: the writable file-like object to write output to
"""
functions = []
environments = dict()
def _writejson(o... | [
"def",
"run",
"(",
"input",
"=",
"sys",
".",
"stdin",
",",
"output",
"=",
"sys",
".",
"stdout",
")",
":",
"functions",
"=",
"[",
"]",
"environments",
"=",
"dict",
"(",
")",
"def",
"_writejson",
"(",
"obj",
")",
":",
"obj",
"=",
"json",
".",
"enco... | 31.405941 | 0.000306 |
def chhome(name, home, persist=False):
'''
Set a new home directory for an existing user
name
Username to modify
home
New home directory to set
persist : False
Set to ``True`` to prevent configuration files in the new home
directory from being overwritten by the fi... | [
"def",
"chhome",
"(",
"name",
",",
"home",
",",
"persist",
"=",
"False",
")",
":",
"pre_info",
"=",
"info",
"(",
"name",
")",
"if",
"not",
"pre_info",
":",
"raise",
"CommandExecutionError",
"(",
"'User \\'{0}\\' does not exist'",
".",
"format",
"(",
"name",
... | 24.205882 | 0.001168 |
def save_objective_bank(self, objective_bank_form, *args, **kwargs):
"""Pass through to provider ObjectiveBankAdminSession.update_objective_bank"""
# Implemented from kitosid template for -
# osid.resource.BinAdminSession.update_bin
if objective_bank_form.is_for_update():
ret... | [
"def",
"save_objective_bank",
"(",
"self",
",",
"objective_bank_form",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"# Implemented from kitosid template for -",
"# osid.resource.BinAdminSession.update_bin",
"if",
"objective_bank_form",
".",
"is_for_update",
"(",
"... | 59.875 | 0.010288 |
def _move(self, new_path):
"""
Moves the collection to a different database path
NOTE: this function is intended for command prompt use only.
WARNING: if execution is interrupted halfway through, the collection will
be split into multiple pieces. Furthermore, t... | [
"def",
"_move",
"(",
"self",
",",
"new_path",
")",
":",
"for",
"elt",
"in",
"self",
":",
"DatabaseObject",
".",
"create",
"(",
"elt",
",",
"path",
"=",
"new_path",
")",
"for",
"elt",
"in",
"self",
":",
"elt",
".",
"_collection",
".",
"remove",
"(",
... | 39.722222 | 0.009563 |
def remove(self, name=None, setn=None):
"""
Remove filter.
Parameters
----------
name : str
name of the filter to remove
setn : int or True
int: number of set to remove
True: remove all filters in set that 'name' belongs to
Re... | [
"def",
"remove",
"(",
"self",
",",
"name",
"=",
"None",
",",
"setn",
"=",
"None",
")",
":",
"if",
"isinstance",
"(",
"name",
",",
"int",
")",
":",
"name",
"=",
"self",
".",
"index",
"[",
"name",
"]",
"if",
"setn",
"is",
"not",
"None",
":",
"nam... | 26.833333 | 0.001712 |
def print_stack(pid, include_greenlet=False, debugger=None, verbose=False):
"""Executes a file in a running Python process."""
# TextIOWrapper of Python 3 is so strange.
sys_stdout = getattr(sys.stdout, 'buffer', sys.stdout)
sys_stderr = getattr(sys.stderr, 'buffer', sys.stderr)
make_args = make_gd... | [
"def",
"print_stack",
"(",
"pid",
",",
"include_greenlet",
"=",
"False",
",",
"debugger",
"=",
"None",
",",
"verbose",
"=",
"False",
")",
":",
"# TextIOWrapper of Python 3 is so strange.",
"sys_stdout",
"=",
"getattr",
"(",
"sys",
".",
"stdout",
",",
"'buffer'",... | 36.575 | 0.000666 |
def import_action(self, request, *args, **kwargs):
"""
Perform a dry_run of the import to make sure the import will not
result in errors. If there where no error, save the user
uploaded file to a local temp file that will be used by
'process_import' for the actual import.
... | [
"def",
"import_action",
"(",
"self",
",",
"request",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"if",
"not",
"self",
".",
"has_import_permission",
"(",
"request",
")",
":",
"raise",
"PermissionDenied",
"context",
"=",
"self",
".",
"get_import_con... | 47.961538 | 0.002095 |
def resolve_data_objects(objects, project=None, folder=None, batchsize=1000):
"""
:param objects: Data object specifications, each with fields "name"
(required), "folder", and "project"
:type objects: list of dictionaries
:param project: ID of project context; a data object's project... | [
"def",
"resolve_data_objects",
"(",
"objects",
",",
"project",
"=",
"None",
",",
"folder",
"=",
"None",
",",
"batchsize",
"=",
"1000",
")",
":",
"if",
"not",
"isinstance",
"(",
"batchsize",
",",
"int",
")",
"or",
"batchsize",
"<=",
"0",
"or",
"batchsize"... | 47.025641 | 0.001068 |
def _check_for_default_values(fname, arg_val_dict, compat_args):
"""
Check that the keys in `arg_val_dict` are mapped to their
default values as specified in `compat_args`.
Note that this function is to be called only when it has been
checked that arg_val_dict.keys() is a subset of compat_args
... | [
"def",
"_check_for_default_values",
"(",
"fname",
",",
"arg_val_dict",
",",
"compat_args",
")",
":",
"for",
"key",
"in",
"arg_val_dict",
":",
"# try checking equality directly with '=' operator,",
"# as comparison may have been overridden for the left",
"# hand object",
"try",
... | 36.210526 | 0.000708 |
def pair(seeders, delegator_factory, *args, **kwargs):
"""
The basic pair producer.
:return:
a (seeder, delegator_factory(\*args, \*\*kwargs)) tuple.
:param seeders:
If it is a seeder function or a list of one seeder function, it is returned
as the final seeder. If it is a list... | [
"def",
"pair",
"(",
"seeders",
",",
"delegator_factory",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"return",
"(",
"chain",
"(",
"*",
"seeders",
")",
"if",
"len",
"(",
"seeders",
")",
">",
"1",
"else",
"seeders",
"[",
"0",
"]",
",",
"de... | 38.071429 | 0.010989 |
def p_action(p):
"""
action : CLIENT_KWD KEY DOT KEY LPAREN args RPAREN
action : SERVER_KWD KEY DOT KEY LPAREN args RPAREN
action : CLIENT_KWD KEY DOT KEY LPAREN args RPAREN IF_KWD REGEX_MATCH_INCOMING_KWD LPAREN p_string_arg RPAREN
action : SERVER_KWD KEY DOT KEY LPAREN args RPAREN IF_KWD REGEX_MAT... | [
"def",
"p_action",
"(",
"p",
")",
":",
"if",
"len",
"(",
"p",
")",
"==",
"8",
":",
"p",
"[",
"0",
"]",
"=",
"[",
"p",
"[",
"1",
"]",
",",
"p",
"[",
"2",
"]",
",",
"p",
"[",
"4",
"]",
",",
"p",
"[",
"6",
"]",
",",
"None",
"]",
"elif"... | 44.727273 | 0.00996 |
def _next_file_gen(self, root):
"""Generator for next file element in the document.
Args:
root: root element of the XML tree.
Yields:
GCSFileStat for the next file.
"""
for e in root.getiterator(common._T_CONTENTS):
st_ctime, size, etag, key = None, None, None, None
for chi... | [
"def",
"_next_file_gen",
"(",
"self",
",",
"root",
")",
":",
"for",
"e",
"in",
"root",
".",
"getiterator",
"(",
"common",
".",
"_T_CONTENTS",
")",
":",
"st_ctime",
",",
"size",
",",
"etag",
",",
"key",
"=",
"None",
",",
"None",
",",
"None",
",",
"N... | 32.25 | 0.011292 |
def add_config(self, config_id, config_data):
"""Add a configuration variable to the MIB block"""
if config_id < 0 or config_id >= 2**16:
raise ArgumentError("Config ID in mib block is not a non-negative 2-byte number",
config_data=config_id, data=config_data... | [
"def",
"add_config",
"(",
"self",
",",
"config_id",
",",
"config_data",
")",
":",
"if",
"config_id",
"<",
"0",
"or",
"config_id",
">=",
"2",
"**",
"16",
":",
"raise",
"ArgumentError",
"(",
"\"Config ID in mib block is not a non-negative 2-byte number\"",
",",
"con... | 48.833333 | 0.008375 |
def fire_event(self, data, tag, timeout=1000):
'''
Send a single event into the publisher with payload dict "data" and
event identifier "tag"
The default is 1000 ms
'''
if not six.text_type(tag): # no empty tags allowed
raise ValueError('Empty tag.')
... | [
"def",
"fire_event",
"(",
"self",
",",
"data",
",",
"tag",
",",
"timeout",
"=",
"1000",
")",
":",
"if",
"not",
"six",
".",
"text_type",
"(",
"tag",
")",
":",
"# no empty tags allowed",
"raise",
"ValueError",
"(",
"'Empty tag.'",
")",
"if",
"not",
"isinst... | 35.824561 | 0.000953 |
def get_hoisted(dct, child_name):
"""Pulls all of a child's keys up to the parent, with the names unchanged."""
child = dct[child_name]
del dct[child_name]
dct.update(child)
return dct | [
"def",
"get_hoisted",
"(",
"dct",
",",
"child_name",
")",
":",
"child",
"=",
"dct",
"[",
"child_name",
"]",
"del",
"dct",
"[",
"child_name",
"]",
"dct",
".",
"update",
"(",
"child",
")",
"return",
"dct"
] | 31.5 | 0.030928 |
def main():
'''
Parse command line options and launch the prebuilder.
'''
parser = optparse.OptionParser(usage="%prog [options] <model_path> [another_model_path..]",
version=xtuml.version.complete_string,
formatter=optparse.TitledHelp... | [
"def",
"main",
"(",
")",
":",
"parser",
"=",
"optparse",
".",
"OptionParser",
"(",
"usage",
"=",
"\"%prog [options] <model_path> [another_model_path..]\"",
",",
"version",
"=",
"xtuml",
".",
"version",
".",
"complete_string",
",",
"formatter",
"=",
"optparse",
"."... | 36.857143 | 0.009819 |
def _draw_rect(self, rect, painter):
"""
Draw the background rectangle using the current style primitive color.
:param rect: The fold zone rect to draw
:param painter: The widget's painter.
"""
c = self.editor.sideareas_color
grad = QLinearGradient(rect.topLeft(... | [
"def",
"_draw_rect",
"(",
"self",
",",
"rect",
",",
"painter",
")",
":",
"c",
"=",
"self",
".",
"editor",
".",
"sideareas_color",
"grad",
"=",
"QLinearGradient",
"(",
"rect",
".",
"topLeft",
"(",
")",
",",
"rect",
".",
"topRight",
"(",
")",
")",
"if"... | 37.783784 | 0.002092 |
def tx(self, *args, **kwargs):
""" Executes a raw tx string, or get a new TX object to work with.
Passing a raw string or list of strings will immedately transact
and return the API response as a dict.
>>> resp = tx('{:db/id #db/id[:db.part/user] :person/name "Bob"}')
{db-before: db-after: tempids... | [
"def",
"tx",
"(",
"self",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"if",
"0",
"==",
"len",
"(",
"args",
")",
":",
"return",
"TX",
"(",
"self",
")",
"ops",
"=",
"[",
"]",
"for",
"op",
"in",
"args",
":",
"if",
"isinstance",
"(",
"... | 32.608696 | 0.008414 |
def pop(self, key):
"""Get and remove an element by key name"""
arr = dict.pop(self, key).copy()
self.remover(key)
return arr | [
"def",
"pop",
"(",
"self",
",",
"key",
")",
":",
"arr",
"=",
"dict",
".",
"pop",
"(",
"self",
",",
"key",
")",
".",
"copy",
"(",
")",
"self",
".",
"remover",
"(",
"key",
")",
"return",
"arr"
] | 30.6 | 0.012739 |
def run_spider(spider_cls, **kwargs):
"""Runs a spider and returns the scraped items (by default).
Parameters
----------
spider_cls : scrapy.Spider
A spider class to run.
capture_items : bool (default: True)
If enabled, the scraped items are captured and returned.
return_crawler... | [
"def",
"run_spider",
"(",
"spider_cls",
",",
"*",
"*",
"kwargs",
")",
":",
"timeout",
"=",
"kwargs",
".",
"pop",
"(",
"'timeout'",
",",
"DEFAULT_TIMEOUT",
")",
"return",
"wait_for",
"(",
"timeout",
",",
"_run_spider_in_reactor",
",",
"spider_cls",
",",
"*",
... | 32.166667 | 0.001006 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.