content stringlengths 35 762k | sha1 stringlengths 40 40 | id int64 0 3.66M |
|---|---|---|
from typing import List
def find_anomaly_periods(
data: pd.DataFrame,
time_column: str = "TimeGenerated",
period: str = "1H",
pos_only: bool = True,
) -> List[TimeSpan]:
"""
Merge adjacent anomaly periods.
Parameters
----------
data : pd.DataFrame
The data to process
t... | cd7a77ecfae16bd96f794f294be4f49af08e7552 | 3,612,900 |
def intf_Contain(*args):
"""
* Compute if the triangle <P1> <P2> <P3> contain <ThePnt>.
:param P1:
:type P1: gp_Pnt
:param P2:
:type P2: gp_Pnt
:param P3:
:type P3: gp_Pnt
:param ThePnt:
:type ThePnt: gp_Pnt
:rtype: bool
"""
return _Intf.intf_Contain(*args) | edb64c467c415f36219ac48e082c67416f8fb43a | 3,612,901 |
def _generate_image_and_label_batch(image, label, min_queue_examples,
batch_size, shuffle):
"""Construct a queued batch of images and labels.
Args:
image: 3-D Tensor of [height, width, depth] of type.float32
label: 1-D Tensor of type.int32
min_queue_examples: int32, ... | e60dc325ea0fd69b86fa07ba87e8e222be21613c | 3,612,902 |
def rgb2gray(rgb):
"""
Convert a RGB image to a grayscale image
Differences from cv2.cvtColor():
1. Input image can be float
2. Output image has three repeated channels, other than a single channel
Args:
rgb: Image in RGB format
Numpy array of shape (h, w... | 395342e337d8e56efa5eef766c82b9300ad05a5b | 3,612,903 |
import re
def glsl_parse_preprocessor(source):
"""Parse preprocessor line."""
match = re.match(r'^\s*#\s*(\S+)\s+.*$', source)
if match:
if match.group(1) in g_directives:
return GlslBlockPreprocessor(source)
return None | 3999beb9aea829b0059d324ac4d87e8bbc4438eb | 3,612,904 |
def print_ofpt_packet_out(msg):
"""
Args:
msg: OpenFlow message unpacked by python-openflow ; PAGE 107 MANUAL
"""
print('PacketOut: buffer_id: %s in_port: %s actions_len: %s' %
(hex(msg.buffer_id.value),
green(dissector.get_phy_port_no(msg.in_port.value)),
... | a5f459e835b168480e1cd3c6fdeea1ebd7601bdb | 3,612,905 |
def convert_to_example_temporal(
image_datas,
image_paths,
image_shapes,
labels,
centers,
gt3ds,
scale_factors,
start_pts,
cams,
poses=None,
shape=None,
phis=None,
image_datas_og=None,
time_pts=None):
"""... | 9ce82538e5dc68b64ec171b7b26723fea3923d3c | 3,612,906 |
import os
def newchart(data):
"""
Determines the environment for generating a timeseries chart. Call this function
"""
# response metadata items
meta = {
'variable': data['variable'],
'loc_type': data['loc_type']
}
for item in nldas_variables():
if item[1] == data['... | 257f66405fd6845519b306a80c3ee750aad06c7d | 3,612,907 |
def conformance(source):
"""
Creates a function that does a shallow comparison between a given object and the `source`
dictionary using :func:`conforms`.
Examples:
>>> conformance({'a': 1})({'b': 2, 'a': 1})
True
>>> conformance({'a': 1})({'b': 2, 'a': 2})
False
Arg... | 9c4c56e7ce5de819b6392a3c3ac734298fdb0896 | 3,612,908 |
from typing import Optional
def stack_v1(
x: tf.Tensor,
filters: int,
blocks: int,
stride1: int = 2,
dilation_rate: int = 1,
name: Optional[Text] = None,
) -> tf.Tensor:
"""Create a set of stacked ResNetv1 residual blocks.
Args:
x: input tensor.
filters: integer, filte... | 7d5674589147fe2797126cb02c085b259e04aedc | 3,612,909 |
import torch
def get_params(model):
"""Aggregates model parameters of all linear layers into a vector.
Args:
model: A (pre-trained) torch.nn.Module or torch.nn.Sequential model.
Returns:
The aggregated parameters.
"""
weights = list()
biases = list()
for module in model.m... | c6a66f3a013f62e79e51f47d130e65b12b38ff33 | 3,612,910 |
def as_series(alist, trim=True) :
"""Return arguments as a list of 1d arrays.
The return type will always be an array of double, complex double. or
object.
Parameters
----------
[a1, a2,...] : list of array_like.
The arrays must have no more than one dimension when converted.
trim ... | 4117ec228be723b4d445eaa1d8f67a7ce303c134 | 3,612,911 |
import math
def hist16bit(array, bins=64, step=None, low=None, high=None, use_numba=True):
"""
stepsize should be power of 2
array should be 8 or 16 bit integer
"""
if array.dtype == 'uint8':
length = 256
offset = 0
elif array.dtype == 'int8':
length... | d18dde94e5d947407741d7acf82a0f6f459903bf | 3,612,912 |
import requests
def get_circ_supply_on_chain(chain:str):
"""
chain: Allowed: ethereum ┃ avalanche ┃ bsc ┃ polygon ┃ arbitrum ┃ fantom ┃ harmony ┃ boba ┃ optimism ┃ moonriver ┃ aurora
direction: Allowed: in ┃ out
"""
chain = chain.lower()
chains = ["ethereum", "avalanche", "bsc", "polygon", "... | 3ed143a35d697c52f42696f14dfa8ea3c90c712b | 3,612,913 |
def test(epoch, max_epoch):
""" Test model
"""
loss_meter = AverageMeter()
acc_meter = AverageMeter()
for ind, (x, target) in enumerate(testing_loader):
# x is NxCxHxW => WxNx(HxC)
x = preprocess_data(x)
act_lengths = get_seq_length(x)
# target is a list of `torch.In... | 74f038b9c38cbaaaff70fb64fa146454a1e7309a | 3,612,914 |
from typing import List
def find_response(triggers: List[Trigger], message: str, is_gauchito: bool):
"""
Returns the first matching trigger in a list of triggers given the message contents and whether or not the author
is a gauchito.
Returns None if the message matches none of the triggers
"""
... | 5f78dd309bee3b16ecd87cd5f16d116dc2f5cd86 | 3,612,915 |
from typing import List
def create_sql_endpoint_class(
name: str,
method: str,
url: str,
sql: str,
repository: DataRepository,
query_parameters: List,
tags: List,
request_schema: type = None,
response_schema: dict = None,
description: str = None,
is_from_template: bool = Fa... | 4f96eb7042885699612cd5d25ec0274d9f7bd714 | 3,612,916 |
def loss(logits, labels):
"""Add L2Loss to all the trainable variables.
Add summary for "Loss" and "Loss/avg".
Args:
logits: Logits from inference().
labels: Labels from distorted_inputs or inputs(). 1-D tensor
of shape [batch_size]
Returns:
Loss tensor of type float.
"""
# Calculate... | 4b743f554123776fe8240ab273de997c1b967488 | 3,612,917 |
def make_production_app():
"""
Configure logging before creating the application. Useful with application servers, where it's pretty impossible to
run code other than the app factory.
:return: standard app created by make_app
"""
configure_logging()
return make_app() | f3dc6118ae55b2706e174924a89bd64c55429f3e | 3,612,918 |
from re import IGNORECASE
def high_light(pattern, content, option):
"""
Will find pattern every pattern in content ignore upper or lower
and highlight that pattern in content
"""
patterns = findall(pattern, content, IGNORECASE) if option != '--case-sensitive' else findall(pattern, content)
for... | b83a363ea82e61ef022d7937ca0c71dcc5159867 | 3,612,919 |
def _lst_for_pes(pes_dct, run_pes_idxs):
""" Get a dictionary of requested species matching the PES_DCT format
"""
red_pes_dct = {}
for (form, pidx, sidx), chnls in pes_dct.items():
# Grab PES if idx in run_pes_idx dct
run_chnl_idxs = run_pes_idxs.get(pidx, None)
if run_chnl_idx... | 75307b871588b5a9c04a95e29c315c7528fc1259 | 3,612,920 |
def cholesky_decomposition(matrix):
"""
Compute the Cholesky decomposition of a symmetric positive definite matrix
"""
# compute the decomposition
gsl.linalg_cholesky_decomp(matrix.data)
# and return the matrix
return matrix | 1d15a86aeb579985f0c46df3c250c7eac6aa2e31 | 3,612,921 |
def _cvt_names_to_graph(srcpath, destpath):
"""Translates model pathnames into pathnames in term of
our 'fake' graph nodes @xin, @bin, @bout, and @xout.
"""
srcvar, _ = _split_expr(srcpath)
srccompname, _, srcvarname = srcvar.partition('.')
destcompname, _, destvarname = destpath.partition(... | 47cb7a50e2a20515cd012c90eb00f372e187db79 | 3,612,922 |
from . import dirty
import click
import functools
import sys
def jobs_command(num_jobs=-1, dirty_flag=False, allow_unknown=False,
default_to_all=True):
"""
Base options for jobs that take a list of jobs names.
Expects a *base_dir* argument, so normally used after ``@repos_command``.
... | a5143e294fb6a6ac263cd292a466503b27844cef | 3,612,923 |
import math
def math_pow(x, y):
"""Implement the SQLite3 math built-in 'pow' via Python.
"""
try:
return math.pow(x, y)
except:
pass | d8e1ad37b0fc2f0df6f525cae282478417a919b7 | 3,612,924 |
def grid_search(estimator, param_grid, X_train, y_train, X_test, y_test, batch_size=10000, nn=False):
""" Performs grid search over parameter grid.
Function iterates over the combinations of parameters in the parameter grid. Trains the estimator on the X_train.
Evaluation is done on both the training set a... | 2cb0a85ead51c0aacbfc6989e76a7948a9101a59 | 3,612,925 |
def get_voted_content_for_user(user):
"""Returns a dict where:
- The key is the content_type model
- The values are list of id's of the different objects voted by the user
"""
if user.is_anonymous():
return {}
user_votes = {}
for (ct_model, object_id) in user.votes.values_li... | 799eff5efd184da0b5121f59025c39d0ddb593a3 | 3,612,926 |
def get_bbx_from_seg(label):
"""
Get a bounding box from a binary mask
"""
border_list = [-1, 40, 80, 120, 160, 200, 240, 280, 320, 360, 400, 440, 480, 520, 560, 600, 640, 680]
img_width = 480
img_length = 640
rows = np.any(label, axis=1)
cols = np.any(label, axis=0)
rmin, rmax = n... | 0cd040a9e37ee8808bc8fa7b79d3ce8cd26e60f9 | 3,612,927 |
def odd_occurences_in_array(a):
"""
Finds the odd number of occurences of an element in an array.
XOR of all elements gives us odd occurring element.
Note that XOR of two elements is 0 if both elements are same and XOR of a number x with 0 is x
:param a
"""
result = 0
for number in a:
... | 8085fb8ffa5df9628caa5fef541b5d7b78c372b0 | 3,612,928 |
def new_pm():
""" function that is called when you visit /portfolio_manager/new, creates a new PM """
token = request.headers.get("token")
headers = {"Content-type": "application/x-www-form-urlencoded", "token": token}
message, info = verify_token(token)
if message != None:
return create_... | 8d46547351ef0650a0189a2a039d42afa6374584 | 3,612,929 |
def _data_aug_fn(image, ground_truth):
"""Data augmentation function."""
ground_truth = cPickle.loads(ground_truth)
ground_truth = list(ground_truth)
annos = ground_truth[0]
mask = ground_truth[1]
h_mask, w_mask, _ = np.shape(image)
# mask
mask_miss = np.ones((h_mask, w_mask), dtype=np.... | 2ed7a1c6ffd8445816ddeb5e55d0a6aec0f583ac | 3,612,930 |
import array
def to_envelopes(path,num_bands,freq_lims,downsample=True):
"""Generate amplitude envelopes from a full path to a .wav, following
Lewandowski (2012).
Parameters
----------
filename : str
Full path to .wav file to process.
num_bands : int
Number of frequency bands ... | e66ee3e5cab282247b4ce91f5834641fa966a447 | 3,612,931 |
def separe_liste(points):
"""
Parameters
----------
points : TYPE
DESCRIPTION.
Returns
-------
points_1 : TYPE
DESCRIPTION.
points_2 : TYPE
DESCRIPTION.
"""
centroide = trouver_coordonnees_centroide(points)
distances = []
for point in points:
... | 22a50b79744119814ba723c13335bda6767ce045 | 3,612,932 |
def fdq(node_results, Qstar, average_times=False, average_nodes=False):
"""
Compute fraction delivered quality (FDQ), equations modified from [1].
The metric can be averaged over times and/or nodes.
Parameters
----------
node_results : pd.Panel
A pandas Panel containing node result... | b27be4f8dc1d40d9fee2ee901f43f0a256d35f02 | 3,612,933 |
import time
import random
import json
def lambda_handler(event: dict, _context: dict):
"""Sample Lambda function that notifies back the Step function that invoked it,
using the Task Token id passed along with its payload
Parameters
----------
event: dict, required
Input event to the Lambd... | 0cb0c0b042bf886d953a8b5310f16409f3d26332 | 3,612,934 |
import yaml
def read_documents(*paths, uri=False):
"""
Read and parse documents from the filesystem or remote URLs (yaml or json).
Note that a single yaml file can contain multiple documents.
This function will load any dates in the documents as strings. In
Data Cube we store JSONB in PostgreSQL... | c81beb6a90105cbc7288d5910a67091c86867c74 | 3,612,935 |
def delete_service(service_handle):
"""See: DeleteService function
https://msdn.microsoft.com/en-us/library/windows/desktop/ms682562(v=vs.85).aspx
"""
DeleteService_Fn = windll.Advapi32.DeleteService #BOOL WINAPI DeleteService(
DeleteService_Fn.argtypes = [ #
wintypes.SC_HANDLE # _In_ SC_HANDLE hServ... | 3f5cb513e3fde57982472f3744cba22b175151aa | 3,612,936 |
def dns_installation(instance, arg, verbose=True):
""" Install bind9 package on the remote instance and configure name resolution for his own domain name """
if install(instance, {"module":"bind9"}, verbose=False) == 1:
return 1
# execute_command(instance, {"command":["truncate", "-s", "0", "/etc/bi... | aa2825e60d8ebbe16064858e370646431389de06 | 3,612,937 |
import collections
def get_inv_aliases():
"""Return a mapping from target to list of sources for all alias
targets in either the default alias table or the unknown_flag alias
table."""
inv_aliases = collections.defaultdict(list)
standard_aliases = add_aliases.read_default_emoji_aliases()
for k, v in sta... | c2d8f4b44503b0fd17cae73c5757d3126ae92289 | 3,612,938 |
from typing import Union
from typing import List
from typing import Tuple
def region_expand(
region: RegionLike,
expansion: Union[int, List[int], Tuple[int, int]],
) -> Union[Tuple[int, int], sublime.Region]:
"""
@brief Expand the region by given amount.
@param region The region
@param exp... | 0b2db5cbc5810290c073cb8cae3d6c032286ac83 | 3,612,939 |
def median(embedding, neighbors, verbose=False):
"""Initialize points onto an existing embedding by placing them in the
median position of their nearest neighbors on the reference embedding.
Parameters
----------
embedding: TSNEEmbedding
neighbors: np.ndarray
verbose: bool
Returns
... | 29af122e2b04f712ea4d0e0c8fcfd72341d6bce6 | 3,612,940 |
def check_file_tab(file_name):
"""
Check if any files contain tabs and return the number of tabs.
"""
f = open(file_name, "r+b")
key_positions = []
for num, line in enumerate(f, 1):
if b'\t' in line:
key_positions.append(num)
if len(key_positions) > 0:
# If there... | dc9cc0a7454bc0c63c67d260feb1a0e071157260 | 3,612,941 |
def checkExtention(files):
"""
This function will check extention of each file.
"""
for file in files:
if file.name.lower().split(".")[-1] not in ['pdf', "jpeg", "png", "jpg"]:
return file.name + " is not accepted. We accept only 'pdf', 'jpeg', 'png', 'jpg' file format."
return ... | 247f43087d9e85d360900c5da2b8bfa1581117ef | 3,612,942 |
def accuracy(output, target, topk=(1,)):
"""Derived directly from the reference NIPS2017 Workshop.
Computes the precision@k for the specified values of k, used for semi-supervised learning.
"""
maxk = max(topk)
batch_size = target.size(0)
_, pred = output.topk(maxk, 1, True, True)
pred = p... | 00b77a713e5ab26d7614981666eb35e111dde992 | 3,612,943 |
def merge_pairs(seq1,
seq2,
qual1,
qual2,
ins1=None,
ins2=None,
q_cutoff=10,
minimum_q_delta=5):
"""
Combine paired-end reads into a single sequence.
Manage discordant base calls on the basis of ... | 0e3863359488aceca8ae388a5b672c22842188b8 | 3,612,944 |
def activation_func(func_type, z):
"""
Implements the different kind of activation functions including:
sigm - sigmoidal
tanh - hyperbolic tangent
relu - Rectfied
step - Heavside (binary step 0 or 1)
"""
if func_type == 'sigm':
return (1 / (1 + np.exp(-z)))
... | 2e4cd2e4679beb54f1f34f3e2985167ef99978d8 | 3,612,945 |
import sys
import os
def get_check_option():
"""
得到和检查用户输入的参数,返回参数对象
"""
logger.debug(sys.argv)
usage = 'usage: python %prog [options]' \
'\nsample1:python %prog --host="127.0.0.1" --username="root" --port=43306 --password="" --schema=test --table="test5"' \
'\n' \
... | f9d1ed9b5553eb5fa42b2cfb6386bcf63393a231 | 3,612,946 |
import pdb
def find_bubbles(G, path_d, mermap):
"""
We find all cases where n' -> n1 -> n3
n' -> n2 -> n3
(that is, n3 has > 1 incoming) and n1, n2 each have only one incoming and one outgoing
<i> make sure that n1 and n2 is not used in the same path (which indicates in-ge... | d3a7a06942ef165c7d90ce086cfc79860a4e73b6 | 3,612,947 |
import argparse
from typing import Optional
from typing import List
from typing import Tuple
def main(args: argparse.Namespace) -> bool:
"""GPG Key Validator
Args:
args (argparse.Namespace): arguments
Raises:
Exception: Local GPG Error
Exception: Platform GPG Error
Returns:
... | b182349b160165e187c1b31b14b8d5ba26140cfa | 3,612,948 |
def ldns_dnssec_zone_sign_nsec3_flg(*args):
"""LDNS buffer."""
return _ldns.ldns_dnssec_zone_sign_nsec3_flg(*args) | 888886c068b4bc626f20bb068fca9c4775ad4666 | 3,612,949 |
def sub(x, y):
"""values are subtracted and return"""
return y - x | d07223d6866d27e926952b74d29274f7de1b7a9f | 3,612,950 |
def _to_numpy_array(arr):
"""
Help function for converting an iterable to a Numpy array.
:param arr: Array we want to convert.
:type arr: Iterable[float]
:return: Input array converted to a Numpy array.
:rtype: :class:`Numpy array <numpy.ndarray>`
>>> _to_numpy_array([1.0, 2.0, 3.0])
a... | c0ef84dae59418e21f268171dbf75e1feb2e68d7 | 3,612,951 |
from typing import Counter
def infer_dependency(op):
"""
Infer the dependency of all operations with the
given op as the last operation.
Operator A is depending on B if A uses the output(s) of B.
Args:
op: an Operator instance, e.g. the loss operation.
Return:
a Counter insta... | 0c916c7f5535845460084ed1d4846e9c6cd0a39b | 3,612,952 |
def softmax_loss(x, y):
"""
Computes the loss and gradient for softmax classification.
Inputs:
- x: Input data, of shape (N, C) where x[i, j] is the score for the jth
class for the ith input.
- h: Vector of labels, of shape (N,) where h[i] is the label for x[i] and
0 <= h[i] < C
Re... | b38c7dff075499ec1de2bb1f742614f484951a31 | 3,612,953 |
import json
def stopOscProgress(request):
"""中止该SQL的pt-OSC进程"""
workflowId = request.POST['workflowid']
sqlID = request.POST['sqlID']
if workflowId == '' or workflowId is None or sqlID == '' or sqlID is None:
context = {"status":-1 ,'msg': 'workflowId或sqlID参数为空.', "data":""}
return Htt... | 36b9d2a8e4eb516084e728269c8f1846ec22c794 | 3,612,954 |
from datetime import datetime
def search(request: HttpRequest):
"""
搜索界面的呈现逻辑
分成搜索个人和搜索小组两个模块,每个模块的呈现独立开,有内容才呈现,否则不显示
搜索个人:
支持使用姓名搜索,支持对未设为不可见的昵称和专业搜索
搜索结果的呈现采用内容/未公开表示,所有列表为people_filed
搜索小组
支持使用小组名、小组类型搜索、一级负责人姓名
小组的呈现内容由拓展表体现,不在这个界... | 49de5b5cefff5b26f470e86fcec4f10928c89088 | 3,612,955 |
import re
def extract_length(value):
"""
extract length data from a provided value
Returns a tuple of a detected length value and a length unit. If no unit
type can be extracted, it will be assumed that the provided value has no
unit.
Args:
value: the value to parse
Returns:
... | b418b76114fafe24c86c2e0dcfa62bb19b29ff59 | 3,612,956 |
def get_session(role_arn, region_name):
"""
Returns a session for the specified accountId
"""
sts_connection = boto3.client('sts')
acct_a = sts_connection.assume_role(
RoleArn=PIVOTAL_ROLE,
RoleSessionName='AWS-Tower'
)
access_key = acct_a['Credentials']['AccessKeyId']
s... | 513d910de2f18bfc4a7a7257a74072f4fe0aefe0 | 3,612,957 |
def get_node_by_name(node_name):
"""
Returns pymxs node object with the given name, if exists in the scene; otherwise returns None
:param node_name: str, name of the node we want to retrieve
:return: variant, pymxs object or None
"""
return rt.getNodeByName(str(node_name)) | fe56a4c10bda6d1fe9237dc48d0bb47dd4ab8ec9 | 3,612,958 |
def get_cache_file_metadata_path(cache_file_path):
"""Return metadata file path for a cache file."""
return '%s%s' % (cache_file_path, CACHE_METADATA_FILE_EXTENSION) | b9eed0a52f49c64e64a48b8d92f9d20e4ad6b3f5 | 3,612,959 |
def undo_grad_transforms(grad, tasks, transformers):
"""DEPRECATED. DO NOT USE."""
logger.warning(
"undo_grad_transforms is DEPRECATED and will be removed in a future version of DeepChem. "
"Manually implement transforms to perform force calculations.")
for transformer in reversed(transformers):
i... | c6a2f51704ecf5ab941e5720c74377b1b858669a | 3,612,960 |
def check_agency_status(msg):
"""
checks to see if message contains an agency slug
(i.e., char string between two # hashtags)
and, if so, looks up to see what if any agency it belongs to.
returns agency name
"""
slug = check_agency_hashtag(msg)
# sender_agency = check_sender_agency(msg)
... | b5bf5e29304a48aa2abf85fe0e316f64ecdc0485 | 3,612,961 |
def euclidean_distance(x: np.array, y: np.array) -> float:
"""Calculates euclidean distance.
This function calculates euclidean distance between
two points x and y in Euclidean n-space.
Args:
x, y: points in Euclidean n-space.
Returns:
length of the line segment connecting giv... | c62f2e374dd523b676476a75f8a45d3b5c8cc249 | 3,612,962 |
def transform_geojson_wgs_to_epsg(geojson, EPSG):
"""
Takes a geojson dictionary and converts it from WGS84 (EPSG:4326) to desired EPSG
Parameters
----------
geojson: dict
a geojson dictionary containing a 'geometry' key, in WGS84 coordinates
EPSG: int
numeric code for the EPSG ... | 8dff1f786fa5bfeddd9ff63c43a042da4a6a9a68 | 3,612,963 |
def time_offset(tds, insttime, utctime):
"""Calculate and apply time offset to SBE56 time series
Parameters
----------
tds : xarray.DataArray
SBE56 data structure
insttime : np.datetime64
Instrument time at end of time series
utctime : np.datetime64
UTC... | a8c7ef290f09c6b6975575715233986ff171e24a | 3,612,964 |
def gaussian_kernel(kernel_shape: tuple, centre: tuple, sigma: float, amplitude: int = 1) -> np.ndarray:
"""Returns a 2D Gaussian kernel array."""
y, x = np.ogrid[0:kernel_shape[0], 0:kernel_shape[1]]
h = np.exp(-(pow(x - centre[0], 2) + pow(y - centre[1], 2)) / (2. * sigma * sigma))
h[h < np.finfo(h.dt... | 245d61bd3c33b082658cbcd8cf57c6a968ece6ae | 3,612,965 |
def web_hook():
"""
transfer station of teambition's webhook to feishu's webhook
"""
# resolve teambition's request, maybe we need some authentication
signature = request.headers.get('X-Signature', '')
response = request.json
type = response['event']
task_state_map = {'task.create'... | 1f221f0a2e88dec136fa3fbe11ce9db35a2172ac | 3,612,966 |
def flip_op(input, dims):
"""
Reverse the order of a n-D tensor along given axis in dims.
.. note::
`flow.flip` makes a copy of :attr:`input`'s data. This is different from NumPy's `np.flip`,
which returns a view in constant time. Since copying a tensor's data is more work than viewing... | 0c08e3f0713f99e17b2276de51593c981a5e5073 | 3,612,967 |
def deserialize_timestamp_from_binance(time: int) -> Timestamp:
"""Deserializes a timestamp from a binance api query result entry
Kraken has timestamps in integer but also including milliseconds
Can throw DeserializationError if the data is not as expected
"""
if not isinstance(time, int):
... | 94f4ced79fe3bf026fcb37e4e40d6265b7eacf3a | 3,612,968 |
def intersect(set_a, set_b):
"""
"""
return [x for x in set_a if x in set_b] | be1bf6cb55d0ab94e68cc05fc6d9fb5d68f5dd4c | 3,612,969 |
def refine_general(splits, sigma, n=1, combine=lambda a,
b: a + b, key=lambda a: a):
""" Do a general refinement of up to n steps """
oldsplits = splits[:]
N = splits[-1]
counter = 0
k = len(splits)
n = n or np.inf
while counter < n:
splits = [bestsplit_general(sp... | 6a99beec1dde51689f1f9bd9e18d0408f884c39a | 3,612,970 |
def matrix_exponential(matrix:tf.Tensor, dt):
"""Computes the matrix exponential of one or more square matrices.
$$exp(A) = \sum_{n=0}^\infty A^n/n!$$
The exponential is computed using a combination of the scaling and squaring
method and the Pade approximation. Details can be found in:
Nicholas J. H... | baef93f6eaf2af00ddf43098fd6f0f5039f7f67e | 3,612,971 |
def enumerate_param(param, values):
"""Builds a dictionary of an enumerated parameter, using the param string and some values.
If values is not a list, tuple, or set, it will be coerced to a list
with a single item.
Example:
enumerate_param('MarketplaceIdList.Id', (123, 345, 4343))
Returns:
... | 27e109224c1315a34ebac6e78f47a7cf6136cd29 | 3,612,972 |
def enumerate_paths(src):
"""flatten out a nested dictionary into an iterable
DIODE metadata is a nested dictionary;
One could easily query a particular scene and scan, but sequentially
enumerating files in a nested dictionary is troublesome. This function
recursively traces out and aggregates the l... | d9195cba20b9d370e762f9ff839bb8b294368a20 | 3,612,973 |
def tweet_decode(tweet):
""" Gets data from tweet and returns a simplified data structure
tweet = {
'full_text': 'This is a tweet #hello #world http://t.co/13456',
'urls': [ 'http://en.wikipedia.org/' ]
'hashtags': [ '#hello', '#world' ]
}
"""
tweet_simple... | b7c9667bd3bd755e3e7120f366faf6d19419c316 | 3,612,974 |
def load_clonotypes_csv_general(fname: str, single_return: bool = True) -> pd.DataFrame:
"""
Load clonotypes.csv file. This file is expected to be a comma-delimited table with columns
"clonotype_id" and "cdr3s_aa".
Returned data frame is the df contained in fname with added columns TRA_aa and TRB_aa
... | 5f03f56e02d75d34e85b3d631d558361472645bb | 3,612,975 |
def pattern_search(search_pattern):
"""
Search for search_pattern in pattern. Convert from hex if needed
Looking for needle in haystack
"""
needle = search_pattern
try:
if needle.startswith("0x"):
# Strip off '0x', convert to ASCII and reverse
needle = needle[2:]... | c7eb27988b951888b753849a62b8680742ef1055 | 3,612,976 |
import unittest
def suite():
"""Define all the tests of the module."""
suite = unittest.TestSuite()
suite.addTest(unittest.makeSuite(SearchV2TestCase))
return suite | e9e4d3ebeb95dab99a154730218c074ef5389e1d | 3,612,977 |
def manhattan_distance(pointA: tuple[int], pointB: tuple[int]) -> int:
"""Returns the Manhattan distance between points A and B, assuming a weight of 1"""
return abs(pointA[0] - pointB[0]) + abs(pointA[1] - pointB[1]) | 6ad8b15519d577f9cb5d0b86e2bc89674f190155 | 3,612,978 |
def SysFont(name, size, bold=False, italic=False, constructor=None):
"""pygame.font.SysFont(name, size, bold=False, italic=False, constructor=None) -> Font
create a pygame Font from system font resources
This will search the system fonts for the given font
name. You can also enable bold or ita... | 09ce25ae98b47fc62c544f010bfff5489771a003 | 3,612,979 |
import asyncio
def forecast(latitude: float, longitude: float) -> list[Forecast]:
"""Main function for retrieving forecast for a longitude and latitude"""
loop = asyncio.get_event_loop()
*information, request = loop.run_until_complete(_get_gridpoint(latitude, longitude))
res = loop.run_until_complete(... | 40ffbdb73bb9603532e65d6bd9f9f4a5e83cdbb2 | 3,612,980 |
def get_berkeley_format():
"""Creates a configuration for images saved in Berkeley format.
Returns:
the configuration.
"""
config = {}
config['image_name'] = '{}/image_aux1/encoded'
config['state_name'] = '{}/endeffector_pos'
config['action_name'] = '{}/action'
config['state_dim'] = 3
config['act... | 521df1a7244d796f5d8a91075c5723ac6c4557ae | 3,612,981 |
def cxyz_to_xyzc( v ):
"""
Takes a torch array and returns it as a numpy array on the cpu
:param v: torch array
:return: numpy array
"""
dim = len(v.shape)-2
if dim ==2:
v = v.permute(0,2,3,1)
if dim ==3:
v = v.permute(0,2,3,4,1)
return v | 65dcaf573bf53f0b78bdea83d0ce809bd335a480 | 3,612,982 |
def start_flow():
"""
Starts the oauth flow. This will return a dict which causes a redirect to the providers page.
"""
LOG.debug("Read OAuth id/secret: none? %s/%s", CLIENT_ID is None, CLIENT_SECRET is None)
github = OAuth2Session(CLIENT_ID, scope=SCOPE)
authorization_url, state = github.aut... | 29f1445a17d116c46603d875285242568b33334c | 3,612,983 |
import time
import functools
import logging
def monorail_api_method(
request_message, response_message, **kwargs):
"""Extends endpoints.method by performing base checks."""
time_fn = kwargs.pop('time_fn', time.time)
method_name = kwargs.get('name', '')
method_path = kwargs.get('path', '')
http_method = ... | 60f13597b89cbdddd113c705a0b752d7a6874b3e | 3,612,984 |
from typing import Union
def _extend_dict(main_dict: Union[PerArraySequenceDict, PerArrayDict],
added_dict: Union[PerArraySequenceDict, PerArrayDict]):
"""
We can't do anything like main_dpp.extend(added_dpp).
Doing as in nibabel.streamlines.tests.test_tractogram.
"""
for k, v in ... | 657bd195324e63fa03ffbbfb20295e33428d0179 | 3,612,985 |
def expool(CONST_STRING):
"""expool(ConstSpiceChar * CONST_STRING)"""
return _cspyce0.expool(CONST_STRING) | 7a88c120b9a0f02d03f1e9f63dd811523e419da0 | 3,612,986 |
def stackop(func, stack):
"""Returns a function, that operates on the elements of a given stack.
Example for creating a multiply stack operation,
which takes two arguments:
>>> stack = [1, 2, 3, 4]
>>> multiply = stackop(lambda x, y: x * y, stack)
>>> multiply()
>>> stack
... | 5c6a06ef6dcb8c3fdbc31ee61fb769c5b254f960 | 3,612,987 |
def get_seed_catalog(seedname="DeveloperSeed"):
"""Returns the developer seed sucatalog"""
try:
seed_catalogs = read_plist(SEED_CATALOGS_PLIST)
return seed_catalogs.get(seedname)
except (OSError, IOError, ExpatError, AttributeError, KeyError) as err:
log.warn(err)
return "" | 59c3a86dda7e27673fd496c1a59504156d380471 | 3,612,988 |
def generate_all_valid_patterns():
"""Generate all valid dot patterns, as strings representing 16 bit binary numbers.
Valid patterns are made up of dots and blanks in an 8x2 pattern which are
- made up of exactly 10 dots, where 4 dots always make up the left-most and right-most column
- not rot... | 4ea136ab06901179d786e9e205484485017f8813 | 3,612,989 |
def get_id(serving_name):
"""
Gets the id of a serving with a given name
Example use-case:
>>> from hops import serving
>>> serving.get_id(serving_name)
Args:
:serving_name: name of the serving to get the id for
Returns:
the id of the serving, None if Serving does not ex... | 32198ec978df268bfbfd328f4031593e0f53a38b | 3,612,990 |
import sys
def get_podcastep(podcastep_id):
"""
Get a podcast ep by their ID in your media server
"""
conn = database_connect()
if(conn is None):
return None
cur = conn.cursor()
try:
#########
# TODO #
#########
#################################... | 7dc01863a69d4ead222865fab4430160d79a3d08 | 3,612,991 |
def ImageMLP_Imagenet16_Relu256x256x256():
"""A 3 hidden layer MLP trained on 16x16 resized imagenet."""
datasets = image.imagenet16_datasets(batch_size=128)
return _MLPImageTask(datasets, [256, 256, 256]) | 819d08976fa9479f4d51aaf6e40fe3eb1334aef3 | 3,612,992 |
def _ros(veos, vpos, eos, pos):
"""
ROG = Rate of Senescing (Days)
"""
return (veos - vpos) / (eos - pos) | 6a944f9c7719866fcd862f8d4b9f088d277b48aa | 3,612,993 |
def bollinger_lband_indicator(close, n=20, ndev=2, fillna=False):
"""Bollinger Low Band Indicator
Returns 1, if close is lower than bollinger low band. Else, return 0.
https://en.wikipedia.org/wiki/Bollinger_Bands
Args:
close(pandas.Series): dataset 'Close' column.
n(int): n period.
... | 3336001233ab4055ba0a867dd698878a271faf53 | 3,612,994 |
import os
def make_cython_wrapper(filenames, sources, modulename=None, target=".",
config=Config(), incdirs=(), compiler_flags=("-O3",),
verbose=0):
"""Make Cython wrapper for C++ files.
Parameters
----------
filenames : list of strings or string
... | 15ab90e0f40beba2027473f3d9fe1e933f80cf44 | 3,612,995 |
def _create_missing_method(name):
"""Create a drop-in callable for a missing role method with the given name."""
def bridge(roles, compound, *args, **kwargs):
return proceed(name, roles, compound, *args, **kwargs)
return bridge | ffbca1da0748091c3fa24ad3ec927e047f64b07c | 3,612,996 |
def werCalc(s1, s2):
"""
Computes the Word Error Rate, defined as the edit distance between the
two provided sentences after tokenizing to words.
Arguments:
s1 (string): space-separated sentence
s2 (string): space-separated sentence
"""
s1 = s1.lower()
s2 = s2.lower()
# b... | ea3738f96496da2fc2d9f1a9a366f1c24a4302f4 | 3,612,997 |
def not_found_error(error):
"""404 Page Missing handling"""
if wants_json_response():
return api_error_response(404)
return render_template('errors/404.html'), 404 | ed48f02611ac8cc45b69ac7209be61d9a01398ec | 3,612,998 |
def read_general_arr(fpath, txt=True, compress=False):
"""
Reads general data array (txt, npy, or compressed npz)
"""
if txt:
assert not compress
return np.loadtxt(fpath, delimiter=',')
else:
X = np.load(fpath)
if compress:
return X['a']
else:
... | 86904cbb619eaa350f458cb26321756333531d8f | 3,612,999 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.