text
string
label_name
string
labels
int64
'examples': examples_list, 'definitions_options': definitions_options } return render_template('recite.html', word_card=word_card, current_index=current_index, total_words=total_unmastered, ...
Python
1
hot::Query; use dropshot::RequestContext; use dropshot::TypedBody; use dropshot::UntypedBody; use dropshot::CONTENT_TYPE_JSON; use http::StatusCode; use hyper::Body; use hyper::Method; use hyper::Response; use schemars::JsonSchema; use serde::Deserialize; use serde::Serialize; use std::sync::Arc; use uuid::Uuid; #[mac...
Rust
0
return None; } self.block = block.unwrap().unwrap(); self.block_size = self.block.row_count(); } self.row_block_idx = 1; } Some(Self::row_to_obs(Row { block: &self.block, idx: self.row_blo...
Rust
0
.link_defaults()?; builder.add_host_component(wasi_outbound_http::OutboundHttpComponent)?; builder.add_host_component(outbound_redis::OutboundRedis)?; Ok(()) } } pub struct ExecutionOptions<T: Trigger> { log_dir: Option<PathBuf>, follow: FollowComponents, execution_config: T::Ex...
Rust
0
import unittest from quick_sort import quick_sort class TestQuickSort(unittest.TestCase): def test_quick_sort_ascending(self): data = [ {"name": "Alice", "age": 40}, {"name": "Bob", "age": 30}, {"name": "Charlie", "age": 25}, {"name": "David", "age": 35} ...
Python
1
scriber { message: String, _producer: Box<dyn Bridge<EventBus>>, } impl Component for Subscriber { type Message = Msg; type Properties = (); fn create(_props: Self::Properties, link: ComponentLink<Self>) -> Self { Self { message: "No message yet.".to_owned(), _produ...
Rust
0
: {"type": b"Z"}}}) r( b"NSObject", b"drawInMTKView:", {"required": True, "retval": {"type": b"v"}, "arguments": {2: {"type": b"@"}}}, ) r( b"NSObject", b"mtkView:drawableSizeWillChange:", { "required": True, "retval": {"type": b"v"}, ...
Python
1
lab = int(input("กรอกคะแนน Lab : ")) mid = int(input("กรอกคะแนน Midterm : ")) final = int(input("กรอกคะแนน Final : ")) x = int(lab+mid+final) if x <= 100 and x >= 80: print("คะแนนของคุณคือ "+str(x)+" ได้เกรด A") elif x <= 79 and x >= 70: print("คะแนนของคุณคือ "+str(x)+" ได้เกรด B") elif x <= 69 and x >= 60: ...
Python
1
ontextmanager def _acquire_lock(self): self._lock.acquire() try: yield finally: self._lock.release() def get_config(self) -> Config: with self._acquire_lock(): return self._config def set_config(self, cfg: Config) -> None: with se...
Python
1
=> $r:path),+ $(,)?) => { $( /// A wrapper over a shared-mutable type that forbids writing to the /// location through its own reference. Other references to the location /// may still write to it, and reads from this reference will be aware /// of this possibility. /// /// This is necessary in order to en...
Rust
0
if not self._closed: self._closed = True _original_os.close(self._fileno) notify_close(self._fileno) for method in [ 'fileno', 'flush', 'isatty', 'next', 'read', 'readinto', 'readline', 'readlines', 'seek', 'tell', 'truncate', ...
Python
1
import json import os import sys TOPOLOGY_TXT_PATH = "/home/ubuntu/digital-twin/rss/build/topology.txt" TOPOLOGY_JSON_PATH = "/home/ubuntu/digital-twin/topology.json" def start_mode(): # Delete topology.txt if it exists if os.path.exists(TOPOLOGY_TXT_PATH): os.remove(TOPOLOGY_TXT_PATH) # Load JSO...
Python
1
eFile", node: tree_sitter.Node) -> List[Scope]: scopes = [] node = node.parent while node is not None: st = sf.lang.scope_type(node) if st is not None: scopes.append(Scope.from_ts_node(st, node, sf)) if node.parent is None: scopes.append(Scope(ScopeType.FILE...
Python
1
k(Pid), /// seccomp event Seccomp(SyscallNo), /// XXX: internal only Syscall(SyscallNo), /// XXX: internal only VforkDone, /// exited Exited(Pid, i32), } /// Task which can be scheduled by `Sched` #[derive(Debug, Clone, PartialEq, Eq)] pub enum RunTask<Task> { /// `Task` Exited with...
Rust
0
for CortexMTarget { fn irq_setup(&self) { let peripherals = unsafe { Peripherals::steal() }; let mut syst = peripherals.SYST; syst.set_clock_source(SystClkSource::Core); syst.set_reload(8_000_000); syst.enable_counter(); syst.enable_interrupt(); } } <gh_stars>1...
Rust
0
import subprocess import sys from pathlib import Path from qmtl.interfaces.tools.taglint import ( REQUIRED_KEYS, RECOMMENDED_KEYS, apply_fixes, load_tags, validate_tags, ) def run(path: Path, fix: bool = False): args = [sys.executable, "-m", "qmtl", "taglint"] if fix: args.append(...
Python
1
, &mut self.index, &mut self.previous_value, ); } } impl DecrypterHalf { /// Tests whether both halves originate from the same /// [`HeaderCrypto`](crate::header_crypto::HeaderCrypto) /// and can be [`EncrypterHalf::unsplit`]. /// /// Same as [`EncrypterHalf::is_...
Rust
0
# coding=utf-8 # Copyright 2019 Google 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.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to ...
Python
1
ree::new_and_rebuild(MemoryReadonlyDataStorage::with_data(data.as_slice()), Default::default()).unwrap(); test::black_box(mt); }); } #[bench] fn n_x_0004_step_by_step_rust_siphash(b: &mut Bencher) { b.iter(|| { let mut mt: MerkleTree<MemoryDataStorage<&'static [u8]>, MemoryTreeStorage<DefaultH...
Rust
0
ad_only, ) with tab1: setting_editor( project_name, "settings.yaml", default_value=default_settings, language="yaml", read_only=read_only, ) with tab3: setting_editor( project_name, "prompts/c...
Python
1
ec![]; for block_index in start_index..end_index { match self.ledger.get_block(block_index as u64) { Ok(block) => block_entities.push(block), Err(mc_ledger_db::Error::NotFound) => { // This is okay - it means we have reached the last block in the l...
Rust
0
_mask_bytes; unsafe { set_bytes_vector_256(e31, e30, e29, e28, e27, e26, e25, e24, e23, e22, e21, e20, e19, e18, e17, e16, e15, e14, e13, e12, e11, e10, e9, e8, e7, e6, e5, e4, e3, e2, e1, e0) } } #[inline(always)] fn load_unaligned_bytes_vector(from_memory_address: NonNull<Self>) -> Self { unsafe { load_u...
Rust
0
dd iiiiiiii", "ADD %Rd, SP, #offset[i]", |arm, op| { arm.regs[op.reg3(8)] = arm.regs[REG_SP] + (op.imm8() << 2); } ), ("1011 0000 0iiiiiii", "ADD SP, #imm[i]", |arm, op| { arm.regs[REG_SP] += op.imm8() << 2; } ), ("1011 0000 1iiiiiii", "ADD SP, -#...
Rust
0
mo_get_copy( io: *mut zxio_t, out_vmo: *mut zx_handle_t, out_size: *mut usize, ) -> zx_status_t; } extern "C" { pub fn zxio_vmo_get_clone( io: *mut zxio_t, out_vmo: *mut zx_handle_t, out_size: *mut usize, ) -> zx_status_t; } extern "C" { pub fn zxio_vmo_ge...
Rust
0
:raises Exception: 工具在所有重试中均失败 """ if not self.session: raise RuntimeError(f"Server {self.name} not initialized") attempt = 0 while attempt < retries: try: logging.info(f"Executing {tool_name}...") result = await self.sessi...
Python
1
set relative to instruction_addresses emit_alu(jit, OperandSize::S64, 0x29, REGISTER_MAP[STACK_REG], REGISTER_MAP[0], 0, None)?; // RAX -= jit.program_vm_addr; if jit.config.enable_instruction_meter { // Calculate the target_pc to update the instruction_meter let ...
Rust
0
and self.loitering: self.get_logger().info(f"Loitering finished (offboard)") self.loitering = False # General function for publishing vehicle commands # Used to publish speed commands def publish_vehicle_command( self, command, param1, ...
Python
1
n\nThis register you can [`read`](crate::generic::Reg::read). See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [pintsmry](index.html) module"] pub struct PINTSMRY_SPEC; impl crate::RegisterSpec for PINTSMRY_SPEC { type Ux = u16; } #[doc = "`read()` method r...
Rust
0
import pytest from great_tables._text import ( BaseText, Text, Md, Html, _latex_escape, escape_pattern_str_latex, _process_text, ) def test_base_text_class(): with pytest.raises(NotImplementedError): BaseText().to_html() with pytest.raises(NotImplementedError): Ba...
Python
1
f.config.lr /= self.config.anneal_by print 'annealed lr to %f' % self.config.lr prev_epoch_loss = epoch_loss #save if model has improved on val if val_loss < best_val_loss: shutil.copyfile(SAVE_DIR + '%s.temp' % self.config.model_name, SAVE_DIR + '%s' % self.co...
Python
1
orch.tensor([[1985229328] * (IN // GROUPSIZE)] * (OUT // 8)).int().cuda() x = torch.tensor([[1.] * IN]).cuda() # q_weights = torch.randint(0, 100, (OUT, (IN // 8))).int().cuda() # q_scale = torch.rand( (OUT, (IN // GROUPSIZE))).float().cuda() # q_zeros = torch.randint(0, 100000, (OUT//8, (IN // GROUPSIZE))).int().cud...
Python
1
}) } } impl ::std::marker::Copy for AuthType { } impl ::std::default::Default for AuthType { fn default() -> Self { AuthType::undef } } impl ::protobuf::reflect::ProtobufValue for AuthType { fn as_ref(&self) -> ::protobuf::reflect::ReflectValueRef { ::protobuf::reflect::Reflec...
Rust
0
# # Copyright (c) 2023 Airbyte, Inc., all rights reserved. # from setuptools import find_packages, setup MAIN_REQUIREMENTS = [ "airbyte-cdk", ] TEST_REQUIREMENTS = [ "requests-mock~=1.9.3", "pytest~=6.2", "pytest-mock~=3.6.1", ] setup( entry_points={ "console_scripts": [ "so...
Python
1
while self.elems.len() < len { self.elems.push(Property::new_data_simple(Value::empty())) } return; } // Shorten if self.elems.len() > len { unsafe { self.elems.set_len(len) }; return; } } #[inline] pu...
Rust
0
= 0xF0FF; const HID_VENDOR_DEFINED_2: u16 = 0xF4FF; const HID_VENDOR_DEFINED_3: u16 = 0xF8FF; const HID_VENDOR_DEFINED_4: u16 = 0xFCFF; #[test] fn it_recognizes_afrikaans_as_afrikaans_language() { assert_eq!( super::from_lang_id(AFRIKAANS).primary_language(), Primary...
Rust
0
""" функция уравнения f(x) = x^2 - 2. вычисляет значение функции f(x) = x^2 - 2.""" def f(x): return x ** 2 - 2 def dichotomy_method(a, b, delta): # реализация метода дихотомии '''если поданы значения аргуменета (интервалов), при которых функция не меняет знак, то будет ошибка. т.е. на концах интерв...
Python
1
""" `sam docs` command """ # Expose the cli object here from .command import cli # noqa
Python
1
cept(mut stream: TcpStream, checks: Vec<Uuid>) -> std::io::Result<()> { let read_limit = std::env::var("GCTF_READ_LIMIT") .map(|s| s.parse().unwrap()) .unwrap_or(DEFAULT_READ_LIMIT); debug!("Accepted connection"); let bytes = (&stream).bytes().take(read_limit).map(|b| b.unwrap()); let c...
Rust
0
from btpg.algos.base.planning_action import PlanningAction def MakeCoffee(): actions=[ PlanningAction(name='Put(Table,Coffee)', pre={'Holding(Coffee)','At(Table)'}, add={'At(Table,Coffee)','NotHolding'}, del_set={'Holding(Coffee)'}, cost=1), PlanningAction(name='Put(Table,VacuumCup)', pre={'Hold...
Python
1
from .std import bars, brange from .gui import bars as bars_gui # TODO: remove in v5.0.0 from .gui import brange as tgrange # TODO: remove in v5.0.0 from ._bars_pandas import bars_pandas from .cli import main # TODO: remove in v5.0.0 from ._monitor import TMonitor, BarsSynchronisationWarning from ._version import __...
Python
1
TV", "two", "type", "under", "understand", "unit", "until", "up", "upon", "us", "use", "usually", "value", "various", "very", "victim", "view", "violence", "visit", "voice", "vote", "wait", "walk", "wall", "want", "war", "watch", "water", "way", "we", "weapon", "wear", "week", "weight", "well", "west", "wes...
Python
1
# -*- coding: utf-8 -*- { 'About': 'අප ගැන', 'About us': 'අප ගැන', 'Add strings manually through a text file': 'පෙළ ගොනුවකින් ඍජුවම අක්ෂර එකතු කරන්න', 'Administration': 'පරිපාලනය', 'Assets': 'වත්කම්', 'Change Password': 'මුරපදය වෙනස් කරන්න', 'City / Town / Village': 'නගරය / ගම්', 'Contact Details': 'ඇමතුම් විස්තර', 'Co...
Python
1
# -*- coding: utf-8 -*- # Copyright (c) 2017, Frappe Technologies Pvt. Ltd. and contributors # For license information, please see license.txt from __future__ import unicode_literals import frappe from frappe.model.document import Document class AssetMaintenanceTask(Document): pass
Python
1
from odoo import api, fields, models from datetime import datetime class ProjectTask(models.Model): _name = 'project.task' _inherit = ['mail.thread', 'mail.activity.mixin'] _description = 'Project Task' name = fields.Char(string='Task Name', required=True, tracking=True) project_id = fields.Many2...
Python
1
ath: lineedit.setText(path) def _browse_dir(self, lineedit: QLineEdit): path = QFileDialog.getExistingDirectory(self, "Select Folder", "") if path: lineedit.setText(path) def _check_updates_now_clicked(self): """Persist update settings, then ask the main window ...
Python
1
import os import time def shutdown(): os.system("shutdown /s /t 1") set_time = input("Shutdown After ----> ") set_time = int(set_time) sec = 60 print("Computer Will Now Shutdown in " + str(set_time) + " Minutes") time.sleep(set_time * sec) print("\n") print("Computer Will Now Shutdown!") time.sleep(3) shutdow...
Python
1
"FaultInfo {{ view: {:x}, addr: {:x}, flags: {:x} }}", self.view, self.addr, self.flags ) } } const OBJECT_READ: u64 = 1; const OBJECT_WRITE: u64 = 2; const OBJECT_EXEC: u64 = 4; const OBJECT_NOMAP: u64 = 8; const OBJECT_EXIST: u64 = 16; const OBJECT_INVALID: u64 = 32; const OBJECT_UNKNOWN: u64 = 64; const O...
Rust
0
url", return_value=state): next_url = handler.get_next_url() assert next_url == "some url" async def test_lti13_callback_handler_get_next_url_returns_user_default_url( req_handler, ): """Test invokation of parameter, token and state validation.""" state = _serialize_state(dict(other_stuff="som...
Python
1
import torch from PIL import Image from diffsynth import save_video, VideoData from diffsynth.pipelines.wan_video_new import WanVideoPipeline, ModelConfig from modelscope import dataset_snapshot_download pipe = WanVideoPipeline.from_pretrained( torch_dtype=torch.bfloat16, device="cuda", model_configs=[ ...
Python
1
be_from_list" class="btn btn-link">Unsubscribe</a> </div> </p>''', 'preview': 'Preview {{ object.name }}', 'subject': 'Subject {{ object.name }}', }) with self.mock_mail_gateway(): mailing_test.send_mail_test() body_html =...
Python
1
# -*- coding: utf-8 -*- # Copyright (c) 2025, PT. Innovasi Terbaik Bangsa and contributors # For license information, please see license.txt import frappe def account_on_update(doc, method=None): """Hook when accounts are updated""" try: if doc.account_type in ["Payable", "Expense", "Liability"] and ...
Python
1
ontext['recent_patterns']['moods_count']} entries - Energy levels: {', '.join(context['recent_patterns']['energy_levels'][:3])} - Focus areas: {', '.join(context['recent_patterns']['focus_areas'][:3])} - Accomplishments: {', '.join(context['recent_patterns']['accomplishments'][:3])} ANALYSIS REQUEST: Provide a persona...
Python
1
warnings.warn("%s fileds are useless." % ",".join(memeber_set)) class EcgDescription(AbstractModel): r"""心电图详情 """ def __init__(self): r""" :param _HeartRate: 心率 :type HeartRate: :class:`tencentcloud.mrs.v20200910.models.EcgItem` :param _AuricularRate:...
Python
1
err.into()) } } } #[pyimpl(flags(BASETYPE))] impl PySocket { #[pyslot] fn slot_new(cls: PyTypeRef, _args: FuncArgs, vm: &VirtualMachine) -> PyResult { Self::default().into_pyresult_with_type(vm, cls) } #[pymethod(magic)] fn init( ...
Rust
0
c<'a, Lbl> { fn new<Loc: Copy>(e: &'a BorrowEdge<Loc, Lbl>) -> Self { BorrowEdgeNoLoc { strong: e.strong, path: &e.path, } } } impl<Loc: Copy, Lbl: Clone + Ord> PartialEq for BorrowEdge<Loc, Lbl> { fn eq(&self, other: &BorrowEdge<Loc, Lbl>) -> bool { BorrowEd...
Rust
0
from .default_styles import DEFAULT_STYLES from .theme import Theme DEFAULT = Theme(DEFAULT_STYLES)
Python
1
proof.verify(proof_spec, None).unwrap(); total_verify += start.elapsed(); } println!( "Time taken for {} iterations and {} chunk size:", count, chunk_bit_size ); println!("Proving {:?}", total_prove); println!("Verifying {:?}", total_verify); ...
Rust
0
vm_allocator::GLOBAL_VM_ALLOC.cur_pool_remain() < 3072 { use rustyl4api::vspace::{Permission, FRAME_SIZE}; let addr = GLOBAL_SPACEMAN .map_frame_at(0, 0, FRAME_SIZE, Permission::writable()) .unwrap(); crate::vm_allocator::GLOBAL_VM_ALLOC.add_mempool(addr, FRAME_SIZE); ...
Rust
0
nx.invoke("Min", &args).map_err(Error::from)?; if let Some(e) = result.error() { bail!("{}", e); } result.get_node("clip").map_err(Error::from) } pub(crate) struct Max<'core> { pub clip1: Node<'core>, pub clip2: Node<'core>, } impl<'core> Filter<'core> for Max<'core> { fn video_info(&s...
Rust
0
from odoo import fields, models, _ PROCESSING_RESULTS = [ ('accepted', _('Accepted')), ('declined', _('Declined')) ] class TaskStage(models.Model): _inherit = 'task.stage' processing_result = fields.Selection(PROCESSING_RESULTS, string='Processing Result', copy=True)
Python
1
pub mod propagate; pub mod reduce_db; pub mod search; pub mod simplify_db; pub mod solve; // Copyright 2014 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APAC...
Rust
0
The Starcoin Core Contributors // SPDX-License-Identifier: Apache-2.0 use super::mock_star_node::{setup_environment, StarHandle}; use admission_control_proto::proto::admission_control::{ AdmissionControlClient, SubmitTransactionRequest, SubmitTransactionResponse, }; use admission_control_service::admission_contro...
Rust
0
::RED)), pixel_type: <$prim as ScalarBase>::GL_ENUM, }; } )*} } basic_format! { u8, Normalized = (RGBA8, RGB8, RG8, R8); u16, Normalized = (RGBA16, RGB16, RG16, R16); i8, Normalized = (RGBA8_SNORM, RGB8_SNORM, RG8_SNORM, R8_SNORM); i16, Normalized = (RGBA16_SNOR...
Rust
0
ControlNetのサンプルはcv2を使っているが、読み込みはGradioなので実はRGBになっている # image = image[:, :, ::-1].copy() # rgb to bgr image = image[None].transpose(0, 3, 1, 2) # nchw image = torch.from_numpy(image) return image # 0 to 1 def get_guided_hints(control_nets: List[ControlNetInfo], num_latent_inpu...
Python
1
let stretched_floor = stretched.floor_to_isize().numcast().unwrap(); // Skew out to get actual coordinates of stretched rhombo-hypercube origin. // We'll need these later. let squish_offset = stretched_floor.sum() * SQUISH_CONSTANT; let origin = stretched_floor.map(|v| v + squish_offset); // C...
Rust
0
y: [PointLight; 4], // } pub struct DemoWindow { pub events: EventsLoop, pub display: Display, pub input: InputState, view: M4x4, pub camera: Pose, pub hemilight_intensity: f32, // pub lit_shader: glium::Program, // pub solid_shader: glium::Program, // pub tex_shader: glium::Progr...
Rust
0
{ let mut stream_err = TcpStream::connect(&self.connection); match stream_err { Ok(mut stream) => { stream.write_all(&ti(READ)); send_tuple(tuple, &mut stream); stream.shutdown(Shutdown::Write); return Ok(recv_tuple(&mut stream)); } Err(why) => { return Err(why); } ...
Rust
0
#Space Invaders - Part 3 #Create the Enemy and move left / right / down #Python 2.7 on Mac import turtle import os #Set up the screen wn = turtle.Screen() wn.bgcolor("black") wn.title("Space Invaders") #Draw border border_pen = turtle.Turtle() border_pen.speed(0) border_pen.color("white") border_pen.penup() border_pe...
Python
1
onfig: ClientConfig, device: Device, buf_provider: BufferProvider, scheduler: Scheduler, cpp_chan_sched: CppChannelScheduler, ) -> Self { // TODO(41417): Remove this once devmgr installs a Rust logger. logger::install(); let iface_mac = device.wlan_info().ifc...
Rust
0
(3.0, 2.0, "baz"), Item::new(1.0, 4.0, "qux")]; sort_by_axis(Axis::Longitude, &mut items); let actual = items.iter() .map(|n| n.value); assert!(actual.eq(vec!["bar", "baz", "foo", "qux"])); } fn cmp_by_latitude<T: Copy>(a: &Item<T>, b: &Item<T>) -> Ordering ...
Rust
0
if let rustc_ast::ast::LitKind::Int(10, _) = lit.node; then { let expr = if let ExprKind::AddrOf(_, _, expr) = &arguments[0].kind { let ty = cx.typeck_results().expr_ty(expr); if is_ty_stringish(cx, ty) { expr ...
Rust
0
loop { for k in node.as_ref().prefix() { key_tracker.push(*k); } let child_node = node.as_ref().get_random_child(rng); node.check_version()?; let (k, child_node) = match child_node { Some(n) => n, None => ...
Rust
0
($arg:tt)*) => {}; } #[cfg(feature = "logging")] #[macro_export] macro_rules! log_warn { ($($arg:tt)*) => ( $crate::log::warn!($($arg)*) ) } #[cfg(not(feature = "logging"))] #[macro_export] macro_rules! log_warn { ($($arg:tt)*) => {}; } #[cfg(feature = "logging")] #[macro_export] macro_rules! log...
Rust
0
c = "Bit 1 - SYS - Incoming JTAG Mailbox 1 Flag"] #[inline(always)] pub fn jmbin1fg(&self) -> JMBIN1FG_R { JMBIN1FG_R::new(((self.bits >> 1) & 0x01) != 0) } #[doc = "Bit 2 - SYS - Outgoing JTAG Mailbox 0 Flag"] #[inline(always)] pub fn jmbout0fg(&self) -> JMBOUT0FG_R { JMBOUT0FG_...
Rust
0
from unittest import TestCase import simplejson.encoder CASES = [ (u'/\\"\ucafe\ubabe\uab98\ufcde\ubcda\uef4a\x08\x0c\n\r\t`1~!@#$%^&*()_+-=[]{}|;:\',./<>?', '"/\\\\\\"\\ucafe\\ubabe\\uab98\\ufcde\\ubcda\\uef4a\\b\\f\\n\\r\\t`1~!@#$%^&*()_+-=[]{}|;:\',./<>?"'), (u'\u0123\u4567\u89ab\ucdef\uabcd\uef4a', '"\\u0...
Python
1
# This set of code was honestly just me attempting to get a handle on python, # and using that knowledge for basic sprite changes import thumby from sys import path if not '/Games/CharTest' in path: path.append( '/Games/CharTest' ) import displaymanager import inputmanager # BITMAP: width: 8, height: 8 catMap...
Python
1
def grab_wildcard_values(wildcard_option_dict: Dict[str, List[str]]={}, wildcard_files: List[str]=[]): for wildcard_file in wildcard_files: filename = get_filename(wildcard_file) read_values = read_wildcard_values(wildcard_file) if filename not in wildcard_option_dict: wildca...
Python
1
('validation') as scope: correct_prediction = tf.equal(tf.argmax(predict_label, axis=1), tf.argmax(true_label, axis=1)) accuracy = tf.reduce_mean(tf.cast(correct_prediction, 'float')) # ---------------------------------------- train --------------------------------------------- # with tf.Sessio...
Python
1
box=pks[j].copy() if min(box[2],box[1],e["nx"]-box[2],e["ny"]-box[1])<options.edge+options.boxsz//2: continue if "apix_unbin" in js: box=(box-shp/2)*apix/apix_unbin allbox3d.append([box[2], box[1],int(box[0]), "tomoseg", float(np.round(pkscore[j],3)), mytag]) if "boxes_3d" in js: b3d=js["boxes_3d"] ...
Python
1
ey(a): return a.lower() def sortListInsensitive(l): try: # Try key function l.sort(key=ciKey) except TypeError: # Earlier version of Python, so use comparison function l.sort(ciCompare) def RegenerateAll(): root="../../" # Find all the lexer source code files lexFilePath...
Python
1
]) { None => return None, Some(x) => x, }; Some(Self { public_key, level: level as usize, }) } } #[cfg(test)] mod tests { use rand::{rngs::OsRng, RngCore}; use crate::util::helper::test_helper::gen_random_seed; use crate::{ ...
Rust
0
class ListNode: def __init__(self, val=0, next=None): self.val = val self.next = next class Solution(object): def mergeTwoLists(self, list1, list2): #starting point of the merged list dummy = ListNode(0) current = dummy # two pointers for list1 and list...
Python
1
ros(num_samples, np.float32) log_rms = np.zeros(num_samples, np.float32) abs_rel = np.zeros(num_samples, np.float32) sq_rel = np.zeros(num_samples, np.float32) d1_all = np.zeros(num_samples, np.float32) a1 = np.zeros(num_samples, np.float32) a2 = np.zeros(num_samples, np.float32) ...
Python
1
import argparse from collections import defaultdict from boto3 import resource parser = argparse.ArgumentParser() parser.add_argument("--bucket", type=str, required=True) parser.add_argument("--region", type=str, required=True) args = parser.parse_args() ROOT_URL = f"https://{args.bucket}.s3.{args.region}.amazonaws....
Python
1
l[Dict] = None): self.log(LogLevel.SUCCESS, module, message, data) def warning(self, module: str, message: str, data: Optional[Dict] = None): self.log(LogLevel.WARNING, module, message, data) def error(self, module: str, message: str, data: Optional[Dict] = None): self.log(LogL...
Python
1
nput_IMU_0, input_IMU_x, input_IMU_y, input_IMU_z), axis=-1) # [N_frame, 12] ##################### Augumentation using diff ##################### diff_interval = config["PRE_PROCESS"]["INPUT_IMU_DIFF_INTERVAL"] if diff_interval is not None and diff_interval > 0: input_IMU_diff = np.concaten...
Python
1
ate of the object. /// /// # Important Disclaimer /// This is primarily intended for library maintainers. The internal representation of a /// `Decimal` is considered "unstable" for public use. /// /// # Example /// /// ``` /// use rust_decimal::Decimal; /// use core::str::FromSt...
Rust
0
"""Forward-backward consistency loss for optical flow.""" def fb_consistency_loss(flow_fwd, flow_bwd): """ Compute forward-backward consistency loss between flow fields. Args: flow_fwd: forward flow tensor. flow_bwd: backward flow tensor. Returns: scalar loss """ # TOD...
Python
1
ting buffer, using pixel masks. pub fn from_data_pixelmasks(data: &'a mut [u8], width: u32, height: u32, pitch: u32, masks: pixels::PixelMasks) -> Result<Surface<'a>, String> { unsafe { if width >= (1<<31) || height >= (1<<31) { Err("Image is too large.".to_owned()) }...
Rust
0
x7F, 0xE3, 0x97, 0x3E, 100} DEFINE_PROPERTYKEY!{PKEY_Calendar_ReminderTime, 0x72FC5BA4, 0x24F9, 0x4011, 0x9F, 0x3F, 0xAD, 0xD2, 0x7A, 0xFA, 0xD8, 0x18, 100} DEFINE_PROPERTYKEY!{PKEY_Calendar_RequiredAttendeeAddresses, 0x0BA7D6C3, 0x568D, 0x4159, 0xAB, 0x91, 0x78, 0x1A, 0x91, 0xFB, 0x71, 0xE5, 100} DEFINE_PROPER...
Rust
0
players_stats = [] players_stats.append({"name": "Aaron Judge", "Games": 123, "Home Runs": 44}) players_stats.append({"name": "Juan Soto", "Games": 121, "Home Runs": 34}) players_stats.append({"name": "Bobby Witt", "Games": 124, "Home Runs": 25}) players_stats.append({"name": "Shohei Ohtani", "Games":122, "Home Runs":...
Python
1
eady checked it. # If not, write us into that spot. neighbour = join_points.setdefault( (over_name, round(point, 0).freeze()), seg, ) if neighbour is seg: # None found continue overlay_joins[neigh...
Python
1
settings), }; ctx.notify(notification::DidChangeConfiguration::METHOD.into(), params); } pub fn workspace_symbol(meta: &EditorMeta, params: EditorParams, ctx: &mut Context) { let req_params = WorkspaceSymbolParams::deserialize(params.clone()); if req_params.is_err() { error!("Params should foll...
Rust
0
PT + f"\n\nCurrent hog code:\n{hog_code}" + f"\nCurrent inputs schema:\n{current_inputs_schema}" + "\n\n<input_schema_types>\n" + INPUT_SCHEMA_TYPES_MESSAGE + "\n</input_schema_types>" ) user_content = f"Create or modify the input variables fo...
Python
1
1/1B6/1P2K3/P7/5RPP/ b - - 0 28", "r1bqkbnr/ppppppp1/n7/3P2p1/Q4P2/2P5/PP2P1PP/RN2KBNR b KQkq - 2 6", "3rk2r/pppb3p/2n1p3/1B6/3bP3/P4P2/3N2PP/4K2R b Kk - 0 22", "rn2kb1r/1ppqpbpp/5n2/p3Q3/8/PP1P4/1BPP1PPP/R2NKB1R b KQkq - 3 13", "r2qkbnr/ppp1Bppp/2n5/3p1b2/3P4/2N5/PPP1PPPP/R2QKBNR b KQkq - 0 4", "r3...
Rust
0
# Calcule perimetro y superficie de un rectangulo """ Elaborar un algoritmo talque dado como datos la base y la altura de un rectángulo, que calcule e imprima su perímetro y su superficie """ b = float(input("Ingrese la base de el rectangulo: ")) h = float(input("Ingrese la altura de el rectangulo: ")) perimetro =...
Python
1
OUT` endpoint."] pub mod out_status; #[doc = "\n\nThis register you can [`read`](crate::generic::Reg::read), [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`write_with_zero`](crate::generic::Reg::write_with_zero), [`modify`](crate::generic::Reg::modify). See [API](https://docs.rs/svd2rus...
Rust
0
0, 0.0, 70.0]); // sum in output lane 3 let c = dot_product_m128::<0b1111_1111>(a, b).to_array(); assert_eq!(c, [70.0, 70.0, 70.0, 70.0]); // sum in all output lanes } #[test] fn test_extract_i32_imm_m128i() { let a = m128i::from([5, 6, 7, 8]); assert_eq!(extract_i32_imm_m128i::<1>(a), 6); } use crate::ctx::C...
Rust
0
persize': 'letterpaper', # The font size ('10pt', '11pt' or '12pt'). # # 'pointsize': '10pt', # Additional stuff for the LaTeX preamble. # # 'preamble': '', # Latex figure (float) alignment # # 'figure_align': 'htbp', } # Grouping the document tree into LaTeX files. List of tuple...
Python
1
h.delete(i); } }); } #[bench] fn bench_set_1000_rand(b: &mut Bencher) { let mut h = HashTableLinked::new_size(10000); let mut rng = rand::thread_rng(); let mut vals: Vec<usize> = vec![]; for _ in 0..1000 { vals.push(rng.gen_r...
Rust
0