text
string
label_name
string
labels
int64
from pydantic import BaseModel, Field last_id: int = 0 class CodeNote(BaseModel): id: int = Field(title="note id", default_factory=lambda: CodeNote.generate_id()) name: str = Field(title="note name") code_block: str = Field(title="note code block") @staticmethod def generate_id() -> int: ...
Python
1
#!/usr/bin/env python3 """ Duck typing - first element of a sequence """ from typing import Any, Union, Sequence, Iterable, List, Tuple # The types of the elements of the input are not know def safe_first_element(lst: Sequence[Any]) -> Union[Any, None]: """ Safe first element """ if lst: return lst[0]...
Python
1
ts_grade) is list: bboxes = results_grade else: bboxes = results_grade.boxes.data.cpu().numpy() for box in bboxes: xmin = int(box[0]) ymin = int(box[1]) xmax = int(box[2]) ymax = int(box[3]) if len(box) >= 6: ...
Python
1
#[panic_handler] pub fn panic(_info: &::core::panic::PanicInfo) -> ! { revert(ApiError::OutOfMemory) } #[lang = "eh_personality"] extern "C" fn eh_personality() {} #[no_mangle] pub extern "C" fn call() { let initial_memory_pages = memory_size(); // Grow memory into exactly MAX_MEMORY_PAGES - GROW_MARGIN ...
Rust
0
timeauth_verify(&out1, &m, &k); let r2 = tweetnacl::onetimeauth_verify(&out2, &m, &k); assert_eq!(r1, r2); }) } #[test] fn stream() { let mut rng = rand::thread_rng(); prob_test(10, || { let len = rng.gen_range(0..1024); println!("length: {}", len); let mut m = vec...
Rust
0
import os, sys sys.path.insert(1, "/".join(os.path.realpath(__file__).split("/")[0:-2])) from fsm.machine import * from fsm.assign import * from fsm.optimize import calcBest s0, s1, s2, s3, s4 = createStatesByCount(5) m = MooreMachine(symbols("X"), symbols("Z")) m.addState(s0, (s0, s1), 1) m.addState(s1, (s2, s4), 0...
Python
1
Margin=72, leftMargin=72, topMargin=72, bottomMargin=72 ) # Define styles styles = getSampleStyleSheet() title_style = styles['Title'] heading_style = styles['Heading2'] normal_style = styles['Normal'] # Create a custom style for Braille text braille_sty...
Python
1
nk,)) if not items_for_main_db: logging.warning("정제 후 삽입할 유효한 데이터가 없습니다.") return try: # (DB 저장 로직은 기존과 동일) conn_main = sqlite3.connect(DB_PATH) cursor_main = conn_main.cursor() cursor_main.executemany(""" INSERT OR IGNORE INTO knowledge_base (link, ...
Python
1
); Ok(()) } // Computed Replicas 1 => { let mut param = TopicReplicaParam::default(); param.decode(src, version)?; *self = TopicSpec::Computed(param); Ok(()) } // Unexpected type...
Rust
0
print(f'{self.split} unanswerable question {len(json_data) - len(lang_data)},' + f'answerable question {len(lang_data)}') return lang_data, scan_ids, scan_to_item_idxs def build_answer(self): train_data = json.load(open(os.path.join(self.base_dir, 'anno...
Python
1
ngers centered self.world.add_constraint( self.body, self.body.links["panda_leftfinger"], self.body, self.body.links["panda_rightfinger"], pybullet.JOINT_GEAR, [1.0, 0.0, 0.0], Transform.identity(), Transform.identit...
Python
1
ror!("[queue:{}] failed to create new job: {}", &queue_name, err); Ok(HttpResponse::ServiceUnavailable().body(err.to_string())) }, Err(err) => { error!("[queue:{}] failed to create new job: {}", &queue_name, err); ...
Rust
0
WhiteBeam service"); } Ok(()) } fn run_stop() -> Result<(), Box<dyn Error>> { if !platform::is_superuser() { return Err("WhiteBeam: Insufficient privileges to stop WhiteBeam service".into()); } if !valid_auth()? { return Err("WhiteBeam: Authorization failed".into()); } println!("WhiteBeam: Stoppin...
Rust
0
{ type Output = Vector<T>; /// Subtract a scalar from vector elements /// /// # Example /// /// ``` /// use mathru::algebra::linear::Vector; /// /// let a: Vector<f64> = Vector::new_column(vec![1.0, 2.0, 3.0, 4.0]); /// let res_ref: Vector<f64> = Vector::new_column(vec![-4.0, -3...
Rust
0
# # COPYRIGHT: # The Leginon software is Copyright under # Apache License, Version 2.0 # For terms of the license agreement # see http://leginon.org # import os import ConfigParser import pyami.fileutil leginonconfigparser = ConfigParser.SafeConfigParser() confdirs = pyami.fileutil.get_config_dirs(packag...
Python
1
""" This is just a utility that I use to extract the projector for quantized models. It is NOT necessary at all to train, or run inference/serve demos. Use this script ONLY if you fully understand its implications. """ import os import argparse import torch import json from collections import defaultdict def parse_...
Python
1
n loss_types: value = rec['value-' + loss_type] for peril in binary_perils: rec['loss-%s-%s' % (loss_type, peril)] = haz[ 'Volcanic_' + peril] * value for occupant in occupants: occ = rec[occupant] for peril in binary_perils: ...
Python
1
hereum.is_erc20_deposit_approved(token.address).await?); } // To be sure that the deposit is committed, we need to listen to the event `NewPriorityRequest` // rust SDK doesn't support getting this information yet, but it will be added soon. // assert_eq!(balance_after - balance_before, u256_to_big_dec(...
Rust
0
name=input_dict.get("dataset").get("name"), ordinal=input_dict.get("dataset").get("ordinal"), ), implements_variable=( SimpleImplementsVariable( uid=input_dict.get("implements_variable").get("uid"), name=input_di...
Python
1
# Requires com.databricks:spark-xml_2.12:0.14.0 # TODO: normalize column names - remove `_`, switch to snake case posts_schema = "`_AcceptedAnswerId` BIGINT, `_AnswerCount` int,`_Body` STRING,`_ClosedDate` TIMESTAMP,`_CommentCount` int,`_CommunityOwnedDate` TIMESTAMP,`_ContentLicense` STRING,`_CreationDate` TIMESTAMP...
Python
1
rLrBrZset_rawZheader_source_parse startswithrerfrgrdZ set_unixfromr>r'ZMisplacedEnvelopeHeaderDefectZdefectsfindZInvalidHeaderDefect) rr0Z lastheaderZ lastvaluelinenor$rNrnirrrr[sH            ...
Python
1
t(&b.n_file).unwrap().clone(); let mut map = pos_to_height.write().unwrap(); map.insert(b.n_data_pos, height); } TxDB { db: Some(db), file_pos_to_height, } } else { TxDB::null() } } p...
Rust
0
(VXX2 + p * (VXX3 + p * (VXX4 + p * (V005 + V006 * p))))) } #[cfg(test)] mod test_specvol_sso_0 { use super::specvol_sso_0; use crate::gsw_internal_const::GSW_SSO; use crate::volume::specvol; /// specvol() at SSO & CT=0 should be identical to specvol_sso_0() #[test] fn specvol_vs_specvol_sso_...
Rust
0
""" Highstock Demos Two panes, candlestick and volume: http://www.highcharts.com/stock/demo/candlestick-and-volume This code accompanies the blog post https://www.pyxll.com/blog/interactive-charts-in-excel-with-highcharts """ from pyxll import xl_func from highcharts import Highstock from highcharts_xl import hc_plot ...
Python
1
d = NonNegativeF64::zero(); } } if warn { // warn!( // "Corrected dispersal values to 0.0 at ({},{}) to fit // \ habitat ...", x, y, // ); } } else { ...
Rust
0
import os import sys import traceback from typing import TYPE_CHECKING if TYPE_CHECKING: from datachain.catalog import Catalog def query( catalog: "Catalog", script: str, parallel: int | None = None, params: dict[str, str] | None = None, ) -> None: from datachain.data_storage import JobQueryT...
Python
1
ception.args[0] for memory_substring in MEMORY_ERROR_SUBSTRINGS ] ) ): self._caught_memory_errors.append(exception) self._caught_memory_error_on_last_attempt = True else: self._caught_runtime_errors.append(exception) ...
Python
1
1: f64, y1: f64, x2: f64, y2: f64) -> i32; #[no_mangle] fn pdf_dev_arc(c_x: f64, c_y: f64, r: f64, a_0: f64, a_1: f64) -> i32; #[no_mangle] fn pdf_dev_arcn(c_x: f64, c_y: f64, r: f64, a_0: f64, a_1: f64) -> i32; #[no_mangle] fn pdf_dev_newpath() -> i32; /* Path Painting */ #[no_mangle] ...
Rust
0
# This file was auto-generated by Fern from our API Definition. import typing import typing_extensions from .modifier_location_overrides import ModifierLocationOverridesParams from .money import MoneyParams class CatalogModifierParams(typing_extensions.TypedDict): """ A modifier that can be applied to items...
Python
1
more Verifiable Credentials. //! This example demonstrates building and usage of VPs. //! //! cargo run --example verifiable_presentation mod common; use identity::core::Url; use identity::credential::Credential; use identity::credential::Presentation; use identity::credential::PresentationBuilder; use identity::cryp...
Rust
0
/// This is an example commit message for linting /// /// Relates-to: #153 /// /// ; Bitte geben Sie eine Commit-Beschreibung f\u{00FC}r Ihre \u{00E4}nderungen ein. Zeilen, /// ; die mit ';' beginnen, werden ignoriert, und eine leere Beschreibung /// ; bricht den Commit ab. ...
Rust
0
.checked_mul(min)) .and_then(|r| r.floor().checked_as::<u64>()) } #[cfg(test)] mod tests { use super::*; /// floor(a * b / denominator) pub fn mul_div_old<SrcA, SrcB, SrcD>(a: SrcA, b: SrcB, denominator: SrcD) -> Option<u64> where SrcA: fixed::traits::ToFixed, SrcB: fixed::trai...
Rust
0
s[:, 0].unsqueeze(0) # next_token_prob_0 = token_probs[:, next_token_id_0].item() # next_token_id_1 = output_ids[:, 1].unsqueeze(0) # next_token_prob_1 = token_probs[:, next_token_id_1].item() # prob_subtract=next_token_prob_1-next_token_prob_0 # return prob_subtract # star...
Python
1
# Copyright 2025 The HuggingFace Team. All rights reserved. # # 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 applicabl...
Python
1
target.waiting_for_sync(node1, 3); // check whether node panic assert!(target.rpc_client().get_block(uncle.hash()).is_none()); } } pub struct BlockSyncForks; impl Spec for BlockSyncForks { crate::name!("block_sync_forks"); crate::setup!( num_nodes: 3, connect_all: f...
Rust
0
msg: String, } fn hello(timer: &Timer, _req: serv::Empty) -> Box<Future<Item = HelloResp, Error = serv::Error>> { let f = timer .sleep(Duration::from_secs(1)) .map_err(|_e| "timer failed".into()) .map(|_| HelloResp { msg: "hello, world".to_owned(), }); Box::new(f)...
Rust
0
## IMPORT MODULES import cv2 import PIL ## BEGIN CHECK FILE TYPE def fn_ConvertFrameThresholdAdaptive_Mean(DictOfVideoCaptureDataObjects): """ DOC STRING HERE - ERROR WITH THIS FUNCTION """ ## TEST PRINT OUTPUT print(f"\nBEGIN FUNCTION #00 - CONVERT FRAME THRESHOLD ADAPTIVE MEAN") ## DEC...
Python
1
# -*- coding: utf-8 -*- # Part of Odoo. See LICENSE file for full copyright and licensing details. from odoo import api, fields, models, _ from odoo.addons.http_routing.models.ir_http import slug class Event(models.Model): _inherit = 'event.event' exhibition_map = fields.Image(string='Exhibition Map', max_w...
Python
1
# Copyright (c) Qualcomm Innovation Center, Inc. # All rights reserved # # This source code is licensed under the BSD-style license found in the # LICENSE file in the root directory of this source tree. import torch from executorch.backends.qualcomm.builders.node_visitor import dq_ops from executorch.backends.qualcomm....
Python
1
fn backtrace(&self) -> Option<&Backtrace> { None } fn context<D>(self, context: D) -> Context<D> where D: Display + Send + Sync + 'static, Self: Sized { Context::new(context) } } impl Display for CudaErrorExt { fn fmt(&self, f: &mut Formatter<'_>) -> FmtResult { write!(f, "{}: {}", self.inner....
Rust
0
} } } #[cfg(test)] mod tests { use rand::{prelude::StdRng, Rng, SeedableRng}; use std::fmt::Debug; use crate::Point; use super::{field_of_view, VisionMap}; const WIDTH: i32 = 45; const HEIGHT: i32 = 45; const POSITION_X: i32 = 22; const POSITION_Y: i32 = 22; const RAD...
Rust
0
* from_id: TradeId to fetch from. Default gets most recent trades. /// * limit: Default 500; max 1000. /// /// If fromId is set, it will get id >= that fromId. Otherwise most recent trades are returned. pub async fn my_trades( &self, symbol: impl AsRef<str>, ...
Rust
0
ext("Enter Text", state.text_input) PyImGui.text(f"Entered Text: {state.text_input}") PyImGui.separator() if PyImGui.collapsing_header("Tables"): # Test Table if PyImGui.begin_table("Test Table", 3): # Begin a table with 3 columns PyI...
Python
1
def to_pig(eng_string): eng_words = eng_string.split() pig_words = [] vowels = ["a", "e", "i", "o", "u"] cap_vowels = ["A", "E", "I", "O", "U"] for word in eng_words: for i in range(len(word)): if word[0] in vowels or word[0] in cap_vowels: pig_words.append(word ...
Python
1
Ok(()) } _ => Err("example missing GITHUB_TOKEN".into()), } } <filename>src/data/two_dim/mod.rs //! Mathematical data structures in two dimensions pub mod vector; <reponame>colin-daniels/agnr-ml<filename>rsp2/src/io/lammps/low_level/c_enum_macros.rs<gh_stars>0 /* **************************************...
Rust
0
from celery import Celery from app.celery_tasks.celery_schedule import schedules as task_schedules from app.config import settings app = Celery( "app", broker=settings.CELERY_BROKER, backend=settings.CELERY_BACKEND, timezone=settings.TIMEZONE, task_serializer="json", result_serializer="json", ...
Python
1
gl.TexParameteri(gl::TEXTURE_2D, gl::TEXTURE_MAG_FILTER, gl::NEAREST as i32); } let img = image::open("./assets/imgs/container.jpg")?; let data = img.to_bytes(); unsafe { gl.TexImage2D( gl::TEXTURE_2D, 0, gl::RGB as ...
Rust
0
url: https://wdl1.pcfg.cache.wpscdn.com/wps-office_11.1.0.10702.XA_amd64.deb sha256: 390a8b358aaccdfda54740d10d5306c2543c5cd42a7a8fd5c776ccff38492992 size: 275210770 installed-size: 988671247 x-checker-data: type: html ...
Rust
0
ripherals<'a> { #(#fields,)* } impl<'a> Peripherals<'a> { /// Grants access to all the peripherals pub unsafe fn all() -> Self { Peripherals { #(#exprs,)* } } } }); Ok(()) } /// Generat...
Rust
0
.value { let attr_value = value.content.clone(); return Some(IAttrValue::Value(attr_value.iter().collect(), attr.quote)); } else { return Some(IAttrValue::True); } } } None } /// impl `set_attribute` fn set_attribute(&mut self, name: &str, value: Option<&str>) { let mut need_quote = ...
Rust
0
"""The localization decorator (~l10n) for message localization information.""" from typing import Optional, Sequence from marshmallow import EXCLUDE, fields from ..models.base import BaseModel, BaseModelSchema class LocalizationDecorator(BaseModel): """Class representing the localization decorator.""" cla...
Python
1
import os import unittest from pyats.topology import loader from genie.libs.sdk.apis.iosxe.spanning_tree.configure import unconfigure_spanning_tree_guard_loop class TestUnconfigureSpanningTreeGuardLoop(unittest.TestCase): @classmethod def setUpClass(self): testbed = f""" devices: E-...
Python
1
D_SIZE, None => 0 } + payload_size; result } } #[cfg(test)] mod whitebox_tests { //whitebox tests that need internal access #[test] fn size() { use super::*; assert_eq!(0, PacketBuilderStep::<UdpHeader> { state: PacketImpl { ...
Rust
0
= c.regs.pc.wrapping_add(c.fix_pc_rti as u16); c.fix_pc_rti = 0; } Ok(( if decode_only { A::len() } else { 0 }, in_cycles + if extra_cycle { 1 } else { 0 }, )) } /** * RTS - Return from Subroutine * * The RTS instruction is used at the end of a subroutine to return to the callin...
Rust
0
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { write!( f, "({}){:?} {} {}", self.index, self.token_type, self.lexeme, self.literal ) } } <reponame>ACSimon33/Advent_of_Code mod day_14_transparent_origami { use pretty_assertions::assert_eq; // Exa...
Rust
0
from plone.app.testing import applyProfile from plone.app.testing import FunctionalTesting from plone.app.testing import IntegrationTesting from plone.app.testing import PLONE_FIXTURE from plone.app.testing import PloneSandboxLayer import collective.contentrules.telegram class CollectiveContentrulesTelegramLayer(Plo...
Python
1
()); } } <filename>crates/comet/src/semispace.rs //! # SemiSpace //! //! Simple semi-space garbage collector that separates heap into two spaces: "to space" and "from space". During mutator time //! all allocations go to "to space" and when it is full they are swapped and all objects are copied from "from space" to...
Rust
0
d_pline) return jsonify({'selectedData': selected_data}) except Exception as e: print(f"Error delete table data: {e}") return jsonify({'error': 'Internal Server Error'}), 500 @app.route('/delete_products', methods=['POST']) def delete_products(): try: data = request.get_json() ...
Python
1
ink.recv() assert rx_frame == test_frame1 yield sink.wait() rx_frame = sink.recv() assert rx_frame == test_frame2 yield delay(100) yield clk.posedge print("test 7: alternate pause sink") current_test.next = 7 test_frame1 = axis_ep.AXIStreamFr...
Python
1
= phf_map! { "atr_tv_a" => 1 << 0, "atr_tv_b" => 1 << 1, "atr_tv_c" => 1 << 2, "atr_tv_d" => 1 << 3, "atr_tv_e" => 1 << 4, "atr_tv_f" => 1 << 5, "atr_tv_g" => 1 << 6, "atr_tv_h" => 1 << 7, "atr_tv_i" => 1 << 8, "atr_tv_j" => 1 << 9, "atr_mv_a" => 1 << 0, "atr_mv_b" => 1 ...
Rust
0
; #[derive(Queryable, Serialize, Debug)] pub struct Node { pub id: i32, pub node: String, pub visited: bool, } use crate::rt::{alloc, arc, atomic, condvar, execution, mutex, notify}; use crate::rt::{Access, Execution}; #[derive(Debug, Copy, Clone, Eq, PartialEq)] pub struct Object { /// Index in the s...
Rust
0
_mult, b1_row_vec, c1_row_vec); _mm256_storeu_pd(c1_row, c1_row_vec); let c2_row = c.get_chunk(row, pillar + 4, p_stride); let mut c2_row_vec = _mm256_loadu_pd(c2_row as *const f64); c2_row_vec = _mm256_fmadd_pd(a_mult, b2_row_vec, c2_row...
Rust
0
()?; if exponent < 0 { Ok(-exponent as usize) } else { Ok(0) } } // For example, "123.456". (Some(i), None) => Ok(s.len() - (i + 1)), // For example, "123.456e789". (Some(i), Some(j)) if i < j => { ...
Rust
0
ONT_CARE, GLX_X_VISUAL_TYPE: int = GLX_DONT_CARE, // enum { GLX_NONE, GLX_SLOW_CONFIG, GLX_NON_CONFORMANT_CONFIG } GLX_CONFIG_CAVEAT: enum = GLX_DONT_CARE, // enum { GLX_NONE, GLX_TRANSPARENT_RGB, GLX_TRANSPARENT_INDEX } GLX_TRANSPARENT_TYPE: enum = GLX_NONE, GLX_TRANSPAR...
Rust
0
import atexit from pathlib import Path from typing import Any, Optional from .ffi import ffi, load_netfx from .types import Runtime, RuntimeInfo, StrOrPath _FW: Any = None class NetFx(Runtime): def __init__( self, domain: Optional[str] = None, config_file: Optional[Path] = None ): initialize...
Python
1
::ToVal}; pub trait Sealed<T> { } impl<T> Sealed<Slot> for T where T: ToVal { } impl Sealed<char> for char { } impl Sealed<char> for &char { } impl Sealed<char> for &mut char { } impl Sealed<char> for Val { } impl Sealed<char> for &Val { } impl Sealed<char> for &mut Val { } impl Sealed<char> for ...
Rust
0
import socket as s import threading as t import mysql from sqlfunctions import Database #import _mysql_connector import sys import os option = False selection = 0 while option == False: print("1. Iniciar sesión") print("2. Crear sesión") selection = input("Ingrese un numero: ") if selection == "1" o...
Python
1
# Copyright (c) 2011 Andrew Wilkins <axwalk@gmail.com> # # Permission is hereby granted, free of charge, to any person obtaining a copy # of this software and associated documentation files (the "Software"), to deal # in the Software without restriction, including without limitation the rights # to use, copy, modify, ...
Python
1
one and bk_decimal.epsilon_lte(new_qty, order.filled_qty): self._publish_replace_reject(order, RejectCode.NewQtyCantBeLessThanOrEqualToFilledQty) return result = self._cancel_without_publish(order) if isinstance(result, RejectCode): self._publish_replace_reject(order,...
Python
1
规用途是传入卖出order, with_points_ext=sell_index=pd.to_datetime(orders['sell_date'])) :param with_price: 将价格一起绘制 :return: """ # TODO Iterable和six.string_types的判断抽出来放在一个模块,做为Iterable的判断来使用 if not isinstance(time_period, Iterable) or isinstance(time_period, six.string_types): raise TypeError('MA CAL...
Python
1
size): gbi = batch_slot[bi] # Global index in the input batch l = prefix_len[bi] r = min(t_seq_len[bi], max_seq_len[gbi]) t_ids[bi] = target["output_ids"][bi, 0, l:r].tolist() t_seq_ids[bi] = target["output_ids"][bi, 0, :r] outputs["output_ids"][g...
Python
1
operand4: None, lock: false, rounding_mode: None, merge_mode: None, sae: false, mask: None, broadcast: None, }, &[197, 252, 80, 219], OperandSize::Qword, ) } pub mod device_profile; mod device_resource; mod prof...
Rust
0
rted_sinput_F+self.pe(sorted_sinput_C,sorted_sinput.tensor_stride[0]) # sorted_sinput_F=sorted_sinput_F # Split the features based on batch indices,then split to windows with padding mask 把大batch分成小窗,不同实例的被分开,不够分的补齐 coords, features = sorted_sinput_C, sorted_sinput_F batch_indices = coor...
Python
1
s.playing = True await send_ws_message(ws, ENUM_TO_CAMEL[MessageType.ON_RESUMED], {"progress": last_time}) logger.info(f"状态变更 -> 播放, 进度: {last_time} ms") # 播放开始时,尝试更新音量信息 curre...
Python
1
Kill, #[serde(rename = "CAP_LEASE")] /// Establish leases on arbitrary files (see /// [fcntl(2)](https://man7.org/linux/man-pages/man2/fcntl.2.html)). /// /// _since Linux 2.4_ Lease, #[serde(rename = "CAP_LINUX_IMMUTABLE")] /// Set the **FS_APPEND_FL** and **FS_IMMUTABLE_FL** inod...
Rust
0
# file: runme.py # This file illustrates the shadow-class C++ interface generated # by SWIG. from __future__ import print_function import new_example # ----- Object creation ----- print ("Creating some objects:") c = new_example.Circle(10) print (" Created circle", c) s = new_example.Square(10) print (" Crea...
Python
1
_txt())); } let path_str_c = if cfg!(unix) { use std::os::unix::ffi::OsStrExt; CString::new(path.as_os_str().as_bytes()) } else { CString::new( path.as_os_str() .to_str() .ok_or(Error::Path(PathErrorKind...
Rust
0
gex::new(r"^(\d\d?\d?)(\d{3}*)$").unwrap()); static CVTHOUSANDS: Lazy<Regex> = Lazy::new (|| Regex::new(r"(\d{3})").unwrap()); // Fill slice with random bytes. pub fn random_bytes(dst: &mut [u8], n: usize) { let n = cmp::min(n, dst.len()); if unsafe { libc::getrandom(dst.as_mut_ptr() as *mut ffi::c...
Rust
0
rgument("--model_name", type=str, help="model name; <results_base_folder>/<model>") parser.add_argument("--retriever", type=str, help="retriever name; results stored at <results_base_folder>/<model>/<retriever>") parser.add_argument("--dataset", type=str, help="dataset name; results stored at <results_base_fold...
Python
1
usReasonDetail::new(example).unwrap(); assert_eq!( detail, StatusReasonDetail::ResourceErrors(ResourceErrors { logical_resource_ids: "Vpc, Fs", }) ); if let StatusReasonDetail::ResourceErrors(resource_errors) = detail { assert_eq!( ...
Rust
0
ext 4 bits represent 2nd row - right rotate 1 bit ((self & 0x0080) >> 3) | ((self & 0x0070) << 1) | // next 4 bits represent 3rd row - right rotate 2 bits ((self & 0x0c00) >> 2) | ((self & 0x0300) << 2) | // next 4 bits represent 4th row - right rotate 3 bits ((self & 0xe000) >> ...
Rust
0
channel: NoiseChannel, dmc_channel: DmcChannel<'a>, counter_mode: bool, even_cycle: bool, cycles: u32, inhibit_irq: bool, irq: bool, t: f32, } impl<'a> Apu2A03<'a> { const SECONDS_PER_CLOCK: f32 = 1.0 / (NES_APU_CLOCK as f32); pub fn new( range_start: cpu6502::Address, ...
Rust
0
(i) => i, None => { return Err(MetaParseError::new(format!( "{:?} has unterminated metadata", s ))) } }; let (meta, text) = { let (meta, line_with_sep) = meta_and_text.split_at(meta_end); ...
Rust
0
to_nanos(); // TODO: Some profilers will show the two batches of iterations as // being different code-paths even though they aren't really. // Get the warmup time for one second let (wu_elapsed, wu_iters) = self.warm_up(measurement, Duration::from_secs(1), parameter); if wu_el...
Rust
0
during setup factory.connect_setup(move |_, list_item| { // Create `TodoRow` let todo_row = TodoRow::new(); list_item.set_child(Some(&todo_row)); }); // Tell factory how to bind `TodoRow` to a `TodoObject` factory.connect_bind(move |_, list_item| { ...
Rust
0
#[test] fn conversion_test() { let threshold = 0.00001; let mut fov = Fov::default(); let initial_fov = fov.radian; fov.convert_axis(FovAxis::Horizontal, AspectRatio::default()); let fov_horizontal = fov.radian; println!("Horizontal fov is {}", fov_horizontal....
Rust
0
# Copyright (c) OpenMMLab. All rights reserved. from mmdet.models.builder import DETECTORS from mmdet.models.detectors.detr import DETR @DETECTORS.register_module() class DINO(DETR): def __init__(self, *args, **kwargs): super(DETR, self).__init__(*args, **kwargs)
Python
1
m_score", sql) def test_generate_sql_statistical_analysis(self): """测试统计分析SQL生成""" # 测试方差 sql = self.generator.generate_sql("score", AnalysisType.VAR_POP) self.assertIn("SELECT VAR_POP(score) as var_pop_score", sql) # 测试标准差 sql = self.generator.generate_sql("score",...
Python
1
#!/usr/bin/env python3 # SPDX-FileCopyrightText: 2024 Eli Array Minkoff # # SPDX-License-Identifier: 0BSD # Solution to AoC 2016 Day 8 Part 1 import sys from typing import TypeAlias Display: TypeAlias = list[list[bool]] def rotate_row(row: int, shift: int, grid: Display) -> None: grid[row] = grid[row][-shift:...
Python
1
t_button.click() assert self.driver.find_element(By.ID, "wpforms-30-field_2-error").text == "Este campo es obligatorio." except AttributeError as e: print(f"AttributeError {e}") except Exception as e: print(f"Exception {e}") ''' def test_comprovarqueelformular...
Python
1
the page level */); self.next_table_mut(index).unwrap().zero(); } self.next_table_mut(index).unwrap() } fn next_table_address(&self, index: usize) -> Option<usize> { let entry_flags = self[index].flags(); if entry_flags.contains(PRESENT) && !entry_flags.contains(HUG...
Rust
0
# -*- coding: utf-8 -*- # Part of Odoo. See LICENSE file for full copyright and licensing details. from odoo import fields, models class ResCompany(models.Model): _inherit = 'res.company' recruitment_extract_show_ocr_option_selection = fields.Selection( selection=[ ('no_send', 'Do not di...
Python
1
_proof_ptr: ConstNipopowProofPtr, ) -> ErrorPtr { let res = nipopow_verifier_process(nipopow_verifier_ptr, nipopow_proof_ptr); Error::c_api_from(res) } /// Delete `NipopowVerifier` #[no_mangle] pub unsafe extern "C" fn ergo_lib_nipopow_verifier_delete(ptr: NipopowVerifierPtr) { delete_ptr(ptr) } #[no_mang...
Rust
0
final call using `doit()`. /// // Values shown here are possibly random and not representative ! /// let result = hub.users().data_sources_datasets_get("userId", "dataSourceId", "datasetId") /// .page_token("<PASSWORD>") /// .limit(-9) /// .doit(); /// # } /// ``` pub struct User...
Rust
0
mem::drop(lengths); mem::drop(pointers); } $( $opt )? fn read_buffer(&self, mode: GLenum) { #[cfg(feature = "debug")] { _gl_print_debug("glReadBuffer"); } #[cfg(feature = "error")] { _gl_check_for_last_error(self); } if self.glReadBuffer =...
Rust
0
> { /// //get the battery percentage somehow... /// Ok(100u8) //always fully charged /// } /// /// fn status(&self) -> Result<BatteryState, ReadoutError> { /// //check if battery is being charged... /// Ok(BatteryState::Charging) //always charging. /// } /// } /// ``` pub tra...
Rust
0
return self.mode_type.label class UserRegMixin(SQLModel): username: str = Field( ..., min_length=2, max_length=32, sa_type=String(32), title="用户名", unique=True, index=True, regex="^[a-z0-9\u4e00-\u9fa5]+$", schema_extra={"example": "s...
Python
1
# # 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 writing, software # ...
Python
1
=============================================== class BrainWallet: @staticmethod def generate_address_from_passphrase(passphrase): private_key = str(hashlib.sha256( passphrase.encode('utf-8')).hexdigest()) address = BrainWallet.generate_address_from_private_key(private_key) ...
Python
1
fn given_player_40_other_15_when_other_wins_then_score_is_40_30() { unimplemented!() } #[test] fn given_player_15_other_15_when_player_wins_then_score_is_30_15() { unimplemented!() } #[test] fn given_player_0_other_15_when_other_wins_then_score_is_0_30() { unimpleme...
Rust
0