content stringlengths 35 762k | sha1 stringlengths 40 40 | id int64 0 3.66M |
|---|---|---|
from datetime import datetime
def get_remaining_submission_for_a_phase(
user, challenge_phase_pk, challenge_pk
):
"""
Returns the number of remaining submissions that a participant can
do daily, monthly and in total to a particular challenge phase of a
challenge.
"""
get_challenge_model(c... | 23728989736086e45d4d8201bd7640510edce568 | 3,606,600 |
def _get_more_basis_columns(A, basis):
"""
Called when the auxiliary problem terminates with artificial columns in
the basis, which must be removed and replaced with non-artificial
columns. Finds additional columns that do not make the matrix singular.
"""
m, n = A.shape
# options for inclu... | 360c4999771e26987c0d50584f095da9b7937671 | 3,606,601 |
def generate_peptide(model, alphabet_list, network_input, n_alphabets):
""" Generate peptide from the neural network based on a sequence of amino acids """
# pick a random sequence from the input as a starting point for the prediction
alphabets = sorted(set(alphabet_list))
start = np.random.ra... | 65a6c64ac20fd15cc260f3ee090503ba7a6fc420 | 3,606,602 |
def polyfit(dates, levels, p):
"""Returns the polynomial object of a degree p least-squares polynomial fit to the dates, levels input."""
dates_float = matplotlib.dates.date2num(dates)
d0 = -1*dates_float[0]
p_coeff = np.polyfit(dates_float + d0, levels, p)
poly = np.poly1d(p_coeff)
return po... | 1c27110e1e42f43b71859fecb11ed8d489e4bc9b | 3,606,603 |
def spm_hrf(RT, P=None, fMRI_T=16):
""" python implementation of spm_hrf
see spm_hrf for implementation details
% RT - scan repeat time
% p - parameters of the response function (two gamma
% functions)
% defaults (seconds)
% p(0) - delay of response (relative to onset) 6
% p(1... | 2bb8f11a5f2b3be3852be2b6c9fc63ff75964973 | 3,606,604 |
import operator
def sort_load_list_by_time(load_list):
"""Given the standard load list return a list orderd by time
The list contains a tuple of the load_id and the actual load_set
"""
return sorted(load_list, key=operator.itemgetter(1)) | 1ae00f8ffe0cf4ef7ab899b9e6d3c9a0051c7e91 | 3,606,605 |
def product_moment_corr(x, y):
""" Product-moment correlation for two ndarrays x, y """
r, n = _product_moment_corr(x, y)
# From scipy.stats.pearsonr:
# As explained in the docstring, the p-value can be computed as
# p = 2*dist.cdf(-abs(r))
# where dist is the beta distribution on [-1, 1] wi... | ca54c6aa218553878ced0d500549c8bf370a904f | 3,606,606 |
import functools
def singleton(cls):
""" Singleton decorator """
@functools.wraps(cls)
def wrapper():
if not wrapper.instance:
wrapper.instance = cls()
return wrapper.instance
wrapper.instance = None
return wrapper | 7d99cf00603ee05be47b4579e9671c246a7b793f | 3,606,607 |
def is_blackout(date):
"""Returns true if the date falls in the Resource Blackout dates."""
return ResourceBlackoutDate.objects.filter(date=date).exists() | 86de14f2c5ba26ccb5c78aea501ff2ad5d139ec8 | 3,606,608 |
def mseuclidean(u, v, V):
"""
Returns the standardized Euclidean distance between two n-vectors
``u`` and ``v``. ``V`` is an m-dimensional vector of component
variances. It is usually computed among a larger collection
vectors.
Parameters
----------
u : ndarray
An :math:`n`-dime... | 76b518cd6cfe97eb8820c81f1d4c15a6833bcf9c | 3,606,609 |
import os
def get_unused_block_devices(devices, domain_disks):
"""
Get the set of block devices that are neither used by the host nor
assigned to a libvirt domain.
Parameters
----------
devices: dict
The list of block devices.
domain_disks: dict
The list of block devices o... | d2e0097d4f9b8c8d83ec925f01c3133ec6318813 | 3,606,610 |
def crop_to_ratio(im, desired_ratio=4 / 3):
""" Crop (either) the rows or columns of an image to match (as best as possible) the
desired ratio.
Arguments:
im (np.array): Image to be processed.
desired_ratio (float): The desired ratio of the output image expressed as
width/... | dd2301708aa514b2d9b87758ce38d7bd9f9d874c | 3,606,611 |
def handle_rewind_data_button(n, session_id):
"""
When the rewind button is clicked, reset the last drf data point seen to the beginning
and clear the spectrogram waterfall plot
"""
if n and n[0] < 1: raise dash.exceptions.PreventUpdate
cfg.redis_instance.set(f"{session_id}:last-drf-id", "0-0", ... | c9a3fa625ad69cacab2fe0259d2423796cf4f293 | 3,606,612 |
def generate_weights(rows, cols, zeros=False):
"""
Generates a Matrix of weights according to the
specified rows and columns
"""
if zeros:
return np.zeros((rows, cols))
return np.random.rand(rows, cols) | ab08d85989d3f3c15049b452ba9070f27d433066 | 3,606,613 |
import json
def post(url, data):
"""
发送post请求
:param url: str, url地址
:param data: dict, post请求的查询数据
:return: str, 请求返回的数据
"""
data = bytes(json.dumps(data), encoding="utf-8")
request_obj = request.Request(url, headers={'Content-Type': 'application/json'})
with request.urlopen(requ... | 814951a9b8b860f8b20f3a32be12018f7f943afd | 3,606,614 |
async def async_setup_entry(hass: HomeAssistantType, entry: ConfigEntry) -> bool:
"""Set up Paradox from a config entry."""
if DOMAIN not in hass.data:
hass.data[DOMAIN] = {}
module = ParadoxDevice(hass, entry)
if not await module.async_setup():
return False
if not module.available... | 92852a4164f181926e5c93b745d0df667171a4b2 | 3,606,615 |
def cot(x):
"""Returns a new Var with cotangent applied to the input Var x
:param x: object on which cotangent is applied, required
:type x: AD_Object.Var
:return: new object with cotangent applied to input
:rtype: AD_Object.Var
:example:
>>> from autodiff.AD_BasicMath import cos
... | 9ebca0d35c5023a0a8eedc76c97d9c76a010f419 | 3,606,616 |
def grompp_npt(job):
"""Run GROMACS grompp for the npt step."""
npt_mdp_path = "npt.mdp"
msg = f"gmx grompp -f {npt_mdp_path} -o npt.tpr -c em.gro -p init.top --maxwarn 1"
return msg | 7afdf17586250a62106c67b2594d1aa057fef09e | 3,606,617 |
def set_figure_title_anchor(obj_title, anchor_params):
# type: (object, Dict) -> object
"""Set the anchor properties of the figure title
Args:
obj_title (object): a matplotlib Text object
anchor_params (dict): anchor parameter dict
Returns:
same as input obj_title
"""
if... | 24730bf8305b36ce67ca673158854e409fa60a78 | 3,606,618 |
import math
def pad_image(image, size=(352, 512)):
"""Helper function to pad image to size (height, width)"""
pad_h = max((size[0] - image.shape[0]) / 2, 0)
pad_w = max((size[1] - image.shape[1]) / 2, 0)
pad_h = (math.floor(pad_h), math.ceil(pad_h))
pad_w = (math.floor(pad_w), math.ceil(pad_w))
... | 2f2ce22db96499778899e33e9f1bf94897502a39 | 3,606,619 |
def uri_leaf(uri):
"""
Get the "leaf" - fragment id or last segment - of a URI. Useful e.g. for
getting a term from a "namespace like" URI.
>>> uri_leaf("http://purl.org/dc/terms/title") == 'title'
True
>>> uri_leaf("http://www.w3.org/2004/02/skos/core#Concept") == 'Concept'
True
>>> ur... | 3045806ac56124331c58b6daffb5c1b5c202c0eb | 3,606,620 |
def create_single_item_trie(in_dict, out_file=""):
"""Creates a marisa trie from the input dictionary. We assume the
dictionary has string keys and integer values.
Args:
in_dict: Dict[str] -> Int
out_file: marisa file to save (useful for reading as memmap) (optional)
Returns: marisa tr... | b9c40430b356866cdd76b88f669bb81c609f3660 | 3,606,621 |
def reader_conf(path: str, encoding: str = 'UTF-8') -> dict:
"""读取配置文件
[capitalize]
a
b
:param path: 配置文件路径
:param encoding: 文件编码
"""
cx = {}
with open(path, encoding=encoding)as fp:
for data in fp:
data = data.strip()
if data.startswith('[') and data... | bad9774cd302605061b26d65e3c0bfe26a1f6984 | 3,606,622 |
def connect_leaf_device_client():
"""
connect the device client for the leaf device and return the client object
"""
current_config = runtime_config.get_current_config()
client = adapters.LeafDeviceClient()
client.connect(
current_config.leaf_device.transport,
current_config.leaf... | d3f4122ef49b6971739bd7e4e484cd8b8ad4a37a | 3,606,623 |
def setup_tent(model, args):
"""Set up tent adaptation.
Configure the model for training + feature modulation by batch statistics,
collect the parameters for feature modulation by gradient optimization,
set up the optimizer, and then tent the model.
"""
model = configure_model(model)
params,... | 0027c0566b25631a9db37300f3c53d344db4b681 | 3,606,624 |
def reshape_spectrum_lines(energy, weights=None, normalize=True, **others):
"""
Args:
energy(num or array): source energies
shape = [nSource x] nSourceLines
weights(Optional(num or array): source line weights
shape= [nSource x... | 4499d77c569e6c6cc996313beee7c0a9cc1da319 | 3,606,625 |
import argparse
import sys
import getpass
import warnings
def console_main():
"""
Console-only: Main functions, called from CLI entry point.
:return int: 0 on success, 1 on failure.
"""
if argparse is None:
print >> sys.stderr, "`argparse' module is not available. CLI functions are disable... | d80df47b637f97a83ccd29d82cae6dddb01337b0 | 3,606,626 |
def L1_Norm(arr: _Array) -> float:
"""Compute the L_1 norm of input vector `x`.
This implementation is generally faster than np.norm(arr, ord=1).
"""
return _np.abs(arr).sum(axis=0) | 1a8797f58d60abf7f228e0f9be4edebafd4494b3 | 3,606,627 |
def solution(source, destination):
"""
Identifies shortest distance a knight would have to move between two points of a chess board.
Accepts a source cell number and a destination cell number
Parameters:
source: int
destination: int
Returns:
int: Shortest number of levels traverse... | b23aaaa2747ed47ed7c02fde76856ef650eef1cd | 3,606,628 |
import yaml
def load_yaml_config(filename):
"""Load a YAML configuration file."""
with open(filename, "rt", encoding='utf-8') as file:
config_dict = yaml.safe_load(file)
return config_dict | 771dbf8fdaca1575bc9bdb472d6aa1405c689e7a | 3,606,629 |
def getConvolutionOutputShape(tensor_shape, conv):
"""
compute the output shape of a convolution given the input tensor shape
args:
tensor_shape (tuple): input tensor shape (B x C x D)
conv (nn.Module): convolution object
returns:
output_shape (tuple): expected output shape
"... | d7e2a0d8806a93af10ae3fac9bbc9132cf7d615f | 3,606,630 |
def shell_Green_grid_Arnoldi_Mmn_step(n,k, invchi, rgrid,rsqrgrid,rdiffgrid, RgMgrid, ImMgrid, unitMvecs, Gmat, plotVectors=False):
"""
this method does one more Arnoldi step, given existing Arnoldi vectors in unitMvecs
the last entry in unitMvecs is G*unitMvecs[-2] without orthogonalization and normalizati... | 2c07c08a1ed60a001f7dde52dd9c2db4adb704af | 3,606,631 |
def prepare_data(data, variables, bg_vars, nice_names, labels, nothing_string):
"""Create data for a distplot.
Args:
data (pd.DataFrame): The dataset that contains variable and background_variables.
variables (list): List of variables whose distributions are visualized. Can be
categ... | 79ae6e8c08e59058063705ddea0d331ea2f1eb97 | 3,606,632 |
def run_rod(smooth = 0.001, dirname = 'task1/val/'):
"""
use_set: validation or test
"""
#if use_set == 'val':
# dirname = 'task1/val/'
#elif use_set == 'test':
# dirname = 'task1/test/'
#else:
# dirname = ''
# read ground truth
all_sen, features, labels, docs = uti... | 028248b84b5aaaebbd78d3c09023c4153281f387 | 3,606,633 |
def on_leafs(y_leafs,
grouping_name: str,
is_leaf_list: bool) -> list:
""" Parse all the 'leaf' or 'leaf-list' elements
Args:
y_leafs: reference to all 'leaf' elements
grouping_name: if YANG entity contain 'uses',
this argument represent the... | cde3ee003c180370af0ea506c5dba05fe0e8e980 | 3,606,634 |
def preprocessor(accepts, exports, flag=None):
"""Decorator to add a new preprocessor"""
def decorator(f):
preprocessors.append((accepts, exports, flag, f))
return f
return decorator | c579934724612c8788ad9e50acb529fae696977d | 3,606,635 |
import uuid
def build_request_body(method, params):
"""Build a JSON-RPC request body based on the parameters given."""
data = {
"jsonrpc": "2.0",
"method": method,
"params": params,
"id": str(uuid.uuid4())
}
return data | 372df70bd17e78f01de5f0e537988072ac9716cc | 3,606,636 |
import wave
import json
def recognize(model, wav_file_path):
"""
Speech to text recognizer for russian speech using vosk models
path to russian vosk model should be configured in config.py file
"""
with wave.open(wav_file_path, "rb") as wf:
if wf.getnchannels() != 1 or wf.getsampwidth() !... | c51ab23bd3f170e4dd48c4f2b1b282b0320b14ba | 3,606,637 |
def read_config(fname):
"""
Opens and reads in the config file in its most raw form.
Creates a dictionary of dictionaries that contain the string result
Args:
fname: Real path to the config file to be opened
Returns:
config: dict of dicts containing the info in a config file
"""... | 88248fc9b17f1d551bbfd0602757fddd85c3d67f | 3,606,638 |
import hashlib
def get_content_md5(fileobj):
"""Get Content-MD5 value
All content will be read from the current position to the end of the
file. The file will be left open with its seek position at the end
of the file.
:param fileobj: A file-like object.
:returns: RFC-1864-compliant Content-... | f7612ad1302dc7c9ecac6deeac4dcb9acdc9d62c | 3,606,639 |
def cosine_similarity_loss(x1, x2, labels):
""" cosine 相似度损失
Examples:
# >>> logits = torch.randn(5, 5).clamp(min=_EPSILON) # 负对数似然的输入需要值大于 0
# >>> labels = torch.arange(5)
# >>> onehot_labels = F.one_hot(labels)
#
# # 与官方结果比较
# >>> my_ret = negative_log_likelih... | ad9e32d2496e77d42e87bafc3550f727a39edd51 | 3,606,640 |
def line_count(text_field: bytes, is_double_height: bool) -> int:
"""Returns the number of lines separated by one or more newline characters
in the TF field `text_field`
"""
count = 0
was_eol = False
for c in text_field:
if _is_newline_code(c):
if is_double_height:
if was_eol:
w... | 4ebf186b08b1591e81a7d9493e50b071e7a9d1c9 | 3,606,641 |
from typing import Optional
import ntpath
import sys
import re
def pathscrub(dirty_path: str, os: Optional[str] = None, filename: bool = False) -> str:
"""
Strips illegal characters for a given os from a path.
:param dirty_path: Path to be scrubbed.
:param os: Defines which os mode should be used, ca... | b57a0be8b3c19fb47a794a9fc131c16c80a12fae | 3,606,642 |
def part1(input_data):
"""
>>> part1(["939","7,13,x,x,59,x,31,19"])
295
"""
timestamp = int(input_data[0])
bus_ids = input_data[1].split(',')
# Ignore bus_ids with 'x'
bus_ids = map(int, filter(lambda bus_id: bus_id != 'x', bus_ids))
# (id, time_to_wait)
# last_busstop = timestam... | 99c1928c5833f3c9773a28323f2bd2a903f626f3 | 3,606,643 |
from dronekit.mavlink import MAVConnection
def connect(ip,
_initialize=True,
wait_ready=None,
timeout=30,
still_waiting_callback=default_still_waiting_callback,
still_waiting_interval=1,
status_printer=None,
vehicle_class=None,
... | 2ec36b5d7d2c766ebb1a3856ce8abc606432b3bf | 3,606,644 |
def create(movie_id, country_id, **options):
"""
creates a new movie 2 country record.
:param uuid.UUID movie_id: movie id.
:param uuid.UUID country_id: country id.
:keyword bool is_main: is main.
:raises ValidationError: validation error.
"""
return get_component(RelatedCountriesPac... | fbe2795d0f239371a6d760a5c26778e170839eb4 | 3,606,645 |
import uuid
def read_bootid():
"""
Mocks read_bootid as this is a Linux-specific operation.
"""
return uuid.uuid4().hex | 02ef132a4aa157a4c111bf8938a4a3716a9c2f29 | 3,606,646 |
import os
def validate_dark_current(results, det_names):
"""Validate and persist dark current results."""
run = siteUtils.getRunNumber()
missing_det_names = []
for det_name in det_names:
raft, slot = det_name.split('_')
file_prefix = make_file_prefix(run, det_name)
results_file... | 6f645221989c8ddcef8c2516af437af0ab13ac18 | 3,606,647 |
def make_grid_point_weight(reference_point, MO,
approach_code=1, table_code=13,
title='', subtitle='', label='',
superelement_adaptivity_index='') -> None:
"""creates a grid point weight table"""
Mtt_ = MO[:3, :3]
Mrr_ = MO[3:,... | 20d8194c595ca51ddd1777b82c00c22c692a8df3 | 3,606,648 |
import torch
def total_correlation(z, mu, logvar):
"""Estimate total correlation in a batch.
Compute the expectation over a batch of:
E_j [log(q(z(x_j))) - log(prod_l q(z(x_j)_l))]
We ignore the constant as it does not matter for the minimization. The constant should be
equal to (n_dims - 1) * ... | ffa518d09de672a894d088d8b9ac0a9689135bc8 | 3,606,649 |
def list_group(flatten_list, offset_list):
"""list_flatten的逆操作"""
pos_lists = []
for offset in offset_list:
pos_lists.append(flatten_list[offset[0] : offset[1]])
return pos_lists | 6ae7f52d267ea682c704a4a494bdfb63f8ccf23a | 3,606,650 |
async def get_balance(user: str) -> int:
""" Returns the balance for a user. """
async with aiosqlite.connect("./balance.db") as db:
db.row_factory = aiosqlite.Row
await _create_if_not_exists(db, user)
async with db.execute("SELECT * FROM balance WHERE username = ?", [user]) as cursor:
... | bdb48e2038be1aeb10c5f64d8fe5f60a8805eb8a | 3,606,651 |
def get_auth0_user_key_info(is_authenticated):
"""Getting users permission on their first launch
At the same time, also update the users_permissions table
as we want to keep the users_permissions table up to date
for the dashboards.
"""
if is_authenticated:
app.logger.info(
f... | b01c731bac3665636a6ce7af255bd5dc86584cf5 | 3,606,652 |
def main(*args):
"""Main function."""
BenchBuild.subcommand('bootstrap', BenchBuildBootstrap)
BenchBuild.subcommand('config', BBConfig)
BenchBuild.subcommand('container', cli.BenchBuildContainer)
BenchBuild.subcommand('experiment', BBExperiment)
BenchBuild.subcommand('log', BenchBuildLog)
B... | 0a97e7a2fda2370b2dccc03ebc6e8748cbcb6d51 | 3,606,653 |
from sys import path
def preprocess(index, crop=(0.1, 0.15)):
"""
Preprocess data directly from file.
Args:
index (ndarray): Frame range to extract, must be contiguous.
crop (tuple): Timestamp range for coarse croping.
Returns:
(tuple): tuple containing:
t (nd... | ae026a2f6222e6a3ec3b046faa6680149e86a002 | 3,606,654 |
def exporter():
"""Create exporters."""
serving_input_fn = tf.estimator.export.build_raw_serving_input_receiver_fn(
features=dict(
block_ids=tf.placeholder(tf.int32, [None, None]),
block_mask=tf.placeholder(tf.int32, [None, None]),
block_segment_ids=tf.placeholder(tf.int32, [None... | ca4effcb35d1d95d153c7a5fb8debeddd502e065 | 3,606,655 |
import numpy
def normalized(vector):
"""
Get unit vector for a given one.
:param vector:
Numpy vector as coordinates in Cartesian space, or an array of such.
:returns:
Numpy array of the same shape and structure where all vectors are
normalized. That is, each coordinate compon... | 424595a59e52ed8b328a629b28dd0206c599484f | 3,606,656 |
def getBoxesMidpoint(box):
"""
takes in normalized coordinates of the 800x600 screen. coordinates are xmin,ymin,xmax,ymax
returns a tuple of the midpoint
"""
#denormalize them
normalized_coord = np.array([box[0]*806,box[1]*629,box[2]*806,box[3]*629],dtype=np.float32)
#offset from the origin
... | aaadb54af0a24ab52e977a8968e258c79c66e75a | 3,606,657 |
import os
import tempfile
import tarfile
import packaging
import sys
import glob
import shutil
import urllib
def download_version(version, url=None, verbose=False, target_dir=None):
"""
Download, scylla relocatable package tarballs.
"""
try:
if os.path.exists(url) and url.endswith('.tar.gz'):
... | 344d7c061e7518d004b9fe3c4648d19679ea2d14 | 3,606,658 |
def sample_conditional_random(generator, m, n, **kwargs):
"""
Sample `m * n` points from condition space completely randomly.
"""
return generator.condition_distribution.sample(m * n).eval() | bc50e32e47bffe10c11df02cf365c5396b722d4a | 3,606,659 |
import pathlib
def my_read_image(img_path):
"""
Return a loaded image according to the input path.
Note that the color channels are sorted as RGB order.
Args:
img_path: pathlib.Path
File path of an image you want to load.
Returns: ndarray
Loaded image sorted as RGB ord... | 632f9d9954168588cb98757f7f3c0021ec538692 | 3,606,660 |
import asyncio
def rpc(func):
"""
A decorator used to indicate an RPC.
All @rpc methods if explicitly called via a request message must have
node.identifier as the first argument.
All @rpc methods return a 2-tuple: (node_identifier, response)
The node_identifier is consumed by kademlia to u... | f54ee5897f73c6407c38716b1b15dbfa31ccbf6e | 3,606,661 |
def low_cut_filter(x, fs, cutoff=70):
"""Low cut filter
Parameters
---------
x : array, shape(`samples`)
Waveform sequence
fs: array, int
Sampling frequency
cutoff : float, optional
Cutoff frequency of low cut filter
Default set to 70 [Hz]
Returns
------... | 2e936503e1a719575e11ec2a92147d2f85f366bc | 3,606,662 |
import json
import base64
def lambda_handler(event, context):
"""
Lambda Handler for Image Processing logic.
"""
#Load the event
print("My event: {}\n".format(event))
try:
event = json.loads(event['body'])
except:
event = event['body']
# Content image pre-pro... | 7d25d12ac20fb1530423aced98c438166959a885 | 3,606,663 |
def empty_like(a, dtype=None):
""" alias for empty(a.axes, dtype=a.dtype)
See also
--------
empty, ones_like, zeros_like, nans_like
>>> a = empty([('time',[2000,2001]),('items',['a','b','c'])])
>>> b = empty_like(a)
>>> b.fill(3)
>>> b
dimarray: 6 non-null elements (0 null)
0 /... | 84fda4883556ddad085949bf145f2ee3c4ec7df2 | 3,606,664 |
import torch
def fetch_optimizer(lr, wdecay, epsilon, num_steps, params):
""" Create the optimizer and learning rate scheduler """
optimizer = torch.optim.AdamW(params, lr=lr, weight_decay=wdecay, eps=epsilon)
scheduler = torch.optim.lr_scheduler.OneCycleLR(optimizer, lr, num_steps+100,
pct_start... | e6d028f4adf58c303e1e7f0cb0b5233cf4f6026c | 3,606,665 |
import os
import json
import re
def read_tags(tag):
"""
read a list of tags, either from a json file or a list of comma
separated key=value pairs.
"""
if os.path.isfile(tag):
with open(tag) as fp:
tags = json.load(fp)
elif os.path.isfile(os.path.join(os.path.expand... | 9cb93630a6eda5081f7d91682c5fbfdfda8fbcbd | 3,606,666 |
import random
def calc_rpn(C, img_data, width, height, resized_width, resized_height, img_length_calc_function):
"""(Important part!) Calculate the rpn for all anchors
If feature map has shape 38x50=1900, there are 1900x9=17100 potential anchors
Args:
C: config
img_data: augmented image data
width: origi... | 9510f1652342830515d8eafe7c4367e729d39c6e | 3,606,667 |
def actionify(trip_message, vehicle_message, timestamp):
"""
Parses the trip update and vehicle update messages (if there is one; may be None) for a
particular trip into an action log.
"""
# If a vehicle message is not None, the trip is already in progress.
inp = vehicle_message is not None
... | 591a239d2a732a5e40188324ff7b4e9986565aae | 3,606,668 |
def closest_index(x, a):
"""
x: value
a: array
"""
return np.argmin(np.abs(x - a)) | 0c06f75d1530f4b7f511209c4ee039f3e2ce51bb | 3,606,669 |
def calc_darcy(pipe_diameter_m, reynolds, pipe_roughness_m):
"""
Calculates the Darcy friction factor [Oppelt et al., 2016].
:param pipe_diameter_m: vector containing the pipe diameter in m for each edge e in the network (e x 1)
:param reynolds: vector containing the reynolds number of flows ... | b5e7b4123d1cb1b1c357ec40402ef59ddfd06740 | 3,606,670 |
def makeCube():
""" Create a Cube
Credits: https://github.com/danginsburg/webgl-brain-viewer/blob/master/common/esShapes.js
"""
vertices = np.array( [
[-0.5, -0.5, -0.5],[-0.5, -0.5, 0.5],[0.5, -0.5, 0.5],[0.5, -0.5, -0.5],
[-0.5, 0.5, -0.5],[-0.5, 0.5, 0.5],[0.5, 0.5, 0.5],[0.5, 0.... | 96d788d95ceba0bac1ce13677745610145aeae59 | 3,606,671 |
def bv_maxlikelihood_irl(
x,
xtr,
phi,
rollouts,
weights=None,
boltzmann_scale=0.5,
qge_tol=1e-3,
nll_only=False,
):
"""Compute the average rollout Negative Log Likelihood (and gradient) for ML-IRL
This method is biased to prefer shorter paths through any MDP.
TODO ajs 29/O... | 6785ca5938be2fdf7cb293b6304bdd4983d9713a | 3,606,672 |
def try_create(model, where):
"""Try to create an object in the database and return it if successful.
Args:
model (Model): DB model class to instantiate.
where (dict): Values for fields to be populated in the new instance.
Returns:
A new instance of the Model if creation was successf... | 1044ae5b5fa23b3c1e860e75d7643565b1407e7a | 3,606,673 |
def load_user_data(filename, **kwargs):
"""
Load `filename`, template in `kwargs` dynamically (kwarg values may be
cloud formation json values).
"""
with open(filename) as fd:
content = fd.read()
lines = content.split("\n")
# Template in parts matching {{foo}} with kwargs
lines... | e40296a0fbeb4923f41a0c6883212060171c7386 | 3,606,674 |
from typing import Dict
from typing import List
from typing import Any
def load_library_metadata() -> TypeRawLibraryCache:
"""
Loads the cached version of the music library. The cache is saved in the configurable cache directory.
Recreates LibraryFile instances from the data.
Returns:
A
"... | bf3c00858dc5d65c67f5399ed5388d99da9d611a | 3,606,675 |
def get_b(i,j):
"""returns the in-tad coordinates"""
i,j = np.sort([i,j])
bx,by=[],[]
for y_ in range(i,j+1):
for x_ in range(i,y_):
bx.append(x_)
by.append(y_)
return bx,by | 4e66bce44f00dd2642af460015db69ade4084ab0 | 3,606,676 |
def load_bmrbm(table_fname, resname_col, atom_col, shift_col):
"""Load a BMRBM table and return a dictionary."""
bmrb_dic = {}
with open(table_fname, "r") as bmrb_file:
for line in bmrb_file.readlines():
# Split so that the whitespaces don't matter
c_shift = line.split()
... | 85abb1fb714f407b91ecb9b3b04163b2badbec8f | 3,606,677 |
def random_spd(p, eig_min, cond, rand_gen=None):
"""Generate a random symmetric positive definite matrix.
Parameters
----------
p : int
The first dimension of the array.
eig_min : float
Minimal eigenvalue.
cond : float
Condition number, defined as the ratio of the maxi... | 4d4ae1bbb290e635cfbba2ab7ee824695aa07e30 | 3,606,678 |
from typing import Any
from datetime import datetime
def upload_blob(
container: ContainerClient,
blob_name: str,
content_type:str,
content_encoding:str,
data: Any,
return_sas_token: bool=True
) -> str:
"""
Uploads the given data to a blob record. If a blob with the given name already ... | c49a91ede69bad71a6f5535c29db5027f89edab0 | 3,606,679 |
def get_centroids(w2v_model, aspects_count):
"""
Clustering all word vectors with K-means and returning L2-normalizes
cluster centroids; used for ABAE aspects matrix initialization
"""
km = MiniBatchKMeans(n_clusters=aspects_count, verbose=0, n_init=100)
m = []
for k in w2v_model.w... | 5a23b20e59fa6fdc993f8bc04128e5a5257172ca | 3,606,680 |
def get_wikidata_sitelinks(source, target, titles):
"""
Returns a dictionary mapping from titles to wikidata ids
for the articles in source missing in target
"""
endpoint = configuration.get_config_value('endpoints', 'wikidata')
params = configuration.get_config_dict('wikidata_params')
param... | c4f16eaad0c7f2bea46fa1af0ded355e56447b60 | 3,606,681 |
def stats_filter(session, datapath, threshold):
"""
Here we test for the first 4 critieria used in the publication, basically
if a neurons passes these at a threshold of 0.05. Despite doing 4 tests
a neurons transientyl firing would be excluded so this threshold was
chosen inste... | 29a93f938793543052d28cd588c9d3457f07a90d | 3,606,682 |
def yp_raw_competitors(data_path):
"""
The file contains the list of business objects.
File Type: JSON
"""
return f'{data_path}/yp_competitors.json' | 7c33229d9cec5900a2e7b4fd868f91f576761c50 | 3,606,683 |
def compute_geodesic_from_start_to_target_vkeys(mesh, start_v_keys_list, target_v_keys_list):
"""
compute distances from one edges to another edge and get longest way and shortest way
"""
v, f = mesh.to_vertices_and_faces()
v = np.array(v)
f = np.array(f)
vertices_start = np.array(start_v_ke... | 99dc0a4206bfddc728970d92b4ff058c353d1d90 | 3,606,684 |
def typename(char):
"""
Return a description for the given data type code.
Parameters
----------
char : str
Data type code.
Returns
-------
out : str
Description of the input data type code.
See Also
--------
typecodes
dtype
"""
return _namefro... | 87f31468176c715813c25877453d5c06d94c3bc9 | 3,606,685 |
def _load_pascal_annotation(filename, class2ind):
"""
Load image and bounding boxes info from XML file in the PASCAL VOC
format.
"""
tree = ET.parse(filename)
objs = tree.findall('object')
if not cfg.USE_DIFFICULT:
# Exclude the samples labeled as difficult
non_diff_objs... | 490a1c3e0c553ce5f21f59835a07686591e9f132 | 3,606,686 |
def imitation_sonar():
"""imitates a sonar object that sends either depth or temperature data"""
return str(sonar_depth()) + "_" + str(sonar_temp()) | 2ab655b00a56167d823ef6ae52f004db0cc3b57e | 3,606,687 |
from operator import gt
def _evaluate_class(class_id, iou_threshold, recall_thresholds, class_counter, mpolicy="greedy"):
""" Evaluate class.
Arguments:
class_id (int): index of evaluated class.
iou_threshold (float): iou threshold.
recall_thresholds (np.array or None): specific recal... | 00033a24af59bd0f2582db3d3d5fdc46024760fd | 3,606,688 |
def reciprocal_rank(rs): # iterator of relevance scores in rank order
""" Compute reciprocal ranks for a bunch of queries: reciprocal of the rank of the first relevant item for
each query (considering the first element being of 'rank 1'). Relevance is binary (nonzero is relevant).
Args:
rs: Iterat... | a7740625cd938983a71eab1697f0134ad9efae3a | 3,606,689 |
def can_view_related_model(func):
"""
Decorator for view-methods to check permission to view the filtered items.
"""
def wrapper(self, request, **kwargs):
permission = '{app_label}.view_{model}'.format(**kwargs)
if not request.user.has_perm(permission):
raise PermissionDenied... | 6cb3b4fc054163b69d630f4928945cf4462b40d9 | 3,606,690 |
def add_colorbar(im, aspect=20, pad_fraction=0.5, **kwargs):
"""Add a vertical color bar to an image plot."""
divider = axes_grid1.make_axes_locatable(im.axes)
width = axes_grid1.axes_size.AxesY(im.axes, aspect=1 / aspect)
pad = axes_grid1.axes_size.Fraction(pad_fraction, width)
current_ax = plt.gca... | 5939616ca7e1f873e7ac87d98ba3be73e830d915 | 3,606,691 |
import os
import shutil
def create_gitbom_doc(infile_hashes, db, destdir):
"""
Create the gitBOM doc text contents
:param infile_hashes: the list of input file hashes
:param db: gitBOM DB with {file-hash => its gitBOM hash} mapping
:param destdir: destination directory to create the gitbom doc fil... | 86167b3e4eb7823ee7692c1931f7f724553a8260 | 3,606,692 |
import re
def to_num(string):
"""Convert string to number (or None) if possible"""
if type(string) != str:
return string
if string == "None":
return None
if re.match("\d+\.\d*$", string):
return float(string)
elif re.match("\d+$", string):
return int(string)
... | 79a0740e298e33198dca2d7b7fcd53700f121869 | 3,606,693 |
def button_action (date, action, value) :
""" Create a button for time-tracking actions """
''"approve", ''"deny", ''"edit again"
if not date :
return ''
return \
'''<input type="button" value="%s"
onClick="
if(submit_once()) {
document.forms.edit_... | 314f950d1601987d23490fc48c2f5365a39d4533 | 3,606,694 |
from typing import Callable
import hmac
def validate_hmac(header: str, secret: Callable):
"""
Validates that the HMAC signature in `header` is a valid signature for the request
body
"""
def decorator(f):
@wraps(f)
def decorated_function(request: Request, *args, **kwargs):
... | bded33fefea4957dd09f0b0555a0ba1455789f54 | 3,606,695 |
from typing import Tuple
import os
def _landsatlive() -> Tuple[str, str, str]:
"""
Handle / requests.
Returns
-------
status : str
Status of the request (e.g. OK, NOK).
MIME type : str
response body MIME type (e.g. application/json).
body : str
String encoded html
... | 39a8142f93a562fd5fab4cc32218cf0a267db06a | 3,606,696 |
import sys
def contract_hash(
from_addr_base16: str,
nonce: int,
function_counter: int) -> bytes:
"""
Should match what the EE does:
blake2b256( [0;32] ++ [0;8] ++ [0;4] )
pk ++ nonce ++ function_counter
"""
def hash(data: bytes) -> bytes:
h = blake2b(digest_size=3... | 24ec82ddea3493632ae4330170da6dd489d5cd1a | 3,606,697 |
def get_tidy_invocation(f, clang_tidy_binary, checks, build_path,
quiet, config):
"""Gets a command line for clang-tidy."""
start = [clang_tidy_binary]
# Show warnings in all in-project headers by default.
start.append('-header-filter=src/')
if checks:
start.append('-... | 50e95d612f08ec5762bd2d0689a4fcbe9c699a11 | 3,606,698 |
import sqlite3
def get_all_users():
"""
Gets all fields from all users.
"""
conn = sqlite3.connect(DB_STRING)
# Create a query cursor on the db connection
queryCurs = conn.cursor()
queryCurs.execute('SELECT * FROM Users')
usersData = queryCurs.fetchall()
conn.commit()
conn.clos... | 7d4849dafd67c8af162b06b2bf53a8c1369e56df | 3,606,699 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.