content stringlengths 35 762k | sha1 stringlengths 40 40 | id int64 0 3.66M |
|---|---|---|
def _find_popular_codon(aa):
"""
This function returns popular codon from a 4+ fold degenerative codon.
:param aa: dictionary containing amino acid information.
:return:
"""
codons = [c[:2] for c in aa["codons"]]
counts = []
for i in range(len(codons)):
pc = codons[i]
cou... | a555a9d42ea4dfa0260d9d4d2040de3c6fca69a0 | 3,641,700 |
import pathlib
def initialize_cluster_details(scale_version, cluster_name, username,
password, scale_profile_path,
scale_replica_config):
""" Initialize cluster details.
:args: scale_version (string), cluster_name (string),
username (str... | 5508733e0bfbd20fb76ecaaf0df7f41675b0c5c8 | 3,641,701 |
def load(data_home=None):
"""Load RWC-Genre dataset
Args:
data_home (str): Local path where the dataset is stored.
If `None`, looks for the data in the default directory, `~/mir_datasets`
Returns:
(dict): {`track_id`: track data}
"""
if data_home is None:
data_... | 61d09f64ec7f36bc1dac6bfc6bea8e47fe82248b | 3,641,702 |
import copy
def collate_spectra_by_source(source_list, tolerance, unit=u.arcsec):
"""Given a list of spec1d files from PypeIt, group the spectra within the
files by their source object. The grouping is done by comparing the
position of each spectra (using either pixel or RA/DEC) using a given tolerance.
... | a82b470685ee53f3fe2de5e41a3f212e32a4d606 | 3,641,703 |
def tolist(obj):
"""
Convert given `obj` to list.
If `obj` is not a list, return `[obj]`, else return `obj` itself.
"""
if not isinstance(obj, list):
return [obj]
return obj | f511f4ebb86977b2db8646e692abc9840c2ae2d1 | 3,641,704 |
def bip44_tree(config: dict, cls=hierarchy.Node) -> hierarchy.Node:
"""
Return the root node of a BIP44-compatible partially ordered hierarchy.
https://github.com/bitcoin/bips/blob/master/bip-0044.mediawiki
The `config` parameter is a dictionary of the following form:
- the keys of the dictionary a... | bd88895932b66963aa7f63f30ad49ac009ea41f1 | 3,641,705 |
def delete_useless_vrrp_subnets(client, to_delete, project_id):
"""
:param 'Client' client
:param dict((prefix_length, type, master_region, slave_region),
(state:quantity)) to_delete
:rtype: list
"""
result = []
vrrp_subnets = client.vrrp.list(project_id=project_id)
for k... | b16019b026c32d310f9f938a7ca1fada31d02d84 | 3,641,706 |
import torch
import warnings
def barycenter_wbc(P, K, logweights, Kb=None, c=None, debiased=False,
maxiter=1000, tol=1e-4):
"""Compute the Wasserstein divergence barycenter between histograms.
"""
n_hists, width, _ = P.shape
if Kb is None:
b = torch.ones_like(P)[None, :]
... | 453c40ed988d4fe86dc202f816c5eb3bb6cbd452 | 3,641,707 |
import logging
def syllable_fingerprint(word):
"""
Use the pronuncation dict to map the potential syllable stress patterns
of a word to a ternary string "fingerprint"
0 is a syllable that must be unstressed
1 is a syllable that must be stressed
x is a syllable that may be stressed or unstress... | 7acce68ee686c5d5dbfc06eea00a95f7ae214ac9 | 3,641,708 |
def logistic_predict(weights, data):
"""
Compute the probabilities predicted by the logistic classifier.
Note: N is the number of examples and
M is the number of features per example.
Inputs:
weights: (M+1) x 1 vector of weights, where the last element
corresp... | 52c2ff3ed4b854de645b2252b4949b4a7a68bda1 | 3,641,709 |
def score_matrix(motifs, k):
"""returns matrix score formed from motifs"""
nucleotides = {'A': [0]*k, 'T': [0]*k, 'C': [0]*k, 'G': [0]*k}
for motif in motifs:
for index, nucleotide in enumerate(motif):
nucleotides[nucleotide][index] = nucleotides[nucleotide][index] + 1
i = 0
matr... | ce9f7b770ce75d4e872da7b3c9b4fa3fbcd1e900 | 3,641,710 |
def log_loss(y_true, dist_pred, sample=True, return_std=False):
""" Log loss
Parameters
----------
y_true: np.array
The true labels
dist_pred: ProbabilisticEstimator.Distribution
The predicted distribution
sample: boolean, default=True
If true, loss will be averaged acro... | 0f3d19111593441011cfb1e532be50a19d423390 | 3,641,711 |
import scipy
def matrix_pencil_method_old(data, p, noise_level=None, verbose=1, **kwargs):
""" Older impleentation of the matrix pencil method with pencil p on given data to
extract energy levels.
Parameters
----------
data -- lists of Obs, where the nth entry is considered to be the correlat... | 4bcb435b3b16b153d0d1f1689f542df1fdc74ca8 | 3,641,712 |
def ext_sum(text, ratio=0.8):
"""
Generate extractive summary using BERT model
INPUT:
text - str. Input text
ratio - float. Enter a ratio between 0.1 - 1.0 [default = 0.8]
(ratio = summary length / original text length)
OUTPUT:
summary - str. Generated summary
"""
bert_... | 99285d08425340f70984ce0645efdbaaa3e9072a | 3,641,713 |
def khinalug_input_normal(field, text):
"""
Prepare a string from one of the query fields for subsequent
processing: replace common shortcuts with valid Khinalug characters.
"""
if field not in ('wf', 'lex', 'lex2', 'trans_ru', 'trans_ru2'):
return text
text = text.replace('c1_', 'č̄')
... | b9b9413ae461b6a03aa8c0db4396658dbe242c91 | 3,641,714 |
from typing import List
from typing import Dict
from typing import Any
def _shift_all_classes(classes_list: List[ndarray], params_dict: Dict[str, Any]):
"""Shift the locale of all classes.
Args:
classes_list: List of classes as numpy arrays.
params_dict: Dict including the shift values for al... | 2176e5f4da6aecc25386e978182887fb8568faaa | 3,641,715 |
def fully_connected_layer(tensor,
size=None,
weight_init=None,
bias_init=None,
name=None):
"""Fully connected layer.
Parameters
----------
tensor: tf.Tensor
Input tensor.
size: int
Number of output... | 605cc52e8c5262aead6cb758488940e7661286b1 | 3,641,716 |
from pathlib import Path
def fetch_osborne_magnetic(version):
"""
Magnetic airborne survey of the Osborne Mine and surroundings, Australia
This is a section of a survey acquired in 1990 by the Queensland
Government, Australia. The line data have approximately 80 m terrain
clearance and 200 m line... | 2a0575557a18ca4442f0cf21ee51ccd94d316ffa | 3,641,717 |
from sympy.core.symbol import Symbol
from sympy.printing.pycode import MpmathPrinter as Printer
from sympy.printing.pycode import SciPyPrinter as Printer
from sympy.printing.pycode import NumPyPrinter as Printer
from sympy.printing.lambdarepr import NumExprPrinter as Printer
from sympy.printing.tensorflow import Tensor... | cf7b65c503d1a7873f0ddacfb3f6aa841340ee0e | 3,641,718 |
def _matches(o, pattern):
"""Match a pattern of types in a sequence."""
if not len(o) == len(pattern):
return False
comps = zip(o,pattern)
return all(isinstance(obj,kind) for obj,kind in comps) | e494016affa28e9018f337cb7184e96858701208 | 3,641,719 |
import csv
from io import StringIO
def excl_import_route():
"""import exclustions from csv"""
form = ExclImportForm()
if form.validate_on_submit():
imported = []
try:
for row in csv.DictReader(StringIO(form.data.data), EXPORT_FIELDNAMES, quoting=csv.QUOTE_MINIMAL):
... | 780c5646b2a5771691c538cb71bfde390cd9b847 | 3,641,720 |
def receiver(signal, **kwargs):
"""
A decorator for connecting receivers to signals. Used by passing in the
signal and keyword arguments to connect::
@receiver(signal_object, sender=sender)
def signal_receiver(sender, **kwargs):
...
"""
def _decorator(func):
sig... | dbbde0855b2a657adaff9fa688aa158053e46579 | 3,641,721 |
from typing import final
def create_new_connected_component(dict_projections, dict_cc, dict_nodes_cc, g_list_, set_no_proj, initial_method,
params, i, file_tags=None):
"""
If needed, create new connect component and update wanted dicts.
:param dict_projections: Embedding... | 18b8c046e78f17b125bf85250953c9d7a656892a | 3,641,722 |
def laguerre(x, k, c):
"""Generalized Laguerre polynomials. See `help(_gmw.morsewave)`.
LAGUERRE is used in the computation of the generalized Morse
wavelets and uses the expression given by Olhede and Walden (2002),
"Generalized Morse Wavelets", Section III D.
"""
x = np.atleast_1d(np.asarray(... | 4eac2e1cbd9fd2097763b56129873aa6af4e8419 | 3,641,723 |
def EGshelfIIseas2km_ERAI(daily = False,
gridpath = '/home/idies/workspace/OceanCirculation/exp_ERAI/grid_glued.nc',
kppspath = '/home/idies/workspace/OceanCirculation/exp_ERAI/kpp_state_glued.nc',
fldspath = '/home/idies/workspace/Oc... | 89b70cebbdecdde6d38310b1d0aa6cfec495ae9b | 3,641,724 |
from typing import Optional
from typing import Dict
import os
import time
import logging
import pickle
import json
def generate_pkl_features_from_fasta(
fasta_path: str,
name: str,
output_dir: str,
data_pipeline: DataPipeline,
timings: Optional[Dict[str, float]] = None):
""... | dfd166f8af954e4bac22cb893c102c0773ece27b | 3,641,725 |
import math
def find_all_combinations(participants, team_sizes):
""" Finds all possible experience level combinations for specific team
sizes with duplicated experience levels (e.g. (1, 1, 2))
Returns a list of tuples representing all the possible combinations """
num_teams = len(team_sizes)
part... | d3f4de9911a1fc427fc2e01433634ccf815f9183 | 3,641,726 |
from typing import Callable
from typing import Any
def debug_callback(callback: Callable[..., Any], effect: DebugEffect, *args,
**kwargs):
"""Calls a stageable Python callback.
`debug_callback` enables you to pass in a Python function that can be called
inside of a staged JAX program. A `deb... | 8e95dc55fbf5fe26875e5905b565f6ee0d9b143b | 3,641,727 |
def normalized_copy(data):
"""
Normalize timeseries data, using the maximum across all regions and timesteps.
Parameters
----------
data : xarray Dataset
Dataset with all non-time dependent variables removed
Returns
-------
ds : xarray Dataset
Copy of `data`, with the a... | cfcb94458deb6caa1125cfcf2904652900babc87 | 3,641,728 |
def _get_exception(ex: Exception) -> Exception:
"""Get exception cause/context from chained exceptions
:param ex: chained exception
:return: cause of chained exception if any
"""
if ex.__cause__:
return ex.__cause__
elif ex.__context__:
return ex.__context__
else:
re... | 3f670dc237ebd865e31c7d0fd3719e2ea929de6d | 3,641,729 |
from typing import Any
from typing import Dict
def recursive_normalizer(value: Any, **kwargs: Dict[str, Any]) -> Any:
"""
Prepare a structure for hashing by lowercasing all values and round all floats
"""
digits = kwargs.get("digits", 10)
lowercase = kwargs.get("lowercase", True)
if isinstanc... | e274c3976405838054d7251fdca8520dc75c48fd | 3,641,730 |
from typing import Set
def rip_and_tear(context) -> Set:
"""Edge split geometry using specified angle or unique mesh settings.
Also checks non-manifold geometry and hard edges.
Returns set of colors that are used to color meshes."""
processed = set()
angle_use_fixed = prefs.RenderFixedAngleUse
... | 6a67e9a90b4909c1aec8f7f784b2bc41750f5f79 | 3,641,731 |
def generate_primes(d):
"""Generate a set of all primes with d distinct digits."""
primes = set()
for i in range(10**(d-1)+1, 10**d, 2):
string = str(i)
unique_string = "".join(set(string))
if len(string) == len(unique_string): # Check that all digits are unique
if isprim... | 4edf615165144f2ab6e5d12533adc4357d904506 | 3,641,732 |
def poinv(A, UPLO='L', workers=1, **kwargs):
"""
Compute the (multiplicative) inverse of symmetric/hermitian positive
definite matrices, with broadcasting.
Given a square symmetic/hermitian positive-definite matrix `a`, return
the matrix `ainv` satisfying ``matrix_multiply(a, ainv) =
matrix_mul... | ccba9b0fc518e0482c6ac647d56abe0e86d3409c | 3,641,733 |
def gen_task3() -> np.ndarray:
"""Task 3: centre of cross or a plus sign."""
canv = blank_canvas()
r, c = np.random.randint(GRID-2, size=2, dtype=np.int8)
# Do we create a cross or a plus sign?
syms = rand_syms(5) # a 3x3 sign has 2 symbols, outer and centre
# syms = np.array([syms[0], syms[0], syms[1], sym... | aba9e78cf4d042cacd8787a90275947ba603b37c | 3,641,734 |
def init_susceptible_00():
"""
Real Name: b'init Susceptible 00'
Original Eqn: b'8e+06'
Units: b'person'
Limits: (None, None)
Type: constant
b''
"""
return 8e+06 | acc506bdea96b224f3627084bbee9e1a025bcff9 | 3,641,735 |
def spectrum_1D_scalar(data, dx, k_bin_num=100):
"""Calculates and returns the 2D spectrum for a 2D gaussian field of scalars, assuming isotropy of the turbulence
Example:
d=np.random.randn(101,101)
dx=1
k_bins_weighted,spect3D=spectrum_2D_scalar(d, dx, k_bin_num=100)
... | 88cdb3917d995fdf5d870ebfef3da90f8a4526fb | 3,641,736 |
from operator import and_
def get_previous_cat(last_index: int) -> models.Cat:
"""Get previous cat.
Args:
last_index (int): View index of last seen cat.
"""
cat = models.Cat.query.filter(and_(models.Cat.disabled == False, models.Cat.index < last_index)).order_by(
desc(models.Cat.index)... | bd4b6511ab7b2f004b8539e46109ce128d7af4dd | 3,641,737 |
def encode(file, res):
"""Encode an image. file is the path to the image, res is the resolution to use. Smaller res means smaller but lower quality output."""
out = buildHeader(res)
pixels = getPixels(file, res)
for i in range(0, len(pixels)):
px = encodePixel(pixels[i])
out += px
return out | 07f9622bc222f91cb614165e432b4584374030a3 | 3,641,738 |
def process_image(img):
"""Resize, reduce and expand image.
# Argument:
img: original image.
# Returns
image: ndarray(64, 64, 3), processed image.
"""
image = cv2.resize(img, (416, 416), interpolation=cv2.INTER_CUBIC)
image = np.array(image, dtype='float32')
image /= 255.
... | a139d0b82c82273de35d5e95b75cfd5f0e7635e3 | 3,641,739 |
def unnormalise_x_given_lims(x_in, lims):
"""
Scales the input x (assumed to be between [-1, 1] for each dim)
to the lims of the problem
"""
# assert len(x_in) == len(lims)
r = lims[:, 1] - lims[:, 0]
x_orig = r * (x_in + 1) / 2 + lims[:, 0]
return x_orig | 1d4cd35f45ab8594e297eb64e152a481c01905cd | 3,641,740 |
def scalar_projection(vector, onto):
"""
Compute the scalar projection of `vector` onto the vector `onto`.
`onto` need not be normalized.
"""
if vector.ndim == 1:
check(locals(), "vector", (3,))
check(locals(), "onto", (3,))
else:
k = check(locals(), "vector", (-1, 3))
... | d5b27d46e6d498b22adb1b081b9c7143c636307b | 3,641,741 |
def update_table(page_current, page_size, sort_by, filter, row_count_value):
"""
This is the collback function to update the datatable
with the required filtered, sorted, extended values
:param page_current: Current page number
:param page_size: Page size
:param sort_by: Column selected for sort... | e2669f3b98546731974e5706b8af9f6d82b47550 | 3,641,742 |
import os
def get_value(environment_variable, default_value=None):
"""Return an environment variable value."""
value_string = os.getenv(environment_variable)
# value_string will be None if the variable is not defined.
if value_string is None:
return default_value
# Exception for ANDROID_SERIAL. Someti... | db3bba6567b53cb103a38b56055cdbf554a59db3 | 3,641,743 |
def load_mooring_csv(csvfilename):
"""Loads data contained in an ONC mooring csv file
:arg csvfilename: path to the csv file
:type csvfilename: string
:returns: data, lat, lon, depth - a pandas data frame object and the
latitude, longitude and depth of the morning
"""
data_line, lat, lon,... | a974e8607916e8fbc1b2beb7af8768d048aca8f0 | 3,641,744 |
def ez_execute(query, engine):
"""
Function takes a query string and an engine object
and returns a dataframe on the condition that the
sql query returned any rows.
Arguments:
query {str} -- a Sql query string
engine {sqlalchemy.engine.base.Engine} -- a database engine object
... | c350d552f89dca550e766337fd7c071e138c43e6 | 3,641,745 |
def compute_lima_image(counts, background, kernel):
"""Compute Li & Ma significance and flux images for known background.
Parameters
----------
counts : `~gammapy.maps.WcsNDMap`
Counts image
background : `~gammapy.maps.WcsNDMap`
Background image
kernel : `astropy.convolution.Ker... | 8049f5a46ecf81459a64811aec917e72ec78a208 | 3,641,746 |
def get_list_from(matrix):
"""
Transforms capability matrix into list.
"""
only_valuable = []
counter = 1
for row_number in range(matrix.shape[0]):
only_valuable += matrix[row_number, counter::].tolist()
counter += 1
return only_valuable | bbfa52ff6a960d91d5aece948e9d416c3dcf0667 | 3,641,747 |
from typing import Tuple
def get_user_bubble_text_for_justify_statement(statement: Statement, user: User, is_supportive: bool,
_tn: Translator) -> Tuple[str, str]:
"""
Returns user text for a bubble when the user has to justify a statement and text for the add-po... | b303939794daada5b29d737270f474b380b5a192 | 3,641,748 |
def g1_constraint(x, constants, variables):
""" Constraint that the initial value of tangent modulus > 0 at ep=0.
:param np.ndarray x: Parameters of updated Voce-Chaboche model.
:param dict constants: Defines the constants for the constraint.
:param dict variables: Defines constraint values that depend... | 51d55a03b608cef2c3b5d87fe5cb56bf73326ae3 | 3,641,749 |
import sqlite3
def disconnect(connection_handler):
""" Closes a current database connection
:param connection_handler: the Connection object
:return: 0 if success and -1 if an exception arises
"""
try:
if connection_handler is not None:
connection_handler.close()
... | aaba17e38ef48fe7e0be5ba825e114b6f5148433 | 3,641,750 |
def throw_out_nn_indices(ind, dist, Xind):
"""Throw out near neighbor indices that are used to embed the time series.
This is an attempt to get around the problem of autocorrelation.
Parameters
----------
ind : 2d array
Indices to be filtered.
dist : 2d array
Distances to be fi... | 638fb43ac484ffa0e15e3c19a5b643aae5a749d9 | 3,641,751 |
import math
def lead_angle(target_disp,target_speed,target_angle,bullet_speed):
"""
Given the displacement, speed and direction of a moving target, and the speed
of a projectile, returns the angle at which to fire in order to intercept the
target. If no such angle exists (for example if the projectile is slower t... | fb5dfddf8b36d4e49df2d740b18f9aa97381d08f | 3,641,752 |
def fix_attr_encoding(ds):
""" This is a temporary hot-fix to handle the way metadata is encoded
when we read data directly from bpch files. It removes the 'scale_factor'
and 'units' attributes we encode with the data we ingest, converts the
'hydrocarbon' and 'chemical' attribute to a binary integer ins... | a0d0c8bd8fcf8dfa999bec9a2022d29a1af22514 | 3,641,753 |
import time
def acme_parser(characters):
"""Parse records from acme global
Args:
characters: characters to loop through the url
Returns:
2 item tuple containing all the meds as a list and a count of all meds
"""
link = (
'http://acmeglobal.com/acme/'
'wp-content/t... | 8e9fe3b020e05243075351d7eedbdba7a54d5d81 | 3,641,754 |
from typing import Any
import sys
def toStr(s: Any) -> str:
"""
Convert a given type to a default string
:param s: item to convert to a string
:return: converted string
"""
return s.decode(sys.getdefaultencoding(), 'backslashreplace') if hasattr(s, 'decode') else str(s) | 10adab737ab909760215810b94743a15e39b9035 | 3,641,755 |
def standard_atari_env_spec(env):
"""Parameters of environment specification."""
standard_wrappers = [[tf_atari_wrappers.RewardClippingWrapper, {}],
[tf_atari_wrappers.StackWrapper, {"history": 4}]]
env_lambda = None
if isinstance(env, str):
env_lambda = lambda: gym.make(env)
if cal... | e9751e1b376cdee5ec0f9c27d8ab4bf2e303f35b | 3,641,756 |
def load_bikeshare(path='data', extract=True):
"""
Downloads the 'bikeshare' dataset, saving it to the output
path specified and returns the data.
"""
# name of the dataset
name = 'bikeshare'
data = _load_file_data(name, path, extract)
return data | 7cce01f22c37460800a44a85b18e6574d9d7f6fb | 3,641,757 |
def file2bytes(filename: str) -> bytes:
"""
Takes a filename and returns a byte string with the content of the file.
"""
with open(filename, 'rb') as f:
data = f.read()
return data | f917a265c17895c917c3c340041586bef0c34dac | 3,641,758 |
import json
def load_session() -> dict:
"""
Returns available session dict
"""
try:
return json.load(SESSION_PATH.open())
except FileNotFoundError:
return {} | 342c8e143c878cfc4821454cebfcc3ba47a2cd2a | 3,641,759 |
def _preprocess_zero_mean_unit_range(inputs, dtype=tf.float32):
"""Map image values from [0, 255] to [-1, 1]."""
preprocessed_inputs = (2.0 / 255.0) * tf.cast(inputs, tf.float32) - 1.0
return tf.cast(preprocessed_inputs, dtype=dtype) | 08238566a04ed35346b8f4ff0874fff7be48bded | 3,641,760 |
from typing import cast
def fill_like(input, value, shape=None, dtype=None, name=None):
"""Create a uniformly filled tensor / array."""
input = as_tensor(input)
dtype = dtype or input.dtype
if has_tensor([input, value, shape], 'tf'):
value = cast(value, dtype)
return tf.fill(value, inp... | 1879ac8669396dfe3fe351dae97a96cd8d6a8e5e | 3,641,761 |
from typing import Callable
import operator
def transform_item(key, f: Callable) -> Callable[[dict], dict]:
"""transform a value of `key` in a dict. i.e given a dict `d`, return a new dictionary `e` s.t e[key] = f(d[key]).
>>> my_dict = {"name": "Danny", "age": 20}
>>> transform_item("name", str.upper)(m... | a202fe59b29b0a1b432df759b4600388e2d9f72e | 3,641,762 |
def mock_dataset(mocker, mock_mart, mart_datasets_response):
"""Returns an example dataset, built using a cached response."""
mocker.patch.object(mock_mart, 'get', return_value=mart_datasets_response)
return mock_mart.datasets['mmusculus_gene_ensembl'] | bb9a8b828f0ac5bfa59b3faee0f9bcc22c7d954e | 3,641,763 |
import torch
def loss_function(recon_x, x, mu, logvar):
"""Loss function for varational autoencoder VAE"""
BCE = F.binary_cross_entropy(recon_x, x, size_average=False)
# 0.5 * sum(1 + log(sigma^2) - mu^2 - sigma^2)
KLD = -0.5 * torch.sum(1 + logvar - mu.pow(2) - logvar.exp())
return BCE + KLD | 38c0d6ab7a8388e007324bdcfb8611f0a3072c35 | 3,641,764 |
import scipy
def resize_img(img, size):
"""
Given a list of images in ndarray, resize them into target size.
Args:
img: Input image in ndarray
size: Target image size
Returns: Resized images in ndarray
"""
img = scipy.misc.imresize(img, (size, size))
if len(img.shape) ==... | 8a3ff8bfab0c864a6c0e4701be07b9296ad23f28 | 3,641,765 |
def cloudtopheight_IR(bt, cloudmask, latitude, month, method="modis"):
"""Cloud Top Height (CTH) from 11 micron channel.
Brightness temperatures (bt) are converted to CTHs using the IR window approach:
(bt_clear - bt_cloudy) / lapse_rate.
See also:
:func:`skimage.measure.block_reduce`
... | b68dfb37b27d3067c2956fc3653640393491e014 | 3,641,766 |
def info2lists(info, in_place=False):
"""
Return info with:
1) `packages` dict replaced by a 'packages' list with indexes removed
2) `releases` dict replaced by a 'releases' list with indexes removed
info2list(info2dicts(info)) == info
"""
if 'packages' not in info and 'releases' not in i... | 313fda757d386332e16a0a91bb4408fe3cb8c070 | 3,641,767 |
def calc_wave_number(g, h, omega, relax=0.5, eps=1e-15):
"""
Relaxed Picard iterations to find k when omega is known
"""
k0 = omega ** 2 / g
for _ in range(100):
k1 = omega ** 2 / g / tanh(k0 * h)
if abs(k1 - k0) < eps:
break
k0 = k1 * relax + k0 * (1 - relax)
... | 7173fc9f38547864943046fed1e74d9b5cc832b5 | 3,641,768 |
def emit_live_notification_for_model(obj, user, history, *, type:str="change", channel:str="events",
sessionid:str="not-existing"):
"""
Sends a model live notification to users.
"""
if obj._importing:
return None
content_type = get_typename_for_model_in... | 94e7e91ec73537aad71ab3839fbd203552d4fec2 | 3,641,769 |
def is_chitoi(tiles):
"""
Returns True if the hand satisfies chitoitsu.
"""
unique_tiles = set(tiles)
return (len(unique_tiles) == 7 and
all([tiles.count(tile) == 2 for tile in unique_tiles])) | c04149174bb779cd07616d4f419fc86531ab95dd | 3,641,770 |
import itertools
def get_hpo_ancestors(hpo_db, hpo_id):
"""
Get HPO terms higher up in the hierarchy.
"""
h=hpo_db.hpo.find_one({'id':hpo_id})
#print(hpo_id,h)
if 'replaced_by' in h:
# not primary id, replace with primary id and try again
h = hpo_db.hpo.find_one({'id':h['replac... | 2ef2c968bc3001b97529ccd269884cefad7a899f | 3,641,771 |
def mcBufAir(params: dict, states: dict) -> float:
"""
Growth respiration
Parameters
----------
params : dict
Parameters saved as model constants
states : dict
State variables of the model
Returns
-------
float
Growth respiration of the plant [mg m-2 s-1]
... | d31f201384fdab6c03856def1eed7d96fe28482a | 3,641,772 |
import os
import re
def gene_calling (workflow, assembly_dir, assembly_extentsion, input_dir, extension, extension_paired,
gene_call_type, prokka_dir, prodigal_dir,
threads,
gene_file, gene_PC_file, protein_file, protein_sort,
gene_info, complete_gen... | 5bd17208605c8ad99cf7b72db28506e26fc170c4 | 3,641,773 |
def space_boundaries_re(regex):
"""Wrap regex with space or end of string."""
return rf"(?:^|\s)({regex})(?:\s|$)" | 68861da6218165318b6a446c173b4906a93ef850 | 3,641,774 |
import requests
import json
import dateutil
def get_jobs():
"""
this function will query USAJOBS api and return all open FEC jobs.
if api call failed, a status error message will be displayed in the
jobs.html session in the career page.
it also query code list to update hirepath info. a hard-coded... | 46c69348b3f964fc1c4f35391aa5c7a8d049b47e | 3,641,775 |
def artanh(x) -> ProcessBuilder:
"""
Inverse hyperbolic tangent
:param x: A number.
:return: The computed angle in radians.
"""
return _process('artanh', x=x) | d93ec8e7059df02ebf7a60506d2e9896bc146b32 | 3,641,776 |
from thunder.readers import normalize_scheme, get_parallel_reader
import array
def fromtext(path, ext='txt', dtype='float64', skip=0, shape=None, index=None, labels=None, npartitions=None, engine=None, credentials=None):
"""
Loads series data from text files.
Assumes data are formatted as rows, where eac... | 9ab049954b23888c2d2a17786edde57dd90507c0 | 3,641,777 |
def flop_gemm(n, k):
"""# of + and * for matmat of nxn matrix with nxk matrix, with accumulation
into the output."""
return 2*n**2*k | b217b725e2ac27a47bc717789458fd20b4aa56c1 | 3,641,778 |
def index() -> str:
"""Rest endpoint to test whether the server is correctly working
Returns:
str: The default message string
"""
return 'DeChainy server greets you :D' | ce0caeb9994924f8d6ea10462db2be48bbc126d0 | 3,641,779 |
import os
def get_git_hash() -> str:
"""Get the PyKEEN git hash.
:return:
The git hash, equals 'UNHASHED' if encountered CalledProcessError, signifying that the
code is not installed in development mode.
"""
with open(os.devnull, 'w') as devnull:
try:
ret = check_o... | dc00c46c07e2b819718a04fde878ec3669a81e4f | 3,641,780 |
from typing import AnyStr
from typing import List
import json
def load_json_samples(path: AnyStr) -> List[str]:
"""
Loads samples from a json file
:param path: Path to the target file
:return: List of samples
"""
with open(path, "r", encoding="utf-8") as file:
samples = json.load(file... | b735e7265a31f6bc6d19381bfe9d0cbe26dcf170 | 3,641,781 |
import sys
def openPort(path = SERIALPATH):
"""open the serial port for the given path"""
try:
port = Serial(path, baudrate = 115200)
except :
print("No serial device on the given path :" + path)
sys.exit()
return(port) | 67f6044a7cc1c726f7226dce8768e8f6cdca6cdb | 3,641,782 |
import struct
import lzma
def decompress_lzma(data: bytes) -> bytes:
"""decompresses lzma-compressed data
:param data: compressed data
:type data: bytes
:raises _lzma.LZMAError: Compressed data ended before the end-of-stream marker was reached
:return: uncompressed data
:rtype: bytes
"""
... | 247c3d59d45f3f140d4f2c36a7500ff8a51e45b0 | 3,641,783 |
def validate(request):
"""
Validate actor name exists in database before searching.
If more than one name fits the criteria, selects the first one
and returns the id.
Won't render.
"""
search_for = request.GET.get('search-for', default='')
start_from = request.GET.get('start-from', def... | 39b9183cd570cce0ddfd81febde0ec125f11c578 | 3,641,784 |
def merge(left, right, on=None, left_on=None, right_on=None):
"""Merge two DataFrames using explicit-comms.
This is an explicit-comms version of Dask's Dataframe.merge() that
only supports "inner" joins.
Requires an activate client.
Notice
------
As a side effect, this operation concatena... | 847070e27007c049d0c58059ec9f7c66681f21bc | 3,641,785 |
def estimate_fs(t):
"""Estimates data sampling rate"""
sampling_rates = [
2000,
1250,
1000,
600,
500,
300,
250,
240,
200,
120,
75,
60,
50,
30,
25,
]
fs_est = np.median(1 / np.diff(t))... | 82dbd115e3c7b656302d10339cdfe77b60ab0620 | 3,641,786 |
def get_case_number(caselist):
"""Get line number from file caselist."""
num = 0
with open(caselist, 'r') as casefile:
for line in casefile:
if line.strip().startswith('#') is False:
num = num + 1
return num | b1366d8e4a0e2c08da5265502d2dd2d72bf95c19 | 3,641,787 |
from typing import Any
def build_param_float_request(*, scenario: str, value: float, **kwargs: Any) -> HttpRequest:
"""Send a post request with header values "scenario": "positive", "value": 0.07 or "scenario":
"negative", "value": -3.0.
See https://aka.ms/azsdk/python/protocol/quickstart for how to inco... | 3e310a92ebe5760a00abc82c5c6465e160a5881d | 3,641,788 |
from typing import List
def async_entries_for_config_entry(
registry: DeviceRegistry, config_entry_id: str
) -> List[DeviceEntry]:
"""Return entries that match a config entry."""
return [
device
for device in registry.devices.values()
if config_entry_id in device.config_entries
... | 17af1610631e6b0f407883fa8386082a694f9cd2 | 3,641,789 |
from pathlib import Path
import yaml
def load_material(name: str) -> Material:
"""Load a material from the materials library
Args:
name (str): Name of material
Raises:
FileNotFoundError: If material is not found, raises an error
Returns:
Material: Loaded material
"""
... | aa53eac4889d6c44e78d8f3f6e3b5c2099a7bb53 | 3,641,790 |
def reportBusniessModelSummaryView(request):
""" รายงาน สรุปจำนวนผู้สมัครตามสถานะธุรกิจ ทุกขั้นตอน"""
queryset = SmeCompetition.objects \
.values('enterpise__business_model', 'enterpise__business_model__name') \
.annotate(step_register=Count('enterpise__business_model')) \
.annotate(step... | a0bcb8e0b9d51fc1ed9070857ef9db2c4641ddd6 | 3,641,791 |
def _get_announce_url(rjcode: str) -> str:
"""Get DLsite announce URL corresponding to an RJ code."""
return _ANNOUNCE_URL.format(rjcode) | 997b82270fcb115f8510d0ded1e1b6204e835e92 | 3,641,792 |
import torch
def get_r_adv(x, decoder, it=1, xi=1e-1, eps=10.0):
"""
Virtual Adversarial Training
https://arxiv.org/abs/1704.03976
"""
x_detached = x.detach()
with torch.no_grad():
pred = F.softmax(decoder(x_detached), dim=1)
d = torch.rand(x.shape).sub(0.5).to(x.device)
d = _... | 7613e59d88117a8ed263aad76139b1e4d808582c | 3,641,793 |
import os
def fetch_brats(datasetdir):
""" Fetch/prepare the Brats dataset for pynet.
Parameters
----------
datasetdir: str
the dataset destination folder.
Returns
-------
item: namedtuple
a named tuple containing 'input_path', 'output_path', and
'metadata_path'.
... | 0adac8fa6c6c83c90c9f2809b8ebda52559e9600 | 3,641,794 |
def get_factors(shoppers, n_components=4, random_state=903, **kwargs):
"""
Find Factors to represent the shopper-level features in compressed space.
These factors will be used to map simplified user input from application
to the full feature space used in modeling.
Args:
shoppers (pd.DataFr... | 966ca305b87b836d9caa5c857608bc6b16120e26 | 3,641,795 |
def cols_to_array(*cols, remove_na: bool = True) -> Column:
"""
Create a column of ArrayType() from user-supplied column list.
Args:
cols: columns to convert into array.
remove_na (optional): Remove nulls from array. Defaults to True.
Returns:
Column of ArrayType()
"""
... | a33e9b907d95fc767c2f247e12c22bdac9ad7585 | 3,641,796 |
def _git_repo_status(repo):
"""Get current git repo status.
:param repo: Path to directory containing a git repo
:type repo: :class:`pathlib.Path()`
:return: Repo status
:rtype: dict
"""
repo_status = {
'path': repo
}
options = ['git', '-C', str(repo), 'status', '-s']
... | c35a20b7350dcf20bedcd9b201fd04a46c83449b | 3,641,797 |
def _parseList(s):
"""Validation function. Parse a comma-separated list of strings."""
return [item.strip() for item in s.split(",")] | 5bf9ac50a44a18cc4798ed616532130890803bac | 3,641,798 |
def true_segments_1d(segments,
mode=SegmentsMode.CENTERS,
max_gap=0,
min_length=0,
name=None):
"""Labels contiguous True runs in segments.
Args:
segments: 1D boolean tensor.
mode: The SegmentsMode. Returns the start of each... | 801541b7c3343fd59f79a3f3696c3cb17ab41c31 | 3,641,799 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.