text string | label_name string | labels int64 |
|---|---|---|
cars = int(input())
distance = float(input())
maxi = 0
winner = ""
for car in range(cars):
id, vel, fuel = list(input().split())
vel = float(vel)
fuel = float(fuel)
rof = fuel/(distance/vel)
efficiency = vel/rof
if efficiency > maxi:
maxi = efficiency
winner = id
print(winn... | Python | 1 |
del_all"))
def test_model_monitors_get_model_all(client, api_key):
response_multi = client.get(
f"/v1/model-monitors?model_id={state.model_multi['id']}",
headers={"api-key": api_key},
)
response_all = client.get(
f"/v1/model-monitors",
headers={"api-key": api_key},
)
... | Python | 1 |
);
// Add one to the result and test for it.
tmp.add_assign(&Fr(FrRepr::from(1)));
assert!(tmp.0.is_zero());
}
// Test associativity
let mut rng = XorShiftRng::from_seed([0x5dbe6259, 0x8d313d76, 0x3237db17, 0xe5bc0654]);
for _ in 0..1000 {
// Generate a, b, c and ensur... | Rust | 0 |
relative_path = f"{ensemble_folder}/{save_name}"
retrieved_image_file_paths_per_obj.append(relative_path)
else:
print(f"Image not found for ID: {img_id}")
retrieved_image_file_paths_per_obj.append(None)
'''
... | Python | 1 |
atten)]
pub(crate) mac: Macro,
}
}
ast_struct! {
/// A parenthesized type equivalent to the inner type.
pub struct TypeParen {
pub(crate) elem: Box<Type>,
}
}
ast_struct! {
/// A path like `std::slice::Iter`, optionally qualified with a
/// self-type as in `<Vec<T> as SomeTrait... | Rust | 0 |
}
}
pub fn page_rank<NI: Idx>(
graph: &DirectedCsrGraph<NI>,
config: PageRankConfig,
) -> (Vec<f32>, usize, f64) {
let PageRankConfig {
max_iterations,
tolerance,
damping_factor,
} = config;
let node_count = graph.node_count().index();
let init_score = 1_f32 / node_c... | Rust | 0 |
time_point.year = int(year.group()) if year else self.time_base_handler[0]
time_handler = time_point.handler()
return time_handler, time_handler, 'time_span', 'accurate'
def _normalize_year(self, time_string, time_base_handler):
year = self.year_patterns[0].search(time_string)
... | Python | 1 |
filter
with dataset.filter_camera('structureio_480x640') as ds:
assert len(ds) == len(dataset2)
assert ds.camera == 'structureio_480x640'
# everything should be back to normal
assert len(dataset) == n_samples_total
assert dataset.camera is None
# test with camera filter without con... | Python | 1 |
ProgressEvent::Stats(StatsProgressEvent::ComputeTestStats(
progress,
)));
});
handle_progress_event(ProgressEvent::Stats(
StatsProgressEvent::ComputeTestStatsDone,
));
handle_progress_event(ProgressEvent::Stats(StatsProgressEvent::Finalize));
let overall_column_stats = train_column_stats.clone().mer... | Rust | 0 |
pub const INTERNET_FLAG_PRAGMA_NOCACHE: u32 = 256u32;
#[doc = "*Required features: 'Win32_Networking_WinInet'*"]
pub const INTERNET_FLAG_RAW_DATA: u32 = 1073741824u32;
#[doc = "*Required features: 'Win32_Networking_WinInet'*"]
pub const INTERNET_FLAG_READ_PREFETCH: u32 = 1048576u32;
#[doc = "*Required features: 'Win32... | Rust | 0 |
-> bool {
match value {
Some(v) => predicate(v),
_ => false
}
}
fn validate_ref<T>(value: &Option<T>, predicate: impl Fn(&T) -> bool) -> bool {
match value {
Some(v) => predicate(v),
_ => false
}
}
fn is_valid_birth_year(v: i32) -> bool { v >= 1920 && v <= 2002 }
fn i... | Rust | 0 |
#!/usr/bin/python
import os, socket, sys, time
host = ''
port = 2007
if len(sys.argv) > 1:
mps = float(sys.argv[1])
else:
mps = 1.0
bps = mps * 1000000
BUFSIZE = int(bps/10) # sleep 100ms at full speed
print "Mbytes/s =", mps
if len(sys.argv) > 3:
host = sys.argv[2]
port = int(sys.argv[3])
print "connecting t... | Python | 1 |
);
v.push(5);
println!("Vector: {:?}", v);
let mut i = 1;
let velem: &mut i32 = &mut v[i];
println!("Vector[{}]: {}", i, velem);
*velem = 3; // Borrow ends
v.push(55);
i += 1;
println!("Vector: {:?}", v);
let velem: &mut i32 = &mut v[i];
println!("Vector[{}]: {}", i, velem)... | Rust | 0 |
#!/usr/bin/env python3
from __future__ import annotations
import argparse
import os
from pathlib import Path
from src.runtime.gh_release import GHConfig, GHReleases, GHError
def main() -> int:
ap = argparse.ArgumentParser(
description="Restore latest index bundle from GitHub Releases"
)
ap.add_a... | Python | 1 |
pub fn with_request(req: &Request, upstream: &'a str) -> Self {
Self {
upstream,
request: req.id,
task_id: -1,
response_buf: Vec::with_capacity(1452),
}
}
}
impl<'a> Future for Forward<'a> {
type Output = Result<Vec<u8>, Error>;
fn poll(mut s... | Rust | 0 |
();
let c1 = Fp::from_be_bytes(&bls12_381::BLS12_381_FIELD, &num.to_bytes_be(), true).unwrap();
let as_vec = decode_fp::serialize_fp_fixed_len(SERIALIZED_FP_BYTE_LENGTH, &c1).unwrap();
encoding.extend(as_vec);
assert!(encoding.len() == SERIALIZED_FP2_BYTE_LENGTH);
assert_eq!(&... | Rust | 0 |
47429717, 332085264, 296925009, 179969654, 285965854, 188329006, 353044452,
907132439, 173498729, 971005353, 886796300, 374137584, 167007939, 257311427, 69578518,
986207933, 820577598, 762893591, 855603877, 154159499, 81230719, 988672413, 560039653,
187206037, 124634358, 756546188, 5... | Rust | 0 |
CharacterChoices {
fn choices(&self, max_times: u8) -> Vec<Character>;
fn choose(&mut self, max_times: u8, character: Character) -> Result<(), ()>;
}
impl CharacterChoices for Option<CharacterStreak> {
fn choices(&self, max_times: u8) -> Vec<Character> {
let mut characters = Character::all();
... | Rust | 0 |
: Env, _msg: MigrateMsg) -> StdResult<Response> {
Ok(Response::default())
}
///! These functions and structs are only relevant to the database migration from schema 5 to 6.
use crate::persisted_fork_choice::PersistedForkChoiceV1;
use crate::schema_change::types::{SszContainerV1, SszContainerV6};
use crate::BeaconCh... | Rust | 0 |
back as 0x0
PARTNUMBER1 OFFSET(0) NUMBITS(4) [],
/// these bits read back as 0x1
DESIGNER0 OFFSET(4) NUMBITS(4) []
],
/// UARTPeriphID2 register
UARTPERIPHID2 [
/// these bits read back as 0x4
DESIGNER1 OFFSET(0) NUMBITS(4) [],
/// this field depends on the r... | Rust | 0 |
imW)))
cv2.rectangle(image, (xmin,ymin), (xmax,ymax), (10, 255, 0), 2)
# Draw label
object_name = category_index[int(classes[i])]['name'] # Look up object name from "labels" array using class index
label = '%s: %d%%' % (object_name, int(scores[i]*100)) # Example: 'person: 72%'
... | Python | 1 |
# This is an automatically generated file converting from the apm format
import casadi as cs
def hs067():
# The optimal objective is (if given in):
f_opt = -1162.02698006
x_opt = cs.DM([1728.37, 16000, 98.1362, 3056.04, 2000, 90.6185, 94.1896, 10.4144, 2.61574, 149.569])
x = cs.MX.sym('x', 10)
obj... | Python | 1 |
params: AffineBGParams,
wraparound: bool,
mosaic_x: u32,
mosaic_y: u32,
first_target: bool,
second_target: bool,
}
impl AffineBG {
/// Internal Screen Size (dots) and size of BG Map (bytes):
///
/// Value Rotation/Scaling Mode
/// 0 128x128 (256 bytes)
/// 1... | Rust | 0 |
ot, fg="#494e54", text="400px", font=("Calibri", 15, "normal"), bg="#101317", wraplength=1)
menubar = Menu(root)
file = Menu(menubar, tearoff = 0)
menubar.add_cascade(label = 'File', menu = file)
file.add_command(label ='New', command= lambda: resetWorkspace())
file.add_command(label ='Save As', command= lambda: save... | Python | 1 |
到:{}".format(zip_filename))
backup_type = 1 if first_backup else 0
cloud_backup_path = zip_filename # 初始备份路径为本地路径
# backup_to="alioss"
backup_task_status = True
# 判断是否需要上传到云存储
if backup_to and backup_to != 'localhost':
if backup_to in ["tianyiyun","... | Python | 1 |
from dataclasses import dataclass
from mypy.nodes import Block, CallExpr, ComparisonExpr, ExpressionStmt, IfStmt, MemberExpr
from refurb.checks.common import get_mypy_type, is_equivalent, is_same_type, stringify
from refurb.error import Error
@dataclass
class ErrorInfo(Error):
"""
If you want to remove a va... | Python | 1 |
#!/usr/bin/env python
# -*- coding: utf-8 -*
import os
import sys
import tty, termios
import rospy
from geometry_msgs.msg import Twist
from std_msgs.msg import String
from std_msgs.msg import Float64
# 全局变量
pub_action = rospy.Publisher('action_command', String, queue_size=10)
def keyboardLoop():
#初始化
... | Python | 1 |
imit")]
pub enum LimitDef {
None,
ByStakeAbsolute(#[serde(with = "RatioDef")] Ratio),
}
#[derive(Debug, Clone, Copy, Deserialize, Serialize, PartialEq, Eq)]
#[serde(remote = "Ratio")]
pub struct RatioDef {
pub numerator: u64,
pub denominator: NonZeroU64,
}
#[derive(Deserialize, Serialize)]
#[serde(rem... | Rust | 0 |
# Copyright 2022 The T5X Authors.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writ... | Python | 1 |
import torch
from diffusers import DiffusionPipeline, DPMSolverMultistepScheduler
# model_base = "stabilityai/stable-diffusion-2-1-base"
# pipe = DiffusionPipeline.from_pretrained(model_base, torch_dtype=torch.float16, cache_dir=CACHE_DIR, local_files_only=True)
# pipe.scheduler = DPMSolverMultistepScheduler.from_co... | Python | 1 |
def xywh2xyxy(x):
y = x.clone() if isinstance(x, torch.Tensor) else np.copy(x)
y[:, 0] = x[:, 0] - x[:, 2] / 2
y[:, 1] = x[:, 1] - x[:, 3] / 2
y[:, 2] = x[:, 0] + x[:, 2] / 2
y[:, 3] = x[:, 1] + x[:, 3] / 2
return y
| Python | 1 |
Perioidc 0"]
pub struct PER0_R(crate::FieldReader<bool, bool>);
impl PER0_R {
pub(crate) fn new(bits: bool) -> Self {
PER0_R(crate::FieldReader::new(bits))
}
}
impl core::ops::Deref for PER0_R {
type Target = crate::FieldReader<bool, bool>;
#[inline(always)]
fn deref(&self) -> &Self::Target... | Rust | 0 |
from sqlalchemy import create_engine
from sqlalchemy.orm import sessionmaker
from db.models import Base
# Create the database engine
engine = create_engine('sqlite:///project.db', echo=True)
# Create a configured "Session" class
Session = sessionmaker(bind=engine)
# Create the session object (global)
session = Sessi... | Python | 1 |
###
# Author: Kai Li
# Date: 2021-06-20 00:21:33
# LastEditors: Please set LastEditors
# LastEditTime: 2022-05-27 11:19:51
###
from torch.optim.optimizer import Optimizer
from torch.optim import Adam, RMSprop, SGD, Adadelta, Adagrad, Adamax, AdamW, ASGD
from torch_optimizer import (
AccSGD,
AdaBound,
AdaMo... | Python | 1 |
, &buff);
}
}
}
// ----------
// Unit tests
// ----------
#[test]
fn scaling_works() {
let canvas: CanvasRef<u32> = Canvas::new(100, 21); // 100 wide, 21 high
let c = canvas.borrow();
let (scale_x, scale_y, offset) = c.calc_scaling(-1.0, 1.0, 100); // 100 values from -1.0 to 1.0
assert_eq... | Rust | 0 |
, colorize_tokens, space_tokens};
pub use commands::{Command, get_command};
fn main() {
let term = Term::stdout();
let mut factory = Factory::new();
while let Ok(line) = term.read_line() {
parse_line(&line, &mut factory, &term)
.expect("parse_line");
}
}
fn parse_line(line: &str, factory: &mut Factory, te... | Rust | 0 |
0xE92A_9276),
(r"meshes\f\flora_bm_treestump_06.nif", 0x031C_114B, 0xF985_942A),
(r"meshes\w\w_huntsman_crossbow.nif", 0x0404_0F21, 0x62A7_6C92),
(r"meshes\w\w_huntsman_longsword.nif", 0x0404_0F21, 0xCDE4_5BCF),
(r"meshes\m\gravetar.nif", 0x052F_7154, 0x9C84_6894),
(r"meshes\m\horkertusk.nif",... | Rust | 0 |
: self }
}
}
<reponame>DigitalPulseSoftware/NazarustEngine
/// Represents a Nazara application with Windows
use nazara_core::application::Application;
use std::{cell::RefCell, collections::HashMap, rc::Rc};
use winit::{
event::{Event, WindowEvent},
event_loop::{ControlFlow, EventLoop},
window::{Window, ... | Rust | 0 |
str.op() == &asm::OpWire::Cat => {
assembler.expand_instr_cat(instr)?;
}
asm::Instr::Wire(instr) if instr.op() == &asm::OpWire::Ext => {
assembler.expand_instr_ext(instr)?;
}
asm::Instr::Asm(instr) => assembler.expand_instr_asm(instr)?,
... | Rust | 0 |
# coding=utf-8
# Copyright 2025 The Google Research Authors.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicab... | Python | 1 |
# *****************************************************************************
# Copyright (c) 2020, Intel Corporation All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are met:
#
# Redistributions of sou... | Python | 1 |
");
let spotify_access_token = {
let token_data = &mut *(&*token_data).lock().unwrap();
token_data.get()
}?;
mark("Got spotify access token");
let (artist_stats, track_stats) = match rayon::join(
|| db_util::get_artist_stats(&user, conn, &spotify_access_token),
|| db_ut... | Rust | 0 |
, f: impl FnOnce(&mut Model<Self::Store>) + 'static) {
self.bridge()
.borrow_mut()
.send_service(ServiceRequest::ApplyOnce(Box::new(f)))
}
/// Like [reduce](Self::reduce) but from a callback.
///
/// ```ignore
/// let onclick = dispatch.reduce_callback(|s| s.count +=... | Rust | 0 |
ops.stop_gradient(v2[:, None]), v1[:, :, None])[:, 0, 0]
surrogate = ops.sum((ops.stop_gradient(v2) * v1), axis=-1)
nll = -self.base_distribution.log_prob(z)
maximum_likelihood_loss = nll - surrogate
reconstruction_loss = ops.sum((x - x_pred) ** 2, axis=-1)
losses = maximum_like... | Python | 1 |
#* coding:UTF8 *
import RPi.GPIO as GPIO
import time
import YB_Pcb_Car #导入Yahboom专门库文件
import Distance
#from JudgeTreasure import RED_GREEN, BLUE_YELLOW, BLUE_GREEN, RED_YELLOW
#
car = YB_Pcb_Car.YB_Pcb_Car()
#
BLUE_YELLOW = 2 # 蓝色真
BLUE_GREEN = 4 # 蓝色假
RED_GREEN = 1 # 红色真
RED_YELLOW = 3 # 红色假
Tracking_Right1 = ... | Python | 1 |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# Copyright 2019 Wuhan PS-Micro Technology Co., Itd.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICE... | Python | 1 |
address 127.0.0.1.')
if settings.verbose >= 2:
print('Local interface found ' + ' '.join(nics))
return nics
def get_common_interfaces(settings, all_host_names, remote_host_names=None, fn_cache=None):
'''
Find the set of common and routed interfaces on all the hosts.
:param settings: the o... | Python | 1 |
from __future__ import annotations
from typing import TYPE_CHECKING
from cleo.helpers import argument
from poetry.console.commands.env_command import EnvCommand
from poetry.utils._compat import WINDOWS
if TYPE_CHECKING:
from poetry.core.masonry.utils.module import Module
class RunCommand(EnvCommand):
nam... | Python | 1 |
"""Config flow for Ondilo ICO."""
import logging
from homeassistant.helpers import config_entry_oauth2_flow
from .const import DOMAIN
from .oauth_impl import OndiloOauth2Implementation
class OAuth2FlowHandler(
config_entry_oauth2_flow.AbstractOAuth2FlowHandler, domain=DOMAIN
):
"""Config flow to handle Ondi... | Python | 1 |
"""
This module houses the GEOS ctypes prototype functions for the
unary and binary predicate operations on geometries.
"""
from ctypes import c_char, c_char_p, c_double
from django.contrib.gis.geos.libgeos import lgeos, GEOM_PTR
from django.contrib.gis.geos.prototypes.errcheck import check_predicate
## Binary & una... | Python | 1 |
FilterItems,
NewWindow(WindowId),
ReloadWindow,
CloseBuffers(Vec<BufferId>),
RequestPaintRect(Rect),
ApplyEdits(usize, u64, Vec<TextEdit>),
ApplyEditsAndSave(usize, u64, Result<Value>),
DocumentFormat(PathBuf, u64, Result<Value>),
DocumentFormatAndSave(PathBuf, u64, Result<Value>, O... | Rust | 0 |
old_count) |
((counts_grid == old_count) & (faces_grid > old_face)))
fly_mask = fly_mask & (faces_grid != 1)
legal_mask[0] = fly_mask.squeeze(0)
ceil_half = (old_count + 1) // 2
zhai_mask = (counts_grid >= ceil_half)
... | Python | 1 |
s, features, labels, adapter=None):
if cfg['search_hp'] == True:
beta_list = [i * (cfg['search_scale'][0] - 0.1) / cfg['search_step'][0] + 0.1 for i in range(cfg['search_step'][0])]
best_acc = 0
best_beta, best_alpha = 0, 0
if adapter:
affinity = adapter(features)... | Python | 1 |
:expr; $($key:ident: $t:ty => $fn:expr$(;)*)+) => {{
const KEYS: &'static [&'static str] = &[
$(stringify!($key),)+
];
let mut matchers = MatcherVec::new();
while let Some(key) = $access.next_key()? {
match key {
$(
stringify!... | Rust | 0 |
} else if ccd.nocase {
if ccd.data.matches(ch.to_lowercase().next().unwrap()) {
//println!("CharClass {} i-matches {} at {}", ccd.data, ch, str_pos);
nlist.add_task(ccd.goto);
}
}
... | Rust | 0 |
Holder{
SignalDataHolder::default()
}
pub fn update(&mut self,pointer:Pointer,data:Vec<u8>){
self.pointer = pointer;
self.data = data;
}
}
#[derive(Debug)]
pub struct SignalData{
pub result:bool,
pub data:SignalDataHolder,
pub waker:Arc<Notify>
}
impl SignalData{
p... | Rust | 0 |
from model import MyModel
import dgl
import time
import torch
import argparse
parser = argparse.ArgumentParser(description="Speed benchmark")
parser.add_argument("-N", "--max_node", type=int, default=500, help="max node number")
parser.add_argument(
"-B", "--batch_size", type=int, default=100, help="how many graph... | Python | 1 |
# This Source Code Form is subject to the terms of the Mozilla Public
# License, v. 2.0. If a copy of the MPL was not distributed with this
# file, You can obtain one at http://mozilla.org/MPL/2.0/.
class ReplicateRetriever:
entry_number = 0
def merge(self, data):
# Merge data from all subtests
... | Python | 1 |
val if val > 0xFF => 0xFF,
val => val as u8,
}
}
}
macro_rules! do_dithering(
($map:expr, $image:expr, $err:expr, $x:expr, $y:expr) => (
{
let old_pixel = $image[($x, $y)];
let new_pixel = $image.get_pixel_mut($x, $y);
$map.map_color(new_pixel);... | Rust | 0 |
string_1), Ok(()));
assert_eq!(is_usize(usize_string_2), Ok(()));
// invalid usize strings
let invalid_usize_string_1 = String::from("0-1");
let invalid_usize_string_2 = String::from("usize");
let invalid_usize_string_3 = String::from("?");
let invalid_usize_string_4 = S... | Rust | 0 |
trace buffer.
/// * `buffer` - New gradient buffer instance.
fn update_trace(&self, trace: &mut B, buffer: &B);
}
/// Accumulating eligibility trace rule.
pub struct Accumulate {
/// Discount factor.
pub gamma: f64,
/// Forgetting rate.
pub lambda: f64,
}
impl<B: BufferMut> UpdateRule<B> for... | Rust | 0 |
from functools import wraps
from types import FunctionType
from Script.Core import cache_control, constant, constant_promise, game_type, get_text
cache: game_type.Cache = cache_control.cache
""" 游戏缓存数据 """
_: FunctionType = get_text._
""" 翻译api """
def add_premise(premise: str) -> FunctionType:
"""
添加前提
K... | Python | 1 |
SetupStatus";
#[doc = "*Required features: `\"Win32_Security_Cryptography_Certificates\"`*"]
pub const wszREGSP4DEFAULTCONFIGURATION: &str = "DefaultConfiguration";
#[doc = "*Required features: `\"Win32_Security_Cryptography_Certificates\"`*"]
pub const wszREGSP4KEYSETNAME: &str = "KeySetName";
#[doc = "*Required featu... | Rust | 0 |
def read_database (filename):
f = open (filename)
db = []
for line in f:
db.append(line.rstrip())
f.close()
return db
def build_map (query, w):
res = {}
for i in range(len(query)-w+1):
subseq = query[i:i+w]
if subseq in res:
res[subseq].append(i)
... | Python | 1 |
htm);;MHT文件 (*.mht);;文本文件 (*.txt)"
)
if not file_name:
return
# 获取文件扩展名
ext = os.path.splitext(file_name)[1].lower()
try:
if ext == '.eml':
subject, content = self._pars... | Python | 1 |
# SPDX-License-Identifier: BUSL-1.1
import os
import pytest
CHAIN_ID = os.getenv("CHAIN_ID", 10)
@pytest.fixture
def sugar_contract(project, accounts):
# Since we depend on the rest of the protocol,
# we just point to an existing deployment
yield project.RewardsSugar.at(os.getenv(f"REWARDS_SUGAR_ADDRESS_... | Python | 1 |
onse, SetRegularError<E>> {
if self.ok {
Ok(self)
} else {
Err(SetRegularError::Unknown(
"Server failed without providing an error message.".into(),
))
}
}
}
#[derive(Debug)]
pub enum SetRegularError<E: Error> {
/// The response was no... | Rust | 0 |
with open(file_path, 'w', encoding='utf-8') as f:
json.dump(data, f, ensure_ascii=False, indent=4)
self.logger.info(f"角色详细信息数据库已保存到 {file_path}")
except Exception as e:
self.logger.error(f"保存角色详细信息数据库失败: {e}")
raise
... | Python | 1 |
#!/usr/bin/env python3
# Copyright (c) Meta Platforms, Inc. and affiliates.
#
# This source code is licensed under both the MIT license found in the
# LICENSE-MIT file in the root directory of this source tree and the Apache
# License, Version 2.0 found in the LICENSE-APACHE file in the root directory
# of this source ... | Python | 1 |
nctions::fetch_an_integer_async();
let result_final = result2
.and_then(move |data| {
ok(MyObj {
id: data as u32,
name: info.into_inner().friend,
// on into_inner() from https://users.rust-lang.org/t/explanation-of-into-inner/13872, also see https:... | Rust | 0 |
# store AVPR for features (cell only)
df_avpr_feat_cell = pd.DataFrame([], index=['AVPR'], columns=attributes)
df_avpr_feat_cell.loc['AVPR'] = avpr_feats
df_avpr_feat_cell.to_csv(folder_output + "/train_avpr_features.csv")
# store AUC for features (cell only)
df_auc_feat_cel... | Python | 1 |
:
d = 1
return [-(x[0])**(-((d+1)/d))]
idx = 7
if idx >= initsize:
w0 = W(1E-1)
bounds = Bounds([w0],[Wbudget])
nonlinear_constraint = NonlinearConstraint(cons_f, threshold, epsofw(w0, d=1), jac=cons_J, hess=BFGS())
print("Index: {}, point x: {}(e), initial work value {}".format(idx, Xt... | Python | 1 |
userSchema:dict = {
"type": "object",
"properties": {
"username": { "type": "string" },
"email": { "type": "string", "format": "email" },
"password": { "type": "string" },
"name": { "type": "string" },
"role": { "type": "integer" },
"gender": { "type": "string" },... | Python | 1 |
import pyrustfft
import numpy as np
import matplotlib.pyplot as plt
t = np.linspace(0, 25, 1000)
real = np.sin(t)
imag = np.zeros(len(real))
print(real)
print(imag)
ft_real, ft_imag = pyrustfft.fft(real, imag)
print(ft_real)
print(ft_imag)
ft_real_inv, ft_imag_inv = pyrustfft.ifft(ft_real, ft_imag)
print(ft_real_... | Python | 1 |
e::<u16>();
match signal {
3 => DolorOneFloat::Dolor,
5 => DolorOneFloat::Other,
_ => DolorOneFloat::_Other(self.one_float_raw()),
}
}
/// Get raw value of OneFloat
///
/// - Start bit: 0
/// - Signal size: 12 bits
/// - Factor: 0.5
/// -... | Rust | 0 |
def event_cb(e):
code = e.get_code()
chart = e.get_target()
if code == lv.EVENT.VALUE_CHANGED:
chart.invalidate()
if code == lv.EVENT.REFR_EXT_DRAW_SIZE:
e.set_ext_draw_size(20)
elif code == lv.EVENT.DRAW_POST_END:
id = lv.chart.get_pressed_point(chart)
if id == lv... | Python | 1 |
import matplotlib.pyplot as plt
import numpy as np
# Set Matplotlib backend to 'Agg' for non-GUI usage
plt.switch_backend('Agg')
# Data for pie chart
labels = ['Apples', 'Oranges', 'Bananas']
sizes = [35, 45, 20]
colors = ['#1f77b4', '#ff7f0e', '#2ca02c']
explode = (0.1, 0, 0) # Only explode the 1st slice (i.e., 'Ap... | Python | 1 |
# WARNING: Please don't edit this file. It was generated by Python/WinRT v0.9.210202.1
import typing, winrt
_ns_module = winrt._import_ns_module("Windows.UI.Core.Preview")
try:
import winrt.windows.foundation
except:
pass
SystemNavigationCloseRequestedPreviewEventArgs = _ns_module.SystemNavigationCloseReque... | Python | 1 |
q_tmp = rgoth_square.phi_q_to_the_minus_1(&FE::q()).reduce();
let gq = gq_tmp.exp(&FE::q());
match gq == self.gq {
true => Ok(()),
false => Err(ErrorReason::SetupError),
}
}
/// randomly sample a scalar (secret key) and compute its corresponding group element (p... | Rust | 0 |
ad::graphics::Texture::from_data_and_format(
ctx,
&tex_water_raw.bytes,
TextureParams {
format: TextureFormat::RGBA8,
wrap: TextureWrap::Repeat,
filter: FilterMode::Linear,
width: tex_water_raw.width as u32,
... | Rust | 0 |
nt_numbers.push_back(i);
while current_sum > part1 {
// Start pulling off the earlier numbers until we're back below
current_sum -= current_numbers.pop_front().unwrap();
}
}
let min = current_numbers.iter().min().unwrap();
let max = current_numbers.iter().max().unwrap... | Rust | 0 |
er::color_edit_button_srgba(
ui,
&mut egui_color32,
egui::color_picker::Alpha::Opaque,
)
.changed()
{
let egui_srgba: egui::color::Rgba = egui_color32.into();
*color = nannou::color::srgba(
egui_srgba.r(),
egui_srgba.g(),
egui_srgba... | Rust | 0 |
Pool: PTP_POOL,
CleanupGroup: PTP_CLEANUP_GROUP,
CleanupGroupCancelCallback: PTP_CLEANUP_GROUP_CANCEL_CALLBACK,
RaceDll: PVOID,
ActivationContext: *mut ACTIVATION_CONTEXT,
FinalizationCallback: PTP_SIMPLE_CALLBACK,
u: DWORD,
CallbackPriority: TP_CALLBACK_PRIORITY,
Size: DWORD,
}}
UN... | Rust | 0 |
import json
from typing import Any
from benchmark.tau_bench.envs.tool import Tool
class GetOrderDetails(Tool):
@staticmethod
def invoke(data: dict[str, Any], order_id: str) -> str:
orders = data["orders"]
if order_id in orders:
return json.dumps(orders[order_id])
raise Exc... | Python | 1 |
from flask import Flask #Importación de Flask
app = Flask(__name__) #Crea instancia de Flask
app.secret_key = "clave secreta!"
| Python | 1 |
CDIV2_5)
}
#[doc = "Divide by 32"]
#[inline(always)]
pub fn soscdiv2_6(self) -> &'a mut W {
self.variant(SOSCDIV2_A::SOSCDIV2_6)
}
#[doc = "Divide by 64"]
#[inline(always)]
pub fn soscdiv2_7(self) -> &'a mut W {
self.variant(SOSCDIV2_A::SOSCDIV2_7)
}
#[doc = r"Wri... | Rust | 0 |
[str, Any],
rl_weight: float) -> Dict[str, Any]:
"""合併RL和傳統決策"""
# 簡化的決策合併邏輯
merged = {
'selected_satellites': self._merge_satellite_selections(
rl_decision.get('selected_satellites', []),
traditional_decision.get('optimal_pool'... | Python | 1 |
f32_open(r2.next_u32());
assert_eq!(f1, f2);
assert!(f1 >= 0.0);
assert!(f1 < 1.0);
}
*/
}
}
#[test]
fn test_float64() {
{
let seed = 2718281828;
... | Rust | 0 |
# python3
import sys
def sort_characters(text):
order = [0] * len(text)
char_set = sorted(set(text))
count = [text.count(c) for c in char_set]
for i in range(1, len(count)):
count[i] += count[i - 1]
for i, c in reversed(list(enumerate(text))):
count[char_set.index(c)] -= 1
... | Python | 1 |
impl CornerCrackConstrainedTensionMcdonald07 {
fn new() -> Self {
let a = vec![
0.0, 0.0001, 0.0006, 0.0011, 0.0016, 0.0021001, 0.0026003, 0.0031004, 0.0036005,
0.0041007, 0.0046014, 0.005102, 0.0056027, 0.0061034, 0.0066051, 0.0071055, 0.0076062,
0.0081089, 0.0086145, ... | Rust | 0 |
ACT_MAIN_SCIMITAR_MORGANA"),
(1007, "T7_ARTEFACT_MAIN_SPEAR_KEEPER"),
(1008, "T8_ARTEFACT_2H_ARCANESTAFF_HELL"),
(1009, "T8_ARTEFACT_2H_BOW_HELL"),
(1010, "T8_ARTEFACT_2H_BOW_KEEPER"),
(1011, "T8_ARTEFACT_2H_CLEAVER_HELL"),
(1012, "T8_ARTEFACT_2H_COMBATSTAFF_MORGANA"),
... | Rust | 0 |
# -*- coding: utf-8 -*- #
# Copyright 2021 Google LLC. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless requir... | Python | 1 |
>LucidSigma/ChanceOfElimination<filename>src/main.rs<gh_stars>0
mod athlete;
mod parsing;
mod simulation;
use std::io::{self, prelude::*};
use num_format::{Locale, ToFormattedString};
use rand::Rng;
use athlete::Athlete;
fn main() {
let athletes_toml = parsing::parse_athletes_toml_file("data/athletes.toml").unw... | Rust | 0 |
::Element_DataType>> {
unsafe {
let (class, field) = env.require_class_static_field("android/renderscript/Element$DataType\0", "FLOAT_32\0", "Landroid/renderscript/Element$DataType;\0");
env.get_static_object_field(class, field)
}
}
/// **get** pu... | Rust | 0 |
_samples.wrapping_add(self.phase_steps);
if !self.stepper.steps.is_empty() {
// TODO(AJM): this is just bad for a lot of reasons
let samps_per_beat = (self.stepper.bpm * 48000) / 60;
if num_samples % samps_per_beat == 0 {
println!("step!");
let... | Rust | 0 |
std::fmt::Display for Compressratio {
fn fmt(&self, f: &mut ::std::fmt::Formatter<'_>) -> ::std::fmt::Result {
::std::fmt::Display::fmt(Self::NAME, f)
}
}
impl<'a, D> Default for Value<'a, D, Compressratio>
where
D: crate::datasets::Dataset,
Compressratio: DatasetProperty<'a, D, Value = u64>,
{
... | Rust | 0 |
ngsten} -s {seeds[1]} -d {args.output_dir} {target_path}'
sp.call(render_source_cmd.split())
sp.call(render_target_cmd.split())
# Create renaming/moving commands
mv_imgs = []
for name, subdir_path in zip(subdirs, subdirs_paths):
file_ext = target_ext if name == 'targ... | Python | 1 |
= mf_img.to(self.device)
with torch.no_grad():
output = self.model.generate({"image": mf_img})
mfr_res.extend(output["fixed_str"])
# 更新进度条,每次增加batch_size,但要注意最后一个batch可能不足batch_size
current_batch_size = min(batch_size, len(sorted_imag... | Python | 1 |
# Copyright (C) 2019 The Raphielscape Company LLC.
#
# Licensed under the Raphielscape Public License, Version 1.c (the "License");
# you may not use this file except in compliance with the License.
#
""" Userbot module containing hash and encode/decode commands. """
from subprocess import PIPE
from subprocess import r... | Python | 1 |
a T>,
O: Slist<&'a mut T>,
N::Filter: SlistSum<T, Next = N>,
M::Filter: SlistSum<&'a T, Next = M>,
O::Filter: SlistSum<&'a mut T, Next = O>,
{
type Result = List<&'a T, N::Result>;
type ResultMut = List<&'a mut T, N::ResultMut>;
#[inline]
fn as_ref(&'a self) -> Self::Result {
Li... | Rust | 0 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.