text string | label_name string | labels int64 |
|---|---|---|
ot None:
return x + self.gamma.view(-1, len(self.gamma), 1, 1) * y
return y
class SEAttention(nn.Module):
def __init__(self, channel=512,reduction=16):
super().__init__()
self.avg_pool = nn.AdaptiveAvgPool2d(1)
self.fc = nn.Sequential(
nn.Linear(channel, cha... | Python | 1 |
# Ultralytics YOLO 🚀, AGPL-3.0 license
from ultralytics.utils import LOGGER, ROOT, SETTINGS, TESTS_RUNNING, colorstr
try:
assert not TESTS_RUNNING # do not log pytest
assert SETTINGS['mlflow'] is True # verify integration is enabled
import mlflow
assert hasattr(mlflow, '__version__') # verify pac... | Python | 1 |
32>),
I32I16(fixed::Fixed<i16>),
I32U16(fixed::Fixed<u16>),
I32I8(fixed::Fixed<i8>),
I32U8(fixed::Fixed<u8>),
I16I16(fixed::Fixed<i16>),
I16I8(fixed::Fixed<i8>),
I16U8(fixed::Fixed<u8>),
I8I8(fixed::Fixed<i8>),
U64U64(fixed::Fixed<u64>),
U64U32(fixed::Fixed<u32>),
U64U16(fix... | Rust | 0 |
total_round_p2p_msgs: usize,
total_num_of_shares: usize,
round_count: usize,
span: Span,
) -> TofndResult<()> {
let mut p2p_msg_count = 0;
let mut bcast_msg_count = 0;
// loop until no more messages are needed for this round
while round.expecting_more_msgs_this_round() {
// get inte... | Rust | 0 |
# -*- coding: utf-8 -*-
"""
Copyright (C) 2012-2018 Twitch-on-Kodi
This file is part of Twitch-on-Kodi (plugin.video.twitch)
SPDX-License-Identifier: GPL-3.0-only
See LICENSES/GPL-3.0-only for more information.
"""
from ..addon import utils
from ..addon.common import kodi
from ..addon.constants impor... | Python | 1 |
// All lower case
let retrieved_creds = proof.retrieve_credentials().await.unwrap();
assert!(retrieved_creds.contains(r#""zip":"84000""#));
let ret_creds_as_value: serde_json::Value = serde_json::from_str(&retrieved_creds).unwrap();
assert_eq!(ret_creds_as_value["attrs"]["zip_1"][... | Rust | 0 |
_ => false,
});
}
#[test]
fn buffer_less_than_minimal_required_size_for_parsing() {
let buffer = &mut [0u8; 4];
let err = expect_parse_error(buffer);
assert!(match err {
ParseError::BufferTooSmall(_) => true,
_ => false,
});
}
#[test]... | Rust | 0 |
let mut is = Vec::new();
is.extend(emit_expr(*p));
is.extend([
Instruction::Wrap(Type::I32, Type::I64),
Instruction::If(emit_expr(*c), emit_expr(*a), Type::I64),
]);
is
}
Expr::BinaryPrimitive(o, l, r) => {
... | Rust | 0 |
import requests
import time
import os
from itertools import islice
cp2 = os.path.dirname(os.path.realpath(__file__) + '\\')
cp = cp2[:-8]
### CHANGE YOUR FILENAMES HERE ###
forbiddenfa = cp + "wforbidden.txt"
foundfa = cp + "wfound.txt"
nffa = cp + "w404.txt"
latest2 = cp + "latest.txt"
wlist = cp + "wordlist.t... | Python | 1 |
FixedDate>>,
}
#[derive(Serialize, Deserialize, Clone, Debug, Default, PartialEq)]
pub struct UnderlyingProvisionOptionExerciseFixedDate {
/// Required if NoUnderlyingProvisionOptionExerciseFixedDates(42112) > 0.
#[serde(skip_serializing_if = "Option::is_none")]
#[serde(rename = "42113")]
pub underlying_provisi... | Rust | 0 |
# Aquí se definirá el DataClass (RAGData)
from dataclasses import dataclass, field
from typing import List, Optional
from adalflow import DataClass
@dataclass
class RAGData(DataClass):
question: str
documents: List[str] = field(default_factory=list)
prompt: Optional[str] = None
output: Optional[str] = ... | Python | 1 |
test_center_reindex_frame(raw):
# shifter index
frame = DataFrame(range(100), index=date_range("2020-01-01", freq="D", periods=100))
s = [f"x{x:d}" for x in range(12)]
minp = 10
frame_xp = (
frame.reindex(list(frame.index) + s)
.rolling(window=25, min_periods=minp)
.apply(f,... | Python | 1 |
result['stop'] = self.pickler.loads(result['stop'])
return result
def _evaluate(self, result):
return result
def _add(self, dt, *args):
timestamp = self.pickler.dumps(dt)
add = self.cache.add
dump = self.value_pickler.dumps
if len(args) == 1:
mappin... | Python | 1 |
import requests
from bs4 import BeautifulSoup
import threading
import mysql.connector
from queue import Queue
def obtener_conexion():
try:
conexion = mysql.connector.connect(
host='localhost',
port=3306,
user='root',
password='1234',
databa... | Python | 1 |
= .001
material_pointers_cabinet.assign_pointer_to_assembly(part,"Wire Baskets")
material_pointers_cabinet.assign_materials_to_assembly(part)
return part
def add_wine_rack(assembly):
part_path = path.join(paths_cabinet.get_assembly_path(),"Wine Rack.blend")
part = pc_types.Assembly(as... | Python | 1 |
eric::Reg::read), [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`write_with_zero`](crate::generic::Reg::write_with_zero), [`modify`](crate::generic::Reg::modify). See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about avaliable fields see [dap](dap) modul... | Rust | 0 |
of the file.
Plugins with a "noinclude" file are also skipped.
"""
files = set(ListDir(self.sourceDir, [], fullpath=False))
with open(join(self.pyVersionDir, "Root Includes.txt"), "r") as f:
rootIncludes = CaseInsensitiveList(*f.read().strip().split("\n"))
noinclud... | Python | 1 |
t.ComputedFeatureNames.setValue(featnames)
# run the workflow with the test blocks in the gui,
# if you want to see why these labels are chosen
# object 11 -small white square
# object 27 -large grey square
labelArray11 = numpy.zeros((12,))
labelArray11[11] = 1
l... | Python | 1 |
out = list(out.keys())[0]
if "${item." in out:
extra_outs = []
dvc_matrix = dvc_stages[i.from_stage_outputs][
"matrix"
]
replacements... | Python | 1 |
nemonic: Mnemonic::VMOVNTPD, operand1: Some(IndirectScaledIndexedDisplaced(RCX, RCX, Eight, 577948270, Some(OperandSize::Zmmword), None)), operand2: Some(Direct(ZMM20)), operand3: None, operand4: None, lock: false, rounding_mode: None, merge_mode: None, sae: false, mask: None, broadcast: None }, &[98, 225, 253, 72, 43,... | Rust | 0 |
lue as TipValue;
use serialize::json::{Json, ToJson};
#[derive(Debug)]
pub struct Tip {
// Made pub for serializer, may be fix it?
pub latest_timestamp: (u64, u32),
pub values: HashMap<Key, (u64, TipValue)>,
}
// Named fields are ok since we don't store lots of History objects
probor_struct_encoder_decod... | Rust | 0 |
),
Value::Number(NAN)
);
assert_eq!(
atan2(
avm,
context,
*math.read(),
&[Value::Undefined, Value::Number(1.0)]
),
Value::Number(NAN)
);
... | Rust | 0 |
let mut builder = TlshBuilder::new(
tlsh::BucketKind::Bucket128,
tlsh::ChecksumKind::ThreeByte,
tlsh::Version::Version4,
);
let file = File::open(&pb).unwrap();
let mut reader = BufReader::new(file);
let mut byte_read = 1;
... | Rust | 0 |
8 {
const MAX: u8 = 0xff;
}
struct Sum<A,B>(A,B);
impl<A: Unsigned, B: Unsigned> Unsigned for Sum<A,B> {
const MAX: u8 = A::MAX + B::MAX; //~ ERROR any use of this value will cause an error
}
fn foo<T>(_: T) -> &'static u8 {
&Sum::<U8,U8>::MAX //~ ERROR E0080
}
fn main() {
foo(0);
}
<gh_stars>0
// C... | Rust | 0 |
_id.
QuantityOpPathMismatch {},
/// Raised when a locked `Quantity` is trying to get locked again
DoubleLockedQuantity {},
/// Raised when a free `Quantity` is trying to get unlocked
DoubleUnlockedQuantity {},
/// Raised when a locked `Quantity` does not have a path_id in the `Wallet` it is t... | Rust | 0 |
1.x, p1.y, mem::size_of_val(&p1));
let p2 = Box::new(get_point());
println!("p2: x = {}; y = {}; takes {} bytes", p2.x, p2.y, mem::size_of_val(&p2));
println!("p2: len = {}", p2.len());
}
use std::collections::HashSet;
use crate::graph::Graph;
use crate::selection::components;
use crate::traversal::{ Dept... | Rust | 0 |
ank:shard_size *
(tensor_model_parallel_rank + 1)]
param_slice = param.data[shard_size * stride_id:shard_size *
(stride_id + 1)]
assert param_slice.shape == loaded_weight.shape
param_slice.copy_(loaded_weight)
... | Python | 1 |
s, ratios = build_inference_based_loaders(cfg, model)
loaders = [data_loader] + inference_based_loaders
ratios = [1.0] + ratios
combined_data_loader = build_combined_loader(cfg, loaders, ratios)
sample_counting_loader = SampleCountingLoader(combined_data_loader)
return sample_cou... | Python | 1 |
100 words.
If no reflection is needed, return "Things are going well".
Do not directly copy the previous reflection.
```
"""
def get_reflection_react_goal_prompt(
few_shot_example_prompt: str,
info_input: str,
message_prompt: str = "",
latest_message_prompt: str = "",
) -> str:
class PartialForma... | Python | 1 |
s,
object_split_bucket,
);
let (a_in, b_in) = output_buffer.split_at_mut(split_point);
let (a_out, b_out) = input_buffer.split_at_mut(split_point);
let (lhs, rhs) = {
cfg_if::cfg_if! {
if #[cfg(feature = "rayon")] {
... | Rust | 0 |
hmentResponse);
implement_from!(GetDatabaseResponse);
implement_from!(GetCollectionResponse);
implement_from!(CreateUserResponse);
implement_from!(DeleteAttachmentResponse);
implement_from!(ReplaceReferenceAttachmentResponse);
implement_from!(CreateReferenceAttachmentResponse);
implement_from!(ListAttachmentsResponse);... | Rust | 0 |
#!/usr/bin/python3
import unittest
import sys
sys.path.append('../util')
from iwd import IWD
from iwd import AdHocDevice
from config import ctx
import testutil
class Test(unittest.TestCase):
def validate_connection(self, wd, client=False):
dev1, dev2 = wd.list_devices(2)
self.assertIsNotNone(de... | Python | 1 |
import os
import string
import nltk
import re
_alphabet = set(string.ascii_lowercase + string.digits + ' ')
word_regexp = r"(?u)\b[a-zA-Z_][a-zA-Z_]+\b"
class NltkNormalizer:
def __init__(self):
self.install_nltk_corpora('stopwords', 'wordnet', 'punkt')
self.lemmatizer = nltk.WordNetLemmatizer()... | Python | 1 |
te',
),
],
))
if include_delete:
arr.append(dict(
item_type=ItemType.DELETE,
title='Remove remote',
uuid=f'{model.name}_delete',
actions=[
dict(
request=shared_request() | dict(
... | Python | 1 |
..Default::default()
});
// light
commands.spawn_bundle(LightBundle {
transform: Transform::from_xyz(4.0, 8.0, 4.0),
..Default::default()
});
commands
.spawn_bundle(LookTransformBundle {
transform: LookTransform {
eye: Vec3::new(-2.0, 2.... | Rust | 0 |
::LinearFee::new(
*constant.0.as_ref(),
*coefficient.0.as_ref(),
*certificate.0.as_ref(),
)))
}
pub fn calculate(&self, tx: Transaction) -> Value {
let fee_algorithm = match &self.0 {
FeeVariant::Linear(algorithm) => algorithm,
};
... | Rust | 0 |
# =========================
# iLiDAR
# utils.py
# Created by Bo Liang on 2024/12/8.
# =========================
import os
import shutil
def classification_by_event(input_folder, output_folder):
os.makedirs(output_folder, exist_ok=True)
files = os.listdir(input_folder)
for file in files:
if file.en... | Python | 1 |
import E_03_Dialog
from PyQt5 import QtWidgets
class MyDialog(QtWidgets.QDialog, E_03_Dialog.Ui_Dialog):
def __init__(self):
QtWidgets.QDialog.__init__(self)
E_03_Dialog.Ui_Dialog.__init__(self)
self.setupUi(self) | Python | 1 |
fn test_debug_id_debug() {
let id = DebugId::from_parts(
Uuid::parse_str("DFB8E43AF2423D73A453AEB6A777EF75").unwrap(),
10,
);
assert_eq!(
format!("{:?}", id),
"DebugId { uuid: \"dfb8e43a-f242-3d73-a453-aeb6a777ef75\", appendix: 10 }"
);
}
#[test]
#[cfg(feature = "with_s... | Rust | 0 |
ill check for these special cases and bail out early with the largest set found
if classes.contains(&CharacterClass::Unicode) {
return vec![CharacterClass::Unicode];
}
if classes.contains(&CharacterClass::AsciiPrintable) {
return vec![CharacterClass::AsciiPrintable];
}
// Mark off ... | Rust | 0 |
# Copyright 2025 SqueezeBits, Inc.
#
# 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 wri... | Python | 1 |
output_serialized = [serialize_output(block, o) for o in output]
else:
output_serialized = serialize_output(block, output)
model['outputs'].append(
dict(
data=out... | Python | 1 |
_FC_I_BW1_W<'a> {
w: &'a mut W,
}
impl<'a> RBB_CAP1_FC_I_BW1_W<'a> {
#[doc = r"Writes raw bits to the field"]
#[inline(always)]
pub unsafe fn bits(self, value: u8) -> &'a mut W {
self.w.bits = (self.w.bits & !(0x3f << 24)) | ((value as u32 & 0x3f) << 24);
self.w
}
}
#[doc = "Field `r... | Rust | 0 |
# Copyright 2016 The TensorFlow Authors. All Rights Reserved.
#
# 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 applica... | Python | 1 |
import sys
import os
project_root = os.path.abspath(os.path.join(os.path.dirname(__file__), '..', '..'))
if project_root not in sys.path:
sys.path.insert(0, project_root)
from google.adk.agents import Agent
from google.adk.tools import google_search
from app.core.config import DEFAULT_MODEL_ID, GOOGLE_API_KEY
from... | Python | 1 |
bpcbzxvnvnnxwhwnzj
2-4 c: ccctcc
7-10 t: kstttdlttn
6-7 b: bbbfbbb
13-14 c: txhkmvxwqjdjph
9-10 n: pknnpbstnnwztsjkfc
4-5 k: kqtqk
13-15 p: kndptjczrnqtphl
1-3 x: pxxxx
11-12 r: lrcgqtrmjjrrxhg
1-4 f: ffdf
7-18 d: cdddddsddddddddddd
4-10 r: rrrrrwrrrrrf
11-12 p: dpvmgjrmfspp
1-2 q: snqqqgq
11-12 x: fxxxhxxxlxbxxqx
3-4 ... | Rust | 0 |
# Adapted from https://github.com/flashinfer-ai/flashinfer/blob/4e8eb1879f9c3ba6d75511e5893183bf8f289a62/tests/test_bmm_fp8.py
import pytest
import torch
import torch.nn.functional as F
from sgl_kernel import bmm_fp8
def to_float8(x, dtype=torch.float8_e4m3fn):
finfo = torch.finfo(dtype)
min_val, max_val = x... | Python | 1 |
}mod error;
mod grid;
mod img;
use error::{print_error, print_warning};
use grid::{get_pixel_grid, PixelGrid};
use image::DynamicImage;
use img::{
get_image_list, get_random_image_url, get_temp_image, print_image, resize_image, ImageList,
};
use term_size::dimensions as get_terminal_dimensions;
use colored;
use st... | Rust | 0 |
(EscapeType::Null),
_ => ::std::option::Option::None
}
}
fn values() -> &'static [Self] {
static values: &'static [EscapeType] = &[
EscapeType::UnicodeEscape,
EscapeType::Octal,
EscapeType::Hexadecimal,
EscapeType::Reserved,
... | Rust | 0 |
), i32x4(!0, !0, 0, 0)));
assert!(eq_i32x4(i32x4(1, 2, 3, 4) >= i32x4(3, 2, 1, 0), i32x4(0, !0, !0, !0)));
assert!(eq_i32x4(i32x4(1, 2, 3, 4) > i32x4(3, 2, 1, 0), i32x4(0, 0, !0, !0)));
}
#![feature(test)]
extern crate test;
extern crate rand;
extern crate nalgebra as na;
use rand::{IsaacRng, Rng};
use test::... | Rust | 0 |
import setup_path
import cosysairsim as airsim
import cv2
import numpy as np
import os
import time
import tempfile
# connect to the AirSim simulator
client = airsim.CarClient()
client.confirmConnection()
client.enableApiControl(True)
print("API Control enabled: %s" % client.isApiControlEnabled())
car_controls = airsim... | Python | 1 |
t match standard config"
);
}
let f_memory = standard_plugboard_f_memory_settings();
for (index, case) in cases.iter().enumerate() {
let expected = case.config;
let got = f_memory[index];
assert_eq!(
expected, got,
... | Rust | 0 |
is a file')
if os.path.isdir(filepath): # make sure we're not overwriting another type of directory
if _init:
raise ValueError(f'directory {filepath} exists')
if 'config.pkl' in os.listdir(filepath):
valid = True
for fn in filter(lambda x: not x == 'config.pkl'... | Python | 1 |
)
rectangle_of_menu_window["rectangle_of_menu"][2]["right"] = rectangle_of_menu_window["rectangle_of_menu"][2]["left"] + rectangle_of_menu_window["rectangle_of_menu"][2]["width"]
rectangle_of_menu_window["rectangle_of_menu"][2]["bottom"] = rectangle_of_menu_window["rectangle_of_menu"][2]["top"] + rectangle_of_menu_wind... | Python | 1 |
334a6850509ae7794d410524b061740000000000ffffffffc16d35d26589dfd54634181aa4a290cb9e06a716ea68620be05fbc46f1e197140100000000ffffffff0200e1f50500000000160014751e76e8199196d454941c45d1b3a323f1433bd620544771000000001600144dc2412fe3dc759e3830b6fb360264c8ce0abe3800000000";
/// let pubkey = Pubkey::from_str("03d34d21d3017acd... | Rust | 0 |
et mut mem: Vec<u8> = text.as_bytes().iter().cloned().collect();
mem.reserve(32);
let mut offsets: Offsets = Default::default();
let (in_quote, in_cr) =
unsafe { generic::find_indexes_csv::<V>(&mem[..], &mut offsets, 0, 0) };
assert_ne!(in_quote, 0);
assert_eq!(in_cr,... | Rust | 0 |
xHPS0S,*H@H HxHP H@H HxHPH{о [ [ÐATUISHHH9]t3LHU[]A\SH@ Ƈ Ƈ H HHlX HlX t H;HD HЄuH{X [ÐUS@HHH Ht tHnZ1[]HHHH+WHH vEHH H
HHH HHpH4H H)HpH6H HHpHHxHHÐUSHHH(HLHH{HH6H(H[]ATUISHHHI$HCpgX HuH{HH@IT$H/[]A\HH H] USHHvHHHE HChX HH@HUHX[]SHHHG... | Python | 1 |
into();
value.into_deserializer().deserialize_any(visitor)
}
}
/// Реализует разбор простых типов данных.
///
/// # Параметры
/// - `dser_method`: реализуемый макросом метод
/// - `visit_method`: метод типажа [`Visitor`], который будет вызван для создания конечного значения
/// - `type`: тип GFF файла, одно из з... | Rust | 0 |
"ctype",
postgresql.ENUM("text", "redshift", name="comment_types"),
autoincrement=False,
nullable=True,
),
)
op.drop_index(
op.f("ix_group_comments_on_spectra_created_at"),
table_name="group_comments_on_spectra",
)
op.drop_index(
... | Python | 1 |
# Spessore della riga
canvas.line(
doc.leftMargin, # Punto x iniziale
doc.bottomMargin - 65, # Punto y (leggermente sopra il testo del footer)
doc.width + doc.leftMargin, # Punto x finale (larghezza totale)
doc.bottomMargin - 65 # Punto y finale (stesso y iniziale)
)
fo... | Python | 1 |
n = tid % allowed.NumCPUs() as i32;
// ... then pick the nth CPU in allowed.
let mut cpu = 0;
allowed.ForEachCPU(|c| {
n -= 1;
if n == 0 {
cpu = c as i32;
}
});
return cpu;
}
impl Task {
pub fn CPU(&self) -> i32 {
/*let k = self.Thread().lock().k.cl... | Rust | 0 |
import numpy as np
import matplotlib.pyplot as plt
from scipy.interpolate import RegularGridInterpolator
import tifffile
from mpl_toolkits.mplot3d import Axes3D
from matplotlib.widgets import Slider
# Load TIFF data
tiff_data = tifffile.imread('data/1300kDa uncropped 22V for 30s.tif')
# Downsample the data for faster... | Python | 1 |
me(value) => {
info!("{}.{}: connect ok {}:{}", tid, id, value.host, value.port);
let _ = value.sender.send(EntryMessage::ConnectOk(buf)).await;
}
None => {
info!("{}.{}: connect unknown... | Rust | 0 |
ay_name}_error", {"message": msg})
except Exception as e:
msg = f"Error reading/parsing zmap6 output file for {plugin_display_name} {output_file_path}: {e}"
self.error(msg)
if progress_cb: progress_cb(f"{plugin_display_name}_error", {"message":... | Python | 1 |
HINT,
);
}
}
}
}
}
#[cfg(test)]
mod tests {
use super::*;
// Some tests are derived from
// https://github.com/eslint/eslint/blob/v7.10.0/tests/lib/rules/no-class-assign.js
// MIT Licensed.
#[test]
fn no_class_assign_valid() {
assert_lint_ok! {
NoClassAssi... | Rust | 0 |
rs, _, sample_negs = batch
recommend_output = self.model(input_ids)
test_neg_items = torch.cat((answers.unsqueeze(-1), sample_negs), -1)
recommend_output = recommend_output[:, -1, :]
test_logits = self.predict_sample(recommend_output, test... | Python | 1 |
d, s_t = list(map(int, input().split()))
t_s = 0
l_h = list()
l_t = list()
for i in range(d):
l_h.append(list(map(int, input().split())))
s_t -= l_h[i][0]
t_s += l_h[i][1] - l_h[i][0]
if s_t < 0:
print("NO")
elif s_t <= t_s:
print("YES")
for h in l_h:
print(h[0] + min(s_t, h[1... | Python | 1 |
asset and reserve of buying asset.
/// Formula : SELL_RESERVE * AMOUNT / (BUY_RESERVE - AMOUNT )
///
/// - `sell_reserve` - reserve amount of selling asset
/// - `buy_reserve` - reserve amount of buying asset
/// - `amount` - buy amount
///
/// Returns None in case of error
pub fn calculate_buy_price(sell_reserve: Bal... | Rust | 0 |
import argparse
import subprocess
import os.path as osp
from utils.download_model import download_model
parser = argparse.ArgumentParser()
parser.add_argument('images', type=str, help='Directory of images to run the model on') # noqa
parser.add_argument('--out-dir', type=str, default='', help='Directory to write pre... | Python | 1 |
position: x: {}, y: {}", pos.x, pos.y);
/// ```
#[macro_export]
macro_rules! debug {
(logger: $logger:expr, $($arg:tt)+) => (
$crate::log!(logger: $logger, $crate::Level::Debug, $($arg)+)
);
($($arg:tt)+) => (
$crate::log!($crate::Level::Debug, $($arg)+)
)
}
/// Logs a message at the t... | Rust | 0 |
yName(message_type, request)
message_controls = build_controls_list(controls)
if message_controls is not None:
ldap_message['controls'] = message_controls
asn1_request = BaseStrategy.decode_request(message_type, request, controls)
self.... | Python | 1 |
y).powi(2)).sqrt()
}
fn norm((a_x, a_y) : (f64, f64)) -> f64 {
(a_x.powi(2) + a_y.powi(2)).sqrt()
}
pub struct ChessboardDetectorParameters {
pub r: f64,
pub p: f64,
pub d: f64,
pub t: f64,
pub corner_distance: u32,
}
pub fn compute_adaptive_parameters(a_min: f64, a_max: f64) -... | Rust | 0 |
.env("message", message)
.status()
.map_err(|e| format!("run shell cmd:{} fail:{}", self.command, e))?
.code()
.map_or("None".to_string(), |v| v.to_string()))
}
}
use std::collections::HashMap;
use std::fmt::{Debug, Formatter};
use std::ops::{Deref, DerefMut};
use... | Rust | 0 |
n down
#[serde(rename = "4")]
KnockInDown,
/// Knock-out up
#[serde(rename = "5")]
KnockOutUp,
/// Knock-out down
#[serde(rename = "6")]
KnockOutDown,
/// Underlying
#[serde(rename = "7")]
Underlying,
/// Reset Barrier
#[serde(rename = "8")]
ResetBarrier,
/// Rolling Barrier
#[serde(rename = "9")]
Roll... | Rust | 0 |
_relu() {
let x = Tensor1D::new([-2.0, -1.0, 0.0, 1.0, 2.0]);
let r = x.trace().relu();
assert_eq!(r.data(), &[0.0, 0.0, 0.0, 1.0, 2.0]);
// NOTE: call .exp() to make sure we cover cases where .relu() uses the result's gradient
let gradients = r.exp().mean().backward();
a... | Rust | 0 |
import json
ace2004_entities = ['FAC', 'GPE', 'LOC', 'ORG', 'PER', 'VEH', 'WEA']
ace2004_entities_full = ["facility","geo political","location","organization","person","vehicle","weapon"]
ace2004_relations = ['ART', 'EMP-ORG', 'GPE-AFF', 'OTHER-AFF', 'PER-SOC', 'PHYS']
ace2004_relations_full = ['artifact','employment... | Python | 1 |
fn bindgen_test_layout_rlRfRxSaturationCqData() {
assert_eq!(
::core::mem::size_of::<rlRfRxSaturationCqData>(),
128usize,
concat!("Size of: ", stringify!(rlRfRxSaturationCqData))
);
assert_eq!(
::core::mem::align_of::<rlRfRxSaturationCqData>(),
1usize,
concat... | Rust | 0 |
"blue")
axs4[0].set_ylabel("FORCE FL")
axs4[1].plot(timestamps, FR_forces[:, 2], label="Ground Truth", color="blue")
axs4[1].set_ylabel("FORCE FR")
axs4[2].plot(timestamps, RL_forces[:, 2], label="Ground Truth", color="blue")
axs4[2].set_ylabel("FORCE RL")
axs4[3].plot(timestamps, RR_forces[:... | Python | 1 |
s, 0, p);
setrow(rhs, n - 1, o);
m.solve(rhs)
}
EndConditions::ParabolicBlending => {
m.set(0, 0, 1.);
m.set(n - 1, n - 1, 1.);
setup_mat(m, pts, tb, explicit_tgts, rhs);
// see 3.19 expanded hoschek
let p = o + e!(pts... | Rust | 0 |
import requests
import logging
import time
# 设置详细日志
logging.basicConfig(level=logging.DEBUG)
# 测试URL
urls = [
"https://static.cninfo.com.cn/finalpage/2025-04-23/1223214399.pdf",
"https://static.cninfo.com.cn/finalpage/2025-04-23/1223214399.PDF"
]
# 更完整的请求头,模拟真实浏览器
headers = {
'User-Agent': 'Mozilla/5.0 (... | Python | 1 |
if rng.sample(unsafe {
match CORNACOPIA_FOOD_DISTRIBUTION {
Some(val) => val,
None => Bernoulli::new(0.0).unwrap(),
}
}) {
cell.food += unsafe { CORNACOPIA_FOOD_SPAWN };
... | Rust | 0 |
': 'LLM metadata update',
},
{
'content': 'A head-to-head comparison between Claude 4 and Gemini 2.5 Pro shows that Claude 4 outperforms in 87% of tasks, particularly excelling in reasoning, coding, and factual accuracy. This marks a shift in the LLM landscape with Anthropic taking the lead.',
'... | Python | 1 |
import re
import requests
# from bs4 import BeautifulSoup
cookies = {
XXXXX
}
headers = {
'accept': 'text/html,application/xhtml+xml,application/xml;q=0.9,image/avif,image/webp,image/apng,*/*;q=0.8,application/signed-exchange;v=b3;q=0.7',
'accept-language': 'zh-TW,zh;q=0.9,en-US;q=0.8... | Python | 1 |
import cv2
from ultralytics import YOLO
def contar_pessoas(imagem_path):
# Carregar o modelo pré-treinado YOLO
modelo = YOLO('yolov8n.pt') # Modelo YOLOv8
# Carregar a imagem
imagem = cv2.imread(imagem_path)
if imagem is None:
raise FileNotFoundError("Imagem não encontrada.")
# Faze... | Python | 1 |
at_input('What is up?'):
# Display user message in chat message container
with st.chat_message('user', avatar=user_avator):
st.markdown(prompt)
print("用户输入问题:\n"+prompt)
print("--------------------------------------")
# Add user message to chat history
st.sess... | Python | 1 |
u64; 10]; 21];
// Let's work with pos - 1 as pos for now, indexes nicer;
let pos = pos as usize - 1;
let mut alive = [0; MAX_TURNS];
let mut wins = [0; MAX_TURNS];
alive[0] = 1;
let mut current = [[0u64; 10]; 21];
current[0][pos] = 1;
let mut next = [[0u64; 10]; 21];
let mut hel... | Rust | 0 |
dth=px(1)
)
)
# 基础Card展示标题
basic_section_title = Label(
"📋 基础Card样式",
font_size=22,
font_weight="bold",
color="#34495e",
text_align="center",
style=ComponentStyle(
margin_top=px(20),
margin_bottom=px(30)
)
)
... | Python | 1 |
---------------- #
# -------------------- Dataset for SHL NPZ files -------------------- #
# ----------------------------------------------------------------------------- #
class SHLNpzDataset(Dataset):
"""
Dataset that loads preprocessed NPZ files containing SHL sensor data.
Each sample:
X : ... | Python | 1 |
pl<'a> Drop for Lpuart1<'a> {
fn drop(&mut self) {
self.pcc.pcc_lpuart1.reset();
}
}
impl<'a> Drop for Can0<'a> {
fn drop(&mut self) {
self.pcc.pcc_flex_can0.reset();
}
}
extern crate rotor;
extern crate c_ares;
#[macro_use]
extern crate log;
use std::thread::{JoinHandle, Builder};
use... | Rust | 0 |
import pytest
import torch
from mmdet.models.backbones import RegNet
regnet_test_data = [
('regnetx_400mf',
dict(w0=24, wa=24.48, wm=2.54, group_w=16, depth=22,
bot_mul=1.0), [32, 64, 160, 384]),
('regnetx_800mf',
dict(w0=56, wa=35.73, wm=2.28, group_w=16, depth=16,
bot_mul=1.0),... | Python | 1 |
ADD_WHAT_CONTENT = (
'你想记录什么内容呢?',
'你想记下什么?',
'你想让我帮你记录什么呢?',
'要记录的内容是?',
)
ADD_SUCCESS = (
'好的,记下了,ID 是 {id}',
'记下了,ID 是 {id}',
'好的,记下了',
)
LIST_EMPTY = (
'你还没有记录任何笔记',
'你还没有添加过笔记呢',
'现在还没有笔记哦',
)
LIST_COMPLETE = (
'好了,一共就这些',
'好了,就这 {count} 条',
'以上就是所有的笔记了',
... | Python | 1 |
'''
This code is highly based on https://github.com/carpedm20/deep-rl-tensorflow/blob/master/agents/statistic.py
'''
import tensorflow as tf
import numpy as np
import baselines.common.tf_util as U
class stats():
def __init__(self, scalar_keys=[], histogram_keys=[]):
self.scalar_keys = scalar_keys
... | Python | 1 |
__enter__(&mut self) {
self.enable();
}
fn __exit__(
&mut self,
_exc_type: Option<&PyAny>,
_exc_value: Option<&PyAny>,
_traceback: Option<&PyAny>,
) {
self.disable();
}
}
const PY_TRACE_CALL: i32 = 0;
const PY_TRACE_RETURN: i32 = 3;
const PY_TRACE_C_CAL... | Rust | 0 |
import numpy as np
import pandas as pd
import sympy as sp
import matplotlib.pyplot as plt
import plotly.express as px
from mpl_toolkits.mplot3d import Axes3D
from sklearn.linear_model import LinearRegression
from scipy.optimize import curve_fit
# Constants
diameter_cm = 3.00 # cm
field_T = 0.500 # T
hall_voltage_mv ... | Python | 1 |
se)
print("\nPlotting the actual scores vs predicted scores...")
# Function to plot the actual values vs the predicted values for both targets
def predictions_plot(predict, actual, color, label, max_score):
fig, ax = plt.subplots(figsize=(8, 8))
fig.tight_layout(pad=5)
# Create the plot
sns.scatterpl... | Python | 1 |
# 1. Mode write
# dia ini akan membuat file baru jika tidak ada, lalu
# akan menimpa atau overwrite isinya
# encoding --> agar jelas character" nya dengan uts-8
with open(
"D:\BELAJAR FT MY CODING\BELAJAR PYTHON\BELAJAR_PYTHON\[ 65 ] Write External File\data_1.txt",
"w",
encoding="utf-8",
) as file:
f... | Python | 1 |
import bpy, math, os, platform, subprocess, sys, re, shutil
def ShowMessageBox(message = "", title = "Message Box", icon = 'INFO'):
def draw(self, context):
self.layout.label(text=message)
bpy.context.window_manager.popup_menu(draw, title = title, icon = icon)
class TLM_Install_OpenCV(bpy.types.Oper... | Python | 1 |
from flask import Flask, render_template, request, jsonify
# from openai import OpenAI # 注释掉 OpenAI 的导入
import qianfan # 导入 Qianfan 库
import markdown
from utils.get_yaml_data import *
app = Flask(__name__)
# 使用 Qianfan 的 AccessKey 和 SecretKey
chat_completion = qianfan.ChatCompletion(
ak="QMoXrcUZxBiTms0lEXq8sIF... | Python | 1 |
# wm....mw
# .w..ww..
# ..wm.wwm
# w.w....w
# .m.c.m..
# w.....w.
def f():
n, m = map(int, input().split())
pre_grid = [list(input()) for _ in range(n)]
pre_coid = [pre_grid[i].copy() for i in range(n)]
for i in range(n):
for j in range(m):
if pre_coid[i][j] == 'w':
p... | Python | 1 |
class Solution:
def minOperations(self, nums: List[int]) -> int:
ans = 0
last = 0
for num in nums:
ans += max(0, last - num + 1)
last = max(num, last + 1)
return ans
| Python | 1 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.