content stringlengths 35 762k | sha1 stringlengths 40 40 | id int64 0 3.66M |
|---|---|---|
def get_eval(appdir, config):
"""Get an Evaluation object given the configured `GlobalConfig`.
"""
return core.Evaluation(appdir, config.client, config.reps,
config.test_reps, config.simulate) | 89b1a7bbbbbf936b622c90635a54ab6517b7bc65 | 3,653,478 |
def load_queue_from_disk(filename):
"""
Load the old queue from disk when started. Old messages that weren't
posted yet are read from the queue and processed.
"""
if os.path.exists(filename):
log.msg("Loading queue from %s" % filename)
try:
with closing(open(filename, 'r'... | b2641c7c4ad58e683b856d82825f7bd71ec00f91 | 3,653,479 |
def ask_ok(title="Confirm", message=""):
"""Ask the user to confirm something via an ok-cancel question.
Parameters:
title (str): the text to show as the window title.
message (str): the message to show in the body of the dialog.
Returns:
bool: Whether the user selected "OK".
"... | 43e88f56219715a4f292ab6021d08d1e1fbc44de | 3,653,480 |
def indexate(points):
"""
Create an array of unique points and indexes into this array.
Arguments:
points: A sequence of 3-tuples
Returns:
An array of indices and a sequence of unique 3-tuples.
"""
pd = {}
indices = tuple(pd.setdefault(tuple(p), len(pd)) for p in points)
... | f78ef40ea9bf6cfe427d366026b633fbb67016a2 | 3,653,481 |
import ray
def get_handle(endpoint_name,
relative_slo_ms=None,
absolute_slo_ms=None,
missing_ok=False):
"""Retrieve RayServeHandle for service endpoint to invoke it from Python.
Args:
endpoint_name (str): A registered service endpoint.
relative_slo... | 9db603fb9f0069a328f3fce86c2b56eec719dd21 | 3,653,482 |
def create_symbolic_controller(states, inputs):
""""Returns a dictionary with keys that are the joint torque inputs and
the values are the controller expressions. This can be used to convert
the symbolic equations of motion from 0 = f(x', x, u, t) to a closed
loop form 0 = f(x', x, t).
Parameters
... | 98d8cc545e6b70dce6161ef6c14d8bc12e0dfe77 | 3,653,483 |
def is_gene_name(instance):
"""This SHOULD check a webservice at HGNC/MGI for validation, but for now this just returns True always.."""
ignored(instance)
return True | a8a5b4047e8d0d8e70280f54365adf7a5eec20ee | 3,653,484 |
import re
def install_package_family(pkg):
"""
:param: pkg ie asr900rsp2-universal.03.13.03.S.154-3.S3-ext.bin
:return: device_type of the installed image ie asr900
"""
img_dev = None
m = re.search(r'(asr\d+)\w*', pkg)
if m:
img_dev = m.group(1)
return img_dev | b344d51ae426e167dbd2397ab93cbf8707b01496 | 3,653,485 |
def get_dendritic_mask_path_from_sessid(maindir, sessid, runtype="prod",
check=True):
"""
get_dendritic_mask_path_from_sessid(maindir, sessid)
Returns path to dendritic mask file for the specified session.
Required args:
- maindir (str): main directory
... | 3dafdc661f933f93fdfdfa9d7279649ce0d08b01 | 3,653,486 |
def abbn_min_vol():
"""
Real Name: b'"Ab-bn min vol"'
Original Eqn: b'25.6'
Units: b''
Limits: (None, None)
Type: constant
b''
"""
return 25.6 | 9fdde32cf832354b9bda9fe23ab000da66205d60 | 3,653,487 |
def clear(self: Client, player: str = None, item_name: str = None,
data: int = None, max_count: int = None) -> str:
"""Clears items from player inventory, including
items being dragged by the player.
Bedrock Edition implementation.
"""
return self.run('clear', player, item_name, data, max... | 3b7975b80f08c1f44c1a49b0a973586859f949bf | 3,653,488 |
def load_glove_embeddings(dim, vocab):
"""
Load GloVe embedding vectors for all words in our vocabulary.
https://machinelearningmastery.com/use-word-embedding-layers-deep-learning-keras/
Parameters
----------
dim : int
Dimension of GloVe embeddings. Can be 50, 100, 200 and 300.
voca... | 63bf52b86efbb20ade43d144fd674bebd8111901 | 3,653,489 |
def check_vat_number(vat_number, country_code=None):
"""Check if a VAT number is valid.
If possible, the VAT number will be checked against available registries.
:param vat_number: VAT number to validate.
:param country_code:
Optional country code. Should be supplied if known, as there is no
... | 142a2dce1def90beed2a222b67f47e9458f97ea0 | 3,653,490 |
def argextrema(y, separate=True):
"""
Deprecated in favor of argrel{min|max} in scypy.signal to get separate
extrema in about the same CPU time.
If you need a list of
all relative extrema in order, using this with separate=False takes about
half the time as by combining the scipy
functions ... | 709c045d608c35c3af5ca29131da8629716a07d5 | 3,653,491 |
from typing import Union
def examine_normal_mode(r_mol: RDKitMol,
p_mol: RDKitMol,
ts_xyz: np.array,
disp: np.array,
amplitude: Union[float, list] = 0.25,
weights: Union[bool, np.array] = True,
... | 96fc2f4153dd231756a88e46ee608a0f54d6dabc | 3,653,492 |
def generate_sprites(factor_dist, num_sprites=1):
"""Create callable that samples sprites from a factor distribution.
Args:
factor_dist: The factor distribution from which to sample. Should be an
instance of factor_distributions.AbstractDistribution.
num_sprites: Int or callable returning int. Number... | 8c09b3fe9916d0d8bc4094d62de3910de800f835 | 3,653,493 |
import warnings
def recode_from_index_mapper(meta, series, index_mapper, append):
"""
Convert a {value: logic} map to a {value: index} map.
This function takes a mapper of {key: logic} entries and resolves
the logic statements using the given meta/data to return a mapper
of {key: index}. The inde... | e8d2afc8536f552e2af277b60af47f8b8c07d961 | 3,653,494 |
def get_variables():
"""Loads ODAHU config as Robot variable
"""
return {'CONFIG': {var: getattr(config, var) for var in config.ALL_VARIABLES}} | 78ae110fdbe2837df00b06e47132b0ceda3648dd | 3,653,495 |
import string
def is_number(char: Text) -> bool:
"""Checks if char is number. Returns Boolean."""
return char in string.digits | 4bec510537057c8f6a48f35c6d0b6d9f300c00b7 | 3,653,496 |
def sliceData(data, slicebox=[None,None,None,None]):
"""
Sum 2d data along both axes and return 1d datasets
**Inputs**
data (sans2d) : data in
slicebox (range?:xy): region over which to integrate (in data coordinates)
**Returns**
xout (sans1d) : xslice
yout (sans1d) : yslice
... | 1d30a500a29c1803eb6982bb7442f9e328e3f245 | 3,653,497 |
def GetChangeUrl(host, change):
"""Given a Gerrit host name and change ID, returns a URL for the change."""
return '%s://%s/a/changes/%s' % (GERRIT_PROTOCOL, host, change) | 61ff03daa28b22ca88ab2b2f67ec18ab9617c691 | 3,653,498 |
def recipe_clone_message(recipe):
"""
Renders the recipe clone message.
"""
return dict(recipe=recipe) | 09728b431966b12415861a212f2cb85af475dc37 | 3,653,500 |
def read_expression_file(file):
"""Reads a file with the expression profiles."""
D = []
genes = []
with open(file) as fp:
firstline = fp.readline()
classes = [c.strip() for c in firstline.split("\t")[1:]]
for line in fp.readlines():
items = [w.strip() for w in line.sp... | aa3465855eb75a731801660e8f7b22091aae0a36 | 3,653,501 |
def train(X, Y, n_h, num_iterations=10000, print_cost=False):
"""
定义神经网络模型,把之前的操作合并到一起
Args:
X: 输入值
Y: 真实值
n_h: 隐藏层大小/节点数
num_iterations: 训练次数
print_cost: 设置为True,则每1000次训练打印一次成本函数值
Return:
parameters: 模型训练所得参数,用于预测
"""
np.random.seed(3)
n_x... | 57efdadd744b9801227da87aed8ca458e2990c5c | 3,653,502 |
def get_drawdowns(cum_returns):
"""
Computes the drawdowns of the cumulative returns.
Parameters
----------
cum_returns : Series or DataFrame, required
a Series or DataFrame of cumulative returns
Returns
-------
Series or DataFrame
"""
cum_returns = cum_returns[cum_retu... | 1f4da9e405b8b4f8a691b09e42e479cd6fdec3ae | 3,653,503 |
def calc_recipe_quantity_ratio(
first_month: str,
first_recipe: str,
second_recipe: str,
file_name: str,
second_month: str = None) -> float:
"""
A function which calculates the ratio of quantity between two months.
:param first_month: str
:param first_recipe: str... | 284fd4c010c933523967a11f774fc7e220198e7f | 3,653,504 |
def teacher_add_to_db():
"""Adds a teacher to database
Returns:
Redirect: Redirects to teachers list route
"""
if request.method == "POST":
fet_name = request.form["fet_name"]
fullname = request.form["fullname"]
teacher_email = request.form["t_email"]
try:
... | 224f95f00e88dce00d21406883dd5655ed9e8fbd | 3,653,505 |
def authorize(app_id, channel_id, team_id):
"""Just double check if this app is invoked from the expected app/channel/team"""
if app_id != SLACK_APP_ID:
return f"app ID {app_id}"
if team_id not in SLACK_TEAM_IDS:
return f"team ID {team_id}"
if channel_id not in SLACK_CHANNEL_IDS:
... | ff1f43a2073e7a0a54bda709b41fce02475c48ec | 3,653,506 |
import random
def deal_one_card():
""" returns a random card from the deck """
cards = [11, 2, 3, 4, 5, 6, 7, 8, 9, 10, 10, 10, 10]
return random.choice(cards) | e8836c6569ed5c9e48043c9b750e730c42781a14 | 3,653,507 |
def grey_pal(start=0.2, end=0.8):
"""
Utility for creating continuous grey scale palette
Parameters
----------
start : float
grey value at low end of palette
end : float
grey value at high end of palette
Returns
-------
out : function
Continuous color palett... | f38295a48120a3e17b000276797bfec78a644749 | 3,653,508 |
from typing import Optional
from typing import Union
from typing import Any
from typing import Dict
def get_parameter_value_and_validate_return_type(
domain: Optional[Domain] = None,
parameter_reference: Optional[Union[Any, str]] = None,
expected_return_type: Optional[Union[type, tuple]] = None,
varia... | be1ab4c90942d69083b765194baa494658265275 | 3,653,511 |
def add_leaf_to_edge(t):
"""
Returns a `Shape` instance with a new root; both a new leaf and the input `Shape` pend from it.
:param t: `Shape` instance.
:return: `Shape` instance.
"""
return Shape([Shape.LEAF, t]) | 18d4a383dcc2873e506677f76501c76e36b99ac7 | 3,653,512 |
def create_simulation(parameter_values=None, experiment=None, make_inputs=False):
"""
Create a PyBaMM simulation set up for interation with liionpack
Parameters
----------
parameter_values : :class:`pybamm.ParameterValues`
The default is None.
experiment : :class:`pybamm.Experiment`
... | 0faf24958440e42b64ef8cc82b9ec478d4899dd2 | 3,653,513 |
def _logistic_loss_and_grad(w, X, y, alpha, mask, sample_weight=None):
"""Computes the logistic loss and gradient.
Parameters
----------
w : ndarray, shape (n_features,) or (n_features + 1,)
Coefficient vector.
X : {array-like, sparse matrix}, shape (n_samples, n_features)
Training ... | 39a05f090807a6eb83000e6daf5f3719bbbe9aa1 | 3,653,514 |
import requests
def verify_status_code(request_response: requests.Response) -> tuple:
"""Verify the status code of the post request to the search url and raise exceptions if the code is unexpected
:type request_response: requests.Response
:return:
"""
if request_response.status_code == 200:
... | b5f686dfe11d7fd4bd9d5f32ccd51df9f2322a13 | 3,653,515 |
def instability_product_graphs(gra):
""" Determine if the species has look for functional group attachments that
could cause molecule instabilities
"""
# Build graphs for the detection scheme
rad_grp_dct = radical_group_dct(gra)
# Check for instability causing functional groups
prd_gra... | 42aba79627bd6343bd2e99bca9a099d1047a9f5c | 3,653,516 |
def build_pdb_rmsd_matrix(pdb_paths, pdb_diff_path=None):
"""
Returns rmsd difference matrix for multiple pdb files.
Returns rmsd_list (3-item list), pdb_comp_amount (int).
Optional with pdb_diff_path return pdb_diff_comp(int).
"""
# make 3 column list or ndarray for x, y = (pdb1-n * pdb1-n) and... | fe00efa6a853d0e77ae52c21267376eca25a110c | 3,653,517 |
from typing import Optional
def expected_response(y: np.ndarray, w: np.ndarray, policy: np.ndarray,
mu: Optional[np.ndarray]=None, ps: Optional[np.ndarray]=None) -> float:
"""Estimate expected response.
Parameters
----------
y: array-like of shape = (n_samples)
Observed ... | ffa6938914480f236d8b0aff7ebc993a2e714682 | 3,653,519 |
def get_type_for_field(field: Field) -> type:
"""
For optional fields, the field type_ is a :class:`typing.Union`, of
``NoneType`` and the actual type.
Here we extract the "actual" type from a Union with None
"""
if not field.sub_fields:
return field.type_
for f in field.sub_fields:... | 2d0163b6e92bcd67c2aaee60d7088cc70e9bd09b | 3,653,520 |
from typing import List
def read_program_data(program: List[str]) -> int:
"""Read program data from port computer system.
Args:
program (List[str]): the program code containing masks and memory
Returns:
int: sum of all values in memory
"""
memory = defaultdict(int)
for line ... | 7852d13f1de9cc04ee4170a10807b49ed2592905 | 3,653,521 |
def get_mgr_worker_msg(comm, status=None):
"""Get message to worker from manager.
"""
status = status or MPI.Status()
comm.probe(source=0, tag=MPI.ANY_TAG, status=status)
tag = status.Get_tag()
if tag in [STOP_TAG, PERSIS_STOP]:
return tag, None, None
Work = comm.recv(buf=None, sourc... | 76bf2be4707052ab5ea0f447822208eccb19f9ef | 3,653,522 |
import time
def retry(exceptions, tries=4, delay=3, backoff=2, logger=None):
"""
Retry calling the decorated function using an exponential backoff.
Args:
exceptions: The exception to check. may be a tuple of
exceptions to check.
tries: Number of times to try (not retry) before... | 8c0917ad45b2c000ced926f0457b9b9aebbc4543 | 3,653,523 |
def load_dictionary(dicttimestamp, server='postgres-cns-myaura'):
""" Load dictionary from database
Args:
dicttimestamp (string): the version of dictionary (ex: 20210131)
server (string): the server name in db_config.ini
Returns:
tuple (termdictparser, pandas.DataFrame): A TermDict... | 63df416815386c1bf4d6a820c98490ae5a6e4d08 | 3,653,524 |
def part1(data):
"""
>>> part1(((20, 30), (-10, -5)))
45
>>> part1(INPUT)
13203
"""
target_x, target_y = data
best = None
for dx in range(1, max(target_x) + 1):
for dy in range(0, - min(target_y) + 1):
hit_target, height = trajectory(target_x, target_y, dx, dy)
... | 293dd006caa20471cc849c1366f0610594279b8b | 3,653,525 |
def get_neighbors(p, exclude_p=True, shape=None, nNeighbors=1,
get_indices=False, direction=None, get_mask=False):
"""Determine pixel coordinates of neighboring pixels.
Includes also all pixels that neighbor diagonally.
Parameters
----------
p : tuple
Gives the coordinate... | 4dc68ed4f44667253c4bdb114a0d3034a65ef725 | 3,653,526 |
import torch
def make_coordinate_grid(spatial_size, type):
"""
Create a meshgrid [-1,1] x [-1,1] of given spatial_size.
"""
h, w = spatial_size
x = torch.arange(w).type(type)
y = torch.arange(h).type(type)
x = (2 * (x / (w - 1)) - 1)
y = (2 * (y / (h - 1)) - 1)
yy = y.view(-1, 1)... | 0bbbd2f0e0d588b58feebce19b3f2fd9c84934d8 | 3,653,527 |
def add_wrong_column(data_frame):
"""
Adds wrong column to dataframe
:params dataframe data_frame:
:returns dataframe:
"""
new_df = data_frame.copy()
new_df['Ducks'] = 0
return new_df | 0f3ae838c0975e8021cfeee258576afac75072c5 | 3,653,528 |
def p2l(X, Y, D, tol, inputTransform):
"""
Computes the Procrustean point-line registration between X and Y+nD with
anisotropic Scaling,
where X is a mxn matrix, m is typically 3
Y is a mxn matrix denoting line origin, same dimension as X
D is a mxn normalized matrix denoting line direction
R i... | 5b7b1143fd7dbbeae6767f8ef5f71464eb6220a0 | 3,653,529 |
def config_database(db_name):
"""
Create a database in sqlite3
:param db_name: The name of the file for the database
:return: A database objetc and his connections object
"""
db = Database()
connection = db.create_connection(db_name)
db.create_table(connection)
return db, connection | 42602f32a3cca0dfbbc791973acbf6279af7cde3 | 3,653,530 |
from pathlib import Path
def parse_main_argument(argument, export_folder):
"""Function parsing the main_argument argument.
Returns a dataframe containing the search terms (or the urls if main_argument is a youtube file."""
# File or string
if Path(argument).is_file():
is_file = True
ar... | f3cbd81e3fe98333fa2a4ad04f746c291dc9138a | 3,653,531 |
from datetime import datetime
def validate_auth_header(headers):
"""Validate and decode auth token in request headers.
This helper function is used in each of the below wrappers, and is responsible to
validate the format of the `Authorization` header where the Lowball token is
supposed to reside.
... | be75c33767a43f1482417277d6a41f887b26f388 | 3,653,532 |
def shared_random_seed():
"""All workers must call this function, otherwise it will deadblock.
"""
seed = np.random.randint(2 ** 31)
all_seeds = all_gather(seed)
return all_seeds[0] | bdf636ddc24defd13339c20fed0bb5896c35400e | 3,653,533 |
def _version(base):
"""Get a chronological version from git or PKG-INFO
Args:
base (dict): state
Returns:
str: Chronological version "yyyymmdd.hhmmss"
str: git sha if available
"""
v1 = _version_from_pkg_info(base)
v2, sha = _version_from_git(base)
if v1:
if... | 2d5b5e08fe44386347541634643e28e86cda5a44 | 3,653,534 |
def average_link_distance_segment(D,stop=-1,qmax=1,verbose=0):
"""
Average link clustering based on a pairwise distance matrix.
Parameters
----------
D: a (n,n) distance matrix between some items
stop=-1: stopping criterion, i.e. distance threshold at which
further merges are forbi... | 1be3da149a5ceb99ab94980b94caec0c42edb096 | 3,653,535 |
def _process_get_set_Operand(column, reply):
"""Process reply for functions zGetOperand and zSetOperand"""
rs = reply.rstrip()
if column == 1:
# ensure that it is a string ... as it is supposed to return the operand
if isinstance(_regressLiteralType(rs), str):
return str(rs)
... | b63de89b480ab263eb49c04dba47befb8bbe0997 | 3,653,536 |
def generic_laplace(input, derivative2, output=None, mode="reflect",
cval=0.0, extra_arguments=(), extra_keywords=None):
"""Multi-dimensional Laplace filter using a provided second derivative
function.
Args:
input (cupy.ndarray): The input array.
derivative2 (callable): ... | bc58a7ca79b551f4cba4c4c61855e027d666f2a0 | 3,653,537 |
import functools
def as_keras_metric(method):
""" from https://stackoverflow.com/questions/43076609/how-to-calculate-precision-and-recall-in-keras """
@functools.wraps(method)
def wrapper(self, args, **kwargs):
""" Wrapper for turning tensorflow metrics into keras metrics """
value, updat... | 17a6a6e39a25576215e0b426779df2ccac48e9b4 | 3,653,538 |
def do_get_video_capture_job(port_output_name: str = 'RAW') -> str:
"""
Function for configure the image retrieval job from video camera.
:param port_output_name: name you want to use for raw image in the application
:return: output image port name
"""
output_raw_port_name = transform_port_name_... | b7965cde58e6b562d289cc58ac25edfd400c3b8a | 3,653,539 |
def vgg8_S(*args, **kwargs):
"""VGG 16-layer model (configuration "D")
Args:
pretrained (bool): If True, returns a model pre-trained on ImageNet
"""
model = VGG(make_layers(cfg['YS']), final_filter=256, **kwargs)
return model | ec3824dbccbbca804ec5160c551bc7171a9b3866 | 3,653,541 |
from typing import IO
def createWords(word_str):
"""Cn Mandarin sentence to Cn Mandarin Words list"""
pre_func = IO.readList(r'docs/pre_punctuation.txt')[1:]
lat_func = IO.readList(r'docs/post_punctuation.txt')[1:]
en_letters = IO.readList(r'docs/special_English_letters.txt')[1:]
words = []
j ... | 7d7aad411773550e6a884539a1160218499dea73 | 3,653,542 |
def get_calib_driver(calib_dir: str):
""" Create left/right charuco point detectors and load calibration images from directory. """
reference_image = cv2.imread("tests/data/2020_01_20_storz/pattern_4x4_19x26_5_4_with_inset_9x14.png")
minimum_points = 50
number_of_squares = [19, 26]
square_tag_sizes... | 1c0b859327fefa983c68b2f70909f5d1ca8108cd | 3,653,543 |
def stop_loading() -> dict:
"""Force the page stop all navigations and pending resource fetches."""
return {"method": "Page.stopLoading", "params": {}} | fd46497cee6a87ca0b00cc6ceed487655361d896 | 3,653,544 |
def drop_duplicates(df):
"""Drop duplicate rows and reindex.
Args:
df (pd.DataFrame): Dataframe.
Returns:
pd.DataFrame: Dataframe with the replaced value.
Examples:
>>> df = pd.DataFrame({'letters':['b','b','c'], 'numbers':[2,2,3]})
>>> drop_duplicates(df)
... | 517d9faf09267df72def3fa7b90b0f59d819d660 | 3,653,545 |
def make_otf(
psf,
outpath=None,
dzpsf=0.1,
dxpsf=0.1,
wavelength=520,
na=1.25,
nimm=1.3,
otf_bgrd=None,
krmax=0,
fixorigin=10,
cleanup_otf=False,
max_otf_size=60000,
**kwargs
):
""" Generate a radially averaged OTF file from a PSF file
Args:
psf (str... | ad3fbdbea7562f766c53f26a82880f41002c893f | 3,653,547 |
import unicodedata
def is_number(input_string):
"""
if input_string includes number only, return corresponding number,
otherwise return input_string
"""
try:
return float(input_string)
except ValueError:
pass
try:
return unicodedata.numeric(input_string)
except... | 2b435b1f23c8764e0ff6bf741678db91bb4a5b23 | 3,653,549 |
def latest_active(name, at_time=None, **kwargs): # pylint: disable=unused-argument
"""
Initiate a reboot if the running kernel is not the latest one installed.
.. note::
This state does not install any patches. It only compares the running
kernel version number to other kernel versions al... | 449819b4abb43b062514f0c8356f3fcd992198f7 | 3,653,550 |
import logging
def upload_file(file_name, bucket, object_name):
"""Upload a file to an S3 bucket
:param file_name: File to upload
:param bucket: Bucket to upload to
:param object_name: S3 object name. If not specified then file_name is used
:return: True if file was uploaded, else False
"""
... | 3db16ca5b2136995f4772dafa3778b54e5e41e5c | 3,653,551 |
def get_conf(bs_info, client_config, genesis_time, setup_oracle=None, setup_poet=None, args=None):
"""
get_conf gather specification information into one ContainerSpec object
:param bs_info: DeploymentInfo, bootstrap info
:param client_config: DeploymentInfo, client info
:param genesis_time: string... | c2d27fa1922be786b0afa9212864465e14ee3de7 | 3,653,552 |
def zeropad(tr, starttime, endtime):
"""
Zeropads an obspy.Trace so as to cover the time window specified by
`starttime`'and `endtime`
Parameters
----------
tr : obspy.Trace
starttime, endtime : obspy.UTCDateTime
Returns
-------
trace : obspy.Trace
Zeropadded c... | 417c17d8dea148f6534f204d064ba13665ede597 | 3,653,553 |
import time
import random
def deepwalk(G, _filepath, o=1, num_walks_node=10, walk_length=80,
representation_size=128, window_size=5,):
"""not going to deal with memory exceeding case"""
output = _filepath + G.name
print("Walking...")
time_start = time.time()
walks = gu.build_deepwalk... | a5b77e6485d29a6a08ca25aa9ea06507a7fae076 | 3,653,554 |
def logship_status(host):
"""Report log shipping retstore delta and latency"""
crit = warn = 0
msg = ''
sql = """SELECT secondary_server, secondary_database, primary_server, primary_database,
last_restored_date, DATEDIFF(mi, last_restored_date, GETDATE()) last_restored_delta,
last_resto... | 7b0ea3282d66dd7d354d4b6d14d54bfd826d85d9 | 3,653,555 |
def dice(y_true, y_pred):
"""
Attention:
y_true can be weighted to modify learning therefore
apply sign to get back to labels
y_pred have to be rounded to nearest integer to obtain labels.
"""
smooth = 1.
y_true_f = y_true.flatten()
y_pred_f = y_pred.flatten()
intersection = n... | 205d7cf0f09f702d7905d42c0dfbbd16738ed1e8 | 3,653,556 |
def get_default_language():
"""
Returns the default language code based on the data from LANGUAGES.json.
"""
for language_code, language_data in MEDICINE_LANGUAGE_DATA.items():
if 'DEFAULT' in language_data:
if language_data['DEFAULT']:
return language_code
r... | 5bbfbc1060e52a4db957afd0eb8b45cdb60036f4 | 3,653,558 |
def triple_triple(r, p=qt.QH([1, 0, 0, 0])):
"""Use three triple products for rotations and boosts."""
# Note: 'qtype' provides a record of what algrabric operations were done to create a quaternion.
return triple_sandwich(r, p).add(triple_2_on_1(r, p), qtype="triple_triple") | 58b529faa97fae29fcc5b481263c0c84af2ddca2 | 3,653,559 |
def _pinv_trunc(x, miss):
"""Compute pseudoinverse, truncating at most "miss" fraction of varexp."""
u, s, v = linalg.svd(x, full_matrices=False)
# Eigenvalue truncation
varexp = np.cumsum(s)
varexp /= varexp[-1]
n = np.where(varexp >= (1.0 - miss))[0][0] + 1
logger.info(' Truncating at ... | fca4f8b7e118c88ed7be37553ede09275f8d06ec | 3,653,560 |
def mog_loglike(x, means, icovs, dets, pis):
""" compute the log likelihood according to a mixture of gaussians
with means = [mu0, mu1, ... muk]
icovs = [C0^-1, ..., CK^-1]
dets = [|C0|, ..., |CK|]
pis = [pi1, ..., piK] (sum to 1)
at locations given by x = [x1... | e907c642e664188cb838e89b889257ded2a5aed9 | 3,653,561 |
from typing import Sequence
def align_chunks(array: da.core.Array, scale_factors: Sequence[int]) -> da.core.Array:
"""
Ensure that all chunks are divisible by scale_factors
"""
new_chunks = {}
for idx, factor in enumerate(scale_factors):
aligned = aligned_coarsen_chunks(array.chunks[idx], ... | df8b845f10bc4a8fa72e1da53d655d25f73d971d | 3,653,562 |
def getWordScore(word):
"""
Computes the score of a word (no bingo bonus is added).
word: The word to score (a string).
returns: score of the word.
"""
if len(word) == HAND_SIZE:
score = 50
else:
score = 0
for letter in word:
score = score + SCRABBLE_LETTER_VALU... | 5d848b5ef5bb0e77d75a866300d9a87b557b5b1b | 3,653,563 |
import requests
import json
def get_lang_list(source_text, key=None, print_meta_data=False):
"""
Inputs:
source_text - source text as a string
key - google api key, needed or function will raise and error
returns list of language identifiers
"""
#set up url request to google translate api... | 720c3c9252535e82881411fa345734d984350537 | 3,653,564 |
def single_value_rnn_regressor(num_units,
sequence_feature_columns,
context_feature_columns=None,
cell_type='basic_rnn',
num_rnn_layers=1,
optimizer_type='SGD',
... | 4290d8b4e5ea069f58b7fc5a5734c16133b1a614 | 3,653,565 |
import uuid
def token():
""" Return a unique 32-char write-token
"""
return str(uuid.uuid4().hex) | f7dc5725cc1d11ee0ab9471d141a89178fa3d07c | 3,653,566 |
def _get_caller_caller_module_name():
"""Return name of module which calls the function from which this function is invoked"""
frame = currentframe().f_back.f_back
return getmodule(frame).__name__ | 4199207922db40424e1a4fa56ee662209de06830 | 3,653,567 |
from typing import Tuple
def percentile(x: np.ndarray, percentile: float = 99) -> Tuple[float, float]:
"""Get the (low, high) limit for the series by only including the data within the given percentile.
For example, if percentile is 99, (1st percentile, 99th percentile) will be returned.
Also, if percen... | 00a7c6561432da84f878985b1e3dba942d4ec478 | 3,653,568 |
from pathlib import Path
def get_versions_data(
hidden=None,
is_unreleased=None,
find_latest_release=None,
sort_key=None,
labels=None,
suffix_latest_release=' (latest release)',
suffix_unreleased=' (dev)',
find_downloads=None,
):
"""Get the versions data, to be serialized to json."... | 4232013fe403b3de54df571e13b881077145b61f | 3,653,569 |
from wheel_filename import InvalidFilenameError, parse_wheel_filename
import json
from datetime import datetime
def wheels(
package_name: str = Argument(..., help="The name of the package to show wheel info for"),
version: str = Argument(
None,
help="The version of the package to show info for... | f57b577426dbd24b86d9eaa91b13c0b048d22afe | 3,653,571 |
def extract_pvdata(h5file, timestamp, pvnames=None):
"""
Extract as a snapshot (PV values) nearest a timestamp from a BSA HDF5 file.
Parameters
----------
h5file: str
BSA HDF5 file with data that includes the timestamp
timestamp: datetime-like, str, int, float
This ... | cd62b347735c97e962c8eec01d4344b4fb4e63f9 | 3,653,573 |
import functools
def decorate_func_with_plugin_arg(f):
"""Decorate a function that takes a plugin as an argument.
A "plugin" is a pair of simulation and postprocess plugins.
The decorator expands this pair.
"""
@functools.wraps(f)
def wrapper(self, plugins_tuple):
return f(self, plugi... | e90c86bfd6c3cada33c867d26ed64da3cac6f9c4 | 3,653,574 |
from datetime import datetime
def datestr(date=None):
"""Convert timestamps to strings in a predefined format
"""
if date is None:
date = datetime.utcnow()
if isinstance(date, str):
date = parse_time(date)
return date.strftime("%y-%m-%d %H:%M:%S") | 36505b926eef6aaa5bcbae011ba90931c20a5067 | 3,653,575 |
def init():
"""Connect to the keyboard, switch all lights off"""
global bufferC # Buffer with the full key/lights mapping
global device
device=hid.device()
# 0x17cc: Native Instruments. 0x1410: KK S88 MK1
device.open(0x17cc, pid)
device.write([0xa0])
bufferC = [0x00] * numkeys
... | 0edc2085cbd6b48fef85d5492e4093551a15aac1 | 3,653,577 |
def compute_acc_bin(conf_thresh_lower, conf_thresh_upper, conf, pred, true):
"""
# Computes accuracy and average confidence for bin
Args:
conf_thresh_lower (float): Lower Threshold of confidence interval
conf_thresh_upper (float): Upper Threshold of confidence interval
conf (numpy.n... | eb338800751de635e6b72213254287554cd34dc0 | 3,653,579 |
import importlib
def multi_backend_test(globals_dict,
relative_module_name,
backends=('jax', 'tensorflow'),
test_case=None):
"""Multi-backend test decorator.
The end goal of this decorator is that the decorated test case is removed, and
repla... | 1006e2bc983f7821138ab27b6d2465055a275c0d | 3,653,580 |
import random
def _get_typed_array():
"""Generates a TypedArray constructor.
There are nine types of TypedArrays and TypedArray has four constructors.
Types:
* Int8Array
* Int16Array
* Int32Array
* Uint8Array
* Uint16Array
* Uint32Array
* Uint8ClampedArray
... | 31eea5c66689584ff38eb8edad3a15231f7cd438 | 3,653,581 |
def _is_valid_requirement(requirement: str) -> bool:
"""Returns True is the `requirement.txt` line is valid."""
is_invalid = (
not requirement or # Empty line
requirement.startswith('#') or # Comment
requirement.startswith('-r ') # Filter the `-r requirement.txt`
)
return not is_invalid | 73b8ad139329698ad334b230cb04976db4ec05ba | 3,653,582 |
from kivy.clock import mainthread
from kivy.app import App
import threading
def execute(cmd):
"""Execute a random string in the app context
"""
_result = [None]
_event = threading.Event()
@mainthread
def _real_execute():
app = App.get_running_app()
idmap = {"app": app}
... | 2ec1850487d854a074dd60642ff38a7ec9fc7e97 | 3,653,583 |
import six
def is_scalar(element):
"""An `is_atomic` criterion. Returns `True` for scalar elements.
Scalar elements are : strings and any object that is not one of:
collections.Sequence, collections.Mapping, set, or attrs object.
```
import nifty_nesting as nest
flat = nest.flatten([1, [2,... | 07f280822a6167ab951942f6e2479476ceec2dc5 | 3,653,584 |
from typing import Union
from typing import Sequence
def wrap_singleton_string(item: Union[Sequence, str]):
""" Wrap a single string as a list. """
if isinstance(item, str):
# Can't check if iterable, because a string is an iterable of
# characters, which is not what we want.
return [i... | 6e0946fee8fddd23631ff66d405dce2ae8a15fa6 | 3,653,585 |
def view_milestone_history(request, chosen_year=None):
"""
http://127.0.0.1:8000/milestones/by-columns/
:param request:
:return:
"""
(chosen_year, basic_query) = get_basic_milestone_history_query(chosen_year)
milestones = basic_query.order_by('due_on')
open_closed_cnts = get_is... | 1d40c08701e9088682e9e0663c1538956b22770c | 3,653,586 |
def M_absolute_bol(lum):
"""Computes the absolute bolometric luminosity
Parameters
----------
lum : `float/array`
luminosity in solar luminosities
Returns
-------
M_bol : `float/array`
absolute bolometric magnitude
"""
log_lum = np.log10(lum)
M_bol = 4.75 - ... | dd3209fd6c91a7b1b51f43a7a15f9c5eaccd740d | 3,653,587 |
def codes_index_get_double(indexid, key):
# type: (cffi.FFI.CData, bytes) -> T.List[float]
"""
Get the list of double values associated to a key.
The index must be created with such a key (possibly together with other
keys).
:param bytes key: the keyword whose list of values has to be retrieved... | 9a0c2c27f917ecfe63ad1f6a797aa152928d294c | 3,653,588 |
from typing import Optional
def lemmatize(
nlp: Optional[Language] = None, name="lemmatize"
) -> ops.base.SpacyBasedOperation:
"""Helper function to return SpacyBasedOperation for lemmatizing.
This operation returns a stream.DataStream where each item is a string after
being lemmatized.
Parameter... | 797efa35320cf4b4e5e1176d1fbbcee13bbaa884 | 3,653,589 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.