text string | label_name string | labels int64 |
|---|---|---|
_device_attribute_query = 0x4002;
pub const CL_DEVICE_WARP_SIZE_NV: cl_nv_device_attribute_query = 0x4003;
pub const CL_DEVICE_GPU_OVERLAP_NV: cl_nv_device_attribute_query = 0x4004;
pub const CL_DEVICE_KERNEL_EXEC_TIMEOUT_NV: cl_nv_device_attribute_query = 0x4005;
pub const CL_DEVICE_INTEGRATED_MEMORY_NV: cl_nv_device_... | Rust | 0 |
return str(self.ExchangeID, 'GBK')
def getParticipantID(self):
'''会员代码'''
return str(self.ParticipantID, 'GBK')
def getTraderID(self):
'''交易所交易员代码'''
return str(self.TraderID, 'GBK')
class CThostFtdcQrySyncDepositField(Structure):
"""查询出入金流水"""
_fields_ = [
... | Python | 1 |
'''
色块识别
1. 识别画面中的红色小球
2. 将识别的到的色块位置,通过串口发送
'''
import sensor
import image
import time
import ustruct as struct
from pyb import UART
# 红色小球的LAB色彩空间阈值 (L Min, L Max, A Min, A Max, B Min, B Max)
RED_BALL_THRESHOLD = (30, 74, 38, 85, -21, 62)
# ROI搜索半径
ROI_R = 10
# 串口初始化
uart = UART(3, 115200)
# OpenMV感光芯片初始化
sensor.re... | Python | 1 |
uest.form['id_give']
# print(userId)
# if userId == informations["userId"]:
# return jsonify({"result":"success", "userInfo": informations})
# else:
# return jsonify({"result":"failed"})
# @app.route('/banana', methods=['POST'])
# def incrementBanana():
# # # 클라이언트로부터 받은 토큰을 디코딩하여 유저 정... | Python | 1 |
lambda: True)
p("colorama.win32.winapi_test", lambda: True)
p("colorama.winterm.win32.windll", "non-None")
p("colorama.winterm.get_osfhandle", lambda _: 1234)
# Pretend that our mock stream has native ANSI support
p(
"colorama.winterm.win32.Ge... | Python | 1 |
from enum import Enum
class GetBetterForecastUnitsPressure(str, Enum):
HPA = "hpa"
INHG = "inhg"
MB = "mb"
MMHG = "mmhg"
def __str__(self) -> str:
return str(self.value)
| Python | 1 |
marshaller;
impl UnmarshallMessage for Unmarshaller {
type Output = UnmarshalledMessage;
fn unmarshall(&self, message: Message) -> Result<Self::Output, EventStreamError> {
Ok(UnmarshalledMessage(
std::str::from_utf8(&message.payload()[..]).unwrap().into(),
))... | Rust | 0 |
erted from "sass-spec/spec/libsass-closed-issues/issue_231.hrx"
#[test]
fn test() {
assert_eq!(
crate::rsass(
"// test.scss:\r\
\na {\r\
\n background-image: url(fn(\"s\"));\r\
\n}"
)
.unwrap(),
"a {\
\n background-image: url... | Rust | 0 |
"""
This module contains commands for interacting with social APIs,
such as fetching anime quotes and quotes of the day.
Functions:
anime_quote(self, ctx: Context | Interaction):
Fetches an anime quote and sends it as an embed message.
qotd_command(self, ctx: Context | Interaction):
Fetches the... | Python | 1 |
rics['std_count'] += 1
else:
# 模型侧处理新增包含逻辑
model_clean = re.sub(r'[^a-zA-Z0-9]', '', str(model_val)).lower() if model_val else ''
metrics['model_values'].append(model_clean)
metrics['model_count'] += 1
# 判断字段类型
... | Python | 1 |
d
//! with the controller's lifetime. The controller's purpose is handle the server management commands:
//! - respond to ping requests - which can be used check that the server is running
//! - listen for a signal to stop the server. Upon receiving the signal the controller will
//! - close the nng Listener and Sock... | Rust | 0 |
Observer.
#[derive(Copy, Clone, Debug, PartialEq, Eq)]
pub struct F2;
impl WhitePoint for F2 {
fn get_xyz<Wp: WhitePoint, T: FloatComponent>() -> Xyz<Wp, T> {
Xyz::with_wp(from_f64(0.99186), T::one(), from_f64(0.67393))
}
}
///CIE fluorescent illuminant series - F7
///
///F7 represents a broadband fluo... | Rust | 0 |
.e., not between sequences in the same file. The first
/// file will be the column names, while the second is the row names.
/// The alignment file(s) can be compressed.
#[structopt(required = true, min_values = 1, max_values = 2, parse(try_from_os_str = path_exists))]
alignments: Vec<PathBuf>,
///... | Rust | 0 |
vior` is Aware (as it is by default), `scandir` will produce `Link` entries so
/// that a consumer can explicitly track their expansion. Otherwise, if Oblivious, operations will
/// allow the operating system to expand links to their underlying types without regard to the
/// links traversed, and `scandir` will produce... | Rust | 0 |
#!/usr/bin/env python
# -*-coding=utf-8-*-
"""
author:lkw
date:2017.10.14
function:更新语料库
email:a18829040692@163.com
"""
import os
from robots.dicts.bai_ke import bai_ke
from robots.dicts.zb import *
class SyncCorpus:
def __init__(self):
self.corpus_path = os.path.join(os.path.dirname(__file__), 'corpus'... | Python | 1 |
msg: MigrateMsg) -> StdResult<Response> {
Ok(Response::default())
}
// Copyright (c) The Libra Core Contributors
// SPDX-License-Identifier: Apache-2.0
//! Integration tests for Protocol negotiation
use crate::negotiate::{
inbound::negotiate_inbound,
outbound::{negotiate_outbound_interactive, negotiate_ou... | Rust | 0 |
queue.push_back((-a + 2*b + 2*c, -2*a + b + 2*c, -2*a + 2*b + 3*c));
}
},
None => {
// We're done, no more nodes to search
break;
}
}
}
(tot_cnt, prim_cnt)
}
#[cfg(not(test))]
fn main() {
for n in (... | Rust | 0 |
n True
def get_children(self):
if self.decorators is not None:
yield self.decorators
yield from self.bases
if self.keywords is not None:
yield from self.keywords
yield from self.type_params
yield from self.body
@cached_property
def _assign_... | Python | 1 |
"""Some calculus-related methods waiting to find a better place in the
SymPy modules tree.
"""
from .euler import euler_equations
from .singularities import (singularities, is_increasing,
is_strictly_increasing, is_decreasing,
is_strictly_decreasing, is_monotonic... | Python | 1 |
all = "snake_case")]
enum Enum {
One { one: u8 },
Two { one: u8, two: u8 },
};
let result = to_attribute_value(Enum::Two { one: 1, two: 2 }).unwrap();
assert_eq!(
result,
AttributeValue {
m: Some(hashmap! {
String::from("type") => AttributeVa... | Rust | 0 |
path = getattr(r, "path", "")
methods = sorted(getattr(r, "methods", []) or [])
# Filter out docs, openapi, static
if path.startswith("/static") or path in {
"/openapi.json",
"/docs",
"/redoc",
"/docs/oauth2-redirect",
}:
contin... | Python | 1 |
(u32, u16) {
loop {
let seconds = self.hib.rtcc.read().bits();
let subsec = self.hib.rtcss.read().rtcssc().bits();
if seconds == self.hib.rtcc.read().bits() {
return (seconds, subsec);
}
}
}
/// Get the current time in millisecon... | Rust | 0 |
tput_dim, kernel_size, degree=3, groups=1, padding=0, stride=1, dilation=1,
dropout=0.0, norm_layer=nn.InstanceNorm1d, **norm_kwargs):
super(KACNConv1DLayer, self).__init__(nn.Conv1d, norm_layer,
input_dim, output_dim,
... | Python | 1 |
# coding: utf-8
# https://github.com/cclauss/Pythonista_ui/blob/master/ValidatingView.py
import ui
# See: https://forum.omz-software.com/topic/2499/textfield-validation-example
class ValidatingView(ui.View):
def __init__(self):
for name in 'lower upper title numeric'.split():
text_field = ui... | Python | 1 |
or not in visited:
visited.add(neighbor)
frontier.append(neighbor)
# Search if node is not adj to any col2 vertex
connected = (
len(
visited.intersection(graph[nod... | Python | 1 |
runner().ok("a {b: set-nth(c d, -1, e)}\n"),
"a {\
\n b: c e;\
\n}\n"
);
}
}
mod t2 {
#[allow(unused)]
use super::runner;
#[test]
fn of_2() {
assert_eq!(
runner().ok("a {b: set-nth(c... | Rust | 0 |
llatrix_fork_epoch,
}
}
pub fn inactivity_penalty_quotient(&self, current_epoch: Epoch) -> Result<u64> {
if current_epoch < self.fork_schedule.altair {
Ok(self.inactivity_penalty_quotient)
} else if current_epoch < self.fork_schedule.bellatrix {
Ok(self.inactivit... | Rust | 0 |
<LICENSE-APACHE or
// http://apache.org/licenses/LICENSE-2.0> or the MIT license <LICENSE-MIT or
// http://opensource.org/licenses/MIT>, at your option. This file may not be
// copied, modified, or distributed except according to those terms.
//! A crate for writing fast and highly resilient in-process gRPC service me... | Rust | 0 |
def test_tmpdir(tmpdir):
# tmpdir already has a path name associated with it
# join() extends the path to include a filename
# the file is created when it's written to
a_file = tmpdir.join("something.txt")
# you can create directories
a_sub_dir = tmpdir.mkdir("anything")
# you can create f... | Python | 1 |
# Last updated: 6/6/2025, 3:31:49 PM
class Solution:
def smallestDistancePair(self, nums: List[int], k: int) -> int:
nums.sort()
def helper(dist):
l, res = 0, 0
for r in range(len(nums)):
while nums[r] - nums[l] > dist:
l += 1
... | Python | 1 |
is inconsistent to leader.
// Then it will update commit_index to 3 and apply {2,3}
// TODO(xp): cleanup commit index at sender side.
let valid_commit_index = msg_entries.last().map(|x| Some(x.log_id)).unwrap_or_else(|| msg.prev_log_id);
let valid_committed = std::cmp::min(msg.leader... | Rust | 0 |
Convert CNN to SNN
snn_model = SNNModel(model).to(device)
# Evaluate SNN on test data
correct = 0
total = 0
with torch.no_grad():
for data in testloader:
images, labels = data[0].to(device), data[1].to(device)
outputs = snn_model(images)
_, predicted = to... | Python | 1 |
, const3, line)?;
chunk.encode2(CONST, 4, const4, line)?;
chunk.encode2(DEFV, 1, 2, line)?;
chunk.encode2(DEFV, 1, 3, line)?;
chunk.encode2(REF, 0, 4, line)?;
chunk.encode0(RET, line)?;
let chunk = Rc::new(chunk);
vm.execute(chunk.clone())?;
assert!(vm.sta... | Rust | 0 |
import torch
from .resnet50 import ResNet50
class ResNet50_Ensemble(torch.nn.Module):
def __init__(self, num_classes=10, num_models=5, discriminator_cls=None):
super(ResNet50_Ensemble, self).__init__()
self.nets = torch.nn.ModuleList([ResNet50(num_classes=num_classes) for _ in range(num_models)])
... | Python | 1 |
from flask import Flask, request, redirect
import sqlite3
import datetime
app = Flask(__name__)
def registrar_clic(id_clic, ip_usuario):
conexion = sqlite3.connect('phishing.db')
cursor = conexion.cursor()
fecha_hora = datetime.datetime.now().strftime("%Y-%m-%d %H:%M:%S")
cursor.execute("INSERT INTO c... | Python | 1 |
terd.pkl"
pkl_path_for_train=r"C:\Users\<user>\Desktop\relevant_directories\relevant\model_new\filtered_train_data\pkl.pkl"
# test_graphs = load_graphs(pkl_path_for_test)
train_graphs_all = load_graphs(pkl_path_for_train)
# חישוב אורך כולל
n_total = len(train_graphs_all)
# test_graphs = load_graphs(pkl_path_for_test... | Python | 1 |
at[cy, cx] = curr_pear
else:
for cx in range(n_col):
for cy in range(cx + 1, n_row):
curr_pear = pearsonr(mat[cx, :], mat[cy, :])[0]
pear_mat[cx, cy] = curr_pear
pear_mat[cy, cx] = curr_pear
return pear_mat
def column_ecdf(matrix: np.ndarray)... | Python | 1 |
!("{}", abstutil::to_json(queue));
}
}
pub fn agent_properties(&self, id: CarID, now: Time) -> AgentProperties {
if let Some(car) = self.cars.get(&id) {
let path = car.router.get_path();
let time_spent_waiting = car.state.time_spent_waiting(now);
// In all c... | Rust | 0 |
ge.lower() in ["text", "markdown"]:
continue
# Generate code
prompt = create_code_generation_prompt(
requirements,
functional_design,
non_functional_design,
file_name,
language
)
code = generate_w... | Python | 1 |
}
true
}
}
impl<'a, S: Set, I> Subset<S, I> {
/// Get a references to the underlying indices. If `None` is returned, then
/// this subset spans the entire domain `data`.
#[inline]
pub fn indices(&self) -> Option<&I> {
self.indices.as_ref()
}
/// Return the superset... | Rust | 0 |
selected_options += 1
pd = DoubleProgressDialog(
selected_options,
partial(self.pd_callback, add_empty_books, metadata_update_books),
self
)
gui = self.wizard().gui
gui.tags_view.blockSignals(True)
try:
# Put Last ... | Python | 1 |
from pyspark.sql import SparkSession, Window
from pyspark.sql.functions import col, from_json, when, to_json, struct, current_timestamp, count, lit, max, min, row_number
from pyspark.sql.types import StructType, StructField, FloatType, TimestampType, StringType
def process_batch(batch_df, batch_id):
window_spec =... | Python | 1 |
cv: constant-volume specific heat, in eV/K. Shape (ph_nvols, num).
free_energy: free energy, in eV. Shape (ph_nvols, num).
entropy: entropy, in eV/K. Shape (ph_nvols, num).
zpe: zero point energy in eV. Shape (ph_nvols).
"""
tmesh = np.lin... | Python | 1 |
ser),
) -> Result<WebPayload<DomainTransactionReportRow>, ApiError> {
let connection = connection.get();
user.requires_scope(Scopes::ReportAdmin)?;
let result = Report::domain_transaction_detail_report(
query.transaction_start_utc,
query.transaction_end_utc,
query.event_start_utc,
... | Rust | 0 |
nImgLoader = DataLoader(train_dataset, args.batch_size, shuffle=True, num_workers=0, drop_last=False,
pin_memory=args.pin_m)
TestImgLoader = DataLoader(test_dataset, args.batch_size, shuffle=False, num_workers=0, drop_last=False,
pin_memory=... | Python | 1 |
($a as usize, $b as usize);
};
}
let aeffect = unsafe { &mut *VSTPluginMain(pass_callback) };
assert_eq!(aeffect.magic, VST_MAGIC);
assert_fn_eq!(aeffect.dispatcher, interfaces::dispatch);
assert_fn_eq!(aeffect._process, interfaces::process_deprecated);
asse... | Rust | 0 |
#[serde(rename = "R")]
QuoteRequest(Box<fix43::messages::quote_request::QuoteRequest>),
/// Quote
#[serde(rename = "S")]
Quote(Box<fix43::messages::quote::Quote>),
/// Settlement Instructions
#[serde(rename = "T")]
SettlementInstructions(Box<fix43::messages::settlement_instructions::SettlementInstructions>),
... | Rust | 0 |
for SESSION_HEADER {}
impl ::core::clone::Clone for SESSION_HEADER {
fn clone(&self) -> Self {
*self
}
}
#[doc = "*Required features: `\"Win32_NetworkManagement_NetBios\"`*"]
pub const UNIQUE_NAME: u32 = 0u32;
<reponame>dpc/titanos<filename>src/arch/aarch64/mod.rs
pub mod pagetable;
use titanium::arch... | Rust | 0 |
= r#"hello:"world"world:1236"#.to_string();
let mut lex = Lexer::new(&s);
macro_rules! get_current( () => { lex.next().unwrap().unwrap() } );
let mut current = get_current!();
macro_rules! msg( ($str:expr) => { format!("expected {}, was {:?}", $str, current) } );
// assert
... | Rust | 0 |
(5258, "Israel", "Qalansuwa", 32.2847222, 34.9797211, 47.0),
City::new(5259, "Israel", "<NAME>", 32.7236111, 35.3125000, 312.0),
City::new(5260, "Israel", "<NAME>", 32.8072222, 35.2602768, 152.0),
City::new(5261, "Israel", "Gan Yavne", 31.7833333, 34.7166672, 55.0),
City::new(5262, "Israel", "Gedera", 31.8166667, 3... | Rust | 0 |
#
# File:
# vinth2p.py
#
# Synopsis:
# Illustrates a call to the vinth2p function.
#
# Category:
# Processing.
#
# Author:
# Fred Clare
#
# Date of initial publication:
# August, 2005
#
# Description:
# Reads from a NetCDF file, creates arguments and calls
# vinth2p, prints some return valu... | Python | 1 |
import sys
from setuptools import setup
from setuptools import find_packages
version = '0.2.0.dev0'
# Please update tox.ini when modifying dependency version requirements
install_requires = [
# load_pem_private/public_key (>=0.6)
# rsa_recover_prime_factors (>=0.8)
'cryptography>=0.8',
'ndg-httpscli... | Python | 1 |
+ bar.rotate(-angle)).into();
//! shape(background_color, icon_color, cross, radius)
//! }
//! }
//! }
//!
//! // The defined shape should then implement the [`ButtonShape`] trait:
//!
//! impl ButtonShape for shape::DynamicShape {
//! fn debug_name() -> &'static str {
//! "CloseButt... | Rust | 0 |
entifier(&self) -> &'static str {
IDENT
}
fn param_info(&self) -> ParamInfo {
ParamInfo {
num_required: 2,
num_optional: 1,
param_docs: vec![
make_param_doc("<destination>", ""),
make_param_doc("<troop_id>", ""),
... | Rust | 0 |
);
println!("This is bad.");
println!("This is bad.");
println!("This is bad.");
println!("This is bad.");
println!("This is bad.");
println!("This is bad.");
}
fn main() {}
//! Gridsim is a library intended to run grid-based simulations.
//!
//! The new generics introduced in gridsim 0.2.0 mak... | Rust | 0 |
r: pixel.r,
g: pixel.g,
b: pixel.b,
});
}
}
let result = plugin_data!(data_out, {
"width" => width,
"height" => height,
});
Ok(result)
}
}
#[no_mangle]
pub fn create(config: &serd... | Rust | 0 |
a file
'otherdir': {},
},
}
},
sources,
)
os.chdir(sources)
dist = Distribution({"packages": ["pkg"], "package_data": {"pkg": ["doc/*"]}})
# script_name need not exist, it just need to be initialized
... | Python | 1 |
_size: Optional[Union[np.ndarray, List]] = None,
out_size: Optional[List[int]] = None,
) -> None:
"""Add module logging information.
Args:
info: (i, idx, repeat) Current parsing information.
module: Parsed module.
module_generator: Module generator used t... | Python | 1 |
* 0.1
# normalize initial weights to 1.0
for cf,i in iterator():
current_norm_value = 1.0*np.sum(abs(cf.weights.ravel()))
if current_norm_value != 0:
factor = (1.0/current_norm_value)
cf.weights *= factor
# compu... | Python | 1 |
from django.test import TestCase
from tests.utils import UserMixin
from two_factor.plugins.phonenumber.method import PhoneCallMethod, SMSMethod
class PhoneMethodBaseTestMixin(UserMixin):
def test_get_devices(self):
other_method_code = PhoneCallMethod.code if isinstance(self.method, SMSMethod) else SMSMet... | Python | 1 |
# Code generated by Lark OpenAPI.
from typing import Any, Optional, Union, Dict, List, Set, IO, Callable, Type
from lark_oapi.core.model import BaseRequest
from lark_oapi.core.enum import HttpMethod, AccessTokenType
from .create_ticket_message_request_body import CreateTicketMessageRequestBody
class CreateTicketMess... | Python | 1 |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
MEK-ICS 완전 자동화 - 로그인부터 다운로드까지
"""
import asyncio
import json
import sys
from pathlib import Path
from datetime import datetime
import os
import shutil
project_root = Path(__file__).parent.parent
sys.path.insert(0, str(project_root))
from playwright.async_api import a... | Python | 1 |
ys_left = (deadline - today).days
if remaining <= 0:
continue
# pad difficulty if short
if len(data["difficulty"]) < total:
data["difficulty"] += [1] * (total - len(data["difficulty"]))
priority = calculate_priority(remaining, days_left)
tasks.append({
... | Python | 1 |
nd()
.stderr()
.is("")
.stdout()
.contains(
"** Executing `echo \"Hello World\"`
Hello World
** Executing `echo \"Goodbye World!\"`
Goodbye World!
",
).unwrap();
});
}
#[test]
fn when_command_failes_... | Rust | 0 |
// Collect iterators into a single future - after doing error handling.
// TODO: actual error handling
futures::stream::futures_unordered(iter).collect().map(|_| ()).map_err(|_| ())
});
// Put on reactor. This reactor will drive the source `Stream`, which by the above l... | Rust | 0 |
none_mut().0, this.to_glib())
}
}
#[cfg(any(feature = "v3_18", feature = "dox"))]
bitflags! {
pub struct SortFlags: u32 {
const NONE = 0;
const CASE_SENSITIVE = 1;
const REVERSE_ORDER = 2;
const REMOVE_DUPLICATES = 4;
}
}
#[cfg(any(feature = "v3_18", feature = "dox"))]
#[do... | Rust | 0 |
ins category
Trains,
/// The freight cars category
FreightCars,
/// The passenger cars category
PassengerCars,
}
impl Category {
const LOCOMOTIVE_SYMBOL: char = 'L';
const PASSENGER_CAR_SYMBOL: char = 'P';
const FREIGHT_CAR_SYMBOL: char = 'F';
const TRAIN_SYMBOL: char = 'T';
... | Rust | 0 |
from django.shortcuts import render, get_object_or_404
from .models import Blog
def blog_list(request):
blogs = Blog.objects.all().order_by('-id')
return render(request, 'blog/blogs.html', {'blogs': blogs})
def blog_detail(request, id):
blog = get_object_or_404(Blog, id=id)
return render(request, 'blo... | Python | 1 |
}
#[test]
#[should_panic(expected = "overflow")]
fn overflow_frac() {
let one = FixedP::from_units_frac(0, 1).unwrap();
let _overflow = MAX + one;
}
#[test]
#[should_panic(expected = "underflow")]
fn underflow_frac() {
... | Rust | 0 |
N_LEN_MASK: u64 = 0x00FF_0000_0000_0000;
/// A mask to get the bits containing the timestamp from the bucket info
pub(crate) const TS_MASK: u64 = 0x0000_FFFF_0000_0000;
/// A mask to get the bits containing the CAS value from the bucket info
pub(crate) const CAS_MASK: u64 = 0x0000_0000_FFFF_FFFF;
/// Number of bits to... | Rust | 0 |
from django.test import TestCase
from django.core.files.uploadedfile import SimpleUploadedFile
from .models import Category, Book
import os
# Category test case
class CategoryTestCase(TestCase):
@classmethod
def setUpTestData(cls):
cls.category = Category.objects.create(
title='Test Cate... | Python | 1 |
#!/usr/bin/env python3
import h5py
from pathlib import Path
import argparse
def compare_interp(fn: Path, doplot: bool = False) -> None:
with h5py.File(Path(fn).expanduser(), "r") as f:
lx1 = f["/lx1"][()]
lx2 = f["/lx2"][()]
lx3 = f["/lx3"][()]
x1 = f["/x1"][:]
x2 = f["/x2... | Python | 1 |
es = Vec::new();
for location in locations.into_iter() {
let Vec3(vx, vy, vz) = location;
for i in 0..6 {
updates.append(&mut Builder::draw_circle(
vx,
vy + i,
vz,
3 + i % 3 - 1,
... | Rust | 0 |
.value_name("MODE")
.help("Sets a mode. Currently, `stdout` and `zsh` are supported")
.takes_value(true),
)
.get_matches();
let repo = match Repository::discover(".") {
Ok(repo) => repo,
Err(_) => std::process::exit(1),
};
let branch = match ... | Rust | 0 |
""
<div style="text-align: center; margin: 30px 0;">
<h3 style="font-family: 'Permanent Marker', cursive; font-size: 2rem; color: #FF6B6B;">
Your friendship wish has been sent to the universe! 🌈
</h3>
<p style="font-family: 'Comic Neue', c... | Python | 1 |
ck2D"],
up_block_types=["UpDecoderBlock2D", "UpDecoderBlock2D"],
latent_channels=4,
)
torch.manual_seed(0)
text_encoder_config = CLIPTextConfig(
bos_token_id=0,
eos_token_id=2,
hidden_size=32,
intermediate_size=37,
... | Python | 1 |
' * leading_spaces}# {line_content.lstrip()}"
self.text_area.delete(line_start, line_end)
self.text_area.insert(line_start, new_content)
else:
# 取消注释:删除行首的 #
stripped_content = line_content.lstrip() # 去掉前导空格
if stripped_content... | Python | 1 |
MREMAP: usize = 5024;
pub const MSGCTL: usize = 5069;
pub const MSGGET: usize = 5066;
pub const MSGRCV: usize = 5068;
pub const MSGSND: usize = 5067;
pub const MSYNC: usize = 5025;
pub const MUNLOCK: usize = 5147;
pub const MUNLOCKALL: usize = 5149;
pub const MUNMAP: usize = 5011;
pub const NAME_TO_HANDLE_AT: usize = ... | Rust | 0 |
ate) fn iced_to_op_code_operand_kind(value: iced_x86_rust::OpCodeOperandKind) -> OpCodeOperandKind {
// Safe, the enums are exactly identical
unsafe { std::mem::transmute(value as u8) }
}
<gh_stars>1-10
pocketmine::plugin!("example-plugin" version "0.2.0": Main);
struct Main;
impl pocketmine::Plugin for Main {
... | Rust | 0 |
se rocket::response::Responder;
#[cfg(test)]
use GrpcConfig;
#[cfg(test)]
use NetAddr;
#[cfg(test)]
use TrowConfig;
#[cfg(test)]
pub fn test_route<'r, A: Responder<'r>>(handler: A) -> rocket::Response<'r> {
let trow_config = TrowConfig {
data_dir: "".to_string(),
addr: NetAddr {
host: "... | Rust | 0 |
# coding=utf-8
# Copyright (c) 2020 Alibaba PAI team.
#
# 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 applicable law ... | Python | 1 |
r("0"),
"total": "true"
});
let cookies = get_cookie_string(&req);
request_handler(url, "weapi", query_params, &cookies, &req).await
}
#[get("/artist/sub")]
pub(crate) async fn index_artist_sub(req: HttpRequest) -> impl Responder {
let query_string = QueryParams::from(req.query_string());
... | Rust | 0 |
# Copyright (C) 2021 - 2025 ANSYS, Inc. and/or its affiliates.
# SPDX-License-Identifier: MIT
#
#
# 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 limita... | Python | 1 |
odec::STRING_CODEC;
#[derive(Serialize, Deserialize, Debug)]
pub struct MethodCall {
pub method: String,
pub args: Value,
}
pub enum MethodCallResult {
Ok(Value),
Err {
code: String,
message: String,
details: Value,
},
NotImplemented,
}
pub trait MethodCodec: Send + Sy... | Rust | 0 |
as usize])?;
}
}
writeln!(f, "}}")?;
Ok(())
}
}
// Pretty-printing with `RealRegUniverse` context.
impl<I: VCodeInst + ShowWithRRU> ShowWithRRU for VCode<I> {
fn show_rru(&self, mb_rru: Option<&RealRegUniverse>) -> String {
use crate::alloc::string::ToString;
... | Rust | 0 |
ions"][node.name].extend(result_list[v[i]])
new_relations = [[] for i in range(len(data))]
for i in range(len(relations)):
for j in range(len(relations[i])):
if "relations" in relations[i][j].keys() and node.name in relations[i][j]["relations"]... | Python | 1 |
, -100, 0, 0, 1.35), (1, 5, 1000, 100, 0, 0, 1.35), (2, 1, 1000, 200, 0, 0, 1.5)},
13: {(0, -1, 2800, -100, 0, 0, 1.35), (1, 5, 1000, 100, 0, 0, 1.35), (2, 1, 1000, 200, 0, 0, 1.5)},
14: {(0, -1, 2800, -100, 0, 0, 1.35), (1, 5, 1000, 100, 0, 0, 1.35), (2, 1, 1000, 200, 0, 0, 1.5)},
15: {(0, -... | Python | 1 |
}
"SSECustomerKeyMD5" => {
obj.sse_customer_key_md5 = Some(deserialize_primitive("SSECustomerKeyMD5", stack, Ok)?);
}
"SSEKMSKeyId" => {
obj.ssekms_key_id = Some(deserialize_primitive("SSEKMSKeyId", ... | Rust | 0 |
sig_old_msg = AggregateSig::new(&atms_registration_2, &signatures[..], &msg_1);
assert_eq!(aggr_sig_old_msg.unwrap_err(), AtmsError::InvalidSignature);
Ok(())
}
#![feature(test)]
extern crate http;
extern crate test;
extern crate ordermap;
extern crate seahash;
extern crate fnv;
mod basic;
mod vec_map;
mod b... | Rust | 0 |
#[derive(StructOpt, Debug)]
pub struct CompatiblityTestParams {
#[structopt(
long,
default_value = "15",
help = "Number of nodes to update in the first batch"
)]
pub count: usize,
#[structopt(long, help = "Image tag of newer validator software")]
pub updated_image_tag: Stri... | Rust | 0 |
kv_cache object per _update_kv_cache call
self._update_kv_cache(
kv_cache_state=kv_cache_state[i], kv_cache=kv_cache[i]
)
else:
for i in range(len(kv_cache)):
self._update_kv_cache(kv_cache=kv_cache[i])
output = {
... | Python | 1 |
ce_results::JsonRpcResult;
use std::sync::atomic::{AtomicUsize, Ordering};
pub const BLOCK_NUMBER_TAGS: [&'static str; 3] = ["latest", "earliest", "pending"];
pub static NONCE_COUNTER: AtomicUsize = AtomicUsize::new(1);
pub fn get_nonce() -> u64 {
NONCE_COUNTER.fetch_add(1, Ordering::SeqCst) as u64
}
pub fn chec... | Rust | 0 |
from typing import Sequence
from typing import TYPE_CHECKING
from sqlalchemy import create_engine
from sqlalchemy import select
from sqlalchemy.orm import DeclarativeBase
from sqlalchemy.orm import Mapped
from sqlalchemy.orm import mapped_column
from sqlalchemy.orm import Session
from sqlalchemy.orm import with_polymo... | Python | 1 |
response_data = {"error": "Unknown model"}
return response_data
return mock_response
def test_successful_analysis_eth(scorer_api_key, mocker):
"""
Tests that analysis can be requested successfully.
"""
event = {
"headers": {"x-api-key": scorer_api_key},
"path": f... | Python | 1 |
name: name()?,
message,
})
}
/// Set a link down.
async fn set_link_down(&self, link: &Link) -> Result<()> {
trace!("Setting link {} down", link);
self.handle()
.link()
.set(link.message().header.index)
.down()
.execute... | Rust | 0 |
import numpy as np
import pytest
import sdr
def test_types():
bsc = sdr.BinarySymmetricChannel(0.5)
y = bsc(0)
assert isinstance(y, int)
y = bsc([0, 1])
assert isinstance(y, np.ndarray)
def test_bit_flips():
rng = np.random.default_rng()
p = rng.uniform(0.2, 0.8)
N = int(1000 / p)... | Python | 1 |
Proto>,
metadata_props: ::protobuf::RepeatedField<StringStringEntryProto>,
// special fields
unknown_fields: ::protobuf::UnknownFields,
cached_size: ::protobuf::CachedSize,
}
impl ModelProto {
pub fn new() -> ModelProto {
::std::default::Default::default()
}
// optional int64 ir_ve... | Rust | 0 |
v, X, Y = computeObjectVelocity(track.box_array, P, track.frame_array, fps=video_fps)
mean_v = np.mean(v) * 3.6 # 取10帧内的平均速度(km/h)
# 当速度太小时,认为目标静止
if mean_v < min_speed:
mean_v = 0
... | Python | 1 |
# MIT License
#
# Copyright (C) The Adversarial Robustness Toolbox (ART) Authors 2018
#
# 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
# r... | Python | 1 |
from fastapi import FastAPI
from pydantic import BaseModel
from chatbot import ChatBot
# Pydantic class
class Message(BaseModel):
content: str
# instantiate app
app = FastAPI()
# instantiate chatbot
chatbot = ChatBot()
@app.post("/chatbot/")
async def chatbot_endpoint(message: Message):
embeddings = chatbot... | Python | 1 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.