text stringlengths 75 104k | code_tokens list | avg_line_len float64 7.91 980 | score float64 0 0.18 |
|---|---|---|---|
def in_telephones(objet, pattern):
""" abstractSearch dans une liste de téléphones."""
objet = objet or []
if pattern == '' or not objet:
return False
return max(bool(re.search(pattern, t)) for t in objet) | [
"def",
"in_telephones",
"(",
"objet",
",",
"pattern",
")",
":",
"objet",
"=",
"objet",
"or",
"[",
"]",
"if",
"pattern",
"==",
"''",
"or",
"not",
"objet",
":",
"return",
"False",
"return",
"max",
"(",
"bool",
"(",
"re",
".",
"search",
"(",
"pattern",
... | 40.666667 | 0.008032 |
def arg_type(arg_names, kwargs):
"""
Returns a hashable summary of the types of arg_names within kwargs.
:param arg_names: tuple containing names of relevant arguments
:param kwargs: dict mapping string argument names to values.
These must be values for which we can create a tf placeholder.
Currently su... | [
"def",
"arg_type",
"(",
"arg_names",
",",
"kwargs",
")",
":",
"assert",
"isinstance",
"(",
"arg_names",
",",
"tuple",
")",
"passed",
"=",
"tuple",
"(",
"name",
"in",
"kwargs",
"for",
"name",
"in",
"arg_names",
")",
"passed_and_not_none",
"=",
"[",
"]",
"... | 37.772727 | 0.010557 |
def init_write_line(self):
"""init_write_line() initializes fields relevant to output generation"""
format_list = self._format_list
output_info = self.gen_output_fmt(format_list)
self._output_fmt = "".join([sub[0] for sub in output_info])
self._out_gen_fmt = [sub[1] for sub in ou... | [
"def",
"init_write_line",
"(",
"self",
")",
":",
"format_list",
"=",
"self",
".",
"_format_list",
"output_info",
"=",
"self",
".",
"gen_output_fmt",
"(",
"format_list",
")",
"self",
".",
"_output_fmt",
"=",
"\"\"",
".",
"join",
"(",
"[",
"sub",
"[",
"0",
... | 57.875 | 0.010638 |
def __check_suc_cookie(self, components):
'''
This is only called if we're on a known sucuri-"protected" site.
As such, if we do *not* have a sucuri cloudproxy cookie, we can assume we need to
do the normal WAF step-through.
'''
netloc = components.netloc.lower()
for cookie in self.cj:
if cookie.domai... | [
"def",
"__check_suc_cookie",
"(",
"self",
",",
"components",
")",
":",
"netloc",
"=",
"components",
".",
"netloc",
".",
"lower",
"(",
")",
"for",
"cookie",
"in",
"self",
".",
"cj",
":",
"if",
"cookie",
".",
"domain_specified",
"and",
"(",
"cookie",
".",
... | 47.1875 | 0.027273 |
def traverse_preorder(self, leaves=True, internal=True):
'''Perform a preorder traversal starting at this ``Node`` object
Args:
``leaves`` (``bool``): ``True`` to include leaves, otherwise ``False``
``internal`` (``bool``): ``True`` to include internal nodes, otherwise ``False`... | [
"def",
"traverse_preorder",
"(",
"self",
",",
"leaves",
"=",
"True",
",",
"internal",
"=",
"True",
")",
":",
"s",
"=",
"deque",
"(",
")",
"s",
".",
"append",
"(",
"self",
")",
"while",
"len",
"(",
"s",
")",
"!=",
"0",
":",
"n",
"=",
"s",
".",
... | 38.5 | 0.009058 |
def list_(properties='size,alloc,free,cap,frag,health', zpool=None, parsable=True):
'''
.. versionadded:: 2015.5.0
Return information about (all) storage pools
zpool : string
optional name of storage pool
properties : string
comma-separated list of properties to list
parsable... | [
"def",
"list_",
"(",
"properties",
"=",
"'size,alloc,free,cap,frag,health'",
",",
"zpool",
"=",
"None",
",",
"parsable",
"=",
"True",
")",
":",
"ret",
"=",
"OrderedDict",
"(",
")",
"## update properties",
"# NOTE: properties should be a list",
"if",
"not",
"isinstan... | 27.094737 | 0.001874 |
def run(self, group_x=1, group_y=1, group_z=1) -> None:
'''
Run the compute shader.
Args:
group_x (int): The number of work groups to be launched in the X dimension.
group_y (int): The number of work groups to be launched in the Y dimension.
... | [
"def",
"run",
"(",
"self",
",",
"group_x",
"=",
"1",
",",
"group_y",
"=",
"1",
",",
"group_z",
"=",
"1",
")",
"->",
"None",
":",
"return",
"self",
".",
"mglo",
".",
"run",
"(",
"group_x",
",",
"group_y",
",",
"group_z",
")"
] | 41.545455 | 0.010707 |
def _get_voronoi_poly_points(vert_index_list, voronoi_vertices,
voronoi_centroid):
"""
This function returns the corner points for a
polygon from scipy voronoi information
"""
voronoi_poly_points = []
if -1 not in vert_index_list and len(vert_index_list) > 3:
... | [
"def",
"_get_voronoi_poly_points",
"(",
"vert_index_list",
",",
"voronoi_vertices",
",",
"voronoi_centroid",
")",
":",
"voronoi_poly_points",
"=",
"[",
"]",
"if",
"-",
"1",
"not",
"in",
"vert_index_list",
"and",
"len",
"(",
"vert_index_list",
")",
">",
"3",
":",... | 42.362069 | 0.000398 |
def resolve_path(self, file_path, allow_fd=False, raw_io=True):
"""Follow a path, resolving symlinks.
ResolvePath traverses the filesystem along the specified file path,
resolving file names and symbolic links until all elements of the path
are exhausted, or we reach a file which does n... | [
"def",
"resolve_path",
"(",
"self",
",",
"file_path",
",",
"allow_fd",
"=",
"False",
",",
"raw_io",
"=",
"True",
")",
":",
"if",
"(",
"allow_fd",
"and",
"sys",
".",
"version_info",
">=",
"(",
"3",
",",
"3",
")",
"and",
"isinstance",
"(",
"file_path",
... | 41.694915 | 0.000794 |
def is_readable(path):
'''
Returns True if provided file or directory exists and can be read with the current user.
Returns False otherwise.
'''
return os.access(os.path.abspath(path), os.R_OK) | [
"def",
"is_readable",
"(",
"path",
")",
":",
"return",
"os",
".",
"access",
"(",
"os",
".",
"path",
".",
"abspath",
"(",
"path",
")",
",",
"os",
".",
"R_OK",
")"
] | 34.666667 | 0.00939 |
def make_structure_from_geos(geos):
'''Creates a structure out of a list of geometry objects.'''
model_structure=initialize_res(geos[0])
for i in range(1,len(geos)):
model_structure=add_residue(model_structure, geos[i])
return model_structure | [
"def",
"make_structure_from_geos",
"(",
"geos",
")",
":",
"model_structure",
"=",
"initialize_res",
"(",
"geos",
"[",
"0",
"]",
")",
"for",
"i",
"in",
"range",
"(",
"1",
",",
"len",
"(",
"geos",
")",
")",
":",
"model_structure",
"=",
"add_residue",
"(",
... | 37.285714 | 0.014981 |
def endpoint_search(filter_fulltext, filter_owner_id, filter_scope):
"""
Executor for `globus endpoint search`
"""
if filter_scope == "all" and not filter_fulltext:
raise click.UsageError(
"When searching all endpoints (--filter-scope=all, the default), "
"a full-text sea... | [
"def",
"endpoint_search",
"(",
"filter_fulltext",
",",
"filter_owner_id",
",",
"filter_scope",
")",
":",
"if",
"filter_scope",
"==",
"\"all\"",
"and",
"not",
"filter_fulltext",
":",
"raise",
"click",
".",
"UsageError",
"(",
"\"When searching all endpoints (--filter-scop... | 30.724138 | 0.001088 |
def expand_groups(grp):
"""Expand group names.
Args:
grp (string): group names to expand
Returns:
list of groups
Examples:
* grp[1-3] will be expanded to [grp1, grp2, grp3]
* grp1 will be expanded to [grp1]
"""
p = re.compile(r"(?P<name>.+)\[(?P<start>\d+)-(?P... | [
"def",
"expand_groups",
"(",
"grp",
")",
":",
"p",
"=",
"re",
".",
"compile",
"(",
"r\"(?P<name>.+)\\[(?P<start>\\d+)-(?P<end>\\d+)\\]\"",
")",
"m",
"=",
"p",
".",
"match",
"(",
"grp",
")",
"if",
"m",
"is",
"not",
"None",
":",
"s",
"=",
"int",
"(",
"m"... | 23.608696 | 0.00177 |
def make_funcs(dataset, setdir, store):
"""Functions available for listing columns and filters."""
return {
'cat': lambda *lists: [x for lst in lists for x in lst],
'comments': lambda: None,
'detail_route': detail_route,
'format': lambda fmt, *args: fmt.format(*args),
'ge... | [
"def",
"make_funcs",
"(",
"dataset",
",",
"setdir",
",",
"store",
")",
":",
"return",
"{",
"'cat'",
":",
"lambda",
"*",
"lists",
":",
"[",
"x",
"for",
"lst",
"in",
"lists",
"for",
"x",
"in",
"lst",
"]",
",",
"'comments'",
":",
"lambda",
":",
"None"... | 38.772727 | 0.001144 |
def grad(self, x):
r"""Compute the gradient of a signal defined on the vertices.
The gradient :math:`y` of a signal :math:`x` is defined as
.. math:: y = \nabla_\mathcal{G} x = D^\top x,
where :math:`D` is the differential operator :attr:`D`.
The value of the gradient on the ... | [
"def",
"grad",
"(",
"self",
",",
"x",
")",
":",
"x",
"=",
"self",
".",
"_check_signal",
"(",
"x",
")",
"return",
"self",
".",
"D",
".",
"T",
".",
"dot",
"(",
"x",
")"
] | 32.74026 | 0.00077 |
def _sync_table(self, columns):
"""Lazy load, create or adapt the table structure in the database."""
if self._table is None:
# Load an existing table from the database.
self._reflect_table()
if self._table is None:
# Create the table with an initial set of co... | [
"def",
"_sync_table",
"(",
"self",
",",
"columns",
")",
":",
"if",
"self",
".",
"_table",
"is",
"None",
":",
"# Load an existing table from the database.",
"self",
".",
"_reflect_table",
"(",
")",
"if",
"self",
".",
"_table",
"is",
"None",
":",
"# Create the t... | 52.243243 | 0.001524 |
def house(self):
""" Returns the object's house. """
house = self.chart.houses.getObjectHouse(self.obj)
return house | [
"def",
"house",
"(",
"self",
")",
":",
"house",
"=",
"self",
".",
"chart",
".",
"houses",
".",
"getObjectHouse",
"(",
"self",
".",
"obj",
")",
"return",
"house"
] | 34.25 | 0.014286 |
def create_download_specifications(ctx_cli_options, config):
# type: (dict, dict) -> List[blobxfer.models.download.Specification]
"""Create a list of Download Specification objects from configuration
:param dict ctx_cli_options: cli options
:param dict config: config dict
:rtype: list
:return: l... | [
"def",
"create_download_specifications",
"(",
"ctx_cli_options",
",",
"config",
")",
":",
"# type: (dict, dict) -> List[blobxfer.models.download.Specification]",
"cli_conf",
"=",
"ctx_cli_options",
"[",
"ctx_cli_options",
"[",
"'_action'",
"]",
"]",
"cli_options",
"=",
"cli_c... | 44.380531 | 0.000195 |
def as_xml(self,parent):
"""Create vcard-tmp XML representation of the field.
:Parameters:
- `parent`: parent node for the element
:Types:
- `parent`: `libxml2.xmlNode`
:return: xml node with the field data.
:returntype: `libxml2.xmlNode`"""
n=pa... | [
"def",
"as_xml",
"(",
"self",
",",
"parent",
")",
":",
"n",
"=",
"parent",
".",
"newChild",
"(",
"None",
",",
"\"TEL\"",
",",
"None",
")",
"for",
"t",
"in",
"(",
"\"home\"",
",",
"\"work\"",
",",
"\"voice\"",
",",
"\"fax\"",
",",
"\"pager\"",
",",
... | 36.294118 | 0.034755 |
def get_feed(self, buckets=None, since=None, results=15, start=0):
"""
Returns feed (news, blogs, reviews, audio, video) for the catalog artists; response depends on requested buckets
Args:
Kwargs:
buckets (list): A list of strings specifying which feed items to retrieve
... | [
"def",
"get_feed",
"(",
"self",
",",
"buckets",
"=",
"None",
",",
"since",
"=",
"None",
",",
"results",
"=",
"15",
",",
"start",
"=",
"0",
")",
":",
"kwargs",
"=",
"{",
"}",
"kwargs",
"[",
"'bucket'",
"]",
"=",
"buckets",
"or",
"[",
"]",
"if",
... | 41.487179 | 0.019324 |
def writers(self):
"""
Return a list of `(fd, data)` tuples for every FD registered for
transmit readiness.
"""
return list((fd, data) for fd, (data, gen) in self._wfds.items()) | [
"def",
"writers",
"(",
"self",
")",
":",
"return",
"list",
"(",
"(",
"fd",
",",
"data",
")",
"for",
"fd",
",",
"(",
"data",
",",
"gen",
")",
"in",
"self",
".",
"_wfds",
".",
"items",
"(",
")",
")"
] | 35.333333 | 0.009217 |
def position(msg0, msg1, t0, t1, lat_ref=None, lon_ref=None):
"""Decode position from a pair of even and odd position message
(works with both airborne and surface position messages)
Args:
msg0 (string): even message (28 bytes hexadecimal string)
msg1 (string): odd message (28 bytes hexadec... | [
"def",
"position",
"(",
"msg0",
",",
"msg1",
",",
"t0",
",",
"t1",
",",
"lat_ref",
"=",
"None",
",",
"lon_ref",
"=",
"None",
")",
":",
"tc0",
"=",
"typecode",
"(",
"msg0",
")",
"tc1",
"=",
"typecode",
"(",
"msg1",
")",
"if",
"(",
"5",
"<=",
"tc... | 37.176471 | 0.010023 |
def fpid_query(duration, fpdata, metadata=None):
"""Send fingerprint data to Last.fm to get the corresponding
fingerprint ID, which can then be used to fetch metadata.
duration is the length of the track in (integral) seconds.
If metadata is provided, it is a dictionary with three optional
fields re... | [
"def",
"fpid_query",
"(",
"duration",
",",
"fpdata",
",",
"metadata",
"=",
"None",
")",
":",
"metadata",
"=",
"metadata",
"or",
"{",
"}",
"params",
"=",
"{",
"'artist'",
":",
"metadata",
".",
"get",
"(",
"'artist'",
",",
"''",
")",
",",
"'album'",
":... | 36.461538 | 0.00137 |
def preproc_data(data, gene_subset=False, **kwargs):
"""
basic data preprocessing before running gap score
Assumes that data is a matrix of shape (genes, cells).
Returns a matrix of shape (cells, 8), using the first 8 SVD
components. Why 8? It's an arbitrary selection...
"""
import uncurl
... | [
"def",
"preproc_data",
"(",
"data",
",",
"gene_subset",
"=",
"False",
",",
"*",
"*",
"kwargs",
")",
":",
"import",
"uncurl",
"from",
"uncurl",
".",
"preprocessing",
"import",
"log1p",
",",
"cell_normalize",
"from",
"sklearn",
".",
"decomposition",
"import",
... | 37 | 0.001387 |
def locateChild(self, context, segments):
"""
Return a statically defined child or a child defined by a sessionless
site root plugin or an avatar from guard.
"""
shortcut = getattr(self, 'child_' + segments[0], None)
if shortcut:
res = shortcut(context)
... | [
"def",
"locateChild",
"(",
"self",
",",
"context",
",",
"segments",
")",
":",
"shortcut",
"=",
"getattr",
"(",
"self",
",",
"'child_'",
"+",
"segments",
"[",
"0",
"]",
",",
"None",
")",
"if",
"shortcut",
":",
"res",
"=",
"shortcut",
"(",
"context",
"... | 39 | 0.002275 |
def _create_application(self):
"""
Create an `Application` instance.
"""
return Application(
input=self.input,
output=self.output,
layout=self.ptpython_layout.layout,
key_bindings=merge_key_bindings([
load_python_bindings(se... | [
"def",
"_create_application",
"(",
"self",
")",
":",
"return",
"Application",
"(",
"input",
"=",
"self",
".",
"input",
",",
"output",
"=",
"self",
".",
"output",
",",
"layout",
"=",
"self",
".",
"ptpython_layout",
".",
"layout",
",",
"key_bindings",
"=",
... | 44.5 | 0.002357 |
def add_orthologs_by_gene_group(self, graph, gene_ids):
"""
This will get orthologies between human and other vertebrate genomes
based on the gene_group annotation pipeline from NCBI.
More information 9can be learned here:
http://www.ncbi.nlm.nih.gov/news/03-13-2014-gene-provides... | [
"def",
"add_orthologs_by_gene_group",
"(",
"self",
",",
"graph",
",",
"gene_ids",
")",
":",
"src_key",
"=",
"'gene_group'",
"LOG",
".",
"info",
"(",
"\"getting gene groups\"",
")",
"src_file",
"=",
"'/'",
".",
"join",
"(",
"(",
"self",
".",
"rawdir",
",",
... | 42.441176 | 0.000903 |
def get_connected_sites(self, n):
"""
Returns a named tuple of neighbors of site n:
periodic_site, jimage, index, weight.
Index is the index of the corresponding site
in the original structure, weight can be
None if not defined.
:param n: index of Site in Molecule... | [
"def",
"get_connected_sites",
"(",
"self",
",",
"n",
")",
":",
"connected_sites",
"=",
"set",
"(",
")",
"out_edges",
"=",
"[",
"(",
"u",
",",
"v",
",",
"d",
")",
"for",
"u",
",",
"v",
",",
"d",
"in",
"self",
".",
"graph",
".",
"out_edges",
"(",
... | 37.1875 | 0.001638 |
def api_upload(service, encData, encMeta, keys):
'''
Uploads data to Send.
Caution! Data is uploaded as given, this function will not encrypt it for you
'''
service += 'api/upload'
files = requests_toolbelt.MultipartEncoder(fields={'file': ('blob', encData, 'application/octet-stream') })
... | [
"def",
"api_upload",
"(",
"service",
",",
"encData",
",",
"encMeta",
",",
"keys",
")",
":",
"service",
"+=",
"'api/upload'",
"files",
"=",
"requests_toolbelt",
".",
"MultipartEncoder",
"(",
"fields",
"=",
"{",
"'file'",
":",
"(",
"'blob'",
",",
"encData",
... | 40.206897 | 0.01005 |
def setupLogFile(self):
"""Set up the logging file for a new session- include date and some whitespace"""
self.logWrite("\n###############################################")
self.logWrite("calcpkg.py log from " + str(datetime.datetime.now()))
self.changeLogging(True) | [
"def",
"setupLogFile",
"(",
"self",
")",
":",
"self",
".",
"logWrite",
"(",
"\"\\n###############################################\"",
")",
"self",
".",
"logWrite",
"(",
"\"calcpkg.py log from \"",
"+",
"str",
"(",
"datetime",
".",
"datetime",
".",
"now",
"(",
")",... | 54 | 0.025547 |
def replace_lines(regexer, handler, lines):
"""Uses replacement handler to perform replacements on lines of text
First we strip off all whitespace
We run the replacement on a clean 'content' string
Finally we replace the original content with the replaced version
This ensures that we retain the cor... | [
"def",
"replace_lines",
"(",
"regexer",
",",
"handler",
",",
"lines",
")",
":",
"result",
"=",
"[",
"]",
"for",
"line",
"in",
"lines",
":",
"content",
"=",
"line",
".",
"strip",
"(",
")",
"replaced",
"=",
"regexer",
".",
"sub",
"(",
"handler",
",",
... | 39.142857 | 0.001783 |
def convert_unsqueeze(params, w_name, scope_name, inputs, layers, weights, names):
"""
Convert unsqueeze operation.
Args:
params: dictionary with layer parameters
w_name: name prefix in state_dict
scope_name: pytorch scope name
inputs: pytorch node inputs
layers: dic... | [
"def",
"convert_unsqueeze",
"(",
"params",
",",
"w_name",
",",
"scope_name",
",",
"inputs",
",",
"layers",
",",
"weights",
",",
"names",
")",
":",
"print",
"(",
"'Converting unsqueeze ...'",
")",
"if",
"names",
"==",
"'short'",
":",
"tf_name",
"=",
"'UNSQ'",... | 30.357143 | 0.002281 |
def http_method(self, data):
"""The HTTP Method for this resource request."""
data = data.upper()
if data in ['DELETE', 'GET', 'POST', 'PUT']:
self._request.http_method = data
self._http_method = data | [
"def",
"http_method",
"(",
"self",
",",
"data",
")",
":",
"data",
"=",
"data",
".",
"upper",
"(",
")",
"if",
"data",
"in",
"[",
"'DELETE'",
",",
"'GET'",
",",
"'POST'",
",",
"'PUT'",
"]",
":",
"self",
".",
"_request",
".",
"http_method",
"=",
"data... | 40.5 | 0.008065 |
def vm_attach(name, kwargs=None, call=None):
'''
Attaches a new disk to the given virtual machine.
.. versionadded:: 2016.3.0
name
The name of the VM for which to attach the new disk.
path
The path to a file containing a single disk vector attribute.
Syntax within the file... | [
"def",
"vm_attach",
"(",
"name",
",",
"kwargs",
"=",
"None",
",",
"call",
"=",
"None",
")",
":",
"if",
"call",
"!=",
"'action'",
":",
"raise",
"SaltCloudSystemExit",
"(",
"'The vm_attach action must be called with -a or --action.'",
")",
"if",
"kwargs",
"is",
"N... | 27.338462 | 0.000543 |
def from_df(cls, df, **kwargs):
"""
DataFrame must have the right columns.
these are: name, band, resolution, mag, e_mag, separation, pa
"""
tree = cls(**kwargs)
for (n,b), g in df.groupby(['name','band']):
#g.sort('separation', inplace=True) #ensures that t... | [
"def",
"from_df",
"(",
"cls",
",",
"df",
",",
"*",
"*",
"kwargs",
")",
":",
"tree",
"=",
"cls",
"(",
"*",
"*",
"kwargs",
")",
"for",
"(",
"n",
",",
"b",
")",
",",
"g",
"in",
"df",
".",
"groupby",
"(",
"[",
"'name'",
",",
"'band'",
"]",
")",... | 33.666667 | 0.019257 |
def detailed_tokens(tokenizer, text):
"""Format Mecab output into a nice data structure, based on Janome."""
node = tokenizer.parseToNode(text)
node = node.next # first node is beginning of sentence and empty, skip it
words = []
while node.posid != 0:
surface = node.surface
base = s... | [
"def",
"detailed_tokens",
"(",
"tokenizer",
",",
"text",
")",
":",
"node",
"=",
"tokenizer",
".",
"parseToNode",
"(",
"text",
")",
"node",
"=",
"node",
".",
"next",
"# first node is beginning of sentence and empty, skip it",
"words",
"=",
"[",
"]",
"while",
"nod... | 40.411765 | 0.001422 |
def _remove_ellipsis(self, index, numrows, numcols, numbands):
"""
resolve the first ellipsis in the index so that it references the image
Parameters
----------
index : tuple
tuple of index arguments, presumably one of them is the Ellipsis
numrows, numcols, n... | [
"def",
"_remove_ellipsis",
"(",
"self",
",",
"index",
",",
"numrows",
",",
"numcols",
",",
"numbands",
")",
":",
"# Remove the first ellipsis we find.",
"rows",
"=",
"slice",
"(",
"0",
",",
"numrows",
")",
"cols",
"=",
"slice",
"(",
"0",
",",
"numcols",
")... | 33.975 | 0.001431 |
def ajax_required(func):
# taken from djangosnippets.org
"""
AJAX request required decorator
use it in your views:
@ajax_required
def my_view(request):
....
"""
def wrap(request, *args, **kwargs):
if not request.is_ajax():
return HttpResponseBadRequest
... | [
"def",
"ajax_required",
"(",
"func",
")",
":",
"# taken from djangosnippets.org",
"def",
"wrap",
"(",
"request",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"if",
"not",
"request",
".",
"is_ajax",
"(",
")",
":",
"return",
"HttpResponseBadRequest",
... | 23.611111 | 0.002262 |
def request_log_level(self, req, msg):
"""Query or set the current logging level.
Parameters
----------
level : {'all', 'trace', 'debug', 'info', 'warn', 'error', 'fatal', \
'off'}, optional
Name of the logging level to set the device server to (the default
... | [
"def",
"request_log_level",
"(",
"self",
",",
"req",
",",
"msg",
")",
":",
"if",
"msg",
".",
"arguments",
":",
"try",
":",
"self",
".",
"log",
".",
"set_log_level_by_name",
"(",
"msg",
".",
"arguments",
"[",
"0",
"]",
")",
"except",
"ValueError",
",",
... | 29.057143 | 0.001903 |
def set_attribute_label(series, resource_labels, attribute_key,
canonical_key=None, label_value_prefix=''):
"""Set a label to timeseries that can be used for monitoring
:param series: TimeSeries object based on view data
:param resource_labels: collection of labels
:param attribu... | [
"def",
"set_attribute_label",
"(",
"series",
",",
"resource_labels",
",",
"attribute_key",
",",
"canonical_key",
"=",
"None",
",",
"label_value_prefix",
"=",
"''",
")",
":",
"if",
"attribute_key",
"in",
"resource_labels",
":",
"if",
"canonical_key",
"is",
"None",
... | 47.466667 | 0.001377 |
def gen_gmfs(self):
"""
Compute the GMFs for the given realization and
yields arrays of the dtype (sid, eid, imti, gmv), one for rupture
"""
self.sig_eps = []
for computer in self.computers:
rup = computer.rupture
sids = computer.sids
e... | [
"def",
"gen_gmfs",
"(",
"self",
")",
":",
"self",
".",
"sig_eps",
"=",
"[",
"]",
"for",
"computer",
"in",
"self",
".",
"computers",
":",
"rup",
"=",
"computer",
".",
"rupture",
"sids",
"=",
"computer",
".",
"sids",
"eids_by_rlz",
"=",
"rup",
".",
"ge... | 45.95122 | 0.00104 |
def open(cls, blob, username, password):
"""Creates a vault from a blob object"""
return cls(blob, blob.encryption_key(username, password)) | [
"def",
"open",
"(",
"cls",
",",
"blob",
",",
"username",
",",
"password",
")",
":",
"return",
"cls",
"(",
"blob",
",",
"blob",
".",
"encryption_key",
"(",
"username",
",",
"password",
")",
")"
] | 51 | 0.012903 |
def set_field(self, field_name, field_val=None):
"""
set a field into .fields attribute
n insert/update queries, these are the fields that will be inserted/updated into the db
"""
field_name = self._normalize_field_name(field_name)
self.fields_set.append(field_name, [fie... | [
"def",
"set_field",
"(",
"self",
",",
"field_name",
",",
"field_val",
"=",
"None",
")",
":",
"field_name",
"=",
"self",
".",
"_normalize_field_name",
"(",
"field_name",
")",
"self",
".",
"fields_set",
".",
"append",
"(",
"field_name",
",",
"[",
"field_name",... | 39.111111 | 0.008333 |
def Upload(cls, filename):
""" 文件上传, 非原生input
@todo: some upload.exe not prepared
@param file: 文件名(文件必须存在在工程resource目录下), upload.exe工具放在工程tools目录下
"""
raise Exception("to do")
TOOLS_PATH = ""
RESOURCE_PATH = ""
tool_4path = os.path.... | [
"def",
"Upload",
"(",
"cls",
",",
"filename",
")",
":",
"raise",
"Exception",
"(",
"\"to do\"",
")",
"TOOLS_PATH",
"=",
"\"\"",
"RESOURCE_PATH",
"=",
"\"\"",
"tool_4path",
"=",
"os",
".",
"path",
".",
"join",
"(",
"TOOLS_PATH",
",",
"\"upload.exe\"",
")",
... | 36.555556 | 0.008889 |
def common_options(*args, **kwargs):
"""
This is a multi-purpose decorator for applying a "base" set of options
shared by all commands.
It can be applied either directly, or given keyword arguments.
Usage:
>>> @common_options
>>> def mycommand(abc, xyz):
>>> ...
or
>>> @c... | [
"def",
"common_options",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"def",
"decorate",
"(",
"f",
",",
"*",
"*",
"kwargs",
")",
":",
"\"\"\"\n Work of actually decorating a function -- wrapped in here because we\n want to dispatch depending on how `co... | 27.775 | 0.00087 |
def priceItems(items):
""" Takes a list of Item objects and returns a list of Item objects with respective prices modified
Uses the given list of item objects to formulate a query to the item database. Uses the returned
results to populate each item in the list with its respective price... | [
"def",
"priceItems",
"(",
"items",
")",
":",
"retItems",
"=",
"[",
"]",
"sendItems",
"=",
"[",
"]",
"for",
"item",
"in",
"items",
":",
"sendItems",
".",
"append",
"(",
"item",
".",
"name",
")",
"resp",
"=",
"CodexAPI",
".",
"searchMany",
"(",
"sendIt... | 35.304348 | 0.013189 |
def register(devices, params, facet):
"""
Interactively registers a single U2F device, given the RegistrationRequest.
"""
for device in devices[:]:
try:
device.open()
except:
devices.remove(device)
sys.stderr.write('\nTouch the U2F device you wish to register... | [
"def",
"register",
"(",
"devices",
",",
"params",
",",
"facet",
")",
":",
"for",
"device",
"in",
"devices",
"[",
":",
"]",
":",
"try",
":",
"device",
".",
"open",
"(",
")",
"except",
":",
"devices",
".",
"remove",
"(",
"device",
")",
"sys",
".",
... | 32.090909 | 0.001833 |
def _record2card(self, record):
"""
when we add new records they don't have a card,
this sort of fakes it up similar to what cfitsio
does, just for display purposes. e.g.
DBL = 23.299843
LNG = 3423432
KEYSNC = 'hello ... | [
"def",
"_record2card",
"(",
"self",
",",
"record",
")",
":",
"name",
"=",
"record",
"[",
"'name'",
"]",
"value",
"=",
"record",
"[",
"'value'",
"]",
"v_isstring",
"=",
"isstring",
"(",
"value",
")",
"if",
"name",
"==",
"'COMMENT'",
":",
"# card = 'COMMEN... | 32.955224 | 0.00088 |
def put_comments(self, resource, comment, timeout=None):
""" Post a comment on a file or URL.
The initial idea of VirusTotal Community was that users should be able to make comments on files and URLs,
the comments may be malware analyses, false positive flags, disinfection instructions, etc.
... | [
"def",
"put_comments",
"(",
"self",
",",
"resource",
",",
"comment",
",",
"timeout",
"=",
"None",
")",
":",
"params",
"=",
"{",
"'apikey'",
":",
"self",
".",
"api_key",
",",
"'resource'",
":",
"resource",
",",
"'comment'",
":",
"comment",
"}",
"try",
"... | 59.653846 | 0.008883 |
def delete(self, request, bot_id, id, format=None):
"""
Delete existing Messenger chat state
---
responseMessages:
- code: 401
message: Not authenticated
"""
return super(MessengerChatStateDetail, self).delete(request, bot_id, id, format) | [
"def",
"delete",
"(",
"self",
",",
"request",
",",
"bot_id",
",",
"id",
",",
"format",
"=",
"None",
")",
":",
"return",
"super",
"(",
"MessengerChatStateDetail",
",",
"self",
")",
".",
"delete",
"(",
"request",
",",
"bot_id",
",",
"id",
",",
"format",
... | 33.777778 | 0.009615 |
def _adjusted_rand_index(reference_indices, estimated_indices):
"""Compute the Rand index, adjusted for change.
Parameters
----------
reference_indices : np.ndarray
Array of reference indices
estimated_indices : np.ndarray
Array of estimated indices
Returns
-------
ari ... | [
"def",
"_adjusted_rand_index",
"(",
"reference_indices",
",",
"estimated_indices",
")",
":",
"n_samples",
"=",
"len",
"(",
"reference_indices",
")",
"ref_classes",
"=",
"np",
".",
"unique",
"(",
"reference_indices",
")",
"est_classes",
"=",
"np",
".",
"unique",
... | 38.045455 | 0.000582 |
def register_action(self, relative_directory, file_pattern, action_function):
"""
Add/register an "action".
Args:
relative_directory (str): Relative directory from root directory. Separator is OS dependent. For instance,
under linux, you can register the following:
... | [
"def",
"register_action",
"(",
"self",
",",
"relative_directory",
",",
"file_pattern",
",",
"action_function",
")",
":",
"# test if directory exists",
"if",
"not",
"os",
".",
"path",
".",
"isdir",
"(",
"os",
".",
"path",
".",
"join",
"(",
"self",
".",
"__roo... | 48.034483 | 0.008445 |
def create_database(self, dbname, partitioned=False, **kwargs):
"""
Creates a new database on the remote server with the name provided
and adds the new database object to the client's locally cached
dictionary before returning it to the caller. The method will
optionally throw a... | [
"def",
"create_database",
"(",
"self",
",",
"dbname",
",",
"partitioned",
"=",
"False",
",",
"*",
"*",
"kwargs",
")",
":",
"new_db",
"=",
"self",
".",
"_DATABASE_CLASS",
"(",
"self",
",",
"dbname",
",",
"partitioned",
"=",
"partitioned",
")",
"try",
":",... | 46.4 | 0.001689 |
def _translate_residue(self, selection, default_atomname='CA'):
"""Translate selection for a single res to make_ndx syntax."""
m = self.RESIDUE.match(selection)
if not m:
errmsg = "Selection {selection!r} is not valid.".format(**vars())
logger.error(errmsg)
ra... | [
"def",
"_translate_residue",
"(",
"self",
",",
"selection",
",",
"default_atomname",
"=",
"'CA'",
")",
":",
"m",
"=",
"self",
".",
"RESIDUE",
".",
"match",
"(",
"selection",
")",
"if",
"not",
"m",
":",
"errmsg",
"=",
"\"Selection {selection!r} is not valid.\""... | 43.05 | 0.011364 |
def as_variable(obj, name=None) -> 'Union[Variable, IndexVariable]':
"""Convert an object into a Variable.
Parameters
----------
obj : object
Object to convert into a Variable.
- If the object is already a Variable, return a shallow copy.
- Otherwise, if the object has 'dims' a... | [
"def",
"as_variable",
"(",
"obj",
",",
"name",
"=",
"None",
")",
"->",
"'Union[Variable, IndexVariable]'",
":",
"from",
".",
"dataarray",
"import",
"DataArray",
"# TODO: consider extending this method to automatically handle Iris and",
"if",
"isinstance",
"(",
"obj",
",",... | 38.972973 | 0.000338 |
def rstrip(iterable, pred):
"""Yield the items from *iterable*, but strip any from the end
for which *pred* returns ``True``.
For example, to remove a set of items from the end of an iterable:
>>> iterable = (None, False, None, 1, 2, None, 3, False, None)
>>> pred = lambda x: x in {None, F... | [
"def",
"rstrip",
"(",
"iterable",
",",
"pred",
")",
":",
"cache",
"=",
"[",
"]",
"cache_append",
"=",
"cache",
".",
"append",
"cache_clear",
"=",
"cache",
".",
"clear",
"for",
"x",
"in",
"iterable",
":",
"if",
"pred",
"(",
"x",
")",
":",
"cache_appen... | 28.791667 | 0.001401 |
def add_config_source(self, config_source, position=None):
"""
Add a config source to the current ConfigResolver instance.
If position is not set, this source will be inserted with the lowest priority.
"""
rank = position if position is not None else len(self._config_sources)
... | [
"def",
"add_config_source",
"(",
"self",
",",
"config_source",
",",
"position",
"=",
"None",
")",
":",
"rank",
"=",
"position",
"if",
"position",
"is",
"not",
"None",
"else",
"len",
"(",
"self",
".",
"_config_sources",
")",
"self",
".",
"_config_sources",
... | 52.428571 | 0.008043 |
def _receiveFromRemotes(self, quotaPerRemote) -> int:
"""
Receives messages from remotes
:param quotaPerRemote: number of messages to receive from one remote
:return: number of received messages
"""
assert quotaPerRemote
totalReceived = 0
for ident, remot... | [
"def",
"_receiveFromRemotes",
"(",
"self",
",",
"quotaPerRemote",
")",
"->",
"int",
":",
"assert",
"quotaPerRemote",
"totalReceived",
"=",
"0",
"for",
"ident",
",",
"remote",
"in",
"self",
".",
"remotesByKeys",
".",
"items",
"(",
")",
":",
"if",
"not",
"re... | 36.034483 | 0.001864 |
def _cmd(jail=None):
'''
Return full path to service command
.. versionchanged:: 2016.3.4
Support for jail (representing jid or jail name) keyword argument in kwargs
'''
service = salt.utils.path.which('service')
if not service:
raise CommandNotFoundError('\'service\' command not f... | [
"def",
"_cmd",
"(",
"jail",
"=",
"None",
")",
":",
"service",
"=",
"salt",
".",
"utils",
".",
"path",
".",
"which",
"(",
"'service'",
")",
"if",
"not",
"service",
":",
"raise",
"CommandNotFoundError",
"(",
"'\\'service\\' command not found'",
")",
"if",
"j... | 31.882353 | 0.001792 |
def data(self, data):
""" Sets the font data of this item.
Does type conversion to ensure data is always of the correct type.
Also updates the children (which is the reason for this property to be overloaded.
"""
self._data = self._enforceDataType(data) # Enforce self._d... | [
"def",
"data",
"(",
"self",
",",
"data",
")",
":",
"self",
".",
"_data",
"=",
"self",
".",
"_enforceDataType",
"(",
"data",
")",
"# Enforce self._data to be a QFont",
"self",
".",
"familyCti",
".",
"data",
"=",
"fontFamilyIndex",
"(",
"self",
".",
"data",
... | 56.636364 | 0.011058 |
async def isReachable(self, url, *, headers=None, verify=True, response_headers=None, cache=None):
""" Send a HEAD request with short timeout or get data from cache, return True if ressource has 2xx status code, False instead. """
if (cache is not None) and (url in cache):
# try from cache first
sel... | [
"async",
"def",
"isReachable",
"(",
"self",
",",
"url",
",",
"*",
",",
"headers",
"=",
"None",
",",
"verify",
"=",
"True",
",",
"response_headers",
"=",
"None",
",",
"cache",
"=",
"None",
")",
":",
"if",
"(",
"cache",
"is",
"not",
"None",
")",
"and... | 47.706897 | 0.010623 |
def _make_record(self, parent, gline):
"""Process next record.
This method created new record from the line read from file if
needed and/or updates its parent record. If the parent record tag
is ``BLOB`` and new record tag is ``CONT`` then record is skipped
entirely and None is ... | [
"def",
"_make_record",
"(",
"self",
",",
"parent",
",",
"gline",
")",
":",
"if",
"parent",
"and",
"gline",
".",
"tag",
"in",
"(",
"\"CONT\"",
",",
"\"CONC\"",
")",
":",
"# concatenate, only for non-BLOBs",
"if",
"parent",
".",
"tag",
"!=",
"\"BLOB\"",
":",... | 37.595745 | 0.001103 |
async def get_state(self):
"""Get the latest state change of QTM. If the :func:`~qtm.connect` on_event
callback was set the callback will be called as well.
:rtype: A :class:`qtm.QRTEvent`
"""
await self._protocol.send_command("getstate", callback=False)
return await sel... | [
"async",
"def",
"get_state",
"(",
"self",
")",
":",
"await",
"self",
".",
"_protocol",
".",
"send_command",
"(",
"\"getstate\"",
",",
"callback",
"=",
"False",
")",
"return",
"await",
"self",
".",
"_protocol",
".",
"await_event",
"(",
")"
] | 42.25 | 0.008696 |
def verify_firebase_token(id_token, request, audience=None):
"""Verifies an ID Token issued by Firebase Authentication.
Args:
id_token (Union[str, bytes]): The encoded token.
request (google.auth.transport.Request): The object used to make
HTTP requests.
audience (str): The ... | [
"def",
"verify_firebase_token",
"(",
"id_token",
",",
"request",
",",
"audience",
"=",
"None",
")",
":",
"return",
"verify_token",
"(",
"id_token",
",",
"request",
",",
"audience",
"=",
"audience",
",",
"certs_url",
"=",
"_GOOGLE_APIS_CERTS_URL",
")"
] | 39.625 | 0.001541 |
def working_cycletime(start, end, workday_start=datetime.timedelta(hours=0), workday_end=datetime.timedelta(hours=24)):
"""
Get the working time between a beginning and an end point subtracting out non-office time
"""
def clamp(t, start, end):
"Return 't' clamped to the range ['start', 'end']"
... | [
"def",
"working_cycletime",
"(",
"start",
",",
"end",
",",
"workday_start",
"=",
"datetime",
".",
"timedelta",
"(",
"hours",
"=",
"0",
")",
",",
"workday_end",
"=",
"datetime",
".",
"timedelta",
"(",
"hours",
"=",
"24",
")",
")",
":",
"def",
"clamp",
"... | 39.439024 | 0.002414 |
def cookies(self):
"""Container of request cookies
"""
cookies = SimpleCookie()
cookie = self.environ.get('HTTP_COOKIE')
if cookie:
cookies.load(cookie)
return cookies | [
"def",
"cookies",
"(",
"self",
")",
":",
"cookies",
"=",
"SimpleCookie",
"(",
")",
"cookie",
"=",
"self",
".",
"environ",
".",
"get",
"(",
"'HTTP_COOKIE'",
")",
"if",
"cookie",
":",
"cookies",
".",
"load",
"(",
"cookie",
")",
"return",
"cookies"
] | 27.5 | 0.008811 |
def add_affect(self, name, src, dest, val, condition = None ):
"""
adds how param 'src' affects param 'dest' to the list
"""
self.affects.append(ParamAffects(name, src, dest, val, condition)) | [
"def",
"add_affect",
"(",
"self",
",",
"name",
",",
"src",
",",
"dest",
",",
"val",
",",
"condition",
"=",
"None",
")",
":",
"self",
".",
"affects",
".",
"append",
"(",
"ParamAffects",
"(",
"name",
",",
"src",
",",
"dest",
",",
"val",
",",
"conditi... | 43.8 | 0.022422 |
def _load_data():
"""Load the transcription mapping data into a dictionary."""
lines = dragonmapper.data.load_data_file('transcriptions.csv')
pinyin_map, zhuyin_map, ipa_map = {}, {}, {}
for line in lines:
p, z, i = line.split(',')
pinyin_map[p] = {'Zhuyin': z, 'IPA': i}
zhuyin_m... | [
"def",
"_load_data",
"(",
")",
":",
"lines",
"=",
"dragonmapper",
".",
"data",
".",
"load_data_file",
"(",
"'transcriptions.csv'",
")",
"pinyin_map",
",",
"zhuyin_map",
",",
"ipa_map",
"=",
"{",
"}",
",",
"{",
"}",
",",
"{",
"}",
"for",
"line",
"in",
"... | 43.3 | 0.002262 |
def merge_dicts(a, b, path=None):
""" Merge dict :b: into dict :a:
Code snippet from http://stackoverflow.com/a/7205107
"""
if path is None:
path = []
for key in b:
if key in a:
if isinstance(a[key], dict) and isinstance(b[key], dict):
merge_dicts(a[key]... | [
"def",
"merge_dicts",
"(",
"a",
",",
"b",
",",
"path",
"=",
"None",
")",
":",
"if",
"path",
"is",
"None",
":",
"path",
"=",
"[",
"]",
"for",
"key",
"in",
"b",
":",
"if",
"key",
"in",
"a",
":",
"if",
"isinstance",
"(",
"a",
"[",
"key",
"]",
... | 28.9 | 0.001675 |
def serve_dir(dir_path):
"""
Generate indexes and run server from the given directory downwards.
@param {String} dir_path - The directory path (absolute, or relative to CWD)
@return {None}
"""
# Create index files, and store the list of their paths for cleanup later
# This time, force no pro... | [
"def",
"serve_dir",
"(",
"dir_path",
")",
":",
"# Create index files, and store the list of their paths for cleanup later",
"# This time, force no processing - this gives us a fast first-pass in terms",
"# of page generation, but potentially slow serving for large image files",
"print",
"(",
"... | 51.083333 | 0.002402 |
def get_user(self, user_id):
"""Returns the current user from the session data.
If authenticated, this return the user object based on the user ID
and session data.
.. note::
This required monkey-patching the ``contrib.auth`` middleware
to make the ``request`` obje... | [
"def",
"get_user",
"(",
"self",
",",
"user_id",
")",
":",
"if",
"(",
"hasattr",
"(",
"self",
",",
"'request'",
")",
"and",
"user_id",
"==",
"self",
".",
"request",
".",
"session",
"[",
"\"user_id\"",
"]",
")",
":",
"token",
"=",
"self",
".",
"request... | 38.636364 | 0.002296 |
def constrain_secdepth(self, thresh):
"""
Constrain the observed secondary depth to be less than a given value
:param thresh:
Maximum allowed fractional depth for diluted secondary
eclipse depth
"""
self.apply_constraint(UpperLimit(self.secondary_depth, ... | [
"def",
"constrain_secdepth",
"(",
"self",
",",
"thresh",
")",
":",
"self",
".",
"apply_constraint",
"(",
"UpperLimit",
"(",
"self",
".",
"secondary_depth",
",",
"thresh",
",",
"name",
"=",
"'secondary depth'",
")",
")"
] | 34.3 | 0.008523 |
def policy_parameters(self):
""" Parameters of policy """
return it.chain(self.policy_backbone.parameters(), self.action_head.parameters()) | [
"def",
"policy_parameters",
"(",
"self",
")",
":",
"return",
"it",
".",
"chain",
"(",
"self",
".",
"policy_backbone",
".",
"parameters",
"(",
")",
",",
"self",
".",
"action_head",
".",
"parameters",
"(",
")",
")"
] | 51 | 0.019355 |
def mie_avg(radius=5e-6, sphere_index=1.339, medium_index=1.333,
wavelength=550e-9, pixel_size=1e-7, grid_size=(80, 80),
center=(39.5, 39.5), interpolate=3, focus=0, arp=True):
"""Mie-simulated non-polarized field behind a dielectric sphere
Parameters
----------
radius: float
... | [
"def",
"mie_avg",
"(",
"radius",
"=",
"5e-6",
",",
"sphere_index",
"=",
"1.339",
",",
"medium_index",
"=",
"1.333",
",",
"wavelength",
"=",
"550e-9",
",",
"pixel_size",
"=",
"1e-7",
",",
"grid_size",
"=",
"(",
"80",
",",
"80",
")",
",",
"center",
"=",
... | 33.957576 | 0.000173 |
def install(pkg=None,
pkgs=None,
dir=None,
runas=None,
registry=None,
env=None,
dry_run=False,
silent=True):
'''
Install an NPM package.
If no directory is specified, the package will be installed globally. If
no packag... | [
"def",
"install",
"(",
"pkg",
"=",
"None",
",",
"pkgs",
"=",
"None",
",",
"dir",
"=",
"None",
",",
"runas",
"=",
"None",
",",
"registry",
"=",
"None",
",",
"env",
"=",
"None",
",",
"dry_run",
"=",
"False",
",",
"silent",
"=",
"True",
")",
":",
... | 23.904348 | 0.000349 |
def _download_images(label_path:PathOrStr, img_tuples:list, max_workers:int=defaults.cpus, timeout:int=4) -> FilePathList:
"""
Downloads images in `img_tuples` to `label_path`.
If the directory doesn't exist, it'll be created automatically.
Uses `parallel` to speed things up in `max_workers` when the s... | [
"def",
"_download_images",
"(",
"label_path",
":",
"PathOrStr",
",",
"img_tuples",
":",
"list",
",",
"max_workers",
":",
"int",
"=",
"defaults",
".",
"cpus",
",",
"timeout",
":",
"int",
"=",
"4",
")",
"->",
"FilePathList",
":",
"os",
".",
"makedirs",
"("... | 61.9 | 0.022293 |
def scene_to_html(scene):
"""
Return HTML that will render the scene using
GLTF/GLB encoded to base64 loaded by three.js
Parameters
--------------
scene : trimesh.Scene
Source geometry
Returns
--------------
html : str
HTML containing embedded geometry
"""
# use... | [
"def",
"scene_to_html",
"(",
"scene",
")",
":",
"# use os.path.join so this works on windows",
"base",
"=",
"get_resource",
"(",
"'viewer.html.template'",
")",
"# get export as bytes",
"data",
"=",
"scene",
".",
"export",
"(",
"file_type",
"=",
"'glb'",
")",
"# encode... | 23.703704 | 0.001502 |
def add_clause(self, clause, no_return=True):
"""
Add a new clause to solver's internal formula.
"""
if self.lingeling:
pysolvers.lingeling_add_cl(self.lingeling, clause) | [
"def",
"add_clause",
"(",
"self",
",",
"clause",
",",
"no_return",
"=",
"True",
")",
":",
"if",
"self",
".",
"lingeling",
":",
"pysolvers",
".",
"lingeling_add_cl",
"(",
"self",
".",
"lingeling",
",",
"clause",
")"
] | 30.428571 | 0.009132 |
async def add_claims(self, payload, user, *args, **kwargs):
"""
Injects standard claims into the payload for: exp, iss, iat, nbf, aud.
And, custom claims, if they exist
"""
delta = timedelta(seconds=self.config.expiration_delta())
exp = datetime.utcnow() + delta
a... | [
"async",
"def",
"add_claims",
"(",
"self",
",",
"payload",
",",
"user",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"delta",
"=",
"timedelta",
"(",
"seconds",
"=",
"self",
".",
"config",
".",
"expiration_delta",
"(",
")",
")",
"exp",
"=",
... | 37.766667 | 0.001721 |
def trim(hdu):
"""TRIM a CFHT MEGAPRIME frame using the DATASEC keyword"""
datasec = re.findall(r'(\d+)',
hdu.header.get('DATASEC'))
l=int(datasec[0])-1
r=int(datasec[1])
b=int(datasec[2])-1
t=int(datasec[3])
if opt.verbose:
print "Trimming [%d:%d,%d:%d]" % ... | [
"def",
"trim",
"(",
"hdu",
")",
":",
"datasec",
"=",
"re",
".",
"findall",
"(",
"r'(\\d+)'",
",",
"hdu",
".",
"header",
".",
"get",
"(",
"'DATASEC'",
")",
")",
"l",
"=",
"int",
"(",
"datasec",
"[",
"0",
"]",
")",
"-",
"1",
"r",
"=",
"int",
"(... | 39.785714 | 0.038596 |
def get_and_unzip_archive(i):
"""
Input: {
zip - zip filename or URL
path - path to extract
(overwrite) - if 'yes', overwrite files when unarchiving
(path_to_remove) - if !='', remove this part of the path from extracted arch... | [
"def",
"get_and_unzip_archive",
"(",
"i",
")",
":",
"o",
"=",
"i",
".",
"get",
"(",
"'out'",
",",
"''",
")",
"zp",
"=",
"i",
"[",
"'zip'",
"]",
"p",
"=",
"i",
"[",
"'path'",
"]",
"pr",
"=",
"i",
".",
"get",
"(",
"'path_to_remove'",
",",
"''",
... | 26.558824 | 0.038965 |
def __getCashToBuyStock(self):
''' calculate the amount of money to buy stock '''
account=self.__strategy.getAccountCopy()
if (account.buyingPower >= account.getTotalValue() / self.__buyingRatio):
return account.getTotalValue() / self.__buyingRatio
else:
return 0 | [
"def",
"__getCashToBuyStock",
"(",
"self",
")",
":",
"account",
"=",
"self",
".",
"__strategy",
".",
"getAccountCopy",
"(",
")",
"if",
"(",
"account",
".",
"buyingPower",
">=",
"account",
".",
"getTotalValue",
"(",
")",
"/",
"self",
".",
"__buyingRatio",
"... | 39.125 | 0.0125 |
def all_up(self):
"""
Get the root object of this comparison.
(This is a convenient wrapper for following the up attribute as often as you can.)
:rtype: DiffLevel
"""
level = self
while level.up:
level = level.up
return level | [
"def",
"all_up",
"(",
"self",
")",
":",
"level",
"=",
"self",
"while",
"level",
".",
"up",
":",
"level",
"=",
"level",
".",
"up",
"return",
"level"
] | 29.2 | 0.009967 |
def clean(self):
"""
Validate that an event with this name on this date does not exist.
"""
cleaned = super(EventForm, self).clean()
if Event.objects.filter(name=cleaned['name'], start_date=cleaned['start_date']).count():
raise forms.ValidationError(u'This event appea... | [
"def",
"clean",
"(",
"self",
")",
":",
"cleaned",
"=",
"super",
"(",
"EventForm",
",",
"self",
")",
".",
"clean",
"(",
")",
"if",
"Event",
".",
"objects",
".",
"filter",
"(",
"name",
"=",
"cleaned",
"[",
"'name'",
"]",
",",
"start_date",
"=",
"clea... | 46.375 | 0.010582 |
def _upload_media(self,directory,files=None,resize_request=None):
"""Uploads media file to FLICKR, returns True if
uploaded successfully, Will replace
if already uploaded, If megapixels > 0, will
scale photos before upload
If no filename given, will go through all files in DB"""... | [
"def",
"_upload_media",
"(",
"self",
",",
"directory",
",",
"files",
"=",
"None",
",",
"resize_request",
"=",
"None",
")",
":",
"# Connect if we aren't already",
"if",
"not",
"self",
".",
"_connectToFlickr",
"(",
")",
":",
"logger",
".",
"error",
"(",
"\"%s ... | 36.295455 | 0.014634 |
def _indiameter_from_fibers(self):
r"""
Calculate an indiameter by distance transforming sections of the
fiber image. By definition the maximum value will be the largest radius
of an inscribed sphere inside the fibrous hull
"""
Np = self.num_pores()
indiam = np.ze... | [
"def",
"_indiameter_from_fibers",
"(",
"self",
")",
":",
"Np",
"=",
"self",
".",
"num_pores",
"(",
")",
"indiam",
"=",
"np",
".",
"zeros",
"(",
"Np",
",",
"dtype",
"=",
"float",
")",
"incen",
"=",
"np",
".",
"zeros",
"(",
"[",
"Np",
",",
"3",
"]"... | 43.153846 | 0.001744 |
def find(self, *_clauses, **kwargs):
"""Perform a simple search on the table.
Simply pass keyword arguments as ``filter``.
::
results = table.find(country='France')
results = table.find(country='France', year=1980)
Using ``_limit``::
# just return ... | [
"def",
"find",
"(",
"self",
",",
"*",
"_clauses",
",",
"*",
"*",
"kwargs",
")",
":",
"if",
"not",
"self",
".",
"exists",
":",
"return",
"iter",
"(",
"[",
"]",
")",
"_limit",
"=",
"kwargs",
".",
"pop",
"(",
"'_limit'",
",",
"None",
")",
"_offset",... | 36.018868 | 0.00102 |
def convert_runsummary_to_json(
df, comment='Uploaded via km3pipe.StreamDS', prefix='TEST_'
):
"""Convert a Pandas DataFrame with runsummary to JSON for DB upload"""
data_field = []
comment += ", by {}".format(getpass.getuser())
for det_id, det_data in df.groupby('det_id'):
runs_field = ... | [
"def",
"convert_runsummary_to_json",
"(",
"df",
",",
"comment",
"=",
"'Uploaded via km3pipe.StreamDS'",
",",
"prefix",
"=",
"'TEST_'",
")",
":",
"data_field",
"=",
"[",
"]",
"comment",
"+=",
"\", by {}\"",
".",
"format",
"(",
"getpass",
".",
"getuser",
"(",
")... | 43.948718 | 0.000571 |
def read_data_transition(self, length, whence=None,
skip=False, stream_event=ION_STREAM_INCOMPLETE_EVENT):
"""Returns an immediate event_transition to read a specified number of bytes."""
if whence is None:
whence = self.whence
return Transition(
... | [
"def",
"read_data_transition",
"(",
"self",
",",
"length",
",",
"whence",
"=",
"None",
",",
"skip",
"=",
"False",
",",
"stream_event",
"=",
"ION_STREAM_INCOMPLETE_EVENT",
")",
":",
"if",
"whence",
"is",
"None",
":",
"whence",
"=",
"self",
".",
"whence",
"r... | 43.666667 | 0.012469 |
def __thread_started(self):
""" Start a scheduled task
:return: None
"""
if self.__task is None:
raise RuntimeError('Unable to start thread without "start" method call')
self.__task.start()
self.__task.start_event().wait(self.__scheduled_task_startup_timeout__) | [
"def",
"__thread_started",
"(",
"self",
")",
":",
"if",
"self",
".",
"__task",
"is",
"None",
":",
"raise",
"RuntimeError",
"(",
"'Unable to start thread without \"start\" method call'",
")",
"self",
".",
"__task",
".",
"start",
"(",
")",
"self",
".",
"__task",
... | 29.888889 | 0.032491 |
def serialize_particle_data(self,**kwargs):
"""
Fast way to access serialized particle data via numpy arrays.
This function can directly set the values of numpy arrays to
current particle data. This is significantly faster than accessing
particle data via `sim.particles` as all ... | [
"def",
"serialize_particle_data",
"(",
"self",
",",
"*",
"*",
"kwargs",
")",
":",
"N",
"=",
"self",
".",
"N",
"possible_keys",
"=",
"[",
"\"hash\"",
",",
"\"m\"",
",",
"\"r\"",
",",
"\"xyz\"",
",",
"\"vxvyvz\"",
",",
"\"xyzvxvyvz\"",
"]",
"d",
"=",
"{"... | 44.460526 | 0.009844 |
def Cos(input_vertex: vertex_constructor_param_types, label: Optional[str]=None) -> Vertex:
"""
Takes the cosine of a vertex, Cos(vertex)
:param input_vertex: the vertex
"""
return Double(context.jvm_view().CosVertex, label, cast_to_double_vertex(input_vertex)) | [
"def",
"Cos",
"(",
"input_vertex",
":",
"vertex_constructor_param_types",
",",
"label",
":",
"Optional",
"[",
"str",
"]",
"=",
"None",
")",
"->",
"Vertex",
":",
"return",
"Double",
"(",
"context",
".",
"jvm_view",
"(",
")",
".",
"CosVertex",
",",
"label",
... | 40 | 0.020979 |
def execute(self, input_data):
''' Execute the ViewPDF worker '''
# Just a small check to make sure we haven't been called on the wrong file type
if (input_data['meta']['type_tag'] != 'pdf'):
return {'error': self.__class__.__name__+': called on '+input_data['meta']['type_tag']}
... | [
"def",
"execute",
"(",
"self",
",",
"input_data",
")",
":",
"# Just a small check to make sure we haven't been called on the wrong file type",
"if",
"(",
"input_data",
"[",
"'meta'",
"]",
"[",
"'type_tag'",
"]",
"!=",
"'pdf'",
")",
":",
"return",
"{",
"'error'",
":"... | 41.090909 | 0.008658 |
def undo(self, key_value, modifier_mask):
"""Undo for selected state-machine if no state-source-editor is open and focused in states-editor-controller.
:return: True if a undo was performed, False if focus on source-editor.
:rtype: bool
"""
# TODO re-organize as request to contr... | [
"def",
"undo",
"(",
"self",
",",
"key_value",
",",
"modifier_mask",
")",
":",
"# TODO re-organize as request to controller which holds source-editor-view or any parent to it",
"for",
"key",
",",
"tab",
"in",
"gui_singletons",
".",
"main_window_controller",
".",
"get_controlle... | 62.65 | 0.008648 |
def returns_cumulative(returns, geometric=True, expanding=False):
""" return the cumulative return
Parameters
----------
returns : DataFrame or Series
geometric : bool, default is True
If True, geometrically link returns
expanding : bool default is False
If True,... | [
"def",
"returns_cumulative",
"(",
"returns",
",",
"geometric",
"=",
"True",
",",
"expanding",
"=",
"False",
")",
":",
"if",
"expanding",
":",
"if",
"geometric",
":",
"return",
"(",
"1.",
"+",
"returns",
")",
".",
"cumprod",
"(",
")",
"-",
"1.",
"else",... | 30.181818 | 0.00146 |
def bss_eval_sources_framewise(reference_sources, estimated_sources,
window=30 * 44100, hop=15 * 44100,
compute_permutation=False):
"""
BSS Eval v3 bss_eval_sources_framewise
Wrapper to ``bss_eval`` with the right parameters.
The call to thi... | [
"def",
"bss_eval_sources_framewise",
"(",
"reference_sources",
",",
"estimated_sources",
",",
"window",
"=",
"30",
"*",
"44100",
",",
"hop",
"=",
"15",
"*",
"44100",
",",
"compute_permutation",
"=",
"False",
")",
":",
"(",
"sdr",
",",
"isr",
",",
"sir",
",... | 38.947368 | 0.001319 |
def contributions(self):
"""Apply a datetime filter against the contributor's contribution queryset."""
if self._contributions is None:
self._contributions = self.contributor.contributions.filter(
content__published__gte=self.start,
content__published__lt=self... | [
"def",
"contributions",
"(",
"self",
")",
":",
"if",
"self",
".",
"_contributions",
"is",
"None",
":",
"self",
".",
"_contributions",
"=",
"self",
".",
"contributor",
".",
"contributions",
".",
"filter",
"(",
"content__published__gte",
"=",
"self",
".",
"sta... | 45.75 | 0.008043 |
def browse(package, homepage):
"""Browse to a package's PyPI or project homepage."""
p = Package(package)
try:
if homepage:
secho(u'Opening homepage for "{0}"...'.format(package), bold=True)
url = p.home_page
else:
secho(u'Opening PyPI page for "{0}"...'.f... | [
"def",
"browse",
"(",
"package",
",",
"homepage",
")",
":",
"p",
"=",
"Package",
"(",
"package",
")",
"try",
":",
"if",
"homepage",
":",
"secho",
"(",
"u'Opening homepage for \"{0}\"...'",
".",
"format",
"(",
"package",
")",
",",
"bold",
"=",
"True",
")"... | 34.384615 | 0.002179 |
def plot_dir(ZED, pars, datablock, angle):
"""
function to put the great circle on the equal area projection
and plot start and end points of calculation
DEPRECATED (used in zeq_magic)
"""
#
# find start and end points from datablock
#
if pars["calculation_type"] == 'DE-FM':
x, y = [], ... | [
"def",
"plot_dir",
"(",
"ZED",
",",
"pars",
",",
"datablock",
",",
"angle",
")",
":",
"#",
"# find start and end points from datablock",
"#",
"if",
"pars",
"[",
"\"calculation_type\"",
"]",
"==",
"'DE-FM'",
":",
"x",
",",
"y",
"=",
"[",
"]",
",",
"[",
"]... | 35.429825 | 0.000723 |
def parse_certificate(data):
"""
Loads a certificate from a DER or PEM-formatted file. Supports X.509
certificates only.
:param data:
A byte string to load the certificate from
:raises:
ValueError - when the data does not appear to contain a certificate
:return:
An asn... | [
"def",
"parse_certificate",
"(",
"data",
")",
":",
"if",
"not",
"isinstance",
"(",
"data",
",",
"byte_cls",
")",
":",
"raise",
"TypeError",
"(",
"pretty_message",
"(",
"'''\n data must be a byte string, not %s\n '''",
",",
"type_name",
"(",
"data... | 26.321429 | 0.000654 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.