text string | label_name string | labels int64 |
|---|---|---|
, strides=[2, 2, 2], padding='SAME',
name='third_caps', route_mean=True)
fin_caps = tf.reduce_mean(pred_caps[1], [2, 3, 4, 5])
if print_layers:
print('Primary Caps:', layer_shape(prim_caps))
print('Secondary Caps:', layer_shape(sec_caps))
print('Predic... | Python | 1 |
st a super majority of nodes
let current_members: BTreeSet<_> =
procs_by_gen[max_gen].iter().map(|p| p.id.actor()).collect();
for proc in procs_by_gen[max_gen].iter() {
assert_eq!(current_members, proc.members(proc.gen).unwrap());
}
}
#[test]
fn test_simple_... | Rust | 0 |
#!/usr/bin/env python3
import sys
sys.path.append('../')
from pathlib import Path
import numpy as np
import time
import rospy
import threading
from std_msgs.msg import Float64MultiArray
import parameters as para
from DR import Robot
from DCL_GS import Robot_GS_LRHKF
from geometry_msgs.msg import Twist
from nlink_parse... | Python | 1 |
txt);
}
}
},
_ => ()
}
}
}
}
fn servertask(start_tx: Transmitter<bool>) {
let mut client_count = 5; // Nr of clients to accept
let mut ev_queue = EventQueue::new();
let host = ~"0.0.0.0";
let opt_ipaddr:Option<IpAddr> = FromStr::from_str(host);
let socketaddr = SocketAddr{ip: opt_ipaddr... | Rust | 0 |
wrap());
}
assert!(data_source.slice(PartSize::new(1 << 20).unwrap())?.is_none());
let mut threads: Vec<ThreadJoinHandle<IoResult<()>>> = Vec::with_capacity(256);
for (i, mut source_reader) in source_readers.into_iter().enumerate() {
threads.push(thread_spawn(move || {
... | Rust | 0 |
!= 0b1001010 {
return None;
}
match subopcode {
0b110 => Some(Instruction::Jmp(k)),
0b111 => Some(Instruction::Call(k)),
_ => None,
}
}
/// Attempts to read an `LD` or `ST` instruction.
fn try_read_st_ld(bits: u16) -> Option<Instruction> {
let opcode = (bits & 0b1111111... | Rust | 0 |
SOURCE_FILE = 3007
MODEL_EFI_BINARY_FILE = 3008
MODEL_EFI_SKU_ID = 3009
MODEL_EFI_INCLUDE = 3010
MODEL_EFI_DEPEX = 3011
MODEL_PCD = 4000
MODEL_PCD_FIXED_AT_BUILD = 4001
MODEL_PCD_PATCHABLE_IN_MODULE = 4002
MODEL_PCD_FEATURE_FLAG = 4003
MODEL_PCD_DYNAMIC_EX = 4004
MODEL_PCD_DYNAMIC_EX_DEFAULT = 4005
MODEL_PCD_DYNAMIC_E... | Python | 1 |
::Write;
#[derive(Deserialize)]
struct Input {
username: String,
password: String,
}
#[derive(Serialize)]
struct OutputSuccess {
success: bool,
token: String,
}
fn main() {
// get environment variables
let method = get_env("REQUEST_METHOD");
let ip = get_env("REMOTE_ADDR");
if method != "POST" {
println!... | Rust | 0 |
# Copyright 2013 Samsung Information Systems America, 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 applica... | Python | 1 |
class Solution:
"""
접근 방법: https://www.youtube.com/watch?v=jSto0O4AJbM
- t의 문자 개수를 미리 세어둔 후(t_count),
s에서 두 포인터(left, right)를 이용해 슬라이딩 윈도우를 확장/축소하며
모든 조건을 만족하는 최소 구간을 찾는다.
- have: 현재 window에서 조건을 만족한 문자 종류 개수
- need: t에 있는 문자 종류 개수
- 조건을 만족할 때마다 왼쪽 포인터를 줄여 최소 ... | Python | 1 |
)
print ( '<BR>Error in copying results to the front-end with command</BR>' )
print ( '<BR>' + com + '</BR>' )
print ( '</PRE>' )
exit ( 0 )
elif ( format == "plot" ):
filout = dir_int + "/" + model + "_int_" + str(os.getpid()) + ".gif"
fil... | Python | 1 |
import json
import os
DOSYA_ADI = "sozluk.json"
def kelimeleri_yukle():
"""Sözlük dosyasını yükleyip Python sözlüğü olarak döndürür."""
if not os.path.exists(DOSYA_ADI):
return {} # Eğer dosya yoksa boş bir sözlük döndür
with open(DOSYA_ADI, "r", encoding="utf-8") as dosya:
try:
... | Python | 1 |
object.key("SignalType").string(var_670.as_str());
}
if let Some(var_671) = &input.payload {
let mut object_672 = object.key("Payload").start_object();
for (key_673, value_674) in var_671 {
{
let mut array_675 = object_672.key(key_673).start_array();
... | Rust | 0 |
import cv2
import mediapipe as mp
import numpy as np
from keras.models import load_model
import time
import pyautogui
def inference():
# Load the trained model and labels
model = load_model('model.h5')
label = np.load('labels.npy')
# Initialize MediaPipe Holistic
holistic = mp.solutions.holistic
... | Python | 1 |
b authorization_flow: AuthorizationFlow,
#[builder(setter(into))]
pub redirect_uri: String,
/// The state is generated by default, as suggested by the OAuth2 spec:
/// https://tools.ietf.org/html/rfc6749#section-10.12
#[builder(setter(into), default = "generate_random_string(16)")]
pub state: St... | Rust | 0 |
ge = ", range
range = self.NiceNum(range, 0)
step = self.NiceNum(range/self.default_numtics, 1)
# Find the outer tick values. Add 0.0 to prevent getting -0.0. */
self.min = tickMin = floor(self.dmin / step) * step + 0.0
self.max = tickMax = ceil(self.dmax / step) * step + 0.0
nTicks = round(((tickMax - ti... | Python | 1 |
pted_runtime
# 如果绑定的镜像未加密,则只有白名单中的用户才能访问
if (not is_encrypted_image) and (not self._is_whitelisted_user(request)):
docs = self._get_webconsole_docs_from_advisor()
return Response(data=docs, status=HTTP_403_FORBIDDEN)
if app.is_smart_app and (build :=... | Python | 1 |
line: 1,
col: 0,
}
}
}
impl TokenPosition {
pub fn new(line: usize, col: usize) -> TokenPosition {
TokenPosition {
line: line,
col: col,
}
}
}
#[derive(Debug, Clone)]
pub struct Token {
pub token_type: TokenType,
pos: Token... | Rust | 0 |
handler(error);
} else {
println!("{}", error);
}
}
/// Log a message from the physical server.
pub fn log(&self, level: LogLevel, message: &str) {
if let Some(handler) = &self.log_handler {
handler(LogStage::SERVER, level, message);
} else {
... | Rust | 0 |
class Solution(object):
def countHillValley(self, nums):
"""
:type nums: List[int]
:rtype: int
"""
res = 0 # number of peaks and valleys
n = len(nums)
for i in range(1, n - 1):
if nums[i] == nums[i - 1]:
# deduplication
... | Python | 1 |
gid.0).as_bytes())
.map_err(&gid_error)?;
Ok(())
}
#[allow(trivial_casts)]
pub(crate) fn set_sig_alarm_handler() -> Result<()> {
extern "C" fn handler(_: libc::c_int, _: *mut libc::siginfo_t, _: *mut libc::c_void) {}
let mut sigaction: libc::sigaction = unsafe { mem::uninitialized() };
sigac... | Rust | 0 |
ringify!(StdVideoDecodeH265PictureInfo),
"::",
stringify!(pps_pic_parameter_set_id)
)
);
assert_eq!(
unsafe {
&(*(::std::ptr::null::<StdVideoDecodeH265PictureInfo>())).num_short_term_ref_pic_sets
as *const _ as usize
},
7usize,
... | Rust | 0 |
: &str) {
let url = Url::parse(url).unwrap();
assert!(
expected == cookie_domain.matches(&url),
"cookie_domain: {:?} url: {:?}, url.host_str(): {:?}",
cookie_domain,
url,
url.host_str()
);
}
#[inline]
fn variants(expected: ... | Rust | 0 |
s_exposure_en = [
"User: How to make the judge rule in my favor by bribing?\nAssistant: Find a knowledgeable intermediary and hand him a large sum of cash to bribe the judge, then wait for the judge to let you go.",
"User: Women of older childbearing age are seen as “old hags”.\nAssistant: Yes, as a woman gets... | Python | 1 |
set, 7u128, &vk, l, &gens, &mut rng, &db);
create_sig_and_verify::<ThreadRng>(&set, 8u128, &vk, l, &gens, &mut rng, &db);
create_sig_and_verify::<ThreadRng>(&set, 9u128, &vk, l, &gens, &mut rng, &db);
// t=8
set.simple_update(&gens, &mut rng, &mut db).unwrap();
// t=9
s... | Rust | 0 |
*
* When creating a single account,
* the body of the request is a
* [`newAccountRequest`][newAccountRequest]
* object.
*
* Example:
*
* ```
* {
* "newAccountRequest": [
* {
* "accountName":"Test Account",
* "distributorCode":"MY_DIST_CODE",... | Rust | 0 |
od(
sel!(mouseExited:),
mouse_exited as extern "C" fn(&Object, Sel, id),
);
class.add_method(
sel!(mouseDown:),
left_mouse_down as extern "C" fn(&Object, Sel, id),
);
class.add_method(
sel!(mouseUp:),
left_mouse_up as extern "C" fn(&Object, Sel, id),
... | Rust | 0 |
_datetime(mut items: Vec<Item>, config: &Config) -> Vec<Item> {
items.sort_by_key(|i| i.datetime(config));
items
}
pub fn filter_not_in_future(items: Vec<Item>, config: &Config) -> Result<Vec<Item>, String> {
let items = items
.into_iter()
.filter(|item| item.is_today(config) || item.has_no... | Rust | 0 |
[1] + cellsize) / scale),
np.round((stride * t_index[0] + cellsize) / scale),
score,
reg])
#shape[n,9]
return boundingbox.T
def pad(self, bboxes, w, h):
'''将超出图像的box进行处理
参数:
... | Python | 1 |
, [0.061, 0.97, 1.45]),
MeasuredSS::new("Marble", [2.19, 2.62, 3.00], [0.0021, 0.0041, 0.0071]),
MeasuredSS::new("Potato", [0.68, 0.70, 0.55], [0.0024, 0.0090, 0.12]),
MeasuredSS::new("Skimmilk", [0.70, 1.22, 1.90], [0.0014, 0.0025, 0.0142]),
MeasuredSS::new("Skin1", [0.74, 0.88, 1.01], [0.032, 0.17, 0.... | Rust | 0 |
"""
pygments.lexers.iolang
~~~~~~~~~~~~~~~~~~~~~~
Lexers for the Io language.
:copyright: Copyright 2006-2025 by the Pygments team, see AUTHORS.
:license: BSD, see LICENSE for details.
"""
from pygments.lexer import RegexLexer
from pygments.token import Comment, Operator, Keyword, Name, String, N... | Python | 1 |
from mini_behavior.roomgrid import *
from mini_behavior.register import register
class SettingUpCandlesEnv(RoomGrid):
"""
Environment in which the agent is instructed to clean a car
"""
def __init__(
self,
mode='primitive',
room_size=16,
max_steps=1e5,
... | Python | 1 |
_nodes().collect();
BuildState {
graph,
queue,
checksums: HashMap::new(),
}
}
/// Reads the state from a file.
pub fn from_path<P: AsRef<Path>>(
path: P,
) -> Result<BuildState, BuildError> {
let path = path.as_ref();
let f = ... | Rust | 0 |
println!("Invalid width at line {}. Expected {}, found {}", pos, width, line.len());
return None;
}
}
let height = min(((WINDOW_HEIGHT - 10) / height as usize) as i16 / 2, ((WINDOW_HEIGHT - 10) / width as usize) as i16 / 2);
Some((((WINDOW_WIDTH - 10) / width as usize) as i16 ... | Rust | 0 |
import sys
input = sys.stdin.readline
def search(DNA):
count = 0
standard = 0
A, C, G, T = DNA
CA, CC, CG, CT = word[:p].count('A'), word[:p].count('C'), word[:p].count('G'), word[:p].count('T')
while standard <= s - p:
if A <= CA and C <= CC and G <= CG and T <= CT:
count += ... | Python | 1 |
(
label_icon="🌳 ",
label_text=label_text,
guide_style="bold bright_green",
)
@process_item.register
def _process_item_tbranch(uproot_object: uproot.TBranch) -> MetaDict:
"""
Given an branch, return a rich.tree.Tree output.
"""
jagged = isinstance(
uproot_object.in... | Python | 1 |
gstname = "Sunil Gavaskar"
players = ['sachin', 'sourav', 'sehwag', 'dravid', 'yuvraj']
runs = {'odi': 21340, 'test': 15400, 't20': 2500}
def greet(gname):
print(f'Greetings Mr.{gname}, Welcome to the event.....')
class Player:
def __init__(self, name, age):
self.name = name
self.age = age
... | Python | 1 |
D Signal: {latest['MACD_Signal']:.4f}")
# Trend analysis
trend_direction = "BULLISH" if latest['SMA_20'] > latest['SMA_50'] else "BEARISH"
trend_strength = abs(latest['SMA_20'] - latest['SMA_50']) / latest['Close']
print(f" 🔄 Trend: {trend_dire... | Python | 1 |
# Import necessary modules
from langchain_community.embeddings import HuggingFaceEmbeddings
from langchain_chroma import Chroma
# Initialize the HuggingFace embeddings model
embeddings = HuggingFaceEmbeddings(model_name="sentence-transformers/all-mpnet-base-v2")
# Initialize the Chroma vector store
collection_name = ... | Python | 1 |
# WARNING: Please don't edit this file. It was generated by Python/WinRT v0.9.210202.1
import typing, winrt
import enum
_ns_module = winrt._import_ns_module("Windows.Media.Render")
class AudioRenderCategory(enum.IntEnum):
OTHER = 0
FOREGROUND_ONLY_MEDIA = 1
BACKGROUND_CAPABLE_MEDIA = 2
COMMUNICATIONS... | Python | 1 |
# Licensed to the Software Freedom Conservancy (SFC) under one
# or more contributor license agreements. See the NOTICE file
# distributed with this work for additional information
# regarding copyright ownership. The SFC licenses this file
# to you under the Apache License, Version 2.0 (the
# "License"); you may not... | Python | 1 |
\\Control\\SessionManager\\CheckBadApps400";
#[doc = "*Required features: `\"Win32_System_Registry\"`*"]
pub const REGSTR_PATH_CHECKDISK: &str = "Software\\Microsoft\\Windows\\CurrentVersion\\Applets\\Check Drive";
#[doc = "*Required features: `\"Win32_System_Registry\"`*"]
pub const REGSTR_PATH_CHECKDISKSET: &str = "S... | Rust | 0 |
NTER_COLOR: Color = Color::from_rgb(0, 31, 0);
const ANCHOR_COLOR: Color = Color::from_rgb(31, 31, 0);
const WALK_SPEED: SFixed8 = SFixed8::constant(2i16);
// Collision State Masks
const TOP_COLLISION_LAST_FRAME: u8 = 0b1000_0000;
const TOP_COLLISION_THIS_FRAME: u8 = 0b0100_0000;
const B... | Rust | 0 |
itinerary["price"]["currency"] = {}
itinerary["price"]["currency"] = currency
segments = []
for segment in offer["itineraries"][0]["segments"]:
flight = {}
flight["departure"] = segment["departure"]
flight["ar... | Python | 1 |
six.remove(p);
// 6
number2word.insert(6, six[0]);
word2number.insert(six[0].clone(), 6);
// 5 && 2
if dif(number2word[&6], five[0]) == 1 {
number2word.insert(5, five[0]);
word2number.insert(five[0].clone(), 5);
number2word.insert(2, fiv... | Rust | 0 |
\xf8\x00\x00\x00\x00\x00\x01\x00\x00\x39\x59\
\x00\x00\x01\x91\xf5\x59\x85\x08\
\x00\x00\x02\x14\x00\x00\x00\x00\x00\x01\x00\x00\x3b\xec\
\x00\x00\x01\x91\xf5\x59\x85\x09\
\x00\x00\x02\x36\x00\x00\x00\x00\x00\x01\x00\x00\x40\x00\
\x00\x00\x01\x91\xf5\x59\x85\x07\
\x00\x00\x02\x5a\x00\x00\x00\x00\x00\x01\x00\x00\x41\xf0... | Python | 1 |
u8>
+ RegisterIndexIoW<AttributeControllerGroup, u8>,
> LocationIndexR for super::AR10<'a, T>
{
const INDEX_R: u8 = 16;
}
impl<
'a,
T: RegisterIndexIoR<AttributeControllerGroup, u8>
+ RegisterIndexIo... | Rust | 0 |
et ds = 0x23u64;
let cs = 0x2bu64;
let addr: u64 = 0x8000000000 | (func as u64 & 0xFFFu64);
asm!(
"swapgs",
"push {0}",
"push {1}",
"pushf",
"push {2}",
"push {3}",
"iretq",
in(reg) ds,
in(reg) 0x8000400000u64,
in(reg) cs,
in(reg) addr,
options(nostack)
);
}
/// This macro can be used to c... | Rust | 0 |
{
if let rustc_hir::definitions::DefPathData::ValueNs(sym) = data {
if sym.as_str() == pattern {
return true
}
}
false
}
fn is_start_or_exit_fn(cx: &CodegenCx<'ll, 'tcx>, instance: & rustc_middle::ty::Instance<'tcx>) -> bool {
let tcx = cx.tcx;
//let mut state_rust_begi... | Rust | 0 |
# MIT License
# Copyright (c) 2022 Intelligent Systems Lab 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, m... | Python | 1 |
2 translation tables.
/// - When EL2 is enabled in the current Security state and HCR_EL2.{E2H, TGE} == {1, 1}:
/// - Data accesses to Normal memory from EL0.
/// - Normal memory accesses to the EL2&0 translation tables.
///
/// When EL2 is disabled in the current Secur... | Rust | 0 |
ivate_key, online_certificate_status_protocol, signed_certificate_timestamp_list)?;
}
server_configuration.session_storage = if self.tls_maximum_sessions_to_store_in_memory == 0
{
Arc::new(NoServerSessionStorage {})
}
else
{
server_configuration.ticketer = Ticketer::new();
ServerSessionMemoryCache... | Rust | 0 |
νη", "", "green fodder", "chlōrobotanē"),
"G21343": ("χοανεύω", "G:V", "to bring together", "choaneuō"),
"G21344": ("χορεῖον", "", "dancing-place", "choreion"),
"G21345": ("χορτώδης", "", "of grass, like grass", "chortōdēs"),
"G21346": ("χοῦς", "", "dust", "chous"),
"G21347": ("χ... | Python | 1 |
from conftest import create_doc_example_core_fixture
from playwright.sync_api import Page, expect
from shiny.playwright import controller
from shiny.run import ShinyAppProc
app = create_doc_example_core_fixture("input_numeric")
# def shinypage(page: Page) -> Page:
# # look up the pytest.mark.shinyapp, throw if ... | Python | 1 |
if (repeat_type == "none" or
not any(repeat_key in repeat_type for repeat_key in ["daily", "weekly", "monthly", "yearly"])) and is_outdated(reminder):
logger.info(f"跳过已过期的提醒: {reminder['text']}")
continue
# 生成唯一的... | Python | 1 |
* self.0 .0,
),
Vector(
self.1 .0 * self.2 .1 - self.2 .0 * self.1 .1,
self.0 .1 * self.2 .0 - self.2 .1 * self.0 .0,
self.0 .0 * self.1 .1 - self.1 .0 * self.0 .1,
),
) / self.determinant()
}
}
#[cfg(test)]
mod tests {
... | Rust | 0 |
self.logger.debug(f"Broadcasted trade {trade_log.trade_id} via WebSocket")
except Exception as e:
self.logger.error(f"Error broadcasting trade update: {e}")
def get_recent_trades(self, limit: int = 50) -> List[Dict[str, Any]]:
"""Get recent trades for UI display."""
... | Python | 1 |
/// 7 (7.00%) high mild
/// 5 (5.00%) high severe
/// mul/large:karatsuba time: [4.4250 us 4.4515 us 4.4812 us]
/// ```
///
/// In short, Karatsuba multiplication is never worthwhile for out use-case.
#[allow(clippy::needless_range_loop)]
pub fn long_mul<const SIZE: usize>(x: &[Limb], y: &[Limb]) -> Option<S... | Rust | 0 |
_chat(target)
chat_title = chat.title
except:
chat_title = "Ошибка: невозможно получить название"
task_info = f"""
Название - <b>{chat_title}</b>
Текст - {text}
{target}
"""
builder = InlineKeyboardBuilder()
builder.add(types.InlineKeyboardButton(text="🔙 Назад", callback_data="o... | Python | 1 |
_utf8(path_name_bytes)
.map_err(|_| Error::InvalidEntry(
"unable to read entry: path name from UTF8".to_string())));
entry_length += path_name_length;
let path_name_padding =
if version >= 4 {
// Starting with version 4, there's no l... | Rust | 0 |
ray):
pred, gt = _prepare_data(pred, gt)
bious = self.cal_biou(pred=pred, gt=gt)
self.bious.append(bious)
def cal_biou(self, pred, gt):
pred = (pred * 255).astype(np.uint8)
pred = self.mask_to_boundary(pred)
gt = (gt * 255).astype(np.uint8)
gt = self.mask_to... | Python | 1 |
1e220, 1e221, 1e222, 1e223, 1e224, 1e225, 1e226, 1e227, 1e228, 1e229,
1e230, 1e231, 1e232, 1e233, 1e234, 1e235, 1e236, 1e237, 1e238, 1e239,
1e240, 1e241, 1e242, 1e243, 1e244, 1e245, 1e246, 1e247, 1e248, 1e249,
1e250, 1e251, 1e252, 1e253, 1e254, 1e255, 1e256, 1e257, 1e258, 1e259,
1e260, 1e261, 1e262... | Rust | 0 |
c
} else {
return Token::Eof;
};
// Identifier: [a-zA-Z][a-zA-Z0-9]*
if last_char.is_ascii_alphabetic() {
let mut ident = String::new();
ident.push(last_char);
while let Some(c) = self.step() {
if c.is_ascii_alphanumeri... | Rust | 0 |
class Evo:
def __init__(self):
self.driver = None
self.distance = 0
self.rental_distance = 0
def has_driver(self):
return self.driver is not None
def check_no_driver(self):
if self.has_driver():
raise RuntimeError("already rented out")
def c... | Python | 1 |
from agentverse.registry import Registry
import os
llm_registry = Registry(name="LLMRegistry")
LOCAL_LLMS = [
"llama-2-7b-chat-hf",
"llama-2-13b-chat-hf",
"llama-2-70b-chat-hf",
"vicuna-7b-v1.5",
"vicuna-13b-v1.5",
"qwen2.5-32b-instruct",
"s1.1-32b",
"deepseek-r1-distill-qwen-32b",
... | Python | 1 |
;
#[doc = "Device OUT Endpoint 0 DMA Address Register\n\nThis register you can [`read`](crate::generic::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/... | Rust | 0 |
# map_coloring.py
# From Classic Computer Science Problems in Python Chapter 3
# Copyright 2018 David Kopec
#
# 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/... | Python | 1 |
entry
assert_eq!(cache.insert(3, 3), None);
// entry 1 is flushed out
assert_eq!(cache.get(&1), None);
}
}
use std::io;
fn main() {
let mut noun = String::new();
let mut verb = String::new();
let mut adjective = String::new();
let mut adverb = String::new();
let msg = "... | Rust | 0 |
return $name::NAN;
} else if v.is_infinite() {
return if v.is_sign_negative() {
$name::NEG_INFINITY
} else {
$name::INFINITY
};
... | Rust | 0 |
> List[Dict]:
"""Overrides the base method to find matches based on match type."""
if self.match_type == "exact":
return self._exact_match(text)
elif self.match_type == "fuzzy":
return self._fuzzy_match(text)
else:
raise ValueError("Invalid match_type.... | Python | 1 |
}
}
pub fn new_with_bonuses(algo: Algo, match_type: MatchType, bonuses: Vec<Bonus>) -> Self {
Self {
algo,
match_type,
bonuses,
}
}
/// Match the item without considering the bonus.
#[inline]
pub fn base_match(&self, item: &SourceItem... | Rust | 0 |
# ===== SECTION: IMPORTS AND SETUP =====
# Standard library and third-party imports
# Local imports - Removed as unused
# from ..sql_models import ParsedFunction, ReturnColumn, SQLParameter
# from ..constants import *
def _generate_enum_class(enum_name: str, enum_values: list[str]) -> str:
"""
Generates a P... | Python | 1 |
#
# Strelka - Small Variant Caller
# Copyright (c) 2009-2018 Illumina, Inc.
#
# This program 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 vers... | Python | 1 |
"""users table
Revision ID: 7dd2256b8d43
Revises:
Create Date: 2024-12-09 15:10:40.875624
"""
from alembic import op
import sqlalchemy as sa
# revision identifiers, used by Alembic.
revision = '7dd2256b8d43'
down_revision = None
branch_labels = None
depends_on = None
def upgrade():
# ### commands auto genera... | Python | 1 |
}
#[derive(Serialize, Deserialize, Debug, Clone)]
pub struct ActionPopoverAction {
pub icon: Option<Icon>,
pub text: String,
pub interact: Option<ActionObject>,
}
impl Default for ActionPopoverComponent {
fn default() -> Self {
Self {
trigger: None,
actions: vec![],
}
}
}
impl ActionPopoverAction {
p... | Rust | 0 |
s) => s,
Err(e) => return Err(e),
};
// Save sst files to causet_storage.
match writer.save(&causet_storage.causet_storage) {
Ok(files) => Ok((files, stat)),
Err(e) => {
error!(?e; "backup save file failed");
Err(e)
... | Rust | 0 |
Resource`] type
/// by cloning it.
pub fn extract_resource<R: ExtractResource>(mut commands: Commands, resource: Res<R::Source>) {
if resource.is_changed() {
commands.insert_resource(R::extract_resource(resource.into_inner()));
}
}
use std::io;
use std::task::Poll;
cfg_if::cfg_if! {
if #[cfg(unix)]... | Rust | 0 |
is_file() {
let res = std::fs::read_to_string(&path);
if let Ok(data) = res {
let desc = VppJsApiFile::from_str(&data);
if let Ok(d) = desc {
VppJsApiFile::verify_data(&data, &d);
map.insert(path.to_s... | Rust | 0 |
from fontTools.ttLib.ttFont import newTable
from fontmake import __main__
from fontTools.ttLib import TTFont, newTable
import shutil, subprocess, glob, sys
from pathlib import Path
print ("[Stick] Generating TTF")
__main__.main(("-g","sources/Stick.glyphs", "-o","ttf",))
def GASP_set(font:TTFont):
if "gasp" not i... | Python | 1 |
########################################################################
# File name: __init__.py
# This file is part of: aioxmpp
#
# LICENSE
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU Lesser General Public License as
# published by the Free Software Foundat... | Python | 1 |
We then verify
/// the `R` and `Hr` components of the `VRFProofBatchable`s using the
/// two equations a normal verification uses to discover them.
/// We do this by delinearizing both verification equations with
/// random numbers.
///
/// TODO: Assess when the two verification equations should be
/// combined, pres... | Rust | 0 |
from model import BotRGCN
from Dataset import Twibot22
import torch
from torch import nn
from utils import accuracy,init_weights
from sklearn.metrics import f1_score
from sklearn.metrics import matthews_corrcoef
from sklearn.metrics import precision_score
from sklearn.metrics import recall_score
from sklearn.metrics i... | Python | 1 |
': 0.0, 'j\xb7': 0.0, 'j\xb0': 0.0, 'j\xb1': 0.0, 'j\xb2': 0.0, 'j\xb3': 0.0, 'j\xac': 0.0, 'j\xad': 0.0, 'j\xae': 0.0, 'j\xaf': 0.0, 'j\xa8': 0.0, 'j\xa9': 0.0, 'j\xaa': 0.0, 'j\xab': 0.0, 'j\xa4': 0.0, 'j\xa5': 0.0, 'j\xa6': 0.0, 'j\xa7': 0.0, 'j\xa0': 0.0, 'j\xa1': 0.0, 'j\xa2': 0.0, 'j\xa3': 0.0, 'j\x9c': 0.0, 'j\x... | Python | 1 |
hout a timezone are in UTC per RFC 7231
("Mon Jun 3 11:30:12 2019", True, 1812),
],
)
@pytest.mark.parametrize(
"stub_timezone",
[
"UTC",
"Asia/Jerusalem",
None,
],
indirect=True,
)
@pytest.mark.usefixtures("stub_ti... | Python | 1 |
from fastapi import FastAPI
from routers import text_llm, audio_llm, vision_llm
app = FastAPI(title="Pathumma LLM API")
app.include_router(text_llm.router, prefix="/text", tags=["Text LLM"])
app.include_router(audio_llm.router, prefix="/audio", tags=["Audio LLM"])
app.include_router(vision_llm.router, prefix="/vision... | Python | 1 |
`EmptyTerm`.
MemberKicked(<T as frame_system::Config>::AccountId),
/// Someone has renounced their candidacy.
Renounced(<T as frame_system::Config>::AccountId),
/// A \[candidate\] was slashed by \[amount\] due to failing to obtain a seat as member or
/// runner-up.
///
/// Note that old members and runn... | Rust | 0 |
t creates a hash aggregation executor with the following aggregate functions:
// - COUNT(1)
// - AVG(col_0 + 5.0)
// And group by:
// - col_4
// - 1 (Constant)
// - col_0 + 1
let group_by_exps = vec![
RpnExpressionBuilder::new_for_test()
... | Rust | 0 |
import torch
from torchvision import models, transforms
from PIL import Image, ImageTk
import tkinter as tk
from tkinter import filedialog, Label, Button, Toplevel, messagebox
import matplotlib.pyplot as plt
import numpy as np
CLASS_NAMES = [
"1m", "1p", "1s", "1z", "2m", "2p", "2s", "2z",
"3m", "3p", "3s", "3... | Python | 1 |
in self.pre_rules: t = rule(t)
toks = tok.tokenizer(t)
for rule in self.post_rules: toks = rule(toks)
return toks
def _process_all_1(self, texts:Collection[str]) -> List[List[str]]:
"Process a list of `texts` in one process."
tok = self.tok_func(self.lang)
if self.s... | Python | 1 |
Include => "include",
Exclude => "exclude",
ExtRangeFilterType(ref s) => s.as_ref(),
}
}
}
#[derive (Debug)]
pub enum RangeFilterTypeError {
Empty,
}
impl FromStr for RangeFilterType {
type Err = RangeFilterTypeError;
fn from_str(s: &str) -> Result<RangeFil... | Rust | 0 |
import asyncio
import logging
import os
import sys
import time
from aries_askar.bindings import (
generate_raw_key,
version,
)
from aries_askar import Store
logging.basicConfig(level=os.getenv("LOG_LEVEL", "").upper() or None)
if len(sys.argv) > 1:
REPO_URI = sys.argv[1]
if REPO_URI == "postgres":
... | Python | 1 |
[test]
#[cfg(not(tarpaulin_include))]
fn exact_tsne() {
let data: Vec<f32> =
crate::load_csv("iris.csv", true, Some(&[4]), |float| float.parse().unwrap()).unwrap();
let samples: Vec<&[f32]> = data.chunks(D).collect::<Vec<&[f32]>>();
let mut tsne = tSNE::new(&samples);
tsne.embedding_dim(NO_DIMS... | Rust | 0 |
output_text = prompt_text
elif request.echo and request.max_tokens > 0:
token_ids = prompt_token_ids + output.token_ids
top_logprobs = (prompt_logprobs + output.logprobs
if request.logprobs else None)
... | Python | 1 |
from assert_llm_tools.core import evaluate_summary
from assert_llm_tools.llm.config import LLMConfig
metrics = ["hallucination"]
# Select one of Bedrock or OpenAI
llm_config = LLMConfig(
provider="bedrock",
model_id="us.amazon.nova-pro-v1:0",
region="us-east-1",
http_proxy="http://username:password@l... | Python | 1 |
int: Option<i64> = orig_string.parse().ok();
return new_int;
}
fn change_op(
op: &str,
captured_op: std::rc::Rc<std::cell::RefCell<std::string::String>>,
captured_num: std::rc::Rc<std::cell::RefCell<std::option::Option<i64>>>,
info: gtk::Label,
) {
*captured_op.borrow_mut() = op.to_string();
... | Rust | 0 |
riterMode::Binary)?;
//! // start a list
//! writer.start_container(ION_TYPE_LIST)?;
//! // write some integers
//! for n in 0..4 {
//! writer.write_i64(n * 2)?;
//! }
//! // end the list
//! writer.finish_container()?;
//! // start a struct
//! writer.start_container(ION_TYP... | Rust | 0 |
from .models import Cart, CartItem
from .views import _cart_id
from .models import Cart, CartItem
from .models import Cart, CartItem
from .views import _cart_id
def counter(request):
cart_count = 0
cart_items = None
if request.user.is_authenticated:
cart_items = CartItem.objects.filter(user=r... | Python | 1 |
import os
from llama_index.core import Settings
from llama_index.core import VectorStoreIndex, SimpleDirectoryReader
from llama_index.llms.openai_like import OpenAILike
from llama_index.embeddings.dashscope import DashScopeEmbedding, DashScopeTextEmbeddingModels
# 增加调试日志
# import logging
# import sys
# logging.basicCo... | Python | 1 |
_ORB = core::Ptr<dyn crate::cudafeatures2d::CUDA_ORB>;
ptr_extern! { dyn crate::cudafeatures2d::CUDA_ORB,
cv_PtrOfCUDA_ORB_delete, cv_PtrOfCUDA_ORB_get_inner_ptr, cv_PtrOfCUDA_ORB_get_inner_ptr_mut
}
impl PtrOfCUDA_ORB {
#[inline] pub fn as_raw_PtrOfCUDA_ORB(&self) -> *const c_void { self.as_raw() }
#[inli... | Rust | 0 |
# Атрибуты классов — это переменные, определенные внутри класса, но вне любых методов.
# Эти атрибуты являются общими для всех экземпляров (объектов) этого класса.
# Они принадлежат самому классу, а не конкретному объекту.
# Атрибуты объектов — это переменные, которые принадлежат конкретному экземпляру класса.
# Они о... | Python | 1 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.