text string | label_name string | labels int64 |
|---|---|---|
"""Tests for the html5 component."""
| Python | 1 |
ALLS_CAP_SYS_NICE: &[&str] = &["get_mempolicy", "mbind", "set_mempolicy"];
pub const SYSCALLS_CAP_SYSLOG: &[&str] = &["syslog"];
// syscalls to be added if a given capability is _missing_
pub const SYSCALLS_NON_CAP_SYS_ADMIN: &[&str] = &[
// Parameter condition: index=0, value=0x7E020000, op=SCMP_CMP_MASKED_EQ
... | Rust | 0 |
hes\i\in_impsmall_r_corner_03.nif", 0x2D31_7350, 0xACB3_4A41),
(r"meshes\i\in_impsmall_trapdoor_01.nif", 0x2D31_7350, 0xC53F_85CA),
(r"meshes\i\in_impsmall_r_center_01.nif", 0x2D31_7350, 0xD3D1_D3EA),
(r"icons\m\tx_potion_standard_01.dds", 0x2D34_3301, 0x91CC_91A1),
(r"icons\m\tx_potion_quality_01.d... | Rust | 0 |
function:
///
/// ```rust
/// use fuzzy_logic::functions::MembershipFactory;
///
/// let mem = MembershipFactory::triangular(-15.0, -15.0, 22.0);
/// mem(-15.0); // -> 1.0
/// ```
pub struct MembershipFactory;
impl MembershipFactory {
/// Creates triangular function.
pub fn triangular(a: f32, b: f32, c: f32) ... | Rust | 0 |
def change_tab():
"""
Clicks on the 'Text generation' tab for direct usage upon character selection.
"""
return """
() => {
var tabButtons = document.evaluate("//button[contains(., 'Text generation')]", document, null, XPathResult.ANY_TYPE, null );
var chatTab = tabButtons.iterateNe... | Python | 1 |
# Program 09c: Phase portrait and Poincare section of a nonautonomous ODE.
# See Figure 9.11(b).
import matplotlib.pyplot as plt
import numpy as np
from scipy.integrate import odeint
xmin, xmax = -2, 2
ymin, ymax = -2, 2
k = 0.3
omega = 1.25
gamma = 0.5
def dx_dt(x, t):
return [x[1], x[0] - k*x[1] - x[0]**3 + g... | Python | 1 |
import os
import shlex
from somewhere import something
def handler(event, context):
# ok:dangerous-spawn-process
os.spawnlp(os.P_WAIT, "ls")
# ok:dangerous-spawn-process
os.spawnlpe(os.P_WAIT, "ls")
# ok:dangerous-spawn-process
os.spawnv(os.P_WAIT, "/bin/ls")
# ok:dangerous-spawn-process... | Python | 1 |
ntation: ffi::GtkOrientation,
minptr: *mut i32,
natptr: *mut i32,
) {
let instance = &*(ptr as *mut T::Instance);
let imp = instance.get_impl();
let wrap: Borrowed<Widget> = from_glib_borrow(ptr);
let wrap_orientation: Orientation = from_glib(orientation);
imp.adjust_size_request(
w... | Rust | 0 |
분석
anomalies = analyzer.analyze_close_price_anomalies()
# 사용자가 특정 케이스를 보고 싶어할 경우를 대비한 예시
if len(anomalies) > 0:
print("\n" + "="*60)
print("💡 특정 케이스 상세 분석 예시:")
# 가장 큰 편차를 보인 케이스
top_case = anomalies.iloc[0]
print... | Python | 1 |
Button::Start => Some(input_event_codes::BTN_START ),
ControllerButton::Mode => Some(input_event_codes::BTN_MODE ),
ControllerButton::LStickClick => Some(input_event_codes::BTN_THUMBL ),
ControllerButton::RStickClick => Some(input_event_codes::BTN_THUMBR ),
Co... | Rust | 0 |
# Обновляем данные пользователя на случай, если они изменились
cursor.execute("""
UPDATE Users
SET username = ?, user_fullname = ?
WHERE user_id = ?
""", (username, user_fullname, user_id))
else:
# Вставляем нового пользователя со всеми полями
cu... | Python | 1 |
9, 8,
3, 2, 1, 0, 3, 2, 1, 0, 3, 2, 1, 0, 3, 2, 1, 0,
);
#[rustfmt::skip]
let sh3 = _mm256_set_epi8(
-1, -1, -1, -1, -1, 11, -1, 8, -1, 10, -1, 7, -1, 9, -1, 6,
-1, -1, -1, -1, -1, 11, -1, 8, -1, 10, -1, 7, -1, 9, -1, 6,
);
#[rustfmt::skip]
let sh4 = _mm256_set_epi8(
... | Rust | 0 |
.{}.{}d.ann", metric, dim);
let index = AnnoyIndex::load(dim, path.as_str(), metric).unwrap();
let t_start = time::Instant::now();
for i in 0..n_loop {
let id = i % size;
let v = index.get_item_vector(id);
index.get_nearest(v.as_slice(), n_result, -1, true);
... | Rust | 0 |
from nbodykit.lab import *
from nbodykit import setup_logging
from nbodykit.utils import ScatterArray, GatherArray
from numpy.testing import assert_array_equal
from mpi4py import MPI
import pytest
# debug logging
setup_logging("debug")
@pytest.mark.parametrize("comm", [MPI.COMM_WORLD,])
@pytest.mark.mpi
def test_fiber... | Python | 1 |
Iterator[MoleculeDataset]:
r"""Creates an iterator which returns :class:`MoleculeDataset`\ s"""
return super(MoleculeDataLoader, self).__iter__()
def make_mols(smiles: List[str], reaction_list: List[bool], keep_h_list: List[bool], add_h_list: List[bool], keep_atom_map_list: List[bool]):
"""
... | Python | 1 |
let msg = format!("-f, --from=[FROM] 'From date e.g. 2016-01-01 Defaults to the begging of the month'
-t, --to=[TO] 'To date e.g. 2016-01-31 Defaults to the end of the month'
-c, --config=[CONFIG] 'Config file. Defaults to {}'", CONFIG_FILE_NAME);
let matches = App::new... | Rust | 0 |
# coding: utf-8
"""
Slurm REST API
API to access and control Slurm
The version of the OpenAPI document: Slurm-24.11.5&openapi/slurmdbd&openapi/slurmctld
Contact: sales@schedmd.com
Generated by OpenAPI Generator (https://openapi-generator.tech)
Do not edit the class manually.
""" # noqa: E50... | Python | 1 |
'a, T> {
/// Creates a new JSON RPC request
fn new(id: u64, method: &'a str, params: T) -> Self {
Self {
id,
jsonrpc: "2.0",
method,
params,
}
}
}
#[derive(Serialize, Deserialize, Debug, Clone)]
struct Response<T> {
id: u64,
jsonrpc: S... | Rust | 0 |
['a', 'a', 'b', 'c', 'b', 'c', 'd', 'c', 'b', 'e'];
let found_decoding = decode::<char, u8>(&encoding);
assert_eq!(&found_decoding, &expected_decoding);
}
}
#[cfg(test)]
mod to_string {
use super::*;
#[test]
fn empty_encoding() {
let encoding: [Code<char, u8>; 0] = [];
... | Rust | 0 |
let next_ts6 = schedule6.next_after(¤t_block_ts).unwrap();
println!("TS 6: {} {}", next_ts6, human_readable_time(next_ts6));
assert_eq!(next_ts6, 1750381904000000000);
}
#[test]
fn test_get_slot_from_cadence_match() {
let mut context = get_context(accounts(1));
te... | Rust | 0 |
AT_EN>;
#[allow(missing_docs)]
#[doc(hidden)]
pub struct _INT_STAT_EN;
#[doc = "`read()` method returns [int_stat_en::R](int_stat_en::R) reader structure"]
impl crate::Readable for INT_STAT_EN {}
#[doc = "`write(|w| ..)` method takes [int_stat_en::W](int_stat_en::W) writer structure"]
impl crate::Writable for INT_STAT_... | Rust | 0 |
_commits: Result<Vec<Commit>, GitError> = most_recent.parent_ids.into_iter()
.filter(commit_id_matches)
.map(|id| find_one(&id, repository))
.collect();
try!(parent_commits)
};
commits.p... | Rust | 0 |
}
}
<filename>src/mailimf_write_generic.rs
use crate::clist::*;
use crate::mailimf_types::*;
use crate::other::*;
pub const STATE_WORD: libc::c_uint = 1;
pub const STATE_SPACE: libc::c_uint = 2;
pub const STATE_BEGIN: libc::c_uint = 0;
/*
mailimf_string_write writes a string to a given stream
@param f is th... | Rust | 0 |
2211 = round(*(float4*)buf2212);
rsAllocationCopy1DRange(*(rs_allocation*)buf2213, *(uint32_t*)buf2214, *(uint32_t*)buf2215, *(uint32_t*)buf2216, *(rs_allocation*)buf2217, *(uint32_t*)buf2218, *(uint32_t*)buf2219);
rsAllocationCopy2DRange(*(rs_allocation*)buf2220, *(uint32_t*)buf2221, *(uint32_t*)buf2222, *(uin... | Rust | 0 |
hanging authority set.
type EpochChangeTrigger: EpochChangeTrigger;
/// The proof of key ownership, used for validating equivocation reports.
/// The proof must include the session index and validator count of the
/// session at which the equivocation occurred.
type KeyOwnerProof: Parameter + GetSessionNumber + G... | Rust | 0 |
import pygame as pg
from pygame import RESIZABLE, Surface, FULLSCREEN
from pygame.display import set_caption, is_fullscreen
import numpy as np
from func_for_pg import power_lines, movement, button, vec, slider
# предварительное создание некоторых "физических" констант
x_list = np.array(())
y_list = np.array(())
q_list... | Python | 1 |
from .ship import Ship
from views.view_constants import *
from views.spritesheet import spritesheet
class Battleship(Ship):
def __init__(self, cells):
super().__init__(cells)
def init_ship_sprite(self, path, width, height):
super().init_ship_sprite(BATTLESHIP_PATH, 500, 500)
... | Python | 1 |
Debug,
_ => log::LevelFilter::Trace,
}
}
macro_rules! fail {
($logger:expr, $e:expr) => {{
fail!($logger, $e => {})
}};
($logger:expr, $e:expr => $exec:block) => {
match $e {
Ok(v) => v,
Err(e) => {
let logger: bool = $logger;
if logger {
error!("Error: {e}");... | Rust | 0 |
::src::simd::x86_64::jsimd::jsimd_encode_mcu_AC_refine_prepare_sse2(
block,
jpeg_natural_order_start,
Sl,
Al,
absvalues,
bits,
);
}
pub const FUNCTION_ARGUMENT_OFFSET: usize = 1;
pub fn compile_generic_pointer() -> fmm::types::Pointer {
fmm::types::Pointer::new(f... | Rust | 0 |
import sys
import scipy.signal as signal
PDM_FTL_TAPS = 16
PDM_FTL_SAMPLE_F = 1024
PDM_FTL_CUT_OFF = 4
PDM_FTL_SCALE_BITS = 30
taps1 = signal.firwin(PDM_FTL_TAPS*16, PDM_FTL_CUT_OFF, nyq=PDM_FTL_SAMPLE_F/2)
taps = (taps1 * (2**PDM_FTL_SCALE_BITS)).astype(int)
def print_head():
print '/* Generated by pdm... | Python | 1 |
dst: edge.target,
local: edge.local,
scopes: edge.scopes,
guard,
peers: vec![false;guard],
drivers: HashMap::new(),
parent_ends: HashSet::new(),
blocked: HashMap::new(),
block_recover: Vec::new(),
hw... | Rust | 0 |
assert_eq!(
out,
[
158, 139, 109, 83, 238, 96, 25, 26, 219, 93, 71, 130, 155, 7, 70, 50, 56, 171, 15,
159, 227, 157, 222, 97, 216, 238, 73, 54, 50, 158, 49, 251
]
);
}
}
<reponame>umanwizard/rustfmt<filename>src/git-rustfmt/main.rs
use std::io::stdout;
use std::path::{Path, PathBuf};
use std::pr... | Rust | 0 |
reflectors[np.ix_(ryrange, rxrange)] = np.logical_or(
reflectors[np.ix_(ryrange, rxrange)], ellipse
)
return reflectors.nonzero()
def video_placement(Ly, Lx):
"""Ly and Lx are lists of video sizes"""
npix = Ly * Lx
picked = np.zeros((Ly.size,), bool)
ly = 0
... | Python | 1 |
]
);
match vm.ctx.get_attr(&cls, "fget") {
Some(getter) => {
let py_method = vm.ctx.new_bound_method(getter, inst.clone());
vm.invoke(py_method, PyFuncArgs::default())
}
None => {
let attribute_error = vm.context().exceptions.attribute_error.clone();
... | Rust | 0 |
for gcn in (self.st_gcnns_compress): #0-3 layer
z1 = gcn(z1)
z1 = z1.mean(-1).mean(-1).view(bs*self.nk,-1)
alpha = self.down_fc(z1)
directions = self.direction(alpha)
N, C, T, V = z.shape
feature = torch.cat((directions.unsqueeze(2).unsqueeze(3).repeat... | Python | 1 |
= 0;
loop {
if reader.buffer_position() - last_progress_byte >= 1024 * 1024 * 10 {
last_progress_byte = reader.buffer_position();
println!(
"Processed {} MB of {}",
last_progress_byte / (1024 * 1024),
path
);
}
... | Rust | 0 |
version
);
}
}
}
struct Point {
x: f64,
y: f64,
}
let stack_point = Point { x: 0.0, y: 0.0 };
let heap_point = Box::new(Point { x: 0.0, y: 0.0 });
fn print_point(p: Point) {
println!("{} - {}", p.x, p.y);
}
print_point(stack_point);
print_point(*heap_point);
#[allow(unused_import... | Rust | 0 |
"")
}
}
pub struct Goal {
link: ComponentLink<Self>,
storage: StorageService,
database: Database,
temp_task: Task,
}
pub enum Msg {
AddTask,
RemoveTask(usize),
SetTitle(String),
SetDescription(String),
}
impl Component for Goal {
type Message = Msg;
type Properties = ();
... | Rust | 0 |
"BufferedReader")?;
let raw = vm.get_attribute(instance.clone(), "buffer").unwrap();
if !objtype::isinstance(&raw, &buffered_reader_class) {
// TODO: this should be io.UnsupportedOperation error which derives both from ValueError *and* OSError
return Err(vm.new_value_error("not readable".to_st... | Rust | 0 |
# Eve W-Space
# Copyright 2014 Andrew Austin and contributors
#
# 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 requi... | Python | 1 |
# parameters for detection
vpy = 224 # y vanishing point
#turn_slope = 15
turn_slope = 0
threshold = 200
bandheight = 8 # height of vertical band of pixels to look at
# WHEEL_TICK_LENGTH = 0.02 * 32/40.
# NUM_ENCODERS = 4
WHEEL_DIAMETER = 0.0666
DRIVE_RATIO = 84./27. * 2.1 # 27t pinion
#DRIVE_RATIO = 84./25. * 2.1... | Python | 1 |
shaped_canvas = shape_img(canvas)
shaped_stroke = shape_img(stroke)
r1_canvas = np.rot90(shaped_canvas)
r1_stroke = np.rot90(shaped_stroke)
r2_canvas = np.rot90(r1_canvas)
r2_stroke = np.rot90(r1_stroke)
r3_canvas = np.rot90(r2_canvas)
r3_stroke = np.rot90(r2_str... | Python | 1 |
(0-1)
"""
if not keywords or not content:
return 0.0
content_lower = content.lower()
total_score = 0.0
for keyword in keywords:
keyword_lower = keyword.lower()
# 精确匹配得分更高
if keyword_lower in content_lo... | Python | 1 |
rCodeNotFound => match lang {
Lang::Ja => "指定されたカラーコードが見つかりませんでした。",
Lang::En => "Can't find the specified color codes.",
},
MsgType::ErrFmtCodeNotFound => match lang {
Lang::Ja => "指定された装飾コードが見つかりませんでした。",
Lang::En => "Can't find the specified format code... | Rust | 0 |
from __future__ import print_function
import cv2 as cv
import argparse
max_value = 255
max_type = 4
max_binary_value = 255
trackbar_type = 'Type: \n 0: Binary \n 1: Binary Inverted \n 2: Truncate \n 3: To Zero \n 4: To Zero Inverted'
trackbar_value = 'Value'
window_name = 'Threshold Demo'
## [Threshold_Demo]
def Thre... | Python | 1 |
= parent_pos.y() + (parent_rect.height() - self.height()) // 2
self.move(x, y)
def paintEvent(self, event):
painter = QtGui.QPainter(self)
painter.setRenderHint(QtGui.QPainter.RenderHint.Antialiasing)
painter.setBrush(QtGui.QBrush(QtGui.QColor(160, 160, 160, 160)))
painter.... | Python | 1 |
flags=re.IGNORECASE)
except Exception as e:
raise ConfluenceException('Error %s: Cannot replace placeholders in template file.' % e)
write_2_file(path, html_content)
def sanitize_for_filename(original_string):
""" Sanitizes a string to use it as a filename on most filesystems.
:... | Python | 1 |
from num2words import num2words
from odoo.tests.common import TransactionCase
class TestNum2WordsAr(TransactionCase):
@classmethod
def setUpClass(cls):
super().setUpClass()
def test_multiple_of_thousands(self):
"""Test num2words function with a multiple of thousands number."""
t... | Python | 1 |
_ as *mut _,
&mut cpus_size as *mut _ as *mut _,
ptr::null_mut(),
0,
);
}
if cpus < 1 {
cpus = 1;
}
}
cpus as usize
}
} els... | Rust | 0 |
}
else if character == CR {
self.cr();
}
else if character >= WHITESPACE {
let offset = self.offset();
self.put(offset, Black as u16, White as u16, character);
self.forward();
}
self.mov();
}
fn puti(&mut self, integer: ... | Rust | 0 |
ata.decode("utf-8"))
print("firmware apps:")
while True:
resp = self.device.readcmd()
if len(resp.data) == 0:
break
print(resp.data.decode("utf-8"))
def echo(self, s):
b = bytes(s, encoding="utf-8")
cmd = FacedancerCommand(self.a... | Python | 1 |
", "ms1"), ("ms3", "ms-three")],
),
},
];
wasmercise_wasi(
pod_name,
client,
pods,
vec![],
containers,
volumes,
None,
OnFailure::Panic,
resource_manager,
)
.await
}
async fn create_loggy_pod(
client: kube::... | Rust | 0 |
this disk."]
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
#[serde(remote = "RecommendedDiskType")]
pub enum RecommendedDiskType {
Unknown,
Standard,
Premium,
#[serde(rename = "StandardSSD")]
StandardSsd,
StandardOrPremium,
#[serde(skip_d... | Rust | 0 |
[dimension][1], desc="Processing videos"):
video_data.append({
'path': item['video_path'],
dimension: item['video_results'],
})
df = pd.DataFrame(video_data)
df.to_csv('results.csv', index=False)
print('resu... | Python | 1 |
| x.map(|val| val.to_vec()))?)
}
// Utilities (not exported):
const EMPTY_TRIE: u8 = 0;
const LEAF_NODE_OFFSET: u8 = 1;
const LEAF_NODE_BIG: u8 = 127;
const EXTENSION_NODE_OFFSET: u8 = 128;
const EXTENSION_NODE_BIG: u8 = 253;
const BRANCH_NODE_NO_VALUE: u8 = 254;
const BRANCH_NODE_WITH_VALUE: u8 = 255;
const LEAF_NOD... | Rust | 0 |
64, (50, 100), 1E-4,
}
}
<filename>src/test_utils.rs<gh_stars>1-10
use std::{io::BufReader, process::{Child, Command, Stdio}, str::from_utf8, time};
use std::io;
use uuid::Uuid;
use std::io::prelude::*;
pub(crate) struct Server {
child: Child,
process_name: String,
pub port: u16,
}
impl Drop for Serve... | Rust | 0 |
T2, RtsPin, PA1, 4);
impl_usart_pin!(USART2, RxPin, PA10, 4);
impl_usart_pin!(USART2, CtsPin, PA11, 4);
impl_usart_pin!(USART2, RtsPin, PA12, 4);
impl_usart_pin!(USART2, TxPin, PA14, 4);
impl_usart_pin!(USART2, RxPin, PA15, 4);
impl_usart_pin!(USART2, TxPin, PA2, 4);
impl_usart_pin!(USART2, RxPin, PA3, 4);
impl_usart_p... | Rust | 0 |
/// pi/4.0
pub static FRAC_PI_4: f32 = 0.785398163397448309615660845819875721_f32;
/// pi/6.0
pub static FRAC_PI_6: f32 = 0.52359877559829887307710723054658381_f32;
/// pi/8.0
pub static FRAC_PI_8: f32 = 0.39269908169872415480783042290993786_f32;
/// 1.0/pi
pub static FRAC_1_PI: f32 =... | Rust | 0 |
_entries_idx
.get(package_id)
// UNWRAP: Indexes guaranteed to be valid -- structure is immutable
.map(|entry_idx| self.entries.get(*entry_idx).unwrap())
}
}
impl<'fetcher> BuildPlanner for BuildPlannerImpl<'fetcher> {
/** Retrieves metadata for local workspace and produces a build plan. */
fn ... | Rust | 0 |
json.loads(response.text)
if response.status_code != 400:
for data in data["events"]:
link = data["url"]
if "ticketmaster.com" ... | Python | 1 |
"""LLM retriever interface definitions."""
from __future__ import annotations
from abc import ABC, abstractmethod
from pathlib import Path
import google.generativeai as genai
from app.core.config import settings
from app.core.logger import logger
genai.configure(api_key=settings.GEMINI_API_KEY)
class BaseRetriev... | Python | 1 |
ait_imgs) > 0
assert APITestTemplate(
"instant_id_sdxl",
"txt2img",
payload_overrides={
"width": 1000,
"height": 1000,
"prompt": "1girl, red background",
},
unit_overrides=[
dict(
image=portrait_imgs[0],
... | Python | 1 |
##########################################################################
#
# Copyright (c) 2007-2008, Image Engine Design Inc. All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are
# met:
#
# * Redis... | Python | 1 |
# -*- coding: UTF-8 -*-
#/**
# * Software Name : pycrate
# * Version : 0.4
# *
# * Copyright 2018. Benoit Michau. P1sec.
# *
# * This library 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 Foundation; either
#... | Python | 1 |
"""
Pangram.
You work for a company that sells fonts through their website. They'd like to
show a different sentence each time someone views a font on their website.
To give a comprehensive sense of the font, the random sentences should use
all the letters in the English alphabet.
They're running a competition to ge... | Python | 1 |
elow the threshold, we are within the target distribution
if rng.gen::<N>() <= check {
break;
}
}
result
}
}
}
impl<N: Float> Distribution<u64> for Poisson<N>
where Standard: Distribution<N>
{
#[inline]
fn sample<R: Rng + ?... | Rust | 0 |
()
for veh_id in self.sorted_ids]
return np.array(speed + pos)
def additional_command(self):
"""See parent class.
Define which vehicles are observed for visualization purposes, and
update the sorting of vehicles using the self.sorted_ids variable.
"""
... | Python | 1 |
if self.drag_button != app_data[0]:
self.drag_begin_x = self.cursor_x
self.drag_begin_y = self.cursor_y
self.drag_button = app_data[0]
self.cam_rot_begin = self.cam.rot
def callback_mouse_release(sender, app_data):
self... | Python | 1 |
opy(self):
cp = self.rng.copy()
repr(cp)
tm.assert_index_equal(cp, self.rng)
def test_shift(self):
shifted = self.rng.shift(5)
assert shifted[0] == self.rng[5]
assert shifted.freq == self.rng.freq
shifted = self.rng.shift(-5)
assert shifted[5] == sel... | Python | 1 |
"""Checker functions for neurodsp.spectral."""
###################################################################################################
###################################################################################################
def check_spg_settings(fs, window, nperseg, noverlap):
"""Check set... | Python | 1 |
lete()
Dump(ctx)
@Alucard.command(aliases=['clearconsole', 'consoleclear'])
async def cls(ctx): # b'\xfc'
await ctx.message.delete()
Clear()
startprint()
@Alucard.command()
async def nitro(ctx): # b'\xfc'
await ctx.message.delete()
await ctx.send(Nitro())
@Alucard.command(name='gmail-bomb', a... | Python | 1 |
ogger.error(f"RL環境初始化失敗: {e}")
return False
def _initialize_rl_agents(self) -> bool:
"""初始化RL代理"""
try:
from ..reinforcement_learning.agents.ppo_agent import PPOAgent
from ..agents.personas.rl_agent import RLAgentWrapper
# 創建PPO代理
... | Python | 1 |
File: *const c_char) -> *mut c_void ;
fn musix_plugin_create_player(plugin: *mut c_void, musicFile: *const c_char)
-> *mut c_void;
fn musix_player_get_meta(player: *mut c_void, what: *const c_char)
-> *const c_char;
fn musix_player_get_samples(player: *mut c_void, target: *mut i16, size: i32... | Rust | 0 |
"w+")
master_proc = subprocess.Popen(command, stderr=log_file)
else:
master_proc = subprocess.Popen(command)
master_and_chunk_server_procs.append(master_proc)
# Launch chunk servers
if start_chunk:
for chunk_server_name in config_data["s... | Python | 1 |
/// ```
/// #[macro_use] extern crate colmac;
///
/// assert_eq!(0, count_args!());
/// assert_eq!(1, count_args!("one"));
/// assert_eq!(3, count_args!("one", "two", "three"));
/// ```
#[macro_export]
macro_rules! count_args {
// base cases
() => {
0usize
};
( $arg:expr ) => {
1usize
... | Rust | 0 |
# SPDX-License-Identifier: Apache-2.0
# (C) Copyright IBM Corp. 2024.
# 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 applicab... | Python | 1 |
F, GPIOG, GPIOH, GPIOI, GPIOJ, GPIOK};
use cast::u32;
bitflags! {
/// Bit value assignment for each of the pins
///
/// Allows for using multiple pins through bitwise or
pub struct Pins: u16 {
const PIN0 = 0x0001;
const PIN1 = 0x0002;
const PIN2 = 0x0004;
const PIN3 ... | Rust | 0 |
class MagicDictionary:
def __init__(self):
self.dict = {}
def buildDict(self, dictionary: List[str]) -> None:
for word in dictionary:
for i, c in enumerate(word):
replaced = self._getReplaced(word, i)
self.dict[replaced] = '*' if replaced in self.dict else c
def search(self, search... | Python | 1 |
"""Google Trends API Toolkit."""
from langchain_community.tools.google_trends.tool import GoogleTrendsQueryRun
__all__ = ["GoogleTrendsQueryRun"]
| Python | 1 |
"""This method returns a new request-level logits processor, customized
to the `target_token` value associated with a particular request.
Returns None if the logits processor should not be applied to the
particular request. To use the logits processor the request must have
a "tar... | Python | 1 |
self.images_te[idx]
filename, _ = os.path.splitext(os.path.basename(f_hr))
if self.args.ext == 'img' or self.benchmark:
hr = imageio.imread(f_hr)
elif self.args.ext.find('sep') >= 0:
with open(f_hr, 'rb') as _f:
hr = pickle.load(_f)
with open(f... | Python | 1 |
import pandas as pd
from nltk.corpus import wordnet as wn
from collections import defaultdict
import spacy
import pickle
df = pd.read_csv("RQ1\\full-triplets-2022Dec16-11720-release.tsv", delimiter="\t")
everyday_things = list(set(df["everyday-thing"]))
et2hypernym_up = defaultdict(list)
et2hyponym_down = defaultdict... | Python | 1 |
xCFF442-0xCFF450",
"0xCFFB29-0xCFFC00",
"0xCFFCE0-0xCFFD00",
"0xCFFFBE-0xD00000",
"0xD0CF4A-0xD0D000",
"0xD0FC7A-0xD0FD00",
"0xD1E989-0xD1EAD7",
"0xD1F751-0xD1F7A0",
"0xD1F9A0-0xD1F9AB",
"0xD1F9D0-0xD1FA00",
"0xD2A130-0xD2A820",
"0x... | Rust | 0 |
from Adarsh.bot import StreamBot
from pyrogram.types import InlineKeyboardMarkup, InlineKeyboardButton
from pyrogram import filters
import time
import shutil, psutil
from utils_bot import *
from Adarsh import StartTime
START_TEXT = """ ʏᴏᴜʀ ᴛᴇʟᴇɢʀᴀᴍ ᴅᴄ ɪꜱ : `{}` """
@StreamBot.on_message(filters.regex("owner😎"... | Python | 1 |
ian>().unwrap(),
min.x,
edge_length,
);
point.position.y = decode(
self.xyz_reader.read_f32::<LittleEndian>().unwrap(),
min.y,
edge_length,
... | Rust | 0 |
ond.output_type == ExecuteResponse.TracebackType:
traceback = json.loads(kernel_respond.output)["traceback"]
console_stderr += traceback
logger.debug(f"the new traceback {console_stderr}")
has_error = True
yield (
None,
... | Python | 1 |
, MAP_EMPTY_SLUG, MAP_FADE_NAME, MAP_FADE_PATH, MAP_FADE_SLUG,
},
object::{
CHAR_BAT_NAME, CHAR_BAT_PATH, CHAR_BAT_SLUG, CHAR_BAT_SPRITE_BROWN_NAME,
CHAR_BAT_SPRITE_GREY_NAME, ENERGY_SQUARE_NAME, ENERGY_SQUARE_PATH, ENERGY_SQUARE_SLUG,
ENERGY_SQUARE_SPRITE_NAME, OBJECT_PATH,
},
u... | Rust | 0 |
# self
from contextlib import contextmanager
from fastapi import Depends
from ..do.article import Article
from ..dao.article import ArticleDao
from sqlmodel.ext.asyncio.session import AsyncSession
# lib
# from config.db import async_transaction
class ArticleService:
"""article"""
def __init__(self, session: ... | Python | 1 |
ng = thread_rng();
for i in (1..(iter.len() - 1)).rev() {
let idx = rng.gen_range(0..=i);
iter.swap(idx, i);
}
}
}
<gh_stars>0
use std::fmt::Display;
use std::time::Instant;
use aoc_2020::get_input;
fn solve(input: &[String]) -> (impl Display, impl Display) {
(0, 0)
}
... | Rust | 0 |
break;
}
}
let ExtendedGcd {
gcd,
y: mut alpha_inv,
..
} = p_minus_one.extended_gcd(&actual_alpha);
assert!(gcd.is_one());
if alpha_inv < BigInt::zero() {
alpha_inv += p_minus_one;
};
(
actual_alpha.to_biguint().unwrap(),
alpha_inv... | Rust | 0 |
import torch
import numpy as np
from scipy.spatial.distance import pdist, squareform
def dice_coefficient(pred, target):
smooth = 1.0
intersection = (pred * target).sum()
return (2.0 * intersection + smooth) / (pred.sum() + target.sum() + smooth)
def combined_sensitivity(real_masks, pred_masks):
real_... | Python | 1 |
lookups
# or default_lookup is provided, defaults are used (all lookups
# available, term is the default lookup). The dictionary value
# (in this case `category.raw`) is the field name in the
# Elasticsearch document (`PostDocument`).
"category": "category.raw",
# The di... | Python | 1 |
(r"textures\tx_b_n_dark elf_m_hair09.dds", 0x070B_5D5B, 0x0E9D_B07F),
(r"textures\tx_b_n_dark elf_m_hpalm.dds", 0x070B_5D5B, 0x450D_4394),
(r"textures\tx_b_n_dark elf_f_hpalm.dds", 0x070B_5D5B, 0x450D_5594),
(r"textures\tx_b_n_dark elf_f_hvamp.dds", 0x070B_5D5B, 0x47E5_F424),
(r"textures\tx_b_n_... | Rust | 0 |
I2S Enable"]
#[inline(always)]
pub fn i2se(&mut self) -> I2SE_W {
I2SE_W { w: self }
}
#[doc = "Bits 8:9 - I2S configuration mode"]
#[inline(always)]
pub fn i2scfg(&mut self) -> I2SCFG_W {
I2SCFG_W { w: self }
}
#[doc = "Bit 7 - PCM frame synchronization"]
#[inline(a... | Rust | 0 |
53537479076557105009345927645442,
249369722351358137898587699909312963803,
300544292992993952360719000252205715076,
323117003802246814764810890058143344905,
243579355010018669877160932197352017974,
],
[
339223760157195739332845857285008200423,
20863286514735120934... | Rust | 0 |
ice: {model_info.get('device', 'Unknown')}",
f"Max Length: {model_info.get('max_length', 'Unknown')} tokens",
f"Temperature: {model_info.get('temperature', 'Unknown')}",
f"Top-p: {model_info.get('top_p', 'Unknown')}"
]
return "\n".join(lines)
class Timer:
"""Simple timer for p... | Python | 1 |
)
self.rop_matrix = self.rop_matrix.to(self.device)
def _generate_orthonormal_matrix(self, in_dim=1024, out_dim=256, seed=42):
"""
生成一个随机正交矩阵 [in_dim, in_dim],并选取前 out_dim 列作为投影矩阵 [in_dim, out_dim]。
"""
torch.manual_seed(seed)
rand_mat = torch.randn(in_dim, in_dim)... | Python | 1 |
fn shaderProgramUse(sp: *mut shaderProgram_s) -> Result;
}
pub const NDSP_OUTPUT_MONO: ndspOutputMode = 0;
pub const NDSP_OUTPUT_STEREO: ndspOutputMode = 1;
pub const NDSP_OUTPUT_SURROUND: ndspOutputMode = 2;
pub type ndspOutputMode = u32;
pub const NDSP_CLIP_NORMAL: ndspClippingMode = 0;
pub const NDSP_CLIP_SOFT: nds... | Rust | 0 |
A>
{
#[inline(always)]
fn drop(&mut self)
{
unsafe { ucp_rkey_destroy(self.handle) }
}
}
impl<E: EndPointPeerFailureErrorHandler, A: LocalToRemoteMemoryAddressTranslation> Deref for TheirRemotelyAccessibleMemory<E, A>
{
type Target = Rc<TheirRemotelyAccessibleEndPoint<E, TheirRemotelyAccessibleWorkerEndPointAd... | Rust | 0 |
# Copyright (C) 2022-2025 Intel Corporation
# LIMITED EDGE SOFTWARE DISTRIBUTION LICENSE
"""Initialize telemetry (logging, traces, ...)"""
import logging
from geti_logger_tools.logger_config import initialize_logger
from geti_telemetry_tools import ENABLE_TRACING, LoggerTelemetry
from geti_telemetry_tools.tracing.c... | Python | 1 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.