text
string
label_name
string
labels
int64
total_size += types::VarInt.compute_size(v.len() as i32)?; total_size += v.len(); } else { total_size += types::VarInt.compute_size(-1)?; } } Ok(total_size) } fn decode_legacy<B: ByteBuf>(buf: &mut B, version: i8, records: &mut Vec<Record>...
Rust
0
# Adapted straight from https://triton-lang.org/main/getting-started/tutorials/02-fused-softmax.html import triton import triton.language as tl import torch # if @triton.jit(interpret=True) does not work, please use the following two lines to enable interpret mode # import os # os.environ["TRITON_INTERPRET"] = "1" @t...
Python
1
> Option<Square> { for _ in 0..delta.abs() { if delta > 0 { self = self.next_row()?; } else { self = self.prev_row()?; } } Some(self) } pub fn next_row(mut self) -> Option<Square> { if self.row < (BOARD_DIMENSIO...
Rust
0
from config.icon import ICON_CHAT, ICON_SHIELD, ICON_SONG, ICON_SWORD, PATH_ITEM, PATH_SPAWN_SKILL, get_image class Macro: def __init__(self, _id, name, icon): self.id = _id self.name = name self.icon = icon MAX_HOTKEY = 15 ICON_CLIP = get_image(PATH_ITEM, "clip") ICON_FIRE = get_image(P...
Python
1
.' * * '.5', or, equivalently, '0.5' * * '+inf', 'inf', '-inf', 'NaN' * * Leading and trailing whitespace represent an error. * * # Arguments * * * num - A string * * # Return value * * `none` if the string did not represent a valid number. Otherwise, * `Some(n)` where `n` is the floating-point number re...
Rust
0
r_target0_period(&self) -> SYS_TIMER_TARGET0_PERIOD_R { SYS_TIMER_TARGET0_PERIOD_R::new((self.bits & 0x03ff_ffff) as u32) } } impl W { #[doc = "Bit 31"] #[inline(always)] pub fn sys_timer_target0_timer_unit_sel(&mut self) -> SYS_TIMER_TARGET0_TIMER_UNIT_SEL_W { SYS_TIMER_TARGET0_TIMER_UN...
Rust
0
handler: Some(ngx_http_set_response_header), }; init }, { let init = ngx_http_set_header_t { name: { let init = bindings::ngx_str_t { len: 0, data: ptr::null_mut(), ...
Rust
0
429, 0, "", {is_parking_spot: [4, false]}] - [631.562, 587.894, 0, coe, {is_holding_point: [4, true], is_parking_spot: [4, false]}] - [1790.467, 1326.218, 0, ""] - [1364.76, 1336.717, 0, ""] - [2222.415, 1308.722, 0, ""] - [943.631, 1273.435, 0, ""] - [1107.614, 1316.271, 0, ""] ...
Rust
0
### SYSTEM PROMPT # if this is not present, the default system prompt from config.py will be used. """You are a state-of-the-art python code completion system that will be used as part of a genetic algorithm. You will be given a list of functions, and you should improve the incomplete last function in the list. 1. Make...
Python
1
ures _C.PROBABILISTIC.METHOD = 'GAUSSIAN' # [BERNOULLI, GAUSSIAN, MIXGAUSSIAN] _C.PLANNING = CN() _C.PLANNING.ENABLED = True _C.PLANNING.GRU_ENABLED = False _C.PLANNING.GRU_STATE_SIZE = 256 _C.PLANNING.SAMPLE_NUM = 150 _C.PLANNING.COMMAND = ['LEFT', 'FORWARD', 'RIGHT'] # dense configs _C.PLANNING.DENSE = CN() _C.PLAN...
Python
1
22_0624, 0x7BC8_5CD3), (r"meshes\i\in_pycave_sroom3_02.nif", 0x3F22_0624, 0x7BC8_5F33), (r"meshes\i\in_pycave_doorway00.nif", 0x3F22_0624, 0xCD69_B598), (r"meshes\i\in_pycave_lroom2_00.nif", 0x3F22_0624, 0xD8E2_5AE4), (r"meshes\i\in_pycave_sroom2_00.nif", 0x3F22_0624, 0xD8E2_5D24), (r"meshes\i\...
Rust
0
millis: millis as u16, // safe cast: value in range [0, 999] }; Self::new(date, time) } } /// A current time and date provider. /// /// Provides a custom implementation for a time resolution used when updating directory entry time fields. /// `TimeProvider` is specified by the...
Rust
0
def main(): # Ask the user for a number number = float(input("Type a number to see its square: ")) # Calculate the square square = number * number # Print the result print(str(number) + " squared is " + str(square)) # Run the program if __name__ == "__main__": main()
Python
1
JsValue::from_serde(&map_event).unwrap() } else { JsValue::NULL } } #[wasm_bindgen(js_name = getSpriteMasks)] pub fn get_js_sprite_masks(&self, rect: Rect, z: i32, level: i8, upright: bool) -> JsValue { // log!("get_js_sprite_masks: received {:?} {} {}...
Rust
0
tags", &self.tags); formatter.field("next_marker", &self.next_marker); formatter.field("truncated", &self.truncated); formatter.finish() } } #[non_exhaustive] #[derive(std::default::Default, serde::Deserialize, std::clone::Clone, std::cmp::PartialEq)] pub struct ListRetirableGrantsOutputBod...
Rust
0
itter(Duration::default()) .max(Duration::from_secs(5)) .build(); assert_eq!(RetryBackoff::delay(&backoff, 1), Duration::from_millis(500)); assert_eq!(RetryBackoff::name(&backoff), "CrateBackoffRs"); } } <filename>src/postings/block_search.rs use crate::postings::compression...
Rust
0
s x = C() AssertErrorWithMessage(TypeError, "expected int, got NoneType", f, x) C.m_e = lambda self: 10 AreEqual(f(x), 10) C.m_e = lambda self: "abc" AssertErrorWithMessage(TypeError, "expected int, got str", f, x) f = IInterface6...
Python
1
', "letter-f"), (0xFF47, 'g', "letter-g"), (0xFF48, 'h', "letter-h"), (0xFF49, 'i', "letter-i"), (0xFF4A, 'j', "letter-j"), (0xFF4B, 'k', "letter-k"), (0xFF4C, 'l', "letter-l"), (0xFF4D, 'm', "letter-m"), (0xFF4E, 'n', "letter-n"), (0xFF4F, 'o', "letter-o"), (0xFF50, 'p', "letter...
Rust
0
ntinue kernel_frequency[kernel] = [transfer[k], frequency[k]] with open(f'kernel_{threshold}.res', mode='wb') as f: pickle.dump(kernel_frequency, f) # print(kernel_count) return { 'gates_library': transfer, 'frequency': frequenc...
Python
1
plugin_sdk::generators::v1beta1::server::{ GeneratorApi, GeneratorServer, }, protocol::{ healthcheck::HealthcheckStatus, tls::Identity, }, }; use tokio::net::TcpListener; #[derive(clap::Parser, Debug)] pub struct GeneratorServiceConfig { #[clap(long, env = "PLUGIN_BIND_A...
Rust
0
xD6; pub const SMB5_ZP: u8 = 0xD7; pub const CLD: u8 = 0xD8; pub const CMP_ABSY: u8 = 0xD9; pub const PHX: u8 = 0xDA; pub const STP: u8 = 0xDB; pub const CMP_ABSX: u8 = 0xDD; pub const DEC_ABSX: u8 = 0xDE; pub const BBS5: u8 = 0xDF; pub const CPX_IMM: u8 = 0xE0; pub const SBC_ZPXI: u8 = 0xE1; pub const NOP_IMM: u8 = 0x...
Rust
0
self.num_opt_iters, self.mean, self.var, self.best_val, self.best_sol = tf.while_loop( cond=continue_optimization, body=iteration, loop_vars=[0, self.init_mean, self.init_var, float("inf"), self.init_mean] ) def reset(self): pass ...
Python
1
float(scanpoint), effval) # Set errors to 0 for thisscan in scanstoplot: for var in scans[thisscan]: for ppgroup in ordertoread: for ppcat in physperftoplot[ppgroup]["cats"]: for thisbin in range(1...
Python
1
CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. * ----------------------------------------------------------------------------------- * Apache 2.0 License Declaration: * * Licensed under the Apache License, Version 2.0 (the "Li...
Rust
0
ys_bti_release_quarantine(a0 as _), Sys::VMAR_UNMAP_HANDLE_CLOSE_THREAD_EXIT => self .sys_vmar_unmap(a0 as _, a1 as _, a2 as _) .and_then(|_| { let _ = self.sys_handle_close(a3 as _); self.sys_thread_exit() }), ...
Rust
0
import serial import matplotlib.pyplot as plt from collections import deque import time PORT = 'COM9' BAUD_RATE = 115200 ser = serial.Serial(PORT, BAUD_RATE) buffer_size = 100 roll_data = deque(maxlen=buffer_size) pitch_data = deque(maxlen=buffer_size) yaw_data = deque(maxlen=buffer_size) # Added Yaw trac...
Python
1
(Copy, Clone, Debug)] #[repr(C)] pub struct xcb_sync_create_fence_request_t { pub major_opcode: u8, pub minor_opcode: u8, pub length: u16, pub drawable: xcb_drawable_t, pub fence: xcb_sync_fence_t, pub initially_triggered: u8, } impl Default for xcb_sync_create_fence_request_t { fn default(...
Rust
0
type Error = (); /// Attempt to convert a Postgres error into a generic ProvideError /// /// Unexpected cases will be bounced back to the caller for handling /// /// * [Postgres Error Codes](https://www.postgresql.org/docs/current/errcodes-appendix.html) fn try_from(pg_err: &PgDatabaseError...
Rust
0
from langchain_community.vectorstores.utils import ( DistanceStrategy, filter_complex_metadata, maximal_marginal_relevance, ) __all__ = ["DistanceStrategy", "maximal_marginal_relevance", "filter_complex_metadata"]
Python
1
) feasibility_scores = dataset.seen_mask.clone().float() for a in attrs: print('Attribute', a) for o in objs: if (a, o) not in dataset.train_pairs: idx = dataset.pair2idx[(a, o)] score_obj = get_pair_scores_objs( a, ...
Python
1
pub extern crate slog; pub extern crate failure; pub use failure::Error; pub use slog::Logger; use std::borrow::Cow; use std::fmt::{self, Debug, Display, Formatter}; use std::str::FromStr; pub trait Challenge { /// Information describing this challenge. fn info(&self) -> &Info; /// Run the challenge to c...
Rust
0
from django.db import models # Create your models here. # password_reset/models.py from django.db import models from django.contrib.auth.models import User class PasswordResetOTP(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) otp = models.CharField(max_length=6) expires_at = m...
Python
1
from django.contrib import admin from .models import Post, PostAttachment # Register your models here. admin.site.register(PostAttachment) @admin.register(Post) class CustomPostAdmin(admin.ModelAdmin): fieldsets = ( ('Основная информация', {'fields' : ('title', 'content')}), ('Дополнительная инфор...
Python
1
ic_to(7600.0, 16800.0, 13200.0, 16000.0, 18800.0, 16000.0); pb.cubic_to(14800.0, 9200.0, 8800.0, 3200.0, 1200.0, 1200.0); pb.close(); pb.finish().unwrap() }; let path2 = { let mut pb = PathBuilder::new(); pb.move_to(18800.0, 1200.0); pb.line_to(16800.0, 18800.0);...
Rust
0
g_addr(addr as usize) }; if frame > current_area_last_frame { // Current area is full, switch to the next area self.choose_next_area(); } else if frame >= self.kernel_start && frame <= self.kernel_end { // `frame` is being used by the ...
Rust
0
from qiskit import QuantumCircuit, transpile, visualization from qiskit_aer import AerSimulator import matplotlib.pyplot as plt from qiskit.visualization import plot_state_qsphere from qiskit.quantum_info import Statevector from qiskit.visualization import plot_state_city # Create a quantum circuit with 5 qubits and 5 ...
Python
1
lf.pretty = Some(pretty); self } #[doc = "Sets a request timeout for this API call.\n\nThe timeout is applied from when the request starts connecting until the response body has finished."] pub fn request_timeout(mut self, timeout: Duration) -> Self { self.request_timeout = Some(timeout); ...
Rust
0
> Result<(), Error> { match &mut self.pin { #[cfg(raspi)] Pwm::Hardware(pwm_channel, _pin) => { pwm_channel.disable()?; } #[cfg(raspi)] Pwm::Software(pin) => { pin.clear_pwm()?; } #[cfg(not(raspi)...
Rust
0
rate_name = "struct_like_variant"] pub enum Enum { Bar { /// This is a name. name: String } } use std::sync::Mutex; use tokio::time::{delay_for, Duration}; use std::sync::Arc; use rusqlite::Connection; mod telegram; use telegram::structs::{Update,Message}; mod db; mod utils; use utils::{BoxE...
Rust
0
= gdt.add_entry(Descriptor::kernel_code_segment()); let data = gdt.add_entry(Descriptor::kernel_data_segment()); // `sysret` loads segments from STAR MSR assuming `user_code_segment` follows `user_data_segment` // so the ordering is crucial here. Star::write() will panic otherwise later. let user_dat...
Rust
0
FOOD_DATABASE = { 'Chicken Breast': {'calories': 165, 'protein': 31, 'carbs': 0, 'fats': 3.6}, 'Rice': {'calories': 130, 'protein': 2.7, 'carbs': 28, 'fats': 0.3}, 'Eggs': {'calories': 155, 'protein': 13, 'carbs': 1.1, 'fats': 11}, 'Oatmeal': {'calories': 389, 'protein': 16.9, 'carbs': 66, 'fats': 6.9},...
Python
1
WorkQueueError, consensus_service::IncomingConsensusMsg, tx_manager::MockTxManager, }; use grpcio::{ChannelBuilder, Environment, Error::RpcFailure, Server, ServerBuilder}; use mc_common::{ logger::{test_with_logger, Logger}, NodeID, ResponderId, }; use mc_consensus_api::{ ...
Rust
0
=> { if let Some(head_op) = ops.pop() { let work_goal = Goal { state: self.state, op: head_op, }; let goals = work_goal.achieve(); for elem in goals.elements { ...
Rust
0
arams(axis='both', which='major', labelsize=40) dax50.set_xticks(xaxis); dax50.set_yticks(yaxis); dax50.set_xlabel('Expectation of time interval (ms)', fontsize=fontsize, color='black'); dax50.set_ylabel('AP@0.50', fontsize=fontsize, color='black'); # ax50.legend(ncol=2, loc = 'best') # ax50.legend(loc = '...
Python
1
e` //! The `execute` method has no category, so its path is `rvk::methods::execute`. //! //! ## Note: `photos.move` //! Since `move` is a Rust keyword, the function for calling `photos.move` API method is `rvk::methods::photos::move_` (**with the underscore!**) macro_rules! api_category { ($category:expr; methods ...
Rust
0
# model/train.py import torch import os from ultralytics import YOLO def train_yolo(): # Caminho absoluto para o arquivo data.yaml data_config = os.path.abspath(os.path.join(".", "configs", "data.yaml")) # Escolha do modelo pré-treinado; aqui usamos a variante "nano" # Outras opções: yolov8s.pt, yolo...
Python
1
from .config import load_env load_env()
Python
1
import boto3 import os import json import re import requests from . import aws def _to_claude_response(streaming_response)->str: texts = list() for event in streaming_response["body"]: chunk = json.loads(event["chunk"]["bytes"]) if chunk["type"] == "content_block_delta": texts.app...
Python
1
)); } let variants = match &ast.data { Data::Enum(v) => &v.variants, _ => return Err(non_enum_error()), }; let mut arms = Vec::new(); let mut constant_defs = Vec::new(); let mut has_additional_data = false; let mut prev_const_var_ident = None; for variant in variants { ...
Rust
0
from flask import render_template from app import db from app.errors import bp @bp.app_errorhandler(404) def not_found_error(error): return render_template("errors/404.html"), 404 @bp.app_errorhandler(500) def internal_error(error): db.session.rollback() return render_template("errors/500.html"), 500
Python
1
vec![]); // Call all functions that calculate the remainder against rx_buffer.capacity() // with a backing storage with a length of 0. assert_eq!(no_capacity.get_unallocated(0, 0), &[]); assert_eq!(no_capacity.get_allocated(0, 0), &[]); no_capacity.dequeue_allocated(0); ...
Rust
0
_t { /// The sequence number of the request. pub sequence: c_uint, } impl Default for xcb_randr_get_providers_cookie_t { fn default() -> Self { unsafe { std::mem::MaybeUninit::zeroed().assume_init() } } } /// The opcode for `RandR::GetProviders` requests. /// /// If this value appears in [`xcb...
Rust
0
(C)]#[derive(Copy, Clone)] pub struct wlr_box { pub x: libc::c_int, pub y: libc::c_int, pub width: libc::c_int, pub height: libc::c_int, } pub type wl_output_transform = libc::c_uint; pub const WL_OUTPUT_TRANSFORM_FLIPPED_270: wl_output_transform = 7; pub const WL_OUTPUT_TRANSFORM_FLIPPED_180: wl_output...
Rust
0
) - Pennylane', color=color) ax2.plot(qubits_list, time_list_pennylane, '-o', color=color) ax2.tick_params(axis='y', labelcolor=color) # Annotate NMI scores for Pennylane for i, n_qubits in enumerate(qubit_range): nmi_score = nmi_scores[len(qubit_range) + i] ax2.annotate(f'{nmi_score:.2f}', (n_qubits, time_lis...
Python
1
or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation, either version 3 of the License, or // (at your option) any later version. // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty...
Rust
0
().clone()), Expr::Value(mut val) => { if let Some(missing) = val.interpolate(|var| self.find_var(var, |var| var.clone())) { return Err(Error::UndefinedVar(missing)); } Ok(val) }, Expr::Var(ident) => { ...
Rust
0
import json WINDOW_DATA_PATH = 'window_data.json' class WindowData: def __init__(self): self.x = 0 self.y = 0 self.width = 800 self.height = 100 self.need_blur = True def load(self): try: with open(WINDOW_DATA_PATH, 'r') as file: ra...
Python
1
# path: f2/apps/tiktok/api.py class TiktokAPIEndpoints: """ API Endpoints for TikTok """ # 抖音域名 (Tiktok Domain) TIKTOK_DOMAIN = "https://www.tiktok.com" # 直播域名 (Webcast Domain) WEBCAST_DOMAIN = "https://webcast.tiktok.com" # WSS域名 (WSS Domain) WEBCAST_WSS_DOMAIN = "wss://webcast...
Python
1
nned( &input, "Deriving LnpApi can be done only with enums, not with structs", )), Data::Enum(ref data) => lnp_api_inner_enum(&input, data), //strict_encode_inner_enum(&input, &data), Data::Union(_) => Err(Error::new_spanned( &input, "Deriv...
Rust
0
mocker.mock_open(read_data=PIPFILE_LOCK).return_value, write_mock, ] mocker.patch('pundle.op.exists') mocker.patch('pundle.os.listdir') parser = create_parser(**PARSER_ARGS) suite = parser.create_suite() assert suite.need_freeze() == False assert 'requests' in suite.states su...
Python
1
: HttpRequest<AppState>, params: Path<UpdateParams>, ) -> FutureResponse<HttpResponse> { req.state() .db .send(DeleteTask { id: params.id }) .from_err() .and_then(move |res| match res { Ok(_) => { session::set_flash(&req, FlashMessage::success("Task wa...
Rust
0
> 0: self.save_batch_data() # 最终保存进度 self.save_progress("COMPLETED", total_files, processed_count) print(f"处理完成: 成功 {processed_count - already_processed} 个,失败 {failed_count} 个") except KeyboardInterrupt: print...
Python
1
import numpy as np import cv2 class CoordGenerator(object): def __init__(self, intrin, img_w, img_h): super(CoordGenerator, self).__init__() self.intrinsics = intrin self.image_width = img_w self.image_height = img_h def pixel2local(self, depth): # depth: float32, meter. ...
Python
1
import math from rlcard.utils.utils import rank2int class LeducholdemJudger: ''' The Judger class for Leduc Hold'em ''' def __init__(self, np_random): ''' Initialize a judger class ''' self.np_random = np_random @staticmethod def judge_game(players, public_card,typ=0): ...
Python
1
except Exception as e: print(f"❌ API benchmark failed: {e}") def demo_hybrid_approach(): """Main demo showing the hybrid approach.""" print("🎯 InvokeAI Job Queue Hybrid Approach") print("=" * 50) print("⚡ Trying direct database first, API fallback if needed") # Get latest job using...
Python
1
}; return Ok( str::from_utf8( &[ u8_from_octlets( init, chars )? ])?.to_owned() ); }, } } } fn u8_from_octlets( init: u8, chars: &mut impl Iterator<Item=char> ) -> anyhow::Result<u8> { let mut result = init; for i in 0..2 { match chars.next() { Some( ...
Rust
0
expected_output = { 'vrf': { 'VRF1': { 'peer': { '10.4.1.1': { 'active_sa': 0, 'as': 0, 'sa_msgs': { 'received': 0, 'sent': 0, }, ...
Python
1
|&curc| curc); assert_eq!( res, &[ (0, vec![0, 0]), (1, vec![1, 1]), (2, vec![2, 2]), (3, vec![3]), (0, vec![0]), (5, vec![5, 5, 5]), ] ); } #[test] fn test_clsf1() { let input: Vec<Option<u8>> = vec![ ...
Rust
0
trait representing either a `v1` or `v2` SMI syntax. pub trait SmiSyntax {} impl SmiSyntax for crate::v1::ObjectSyntax {} impl SmiSyntax for crate::v2::ObjectSyntax {} /// The current access provided to the object. #[derive(Debug, Clone, Copy, Eq, Ord, PartialEq, PartialOrd)] #[non_exhaustive] pub enum Access { R...
Rust
0
!((i.0, i.1), gen_call!(cf_request_line, r.method, r.uri) >> gen_many!(&r.headers, cf_header) >> gen_slice!(b"\r\n") >> gen_slice!(r.body) ) } pub fn cf_request_line<'a, 'b>(i:(&'a mut [u8],usize), method: &'b str, uri: &'b str) -> Result<(&'a mut [u8],usize),GenError> { do_gen!((i.0, i.1), gen...
Rust
0
ake(_) = self { true } else { false } } } #[derive(Debug)] pub struct Hive { /// Path to the hive. path: HivePath, /// Path to the context directory. /// /// Normally this is directory containing the "hive.nix" /// or "flake.nix". context_dir: Op...
Rust
0
pr::Input(next_input)); next_input += 1; regs[*reg] = v; } Instruction::Add(target, source) => { let lhs = pop_reg(&mut regs, *target); regs[*target] = Box::new(Expr::Add(lhs, source_value(&regs, source))) } ...
Rust
0
ead(block_size) # 解压 decompressed_data = lzma.decompress(block_data) # 每条记录8字节(uint32,uint32) num_records = len(decompressed_data) // 8 block_lengths.append(num_records) decompressed_blocks.append(decompressed_data) # 拼接所有解压块形成原始数据数组book_ ...
Python
1
""" Run The Tyson Oscillator model using StochKit's stochastic simulation algorithm (SSA) implementation. """ import matplotlib.pyplot as plt import numpy as np from pysb.simulator import StochKitSimulator from tyson_oscillator import model def plot_mean_min_max(name, title=None): x = np.array([tr[:][name] for ...
Python
1
es_sent'], 0)), latency=int(row.get(self.column_mappings['latency'], 0)), connect_time=int(row.get(self.column_mappings['connect_time'], 0)) ) # Add sample to test results ...
Python
1
if code < __INTERRUPTS.len() { __INTERRUPTS[code].handler = f; } } #[no_mangle] static mut __INTERRUPTS: [InterruptVector; 12] = [const { InterruptVector { reserved: 0 } }; 12]; #[no_mangle] static mut __Exception: ExceptionVector = ExceptionVector { reserved: 0 }; <filename>vendor/rustcrypto-block-ci...
Rust
0
let rx = borrow_loop(&resource_table, |table| { let receiver = table.get::<ServerResource>(rid).ok_or_else(OpError::bad_resource_id).unwrap(); Rc::clone(&receiver.channel) }); let result = rx.1.borrow_mut().recv().await; match result { Some(req) => { let uri = req.0.uri().to...
Rust
0
#!/usr/bin/env python # How to use: # # Ubuntu 16.04: apt install -y python-boto OR apt install -y python3-boto # # Specify the default profile on aws/boto profile files or use the optional AWS_PROFILE env var: # AWS_PROFILE=example ./dehydrated -c -d example.com -t dns-01 -k /etc/dehydrated/hooks/route53.py # # Manua...
Python
1
chain self.chain = create_retrieval_chain(history_aware_retriever, question_answer_chain) def get_response(self, query: str) -> Dict: response = self.chain.invoke({"input": query, "chat_history": self.chat_history}) sources = set() for context in response["context"]: me...
Python
1
ize = match f32::sqrt(tile_vec.len() as f32) { x if !x.is_normal() || x.fract() != 0.0 => bail!("Invalid puzzle size sqrt({}): {}",tile_vec.len(), x), x => x as usize }; let mut edge_count = HashMap::new(); let mut tiles = HashMap::with_capacity(tile_vec.len()); l...
Rust
0
_size=yaml_cfg.get("MODEL").get("SWIN").get("WINDOW_SIZE")).cuda() model_1.load_from(config) print(f"total number of trainable parameters {count_parameters(model_1)}") model_1 = model_1.cuda() bench_dataset = get_test_datasets(args.seed, fold_number=args.fold) bench_loader = torch.utils.data.Dat...
Python
1
class Solution: def findTheWinner(self, n: int, k: int) -> int: res = [i for i in range(1, n+1)] curr = 0 while len(res) > 1: curr += k - 1 if curr > len(res)-1: curr %= len(res) res.pop(curr) return res[0]
Python
1
import numpy as np import pandas as pd from pathlib import Path import datetime as dt import yfinance as yf import sys data_dir = Path(__file__).resolve().parents[0]/"data" from setup import portofolio, ticker_currency, scenarios # single source of truth px = pd.read_csv(data_dir/"prices.csv", i...
Python
1
# -*- coding: utf-8 -*- """ Views ################# *Module* ``project.annotator.views`` This module defines routes to manage views for annotators. """ from flask_login import login_required, current_user from flask import render_template from . import annotator_app from .helpers import batches_list # Annotator - ...
Python
1
quences[0] output = tokenizer.decode(s)[6:-4] pred = output[len(prompt):] pred_captions[video_name] = pred # print(video_name, " ", pred) # print("gt_sentence: ", gt_sentence) # print("x"*10) except Exception as e: print(e) print("Problem with video:...
Python
1
e fields see [ep4_fifo_config](index.html) module"] pub struct EP4_FIFO_CONFIG_SPEC; impl crate::RegisterSpec for EP4_FIFO_CONFIG_SPEC { type Ux = u32; } #[doc = "`read()` method returns [ep4_fifo_config::R](R) reader structure"] impl crate::Readable for EP4_FIFO_CONFIG_SPEC { type Reader = R; } #[doc = "`write...
Rust
0
end1 += job.finished end2 = 0 for job in self.new_job: end2 += job.finished if end1 == self.multiShop[shop_id].jobs and end2 == self.args.add_job: done = True return done def obs_list_to_state_vector(self, observation): state = observatio...
Python
1
# ---------------------------------------------------------------------------- # Copyright 2019-2022 Diligent Graphics LLC # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.a...
Python
1
from django.test import TestCase from unittest.mock import patch, MagicMock from Mapapi.test_runner import CoverageRunner class TestCoverageRunner(TestCase): """Tests for the CoverageRunner class""" @patch('coverage.Coverage') def test_init(self, mock_coverage): """Test initialization of Coverage...
Python
1
a Expr<'a, Ex, Fb, En, Hi>, ); impl<'a, Ex: TrivialDrop, Fb: TrivialDrop, En: TrivialDrop, Hi: TrivialDrop> TrivialDrop for Field<'a, Ex, Fb, En, Hi> { } #[derive( Clone, Copy, Debug, Eq, FromOcamlRepIn, Hash, NoPosHash, Ord, PartialEq, PartialOrd, Serialize, ToOcaml...
Rust
0
Stream}; // use hyper::client::HttpConnector; use http_router::constraint::{INDEX, NOTFOUND}; use hyper::client::HttpConnector; use hyper::{Body, Chunk, Client, Method, Request, Response, Server, StatusCode}; use serde_json; use std::str; use std::sync::{Arc, Mutex, MutexGuard}; pub struct ImgRecog { bd: Arc<Mutex...
Rust
0
lt of "%U %u %V %Y" is different from MySQL. "%b %M %m %c %D %d %e %j %k %h %i %p %r %T %s %f %v %x %Y %y %%", "Jan January 01 1 1st 01 1 001 0 12 00 AM 12:00:00 AM 00:00:00 00 123456 52 4294967295 0000 00 %", ), ( "...
Rust
0
import os import asyncio from pyrogram import Client, filters from pyrogram.types import InlineKeyboardMarkup, InlineKeyboardButton, Message, CallbackQuery from telegraph import upload_file from utils import get_file_id @Client.on_message(filters.command("telegraph") & filters.private) async def telegraph_upload(bot,...
Python
1
from pyramid import cv_laplacian, cv_pyramid, cv_multiresolution_blend, cv_reconstruct_laplacian def pyramid_blend(dst_img,src_img,mask,scale): gpA = cv_pyramid(dst_img.copy(), scale) gpB = cv_pyramid(src_img.copy(), scale) gpM = cv_pyramid(mask.copy(), scale) lpA = cv_laplacian(gpA, scale) lpB =...
Python
1
MaskPrimitiveType { EVROverlayIntersectionMaskPrimitiveType_OverlayIntersectionPrimitiveType_Rectangle = 0, EVROverlayIntersectionMaskPrimitiveType_OverlayIntersectionPrimitiveType_Circle = 1, } #[repr(i32)] #[derive(Debug, Copy, Clone, PartialEq, Eq, Hash)] pub enum EVRRenderModelError { EV...
Rust
0
digest(v in any::<AvlTreeData>()) { let digest: Vec<i8> = v.digest.clone().into(); let obj = Expr::Const(v.into()); let expr: Expr = MethodCall::new( obj, savltree::DIGEST_METHOD.clone(), vec![], ) .unwrap() ...
Rust
0
_secs: u64) { loop { let mut data = String::new(); for metric in self.metrics.get_metrics() { let metric_data = metric.get_push_metric_format(); data.push_str(&metric_data); } let response = ureq::post(&push_metrics_endpoint) ...
Rust
0
import torch.nn as nn import torch class CNNTeacherModel(nn.Module): def __init__(self, shared_model, tokenizer, num_labels, args, hidden_size): super().__init__() self.shared_model = shared_model self.category_head = nn.Linear(hidden_size, num_labels) self.class_head = nn.Linea...
Python
1
v_last(x) x = self.bn_last(x) x = self.activation(x) # average pooling layer x = self.avgpool(x) # flatten for input to fully-connected layer x = x.view(x.size(0), -1) x = self.fc(x) return F.log_softmax(x, dim=1) if __name__ == "__main__": """Test...
Python
1
env.store(variable_name, rhs_poly.clone()); } else { self.add_witness_to_env(variable_name, witness, env); } // This is a private statement, which is why we extract only a witness type from the object let rhs_as_witness = rhs_poly .extract_private_wit...
Rust
0