text string | label_name string | labels int64 |
|---|---|---|
"""Tests for EQ3 Max! component."""
from unittest.mock import create_autospec, patch
from maxcube.device import MAX_DEVICE_MODE_AUTOMATIC, MAX_DEVICE_MODE_MANUAL
from maxcube.room import MaxRoom
from maxcube.thermostat import MaxThermostat
from maxcube.wallthermostat import MaxWallThermostat
from maxcube.windowshutter... | Python | 1 |
from django.contrib import admin
from django.urls import path
from . import views
urlpatterns = [
path('', views.index, name='home'),
path('game_1/', views.game_1, name='game_1'),
path('game_2/', views.game_2, name='game_2'),
path('game_3/', views.game_3, name='game_3'),
path('static_game/', views... | Python | 1 |
from behave import use_fixture
from fixtures import fixture_map
import helper
import shutil
import os
import time
def before_tag(context, tag):
tag_parts = tag.split(".", 2)
match tag_parts[0].lower():
case "fixture":
if len(tag_parts) > 1:
try:
use_fix... | Python | 1 |
nedness {
Unsigned = 0,
Signed = 1,
}
#[derive(Debug, PartialEq, Hash, Eq, Copy, Clone)]
enum LocalType {
Scalar {
kind: crate::ScalarKind,
width: Bytes,
},
Vector {
size: crate::VectorSize,
kind: crate::ScalarKind,
width: Bytes,
},
Pointer {
... | Rust | 0 |
-> std::fmt::Result {
write!(
f,
"session: {}\nclient: {}",
self.session,
self.client.as_deref().unwrap_or_default()
)
}
}
impl Context {
pub fn new(session: String, client: Option<String>) -> Self {
let mut path = std::env::temp_dir();
... | Rust | 0 |
let config = config.clone();
let pool = pool.clone();
async move {
deadmanswitch::run(pool, config).await;
}
});
}
match config.api {
true => {
if let Err(err) = run_api(pool, config, keys).await {
log::error!("{:#}", err);
}
}
false => future::... | Rust | 0 |
from urllib.parse import urlparse
def is_basic_valid_url(url):
"""Check if URL has basic validity (proper scheme and netloc) without domain restrictions."""
parsed = urlparse(url)
return parsed.scheme in ('http', 'https') and bool(parsed.netloc)
def is_valid_url(url, allowed_prefixes_or_domains):
"""C... | Python | 1 |
vert the argument of Basic.find() into a callable"""
try:
query = _sympify(query)
except SympifyError:
pass
if isinstance(query, type):
return lambda expr: isinstance(expr, query)
elif isinstance(query, Basic):
return lambda expr: expr.match(query) is not None
return ... | Python | 1 |
from ultralytics import YOLO
if __name__ == '__main__':
# Load a model
model = YOLO("yolov8s.pt") # build from YAML and transfer weights
# Train the model
results = model.train(data="coco128.yaml", epochs=100, imgsz=2048, batch=8, device='xpu')
| Python | 1 |
self, world: &world::World) {
let messages = match self.inbox {
Some(ref drain) => drain.drain(),
None => Vec::new(),
};
self.picked.clear();
for message in messages {
if let Message::Event(Event::PickMinion(position)) = message {
let picked = self.pick(position);
if let Some(picked_id) = pick... | Rust | 0 |
GenericErr { msg, .. }) => {
assert_eq!(msg, "Deposit amount must be greater than 0 uusd")
}
_ => panic!("DO NOT ENTER HERE"),
}
let env = mock_env(
"addr0000",
&[Coin {
denom: "uusd".to_string(),
amount: Uint128::from(55_555_555_000_000u128),... | Rust | 0 |
from django.db import models
class Scheme(models.Model):
schemename = models.CharField(max_length=255)
ministry = models.CharField(max_length=255)
desc = models.TextField()
place = models.CharField(max_length=255)
moneygranted = models.DecimalField(max_digits=15, decimal_places=2)
moneyspent = ... | Python | 1 |
# test_error_calculation.py
import unittest
import sys
from project_ppchem_tools_kit.error_calculation_interface import calculate_error_propagation
class TestErrorCalculation(unittest.TestCase):
def test_calculate_error_propagation(self):
derivatives = [1.0, 2.0, 3.0]
uncertainties = [0.1, 0.2, ... | Python | 1 |
import matplotlib.pyplot as plt
from pprint import pprint
gpu_nums = [1, 2, 4, 8, 16, 32]
latencies = {
"2.6B": {
1: [0.145, 0.145, 0.144, 0.145, 0.146, 0.154],
2: [0.187, 0.184, 0.182, 0.185, 0.197, 0.213],
4: [0.368, 0.363, 0.362, 0.373, 0.383, 0.426],
8: [0.736, 0.733, 0.733, 0.7... | Python | 1 |
itable: caps.clone(),
permitted: caps.clone(),
ambient: caps,
};
Ok(Some(capabilities))
}
serde_json::Value::Object(o) => {
let capabilities = LinuxCapabilities {
bounding: cap_from_object::<D>(&o, "bounding")?,
... | Rust | 0 |
}
}
}
eprintln!("{}", unique_beacons.len());
let mut max_distance = 0;
for i in 0..offsets.len() {
for j in 0..offsets.len() {
if i != j {
let distance = (offsets[i][0] - offsets[j][0]).abs() + (offsets[i][1] - offsets[j][1]).... | Rust | 0 |
new(self.app().as_middleware().call(&mut request))
}
/// Create a get request
fn get_request(&self, path: &str) -> MockRequest {
self.request_builder(Method::GET, path)
}
/// Issue a GET request
fn get<T>(&self, path: &str) -> Response<T>
where
for<'de> T: serde::Deserializ... | Rust | 0 |
�度器里面还有睡眠任务
// 如果等待时间过长,则下一次时间中断的时候切换地址空间
return TaskResult::NoWakeTask;
}
// 睡眠状态,将当前任务放到调度队列尾部
let sleep_task = scheduler.next_task().unwrap();
let add_ret = scheduler.add_task(sleep_task);
... | Rust | 0 |
cense, use of this software will be governed
// by the Apache License, Version 2.0.
use super::InvalidValue;
use thiserror::Error;
///////////////////////////////////////////////////////////////////////////////
#[repr(u32)]
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, PartialOrd, Ord)]
#[allow(non_camel_case_ty... | Rust | 0 |
eduler Process Died", "Incremental sync scheduler stopped unexpectedly", "Attempting automatic restart")
# Wait a bit and restart
time.sleep(60)
scheduler_process = self.start_continuous_scheduler()
... | Python | 1 |
import struct
import pandas as pd
def write_string(f, s):
if pd.isna(s):
f.write(struct.pack("B", 0))
else:
encoded = s.encode("utf-8")
f.write(struct.pack("B", len(encoded)))
f.write(encoded)
def write_int(f, value, size=4):
f.write(bytes.fromhex(value))
def write_byte(f,... | Python | 1 |
ces in alphabetical order.",
"Write a Python program that prints the first 10 Fibonacci numbers.",
"Write a program that prints the numbers from 1 to 100. But for multiples of three print 'Fizz' instead of the number and for the multiples of five print 'Buzz'. For numbers which are multiples of both thr... | Python | 1 |
"深": 0x64,
"森": 0x65,
"水": 0x66,
"若": 0x67,
"美": 0x68,
"探": 0x69,
"今": 0x6A,
"士": 0x6B,
"店": 0x6C,
"好": 0x6D,
"代": 0x6E,
"名": 0x6F,
"迷": 0x70,
"立": 0x... | Python | 1 |
on a set of boards each consisting of a 5x5 grid of numbers.
//! Numbers are chosen at random, and the chosen number is marked on all boards
//! on which it appears. (Numbers may not appear on all boards.) If all numbers
//! in any row or any column of a board are marked, that board wins. (Diagonals
//! don't count.)
... | Rust | 0 |
F: Fn(i32) -> i32,
{
tokens.consume().ok_or(CONSUME_ERR)?;
let register_idx = tokens.expect_register()?;
registers[register_idx] = {
tokens.consume().ok_or(CONSUME_ERR)?;
if let Ok(integer) = tokens.expect_integer() {
fun(integer)
} else {
let float = token... | Rust | 0 |
from tkinter import *
from tkinter import messagebox
from PIL import Image, ImageTk
root = Tk()
root.title("Авторизация")
w = root.winfo_screenwidth()
h = root.winfo_screenheight()
w = w // 2
h = h // 2
w = w - 480
h = h - 270
root.geometry(f'500x540+{w}+{h}')
root.resizable(width=False, height=False)
root.configure... | Python | 1 |
items.len());
let mut spreading = false;
for item in items {
match item {
Calcit::Symbol { sym: s, .. } if &**s == "&" => {
spreading = true;
}
_ => {
let v = evaluate_expr(item, scope, file_ns.to_owned(), call_stack)?;
if spreading {
match v {
Ca... | Rust | 0 |
= f"\n{Colors.BOLD}{Colors.MAGENTA}{title}{Colors.END}\n"
chart += f"{Colors.YELLOW}{'='*70}{Colors.END}\n"
# Posterior statistics
if 'posterior_stats' in results:
stats = results['posterior_stats']
chart += f"{Colors.CYAN}Posterior Distribution Statistics:{Colo... | Python | 1 |
"""
Point Pillar's Scatter.
Converts learned features from dense tensor to sparse pseudo image. This replaces SECOND's
second.pytorch.voxelnet.SparseMiddleExtractor.
:param output_shape: ([int]: 4). Required output shape of features.
:param num_input_features: <int>. Number of in... | Python | 1 |
WasmPastaFp(x.0 * y.0)
}
#[wasm_bindgen]
pub fn caml_pasta_fp_div(x: WasmPastaFp, y: WasmPastaFp) -> WasmPastaFp {
WasmPastaFp(x.0 / y.0)
}
#[wasm_bindgen]
pub fn caml_pasta_fp_inv(x: WasmPastaFp) -> Option<WasmPastaFp> {
x.0.inverse().map(|x| { WasmPastaFp(x) })
}
#[wasm_bindgen]
pub fn caml_pasta_fp_sq... | Rust | 0 |
AsyncMock()
mock_ws_instance.register_callback = MagicMock()
mock_ws_instance.websocket = mock_websocket
with (
patch(
"homeassistant.components.weatherflow_cloud.coordinator.WeatherFlowWebsocketAPI",
return_value=mock_ws_instance,
),
patch(
"hom... | Python | 1 |
r other materials provided
# with the distribution.
# * Neither the name of Novartis Institutes for BioMedical Research Inc.
# nor the names of its contributors may be used to endorse or promote
# products derived from this software without specific prior written permission.
#
# THIS SOFTWARE I... | Python | 1 |
res.par_iter().cloned())
.with_min_len(2)
.mapfold_reduce_into(
&mut names,
|names, (name, score)| {
names.push(name);
score
},
Default::default,
|left_names, mut right_names| {
left_names.append(... | Rust | 0 |
use crate::{
errors::catch,
raw::{cx_ecfp_private_key_t, cx_ecfp_public_key_t},
};
use core::mem::MaybeUninit;
use zeroize::{Zeroize, Zeroizing};
pub fn cx_edward_compress_point(curve: Curve, p: &mut [u8]) -> Result<usize, Error> {
let curve: u8 = curve.into();
cfg_if... | Rust | 0 |
here::new(Point3::new(0.0, -1000.0, 0.0), 1000.0, Box::new(Lambertian::new(Box::new(checker))))));
for a in -10..10 {
for b in -10..10 {
let center = Point3::new(a as f32 + 0.9*random_float_from_0_to_1(), 0.2, b as f32 + 0.9*random_float_from_0_to_1());
if (center.to_vec() - vec... | Rust | 0 |
def build_scheduler(cfg, optimizer):
name = cfg.SCHEDULER.TYPE
if name == '':
warnings.warn('No scheduler is built.')
return None
elif hasattr(torch.optim.lr_scheduler, name):
scheduler = getattr(torch.optim.lr_scheduler, name)(optimizer, **
cfg.SCHEDULER.get(name, dict()... | Python | 1 |
import os
from celery import Celery, signature
os.environ.setdefault("DJANGO_SETTINGS_MODULE", "core.settings")
app = Celery("sessiontrackr")
app.config_from_object("django.conf:settings", namespace="CELERY")
app.autodiscover_tasks()
app.conf.update(
task_serializer="json",
accept_content=["json"],
res... | Python | 1 |
= 0;
let mut res = hv_vmx_read_capability(VMXCap::PINBASED, &mut vmx_cap_pinbased);
if res != 0 {
panic!("vmx read capability res: {}", res);
}
res = hv_vmx_read_capability(VMXCap::PROCBASED, &mut vmx_cap_procbased);
if res != 0 {
panic!("vmx read capability res: {}", res);
}
res = hv_vmx_read_cap... | Rust | 0 |
x = (non_cfg_x, cond_token)
x.append(non_cfg_x)
if cfg_scale[0] > 1.0:
x.append(torch.concat([cond_token, uncond_token]))
else:
x.append(cond_token)
sample_pre = sample_pre[:, cond_len:]
sample_post = sample_post[:, cond_len:]
sample = (sample_pre... | Python | 1 |
import frappe
__version__ = "15.13.1"
def refetch_resource(cache_key: str | list, user=None):
frappe.publish_realtime(
"hrms:refetch_resource",
{"cache_key": cache_key},
user=user or frappe.session.user,
after_commit=True,
)
| Python | 1 |
use serde::{Deserialize, Serialize};
use crate::network::internal::NetworkError;
use crate::types::dag::Operation;
use crate::types::{CudaKernelId, EventId, SyncId, TaskletOutput, WorkerInfo};
#[derive(Debug, Serialize, Deserialize)]
pub(crate) enum DriverMsg {
Submit(Vec<Operation>),
Compile(CudaKernelId, Cu... | Rust | 0 |
[3]
);
assert_eq!(
LocalToken::decrypt(
&test_local_sk,
&invalid_local,
Some(FOOTER.as_bytes()),
None
)
.unwrap_err(),
Error::TokenValidation
);
}
#[test]
fn err_on_modif... | Rust | 0 |
rkers, plan=plan)
def rfft2(x, s=None, axes=(-2, -1), norm=None,
overwrite_x=False, workers=None, *, plan=None):
return rfftn(x, s, axes, norm, overwrite_x, workers, plan=plan)
def irfftn(x, s=None, axes=None, norm=None,
overwrite_x=False, workers=None, *, plan=None):
return _execute_nD(... | Python | 1 |
= (500 - COG[1]) * 1.08 # 更新 COG_height 為當前 COG 的 y 值
else:
COG_height = COG_last_height
###------右下角高度表示------___________________________________________________________________________________________________________________________________
# 提取 CT 和 COG 的 y 座標
CT_2dy = projected_p... | Python | 1 |
t_params(
time_series_df_default_index, dataset_id, id_col_name
):
model = forecasting.ARIMAPlus(
horizon=100,
auto_arima=True,
auto_arima_max_order=4,
auto_arima_min_order=1,
data_frequency="daily",
holiday_region="US",
clean_spikes_and_dips=False,
... | Python | 1 |
avaliable fields see [scgccan](scgccan) module"]
pub type SCGCCAN = crate::Reg<u32, _SCGCCAN>;
#[allow(missing_docs)]
#[doc(hidden)]
pub struct _SCGCCAN;
#[doc = "`read()` method returns [scgccan::R](scgccan::R) reader structure"]
impl crate::Readable for SCGCCAN {}
#[doc = "`write(|w| ..)` method takes [scgccan::W](s... | Rust | 0 |
# -*- coding: utf-8 -*-
"""
Created on Tue Feb 21 14:50:19 2023
@author: dell
"""
"""
MC simulation
"""
import scipy.io as scio
import numpy as np
import matplotlib.pyplot as plt
import tensorflow as tf
import os
os.environ['KMP_DUPLICATE_LIB_OK']='True'
###系统参数
alpha=-0.5
beta=0.1
omega=1.4
D1=0.01
D2=0.01 #噪声... | Python | 1 |
et_as("idVars")?;
let value_vars: Vec<String> = params.get_as("valueVars")?;
ldf.melt(id_vars, value_vars).try_into_js(&cx)
}
#[js_function(1)]
pub fn tail(cx: CallContext) -> JsResult<JsExternal> {
let params = get_params(&cx)?;
let ldf = params.get_external::<LazyFrame>(&cx, "_ldf")?.clone();
let... | Rust | 0 |
:*;
<gh_stars>100-1000
use specs::prelude::*;
use crate::{EquipmentChanged, Item, InBackpack, Equipped, Pools, Attributes, gamelog::GameLog, AttributeBonus,
gamesystem::attr_bonus, StatusEffect};
use std::collections::HashMap;
pub struct EncumbranceSystem {}
impl<'a> System<'a> for EncumbranceSystem {
#[allow... | Rust | 0 |
from random import randint, uniform
combat_side_cal = (1, 0.4, 0.1) # for melee attack target defend side modifier 0 = Front, 1 = Side, 2 = Rear
infinity = float("inf")
def cal_charge_hit(self, target, hit_side, hit_angle):
"""Calculate charge attack hit chance and defence chance, then damage"""
attacker_lu... | Python | 1 |
let client = context.data.read().await.get::<ReqwestContainer>().cloned().unwrap();
let search_endpoint = "https://api.themoviedb.org/3/search/tv";
let search_query = ("query", &show.replace(" --cast", "").replace(" -c", ""));
let search_response = client.get(search_endpoint).query(&[("api_key", &api_... | Rust | 0 |
tly_chart(price_fig, use_container_width=True)
# Display RSI chart
st.subheader("Relative Strength Index (RSI)")
rsi_fig = create_rsi_chart(hist_data, rsi_window)
st.plotly_chart(rsi_fig, use_container_width=True)
# Display financial data table
s... | Python | 1 |
void main() {
gl_Position = vec4(position, 0.0, 1.0);
v_tex_coords = tex_coords;
v_color = color;
v_mode = mode;
}
";
/// The fragment shader used within the `glium::Program` for OpenGL ES.
pub const FRAGMENT_SHADER_300_ES: &'static str = "
#version 300 es
precision mediu... | Rust | 0 |
>) -> Point {
let q = p.right();
if q.x >= mat.width() as isize {
point(0, q.y)
} else {
q
}
}
#[cfg(test)]
mod test {
use super::*;
#[test]
fn solution() {
let a = solve(&input());
assert_eq!(a, 530);
}
}
extern crate gtk;
extern crate gio;
extern crate... | Rust | 0 |
JSON blob is emitted to stdout is valid.
try:
json.loads(stdout)
except ValueError as e:
raise AssertionError(
f"Could not generate CLI skeleton for command: {command_name} "
f"{operation_name}\n stdout:\n{stdout}\nstderr:\n{stderr}\n"
)
def _run_cmd(cmd, expec... | Python | 1 |
len_site {
let aa : char = ( *site )[ i ];
let add : f64 = freq[ &aa ] + ( *weight_list )[ i ];
freq.insert( aa, add );
}
//println!( "{:?}", freq );
freq
}
///////////////////////////////////////////////////////////////////////////////////////////
// SHANNON'S ENTROPY WITH 7 AMINO ACID TYPES
////////////... | Rust | 0 |
from GridWorld import *
from library import *
import matplotlib.pyplot as plt
# Environment
goals = [(3,3)] # Task goals
env = GridWorld(goals=goals)
### Load WVF
WVF = load_WVF("WVF.npy")
### Planning using inferred dynamics
fig = plt.figure(1, figsize=(20, 20), dpi=60, facecolor='w', edgecolor='k')
params = {'font... | Python | 1 |
Vnew = spsolve( M, V + B )
scale = np.maximum( np.abs( Vnew ), np.ones_like( Vnew ) )
residuals = np.abs( Vnew - Vhat ) / scale
if np.all( residuals[:-1] < tol ):
V = Vnew
break
else:
Vhat = Vnew
... | Python | 1 |
wd_zmm_k1z_zmm_zmmm512
MemorySize::Unknown,// Punpckldq_mm_mmm32
MemorySize::Unknown,// Punpckldq_xmm_xmmm128
MemorySize::Unknown,// VEX_Vpunpckldq_xmm_xmm_xmmm128
MemorySize::Unknown,// VEX_Vpunpckldq_ymm_ymm_ymmm256
MemorySize::Broadcast128_UInt32,// EVEX_Vpunpckldq_xmm_k1z_xmm_xmmm128b32
MemorySize::Broadcast2... | Rust | 0 |
即 [`crate::MultiPartsV1Uploader`]。
V1,
/// 分片上传器 V2
///
/// 即 [`crate::MultiPartsV2Uploader`]。
#[default]
V2,
}
impl AutoUploaderObjectParams {
/// 创建自动上传器对象参数构建器
#[inline]
pub fn builder() -> AutoUploaderObjectParamsBuilder {
Default::default()
}
/// 获取期望的分片上传调度器... | Rust | 0 |
result["value"] = value
# rule_schema["then"] = result
#
# return rule_schema
#
#
# def build_index_list(cconjs, if_docs):
# index_list = [0]
# for c in cconjs:
# index_list.append(c.i)
# index_list.append(len(if_docs))
# return index_list
#
#
# def root_match(nlp, rul... | Python | 1 |
# cook your dish here
t=int(input())
for i in range(t):
x,y,z=map(int,input().split())
a1=x*y
a2=y*z
a3=x*z
b1=z
b2=x
b3=y
if a1%b1==0 :
print(f"{a1} {b1}")
elif a2%b2==0:
print(f"{a2} {b2}")
elif a3%b3==0:
print(f"{a3} {b3}")
else:
print(-1... | Python | 1 |
fn check_pragma_directives(&self, solidity: &mut Vec<&str>, abicoder: &mut Vec<&str>) {
let mut op = None;
let mut lower: Option<f32> = None;
let mut upper: Option<f32> = None;
for &literal in solidity.iter() {
match literal {
"^" | ">" | ">=" | "<=" | "<" ... | Rust | 0 |
/// Writes out a C++ wrapper class for the given type, which contains various utilities to access
/// the underlying C-mapped type safely avoiding some common memory management issues by handling
/// resource-freeing and prevending accidental raw copies.
pub fn write_cpp_wrapper(cpp_header_file: &mut File, ty: &str, h... | Rust | 0 |
",
}
return make_response(jsonify(response), 400)
for key, value in update_fields.items():
setattr(interface_obj, key, value)
BaseDao.safe_commit()
return jsonify(interface_obj.as_dict())
@interface_bp.route("/<hostname>/<if_name>", methods=["DELETE"])
@check_access(["admin"])
def... | Python | 1 |
tree = let_tree
return tree
@Walker
def fix_columns(tree, stop, elt_aliases, **kw):
"""if the "columns" name isn't attribute accessed, replace it with the
same name witn '_alias' appended."""
if (type(tree) is ast.Attribute and type(tree.value) is ast.Name
and any(map(lambda elt: elt.id... | Python | 1 |
matches!(
result.body_location,
optic_engine::BodyAnalysisLocation::MatchedQueryParameters { .. }
)
});
for result in results {
let pointers = {
let mut set = HashSet::new();
set.insert(interaction_pointer.clone());
set
};
learned_shape_dif... | Rust | 0 |
c @ s5 d d l Td d l Z d d l Z d Z d Z d Z d Z d d d YZ d d! d YZ d
d" d YZ d d# d
YZ d d$ d YZ
d d% d YZ d d& |