content stringlengths 35 762k | sha1 stringlengths 40 40 | id int64 0 3.66M |
|---|---|---|
def scale_values(tbl, columns):
"""Scale values in a dataframe using MinMax scaling.
:param tbl: Table
:param columns: iterable with names of columns to be scaled
:returns: Table with scaled columns
"""
new_tbl = tbl.copy()
for col in columns:
name = new_tbl.labels[col]
x_sc... | c2b6ff0414ab7930020844005e3bdf4783609589 | 33,059 |
def get_params_out_of_range(
params: list, lower_params: list, upper_params: list
) -> list:
"""
Check if any parameter specified by the user is out of the range that was defined
:param params: List of parameters read from the .inp file
:param lower_params: List of lower bounds provided by the user... | 67a8ca57a29da8b431ae26f863ff8ede58f41a34 | 33,062 |
import functools
def _filter_work_values(
works: np.ndarray,
max_value: float = 1e4,
max_n_devs: float = 100,
min_sample_size: int = 10,
) -> np.ndarray:
"""Remove pairs of works when either is determined to be an outlier.
Parameters
----------
works : ndarray
Array of records... | 93002df6f7bdaf0ffd639f37021a8e6844fee4bd | 33,063 |
def pf_from_ssig(ssig, ncounts):
"""Estimate pulsed fraction for a sinusoid from a given Z or PDS power.
See `a_from_ssig` and `pf_from_a` for more details
Examples
--------
>>> round(a_from_pf(pf_from_ssig(150, 30000)), 1)
0.1
"""
a = a_from_ssig(ssig, ncounts)
return pf_from_a(a) | 235b473f60420f38dd8c0ad19c64366f85c8ac4c | 33,064 |
def get_aic(mse: float, n: int, p: int):
"""
Calcuate AIC score.
Parameters
----------
mse: float
Mean-squared error.
n: int
Number of observations.
p: int
Number of parameters
Returns
-------
float
AIC value.
"""
return n * log(mse) + 2 ... | 033cb5ea7e9d06a2f630d3eb2718630904e4209f | 33,065 |
def triangle(a, b):
""" Return triangle function:
^ .
| / \
|____/___\____
a b
"""
return partial(primitives.tri, a, b) | f28bbe0bacb260fb2fb30b9811b1d5d6e5b99750 | 33,066 |
import pickle
def get_max_trans_date() -> date:
"""Return the date of the last transaction in the database"""
return pickle.load(open(conf("etl_accts"), "rb"))[1] | 61db89cfbbdc9f7e2b86930f50db75dcc213205c | 33,067 |
def build_argparser():
"""
Parse command line arguments.
:return: command line arguments
"""
parser = ArgumentParser()
parser.add_argument("-m", "--model", required=True, type=str,
help="Path to an xml file with a trained model.")
parser.add_argument("-i", "--input",... | 65c6e45e30b67ff879dbcf1a64cd8321192adfcf | 33,068 |
from pathlib import Path
def read_file(in_file: str):
"""Read input file."""
file_path = Path(in_file)
data = []
count = 0
with open(file_path) as fp:
for line in fp:
data.append(line)
count = count + 1
return ''.join(data), count | 4fbae8f1af7800cb5f89784a0230680a1d6b139a | 33,069 |
def limit(value, limits):
"""
:param <float> value: value to limit
:param <list>/<tuple> limits: (min, max) limits to which restrict the value
:return <float>: value from within limits, if input value readily fits into the limits its left unchanged. If value exceeds limit on either boundary its set to t... | 55fb603edb478a26b238d7c90084e9c17c3113b8 | 33,071 |
def _cdp_no_split_worker(work_queue, counts_by_ref, seq_1, seq_2, nt):
"""
Worker process - get refseq from work queue, aligns reads from seq_1 and seq_2,
and adds as (x,y) coords to counts_by_ref if there are alignments.
:param work_queue: joinable queue with refseq header and seq tuples (JoinableQueue... | 498e9da9c9f30adc1fa2564590cc7a99cbed9b94 | 33,072 |
def createIQSatelliteChannel(satellite_id):
"""Factory
This method creates a satellite channel object that exchanges IQ data in between both ends.
"""
return SatelliteChannel(satellite_id, stellarstation_pb2.Framing.Value('IQ')) | e1fc08de59692ab308716abc8d137d0ab90336bc | 33,073 |
def scaled_herding_forward_pass(weights, scales, input_data, n_steps):
"""
Do a forward pass with scaled units.
:param weights: A length:L list of weight matrices
:param scales: A length:L+1 list of scale vectors
:param input_data: An (n_samples, n_dims) array of input data
:param n_steps: Numbe... | e5af2c099b1296bdc1f584acaa6ce8f832fb29f6 | 33,074 |
from io import StringIO
def open_remote_factory(mocker):
"""Fixture providing open_remote function for ReferenceLoader construction."""
return mocker.Mock(return_value=StringIO(REMOTE_CONTENT)) | b3df151b021cfd3a07c5737b50d8856d3dc0a599 | 33,075 |
def get_displacement_bcs(domain, macro_strain):
"""Get the shift and fixed BCs.
The shift BC has the the right top and bottom points in x, y and z
fixed or displaced.
The fixed BC has the left top and bottom points in x, y and z
fixed.
Args:
domain: an Sfepy domain
macro_strain: t... | 02090e4d64f75b671597c4b916faf086c5bfe096 | 33,076 |
def public_rest_url(path_url: str = "",
domain: str = CONSTANTS.DEFAULT_DOMAIN,
only_hostname: bool = False,
domain_api_version: str = None,
endpoint_api_version: str = None) -> str:
"""
Creates a full URL for provided public REST e... | 3c99f5a388c33d5c7aa1e018d2d38c7cbe82b112 | 33,077 |
import torch
def get_dir_cos(dist_vec):
""" Calculates directional cosines from distance vectors.
Calculate directional cosines with respect to the standard cartesian
axes and avoid division by zero
Args:
dist_vec: distance vector between particles
Returns: dir_cos, array of directional co... | f325ca5535eaf9083082b147ff90f727214031ec | 33,078 |
def lambda_handler(event, context):
"""
Entry point for the Get All Lambda function.
"""
handler_request.log_event(event)
# Get gk_user_id from requestContext
player_id = handler_request.get_player_id(event)
if player_id is None:
return handler_response.return_response(401, 'Unautho... | 2cc1aeb6a451feb41cbf7a121c67ddfbd06e686f | 33,079 |
def reverse_complement_dna(seq):
"""
Reverse complement of a DNA sequence
Parameters
----------
seq : str
Returns str
"""
return complement_dna(seq)[::-1] | 680cf032c0a96fc254928bfa58eb25bee56e44dc | 33,080 |
def Wizard():
"""
Creates a wizardcharacter
:returns: fully initialised wizard
:rtype: Character
"""
character = (CharacterBuilder()
.with_hit_points(5)
.with_max_hp(5)
.with_spirit(20)
.with_max_spirit(20)
.wi... | 23019f41ba6bf51e049ffe16831a725dd3c20aa2 | 33,081 |
def tournament_communication(comm,
comm_fn=lambda x,y: None,
comm_kw={}):
"""
This is useful for the development of parallelized O(N) duplicate check
functions. The problem with such functions is that the operation of
checking if a set of param... | 03827a02f3df099aa3eead3d8214f0f2f90e60b1 | 33,082 |
def create_permutation_feature(number, rate_pert=1., name=None):
"""Create permutation for features."""
n = np.random.randint(0, 100000)
if name is None:
name = f_stringer_pert_rate(rate_pert)
lista_permuts = []
for i in range(number):
lista_permuts.append((name, PartialPermutationP... | 8c6931e2e2b1dcd9313fda5d8be63bfb0c549f5f | 33,083 |
import random
def DiceRoll():
"""A function to simulate rolling of one or more dice."""
def Roll():
return random.randint(1,6)
print("\nRoll Dice: Simulates rolling of one or more dice.")
num = 1
try: num = int(input("\nEnter the number of dice you wish to roll: "))
except: print... | 90e9587473fb06541ec9daa2ec223759940a5ecb | 33,084 |
def rook_move(self, game, src):
""" Validates rook move """
x = src[0]
y = src[1]
result = []
loop_condition = (lambda i: i < 8) if self.color == 'white' else (lambda i: i >= 0)
reverse_loop_condition = (lambda i: i < 8) if self.color == 'black' else (lambda i: i >= 0)
counter_eval = +1 if ... | 76a782541c565d14a84c1845841338d99f23704d | 33,085 |
def figure_5a():
"""
This creates the plot for figure 5A in the Montague paper. Figure 5A is
a 'plot of ∂(t) over time for three trials during training (1, 30, and 50).'
"""
# Create Processing Components
sample_mechanism = pnl.TransferMechanism(default_variable=np.zeros(60),
... | a8764f75cd9fc7cf0e0a9ddadc452ffdf05f099e | 33,086 |
import json
def lambda_handler(event, context):
""" Transforms a binary payload by invoking "decode_{event.type}" function
Parameters
----------
DeviceId : str
Device Id
ApplicationId : int
LoRaWAN Application Id / Port number
PayloadData : str
... | d645454656d85589652942b944e84863cb22a425 | 33,088 |
def _get_adi_snrs(psf, angle_list, fwhm, plsc, flux_dist_theta_all,
wavelengths=None, mode='median', ncomp=2):
""" Get the mean S/N (at 3 equidistant positions) for a given flux and
distance, on a median subtracted frame.
"""
snrs = []
theta = flux_dist_theta_all[2]
flux = flux... | 3d00ccb6163962dbfdcedda7aa565dfc549e1f2b | 33,089 |
def compute_nearest_neighbors(fit_embeddings_matrix, query_embeddings_matrix,
n_neighbors, metric='cosine'):
"""Compute nearest neighbors.
Args:
fit_embeddings_matrix: NxD matrix
"""
fit_eq_query = False
if ((fit_embeddings_matrix.shape == query_embeddings_matri... | 1020827cbaab50d591b3741d301ebe88c4ac6d93 | 33,090 |
import re
def commodify_cdli_no( cdli_no ):
"""
Given a CDLI number, fetch the text of the corresponding
artifact from the database and pass it to commodify_text
"""
# Ensure that we have a valid artifact number:
if re.match(r'P[0-9]{6}', cdli_no) is not None:
art_no = int(cdli_no[1:])... | 5c194f40cbde371329671712d648019ac2e43a90 | 33,091 |
def zvalues(r, N=1):
"""
Generate random pairs for the CDF a normal distribution.
The z-values are from the cumulative distribution function of the
normal distribution.
Args:
r: radius of the CDF
N: number of pairs to generate
Returns:
pairs of random numbers
"""
... | 146d363d7fbb92a9152c6b05a8f38562d4cfc107 | 33,093 |
def exp(fdatagrid):
"""Perform a element wise exponential operation.
Args:
fdatagrid (FDataGrid): Object to whose elements the exponential
operation is going to be applied.
Returns:
FDataGrid: Object whose elements are the result of exponentiating
the elements of th... | aef02937bf0fac701e0ae2bac75911a5a2a8ee9e | 33,094 |
def ksvm(param, data):
""" kernelized SVM """
certif = np.linalg.eigvalsh(data['K'])[0]
if certif < 0:
data['K'] = data['K'] - 2 * certif * np.eye(data['K'].shape[0])
optimal = {}
if len(param['kappa']) > 1 or float('inf') not in param['kappa']:
optimal.update(dist_rob_ksvm(param, da... | e549411b0ac12926753e2eefa968e978414829fa | 33,095 |
def _ordered_unique(arr):
"""
Get the unique elements of an array while preserving order.
"""
arr = np.asarray(arr)
_, idx = np.unique(arr, return_index=True)
return arr[np.sort(idx)] | c4e2578a41d7481b602c4251890276dc2a92dbe9 | 33,096 |
def is_byte_array(value, count):
"""Returns whether the given value is the Python equivalent of a
byte array."""
return isinstance(value, tuple) and len(value) == count and all(map(lambda x: x >= 0 and x <= 255, value)) | 16793415885ea637aecbeeefe24162d6efe9eb39 | 33,097 |
def _FilterSubstructureMatchByAtomMapNumbers(Mol, PatternMol, AtomIndices, AtomMapIndices):
"""Filter substructure match atom indices by atom map indices corresponding to
atom map numbers.
"""
if AtomMapIndices is None:
return list(AtomIndices)
... | 3594a11452848c9ae11f770fa560fe29d68aa418 | 33,098 |
def questions_for_written_answer_tabled_in_range(start, end):
"""Returns a list of all Questions for Written Answer tabled in date range.
"""
try:
_start = start.isoformat()
except AttributeError:
return []
try:
_end = end.isoformat()
except AttributeError:
return... | 5702005be754bb7485fb81e49ff9aab6fbc1d549 | 33,099 |
def get_headers_token(security_scopes: SecurityScopes, encoded: str = Depends(get_reusable_oauth2())) -> Token:
"""
This FastAPI dependency *will not* result in an argument added to the OpenAPI spec.
This should generally be used for dependencies involving the access token.
"""
return get_validated... | f7c9794fcd4b95f1e541b98203bfbe4fb1a6ec60 | 33,100 |
def worker_mode(self):
"""
bool: Whether or not all MPI ranks are in worker mode, in which all
worker ranks are listening for calls from the controller rank. If
*True*, all workers are continuously listening for calls made with
:meth:`~_make_call` until set to *False*.
By default, this is *False... | 45d256e47bfeffe9e3878297c6009061801e5d8d | 33,101 |
def _pcolor(text, color, indent=0):
""" Colorized print to standard output """
esc_dict = {
'black':30, 'red':31, 'green':32, 'yellow':33, 'blue':34, 'magenta':35,
'cyan':36, 'white':37, 'none':-1
}
if esc_dict[color] != -1:
return (
'\033[{color_code}m{indent}{text}\... | b156f86b2c73c00b44b8b5fd968499549bc79389 | 33,102 |
def naninterp(X, method='linear'):
"""
---------------------------------------------------------------------
fill 'gaps' in data (marked by NaN) by interpolating
---------------------------------------------------------------------
"""
inan = np.argwhere(np.isnan(X))
if inan.size == 0:
... | 33b95a879ead6ce93fa7cf4826c05c8086194c5f | 33,103 |
def to_op_list(elements: list) -> OperatorList:
"""elements should be a properly written reverse polish notation expression to be made into OperatorLists"""
if len(elements) == 0:
raise InvalidExpressionError()
new_elements = []
for e in elements:
if isinstance(e, Element):
n... | d849d840c4c391559dd85c5135909bc3381ed9cc | 33,104 |
def future(fn):
"""Mark a test as expected to unconditionally fail.
Takes no arguments, omit parens when using as a decorator.
"""
fn_name = fn.__name__
def decorated(*args, **kw):
try:
fn(*args, **kw)
except Exception, ex:
print ("Future test '%s' failed as ... | ae7b5fed9aea4546dcc07fa89a1d37dac89c0a94 | 33,105 |
def prodXTXv(v):
"""
Fast computation function for the product between a vector v, the matrix X and the transpose of the matrix X,
where X is the triangular matrix with only one below the diagonal.
:parameters:
- v : (array-like) the vector v
:return:
- res : the result of the mat... | 0e7526df922518278791c6c67c7233d2f53ca6c8 | 33,106 |
def input_fn(mode, batch_size, data_dir):
"""Input_fn using the contrib.data input pipeline for CIFAR-10 dataset.
Args:
mode: Standard names for model modes (tf.estimators.ModeKeys).
batch_size: The number of samples per batch of input requested.
"""
dataset = record_dataset(filenames(mode, data_di... | 4e59ed0e8a7ff1151a93a457b68cb99d3a47124b | 33,107 |
from typing import Any
from typing import Set
import inspect
from unittest.mock import Mock
def _get_default_arguments(obj: Any) -> Set[str]:
"""Get the names of the default arguments on an object
The default arguments are determined by comparing the object to one constructed
from the object's class's in... | 483fe82dd79aadfe1da387fb0c602beb503f344b | 33,108 |
from typing import Union
from typing import Optional
import logging
def execute_query(
connection: mysql.connector.connection_cext.CMySQLConnection,
sql_query: str,
data: Union[dict, tuple],
commit=True,
) -> Optional[int]:
"""
Execute and commit MySQL query
Parameters
----------
... | 7c7fbeb7880d2b4efd758387af860dc6af05bbfd | 33,109 |
def rpn_targets(anchors, bbox_gt, config):
"""Build the targets for training the RPN
Arguments
---------
anchors: [N, 4]
All potential anchors in the image
bbox_gt: [M, 4]
Ground truth bounding boxes
config: Config
Instance of the Config class that stores the parameters
... | 3775c2c3222911377a85ddaae802a625a181a9d9 | 33,110 |
from datetime import datetime
def add_years(d, years):
"""Return a date that's `years` years after the date (or datetime).
Return the same calendar date (month and day) in the destination year,
if it exists, otherwise use the following day
(thus changing February 29 to February 28).
"""
try:
... | 325085694b92f39e3ed8d22f690b5b520cdcbe5f | 33,111 |
def adj_to_knn(adj, n_neighbors):
"""convert the adjacency matrix of a nearest neighbor graph to the indices
and weights for a knn graph.
Arguments
---------
adj: matrix (`.X`, dtype `float32`)
Adjacency matrix (n x n) of the nearest neighbor graph.
n_neighbors: 'int' (o... | baed2ea35131705bf99fe01f5ffd6924eb689f32 | 33,112 |
def typeck(banana_file):
"""
Type-check the provided BananaFile instance.
If it type check, it returns the associated TypeTable.
:type banana_file: ast.BananaFile
:param banana_file: The file to typecheck.
:rtype: typetbl.TypeTable
:return: Returns the TypeTable for this BananaFile
"""
... | 71516db1fcb34666b35f2f62736e585d46766c5c | 33,113 |
import aiohttp
import async_timeout
async def authenticate(
session: aiohttp.ClientSession, username: str, password: str
) -> str:
"""Authenticate and return a token."""
with async_timeout.timeout(10):
resp = await session.request(
"post",
BASE_URL + "authenticate",
... | 5728503c49e2173f872eda7fbd5152f67f50d6c2 | 33,115 |
async def create_individual_sensors(
hass: HomeAssistantType, sensor_config: dict
) -> list[SensorEntity]:
"""Create entities (power, energy, utility_meters) which track the appliance."""
source_entity = await create_source_entity(sensor_config[CONF_ENTITY_ID], hass)
try:
power_sensor = await ... | 3112b85721fe4692ddec3f15c13ae9e5192dfb55 | 33,116 |
def collatz(number):
"""If number is even (number // 2) else (3 * number + 1)
Args:
number (int): number to collatz
Returns:
int: collatz number
"""
if (number % 2) == 0:
print(number // 2)
return number // 2
print(3 * number + 1)
return 3 * number + 1 | 221fd238bd6d0c40c9cb80be2c58746bb206c17b | 33,117 |
def maximum_clique(adjacency):
"""Maximum clique of an adjacency matrix.
Parameters
----------
adjacency : (M, M) array
Adjacency matrix.
Returns
-------
maximum_clique : list with length = size of maximum clique
Row indices of maximum clique coordinates. Set to False if no... | a8cf5cb67b74f334ea632263f68127b35f8e7816 | 33,118 |
def get_disk_at(board, position):
"""
Return the disk at the given position on the given board.
- None is returned if there is no disk at the given position.
- The function also returns None if no disk can be obtained from the given
board at the given position. This is for instance... | 4b793ce1947b2f71d666b1d1676ca894f43c3b58 | 33,119 |
def incr_key_store(key, amount=1):
"""
increments value of key in store with amount
:param key: key of the data
:param amount: amount to add
:return: new value
"""
if get_use_redis():
return rds.incr(str(key), amount)
else:
if exists_key_store(key):
value = g... | b31d024952c133863f38a6504d4c39e92493f27a | 33,120 |
def firstUniqChar(s):
"""
:type s: str
:rtype: int
"""
if len(s) == 0:
return -1
if len(s) == 1:
return 0
hash_table = {}
for i in s:
if i not in hash_table:
hash_table[i] = 1
else:
hash_table[i] += 1
for i in s:
if hash... | 25148de95099094991339bb0fe6815644e5b94cb | 33,121 |
def sum_of_powers_of_transition_matrix(adj, pow):
"""Computes \sum_{r=1}^{pow) (D^{-1}A)^r.
Parameters
-----
adj: sp.csr_matrix, shape [n_nodes, n_nodes]
Adjacency matrix of the graph
pow: int
Power exponent
Returns
----
sp.csr_matrix
Sum of powers of the transi... | 6b20b6cf8f9bba2d04672a04401f265f751cd5f0 | 33,122 |
from typing import Optional
from typing import Union
from typing import Callable
def get_current_sites(
brand_id: Optional[BrandID] = None, *, include_brands: bool = False
) -> set[Union[Site, SiteWithBrand]]:
"""Return all "current" (i.e. enabled and not archived) sites."""
query = db.session.query(DbSit... | 7bddf17bc2d2b3b5854f6c2bf47089bbac930d0a | 33,123 |
def get_text_editor_for_attr(traits_ui, attr):
""" Grab the Qt QLineEdit for attr off the UI and return its text.
"""
widget = get_widget_for_attr(traits_ui, attr)
return widget.text() | 6691fe0ddc13b379b1edcc5494e6378317df3bdc | 33,124 |
def check_coords(lat, lng):
""" Accepts a list of lat/lng tuples.
returns the list of tuples that are within the bounding box for the US.
NB. THESE ARE NOT NECESSARILY WITHIN THE US BORDERS!
"""
if bottom <= lat <= top and left <= lng <= right:
inside_box = 1
else:
inside... | e9b1678b2d736dbae9c2524df08bc59a3fe1912f | 33,125 |
async def confirm_email(body: ConfirmTokenModel, include_in_schema=False):
"""Mark a user's email as confirmed"""
email = verify_access_token(body.token)
if not email:
logger.info("Error getting email")
return JSONResponse(
status_code=status.HTTP_401_UNAUTHORIZED,
c... | 428ce5b9ed1e23bde91d57f16e5a18f9add3da83 | 33,126 |
def create_config_hyperparameter_search(dataset_name):
"""
Create the config file for the hyper-parameter tuning given a dataset.
"""
hidden_layer_size = [16, 32, 64]
n_hidden_layers = [2, 3, 4]
learning_rate = [0.005, 0.01, 0.02, 0.05]
lr_decay = [0.99, 0.995, 0.999, 1.0]
pytorch_init_... | d8635f42bf66e782c11dd9bc310b2c1ae30deff2 | 33,127 |
def get_genome_set(gids=[], def_name=None):
"""Wrapper for Genome object creation, checks if cache (created through unique option set) exists first and returns that.
returns dict: key = genome_id, value = Genome() object
see: help(Genome)
"""
if not gids:
sys.stderr.write("No ids inputt... | ea3cc9f5094b5ac21c760c3f2dfa2f0072c3ead4 | 33,128 |
def sample_tag(user: User, name: str = "Main course") -> Tag:
"""Create and return a sample name"""
return Tag.objects.create(user=user, name=name) | d0181ae04479661bde1ed4d72c6e871de95a016a | 33,129 |
def trustworthiness(X, X_embedded, n_neighbors=5, precomputed=False):
"""Expresses to what extent the local structure is retained.
The trustworthiness is within [0, 1]. It is defined as
Returns
-------
trustworthiness : float
Trustworthiness of the low-dimensional embedding.
"""
if ... | d5db0a3c8b3ecbdb3375171a9601320bd6628020 | 33,131 |
def compute_logomaker_df(adata, indices, fixed_length: int = None):
"""
The sample names (adata.obs_names) must be strings made of amino acid characters.
The list of allowed characters is stored in the variable aminoacids.
"""
if fixed_length is None:
pos_list = np.arange(max([len(adata.obs_... | 760715143605bb9cc1b632978a10d8bd2d56bd66 | 33,132 |
from typing import Optional
from typing import Tuple
import re
def parse_test_stats_from_output(output: str, fail_type: Optional[str]) -> Tuple[int, int]:
"""Parse tasks output and determine test counts.
Return tuple (number of tests, number of test failures). Default
to the entire task representing a si... | 8ec67d226c2280eb08de3589cba7b6aa0a09024c | 33,133 |
from typing import List
from typing import Tuple
from typing import Dict
def _constraint_items_missing_from_collection(
constraints: List[Tuple], collection: Dict[str, int]
) -> List[str]:
"""
Determine the constrained items that are not specified
in the collection.
"""
constrained_items = se... | 918667f1e8b001637c9adf00ef5323b2e8587775 | 33,134 |
import scipy
def coldpool_edge_shear_direction_split(
tv0100,
ds_profile,
l_smoothing=L_SMOOTHING_DEFUALT,
l_edge=L_EDGE_DEFAULT,
d_theta_v=COLDPOOL_THRESHOLD_DEFAULT,
shear_calc_z_max=SHEAR_DIRECTION_Z_MAX_DEFAULT,
profile_time_tolerance=60.0,
):
"""
Computes a mask for the edge o... | 9a8f97005c1ed638828a9a9ae00ffbbf516606c3 | 33,135 |
import json
def store_audio_tracks():
"""
Store the audio tracks of an event identified after probing the first HLS video segment.
Body:
.. code-block:: python
{
"Name": string,
"Program": string,
"AudioTracks": list
}
Returns:
None
... | 4310bd8bfa7e65b4be113bfac93db74957b4e822 | 33,136 |
import operator
def isqrt(n):
"""
Return the integer part of the square root of the input.
(math.isqrt from Python 3.8)
"""
n = operator.index(n)
if n < 0:
raise ValueError("isqrt() argument must be nonnegative")
if n == 0:
return 0
c = (n.bit_length() - 1) // 2
a =... | b841bc3907c15677ddc97a5c5366b1a0312d12b6 | 33,137 |
import csv
def main(file_in, file_out):
"""
Read in lines, flatten list of lines to list of words,
sort and tally words, write out tallies.
"""
with open(file_in, 'r') as f_in:
word_lists = [line.split() for line in f_in]
# Flatten the list
# http://stackoverflow.com/questions/95... | 225dd5d5b4c2bcb158ee61aa859f78e1e608a5fe | 33,138 |
def check_api_key(current_request):
"""
Check if an API Key for GitHub was provided and
return a 403 if no x-api-key header was sent by the client.
"""
x_api_key = current_request.headers.get('x-api-key', False)
if not x_api_key:
return Response(
body='Missing x-api-key heade... | cb0b76e8b76135fe4498fdc66f34b1f5184441d1 | 33,139 |
def read_mm_stamp(fh, byteorder, dtype, count):
"""Read MM_STAMP tag from file and return as numpy.array."""
return numpy_fromfile(fh, byteorder+'8f8', 1)[0] | f575243ecfa67160bdbd90a476fd9fd3c6b0bed8 | 33,140 |
def Qfromq(q):
""" converts five-element set q of unique Q-tensor elements to the full 3x3 Q-tensor matrix """
return np.array( [ [ q[0], q[1], q[2] ],
[ q[1], q[3], q[4] ],
[ q[2], q[4], -q[0] - q[3] ] ] ) | cebc58a8023588fffd0a504e8894cd2c075cde3a | 33,141 |
def load_atomic(val):
"""
Load a std::atomic<T>'s value.
"""
valty = val.type.template_argument(0)
# XXX This assumes std::atomic<T> has the same layout as a raw T.
return val.address.reinterpret_cast(valty.pointer()).dereference() | 307bcc9d3eae2eede6a8e2275104280a1e7b4b94 | 33,142 |
def sample_trunc_beta(a, b, lower, upper):
"""
Samples from a truncated beta distribution in log space
Parameters
----------
a, b: float
Canonical parameters of the beta distribution
lower, upper: float
Lower and upper truncations of the beta distribution
Returns
------... | 40380436b82c4f5f169e21443aabbe2d30ccf84a | 33,143 |
import torch
def reduce_dict(input_dict, average=True):
# ref: https://github.com/pytorch/vision/blob/3711754a508e429d0049df3c4a410c4cde08e4e6/references/detection/utils.py#L118
"""
Args:
input_dict (dict): all the values will be reduced
average (bool): whether to do average or sum
Red... | 877919878977df23fae0cecddb9042762394d083 | 33,144 |
def dataId_to_dict(dataId):
""" Parse an LSST dataId to a dictionary.
Args:
dataId (dataId): The LSST dataId object.
Returns:
dict: The dictionary version of the dataId.
"""
return dataId.to_simple().dict()["dataId"] | 77b7566492b80a8c6e2becacafff36737c8a7256 | 33,145 |
def norm_max(tab):
"""
Short Summary
-------------
Normalize an array or a list by the maximum.
Parameters
----------
`tab` : {numpy.array}, {list}
input array or list.
Returns
-------
`tab_norm` : {numpy.array}, {list}
Normalized array.
"""
tab_norm = t... | 657f6ed358e81c6635e967d5b995663c05145c57 | 33,146 |
def getHoliday(holidayName):
"""Returns a specific holiday.
Args:
holidayName (str): The name of the holiday to return.
Case-sensitive.
Returns:
HolidayModel: The holiday, as a HolidayModel object, or None if
not found.
"""
print(holidayName)
return None | 15b67fd6ac607d1ff12a216cc3c4baab61305be6 | 33,147 |
def draw_object(obj, bb: "BBLike" = None, ax=None):
"""
Draw easymunk object using matplotlib.
"""
options = DrawOptions(ax or plt.gca(), bb=bb)
options.draw_object(obj)
return ax | 3b7322d12290d22be6eb47ac74d30494a1c091de | 33,148 |
import six
import hashlib
def hash_mod(text, divisor):
"""
returns the module of dividing text md5 hash over given divisor
"""
if isinstance(text, six.text_type):
text = text.encode('utf8')
md5 = hashlib.md5()
md5.update(text)
digest = md5.hexdigest()
return int(digest, 16) % d... | 3f127837bb072df5ee609b3afa80dd04e4f7b794 | 33,149 |
import re
def normalize_mac_address_table(input_string):
"""
:param input_string: cli string has been get from network device by command like "show mac-address table"
:return: {(mac_address', 'vlan'): 'l2_interface'}
"""
res = {}
same_local_mac_address_count: int = 0
mac_address_number: ... | f4c010d440e6e3ea89dd35c967019096fb2269ef | 33,150 |
def _get_exploration_memcache_key(exploration_id):
"""Returns a memcache key for an exploration."""
return 'exploration:%s' % exploration_id | 1400607cc86f84c242201c9c9fe36a7a06cd2357 | 33,151 |
from typing import Optional
from typing import Tuple
def corr_filter(
corrs: np.ndarray,
value_range: Optional[Tuple[float, float]] = None,
k: Optional[int] = None,
) -> Tuple[np.ndarray, np.ndarray]:
"""
Filter correlation values by k and value_range
"""
assert (value_range is None) or (... | bbf84b19edb39ac2b787517ad1e9817bf2a042f5 | 33,152 |
import re
def isValid(text):
"""
Returns True if the input is related to jokes/humor.
Arguments:
text -- user-input, typically transcribed speech
"""
return bool(re.search(r'WATCH|OUT', text, re.IGNORECASE)) | 7d94e30bf9e0da267bd4ccab1ce823aaa315eba2 | 33,153 |
def pairs_from_array(a):
"""
Given an array of strings, create a list of pairs of elements from the array
Creates all possible combinations without symmetry (given pair [a,b], it does not create [b,a])
nor repetition (e.g. [a,a])
:param a: Array of strings
:return: list of pairs of strings
"""
pairs = l... | 50c489d660a7e82c18baf4800e599b8a3cd083f0 | 33,155 |
def cleanse_comments(line):
"""Removes //-comments and single-line C-style /* */ comments.
Args:
line: A line of C++ source.
Returns:
The line with single-line comments removed.
"""
comment_position = line.find('//')
if comment_position != -1 and not is_cpp_string(line[:comment_pos... | d209b93070ab33d3f85f5a1d5c44ed47cde2fe91 | 33,156 |
def get_next_document_id(request, document_id):
"""Gets the id of the next document, by the current document's id
Gets the id of the next document, by the current document's id
The function is accessible for users with 'read_project' permission of the project and the owner of the project.
Args:
... | c9a098077a4672e27f438dc58ce0fb3c93d528d2 | 33,157 |
def is_merged(request):
"""Makes tests try both merged and closed pull requests."""
return request.param | d621f44b2ac3fe4a8639fd71d11e146fde9ca725 | 33,158 |
from typing import Dict
from typing import cast
def is_table(base_url: str, token: str) -> bool:
"""check if service layer is a table"""
params: Dict[str, str] = init_params(token)
type_layer = cast(Dict[str, str], request(base_url.rstrip('/'), params))['type']
return type_layer.lower() == 'table' | 23c67be574335689ac5e906c748e465d3d6ed0a0 | 33,159 |
def shared_options(option_list):
"""Define decorator for common options."""
def _shared_options(func):
for option in reversed(option_list):
func = option(func)
return func
return _shared_options | 7ef551ea9879b708e6b449ce1155d47b662efd3d | 33,160 |
from typing import Any
def complex_key(c: complex) -> Any:
"""Defines a sorting order for complex numbers."""
return c.real != int(c.real), c.real, c.imag | 55c17b0d4adf8bcfb39b50c66d5bd8133f5bb814 | 33,161 |
def make_raw_query_nlist_test_set(box, points, query_points, mode, r_max,
num_neighbors, exclude_ii):
"""Helper function to test multiple neighbor-finding data structures.
Args:
box (:class:`freud.box.Box`):
Simulation box.
points ((:math:`N_{points... | 2f9b6bd9436f6f416d62e3056b9baf663ed3b209 | 33,162 |
def runs_new_in_exp(exp='xpptut15', procname='pixel_status', verb=0) :
"""Returns list of (4-char str) runs which are found in xtc directory and not yet listed in the log file,
e.g. ['0059', '0060',...]
"""
runs_log = runs_in_log_file(exp, procname)
runs_xtc = runs_in_xtc_dir(exp)
runs_new = ... | 42faf8c27bdea9e979a8b2390a89fd6c3cad72f4 | 33,163 |
def get_targets(
initial_positions,
trajectory_target_positions):
"""Returns the averaged particle mobilities from the sampled trajectories.
Args:
initial_positions: the initial positions of the particles with shape
[n_particles, 3].
trajectory_target_positions: the absolute positions of the ... | e9f5bde1f791fe2f0546ba7d5323745b90f1029b | 33,165 |
def get_campaign_goal(campaign, goal_identifier):
"""Returns goal from given campaign and Goal_identifier.
Args:
campaign (dict): The running campaign
goal_identifier (string): Goal identifier
Returns:
dict: Goal corresponding to goal_identifer in respective campaign
"""
i... | 1a8738416ee8187ad2a6a977b36b68f66052bfe8 | 33,166 |
def vox2mm(ijk, affine):
"""
Convert matrix subscripts to coordinates.
.. versionchanged:: 0.0.8
* [ENH] This function was part of `nimare.transforms` in previous versions (0.0.3-0.0.7)
Parameters
----------
ijk : (X, 3) :obj:`numpy.ndarray`
Matrix subscripts for coordinates b... | 9800c53a447e2f7eab85e62ea802c91aaa23aea7 | 33,167 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.