text stringlengths 75 104k | code_tokens list | avg_line_len float64 7.91 980 | score float64 0 0.18 |
|---|---|---|---|
def aroon_down(data, period):
"""
Aroon Down.
Formula:
AROONDWN = (((PERIOD) - (PERIODS SINCE PERIOD LOW)) / (PERIOD)) * 100
"""
catch_errors.check_for_period_error(data, period)
period = int(period)
a_down = [((period -
list(reversed(data[idx+1-period:idx+1])).index(np.min... | [
"def",
"aroon_down",
"(",
"data",
",",
"period",
")",
":",
"catch_errors",
".",
"check_for_period_error",
"(",
"data",
",",
"period",
")",
"period",
"=",
"int",
"(",
"period",
")",
"a_down",
"=",
"[",
"(",
"(",
"period",
"-",
"list",
"(",
"reversed",
"... | 32.066667 | 0.008081 |
def _dask_array_with_chunks_hint(array, chunks):
"""Create a dask array using the chunks hint for dimensions of size > 1."""
import dask.array as da
if len(chunks) < array.ndim:
raise ValueError('not enough chunks in hint')
new_chunks = []
for chunk, size in zip(chunks, array.shape):
... | [
"def",
"_dask_array_with_chunks_hint",
"(",
"array",
",",
"chunks",
")",
":",
"import",
"dask",
".",
"array",
"as",
"da",
"if",
"len",
"(",
"chunks",
")",
"<",
"array",
".",
"ndim",
":",
"raise",
"ValueError",
"(",
"'not enough chunks in hint'",
")",
"new_ch... | 44.777778 | 0.002433 |
def cron(cronline, venusian_category='irc3.plugins.cron'):
"""main decorator"""
def wrapper(func):
def callback(context, name, ob):
obj = context.context
crons = obj.get_plugin(Crons)
if info.scope == 'class':
callback = getattr(
ob... | [
"def",
"cron",
"(",
"cronline",
",",
"venusian_category",
"=",
"'irc3.plugins.cron'",
")",
":",
"def",
"wrapper",
"(",
"func",
")",
":",
"def",
"callback",
"(",
"context",
",",
"name",
",",
"ob",
")",
":",
"obj",
"=",
"context",
".",
"context",
"crons",
... | 37.75 | 0.001616 |
def _handle_msg(self, msg):
"""When a BGP message is received, send it to peer.
Open messages are validated here. Peer handler is called to handle each
message except for *Open* and *Notification* message. On receiving
*Notification* message we close connection with peer.
"""
... | [
"def",
"_handle_msg",
"(",
"self",
",",
"msg",
")",
":",
"LOG",
".",
"debug",
"(",
"'Received msg from %s << %s'",
",",
"self",
".",
"_remotename",
",",
"msg",
")",
"# If we receive open message we try to bind to protocol",
"if",
"msg",
".",
"type",
"==",
"BGP_MSG... | 44.450704 | 0.00062 |
def shift_and_pad(tensor, shift, axis=0):
"""Shifts and pads with zero along an axis.
Example:
shift_and_pad([1, 2, 3, 4], 2) --> [0, 0, 1, 2]
shift_and_pad([1, 2, 3, 4], -2) --> [3, 4, 0, 0]
Args:
tensor: Tensor; to be shifted and padded.
shift: int; number of positions to shift by.
axis: ... | [
"def",
"shift_and_pad",
"(",
"tensor",
",",
"shift",
",",
"axis",
"=",
"0",
")",
":",
"shape",
"=",
"tensor",
".",
"shape",
"rank",
"=",
"len",
"(",
"shape",
")",
"assert",
"0",
"<=",
"abs",
"(",
"axis",
")",
"<",
"rank",
"length",
"=",
"int",
"(... | 23.138889 | 0.016129 |
def do_show(self, args):
"""Valid parameters for the "show" command are: modules, options"""
self.print_line('')
if args.thing == 'modules':
self.print_line('Modules' + os.linesep + '=======')
headers = ('Name', 'Description')
rows = [(module.path, module.description) for module in self.frmwk.modules.val... | [
"def",
"do_show",
"(",
"self",
",",
"args",
")",
":",
"self",
".",
"print_line",
"(",
"''",
")",
"if",
"args",
".",
"thing",
"==",
"'modules'",
":",
"self",
".",
"print_line",
"(",
"'Modules'",
"+",
"os",
".",
"linesep",
"+",
"'======='",
")",
"heade... | 51.428571 | 0.022495 |
def pairwise_distances(x, y=None, **kwargs):
r"""
pairwise_distances(x, y=None, *, exponent=1)
Pairwise distance between points.
Return the pairwise distance between points in two sets, or
in the same set if only one set is passed.
Parameters
----------
x: array_like
An :math:... | [
"def",
"pairwise_distances",
"(",
"x",
",",
"y",
"=",
"None",
",",
"*",
"*",
"kwargs",
")",
":",
"x",
"=",
"_transform_to_2d",
"(",
"x",
")",
"if",
"y",
"is",
"None",
"or",
"y",
"is",
"x",
":",
"return",
"_pdist",
"(",
"x",
",",
"*",
"*",
"kwar... | 31.689655 | 0.000528 |
def underlying_variable_ref(t):
"""Find the underlying variable ref.
Traverses through Identity, ReadVariableOp, and Enter ops.
Stops when op type has Variable or VarHandle in name.
Args:
t: a Tensor
Returns:
a Tensor that is a variable ref, or None on error.
"""
while t.op.type in ["Identity",... | [
"def",
"underlying_variable_ref",
"(",
"t",
")",
":",
"while",
"t",
".",
"op",
".",
"type",
"in",
"[",
"\"Identity\"",
",",
"\"ReadVariableOp\"",
",",
"\"Enter\"",
"]",
":",
"t",
"=",
"t",
".",
"op",
".",
"inputs",
"[",
"0",
"]",
"op_type",
"=",
"t",... | 23.3 | 0.012371 |
def get_workflow_info(brain_or_object, endpoint=None):
"""Generate workflow information of the assigned workflows
:param brain_or_object: A single catalog brain or content object
:type brain_or_object: ATContentType/DexterityContentType/CatalogBrain
:param endpoint: The named URL endpoint for the root ... | [
"def",
"get_workflow_info",
"(",
"brain_or_object",
",",
"endpoint",
"=",
"None",
")",
":",
"# ensure we have a full content object",
"obj",
"=",
"get_object",
"(",
"brain_or_object",
")",
"# get the portal workflow tool",
"wf_tool",
"=",
"get_tool",
"(",
"\"portal_workfl... | 30.662921 | 0.00071 |
def get_path_matching(name):
"""Get path matching a name.
Parameters
----------
name : string
Name to search for.
Returns
-------
string
Full filepath.
"""
# first try looking in the user folder
p = os.path.join(os.path.expanduser("~"), name)
# then try expa... | [
"def",
"get_path_matching",
"(",
"name",
")",
":",
"# first try looking in the user folder",
"p",
"=",
"os",
".",
"path",
".",
"join",
"(",
"os",
".",
"path",
".",
"expanduser",
"(",
"\"~\"",
")",
",",
"name",
")",
"# then try expanding upwards from cwd",
"if",
... | 27 | 0.001431 |
def parse_str_to_expression(fiql_str):
"""Parse a FIQL formatted string into an ``Expression``.
Args:
fiql_str (string): The FIQL formatted string we want to parse.
Returns:
Expression: An ``Expression`` object representing the parsed FIQL
string.
Raises:
FiqlFormatExc... | [
"def",
"parse_str_to_expression",
"(",
"fiql_str",
")",
":",
"#pylint: disable=too-many-branches",
"nesting_lvl",
"=",
"0",
"last_element",
"=",
"None",
"expression",
"=",
"Expression",
"(",
")",
"for",
"(",
"preamble",
",",
"selector",
",",
"comparison",
",",
"ar... | 39.983871 | 0.000787 |
def _get_compressed_vlan_list(self, pvlan_ids):
"""Generate a compressed vlan list ready for XML using a vlan set.
Sample Use Case:
Input vlan set:
--------------
1 - s = set([11, 50, 25, 30, 15, 16, 3, 8, 2, 1])
2 - s = set([87, 11, 50, 25, 30, 15, 16, 3, 8, 2, 1, 88])... | [
"def",
"_get_compressed_vlan_list",
"(",
"self",
",",
"pvlan_ids",
")",
":",
"if",
"not",
"pvlan_ids",
":",
"return",
"[",
"]",
"pvlan_list",
"=",
"list",
"(",
"pvlan_ids",
")",
"pvlan_list",
".",
"sort",
"(",
")",
"compressed_list",
"=",
"[",
"]",
"begin"... | 33.043478 | 0.001278 |
def create_response_signature(self, string_message, zone):
""" Basic helper function to keep code clean for defining a response message signature """
zz = ''
if zone is not None:
zz = hex(int(zone)-1).replace('0x', '') # RNET requires zone value to be zero based
string_mess... | [
"def",
"create_response_signature",
"(",
"self",
",",
"string_message",
",",
"zone",
")",
":",
"zz",
"=",
"''",
"if",
"zone",
"is",
"not",
"None",
":",
"zz",
"=",
"hex",
"(",
"int",
"(",
"zone",
")",
"-",
"1",
")",
".",
"replace",
"(",
"'0x'",
",",... | 51 | 0.012048 |
def get_datasource_info(datasource_id, datasource_type, form_data):
"""Compatibility layer for handling of datasource info
datasource_id & datasource_type used to be passed in the URL
directory, now they should come as part of the form_data,
This function allows supporting both without duplicating code... | [
"def",
"get_datasource_info",
"(",
"datasource_id",
",",
"datasource_type",
",",
"form_data",
")",
":",
"datasource",
"=",
"form_data",
".",
"get",
"(",
"'datasource'",
",",
"''",
")",
"if",
"'__'",
"in",
"datasource",
":",
"datasource_id",
",",
"datasource_type... | 46.235294 | 0.001247 |
def find_physics(self, geometry=None, phase=None):
r"""
Find the Physics object(s) associated with a given Geometry, Phase,
or combination.
Parameters
----------
geometry : OpenPNM Geometry Object
The Geometry object for which the Physics object(s) are sought... | [
"def",
"find_physics",
"(",
"self",
",",
"geometry",
"=",
"None",
",",
"phase",
"=",
"None",
")",
":",
"if",
"geometry",
"and",
"phase",
":",
"physics",
"=",
"self",
".",
"find_physics",
"(",
"geometry",
"=",
"geometry",
")",
"phases",
"=",
"list",
"("... | 38.666667 | 0.000764 |
def ConvBPDNMaskOptionsDefaults(method='admm'):
"""Get defaults dict for the ConvBPDNMask class specified by the
``method`` parameter.
"""
dflt = copy.deepcopy(cbpdnmsk_class_label_lookup(method).Options.defaults)
if method == 'admm':
dflt.update({'MaxMainIter': 1, 'AutoRho':
... | [
"def",
"ConvBPDNMaskOptionsDefaults",
"(",
"method",
"=",
"'admm'",
")",
":",
"dflt",
"=",
"copy",
".",
"deepcopy",
"(",
"cbpdnmsk_class_label_lookup",
"(",
"method",
")",
".",
"Options",
".",
"defaults",
")",
"if",
"method",
"==",
"'admm'",
":",
"dflt",
"."... | 38.8 | 0.001678 |
def conditional_accept(self):
"""Accepts the inputs if all values are valid and congruent.
i.e. Valid datafile and frequency range within the given calibration dataset."""
if self.ui.calfileRadio.isChecked() and str(self.ui.calChoiceCmbbx.currentText()) == '':
self.ui.noneRadio.setCh... | [
"def",
"conditional_accept",
"(",
"self",
")",
":",
"if",
"self",
".",
"ui",
".",
"calfileRadio",
".",
"isChecked",
"(",
")",
"and",
"str",
"(",
"self",
".",
"ui",
".",
"calChoiceCmbbx",
".",
"currentText",
"(",
")",
")",
"==",
"''",
":",
"self",
"."... | 54.952381 | 0.010221 |
def search_maintenance_window_for_facet(self, facet, **kwargs): # noqa: E501
"""Lists the values of a specific facet over the customer's maintenance windows # noqa: E501
# noqa: E501
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, pleas... | [
"def",
"search_maintenance_window_for_facet",
"(",
"self",
",",
"facet",
",",
"*",
"*",
"kwargs",
")",
":",
"# noqa: E501",
"kwargs",
"[",
"'_return_http_data_only'",
"]",
"=",
"True",
"if",
"kwargs",
".",
"get",
"(",
"'async_req'",
")",
":",
"return",
"self",... | 47.863636 | 0.001862 |
def _extractBasicPredicateFromClause( clauseTokens, clauseID ):
'''
Meetod, mis tuvastab antud osalausest kesksed verbid + nendega otseselt seotud
esmased verbifraasid:
1) predikaadiga seotud eituse(d): (ei/ära/pole) + sobiv verb;
2) olema-verbifraasid: olema; olema + so... | [
"def",
"_extractBasicPredicateFromClause",
"(",
"clauseTokens",
",",
"clauseID",
")",
":",
"global",
"_phraseBreakerAdvs",
"# Verbieituse indikaatorid\r",
"verbEi",
"=",
"WordTemplate",
"(",
"{",
"ROOT",
":",
"'^ei$'",
",",
"FORM",
":",
"'neg'",
",",
"POSTAG",
":",
... | 64.400901 | 0.014556 |
def related_tags(self,release_id=None,tag_names=None,response_type=None,params=None):
"""
Function to request FRED related tags for a particular release.
FRED tags are attributes assigned to series.
Series are assigned tags and releases. Indirectly through series,
it is possible ... | [
"def",
"related_tags",
"(",
"self",
",",
"release_id",
"=",
"None",
",",
"tag_names",
"=",
"None",
",",
"response_type",
"=",
"None",
",",
"params",
"=",
"None",
")",
":",
"path",
"=",
"'/release/related_tags?'",
"params",
"[",
"'release_id'",
"]",
",",
"p... | 69.612903 | 0.011426 |
def set_data(self, data=None, **kwargs):
"""Set the line data
Parameters
----------
data : array-like
The data.
**kwargs : dict
Keywoard arguments to pass to MarkerVisual and LineVisal.
"""
if data is None:
pos = None
e... | [
"def",
"set_data",
"(",
"self",
",",
"data",
"=",
"None",
",",
"*",
"*",
"kwargs",
")",
":",
"if",
"data",
"is",
"None",
":",
"pos",
"=",
"None",
"else",
":",
"if",
"isinstance",
"(",
"data",
",",
"tuple",
")",
":",
"pos",
"=",
"np",
".",
"arra... | 38.105263 | 0.000898 |
def readAltWCS(fobj, ext, wcskey=' ', verbose=False):
"""
Reads in alternate primary WCS from specified extension.
Parameters
----------
fobj : str, `astropy.io.fits.HDUList`
fits filename or fits file object
containing alternate/primary WCS(s) to be converted
wcskey : str
... | [
"def",
"readAltWCS",
"(",
"fobj",
",",
"ext",
",",
"wcskey",
"=",
"' '",
",",
"verbose",
"=",
"False",
")",
":",
"if",
"isinstance",
"(",
"fobj",
",",
"str",
")",
":",
"fobj",
"=",
"fits",
".",
"open",
"(",
"fobj",
",",
"memmap",
"=",
"False",
")... | 29.095238 | 0.001584 |
def sg_regularizer_loss(scale=1.0):
r""" Get regularizer losss
Args:
scale: A scalar. A weight applied to regularizer loss
"""
return scale * tf.reduce_mean(tf.get_collection(tf.GraphKeys.REGULARIZATION_LOSSES)) | [
"def",
"sg_regularizer_loss",
"(",
"scale",
"=",
"1.0",
")",
":",
"return",
"scale",
"*",
"tf",
".",
"reduce_mean",
"(",
"tf",
".",
"get_collection",
"(",
"tf",
".",
"GraphKeys",
".",
"REGULARIZATION_LOSSES",
")",
")"
] | 32.571429 | 0.008547 |
def lag_calc(self, stream, pre_processed, shift_len=0.2, min_cc=0.4,
horizontal_chans=['E', 'N', '1', '2'], vertical_chans=['Z'],
cores=1, interpolate=False, plot=False, parallel=True,
overlap='calculate', process_cores=None, debug=0):
"""
Compute picks... | [
"def",
"lag_calc",
"(",
"self",
",",
"stream",
",",
"pre_processed",
",",
"shift_len",
"=",
"0.2",
",",
"min_cc",
"=",
"0.4",
",",
"horizontal_chans",
"=",
"[",
"'E'",
",",
"'N'",
",",
"'1'",
",",
"'2'",
"]",
",",
"vertical_chans",
"=",
"[",
"'Z'",
"... | 46.949686 | 0.000656 |
def prepareDatasetMigrationList(self, conn, request):
"""
Prepare the ordered lists of blocks based on input DATASET (note Block is different)
1. Get list of blocks from source
2. Check and see if these blocks are already at DST
3. Check if dataset has parents
... | [
"def",
"prepareDatasetMigrationList",
"(",
"self",
",",
"conn",
",",
"request",
")",
":",
"ordered_dict",
"=",
"{",
"}",
"order_counter",
"=",
"0",
"srcdataset",
"=",
"request",
"[",
"\"migration_input\"",
"]",
"url",
"=",
"request",
"[",
"\"migration_url\"",
... | 50.045455 | 0.012472 |
def update_project(project,**kwargs):
"""
Update a project
returns a project complexmodel
"""
user_id = kwargs.get('user_id')
#check_perm(user_id, 'update_project')
proj_i = _get_project(project.id)
proj_i.check_write_permission(user_id)
proj_i.name = project.name
... | [
"def",
"update_project",
"(",
"project",
",",
"*",
"*",
"kwargs",
")",
":",
"user_id",
"=",
"kwargs",
".",
"get",
"(",
"'user_id'",
")",
"#check_perm(user_id, 'update_project')",
"proj_i",
"=",
"_get_project",
"(",
"project",
".",
"id",
")",
"proj_i",
".",
"... | 27.761905 | 0.008292 |
def polylinear_gradient(colors, n):
"""
Interpolates the color gradients between a list of hex colors.
"""
n_out = int(float(n) / (len(colors)-1))
gradient = linear_gradient(colors[0], colors[1], n_out)
if len(colors) == len(gradient):
return gradient
for col in range(1, len(colors... | [
"def",
"polylinear_gradient",
"(",
"colors",
",",
"n",
")",
":",
"n_out",
"=",
"int",
"(",
"float",
"(",
"n",
")",
"/",
"(",
"len",
"(",
"colors",
")",
"-",
"1",
")",
")",
"gradient",
"=",
"linear_gradient",
"(",
"colors",
"[",
"0",
"]",
",",
"co... | 34.714286 | 0.002004 |
def endpoint_class(collection):
"""Return the :class:`sandman.model.Model` associated with the endpoint
*collection*.
:param string collection: a :class:`sandman.model.Model` endpoint
:rtype: :class:`sandman.model.Model`
"""
with app.app_context():
try:
cls = current_app.cl... | [
"def",
"endpoint_class",
"(",
"collection",
")",
":",
"with",
"app",
".",
"app_context",
"(",
")",
":",
"try",
":",
"cls",
"=",
"current_app",
".",
"class_references",
"[",
"collection",
"]",
"except",
"KeyError",
":",
"raise",
"InvalidAPIUsage",
"(",
"404",... | 29.714286 | 0.002331 |
def xpathNextAttribute(self, ctxt):
"""Traversal function for the "attribute" direction TODO:
support DTD inherited default attributes """
if ctxt is None: ctxt__o = None
else: ctxt__o = ctxt._o
ret = libxml2mod.xmlXPathNextAttribute(ctxt__o, self._o)
if ret is None:ra... | [
"def",
"xpathNextAttribute",
"(",
"self",
",",
"ctxt",
")",
":",
"if",
"ctxt",
"is",
"None",
":",
"ctxt__o",
"=",
"None",
"else",
":",
"ctxt__o",
"=",
"ctxt",
".",
"_o",
"ret",
"=",
"libxml2mod",
".",
"xmlXPathNextAttribute",
"(",
"ctxt__o",
",",
"self",... | 46.111111 | 0.014184 |
def offset_to_sky(skydir, offset_lon, offset_lat,
coordsys='CEL', projection='AIT'):
"""Convert a cartesian offset (X,Y) in the given projection into
a pair of spherical coordinates."""
offset_lon = np.array(offset_lon, ndmin=1)
offset_lat = np.array(offset_lat, ndmin=1)
w = crea... | [
"def",
"offset_to_sky",
"(",
"skydir",
",",
"offset_lon",
",",
"offset_lat",
",",
"coordsys",
"=",
"'CEL'",
",",
"projection",
"=",
"'AIT'",
")",
":",
"offset_lon",
"=",
"np",
".",
"array",
"(",
"offset_lon",
",",
"ndmin",
"=",
"1",
")",
"offset_lat",
"=... | 36.25 | 0.002242 |
def assign_default_storage_policy_to_datastore(profile_manager, policy,
datastore):
'''
Assigns a storage policy as the default policy to a datastore.
profile_manager
Reference to the profile manager.
policy
Reference to the policy to assi... | [
"def",
"assign_default_storage_policy_to_datastore",
"(",
"profile_manager",
",",
"policy",
",",
"datastore",
")",
":",
"placement_hub",
"=",
"pbm",
".",
"placement",
".",
"PlacementHub",
"(",
"hubId",
"=",
"datastore",
".",
"_moId",
",",
"hubType",
"=",
"'Datasto... | 35.9 | 0.000904 |
def load_unsafe(self, f, *args, **kwargs):
"""Like :meth:`loads_unsafe` but loads from a file.
.. versionadded:: 0.15
"""
return self.loads_unsafe(f.read(), *args, **kwargs) | [
"def",
"load_unsafe",
"(",
"self",
",",
"f",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"return",
"self",
".",
"loads_unsafe",
"(",
"f",
".",
"read",
"(",
")",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")"
] | 33.5 | 0.009709 |
def sequential(self, func, args_dict=None):
"""
Execute a function for all Crazyflies in the swarm, in sequence.
The first argument of the function that is passed in will be a
SyncCrazyflie instance connected to the Crazyflie to operate on.
A list of optional parameters (per Cra... | [
"def",
"sequential",
"(",
"self",
",",
"func",
",",
"args_dict",
"=",
"None",
")",
":",
"for",
"uri",
",",
"cf",
"in",
"self",
".",
"_cfs",
".",
"items",
"(",
")",
":",
"args",
"=",
"self",
".",
"_process_args_dict",
"(",
"cf",
",",
"uri",
",",
"... | 33.75 | 0.002058 |
def inject2(module_name=None, module_prefix=None, DEBUG=False, module=None, N=1):
""" wrapper that depricates print_ and printDBG """
if module_prefix is None:
module_prefix = '[%s]' % (module_name,)
noinject(module_name, module_prefix, DEBUG, module, N=N)
module = _get_module(module_name, modul... | [
"def",
"inject2",
"(",
"module_name",
"=",
"None",
",",
"module_prefix",
"=",
"None",
",",
"DEBUG",
"=",
"False",
",",
"module",
"=",
"None",
",",
"N",
"=",
"1",
")",
":",
"if",
"module_prefix",
"is",
"None",
":",
"module_prefix",
"=",
"'[%s]'",
"%",
... | 52.8 | 0.009311 |
def plotBrokerQueue(dataTask, filename):
"""Generates the broker queue length graphic."""
print("Plotting broker queue length for {0}.".format(filename))
plt.figure()
# Queue length
plt.subplot(211)
for fichier, vals in dataTask.items():
if type(vals) == list:
timestamps = l... | [
"def",
"plotBrokerQueue",
"(",
"dataTask",
",",
"filename",
")",
":",
"print",
"(",
"\"Plotting broker queue length for {0}.\"",
".",
"format",
"(",
"filename",
")",
")",
"plt",
".",
"figure",
"(",
")",
"# Queue length",
"plt",
".",
"subplot",
"(",
"211",
")",... | 35.657143 | 0.00234 |
def _fetch_profile_opts(
cfg, virtualname,
__salt__,
_options,
profile_attr,
profile_attrs
):
"""
Fetches profile specific options if applicable
@see :func:`get_returner_options`
:return: a options dict
"""
if (not profile_attr) or (profile_attr not... | [
"def",
"_fetch_profile_opts",
"(",
"cfg",
",",
"virtualname",
",",
"__salt__",
",",
"_options",
",",
"profile_attr",
",",
"profile_attrs",
")",
":",
"if",
"(",
"not",
"profile_attr",
")",
"or",
"(",
"profile_attr",
"not",
"in",
"_options",
")",
":",
"return"... | 20.3 | 0.00235 |
def load_asdf(asdf_obj, data_key='sci', wcs_key='wcs', header_key='meta'):
"""
Load from an ASDF object.
Parameters
----------
asdf_obj : obj
ASDF or ASDF-in-FITS object.
data_key, wcs_key, header_key : str
Key values to specify where to find data, WCS, and header
in AS... | [
"def",
"load_asdf",
"(",
"asdf_obj",
",",
"data_key",
"=",
"'sci'",
",",
"wcs_key",
"=",
"'wcs'",
",",
"header_key",
"=",
"'meta'",
")",
":",
"asdf_keys",
"=",
"asdf_obj",
".",
"keys",
"(",
")",
"if",
"wcs_key",
"in",
"asdf_keys",
":",
"wcs",
"=",
"asd... | 20.590909 | 0.001054 |
def __set_missense_status(self, hgvs_string):
"""Sets the self.is_missense flag."""
# set missense status
if re.search('^[A-Z?]\d+[A-Z?]$', hgvs_string):
self.is_missense = True
self.is_non_silent = True
else:
self.is_missense = False | [
"def",
"__set_missense_status",
"(",
"self",
",",
"hgvs_string",
")",
":",
"# set missense status",
"if",
"re",
".",
"search",
"(",
"'^[A-Z?]\\d+[A-Z?]$'",
",",
"hgvs_string",
")",
":",
"self",
".",
"is_missense",
"=",
"True",
"self",
".",
"is_non_silent",
"=",
... | 36.875 | 0.009934 |
def _Rforce(self,R,z,phi=0.,t=0.):
"""
NAME:
Rforce
PURPOSE:
evaluate radial force K_R (R,z)
INPUT:
R - Cylindrical Galactocentric radius
z - vertical height
phi - azimuth
t - time
OUTPUT:
K_R (R,z)
... | [
"def",
"_Rforce",
"(",
"self",
",",
"R",
",",
"z",
",",
"phi",
"=",
"0.",
",",
"t",
"=",
"0.",
")",
":",
"if",
"True",
":",
"if",
"isinstance",
"(",
"R",
",",
"nu",
".",
"ndarray",
")",
":",
"if",
"not",
"isinstance",
"(",
"z",
",",
"nu",
"... | 43.8125 | 0.024424 |
def shared_np_array(shape, data=None, integer=False):
"""Create a new numpy array that resides in shared memory.
Parameters
----------
shape : tuple of ints
The shape of the new array.
data : numpy.array
Data to copy to the new array. Has to have the same shape.
integer : boolea... | [
"def",
"shared_np_array",
"(",
"shape",
",",
"data",
"=",
"None",
",",
"integer",
"=",
"False",
")",
":",
"size",
"=",
"np",
".",
"prod",
"(",
"shape",
")",
"if",
"integer",
":",
"array",
"=",
"Array",
"(",
"ctypes",
".",
"c_int64",
",",
"int",
"("... | 29.789474 | 0.000855 |
def Remove(self,directory,filename):
"""Deletes files from fb"""
if self._isMediaFile(filename):
return self._remove_media(directory,filename)
elif self._isConfigFile(filename):
return True
print "Not handled!"
return False | [
"def",
"Remove",
"(",
"self",
",",
"directory",
",",
"filename",
")",
":",
"if",
"self",
".",
"_isMediaFile",
"(",
"filename",
")",
":",
"return",
"self",
".",
"_remove_media",
"(",
"directory",
",",
"filename",
")",
"elif",
"self",
".",
"_isConfigFile",
... | 31.111111 | 0.017361 |
def move_active_window(x, y):
"""
Moves the active window to a given position given the window_id and absolute co ordinates,
--sync option auto passed in, will wait until actually moved before giving control back to us
will do nothing if the window is maximized
"""
window_id = get_window_id()
... | [
"def",
"move_active_window",
"(",
"x",
",",
"y",
")",
":",
"window_id",
"=",
"get_window_id",
"(",
")",
"cmd",
"=",
"[",
"'xdotool'",
",",
"'windowmove'",
",",
"window_id",
",",
"str",
"(",
"x",
")",
",",
"str",
"(",
"y",
")",
"]",
"subprocess",
".",... | 46.1 | 0.019149 |
def call_graphviz_dot(src, fmt):
"""Call dot command, and provide helpful error message if we
cannot find it.
"""
try:
svg = dot(src, T=fmt)
except OSError as e: # pragma: nocover
if e.errno == 2:
cli.error("""
cannot find 'dot'
pydeps c... | [
"def",
"call_graphviz_dot",
"(",
"src",
",",
"fmt",
")",
":",
"try",
":",
"svg",
"=",
"dot",
"(",
"src",
",",
"T",
"=",
"fmt",
")",
"except",
"OSError",
"as",
"e",
":",
"# pragma: nocover",
"if",
"e",
".",
"errno",
"==",
"2",
":",
"cli",
".",
"er... | 29.176471 | 0.001953 |
def get_number_footer_lines(docbody, page_break_posns):
"""Try to guess the number of footer lines each page of a document has.
The positions of the page breaks in the document are used to try to guess
the number of footer lines.
@param docbody: (list) of strings - each string being a line in t... | [
"def",
"get_number_footer_lines",
"(",
"docbody",
",",
"page_break_posns",
")",
":",
"num_breaks",
"=",
"len",
"(",
"page_break_posns",
")",
"num_footer_lines",
"=",
"0",
"empty_line",
"=",
"0",
"keep_checking",
"=",
"1",
"p_wordSearch",
"=",
"re",
".",
"compile... | 48.345455 | 0.001106 |
def select_action(self, state):
"""
Select the best action for the given state using e-greedy exploration to
minimize overfitting
:return: tuple(action, value)
"""
value = 0
if self.steps < self.min_steps:
action = np.random.randint(self.actions)
else:
self.eps = max(self.ep... | [
"def",
"select_action",
"(",
"self",
",",
"state",
")",
":",
"value",
"=",
"0",
"if",
"self",
".",
"steps",
"<",
"self",
".",
"min_steps",
":",
"action",
"=",
"np",
".",
"random",
".",
"randint",
"(",
"self",
".",
"actions",
")",
"else",
":",
"self... | 31.272727 | 0.012694 |
def save(self, location=None, custom_name=None):
""" Save the attachment locally to disk
:param str location: path string to where the file is to be saved.
:param str custom_name: a custom name to be saved as
:return: Success / Failure
:rtype: bool
"""
if not se... | [
"def",
"save",
"(",
"self",
",",
"location",
"=",
"None",
",",
"custom_name",
"=",
"None",
")",
":",
"if",
"not",
"self",
".",
"content",
":",
"return",
"False",
"location",
"=",
"Path",
"(",
"location",
"or",
"''",
")",
"if",
"not",
"location",
".",... | 33.965517 | 0.001974 |
def get_unused_ips(session, used_ips_counts, **kwargs):
"""Returns dictionary with key segment_id, and value unused IPs count.
Unused IP address count is determined by:
- adding subnet's cidr's size
- subtracting IP policy exclusions on subnet
- subtracting used ips per segment
"""
LOG.debu... | [
"def",
"get_unused_ips",
"(",
"session",
",",
"used_ips_counts",
",",
"*",
"*",
"kwargs",
")",
":",
"LOG",
".",
"debug",
"(",
"\"Getting unused IPs...\"",
")",
"with",
"session",
".",
"begin",
"(",
")",
":",
"query",
"=",
"session",
".",
"query",
"(",
"m... | 36.153846 | 0.001036 |
def subtract(self, route):
"""
Remove the route entirely.
"""
for address in self.raw_maps.pop(route, NullHardwareMap()).iterkeys():
self.pop(address, NullHardwareNode()) | [
"def",
"subtract",
"(",
"self",
",",
"route",
")",
":",
"for",
"address",
"in",
"self",
".",
"raw_maps",
".",
"pop",
"(",
"route",
",",
"NullHardwareMap",
"(",
")",
")",
".",
"iterkeys",
"(",
")",
":",
"self",
".",
"pop",
"(",
"address",
",",
"Null... | 35.5 | 0.009174 |
def _get_segmentation_id(self, netid, segid, source):
"""Allocate segmentation id. """
return self.seg_drvr.allocate_segmentation_id(netid, seg_id=segid,
source=source) | [
"def",
"_get_segmentation_id",
"(",
"self",
",",
"netid",
",",
"segid",
",",
"source",
")",
":",
"return",
"self",
".",
"seg_drvr",
".",
"allocate_segmentation_id",
"(",
"netid",
",",
"seg_id",
"=",
"segid",
",",
"source",
"=",
"source",
")"
] | 47 | 0.008368 |
def last(self, predicate=None):
'''The last element in a sequence (optionally satisfying a predicate).
If the predicate is omitted or is None this query returns the last
element in the sequence; otherwise, it returns the last element in
the sequence for which the predicate evaluates to ... | [
"def",
"last",
"(",
"self",
",",
"predicate",
"=",
"None",
")",
":",
"if",
"self",
".",
"closed",
"(",
")",
":",
"raise",
"ValueError",
"(",
"\"Attempt to call last() on a closed Queryable.\"",
")",
"return",
"self",
".",
"_last",
"(",
")",
"if",
"predicate"... | 44.451613 | 0.002131 |
def show_all(self):
"""Show details for all workspaces."""
for ws in self.workspace.list().keys():
self.show_workspace(ws)
print("\n\n") | [
"def",
"show_all",
"(",
"self",
")",
":",
"for",
"ws",
"in",
"self",
".",
"workspace",
".",
"list",
"(",
")",
".",
"keys",
"(",
")",
":",
"self",
".",
"show_workspace",
"(",
"ws",
")",
"print",
"(",
"\"\\n\\n\"",
")"
] | 34.4 | 0.011364 |
def cut(self, partial=True):
"""
Trigger cutter to perform partial (default) or full paper cut.
"""
if self.hardware_features.get(feature.CUTTER, False):
# TODO: implement hardware alternative for unavailable features
# For example:
#
# ... | [
"def",
"cut",
"(",
"self",
",",
"partial",
"=",
"True",
")",
":",
"if",
"self",
".",
"hardware_features",
".",
"get",
"(",
"feature",
".",
"CUTTER",
",",
"False",
")",
":",
"# TODO: implement hardware alternative for unavailable features",
"# For example:",
"#",
... | 45.130435 | 0.001887 |
def EverestModel(ID, model='nPLD', publish=False, csv=False, **kwargs):
'''
A wrapper around an :py:obj:`everest` model for PBS runs.
'''
if model != 'Inject':
from ... import detrender
# HACK: We need to explicitly mask short cadence planets
if kwargs.get('cadence', 'lc') == ... | [
"def",
"EverestModel",
"(",
"ID",
",",
"model",
"=",
"'nPLD'",
",",
"publish",
"=",
"False",
",",
"csv",
"=",
"False",
",",
"*",
"*",
"kwargs",
")",
":",
"if",
"model",
"!=",
"'Inject'",
":",
"from",
".",
".",
".",
"import",
"detrender",
"# HACK: We ... | 31.114286 | 0.00089 |
def deploy_static():
"""
Deploy static (application) versioned media
"""
if not env.STATIC_URL or 'http://' in env.STATIC_URL: return
from django.core.servers.basehttp import AdminMediaHandler
remote_dir = '/'.join([deployment_root(),'env',env.project_fullname,'static'])
m_prefix = len(... | [
"def",
"deploy_static",
"(",
")",
":",
"if",
"not",
"env",
".",
"STATIC_URL",
"or",
"'http://'",
"in",
"env",
".",
"STATIC_URL",
":",
"return",
"from",
"django",
".",
"core",
".",
"servers",
".",
"basehttp",
"import",
"AdminMediaHandler",
"remote_dir",
"=",
... | 47.677419 | 0.014589 |
def colourblind(i):
'''
colour pallete from http://tableaufriction.blogspot.ro/
allegedly suitable for colour-blind folk
SJ
'''
rawRGBs = [(162,200,236),
(255,128,14),
(171,171,171),
(95,158,209),
(89,89,89),
... | [
"def",
"colourblind",
"(",
"i",
")",
":",
"rawRGBs",
"=",
"[",
"(",
"162",
",",
"200",
",",
"236",
")",
",",
"(",
"255",
",",
"128",
",",
"14",
")",
",",
"(",
"171",
",",
"171",
",",
"171",
")",
",",
"(",
"95",
",",
"158",
",",
"209",
")"... | 24.8 | 0.043478 |
def keep_label(self, label, relabel=False):
"""
Keep only the specified label.
Parameters
----------
label : int
The label number to keep.
relabel : bool, optional
If `True`, then the single segment will be assigned a label
value of 1... | [
"def",
"keep_label",
"(",
"self",
",",
"label",
",",
"relabel",
"=",
"False",
")",
":",
"self",
".",
"keep_labels",
"(",
"label",
",",
"relabel",
"=",
"relabel",
")"
] | 34.916667 | 0.001161 |
def redirect(self, redirect, auth):
"""Redirect the client endpoint using a Link DETACH redirect
response.
:param redirect: The Link DETACH redirect details.
:type redirect: ~uamqp.errors.LinkRedirect
:param auth: Authentication credentials to the redirected endpoint.
:t... | [
"def",
"redirect",
"(",
"self",
",",
"redirect",
",",
"auth",
")",
":",
"if",
"self",
".",
"_ext_connection",
":",
"raise",
"ValueError",
"(",
"\"Clients with a shared connection cannot be \"",
"\"automatically redirected.\"",
")",
"if",
"self",
".",
"message_handler"... | 39.347826 | 0.002157 |
def fillna(df, column: str, value=None, column_value=None):
"""
Can fill NaN values from a column with a given value or a column
---
### Parameters
- `column` (*str*): name of column you want to fill
- `value`: NaN will be replaced by this value
- `column_value`: NaN will be replaced by ... | [
"def",
"fillna",
"(",
"df",
",",
"column",
":",
"str",
",",
"value",
"=",
"None",
",",
"column_value",
"=",
"None",
")",
":",
"if",
"column",
"not",
"in",
"df",
".",
"columns",
":",
"df",
"[",
"column",
"]",
"=",
"nan",
"if",
"value",
"is",
"not"... | 27.345455 | 0.001926 |
def map(self, mapper, na_action=None):
"""
Map values using input correspondence (a dict, Series, or function).
Parameters
----------
mapper : function, dict, or Series
Mapping correspondence.
na_action : {None, 'ignore'}
If 'ignore', propagate NA... | [
"def",
"map",
"(",
"self",
",",
"mapper",
",",
"na_action",
"=",
"None",
")",
":",
"from",
".",
"multi",
"import",
"MultiIndex",
"new_values",
"=",
"super",
"(",
")",
".",
"_map_values",
"(",
"mapper",
",",
"na_action",
"=",
"na_action",
")",
"attributes... | 33.857143 | 0.001367 |
def get_response_dict(self, helper, context, is_formset):
"""
Returns a dictionary with all the parameters necessary to render the form/formset in a template.
:param context: `django.template.Context` for the node
:param is_formset: Boolean value. If set to True, indicates we are workin... | [
"def",
"get_response_dict",
"(",
"self",
",",
"helper",
",",
"context",
",",
"is_formset",
")",
":",
"if",
"not",
"isinstance",
"(",
"helper",
",",
"FormHelper",
")",
":",
"raise",
"TypeError",
"(",
"'helper object provided to {% crispy %} tag must be a crispy.helper.... | 49.56 | 0.002374 |
def _folder_item_calculation(self, analysis_brain, item):
"""Set the analysis' calculation and interims to the item passed in.
:param analysis_brain: Brain that represents an analysis
:param item: analysis' dictionary counterpart that represents a row
"""
is_editable = self.is_... | [
"def",
"_folder_item_calculation",
"(",
"self",
",",
"analysis_brain",
",",
"item",
")",
":",
"is_editable",
"=",
"self",
".",
"is_analysis_edition_allowed",
"(",
"analysis_brain",
")",
"# Set interim fields. Note we add the key 'formatted_value' to the list",
"# of interims th... | 48.536585 | 0.001478 |
def get_type_data(name):
"""Return dictionary representation of type.
Can be used to initialize primordium.type.primitives.Type
"""
try:
return {
'authority': 'birdland.mit.edu',
'namespace': 'Genus Types',
'identifier': name,
'domain': 'Generic ... | [
"def",
"get_type_data",
"(",
"name",
")",
":",
"try",
":",
"return",
"{",
"'authority'",
":",
"'birdland.mit.edu'",
",",
"'namespace'",
":",
"'Genus Types'",
",",
"'identifier'",
":",
"name",
",",
"'domain'",
":",
"'Generic Types'",
",",
"'display_name'",
":",
... | 32.736842 | 0.001563 |
def combine_inputs(self, args, kw, ignore_args):
"Combines the args and kw in a unique way, such that ordering of kwargs does not lead to recompute"
inputs= args + tuple(c[1] for c in sorted(kw.items(), key=lambda x: x[0]))
# REMOVE the ignored arguments from input and PREVENT it from being chec... | [
"def",
"combine_inputs",
"(",
"self",
",",
"args",
",",
"kw",
",",
"ignore_args",
")",
":",
"inputs",
"=",
"args",
"+",
"tuple",
"(",
"c",
"[",
"1",
"]",
"for",
"c",
"in",
"sorted",
"(",
"kw",
".",
"items",
"(",
")",
",",
"key",
"=",
"lambda",
... | 78.8 | 0.017588 |
def to_file(epub, file):
"""Export to ``file``, which is a *file* or *file-like object*."""
directory = tempfile.mkdtemp('-epub')
# Write out the contents to the filesystem.
package_filenames = []
for package in epub:
opf_filepath = Package.to_file(package, directory)... | [
"def",
"to_file",
"(",
"epub",
",",
"file",
")",
":",
"directory",
"=",
"tempfile",
".",
"mkdtemp",
"(",
"'-epub'",
")",
"# Write out the contents to the filesystem.",
"package_filenames",
"=",
"[",
"]",
"for",
"package",
"in",
"epub",
":",
"opf_filepath",
"=",
... | 46.08 | 0.001701 |
def commit(self, cont = False):
""" Finish a transaction """
self.journal.close()
self.journal = None
os.remove(self.j_file)
for itm in os.listdir(self.tmp_dir): os.remove(cpjoin(self.tmp_dir, itm))
if cont is True: self.begin() | [
"def",
"commit",
"(",
"self",
",",
"cont",
"=",
"False",
")",
":",
"self",
".",
"journal",
".",
"close",
"(",
")",
"self",
".",
"journal",
"=",
"None",
"os",
".",
"remove",
"(",
"self",
".",
"j_file",
")",
"for",
"itm",
"in",
"os",
".",
"listdir"... | 27 | 0.02509 |
def create(self, validated_data):
"""
Create a new email and send a confirmation to it.
Returns:
The newly creating ``EmailAddress`` instance.
"""
email_query = models.EmailAddress.objects.filter(
email=self.validated_data["email"]
)
if e... | [
"def",
"create",
"(",
"self",
",",
"validated_data",
")",
":",
"email_query",
"=",
"models",
".",
"EmailAddress",
".",
"objects",
".",
"filter",
"(",
"email",
"=",
"self",
".",
"validated_data",
"[",
"\"email\"",
"]",
")",
"if",
"email_query",
".",
"exists... | 27.785714 | 0.002484 |
def validate(self, value, redis):
'''
Validates data obtained from a request and returns it in the apropiate
format
'''
# cleanup
if type(value) == str:
value = value.strip()
value = self.value_or_default(value)
# validation
self.vali... | [
"def",
"validate",
"(",
"self",
",",
"value",
",",
"redis",
")",
":",
"# cleanup",
"if",
"type",
"(",
"value",
")",
"==",
"str",
":",
"value",
"=",
"value",
".",
"strip",
"(",
")",
"value",
"=",
"self",
".",
"value_or_default",
"(",
"value",
")",
"... | 29.142857 | 0.001898 |
def _psrdp(cmd):
'''
Create a Win32_TerminalServiceSetting WMI Object as $RDP and execute the
command cmd returns the STDOUT of the command
'''
rdp = ('$RDP = Get-WmiObject -Class Win32_TerminalServiceSetting '
'-Namespace root\\CIMV2\\TerminalServices -Computer . '
'-Authentic... | [
"def",
"_psrdp",
"(",
"cmd",
")",
":",
"rdp",
"=",
"(",
"'$RDP = Get-WmiObject -Class Win32_TerminalServiceSetting '",
"'-Namespace root\\\\CIMV2\\\\TerminalServices -Computer . '",
"'-Authentication 6 -ErrorAction Stop'",
")",
"return",
"__salt__",
"[",
"'cmd.run'",
"]",
"(",
... | 46.9 | 0.002092 |
def create_xtm_handler(fileobj, title=u'Cablegate Topic Map', comment=u'Generated by Cablemap - https://github.com/heuer/cablemap'):
"""\
Returns a `ICableHandler` instance which writes XML Topic Maps syntax (XTM) 2.1.
`fileobj`
A file-like object.
"""
return MIOCableHandler(create_xtm_mioh... | [
"def",
"create_xtm_handler",
"(",
"fileobj",
",",
"title",
"=",
"u'Cablegate Topic Map'",
",",
"comment",
"=",
"u'Generated by Cablemap - https://github.com/heuer/cablemap'",
")",
":",
"return",
"MIOCableHandler",
"(",
"create_xtm_miohandler",
"(",
"fileobj",
",",
"title",
... | 43.125 | 0.008523 |
def destroy_page(self, tab_dict):
""" Destroys desired page
Disconnects the page from signals and removes interconnection to parent-controller or observables.
:param tab_dict: Tab-dictionary that holds all necessary information of a page and state-editor.
"""
# logger.info("des... | [
"def",
"destroy_page",
"(",
"self",
",",
"tab_dict",
")",
":",
"# logger.info(\"destroy page %s\" % tab_dict['controller'].model.state.get_path())",
"if",
"tab_dict",
"[",
"'source_code_changed_handler_id'",
"]",
"is",
"not",
"None",
":",
"handler_id",
"=",
"tab_dict",
"[",... | 59.6 | 0.008811 |
def _hex_to_bytes(hex_id):
"""Encodes to hexadecimal ids to big-endian binary.
:param hex_id: hexadecimal id to encode.
:type hex_id: str
:return: binary representation.
:type: bytes
"""
if len(hex_id) <= 16:
int_id = unsigned_hex_to_signed_int(hex_id)
return struct.pack('>q... | [
"def",
"_hex_to_bytes",
"(",
"hex_id",
")",
":",
"if",
"len",
"(",
"hex_id",
")",
"<=",
"16",
":",
"int_id",
"=",
"unsigned_hex_to_signed_int",
"(",
"hex_id",
")",
"return",
"struct",
".",
"pack",
"(",
"'>q'",
",",
"int_id",
")",
"else",
":",
"# There's ... | 35.875 | 0.002262 |
def fancy_transpose(data, roll=1):
"""Fancy transpose
This method transposes a multidimensional matrix.
Parameters
----------
data : np.ndarray
Input data array
roll : int
Roll direction and amount. Default (roll=1)
Returns
-------
np.ndarray transposed data
N... | [
"def",
"fancy_transpose",
"(",
"data",
",",
"roll",
"=",
"1",
")",
":",
"axis_roll",
"=",
"np",
".",
"roll",
"(",
"np",
".",
"arange",
"(",
"data",
".",
"ndim",
")",
",",
"roll",
")",
"return",
"np",
".",
"transpose",
"(",
"data",
",",
"axes",
"=... | 22.216667 | 0.000718 |
def locus_reads_dataframe(*args, **kwargs):
"""
Traverse a BAM file to find all the reads overlapping a specified locus.
Parameters are the same as those for read_locus_generator.
"""
df_builder = DataFrameBuilder(
LocusRead,
variant_columns=False,
converters={
"... | [
"def",
"locus_reads_dataframe",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"df_builder",
"=",
"DataFrameBuilder",
"(",
"LocusRead",
",",
"variant_columns",
"=",
"False",
",",
"converters",
"=",
"{",
"\"reference_positions\"",
":",
"list_to_string",
","... | 34.625 | 0.001757 |
def __relocate_cluster(self, cluster):
"""!
@brief Relocate cluster in list in line with distance order.
@param[in] cluster (cure_cluster): Cluster that should be relocated in line with order.
"""
self.__queue.remove(cluster)
self.__ins... | [
"def",
"__relocate_cluster",
"(",
"self",
",",
"cluster",
")",
":",
"self",
".",
"__queue",
".",
"remove",
"(",
"cluster",
")",
"self",
".",
"__insert_cluster",
"(",
"cluster",
")"
] | 33.1 | 0.017647 |
def lowpass_cheby2_coeffs(freq, sr, maxorder=12):
# type: (float, int, int) -> Tuple[np.ndarray, np.ndarray, float]
"""
freq : The frequency above which signals are attenuated
with 95 dB
sr : Sampling rate in Hz.
maxorder: Maximal order of the designed cheby2 filter
Return... | [
"def",
"lowpass_cheby2_coeffs",
"(",
"freq",
",",
"sr",
",",
"maxorder",
"=",
"12",
")",
":",
"# type: (float, int, int) -> Tuple[np.ndarray, np.ndarray, float]",
"nyquist",
"=",
"sr",
"*",
"0.5",
"# rp - maximum ripple of passband, rs - attenuation of stopband",
"rp",
",",
... | 35.275862 | 0.001903 |
def _print_message(self, prefix, message, verbose=True):
'Prints a message and takes care of all sorts of nasty code'
# Load up the standard output.
output = ['\n', prefix, message['message']]
# We have some extra stuff for verbose mode.
if verbose:
verbose_output =... | [
"def",
"_print_message",
"(",
"self",
",",
"prefix",
",",
"message",
",",
"verbose",
"=",
"True",
")",
":",
"# Load up the standard output.",
"output",
"=",
"[",
"'\\n'",
",",
"prefix",
",",
"message",
"[",
"'message'",
"]",
"]",
"# We have some extra stuff for ... | 40.354839 | 0.00078 |
def __args_check(self, valid, args=None, kwargs=None):
'''
valid is a dicts: {'args': [...], 'kwargs': {...}} or a list of such dicts.
'''
if not isinstance(valid, list):
valid = [valid]
for cond in valid:
if not isinstance(cond, dict):
# I... | [
"def",
"__args_check",
"(",
"self",
",",
"valid",
",",
"args",
"=",
"None",
",",
"kwargs",
"=",
"None",
")",
":",
"if",
"not",
"isinstance",
"(",
"valid",
",",
"list",
")",
":",
"valid",
"=",
"[",
"valid",
"]",
"for",
"cond",
"in",
"valid",
":",
... | 36.921053 | 0.002083 |
def _init_sqlite_functions(self):
"""additional SQL functions to the database"""
self.connection.create_function("sqrt", 1,sqlfunctions._sqrt)
self.connection.create_function("sqr", 1,sqlfunctions._sqr)
self.connection.create_function("periodic", 1,sqlfunctions._periodic)
self.c... | [
"def",
"_init_sqlite_functions",
"(",
"self",
")",
":",
"self",
".",
"connection",
".",
"create_function",
"(",
"\"sqrt\"",
",",
"1",
",",
"sqlfunctions",
".",
"_sqrt",
")",
"self",
".",
"connection",
".",
"create_function",
"(",
"\"sqr\"",
",",
"1",
",",
... | 71.5 | 0.027604 |
def prolong(self):
"""Prolong the working duration of an already held lock.
Attempting to prolong a lock not already owned will result in a Locked exception.
"""
D = self.__class__
collection = self.get_collection()
identity = self.Lock()
query = D.id == self
query &= D.lock.instance == identit... | [
"def",
"prolong",
"(",
"self",
")",
":",
"D",
"=",
"self",
".",
"__class__",
"collection",
"=",
"self",
".",
"get_collection",
"(",
")",
"identity",
"=",
"self",
".",
"Lock",
"(",
")",
"query",
"=",
"D",
".",
"id",
"==",
"self",
"query",
"&=",
"D",... | 28.481481 | 0.050314 |
def _write_trans_into_ods(ods, languages, locale_root,
po_files_path, po_filename, start_row):
"""
Write translations from po files into ods one file.
Assumes a directory structure:
<locale_root>/<lang>/<po_files_path>/<filename>.
"""
ods.content.getSheet(0)
for i, ... | [
"def",
"_write_trans_into_ods",
"(",
"ods",
",",
"languages",
",",
"locale_root",
",",
"po_files_path",
",",
"po_filename",
",",
"start_row",
")",
":",
"ods",
".",
"content",
".",
"getSheet",
"(",
"0",
")",
"for",
"i",
",",
"lang",
"in",
"enumerate",
"(",
... | 44.708333 | 0.000912 |
def get_ipopo_svc_ref(bundle_context):
# type: (BundleContext) -> Optional[Tuple[ServiceReference, Any]]
"""
Retrieves a tuple containing the service reference to iPOPO and the service
itself
:param bundle_context: The calling bundle context
:return: The reference to the iPOPO service and the s... | [
"def",
"get_ipopo_svc_ref",
"(",
"bundle_context",
")",
":",
"# type: (BundleContext) -> Optional[Tuple[ServiceReference, Any]]",
"# Look after the service",
"ref",
"=",
"bundle_context",
".",
"get_service_reference",
"(",
"SERVICE_IPOPO",
")",
"if",
"ref",
"is",
"None",
":",... | 31.25 | 0.001294 |
def trace_parser(p):
"""
Decorator for tracing the parser.
Use it to decorate functions with signature:
string -> (string, nodes)
and a trace of the progress made by the parser will be printed to stderr.
Currently parse_exprs(), parse_expr() and parse_m() have the right signature.
"""
... | [
"def",
"trace_parser",
"(",
"p",
")",
":",
"def",
"nodes_to_string",
"(",
"n",
")",
":",
"if",
"isinstance",
"(",
"n",
",",
"list",
")",
":",
"result",
"=",
"'[ '",
"for",
"m",
"in",
"map",
"(",
"nodes_to_string",
",",
"n",
")",
":",
"result",
"+="... | 23.326923 | 0.001582 |
def get_signout_token(self):
"""GetSignoutToken.
[Preview API]
:rtype: :class:`<AccessTokenResult> <azure.devops.v5_0.identity.models.AccessTokenResult>`
"""
response = self._send(http_method='GET',
location_id='be39e83c-7529-45e9-9c67-0410885880da',... | [
"def",
"get_signout_token",
"(",
"self",
")",
":",
"response",
"=",
"self",
".",
"_send",
"(",
"http_method",
"=",
"'GET'",
",",
"location_id",
"=",
"'be39e83c-7529-45e9-9c67-0410885880da'",
",",
"version",
"=",
"'5.0-preview.1'",
")",
"return",
"self",
".",
"_d... | 47.888889 | 0.009112 |
def spectra(
self):
"""*The associated source spectral data*
**Usage:**
.. code-block:: python
sourceSpectra = tns.spectra
"""
specResultsList = []
specResultsList[:] = [dict(l) for l in self.specResultsList]
return specResultsL... | [
"def",
"spectra",
"(",
"self",
")",
":",
"specResultsList",
"=",
"[",
"]",
"specResultsList",
"[",
":",
"]",
"=",
"[",
"dict",
"(",
"l",
")",
"for",
"l",
"in",
"self",
".",
"specResultsList",
"]",
"return",
"specResultsList"
] | 23.923077 | 0.012384 |
def connect(self):
"""Enumerate and connect to the first available interface."""
transport = self._defs.find_device()
if not transport:
raise interface.NotFoundError('{} not connected'.format(self))
log.debug('using transport: %s', transport)
for _ in range(5): # Re... | [
"def",
"connect",
"(",
"self",
")",
":",
"transport",
"=",
"self",
".",
"_defs",
".",
"find_device",
"(",
")",
"if",
"not",
"transport",
":",
"raise",
"interface",
".",
"NotFoundError",
"(",
"'{} not connected'",
".",
"format",
"(",
"self",
")",
")",
"lo... | 45.130435 | 0.001887 |
def init(filename=ConfigPath):
"""Loads INI configuration into this module's attributes."""
section, parts = "DEFAULT", filename.rsplit(":", 1)
if len(parts) > 1 and os.path.isfile(parts[0]): filename, section = parts
if not os.path.isfile(filename): return
vardict, parser = globals(), config... | [
"def",
"init",
"(",
"filename",
"=",
"ConfigPath",
")",
":",
"section",
",",
"parts",
"=",
"\"DEFAULT\"",
",",
"filename",
".",
"rsplit",
"(",
"\":\"",
",",
"1",
")",
"if",
"len",
"(",
"parts",
")",
">",
"1",
"and",
"os",
".",
"path",
".",
"isfile"... | 53 | 0.011329 |
async def unformat(self):
"""Unformat this partition."""
self._data = await self._handler.unformat(
system_id=self.block_device.node.system_id,
device_id=self.block_device.id, id=self.id) | [
"async",
"def",
"unformat",
"(",
"self",
")",
":",
"self",
".",
"_data",
"=",
"await",
"self",
".",
"_handler",
".",
"unformat",
"(",
"system_id",
"=",
"self",
".",
"block_device",
".",
"node",
".",
"system_id",
",",
"device_id",
"=",
"self",
".",
"blo... | 44.6 | 0.008811 |
def connectSig(self, signal):
"""
Connect to port item on subunit
"""
if self.direction == DIRECTION.IN:
if self.src is not None:
raise HwtSyntaxError(
"Port %s is already associated with %r"
% (self.name, self.src))
... | [
"def",
"connectSig",
"(",
"self",
",",
"signal",
")",
":",
"if",
"self",
".",
"direction",
"==",
"DIRECTION",
".",
"IN",
":",
"if",
"self",
".",
"src",
"is",
"not",
"None",
":",
"raise",
"HwtSyntaxError",
"(",
"\"Port %s is already associated with %r\"",
"%"... | 31.76 | 0.002445 |
def vector_to_volume(arr, mask, order='C'):
"""Transform a given vector to a volume. This is a reshape function for
3D flattened and maybe masked vectors.
Parameters
----------
arr: np.array
1-Dimensional array
mask: numpy.ndarray
Mask image. Must have 3 dimensions, bool dtype.... | [
"def",
"vector_to_volume",
"(",
"arr",
",",
"mask",
",",
"order",
"=",
"'C'",
")",
":",
"if",
"mask",
".",
"dtype",
"!=",
"np",
".",
"bool",
":",
"raise",
"ValueError",
"(",
"\"mask must be a boolean array\"",
")",
"if",
"arr",
".",
"ndim",
"!=",
"1",
... | 27.724138 | 0.002404 |
def barplot(df, column='Adjusted P-value', title="", cutoff=0.05, top_term=10,
figsize=(6.5,6), color='salmon', ofname=None, **kwargs):
"""Visualize enrichr results.
:param df: GSEApy DataFrame results.
:param column: which column of DataFrame to show. Default: Adjusted P-value
:param title... | [
"def",
"barplot",
"(",
"df",
",",
"column",
"=",
"'Adjusted P-value'",
",",
"title",
"=",
"\"\"",
",",
"cutoff",
"=",
"0.05",
",",
"top_term",
"=",
"10",
",",
"figsize",
"=",
"(",
"6.5",
",",
"6",
")",
",",
"color",
"=",
"'salmon'",
",",
"ofname",
... | 38.90566 | 0.008988 |
def init():
"""Initialize foreground and background attributes."""
global _default_foreground, _default_background, _default_style
try:
attrs = GetConsoleScreenBufferInfo().wAttributes
except (ArgumentError, WindowsError):
_default_foreground = GREY
_default_background = BLACK
... | [
"def",
"init",
"(",
")",
":",
"global",
"_default_foreground",
",",
"_default_background",
",",
"_default_style",
"try",
":",
"attrs",
"=",
"GetConsoleScreenBufferInfo",
"(",
")",
".",
"wAttributes",
"except",
"(",
"ArgumentError",
",",
"WindowsError",
")",
":",
... | 36.461538 | 0.002058 |
def to_message(self, keywords=None, show_header=True):
"""Format keywords as a message object.
.. versionadded:: 3.2
.. versionchanged:: 3.3 - default keywords to None
The message object can then be rendered to html, plain text etc.
:param keywords: Keywords to be converted t... | [
"def",
"to_message",
"(",
"self",
",",
"keywords",
"=",
"None",
",",
"show_header",
"=",
"True",
")",
":",
"if",
"keywords",
"is",
"None",
"and",
"self",
".",
"layer",
"is",
"not",
"None",
":",
"keywords",
"=",
"self",
".",
"read_keywords",
"(",
"self"... | 35.791209 | 0.000598 |
def pack(o, stream, **kwargs):
'''
.. versionadded:: 2018.3.4
Wraps msgpack.pack and ensures that the passed object is unwrapped if it is
a proxy.
By default, this function uses the msgpack module and falls back to
msgpack_pure, if the msgpack is not available. You can pass an alternate
ms... | [
"def",
"pack",
"(",
"o",
",",
"stream",
",",
"*",
"*",
"kwargs",
")",
":",
"msgpack_module",
"=",
"kwargs",
".",
"pop",
"(",
"'_msgpack_module'",
",",
"msgpack",
")",
"orig_enc_func",
"=",
"kwargs",
".",
"pop",
"(",
"'default'",
",",
"lambda",
"x",
":"... | 34.105263 | 0.001502 |
def popen_nonblock(*args, **kwargs):
"""
Create a process in the same way as popen_sp, but patch the file
descriptors so they can be accessed from Python/gevent
in a non-blocking manner.
"""
proc = popen_sp(*args, **kwargs)
if proc.stdin:
proc.stdin = pipebuf.NonBlockBufferedWriter... | [
"def",
"popen_nonblock",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"proc",
"=",
"popen_sp",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
"if",
"proc",
".",
"stdin",
":",
"proc",
".",
"stdin",
"=",
"pipebuf",
".",
"NonBlockBufferedWriter... | 26.578947 | 0.001912 |
def properties(dataset_uri, item_identifier):
"""Report item properties."""
dataset = dtoolcore.DataSet.from_uri(dataset_uri)
try:
props = dataset.item_properties(item_identifier)
except KeyError:
click.secho(
"No such item in dataset: {}".format(item_identifier),
... | [
"def",
"properties",
"(",
"dataset_uri",
",",
"item_identifier",
")",
":",
"dataset",
"=",
"dtoolcore",
".",
"DataSet",
".",
"from_uri",
"(",
"dataset_uri",
")",
"try",
":",
"props",
"=",
"dataset",
".",
"item_properties",
"(",
"item_identifier",
")",
"except"... | 32.407407 | 0.00111 |
def is_required_version(version, specified_version):
"""Check to see if there's a hard requirement for version
number provided in the Pipfile.
"""
# Certain packages may be defined with multiple values.
if isinstance(specified_version, dict):
specified_version = specified_version.get("versio... | [
"def",
"is_required_version",
"(",
"version",
",",
"specified_version",
")",
":",
"# Certain packages may be defined with multiple values.",
"if",
"isinstance",
"(",
"specified_version",
",",
"dict",
")",
":",
"specified_version",
"=",
"specified_version",
".",
"get",
"("... | 41.090909 | 0.002165 |
def dump(args):
"""
%prog dump fastbfile
Export ALLPATHS fastb file to fastq file. Use --dir to indicate a previously
run allpaths folder.
"""
p = OptionParser(dump.__doc__)
p.add_option("--dir",
help="Working directory [default: %default]")
p.add_option("--nosim", defau... | [
"def",
"dump",
"(",
"args",
")",
":",
"p",
"=",
"OptionParser",
"(",
"dump",
".",
"__doc__",
")",
"p",
".",
"add_option",
"(",
"\"--dir\"",
",",
"help",
"=",
"\"Working directory [default: %default]\"",
")",
"p",
".",
"add_option",
"(",
"\"--nosim\"",
",",
... | 25.513889 | 0.002096 |
def process(*args, **kwargs):
"""Runs the decorated function in a concurrent process,
taking care of the result and error management.
Decorated functions will return a concurrent.futures.Future object
once called.
The timeout parameter will set a maximum execution time
for the decorated functi... | [
"def",
"process",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"timeout",
"=",
"kwargs",
".",
"get",
"(",
"'timeout'",
")",
"# decorator without parameters",
"if",
"len",
"(",
"args",
")",
"==",
"1",
"and",
"len",
"(",
"kwargs",
")",
"==",
"0... | 36.115385 | 0.001037 |
def toggle_word_wrap(self):
"""
Toggles document word wrap.
:return: Method success.
:rtype: bool
"""
self.setWordWrapMode(not self.wordWrapMode() and QTextOption.WordWrap or QTextOption.NoWrap)
return True | [
"def",
"toggle_word_wrap",
"(",
"self",
")",
":",
"self",
".",
"setWordWrapMode",
"(",
"not",
"self",
".",
"wordWrapMode",
"(",
")",
"and",
"QTextOption",
".",
"WordWrap",
"or",
"QTextOption",
".",
"NoWrap",
")",
"return",
"True"
] | 25.5 | 0.011364 |
def model_saved(sender, instance,
created,
raw,
using,
**kwargs):
"""
Automatically triggers "created" and "updated" actions.
"""
opts = get_opts(instance)
model = '.'.join([opts.app_label, opts.object_na... | [
"def",
"model_saved",
"(",
"sender",
",",
"instance",
",",
"created",
",",
"raw",
",",
"using",
",",
"*",
"*",
"kwargs",
")",
":",
"opts",
"=",
"get_opts",
"(",
"instance",
")",
"model",
"=",
"'.'",
".",
"join",
"(",
"[",
"opts",
".",
"app_label",
... | 34.25 | 0.011848 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.