content stringlengths 35 762k | sha1 stringlengths 40 40 | id int64 0 3.66M |
|---|---|---|
def put_sns_message(topic, message, subject=None, conn=conn):
"""Send message via Amazon SNS.
:param message: Plain text message
"""
try:
result = conn.publish(topic=topic, message=message)
return result
except Exception, e:
return ('Error: %s' % (e))
sns_error.send(... | d113ce64e0fcc2b47c0b304643619a60d15dbdd1 | 76,327 |
def _rotate(x, degrees):
"""Returns x rotated around the origin by degrees."""
theta = np.deg2rad(degrees)
cos, sin = np.cos(theta), np.sin(theta)
rotation_matrix = np.array([[cos, -sin], [sin, cos]])
return np.matmul(rotation_matrix, x) | f1b7be01d489ac3ff8305d65868eb58024425169 | 76,328 |
def post(url, data={}, headers={}, multipart_files={}, auth=None):
"""Sends a POST request. Returns :class:`Response` object.
:param url: URL for the new :class:`Request` object.
:param data: (optional) Dictionary of POST Data to send with the :class:`Request`.
:param headers: (optional) Dictionary of ... | 7e2ea6b2c3b4c0815026a93a06adc624ad8c3a6f | 76,329 |
import torch
def expand_cholesky_upper(U,B,C):
"""
U : upper cholesky factor of a positive-definite matrix K (n,n)
B : (n,m)
C : (m,m)
Assumes that [K b, b^T c] will be positive-definite
returns : upper cholesky factor of the matrix
K b^T
b ... | 5acdaceb8ab53fa22566e52032d6fc6d149cf731 | 76,331 |
def _translate_ip_xml_json(ip):
"""
Convert the address version to int.
"""
ip = dict(ip)
version = ip.get('version')
if version:
ip['version'] = int(version)
if ip.get('type'):
ip['type'] = ip.get('type')
if ip.get('mac_addr'):
ip['mac_addr'] = ip.get('mac_addr')... | 6c6656e27fe8e67103783f714cb12e75acf82329 | 76,332 |
from datetime import datetime
def is_aware(value: datetime) -> bool:
"""
Determine if a given datetime.datetime is aware.
The concept is defined in Python's docs:
https://docs.python.org/library/datetime.html#datetime.tzinfo
Assuming value.tzinfo is either None or a proper datetime.tzinfo,
v... | 8817706aa6baad1538e6521ddb5fdb2115556af1 | 76,333 |
def read_batch(filenames, batch_size, num_epochs, random=False):
"""
Read single batch.
"""
context_features = {
"lcl": tf.FixedLenFeature([], dtype=tf.int64),
"rcl": tf.FixedLenFeature([], dtype=tf.int64),
"eml": tf.FixedLenFeature([], dtype=tf.int64),
"clean": tf.FixedL... | 8a19bea54a085da04e6bbeb56084b033208ad9b6 | 76,334 |
import numpy as np
def mean_and_error(_data):
"""A helper for creating error bar"""
_data = np.array(_data)
_two_sigma = 2*np.std(_data)
_mean = np.mean(_data)
print(f"{_mean:.0f} +- {_two_sigma:.0f}")
return _mean, _two_sigma | a26cde22d1197e964297e04473df2a309b567f05 | 76,337 |
import string
def sanitizeName(s, validChars=string.ascii_letters+string.digits+'_',
prefix="v", reservedWords=RESERVED_WORDS):
""" Convert an arbitrary string into a valid MATLAB variable name.
:keyword validChars: A string of all valid characters
"""
s = s.strip().encode('a... | 9c0169f3dea70916ee503735859cba4627d7e0f2 | 76,338 |
def compute_class_balanced_weights(labels, beta: float):
"""
:param labels: list of labels
:param beta: make believe hyperparameter
:return:
"""
num_per_class = get_num_per_class(labels)
effective_num = 1.0 - np.power(beta, num_per_class)
weights = (1.0 - beta) / np.array(effective_num)... | 5f0df35a9671a92f2eb8e959b82392ea3bc4223c | 76,339 |
def clone(n:Node, args:Number=None, inpanel:bool=None):
"""
clone(n, args, inpanel) -> Node
Create a clone node that behaves identical to the original. The node argument is the node to be cloned, args and inpanel are optional arguments similar to createNode.
A cloned node shares the exact same properti... | fb2dab34984e082ad3b64846b68a3d4f7b99ef66 | 76,340 |
import struct
def _gencpp_impl(ctx):
"""Implementation for the gencpp rule. Shells out to the sripts
shipped with gencpp"""
srcpath = ctx.files.srcs[0].dirname
outpath = ctx.outputs.outs[0].dirname
# Collect include flags and source files for this package and all its transitive deps.
include_... | 9e4c807e9dc5e2f9b2118c332fcac0ac76c245e7 | 76,341 |
def kube_rootca_update_generate_cert(token, expiry_date=None, subject=None):
"""
Ask System Inventory to kube rootca update generate a cert
"""
api_cmd_payload = dict()
# even if these values are None, they need to be passed to sysinv API
api_cmd_payload['expiry_date'] = expiry_date
api_cmd_... | 799b9b4181990d18bfc8e519653e57bbdb7b85d2 | 76,342 |
def compare_ssim(image_0, image_1, tile_size: int = 7, GPU: bool = True) -> float:
"""
Compute the structural similarity between the two images.
:param image_0: PIL Image object
:param image_1: PIL Image object
:param tile_size: Height and width of the image's sub-sections used
:param GPU: If tr... | 6bd322b45e622fdd8fba8d596644ec5f1368b626 | 76,344 |
def get_date(timestamp):
"""Get date from timestamp.
"""
return date.fromtimestamp(timestamp) | 6b3fd39142e2648323ec49d9fd0bb0a84c18230b | 76,345 |
from datetime import datetime
def community():
"""Community Page that allows users to post a global comment or picture"""
if request.method == 'POST':
user = crud.get_user_by_id(session['user_id'])
global_comment = request.form.get('comment')
timestamp = datetime.now()
com... | 39f5c506ea1fed6d6e9caadf627636bc399509ef | 76,346 |
def multiplication(image, constant):
""" Multiply by constant each input image voxel and return the result.
<gui>
<item name="image" type="Image" label="Image"/>
<item name="constant" type="Float" label="Constant"/>
<item name="result" type="Image" role="return"
... | de2cd3834ccabefd9bb8e9ec45fb3ac56c70a628 | 76,347 |
import collections
def collect_refcount(expression_dags):
"""Collects reference counts for a multi-root expression DAG."""
result = collections.Counter(expression_dags)
for node in traversal(expression_dags):
result.update(node.children)
return result | 7160ac8f3053d3c7532445287950f1081a8b7516 | 76,348 |
def normal_trace(field):
"""
u1 = normal_trace(field, ellipse)
Return the normal trace of the field u along the ellipse.
Parameters
----------
field : Field
Field class
Returns
-------
u_dir : Function
t ↦ ∂ₙu(ε cos(t), sin(t))
"""
c, ξ0 = ellipse_param(1, ... | 6ad11d794fef35cc9c05cecc6a91659d61cda13b | 76,349 |
def wl_egl_window_get_attached_size(wl_egl_window):
"""Destroy the window-egl window
Args:
wl_egl_window (window): The window created with `wl_egl_window_create`
Returns:
(int, int): Width and height
"""
width = ffi.new('int*')
height = ffi.new('int*')
lib.wl_egl_window_get... | 4344edbff1363c4b59c0361f203343fd9f0edfe1 | 76,351 |
from .connect_math import expected_unique
from .monte_carlo import monte_carlo
def test_unique(total, draws, n_senders):
"""Test the calculation of expected unique."""
total_a = np.array([i for i in range(total)])
def gen_random(i):
random = np.random.choice(total_a, draws)
return (rando... | 055ff3921953098a7bf4911d059e6aa8e9b12de8 | 76,352 |
def parse_plim_tail(lineno, indent_level, tail_line, source, syntax):
"""
:param lineno:
:param indent_level:
:param tail_line:
:param source:
:param syntax: an instance of one of :class:`plim.syntax.BaseSyntax` children.
:type syntax: :class:`plim.syntax.BaseSyntax`
:return:
"""
... | e1b899bb95998f2194aa9de708ded43d55a20778 | 76,353 |
def iterClients():
"""
Returns a generator that yields all client key-value pairs.
:rtype: iter
"""
return iter(__clientspecs__.items()) | bb9f48727857e60fb3a69c143ffe51b751d1c0d3 | 76,354 |
def combine_panther_locus_data(panther_list, locus_list):
""" Create dictionary with panther ids and locus objects.
Parameters
----------
panther_list
list of panther objects
locus_list
list of locus object
Returns
-------
dictionary
"""
combined_data = {}... | 2e5c691e3ca97f79a46f346a876150b5a9ed7e4a | 76,355 |
def trace(args, trace_action="tvm.default_trace_action"):
"""Trace tensor data at the runtime.
The trace function allows to trace specific tensor at the
runtime. The tracing value should come as last argument.
The trace action should be specified, by default
tvm.default_trace_action is used.
P... | f53bfc3db707efe98b0d53b130fb55bddf201edc | 76,357 |
def _explicit_module_name(tags):
"""Returns an explicit module name specified by a tag of the form `"swift_module=Foo"`.
Since tags are unprocessed strings, nothing prevents the `swift_module` tag from being listed
multiple times on the same target with different values. For this reason, the aspect uses th... | 88cfba0731e3d1503d6a377150ed12534d7c8688 | 76,358 |
def adaptive_threshold_gaussian(mat, neighborhood_size, bias=0):
"""
Applies an adaptive threshold value, calculated as a weighted sum of neighboring values. The weights are a Gaussian
window. Values above the threshold are set to 255 and values less than or equal to the threshold are set to zero.
:para... | 95dfabaffd8fde005e6df9cdd821a546dcd492ac | 76,359 |
def scan_cluster(inp, cluster_threshold_kruskal = True, cluster_threshold_beta = True, cluster_threshold_vip = True, cluster_threshold_vip_relevant = True, cluster_orientation = 'vertical', cluster_vip_top_number = 50, cluster_mean_area = True, cluster_labelsize_cluster = 12, cluster_figsize_cluster = (10,20)):
"... | c23273668ffb45ff4d2be51e7216cd239a59ad3a | 76,360 |
def value_index_map(array):
"""
Given input array, returns dict with key/values k,i,
where i is the 0-index where value k appeared in the input array
Assumes array elements are unique
Used to get a mapping from pk's of an query set axis to the 0-index
:param array:
:return: dict
"""
... | aa623b0a6fed762caa005506f4729b079f97fbb2 | 76,362 |
def strip_quotes(string: str) -> str:
"""
This function is used as a get_parser for various
parameters in this driver
"""
return string.strip('"') | 4eba25b52d7959bf88e9059663201086a3a00335 | 76,363 |
def t_statistic_of_beta1(x: ArrayLike, y: ArrayLike, beta1: float) -> float:
"""Estimates the t-statistic for the beta1 parameter.
The return value should be used to determine whether the linear regressor
is statistically significant.
Args:
x (ArrayLike): Numpy array or list of floats.
... | a5afd391ec2ddc13bbd6f200d549002a6f86605a | 76,364 |
def combine(wos_final, tb_final, zb_final):
"""This function generates the final, combined dataframe that will be used
to generate the charts and tables to answer the questions of this project.
- It first selects the top 100 journals of each dataframe
- Then concatenates them
- Next, groups them by... | 39d1057d4824733b819a940169d57b518a98f914 | 76,365 |
def Scope( inherit = True, name = None):
"""
Creates a new scope, with new context. Think of it as a nested
casual-make-file.
Shall be used in a 'with statement", example:
with Scope():
Parallel()
Build( someother-casual-make-file)
User can use as many... | 7467ede16a087322a86c6755d06f936b516b06d9 | 76,368 |
def edit_an_item(request, id):
""" Return an existing form for edit """
item = get_object_or_404(Item, pk=id)
if request.method == "POST":
form = ItemEditForm(request.POST, instance=item)
if form.is_valid():
form.save()
return redirect(get_issues_list)
else:
... | beaaaae4ba41133c51ce2e4946ecc74c2da5ab0b | 76,369 |
def plot_calcium_trace(cell_trace, ax=None):
"""
Plot the calcium trace of a cell.
params:
- cell_trace: Calcium trace of a cell
- ax: The axis for the plot. If None, a new plot is created
return:
- The axis of the plot
"""
if ax is None:
fig, ax = plt.subplots(... | d2b63e1a08c553f38e07f3f1a18b1ebf4f58898d | 76,370 |
def initial_prey():
"""
Real Name: b'initial_prey'
Original Eqn: b'50'
Units: b''
Limits: (None, None)
Type: constant
b''
"""
return 50 | ae01003f2c8a5df3c6c2f212c01224959596bc5f | 76,371 |
def file_in_environment_path(string):
"""Gives the path to string, or string.exe
>>> file_in_environment_path('python') == sys.executable or True
True
"""
try:
return files_in_environment_path()[string]
except KeyError:
return file_in_environment_path('%s.exe' % string) | 80f9a56a423ed53c0e228cd1b1d31da4fd8d47ea | 76,372 |
def get_friends(screen_name=SCREEN_NAME, max_friends=MAX_FRIENDS):
"""For a given user, fetches all screen names of users they follow, up to a specified limit"""
friend_names = []
next_page_id = None
page_counter = 0
while True:
page, next_page_id = next_page_of_friends(screen_name, next_pag... | 5a12e1a8c1c6329191248785948b82c0b0a56c06 | 76,375 |
from typing import List
def pd_to_xarray_datacube(df: pd.DataFrame, dim_cols: List[str], value_col: str):
"""
Converts long format data to a datacube, where every dimention is a variable, and each element is one level/unit of that variable
:param df: dataframe to convert
:param dim_cols: column names ... | b6e26ca8b356ec724284029fe4465c1f35dcfd22 | 76,376 |
def check_maybefloat(option, opt, value): # pylint: disable=W0613
"""Custom parser for float numbers which might be also defaults.
"""
value = value.lower()
if value == constants.VALUE_DEFAULT:
return value
else:
return float(value) | 1ce667add870d5cd06f30cae475fbc07d6429d3b | 76,377 |
def create_MS_object(mspath,ack=False,readonly=True):
"""This function aims to speed up other bits of this module,
by returning a ``casacore.tables.table.table`` object.
The trick is, that the ``mspath`` argument can be either a string i.e. the path
to the MS which will be read in and returned, **or**... | aba5bcc459243cd24fefed915a5897c8bfcd64e5 | 76,378 |
import torch
def test_time_augmentation(
model,
regime='loader',
loader=None,
tensors=None,
repetitions=20,
augmenter=None,
tensors_to_augment=None
):
"""
Attempts to measure aleatoric uncertainity through augmentation during test
time. It returns a list of sample-wise confiden... | 12737f8d11751c782734fd0d5263bd49ec366548 | 76,379 |
def routeToGpx(lat1,lon1,lat2,lon2, transport, description="", style="track"):
"""Format a route (as list of nodes) into a GPX file"""
data = LoadOsm(transport)
node1 = data.findNode(lat1,lon1)
node2 = data.findNode(lat2,lon2)
router = Router(data)
result, route = router.doRoute(node1, node2)
if result ... | 57e946b4a700afc55d4249757a2e36e1e7959609 | 76,380 |
import torch
import math
def attention(q, k, v, d_k, mask, dropout, zero_pad, gamma=None):
"""
This is called by Multi-head atention object to find the values.
"""
scores = torch.matmul(q, k.transpose(-2, -1)) / \
math.sqrt(d_k) # BS, 8, seqlen, seqlen
bs, head, seqlen = scores.size(... | e6146e371e09e5a9c56900650feeb770aa99dd20 | 76,381 |
def build_file_delete_url(token, file_id):
"""Returns a URL for the delete file API call
:param token: Slack API token
:param file_id: ID of the file to be deleted
:return: URL
"""
return build_url(token, 'files.delete', file=file_id) | e6d1a6b16308e229c848c41818668d79983a5f4e | 76,382 |
def functional_domains(gene_descriptors, location_descriptors):
"""Provide possible functional_domains input."""
return [
{
"status": "preserved",
"name": "WW domain",
"id": "interpro:IPR001202",
"gene_descriptor": gene_descriptors[5],
"locatio... | a6153f34c1ee241542696ce9638ca7667769af97 | 76,383 |
from datetime import datetime
def ferry_salinity(ferry_data_dir, route_name, dmy, step=1):
"""Load ferry data and slice it to contain only the during route values.
:arg str ferry_data_dir: storage file location for ONC ferry data.
:arg str route_name: name of a ferre route. HBDB, TWDP or TWSB.
:arg... | 7393fcff6387425f12727695fad2461c7fc23527 | 76,384 |
def get_list_index(imageList, index):
"""
This function returns the imageList value at an index
:param imageList:
:param index:
:return:
"""
return imageList[index] | d27319ee73a250421d7f4a68158dcd796c438ba4 | 76,385 |
def permute_all_cls_and_box_to_N_HWA_K_and_concat(box_cls, box_delta, num_classes=80):
"""
Rearrange the tensor layout from the network output, i.e.: list[Tensor]: #lvl tensors of shape (N, A x K, Hi, Wi)
to per-image predictions, i.e.:Tensor: of shape (N x sum(Hi x Wi x A), K)
"""
# for each featur... | ff843c9e0a85212ef98f90a7927b317a4753fde9 | 76,386 |
import inspect
def get_code():
"""
returns the code for the is_isogram function
:return: source code
"""
return inspect.getsource(is_isogram) | a6221f597ade995431ec1e28c4f60ad55f09a1e6 | 76,387 |
import time
def generate_rollout(pi, logp, env,
min_n_samples, max_n_rollouts, max_rollout_len,
with_animation=False):
"""
Collect rollouts until we have enough samples. All rollouts are COMPLETE in
that they never end prematurely: they end either when done is tru... | b6b774b769208a7241af86c9197f56c7c556bdd6 | 76,388 |
def remove_workflow_command():
"""Command that removes the workflow named <name>."""
return Command().command(_remove_workflow).require_clean().with_database(write=True).with_commit() | ad4b46f70f0e20ea1f5ee6fda1250b2f8b44e245 | 76,389 |
import itertools
def auto_name(name):
"""Append number to variable name to make it unique.
Inputs:
name: Initial variable name.
Returns:
Full variable name with number afterwards to make it unique.
"""
scope = tf.contrib.framework.get_name_scope()
vars = tf.get_collectio... | 0a7984da6c362961c0b1644ec9616915bb0dd374 | 76,390 |
def test_multitenant_authentication_not_allowed():
"""get_token(tenant_id=...) should raise when allow_multitenant_authentication is False (the default)"""
expected_tenant = "expected-tenant"
expected_token = "***"
def send(request, **_):
parsed = urlparse(request.url)
tenant = parsed.... | 0362bbc60b89343f6709b1a8b22b5d6ae91f5e11 | 76,391 |
def get_value(key):
"""
call global func to get product value.
Args:
key (str): key.
"""
mode = kernel_exec.get_runtime_mode()
if "cloud" in mode:
product = "1.6"
else:
product = "1.1"
if "Buffer" in key:
f = akg.tvm.get_global_func("cce.product_conf_buf... | d70d216e24c431c440ae268c642e39995923c9dc | 76,392 |
def registeredusers():
"""registeredusers
"""
delete_url = url_for(
'delete',
schema=config['user_schema'],
table=config['user_table'],
subtable=None)
return joined_table_template(
[config.user_table],
'Registered Users',
edit_url=url_for(
... | 82357133f3691571d859aeb6e56fe54477b126b6 | 76,394 |
import copy
import time
def complex_LightGBM_model(X_train, y_train, X_test, log_y=False, GPU_flag=False,
scaler = '', enc_method='label', n_splits=5, verbose=-1):
"""
This model is called complex because it handle multi-label, mulit-class datasets which LGBM ordinarily cant.
Just send in ... | c9ef8015c52bb172464386abc2202c3421c859ab | 76,396 |
def cos_contrib(
emb1: np.ndarray,
emb2: np.ndarray,
):
"""
Cosine contribution function defined in eq. 3 by Timkey & van Schijndel (2021): https://arxiv.org/abs/2109.04404
Args:
emb1 (np.ndarray): Embedding vector 1
emb2 (np.ndarray): Embedding vector 2
Returns:
cos_co... | 432ba0dec1e61b913164229e290c6ac043550c1e | 76,397 |
from typing import Iterable
from typing import Mapping
import logging
def _parse_saved_model_signatures(
model_path: Text,
tag_set: Iterable[Text],
signature_names: Iterable[Text]) -> Mapping[Text, _SignatureDef]:
"""Parse SignatureDefs of given signature names from SavedModel.
Among one or more Meta... | 6d6f089fd6b32bdc5d8f261b2978c766cfe5a911 | 76,398 |
def check_feii_options(input,):
"""
Checks the inputs of the mcmc_options dictionary and ensures that
all keywords have valid values.
feii_options={
'amp_const':{'bool':False,'br_feii_val':1.0,'na_feii_val':1.0},
'fwhm_const':{'bool':True,'br_feii_val':3000.0,'na_feii_val':500.0},
'voff_const':{'bool':True,'b... | 5b522a56a8117321ca48fdf22faabc0aa9bd8958 | 76,400 |
def internal_server_error(error):
""" Handles unexpected server error with 500_SERVER_ERROR """
app.logger.error(str(error))
return {
'status': 'status.HTTP_500_INTERNAL_SERVER_ERROR,',
'error': '"Internal Server Error",',
'message': 'str(error),',
}, status.HTTP_500_INTERNAL_SER... | be79dd1e8ca46792e7c75bed369259610845c74b | 76,401 |
def calc_predicted_points_for_player(
player,
team_model,
df_player,
df_bonus,
df_saves,
df_cards,
season,
gw_range=None,
fixtures_behind=None,
tag="",
dbsession=session,
):
"""
Use the team-level model to get the probs of scoring or conceding
N goals, and player-... | 183022363a943596bf927ecbfaaf0f33577ec78a | 76,402 |
def add_emissions_data(suisse, emissions):
"""map the emissions data to each category in the Suisse dataframe"""
dic = load_dic()
suisse.reset_index(inplace=True)
suisse['emissions_category'] = suisse['subtype'].map(dic)
suisse.emissions_category.fillna(suisse['subtype'], inplace=True)
suis... | 0e35fb00483c9243b6ee767b241291b357213f99 | 76,403 |
from typing import Iterable
from typing import Union
import platform
def generate_repo_names(
team_names: Iterable[Union[str, localreps.StudentTeam, platform.Team]],
assignment_names: Iterable[str],
) -> Iterable[str]:
"""Construct all combinations of generate_repo_name(team_name,
assignment_name) for... | c7a6b2156de577c22dbb13c05e018c7bc33ae89d | 76,404 |
import re
def _fix_global_ids(html):
"""Fix the global_ids after reordering in _render_toc()."""
html = re.sub(r'id="\d+"', 'id="###"', html)
global_id = 1
while len(re.findall('id="###"', html)) > 0:
html = re.sub('id="###"', 'id="%s"' % global_id, html, count=1)
global_id += 1
re... | fd7593f95ef000dc7aaeb60cee7b8fd9e274b12b | 76,405 |
def logNorm(
x : Tensor,
mu : Tensor,
logvar : Tensor,) -> Tensor:
"""
gives log of the density of the normal distribution.
element-wise, no reductions.
"""
y = -0.5 * (log(2 * pi) + logvar + (x - mu).pow(2) / logvar.exp() )
return y | 9f5f46a4a9bc221d271ad8d8445df78f142bbb97 | 76,406 |
def roi_to_gwmi(img,brain_wm,nth):
"""Transform the functional roi to wm.
Algorithm: find the nearest wm voxel.
"""
#st = time.time()
data = img
wmdata = imt.multi_label_edge_detection(brain_wm)
shape = data.shape
roi_ids = np.unique(data)
roi = roi_ids[1:]
roi = [int(i) for i ... | ccd00f93960840946b41c669d0c82759172d3295 | 76,407 |
def substract(x, y):
"""substract two numbers."""
return y - x | 07854a7c3fdc61d97e888358e2a14dae1c3b673b | 76,408 |
def stefanboltzman(temperature, type='e'):
"""Stefan-Boltzman wideband integrated exitance.
Calculates the total Planck law exitance, integrated over all wavelengths,
from a surface at the stated temperature. Exitance can be given in radiant or
photon rate units, depending on user input in type.
A... | b9d88f60161e798fd7606e5013e1a43ecfbfdfe5 | 76,409 |
def delete(mod, id):
""" Delete the record for Model indicated by 'mod' with a primary key of 'id'. """
Model = mod_lookup.get(mod, None)
if not Model:
return f"No such route: {mod}", 404
Model.query.filter_by(id=id).delete()
db.session.commit()
return redirect(url_for('all', mod=mod)) | c36013b5f3a13d59eedf648cdd85737333149c31 | 76,410 |
from re import T
def checkio(anything):
"""Try to return anything else :)."""
return T(anything) | 3a4104dc3cbe0306888e50fb8ac49d3c0b6904b6 | 76,411 |
def predict_with_preprocessing(model, b64_image_string: str) -> np.ndarray:
""" Apply necessary preprocessing to conver b64 image string to image values, preprocessing to
the image values and finally predict bounding boxes and labels with the preprocessed image
values
"""
image, scale = apply_image_... | 6d8b18317b945a3a5c03ad34ddc7f93a01fd6768 | 76,412 |
def label_wavepr_dataset(year_symbols, label_dic, info_dic):
"""Label a whole year-symbol dataset.
Args:
year_symbols: The key list.
label_dic: The target dict to be modified.
info_dic: The information dict used for labeling.
Returns:
The label count for each category.
""... | 45327c19efca0c58b6b831e3f9b8eac1c365fb6e | 76,413 |
def get_synthesis_router():
"""
Generate the router for the Synthesis API.
:return: Synthesis Router
:rtype: :class:`routers.DefaultRouter`
"""
router = routers.DefaultRouter()
if settings.BASIN3D["SYNTHESIS"]:
router.register(r'datasources', DataSourceViewSet, base_name='datasourc... | ff50278e06b953dc3e85b516ba53a796551a6ac0 | 76,414 |
def gnomad_link(variant_obj, build=37):
"""Compose link to gnomAD website."""
if build == 38:
url_template = (
"http://gnomad.broadinstitute.org/variant/{this[chromosome]}-"
"{this[position]}-{this[reference]}-{this[alternative]}?dataset=gnomad_r3"
)
else:
ur... | 6423bc40abbae2a037bb5d416746a3ce7207ba32 | 76,415 |
def _build_word_list():
"""
Builds a set of valid English words.
"""
all_words = set()
for filepath in WORDS_FILEPATHS:
with open(filepath) as words_file:
some_words = [word.strip() for word in words_file.readlines()]
all_words |= set(some_words)
return all_words | 3dee8766458e0345210c3f0ea7a19f798249cb56 | 76,416 |
from typing import Callable
def get_freq_label(date_value: str, freq: str) -> Callable:
"""Gets frequency label for the date value.
Args:
date_value (str): The date value.
freq (str): The frequency value specifies how the date field should be aggregated,
by year, quarter, month, w... | 22ea07232a0be25c6462d7c7fb380f8facf76f7e | 76,417 |
def gmst00(uta, utb, tta, ttb):
""" Greenwich mean sidereal time, consistent with IAU 2000 resolutions.
:param uta, utb: UT1 as a two-part Julian date.
:type uta, utb: float
:param tta, ttb: TT as a two-part Julian date.
:type tta, ttb: float
:returns: Greenwich mean sidereal time in radians ... | 0b1d293b1db0a504fca4fde75d33c7f6ae3d7ef9 | 76,418 |
def get_vos_xml():
"""
Returns the serialized xml (as a string)
"""
to_output = get_vos()
return anymarkup.serialize(to_output, 'xml').decode() | 59b6b0624f68f1ea58aa99feea5959559f40d81d | 76,419 |
def _input_type(param, dim, dtype, name):
"""Checks if the input parameter is a callable or piecewise constant."""
# If the parameter is callable but not a piecewise constant use
# generic sampling method (e.g., Euler).
sample_with_generic = False
if hasattr(param, 'is_piecewise_constant'):
if param.is_pi... | 3612dc0b85b5edb731827654f6c499c3940dc60c | 76,420 |
def question_cleaner(df_query):
"""
used in the notebook "model_funetuning" for insuranceQA dataset to extract those questions which have answers
Parameters:
df_query: all the questions and answers
Returns:
only questions that have answers
"""
kb=([int(xx) for xx in (df_query[3].iloc[... | ba294e7adebf9ddc56249406ee3c6ce2e7fc8068 | 76,421 |
from typing import Dict
from typing import Any
def metadata_to_program(metadata: Dict[bytes, Any]) -> Program:
"""
Convert the metadata dict to a Chialisp program
:param metadata: User defined metadata
:return: Chialisp program
"""
kv_list = []
for key, value in metadata.items():
k... | 52d6910e85d580ae63bda7f0ee76fec70f8a2d62 | 76,422 |
from operator import sub
def cleanup_comments(comments):
"""
Cleans up the given comments.
:param comments: List containing all the comments for a specific section
:return: List with the comments cleanup up
"""
clean_comments = []
if comments:
for comment in comments:
... | a7a7a7aacba637513223c69aa06f4c50ef52e1a3 | 76,423 |
def ask_user_for_master(pts):
"""
Prompt the user for the master password. Bail after 3 attempts.
Args:
pts (PassTheSalt): the PassTheSalt instance calling this function.
Returns:
str: the master password.
"""
for _ in range(3):
master = prompt('Enter master password', ... | 7e1c08df7000bbb60c590c20c0e3214726a5e307 | 76,424 |
def access_info_get_all(context, marker=None, limit=None, sort_keys=None,
sort_dirs=None, filters=None, offset=None):
"""Retrieves all storage access information.
If no sort parameters are specified then the returned volumes are sorted
first by the 'created_at' key and then by the '... | 4b1d73fdfe248f4f89255c7720c333eff914e947 | 76,426 |
def init_landmarks(num_lm, c=None):
"""
construct map of landmarks will all locations at ``c`` with IDs in range
``[0, num_lm]``.
"""
if c is None:
c = EigenArray.from_iterable([0, 0, 0])
d = {}
for i in xrange(num_lm):
d[i] = Landmark(loc=c)
return LandmarkMap.from_dict(... | b20d7c966850138270502159334e8f395c833478 | 76,428 |
def rescale_multivariate_data(data, scaling_values=None):
"""
Converts raw data into normalized values for each channel and then rescales the values from -1 to 1.
Args:
data: ndarray of shape (examples, y, x, variable)
Returns:
Normalized data, values used for scaling
"""
norme... | 1ebdc7e19a21b1bb1751a8c9d47fe3b7608f1713 | 76,429 |
def basis_funs_all_ders( knots, degree, x, span, n ):
"""
Evaluate value and n derivatives at x of all basis functions with
support in interval [x_{span-1}, x_{span}].
ders[i,j] = (d/dx)^i B_k(x) with k=(span-degree+j),
for 0 <= i <= n and 0 <= j <= degree+1.
Parameters
-------... | 444ee84e61ab80745a4d62b3e3618a66429ba43a | 76,430 |
def combine_files(c3d_file, mat_file, postfix='_Updated'):
""" Combine a c3d file with the 'RefPoints' markers from a corresponding
mat file
"""
c3dacq = open_acqusition(c3d_file)
acq_frames = c3dacq.GetPointFrameNumber()
matobj = loadmat(mat_file, struct_as_record=False, squeeze_me=Tr... | 4b606c9732a3d403d23a54022ef19666b90eb7ad | 76,431 |
import yaml
def load_config(config_path):
"""Loads parameters into the dict from the specified path.
:param config_path: Path to config file
:return: Dictionary with parameters
"""
with open(config_path, 'r') as config_file:
config_values = AttributedDict(yaml.load(config_file, Loader=ya... | bb2ffa7542f7e8d7842bc8dc636fca249c41b0b2 | 76,432 |
def detector_drift_adjust_aps_1id(imgstacks,
slit_cnr_ref,
medfilt2_kernel_size=3,
medfilt_kernel_size=3,
ncore=None,
):
"""
Adjust each still... | 87c4cedd9820d4fcc8e97b9069f68f088317f737 | 76,433 |
import torch
def move_palm_to_wrist(joints: torch.Tensor) -> torch.Tensor:
"""Reverts palm keypoint to wrist's position.
Args:
joints (torch.Tensor): [description]
"""
palm = joints[JOINTS.mapping.ait.wrist]
index_mcp = joints[JOINTS.mapping.ait.index_mcp]
wrist = 2 * palm - index_mcp... | 8303b193d07887a31b4ca0558905b7e9cd379cee | 76,434 |
from typing import List
def get_experiment_numbers(start: int, end: int, step: int) -> List[int]:
"""Return a list of sequential image numbers given start, end and step."""
experiment_numbers = list(range(start, end + 1, step))
return experiment_numbers | cb27207ade91158a77a9ba4fb927c08ba67fcd5d | 76,435 |
def format_latex_num(number, prec=3, trans = -3):
"""Return a strong formatting a number as, eg 3.1 x 10^4"""
if number == 0.:
return "$0$"
exponent = int(np.floor(np.log10(number)))
if 1 >= exponent > trans:
forstr = "$ {0:."+str(prec)+"f} $"
return forstr.format(number)
els... | ccce750d43f1f286bc4991ecae6dcb15c1303fa9 | 76,436 |
import requests
def is_online():
"""Returns True if devices can communicate on internet.
"""
for time_out in (2,5,10,15):
try:
# connect to the host -- tells us if the host is actually
# reachable
s = requests.adapters.socket.create_connection(("www.google.com",... | 71c1a6bb7d94639d392b072be6d48beb2eefd8c4 | 76,437 |
def data_ready(req, cache):
"""
Checks that all required data are in the data_cache
:param req: string or list of string containing the keys of
required data in cache
:param cache: dictionary with the computed data
:return: Boolean indicating whether all required data are in cache
"""
i... | 6da2c174802edafca67c2e196eaedb80aa6812d3 | 76,438 |
import torch
def argmax_mae(output, target):
"""age range, categorized by [0-12, 13-18, 19-25,
26-35, 36-45, 46-55, 56-65, >= 66]"""
with torch.no_grad():
batch_size = output.size(0)
predicted_age_ranges=torch.argmax(output,1)
mae=torch.sum(torch.abs(predicted_age_ranges-target)).f... | eafb7c069c4ac37875bea25cca442126c2c6e08f | 76,439 |
from typing import Sequence
from typing import Iterable
from typing import Dict
from typing import DefaultDict
from typing import List
def assign_data(centroids: Sequence[Centroid], data: Iterable[Point]) -> Dict[Centroid, Sequence[Point]]:
"""Assign data the closest centroid"""
d: DefaultDict[Point, List[Poi... | 99dd92f8b25b1f5159ebc328eeea3f20640196f0 | 76,440 |
from typing import List
def make_random_clusters(cluster_sizes: List[int]) -> List[int]:
"""
Assign cluster labels randomly
:param cluster_sizes: list where each index is the cluster label
:return: list with an assigned cluster label per point
"""
labels = list(range(len(cluster_sizes))) # to... | 2c84ad61aeb9fc19027efbc3398c9a2b59adf69b | 76,441 |
def parallelize(n_jobs, func, **kwargs):
"""
Creates joblib-style parallelization function if joblib is available
Parameters
----------
n_jobs : int
Number of processors (i.e., jobs) to use for parallelization
func : function
Function to parallelize
kwargs : key-value pairs
... | 48349c7ef97728f961ffae36867b26e54b5e410b | 76,442 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.