content stringlengths 35 762k | sha1 stringlengths 40 40 | id int64 0 3.66M |
|---|---|---|
def plot_karyotype_summary(haploid_coverage,
chromosomes,
chrom_length,
output_dir,
bed_filename,
bed_file_sep=',',
binsize=1000000,
... | 5234b2ac9e459cfe445be6820abb97821503f554 | 3,649,200 |
import os
import bisect
def create_percentile_rasters(
raster_path, output_path, units_short, units_long, start_value,
percentile_list, aoi_shape_path):
"""Creates a percentile (quartile) raster based on the raster_dataset. An
attribute table is also constructed for the raster_dataset that... | 69f8ea165141ceac4f0f272e36662bbd820b8e0a | 3,649,201 |
import torch
def probs_to_mu_sigma(probs):
"""Calculate mean and covariance matrix for each channel of probs
tensor of keypoint probabilites [N, C, H, W]
mean calculated on a grid of scale [-1, 1]
Parameters
----------
probs : torch.Tensor
tensor of shape [N, C, H, W] where each chann... | d0653e50d1f9ec4125e9b30c10a0e6cb78c6dc8e | 3,649,202 |
def fetch_biomart_genes_mm9():
"""Fetches mm9 genes from Ensembl via biomart."""
return _fetch_genes_biomart(
host='http://may2012.archive.ensembl.org',
gene_name_attr='external_gene_id') | f184608e87a2d390b47fd0f78d293dfd52064ad0 | 3,649,203 |
def tweet_words(tweet):
"""Return the words in a tweet."""
return extract_words(tweet_text(tweet)) | c207553fa1bd718083d26e57a9daea43c5629116 | 3,649,204 |
def meter_statistics(meter_id,api_endpoint,token,meter_list,web,**kwargs):
"""
Get the statistics for the specified meter.
Args:
meter_id(string): The meter name.
api_endpoint(string): The api endpoint for the ceilometer service.
token(string): X-Auth-token.
meter_list(list): T... | 33c717dee32027a1502a5a295b87c5cd67a2c054 | 3,649,205 |
from typing import Union
from typing import Tuple
def parse_image_size(image_size: Union[Text, int, Tuple[int, int]]):
"""Parse the image size and return (height, width).
Args:
image_size: A integer, a tuple (H, W), or a string with HxW format.
Returns:
A tuple of integer (height, width).
... | 12d8925780914672b1e7d976040596f3178e7e20 | 3,649,206 |
def find_last_match(view, what, start, end, flags=0):
"""Find last occurrence of `what` between `start`, `end`.
"""
match = view.find(what, start, flags)
new_match = None
while match:
new_match = view.find(what, match.end(), flags)
if new_match and new_match.end() <= end:
... | fc863cf00d05a1fb6302a34b5b1e891e3c9eb3d7 | 3,649,207 |
def convert_metrics_per_batch_to_per_sample(metrics, target_masks):
"""
Args:
metrics: list of len(num_batches), each element: list of len(num_metrics), each element: (num_active_in_batch,) metric per element
target_masks: list of len(num_batches), each element: (batch_size, seq_len, feat_dim) b... | 2ceae1402ac0efae841683d426f87a295f3695c8 | 3,649,208 |
import asyncio
async def get_series(database, series_id):
"""Get a series."""
series_query = """
select series.id, series.played, series_metadata.name, rounds.tournament_id, tournaments.id as tournament_id,
tournaments.name as tournament_name, events.id as event_id, events.name as event_name
... | f5e122052209c399c41afcd579f9b16e863c7a28 | 3,649,209 |
def n_mpjpe(predicted, target):
"""
Normalized MPJPE (scale only), adapted from:
https://github.com/hrhodin/UnsupervisedGeometryAwareRepresentationLearning/blob/master/losses/poses.py
"""
assert predicted.shape == target.shape
norm_predicted = np.mean(np.sum(predicted**2, axis=2, keepdims=T... | 68656aca6226db3a4cc7670ccc1972d666b11261 | 3,649,210 |
import math
def calc_distance(p1, p2):
""" calculates a distance on a 2d euclidean space, between two points"""
dist = math.sqrt((p2[0] - p1[0]) ** 2 + (p2[1] - p1[1]) ** 2)
return dist | d4005d44d5724c051860fb9aa2edeab1654157c6 | 3,649,211 |
def rgb2ycbcr(img, range=255., only_y=True):
"""same as matlab rgb2ycbcr, please use bgr2ycbcr when using cv2.imread
img: shape=[h, w, 3]
range: the data range
only_y: only return Y channel
"""
in_img_type = img.dtype
img.astype(np.float32)
range_scale = 255. / range
img *= range_sca... | e3dfd7b35faf437a936813afe537d1d4a41b2f6b | 3,649,212 |
def _create_xctest_bundle(name, actions, binary):
"""Creates an `.xctest` bundle that contains the given binary.
Args:
name: The name of the target being built, which will be used as the
basename of the bundle (followed by the .xctest bundle extension).
actions: The context's action... | cf6c64b73b7fcbd7df2a5e6bb60e0605b16a8f58 | 3,649,213 |
def doFile(path_, *args, **kwargs):
"""Execute a given file from path with arguments."""
result, reason = loadfile(path_)
if result:
data = result(*args, **kwargs)
if data:
return data[1]
error(data[1])
error(reason) | 15c6dd79872b479275717fb8a574a34f92381390 | 3,649,214 |
from pretty import pretty
from pprint import pformat
def pformat(obj, verbose=False):
"""
Prettyprint an object. Either use the `pretty` library or the
builtin `pprint`.
"""
try:
return pretty(obj, verbose=verbose)
except ImportError:
return pformat(obj) | 7522c9b64650a5056fb22d7fdd0c459ce87ca7c7 | 3,649,215 |
def reanalyze_function(*args):
"""
reanalyze_function(func_t pfn, ea_t ea1=0, ea_t ea2=BADADDR, bool analyze_parents=False)
reanalyze_function(func_t pfn, ea_t ea1=0, ea_t ea2=BADADDR)
reanalyze_function(func_t pfn, ea_t ea1=0)
reanalyze_function(func_t pfn)
"""
return _idaapi.reanalyze_function... | 52d248fbb82ebb41ff925c42b7cb6856c5cba927 | 3,649,216 |
def categorical_sample_logits(logits):
"""
Samples (symbolically) from categorical distribution, where logits is a NxK
matrix specifying N categorical distributions with K categories
specifically, exp(logits) / sum( exp(logits), axis=1 ) is the
probabilities of the different classes
Cleverly ... | c5bf8615fe3c25f392bc3fa27f965527f237ef3e | 3,649,217 |
def mass(d, r):
""" computes the right hand side of the differential equation of mass continuity
"""
return 4 * pi * d * r * r | 1924309951e35d36b51fe92389c3fa68fac3ebfa | 3,649,218 |
def bord(u):
"""
éxécution de bord("undébutuntructrucundébut")
i suffix estPréfixe
23 ndébutuntructrucundébut False
22 débutuntructrucundébut False
21 ébutuntructrucundébut False
20 butuntructrucundébut False
19 utuntructrucundébut False
18 tuntructrucundé... | 950eaac804a0788c9d2f845d594b7781d5ea9aa4 | 3,649,219 |
def is_unique_n_bit_vector(string: str) -> bool:
"""
Similiar to the dict solution, it just uses a bit vector instead of a dict or array.
"""
vector = 0
for letter in string:
if vector & 1 << ord(letter):
return False
vector |= 1 << ord(letter)
return True | d19609f1fb1e6a189a9adb11b37a96632c8d0958 | 3,649,220 |
def seq2msk(isq):
"""
Convert seqhis into mskhis
OpticksPhoton.h uses a mask but seq use the index for bit-bevity::
3 enum
4 {
5 CERENKOV = 0x1 << 0,
6 SCINTILLATION = 0x1 << 1,
7 MISS = 0x1 << 2,
8 BU... | 950dc8fe1fcc275f7a90e695816ea1777cc5164e | 3,649,221 |
def split(ich):
""" Split a multi-component InChI into InChIs for each of its components.
(fix this for /s [which should be removed in split/join operations]
and /m, which is joined as /m0110.. with no separators)
:param ich: InChI string
:type ich: str
:rtype: tuple(str)... | 0db3bee951e38f7db8cbcdb02a64ed28b9562e9d | 3,649,222 |
def crtb_cb(client, crtb):
"""Wait for the crtb to have the userId populated"""
def cb():
c = client.reload(crtb)
return c.userId is not None
return cb | eff248a877e195e59d2f6db812af2ff43955aee0 | 3,649,223 |
def create_network(network_input, n_alphabets):
""" create the structure of the neural network """
model = Sequential()
model.add(LSTM(512,input_shape=(network_input.shape[1], network_input.shape[2]),return_sequences=True))
model.add(Dropout(0.3))
model.add(Bidirectional(LSTM(512, return_sequences=T... | dd6610f0db02d0d20fb457d91346144494ad32e4 | 3,649,224 |
def create_derivative_graph(f, xrange, n):
"""Takes a function as an input with a specific interval xrange, then creates a list with the ouput
y-points for the nth derivative of f.
:param f: Input function that we wish to take the derivative of.
:type f: lambda
:param xrange: The interval on wh... | 782d26d22c93ae4b05d075fbf4075a8bba9d89b8 | 3,649,225 |
def _matching_not_matching(on, **kwargs):
"""
Change the text for matching/not matching
"""
text = "matching" if not on else "not matching"
classname = "colour-off" if not on else "colour-on"
return text, classname | aeefa7f16e3268ffe7af93db72490abe053370b2 | 3,649,226 |
import os
def prepare_testenv(config=None, template=None, args=None):
"""
prepare an engine-ready environment for a test
This utility method is used to provide an `RelengEngine` instance ready for
execution on an interim working directory.
Args:
config (optional): dictionary of options t... | f1d021ed0eedcc9b0481ba3524581e5fd5aa241b | 3,649,227 |
def sample(model, x, steps, temperature=1.0, sample=False, top_k=None):
"""
take a conditioning sequence of indices in x (of shape (b,t)) and predict the next token in
the sequence, feeding the predictions back into the model each time. Clearly the sampling
has quadratic complexity unlike an RNN that is... | 532ad7e1af4c7b059bbd12a8584c469bcb5d079e | 3,649,228 |
def vstack(arg_list):
"""Wrapper on vstack to ensure list argument.
"""
return Vstack(*arg_list) | 95215c8277da6b86c21220021d667ae3dcc05440 | 3,649,229 |
import json
def metadata_to_list(metadata):
"""Transform a metadata dictionary retrieved from Cassandra to a list of
tuples. If metadata items are lists they are split into multiple pairs in
the result list
:param metadata: dict"""
res = []
for k, v in metadata.iteritems():
try:
... | 1044a93742a635e72e443d3a5c2e5805702d1602 | 3,649,230 |
def GetSetUpAndResponse():
"""
This method is called by an API acting as a client while performing the PSI protocol.
This method initialises a server object. (This API acts as server)
This method uses the PSI Request ID given by the calling API to identify the corresponding node list from the server di... | b8795f5aaebcf28c448e81d725a3b4235c5490c2 | 3,649,231 |
from typing import Optional
from typing import Union
import torch
from pathlib import Path
import json
def load_separator(
model_str_or_path: str = "umxhq",
niter: int = 1,
residual: bool = False,
slicq_wiener: bool = False,
wiener_win_len: Optional[int] = 300,
device: Union[str, torch.device]... | 2cb2d951d669c7d08a3bf3cabc5c49a11ca717fc | 3,649,232 |
def IntermediateParticleConst_get_decorator_type_name():
"""IntermediateParticleConst_get_decorator_type_name() -> std::string"""
return _RMF.IntermediateParticleConst_get_decorator_type_name() | efb869aece5ad0f19e06f5d1a13e89998cde53a8 | 3,649,233 |
def multiply_add_plain_with_delta(ct, pt, context_data):
"""Add plaintext to ciphertext.
Args:
ct (Ciphertext): ct is pre-computed carrier polynomial where we can add pt data.
pt (Plaintext): A plaintext representation of integer data to be encrypted.
context (Context): Context for extr... | 4f004cc443d183f25cf35bc691c9797b4a8a5875 | 3,649,234 |
def ginput(n=1, timeout=30, debug=False):
"""
Simple functional call for physicists. This will wait for n clicks
from the user and
return a list of the coordinates of each click.
"""
x = GaelInput()
return x(n, timeout, debug) | 60c7c89774fcaee0143003fc6e2d66a4dc1c356b | 3,649,235 |
import json
from datetime import datetime
def retrieve_form_data(form, submission_type="solution"):
"""Quick utility function that groups together the processing of request data. Allows for easier handling of exceptions
Takes request object as argument
On Success, returns hashmap of processed data...other... | 4ab635ac226ebb7811baf2d0e3d71c8cfc25b1da | 3,649,236 |
import os
def existing_file(fname):
"""
Check if the file exists. If not raise an error
Parameters
----------
fname: string
file name to parse
Returns
-------
fname : string
"""
if os.path.isfile(fname):
return fname
else:
msg = "The file '{}' does... | 2e93559868588398c255d512a6009df0556df742 | 3,649,237 |
def keep_english_for_spacy_nn(df):
"""This function takes the DataFrame for songs
and keep songs with english as main language
for english version of spacy neural network for word processing"""
#Keep only english for spacy NN English preprocessing words
#Network for other languages like fre... | e24402fa91ee0444c86867c98777fbd3cb7c9894 | 3,649,238 |
def make_dealer_cards_more_fun(deck, dealer):
"""
to make dealercards more fun to make dealer win this game more.
:param dealercards: dealercards
:return: none
maybe has a lot of memory work will arise.
"""
dealercards = card_sorting_dealer(dealer)
count = 0
if jokbo(dealercards) =... | 5adf8fbeeb53124c75ec43a13492d7aef1ebdc7e | 3,649,239 |
import os
import configparser
import logging
def subinit1_initpaths_config_log():
"""
Initializes the paths (stored in global __PATHS):
1 Finds the project location
2 Reads config.ini
3 Reads the paths defined in config.ini
4 Checks that the paths exist
"""
# ----------------------------------------------... | d2edfc46736b742cb2707b3c90915889e729f7ff | 3,649,240 |
def data(request):
"""Returns available albums from the database. Can be optionally filtered by year.
This is called from templates/albums/album/index.html when the year input is changed.
"""
year = request.GET.get('year')
if year:
try:
year = int(year)
except (ValueErro... | 8390bcc6fd2bcc109930cb34b3269b450c12a87c | 3,649,241 |
from typing import Tuple
def yaw_to_quaternion3d(yaw: float) -> Tuple[float,float,float,float]:
"""
Args:
- yaw: rotation about the z-axis
Returns:
- qx,qy,qz,qw: quaternion coefficients
"""
qx,qy,qz,qw = Rotation.from_euler('z', yaw).as_quat()
return qx,qy,qz,qw | 263a0b12e0c165f929c5004cdb67b8133f117140 | 3,649,242 |
def parse_coap_response_code(response_code):
"""
Parse the binary code from CoAP response and return the response code as a float.
See also https://tools.ietf.org/html/rfc7252#section-5.9 for response code definitions.
:rtype float
"""
response_code_class = response_code // 32
response_code... | 9a8165f205ec2f6fe8576e18a831498f82834a10 | 3,649,243 |
from functools import reduce
def modified_partial_sum_product(
sum_op, prod_op, factors, eliminate=frozenset(), plate_to_step=dict()
):
"""
Generalization of the tensor variable elimination algorithm of
:func:`funsor.sum_product.partial_sum_product` to handle markov dimensions
in addition to plate... | 24d5f529d03eeb3a332cc861fdabff3a0d613d37 | 3,649,244 |
def load_scicar_cell_lines(test=False):
"""Download sci-CAR cell lines data from GEO."""
if test:
adata = load_scicar_cell_lines(test=False)
adata = subset_joint_data(adata)
return adata
return load_scicar(
rna_url,
rna_cells_url,
rna_genes_url,
atac_u... | 4760b41e2a29125ba9eaf597c555b1b40e338612 | 3,649,245 |
def binary_search(sorted_list, item):
"""
Implements a Binary Search, O(log n).
If item is is list, returns amount of steps.
If item not in list, returns None.
"""
steps = 0
start = 0
end = len(sorted_list)
while start < end:
steps += 1
mid = (start + end) // 2
... | 30b1bba330752455d932b4c6cf1ad4dab5969db3 | 3,649,246 |
from typing import List
import os
def _process_split(
pipeline,
*,
filename_template: naming.ShardedFileTemplate,
out_dir: utils.ReadWritePath,
file_infos: List[naming.FilenameInfo],
):
"""Process a single split."""
beam = lazy_imports_lib.lazy_imports.apache_beam
# Use unpack syntax on set... | cb5134cb5213de817d49ad9239ef96be8c8e750b | 3,649,247 |
def _scale_by(number, should_fail=False):
"""
A helper function that creates a scaling policy and scales by the given
number, if the number is not zero. Otherwise, just triggers convergence.
:param int number: The number to scale by.
:param bool should_fail: Whether or not the policy execution sho... | 046dcaf120d4c04578e9562b23f76f1cb8f98690 | 3,649,248 |
import traceback
def selectgender(value):
"""格式化为是/否
:param value:M/F,
:return: 男/女
"""
absent = {"M": u'男', "F": u'女'}
try:
if value:
return absent[value]
return ""
except:
traceback.print_exc() | 7b6b0b41b5ea8d3eaab5574881b40f5c00da73cd | 3,649,249 |
def Clifford_twirl_channel_one_qubit(K, rho, sys=1, dim=[2]):
"""
Twirls the given channel with Kraus operators in K by the one-qubit
Clifford group on the given subsystem (specified by sys).
"""
n = int(np.log2(np.sum([d for d in dim])))
C1 = eye(2**n)
C2 = Rx_i(sys, np.pi, n)
C3 = Rx... | 1225c8689641e245d7666c75f9e31d862f1efe56 | 3,649,250 |
def unpack_batch(batch, use_cuda=False):
""" Unpack a batch from the data loader. """
input_ids = batch[0]
input_mask = batch[1]
segment_ids = batch[2]
boundary_ids = batch[3]
pos_ids = batch[4]
rel_ids = batch[5]
knowledge_feature = batch[6]
bio_ids = batch[1]
# knowledge_adjoin... | 6bc8bc9b3c8a9e2b40ac08e67c9fbcf84914e2eb | 3,649,251 |
def truncate(text: str, length: int = 255, end: str = "...") -> str:
"""Truncate text.
Parameters
---------
text : str
length : int, default 255
Max text length.
end : str, default "..."
The characters that come at the end of the text.
Returns
-------
truncated text... | f14605542418ca95e4752be7ec2fea189b9454ce | 3,649,252 |
from sys import path
import logging
def create_logger(log_dir, log_file, level="info"):
"""
Function used to create logger object based on log directory
and log file name
"""
handler = RotatingFileHandler(filename=path.join(log_dir, log_file),
mode='a', maxBytes=5... | 128abb796c7a602dee3d835c3f3c39ccf5f07c56 | 3,649,253 |
def gaussian_slice(x, sigma, mu):
"""
return a slice of x in which the gaussian is significant
exp(-0.5 * ((x - mu) / sigma) ** 2) < given_threshold
"""
r = sigma * sp.sqrt(-2.0 * sp.log(small_thr))
x_lo = bisect_left(x, mu - r)
x_hi = bisect_right(x, mu + r)
return slice(x_lo, x_hi) | 25ed1bf4423e8d86baaebec54e4478b58b58365c | 3,649,254 |
def preview(delivery_id):
"""
打印预览
:param delivery_id:
:return:
"""
delivery_info = get_delivery_row_by_id(delivery_id)
# 检查资源是否存在
if not delivery_info:
abort(404)
# 检查资源是否删除
if delivery_info.status_delete == STATUS_DEL_OK:
abort(410)
delivery_print_date = ti... | d57acf49d7692fe4da02607695ad71fdad1758e5 | 3,649,255 |
import requests
def request_with_json(json_payload):
"""
Load interpolations from the interp service into the DB
"""
test_response = requests.post(INTERP_URL, json=json_payload)
test_response_json = test_response.json()
return test_response_json | 5222060788ce321d258fa23309f5894640a70589 | 3,649,256 |
def correlation(df, rowvar=False):
"""
Calculate column-wise Pearson correlations using ``numpy.ma.corrcoef``
Input data is masked to ignore NaNs when calculating correlations. Data is returned as
a Pandas ``DataFrame`` of column_n x column_n dimensions, with column index copied to
both axes.
... | b64ab2f5f08191c9536f6d08b8132b3ecc100698 | 3,649,257 |
def cost_zpk_fit(zpk_args, f, x,
error_func=kontrol.core.math.log_mse,
error_func_kwargs={}):
"""The cost function for fitting a frequency series with zero-pole-gain.
Parameters
----------
zpk_args: array
A 1-D list of zeros, poles, and gain.
Zeros and ... | fb18cfae20a279e0b65a03b37a10c33e6a17c6db | 3,649,258 |
def getTrainPredictions(img,subImgSize,model):
"""Makes a prediction for an image.
Takes an input of any size, crops it to specified size, makes
predictions for each cropped window, and stitches output together.
Parameters
----------
img : np.array (n x m x 3)
Image to be transformed
... | e81ee8d6839fa07753ac379520c60d7b2d5be175 | 3,649,259 |
def use_bcbio_variation_recall(algs):
"""Processing uses bcbio-variation-recall. Avoids core requirement if not used.
"""
for alg in algs:
jointcaller = alg.get("jointcaller", [])
if not isinstance(jointcaller, (tuple, list)):
jointcaller = [jointcaller]
for caller in joi... | c833f9a2dd9523f78cf294a1822b251b6940a1cd | 3,649,260 |
from typing import Mapping
def _sa_model_info(Model: type, types: AttributeType) -> Mapping[str, AttributeInfo]:
""" Get the full information about the model
This function gets a full, cachable, information about the model's `types` attributes, once.
sa_model_info() can then filter it the way it likes, w... | 8886427a4722bb1fb37664fa7382f61922d89b69 | 3,649,261 |
def bll6_models(estimators, cv_search={}, transform_search={}):
"""
Provides good defaults for transform_search to models()
Args:
estimators: list of estimators as accepted by models()
transform_search: optional LeadTransform arguments to override the defaults
"""
cvd = dict(
... | c69d17c1f5c6625ef6382959910b23d44459c158 | 3,649,262 |
def bgColor(col):
""" Return a background color for a given column title """
# Auto-generated columns
if col in ColumnList._COLUMNS_GEN:
return BG_GEN
# KiCad protected columns
elif col in ColumnList._COLUMNS_PROTECTED:
return BG_KICAD
# Additional user columns
else:
... | ae6a44c61807f513a679ccad0f4c39622efa768e | 3,649,263 |
def merge_hedge_positions(df, hedge):
"""
将一个表中的多条记录进行合并,然后对冲
:param self:
:param df:
:return:
"""
# 临时使用,主要是因为i1709.与i1709一类在分组时会出问题,i1709.是由api中查询得到
if df.empty:
return df
df['Symbol'] = df['InstrumentID']
# 合并
df = df.groupby(by=['Symbol', 'InstrumentID', 'HedgeFla... | 4bcaa8b160186c6c5e6e3382017d0db3ee9d6c6e | 3,649,264 |
import numpy
def BackwardSubTri(U,y):
"""
usage: x = BackwardSubTri(U,y)
Row-oriented backward substitution to solve the upper-triangular, 'tridiagonal'
linear system
U x = y
This function does not ensure that U has the correct nonzero structure. It does,
however, attempt to catch ... | 5b7c2c636eac0912aa26bc8a236f1c870b95c48b | 3,649,265 |
def discrete_model(parents, lookup_table):
"""
Create CausalAssignmentModel based on a lookup table.
Lookup_table maps inputs values to weigths of the output values
The actual output values are sampled from a discrete distribution
of integers with probability proportional to the weights.
Looku... | a0eee81439b5997b91941181b8c7978d7f3581c9 | 3,649,266 |
import base64
import json
import tempfile
import traceback
def retrieve(datafile, provider):
"""
Retrieve a file from the remote provider
:param datafile:
:param provider:
:return: the path to a temporary file containing the data, or None
"""
r = _connect(provider)
try:
data =... | fca0595df40b1743e5cdb73c8a20b0ddc6a2611f | 3,649,267 |
def edf_parse_message(EDFFILE):
"""Return message info."""
message = edf_get_event_data(EDFFILE).contents
time = message.sttime
message = string_at(byref(message.message[0]), message.message.contents.len + 1)[2:]
message = message.decode('UTF-8')
return (time, message) | 3d29db28b7d110e9fcdf6e8309c027cb4254c647 | 3,649,268 |
from typing import Dict
import logging
def read_abbrevs_and_add_to_db(abbrevs_path: str,
db: Connection) -> Dict[str, int]:
"""Add abbreviations from `abbrevs_path` to `idx` and `defns`."""
with open(abbrevs_path, 'rt') as ab:
abbrevs = read_abbrevs(ab)
abbrev_nid = ... | 6c937fd15352d8b7e3dcf607bbf2a5b66f105ffb | 3,649,269 |
def is_encrypted(input_file: str) -> bool:
"""Checks if the inputted file is encrypted using PyPDF4 library"""
with open(input_file, 'rb') as pdf_file:
pdf_reader = PdfFileReader(pdf_file, strict=False)
return pdf_reader.isEncrypted | be03d2843f35e21d7881c17f086f33ffbee5e8fa | 3,649,270 |
def get_parameter_by_name(device, name):
""" Find the given device's parameter that belongs to the given name """
for i in device.parameters:
if i.original_name == name:
return i
return | 9669262a9bcac8b4c054e07b2c04b780b5f84f87 | 3,649,271 |
from typing import Optional
import requests
def LogPrint(email: str, fileName: str, materialType: str, printWeight: float, printPurpose: str, msdNumber: Optional[str], paymentOwed: bool) -> bool:
"""Logs a print. Returns if the task was successful.
:param email: Email of the user exporting the print.
:pa... | eb8c629d4eacdf24988cd6d33d4b4733bb90caac | 3,649,272 |
def is_requirement(line):
"""
Return True if the requirement line is a package requirement;
that is, it is not blank, a comment, or editable.
"""
# Remove whitespace at the start/end of the line
line = line.strip()
# Skip blank lines, comments, and editable installs
return not (
... | db30ff6bb2421d2b31939a20e708bf1c923a353e | 3,649,273 |
def read_pose_txt(pose_txt):
"""
Read the pose txt file and return a 4x4 rigid transformation.
"""
with open(pose_txt, "r") as f:
lines = f.readlines()
pose = np.zeros((4, 4))
for line_idx, line in enumerate(lines):
items = line.split(" ")
for i in range(4... | 250cc4c793a3bba948aeac2ca547c6680937a6e7 | 3,649,274 |
def get_futures(race_ids=list(range(1, 13000))):
"""Get Futures for all BikeReg race pages with given race_ids."""
session = FuturesSession(max_workers=8)
return [session.get(f'https://results.bikereg.com/race/{race_id}')
for race_id in race_ids if race_id not in BAD_IDS] | 1992c7b2fee93eecb75fd6e0c7a625181073609f | 3,649,275 |
def sum_of_proper_divisors(number: int):
"""
Let d(n) be defined as the sum of proper divisors of n
(numbers less than n which divide evenly into n).
:param number:
:return:
"""
divisors = []
for n in range(1, number):
if number % n == 0:
divisors.append(n)
retu... | 9015dd3809f90d328b0b4a6b51f6fcb145f0241d | 3,649,276 |
def coddington_meridional(p, q, theta):
""" return radius of curvature """
f = p * q / (p + q)
R = 2 * f / np.sin(theta)
return R | ef4964f08af065b2da6cbe5b156e4e976406a879 | 3,649,277 |
def read_analysis_file(timestamp=None, filepath=None, data_dict=None,
file_id=None, ana_file=None, close_file=True, mode='r'):
"""
Creates a data_dict from an AnalysisResults file as generated by analysis_v3
:param timestamp: str with a measurement timestamp
:param filepath: (str)... | 5e0d1797f45f18665f3ae5eaa6bac987fe94f926 | 3,649,278 |
def get_player_macro_econ_df(rpl: sc2reader.resources.Replay,
pid: int) -> pd.DataFrame:
"""This function organises the records of a player's major
macroeconomic performance indicators.
The function uses a player's PlayerStatsEvents contained in a Replay
object to compose a... | 4a0123ce4fe7f704f83c39a8c78e29c9347b1e1a | 3,649,279 |
import re
def get_seconds_from_duration(time_str: str) -> int:
"""
This function will convert the TM1 time to seconds
:param time_str: P0DT00H01M43S
:return: int
"""
pattern = re.compile('\w(\d+)\w\w(\d+)\w(\d+)\w(\d+)\w')
matches = pattern.search(time_str)
d, h, m, s = matches.groups(... | a8614c0ed6e41c7216ae461ef1fd57319a5995e1 | 3,649,280 |
def get_protecteds(object: Object) -> Dictionary:
"""Gets the protected namespaces of an object."""
return object.__protecteds__ | 479f6ee0a9334107f67517fd6bb2ad55a915d0ac | 3,649,281 |
def pah2area(_position, angle, height, shape):
"""Calculates area from position, angle, height depending on shape."""
if shape == "PseudoVoigt":
fwhm = np.tan(angle) * height
area = (height * (fwhm * np.sqrt(np.pi / ln2))
/ (1 + np.sqrt(1 / (np.pi * ln2))))
return area
... | 79e239de4ee8b356152717f7a9a301f062cc6c71 | 3,649,282 |
from typing import Callable
import os
import logging
def caching_query_s3(
s3_url: str,
query_fun: Callable,
force_query=False,
df_save_fun: Callable = lambda df, loc: df.to_pickle(loc, compression="gzip"),
df_load_fun: Callable = lambda loc: pd.read_pickle(loc, compression="gzip"),
):
"""
... | 6704a02265eb14fc45dd63be212090401a93e635 | 3,649,283 |
def config(key, values, axis=None):
"""Class decorator to parameterize the Chainer configuration.
This is a specialized form of `parameterize` decorator to parameterize
the Chainer configuration. For all `time_*` functions and `setup` function
in the class, this decorator wraps the function to be calle... | a2ab11ca245647c6a5267b2f1c62a55b9aa1b96b | 3,649,284 |
import sys
import logging
def handle_switches(args, sysroot):
"""Fetch the targeted binary and determine how to attach gdb.
Args:
args: Parsed arguments.
sysroot: Local sysroot path.
Returns:
(binary_file, attach_pid, run_cmd).
Precisely one of attach_pid or run_cmd will ... | 04bc894568da275516df94a4a49ef9ec58ef3cf3 | 3,649,285 |
def dot2states(dot):
"""Translate a dot-bracket string in a sequence of numerical states"""
dot = dot.replace(".", "0") # Unpaired
dot = dot.replace("(", "1") # Paired
dot = dot.replace(")", "1") # Paired
return np.array(list(dot), dtype=int) | 655b57749a39d04f62aae20ac16ffb1f31b0bc71 | 3,649,286 |
def mel_to_hz(mels, htk=False):
"""Convert mel bin numbers to frequencies
Examples
--------
>>> librosa.mel_to_hz(3)
200.
>>> librosa.mel_to_hz([1,2,3,4,5])
array([ 66.667, 133.333, 200. , 266.667, 333.333])
Parameters
----------
mels : np.ndarray [shape=(n,)],... | 93e9d115d9ef0a58420c796737b96f4460f44ceb | 3,649,287 |
import numpy as np
def load_images(images):
"""
Decodes batch of image bytes and returns a 4-D numpy array.
"""
batch = []
for image in images:
img_np = readImage(image)
batch.append(img_np)
batch_images = np.concatenate(batch)
logger.info('batch_images.shape:%s'%(str(bat... | ae4f18488cdfa4980f849f2f7110f9963381e6e7 | 3,649,288 |
from bob.db.base.utils import null
import sys
def dumplist(args):
"""Dumps lists of files based on your criteria"""
db = Database()
objects = db.objects(
protocol=args.protocol,
purposes=args.purposes,
groups=args.groups,
kinds=args.kinds
)
output = sys.stdout
... | cb57aa44ad89a023d33661421de4fc62a5b3c094 | 3,649,289 |
def stats_hook():
"""
decorator to register a stats hook.
:raises InvalidStatsHookTypeError: invalid stats hook type error.
:returns: stats hook class.
:rtype: type
"""
def decorator(cls):
"""
decorates the given class and registers an instance
of it into available... | de386a9bff39c4060833f11100ec538b6d2b8d68 | 3,649,290 |
def safe_infer(node, context=None):
"""Return the inferred value for the given node.
Return None if inference failed or if there is some ambiguity (more than
one node has been inferred).
"""
try:
inferit = node.infer(context=context)
value = next(inferit)
except exceptions.Infer... | 928c1d2e3c2813cc389085ea6bd3ccd50709effe | 3,649,291 |
import functools
def catch_exception(func):
"""
Returns:
object:
"""
@functools.wraps(func)
def wrapper(*args, **kwargs):
worker = kwargs['error_catcher']
try:
return func(*args, **kwargs)
except Exception as e:
print('stdout:', worker.stdou... | be579d9b6723e5025b7b70f38c83bcedc30196a5 | 3,649,292 |
def RandomCrop(parent, new_shape, name=""):
"""\
Crop an image layer at a random location with size ``[height, width]``.
:param parent: parent layer
:param new_shape: [height, width] size
:param name: name of the output layer
:return: CropRandom layer
"""
return _eddl.RandomCrop(parent,... | 6078cf9f6daf73876d3503a1e77523df079c41d1 | 3,649,293 |
import subprocess
def run_client(instance):
"""
Start a client process
"""
port = [1008, 8989, 9002][instance]
cpu = ['(3,4)', '(5,6)', '(7,8)'][instance]
# TODO: the following line is an example of code that is not suitable!
# should switch to run_udp_app instead of this function
... | 7f7b91a9c3a503df99736948ad3b37501e0609df | 3,649,294 |
import time
def get_linear_sys(eqns, params):
"""Gets the linear system corresponding to the symbolic equations
Note that this function only work for models where the left-hand side of
the equations all contain only linear terms with respect to the given model
parameters. For these linear cases, this... | e3ef88c695bcbcd6e7ab1dfbe8ee45ad552e3be7 | 3,649,295 |
def slightly(membership: npt.ArrayLike) -> npt.ArrayLike:
"""
Applies the element-wise function fn(u) = u^(1/2).
:param membership: Membership function to be modified.
>>> from fuzzy_expert.operators import slightly
>>> slightly([0, 0.25, 0.5, 0.75, 1])
array([0. , 0.16326531, 0.9969618... | eb0e71462c5e3959584970e9e9b84a3dff876d54 | 3,649,296 |
def int_max(int_a, int_b):
"""
max(a, b)
"""
if int_a > int_b:
return int_a
else:
return int_b | 5ae0df8ff7bdc5539d127fad4df03b6215d9380f | 3,649,297 |
def extract_depth_map(frame):
"""
Extract front-view lidar camera projection for ground-truth depth maps
"""
(range_images, camera_projections, range_image_top_pose) = frame_utils.parse_range_image_and_camera_projection(frame)
for c in frame.context.camera_calibrations:
if dataset_pb2.CameraName.Name.Nam... | 2568d8563e256bde6c5df5c3bb34038b57993a1b | 3,649,298 |
from .functions import express
def cross(vect1, vect2):
"""
Returns cross product of two vectors.
Examples
========
>>> from sympy.vector import CoordSys3D
>>> from sympy.vector.vector import cross
>>> R = CoordSys3D('R')
>>> v1 = R.i + R.j + R.k
>>> v2 = R.x * R.i + R.y * R.j + ... | 8857f53a3db4066b2be6cd0fc3443b89a9c97022 | 3,649,299 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.