text string | label_name string | labels int64 |
|---|---|---|
'''
Created on Apr 30, 2025
@author: Pat Deegan
@copyright: Copyright (C) 2025 Pat Deegan, https://psychogenic.com
'''
import sys
from spasic.experiment.experiment_result import ExpResult
from spasic.experiment.experiment_parameters import ExperimentParameters
def run_experiment(params:ExperimentParameters, response... | Python | 1 |
let mut group = c.benchmark_group("quaternion conjugate");
bench_glam!(group, |b| {
use glam::Quat;
bench_unop!(b, op => conjugate, ty => Quat)
});
bench_cgmath!(group, |b| {
use cgmath::Quaternion;
bench_unop!(b, op => conjugate, ty => Quaternion<f32>)
});
bench_... | Rust | 0 |
o::BufReader::new(File::open(old_path)?);
let new_file = io::BufWriter::new(File::create(&new_path)?);
if self.decompress {
self.decompress(old_file, new_file)?;
} else {
self.compress(old_file, new_file)?;
}
let last_access = FileTime::from_last_access_t... | Rust | 0 |
R, 'input[name="search"]')))
search_input.send_keys('Post')
search_button = webDriver_wait.until(expected_conditions.element_to_be_clickable((By.XPATH, '//button[i[contains(@class, "fa fa-search")]]')))
search_button.click()
take_screenshot(webDriver, "Post to edit")
post = webDriver_wait.until(e... | Python | 1 |
reassign_with_default)]
use std::env;
use std::error;
use std::fmt;
use std::fmt::Debug;
use std::sync::Arc;
use chrono::offset::Utc;
use chrono::DateTime;
use reqwest::{header, Client, Method, Request, StatusCode, Url};
use schemars::JsonSchema;
use serde::de::DeserializeOwned;
use serde::de::{MapAccess, SeqAccess, V... | Rust | 0 |
opt.cuda_ray = True
opt.preload = True
if opt.patch_size > 1:
opt.error_map = False # do not use error_map if use patch-based training
# assert opt.patch_size > 16, "patch_size should > 16 to run LPIPS loss."
assert opt.num_rays % (opt.patch_size ** 2) == 0, "patch_size ** 2... | Python | 1 |
d_v1_v2 = c_distance(links[key]['receive_post'], links[key]['send_post'])
# d_v1_v2 = d_v1_v2_all[links[key]['receiver']][links[key]['sender']]
channel_num,perception_size =calculate_channels(d_v1_v2,links[key]['perception_len'],fea_number)
links[key]['perception_size'] = percept... | Python | 1 |
ssh.exec_command(command)
# 检查是否成功
exit_status = stdout.channel.recv_exit_status()
if exit_status != 0:
error = stderr.read().decode()
logger.error(f"下载失败: {error}")
raise Exception(f"下载失败: {error}")
# 确认文件存在
stdin, stdout, st... | Python | 1 |
/arch/sparc_sysv.s", true)),
("riscv32", _, _, _) => Some(("src/arch/riscv.s", true)),
("riscv64", _, _, _) => Some(("src/arch/riscv64.s", true)),
("wasm32", _, _, _) => Some(("src/arch/wasm32.o", true)),
_ => None,
}
}
fn main() {
use std::env::var;
let arch = var("CARGO_C... | Rust | 0 |
key=self.with_pos_embed(memory, pos),
value=memory, attn_mask=memory_mask,
key_padding_mask=memory_key_padding_mask)
tgt_sub = tgt_sub + self.dropout1_sub(tgt2_sub)
tgt_sub = self.norm1_sub(tgt_sub... | Python | 1 |
g=(3 // 2), bias=bias))
m.append(nn.PixelShuffle(2))
if bn:
m.append(nn.BatchNorm2d(n_feats))
if act_type == 'relu':
m.append(nn.ReLU(True))
elif act_type == 'prelu':
m.append(nn.PReLU(n_feats))
... | Python | 1 |
itedForwarding: DifferentiatedServiceCodePoint = DifferentiatedServiceCodePoint(0b101110);
/// Voice Admit.
pub const VoiceAdmit: DifferentiatedServiceCodePoint = DifferentiatedServiceCodePoint(0b101100);
/// Also known as AF11.
pub const AssuredForwardingClass1LowDropProbability: DifferentiatedServiceCodePoint... | Rust | 0 |
MIN_CART_COUNT = 1
MAX_CART_COUNT = 50
| Python | 1 |
p.x + dir.x * mind,
};
let tolog = self.log << 4 | robot_index << 2 | robot_dir; //self.log.cons(Move{c: robot_index,d: robot_dir});
let mut res = State {
bo: self.bo,
robots: self.robots.clone(),
log: tolog,
};
res.robots[robot_index] = p;
Some(res)
}
fn enumerate_states(&self) -> Vec<State<'a... | Rust | 0 |
ding {count} events in {burst_duration_seconds} seconds")
events_per_second = count // burst_duration_seconds
start_time = time.time()
end_time = start_time + burst_duration_seconds
sent_count = 0
while time.time() < end_time and sent_count < count:
... | Python | 1 |
system" fn Java_com_exonum_binding_storage_indices_ProofMapIndexProxy_nativeValuesFrom(
env: JNIEnv,
_: JClass,
map_handle: Handle,
key: jbyteArray,
) -> Handle{
let res = panic::catch_unwind(|| {
let key = convert_to_key(&env, key)?;
Ok(utils::to_handle(
match *utils::ca... | Rust | 0 |
{
fn default() -> AtomicCell<T> {
AtomicCell::new(T::default())
}
}
impl<T> From<T> for AtomicCell<T> {
#[inline]
fn from(val: T) -> AtomicCell<T> {
AtomicCell::new(val)
}
}
impl<T: Copy + fmt::Debug> fmt::Debug for AtomicCell<T> {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> ... | Rust | 0 |
# Copyright (c) OpenMMLab. All rights reserved.
# Please refer to https://mmengine.readthedocs.io/en/latest/advanced_tutorials/config.html#a-pure-python-style-configuration-file-beta for more details. # noqa
# mmcv >= 2.0.1
# mmengine >= 0.8.0
from mmengine.config import read_base
with read_base():
from .mask_rc... | Python | 1 |
{
s.map(|x| x.to_uppercase())
}
/// Receives a string vector from R, uppoercases it, then returns it
/// Demonstrates passing a string vector from/to R
pub(crate) fn pass_multiple_characters_fn(s: CharVec) -> CharVec {
s.into_iter().map(|x| x.map(to_uppercase)).collect()
}
// Just a helper function
fn to_upp... | Rust | 0 |
LOCK, &mask, ptr::null_mut());
libc::signalfd(
-1, /* create new fd */
&mask,
0, /* no flag */
)
};
if sig_fd < 0 {
println!("BUG: Failed to handle SIGHUP signal");
exit(1);
}
// 1. Start parser threads
parsers.push(mpath::parser_s... | Rust | 0 |
handler_call_details):
method = handler_call_details.method.split('/')[-1]
GRPC_SERVER_METRICS['requests_in_flight'].labels(method=method).inc()
start_time = time.time()
try:
response = await continuation(handler_call_details)
latency = time.time() - sta... | Python | 1 |
fn origin_channel_package_get(
req: &mut Envelope,
sock: &mut zmq::Socket,
state: &mut ServerState,
) -> Result<()> {
let msg: proto::OriginChannelPackageGet = req.parse_msg()?;
match state.datastore.get_origin_channel_package(&msg) {
Ok(Some(ref package)) => req.reply_complete(sock, packag... | Rust | 0 |
oc(alias = "MEMBARRIER_CMD_SHARED")]
Global = 1,
/// `MEMBARRIER_CMD_GLOBAL_EXPEDITED`
GlobalExpedited = 2,
/// `MEMBARRIER_CMD_REGISTER_GLOBAL_EXPEDITED`
RegisterGlobalExpedited = 4,
/// `MEMBARRIER_CMD_PRIVATE_EXPEDITED`
PrivateExpedited = 8,
/// `MEMBARRIER_CMD_REGISTER_PRIVATE_EXPEDI... | Rust | 0 |
from datetime import date
from tinydb import TinyDB, where
from tinydb.storages import JSONStorage
from tinydb_serialization import SerializationMiddleware
from tinydb_serialization.serializers import DateSerializer
def test_serializer(tmpdir):
path = str(tmpdir.join('db.json'))
serializer = SerializationM... | Python | 1 |
import allure
from locators.locators_login_page import LoginPageForm
from locators.locators_login_page import LoginPageButtons
from pages.base_page import BasePage
class LoginPageBurger(BasePage): # создали класс страницы входа в сервис
def __init__(self, driver):
self.driver = driver
@allure.step(... | Python | 1 |
;
re = Regex::Concat(Box::new(re), Box::new(re2)); // left associative
}
Ok(re)
}
// re_2 -> re_3 | re_3* | re_3? | re_3+
fn parse_regex_2(input: ParseStream) -> syn::Result<Regex> {
let mut re = parse_regex_3(input)?;
loop {
if input.peek(syn::token::Star) {
let _ = input... | Rust | 0 |
,
"BB_anon_425_2_mask_pred_postprocessed.png",
0.75,
),
(
"BB_anon_425_2_mask_pred.png",
"BB_anon_425_2_mask_pred_postprocessed.png",
0.5,
),
(
"GM_anon_780_3_mask_pred.png",
"GM_anon_780_3_mask_pred_post... | Python | 1 |
Clone)]
pub struct FontForSort_s {
pub name: *mut c_types::c_char,
pub flags: c_types::c_int,
pub font: *mut c_types::c_char,
}
pub type FontForSort = FontForSort_s;
extern "C" {
pub fn EnumFontsEx() -> *mut FontForSort;
}
extern "C" {
pub fn EnumFontsFromDirectoryEx(
directory1: *const c_t... | Rust | 0 |
"""Wrapper around classic-algos.
This is needed to extract features at different blocks of the Vision Transformer.
ruff: disable=N801
"""
from __future__ import annotations
import timm
from timm.models.vision_transformer import VisionTransformer as TimmVisionTransformer
from .ops import SwiGLUFFNFused
def module... | Python | 1 |
ale,
# # exchange_xy=False,
# # )
# self.pos_func = PosEmbedding()
# def forward(self, src_boxes: Tensor, tgt_boxes: Tensor = None):
# if tgt_boxes is None:
# tgt_boxes = src_boxes
# # src_boxes: [batch_size, num_boxes1, 4]
# # tgt_boxes: [batch_size,... | Python | 1 |
from django.contrib import admin
from .models import Beetype,Beeyard,Hive,Intervention,Gathering,Contamination
from django.contrib.auth.admin import UserAdmin
# Register your models here.
# Admin pour le modèle Hive avec des filtres avancés
class HiveAdmin(admin.ModelAdmin):
list_display = ('name', 'bee_type', '... | Python | 1 |
level)
.init();
// Parse the input parameters.
match matches.subcommand() {
Some(("generate", sub_matches)) => PrivateConfig::new()
.export(sub_matches.value_of("filename").unwrap())
.context("Failed to generate key pair")?,
Some(("run", sub_matches)) => spawn(su... | Rust | 0 |
= decode( wordarr+, bytearr+ ); // "k+" means "successor in k"
// m := ( x - y ) - [contents of word at "wordarr"];
// [byte pointed to by "bytearr"] := [the eight bits at "m"<20:13>];
// r := TWO'S-COMPLEMENT OF codgen();
// r := x + y + m + r + 5;
// ENDIF;
// RETURN( r );
fn decode(wordarr... | Rust | 0 |
let client = Openstreetmap::new(mock_server.uri(), credentials);
// WHEN
let actual = client.user().users(&user_ids).await.unwrap();
// THEN
assert_eq!(actual, expected);
}
#[rstest(response_str, expected,
case(
r#"
<osm version="0.6" generator="OpenStreetMap server">
... | Rust | 0 |
onst EGUI_PASS: &str = "egui_pass";
/// Keeps the transform uniform up to date.
pub const EGUI_TRANSFORM: &str = "egui_transform";
}
/// The names of `bevy_egui` stages.
pub mod stage {
/// Runs after [bevy::app::stage::EVENT]. This is where `bevy_egui` translates Bevy's input events to Egui.
pub const... | Rust | 0 |
f/main/.assets/docs.png"
)]
#![forbid(unsafe_code)]
#![cfg_attr(feature = "docs", feature(doc_cfg))]
#![deny(missing_docs)]
#![deny(unused_imports)]
#![deny(missing_debug_implementations)]
#![warn(clippy::expect_used)]
#![deny(clippy::unwrap_used)]
#![deny(unused_results)]
use http_types::headers::{HeaderName, HeaderV... | Rust | 0 |
t_memory("memory").unwrap();
let data = String::from("data_test");
let mem_addr = 0x2220;
memory.write(mem_addr as u32, data.as_bytes()).unwrap();
let slice_raw = memory.read(mem_addr as u32, data.as_bytes().len()).unwrap();
assert_eq!(data.as_bytes(), slice_raw);
}
}
// ... | Rust | 0 |
new_value: NaiveDateTime,
) -> Result<Giveaway, anyhow::Error> {
use crate::schema::Giveaways::dsl::*;
diesel::update(Giveaways.filter(id.eq(giveaway_id)))
.set(end_time.eq(new_value))
.execute(&self.pool.get()?)?;
Ok(Giveaways
.filter(id.eq(giv... | Rust | 0 |
from typing import Dict, Any
from fastapi import HTTPException
from src.users.dao import UserDao
from src.users.schemas import UserFromDB, UserStatistics
class UserService:
@classmethod
async def get_user_statistics(cls, domain: str) -> UserStatistics:
try:
recent_7days_users_count = awa... | Python | 1 |
prompt_embeddings = self.llm_model.get_input_embeddings()(
prompt.to(x_enc.device)) # (batch, prompt_token, dim)
# 对 LLM 词嵌入矩阵 (word_embeddings) 进行线性映射(降维或变换),然后恢复原来的维度顺序。
# self.word_embeddings 词嵌入矩阵 word_embeddings∈R V×D V = 词汇表大小 (vocab_size) D = 词嵌入维度 (embedding_dim)
... | Python | 1 |
self.inner.resourceid)
.field("serial", &self.inner.serial)
.finish()
}
}
<filename>src/main.rs
// SPDX-License-Identifier: Apache-2.0
use clap::{App, Arg};
use std::fmt;
use std::io::prelude::*;
use std::fs::File;
use std::io::{BufRead, BufReader};
fn main() {
let matches = App::new(... | Rust | 0 |
##################################
############################## УПРАВЛЕНИЕ ПРОФИЛЕМ #############################
# Обновление профиля пользователя
@router.callback_query(F.data.startswith("admin_user_refresh:"))
async def functions_user_refresh(call: CallbackQuery, bot: Bot, state: FSM, arSession: ARS):
user_id ... | Python | 1 |
# -*- coding: utf-8 -*-
# File: report.py
# Created at 16/11/2021
"""
Description:
-
-
"""
from os import terminal_size
from marshmallow import Schema, fields, INCLUDE, EXCLUDE
from paydi_lib.schema import BaseResponse
from src.utils.format import is_report_type
#################################... | Python | 1 |
the auxiliary security header is still included if the frame
/// was previously secured.
/// - `data_offset`: Offset of the data payload relative to
/// `buf`, so that the payload of the frame is contained in
/// `buf[data_offset..data_offset + data_len]`.
/// - `data_len`: Length of the data paylo... | Rust | 0 |
= "Option::is_none")]
pub up: Option<bool>,
#[serde(skip_serializing_if = "Option::is_none")]
/// Note: This flag asks to perform UV *within the authenticator*,
/// for instance with biometrics or on-device PIN entry,
/// use of pinAuth is implicit where required.
pub uv: Option<bool>,
}
// #[... | Rust | 0 |
SPEC {
type Reader = R;
}
///`write(|w| ..)` method takes [ttocn::W](W) writer structure
impl crate::Writable for TTOCN_SPEC {
type Writer = W;
}
///`reset()` method sets TTOCN to value 0
impl crate::Resettable for TTOCN_SPEC {
#[inline(always)]
fn reset_value() -> Self::Ux {
0
}
}
use super... | Rust | 0 |
根据 [SEP] 等特殊标记对文本进行分段处理,否则直接从预测的文本概率图中提取匹配的短语
# get_phrases_from_posmap: 根据匹配的概率图从文本中提取短语
if remove_combined:
sep_idx = [i for i in range(len(tokenized['input_ids'])) if tokenized['input_ids'][i] in [101, 102, 1012]]
phrases = []
for logit in logits:
max_idx = logit.argmax()... | Python | 1 |
from create_dist_multi_processing import run_mnist_experiment
from pathlib import Path
from robustness_experiment_box.verification_module.auto_verify_module import AutoVerifyModule
from robustness_experiment_box.verification_module.property_generator.one2any_property_generator import One2AnyPropertyGenerator
from auto... | Python | 1 |
the size of the auth field.
pub fn len(&self) -> usize {
self.bytes.len()
}
// Check if auth field is empty.
pub fn is_empty(&self) -> bool {
self.bytes.is_empty()
}
}
<gh_stars>0
use serde::Deserialize;
use crate::{
api::format_api,
ast::{Biblio, BiblioResolver},
form... | Rust | 0 |
ates(&self) -> Result<(), Error> {
let mut tera = self.tera.borrow_mut();
tera.full_reload().map_err(TeraFailure::from)?;
Ok(())
}
}
/// Converts an HTML body string into a hyper response.
fn html_response(body: &str, can_gzip: bool) -> Result<Response, Error> {
let mut response = Respo... | Rust | 0 |
atch meta.chunks_stored.get(chunk.index.0 as usize).map(|b| *b) {
Some(true) => return Ok(true), // already stored.
Some(false) => {
meta.chunks_stored.set(chunk.index.0 as usize, true);
write_chunk(&mut tx, config, &candidate_hash, chunk.index, &chunk);
write_meta(&mut tx, config, &candidate_hash, &meta)... | Rust | 0 |
w)
k1.cw_list.append(cw)
t_keep_cw = torch.where(cond, t_l_cw, t_r_cw)
s_last_0 = s_keep_0 ^ (t_last_0 * s_cw)
s_last_1 = s_keep_1 ^ (t_last_1 * s_cw)
t_last_0 = t_keep_0 ^ (t_last_0 * t_keep_cw)
t_last_1 = t_keep_1 ^ (t_last_1 * t_keep_cw)
... | Python | 1 |
import json
import os
# Define file paths
trophies_extracted_file = "out/trophies_extracted.json"
input_folder = "../src/content/trophy" # Folder with individual trophy JSON files
# Function to match trophies and add the code to individual files
def add_trophy_code_to_files():
# Read the extracted trophies data... | Python | 1 |
ampled_data = model.sample(10)
params = model.to_dict()
model2 = GaussianMultivariate.from_dict(params)
pdf = model.probability_density(sampled_data)
pdf2 = model2.probability_density(sampled_data)
assert np.all(np.isclose(pdf, pdf2, atol=0.01))
cdf = model.cumulative_... | Python | 1 |
import os
# Trainer: Where the ✨️ happens.
# TrainingArgs: Defines the set of arguments of the Trainer.
from trainer import Trainer, TrainerArgs
# GlowTTSConfig: all model related values for training, validating and testing.
from TTS.tts.configs.glow_tts_config import GlowTTSConfig
# BaseDatasetConfig: defines name,... | Python | 1 |
# Copyright 2023 The Kubric Authors.
#
# 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 or agreed to in w... | Python | 1 |
;
use crate::character::Character;
#[derive(Clone, Debug)]
pub struct StatusEffect {
pub status_type: StatusType,
pub duration: Duration,
}
#[derive(Copy, Clone, PartialEq, Eq, Debug)]
pub enum StatusType {
// Poison,
Bless,
// Unconscious,
// Dead,
}
// order is important, as we use this to... | Rust | 0 |
print("统计每个类别物体出现的草图数:")
cat_num = dict()
all_nums = 0
for sketch in tqdm(sketches):
for item in sketch.get_items():
all_nums += item.get_strokes_len()
if item.category in cat_num:
cat_num[item.category] += item.get_strokes_len()
else:
... | Python | 1 |
Properties::ACYCLIC) {
determinize(fst)?;
minimize(fst)?;
}
} else {
minimize(fst)?;
}
} else {
if !fst.properties().contains(FstProperties::I_DETERMINISTIC) {
if !fst.properties().intersects(
FstProperties::... | Rust | 0 |
'''
Author : Thyssen Wen
Date : 2022-10-28 14:26:24
LastEditors : Thyssen Wen
LastEditTime : 2022-11-04 09:33:46
Description : EGTEA dataset config
FilePath : /SVTAS/config/_base_/dataset/egtea/egtea_stream_feature.py
'''
DATASET = dict(
temporal_clip_batch_size = 1,
video_batch_size = 1,
... | Python | 1 |
容
if 'shots' in result:
doc.add_heading('分镜头建议', level=1)
for i, shot in enumerate(result['shots'], 1):
doc.add_paragraph(f"{i}. {shot}")
if 'bgm_suggestions' in result:
doc.add_heading('BGM音效建议', level=1)
for bgm in result['bgm_su... | Python | 1 |
_tuplespaceInstanton_causet(Causet_WRITE, cone, brane_id, 0)?;
let causet = if default_causet_size >= write_causet_size {
Causet_DEFAULT
} else {
Causet_WRITE
};
self.divide_cone_causet(causet, cone, brane_id, parts)
}
fn divide_cone_causet(
&se... | Rust | 0 |
impossible to pass the task context into the VM. So we store it in a thead local storage.
// Just as the initial version of Rust's async/await did. The following codes are taken from
// https://github.com/rust-lang/rust/pull/51580/files#diff-2437bade3937fa15310072df88db95aa1d2cd047069275cdddaccf2e4b1dc431R53-R116
thr... | Rust | 0 |
# output "Hello Copilot" to the screen
print("Hello Copilot")
"""open the csv file called "nfl_offensive_stats.csv" and read in the csv data from the file"""
import csv
with open('nfl_offensive_stats.csv') as csvfile:
nfl_offensive_stats = csv.reader(csvfile)
for row in nfl_offensive_stats:
print(row)
... | Python | 1 |
}
<gh_stars>1-10
fn main() -> Result<(), Box<dyn std::error::Error>> {
tonic_build::configure().compile(
&["proto/runtime/v1alpha2/api.proto"],
&[
"proto",
"proto/runtime/v1alpha2/",
//"proto/github.com/gogo/protobuf/gogoproto/",
],
)?;
println!("... | Rust | 0 |
org/registry/vulkan/specs/1.0-extensions/html/vkspec.html#VkImportSemaphoreFdInfoKHR)
pub fn vkImportSemaphoreFdKHR(device: vk::VkDevice, pImportSemaphoreFdInfo: *const khr_external_semaphore_fd::VkImportSemaphoreFdInfoKHR) -> vk::VkResult; [pfn_vkImportSemaphoreFdKHR: khr_external_semaphore_fd::PFN_vkImportSem... | Rust | 0 |
LONGLONG
}
SqlType::Tinyint(_) => msql_srv::ColumnType::MYSQL_TYPE_TINY,
SqlType::UnsignedTinyint(_) => {
flags |= msql_srv::ColumnFlags::UNSIGNED_FLAG;
msql_srv::ColumnType::MYSQL_TYPE_TINY
}
SqlType::Bool => msql_srv::ColumnTy... | Rust | 0 |
CGTCCTTCGTGTTTGGCGTTTACATACGGCACCCCGTTTCTGCACGTTAACCGTCTAGTATCCAACGGTGGATGGCGGACGCTAGACTATAGATATGAGATATCGAGACCTGGAGCTGGGTGTGGCTGCAGCCCGGGTCATTGCGGGCTGTGAATTCAAGGGCATGTAAACAAGCGTATATCGAACAGTGGATGGGCACCTGCAATACTCACGGTAGAGTTAGCTCACAGGATTCACGTTGAGGACTATGAGTCCCTCTTCGCTAGCAGTCTGGGGGGATATGGAGTTTAATAGCTTGACGTAGTAATGGGGCTCAAACA... | Python | 1 |
::<Vec<u8>>()
)
)
.as_str(),
"216db1f37dc7240a2b7ce62242948623"
);
}
#[test]
fn pi2() {
let input = r#"
function main(output: * [3750] i32): i32 {
var a: [52514] i32;
var b: i32;
var c: i32;
var d: i32; d = 0;
var e: i32;
v... | Rust | 0 |
ttention_mask,
)
else:
sample = upsample_block(
hidden_states=sample, temb=emb, res_hidden_states_tuple=res_samples, upsample_size=upsample_size, encoder_hidden_states=encoder_hidden_states,
)
# post-process
sample = self.c... | Python | 1 |
# mypy: allow-untyped-defs
import torch
class StaticForLoop(torch.nn.Module):
"""
A for loop with constant number of iterations should be unrolled in the exported graph.
"""
def forward(self, x):
# constant
ret = [i + x for i in range(10)]
return ret
example_args = (torch.rand... | Python | 1 |
#-----------------------------------------------------------------------------
# Copyright (c) 2012 - 2019, Anaconda, Inc., and Bokeh Contributors.
# All rights reserved.
#
# The full license is in the file LICENSE.txt, distributed with this software.
#-------------------------------------------------------------------... | Python | 1 |
>>> print(enums.getvalue()) # <BLANKLINE> is necessary for doctest
class Foo(IntFlag):
ham = 1
spam = 2
<BLANKLINE>
<BLANKLINE>
class Bar(IntFlag):
bacon = 3
"""
self.data.setdefault(enum_name, []).appe... | Python | 1 |
{
#[inline(always)]
pub(crate) fn new(bits: u8) -> Self {
EP0_TX_FIFO_CNT_R(crate::FieldReader::new(bits))
}
}
impl core::ops::Deref for EP0_TX_FIFO_CNT_R {
type Target = crate::FieldReader<u8, u8>;
#[inline(always)]
fn deref(&self) -> &Self::Target {
&self.0
}
}
#[doc = "Fi... | Rust | 0 |
.expect("to succeed");
}
/// JWK has algorithm and user provided a non-matching expected algorithm
#[test]
#[should_panic(expected = "WrongAlgorithmHeader")]
fn compact_jws_decode_with_jwks_shared_secret_mismatched_alg() {
let token = Compact::<PrivateClaims, Empty>::new_encoded(
... | Rust | 0 |
# © 2025 EarthDaily Analytics Corp.
"""
============================
Create time stacks of images
============================
This example demonstrates how to aggregate the images returned from a Catalog image search by date.
"""
from descarteslabs.catalog import Product, properties as p
from descarteslabs.utils im... | Python | 1 |
Commons Attribution-NonCommercial-ShareAlike 3.0 Unported License
//! // Contact the author for other licensing options
//!
//! /*
//! Technical details:
//!
//! The main volume noise is generated from a deformed periodic grid, which can produce
//! a large range of noise-like patterns at very cheap evalutation cos... | Rust | 0 |
",
"ύ",
],
"Tamil": [
"க",
"த",
"ப",
"ட",
"ர",
"ம",
"ல",
"ன",
"வ",
"ற",
"ய",
"ள",
"ச",
"ந",
"இ",
"ண",
"அ",
"ஆ",
"ழ",
"ங",
"எ",
"... | Python | 1 |
ed, body_pred) not in used_pairs and (body_pred, head_pred) not in used_pairs:
satisfaction = self.compute_satisfaction(head_pred, [body_pred])
rule = Rule(
head=f"{head_pred}(X)",
body=[f"{body_pred}(X)"],
... | Python | 1 |
Self { relays }
}
}
/// Defines a compatibility format for deserializing relays info that supports
/// both the old and the new format for relay info
#[derive(Debug, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct PublicKeysResultCompatibility {
/// DEPRECATED. Legacy format only public key... | Rust | 0 |
redis_key_prefix,
})
}
// pub fn new_server(
// address: String,
// port: u16,
// pg_pool: RenewablePostgresPool,
// ) -> std::io::Result<actix_web::dev::Server> {
// let data = app_data(pg_pool);
// let server = HttpServer::new(move || {
// App::new()
// .wrap(TracingLogger... | Rust | 0 |
<gh_stars>1-10
#![feature(proc_macro_hygiene, decl_macro)]
#[macro_use] extern crate rocket;
use rocket::Request;
use rocket::response::status::BadRequest;
use rocket_contrib::json::Json;
use enigmap::HexMap;
use enigmap::generators::{Circle, MapGen, Islands, Inland};
#[catch(404)]
fn not_found(req: &Request) -> Str... | Rust | 0 |
| Error::InvalidResponse {
endpoint: "/channels/{channel_id}/{type}",
source: e,
})?;
Ok(videos)
}
/// Quickly access live/upcoming for a set of channels.
///
/// This method is similar to [`live`](#method.live) and usually replies much faster.
/// It is mor... | Rust | 0 |
::new(xs);
{
let unshielded = shielded.unshield();
assert_eq!(original, unshielded.as_ref());
}
let unshielded = shielded.unshield();
original == unshielded.as_ref()
}
}
/*
* Python SDK for Opsgenie REST API
*
* Python SDK for Opsgenie REST API
*
* The ... | Rust | 0 |
_CLK_LeftGui,
KeyLeftAlt = ffi::CorsairLedId_CLK_LeftAlt,
KeyLang2 = ffi::CorsairLedId_CLK_Lang2,
KeySpace = ffi::CorsairLedId_CLK_Space,
KeyLang1 = ffi::CorsairLedId_CLK_Lang1,
KeyInternational2 = ffi::CorsairLedId_CLK_International2,
KeyRightAlt = ffi::CorsairLedId_CLK_RightAlt,
KeyRightGu... | Rust | 0 |
# -*- coding: utf-8 -*-
# Part of Odoo. See LICENSE file for full copyright and licensing details.
{
'name': 'PayuMoney Payment Acquirer',
'category': 'Accounting/Payment Acquirers',
'sequence': 375,
'summary': 'Payment Acquirer: PayuMoney Implementation',
'description': """
PayuMoney Payment A... | Python | 1 |
"""
You have a lock in front of you with 4 circular wheels. Each wheel has 10 slots: '0', '1', '2', '3', '4', '5', '6', '7', '8', '9'. The wheels can rotate freely and wrap around: for example we can turn '9' to be '0', or '0' to be '9'. Each move consists of turning one wheel one slot.
The lock initially starts at '0... | Python | 1 |
}
expect_punct = !expect_punct;
}
Some(output)
}
//Macro to generate the proc_macro code without repetition
macro_rules! include_path_macro {
($original_ident: literal, $new_ident: ident, $for_windows: expr) => {
#[proc_macro]
pub fn $new_ident(t: TokenStream) -> TokenStream... | Rust | 0 |
_fit(amount: AmountT) -> Self {
let take_all = Self::REF_UNIT.si_prefix().is_none();
let mut it =
Self::iter_units().filter(|u| take_all || u.si_prefix().is_some());
// `it` returns atleast the reference unit, so its safe to unwrap here
let first = it.next().unwrap();
... | Rust | 0 |
ower().replace(' ', '_')}.json"
stage_content = load_data(stage_filename)
accumulated_content += f"{st.session_state.stages[i][0]}:\n{stage_content}\n\n"
with st.spinner(f"Our AI is working on your {next_stage[0].lower()}..."):
... | Python | 1 |
sec % 60.0);
println!("");
//save trained model and estimate and display results
model.set_params(opt.get_params());
model.reset();
model.save("cifar10.lstm").ok();
opt.get_opt().save("optimizer.json").ok();
println!("Final results on test data:");
tester.set_model(model.clone... | Rust | 0 |
if !self.dev_addr.is_empty() {
os.write_bytes(3, &self.dev_addr)?;
}
if !self.nwk_s_key.is_empty() {
os.write_bytes(4, &self.nwk_s_key)?;
}
if self.rx1_dr_offset != 0 {
os.write_uint32(11, self.rx1_dr_offset)?;
}
if self.rx2_dr != 0 {
... | Rust | 0 |
value,
dec_hook=partial(default_deserializer, type_decoders=type_decoders),
type=target_type,
strict=strict,
)
except msgspec.DecodeError as msgspec_error:
raise SerializationException(str(msgspec_error)) from msgspec_error
def get_serializer(type_encoder... | Python | 1 |
b}[33m1\u{1b}[0m interactions with \u{1b}[33m1\u{1b}[0m checks in \u{1b}[33m2000ms\u{1b}[0m\n\nSuccess: \u{1b}[32m0\u{1b}[0m\nFailure: \u{1b}[31m0\u{1b}[0m\n Error: \u{1b}[31m0\u{1b}[0m\nSkipped: \u{1b}[2m1\u{1b}[0m\n");
}
}
pub mod helper;
pub mod loader;
<filename>src/crates/local.rs
use super::CrateTrait;
use c... | Rust | 0 |
H,zeros,name_new):
# import torch
model = torch.jit.load(NN_model)
model=model.to('cpu')
model.eval()
x1=np.linspace(-TH[0],TH[0],200)
x2=np.linspace(-TH[0],TH[0],200)
X1,X2=np.meshgrid(x1,x2)
data=np.array(tuple(zip(np.ravel(X1),np.ravel(X2))))
with torch.no_grad(): # No need to t... | Python | 1 |
"UPGRADE" => UpgradeStep::Upgrade,
other => UpgradeStep::Unknown(other.to_owned()),
}
}
}
impl std::str::FromStr for UpgradeStep {
type Err = std::convert::Infallible;
fn from_str(s: &str) -> std::result::Result<Self, Self::Err> {
Ok(UpgradeStep::from(s))
}
}
im... | Rust | 0 |
_ids {
if let Err(e) = ton_engine.wait_state(&block_id, None, false).await {
log::error!("Failed to wait shard state: {:?}", e);
continue 'outer;
}
}
sh... | Rust | 0 |
::raw::c_int,
arg5: ::std::os::raw::c_int,
arg6: ::std::os::raw::c_int,
) -> ::std::os::raw::c_int,
>,
) -> ::std::os::raw::c_int,
>,
pub xPhraseCount: ::std::option::Option<
unsafe extern "C" fn(arg1: *mut Fts5Context) -> ::std... | Rust | 0 |
str1 = 'geeksforgeeks'
K = 'seek'
def temp(sub): return ''.join(char for char in sub if char in set(K))
res1 = K in temp(str1)
str1 = iter(str1)
res2 = all(next((ele for ele in str1 if ele == chr), None) is not None for char in K)
print('Is substring in order:\n', res1, '\n', res2)
'''
# Python3 code to test su... | Python | 1 |
Error>> {
loop {
info!("Metrics refresh started.");
let public_keys_and_usernames = get_all_public_keys_and_usernames(&server_state).await?;
METRICS_STATISTICS
.total_users
.set(public_keys_and_usernames.len() as i64);
let mut total_documents = 0;
le... | Rust | 0 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.