text string | label_name string | labels int64 |
|---|---|---|
# Code generated by Lark OpenAPI.
from typing import Any, Optional, Union, Dict, List, Set, IO, Callable, Type
from lark_oapi.core.model import BaseRequest
from lark_oapi.core.enum import HttpMethod, AccessTokenType
from .batch_create_public_mailbox_member_request_body import BatchCreatePublicMailboxMemberRequestBody
... | Python | 1 |
def x_equilibrium(self) -> torch.Tensor:
return self.goal_state
@property
def u_equilibrium(self) -> torch.Tensor:
return torch.tensor([0.0])
class TestLyapunovDerivativeSimpleLoss(unittest.TestCase):
def forward_test(self, goal_state, nominal, V_psd_form):
lyap_nn = SetupLya... | Python | 1 |
.concat(combine_1, full_5)
del combine_1
# pd_op.share_data_: (2x9261x10xf32) <- (2x9261x10xf32)
share_data__0 = data_0.detach()
del data_0
# pd_op.share_data_: (-1x9261x4xf32) <- (-1x9261x4xf32)
share_data__1 = concat_0.detach()
# pd_op.multiply: (-1x9261x4xf3... | Python | 1 |
8 pixels of screen, 0: Hide
// |||| |+--- 1: Show sprites in leftmost 8 pixels of screen, 0: Hide
// |||| +---- 1: Show background
// |||+------ 1: Show sprites
// ||+------- Emphasize red
// |+-------- Emphasize green
// +--------- Emphasize blue
pub struct MaskRegister: u8 {
const... | Rust | 0 |
import asyncio
import time
from dotenv import load_dotenv
from pyrogram import filters
from pyrogram import Client
from pyrogram.types import InlineKeyboardButton, InlineKeyboardMarkup
from pyrogram.enums import ChatMembersFilter
from pyrogram.types import CallbackQuery, Message
import re
from strings.filters import co... | Python | 1 |
import pytest
from plenum.test.script.helper import looper
from stp_core.common.log import getlogger
from plenum.test.script.helper import changeNodeHa
logger = getlogger()
whitelist = ['found legacy entry', "doesn't match", 'reconciling nodeReg',
'missing', 'conflicts', 'matches', 'nodeReg',
... | Python | 1 |
CallbackResult {
eprintln!("Error: {}", error);
CallbackResult::Next
}
}
pub fn main() {
let _ = Master::new(Handler).run();
}
#[doc = "Reader of register TIMER2_BC12"]
pub type R = crate::R<u32, super::TIMER2_BC12>;
#[doc = "Writer for register TIMER2_BC12"]
pub type W = crate::W<u32, super:... | Rust | 0 |
# --------------------------------------------------------
# LightHuBERT: Lightweight and Configurable Speech Representation Learning with Once-for-All Hidden-Unit BERT (https://arxiv.org/pdf/2203.15610.pdf)
# Github source: https://github.com/mechanicalsea/lighthubert
# Licensed under The MIT License [see LICENSE for ... | Python | 1 |
self.utime
}
/// system time consumed by the process
pub fn get_stime(&self) -> libc::clock_t {
self.stime
}
/// Get exit status if the child terminated normally instead of terminated
/// by signal
pub fn get_exit_status(&self) -> Option<c_int> {
if libc::WIFEXITED... | Rust | 0 |
import os
import glob
import cv2
import numpy as np
import multiprocessing as mp
from shutil import rmtree
from scipy.io import loadmat
from scipy.interpolate import interp1d
from .bwmorph_thin import bwmorph_thin
from .correspond_pixels import correspond_pixels
eps = 2e-6
def edges_eval_img(im, gt, out="", thrs=9... | Python | 1 |
from collections import defaultdict
from rich.console import Console
from rich.table import Table
from rich.panel import Panel
from rich.progress import track
console = Console()
def analyze_performance(data):
players = list(data[0]["bids"].keys())
win_count = defaultdict(int)
bid_points = {p: defaultdict... | Python | 1 |
# Faça um programa que receba o nome completo
# de uma pessoa e, em seguida, mostre
# o primeiro e o último nome.
import os
os.system('cls')
print('-' * 90)
print('PRIMEIRO E ÙLTIMO NOME.')
print('=' * 90)
nome = str(input('Nome: '))
lista = nome.split()
nome1 = lista[:1]
nome3 = lista[-1:]
print(f'Nome: {nome... | Python | 1 |
import gymnasium as gym
import matplotlib.pyplot as plt
from stable_baselines3 import PPO
from stable_baselines3.common.callbacks import EvalCallback
from stable_baselines3.common.monitor import Monitor
import numpy as np
import torch
# 创建并监控训练环境
env = Monitor(gym.make("Pendulum-v1"))
# 创建用于周期性评估的环境(不渲染)
eval_env = ... | Python | 1 |
{ first = Some(f.0) }
if first? > f.0 { first = Some(f.0) }
}
None => {}
}
}
return first;
}
fn get_attributes(reader : &mut BufReader<File>, first_line : &mut String, end_char : char) -> HashMap<String, String>{
let mut map : HashMap<String, String> = HashM... | Rust | 0 |
ays)]
pub fn sense2_slp_ie(&mut self) -> SENSE2_SLP_IE_W {
SENSE2_SLP_IE_W { w: self }
}
#[doc = "Bit 16 - the sleep status selection signal of the pad"]
#[inline(always)]
pub fn sense2_slp_sel(&mut self) -> SENSE2_SLP_SEL_W {
SENSE2_SLP_SEL_W { w: self }
}
#[doc = "Bits 17:1... | Rust | 0 |
#_*_ coding: utf-8 _*_
#https://sshuhei.com
import json
import logging
import logging.handlers
from src import channel
if __name__ == '__main__':
#logging設定
logging.basicConfig(
level=logging.INFO,
format='%(asctime)s %(levelname)s: %(message)s',
datefmt='%Y-%m-%d %H:%M:%S')
logfil... | Python | 1 |
, ref substs) => {
w.write_str(&"t[");
w.write_str((cx.ds)(def));
w.write_char('|');
enc_substs(w, cx, substs);
w.write_char(']');
}
ty::ty_trait(def, ref substs, store, mt, bounds) => {
w.write_str(&"x[");
w.write_str((cx.ds)(def));
w.write_ch... | Rust | 0 |
ummary[f"{metric}_std"] = np.std(values)
metrics_summary[f"{metric}_min"] = np.min(values)
metrics_summary[f"{metric}_max"] = np.max(values)
# 출력
print(f" MAE: {metrics_summary['mae_mean']:.6f} ± {metrics_summary['mae_std']:.6f}")
print(f" R²: {me... | Python | 1 |
source.read_exact(data.bytes_mut());
match result {
/*Ok(result) =>
eprintln!("{:?}: fed {} bytes with {} bytes",
info.timestamp().playback,
data.bytes().len(),
result),*/
Err(what) => if what.kind() == std::io::ErrorKind::UnexpectedEof {
eprintln!("e o f");
end1.store(true,... | Rust | 0 |
nput::Key::A));
responder.send(ui_input::Status::Handled).expect("responding from key listener")
}
Some(Err(e)) => {
panic!("Error from listener_stream.next(): {:}", e);
}
None => {
panic!("Error from listener_stream.next(): empty stream");
}
... | Rust | 0 |
method requires command-line arguments
demo.basic_argv_method()
elif method_choice == '2':
# Argparse method (run with additional arguments)
demo.argparse_method()
elif method_choice == '3':
# Interactive input method
demo.interactive_input_... | Python | 1 |
xpected_result);
let p = PathBuf::from("../pinyincd_rust_backend/test/weituomapinyin");
let result = resolve(&p, false, false);
assert_eq!(result, vec![PathBuf::from("../pinyincd_rust_backend/test/威妥玛拼音")]);
let p = PathBuf::from("test/weituomapinyin/zhanlve");
let result = res... | Rust | 0 |
"
)
def save_model(name: str, cur_epoch: int, model_to_save: nn.Module, training_path: Path):
"""
Save the weights of the model during training
:param name: name of the file
:param cur_epoch: current epoch
:param model_to_save: pytorch model to be saved
:param training_path: path associa... | Python | 1 |
e {..ii}),
ImplItem::Macro(ii) => ImplItem::Macro(ImplItemMacro {..ii}),
_ => unimplemented!(),
}
}
pub fn traverse_block_def<W: Traversal>(walk: &mut W, mut b: Block) -> Block {
b.stmts = b.stmts.traverse(walk);
b
}
pub fn traverse_local_def<W: Traversal>(walk: &mut W, mut l: Local) -> Lo... | Rust | 0 |
_iter()
.map(|field| {
let name = field.ident.as_ref().unwrap();
let attrs: BTreeMap<String, String> = field
.attrs
.iter()
.filter_map(|a| {
a.interpret_meta().and_then(|meta| {
if let Meta::NameValue(MetaNameValue {
ref ident,
l... | Rust | 0 |
"spawn peer" );
// This is the relevant line for this test!
//
peer.set_timeout( Duration::from_millis( 10 ) );
debug!( "start mailbox for [{}] in peerb", name );
AsyncStd.spawn( peer_mb.start(peer).map(|_|()) ).expect( "Start mailbox of Peer" );
// Call the service and receive the response
//
le... | Rust | 0 |
#Creates the list in Python
book_list = ["Fourth Wing","Iron Flame"]
#defines the function of viewing books
#Begins if/else statement
#If something is on the list, it prints the list, one title at a time
#If nothing on list, print message to user
def view_books():
if book_list:
print ("\nYour library: ")
... | Python | 1 |
vert a path like obj1.obj2 to array notation: ["obj1"]["obj2"]."""
return "".join(f'["{escape_double_quotes(x)}"]' for x in path.split("."))
def get_and_assert_figure_root(obj: Element) -> Figure:
"""Return the root element of the tree and assert it's a Figure."""
figure = obj.get_root()
assert isinst... | Python | 1 |
Err(_) => {
msg.channel_id
.say(ctx, RoyalError::MissingError("emoji in position 4"))
.await?;
return Ok(());
}
};
let reaction_emoji = generate_emoji(&emoji_string);
let storage = WizardIntermediate {
message_id: msg_id,
... | Rust | 0 |
class TaskFamily:
import random
@staticmethod
def get_tasks() -> dict[str, dict]:
return {
"1": {"hypothesis": "Plants grow faster in blue light than in red light."},
"2": {"hypothesis": "Increasing the amount of sugar in a yeast solution will produce more carbon dioxide."}
... | Python | 1 |
cmp(&self, other: &Qcell) -> std::cmp::Ordering {
self.max_distance.partial_cmp(&other.max_distance).unwrap()
}
}
impl PartialEq for Qcell {
fn eq(&self, other: &Qcell) -> bool {
(self.max_distance - other.max_distance).abs() < COORD_PRECISION
}
}
impl Eq for Qcell { }
/// Signed distance... | Rust | 0 |
get(r, "A_stance", ""))
sb = norm_stance(rget(r, "B_stance", ""))
same_stance = int(sa != "unknown" and sb != "unknown" and sa == sb)
open_stance = int({sa, sb} == {"orthodox", "southpaw"})
southpaw_adv = int(sa == "southpaw" and sb != "southpaw")
... | Python | 1 |
(), state)
})
}
}
impl<T> $result_ext_name<T> for ::std::option::Option<T> {
fn chain_err<F, EK>(self, callback: F) -> ::std::result::Result<T, $error_name>
where F: FnOnce() -> EK,
EK: Into<$error_kind_name> {
... | Rust | 0 |
(may still be near-optimal).")
# ----- Visualization -----
V_grid = V.reshape(N_theta, N_thetadot)
fig, ax = plt.subplots(figsize=(7,5), dpi=120)
im = ax.imshow(
V_grid,
origin="lower",
extent=[thetadot_grid.min(), thetadot_grid.max(),
theta_grid.min(), theta_grid.max()],
aspect="auto",
... | Python | 1 |
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 writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARR... | Rust | 0 |
32300, "cù".to_string());
d.insert(32301, "lí".to_string());
d.insert(32302, "suō,sù".to_string());
d.insert(32303, "yǎn,yǐn".to_string());
d.insert(32304, "xǐ".to_string());
d.insert(32305, "zòng,zǒng".to_string());
d.insert(32306, "léi".to_string());
d.insert(32307, "zhuàn,juàn".to_string());
d.insert... | Rust | 0 |
n mut_consumed(&mut self) -> &mut ConsumedCapacity {
if self.consumed.is_none() {
self.consumed.set_default();
}
self.consumed.as_mut().unwrap()
}
// Take field
pub fn take_consumed(&mut self) -> ConsumedCapacity {
self.consumed.take().unwrap_or_else(|| ConsumedC... | Rust | 0 |
eCoord;
pub struct SourceMap {
line_offsets: SmallVec<[usize; 128]>
}
pub struct SourceManager {
files: Vec<String>,
file_contents: Vec<String>,
source_maps: Vec<UnsafeCell<Option<SourceMap>>>
}
impl SourceManager {
pub fn new() -> Self {
Self {
files: Vec::new(),
... | Rust | 0 |
new(PathBuf::from(format!("tla_code {}", name))), code)?;
self.add_tla(name, value);
Ok(())
}
pub fn resolve_file(&self, from: &PathBuf, path: &PathBuf) -> Result<Rc<PathBuf>> {
Ok(self.settings().import_resolver.resolve_file(from, path)?)
}
pub fn load_file_contents(&self, path: &PathBuf) -> Result<Rc<str>>... | Rust | 0 |
Ok(Self::Inet6(Inet6SockAddr::from(unsafe {
core::mem::transmute_copy::<_, libc::sockaddr_in6>(&storage)
})))
}
libc::AF_UNIX
if len
>= (core::mem::size_of::<libc::sockaddr_un>()
- unsafe { cor... | Rust | 0 |
sed in the eigenfrequency analysis.
# This argument value should be less than or equal to the half of the total number of
# sectors. The default value is 0.
highestNodalDiameter: int = 0
# A SymbolicConstant specifying the propagation state of the *highestNodalDiameter*
# member. Possible values ar... | Python | 1 |
Some(xmlns) => {
svg.push_str(&format!("<svg viewBox=\"{} {} {} {}\" xmlns=\"{}\">",
self.viewbox[0],self.viewbox[1],self.viewbox[2],self.viewbox[3],xmlns));
}
}
match &self.background {
Color::None => {
},... | Rust | 0 |
or c in include:
x = c[i] * np.ones_like(z)
_X = np.hstack([np.expand_dims(x, 1), _X])
else:
raise IndexError('Too many dimensions in include.')
except:
raise WellError('Problem broadc... | Python | 1 |
| EventData::CoveragePathsFavored(_)
| EventData::CoveragePathsFound(_)
| EventData::CoveragePathsImported(_)
| EventData::CoverageMaxDepth(_)
)
}
async fn listen_telemetry_event(
ui_event_tx: Sender<TerminalEvent>,
mut cancellation_... | Rust | 0 |
# src/__init__.py
PACKAGE_NAME = "src"
VERSION = "1.0.0"
| Python | 1 |
'a>,
pub out_tex_buffer_read_addrs: Vec<&'a Output<'a>>,
}
impl<'a> FrontPipe<'a> {
pub fn new(instance_name: impl Into<String>, p: &'a impl ModuleParent<'a>) -> FrontPipe<'a> {
let m = p.module(instance_name, "FrontPipe");
// Inputs
let in_valid = m.input("in_valid", 1);
let ... | Rust | 0 |
arams, &Patch::Merge(()))
.unwrap();
assert_eq!(req.uri(), "/apis/clux.dev/v1/namespaces/myns/foos/baz?");
assert_eq!(req.method(), "PATCH");
}
#[test]
fn raw_resource_in_default_group() {
let gvk = GroupVersionKind::gvk("", "v1", "Service");
let api_resource = A... | Rust | 0 |
"""============================================================================
#!🧪 Ejercicio 2 Clase 13
#?📌 Nombre: Calcular precio con o sin descuento
#?🔑 Concepto: Función limpia + parámetro opcional + validación de rango
#todo🎯 ¿Qué debe hacer la función?
1️⃣ Recibir dos parámetros:
• precio_base → obligator... | Python | 1 |
nt, value });
curr_move = next_move;
if value as usize > size {
break;
}
}
memory
}
fn get_next_move_and_point(curr_move: Move, curr_point: Point) -> (Move, Point) {
let Point { x, y } = curr_point;
match curr_move {
Move::Right { total, moves_left } => {... | Rust | 0 |
[_dst] as u32 ^ reg[_src] as u32) as u64,
ebpf::MOV32_IMM => reg[_dst] = insn.imm as u32 as u64,
ebpf::MOV32_REG => reg[_dst] = (reg[_src] as u32) as u64,
ebpf::ARSH32_IMM => { reg[_dst] = ... | Rust | 0 |
_if_exists::<ContentEncoding>(h);
str_to_sign = str_to_sign + &add_if_exists::<ContentLanguage>(h);
// content lenght must only be specified if != 0
// this is valid from 2015-02-21
let m = match h.get::<ContentLength>() {
Some(ce) => {
if ce.to_be() != 0u64 {
ce.to_... | Rust | 0 |
dExceptionReason {
AccountThrottled,
DependencyRequestThrottled,
/// Unknown contains new variants that have been added since this code was generated.
Unknown(String),
}
impl std::convert::From<&str> for RequestThrottledExceptionReason {
fn from(s: &str) -> Self {
match s {
"ACCO... | Rust | 0 |
import os
import sys
root = os.path.dirname(os.path.dirname(os.path.dirname(os.path.dirname(os.path.abspath(__file__)))))
sys.path.append(root)
# ----------------------------------------------------------------------------
# PLEASE DO NOT EDIT THIS FILE, IT IS GENERATED AND WILL BE OVERWRITTEN:
# https://github.com/... | Python | 1 |
/ self.T)
z = torch.unsqueeze(z, 1)
z = z.repeat(1, self.teacher_dim, 1)
f_hat = [f[i](s).unsqueeze(-1) for i in range(self.K)]
f_hat = torch.cat(f_hat, -1)
f_hat = f_hat * z
f_hat = f_hat.sum(2)
GA_loss = ((t-f_hat) ** 2).sum(-1).sum()
return GA... | Python | 1 |
)| *s != "x")
.map(|(idx, x)| (idx as u64, x.parse().unwrap()))
.collect();
let (mut curr_ts, mut step) = bus_ids[0];
for &(idx, ts) in &bus_ids[1..] {
while (curr_ts + idx) % ts != 0 {
curr_ts += step;
}
step *= ts;
}
println!("day13.part2.solution... | Rust | 0 |
onent>();
f2(rrc, videos);
}
})
.await
);
}
});
}
/// call with parameters rrc, game_data_mod::Audio, url
pub fn call_on_next_tick_8(
vdom: dodrio::VdomWeak,
f1: &'static impl Fn(String) -> Pin<B... | Rust | 0 |
promote interoperability.
//!
//! This crate attempts to implement a strict interpretation of the [RFC 7468]
//! rules, implementing all of the MUSTs and SHOULDs while avoiding the MAYs,
//! and targeting the "ABNF (Strict)" subset of the grammar as described in
//! [RFC 7468 Section 3 Figure 3 (p6)][RFC 7468 p6].
//!... | Rust | 0 |
decision = {
"investments": [],
"cash_reserve": available_funds,
"strategy": "투자 결정을 파싱할 수 없습니다.",
"raw_response": decision_text
}
# 메타데이터 추가
decision["timestamp"] = datetime.no... | Python | 1 |
i = 0; i < num_coins; i++) {
/* Check if they are within the main char bounding box */
if ((coins[i]->position.x > top_left.x) &&
(coins[i]->position.x < bottom_right.x) &&
(coins[i]->position.y > top_left.y) &&
(coins[i]->position.y < bottom_right.y)) {
/* Remove them fro... | Rust | 0 |
ientStore, registry::Registry, ClientData, ClientId, Credentials, GlobalHandler,
InnerClientId, InnerGlobalId, InnerObjectId, ObjectData, ObjectId,
};
pub(crate) type PendingDestructor<D> = (Arc<dyn ObjectData<D>>, InnerClientId, InnerObjectId);
#[derive(Debug)]
pub struct State<D: 'static> {
pub(crate) clien... | Rust | 0 |
xff_u32
^ *rk.offset(0);
*ciphertext.offset(0) = (s0 >> 24i32) as u8;
*ciphertext.offset(1) = (s0 >> 16i32) as u8;
*ciphertext.offset(2) = (s0 >> 8i32) as u8;
*ciphertext.offset(3) = s0 as u8;
s1 = Te4[(t1 >> 24i32) as usize] & 0xff000000u32
^ Te4[(t2 >> 16i32 & 0xff_u32) as usize] &... | Rust | 0 |
::EDREQ_28_1
}
}
#[doc = "Write proxy for field `EDREQ_28`"]
pub struct EDREQ_28_W<'a> {
w: &'a mut W,
}
impl<'a> EDREQ_28_W<'a> {
#[doc = r"Writes `variant` to the field"]
#[inline(always)]
pub fn variant(self, variant: EDREQ_28_A) -> &'a mut W {
{
self.bit(variant.into())
... | Rust | 0 |
#
# Copyright (c) 2017, Massachusetts Institute of Technology 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 source code must retain the above copyright notice, this
# list o... | Python | 1 |
.hostname.unwrap();
i.port = apply_result.port.unwrap();
i.pathname = apply_result.pathname.unwrap();
i.search = apply_result.search.unwrap();
i.hash = apply_result.hash.unwrap();
} else {
return None;
}
}
crate::UrlPatternMatchInput::Url(url) => {
i.pro... | Rust | 0 |
res).map_cont(Union::JustA),
Union::JustB(b) => b.step(res).map_cont(Union::JustB),
}
}
}
#[derive(Clone)]
pub struct Map<A, F>(pub(super) A, pub(super) F);
impl<Req, Res, A, F, T> LazySet<Req, Res> for Map<A, F>
where
A: LazySet<Req, Res>,
F: Fn... | Rust | 0 |
s `true` if the result of `this <=> rhs` is either a positive [`Number`] or [zero](Number::ZERO).
#[instrument(name="Comparable::>=", level="trace", skip(this, args), fields(self=?this, ?args))]
pub fn qs_geq(this: &Object, args: Args) -> crate::Result<Object> {
let rhs = args.try_arg(0)?;
let cmp = compare(this,... | Rust | 0 |
Cmd::Int(f.unwrap_or(Flags::NONE),w.unwrap_or(0),p.unwrap_or(0)) }
['o'] => { Cmd::Oct(f.unwrap_or(Flags::NONE),w.unwrap_or(0),p.unwrap_or(0)) }
['x'] => { Cmd::LowerHex(f.unwrap_or(Flags::NONE),w.unwrap_or(0),p.unwrap_or(0... | Rust | 0 |
::ScanRight,
BrainfuckInstruction::ScanLeft
]
);
assert!(result.len() < len);
}
}
#[allow(unused_imports)]
use std::ops::Div;
#[allow(unused_imports)]
use std::ops::Index;
#[allow(unused_imports)]
use std::ops::IndexMut;
#[allow(unused_imports)]
use std::ops::{Add, Mul, S... | Rust | 0 |
_run_signed_run_tx.rawTransaction)
logger.info(f"Sandwich attack front run transaction hash: {front_run_signed_run_tx.hash.hex()}")
logger.info(f"Sandwich attack back run transaction hash: {back_run_signed_run_tx.hash.hex()}")
return front_run_signed_run_tx.hash.hex(), back_run_signed_run_tx.hash.hex()
a... | Python | 1 |
quantity! {
/// Molar energy (base unit joule per mole, kg · m² · s⁻² · mol⁻¹).
quantity: MolarEnergy; "molar energy";
/// Dimension of molar energy, L²MT⁻²N⁻¹ (base unit joule per mole, kg · m² · s⁻² · mol⁻¹).
dimension: ISQ<
P2, // length
P1, // mass
N2, // time
... | Rust | 0 |
self) {
let lockfile = load_lockfile(&self.file);
let tree = lockfile.dependency_tree().unwrap_or_else(|e| {
eprintln!("*** error: {}", e);
exit(1);
});
if self.dependencies.is_empty() {
self.dependency_tree(&tree);
} else {
self.... | Rust | 0 |
ize,
concat!(
"Offset of field: ",
stringify!(TPM2B_ATTEST),
"::",
stringify!(size)
)
);
assert_eq!(
unsafe { &(*(::std::ptr::null::<TPM2B_ATTEST>())).attestationData as *const _ as usize },
2usize,
concat!(
"Off... | Rust | 0 |
use specs::prelude::*;
use specs_registration::{insert_resources, register_components};
use std::sync::mpsc::Receiver;
pub(super) fn init_world(
err_send: std::sync::mpsc::Sender<PadlError>,
resolution: ScreenResolution,
player_info: PlayerInfo,
rest: RestApiState,
errq: ErrorQueue,
tb: TextBoa... | Rust | 0 |
class Solution:
def replaceDigits(self, s: str) -> str:
def shift(c, x):
"""
Shifts the character 'c' by 'x' positions in the alphabet.
Args:
c: The character to shift (must be a letter).
x: The number of positions to shift (must b... | Python | 1 |
#!/usr/bin/env python
# -*- coding:utf-8 -*-
# __author__ = 'liao gao xiang'
# 查找两个字典的相同点
a = {
'x': 1,
'y': 2,
'z': 3
}
b = {
'w': 10,
'x': 11,
'y': 2
}
# Find keys in common
aa = a.keys() & b.keys() # { 'x', 'y' }
print(aa)
# Find keys in a that are not in b
bb = a.keys() - b.keys() # { ... | Python | 1 |
nanmean(abs_err.ravel())
def sort_by_increasing_view_incidence_angle(root_dir):
incidence_angles = []
json_paths = glob.glob(os.path.join(root_dir, "*.json"))
for json_p in json_paths:
with open(json_p) as f:
d = json.load(f)
rpc = rpcm.RPCModel(d["rpc"], dict_format="rpcm")
... | Python | 1 |
_xmm_xmmm32_sae
0x0008_4034, 0x7A00_0000,// Ucomisd_xmm_xmmm64
0x0008_4034, 0x0F00_0001,// VEX_Vucomisd_xmm_xmmm64
0x0008_4034, 0x1E00_0002,// EVEX_Vucomisd_xmm_xmmm64_sae
0x0008_4034, 0x7900_0000,// Comiss_xmm_xmmm32
0x0008_4034, 0x7A00_0000,// Comisd_xmm_xmmm64
0x0008_4034, 0x0F00_0001,// VEX_Vcomiss_xmm_xmmm32... | Rust | 0 |
"""Physics pipeline for fully articulated dynamics and collision."""
import jax
from mujoco import mjx
from quadruped_mjx_rl.environments.physics_pipeline.base import (
Motion,
Transform,
PipelineState,
PipelineModel,
)
def pipeline_init(
pipeline_model: PipelineModel,
qpos: jax.Array,
q... | Python | 1 |
eport_dir, test_settings):
"""異常系:存在しないレポートは404を返す"""
# settings.REPORT_DIRをパッチして、report routerがテスト用ディレクトリを使用するようにする
with (
patch("src.routers.report.settings.REPORT_DIR", temp_report_dir),
patch("src.routers.report.load_status_as_reports", return_value=[]),
):
... | Python | 1 |
from abc import ABC, abstractmethod
from pathlib import Path
from models.notification_history import NotificationHistory
class NotificationHistoryRepository(ABC):
"""通知履歴リポジトリのインターフェース"""
@abstractmethod
def load(self, file_path: Path) -> NotificationHistory:
"""
通知履歴を読み出す
Retur... | Python | 1 |
import asyncio
import json
import os
from dataclasses import asdict, dataclass
import nats
@dataclass
class Payload:
foo: str
bar: int
async def main():
# Use the NATS_URL env variable if defined, otherwise fallback to the default.
nats_url = os.getenv("NATS_URL", "nats://localhost:4222")
clie... | Python | 1 |
ub struct Bus(pub(crate) sensors_bus_id);
/// Shared reference to a bus connection of some [`Kind`], *e.g.,* PCI.
///
/// [`Kind`]: crate::bus::Kind
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct BusRef<'a>(pub(crate) &'a sensors_bus_id);
/// Exclusive reference to a bus connection of some [`Kind`], *e.g.,* ... | Rust | 0 |
import torch
from tqdm import tqdm
CLAMP_QUANTILE = 0.99
MIN_DIFF = 1e-6
# Get a dict of lora weights calculated using singular value decomposition on the difference between an untuned and tuned model
def calculate_svds(model_original, model_tuned, lora_names, lora_dim):
map_o = {
name.replace(".", "/"):... | Python | 1 |
);
pub const PackMatrixColumnMajor : Compile = Compile(D3DCOMPILE_PACK_MATRIX_COLUMN_MAJOR);
pub const PartialPrecision : Compile = Compile(D3DCOMPILE_PARTIAL_PRECISION);
pub const ForceVsSoftwareNoOpt : Compile = Compile(D3DCOMPILE_FORCE_VS_SOFTWARE_NO_... | Rust | 0 |
_call_with_return(
&mut client,
rpc::eth_get_transaction_by_block_number_and_index(None, U64::zero()),
);
assert_eq!(tx.gas, U256::from_int_unchecked(21000_u32));
assert_eq!(tx.gas_price, U256::from_int_unchecked(1_u8));
assert_eq!(tx.value, U256::from_int_unchecked(value));
}
#[test]
f... | Rust | 0 |
#!/usr/bin/python
from __future__ import print_function
from keras.models import Sequential
from keras.models import Model
from keras.layers import Input
from keras.layers import Dense
from keras.layers import LSTM
from keras.layers import GRU
from keras.models import load_model
from keras import backend as K
import ... | Python | 1 |
'xsl:stylesheet SYSTEM "htmlent.dtd"')
def test_namespaced_public_doctype(self):
self.assertRaises(HTMLParseError, self._test_doctype,
'xsl:stylesheet PUBLIC "htmlent.dtd"')
class TestHTMLParserTreeBuilderInvalidMarkup(TestLXMLBuilderInvalidMarkup):
# Oddly... | Python | 1 |
el_flat = pixel_flat.view(bs * num_objects, h, w, self.dim)
pixel_flat = pixel_flat.permute(0, 3, 1, 2).contiguous()
x = self.conv(pixel_flat)
x = x.view(bs, num_objects, self.dim, h, w)
return x
class OutputFFN(nn.Module):
def __init__(self, dim_in: int, dim_out: int, activation=... | Python | 1 |
rationales = await paginator.process_and_generate(annotated_text, min_words, max_words, overlap) # get a breakpoint and rationale
breakpoints = list(dict.fromkeys(breakpoints)) # Remove duplicate breakpoints
return breakpoints, rationales
def split_text_into_episodes(annotated_text: str, breakpoints: list[in... | Python | 1 |
al::Dog(static_entity.to_owned()));
Some(dynamic_cast::<Animal, T>(&static_entity).to_owned())
} else if requested_type_id == TypeId::of::<Mammal>() {
let static_entity = Mammal::Dog(static_entity.to_owned());
Some(dynamic_cast::<Mammal, T>(&static_entity).to_owned())
... | Rust | 0 |
тура для десериализации потока байт, практически из значений, как они хранятся
/// в памяти, в значения Rust.
///
/// # Правила десериализации
/// Все типы десериализуются максимально прямолинейно, так, как они лежат в памяти: для
/// всех целых типов читается соответствующее их разрядности количество байт и интерпрети... | Rust | 0 |
) -> web_sys::CanvasRenderingContext2d {
let document = web_sys::window().unwrap().document().unwrap();
let canvas = document.get_element_by_id(canvas_id).unwrap();
let canvas: web_sys::HtmlCanvasElement = canvas
.dyn_into::<web_sys::HtmlCanvasElement>()
.map_err(|_| ())
.unwrap();
... | Rust | 0 |
)
}
/// Conditionally multiply the packed single-precision (32-bit) floating-point
/// elements in `a` and `b` using the high 4 bits in `imm8`,
/// sum the four products, and conditionally return the sum
/// using the low 4 bits of `imm8`.
#[inline(always)]
#[target_feature = "+avx"]
#[cfg_attr(test, assert_instr(vdp... | Rust | 0 |
from metaflow_test import MetaflowTest, ExpectationFailed, steps, assert_equals
class ForeachInSwitchTest(MetaflowTest):
PRIORITY = 2
ONLY_GRAPHS = ["foreach_in_switch"]
@steps(0, ["start-foreach-in-switch"], required=True)
def step_start(self):
self.mode = "process"
@steps(0, ["process-... | Python | 1 |
ct("USCI_B1_I2C_MODE").finish()
}
}
#[doc = "USCI_B1 I2C Mode"]
pub mod usci_b1_i2c_mode;
#[doc = "USCI_B1 SPI Mode"]
pub struct USCI_B1_SPI_MODE {
_marker: PhantomData<*const ()>,
}
unsafe impl Send for USCI_B1_SPI_MODE {}
impl USCI_B1_SPI_MODE {
#[doc = r"Pointer to the register block"]
pub const PTR:... | Rust | 0 |
&req.msg.env_id,
req.msg.life_time,
req.msg.is_fucker,
)
.c(d!())
.and_then(|_| send_ok!(req.uuid, "Success!", peeraddr).c(d!()))
.or_else(|e| send_err!(req.uuid, e, peeraddr).c(d!()))
}
/// 删除 Env
fn del_env(peeraddr: SocketAddr, request: Vec<u8>) -> Result<()> {
#[derive(Deseri... | Rust | 0 |
def main():
s1 = input()
s2 = input()
p = int(input())
for i in range(0, p - 1):
print(s1[i], end="")
print(*s2,sep="", end="")
print(s1[p-1::])
if __name__ == "__main__":
main() | Python | 1 |
from .._imperative_rt.core2 import (
_get_amp_dtype_autocast,
_get_amp_high_prec_dtype,
_get_amp_low_prec_dtype,
_set_amp_dtype_autocast,
_set_amp_high_prec_dtype,
_set_amp_low_prec_dtype,
)
_enabled = False
_set_amp_dtype_autocast(_enabled)
__all__ = [
"enabled",
"high_prec_dtype",
... | Python | 1 |
WDSLPW::GROUP0 => 3,
DTCMPWDSLPW::ALLBUTGROUP0DTCM0 => 6,
DTCMPWDSLPW::GROUP1 => 4,
DTCMPWDSLPW::ALL => 7,
}
}
}
#[doc = r" Proxy"]
pub struct _DTCMPWDSLPW<'a> {
w: &'a mut W,
}
impl<'a> _DTCMPWDSLPW<'a> {
#[doc = r" Writes `variant` to the field"]
#[inline]
... | Rust | 0 |
Bool,
pub ioStats: avifIOStats,
pub diag: avifDiagnostics,
pub io: *mut avifIO,
pub data: *mut avifDecoderData,
}
impl Default for avifDecoder {
fn default() -> Self {
let mut s = ::std::mem::MaybeUninit::<Self>::uninit();
unsafe {
::std::ptr::write_bytes(s.as_mut_ptr(), ... | Rust | 0 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.