text
string
label_name
string
labels
int64
Fqk::zero(); // MillerLoop(Accum_AB) let mut acc_ab = E::Fqk::zero(); // Y^-Accum_Y let mut y = E::Fqk::zero(); POOL.install(|| { let accum_y = &accum_y; let rand_z_repr = &rand_z_repr; rayon::scope(|s| { // - Thread 1: Calculate MillerLoop(\sum Accum_Gamma) ...
Rust
0
ctory { fn factory(&self, r: Box<io::BufRead>, s: CodecSettings) -> Result<Box<io::BufRead>, Error> { match s.dir { Direction::Forward => Ok(Encoder::new().into_bufread(r, s.bufsize)), Direction::Reverse => Ok(Decoder::new(s.strict).into_bufread(r, s.bufsize)), } } f...
Rust
0
d.FrontEnd.__init__ = new_fe_init def _get_factory_callable() -> Callable[[], NodeFactory]: factory = {} def inner(opset_version: Optional[str] = None) -> NodeFactory: nonlocal factory if opset_version not in factory: if is_openvino_tokenizers_compatible: openvino....
Python
1
e fn initializer(&self) -> Initializer { Initializer::nop() } } impl Write for CharacterDeviceFileDescriptor { /// This particular implementation can only return an `io::ErrorKind` of:- /// /// * `WriteZero` (implying end-of-file). /// * `WouldBlock` /// * `Interrupted` /// * `BrokenPipe` #[inline(always)] ...
Rust
0
pd.Series() ESR = 30 NBR = 10000 VBE = 50 for train_part_index, eval_index in kf.split(train, train_y): # 模型训练 train_part = xgb.DMatrix(train.tocsr()[train_part_index, :], train_y.loc[train_part_index]) eval = xgb.DMatrix(train.tocsr()[eval_index...
Python
1
/// This is most often equal to `Exposure.total` but not always. Needed for [`equalize`] backing_stake: ExtendedBalance } /// Wrapper around the nomination info of a single nominator for a group of validators. #[derive(Clone, Encode, Decode, Default)] #[cfg_attr(feature = "std", derive(Debug))] pub struct Nominator<A...
Rust
0
oto().op[0].type = "Int8Quantize" ref_net.Proto().op[1].type = "Int8FC" ref_net.Proto().op[2].type = "Int8Dequantize" net_onnxified = onnxifi_caffe2_net( ref_net.Proto(), {}, debug=True, adjust_batch=False, use_onnx=False, w...
Python
1
ob green component color to shader. :param node_tree: node tree of current shader :type node_tree: bpy.types.NodeTree :param color: paintjob green component color represented with property group :type color: bpy.types.IDPropertyGroup """ # as this functions should be ca...
Python
1
from torch import nn from torchvision import models, transforms from torchvision.models import ResNet18_Weights from torch.nn.functional import cosine_similarity class SiameseNetwork(nn.Module): def __init__(self, backbone='resnet18'): super(SiameseNetwork, self).__init__() if backbone not in model...
Python
1
import tensorflow as tf EMBEDDING_SIZE = 40 N_FILTERS = 10 WINDOW_SIZE = 20 FILTER_SHAPE1 = [WINDOW_SIZE, EMBEDDING_SIZE] FILTER_SHAPE2 = [WINDOW_SIZE, N_FILTERS] POOLING_WINDOW = 4 POOLING_STRIDE = 2 LEARNING_RATE = 0.05 def generate_cnn_model(n_classes, n_words): """2 layer ConvNet to predict from sequence of ...
Python
1
""" 情感分析模块 """
Python
1
) << 1), (((3 << 3) + 1) << 2) - 1, (((7 << 2) - 1) << 2), ((((3 << 2) + 1)) << 3) + 1, (7 << 4), (3 << 5) + (1 << 1), (7 << 4) - 1, (3 << 5) + 1, (7 << 4) + (1 << 1), (((3 << 3) + 1) << 2), (5 << 4) + (1 << 1), (((3 << 3) + 1) << 2) + 1, (3 << 5) + 1, (((3 << 3) + 1) << 2), (((1 << 4) + 1) << 1), (((3 << 3) - 1) << 2)...
Python
1
ments=assignments) # Calculate marginal for first component by hand k_N = k_0 + N_1 v_N = v_0 + N_1 m_N = (k_0*m_0 + N_1*X_1.mean(axis=0))/k_N S_N = S_0 + np.square(X_1).sum(axis=0) + k_0*np.square(m_0) - k_N*np.square(m_N) var = S_N*(k_N + 1)/(k_N*v_N) expected_log_marg_1 = ( - N_1...
Python
1
_float min_int) || xf < Int64.(to_float min_int) then // raise Numeric_error.IntegerOverflow // else // Int64.of_float xf } Instruction::I64TruncUF64 => { op1_trap::<f64, i64, _>(rt, |f| { if f.is_nan() { ...
Rust
0
#!/usr/bin/env python """ Copyright (c) 2006-2024 sqlmap developers (https://sqlmap.org/) See the file 'LICENSE' for copying permission """ import re from lib.core.common import isDBMSVersionAtLeast from lib.core.common import randomStr from lib.core.convert import getOrds from plugins.generic.syntax import Syntax a...
Python
1
# diagonal_trace.py import numpy as np # Creating a square matrix matrix = np.array([[1, 2, 3], [4, 5, 6], [7, 8, 9]]) # Extracting diagonal diagonal = np.diag(matrix) print(f"Diagonal of the matrix: {diagonal}") # Computing trace (sum of diagonal elements) trace = np.trace(matrix) print(f"Trace of the matrix: {trac...
Python
1
TA_KEY = Button(area={'cn': (688, 316, 781, 338), 'en': (759, 323, 889, 342), 'jp': (627, 300, 743, 321), 'tw': (688, 316, 782, 338)}, color={'cn': (165, 154, 99), 'en': (170, 160, 94), 'jp': (127, 128, 116), 'tw': (159, 150, 97)}, button={'cn': (688, 316, 781, 338), 'en': (759, 323, 889, 342), 'jp': (627, 300, 743, 32...
Python
1
rent_time_tz = current_time.astimezone(timezone) current_hour = current_time_tz.hour current_minute = current_time_tz.minute run_hour = run_time.hour run_minute = run_time.minute if current_time_tz.weekday() in weekdays: return (current_hour == run_hour) and (current_minute == run_minute)...
Python
1
Command)); }<reponame>vedranvinko/xkcd<filename>src/main.rs #[macro_use] extern crate clap; use clap::App; extern crate image; use serde::{Deserialize, Serialize}; use std::fs::File; use std::path::Path; #[derive(Debug, Deserialize, Serialize)] struct Response { month: String, num: i32, link: String, ...
Rust
0
chunk names for a dataset with the given chunk coords shape. For example: _get_chunk_names_for_dataset([1, 2, 3]) returns ['0.0.0', '0.0.1', '0.0.2', '0.1.0', '0.1.1', '0.1.2'] """ ndim = len(chunk_coords_shape) if ndim == 0: return ["0"] elif ndim == 1: return [str(i) for i in...
Python
1
_is:0 %}Length is 0{% else %}Length not 0{% endif %}', {}, 'Length not 0'), 'length_is08': (r'{% if "X"|length_is:1 %}Length is 1{% else %}Length not 1{% endif %}', {}, 'Length is 1'), # Invalid uses that should fail silently. 'length_is09': ('{{ var|length_is:"fish" }}', {'var': 'django'}, ''),...
Python
1
from clip import CLIP from encoder import VAE_Encoder from decoder import VAE_Decoder from diffusion import Diffusion import model_converter def preload_models_from_standard_weights(ckpt_path, device): state_dict = model_converter.load_from_standard_weights(ckpt_path, device) encoder = VAE_Encoder().to(devic...
Python
1
.1; let best_score = guess_tuple.0; println!("{}", str::from_utf8(&best_word).unwrap()); Ok(()) }<reponame>capyloon/api-daemon // This file is part of ICU4X. For terms of use, please see the file // called LICENSE at the top level of the ICU4X source tree // (online at: https://github.com/unicode-org/icu4...
Rust
0
# Copyright (c) Streamlit Inc. (2018-2022) Snowflake Inc. (2022-2024) # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by...
Python
1
vResult.f[0] = V.vector4_f32[1]; vResult.f[1] = V.vector4_f32[1]; vResult.f[2] = V.vector4_f32[1]; vResult.f[3] = V.vector4_f32[1]; return vResult.v; } #[cfg(_XM_ARM_NEON_INTRINSICS_)] { unimplemented!() } #[cfg(_XM_SSE_INTRINSICS_)] unsafe { ...
Rust
0
from __future__ import annotations from typing import TYPE_CHECKING from typing import Callable from typing import Sequence if TYPE_CHECKING: from typing_extensions import Self from narwhals._dask.expr import DaskExpr class DaskExprNameNamespace: def __init__(self: Self, expr: DaskExpr) -> None: ...
Python
1
import sys import requests import base64 import re import json import subprocess def main(): if len(sys.argv) < 2: print(f"Usage: {sys.argv[0]} <base-url>") sys.exit(1) base_url = sys.argv[1] vulnerable_url = f"{base_url}/api/index.php/authorize" try: response = requests.get(...
Python
1
cale"] = torch.tensor(1) return new_sd def save_stable_diffusion_checkpoint(v2, output_file, text_encoder, unet, ckpt_path, epochs, steps, save_dtype=None, vae=None): if ckpt_path is not None: # epoch/stepを参照する。またVAEがメモリ上にないときなど、もう一度VAEを含めて読み込む checkpoint, state_dict = load_checkpoint_with_te...
Python
1
p_module=self.toplevel, vc_file=self.verilator_file, verilator_options=verilator_options, make_options=make_options, ) ) def build_main(self): logger.info("Building simulation model") if "mode" not in self.tool_...
Python
1
L_A::PULL12K } #[doc = "Checks if the value of the field is `PULL24K`"] #[inline(always)] pub fn is_pull24k(&self) -> bool { *self == PAD42RSEL_A::PULL24K } } #[doc = "Write proxy for field `PAD42RSEL`"] pub struct PAD42RSEL_W<'a> { w: &'a mut W, } impl<'a> PAD42RSEL_W<'a> { #[doc = ...
Rust
0
_predecessor_should_fail_unknown_predecessor_context( ) { init_test_runtime(); // init empty context for test let (chain_id, ..) = init_test_protocol_context( "bootstrap_test_storage_02", test_data_protocol_v1::tezos_network(), ); // apply second block - level 2 let apply_block...
Rust
0
Effective Field Goal Percentage" X = merged_df[[x,y]].values kmeans = KMeans(n_clusters=3).fit(X) # 3 clusters for champ contendors, playoff contendors, rebuilding teams clusters = kmeans.labels_ print(clusters) # 0, 1, 2 for each cluster. print(merged_df['Win Percentage'].values) # print this, map to cluster valu...
Python
1
) -> c_int>, pub get_read_only: Option<unsafe extern "C" fn(*mut GeeMultiMap) -> gboolean>, pub get_read_only_view: Option<unsafe extern "C" fn(*mut GeeMultiMap) -> *mut GeeMultiMap>, } impl ::std::fmt::Debug for GeeMultiMapIface { fn fmt(&self, f: &mut ::std::fmt::Formatter) -> ::std::fmt::Result { ...
Rust
0
#!/usr/bin/python3 """Island perimeter computing module. """ def island_perimeter(grid): """Computes the perimeter of an island with no lakes. """ perimeter = 0 if type(grid) != list: return 0 n = len(grid) for i, row in enumerate(grid): m = len(row) for j, cell in enum...
Python
1
R>, rconf2: &Config, rdr2: &mut csv::Reader<R>, ) -> CliResult<(Selection, Selection)> { let headers1 = rdr1.byte_headers()?; let headers2 = rdr2.byte_headers()?; let select1 = rconf1.selection(&*headers1)?; let select2 = rconf2.selection(&*headers2)?; if sele...
Rust
0
external_update_proposal( &nns_canisters.governance, Sender::from_keypair(&TEST_NEURON_1_OWNER_KEYPAIR), NeuronId(TEST_NEURON_1_ID), NnsFunction::AssignNoid, proposal_payload.clone(), "<proposal created by test_submit_and_accept_add_node_operator_proposal>".to_string(), ...
Rust
0
from PA03 import * import csv def test(): """ This function runs a series of tests on three algorithms: O(N**2), O(NlogN), and O(N). It prompts the user to enter the input size, then generates an array and a target sum using the main function. It runs each algorithm on the generated array and target s...
Python
1
import openai import os import json import re from dotenv import load_dotenv load_dotenv() def ai(user_input): client = openai.OpenAI(api_key=os.getenv("OPENAI_API_KEY")) messages = [ {"role": "system", "content": "You are a JSON generator. Respond only with valid JSON."}, {"role": "user"...
Python
1
import openai import pandas as pd import blog_link import blog_content import os from dotenv import load_dotenv import psycopg2 import numpy as np load_dotenv() # 1.PostgreSQL 연결 user, password, host = os.getenv("DB_USER"), os.getenv("DB_PASSWORD"), os.getenv("DB_HOST") def connect_db(): connection = psycopg2.co...
Python
1
import numpy as np from rlkit.envs.mujoco.ant_multitask_base import MultitaskAntEnv from rlkit.envs import register_env @register_env('ant-dir') class AntDirEnv(MultitaskAntEnv): def __init__(self, task={}, n_tasks=2, forward_backward=False, max_episode_steps=200, randomize_tasks=True, **kwargs): self.f...
Python
1
from fastapi import FastAPI,HTTPException import uvicorn import pandas as pd # from utils.resources import resources from utils import resources from utils import index from service import lstm_service,var_service app = FastAPI() print("In module products __package__, __name__ ==", __package__, __name__) @app.post(...
Python
1
dec = lz77_decompress(&comp); //assertion raised!!!!!!! //assert!(comp.len() < data.len()); println!("{} vs {}", comp.len(), data.len()); println!("{:#?}", data); println!("{:#?}", comp); assert_eq!(data.to_vec(), dec); } <reponame>l0calh05t/raytracing-weekend-rs pub use na::Unit; pub use nalgebra as na; pub use ra...
Rust
0
E_BACKUP_BUS_PMS_MONITOR_3>; #[allow(missing_docs)] #[doc(hidden)] pub struct _SENSITIVE_BACKUP_BUS_PMS_MONITOR_3; #[doc = "`read()` method returns [sensitive_backup_bus_pms_monitor_3::R](sensitive_backup_bus_pms_monitor_3::R) reader structure"] impl crate::Readable for SENSITIVE_BACKUP_BUS_PMS_MONITOR_3 {} #[doc = "SE...
Rust
0
jul18/toppar/param19.inp"; let angle:&str = args.get("-angle").unwrap_or_else(|| panic!("Please specify backbone torsion angle file with -angle")); let param1:String = args.get("-build_missing_param1").unwrap_or(&"".to_string()).to_string(); let param2:String = args.get("-build_missing_param2").un...
Rust
0
hts.isel(time=-2) holding_time_prev = state['holding_time'] holding_time_prev = holding_time_prev.reindex_like(curr_pos, fill_value=0) reset_or_increase = xr.where(holding_time_prev >= max_period, 0, holding_time_prev + 1) holding_time = xr.where(curr_pos < 0, reset_or_increase, holding_time_prev) ...
Python
1
'ENABLE_TIMEOUT','FILE_TIMEOUT_SECONDS','ENABLE_MEMORY_MONITOR','MEMORY_LIMIT_MB','ENABLE_RESUME','RESUME_LOG_FILE', 'MAX_RETRY','RETRY_INTERVAL_SEC','WHITELIST_USERS','LOG_WHITELIST_USER_CHANGE','FORCE_BASELINE_ON_FIRST_SEEN','SHOW_DEBUG_MESSAGES', 'ENABLE_HEARTBEAT','HEART...
Python
1
PC_STATUS; #[doc = "*Required features: `\"Win32_System_Rpc\"`*"] pub fn RpcServerTestCancel(bindinghandle: *const ::core::ffi::c_void) -> RPC_STATUS; #[doc = "*Required features: `\"Win32_System_Rpc\"`*"] pub fn RpcServerUnregisterIf(ifspec: *const ::core::ffi::c_void, mgrtypeuuid: *const ::windows_sys...
Rust
0
duplicate_duration = settings .var("duplicate-duration", utils::Duration::default()) .await?; let song_switch_feedback = settings.var("song-switch-feedback", true).await?; let max_songs_per_user = settings.var("max-songs-per-user", 2).await?; let max_queue_length = settings.var("max-queue-l...
Rust
0
to the last valid index, so if span_end is below span_start, # both were above the max index: if (adapted_span_indices[:, :, 0] > adapted_span_indices[:, :, 1]).any(): raise IndexError( "Span indices were masked out entirely by sequence mask", ) # span_...
Python
1
# plt.yticks([]) fig plt.show() ##################################################################### "Inf!" fig = plt.figure(figsize=(9, 5)) for i in range(6): plt.subplot(2,3,i+1) plt.tight_layout() # x_e = test_x_e2[i+15].view(-1, X_DIM).to(device).float()/255 x_e = test_x_e1[i+1].to(device).un...
Python
1
import os import sys import redis from redisgraph import Graph sys.path.append(os.path.dirname(os.path.abspath(__file__))) sys.path.append(os.path.dirname(os.path.abspath(__file__)) + '/../') from social_queries import queries_info import social_utils from utils import execute_query, _redis redis_con = None redis_gr...
Python
1
quivos_e_dirs(caminhos_log_windows) print("Limpeza concluída.") def otimizar_roblox(): finalizar_processo("RobloxPlayerBeta.exe") try: caminho_reg = r'SYSTEM\\CurrentControlSet\\Control\\GraphicsDrivers' with reg.OpenKey(reg.HKEY_LOCAL_MACHINE, caminho_reg, 0, reg.KEY_WRITE) as key: ...
Python
1
end(&mut out_bytes).unwrap(); out_bytes } // Converts the input bytes to an output string in the format "0x01,0x02,0x03...". fn format_as_hex(data: &[u8]) -> String { let mut out = String::new(); for (i, d) in data.iter().enumerate() { out.push_str(&format!("0x{:02x}", d)); if i < data.len(...
Rust
0
# This code is supporting material for the book # Building Machine Learning Systems with Python # by Willi Richert and Luis Pedro Coelho # published by PACKT Publishing # # It is made available under the MIT License import os import sys import scipy as sp from sklearn.feature_extraction.text import CountVectorizer ...
Python
1
/** An internal working planner for generating context for a whole workspace. */ struct WorkspaceSubplanner<'planner> { metadata: &'planner Metadata, settings: &'planner RazeSettings, platform_details: &'planner PlatformDetails, crate_catalog: &'planner CrateCatalog, files: &'planner CargoWorkspaceFiles, } /...
Rust
0
Tag::CodeBlock(_) => { attrs.font_family(FontFamily::MONOSPACE); } Tag::Emphasis => { attrs.style(FontStyle::Italic); } Tag::Strong => { attrs.weight(FontWeight::BOLD); } Tag::Strikethrough => { attrs.strikethrough(true...
Rust
0
#!/usr/bin/env python3 """ 🎨 现代化音乐播放器主题系统 深色优雅主题 + 动态配色 + 视觉效果 """ from typing import Dict, Any, Optional from dataclasses import dataclass @dataclass class ColorScheme: """颜色方案数据类""" # 背景层次 bg_primary: str # 主背景 bg_secondary: str # 次级背景 bg_card: str # 卡片背景 bg_overlay: st...
Python
1
}; use cty; use cty::{c_char, c_void}; use libc; #[repr(C)] pub struct message_t { pub in_msg_t: cty::int8_t, pub token_t: cty::int64_t, pub payload: [c_char; 8] } #[no_mangle] pub struct sensor_t { _addr: SocketAddr, _msg_arr: Box<Vec<message_t>>, _next: Option<Box<sensor_t>> } impl sensor_...
Rust
0
ape: (M,) M = len(valid_indices) if M < 3: # 有效点不足3,无法计算角度,全部保持0 continue # 环状遍历 for k in range(M): i = valid_indices[k].item() # 当前点索引 i_l = valid_indices[(...
Python
1
/raw-data-JdeK1YeQ90aJ` /// /// If that doesn't suit you, you can override this behavior by specifying two /// strings in between which the hash will be inserted. For example: /// /// ```text /// "main-v1.0-min.js.map": { /// hash: "main-v1.0-min." ... ".js.map", /// } /// ``` /// /// The resulting filename would b...
Rust
0
# Copyright 2010-present MongoDB, 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 applicable law or agreed to in wri...
Python
1
bolizando el estado de la respuesta. Los posibles estados de respuesta son: - 0: Resultado exitoso. - 1: Doctor inexistente. - 2: Especialidad inexistente. - 3: Relación inexistente. """ doctor_search: schemas.UserSearch = schemas.UserSearc...
Python
1
enzimas = { 'EcoRI' : 'GAATTC', 'BamHI' : 'GGATCC', 'HindIII' : 'AAGCTT', 'PstI' : 'CTGCAG', 'XhoI' : 'CTCGAG', 'SalI' : 'GTCGAC', 'SmaI / blunt' : 'CCCGGG', 'NotI' : 'GCGGCCGC', 'NdeI' : 'CATATG', 'NcoI' : 'CCATGG', 'ApaI' : 'GGGCCC', 'KpnI' : 'GGTACC', 'SacI' : 'GA...
Python
1
overwrite=True).compute(scheduler='processes') def inplace_morph_close_chunks_zarr(zarr_path, chunk_size=512, radius=16, morph_labels=[]): compute_chunks = (chunk_size,chunk_size,chunk_size) zarr_array = zarr.open(zarr_path, mode='r+') zarr_chunk_size = zarr_array.chunks print(f"Zarr chunk size: {zarr...
Python
1
import asyncio from typing import Callable, List from outspeed.streams import AudioStream, ByteStream, Stream, TextStream, VideoStream def join(input_queues: List[Stream], func: Callable): output_queue = None if not all(isinstance(x, type(input_queues[0])) for x in input_queues): raise ValueError("Al...
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
let state = value.sival_ptr as *const TimerState; (*state).wake(); } #[cfg(not(feature = "c_wrapper"))] pub unsafe extern "C" fn timer_handler(_sig: libc::c_int, si: *mut libc::siginfo_t, _uc: *mut libc::c_void) { let state = (*si).si_value().sival_ptr as *const TimerState; ...
Rust
0
.vote_accounts()); let baseline_credits = validator_credits.remove(baseline_id).unwrap_or_else(|| { panic!( "Solana baseline validator {} not found in validator_credits", baseline_id ) }); let mut validator_leader_stats = validator_leader_stats(bank, block_ch...
Rust
0
actor = DatabaseStorageInteractor::new(storage); // If genesis is argument is present - there will be fetching contracts creation transactions to get first eth block and genesis acc address if opt.genesis { // We have to load pre-defined tokens into the database before restoring state, // since ...
Rust
0
s connection up as a LairClient let cli_hnd = crate::lair_client::async_io::new_async_io_lair_client( send, recv, server_pub_key.cloned_inner().into(), ) .await?; // verify the server and unlock the connection let ver = cli_hnd.hello(server_pu...
Rust
0
mut self, id1: Id, id2: Id) { use libsolv_sys::export::queue::e_queue_push2; unsafe {e_queue_push2(&mut self._q, id1, id2)}; } pub fn truncate(&mut self, n: c_int) { use libsolv_sys::export::queue::e_queue_truncate; unsafe {e_queue_truncate(&mut self._q, n)}; } pub fn i...
Rust
0
# Promedio """ Cree un programa que reciba tres calificaciones, promedielas y decir si el estudiante aprobó o no """ notas = [] for c in range (3): calificacion = float(input(f"Ingrese {c+1}° calificacion: ")) notas.append(calificacion) promedio = sum(notas) / len(notas) if promedio >= 3.5: print(f"El a...
Python
1
bool { Self::same_cell_at_depth(self, other, std::cmp::min(self.depth(), other.depth())) } fn same_cell_at_depth(Self(lhs): Self, Self(rhs): Self, depth: u32) -> bool { (lhs ^ rhs) & Self::level_mask(depth) == 0 } } }; (primitive_type:...
Rust
0
pub quality: Option<String>, pub reason: Option<String>, pub metadata: Option<Metadata>, } impl TryFrom<Message> for WebsocketResponse { type Error = std::io::Error; fn try_from(value: Message) -> Result<Self, Self::Error> { if let Message::Text(text) = value { serde_json::from_str(&text).map_err(|e|...
Rust
0
uaFile(ref mut v) => f(v), AccessByLuaFile(ref mut v) => f(v), HeaderFilterByLuaFile(ref mut v) => f(v), ContentByLuaFile(ref mut v) => f(v), BodyFilterByLuaFile(ref mut v) => f(v), LogByLuaFile(ref mut v) => f(v), LuaNeedRequestBody(ref mut v) => ...
Rust
0
): """ Delete the application with `application_id`. """ self._client.delete( self._client.api_host(), f"/v2/applications/{application_id}", auth_type=Application.auth_type, ) def list_applications(self, page_size=None, page=None): ...
Python
1
, total_reserves: state.total_reserves, last_interest_updated: state.last_interest_updated, last_reward_updated: state.last_reward_updated, global_interest_index: state.global_interest_index, global_reward_index: state.global_reward_index, anc_emission_rate: state.anc_emi...
Rust
0
lysis wijken_path = get_geojson_path("alkmaar_wijken_buurten.geojson") # Run the analysis and get results top10nl_green_results_fixed = calculate_green_percentage_per_wijk_clean( wijken_path, gdf ) # %% def load_cbs_data(year): """ Load CBS kerncijfers wijken en buurten data for specified year Parame...
Python
1
se crate::splashsurf_lib::topology::{Axis, DirectedAxis, Direction}; /// assert_eq!(DirectedAxis::new(Axis::X, Direction::Positive) /// .apply_single_step(&[1,2,3]), Some([2,2,3])); /// ``` #[inline(always)] pub fn apply_single_step<N: Clone + CheckedAdd<Output = N> + CheckedSub<Outp...
Rust
0
from(true) } } impl sciter::EventHandler for EventHandler { #[cfg(windows)] dispatch_script_call! ( fn createWindowsShortcut(bool); ); } fn main() { // allows CTRL+SHIFT+I to connect to inspector.exe sciter::set_options(sciter::RuntimeOptions::DebugMode(true)).unwrap(); let archive...
Rust
0
Deserialize, Clone)] pub struct Response { // JSON RPC allows this to be null if it was impossible // to decode the request's id. Ignore this special case // and just die horribly. pub id: RequestId, #[serde(skip_serializing_if = "Option::is_none")] pub result: Option<serde_json::Value>, #[...
Rust
0
ist def mouseMoveEvent(self, a0: QMouseEvent | None): assert a0 is not None point_view_location = NumberVector(a0.pos().x(), a0.pos().y()) point_world_location = self.camera.location_view2world(point_view_location) if a0.buttons() == Qt.MouseButton.LeftButton: if self.f...
Python
1
gents.map(|[x, y, z, _]| Vec3::new(x, y, z)).collect()) } if let Some(uvs) = reader.read_tex_coords(0) { builder = builder.with_vertex_uv0(uvs.into_f32().map(Vec2::from).collect()) } if let Some(uvs) = reader.read_tex_coords(1) { ...
Rust
0
self.inner.lock().await; if let Some(err_kind) = inner.error.read().await.as_ref() { return Err(Error::from(*err_kind)); } if inner.buffer.len() == inner.buffer_size as _ { drop(inner); self.can_send_notify.notified().await; ...
Rust
0
source2, e| { assembler.write_vnull(target, source1, source2, e); }) } } pub struct V30 {} impl Test for V30 { fn name(&self) -> &str { "RSP V30" } fn level(&self) -> Level { Level::RarelyUsed } fn values(&self) -> Vec<Box<dyn Any>> { Vec::new() } fn run(&self, _value: &Box<dyn Any>) -> Result...
Rust
0
); } if !(config.sync_jump_width >= 1 && config.sync_jump_width <= 4) { return Err(McpErrorKind::WrongSJW); } if !(config.sync_jump_width <= config.ph_seg1 && config.sync_jump_width <= config.ph_seg2) { return Err(McpErrorKind::WrongSJW); } self.ch...
Rust
0
m.clone(); config.atoken = deps .api .addr_canonicalize(market_config.aterra_contract.as_str())?; config::store(deps.storage, &config)?; Ok(Response::new().add_submessage(SubMsg { // Create DP token msg: WasmMsg::Instantiate { admin: None, code_id: m...
Rust
0
from django.contrib import admin from django.utils.html import format_html from .models import Stand @admin.register(Stand) class StandAdmin(admin.ModelAdmin): list_display = ('stand_user', 'stand_name', 'power', 'speed', 'range', 'durability', 'precision', 'potential', 'stand_image_thumbnail', 'user_image_thumbna...
Python
1
import simplepyble if __name__ == "__main__": adapters = simplepyble.Adapter.get_adapters() if len(adapters) == 0: print("No adapters found") # Query the user to pick an adapter print("Please select an adapter:") for i, adapter in enumerate(adapters): print(f"{i}: {adapter.identif...
Python
1
self.card .control_by_name::<IntControl>(&self.setting.controls[ch].rdc_ctrl)? .set(rdc)?; self.card .control_by_name::<IntControl>(&self.setting.controls[ch].temp_ctrl)? .set(Self::celsius_to_dsm_unit(temp))?; } Ok(()...
Rust
0
use nx::gpu; use nx::service::hid; use nx::input; use nx::service::nv; use nx::service::vi; use core::ptr; use core::mem as cmem; pub struct RegisteredFont { pub name: &'static str, pub font: &'static rusttype::Font<'static> } impl RegisteredFont { pub fn new(name: &'static str, font: &'static rusttype::...
Rust
0
"{:?}\" is not accessible with dimension \"{:?}\" in algorithm \"{}\"", dir, $dim, $name), }), vec![(x,X)], [x as _,1,1,0]) }, D2(x,y) => { if x<1 || y<1 { panic!("Each given dim in algorithm \"{}\" must be strictly greater than 1, ...
Rust
0
from django.urls import path from rest_framework.routers import DefaultRouter from .views import AutorViewsSet, LivroViewsSet router = DefaultRouter() router.register(r'livros', LivroViewsSet) router.register(r'autor', AutorViewsSet) urlpatterns = router.urls #Criação de rota arquivo urls.py(EXEMPLO): #from djang...
Python
1
from funasr import AutoModel import soundfile as sf from mysql_service import funasr_db # # 初始化VAD模型和流式ASR模型 # vad_model = AutoModel(model="fsmn-vad") # asr_model = AutoModel(model="paraformer-zh-streaming", chunk_size=[0, 10, 5]) # # # 读取长音频文件 # long_audio_path = "D:/software/python/project/funasr_web/字节-安静环境.mp3" # ...
Python
1
## 终版;可指定开始文件夹 import os import json import cv2 def is_number(s): try: int(s) return True except ValueError: return False def load_annotations(json_path): with open(json_path, 'r') as f: annotations = json.load(f) return annotations def extract_face_and_body(image, fa...
Python
1
c = input // Non-incremental implementation of distinct_nested_incremental. .integrate() .integrate_nested() .distinct() .differentiate() .differentiate_nested(); ...
Rust
0
eaning main README, don't forget to run `make fix-copies`.") # clean_main_ref_in_model_list() if __name__ == "__main__": parser = argparse.ArgumentParser() parser.add_argument("--post_release", action="store_true", help="Whether this is pre or post release.") parser.add_argument("--patch", action="stor...
Python
1
to_string(), app.clone()).unwrap()) .collect::<Vec<_>>() } /// Create a Auth object for an application. Take service_id, service_token and app_id of type /// AppIdentifier and returns an Auth object. pub fn auth( service_id: String, service_token: String, app_id: AppIdentifier, ) -> Result<Auth, an...
Rust
0
ckend }) | Backend::Multi(MultiBackend { backend }) | Backend::LibInput(LibInputBackend { backend }) => backend } } } <reponame>wezm/cc2650 #[doc = r" Value read from the register"] pub struct R { bits: u32, } impl super::MISC_CONF_1 { #[doc = r" Reads the contents of the reg...
Rust
0
Rc::new(43u32); mock.expect() .returning_st(move |_| y.clone()); let x = Rc::new(42u32); assert_eq!(43, *MockFoo::bar(x).as_ref()); } #[test] fn withf_st() { let mut mock = MockFoo::new(); let x = Rc::new(42u32); let argument = x.clone(); mock.expect_foo() .withf_st(move |x...
Rust
0