text string | label_name string | labels int64 |
|---|---|---|
'i (g parents) d -> parents i g d', parents = 2)
# cross over
parent1, parent2 = parents
children = parent1.lerp(parent2, (torch.randn_like(parent1) / temperature).sigmoid())
# maybe migration
if (
divisible_by(self.step.item() + 1, self.migrate_genes_every) and... | Python | 1 |
{"title": "Error: OSRM reach the limit number of points. Please switch to Vincenty"}
return return_lambda_gateway_response(400, cluster)
# Define weight of each edge
distance = constraints.CreateDistanceEvaluator(data)
distance_matrix = distance.get_distance_matrix()
distance_evaluator = dista... | Python | 1 |
import numpy as np
import sys
import os
import cPickle
if len(sys.argv) < 2:
print 'Usage: python VerifyDistMatrix.py target_name'
exit(-1)
target = sys.argv[1]
distcbDir = 'Test500-distcb/'
tplDistDir = 'pdb25-tpl-atomDistMatrix/'
pdbDistDir = 'pdb25-7952-atomDistMatrix/'
distcbFile = distcbDir + target + '.dist... | Python | 1 |
;
match PageTable::alloc_proc_pagetable(pdata.tf as usize) {
Some(p) => pgt = p,
None => {
drop(idata); drop(inode); LOG.end_op();
return Err("mem not enough")
},
}
let mut proc_size = 0usize;
// load each program section
let ph_size = mem::size_of::<... | Rust | 0 |
import pytest
import os
from fastNLP import Vocabulary
@pytest.mark.torch
class TestCRF:
def test_case1(self):
from fastNLP.modules.torch.decoder.crf import allowed_transitions
# 检查allowed_transitions()能否正确使用
id2label = {0: 'B', 1: 'I', 2:'O'}
expected_res = {(0, 0), (0, 1), (0, 2... | Python | 1 |
e:
logger.error(f"Error checking/loading PDF: {e}")
# Domain-specific handling for other URLs
httpx_domains = [
"https://ncode.syosetu.com",
"https://pubmed.ncbi.nlm.nih.gov",
"https://www.bnext.com.tw",
"https://github.com",
"https://www.twreporter.org",
... | Python | 1 |
te_to_check >= start_date:
day_start_time = datetime.combine(date_to_check, time(9, 30))
day_start_time_et = eastern.localize(day_start_time)
# 添加API调用间隔控制
if api_call_count > 0:
time_module.sleep(0.2) # 200毫秒延迟,避免触发限流
# 重试机制
max_retries = 3... | Python | 1 |
/// it is destroyed.
unsafe fn destroy_sampler(&self, sampler: vk::Sampler);
}
impl SamplerFactory for Graphics {
/// Create a new sampler using the Graphics subsystem's logical device.
unsafe fn create_sampler(
&self,
debug_name: impl Into<String>,
sampler_create_info: vk::Sample... | Rust | 0 |
from web3 import Web3
w3 = Web3()
| Python | 1 |
import sqlalchemy
import datetime
from sqlalchemy import orm
from sqlalchemy_serializer import SerializerMixin
from .db_session import SqlAlchemyBase
# Таблица для хранения содержимого письма(feedback).
class Letter(SqlAlchemyBase, SerializerMixin):
__tablename__ = 'letters'
id = sqlalchemy.Column(sqlalchemy... | Python | 1 |
target: "QueryResponse".into()
})
}
}
}
#[derive(Debug, Eq, PartialEq, Clone)]
pub struct SetDeviceIdResponse {
// 2-byte device ID
device: u16
}
impl ResponseParser for SetDeviceIdResponse {
fn parse(mut buf: &[u8]) -> Resp {
buf.advance(6); // bytes 3-5 are reserved
Resp::SetDevic... | Rust | 0 |
confirm_timer.start()
if confirm_timer.reached() and self.appear_then_click(PLAY_HIGHLIGHTS, offset=30, interval=1):
continue
else:
confirm_timer.clear()
def switch_to_next(self):
logger.info('Switch to next nikke')
s... | Python | 1 |
Reg<chstatus::CHSTATUS_SPEC>;
#[doc = "Channel %s status register"]
pub mod chstatus;
#[doc = "CHADDR register accessor: an alias for `Reg<CHADDR_SPEC>`"]
pub type CHADDR = crate::Reg<chaddr::CHADDR_SPEC>;
#[doc = "Channel %s address register"]
pub mod chaddr;
#[doc = "INT_RAW register accessor: an alias for `Reg<INT_R... | Rust | 0 |
html#method.flatten
/// [`Iterator`]: trait.Iterator.html
#[must_use = "iterator adaptors are lazy and do nothing unless consumed"]
#[stable(feature = "iterator_flatten", since = "1.29")]
pub struct Flatten<I: Iterator>
where I::Item: IntoIterator {
inner: FlattenCompat<I, <I::Item as IntoIterator>::IntoIter>,
}
#... | Rust | 0 |
import pinocchio as pin
import numpy as np
import mujoco
from mujoco import viewer
def main():
# 加载 Pinocchio 模型(URDF)
urdf_path = "../../Kinova_description/urdf/Kinova_description.urdf"
model = pin.buildModelFromUrdf(urdf_path)
data = model.createData()
# 加载 Mujoco 模型(MJCF)
mjcf_path = "../..... | Python | 1 |
return Err(Error::SysError(SysErr::EINTR));
//return NansleepFor(task, self.dur, self.rem)
}
}
pub fn SysGettimeofday(task: &mut Task, args: &SyscallArguments) -> Result<i64> {
let tvAddr = args.arg0 as u64;
let tzAddr = args.arg1 as u64;
let mut timeV = Timeval::default();
let mut time... | Rust | 0 |
&str = r#"---
rx_max_frames: 60"#;
const EXPECTED_ETHTOOL_LINK_MODE: &str = r#"---
auto_negotiate: false
ours: []
speed: 10
duplex: full"#;
#[test]
fn test_get_ethtool_coalesce_yaml() {
with_tun_iface(|| {
let state = NetState::retrieve().unwrap();
let iface = &state.ifaces[IFACE_TUN_NAME];
... | Rust | 0 |
sent"
def test_reproduce_mobile_app_error_scenario(self):
"""Test reproducing mobile app adset creation error scenario"""
result = self.tester.test_reproduce_mobile_app_error()
assert result["success"], f"Error reproduction test failed: {result.get('error', 'Unknown error')}"
... | Python | 1 |
operation.parameters().0.a()
};
let name: String = {
let mut name_vec = vec![0; name_len as usize];
//let mut name_vec = Vec::with_capacity(name_len as usize);
let p0 = ParamTmpRef::new_output(&mut name_vec);
let mut opera... | Rust | 0 |
75, 2347, 4039, 5177, 3146,
6710, 4858, 4829, 4982, 7618, 2981, 2813, 521,
5462, 4291, 934, 7256, 4626, 6053, 3027, 1246,
1637, 7520, 1644, 3775, 478, 5424, 1578, 680,
4888, 4141, 4374, 2615, 6598, 3330, 442, 1641,
5380, 2075, 3620, 6593, 6005, 5664, 3... | Rust | 0 |
######### ########### ###########
def observeUpdate(self, observation: int, gameState: busters.GameState):
"""
Update beliefs based on the distance observation and Pacman's position.
The observation is the noisy Manhattan distance to the ghost you are
tracking.
There is on... | Python | 1 |
`\(`` and end with ``\)``,
are preserved without escaping. Otherwise regular LaTeX escaping applies.
Parameters
----------
s : str
Input to be escaped
Return
------
str :
Escaped string
"""
s = s.replace(r"\$", r"rt8§=§7wz")
ps_d = re.compile(r"\$.*?\$").search(... | Python | 1 |
#
# Copyright (c) 2023 Airbyte, Inc., all rights reserved.
#
from setuptools import find_packages, setup
MAIN_REQUIREMENTS = [
"airbyte-cdk~=0.1",
]
TEST_REQUIREMENTS = [
"requests-mock~=1.9.3",
"pytest~=6.1",
"pytest-mock~=3.6.1",
]
setup(
entry_points={
"console_scripts": [
... | Python | 1 |
;
return self;
}
pub fn operation<'a>(
&'a mut self,
val: Vec<MedicinalProductDefinition_Operation>,
) -> &'a mut MedicinalProductDefinitionBuilder {
self.value["operation"] = json!(val.into_iter().map(|e| e.value).collect::<Vec<_>>());
return self;
}
pub fn... | Rust | 0 |
["{j:{a:0}}", "{i:{a:A,b:1,f:2255100,c:{a:0,b:0,c:0,d:44},d:{a:FFB,b:0,c:1,d:12,e:0,f:0},e:{}}}", ],
["{j:{a:0}}", "{i:{a:B,b:1,f:2255100,c:{a:0,b:0,c:0,d:44},d:{a:FFB,b:0,c:1,d:12,e:0,f:0},e:{}}}", ],
["{j:{a:0}}", "{i:{a:C,b:1,f:2255100,c:{a:0,b:0,c:0,d:44},d:{a:FFB,b:0,c:1,d:12,e:0,f:0},... | Rust | 0 |
0.3,
}),
));
let sphere_4 = Box::new(Sphere::new(
Vector3::from((-1.3, 0., -1.)),
0.5,
Box::new(Metal {
albedo: Vector3::from((0.8, 0.8, 0.2)),
fuzziness: 1.,
}),
));
let sphere_5 = Box::new(Sphere::new(
Vector3::from((-0.5, 0.15... | Rust | 0 |
为s
// 那么对于任意的v,假如s小于目标区域的最小x范围,该速度v无论如何无法达到目标范围
// 实际上就是求解 (v * v + v) / 2 >= x_min 这样一个一元二次不等式
// 当x方向上的速度大于x的最大范围时,1步之后,探针就超出了x的目标范围
// 那么x方向上的最大速度为x的最大范围
// 裁剪之后运行时间加快了10倍
for v_x in (0..=x_range.1).filter(|v| (v * v + v) / 2 >= x_range.0) {
// 因为初始位置不在区域范围内,所以至少需要1步 才能使探针在y方向的范围内
... | Rust | 0 |
# -*- coding: utf-8 -*-
from Components.Language import language
from Tools.Directories import resolveFilename, SCOPE_PLUGINS
import gettext
#def localeInit():
# gettext.bindtextdomain("DeviceManager", resolveFilename(SCOPE_PLUGINS, "SystemPlugins/DeviceManager/locale"))
def _(txt):
t = gettext.dgettext("DeviceManag... | Python | 1 |
):
update_processed_files(file.name, st.session_state.new_file_name)
# メイン関数
def main():
st.title("見積書/納品書/請求書のファイル名変換ツール")
st.write("PDFファイルをアップロードして、ファイル名を変換してダウンロードできます。")
st.write("複数のPDFファイルをアップロードできます。")
st.sidebar.header("ナビゲーションウィンドウ")
files = st.sidebar.file_uploader("PDFファイルをアップ... | Python | 1 |
from __future__ import annotations
from unittest.mock import Mock, patch
import pytest
try:
from urllib3.contrib.pyopenssl import extract_from_urllib3, inject_into_urllib3
except ImportError:
pass
def setup_module() -> None:
try:
from urllib3.contrib.pyopenssl import inject_into_urllib3
... | Python | 1 |
hiddens).T, y, y_star_mean, y_star_cov, plot_xs)
ax_h_to_y.set_title("hiddens to y")
plt.draw()
plt.pause(1.0 / 60.0)
# Initialize covariance parameters and hiddens.
rs = npr.RandomState(0)
init_params = 0.1 * rs.randn(total_num_params)
print("Optimizing covariance parameters.... | Python | 1 |
.len());
self.proof_order.push((a, e, p));
}
}
#[repr(C)]
struct ElabTerm<'a> {
lc: &'a LocalContext,
fe: FormatEnv<'a>,
fsp: FileSpan,
}
#[repr(C)]
struct ElabTermMut<'a> {
elab: &'a mut Elaborator,
fsp: FileSpan,
}
impl<'a> Deref for ElabTermMut<'a> {
type Target = Elaborator;
fn deref(&self) -... | Rust | 0 |
_slider_changed)
layout.addWidget(self.slider)
# 范围标签
range_label = QLabel(f"[{self.joint_range[0]:.2f}, {self.joint_range[1]:.2f}]")
range_label.setMinimumWidth(100)
range_label.setMaximumWidth(100)
range_label.setStyleSheet("color: gray; font-size: 10px;")
layo... | Python | 1 |
compare equality of the
// inner range!
use core::cmp::Ordering;
use core::ops::{Range, RangeInclusive};
//
// Range start wrapper
//
#[derive(Eq, Debug, Clone)]
pub struct RangeStartWrapper<T> {
pub range: Range<T>,
}
impl<T> RangeStartWrapper<T> {
pub fn new(range: Range<T>) -> RangeStartWrapper<T> {
... | Rust | 0 |
ranges as *mut libc::c_void);
}
free(fdselect as *mut libc::c_void);
};
}
pub(crate) unsafe fn cff_fdselect_lookup(cff: &cff_font, gid: u16) -> u8 {
if cff.fdselect.is_null() {
panic!("in cff_fdselect_lookup(): FDSelect not available");
}
let fdsel = cff.fdselect;
if gid as ... | Rust | 0 |
86
87, // 87
11, // 88
43, // 89
45, // 90
91, // 91
23, // 92
87, // 93
47, // 94
95, // 95
3, // 96
11, // 97
19, // 98
27, // 99
25, // 100
43, // 101
51, // 102
59, // 103
13, // 104
45, // 105
53, // 106
91, // 107
27, // 108
91, // 109
55, // 110
111, // 111
7, // 112
23, // 113
39, ... | Rust | 0 |
loilike+=1
else:
nhan=tds.nhan_xu('LIKEGIARE', id)
try:
xu = nhan[1]
msg = nhan[0]
dem+=1
hoanthanh(dem, id, 'LIKE 2', msg, xu)
loilike=0
if dem % doinick == 0:
namtool(14); print(f'\033[1;32mSố Xu Hiện Tại: \033[1;3... | Python | 1 |
_sample: Point2f) -> LightSample {
let radiance = self.intensity;
let pfrom = pos + (-2.0 as Float * self.world_radius) * self.dir;
let pto = pos;
let pdf = 1.0 as Float;
LightSample{
radiance: radiance,
pfrom: pfrom,
pto: pto,
pdf:... | Rust | 0 |
cs.alloc(|| "preimage xr", || {
xr_value.ok_or(SynthesisError::AssignmentMissing)
})?;
for i in 0..MIMC_ROUNDS {
// xL, xR := xR + (xL + Ci)^3, xL
let cs = &mut cs.namespace(|| format!("round {}", i));
// tmp = (xL + Ci)^2
let tmp_value = xl... | Rust | 0 |
}
}
/// Print a success status message (in green if colors are enabled)
macro_rules! status_ok {
($status:expr, $msg:expr) => {
::shell::status(::term::color::GREEN, $status, $msg, true);
};
($status:expr, $fmt:expr, $($arg:tt)+) => {
status_ok!($status, format!($fmt, $($arg)+));
}... | Rust | 0 |
# Copyright (C) 2024 Open Source Integrators
# License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl).
from odoo import _, api, fields, models
class TMSOrder(models.Model):
_inherit = "tms.order"
purchase_ids = fields.One2many("purchase.order", "trip_id", store=True)
purchase_order_count = fields... | Python | 1 |
combined.save(path)
raise Exception(
f"Cairo and Inkscape {name} images differ by {diff} pixels, "
f"images written to {path}"
)
else:
print(f"{name} difference: {diff}", file=sys.stderr)
def check_svg(svg: str, inkscape_shell, wrapped, ch... | Python | 1 |
d_qty_for_production_plan", "fieldtype": "Float", "width": 100, "convertible": "qty"},
{"label": _("Reserved for Sub Contracting"), "fieldname": "reserved_qty_for_sub_contract", "fieldtype": "Float", "width": 100, "convertible": "qty"},
{"label": _("Reserved for POS Transactions"), "fieldname": "reserve... | Python | 1 |
def encode_prompt(text_encoders, tokenizers, prompt, text_input_ids_list=None):
for i, text_encoder in enumerate(text_encoders):
if tokenizers is not None:
tokenizer = tokenizers[i]
text_input_ids = tokenize_prompt(tokenizer, prompt)
else:
assert text_input_ids_li... | Python | 1 |
from django_cotton.tests.utils import CottonTestCase
from django_cotton.tests.utils import get_rendered
class DynamicComponentTests(CottonTestCase):
def test_dynamic_components_via_string(self):
self.create_template(
"cotton/dynamic_component_via_string.html",
"""
<div>... | Python | 1 |
tau = rtr/rt1r1;
rt1r1 = rtr.clone();
Zip::from(&mut pki).and(&ri).apply(|pki, &ri|{
*pki = ri + tau * *pki;
});
}
err
}
//We can set the below in the future to allowing rectangular A matrices. Therefore, it could be applied to solve full-rank least squares
/... | Rust | 0 |
Flags::IGNORECASE.bits() | 64),
opts
);
assert_eq!(Options::from(Flags::EXTENDED | Flags::IGNORECASE), opts);
assert_ne!(
Options::from(Flags::EXTENDED | Flags::IGNORECASE | Flags::MULTILINE),
opts
);
assert_eq!(opts.ignore_case(), RegexpOption... | Rust | 0 |
tion = reserve.config.optimal_utilization_rate as f64 / 100f64;
let borrow_apy = {
if optimal_utilization == 1f64 || current_utilization < optimal_utilization {
let normalized_factor = current_utilization / optimal_utilization;
let optimal_borrow_rate = reserve.config... | Rust | 0 |
src/model/undo_stack.rs
use super::{Buffer, DosChar, Position, Layer, Size};
pub trait UndoOperation {
fn undo(&self, buffer: &mut Buffer);
fn redo(&self, buffer: &mut Buffer);
}
pub struct UndoSetChar {
pub pos: Position,
pub layer: usize,
pub old: Option<DosChar>,
pub new: Option<DosChar>
}
... | Rust | 0 |
ut(self) -> &'a mut V {
self.table.bst.arena[self.node_idx].get_mut().1
}
/// Sets the value of the entry with the `OccupiedEntry`'s key,
/// and returns the entry's old value.
///
/// # Examples
///
/// ```
/// use scapegoat::SgMap;
/// use scapegoat::map_types::Entry;
... | Rust | 0 |
//avoid optimizations
println!("{}",a);
}
}
}
let mut system = System::new();
let _handler = spawn(|| expensive_computation());
let _handler1 = spawn(|| expensive_computation());
let _handler2 = spawn(|| expensive_computation());
let _handler3 = spawn(|| exp... | Rust | 0 |
lt() -> Self {
let mut s = ::std::mem::MaybeUninit::<Self>::uninit();
unsafe {
::std::ptr::write_bytes(s.as_mut_ptr(), 0, 1);
s.assume_init()
}
}
}
#[repr(C)]
#[derive(Copy, Clone)]
pub struct MemoryTrackerTraceDataT {
pub file: *const ::std::os::raw::c_char,
... | Rust | 0 |
EFIX
return os.path.normpath(os.path.join(prefix, pyc_filename))
elif filename.startswith(SYS_PREFIX) and filename.endswith('.pyc'):
# If filename is already PyInstaller-compatible, prevent any further processing (i.e., with original
# implementation).
return ... | Python | 1 |
Err(UnexpectedAdditionalParameter)?
}
Ok(Self {
name,
r#type,
steeler,
size,
count,
param1,
param2,
__: (),
})
}
}
pub struct TableItem {
pub items: Vec<Item>,
__: (),
}
im... | Rust | 0 |
nt_queue.get())
return events
def get_telemetry(self, stream_id: str) -> Optional[dict]:
return self.telemetry_simulator.get_telemetry(stream_id)
def get_all_telemetry(self) -> Dict[str, dict]:
return self.telemetry_simulator.get_all_telemetry()
def add_drone(self,... | Python | 1 |
Transform(label1, label21),
Transform(point2, point22), Transform(label2, label22),
Transform(point3, point23), Transform(label3, label23),
)
self.wait_until_bookmark("A")
self.play(
Transform(label1, MathTex(r"(x_1, y_1)").move_to(lab... | Python | 1 |
nt_request", "number of request on api"),
&["endpoint", "method", "status"]
)
.expect("metrics 'oauth10a_client_request' to not be initialized");
static ref CLIENT_REQUEST_DURATION: CounterVec = register_counter_vec!(
opts!(
"oauth10a_client_request_duration",
"durati... | Rust | 0 |
vice
pub mod interrupts;
pub use self::interrupts::Interrupt;
pub use self::interrupts::Interrupt as interrupt;
pub use super::instances::adc;
pub use super::instances::cec;
pub use super::instances::crc;
pub use super::instances::dma;
pub use super::instances::exti;
pub use super::instances::flash;
pub use super::ins... | Rust | 0 |
, I> {
type Item = (usize, u8);
fn next(&mut self) -> Option<(usize, u8)> {
for (i, &a) in self.text.by_ref() {
self.myers.step(&mut self.state, a);
if self.state.dist <= self.max_dist {
return Some((i, self.state.dist));
}
}
None
... | Rust | 0 |
lf {
path,
file,
offset,
last_timestamp,
})
}
pub async fn seal(mut self) -> Result<Timestamp> {
let ts = self.last_timestamp.ok_or_else(|| {
Error::Unknown("should not seal a segment with no timestamp".to_owned())
})?;
... | Rust | 0 |
LF: &str = "../../resources/kernel/vmlinux-hello-busybox-halt";
fn default_memory_config() -> MemoryConfig {
MemoryConfig { size_mib: 1024 }
}
fn default_kernel_config(path: PathBuf) -> KernelConfig {
KernelConfig {
path,
himem_start: 0x0010_0000, // 1 MB
cmdline: "console=ttyS0 i8042.... | Rust | 0 |
t_id" => Stat::SetUnitId,
"player_color" => Stat::PlayerColor,
"player_color_palette" => Stat::PlayerColorPalette,
"show_energy" => Stat::ShowEnergy,
"show_shields" => Stat::ShowShields,
_ => return Err(anyhow!("Unknown stat {}", key)),
})
}
/// NOTE: Passing an empty string... | Rust | 0 |
from flask import Flask, render_template, request, flash # jsonif
from markupsafe import escape
app = Flask(__name__)
@app.route('/')
def homepage():
return render_template('site.html')
@app.route('/submit', methods=['POST'])
def submit_form():
if request.method == 'POST':
# Get data from the form
... | Python | 1 |
od
def from_json(cls, json: T_JSON_DICT) -> DomStorageItemUpdated:
return cls(
storage_id=StorageId.from_json(json['storageId']),
key=str(json['key']),
old_value=str(json['oldValue']),
new_value=str(json['newValue'])
)
@event_class('DOMStorage.domSto... | Python | 1 |
from fastapi import APIRouter, Request
from fastapi.responses import HTMLResponse
from fastapi.templating import Jinja2Templates
router = APIRouter(prefix="/combustivel")
templates = Jinja2Templates(directory = "templates")
@router.get("/gasolina_comum", response_class=HTMLResponse)
async def get_raiz(request: Reque... | Python | 1 |
bias = ctx.saved_tensors
# out_features, in_features = weight.shape
# grad_x = grad_output @ weight
# #grad_weight_deq = grad_output.view(out_features, -1) @ x.view(-1, in_features) # out_features x in_features
# grad_weight = grad_output.view(-1, out_features).t() @ ... | Python | 1 |
es[2];
info!("Generate new block on node1");
let hash = node1.generate_block();
let rpc_client = node0.rpc_client();
let ret = wait_until(10, || rpc_client.get_block(hash.clone()).is_some());
assert!(ret, "Block should be relayed to node0");
let rpc_client = node2.rpc_... | Rust | 0 |
.last_allowedip {
break;
}
current_ip = ip.next_allowedip;
}
result
}
fn parse_endpoint(endpoint: &wgctrl_sys::wg_peer__bindgen_ty_1) -> Option<SocketAddr> {
let addr = unsafe { endpoint.addr };
match i32::from(addr.sa_family) {
libc::AF_INET => {
let ad... | Rust | 0 |
}
"wasm" => {
resp.headers_mut().insert(
"Content-Type",
HeaderValue::from_str("application/wasm").unwrap(),
);
}
... | Rust | 0 |
# Copyright (c) 2006-2009 Mitch Garnaat http://garnaat.org/
#
# Permission is hereby granted, free of charge, to any person obtaining a
# copy of this software and associated documentation files (the
# "Software"), to deal in the Software without restriction, including
# without limitation the rights to use, copy, modi... | Python | 1 |
@$(BLUEPRINT_FILENAME).function_name("CreateChatBot")
@$(BLUEPRINT_FILENAME).route(route="chats/{chatID}", methods=["PUT"], auth_level=func.AuthLevel.$(AUTHLEVEL_INPUT))
@$(BLUEPRINT_FILENAME).assistant_create_output(arg_name="requests")
def create_chat_bot(req: func.HttpRequest, requests: func.Out[str]) -> func.HttpRe... | Python | 1 |
H S SK Jr \" \5 rS/rS\S\\\\ 4 4S jr g)
get_logger!log_debug_info_for_expired_timersrun_idexpired_timersc @ U( a [ R SX5 g g )N!Timers expired for run:[%s] [%s].loggerinf... | Python | 1 |
3)
optimizer=SGD(lr=learning_rate)
#학습에 사용하는 변수
data_size=len(x)
max_iters=data_size//batch_size
total_loss=0
loss_count=0
loss_list=[]
for epoch in range(max_epoch):
#데이터 뒤섞기
idx=np.random.permutation(data_size)
x=x[idx]
t=t[idx]
for iters in range(max_iters):
batch_x=x[iters*batch_size:... | Python | 1 |
[allow(unused_mut)]
let mut scope_1206 = writer.prefix("Ipv6PrefixCount");
if let Some(var_1207) = &input.ipv6_prefix_count {
scope_1206.number(
#[allow(clippy::useless_conversion)]
aws_smithy_types::Number::NegInt((*var_1207).into()),
);
}
Ok(())
}
#[allow(unuse... | Rust | 0 |
ly used LoRAs will
be unloaded if the cache is above capacity."""
_manager_cls: type[LRUCacheLoRAModelManager] = LRUCacheLoRAModelManager
def create_lora_manager(
self,
model: torch.nn.Module,
) -> Any:
lora_manager = create_lora_manager(
model,
lora_man... | Python | 1 |
format!("redis://{}:{}@{}", self.username, self.password, self.host)
}
}
impl PostgresSettings {
pub fn with_db(&self) -> PgConnectOptions {
self.without_db().database(&self.database_name)
}
pub fn without_db(&self) -> PgConnectOptions {
let ssl_mode = if self.require_ssl {
... | Rust | 0 |
indowMask;
const LEAVE_WINDOW = xlib::LeaveWindowMask;
const POINTER_MOTION = xlib::PointerMotionMask;
const POINTER_MOTION_HINT = xlib::PointerMotionHintMask;
const BUTTON_1_MOTION = xlib::Button1MotionMask;
const BUTTON_2_MOTION = xlib::Button2MotionMask;
const BUTTON_3... | Rust | 0 |
(),
input.as_encrypted_data_ref().to_owned()
)
}
<reponame>patrickelectric/rust-clippy
// compile-flags: --emit=link
// no-prefer-dynamic
#![crate_type = "proc-macro"]
#![feature(repr128, proc_macro_hygiene, proc_macro_quote, box_patterns)]
#![allow(clippy::useless_conversion)]
extern crate proc_macro;
ex... | Rust | 0 |
from qnt.ta.ndadapter import NdType, nd_to_1d_universal_adapter
from qnt.ta.change import change
import numpy as np
from qnt.log import log_info, log_err
def ad_ratio_np(prices: np.ndarray) -> np.ndarray:
"""
Advance/Decline Ratio (numpy)
:param prices: last dimension - time
:return:
"""
ch =... | Python | 1 |
: int = 64
config_file: str | None = None
label_map_file: Path | str | None = None
def __post_init__(self):
if self.experiment_path is not None:
self.experiment_path = Path(self.experiment_path)
checkpoint = None
if self.experiment_path.is_file(): # Best model p... | Python | 1 |
LECT message_id FROM last_seen_message", params![], |r| r.get::<_, i32>(0)) {
c.execute("INSERT INTO last_seen_message VALUES (?)", params![message_id]);
} else {
c.execute("UPDATE last_seen_message SET message_id = MAX(message_id, ?)", &[message_id]);
}
}
}
/// Returns whet... | Rust | 0 |
# -*- coding: utf-8 -*-
"""
最终验证测试:自动HWND更新功能完整测试
"""
import sys
import os
import time
# 添加项目路径
sys.path.append(os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
from auto_approve.config_manager import load_config
from auto_approve.auto_hwnd_updater import AutoHWNDUpdater
from auto_approve.smart_process_f... | Python | 1 |
)
}
else if rc == 1 {
Ok(false)
}
else {
Err(Error::from(rc))
}
}
}
<reponame>chridou/nakadion
use nakadi_types::event_type::*;
use nakadi_types::RandomFlowId;
use nakadion::api::{ApiClient, MonitoringApi, SchemaRegistryApi};
#[cfg(feature = "reqwest"... | Rust | 0 |
rotation_count == 0:
cv2.line(original_image, top_left, top_right, green_color, 5)
cv2.line(original_image, top_right, bottom_right, red_color, 5)
cv2.line(original_image, bottom_left, bottom_right, blue_color, 5)
cv2.line(original_image, top_left, bottom_left, red_color, 5)
elif ro... | Python | 1 |
::create().expect("mrb init");
// get a mrb_value that can't be converted to a primitive type.
let value = interp.eval("Object.new").expect("eval");
let expected = Error {
from: Ruby::Object,
to: Rust::Float,
};
let result = unsafe { Float::try_from_mrb(&i... | Rust | 0 |
, 5000)
df_subtracted = self.read_sequences(df_subtracted)
df_subtracted.to_csv(os.path.join(self.data_path, 'protein_without_cofactor.tsv'), sep='\t', index=False)
cofactor_columns = ['SAM', 'NAD', 'NADP', 'FAD', 'GSH', 'CoA', 'THF', 'FMN', 'Menaquinone', 'Ubiquinone', 'Plastoquinone', 'Ferred... | Python | 1 |
oins_async() {
block_on(async {
let mut tt: TextTransliterateOffThread = Default::default();
let result = tt.transliterate("€ £ $ ¥", "en_US.UTF-8");
if let Ok(result) = result {
assert_eq!("EUR GBP $ JPY", result);
} else {
unreach... | Rust | 0 |
pred = model.predict(X_test)
# convert the predictions into label index
pred_classes = np.argmax(pred, axis=1)
# plot the actual results with actual and predicted labels
plt.figure(figsize=[10, 10])
# Convert y_test to integer values
y_test = y_test.astype(int)
for i in range(30):
... | Python | 1 |
cast_rx,
));
let (handle_tx, handle_rx) = oneshot::channel();
let subscription = Subscription(handle_tx);
sub_tx.send(subscription).await.unwrap();
let action_request = IncomingMessage::ActionRequest {};
broadcast_tx.send(action_request).unwrap();
let event = handle_rx.await.unwrap();
... | Rust | 0 |
import torch
from torch import nn
from torch.nn import functional as F
class ResGangneuron_A(nn.Module):
def __init__(self):
super(ResGangneuron_A, self).__init__()
# xw+b
self.fc0 = nn.Linear(3*32*32, 256, bias=False)
self.dd = nn.Linear(256, 256, bias=False)
self.dd2 = ... | Python | 1 |
gative_indices, 100)
train_x_batch = train_x[negative_batch]
train_y_batch = train_y[negative_batch]
x_val, y_val = val_set.next_batch(min(bsize, nval))
lr = config.lr
loss, acc, _ = sess.run(
[loss_c, acc_, train_op],
... | Python | 1 |
# Without the `in`, this is considered to be a unary `not`
x not
1 + 2 | Python | 1 |
} else {
i
};
val |= 1 << index;
}
}
val
}
#[inline]
pub fn set(&mut self, bit_offset: usize, bit_width: u8, val: u64) {
debug_assert!(bit_width <= 64);
debug_assert!(bit_offset / 8 < self.storag... | Rust | 0 |
('class:theme-fg-dim', 'class:theme-fg-dim'),
space,
('class:theme-bg-dim', 'class:theme-bg-dim'),
space,
('class:theme-bg-dialog', 'class:theme-bg-dialog'),
space,
(
'class:theme-bg-line-highlight',
... | Python | 1 |
mateDiffLoraLoader,
"ADE_AnimateDiffModelSettings_Release": AnimateDiffModelSettings,
# Noise Layer Nodes
"ADE_NoiseLayerAdd": NoiseLayerAddNode,
"ADE_NoiseLayerAddWeighted": NoiseLayerAddWeightedNode,
"ADE_NoiseLayerReplace": NoiseLayerReplaceNode,
# Iteration Opts
"ADE_IterationOptsDefault... | Python | 1 |
format(str(error)))
# If garbage collection is on, deallocate everything possible.
if gc_thread:
print(f"{formatting.timestamp()}: Terminating garbage collection. "
f"Waiting for max {settings.garbage_collector_cleanup_time} seconds. ")
gc_thread.finish(settings.garbage_col... | Python | 1 |
0x00,
0x7F,0xFF,0xFF,0x7F, 0x00,0x00,0x00,0x00,
0x7F,0xFF,0xFF,0xFF, 0x7F,0x00,0x00,0x00,
0x7F,0xFF,0xFF,0xFF, 0xFF,0x7F,0x00,0x00,
0x7F,0xFF,0xFF,0xFF, 0xFF,0xFF,0x7F,0x00,
0x7F,0xFF,0xFF,0xFF, 0xFF,0x7F,0x7F,0x7F,
0x7F,0xFF,0xFF,0xFF, 0x7F,0x00,0x00,0x00,
0x7F,0xFF,0x7F,0xFF, 0x7F,0x00,0x... | Rust | 0 |
we reach a certain point
// Use positive root. Negative root is extrapolating backwards in time
let tmp = (2.0 * vy as f64 + 1.0) / 2.0;
let first_t = (tmp + (tmp.powf(2.0) - 2.0 * end_y as f64).sqrt()).ceil() as usize;
let last_t = (tmp + (tmp.powf(2.0) - 2.0 * start_y as f64).sqrt()).... | Rust | 0 |
_screen_quit::ChangeScreenQuitOp {}));
result.push(Box::new(change_screen_return::ChangeScreenReturnOp {}));
result.push(Box::new(change_screen_trade::ChangeScreenTradeOp {}));
result.push(Box::new(
change_screen_trade_prisoners::ChangeScreenTradePrisonersOp {},
));
result.push(Box::new(chan... | Rust | 0 |
"""Add dimensions to vehicle0.py figure."""
from pysketcher import *
R = 1 # radius of wheel
L = 4 # distance between wheels
H = 2 # height of vehicle body
w_1 = 5 # position of front wheel
xmax = w_1 + 2*L + 3*R
drawing_tool.set_coordinate_system(xmin=0, xmax=xmax,
ymin=-... | Python | 1 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.