content stringlengths 35 762k | sha1 stringlengths 40 40 | id int64 0 3.66M |
|---|---|---|
def main(global_config, **settings):
""" This function returns a Pyramid WSGI application.
"""
# Database setup
common_db_configure(settings)
# Add some default settings (would be nicer to do this programatically)
f = "route_url = pyramid_jinja2.filters:route_url_filter"
settings['jinja2.fi... | 1d51148ec8ce2ca2a1753b45170d6e83a12fe022 | 52,500 |
import yaml
def wsgi_server(config_path):
"""create wsgi server given a config path"""
with open(config_path) as fp:
config = yaml.load(fp)
tile_server = create_tileserver_from_config(config)
return tile_server | 557f84ccbae734a5598dbefce8a22e0b5ad64679 | 52,501 |
def all_task_types_for_sequence(sequence, client=default):
"""
return the list of task_tyes for given asset and current user.
"""
sequence = normalize_model_parameter(sequence)
path = "user/sequences/%s/task-types" % sequence["id"]
task_types = raw.fetch_all(path, client=client)
return sort_... | bd0b665a8045dd53c30092ff29af90a78a2170e3 | 52,502 |
def find_most_probable_dates(text):
"""
Find in text the patterns that are the most probable to be the date of the documents and return them as
a list match objects, along with the code that characterize the date.
text : the text to be analyzed
Return : (match_list, code)
match_list : the list o... | bcfb36e4d5017c9746b761f5c263c853be037ef6 | 52,503 |
import scipy
def gensettings(T, Z=300, EED=1e-6, n=5e19, yMax=5):
"""
Generate appropriate DREAM settings.
T: Electron temperature.
Z: Effective charge of plasma.
EEc: Electric field (in units of critical electric field).
n: Electron density.
yMax: Maximum momentum (normalized t... | 123ef49d540c11d3bbe3620a75de0ca48357b641 | 52,504 |
import random
def get_fitness(individual, hash_table, environment, rerun=0):
"""
Gets fitness from hash table if possible, otherwise gets it from simulation
rerun = 0 means never rerun
rerun = 1 means rerun with diminishing probability
rerun = 2 means rerun always
"""
values = hash_table.f... | 648814b573af3237d5d6f3ed9aaff73fbc0e2e40 | 52,505 |
import itertools
def grid_params(dict):
""" Generate all possible combinations (cartesian product) of the hyperparameter values
Returns:
A new dictionary with a grid of all the possible hyperparameter combinations
"""
keys = dict.keys()
val_arr = []
for key in keys:
val_arr.appen... | ca8fdd49d094c3e43e08614c32a40c2d4f020748 | 52,506 |
def datetime_to_str(dt):
"""
Convert default datetime format to str & remove digits after int part of seconds
"""
result = dt.strftime('%Y-%m-%d %H:%M:%S.%f')[:-7]
return result | 5a08bb546f8afc8a6dbbbf827389f86d8004de28 | 52,507 |
from typing import List
def longest_substring_using_nested_for_loop(s: str) -> int:
"""
Given a string s, find the length of the longest substring without repeating characters.
https://leetcode.com/problems/longest-substring-without-repeating-characters/
3946 ms 14.2 MB
>>> longest_substring_usin... | 996ce5fcb956012cb75fef35c6bec8be6ecad461 | 52,508 |
def neighborhood_values(image: np.ndarray, r: int, c: int, mode: str):
"""
Get values of pixels in the neighborhood of the current position
"""
assert mode in {'forward', 'reverse', 'search', 'forward4'}
neighborhood = []
for (supp_r, supp_c) in neighborhood_idxs(image, r, c, mode):
if... | 8185aefdac574bd7287d76d9f5df7b50e3aa8abc | 52,509 |
def get_fit3_treatment():
"""
Returns fit file for unit tests.
"""
info_path = InfoPath(
path='temp_data',
dir_name="a04_height3_treatment",
sub_dir_name=InfoPath.DO_NOT_CREATE
)
iters = get_iters()
data = get_data3_tr... | 71bcb7c6f2726256221031529270e2888c981539 | 52,510 |
def _get_string_value(dictionary, key, default=None):
"""Return the valid string value for key in dictionary or default."""
if isinstance(dictionary, dict) and isinstance(key, str):
value = dictionary.get(key)
if _is_valid(value):
return value
return default | 5bcefc4a8a118dc933ded99a03ef62ca285ef6fe | 52,511 |
def children_intent_handler(handler_input):
"""Handler for Hello World Intent."""
# type: (HandlerInput) -> Response
speech_text = 'Aus meiner Ehe mit Eleonore gingen sechs Kinder hervor, wovon der 1459 geborene Maximilian und die 1465 geborene Kunigunde überlebten.'
try:
if ENABLE_TWEETS:
... | af0edee370ae2d3c99988a901d3a61adaff86745 | 52,512 |
def least_squares_GD(y, tx, initial_w, max_iters, gamma, debug = False):
""" implement least squares via gradient descent """
losses, ws = gradient_descent(y, tx, initial_w, max_iters, gamma, loss_f = model_linear.compute_loss, grad_f = model_linear.compute_gradient, debug = debug)
return get_last_ans(ws, l... | f937aa478091f37504e59699a315415c94453a5a | 52,513 |
import os
def getJobDir(jobName=None):
"""
Full path of the harnessed job scripts.
"""
if jobName is None:
jobName = getJobName()
return os.path.join(os.environ['LCATR_INSTALL_AREA'], jobName,
os.environ['LCATR_VERSION']) | 613f5867ca2a612859c58aede8a435688fb52c7a | 52,514 |
from pathlib import Path
def generate_notebook(
notebook: dict, credentials: Credentials, package_versions: dict, path: Path
) -> None:
"""
Modifies a notebook so that the Relevanceclient has the proper credentials.
Updates notebook to latest RelevanceAI SDK version.
"""
notebook["metadata"][... | 25c92ffbc025bb0d7761dd08cdd3119fd9c7d9a6 | 52,515 |
def create_app() -> Application:
"""
Creates a new instance of the application.
"""
app = Application.create(
name='Auth API',
secret=INTERNAL_TOKEN_SECRET,
health_check_path='/health',
)
# -- OpenID Connect Login ------------------------------------------------
# ... | de7a213a6c337808ab932c14dd40d4bc379b6cb5 | 52,516 |
import re
def isSane(filename):
"""Check whether a file name is sane, in the sense that it does not contain any "funny" characters"""
if filename == '':
return False
funnyCharRe = re.compile('[\t/ ;,$#]')
m = funnyCharRe.search(filename)
if m is not None:
return False
if filena... | d9e8bac7ebad1fd2af024f8880e255fcb40db68c | 52,517 |
def get_list_of_keys( d, *keys ):
"""
crea un nuevo dicionario con el subconjunto de llaves
Parameters
==========
d: dict
keys: tuple
Examples
========
>>>origin = { 'a': 'a', 'b': 'b': 'c': 'c' }
>>>get_list_of_keys( origin, 'b', 'c' )
{ 'b': 'b': 'c': 'c' }
"""
re... | c20291f2b3fe720ccf25e9a08dde15927fce97fb | 52,518 |
def _nearest_cluster_distance(distances_row, labels, i):
"""Calculate the mean nearest-cluster distance for sample i.
Parameters
----------
distances_row : array, shape = [n_samples]
Pairwise distance matrix between sample i and each sample.
labels : array, shape = [n_samples]
labe... | 1fe20cfddf336dab54aaa4140427b93c6cbf89c1 | 52,519 |
import requests
import json
def submit_request(testurl,payload,method,headers):
""" Function to submit Akamai API """
logger.debug("Requesting Method: %s URL %s with payload: %s with Headers %s", \
method, testurl, payload, headers)
my_headers = headers
logger.debug(my_headers)
req_session = r... | 752f3baff6aa8aaeb846f4288f860d2870f371a0 | 52,520 |
def condense_residual_matrix(matrix, sequential_diffs, data_density):
"""
Condense the residuals from a residual matrix to three columns
that represent how far out the prediction was, the number of data points,
and the observed residual.
Args:
matrix: (np.ndarray)
sequential_diffs:
... | 36e3202269f230849df0afe2801a7586ab4c7862 | 52,521 |
from pathlib import Path
def lfn_list(wb, lfn: str = ''):
"""Completer function : for a given lfn return all options for latest leaf"""
if not wb: return []
if not lfn: lfn = '.' # AlienSessionInfo['currentdir']
list_lfns = []
lfn_path = Path(lfn)
base_dir = '/' if lfn_path.parent.as_posix() ... | 997a11088e0ff198c4b4db38f420ae30784a4232 | 52,522 |
def unmap(roi_db):
"""
For each entry in a database, unmap the labels and bounding box targets
back to the full canvas size.
"""
for db in roi_db:
db['labels'] = _unmap(db['labels'], db['total_anchors'], db['idx_inside'], fill=-1)
db['bbox_targets'] = _unmap(db['bbox_targets'], db['... | c148fe25aaaae8c2f16d7ea5882bd07d216b62c9 | 52,523 |
import csv
import itertools
def csv_read_row(filename, n):
""" Read and return nth row of a csv file, counting from 1. """
with open(filename, 'r') as f:
reader = csv.reader(f)
return next(itertools.islice(reader, n-1, n)) | a95cf8ed35b61acff418a02bfa5f8285f589e6d6 | 52,524 |
def load_proto(fpath, proto_type):
"""Load the protobuf
Args:
fpath: The filepath for the protobuf
Returns:
protobuf: A protobuf of the model
"""
with open(fpath, "rb") as f:
return proto_type().FromString(f.read()) | 7b6bcf6d2e56f2ca4087a9ec769b16a986511c55 | 52,525 |
import six
def parse_fetch_response(text, normalise_times=True, uid_is_key=True):
"""Pull apart IMAP FETCH responses as returned by imaplib.
Returns a dictionary, keyed by message ID. Each value a dictionary
keyed by FETCH field type (eg."RFC822").
"""
if text == [None]:
return {}
res... | 3d629cb318ccf48f36a276a26caf7526e23aa4ea | 52,526 |
def compute_result(result_parameter, inputs, env, fix_point):
"""
Funciton to generate the expected result of the testcase.
Arguments
---------
result_parameter: Either OutputArgument or ReturnValue (see pulp_dsp_test.py)
inputs: Dict mapping name to the Argument, with arg.value, arg.ctype (and... | cb8798f79ae641f7223b5597c51f37e87f1f3bfe | 52,527 |
import re
def read_mp_feat(pred_path):
"""
if no prediction was done take mp_feat_norm
"""
header = []
temp = {}
test = makehash()
for line in open(pred_path, "r"):
line = line.rstrip("\n")
if line.startswith(str("ID") + "\t"):
header = re.split(r"\t+", line)
... | 54e70de2d34c4f8cbee5cec638ff22f5a4e6afa3 | 52,528 |
from typing import Any
def netconf_capabilities(task: Task, **kwargs: Any) -> Result:
"""nornir get netconf capabilities
:params task: type object
:returns: nornir result object
"""
conn = task.host.get_connection(
connection="netconf", configuration=task.nornir.config
)
results =... | 95119f081e9d06b43c8da36550b3e47aa7731eae | 52,529 |
def objective_fun(beta, lam, K, y):
"""Dual objective of binary kernel SVMs with intercept."""
# The dual objective is:
# fun(beta) = 0.5 beta^T K beta - beta^T y
# subject to
# sum(beta) = 0
# 0 <= beta_i <= C if y_i = 1
# -C <= beta_i <= 0 if y_i = -1
# where C = 1.0 / lam
return 0.5 * jnp.dot(beta,... | b72cecabdaf6f07fdba4f02f63b7e3923bdf7160 | 52,530 |
def is_unquoted_text(token):
"""
:param token: Token
:return: boolean
"""
return isinstance(token, UnquotedText) | 5f3a95c855885a7c607b5ab8889eac821fef50a2 | 52,531 |
def gallery(request):
"""renders the gallery for all images
"""
if request.user.is_authenticated():
return render(request, 'gallery.html')
return HttpResponseRedirect("/") | cdf17f2fb01444a2532457a775276dc77af0cd49 | 52,532 |
def rel_rmse(obs, mod):
"""returns RMSE of model results given observations"""
arg = ((mod - obs) / obs) ** 2
return sqrt(nanmean(arg)) | e5f99281123e255a47e949ee39380b194f180b15 | 52,533 |
import json
import logging
def spell_check(request):
"""
Returns a HttpResponse that implements the TinyMCE spellchecker protocol.
"""
try:
if not enchant:
raise RuntimeError("install pyenchant for spellchecker functionality")
raw = force_text(request.body)
input =... | 969cd2bc685c6ca9aef0e9eef850a4fb38dbe2ff | 52,534 |
def initialize_firebase():
"""Initialize Firebase, unless already initialized.
Returns:
(Firestore client): A Firestore database instance.
"""
try:
initialize_app()
except ValueError:
pass
return firestore.client() | 93c6e263bf94e9a9133605b2e7da730fcb5acccf | 52,535 |
def evaluate_(batch_iter, model):
""" To evaluate the model in EDU segmentation.
因内存原因,我们依旧选择批量运算的方式
不同的解码评测,不同的是,这个模式下只要一句一句进行,因为边界是未知
的,所以模型要做完边界预测才知道下一步做什么。
"""
c_b, g_b, h_b = 0., 0., 0.
for n_batch, (inputs, target) in enumerate(batch_iter, start=1):
word_ids, word_e... | 972758d49c81a176f1c50458757c8da59aebf70f | 52,536 |
from typing import Tuple
from pathlib import Path
def saved_model(od_detection_learner, tiny_od_data_path) -> Tuple[str, Path]:
""" A saved model so that loading functions can reuse. """
model_name = "test_fixture_model"
od_detection_learner.save(model_name)
assert (Path(tiny_od_data_path) / "models" ... | 383cd80905992775814be6f0024c836ec0c73c3d | 52,537 |
import itertools
def build_instance(ξ, n, m, r, D):
"""The graph generation algorithm."""
assert n <= m <= n * (n - 1), f"invalid number of arcs {m=}"
network = Network(nodes=range(n))
# Create optimal shortest path tree
m_neg = nb_neg_arcs(n, m, r)
m_neg_tree = nb_neg_tree_arcs(ξ, n, m, m_neg... | 1dd063a086304892fd6e8e88d0ca72ec4fd3265f | 52,538 |
import pathlib
def _check_if_python_module_exists(path: str) -> bool:
"""Check if an Earth Engine python module has been created from a JavaScript module in ee_extra.
Args:
path: str
Returns:
Whether the python module has been created.
"""
return pathlib.Path(_convert_path_to_ee_... | d5d57c63dff84a5d62945b64ece8ac7d6ba18804 | 52,539 |
def conv2d_bn(x,
filters,
num_row,
num_col,
padding='same',
strides=(1, 1),
name=None):
"""Utility function to apply conv + BN.
Arguments:
x: input tensor.
filters: filters in `Conv2D`.
num_row: height o... | fd317404f3625ea54e27ad15b64ae253b79374b4 | 52,540 |
def rho_basis(qubits):
"""
Generates a complete orthonormal basis composed of pure
states for the n-qubit density matrix.
:param qubits: number of qubits
:type qubits: int
:return: pure state spectral decomposition
:rtype: np.ndarray, float
"""
return np.array([i*np.conjugate(j).... | 3755613dcb3776e547d9219fde1652470e7c7f3d | 52,541 |
def formatted_value(value, array=True):
"""Format a given input value to be compliant for USD
Args:
array (bool): If provided, will treat iterables as an array rather than a tuple
"""
if isinstance(value, str):
value = '"{}"'.format(value.replace('"', '\\"'))
elif isinstance(value,... | 915e3b2952d43f45a7a75ab266802e22702600c8 | 52,542 |
import math
def estimate_highest_divisor(method, divisor, populations, seats):
"""
Calculates the estimated highest possible divisor.
:param method: The method used.
:type method: str
:param divisor: A working divisor in calculating fair shares.
:type divisor: float
:param populations: ... | e8b06564ed8bd13d1992cb8f498f5180cf27b5bd | 52,543 |
def growth_rate(x, steps=1):
""" calculates first differences"""
return x[steps:]-x[:-steps] | aebb957d53936b2d5a81754a505d3f9b42c7fdd4 | 52,544 |
def vit_base_patch16_224_in21k(num_classes: int = 21843, has_logits: bool = True):
"""
ViT-Base model (ViT-B/16) from original paper (https://arxiv.org/abs/2010.11929).
ImageNet-21k weights @ 224x224, source https://github.com/google-research/vision_transformer.
weights ported from official Google JAX i... | fe9ff82fad38ce04026f84322ec57689c97d24d2 | 52,545 |
def rigidbodies(traj,pdb_output=None,pdb_keep_all=False,pdb_filter=False,cluster_output=False,cutoff=None,ndomains=2,similarity_type='distance_fluctuation',similarity_binarize=None):
"""rigidbodies
Description
-----------
Rigid body decomposition through Ward clustering of a pariwise atom similarity ma... | 754af9f260d62d117425b4bb84994f52e58b4402 | 52,546 |
def swinnet50ts_256(pretrained=False, **kwargs):
"""
"""
kwargs.setdefault('img_size', 256)
return _create_byoanet('swinnet50ts_256', 'swinnet50ts', pretrained=pretrained, **kwargs) | 88c5d1a5be9f1da2cbf9a846b8b298beb003a557 | 52,547 |
import logging
def produce_segmentation(mtx, gamma, good_bins='default', method='modularity', max_intertad_size=3, max_tad_size=10000):
"""
Produces single segmentation (TADs or CDs calling) of mtx with one gamma with the algorithm provided.
:param mtx: input numpy matrix
:param gamma: parameter for s... | e78b56eba6e54e83f7cb45f92749cf92aa3bd58b | 52,548 |
def role_required(*roles):
"""Ensure that logged in user has one of the required roles.
Return 403 if the user doesn't have a required role.
Should be applied before the `@login_required` decorator:
@login_required
@role_required('admin', 'admin-ccs-category')
def view():
... | 7e739e4883ceb5083ec0d9958f197eded45fdc0a | 52,549 |
def ResNet50(inputs):
"""
Implementation of the popular ResNet50 the following architecture:
CONV2D -> BATCHNORM -> RELU -> MAXPOOL -> CONVBLOCK -> IDBLOCK*2 -> CONVBLOCK -> IDBLOCK*3
-> CONVBLOCK -> IDBLOCK*5 -> CONVBLOCK -> IDBLOCK*2 -> AVGPOOL -> TOPLAYER
Arguments:
input_shape -- shape of th... | 15982f1d6cbbfababcd65afb9b6458aea99336da | 52,550 |
import csv
def readCSV(path, datatype=float, realVal=True):
"""
Function to read from a CSV file in the given path. Rows of the CSV file are read in as list into an arrays.
Parameters
----------
path : str
path to the CSV file
Returns
-------
list
list containing the ... | f23f780a54af648deaece10bb5e2167d70411db4 | 52,551 |
import os
def get_prediction(image_location, model_path):
"""Generate a prediction of the biofuel source in an image
Args:
image_location: The absolute file path of the image
model_path: The absolute file path of the model weights file
Returns:
The class label of the biofuel dete... | 8fdcf607baaf1ffc6149b9797dfa83a835999508 | 52,552 |
import torch
def build_lm_1(state_dict_path):
"""
:meta private:
"""
model = SkipLSTM(21, 100, 1024, 3)
state_dict = torch.load(state_dict_path)
model.load_state_dict(state_dict)
model.eval()
return model | 157dc2c35520cfbc159324ea3f1594f55c550bc3 | 52,553 |
from typing import Union
from pathlib import Path
def _filename(path: Union[str, Path]) -> str:
"""Get filename and extension from the full path."""
if isinstance(path, str):
return Path(path).name
return path.name | 552655ff66ec6cd42b57ada6080df9dc34db1bd0 | 52,554 |
def stitch(probs, positions, decode_consensus_func):
"""Stitch predictions on chunks into a contiguous sequence.
Args:
probs: 3D array of predicted probabilities. no. of chunks X no. of positions in chunk X no. of bases.
positions: Corresponding list of position array for each chunk in probs.
... | 26773439bb7f1e8109791a2536bc075ed34e3387 | 52,555 |
from typing import Optional
from typing import Union
def sync(
*,
client: AuthenticatedClient,
form_data: FormBody,
multipart_data: MultiPartBody,
json_body: Json,
) -> Optional[Union[str, int]]:
""" POST endpoint """
return sync_detailed(
client=client,
form_data=form_dat... | 713a42fb1da92ce0fd25126701ae910cf4167018 | 52,556 |
def O2_sat(P_air, temp):
"""This equation returns saturaed oxygen concentration in mg/L. It is valid
for 278 K < T < 318 K
Parameters
----------
Pressure_air : float
air pressure with appropriate units.
Temperature :
water temperature with appropriate units
Returns
----... | 99014fee424140f01cecb38d742b97574e61ebd9 | 52,557 |
def new_version_available():
"""
Checks this version and checks the download site for a new version.
"""
return current_version() < available_version() | 5b42d7b8182a346783f27efad6e9ee45709d8eae | 52,558 |
def getAppModuleFromProcessID(processID: int) -> AppModule:
"""Finds the appModule that is for the given process ID. The module is also cached for later retreavals.
@param processID: The ID of the process for which you wish to find the appModule.
@returns: the appModule
"""
with _getAppModuleLock:
mod=runningTab... | a999667ecd79c38d3defe8ebf2f23f0ae13700cb | 52,559 |
import logging
def new_algo_logger():
"""
Create and return a logger for the simulation algorithms.
:return: Logger object from the logging library
"""
algo_logger = logging.getLogger("algo_logger")
algo_logger.propagate = False
formatter = logging.Formatter(ALGO_LOGGER_FORMAT)
strea... | b0d86d5c528702d624e68bd0cd27483e5c4bc41f | 52,560 |
def device(request):
"""Run a test case for all available devices."""
return request.param | 7547dae12266fbe6c2b9d3ec87dea20118f5e1e2 | 52,561 |
def _xls_eval_ir_test_impl(ctx):
"""The implementation of the 'xls_eval_ir_test' rule.
Executes the IR Interpreter on an IR file.
Args:
ctx: The current rule's context object.
Returns:
DefaultInfo provider
"""
src = ctx.file.src
runfiles, cmd = get_eval_ir_test_cmd(ctx, src)
... | 415eeebb78e21e2c8f2f9c4e14d968fbde317c00 | 52,562 |
def map_dimensions_to_integers(dimensions):
"""
FragmentSelector requires percentages expressed as integers.
https://www.w3.org/TR/media-frags/#naming-space
"""
int_dimensions = {}
for k, v in dimensions.items():
int_dimensions[k] = round(v)
return int_dimensions | e265e71912c6d582cf21d331767acca3511452f2 | 52,563 |
def get_source_title(meta_data):
"""
get source title for cards on web app
:return: string
"""
if 'source_title' in meta_data:
return meta_data['source_title']
crawler_used = meta_data["crawler_used"]
display_source = CRAWLER_TO_SOURCE_TITLE_LOOKUP[crawler_used]
return display_... | fbc8e8ac9d4c8c8c30f66d1f47d39f28c6724e36 | 52,564 |
from typing import Union
from typing import List
from typing import Tuple
def write_LUT_SonySPI3D(
LUT: Union[LUT3D, LUTSequence], path: str, decimals: Integer = 7
) -> Boolean:
"""
Writes given *LUT* to given *Sony* *.spi3d* *LUT* file.
Parameters
----------
LUT
:class:`LUT3D` or :cl... | 2702326cb92f487dced3c18c839be2ffdeeaf377 | 52,565 |
import os
def facebook_post_json(endpoint, json):
"""Makes a POST request to the specified endpoint with a JSON body"""
params = {"access_token": os.environ.get("FACEBOOK_PAGE_ACCESS_TOKEN")}
return facebook_base_post_json(endpoint, json, params) | ffeb0ebd9856f7145c6bcf7ecdc534fc2e845fed | 52,566 |
def padstr(x, align=8):
"""Pad string x with null bytes so it's a multiple of align bytes long.
Return bytes object"""
nbytes = len(x)
rem = nbytes % align
npadbytes = align - rem if rem else 0 # nbytes to pad with for 8 byte alignment
x = x.encode('ascii') # ensure it's pure ASCII, where each c... | ef23c8669c05afe333e524eae3969146a109e734 | 52,567 |
def rmsprop(step_size, gamma=0.9, eps=1e-8):
"""Construct optimizer triple for RMSProp.
Args:
step_size: positive scalar, or a callable representing a step size schedule
that maps the iteration index to positive scalar.
Returns:
An (init_fun, update_fun, get_params) triple.
"""
step_size = mak... | 23de7cda1335ca83917a7b66a716a02cd2b7cb03 | 52,568 |
def get_mail(monitoring: Monitoring):
"""
メールを取得する
Params
------
monitoring: Monitoring
監視設定オブジェクト
"""
config = Config()
run_time = RunTime(monitoring.search_word)
# メールボックスへの接続
credentials = (config.client_id, config.client_secret)
token_backend = FileSystemTokenBa... | 86c6793961dd7e62de6b8262b9f2630a60054027 | 52,569 |
def grpdelay(b, a=1, nfft=512, whole='none', analog=False, Fs=2.*pi):
#==================================================================
"""
Calculate group delay of a discrete time filter, specified by
numerator coefficients `b` and denominator coefficients `a` of the system
function `H` ( `z`).
... | af20fe32ab6e08480d35efbb7213cff2a12cba19 | 52,570 |
def request_recognizer(user_id, message):
"""
Выделяет команду из сообщения и передает на выполнение ответственному модулю
:param user_id: str or int
:param message: str
:return: tuple(str, tuple(str, bool))
"""
answer = "Не понял вас. Напиши 'помощь', чтобы узнать мои команды", ('text',)
... | 80b54303dde4576b286f4d81c82f5a46c581ec97 | 52,571 |
def unbox(boxed_pixels):
""" assumes the pixels came from box
and unboxes them!
"""
flat_pixels = []
for boxed_row in boxed_pixels:
flat_row = []
for pixel in boxed_row:
flat_row.extend(pixel)
flat_pixels.append(flat_row)
return flat_pixels | d74741a206448273330b866d8ec045d59dea02fb | 52,572 |
from re import T
def log_multinomial(x, p, eps=0.0):
"""
Compute log pdf of multinomial distribution
.. math:: \log p(x; p) = \sum_x p(x) \log q(x)
where p is the true class probability and q is the predicted class
probability.
Parameters
----------
x : Theano tensor
Va... | 8041827ca49bbebc7c3e68bc714695884d28a6c5 | 52,573 |
import re
def parse_human_input(file_size):
"""Parse an input in human-readable format and return a number of bytes."""
multipliers = {
"K": 10 ** 3,
"M": 10 ** 6,
"G": 10 ** 9,
"T": 10 ** 12,
"Ki": 2 ** 10,
"Mi": 2 ** 20,
"Gi": 2 ** 30,
"Ti": 2 ... | e88ed389d2a71f642f12438caabc14d8c7b21e81 | 52,574 |
def check_internet_connection(ad, ping_addr):
"""Validate internet connection by pinging the address provided.
Args:
ad: android_device object.
ping_addr: address on internet for pinging.
Returns:
True, if address ping successful
"""
droid, ed = ad.droid, ad.ed
ping = d... | b63d4e2e2dcaa57afa90163edca2aff8552a97b6 | 52,575 |
def create_frozen_request(sheet_id, rows=None, cols=None):
"""
Create v4 API request to freeze rows and/or columns for a
given worksheet.
"""
grid_properties = {}
if rows is not None and rows >= 0:
grid_properties["frozen_row_count"] = rows
if cols is not None and cols >= 0:
... | 0eeeebd636ff31cd5a0a31aee81701243edbbd3e | 52,576 |
from pathlib import Path
def create_path():
"""function to create traffic monitor directory"""
data_store_path = '~/Documents/TrafficMonitor'
path = Path(data_store_path).expanduser()
path.mkdir(parents=True, exist_ok=True)
return str(path) | 2aef318d62a2f4a19879ef87d62af48247afdcf7 | 52,577 |
def search(request):
"""
Search page view
"""
try:
query = request.GET.get('query')
if len(query) < 3:
messages.warning(request, "Search query must be at least 4 characters.")
query = "NONE"
except:
query = "NONE"
cards = Card.objects.filter(nam... | 0589ec1fe62b624221eb1db4b82ece3e79159167 | 52,578 |
def gauss_function(x, a, x0, sigma):
"""
Gaussian
_________
Arguments:
x (float or float array) - argument
a (float) - amplitude
x0 (float) - mathematical expectation
sigma (float) - standard deviation
__________________________________
Returns:
Gauss function by formula
... | 3178d2e187a8f0c0c5dcbc2c79ab83c368251f76 | 52,579 |
import requests
import random
def bingimage(text, bot):
"""<query> - returns the first bing image search result for <query>"""
api_key = bot.config.get("api_keys", {}).get("bing_azure")
# handle NSFW
show_nsfw = text.endswith(" nsfw")
# remove "nsfw" from the input string after checking for it
... | 372bbb2192c547405f96b1c2b7393600ff2e30e1 | 52,580 |
def convert_to_axes(axes, container=tuple):
"""Convert `obs` to the list of obs, also if it is a
:py:class:`~ZfitSpace`. Return None if axes is None.
Raises
TypeError: if the axes are not int
"""
if axes is None:
return axes
axes = convert_to_container(value=axes, container=cont... | 12cdcda5d989ec2ce53e71d8a1b6a93a218d0a7d | 52,581 |
def aumentar(n=0, p=0, formato=False):
"""
Somar porcentagem
:param n: número a ser somado
:param p: porcentagem a ser somada
:param formato: (opicional) mostrar o moeda
:return: resultado
"""
n = float(n)
resultado = n + (n * p / 100)
return moeda(resultado) if formato else resu... | 65af169a0ab7d33450e698e4d303e09e0f09dadf | 52,582 |
import math
def calculate_threshold_value(q: int,
t: int,
p: int,
lmbda: int,
w: float,
lower_val: float,
upper_val: float,
... | 0fc60fb8308b8f75a80eb2b6a2940a61f6e421d6 | 52,583 |
import pandas as pd
import pbio.misc.parallel as parallel
def _parse_gtf_group(rows):
""" This is a helper function for parsing GTF attributes from a data frame.
It is not intended for external use.
"""
res = parallel.apply_df_simple(rows, parse_gtf_attributes)
res = pd.DataFrame(res)
retu... | 24486ec6249714bf736258b4acbc59f11667b1a8 | 52,584 |
def z_levels(fid, x, y, variable, n_levels, n_frames, t_idx,
symflag, n_lev_auto, n_dec, n_seg, avleng):
"""
list(float) = zlevels(fid, variable, n_levels, n_frames, t_idx,
symflag, n_lev_auto, n_dec, n_seg, avleng)
"""
z_levs_auto = auto_z_levels(fid, x, y, variab... | b9cd63defbe776d2ab451d3ceec557c88c7913d1 | 52,585 |
from typing import Union
import io
from typing import Optional
def getint(
string: Union[io.StringIO, str], key: str, section: Optional[str] = None
) -> Union[int, None]:
"""get option's value in `int` type"""
val = get(string, key, section)
if val:
return int(val) | 6127e5fbaefb753ddac6312d8badc18815e1c7e1 | 52,586 |
def fec_old_patch():
"""
Further Education College UK RSF patch generated with the old
`rsfcreate.py` script.
"""
with open("tests/fixtures/fec_old_patch.rsf") as handle:
return handle.read().splitlines() | 41f382e1b31be2633a0d2c352e352f8926a8bae0 | 52,587 |
def get_n_pixels(bad_bin_mask, window=10, ignore_diags=2):
"""
Calculate the number of "good" pixels in a diamond at each bin.
"""
N = len(bad_bin_mask)
n_pixels = np.zeros(N)
loc_bad_bin_mask = np.zeros(N, dtype=bool)
for i_shift in range(0, window):
for j_shift in range(0, window)... | 564d1e40cbd3053bcb170e90496e2efc5418808e | 52,588 |
import argparse
import sys
def argparser():
"""parse command line arguments"""
parser = argparse.ArgumentParser(prog='impsamp')
parser.description = 'MT decoding by importance sampler'
parser.formatter_class = argparse.ArgumentDefaultsHelpFormatter
parser.add_argument("proxy",
... | 888b0fd5eb16c395431cf93f6ebc181cfea309bc | 52,589 |
def ruleset_refresh(p_engine, p_username, rulesetname, envname):
"""
Refresh ruleset on the Masking engine
param1: p_engine: engine name from configuration
param2: rulesetname: ruleset name
param3: envname: environment name
return 0 if added, non 0 for error
"""
return ruleset_worker(p_... | 97d053a3164bde44384e55e99108a901bdf83b04 | 52,590 |
from typing import Any
def str_or_raise(value: Any) -> str:
"""Return string or raise exception."""
return enforce_type(str_or_none(value), str) | 63b77bb8d75879ab45d9182aef02ebf8785d8a17 | 52,591 |
def trima(close, timeperiod=30):
"""Triangular Moving Average 三角移动平均线
the triangular moving average (TMA) is a technical indicator that
is similar to other moving averages. The TMA shows the average
(or mean) price of an asset over a specified number of data
points—usually a number of price bars. H... | ecf64f24db7f09070c549528d78e33122507a1f7 | 52,592 |
def CheckCardinalities(*cardinality):
"""Checks cardinality values for compatibility. None is treated as a wild
card that matches all cardinalities. It returns the resulting cardinality,
or None if all are wild cards. If they don't match then a ProcessingError
is raised."""
cReturn = None
for... | a320312eb117749133045787364b9cb388137088 | 52,593 |
async def index_route(request):
""" Redirect to the dashboard. """
return response.redirect('/jobs') | ba5f1a341fe5afef5247e0feb473e8a4c2405680 | 52,594 |
def make_format_plugin_table(group="waveform", method="read", numspaces=4,
unindent_first_line=True):
"""
Returns a markdown formatted table with read waveform plugins to insert
in docstrings.
>>> table = make_format_plugin_table("event", "write", 4, True)
>>> print(tab... | 74614844b0f7445af42d0eb2978599a36b79ed85 | 52,595 |
def create_gsheet(gc, eid, program_db):
"""
Creates a Google sheet for the program.
:param gc: The `gspread.Client` object. Should have called
`gc = authorize_google_sheets()` before passing into this function.
:type gc: `gspread.Client` object
:param eid: The eid of the program.
:type... | 6134250dd2247a8abbcec6fa72363c1f0c6634cf | 52,596 |
def probability_of_selection(spt, snr):
"""
probablity of selection for a given snr and spt
"""
ref_df=SELECTION_FUNCTION.dropna()
#self.data['spt']=self.data.spt.apply(splat.typeToNum)
interpoints=np.array([ref_df.spt.values, ref_df.logsnr.values]).T
return griddata(interpoints, ref_df.tot_... | 562ffbe0dc280e4544af32daa94a07b3320c7207 | 52,597 |
def entryPoint(coursesCompleted, coursesDesired, startSem):
"""
This is the entry point function for the ILP scheduler.
coursesCompleted: a list of courses that the person already has credits for
coursesDesired: a list of courses that the person wants to take.
startSem: either 0 or 1 indicating wet... | 96a766f7ea756e90b289ef2c14cc7b78ae0363d0 | 52,598 |
def render(template, context=None, **kwargs):
"""
Return the given template string rendered using the given context.
"""
renderer = Renderer()
return renderer.render(template, context, **kwargs) | b5220cdc10cc55346bb0593e60bd5d7e80b63883 | 52,599 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.