content stringlengths 35 762k | sha1 stringlengths 40 40 | id int64 0 3.66M |
|---|---|---|
def _get_minimum_columns(
nrows, col_limits, families, family_counts, random_state
):
"""If ``col_limits`` has a tuple lower limit then sample columns of the
corresponding element of ``families`` as needed to satisfy this bound."""
columns, metadata = [], []
for family, min_limit in zip(families, c... | 56a0abc58a6e6c3356be08511e7a30da3c1c52e3 | 3,631,000 |
from typing import Union
from typing import Any
from typing import cast
def ensure_callable(x: Union[Any, Function]) -> Function:
"""ensure a given args is a callable by returning a new callable if not"""
if not callable(x):
def wrapped(*args: Any, **kwargs: Any) -> Any:
return x
... | 5165a1b44de13f570454f223f3b9b1e799bd309d | 3,631,001 |
from typing import List
def concat_dataframes(dataframes: List[pd.DataFrame],
remove_duplicates: bool = True,
keep: str = 'first'
) -> pd.DataFrame:
"""
Concatenate list of dataframes with optional removal of duplicate keys.
Args:
... | fd21c0ca6e95bdc5e5c854ba0d3cd2e30f018966 | 3,631,002 |
def __split_pair(number: SnailfishNumber, left: bool) -> int | None:
"""Splits a number into a pair if the number is >= 10.
:param number: Number node from the binary tree.
:param left: Boolean if we are inspecting the right or left leaf.
:return: 1 if we split else None.
"""
# Search for the l... | cd9a762fbad3148989fa2f823d83779ebd12e3ba | 3,631,003 |
def def_pin_pout(m):
# This could be better implemented.
# In particular, it should not use m.p directly but m.find_component(name_var)
"""
Defines power 'in' and 'out' variables
:param m:
:return:
"""
assert isinstance(m, Block), f"argument 'm', must be an instance of Block, but i... | 606d21f8b3204ca4394a891a260c88384e56c435 | 3,631,004 |
def get_user_choice() -> tuple[str, str]:
"""Returns the headers for the x and y value choices as a tuple."""
while True:
# X
console_display_choices(X_OPTIONS, "X")
x_choice = get_x_y_value(X_OPTIONS, "X")
# Y
console_display_choices(Y_OPTIONS, "Y")
y_choice ... | 94ff044acfbd52752dbe625e2a3f43531692ac14 | 3,631,005 |
import torch
import test
def exp(args, model_type, vertex_label, b_true, X_train, X_test_ID, X_test_OOD):
"""Experiment function."""
torch.set_default_dtype(torch.double)
np.set_printoptions(precision=3)
model, w_est = train(
X_train,
vertex_label=vertex_label,
b_true=b_true,
model_t... | 245f0feea515cfa1c28c8d59c176a486ddf43675 | 3,631,006 |
def sliding_window(warped):
"""
Using sliding window to find the lane line segments. This method will be used at the start of a video or when there is no lane line found on the previous video frame.
"""
img_height, img_width = warped.shape[0], warped.shape[1]
histogram = np.sum(warped[img_heig... | 9c495a502b79e8708573a94a0015915a35d44e41 | 3,631,007 |
def get_config(n_layers, use_auto_acts,
fp_quant):
"""Returns a ConfigDict instance for a WMT transformer.
The ConfigDict is wired up so that changing a field at one level of the
hierarchy changes the value of that field everywhere downstream in the
hierarchy. For example, changing the top-level... | c3b30a30ed2e272cd5e9802508d3eab78a679b47 | 3,631,008 |
import torch
def get_train_loader(transform=None):
"""
Args:
transform (transform): Albumentations transform
Returns:
trainloader: DataLoader Object
"""
if transform:
trainset = Cifar10SearchDataset(transform=transform)
else:
trainset = Cifar10SearchDataset(root="~/data/cifar10", train... | c72222835c98b104fa4a04f4bf49de5850071365 | 3,631,009 |
def train_regression(train_data, model, criterion, optimizer, batch_size, device, scheduler=None, collate_fn=None):
"""Train a Pytorch regresssion model
Parameters
----------
train_data : torch.utils.data.Dataset
Pytorch dataset
model: torch.nn.Module
Pytorch Model
criterion: fu... | 6a20c532137e32e1a56656b3cecf0c1686ec9f40 | 3,631,010 |
import re
import urllib
import locale
import socket
def get_url_content(url):
"""Performs a HTTP GET on the url.
Returns False if the url is invalid or not-found"""
res = None
if not re.search(r'^http', url):
url = 'http://' + url
try:
req = urllib.request.urlopen(url, None, 30)
... | a6cebdb19eff1daa86e9f7aa18943c19854e5641 | 3,631,011 |
def _evaluate(cmd, dork):
"""Parse a command and execute it"""
cmd = cmd.strip().split(" ", 1)
if cmd[0]:
verb, *noun = cmd
noun = noun[0] if noun else None
call = _CMDS.get(verb, _MOVES.get(verb, _META.get(verb, _ERRS["u"])))
if isinstance(call, dict):
method, ... | cfb6957cf1c10c18cc768c266992412c36222571 | 3,631,012 |
from typing import OrderedDict
def build_input_dict(feature_columns):
"""
基于特征列(feature columns)构建输入字典
:param feature_columns: list 特征列
:return:
input_dict: dict 输入字典,形如{feature_name: keras.Input()}
"""
# 1,基于特征列构建输入字典
input_dict = OrderedDict()
for fc in feature_columns:
... | 033a6cb0d73a9652a5a9ce83026a05a93756e85c | 3,631,013 |
def factorial(n):
"""Calcula el factorial de un numero"""
fact = 1
for i in range (1, n+1):
fact = fact * i
return fact | b341682fbc13fd184af8551be37348bf36ec082c | 3,631,014 |
def sigmoid(x):
"""
Computes sigmoid of x element-wise.
Parameters
----------
x : tensor
A Tensor with type float16, float32, float64, complex64, or complex128.
Returns
-------
A Tensor with the same type as x.
"""
outputs = P.Sigmoid()
return outputs(x) | 314c13df8127e3bb602e3a3eab98b2c2b68fb82d | 3,631,015 |
def conf_serializer(configuration: Configuration) -> str:
"""Serialize configuration to .conf files."""
lines = [f"{key} {val}" for key, val in configuration.Properties.items()]
return "\n".join(lines) + "\n" | 8bf3104495cf849ad0b3576c3bf61482c51d04fe | 3,631,016 |
def redness_greenness_response(C, e_s, N_c, N_cb):
"""
Returns the redness / greenness response :math:`M_{yb}`.
Parameters
----------
C : array_like
Colour difference signals :math:`C`.
e_s : numeric or array_like
Eccentricity factor :math:`e_s`.
N_c : numeric or array_like
... | 06ea4162ec83957db705a2903c8cd748f7a7c34a | 3,631,017 |
import re
import os
def validate_file(file_type, path):
"""Ensure the data file contains parseable rows data"""
match = re.search(r'\.(\w+)$', str(path))
extension = None
if match:
extension = match.group(1).lower()
else:
return 'invalid file extension'
if extension not in _FIL... | b2697cfc8105859bf6b78201d317f7203a80f5b0 | 3,631,018 |
import mimetypes
def upload(bucket_name, key, file_path):
""" upload object to bucket """
# create s3 client
client = boto3.client("s3")
# guess ContentType
mime, _ = mimetypes.guess_type(file_path, strict=False)
mime = "text/plain" if mime is None else mime
with open(file_path, "rb") as... | 9ad3500ea8631cb44e2ab35aa020ae7434181e2a | 3,631,019 |
import platform
def _format_source(src, virtual_cells = None): # type: (Union[str, RuleTarget], str) -> str
"""
Converts a 'source' to a string that can be used by buck native rules
Args:
src: Either a string (for a source file), or a RuleTarget that needs converted to a label
platform: ... | 530c13b7ce8239e97159f57ef794f036f958f9d4 | 3,631,020 |
def test_vnic_and_assign_vf(ip_addr, free_vnics_ips, backlisted_vfs=()):
"""
Based on the IP address of an OCI VNIC, ensure that the VNIC is not
already assigned to a virtual machine. If that VNIC is available, find a
free virtual function on the appropriate physical interface and return
the necessa... | af1b60812c2ea03e4042de0560f852f932fb6337 | 3,631,021 |
from sys import path
def read_config_file_step(
info=None,
config_file_path=path.join(path.dirname(path.dirname(__file__)), 'config', 'config.yml')):
"""
读取配置文件
:param info:
:param config_file_path: 配置文件路径
:return:
"""
if info:
res = FileOperate.read_yaml(config_fil... | 0e934bb23da497ebe74e9ec8768f91770e33b213 | 3,631,022 |
def get_player():
"""Returns a driver to control the VoiceHat speaker.
The aiy modules automatically use this player. So usually you do not need to
use this. Instead, use 'aiy.audio.play_wave' if you would like to play some
audio.
"""
global _voicehat_player
if not _voicehat_player:
... | f8c242083072392663a19bc720fac156e96cef7a | 3,631,023 |
import json
def post_user_events():
"""Endpoint for users to post the events they want to add to their calendar
Returns:
Response: JSON with the success status of each event
"""
body = request.json
response = insert_user_calendar_events(
session['google-idap']['access_token'],
... | 23dc6e8d4751e4c630b4049f1aec50ee6a8783b2 | 3,631,024 |
def zmq_version():
"""return the version of libzmq as a string"""
return "%i.%i.%i" % zmq_version_info() | 49fc037744e4215a583ccc8de07cd415a99fc17c | 3,631,025 |
def parse_datetime_interval(period_from: str, period_to: str, strformat: str = None) -> date_tuple:
"""
Returns given period parameters in datetime format, or next step in back-fill mode
along with generated last state for next iteration.
Args:
period_from: YYYY-MM-DD or relative string support... | ddf97283465b04cc85bf74a079465439c49c82ff | 3,631,026 |
def _paths_from_ls(recs):
"""The xenstore-ls command returns a listing that isn't terribly
useful. This method cleans that up into a dict with each path
as the key, and the associated string as the value.
"""
ret = {}
last_nm = ""
level = 0
path = []
ret = []
for ln in recs.split... | afa0fbe3e5c1773074569363a538587664a00a2f | 3,631,027 |
import torch
import tqdm
import os
import pickle
def train(args, train_dataset, eval_dataset, model, tokenizer):
""" Train the model """
# ===== Setting up
# summary writer
tb_writer = SummaryWriter()
print("DEBUGGING!")
print("train_dataset: " + str(len(train_dataset)))
print(train_... | f20c68d1f8c7b1d704f537c56bb0f6d8bbe46f93 | 3,631,028 |
def TRS_between_rounds(X1, X2):
"""
Calculate the TRS rotor between any pair of rounds of the same grade
Bring rounds to origin, line up carriers, calculate scale
"""
T1 = generate_translation_rotor(-down((X1 * einf * X1)(1)))
X1h = (T1 * X1 * ~T1).normal()
T2 = generate_translation_rotor(-d... | 6e25e89999e22a6f3e3ef853f7b4c8e6268824b6 | 3,631,029 |
def col_range_nb(col_arr, n_cols):
"""Build column range for sorted column array.
Creates a 2-dim array with first column being start indices (inclusive) and
second column being end indices (exclusive).
!!! note
Requires `col_arr` to be in ascending order. This can be done by sorting."""
c... | f6ff35b01c34b917f9aaf69acfe4aa3d1e6d7548 | 3,631,030 |
def filterfiles(files, criteria):
"""Rerturns only the files from filelist that match the criteria.
The criteria should be a list of (unit,keyword,function) where the function
returns true for desired values of the keyword. For example
criteria = ((0,'OPT_ELEM', lambda x: x == 'G130M'),
... | 5a60a2a46944eeb8d70337b342824cad6156c33d | 3,631,031 |
def module_start(ip, port, dev, module):
"""模块启动
Args:
ip(str):ip地址
port(int):端口号
dev(str): 设备名称
module(str):模块名称
Returns:
tuple:返回错误码以及对应信息
"""
command = "模块启动"
AP.__class__.logout("发送{}{}{}指令".format(dev, module, command))
MESSAGE_DICT["mod_start_... | 9eb5f222cb3fb6f55398c2390fb67b9f823cae6e | 3,631,032 |
def activate_bgp_neighbor(dut, local_asn, neighbor_ip, family="ipv4", config='yes',vrf='default', **kwargs):
"""
:param dut:
:param local_asn:
:param neighbor_ip:
:param family:
:param config:
:param vrf:
:return:
"""
st.log("Activate BGP neigbor")
cli_type = get_cfg_cli_ty... | 8e335938c73b1cd816afc77b0a8af75c5dfdd893 | 3,631,033 |
def print_experiment_record_argtable(records):
"""
Print a table comparing experiment arguments and their results.
"""
funtion_names = [record.info.get_field(ExpInfoFields.FUNCTION) for record in records]
args = [record.get_args() for record in records]
common_args, different_args = separate_com... | 04b8e5e07e19f6dae0f8b9d988a4bda0a0a1de17 | 3,631,034 |
def key_validator(*args, **kwargs):
"""Wraps hex_validator generator, to keep makemigrations happy."""
return hex_validator()(*args, **kwargs) | 59c6ddda60ac4d1a954f112e426bd2952800dd8e | 3,631,035 |
def fuzzy_search(request):
"""
ajax interface for fuzzy string search
:param request: request of the web server
:return: json-set with all matched strings
"""
LOG.debug("Fuzzy String search for AJAX: %s", request.json_body)
mode = request.validated['type']
value = request.validated['va... | 501425306babe15af0baae73b4f69dd89b4947ec | 3,631,036 |
from . import routes
from . import auth
def create_app():
""" Initialize the core application """
app = Flask(__name__, instance_relative_config=False)
app.config.from_object(Config)
# Initialize Plugins
db.init_app(app)
login_manager.init_app(app)
with app.app_context():
# Regi... | 1aaffaf9ece821e6448670006871c143286ac37c | 3,631,037 |
from typing import Optional
def plot_points_3D_mayavi(
points: np.ndarray,
bird: bool,
fig: Figure,
per_pt_color_strengths: np.ndarray = None,
fixed_color: Optional[Color] = (1, 0, 0),
colormap: str = "spectral",
) -> Figure:
"""Visualize points with Mayavi. Scale factor has no influence o... | e9f80d8de890cd4b1c51a9614dc69812c951cec5 | 3,631,038 |
import io
def read_binary_integer32_token(file_desc: io.BufferedReader) -> int:
"""
Get next int32 value from file
The carriage moves forward to 5 position.
:param file_desc: file descriptor
:return: next uint32 value in file
"""
buffer_size = file_desc.read(1)
return get_uint32(file_d... | 81a0c6a592476a142e28ddbf65bddd59004486ad | 3,631,039 |
def pop(key):
"""
从缓存队列的后尾读取一条数据
:param key: 缓存key,字符串,不区分大小写
:return: 缓存数据
"""
# 将key转换为小写字母
key = str(key).lower()
try:
value = r.rpop(key)
except Exception as e:
log_helper.info('读取缓存队列失败:key(' + key + ')' + str(e.args))
value = None
return _str_to_jso... | 92cc254b9b2270ac2fa6c7d66b7f8a13b11b2522 | 3,631,040 |
def _one_q_pauli_prep(label, index, qubit):
"""Prepare the index-th eigenstate of the pauli operator given by label."""
if index not in [0, 1]:
raise ValueError(f'Bad Pauli index: {index}')
if label == 'X':
if index == 0:
return Program(_RY(pi / 2, qubit))
else:
... | 4c4f02c6e1ffcbb57ca161f3cb0f17a678563b0b | 3,631,041 |
import logging
def run(camera: Camera):
"""
Runs the PictogramDetector.
:return: the pictogram which had the most hits.
"""
try:
detector = PictogramDetector(camera)
stats = detector.detect()
logging.debug(stats)
result = max(stats, key=stats.get)
t2s = pyt... | 7479d84174130edc078a4e00fcfed39dadb014c4 | 3,631,042 |
import os
import pickle
def concat_claims_all_documents(index: list, file_name: str):
"""
Merges all the lists of unique tags and saves the merged version as one pickle file with all unique tags
"""
list_of_dfs = []
for i in index:
location = '{0}{1}_wclaims.pkl'.format(file_name.split('.'... | 09d155c5f14ee88bfc797e861551b12d987867e3 | 3,631,043 |
def get_movie_data_from_wikidata(slice_movie_set: pd.DataFrame):
"""
Function that consults the wikidata KG for a slice of the movies set
:param slice_movie_set: slice of the movie data set with movie id as index and imdbId, Title, year and imdbUrl
as columns
:return: JSON with the results of the qu... | a4c3a9a7e7cce1a2eb85326422afcb4ff3463db4 | 3,631,044 |
def run_dpc(
filename,
i,
j,
ref_fx=None,
ref_fy=None,
start_point=[1, 0],
pixel_size=55,
focus_to_det=1.46,
dx=0.1,
dy=0.1,
energy=19.5,
zip_file=None,
roi=None,
bad_pixels=[],
max_iters=1000,
solver="Nelder-Mead",
hang=True,
reverse_x=1,
reve... | e7d96201350cb84c323066434d8257631de353f7 | 3,631,045 |
from ostap.utils.cleanup import CleanUp
import os
def make_build_dir ( build = None ) :
"""Create proper temporary directory for ROOT builds
"""
if not build or not writeable ( build ) :
build = CleanUp.tempdir ( prefix = 'ostap-build-' )
if not os.path.exists ( build ) :
make_dir ... | 28a6b9de1b8b33235c4abce988624c3e6a56ba25 | 3,631,046 |
def api_converter():
"""
Handler for conversion API request
:return: Text of response
:rtype: str
"""
try:
parsed_args = parse_request_arguments()
conversion_result = convert_core.convert_currency(**parsed_args)
except (APIRequestError, CurrencyConversionError) as exc_msg:
... | 591961f92a5e1e831976bcb09396630b515785cb | 3,631,047 |
import pytz
def plot1(ctx):
"""Do main plotting logic"""
df = read_sql("""
SELECT * from sm_hourly WHERE
station = %s and valid BETWEEN %s and %s ORDER by valid ASC
""", ctx['pgconn'], params=(ctx['station'], ctx['sts'],
ctx['ets']), index_col='valid')
i... | 8c94e9b989bbf0f04db99cffdc54cc9ec46b8e40 | 3,631,048 |
from typing import Tuple
from typing import Optional
def is_royal_flush(hand: Tuple[Card]) -> Optional[Tuple[str, PokerHand, int]]:
""" If this hand contains a royal flush, return string representation of it """
straight_flush = is_straight_flush(hand)
if straight_flush is not None and "Ten to Ace" in str... | 9e530d3c1ff44b35e6e17bc068f4557e059e3415 | 3,631,049 |
import torch
def make_complex_matrix(x, y):
"""A function that takes two tensors (a REAL (x) and IMAGINARY part (y)) and returns the combine complex tensor.
:param x: The real part of your matrix.
:type x: torch.doubleTensor
:param y: The imaginary part of your matrix.
:type y: torch.doubleTe... | faae031b3aa6f4972c8f558f6b66e33d416dec71 | 3,631,050 |
def array(dtype, ndim):
"""
:param dtype: the Numba dtype type (e.g. double)
:param ndim: the array dimensionality (int)
:return: an array type representation
"""
if ndim == 0:
return dtype
return minitypes.ArrayType(dtype, ndim) | f9b89a414d9bfb7a1e154df34c1c75a47943bca5 | 3,631,051 |
def as_pandas(data):
"""Returns a dataframe if possible, an error otherwise"""
if isinstance(data, pd.DataFrame):
return data
elif isinstance(data, dict):
return pd.DataFrame(data)
else:
raise TypeError(
f"Expected a DataFrame or dict type, got: {type(data)} insead"
... | a9243c327f8f7851b0b8347a9df684db7b152561 | 3,631,052 |
def scale3(v, s):
"""
scale3
"""
return (v[0] * s, v[1] * s, v[2] * s) | 4993c072fb66a33116177023dde7b1ed2c8705fd | 3,631,053 |
def _get_last_ext_comment_id(connection):
"""Returns last external comment id.
Args:
connection: An instance of SQLAlchemy connection.
Returns:
Integer of last comment id from external model.
"""
result = connection.execute(
sa.text("""
SELECT
MAX(id)
FROM ... | 5cc139e3c4490293ebb305b7cac03d4803c51df6 | 3,631,054 |
from typing import SupportsAbs
import math
def is_unit(v: SupportsAbs[float]) -> bool: # <2>
"""'True' if the magnitude of 'v' is close to 1."""
return math.isclose(abs(v), 1.0) | 0b31da2e5a3bb6ce49705d5b2a36d3270cc5d802 | 3,631,055 |
def atom_eq(at1,at2):
""" Returns true lits are syntactically equal """
return at1 == at2 | 43aab77292c81134490eb8a1c79a68b38d50628d | 3,631,056 |
def is_valid_month (val):
""" Checks whether or not a two-digit string is a valid date month.
Args:
val (str): The string to check.
Returns:
bool: True if the string is a valid date month, otherwise false.
"""
if len(val) == 2 and count_digits(val) == 2:
month = int(val)
... | 53d825473cf497441d09e08402e833fa9c362a83 | 3,631,057 |
def env_repos(action=None):
"""
Perform an action on each environment repository, specified by action.
"""
actions = {
'add': _add_repo,
'reset': _reset_repo,
'rm': _rm_repo
}
def validate_action(input):
if input not in actions:
raise Exception('Inval... | f9b9ab0e671757bbcdf7bf4f50fe05e079aca115 | 3,631,058 |
import re
def get_job_definition_name_by_arn(job_definition_arn):
"""
Parse Job Definition arn and get name.
Args:
job_definition_arn: something like arn:aws:batch:<region>:<account-id>:job-definition/<name>:<version>
Returns: the job definition name
"""
pattern = r".*/(.*):(.*)"
... | d55bab5bbc62bf6d9f7907e26cb2a4a418bd9c50 | 3,631,059 |
def get_polyline_length(polyline: np.ndarray) -> float:
"""Calculate the length of a polyline.
Args:
polyline: Numpy array of shape (N,2)
Returns:
The length of the polyline as a scalar
"""
assert polyline.shape[1] == 2
return float(np.linalg.norm(np.diff(polyline, axis=0), axi... | 9fb76a611c961af8ca10fda33029a55eb8589be1 | 3,631,060 |
import sys
def GDALReadBlock(dataset, blocno, BSx=-1, BSy=-1, verbose=False):
"""
GDALReadBlock
"""
dataset = gdal.Open(dataset, gdal.GA_ReadOnly) if isstring(dataset) else dataset
if dataset:
band = dataset.GetRasterBand(1)
BSx, BSy = (BSx, BSy) if BSx > 0 else band.GetBlockSize(... | 09aa97b137e7c9f627af007d80610829a0c98827 | 3,631,061 |
def add_update_stock(symbol, is_held):
"""This function takes a stock symbol as a string, makes a call to yfinance, and gets back the necessary data to add the symbol to the database.
`is_held` must also be specified, to mark the is_held flag in the database True/False."""
session = connect_to_sessio... | df5c7782fd07f916e61e4d5dc1f8f8cf9be86eec | 3,631,062 |
import math
def k2(Ti, exp=math.exp):
"""[cm^3 / s]"""
return 2.78e-13 * exp(2.07/(Ti/300) - 0.61/(Ti/300)**2) | 6c1f471b31767f2d95f3900a8811f47dc8c45086 | 3,631,063 |
async def add_source(request):
"""
API Endpoint to add new datasets to an instance
API Params:
file: location of the json or hub file
filetype: 'hub' if trackhub or 'json' if configuration file
Args:
request: a sanic request object
Returns:
success/fail after addi... | 624218d1e773c43a35fa3579d892cc6207e1ee1d | 3,631,064 |
def clean_counties_data():
"""Clean US Counties data from NY Times
Returns:
DataFrame -- clean us counties data
Updates:
database table -- NYTIMES_COUNTIES_TABLEs
database view -- COUNTIES_VIEW
"""
_db = DataBase()
data = _db.get_table(US_COUNTIES_TABLE, parse_dates=['d... | 083e9720de9bfa422984d01fec08c0c4b33b0861 | 3,631,065 |
def get_3D_hist(sub_img):
"""
Take in a sub-image
Get 3D histogram of the colors of the image and return it
"""
M, N = sub_img.shape[:2]
t = 4
pixels = sub_img.reshape(M * N, 3)
hist_3D, _ = np.histogramdd(pixels, (t, t, t))
return hist_3D | c582ec9b7d6bb24585ce5f95d2a770b4b7a06c37 | 3,631,066 |
import os
import time
from datetime import datetime
def cache_tree(config_age, location_suffix):
"""
A decorator for caching pickle files based on the configuration file.
It is currently set up to decorate a function that has a single parameter ``site``.
The returned function also can be passed keywo... | 445384fa353d0bf60d7e78a28951562880b24717 | 3,631,067 |
import math
import torch
def magnitude_prune(masking, mask, weight, name):
"""Prunes the weights with smallest magnitude.
The pruning functions in this sparse learning library
work by constructing a binary mask variable "mask"
which prevents gradient flow to weights and also
sets the weights to z... | 4bac89da952338e133ac0d85735e80631862c7da | 3,631,068 |
import requests
def delete_post(post_id):
"""Authenticates and proxies a request to users service to delete a post."""
try:
my_user_id = get_user()['user_id']
response = requests.delete(app.config['POSTS_ENDPOINT'] + post_id,
data={'author_id': my_user_id})
... | a558ab58ac3129fb543c89c8b3c236126d26ddac | 3,631,069 |
import collections
def file_based_convert_examples_to_features_single(examples, label_list,
max_seq_length, tokenizer,
output_file):
"""Convert a set of `InputExample`s to a TFRecord file."""
writer = tf.python_... | 444afd74b8bccd7e014e727d4be41be75fbdbb11 | 3,631,070 |
def less_equal(x, y):
"""Element-wise truth value of (x <= y).
# Arguments
x: Tensor or variable.
y: Tensor or variable.
# Returns
A bool tensor.
# Raise
TypeError: if inputs are not valid.
"""
scalar = False
if isinstance(x, KerasSymbol):
x = x.sym... | 566c46cc4882f167275cb6bc400800413efdc85b | 3,631,071 |
from datetime import datetime
def annual_reports():
""" Return list of all existing annual reports """
database = DataProvider()
total = count(database.objects, lambda x: x.with_cafe) * 2 + \
count(database.objects, lambda x: not x.with_cafe)
reports_list = list()
# calculate count of ... | 2e6daacd7150e47b299948b60866238589881ef5 | 3,631,072 |
import sys
def alpha_036(code, end_date=None, fq="pre"):
"""
公式:
RANK(SUM(CORR(RANK(VOLUME), RANK(VWAP)), 6), 2)
Inputs:
code: 股票池
end_date: 查询日期
Outputs:
因子的值
"""
end_date = to_date_str(end_date)
func_name = sys._getframe().f_code.co_name
return JQDataC... | 0c65d8d0b7961fcf79dafd87e3ed683a11da6350 | 3,631,073 |
def definition_for_include(parsed_include, parent_definition_key):
"""
Given a parsed <xblock-include /> element as a XBlockInclude tuple, get the
definition (OLX file) that it is pointing to.
Arguments:
parsed_include: An XBlockInclude tuple
parent_definition_key: The BundleDefinitionLocator... | 325de830231c9b21a3c7cfce4262fef291ab6fbf | 3,631,074 |
def verify_user(uid, token_value):
"""
Verify the current user's account.
Link should have been sent to the user's email.
Args:
token_value: the verification token value
Returns:
True if successful verification based on the (uid, token_value)
False if token is not valid for... | e63e7044e66bb29e8f44d7fa0a08128597e7b07e | 3,631,075 |
def cholesky_metric(chol: JAXArray, *, lower: bool = True) -> Metric:
"""A general metric parameterized by its Cholesky factor
The units of the Cholesky factor are length, unlike the dense metric.
Therefore,
.. code-block:: python
cholesky_metric(jnp.diag(ell))
and
.. code-block:: p... | 406d0db5d3f6f9317a0b45895823c3927564653a | 3,631,076 |
import typing
def format_roman(value: int) -> str:
"""Format a number as lowercase Roman numerals."""
assert 0 < value < 4000
result: typing.List[str] = []
index = 0
while value != 0:
value, remainder = divmod(value, 10)
if remainder == 9:
result.insert(0, ROMAN_ONES[... | 259b205ffa25bbdeccb0ca6883c02c99d194f60d | 3,631,077 |
import os
def find_top_directory():
"""
Find the parent directory of the poky meta-layer
:return: the base path
"""
return os.path.dirname(tinfoil.config_data.getVar("COREBASE", True)) | 9978c6f0c0673c9fb42d47c15d24e17c684161d7 | 3,631,078 |
def isint(s):
"""Does this object represent an integer?"""
try:
int(s)
return True
except (ValueError, TypeError):
return False | dbcb20b437f1ccfb09f5cb969b7d5b9d369d2e38 | 3,631,079 |
def embed_vimeo(url):
"""
Return HTML for embedding Vimeo videos or ``None``, if argument isn't a
Vimeo link.
The Vimeo ``<iframe>`` is wrapped in a
``<div class="responsive-embed widescreen vimeo">`` element.
"""
match = VIMEO_RE.search(url)
if not match:
return None
d = ma... | 7923991466ec3eafa4c991bb93b2244ebcf99c47 | 3,631,080 |
def random_sample(random_state, size=None, chunk_size=None, gpu=None, dtype=None):
"""
Return random floats in the half-open interval [0.0, 1.0).
Results are from the "continuous uniform" distribution over the
stated interval. To sample :math:`Unif[a, b), b > a` multiply
the output of `random_samp... | 441a8d1b6e972ab961cf5910cd3737e5a21578e7 | 3,631,081 |
def anndata_file():
"""Pytest fixture for creation of anndata files."""
def _create_file(nvals):
size = 15289 * nvals
vals = np.zeros(size, dtype=np.float32)
non_zero = size - int(size * 0.92)
non_zero = int(np.random.normal(loc=non_zero, scale=10, size=1))
rand = np.rand... | 0f9c1ff260ae48837e9f925c65fd87c7b5f75768 | 3,631,082 |
def _heatmap_summary(pvals, coefs, plot_width=1200, plot_height=400):
""" Plots heatmap of coefficients colored by pvalues
Parameters
----------
pvals : pd.DataFrame
Table of pvalues where rows are balances and columns are
covariates.
coefs : pd.DataFrame
Table of coefficien... | 32dae78fbaa3e978d418255e387e63f6346315ff | 3,631,083 |
from datetime import datetime
def get_warehouse_latest_modified_date(email_on_delay=False):
"""
Return in minutes how fresh is the data of app_status warehouse model.
"""
last_completed_app_status_batch = Batch.objects.filter(
dag_slug='app_status_batch', completed_on__isnull=False
).order... | 541dba13fde93acc51a41a9079a6da5f0344514a | 3,631,084 |
import subprocess
def retrieve_contents(repo, commit, path, encoding=None):
"""Retrieve contents of given file at given revision / tree
Parameters
----------
repo : str | git.Repo | pygit2.Repository
Pathname to the repository, or either GitPython (git.Repo)
or pygit2 (pygit2.Reposito... | 834aabe9eca88f9a9f4b3ba377832aa24ae720b9 | 3,631,085 |
async def async_unload_entry(hass, config_entry):
"""Handle removal of an entry."""
return True | 28005ececbf0c43c562cbaf7a2b8aceb12ce3e41 | 3,631,086 |
def render_links(link_dict):
"""Render links to html
Args:
link_dict: dict where keys are names, and values are lists (url,
text_to_display). For example::
{"column_moistening.mp4": [(url_to_qv, "specific humidity"), ...]}
"""
return {
key: " ".join([_html_l... | c07f388e97f9e723cfc42ee66ef1eea654167820 | 3,631,087 |
import json
def is_valid_json(text: str) -> bool:
"""Is this text valid JSON?
"""
try:
json.loads(text)
return True
except json.JSONDecodeError:
return False | 3013210bafd5c26cacb13e9d3f4b1b708185848b | 3,631,088 |
import signal
def peri_saccadic_response(spike_counts, eye_track, motion_threshold=5, window=15):
"""
Computes the cell average response around saccades.
params:
- spike_counts: cells activity matrix of shape (t, n_cell)
- eye_track: Eye tracking data of shape (t, x_pos, y_pos, ...)
... | 85455106bb1cd438b2aeb25ee0fc3708a166d4b7 | 3,631,089 |
import operator
def assign_subpopulation_from_region(pop, region, criteria, verbose=False):
"""
Compute required consistencies and assign subpopulations to a population of models based on results from
a simulation region.
Inputs:
pop - a PopulationOfModels class
region - a list of simulations
... | 5279d7e398ed164aed4131bb1c826c5f1604c4a4 | 3,631,090 |
def op_structure(ea, opnum, id, **delta):
"""Apply the structure identified by `id` to the instruction operand `opnum` at the address `ea`.
If the offset `delta` is specified, shift the structure by that amount.
"""
ea = interface.address.inside(ea)
if not database.type.is_code(ea):
raise E... | 95d45003c86b4a99bb60d00eb584bb358f1cf350 | 3,631,091 |
from pathlib import Path
def get_config_path(root: str, idiom: str) -> Path:
"""Get path to idiom config
Arguments:
root {str} -- root directory of idiom config
idiom {str} -- basename of idiom config
Returns:
Tuple[Path, Path] -- pathlib.Path to file
"""
root_path = Path... | 86d65f11fbd1dfb8aca13a98e129b085158d2aff | 3,631,092 |
def status():
"""
Method to get the list of components available.
:return: It yields json string for the list of components.
"""
data = pgc.get_data("status")
return render_template('status.html', data=data) | 012431c843d051aec85df45fad005b9d17c71a5d | 3,631,093 |
from typing import Union
from typing import Iterable
from typing import Tuple
from typing import List
import heapq
def dijkstra(
graph: LilMatrix, source: Union[int, Iterable[int]]
) -> Tuple[List[int], List[int]]:
"""Dijkstra
Parameters
----------
graph
Weighted Graph
source
... | 62278adeda336344eadaac00b9240cddd747b496 | 3,631,094 |
def stdev(some_list):
"""
Calculate the standard deviation of a list.
"""
m = mean(some_list)
var = mean([(v - m)**2 for v in some_list])
return sqrt(var) | 4a8cf5d19af1e07e8228d285d1f2fcfb702a2158 | 3,631,095 |
def get_hg19_chroms():
"""Chromosomes in the human genome
Returns:
list: list of chromosomes
"""
return get_hg38_chroms() | 2565eb2fa1ca1dd1b513a2a7dc836777911c7fc8 | 3,631,096 |
def track(im0, im1, p0, lk_params_, fb_threshold=-1):
"""
Main tracking method using sparse optical flow (LK)
im0: previous image in gray scale
im1: next image
lk_params: Lukas Kanade params dict
fb_threshold: minimum acceptable backtracking distance
"""
if p0 is None or not len(p0):
... | 4a35dbb3c206f3b2e967f2b15853b19c7d579eb9 | 3,631,097 |
def get_kernel(X, Y, type='linear', param=1.0):
"""Calculates a kernel given the data X and Y (dims x exms)"""
_, Xn = X.shape
_, Yn = Y.shape
kernel = 1.0
if type == 'linear':
#print('Calculating linear kernel with size {0}x{1}.'.format(Xn, Yn))
kernel = X.T.dot(Y)
if type == ... | 98bd634456bbc4ec115de58fd58a1cd6df84b3a5 | 3,631,098 |
def MIDPOINT(ds, count, timeperiod=-2**31):
"""MidPoint over period"""
return call_talib_with_ds(ds, count, talib.MIDPOINT, timeperiod) | 0315f5148bbd4621db30aa572fd984f23cb6ee79 | 3,631,099 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.