content stringlengths 35 762k | sha1 stringlengths 40 40 | id int64 0 3.66M |
|---|---|---|
import random
import multiprocessing
import concurrent
import tqdm
def solve_lineage_instance(
_target_nodes,
prior_probabilities=None,
method="hybrid",
threads=8,
hybrid_cell_cutoff=200,
hybrid_lca_cutoff=None,
time_limit=1800,
max_neighborhood_size=10000,
seed=None,
num_iter=... | 6babbb6c071a17f9a5bfe2fbe402d1cb72a6c330 | 33,523 |
def split_in_chunks(
data,
chunk_size,
train_size=None,
val_size=None,
test_size=None,
shuffle=True,
seed=None,
):
"""Split data into train-test, where chunks of data are held together
Assume `data` is a list of numpy arrays
"""
chunks = []
for rollout in data:
f... | fad3ebdc99731ad95ff0200e70e2e64d4a9acdc8 | 33,524 |
import re
def check_id(id):
"""
Check whether a id is valid
:param id: The id
:return: The result
"""
return bool(re.match(r"^[a-f0-9]{24}$", id)) | f336d34de12f4f5520d4c88a838ebdb396857d2b | 33,526 |
def totaled_tbr_no_lgtm(cc, sql_time_specification):
"""Counts the number of commits with a TBR that have not been lgtm'ed
in a given timeframe
Args:
cc(cursor)
sql_time_specification(str): a sql command to limit the dates of the
returned results
Return:
count(i... | 25666c4f741f6bdd2c8358468a54c6e261cc57e3 | 33,527 |
import unicodedata
def normalize_text(text: str) -> str:
"""Normalize the text to remove accents
and ensure all the characters are valid
ascii symbols.
Args:
text : Input text
Returns:
Output text
"""
nfkd_form = unicodedata.normalize("NFKD", text)
only_ascii = nfkd_f... | fa1c5362caa9946e79152f9e14ccf2131754f258 | 33,528 |
def rotate_y(x, z, cosangle, sinangle):
"""3D rotaion around *y* (roll). *x* and *z* are values or arrays.
Positive rotation is for positive *sinangle*. Returns *xNew, zNew*."""
return cosangle*x + sinangle*z, -sinangle*x + cosangle*z | 0a1b28548f771b9ca8cec29ba4060be7b0919182 | 33,529 |
import base64
import html
def json_file_upload(contents, file_names, dates):
"""
Reads a JSON file from disk and saves it in the default path
The goal is to keep that file over there for the Draw JSON
Function to read and draw it.
Args:
ontents, file_names, dates: inputs from the Dash UI... | 88d06880fb4e102260ef7df6f931ee541d8c98fc | 33,530 |
import getpass
def ask_credential(login=None, password=None):
""" Ask for a login and a password when not specified.
Parameters
----------
login: str, default None
a login.
password: str, defualt None
a password.
Returns
-------
login: str, default None
a logi... | 55ba7425cd2016212c897345c21b6d24ce3d8578 | 33,532 |
import numpy
def zeros_like(a, dtype=None, bohrium=None):
"""
Return an array of zeros with the same shape and type as a given array.
With default parameters, is equivalent to ``a.copy().fill(0)``.
Parameters
----------
a : array_like
The shape and data-type of `a` define these same ... | 6d831ead77b55229121f85d005a426e86565353a | 33,533 |
import random
def rand():
"""
Returns a random number.
"""
return random.random() | efad85c9f169d39358ed034a29f166df175d0ea7 | 33,534 |
def read_counters():
"""read_counters()
Get current counts and reset counters.
:rtype: list(int)
:raises PapiInvalidValueError: One or more of the arguments is invalid
(this error should not happen with PyPAPI).
:raises PapiSystemError: A system or C library call failed inside PAPI.
"... | d82c3b186aadc0b61e848a838549cf8393fa1010 | 33,535 |
def is_monotonic_decreasing(series_or_index):
"""
Return boolean scalar if values in the object are
monotonic_decreasing.
Returns
-------
Scalar
"""
return check_monotonic(series_or_index, decreasing=True, strict=False) | 3b5c2f989d53cc96fc6e9131cb2b3a78945befaa | 33,536 |
def mprint(m,fmt):
"""
This function will print a VSIPL matrix or vector suitable for pasting into Octave or Matlab.
usage: mprint(<vsip matrix/vector>, fmt)
fmt is a string corresponding to a simple fmt statement.
For instance '%6.5f' prints as 6 characters wide with 5 decimal dig... | 36b555720a8908f2552dbbec7f03c648e34f168a | 33,537 |
import requests
def fetch_reviews(app_id, page_num):
"""Fetch a single page of reviews for a given app_id.
:param app_id: The ID of the app in the app store.
:param page_num: The page of reviews to fetch.
:return: A list of Review objects.
"""
# page=1 is the same as if the "page" param was l... | 99b71a41ae7bc96e40d6d1798dd676c6a889f80b | 33,539 |
def graph_push_point(graph_id):
"""
Push points to graph
"""
request_data, error = parseHTTPRequest(request, ["value"])
if error:
response = jsonify({
"error": error
})
return response, 422
try:
# data = {"value":10, "date": datetime.datetime.... | cf6522e294887370a3f8ad76ff66e96fb9b79291 | 33,540 |
def or_operator():
"""|: Bitwise "or" operator."""
class _Operand:
def __or__(self, other):
return " ~or~ ".join(('east coast', other))
return _Operand() | 'dirty south' | 9ccfc124dd6c7aae8035b336788cc07cdff983d1 | 33,541 |
import tqdm
def computeAlignmentScores(vocabulary, sub_mat, gap_open, gap_extend):
"""
Pre-computes the alignment scores between all the k-mer pairs
Args:
vocabulary (list [str]): The list of all possible k-mers
sub_mat (dict[tuple[str,str],int]): Substitution matrix as represented in Bio.SubsMat.MatrixInfo.b... | 0b7aeb6b592586b827e19969a418146800805687 | 33,542 |
import re
def _get_version(basename):
"""Returns the _get_next_version of a file."""
match = re.search(r"\(\d*\)", basename)
if match:
v = int(match.group(0)
.replace('(', '')
.replace(')', ''))
return v
return 0 | 7340b74dca04ecb5520c03b046ec650c34527b4c | 33,544 |
def list_tags():
"""Show all the known tags."""
streets_with_tags = (
db.session.query(Street).filter(Street.tags != None).all() # noqa
)
all_tags = set()
for street in streets_with_tags:
all_tags.update(set(street.tags))
all_tags = sorted(list((all_tags)))
return render_t... | 737e65e7088357407c71eb19b9b3a4ddc948e26a | 33,545 |
def get_records(field_id):
"""Return TOP 10 records for selected field"""
if not request.is_xhr:
abort(403)
if field_id == 0:
field_id = session.get('current_field_id', 2)
field = Field.query.get(field_id)
records = field.records.limit(10)
top_10 = []
for record in records:... | c9fcf236ee765d2a09148367293ea882093ab001 | 33,546 |
def self_play_iterator_creator(hparams, num_workers, jobid):
"""create a self play iterator. There are iterators that will be created here.
A supervised training iterator used for supervised learning. A full text
iterator and structured iterator used for reinforcement learning self play.
Full text iterators fee... | 618179a8694a2df0edbd1401a6caf18e607b2652 | 33,547 |
def utf8_product_page():
"""
Single product page with utf8 content.
"""
with open('data/product_utf8.html') as f:
return ''.join(f) | 56a70e463cebdaef632ebd2997be4a523289da02 | 33,548 |
def detect_Nir2011(dat_orig, s_freq, time, opts):
"""Spindle detection based on Nir et al. 2011
Parameters
----------
dat_orig : ndarray (dtype='float')
vector with the data for one channel
s_freq : float
sampling frequency
time : ndarray (dtype='float')
vector with the ... | f4e4c1cd22944fd09121c0f43bb28a4dd3e7d629 | 33,549 |
def is_indel(variant):
"""Is variant an indel?
An indel event is simply one where the size of at least one of the alleles
is > 1.
Args:
variant: third_party.nucleus.protos.Variant.
Returns:
True if the alleles in variant indicate an insertion/deletion event
occurs at this site.
"""
# redact... | dc44642a011ac292c73a163b29bb1f3c4cb36624 | 33,550 |
import functools
def project_access_required(f):
"""Decorator function to verify the users access to the project."""
@functools.wraps(f)
def verify_project_access(current_user, project, *args, **kwargs):
"""Verifies that the user has been granted access to the project."""
if project["id"... | 4689e05ae330e360ca0e1ac221b571545608d5b4 | 33,551 |
def downloadRangesHelper(imageCount : int, downloadRange, downloadIndex):
"""Helper function for calculating download ranges and/or download index"""
# expected output should be [x,y], where x = zero-based image index start,
# and y = the amount of images in a post.
# check if downloadRange and downloa... | 2fa98a1111059d5c2f2126f19a8eccab9b23a596 | 33,552 |
import sqlite3
def removeProduct(product, connection=None):
"""
Remove a product tuple from the database.
Args:
products (str): The product to be removed from the database.
connection (sqlite3.Connection, optional): A connection to the database.
Returns:
bool: True if successful, f... | 131c013a4ee1569b91dd7f52b3c961877e4a9124 | 33,553 |
def health():
"""Return information about the health of the queue in a format that
can be turned into JSON.
"""
output = {'queue': {}, 'errors': {}}
output['queue']['all-jobs'] = Job.objects.all().count()
output['queue']['not-executed'] = Job.objects.filter(executed=None).count()
output['que... | f65ac55808d52ece96b6168137e78f8ad42c7d7f | 33,554 |
def build_confirmation_msg(message_template: str, variables_arr: [], record):
"""Returns the full confirmation email as a string
Note: some email services also support sending HTML for future purposes.
"""
inserts = []
for variable in variables_arr:
inserts.append(record['fields'][variable.strip()])
mes... | 6d84b19f2bcce3fab298fe7ece2a011b423f9e90 | 33,557 |
import re
def _get_freq_label_by_month(date_value: str) -> str:
"""Gets frequency label for the date value which is aggregated by month.
Args:
date_value (str): The date value.
Returns:
str: The date value aggregated by month.
"""
if bool(re.match(r"^\d{4}M\d{1,2}$", date_value))... | a789d993bf390fba42dc5451302f3fe89623cb3d | 33,558 |
import torch
def get_depth_metrics(pred, gt, mask=None):
"""
params:
pred: [N,1,H,W]. torch.Tensor
gt: [N,1,H,W]. torch.Tensor
"""
if mask is not None:
num = torch.sum(mask) # the number of non-zeros
pred = pred[mask]
gt = gt[mask]
else:
num = pred.nume... | 2d4e617bbbf3823ee60dbf1480aed624fd7ba57b | 33,559 |
def run_ica(raw, n_components, max_pca_components=100,
n_pca_components=64, noise_cov=None, random_state=None,
algorithm='parallel', fun='logcosh', fun_args=None,
verbose=None, picks=None, start=None, stop=None, start_find=None,
stop_find=None, ecg_ch=None, ecg_score_func... | 56b36d33211123839ed61f6cc19e7c7ee4c2e336 | 33,560 |
def remove_member(context, request):
"""Remove a member from the given group."""
# Currently, we only support removing the requesting user
if request.matchdict.get("userid") == "me":
userid = request.authenticated_userid
else:
raise HTTPBadRequest('Only the "me" user value is currently s... | 494ddb9e824911680c8c4f80dbc7d1c6aa6f12d2 | 33,561 |
def convert_length(length, original_unit="kilometers", final_unit="kilometers"):
"""
:param length: length to be converted
:param original_unit: original unit of the length
:param final_unit: return unit of the length
:return: the converted length
"""
if not isinstance(length, (float, int))... | e76dcaa050eaa1a77621c7062ca2a187238d0ea3 | 33,562 |
def get_value_larger(threshold, value, step, direction, size_x, size_y):
"""Function for looping until correct coordinate is found"""
matrix = [[0 for _ in range(size_x)] for _ in range(size_y)]
current_x = size_x / 2
current_y = size_y / 2
while value <= threshold:
for _ in range(0, 2):
... | 49db166798446e98ae23800eb1428ba3baf0a026 | 33,565 |
def get_daq_device_inventory(interface_type, number_of_devices=100):
# type: (InterfaceType, int) -> list[DaqDeviceDescriptor]
"""
Gets a list of :class:`DaqDeviceDescriptor` objects that can be used
as the :class:`DaqDevice` class parameter to create DaqDevice objects.
Args:
interface_type... | abee7adb4fa57471e09a480a971e35e5081a9837 | 33,566 |
def statement_passive_verb(stmt_type):
"""Return the passive / state verb form of a statement type.
Parameters
----------
stmt_type : str
The lower case string form of a statement type, for instance,
'phosphorylation'.
Returns
-------
str
The passive/state verb form... | 21a34fc7270d0c9f9d4c096930ed5bcb9f6af72b | 33,567 |
from typing import Iterable
def find_hpas(config: Config,) -> Iterable[client.models.v1_horizontal_pod_autoscaler.V1HorizontalPodAutoscaler]:
"""Find any HorizontalPodAutoscaler having klutch annotation."""
resp = client.AutoscalingV1Api().list_horizontal_pod_autoscaler_for_all_namespaces()
return filter(... | fcc34c83d7f50c25510eabfb6b60d6106fe97432 | 33,569 |
def bioacoustics_index (Sxx, fn, flim=(2000, 15000), R_compatible ='soundecology'):
"""
Compute the Bioacoustics Index from a spectrogram [1]_.
Parameters
----------
Sxx : ndarray of floats
matrix : Spectrogram
fn : vector
frequency vector
flim : tupple (fmin, fmax), ... | fcc557d1bbbe5d3c9758cb500cb8a98cd83510ce | 33,570 |
def ctm_to_dict(ctm_fn):
"""
Return a dictionary with a list of (start, dur, word) for each utterance.
"""
ctm_dict = {}
with open(ctm_fn, "r") as f:
for line in f:
utt, _, start, dur, word = line.strip().split(" ")
if not utt in ctm_dict:
ctm_dict[utt... | 7a0c58e544029fd118448b916c2c2966172c5d1b | 33,572 |
def qft_core(qubits, coef=1):
"""
Generates a quil programm that performs
quantum fourier transform on given qubits
without swaping qubits at the end.
:param qubits: A list of qubit indexes.
:param coeff: A modifier for the angle used in rotations (-1 for inverse
QFT, 1 f... | 79944c93ff2d3d5393d9f94e546d79b69334f005 | 33,573 |
def get_formatted_timestamp(app_type):
"""Different services required different date formats - return the proper format here"""
if app_type in {'duo', 'duo_admin', 'duo_auth'}:
return 1505316432
elif app_type in {'onelogin', 'onelogin_events'}:
return '2017-10-10T22:03:57Z'
elif app_type... | f5d4f2ac1d30383849b6149a46525e67439229df | 33,574 |
import array
def preprocess(x, copy=False, float=False, axis=None):
"""
Ensure that `x` is a properly formatted numpy array.
Proper formatting means at least one dimension, and may include
optional copying, reshaping and coersion into a floating point
datatype.
Parameters
----------
... | b1632ca64fe315330d26f9beeef6fa9df8a40382 | 33,576 |
def detect_defaults_settings(output):
""" try to deduce current machine values without any
constraints at all
"""
output.writeln("\nIt seems to be the first time you run conan", Color.BRIGHT_YELLOW)
output.writeln("Auto detecting your dev setup to initialize conan.conf", Color.BRIGHT_YELLOW)
re... | 86e15908c6219e3f0f5caefe8a0a858ce602e484 | 33,577 |
from .continent import COUNTRY_TO_CONTINENT
def compute_continent_histogram(docs: DocumentSet, **kwargs) -> pd.DataFrame:
""" Compute a histogram of number of documents by affiliation
continent.
"""
def extract(doc):
result = set()
for author in doc.authors or []:
for ... | 031617c337850eeada50046acdade4fb7ada4fef | 33,579 |
from typing import OrderedDict
def calc_prod(corpus_context, envs, strict = True, all_info = False, ordered_pair = None,
stop_check = None, call_back = None):
"""
Main function for calculating predictability of distribution for
two segments over specified environments in a corpus.
Param... | 4c104b235bb6970573c2ea659c81038e266c40d3 | 33,580 |
import tqdm
def read_run_dict(file_name):
"""Read a run file in the form of a dictionary where keys are query IDs.
:param file_name: run file name
:return:
"""
result = {}
with FileWrapper(file_name) as f:
for ln, line in enumerate(tqdm(f, desc='loading run (by line)', leave=False)):
... | 2aa7937e259481c86ddaf13d9f6af8e49efb087c | 33,581 |
def parse_address(address):
"""Convert host:port or port to address to pass to connect."""
if ':' not in address:
return ('', int(address))
host, port = address.rsplit(':', 1)
return (host, int(port)) | 06eb172974c4e75d33ae205f952e8533c88acfeb | 33,582 |
def secure_host_url(request, secure_url=None):
"""Overrides ``host_url`` to make sure the protocol is secure."""
# Test jig.
if secure_url is None:
secure_url = secure_request_url
return secure_url(request, 'host_url') | d4a0b43a52170d7ac07d2cc8141e789a0005c2fa | 33,584 |
def get_resource_mutator(cpu=None, memory=None, gpu=None, gpu_vendor='nvidia'):
"""The mutator for getting the resource setting for pod spec.
The useful example:
https://github.com/kubeflow/fairing/blob/master/examples/train_job_api/main.ipynb
:param cpu: Limits and requests for CPU resources (Default... | 02cc5069470d6b255c2c8cb1e8eb27f282b66911 | 33,586 |
def gram_matrix(features):
"""
Calculates the gram matrix of the feature representation matrix
:param features: The feature matrix that is used to calculate the gram matrix
:return: The gram matrix
"""
return K.dot(features, K.transpose(features)) | ebc8a354de903b764e7cc5a214c9d6bbcbe5a1f8 | 33,587 |
def lp_dominate(w, U):
"""
Computes the belief in which w improves U the most.
With LP in White & Clark
:param w: np.ndarray
:param U: list of np.ndarray
:return: b if d >= 0 else None
"""
# print("LP dominate")
if len(U) == 0:
return w
S = len(w)
d = cvx.Variable()
... | 26ff577b8ad7d97b2062d37299ca59c84897c404 | 33,588 |
from typing import Union
import torch
def get_random_subset_dataloader(dataset: Dataset, subset_size: Union[float, int], **dataloader_kwargs) -> DataLoader:
""" Returns a random subset dataloader sampling data from given dataset, without replacement.
Args:
- dataset: PyTorch dataset from which random ... | a6dc4e70d6676a6e348339c90ffa99dc76772e9a | 33,589 |
import numpy
def _combine_pfs(pfa, pfb, coeff, operator):
""" Obtain the pf information of the multiplication of pfa and pfb
"""
tempsa, logqa, dq_dta, d2q_dt2a = pfa
_, logqb, dq_dtb, d2q_dt2b = pfb
if operator == 'multiply':
logq = [a+b+numpy.log(coeff) for a, b in zip(logqa, logqb)]
... | f89ee97ab5e5de348f42e71d9ad5fa86ba15f922 | 33,590 |
def epa_nei_nonpoint_parse(*, df_list, source, year, config, **_):
"""
Combine, parse, and format the provided dataframes
:param df_list: list of dataframes to concat and format
:param source: source
:param year: year
:param config: dictionary, items in FBA method yaml
:return: df, parsed an... | 0a411cd7ce130adafcc8b3615a2c41998454e585 | 33,591 |
from typing import Union
from typing import List
from typing import Dict
import ray
def create_auto_config(
dataset: Union[str, pd.DataFrame, dd.core.DataFrame, DatasetInfo],
target: Union[str, List[str]],
time_limit_s: Union[int, float],
tune_for_memory: bool,
user_config: Dict = None,
) -> dict:... | 1bd76497b71ed7163af9bddf87e7ee346ed9ff4d | 33,592 |
import numpy
def create_orbit_from_particles(particles, angular_velocity=0.|units.yr**-1):
"""
Use mass, position and velocity to determine orbital parameters.
Then setup Roche_Orbit
"""
roche = Roche_Orbit()
roche.mass_1, roche.mass_2 = particles.mass
position_vector = particles.... | e9314b582e4031a4ca5816f7d0980430c325dc53 | 33,594 |
def bitter_rivals(voting_dict):
"""
Input: a dictionary mapping senator names to lists representing
their voting records
Output: a tuple containing the two senators who most strongly
disagree with one another.
Example:
>>> voting_dict = {'Klein': [-1,0,1], 'Fox-Epstein': ... | 154e067add7a8d5b58d1474530e690bdfb40a7ea | 33,595 |
from operator import and_
def last_contacts(ts_start):
"""Get the last time each timeseries datapoint was updated.
Args:
config: Configuration object
ts_start: Timestamp to start from
Returns:
data: List of dicts of last contact information
"""
# Initialize key variables... | 6e46d10f0ad7ab1523cd21255cf659d791f551c4 | 33,596 |
import torch
def train_one_epoch_loss_acc(net, train_iter, loss, updater):
"""训练模型一个迭代周期(定义见第3章)
Defined in :numref:`sec_softmax_scratch`
返回 train loss 和 train acc
"""
# 将模型设置为训练模式
if isinstance(net, torch.nn.Module):
net.train()
# 训练损失总和、训练准确度总和、样本数
metric = Accumulator(3)
... | 314fe27c20d690a3a09a02571a0e545aea73f845 | 33,598 |
def get_numeric_cache(hostname):
"""Get all the numeric cache entries we have for an hostname
"""
return [{
'collection': str(n.template.collection),
'template': str(n.template),
'value': n.value,
'last_modified': n.last_modified,
} for n in NumericCache.objects.filter(h... | 6adb7f3a17e6856ba9319e7cd10567e9cf820378 | 33,599 |
from typing import Sequence
from typing import Optional
import math
def partition_dataset(
data: Sequence,
ratios: Optional[Sequence[float]] = None,
num_partitions: Optional[int] = None,
shuffle: bool = False,
seed: int = 0,
drop_last: bool = False,
even_divisible: bool = False,
):
"""... | a8a306e72d256d511d0a8f9493dd46dcbf6c1d7e | 33,600 |
def canopy_PAR_absorbed(states: States, setpoints: Setpoints, weather: Weather):
"""The PAR absorbed by the canopy
Equation 8.26
:return: The PAR absorbed by the canopy [W m^-2]
"""
return canopy_PAR_absorbed_from_greenhouse_cover(states, setpoints, weather) + canopy_PAR_absorbed_from_greenhouse_flo... | 0ea8103d1087be3d283e4834ec7ec8b436357e28 | 33,601 |
def tiff_to_array(tiff):
"""
Open a TIFF file as an array, normalizing the dimensions.
:param tiff: Filename
:return:
"""
array = (
tiff.asarray(out='memmap') if tiff.pages[0].is_memmappable else tiff.asarray()
)
if array.ndim < 3:
array = array[np.newaxis, ...]
retu... | 157591e2f9980602fc9bca3f713fb512c696821b | 33,602 |
def version():
"""donghuangzhong version"""
return "0.0.1" | ad5d9834dddad46c2f4add31f46ea470bf370304 | 33,604 |
def list_dot(a, b):
"""
Returns the Euclidean inner product of two itterable data-structures.
"""
try:
if len(a) == len(b):
temp = 0
for i in range(len(a)):
temp += a[i]*b[i]
return(temp)
else:
raise ValueError("The length o... | 80dcdb22ed76a9cfe9750deb55971548efe4380e | 33,605 |
import struct
def pack_bytes(payload):
"""Optimally pack a byte string according to msgpack format"""
pl = len(payload)
if pl < (2**8):
prefix = struct.pack('BB', 0xC4, pl)
elif pl < (2**16):
prefix = struct.pack('>BH', 0xC5, pl)
else:
prefix = struct.pack('>BI', 0xC6, pl)
... | eaea52c44a766d74d0aa10e1da20e70f49b624f6 | 33,606 |
import torch
def disparity_consistency_src_to_tgt(meshgrid_homo, K_src_inv, disparity_src,
G_tgt_src, K_tgt, disparity_tgt):
"""
:param xyz_src_B3N: Bx3xN
:param G_tgt_src: Bx4x4
:param K_tgt: Bx3x3
:param disparity_tgt: Bx1xHxW
:return:
"""
B, _, ... | c407085bf10b0f7c67152d7d92f55a4984520766 | 33,607 |
import re
def split (properties):
""" Given a property-set of the form
v1/v2/...vN-1/<fN>vN/<fN+1>vN+1/...<fM>vM
Returns
v1 v2 ... vN-1 <fN>vN <fN+1>vN+1 ... <fM>vM
Note that vN...vM may contain slashes. This is resilient to the
substitution of backslashes for slashes, since Jam, unb... | 8b15697f6ae15b2fb634144987893ca04eabcccc | 33,608 |
def abort_behavior(token):
""" Abort behavior identified with the token """
return True, stop_nodenetrunner(behavior_token_map[token]) | faee270933a225ab376fef9b3ede589960e9c594 | 33,609 |
def limit_to_value_max(value_max, value):
"""
:param
1.(int) value_max -- value that should not be exceed
2.(int) value -- actual value
:return
1. return a value in the given range bound with value_max
"""
if value > value_ma... | a568bc1febe9a0cb6115efb4c95c0e1705787bfe | 33,610 |
def reference_col(
tablename, nullable=False, pk_name="id", foreign_key_kwargs=None, column_kwargs=None
):
"""Column that adds primary key foreign key reference.
Usage: ::
category_id = reference_col('category')
category = relationship('Category', backref='categories')
"""
foreign_... | 17da349907c2764b4d4a205a9a5a4e4ff9d02484 | 33,611 |
import numpy as np
def extract_municipality_hashtags(df):
""" This function takes a twitter dataframe as an input then the output is the dataframe with 2 new columns namely a hashtag
column and a municipality column.
Example
------
if the tweet contains the @mention '@CityPowerJhb' then the c... | 1c58e3154f57ad82a8129c5ed765a622b12b8d08 | 33,612 |
import math
def vertices_homography(vertices, H):
"""Apply projective transformation (homography) on a sequence of points.
Parameters:
vertices: List of (x, y) tuples.
A list for projective transformation.
H: A homography matrix.
Return:
vertices_homo: List of (... | ad0b1cd397d0b01a0f333d872b4f8a8d2e5f0736 | 33,613 |
def SRCNNv2(input_shape, depth_multiplier=1, multi_output=False):
"""
conv 9-64 puis 7-64 puis 5-32 puis 7-1 -> 1.006 120 epoch
conv 9-128 puis 7-64 puis 5-32 puis 7-16 puis 9-1 -> 1.007 130 epoch
@ multi_output : set to True
"""
inputs = Input(input_shape, name="inputs")
conv1 ... | 752d4e7da9f62a532db326c9eb68d91369a44dd9 | 33,614 |
import json
def parse_labels(string, bb_label_mapping, static_label):
"""Returns array of rectangles geometry and their labels
Arguments:
string {str} -- JSON string
bb_label_mapping {dict} -- Mapping from color to label
static_label {list} -- List of labels valid for the whole im... | 3a671abaac1faa326d0faa7e618249b5f17cd705 | 33,615 |
def spike_profile(*args, **kwargs):
""" Computes the spike-distance profile :math:`S(t)` of the given
spike trains. Returns the profile as a PieceWiseConstLin object. The
SPIKE-values are defined positive :math:`S(t)>=0`.
Valid call structures::
spike_profile(st1, st2) # returns the bi-variate ... | ffaff8b0e1e3f81dcbbf8cb0762224dc3850b2b3 | 33,616 |
import re
import pandas
def wig_to_dataframe(infile, step, format):
"""Read a wig file into a Pandas dataframe
infile(str): Path to file
Returns:
Dataframe
"""
fs = open(infile, 'r')
coverage_data = []
pos = 0
chr = ""
for line in fs.readlines():
try:
... | 07873b340b450ef3d0eb3d7715afb9b204a8277e | 33,617 |
from corehq.apps.users.models import CommCareUser
def get_all_commcare_users_by_domain(domain):
"""Returns all CommCareUsers by domain regardless of their active status"""
def get_ids():
for flag in ['active', 'inactive']:
key = [flag, domain, CommCareUser.__name__]
for user i... | 2b9209ac899b73eb534ba98cd5930bb0dc4749c2 | 33,618 |
def print_cycles_info(data):
"""
Print various information about cycles.
"""
n_cycles = len(data.cycles)
output('number of cycles:', n_cycles)
if not n_cycles:
return data
slengths = sorted(set(data.cycles_lengths))
lhist, lbins = np.histogram(data.cycles_lengths,
... | d22d827d966ff467de232818edd7854c20e12bb9 | 33,619 |
def get_block_size(sigma = 1.5):
"""
Devuelve el tamaño de los vecinos (block_size) que se va a utilizar para
obtener los puntos Harris. El valor se fija al valor correspondiente al uso
de máscaras gaussianas de sigma 1.5. El tamaño de la máscara Gaussiana es
6*1.5+1.
"""
return int(6*sigma... | 52f4aa88580252ab9c0f7a1840ac3097166c3930 | 33,620 |
from typing import Callable
from typing import Union
from typing import Tuple
import typing
def approxZeroNewton(f: Callable[[float], float], df: Callable[[float], float], ddf: Callable[[float], float], a: Union[int, float], b: Union[int, float], epsilon: float, iteration: int) -> Tuple[float, int]:
"""
Appro... | f15e37f581f2f040af8b2c7edcec11ebce75c93f | 33,622 |
def chain_data(symbol, info=None):
"""Gets chain data for stock. INSTANT. Includes possible expiration dates for options."""
assert type(symbol) == str
return robin_stocks.options.get_chains(symbol, info) | 04cdb028420fbabdd1a4951762a5a6fea24a821a | 33,623 |
def convert_Cf2manningn(Cf, h):
"""
Convert the friction coefficient Cf to the Manning's n
"""
n = h**(1 / 6) * np.sqrt(Cf / g)
return n | 6552425ed1deea8ea93b226e1cbd19df40d3e5af | 33,624 |
def lstmemory_unit(input,
name=None,
size=None,
param_attr=None,
act=None,
gate_act=None,
state_act=None,
mixed_bias_attr=None,
lstm_bias_attr=None,
... | 5e4ec7203b58d44b7b07c865ea7683994869dd90 | 33,625 |
def _GetPrivateIpv6GoogleAccess(dataproc, private_ipv6_google_access_type):
"""Get PrivateIpv6GoogleAccess enum value.
Converts private_ipv6_google_access_type argument value to
PrivateIpv6GoogleAccess API enum value.
Args:
dataproc: Dataproc API definition
private_ipv6_google_access_type: argument va... | 56c830257ce996716a6dea7d205dca00e06ab6a9 | 33,626 |
def retry_(f, ex, times=3, interval=1, on_error=lambda e, x: None, *args, **kwargs):
"""
Call a function and try again if it throws a specified exception.
:param funciton f: The function to retry
:param ex: The class of the exception to catch, or an iterable of classes
:type ex: class or iterable
... | e28d39dfee43c9c651b174f87acdd077920f3ed9 | 33,627 |
from sklearn.decomposition import PCA
from sklearn import linear_model
def pca_analysis(model, data):
"""Run PCA analysis on model to visualize hidden layer activity.
To get the values of the intermediate layer, a new model needs to be
created. This model takes the normal input from the RNN, and returns... | 00ec016e4c47cd15b2570457b835990ae9aef2e2 | 33,628 |
def get_plugin_history(name):
"""
Get history of results for single plugin
:param name: name of the plugin
:type name: string
"""
plugin = smokerd.pluginmgr.get_plugin(name)
results = []
for res in plugin.result:
res = standardized_api_list(res)
results.append({'result'... | 64225c04d13ee228c0a375c78ff805c0dcd56bb4 | 33,629 |
def _parse_instance_info(node):
"""Gets the instance and driver specific Node deployment info.
This method validates whether the 'instance_info' and 'driver_info'
property of the supplied node contains the required information for
this driver to deploy images to the node.
:param node: a single Nod... | 65e687704ad5fa70f8fc23eaf73f3c48eec9e17c | 33,630 |
def str2polynomial(string):
""" Get a string, return a polynomial """
try:
parts = advanced_split(string, '+', '-', contain=True)
terms = [str2term(each) for each in parts]
return Polynomial(*terms)
except:
raise Exception('Example input: -5x_1^2*y_1^3+6x_2^2*y_2^4-x_3^1*y_3^... | a52641bcbbc67159f5b73bbbc91ba84ea38cb223 | 33,632 |
def transpose_2d(array):
"""Transpose an array represented as an iterable of iterables."""
return list(map(list, zip_equal(*array))) | 48249de78d7d7c591f6d9fc8d79e184d3f291b49 | 33,633 |
def get_test_examples(args):
"""See base class."""
src = file2list(args.src_data)
trg = file2list(args.trg_data)
return _create_examples(src, trg, "test") | b1353a7b2bb87379c71c025f7abeb6142c55cf30 | 33,634 |
def precrec_unvoted(preds, gts, radius, pred_rphi=False, gt_rphi=False):
"""
The "unvoted" precision/recall, meaning that multiple predictions for the same ground-truth are NOT penalized.
- `preds` an iterable (scans) of iterables (per scan) containing predicted x/y or r/phi pairs.
- `gts` an iterable ... | eff8aef552999db2377c9d053c548a705f07bf3a | 33,636 |
def get_weapon_objects(json_load):
"""creates weapon objects by iterating over the json load
and making an object of each dictionary, then returns
a list of all the objects
"""
weapon_object_list = []
for weapon_dict in json_load:
# weapon_dict is a dictionary which has data for one weap... | e3b7309b4267ce4f237db3e7d6e17c69b187a1fc | 33,637 |
def _t_P(P):
"""Define the boundary between Region 2 and 3, T=f(P)
>>> "%.2f" % _t_P(16.52916425)
'623.15'
"""
n=[0, 0.34805185628969e3, -0.11671859879975e1, 0.10192970039326e-2,0.57254459862746e3, 0.1391883977870e2]
return n[4]+((P-n[5])/n[3])**0.5 | 196f4fae80d9425b0f3a06213c21f77d3049e401 | 33,638 |
import inspect
def add_as_function(cls):
""" Decorator for classes. Automatically adds functional interface for `call` method of class.
For example, `ConvBlock` class is transformed into `conv_block` function, while
`Conv1DTranspose` class is transformed into `conv1d_transpose` function.
"""
name... | 38f2e604e03e5a356450569bbfe7d0764bd784cb | 33,639 |
def remove_from_cart(request):
"""
Remove product from cart
"""
product_id = int(request.POST['product_id'])
# Checking if user session has cart or session may already flushed
# Cart an empty cart for user
if 'cart_id' in request.session:
cart_id = int(request.session['cart_id'])
... | 7a5fe35bce0d8ad7adb00c6b8a5677099c728c14 | 33,640 |
def preresnet164bn_svhn(classes=10, **kwargs):
"""
PreResNet-164(BN) model for SVHN from 'Identity Mappings in Deep Residual Networks,'
https://arxiv.org/abs/1603.05027.
Parameters:
----------
classes : int, default 10
Number of classification classes.
pretrained : bool, default Fal... | ebad863e846fd865772e93daf1225dd71654fc6a | 33,641 |
from typing import List
def value_map_distribution(value_map: dict, bounds: List[float] = None):
"""Percent of values that fall in ranges.
Args:
value_map: dict, value map
bound: list of float, boundaries to count values within
Returns:
dist: dict, distribution values... | 09988024007327ee26f27f43d9dc647e78a78915 | 33,643 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.