text string | label_name string | labels int64 |
|---|---|---|
().unwrap();
let x4 = idMgr.AllocId().unwrap();
println!("x1: {}, x2: {}, x3: {}, x4: {}", x1, x2, x3, x4);
idMgr.Remove(x3);
idMgr.Remove(x2);
let x3 = idMgr.AllocId().unwrap();
println!("x1: {}, x2: {}, x3: {}, x4: {}", x1, x2, x3, x4);
idMgr.Remove(x2);
idMgr.Remove(x4);
let x2 = ... | Rust | 0 |
import datetime
from datetimerange import DateTimeRange
from .types import ComparisonDetail, ComparisonResult, MaintenanceSchedule, Status
def compare_server_status(
previous: list[Status],
current: list[Status],
maintenance_schedule: MaintenanceSchedule | None = None,
) -> list[ComparisonResult]:
"""2つのサーバーステー... | Python | 1 |
# Write a dummy program that can perform login and registration using a menu-driven approach.
database = {}
def user_menu():
user_input = input('''
1. Enter 1 to Register
2. Enter 2 to Login
3. Enter 3 to Exit
''')
if user_input == '1':
register()
elif user_input == '2':
... | Python | 1 |
okens) # no labels ==> test mode
# this_err = sum([a!=b for a,b in zip(pred,labels)])
# #this_err2 = task.ref_policy.final_loss()
# #print task.ref_policy.truth, task.ref_policy.prediction
# #assert this_err2 == this_err, 'mismatch %g != %g' % (this_err, this_err2)
# ... | Python | 1 |
s u32) | ((b[1] as u32) << 8) | ((b[2] as u32) << 16) | ((b[3] as u32) << 24),
)
}
pub fn read_fill<R: Read + ?Sized>(r: &mut R, mut slice: &mut [u8]) -> io::Result<()> {
while !slice.is_empty() {
let n = r.read(slice)?;
if n == 0 {
return Err(io::Error::new(io::ErrorKind::Other, "e... | Rust | 0 |
"",
need_config_file: true,
exec_cmd: test_help,
};
let commands = &[one_cmd];
let args = [];
let exit_code = commands[0].exec(&args, io_helper, dck_helper, dl_helper);
assert_eq!(exit_code, CommandExitCode::ConfigFileNotFound);
}
#[test]
fn check_if_need_config_file_and_found(... | Rust | 0 |
import numpy as np
import cv2
def relight_pfc_object(A, I, relit_image, mask, thresholds=[0.1, 0.15]):
"""
Generate relit image using estimated normal map and albedo.
Parameters:
normal_map (numpy.ndarray): Estimated surface normal map (HxWx3)
albedo_map (numpy.ndarray): Estimated albe... | Python | 1 |
eprintln!("Failed to parse filecontent for default location '{}'", e);
process::exit(0);
}
};
}
fn build_file_path() -> String {
let mut current_dir = current_exe().unwrap();
// Remove the actual binary to get the directory
current_dir.pop();
let current_path = cur... | Rust | 0 |
(segmentation_labels[x], 0), reverse=True)
segmentation_labels = {k: segmentation_labels[k] for k in sorted_labels[:self.max_segments] if seg_id2count.get(segmentation_labels[k], 0) >= self.min_seg_area}
instance.update({
'image': torch.from_numpy(tgt_image.astype(np.float32) / 255.0).p... | Python | 1 |
code: usize,
message: String,
}
#[inline]
fn is_number(field_name: &str, field_value: Option<&str>) -> Result<(), CustomError> {
if let Some(field_value) = field_value {
if field_value.parse::<i64>().is_err() {
return Err(CustomError {
status_code: 400,
messa... | Rust | 0 |
,nmol))
quad_mol = calc_quad(crd, dipindperm)
###### Write charges & permanent dipoles ######
wrt_qout()
###### Calculate and print sum-of-squares, rmse, and rrmse ######
wrt_out()
output_file.close()
print("-----------------------------------------------------------------")
print("To cite PyRESP use:")
print()
pr... | Python | 1 |
self.rng.borrow_mut().fill_bytes(&mut bytearray);
let bits = bytes % 8;
if bits > 0 {
bytearray[0] >>= 8 - bits;
}
println!("{:?}", k);
println!("{:?}", bytearray);
let result = BigInt::from_bytes_be(Sign::Plus, &bytearray);
Ok(vm.ctx.new_bi... | Rust | 0 |
s)):
plots_np[i] = np.loadtxt(paths[i] + ".txt")[0]
y_mean = np.mean(plots_np, axis=1)
y_variance = np.var(plots_np, axis=1)
y_err = 1.96 * np.sqrt(y_variance / plots_np.shape[1])
y_mean_lg = np.log10(y_mean)
y_err_lg = np.full((2, len(paths)), 0)
if np.all(y_mean > y_err):
y_er... | Python | 1 |
if not errors:
if self._is_new:
return self.async_create_entry(
title=user_input.pop(CONF_NAME, "Zhipu AI Task"),
data=user_input,
)
return self.async_update_and_ab... | Python | 1 |
num as u64,
};
let pos_end = FilePos {
pos_lnum: end_lnum as u64,
pos_bol: end_bol as u64,
pos_cnum: end_cnum as u64,
};
(pos_file, pos_start, pos_end)
})
}
pub fn mk_pos_of_ref<R: Reason>(&self, pos: &oxidi... | Rust | 0 |
;
use crate::mail::templates::Template;
use crate::rules::engine::CREATE_GROUP;
use crate::rules::engine::HOST_IS_GROUP_ADMIN;
use crate::rules::engine::ONLY_ADMINS;
use crate::rules::RuleContext;
use crate::user::User;
use cis_client::AsyncCisClientTrait;
use diesel::pg::PgConnection;
use dino_park_gate::scope::ScopeA... | Rust | 0 |
RA Register high byte.
pub const OCR0RAH: *mut u8 = 0xD5 as *mut u8;
/// Output Compare SB Register.
pub const OCR0SB: *mut u16 = 0xD6 as *mut u16;
/// Output Compare SB Register low byte.
pub const OCR0SBL: *mut u8 = 0xD6 as *mut u8;
/// Output Compare SB Register high byte.
pub const OCR0SBH: *mut u8 = 0xD7 as... | Rust | 0 |
import sys
if len(sys.argv) < 2:
print('usage: gensimilar.py num', file=sys.stderr)
sys.exit(1)
for i in range(int(sys.argv[1])):
print('word{}'.format(i+1))
| Python | 1 |
import torch
import torch_xla
import torch_xla.core.xla_model as xm
import torch_xla.debug.metrics as met
import torch_xla.debug.metrics_compare_utils as mcu
from absl.testing import absltest
from torch_xla import runtime as xr
EXPECTED_COMPUTATION_CLIENT_METRICS = [
"CompileTime",
"CreateCompileHandles",
... | Python | 1 |
p(expr_values[i], expr_values[j]))
def test_quicksum():
N = 6
vars = [VariableIndex(i) for i in range(N)]
var_value_map = {v.index: float(v.index) for v in vars}
vars_dict = {i: v for i, v in enumerate(vars)}
expr = ExprBuilder()
for v in vars:
expr += v
expr_sum = quicksum(vars_d... | Python | 1 |
import calendar
year = int(input('Введите год: '))
month = int(input('Введите месяц: '))
print(calendar.month(year, month))
| Python | 1 |
# Copyright 2019 Odoo Community Association
# License AGPL-3.0 or later (https://www.gnu.org/licenses/agpl).
from odoo import fields, models
class MgmtSystemManual(models.Model):
_inherit = "mgmtsystem.system"
manual_id = fields.Many2one("document.page", string="Manual")
| Python | 1 |
default()
})]
#[test]
fn test_average_add_s(x in u64::MIN..=u64::MAX, y in u64::MIN..=u64::MAX) {
let r0 = Eint::average_add_s(E64::from(x), E64::from(y));
let r1 = Eint::average_add_s(T64::recv(x), T64::recv(y));
assert_eq!(r0, r1.into());
assert_eq!(r0, E64((((x as i64 as ... | Rust | 0 |
"""
metric_markers.py
Utility for putting star and triangle markers onto 1-D curves.
Two use-cases
-------------
1. Left-column theory curves: always put both markers at their kappa targets.
2. Right-hand experimental splitting curves: put a single marker only if the
curve endpoint matches the kappa target (within ... | Python | 1 |
# Copyright 2015 igallyamov <https://github.com/igallyamov>
# Copyright 2016 ufaks <https://github.com/ufaks>
# Copyright 2016-2018 Ivan Yelizariev <https://it-projects.info/team/yelizariev>
# Copyright 2018 Ruslan Ronzhin <https://it-projects.info/team/rusllan>
# Copyright 2019 Kolushov Alexandr <https://it-projects.i... | Python | 1 |
Some(lock) => lock.read().say(ctx, to_post)?,
None => {
error!("Could not retrieve the channel by id {}", state.channel_id);
message.reply(ctx, "The channel reference could not be retrieved")?;
return Ok(());
}
},
_ => ... | Rust | 0 |
io::BufReader::new(fs::File::open(dep).unwrap());
for d in deps.lines() { println!("cargo:rerun-if-changed={}", d.unwrap()); }
}
let mut c = gcc::Config::new();
for o in &objects { c.object(&*o); }
c.compile(output);
let superheader =
dst.join(outbase)
.with_extension("h");
... | Rust | 0 |
else:
# 히트맵 데이터가 없는 경우 메시지
no_data_text = status_font.render("히트맵 데이터가 없습니다.", True, BLACK)
screen.blit(no_data_text, (content_rect.centerx - no_data_text.get_width()//2,
content_rect.centery - no_data_text.get_height()//2))
... | Python | 1 |
# Catch exception when operation doesn't finish before timeout
except (RetryError, InternalServerError) as e:
print(e.message)
# NOTE: Can also use callbacks for asynchronous processing
#
# def my_callback(future):
# result = future.result()
#
# operation.add_done_callback(my... | Python | 1 |
let mut last = E::ONE;
for (result, &value) in result.iter_mut().zip(values.iter()) {
*result = last;
if value != E::ZERO {
last *= value;
}
}
last = last.inv();
for i in (0..values.len()).rev() {
if values[i] == E::ZERO {
result[i] = E::ZERO;
... | Rust | 0 |
vec![0; 4].into_boxed_slice(),
cpos: 0,
clen: 8,
upos: 0,
ulen: 4,
};
assert!(!block.is_eof());
block.set_upos(4);
assert!(block.is_eof());
}
}
use bevy::
{input::{Input, keyboard::KeyboardInput, mouse::{MouseMotion, MouseWheel}}, m... | Rust | 0 |
fo_text)
for i in range(num_data):
scenario_text = scenario_info_text[i]
scene_descriptions = scenario_text.split("\n")[1].split("Scene: ")[1]
instruction = scenario_text.split("\n")[2].split("Task: ")[1]
new_prompt = scenario_test_prompt.format(scene_descriptions, instruction).stri... | Python | 1 |
nnel(&self, channel_id: &ChannelId) -> Result<Channel, Error> {
let res = self
.http
.get(&format!("{}/channels/{}", Self::ENDPOINT, channel_id))
.set("x-apikey", &self.token)
.call()
.map_err(|e| Error::ApiRequestFailed {
endpoint: "/c... | Rust | 0 |
range=[0, 2200]),
aspectmode='manual', aspectratio=dict(x=5, y=2, z=0.8)
),
updatemenus=[{'type': 'buttons','buttons': [
{'label': '播放', 'method': 'animate', 'args': [None, {'frame': {'duration': 1000*TIME_STEP, 'redraw': True}, 'transition': {'duration': 0}, 'fromcurrent': ... | Python | 1 |
#!/usr/bin/env python
import rospy
from std_msgs.msg import String
import sys
def publish_once(mode):
# Initialize the ROS node
rospy.init_node('mode_publisher_node', anonymous=True)
# Create a publisher for the /robot_2/gait topic with std_msgs/String type
pub = rospy.Publisher('mode', String, queue_... | Python | 1 |
"0x3c00c - USB Configuration Register"]
pub gusbcfg: GUSBCFG,
#[doc = "0x3c010 - Reset Register"]
pub grstctl: GRSTCTL,
#[doc = "0x3c014 - Interrupt Register"]
pub gintsts: GINTSTS,
#[doc = "0x3c018 - Interrupt Mask Register"]
pub gintmsk: GINTMSK,
#[doc = "0x3c01c - Receive Status Debug... | Rust | 0 |
global_opts(
legend_opts=opts.LegendOpts(is_show=False),
xaxis_opts=opts.AxisOpts(
type_="category",
splitarea_opts=opts.SplitAreaOpts(
is_show=True, areastyle_opts=opts.AreaStyleOpts(opacity=1)
),
),
yaxis_opts=opts.AxisOpts(
... | Python | 1 |
for i, img_data in enumerate(self._data):
if isinstance(img_data, np.ndarray):
image = self.get_image(i)
pil_images.append(image)
else:
pil_images.append(img_data)
result = np.empty(len(self), dtype=object)
result[:] = pil_images... | Python | 1 |
ot gol_marcado:
bolas.remove(bola)
print("chutou pra fora")
whistle_sound.play()
else:
for adversario in adversarios[:]:
if bola.checar_se_bateu(bola_rect, adversario.rect):
... | Python | 1 |
from odoo import models, api
class PosConfig(models.Model):
_inherit = 'pos.config'
@api.model
def _load_pos_data_read(self, records, config):
data = super()._load_pos_data_read(records, config)
if data:
l10n_pe_edi_refund_reason = self.env['ir.model.fields']._get('account.mov... | Python | 1 |
screen_num: i32,
format24: u32,
format32: u32,
frame: u32,
black: u32,
meta_mod_mask: xcb::ModMask,
alt_mod_mask: xcb::ModMask,
super_mod_mask: xcb::ModMask,
hyper_mod_mask: xcb::ModMask,
num_lock_mask: xcb::ModMask,
scroll_lock_mask: xcb::ModMask,
keycode_to_keysym: V... | Rust | 0 |
_with_json_data(&block_hash)?.map(|(header, json_data)| map_header_and_json_to_full_block_info(header, json_data, &state));
}
}
Ok(block)
}
/// Get information about block header
pub(crate) fn get_block_header(block_id: &str, persistent_storage: &PersistentStorage, state: &RpcCollectedStateRef) -> Resu... | Rust | 0 |
state = {
"awaiting_followup": False,
"pending_tool": None,
"pending_params": None,
"followup_type": None,
}
def set_followup(tool, params, followup_type="confirm"):
state["awaiting_followup"] = True
state["pending_tool"] = tool
state["pending_params"] = params
state["followup_type"] = ... | Python | 1 |
// write the data
let mut s2 = String::new();
let mut num_decimals = 0;
if r.configs.data_type == DataType::F32 || r.configs.data_type == DataType::F64 {
num_decimals = 3;
}
for row in (0..r.configs.rows).rev() {
for col in 0..r.configs.columns {
let i = row * r.co... | Rust | 0 |
import numpy as np
import scipy.io as spio
from scipy.interpolate import PchipInterpolator
from bisect import bisect
def HSI2RGB(wY,HSI,ydim,xdim,d,threshold):
# wY: wavelengths in nm
# Y : HSI as a (#pixels x #bands) matrix,
# dims: x & y dimension of image
# d: 50, 55, 65, 75, determines the illuminant used, if in d... | Python | 1 |
opInfo {
#[allow(dead_code)]
pub fn new(__js: &json::JsonValue) -> Result<BonusDropInfo, LoadError> {
let __b = BonusDropInfo {
id: match __js["id"].as_i32() { Some(__x__) => __x__, None => return Err(LoadError{}) },
desc: match __js["desc"].as_str() { Some(__x__) => __x__.to_str... | Rust | 0 |
60),
(6829, 6840), (7022, 7030), (7120, 7410), (7495, 7632), (7686, 7698),
(7698, 7790), (16525, 16530), (23767, 23846), (23651, 23656),
(23750, 23766), (7189, 7672), (6186, 6650), (7622, 7624),
]; // 2996 entries
#[cfg(feature = "no-optimized-legacy-encoding")]
const BACKWARD_SEARCH_UPPER: &'static [u16] ... | Rust | 0 |
tokenized_input = tokenizer([sequence], return_tensors="pt", add_special_tokens=False)['input_ids'].cuda()
with torch.no_grad():
output = model(tokenized_input)
except Exception as e:
print(e)
print(f"Failed to predict {name}")
... | Python | 1 |
);
if result != pkcs11_sys::CKR_OK {
return Some(Err(FindObjectsError::FindObjectsFailed(
format!("C_FindObjects failed with {}", result).into(),
)));
}
match num_objects {
0 => None,
1 if object_hand... | Rust | 0 |
ol: Whether tool selection is justified by reasoning
"""
# Extract tool justification from thought content
tool_mentions = []
for tool in selected_tools:
# Look for explicit reasoning about tool selection
if tool.lower() in thought_content.lower():
... | Python | 1 |
_volume(CreateVolumeOptions {
name: volume_name,
driver: "local",
..Default::default()
})
.await
}
pub async fn remove_volume(
client: &Docker,
volume_name: &str,
) -> Result<(), bollard::errors::Error> {
client
.remove_volume(volume_name, None::<... | Rust | 0 |
types which can be used
/// to access them.
///
/// # Example
/// ```
/// let dp = atmega_hal::Peripherals::take().unwrap();
/// let mut adc = atmega_hal::Adc::new(dp.ADC, Default::default());
///
/// let value = adc.read_blocking(&channel::Vbg);
/// ```
pub mod channel {
#[cfg(all(
any(
featur... | Rust | 0 |
(e1);
explosions.push(*e2);
continue;
}
// if we are already attracting a pixie, and our lead pixie is
// dissimilar, then we can just carry on.
if attractors.contains(&e1) && flavor.color != p1.flavor.color {
continue;
... | Rust | 0 |
---------------
DATABASES = {
'default': dj_database_url.config(
default=os.getenv('DATABASE_URL'),
conn_max_age=600,
ssl_require=os.getenv('DB_SSL_REQUIRE', 'False').lower() == 'true'
)
}
# -----------------------------------------------------------------------------
# Password validat... | Python | 1 |
"type_id": "MUSICBRAINZ",
"processed_by": [],
"data_dir": self.ensureDir(f"{self.project_dir}/MUSICBRAINZ"),
"data_files": {
"JSON": f"{media_sample["name"]}-musicbrainz.json"
}
}
# Don't re-download data if exists
if ... | Python | 1 |
import os
def find_free_port() -> int:
import socket
from contextlib import closing
with closing(socket.socket(socket.AF_INET, socket.SOCK_STREAM)) as s:
s.bind(('', 0))
s.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
return s.getsockname()[1]
def init_one_chip(process_num)... | Python | 1 |
import re
import json
import requests
from bs4 import BeautifulSoup
from typing import Dict, List, Any
from langchain_core.tools import tool
@tool
def my_current_info() -> Dict[str, Any]:
"""
this tool is used to get your current info.Details like what are u currently doing these days future plans, general fac... | Python | 1 |
stream),
close,
})
}
}
impl Parse for MacroCall {
fn parse(parser: &mut Parser) -> Result<Self, ParseError> {
let attributes = parser.parse()?;
let path = parser.parse()?;
Self::parse_with_meta_path(parser, attributes, path)
}
}
impl Opaque for MacroCall {
f... | Rust | 0 |
default_app_config = 'server.contrib.sites.apps.SitesConfig'
| Python | 1 |
Node::new("http://example.com")?;
/// assert_eq!(vec![Quad::new(ex.clone(), ex.clone(), ex.clone(), None)], results);
/// # Result::Ok(())
/// ```
pub fn load_graph(
&mut self,
reader: impl BufRead,
syntax: GraphSyntax,
to_graph_name: &GraphName,
base_iri: Option<... | Rust | 0 |
ield_index = field_index - 1;
let class_id = ClassId::new_unchecked(class_id);
let field_index = FieldIndex::new_unchecked(field_index);
Some((class_id, field_index))
}
}
// TODO: This only supports ExactMethodIds
#[derive(Clone, Copy)]
#[repr(transparent)]
pub struct JMethodId(*const ())... | Rust | 0 |
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the... | Python | 1 |
ationMode {
#[inline]
fn default() -> CalibrationMode {
CalibrationMode::Unknown
}
}
impl From<i32> for CalibrationMode {
fn from(v: i32) -> CalibrationMode {
match v {
0 => CalibrationMode::BootTareGyroAccel,
1 => CalibrationMode::Temperature,
2 => Ca... | Rust | 0 |
from django.conf.urls import url
from .views import (SubmissaoListView, SubmissaoAprovadoListView , SubmissaoAtencaoListView, SubmissaoCreateView,
SubmissaoUpdateView, SubmissaoAprovadoUpdateView, SubmissaoPendenteUpdateView, SubmissaoDeleteView,
SubmissaoEditalListView)
urlpatterns = [
url(r'edital/list/... | Python | 1 |
elif len(binary_op) == 3:
[op_str, op_pt_func, op_np_func] = binary_op
split_str = "split" if split_input else "shared"
op_str = split_str + "_" + op_str
bm_cls = type("ElementBench_" + op_str, (ElementBench,), {})
bm_cls.op_str = op_str
bm_cls.binary_op_pt_fu... | Python | 1 |
#) {
let invalid: InvalidSession = serde_json::from_str(msg)
.expect("Could not deserialize Discord invalid session message");
if invalid.d {
info!("Dicord session is resumable");
return bot.resume();
} else {
return Err... | Rust | 0 |
[`RocksEngine`](RocksEngine) are used for testing only.
#![feature(min_specialization)]
#![feature(generic_associated_types)]
#[macro_use(fail_point)]
extern crate fail;
#[macro_use]
extern crate tikv_util;
mod btree_engine;
mod cursor;
pub mod metrics;
mod mock_engine;
mod raftstore_impls;
mod rocksdb_engine;
mod ... | Rust | 0 |
&'a T) -> Self {
s.as_ref().to_ustring()
}
}
impl<C: UChar> Index<RangeFull> for UString<C> {
type Output = UStr<C>;
#[inline]
fn index(&self, _index: RangeFull) -> &UStr<C> {
UStr::from_slice(&self.inner)
}
}
impl<C: UChar> Deref for UString<C> {
type Target = UStr<C>;
... | Rust | 0 |
f => Species::Gnome,
};
// All squares we've already reached.
let mut seen = HashSet::new();
// All squares on the current distance frontier.
let mut frontier = Move::neighbours(&mut seen, &grid, target, x, y);
while !frontier.is_empty() {
// println!("Frontie... | Rust | 0 |
##############")
print("############################")
# reorder image
image_tmp = image
print(" Image TMP SHAPE", image_tmp.shape)
image = np.zeros((size_rows, image_size * channels * tiles))
column=0
print("Reordered shape : ", image.shape)
for tile_y in range(tiles):
#print("tile_y = ", tile_y)
#print("###... | Python | 1 |
-0.329_058_294_496_178_439_8_e-3
},
)
.mul_add(
u,
if o0 {
-0.149_256_503_584_062_486_6_e-4
} else if o1 {
0.499_664_528_037_294_586_e-3
} else {
0.969_696_606_878_910_115_7_e-3
},
)
.mul_add(
u,
... | Rust | 0 |
Default)]
pub struct InboundNatRuleFragment {
#[doc = "The transport protocol for the endpoint."]
#[serde(rename = "transportProtocol", default, skip_serializing_if = "Option::is_none")]
pub transport_protocol: Option<inbound_nat_rule_fragment::TransportProtocol>,
#[doc = "The external endpoint port of ... | Rust | 0 |
ight="24" viewBox="0 0 24 24" width="24"><g><path d="M0,0h24v24H0V0z" fill="none"/></g><g><path d="M12,18.5c0.83,0,1.5-0.67,1.5-1.5h-3C10.5,17.83,11.17,18.5,12,18.5z M12,2C6.48,2,2,6.48,2,12s4.48,10,10,10 c5.52,0,10-4.48,10-10S17.52,2,12,2z M12,20c-4.41,0-8-3.59-8-8s3.59-8,8-8c4.41,0,8,3.59,8,8S16.41,20,12,20z M16,11.3... | Rust | 0 |
assert_eq!(db.groups[0].borrow().entries.len(),
num_entries_in_group - 1);
}
//! Types builtin to the 'static reflection' system
//!
//! These are mostly FFI-safe alternatives to the standard library
//! types.
use std::mem::MaybeUninit;
use crate::{StaticReflect, field_offset, TypeInfo};
#[cfg(feat... | Rust | 0 |
"w"), indent=4)
def sensitive_analysis(model, loader, summary_file):
summary = SummaryTool(summary_file)
# for 循环每一个层
print("Sensitive analysis by each layer....")
for i in range(0, len(model.model)):
layer = model.model[i]
# 判断layer是否是量化层
if have_quantizer(layer): # 如果是量化层
... | Python | 1 |
extensions: &mut Extensions,
) -> Result<Response> {
let copied_req = req.try_clone().ok_or_else(|| {
Error::Middleware(anyhow!(
"Request object is not clonable. Are you passing a streaming body?".to_string()
))
})?;
let res = next.run(req, ext... | Rust | 0 |
import chess
from chess_engine.eval.material import score_material
def greedy_bot(board):
best_move = None
best_value = -float('inf')
mover_is_white = board.turn # True if white to move, False if black
for move in board.legal_moves:
board.push(move)
board_value = score_material(board)... | Python | 1 |
_alphabetic() {
let diag = Opath::parse("12.5e+string").unwrap_err();
let err = parse_error_detail(&diag);
match *err {
DiagParseErrorDetail::UnexpectedInput { .. } => {
// assert_eq!(found, &String::from("string"));
}
_ => panic!("Wrong error kind")
}
assert_eq!(d... | Rust | 0 |
from ..base import database
from ..utils import BOT_ID
async def add_generate_status(value: bool) -> None:
await database.add_value(int(BOT_ID), "GENERATE_URL", value)
async def del_generate_status() -> None:
await database.clear_value(int(BOT_ID), "GENERATE_URL")
async def get_generate_status() -> bool:
... | Python | 1 |
(v) = self.owner_id {
os.write_uint64(1, v)?;
}
if let Some(ref v) = self.origin.as_ref() {
os.write_string(2, &v)?;
}
if let Some(ref v) = self.revision.as_ref() {
os.write_string(3, &v)?;
}
os.write_unknown_fields(self.get_unknown_fie... | Rust | 0 |
else:
print("❌ Failed to find Set Coding Rules cell")
# Update download cell with commit SHA
if update_download_cell(notebook, commit_sha, branch_name):
print(f"✅ Updated Download cell to use commit {commit_sha}")
else:
print("❌ Failed to find Download cell")
# Updat... | Python | 1 |
aws_smithy_http::body::SdkBody::from(out))
}
pub fn serialize_operation_crate_operation_describe_ssl_policies(
input: &crate::input::DescribeSslPoliciesInput,
) -> Result<aws_smithy_http::body::SdkBody, aws_smithy_http::operation::SerializationError> {
let mut out = String::new();
#[allow(unused_mut)]
... | Rust | 0 |
= MapBuilder::new();
builder.insert(&Node::KV(vec![1, 2, 3], vec![1])).unwrap();
builder.insert(&Node::Hash([0; HASH_LENGTH])).unwrap();
builder.insert(&Node::KV(vec![1, 2, 4], vec![2])).unwrap();
let map = builder.build();
assert_eq!(map.get(&[1, 2, 3]).unwrap().unwrap(), vec!... | Rust | 0 |
Map;
use parallel_processor::buckets::concurrent::{BucketsThreadBuffer, BucketsThreadDispatcher};
use parallel_processor::buckets::writers::compressed_binary_writer::CompressedBinaryWriter;
use parallel_processor::buckets::writers::lock_free_binary_writer::LockFreeBinaryWriter;
use parallel_processor::buckets::{LockFre... | Rust | 0 |
ec![0, 1, 2, 3, 4, 5, 6, 7]).unwrap();
let slice = matrix.slice(s![1..4; -1, ..]);
let slice_py = slice.to_pyarray(py);
assert_eq!(
slice_py.readonly().as_array(),
array![[6, 7], [4, 5], [2, 3]],
);
pyo3::py_run!(py, slice_py, "assert slice_py.flags['C_CON... | Rust | 0 |
turn True
except Exception as e:
print(f"翻页失败: {e}")
return False
def save_videos_to_csv(videos, filename="bilibili_videos.csv"):
"""将视频列表保存到CSV文件"""
if not videos:
print("没有视频数据可保存")
return
with open(filename, 'w', newline='', encoding='utf-8-sig') as ... | Python | 1 |
}
fn default_instance() -> &'static RawNebulaCertificateDetails {
static instance: ::protobuf::rt::LazyV2<RawNebulaCertificateDetails> = ::protobuf::rt::LazyV2::INIT;
instance.get(RawNebulaCertificateDetails::new)
}
}
impl ::protobuf::Clear for RawNebulaCertificateDetails {
fn clear(&mut ... | Rust | 0 |
import pandas as pd
import networkx as nx
def find_k_cores(graph, gdf_nodes, gdf_edges, mapping_nodes, k_value):
k_core_values = nx.k_core(nx.Graph(graph), k=k_value)
core_k_field = "core_"+str(k_value)
k_core_ids = [mapping_nodes['map_coords'][x][0] for x in list(k_core_values)]
gdf_nodes[core_k_fie... | Python | 1 |
ial_build[kk - 1, :]
plt.barh(
ind if scan_var_name != "Null" else 0,
radial_build[kk, :],
left=lower,
height=0.8,
label=f"{radial_labels[kk]}"
+ f"\n {radial_build[kk][0]:.3f} m" * args.numbers,
color=radial_color[kk],
... | Python | 1 |
_e, item_e).sum(dim=1)
def full_sort_predict(self, interaction):
user_index = interaction[self.USER_ID]
item_index = torch.tensor(range(self.n_items)).to(self.device)
user = torch.unsqueeze(user_index, dim=1).repeat(1, item_index.shape[0])
user = torch.flatten(user)
item = ... | Python | 1 |
",
},
},
"batch_prefill": {
"input_embeds": nn.spec.Tensor([1, "seq_len", self.hidden_size], self.dtype),
"logit_positions": nn.spec.Tensor(["batch_size"], "int32"),
"paged_kv_cache": nn.spec.Object(object_type=PagedKVCache),
... | Python | 1 |
import sys
sys.path.append(r'D:\Dev\Source\Falcom\Decompiler2')
from Falcom.ED62.Parser.scena_writer_helper import *
try:
import T1131_2_hook
except ModuleNotFoundError:
pass
scena = createScenaWriter('T1131_2 ._SN')
# id: 0xFFFF offset: 0x0
@scena.Header('Header')
def Header():
header = ScenaHeader()
... | Python | 1 |
oadbalancer must be '
'specified.')
raise exceptions.CommandError(message)
body = _parse_common_args(parsed_args)
if parsed_args.listener:
listener_id = _get_listener_id(
self.get_client(),
parsed_args.listener)
... | Python | 1 |
eCreate2d {
hdr: CtrlHeader {
ctrl_type: CtrlType::CmdResourceCreate2d,
flags: 0,
fence_id: 0,
ctx_id: 0,
padding: 0,
},
resource_id: 1,
format: Formats::R8G8B8A8Unorm,
width: dev.width,
height: dev.height,
});
let desc_c2d = Descriptor {
addr: unsafe { &(*rq).request as *co... | Rust | 0 |
import random
import math
import matplotlib.pyplot as plt
# Step 1: Generate K random numbers within limit N
K = int(input("Enter the number of random numbers (K, minimum 10): "))
N = int(input("Enter the limit (N): "))
if K < 10:
raise ValueError("K should be at least 10.")
numbers = random.sample(range(1, N + 1... | Python | 1 |
nal_metrics[value] = metrics_file[epoch]
torch.save(model.state_dict(), DIR_EXPERIMENT + f'/model_{EPOCHS}_noise_{value}')
with open(DIR_EXPERIMENT + '/gaussian_noise01_19.txt', 'w') as file:
file.write(json.dumps(final_metrics))
np.save(DIR_EXPERIMENT + '/gaussian_noise01_19.npy', final_metrics, ... | Python | 1 |
:from_slice(&sk).unwrap();
// Hashed input message (labelled as h1)
let data =
hex::decode("02e2e1ab1b9f5a8a68fa4aad597e7493095648d3473b213bba120fe42d1a595f3e")
.unwrap();
// Nonce generation
let nonce = ecdsa.generate_nonce(&sk_bn, &data).unwrap();
... | Rust | 0 |
# Spatial average
diffs = [diff.mean([1, 2]) for diff in diffs]
# Shape of each diff after mean: [5*batch_size]
# The spatial dimensions are averaged, leaving only the batch dimension
sum_diffs=sum(diffs)
#Shape of sum_diffs: [15]
#The sum across all feature maps for... | Python | 1 |
rr
}
/// Returns the 1D memory index calculated from 2D coordinates.
fn calc_index(&self, (row, col): Coords) -> usize {
B::WIDTH * row + col
}
}
impl<'a, T, B: BlockDim> Index<Coords> for Block<'a, T, B> {
type Output = T;
#[inline]
fn index(&self, coords: Coords) -> &Self::Outpu... | Rust | 0 |
from langchain.schema import BaseRetriever, Document
from typing import List
from pydantic import Field
import re
class HybridRetriever(BaseRetriever):
bm25_retriever: BaseRetriever = Field(...)
semantic_retriever: BaseRetriever = Field(...)
k_bm25: int = Field(default=3)
k_semantic: int = Field(defaul... | Python | 1 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.