content stringlengths 35 762k | sha1 stringlengths 40 40 | id int64 0 3.66M |
|---|---|---|
def _conv2d(input,
filter,
bias=False,
strides=[1, 1],
pads=[1, 1, 1, 1],
dilations=[1, 1],
group=1,
debugContext=''):
"""Encapsulation of function get_builder().aiOnnx.conv!
args:
x: input tensor
ksize: i... | ca80e49e218414e04fcfc81a8890546188765eb3 | 23,500 |
def split_data(n_samps, percent_test):
"""
:param n_samps: number of data samples
:param percent_test: percent of data to hold out
:return: two sets of indices corresponding to training and validation data
"""
# generate and randomly shuffle
idx = np.arange(n_samps)
np.random.shuffle(id... | 68d63d28b2aaab2697f2aab70fc7341a9a31811d | 23,501 |
def compute_totals(songs, limit_n, save_file=None):
"""
Return array of shape (4, 3, 35) representing counts for
each group of each context type of each label
"""
totals = np.zeros((4, 3, 35), dtype='int32')
i = 0
for song_path, beatmap_ids in songs:
print('song {}'.format(i))
... | d8e845912d6e1b5e0fab864e8a19cdc08500b4c5 | 23,502 |
def _initialize_arrays(initial_values,
num_steps):
"""Construct a structure of `TraceArray`s from initial values."""
trace_arrays = tf.nest.map_structure(
lambda t: tf.TensorArray( # pylint: disable=g-long-lambda
dtype=t.dtype,
size=num_steps, # Initial size.
... | f63e13f35aade7979b4090964c593c2d222e94bd | 23,503 |
def blend(image1, image2, factor):
"""Blend image1 and image2 using 'factor'.
Factor can be above 0.0. A value of 0.0 means only image1 is used.
A value of 1.0 means only image2 is used. A value between 0.0 and
1.0 means we linearly interpolate the pixel values between the two
images. A value greater than... | 5012d34ab9974e88bfc7dae4683521313fd37cd0 | 23,504 |
def handle_debug(drive_file, node_id, show_all):
"""Handle the debug verb by toggling the debug flag."""
if drive_file.debug:
print("# handle_debug(node_id: " + str(node_id) + ",")
print("# show_all: " + str(show_all))
drive_file.set_debug(not drive_file.get_debug())
return True | 7afcecc36c9f0cc9104267dac68ff65eb0eb527a | 23,505 |
def start_of_next_clk_period(time: float, clk_period: float):
"""
:return: start time of next clk period
"""
return (start_clk(time, clk_period) + 1) * clk_period | d59dafc3a8fdec9d199dcf379eefce52267ea4c1 | 23,506 |
import re
def eval_formula(formula, assignment):
""" Evaluates a formula represented as a string.
**Attention**: Be extremely careful about what to pass to this function.
All parameters are plugged into the formula and evaluated using `eval()`
which executes arbitrary python code.
Parameters
... | c1f344fc0049e20e86feb2428a46d51f9eee5898 | 23,507 |
def soil_temperature(jth: int, states: States, weather: Weather): # j = 1,2,..,5
"""
Equation 2.4 / 8.4
cap_soil_j * soil_j_t = sensible_heat_flux_soil_j_minus_soil_j - sensible_heat_flux_soil_j_soil_j_plus
0 is Floor, 6 is SoOut
"""
h_soil_j_minus = Coefficients.Floor.floor_thickness if jth =... | ddd3e50b30dc1240d5f6c6200aea710beba6b498 | 23,508 |
def clean_user_data(model_fields):
"""
Transforms the user data loaded from
LDAP into a form suitable for creating a user.
"""
# Create an unusable password for the user.
model_fields["password"] = make_password(None)
return model_fields | 9b9f968c4a775527dac36597ecadee476549dc7d | 23,509 |
import json
def case_structure_generator(path):
"""Create test cases from reference data files."""
with open(str(path), 'r') as in_f:
case_data = json.load(in_f)
system_dict = case_data['namelists']['SYSTEM']
ibrav = system_dict['ibrav']
ins = {'ibrav': ibrav, 'cell': case_data['cell']}
... | 1c7249c207032ed623bbfe274ed117283cd6ef4d | 23,510 |
from typing import Optional
from typing import Type
from typing import Dict
from typing import List
from typing import Any
def load_ascii(file: 'BinaryFile', # pylint: disable=unused-argument,keyword-arg-before-vararg
parser: 'Optional[Type[ASCIIParser]]' = None,
type_hook: 'Optional[Di... | fa7f0ba4a98dc295fb23651373a6489dad5c205e | 23,511 |
def differences_dict(input_dict):
"""Create a dictionary of combinations of readers to create bar graphs"""
# Getting the combinations of the formats
for each_case in input_dict.keys():
comb = combinations(input_dict[each_case].keys(), 2)
x = list(comb)
comp_values = {}
comp_... | a15ef7bab8a9abaf556e1ce97a4c695b50d5b460 | 23,512 |
import psutil
def available_memory():
"""
Returns total system wide available memory in bytes
"""
return psutil.virtual_memory().available | 5071312f64aa37e1d777c8f20009fa38137381a4 | 23,513 |
def aslr_for_module(target, module):
"""
Get the aslr offset for a specific module
- parameter target: lldb.SBTarget that is currently being debugged
- parameter module: lldb.SBModule to find the offset for
- returns: the offset as an int
"""
header_address = module.GetObjectFileHeaderAddr... | bd4e6ff8949da55d678f5d89b296b3a6256b6c8a | 23,514 |
from typing import List
from typing import Set
import numpy
def get_hypergraph_incidence_matrix(node_list: List[Node],
hyperedge_list: List[Set[Node]]
) -> numpy.array:
"""Get the incidence matrix of a hypergraph"""
node_to_index = {node:... | 706bdd53a1fefec3ee3f77fa79248361ffff0351 | 23,515 |
from re import X
def fformat(last_data, last_records):
"""
@param last_data: dictionary(node_name => node's data segment)
@param last_records: dictionary(node_name => timestamp, node when
last transmitted)
@return: html
"""
nodelist = last_data... | 28da148b43c616652872cabc7815cba51dafd16c | 23,516 |
import math
def ceil(base):
"""Get the ceil of a number"""
return math.ceil(float(base)) | ebe78a5eb8fa47e6cfba48327ebb1bdc469b970d | 23,517 |
import os
def process_raw_data(input_seqs, scaffold_type=None, percentile=None,
binarize_els=True, homogeneous=False, deflank=True,
insert_into_scaffold=True, extra_padding=0,
pad_front=False, report_loss=True, report_times=True,
remo... | 7dafb359dba280a56b6d9860cd23c4f1dde7cd02 | 23,518 |
def train(
dir,
input_s3_dir,
output_s3_dir,
hyperparams_file,
ec2_type,
volume_size,
time_out,
docker_tag,
aws_role,
external_id,
base_job_name,
job_name,
use_spot_instances=False,
metric_names=None,
... | 7cd92363bcde8dc86989a8932236cd4b2961b0e3 | 23,519 |
def wikitext_page(d, e, title, fmt='wikitext'):
"""Create infobox with stats about a single page from a category.
Create infobox with stats about a single page from a category. Currently only supports formatting as wikitext.
Only returns the string of the text, does not save any files or modify other data ... | 1288a1fea5bc54ef6243089eea0578cc43ec311e | 23,520 |
from typing import Tuple
def _quadratic(
self: qp.utils.Minimize[Vector],
direction: Vector,
step_size_test: float,
state: qp.utils.MinimizeState[Vector],
) -> Tuple[float, float, bool]:
"""Take a quadratic step calculated from an energy-only test step.
Adjusts step size to back off if energy ... | 49b2e75d0ae39e968e7288690dea7d42c423a2df | 23,521 |
def create_image(ds: "Dataset", data_element: "DataElement") -> "gdcm.Image":
"""Return a ``gdcm.Image``.
Parameters
----------
ds : dataset.Dataset
The :class:`~pydicom.dataset.Dataset` containing the Image
Pixel module.
data_element : gdcm.DataElement
The ``gdcm.DataElemen... | 95f96b0f666903529811fbf3aaeb71305dfcb1bc | 23,522 |
def linear_interpolate_by_datetime(datetime_axis, y_axis, datetime_new_axis,
enable_warning=True):
"""A datetime-version that takes datetime object list as x_axis
"""
numeric_datetime_axis = [
totimestamp(a_datetime) for a_datetime in datetime_axis
]
numer... | 515eb1e389b711ff3add707abe91bf577b38192d | 23,523 |
def calculate_index(
target_ts: pd.Timestamp, timestamps: pd.DatetimeIndex
) -> pd.Timestamp:
"""
Return the first index value after the target timestamp if the exact timestamp is not available
"""
# noinspection PyUnresolvedReferences
target_beyond_available = (target_ts > timestamps).all()
... | db1ad3130b3763115cb88e8798618d9632996bd7 | 23,524 |
from typing import OrderedDict
import pydoc
def walk_through_package(package):
"""
Get the documentation for each of the modules in the package:
Args:
package: An imported python package.
Returns:
output: A dictionary with documentation strings for each module.
"""
output = ... | 9ad0e9d935a812608fb42af788c1ae6746b78684 | 23,525 |
import gzip
def extract_images_2(f):
"""Extract the images into a 4D uint8 numpy array [index, y, x, depth].
Args:
f: A file object that can be passed into a gzip reader.
Returns:
data: A 4D unit8 numpy array [index, y, x, depth].
Raises:
ValueError: If the bytestream does not start with 2051.
"... | eb3b44051c6cc3721a82641346c233d9d4bfe1da | 23,526 |
from datetime import datetime
def slope_finder(station):
""" This function computes the slope of a least-squares fit of polynomial
of degree p to water level data and return that is it positive or negative"""
try:
dt = 2
dates, levels = fetch_measure_levels(station.measure_id, dt=datetime.... | 035a78a4e54b94945837e97c6dce53bc36770956 | 23,527 |
def get_attr_counts(datas, attr):
"""
不同属性值的数量.
:param datas:
:type datas: list[BaseDataSample]
:param attr:
:type attr: str
:return:
"""
results = {}
for data in datas:
value = data.get_value(attr)
if isinstance(value, list):
for v in value:
... | bea8e6e1c99efe1ad18894831006f0e218517c74 | 23,528 |
def split(string: str, separator: str = " ") -> list:
"""
Will split the string up into all the values separated by the separator (defaults to spaces)
>>> split("apple#banana#cherry#orange",separator='#')
['apple', 'banana', 'cherry', 'orange']
>>> split("Hello there")
['Hello', 'there... | 73e01d7ff9111d949f31f37b36c3b0656d06e340 | 23,529 |
import ast
def _find_class(name: str, target: ast.Module) -> t.Tuple[int, ast.ClassDef]:
"""Returns tuple containing index of classdef in the module and the ast.ClassDef object"""
for idx, definition in enumerate(target.body):
if isinstance(definition, ast.ClassDef) and definition.name == name:
... | ad67d36772ef9541edb72a9d56f3553dc9eaffd2 | 23,530 |
def get_floor_reference_points():
"""
This function get 4 points of reference from the real world, asking the
user to move the baxter arm to the position of each corresponding point
in the image, and then getting the X,Y and Z coordinates of baxter's hand.
Returns an array of size 4 containing 4 coo... | 2e058caedeabb23f4efc0a7119456db596421c30 | 23,531 |
def tidy_osx_command_line_tools_command(client: TidyClient, **kwargs) -> DemistoResult:
""" Install OSX command line tools
Args:
client: Tidy client object.
**kwargs: command kwargs.
Returns:
DemistoResults: Demisto structured response.
"""
runner: Runner = client.osx_comma... | 0045848f0cef054dfab24a7698e4b3432843f747 | 23,532 |
def nav_entries(context):
"""
Renders dynamic nav bar entries from nav_registry for the provided user.
"""
context['nav_registry'] = nav_registry
return context | 8af1917c04a9cbd17895c0fab0239d6fd7c009d2 | 23,533 |
from typing import Any
def get_largest_component(graph: ig.Graph, **kwds: Any) -> ig.Graph:
"""Get largest component of a graph.
``**kwds`` are passed to :py:meth:`igraph.Graph.components`.
"""
vids = None
for component in graph.components(**kwds):
if vids is None or len(component) > len(... | 24f04905c767f02a03b5a6fbf4ae0ba0b1f49269 | 23,534 |
def hiring_contests():
"""Gets all the hiring challenges from all the availbale platforms"""
contests_data = get_contests_data()
active_contests = contests_data["active"]
upcoming_contests = contests_data["pending"]
get_challenge_name = lambda x : x.lower().split()
hiring_challenges = [contest for contest i... | 91566f0117fc5bc38db7bc930d5e4c7bd1bd2992 | 23,535 |
import torch
def _find_quantized_op_num(model, white_list, op_count=0):
"""This is a helper function for `_fallback_quantizable_ops_recursively`
Args:
model (object): input model
white_list (list): list of quantizable op types in pytorch
op_count (int, optional): count the quantizable... | c51b06e476ff4804d5bdfca5a187717536a0418f | 23,536 |
import sys
def make_withdrawal(account):
"""Adjusts account balance for withdrawal.
Script that verifies withdrawal amount is valid, confirms that withdrawal amount is less than account balance, and adjusts account balance.
Arg:
account(dict): contains pin and balance for account
... | 94600c74b0aa61674c6e6d63cd1a541b8157cb47 | 23,537 |
def monta_reacao(coef, form):
"""
Retorna a estrutura de uma reação química com base em arrays gerados por métodos de sorteio de reações.
:param coefs: Array com coeficientes das substâncias.
:param formulas: Array com fórmulas das substâncias.
:return: string pronta para ser impressa (print()) adeq... | 9ead94969fbeec6f403f21dc8ebc9eec36ad9438 | 23,538 |
from unittest.mock import patch
def test_process_bulk_queue_errors(app, queue):
"""Test error handling during indexing."""
with app.app_context():
# Create a test record
r1 = Record.create({
'title': 'invalid', 'reffail': {'$ref': '#/invalid'}})
r2 = Record.create({
... | 83c4609eb62d65fb7d53117906a0d6f128fe7b30 | 23,539 |
def list_to_string(the_list):
"""Converts list into one string."""
strings_of_list_items = [str(i) + ", " for i in the_list]
the_string = "".join(strings_of_list_items)
return the_string | f580dd8646526e64bb50297608e8ad8e338d9197 | 23,540 |
import os
import sys
from typing import get_args
def _op_select_format(kernel_info):
"""
call op's op_select_format to get op supported format
Args:
kernel_info (dict): kernel info load by json string
Returns:
op supported format
"""
try:
op_name = kernel_info['op_inf... | 8ab9a28e9e680ad181a317ba07cd120ca9dac762 | 23,541 |
from typing import Optional
def get_rate_plan(apiproduct_id: Optional[str] = None,
organization_id: Optional[str] = None,
rateplan_id: Optional[str] = None,
opts: Optional[pulumi.InvokeOptions] = None) -> AwaitableGetRatePlanResult:
"""
Gets the details of... | c439d2b991174b2fa4137d0b88f04af0ba4a22b9 | 23,542 |
def detail_blotter(backtest, positions, holdings, mode='simplified'):
"""
分品种获取详细交易状况,合并市场数据、交易情况和账户变动
参数:
backtest, positions, holdings为回测引擎返回的变量
mode: 'simplified'则市场行情数据只保留'close'列
(DataFrame的字典)
返回:
字典,键为symbol,值为DataFrame格式
示例:
blotter = detail_blotter(backtest, positions, ... | 9a2d8168cfc9ee979be847c6dac783a70503503c | 23,543 |
def parameters_create_lcdm(Omega_c, Omega_b, Omega_k, h, norm_pk, n_s, status):
"""parameters_create_lcdm(double Omega_c, double Omega_b, double Omega_k, double h, double norm_pk, double n_s, int * status) -> parameters"""
return _ccllib.parameters_create_lcdm(Omega_c, Omega_b, Omega_k, h, norm_pk, n_s, status) | d0a623fcfbcee06a387a3bf7add96068a8205824 | 23,544 |
def _split_header_params(s):
"""Split header parameters."""
result = []
while s[:1] == b';':
s = s[1:]
end = s.find(b';')
while end > 0 and s.count(b'"', 0, end) % 2:
end = s.find(b';', end + 1)
if end < 0:
end = len(s)
f = s[:end]
resu... | fabbfb0959133e70019742c6661cb3bb443ca34d | 23,545 |
def countDigits(string):
"""return number of digits in a string (Helper for countHaveTenDigits)"""
count = 0
for char in string:
if char == '0' or char == '1' or char == '2' or char == '3' or char == '4' or \
char == '5' or char == '6' or char == '7' or char == '8' or char == '9':
... | f8d2327e022efc7a117b744588dfe16a3a7ba75e | 23,546 |
def get_process_entry(process_id: int) -> Process:
"""Get process entry
:raises AssertionError: When illegal state: Active processes != 1
:param process_id: specify process
:return: Process entry
"""
active_process_entry_query = db.session.query(Process).filter(Process.id == process_id)
ass... | 442df14f1d032ff1fe8c40598f39a06255982da8 | 23,547 |
def shrink(filename):
"""
The function will make the original image shrink to its half without losing too much quality.
:param filename: The directory of an image tou want to process.
:return img: SimpleImage, a shrink image that is similar to the original image.
"""
img = SimpleImage(filename)
... | 0bff7d59bb7ae512883103bfe21ba80598c28c17 | 23,548 |
import getpass
def get_target_config():
"""
Get details of the target database (Postgres)
"""
print('\n------------------------------------------')
print('Enter target database settings:')
print('------------------------------------------')
config = {}
config['username'] = input('- U... | 36820bae4af66b2db92ce1d467996b6e9a7a2624 | 23,549 |
def GetGPU():
"""Get the global index of GPU.
Returns
-------
int
The global index of GPU.
"""
return option['device_id'] | 2c392c97da988c33ff12f59db4bb10f6b41e3bc1 | 23,550 |
def get_generic_explanation(exception_type):
"""Provides a generic explanation about a particular exception."""
if hasattr(exception_type, "__name__"):
exception_name = exception_type.__name__
else:
exception_name = exception_type
if exception_name in GENERIC:
return GENERIC[exce... | b590be31518f3eabdc1cdeb31b1c66e66b47b253 | 23,551 |
import os
def _normalized_bam_coverage(name, bam_input, data):
"""Run bamCoverage from deeptools but produce normalized bigWig files"""
cmd = ("{bam_coverage} --bam {bam_input} --outFileName {bw_output} "
"--binSize 20 --effectiveGenomeSize {size} "
"--smoothLength 60 --extendReads 150 --c... | e282a1333d30656eb35157bb78f7bd429d6c5358 | 23,552 |
def simple_histogram(queryset, column, bins):
"""
Return a histogram from data in queryset.
:param queryset: A Queryet, Model, or Manager
:param column: The column we are aggregating into a histogram
:param bins: An ordered iterable of left endpoints of the bins. Must have at least two elements.
... | b6f4f2738cdf5e3e610e830886e2c6639aae309e | 23,553 |
import os
def ProbeDebuggerDir():
"""Probes the debugger installed path and returns the path."""
program_files = os.environ.get('ProgramFiles')
if not program_files:
return None
# Probing debugger installed path.
# Starting with 32 bit debugger on 32 bit platform.
debugger_dir = '%s\\Debugging Tools F... | 56b6d18782d0557fd8f4236fd0cdfcbbc98faf90 | 23,554 |
def bounding_box(points):
"""Bounding box
Args:
points: Array of shape (amount_of_points, dimensions)
Returns:
numpy.ndarray: Array of [[min, max], [min, max], ...] along the
dimensions of points.
"""
out = np.empty((points.ndim, 2))
for i in range(points.ndim):
... | 44871a584f3592296c982c82a798c05ee8b166f7 | 23,555 |
def get_ts_WFI(self):
"""
Get kinetic energy density
"""
ts = np.zeros((self.grid.Nelem, len(self.solver[0,:]) ))
if self.optInv.ens_spin_sym is not True:
for i in range(self.solver.shape[0]):
for j in range(self.solver.shape[1]):
self.solver[i,j].calc_ked_WFI... | 8384a5c3d1e2cdb5551ecb783101961f73a2d523 | 23,556 |
def _correct_outlier_correlation(rpeaks: pd.DataFrame, bool_mask: np.array, corr_thres: float, **kwargs) -> np.array:
"""Apply outlier correction method 'correlation'.
This function compute the cross-correlation coefficient between every single beat and the average of all detected
beats. It marks beats as ... | 7216b1c8e2c3352d14273aa058e5c9fd4398044b | 23,557 |
import time
def _time_from_timestamp(timestamp: int) -> time:
"""
Casts a timestamp representing the number of seconds from the midnigh to a time object
Parameters
----------
timestamp : int
The number of seconds since midnight
Returns
-------
time
The associated time... | 552f2b3b6841d48f3340ecdd94edb03f791a84c9 | 23,558 |
def get_marginal_frequencies_of_spikes_in_bins(symbol_counts, number_of_bins_d):
"""
Compute for each past bin 1...d the sum of spikes found in that bin across all
observed symbols.
"""
return np.array(sum((emb.symbol_binary_to_array(symbol, number_of_bins_d)
* symbol_counts... | c1ace43f040715c87a3a137bebf64d862060a590 | 23,559 |
def member_stand(v, m):
""" returns member m stand on vote v """
va = VoteAction.objects.filter(member = m, vote = v)
if va:
for (name,string) in VOTE_ACTION_TYPE_CHOICES:
if va[0].type==name:
stand = _(string)
cls = name
return {'stand':stand, 'cl... | 2a038c907046fad81784c442fe67f0b65902df85 | 23,560 |
def pagination(cl):
"""
Generate the series of links to the pages in a paginated list.
"""
paginator, page_num = cl.paginator, cl.page_num
pagination_required = (not cl.show_all or not cl.can_show_all) and cl.multi_page
if not pagination_required:
page_range = []
else:
ON_EA... | cca1b80f1bc2c60c8f4af44f138b5433023298f7 | 23,561 |
def ants_apply_inverse_warps_template_to_func(
workflow, strat, num_strat, num_ants_cores, input_node, input_outfile,
ref_node, ref_outfile, func_name, interp, input_image_type
):
"""Apply the functional-to-structural and structural-to-template warps
inversely to functional time-series in templa... | e1fdd24a9e3b13ff280baf89586eeca85f1f0a7d | 23,562 |
def get_metrics_influx(query, query_index):
""" Function to Query InfluxDB """
influx_connect = InfluxDBClient(
host=defs.INFLUX_DETAILS[query_index][0],
database=defs.INFLUX_DETAILS[query_index][1],
port=8086,
timeout=5,
retries=5)
response = influx_connect.query(que... | 3f5d7c147553d3b16cfb3d18a1b86805f879fda7 | 23,563 |
def find_buckets(pc, target_centres, N, bucket_height=.38, bucket_radius=.15):
"""
Returns: pc, bucket_centres
"""
### find buckets and remove ###
print ('finding buckets')
buckets = pc[pc.z.between(.1, .4)]
# voxelise to speed-up dbscan
buckets.loc[:, 'xx'] = (buckets.x // .0... | e7e5480783235e6e9ad48cbfc4d006e9a0a7b61e | 23,564 |
import torch
def fit_model(model, state_train, action_train, num_epochs, learning_rate = 1e-2, batch_size=32, shuffle=True):
"""
Trains a pytorch module model to predict actions from states for num_epochs passes through the dataset.
This is used to do a (relatively naive) version of behavior cloning
... | f68573326a218c3da47bb016f02318412ddf9d1d | 23,565 |
from typing import Any
from typing import Dict
import typing
def _deserialize_dict(
class_reference, data, debug_name, *, throw_on_unhandled: bool, raw_storage_mode: RawStorageMode
):
"""Deserialize a dictionary to a Python object."""
# Check if we are doing a straightforward dictionary parse first, or i... | d1b81247d47958b05bc4ff116a2a0df9ee6eaeb6 | 23,566 |
def red_bg(text):
"""
Red background.
"""
return _create_color_func(text, bgcolor=1) | c867f7415230b6f5c179a4369bf4751f9ee2a442 | 23,567 |
def does_block_type_support_children(block_type):
"""
Does the specified block type (e.g. "html", "vertical") support child
blocks?
"""
try:
return XBlock.load_class(block_type).has_children
except PluginMissingError:
# We don't know if this now-uninstalled block type had childre... | f1e86e6b378ef3e134106653e012c8a06cebf821 | 23,568 |
def jsonDateTimeHandler(obj):
"""Takes an object and tries to serialize it in JSON
by using strftime or isoformat."""
if hasattr(obj, "strftime"):
# To avoid problems with the js date-time format
return obj.strftime("%a %b %d, %Y %I:%M %p")
elif hasattr(obj, 'isoformat'):
return ... | 605f8a379575d185bc2a8b16810252511eec52af | 23,569 |
def truncate_desired(cluster, desired, min_size, max_size):
"""Do truncation of desired capacity for non-strict cases.
:param cluster: The target cluster.
:param desired: The expected capacity of the cluster.
:param min_size: The NEW minimum capacity set for the cluster.
:param max_size: The NEW ma... | c282a7faece40f78bb9baf58b702b942603cc793 | 23,570 |
def get_crypto_price(crypto, fiat):
"""Helper function to convert any cryptocurrency to fiat"""
converted_btc_value = float(binance_convert_crypto(
crypto, "BTC").split('=')[1].strip().split()[0])
# grab latest bitcoin price
btc_price = float(get_price("btc", fiat).split('=')[1].strip().split()... | f91e56c74b3422d3ab272c029352ae94521033b0 | 23,571 |
def boxblur(stream: Stream, *args, **kwargs) -> FilterableStream:
"""https://ffmpeg.org/ffmpeg-filters.html#boxblur"""
return filter(stream, boxblur.__name__, *args, **kwargs) | 5f29981abaf050b43207452649f4ad9e3fafc05c | 23,572 |
import os
def create_netcdf_dataset(
location,
name,
start_time,
end_time,
sweep,
inpath=None,
outpath="",
chunks={},
engine="h5netcdf",
):
"""Create NetCDF file from radar data"""
radar_path = get_xpol_path(inpath=inpath, start_time=start_time, loc=location)
file_path ... | 062b79957862995cd59403afb6343b793727fb77 | 23,573 |
def flatten(lis):
"""Given a list, possibly nested to any level, return it flattened."""
new_lis = []
for item in lis:
if type(item) == type([]):
new_lis.extend(flatten(item))
else:
new_lis.append(item)
return new_lis | 7e4e00af9f20f58dc0798a0731c352949dd71cf5 | 23,574 |
def name(ndims=2, ndepth=2):
""" encrypt n and version into a standardized string """
# Model name, depth and version
value = 'care_denoise_%dDdepth%d' % (ndims, ndepth)
return value | 1933ac0454eac4c860d70683e58c922074498b63 | 23,575 |
import string
import random
def _generate_url_slug(size=10, chars=string.ascii_lowercase + string.digits):
"""
This is for a Django project and it assumes your instance
has a model with a slug field and a title character (char) field.
Parameters
----------
size: <Int>
Size of the slug... | 1ebe945730e7e5f977c80666db92cfefb9a1a1a7 | 23,576 |
def mc_compute_stationary(P):
"""
Computes the stationary distribution of Markov matrix P.
Parameters
----------
P : array_like(float, ndim=2)
A discrete Markov transition matrix
Returns
-------
solution : array_like(float, ndim=1)
The stationary distribution for P
... | dc971399bc7b8626347ba9a20a6c8f449870b606 | 23,577 |
def isight_prepare_data_request(a_url, a_query, a_pub_key, a_prv_key):
"""
:param a_url:
:type a_url:
:param a_query:
:type a_query:
:param a_pub_key:
:type a_pub_key:
:param a_prv_key:
:type a_prv_key:
:return:
:rtype:
"""
header = set_header(a_prv_key, a_pub_key, a_... | 8854013b509fa52a35bd1957f6680ce4e4c17dc4 | 23,578 |
def norm_fisher_vector(v, method=['power', 'l2']):
"""
Normalize a set of fisher vectors.
:param v: numpy.array
A matrix with Fisher vectors as rows (each row corresponding to an
image).
:param method: list
A list of normalization methods. Choices: 'power', 'l2'.
:return: n... | 06592b42914902f183d085f584b00cd9a1f057ce | 23,579 |
def get_top_funnels_df(funurl: str, funlen: int, useResolvedUrls: bool, events: DataFrame, limit_rows: int = 0) -> dict:
"""Get top funnels of specified length which contain the specified URL
:param funurl: URL that should be contained in the funnel
:param funlen: funnel length
:param useResolvedUrls: ... | 1fe29668e98076bbb39023e04fc1a5845788d9ef | 23,580 |
import os
import string
def count_alphabet():
"""
Return dict which contains rating of alplabet
"""
# Get all txt file in folder data
list_file = []
for file in os.listdir("data"):
if file.endswith(".txt"):
list_file.append(os.path.join("data", file))
# Int result
r... | 241af2b66abd46afc72259615ad216b96bef6ea5 | 23,581 |
from typing import Dict
from typing import Any
def graph_to_json(obj: Graph) -> Dict[str, Any]:
"""
Uses regular serialization but excludes "operator" field to rid of circular references
"""
serialized_obj = {
k: v
for k, v in any_to_json(obj).items()
if k != 'operator' # to p... | 922d53d5fb9b23773cdea13e94930985785f6c77 | 23,582 |
def log_ttest_vs_basal(df, basal_key):
"""Do t-tests in log space to see if sequences has the same activity as basal.
Parameters
----------
df : pd.DataFrame
Index is sequence ID, columns are average RNA/DNA barcode counts for each replicate.
basal_key : str
Index value for basal.
... | b41029c7c61b3b365bf71e2aaba8a81aecf5533a | 23,583 |
def spleen_lymph_cite_seq(
save_path: str = "data/",
protein_join: str = "inner",
remove_outliers: bool = True,
run_setup_anndata: bool = True,
) -> anndata.AnnData:
"""
Immune cells from the murine spleen and lymph nodes [GayosoSteier21]_.
This dataset was used throughout the totalVI manus... | 7eeead5e6f69b7f3b9dff85b33cae675ea0a47ec | 23,584 |
import os
def getInputs(path, sequenceNames):
"""Requires setting SON_TRACE_DATASETS variable and having access to datasets.
"""
seqPath = os.path.join(TestStatus.getPathToDataSets(), path)
sequences = [ os.path.join(seqPath, sequence) for sequence in sequenceNames ] #Same order as tree
newickTree... | fc5bb96daf0309e7ca4bd65b1217b6a333c0e8a2 | 23,585 |
def strftime_local(aware_time, fmt="%Y-%m-%d %H:%M:%S"):
"""
格式化aware_time为本地时间
"""
if not aware_time:
# 当时间字段允许为NULL时,直接返回None
return None
if timezone.is_aware(aware_time):
# translate to time in local timezone
aware_time = timezone.localtime(aware_time)
return a... | 1294795d793c22e7639fb88ca02e34bb6b764892 | 23,586 |
import re
def filter_issues_fixed_by_prs(issues, prs, show_related_prs, show_related_issues):
"""
Find related issues to prs and prs to issues that are fixed.
This adds extra information to the issues and prs listings.
"""
words = [
'close', 'closes', 'fix', 'fixes', 'fixed', 'resolve', '... | 6e63dc9988c9343b4f9d2baae2d995b26b666ed3 | 23,587 |
import re
def run_job(answer: str, job: dict, grade: float, feedback: str):
"""
Match answer to regex inside job dictionary.
Add weight to grade if successful, else add comment to feedback.
:param answer: Answer.
:param job: Dictionary with regex, weight, and comment.
:param grade: Current gr... | 487916da129b8958f8427b11f0118135268f9245 | 23,588 |
def __build_data__(feature, qars):
"""
Return all the data needed to build the Benin republic departments Layer
"""
data = {
'qars': qars,
}
# GEOJSON layer consisting of a single feature
department_name = feature["properties"]["NAME_1"]
data["department"] = department_name
... | e1982a1f610ea724ca8cf06f6641a4bc3428fa47 | 23,589 |
def hook(callback):
"""
Installs a global listener on all available mouses, invoking `callback`
each time it is moved, a key status changes or the wheel is spun. A mouse
event is passed as argument, with type either `mouse.ButtonEvent`,
`mouse.WheelEvent` or `mouse.MoveEvent`.
Returns the g... | 4bf0884de591fc4f0b30bee42b6e36b06c526134 | 23,590 |
def notification_list(request):
"""
returns the notification list
"""
notifications = Notification.get_notifications(user=request.user)
return {"notifications": notifications} | c8e967fa8cef0dfd5cc9673c99289e17813f2e75 | 23,591 |
from typing import Iterator
def filter_samples_by_detected_language_via_langid(
samples_iterator: Iterator[Sample],
lang_code: str,
) -> Iterator[Sample]:
"""Return sample documents whose language detected by langid matches the expected language.
Documents are converted to a simple text via the metho... | c6c952f46903fc491f88ba32dddb93398420c9d8 | 23,592 |
def predictClass(x, mus, sigmas, X_train, number_of_classes, class_probabilities):
"""
For every model, it calculates the likelihood for each class, and picks the class with max likelihood.
:param x: The datapoint we want to derive the class for.
:param mus: A list with the mean vector for each method.... | dbd9d6227c8877862d74d4bf1932f3f1acd37a2f | 23,593 |
def create_secret_id(vault, name, version=None):
"""
:param vault: The vault uri.
:type vault: str
:param name: The secret name.
:type name: str
:param version: The secret version.
:type version: str
:rtype: KeyVaultId
"""
return create_object_id('secrets', vault, name, version) | 65c918a8f9c1f5c087835ff36a9eb13233bada2d | 23,594 |
def config_output_page():
"""
Configuration landing page
:return: config.html
"""
config_type = "output"
c = ConfigFile()
# First load in all the configuration from the provided configuration file, if it exists
c.load_from_file(DEFAULT_CONFIG_FILE)
cdb = c.get_cdb()
cdb.update_... | 346ae058db6e0081a37a5ebedd6d231f0a3204da | 23,595 |
from typing import Optional
def compute_all_aggregator_metrics(
per_plan_confidences: np.ndarray,
predictions: np.ndarray,
ground_truth: np.ndarray,
metric_name: Optional[str] = None
):
"""Batch size B, we assume consistent number of predictions D per scene.
per_plan_confidences: np.ndarray, ... | cd17c4c1273ec2a23aa16efebd7a4437dc4e16f7 | 23,596 |
import requests
import re
def query_url_base(_url, _proxy=True, _isPC=True, _isPhone=False):
""" 基于requset的模块,不能采集动态网页数据
:param _url<str>
:param _proxy<bool>
:param _isPc<bool>
:param _isPhone<bool>
:return _result<dict>
"""
_result = {}
_headers = {'Connection':'kepp-alive'}
i... | f916b974a472f6a3d079911461902da1ae7cb18d | 23,597 |
def timefstring(dtobj, tz_name=True):
"""Standardize the format used for timestamp string format.
Include 3 letter string for timezone if set to True.
"""
if tz_name:
return f'{dtobj.strftime("%Y-%m-%d_%H:%M:%S%Z")}'
else:
return f'{dtobj.strftime("%Y-%m-%d_%H:%M:%S")}NTZ' | 5bbf0454a76ed1418cbc9c44de909940065fb51f | 23,598 |
def is_block(modules):
"""Check if is ResNet building block."""
if isinstance(modules, (ShuffleUnit, )):
return True
return False | ac6f059b763f25d81508826a3a8c8db5beb769b0 | 23,599 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.