text string | label_name string | labels int64 |
|---|---|---|
val_type: ASTType::STRING,
};
return node;
}
}
impl ValNode<char> {
pub fn new(val: char) -> ValNode<char> {
let node = ValNode {
value: val,
val_type: ASTType::CHAR,
};
return node;
}
}
// Expression Nodes
pub struct ExprNode {
... | Rust | 0 |
for new_row in self._write_buffer:
if (new_keys := set(new_row.keys())) != known_names:
logger.warning(f'Row has different keys than the Table. New keys: ({", ".join(new_keys.difference(known_names))}.'
f' Missing: {", ".join(known_names.differenc... | Python | 1 |
) -> ValidationResult:
"""Check hermiticity requirements for observables."""
return ValidationResult(
rule=ValidationRule.HERMITICITY_CHECK,
passed=True,
message="Hermiticity check not implemented",
details={},
suggestions=["Implement hermitici... | Python | 1 |
apply_patch_to_grf(
GrfPatchingMethod::InPlace,
&grf_archive_path,
&mut thor_archive,
)
.unwrap();
// After patching
let grf_archive = GrfArchive::open(&grf_archive_path).unwrap();
assert_eq!(nb_of_added_files,... | Rust | 0 |
ept ValueError as e:
print(f"Error in data preparation: {e}")
return
# Load scaler (in case it differs from the one returned above)
try:
scaler = joblib.load(args.scaler_path)
print("Scaler loaded successfully!")
except Exception as e:
print(f"Error loading scale... | Python | 1 |
# %% tags=["hide_source"]
import colight.plot as Plot
my_data = [[1, 1], [2, 1.5], [3, 1.25], [4, 2]]
(my_plot := Plot.line(my_data, r=10))
# %% [markdown]
### Show a grid
# %%
my_plot + Plot.grid()
# %% [markdown]
### Label axes
# Add an options object to your plot, putting a "label" in the options for the `"x"` ... | Python | 1 |
MASKED_LM_LANG_CODE = "msk_LANG"
MASK_TOKEN = "<mask>"
NER_BATCH_SIZE = 32
N_DOCS = 2
LANG_CONFIG = {
"english": {
"dataset_ext": "en",
"nllb_id": "eng_Latn",
"ner_id": "en",
"ner_model": "en_core_web_sm",
},
"german": {
"dataset_ext": "de",
"nllb_id": "deu_L... | Python | 1 |
#[cfg_attr(docsrs, doc(cfg(feature = "smol")))]
$item
)*
}
}
macro_rules! cfg_tokio {
($($item:item)*) => {
$(
#[cfg(feature = "tokio-async")]
#[cfg_attr(docsrs, doc(cfg(feature = "tokio")))]
$item
)*
}
}
macro_rules! cfg_sync {
... | Rust | 0 |
rue)
with tf.variable_scope("model", reuse=True):
valid_model = model_class(config, training=False)
saver = tf.train.Saver(tf.all_variables(), max_to_keep=40)
tf.initialize_all_variables().run()
# training
early_stop_best_loss = None
... | Python | 1 |
pk(num_topk)
topk_idxs = topk_idxs[idxs]
anchor_idxs, classes_idxs = topk_idxs.unbind(dim=1)
pred_boxes = self.box2box_transform.apply_deltas(
pred_deltas[anchor_idxs], anchors.tensor[anchor_idxs]
)
return Instances(
image_size, pred_boxes=Boxes(pred_box... | Python | 1 |
XmlFormat,
JsonlFormat
}
pub struct CallbackContext {
format: OutputFormat
}
impl CallbackContext {
pub fn new() -> Self {
Self::default()
}
pub fn with_format(mut self, format: OutputFormat) -> Self {
self.format = format;
self
}
pub fn handle_record(&self, ... | Rust | 0 |
parser.add_argument("--n", type=int, default=1)
parser.add_argument("--topp", type=float, default=1)
parser.add_argument("--call_per_minute", type=int, default=60)
args = parser.parse_args()
api_config = {
'temperature': args.temperature,
'n': args.n,
'max_tokens': 2048,
... | Python | 1 |
if cov is None:
cov = xp.eye(len(b1))
if mean is None:
mean = xp.zeros(len(b1))
assert cov is not None and mean is not None
# The network takes the form σ(W @ x + b1) * (V @ x + b2)
# Let y = W @ x + b1 and z = V @ x + b2
cov_xz = cov @ V.T
cov_yx = W @ cov
cov_yz = xp.... | Python | 1 |
ing()
}
};
let (gas_channel_sender, gas_requests) = mpsc::channel(0);
// Initialize a HangingGetBroker to process watch_peers requests
let watch_peers_broker = hanging_get::HangingGetBroker::new(
HashMap::new(),
PeerWatcher::observe,
hangi... | Rust | 0 |
# Copyright (c) 2020 - present Vitor Oriel <https://github.com/VitorOriel>
#
# 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 ... | Python | 1 |
class Solution:
def maxSubArray(self, nums: List[int]) -> int:
prev = nums[0]
res = nums[0]
for i in range(1, len(nums)):
prev = max(nums[i], prev + nums[i])
res = max(res, prev)
return res
| Python | 1 |
页面(如创作中心),说明已登录
return True
return False
except Exception as e:
self.log(f"测试登录状态失败: {e}")
return False
def login(self) -> bool:
"""
登录AcFun账号,优先使用cookie,其次使用用户名密码
Returns:
bool: 登录是否成功
"""
... | Python | 1 |
ds_cat_conf_score[i][args.class_id]), 0, int(255 * preds_cat_conf_score[i][args.class_id])), 2)
cv2.arrowedLine(result.orig_img, (int(x), int(y)), (int(x + r), int(y)), (0, int(255 * preds_cat_conf_score[i][args.class_id]), int(255 * preds_cat_conf_score[i][args.class_id])), 2)
cv2.arrowedLine(result.or... | Python | 1 |
C::try_from([3])?;
/// assert_eq!(unsafe { a.as_ptr().add(0).read() }, 3);
/// assert_eq!(unsafe { a.as_ptr().add(1).read() }, 0);
///
/// // spare memory is zeroed after removal of an element
/// assert_eq!(a.pop(), Some(3));
/// assert_eq!(unsafe { a.as_ptr().add(0).read() }, 0);
/// assert_eq!(unsafe { a.as_ptr().a... | Rust | 0 |
iter().for_each(|input| {
input_set.insert(input.previous_output.clone().into());
});
}
_ => warn!("Get transaction from pool failed"),
}
}
}
let mut pool_cache = TX_POOL_CACHE.write();
*pool_cache = input_set;... | Rust | 0 |
###########################################################################################
# #
# Set up paths for the Object Detection Metrics #
# ... | Python | 1 |
import re
from datetime import datetime
def sanitize_for_folder(text):
if not text:
return ''
# Keep only alphanumeric and spaces, then replace spaces with underscores
clean = re.sub(r'[^\w\s]', '', text)
return re.sub(r'\s+', '_', clean.strip())
# Test with example video data
test_cases = [
... | Python | 1 |
pub fn new(inner: Inner) -> Self {
// Lines typically aren't that long, don't use giant buffers
Self::with_capacities(1024, 1024, inner)
}
pub fn with_capacities(reader_capacity: usize, writer_capacity: usize, inner: Inner) -> Self {
Self {
inner: BufDuplexerBackend::wit... | Rust | 0 |
}
use core::fmt::Display;
pub type Result<T> = ::core::result::Result<T, Error>;
// TODO: consider using thiserror when support for no_std lands
// https://github.com/dtolnay/thiserror/pull/64
#[derive(Debug)]
pub enum Error {
X509(x509::der::Error),
X509Spki(spki::Error),
CustomStatic(&'static str),
... | Rust | 0 |
#!/usr/bin/env python3
# SPDX-License-Identifier: BSD-3-Clause
import logging
import multiprocessing
import socket
import sys
def fibonacci(num):
if num in (0, 1):
return 1
return fibonacci(num - 1) + fibonacci(num - 2)
def handle(connection, address):
logging.info("Received connection from %s... | Python | 1 |
assert!((*header).flags.is_set($val), $($arg)*);
}};
}
/// Assert the table of Param contains a param with the given name value pair
///
/// Example usage:
/// assert_contains_param!(params, "name", "value");
#[macro_export]
macro_rules! assert_contains_param {
($params:expr, $name:expr, $val:expr) => {{
... | Rust | 0 |
#Simple inverted number triangle piramid
#11111
#2222
#333
#44
#5
def main():
lines = int(input("Enter no.of lines: "))
pattern(lines)
def pattern(lines):
t = 1
for i in reversed(range(1, (lines +1))):
format = str(t)*i
print(format)
t = t + 1
if __name__ == "__main__":
ma... | Python | 1 |
ist()
return
raise ValueError(f"Calculation with id {calculation_id} not found")
def get_atom_and_orbital_options(self):
initial_data = self.info_list[0]
atom_options = initial_data.get_atom_index_list()
orbital_options = initial_data.get_orbital_list()
retur... | Python | 1 |
from flask import Blueprint, jsonify, request
from ..storage.channel_user_association_data_manager import ChannelUserAssociationManager
channel_user_association_routes = Blueprint(
"channel_user_association_routes", __name__)
channel_user_association_data_manager = ChannelUserAssociationManager()
@channel_user_a... | Python | 1 |
# Generated by Django 2.1.7 on 2019-02-19 23:37
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('app', '0004_auto_20190210_1254'),
]
operations = [
migrations.RemoveField(
model_name='historicalprinter',
name='cur... | Python | 1 |
t-modify-public user-modify-playback-state playlist-modify-private user-follow-modify user-read-currently-playing user-follow-read user-library-modify user-read-playback-position playlist-read-private user-library-read playlist-read-collaborative";
fn main() {
let client_id = env::var("LIBMAN_ID").unwrap_or_else(|... | Rust | 0 |
canonical_usize).collect();
let a: Vec<Vec<Target>> = lst[..]
.chunks(2)
.map(|pair| vec![builder.constant(pair[0]), builder.constant(pair[1])])
.collect();
let mut b = a.clone();
b.shuffle(&mut thread_rng());
assert_permutation(&mut builder, a, b);
... | Rust | 0 |
use crate::storage::EntityId;
use crate::view::ViewMut;
use alloc::vec::Vec;
use core::any::{type_name, TypeId};
/// Adds components to an existing entity.
pub trait AddComponentUnchecked<T> {
/// Adds `component` to `entity`, multiple components can be added at the same time using a tuple.
/// This function... | Rust | 0 |
#
# Monic Framework
#
# Copyright (c) 2024-2025 Cognica, Inc.
#
import pytest
from monic.expressions import (
ExpressionsParser,
ExpressionsInterpreter,
)
def test_named_expr_basic():
"""Test basic assignment and return value"""
code = "(x := 42)"
parser = ExpressionsParser()
tree = parser.p... | Python | 1 |
epochs=EPOCHS,
batch_size=BATCH_SIZE,
callbacks=callbacks,
verbose=1)
print("\nModel training complete!")
# 4. Plot training & validation accuracy values
plt.subplot(1, 2, 1)
plt.plot(history.history['accuracy'])
plt.plot(history.history['val... | Python | 1 |
update_usergroup_plan(project=project, plan_id=group_id, latest_data_list_index=index_id+1,updated_at=int(time.time()), repeat_times_add=1, latest_data_time=int(time.time()))
return 5,index_id+1
except Exception:
error = traceback.format_exc()
list_info = check_list_id(project=project... | Python | 1 |
ock_get_bucket_name.assert_called()
mock_get_object_name_base.assert_called()
client.list_files.assert_called_once_with(bucket_name="bucket", relative_path=Path("object_name_base/inputs"))
@pytest.mark.parametrize("optimize", [True, False])
@patch.object(S3ClientSingleton, "instance")
@patch("otx_io.download_... | Python | 1 |
threads = AccountantSkel::serve(&acc, addr, exit.clone()).unwrap();
sleep(Duration::from_millis(300));
let socket = UdpSocket::bind(send_addr).unwrap();
socket.set_read_timeout(Some(Duration::new(5, 0))).unwrap();
let acc = AccountantStub::new(addr, socket);
let last_id = acc.g... | Rust | 0 |
import glob
import os
from osocrNG.athena.common.quickptg1 import prepare_pt,prepare_pt_ng
def bootstrap_folder(root,dst,lang,pfix="*.jpg"):
ptfile,_=prepare_pt(os.path.join(root,lang));
sfolder=os.path.join(root,lang);
dfolder=os.path.join(dst,os.path.basename(lang),"results");
os.makedirs(dfolder,... | Python | 1 |
ewly-created file
/// descriptor.
pub const OPEN_MAX: usize = 1024;
/// Size in bytes of a page.
pub const PAGESIZE: usize = memory::PAGE_SIZE;
/// Equivalent to {PAGESIZE}. If either {PAGESIZE} or {PAGE_SIZE} is defined, the other is defined
/// with the same value.
pub const PAGE_SIZE: usize = PAGESIZE;
/// Maximum n... | Rust | 0 |
_scale,
libinput_event_gesture_get_time,
},
Libinput, LibinputInterface,
};
use libc::{poll, pollfd};
use serde::{Deserialize, Serialize};
use zvariant::derive::Type;
#[derive(Debug, Deserialize, Serialize, Type)]
pub struct CustomSwipeEvent {
pub stage: String,
pub fingers: i32,
pub dx: f6... | Rust | 0 |
tan", my_tan);
repl(&mut L);
}
lua_extern! {
unsafe fn my_sin(L: &mut lua::ExternState) -> i32 {
let input = L.checknumber(1);
let output = input.sin();
L.pushnumber(output);
1
}
unsafe fn my_cos(L: &mut lua::ExternState) -> i32 {
let input = L.checknumber(1);
... | Rust | 0 |
28]) -> f64 {
data[0] as f64
}
fn fold_min(point: i16, data: &mut Vec<i128>) {
if data.is_empty() {
data.push(i128::MAX);
}
data[0] = cmp::min(point as i128, data[0]);
}
fn fold_min_res(data: &[i128]) -> f64 {
data[0] as f64
}
pub fn get_fold_add_point(name: &str) -> FoldAddPointFn {
... | Rust | 0 |
int, SurfaceView};
use sdf_text_view::SDFTextView;
use uni_view::AppView;
fn main() {
use winit::event::{
ElementState, Event, KeyboardInput, MouseScrollDelta, VirtualKeyCode, WindowEvent,
};
use winit::{event_loop::ControlFlow, event_loop::EventLoop, window::Window};
let events_loop = EventLo... | Rust | 0 |
xb1\x04\
\x1c\x86f\xb7e\xeb\xb4\xd0\xae\x0d\xb8\xb0^\xe2\xeaV\
\xd16d\xcf\xa7K\xf8\xc2\xa0>7n\x9ae\x8b\x91\
\xbe\xa5\xd3\xa3s\xebU\xa46\x82\xf3\x8a\x1d\xf4\xbeP\
\xe3\xe8V\x1d\x92,b\x22\x89\x8c\xf2\x8d\xab\xd8\x8b\xcc\
\x84\xdb\x9a\xd8\xf0\x06K\xc2\xaa\xa1\xd5\xde\x0bO\x0e\x18\
\x0f]\xa0\x95\x1c\xae!\xd2\xdbN\x04\xba\x... | Python | 1 |
tf policy that will apply the augmentation procedue
# on image.
def make_final_policy(tf_policy_):
def final_policy(image_, bboxes_):
for func, prob, args in tf_policy_:
image_, bboxes_ = _apply_func_with_prob(
func, image_, args, prob, bboxes_)
return image_, bbox... | Python | 1 |
Config> =
StorageMap<_, Blake2_128Concat, T::KittyIndex, Option<BalanceOf<T>>, ValueQuery>;
///仓库
#[pallet::storage]
#[pallet::getter(fn query_kitty_farm)]
pub type ColorKittyFarm<T: Config> = StorageMap<
_,
Twox64Concat,
T::KittyIndex,
FarmOf<T>,
OptionQuery,
>;
///仓库
#[pallet::storage]
#[pallet::... | Rust | 0 |
ity",value=2000.0,dataType="MIPS")
I2 = port(name="I2",type="event data")
RPI = processor(name="Raspberry Pi 4B",propertyList=[MIPSCapacity],featureList=[I2])
# WIFI CONNTECTION
BandWidthCapacity = characteristic(name="BandWidthCapacity",value=100.0,dataType="Mbytesps")
Protocol = characteristic(na... | Python | 1 |
int("Servidor da API está online!")
# Determinar o arquivo a ser processado
if len(sys.argv) > 1 and os.path.exists(sys.argv[1]) and sys.argv[1].lower().endswith('.pdf'):
arquivo_pdf = sys.argv[1]
else:
if len(sys.argv) > 1:
print(f"Arquivo não encontrado ou não é um PDF: {s... | Python | 1 |
mark(c: &mut Criterion) {
let elements = (
("k1", 1usize),
("k2", "v2"),
("k3", "longstring"),
("k4", vec![1u8, 0, 1, 0, 1, 0]),
("k5", 5usize),
("k6", "v6"),
("k7", "longstring7"),
("k8", vec![1u8, 0, 1, 0, 1, 0]),
("k9", 5.0f64),
("k1... | Rust | 0 |
=MessageResponse,
summary="Conceder acesso à empresa",
)
async def grant_company_access(
company_id: int,
user_id: int,
access_level: str = Query(
..., regex="^(viewer|editor|admin)$", description="Nível de acesso"
),
db: Session = Depends(get_db_session),
current_user: Usuario = Dep... | Python | 1 |
"""Extra tools for the :py:class:`ee.DateRange` class."""
from __future__ import annotations
import ee
from .accessors import register_class_accessor
@register_class_accessor(ee.DateRange, "geetools")
class DateRangeAccessor:
"""Toolbox for the :py:class:`ee.DateRange` class."""
def __init__(self, obj: ee.... | Python | 1 |
op, new_args, call.attrs, call.type_args)
return compiler_end(new_call, annotator.compiler)
else:
return super().visit_call(call)
xgraph = pyxir.frontend.tvm.from_relay(mod, self.params, postprocessing=None)
xgraph = pyxir.partition(xgraph, targe... | Python | 1 |
::default::Default for Struct_x86_state_hdr {
fn default() -> Self { unsafe { ::std::mem::zeroed() } }
}
pub type x86_state_hdr_t = Struct_x86_state_hdr;
pub type i386_thread_state_t = Struct___darwin_i386_thread_state;
pub type x86_thread_state32_t = Struct___darwin_i386_thread_state;
pub type i386_float_state_t =... | Rust | 0 |
': prec, 'ap': ap}, f)
print(('Mean AP = {:.4f}'.format(np.mean(aps))))
print('~~~~~~~~')
print('Results:')
for ap in aps:
print(('{:.3f}'.format(ap)))
print(('{:.3f}'.format(np.mean(aps))))
print('~~~~~~~~')
print('')
print('--------------------------------------------------------... | Python | 1 |
import numpy as np
from prml.linear.regression import Regression
class VariationalLinearRegression(Regression):
"""
variational bayesian estimation of linear regression model
p(w,alpha|X,t)
~ q(w)q(alpha)
= N(w|w_mean, w_var)Gamma(alpha|a,b)
Attributes
----------
a : float
a p... | Python | 1 |
self.unwrap(output[0]) == {'0': 1, '1': 2}
assert self.unwrap(output[1]) == {"a": 1, "b": 2, "c": 3}
def test_multisort_a(self):
output = self.run('''
$ar1 = array(10, 100, 100, 0);
$ar2 = array(1, 3, 2, 4);
array_multisort($ar1, SORT_ASC, SORT_REGULAR, $ar2);
forea... | Python | 1 |
fg(test)]
mod tests {
use crate::avar;
use otspec::ser;
/* All numbers here carefully chosen to avoid OT rounding errors... */
#[test]
fn avar_axis_value_map_serde() {
let v = avar::AxisValueMap {
fromCoordinate: 0.2999878,
toCoordinate: 0.5,
};
let b... | Rust | 0 |
// unsigned <
Ltu,
// unsigned >=
Geu,
}
impl BranchFunct3 {
pub(crate) fn bits(self) -> u32 {
match self {
BranchFunct3::Eq => 0b000,
BranchFunct3::Ne => 0b001,
BranchFunct3::Lt => 0b100,
BranchFunct3::Ge => 0b101,
BranchFunct3::... | Rust | 0 |
" echivaleaza parametrul functiei decorate
# return f'Ambalare produs {functia_noastra.__name__} cu ambalaj din material {material} ce contine cartea cu titlul: {", ".join(carte)}'
# return ambalaj_interior
# return ambalaj
#
#
# @decorator_depozit('hartie')
# def impachetare_carti(*nume):
# ... | Python | 1 |
rank_scores_per_pair = \
rank_scores_per_pair + hmodel.allocModel.calcHardMergeGap_SpecificPairs(
SS, EligibleAIDPairs)
rank_scores_per_pair /= hmodel.obsModel.getDatasetScale(SS)
else:
raise ValueError(
"Unrecognised --m_pair_ranking_procedure: %s... | Python | 1 |
import random
# 1) Set your new flag here:
flag_str = "bcactf{5011d11y_r3v3r53_3n61n33r3d_600d_j08}"
flag = flag_str.encode("utf-8")
assert len(flag) == 44, "Flag length must be 44 bytes"
# 2) Split into three groups
g1 = flag[0:16] # bytes[0..15]
g2 = flag[16:32] # bytes[16..31]
g3 = flag[32:44] # bytes[32..43]
... | Python | 1 |
# Copyright (c) Mathias Kaerlev 2012.
# This file is part of Anaconda.
# Anaconda is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
# ... | Python | 1 |
"""
计算机视觉论文分类配置文件 (2025前瞻版)
包含一级分类和二级分类的层次结构,以及中英文对照和元数据
"""
# 类别阈值配置(越大越严格)
CATEGORY_THRESHOLDS = {
# 1. 视觉表征与基础模型
"视觉表征与基础模型 (Visual Representation & Foundation Models)": {
"threshold": 1.15,
"subcategories": {
"大规模预训练模型 (Large-scale Pretrained Models)": 1.25,
"视觉Trans... | Python | 1 |
vertices = SVec::new();
for &v in vertices.iter() {
let pos = mesh.vertex_position(v);
new_vertices.push(mesh.alloc_vertex(pos + position_delta, None));
}
// NOTE: It's important to initialize this structure, or some halfedges
// would get duplicated.
let mut pair_to_halfedge: PairT... | Rust | 0 |
# 03. **Agenda de Tareas**
# Contiene una lista de tareas con detalles como descripción, fecha de vencimiento y estado.
# Insertar al menos 10 tareas al fichero.
# Agregar nuevas tareas, actualizar el estado de una tarea, filtrar tareas completadas.
''' JSON =
{
"tareas": [
{"descripcion": "Estudiar Pytho... | Python | 1 |
# SETS
some_set = {"a", "b", "c"}
some_set_2 = {"b", "a", "c"}
def test_is_container():
assert len(some_set) == 3
assert "a" in some_set
assert list(sorted(some_set)) == ['a', 'b', 'c']
def test_is_subset1():
assert some_set == some_set_2
assert sorted(some_set) <= sorted(some_set_2)
assert... | Python | 1 |
_info:
return
# URL encode the search query
encoded_query = urllib.parse.quote_plus(query)
search_url = engine_info["url"].format(encoded_query)
try:
# Open the search URL in the default browser
subprocess.Popen(
["xdg-open", search_u... | Python | 1 |
|_| 1)); // return 1 if the "efgh" tag is found
///
/// named!(z<&[u8], B>,
/// chain!(
/// tag!("abcd") ~ // the '~' character is used as separator
/// aa: ret_int ~ // the result of that parser will be used in the closure
/// tag!("abcd")? ~ // this parser is optional
/// bb: r... | Rust | 0 |
#!/usr/bin/env python3
"""
Test script to verify the AI reprocessing fix
"""
import asyncio
from ai_reprocess import ai_reprocess_nodes
async def test_ai_reprocess_with_different_provider_formats():
"""Test that ai_reprocess_nodes handles different provider formats properly"""
note_text = "This is a test ... | Python | 1 |
print(
'''
Task 1
'''
)
import re
class EmailValidator:
def __init__(self, email: str):
self.email = email
self.validate(email) # Передаем email явно
@classmethod
def validate(cls, email: str):
pattern = r'^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}$'
if not ... | Python | 1 |
assert_eq!(
storage
.create_table(
"schema_name_1",
"table_name",
vec![("column_rstest::rstest".to_owned(), SqlType::SmallInt)]
)
.expect("no system errors"),
Ok(())
);
assert_eq!(
storage
... | Rust | 0 |
key = filekey.read()
f = Fernet(key)
token = f.decrypt(data_to_decrypt.decode('utf-8'))
return token
@staticmethod
def load_encryption_key():
try:
with open('enc_key.key', 'wb') as filekey:
key = Fernet.genera... | Python | 1 |
.partial_charge for a in mol_pb.atoms))
out_pb.formal_charges_distribution.CopyFrom(_values_to_distribution_summary(
a.formal_charge for a in mol_pb.atoms))
out_pb.is_aromatic = any(a.aromatic for a in mol_pb.atoms)
for bond_type in (p.bond_type for p in mol_pb.atom_pairs):
if bond_type != mgpb.Molecu... | Python | 1 |
h_model.bin.index.json"
model_safetensor_map_json_path = checkpoint_dir / "model.safetensors.index.json"
if pytorch_bin_map_json_path.is_file(): # not all checkpoints have this file
with open(pytorch_bin_map_json_path, encoding="utf-8") as json_map:
bin_index = json.load(json_map)
b... | Python | 1 |
#!/usr/bin/python2
from collections import OrderedDict
import json
import re
import sys
def TransforExpre(simExpreStr):
"""transformate the result to format result.
Args:
simExpreStr: expression string.
Returns:
expreStr: new expression string.
Raise:
None.
"""
exp... | Python | 1 |
.linspace(-5, 5, 100)
Y = np.linspace(-5, 5, 100)
X, Y = np.meshgrid(X, Y)
Z = loss_function(X, Y)
# Plot the surface and the optimization path
fig = plt.figure(figsize=(10, 7))
ax = fig.add_subplot(111, projection='3d')
ax.plot_surface(X, Y, Z, cmap='viridis', alpha=0.8)
path = np.array(path)
ax.plot(path[:, 0], path... | Python | 1 |
VE);
static FLAGS_DT_NIOS2: &[Flag<u32>] = &flags!(DT_NIOS2_GP);
static FLAGS_DF: &[Flag<u32>] = &flags!(
DF_ORIGIN,
DF_SYMBOLIC,
DF_TEXTREL,
DF_BIND_NOW,
DF_STATIC_TLS,
);
static FLAGS_DF_1: &[Flag<u32>] = &flags!(
DF_1_NOW,
DF_1_GLOBAL,
DF_1_GROUP,
DF_1_NODELETE,
DF_1_LOADFLTR,... | Rust | 0 |
_block_3 = [0xf0, 0xf1, 0xf2, 0xf3, 0xf4, 0xf5, 0xf6, 0xf7, 0xf8, 0xf9, 0xfa, 0xfb, 0xfc, 0xfd, 0xff, 0x01];
let out_block_3 = [0x6a, 0x2c, 0xc3, 0x78, 0x78, 0x89, 0x37, 0x4f, 0xbe, 0xb4, 0xc8, 0x1b, 0x17, 0xba, 0x6c, 0x44];
let plaintext_3 = [0x30, 0xc8, 0x1c, 0x46, 0xa3, 0x5c, 0xe4, 0x11, 0xe5, 0xfb, ... | Rust | 0 |
let stream = client.stream().map(|msg| IrcMessage(msg));
Self::add_stream(stream, ctx);
info!("IRC: Joined");
act.client = Some(client);
});
ctx.spawn(irc);
}
}
<gh_stars>0
#![deny(clippy::all)]
#![forbid(unsafe_code)]
#![cfg_attr(not(debug_assertions), windows_... | Rust | 0 |
logger.info(f"Conversations imported successfully from {file_name}")
QMessageBox.information(self, "Import Successful", "Conversations imported successfully.")
except Exception as e:
logger.error(f"Error importing conversations: {str(e)}")
QMessageBox.critical... | Python | 1 |
from datetime import datetime
import pytest
from tests.unit import create_rate_data
from custom_components.octopus_energy.utils.rate_information import get_unique_rates
@pytest.mark.asyncio
async def test_when_called_then_unique_rates_for_current_day_returned_in_order():
period_from = datetime.strptime("2024-04-16... | Python | 1 |
tars>0
// Copyright Materialize, Inc. and contributors. All rights reserved.
//
// Use of this software is governed by the Business Source License
// included in the LICENSE file.
//
// As of the Change Date specified in that file, in accordance with
// the Business Source License, use of this software will be governed... | Rust | 0 |
#!/usr/bin/env python3
"""Multi-protocol agent demonstration."""
import dspy
from agenspy import (
MultiProtocolAgent,
MCPClient,
Agent2AgentClient,
ProtocolType
)
def main():
print("🚀 Multi-Protocol Agent Demo")
print("=" * 40)
# Configure DSPy
try:
lm = dspy.LM('openai/gpt-... | Python | 1 |
Data.measured_js)
print("------------------------------------")
print("measured_cp: ", robData.measured_cp.pose)
# ######
# The following 3 lines move the first two joints in a sinusoidal pattern
elif key == 2:
servo_jp_msg.position[0] = 0.2 * math.sin(rospy.Time.now().to_sec())
... | Python | 1 |
),
}
}
}
impl From<BinaryOpOutput> for LogicalExprOp {
fn from(o: BinaryOpOutput) -> Self {
match o {
BinaryOpOutput::LogicOp(op) => op,
BinaryOpOutput::BinOp(_) => panic!(
"illegal conversion: Cannot convert {:?} to LogicalExprOp",
... | Rust | 0 |
'scope>, Thunk<'static>>(Box::new(job))
})
}
}
}
#[cfg(feature = "no-threads")]
mod mt {
pub struct EmptyPool {}
pub fn da_pool() -> EmptyPool {
EmptyPool {}
}
impl EmptyPool {
pub fn max_count(&self) -> usize {
1
}
pub fn joined_exe... | Rust | 0 |
set_pin(false);
}
fn swap(&mut self) {
self.dc_pin.set_pin(true);
self.spi.send_bytes(&self.fb.buffer);
}
fn safe_swap(&mut self) {
self.swap(); // No double buffering, one swap is sufficient
}
fn fb<'a>(&'a mut self) -> &'a mut DisplayBuffer {
&mut self.fb
... | Rust | 0 |
pub fn build(self) -> Params {
Params {
target: self.target.expect("target is required"),
build_mode: self.build_mode,
output_kind: self.output_kind,
}
}
}
impl ActionOutput<Params> {
pub fn pilot_file_path(&self) -> PathBuf {
PathBuf::new().join... | Rust | 0 |
sage);
relm.connect_exec_ignore_err(send_future, Message);
}
}
}
view! {
gtk::Window {
gtk::Box {
orientation: Vertical,
gtk::Label {
text: &model.text,
},
// Give a name ... | Rust | 0 |
"""规则库文件"""
import basic
from error import *
# 常量定义
opreators = basic.Register() # 操作类注册表
descriptions = basic.Register() # 操作描述注册表
begin = lambda string : 0 # 字符串开头lambda表达式
end = lambda string : len(string) # 字符串结尾lambda表达式
# Author : guiqiqi187@gmail.com
class Description(object):
@staticmethod
@descriptions.re... | Python | 1 |
Vgatherqps_xmm_vm64y_xmm
0x2000_0136, 0x1100_0001,// VEX_Vgatherqpd_xmm_vm64x_xmm
0x2000_0136, 0x1100_0001,// VEX_Vgatherqpd_ymm_vm64y_ymm
0x2000_0036, 0x2D08_0002,// EVEX_Vgatherqps_xmm_k1_vm64x
0x2000_0036, 0x2D08_0002,// EVEX_Vgatherqps_xmm_k1_vm64y
0x2000_0036, 0x1E08_0002,// EVEX_Vgatherqps_ymm_k1_vm64z
0x20... | Rust | 0 |
#[allow(dead_code)]
pub fn get(self: &Dialog, data: &DialogData)
-> Result<String, &'static str> {
if self.dialog_strings.is_empty() {
Err("No dialogs")
} else {
let index = rand::thread_rng().gen_range(
0..self.dialog_strings.len()
... | Rust | 0 |
let mut map = HashMap::new();
map.insert(1, 2);
}
// Using the parent modules distinguishes the two Result types
// fmt::Result and io::Result
use std::fmt;
use std::io;
fn function1() -> fmt::Result {
Ok(())
}
fn function2() -> io::Result<()> {
Ok(())
}
// Alternatively
use std::io::Result as IoRes... | Rust | 0 |
cv2.putText(image, text, tpos, font, font_scale, tc, 2)
if waitKey is not None:
cv2.imshow(window_name, image)
cv2.waitKey(waitKey)
yield image
except StopIteration:
if not count:
return
... | Python | 1 |
(AbstractValue::new_primitive(ty.clone()));
let state2 = common::run_instruction(op.clone(), state1);
assert_eq!(
state2.stack_peek(0),
Some(AbstractValue::new_primitive(ty.clone())),
"stack type postcondition not met"
);
}
}
#[test]
fn bytecode_shl_shr()... | Rust | 0 |
# Copyright (c) 2021 PaddlePaddle 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 appli... | Python | 1 |
�",
"Immagini" => "",
"Modelli" => "",
"Musica" => "",
"Pubblici" => "",
"Scaricati" => "",
"Scrivania" => "",
"Video" => "",
// German
"Bilder" => "",
"Dokumente" => "",
"Musik" => "",
"Schreibtisch" => "",
... | Rust | 0 |
brace, rbrace, lparen, rparen, colon, qmark = Literal.using_each(
"[]{}():?"
)
re_macro = Combine("\\" + one_of("d w s"))
escaped_char = ~re_macro + Combine("\\" + one_of(list(printables)))
re_literal_char = (
"".join(c for c in printables if c not in r"\[]{}().*... | Python | 1 |
acOS :: MacOS X',
'Operating System :: Microsoft :: Windows',
'Operating System :: POSIX :: BSD :: FreeBSD',
'Operating System :: POSIX :: Linux',
'Programming Language :: Python :: 3.9',
'Programming Language :: Python :: 3.10',
'Programming Langu... | Python | 1 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.