text string | label_name string | labels int64 |
|---|---|---|
pub header: DTLSRecordHeader,
pub fragment: &'a [u8],
}
#[derive(Debug, PartialEq)]
pub struct DTLSClientHello<'a> {
pub version: TlsVersion,
pub random: &'a [u8],
pub session_id: Option<&'a [u8]>,
pub cookie: &'a [u8],
/// A list of ciphers supported by client
pub ciphers: Vec<TlsCipherSui... | Rust | 0 |
}
T2 = model.easub + T1 - model.p() * T0;
size_params.vfbsd = model.phig - T2;
}
size_params.cdep0 = sqrt(Q * model_derived.epssub * size_params.ndep * 1.0e6 / 2.0 / size_params.phi);
size_params.ToxRatio = exp(size_params.ntox * log(model.toxref / model.toxe)) / m... | Rust | 0 |
mand += ';'
return self.g_clients[boxID].sendAndRecv(command, result)
'''
* @index : 7
* @param brief:设置直线运动最大加速度
* @param boxID:电箱ID
* @param rbtID:机器人ID,一般为0
* @param MaxAcc:最大直线速度
* @param return: 错误码
'''
def HRIF_SetLinearMaxAcc(self, boxID, rbtID, MaxAcc):
resu... | Python | 1 |
mp_prod(G,D),np.eye(G.shape[0]))
# commutation of stabilizers with logicals
for Z in Z_logicals:
assert np.allclose(symp_prod(G,Z),np.zeros((G.shape[0])))
for X in X_logicals:
assert np.allclose(symp_prod(G,X),np.zeros((G.shape[0])))
# commutation of destabilizers with logicals
for Z... | Python | 1 |
center_file: ("$ROOT/templates/idx_центр".to_string(), root.join("templates").join("idx_центр")),
footer_file: (format!("$ROOT/templates{}idx_foot", ALT_SLASH), root.join("templates").join("idx_foot")),
center_order: CenterOrder::Backward,
styles: vec... | Rust | 0 |
E doesn't
// include 0.
let tryport = NonZeroU16::new(port.get()).unwrap();
if !used_ports.contains(&tryport) {
return Some(tryport);
}
port.next();
}
None
}
impl<I: Ip, D: IpDeviceId, S> PortAllocImpl for UdpConnectionState<I, D, S> {
const TABLE_SIZE: N... | Rust | 0 |
)) >= 0
theta = ll[cs-1]
lbda -= theta
lbda *= lbda > 0
return lbda
def do_z(self):
indices = [0 for i in xrange(self.V)]
for d in xrange(self.Nd):
for i,w in enumerate(self.docs[d]):
zw = self.ptheta[w][indices... | Python | 1 |
if let Some(after) = result.1 {
new_memory_map[insertion_index] = after;
insertion_index += 1;
}
if result.0.is_none() && result.1.is_none() {
new_memory_map[insertion_index] = area.clone();
insertion_index += 1;
}
... | Rust | 0 |
import tensorflow as tf
from doctr.datasets import DataLoader
class MockDataset:
def __init__(self, input_size):
self.data: list[tuple[float, bool]] = [
(1, True),
(0, False),
(0.5, True),
]
self.input_size = input_size
def __len__(self):
r... | Python | 1 |
import cocotb
from cocotb.triggers import Timer
from uvm import sv
async def proc1(args):
await Timer(10, "NS")
args['ok1'] = True
async def proc2(args):
await Timer(15, "NS")
args['ok2'] = True
await Timer(5, "NS")
@cocotb.test()
async def test_fork_join_any(dut):
state = {'ok1': False, ... | Python | 1 |
from dataclasses import dataclass, field
from typing import List, Optional, Union
from .base import BaseMaterial
import numpy as np
def _convert_scalar(val):
"""Convert numpy scalar to Python scalar."""
return val.item() if isinstance(val, np.generic) else val
@dataclass
class MeshStandardMaterial(BaseMateri... | Python | 1 |
er=encoder, storage=storage, policy=policy, distribution=dist)
def update(self, batch: Dict, lock=threading.Lock()) -> Dict[str, Any]: # type: ignore[override]
"""Update the learner model.
Args:
batch (Batch): Batch samples.
lock (Lock): Thread lock.
Returns:
... | Python | 1 |
xd7, 0x52, 0x35, 0x26, 0xd1, 0xbf, 0x70, 0x95, 0x8f, 0x67, 0x7f, 0xf1, 0xcf, 0x57, 0x66,
0x7a, 0x30, 0x83, 0xc1, 0x42, 0x1c, 0xfb, 0xa0, 0xde, 0x85, 0xaf, 0x97, 0xf1, 0x72, 0x43,
0xe9, 0xa2, 0x3, 0x15, 0x88, 0x3d, 0xec, 0x9b, 0x79, 0xa3, 0xd6, 0x67, 0x19, 0xbb, 0x29,
0x1d, 0xb6, 0xbf, 0xda, 0x1b... | Rust | 0 |
import numpy as np
import cv2
import math
import time
import shutil
import os, re
import tensorflow as tf
from net.ops import np_free_form_mask
def f2uint(x):
if x.__class__ == tf.Tensor:
return tf.cast(tf.clip_by_value((x+1)*127.5, 0, 255), tf.uint8)
else:
return np.clip((x+1)*127.5, 0, 255).a... | Python | 1 |
_absolute("C:cwd\\another"), false);
assert_eq!(
nodejs_path::win32::is_absolute("directory/directory"),
false
);
assert_eq!(
nodejs_path::win32::is_absolute("directory\\directory"),
false
);
}
mod error;
mod macros;
mod container;
mod field;
#[cfg(test)]
mod tests;
pub ... | Rust | 0 |
\r\n");
client.close().await;
assert!(client.is_server_dropped());
assert!(client.read_any().is_empty());
// only first request get handled
assert_eq!(num.load(Ordering::Relaxed), 0);
}
#[crate::rt_test]
async fn test_read_large_message() {
let (client, serv... | Rust | 0 |
_0: &mut u64,
// mod_1: &mut u64,
// rem_1: &mut u64,
// ) {
// assert!(rem_0 < mod_0 && rem_1 < mod_1);
// if rem_0 < rem_1 {
// std::mem::swap(rem_0, rem_1);
// std::mem::swap(mod_0, mod_1);
// }
// }
pub fn crt(
mut mod_0: u64,
mut rem_0: u64,
mut mod_1: u64,
mut ... | Rust | 0 |
rginica
6.5,3.0,5.5,1.8,Iris-virginica
7.7,3.8,6.7,2.2,Iris-virginica
7.7,2.6,6.9,2.3,Iris-virginica
6.0,2.2,5.0,1.5,Iris-virginica
6.9,3.2,5.7,2.3,Iris-virginica
5.6,2.8,4.9,2.0,Iris-virginica
7.7,2.8,6.7,2.0,Iris-virginica
6.3,2.7,4.9,1.8,Iris-virginica
6.7,3.3,5.7,2.1,Iris-virginica
7.2,3.2,6.0,1.8,Iris-virginica
6.... | Python | 1 |
xlabel("GPU Number")
axes[i].set_ylabel("Time (seconds)")
axes[i].set_xticks(x)
axes[i].set_xticklabels(valid_gpu_nums)
axes[i].legend()
axes[i].grid(axis="y", alpha=0.3)
# Hide the last subplot if not needed
if len(metrics) < len(axes):
axes[... | Python | 1 |
ime()
if now - last_detect_time >= DETECT_INTERVAL:
last_detect_time = now
detections = detector.detect()
# choose highest-confidence detection that's not picked
detections = [d for d in detections if d.confidence > 0.3]
# pick nearest detection to age... | Python | 1 |
### Parameters
- `board`: The game board.
### Returns
- The move of the bot.
### Notes
- This approach uses the A* algorithm to find the shortest path to the
nearest finish tile, and places a wall either on the path if the tile
has at least one cracked ice... | Python | 1 |
# -*- coding: utf-8 -*-
# pylint: disable=attribute-defined-outside-init, invalid-name, objects-update-used
from tcms.rpc.tests.utils import APIPermissionsTestCase, APITestCase
from tcms.xmlrpc_wrapper import XmlRPCFault
class TestFilter(APITestCase):
"""Test TestExecutionStatus.filter"""
def test_filter_s... | Python | 1 |
ght) - V_STATE.buffer);
const visibleCount = Math.ceil(viewH / V_STATE.rowHeight) + 2 * V_STATE.buffer;
const last = Math.min(V_STATE.total, first + visibleCount);
const padTop = first * V_STATE.rowHeight;
const padBottom = (V_STATE.total - last) * V_STATE.rowHeight;
// Update ... | Python | 1 |
# MultiMolecule
# Copyright (C) 2024-Present MultiMolecule
# This file is part of MultiMolecule.
# MultiMolecule is free software: you can redistribute it and/or modify
# it under the terms of the GNU Affero General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# ... | Python | 1 |
# -*- coding: utf-8 -*-
import pytest
from trustrag.applications import RerankerApp
# import os
def test_reranker():
component_name = 'bge_large'
model = RerankerApp(component_name = component_name)
query = "恐龙是怎么被命名的?"
contexts = ["[12]恐龙是 介于冷血和温血之间的动物2014年6月,有关恐龙究竟是像鸟类和哺乳动物一样的温血动物,还是类似爬行动物、鱼类和两栖动物的冷... | Python | 1 |
IO7_A::RF_GPIO7_SRC_DIO_14),
15 => Val(GPIO7_A::RF_GPIO7_SRC_DIO_15),
16 => Val(GPIO7_A::RF_GPIO7_SRC_CONST_LOW),
17 => Val(GPIO7_A::RF_GPIO7_SRC_CONST_HIGH),
i => Res(i),
}
}
#[doc = "Checks if the value of the field is `RF_GPIO7_SRC_DIO_0`"]
#[inline... | Rust | 0 |
from setuptools import setup, find_packages
setup(
name='precision_mapping',
version='0.9',
packages=find_packages(),
entry_points={
'console_scripts': [
'cortex_mapping = cortex_mapping.main:main',
'hipp_mapping = hipp_mapping.main:main',
],
},
install_r... | Python | 1 |
7V\x8bf9p\xff\x8fP\xfa\x14\
\xee\xd3\xce\xafp\xcf\xf1\x19\xfb]\xb3\xbbF\xd1Y\x5c\
\xe2h\x8f\xb5\x17o\x10\xc4\x0a\xd7\x18\x09\x8bV\xc7_\
\xa3\xb5\x22\xb7{N\xf40)lCj\xdef\xb3\x8e\
\xe8\x1e\xa1s\xc2\x09\xa0\x82v\xa0\x0e!\xd3\x94\x041\
\x9e\xfb\xbd\xf5\x9c_s\xa2Z\xc1\xef\x15\x87n\xe2\xdf\
\xf6g\xa7\xb3\xa6\x90t\x1c@`\x8f\x... | Python | 1 |
()
} else {
let mut out_path = out_dir.clone().join(p.file_name().unwrap());
assert!(out_path.set_extension(target.obj_ext));
if need_run(&p, &out_path, includes_modified) {
let cmd = if target.os() != WINDOWS || ext != "asm" {
cc(p, ext, target, warnings_are_erro... | Rust | 0 |
num = 10 * num + (n as i32);
} else if c == '+' || c == '-' {
res += sign * num;
num = 0;
sign = if c == '+' { 1 } else { -1 };
} else if c == '(' {
stack.push(res);
stack.push(sign);
println!("{}", r... | Rust | 0 |
from __future__ import annotations
import typing as t
import uuid
import click
from globus_cli.constants import EXPLICIT_NULL, ExplicitNullType
from globus_cli.login_manager import LoginManager
from globus_cli.parsing import command
from globus_cli.termio import display
from ._common import GroupSubscriptionVerifie... | Python | 1 |
import os
import subprocess
import sys
def run_command(command):
"""Executes a shell command and prints its output in real-time."""
print(f"Executing: {' '.join(command)}")
process = subprocess.Popen(
command,
stdout=subprocess.PIPE,
stderr=subprocess.STDOUT,
text=True,
... | Python | 1 |
ca.fmax(denominador_S_anaerob, 1e-9)
# Término de inhibición por producto (Etanol)
# Reemplaza: (1.0 - (P / KP_anaerob))**n_p if P < KP_anaerob else 0.0
# Asumiendo KP_anaerob > 0
inhib_P_base = ca.fmax(0.0, 1.0 - P / KP_anaerob)
term_P_anaerob = inhib_P_base**n_p
# Término de INHIBICIÓN por... | Python | 1 |
DataType::Utf8, false),
Field::new("character_maximum_length", DataType::UInt32, true),
Field::new("character_octet_length", DataType::UInt32, true),
Field::new("numeric_precision", DataType::UInt32, true),
Field::new("numeric_precision_radix", DataType::UInt32, true),
... | Rust | 0 |
#!/usr/bin/env python3
"""
Test DIRECTO de limpieza sin instanciar TextSummarizer completo
"""
import sys
import os
import re
import logging
# Configurar logging
logging.basicConfig(level=logging.INFO, format='%(asctime)s - %(levelname)s - %(message)s')
logger = logging.getLogger(__name__)
def clean_summary_text(sum... | Python | 1 |
sing
pub enum ParsePacketError {
/// Failed to parse int from hex representation
ParseIntError(#[from] ParseIntError),
/// Invalid packet format
InvalidPacketFormat,
/// String wasn't ASCII
InvalidString(#[from] Utf8Error),
}
impl FromStr for Packet {
type Err = ParsePacketError;
fn fr... | Rust | 0 |
} else {
None
};
let hwheel = if (mouse.Anonymous.Anonymous.usButtonFlags & (RI_MOUSE_HWHEEL as u16)) != 0 {
Some(mouse.Anonymous.Anonymous.usButtonData as i16)
} else {
None
};
let handle = input.header.hDevice;
Some(InputData::Mouse(MouseData {
device: DEVICE_LI... | Rust | 0 |
from types import TracebackType
from typing import Optional, Type, List
from urllib.parse import unquote
import httpx
from modules.apihelper.models.genshin.akasha import (
AkashaRank,
AkashaLeaderboardCategory,
AkashaLeaderboard,
AkashaSubStat,
AkashaArtifact,
)
BASE_URL = "https://akasha.cv/api"... | Python | 1 |
# Slixmpp: The Slick XMPP Library
# Copyright (C) 2012 Nathanael C. Fritz, Lance J.T. Stout
# This file is part of Slixmpp.
# See the file LICENSE for copying permission.
from slixmpp.xmlstream import ElementBase, ET
class UserMood(ElementBase):
name = 'mood'
namespace = 'http://jabber.org/protocol/mood'
... | Python | 1 |
, path);
});
if words.next().is_some() {
panic!(
"Garbage after end of line on line {} in {:?}",
line_num + 1,
path
);
}
// Parse array types.
let array_len = type_.find('[').map(|open_brace| {
if !type_.ends_with(']') {
panic!("Missing `]` on line {} in {:?}", line_num + 1, path);
... | Rust | 0 |
!(0x01 << 7)) | ((value as u32 & 0x01) << 7);
self.w
}
}
#[doc = "Real-Time Clock Prescaler Select\n\nValue on reset: 0"]
#[derive(Clone, Copy, Debug, PartialEq)]
#[repr(u8)]
pub enum RTCPS_A {
#[doc = "0: Off"]
_000 = 0,
#[doc = "1: If RTCLKS = x0, it is 1; if RTCLKS = x1, it is 128."]
_001... | Rust | 0 |
oat]:
"""Calculate Fibonacci levels."""
high, low = self.df["high"].max(), self.df["low"].min()
diff = high - low
return {
"Fib 161.8%": round(high + diff * 1.618, PRECISION),
"Fib 100.0%": round(high, PRECISION),
"Fib 78.6%": round(high - diff * 0.786... | Python | 1 |
balanced)
# Stage 2: Home vs Away
train_non_draw = train_df[train_df['FullTimeResult'] != 'D'].copy()
X_train_s2 = train_non_draw[test_features].fillna(train_non_draw[test_features].median())
y_train_s2 = train_non_draw['FullTimeResult'].map({'H': 0, 'A': 1})
stage2_model = RandomForestCla... | Python | 1 |
)
# Store the user's stopping criteria for the later training run.
stop_iters = args.stop_iters
stop_timesteps = args.stop_timesteps
stop_reward = args.stop_reward
num_agents = args.num_agents
as_test = args.as_test
# Override these criteria for the pre-training run.
args.stop_iters ... | Python | 1 |
#!/usr/bin/python3
# Factorial of a number using recursion
def factorial(n):
"""Less efficient recursive function.
With O(2^n) time complexity."""
if n == 0 or n == 1:
return 1
else:
return n * factorial(n - 1)
# Using Memoization or Dynamic Programming to optimize the recursive factor... | Python | 1 |
start=1):
if i > 1 and trial.check_early_stopping():
break
evaluated_curve.append(obj)
trial.add_measurement(
vz.Measurement(
steps=i,
elapsed_secs=0.1 * i,
metrics={'accuracy': obj, 'latency': 0.5 * num_layers... | Python | 1 |
bytes long. Let's try with 2 items instead: */
type L2i = L<i64>;
pub fn size_l2i() {
println!("Size of Li2: {}", size_of::<L2i>()) // 24 bytes
}
/* Where are the extra 8 bytes coming from? Let's build a stupid thing: */
struct StupidThing {
v: i64,
n: i64,
}
pub fn size_stupidthing() {
println!("S... | Rust | 0 |
r()
.filter_map(|t| match t {
TypeParamBound::Trait(t) => last_path_element(&t.path),
_ => None, // skip lifetime etc.
})
.map(|t| self.generic_to_fs(&t))
.collect::<Vec<String>>()
... | Rust | 0 |
guards against regression for the issue found in fxbug.dev/62989. The test attempts to
// create an inconsistent state on the dhcp server by allowing the server to complete a transaction
// with a client, thereby creating a record of a lease. The server is then restarted; if the linked
// issue has not been fixed, the... | Rust | 0 |
tr(sdt))
dt_list = set_data_types(sdt)
print("\nSelected columns from dataset:\n" + str(dt_list))
ACT_LABELS = ["sit", "std", "dws", "ups", "wlk", "jog"]
act_labels = ACT_LABELS [0:6] # all activities
print("Selected activites: " + str(act_labels))
TRIAL_CODES = {
ACT_LABELS[0]:[5],
ACT_LABELS[1]:[6],
... | Python | 1 |
(),
GetSequenceLastEntry(result) => result.is_ok(),
GetSequencePublicPolicy(result) => result.is_ok(),
GetSequencePrivatePolicy(result) => result.is_ok(),
GetSequenceUserPermissions(result) => result.is_ok(),
GetRegister(result) => result.is_ok(),
... | Rust | 0 |
255) : m_OutputImage[rgb][i][k] = 255
elif (m_OutputImage[rgb][i][k] < 0) : m_OutputImage[rgb][i][k] = 0
displayImage()
def zoomImage() :
global m_InputImage, m_OutputImage, m_inH, m_inW, m_outH, m_outW, window, canvas, paper
size = askinteger("이미지 확대", "확대배율을 입력해주세요.")
# (중요!) 출력 영상 크... | Python | 1 |
(ni.node_id().clone()).is_none());
}
// Next 2 inserts will always remove a node id
for ni in shuffled.iter().skip(8) {
assert!(dht_connectivity.insert_neighbour(ni.node_id().clone()).is_some())
}
// Check the first 7 node ids match our neighbours, the last element depends on distance and ... | Rust | 0 |
r"""
Provides frozendict, a simple immutable dictionary.
"""
try:
from ._frozendict import *
c_ext = True
del _frozendict
except ImportError:
from ._frozendict_py import *
c_ext = False
from .version import version as __version__
from . import monkeypatch
from .cool import *
def _getFrozendictJs... | Python | 1 |
: crate::R<DT1_CFG_SPEC>) -> Self {
R(reader)
}
}
#[doc = "Register `DT1_CFG` writer"]
pub struct W(crate::W<DT1_CFG_SPEC>);
impl core::ops::Deref for W {
type Target = crate::W<DT1_CFG_SPEC>;
#[inline(always)]
fn deref(&self) -> &Self::Target {
&self.0
}
}
impl core::ops::DerefMut f... | Rust | 0 |
steps,
}
}
fn is_vertical(&self) -> bool {
self.direction == Direction::Vertical
}
}
#[derive(Debug, PartialEq)]
enum Error {
IoError,
InvalidInstruction,
}
impl fmt::Display for Error {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
match self {
... | Rust | 0 |
toplay() {
sprite.fill_area((0u, SCREENH-16), (368u, 16u), gray);
sprite.fill_area((4u, SCREENH-12), (360u, 8u), black);
}
sprite
}
/// Full-featured graphic display. Used for the normal game play and automatic play mode.
pub struct GraphicDisplay {
/// Spri... | Rust | 0 |
from __future__ import division
import sys
import math
import pysam
import numpy as np
from sklearn.cluster import DBSCAN
import random
import re
import os
import multiprocessing
import argparse
import time
from get_raw_bkp import getInsertSize
def calCrossReads(bam_name):
f = open(graph, "w")
edge_dict = {}
... | Python | 1 |
ler.get_last_lr())
step(optimizer, scheduler)
step(new_optimizer, cos_scheduler)
assert scheduler.get_last_lr() == pytest.approx(cos_scheduler.get_last_lr())
step(optimizer, scheduler)
step(new_optimizer, cos_scheduler)
assert scheduler.get_last_lr() == pytest.approx(cos_scheduler.get_last_lr())... | Python | 1 |
!("this packet type is not icmp")
}
}
*/
fn main() {
use std::str::FromStr;
let args = Cli::from_args();
let target: String = args.target_ip.parse().unwrap();
// target: &StringがIpAddr型に一致しなかった場合パニックを起こして終了。
let target: IpAddr = IpAddr::from_str(&target)
.unwrap_or_else(|_| panic!("Ch... | Rust | 0 |
*font).ident, CIDFont_get_opt_index(font), 0i32, &mut info) {
CIDType0Error_Show(error, (*font).ident);
return;
}
let cffont = &mut *info.cffont;
cff_read_private(cffont);
cff_read_subrs(cffont);
if !(*cffont.private.offset(0)).is_null()
&& cff_dict_known(
*cffont... | Rust | 0 |
__title__ = "httpx"
__description__ = "A next generation HTTP client, for Python 3."
__version__ = "0.28.1"
| Python | 1 |
rap();
virtio_device.read_link_status(addr);
}
_ => {
info!("Unhanded IO Exit");
}
},
VcpuExit::IoOut(port, addr) => {
match port {
#[allow(clippy::cast_ptr_alignment)]
SHUTDOWN_PORT => {
return Ok(None);
}
UHYVE_UART_PORT => {
self.uart(addr... | Rust | 0 |
4 * 4, 3, 1, 1, bias=True)
self.pixel_shuffle_denoise = nn.PixelShuffle(2)
self.HRconv_denoise = nn.Conv2d(64, 64, 3, 1, 1, bias=True)
self.conv_last_denoise = nn.Conv2d(64, 3, 3, 1, 1, bias=True)
self.lrelu = nn.LeakyReLU(negative_slope=0.1, inplace=True)
def forward(self, x):
... | Python | 1 |
help='显示统计信息')
parser.add_argument('--tree', action='store_true', help='显示树结构')
parser.add_argument('--interactive', '-i', action='store_true', help='交互式模式')
args = parser.parse_args()
# 构建分类树
print("正在加载法律分类数据...")
tree = LegalClassificationTree()
try:
tree.build_tree_fro... | Python | 1 |
target_os = "macos"))]
{
assert!(is_same_file(&mock_files[0], &mock_files[0]));
assert!(is_same_file(&mock_files[0], &mock_files[1]));
assert!(is_same_file(&mock_files[0], &mock_files[2]));
assert!(is_same_file(&mock_files[1], &mock_files[2]));
assert!... | Rust | 0 |
5 => Trace,
_ => unreachable!(),
}
}
/// The default log format. See [`LogBuilder::with_format`] for more information.
///
/// [`LogBuilder::with_format`]: struct.LogBuilder.html#method.with_format
pub const DEFAULT_LOG_FORMAT: &str = "{time} {level} {fileLine} {msg}";
/// The default time format. ... | Rust | 0 |
}
}
pub fn resources_grpc_to_oci(res: &grpcLinuxResources) -> ociLinuxResources {
let devices = {
let mut d = Vec::new();
for dev in res.Devices.iter() {
let major = if dev.Major == -1 {
None
} else {
Some(dev.Major)
};
... | Rust | 0 |
te_model_to_string;
use atelier_json::JsonWriter;
use atelier_test::examples::weather::make_weather_model;
fn main() {
let mut writer = JsonWriter::new(true);
let test_case = make_weather_model();
let output = write_model_to_string(&mut writer, &test_case.model);
assert!(output.is_ok());
println!("... | Rust | 0 |
#!/usr/bin/env python3
""" MongoDB Operations with Python using pymongo """
from pymongo import MongoClient
if __name__ == "__main__":
""" Provides some stats about Nginx logs stored in MongoDB """
client = MongoClient('mongodb://127.0.0.1:27017')
nginx_collection = client.logs.nginx
n_logs = nginx_co... | Python | 1 |
ckport.text(R.strings.white_tiger.sysMessageFairPlayMsg.arenaBanStop.header())
body = backport.text(R.strings.white_tiger.sysMessageFairPlayMsg.arenaBanStop.body())
icon = 'InformationIcon'
data = {'savedData': {'isStarted': isStarted,
'reason': data.get('reason', ... | Python | 1 |
),
headers: TaskHeaders::default(),
custom_headers: Default::default(),
payload: NIL.to_vec().into(),
}
}
}
impl TaskEvent {
pub fn add_custom_header<S: Into<String>>(&mut self, key: S, value: S) {
self.custom_headers.insert(key.into(), value.into());
}
}... | Rust | 0 |
eE = Node('E')
graph = Graph()
graph.add_node(nodeA)
graph.add_node(nodeB)
graph.add_node(nodeC)
graph.add_node(nodeD)
graph.add_node(nodeE)
graph.add_edge(nodeA, nodeB, 1)
graph.add_edge(nodeA, nodeC, -4)
graph.add_edge(nodeB, nodeC, 2)
graph.add_edge(nodeB, nodeD, 5)
grap... | Python | 1 |
target_layer: torch.nn.Module,
targets: List[torch.nn.Module],
activations: torch.Tensor,
grads: torch.Tensor,
eigen_smooth: bool = False) -> np.ndarray:
weights = self.get_cam_weights(input_tensor, t... | Python | 1 |
PyObject,
name: *const c_char,
min: Py_ssize_t,
max: Py_ssize_t,
...
) -> c_int;
pub fn Py_BuildValue(format: *const c_char, ...) -> *mut PyObject;
ignore! {
fn _Py_BuildValue_SizeT(arg1: *const c_char, ...) -> *mut PyObject;
fn _PyArg_NoKeywords(funcname: *... | Rust | 0 |
DecoderInner::Lz4(rd) => rd.read(buf),
DecoderInner::Zstd(rd) => rd.read(buf),
}
}
}
pub struct Encoder<W: Write>(EncoderInner<W>);
impl<W: Write> Encoder<W> {
pub fn new(wr: W, codec: Codec) -> Result<Self> {
Ok(Self(match codec {
Codec::Uncompressed => EncoderInner::U... | Rust | 0 |
},
};
use circle_collision::CircleCollider;
use gravity::{GravitySource, GravityTarget};
use physics::components::{
ForceAccumulator,
Mass,
Position,
Rotation,
Vector,
Velocity,
};
use scene_management::{resources::SceneLoader, components::InScene};
use crate::{
collision,
model::{Pla... | Rust | 0 |
Clone, Debug, PartialEq, Deserialize, Serialize)]
pub struct FsConfig {
pub tag: String,
pub socket: PathBuf,
#[serde(default = "default_fsconfig_num_queues")]
pub num_queues: usize,
#[serde(default = "default_fsconfig_queue_size")]
pub queue_size: u16,
#[serde(default = "default_fsconfig_da... | Rust | 0 |
assert msg['header']['msg_type'] == 'execute_input'
# Open comm
comm = comm_manager.new_comm('test_api', data='open')
msg = self._get_next_msg()
assert msg['header']['msg_type'] == 'stream'
assert msg['content']['text'] == 'open\n'
# Get message
comm.send('me... | Python | 1 |
import __init__
import torch
from backbone.camera import CameraOptions
from backbone.mamba_ssm.models import MambaConfig
from utils.config import EasyConfig
class ScanObjectNNConfig(EasyConfig):
def __init__(self):
super().__init__()
self.name = 'ScanObjectNNConfig'
self.k = [32, 32, 32]... | Python | 1 |
}
}
fn with_data(data_path: PathBuf, operation: metadata::v1::Operation) -> Self {
Self { operation, data_path: Some(data_path) }
}
}
/// Build package options (compressors, patchers, ...)
pub struct BuildOptions {
pub compressors: Vec<CoderOptions>,
pub patchers: Vec<CoderOptions>,
}
im... | Rust | 0 |
"value",
"one_of_many_required": True,
},
)
valueReference: fhirtypes.ReferenceType | None = Field( # type: ignore
default=None,
alias="valueReference",
title="Characteristic value",
description=None,
json_schema_extra={
"element_propert... | Python | 1 |
# Licensed to the Apache Software Foundation (ASF) under one
# or more contributor license agreements. See the NOTICE file
# distributed with this work for additional information
# regarding copyright ownership. The ASF licenses this file
# to you under the Apache License, Version 2.0 (the
# "License"); you may not u... | Python | 1 |
s function unless the calling instance
/// itself has static lifetime.
fn register_and_enable_irq_handler(&'static self) -> Result<(), &'static str> {
Ok(())
}
}
/// Device driver management functions.
///
/// The `BSP` is supposed to supply one global instance.
... | Rust | 0 |
ouldNotBeZero.into(),
"SELECT * FROM Arith WHERE id = 2 % 0",
),
(
LiteralError::DivisorShouldNotBeZero.into(),
"SELECT * FROM Arith WHERE id = 2 % 0.0",
),
(
EvaluateError::BooleanTypeRequired(format!(
"{:?}",
... | Rust | 0 |
from effect import Burn
class Ability:
def __init__(self, name, mana_cost, damage, effect=None):
self.name = name
self.mana_cost = mana_cost
self.damage = damage
self.effect = effect
def use(self, user, target):
target.health -= self.damage
print(f"DEBUG: {user.... | Python | 1 |
wvaEF5zXb26Fz9rcQpDWS57CtERHpNehXCPcNoHGKutQY
* // hex: 0xd43593c715fdd31c61141abd04a99fd6822c8558854ccde39a5684e7a56da27d
* // Using the full hex key, truncating to the first 20 bytes (the first 40 hex chars)
* H160::from_str("d43593c715fdd31c61141abd04a99fd6822c8558").expect("internal H160 is val... | Rust | 0 |
#[doc = "Bit 21 - DP over voltage"]
#[inline(always)]
pub fn dp_ovv(&self) -> DP_OVV_R {
DP_OVV_R::new(((self.bits >> 21) & 0x01) != 0)
}
#[doc = "Bit 20 - DM overcurrent"]
#[inline(always)]
pub fn dm_ovcn(&self) -> DM_OVCN_R {
DM_OVCN_R::new(((self.bits >> 20) & 0x01) != 0)
... | Rust | 0 |
implicit none ";
let expected_output = IResult::Done("", ());
let result = parse_implicit(input);
assert_eq!(result, expected_output);
}
#[test]
fn parse_implicit6() {
let input = "implicit none ! Some stuff";
let expected_output = IResult::Done("", ());
let result = parse_implic... | Rust | 0 |
struct Bar;
/// #[derive(Component)]
/// struct Baz;
/// #[derive(Component)]
/// struct Qux;
///
/// #[derive(WorldQuery)]
/// struct MyFilter<T: Component, P: Component> {
/// _foo: With<Foo>,
/// _bar: With<Bar>,
/// _or: Or<(With<Baz>, Changed<Foo>, Added<Bar>)>,
/// _generic_tuple: (With<T>, Witho... | Rust | 0 |
ties()
self.spPr = spPr
self.pictureOptions = pictureOptions
self.dPt = dPt
self.dLbls = dLbls
self.trendline = trendline
self.errBars = errBars
self.cat = cat
self.val = val
self.invertIfNegative = invertIfNegative
self.shape = shape
... | Python | 1 |
ressEvent::Test(progress_counter.clone()));
struct State {
predictions: Array1<f32>,
test_metrics: tangram_metrics::RegressionMetrics,
}
let State { test_metrics, .. } = zip!(
features.axis_chunks_iter(Axis(0), n_examples_per_batch),
labels.as_slice().chunks(n_examples_per_batch),
)
.fold(
{
let predi... | Rust | 0 |
from datetime import date
import unittest
from owlready2.prop import DataProperty
from ontolearn.value_splitter import BinningValueSplitter
from owlapy.owl_reasoner import StructuralReasoner
from owlapy.owl_literal import OWLDataProperty, OWLLiteral
from owlapy.iri import IRI
from owlapy.owl_ontology_manager import On... | Python | 1 |
# Copyright 2025 Google LLC
#
# 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
#
# https://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, ... | Python | 1 |
# This code is part of Qiskit.
#
# (C) Copyright IBM 2020.
#
# This code is licensed under the Apache License, Version 2.0. You may
# obtain a copy of this license in the LICENSE.txt file in the root directory
# of this source tree or at http://www.apache.org/licenses/LICENSE-2.0.
#
# Any modifications or derivative wo... | Python | 1 |
return;
}
try {
const response = await fetch(`/api/vllm/conda-status/${this.currentServer}`);
const data = await response.json();
if (data.success) {
... | Python | 1 |
import pandas as pd
import matplotlib.pyplot as plt
from openpyxl import load_workbook
from openpyxl.drawing.image import Image as XLImage
from io import BytesIO
def analisar_produtos(arquivo_excel):
"""
Esta função realiza uma análise dos produtos listados em um arquivo Excel, calcula um score ponderado
c... | Python | 1 |
[1])
if pos_interp:
pos_embed = self.pos_embed
cls_pos_embed = pos_embed[0, 0, :].unsqueeze(0).unsqueeze(1)
other_pos_embed = pos_embed[0, 1:, :].unsqueeze(0).transpose(
(0, 2, 1))
P = int(other_pos_embed.shape[2]**0.5)
H = x.shape[1] /... | Python | 1 |
import torch
import torch.nn as nn
from src.gans.relativistic_gan import RelativisticGAN
class R3GAN(RelativisticGAN):
def __init__(self, G, D, batch_size=64, steps_d=1, lambda_r1=10, lambda_r2=10):
super(R3GAN, self).__init__(G, D, batch_size, steps_d)
self.lambda_r1 = 10
self.lambda_r2 =... | Python | 1 |
#!/usr/bin/env python
#
# Copyright 2016 Cisco Systems, 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 applicab... | Python | 1 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.