content stringlengths 35 762k | sha1 stringlengths 40 40 | id int64 0 3.66M |
|---|---|---|
def ask_the_user(runner: Runner) -> Direction:
"""Ask the user what to do (in absolute UP, DOWN, etc.)"""
return runner.ask_absolute() | 2f289aba30e1368abd675a9b9bb2be0924984d3d | 3,648,200 |
import pandas as pd
import os
def patents_hgh(path):
"""Dynamic Relation Between Patents and R\\&D
a panel of 346 observations from 1975 to 1979
*number of observations* : 1730
*observation* : production units
*country* : United States
A dataframe containing :
obsno
firm index
year
... | a3093aa59ea567f37560fb0d591e0cb9544e24f8 | 3,648,201 |
def optimize_spot_bid(ctx, instance_type, spot_bid):
"""
Check whether the bid is sane and makes an effort to place the instance in a sensible zone.
"""
spot_history = _get_spot_history(ctx, instance_type)
if spot_history:
_check_spot_bid(spot_bid, spot_history)
zones = ctx.ec2.get_all_z... | 25bd3d9c952c256df12c3cc7efa257629d127af9 | 3,648,202 |
def new_hassle_participants():
"""Select participants for the room helpers."""
# Get a list of all current members.
members = helpers.get_all_members()
return flask.render_template('hassle_new_participants.html', members=members) | c8062ae498691ac72a17a969cf2ba7547e08eb9c | 3,648,203 |
import json
def data_store_remove_folder(request):
"""
remove a sub-folder/sub-collection in hydroshareZone or any federated zone used for HydroShare
resource backend store. It is invoked by an AJAX call and returns json object that include a
status of 'success' if succeeds, and HttpResponse of status... | d6583dca0967fdf282a3510defcdeeb70da6c7f7 | 3,648,204 |
import math
def distance(x1: float, y1: float, x2: float, y2: float) -> float:
"""
Finds distance between two given points
Parameters:
x1, y1 : The x and y coordinates of first point
x2, y2 : The x and y coordinates of second point
Returns:
... | 63f103f46b52aae146b52f385e15bc3441f042e5 | 3,648,205 |
def load_target_class(input_dir):
"""Loads target classes."""
df = pd.read_csv(join(input_dir, "target_class.csv"), header=None, index_col=0, names=["Target"])
return df | 58fea2aebd6c04dd0b51ec3ef3fc627212aa2b29 | 3,648,206 |
import os
import io
import PIL
import hashlib
def dict_to_tf_example(data,
dataset_directory,
label_map_path,
ignore_difficult_instances=False,
image_subdirectory='Images',
is_debug=False):
"""Convert ... | af307dacf5b0b2ccfbc2ceaa74059794dbf872f2 | 3,648,207 |
def fix_labels(ply_gt, ply_seg):
"""
Remove extra vertices from the ground truth
"""
size = len(ply_gt.elements[0]["x"])
gt_x = np.array(ply_gt.elements[0]["x"])
seg_x = np.array(ply_seg.elements[0]["x"])
new_gt_label = np.zeros_like(seg_x)
gt_label = np.array(ply_gt.elements[0]["labe... | 291fedd887b82e6099f5aba6a006fd0e33a7fb18 | 3,648,208 |
import requests
def get_coin_price(api_url: str, currency: str) -> float:
"""
Get the USD price of a coin from Gemini
Args:
api_url: The API URL for Gemini
currency: The cryptocurrency the bot is monitoring
Returns:
coin_price: The price the coin currently holds in USD
"""
# Inst... | 0683554aea85faa1dd105cbf81144685d7d2deec | 3,648,209 |
import hmac
import base64
def GenerateAuthToken(key_name, user_id, action_id='', when=None):
"""Generates a URL-safe token based on XSRFToken but for generla purpose.
Args:
key_name (str): name of secret key to generate token.
user_id (str): the user ID of the authenticated user.
action_id (str): a s... | 8375889ba4cdc1fc996c48330cf0cd23824f5946 | 3,648,210 |
import os
def download_dataset(file_url, file_name):
"""
Utility to download a dataset
"""
# %%
new_dir = up(up(up(up(os.path.abspath(__file__)))))
os.chdir(new_dir)
file_path = r'artificial_neural_networks/datasets/' + file_name
exists = os.path.isfile(file_path)
if exists:
... | 90a2cf4da99b1a69e60e160dd69db3df333924bb | 3,648,211 |
import torch
def get_dataset_psnr(device, model, dataset, source_img_idx_shift=64,
batch_size=10, max_num_scenes=None):
"""Returns PSNR for each scene in a dataset by comparing the view predicted
by a model and the ground truth view.
Args:
device (torch.device): Device to per... | 0ce2274aac72d2510fd0c9c067a6efa542c103ec | 3,648,212 |
def smallest_continuous_multiple(max_multiple):
"""
Function takes an int, and returns the smallest natural number evenly divisible by all numbers
less than or equal to the input max_multiple.
REQ: max_multiple >= 0 and whole
:param max_multiple: {int}
:return: smallest natural number evenly d... | 57423ed0941d18b54a1da33bc561f79ed19ae145 | 3,648,213 |
def context_list_entities(context):
"""
Returns list of entities to be displayed in list view
"""
# log.info(context['List_rows'])
if 'List_rows' in context:
return context['List_rows']['field_value']
elif 'entities' in context:
return context['entities']
log.warning("No enti... | 1b00e5cd6593a7e0c8770e9bbeaae5c3b47ac78a | 3,648,214 |
def run(arg):
"""Entry point"""
error_map = {}
validate_path(arg, None, error_map)
if len(error_map) > 0:
error_count = 0
for file, errors in error_map.items():
print(f"Error in {file}:")
for error in errors:
print(f" {error}")
e... | 0e124b87b62076af713b8caea686e3c44a4e83a2 | 3,648,215 |
import struct
def _bitcode_symbols_partial_impl(
*,
actions,
binary_artifact,
bitcode_symbol_maps,
dependency_targets,
label_name,
output_discriminator,
package_bitcode,
platform_prerequisites):
"""Implementation for the bitcode symbols proce... | 64606e63a7831a110585ceb83fb34699b373db0a | 3,648,216 |
def _str_trim_left(x):
"""
Remove leading whitespace.
"""
return x.str.replace(r"^\s*", "") | 2718086073706411929b45edf80a1d464dfaeff6 | 3,648,217 |
def zipcompress(items_list, flags_list):
"""
SeeAlso:
vt.zipcompress
"""
return [compress(list_, flags) for list_, flags in zip(items_list, flags_list)] | e8f85c058db442a967d89ef2f74e5e32cc58a737 | 3,648,218 |
def test_config_file_fails_missing_value(monkeypatch, presence, config):
"""Check if test fails with missing value in database configuration."""
def mock_file_config(self):
return {'database': {}}
monkeypatch.setattr(presence.builder, "fetch_file_config", mock_file_config)
status, msg = presen... | 34e14fa3b72fbd3a64930b9ce46da61e76138650 | 3,648,219 |
def construct_run_config(iterations_per_loop):
"""Construct the run config."""
# Parse hparams
hparams = ssd_model.default_hparams()
hparams.parse(FLAGS.hparams)
return dict(
hparams.values(),
num_shards=FLAGS.num_shards,
num_examples_per_epoch=FLAGS.num_examples_per_epoch,
resnet_ch... | d2989e795ab14a9931837356cb7a6c3752538429 | 3,648,220 |
def bezier_curve(points, nTimes=1000):
"""
Given a set of control points, return the
bezier curve defined by the control points.
Control points should be a list of lists, or list of tuples
such as [ [1,1],
[2,3],
[4,5], ..[Xn, Yn] ]
nTimes is ... | 3d4ea2a42e3e4bb7ff739b262e3fc69784656fed | 3,648,221 |
def _compact_temporaries(exprs):
"""
Drop temporaries consisting of isolated symbols.
"""
# First of all, convert to SSA
exprs = makeit_ssa(exprs)
# What's gonna be dropped
mapper = {e.lhs: e.rhs for e in exprs
if e.lhs.is_Symbol and (q_leaf(e.rhs) or e.rhs.is_Function)}
... | b28b839cc17124b83b6b26b972394486cd7d8741 | 3,648,222 |
def print_formula(elements):
"""
The input dictionary, atoms and their amount, is processed to produce
the chemical formula as a string
Parameters
----------
elements : dict
The elements that form the metabolite and their corresponding amount
Returns
-------
formula : str
... | a3c404ef0d18c417e44aee21106917f4ee203065 | 3,648,223 |
def try_get_code(url):
"""Returns code of URL if exists in database, else None"""
command = """SELECT short FROM urls WHERE full=?;"""
result = __execute_command(command, (url,))
if result is None:
return None
return result[0] | 63a88471f6fdfc44bc22383edda0eb65f9bf1b84 | 3,648,224 |
import unicodedata
def is_chinese_char(cc):
"""
Check if the character is Chinese
args:
cc: char
output:
boolean
"""
return unicodedata.category(cc) == 'Lo' | d376e6097e628ac2f3a7934ba42ee2772177f857 | 3,648,225 |
import json
def _get_ec2_on_demand_prices(region_name: str) -> pd.DataFrame:
"""
Returns a dataframe with columns instance_type, memory_gb, logical_cpu, and price
where price is the on-demand price
"""
# All comments about the pricing API are based on
# https://www.sentiatechblog.com/using-th... | 8946260abee2f11f47c9ed93f1b6e2c90cd17c31 | 3,648,226 |
def resize_image(image, min_dim=None, max_dim=None, padding=False):
"""
Resizes an image keeping the aspect ratio.
min_dim: if provided, resizes the image such that it's smaller
dimension == min_dim
max_dim: if provided, ensures that the image longest side doesn't
exceed this value.
... | 17c8cb953753321f1aea169ebcb199598b7fd2f1 | 3,648,227 |
def idwt(approx, wavelets, h=np.array([1.0 / np.sqrt(2), -1.0 / np.sqrt(2)]),
g=np.array([1.0 / np.sqrt(2), 1.0 / np.sqrt(2)])):
"""
Simple inverse discrete wavelet transform.
for good reference: http://www.mathworks.com/help/wavelet/ref/dwt.html
@param approx: approximation of signal at low re... | a41cd22d81de733428123681bbea10837d4c7237 | 3,648,228 |
import json
def app_durations():
"""Generate JavaScript for appDurations."""
return 'appDurations = ' + json.dumps(supported_durations) | 3be9ecc801cd650a5cd1a3c4db1c50957ccfa1c0 | 3,648,229 |
def generic_cc(mag=10,dmag=8,band='K'):
"""Returns a generic contrast curve.
Keyword arguments:
mag -- magnitude of target star in passband
dmag -- can currently be either 8 or 4.5 (two example generic cc's being used)
band -- passband of observation.
"""
if dmag==8:
return fpp.Con... | 04ca148c2a5b8d9eb2d0c60a0d6ad8e177901c5f | 3,648,230 |
from typing import Any
def read_routes(*, db: Session = Depends(deps.get_db),data_in: schemas.DictDataCreate,current_user: models.User = Depends(deps.get_current_active_user)) -> Any:
"""
Retrieve Mock Data.
"""
db.add(models.Dict_Data(**jsonable_encoder(data_in)))
return {
"code": 20000,
... | 09e575a8262a0818c7904e4e077d86f492f3407e | 3,648,231 |
def get_companies_pagination_from_lagou(city_id=0, finance_stage_id=0, industry_id=0, page_no=1):
"""
爬取拉勾公司分页数据
:param city_id: 城市 id
:param finance_stage_id: 融资阶段 id
:param industry_id: 行业 id
:param page_no: 页码
:return: 拉勾公司分页数据
:rtype: utils.pagination.Pagination
"""
url = co... | 7a82e0dd7ad8ab960dbabb749e68867607b70878 | 3,648,232 |
def is_quant_contam(contam_model):
"""Get the flag for quantitative contamination"""
# the list of quantitative models
quant_models = ['GAUSS', 'FLUXCUBE']
# set the default value
isquantcont = True
# check whether the contamination is not quantitative
if not contam_model.upper() in quant_... | 8a88609857ac8eb61bfddfa8d8227ffa237d2641 | 3,648,233 |
def nms_wrapper(scores, boxes, threshold = 0.7, class_sets = None):
"""
post-process the results of im_detect
:param scores: N * K numpy
:param boxes: N * (K * 4) numpy
:param class_sets: e.g. CLASSES = ('__background__','person','bike','motorbike','car','bus')
:return: a list of K-1 dicts, no b... | 7f6a260811a1c20da40e41cc179488440bfc5164 | 3,648,234 |
def Rbf(
gamma: float = 1.0) -> InternalLayer:
"""Dual activation function for normalized RBF or squared exponential kernel.
Dual activation function is `f(x) = sqrt(2)*sin(sqrt(2*gamma) x + pi/4)`.
NNGP kernel transformation correspond to (with input dimension `d`)
`k = exp(- gamma / d * ||x - x'||^2) = e... | c7c44f6227d0d337da40a1afe8eff359ccaebbf5 | 3,648,235 |
from typing import Dict
from typing import Any
import os
def upgrade_state_dict_with_xlm_weights(
state_dict: Dict[str, Any], pretrained_xlm_checkpoint: str,
) -> Dict[str, Any]:
"""
Load XLM weights into a Transformer encoder or decoder model.
Args:
state_dict: state dict for either Transfo... | 4f73d82117cb0fa6a07926a9527ef5a0f185c1cf | 3,648,236 |
def create_returns_tear_sheet(returns, positions=None,
transactions=None,
live_start_date=None,
cone_std=(1.0, 1.5, 2.0),
benchmark_rets=None,
bootstrap=False,
... | 5d01bb52ed3bd642ed8c7743ee41b4d57f732c2f | 3,648,237 |
def vectorize_text(text_col: pd.Series,
vec_type: str = 'count',
**kwargs):
"""
Vectorizes pre-processed text. Instantiates the vectorizer and
fit_transform it to the data provided.
:param text_col: Pandas series, containing preprocessed text.
:param vec_type: ... | fd1b720c5eee83d788684a49f5fe7ad26e955016 | 3,648,238 |
def creation_LS(X,y,N):
"""Generates a random learning set of size N from the data in X
(containing the input samples) and in y (containing the corresponding
output values).
Parameters
----------
X: array containing the input samples
y: array conta... | fdcf5fe96082a75b096b43747f940b8cf46f326b | 3,648,239 |
def print_summary(show="all",
blocks=False, cid=True, blobs=True, size=True,
typ=False, ch=False, ch_online=True,
name=True, title=False, path=False,
sanitize=False,
start=1, end=0, channel=None, invalid=False,
r... | 6888917bd6a944c6e91c0d9796383b279db68315 | 3,648,240 |
def nice_number_en(number, speech, denominators=range(1, 21)):
""" English helper for nice_number
This function formats a float to human understandable functions. Like
4.5 becomes "4 and a half" for speech and "4 1/2" for text
Args:
number (int or float): the float to format
speech (bo... | 9816277c3374ddc5ba8c9b598f5ef27893fb3f1b | 3,648,241 |
import os
import re
def read_dataframe_by_substring(directory, substring, index_col=None, parse_dates=False, **kwargs):
"""Return a dataframe for the file containing substring.
Parameters
----------
directory : str
substring : str
identifier for output file, must be unique in directory
... | c4b8d10c36f8262263b45fbaae0cdb6306e5d6cc | 3,648,242 |
import logging
def load_embeddings(path):
"""
Load embeddings from file and put into dict.
:param path: path to embeddings file
:return: a map word->embedding
"""
logging.info('Loading embeddings...')
embeddings = dict()
with open(path, 'r') as f:
for line in f:
li... | 3e7e05cc9131dfb9d06c4c220d5e13d6965180b7 | 3,648,243 |
def helm_preserve(preserve):
"""Convert secret data to a "--set" string for Helm deployments.
Args:
preserve (Iterable): Set of secrets we wish to get data from to assign to the Helm Chart.
Returns:
str: String containing variables to be set with Helm release.
"""
env_vars = []
... | 095d5b914feb327c81e4630347ab04d1954d2f14 | 3,648,244 |
def format_component_descriptor(name, version):
"""
Return a properly formatted component 'descriptor' in the format
<name>-<version>
"""
return '{0}-{1}'.format(name, version) | 2edb92f20179ae587614cc3c9ca8198c9a4c240e | 3,648,245 |
import sqlite3
def dbconn():
"""
Initializing db connection
"""
sqlite_db_file = '/tmp/test_qbo.db'
return sqlite3.connect(sqlite_db_file, detect_types=sqlite3.PARSE_DECLTYPES|sqlite3.PARSE_COLNAMES) | b0c6dd235490cee93ada20f060d681a319b120f0 | 3,648,246 |
import hashlib
def md5(fname):
"""
Compute the md5 of a file in chunks.
Avoid running out of memory when hashing large files.
"""
hash_md5 = hashlib.md5()
with open(fname, "rb") as f:
for chunk in iter(lambda: f.read(4096), b""):
hash_md5.update(chunk)
return hash_md5.h... | 9e0bfbd625df6a46d5bff4cd0e9f065d1eaf8a4b | 3,648,247 |
def get_r(x, y, x1, y1):
"""
Get r vector following Xu et al. (2006) Eq. 4.2
x, y = arrays; x1, y1 = single points; or vice-versa
"""
return ((x-x1)**2 + (y-y1)**2)**0.5 | 424408f86e6e3301ee6eca72e2da7da5bf1f8140 | 3,648,248 |
import re
def replace_empty_bracket(tokens):
"""
Remove empty bracket
:param tokens: List of tokens
:return: Fixed sequence
"""
merged = "".join(tokens)
find = re.search(r"\{\}", merged)
while find:
merged = re.sub(r"\{\}", "", merged)
find = re.search(r"\{\}", merged)
... | fd2c9f2f1c2e199056e89dbdba65f92e4d5834eb | 3,648,249 |
def presentation():
"""
This route is the final project and will be test
of all previously learned skills.
"""
return render_template("") | c592ae4b28c5c9b89592c3842e73c0e76cc4bd66 | 3,648,250 |
def extra_credit(grades,students,bonus):
"""
Returns a copy of grades with extra credit assigned
The dictionary returned adds a bonus to the grade of
every student whose netid is in the list students.
Parameter grades: The dictionary of student grades
Precondition: grades has netids as keys, i... | 334a9edb3d1d045832009e20c6cba7f24e5c181d | 3,648,251 |
def get_geo_signal_combos(data_source):
"""
Get list of geo type-signal type combinations that we expect to see.
Cross references based on combinations reported available by COVIDcast metadata.
"""
meta = covidcast.metadata()
source_meta = meta[meta['data_source'] == data_source]
# Need to ... | 90d030372b3e7d9ed2de0d53b6aa42fdf3723355 | 3,648,252 |
def absolute_(x, track_types = True, **kwargs):
"""Compute the absolute value of x.
Parameters
----------
x : :obj:`xarray.DataArray`
Data cube containing the values to apply the operator to.
track_types : :obj:`bool`
Should the operator promote the value type of the output object, based
... | b88c6662890832b0d54f752e59c97c9a9ca9ceb5 | 3,648,253 |
def any_input(sys_, t, input_signal=0, init_cond=None, *, plot=True):
"""
Accept any input signal, then calculate the response of the system.
:param sys_: the system
:type sys_: TransferFunction | StateSpace
:param t: time
:type t: array_like
:param input_signal: input signal accepted by th... | fc6d72b5c22d585a4ba7c5be895b1266e72e70dd | 3,648,254 |
import os
def get_combinations(suite_dir, fields, subset,
limit, filter_in, filter_out,
include_facet):
"""
Describes the combinations of a suite, optionally limiting
or filtering output based on the given parameters. Includes
columns for the subsuite and face... | 27fa774468b8fcb8aa34579ab0e1868375d7683e | 3,648,255 |
from .mnext import mnext
def mnext_mbv2_cfg(pretrained=False,in_chans=3,drop_rate=0.2,drop_connect_rate=0.5,bn_tf=False,bn_momentum=0.9,bn_eps=0.001, global_pool=False, **kwargs):
"""Creates a MNeXt Large model. Tensorflow compatible variant
"""
model = mnext(**kwargs)
return model | 5f8fcdcaa6abf4047b4fc06ea7dcb92f6fbeade7 | 3,648,256 |
def _embeddings_from_arguments(column,
args,
weight_collections,
trainable,
output_rank=2):
"""Returns embeddings for a column based on the computed arguments.
Args:
column: the column nam... | 30c305bfbf20d48af48dd25aa32c1648f8f95fce | 3,648,257 |
def stuw_laagstedoorstroombreedte(damo_gdf=None, obj=None, damo_doorstroombreedte="DOORSTROOMBREEDTE",
damo_kruinvorm="WS_KRUINVORM"):
"""
als LAAGSTEDOORSTROOMHOOGTE is NULL en WS_KRUINVORM =3 (rechthoek) dan LAAGSTEDOORSTROOMBREEDTE = DOORSTROOMBREEDTE
"""
return damo... | 534d917326222ef77fc0a8022ed84ea08bb0be0a | 3,648,258 |
def manage_categories():
"""
Display all categories to manage categories page (admin only)
"""
# Denied user access to manage_categories page
if session["user"] != "admin":
return redirect(url_for('error', code=403))
# query for all categories from categories collection
manage_categ... | 5002375f904240f2274aa8040b426da8515122a7 | 3,648,259 |
def callback(id):
"""
获取指定记录
"""
# 检查用户权限
_common_logic.check_user_power()
_positions_logic = positions_logic.PositionsLogic()
# 读取记录
result = _positions_logic.get_model_for_cache(id)
if result:
# 直接输出json
return web_helper.return_msg(0, '成功', result)
else:
... | 3451cc1ebb18004f46847f6538c751afd86bdf74 | 3,648,260 |
import json
def setup_exps_rllib(flow_params,
n_cpus,
n_rollouts):
"""Return the relevant components of an RLlib experiment.
Parameters
----------
flow_params : dict
flow-specific parameters (see flow/utils/registry.py)
n_cpus : int
number... | af4f1bb6a11b2502efcfae77ae7dbaf4bb30c1b3 | 3,648,261 |
def sort_cluster(x: list, t: np.ndarray) -> list:
"""
sort x according to t
:param x:
:param t:
:return:
"""
return [x[i] for i in np.argsort(t)] | a2bcd57bb9c402aa19f12483e792f1e4379c4481 | 3,648,262 |
def gettof(*args):
"""gettof(flags_t F) -> ushort"""
return _idaapi.gettof(*args) | d377fc28b7515a45112083fc38c722b82caee0b9 | 3,648,263 |
def generate(temp):
"""
Wrapper that checks generated names against the base street names to avoid a direct
regurgitation of input data.
returns list
"""
is_in_dict = True
while is_in_dict:
result = textgen.generate(temperature=temp, return_as_list=True)
str = ' '.join(result... | 2bfc6d366d0543d6ada762539c0c6cb301d729a8 | 3,648,264 |
import re
def __create_pyramid_features(backbone_dict,
ndim=2,
feature_size=256,
include_final_layers=True,
lite=False,
upsample_type='upsamplelike',
... | 956a04a1ebe14e11061de009894b27e7c2640cb2 | 3,648,265 |
def graphviz(self, filename=None, directory=None, isEdge=False,showLabel=True, **kwargs):
"""Return graphviz source for visualizing the lattice graph."""
return lattice(self, filename, directory, isEdge, showLabel, **kwargs) | 1c7426efe0f0379822c4c9c0a765a615f26f04a1 | 3,648,266 |
def get_rectangle(origin, end):
"""Return all points of rectangle contained by origin and end."""
size_x = abs(origin[0]-end[0])+1
size_y = abs(origin[1]-end[1])+1
rectangle = []
for x in range(size_x):
for y in range(size_y):
rectangle.append((origin[0]+x, origin[1]+y))
retu... | 36badfd8aefaaeda806215b02ed6e92fce6509a3 | 3,648,267 |
def corr_list(df, target, thresh=0.1, sort=True, fill=True):
"""
List Most Correlated Features
Returns a pandas Series with the most correlated features to a certain
target variable. The function will return features with a correlation value
bigger than some threshold, which can be adjusted.
P... | d9562d1bbc7947338cf87ddc6703ef54a21554e0 | 3,648,268 |
def compute_epsilon(steps):
"""Computes epsilon value for given hyperparameters."""
if FLAGS.noise_multiplier == 0.0:
return float('inf')
orders = [1 + x / 10. for x in range(1, 100)] + list(range(12, 64))
sampling_probability = FLAGS.batch_size / NUM_TRAIN_EXAMPLES
rdp = compute_rdp(q=sampling_probabilit... | 9819cafafeec66cd29b13a916432c839e4365ded | 3,648,269 |
def get_native_includes(object):
"""
After method association, check which native types an object uses
and return a corresponding string list of include file
This will also add the include needed for inheritance
"""
includes = set()
for proc in object.procs:
for argname,arg in proc.... | 0c09d39bd61b5a711bd718dcb38fab7e4e1e01bf | 3,648,270 |
from sys import path
def libraries_data_path():
"""
Path to Packages/User/Deviot/pio/libraries.json
"""
user_data = user_pio_path()
return path.join(user_data, 'libraries.json') | 1e60f00544d8008bf44b47536ed19ebdc32bed33 | 3,648,271 |
import torch
def dice_coeff(input, target):
"""Dice coeff for batches"""
if input.is_cuda:
s = torch.FloatTensor(1).to(device_f).zero_()
else:
s = torch.FloatTensor(1).zero_()
for i, c in enumerate(zip(input, target)):
s = s + DiceCoeff().forward(c[0], c[1])
return s / (i... | da390729d2e1d8e2ae53814f8ac398a6c7e5380a | 3,648,272 |
def group_error_rates(labels, predictions, groups):
"""Returns a list containing error rates for each protected group."""
errors = []
for jj in range(groups.shape[1]):
if groups[:, jj].sum() == 0: # Group is empty?
errors.append(0.0)
else:
signed_labels_jj = 2 * labels[groups[:, jj] == 1] - 1... | 0b390dfde16910332f10afacaa2f9031c04d846a | 3,648,273 |
def get_emails_by_user_names(user_names):
"""Get emails by user names."""
emails_service = emails_digest_service.DailyEmailsService()
emails_service.open_emails_digest()
user_emails_dict = dict.fromkeys(user_names)
for user_name in user_names:
user_emails_dict[user_name] = emails_service.get_email_by_user... | 331d5799bac79c08240770260306ba84bf2f568b | 3,648,274 |
def inbound_and_outbound_node_sets(C, CT):
"""
Returns the set of nodes that can reach an event and can be reached by an event,
and the difference between those sets (outbound / inbound).
"""
inbound = defaultdict(set)
for node, event in zip(*np.nonzero(C)):
inbound[event].add(node)
outbound = defaultdic... | 517746700a7a978a49a597237db362eee98d91b6 | 3,648,275 |
def policy(Q):
"""Hard max over prescriptions
Params:
-------
* Q: dictionary of dictionaries
Nested dictionary representing a table
Returns:
-------
* policy: dictonary of states to policies
"""
pol = {}
for s in Q:
pol[s] = max(Q[s].items(), key=lambda... | e69f66fba94b025034e03428a5e93ba1b95918e8 | 3,648,276 |
def fft(series):
"""
FFT of a series
Parameters
----------
series
Returns
-------
"""
signal = series.values
time = series.index
dt = np.mean(np.diff(time))
#n = 11*len(time)
n = 50000
frequencies = np.fft.rfftfreq(n=n, d=dt) # [Hz]
dft = np.abs(np.fft.rf... | a6d1f7cfa45d504a86b434702a49eafa08737006 | 3,648,277 |
def local_variance(V, tsize=5):
""" local non-linear variance calculation
Parameters
----------
V : numpy.array, size=(m,n), dtype=float
array with one velocity component, all algorithms are indepent of their
axis.
Parameters
----------
sig_V : numpy.array, size=(m,n), dtyp... | e7e10f8c73f01b20a27ad06813defdd406bf977a | 3,648,278 |
def get_virtual_device_configuration(device):
"""Get the virtual device configuration for a PhysicalDevice.
Returns the list of VirtualDeviceConfiguration objects previously configured
by a call to `tf.config.experimental.set_virtual_device_configuration()`.
For example:
>>> physical_devices = tf.config.ex... | 49a99c17c2859bb40a7bfbbac840bf82310428e1 | 3,648,279 |
def user_directory_path(instance, filename):
"""Sets path to user uploads to: MEDIA_ROOT/user_<id>/<filename>"""
return f"user_{instance.user.id}/{filename}" | 84be5fe74fa5059c023d746b2a0ff6e32c14c10d | 3,648,280 |
def setup(app):
"""Setup the Sphinx extension."""
# Register builder.
app.add_builder(BeamerBuilder)
# Add setting for allowframebreaks.
app.add_config_value("beamer_allowframebreaks", True, "beamer")
# Add setting for Beamer theme.
app.add_config_value("beamer_theme", "Warsaw", "beamer")
... | cc5f48eeff65876a2d052dad285a77bc76e115c0 | 3,648,281 |
def extract_text(arg: Message_T) -> str:
"""
提取消息中的纯文本部分(使用空格合并纯文本消息段)。
参数:
arg (nonebot.typing.Message_T):
"""
arg_as_msg = Message(arg)
return arg_as_msg.extract_plain_text() | 06d19c9ca4e907edf433f910600161d142ca914e | 3,648,282 |
def dtw(x, y, dist, warp=1):
"""
Computes Dynamic Time Warping (DTW) of two sequences.
:param array x: N1*M array
:param array y: N2*M array
:param func dist: distance used as cost measure
:param int warp: how many shifts are computed.
Returns the minimum distance, the cost matrix, the accum... | a30a492d816e5234590d9fadfbba722db0ae9f72 | 3,648,283 |
def format_line_count_break(padding: int) -> str:
"""Return the line count break."""
return format_text(
" " * max(0, padding - len("...")) + "...\n", STYLE["detector_line_start"]
) | 2fe4d4b8195468787f31b3407d32a4e039f7bb6c | 3,648,284 |
from typing import Tuple
from typing import get_args
def identify_generic_specialization_types(
cls: type, generic_class: type
) -> Tuple[type, ...]:
"""
Identify the types of the specialization of generic class the class cls derives from.
:param cls: class which derives from a specialization of gene... | 3932062a5a4543b280ebc8601126e10d11136717 | 3,648,285 |
def Metadata():
"""Get a singleton that fetches GCE metadata.
Returns:
_GCEMetadata, An object used to collect information from the GCE metadata
server.
"""
def _CreateMetadata(unused_none):
global _metadata
if not _metadata:
_metadata = _GCEMetadata()
_metadata_lock.lock(function=_Crea... | 096ac4f0278e0048944d5a10c4153be7c60aae88 | 3,648,286 |
def pa11y_counts(results):
"""
Given a list of pa11y results, return three integers:
number of errors, number of warnings, and number of notices.
"""
num_error = 0
num_warning = 0
num_notice = 0
for result in results:
if result['type'] == 'error':
num_error += 1
... | 346c1efe0cae5934e623a8643b0f23f85300181d | 3,648,287 |
def parse_properties(df, columns_to_integer=None, columns_to_datetime=None, columns_to_numeric=None, columns_to_boolean=None, columns_to_string = None, dt_unit = 'ms', boolean_dict = {'true': True, 'false': False, '': None}):
"""
Parse string columns to other formats. This function is used in hubspot routine, it... | a162397308d98faac6ab24f07aceee439aa32095 | 3,648,288 |
import requests
def http_request(method, url, headers, data=None):
"""
Request util
:param method: GET or POST or PUT
:param url: url
:param headers: headers
:param data: optional data (needed for POST)
:return: response text
"""
response = requests.request(method, url, headers=hea... | 6d0453be79b3ae0f7ed60b5a8759b9295365dd6c | 3,648,289 |
import time
def beNice(obj):
"""Be nice : exponential backoff when over quota"""
wait = 1
while wait :
try :
return_value = obj.execute()
wait = 0
except : #FIXME : we should test the type of the exception
print("EXCEPT : Wait for %d seconds" % wait)
... | a68d4369c02ec37c48518a109f8c27fa1e014aa3 | 3,648,290 |
def parse_title(line):
"""if this is title, return Tuple[level, content],
@type line: str
@return: Optional[Tuple[level, content]]
"""
line = line.strip()
if not line.startswith('#'):
return None
sharp_count = 0
for c in line:
if c == '#':
sharp_count += 1
... | 7c170f417755c878d225b780b8475a379501c19f | 3,648,291 |
import typing
def issubtype(cls: type, clsinfo: type) -> bool:
"""
Return whether ``cls`` is a subclass of ``clsinfo`` while also considering
generics.
:param cls: the subject.
:param clsinfo: the object.
:return: True if ``cls`` is a subclass of ``clsinfo`` considering generics.
"""
i... | 942d5760c3de4d63bcd9c3f5934fcc89727dc958 | 3,648,292 |
def delete_status(id):
"""Delete an existing status
The status to be deleted should be posted as JSON using
'application/json as the content type. The posted JSON needs to
have 2 required fields:
* user (the username)
* api_key
An example of the JSON::
{
"user": "r1ck... | d6a9ebbc787283f3ac247935f3fe5ad9080d2bd0 | 3,648,293 |
def process_data(data):
""" Change labels, group by planner and format for latex."""
data = data.replace(
{
"grid_run_1": "Grid",
"prm_run_1": "PRM A",
"prm_run_2": "PRM B",
"prm_run_3": "PRM C",
}
)
data = data.rename(
columns={"n... | 24ac1c2ee872c5051eccc9774943f922671267b1 | 3,648,294 |
def detect_outlier(TS, samples_wind=60, order=3):
"""Find outliers in TS by interpolate one sample at a time, measure diff.
between rec. sample and interpolated, and getting the peaks in the int diff
across recording.
Parameters
-------------
TS : array (x, y) x n_samples
Times ser... | 91515770554155ddb0da507e94e4cffc611202d9 | 3,648,295 |
def postprocess(backpointers, best_tag_id):
"""Do postprocess."""
best_tag_id = best_tag_id.asnumpy()
batch_size = len(best_tag_id)
best_path = []
for i in range(batch_size):
best_path.append([])
best_local_id = best_tag_id[i]
best_path[-1].append(best_local_id)
for b... | 5be856610a3c81453c11c584507dcb4ad0e4cf61 | 3,648,296 |
def carnatic_string_to_ql_array(string_):
"""
:param str string_: A string of carnatic durations separated by spaces.
:return: The input string converted to a quarter length array.
:rtype: numpy.array.
>>> carnatic_string_to_ql_array('oc o | | Sc S o o o')
array([0.375, 0.25 , 0.5 , 0.5 , 1.5 , 1. , 0.25 , ... | 19386ac13233c3f5cc70eea7f75d287784f6a969 | 3,648,297 |
import tqdm
import json
import os
def get_examples(fpath, doc_dir, max_seq_len=-1, max_sent_num=200, sent_level=True):
"""
Get data from tsv files.
Input:
fpath -- the file path.
Assume number of classes = 2
Output:
ts -- a list of strings (each contain the text)
... | 54c1743528d27e9c2a2dbf176172a29c2ab48d50 | 3,648,298 |
def login_redirect(request: HttpRequest) -> HttpResponse:
"""
Redirects the user to the Strava authorization page
:param request: HttpRequest
:return: HttpResponse
"""
strava_uri = get_strava_uri()
return redirect(strava_uri) | 80eb714ab8f1fde25f2a3ce57bdc540a5a7a980d | 3,648,299 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.