text stringlengths 75 104k | code_tokens list | avg_line_len float64 7.91 980 | score float64 0 0.18 |
|---|---|---|---|
def predictions(self, stpid="", rt="", vid="", maxpredictions=""):
"""
Retrieve predictions for 1+ stops or 1+ vehicles.
Arguments:
`stpid`: unique ID number for bus stop (single or comma-seperated list or iterable)
or
`vid`: vehicle ID number (single... | [
"def",
"predictions",
"(",
"self",
",",
"stpid",
"=",
"\"\"",
",",
"rt",
"=",
"\"\"",
",",
"vid",
"=",
"\"\"",
",",
"maxpredictions",
"=",
"\"\"",
")",
":",
"if",
"(",
"stpid",
"and",
"vid",
")",
"or",
"(",
"rt",
"and",
"vid",
")",
":",
"raise",
... | 42.928571 | 0.009219 |
def findvalue(array, value, compare = lambda x, y: x == y):
"A function that uses the compare function to return a value from the list."
try:
return next(x for x in array if compare(x, value))
except StopIteration:
raise ValueError('%r not in array'%value) | [
"def",
"findvalue",
"(",
"array",
",",
"value",
",",
"compare",
"=",
"lambda",
"x",
",",
"y",
":",
"x",
"==",
"y",
")",
":",
"try",
":",
"return",
"next",
"(",
"x",
"for",
"x",
"in",
"array",
"if",
"compare",
"(",
"x",
",",
"value",
")",
")",
... | 46.5 | 0.017606 |
def get_body(message):
"""
Extracts body text from an mbox message.
:param message: Mbox message
:return: String
"""
try:
sm = str(message)
body_start = sm.find('iamunique', sm.find('iamunique')+1)
body_start = sm.find('Content-Transfer-Encoding', body_start+1)
bo... | [
"def",
"get_body",
"(",
"message",
")",
":",
"try",
":",
"sm",
"=",
"str",
"(",
"message",
")",
"body_start",
"=",
"sm",
".",
"find",
"(",
"'iamunique'",
",",
"sm",
".",
"find",
"(",
"'iamunique'",
")",
"+",
"1",
")",
"body_start",
"=",
"sm",
".",
... | 32.2 | 0.001723 |
def insert(self, context):
"""
Create resource.
:param resort.engine.execution.Context context:
Current execution context.
"""
status_code, msg = self.__endpoint.post(
"/resources/connector-resource",
data={
"id": self.__name,
"poolname": self.__pool_name
}
)
self.__available... | [
"def",
"insert",
"(",
"self",
",",
"context",
")",
":",
"status_code",
",",
"msg",
"=",
"self",
".",
"__endpoint",
".",
"post",
"(",
"\"/resources/connector-resource\"",
",",
"data",
"=",
"{",
"\"id\"",
":",
"self",
".",
"__name",
",",
"\"poolname\"",
":",... | 18.294118 | 0.067278 |
def maximum_vline_bundle(self, x0, y0, y1):
"""Compute a maximum set of vertical lines in the unit cells ``(x0,y)``
for :math:`y0 \leq y \leq y1`.
INPUTS:
y0,x0,x1: int
OUTPUT:
list of lists of qubits
"""
y_range = range(y1, y0 - 1, -1) if y0 < ... | [
"def",
"maximum_vline_bundle",
"(",
"self",
",",
"x0",
",",
"y0",
",",
"y1",
")",
":",
"y_range",
"=",
"range",
"(",
"y1",
",",
"y0",
"-",
"1",
",",
"-",
"1",
")",
"if",
"y0",
"<",
"y1",
"else",
"range",
"(",
"y1",
",",
"y0",
"+",
"1",
")",
... | 33.142857 | 0.008386 |
def get_products_metadata_path(year, month, day):
""" Get paths to multiple products metadata """
products = {}
path = 'products/{0}/{1}/{2}/'.format(year, month, day)
for key in bucket.objects.filter(Prefix=path):
product_path = key.key.replace(path, '').split('/')
name = product_path[... | [
"def",
"get_products_metadata_path",
"(",
"year",
",",
"month",
",",
"day",
")",
":",
"products",
"=",
"{",
"}",
"path",
"=",
"'products/{0}/{1}/{2}/'",
".",
"format",
"(",
"year",
",",
"month",
",",
"day",
")",
"for",
"key",
"in",
"bucket",
".",
"object... | 33.777778 | 0.0016 |
def get_entity(ent_type, **kwargs):
'''
Attempt to query Keystone for more information about an entity
'''
try:
func = 'keystoneng.{}_get'.format(ent_type)
ent = __salt__[func](**kwargs)
except OpenStackCloudException as e:
# NOTE(SamYaple): If this error was something other ... | [
"def",
"get_entity",
"(",
"ent_type",
",",
"*",
"*",
"kwargs",
")",
":",
"try",
":",
"func",
"=",
"'keystoneng.{}_get'",
".",
"format",
"(",
"ent_type",
")",
"ent",
"=",
"__salt__",
"[",
"func",
"]",
"(",
"*",
"*",
"kwargs",
")",
"except",
"OpenStackCl... | 39.6 | 0.001233 |
def _load_entries(self):
"""Check for availability of lemmatizer for French."""
rel_path = os.path.join('~','cltk_data',
'french',
'text','french_data_cltk'
,'entries.py')
path = os.path.expanduser(r... | [
"def",
"_load_entries",
"(",
"self",
")",
":",
"rel_path",
"=",
"os",
".",
"path",
".",
"join",
"(",
"'~'",
",",
"'cltk_data'",
",",
"'french'",
",",
"'text'",
",",
"'french_data_cltk'",
",",
"'entries.py'",
")",
"path",
"=",
"os",
".",
"path",
".",
"e... | 42 | 0.012545 |
def get_vndmat_attr(d,keypath,attr,**kwargs):
'''
get_vndmat_attr(d,['x'],'lsib_path',path2keypath=True)
get_vndmat_attr(d,['t'],'lsib_path',path2keypath=True)
get_vndmat_attr(d,['u'],'lsib_path',path2keypath=True)
get_vndmat_attr(d,['y'],'lsib_path',path2keypath=True)
'''
kt... | [
"def",
"get_vndmat_attr",
"(",
"d",
",",
"keypath",
",",
"attr",
",",
"*",
"*",
"kwargs",
")",
":",
"kt",
",",
"vn",
"=",
"_d2kvmatrix",
"(",
"d",
")",
"kdmat",
"=",
"_scankm",
"(",
"kt",
")",
"ltree",
"=",
"elel",
".",
"ListTree",
"(",
"vn",
")"... | 32.473684 | 0.011802 |
async def create_turn_endpoint(protocol_factory, server_addr, username, password,
lifetime=600, ssl=False, transport='udp'):
"""
Create datagram connection relayed over TURN.
"""
loop = asyncio.get_event_loop()
if transport == 'tcp':
_, inner_protocol = await l... | [
"async",
"def",
"create_turn_endpoint",
"(",
"protocol_factory",
",",
"server_addr",
",",
"username",
",",
"password",
",",
"lifetime",
"=",
"600",
",",
"ssl",
"=",
"False",
",",
"transport",
"=",
"'udp'",
")",
":",
"loop",
"=",
"asyncio",
".",
"get_event_lo... | 40.928571 | 0.001705 |
def make_value_from_shell(self, param, value_type, function):
"""
run command in the shell
"""
try:
value = check_output(param, shell=True).rstrip()
except CalledProcessError:
# for value_type of 'bool' we return False on error code
if value_ty... | [
"def",
"make_value_from_shell",
"(",
"self",
",",
"param",
",",
"value_type",
",",
"function",
")",
":",
"try",
":",
"value",
"=",
"check_output",
"(",
"param",
",",
"shell",
"=",
"True",
")",
".",
"rstrip",
"(",
")",
"except",
"CalledProcessError",
":",
... | 37.807692 | 0.001984 |
def tensor(x:Any, *rest)->Tensor:
"Like `torch.as_tensor`, but handle lists too, and can pass multiple vector elements directly."
if len(rest): x = (x,)+rest
# XXX: Pytorch bug in dataloader using num_workers>0; TODO: create repro and report
if is_listy(x) and len(x)==0: return tensor(0)
res = torch... | [
"def",
"tensor",
"(",
"x",
":",
"Any",
",",
"*",
"rest",
")",
"->",
"Tensor",
":",
"if",
"len",
"(",
"rest",
")",
":",
"x",
"=",
"(",
"x",
",",
")",
"+",
"rest",
"# XXX: Pytorch bug in dataloader using num_workers>0; TODO: create repro and report",
"if",
"is... | 52 | 0.017013 |
def add_webhook(self, name, metadata=None):
"""
Adds a webhook to this policy.
"""
return self.manager.add_webhook(self.scaling_group, self, name,
metadata=metadata) | [
"def",
"add_webhook",
"(",
"self",
",",
"name",
",",
"metadata",
"=",
"None",
")",
":",
"return",
"self",
".",
"manager",
".",
"add_webhook",
"(",
"self",
".",
"scaling_group",
",",
"self",
",",
"name",
",",
"metadata",
"=",
"metadata",
")"
] | 34.666667 | 0.014085 |
def get_padding_lengths(self) -> Dict[str, Dict[str, int]]:
"""
Returns a dictionary of padding lengths, keyed by field name. Each ``Field`` returns a
mapping from padding keys to actual lengths, and we just key that dictionary by field name.
"""
lengths = {}
for field_n... | [
"def",
"get_padding_lengths",
"(",
"self",
")",
"->",
"Dict",
"[",
"str",
",",
"Dict",
"[",
"str",
",",
"int",
"]",
"]",
":",
"lengths",
"=",
"{",
"}",
"for",
"field_name",
",",
"field",
"in",
"self",
".",
"fields",
".",
"items",
"(",
")",
":",
"... | 47.888889 | 0.009112 |
def does_not_contain_key(self, *keys):
"""Asserts the val is a dict and does not contain the given key or keys. Alias for does_not_contain()."""
self._check_dict_like(self.val, check_values=False, check_getitem=False)
return self.does_not_contain(*keys) | [
"def",
"does_not_contain_key",
"(",
"self",
",",
"*",
"keys",
")",
":",
"self",
".",
"_check_dict_like",
"(",
"self",
".",
"val",
",",
"check_values",
"=",
"False",
",",
"check_getitem",
"=",
"False",
")",
"return",
"self",
".",
"does_not_contain",
"(",
"*... | 68.75 | 0.014388 |
def chunks(it, n):
"""Split an iterator into chunks with `n` elements each.
Examples
# n == 2
>>> x = chunks(iter([0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10]), 2)
>>> list(x)
[[0, 1], [2, 3], [4, 5], [6, 7], [8, 9], [10]]
# n == 3
>>> x = chunks(iter([0, 1, 2, 3, 4, 5, 6, ... | [
"def",
"chunks",
"(",
"it",
",",
"n",
")",
":",
"for",
"first",
"in",
"it",
":",
"yield",
"[",
"first",
"]",
"+",
"list",
"(",
"itertools",
".",
"islice",
"(",
"it",
",",
"n",
"-",
"1",
")",
")"
] | 34.428571 | 0.00202 |
def create_temp_file_name(suffix, prefix=None, dir=None, directory=None):
"""
Small convenience function that creates temporary files.
This function is a wrapper around the Python built-in
function tempfile.mkstemp.
"""
if dir is not None:
warnings.warn(
"The dir argument i... | [
"def",
"create_temp_file_name",
"(",
"suffix",
",",
"prefix",
"=",
"None",
",",
"dir",
"=",
"None",
",",
"directory",
"=",
"None",
")",
":",
"if",
"dir",
"is",
"not",
"None",
":",
"warnings",
".",
"warn",
"(",
"\"The dir argument is deprecated.\\n\"",
"+",
... | 32.571429 | 0.00142 |
def isnamedtuple(obj):
"""Heuristic check if an object is a namedtuple."""
return isinstance(obj, tuple) \
and hasattr(obj, "_fields") \
and hasattr(obj, "_asdict") \
and callable(obj._asdict) | [
"def",
"isnamedtuple",
"(",
"obj",
")",
":",
"return",
"isinstance",
"(",
"obj",
",",
"tuple",
")",
"and",
"hasattr",
"(",
"obj",
",",
"\"_fields\"",
")",
"and",
"hasattr",
"(",
"obj",
",",
"\"_asdict\"",
")",
"and",
"callable",
"(",
"obj",
".",
"_asdi... | 38 | 0.017167 |
def fields_for_model(self, model, include_fk=False, fields=None,
exclude=None, base_fields=None, dict_cls=dict):
"""
Overridden to correctly name hybrid_property fields, eg given::
class User(db.Model):
_password = db.Column('password', db.String)
... | [
"def",
"fields_for_model",
"(",
"self",
",",
"model",
",",
"include_fk",
"=",
"False",
",",
"fields",
"=",
"None",
",",
"exclude",
"=",
"None",
",",
"base_fields",
"=",
"None",
",",
"dict_cls",
"=",
"dict",
")",
":",
"# this prevents an error when building the... | 39.942308 | 0.00235 |
def load_config(self, configfile=None, override_config=None):
"""
Process a configfile, or reload if previously given one.
"""
self.config = configobj.ConfigObj()
# Load in the collector's defaults
if self.get_default_config() is not None:
self.config.merge(s... | [
"def",
"load_config",
"(",
"self",
",",
"configfile",
"=",
"None",
",",
"override_config",
"=",
"None",
")",
":",
"self",
".",
"config",
"=",
"configobj",
".",
"ConfigObj",
"(",
")",
"# Load in the collector's defaults",
"if",
"self",
".",
"get_default_config",
... | 37.40625 | 0.001629 |
def svg2paths(svg_file_location,
return_svg_attributes=False,
convert_circles_to_paths=True,
convert_ellipses_to_paths=True,
convert_lines_to_paths=True,
convert_polylines_to_paths=True,
convert_polygons_to_paths=True,
con... | [
"def",
"svg2paths",
"(",
"svg_file_location",
",",
"return_svg_attributes",
"=",
"False",
",",
"convert_circles_to_paths",
"=",
"True",
",",
"convert_ellipses_to_paths",
"=",
"True",
",",
"convert_lines_to_paths",
"=",
"True",
",",
"convert_polylines_to_paths",
"=",
"Tr... | 45.080808 | 0.001754 |
def generate_variables(name, n_vars=1, hermitian=None, commutative=True):
"""Generates a number of commutative or noncommutative variables
:param name: The prefix in the symbolic representation of the noncommuting
variables. This will be suffixed by a number from 0 to
n_vars-1... | [
"def",
"generate_variables",
"(",
"name",
",",
"n_vars",
"=",
"1",
",",
"hermitian",
"=",
"None",
",",
"commutative",
"=",
"True",
")",
":",
"variables",
"=",
"[",
"]",
"for",
"i",
"in",
"range",
"(",
"n_vars",
")",
":",
"if",
"n_vars",
">",
"1",
"... | 36.878049 | 0.000644 |
def image_information_response(self):
"""Parse image information request and create response."""
dr = degraded_request(self.identifier)
if (dr):
self.logger.info("image_information: degraded %s -> %s" %
(self.identifier, dr))
self.degraded = s... | [
"def",
"image_information_response",
"(",
"self",
")",
":",
"dr",
"=",
"degraded_request",
"(",
"self",
".",
"identifier",
")",
"if",
"(",
"dr",
")",
":",
"self",
".",
"logger",
".",
"info",
"(",
"\"image_information: degraded %s -> %s\"",
"%",
"(",
"self",
... | 47.131579 | 0.001641 |
def interval(host, time, actor, method, *args, **kwargs):
'''Creates an Event attached to the host for management that will
execute the *method* of the *actor* every *time* seconds.
See example in :ref:`sample_inter`
:param Proxy host: host that will manage the interval, commonly the
host of t... | [
"def",
"interval",
"(",
"host",
",",
"time",
",",
"actor",
",",
"method",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"call",
"=",
"getattr",
"(",
"actor",
",",
"method",
",",
"None",
")",
"if",
"not",
"callable",
"(",
"call",
")",
":",
... | 47.65625 | 0.000643 |
def nmltostring(nml):
"""Convert a dictionary representing a Fortran namelist into a string."""
if not isinstance(nml,dict):
raise ValueError("nml should be a dict !")
curstr = ""
for key,group in nml.items():
namelist = ["&" + key]
for k, v in group.items():
if isinstance(... | [
"def",
"nmltostring",
"(",
"nml",
")",
":",
"if",
"not",
"isinstance",
"(",
"nml",
",",
"dict",
")",
":",
"raise",
"ValueError",
"(",
"\"nml should be a dict !\"",
")",
"curstr",
"=",
"\"\"",
"for",
"key",
",",
"group",
"in",
"nml",
".",
"items",
"(",
... | 32.65 | 0.020833 |
def error(args):
"""
%prog error version backup_folder
Find all errors in ../5-consensus/*.err and pull the error unitigs into
backup/ folder.
"""
p = OptionParser(error.__doc__)
opts, args = p.parse_args(args)
if len(args) != 2:
sys.exit(not p.print_help())
version, backu... | [
"def",
"error",
"(",
"args",
")",
":",
"p",
"=",
"OptionParser",
"(",
"error",
".",
"__doc__",
")",
"opts",
",",
"args",
"=",
"p",
".",
"parse_args",
"(",
"args",
")",
"if",
"len",
"(",
"args",
")",
"!=",
"2",
":",
"sys",
".",
"exit",
"(",
"not... | 25.156863 | 0.002251 |
def sub(prev, pattern, repl, *args, **kw):
"""sub pipe is a wrapper of re.sub method.
:param prev: The previous iterator of pipe.
:type prev: Pipe
:param pattern: The pattern string.
:type pattern: str|unicode
:param repl: Check repl argument in re.sub method.
:type repl: str|unicode|callab... | [
"def",
"sub",
"(",
"prev",
",",
"pattern",
",",
"repl",
",",
"*",
"args",
",",
"*",
"*",
"kw",
")",
":",
"count",
"=",
"0",
"if",
"'count'",
"not",
"in",
"kw",
"else",
"kw",
".",
"pop",
"(",
"'count'",
")",
"pattern_obj",
"=",
"re",
".",
"compi... | 35.357143 | 0.001969 |
def join(cls, splits, *namables):
"""
Interpolate strings.
:params splits: The output of Parser.split(string)
:params namables: A sequence of Namable objects in which the interpolation should take place.
Returns 2-tuple containing:
joined string, list of unbound object ids (potenti... | [
"def",
"join",
"(",
"cls",
",",
"splits",
",",
"*",
"namables",
")",
":",
"isplits",
"=",
"[",
"]",
"unbound",
"=",
"[",
"]",
"for",
"ref",
"in",
"splits",
":",
"if",
"isinstance",
"(",
"ref",
",",
"Ref",
")",
":",
"resolved",
"=",
"False",
"for"... | 28.6 | 0.011274 |
def returnMatches(kw, kv, n, theta, inputScaling=1.0):
"""
:param kw: k for the weight vectors
:param kv: k for the input vectors
:param n: dimensionality of input vector
:param theta: threshold for matching after dot product
:return: percent that matched, number that matched, total match comparisons
""... | [
"def",
"returnMatches",
"(",
"kw",
",",
"kv",
",",
"n",
",",
"theta",
",",
"inputScaling",
"=",
"1.0",
")",
":",
"# How many weight vectors and input vectors to generate at a time",
"m1",
"=",
"4",
"m2",
"=",
"1000",
"weights",
"=",
"getSparseTensor",
"(",
"kw",... | 35.64 | 0.014208 |
def create_single_method(self, estimator_index, estimator):
"""
Port a method for a single tree.
Parameters
----------
:param estimator_index : int
The estimator index.
:param estimator : RandomForestClassifier
The estimator.
Returns
... | [
"def",
"create_single_method",
"(",
"self",
",",
"estimator_index",
",",
"estimator",
")",
":",
"indices",
"=",
"[",
"str",
"(",
"e",
")",
"for",
"e",
"in",
"estimator",
".",
"tree_",
".",
"feature",
"]",
"tree_branches",
"=",
"self",
".",
"create_branches... | 36.296296 | 0.001988 |
def sspro_results(self):
"""Parse the SSpro output file and return a dict of secondary structure compositions.
Returns:
dict: Keys are sequence IDs, values are the lists of secondary structure predictions.
H: helix
E: strand
C: the rest
... | [
"def",
"sspro_results",
"(",
"self",
")",
":",
"return",
"ssbio",
".",
"protein",
".",
"sequence",
".",
"utils",
".",
"fasta",
".",
"load_fasta_file_as_dict_of_seqs",
"(",
"self",
".",
"out_sspro",
")"
] | 37.636364 | 0.011792 |
def get_cached_or_new(url, new=False):
"""
Look into the database and return :class:`RequestInfo` if the `url` was
already analyzed, or create and return new instance, if not.
If the `new` is set to True, always create new instance.
Args:
url (str): URL of the analyzed resource.
ne... | [
"def",
"get_cached_or_new",
"(",
"url",
",",
"new",
"=",
"False",
")",
":",
"garbage_collection",
"(",
")",
"old_req",
"=",
"DATABASE",
".",
"get",
"(",
"url",
")",
"if",
"old_req",
"and",
"not",
"new",
":",
"return",
"old_req",
"if",
"not",
"(",
"url"... | 25.285714 | 0.001361 |
def htmlDocDump(self, f):
"""Dump an HTML document to an open FILE. """
ret = libxml2mod.htmlDocDump(f, self._o)
return ret | [
"def",
"htmlDocDump",
"(",
"self",
",",
"f",
")",
":",
"ret",
"=",
"libxml2mod",
".",
"htmlDocDump",
"(",
"f",
",",
"self",
".",
"_o",
")",
"return",
"ret"
] | 36 | 0.013605 |
def _simple_blockify(tuples, dtype):
""" return a single array of a block that has a single dtype; if dtype is
not None, coerce to this dtype
"""
values, placement = _stack_arrays(tuples, dtype)
# CHECK DTYPE?
if dtype is not None and values.dtype != dtype: # pragma: no cover
values = ... | [
"def",
"_simple_blockify",
"(",
"tuples",
",",
"dtype",
")",
":",
"values",
",",
"placement",
"=",
"_stack_arrays",
"(",
"tuples",
",",
"dtype",
")",
"# CHECK DTYPE?",
"if",
"dtype",
"is",
"not",
"None",
"and",
"values",
".",
"dtype",
"!=",
"dtype",
":",
... | 33.416667 | 0.002427 |
def _evaluate(self,R,z,phi=0.,t=0.):
"""
NAME:
_evaluate
PURPOSE:
evaluate the potential at R,z
INPUT:
R - Galactocentric cylindrical radius
z - vertical height
phi - azimuth
t - time
OUTPUT:
Phi(R,z)
... | [
"def",
"_evaluate",
"(",
"self",
",",
"R",
",",
"z",
",",
"phi",
"=",
"0.",
",",
"t",
"=",
"0.",
")",
":",
"r",
"=",
"nu",
".",
"sqrt",
"(",
"R",
"**",
"2.",
"+",
"z",
"**",
"2.",
")",
"return",
"2.",
"*",
"nu",
".",
"pi",
"*",
"self",
... | 35.388889 | 0.015291 |
def get_command_handlers():
'''
Create a map of command names and handlers
'''
return {
'activate': activate,
'config': hconfig,
'deactivate': deactivate,
'help': cli_help,
'kill': kill,
'restart': restart,
'submit': submit,
'update': update,
'version': vers... | [
"def",
"get_command_handlers",
"(",
")",
":",
"return",
"{",
"'activate'",
":",
"activate",
",",
"'config'",
":",
"hconfig",
",",
"'deactivate'",
":",
"deactivate",
",",
"'help'",
":",
"cli_help",
",",
"'kill'",
":",
"kill",
",",
"'restart'",
":",
"restart",... | 20.866667 | 0.009174 |
def add_headers(self, **headers):
"""packing dicts into typecode pyclass, may fail if typecodes are
used in the body (when asdict=True)
"""
class _holder: pass
def _remap(pyobj, **d):
pyobj.__dict__ = d
for k,v in pyobj.__dict__.items():
if... | [
"def",
"add_headers",
"(",
"self",
",",
"*",
"*",
"headers",
")",
":",
"class",
"_holder",
":",
"pass",
"def",
"_remap",
"(",
"pyobj",
",",
"*",
"*",
"d",
")",
":",
"pyobj",
".",
"__dict__",
"=",
"d",
"for",
"k",
",",
"v",
"in",
"pyobj",
".",
"... | 34.65625 | 0.014035 |
def factory(
method,
description="",
request_example=None,
request_ctor=None,
responses=None,
method_choices=HTTP_METHODS,
):
"""
desc: Describes a single HTTP method of a URI
args:
- name: method
type: str
... | [
"def",
"factory",
"(",
"method",
",",
"description",
"=",
"\"\"",
",",
"request_example",
"=",
"None",
",",
"request_ctor",
"=",
"None",
",",
"responses",
"=",
"None",
",",
"method_choices",
"=",
"HTTP_METHODS",
",",
")",
":",
"return",
"RouteMethod",
"(",
... | 33.423077 | 0.001677 |
def result(self, r=None, **kwargs):
'''
Validates a result, stores it in self.results and prints it.
Accepts the same kwargs as the binwalk.core.module.Result class.
@r - An existing instance of binwalk.core.module.Result.
Returns an instance of binwalk.core.module.Result.
... | [
"def",
"result",
"(",
"self",
",",
"r",
"=",
"None",
",",
"*",
"*",
"kwargs",
")",
":",
"if",
"r",
"is",
"None",
":",
"r",
"=",
"Result",
"(",
"*",
"*",
"kwargs",
")",
"# Add the name of the current module to the result",
"r",
".",
"module",
"=",
"self... | 32.456522 | 0.001951 |
def from_element(cls, element):
"""Set the resource properties from a ``<res>`` element.
Args:
element (~xml.etree.ElementTree.Element): The ``<res>``
element
"""
def _int_helper(name):
"""Try to convert the name attribute to an int, or None."""
... | [
"def",
"from_element",
"(",
"cls",
",",
"element",
")",
":",
"def",
"_int_helper",
"(",
"name",
")",
":",
"\"\"\"Try to convert the name attribute to an int, or None.\"\"\"",
"result",
"=",
"element",
".",
"get",
"(",
"name",
")",
"if",
"result",
"is",
"not",
"N... | 40.897436 | 0.001225 |
def update(self, label):
"""
Update a Label
:param label: The data to update. Must include keys:
* id (str)
* appearance (dict)
* description (str)
* name (str)
* title (str)
:type label: dict
Example:
.. cod... | [
"def",
"update",
"(",
"self",
",",
"label",
")",
":",
"data",
"=",
"{",
"'id'",
":",
"label",
"[",
"'id'",
"]",
",",
"'name'",
":",
"label",
"[",
"'name'",
"]",
",",
"'appearance'",
":",
"label",
"[",
"'appearance'",
"]",
",",
"'description'",
":",
... | 25.095238 | 0.001826 |
def create_project_with_docs(
client, docs, language, name, account=None, progress=False
):
"""
Given an iterator of documents, upload them as a Luminoso project.
"""
description = 'Uploaded using lumi-upload at {}'.format(time.asctime())
if account is not None:
proj_record = client.post... | [
"def",
"create_project_with_docs",
"(",
"client",
",",
"docs",
",",
"language",
",",
"name",
",",
"account",
"=",
"None",
",",
"progress",
"=",
"False",
")",
":",
"description",
"=",
"'Uploaded using lumi-upload at {}'",
".",
"format",
"(",
"time",
".",
"ascti... | 31.75 | 0.000637 |
def com_google_fonts_check_metadata_familyname(family_metadata):
"""Check that METADATA.pb family values are all the same."""
name = ""
fail = False
for f in family_metadata.fonts:
if name and f.name != name:
fail = True
name = f.name
if fail:
yield FAIL, ("METADATA.pb: Family name is not th... | [
"def",
"com_google_fonts_check_metadata_familyname",
"(",
"family_metadata",
")",
":",
"name",
"=",
"\"\"",
"fail",
"=",
"False",
"for",
"f",
"in",
"family_metadata",
".",
"fonts",
":",
"if",
"name",
"and",
"f",
".",
"name",
"!=",
"name",
":",
"fail",
"=",
... | 34.714286 | 0.016032 |
def dayname(year, month, day):
'''
Give the name of the month and day for a given date.
Returns:
tuple month_name, day_name
'''
legal_date(year, month, day)
yearday = (month - 1) * 28 + day
if isleap(year + YEAR_EPOCH - 1):
dname = data.day_names_leap[yearday - 1]
else... | [
"def",
"dayname",
"(",
"year",
",",
"month",
",",
"day",
")",
":",
"legal_date",
"(",
"year",
",",
"month",
",",
"day",
")",
"yearday",
"=",
"(",
"month",
"-",
"1",
")",
"*",
"28",
"+",
"day",
"if",
"isleap",
"(",
"year",
"+",
"YEAR_EPOCH",
"-",
... | 22.705882 | 0.002488 |
def get_data(self, special_fields=None):
"""
special_fields: "a dict of data specific to collector type
that should be added to the data returned by the parser.
This will also be and operated on by idMapping, mappings and
plugins"
This method loops through th... | [
"def",
"get_data",
"(",
"self",
",",
"special_fields",
"=",
"None",
")",
":",
"docs",
"=",
"build_document_set",
"(",
"self",
".",
"data",
",",
"self",
".",
"data_type",
",",
"self",
".",
"mappings",
",",
"special_fields",
",",
"self",
".",
"idMapping",
... | 44.473684 | 0.001158 |
def get_setter(self, oid):
"""
Retrieve the nearest parent setter function for an OID
"""
if hasattr(self.setter, oid):
return self.setter[oid]
parents = [ poid for poid in list(self.setter.keys()) if oid.startswith(poid) ]
if parents:
return self.setter[max(parents)]
return self.default_setter | [
"def",
"get_setter",
"(",
"self",
",",
"oid",
")",
":",
"if",
"hasattr",
"(",
"self",
".",
"setter",
",",
"oid",
")",
":",
"return",
"self",
".",
"setter",
"[",
"oid",
"]",
"parents",
"=",
"[",
"poid",
"for",
"poid",
"in",
"list",
"(",
"self",
".... | 30.6 | 0.044444 |
def generateDistanceMatrix(width, height):
"""
Generates a matrix specifying the distance of each point in a window to its centre.
"""
# Determine the coordinates of the exact centre of the window
originX = width / 2
originY = height / 2
# Generate the distance matrix
distances = zerosFactory((height,width)... | [
"def",
"generateDistanceMatrix",
"(",
"width",
",",
"height",
")",
":",
"# Determine the coordinates of the exact centre of the window",
"originX",
"=",
"width",
"/",
"2",
"originY",
"=",
"height",
"/",
"2",
"# Generate the distance matrix",
"distances",
"=",
"zerosFactor... | 30.5 | 0.05169 |
def get_image_and_mask(self, label, positive_only=True, hide_rest=False,
num_features=5, min_weight=0.):
"""Init function.
Args:
label: label to explain
positive_only: if True, only take superpixels that contribute to
the prediction of ... | [
"def",
"get_image_and_mask",
"(",
"self",
",",
"label",
",",
"positive_only",
"=",
"True",
",",
"hide_rest",
"=",
"False",
",",
"num_features",
"=",
"5",
",",
"min_weight",
"=",
"0.",
")",
":",
"if",
"label",
"not",
"in",
"self",
".",
"local_exp",
":",
... | 40.16 | 0.001458 |
def to_neo(self,index_label='N',time_label=0,name='segment of exported spikes',index=0):
"""
Returns a `neo` Segment containing the spike trains.
Example usage::
import quantities as pq
seg = sp.to_neo()
fig = pyplot.figure()
... | [
"def",
"to_neo",
"(",
"self",
",",
"index_label",
"=",
"'N'",
",",
"time_label",
"=",
"0",
",",
"name",
"=",
"'segment of exported spikes'",
",",
"index",
"=",
"0",
")",
":",
"import",
"neo",
"from",
"quantities",
"import",
"s",
"seq",
"=",
"neo",
".",
... | 38.84375 | 0.014129 |
def _bind_target(self, target, ctx=None):
"""Method to override in order to specialize binding of target.
:param target: target to bind.
:param ctx: target ctx.
:return: bound target.
"""
result = target
try:
# get annotations from target if exists.... | [
"def",
"_bind_target",
"(",
"self",
",",
"target",
",",
"ctx",
"=",
"None",
")",
":",
"result",
"=",
"target",
"try",
":",
"# get annotations from target if exists.",
"local_annotations",
"=",
"get_local_property",
"(",
"target",
",",
"Annotation",
".",
"__ANNOTAT... | 29.823529 | 0.00191 |
def _normalize_seqs(s, t):
"""Normalize to RPM"""
for ids in s:
obj = s[ids]
[obj.norm_freq.update({sample: 1.0 * obj.freq[sample] / (t[sample]+1) * 1000000}) for sample in obj.norm_freq]
s[ids] = obj
return s | [
"def",
"_normalize_seqs",
"(",
"s",
",",
"t",
")",
":",
"for",
"ids",
"in",
"s",
":",
"obj",
"=",
"s",
"[",
"ids",
"]",
"[",
"obj",
".",
"norm_freq",
".",
"update",
"(",
"{",
"sample",
":",
"1.0",
"*",
"obj",
".",
"freq",
"[",
"sample",
"]",
... | 34.142857 | 0.008163 |
def workspace_from_dir(directory, recurse=True):
"""
Construct a workspace object from a directory name. If recurse=True, this
function will search down the directory tree and return the first workspace
it finds. If recurse=False, an exception will be raised if the given
directory is not a workspa... | [
"def",
"workspace_from_dir",
"(",
"directory",
",",
"recurse",
"=",
"True",
")",
":",
"directory",
"=",
"os",
".",
"path",
".",
"abspath",
"(",
"directory",
")",
"pickle_path",
"=",
"os",
".",
"path",
".",
"join",
"(",
"directory",
",",
"'workspace.pkl'",
... | 41.552632 | 0.000619 |
def triggerTrailingStops(self, tickerId):
""" trigger waiting trailing stops """
# print('.')
# test
symbol = self.tickerSymbol(tickerId)
price = self.marketData[tickerId]['last'][0]
# contract = self.contracts[tickerId]
if symbol in self.triggerableTrailingStop... | [
"def",
"triggerTrailingStops",
"(",
"self",
",",
"tickerId",
")",
":",
"# print('.')",
"# test",
"symbol",
"=",
"self",
".",
"tickerSymbol",
"(",
"tickerId",
")",
"price",
"=",
"self",
".",
"marketData",
"[",
"tickerId",
"]",
"[",
"'last'",
"]",
"[",
"0",
... | 37.373494 | 0.011307 |
def get_aws_creds(account, tenant, token):
"""Get AWS account credentials to enable access to AWS.
Returns a time bound set of AWS credentials.
"""
url = (FAWS_API_URL.format(account))
headers = {
'X-Auth-Token': token,
'X-Tenant-Id': tenant,
}
response = requests.post(url, ... | [
"def",
"get_aws_creds",
"(",
"account",
",",
"tenant",
",",
"token",
")",
":",
"url",
"=",
"(",
"FAWS_API_URL",
".",
"format",
"(",
"account",
")",
")",
"headers",
"=",
"{",
"'X-Auth-Token'",
":",
"token",
",",
"'X-Tenant-Id'",
":",
"tenant",
",",
"}",
... | 33.5 | 0.001815 |
def pull(self,bookName=None,sheetName=None):
"""pull data into this OR.SHEET from a real book/sheet in Origin"""
# tons of validation
if bookName is None and self.bookName: bookName=self.bookName
if sheetName is None and self.sheetName: sheetName=self.sheetName
if bookName is No... | [
"def",
"pull",
"(",
"self",
",",
"bookName",
"=",
"None",
",",
"sheetName",
"=",
"None",
")",
":",
"# tons of validation",
"if",
"bookName",
"is",
"None",
"and",
"self",
".",
"bookName",
":",
"bookName",
"=",
"self",
".",
"bookName",
"if",
"sheetName",
"... | 50.695652 | 0.021886 |
def convert_PSFLab_xz(data, x_step=0.5, z_step=0.5, normalize=False):
"""Process a 2D array (from PSFLab .mat file) containing a x-z PSF slice.
The input data is the raw array saved by PSFLab. The returned array has
the x axis cut in half (only positive x) to take advantage of the
rotational symmetry a... | [
"def",
"convert_PSFLab_xz",
"(",
"data",
",",
"x_step",
"=",
"0.5",
",",
"z_step",
"=",
"0.5",
",",
"normalize",
"=",
"False",
")",
":",
"z_len",
",",
"x_len",
"=",
"data",
".",
"shape",
"hdata",
"=",
"data",
"[",
":",
",",
"(",
"x_len",
"-",
"1",
... | 41.454545 | 0.001072 |
def convert_convolution(net, node, module, builder):
"""Convert a convolution layer from mxnet to coreml.
Parameters
----------
network: net
A mxnet network object.
layer: node
Node to convert.
module: module
An module for MXNet
builder: NeuralNetworkBuilder
... | [
"def",
"convert_convolution",
"(",
"net",
",",
"node",
",",
"module",
",",
"builder",
")",
":",
"input_name",
",",
"output_name",
"=",
"_get_input_output_name",
"(",
"net",
",",
"node",
")",
"name",
"=",
"node",
"[",
"'name'",
"]",
"param",
"=",
"_get_attr... | 26 | 0.000469 |
def graph_sparsify(M, epsilon, maxiter=10):
r"""Sparsify a graph (with Spielman-Srivastava).
Parameters
----------
M : Graph or sparse matrix
Graph structure or a Laplacian matrix
epsilon : int
Sparsification parameter
Returns
-------
Mnew : Graph or sparse matrix
... | [
"def",
"graph_sparsify",
"(",
"M",
",",
"epsilon",
",",
"maxiter",
"=",
"10",
")",
":",
"# Test the input parameters",
"if",
"isinstance",
"(",
"M",
",",
"graphs",
".",
"Graph",
")",
":",
"if",
"not",
"M",
".",
"lap_type",
"==",
"'combinatorial'",
":",
"... | 29.132075 | 0.001566 |
def forward(self, is_train=False):
"""Perform a forward pass on each executor."""
for texec in self.train_execs:
texec.forward(is_train=is_train) | [
"def",
"forward",
"(",
"self",
",",
"is_train",
"=",
"False",
")",
":",
"for",
"texec",
"in",
"self",
".",
"train_execs",
":",
"texec",
".",
"forward",
"(",
"is_train",
"=",
"is_train",
")"
] | 42.5 | 0.011561 |
def get_fresh_content(top=4, additional=10, featured=False):
"""
Requires articles, photos and video packages to be installed.
Returns published *Featured* content (articles, galleries, video, etc)
and an additional batch of fresh regular (featured or not) content.
The number of objects returned i... | [
"def",
"get_fresh_content",
"(",
"top",
"=",
"4",
",",
"additional",
"=",
"10",
",",
"featured",
"=",
"False",
")",
":",
"from",
"articles",
".",
"models",
"import",
"Article",
"from",
"photos",
".",
"models",
"import",
"Gallery",
"from",
"video",
".",
"... | 38.837838 | 0.001697 |
def add(self, item, group_by=None):
"""General purpose class to group items by certain criteria."""
key = None
if not group_by:
group_by = self.group_by
if group_by:
# if group_by is a function, use it with item as argument
if hasattr(group_by, '__ca... | [
"def",
"add",
"(",
"self",
",",
"item",
",",
"group_by",
"=",
"None",
")",
":",
"key",
"=",
"None",
"if",
"not",
"group_by",
":",
"group_by",
"=",
"self",
".",
"group_by",
"if",
"group_by",
":",
"# if group_by is a function, use it with item as argument",
"if"... | 36.357143 | 0.001914 |
def swap_pairs(line, starttag=position_tag):
"""Swap coordinate pairs
Inputs
line: gml line assumed to contain pairs of coordinates ordered as
latitude, longitude
starttag: tag marking the start of the coordinate pairs.
"""
endtag = starttag.replace('<', '</')
index ... | [
"def",
"swap_pairs",
"(",
"line",
",",
"starttag",
"=",
"position_tag",
")",
":",
"endtag",
"=",
"starttag",
".",
"replace",
"(",
"'<'",
",",
"'</'",
")",
"index",
"=",
"line",
".",
"find",
"(",
"starttag",
")",
"if",
"index",
"<",
"0",
":",
"msg",
... | 27.784314 | 0.000682 |
def logical_xor(self, other):
"""logical_xor(t) = self(t) ^ other(t)."""
return self.operation(other, lambda x, y: int(bool(x) ^ bool(y))) | [
"def",
"logical_xor",
"(",
"self",
",",
"other",
")",
":",
"return",
"self",
".",
"operation",
"(",
"other",
",",
"lambda",
"x",
",",
"y",
":",
"int",
"(",
"bool",
"(",
"x",
")",
"^",
"bool",
"(",
"y",
")",
")",
")"
] | 50.666667 | 0.012987 |
def glsfit(psr,renormalize=True):
"""Solve local GLS problem using scipy.linalg.cholesky.
Update psr[...].val and psr[...].err from solution.
If renormalize=True, normalize each design-matrix column by its norm."""
mask = psr.deleted == 0
res, err = psr.residuals(removemean=False)[mask], psr.to... | [
"def",
"glsfit",
"(",
"psr",
",",
"renormalize",
"=",
"True",
")",
":",
"mask",
"=",
"psr",
".",
"deleted",
"==",
"0",
"res",
",",
"err",
"=",
"psr",
".",
"residuals",
"(",
"removemean",
"=",
"False",
")",
"[",
"mask",
"]",
",",
"psr",
".",
"toae... | 32.166667 | 0.019115 |
def xml_to_json_response(service_spec, operation, xml, result_node=None):
"""Convert rendered XML response to JSON for use with boto3."""
def transform(value, spec):
"""Apply transformations to make the output JSON comply with the
expected form. This function applies:
(1) Type cast t... | [
"def",
"xml_to_json_response",
"(",
"service_spec",
",",
"operation",
",",
"xml",
",",
"result_node",
"=",
"None",
")",
":",
"def",
"transform",
"(",
"value",
",",
"spec",
")",
":",
"\"\"\"Apply transformations to make the output JSON comply with the\n expected for... | 37.959459 | 0.001388 |
def main(argv=None):
"""Main entry point for iotile sensorgraph simulator.
This is the iotile-sgrun command line program. It takes
an optional set of command line parameters to allow for
testing.
Args:
argv (list of str): An optional set of command line
parameters. If not pas... | [
"def",
"main",
"(",
"argv",
"=",
"None",
")",
":",
"if",
"argv",
"is",
"None",
":",
"argv",
"=",
"sys",
".",
"argv",
"[",
"1",
":",
"]",
"try",
":",
"executor",
"=",
"None",
"parser",
"=",
"build_args",
"(",
")",
"args",
"=",
"parser",
".",
"pa... | 27.109589 | 0.000975 |
def start(self, on_done):
"""
Starts the genesis block creation process. Will call the given
`on_done` callback on successful completion.
Args:
on_done (function): a function called on completion
Raises:
InvalidGenesisStateError: raises this error if a ... | [
"def",
"start",
"(",
"self",
",",
"on_done",
")",
":",
"genesis_file",
"=",
"os",
".",
"path",
".",
"join",
"(",
"self",
".",
"_data_dir",
",",
"'genesis.batch'",
")",
"try",
":",
"with",
"open",
"(",
"genesis_file",
",",
"'rb'",
")",
"as",
"batch_file... | 39.730769 | 0.000472 |
def _instantiate_task(api, kwargs):
"""Create a Task object from raw kwargs"""
file_id = kwargs['file_id']
kwargs['file_id'] = file_id if str(file_id).strip() else None
kwargs['cid'] = kwargs['file_id'] or None
kwargs['rate_download'] = kwargs['rateDownload']
kwargs['percent_done'] = kwargs['per... | [
"def",
"_instantiate_task",
"(",
"api",
",",
"kwargs",
")",
":",
"file_id",
"=",
"kwargs",
"[",
"'file_id'",
"]",
"kwargs",
"[",
"'file_id'",
"]",
"=",
"file_id",
"if",
"str",
"(",
"file_id",
")",
".",
"strip",
"(",
")",
"else",
"None",
"kwargs",
"[",
... | 36.84 | 0.001058 |
def get(self, key, timeout=None):
"""Given a key, returns an element from the redis table"""
key = self.pre_identifier + key
# Check to see if we have this key
unpickled_entry = self.client.get(key)
if not unpickled_entry:
# No hit, return nothing
return N... | [
"def",
"get",
"(",
"self",
",",
"key",
",",
"timeout",
"=",
"None",
")",
":",
"key",
"=",
"self",
".",
"pre_identifier",
"+",
"key",
"# Check to see if we have this key",
"unpickled_entry",
"=",
"self",
".",
"client",
".",
"get",
"(",
"key",
")",
"if",
"... | 36.181818 | 0.002448 |
def _transposes(self):
"""teh"""
return {concat(a, reversed(b[:2]), b[2:])
for a, b in self.slices[:-2]} | [
"def",
"_transposes",
"(",
"self",
")",
":",
"return",
"{",
"concat",
"(",
"a",
",",
"reversed",
"(",
"b",
"[",
":",
"2",
"]",
")",
",",
"b",
"[",
"2",
":",
"]",
")",
"for",
"a",
",",
"b",
"in",
"self",
".",
"slices",
"[",
":",
"-",
"2",
... | 33.25 | 0.014706 |
def r_annotation(self, sha):
""" Route to retrieve contents of an annotation resource
:param uri: The uri of the annotation resource
:type uri: str
:return: annotation contents
:rtype: {str: Any}
"""
annotation = self.__queryinterface__.getResource(sha)
i... | [
"def",
"r_annotation",
"(",
"self",
",",
"sha",
")",
":",
"annotation",
"=",
"self",
".",
"__queryinterface__",
".",
"getResource",
"(",
"sha",
")",
"if",
"not",
"annotation",
":",
"return",
"\"invalid resource uri\"",
",",
"404",
"response",
"=",
"{",
"\"@c... | 37.590909 | 0.002358 |
def codify(combination):
"""
Gets escape-codes for flag combinations.
Arguments:
combination (int): Either a single integer-convertible flag
or an OR'd flag-combination.
Returns:
A semi-colon-delimited string of appropriate escape sequences.
Raises:
errors.FlagError if the combination is out-of-r... | [
"def",
"codify",
"(",
"combination",
")",
":",
"if",
"(",
"isinstance",
"(",
"combination",
",",
"int",
")",
"and",
"(",
"combination",
"<",
"0",
"or",
"combination",
">=",
"LIMIT",
")",
")",
":",
"raise",
"errors",
".",
"FlagError",
"(",
"\"Out-of-range... | 22.074074 | 0.03537 |
def _group_keys(self):
"""
every child key referencing a group that is not a dataframe
"""
return [name for name, child in iteritems(self._children) if isinstance(child, GroupNode)] | [
"def",
"_group_keys",
"(",
"self",
")",
":",
"return",
"[",
"name",
"for",
"name",
",",
"child",
"in",
"iteritems",
"(",
"self",
".",
"_children",
")",
"if",
"isinstance",
"(",
"child",
",",
"GroupNode",
")",
"]"
] | 41.8 | 0.014085 |
def get_element_profile(self, element, comp, comp_tol=1e-5):
"""
Provides the element evolution data for a composition.
For example, can be used to analyze Li conversion voltages by varying
uLi and looking at the phases formed. Also can be used to analyze O2
evolution by varying ... | [
"def",
"get_element_profile",
"(",
"self",
",",
"element",
",",
"comp",
",",
"comp_tol",
"=",
"1e-5",
")",
":",
"element",
"=",
"get_el_sp",
"(",
"element",
")",
"element",
"=",
"Element",
"(",
"element",
".",
"symbol",
")",
"if",
"element",
"not",
"in",... | 45.348837 | 0.001004 |
def _inherit_parent_kwargs(self, kwargs):
"""Extract any necessary attributes from parent serializer to
propagate down to child serializer.
"""
if not self.parent or not self._is_dynamic:
return kwargs
if 'request_fields' not in kwargs:
# If 'request_fie... | [
"def",
"_inherit_parent_kwargs",
"(",
"self",
",",
"kwargs",
")",
":",
"if",
"not",
"self",
".",
"parent",
"or",
"not",
"self",
".",
"_is_dynamic",
":",
"return",
"kwargs",
"if",
"'request_fields'",
"not",
"in",
"kwargs",
":",
"# If 'request_fields' isn't explic... | 36.678571 | 0.001898 |
def raw_machine_data(self, machine_id, credentials=False):
"""
::
GET /:login/machines/:machine
:param machine_id: identifier for the machine instance
:type machine_id: :py:class:`basestring` or :py:class:`dict`
:param credentials: whether t... | [
"def",
"raw_machine_data",
"(",
"self",
",",
"machine_id",
",",
"credentials",
"=",
"False",
")",
":",
"params",
"=",
"{",
"}",
"if",
"isinstance",
"(",
"machine_id",
",",
"dict",
")",
":",
"machine_id",
"=",
"machine_id",
"[",
"'id'",
"]",
"if",
"creden... | 33.416667 | 0.010909 |
def V_vertical_ellipsoidal_concave(D, a, h):
r'''Calculates volume of a vertical tank with a concave ellipsoidal bottom,
according to [1]_. No provision for the top of the tank is made here.
.. math::
V = \frac{\pi D^2}{12} \left(3h + 2a - \frac{(a+h)^2(2a-h)}{a^2}\right)
,\;\; 0 \le h < |a... | [
"def",
"V_vertical_ellipsoidal_concave",
"(",
"D",
",",
"a",
",",
"h",
")",
":",
"if",
"h",
"<",
"abs",
"(",
"a",
")",
":",
"Vf",
"=",
"pi",
"*",
"D",
"**",
"2",
"/",
"12.",
"*",
"(",
"3",
"*",
"h",
"+",
"2",
"*",
"a",
"-",
"(",
"a",
"+",... | 28.44186 | 0.001581 |
def crypto_secretstream_xchacha20poly1305_rekey(state):
"""
Explicitly change the encryption key in the stream.
Normally the stream is re-keyed as needed or an explicit ``tag`` of
:data:`.crypto_secretstream_xchacha20poly1305_TAG_REKEY` is added to a
message to ensure forward secrecy, but this meth... | [
"def",
"crypto_secretstream_xchacha20poly1305_rekey",
"(",
"state",
")",
":",
"ensure",
"(",
"isinstance",
"(",
"state",
",",
"crypto_secretstream_xchacha20poly1305_state",
")",
",",
"'State must be a crypto_secretstream_xchacha20poly1305_state object'",
",",
"raising",
"=",
"e... | 40.368421 | 0.001274 |
def get_realtime_urls(admin_view_func=lambda x: x):
"""
Get the URL for real-time widgets.
Args:
admin_view_func (callable): an admin_view method from an AdminSite
instance. By default: identity.
Returns:
list: the list of the real-time URLs as django's ``url()``.
"""
... | [
"def",
"get_realtime_urls",
"(",
"admin_view_func",
"=",
"lambda",
"x",
":",
"x",
")",
":",
"from",
".",
"widgets",
"import",
"REALTIME_WIDGETS",
"return",
"[",
"url",
"(",
"w",
".",
"url_regex",
",",
"admin_view_func",
"(",
"w",
".",
"as_view",
"(",
")",
... | 33 | 0.002105 |
def symmetry_reduce(tensors, structure, tol=1e-8, **kwargs):
"""
Function that converts a list of tensors corresponding to a structure
and returns a dictionary consisting of unique tensor keys with symmop
values corresponding to transformations that will result in derivative
tensors from the origina... | [
"def",
"symmetry_reduce",
"(",
"tensors",
",",
"structure",
",",
"tol",
"=",
"1e-8",
",",
"*",
"*",
"kwargs",
")",
":",
"sga",
"=",
"SpacegroupAnalyzer",
"(",
"structure",
",",
"*",
"*",
"kwargs",
")",
"symmops",
"=",
"sga",
".",
"get_symmetry_operations",... | 43.40625 | 0.001408 |
def reduction_ratio(links_pred, *total):
"""Compute the reduction ratio.
The reduction ratio is 1 minus the ratio candidate matches and the maximum
number of pairs possible.
Parameters
----------
links_pred: int, pandas.MultiIndex
The number of candidate record pairs or the pandas.Mult... | [
"def",
"reduction_ratio",
"(",
"links_pred",
",",
"*",
"total",
")",
":",
"n_max",
"=",
"full_index_size",
"(",
"*",
"total",
")",
"if",
"isinstance",
"(",
"links_pred",
",",
"pandas",
".",
"MultiIndex",
")",
":",
"links_pred",
"=",
"len",
"(",
"links_pred... | 25.548387 | 0.001217 |
def start(self):
''' doesn't work'''
thread = threading.Thread(target=reactor.run)
thread.start() | [
"def",
"start",
"(",
"self",
")",
":",
"thread",
"=",
"threading",
".",
"Thread",
"(",
"target",
"=",
"reactor",
".",
"run",
")",
"thread",
".",
"start",
"(",
")"
] | 29.5 | 0.016529 |
def gtk_threadsafe(func):
'''
Decorator to make wrapped function threadsafe by forcing it to execute
within the GTK main thread.
.. versionadded:: 0.18
.. versionchanged:: 0.22
Add support for keyword arguments in callbacks by supporting functions
wrapped by `functools.partial()`. ... | [
"def",
"gtk_threadsafe",
"(",
"func",
")",
":",
"# Set up GDK threading.",
"# XXX This must be done to support running multiple threads in GTK",
"# applications.",
"gtk",
".",
"gdk",
".",
"threads_init",
"(",
")",
"# Support",
"wraps_func",
"=",
"func",
".",
"func",
"if",... | 30.72973 | 0.001705 |
def Voicemail(self, Id):
"""Queries the voicemail object.
:Parameters:
Id : int
Voicemail Id.
:return: A voicemail object.
:rtype: `Voicemail`
"""
o = Voicemail(self, Id)
o.Type # Test if such a voicemail exists.
return o | [
"def",
"Voicemail",
"(",
"self",
",",
"Id",
")",
":",
"o",
"=",
"Voicemail",
"(",
"self",
",",
"Id",
")",
"o",
".",
"Type",
"# Test if such a voicemail exists.",
"return",
"o"
] | 22.846154 | 0.009709 |
def kill_session(self):
"""``$ tmux kill-session``."""
proc = self.cmd('kill-session', '-t%s' % self.id)
if proc.stderr:
raise exc.LibTmuxException(proc.stderr) | [
"def",
"kill_session",
"(",
"self",
")",
":",
"proc",
"=",
"self",
".",
"cmd",
"(",
"'kill-session'",
",",
"'-t%s'",
"%",
"self",
".",
"id",
")",
"if",
"proc",
".",
"stderr",
":",
"raise",
"exc",
".",
"LibTmuxException",
"(",
"proc",
".",
"stderr",
"... | 27.428571 | 0.010101 |
def attach(self, api_object, on_cloud=False):
""" Attach this attachment to an existing api_object. This
BaseAttachment object must be an orphan BaseAttachment created for the
sole purpose of attach it to something and therefore run this method.
:param api_object: object to attach to
... | [
"def",
"attach",
"(",
"self",
",",
"api_object",
",",
"on_cloud",
"=",
"False",
")",
":",
"if",
"self",
".",
"on_cloud",
":",
"# item is already saved on the cloud.",
"return",
"True",
"# api_object must exist and if implements attachments",
"# then we can attach to it.",
... | 42.837209 | 0.002123 |
def script_input(module_name):
'''Render a module's input page. Forms are created based on objects in
the module's WebAPI class.'''
if module_name not in registered_modules:
return page_not_found(module_name)
form = registered_modules[module_name].WebAPI()
return render_template('script_inde... | [
"def",
"script_input",
"(",
"module_name",
")",
":",
"if",
"module_name",
"not",
"in",
"registered_modules",
":",
"return",
"page_not_found",
"(",
"module_name",
")",
"form",
"=",
"registered_modules",
"[",
"module_name",
"]",
".",
"WebAPI",
"(",
")",
"return",
... | 46.4 | 0.002114 |
def sdiff(self, *other_sets):
"""Union between Sets.
Returns a set of common members. Uses Redis.sdiff.
"""
return self.db.sdiff([self.key] + [s.key for s in other_sets]) | [
"def",
"sdiff",
"(",
"self",
",",
"*",
"other_sets",
")",
":",
"return",
"self",
".",
"db",
".",
"sdiff",
"(",
"[",
"self",
".",
"key",
"]",
"+",
"[",
"s",
".",
"key",
"for",
"s",
"in",
"other_sets",
"]",
")"
] | 33 | 0.009852 |
def extract_germline_vcinfo(data, out_dir):
"""Extract germline VCFs from existing tumor inputs.
"""
supported_germline = set(["vardict", "octopus", "freebayes"])
if dd.get_phenotype(data) in ["tumor"]:
for v in _get_variants(data):
if v.get("variantcaller") in supported_germline:
... | [
"def",
"extract_germline_vcinfo",
"(",
"data",
",",
"out_dir",
")",
":",
"supported_germline",
"=",
"set",
"(",
"[",
"\"vardict\"",
",",
"\"octopus\"",
",",
"\"freebayes\"",
"]",
")",
"if",
"dd",
".",
"get_phenotype",
"(",
"data",
")",
"in",
"[",
"\"tumor\""... | 43.133333 | 0.001513 |
def close(self, suppress_logging=False):
""" iterates thru all publisher pools and closes them """
pool_names = list(self.pools)
for name in pool_names:
self._close(name, suppress_logging) | [
"def",
"close",
"(",
"self",
",",
"suppress_logging",
"=",
"False",
")",
":",
"pool_names",
"=",
"list",
"(",
"self",
".",
"pools",
")",
"for",
"name",
"in",
"pool_names",
":",
"self",
".",
"_close",
"(",
"name",
",",
"suppress_logging",
")"
] | 44 | 0.008929 |
def penalize_boundary_complexity(shp, w=20, mask=None, C=0.5):
"""Encourage the boundaries of an image to have less variation and of color C.
Args:
shp: shape of T("input") because this may not be known.
w: width of boundary to penalize. Ignored if mask is set.
mask: mask describing what area should be... | [
"def",
"penalize_boundary_complexity",
"(",
"shp",
",",
"w",
"=",
"20",
",",
"mask",
"=",
"None",
",",
"C",
"=",
"0.5",
")",
":",
"def",
"inner",
"(",
"T",
")",
":",
"arr",
"=",
"T",
"(",
"\"input\"",
")",
"# print shp",
"if",
"mask",
"is",
"None",... | 23.703704 | 0.012012 |
def get_simulant_creator(self) -> Callable[[int, Union[Mapping[str, Any], None]], pd.Index]:
"""Grabs a reference to the function that creates new simulants (adds rows to the state table).
Returns
-------
Callable
The simulant creator function. The creator function takes the ... | [
"def",
"get_simulant_creator",
"(",
"self",
")",
"->",
"Callable",
"[",
"[",
"int",
",",
"Union",
"[",
"Mapping",
"[",
"str",
",",
"Any",
"]",
",",
"None",
"]",
"]",
",",
"pd",
".",
"Index",
"]",
":",
"return",
"self",
".",
"_population_manager",
"."... | 62.866667 | 0.010449 |
def search_hashes(
self,
hash_prefix=None,
threat_types=None,
retry=google.api_core.gapic_v1.method.DEFAULT,
timeout=google.api_core.gapic_v1.method.DEFAULT,
metadata=None,
):
"""
Gets the full hashes that match the requested hash prefix.
This ... | [
"def",
"search_hashes",
"(",
"self",
",",
"hash_prefix",
"=",
"None",
",",
"threat_types",
"=",
"None",
",",
"retry",
"=",
"google",
".",
"api_core",
".",
"gapic_v1",
".",
"method",
".",
"DEFAULT",
",",
"timeout",
"=",
"google",
".",
"api_core",
".",
"ga... | 45.370968 | 0.002436 |
def classify_segmented_recording(recording, result_format=None):
"""Use this function if you are sure you have a single symbol.
Parameters
----------
recording : string
The recording in JSON format
Returns
-------
list of dictionaries
Each dictionary contains the keys 'symb... | [
"def",
"classify_segmented_recording",
"(",
"recording",
",",
"result_format",
"=",
"None",
")",
":",
"global",
"single_symbol_classifier",
"if",
"single_symbol_classifier",
"is",
"None",
":",
"single_symbol_classifier",
"=",
"SingleClassificer",
"(",
")",
"return",
"si... | 32.722222 | 0.00165 |
def _run_svn(cmd, cwd, user, username, password, opts, **kwargs):
'''
Execute svn
return the output of the command
cmd
The command to run.
cwd
The path to the Subversion repository
user
Run svn as a user other than what the minion runs as
username
Connect ... | [
"def",
"_run_svn",
"(",
"cmd",
",",
"cwd",
",",
"user",
",",
"username",
",",
"password",
",",
"opts",
",",
"*",
"*",
"kwargs",
")",
":",
"cmd",
"=",
"[",
"'svn'",
",",
"'--non-interactive'",
",",
"cmd",
"]",
"options",
"=",
"list",
"(",
"opts",
")... | 23.75 | 0.001838 |
def post_vars(self):
""" Parse request payload and return POST-vars
:return: None or dictionary of names and tuples of values
"""
if self.method() != 'POST':
raise RuntimeError('Unable to return post vars for non-get method')
content_type = self.content_type()
if content_type is None or content_type.lo... | [
"def",
"post_vars",
"(",
"self",
")",
":",
"if",
"self",
".",
"method",
"(",
")",
"!=",
"'POST'",
":",
"raise",
"RuntimeError",
"(",
"'Unable to return post vars for non-get method'",
")",
"content_type",
"=",
"self",
".",
"content_type",
"(",
")",
"if",
"cont... | 42 | 0.023288 |
def delete_from_directory_by_hashes(cache_type, hashes):
"""
Deletes all cache files corresponding to a list of hashes from a directory
:param str directory: The type of cache to delete files for.
:param list(str) hashes: The hashes to delete the files for
"""
global CACHE_
if hashes == '*... | [
"def",
"delete_from_directory_by_hashes",
"(",
"cache_type",
",",
"hashes",
")",
":",
"global",
"CACHE_",
"if",
"hashes",
"==",
"'*'",
":",
"CACHE_",
"[",
"cache_type",
"]",
"=",
"{",
"}",
"for",
"h",
"in",
"hashes",
":",
"if",
"h",
"in",
"CACHE_",
"[",
... | 30.066667 | 0.002151 |
def launch_image(
# players info
player: Player,
nth_player: int,
num_players: int,
# game settings
headless: bool,
game_name: str,
map_name: str,
game_type: GameType,
game_speed: int,
timeout: Optional[int],
hide_names: bo... | [
"def",
"launch_image",
"(",
"# players info",
"player",
":",
"Player",
",",
"nth_player",
":",
"int",
",",
"num_players",
":",
"int",
",",
"# game settings",
"headless",
":",
"bool",
",",
"game_name",
":",
"str",
",",
"map_name",
":",
"str",
",",
"game_type"... | 33.7125 | 0.001981 |
def approximating_model(self, beta, T, Z, R, Q, h_approx, data):
""" Creates approximating Gaussian state space model for Poisson measurement density
Parameters
----------
beta : np.array
Contains untransformed starting values for latent variables
T,... | [
"def",
"approximating_model",
"(",
"self",
",",
"beta",
",",
"T",
",",
"Z",
",",
"R",
",",
"Q",
",",
"h_approx",
",",
"data",
")",
":",
"H",
"=",
"np",
".",
"ones",
"(",
"data",
".",
"shape",
"[",
"0",
"]",
")",
"mu",
"=",
"np",
".",
"zeros",... | 29.878049 | 0.011858 |
def write_packages(self, reqs_file):
"""
Dump the packages in the catalog in a requirements file
"""
write_file_lines(reqs_file, ('{}\n'.format(package) for package in self.packages)) | [
"def",
"write_packages",
"(",
"self",
",",
"reqs_file",
")",
":",
"write_file_lines",
"(",
"reqs_file",
",",
"(",
"'{}\\n'",
".",
"format",
"(",
"package",
")",
"for",
"package",
"in",
"self",
".",
"packages",
")",
")"
] | 42.2 | 0.013953 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.