content stringlengths 35 762k | sha1 stringlengths 40 40 | id int64 0 3.66M |
|---|---|---|
def gaussian_noise(img):
""" Apply random noise to the image. """
cv.randu(img, 0, 255)
return {
"points": None,
"line_map": None
} | 3ec289b7eb71db0c235082ea476952c0140f4f53 | 67,400 |
def per_field_value(values, fields):
""" This normalises all patches relative to their field.
'fields' is a map of field numbers to a list of patches in that field.
"""
field_list = list(fields.values())
# We calculate the maximum and minimum values for each field.
maxs = [max((values[inde... | b51e344463d4d75f21ab8fc3a58d6201249fc2dc | 67,401 |
import torch
def one_hot(y, K, smooth_eps = 0): # pylint: disable=invalid-name
"""One-hot encodes a tensor with optional label smoothing.
Args:
y: A tensor containing the ground-truth labels of shape (N,), i.e. one label
for each element in the batch.
K: The number of classes.
smooth_eps: Labe... | ee47f9c778d875834c49c098ded4936edb104887 | 67,402 |
import os
def iradonmap_reconstructor(dataset='ellipses', size_part=1.0, pretrained=True, name=None):
"""
:param dataset: Can be 'ellipses' or 'lodopab'
:param size_part: Can be one of: [0.001, 0.002, 0.005, 0.01, 0.02, 0.05, 0.1, 0.2, 0.5, 1.0]
:return: The iRadonMap method trained on the specified d... | 08bb3b1424bdc5968adbb802d9e90c144b07dac1 | 67,403 |
def grids(request, template_name="grid/grids.html"):
"""lists grids
Template context:
* ``grids`` - all grid objects
"""
# annotations providing bad counts
#grids = Grid.objects.annotate(gridpackage_count=Count('gridpackage'), feature_count=Count('feature'))
return render(request, template... | 36110a0d5ce9192c9cf931b44c6aba2d193947bf | 67,404 |
import random
def generate():
"""
Generates a quote based on the internal markov chain.
:raises: ValueError: if parsing has not occured and the internal chain is invalid
"""
# If not parsed, fail.
if not _GRAPH[_START]:
raise ValueError("Please initilise the internal chain using parse(... | 1b5f55c2c6387dd829508c8eb2f9789f8685b42f | 67,405 |
def f_rank_classif(X, y):
"""
Same idea as f_classif, but computed on ranks
"""
X, y = check_X_y(X, y, accept_sparse=["csr", "csc", "coo"])
assert(isinstance(X, np.ndarray))
X = np.array([rankdata(feat_vector) for feat_vector in X])
args = [X[safe_mask(X, y == k)] for k in np.unique(y)]
... | 958e4bfb2d9c82f55094a2957eae197fc0d702e3 | 67,406 |
def index(request):
"""The home page."""
continent_counts, total_countries = display_country_totals()
context = {
'countries_per': continent_counts, # amount of countries per continent
'total_countries': total_countries, # total amount of countries in world
}
return render(request, '... | 11439688de8f20ca559d257e96ccfe15050e0716 | 67,407 |
def get_order_coeff_from_expr(expr, symb, order):
"""
example:
3*s**2 -4*s + 5, s, 3 -> 0
3*s**2 -4*s + 5, s, 2 -> 3
3*s**2 -4*s + 5, s, 1 -> -4
3*s**2 -4*s + 5, s, 9 -> 0
"""
p = sp.Poly(expr, symb, domain = "EX")
default = 0
return p.as_dict().get( (order,), def... | 791205bf4af1f8aeeb12fb22bfeb73ca8037885a | 67,408 |
def decodeTcpdump(FileName,**options):
"""
Function to extract RSSI information stored in a .txt file
Input
FileName Name of .txt file, input as string including file type termination
Output
addressList Dictionary with address names and index where they are stored
RSSI m... | ca04d1fa2e3d1d103ee032112461aedfb5d211ef | 67,409 |
import torch
def train(model, scaler, train_loader, epochs, optimizer, criterion, train_on_gpu):
"""
This is the training method that is called by the PyTorch training script. The parameters
passed are as follows:
model - The PyTorch model that we wish to train.
scaler - Scaler object... | 8ddad0b42a1fbabc961db8ae3bf8b2a9ac4c0714 | 67,410 |
from datetime import datetime
def home():
"""Renders the home page."""
return render_template('index.html',
posts=posts,
title='Contact',
year=datetime.now().year,
message='Your contact page.') | 6b97257331bae9134e6f92022f89dfaa3b30e7ba | 67,411 |
def getClasses():
"""
Returns a list of class ids from the database
"""
if 'email' not in session or session['email'] is None:
abort(401)
email = mailsane.normalize(session['email'])
if email.error:
abort(400)
return jsonify({'classList' : dbworker.getClasses(str(email)), '... | cc83b795dbfed3a0f7beb957d93683669d9e7e13 | 67,412 |
from typing import Optional
def disconnect(ip: Optional[str]) -> bool:
"""
Disconnect from the given device ip
:param ip: device ip
:return: true if successfully disconnected
"""
log().verbose(f"Disconnecting from {ip}..")
if execute("disconnect", ip=ip):
zope.event.notify(events.A... | 88198c24324b8eedfcb91c418a66980914e2636b | 67,413 |
def run_in_executor(executor, func, *args, **kwargs):
"""Run a blocking function in a separate thread in the tornado ioloop.
Copied from function which is added in a later version: https://www.tornadoweb.org/en/stable/_modules/tornado/ioloop.html#IOLoop.run_in_executor
Improves a little on the function by... | b31fc90a91c1a2cc021c5bb0b573283bc110e5b0 | 67,414 |
import argparse
import torch
def ipu_options(opt: argparse.ArgumentParser, cfg: yacs.config.CfgNode, model: Detector):
"""Configurate the IPU options using cfg and opt options.
Parameters:
opt: opt object containing options introduced in the command line
cfg: yacs object containing the config
... | e93cc1c08be77c41c9a103bea21acf6e2db64cbe | 67,415 |
from typing import Callable
def trigger_redraw(fn: Callable) -> Callable:
"""Method decorator for functions that need to trigger a re-draw.
Parameters
----------
fn : Callable
The function that needs to trigger a re-draw, e.g. because it changes
the appearance of the canvas.
Retu... | 4ef063fd85a81e3167cddf98a1311bd40ae04c1c | 67,416 |
def rsa_pkcs1v15_verify(certificate_or_public_key, signature, data, hash_algorithm):
"""
Verifies an RSASSA-PKCS-v1.5 signature.
When the hash_algorithm is "raw", the operation is identical to RSA
public key decryption. That is: the data is not hashed and no ASN.1
structure with an algorithm identi... | 788b5473fc8310c3b88ec7c39514039cb8f988d0 | 67,417 |
from typing import Optional
def to_timedelta(
arg,
unit: Optional[str] = None,
errors: str = "raise",
):
"""
Convert argument to timedelta.
Parameters
----------
arg : str, timedelta, list-like or Series
The data to be converted to timedelta.
unit : str, optional
D... | 77ec21509d69b60512d31be81dce6cf5d2317e9b | 67,418 |
def scheduling_blocks():
"""Return list of Scheduling Block instances known to SDP."""
sbi_list = SchedulingBlockInstanceList()
return dict(active=sbi_list.active,
completed=sbi_list.completed,
aborted=sbi_list.aborted) | a3171d351ca0a863340e22d2610c5c96999a393c | 67,419 |
def odd_ext(x, n, axis=-1):
"""Generate a new ndarray by making an odd extension of x along an axis.
Parameters
----------
x : ndarray
The array to be extended.
n : int
The number of elements by which to extend x at each end of the axis.
axis : int
The axis along which t... | bd5b1da526e8a97dcc8d26f42f56d695057021b2 | 67,420 |
import itertools
def patches_from_ct(ct_array, meta, patch_shape=None, centroids=None, stride=None, pad_value=0):
""" Given a CT scan, and a list of centroids return the list of patches
of the desired patch shape.
This is just a wrapper over crop_patch generator.
Args:
ct_array (np.ndarray):... | dd3f7e034477938c3239eda210904034de3ab64a | 67,421 |
def delivery_point_deliveries_waiting(request, campaign_id, delivery_point_id,
campaign, delivery_point, multi_tenant):
"""
:return: JsonResponse
"""
columns = _columns
if multi_tenant:
deliveries = GoodDelivery.objects.filter(Q(choosen_delivery_point__c... | 4411159e21d013c4e9218715c26cf4d809e51912 | 67,422 |
def inserisciNumero():
"""Permette di inserire all'utente un numero di fibonacci valido"""
num = int(raw_input("Inserisci il numero di Fibonacci da calcolare:\n"))
while num < 0:
num = int(raw_input("Inserisci un numero di Fibonacci valido (>= 0):\n"))
return num | 54c4315085201478232a8361910d349fc1fef210 | 67,423 |
def eval_generalized_normal_pdf(eval_at, mu=0.0, alpha=1.0, p=10.0, lower=-np.inf, upper=np.inf):
"""Evaluate the generalized normal pdf, scaled/shifted
See `sample_generalized_normal` for parameter definitions.
"""
generalized_normal = stats.gennorm(beta=p, loc=mu, scale=alpha)
unnormed_eval_pdf ... | 5fb01f00ad8d47630c02c60387fdd09a02d85a98 | 67,424 |
import re
def wrap_with_span(string, arg):
""" Wraps all instances of a string with a span element"""
words = arg.split(' ')
for word in words:
if word[-1].lower() == 's':
word = word[:-1]
pattern = re.compile(r'\b({0}[\w\d]*)\b'.format(word), flags=re.I)
for (match) ... | 9390f0f12d673c9a809760c1e7ff614d4fc079ef | 67,425 |
import pathlib
def resolve_extension_name(ext):
"""Search in extension folders and return fully-qualified extension name."""
basepath = pathlib.Path(".").resolve()
matching_ext = list(basepath.glob(f"**/*extension*/{ext}.py"))
if len(matching_ext) != 1:
matching_ext = list(basepath.glob(f"**/*... | 7582e47057417ac1b1b0e41c4cb61637222f91e9 | 67,426 |
def get_content_success(app_name):
"""
Retorna a mensagem de sucesso em caso de execução bem sucedida
:param app_name: Nome do app que está sendo criado
:type app_name: str
"""
params = {'app': app_name}
return render_to_string('app_generator/command/success.txt', params) | d5b5bb84a4e69b3866c396b3e7ee8e6cf7ac93ab | 67,427 |
def encumberance_desc( pc, show_ceiling=True ):
"""Return a string describing this PC's encumberance level."""
mass = sum( i.mass for i in pc.contents )
ec = pc.get_encumberance_ceilings()
el = pc.encumberance_level()
if show_ceiling:
return "{0}.{1}/{2}.{3}lbs {4}".format( mass//10, mass%10... | 833d3f66d50243902910b6af98809c529f397ae2 | 67,428 |
import os
def is_nix() -> bool:
"""
Determine if the platform is UNIX-like.
:return: `True` if the OS is UNIX-like, `False` otherwise.
:rtype: bool
"""
return os.name == "posix" | 35ebc6c15146ada2b0df5bff7fa922f08c5c9fa8 | 67,429 |
def correlation_by_exemplar(brands, exemplars, validation_scores, analyze_fn_str, outf):
""" Report the overall correlation with the validation scores using each exemplar in isolation. """
analyze_fn = getattr(analyze, analyze_fn_str)
keys = sorted(k for k in validation_scores.keys() if k in set(x[0] for x ... | e600e1a9b82a448dcff9d865a4366696d76131f0 | 67,430 |
def get_discont_price(S: float, i: float, n: int) -> float:
""" "
Parameters
----------
S : float
Сума
i : float
Річна ставка складних відсотків
n: int
Кількість років
Returns
-------
P : float
ціна
"""
return S / ((1 + i) ** n) | a5578e8dc80a27c9188c9213d43c3caae09b030a | 67,431 |
def plot_matrix_sizes(plots_no):
"""Calculate the size of the matrix fitting 'plots_no' plots.
Args:
plots_no (int): the number of plots in the matrix.
Returns:
tuple containing the number of row 'rows_no' and columns 'cols_no'.
"""
rows_no = floor(sqrt(plots_no))
cols_no = rows_no + ceil((plots_no - rows_no... | bcab52b63ac6973a92541b68073df0ac18a8847c | 67,432 |
def de_unicode(input):
""" json output ends up as unicode strings some/all of the time
this turns them into strings.
"""
if isinstance(input, dict):
foo=dict()
for key,value in input.iteritems():
foo[de_unicode(key)] = de_unicode(value)
return foo
elif isinstance(input, list):
foo = []
... | 003eea311e22c7c0b1ff2bcadf83a61be406601d | 67,433 |
def import_name(modulename, name=None):
""" Import identifier ``name`` from module ``modulename``.
If ``name`` is omitted, ``modulename`` must contain the name after the
module path, delimited by a colon.
Parameters:
modulename (str): Fully qualified module name, e.g. ``x.y.z``... | a320063e878db935f8a2409c7487617e2c9f1802 | 67,434 |
import argparse
def get_opts():
"""Return hostname and server from the list of command arguments."""
parser = argparse.ArgumentParser(
description='Get certificate information from server and validate it')
parser.add_argument('--server', '-s', help='Server to connect to')
parser.add_argument(
... | 6ac6b243d8757828339f9ed0d7e9c59059c659c2 | 67,435 |
def get_widgets(request):
"""Return a set of all available widgets."""
return WIDGETS | b286e3468f3e323617feb76541d5b01059c4cd5b | 67,436 |
def find_bounding_shape(virtual_size, available_shape):
"""
Finds a tuple of the same length as ``available_shape``, with every element
not greater than the corresponding element of ``available_shape``,
and product not lower than ``virtual_size``.
"""
assert virtual_size <= product(available_sha... | 46801faf463b34fe39ecaf71e7821444d29bb0eb | 67,437 |
def path_to_route(path_dataframe,edge_dataframe,tiploc_mapping_nodes):
"""Map the TIPLOC route onto the network route by mapping TIPLOC to network nodes and
Finding the equivalent route on a network for given node-node paths that might not be adjacent to each other
By estimating the shortest path between co... | 8bb849a6dcbfba47dd29bfccdbe6e7876b0a268d | 67,438 |
def thickness_params(xarray, mask_values= 0):
"""Return the plotting parameters for the surface oil thickness
:arg xarray: Output netcdf Lagrangian file loaded with xarray
:returns: tuple consisting of truncated array bounding the oil data needed, the x and y bounds for
further visualisation... | ac0f413376ef5c185f389d2a2814667b14366716 | 67,439 |
from unittest.mock import call
import sys
def run_subprocess(command):
"""
Run the subprocess
"""
try:
retcode = call(command, shell=True)
print("RAN: %s Returned: %s" % (command,retcode))
if retcode < 0:
print("CMD: %s, was terminated by signal: " % command,... | 6334513947c99ed4f1bbe28fe4c3bfcbd4fa4326 | 67,440 |
def createOutputTask1(DLmodel, testTokenizedSentences, testEncodedSentences, testClasses, testDocMapping, bertUtils, neji_classes=None):
"""
Runs the trained model on the unseen data split (validation or test), returning the resulting entity predictions
:param DLmodel:
:param testTokenizedSentences:
... | dfcbc32d394d76093a073a452d83206fff81080d | 67,441 |
def sort_012(arr):
"""
Given an input array consisting on only 0, 1, and 2, sort the array in a single traversal.
Args:
arr(list): List to be sorted
"""
if arr is None:
return arr
zero_index = 0
current_index = 0
two_index = len(arr) - 1
while current_index < len(arr... | d1fa4ee67c9d6b62928b5ea1e2fc1daf011db29d | 67,442 |
def handle_aborted(fsm_ctx):
"""
:param ctx: FSM Context
:return: True if successful other False
"""
global plugin_ctx
if plugin_ctx.nextlevel:
nextlevel_processing(plugin_ctx)
report_install_status(ctx=plugin_ctx, op_id=get_op_id(fsm_ctx.ctrl.before))
# Indicates the failure
... | 07488733031cf4989ece92728054f56363f7bc97 | 67,443 |
from operator import and_
def get_next_cat(last_index: int) -> models.Cat:
"""Get next cat.
Args:
last_index (int): View index of last seen cat.
"""
cat = None
if last_index != -1:
cat = models.Cat.query.filter(and_(models.Cat.disabled == False, models.Cat.index > last_index)).orde... | 055493449a0ad56739c16553474f767a2488c011 | 67,444 |
def txt_split(filename):
"""Strip '#' from first line and get string list of column
:filename: file to get header from
:returns: [string],ndarray
"""
with open(filename,'r') as f:
header=f.readline()
#strip header and split into words
header=header.translate(None,'#')
... | 52799d21f60a5a23f1571bbf3ea98b9d921f0ef5 | 67,445 |
def QueryChanges(host, param_dict, first_param=None, limit=None, o_params=None,
sortkey=None):
"""
Queries a gerrit-on-borg server for changes matching query terms.
Args:
param_dict: A dictionary of search parameters, as documented here:
http://gerrit-documentation.googlecode.com/svn... | c0618cbcb6975c7bafd3eec366fade451e040b47 | 67,446 |
def update(user_id, account_id, calendar_id, event_id, body):
"""
This function updates an account based on the provided information
:param user_id: user_id passed-in URL
:param account_id: account_id passed-in URL
:param calendar_id: calendar_id passed-in URL
:param event_id: event_id passed-i... | e432c33de97aaaf3da000a7f8641189aad64b6ab | 67,447 |
def stop_process(client, pid):
"""获取进程状态"""
stop_result = ""
command = 'kill -9 "%s" '
stdin, stdout, stderr = client.exec_command(command % pid) # 执行bash命令
kill_status = stdout.read()
error = stderr.read()
if error or kill_status:
error = error.split(':')[3].strip()
stop_re... | 454bb8763017119efe360cb5f7c07b9a353ba345 | 67,448 |
from typing import OrderedDict
from typing import Union
def match_state_dict(
model_dict : OrderedDict[str, Tensor],
pretrained_dict: OrderedDict[str, Tensor],
exclude : Union[tuple, list] = ()
) -> OrderedDict[str, Tensor]:
"""Filter out unmatched keys btw the model's `state_dict` and the
... | 4e27bab6d14c074a4d39b9ade24c2bb78045b36d | 67,449 |
import json
def get_original_df(handler):
"""Get the original dataframe which was uploaded to the webapp."""
data_dir = get_user_dir(handler)
meta_path = op.join(data_dir, 'meta.cfg')
if op.isfile(meta_path):
with open(meta_path, 'r') as fout: # noqa: No encoding for json
meta = j... | 71b1e49aef8ab43f2d029caa663c10ba0fe54139 | 67,450 |
def pil_gen(pil_mask_c, hmi_dat, threshperc=0.05, lx=800, ly=800,
polyor=4):
"""
Generate PIL polynomial.
Parameters
----------
pil_mask_c : list
PIL mask.
hmi_dat : list
Array of HMI values associated with the flare.
threshperc: float, optional
Percentag... | 0ebd5c967336ce4bb90763c2413e2d46d11c99df | 67,451 |
def rollmean(ts_data, window_size, alignment=Alignment.center):
"""
Compute the rollmean on TS data provided
This operator needs:
* a TS
* a window range (in number of points)
* an alignment method for the output
.. warning::
The TS must not contain any hole (an interpo... | 51949a07091cf9e8d9ae71b76ee6cbd2872750e8 | 67,452 |
def _append_x(clifford, qubit):
"""Apply an X gate to a Clifford.
Args:
clifford (Clifford): a Clifford.
qubit (int): gate qubit index.
Returns:
Clifford: the updated Clifford.
"""
clifford.table.phase ^= clifford.table.Z[:, qubit]
return clifford | 73a747ec0f8ea7245f6be9fe3805fa9fecf0665d | 67,453 |
def isprime(n, k=10):
"""test if n is a prime number
if n is less than 100, check if n is in a set of small primes
else check if n is prime using the Miller-Rabin test
>>> isprime(2) and isprime(2**1279-1)
True
>>> isprime(1) or isprime(-2)
False"""
if n == 2:
return True
if ... | d02d84e97ab545e084d90a1dcfe30c2693d51092 | 67,454 |
def add_overlap_ellipse(segm, ellipse_params, label, thr_overlap=1.):
""" add to existing image ellipse with specific label
if the new ellipse does not ouvelap with already existing object / ellipse
:param ndarray segm: segmentation
:param tuple ellipse_params: parameters
:param int label: selected... | a2b3e7d5c96854114793c22e7e9bb34a7f061ae6 | 67,455 |
import os
def create_dir(dir_path):
""" Creates a directory (or nested directories) if they don't exist.
"""
if not osp.exists(dir_path):
os.makedirs(dir_path)
return dir_path | a8d31870391153cee3ef67d9df13f9539d0eded9 | 67,456 |
def recursive_matches_strict(src, key, val, **kwargs):
"""
Searches the 'input' recursively for nested elements provided in 'key' with dot notation.
In case some levels are iterable (list, tuple) it checks every element.
In case the full path is inaccessible raises AttributeError or KeyError.
:para... | b179db90eb1d0d0494cc29e3b924ac277e7914b1 | 67,457 |
import pathlib
import os
def CanCreateSubmodule(repo, subpath, must_be_empty=False):
"""Returns a tupple of (repo,subpath) for the submodule repository for which
the given subpath can be created. This function walks recursively into
submodules, shortening the subpath as neccesary.
And if the submodul... | c388b8b7f13ebad58365816526dac7719efb8314 | 67,458 |
import functools
def cowell(k, r, v, tofs, rtol=1e-11, *, ad=None, **ad_kwargs):
"""Propagates orbit using Cowell's formulation.
Parameters
----------
k : ~astropy.units.Quantity
Standard gravitational parameter of the attractor.
r : ~astropy.units.Quantity
Position vector.
v ... | c6b188130811216b0f72912e3918623a8e20702f | 67,459 |
from typing import Tuple
import bisect
def find_closest(m: 'Metric', key: metric_key) -> Tuple[metric_key, metric_key]:
""" assumes keys are sorted."""
if m.keysmin >= key: # neet to extrapolate
left, right = m.all_keys[:2]
elif m.keysmax <= key:
left, right = m.all_keys[-2:]
else:
... | a92f6d1eef1b05727395652c2a904216a0b51781 | 67,460 |
def add_host(params, host_name, host_visible_name):
"""Add Host to Zabbix."""
try:
result = params['zapi'].host.create(
host=host_name,
name=host_visible_name,
description=host_visible_name,
interfaces=[
{
'type': 1,
... | 21252590f55789ec72aea192917c9f931f73a469 | 67,461 |
def list_rune(*args, nodes, attrs, context):
"""Creates an unordered list."""
style = " - " if len(args) < 1 else args[0]
def list_recurse(s, i, n): # style, indent, nodes
for node in n:
if isdata(node):
yield i + s + node.data
if len(node.nodes) > 0:
... | 260456b0035796f57807b0c3f1e30c8684dd8fa6 | 67,462 |
def calculate():
"""
Perform a super important calculation.
"""
return 12 | b6aa643b9f6e24f579fdc273c2dec512692cdc4b | 67,463 |
from typing import List
def connect_mini_buckets(mini_buckets:List[Bucket])->List[int]:
"""
connect mini buckets with possibly different variable labels by maximal separators
"""
mini_bucket_inds = []
g_score = dict()
for src in range(len(mini_buckets)):
g_score[src] = dict()
f... | b0a3d03d4faa1c912fa2952a2edb376be9d2a280 | 67,464 |
def check_if_get_event_types_succeeds(frauddetector_client, event_type_to_check: str):
"""
This calls get_event_types and returns True if the response contains an event type: (True, event_type)
If the call does not return any event types, return (False, None)
:param frauddetector_client: frauddetector b... | ceb961770f643f8c88b20b2ee0cea2209d9ffcd3 | 67,465 |
def get_cleanse_logs(user_cleanse_id):
"""Shows all cleanse logs for a specific user cleanse"""
return CleanseLog.query.filter(CleanseLog.user_cleanse_id == user_cleanse_id).all() | f3be3573d19e9aa6065e2546a02cdc9b3c802fb6 | 67,466 |
def shard_hset(connection, base, key, value, total_elements, shard_size):
"""分片式的hset函数"""
shard = shard_key(base, key, total_elements, shard_size)
return connection.hset(shard, key, value) | 444511a3ce202f0bd5992cdfe33ec9e99c1e50a4 | 67,467 |
def load_fermi_image():
"""Load Fermi counts image for the Galactic center region.
Returns
-------
hdu : `~astropy.io.fits.ImageHDU`
Image HDU
Examples
--------
.. plot::
:include-source:
from photutils import datasets
hdu = datasets.load_fermi_image()
... | 94ae2e1ee302897ff7989e3f8ca88ae1a3f7c544 | 67,468 |
def color(red: int, green: int, blue: int, white: int = 0):
"""Convert the provided red, green, blue color to a 24-bit color value.
Each color component should be a value 0-255 where 0 is the lowest intensity
and 255 is the highest intensity.
Note the sequencing has been changed from RGB (most signific... | e821999f1a66d1bc8a7bec4dc298679b205165ad | 67,469 |
def N_(msg):
"""Designate a string to be found by gettext but not to be translated."""
return msg | e82c1f4219e53be05e863bfd636bec932ddd7f5c | 67,470 |
def getticket():
"""
获取 jsapi_ticket
http://mp.weixin.qq.com/wiki/7/aaa137b55fb2e0456bf8dd9148dd613f.html#.E9.99.84.E5.BD.951-JS-SDK.E4.BD.BF.E7.94.A8.E6.9D.83.E9.99.90.E7.AD.BE.E5.90.8D.E7.AE.97.E6.B3.95
"""
access_token = request.args.get('access_token', None)
if not access_token:
ret... | 33c5477109ae2a2a40fec4444e18de32d7129026 | 67,471 |
import json
def _get_needed_packages(json_file, test=None):
"""
Returns a dict with needed packages based on a JSON file.
If a test is specified it will return the dict just for that test.
"""
needed_packages = {}
with open(json_file) as f:
test_packages = json.load(f)
for key,va... | b929e57beda05372b03936598db275e87a318962 | 67,472 |
import os
async def is_init():
""" Determine whether to initialize """
return os.path.exists(CONN_PATH) | dcb712dff150034cd1ea7e0e7751f1d9098c8091 | 67,473 |
def calc_eigenvectors(verts: [[float]]):
"""
It computes eigenvectors from a set of vertices.
----------------------------
Args:
verts (obj: 'list' of obj: 'list' of float): The list of vertices
Returns:
eigenvalues (obj: 'list'): The list of eigenvalues
eigenvectors (obj: 'l... | e8d7e6a675718075da23fc4cc461fd9cff4e485c | 67,474 |
import collections
def steps_to_weighted_trajectories(steps, ensembles):
"""Bare function to convert to the weighted trajs dictionary.
This prepares data for the faster analysis format. This preparation only
need to be done once, and it will cover a lot of the analysis cases.
Parameters
--------... | 2006053befc0245a943b45d3fcb5b3269c000b35 | 67,475 |
def get_parser():
"""
Get parser object for `eco_mocks_create.py` script.
Returns
-------
args:
input arguments to the script
"""
## Define parser object
description_msg = 'Downloads the necessary catalogues from the web'
parser = ArgumentParser(description=description_msg,... | a3fd681a723abff5b1e5526e33598483fe84997d | 67,476 |
def grid_creator():
"""formats the given grid from project euler"""
a = '08 02 22 97 38 15 00 40 00 75 04 05 07 78 52 12 50 77 91 08'
b = '49 49 99 40 17 81 18 57 60 87 17 40 98 43 69 48 04 56 62 00'
c = '81 49 31 73 55 79 14 29 93 71 40 67 53 88 30 03 49 13 36 65'
d = '52 70 95 23 04 60 11 42 69 2... | 1a08ad9671fb14a03671b803e4045c5c7d3b9286 | 67,477 |
from typing import Sequence
from typing import List
def transposition_order_rep(
ttset: Sequence,
n: int
) -> List:
""" Applies the transposition operation on a tone row with its order numbers
"""
result = [0] * len(ttset)
for i, pair in enumerate(ttset):
new_pc = (pair[1] + n) % 12
... | 1d9bf53166d3119b465c9dab4c7558892f720b79 | 67,478 |
def groupby_healpix(df, equal_area_points, return_point_indices=True):
"""
Given a (geo)dataframe with irregularly distributed point in lat,long,
and equal area point distribution, this functions will bin the dataframe point
based on the equal area pixel extents (using the underlying healpix function).... | 141e3d16d087e008c643cf1daac514249d24a3e6 | 67,479 |
def parse_lines(lines: str):
"""
Parse multiple Write objects separeted by new-line character.
"""
writes = map(LineParser.parse, lines.split("\n"))
return list(writes) | a6533fb6972f66692e730d10d2253b59cad77d8a | 67,480 |
def get_factory_log_recipients(entry):
"""Read the log recipients specified by the Factory in its configuration
Args:
entry: dict-like object representing the entry configuration
Returns:
list: list contaning the URLs of the log servers, empty if none present
"""
entr_attrs = entry... | f3e776ea9b8102247b5c7e817762523467d9f953 | 67,481 |
def translate_name(name: str) -> str:
"""Not complete func"""
return name.replace(' ', '+').replace(',', '%2C').replace('’', "'") | 4faf41ffbd2231b35bc235c1c76ea9403b7cd78c | 67,482 |
import csv
def get_conditions_bids(infile):
"""
read onsets, duration and amplitude from 3 column format file.
(e.g. events.tsv in BIDS format)
"""
spec = []
if infile.endswith('.tsv'):
# read tsv file
with open(infile) as f:
reader = csv.reader(f, delimiter='\t'... | 3bd0546115fa635abbcc7829911fdb476ad1c33e | 67,483 |
import torch
def compute_colors_for_labels(labels, palette=None):
"""
Simple function that adds fixed colors depending on the class
"""
if palette is None:
palette = torch.tensor([2 ** 25 - 1, 2 ** 15 - 1, 2 ** 21 - 1])
colors = labels[:, None] * palette
colors = (color... | aaab8121146d43c44db7a2450c384213b1b92b7f | 67,484 |
import os
def bmSettings():
"""Allows the viewing and modification of keys.dat settings."""
global keysPath
global usrPrompt
BMConfigParser().read(keysPath) # Read the keys.dat
try:
print(' Configure file loading: %s' % os.path.realpath(keysPath))
port = BMConfigParser().get... | 70a73f370ebbb1f96c4345c293e33b5c8ef8a307 | 67,485 |
from datetime import datetime
def get_query_params(node='SLAP_PGEB-APND',
market='RT5',
startdate=datetime(2019, 1, 1),
enddate=datetime(2019, 1, 15),
tz_in='US/Pacific',
tz_out='US/Pacific'):
"""Create a dict... | 13169e3956fd30e08bc064228a8bfdbf9db36bda | 67,486 |
def preprocess(raw):
"""
Basic text formatting e.g. BOM at start of file
"""
## 1. Remove byte order marks if necessary
if raw[0]=='\ufeff':
raw = raw[1:]
# if raw[0] == '\xef':
# raw = raw[1:]
# if raw[0] == '\xbb':
# raw = raw[1:]
# if ... | dfeb75152196ff2ab751ee206aab03eed1f28502 | 67,487 |
def get_assignment_student_grades(course_id, student_id):
""" return a list of a student's assignments with grades
https://canvas.instructure.com/doc/api/analytics.html#method.analytics_api.student_in_course_assignments """
return api.get_list('courses/{}/analytics/users/{}/assignments'.format(course_id... | 488fda23b4978ee820ab60638a6df6fe3fc86f65 | 67,488 |
from typing import Optional
from typing import Dict
def get_strain_strat(voc_params: Optional[Dict[str, VocComponent]]):
"""
Stratify the model by strain, with two strata, being wild or "ancestral" virus type and the single variant of
concern ("VoC").
Args:
voc_params: All the VoC parameters ... | eb9f2c21c506eebccc9b74d59ac3391e8427ef68 | 67,489 |
import tarfile
import json
from datetime import datetime
import re
import uuid
def oc_parser(instance, parameters, context, feedback, inputs):
"""
Dieses Python-Script liest aus Daten einem tar-komprimierten Abbild OpenCaching Datenbank Standorte und Attribute von Geocaches sowie Schutzgebieten ein und schrei... | 6309b16fc9f8043dcfd20bcadbaab84a36e24599 | 67,490 |
def business(category):
"""
view root page function that returns the categories page and its data
"""
news_categories_articles = get_category(category)
return render_template('business.html', business = news_categories_articles) | 0a9ee4416545bc95dc4a568d469543ebee15c9a1 | 67,491 |
import time
import zlib
def query_cash_flow_data(code, year=None, quarter=None):
"""季频现金流量
@param code: 证券代码,不可为空
@param year: 统计年份,为空时默认当前年
@param quarter: 统计季度,为空时默认当前季度
"""
data = rs.ResultData()
if code is None or code == "":
print("股票代码不能为空,请检查。")
data.error_msg = "股票代... | a5dfe8f78abef656562c8eb5824d31fde62a38e5 | 67,492 |
def calc_num_pixels(num_pixels, stride):
"""
Converts the current number of pixels to the number there will be given
a specific stride.
"""
return 1 + (num_pixels - 1) // stride | b6ae056339913c496017251709381c19f551a074 | 67,493 |
import re
def wrap_onspace_strict(text, width):
"""Similar to wrap_onspace, but enforces the width constraint:
words longer than width are split."""
wordRegex = re.compile(r'\S{'+str(width)+r',}')
return wrap_onspace(wordRegex.sub(lambda m: wrap_always(m.group(),width),text),width) | 0a52193b5dc2b827a875641b5cb233b330ef9bfe | 67,494 |
def _eigen_projection(x, b):
"""
Project the vector `x` onto the eigenvector `b`. Here `b` is a column of the matrix B which is an orthonormal
basis from the eigendecomposition::
BDB = C
Parameters
----------
x : array_like, shape (n,)
Vector.
b : array_like, shape (n,)
... | d6ce8183bfa25d474c868786959ed663cd83fbd2 | 67,495 |
def disk_simple(radius, precision=0.0001):
"""
A centered disk of specified radius.
Parameters
----------
radius : float
Radius of desired disk, presumed to be in coordinate units.
precision : float, must be << 1
Desired upper bound for error in fractional partial volumes.
... | 183e4884c5781d5ba32332f6f740592e9b9e8b86 | 67,496 |
import psutil
import subprocess
import os
def memory_usage():
"""Get memory usage of current process in MiB.
Tries to use :mod:`psutil`, if possible, otherwise fallback to calling
``ps`` directly.
Return:
float: Memory usage of the current process.
"""
pid = os.getpid()
try:
... | b23f680738b46aa83fced1e2e9a7e8807cc9f4b4 | 67,497 |
def tokenize(language):
"""Function to tokenize language by mapping words to integer indices"""
# Perform tokenization
language_tokenizer = Tokenizer(filters='')
language_tokenizer.fit_on_texts(language)
tensor = language_tokenizer.texts_to_sequences(language)
# Pad sequences to maximum found se... | 88466883179065a77f1355a5c7d13989f8fd2e57 | 67,498 |
import re
def _fix_broken_markup(html):
"""Replaces invalid comment tags"""
if html.startswith("<CENTER>"):
logger.error("TolkienFanFiction.com couldn't handle this request: '%s'" % html)
html = re.sub("<!-.+?->", "", html)
return html | 4a4b5749ea7737965fd135e0b190cdb8e1ee3d37 | 67,499 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.