content stringlengths 35 762k | sha1 stringlengths 40 40 | id int64 0 3.66M |
|---|---|---|
def custom_leastsq(obj_fn, jac_fn, x0, f_norm2_tol=1e-6, jac_norm_tol=1e-6,
rel_ftol=1e-6, rel_xtol=1e-6, max_iter=100, num_fd_iters=0,
max_dx_scale=1.0, damping_mode="identity", damping_basis="diagonal_values",
damping_clip=None, use_acceleration=False, uphill_s... | 339c892524442a69b7f84f0b05a1931f5ebddf8a | 3,657,300 |
def degrees(x):
"""Converts angle x from radians to degrees.
:type x: numbers.Real
:rtype: float
"""
return 0.0 | 87fe22113f8286db6c516e711b9cf0d4efe7e11d | 3,657,301 |
def account_credit(account=None,
asset=None,
date=None,
tp=None,
order_by=['tp', 'account', 'asset'],
hide_empty=False):
"""
Get credit operations for the account
Args:
account: filter by account code
... | a690d1352344c6f8e3d8172848255adc1fa9e331 | 3,657,302 |
import logging
def get_logger(log_file=None):
"""
Initialize logger configuration.
Returns:
logger.
"""
formatter = logging.Formatter(
'%(asctime)s %(name)s.%(funcName)s +%(lineno)s: '
'%(levelname)-8s [%(process)d] %(message)s'
)
logger = logging.getLogger(__name_... | 3dad72ee83c25d2c49d6cc357bf89048f7018cb5 | 3,657,303 |
import torch
def verify(model):
"""
测试数据模型检验
:param model: 网络模型以及其参数
:return res: 返回对应的列表
"""
device = 'cuda' if torch.cuda.is_available() else 'cpu'
model = model.to(device)
if device == 'cuda':
model = torch.nn.DataParallel(model)
cudnn.benchmark = True
res = []
... | 9ad2fd6280018aacbb2501f6b5eb862924b361a1 | 3,657,304 |
import csv
def parse_solution_file(solution_file):
"""Parse a solution file."""
ids = []
classes = []
with open(solution_file) as file_handle:
solution_reader = csv.reader(file_handle)
header = next(solution_reader, None)
if header != HEADER:
raise ValueError(
... | 19a553bd9979ca1d85d223b3109f3567a3a84100 | 3,657,305 |
def fibonacci_modulo(number, modulo):
"""
Calculating (n-th Fibonacci number) mod m
Args:
number: fibonacci number
modulo: modulo
Returns:
(n-th Fibonacci number) mod m
Examples:
>>> fibonacci_modulo(11527523930876953, 26673)
10552
"""
period = _pi... | 5a7692597c17263ba86e81104762e4c7c8c95083 | 3,657,306 |
from typing import Union
def _str_unusual_grades(df: pd.DataFrame) -> Union[str, None]:
"""Print the number of unusual grades."""
grades = np.arange(0, 10.5, 0.5).astype(float)
catch_grades = []
for item in df["grade"]:
try:
if float(item) not in grades:
catch_grade... | 0998b112438685523cadc60eb438bee94f3ad8fd | 3,657,307 |
from typing import Any
from typing import Dict
def _adjust_estimator_options(estimator: Any, est_options: Dict[str, Any], **kwargs) -> Dict[str, Any]:
"""
Adds specific required classifier options to the `clf_options` dictionary.
Parameters
----------
classifier : Any
The classifier objec... | 4ff98d8a3b3e647e129fb0ffbc9bc549caa60440 | 3,657,308 |
def _prettify(elem,indent_level=0):
"""Return a pretty-printed XML string for the Element.
"""
indent = " "
res = indent_level*indent + '<'+elem.tag.encode('utf-8')
for k in elem.keys():
res += " "+k.encode('utf-8')+'="'+_escape_nl(elem.get(k)).encode('utf-8')+'"'
children = elem.getch... | 8f46637cdbb8daf488fd668a197aee5495b8128a | 3,657,309 |
def predict(text):
"""
Predict the language of a text.
Parameters
----------
text : str
Returns
-------
language_code : str
"""
if language_models is None:
init_language_models(comp_metric, unicode_cutoff=10**6)
x_distribution = get_distribution(text, language_model... | 713d8cd8df040703ee7f138314f5c14f5a89ef26 | 3,657,310 |
def kgup(baslangic_tarihi=__dt.datetime.today().strftime("%Y-%m-%d"),
bitis_tarihi=__dt.datetime.today().strftime("%Y-%m-%d"), organizasyon_eic="", uevcb_eic=""):
"""
İlgili tarih aralığı için kaynak bazlı kesinleşmiş günlük üretim planı (KGÜP) bilgisini vermektedir.
Not: "organizasyon_eic" değeri ... | a1b19ea295bf58db114391e11333e37a9fd6d47d | 3,657,311 |
def distance_loop(x1, x2):
""" Returns the Euclidean distance between the 1-d numpy arrays x1 and x2"""
return -1 | abd35a27cbeb5f5c9fe49a2a076d18f16e2849d9 | 3,657,312 |
def get_ps_calls_and_summary(filtered_guide_counts_matrix, f_map):
"""Calculates protospacer calls per cell and summarizes them
Args:
filtered_guide_counts_matrix: CountMatrix - obtained by selecting features by CRISPR library type on the feature counts matrix
f_map: dict - map of feature ID:fea... | 18aecb335655fb62459350761aeffd4ddbe231ae | 3,657,313 |
def symbol_by_name(name, aliases={}, imp=None, package=None,
sep='.', default=None, **kwargs):
"""Get symbol by qualified name.
The name should be the full dot-separated path to the class::
modulename.ClassName
Example::
celery.concurrency.processes.TaskPool
... | 10921d715abc9c83891b26b884f3c88e86c4a900 | 3,657,314 |
from typing import Tuple
def coefficients_of_line_from_points(
point_a: Tuple[float, float], point_b: Tuple[float, float]
) -> Tuple[float, float]:
"""Computes the m and c coefficients of the equation (y=mx+c) for
a straight line from two points.
Args:
point_a: point 1 coordinates
poi... | b4d89f2bb3db48723f321e01658e795f431427e1 | 3,657,315 |
import os
import subprocess
from datetime import datetime
def logDirManager():
""" Directory manager for TensorFlow logging """
print('Cleaning and initialising logging directory... \n')
# Ensure function is starting from project root..
if os.getcwd() != "/Users/Oliver/AnacondaProjects/SNSS_TF":
... | 664f5554c5c937ff3a95e68c59fbc41ff4276f85 | 3,657,316 |
import tifffile
def read_tiff(fname, slc=None):
"""
Read data from tiff file.
Parameters
----------
fname : str
String defining the path of file or file name.
slc : sequence of tuples, optional
Range of values for slicing data in each axis.
((start_1, end_1, step_1), .... | 39b48229719dd8210059a3a9ed7972e8398728ab | 3,657,317 |
def sorted_non_max_suppression_padded(scores,
boxes,
max_output_size,
iou_threshold):
"""A wrapper that handles non-maximum suppression.
Assumption:
* The boxes are sorted by scores unless the box ... | 5d882acb6b9559eb541d49f6784798e5d342c673 | 3,657,318 |
def create_session() -> Session:
"""
Creates a new session using the aforementioned engine
:return: session
"""
return Session(bind=engine) | 8b480ee216c30b2c6b8652a6b6239ab6b83df4d9 | 3,657,319 |
import torch
def fft_to_complex_matrix(x):
""" Create matrix with [a -b; b a] entries for complex numbers. """
x_stacked = torch.stack((x, torch.flip(x, (4,))), dim=5).permute(2, 3, 0, 4, 1, 5)
x_stacked[:, :, :, 0, :, 1] *= -1
return x_stacked.reshape(-1, 2 * x.shape[0], 2 * x.shape[1]) | 9fb38004041280da0d6d53830761501aebf7969a | 3,657,320 |
import copy
def mcais(A, X, verbose=False):
"""
Returns the maximal constraint-admissible (positive) invariant set O_inf for the system x(t+1) = A x(t) subject to the constraint x in X.
O_inf is also known as maximum output admissible set.
It holds that x(0) in O_inf <=> x(t) in X for all t >= 0.
... | e162a1aed724166f373f8afbd6541622254e8b42 | 3,657,321 |
def evaluation_seasonal_srmse(model_name, variable_name='mean', background='all'):
"""
Evaluate the model in different seasons using the standardized RMSE.
:type model_name: str
:param model_name: The name of the model.
:type variable_name: str
:param variable_name: The name of the variable wh... | 39fb7ae64ab32fc5092e46c77c8593f1aeaf4c92 | 3,657,322 |
def generate_accession_id() -> str:
"""Generate Stable ID."""
accessionID = uuid4()
urn = accessionID.urn
LOG.debug(f"generated accession id as: {urn}")
return urn | d55f63aa0b48a06aaa98f978b6f92a219c0b1457 | 3,657,323 |
def _async_device_ha_info(
hass: HomeAssistant, lg_device_id: str
) -> dict | None:
"""Gather information how this ThinQ device is represented in Home Assistant."""
device_registry = dr.async_get(hass)
entity_registry = er.async_get(hass)
hass_device = device_registry.async_get_device(
iden... | 47af173daba91aa70ea167baf58c05e9f6f595f6 | 3,657,324 |
from typing import Optional
def get_travis_pr_num() -> Optional[int]:
"""Return the PR number if the job is a pull request, None otherwise
Returns:
int
See also:
- <https://docs.travis-ci.com/user/environment-variables/#default-environment-variables>
""" # noqa E501
try:
... | 86ef6ce3f9bf3c3e056b11e575b1b13381e490fe | 3,657,325 |
from typing import List
import json
def get_updated_records(table_name: str, existing_items: List) -> List:
"""
Determine the list of record updates, to be sent to a DDB stream after a PartiQL update operation.
Note: This is currently a fairly expensive operation, as we need to retrieve the list of all i... | 631c21836614731e5b53ed752036f1216d555196 | 3,657,326 |
def normalize_record(input_object, parent_name="root_entity"):
"""
This function orchestrates the main normalization.
It will go through the json document and recursively work with the data to:
- unnest (flatten/normalize) keys in objects with the standard <parentkey>_<itemkey> convention
- identi... | 73647b04ba943e18a38ebf2f1d03cca46b533935 | 3,657,327 |
def rmse(f, p, xdata, ydata):
"""Root-mean-square error."""
results = np.asarray([f(p, x) for x in xdata])
sqerr = (results - ydata)**2
return np.sqrt(sqerr.mean()) | 2b8afdb1742aad5e5c48fbe4407ab0989dbaf762 | 3,657,328 |
import logging
def get_logger(name=None, propagate=True):
"""Get logger object"""
logger = logging.getLogger(name)
logger.propagate = propagate
loggers.append(logger)
return logger | 3ad4dbc39f9bf934b02e2dc6e713a4793a28298b | 3,657,329 |
import os
def load_movielens1m(infile=None, event_dtype=event_dtype_timestamp):
""" load the MovieLens 1m data set
Original file ``ml-1m.zip`` is distributed by the Grouplens Research
Project at the site:
`MovieLens Data Sets <http://www.grouplens.org/node/73>`_.
Parameters
----------
in... | 594e222f1b2fce4fcb97e5ffe7082ccc42172681 | 3,657,330 |
import os
def load_coco_data(split):
"""load the `split` data containing image and label
Args:
split (str): the split of the dataset (train, val, test)
Returns:
tf.data.Dataset: the dataset contains image and label
image (tf.tensor), shape (224, 224, 3)
label (tf.tensor),... | 56d42130dca83ab883a02a1dce48c3374dc7398f | 3,657,331 |
import argparse
import os
def get_args():
"""
Get User defined arguments, or assign defaults
:rtype: argparse.ArgumentParser()
:return: User defined or default arguments
"""
parser = argparse.ArgumentParser()
# Positional arguments
parser.add_argument("main_args", type=str, nargs="*"... | 2f31a2142034127d3de7f4212841c3432b451fc4 | 3,657,332 |
import requests
from typing import Match
def getMatches(tournamentName=None, matchDate=None, matchPatch=None, matchTeam=None):
"""
Params:
tournamentName: str/List[str]/Tuple(str) : filter by tournament names (e.g. LCK 2020 Spring)
matchDate: str/List[str]/Tuple(str) : date in the format of yy... | 89525caa9da0a3b546e0b8982e96469f32f8c5bc | 3,657,333 |
from typing import Optional
import os
def parse_e_elect(path: str,
zpe_scale_factor: float = 1.,
) -> Optional[float]:
"""
Parse the electronic energy from an sp job output file.
Args:
path (str): The ESS log file to parse from.
zpe_scale_factor (float)... | d76eae166309ebe765afcfdcf5fcf26bd19a9826 | 3,657,334 |
from my_app.admin import admin
from my_app.main import main
import os
def create_app():
"""Creates the instance of an app."""
configuration_file=os.getcwd()+'/./configuration.cfg'
app=Flask(__name__)
app.config.from_pyfile(configuration_file)
bootstrap.init_app(app)
mail.init_app(app)
app.... | 54cd56142dadc8c27fa385b3eb12a3b4726c291c | 3,657,335 |
def get_fields(fields):
"""
From the last column of a GTF, return a dictionary mapping each value.
Parameters:
fields (str): The last column of a GTF
Returns:
attributes (dict): Dictionary created from fields.
"""
attributes = {}
description = fields.strip()
description = [x.strip() for x in description... | 30777838934b18a0046017f3da6b3a111a911a9c | 3,657,336 |
def add_log_group_name_params(log_group_name, configs):
"""Add a "log_group_name": log_group_name to every config."""
for config in configs:
config.update({"log_group_name": log_group_name})
return configs | a5fce8143c3404257789c1720bbfefc49c8ea3f5 | 3,657,337 |
from typing import Union
def on_update_user_info(data: dict, activity: Activity) -> (int, Union[str, None]):
"""
broadcast a user info update to a room, or all rooms the user is in if no target.id specified
:param data: activity streams format, must include object.attachments (user info)
:param activ... | 735486cad96545885a76a5a18418db549869304d | 3,657,338 |
def discover(isamAppliance, check_mode=False, force=False):
"""
Discover available updates
"""
return isamAppliance.invoke_get("Discover available updates",
"/updates/available/discover") | 04c68b0ce57d27bc4032cf9b1607f2f1f371e384 | 3,657,339 |
from re import A
def ltistep(U, A=A, B=B, C=C):
""" LTI( A B C ): U -> y linear
straight up
"""
U, A, B, C = map(np.asarray, (U, A, B, C))
xk = np.zeros(A.shape[1])
x = [xk]
for u in U[:-1]:
xk = A.dot(xk) + B.dot(u)
x.append(xk.copy())
return np.dot(x, C) | 5d7c7550a9a6407a8f1a68ee32e158f25a7d50bf | 3,657,340 |
def _registry():
"""Registry to download images from."""
return _registry_config()["host"] | ee7c724f3b9381c4106a4e19d0434b9b4f0125fc | 3,657,341 |
def load_structure(query, reduce=True, strip='solvent&~@/pseudoBonds'):
"""
Load a structure in Chimera. It can be anything accepted by `open` command.
Parameters
==========
query : str
Path to molecular file, or special query for Chimera's open (e.g. pdb:3pk2).
reduce : bool
Ad... | d91ceeba36eb04e33c238ab2ecb88ba2cc1928c7 | 3,657,342 |
from re import T
def is_into_keyword(token):
"""
INTO判定
"""
return token.match(T.Keyword, "INTO") | 337fb0062dc4288aad8ac715efcca564ddfad113 | 3,657,343 |
from typing import Union
def exp(
value: Union[Tensor, MPCTensor, int, float], iterations: int = 8
) -> Union[MPCTensor, float, Tensor]:
"""Approximates the exponential function using a limit approximation.
exp(x) = lim_{n -> infty} (1 + x / n) ^ n
Here we compute exp by choosing n = 2 ** d for some ... | 9cfbb63d39d41e92b506366244ec6e77d52162b2 | 3,657,344 |
from typing import Any
def train(estimator: Estimator, data_root_dir: str, max_steps: int) -> Any:
"""Train a Tensorflow estimator"""
train_spec = tf.estimator.TrainSpec(
input_fn=_build_input_fn(data_root_dir, ModeKeys.TRAIN),
max_steps=max_steps,
)
if max_steps > Training.LONG_TRAI... | bcf81a0b46f3c0eea8f2c26929d3b6440df5e2cb | 3,657,345 |
def isDllInCorrectPath():
"""
Returns True if the BUFFY DLL is present and in the correct location (...\<BTS>\Mods\<BUFFY>\Assets\).
"""
return IS_DLL_IN_CORRECT_PATH | ea31391d41ba04b27df70124a65fdb48791cce57 | 3,657,346 |
import time
def time_remaining(event_time):
"""
Args:
event_time (time.struct_time): Time of the event.
Returns:
float: Time remaining between now and the event, in
seconds since epoch.
"""
now = time.localtime()
time_remaining = time.mktime(event_time) - time.mkti... | cb3dfcf916cffc3b45f215f7642aeac8a1d6fef7 | 3,657,347 |
def _repeat(values, count):
"""Produces a list of lists suitable for testing interleave.
Args:
values: for each element `x` the result contains `[x] * x`
count: determines how many times to repeat `[x] * x` in the result
Returns:
A list of lists of values suitable for testing interleave.
"""
ret... | 46aa7899e7ed536525b7a94675edf89958f6f37f | 3,657,348 |
from functools import reduce
def P2D_l_TAN(df, cond, attr): # P(attr | 'target', cond)
"""Calcule la probabilité d'un attribut sachant la classe et un autre attribut.
Parameters
----------
df : pandas.DataFrame
La base d'examples.
cond : str
Le nom de l'attribut conditionnant.
... | 88affcaea0368c400ccd25356d97a25c9a88a15e | 3,657,349 |
def has_no_jump(bigram, peaks_groundtruth):
"""
Tell if the two components of the bigram are same or successive in the sequence of valid peaks or not
For exemple, if groundtruth = [1,2,3], [1,1] or [2,3] have no jump but [1,3] has a jump.
bigram : the bigram to judge
peaks_groundtruth : the lis... | e334c389436d5cda2642f8ac7629b64074dcd0e0 | 3,657,350 |
import base64
def Base64WSDecode(s):
"""
Return decoded version of given Base64 string. Ignore whitespace.
Uses URL-safe alphabet: - replaces +, _ replaces /. Will convert s of type
unicode to string type first.
@param s: Base64 string to decode
@type s: string
@return: original string that was encod... | 67db2d3f298e0220411f224299dcb20feeba5b3e | 3,657,351 |
def make_window():
"""create the window"""
window = Tk()
window.title("Pac-Man")
window.geometry("%dx%d+%d+%d" % (
WINDOW_WIDTH,
WINDOW_HEIGHT,
X_WIN_POS,
Y_WIN_POS
)
)
window = window
return window | 1e9ecb5acf91e75797520c54be1087d24392f190 | 3,657,352 |
from typing import Union
import re
def construct_scrape_regex_patterns(scrape_info: dict[str, Union[ParseResult, str]]) -> dict[str, Union[ParseResult, str]]:
""" Construct regex patterns for seasons/episodes """
logger.debug("Constructing scrape regexes")
for info in scrape_info:
if info == 'url... | 8d731dee1dc1ce493a4a49140a2fbd11223018fd | 3,657,353 |
def hasf(e):
"""
Returns a function which if applied with `x` tests whether `x` has `e`.
Examples
--------
>>> filter(hasf("."), ['statement', 'A sentence.'])
['A sentence.']
"""
return lambda x: e in x | ac9ce7cf2ed2ee8a050acf24a8d0a3b95b7f2d50 | 3,657,354 |
def borehole_model(x, theta):
"""Given x and theta, return matrix of [row x] times [row theta] of values."""
return f | 9ccfd530ff162d5f2ec786757ec03917f3367635 | 3,657,355 |
def findNodesOnHostname(hostname):
"""Return the list of nodes name of a (non-dmgr) node on the given hostname, or None
Function parameters:
hostname - the hostname to check, with or without the domain suffix
"""
m = "findNodesOnHostname:"
nodes = []
for nodename in listNodes():... | 3a4f28d5fa8c72388cb81d40913e517d343834f0 | 3,657,356 |
def MakeControlClass( controlClass, name = None ):
"""Given a CoClass in a generated .py file, this function will return a Class
object which can be used as an OCX control.
This function is used when you do not want to handle any events from the OCX
control. If you need events, then you should derive a class from... | 634544543027b1870bb72544517511d4f7b08e39 | 3,657,357 |
def obtenTipoNom(linea):
""" Obtiene por ahora la primera palabra del título, tendría que regresar de que se trata"""
res = linea.split('\t')
return res[6].partition(' ')[0] | 73edc42c5203b7ebd0086876096cdd3b7c65a54c | 3,657,358 |
def histogramfrom2Darray(array, nbins):
"""
Creates histogram of elements from 2 dimensional array
:param array: input 2 dimensional array
:param nbins: number of bins so that bin size = (maximum value in array - minimum value in array) / nbins
the motivation for returning this array is for th... | 2c377b926b4708b6a6b29d400ae82b8d2931b938 | 3,657,359 |
def build_pert_reg(unsupervised_regularizer, cut_backg_noise=1.0,
cut_prob=1.0, box_reg_scale_mode='fixed',
box_reg_scale=0.25, box_reg_random_aspect_ratio=False,
cow_sigma_range=(4.0, 8.0), cow_prop_range=(0.0, 1.0),):
"""Build perturbation regularizer."""
i... | 37d60049146c876d423fea6615cf43975f1ae389 | 3,657,360 |
def part_5b_avg_std_dev_of_replicates_analysis_completed(*jobs):
"""Check that the initial job data is written to the json files."""
file_written_bool_list = []
all_file_written_bool_pass = False
for job in jobs:
data_written_bool = False
if job.isfile(
f"../../src/engines/go... | f238382e18de32b86598d5daa13f92af01311d3d | 3,657,361 |
def exportFlatClusterData(filename, root_dir, dataset_name, new_row_header,new_column_header,xt,ind1,ind2,display):
""" Export the clustered results as a text file, only indicating the flat-clusters rather than the tree """
filename = string.replace(filename,'.pdf','.txt')
export_text = export.ExportFi... | f9ade521b67c87518741fb56fb1c80df0961065a | 3,657,362 |
def indent_multiline(s: str, indentation: str = " ", add_newlines: bool = True) -> str:
"""Indent the given string if it contains more than one line.
Args:
s: String to indent
indentation: Indentation to prepend to each line.
add_newlines: Whether to add newlines surrounding the result... | 62eb2fc7c3f3b493a6edc009692f472e50e960f7 | 3,657,363 |
from typing import Optional
def _get_property(self, key: str, *, offset: int = 0) -> Optional[int]:
"""Get a property from the location details.
:param key: The key for the property
:param offset: Any offset to apply to the value (if found)
:returns: The property as an int value if found, None other... | 8d2c35a88810db5255cfb0ca9d7bfa6345ff3276 | 3,657,364 |
def pca_normalization(points):
"""Projects points onto the directions of maximum variance."""
points = np.transpose(points)
pca = PCA(n_components=len(np.transpose(points)))
points = pca.fit_transform(points)
return np.transpose(points) | 753bea2546341fc0be3e7cf4fd444b3ee93378f9 | 3,657,365 |
def _reformTrend(percs, inits):
"""
Helper function to recreate original trend based on percent change data.
"""
trend = []
trend.append(percs[0])
for i in range(1, len(percs)):
newLine = []
newLine.append(percs[i][0]) #append the date
for j in range(1, len(percs[i])): #for each term on date
level =... | 1f6c8bbb4786b53ea2c06643108ff50691b6f89c | 3,657,366 |
def PET_initialize_compression_structure(N_axial,N_azimuthal,N_u,N_v):
"""Obtain 'offsets' and 'locations' arrays for fully sampled PET compressed projection data. """
descriptor = [{'name':'N_axial','type':'uint','value':N_axial},
{'name':'N_azimuthal','type':'uint','value':N_azimuthal},
... | 1f879517182462d8b66886aa43a4103a05a5b6f9 | 3,657,367 |
def get_client_from_user_settings(settings_obj):
"""Same as get client, except its argument is a DropboxUserSettingsObject."""
return get_client(settings_obj.owner) | 4b2c2e87310464807bf6f73d1ff8d7b7c21731ff | 3,657,368 |
def train_student(
model,
dataset,
test_data,
test_labels,
nb_labels,
nb_teachers,
stdnt_share,
lap_scale,
):
"""This function trains a student using predictions made by an ensemble of
teachers. The student and teacher models are trained using the same neural
network architec... | de8db38bde151f5dd65b93a0c8a44c2289351f81 | 3,657,369 |
import numpy
def create_transition_matrix_numeric(mu, d, v):
"""
Use numerical integration.
This is not so compatible with algopy because it goes through fortran.
Note that d = 2*h - 1 following Kimura 1957.
The rate mu is a catch-all scaling factor.
The finite distribution v is assumed to be ... | a60a3da34089fffe2a48cc282ea4cbb528454fd6 | 3,657,370 |
import os
def parse_integrate(filename='INTEGRATE.LP'):
"""
Harvest data from INTEGRATE
"""
if not os.path.exists(filename):
return {'failure': 'Integration step failed'}
info = parser.parse(filename, 'integrate')
for batch, frames in zip(info.get('batches',[]), info.pop('batch_frames... | cc37e4a8f4ed35f0827e93f93e8da301d0b49c8e | 3,657,371 |
def channelmap(stream: Stream, *args, **kwargs) -> FilterableStream:
"""https://ffmpeg.org/ffmpeg-filters.html#channelmap"""
return filter(stream, channelmap.__name__, *args, **kwargs) | 8293e9004fd4dfb7ff830e477dcee4de5d163a5d | 3,657,372 |
def test_token(current_user: DBUser = Depends(get_current_user)):
"""
Test access-token
"""
return current_user | 1ceb90c1321e358124520ab5b1b1ecb07de4619d | 3,657,373 |
import mls
import os
def locate_data(name, check_exists=True):
"""Locate the named data file.
Data files under mls/data/ are copied when this package is installed.
This function locates these files relative to the install directory.
Parameters
----------
name : str
Path of data file ... | 86ed5d2403a8d97aabcd4b65361ffa6f82095fff | 3,657,374 |
def process_label_imA(im):
"""Crop a label image so that the result contains
all labels, then return separate images, one for
each label.
Returns a dictionary of images and corresponding
labels (for choosing colours), also a scene bounding
box. Need to run shape statistics to determine
the n... | 66e89e84d773d102c8fe7a6d10dd0604b52d9862 | 3,657,375 |
def render_graphs(csv_data, append_titles=""):
"""
Convenience function. Gets the aggregated `monthlies` data from
`aggregate_monthly_data(csv_data)` and returns a dict of graph
titles mapped to rendered SVGs from `monthly_total_precip_line()`
and `monthly_avg_min_max_temp_line()` using the `monthli... | c2258faf759c2fd91e55fea06384d5f7ec030154 | 3,657,376 |
import traceback
def _get_location():
"""Return the location as a string, accounting for this function and the parent in the stack."""
return "".join(traceback.format_stack(limit=STACK_LIMIT + 2)[:-2]) | f36037a440d2e8f3613beed217a758bc0cfa752d | 3,657,377 |
from apyfal.client.syscall import SysCallClient
from apyfal import Accelerator
import apyfal.configuration as cfg
import apyfal.exceptions as exc
def test_syscall_client_init():
"""Tests SysCallClient.__init__"""
# Test: accelerator_executable_available, checks return type
assert type(cfg.accelerator_exe... | cdbe5bbcd9aa2b5e655f5c693316f32ee6b9d073 | 3,657,378 |
def start_session():
"""do nothing here
"""
return Response.failed_response('Error') | b8c58ec837c5a77c35cb6682c6c405489cf512c0 | 3,657,379 |
def _combine_keras_model_with_trill(embedding_tfhub_handle, aggregating_model):
"""Combines keras model with TRILL model."""
trill_layer = hub.KerasLayer(
handle=embedding_tfhub_handle,
trainable=False,
arguments={'sample_rate': 16000},
output_key='embedding',
output_shape=[None, 2048]... | 97bf695e6b083dfefcad1d2c8ac24b54687047fd | 3,657,380 |
def phases(times, names=[]):
""" Creates named phases from a set of times defining the edges of hte intervals """
if not names: names = range(len(times)-1)
return {names[i]:[times[i], times[i+1]] for (i, _) in enumerate(times) if i < len(times)-1} | 0e56dcf57a736e4555cae02b8f79b827c17e1d38 | 3,657,381 |
def smesolve(H, rho0, times, c_ops=[], sc_ops=[], e_ops=[],
_safe_mode=True, args={}, **kwargs):
"""
Solve stochastic master equation. Dispatch to specific solvers
depending on the value of the `solver` keyword argument.
Parameters
----------
H : :class:`qutip.Qobj`, or time depen... | 4a27d54d2ca390bb3e4ac88ec2119633481df529 | 3,657,382 |
def harmonic_vector(n):
"""
create a vector in the form [1,1/2,1/3,...1/n]
"""
return np.array([[1.0 / i] for i in range(1, n + 1)], dtype='double') | 6f2a94e0a54566db614bb3c4916e1a8538783862 | 3,657,383 |
import copy
def get_install_task_flavor(job_config):
"""
Pokes through the install task's configuration (including its overrides) to
figure out which flavor it will want to install.
Only looks at the first instance of the install task in job_config.
"""
project, = job_config.get('project', 'c... | 11fcefe3df17acfbce395949aa615d8292585fb6 | 3,657,384 |
def equalize_hist(image, nbins=256):
"""Return image after histogram equalization.
Parameters
----------
image : array
Image array.
nbins : int
Number of bins for image histogram.
Returns
-------
out : float array
Image array after histogram equalization.
N... | ea990cee9bef0e2edc41e2c5279f52b98d2a4d89 | 3,657,385 |
def add9336(rh):
"""
Adds a 9336 (FBA) disk to virtual machine's directory entry.
Input:
Request Handle with the following properties:
function - 'CHANGEVM'
subfunction - 'ADD9336'
userid - userid of the virtual machine
parms['diskPool'] - Disk pool
... | bb7168d5b0ee084b15e8ef91633d5554669cf83f | 3,657,386 |
def window_data(s1,s2,s5,s6,s7,s8, sat,ele,azi,seconds,edot,f,az1,az2,e1,e2,satNu,pfitV,pele):
"""
author kristine m. larson
also calculates the scale factor for various GNNS frequencies. currently
returns meanTime in UTC hours and mean azimuth in degrees
cf, which is the wavelength/2
currently... | f3bd4e96059882c518bd1e8eb2a966eee9c9968a | 3,657,387 |
def get_related(user, kwargs):
"""
Get related model from user's input.
"""
for item in user.access_extra:
if item[1] in kwargs:
related_model = apps.get_model(item[0], item[1])
kwargs[item[1]] = related_model.objects.get(pk=get_id(kwargs[item[1]]))
return kwargs | 6b2ce081d1f61da734d26ef6f3c25e4da871b9ee | 3,657,388 |
def make_logical(n_tiles=1):
"""
Make a toy dataset with three labels that represent the logical functions: OR, XOR, AND
(functions of the 2D input).
"""
pat = np.array([
# X X Y Y Y
[0, 0, 0, 0, 0],
[0, 1, 1, 1, 0],
[1, 0, 1, 1, 0],
[1, 1, 1, 0, ... | e2d936db7ae0d9ea8b0f1654e89a32b5b8c247cc | 3,657,389 |
def get_idmap_etl(
p_idmap: object,
p_etl_id: str,
p_source_table: object =None
):
"""
Генерирует скрипт ETL для таблицы Idmap
:param p_idmap: объект класса Idmap
:param p_etl_id: id etl процесса
:param p_source_table: таблица источник, которую требуется загрузить в idmap
... | 0e24b4cbb5ea935c871cae3338094292c9ebfd02 | 3,657,390 |
def gs_tie(men, women, preftie):
"""
Gale-shapley algorithm, modified to exclude unacceptable matches
Inputs: men (list of men's names)
women (list of women's names)
pref (dictionary of preferences mapping names to list of sets of preferred names in sorted order)
Output: dictiona... | b5dbe7047e3e6be7f0d288e49f8dae25a94db318 | 3,657,391 |
def is_iterable(value):
"""Return True if the object is an iterable type."""
return hasattr(value, '__iter__') | 55e1ecc9b264d39aaf5cfcbe89fdc01264191d95 | 3,657,392 |
def get_search_app_by_model(model):
"""
:returns: a single search app (by django model)
:param model: django model for the search app
:raises LookupError: if it can't find the search app
"""
for search_app in get_search_apps():
if search_app.queryset.model is model:
return se... | 0670fe754df65b02d5dfc502ba3bd0a3a802370c | 3,657,393 |
def prct_overlap(adata, key_1, key_2, norm=False, ax_norm="row", sort_index=False):
"""
% or cell count corresponding to the overlap of different cell types
between 2 set of annotations/clusters.
Parameters
----------
adata: AnnData objet
key_1: observational key corresponding to one ce... | 77a8382af77e8842a99211af58d6a6f85de6a50e | 3,657,394 |
def keep_category(df, colname, pct=0.05, n=5):
""" Keep a pct or number of every levels of a categorical variable
Parameters
----------
pct : float
Keep at least pct of the nb of observations having a specific category
n : int
Keep at least n of the variables having a specific categ... | 3db00aa6bdea797827a693c8e12bbf942a55ec35 | 3,657,395 |
def remove_scope_from_name(name, scope):
"""
Args:
name (str): full name of the tf variable with all the scopes
Returns:
(str): full name of the variable with the scope removed
"""
result = name.split(scope)[1]
result = result[1:] if result[0] == '/' else result
return resul... | aa70042a2f57185a0f5e401d182a02e5654eb2b0 | 3,657,396 |
async def get_timers_matching(ctx, name_str, channel_only=True, info=False):
"""
Interactively get a guild timer matching the given string.
Parameters
----------
name_str: str
Name or partial name of a group timer in the current guild or channel.
channel_only: bool
Whether to ma... | 48e94d2930f48b47b033ec024246065206a2bebb | 3,657,397 |
import random
def comprehension_array(size=1000000):
"""Fills an array that is handled by Python via list comprehension."""
return [random() * i for i in range(size)] | e3ccdc992e5b741cf6f164c93d36f2e45d59a590 | 3,657,398 |
def alignment(alpha, p, treatment):
"""Alignment confounding function.
Reference: Blackwell, Matthew. "A selection bias approach to sensitivity analysis
for causal effects." Political Analysis 22.2 (2014): 169-182.
https://www.mattblackwell.org/files/papers/causalsens.pdf
Args:
alpha (np.a... | 8097dbcd62ba934b31b1f8a9e72fd906109b5181 | 3,657,399 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.