text string | label_name string | labels int64 |
|---|---|---|
from abc import ABC, abstractmethod
from typing import Generic, Type, Self, List
from generic_types import TEvent
from subscriber import ISubscriber
from publisher import IPublisher
from uuid import UUID
class IAsyncEventBus(ABC, Generic[TEvent]):
@abstractmethod
async def publish(self, event: TEvent) -> bool:... | Python | 1 |
a>),
/// This is a type created when we see array() literal
AKempty,
}
/// This is a direct translation of aast_defs::Tprim.
///
/// Why don't we directly use a reference to aast_defs::Tprim in the
/// Tprim constructor?
///
/// 1. Tatom contains a string, that we might want to allocate during
/// type ... | Rust | 0 |
let pitch = view_input.1 as f32 / window_size.height as f32
* std::f32::consts::PI
- 0.5;//50 mm lens
let view = Matrix4::from_angle_x(cgmath::Rad(pitch)) * Matrix4::from_angle_y(cgmath::Rad(yaw));
let mut perspective = f.last_perspective.borrow... | Rust | 0 |
import pandas as pd
def load_data(file_path, n_rows=None):
"""
Loads the dataset and returns the specified number of rows.
:param file_path: The file path of the dataset.
:param n_rows: Number of rows to load (Default: loads all rows).
:return: The loaded dataset (DataFrame).
"""
df = pd.r... | Python | 1 |
e the actual job data is on a second line, we need additional parsing
// extract it from the buffer.
match response {
Response::Pre(pre) => {
if let Some(job) = self.parse_job(src, pre)? {
self.outstart = 0;
... | Rust | 0 |
verifica01 = input("Digite a letra correspondente ao sexo (F/M): ")
if verifica01 == 'F' or verifica01 == 'f':
print("A pessoa é Feminino!")
elif verifica01 == 'M' or verifica01 == 'm':
print("A pesso é Masculina!")
else:
print("Sexo inválido!!") | Python | 1 |
}
pub fn tex(&self) -> &Texture {
&self.tex
}
}
<filename>spath_rust/src/console.rs<gh_stars>0
use alloc::String;
use alloc::Vec;
use debug::*;
const CONSOLE_BASE: u64 = 0xF711_2000;
const CONSOLE_FR: u64 = 0x018;
const CONSOLE_FLAG_RXFIFO_EMPTY: u32 = (1 << 4);
const CONSOLE_FLAG_TXFIFO_FULL: u3... | Rust | 0 |
related to training on large web corpora. Finally, we find that GPT-3 can generate samples of news articles which human evaluators have difficulty distinguishing from articles written by humans. We discuss broader societal impacts of this finding and of GPT-3 in general.""",
),
(
... | Python | 1 |
Rng};
#[test]
fn test_trace_indep() {
let mut rng = rand::thread_rng();
// Need a context with at least 2 keypairs in it
let Context {
msg,
tag,
mut keypairs,
} = rand_ctx(&mut rng, 2);
// Pick two distinct privkeys to ... | Rust | 0 |
讀取API密鑰環境變數
api_key = os.getenv('My_API')
prompt = f"{texts},勿翻譯原文,按照原文順序進行以下欄位分類:姓名,職稱,公司名稱,地址,電話,Email,網址,嚴格審查公司名稱,若無不要回傳"
# 使用request模組串接API
response = requests.post(
'https://api.openai.com/v1/chat/completions',
headers = {
'Content-Type': 'application/json',
... | Python | 1 |
mod delete_emoji;
mod get_emoji;
mod get_emojis;
mod update_emoji;
pub use self::{
create_emoji::CreateEmoji, delete_emoji::DeleteEmoji, get_emoji::GetEmoji,
get_emojis::GetEmojis, update_emoji::UpdateEmoji,
};
pub mod maths;
pub mod new;
pub mod series_f64;
use linalg::vectors::floats::FloatsVector;
use ser... | Rust | 0 |
update(new_kw)
def __repr__(self):
return "%s(class_=%r%s)" % (
self.__class__.__name__,
self.class_.__name__,
", ".join("%s=%r" % (k, v) for k, v in self.kw.items())
)
_sessions = weakref.WeakValueDictionary()
def make_transien... | Python | 1 |
import streamlit as st
from knowledge_base import answer_query
import pandas as pd
from semantic_cache import save_response, query_cache
from utils import lst_text_models, lst_embedding_models
from botocore.exceptions import ClientError
def main():
st.title(f":rainbow[RAG with Amazon Bedrock and a Semantic Cache]"... | Python | 1 |
let (res, res_body) = send_request(cert, request)?;
match check_response(&res, &res_body) {
Ok(()) => {
return Ok((res, res_body));
}
Err(e) => {
if !e.is_recoverable() {
let msg = format!("HTTP error: {}: {}", res.status_c... | Rust | 0 |
ObjDisConnect(songObj)
del self._songObjs[songId]
if songId in self._songsDict:
del self._songsDict[songId]
keys = self._songsDict['index']
if songId in keys:
keys.remove(songId)
self._songsDict['index'] = keys
for index, ... | Python | 1 |
plugin.net/json.gp'
]
for api_url in apis:
try:
response = get(api_url, timeout=5)
if response.status_code == 200:
data = response.json()
... | Python | 1 |
t("flash", msg.msg());
}
Template::render("login", &context)
}
#[get("/home")]
fn user_index(user: db::user::UserId) -> Template {
println!("login user 3");
let mut context = HashMap::new();
context.insert("user_id", user);
Template::render("index", &context)
}
#[get("/home", rank = 2)]
fn in... | Rust | 0 |
# Copyright (C) 2023 CVAT.ai Corporation
#
# SPDX-License-Identifier: MIT
from .driver import BadFunctionError, annotate_task
from .interface import (
DetectionFunction,
DetectionFunctionContext,
DetectionFunctionSpec,
keypoint,
keypoint_spec,
label_spec,
rectangle,
shape,
skeleton,... | Python | 1 |
a> GAIN_CTRL3_ROSDAC_I_BW0_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 << 6)) | ((value as u32 & 0x3f) << 6);
self.w
}
}
#[doc = "Field `gain_ctrl3_rosdac_q_bw0` reader - "]
pub ... | Rust | 0 |
# Конструкция ON CONFLICT (session_id) DO NOTHING предотвращает дублирование записей.
for session in data.get('user_sessions', []):
cur.execute("""
INSERT INTO user_sessions (session_id, user_id, start_time, end_time, pages_visited, device, actions)
VALUES (%s, %s, %s, %s, %s, %s, ... | Python | 1 |
normalized by adjusting exponent
if half_exp == 0 {
// Calculate how much to adjust the exponent by
let e = (half_man as u16).leading_zeros() - 9;
// Rebias and adjust exponent
let exp = ((1023 - 127 - e) as u64) << 52;
let man = (half_man << (46 + e)) & 0xF_FFFF_FFFF_FFFFu... | Rust | 0 |
#[strum(serialize = "PHASERS")]
Phasers = 4,
#[strum(serialize = "PHOTON TORPEDOES")]
PhotonTorpedos = 5,
#[strum(serialize = "GALACTIC RECORDS")]
GalacticRecords = 6,
#[strum(serialize = "QUIT")]
Quit = -99,
}
impl Display for Command {
fn fmt(&self, f: &mut Formatter<'_>) -> std::... | Rust | 0 |
fib(n - 1) + fib(n - 2)
//! }
//! }
//! }
//! Fib {}
//! };
//!
//! assert_eq!(55, fib.call(10));
//! ```
//!
//! or if the function doesn't capture anything,
//! you can use `recur_fn` macro.
//!
//! ```
//! use recur_fn::{recur_fn, RecurFn};
//!
//! let fact = recur_fn!(fact(n: i32) ... | Rust | 0 |
height(network).unwrap().0;
// Load previous block (the block before the activation block of the given network upgrade)
let block_prev = Arc::new(
blocks
.get(&(height - 1))
.expect("test vector exists")
.zcash_deserialize_into::<Block>()
.expect("block i... | Rust | 0 |
rprint(f"\n[bold green]💳 Payment Performance Metrics[/bold green]")
if payment_data['total_payments'] > 0:
success_rate = (payment_data['successful_payments'] / payment_data['total_payments']) * 100
rprint(f" Success Rate: [green]{success_rate:.1f}%[/green]")
... | Python | 1 |
let res = instantiate(deps.as_mut(), mock_env(), info, msg.clone()).unwrap_err();
match res {
ContractError::Std(StdError::GenericErr { msg, .. }) => {
assert_eq!(
msg,
"linear_growth must be higher than min_linear_growth".to_string()
)
}
... | Rust | 0 |
(self.bits >> 28) & 0x01) != 0)
}
#[doc = "Bit 27"]
#[inline(always)]
pub fn brown_out_rst_sel(&self) -> BROWN_OUT_RST_SEL_R {
BROWN_OUT_RST_SEL_R::new(((self.bits >> 27) & 0x01) != 0)
}
#[doc = "Bit 26"]
#[inline(always)]
pub fn brown_out_rst_ena(&self) -> BROWN_OUT_RST_ENA_R {
... | Rust | 0 |
as_sandwich(s)
}
fn nicer_count(input: &str) -> usize {
input.lines()
.filter(|line| nicer(line))
.count()
}
#[cfg(test)]
mod test {
use super::{nice, nicer};
#[test]
fn examples_1() {
assert_eq!(nice("ugknbfddgicrmopn"), true);
assert_eq!(nice("aaa"), true);
... | Rust | 0 |
report descriptor size"));
+ }
+ let size = desc.ucrd_size as usize;
+ let value = Vec::from(&desc.ucrd_data[..size]);
+ Ok(ReportDescriptor { value })
+}
+
+pub fn is_u2f_device(fd: &Fd) -> bool {
+ match read_report_descriptor(fd) {
+ Ok(desc) => has_fido_usage(desc),
+ Err(_) => false,
... | Rust | 0 |
ut register = fs::OpenOptions::new()
.write(true)
.open(register)
.context("Open binfmt misc for registration")?;
register
.write_all(&spec)
.context("Couldn't register binfmt")?;
... | Rust | 0 |
Title,
};
extern crate rand;
extern crate rand_core;
extern crate rand_xorshift;
extern crate statrs;
extern crate getopts;
extern crate toml;
#[macro_use]
extern crate serde_derive;
extern crate usiagent;
extern crate simplenn;
extern crate csaparser;
extern crate packedsfen;
pub mod player;
pub mod solver;
pub mod ... | Rust | 0 |
from datetime import datetime, timezone, timedelta
from typing import Iterable, Dict, Tuple, List, Any
import httpx
# Setting column variables
HOURLY_VARS = "temperature_2m,relative_humidity_2m,precipitation,windspeed_10m"
def build_url(lat: float, lon:float, start:datetime, hours:int) -> str:
"""
Building re... | Python | 1 |
before filtering
jta_cluster = self._traverse(model, TOPOLOGY, CLUSTER, 'staticCluster', self._jta_cluster)
self.assertEqual(True, self._jta_cluster_info_list in jta_cluster,
self._jta_cluster_info_list + " should be in " + self._jta_cluster + " before filtering")
aut... | Python | 1 |
, 'Ş', 't', 'ᬧ', '𝝻', 'ꐾ', '𝕨', '𑒔', 'ᗖ', 'ꩡ',
'㊉', '\u{e0197}', 'ꫂ', '𝣍', 'ᯃ', '⑳', 'ป', '\u{11c9a}', '\u{e0129}', 'ꑮ',
'ꝃ', '𘣵', '𐛊', '\u{18b8b}', '𛉾', 'ꠘ', '𓀑', '𐧔', '🄚', '\u{1e107}',
'⚁', 'ㆃ', '🥚', '𝝩', 'ⵈ', '𞣁', '𛉵', '𓃩', '🤋', 'ᘞ', '\u{1fb60}',
'𒊎', '𖹯', '\u{1fb33}', 'ᔚ', '𑙤', '�... | Rust | 0 |
"Repository parts cannot be empty"
def test_unique_constraints(self):
"""Test unique constraint validation."""
tasks = [
{"id": "task_1", "title": "Task 1"},
{"id": "task_2", "title": "Task 2"},
{"id": "task_1", "title": "Duplicate Task"} # Duplicate ID
... | Python | 1 |
}
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.
// Tracking of s... | Rust | 0 |
# How To Copy Dictionary Works:
# Using copy() method, we can make a copy of a dictionary:
D = {
'name' : 'Ritu',
'Dept' : 'CSE',
'Roll' : 13
}
x = D.copy()
print(x)
# Output: {'name': 'Ritu', 'Dept': 'CSE', 'Roll': 13}
# Using dict() function, we can make a copy of a dictionary:
D = {
'name' : 'Ritu'... | Python | 1 |
{}", command),
};
}
fn split<F: Field + Debug + Display, S: Shamir<F>>(args: &ArgMatches, k: usize, n: usize)
where
S::Share: Display,
{
let secret = match args.value_of("secret") {
None => {
let mut rng = thread_rng();
F::uniform(&mut rng)
}
Some(filename) =... | Rust | 0 |
t)
res.log_print()
res = client.update_alert(project, alert_detail)
res.log_print()
res = client.delete_alert(project, alert)
res.log_print()
res = client.delete_dashboard(project, dashboard_for_alert)
res.log_print()
savedsearch = savedsearch_detail.get('savedsearchName')
res = ... | Python | 1 |
record['R2'].append(max_r2)
record['R'].append(max_r)
record['RMSE'].append(min_rmse)
record['epoch'].append(record_epoch)
losses.append(min_loss)
R2s.append(max_r2)
RMSEs.append(min_rmse)
Rs.append(max_r)
record['trail'].append(trial.number)
record['hi... | Python | 1 |
_name, Position { x: pos_x, y: pos_y }, Velocity { x: vel_x, y: vel_y }));
// }
// }
Ok(result)
}
/// Function exported exclusively for the use of the Master module.
/// Sets the velocity of the worker ids to zero.
pub fn stop_workers(
conn: &PgConnection,
w_ids: &[i32],
_logger: &Logger,
... | Rust | 0 |
]).unwrap();
let memberships = stack(Axis(0), &[memberships_1.view(), memberships_2.view()]).unwrap();
// Does it work?
let centroids = compute_centroids(2, &observations, &memberships);
assert_abs_diff_eq!(
centroids.index_axis(Axis(0), 0),
expected_centroid_1,
... | Rust | 0 |
## @example real_time_line_plotter.py
# This example performs image segmentaton on a stream of ultrasound images with a neural network,
# calculates the area of the segmentation regions and then plots the area curves over time using the
# LinePlotter.
#
# @m_class{m-block m-warning} @par PySide2 Qt Version
# @parblock
... | Python | 1 |
Err(e))
}
impl<T, E> Future for FutureResult<T, E> {
type Item = T;
type Error = E;
fn poll(&mut self) -> Poll<T, E> {
self.inner.take().expect("cannot poll Result twice").map(Async::Ready)
}
}
impl<T, E> From<Result<T, E>> for FutureResult<T, E> {
fn from(r: Result<T, E>) -> Self {
... | Rust | 0 |
from typing import Final
from rotkehlchen.chain.evm.types import string_to_evm_address
CPT_SAFE: Final = 'safe'
SAFE_VESTING: Final = string_to_evm_address('0x96B71e2551915d98d22c448b040A3BC4801eA4ff')
SAFEPASS_AIRDROP: Final = string_to_evm_address('0x57eC1930f3E5c8062926c2F3ee49316E116143df')
SAFE_LOCKING: Final = ... | Python | 1 |
erate(){
if name.cmp(track_name)==Ordering::Equal{
return Some(c)
}
}
None
}
fn remove_track_inner(&mut self,name:&str)->Option<Vec<Set>>{
if let Some(set)=self.search_track(name){
self.names.remove(set);
Some(self.track_s... | Rust | 0 |
print("max_bound: ", self.voxels_bounds_max)
# 有点云落在其中的map索引:
voxel_filled = np.array(np.where(eye_map == 1)).T
# print("voxel_filled.shape: ", voxel_filled.shape)
# 建立target_map,将目标点所在位置map值设为1
target_idx = self.point2voxelidx(target_points)
# print("target_idx: ", targ... | Python | 1 |
# my_string="""
# hello world
# apple
# """
# my_string[0] = 'b'
# print(my_string)
# # print(my_string[1:-1])
# print(type(my_string))
name='ram'
last_name='dksfjdkls'
print('hello {} {} k gardai chau '.format(last_name,name)) | Python | 1 |
await;
} else {
dht_db_cache
.set_activity_ready_to_integrate(op.header().author(), op.header().header_seq())
.await?;
}
}
Ok(())
}
fn insert_locally_validated_op(
txn: &mut Transaction,
op: DhtOpHashed,
) -> StateMutationResult<Option<DhtOpHa... | Rust | 0 |
, &config)?;
set_contract_version(deps.storage, CONTRACT_NAME, CONTRACT_VERSION)?;
Ok(Response::new())
}
#[cfg_attr(not(feature = "library"), entry_point)]
pub fn execute(
deps: DepsMut,
env: Env,
info: MessageInfo,
msg: ExecuteMsg,
) -> Result<Response<Empty>, ContractError> {
match msg {... | Rust | 0 |
background-color: #f0f2f6; border-radius: 20px;
transition: all 0.3s ease; border: 1px solid #e0e0e0;">
<svg width="20" height="20" fill="currentColor" viewBox="0 0 24 24">
<path d="M12 0c-6.626 0-12 5.373-12... | Python | 1 |
haracterBuilder()
.set_basic_info("智慧法师", CharacterClass.MAGE)
.set_level(20)
.set_attributes(strength=8, agility=12, intelligence=35, vitality=15, luck=15)
.add_skill("火球术", 8, "发射火球攻击敌人")
.add_skill("冰冻术", 6, "冻结敌人")
.add_skill("传送术", 4, "瞬间移动")
... | Python | 1 |
e_text,
state=sstate,
small_image="logo",
small_text="Apex Presence",
)
self.display_message(f"{sdetails} on {sstate}", "black", "14000")
if self.rich_presence_checkbox.get() == 1:
sleep(14)
self.mainthr... | Python | 1 |
te = args.sample_rate
enc_model = args.encoder # default="../models/encoder.onnx"
dec_model = args.decoder # default="../models/decoder.onnx"
language = args.language # default: ZH_MIX_EN
if language == "ZH":
language = "ZH_MIX_EN"
print(f"sentence: {sentence}")
print(f"sample_rate: {sa... | Python | 1 |
pub_point_Q = QL[0]
# RD = diff_comb(RQ)
RD = diff_comb_idx(RQ)
print('RQ = ')
for i in RQ: print(f'{i.hex()}')
print('='*70);
print('RD = ')
for i in RD: print(f'{i[2].hex()}')
print('-'*120)
for i in RD:
if i[2] == ZERO: print(f'Duplicate R Found. Congrats!. {i[0], i[1], i[2].hex()}')
#=========================... | Python | 1 |
();
//! ```
//!
//! [`BareReport`]: struct.BareReport.html
//! [`body`]: struct.BareReport.html#structfield.body
//! [`Value`]: https://docs.rs/serde_json/*/serde_json/value/enum.Value.html
//! [`parse`]: struct.BareReport.html#method.parse
//!
//! Note that [`parse`][]'s return value is wrapped in _both_ [`Option`][] ... | Rust | 0 |
F:Future<Output = ()> + Send + 'static,
{
Task::spawn(future, &self.sender)
}
/// 运行执行器
///
/// 这将启动执行器循环,并无限的运行,没有实现关机的机制
///
/// 任务从 scheduled 通道的 receiver方出来. 在channel上接收一个任务表明任务已经准备好被执行了.
/// 这发生在任务首次被创建和任务被唤醒时.
fn run(&self) {
println!("execute MiniTokio run me... | Rust | 0 |
ature = "dev"))]
pub GPIO_30: p0::P0_30<Input<Floating>>,
/// DWM1001: GPIO_31; nRF52: P0.31
///
/// This field is only available, if the `dev` feature is disabled.
/// Otherwise the pin is used for an LED on the DWM1001-Dev board.
#[cfg(not(feature = "dev"))]
pub GPIO_31: p0::P0_31<Input<F... | Rust | 0 |
S SK Jr S SKrS SKJrJrJrJr S SKJ r J
r
JrJrJ
r
JrJrJrJrJrJrJrJrJrJrJrJr \R4 " S S\5 5 rg) annotationsNAnyListLiteralOptional_address _artifact_conversion"_external_property_file_refe... | Python | 1 |
;
fn into_async(self) -> Self::Async {
$reduceaasync{
$($t: self.$t.into_async(),)*
peeked: None,
ready: ($(None::<$t::Done>,)*),
}
}
}
impl<$($t: Reducer<$s>,)* $($s,)*> ReducerProcessSend<$enum<$($s,)*>> for $reducea<$($t,)*> where $($t::Done: ProcessSend + 'static,)* {
type Done ... | Rust | 0 |
df['Date'] = pd.to_datetime(df['Date'])
# Check season structure
if 'Season' in df.columns:
logger.info(f"\n📊 DATASET SEASON ANALYSIS:")
season_counts = df['Season'].value_counts().sort_index()
for season, count in season_counts.items():
... | Python | 1 |
real = float(input('Quanto dinheiro você tem na carteira? R$'))
dolar = real / 5.50
print('Com R${} você pode comprar US${:.2f}'.format(real, dolar)) | Python | 1 |
import tkinter as tk
from pages.start import StartPage
from pages.guide import GuidePage
from pages.settings import SettingsPage
import tkinter.font as font
from intrusiondetection.JSONReader.settings import Settings
class Home(tk.Frame):
def __init__(self, parent, controller):
super().__init__(parent)
... | Python | 1 |
Queueing::Enabled,
other => TaskQueueing::Unknown(other.to_owned()),
}
}
}
impl std::str::FromStr for TaskQueueing {
type Err = std::convert::Infallible;
fn from_str(s: &str) -> std::result::Result<Self, Self::Err> {
Ok(TaskQueueing::from(s))
}
}
impl TaskQueueing {
pub ... | Rust | 0 |
def custom_reward(obs):
reward = 0.0
if obs.puffed > 0:
reward = -1.0
if obs.prey_goal_distance < 0.1:
reward = 1.0
return reward | Python | 1 |
ng(input: &mut input_state_t, chr: i32) {
if chr == FiOrElseCode::Fi as i32 {
/*515:*/
if IF_STACK[IN_OPEN] == cond_ptr {
INPUT_STACK[INPUT_PTR] = *input;
if_warning(input, &INPUT_STACK[..INPUT_PTR + 1]);
}
let p = cond_ptr.unwrap()... | Rust | 0 |
import json
import tensorflow as tf
from gunpowder.zoo.tensorflow import conv_pass, unet
def create_network(input_shape, name):
tf.reset_default_graph()
# create a placeholder for the 3D raw input tensor
raw = tf.placeholder(tf.float32, shape=input_shape)
# create a U-Net
raw_batched = tf.resh... | Python | 1 |
import json
import logging
from typing import Any, Dict, List
from cirrus_sdk import ( # type: ignore
CirrusClient,
EnrollmentStatusExtraDef,
MetricsHandler,
NimbusError,
)
logger = logging.getLogger(__name__)
class CirrusMetricsHandler(MetricsHandler):
def __init__(self, metrics: Any, pings: A... | Python | 1 |
la102')
return model
def dla102x(pretrained=None, **kwargs): # DLA-X-102
BottleneckX.expansion = 2
model = DLA([1, 1, 1, 3, 4, 1], [16, 32, 128, 256, 512, 1024],
block=BottleneckX, residual_root=True, **kwargs)
if pretrained is not None:
model.load_pretrained_model(pretrained,... | Python | 1 |
vy.array([0.02, 0.03, 0.06]),
b: ivy.array([0.06, 0.04, 0.07])
}, {
a: ivy.array([4.0e-05, 9.0e-05, 3.6e-04]),
b: ivy.array([0.00036, 0.00016, 0.00049])
})
"""
r1 = ivy.vector_norm(w)
eff_grads, mw, vw = ivy.adam_step(
dcdw, mw_tm1, vw_tm1, step, beta1=beta1, beta2=be... | Python | 1 |
f __init__(self):
r"""
:param _UserPoolId: 用户池ID
:type UserPoolId: str
:param _UserPoolName: 用户池名字
:type UserPoolName: str
:param _UserPoolDesc: 用户池描述
:type UserPoolDesc: str
:param _UserPoolLogo: 用户池logo
:type UserPoolLogo: str
"""
... | Python | 1 |
import pytest
import torch
from colossalai.nn.optimizer import CPUAdam, HybridAdam
from colossalai.testing import clear_cache_before_run, parameterize
from tests.kit.model_zoo import model_zoo
def move_some_params_to_cuda(model, torch_model):
model.embed.weight.data = model.embed.weight.cuda()
torch_model.em... | Python | 1 |
_of::<cmap2>() as u64) as u32) as *mut cmap2;
i = 0_u16;
while (i as i32) < 256i32 {
(*map).subHeaderKeys[i as usize] = tt_get_unsigned_pair((*sfont).handle);
i = i.wrapping_add(1)
}
n = 0_u16;
i = 0_u16;
while (i as i32) < 256i32 {
(*map).subHeaderKeys[i as usize] = ((*m... | Rust | 0 |
c<T>, name: &str) -> Result<()> {
wrapped.push(block.to_block(name)?);
Ok(())
}
fn unwrap(_name: &str, wrapped: Vec<T>) -> Result<VecUnchecked<T>> {
Ok(VecUnchecked(wrapped))
}
}
impl<T> Deref for VecUnchecked<T> {
type Target = [T];
fn deref(&self) -> &[T] {
let VecU... | Rust | 0 |
from .base import * # noqa
DEBUG = False
# Static files configuration for production
# Use WhiteNoise's CompressedManifestStaticFilesStorage for optimal performance
# This provides both compression and manifest hashing for cache busting
STORAGES["staticfiles"]["BACKEND"] = "whitenoise.storage.CompressedManifestStati... | Python | 1 |
S_HIGH")]
pub static ETHTOOL_OPTNAME_COALESCE_TX_USECS_HIGH: once_cell::sync::Lazy<&'static str> =
once_cell::sync::Lazy::new(|| unsafe {
CStr::from_ptr(ffi::NM_ETHTOOL_OPTNAME_COALESCE_TX_USECS_HIGH)
.to_str()
.unwrap()
});
#[doc(alias = "NM_ETHTOOL_OPTNAME_COALESCE_TX_USECS_IRQ... | Rust | 0 |
'𓇐', '𛄊', '𐬋', '\u{1103a}', '𝢇', '𑒕', 'ꁶ',
'𘠿', '𘩧', '\u{1fa2b}', '𖧽', 'ﱆ', '🈓', 'ᄨ', '𑐥', '🗞', '𔐚', 'ἶ',
'\u{18af3}', '𞲠', '𖽗', '𝄯', '𑫈', '\u{1fa0d}', '𑻯', 'ꭂ', '⤠', '𐅽',
'ᦝ', '𖼇', '𒁟', 'ﶥ', '⡜', '𐠃', '𘡋', '𒇡', '𝂺', '⎿', 'も',
'\u{e01a9}', 'ꅶ', 'ꏜ', '𝋥', '益', '𝓩', 'ꀉ', '⛀', '�... | Rust | 0 |
wanting_frame"] = new_want_frame
new_want_frame.pack(fill='both', expand=True)
def show_manage_user_frame(self, frames, manage_frame):
get_user_type_instance = GetUserInfo.get_instance()
user_type = get_user_type_instance.usertype
if user_type == "普通用户":
messagebox.showi... | Python | 1 |
# app.py
import os
from pathlib import Path
import streamlit as st
from rag_core import (
DATA_PATH,
build_or_load_index,
Retriever,
Embedder,
load_llm,
generate_answer,
TOP_K,
)
st.set_page_config(page_title="Medical FAQ RAG", page_icon="🩺", layout="centered")
st.title("🩺 Medical FAQ ... | Python | 1 |
pping this failure should produce a message that looks like:
// thread 'tests::test_failure' panicked at 'called `Result::unwrap()` on an `Err` value: PermissionDenied(Some("/proc/1/maps"))', src/libcore/result.rs:997:5
}
}
use super::is_present;
use crate::eval::{Fields, ParamEval, TildeExpansion, WordEval... | Rust | 0 |
it
};
JNS.save(store, &name.clone(), &data)?;
Ok(
Response::new().add_attribute("method", "try_register_name")
.add_attribute("tokens_used", total_cost.to_string())
.add_attribute("name_registered", name)
.add_attribute("data_accepted", data)
)
}
pub fn try_set_... | Rust | 0 |
assert_eq!(ms, event2.get_time());
assert_eq!(event1.get_time(), event2.get_time());
assert_eq!(event1.get_utc_milliseconds(), 420);
}
#[wasm_bindgen_test]
fn set_utc_minutes() {
let event1 = Date::new(&"December 31, 1975, 23:15:30 GMT-3:00".into());
let event2 = Date::new(&"January 01, 1976 02:25... | Rust | 0 |
mcfgr2) module"]
pub type MCFGR2 = crate::Reg<u32, _MCFGR2>;
#[allow(missing_docs)]
#[doc(hidden)]
pub struct _MCFGR2;
#[doc = "`read()` method returns [mcfgr2::R](mcfgr2::R) reader structure"]
impl crate::Readable for MCFGR2 {}
#[doc = "`write(|w| ..)` method takes [mcfgr2::W](mcfgr2::W) writer structure"]
impl crate:... | Rust | 0 |
x00, 0x02, 0x02, 0x00, 0x01, 0x03,
0x02, 0xff, 0x7f, 0x04, 0x02, 0x00, 0x01, 0x05, 0x02, 0xff, 0x7f, 0x08,
0x05, 0x53, 0x48, 0x54, 0x50, 0x00, 0x06, 0x01, 0x00, 0x09, 0x08, 0x63,
0x6f, 0x6e, 0x74, 0x72, 0x6f, 0x6c, 0x00, 0x01, 0x04, 0x01, 0x00, 0x00,
0x00, 0x08, 0x0b, 0x65, 0x78, 0x65, 0... | Rust | 0 |
to_euc_map.is_none() {
*combine_utf8_4_to_euc_map = Some(COMBINE_UTF8_4_TO_EUC_MAP.read().unwrap());
}
if Utility::is_enough_4_bytes(utf8_buffer_length, *utf8_i)
&& Encoder::is_candidate_combine_utf8_4(utf8_buffer, *utf8_i)
&& combine_utf8_4_to_euc_map
... | Rust | 0 |
from __future__ import annotations
from typing import List
from typing import Pattern
from typing import Sequence
from typing import Tuple
from typing import Union
from typing import cast
from django.conf import settings
from corsheaders.defaults import default_headers
from corsheaders.defaults import default_method... | Python | 1 |
;
set_bit_in_slice(result, index, res);
}
32 => {
let l = E256::get(lhs);
let r = E256::from(x as i64);
let res = if l.cmp_u(&r).is_le() { 1 } else { 0 };
set_bit_in_slice(result, index, res);
}
_ => {
panic!("Invali... | Rust | 0 |
fy!(FMOD_DSP_DESCRIPTION),
"::",
stringify!(getparameterdata)
)
);
assert_eq!(
unsafe {
&(*(::std::ptr::null::<FMOD_DSP_DESCRIPTION>())).shouldiprocess as *const _ as usize
},
176usize,
concat!(
"Offset of field: ",
... | Rust | 0 |
for u in m.topology.vertices_around(v) {
new_pos += m.properties[(pos,u)];
deg+=1;
}
let beta : f32;
if deg == 3 {
beta = 3./16.;
} else if deg > 3 {
let tmp = 3./8.+(2.*std::f32::consts::PI/deg as ... | Rust | 0 |
me] = {'tmdb_id': tmdb_id, 'seasons': {}}
# 支持多种季目录格式
for dir_name in dirs:
season_number = None
for pattern in season_patterns:
match = pattern.match(dir_name)
if match:
... | Python | 1 |
import json
import os
import random
from argparse import ArgumentParser
import rich
import pathlib
from factguard.utility import (
QueuedTasks,
Writer,
extract_json_text,
THIKINIG_PROMPT_ZH,
THIKINIG_PROMPT_EN,
extract_thinking_final_answer,
)
from openai import OpenAI
from factguard import en... | Python | 1 |
ill store parsed `Example`s
min_after_dequeue: minimum number of elements that can be left by a
dequeue operation. Only used if `shuffle` is true.
shuffle: whether records should be shuffled. Defaults to true.
seed: passed to random shuffle operations. Only used if `shuffle` is true.
dat... | Python | 1 |
_fields)]
pub struct DatadogArchivesSinkConfig {
pub service: String,
pub bucket: String,
pub key_prefix: Option<String>,
#[serde(default)]
pub request: TowerRequestConfig,
#[serde(default)]
pub aws_s3: Option<S3Config>,
#[serde(default)]
pub azure_blob: Option<AzureBlobConfig>,
... | Rust | 0 |
await?;
let q = sqlx::query(sql.as_str())
.bind_all(dyn_update.bind_values)
.execute(&mut tx)
.await?;
if q != 1 {
tx.rollback().await?;
return Err(ApiError::NotFound("No run found for id.".to_string()));
}
tx.commit().await?;... | Rust | 0 |
;
encode_config_buf(&bytes[..], config, &mut b64);
b64_bytes.extend(b64.bytes());
assert_eq!(b64_bytes.len(), b64.len());
// change the last character to every possible symbol. Should behave the same as bulk
// decoding whether invalid or valid.
for &s1 in config.char_s... | Rust | 0 |
from_os_str))]
file: Option<PathBuf>,
}
fn main() -> Result<()> {
let args = Cli::from_args();
let mut base_context = Context::base();
let code = if let Some(f_name) = args.file {
fs::read_to_string(&f_name)?
} else if args.read_stdin {
let mut code_buffer = String::new();
... | Rust | 0 |
:page_of(start_addr);
let end_page = Page::page_of(end_addr - 1);
for page in start_page.to_u32()..end_page.to_u32() + 1 {
jit_dirty_page(get_jit_state(), Page::page_of(page << 12));
}
}
/// dirty pages in the range of start_addr and end_addr, which must span at most two pages
pub fn jit_dirty_cac... | Rust | 0 |
нер ОТКРСиО" ООО Башнефть-Добыча"(по ЭДО)', None, None, None, None, None, None, 0, None,
None,
None, None, None, None, None, None, None, None, None, None, None, None, None, None, None, None, None, None,
None],
[None, None, 'ФИО', None, None, None, None, None, None, None, None, None, N... | Python | 1 |
'''
通过列表生成式,我们可以直接创建一个列表。但是,受到内存限制,
列表容量肯定是有限的。而且,创建一个包含100万个元素的列表,
不仅占用很大的存储空间,如果我们仅仅需要访问前面几个元素,
那后面绝大多数元素占用的空间都白白浪费了。所以,
如果列表元素可以按照某种算法推算出来,
那我们是否可以在循环的过程中不断推算出后续的元素呢?
这样就不必创建完整的list,从而节省大量的空间。
在Python中,这种一边循环一边计算的机制,称为生成器:generator。
要创建一个generator,第一种方法很简单,只要把一个列表生成式的[]改成()
'''
# 生成器的唯一注意事项就是:生成器只能遍历一次。
g = (x * x ... | Python | 1 |
YSQL_TYPE_ENUM,
0xf8_u8 => MysqlType::MYSQL_TYPE_SET,
0xf9_u8 => MysqlType::MYSQL_TYPE_TINY_BLOB,
0xfa_u8 => MysqlType::MYSQL_TYPE_MEDIUM_BLOB,
0xfb_u8 => MysqlType::MYSQL_TYPE_LONG_BLOB,
0xfc_u8 => MysqlType::MYSQL_TYPE_BLOB,
0xfd_u8 => Mysq... | Rust | 0 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.