text
string
label_name
string
labels
int64
] # zyz cb_qubits = torch.einsum('bnki,bnkj->bnkij', self.c_zyz(c), self.b_zyz(b)).view(b.shape[0],b.shape[1],b.shape[2],b.shape[3]*2) # CUnitary cb_qubits = self.cb_c_zyz(cb_qubits,controlled=True) # read b b_cb = (cb_qubits[:,:,:,0:2].conj()*cb_qubits[:,:,:,0:2] + cb_...
Python
1
number=int(input("Enter numer ")) fact=1 for i in range(1,number+1): fact*=i print(fact)
Python
1
astructure for counting occurrences of elements. //! //! Most of this is copied from <https://github.com/BurntSushi/rust-stats> //! I wanted to be able to initialise the hashmap with different capacities, //! and to add some more documentation etc. use std::collections::hash_map::{HashMap, Entry}; use std::fmt; use s...
Rust
0
stacks: Vec<DsnPadstack>, } // <layer_type> = [signal | power | mixed | jumper] #[derive(Debug, Clone, PartialEq, EnumString, EnumDisplay)] #[strum(serialize_all = "snake_case")] pub enum DsnLayerType { Signal, Power, Mixed, Jumper, } impl Default for DsnLayerType { fn default() -> Self { ...
Rust
0
ts/files/b973c.sdf") out = calc_spe(path, "ANI2xt") spe = {"817-2-473": -386.111, "510-2-443":-1253.812} mols = Chem.SDMolSupplier(out, removeHs=False) for mol in mols: spe_out = float(mol.GetProp("E_hartree")) idx = mol.GetProp("ID").strip() spe_ref = spe[idx] diff = ab...
Python
1
assert_eq!(has_manifest, None); } #[cfg(feature = "test-net-private")] #[test] fn test_quayio_auth_manifestref_missing() { let image = "steveej/cincinnati-test"; let tag = "no-such-tag"; let login_scope = format!("repository:{}:pull", image); let (mut runtime, dclient) = common_init(Some(&login_s...
Rust
0
"""Base Model for Semantic Segmentation""" import torch.nn as nn from .base_model import mobilenet_v3_large_1_0, mobilenet_v3_small_1_0 __all__ = ['SegBaseModel'] class SegBaseModel(nn.Module): def __init__(self, nclass, aux=False, backbone='mobilenetv3_small', pretrained_base=True, **kwargs): super(Seg...
Python
1
)], ); match query { Ok(rows) => Ok(rows .iter() .map(|r| Stage { id: r.get(0), code: r.get(1), name: r.get(2), attribute_type: r.get(3), attribute_value: r.get(4), is_default: r.get(5...
Rust
0
ail: tail_idx_reg = len(equal_list_reg)%self.distributed_world_size print("dropping_tail",tail_idx_reg) if tail_idx_reg!=0: final_list_reg = equal_list_reg[:-tail_idx_reg] else: final_list_reg = equal_list_reg tail_idx_cls = len...
Python
1
), np.max(n)) # add meta-data for picking if len(self.groups) > 1: for g, group in enumerate(self.groups.keys()): for i in range(len(artists[g])): artists[g][i]._mt_plot_type = self artists[g][i]._mt_group = group a...
Python
1
ent * ball_object.position; } // Submit the position update to the world. world.deferred_set_position(8, ball_pos); // i += 1; // if i == 480 { // testbed.stop_recording() // } } } <reponame>amethyst/naia<filename>shared/src/property_mutate.rs<gh_stars>1...
Rust
0
def is_palindrome_iterative(word): """Faça o código aqui.""" raise NotImplementedError
Python
1
(10))); b.iter(|| object.into_iter().collect::<Vec<Pixel<Gray8>>>()) }); } criterion_group!(fonts, font_6x8, font_12x16); criterion_main!(fonts); <filename>dep/libflo_action/src/event/construct.rs use { ActionMapper, string }; use error::*; use libflo_std::{ Input, Libflo }; use std::sync::Arc; pub unsaf...
Rust
0
pclk2: u32 = min(108_000_000, self.pclk2.unwrap_or(hclk)); // Configure PPRE1 let mut ppre1_val: u32 = (hclk as f32 / pclk1 as f32).ceil() as u32; let ppre1: u32 = match ppre1_val { 0 => unreachable!(), 1 => { ppre1_val = 1; 0b000}, 2 => { ...
Rust
0
# see https://github.com/justpy-org/justpy/issues/279 import justpy as jp import time def button_click(self, _msg): """ on button click delete the components of the button """ self.num_clicked += 1 self.message.text = f"{self.text} clicked. Number of clicks: {self.num_clicked}" self.set_class(...
Python
1
take_of_neuron_hotkey_account_by_uid(neuron_two.uid)); // Check that the stake is there. // Increase the block number by 1. run_to_block(1); // Let's call an emit. Causes the new node to mint 500000000 to the other guy. let total_emission:u64 = Subtensor::emit_for_neuron(&neuro...
Rust
0
!( Post, " SELECT * FROM posts WHERE id = $1 ", id ) .fetch_one(pool) .await?; Ok(post) } pub async fn create(post: PostRequest, pool: &DbPool, logged_user: User) -> Result<Post> { let slug = slugify(post.t...
Rust
0
import cv2 from ..helper import adjust_mask from ..tests.utils import current_dir, save_dir mask_p = current_dir / "overture-creations-5sI6fQgYIuo_mask.png" def test_adjust_mask(): mask = cv2.imread(str(mask_p), cv2.IMREAD_GRAYSCALE) res_mask = adjust_mask(mask, 0, "expand") cv2.imwrite(str(save_dir / "a...
Python
1
ng { let mut plural_of: HashMap<&str, &str> = HashMap::new(); let mut singular_of: HashMap<&str, &str> = HashMap::new(); let mut past_of: HashMap<&str, &str> = HashMap::new(); let mut present_participle_of: HashMap<&str, &str> = HashMap::new(); let mut past_participle_of: HashMap<&str, &str> = HashM...
Rust
0
:enc_setup(key, nonce); let wrong_mac = [1u8; 16]; let clear = unlock::easy(&cymac.0, [0u8; 32], nonce, wrong_mac); assert_eq!(clear.is_err(), true); assert_eq!(clear.err().unwrap(), "Message is corrupt.".to_owned()) } #[test] fn aead_lock_unlock() { let key: [u8; 32] = [1; 32]; let nonce: [u8...
Rust
0
else { let sequence_ids = Tensor::arange(sequence_length, (Kind::Int64, device)); let mut causal_mask = sequence_ids .unsqueeze(0) .unsqueeze(0) .repeat(&[batch_size, sequence_length, 1]) ...
Rust
0
<symbol>\", \"<doc>\")]`\n\ or `#[unit(<ident>, \"<symbol>\")]`."; fn get_unit_attrs( attrs: &Vec<syn::Attribute>, ) -> (Vec<syn::Attribute>, Option<syn::Attribute>) { const MORE_THAN_ONE_REFUNIT_ATTR_ERROR: &str = "There can only be one `refunit` attribute."; const NO_UNIT_ATTR_ERROR: &str =...
Rust
0
y as well. pub settings: HashMap<String, String>, /// Dependencies for the target. pub dependencies: Vec<Dependency>, } /// This will provide default build settings for a certain product type. #[derive(Copy, Clone, Debug, Eq, PartialEq, Hash, Serialize, Deserialize)] pub enum ProductType { /// Represe...
Rust
0
rocessingError> { match config.exceptions { Some(ref path) => match LocalExceptions::from_file(path) { Ok(res) => Ok(res), Err(err) => { error!("Failed to load exceptions: {}\nAborted.", err); Err(ProcessingError::Other) } } ...
Rust
0
import importlib from basicsr.utils import scandir from os import path as osp # automatically scan and import model modules for registry # scan all the files that end with '_model.py' under the model folder model_folder = osp.dirname(osp.abspath(__file__)) model_filenames = [osp.splitext(osp.basename(v))[0] for v in s...
Python
1
than maximum supported fee"; pub const FEE_AMOUNT_IS_NOT_PACKABLE: &str = "Specified fee is not packable"; pub const AMOUNT_IS_NOT_PACKABLE: &str = "Specified amount is not packable"; pub const WRONG_ACCOUNT_ID: &str = "Specified Account Id is greater than maximum supported"; pub const WRONG_TIME_RANGE: &str = "Specifi...
Rust
0
dX = scaler.transform(X_train) k_values = np.array([.1,.11,.12,.13,.14,.15,.16,.09,.08,.07,.06,.05,.04]) param_grid = dict(alpha=k_values) model = Lasso() kfold = KFold(n_splits=10, random_state=7) grid = GridSearchCV(estimator=model, param_grid=param_grid, scoring='neg_mean_squared_error', cv=kfold) grid_result = grid...
Python
1
-> Self { HitList { objects: Vec::new(), } } pub fn add(&mut self, obj: impl Hittable + 'static) { self.objects.push(Box::new(obj)); } } impl Hittable for HitList { fn intersect(&self, ray: &Ray, min: f64) -> Option<HitResult> { self.objects .ite...
Rust
0
with gr.Tabs(): with gr.TabItem("👁️ Mắt Thần (Visual Scout)"): gr.Markdown("### 1. Tìm kiếm bằng Hình ảnh & Ngữ nghĩa") query_input = gr.Textbox(label="🔍 Nhập mô tả cảnh bạn muốn tìm...", placeholder="Ví dụ: một người phụ nữ mặc váy đỏ...", l...
Python
1
, body: T) -> Self { let req: Request = Request::default(); Request { url, body, method: Method::Post, headers: req.headers, deadline: req.deadline, } } } impl<'a, T: Default> Request<'a, T> { /// Create a new Request builder with the given URL. pub fn new(url: &'a str) -> Self { Request::de...
Rust
0
:core::cmp::min(inbuf.data_size(), buf.len()); if 0 == nbytes { return None } inbuf.read(&mut buf[0..nbytes]); if 0x1B == buf[0] { if let Some((mod_, key, n)) = parse_escape_seq(&buf, keys) { inbuf.skip(n.get()); return Some((mod_, key)) } // it's not escape...
Rust
0
<arg name="bar" type="(iiu)" direction="in"/> <arg name="bar" type="v" direction="out"/> </method> <method name="Frobate"> <arg name="foo" type="i" direction="in"/> <arg name="bar" type="s" direction="out"/> <arg name="baz" type="a{us}" direction="out"/> <annotation name="org....
Rust
0
data_loader=adapt_dataloader_test, nb_envs=1, traj=0, dims=(0,1), ## The Data is 1-dimensional share_axes=False, key=test_key) #%% perp = ode_count ...
Python
1
[tokio::main] async fn main() { env_logger::init(); let port = env::args() .nth(1) .map(|port| port.parse::<u16>().expect("port")) .unwrap_or(80); let thread = new_vm(); if let Err(err) = start(&thread, port).await { panic!("{}", err) } } async fn start(thread: &Th...
Rust
0
::<CanvasRenderingContext2d>() .expect("Should cast render context to CanvasRenderingContext2d") } /// Get document from window pub fn get_document(window: web_sys::Window) -> Document { window.document().expect("Should locate document") } /// Grab the window pub fn get_window() -> web_sys::Window { we...
Rust
0
ummy_table_python_collector_collect_tables_warns_failure_due_to_parse_error(caplog) -> None: linter = DummyTablePyCollector() with caplog.at_level(logging.WARNING, logger="databricks.labs.ucx.source_code.python.python_ast"): used_tables = list(linter.collect_tables("print(1")) # Closing parenthesis is ...
Python
1
rVec::new(); let mut symbols = StrVec::new(); let mut numbers = StrVec::new(); let mut charset = CharVec::new(); let _ = (33..127) .into_iter() .map(|x| { let ch = x as u8 as char; if ch.is_ascii_alphabetic() { letters.push(ch.to_string()).unwra...
Rust
0
return self.create_error_response("Client disconnected") final_res = res assert final_res is not None choices: List[ChatCompletionResponseChoice] = [] role = self.get_chat_request_role(request) if ( request.tool_choice and type(request.tool_choice)...
Python
1
import numpy as np from pyqpanda import * from dotenv import load_dotenv def main(): # 加载.env文件 load_dotenv() # 从环境变量中读取API密钥 online_api_key = os.getenv("API_KEY") # 初始化在线量子虚拟机 machine = QCloud() machine.set_configure(72,72) machine.init_qvm(online_api_key, True) # 初始化量子比特和经典寄存...
Python
1
newton` How much the digital value from the sensor increses per 1 Newton. /// 1. `digital_per_newtonmeter` How much the digital value from the sensor increses per 1 NewtonMeter. pub fn new( digital_per_newton: Triplet<f64>, digital_per_newtonmeter: Triplet<f64>, ) -> Sensitivity { Se...
Rust
0
le {}", OUTPUT); println!("{}", e); } parse_swagger(&params)?; Ok(()) } #[cfg(test)] mod tests { use super::*; #[test] fn run_result() { assert_eq!(2, 2); } }<reponame>oliverdding/codewars-rs<filename>src/kyu_6/mod.rs pub mod id_554ca54ffa7d91b236000023; pub m...
Rust
0
" => "Singing: techniques", "AVX" => "Music recording & reproduction", "C" => "Language & Linguistics", "CB" => "Language: reference & general", "CBD" => "Dictionaries", "CBDX" => "Bilingual & multilingual dictionaries", "CBF" => "Thesauri", "CBG" => "Usage & grammar guides", "CBP" => "S...
Rust
0
import math import numpy as np class StuckChecker: def __init__(self, offset, robot): self.offset = offset self.last_iter = 0 position, rotation = robot.get_world_pose() self.agent_last_position = position self.agent_last_rotation = rotation def check_robot_stuck( ...
Python
1
the locations that are lower than any of its //! adjacent locations. Most locations have four adjacent locations (up, down, left, and right); //! locations on the edge or corner of the map have three or two adjacent locations, respectively. //! (Diagonal locations do not count as adjacent.) //! //! In the above exampl...
Rust
0
_option=measure_option, callbacks=[autotvm.callback.log_to_file(log_name)], ) dispatch_context = autotvm.apply_history_best(log_name) best_config = dispatch_context.query(task.target, task.workload) print("\nBest config:") print(best_config) else: config ...
Python
1
`]. pub const XCB_SHM_BAD_SEG: u8 = 0i32 as u8; /// The `Shm::BadSeg` error. pub type xcb_shm_bad_seg_error_t = xcb_value_error_t; /// The cookie for the reply to a `Shm::QueryVersion` request. /// /// Pass this cookie to [`xcb_shm_query_version_reply`] to retrieve the reply. /// /// [`xcb_shm_query_version_reply`]: ...
Rust
0
let discriminant_enum = quote! { #[derive(Debug, Copy, Clone, Eq, Hash, Ord, PartialEq, PartialOrd)] #visibility enum #discriminant_ident { #variants } impl ::std::fmt::Display for #discriminant_ident { fn fmt(&self, f: &mut ::std::fmt::Formatter<'_>) -> ::std::fmt::Result { #discriminant_display_...
Rust
0
use futures::future::{done, err, ok}; /// Katalyst result type pub type Result<T> = std::result::Result<T, GatewayError>; /// Katalyst async result type pub type AsyncResult<T> = Box<Future<Item = T, Error = GatewayError> + Send>; pub(crate) trait ResultExt<T> { fn fut(self) -> AsyncResult<T>; } impl<T: 'static...
Rust
0
cher<M>, input: &Input<M>) where M: Measurement, { bench_select_count_1_where_fn_impl(0.5, b, input); } /// SELECT COUNT(1) FROM Table WHERE column > X (selectivity = 95%) fn bench_select_count_1_where_fn_sel_h<M>(b: &mut criterion::Bencher<M>, input: &Input<M>) where M: Measurement, { bench_select_cou...
Rust
0
import cleaninput from text_grid import findLocationsOfLetters listOfText_Puzzle = cleaninput.getfileInputLinesAsList('input10.txt') listOfText_Sample1='''..... .S-7. .|.|. .L-J. .....'''.split('\n') listOfText_Sample2='''........... .S--------7. .|.F-----7|. .|.|.....||. .|.|.....||. .|.L-7.F-J|. .|...|.|..|. .L--...
Python
1
if id(v) == obj_id: ref[i] = rewrite_func exec(f'{origin_func_path} = rewrite_func') return origin_func @contextmanager def rewrite_ctx(origin_func_path: List[str], rewrite_func: List[Callable]): """rewrite context.""" assert len(origin_func_path) == len(rewrite_func) orig...
Python
1
import sys import numpy as np def main(): argcnt = len(sys.argv) print("Number of arguments:", argcnt) for i in range(argcnt): print(i, ".", sys.argv[i]) for a in sys.argv: print("-", a) all_frames = [] for i in range(5): image = np.zeros((480...
Python
1
flags: &Flags, ) -> Vec<WeightedPrefix<T>> { let mut c = 0; let mut cum_weight = Vec::with_capacity(wprefixes.len() + 1); cum_weight.push(0); for wp in &wprefixes { c += wp.weight; cum_weight.push(c); } let total_weight = cum_weight[cum_weight.len() - 1]; let lower_unsigneds = wprefixes.iter() ...
Rust
0
from http import HTTPStatus from pathlib import Path import requests def _get_dockerhub_username( deploy_file_info: tuple[Path, str], deploy_info_file_content: dict[str, str], dockerhub_username_key) -> str: _, relative_path = deploy_file_info assert dockerhub_username_key in deploy_i...
Python
1
# 04 - Cadenas de caracteres # Cadenas de caracteres y operaciones cadena = "Hola Mundo" print("Mi cadena: " + cadena) print("Primer caracter: " + cadena[0] + " - Ultimo caracter: " + cadena[-1]) print("Subcadena: " + cadena[0:4]) print("Longitud de la cadena: " + str(len(cadena))) print("Concatenación: " + cadena +...
Python
1
= crate::R<bool, bool>; #[doc = "Reader of field `DMACH28`"] pub type DMACH28_R = crate::R<bool, bool>; #[doc = "Reader of field `DMACH29`"] pub type DMACH29_R = crate::R<bool, bool>; #[doc = "Reader of field `DMACH30`"] pub type DMACH30_R = crate::R<bool, bool>; impl R { #[doc = "Bit 0 - DMA Channel 0"] #[inl...
Rust
0
seResume = 0x0016, ClearMore = 0x0018, } #[link(name = "flash")] extern "C" { #[link_name = "Fapi_enableMainBankSectors"] pub fn enableMainBankSectors(SectorsEnables: u16) -> Status; #[link_name = "Fapi_enableEepromBankSectors"] pub fn enableEepromBankSectors(SectorsEnables_31_0: u32, SectorsEnabl...
Rust
0
import numpy as np import random # Пример данных задачи num_cities = 10 distance_matrix = np.random.randint(10, 100, size=(num_cities, num_cities)) np.fill_diagonal(distance_matrix, 0) # Запрет маршрутов до самого себя # Параметры алгоритма population_size = 100 num_generations = 100 mutation_rate = 0.2 stagnation_l...
Python
1
CloudOpenSearch", "AlibabaCloudOpenSearchSettings", "AnalyticDB", "Annoy", "AtlasDB", "AwaDB", "AzureSearch", "Bagel", "Cassandra", "AstraDB", "Chroma", "Clarifai", "Clickhouse", "ClickhouseSettings", "DashVector", "DatabricksVectorSearch", "DeepLake", ...
Python
1
ferent type or is incomplete. Args: arg: Entity or Key Returns: Key """ # type check if isinstance(arg, Key): key = arg elif isinstance(arg, basestring): # Also accept the string representation of a key. key = Key(arg) elif isinstance(arg, Entity): key = arg.key() elif not isin...
Python
1
"""分散式計算模組測試 測試分散式計算接口的功能,包括 Dask、Ray 和本地計算引擎。 """ import os import sys import unittest import pandas as pd from unittest.mock import patch, MagicMock # 添加專案根目錄到 Python 路徑 sys.path.append(os.path.abspath(os.path.join(os.path.dirname(__file__), ".."))) from src.core.distributed_computing import ( DistributedComp...
Python
1
i], os.path.join(args.output_dir,"AngleZoneMaskList_R"+str(i+1)+".tif")) if l1_reader.has_value("L1TOAImageList") and l1_reader.get_value("L1TOAImageList"): for i in range(0, len(l1_reader.get_value("L1TOAImageList"))): LOGGER.debug("toa image list test: " + str(l1_reader.get...
Python
1
ence: Option<GlobalLineageReference>) -> Self { match optional_coalescence { None => Self::None, Some(coalescence) => Self::Coalescence(coalescence), } } } // Note: manually implementing PartialEq and Eq disables pattern matching impl PartialEq for LineageInteraction { f...
Rust
0
imes the number of GT steps") print(f"Whether steps in gt*2+1 are successful:{done}") print(f" setps: {steps}") print("---------------------------") self.write_log_to_file(f'''--------------------------- The task fail...
Python
1
W6GVsjnZBa1ecGdCssn7KhWYJZGTXgL7Es", "value": "5Z7ktpfVQAhj2gMFR8L6JnG7fQQJzqWwqrDgXQP1CYf2vrjKPe2a27borFVuAcQh2AttoejgAoTzJ36wfyKxu5ox" } ] }, "txnMetadata": { ...
Rust
0
weights - new_weights).abs(); let rel_diff = abs_diff / old_weights; if abs_diff > max_abs_diff { max_abs_diff = abs_diff; } if rel_thresh.map_or(true, |thresh| new_weights > thresh) && rel_diff > max_rel_diff { max_rel_diff = rel_diff } } (max_...
Rust
0
= r'<div[^>]*class="wx_follow_nickname"[^>]*>\s*([^<]+)\s*</div>' match = re.search(nickname_pattern, html_content) if match: account_name = match.group(1).strip() print(f"✅ 通过wx_follow_nickname找到公众号名称: {account_name}") return account_name ...
Python
1
shared::{Day, PartSolution}, }; #[test] fn outcome() { assert_eq!(PartSolution::U32(6521), (Solution {}).part_1()); } #[test] fn answer_set_1() { let answer_set = ["abc".to_string()]; assert_eq!(parse_group_of_answers(&answ...
Rust
0
start: usize, token: Token<&'input str>) -> Spanned<'input, usize> { let end = self.next_index(); self.token2(start, end, token) } fn token2( &mut self, start: usize, end: usize, token: Token<&'input str>, ) -> Spanned<'input, usize> { (start, token,...
Rust
0
import tkinter from tkinter.messagebox import showinfo as alert from tkinter.messagebox import askyesno as question from tkinter.simpledialog import askstring as prompt import customtkinter ''' nombre: Nelly apellido: Burgos --- TP: IF_Iluminacion --- Enunciado: Todas las lámparas están al mismo precio de $800 pesos ...
Python
1
ccess", "message": "Item deleted successfully."} except HttpError as e: try: error_content = ( e.error_details[0].get("message") if e.error_details else str(e) ) except Exception: error_content = str(e) logger.error( f"Google Dr...
Python
1
fn fspan(&self) -> Option<&FileSpan> { match self { ProcPos::Named(fsp, _, _) | ProcPos::Unnamed(fsp) => Some(fsp), ProcPos::Builtin(_) => None, } } } /// A callable procedure. There are several sources of procedures, /// all of which are interactable only via function calls `(f)` and /// print...
Rust
0
from unittest.mock import MagicMock import pytest from slp_base import DiagramType from slp_visio import VisioProcessor from slp_visio.slp_visio.parse.lucid_parser import LucidParser from slp_visio.slp_visio.parse.visio_parser import VisioParser class TestVisioProcessor: @pytest.mark.parametrize('diag_type, ex...
Python
1
nv_var_from_key(key: &str) -> String { format!("{}{}", ENV_VAR_PREFIX, key.to_ascii_uppercase()) } fn file_is_readable(path: &str) -> bool { std::fs::File::open(path).is_ok() } fn get_config_path_candidates(clap_matches: &ArgMatches<'static>) -> Vec<String> { let mut candidates = vec![]; // First che...
Rust
0
def train_microgrid(env, agent, n_episodes, max_steps): episode_rewards = [] episode_costs = [] # Added to track costs env.battery_data = [] for episode in range(n_episodes): logger.info(f"Starting episode {episode}") env.current_episode = episode env.current_step = 0 ...
Python
1
) -> Result<Self, Self::Err> { match s { "asis" | "bytes" | "string" => Ok(Conversion::Bytes), "integer" | "int" => Ok(Conversion::Integer), "float" => Ok(Conversion::Float), "bool" | "boolean" => Ok(Conversion::Boolean), "timestamp" => Ok(Conversion::...
Rust
0
"""多通道通知服務 - 主要入口模組 此模組提供多通道通知服務的統一入口,包括: - 統一通知介面 - 多通道管理 - 失敗重試機制 遵循 Google Style Docstring 標準和 Phase 5.3 開發規範。 """ # 導入所有通知服務 from .notification_manager import NotificationServices from .notification_base import NotificationChannel from .email_service import EmailChannel from .webhook_service import WebhookChanne...
Python
1
# -*- coding: utf-8 -*- #Author: guomaoqiu #Date: 2020-2-28 #Desc: 钉钉通知 import os import sys import json import datetime import requests,time # 依赖包: pip install flask gitpython from flask import Flask, request, jsonify,abort def dingding(dingding_send_info): # dingding_send_info = { # "address": requ...
Python
1
# Copyright (c) OpenMMLab. All rights reserved. import torch from mmdet3d.models.builder import build_voxel_encoder def test_pillar_feature_net(): pillar_feature_net_cfg = dict( type='PillarFeatureNet', in_channels=5, feat_channels=[64], with_distance=False, voxel_size=(0....
Python
1
, i32> = HashMap::new(); recurse_distance_equation(&mut chunk, [0,0,0], size, &mut implicit, 1.0 / (size as f32), &mut dedup); chunk.voxels.reverse(); //fixup the subvoxel pointers (we reversed the order) let n = chunk.voxels.len() as i32; for i in 0..(chunk.voxels.len()) { ...
Rust
0
eaderMap) -> Result<uuid::Uuid, CosmosError> { let s = headers .get(HEADER_ACTIVITY_ID) .ok_or_else(|| CosmosError::HeaderNotFound(HEADER_ACTIVITY_ID.to_owned()))? .to_str()?; Ok(uuid::Uuid::parse_str(s)?) } pub(crate) fn content_path_from_headers(headers: &HeaderMap) -> Result<&str, Co...
Rust
0
from google import genai from google.genai import types from PIL import Image from io import BytesIO import PIL.Image image = PIL.Image.open('./gemini_images/img.jpg') client = genai.Client("api_key") text_input = ('Create an image similar to this, please note-change the wall colour to dark green and the rug should...
Python
1
LEN: usize = 34592; const TABLE_LEN: usize = 893901; const NAMES_LEN: usize = 928493; pub type Characters = &'static [Character; CHARS_LEN]; #[allow(clippy::unusual_byte_groupings)] pub const CHARACTERS: Characters = include!("./characters.rs"); pub const NAMES: &str = include_str!("./names.txt"); include_slice!(u32...
Rust
0
print(f"Error while downloading rb-scrobbler: {e}") return else: print("rb-scrobbler is required to proceed. Exiting.") return # Verify that rb-scrobbler exists and is executable if not (scrobbler_path.exists() and os.access(scrobbler_path, os.X_OK)): ...
Python
1
hijklm | |osa1: | |< #chan |"; expect_screen(screen, &tui, 21, 4, Location::caller()); } #[test] fn test_resize() { let mut tui = TUI::new_test(80, 50); let server = "<server>"; tui.new_server_tab(server, None); let ts = time::empty_tm()...
Rust
0
() -> Optional[Span]: import langchain_core run_id: Optional[UUID] = None config = langchain_core.runnables.config.var_child_runnable_config.get() if not isinstance(config, dict): return None for v in config.values(): if not isinstance(v, langchain_core.callbacks.BaseCallbackManager...
Python
1
.render() .expect("Should render markup") ) .await } "/deciduously-com" => { html_str_handler( &Blog18Template::default() .render() .expect("Should render markup") ...
Rust
0
perator @ {:?}: sending odd number {} on right stream", ctx.timestamp(), data, ); ctx.right_write_stream() .send(Message::new_message(time, *data)) .unwrap(); } } fn on_watermark(&mut self, _ctx: &mut OneInTwoOutCon...
Rust
0
from dashscope.audio.tts_v2 import VoiceEnrollmentService, SpeechSynthesizer import dashscope from config import get_user_data_dir from core.clipgenerate.tongyi_get_online_url import get_online_url, get_online_url_self from core.clipgenerate.tongyi_get_voice_copy import get_voice_copy_disposable from core.clipgenerate....
Python
1
from .ani1 import ANI1 from .custom import Custom from .hdf import HDF5 from .md17 import MD17, MD17A from .pcqm4mv2 import PCQM4MV2_Dihedral, PCQM4MV2_Dihedral2, PCQM4MV2_DihedralF, PCQM4MV2_Force from .pcqm4mv2 import PCQM4MV2_XYZ as PCQM4MV2 from .pcqm4mv2 import PCQM4MV2_XYZ_BIAS as PCQM4MV2_BIAS from .qm9 import Q...
Python
1
import os import json import torch from PIL import Image class ImageList(torch.utils.data.Dataset): def __init__(self, samples, transform=None): self.samples = samples self.transform = transform def __getitem__(self, idx): path, label = self.samples[idx] with open(path, 'rb') ...
Python
1
>::Out, Mode::Err>)>>), /// "this form has the same type/value as one of its subforms". /// (useful for forms that only exist as wrapper s around other AST nodes) Body(Name), /// "traverse the subterms, and rebuild this syntax around them". /// Only valid in modes where `Ast`s can be converted to `:...
Rust
0
le-ratio", type=float, help="Max. scale ratio", ) group.add_argument( "--anchor-generator.ssd.no-clipping", action="store_true", help="Don't clip the anchors", ) group.add_argument( "--anchor-generator.ssd.step", ...
Python
1
import sublime_plugin import re from sublime import Region re_quotes = re.compile("^(['\"`])(.*)\\1$") quoteList = ['\'', '"', '`'] class ToggleQuotesCommand(sublime_plugin.TextCommand): def run(self, edit, **kwargs): v = self.view if v.sel()[0].size() == 0: v.run_command('expand_sele...
Python
1
osition. pos: Rect, /// The stage of growth the crop is in, from /// 0 to 3. stage: u8, /// Rectangle to crop the sprite sheet to the /// appropriate tile. src: Rect, /// Texture of sprite sheet. texture: &'a Texture<'a>, /// Texture of rotten crop sprite sheet rotten_texture...
Rust
0
from lib.devices.VSYS_voltage import VSYS_voltage from machine import Pin, I2C, ADC import lib.devices.bme280_float as bme280 from lib.ble.mble import * import time import bluetooth import struct i2c = I2C(1, sda=Pin(14), scl=Pin(15)) led = Pin(16, Pin.OUT) led.off() devices = i2c.scan() if not devices: print(...
Python
1
ks: Vec<bls::VerKey> = ver_keys.iter().map(|x| convert_from_js(x).unwrap()).collect(); Ok(maperr!(bls::Bls::verify_multi_sig(&multi_sig.0, message, vks.iter().collect::<Vec<_>>().as_slice(), &gen.0))) } } <filename>src/error.rs use pyo3::exceptions::{PyIOError, PyRuntimeError, PyValueError}; use pyo3::PyRes...
Rust
0
path: String::from("Hello World"), cmd: Command::new("").spawn().unwrap(), sender: sender, receiver: receiver } } } impl fmt::Debug for Kind { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { write!(f, ...
Rust
0
x_d = x[:, 3:, :, :] else: x_d_sparse = x[:, 3:4, :, :] x_d_dense = x[:, 4:5, :, :] x_d = torch.cat((x_d_sparse, x_d_dense), dim=1) # ipdb.set_trace() # RGB x_img = self.conv1(x_img) x_img = self.bn1(x_img) x_img = self.re...
Python
1
: voxels, num_points, coors = self.voxelize(points) voxel_features = self.voxel_encoder(voxels, num_points, coors) batch_size = coors[-1, 0].item() + 1 x = self.middle_encoder(voxel_features, coors, batch_size) x = self.backbone(x) if self.with_neck: ...
Python
1