text string | label_name string | labels int64 |
|---|---|---|
from collections.abc import Sequence
from langchain_core.tools import BaseTool
def validate_tools_single_input(class_name: str, tools: Sequence[BaseTool]) -> None:
"""Validate tools for single input.
Args:
class_name: Name of the class.
tools: List of tools to validate.
Raises:
... | Python | 1 |
class FastAPICLIException(Exception):
pass
| Python | 1 |
import os
import math
import ansi
def get_option( prompt, options, is_alpha = False ):
if is_alpha:
all_alpha = "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
indices = []
for i in range( 0, len( options ) ):
indices.append( all_alpha[ i ] )
else:
indices = []
for i in range( 1, len( options ) + 1 ):
indices.append( s... | Python | 1 |
rc<Regex>>>(regex: T, field: Field) -> Self {
RegexQuery {
regex: regex.into(),
field,
}
}
fn specialized_weight(&self) -> AutomatonWeight<Regex> {
AutomatonWeight::new(self.field, self.regex.clone())
}
}
impl Query for RegexQuery {
fn weight(
&s... | Rust | 0 |
map_index = 56,
max_tries = 56,
operator = '',
pid = 56,
pool = '',
pool_slots = 56,
priority_weight = 56,
queue = '',
q... | Python | 1 |
) -> App<'a, 'b> {
App::new("hast")
.about("calculate hash")
.subcommand(
SubCommand::with_name("calc")
.about("calc hash")
.subcommand(command::create_calc_md5())
.subcommand(command::create_calc_sha1())
.subcommand(command... | Rust | 0 |
, F> as *const (),
)),
Box_::into_raw(f),
)
}
}
}
impl fmt::Display for ScriptWorld {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
f.write_str("ScriptWorld")
}
}
//! b(byte): 8bit
//! h(half word): 16bit
//! w(word): 32bit
use crate::ana... | Rust | 0 |
_eq!(s1, s2);
}
#[test]
fn check_invalid_signature() {
let msg = RecoveryMessage::Data("Some data".into());
let address =
Address::from_str("0x014587212741268ad0b1bc727efce9711dbde69c484a9db38bd83bb1b3017c05")
.unwrap();
let mut signature = Signature::fro... | Rust | 0 |
/// If the span builder or context contains a valid span context, it is propagated.
fn build(&self, mut builder: trace::SpanBuilder) -> Self::Span {
let parent_span_context = builder.parent_context.take().and_then(|parent_cx| {
if parent_cx.has_active_span() {
Some(parent_cx.spa... | Rust | 0 |
entry.path()).await?;
match PostInfo::build(content).await {
Ok(page) => {
pages.insert(filename, page);
}
Err(error) => eprintln!(
"Error while opening and rendering post at {}: {}",
filename, error... | Rust | 0 |
AvailablePythonsHelper;
impl Command for AvailablePythonsHelper {
fn run(_config: &Config, _matches: &ArgMatches) -> Result<CommandResult> {
let re = Regex::new(r"^python\d?(?:\.\d+(?:\.\d+)?)?$")?;
let mut python_interpreters: Vec<String> =
which_re(re)?.map(|p| p.file_name().unwrap()... | Rust | 0 |
import FWCore.ParameterSet.Config as cms
from SimGeneral.HepPDTESSource.pythiapdt_cfi import *
from RecoParticleFlow.PFClusterProducer.particleFlowCluster_cff import *
pfClusterRefsForJetsHCAL = cms.EDProducer("PFClusterRefCandidateProducer",
src = cms.InputTag('particleFlowClusterHCAL'),
particleTy... | Python | 1 |
GPublicKeyChangeHandler<
dkg_runtime_primitives::AuthoritySetId,
>;
type ProposalHandler: ProposalHandlerTrait;
/// A type that gives allows the pallet access to the session progress
type NextSessionRotation: EstimateNextSessionRotation<Self::BlockNumber>;
/// Percentage session should have progressed f... | Rust | 0 |
k.name}, 作者: {book.author}")
book.safeName = SanitizeName(book.name)
book.decryptedFolder = Path(f"decrypted/{book.id}")
book.decryptedFolder.mkdir(parents=True,exist_ok=True)
book.decryptedTxt = Path(f"{book.safeName}.txt")
if GetContents(book) != 0: #这个方法作用到了book上
Print.opt(f"[OP... | Python | 1 |
ics["surya"][m] for m in metric_types],
]
if tesseract:
table_data.append(
["tesseract", tess_time, tess_time / len(images)] + [mean_metrics["tesseract"][m] for m in metric_types]
)
print(tabulate(table_data, headers=table_headers, tablefmt="github"))
print("Precision and re... | Python | 1 |
n = int(input())
a=[]
for i in range(n):
a.append(int(input()))
i=0
j=n-1
c=0
while i<j:
c = a[i]
a[i] = a[j]
a[j] = c
i+=1
j-=1
print(a) | Python | 1 |
ter == flag_70 and epoch == 0:
torch.save(accelerator.unwrap_model(model).state_dict(), './ckpt/layer_' + str(args.tf_layer) + '_model_07.pt')
accelerator.print("Save ckpt for 0.7 data!")
if counter == flag_80 and epoch == 0:
torch.save(accelerator.unwrap_model(model).state_dict(), './ckpt/layer_' + str... | Python | 1 |
Err(err) => panic!("Failed to connect socket: {}", err)
/// };
/// ```
///
/// # Error
///
/// - `BadFileDescriptor` : The socket is invalid.
/// - `TooManyOpenFiles` : Maximum number of active endpoints was reached.
/// - `InvalidArgument` : The syntax of the supplied address is in... | Rust | 0 |
self.apply_to(string));
}
#[inline(always)]
fn write(&self, f: &mut fmt::Formatter<'_>, string: &str) -> fmt::Result {
write!(f, "{}", self.apply_to(string))
}
}
macro_rules! Skin {
(
$($name:ident: $fg:expr, $bg:expr; $({$a:expr})*)*
) => {
pub struct Skin {
... | Rust | 0 |
tab.columns.push((
"d".to_string(),
ColumnInfo {
ordinal: 0,
..Default::default()
},
));
tab.sort_columns_by_ordinal();
println!("columns: {:?}", tab.columns);
}
#[test]
fn test_type_sizes() {
show_o... | Rust | 0 |
pen('男性样本GWLR_regression_results_加上城市层面变量之后.csv', 'w', newline='', encoding='utf-8') as f:
writer = csv.writer(f)
writer.writerows(output_data)
'''分析女性样本'''
# 加载数据
file_path = 'logit模型数据表(不包含性别交叉项)+城市层面+去空值并标准化.csv'
df = pd.read_csv(file_path)
print(df.head())
print(len(df['... | Python | 1 |
and "message" in example
and "description" in example
and "error_code" in example
and "data" not in example
):
... | Python | 1 |
1 ),
( 0, 0, 1, 1 ),
( 0, 0, 1, 1 ),
( 0, 0, 1, 1 ),
( 0, 0, 1, 1 ),
( 0, 0, 1, 1 ),
( 0, 0, 1, 1 ),
( 0, 0, 1, 1 ),
( 0, 0, 1, 1 ),
])
#-------------------------------------------------------------------------
# test_case_random
#-----------------------------------------------------... | Python | 1 |
try:
# 解析HTML片段
item_soup = BeautifulSoup(html_item, 'html.parser')
cells = item_soup.select('td')
... | Python | 1 |
polity_id: Option<Uuid>,
pub saint_ids: Option<Vec<uuid::Uuid>>,
pub title: Option<String>,
pub first_name: Option<String>,
pub middle_name: Option<String>,
pub last_name: Option<String>,
pub date_of_birth: Option<NaiveDate>,
pub place_of_birth: Option<String>,
pub email: Option<String>,... | Rust | 0 |
# Copyright 2023 Carlos Dauden - Tecnativa
# Copyright 2023 Sergio Teruel - Tecnativa
# License AGPL-3.0 or later (https://www.gnu.org/licenses/agpl).
from odoo import fields, models
class SaleOrder(models.Model):
_name = "sale.order"
_inherit = ["sale.order", "product.cost.security.mixin"]
margin = fiel... | Python | 1 |
Ip0'],
'-fieldWidth', 'thirtyTwoBits',
'-protocolOffset', 'Root.0',
'-values', [])
ixNet.commit()
#Configuring L2-L3 IPv6 Traffic Item
print ("Configuring L2-L3 IPv6 Traffic Item\n")
trafficItem2 = ixNet.add(ixNet.getRoot() + '/traffic', 'trafficItem')
ixNet.setMultiAttribute(trafficItem2, '-name', 'IPv6_M... | Python | 1 |
}
}
#[macro_use]
extern crate log;
use futures::Future;
use gallop::clients::packer::{PackerClientImpl, PackerClientWrapper};
use gallop::core::index::TantivyIndex;
use grpcio::{RpcContext, UnarySink};
use gallop::core::grpc;
use gallop::protos::common::Error;
use gallop::protos::common::{Segment, SegmentId};
use gal... | Rust | 0 |
"""
Write a function to sort a list of tuples using the second value of each tuple.
assert subject_marks([('English', 88), ('Science', 90), ('Maths', 97), ('Social sciences', 82)])==[('Social sciences', 82), ('English', 88), ('Science', 90), ('Maths', 97)]
"""
def subject_marks(marks):
return sorted(marks, key=lam... | Python | 1 |
bug!("qbox events startup");
broadcast(Event::Startup)?;
// log::debug!("qbox database startup");
// //启动数据库
// crate::db::startup()?;
Ok(())
}
pub fn shutdown() -> Result<()> {
broadcast(Event::Shutdown)
}
// ignore-test auxiliary file for include-single-expr.rs
0
// trailing comment permitt... | Rust | 0 |
distances = {
"Voyager 1": 163,
"Voyager 2": 136,
"Pioneer 10": 80,
"New Horizons": 58,
"Pioneer 11": 44,
}
def main():
for name in distances.keys():
print(f"{name} is {distances[name]} AU from Earth")
main() | Python | 1 |
rget.translation);
println!("move z: +0.1");
target.translation.vector.z += 0.1;
// Create IK solver with default settings
let solver = k::JacobianIKSolver::default();
// Create a set of joints from end joint
let arm = k::SerialChain::from_end(target_link);
// solve and move the manipulato... | Rust | 0 |
u8>, cl_int> {
api_info_size!(get_size, clGetCommandQueueInfo);
let size = get_size(command_queue, param_name)?;
api_info_vector!(get_vector, u8, clGetCommandQueueInfo);
get_vector(command_queue, param_name, size)
}
/// Get specific information about an OpenCL command-queue.
/// Calls clGetCommandQue... | Rust | 0 |
)
return rimat, ramat, org_mat
return [], [], []
def get_images(self, img_name):
stp = str(img_name)
if img_name < 10:
stp = '0000' + stp
elif img_name < 100:
stp = '000' + stp
elif img_name < 1000:
stp = '00' + stp
els... | Python | 1 |
import requests
import base64
import os
import random
import time
from urllib.parse import urlparse, parse_qs
# 输入参数
originallink = input("原始链接: ")
bookname = input("图书名: ")
totalpage = int(input("总页数: "))
getPDF = int(input("是否合成PDF(1合成,0跳过):"))
delePNG = int(input("是否删除图片(1删除,0保留):"))
zoom = 50 # 默认的zoom值,未详细证明,请... | Python | 1 |
mod vm_aux;
pub mod error;
pub use vm::LuaType;
pub use vm::RustFunc;
pub use vm::State;
use compiler::Chunk;
use instr::Instr;
/// Custom result type for evaluating Lua.
pub type Result<T> = std::result::Result<T, error::Error>;
use std::process::Command;
use std::process;
use std::env;
fn main() {
//Grabs argu... | Rust | 0 |
minutes: Box<HashMap<u32, u32>>,
}
impl GuardRecord {
fn new(total: u32) -> GuardRecord {
GuardRecord {
total,
minutes: Box::new((0..60).map(|minute| (minute, 0u32)).collect()),
}
}
}
const FALL_ASLEEP: &str = "falls asleep";
const WAKE_UP: &str = "wakes up";
fn build_g... | Rust | 0 |
n 0..size {
s8k.push(s8.insert(a));
}
(s8, s8k)
},
|(i, k)| {
for _ in 0..size {
black_box(i.get(k[rng.gen_range(0, size)]));
}
},
BatchSize::SmallInput,
);
... | Rust | 0 |
with open('Input.txt', 'r') as f:
data = f.read().split('\n')
rules = [rule.split('|') for rule in data if '|' in rule]
updates = [update.split(',') for update in data if ',' in update]
ruleDict = {}
for rule in rules:
ruleDict.setdefault(rule[0], set()).add(rule[1])
# Part1
correctMiddlesList = []
incorrect... | Python | 1 |
"""
Yang-Zhang-s-Realized-Volatility-Automated-Estimation-in-Python
https://github.com/hugogobato/Yang-Zhang-s-Realized-Volatility-Automated-Estimation-in-Python
论文地址:https://www.jstor.org/stable/10.1086/209650
"""
import warnings
import numpy as np
import pandas as pd
def rv_from_stock_zh_a_hist_min_em(
symbol... | Python | 1 |
ors::Invalid);
}
#[test]
fn should_allow_origins_that_matches_hosts() {
// given
let origin = Origin::parse("http://127.0.0.1:8080");
let host = Host::parse("http://127.0.0.1:8080");
let origin = Some(&*origin);
let host = Some(&*host);
// when
let res = get_cors_allow_origin(origin, host, &None);
... | Rust | 0 |
e`, and `unstable`.
fn generate_protocol_headers() -> io::Result<PathBuf> {
let output_dir_str = env::var("OUT_DIR").unwrap();
let out_path: PathBuf = format!("{}/wayland-protocols", output_dir_str).into();
fs::create_dir(&out_path).ok();
let protocols_prefix = pkg_config::get_variable("wayland-protocol... | Rust | 0 |
te_certs=attr_certs,
)
return cert_info
def byte_range_digest(
stream: IO,
byte_range: Iterable[int],
md_algorithm: str,
chunk_size=misc.DEFAULT_CHUNK_SIZE,
) -> Tuple[int, bytes]:
"""
Internal API to compute byte range digests. Potentially dangerous if used
without due caution.
... | Python | 1 |
self
}
/// Add additonal whitelisted tag-specific attribute values without overwriting old ones.
///
/// # Examples
///
/// let a = ammonia::Builder::default()
/// .add_tags(&["my-tag"])
/// .add_tag_attribute_values("my-tag", "my-attr", &[""])
/// ... | Rust | 0 |
_name = Path(audio_path).with_suffix("").name
audio_names.append(audio_name)
return audio_names
def path2tensor(filepath):
tensor, _ = apply_effects_file(
str(filepath),
[
["channels", "1"],
["rate", "16000"],
["norm"],
],
)
retu... | Python | 1 |
from .bevformer_head import BEVFormerHead
from .bev_head import BEVHead
| Python | 1 |
import os
import json
from loguru import logger
from magic_pdf.pipe.UNIPipe import UNIPipe
from magic_pdf.rw.DiskReaderWriter import DiskReaderWriter
import magic_pdf.model as model_config
model_config.__use_inside_model__ = True
try:
current_script_dir = os.path.dirname(os.path.abspath(__file__))
demo_nam... | Python | 1 |
fn from_client(
ctx: &Context,
peer: SocketAddr,
hostnames: Vec<String>,
) -> Result<WorkerPair> {
trace!("Creating new WS worker pair");
let internal_addr = Address::random_local();
let sender = WebSocketSendWorker::<TcpClientStream>::new(
peer,
... | Rust | 0 |
if getattr(libro, criterio, "").lower() == valor.lower():
resultado.append(libro)
return resultado
except Exception as e:
# Si ocurre un error al realizar la búsqueda, se maneja
print(f"Error al buscar el libro: {e}")
traceback.print_exc... | Python | 1 |
import json, os, re
import pandas as pd
path = "output"
# base
_plot = {
"Big Bad":['MoonOverMiami', 'StarterFor10', 'Secretariat', 'CantHardlyWait', 'MarleyAndMe', 'Evita', 'WeWereSoldiers', 'TheChristmasToy', 'ShatteredGlass', 'StuckInLove', 'NightMoves', 'TheDevilsArithmetic', 'QuickChange', 'Ararat', 'Whistl... | Python | 1 |
e:
# calculate the number of wavs for each preocess
if args.audio_in.endswith(".scp"):
f_scp = open(args.audio_in)
wavs = f_scp.readlines()
else:
wavs = [args.audio_in]
for wav in wavs:
wav_splits = wav.strip().split()
wav_name ... | Python | 1 |
ectors.
///
/// [`NonEmpty`] enables you to safely check `to.first()` or `from.first()`
/// without returning an option. It is guaranteed that there is at least
/// one element.
FocusChanged {
/// The list of elements that has become active after the focus
/// change
to: NonE... | Rust | 0 |
"tipo_grafico": request.tipo_grafico,
"resposta": resposta,
"slug": request.slug,
"status": "success"
})
except Exception as e:
print(f"❌ Erro ao gerar gráfico: {str(e)}")
return JSONResponse(
content={
"pergun... | Python | 1 |
col, label| {
col.push(Text::new(label).size(spacings::_6))
});
let progresses = state.percentage.iter().fold(
Column::new().spacing(spacings::_6).width(Length::Fill),
|col, &perc| {
col.push(
ProgressBar::new(0.0..=100.0, ... | Rust | 0 |
'''Write a Python program to find the nested list elements, which are present in another list using lambda.
Original lists: [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14]
[[12, 18, 23, 25, 45], [7, 11, 19, 24, 28], [1, 5, 8, 18, 15, 16]]
Intersection of said nested lists:
[[12], [7, 11], [1, 5, 8]]'''
original_list ... | Python | 1 |
/// Environment configuration uses this prefix, plus a _.
pub const ENVIRONMENT_PREFIX: &'static str = "NEXTEST";
/// The name of the default profile.
pub const DEFAULT_PROFILE: &'static str = "default";
/// Reads the nextest config from the given file, or if not specified from `.config/nextest.... | Rust | 0 |
(
i,
_a: parse_ber_integer >> _b: parse_der_struct!(parse_ber_integer >> (())) >> (())
)
}
// verifying tag
fn parse_struct04(i: &[u8], tag: BerTag) -> BerResult<MyStruct> {
parse_der_struct!(
i,
TAG tag,
a: parse_ber_integer >>
b: parse_ber_integer >>
... | Rust | 0 |
import re
import sys
import typer
app = typer.Typer(help="CLI tool to parse test output logs.")
@app.command()
def parse_go_failures():
"""
Print FAIL blocks and DONE lines from test output.
Pipe test output into this command.
"""
in_fail_block = False
for line in sys.stdin:
line = re... | Python | 1 |
if (expected_size != actual_size):
raise Exception('Block grid received from server did not match expected observation size')
idx = 0
grid = {} # type: dict[Vector, Block]
for x in range(-observable_distances.x, observable_distances.x):
for z in range(-observ... | Python | 1 |
0, -1, -2],
[0, 0, -1, -2]])
self.assertAllClose(corner_offsets[1, :, :, 2],
[[1, 1, 0, 0],
[0, 0, 3, 3],
[0, 2, 2, 2],
[0, 1, 1, 1]])
self.assertAllClose(corner_offsets[1, :, :, 3],
... | Python | 1 |
(*family).maxWidth = (*thisFont).width
}
if ((*thisFont).slant as libc::c_int) < (*family).minSlant as libc::c_int {
(*family).minSlant = (*thisFont).slant
}
if (*thisFont).slant as libc::c_int > (*family).maxSlant as libc::c_int {
... | Rust | 0 |
(32, 32),
(160, 160),
(5760, 5760),
(8192, 8202),
(8232, 8233),
(8239, 8239),
(8287, 8287),
(12288, 12288),
];
pub const SPACE_SEPARATOR: &'static [(u32, u32)] = &[
(32, 32),
(160, 160),
(5760, 5760),
(8192, 8202),
(8239, 8239),
(8287, 8287),
(12288, 12288),
... | Rust | 0 |
""" The fire zone, fire centre and hfi polygons live in a different database - it's our "tileserver"
database.
"""
from typing import AsyncGenerator
from contextlib import asynccontextmanager
from sqlalchemy.orm import sessionmaker
from sqlalchemy.ext.asyncio import create_async_engine, AsyncSession
from wps_shared imp... | Python | 1 |
> 0 else 80
for c in s:
pitch = c + ((octave - 1) * 12)
encoding.append(
(measure, pos, program, pitch, duration, velocity, timesig, tempo))
encoding = lis... | Python | 1 |
def price_alert(current_price, target_price):
if current_price >= target_price:
return "📢 লক্ষ্য মূল্য ছুঁয়েছে!"
return ""
| Python | 1 |
uns the main game loop.
fn run_loop(world: &mut World, scheduler: &mut Scheduler, shutdown_rx: Receiver<()>) {
loop {
if shutdown_rx.try_recv().is_ok() {
// Shut down
return;
}
let start_time = current_time_in_millis();
scheduler.execute(world);
// h... | Rust | 0 |
ate_currency_name = st.text_input("Update Currency Name", value=selected_currency_data['name'])
if st.button("Update Currency"):
update_currency = {"code": update_currency_code, "name": update_currency_name}
make_request(f"/currencies/{selected_currency_data['id']}", params=u... | Python | 1 |
import math
from tha3.mocap.ifacialmocap_constants import BLENDSHAPE_NAMES, HEAD_BONE_X, HEAD_BONE_Y, HEAD_BONE_Z, \
RIGHT_EYE_BONE_X, RIGHT_EYE_BONE_Y, RIGHT_EYE_BONE_Z, LEFT_EYE_BONE_X, LEFT_EYE_BONE_Y, LEFT_EYE_BONE_Z, \
HEAD_BONE_QUAT, LEFT_EYE_BONE_QUAT, RIGHT_EYE_BONE_QUAT
IFACIALMOCAP_PORT = 49983
IFAC... | Python | 1 |
ritish side was led by Lieutenant Colonel Francis Smith.
Claim: The Stanford Prison Experiment was conducted in the basement of Encina Hall, Stanford’s psychology building.
Evidence: Carried out August 15-21, 1971 in the basement of Jordan Hall, the Stanford Prison Experiment set out to examine the psychological effec... | Python | 1 |
base32(20000000000), 65353130)
}
// All SHA-256 Tests for TOTP from RTC6238
// Tests 1-2 ran with 'SECRET_BYTES_SHA256'
#[test]
fn rtc_test_1_sha256() {
assert_eq!(
run_rfc_test_bytes_with_digest(59, MacDigest::SHA256),
46119246
)
}
#[test]
fn rtc_test_2_sha256() {
assert_eq!(
run_... | Rust | 0 |
import pytest
from click.testing import CliRunner
from dbt_bouncer.main import cli
def test_logging_debug_cli(caplog) -> None:
runner = CliRunner()
runner.invoke(
cli,
["--config-file", "dbt-bouncer-example.yml", "-v"],
)
assert "Running dbt-bouncer (0.0.0)..." in caplog.text
asse... | Python | 1 |
freshestCRL (CtEe)
//PERMISSIBLE TYPES (4)
// - CrlScope : Complete, Delta
// - CrlCoverage : All, EeOnly
//CA certificate with CRL DP or freshestCRL (CaDp)
//PERMISSIBLE TYPES (8)
// - CrlScope : Complete, Dp, Delta, DeltaDp
// - CrlCoverage : All, CaOnly
//CA certificate with no CRL DP nor freshestCRL (CtCa)
//P... | Rust | 0 |
lops_counter_hook,
# normalizations
nn.BatchNorm1d: norm_flops_counter_hook,
nn.BatchNorm2d: norm_flops_counter_hook,
nn.BatchNorm3d: norm_flops_counter_hook,
nn.GroupNorm: norm_flops_counter_hook,
nn.InstanceNorm1d: norm_flops_counter_hook,
nn.InstanceNorm2d: nor... | Python | 1 |
String>> = HashMap::new();
imports.insert("react".into(), vec!["https://esm.sh/react".into()]);
imports.insert(
"react-dom/".into(),
vec!["https://esm.sh/react-dom/".into()],
);
imports.insert(
"https://deno.land/x/aleph/".into(),
vec!["http://localhost:9006/".into()],
);
... | Rust | 0 |
294
C 1.00998 1.73774 -3.59280
O 1.09874 2.34143 -4.64607
O 1.61155 2.19132 -2.48091
H 2.04906 3.01525 -2.77997
C 0.34525 -0.16868 -2.00668
H -0.05656 0.49552 -1.23462
H 1.38253 ... | Python | 1 |
#!/usr/bin/evn python
#-*- coding:utf-8 -*-
#*******************************************************
# Copyright (C) 2014 - All Rights Reserved
# Author(s): BlackYe_. <hswjzhang@gmail.com>
# Time:2014-04-04
#
# Function: 子域名查询接口
#******************************************************
from DomainAnalysis.domain_plugin ... | Python | 1 |
esult {
#[cfg(feature = "tracing")]
tracing::trace!("checking if {} exists in environment", env);
if let Ok(cmd) = std::env::var(env) {
#[cfg(feature = "tracing")]
tracing::trace!("found {} = {}", env, cmd);
open_with_command(&cmd, target)
} else {
#[cfg(feature = "traci... | Rust | 0 |
er, secondary_update, &nc);
assert_eq!(
res.err().unwrap(),
ErrorKind::InvalidMessageData(
"Lock Slate inputs are not found at the chain".to_string()
)
); // Swap cannot be accepted
}
// Because of gonden output new line symbol we skipping Windows.
#[cfg(not(target_os = "windows"))]
#[test]
#[se... | Rust | 0 |
#[must_use]
pub fn base_array_layer(mut self, base_array_layer: u32) -> Self {
self.0.base_array_layer = base_array_layer as _;
self
}
#[inline]
#[must_use]
pub fn image_view_binding(mut self, image_view_binding: crate::vk1_0::ImageView) -> Self {
self.0.image_view_bindin... | Rust | 0 |
# シールド中は弾を反射
proj.reflect(self.player2)
def draw(self):
"""描画処理 - ズーム機能付き"""
if self.state == GameState.GAME or self.state == GameState.TRAINING or self.state == GameState.AUTO_TEST:
# プレイヤー間の距離を計算
dx = self.player1.x - self.player2.... | Python | 1 |
ized + RedisWrite,
{
let mut buf = [0u8; 3];
let n = ::itoa::write(&mut buf[..], *self).unwrap();
out.write_arg(&buf[..n])
}
fn make_arg_vec<W>(items: &[u8], out: &mut W)
where
W: ?Sized + RedisWrite,
{
out.write_arg(items);
}
fn is_single_vec_arg(_i... | Rust | 0 |
})?;
Ok(Some(RGB8 {
r: r?,
g: g?,
b: b?,
}))
} else {
Ok(None)
}
}
/// # Errors
///
/// Returns `Err` if the parameter can't be parsed.
fn parse_vector3_parameter(
&self,
... | Rust | 0 |
import json
def load_json(file_path):
with open(file_path, "r") as file:
return json.load(file)
def save_json(file_path, data):
with open(file_path, "w") as file:
return json.dump(data, file, indent=4)
class Aluno:
def __init__(self, id, nome, idade, curso_id):
... | Python | 1 |
#!/usr/bin/python3
# -*- coding: utf-8 -*-
# @Author: Hui
# @File: unit.py
# @Desc: { 单位数据模型 }
# @Date: 2024/04/24 11:05
import re
class ByteUnit:
"""字节大小单位"""
B = 1 # 字节
KB = 1024 * B # 千字节 (1 KB = 1024 字节)
MB = 1024 * KB # 兆字节 (1 MB = 1024 KB)
GB = 1024 * MB # 吉字节 (1 GB = 1024 MB)
TB = ... | Python | 1 |
import curses
import random
from Suelo import Suelo
ejeYCopia = 20
def main(con:curses.window):
curses.start_color()
curses.init_color(20, 255, 100, 0)
curses.init_pair(1,curses.COLOR_GREEN,curses.COLOR_BLACK)
curses.init_pair(2, 20, curses.COLOR_BLACK)
curses.init_pair(3, curses.COLOR_BLACK, curse... | Python | 1 |
ff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], ... | Rust | 0 |
Deserialization is also performed within this task, so it doesn't
/// have elevated priority.
pub fn hd_rx(cx: crate::app::hd_rx::Context) {
let mut buffer: crate::hdcomm::RxBuf = [0; 516];
let buffer = &mut buffer[..];
let read = cx.local.hd_rx.read(buffer);
let mut window = &buffer[..read];
// D... | Rust | 0 |
es = import_dtypes_module(self._compliant_series._version)
if dtype == dtypes.Date:
# Date is only supported in pandas dtypes if pyarrow-backed
s_cast = s.astype("Int32[pyarrow]")
result = calculate_timestamp_date(s_cast, time_unit)
elif isinstance(dtype, dtypes.Datet... | Python | 1 |
pub line_number_click_margin: f32,
pub draw_line_numbers: bool,
pub top_padding: f32,
//pub colors: CodeEditorColors,
pub cursor_blink_speed: f64,
pub _undo_id: u64,
pub highlight_area_on: bool,
pub mark_unmatched_parens: bool,
pub draw_cursor_row: bool,
pub search_markers_b... | Rust | 0 |
const NETCON_MAX_NAME_LEN: u32 = 256u32;
#[doc = "*Required features: `\"Win32_NetworkManagement_WindowsFirewall\"`*"]
pub type NETCON_MEDIATYPE = i32;
#[doc = "*Required features: `\"Win32_NetworkManagement_WindowsFirewall\"`*"]
pub const NCM_NONE: NETCON_MEDIATYPE = 0i32;
#[doc = "*Required features: `\"Win32_Network... | Rust | 0 |
Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct NodeHealthEvaluation {
#[serde(flatten)]
pub health_evaluation: HealthEvaluation,
#[serde(rename = "NodeName", default, skip_serializing_if = "Option::is_none")]
pub node_name: Option<NodeName>,
#[serde(rename = "UnhealthyEvaluations", def... | Rust | 0 |
from contextlib import asynccontextmanager
from fastapi import FastAPI
from fastapi.responses import JSONResponse
from app.layer_0_db_definition.database_ponyorm import init_pony
from app.layer_0_db_definition.database_sqlalchemy import init_sqlalchemy
from app.layer_3_api.products import router as products_router
fr... | Python | 1 |
if start and end:
text = self._escape_chars(line.rstrip('\n'))
if text != '':
outfile.write(''.join((start, text, end)))
else:
outfile.write(self._escape_chars(line.rstrip('\n')))
if line.endsw... | Python | 1 |
import matplotlib.pyplot as plt
import numpy as np
# 数据准备
matrix_sizes = [31, 32, 33, 63, 64, 65, 95, 96, 97, 127, 128, 129, 159, 160, 161,
191, 192, 193, 223, 224, 225, 255, 256, 257, 287, 288, 289, 319,
320, 321, 384, 392, 452, 472, 496, 511, 512, 513, 528, 575, 576,
... | Python | 1 |
&mut self) -> _USART1ENW {
_USART1ENW { w: self }
}
#[doc = "Bit 16 - TIM15 timer clock enable"]
#[inline(always)]
pub fn tim15en(&mut self) -> _TIM15ENW {
_TIM15ENW { w: self }
}
#[doc = "Bit 17 - TIM16 timer clock enable"]
#[inline(always)]
pub fn tim16en(&mut self) -> ... | Rust | 0 |
class Book:
def __init__(self, content: str):
self.content = content
class Formatter:
def format(self, book: Book) -> str:
return book.content
class Printer:
def get_book(self, book: Book):
formatter = Formatter()
formatted_book = formatter.format(book)
return for... | Python | 1 |
header
0x01, 0x00, 0x00, 0x00, // "wallcreeper" ID
0x77, 0x61, 0x6c, 0x6c, 0x63, 0x72, 0x65, 0x65, // "wallcree"
0x70, 0x65, 0x72, 0x00, // "per"
0x02, 0x00, 0x00, 0x00, // "wagtail" ID
0x77, 0x61, 0x67, 0x74, 0x61, 0x69, 0x6c, 0x00, // "w... | Rust | 0 |
+ 10, 30), cv2.FONT_HERSHEY_SIMPLEX, 1, (0, 255, 0), 2)
# Write frame
out.write(combined_frame)
# Release resources
cap_original.release()
cap_detection.release()
out.release()
print(f"Comparison video saved to {output_path}")
def visualize_occlusion_recovery(bef... | Python | 1 |
opcode: Option<u8>,
pub opcode_ext: Option<u8>,
pub has_mod_rm: bool,
pub fixed_mod_rm_mod: Option<u8>,
pub fixed_mod_rm_reg: Option<u8>,
pub allow_mask: bool,
pub allow_merge_mode: bool,
pub allow_rounding: bool,
pub allow_sae: bool,
pub operands: [Option<OperandDefinition>; 4... | Rust | 0 |
import json
from hashlib import sha256
from pathlib import Path
from typing import List, Sequence
import pytest
import pytest_asyncio
from message_test_helpers import make_validated_message_from_dict
from aleph.db.models import MessageDb
from aleph.types.db_session import DbSessionFactory
@pytest_asyncio.fixture
as... | Python | 1 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.