text string | label_name string | labels int64 |
|---|---|---|
from typing import List, Optional, Type, cast
from hydra._internal.utils import _locate
from hydra.utils import instantiate
from omegaconf import DictConfig
from nuplan.planning.scenario_builder.abstract_scenario import AbstractScenario
from nuplan.planning.simulation.planner.abstract_planner import AbstractPlanner
... | Python | 1 |
_message()?;
match msg {
Message::Text(ref text) => {
let request: Option<RpcRequest> = serde_json::from_str(text.as_str()).ok();
match request {
None => continue,
Some(command) => Self::handle_command(ev... | Rust | 0 |
the integer 16 onto the stack.
///
/// Usage:
/// ```
/// # use bitcoin_cash::Opcode::*;
/// # struct Params;
/// # #[bitcoin_cash::script(DemoInputs)]
/// # fn demo(_: Params) {
/// // push 16
/// let sixteen = OP_16;
///
/// let expected = 16; // equivalent (and prefered)... | Rust | 0 |
p_var_name);
let covmap_section_name = llvm::build_string(|s| unsafe {
llvm::LLVMRustCoverageWriteMapSectionNameToString(cx.llmod, s);
})
.expect("Rust Coverage section name failed UTF-8 conversion");
debug!("covmap section name: {:?}", covmap_section_name);
let llglobal = llvm::add_global... | Rust | 0 |
print("Invoking launch4j...")
subprocess.Popen(
cmdsplit("java -jar \"%s\" \"%s\""% (
os.path.join( base_dir,"installer","launch4j","launch4j.jar"),
os.path.join( base_dir,"installer","launch4j","launch4j.xml"))),
cwd=os.path.join(base_dir,"installer","launch... | Python | 1 |
"""
Model-specific configurations for different architectures.
"""
from dataclasses import dataclass
from .base_config import BaseConfig
@dataclass
class ResNet18Config(BaseConfig):
"""Configuration for ResNet18 CNN baseline"""
model_name: str = "resnet18"
pretrained: bool = True
dropout: float = 0.1
... | Python | 1 |
<T>>;
pub type OptGcCell<T> = Option<Gc<T>>;
struct GcInfo {
root_ref_count: AtomicUsize,
}
impl GcInfo {
fn new() -> GcInfo {
GcInfo {
root_ref_count: AtomicUsize::new(0),
}
}
}
pub struct GcPtr<T> where T: 'static + Sized + Trace {
info: GcInfo,
t: T,
}
impl<T> GcPt... | Rust | 0 |
ovides a stable api to rust crates for interfacing with the Android platform. It is
//! initialized by the runtime, usually [__ndk-glue__](https://crates.io/crates/ndk-glue),
//! but could also be initialized by Java or Kotlin code when embedding in an existing Android
//! project.
//!
//! ```no_run
//! let ctx = ndk_c... | Rust | 0 |
#[inline]
pub fn num_faulty(mut self, num_faulty: usize) -> Self {
self.num_faulty = num_faulty;
self
}
/// Time limit.
///
/// Sets the time limit; `crank` will fail if called after this much time as elapsed since
/// the network was instantiated.
#[inline]
pub fn t... | Rust | 0 |
).await.map_err(AcceptError::Data)?.ok_or(StatusOrError::Status(Status::NotFound))?;
form.verify(&csrf).map_err(AcceptError::Csrf)?; //TODO option to resubmit on error page (with some “are you sure?” wording)
if data.is_started() { return Err(AcceptError::EventStarted.into()) }
let mut transaction = pool.be... | Rust | 0 |
#!/usr/bin/env python3
#
# Copyright 2021 Graviti. Licensed under MIT License.
#
# pylint: disable=invalid-name
"""Dataloader of COVID_CT dataset."""
import os
from tensorbay.dataset import Data, Dataset
from tensorbay.label import Classification
DATASET_NAME = "COVID_CT"
_SEGMENT_TO_PATH = {
"test_COVID": ("te... | Python | 1 |
},
Keycode::W => {
update_server(protocol::ClientToServer::Walk(player_id, Vector3::new(0.0, 0.0, 1.0)));
},
Keycode::S => {
update_server(protocol::ClientToServer::Walk(player_id, Vector3::new(0.0, 0.0, -1.0)));
},
_ => {}
}
})
}
// x and y are relative to la... | Rust | 0 |
let etcd_delegate = EtcdDelegate::new(get_etcd_address_vec(matches))?;
let node_id = get_node_id(matches);
let ip_address = get_ip_address(matches, &node_id);
let mount_dir = get_mount_dir(matches);
let async_args = AsyncFuseArgs {
node_id,
... | Rust | 0 |
self"), self_inode);
}
}
impl DirProcINode for LockedProcRootINode {
fn find(&self, name: &str) -> vfs::Result<Arc<dyn INode>> {
let file = self.0.read().unwrap();
if name == "." {
return Ok(file.this.upgrade().unwrap());
}
if name == ".." {
return Ok(fil... | Rust | 0 |
-1)):
nr, nc = r + dr, c + dc
if 0 <= nr < h and 0 <= nc < w and grid[nr][nc] == 1:
if not filter_holes or comp_touch[nr][nc]:
sevens.add((r, c))
break
return sevens
def _run_pipeline(
grid: Grid,
*,
p... | Python | 1 |
default(); raytracer.get_width() * raytracer.get_height() / nb_threads];
let mut ci = 0;
for y in ((i * raytracer.get_height() / nb_threads)
..((i + 1) * raytracer.get_height() / nb_threads))
.rev()
{
for x in 0..raytracer.get_width() ... | Rust | 0 |
over_rxempty".to_owned(),
))
})?;
loop {
if poll_uart(xover_rxempty, &bridge)? {
let mut char_buffer = vec![];
let mut read_count = 0;
while bridge.peek(xover_rxempty)? == 0 && read_count < 100 {
read_count += 1;
... | Rust | 0 |
title="ℹ️ Usage",
description="`!critproc 0` = make process critical\n`!critproc 1` = disable critical process",
color=0xFF69B4
)
await ctx.send(embed=embed)
return
try:
if mode == '1':
if make_non_critical():
embed = discor... | Python | 1 |
ain() {
input! {
X: i64,
}
let mut a: i64 = 1;
let mut b: i64 = -1;
loop {
loop {
if a.pow(5) - b.pow(5) == X {
println!("{} {}", a, b);
return;
}
b -= 1;
}
a += 1;
}
}
// https://atcoder.jp/con... | Rust | 0 |
_offset(offset);
// The only block values in the slab are the tuple and the string,
// which is allocated 3 words after the tuple.
let valid_offsets = vec![tuple_offset, tuple_offset + 3];
if valid_offsets.iter().any(|&o| o == offset) {
assert_eq!(slab.che... | Rust | 0 |
'),
'total_processed': len(processed_users),
'total_new_edges': len(new_edges)
}
with open(progress_file, 'w', encoding='utf-8') as f:
json.dump(progress_data, f, ensure_ascii=False, indent=2)
print(f"✅ 进度已保存: {len(processed_users)} 个用户完成, {len(new_edges)} 条新边")
def load_p... | Python | 1 |
risk_contrib = weights * marginal_contrib / portfolio_vol
# 標準化風險貢獻
risk_contrib = risk_contrib / risk_contrib.sum()
# 計算與目標的差異
error = np.sum((risk_contrib - target_risk_contrib) ** 2)
return error
... | Python | 1 |
: AtomType::Ordinal }, // 10180
"lbag" => Symbol { unicode: 0x27C5, atom_type: AtomType::Open }, // 10181
"rbag" => Symbol { unicode: 0x27C6, atom_type: AtomType::Close }, // 10182
"veedot" => Symbol { unicode: 0x27C7, atom_type: AtomType::Binary }, // 10183
"bsolhsub" => Symbol { unicode: 0x27C8, atom_... | Rust | 0 |
,
x
),
}
}
}
/* mneumonic opcode clocks flag explanation
*
ld r,r xx 4 ---- r=r
ld r,n xx nn 8 ---- r=n
ld r,(HL) xx 8 ---- r=(HL)
ld (HL),r 7x 8 ---- (HL)=r
ld (HL),n 36 nn ... | Rust | 0 |
})
} else {
// If we're returning an actual value, we need to write it back into the wasm module's memory.
self.func_wrap(module, name, move |mut caller: Caller<'_, InvocationData<K>>, ret: u32 $(, $t: $t)*| {
let (mut m... | Rust | 0 |
8]) {
for byte in buf {
self.0 = (self.0 + *byte as u32) % BASE;
self.1 = (self.1 + self.0) % BASE;
}
}
pub fn checksum(&self) -> [u8; 4] {
(self.1 << 16 | self.0).to_be_bytes()
}
}
<gh_stars>1-10
mod g1 {
use rand_core::SeedableRng;
use rand_xorshift:... | Rust | 0 |
r::PhantomData};
/// Handles jsonrpc requests.
pub trait Handler {
/// Type-check params and call method if method exists. This method is implemented automatically
/// by the [rpc](../easy_jsonrpc_proc_macro/attr.rpc.html) macro.
fn handle(&self, method: &str, params: Params) -> Result<Value, jsonrpc_core:... | Rust | 0 |
8D51)
GL_RENDERBUFFER_HEIGHT=_C('GL_RENDERBUFFER_HEIGHT',0x8D43)
GL_RENDERBUFFER_INTERNAL_FORMAT=_C('GL_RENDERBUFFER_INTERNAL_FORMAT',0x8D44)
GL_RENDERBUFFER_RED_SIZE=_C('GL_RENDERBUFFER_RED_SIZE',0x8D50)
GL_RENDERBUFFER_SAMPLES=_C('GL_RENDERBUFFER_SAMPLES',0x8CAB)
GL_RENDERBUFFER_STENCIL_SIZE=_C('GL_RENDERBUFFER_STENC... | Python | 1 |
right_text = custom_pattern[right_text_start:]
# 合并并输出当前结果
output = left_text + bracketed_text + right_text
# print(f"主循环{i}章节字典:{chapter_dict}")
# 调用 process_output_segment 并获取分章后的章节字典
chapter_dict = self.process_output_segment(output, chapt... | Python | 1 |
oi(self, weekly_themes: List[Dict], business_goals: List[str], historical_roi: Dict[str, Any]) -> Dict[str, Any]:
"""Analyze ROI potential of weekly themes."""
# Implementation would use AI engine for ROI analysis
return {"roi_score": 0.75, "conversion_potential": "high"}
async def _ana... | Python | 1 |
self.thread.start()
def stop(self):
app.shutdown()
self.thread.join(timeout=self.timeout)
class LiveWebTest(BaseWebserverTest):
"""
Real IO LiveTest against LiveWebserver using HTTP requests
"""
def setUp(self, debug=False, profile=True):
"""Set up the test environment... | Python | 1 |
from django.shortcuts import render, get_object_or_404, redirect
from django.contrib import messages
from django.contrib.auth import login, authenticate
from django.contrib.auth.decorators import login_required
from .models import Note
from .forms import NoteForm, UserRegistrationForm
@login_required
def note_list(req... | Python | 1 |
, Ix2>, Array1<L>> + 'static>
FromIterator<P> for MultiTargetModel<ArrayBase<D, Ix2>, L>
{
fn from_iter<I: IntoIterator<Item = P>>(iter: I) -> Self {
let models = iter
.into_iter()
.map(|x| Box::new(x) as Box<dyn PredictRef<ArrayBase<D, Ix2>, Array1<L>>>)
.collect();
... | Rust | 0 |
index(&mut self, index: u32) {
debug_assert!(self.index.is_none());
self.index = Some(index);
}
}
impl fmt::Display for CompileError {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
match self.index {
Some(index) => write!(f, "{} in expression {}", self.reason, index... | Rust | 0 |
for _, (inputs_help, targets) in enumerate(trainloader_help):
if use_cuda:
inputs_help = inputs_help.cuda()
for epoch in range(start_epoch, args.epoch):
mix_inputs_all, mix_targets_all, lams = generate_sample(
trainloader, inputs_help)
train_loss, _ = train(
... | Python | 1 |
:
sprites = []
texture_param = mainFolderSheet + "/" + animationPartFolder + '/' + "param.txt"
params = {}
with open(texture_param, "r") as file:
lines = file.readlines()
if len(lines) == 0:
... | Python | 1 |
_context(
source_code_unit: &SourceCodeUnit, previous_edit_start: usize, previous_edit_end: usize,
rules_store: &mut RuleStore, rules: &Vec<Rule>,
) -> Option<Edit> {
// Context contains - the changed node in the previous edit, its's parent, grand parent and great grand parent
let context = || {
... | Rust | 0 |
let anchors = joint.0.anchors();
insertions.0.push(JointEvent {
handle: entities.entity(*index),
part_one: anchors.0,
part_two: anchors.1,
});
} else {
... | Rust | 0 |
{ self.replace_unchecked(index, value) }
}
/// Writes a new value into a bit, returning the previous value, without
/// bounds checking.
///
/// ## Safety
///
/// `index` must be less than `self.len()`.
///
/// ## Examples
///
/// ```rust
/// use bitvec::prelude::*;
///
/// let bits = bits![mut 0, 0];
... | Rust | 0 |
8ab0ba3c7f
6ab1ceb11d10aa85433f63bbf30b9b0ae8951653bcd3beb12aa61cf942e6e5b442282
0d810871b8f14b7a1059cdadc414c409064a22cf9e970b0ffc6f1fc6fdd539c467677
59f0fe7ab535b75ff4a01887e30a733091b05cc6ace0fd49309fe3758f57f4d0171b2
70e309d14e59413849c3ed672e076d97d71ceace93dcade9f26712461611
KE1: e47c1c5e5eed1910a1cbb6420c5edf26e... | Rust | 0 |
.execute(&*coll.into_inner())
.await?
{
HttpResponse::NoContent().finish()
} else {
HttpResponse::Conflict().finish()
},
)
}
// Copyright takubokudori.
// This source code is licensed under the MIT or Apache-2.0 license.
use crate::*;
use winapi::{
cty... | Rust | 0 |
#[doc = "Output disabled"]
#[inline(always)]
pub fn _000(self) -> &'a mut W {
self.variant(SOSCDIV1_A::_000)
}
#[doc = "Divide by 1"]
#[inline(always)]
pub fn _001(self) -> &'a mut W {
self.variant(SOSCDIV1_A::_001)
}
#[doc = "Divide by 2"]
#[inline(always)]
pub f... | Rust | 0 |
#[tokio::test]
async fn test_node_account_ids_for_execute() {
let mut nodes = HashMap::new();
nodes.insert(
"0.testnet.hedera.com:50211".to_string(),
AccountId::simple(3),
);
nodes.insert(
"1.testnet.hedera.com:50211".to_string(),
Accou... | Rust | 0 |
SyntaxNode {
SyntaxNode::new_root(self.green_node)
}
/// Turn the parse into a DOM tree.
///
/// Any semantic errors that occur will be collected
/// in the returned DOM node.
pub fn into_dom(self) -> dom::RootNode {
dom::RootNode::cast(rowan::NodeOrToken::Node(self.into_syntax... | Rust | 0 |
side-effects, besides the implied
/// side-effects when reading out the RDR register.
/// Handling errors has to be done manually. This can be done, by checking
/// the triggered events via [`Serial::triggered_events`].
///
/// Returns `None` if the hardware is busy.
#[doc(alias = "RDR")]
p... | Rust | 0 |
u32,
}
#[test]
fn bindgen_test_layout__OSUnalignedU32() {
assert_eq!(
::std::mem::size_of::<_OSUnalignedU32>(),
4usize,
concat!("Size of: ", stringify!(_OSUnalignedU32))
);
assert_eq!(
::std::mem::align_of::<_OSUnalignedU32>(),
1usize,
concat!("Alignment of "... | Rust | 0 |
# app/utils.py
import math
# Constantes físicas
Tnt_to_Joules = 4.184e15 # Joules por megatón de TNT
def calculate_impact_energy(diameter_m, velocity_kms, density_kgm3):
"""
Calcula la energía cinética de un asteroide en megatones de TNT.
"""
if diameter_m <= 0 or velocity_kms <= 0 or density_kgm3 <=... | Python | 1 |
olorA = np.empty((len(sensorA),4), dtype=np.float32)
for i in range(len(lbs)):
gcolorA = colors[lbs[i]%15]
#(2)get Target Box:
#get same label id
'''
for k in set(lbs):
gpMask = (lbs == k)
print("Get 3D Box: k:{:} box={:}".format(k,get3dBox(sensorA[gpMask])))
'''
#(3.0)sensorA d... | Python | 1 |
from datetime import datetime
from typing import Union, List
from typing_extensions import TypedDict
import pydantic
from AleMoc.database import models
class BaseModel(pydantic.BaseModel):
table_name: str
# DB objects
class ProductSchema(pydantic.BaseModel):
Id: int
ProductId: str
DateCreated: date... | Python | 1 |
efault (unusable) session type of `()`.
///
/// ```rust
/// # extern crate gotham;
/// # #[macro_use]
/// # extern crate serde_derive;
/// #
/// # use gotham::middleware::session::NewSessionMiddleware;
/// #
/// #[derive(Default, Serialize, Deserialize)]
/// struct MySessionType ... | Rust | 0 |
import pytest
from wps_jobs.weather_model_jobs.utils.interpolate import (
construct_interpolated_noon_prediction,
SCALAR_MODEL_VALUE_KEYS_FOR_INTERPOLATION,
interpolate_between_two_points,
interpolate_wind_direction,
)
from datetime import datetime
from wps_shared.db.models.weather_models import ModelRu... | Python | 1 |
# Licensed to the Apache Software Foundation (ASF) under one
# or more contributor license agreements. See the NOTICE file
# distributed with this work for additional information
# regarding copyright ownership. The ASF licenses this file
# to you under the Apache License, Version 2.0 (the
# "License"); you may not u... | Python | 1 |
, u'栟'),
(0x2F8E6, 'M', u'椔'),
(0x2F8E7, 'M', u'㮝'),
(0x2F8E8, 'M', u'楂'),
(0x2F8E9, 'M', u'榣'),
(0x2F8EA, 'M', u'槪'),
(0x2F8EB, 'M', u'檨'),
(0x2F8EC, 'M', u'𣚣'),
(0x2F8ED, 'M', u'櫛'),
(0x2F8EE, 'M', u'㰘'),
(0x2F8EF, 'M', u'次'),
]
def _seg_75():
return [
(0x2F8F0, '... | Python | 1 |
ature Importance - {symbol} ({self.current_phase})")
plt.xlabel("Importance Score")
plt.ylabel("Features")
plt.grid(True, axis='x')
plt.tight_layout()
# Save plot in phase-specific visualizations directory
plt.savefig(os.path.join(self.phase_dirs[self.current_pha... | Python | 1 |
splay is NULL"));
}
let screen = unsafe { c::XDefaultScreen(display) };
let root_window = unsafe { c::XRootWindow(display, screen) };
let running = Cell::new(false);
Ok(Self {
display,
screen,
root_window,
running,
})
... | Rust | 0 |
Slice<Msb0, u8>) -> Result<(&BitSlice<Msb0, u8>, u16), DekuError> {
u16::read(rest, Self::CTX).map(|(rest, value)| (rest, value / 4))
}
fn write(flight_level: &u16, output: &mut BitVec<Msb0, u8>) -> Result<(), DekuError> {
let value = *flight_level * 4;
value.write(output, Self::CTX)
... | Rust | 0 |
rv1 = T.axis.remap("RR", [i4, i5])
T.where(i2_0 * 80 + i2_1 < 225 and i3_0 * 80 + i3_1 < 225)
T.reads(pad_temp[ax0_3, ax1_3, ax2_3 + rv0, ax3 + rv1])
T.writes(tensor[ax0_3, ax1_3, ax2_3, ax3])
with T.init():
tensor[a... | Python | 1 |
from odoo import api, fields, models
class ResCompanyPartner(models.Model):
_inherit = 'res.company.partner'
contract_ids = fields.One2many('contract.contract', 'partner_id', string='Contracts', copy=False)
contract_count = fields.Integer(compute='_compute_contract_count')
@api.depends('contract_ids... | Python | 1 |
import hashlib
def calculate_sha256(data: str) -> str:
"""Helper function to calculate SHA256 hash of a string."""
sha256_hash = hashlib.sha256()
sha256_hash.update(data.encode())
return sha256_hash.hexdigest()
| Python | 1 |
from typing import Tuple
import numpy
from facefusion import inference_manager
from facefusion.download import conditional_download_hashes, conditional_download_sources
from facefusion.face_helper import warp_face_by_face_landmark_5
from facefusion.filesystem import resolve_relative_path
from facefusion.thread_helper... | Python | 1 |
r) });
std::mem::forget(collector); // We own it as a raw pointer...
raw_ptr
}
#[inline(always)]
unsafe fn gc_write_barrier<'gc, T, V>(
_owner: &Gc<'gc, T>,
_value: &Gc<'gc, V>,
_field_offset: usize
) where T: GcSafe<'gc, CollectorId> + ?Sized, V: GcSafe<'gc, Col... | Rust | 0 |
r with an arbitrary
// period out of it.
force_full_hw_period: true,
// If clearing `mtime` is not allowed, we must record the
// starting value of `mtime` by calling `reset`.
resettable: !<$ty as TimerOptions>::RESET_MT... | Rust | 0 |
e OTG_HS_HCSPLT6 = crate::Reg<u32, _OTG_HS_HCSPLT6>;
#[allow(missing_docs)]
#[doc(hidden)]
pub struct _OTG_HS_HCSPLT6;
#[doc = "`read()` method returns [otg_hs_hcsplt6::R](otg_hs_hcsplt6::R) reader structure"]
impl crate::Readable for OTG_HS_HCSPLT6 {}
#[doc = "`write(|w| ..)` method takes [otg_hs_hcsplt6::W](otg_hs_hc... | Rust | 0 |
},
]
for config in test_configs:
with patch("vibe_check.tools.analyze_issue.EnhancedGitHubIssueAnalyzer.analyze_issue_basic") as mock_basic, \
patch("vibe_check.tools.analyze_issue.EnhancedGitHubIssueAnalyzer.analyze_issue_comprehensive") as mock_comprehensive, \
... | Python | 1 |
from django.urls import path
from steamfake import views
# http://127.0.0.1:8000/steamfake/categoria
urlpatterns = [
path("", views.home),
path("categoria", views.categoria_index, name="categorias"),
path("categoria/cadastro", views.categoria_cadastro),
path("categoria/cadastrar", views.categoria_cada... | Python | 1 |
transmute(hook));
if ok == 0 {
fatal("Unable to hook aiscript opcodes");
}
}
#[no_mangle]
pub unsafe extern fn samase_plugin_init(api: *const PluginApi) {
bw_dat::set_is_scr(crate::is_scr());
let required_version = 30;
if (*api).version < required_version {
fatal(&format!(
... | Rust | 0 |
# Copyright 2009-2017 Ram Rachum.
# This program is distributed under the MIT license.
'''
Defines the `TempFunctionCallCounter` context manager.
See its documentation for more details.
'''
import sys
from python_toolbox import cute_iter_tools
from python_toolbox import address_tools
from python_toolbox.temp_value... | Python | 1 |
reply: f::ReplyCreate,
) {
log::info!("@@@ create");
reply.error(ENOSYS);
}
/// Test for a POSIX file lock.
fn getlk(
&mut self,
_req: &f::Request,
_ino: u64,
_fh: u64,
_lock_owner: u64,
_start: u64,
_end: u64,
_ty... | Rust | 0 |
from django.db.models.signals import post_save, pre_save
from django.dispatch import receiver
from skul_data.school_timetables.models.school_timetable import Timetable, Lesson
from skul_data.action_logs.utils.action_log import log_action
from skul_data.action_logs.models.action_log import ActionCategory
@receiver(pre... | Python | 1 |
verlaps seconds event -> first event has priority
Context::Two,
Context::One,
Context::Two,
Context::One,
Context::Two]);
}
#[test]
fn from_dst_no_overlap() {
let closure = Box::new(|ts| Moment::new_from_timespec(ts + time::Duration::h... | Rust | 0 |
print(int(input('Insira um numero: ')))
num = 7
cont = 0
print('Insira um numero: ')
while num != 7:
cont = cont + 1
print(f'Chance {cont}. Tente novamente!')
| Python | 1 |
er_utils.stix_transmission.utils.RestApiClientAsync.RestApiClientAsync.call_api')
def test_with_invalid_metadata_parameter(self, mock_result_response):
""" test invalid metadata parameter"""
metadata = {'mext_page': '123a'}
query = "{\"feature_name\": \"ALL\",\"product\": \"SAEP\", " \
... | Python | 1 |
from pynput import keyboard
import time
import pyaudio
import wave
import sched
import sys
CHUNK = 1024
FORMAT = pyaudio.paInt16
CHANNELS = 1
RATE = 16000
RECORD_SECONDS = 5
WAVE_OUTPUT_FILENAME = r"/录音文件/input.wav"
p = pyaudio.PyAudio()
frames = []
def callback(in_data, frame_count, time_info, status):
frames.a... | Python | 1 |
self.r
}
pub fn vector(self) -> (I<T>, J<T>, K<T>) {
(self.i, self.j, self.k)
}
}
use crate::app::{App, GamedayPanels};
use std::fmt;
use tui::backend::Backend;
use tui::Frame;
pub struct DebugInfo {
pub game_id: u64,
pub gameday_url: String,
pub terminal_width: u16,
pub t... | Rust | 0 |
VG_128_MSRMTS
}
}
#[doc = "Write proxy for field `ADSEL6`"]
pub struct ADSEL6_W<'a> {
w: &'a mut W,
}
impl<'a> ADSEL6_W<'a> {
#[doc = r"Writes `variant` to the field"]
#[inline(always)]
pub fn variant(self, variant: ADSEL6_A) -> &'a mut W {
{
self.bits(variant.into())
}
... | Rust | 0 |
r()) }
.to_string_lossy()
.into_owned();
return Ok(string);
}
_ => Err(Error::last()),
}
}
fn redirect_std_streams(fd: RawFd) -> Result<()> {
// If fildes2 is already a valid open file descriptor, it shall be closed first
close(STDIN_FILENO)?;
... | Rust | 0 |
from jaxtyping import Float
import numpy as np
from numpy import ndarray
from osu_dreamer.osu.bezier import BezierCurve
def fit_bezier(
points: Float[ndarray, "2 L"],
max_err: float,
constrain_start: bool = False,
constrain_end: bool = False,
) -> list[BezierCurve]:
"""fits a cubic poly-Bezier ... | Python | 1 |
flip=False)
img = self.transform(img.astype(np.float32)) / 255.
root_joint_cam = data['root_joint_cam']
input = {
'img': img,
'full_img': full_img,
'img_fn': img_path,
'bbox': bbox,
'cam_param': cam_para... | Python | 1 |
xchange_weak(ptr2, ptr, Ordering::Release, Ordering::SeqCst);
//~^ ERROR compare_exchange_weak's failure ordering may not be stronger
// Relaxed success order also forbids failure order of Acquire or SeqCst
let _ = x.compare_exchange_weak(ptr, ptr2, Ordering::Relaxed, Ordering::SeqCst);
//~^ ERROR comp... | Rust | 0 |
opt_minmax(histogram_req, min_max);
let empty_sub_aggregation = IntermediateAggregationResults::empty_from_req(&sub_aggregation);
// Use merge_join_by to fill in gaps, since buckets are sorted
let buckets = buckets
.into_iter()
.merge_join_by(
fill_gaps_buckets.into_iter(),
... | Rust | 0 |
Syntax(res.get("document", ""), "python", theme="monokai", line_numbers=True),
title=title,
border_style="cyan",
subtitle=meta.get('file_path', 'N/A')
)
self.console.print(panel)
def _display_structural_table(self, title: str, node... | Python | 1 |
.warn("Warning")
_log.debug("Debug")
_log.trace("Trace", "with", {}, "data")
"#, None).unwrap();
}
}<reponame>ordian/sled
//! ## Built-In Profiler
//!
//! To get a summary of latency histograms relating to different operations you've used on a sled database, sled can print a nice ta... | Rust | 0 |
import sqlite3
conn = sqlite3.connect("players.sqlite3")
cursor = conn.cursor()
FL = open("playersdb.txt", "r")
for line in FL.readlines():
cursor.execute(line)
FL.close()
conn.commit()
conn.close() | Python | 1 |
import re
import copy
import os
import inspect
from run.streaming_media.service.Link_parsing.core.cloud_music_draw import draw_netease_music_card
from run.streaming_media.service.Link_parsing.core.netease_music import fetch_song_info, download_image
json_init = {
"status": False,
"content": {},
"reason": ... | Python | 1 |
() {
bindings_csharp().unwrap();
}
#[test]
fn test_building_and_querying() {
let min = Double3 {
x: -1.0,
y: -1.0,
z: -1.0,
};
let max = Double3 {
x: 1.0,
y: 1.0,
z: 1.0,
};
let bounds = BoundsD { min, max };
let b = BVHBounds {
bounds... | Rust | 0 |
# -*- coding: utf-8 -*-
{
'name': "Material Request",
'version': '17.0.1.0.0',
'depends': ['base','mail','product','stock'],
'author': "Author Name",
'application': True,
'category': 'Category',
'description': """
Request for the materials
""",
'data': [
'security/materi... | Python | 1 |
-> Callee
{
//!
//
// Create a method callee where the method is coming from a trait
// instance (e.g., @Trait type). In this case, we must pull the
// fn pointer out of the vtable that is packaged up with the
// @Trait instance. @Traits are represented as a pair, so we first
// evalua... | Rust | 0 |
from test.vim_test_case import VimTestCase as _VimTest
from test.constant import *
# List Snippets {{{#
class _ListAllSnippets(_VimTest):
snippets = (('testblah', 'BLAAH', 'Say BLAH'),
('test', 'TEST ONE', 'Say tst one'),
('aloha', 'OHEEEE', 'Say OHEE'),
)
class... | Python | 1 |
Extent3d {
width,
height,
depth_or_array_layers: 1,
},
TextureDimension::D2,
vec![0; (width * height * 4) as usize],
TextureFormat::Rgba8UnormSrgb,
);
let texture = images.add(img);
commands
.spawn_bundle(SpriteBundle {
... | Rust | 0 |
get_manifest(ar: &mut Archive<File>) -> Vec<DockerManifest> {
let mut manifest_data = String::new();
for file in ar.entries().unwrap() {
let mut file = file.unwrap();
if Path::new("manifest.json") == file.header().path().unwrap() {
file.read_to_string(&mut manifest_data).unwrap();
... | Rust | 0 |
= py.import( "numpy" ).unwrap();
let kwargs = PyDict::new( py );
let shape = PyTuple::new( py, &init.shape );
kwargs.set_item( "shape", shape ).unwrap();
let order = match init.order {
ArrayOrder::RowMajor => "C",
ArrayOrder::ColumnMajor => "F"
};
... | Rust | 0 |
s(self, response: requests.Response):
"""A stub for the decorator function being tested"""
with patch.object(IntercomRateLimiter, "backoff_time") as backoff_time_mock:
# Call `check_backoff_time` instead of original `IntercomRateLimiter.backoff_time` method
backoff_time_mock.side_effect... | Python | 1 |
}
impl ::protobuf::Clear for GetRequest {
fn clear(&mut self) {
self.id = ::std::option::Option::None;
self.seq = ::std::option::Option::None;
self.resourceId = ::std::option::Option::None;
self.wait = ::std::option::Option::None;
self.ifAvailable = ::std::option::Option::No... | Rust | 0 |
(ref k, ref v) in slot.iter() {
// if *k == *key {
// return Some(v)
// }
// }
// None
}
/// Get a value using deref type.
///
/// This is usable only if the key is a type of smart pointer that can be deref into another type
/// which impleme... | Rust | 0 |
"::",
stringify!(partial_aad_size)
)
);
assert_eq!(
unsafe { &(*(::std::ptr::null::<atca_aes_gcm_ctx>())).enc_cb as *const _ as usize },
96usize,
concat!(
"Offset of field: ",
stringify!(atca_aes_gcm_ctx),
"::",
stringif... | Rust | 0 |
try:
os.remove(file_path)
count += 1
except OSError as e:
logger.warning(f"无法删除缓存文件 {file}: {e}")
return count
except Exception as e:
logger.warning(f"清理缓存时出错: {e}")
return count
def ... | Python | 1 |
) -> zbus::Result<String>;
/// Filters property
#[dbus_proxy(property)]
fn filters(&self) -> zbus::Result<u64>;
/// Groups property
#[dbus_proxy(property)]
fn groups(&self) -> zbus::Result<u64>;
/// Locked property
#[dbus_proxy(property)]
fn locked(&self) -> zbus::Result<bool>;
... | Rust | 0 |
# Atividade 03:
# Tabuada de um Número:
# Faça um programa que solicite um número ao usuário e use
# um laço while para exibir a tabuada desse número (de 1 a 10).
c = 0
m = 0
r = 0
n = int(input('Digite um numero: '))
while n != 10:
c += 1
n | Python | 1 |
import torch
import os
import logging
from tensorizer import TensorSerializer, stream_io
from diffusers import StableDiffusionPipeline
from argparse import ArgumentParser
logging.basicConfig(level=logging.INFO)
logger = logging.getLogger(__file__)
parser = ArgumentParser()
parser.add_argument("--hf-model-id", default... | Python | 1 |
_ok());
let msgs = into_messages(&resp);
assert_eq!(original.len(), msgs.len());
for (msg, orig) in msgs.into_iter().zip(original.iter()) {
assert_eq!(str::from_utf8(msg.value).unwrap(), *orig);
}
}
fn skip_lines(mut lines: &str, mut n: usize) -> &str {
whil... | Rust | 0 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.