content stringlengths 35 762k | sha1 stringlengths 40 40 | id int64 0 3.66M |
|---|---|---|
def rel_improve(scores_a, scores_b):
"""
Determines the relative improvement that is used to derive the Delta Relative Improvement (DeltaRI).
@param scores_a: Scores of the advanced run.
@param scores_b: Scores of the baseline run.
@return: Dictionary with relative improvements for each measure.
... | a7c2515fb4badea38f8a24c94f88552ed7f32f92 | 3,595,335 |
def chr_len(bam):
"""
Load input files required to run add_chromosome_length
"""
# Get sequence lengths of all chromosomes
chr_len, chr_lengths_cumsum = get_sequence_length(bam)
return chr_len | c959da8b39da9da2b5e22ffeff1bebce9ef8c89f | 3,595,336 |
from typing import List
def delete_assets(asset_ids: List[int], **kwargs):
"""Delete a list of assets.
Args:
asset_ids (list[v04.dto.Asset]): List of IDs of assets to delete.
Keyword Args:
api_key (str): Your api-key.
project (str): Project name.
Returns:
An empty r... | 5facf0b26a90aa2a59b116de6e46ff3e5d62a2e9 | 3,595,337 |
def value_definition(definition):
"""
Registers class as a value definition. It must implement BaseValue interface.
:param definition: a class to registered
:return: the provided class without any changes
"""
assert issubclass(definition, BaseValue), f'A class definition must implement {BaseVal... | e4fec9582969169a3d6b4ab45cff800266a5729e | 3,595,339 |
def SX_matrix_scalar(*args):
"""
matrix_scalar(int op, SX x, SX y) -> SX
"""
return _casadi.SX_matrix_scalar(*args) | 4c0787f724ff633f5c085cc70bc00a96f3e799e7 | 3,595,340 |
def count_requests(db_session, endpoint_id, *where):
"""
Return the number of hits for a specific endpoint (possible with more filter arguments).
:param db_session: session for the database
:param endpoint_id: id of the endpoint
:param where: additional arguments
"""
return count_rows(db_ses... | 9ce9df009d2edab2cffa40cfa6872683fc4f5da2 | 3,595,341 |
def get_atom_and_bond_types(smiles, log=True):
"""Identify the atom types and bond types
appearing in this dataset.
Parameters
----------
smiles : list
List of smiles
log : bool
Whether to print the process of pre-processing.
Returns
-------
atom_types : list
... | 4c60ba289ff6b3d2254a1877b48c425381d46cdf | 3,595,342 |
def template_common_option(f):
"""
Common ClI option for template
:param f: Callback passed by Click
:return: Callback
"""
return template_click_option()(f) | 420f0a07d0facfedcedc9695c3512ca0510351ef | 3,595,343 |
def mean_squared_error(output, target, is_mean=False, name="mean_squared_error"):
"""Return the TensorFlow expression of mean-square-error (L2) of two batch of data.
Parameters
----------
output : Tensor
2D, 3D or 4D tensor i.e. [batch_size, n_feature], [batch_size, height, width] or [batch_siz... | 70847dad954ae16e6d576b55d0ca778f3fad13fb | 3,595,344 |
def init(screen_size=screen_size,fullscreen=False):
"""init pygame and returns screen"""
pygame.init()
if fullscreen:
screen= pygame.display.set_mode(screen_size,pygame.FULLSCREEN) #,pygame.FULLSCREEN
else:
screen= pygame.display.set_mode(screen_size) #,
pygame.display.set_caption('Alarm clock')
return screen | 869f1f14680b258e4702df3d47049a15fc7586ca | 3,595,345 |
def bollinger_lband_depreciated(close, n=20, ndev=2, fillna=False):
"""Bollinger Bands (BB)
Lower band at K times an N-period standard deviation below the moving
average (MA − Kdeviation).
https://en.wikipedia.org/wiki/Bollinger_Bands
Args:
close(pandas.Series): dataset 'Close' column.
... | 0196d75877ab1efa47eebf57ade36aa2e25fa6a7 | 3,595,346 |
def subplot_shape(size):
"""
Get the most square shape for the plot axes values.
If only one factor, increase size and allow for empty slots.
"""
facts = [[i, size//i] for i in range(1, int(size**0.5) + 1) if size % i == 0]
# re-calc for prime numbers larger than 3 to get better shape
while ... | 001ce7a0fd8e6e6a8f767a10c74a3e54ac167256 | 3,595,347 |
def sample_ingredient(user,name="Cinamon"):
"""Create and return a sample ingredient"""
return Ingredient.objects.create(user=user,name=name) | bf596b91b73a1d0e48bcdca972ae797a250a3243 | 3,595,348 |
from nncf.torch import load_state
import torch
from typing import OrderedDict
def _load_checkpoint_for_nncf(model, filename, map_location=None, strict=False):
"""Load checkpoint from a file or URI.
Args:
model (Module): Module to load checkpoint.
filename (str): Either a filepath or URL or mo... | c6c26ef6677e3065c53363250cae589482076b41 | 3,595,349 |
def get_peak_day(fuel_yh):
"""Iterate an array with entries and get
entry nr with hightest value
Arguments
---------
fuel_yh : array (hours)
Fuel for every day
Return
------
peak_day_nr : int
Day with most fuel or service
"""
if np.sum(fuel_yh) == 0:
#lo... | 9cd47097b73161f1452e032c9897e5ff24d527f5 | 3,595,350 |
def make_discriminator_model(input_tensor=None,
input_shape=(28, 28, 1)):
"""
Returns:
tf.keras.Model
"""
if input_tensor is None:
img_input = layers.Input(shape=input_shape)
else:
if not backend.is_keras_tensor(input_tensor):
img_input = layers.Input(tensor=inp... | 77d4efe02e74a5d3e05fc73602bb4546fa951630 | 3,595,351 |
def ImportModule(modname):
"""
Helper import funation based on example in std Python docs:
http://docs.python.org/lib/built-in-funcs.html
"""
modname = IMPORT_PREFIX + modname
mod = __import__(modname)
components = modname.split('.')
for comp in components[1:]:
mod = getattr(mod,... | 91b46af31927a677780ff6e2616319d9f007a446 | 3,595,352 |
from typing import Optional
from typing import Dict
def read_config(
filename: str, format: Optional[str] = None, validate: Optional[bool] = False
) -> Dict:
"""Read worker configuration object from a given file.
Parameters
----------
filename: str
Input file name
format: string, opti... | 5fe5938dba56834d4975ccebe1f2132b21f06dda | 3,595,353 |
from typing import Optional
from typing import Union
def last_run_before_date(
da: xr.DataArray,
window: int,
date: DayOfYearStr = "07-01",
dim: str = "time",
coord: Optional[Union[bool, str]] = "dayofyear",
) -> xr.DataArray:
"""Return the index of the last item of the last run before a given... | 4ebc676e7fa10dc81c670d3b8c30f1152beadd00 | 3,595,354 |
import six
def like_filter(query, cls, search_opts):
"""Add 'like' filters for specified columns.
Add a sqlalchemy 'like' filter to the query for any entry in the
'search_opts' dict where the key is the name of a column in
'cls' and the value is a string containing '%'.
This allows the value of ... | c42318350a9c19715fc6a2e0c74d8bec423b4cfc | 3,595,358 |
def CalculateTFD(torsions1, torsions2, weights=None):
""" Calculate the torsion deviation fingerprint (TFD) given two lists of
torsion angles.
Arguments;
- torsions1: torsion angles of conformation 1
- torsions2: torsion angles of conformation 2
- weights: list of torsion weights (... | 621bdf9c51130b33721e48c52f72053d9a0b5f19 | 3,595,359 |
def _change_setting_test(ctx):
"""Test to verify that an analysis test may change configuration."""
env = analysistest.begin(ctx)
dep_min_os_version = analysistest.target_under_test(env)[_ChangeSettingInfo].min_os_version
asserts.equals(env, "1234.5678", dep_min_os_version)
return analysistest.end... | ced1ee2211477cbd19f5279b7faea43c2eb1383c | 3,595,360 |
import io
def get_output_status(out, filename=False):
"""
Returns the name of qc package if the calculation is successful.
Returns None if failed or unknown package.
"""
p = 'NA'
s = 'NA'
m = ''
nchar = 512
if filename:
out = io.read_file(out, aslines=False)
if "Gaussia... | 928eb439ccf42c28ad25bf62b7965c96750605f0 | 3,595,361 |
def reaction_fluxes(verbose=False):
"""
Return the reaction fluxes from the solved FBA model.
:param verbose: Print more output
:type verbose: bool
:return: A dict of reaction ID and flux through that reaction
:rtype: dict of str and float
"""
return lp.col_primal_hash() | e94fa18344eaa3dd90752232801f0f24f630f401 | 3,595,362 |
def compare_values(answer, submitted_answer):
"""Comparing values"""
if answer["value_type"] == "number":
if "comparison_type" in answer and answer["comparison_type"] == "absolute":
return abs(answer["value"]) == abs(submitted_answer)
if answer["value_type"] != "string":
return a... | 7f1e7a9a2b2eb5943fd15562fe3e1d376f30c8db | 3,595,363 |
def calc_cost(pred_xs, input_sample, g_xs,
state_cost_fn, input_cost_fn, terminal_state_cost_fn):
""" calculate the cost
Args:
pred_xs (numpy.ndarray): predicted state trajectory,
shape(pop_size, pred_len+1, state_size)
input_sample (numpy.ndarray): inputs samples tr... | 7f2dfd24ffef341df463405dcddbe9dc763b7410 | 3,595,364 |
def read_file(filename):
"""
Return the contents of the file with the given filename as a string
>>> write_file('read_write_file.txt', 'Hello World')
>>> read_file('read_write_file.txt')
'Hello World'
>>> os.unlink('read_write_file.txt')
"""
with open(filename) as in_fh:
return ... | 756187a755a54b2d6e96ad6d297ceb2472afbb6c | 3,595,366 |
import warnings
def _hideWarnings(func):
"""
Decorator function that hides annoying deprecation warnings in find_peaks_cwt
"""
def func_wrapper(*args, **kwargs):
with warnings.catch_warnings():
warnings.simplefilter("ignore")
return func(*args, **kwargs)
return fun... | cfbd9af74bb08cbfe4d6429c3b4ba2511fa3aa43 | 3,595,368 |
def config(new_config = None):
"""
Read and write to the config.json file
"""
with open('sm_config.json') as f:
conf = ujson.load(f)
if new_config is None:
return conf
else:
conf.update(new_config)
with open('sm_config.json', 'w') as f:
ujson.dump(co... | 3d43a821cacf07a59d93f9097200585aaf04cf36 | 3,595,369 |
from typing import Any
import numpy
def get_source_table(
param_ranges: dict[str, Any],
n_sources: int = 1,
) -> astropy.table.Table:
"""Returns a table of sources."""
def get_random_range(param):
if isinstance(param_ranges[param], list):
return numpy.random.uniform(
... | d5641ecffa4965105dbfa39d60f7d351e9bb3cea | 3,595,370 |
def whatLName(fName, listOfStudents):
"""
return the major of first student in listOfStudents with first name fName, False if none found
>>> whatLName("FRED",[Student("MARY","KAY","MATH"), Student("FRED","CRUZ","HISTORY"), Student("CHRIS","GAUCHO","UNDEC")])
'CRUZ'
>>>
"""
for i in range(... | 81b070be78083697c51abdfed5da2287440b2717 | 3,595,371 |
def rotMatrixFromEcefToCamera(longitude, camPoseEcef):
"""
This rotation matrix aligns the ecef frame to a camera frame where z is the
nadir vector pointing towards earth (thumb), x is vector along ISS orbit (index finger),
and y is downward vector.
"""
longitude = degreesToRadians(longitude)
... | a0d1c3ddac85c9d4d33105763df0d594faedf4b8 | 3,595,372 |
def flows2colorimages(arFlows):
"""
Converts array of optical flow to array of color image.
:param arFlows: optical flow.
:return: array of color image.
"""
n, _, _, _ = arFlows.shape
liImages = []
for i in range(n):
arImage = flow2colorimage(arFlows[i, ...])
liImages.app... | 38b5c16650bb40a4d3300e93f301a4ca38818499 | 3,595,373 |
from typing import Iterator
def load_document_ids(model_name: str, folder: PathLike) -> Iterator[str]:
"""Loads a list with the document identifiers"""
return read_text_items(folder / f"{model_name}_document_ids.txt") | ef0d401a5a8c068aaec1c5fbb31e7d865c89c78f | 3,595,374 |
import math
def convert_depth_data_to_depth_map(
depth_data: DepthData,
undefined_value=-1.0
) -> np.ndarray:
""" converts depth map from 4 season format to kapture format """
depth_map = np.ones(depth_data.image_size, dtype=depth_data.coords.dtype)
depth_map *= undefined_value
assert ... | f5f710fcb5652aef99a5c1646607354dcd72adbd | 3,595,375 |
def scrape_random():
"""
Uses the site's random feature to grab a random profile.
:return: A single Profile object from a randomly chosen subject.
"""
Logs._log("Starting Random function ...")
url = "https://www.celebritynetworth.com/random/"
html = bf.get_pages([url])[0]["html"]
pr... | 77aeb18dfcf19fdadcb4c19bd6e9ad9bd455a9f6 | 3,595,376 |
import configparser
def genconf(text):
"""Generate contents of a config file."""
# set up config parser
config = configparser.ConfigParser(allow_no_value=True)
config.optionxform = str
for i in (("SEPM", SEPM),
("SEPP", SEPP),
("SEPC", SEPC),
("SEPR", SEPR... | 1c79dfff5d30752e47b7d787f19d8fa2d223ee2e | 3,595,377 |
from typing import Optional
async def login_user_form(
request: Request, message: Optional[str] = "") -> templates:
"""rendering login route get method"""
return templates.TemplateResponse("login.html", {
"request": request,
"message": message,
'current_user': "logged in"
}... | ccd5539be92a4fe46db2a2ce81ae505e1b0d2ade | 3,595,378 |
def last_in_array(array, operation = None):
"""Return the last element in an array.
I think this is just [-1]
"""
if len(array) == 0:
return None
return array[-1] | fb93f365368b31ed31ab9f4c2dde066b1add4425 | 3,595,379 |
import math
def vector_norm(data, axis=None, out=None):
"""Return length, i.e. eucledian norm, of ndarray along axis.
>>> v = np.random.random(3)
>>> n = vector_norm(v)
>>> np.allclose(n, np.linalg.norm(v))
True
>>> v = np.random.rand(6, 5, 3)
>>> n = vector_norm(v, axis=-1)
>>> np.al... | 165e9814fac3d990456f33174322c71ab4f94046 | 3,595,380 |
from typing import Dict
import functools
import itertools
def guard(trafaret=None, **kwargs):
"""
Decorator for protecting function with trafarets
>>> @guard(a=String, b=Int, c=String)
... def fn(a, b, c="default"):
... '''docstring'''
... return (a, b, c)
...
>>> fn.__module_... | 52e133aa3cc9fdb9dbbb880ad0571c77a3756ba2 | 3,595,381 |
from typing import Callable
def linear_schedule(initial_value: float) -> Callable[[float], float]:
"""
Linear learning rate schedule.
:param initial_value: Initial learning rate.
:return: schedule that computes
current learning rate depending on remaining progress
"""
def func(progress_... | 47a580788c745b7566c22daa97c3aecee0bb8ff2 | 3,595,382 |
def with_most_orth(lines_list):
""" Might not actually need this for anything
Return the line in lines_list that is perp to the greatest number of lines
in the list
Known uses: find the line parallel to the flow chamber """
best_index = 0
best_score = 0
for i in range(len(lines_list)):
... | 24f5ab0b15db13ab036234769bd16dcac9a3013c | 3,595,383 |
from datetime import datetime
def span_date_to_datetime(date, minutes):
""" Converts date string and minutes to datetime
Args:
date (str): Date in the `%Y_%m_%d` format
minutes (int): Minutes since midnight
Returns:
:obj:`datetime.datetime`
"""
date_format = "%Y_%m_%d %H%M... | 582c8b9c9177a6417b3891f1334c15f25451f6da | 3,595,384 |
def guard(*guard_clauses):
"""guard function.
:param tuple *guard_clauses: guard clauses.
>>> g = guard_cl
>>> (lambda n: guard(
... g(-1, n < 0),
... g(0, n == 0),
... g(1) ## otherwise
... ))(0)
0
>>> s = lambda n: guard(
... g(-1, n < 0),
... g(0, n == 0),
... ... | 6fe02717344b1d1d82eb701891feb898bdcad002 | 3,595,385 |
import gzip
def extract_data(filename, num_clips):
"""
Extract motion clips from a raw gzip data file into a 4D tensor [image index, y, x, channels].
Values are rescaled from [0, 255] down to [-0.5, 0.5].
:param filename: path to raw gzip data file
:param num_clips: number of motion clips in file
... | a6e7490bfd75e6725809a647c6055eb307448e55 | 3,595,386 |
from typing import Sequence
def split_sentences(tokens: Sequence[Token]) -> Sequence[Sequence[Token]]:
""" Breaks a list of Token objects into sentence chunks delimited by sent_start and sent_end. Incomplete sentences
are not included in the result.
>>> len(split_sentences([Token.with_text(env.sent_start... | c2cb0c3ace6d5c657971964c9aa2a174c1edc3cc | 3,595,387 |
from typing import Literal
def to_term(s, default=None):
"""
Creates and returns an Identifier of type corresponding
to the pattern of the given positional argument string ``s``:
'' returns the ``default`` keyword argument value or ``None``
'<s>' returns ``URIRef(s)`` (i.e. without angle bracket... | 0b12106f1ac695ce576d71a853f91fc1316cde49 | 3,595,388 |
def build_resnet_block_Att(inputres, dim, name="resnet", padding="REFLECT"):
"""
build a single block of resnet.
return: a single block of resnet.
"""
with tf.variable_scope(name):
out_res = tf.pad(inputres, [[0, 0], [1, 1], [1, 1], [0, 0]], padding)
out_res = models.layers.general_c... | 7e9d52f9b2e1cfc090d7d0c1b973ed7d86a03aeb | 3,595,389 |
def _simplex_projection_sort(
yp: np.ndarray,
r: float
):
"""
Projection onto the simplex using sorting.
Parameters
----------
yp : ndarray
The vector to project, containing non-negative entries.
r : float
The radius of the simplex on which to project.
Returns
-------
xp : ndarray
The projection.
... | add2196132a5f23b8a71ea2d2a018fcde1dd1b2a | 3,595,390 |
import lark
def evaluate_data(formula, env, parser, evaluator):
"""
Evaluates a formula given a parser, a corresponding evaluator class, and an environment.
The environment is a dict-like object (such as an `xarray.Dataset`) that maps variable names to values.
"""
@lark.v_args(inline=True)
cla... | 9b268c20d39fa7481e98ac19c492e93671069bce | 3,595,392 |
def fieldnames(cursor):
"""
최근 실행한 쿼리의 field names 리스트
:param cursor:
:return: list[str]
"""
return [f[0] for f in cursor.description] | f369ce8e904464082c65d855071bc2e1ebc2a21d | 3,595,393 |
def compute_frags(
soma_coords, labels, im_processed, threshold, res, chunk_size=None, ncpu=2
):
"""Preprocesses a neuron image segmentation by splitting up non-soma components into 5 micron segments.
Args:
soma_coords (list): list of voxel coordinates of somas
labels (np.array): image segm... | 03a75146d8cd7eb3f48c3d28929ffe3e644113d3 | 3,595,394 |
from datetime import datetime
def is_datenum(datenum):
""" Return True if given str is a date in format %Y%m%d """
try:
datetime.strptime(datenum, "%Y%m%d")
return True
except (ValueError, TypeError):
return False | c61998ebf18a3fbdd4c87463a2ab0790864c62b4 | 3,595,395 |
import math
def special_case(sku_data, free_trigger, trigger_amount, free_sku, free_sku_value, free_deal=None):
"""free_deal can be tuple of amount and value"""
free_items = 0
total = 0
if sku_data[free_trigger] / trigger_amount >= 1:
# for every <trigger_amount> of <free_trigger> we get a fr... | 924c1c6f612d98f8b99f1622c2827d97481a7a30 | 3,595,396 |
import torch
def get_cuda_max_memory_allocations() -> int:
"""Get the `max_memory_allocated` for each cuda device"""
return torch.tensor([torch.cuda.max_memory_allocated(i) for i in range(torch.cuda.device_count())]) | 7d2277c5de398b463f8d77606ea7c188bbe3b8cc | 3,595,397 |
def resnet18_builder_mod(inputs, keep_prob, training, data_format, num_filters,
resnet_version, first_pool_size, first_pool_stride, block_sizes,
bottleneck, block_fn, block_strides, pre_activation, num_classes, hk):
"""Add operations to classify a batch of input images.
Args:
inputs: A Tensor representing... | 66ff99a467c8fb101a8c795bb15f96b456a9e838 | 3,595,398 |
def get_values (feature, properties):
""" Returns all values of the given feature specified by the given property set.
"""
if feature[0] != '<':
feature = '<' + feature + '>'
result = []
for p in properties:
if get_grist (p) == feature:
result.append (replace_grist (p, ''))
... | a3468080314f3b4810540d9230abcbfd04d8f4a8 | 3,595,399 |
def convert_crlf(value):
"""
Replace carriage return and line feed character by their javascript value
Make possible to include title with those characters in the aloha links
"""
return value.replace('\r', '\\r').replace('\n', '\\n') | 17210472fcccb27f02fc8dcf5ebbe654bfa58278 | 3,595,400 |
def bathymetry_gradient(bathy, e1u, e2v):
"""Calculate the bathymetry gradient, H_x and H_y. Not that these are the
gradients on the U-grid (H_x) and V-grid (H_y).
:arg bathy: bathymetry array. Dimensions: (y, x)
:type bathy: numpy array
:arg mesh_mask: netCDF handle that contains mesh mask inform... | 567ba828701a790fd636d87be11b38212583373b | 3,595,401 |
from typing import Iterable
def _step_sum(
params:Iterable[float],
values:Iterable[float]
) -> float:
"""
Summation term of an AR(m), MA(n), or GARCH(p) / GARCH(q) process
Each order-specific, fitted relationship parameter is multiplied by the
corresponding order-specific lagged value, t... | bf76123d982e69161b44ab55cfb11adbd7f8e64e | 3,595,402 |
def _compute_position(input, index):
"""Compute line/column position given an index in a string."""
line = 1
col = 1
eol = None # last end of line character
for c in input[:index]:
if c == '\n' or c == '\r':
if eol is None or eol == c:
eol = c
lin... | f08217651d11ed09c1e100368aa8cc869c37e386 | 3,595,403 |
def _get_lrdb_specs(lrdb_path:str):
"""
Return a DataFrame containing the unique combinations of "loss_key",
"grname" and "grcode" from the CAS Loss Reserving Database (lrdb).
"""
fields = ["loss_key", "grcode", "grname"]
lrdb = pd.read_csv(lrdb_path, sep=",")
lrdb = lrdb[fields].drop_duplic... | 32b196c2c0162d3cad46429bde5af312fd928f9e | 3,595,404 |
def _send_cmd_get_status(obj_session, details_dict, index, system_name=None):
"""Sends a command, verifies the response and returns
status of the command """
if isinstance(obj_session, WNetwork.warrior_cli_class.WarriorCli):
result, response = obj_session._send_cmd_get_status(details_dict,
... | 4d73569d6e18fc72a594767bbc7fbdbeb810357e | 3,595,405 |
def training(H, loss, global_step):
"""Sets up the training Ops.
Creates a summarizer to track the loss over time in TensorBoard.
Creates an optimizer and applies the gradients to all trainable variables.
The Op returned by this function is what must be passed to the
`sess.run()` call to cause th... | 5b4a61200bbb45d600daa08a1d256b43cdaebb75 | 3,595,406 |
def within__predictors(network, kinase_column, substrate_column, output):
"""
Finds mutual information shared between kinases based on the substrate phosphorylated
Mutual Information is defined as the intersection substrates between two kinases
A substrate is defined as the substrate accession and site,... | 10626fb54ca4a1c21083ad688540d3801ae6c097 | 3,595,408 |
def _(data: ndarray, thresh: int = 3, subset: Strings = None) -> ndarray:
"""Process ndarrays"""
_warn_subset_not_impl(subset, "ndarray")
mask = np.abs(scale(data)) > thresh
return mask.astype(np.bool_) | c464f863c0a0208f1b261169d1a8b89515218ac2 | 3,595,409 |
import tenacity
def get_tweets(method, *args, **kwargs):
"""Generates tweets for a given API method.
:param method: The tweepy API method to call.
:param args: args to pass to the API method.
:param kwargs: kwargs to pass to the API method.
"""
# We always want the extended mode: this includ... | 5eefea1df328dea57f01d21aa490fcc17900519c | 3,595,411 |
def add_user_to_event(user_id, event_id):
"""
Add user to a event. Make sure event ownership checks are done BEFORE this
function is called.
:param user_id: user to be added to event
:param event_id: event to add user to
"""
event = event_store.get_event_by_id(event_id)
if not event or n... | 24c54626956728f7b41bfdbded423945937d4746 | 3,595,412 |
def extract_matching_object_from_id_set(obj_id, obj_set, server_version='0'):
"""Gets first occurrence of object in the object's id_set with matching id/name and valid from/to version"""
for obj_wrpr in obj_set:
# try to get object by id
if obj_id in obj_wrpr:
obj = obj_wrpr.get(obj_... | 503ac23a488c97944f194142637d0be900805567 | 3,595,413 |
import itertools
def flatten(sequence):
"""
Get a flat list out of a list of lists.
"""
return list(itertools.chain(*sequence)) | 1c3c7c41969c7e172083e73f2e2aa5731fb56ada | 3,595,414 |
def get_gps_vel_msg(stamp, gps_vel):
"""
Get vehicle speed in NED frame as ROS geometry_msgs::TwistStamped
"""
# init:
gps_vel_msg = TwistStamped()
# set header:
gps_vel_msg.header.stamp = stamp
gps_vel_msg.header.frame_id = '/imu_link'
# set NEU speed:
(
gps_vel_msg.tw... | 08c28806c5997cd7e9f3e09bd5e626535f9b323f | 3,595,415 |
def logscale_probwheel(items, logweights):
"""Randomly select an item from a [log] weighted list of items.
Fucntion just rescale logweights and exponentiates before calling
probwheel.
"""
return probwheel(items, N.exp(rescale_logvalues(logweights))) | 25d94a45303b9822272938305303b7aece6fd20c | 3,595,416 |
from typing import Optional
from typing import Dict
from typing import Hashable
from typing import Any
def propagate_indexes(
indexes: Optional[Dict[Hashable, Index]], exclude: Optional[Any] = None
) -> Optional[Dict[Hashable, Index]]:
"""Creates new indexes dict from existing dict optionally excluding some d... | 754c882c7b041f9ce9187cfa45bca72c05c2964c | 3,595,417 |
def null_to_p(test_value, null_array, tail="two"):
"""Return p-value for test value against null array.
Parameters
----------
test_value : :obj:`float`
Value for which to determine p-value.
null_array : 1D :class:`numpy.ndarray`
Null distribution against which test_value is compared... | a85e668f85b0ae0c054cda6b8e56e7ae5bbf93a0 | 3,595,419 |
def get_vizier_tables(key, tab_index=None, row_limit=50, verbose=True):
"""
Parameters
----------
key : str
vizier catalog key
tab_index : int
table index to download and parse
Returns
-------
tables if tab_index is None else parsed df
"""
if row_limit == -1:
... | 7fec131fa64532ae4380a15086eb2a53351decea | 3,595,420 |
def create_endpoint(coriolis, name, platform_type, connection_info,
barbican=None, description=''):
""" Creates and endpoint with the given parameters.
:param platform_type: type of platform (e.g. 'openstack', 'oci', 'azure')
:param connection_info: connection info for the given platfor... | 54dcfd483ae6b2641bbadb0bef1f27e38793dfa3 | 3,595,421 |
from datetime import datetime
def save_update_milestone(request, pk):
"""update project milestone"""
name = request.GET.get('name')
description = request.GET.get('description')
status_id = int(request.GET.get('status'))
start_date = request.GET.get('startdate')
end_date = request.GET.get('endd... | 3159629b53276613a67d4dd15ea3dfaf7be00cbc | 3,595,422 |
def equal_nan(request):
"""Fixture to whether consider nan as equal when comparing fields."""
return request.config.getoption("equal_nan") | 8fce969c2c84201822db735d46574644124c5c1a | 3,595,423 |
def univaqon(bot, update):
"""Defining the command to enable notification for univaq"""
if update.message.chat_id not in utils.USERS['univaq']:
utils.subscribe_user(update.message.chat_id, 'univaq')
bot.sendMessage(update.message.chat_id,
text='Notifiche Abilitate!',
... | 2ae1df624e437f4ef4abdc24aa6458d94b878718 | 3,595,424 |
def plot_tracks(tracks, track_ids, n_events):
"""Plot 3D tracks starting from MC truth information"""
pdgs = []
drawn_objects = []
for itrk in track_ids:
track = tracks[itrk]
if track['dx'] < 1:
continue
html_name = Particle.from_pdgid(track['pdgId']).html_name.replac... | 7e44029aeeee3aeaead4f950409db63150faa8a3 | 3,595,425 |
def round2(number: float) -> float:
"""
Rounds a number to the second decimal.
"""
return round(number, 2) | 5c788d01bce28831145391dcb261362b8a2208f3 | 3,595,426 |
import platform
def get_system() -> str:
"""
gets system - but more detailed
>>> result = get_system()
>>> possible_results = ['darwin', 'linux', 'windows', 'windows_xp', 'windows_wine', 'windows_wine_xp']
>>> assert result in possible_results
"""
if get_is_platform_windows():
s_sy... | 607e50de05fdcb421152042df9f388863297fb5a | 3,595,428 |
def flipslash(value):
""" Convert all backslashes to forward slashes (for apache) """
return value.replace("\\", '/') | 8fa5abe7c334e0b229aa7e9b2477c3c9aecf38e3 | 3,595,429 |
def get_play_actions(match_id2events, match_id, verbose=False):
"""
Given a list of events occuring during a game, it splits the events
into play actions using the following principle:
- an action begins when a team gains ball possession
- an action ends if one of three cases occurs:
-- the... | ba788946c8b0450749a1355b0a599c7fc0aa3d88 | 3,595,430 |
def get_model(point_cloud, input_label, is_training, bn_decay, k=20):
""" Classification DGCNN, input is BxNx3, output BxNx50 """
cat_num = 16
part_num = 50
batch_size = point_cloud.get_shape()[0].value
num_point = point_cloud.get_shape()[1].value
adj = tf_util.pairwise_distance(point_cloud)
nn_idx = tf_... | f9d0174fad344e983132235e0dd200aa7fcbef50 | 3,595,431 |
def _get_filter_area(x, filter_center, filter_width):
"""
Return an 'area' vector demarking where cleaning should be allowed
to take place.
Arguments:
x : array-like real space vector listing where data is sampled.
filter_center : center of the area to be cleaned. Units of 1/(x-units)
... | d90d865a1757829cdb2b7957c43295dba9acbc74 | 3,595,432 |
def get_migration_issue_accounts(request_ctx, account_id, content_migration_id, id, **request_kwargs):
"""
Returns data on an individual migration issue
:param request_ctx: The request context
:type request_ctx: :class:RequestContext
:param account_id: (required) ID
:type accoun... | 5e53c67fe7431d54cdecd3171bc94a4411d1bfed | 3,595,433 |
from typing import Union
def get_header_unicode(header: Union[str, Header]) -> str:
"""
Convert a header to unicode
Should be used to handle headers like From:, To:, CC:, Subject:
"""
if header is None:
return ""
ret = ""
for to_decoded_str, charset in decode_header(header):
... | f0da55ef37606c96b724b8d89a9b590950d74c9b | 3,595,434 |
def create_interpol_function(ephemeris):
"""Given an ephemeris, create an interpolation function that can be
used to get the RA Dec at an arbitrary time
Parameters
----------
ephemeris : astropy.table.Table
Returns
-------
eph_interp : scipy.interpolate.interp1d
"""
# In order ... | 8093f6320d1c9a3502837065dd44a514b3b14e92 | 3,595,435 |
def read_long(byte_arr, offset, endian=GUESS):
"""Read a long value from a byte array using a given endian or
guessing the endian"""
if endian == GUESS:
return min(read_long(byte_arr, offset, BIG_ENDIAN),
read_long(byte_arr, offset, LITTLE_ENDIAN))
b = byte_arr[offset:offset +... | f950d13c7a7474a934f2dc4780774fbaeb638d46 | 3,595,436 |
def alpaca_rest_api_conn(trading_type: str):
"""Creates the initial connection to Alpaca API.
Args:
trading_type: denotes live versus paper trading
Returns:
an API connection to Alpaca
**Example**
.. code-block:: python
from wsbtrading import data_io
alpaca_api =... | 08486479bff64686ceedf702252491d5f9eafd40 | 3,595,437 |
def merge_lists(a, b):
"""
a function to zip together two linked lists augmenting the first linked list
passed in to have the second LL values in it alternating
"""
if b.head == None:
return a
if a.head == None:
return b
if a._size >= b._size:
temp1, temp2 = a.head, ... | 6a979d6f63c59531b202fcad6f0d3701c483a18b | 3,595,438 |
from typing import Optional
def cumprod(
data: tvm.te.Tensor,
axis: Optional[int] = None,
dtype: Optional[int] = None,
exclusive: Optional[bool] = None,
) -> tvm.te.Tensor:
"""Numpy style cumprod op. Return the cumulative product of the elements along a given axis.
Parameters
----------
... | d41d8c0df8049a21cea3ecdc6c1a8af131176a82 | 3,595,439 |
import re
def clean_label_or_catalog_number(string):
"""Clean label or catalog ID: '[TMZ12006]', '[Kalahari Oyster Cult]' """
string = string.replace('【', '[')
string = string.replace('】', ']')
result = re.search(r'(\[.*\])', string)
if result is not None:
label_or_catalog_number = result.... | 3f52df574bf3c1676b67f2affac5287488982c1c | 3,595,441 |
def _load_vocab_file(vocab_file, reserved_tokens=None):
"""Load vocabulary while ensuring reserved tokens are at the top."""
reserved_tokens = []
subtoken_list = []
with tf.io.gfile.GFile(vocab_file, mode="r") as f:
for line in f:
subtoken = _native_to_unicode(line.strip())
subtoken = subtoken[1... | 75fe86baac389963f1f3c58b81e5ddb20deaa89d | 3,595,442 |
def effective_adapting_responses(xez, Y_o, E_o):
"""
Derives the effective adapting responses in the fundamental primary system
of the test or reference field.
Parameters
----------
xez: ndarray
Intermediate values :math:`\\xi`, :math:`\\eta`, :math:`\\zeta`.
E_o : numeric
T... | b08fac0e7c1f1aa6f4a51f2530c1477e61333009 | 3,595,444 |
def check_expr( dummy, opt, value ):
"""
Evaluate `value` as an expression.
"""
try:
val = eval(value)
except:
raise OptionValueError( "Could not evaluate value for option %s:\n%s"
% ( opt, value ) )
return val | afb3dde8a53ccf43f001235bd45e412265af27e0 | 3,595,445 |
def _get_instance_profile(role_name, iam_client=None, region_name=None):
"""
Returns the instance profile arn based of its name.
"""
if not iam_client:
iam_client = boto3.client('iam', region_name=region_name)
try:
resp = iam_client.get_instance_profile(
InstanceProfileNa... | 258ce0ebc215d7f476c6ad791fbf28803db8bae8 | 3,595,447 |
def computeTrial(data, cue_position, labels, fs, class_label = None):
"""
Transform the 2D data matrix of dimensions channels x samples in various 3D matrix of dimensions trials x channels x samples.
The number of 3D matrix is equal to the number of class.
Return everything inside a dicionary with the k... | 0d497221c4553470429970631908cb52b6c2c4dd | 3,595,448 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.