content stringlengths 35 762k | sha1 stringlengths 40 40 | id int64 0 3.66M |
|---|---|---|
def virus_tsne_list(tsne_df, virus_df):
"""
return data dic
"""
tsne_df.rename(columns={"Unnamed: 0": "barcode"}, inplace=True)
df = pd.merge(tsne_df, virus_df, on="barcode", how="left")
df["UMI"] = df["UMI"].fillna(0)
tSNE_1 = list(df.tSNE_1)
tSNE_2 = list(df.tSNE_2)
virus_UMI = lis... | b8265f3f3d6b602d045a890434322727d8e1adc5 | 12,801 |
def sometimes(aug):
"""
Return a shortcut for iaa.Sometimes
:param aug: augmentation method
:type aug: iaa.meta.Augmenter
:return: wrapped augmentation method
:rtype: iaa.meta.Augmenter
"""
return iaa.Sometimes(0.5, aug) | 95f7ece0b1da30c5a4e3be4d1a21e089e11d9036 | 12,802 |
def rev_to_b10(letters):
"""Convert an alphabet number to its decimal representation"""
return sum(
(ord(letter) - A_UPPERCASE + 1) * ALPHABET_SIZE**i
for i, letter in enumerate(reversed(letters.upper()))
) | b4850e97754f0404894673a51c1cce930e437f6c | 12,803 |
def test_from_rsid(rsids, start_rsid):
"""Continue collecting publications for rsids in list, beginning with start_rsid
Args:
rsids (list): list of rsids to collect publications on
start_rsid (str): rsid identifier to resume collecting publications on
Returns:
runtime_rsids (list):... | bf2be86f28645addc08737e64f08695cd6b3a6d3 | 12,805 |
def _average_scada(times, values, nvalues):
"""
Function which down samples scada values.
:param times: Unix times of the data points.
:param values: Corresponding sensor value
:param nvalues: Number of samples we average over.
:return: new time values and
"""
if len(times) % nvalues:
... | 8743e5065741299befe37b230a22512c65001a09 | 12,806 |
def main():
"""
Test harness
"""
def game_factory():
"""
Creates the game we need
"""
return Maze(Layout.from_string(Layout.MEDIUM_STR))
bot_factory = PlannedBot
trainer = BotTrainer(game_factory, bot_factory, 16, 2, goal_score=13)
start_time = time()
gen... | 0528a4a4c51a4b9491314555d2ccd5c5b9baf328 | 12,807 |
def behavior_of(classname):
"""
Finds and loads the behavior class for C++ (decoded) classname or returns
None if there isn't one.
Behaviors do not have a required base class, and they may be used with
Awkward Array's ``ak.behavior``.
The search strategy for finding behavior classes is:
1... | ce588881e283f53755c7e468de298e6bc360cecc | 12,808 |
def adjust(data):
"""Calculate mean of list of values and subtract the mean of every element
in the list, making a new list.
Returns tuple of mean, list of adjusted values
"""
mu = mean(data)
return mu, map(lambda x: (x-mu), data) | c0ddf7140dee90903452c16afb2625ded34c4d73 | 12,810 |
def clear():
"""
Clears the world, and then returns the cleared representation
"""
myWorld.clear()
return jsonify(myWorld.world()) | 4d999388696986ad9a0a954f3791f0a4795ef69a | 12,811 |
from typing import Optional
from typing import TextIO
def _create_terminal_writer_factory(output: Optional[TextIO]):
"""
A factory method for creating a `create_terminal_writer` function.
:param output: The receiver of all original pytest output.
"""
def _create_terminal_writer(config: Config, _f... | 9c06bd4b10eb5b1dc0e3e4f4f9bdb20074cacf6e | 12,812 |
import typing
def filter(
f: typing.Callable,
stage: Stage = pypeln_utils.UNDEFINED,
workers: int = 1,
maxsize: int = 0,
timeout: float = 0,
on_start: typing.Callable = None,
on_done: typing.Callable = None,
) -> Stage:
"""
Creates a stage that filter the data given a predicate fun... | 741a1d4f941a293b41c98872c59c8bf7e451bba5 | 12,813 |
import numpy
def function_factory(model, loss, dataset):
"""A factory to create a function required by tfp.optimizer.lbfgs_minimize.
Args:
model [in]: an instance of `tf.keras.Model` or its subclasses.
loss [in]: a function with signature loss_value = loss(pred_y, true_y).
train_x [in... | 2e50b3e085d2a88d76de31ba0fccb49f4f38dd1e | 12,814 |
import copy
import time
def nn_CPRAND(tensor,rank,n_samples,n_samples_err,factors=None,exact_err=False,it_max=100,err_it_max=20,tol=1e-7,list_factors=False,time_rec=False):
"""
Add argument n_samples_err
CPRAND for CP-decomposition in non negative case, with err_rand
return also exact error
Paramet... | 8cd3402407a54579ef279efd8b3459c34933c9cb | 12,815 |
def get_base_url(host_name, customer_id):
"""
:arg host_name: the host name of the IDNow gateway server
:arg customer_id: your customer id
:returns the base url of the IDNow API and the selected customer
"""
return 'https://{0}/api/v1/{1}'.format(host_name, customer_id) | 5a24a87f597cf01c61ab6a01202b2e01e3b00bf8 | 12,816 |
def sample_category(user, **params):
"""Create and return a sample category"""
defaults = {
'name': 'Sample category',
'persian_title': 'persian',
'parent_category': None
}
defaults.update(params)
return Category.objects.create(user=user, **defaults) | ec013f1b699c4ae76acb0c78819da875b2453846 | 12,817 |
from typing import Dict
def lindbladian_average_infid_set(
propagators: dict, instructions: Dict[str, Instruction], index, dims, n_eval
):
"""
Mean average fidelity over all gates in propagators.
Parameters
----------
propagators : dict
Contains unitary representations of the gates, i... | 71fcc97afc80bae0e53aea2fafd30b8279f76d08 | 12,818 |
def edit(request, course_id):
"""
Teacher form for editing a course
"""
course = get_object_or_404(Course, id=course_id)
courseForm = CourseForm(request.POST or None, instance=course)
if request.method == 'POST': # Form was submitted
if courseForm.is_valid():
courseForm.sa... | d4f39a26598108d9d5f03ad18fa6de26d88d849d | 12,819 |
def _build_ontology_embedded_list():
""" Helper function intended to be used to create the embedded list for ontology.
All types should implement a function like this going forward.
"""
synonym_terms_embed = DependencyEmbedder.embed_defaults_for_type(base_path='synonym_terms',
... | 2245b82313e26ba741200e24d323f6aa6b9741e0 | 12,820 |
def interp1d(x,y,xi,axis=None,extrap=True):
"""
Args:
x (uniformly sampled vector/array): sampled x values
y (array): sampled y values
xi (array): x values to interpolate onto
axis (int): axis along which to interpolate.
extrap (bool): if True, use linear extrapolation ba... | 081c4f5156cc653804cbd770edaf01ecdb426a51 | 12,821 |
import threading
def _back_operate(
servicer, callback, work_pool, transmission_pool, utility_pool,
termination_action, ticket, default_timeout, maximum_timeout):
"""Constructs objects necessary for back-side operation management.
Also begins back-side operation by feeding the first received ticket into ... | 46999af151338d0d8b15704e913801d9f2c80696 | 12,822 |
from typing import Tuple
import datasets
def load_train_val_data(
data_dir: str, batch_size: int,
training_fraction: float) -> Tuple[DataLoader, DataLoader]:
"""
Returns two DataLoader objects that wrap training and validation data.
Training and validation data are extracted from the full ... | 9cc0c67532e5d77fa8653d43c4f537137905767c | 12,823 |
def match(input_string, start_node):
"""匹配字符串
input_string :: 需要配备的字符串
start_node :: NFA起始节点
return :: True | False
"""
# 初始化运行状态的状态集合: 起始节点+空转移能到达的节点
current_state_set = [start_node]
next_state_set = closure(current_state_set)
# 循环读入字符生成状态集合
for i, ch in enumerate(inp... | fdc7c971cfeb3d0b13716ca1017c6557889d3f52 | 12,824 |
def _H_to_h(H):
"""Converts CIECAM02/CAM02-UCS hue composition (H) to raw hue angle (h)."""
x0 = H % 400 * 360 / 400
h, _, _ = fmin_l_bfgs_b(lambda x: abs(h_to_H(x) - H), x0, approx_grad=True)
return h % 360 | a9ccf1ec14b467b8a5e05b5e71141a4113cf0c07 | 12,825 |
def filter_df_merge(cpu_df, filter_column=None):
"""
process cpu data frame, merge by 'model_name', 'batch_size'
Args:
cpu_df ([type]): [description]
"""
if not filter_column:
raise Exception(
"please assign filter_column for filter_df_merge function")
df_lists = []
... | bc0e147ada18cbbb3e8450f8764d80be3ca32315 | 12,826 |
def MRP2Euler121(q):
"""
MRP2Euler121(Q)
E = MRP2Euler121(Q) translates the MRP
vector Q into the (1-2-1) euler angle vector E.
"""
return EP2Euler121(MRP2EP(q)) | 9cd8da8d38ad668b928ed896004611e85571be0d | 12,827 |
def nlayer(depth=64):
"""Constructs a ResNet-18 model.
Args:
pretrained (bool): If True, returns a model pre-trained on ImageNet
"""
model = NLayer_D(depth=depth)
return model | b8e57716e6b9576de9524cf730309885a79d0bfa | 12,828 |
import typing
def deserialize(
value: ElementTree.Element,
cipher: PSCryptoProvider,
**kwargs: typing.Any,
) -> typing.Optional[typing.Union[bool, PSObject]]:
"""Deserialize CLIXML to a Python object.
Deserializes a CLIXML XML Element from .NET to a Python object.
Args:
value: The CL... | 96b53a08c5c8273f29e108e020c40ab806c0949c | 12,829 |
import requests
def is_url_ok(url: str) -> bool:
"""Check if the given URL is down."""
try:
r = requests.get(url)
return r.status_code == 200
except Exception:
return False | 97e0ba4b609282ef0dc166f0f0407e4aacdf30b2 | 12,830 |
def calculate_pair_energy_np(coordinates, i_particle, box_length, cutoff):
"""
Calculate interaction energy of particle w/ its environment (all other particles in sys)
Parameters
----------------
coordinates : list
the coordinates for all particles in sys
i_particle : int
pa... | c626d1398312e42fd72d70c9b23d397fce5070fd | 12,831 |
def lwhere(mappings, **cond):
"""Selects mappings containing all pairs in cond."""
return list(where(mappings, **cond)) | ade55be28f75ae082833948306c43e4070525f7e | 12,832 |
import re
def get_number(message, limit=4):
"""
convert Chinese to pinyin and extract useful numbers
attention:
1. only for integer
2. before apply this method, the message should be preprocessed
input:
message: the message you want to extract numbers from.
limit: lim... | ae1cc6886a4a2931baa61fcb201ffa67f70aecf6 | 12,833 |
import sqlite3
def create_connection(db_file):
"""
Creates a database connection to the SQLite database
specified by the db_file
:param db_file: database file
:return: Connection object or None
"""
conn = None
try:
conn = sqlite3.connect(db_file)
except Error as e:
... | 37571690b5e970fc4344ee1d5d449b16cfc15896 | 12,835 |
def convex_hull(poly):
"""
ratio of the convex hull area to the area of the shape itself
Altman's A_3 measure, from Neimi et al 1991.
"""
chull = to_shapely_geom(poly).convex_hull
return poly.area / chull.area | 0ed9b4803b87b4138cb5490b153376aae6e71e99 | 12,836 |
from typing import Dict
from typing import List
from typing import Tuple
import torch
def create_scifact_annotations(
claims, corpus, tokenizer, class_to_id: Dict[str, int], neutral_class: str
) -> List[SciFactAnnotation]:
"""Create a SciFactAnnotation for each claim - evidence/cited document pair."""
de... | 0a38b572bac113d6aa0a47e7628a5cc9fec85f16 | 12,837 |
import math
def sort_by_value(front, values):
"""
This function sorts the front list according to the values
:param front: List of indexes of elements in the value
:param values: List of values. Can be longer than the front list
:return:
"""
copied_values = values.copy() # Copy so we can modify it
sor... | 2d259ebbc0117f9aa043d78394b6423e596f176e | 12,839 |
def get_cell_area(self, indices=[]):
"""Return the area of the cells on the outer surface.
Parameters
----------
self : MeshVTK
a MeshVTK object
indices : list
list of the points to extract (optional)
Returns
-------
areas: ndarray
Area of the cells
"""
... | 518416acfae67f1b6e1280d5fd903d311d57f4d8 | 12,841 |
def _to_dataarray(origins, sources, values):
""" Converts grid_search inputs to DataArray
"""
origin_dims = ('origin_idx',)
origin_coords = [np.arange(len(origins))]
origin_shape = (len(origins),)
source_dims = sources.dims
source_coords = sources.coords
source_shape = sources.shape
... | d7ac153f4e872e55ab55ddb76dfcf994e4523443 | 12,842 |
from typing import Optional
from typing import List
from pathlib import Path
import inspect
import pprint
import tempfile
import warnings
import json
def package(metadata: Metadata, requirements: Optional[List[str]] = None, path: Optional[str] = None):
"""Packages the chatbot into a single archive for deployment.... | 0fb974eef4c36bc5fa0e5366eb1bf4634585025a | 12,843 |
def warp_grid(grid: tf.Tensor, theta: tf.Tensor) -> tf.Tensor:
"""
Perform transformation on the grid.
- grid_padded[i,j,k,:] = [i j k 1]
- grid_warped[b,i,j,k,p] = sum_over_q (grid_padded[i,j,k,q] * theta[b,q,p])
:param grid: shape = (dim1, dim2, dim3, 3), grid[i,j,k,:] = [i j k]
:param theta... | 570c3acb6c57aff18b27deaa2ab5401e0fac23b6 | 12,844 |
async def makenotifyrole(guild):
"""Make the notify role in the given guild.
:type guild: discord.Guild
:rtype: None | discord.Role
:param guild: Guild instance to create the role in.
:return: The created role, possibly None if the creation failed.
"""
userrole = None
try:
# The... | 1da1eea0a1d510abdf21bc532f6c1d4ab6d41140 | 12,845 |
def mape(forecast: Forecast, target: Target) -> np.ndarray:
"""
Calculate MAPE.
This method accepts one or many timeseries.
For multiple timeseries pass matrix (N, M) where N is number of timeseries and M is number of time steps.
:param forecast: Predicted values.
:param target: Target values.
... | 47d68499aa351b70d466940d7f3722566cf67568 | 12,846 |
def reverse_weighted_graph(graph):
"""
Function for reverting direction of the graph (weights still the same)
Args:
graph: graph representation as Example: {1: {2: 1, 3: 5}, 2: {3: 2}, 4: {1: 2}}
Returns:
reversed graph
Examples:
>>> reverse_weighted_graph({1: {2: 1, 3: 5}... | 100e05bf3b5e937133321673531103c7abd94bdb | 12,847 |
def clean_bin():
"""permanently deletes entries - crud delete"""
mongo.db.bin.remove()
mongo.db.bin.insert({'_id': ObjectId()})
return redirect(url_for('get_bin', data_requested="teams")) | bb1cb957112826710572bb5930dd1683d4295997 | 12,848 |
def correct_by_threshold(img, threshold):
"""
correct the fMRI RSA results by threshold
Parameters
----------
img : array
A 3-D array of the fMRI RSA results.
The shape of img should be [nx, ny, nz]. nx, ny, nz represent the shape of the fMRI-img.
threshold : int
The nu... | 67750aba6d03d82d9e41d2d53a82550e5a68a3e2 | 12,849 |
def config_date(dut, date):
"""
:param dut:
:param date:
:return:
"""
st.log("config date")
command = "date --set='{}'".format(date)
st.config(dut, command)
return True | 055db1a0ddb4d640d154aae4dec29e3845d7dfb8 | 12,850 |
def read_dicom():
"""Read in DICOM series"""
dicomPath = join(expanduser('~'), 'Documents', 'SlicerDICOMDatabase',
'TCIALocal', '0', 'images', '')
reader = sitk.ImageSeriesReader()
seriesIDread = reader.GetGDCMSeriesIDs(dicomPath)[1]
dicomFilenames = reader.GetGDCMSeriesFileNam... | 64c4aae3c1cc0e31d6db46e741a3ecc52be580cc | 12,851 |
def L_model_backward(AL, Y, caches):
"""
完成L层神经网络模型后向传播计算
Arguments:
AL -- 模型输出值
Y -- 真实值
caches -- 包含Relu和Sigmoid激活函数的linear_activation_forward()中每一个cache
Returns:
grads -- 包含所有梯度的字典
grads["dA" + str(l)] = ...
grads["dW" + str(l)] = ...
grads["db... | ef296179d51e8c4b8be474414f65f812b6f8ffb0 | 12,855 |
def Cnot(idx0: int = 0, idx1: int = 1) -> Operator:
"""Controlled Not between idx0 and idx1, controlled by |1>."""
return ControlledU(idx0, idx1, PauliX()) | a087aa4d7fb22343523a8b6114a7b50eea971e21 | 12,857 |
def init_sql_references(conn):
"""
Utility function to get references from SQL.
The returned objects conveniently identify users based on kb_name or user hashkey
"""
# get kb_names to kb_id
kb_ref = pds.read_sql("""SELECT id, kb_name, directory_id FROM dbo.kb_raw""", conn)
get_kb_dir_id = ... | 3f9874632d50cd8a483d75573cc1d63561f253d2 | 12,858 |
def inoptimal_truncation_square_root(A, B, C, k, check_stability=False):
"""Use scipy to perform balanced truncation
Use scipy to perform balanced truncation on a linear state-space system.
This method is the natural application of scipy and inoptimal performance
wise compared to `truncation_square_roo... | 3c4fa1ac73f22f5e07d49314e1cf3d3b022349e8 | 12,859 |
def _tessellate_bed(chrom: str, chromStart: int, chromEnd: int, window_size: int) -> pd.DataFrame:
"""Return tessellated pandas dataframe splitting given window.
Parameters
-----------------------
chrom: str,
Chromosome containing given window.
chromStart: int,
Position where the wi... | 706b031069dd334bc6f364e077398ced56b152a8 | 12,860 |
def compute_locksroot(locks: PendingLocksState) -> Locksroot:
"""Compute the hash representing all pending locks
The hash is submitted in TokenNetwork.settleChannel() call.
"""
return Locksroot(keccak(b"".join(locks.locks))) | 05c4996a9cc837939c662ef419e36421cb00033d | 12,862 |
from typing import Union
from typing import List
def flatten(text: Union[str, List[str]], separator: str = None) -> str:
"""
Flattens the text item to a string. If the input is a string, that
same string is returned. Otherwise, the text is joined together with
the separator.
Parameters
------... | 3980e0d0d14ac5764c4c5844ab3a943d1971d0ad | 12,863 |
def convert_byte32_arr_to_hex_arr(byte32_arr):
"""
This function takes in an array of byte32 strings and
returns an array of hex strings.
Parameters:
byte32_arr Strings to convert from a byte32 array to a hex array
"""
hex_ids = []
for byte32_str in byte32_arr:
hex_ids = hex_ids... | 9185c1e98b6eb10a42714e1fc53ebaed88997a82 | 12,864 |
from typing import Union
from typing import Tuple
def backtest_loop(
start_time: Union[pd.Timestamp, str],
end_time: Union[pd.Timestamp, str],
trade_strategy: BaseStrategy,
trade_executor: BaseExecutor,
) -> Tuple[PortfolioMetrics, Indicator]:
"""backtest function for the interaction of the outerm... | 74620671f0e37b7439d15d76e0e3e92b8984a608 | 12,866 |
import functools
def failOnNonTransient(func):
"""Only allow function execution when immutable is transient."""
@functools.wraps(func)
def wrapper(inst, *args, **kwargs):
# make the call fail if the object is not transient
if inst.__im_state__ != interfaces.IM_STATE_TRANSIENT:
... | 46b94385084a6b7dae9149cfe8864b94df3ed5ea | 12,867 |
def text_has_emoji(text):
"""判断文本中是否包含emoji"""
for character in text:
if character in emoji.UNICODE_EMOJI:
return True
return False | 8fd0cfb2aed42a6b149f29ffea5d65bc901c5353 | 12,868 |
def rod_faces(n1, n2, xform, dim1, dim2): # validated
"""
defines points in a circle with triangle based end caps
"""
# 4,8,12,16,... becomes 5,9,13,17,...
thetas = np.radians(np.linspace(0., 360., 17))
ntheta = len(thetas)
nfaces = 0
all_faces = []
points_list = []
x = np.zeros... | 306fdde57121f497d6ef263c2caea187bfc7af10 | 12,869 |
def xfork():
""" xfork() is similar to fork but doesn't throw an OSError exception.
Returns -1 on error, otherwise it returns the same value as fork() does.
"""
try:
ret = fork()
except OSError:
ret = -1
return ret | 1bc0c16a2d71e4e1607d45af485a7c2999fbe631 | 12,870 |
import re
def cigar_segment_bounds(cigar, start):
"""
Determine the start and end positions on a chromosome of a non-no-matching part of an
RNA-seq read based on a read's cigar string.
cigar string meaning: http://bioinformatics.cvr.ac.uk/blog/tag/cigar-string/
Example:
'50M25N50M' with ... | c870dfb9b11e2fd1df9fb347528252f114b8d70f | 12,871 |
def augument(data_dir, img_path, steering_angle, range_x=100, range_y=10):
"""
Generate an augumented image and adjust steering angle.
(The steering angle is associated with the image)
"""
image, steering_angle = choose_image(data_dir, img_path, steering_angle)
image, steering_angle = random_fli... | 1eafb5ea4ed024e6bab4008155c8364e8a480b8f | 12,872 |
def ldns_buffer_limit(*args):
"""LDNS buffer."""
return _ldns.ldns_buffer_limit(*args) | d7a4c3c50ffd6db98d78a6a092c256bd1e0e3c11 | 12,873 |
def _call_godot(environment, source, arguments, target):
"""Runs the Godot executable with the specified command line arguments
@param environment Environment in which the Godot executable will be run
@param source Input files that will be involved
@param arguments Arguments that will be p... | 4320a6af9d2d1f8e8a06494df201c9c4a6f2416b | 12,876 |
def random_seeded(func):
""" Decorator that uses the `random_seed` parameter from functions to seed the RNG. """
@wraps(func)
def wrapper(*args, random_seed: int = None, **kwargs):
_RNG.seed(random_seed)
return func(*args, **kwargs)
return wrapper | 1bf572625092680fb996b34469a9a990627acd59 | 12,877 |
def getCRS(station_name=None, crs=None, autoCreate=True):
"""
Method to get CRS code for the give station name. This method may not
scale nicely for a production environment. Use a proper DB instead.
@param station_name: Some characters for the station name.
@param crs: CRS code if known
@p... | e44cda3f0299cc5cc57c2574debe011809e716e6 | 12,878 |
def _initialize_object_from_dict(object_dict, parent=None):
"""Initialize a python object from dict."""
provider = object_dict['provider']
args = object_dict.get('args') or []
kwargs = object_dict.get('kwargs') or {}
obj = _get_object_by_referance(provider)
if parent is not None:
kwarg... | a6fb19c0db1e839514d19df50e223bf98a2241f8 | 12,879 |
def from_hdf(in_path, index=None, keypoints=True, descriptors=True):
"""
For a given node, load the keypoints and descriptors from a hdf5 file. The
keypoints and descriptors kwargs support returning only keypoints or descriptors.
The index kwarg supports returning a subset of the data.
Parameters
... | 2ec00092e04dcd41c7a263781b8a5f7e8d888e5f | 12,880 |
def main(cfg):
"""Solve the CVRP problem."""
# Instantiate the data problem.
data = create_data_model(cfg)
print(data)
if len(data['distance_matrix'])==0:
result = {
"solution":False,
"error-message":"unable to calculate distance matrix"
}
return resul... | a33c1df5462e9af2eb508b7e2803dfd371609656 | 12,881 |
def get_corners(p, fov):
"""Get corners relative to DSS coordinates. xy coords anti-clockwise"""
c = np.array([[0, 0], fov[::-1]]) # lower left, upper right xy
# corners = np.c_[c[0], c[:, 1], c[1], c[::-1, 0]].T # / clockwise yx
corners = np.c_[c[0], c[::-1, 0], c[1], c[:, 1]].T # / clockwise xy
... | e66e4dfd8eb26dc2caacd2e59c64de5d85bc7d10 | 12,882 |
from typing import Dict
from typing import Any
from typing import Tuple
from typing import List
def mixnet_m(
num_classes: int = 1000,
multiplier: float = 1.0,
divisor: int = 8,
min_depth: int = None,
dataset: str = "IMAGENET",
) -> Dict[str, Any]:
"""Build MixNet-M."""
if dataset == "IMAG... | 839852df3bc535613093c752addc6aed64e61e5b | 12,883 |
import functools
import asyncio
def no_block(func):
"""Turns a blocking function into a non-blocking coroutine function."""
@functools.wraps(func)
async def no_blocking_handler(*args, **kwargs):
partial = functools.partial(func, *args, **kwargs)
return await asyncio.get_event_loop().run_i... | 5681fe7275a89c522384b28f9473fded8bba846b | 12,884 |
def wgan_g_loss(scores_fake):
"""
Input:
- scores_fake: Tensor of shape (N,) containing scores for fake samples
Output:
- loss: Tensor of shape (,) giving WGAN generator loss
"""
return -scores_fake.mean() | 089561b47059a4bf07bf878012ce650cd6e34b4f | 12,885 |
import time
def centroid_avg(stats):
"""
Read centroid X and Y 10x and return mean of centroids.
stats : stats method of ophyd camera object to use, e.g. cam_8.stats4
Examples
--------
centroid_avg(cam_8.stats4)
centroidY = centroid_avg(cam_8.stats4)[1]
"""
centroidX... | 5fb1715ab77858084f25400bd8c2508689b57cc1 | 12,886 |
def get_address_host_port(addr, strict=False):
"""
Get a (host, port) tuple out of the given address.
For definition of strict check parse_address
ValueError is raised if the address scheme doesn't allow extracting
the requested information.
>>> get_address_host_port('tcp://1.2.3.4:80')
('1... | a0ec20c347becc6f403b9ee121d127fee41c6b0d | 12,887 |
def get_ua_list():
"""
获取ua列表
"""
with open('zhihu_spider/misc/ua_list.txt', 'r') as f:
return [x.replace('\n', '') for x in f.readlines()] | 6ebcf5d85650ad6644ccdf48aafed0160bd52ec0 | 12,888 |
import time
def measure_time(func):
"""add time measure decorator to the functions"""
def func_wrapper(*args, **kwargs):
start_time = time.time()
a = func(*args, **kwargs)
end_time = time.time()
#print("time in seconds: " + str(end_time-start_time))
return end_time - st... | e9fb4c1b7260cfe686204b50cbe46f27f25c467a | 12,889 |
def generate_dummy_targets(bounds, label, n_points, field_keys=[], seed=1):
"""
Generate dummy points with randomly generated positions. Points
are generated on node 0 and distributed to other nodes if running
in parallel.
Parameters
----------
bounds : tuple of float
Bounding box t... | 6986161499aa62c3e0a9bea4367886dc51736c74 | 12,890 |
from typing import List
def load_numbers_sorted(txt: str) -> List[int]:
"""ファイルから番号を読み込みソートしてリストを返す
Args:
txt (str): ファイルのパス
Returns:
List[int]: 番号のリスト
"""
numbers = []
with open(txt) as f:
numbers = sorted(map(lambda e: int(e), f))
return numbers | 6f10badd417a2ceefefa9f28a5c40583ea077d43 | 12,891 |
def translate_pt(p, offset):
"""Translates point p=(x,y) by offset=(x,y)"""
return (p[0] + offset[0], p[1] + offset[1]) | 9fdc578d461219e9e5d1b557b9fde3d7a0946815 | 12,893 |
def truncate(sequence):
""" Do nothing. Just a placeholder. """
string = str(sequence)
return string.split()[0] | 2e8eeffb08d6d3d5d6ad5e6a83e596ec61a2eea2 | 12,895 |
def unbind(port: int) -> dict:
"""Request browser port unbinding.
Parameters
----------
port: int
Port number to unbind.
"""
return {"method": "Tethering.unbind", "params": {"port": port}} | c980eaa28e29dd44139035f0c8882d2960322328 | 12,896 |
def xy_to_ellipse(x,Vx,y,Vy):
"""
Takes the Cartesian variables.
This function returns the particle's position relative to an ellipse and parameters of the ellipse.
Returns a,e,theta,theta_E
"""
# radius using x and y
r = np.sqrt(x ** 2 + y ** 2)
# speed of the particle
V =... | 2606a81899431349adc419b04d87063f2e75936a | 12,898 |
from typing import List
from typing import Dict
from typing import OrderedDict
def leak_dictionary_by_ignore_sha(
policy_breaks: List[PolicyBreak],
) -> Dict[str, List[PolicyBreak]]:
"""
leak_dictionary_by_ignore_sha sorts matches and incidents by
first appearance in file.
sort incidents by first... | d94bc10b8f2d94eee639bd94e75ad5835d9b6f1a | 12,899 |
async def get_token(tkn: Token = Depends(from_authotization_header_nondyn)):
"""
Returns informations about the token currently being used. Requires a
clearance level of 0 or more.
"""
assert_has_clearance(tkn.owner, "sni.read_own_token")
return GetTokenOut.from_record(tkn) | 19ea12ad43a4a61f940e9dce4ca3c4a5d6fbbdf2 | 12,900 |
def import_as_event_history(path):
"""
Import file as event history json format.
Parameters
----------
path : str
Absolute path to file.
Returns
-------
events : list
List of historic events.
"""
# initialise output list
events = []
# import through... | 1c4362263d177bf2d2a5561d3ed2048ff23faeb2 | 12,901 |
def reduce_dataset(d: pd.DataFrame, reduction_pars: dict):
"""
Reduces the data contained in a pandas DataFrame
:param d: pandas DataFrame. Each column contains lists of numbers
:param reduction_pars: dict containing 'type' and 'values'. 'type' describes the type of reduction performed on the
lists ... | 080bb5486787fab25bbc9347e83ed79d4525abe8 | 12,902 |
def update_office(office_id):
"""Given that i am an admin i should be able to edit a specific political office
When i visit to .../api/v2/offices endpoint using PATCH method"""
if is_admin() is not True:
return is_admin()
if not request.get_json():
return make_response(jsonify({'statu... | 897ee73b508caf1e3d463f68d55c030259efb6e5 | 12,903 |
def phraser_on_header(row, phraser):
"""Applies phraser on cleaned header.
To be used with methods such as: `apply(func, axis=1)` or
`apply_by_multiprocessing(func, axis=1, **kwargs)`.
Parameters
----------
row : row of pd.Dataframe
phraser : Phraser instance,
Returns
-------
... | 30b9f11607ce1769b15a1c4fda4a4bc3b0aea94b | 12,905 |
def hard_nms(box_scores, iou_threshold, top_k=-1, candidate_size=200):
"""
Args:
box_scores (N, 5): boxes in corner-form and probabilities.
iou_threshold: intersection over union threshold.
top_k: keep top_k results. If k <= 0, keep all the results.
candidate_size: only consider... | 44a6dbcd0db425196bd91f22907be395d270b3d8 | 12,907 |
def sma(data, span=100):
"""Computes and returns the simple moving average.
Note: the moving average is computed on all columns.
:Input:
:data: pandas.DataFrame with stock prices in columns
:span: int (defaul: 100), number of days/values over which
the average is computed
:Output:
... | 8f8abf7f851424c20f6cee2ad4a01b934b7b0182 | 12,908 |
def parse_csd(dependencies):
"""Parse C-State Dependency"""
return _CSD_factory(len(csd_data))(csd_data) | 54ab24def420fd8350e1130b98be6b4651464fb8 | 12,909 |
def field_path_get_type(root: HdlType, field_path: TypePath):
"""
Get a data type of element using field path
"""
t = root
for p in field_path:
if isinstance(p, int):
t = t.element_t
else:
assert isinstance(p, str), p
t = t.field_by_name[p].dtype
... | d6c5f0c750149505e6da78f7b3e3ed602b8f30b0 | 12,910 |
def reverse(rule):
"""
Given a rule X, generate its black/white reversal.
"""
#
# https://www.conwaylife.com/wiki/Black/white_reversal
#
# "The black/white reversal of a pattern is the result of
# toggling the state of each cell in the universe: bringing
# dead cells to life, and killing live cells.... | 0451b2a49257540b8a069f4cdb96d6bff4337cb7 | 12,911 |
import torch
def hsic(k_x: torch.Tensor, k_y: torch.Tensor, centered: bool = False, unbiased: bool = True) -> torch.Tensor:
"""Compute Hilbert-Schmidt Independence Criteron (HSIC)
:param k_x: n by n values of kernel applied to all pairs of x data
:param k_y: n by n values of kernel on y data
:param c... | 7c91aa5991b90f396abbf835111a456208cbc50a | 12,912 |
def task_group_task_ui_to_app(ui_dict):
"""Converts TaskGroupTask ui dict to App entity."""
return workflow_entity_factory.TaskGroupTaskFactory().create_empty(
obj_id=ui_dict.get("obj_id"),
title=ui_dict["title"],
assignees=emails_to_app_people(ui_dict.get("assignees")),
start_date=str_to_da... | 64ad5bc96b56c2feb41417890c6f04c0f17e4691 | 12,913 |
def int_converter(value):
"""check for *int* value."""
int(value)
return str(value) | ba1b780c7886fccf1203225de249ef129561fd36 | 12,914 |
def wraps(fun, namestr="{fun}", docstr="{doc}", **kwargs):
"""Decorator for a function wrapping another.
Used when wrapping a function to ensure its name and docstring get copied
over.
Args:
fun: function to be wrapped
namestr: Name string to use for wrapped function.
docstr: Docstri... | af05b43ee3ac2cc8595d35148b0156cd441dce3a | 12,915 |
from re import L
def test_plot_distributed_loads_fixed_left():
"""Test the plotting function for distributed loads and fixed support on the left.
Additionally, test plotting of continuity points.
"""
a = beam(L)
a.add_support(0, "fixed")
a.add_distributed_load(0, L / 2, "-q * x")
a.add_dis... | 2c7c2b37e19e69a66a751bf59c3150f0b7aa3d3f | 12,916 |
import requests
import json
def post_report(coverage):
"""Post coverage report to coveralls.io."""
response = requests.post(URL, files={'json_file': json.dumps(coverage)})
try:
result = response.json()
except ValueError:
result = {'error': 'Failure to submit data. '
'... | a33affb2791d3dbb7528ce9d4aae6a89f46d03f2 | 12,917 |
import tokenize
def parse_dialogs_per_response(lines,candid_dic,profile_size=None):
"""Parse dialogs provided in the personalized dialog tasks format.
For each dialog, every line is parsed, and the data for the dialog is made by appending
profile, user and bot responses so far, user utterance, bot answer ... | b919a9d970e93da9de6221f29573261f83158e49 | 12,918 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.