content stringlengths 35 762k | sha1 stringlengths 40 40 | id int64 0 3.66M |
|---|---|---|
def singer_map(pop, rate):
"""
Define the equation for the singer map.
Arguments
---------
pop: float
current population value at time t
rate: float
growth rate parameter values
Returns
-------
float
scalar result of singer map at time t+1
"""
return... | 84aba1d96304b67fba1b4a0e7a909e23121a3d6b | 3,630,500 |
def initialize_embedding_from_dict(vector_map, dim, vocabulary, zero_init=False, standardize=False):
"""
Initialize a numpy matrix from pre-exi\sting vectors with indices corresponding to a given vocabulary. Words in vocabulary
not in vectors are initialized using a given function.
:param vector_map: di... | 0af00d66f8c14909e5e447f2b8eb4bd68c551c97 | 3,630,501 |
def setup_kfolds(
data_dict,
ordered_chrom_keys,
num_examples_per_file,
k):
"""given k, split the files as equally as possible across k
"""
# set up kfolds dict
kfolds = {}
examples_per_fold = {}
for k_idx in xrange(k):
kfolds[k_idx] = [[], [], []]
... | 78035e0e21a9a31cc134721846ded14ccc9528b7 | 3,630,502 |
def get_wall_status_data_by_simplified_calculation_no_01() -> pd.DataFrame:
"""
通気層を有する壁体の総当たりパラメータを取得し、簡易計算法案No.1(簡易版の行列式)による計算結果を保有するDataFrameを作成する
:param: なし
:return: DataFrame
"""
# パラメータの総当たりリストを作成する
parameter_name = ['theta_e', 'theta_r', 'j_surf', 'a_surf', 'C_1', 'C_2', 'l_h', 'l_w... | dafe25b6b484c0116da0f7837555a3b29cc5b068 | 3,630,503 |
def get_audio_embedding(audio, sr, model=None, input_repr="mel256",
content_type="music", embedding_size=6144,
center=True, hop_size=0.1, batch_size=32,
verbose=True):
"""
Computes and returns L3 embedding for given audio data.
Embeddi... | 2a2448c46cbe31c0631ccd049eca796e94a5f973 | 3,630,504 |
import json
def format_rpc_response(data, exception=None):
"""
Formats a response from a RPC Manager.
It provides the data and/or a serialized exception so it can be
re-created by the caller.
:param Any data: A JSON Serializable object.
:param Exception exception: An Exception object
:ret... | c900e2512fd486c91789ab4312883061553a2fb1 | 3,630,505 |
def AbsoluteError(U, Uold):
"""Return absolute error.
Absolute error is calculated to track the changes or deviation in
the numerical solution. This is done by subtracting the solution
obtained at the current time step from the solution at previous
time step within the entire domain.
The compu... | 179cbe81cee92a01e12509b42f6a8800a6c05976 | 3,630,506 |
import os
def scene_filename():
"""Construct a safe scene filename, using 'untitled' instead of ''"""
filename = os.path.splitext(os.path.basename(bpy.data.filepath))[0]
if filename == '':
filename = 'untitled'
return bpy.path.clean_name(filename) | 685177d19345f3e3e8f57761f4f7f7a675bd4920 | 3,630,507 |
from datetime import datetime
import os
def init():
"""Create a new cycle and return its identifier."""
idf = datetime.now().strftime(idffmt)
os.mkdir(directory(idf))
return idf | f93fcf76e120de34fbd2aa7fb32b00c7a0f13add | 3,630,508 |
import os
from datetime import datetime
def convsub_photometry_to_ismphot_database(convsubfits,
convsubphot,
photreftype,
subtracttype,
kernelspec... | 609a6b9b8bfb2189efa0d0271d4c7261495fb0c0 | 3,630,509 |
import typing
def safe_redirect(endpoint: str,
**params: str | bool | None) -> typing.RouteReturn | None:
"""Redirect to a specific page, except if we are already here.
Avoids infinite redirection loops caused by redirecting to the
current request endpoint.
It also automatically ad... | 9cca685ae4e7476be6759d9b4721d7f3e1b7b89f | 3,630,510 |
import scipy
def interpolate_with_ot(p0, p1, tmap, interp_frac, size):
"""
Interpolate between p0 and p1 at fraction t_interpolate knowing a transport map from p0 to p1
Parameters
----------
p0 : 2-D array
The genes of each cell in the source population
p1 : 2-D array
The genes... | 419635d2f6db9a8b95eada62221b1242ceecb80f | 3,630,511 |
import functools
def db_session(func) -> Session:
"""
gets a connection from the pool, create an orm session and passes it as first parameter to `func`
after finish the connection is returned to the pool
no transaction handling
"""
@functools.wraps(func)
def _wrapper(*args, **kwargs):
... | 1ea1f3850b4c062c91b2a33302a23040c9d2d72b | 3,630,512 |
import torch
def get_attention(preds, temp):
""" preds: Bs*C*W*H """
N, C, H, W = preds.shape
value = torch.abs(preds)
# Bs*W*H
fea_map = value.mean(axis=1, keepdim=True)
print("fea_map = ", fea_map.shape)
S_attention = (
H * W * F.softmax((fea_map/temp).view(N, -1), dim=1)).view(... | 0c257ca2fbc17a5e56702c15a138567e7ed81bec | 3,630,513 |
import logging
def select_best_haplotype_match(all_matches):
"""Returns the best HaplotypeMatch among all_matches.
The best matching HaplotypeMatch is the one with the lowest match_metrics
score.
Args:
all_matches: iterable[HaplotypeMatch]. An iterable of HaplotypeMatch objects
we want to select t... | 0e40fef830055e5cd297b0f00672d8b0caedc62e | 3,630,514 |
def get_tokens_list_from_column_list(column_name_list: list,
delimiter: str = '!!') -> list:
"""Function that returns list of tokens present in the list of column names.
Args:
column_name_list: The list of column name strings.
delimiter: delimiter seperating tok... | 66e2c3c280188d2cc3e8df35e0112095f3244918 | 3,630,515 |
def solve(task: str, preamble_length=25) -> int:
"""What is the first invalid number?"""
data = [int(num) for num in task.strip().split("\n")]
return first_invalid(data, preamble_length) | e574aeaba225010e0538d0298a198e37d2272e74 | 3,630,516 |
def schedule(course_list):
"""
Given a list of courses, return a dictionary of the possible schedules
['BT 353','CS 135','HHS 468','BT 181','CS 146','CS 284'] -->
{1:
{'url': 'https://web.stevens.edu/scheduler/#2015F=10063,10486,10479,11840,12011,11995,10482,10487',
'list': "('BT 181A', ... | 8c9c5db6e49b1ae106e7d83a38dde0fc2e7617e7 | 3,630,517 |
def get_repository_instance(conf=None):
"""
Helper function to get a database Repository model instance based on CLA configuration.
:param conf: Same as get_database_models().
:type conf: dict
:return: A Repository model instance based on configuration specified.
:rtype: cla.models.model_interf... | 33b49af8dd1db0af572b6ddc0d3ad5d919e06eb8 | 3,630,518 |
import operator
def _setup_RepeatingContainer_special_names(repeating_class):
"""This function is run when the module is imported--users should
not call this function directly. It assigns magic methods and
special attribute names to the RepeatingContainer class.
This behavior is wrapped in a function... | 83909835d62599f190e26d3e72c40a9759cfbbf4 | 3,630,519 |
def set_up_nircam():
"""
Return a configured instance of the NIRCam simulator on JWST.
Sets up the Lyot stop and filter from the configfile, turns of science instrument (SI) internal WFE and zeros
the OTE.
:return: Tuple of NIRCam instance, and its OTE
"""
nircam = webbpsf.NIRCam()
nir... | b994561fe00f34e704f4ffc06f162da1bc060425 | 3,630,520 |
def _dens0(S,T):
"""Density of seawater at zero pressure"""
# --- Define constants ---
a0 = 999.842594
a1 = 6.793952e-2
a2 = -9.095290e-3
a3 = 1.001685e-4
a4 = -1.120083e-6
a5 = 6.536332e-9
b0 = 8.24493e-1
b1 = -4.0899e-3
b2 = 7.6438e-5
b3 = -8.2467e-7
... | a0df8ba385c18fbb7f51088cac2ec842bdef308f | 3,630,521 |
import logging
def parse_log_level(x):
"""Identify log level in config file"""
return {
'DEBUG': logging.DEBUG,
'INFO': logging.INFO,
'WARNING': logging.WARNING,
'ERROR': logging.ERROR,
'CRITICAL': logging.CRITICAL
}.get(x, None) | 28e599c124c0b375659d3eed2a94b27f3b65e8b2 | 3,630,522 |
import warnings
import ctypes
def convolve(array, kernel, boundary='fill', fill_value=0.,
nan_treatment='interpolate', normalize_kernel=True, mask=None,
preserve_nan=False, normalization_zero_tol=1e-8):
"""
Convolve an array with a kernel.
This routine differs from `scipy.ndimag... | b4ec7a5e8f8e7b1ddd9fd14f50efda96ffb548fd | 3,630,523 |
from pathlib import Path
from typing import Optional
def get_k_best_and_worst_performing(val_metrics_csv: Path, test_metrics_csv: Path, k: int,
prediction_target: str = MetricsDict.DEFAULT_HUE_KEY) -> Optional[Results]:
"""
Get the top "k" best predictions (i.e. correct cla... | 5aaa2510f72649be280859793e0959def07d6e0a | 3,630,524 |
def flow_experiment_from_csv(filename):
"""
Initialise a flow experiment from a formatted .csv file.
Parameters
----------
filename: str
Name of a formatted configuration file.
Returns
-------
experiment: Classes.FlowExperiment
"""
with open(filename, "r", encoding="ut... | 9e37a4392eb3f96dfbd3b8947badb9009e252513 | 3,630,525 |
def get_int(value, allow_sign=False):
"""Convert a value to an integer.
Args:
value: String value to convert.
allow_sign: If True, negative values are allowed.
Return:
int(value) if possible.
"""
try:
# rstrip needed when 0. is passed via [count]
int_val = in... | a50b23cac634d4cf414fa18a68f5a926c0702735 | 3,630,526 |
from typing import Union
def calculate_weights(
performance: Union['xr.DataArray', None],
independence: Union['xr.DataArray', None],
performance_sigma: Union[float, None],
independence_sigma: Union[float, None]) -> 'xr.DataArray':
"""Calculate normalized weights for each model N.
... | 2a5e578b80fb4cff7e8d90ce0d8c7a98d777342f | 3,630,527 |
def validate_state(state):
"""
State validation rule.
Property: LifecyclePolicy.State
"""
VALID_STATES = ("ENABLED", "DISABLED")
if state not in VALID_STATES:
raise ValueError("State must be one of : %s" % ", ".join(VALID_STATES))
return state | 5dcc3d2c8bf9242d8090aef0933f26d2ffa1821d | 3,630,528 |
def load_variable_config(project_config):
"""Extract the variable configuration out of the project configuration.
Args:
project_config (dict-like): Project configuration.
Returns:
dict: Variable dictionary with name: [levels] (single level will have a list containing None.)
"""
# ... | 37caccfa5f9c3a724e61233610c3e4a3e9938695 | 3,630,529 |
from typing import Union
from typing import List
def absolute_simulations_distance_for_tables(
simulation_dfs: Union[List[pd.DataFrame], pd.DataFrame],
gt_simulation_dfs: Union[List[pd.DataFrame], pd.DataFrame]):
"""Compute absolute normalized distance between simulations.
Parameters
----... | e7090bc60bc9da4aed070e7c0af78e91aad7504d | 3,630,530 |
def _experiment_fn(run_config, hparams):
"""Outputs `Experiment` object given `output_dir`.
Args:
run_config: `EstimatorConfig` object fo run configuration.
hparams: `HParams` object that contains hyperparameters.
Returns:
`Experiment` object
"""
estimator = learn.Estimator(
... | aebf6b7586ece3a995f29b8f7f52283e3d29a478 | 3,630,531 |
import torch
def cross_op_torch(r):
"""
Return the cross operator as a matrix
i.e. for input vector r \in \R^3
output rX s.t. rX.dot(v) = np.cross(r, v)
where rX \in \R^{3 X 3}
"""
if len(r.shape) > 1:
rX = torch.zeros(r.shape[0], 3, 3).to(r)
rX[..., 0, 1] = -r[..., 2]
rX[..., 0, 2] = ... | 04f926f00f6ed58bee3feae80ef573f5a8822d20 | 3,630,532 |
from datetime import datetime
def apply_internal(user_id, job_id, resume, comment):
"""
Basic logic for applying to internal job postings.
Arguments:
`user_id`: ID of the user applying
`job_id`: ID of the job a user is applying for
`resume`: Handy tool for applying to jobs
"""
if not ... | af7ebb2e9a31c4ee41514d6330a416018e85999e | 3,630,533 |
def check_acls(user, obj, acl_type):
"""Check ACLs."""
if acl_type == 'moz_contact':
try:
return user.email in obj.addon.get_mozilla_contacts()
except AttributeError:
return user.email in obj.thread.addon.get_mozilla_contacts()
if acl_type == 'admin':
return a... | 6d00906484479c918280e92cc61168aa5959e066 | 3,630,534 |
def variable_labels():
"""Dictionaries that contain Variables objects."""
_phi = r'$\phi$'
_eta = r'$\eta$'
_T = r'$_\text{T}$ [GeV]'
_mass = 'Mass [GeV]'
variables = {}
variables['ljet_C2'] = Variable(binning=hist1d(10, 0., 0.6), label=r'Large-R Jet C$_2^{\beta\text{=1}}$')
v... | 38cf74c3c4a1a136adfa81ee8ff675062caf1f7e | 3,630,535 |
def _calcDistance(fiberMatrix1, fiberMatrix2):
""" *INTERNAL FUNCTION*
Computes average Euclidean distance
INPUT:
fiberMatrix1 - 3D matrix containing fiber spatial infomration
fiberMatrix2 - 3D matrix containing fiber spatial information for
comparison
OUTPUT:
... | d50fef85c6a682c093ba62394103d525d23f58b7 | 3,630,536 |
def find_suppliers(client, framework, supplier_ids=None, map_impl=map, dry_run=False):
"""Return supplier details for suppliers with framework interest
:param client: data api client
:type client: dmapiclient.DataAPIClient
:param dict framework: framework
:param supplier_ids: list of supplier IDs t... | 8343b53249d392a8cddae8d1ca1069736cd2cf9d | 3,630,537 |
from typing import Dict
def filter_topology(model: Dict[str, str], operator: str, value: str,
component: str):
"""Check whether model should be included according to the user input. The
model should be added if the its topology is consistent with the components
requested by the user (n... | c4e26a89a271e5f70b0ca1afae47a78a3e6acca0 | 3,630,538 |
def getAuctionPrice(the_auction: models.DutchAuction, bid: Transaction[BidParameter, TezlandDutchAuctionsStorage]):
"""Returns current price in mutez.
More or less pasted from dutch auction contract."""
granularity = int(bid.storage.granularity)
op_now = bid.data.timestamp
# return start price if ... | 4503fe0212935a2b37a15000448dd0fe8b5674a4 | 3,630,539 |
def __all_paths_between_acceptance_states(Dfa):
"""Generates for each front acceptance state a copy of the complete
graph which can be reached inside 'Dfa' starting from it until the next
acceptance state.
RETURNS: List of DFAs containing a tail for each found acceptance states.
"""
def _get_br... | 136ea0a999bff3b930ad4e05107042da36262d13 | 3,630,540 |
def hello():
"""
An op definition. This example op outputs a single string.
For more hints about writing Dagster ops, see our documentation overview on Ops:
https://docs.dagster.io/concepts/ops-jobs-graphs/ops
"""
return "Hello, Dagster!" | cf701323e751122823f22bad864f7b1f0d700a97 | 3,630,541 |
def vtk_clean_polydata(surface):
"""
Clean surface by merging
duplicate points, and/or
removing unused points
and/or removing degenerate cells.
Args:
surface (vtkPolyData): Surface model.
Returns:
cleanSurface (vtkPolyData): Cleaned surface model.
"""
# Clean surfac... | 340d1e9377b378ff007a6fd115508e7c25890de2 | 3,630,542 |
def custom_exception_handler(exc, context):
"""
A custom exception handler that makes sure errors are returned with a fixed format.
Django, django-rest-framework, and the jwt framework all throw exceptions in slightly
different ways. This has to be caught and each type of exception has to be converted
... | fbb3e8934851b53ea0e771b39d0d5e0fc992ff3e | 3,630,543 |
def fetch_svc(k8s_host, **kwargs):
"""
Fetch named service definition from Kubernetes (output: dict)
"""
pass_headers = {}
if 'k8s_api_headers' in kwargs:
headers = kwargs.pop('k8s_api_headers')
pass_headers.update(headers)
namespace = kwargs['namespace']
service_name = kwargs[... | c302f0cbaf7026356e9f6f9adae2820bb9d17ae5 | 3,630,544 |
def mentionable():
"""
:return: boolean
True, if there is something mentionable to notify about
False, if not
"""
# need to be implemented
return False | d1dac607efb512771677aa7e8dd42a2c21251833 | 3,630,545 |
def cmp_ver(a, b):
"""Compare versions in the form 'a.b.c'
"""
for (i, j) in zip(split_ver(a), split_ver(b)):
if i != j:
return i - j
return 0 | d774235354c613cec15e2d438bc6a1e60e678ae7 | 3,630,546 |
import os
import fnmatch
def findFileTypes(wpath, type ='*.txt', verbose=False):
""" to find all the files in wpath and below with file names matching fname
"""
alist=sorted(os.walk(wpath))
if verbose:
print(' getting file list')
listPath = []
listFile = []
fileName = []
for (... | b424d8bb93bfa5540847a308de9259c5ba14a048 | 3,630,547 |
import argparse
def _parse_args(argv=None):
"""Parse command-line args."""
def _positive_int(value):
"""Define a positive integer ArgumentParser type."""
value = int(value)
if value <= 0:
raise argparse.ArgumentTypeError(
"Value must be positive, {} was pas... | abb5d64089e200592f057ee1356d135328196dab | 3,630,548 |
def delete_buckets(buckets) -> list:
"""Deletes all buckets from a list
Args:
buckets (list): A list of s3 buckets
Returns:
A list of terminated buckets
"""
terminated_buckets = []
for bucket in buckets:
bucket_name = bucket["Name"]
if helpers.check_in_whitelist... | 17c1eaf5b277a3343fd4d0403150b571fa462ee9 | 3,630,549 |
def box_fusion(
bounding_boxes,
confidence_score,
labels,
mode='wbf',
image_size=None,
weights=None,
iou_threshold=0.5):
"""
bounding boxes:
list of boxes of same image [[box1, box2,...],[...]] if ensemble many models
list of boxes of sing... | 59622e278e6805b1a726871bec089a90a68c1d4f | 3,630,550 |
def get_worker_class(global_conf, message):
"""Returns class of worker needed to do message's work"""
worker_type = 'worker-%s' % (message.body['worker_type'])
if worker_type not in global_conf:
raise RuntimeError("Invalid worker type '%s'" % (worker_type))
conf = global_conf[worker_type]
im... | 3f975caf97827fcfaf7d74141ea651c302e4781c | 3,630,551 |
def is_valid_widget(widget):
"""
Checks if a widget is a valid in the backend
:param widget: QWidget
:return: bool, True if the widget still has a C++ object, False otherwise
"""
if widget is None:
return False
# Added try because Houdini does not includes Shiboken library by defau... | 62f01d4e5be2a29c2cb2fc3bd96c98ae18a6477b | 3,630,552 |
from typing import Dict
import os
import yaml
def get_builtin_configs() -> Dict[str, ClientConfig]:
"""
Return a cached mapping of preconfigured clients.
"""
path = os.path.join(os.path.dirname(__file__), "builtin_clients.yml")
with open(path, "r", encoding="utf-8") as fdata:
configs = yam... | 0aee618d7f376207c69abd4a8e7e4e2858d63d0d | 3,630,553 |
def isConsistant(spectrum,kmer):
"""Checks whether a given kmer is consistent with a given spectrum or not.
INPUT :
spectrum: array-like. The spectrum required to check the given kmer against.
kmer: string. The given kmer required to check its consistency.
OUTPUT:
.: bool. The consist... | 0403fdcb324d40d10bdc4555f3d8eb26faebe8ed | 3,630,554 |
def validate_java_file(java_file):
"""Validates a java file.
Args:
java_file_path: the path to the java file.
Returns:
a list of errors.
"""
file_status, java_file_path = java_file
with open(java_file_path, "r") as fp:
contents = fp.read()
if not contents:
return ["[ERROR] Errors exist in " + java_fi... | a0bde1c13ef1d7b5056fe47fefe05bfd8bbcf7b1 | 3,630,555 |
def convertVoltage(raw_voltage):
""" Ground is 1
1.8 is 4095
"""
converted_voltage = (raw_voltage/4095)*1.8
return "%.3f" % converted_voltage | 4f404ff02449a231521f80a2b9a4ae443880e1b3 | 3,630,556 |
def fast_ica(image, components):
"""Reconstruct an image from Fast ICA compression using specific number of components to use
Args:
image: PIL Image, Numpy array or path of 3D image
components: Number of components used for reconstruction
Returns:
Reconstructed image
Example:
... | 49ade88a8d1fe6a7addf8eb35be326088b916846 | 3,630,557 |
from typing import Callable
from typing import Optional
from typing import Union
from typing import Tuple
from typing import Iterable
def solve_nr(
f: Callable[[float], float],
df: Callable[[float], float],
estimate: float,
eps: Optional[float]=1.0e-6,
max_num_iter=100,
throw_if_failed_converge=True,
re... | c6ab8b6bb27f8b9be9c31fe7cbd58300637d9fef | 3,630,558 |
import json
def get_data(source):
"""fungsi ambil data pegawai, jadwal, judul, liburan"""
with open(source, 'r') as srce:
return json.load(srce) | 964efdabcbd21486985bbc9189c5d07dbc800dd6 | 3,630,559 |
import os
def load_testsets_by_path(path):
""" load testcases from file path
@param path: path could be in several type
- absolute/relative file path
- absolute/relative folder path
- list/set container with file(s) and/or folder(s)
@return testcase sets list, each testset is corre... | 2bed9249d297734cfcf37de42a958890941dc647 | 3,630,560 |
def unpack_request(data):
"""Take a buffer and return a pair of the RequestHeader and app data"""
start = MSG_TYPE_SIZE + REQUEST_HEADER_SIZE
return (unpack_request_header(data), data[start:]) | ed0e2baf9aa510e6460eb3a9b4e5e95295389bfe | 3,630,561 |
def basic_pl_stats(degree_sequence):
"""
:param degree sequence of individual nodes
"""
results = Fit(degree_sequence,discrete=True)
return (results.alpha,results.sigma) | a079169a328547a2f43eb6ed9431202895cd75f9 | 3,630,562 |
def merge_config_dictionaries(*dicts):
"""
Merges n dictionaries of configuration data
:param list<dicts>:
:return dict:
"""
res_dict = {}
if isinstance(dicts, list):
if len(dicts) == 1 and isinstance(dicts[0], dict):
return dicts[0]
else:
for diction... | c9711e897d5c7caa47a21f3e901025c91862327f | 3,630,563 |
def op_catalog_size() -> int:
"""
Return number of entries in the operational-data catalog
@return: integer
"""
return sum(len(entries) for entries in _op_catalog.values()) | 844519ec9afa3b06138128f5559acc2090ad4452 | 3,630,564 |
import json
def worker_recv_export_job(request):
"""Worker进程(集群节点)请求接受给定ID(taskSettingId)的导出任务"""
try:
datas = json.loads(request.body.decode())
taskSettingId = int(datas["params"]["taskSettingId"])
# Worker进程可以有多个,为了防止并发请求导致job更新不及时被两个Worker消费,这里需要这样处理
updateRows = PlExportJob... | 084526b0021e7fb31d5edb041fde2c734729a5cc | 3,630,565 |
def add_host_log_history(
host_id, exception_when_existing=False,
filename=None, user=None, session=None, **kwargs
):
"""add a host log history."""
host = _get_host(host_id, session=session)
return utils.add_db_object(
session, models.HostLogHistory, exception_when_existing,
host.id,... | 511213a6f00660c8e5921cf23974842e413e1725 | 3,630,566 |
import os
import json
def process_schools(schools_data, url):
"""
Calculate number of wheelchair-accessible and total stops for each school.
type: str
:param: schools_data: path to the school data json file
:type: str
:param: url: currently, this value is https://api-v3.mbta.com/stops
"""... | 64bd2fe4319caeba56345dbe34261cc341ae94e1 | 3,630,567 |
import os
def load_fiveplates_priority(platerun, filling_scheme):
"""
"""
priority_file = paths.fiveplates_priority(platerun, filling_scheme)
if priority_file.exists():
pass
else:
raise FileNotFoundError(os.fspath(priority_file))
priority_table = Table.read(os.fspath(priority_f... | dd55b8536b33673b40e8b6aaf0170b118bc903d4 | 3,630,568 |
def get_main_window():
"""Return the tkinter root window that Porcupine is using."""
if _root is None:
raise RuntimeError("Porcupine is not running")
return _root | 8c4ff2126f3f9c3367214ff1fe186106e15e7f57 | 3,630,569 |
def calculate_cluster_spatial_enrichment(all_data, dist_mats, fovs=None,
bootstrap_num=1000, dist_lim=100):
"""Spatial enrichment analysis based on cell phenotypes to find significant interactions between different
cell types, looking for both positive and negative enric... | 62cef02346e1461c03a46dad81cb5814010cc8c7 | 3,630,570 |
import calendar
import pytz
def epoch(dt):
"""
Returns the epoch timestamp of a timezone-aware datetime object.
"""
return calendar.timegm(dt.astimezone(pytz.utc).timetuple()) | 027ea75bf75b6bb6b4da14b2bed1afc363a9121a | 3,630,571 |
def main():
"""Implements the main method running this smoke test."""
defaults = {
'TEST_STACK': str(OpenStackSmokeTestScenario.DEFAULT_TEST_ID),
'TEST_APP': 'openstack-smoketest' + OpenStackSmokeTestScenario.DEFAULT_TEST_ID
}
return citest.base.TestRunner.main(
parser_inits=[OpenStackSm... | 02e542c2337f9582e38bedec6067c4290d0317f6 | 3,630,572 |
def is_pandas_series(value):
"""
Check if an object is a Pandas DataFrame
:param value:
:return:
"""
return isinstance(value, pd.Series) | 3ea667302f4a60f68569555c650a297e6b7b3a18 | 3,630,573 |
from typing import Union
import copy
import numpy
def copy_visibility(vis: Union[Visibility, BlockVisibility], zero=False) -> Union[
Visibility, BlockVisibility]:
"""Copy a visibility
Performs a deepcopy of the data array
:param vis: Visibility or BlockVisibility
:returns: Visibility or BlockVisi... | 451d0d365611d3538d8bc3e9d90fc82771df8290 | 3,630,574 |
def set_produce_compilation_cache(enabled: bool) -> dict:
"""Forces compilation cache to be generated for every subresource script.
Parameters
----------
enabled: bool
**Experimental**
"""
return {"method": "Page.setProduceCompilationCache", "params": {"enabled": enabled}} | 3d2dd7fa6c8d04713ace26c666d9b00407a5a586 | 3,630,575 |
import argparse
def get_args(strInput=None):
"""
Collect arguments from command-line, or from strInput if given (only used for debugging)
"""
parser = argparse.ArgumentParser(description="This program allows you to run the randomoverlaps3.py script against "
... | 2e8f65a07e9f61a452a96699f94950f0117e86fa | 3,630,576 |
def raw_input(prompt=None): # real signature unknown; restored from __doc__
"""
raw_input([prompt]) -> string
Read a string from standard input. The trailing newline is stripped.
If the user hits EOF (Unix: Ctl-D, Windows: Ctl-Z+Return), raise EOFError.
On Unix, GNU readline is used if enabled... | ad09db4416e3705a34e4fc88c7df569693608c80 | 3,630,577 |
import zlib
import os
def get_checksum32(oqparam):
"""
Build an unsigned 32 bit integer from the input files of the calculation
"""
# NB: using adler32 & 0xffffffff is the documented way to get a checksum
# which is the same between Python 2 and Python 3
checksum = 0
for key in sorted(oqpa... | c7aaf8d6aeefaa4b3f97dcac535c959b4ba06579 | 3,630,578 |
import asyncio
def create_future(*, loop):
""" Helper for `create a new future`_ with backward compatibility for Python 3.4
.. _create a new future: https://goo.gl/YrzGQ6
"""
try:
return loop.create_future()
except AttributeError:
return asyncio.Future(loop=loop) | 1708ac124c46fa81b7ff3ca1d7b685e4835cd53a | 3,630,579 |
def log_sum_exp(mat, axis=0):
"""
Computes the log-sum-exp of a matrix with a numerically stable scheme,
in the user-defined summation dimension: exp is never applied
to a number >= 0, and in each summation row, there is at least
one "exp(0)" to stabilize the sum.
For instance, if dim = 1 and m... | a72536b03e58eede19e6d18846b44fb1454891cb | 3,630,580 |
def msd(n_x, yr, min_support):
"""Compute the Mean Squared Difference similarity between all pairs of
users (or items).
Only **common** users (or items) are taken into account. The Mean Squared
Difference is defined as:
.. math ::
\\text{msd}(u, v) = \\frac{1}{|I_{uv}|} \cdot
\\sum... | 867989ef28cbce2e4235cb2704ab39cab0eae5f3 | 3,630,581 |
import argparse
def create_parser():
""" Parse command line arguments """
parser = argparse.ArgumentParser(
description="Zeus Z80 assembler files converter")
parser.add_argument(
'-v', '--verbose', help="Increase output verbosity",
action='store_true')
subparsers = parser.add_... | 995b7b2280c13ed5c750186966c4ddffff6944d1 | 3,630,582 |
def wrap_deepmind(env,
episode_life=True,
resize=True,
grayscale=True,
width=84,
height=84,
scale=False,
clip_rewards=True,
frame_stack=True,
stack=4):
""... | 83229995b9be22721e386e8162dde49516d4c0b5 | 3,630,583 |
def annotate_intersection(sv, elements, filetype='gtf'):
"""
Parameters
----------
sv : pbt.BedTool
SV breakpoints and CNV intervals
gencode : pbt.BedTool
Gencode annotations
"""
# Number of fields in SV bedtool
N_BED_FIELDS = 6
# Check intersection with gene bounda... | 4a4b395438c3d1f2c8e1c7fdaccbd3acadbfc6d3 | 3,630,584 |
def analyzeGHP(ghp):
"""Analyze this libLF.GitHubProject
Returns:
(testsPassed, libLF.RegexUsage[])
"""
dynoRegexFileName = getRegexOutputFileName()
libLF.log("{}/{} will use dyno regex file {}".format(ghp.owner, ghp.name, dynoRegexFileName))
libLF.log("Untarring")
untarDir = unpackTarball(ghp)
... | acc0303706ae87f9be643adb9512e32a16b1cfb3 | 3,630,585 |
import re
def convert(name):
"""
Converts camelCase strings to snake_case ones.
:param name
"""
s1 = re.sub('(.)([A-Z][a-z]+)', r'\1_\2', name)
return re.sub('([a-z0-9])([A-Z])', r'\1_\2', s1).lower() | 6a2177023e2f4cdc495aa0525790aeb40ea9d8b8 | 3,630,586 |
def normalize_inputs(py_dict: dict) -> dict:
"""Normalize a dictionary of inputs to contiguous numpy arrays."""
return {k: (Tensor(v) if isinstance(v, np.ndarray) else v)
for k, v in py_dict.items()} | e82d877f98478b2483dca2d6ca8026dba5d87e10 | 3,630,587 |
def get_task_definition_arns():
"""List all task definition ARNs."""
client = get_client("ecs")
return client.list_task_definitions() | 77b016f0f6911870a5f48edcd57fa90e596e1e8b | 3,630,588 |
def clean_column(df, column):
"""
Function to return clean column text. Pass each cell to a cleaner
and return the cleaned text for that specific column
:params:
--------
:df dataframe(): containing the column
:column str(): in which column the text is located
:returns:
---... | 095a854c452f87b9a960eabb81ace5c18814f266 | 3,630,589 |
def get_sheet():
"""
Get selected sheet or active view if sheet
:return: Sheet
:rtype: DB.ViewSheet
"""
sheets = get_selected_by_cat(DB.BuiltInCategory.OST_Sheets, as_list=True)
if sheets:
if len(sheets) > 1:
raise ScriptError("Please select only one sheet") # FIXME
... | a82eb2558707c51d22e6262ad89d7520a922a207 | 3,630,590 |
from typing import Optional
from typing import Iterable
def augment_cost_function(
cost_function: CostFunction,
cost_function_augmentations: Optional[Iterable[FunctionAugmentation]] = None,
gradient_augmentations: Optional[Iterable[FunctionAugmentation]] = None,
):
"""Augment a function and its gradie... | 3cf0e1e51d63ccff75f7438ae052a2832fd9b9e3 | 3,630,591 |
def edit_name(request, name, editable_authorities):
"""View to edit an existing Name object."""
# Much of the code here is a duplicate or close copy of the code
# in create_name.
number_name_part_forms = 2
number_name_note_forms = 1
name_part_forms = []
name_note_forms = []
assertion = n... | 075d6004f2415beaa5e09b529b9df6a0e77b7f89 | 3,630,592 |
import math
def create_convolutional_autoencoder_model_2d(input_image_size,
number_of_filters_per_layer=(32, 64, 128, 10),
convolution_kernel_size=(5, 5),
deconvolution_kernel_size... | 8bc7ad876f67591a81fb14299d6beb09c4e0cf65 | 3,630,593 |
from gdsfactory.pdk import GENERIC, get_active_pdk
from typing import Dict
from typing import Callable
import importlib
import warnings
def _from_yaml(
conf,
routing_strategy: Dict[str, Callable] = routing_strategy_factories,
label_instance_function: Callable = add_instance_label,
) -> Component:
"""R... | fd50e13c6082dd24ee263d4b84bc5afbe9dcd231 | 3,630,594 |
def to_volume(data):
"""Ensure that data is a numpy 3D array."""
assert isinstance(data, np.ndarray)
if data.ndim == 2:
data = data[np.newaxis,...]
elif data.ndim == 3:
pass
elif data.ndim == 4:
assert data.shape[0]==1
data = np.squeeze(data, axis=0)
else:
... | d816dc16a1bdd27437d8c907c2dd8b18902edd80 | 3,630,595 |
def search_down(*args):
"""
search_down(sflag) -> bool
Is the 'SEARCH_DOWN' bit set?
@param sflag (C++: int)
"""
return _ida_search.search_down(*args) | c931b2152e8d5cf803aea9b1228fbd38dc8acc20 | 3,630,596 |
def assign_number_to_top_categories(paths):
"""Assign numbers to the top categories
returned by split_path for consistency"""
cats = {}
def assign_number(path):
name = path[0][1]
n = cats.setdefault(name, len(cats) + 1)
return [(n, name)] + path[1:]
return map(assign_number,... | 0027986bd9097819b76ef9358f3fb0b491456b48 | 3,630,597 |
def instrument_parameters_odim5(radar, odim_file):
"""
Builds the dictionary 'instrument_parameters' in the radar instance,
using the parameter metadata in the input odim5 file.
Parameters
----------
radar : Radar
Py-ART radar structure
odim_file : str
Complete path and fil... | 185838c40a8d8f41dd16dcd92bdb9082396a772f | 3,630,598 |
def topodstostep_DecodeVertexError(*args):
"""
* Returns a new shape without undirect surfaces.
:param E:
:type E: TopoDSToStep_MakeVertexError
:rtype: Handle_TCollection_HAsciiString
"""
return _TopoDSToStep.topodstostep_DecodeVertexError(*args) | 6604b4f834d07ccb5ded4ebd8c573301e72b21ea | 3,630,599 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.