content stringlengths 35 762k | sha1 stringlengths 40 40 | id int64 0 3.66M |
|---|---|---|
from typing import Tuple
from typing import Optional
def _make_generic_sql_bound(
bound: str,
column_names: Tuple[str, str],
values: Tuple[Optional[int], int],
engine: BaseDatabaseEngine,
) -> str:
"""Create an SQL expression that bounds the given column names by the
values, e.g. create the eq... | 5575c25b78d4176f9be14b4410eee29ccb29347f | 67,500 |
import bisect
def add_domain_parallel(updated_mask, lb, ub, lb_all, up_all, domains, selected_domains, slope, growth_rate=0,
branching_decision=None, save_tree=False, decision_thresh=0):
"""
Use binary search to add the new domain `candidate`
to the candidate list `domains` so that... | 80b1a2a53694fff56584854e28ad0db82fadbc91 | 67,501 |
import xloil_core
def get_event_loop():
"""
Returns the background asyncio event loop used to load the current add-in.
Unless specified in the settings, all add-ins are loaded in the same thread
and event loop.
"""
addin = source_addin()
return xloil_core.get_event_loop(addi... | 4ee0c6c5b495dcb0d0c8fbca43cb28a747a1056d | 67,502 |
import socket
import re
def write_handler(host, port, element, handler, value):
"""Write to a click handler."""
sock = socket.socket()
sock.connect((host, port))
f_hand = sock.makefile()
line = f_hand.readline()
if line != "Click::ControlSocket/1.3\n":
raise ValueError("Unexpected r... | ace3954a1893b6f3637332ad799be00c5d36e3c5 | 67,503 |
def register(request):
"""Faz o cadastro de um novo usuário"""
if request.method != 'POST':
# Exibe o formulário de cadastro em branco
form = UserCreationForm()
else:
# Processa o formulário preenchido
form = UserCreationForm(data=request.POST)
if form.is_val... | 136f3b2413745b5d1be3d333e538c82cc7a09e9e | 67,504 |
import copy
def set_quantization_configuration_to_graph(graph: Graph,
quant_config: QuantizationConfig,
fw_info: FrameworkInfo) -> Graph:
"""
Add quantization configuration for each graph node.
Args:
graph: Gr... | fbcdbf47cdd119a26a0a04b1b4032f8fec7eb961 | 67,505 |
from cascade_at.dismod.api.dismod_io import DismodIO
import os
import subprocess
def run_dismod(dm_file: str, command: str):
"""
Executes a command on a dismod file.
Parameters
----------
dm_file
the dismod db filepath
command
a command to run
"""
def check_last_comman... | b0af29d9ee75a84567feefba225f5056ce0a8fe7 | 67,506 |
def snowballstem(context_word_list):
"""Use nltk and Snowball stemmer to stem."""
#print("Stemming using Snowball Stemmer")
#texts_gen = back_to_string(texts)
# KEEP ONLY NOUNS, ADJ, VERB, ADV
return [snowball.stem(word) for word in context_word_list] | 6745704fb7412009b519bebdc30fa3da40a8c325 | 67,507 |
from typing import Optional
import os
def get_odir_res(eval_ds, args, ssvm_model_idx: Optional[int] = None) -> str:
"""
Generate the output directory given the evaluation parameters.
:param eval_ds:
:param args: argparse.Namespace, command line interface arguments
:param ssvm_model_idx: scalar, i... | d1946fd99e578d7536fb040d4e50c2c91210a0f2 | 67,508 |
from typing import Union
from typing import Tuple
def _make_version(version: Union[str,int,Tuple[int]]) -> Tuple[int]:
"""Build a tuple-of-integer version from a string or a unique integer.
:param version: the version to convert, if needed
:return: the tuple-based version
"""
try:
i... | 2c8b05f9ae77657aae84f400c927fb8b2924c78c | 67,509 |
import logging
def file_getchild( gateway, volume, parent_id, name ):
"""
Get all metadata for a file, given the its parent ID and name.
"""
logging.info("getchild /%s/%s/%s" % (volume.volume_id, parent_id, name) )
owner_id = msconfig.GATEWAY_ID_ANON
if gateway != None:
owner_id = gate... | a906aad0bc9db097b5fc6e5e19e9c166b621b87d | 67,510 |
def __convert_timecode(timecode):
"""
Takes a timecode value that's either a string or a number and returns it
back in a number format.
"""
if isinstance(timecode, str):
try:
t = timecode.split(":")
if len(t) == 2: t.insert(0, "0")
return (int(t[0]) * 60 ... | 500e137836db417ff6512c5ff7076abf89b01a28 | 67,511 |
def rig_reg_drift(dset, rel_drift):
""" Shifting images on top of each other
Uses relative drift to shift images on top of each other,
with center image as reference.
Shifting is done with shift routine of ndimage from scipy.
This function is used by rigid_registration routine
Parameters
-... | 29601ef4facf9068d47de29eeb431c965677d404 | 67,512 |
def readme():
"""Returns the contents of the README without the header image."""
header = '======\nGimbal\n======\n'
with open('README.rst', 'r') as f:
f.readline()
return header + f.read() | 892100a63287917a35850258c677ee53ee2883a0 | 67,513 |
def init_lstm(params, prefix='lstm', nin=None, dim=None, init='glorot',
learn_init=True):
"""
Initialize the LSTM parameters.
"""
assert nin > 0, 'nin should be provided'
assert dim > 0, 'dim should be provided'
logger.info('nin: {} dim: {}'.format(nin, dim))
initializer = u... | 9de497d936c8e01da2890743dbf07895ce792875 | 67,514 |
def ApplicationError(e):
"""Return a custom 500 error."""
return 'Sorry, unexpected error: {}'.format(e), 499 | 96d877b89948a58997a11f5f77b4247fe3c6eeac | 67,515 |
def make_sm_update_status_job(
b: Batch, analysis_type: str, status: str, sm_db_name: str, analysis_id: str
) -> Job:
"""
Creates a job that updates the sample metadata server entry analysis status.
"""
assert status in ['in-progress', 'failed', 'completed', 'queued']
j = b.new_job(f'SM: update ... | 59df34ee6db8d91c81318924819cda405bd20303 | 67,516 |
from typing import Callable
from typing import Mapping
def assembly_sub_strategy_factory_for_book_then_lang(
usfm_resources: list[USFMResource],
tn_resources: list[TNResource],
tq_resources: list[TQResource],
tw_resources: list[TWResource],
ta_resources: list[TAResource],
assembly_substrategy_... | 6e74db1ece469523f4a86b5b8e0f501003bc23ad | 67,517 |
from typing import Counter
import random
def stratified_group_k_fold(X, y, groups, k, seed=None) -> (list, list):
"""StratifiedKFoldで分割する関数
Args:
X (pd.DataFrame): trainデータ
y (pd.DataFrame): 目的変数のDF
groups (pd.DataFrame): groupに指定するカラムのDF
k (int): k数
seed (int): seet. ... | cfa4766d047eec36e835ac83b0bb764f7af9a2eb | 67,518 |
def load_images(image_files: list, input_width: int, input_height: int, data_type=np.uint8,
scale: float = 1., mean: list = [0., 0., 0.], stddev: list = [1., 1., 1.],
preprocess_fn=preprocess_default):
"""Loads images, resizes and performs any additional preprocessing to run inferenc... | b4ab3d4dd059f34d5177df6f1743dcc3f6c6ac9e | 67,519 |
def browser(wsgi_app, verwalter):
"""Get a zope.testbrowser for the WSGI-APP."""
return sw.allotmentclub.browser.testing.Browser(wsgi_app=wsgi_app) | 5247993c5587fa4acf7cc6c8c752c4e8eee22bc1 | 67,520 |
def get_one_csv(df):
"""Prepare DataFrame.
__Attributes__
df: DataFrame with parsed data.
__Returns__
df: DataFrame sorted by date abd without duplicates.
"""
# 3:19 PM 13/12/2018
# Change datetime format to what we want (example above)
df['date'] = df['date'].str.strip().... | 0c6ba26f017b47589cf85164bda70ff17dce5ae9 | 67,521 |
def get(expr, key, default=None):
"""
Return the mapped value for this key, or the default
if the key does not exist
Parameters
----------
key : any
default : any
"""
return ops.MapValueOrDefaultForKey(expr, key, default).to_expr() | 1b2e3a8e0d47e5d9512651b840e06c1baba0028c | 67,522 |
from typing import List
import re
def articles_from_file(file_path: str) -> List[WikitextArticle]:
"""Read wikitext articles from file.
Args:
file_path: path to the input `.tokens` file.
Returns:
A list of `WikitextArticle` tuples.
"""
with open(file_path, mode='rb') as f:
content = f.read()
... | 1c8c93e4f781ceeaf27f3fb9362b37ca1f2b1168 | 67,523 |
def get_mt(
mt_path: str,
split: bool = False,
hard_filtered_samples_to_remove_ht: hl.Table = None,
meta_ht: hl.Table = None,
add_meta: bool = False,
release_only: bool = False,
passing_sites_only: bool = False,
unrelated_only: bool = False,
) -> hl.MatrixTable:
"""
Wrapper funct... | ca34e4c1e0a5a5b19270f8015ae1a07b138ab205 | 67,524 |
import itertools
def gen_graphs(n_graphs, n_nodes, p_intra=0.7, p_inter=0.01):
"""
Generate community graphs.
"""
A = np.zeros((n_graphs, n_nodes, n_nodes))
for idx in range(n_graphs):
comms = [nx.gnp_random_graph(n_nodes // 2, p_intra),
nx.gnp_random_graph((n_nodes + 1) /... | 218793c6a29b675807b7180e6507d40fce5fe6de | 67,525 |
def wallis_product(n_terms):
"""Implement the Wallis product to compute an approximation of pi.
See:
https://en.wikipedia.org/wiki/Wallis_product
XXX : write Parameters and Returns sections as above.
"""
# XXX : The n_terms is an int that corresponds to the number of
# terms in the produc... | 1e0ba6bbb9ec5fd9de1d4ee84448402801fdb514 | 67,526 |
def num_executors(sc):
"""
Get the number of executors configured for Jupyter
:param sc: The SparkContext to take the executors from.
:type sc: [SparkContext
:return: Number of configured executors for Jupyter
:rtype: int
"""
return EnvSing.get_instance().get_executors(sc) | 2a18204f17f31fb8ed07d1cacf3ef30d6930b890 | 67,527 |
import struct
def read_zygo_metadata(file_contents):
"""Parse metadata from the contents of a binary Zygo file.
Parameters
----------
file_contents : `bytes`
binary file contents
Returns
-------
`dict`
dictionary with a shitload of keys for all of Zygo's metadata.
""... | 23f20e8ffa3c248cde535b2b2fc2d5a4a2fd2884 | 67,528 |
def bbox_iou2(box1, box2):
"""
Returns the IoU of two bounding boxes
"""
b1_x1, b1_x2 = box1[0], box1[2]
b1_y1, b1_y2 = box1[1], box1[3]
b2_x1, b2_x2 = box2[0] - box2[2] / 2, box2[0] + box2[2] / 2
b2_y1, b2_y2 = box2[1] - box2[3] / 2, box2[1] + box2[3] / 2
# get the corrdinates of the i... | e466a3277c0f0ddd55651c4352d026bb106367fc | 67,529 |
import os
def load_images_map(images_dir):
"""From all face images, produce an easy lookup table.
Format: {frame_index1: set(bbs_tuple1, bbs_tuple2, etc...)}
"""
_, _, files = next(os.walk(images_dir))
# facerec image file format: <movie_id>:<frame_i>:x1_y1_x2_y2.jpeg
image_map = {}
for ... | 691a5b3a03af4dcd14ce08ba33326b6d33d1f927 | 67,530 |
def parse_validator(validator):
""" parse validator
Args:
validator (dict): validator maybe in two formats:
format1: this is kept for compatiblity with the previous versions.
{"check": "status_code", "comparator": "eq", "expect": 201}
{"check": "$resp_body_s... | f97cb8e0d538f6d0a9308541b42d2334733bf6b2 | 67,531 |
import uuid
def AjaxSubForm(form_cls, slug, **kwargs):
"""
Helper method for modifying one form to act as a sub-form to a parent-form.
"""
_id = str(uuid.uuid4()).replace('-', '')
new_cls = type(str('_%s_%s' % (form_cls.__name__, _id)), (
form_cls,), {'extra': kwargs.get('extra', 0)})
... | 095ba1886958c3a13ff35eed7cf39b23f157f0ec | 67,532 |
def BTAZI2BQBU(Bt,azi):
"""Transformation from transverse field and azimuth to BQ and BU
according to https://arxiv.org/abs/1904.03714
Parameters
----------
Bt, azi : float
Values to be transformed
"""
By = Bt*np.sin(azi)
Bx = Bt*np.cos(azi)
BQ = np.sign(Bx**2.-By**2.)*np.sq... | eb29d33a55170950bfc6618a55ef38e2cf7e07e6 | 67,533 |
def random_phase_vector(s, n, rand_state=None):
"""
Generates a uniformly random phase vector for a n-qubit Clifford.
(This vector, together with the provided symplectic matrix, define a valid
Clifford operation.) In combination with a uniformly random `s` the returned `p`
defines a uniformly rand... | 2565696b4ec5b7a07030fee17eaaa194938bb1ed | 67,534 |
def rewrite_arcs (label_map, nfa):
"""Rewrite the label arcs in a NFA according to the input remapping."""
states = [[(label_map[label], tostate) for (label, tostate) in arcs]
for arcs in nfa[2]]
return (nfa[0], nfa[1], states, nfa[3], nfa[4]) | 2bd9911a5c65ce7711848746614a3a6ceb37f8d2 | 67,535 |
def create_fig(image, canvas_list, obj_enc_list, obj_dec_list, z_pres_list, z_prob_list, z_where_list):
"""
All types should be numpy or python numbers.
"""
fig = plt.figure()
for i in range(3):
ax = fig.add_subplot(4, 3, i + 1)
ax.set_title('pres: {:.0f}, p: {:.2f}'.format(z_pres_li... | eb7c805d302e9ee90766e2f2fe59356cb8f16c7e | 67,536 |
from typing import List
from typing import Tuple
def _details_family_code() -> List[Tuple]:
"""Details for logging FamilyCode."""
return [
("AccountID", dht.string, lambda fc: fc.accountID),
("FamilyCode", dht.string, lambda fc: fc.familyCodeStr),
] | bcae9a044bb44b1390ee066225d04db2882d4537 | 67,537 |
import copy
def merge_params(base_params, partial_params=None):
"""Merge a partial change to the base configuration.
Parameters
----------
base_params
The base parameters
partial_params
The partial parameters
Returns
-------
final_params
The final parameters
... | 4c52d492358106b7c5e6df0c1e099d45043a7935 | 67,538 |
def date_message(date_str: str) -> str:
"""Return a message about the date."""
# Get location
location = get_location(date_str)
# Get the current date
date = get_time_by_lat_long(location)
return f"The date in {location} is {date.strftime('%a %d %b')}." | b9f71253fddad95a2ce877358d7f7ec4e0ff7585 | 67,539 |
def modified_cartesian(*args, **kwargs):
"""Modified Cartesian product.
This takes two (or more) lists and returns their Cartesian product.
If one of two list is empty this function returns the non-empty one.
Parameters
-----------
*args : lists, length : two or more
The group of input... | fa0f6830dcffb79c6e2a895458495458b6d62e07 | 67,540 |
def get_person(person_id):
"""Get information about a person."""
try:
with Session(DB.engine) as session:
person = session.query(Person).where(Person.id == person_id).one()
return {"person_id": person.id, "name": person.name, "email": person.email}
except NoResultFound:
... | e667f8b54d608847e7cbee553b1e5bc3e4dcda4c | 67,541 |
def execute_query(query, db):
"""
Executes a query
Arguments:
query - the query to execute
db - the database to execute the query on ("users" or "products")
"""
# Create tables if they don't exist
create_products_table()
create_user_table()
# Connect to tables
users_d... | b0a944e9030177132598785e810af121c8bbbb25 | 67,542 |
def parse_variant(
store,
institute_obj,
case_obj,
variant_obj,
update=False,
genome_build="37",
get_compounds=True,
case_dismissed_vars=[],
):
"""Parse information about variants.
- Adds information about compounds
- Updates the information about compounds if necessary and '... | 5af1283ba64ddd6325e15a18d74de777b4669400 | 67,543 |
def create_dicts_same_nodes(my_set, neighbors_dict, node, dict_out, dict_in):
"""
A function to create useful dictionaries to represent connections between nodes that have the same type, i.e between
nodes that are in the embedding and between nodes that aren't in the embedding. It depends on the input.
... | c4ef94964f2944dcbddd79f76182a4bcc64633e7 | 67,544 |
import json
def get_china_province(ChinaTotal, ChinaProvince):
"""
获取最新国内各省数据
:return:
"""
return json.dumps(inner_get_china_province(ChinaTotal, ChinaProvince), ensure_ascii=False) | a13c22808bedcccbf4d8faba7229fb7b303bd878 | 67,545 |
import torch
import logging
import pickle
def evaluate(model, loss_fn, data_iterator, metrics, params, num_steps, sample_weights=None):
"""Evaluate the model on `num_steps` batches.
Args:
model: (torch.nn.Module) the neural network superclass
loss_fn: a function that takes batch_output and bat... | 3e3cf80f1b26c42da5cbfc802c54d9587dfacc7d | 67,546 |
def plaquette_spanning_tree(lattice: Lattice, shortest_edges_only = True):
"""Given a lattice this returns a list of edges that form a spanning tree over all the plaquettes (aka a spanning tree of the dual lattice!)
The optional argument shortest_edge_only automatically sorts the edges to ensure that only the s... | 9a83a8743244331e62a3447a3b370a70b8decc14 | 67,547 |
def check_params():
"""
Check all the CLI inputs. Must give INSTALLER_TYPE, INSTALLER_IP, user
and filepath of the output file.
Need to give key or password.
"""
if not args.INSTALLER_TYPE or not args.INSTALLER_IP or not args.user:
print("INSTALLER_TYPE, INSTALLER_IP and user are all nee... | abced80ef2cc12b0615bd612051a2c728014cab9 | 67,548 |
def flatten(list_of_lists):
"""Single level flattening of a list."""
return sum((list(sublist) for sublist in list_of_lists), []) | d7a2b9b75a1bd920f50d78cc725f8e551d6bb2f5 | 67,549 |
def get_num_channels(x):
"""
:param x: an input tensor with shape [batch_size, ..., num_channels]
:return: the number of channels of x
"""
return int(x.get_shape()[-1]) | 6016098ae8cea31ddf902f6c6e8c4b45d2d114ae | 67,550 |
def get_movements(
key: dict,
tracking: pd.DataFrame,
moving_threshold: float,
turning_threshold: float,
paw_speed_th=10,
) -> dict:
"""
Creates array indicating when the mouse is doing different kinds of movements
"""
paws = tracking.loc[
tracking.bpname.isin(["left_fl"... | c8c65c46fecdce61341b701d12e52dce24fe1b6a | 67,551 |
from typing import Type
from typing import Optional
def _get_inner_meta_class(struct_class: Type[Struct]) -> Optional[Type]:
"""Retrieve the `Meta` inner class of a Struct class, or None if none is provided."""
if not hasattr(struct_class, _META_INNER_CLASS_NAME): # pytype: disable=wrong-arg-types
re... | f3933fca07fb1dbb82546539892160392e672045 | 67,552 |
def _get_init_fn():
"""Returns a function run by the chief worker to warm-start the training.
Note that the init_fn is only run when initializing the model during the very
first global step.
Returns:
An init function run by the supervisor.
"""
if FLAGS.checkpoint_path is None:
return None
# War... | 6d28bb269c460d143f6cb5999ec4030cc5bc3de7 | 67,553 |
def maximum() -> int:
"""Returns 9."""
return 9 | dfd9a240bdaf985f89ca1b90c2b6e01f5426b2b0 | 67,554 |
def input4FwdBkw(states: tuple, observation_labels: np.array, ts_array: np.array, pai: np.array,
transDist: np.array, emisDist: np.array, f: object) -> (dict, dict, dict):
"""
:param states:
:param observation_labels:
:param ts_array:
:param pai:
:param transDist:
:param em... | 39274416fdd84b1e43a9489c7a1d56b9190dc084 | 67,555 |
import types
def on(signals, callback=None, max_calls=None):
"""
Registers a single callback for receiving an event (or event list). Optionally,
can specify a maximum number of times the callback should receive a signal. This
method works as both a function and a decorator::
smokesignal.on('f... | 759ab43bed7bd865dc3cfe439575b03894aac30d | 67,556 |
def _only_target_vars(ds: xr.Dataset, data_vars: t.Optional[t.List[str]] = None) -> xr.Dataset:
"""If the user specifies target fields in the dataset, create a schema only from those fields."""
# If there are no restrictions on data vars, include the whole dataset.
if not data_vars:
logger.info(f't... | a4602be2d8957e2f1b1b94aac0ce3da0aa9eb6e0 | 67,557 |
def load_model_from_path(model_type, path):
"""
Loads a spark ml model from a path
:param str | AlgorithmEnum | ScalerEnum model_type: the string
representation of the model import, e.g.
`pyspark.ml.feature.StandardScaler`
:param str path:
:return:
"""
return class_from_str(model_typ... | b711751d332591b46b8f82fc24768c1a236f278e | 67,558 |
import tqdm
import itertools
def estimate_parameters(x,processes,total_reads,max_chunk_size):
"""Estimate parameters?
This copied over from the old old old PyFitSeq - dunno if still relevant
but it's missing in this version !!!
A SUB-FUNCTION CALLED BY MAIN FUNCTION main() TO CALCULATE THE LOG
... | 731fd8496f1993635f7c4b6399b861706651dfe6 | 67,559 |
def MagScatFac(El, SQ):
"""compute value of form factor
:param El: element dictionary defined in GetFormFactorCoeff
:param SQ: (sin-theta/lambda)**2
:param gfac: Lande g factor (normally = 2.0)
:return: real part of form factor
"""
mfa = np.array(El['mfa'])
mfb = np.array(El['mfb'])
... | 5469cd78b479d4b4be1225c5303231a069c8d980 | 67,560 |
def reduce(data, filename):
"""
Reduce the data given by the data string and the filename.
"""
#first decide what file type this is.
ext = filename.split(".")[1]
if ext == 'hfbs':
ret = hfbs_reduce(data,filename)
elif ext =='hscn':
ret = hscn_reduce(data,filename)
else:
... | 5a3a5b429c0d0cae094951cbe3c1c453e0e01454 | 67,561 |
from typing import cast
def get_c_struct_from_mechanism(python_dictionary, params_type_string):
"""Gets a c struct from a python dictionary representing that struct
:param python_dictionary: The python dictionary representing the C struct,
see :class:`CK_AES_CBC_PAD_EXTRACT_PARAMS` for an example
... | ba0857276223145e04dc41aaeb4c1bbbd49302ba | 67,562 |
def config():
""" Configuration file for edith usage """
config = {
"edith": { # don't change
"version": 1.0 # don't change
},
"config": { # change this
"host": "Raspberry Pi Zero WH", # change host to machine running program
"online serv... | 3c4adf4407311428be2c97fdc61dd636de63d760 | 67,563 |
def vectorize(hash_function, feature_dict=None, size=1024):
"""Helper function to vectorize a spatial description from a hash.
Hash functions are used to perform spatial featurizations in
DeepChem. However, it's necessary to convert backwards from
the hash function to feature vectors. This function aids in
t... | 3ecbb776ceb162841c83de3d96288fce6c9f551a | 67,564 |
def get_uniform_random_number(low, high):
"""
:param low: 均匀分布的下界
:param high: 均匀分布的上界
:return: 从均匀分布中产生的随机数
"""
# 均匀分布的随机数生成
number = np.random.uniform(low, high)
# 返回值
return number | 206704a81a35d71ecadc9a1e7db1ddcc38c8c981 | 67,565 |
import re
def get_person_info(person):
"""Try to determine gender, etc. from the most complete PERSON reference.
ARGS:
person (required) string: all or part of the person's full name
RETURNS:
dict containing discoverable PERSON attributes
TODO: Rewrite this in a spacy way
"""
... | 30934dddc2c2d94a6e683f09b00ba381bbbcae33 | 67,566 |
def bootstrapOneSampTest(data,nv=0,nullTranslation=None,statFunc=None,nPerms=10000):
"""Uses a bootstrap to calculate a p-value for a
one sample test of H0: mean(data) != nv
Uses a t-statistic as is used in Efron and Tibshirani"""
L=len(data)
if statFunc is None:
statFunc = lambda data: (np... | caff773b1fbb7f98d21e78da98f9436a40a45312 | 67,567 |
def center_time(ds):
"""make time the center of the time bounds"""
ds = ds.copy()
attrs = ds.time.attrs
encoding = ds.time.encoding
tb_name, tb_dim = _get_tb_name_and_tb_dim(ds)
ds["time"] = ds[tb_name].compute().mean(tb_dim).squeeze()
attrs["note"] = f"time recomputed as {tb_name}.mean({tb... | f0b5d72c59757954495a93c74c392d20bfa5e17b | 67,568 |
from typing import List
import logging
def download_conversations_history(
client, channel: str, page_limit: int,
latest_unix_time: float, oldest_unix_time: float) -> List[dict]:
"""download Slack Web API conversations.list response.
Returns:
List of dict{"channel":ccc, "message":{ ...... | 1778400a61c4de1492fd77e891a28cea1778b72f | 67,569 |
import ctypes
def vdistg(v1, v2, ndim):
"""
Return the distance between two vectors of arbitrary dimension.
http://naif.jpl.nasa.gov/pub/naif/toolkit_docs/C/cspice/vdistg_c.html
:param v1: ndim-dimensional double precision vector.
:type v1: list[ndim]
:param v2: ndim-dimensional double prec... | 8081e9058a20ebf717dd87757050328cedee4f3a | 67,570 |
def cos_between_vects_batch(v1, v2):
"""
Returns the cosine angle between vectors 'v1' and 'v2'
:param v1: N,C
:param v2: N,C
:return N,
"""
v1_u = v1 / np.linalg.norm(v1, axis=1).reshape(-1, 1) # N,C
v2_u = v2 / np.linalg.norm(v2, axis=1).reshape(-1, 1)
dots = np.sum(v1_u * v2_u, ... | 55e5efc445c27316851a8df701d7d4eba406c31d | 67,571 |
def get_exchange_rate_key(item: ExchangeItem) -> str:
"""
Generate a caching key for exchanging currency from one to another for today
"""
key = f"{item.currency_from}_{item.currency_to}_{item.historic_date}"
return key | d09dafa1baebd9c231ef9e26fb85339b4c89f97a | 67,572 |
import fnmatch
def iterator(network_filter="*", clear_sessions=False):
"""
Iterator over various networks.
"""
def fetch_networks(module_name, module):
ret = [
("%s.%s" % (module_name, name), (module, name))
for name in module.__all__
if any(
... | 3de5c0eb4067b65099f5f1cd51f944b4ef6c8131 | 67,573 |
def get_sales_order_items_rows(*args, **kwargs):
"""
获取列表
:param args:
:param kwargs:
:return:
"""
return db_instance.get_rows(SalesOrderItems, *args, **kwargs) | 9504fd6cd84081cc01d3d54efa24895f98f27dc4 | 67,574 |
def handle_quit(all_events):
"""If pygame quiting, terminate self. Returns true if quit"""
for event in all_events:
if event.type == pygame.QUIT:
return True
return False | ec2587fcc95b4d6804d6527436c3b5a6155e271c | 67,575 |
def wrap_dqn_bnn(env, noop_max=1):
"""Apply a common set of wrappers for Atari games."""
assert 'NoFrameskip' in env.spec.id
env = EpisodicLifeEnv(env)
env = NoopResetEnv(env, noop_max=noop_max)
env = MaxAndSkipEnv(env, skip=4)
if 'FIRE' in env.unwrapped.get_action_meanings():
env = Fire... | 9ca7ba1adb3dd72fdd04f552ee6260ff6b934a6a | 67,576 |
def list_variables(checkpoint_dir):
"""Returns list of all variables in the latest checkpoint.
Args:
checkpoint_dir: Directory with checkpoints file or path to checkpoint.
Returns:
List of tuples `(name, shape)`.
"""
reader = _load_checkpoint(checkpoint_dir)
variable_map = reader.get_variable_to_s... | 8b8e75e535073aac66eda14705a770d927edb652 | 67,577 |
import os
def _has_extension(file_name, extension):
"""Check if a file has an extension."""
return os.path.splitext(file_name)[1] == extension | 0b8a0979bd3aeaa65509c3b817ca48507775ac4d | 67,578 |
def _is_schar(self):
"""Test auf Schar"""
return len(self.sch_par) == 1 | 8d1229a45fab73a9d7f1560806c6e3497bbb1bcf | 67,579 |
def seqid_to_ahref(text):
"""
Return a new string where each occurrence of a sequence ref `Axxxxxx` replaced as `<a href=...>` html tag.
"""
return Axxxxxx_regex.sub(r'<a href="http://oeis.org/\g<id>">\g<id></a>', text) | 8addba28dda8c05034850bb8c079807af7202b20 | 67,580 |
def getTracks():
"""
Return a list of Track objects.
Result example : [Track1, Track2, ...]
"""
return loadView('tracks') | c39c2ab7662cf6d641d01c08c05f7d4ea74bbe0c | 67,581 |
def call_interp1d(track, inds, nticks, mess=None, linear=False):
"""
Call interp1d for each dimension individually. If LOG_L or
LOG_TE doesn't change, will return a constant array.
Probably could/should go in ._interpolate
Parameters
----------
track: padova_tracks.Track object
inds: ... | e9521d7a3e8646c5edcf64c09afe1e097a7a3473 | 67,582 |
import re
def _match(qs, ks):
"""Return True if regexes in qs match any window of strings in tuple ks."""
# compile regexes and force complete match
qts = tuple(map(lambda x: re.compile(x + '$'), qs))
for i in range(len(ks) - len(qs) + 1):
matches = [x.match(y) for x, y in zip(qts, ks[i:])]
if matches... | b5abe402f8ed0f78b9fef9ff3b274925ce58dbcd | 67,583 |
def getPartCharFunc2Org(partDHisto, key, paramProd, rArray, drPrime, delta):
"""
Calculates inter-atom contributions to the EPDDF for a partial distance histogram.
@param partDHisto Partial distance histogram.
@param key string Representing pair of particle species.
@param paramProd Parameter dicti... | 94dc2ce96600fb999adce3b871074f7a9266bed5 | 67,584 |
import os
def is_exe(fpath):
""" Return true if the given is an executable file that exists. """
return os.path.exists(fpath) and os.access(fpath, os.X_OK) | 96b74863311bfe46b1231da061b2fb2d9f4e5c93 | 67,585 |
def GetBuiltinsPyTD(): # Deprecated. Use Loader.concat_all.
"""Get the "default" AST used to lookup built in types.
Get an AST for all Python builtins as well as the most commonly used standard
libraries.
Returns:
A pytd.TypeDeclUnit instance. It'll directly contain the builtin classes
and functions,... | 552198939d103a04b5c8266aec76b9a8ac16e06b | 67,586 |
def lambda_handler(event, context):
"""
Root website view. I.e. '/' and client-side routes.
"""
return {
'statusCode': 200,
'body': load_html_template(event),
'headers': {'Content-Type': 'text/html'}
} | b64dd6792bed48d0fd5f3df5839cef0b63b1df7f | 67,587 |
def _fit_ovo_binary(estimator, X, y, i, j, sampling=None):
"""Fit a single binary estimator (one-vs-one).
It is possible to apply a sampling method.
"""
cond = np.logical_or(y == i, y == j)
y = y[cond]
y_binary = np.empty(y.shape, np.int)
y_binary[y == i] = 0
y_binary[y == j] = 1
in... | f2188696eb25df98a13be40dcbe114cf2191fcf1 | 67,588 |
def get_formated_ipaddr(input_ip):
"""
Format given ip address string to fortigate format (ip netmask)
Args:
* **ip_str** (string) : string representing ip address
accepted format:
- ip netmask (ex: 192.168.0.10 255.255.255.0)
- ip (ex: 192.168.0.10)
- CIDR (ex... | 06a6c14041de6603f37329a9e9ecd1f75e9a782c | 67,589 |
def _standardize(rec, sd=None, centers=None):
"""Determine standard deviation of noise in each channel
Parameters
----------
rec : matrix [length of recording, number of channels]
recording
sd : vector [number of chnanels,]
standard deviation
centered : bool
if not standa... | 045eba2dc5a3f4a7890fcf87a6322704823c5e22 | 67,590 |
def get_main_workflow_sql(project_id: str, dataset_id: str, merchant_id: str,
customer_id: str) -> str:
"""Returns main workflow sql.
Args:
project_id: A cloud project id.
dataset_id: BigQuery dataset id.
merchant_id: Merchant center id.
customer_id: Google Ads customer id... | f4ac6663a3a6246ef0fef4bb63134b088d499ce4 | 67,591 |
def dividend(
tickers, typ='all', start_date=None, end_date=None, **kwargs
) -> pd.DataFrame:
"""
Bloomberg dividend / split history
Args:
tickers: list of tickers
typ: dividend adjustment type
`all`: `DVD_Hist_All`
`dvd`: `DVD_Hist`
`... | 5e2c99e74557c53ed2dd6b9a6444fdb77771bc31 | 67,592 |
def get_next_mini_batch():
"""Return the next mini batch of training data.
Returns
x_trn_mb: mini batch of training x values
y_trn_mb: batch of training y values
"""
global idx_in_epoch, epoch, ids, x_trn, y_trn
start = idx_in_epoch
idx_in_epoch += mb_size
... | c0ba5720045b9452e54e74987011c3078c5ec765 | 67,593 |
def put(value):
"""Store an object in the object store.
The object may not be evicted while a reference to the returned ID exists.
Args:
value: The Python object to be stored.
Returns:
The object ref assigned to this value.
"""
worker = global_worker
worker.check_connected... | d5e245d63c162a4c72b20fec2ff04d281331ca32 | 67,594 |
import argparse
import os
def cli_main(args: argparse.Namespace) -> int:
"""
Main CLI routine
Args:
args: Command line arguments
Returns:
Exit status
"""
if args.mode not in MODES_OF_OPERATION:
print(f"Invalid mode: {args.mode}, must be one of {MODES_OF_OPERATION}")
... | 72892086d76b178fa47589c6a28c9a3a6916bec7 | 67,595 |
def get_accuracy(data_loader, model, device):
"""
Calculates the accuracy of the model given (inference mode) applied in the dataset of the data_loader
:param data_loader: Data loader
:param model: Model to be used for predictions
:param device: Device to be used
:return: accuracy percentage %
... | afdd5fc792ba726969057c1d12c3287c15778d65 | 67,596 |
def grayscale(image):
"""
Change the image to be grayscale using the NTSC luminosity formula and return it.
"""
for pixel in image:
luminosity = compute_luminosity (pixel.red, pixel.green, pixel.blue)
pixel.red = luminosity
pixel.green = luminosity
pixel.blue = luminosity... | 155eb30b4a4da0d830e0f1b36a0adf13ddee4e65 | 67,597 |
import tensorflow as tf
from art.classifiers import TFClassifier
def get_classifier_tf():
"""
Standard Tensorflow classifier for unit testing.
The following hyper-parameters were used to obtain the weights and biases:
learning_rate: 0.01
batch size: 10
number of epochs: 2
optimizer: tf.tr... | 7df7f0d823da0285f6e82090eefa0cb23bbfbae6 | 67,598 |
def version():
"""Get the current version."""
return _version_info | 42c08ec4d051646ed3dc6bf2e59cd29944136723 | 67,599 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.