content stringlengths 35 762k | sha1 stringlengths 40 40 | id int64 0 3.66M |
|---|---|---|
import re
def parse_BIO_tag(tag):
"""Parse given string as BIO tag.
The expected format is "[BIO]-TYPE", where TYPE is any non-empty
nonspace string, and the "-TYPE" part is optional.
Args:
tag (string): tag to parse.
Returns:
string pair: tag ("B", "I" or "O") and TYPE.
"""
... | 63b8eb2cb3ac183f668a0e9bf788fb7bd4e1ac88 | 42,700 |
from typing import Sequence
from typing import Mapping
from typing import Any
from datetime import datetime
def create_schema(
events: Sequence[Mapping[str, Any]],
links: Sequence[Mapping[str, str]],
tracking: Sequence[Mapping[str, Any]],
schema_id: str,
schema_name: str,
schema_dscpt: str,
) ... | fbd0712edc694b0b45f67c452dbd84cdacb7ed68 | 42,701 |
import math
def dadda_4to2_reduction(previous_bit_heap):
""" BitHeap Wallace reduction using 4:2 compressors """
next_bit_heap = BitHeap()
carry_bit_heap = BitHeap()
max_count = previous_bit_heap.max_count()
new_count = int(math.ceil(max_count / 2.0))
# each step reduce the height of the bit h... | 0256791f9be19af3c64eaa93036fb3cffbc5ac95 | 42,702 |
def modification_oeuvre(identifier):
"""
Route gérant la modification d'une oeuvre
:param id_publ: identifiant de l'oeuvre
:return : affichage du template modifier_oeuvre.html ou redirection
"""
# On renvoie sur la page html les éléments de l'objet oeuvre correspondant à l'identifiant de la route
if request.meth... | 68e808c41f12300b37fcd74746fd0dbfe88e9def | 42,703 |
def VisualizeAll3D(pts3D,ax,dataset_name, xlim, ylim, zlim):
"""
this function visualizes all 3D skeletons from one image
the form if pts3D is 4 by n numpy array, rows 0,1,2 are x,y,z, row3 is always 1
"""
bright_orange_cv2 = (255/255,79/255,0)
bright_blue_cv2 = (0, 229/255, 238/255)
... | 78eba088e513a3967dfe53a0ed02e3f218e9f640 | 42,704 |
def co2_mol_to_C_mass_flux( df, n_seconds ) :
"""
Convert molar CO2 flux to mass C flux ( umolCO2/m^2/s to gC/m^2 )
and sum (integrate) for each period in the timeseries for each column
in data frame
Args:
df: a pandas dataframe
n_seconds: number of seconds to integrate in the conve... | b761bd812663cb5a4cb054087a3657dbb10d8d84 | 42,705 |
def _contourf(darray,
x='lon',
y='lat',
transform=None,
# Facetgrids arguments
figsize=None,
size=None,
aspect=None,
ax=None,
row=None,
col=None,
col_wrap=None,
... | d6e1ed39851f00323fad0ea154cd29d62e7a4bad | 42,706 |
import os
def generate_token(email, token_expire_date):
"""
It generates user token
:param email: user email
:param token_expire_date: time taken for token to expire
:return: token
"""
token = jwt.encode({'email': email,
'exp': token_expire_date},
... | d1e3c5142b1b073fe90d2e21c49849f0230d37ad | 42,707 |
def chunk_textgrid_parser(textgrid_obj):
""" Parsses the Textgrid of One Chunk and Returns a List
Parameters
----------
textgrid_obj : praatio.Textgrid()
One Chunk's Textgrid Object imported using praatio
Returns
-------
textgrid_dict : dict
Dictionary of all of the Tiers f... | ab4d97da02ba0271e1549d4cb67a668e47008de6 | 42,708 |
def _set_values(loop_data):
"""Find rows corresponding to values in data
This is a private function, not meant for general use.
Input: dataframe
Output: dataframe
"""
# These are the indexes of all the data that are unassigned
value_indexes = loop_data.ix[(loop_data.loop==0)&... | 8b246756a12e48f39cd0d1c04c282cbc1a537e5b | 42,709 |
def abs(x):
"""Element-wise absolute value.
# Arguments
x: input tensor.
# Returns
A tensor.
"""
return KerasSymbol(mx.sym.abs(data=x.symbol)) | 9bc1f174aae297699f663aea4bb71a3954ec311f | 42,710 |
def build_module(
mod,
target,
params=None,
enable_acl=True,
tvm_ops=0,
acl_partitions=1,
disabled_ops=["concatenate"],
):
"""Build module with option to build for ACL."""
if isinstance(mod, tvm.relay.expr.Call):
mod = tvm.IRModule.from_expr(mod)
with tvm.transform.PassCo... | 82b6c732f59b759fea8f886f7f8b9399f0be7a27 | 42,711 |
def plus_frequente_occurence(vecteur, valeur_par_defaut=None):
"""Wrapper de la méthode first_valid_index d'un Pandas.Series.
Arguments d'entrée:
vecteur (pandas.Series)
valeur_par_defaut
Arguments de sortie:
(Python Object)
"""
return vecteur.value_counts(ascending=Fals... | e601ec1bf14a3668277767194615f98c28cae432 | 42,712 |
def _get_git_version():
"""Return version of git we use (might be bundled)"""
return __get_git_version(_git_runner) | 07d598f345cff674ad4a6d52f14ecbf46e0df0ed | 42,713 |
import rdflib as rl
from nidm.core import Constants
import json
def create_cde_graph(restrict_to=None):
"""Create an RDFLIB graph with the FSL CDEs
Any CDE that has a mapping will be mapped
"""
with open(cde_file, "r") as fp:
fsl_cde = json.load(fp)
fsl = Constants.FSL
nidm = Consta... | 00b8235cde1ab37f3c65586b1b4d3fb354e299ef | 42,714 |
def trajectory(ddir, file_prefix):
""" generate trajectory DataFile
"""
name = autofile.name.trajectory(file_prefix)
writer_ = autofile.write.trajectory
reader_ = _not_implemented
return factory.DataFile(ddir=ddir, name=name,
writer_=writer_, reader_=reader_) | f2a90ddcf96c040b0132b2f2b466089c443e36c4 | 42,715 |
import re
import base64
def _decode_base64(data, altchars=b'+/'):
"""Decode base64, padding being optional.
:param data: Base64 data as an ASCII byte string
:returns: The decoded byte string.
"""
data = re.sub(rb'[^a-zA-Z0-9%s]+' % altchars, b'', data) # normalize
missing_padding = len(data... | b5acd6beefd5183889391ee2e6c0b92352b77870 | 42,716 |
def compute_condition(t, dt):
"""
Inputs are normalized times.
`t` is the position of one dirac and `dt` is the distance between the two
diracs.
"""
u0 = np.exp(-1j*2*np.pi*t)
u1 = u0*np.exp(-1j*2*np.pi*dt)
# eigenvalues from quadratic formula
a = 1
b = -1*(1+u1)
c = -1*(u... | e4a14f9c9c941f6a90acb96e755c2651508b13c9 | 42,717 |
def dot_general(lhs: np.ndarray,
rhs: np.ndarray,
contracting_dims: Axes,
batch_dims: Axes,
precision=None) -> np.ndarray:
"""`jax.lax.dot_general` with preserved dims order and shared lhs / rhs dims.
Precisely, returns `jax.lax.dot_general(lhs, rhs, ... | 5670783fe82d40fedc0a762f13d6b5acc0fd1ca7 | 42,718 |
def read_current_user_shops(
current_user: usermodels.User = Depends(get_current_active_user),
):
"""
Retrieve a list of shops assigned to the currently logged in user.
"""
return current_user.shops | 27d78ec27afac7e882006be09e58d66e3e6834c9 | 42,719 |
def check_sim_params(params={}):
"""
Checks simulation parameter dictionary for various keywords and sets to
default values if not present
Parameters
----------
params: dict, optional
dictionary containing initial key/value pairs for simulation of catalog
Returns
-------
pa... | 9028ef9de53c1155a6c9e1c4325954c1c418e47d | 42,720 |
def points_on_circle(radius, points):
"""
returns a set of uniform points around a circle
:param radius: radius of the circle
:param points: number of points on the circle
:return:
"""
angle = np.linspace(0, 2*np.pi, points)
x_coord = np.cos(angle)*radius
y_coord = np.sin(angle)*radi... | d5ccc7cd7bd50f7668194f8841aebd68fad046c3 | 42,721 |
import torch
import tqdm
def validate(data_loader):
"""
:return: validation accuracy, validation loss
"""
num_iteration = 0
deep_punctuation.eval()
correct = 0
total = 0
val_loss = 0
with torch.no_grad():
for x, y, att, y_mask in tqdm(data_loader, desc='eval'):
... | f1b545df7d5b8bdfadb72915a285cf3806ce51e8 | 42,722 |
import time
import random
def show_secret(item):
"""
Show a secret for X seconds and erase it from the screen
"""
try:
print("* The password will be hidden after %s seconds." %
(global_scope['conf'].hideSecretTTL))
print('* The password is: %s' % (item.password), end... | 027c422aa4dcd6a3ed4c94d1ee43079caaaf47b7 | 42,723 |
def analyze_data(fitsfn, observables_dir="", affine2d=None,
psf_offset_find_rotation = (0.0,0.0),
psf_offset_ff = None,
rotsearch_d=None,
set_pistons=None):
"""
returns: affine2d (measured or input),
... | c3fa54d252bc57a3bdf315e5918fe050285de1dd | 42,724 |
def value_at_offset(obj_node, offset, dst_type):
"""
Perform (dst_type) (((char *) my_object) + offset)
"""
offset = ConstNode(offset, Py_ssize_t)
pointer = PointerFromObject(obj_node)
pointer = CoercionNode(pointer, char.pointer())
pointer = pointer_add(pointer, offset)
value_at_offset ... | 7d3d60a087efb9c3f0db3f72a9f2630263702413 | 42,725 |
def step_id(value):
"""return the test id from the test step object"""
return f"{value.comment} {value.user_input}" | 843d2ff24b86da8382c75f709a0fe18e8e897d0c | 42,726 |
def _attributes_equal(new_attributes, old_attributes):
"""
Compare attributes (dict) by value to determine if a state is changed
:param new_attributes: dict containing attributes
:param old_attributes: dict containing attributes
:return bool: result of the comparison between new_attributes and
... | 11c92f000f1811254db48a8def3e681a09e8a9a9 | 42,727 |
from datetime import datetime
from pathlib import Path
import numpy
import math
def get_pass_times(
start_time: datetime,
end_time: datetime,
pass_times_filename: PathLike = PASS_TIMES_FILENAME,
):
"""
Retreive array of datetimes of VIIRS passes within the given time interval, given initial period... | b1757ad1e8e5ba6f4f1dfb95135bb7ae30346046 | 42,728 |
import os
import json
def decode_utf8(text: str) -> str:
"""Eliminates encoded UTF-8 symbols in a text
Example: 2020%2D03%2D25 16%3A25%3A17%3A%2E0 --> 2020-03-25 16:25:17.0
Args:
text (str): Input text
Returns:
str: Decoded text
"""
with open(os.path.join(os.path.dirname(__fi... | 4953baf15ac78e7bc823297d5bf4b103819c2df8 | 42,729 |
import sys
import os
def read_cmd_args():
"""Read command line arguments."""
if len(sys.argv) != 12:
print("[ERR] Invalid number of command line arguments!")
_usage()
sys.exit(1)
# fcst_syr
try:
fcst_syr = int(sys.argv[1])
except ValueError:
print(f"[ERR] ... | d44419a603cc91b902976ad876e011b78609db65 | 42,730 |
def _recover_bin_edges(wave):
"""Recover the edges of a set of wavelength bins given the bin centers.
This function is designed to work for standard linear binning along with
other more exotic forms of binning such as logarithmic bins. We do a second
order correction to try to get the bin widths as acc... | 70bb5f10f3b6f47422aac16688f57e061cdd5eb7 | 42,731 |
def structured(inputSchema, outputSchema, schema_store=None,
ignore_body=False):
"""
Decorate a Klein-style endpoint method so that the request body is
automatically decoded and the response body is automatically encoded.
Items in the object encoded in the request body will be passed to
... | 99fb4581714fb7446988b876529faf918f56f744 | 42,732 |
def reweight_distribution(original_distribution, temperature = 0.5):
"""
:param original_distribution: 概率值组成的一维 Numpy 数组,数据之和等于1
:param temperature: 用于定量描述输出分布的熵的因子
:return: 将加权生的分布归一化,保证数组之和为1
"""
distribution = np.exp(np.log(original_distribution) / temperature)
return distribution / np.s... | c8040db76dc0768f2cc80d270bc541796abd3a75 | 42,733 |
import functools
def resnet152_dropout(pretrained=False, **kwargs):
"""Constructs a ResNet-152 model.
Args:
pretrained (bool): If True, returns a model pre-trained on ImageNet
"""
block = functools.partial(DropoutBottleneck,
dropout=args.dropout,
... | 3064ae34636d8de6baf4638a8c66d75e5aa68cfc | 42,734 |
from typing import List
from pathlib import Path
import glob
async def yolov5_weights() -> List[str]:
"""
Get available weights options for model.
Returns:
List[str] of all YOLOv5 model weights files currently available to use.
"""
return [Path(f).as_posix().rsplit('/', maxsplit=1)[-1].sp... | f2cf44f0caa922c4971b1a39a8bd80fe813e1be1 | 42,735 |
import torch
def load_celeba(input_size=224, num_workers=2, trainsize=10000, testsize=1000, batch_size=32, transform_type='normalize'):
"""Load CelebA dataset"""
if transform_type == 'normalize':
transform = transforms.Compose([
transforms.RandomResizedCrop(input_size),
transf... | f2fe03cf4b713926cc048231165f534e12e3df92 | 42,736 |
def pass_if(expression, exc_type, exc_val=_const.CHAR_EMPTY):
"""
Raises an error of type *err_type* when *expression* is **falsy** and silently passes otherwise.
Opposite of :func:`raise_if`.
:param expression: An expression or value to evaluate.
:param exc_type: The error to raise when *expre... | 72035e25227e918f73934cdee64b208b4734031b | 42,737 |
import re
def parse_min_max_info(requirements_string):
"""
Get min max info from a requirements string.
"""
assert "MAXNUM" in requirements_string, "missing MAXNUM"
assert "MINNUM" in requirements_string, "missing MINNUM"
min_num_search = re.search(
r"MINNUM(\d+)",
requirements... | 430812339720dfa735efc77510a148b8f40deac8 | 42,738 |
from typing import Iterable
def dfs_iterative(graph: Graph, strategy: DFSStrategy, roots: Iterable[Vertex]) -> Iterable[Vertex]:
"""Iterative depth-first search algorithm.
:param graph: a graph
:param strategy: a searching strategy
:param roots: starting vertices
:return: iterable object of visit... | 33019b0d635bcca78a8fc43f7762c3b7327f3717 | 42,739 |
def get_fields_from_template(template):
"""
Get list from {item} items of template string
:param template: a "template" string (a string with {item} items
-- the kind that is used to mark token for str.format)
:return: a list of the token items of the string, in the order they appear
>>> get_fi... | b3595e4ccee6e67badd6e6f19ae12aaee05226c5 | 42,740 |
import requests
def sra_ids_to_srrs(ids):
"""Convert SRA IDs (which is a number) to SRRs.
:param id: list of SRA IDs
:type id: list
:return: list of SRR accessions
:rtype: list
"""
# TODO: use cached get. Can't be used currently because dictionaries can
# not be hashed.
response ... | 0887b66ab3c87221493973dd93e26b03f72c091d | 42,741 |
def make_my_v1_running_example_dataset(num_items_per_dataset = 10, num_labels_per_item=10, minimal=False,
include_hard_classifier=False, include_soft_classifier=False)->SyntheticDataset:
"""
Four states: stronghigh = 90/10, weakhigh = 70/30, weaklow = 30/70; stronglow = 10/90
... | 24febbdec522522a9973bee8a9bb3f800c9fe90a | 42,742 |
def get_3d_bbox(actor_, camera_actor):
"""Get the 8 point coordinates of the actor in the camera view."""
# 1. get the 8 vertices of the actor box
vertices = np.zeros((8, 4), dtype="float")
extent = actor_.bounding_box.extent # x, y, z extension from the center
vertices[0, :] = np.array([extent.x, extent.y, ... | 445759300b633635c78674c2f55fe2d130ed32ef | 42,743 |
import subprocess
def launch_scenario_process(
db_path, scenarios_directory, scenario_id, solver, solver_executable
):
"""
:param db_path:
:param scenarios_directory:
:param scenario_id: integer, the scenario_id from the database
:param solver: string, the solver name
:param solver_executa... | c9904afd01d1989308173bcd7208a77ba5ed38bc | 42,744 |
def smt_curve(sig_df, window = 49, order = 1, PLOT = False):
"""
smoothe a noisy signal curve using multi-step savgol_filter
Parameters
----------
sig_df : Pandas.Series
the sigal to be smoothed
window : int, optional
maximum window size. The default is 49.
order: int, optio... | b0870404a28b694a34aa02383b84abbb67f15fd6 | 42,745 |
def backpropagation(network, x, y):
""" Calculate delta values of a network for array inputs x and outputs y.
Return gradw and gradb of the cost function as lists of matrices for each layer.
"""
# Initialize lists to store gradwJ(W,b,x,y) = d(l+1)*a(l)t and gradbJ(W,b,x,y) = d(l+1) with each item in lis... | 484ddcb0b3db03cd5445a7bc95da2a3de7d6b626 | 42,746 |
def vms_list(request):
"""Show the list of VMs"""
liste = []
for server in Server.objects.filter(is_proxmox=True).exclude(proxmox_node_name='').all():
retour = gimme_prox_cox(server.ip_for_proxmox()).getNodeContainerIndex(server.proxmox_node_name)
vm_list = []
vm_servers_linked = ... | af599ccabb849f477d556f0e1ea23d44a73bdf26 | 42,747 |
import os
def add_examples(cls):
""" Add all build.xml files as a test case to the class """
for root, _, files in os.walk(EXAMPLE_DIR):
for filename in files:
if filename == 'build.xml':
fullfilename = os.path.join(root, filename)
add_test(cls, fullfilename... | 1a5e47575a29b580c01cf60d605f07c2f405e98c | 42,748 |
def load_school_collections() -> pd.DataFrame:
"""Load monthly tax collections for the School District."""
# Get the path to the files to load
dirname = SchoolTaxCollections.get_data_directory("processed")
files = dirname.glob("*-tax.csv")
return _load_monthly_collections(files, total_only=True) | 156b4652942cdf7130afbfad6a3eab9833a93da1 | 42,749 |
def get_curve(name):
"""Node Groupに作成したCurve Nodeを返す"""
node_name = "MRGPEN_NODE_{}".format(name)
node_groups = bpy.data.node_groups
nodes = None
if node_name in node_groups:
nodes = node_groups[node_name].nodes
else:
nodes = node_groups.new(
name=node_name,
... | bffe7caffd413b6f2bbe81b9fcba3c116988a04f | 42,750 |
def parse_read(read):
"""parse bioseq to fastq."""
# dele = "-"
dele = ""
# check if there is MD tag
# check whether query sequence is exist
if not read.has_tag("MD") or (query_seq := read.query_sequence) is None:
return None
query_qual = read.query_qualities
# init matched r... | 2033481f6081e98d19c1e8d1f26b5c3b3f339b13 | 42,751 |
from datetime import datetime
def update_policy(data, policy_id):
"""
Args:
data: Dictionary with data to be updated
policy_id: Policy's ID
Returns: Update operation status wrapped on dictionary
"""
class UpdatePolicyError(Exception):
pass
try:
policy_obj =... | d3ae44fda1bf27ecdfb97c6e18a11cee43e69f5f | 42,752 |
def apply_bg_correction(mean_values, params):
""" this function won't work with float16 in practice. limits use to float32 """
if not isinstance(params, BackgroundCorrectionParams):
raise ValueError('params is not a BackgroundCorrectionParams instance')
bg_mean = params.bg_mean
bg_mad = params.... | 0aad31a0ed8be0298fc7cb0f11bd072d1fadf852 | 42,753 |
import argparse
def parse_args():
"""
parse_args parses command line arguments and returns argparse.Namespace object
Returns
-------
argparse.Namespace
Namespace that contains all command line arguments with their corresponding values
"""
parser = argparse.ArgumentParser(descripti... | 7487c30a78d8d64e00547e9f323e237cb4ff92ec | 42,754 |
def run_state_evolution(x_ids, model, **algo_kwargs):
"""
Run state evolution for a given model.
Parameters
----------
- x_ids : ids of the variables to infer (signals)
- model : model that can be used in StateEvolution
Returns
-------
- records : list of x_id, v, n_iter
"""
... | 69e0f20acd6238a21fbd91bcfe1231a512edca9d | 42,755 |
def open(self):
"""获取开盘价序列"""
return self.openArray[-self.size:] | a254b5a389c9b450a685926083b849584ae2a6f9 | 42,756 |
def match_candidates_by_order(images, exifs, max_neighbors):
"""Find candidate matching pairs by sequence order."""
if max_neighbors <= 0:
return set()
n = (max_neighbors + 1) / 2
pairs = set()
for i, image in enumerate(images):
a = max(0, i - n)
b = min(len(images), i + n)
... | 75451de154e0ad2e2013ed63c5e6b3eadac5dc71 | 42,757 |
def meshTensor(value):
"""**meshTensor** takes a list of numbers and tuples
that have the form::
mT = [ float, (cellSize, numCell), (cellSize, numCell, factor) ]
For example, a time domain mesh code needs
many time steps at one time::
[(1e-5, 30), (1e-4, 30), 1e-3]
Means take 30 ... | 7f23eadaf5b38c691cba40f47c9c15c2a4b886d4 | 42,758 |
import re
def attr(*args, **kwargs):
"""Decorator wrapper for the nose 'attrib' attr decorator.
This attr decorator recognizes the 'user' attribute when assigned and
calls the `credentials_for` method of the TestTypePad class to apply the
appropriate OAuth credentials.
This wrapper also atte... | ee40f9349cd8dfee3537263aeaf526c408083394 | 42,759 |
def imperative_grad(
vspace,
target,
sources,
output_gradients=None):
"""Computes gradients from the imperatively defined tape on top of the stack.
Works by filtering the tape, computing how many downstream usages are of each
tensor and entry, and repeatedly applying backward functions until we h... | 943e9340f0bdd8fce35f209f0cbe3e5954581d81 | 42,760 |
def itrs2horizon(station,ts,ts_quasi_mjd,positions,coord_type):
"""
Convert cartesian coordinates of targets in ITRF to spherical coordinates in topocentric reference frame for a specific station.
Usage:
az,alt,r = itrs2horizon(station,ts,ts_quasi_mjd,positions,coord_type)
Inputs:
station ... | 9e38ed0f4101c056ebaff618ed70b97f1f572347 | 42,761 |
import logging
import codecs
def load_utf8_to_str(rel_path):
"""Load file, decode from UTF-8 and return as str."""
logging.debug('Loading test file. rel_path="{}"'.format(rel_path))
utf8_path = get_abs_test_file_path(rel_path)
with codecs.open(utf8_path, encoding="utf-8", mode="r") as f:
unico... | 9ed5b19bef891330d98f7b99429001c7bad19847 | 42,762 |
from coldtype.pens.draftingpen import DraftingPen
def ease(style, x):
"""
Though available as a general-purpose function, this logic is usually accessed through something like the `.progress` function on an animation or timeable.
Return two values — the first is the easing result at a given time x; the s... | 42409e8153a896cc3f83ab971fd11350a6c5cfd8 | 42,763 |
def getAllBlogs(con=None, cur=None, db=None):
"""
gets all blog details
Returns:
- rows: all blogs as list
- [] : if no blogs are present in db
"""
sql = "SELECT * FROM blogs ORDER BY id ASC"
rows = []
db(sql, ( ))
rows = cur.fetchall()
return rows or [] | 642db526bc9b96fe4b8ab58c552daee51584314e | 42,764 |
def advanced_search(post_query):
"""
Perform advanced search using OFF search engine
"""
post_query['json'] = '1'
url = utils.build_url(service='cgi',
resource_type='search.pl',
parameters=post_query)
return utils.fetch(url, json_file=False) | d714af13eb72d948bd8a9a1ed6390db17a138955 | 42,765 |
import subprocess
def read_frame(input, frame_num=None, frame_time=None, video_data=None, force_grayscale=False):
""" Code taken and adapted from zplib.image.ffmpeg
Efficiently locates the desired frame and returns it, looping through every previous frame.
Return specific frame from an input video via ffm... | 3054b42639771c7608dc178500baab376844379e | 42,766 |
def generate_percentiles(results, percentiles=DEFAULT_PERCENTILES):
"""Percentage distribution of the results.
I.e. At what point had 50%, 75% and 90% of results completed?
"""
data = []
total = len(results)
cur_index = 0
if not results:
return data
for percentile in percentil... | 9bcfc51d6779c471adc8ae8590b892be80c6e9cb | 42,767 |
def get_policy(name: str) -> Policy:
"""Returns the Policy with the given name, None if there is none"""
return _registry.get(name) | b58a0146f40a7fe3b85c262ad20484eef6f00c23 | 42,768 |
from typing import Any
def build_patch200_succeeded_ignore_headers_request(
*, json: Any = None, content: Any = None, **kwargs: Any
) -> HttpRequest:
"""Long running put request, service returns a 200 to the initial request with location header. We
should not have any subsequent calls after receiving this... | abfc1e80d833cd1ca270c09d1b43cb5f30bb1d6a | 42,769 |
from datetime import datetime
def htmlpage():
"""For testing: Example HTML page, if you want to use templates."""
# just some data for the template
clock = datetime.datetime.now()
return render_template('example.html', clock=clock) | 216622f59acc4c5053651070fee4deb6202e70c5 | 42,770 |
import math
def test_fallback_abs_float():
"""
Feature: JIT Fallback
Description: Test abs(float) in graph mode
Expectation: No exception
"""
@ms_function
def foo():
x = -1.0
return abs(x)
assert math.isclose(foo(), 1.0, abs_tol=1e-5) | 996253f3b6090422e1c4340f8607053a0dfbc788 | 42,771 |
def sensAnalysis(locator, extraCosts, extraCO2, extraPrim, solarFeat, ntwFeat, gen):
"""
:param locator: path to input locator
:param extraCosts: costs calculated before optimization of specific energy services
(process heat and electricity)
:param extraCO2: green house gas emissions calculated bef... | 11da0be9d25aac235014c4fbd26ac8a9568093d7 | 42,772 |
import requests
def account_addresses_assets(self, stake_address: str, **kwargs):
"""
Obtain information about assets associated with addresses of a specific account.
Be careful, as an account could be part of a mangled address and does not necessarily mean the addresses are owned by user as the account.... | b6b0e276f49c2df90bdd25c61d560a669e93d929 | 42,773 |
import logging
def _get_logger(logger_name):
"""根据名称获取日志器"""
__ = logging.getLogger(logger_name)
_ = LogProxy(__)
loggers.append(_)
return _ | 17b0dc2e8d5fadeb9a3936d6fbf02f20293cc861 | 42,774 |
from datetime import datetime
def detect_resolution(d1: datetime, d2: datetime) -> int:
""" Detects the time difference in milliseconds between two datetimes in ms
:param d1:
:param d2:
:return: time difference in milliseconds
"""
delta = d1 - d2
return int(delta.total_seconds() * 1e3) | a5300254b9f2d84d8111fcb3ad9f222ce6b5a9a6 | 42,775 |
import typing
import re
import html
def parse_image_spec(path: str) -> typing.Tuple[str, utils.ArgDict, typing.Optional[str]]:
""" Parses out a Publ-Markdown image spec into a tuple of path, args, title """
title: typing.Optional[str] = None
# Parse out the title..
match = re.match(r'(.+)\s+\"(.*)\"... | 86374f0ae6dc489d4fd35ad70354e3012a0dd52e | 42,776 |
from typing import List
from typing import Optional
from datetime import datetime
def create_indicates_relationships(
created_by: Identity,
sources: List[_DomainObject],
targets: List[_DomainObject],
confidence: int,
object_markings: List[MarkingDefinition],
start_time: Optional[datetime] = No... | 8e59a256c5b60373dac17b3177b59d3f20fd8917 | 42,777 |
def preprocess_doc(doc: str):
"""
Preprocessing of the string
Args:
doc str: document as string, e.g span
Returns:
[]: tokenized and processed str
"""
return simple_preprocess(doc, deacc=True) | 30f9e1f1242510e05e3165a4e1a888e3b93237d1 | 42,778 |
def _transform_datasets(metadata: dict) -> pd.DataFrame:
"""Transform datasets metadata into a formatted DataFrame."""
df = pd.DataFrame.from_dict(metadata.get("dataSets"))
df = df[
[
"id",
"code",
"shortName",
"name",
"periodType",
... | 11fe69ec4dcf093f1400f192795a0c9320224492 | 42,779 |
def extract_relevant_sentences(tweet, cfg):
"""Extracts all relevant sentences
:param tweet:
:param cfg: configuration map
:returns: dict with keys `in_tweet` and `in_linked_doc` The first
returns a list of sentences extracted from the tweet text proper,
possibly cleaned. `in_linked_doc` has a... | ed765d8c672654fa6c5d24dc820341838d9b3e6d | 42,780 |
import json
def read(socket, freq_start, freq_end, rbw, video, atten, with_data):
"""Return list of satis data."""
socket.send(get_string({
Key.Request: 5,
Key.Start: freq_start,
Key.End: freq_end,
Rbw.name: rbw,
Key.Video: video,
Attenuation.name: atten,
Mode.name: M... | 6560e6347b029aadf789eaad08b02a950d473ab3 | 42,781 |
def request_issues_by_sprint(cfg):
"""Request all issues associated with given sprint"""
issues = []
sprint_issues_url = cjm.request.make_cj_agile_url(
cfg, "sprint/{0:d}/issue".format(cfg["sprint"]["id"]))
start_at = 0
max_results = 50
while True:
response = cjm.request.make_... | 115805a74d593f08e1b0257b1508f49b9cdd00e2 | 42,782 |
def connectRandomNodes(Graph, M=4000):
"""
:param - Graph: snap.PUNGraph object representing an undirected graph
:param - M: number of edges to be added
return type: snap.PUNGraph
return: Graph object with additional M edges added by connecting M randomly
selected pairs of nodes not already... | 4c185d56beb8f1e53b742dbb0b3c1198e95cf463 | 42,783 |
def SimulateIntervals(daily, iters=101, func=RunLinearModel):
"""Run simulations based on different subsets of the data.
daily: DataFrame of daily prices
iters: number of simulations
func: function that fits a model to the data
returns: list of result objects
"""
result_seq = []
starts... | 95ec7cf9bb2a88b8d0b5d8d0e2bb8900390da54d | 42,784 |
from re import T
def sheva_nah_after_short_vowel(last_vowel, guess):
"""`sheva` after short vowel is `sheva-nah`
Source: [Simanim] 3.5
> According to the opinion of the _Minchat Shai_, after a short vowel it
> is a `sheva-nah` even when there is a `meteg` near the short vowel.
Source: [HaMillon]... | dfb895fd1e5add1925b9804117028f5ae2851530 | 42,785 |
def min(col: ColumnExpr) -> ColumnExpr: # pylint: disable=redefined-builtin
"""SQL ``MIN`` function (aggregation)
:param col: the column to find min
.. note::
* this function can infer type from ``col`` type
* this function can infer alias from ``col``'s inferred alias
.. admonition... | a3098e470748cf1dc69fafc025f019824db8e3ef | 42,786 |
def trigger_build(project_name, branch_name):
"""
This task runs our CircleCI builds. If you look at our
"celeryconfig.py" file you would see that we have
CircleCI builds that are scheduled for every 15 minutes, etc.
This basically is responsible for building all of our projects
and uploading th... | 951a67fa3d9dc123fc7ead5b730665b2c639db0c | 42,787 |
def total_distance(solution, distanceMap):
"""
Calculate the total distance among a solution of cities.
Uses a dictionary to get lookup the each pairwise distance.
:param solution: A list of cities in random order.
:distanceMap: The dictionary lookup tool.
:return: The total distance between all... | b478c09540fb93d210df895a9ed31939bf889121 | 42,788 |
def get_design_condition(lineIn):
"""
"""
key = {"hydrotest": r"\b(hydro(test)?)\b",
"operating": r"\b(op(erating)?)\b",
"ultimate": r"\b((ultimate|user))\b"}
keyWord, lineOut, _match = search_line(lineIn, key)
return keyWord | 9a9399996e4f0164f4ee010a752d9a3efb4f0406 | 42,789 |
def get_tite_box(box_in, px_coord=[100, 0]):
"""
Get tight box, px_coord for determine left right border
"""
BORDER = 0
mid_xp = 0
if px_coord[0] < px_coord[1]:
BORDER = 1
mid_xp = (px_coord[1]+px_coord[0])/2
out_boxes = []
ycord, xcord, _ = np.where(box_in == 1)
... | 75e0921b9285c909b0e7e903130af600eaedff7e | 42,790 |
import struct
def py_float2float(val, be=False):
"""
Converts Python float to 4 bytes (double)
"""
sig = '>f' if be else '<f'
return struct.pack(sig, val) | e828bdedc1bca3536d6c6b5c90bf0cb4bf958066 | 42,791 |
import sys
from Support.update import Update
from Support.path import path_text, release_path
from Support.version import __version__
from mglutil import __revision__
from TkinterDnD2 import TkinterDnD
from Tkinter import Tk
from mglutil.splashregister.splashscreen import SplashScreen
from mglutil.splashregister.about ... | 5baa42f58eac15b9ba690f20088c5c931a661ea9 | 42,792 |
import logging
import sys
import os
def setup_logging(log_level=None, log_file=None):
"""
Set up logging for the whole program and return a log handler
Parameters
----------
log_level: str
valid log level to set logging to
log_file: str
name of the log file to log to
Retu... | 8eaedbc574cb9082a1df46b7cbf292c5c6faf388 | 42,793 |
def arg_name(name):
"""Convert snake case argument name to a command line name.
:param str name: The argument parameter name.
:returns: str
"""
return "--" + name.replace('_', '-') | e66284c3a99fe9a75799d4123ad23322089ec2ee | 42,794 |
def stack_str(offset=0, fmt=None, sep=None):
"""
It creates a string representing calling stack from where this function is
called.
Args:
offset:
remove the lowest `offset` frames.
Because usually one does not need the frame of the `k3log.stack_str`
line.
... | a7fd63d2ae8ad3a61138bf760b3e0e51e08540b0 | 42,795 |
def get_latest_model_version(city: str) -> int:
"""Returns the version number of the latest model belonging to the passed city.
Parameters
----------
city: str
Name of the city.
Returns
-------
latest_version: int
Latest model version.
"""
trained_model_query = (
... | 6e5bb6aa62f7012cabc69874bcf5334dedde6be4 | 42,796 |
def delete_event(request, event_id):
"""Event deletion view.
Delete the event specified by the event ID and redirect the user to the
events list.
Arguments:
request - Django object containing request information.
event_id (int) - ID of Event to delete.
Returns:
redirect - Django funct... | bfcd59644b652bc4c4734d8c58609a9636f5505a | 42,797 |
def single_window(
landsat_band_10: np.ndarray,
landsat_band_4: np.ndarray,
landsat_band_5: np.ndarray,
lst_method: str = "mono-window",
emissivity_method: str = "avdan",
unit: str = "kelvin",
) -> np.ndarray:
"""Provides an interface to compute land surface temperature
from landsat ... | d24c0640a3488ed8fe370c3517ddc4f7a182f5e2 | 42,798 |
import numpy
def get_cosine(vec1, vec2):
"""Get cosine for two given vectors"""
OPS = get_current_ops()
v1 = OPS.to_numpy(OPS.asarray(vec1))
v2 = OPS.to_numpy(OPS.asarray(vec2))
return numpy.dot(v1, v2) / (numpy.linalg.norm(v1) * numpy.linalg.norm(v2)) | cc723051d5168ba05ffcdfb97007539fe4f76b07 | 42,799 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.