text stringlengths 75 104k | code_tokens list | avg_line_len float64 7.91 980 | score float64 0 0.18 |
|---|---|---|---|
def delete(self, *keys):
"""Removes the specified keys. A key is ignored if it does not exist.
Returns :data:`True` if all keys are removed.
.. note::
**Time complexity**: ``O(N)`` where ``N`` is the number of keys that
will be removed. When a key to remove holds a value ... | [
"def",
"delete",
"(",
"self",
",",
"*",
"keys",
")",
":",
"return",
"self",
".",
"_execute",
"(",
"[",
"b'DEL'",
"]",
"+",
"list",
"(",
"keys",
")",
",",
"len",
"(",
"keys",
")",
")"
] | 41.684211 | 0.002469 |
def filter(self, table, group_types, filter_string):
"""Naive case-insensitive search."""
query = filter_string.lower()
return [group_type for group_type in group_types
if query in group_type.name.lower()] | [
"def",
"filter",
"(",
"self",
",",
"table",
",",
"group_types",
",",
"filter_string",
")",
":",
"query",
"=",
"filter_string",
".",
"lower",
"(",
")",
"return",
"[",
"group_type",
"for",
"group_type",
"in",
"group_types",
"if",
"query",
"in",
"group_type",
... | 48.2 | 0.008163 |
def set_options(self, options):
"""
options = [{
'product_option': instance of ProductFinalOption,
'product_final': instance of ProductFinal,
'quantity': Float
}, ]
"""
with transaction.atomic():
for option in options:
... | [
"def",
"set_options",
"(",
"self",
",",
"options",
")",
":",
"with",
"transaction",
".",
"atomic",
"(",
")",
":",
"for",
"option",
"in",
"options",
":",
"opt",
"=",
"self",
".",
"line_basket_option_sales",
".",
"filter",
"(",
"product_option",
"=",
"option... | 42.84375 | 0.001427 |
def default_facets_factory(search, index):
"""Add a default facets to query.
:param search: Basic search object.
:param index: Index name.
:returns: A tuple containing the new search object and a dictionary with
all fields and values used.
"""
urlkwargs = MultiDict()
facets = curre... | [
"def",
"default_facets_factory",
"(",
"search",
",",
"index",
")",
":",
"urlkwargs",
"=",
"MultiDict",
"(",
")",
"facets",
"=",
"current_app",
".",
"config",
"[",
"'RECORDS_REST_FACETS'",
"]",
".",
"get",
"(",
"index",
")",
"if",
"facets",
"is",
"not",
"No... | 29.72 | 0.001304 |
def cli(log_level):
"""Manage tmux sessions.
Pass the "--help" argument to any command to see detailed help.
See detailed documentation and examples at:
http://tmuxp.readthedocs.io/en/latest/"""
try:
has_minimum_version()
except TmuxCommandNotFound:
click.echo('tmux not found. t... | [
"def",
"cli",
"(",
"log_level",
")",
":",
"try",
":",
"has_minimum_version",
"(",
")",
"except",
"TmuxCommandNotFound",
":",
"click",
".",
"echo",
"(",
"'tmux not found. tmuxp requires you install tmux first.'",
")",
"sys",
".",
"exit",
"(",
")",
"except",
"exc",
... | 32.866667 | 0.001972 |
def sharing_agreement_delete(self, id, **kwargs):
"https://developer.zendesk.com/rest_api/docs/core/sharing_agreements#delete-a-sharing-agreement"
api_path = "/api/v2/sharing_agreements/{id}.json"
api_path = api_path.format(id=id)
return self.call(api_path, method="DELETE", **kwargs) | [
"def",
"sharing_agreement_delete",
"(",
"self",
",",
"id",
",",
"*",
"*",
"kwargs",
")",
":",
"api_path",
"=",
"\"/api/v2/sharing_agreements/{id}.json\"",
"api_path",
"=",
"api_path",
".",
"format",
"(",
"id",
"=",
"id",
")",
"return",
"self",
".",
"call",
"... | 62.4 | 0.009494 |
def handle_part(self, params):
"""
Handle a client parting from channel(s).
"""
for pchannel in params.split(','):
if pchannel.strip() in self.server.channels:
# Send message to all clients in all channels user is in, and
# remove the user from... | [
"def",
"handle_part",
"(",
"self",
",",
"params",
")",
":",
"for",
"pchannel",
"in",
"params",
".",
"split",
"(",
"','",
")",
":",
"if",
"pchannel",
".",
"strip",
"(",
")",
"in",
"self",
".",
"server",
".",
"channels",
":",
"# Send message to all clients... | 46 | 0.002242 |
def generate(env):
SCons.Tool.bcc32.findIt('tlib', env)
"""Add Builders and construction variables for ar to an Environment."""
SCons.Tool.createStaticLibBuilder(env)
env['AR'] = 'tlib'
env['ARFLAGS'] = SCons.Util.CLVar('')
env['ARCOM'] = '$AR $TARGET $ARFLAGS /a $SOURCES'
... | [
"def",
"generate",
"(",
"env",
")",
":",
"SCons",
".",
"Tool",
".",
"bcc32",
".",
"findIt",
"(",
"'tlib'",
",",
"env",
")",
"SCons",
".",
"Tool",
".",
"createStaticLibBuilder",
"(",
"env",
")",
"env",
"[",
"'AR'",
"]",
"=",
"'tlib'",
"env",
"[",
"'... | 40.888889 | 0.015957 |
def process(texts, *args, **kwargs):
"""
Processes a single sequence of texts with a
:class:`~deltas.SegmentMatcher`.
:Parameters:
texts : `iterable`(`str`)
sequence of texts
args : `tuple`
passed to :class:`~deltas.SegmentMatcher`'s
constructor
... | [
"def",
"process",
"(",
"texts",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"processor",
"=",
"SegmentMatcher",
".",
"Processor",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
"for",
"text",
"in",
"texts",
":",
"yield",
"processor",
".",
... | 29.333333 | 0.001835 |
def _R2deriv(self,R,z,phi=0.,t=0.):
"""
NAME:
R2deriv
PURPOSE:
evaluate R2 derivative
INPUT:
R - Cylindrical Galactocentric radius
z - vertical height
phi - azimuth
t - time
OUTPUT:
-d K_R (R,z) d R
... | [
"def",
"_R2deriv",
"(",
"self",
",",
"R",
",",
"z",
",",
"phi",
"=",
"0.",
",",
"t",
"=",
"0.",
")",
":",
"if",
"self",
".",
"_new",
":",
"if",
"nu",
".",
"fabs",
"(",
"z",
")",
"<",
"10.",
"**",
"-",
"6.",
":",
"y",
"=",
"0.5",
"*",
"s... | 37.136364 | 0.015513 |
def set_quantities(self, product_quantities):
''' Sets the quantities on each of the products on each of the
products specified. Raises an exception (ValidationError) if a limit
is violated. `product_quantities` is an iterable of (product, quantity)
pairs. '''
items_in_cart = co... | [
"def",
"set_quantities",
"(",
"self",
",",
"product_quantities",
")",
":",
"items_in_cart",
"=",
"commerce",
".",
"ProductItem",
".",
"objects",
".",
"filter",
"(",
"cart",
"=",
"self",
".",
"cart",
")",
"items_in_cart",
"=",
"items_in_cart",
".",
"select_rela... | 33.890909 | 0.001043 |
def commit(self):
"""Remove temporary save dir: rollback will no longer be possible."""
if self.save_dir is not None:
rmtree(self.save_dir)
self.save_dir = None
self._moved_paths = [] | [
"def",
"commit",
"(",
"self",
")",
":",
"if",
"self",
".",
"save_dir",
"is",
"not",
"None",
":",
"rmtree",
"(",
"self",
".",
"save_dir",
")",
"self",
".",
"save_dir",
"=",
"None",
"self",
".",
"_moved_paths",
"=",
"[",
"]"
] | 38.333333 | 0.008511 |
def simulationstep(timestep):
""" Define a simulation time step size for testing purposes within a
parameter control file.
Using |simulationstep| only affects the values of time dependent
parameters, when `pub.timegrids.stepsize` is not defined. It thus has
no influence on usual hydpy simulations ... | [
"def",
"simulationstep",
"(",
"timestep",
")",
":",
"if",
"hydpy",
".",
"pub",
".",
"options",
".",
"warnsimulationstep",
":",
"warnings",
".",
"warn",
"(",
"'Note that the applied function `simulationstep` is intended for '",
"'testing purposes only. When doing a HydPy simu... | 46.257143 | 0.000605 |
def _symlink_in_files(in_files, data):
"""Symlink (shared filesystem) or copy (CWL) inputs into align_prep directory.
"""
work_dir = utils.safe_makedir(os.path.join(data["dirs"]["work"], "align_prep"))
out = []
for in_file in in_files:
out_file = os.path.join(work_dir, "%s_%s" % (dd.get_samp... | [
"def",
"_symlink_in_files",
"(",
"in_files",
",",
"data",
")",
":",
"work_dir",
"=",
"utils",
".",
"safe_makedir",
"(",
"os",
".",
"path",
".",
"join",
"(",
"data",
"[",
"\"dirs\"",
"]",
"[",
"\"work\"",
"]",
",",
"\"align_prep\"",
")",
")",
"out",
"="... | 46.5 | 0.008439 |
def parse_esmtp_extensions(message):
"""
Parses the response given by an ESMTP server after a *EHLO* command.
The response is parsed to build:
- A dict of supported ESMTP extensions (with parameters, if any).
- A list of supported authentication methods.
Returns:
... | [
"def",
"parse_esmtp_extensions",
"(",
"message",
")",
":",
"extns",
"=",
"{",
"}",
"auths",
"=",
"[",
"]",
"oldstyle_auth_regex",
"=",
"re",
".",
"compile",
"(",
"r\"auth=(?P<auth>.*)\"",
",",
"re",
".",
"IGNORECASE",
")",
"extension_regex",
"=",
"re",
".",
... | 34.903846 | 0.002144 |
def application(env, start_response):
"""wsgi application
"""
path = env["PATH_INFO"]
if path == "/influx.gif":
# send response
start_response("200 OK", [("Content-Type", "image/gif")])
yield GIF
# parse the query params and stick them in the queue
params = parse... | [
"def",
"application",
"(",
"env",
",",
"start_response",
")",
":",
"path",
"=",
"env",
"[",
"\"PATH_INFO\"",
"]",
"if",
"path",
"==",
"\"/influx.gif\"",
":",
"# send response",
"start_response",
"(",
"\"200 OK\"",
",",
"[",
"(",
"\"Content-Type\"",
",",
"\"ima... | 34.525424 | 0.000477 |
def PCExtension(*args, **kwargs):
"""
Parameters
==========
template_regexps: list of 3-tuples
e.g. [(pattern1, target1, subsd1), ...], used to generate
templated code
pass_extra_compile_args: bool
should ext.extra_compile_args be passed along? default: False
"""
vals... | [
"def",
"PCExtension",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"vals",
"=",
"{",
"}",
"intercept",
"=",
"{",
"'build_callbacks'",
":",
"(",
")",
",",
"# tuple of (callback, args, kwargs)",
"'link_ext'",
":",
"True",
",",
"'build_files'",
":",
"... | 30 | 0.000687 |
def randbytes(self):
""" -> #bytes result of bytes-encoded :func:gen_rand_str """
return gen_rand_str(
10, 30, use=self.random, keyspace=list(self.keyspace)
).encode("utf-8") | [
"def",
"randbytes",
"(",
"self",
")",
":",
"return",
"gen_rand_str",
"(",
"10",
",",
"30",
",",
"use",
"=",
"self",
".",
"random",
",",
"keyspace",
"=",
"list",
"(",
"self",
".",
"keyspace",
")",
")",
".",
"encode",
"(",
"\"utf-8\"",
")"
] | 41.2 | 0.009524 |
def _walk_issuers(self, path, paths, failed_paths):
"""
Recursively looks through the list of known certificates for the issuer
of the certificate specified, stopping once the certificate in question
is one contained within the CA certs list
:param path:
A Validation... | [
"def",
"_walk_issuers",
"(",
"self",
",",
"path",
",",
"paths",
",",
"failed_paths",
")",
":",
"if",
"path",
".",
"first",
".",
"signature",
"in",
"self",
".",
"_ca_lookup",
":",
"paths",
".",
"append",
"(",
"path",
")",
"return",
"new_branches",
"=",
... | 34.5 | 0.002488 |
def convert_from_bytes_if_necessary(prefix, suffix):
"""
Depending on how we extract data from pysam we may end up with either
a string or a byte array of nucleotides. For consistency and simplicity,
we want to only use strings in the rest of our code.
"""
if isinstance(prefix, bytes):
p... | [
"def",
"convert_from_bytes_if_necessary",
"(",
"prefix",
",",
"suffix",
")",
":",
"if",
"isinstance",
"(",
"prefix",
",",
"bytes",
")",
":",
"prefix",
"=",
"prefix",
".",
"decode",
"(",
"'ascii'",
")",
"if",
"isinstance",
"(",
"suffix",
",",
"bytes",
")",
... | 33.846154 | 0.002212 |
def frames_to_samples(frames, hop_length=512, n_fft=None):
"""Converts frame indices to audio sample indices.
Parameters
----------
frames : number or np.ndarray [shape=(n,)]
frame index or vector of frame indices
hop_length : int > 0 [scalar]
number of samples between successi... | [
"def",
"frames_to_samples",
"(",
"frames",
",",
"hop_length",
"=",
"512",
",",
"n_fft",
"=",
"None",
")",
":",
"offset",
"=",
"0",
"if",
"n_fft",
"is",
"not",
"None",
":",
"offset",
"=",
"int",
"(",
"n_fft",
"//",
"2",
")",
"return",
"(",
"np",
"."... | 30.230769 | 0.000822 |
def save(self, fname):
"""Save the report"""
with open(fname, 'wb') as f:
f.write(encode(self.text)) | [
"def",
"save",
"(",
"self",
",",
"fname",
")",
":",
"with",
"open",
"(",
"fname",
",",
"'wb'",
")",
"as",
"f",
":",
"f",
".",
"write",
"(",
"encode",
"(",
"self",
".",
"text",
")",
")"
] | 31.25 | 0.015625 |
def _generate_time_steps(self, trajectory_list):
"""Transforms time step observations to frames of a video."""
for time_step in env_problem.EnvProblem._generate_time_steps(
self, trajectory_list):
# Convert the rendered observations from numpy to png format.
frame_np = np.array(time_step.pop... | [
"def",
"_generate_time_steps",
"(",
"self",
",",
"trajectory_list",
")",
":",
"for",
"time_step",
"in",
"env_problem",
".",
"EnvProblem",
".",
"_generate_time_steps",
"(",
"self",
",",
"trajectory_list",
")",
":",
"# Convert the rendered observations from numpy to png for... | 46.954545 | 0.016129 |
def get(self, limit=None, offset=None):
"""
:param offset: int of the offset to use
:param limit: int of max number of puzzles to return
:return: list of Transfer dict
"""
return self.connection.get('account/transfer/admin/array', limit=limi... | [
"def",
"get",
"(",
"self",
",",
"limit",
"=",
"None",
",",
"offset",
"=",
"None",
")",
":",
"return",
"self",
".",
"connection",
".",
"get",
"(",
"'account/transfer/admin/array'",
",",
"limit",
"=",
"limit",
",",
"offset",
"=",
"offset",
")"
] | 47.285714 | 0.008902 |
def authenticate(self):
"""Authenticate the session"""
postdata = self.authentication_postdata
jar = requests.cookies.cookielib.CookieJar()
self.cookies = jar
resp = self.get(self.authentication_base_url)
authtok = _extract_authenticity_token(resp.content)
if post... | [
"def",
"authenticate",
"(",
"self",
")",
":",
"postdata",
"=",
"self",
".",
"authentication_postdata",
"jar",
"=",
"requests",
".",
"cookies",
".",
"cookielib",
".",
"CookieJar",
"(",
")",
"self",
".",
"cookies",
"=",
"jar",
"resp",
"=",
"self",
".",
"ge... | 48.52381 | 0.001925 |
def get(self, mid=None): # pylint: disable=W0221
'''
A convenience URL for getting lists of minions or getting minion
details
.. http:get:: /minions/(mid)
:reqheader X-Auth-Token: |req_token|
:reqheader Accept: |req_accept|
:status 200: |200|
... | [
"def",
"get",
"(",
"self",
",",
"mid",
"=",
"None",
")",
":",
"# pylint: disable=W0221",
"# if you aren't authenticated, redirect to login",
"if",
"not",
"self",
".",
"_verify_auth",
"(",
")",
":",
"self",
".",
"redirect",
"(",
"'/login'",
")",
"return",
"self",... | 23.26 | 0.00165 |
def missing_homology_models(self):
"""list: List of genes with no mapping to any homology models."""
return [x.id for x in self.genes if not self.genes_with_homology_models.has_id(x.id)] | [
"def",
"missing_homology_models",
"(",
"self",
")",
":",
"return",
"[",
"x",
".",
"id",
"for",
"x",
"in",
"self",
".",
"genes",
"if",
"not",
"self",
".",
"genes_with_homology_models",
".",
"has_id",
"(",
"x",
".",
"id",
")",
"]"
] | 66.666667 | 0.014851 |
def convert_coord(coord_from,matrix_file,base_to_aligned=True):
'''Takes an XYZ array (in DICOM coordinates) and uses the matrix file produced by 3dAllineate to transform it. By default, the 3dAllineate
matrix transforms from base to aligned space; to get the inverse transform set ``base_to_aligned`` to ``False... | [
"def",
"convert_coord",
"(",
"coord_from",
",",
"matrix_file",
",",
"base_to_aligned",
"=",
"True",
")",
":",
"with",
"open",
"(",
"matrix_file",
")",
"as",
"f",
":",
"try",
":",
"values",
"=",
"[",
"float",
"(",
"y",
")",
"for",
"y",
"in",
"' '",
".... | 60.9375 | 0.018182 |
def _calculate_adjustment(
lcm, choosers, alternatives, alt_segmenter,
clip_change_low, clip_change_high, multiplier_func=None):
"""
Calculate adjustments to prices to compensate for
supply and demand effects.
Parameters
----------
lcm : LocationChoiceModel
Used to calcu... | [
"def",
"_calculate_adjustment",
"(",
"lcm",
",",
"choosers",
",",
"alternatives",
",",
"alt_segmenter",
",",
"clip_change_low",
",",
"clip_change_high",
",",
"multiplier_func",
"=",
"None",
")",
":",
"logger",
".",
"debug",
"(",
"'start: calculate supply and demand pr... | 42 | 0.000347 |
def normpath(path):
# type: (str) -> bytes
'''
A method to normalize the path, eliminating double slashes, etc. This
method is a copy of the built-in python normpath, except we do *not* allow
double slashes at the start.
Parameters:
path - The path to normalize.
Returns:
The norm... | [
"def",
"normpath",
"(",
"path",
")",
":",
"# type: (str) -> bytes",
"sep",
"=",
"'/'",
"empty",
"=",
"''",
"dot",
"=",
"'.'",
"dotdot",
"=",
"'..'",
"if",
"path",
"==",
"empty",
":",
"return",
"dot",
".",
"encode",
"(",
"'utf-8'",
")",
"initial_slashes",... | 29.833333 | 0.001803 |
def create_snapshot(self, snapshot_size, snapshot_suffix):
""" Create snapshot for this logical volume.
:param snapshot_size: size of newly created snapshot volume. This size is a fraction of the source \
logical volume space (of this logical volume)
:param snapshot_suffix: suffix for logical volume name (base... | [
"def",
"create_snapshot",
"(",
"self",
",",
"snapshot_size",
",",
"snapshot_suffix",
")",
":",
"size_extent",
"=",
"math",
".",
"ceil",
"(",
"self",
".",
"extents_count",
"(",
")",
"*",
"snapshot_size",
")",
"size_kb",
"=",
"self",
".",
"volume_group",
"(",
... | 45.380952 | 0.023638 |
def figure(key=None, fig=None, **kwargs):
"""Creates figures and switches between figures.
If a ``bqplot.Figure`` object is provided via the fig optional argument,
this figure becomes the current context figure.
Otherwise:
- If no key is provided, a new empty context figure is created.
- If a... | [
"def",
"figure",
"(",
"key",
"=",
"None",
",",
"fig",
"=",
"None",
",",
"*",
"*",
"kwargs",
")",
":",
"scales_arg",
"=",
"kwargs",
".",
"pop",
"(",
"'scales'",
",",
"{",
"}",
")",
"_context",
"[",
"'current_key'",
"]",
"=",
"key",
"if",
"fig",
"i... | 43.326923 | 0.000434 |
def store_fit_results(self, results_dict):
"""
Parameters
----------
results_dict : dict.
The estimation result dictionary that is output from
scipy.optimize.minimize. In addition to the standard keys which are
included, it should also contain the foll... | [
"def",
"store_fit_results",
"(",
"self",
",",
"results_dict",
")",
":",
"# Check to make sure the results_dict has all the needed keys.",
"self",
".",
"_check_result_dict_for_needed_keys",
"(",
"results_dict",
")",
"# Store the basic estimation results that simply need to be transferre... | 43.592233 | 0.000436 |
def query( self ):
"""
Returns the query that will be used for the widget.
:return (<str> term, <str> operator, <str> value)
"""
widget = self.uiWidgetAREA.widget()
if ( widget and type(widget) != QWidget ):
value = nativestring(widget.text())
... | [
"def",
"query",
"(",
"self",
")",
":",
"widget",
"=",
"self",
".",
"uiWidgetAREA",
".",
"widget",
"(",
")",
"if",
"(",
"widget",
"and",
"type",
"(",
"widget",
")",
"!=",
"QWidget",
")",
":",
"value",
"=",
"nativestring",
"(",
"widget",
".",
"text",
... | 34.058824 | 0.018487 |
def load_retinotopy_cache(sdir, sid, alignment='MSMAll'):
'''
Returns the subject's retinotopy cache as a lazy map, or None if no cache exists. The hemi keys
in the returned map will spell out the cortex name (e.g., lh_native_MSMAll or rh_LR32k_MSMAll).
'''
fs = {h:{(k,kk):os.path.join(sdir, 'retino... | [
"def",
"load_retinotopy_cache",
"(",
"sdir",
",",
"sid",
",",
"alignment",
"=",
"'MSMAll'",
")",
":",
"fs",
"=",
"{",
"h",
":",
"{",
"(",
"k",
",",
"kk",
")",
":",
"os",
".",
"path",
".",
"join",
"(",
"sdir",
",",
"'retinotopy'",
",",
"v",
"%",
... | 49.45 | 0.019841 |
def get_notes(ref_key, ref_id, **kwargs):
"""
Get all the notes for a resource, identifed by ref_key and ref_ido.
Returns [] if no notes are found or if the resource doesn't exist.
"""
notes = db.DBSession.query(Note).filter(Note.ref_key==ref_key)
if ref_key == 'NETWORK':
notes =... | [
"def",
"get_notes",
"(",
"ref_key",
",",
"ref_id",
",",
"*",
"*",
"kwargs",
")",
":",
"notes",
"=",
"db",
".",
"DBSession",
".",
"query",
"(",
"Note",
")",
".",
"filter",
"(",
"Note",
".",
"ref_key",
"==",
"ref_key",
")",
"if",
"ref_key",
"==",
"'N... | 36.25 | 0.00224 |
def create_gamma_model(alignment, missing_data=None, ncat=4):
""" Create a phylo_utils.likelihood.GammaMixture for calculating
likelihood on a tree, from a treeCl.Alignment and its matching
treeCl.Parameters """
model = alignment.parameters.partitions.model
freqs = alignment.parameters.partitions.f... | [
"def",
"create_gamma_model",
"(",
"alignment",
",",
"missing_data",
"=",
"None",
",",
"ncat",
"=",
"4",
")",
":",
"model",
"=",
"alignment",
".",
"parameters",
".",
"partitions",
".",
"model",
"freqs",
"=",
"alignment",
".",
"parameters",
".",
"partitions",
... | 42.1 | 0.002323 |
def register_alias(self, alias, key):
"""Aliases provide another accessor for the same key.
This enables one to change a name without breaking the application.
"""
alias = alias.lower()
key = key.lower()
if alias != key and alias != self._real_key(key):
exists... | [
"def",
"register_alias",
"(",
"self",
",",
"alias",
",",
"key",
")",
":",
"alias",
"=",
"alias",
".",
"lower",
"(",
")",
"key",
"=",
"key",
".",
"lower",
"(",
")",
"if",
"alias",
"!=",
"key",
"and",
"alias",
"!=",
"self",
".",
"_real_key",
"(",
"... | 41.647059 | 0.00138 |
def basic_cancel(self, consumer_tag, nowait=False):
"""End a queue consumer
This method cancels a consumer. This does not affect already
delivered messages, but it does mean the server will not send
any more messages for that consumer. The client may receive
an abitrary number ... | [
"def",
"basic_cancel",
"(",
"self",
",",
"consumer_tag",
",",
"nowait",
"=",
"False",
")",
":",
"if",
"self",
".",
"connection",
"is",
"not",
"None",
":",
"self",
".",
"no_ack_consumers",
".",
"discard",
"(",
"consumer_tag",
")",
"args",
"=",
"AMQPWriter",... | 35.510204 | 0.001119 |
def validate_proxy(path):
"""Validate the users X509 proxy certificate
Tests that the proxy certificate is RFC 3820 compliant and that it
is valid for at least the next 15 minutes.
@returns: L{True} if the certificate validates
@raises RuntimeError: if the certificate cannot be validated
"""
... | [
"def",
"validate_proxy",
"(",
"path",
")",
":",
"# load the proxy from path",
"try",
":",
"proxy",
"=",
"M2Crypto",
".",
"X509",
".",
"load_cert",
"(",
"path",
")",
"except",
"Exception",
",",
"e",
":",
"msg",
"=",
"\"Unable to load proxy from path %s : %s\"",
"... | 38.938776 | 0.001534 |
def _get_context(keyspaces, connections):
"""Return all the execution contexts"""
if keyspaces:
if not isinstance(keyspaces, (list, tuple)):
raise ValueError('keyspaces must be a list or a tuple.')
if connections:
if not isinstance(connections, (list, tuple)):
raise... | [
"def",
"_get_context",
"(",
"keyspaces",
",",
"connections",
")",
":",
"if",
"keyspaces",
":",
"if",
"not",
"isinstance",
"(",
"keyspaces",
",",
"(",
"list",
",",
"tuple",
")",
")",
":",
"raise",
"ValueError",
"(",
"'keyspaces must be a list or a tuple.'",
")"... | 34.133333 | 0.001901 |
def dot(self, vec):
"""Return the dot product of self and another Vec2."""
return self.x * vec.x + self.y * vec.y | [
"def",
"dot",
"(",
"self",
",",
"vec",
")",
":",
"return",
"self",
".",
"x",
"*",
"vec",
".",
"x",
"+",
"self",
".",
"y",
"*",
"vec",
".",
"y"
] | 31.75 | 0.015385 |
def get_metadata(self, entity_type, entity_id):
'''Get metadata of an entity.
Args:
entity_type (str): Type of the entity. Admitted values: ['project',
'folder', 'file'].
entity_id (str): The UUID of the entity to be modified.
Returns:
A dict... | [
"def",
"get_metadata",
"(",
"self",
",",
"entity_type",
",",
"entity_id",
")",
":",
"if",
"not",
"is_valid_uuid",
"(",
"entity_id",
")",
":",
"raise",
"StorageArgumentException",
"(",
"'Invalid UUID for entity_id: {0}'",
".",
"format",
"(",
"entity_id",
")",
")",
... | 33.866667 | 0.001914 |
def auth_encrypt(self, P, A, seq_num=None):
"""
Encrypt the data then prepend the explicit part of the nonce. The
authentication tag is directly appended with the most recent crypto
API. Additional data may be authenticated without encryption (as A).
The 'seq_num' should never b... | [
"def",
"auth_encrypt",
"(",
"self",
",",
"P",
",",
"A",
",",
"seq_num",
"=",
"None",
")",
":",
"if",
"False",
"in",
"six",
".",
"itervalues",
"(",
"self",
".",
"ready",
")",
":",
"raise",
"CipherError",
"(",
"P",
",",
"A",
")",
"if",
"hasattr",
"... | 44.481481 | 0.00163 |
def set_debug(enabled: bool):
"""Enable or disable debug logs for the entire package.
Parameters
----------
enabled: bool
Whether debug should be enabled or not.
"""
global _DEBUG_ENABLED
if not enabled:
log('Disabling debug output...', logger_name=_LOGGER_NAME)
_D... | [
"def",
"set_debug",
"(",
"enabled",
":",
"bool",
")",
":",
"global",
"_DEBUG_ENABLED",
"if",
"not",
"enabled",
":",
"log",
"(",
"'Disabling debug output...'",
",",
"logger_name",
"=",
"_LOGGER_NAME",
")",
"_DEBUG_ENABLED",
"=",
"False",
"else",
":",
"_DEBUG_ENAB... | 25.294118 | 0.002242 |
def query_cumulative_flags(ifo, segment_names, start_time, end_time,
source='any', server="segments.ligo.org",
veto_definer=None,
bounds=None,
padding=None,
override_ifos=None,
... | [
"def",
"query_cumulative_flags",
"(",
"ifo",
",",
"segment_names",
",",
"start_time",
",",
"end_time",
",",
"source",
"=",
"'any'",
",",
"server",
"=",
"\"segments.ligo.org\"",
",",
"veto_definer",
"=",
"None",
",",
"bounds",
"=",
"None",
",",
"padding",
"=",
... | 37.753623 | 0.000748 |
def mirrors(name, location):
"""
Select Slackware official mirror packages
based architecture and version.
"""
rel = _meta_.slack_rel
ver = slack_ver()
repo = Repo().slack()
if _meta_.arch == "x86_64":
if rel == "stable":
http = repo + "slackware64-{0}/{1}{2}".format(... | [
"def",
"mirrors",
"(",
"name",
",",
"location",
")",
":",
"rel",
"=",
"_meta_",
".",
"slack_rel",
"ver",
"=",
"slack_ver",
"(",
")",
"repo",
"=",
"Repo",
"(",
")",
".",
"slack",
"(",
")",
"if",
"_meta_",
".",
"arch",
"==",
"\"x86_64\"",
":",
"if",
... | 36.416667 | 0.001115 |
def get_hardware_breakpoint(self, dwThreadId, address):
"""
Returns the internally used breakpoint object,
for the code breakpoint defined at the given address.
@warning: It's usually best to call the L{Debug} methods
instead of accessing the breakpoint objects directly.
... | [
"def",
"get_hardware_breakpoint",
"(",
"self",
",",
"dwThreadId",
",",
"address",
")",
":",
"if",
"dwThreadId",
"not",
"in",
"self",
".",
"__hardwareBP",
":",
"msg",
"=",
"\"No hardware breakpoints set for thread %d\"",
"raise",
"KeyError",
"(",
"msg",
"%",
"dwThr... | 37.5 | 0.001529 |
def main():
"""for resolving names from command line"""
parser = argparse.ArgumentParser(description='Python module name to'
'package name')
group = parser.add_mutually_exclusive_group()
group.add_argument('--dist', help='distribution style '
'... | [
"def",
"main",
"(",
")",
":",
"parser",
"=",
"argparse",
".",
"ArgumentParser",
"(",
"description",
"=",
"'Python module name to'",
"'package name'",
")",
"group",
"=",
"parser",
".",
"add_mutually_exclusive_group",
"(",
")",
"group",
".",
"add_argument",
"(",
"... | 45 | 0.000725 |
def linear(target, m, b, prop):
r"""
Calculates a property as a linear function of a given property
Parameters
----------
target : OpenPNM Object
The object for which these values are being calculated. This
controls the length of the calculated array, and also provides
acce... | [
"def",
"linear",
"(",
"target",
",",
"m",
",",
"b",
",",
"prop",
")",
":",
"x",
"=",
"target",
"[",
"prop",
"]",
"value",
"=",
"m",
"*",
"x",
"+",
"b",
"return",
"value"
] | 28.272727 | 0.001555 |
def add_directory(self, relativePath, info=None):
"""
Adds a directory in the repository and creates its
attribute in the Repository with utc timestamp.
It insures adding all the missing directories in the path.
:Parameters:
#. relativePath (string): The relative to ... | [
"def",
"add_directory",
"(",
"self",
",",
"relativePath",
",",
"info",
"=",
"None",
")",
":",
"path",
"=",
"os",
".",
"path",
".",
"normpath",
"(",
"relativePath",
")",
"# create directories",
"currentDir",
"=",
"self",
".",
"path",
"currentDict",
"=",
"se... | 39.170732 | 0.009113 |
def postorder(self, node=None):
"""Walk the tree in roughly 'postorder' (a bit of a lie
explained below).
For each node with typestring name *name* if the
node has a method called n_*name*, call that before walking
children. If there is no method define, call a
self.defa... | [
"def",
"postorder",
"(",
"self",
",",
"node",
"=",
"None",
")",
":",
"if",
"node",
"is",
"None",
":",
"node",
"=",
"self",
".",
"ast",
"try",
":",
"first",
"=",
"iter",
"(",
"node",
")",
"except",
"TypeError",
":",
"first",
"=",
"None",
"if",
"fi... | 32.090909 | 0.001375 |
def write_version_info(conn, version_table, version_value):
"""
Inserts the version value in to the version table.
Parameters
----------
conn : sa.Connection
The connection to use to execute the insert.
version_table : sa.Table
The version table of the asset database
version... | [
"def",
"write_version_info",
"(",
"conn",
",",
"version_table",
",",
"version_value",
")",
":",
"conn",
".",
"execute",
"(",
"sa",
".",
"insert",
"(",
"version_table",
",",
"values",
"=",
"{",
"'version'",
":",
"version_value",
"}",
")",
")"
] | 30.2 | 0.002141 |
def seq_length_dist_plot (self):
""" Create the HTML for the Sequence Length Distribution plot """
data = dict()
seq_lengths = set()
multiple_lenths = False
for s_name in self.fastqc_data:
try:
data[s_name] = {self.avg_bp_from_range(d['length']): d['c... | [
"def",
"seq_length_dist_plot",
"(",
"self",
")",
":",
"data",
"=",
"dict",
"(",
")",
"seq_lengths",
"=",
"set",
"(",
")",
"multiple_lenths",
"=",
"False",
"for",
"s_name",
"in",
"self",
".",
"fastqc_data",
":",
"try",
":",
"data",
"[",
"s_name",
"]",
"... | 47.87234 | 0.01176 |
def transformFromNative(obj):
"""
Replace the date, datetime or period tuples in obj.value with
appropriate strings.
"""
if obj.value and type(obj.value[0]) == datetime.date:
obj.isNative = False
obj.value_param = 'DATE'
obj.value = ','.join([d... | [
"def",
"transformFromNative",
"(",
"obj",
")",
":",
"if",
"obj",
".",
"value",
"and",
"type",
"(",
"obj",
".",
"value",
"[",
"0",
"]",
")",
"==",
"datetime",
".",
"date",
":",
"obj",
".",
"isNative",
"=",
"False",
"obj",
".",
"value_param",
"=",
"'... | 39.666667 | 0.002051 |
def deep_shap(model, data):
""" Deep SHAP (DeepLIFT)
"""
if isinstance(model, KerasWrap):
model = model.model
explainer = DeepExplainer(model, kmeans(data, 1).data)
def f(X):
phi = explainer.shap_values(X)
if type(phi) is list and len(phi) == 1:
return phi[0]
... | [
"def",
"deep_shap",
"(",
"model",
",",
"data",
")",
":",
"if",
"isinstance",
"(",
"model",
",",
"KerasWrap",
")",
":",
"model",
"=",
"model",
".",
"model",
"explainer",
"=",
"DeepExplainer",
"(",
"model",
",",
"kmeans",
"(",
"data",
",",
"1",
")",
".... | 25.5 | 0.008108 |
def add_row_number(self, column_name='id', start=0, inplace=False):
"""
Returns an SFrame with a new column that numbers each row
sequentially. By default the count starts at 0, but this can be changed
to a positive or negative number. The new column will be named with
the given... | [
"def",
"add_row_number",
"(",
"self",
",",
"column_name",
"=",
"'id'",
",",
"start",
"=",
"0",
",",
"inplace",
"=",
"False",
")",
":",
"if",
"type",
"(",
"column_name",
")",
"is",
"not",
"str",
":",
"raise",
"TypeError",
"(",
"\"Must give column_name as st... | 32.916667 | 0.001639 |
def _build_authorization_request_url(
self,
response_type,
redirect_url,
state=None
):
"""Form URL to request an auth code or access token.
Parameters
response_type (str)
Either 'code' (Authorization Code Grant) or
'token' ... | [
"def",
"_build_authorization_request_url",
"(",
"self",
",",
"response_type",
",",
"redirect_url",
",",
"state",
"=",
"None",
")",
":",
"if",
"response_type",
"not",
"in",
"auth",
".",
"VALID_RESPONSE_TYPES",
":",
"message",
"=",
"'{} is not a valid response type.'",
... | 35.219512 | 0.002022 |
def get_data(self, params={}):
"""
Make the request and return the deserialided JSON from the response
:param params: Dictionary mapping (string) query parameters to values
:type params: dict
:return: JSON object with the data fetched from that URL as a
JSON-for... | [
"def",
"get_data",
"(",
"self",
",",
"params",
"=",
"{",
"}",
")",
":",
"if",
"self",
"and",
"hasattr",
"(",
"self",
",",
"'proxies'",
")",
"and",
"self",
".",
"proxies",
"is",
"not",
"None",
":",
"response",
"=",
"requests",
".",
"request",
"(",
"... | 46.233333 | 0.001412 |
def set_random_seed():
"""Set the random seed from flag everywhere."""
tf.set_random_seed(FLAGS.random_seed)
random.seed(FLAGS.random_seed)
np.random.seed(FLAGS.random_seed) | [
"def",
"set_random_seed",
"(",
")",
":",
"tf",
".",
"set_random_seed",
"(",
"FLAGS",
".",
"random_seed",
")",
"random",
".",
"seed",
"(",
"FLAGS",
".",
"random_seed",
")",
"np",
".",
"random",
".",
"seed",
"(",
"FLAGS",
".",
"random_seed",
")"
] | 35.4 | 0.027624 |
def _get_default_tempdir():
"""Calculate the default directory to use for temporary files.
This routine should be called exactly once.
We determine whether or not a candidate temp dir is usable by
trying to create and write to a file in that directory. If this
is successful, the test file is delet... | [
"def",
"_get_default_tempdir",
"(",
")",
":",
"namer",
"=",
"_RandomNameSequence",
"(",
")",
"dirlist",
"=",
"_candidate_tempdir_list",
"(",
")",
"for",
"dir",
"in",
"dirlist",
":",
"if",
"dir",
"!=",
"_os",
".",
"curdir",
":",
"dir",
"=",
"_os",
".",
"p... | 38.081081 | 0.000692 |
def QA_indicator_OBV(DataFrame):
"""能量潮"""
VOL = DataFrame.volume
CLOSE = DataFrame.close
return pd.DataFrame({
'OBV': np.cumsum(IF(CLOSE > REF(CLOSE, 1), VOL, IF(CLOSE < REF(CLOSE, 1), -VOL, 0)))/10000
}) | [
"def",
"QA_indicator_OBV",
"(",
"DataFrame",
")",
":",
"VOL",
"=",
"DataFrame",
".",
"volume",
"CLOSE",
"=",
"DataFrame",
".",
"close",
"return",
"pd",
".",
"DataFrame",
"(",
"{",
"'OBV'",
":",
"np",
".",
"cumsum",
"(",
"IF",
"(",
"CLOSE",
">",
"REF",
... | 32.428571 | 0.008584 |
def _getCandidateParticleAndSwarm (self, exhaustedSwarmId=None):
"""Find or create a candidate particle to produce a new model.
At any one time, there is an active set of swarms in the current sprint, where
each swarm in the sprint represents a particular combination of fields.
Ideally, we should try t... | [
"def",
"_getCandidateParticleAndSwarm",
"(",
"self",
",",
"exhaustedSwarmId",
"=",
"None",
")",
":",
"# Cancel search?",
"jobCancel",
"=",
"self",
".",
"_cjDAO",
".",
"jobGetFields",
"(",
"self",
".",
"_jobID",
",",
"[",
"'cancel'",
"]",
")",
"[",
"0",
"]",
... | 48.091483 | 0.00874 |
def format_variant(line, header_parser, check_info=False):
"""
Yield the variant in the right format.
If the variants should be splitted on alternative alles one variant
for each alternative will be yielded.
Arguments:
line (str): A string that represents a variant line in the vc... | [
"def",
"format_variant",
"(",
"line",
",",
"header_parser",
",",
"check_info",
"=",
"False",
")",
":",
"logger",
"=",
"getLogger",
"(",
"__name__",
")",
"individuals",
"=",
"[",
"]",
"vcf_header",
"=",
"header_parser",
".",
"header",
"individuals",
"=",
"hea... | 33.078125 | 0.009402 |
def updateObj(self, event):
"""Put this object in the search box"""
name = self.objList.get("active")
self.SearchVar.set(name)
self.object_info.set(str(self.kbos.get(name, '')))
return | [
"def",
"updateObj",
"(",
"self",
",",
"event",
")",
":",
"name",
"=",
"self",
".",
"objList",
".",
"get",
"(",
"\"active\"",
")",
"self",
".",
"SearchVar",
".",
"set",
"(",
"name",
")",
"self",
".",
"object_info",
".",
"set",
"(",
"str",
"(",
"self... | 31.285714 | 0.008889 |
def avail_sizes(call=None):
'''
Return a dict of all available VM sizes on the cloud provider with
relevant data.
'''
if call == 'action':
raise SaltCloudSystemExit(
'The avail_sizes function must be called with '
'-f or --function, or with the --list-sizes option'
... | [
"def",
"avail_sizes",
"(",
"call",
"=",
"None",
")",
":",
"if",
"call",
"==",
"'action'",
":",
"raise",
"SaltCloudSystemExit",
"(",
"'The avail_sizes function must be called with '",
"'-f or --function, or with the --list-sizes option'",
")",
"conn",
"=",
"get_conn",
"(",... | 24.625 | 0.002445 |
def unpack_char16(self, data):
"""
Unpack a CIM-XML string value of CIM type 'char16' and return it
as a unicode string object, or None.
data (unicode string): CIM-XML string value, or None (in which case
None is returned).
"""
if data is None:
ret... | [
"def",
"unpack_char16",
"(",
"self",
",",
"data",
")",
":",
"if",
"data",
"is",
"None",
":",
"return",
"None",
"len_data",
"=",
"len",
"(",
"data",
")",
"if",
"len_data",
"==",
"0",
":",
"raise",
"CIMXMLParseError",
"(",
"\"Char16 value is empty\"",
",",
... | 32.472222 | 0.001661 |
def _large_mrca(self, ts):
"""Find the MRCA using a temporary table."""
cursor = self.db.cursor()
cursor.execute("""
DROP TABLE IF EXISTS _mrca_temp
""")
cursor.execute("""
CREATE TEMPORARY TABLE _mrca_temp(
child TEXT PRIMARY KEY REFEREN... | [
"def",
"_large_mrca",
"(",
"self",
",",
"ts",
")",
":",
"cursor",
"=",
"self",
".",
"db",
".",
"cursor",
"(",
")",
"cursor",
".",
"execute",
"(",
"\"\"\"\n DROP TABLE IF EXISTS _mrca_temp\n \"\"\"",
")",
"cursor",
".",
"execute",
"(",
"\"\"\"\n... | 27.9375 | 0.002162 |
def resolve_prefix_path(cls, start_path=None):
"""
Look for an existing prefix in the given path, in a path/.lago dir, or
in a .lago dir under any of it's parent directories
Args:
start_path (str): path to start the search from, if None passed, it
will use th... | [
"def",
"resolve_prefix_path",
"(",
"cls",
",",
"start_path",
"=",
"None",
")",
":",
"if",
"not",
"start_path",
"or",
"start_path",
"==",
"'auto'",
":",
"start_path",
"=",
"os",
".",
"path",
".",
"curdir",
"cur_path",
"=",
"start_path",
"LOGGER",
".",
"debu... | 36.210526 | 0.001415 |
def to_dict(self):
"""Convert back to the pstats dictionary representation (used for saving back as pstats binary file)"""
if self.subcall is not None:
if isinstance(self.subcall, dict):
subcalls = self.subcall
else:
subcalls = {}
f... | [
"def",
"to_dict",
"(",
"self",
")",
":",
"if",
"self",
".",
"subcall",
"is",
"not",
"None",
":",
"if",
"isinstance",
"(",
"self",
".",
"subcall",
",",
"dict",
")",
":",
"subcalls",
"=",
"self",
".",
"subcall",
"else",
":",
"subcalls",
"=",
"{",
"}"... | 53.5 | 0.011811 |
def initiate_migration(self):
"""
Initiates a pending migration that is already scheduled for this Linode
Instance
"""
self._client.post('{}/migrate'.format(Instance.api_endpoint), model=self) | [
"def",
"initiate_migration",
"(",
"self",
")",
":",
"self",
".",
"_client",
".",
"post",
"(",
"'{}/migrate'",
".",
"format",
"(",
"Instance",
".",
"api_endpoint",
")",
",",
"model",
"=",
"self",
")"
] | 37.833333 | 0.012931 |
def set_config(config, overwrite=False):
'''
Updates the global configuration.
:param config: Can be a dictionary containing configuration, or a string
which represents a (relative) configuration filename.
'''
if config is None:
config = get_conf_path_from_env()
# m... | [
"def",
"set_config",
"(",
"config",
",",
"overwrite",
"=",
"False",
")",
":",
"if",
"config",
"is",
"None",
":",
"config",
"=",
"get_conf_path_from_env",
"(",
")",
"# must be after the fallback other a bad fallback will incorrectly clear",
"if",
"overwrite",
"is",
"Tr... | 33.333333 | 0.001215 |
def _handle_type(self, other):
"""Helper to handle the return type."""
if isinstance(other, Int):
return Int
elif isinstance(other, Float):
return Float
else:
raise TypeError(
f"Unsuported operation between `{type(self)}` and `{type(oth... | [
"def",
"_handle_type",
"(",
"self",
",",
"other",
")",
":",
"if",
"isinstance",
"(",
"other",
",",
"Int",
")",
":",
"return",
"Int",
"elif",
"isinstance",
"(",
"other",
",",
"Float",
")",
":",
"return",
"Float",
"else",
":",
"raise",
"TypeError",
"(",
... | 33.2 | 0.008798 |
def parsetime(s):
"""Internal function to parse the time parses time in HH:MM:SS.mmm format.
Returns:
a four-tuple ``(hours,minutes,seconds,milliseconds)``
"""
try:
fields = s.split('.')
subfields = fields[0].split(':')
H = int(subfields[0])
M = int(subfields[1])... | [
"def",
"parsetime",
"(",
"s",
")",
":",
"try",
":",
"fields",
"=",
"s",
".",
"split",
"(",
"'.'",
")",
"subfields",
"=",
"fields",
"[",
"0",
"]",
".",
"split",
"(",
"':'",
")",
"H",
"=",
"int",
"(",
"subfields",
"[",
"0",
"]",
")",
"M",
"=",
... | 28.904762 | 0.009569 |
def set_calibration(self, attenuations, freqs, frange, calname):
"""See :meth:`AbstractAcquisitionRunner<sparkle.run.abstract_acquisition.AbstractAcquisitionRunner.set_calibration>`"""
self.protocol_model.setCalibration(attenuations, freqs, frange)
self.calname = calname
self.cal_frange ... | [
"def",
"set_calibration",
"(",
"self",
",",
"attenuations",
",",
"freqs",
",",
"frange",
",",
"calname",
")",
":",
"self",
".",
"protocol_model",
".",
"setCalibration",
"(",
"attenuations",
",",
"freqs",
",",
"frange",
")",
"self",
".",
"calname",
"=",
"ca... | 64.8 | 0.009146 |
def xyz2lonlat(x,y,z):
"""
Convert x,y,z representation of points *on the unit sphere* of the
spherical triangulation to lon / lat (radians).
Note - no check is made here that (x,y,z) are unit vectors
"""
xs = np.array(x)
ys = np.array(y)
zs = np.array(z)
lons = np.arctan2(ys, xs)... | [
"def",
"xyz2lonlat",
"(",
"x",
",",
"y",
",",
"z",
")",
":",
"xs",
"=",
"np",
".",
"array",
"(",
"x",
")",
"ys",
"=",
"np",
".",
"array",
"(",
"y",
")",
"zs",
"=",
"np",
".",
"array",
"(",
"z",
")",
"lons",
"=",
"np",
".",
"arctan2",
"(",... | 22.0625 | 0.008152 |
def newCDataBlock(self, content, len):
"""Creation of a new node containing a CDATA block. """
ret = libxml2mod.xmlNewCDataBlock(self._o, content, len)
if ret is None:raise treeError('xmlNewCDataBlock() failed')
__tmp = xmlNode(_obj=ret)
return __tmp | [
"def",
"newCDataBlock",
"(",
"self",
",",
"content",
",",
"len",
")",
":",
"ret",
"=",
"libxml2mod",
".",
"xmlNewCDataBlock",
"(",
"self",
".",
"_o",
",",
"content",
",",
"len",
")",
"if",
"ret",
"is",
"None",
":",
"raise",
"treeError",
"(",
"'xmlNewCD... | 47.5 | 0.013793 |
def convert_embedding(net, node, model, builder):
"""Convert an embedding layer from mxnet to coreml.
Parameters
----------
net: network
A mxnet network object.
node: layer
Node to convert.
model: model
An model for MXNet
builder: NeuralNetworkBuilder
A ne... | [
"def",
"convert_embedding",
"(",
"net",
",",
"node",
",",
"model",
",",
"builder",
")",
":",
"input_name",
",",
"output_name",
"=",
"_get_input_output_name",
"(",
"net",
",",
"node",
")",
"name",
"=",
"node",
"[",
"'name'",
"]",
"inputs",
"=",
"node",
"[... | 30.244444 | 0.02847 |
def addLogForRemoteCommands(self, logname):
"""This method must be called by user classes
composite steps could create several logs, this mixin functions will write
to the last one.
"""
self.rc_log = self.addLog(logname)
return self.rc_log | [
"def",
"addLogForRemoteCommands",
"(",
"self",
",",
"logname",
")",
":",
"self",
".",
"rc_log",
"=",
"self",
".",
"addLog",
"(",
"logname",
")",
"return",
"self",
".",
"rc_log"
] | 40.142857 | 0.010453 |
def _check_package(pkg_xml, zipfilename, zf):
"""
Helper for ``build_index()``: Perform some checks to make sure that
the given package is consistent.
"""
# The filename must patch the id given in the XML file.
uid = os.path.splitext(os.path.split(zipfilename)[1])[0]
if pkg_xml.get('id') != uid:
raise... | [
"def",
"_check_package",
"(",
"pkg_xml",
",",
"zipfilename",
",",
"zf",
")",
":",
"# The filename must patch the id given in the XML file.",
"uid",
"=",
"os",
".",
"path",
".",
"splitext",
"(",
"os",
".",
"path",
".",
"split",
"(",
"zipfilename",
")",
"[",
"1"... | 41.4375 | 0.020649 |
def register_interaction(key=None):
"""Decorator registering an interaction class in the registry.
If no key is provided, the class name is used as a key. A key is provided
for each core bqplot interaction type so that the frontend can use this
key regardless of the kernal language.
"""
def wra... | [
"def",
"register_interaction",
"(",
"key",
"=",
"None",
")",
":",
"def",
"wrap",
"(",
"interaction",
")",
":",
"name",
"=",
"key",
"if",
"key",
"is",
"not",
"None",
"else",
"interaction",
".",
"__module__",
"+",
"interaction",
".",
"__name__",
"interaction... | 39.615385 | 0.001898 |
def _get_stories(self, page, limit):
"""
Hacker News has different categories (i.e. stories) like
'topstories', 'newstories', 'askstories', 'showstories', 'jobstories'.
This method, first fetches the relevant story ids of that category
The URL is: https://hacker-news.firebaseio.... | [
"def",
"_get_stories",
"(",
"self",
",",
"page",
",",
"limit",
")",
":",
"url",
"=",
"urljoin",
"(",
"self",
".",
"base_url",
",",
"F\"{page}.json\"",
")",
"story_ids",
"=",
"self",
".",
"_get_sync",
"(",
"url",
")",
"[",
":",
"limit",
"]",
"return",
... | 39.380952 | 0.002361 |
def send_all_messages(self, close_on_done=True):
"""Send all pending messages in the queue. This will return a list
of the send result of all the pending messages so it can be
determined if any messages failed to send.
This function will open the client if it is not already open.
... | [
"def",
"send_all_messages",
"(",
"self",
",",
"close_on_done",
"=",
"True",
")",
":",
"self",
".",
"open",
"(",
")",
"running",
"=",
"True",
"try",
":",
"messages",
"=",
"self",
".",
"_pending_messages",
"[",
":",
"]",
"running",
"=",
"self",
".",
"wai... | 38.142857 | 0.002436 |
def set_background(self, color, loc='all'):
"""
Sets background color
Parameters
----------
color : string or 3 item list, optional, defaults to white
Either a string, rgb list, or hex color string. For example:
color='white'
color='w... | [
"def",
"set_background",
"(",
"self",
",",
"color",
",",
"loc",
"=",
"'all'",
")",
":",
"if",
"color",
"is",
"None",
":",
"color",
"=",
"rcParams",
"[",
"'background'",
"]",
"if",
"isinstance",
"(",
"color",
",",
"str",
")",
":",
"if",
"color",
".",
... | 34.794118 | 0.002467 |
def trigger_update_by_trigger_name(self, trigger_name, data, **kwargs):
"https://developer.zendesk.com/rest_api/docs/chat/triggers#update-trigger"
api_path = "/api/v2/triggers/{trigger_name}"
api_path = api_path.format(trigger_name=trigger_name)
return self.call(api_path, method="PUT", d... | [
"def",
"trigger_update_by_trigger_name",
"(",
"self",
",",
"trigger_name",
",",
"data",
",",
"*",
"*",
"kwargs",
")",
":",
"api_path",
"=",
"\"/api/v2/triggers/{trigger_name}\"",
"api_path",
"=",
"api_path",
".",
"format",
"(",
"trigger_name",
"=",
"trigger_name",
... | 67 | 0.00885 |
def cli(env, volume_id, sortby, columns):
"""List block storage snapshots."""
block_manager = SoftLayer.BlockStorageManager(env.client)
snapshots = block_manager.get_block_volume_snapshot_list(
volume_id,
mask=columns.mask()
)
table = formatting.Table(columns.columns)
table.sort... | [
"def",
"cli",
"(",
"env",
",",
"volume_id",
",",
"sortby",
",",
"columns",
")",
":",
"block_manager",
"=",
"SoftLayer",
".",
"BlockStorageManager",
"(",
"env",
".",
"client",
")",
"snapshots",
"=",
"block_manager",
".",
"get_block_volume_snapshot_list",
"(",
"... | 30 | 0.00202 |
def search(
self,
search_space,
valid_data,
init_args=[],
train_args=[],
init_kwargs={},
train_kwargs={},
module_args={},
module_kwargs={},
max_search=None,
shuffle=True,
verbose=True,
**score_kwargs,
):
... | [
"def",
"search",
"(",
"self",
",",
"search_space",
",",
"valid_data",
",",
"init_args",
"=",
"[",
"]",
",",
"train_args",
"=",
"[",
"]",
",",
"init_kwargs",
"=",
"{",
"}",
",",
"train_kwargs",
"=",
"{",
"}",
",",
"module_args",
"=",
"{",
"}",
",",
... | 38.810811 | 0.002038 |
def parse_tmhmm_long(tmhmm_results):
"""Parse the 'long' output format of TMHMM and return a dictionary of ``{sequence_ID: TMHMM_prediction}``.
Args:
tmhmm_results (str): Path to long format TMHMM output.
Returns:
dict: Dictionary of ``{sequence_ID: TMHMM_prediction}``
"""
with op... | [
"def",
"parse_tmhmm_long",
"(",
"tmhmm_results",
")",
":",
"with",
"open",
"(",
"tmhmm_results",
")",
"as",
"f",
":",
"lines",
"=",
"f",
".",
"read",
"(",
")",
".",
"splitlines",
"(",
")",
"infodict",
"=",
"defaultdict",
"(",
"dict",
")",
"for",
"l",
... | 30.122807 | 0.001692 |
def by_command(extractor, prefix=('/',), separator=' ', pass_args=False):
"""
:param extractor:
a function that takes one argument (the message) and returns a portion
of message to be interpreted. To extract the text of a chat message,
use ``lambda msg: msg['text']``.
:param prefix:... | [
"def",
"by_command",
"(",
"extractor",
",",
"prefix",
"=",
"(",
"'/'",
",",
")",
",",
"separator",
"=",
"' '",
",",
"pass_args",
"=",
"False",
")",
":",
"if",
"not",
"isinstance",
"(",
"prefix",
",",
"(",
"tuple",
",",
"list",
")",
")",
":",
"prefi... | 37.694444 | 0.002155 |
def from_dict(data, ctx):
"""
Instantiate a new HomeConversions from a dict (generally from loading a
JSON response). The data used to instantiate the HomeConversions is a
shallow copy of the dict passed in, with any complex child types
instantiated appropriately.
"""
... | [
"def",
"from_dict",
"(",
"data",
",",
"ctx",
")",
":",
"data",
"=",
"data",
".",
"copy",
"(",
")",
"if",
"data",
".",
"get",
"(",
"'accountGain'",
")",
"is",
"not",
"None",
":",
"data",
"[",
"'accountGain'",
"]",
"=",
"ctx",
".",
"convert_decimal_num... | 33.076923 | 0.00226 |
def increase_verbosity():
"""
Increase the verbosity of the root handler by one defined level.
Understands custom logging levels like defined by my ``verboselogs``
module.
"""
defined_levels = sorted(set(find_defined_levels().values()))
current_index = defined_levels.index(get_level())
... | [
"def",
"increase_verbosity",
"(",
")",
":",
"defined_levels",
"=",
"sorted",
"(",
"set",
"(",
"find_defined_levels",
"(",
")",
".",
"values",
"(",
")",
")",
")",
"current_index",
"=",
"defined_levels",
".",
"index",
"(",
"get_level",
"(",
")",
")",
"select... | 36.181818 | 0.002451 |
def value(self):
"""gets the color value"""
return [self._red,
self._green,
self._blue,
self._alpha] | [
"def",
"value",
"(",
"self",
")",
":",
"return",
"[",
"self",
".",
"_red",
",",
"self",
".",
"_green",
",",
"self",
".",
"_blue",
",",
"self",
".",
"_alpha",
"]"
] | 26.5 | 0.012195 |
def _make_leading_paths(self, src, mode=0o700):
"""Create leading path components
The standard python `os.makedirs` is insufficient for our
needs: it will only create directories, and ignores the fact
that some path components may be symbolic links.
:param src: ... | [
"def",
"_make_leading_paths",
"(",
"self",
",",
"src",
",",
"mode",
"=",
"0o700",
")",
":",
"self",
".",
"log_debug",
"(",
"\"Making leading paths for %s\"",
"%",
"src",
")",
"root",
"=",
"self",
".",
"_archive_root",
"dest",
"=",
"src",
"def",
"in_archive",... | 39.164706 | 0.000586 |
def hook_outputs(modules:Collection[nn.Module], detach:bool=True, grad:bool=False)->Hooks:
"Return `Hooks` that store activations of all `modules` in `self.stored`"
return Hooks(modules, _hook_inner, detach=detach, is_forward=not grad) | [
"def",
"hook_outputs",
"(",
"modules",
":",
"Collection",
"[",
"nn",
".",
"Module",
"]",
",",
"detach",
":",
"bool",
"=",
"True",
",",
"grad",
":",
"bool",
"=",
"False",
")",
"->",
"Hooks",
":",
"return",
"Hooks",
"(",
"modules",
",",
"_hook_inner",
... | 80.333333 | 0.041152 |
def encode_request(from_pid, to_pid, method, body=None, content_type=None, legacy=False):
"""
Encode a request into a raw HTTP request. This function returns a string
of bytes that represent a valid HTTP/1.0 request, including any libprocess
headers required for communication.
Use the `legacy` option (set to... | [
"def",
"encode_request",
"(",
"from_pid",
",",
"to_pid",
",",
"method",
",",
"body",
"=",
"None",
",",
"content_type",
"=",
"None",
",",
"legacy",
"=",
"False",
")",
":",
"if",
"body",
"is",
"None",
":",
"body",
"=",
"b''",
"if",
"not",
"isinstance",
... | 28.634146 | 0.014003 |
def __pack_message(operation, data):
"""Takes message data and adds a message header based on the operation.
Returns the resultant message string.
"""
request_id = random.randint(-2 ** 31 - 1, 2 ** 31)
message = struct.pack("<i", 16 + len(data))
message += struct.pack("<i", request_id)
mess... | [
"def",
"__pack_message",
"(",
"operation",
",",
"data",
")",
":",
"request_id",
"=",
"random",
".",
"randint",
"(",
"-",
"2",
"**",
"31",
"-",
"1",
",",
"2",
"**",
"31",
")",
"message",
"=",
"struct",
".",
"pack",
"(",
"\"<i\"",
",",
"16",
"+",
"... | 38.272727 | 0.00232 |
def to_postfix(tokens):
"""
Convert a list of evaluatable tokens to postfix format.
"""
precedence = {
'/': 4,
'*': 4,
'+': 3,
'-': 3,
'^': 2,
'(': 1
}
postfix = []
opstack = []
for token in tokens:
if is_int(token):
p... | [
"def",
"to_postfix",
"(",
"tokens",
")",
":",
"precedence",
"=",
"{",
"'/'",
":",
"4",
",",
"'*'",
":",
"4",
",",
"'+'",
":",
"3",
",",
"'-'",
":",
"3",
",",
"'^'",
":",
"2",
",",
"'('",
":",
"1",
"}",
"postfix",
"=",
"[",
"]",
"opstack",
"... | 25.023256 | 0.000894 |
def cell_attributes_from_template(target_tab, template_tab=0):
"""Adjusts cell paarmeters to match the template
Parameters
----------
target_tab: Integer
\tTable to be adjusted
template_tab: Integer, defaults to 0
\tTemplate table
"""
new_cell_attributes = []
for attr in S.cell_attributes:
if attr[1] == ... | [
"def",
"cell_attributes_from_template",
"(",
"target_tab",
",",
"template_tab",
"=",
"0",
")",
":",
"new_cell_attributes",
"=",
"[",
"]",
"for",
"attr",
"in",
"S",
".",
"cell_attributes",
":",
"if",
"attr",
"[",
"1",
"]",
"==",
"template_tab",
":",
"new_attr... | 25.1 | 0.03071 |
def is_complete(self):
"""Returns True if this is a complete solution, i.e, all nodes are allocated
Returns
-------
bool
True if all nodes are llocated.
"""
return all(
[node.route_allocation() is not None for node in list(self._nodes.valu... | [
"def",
"is_complete",
"(",
"self",
")",
":",
"return",
"all",
"(",
"[",
"node",
".",
"route_allocation",
"(",
")",
"is",
"not",
"None",
"for",
"node",
"in",
"list",
"(",
"self",
".",
"_nodes",
".",
"values",
"(",
")",
")",
"if",
"node",
"!=",
"self... | 32.636364 | 0.01355 |
def mkdir(self, path, title="", recurse=False):
"""
Make a new directory. If recurse is True, create parent directories
as required. Return the newly created TDirectory.
"""
head, tail = os.path.split(os.path.normpath(path))
if tail == "":
raise ValueError("in... | [
"def",
"mkdir",
"(",
"self",
",",
"path",
",",
"title",
"=",
"\"\"",
",",
"recurse",
"=",
"False",
")",
":",
"head",
",",
"tail",
"=",
"os",
".",
"path",
".",
"split",
"(",
"os",
".",
"path",
".",
"normpath",
"(",
"path",
")",
")",
"if",
"tail"... | 42.708333 | 0.001908 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.