text string | label_name string | labels int64 |
|---|---|---|
# use the last column in predict proba
predicted_class = args.model.predict_proba(_row).columns[-1]
state.positive_class = predicted_class
ag_wrapper = _ShapAutoGluonWrapper(args.model, args.train_data.columns, predicted_class)
explainer = shap.KernelExplai... | Python | 1 |
match fs::create_dir_all("assets/temp_text") {
Ok(f) => f,
Err(e) => println!("Error: {}.", e),
};
enc_payload(&"assets/cover_audio.wav".to_string(),
&"assets/temp_text/stego_audio.wav".to_string(),
&"assets/secret_text.txt".to_st... | Rust | 0 |
ca<\x22:\xcf\xd9\
\x09\x82\x15B\x12\xb2\x8f\x08\x8e\xb3\xf6B\x92\x91\x95{\
\xf4\xec\xf1\xf2\x88\xd7\x0aO\x05}\x1e\xd1\x0c\x10\x91\x08\
\xca<\x22=?dK\xd2@\x12\xaa\xd6\x0e\xfc\xec\xe8\
\x11\x0d\x13\x14\x8f\x92\x9f<\xfb#\xa6O\xd2*f8\
\x8b\x9b\xd74\xe5\xdez\xddB\x92\xd5\x06Vm\xb9\x19\
\xa5JwCU-\xea\x96\x14\x94\xa9$nw\x05\x... | Python | 1 |
= self.buttons_down.insert(btn);
if was_up {
self.buttons_pressed.insert(btn);
}
was_up
}
pub(crate) fn set_button_up(&mut self, btn: GamepadButton) -> bool {
let was_down = self.buttons_down.remove(&btn);
if was_down {
self.buttons_released.i... | Rust | 0 |
#[inline(always)]
pub fn dirset8(&mut self) -> DIRSET8_W {
DIRSET8_W { w: self }
}
#[doc = "Bit 9 - Port Data Direction Set 9"]
#[inline(always)]
pub fn dirset9(&mut self) -> DIRSET9_W {
DIRSET9_W { w: self }
}
#[doc = "Bit 10 - Port Data Direction Set 10"]
#[inline(alw... | Rust | 0 |
from neonodal.neonodal import Neonodal
initial_nodes = ['A', 'B', 'C']
initial_edges = [('A', 'B'), ('B', 'C'), ('C', 'A'), ('A', 'A'), ('A', 'A'), ('B', 'A')]
graph = Neonodal.Graph(directed = False, nodes = initial_nodes, edges = initial_edges)
for n in graph:
print(n)
### iterate over the graphs nodes
#tree... | Python | 1 |
bots_self_prompts = [
"complain about something you hate about programming.",
"Give us a rude opinion on Python or JavaScript.",
"Roast the concept of clean code.",
"Say something deeply offensive to IDE fanatics.",
"Make up a fake tech headline and complain about it.",
"Rant about the best way ... | Python | 1 |
# Copyright 2017 - 2023 Avram Lubkin, All Rights Reserved
# 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/.
"""
Progress bar example that uses floats for count and total... | Python | 1 |
BlindBoxIsEnded,
BlindBoxIsNotEnded,
BlindBoxNotEnough,
BlindBoxOnlyOwerBuy,
}
}
decl_module! {
pub struct Module<T: Config> for enum Call where origin: T::Origin {
// Errors must be initialized if they are used by the pallet.
type Error = Error<T>;
/// The NFT's mo... | Rust | 0 |
Name};
use std::str::FromStr;
use crate::model::{
attribute::{Attribute, Attributes},
clan::Clan,
class::{Classes, ClassInfo, ClassType},
gender::Gender,
race::Race,
server::Server,
util::load_url
};
/// Represents ways in which a search over the HTML data might go wrong.
#[derive(Fail,... | Rust | 0 |
line, dsname=surf_name, method='shaded', cmap = cm.solid_cmaps[surf_count % len(cm.solid_cmaps)])
visFr.add_layer(layer)
mt._invalidate_parent = True
print('Isosurface layer added')
def Plug(visFr):
visFr.AddMenuItem('View', 'Add Octree Layer', lambda e : add_octree_layer(visFr))
visFr... | Python | 1 |
ault {
pub fn get_dai_value(&self, price: Uint) -> Result<Uint, Box<dyn Error>> {
let dai_col = price * self.collateral / Uint::exp10(self.token.decimals);
Ok(dai_col - self.debt)
}
pub fn get_col_value(&self, price: Uint) -> Result<Uint, Box<dyn Error>> {
let dai_value = self.get_da... | Rust | 0 |
unk, if_exists="overwrite")
# Test insert with auto embedding
chunk = tbl.insert(Chunk(id=1, text="foo", user_id=1))
assert len(chunk.text_vec) == text_embed.dimensions
# Test dict insert with auto embedding
chunk = tbl.insert({"id": 2, "text": "bar", "user_id": 1})
assert len(chunk.text_vec) ... | Python | 1 |
t1 (I t2 t3)) t3))))"#);
// (?) = (\P:A->bool. P ((@) P))
self.parse_thm(Thm, "EXISTS_THM", c::EXISTS_THM,
&[a_ty, bool_ty, "F z1 z2"], &["V \"P\" z3"],
"E (K \"?\" z1) (L t1 (A t1 (A (K \"@\" z1) t1)))");
// (?!) = (\P. ?t. P t /\ (!x. P x ==> x = t))
self.parse_thm(Thm, "EXISTS_UNIQUE_DEF... | Rust | 0 |
Response>::meta(),
deprecated: #deprecated,
security: ::std::vec![],
operation_id: #operation_id,
}
}
},
)
.is_some()
{
return Err(Error::new(method.span(), "duplicate meth... | Rust | 0 |
en", 144), 512)
cfg_best["logdir"] = Path("logs_rerun_best") / dt.datetime.now().strftime("%Y%m%d-%H%M%S")
cfg_best["logdir"].mkdir(parents=True, exist_ok=True)
best_uar, extra = train_run(cfg_best)
print(f"\n✅ Повторный запуск завершён: UAR={best_uar:.4f}")
for k, v in extra.items():
pri... | Python | 1 |
ptr, len as usize)
}
pub fn get_width(&self) -> i32 {
unsafe { ffi::gdk_pixbuf_get_width(self.to_glib_none().0) }
}
pub fn get_height(&self) -> i32 {
unsafe { ffi::gdk_pixbuf_get_height(self.to_glib_none().0) }
}
pub fn get_rowstride(&self) -> i32 {
unsafe { ffi::gdk_p... | Rust | 0 |
world_transform),
)
.set_bool(&self.shader.use_skeletal_animation, batch.is_skinned)
.set_color(&self.shader.color, &instance.color)
.set_matrix4_array(
&se... | Rust | 0 |
make sure the reader is closed before moving any file
let digest = calculate_digest(&file_path)?;
let name = format!("{}.{}", assemble_name(file_stem, &meta, conf), file_ext);
let paths = if tags.is_empty() {
vec![conf
.variables()
.document_location()
.join(&na... | Rust | 0 |
class Solution:
def fractionToDecimal(self, numerator: int, denominator: int) -> str:
if numerator % denominator == 0:
return str(numerator // denominator)
negative = (numerator < 0) ^ (denominator < 0)
numerator, denominator = abs(numerator), abs(denominator)
integer_p... | Python | 1 |
1z_zmm_zmmm512
0x4434_0068,// EVEX_Vp2intersectd_kp1_xmm_xmmm128b32
0x4534_0068,// EVEX_Vp2intersectd_kp1_ymm_ymmm256b32
0x4634_0068,// EVEX_Vp2intersectd_kp1_zmm_zmmm512b32
0x4474_0068,// EVEX_Vp2intersectq_kp1_xmm_xmmm128b64
0x4574_0068,// EVEX_Vp2intersectq_kp1_ymm_ymmm256b64
0x4674_0068,// EVEX_Vp2intersectq_... | Rust | 0 |
# Generated by Django 5.2.3 on 2025-07-11 14:05
import django.db.models.deletion
from django.conf import settings
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('users', '0017_remove_user_profile_last_seen_and_more'),
migrations.swappable_depend... | Python | 1 |
x = 0
while x <= 5:
x=x+1
if x == 4:
continue
print(x) | Python | 1 |
TRANSACTION_PARSING_PROMPT = """
Ты — умный ассистент по ведению личных финансов. Пользователь написал:
"{text}"
Твоя задача — **проанализировать** сообщение и вернуть следующую информацию в **строго формате JSON**:
- "type": тип транзакции — допустимо только "income" (доход) или "expense" (расход)
- "category": кате... | Python | 1 |
from .regex import *
from . import regex
__all__ = regex.__all__
| Python | 1 |
items():
if device in v:
return k
# for v in Supported_But_Unknown:
# if device in v:
# return True
return False
def get_download_link(version, ipex_version="2.1.10+xpu"):
if ipex_version not in AOT_link_fmt:
return None
return AOT_link_fmt[ipex_version]... | Python | 1 |
#!/usr/bin/env python3
import rclpy
from rclpy.node import Node
from ackermann_msgs.msg import AckermannDriveStamped
from sensor_msgs.msg import LaserScan
import numpy as np
class Drive(Node):
def __init__(self):
super().__init__("publisher_node")
self.publisher_=self.create_publisher(AckermannDriv... | Python | 1 |
outputs = tf.reshape(
inputs, shape=[batch_size * max_time, np.prod(inputs.shape.as_list()[-3:])])
for i in range(1, 3, 1):
with tf.variable_scope('fc%d' % (i)) as scope:
outputs = tf.contrib.layers.fully_connected(
inputs=outputs,
... | Python | 1 |
= "type")]
pub kind: String,
pub timestamp: DateTime<Utc>,
#[serde(skip_serializing_if = "Option::is_none")]
pub tech_info: Option<String>,
}
/// Sent by the CSMS to the Charging Station to confirm the receipt of a SecurityEventNotificationRequest message. No fields are defined.
#[derive(serde::Seriali... | Rust | 0 |
��에 담아 사용할 수 있다.
// let cs = calc_something(val);
// 클로저는 fn , 타입명시등의 어노테이션이 없이 간략하다.
// 클로저를 정의하고 변수에 저장, 클로저 정의형식은 다음과 같다.
// |클로저파라미터1, 클로저파라미터2 ... | { 클로저 내용 }
// 타입추론이 가능하면 파라티머 타입을 명시하지 않아도 된다.
// 클로저 내용이 하나의 표현식이면 {}가 없어도 된다.
let cs_closure = |num| num;
println!("{}", cs_closure... | Rust | 0 |
# text details: https://wiki.cloudmodding.com/oot/Text_Format
from .HintList import misc_item_hint_table, misc_location_hint_table
from .TextBox import line_wrap
from .Utils import find_last
TEXT_START = 0x92D000
ENG_TEXT_SIZE_LIMIT = 0x39000
JPN_TEXT_SIZE_LIMIT = 0x3A150
JPN_TABLE_START = 0xB808AC
ENG_TABLE_START =... | Python | 1 |
<u64>) -> bool {
forall(|i: nat, j: nat| i < j && j < seq.len() >>= seq.index(i) <= seq.index(j))
}
fn is_seq_sorted(vec: Vec<u64>) -> bool {
ensures(|ret: bool| ret == is_sorted(vec.view()));
if vec.len() < 2 {
return true;
}
... | Rust | 0 |
;
Self::from_i(i)
}
}
struct TriPiece {
triangle: Triangle3D,
// Segments
// s0: Segment3D,
// s1: Segment3D,
// s2: Segment3D,
// Neighbours
n0: Option<usize>,
n1: Option<usize>,
n2: Option<usize>,
// Constraints
c0: bool,
c1: bool,
c2: bool,
// ... | Rust | 0 |
ocessed_outputs, output_dict
def run(self, data: np.ndarray) -> Dict[str, Any]:
"""Run the full inference pipeline."""
# Preprocess data
raw_signal, spectrogram = self.preprocess(data)
# Run inference
outputs = self.predict(raw_signal, spectrogram)
... | Python | 1 |
00000000,
TZC_REGION_TOP_LOW2: 0x00000FFF,
TZC_REGION_TOP_HIGH2: 0x00000000,
TZC_REGION_ID_ACCESS2: 0x00000000,
TZC_REGION_BASE_LOW3: 0x00000000,
TZC_REGION_BASE_HIGH3: 0x00000000,
TZC_REGION_TOP_LOW3: 0x00000FFF,
TZC_REGION_TOP_HIGH3: 0x00000000,
TZC_REGI... | Rust | 0 |
ct of '\$MaxMachineNumber' and '\$MinMachineNumber' is a constant:
>> $MaxMachineNumber * $MinMachineNumber
= 4.
"""
name = "$MaxMachineNumber"
summary_text = "largest normalized positive machine number"
def evaluate(self, evaluation: Evaluation) -> MachineReal:
return NUMERICAL_CON... | Python | 1 |
let mut rvec = poly_eval(&poly_r, x); // [R] = [PR_0] + x*[PR_1]
let t_hat = dot_prod(&lvec, &rvec); // t_hat = [L].[R]
let tau_x = gamma * zsq + tau1 * x + tau2 * x * x; // tau_x = gamma * z^2 + tau_1 * x + tau_2 * x^2
let mu = alpha + rho * x;
(
BulletProof {
vcmt: Point::co... | Rust | 0 |
as_pair().as_span().end()).max().unwrap(),
line: None,
}
}
}
macro_rules! match_nodes_any {
($nodes:expr; $($f:ident($v:ident) => $e:expr),*) => (
for node in $nodes {
match node.as_rule() {
$(
Rule::$f => {
let... | Rust | 0 |
f conn.destroyed() {
log::debug!("connection:{} removed from list", index);
self.conns.remove(&index);
}
} else {
log::error!("tcp connection:{} not found, check deregister", index)
}
}
pub fn check_timeout(&mut self, poll: &Poll, now: Ins... | Rust | 0 |
import pytest
# workaround for https://github.com/kevin1024/vcrpy/issues/844
@pytest.fixture
def fix_patch_vcr():
import vcr.stubs.httpx_stubs
from vcr.request import Request as VcrRequest
def _make_vcr_request(httpx_request, **kwargs):
body_bytes = httpx_request.read()
try:
b... | Python | 1 |
Formwin2)
self.pushButton_fun11.setGeometry(QtCore.QRect(350, 290, 101, 31))
self.pushButton_fun11.setObjectName("pushButton_fun11")
self.retranslateUi(Formwin2)
QtCore.QMetaObject.connectSlotsByName(Formwin2)
def retranslateUi(self, Formwin2):
_translate = QtCore.QCoreAppl... | Python | 1 |
.unwrap_or_else(|| field.len()),
);
self.s = if !rest.is_empty() { Some(rest) } else { None };
Some((prefix, field))
}
}
fn remove_suffix(i: f64, s: Option<Suffix>, u: &Unit) -> Result<f64> {
match (s, u) {
(None, _) => Ok(i),
(Some((raw_suffix, false)), &Unit::Au... | Rust | 0 |
dvalue(ptr);
if parent.__bindgen_anon_1.bits.gc() == 3 && (ptr.__bindgen_anon_1.bits.gc() & 1) == 0 {
jl_gc_queue_root(parent as *const jl_taggedvalue_t as *mut jl_value_t)
}
}
/*
STATIC_INLINE void jl_gc_wb_back(void *ptr) JL_NOTSAFEPOINT // ptr isa jl_value_t*
{
// if ptr is old
if (__unlike... | Rust | 0 |
pache 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 writing, software
// distributed under the License is distribute... | Rust | 0 |
# dataframe containing counts of every word in the emails dataframe
email_count = emails_df["Folder Name"].value_counts()
indices = email_count.index
count = pd.DataFrame(email_count, columns = ["Folder Name"])
count["Folder Names"] = indices
barplot(df = count[:20], X = "Folder Name", Y = "Folder Names", figsiz... | Python | 1 |
import requests
from bs4 import BeautifulSoup
import pandas as pd
import time
from tqdm import tqdm
# 会议列表及对应DBLP缩写
CONFERENCES = {
'ICML': 'icml',
'AAAI': 'aaai',
'IJCAI': 'ijcai',
'CVPR': 'cvpr'
}
# 爬取年份范围
START_YEAR = 2020
END_YEAR = 2025
# 存储所有论文数据
all_papers = []
headers = {
'User-Agent': '... | Python | 1 |
import asyncio
from chater import Chater
from platforms import Platform
from config import BaseConfig
async def main():
# 创建聊天客户端
chater = Chater.create(
platform=Platform.OLLAMA, config=BaseConfig(model="qwen2.5:1.5b")
)
print(chater.get_current_session())
print(chater.db_manager.get_se... | Python | 1 |
ch.device("cuda")
logger.info(f"Device: {device}")
# We apply CTC and pre-training collators on both domains
# since we are using both domains for training
train_loader = make_dataloader(train_sampler,mixed_collator,train_dataset,args)
student_optim = AdamW(params=student.parameters(),lr=3e-4)
... | Python | 1 |
r y in x["context"]}
if "hosts" in x:
x["hosts"] = self._host_list_to_dict(x)
pkey = {
"communities": "name",
"community_maps": "name",
"interfaces": "name",
"mib_schema": "name",
"groups": "group",
"mib... | Python | 1 |
ally:
# While PEP 517 frontends should be calling each hook in a fresh
# subprocess according to the standard (and thus it should not be
# strictly necessary to restore the old sys.path), we'll restore
# the original path so that the path manipulation does not persist
... | Python | 1 |
import os
# 发送者的基本配置文件
import config
# 导入SMTP协议库
import smtplib
# 邮件正文内容数据处理模块
from email.mime.text import MIMEText
# 邮件头模块
from email.header import Header
"""批量发送邮件应用(简化版)
这里的邮件,只有简单的文本,暂时没有考虑其它图片、附件等情形。
"""
# 读取联系人的邮件列表(excel文件数据请自备,在resources目录下
# 记得留一个表头,函数逻辑是自动跳过表头读取后面的行
# 每个数据的格式:[收件人姓名, 收件人部门, 收件人邮箱]
# 可以根据个人... | Python | 1 |
rfile.open(str(sdist)) as tar:
start = tar.getnames()[0] + "/"
version = start[16:-1]
simpler = set(n.split("/", 1)[-1] for n in tar.getnames()[1:])
with contextlib.closing(
tar.extractfile(tar.getmember(start + "setup.py"))
) as f:
setup_py = f.read()
... | Python | 1 |
},
/// "since": "0x0"
/// }
/// ],
/// "outputs": [
/// {
/// "capacity": "0x2540be400",
/// "lock": {
/// "code_hash": "0x28e83a1277d48add8e72fadaa9248559e1b632bab2bd60b27955ebc4c03800a5",
/// ... | Rust | 0 |
&ValuePack,
) -> Result<Option<$output_type>, DataConvertError> {
match values.get(&self.column_name) {
Some(DatabaseValue::$database_value(value)) => Ok(Some(*value)),
Some(DatabaseValue::Null(DatabaseType::$database_value)) => Ok(None),
... | Rust | 0 |
line).as_ref())?;
}
let hash: BTreeMap<String, String> = conn2.hgetall(&x).unwrap();
let mut values: Vec<String> = Vec::new();
for k in &headers {
let val = hash.get(k).unwrap();
values.push(val.clone());
}
let line = values.join("\t");
wr... | Rust | 0 |
e with step number
prefix = "model" if self._config.model.training_mode == "full" else "lora"
filename = f"{prefix}_weights_step_{self._global_step:05d}.safetensors"
saved_weights_path = save_dir / filename
rel_saved_weights_path = saved_weights_path.relative_to(self._config.output_dir)
... | Python | 1 |
ture = "postgres_backend")]
pub type ContainsJsonb<Lhs, Rhs> =
Grouped<super::operators::ContainsJsonb<Lhs, AsExprOf<Rhs, Jsonb>>>;
/// The return type of [`lsh.is_contained_by(rhs)`](super::expression_methods::PgJsonbExpressionMethods::is_contained_by)
/// for jsonb types
#[cfg(feature = "postgres_backend")]
pub ... | Rust | 0 |
ReadWrite<u32, DAISY_3BIT_SELECT_INPUT::Register>,
flexpwm2_pwmb0_2_select_input: [ReadWrite<u32, DAISY_SELECT_INPUT::Register>; 3],
flexpwm4_pwma0_3_select_input: [ReadWrite<u32, DAISY_SELECT_INPUT::Register>; 4],
flexspi_a_dqs_select_input: ReadWrite<u32, DAISY_SELECT_INPUT::Register>,
flexspi_a_dat... | Rust | 0 |
# prompt模板使用Jinja2语法,简单点就是用双大括号代替f-string的单大括号
# 本配置文件支持热加载,修改prompt模板后无需重启服务。
# LLM对话支持的变量:
# - input: 用户输入内容
# 知识库和搜索引擎对话支持的变量:
# - context: 从检索结果拼接的知识文本
# - question: 用户提出的问题
# Agent对话支持的变量:
# - tools: 可用的工具列表
# - tool_names: 可用的工具名称列表
# - history: 用户和Agent的对话历史
# - input: 用户输入内容
# - agent_scratc... | Python | 1 |
import json
import re
import pandas as pd
import sys
def extract_field_from_testcase(testcase):
regex = r"'field':\s*'(\[.*?\])'"
groups = re.search(regex, testcase)
if groups:
return groups.group(1)
else:
return None
if __name__ == '__main__':
file_name = sys.argv[1]
df = pd.r... | Python | 1 |
(&mut self, props: Self::Properties) -> ShouldRender {
self.props.neq_assign(props)
}
fn view(&self) -> Html {
self.view_schedule_panel(&self.props.schedule)
}
}
impl AvailabilityTable {
fn view_schedule_panel(&self, schedule: &Availability) -> Html {
match schedule {
... | Rust | 0 |
) -> Self {
let bits_per_second = stats.bytes as f64 * 8.0 / period.seconds;
Self {
id: stats.id.0,
start: period.start,
end: period.end,
seconds: period.seconds,
bytes: stats.bytes,
bits_pe... | Rust | 0 |
node.middle = None;
}
let more_pruning = node.value.is_none() && node.left.is_none() && node.middle.is_none() && node.right.is_none();
(more_pruning, old_value)
}
}
}
... | Rust | 0 |
FractionalPart::new().map(Some).and(value(None)))
// ExponentialPart
.or(value(None).and(ExponentialPart::new().map(Some)))
)
.map(|(int_part,(opt_fract_part, opt_exp_part)) : (String, (Option<String>,Option<String>))| {
let mut result = String::new();
result.push_str(&int_part);
... | Rust | 0 |
<size>32</size>
<access>read-write</access>
<resetValue>0x00000000</resetValue>
<resetMask>0x00000023</resetMask>
<fields>
<field>
<name>WREN</name>
<description>Enable Write/Erase ... | Rust | 0 |
"""This is an example workflow for read-mapping using bwa and samtools."""
from gwf import Workflow, AnonymousTarget
gwf = Workflow()
def bwa_index(ref_genome):
"""Template for indexing a genome with `bwa index`."""
inputs = ['{}.fa'.format(ref_genome)]
outputs = ['{}.amb'.format(ref_genome),
... | Python | 1 |
f.training_dataset[self.training_dataset.is_test]
train_data = self.training_dataset[~self.training_dataset.is_test]
scaler = StandardScaler()
pipeline = Pipeline(steps=[("Scaler", scaler), ("Model", model)])
pipeline.fit(train_data[self.features], train_data[[self.label]])
scor... | Python | 1 |
Box::new(Term::FunElim(
Box::new(Term::Var(SpannedString::new(file_id, 0, "Option"))),
vec![Arg::Explicit(Term::Var(SpannedString::new(
file_id, 7, "A",
)))],
)),
Box::new(Term::FunArrowType(
Box::new... | Rust | 0 |
.verify(msg, signature)
.map_err(|_| SignatureVerificationError::CryptoError("EC Signature was wrong".to_string()))
}
<reponame>elmol/examples<filename>archived/multi-service/ethqlite/src/crud.rs
/*
* Copyright 2021 Fluence Labs Limited
*
* Licensed under the Apache License, Version 2.0 (the "License... | Rust | 0 |
郎\">富田健太郎</a></li>\n<li><a href=\"/wiki/%E9%95%B7%E5%B0%BE%E5%8D%93%E4%B9%9F\" title=\"長尾卓也\">長尾卓也</a></li>\n<li><a href=\"/wiki/%E9%87%8E%E6%9D%91%E5%91%A8%E5%B9%B3\" title=\"野村周平\">野村周平</a></li>\n<li><a href=\"/wiki/%E6%A9%8B%E6%9C%AC%E6%B7%B3_(%E4%BF%B3%E5%84%AA)\" title=\"橋本淳 (俳優)\">橋本淳</a></li>\n<li><a href=\"/wik... | Python | 1 |
::Address;
/// use cfd_rust::Network;
/// use cfd_rust::Script;
/// use std::str::FromStr;
/// let script_hex = "522102522952c3fc2a53a8651b08ce10988b7506a3b40a5c26f9648a911be33e73e1a0210340b52ae45bc1be5de083f1730fe537374e219c4836400623741d2a874e60590c21024a3477bc8b933a320eb5667ee72c35a81aa155c8e20cc51c65fb666de... | Rust | 0 |
::TimeChanged => self.event_broadcaster.broadcast_time_changed(),
CallbackReason::TimezoneChanged => self.event_broadcaster.broadcast_timezone_changed(),
CallbackReason::None => error!("unexpected callback reason {:?}", info.reason),
}
}
}
impl From<&EmptyConfig> for SharedObj {
... | Rust | 0 |
ormat like "ta_en"
)
full_text += translation
logger.debug(f"Successfully translated split: {split_file}")
except Exception as e:
logger.error(f"Error during split translation: {e}")
raise ValueError(f"Error... | Python | 1 |
LAYER_SIZE: usize = WIDTH * HEIGHT;
fn part1(image: &str) -> usize {
let img = image.as_bytes();
let zeros = img
.chunks_exact(LAYER_SIZE)
.enumerate()
.map(|(i, layer)| (i, layer.iter().filter(|p| **p == b'0').count()))
.min_by_key(|e| e.1)
.expect("smaller than one la... | Rust | 0 |
TriggerId::STARTUP => write!(f, "startup"),
TriggerId::SHUTDOWN => write!(f, "shutdown"),
TriggerId(id) => write!(f, "{}", id),
}
}
}
<reponame>Fogapod/advent-of-code
use criterion::*;
fn bench(c: &mut Criterion) {
let input = &std::fs::read("../input/d06/full").unwrap... | Rust | 0 |
mg.last_modified.ctime())
print("in local storage: %s" % stored)
# in cache?
(sid, commit) = bu.cache.find_image(img)
if (sid is None):
cached = "no"
else:
cached = "yes (state ID %s, commit %s)" % (sid.short, commit[:7])
if (os.path.exists(img.unpack_path)):
... | Python | 1 |
# _*_ coding:utf-8 _*_
"""
@Version :
1.0.0
@Time :
2024/01/03
@Author :
DuYu (@Duyu09, qluduyu09@163.com)
@File :
text-generation.py
@Describe :
自然语言处理 基于”词袋模型“的文本生成练手代码。Practicing code of text generation based on bag-of-word model of NLP.
@Co... | Python | 1 |
e, warn};
use x86::dtables;
extern "C" {
/// The host entrypoint function.
/// Implemented externally in assembly.
/// Will be called when a VM exit occurs.
/// When a function returns to the host entrypoint, the hypervisor will
/// attempt to resume the guest, or, if resuming the guest fails, it w... | Rust | 0 |
UIStepper")
.blacklist_function("dividerImageForLeftSegmentState_rightSegmentState_")
.blacklist_item("objc_object")
.header_contents("UIKit.h", "#include<UIKit/UIKit.h>");
// Generate the bindings.
let bindings = builder.generate().expect("unable to generate bindings");
// Get the... | Rust | 0 |
"""
self.ensure_started()
return self.do_evaluate_future(
expr, result_update_callback=self.CALLBACK_GET, **kwargs
)
def evaluate_wxf_future(self, expr, **kwargs):
"""Evaluate an expression and return a future object.
The future object result is the WXF ... | Python | 1 |
# Mean-variance-standard-deviation-calculator
import numpy as np
def calculate(input_list):
# Check if input list has exactly 9 elements
if len(input_list) != 9:
raise ValueError("List must contain nine numbers.")
# Convert the input list to a 3x3 NumPy array
matrix = np.array(input_list).... | Python | 1 |
| raw_words | target | words | seq_len |
+-------------+-----------+--------+-------+---------+
| is_input | False | True | True | True |
| is_target | False | True | False | True |
| ignore_type | | False | False | False |
| pad_value | ... | Python | 1 |
cfg(all(not(feature = "alloc"), feature = "std"))]
use std::vec::Vec;
use amacs;
pub use amacs::PublicKey as IssuerParameters;
pub use amacs::SecretKey as IssuerSecretKey;
use curve25519_dalek::ristretto::RistrettoPoint;
use curve25519_dalek::scalar::Scalar;
use merlin::Transcript;
use rand_core::RngCore;
use rand_... | Rust | 0 |
t1 = time.time()
else:
index_refine.k_factor = pre_reorder_k / k
t0 = time.time()
D, I = index_refine.search(xq, k)
t1 = time.time()
times.append(t1 - t0)
header = "Faiss npro... | Python | 1 |
st", struct_info=TensorStructInfo([batch_size, n], dtype))
with bb.function("gather_hidden_states", [src, indices, dst]):
with bb.dataflow():
if tensor_parallel_shards > 1:
indices = relax.op.ccl.broadcast_from_worker0(indices)
output = bb.emit_output(
... | Python | 1 |
5);
/// ```
pub fn log2(x: u32) -> u32 {
// FIXME after leading_trailing_ones get stablized
// let msb = std::mem::size_of::<NodeSize>() as u32 * 8 - x.leading_zeros();
// msb.saturating_sub(1)
if x == 0 {
return 0;
}
let mut k = 0;
while (x >> k) > 0 {
k += 1
}
k - ... | Rust | 0 |
owned(),"flight".to_owned()));
println!("{}",result);
}
<reponame>qbox/rust-sdk
use crate::{
config::qiniu_ng_config_t,
result::qiniu_ng_err_t,
string::{qiniu_ng_char_t, ucstr},
utils::{qiniu_ng_str_list_t, qiniu_ng_str_t},
};
use libc::{c_void, size_t};
use qiniu_ng::{
storage::uploader::{Uploa... | Rust | 0 |
e))
if xf_in is None:
xf_in = obj_bbox_embedding
else:
xf_in = xf_in + obj_bbox_embedding
outputs['obj_bbox_embedding'] = obj_bbox_embedding.permute(0, 2, 1)
for resolution in self.resolution_to_attention:
outputs['image_pat... | Python | 1 |
ool),
}
#[derive(Serialize, Deserialize, Debug, Clone)]
pub struct GatewayConfig {
pub apps: Vec<ClientInfo>,
pub services: Vec<ServiceInfo>,
}
#[derive(Serialize, Deserialize, Debug, Clone, PartialEq)]
pub struct ClientInfo {
pub client_id: String,
pub app_key: String,
pub pub_key: String,
... | Rust | 0 |
() <= std::i32::MAX as usize,
"MPI can only index arrays up to size i32::MAX"
);
}
fn check_statuses(requests: &[MPI_Request], statuses: &Option<&mut [MPI_Status]>) {
if let &Some(ref statuses) = statuses {
assert!(
statuses.len() >= requests.len(),
"The statuses array m... | Rust | 0 |
import torch
import os
from torch import optim
import random
import numpy as np
from exp.e import Experiment
from params import parse_args as pa
from exp.make_data import enso_data
from model import model
def set_seed(seed):
# 固定随机种子等操作
seed_n = seed
print('seed is ' + str(seed_n))
g = torch.Generator()... | Python | 1 |
dSpatialTransformer(nn.Module):
"""
Transformer block for image-like data.
First, project the input (aka embedding)
and reshape to b, t, d.
Then apply standard transformer action.
Finally, reshape to image
"""
def __init__(self, in_channels, n_heads, d_head,
depth=1, dro... | Python | 1 |
#import python libraries
import pandas as pd
import random
import csv
#input the number of rows that the csv file should have
num_rows = int(input( " Enter the number of rows that you want to generate in the csv file : "))
#input the name of the csv file (e.g data.csv)
csv_file = input ( " Enter the name of the... | Python | 1 |
if qual.get('qualificationName') == 'A level':
summary = qual.get('summary', {})
a_level_offer = summary.get('offer', '')
a_level_requirement = f"A Level: {a_level_offer}"
if summary.get('requirements'):
a... | Python | 1 |
req = np.linspace(0,sr/2,len(promedio_idft),endpoint = False)
#frecuencias3 = np.linspace(0,sr/2,len(dftprom),endpoint = False)
tiempo = np.linspace(0,len(reconstruida)/sr, len(reconstruida))
plt.figure(figsize = (12,4))
plt.title('Señal reconstruida IDFT')
plt.plot(tiempo,reconstruida)
plt.xlabel('Tiempo (s)')
plt.yl... | Python | 1 |
race!("vmxon succeeded");
Ok(())
}
Err(e) => {
error!("vmxon failed {:x?}", e);
Err(VmxEnablementError::VmxOnFailure)
}
}
}
pub fn disable() {
unimplemented!();
}
extern "C" {
fn _guest_first_entry() -> usize;
}
pub fn load_vm(vcpu: &VCpu) -> Re... | Rust | 0 |
, S: ElementSerializer<V> {
let s = S::serialize_element(v);
let x_p = to_bigint::<T, N>(M::map(&s)).add(&w.nonce);
self.pi_a = self.pi_a.mul(&x_p);
}
/// Absorb an element that must be deleted from a witness.
pub fn del<'a, M, N, S, V>(&mut self, v: &'a V, w: &Witness<T>)
where... | Rust | 0 |
index].copy_from_slice(before_private_key);
bytes[template.private_key_index..private_key_end_index].copy_from_slice(&private_key);
bytes[private_key_end_index..(private_key_end_index + after_private_key.len())]
.copy_from_slice(after_private_key);
bytes[(private_key_end_index + after_private_key.le... | Rust | 0 |
# --- THIS FILE IS AUTO-GENERATED ---
# Modifications will be overwitten the next time code generation run.
from plotly.basedatatypes import BaseTraceHierarchyType as _BaseTraceHierarchyType
import copy as _copy
class Marker(_BaseTraceHierarchyType):
_parent_path_str = "choroplethmap.unselected... | Python | 1 |
device = torch.device('cpu')
# 获取数据转换
train_transform, val_transform = get_transforms(args_obj.dataset)
# 同步所有进程,确保数据加载器创建前所有进程都准备好
if args.distributed:
dist.barrier()
# 获取数据加载器
train_val_loader, val_loader, val_poisoned_loader = get_dataloaders(args_obj, val_transform)... | Python | 1 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.