text
string
label_name
string
labels
int64
c.iter()).collect(), } } } /// Iterator for Waveform structure. #[derive(Debug, Clone)] pub struct WaveformIterator<'a, BitDepth: Clone> { inner: &'a Waveform<BitDepth>, iters: Vec<WaveIterator<'a>>, } impl<'a, BitDepth: Bounded + NumCast + AsPrimitive<f32>> Iterator for WaveformIterator<'a, ...
Rust
0
{ use tfs::ItemQueries; let now = Utc::now(); let prev = now - Duration::days(30); let start = prev.timestamp() as u64; let end = now.timestamp() as u64; let mut tx = db.begin()?; let total_items = tx.scan::<Item>()?.count(); log::debug!( "looking up items between {} and {}. tot...
Rust
0
def get_model_name_from_path(model_path): model_path = model_path.strip('/') model_paths = model_path.split('/') if model_paths[-1].startswith('checkpoint-'): return model_paths[-2] + '_' + model_paths[-1] else: return model_paths[-1]
Python
1
import torch import torch.nn as nn import torch import torch.nn as nn import torch.nn.functional as F import torch import torch.nn as nn import torch.nn.functional as F class SimpleTransformer(nn.Module): def __init__(self, vocab_size=4, d_model=8, num_heads=2, max_len=16): super().__init__() sel...
Python
1
Error during comprehensive test: {str(e)}" print(error_msg) results['errors'].append(error_msg) traceback.print_exc() return results def main(): ticker = sys.argv[1] if len(sys.argv) > 1 else 'AMD' days_back = int(sys.argv[2]) if len(sys.argv) > 2 else 30 print("DATA RETRIEVAL...
Python
1
t view: [[f32; 4]; 4] = Matrix4::identity().into(); (orthographic, view) }; // let scales = image_data.dim_scales; program.set_uniform("model", model); program.set_uniform("view", view); program.set_uniform("projection", projection); program.set_uniform("tex",...
Rust
0
-> Self { PushAlignment::new(max(self.0, o)) } } /// Macro to implement Push for EndianScalar types. macro_rules! impl_push_for_endian_scalar { ($ty:ident) => { impl Push for $ty { type Output = $ty; #[inline] fn push(&self, dst: &mut [u8], _rest: &[u8]) { ...
Rust
0
ring_inner > 0: th = self.roll x = cx + math.cos(th) * r y = cy - math.sin(th) * r p.setPen(QPen(QColor(120, 120, 120), 3)) p.drawLine(int(x), int(y), int(cx + math.cos(th) * (r - 10)), int(cy - math.sin(th) * (r - 10))) inner = QRect(int(cx - ring_i...
Python
1
notify_show_default_trampoline::<F> as *const (), )), Box_::into_raw(f), ) } } #[doc(alias = "show-fallback")] pub fn connect_show_fallback_notify<F: Fn(&Self) + 'static>(&self, f: F) -> SignalHandlerId { unsafe extern "C" fn notify_show_fallb...
Rust
0
type_vlen, FuncInfo, LineInfo, }; pub(crate) const MAX_RESOLVE_DEPTH: u8 = 32; pub(crate) const MAX_SPEC_LEN: usize = 64; /// The error type returned when `BTF` operations fail. #[derive(Error, Debug)] pub enum BtfError { /// Error parsing file #[error("error parsing {path}")] FileError { /// file...
Rust
0
32 }; // gap open score: -5, gap extension score: -1 let mut aligner = Aligner::with_capacity( forward_consensus.len(), reverse_consensus.len(), -5, -1, &score, ); let alignment = aligner.semiglobal(&forward_consensus, &reverse_...
Rust
0
ss, [1, t0, rsp], "1 * -env.dataSize", addressSize=ssz st rcx, ss, [1, t0, rsp], "2 * -env.dataSize", addressSize=ssz st rdx, ss, [1, t0, rsp], "3 * -env.dataSize", addressSize=ssz st rbx, ss, [1, t0, rsp], "4 * -env.dataSize", addressSize=ssz st rsp, ss, [1, t0, rsp], "5 * -env.dataSize", addressSize=s...
Python
1
: Arc<MetaContext>, ) -> CompilationResult<QueryPlan>; } pub struct SqlAuthDefaultImpl { transport: Arc<dyn TransportService>, } crate::di_service!(SqlAuthDefaultImpl, [SqlService]); #[async_trait] impl SqlService for SqlAuthDefaultImpl { async fn plan( &self, query: &String, stat...
Rust
0
from pathlib import Path from typing import Literal WORKBENCH_NAME = "Assembly2MuJoCo" ########################################## # Paths ########################################## ROOT_DIR = Path(__file__).parents[2].resolve() RESOURCES_DIR = ROOT_DIR / "resources" ICONS_DIR = RESOURCES_DIR / "icons" WORKBENCH_ICON...
Python
1
assert_eq!(consumed_tokens, 10); Ok(()) } } // TODO these are took from tokio and adapted to our delay use std::time::Duration; mod error; mod delay; pub(crate) mod delay_queue; pub(crate) mod wheel; pub(crate) use error::Error; enum Round { Up, Down, } /// Convert a `Duration` to mill...
Rust
0
from django.apps import AppConfig class WorkingcodeConfig(AppConfig): default_auto_field = "django.db.models.BigAutoField" name = "workingcode"
Python
1
from itertools import permutations def tuples_sum(nbval,total,order=True) : """ Generate all the tuples L of nbval positive or nul integer such that sum(L)=total. The tuples may be ordered (decreasing order) or not """ if nbval == 0 and total == 0 : yield tuple() ; raise StopItera...
Python
1
= Cursor::new(&buf); let s: LitStr = cur.parse()?; if !cur.eof() { let _: Comma = cur.parse()?; } let (args, _) = Punctuated::parse_separated(cur.cur)?; let tuple = Expr::Tuple(ExprTuple { attrs: Vec::new(), paren_token: Paren(Span::call_site()), elems: args, ...
Rust
0
deps( &ConnectivityStrategy::Offline, deps, pkg_id.clone(), version, ) .or_else(|_| { solve_deps( &ConnectivityStrategy::Online(VersionStrategy::Newest), deps, pkg_id, version, ...
Rust
0
, USB1_HOST_A>); impl USB1_HOST_R { #[inline(always)] pub(crate) fn new(bits: bool) -> Self { USB1_HOST_R(crate::FieldReader::new(bits)) } #[doc = r"Get enumerated values variant"] #[inline(always)] pub fn variant(&self) -> USB1_HOST_A { match self.bits { false => USB...
Rust
0
let bounds = geoms.get(0).map(|g| g.bounds()).unwrap_or_default(); geoms .iter() .map(Bounds::bounds) .fold(bounds, |a, b| AABB::union(&a, &b)) } fn sorted_markers<'a, I, G>(geoms: I, dimension: usize) -> Vec<Marker> where I: Iterator<Item = &'a G>, G: Bounds + 'a, { let co...
Rust
0
LE_GIC: u32 = 1; pub const AARCH64_FDT_MAX_SIZE: u64 = 0x200000; // This indicates the start of DRAM inside the physical address space. pub const AARCH64_PHYS_MEM_START: u64 = 0x80000000; // This is the base address of MMIO devices. pub const AARCH64_MMIO_BASE: u64 = 1 << 30; const AARCH64_AXI_BASE: u64 = 0x4000000...
Rust
0
def list_bool_base_copy(input_list): return ( 'print(' + input_list + ')' ) def list_bool_multiplier_random(input_list, n): n -= 1 n_1 = n // 2 n_2 = n - n // 2 assert n_1 + n_2 == n return ( 'print([bool(random.getrandbits(1)) for x in ['...
Python
1
if let Some(&(_, c)) = parents.get(&node) { if cost > c { continue; } } for (neighbour, move_cost) in neighbours(&node) { let old_cost = parents.get(&neighbour).map(|&(_, c)| c); let new_cost = cost + move_cost; if neighbour != *start && old_cost.map_or(true, |c| new_cost <...
Rust
0
-> Datetime, updated_at -> Datetime, } } allow_tables_to_appear_in_same_query!(forum_posts, forum_topics,); <reponame>xpeerchain/xpeerchain // Copyright (c) The XPeer Core Contributors // SPDX-License-Identifier: Apache-2.0 use super::TrustedPeersConfigHelpers; #[test] fn generate_test_config() { le...
Rust
0
// public static final [KEY_MMS_ALIAS_ENABLED_BOOL](https://developer.android.com/reference/android/telephony/CarrierConfigManager.html#KEY_MMS_ALIAS_ENABLED_BOOL) pub const KEY_MMS_ALIAS_ENABLED_BOOL : &'static str = "aliasEnabled"; /// public static final [KEY_MMS_ALIAS_MAX_CHARS_INT](https://develop...
Rust
0
import hashlib import logging from datetime import datetime from datetime import timedelta import jwt from psycopg2.extras import DateTimeRange from pcapi.core.educational import exceptions from pcapi.core.educational import models from pcapi.core.educational.constants import COLLECTIVE_OFFER_DISPLAYED_STATUS_LABELS ...
Python
1
f row.row_type == RowType.Stator: row.alpha2[index] = np.radians(exit_angle) stator_calc(row,upstream,downstream) upstream = compute_gas_constants(upstream,fluid) row = compute_gas_constants(row,fluid) elif row.loss_function.loss_type == LossType.Enthalpy:...
Python
1
#!/usr/bin/python import numpy as np import cvxpy as cvx from qcqp import * n = 25 np.random.seed(1) # Make adjacency matrix. p = 0.2 W = np.asmatrix(np.random.uniform(low=0.0, high=1.0, size=(n, n))) for i in range(n): W[i, i] = 1 for j in range(i+1, n): W[j, i] = W[i, j] W = (W < p).astype(float) x...
Python
1
) small numbers, by XORing with a fixed /// pointer that is also on the heap. This should make the most /// significant bits of the resulting u64 be zero, which will mean /// that `Set64` (which is space-efficient in storing small integers) /// can store this result in fewer than 8 bytes. impl<T: Debug> Fits64 for Loc...
Rust
0
#!/usr/bin/env python3 import time from confluent_kafka import Producer, Consumer, KafkaError def test_api_compatibility(): print("=== Testing API version compatibility ===") topic = f'test-api-version-{int(time.time() * 1000)}' producer = Producer({ 'bootstrap.servers': '127.0.0.1:9092', ...
Python
1
import json character_list = {} skin_list = [] with open("aliricia_format.txt","r") as original_data: """ We need to grab the data in 2 different lists. One for the character 4 letter character id in the parent list and all the skins trimmed in a different list. The parents always start with `**` so w...
Python
1
Err(e) => { println!("Error in update container desired: {:#?}", e); } } } } if workload.action_id != None { let result = self.crud.delete_action(&workload.base.p().zone, "workload", "replica-controller", workload.action_id.u...
Rust
0
import json import logging from urllib.parse import urlparse from ..common import Episode, open_url from datetime import datetime # ex: https://douga.tv-asahi.co.jp/program/24583-24582/24590?auto=t def asahi_extractor(url): logging.info("asahi_extractor is called") urlData = urlparse(url) urlPath = urlData...
Python
1
# Atividade 03: # Tabuada de um Número: # Faça um programa que solicite um número ao usuário e use # um laço while para exibir a tabuada desse número (de 1 a 10). x = 0 n = 0 while n < 10: n += 1 res x * n print(f'{x} x {n} = {res}')
Python
1
: ConsumeMode); // The value found at `borrow` is being borrowed at the point // `borrow_id` for the region `loan_region` with kind `bk`. fn borrow(&mut self, borrow_id: ast::NodeId, borrow_span: Span, cmt: mc::cmt, loan_region: ty::Region, ...
Rust
0
ARTITION_SIZE), head_dim], Mid_O_LogExpSum: [batchs, num_heads, cdiv(seq_len, PARTITION_SIZE)] PARTITION_SIZE, ): BLOCK_N_SIZE = 32 BLOCK_DMODEL = q.shape[-1] assert PARTITION_SIZE % BLOCK_N_SIZE == 0, ( "PARTITION_SIZE 必须是 BLOCK_N_SIZE 的倍数" ) batchs, num_heads, head_dim = q.shape s...
Python
1
AlreadyClosed)?; Ok(()).into() } } } impl std::convert::TryFrom<web_sys::MessageEvent> for crate::Message { type Error = crate::Error; fn try_from(event: MessageEvent) -> Result<Self, Self::Error> { match event.data() { payload if payload.is_instance_of::<js_sys::Ar...
Rust
0
_os_str))] output: PathBuf, } impl Generate { fn run(self) -> anyhow::Result<()> { let fixtures = generators::make_abi_test_fixtures()?; for Fixture::ABI { name: file_name, fixture, } in fixtures { let output_path = { let mut ...
Rust
0
.get::<cargo::util::config::StringList>("build.rustflags") .unwrap() .as_slice(), ["--file", "--cli"] ); // With normal env. let config = ConfigBuilder::new() .env("CARGO_BUILD_RUSTFLAGS", "--env1 --env2") .config_arg("build.rustflags = ['--cli']")...
Rust
0
import os from datetime import datetime, timedelta from pydantic import BaseModel, IPvAnyAddress class Settings(BaseModel): """ Класс настроек, который используется для загрузки конфигурации из переменных окружения. **Атрибуты:** - `trusted_ips`: Список доверенных IP-адресов, получаемых из переменно...
Python
1
:guard::{unprotected, Guard}; cfg_if! { if #[cfg(feature = "std")] { #[macro_use] extern crate lazy_static; mod default; pub use self::default::{default_collector, is_pinned, pin}; } } <filename>src/entropy.rs // (c) 2021 <NAME> (<EMAIL>) // //! Entropy module for //! Candle Au...
Rust
0
import streamlit as st import os from src.langgraphagenticai.ui.uiconfigfile import Config class LoadStreamlitUI: def __init__(self): self.config=Config() self.user_controls={} def load_streamlit_ui(self): st.set_page_config(page_title= "🤖 " + self.config.get_page_title(), layout="wi...
Python
1
::ecdsa::VerifyingKey { fn from_bytes(bytes: PublicKeyBytes) -> Result<Self> { Ok(k256::ecdsa::VerifyingKey::from_sec1_bytes(&bytes)?) } fn to_bytes(&self) -> PublicKeyBytes { self.to_bytes() .as_slice() .try_into() .expect("malformed key") } fn ...
Rust
0
from tkinter import * from AllFunctions import * from PIL import ImageTk, Image def reg(): def insert(): if(fname.get()!="" and lname.get()!="" and uname.get()!="" and pwd.get()!=""): regUser(fname.get(), lname.get(), uname.get(), pwd.get()) fname.delete(0, END) lname.de...
Python
1
domain_list_state.select(Some(0)); loop { terminal.draw(|screen| { let main_panes = Gui::render_panes(screen.size()); let tabs_widget = Gui::render_tabs(&menu_titles, active_menu_item.into()); let copyright_widget = Gui::render_copyright(); screen.render...
Rust
0
h open(os.path.join(outputDir, "README.md"), "w") as ctf_readme: logger.info("Writing main CTF readme...") ctf_readme.write("# %s\n\n" % ctfName) ctf_readme.write("## About\n\n[insert description here]\n\n") ctf_readme.write("## Challenges\n\n") for category in categories: ...
Python
1
or_aes_local') local_file_md5 = None content_md5 = None with open('test_for_aes_local', 'rb') as f: local_file_md5 = get_raw_md5(f.read()) content_md5 = get_raw_md5(content.encode("utf-8")) assert local_file_md5 and content_md5 and local_file_md5 == content_md5 if os.path.exists('test_fo...
Python
1
id: Self::ID.as_ptr() as *const i8, name: EMPTY.as_ptr() as *const i8, vendor: EMPTY.as_ptr() as *const i8, url: EMPTY.as_ptr() as *const i8, manual_url: EMPTY.as_ptr() as *const i8, version: EMPTY.as_ptr() as *const i8, description: EMPTY.as_ptr() as *const i8, k...
Rust
0
import user_executable import random import argparse from user_parameter_study import ParameterStudy as ParameterStudy def pi_work_items(ps, num_points): for i in range(num_points): x = (2 * random.random()) - 1 y = (2 * random.random()) - 1 ps.add_work_item([x, y]) def in_circle(x, y): ...
Python
1
buf_reader.read_to_string(&mut contents)?; // load geo data into fences table fences::load_geo_data(&pool, &contents)?; Ok(()) } // Kicks off populating all tables in main database and updating user // with visual progress bar along the way fn populate_all(row_count: u32) -> Result<(), Box<dyn Error...
Rust
0
} impl BackEndTx { pub async fn web_socket_output_async(&mut self) -> Option<Vec<u8>> { timeout(std::time::Duration::from_millis(200), self.receiver.next()) .await .unwrap_or(None) } pub fn web_socket_output(&mut self) -> Option<Vec<u8>> { executor::block_on(self.w...
Rust
0
-> bool { self.contains_three_vowels() & self.has_repeated_letter() & self.has_no_forbidden_combos() } fn is_nicer(&self) -> bool { self.has_repeated_pair_without_overlap() & self.contains_repeat_with_one_letter_between() } fn contains_three_vowels(&self) -> bool { self.0 ...
Rust
0
import logging import os from flask_sqlalchemy import SQLAlchemy from flask_migrate import Migrate from logging.handlers import RotatingFileHandler # init SQLAlchemy db = SQLAlchemy() migrate = Migrate() os.makedirs("logs", exist_ok=True) app_log_handler = RotatingFileHandler('logs/app.log', maxBytes=1000000, backup...
Python
1
h.tensor( [[-0.0098, -0.0570, -0.1286, 0.0439, -0.1037, -0.0235], [-0.0767, 0.0574, -0.3224, 0.0482, 0.0440, -0.0193], [ 0.0220, -0.0878, -0.2027, -0.0028, -0.0666, 0.0721], [ 0.0307, -0.1099, 0.0273, -0.0416, -0.0715, 0.0094], [ 0.0758, -0.0291, 0.108...
Python
1
const Hangul_YO: Key = Key(ffi::GDK_KEY_Hangul_YO as u32); #[doc(alias = "GDK_KEY_Hangul_YU")] pub const Hangul_YU: Key = Key(ffi::GDK_KEY_Hangul_YU as u32); #[doc(alias = "GDK_KEY_Hangul_YeorinHieuh")] pub const Hangul_YeorinHieuh: Key = Key(ffi::GDK_KEY_Hangul_YeorinHieuh as u32); #[doc(alias = "G...
Rust
0
fn manifest_relative_path<S: AsRef<Path>>(relative_path: S) -> PathBuf { PathBuf::new() .join(env!("CARGO_MANIFEST_DIR")) .join(relative_path) } /// Helpers fn _find_tests() -> Vec<PathBuf> { let mut test_paths = std::fs::read_dir(".") .expect("Failed to read test case directory") .map(|res| res....
Rust
0
include!("../fixtures/norway_main.rs"); b.iter(|| { curved::rdp(points.view(), 0.0005); }); }); } criterion_group!(benches, rdp_benches); criterion_main!(benches);<gh_stars>0 use arrow2::error::Result; use super::{integration_read, integration_write}; use crate::io::ipc::read_gzip_js...
Rust
0
NotFound)?; let i = i as usize; let j = j as usize; let n_coins = pool.assets.len(); ensure!(i < n_coins && j < n_coins, Error::<T>::IndexOutOfRange); let dx_u: u128 = dx.into(); let dx_f = FixedU128::saturating_from_integer(dx_u); let min_dy_u: u128 = min_dy.into(); let min_...
Rust
0
perature for Argon') plt.legend() plt.grid(True) melting_point = temperatures[np.argmax(first_derivative)] post_melting_temperatures = temperatures[temperatures > melting_point] post_melting_second_derivative = second_derivative[temperatures > melting_point] if post_melting_temperatures.size ...
Python
1
d == 0 and should_not_find != True: raise AssertionError("No objects matched %s"%(str(to_match))) if num_matched > 0 and should_not_find == True: raise AssertionError("Objects were found %s"%(str(to_match))) def satoshi_round(amount): return Decimal(amount).quantize(Decimal('0.00000001'), round...
Python
1
); for (telegram_user_id, process_response) in citizenships { let user_id = UserId::new(telegram_user_id.parse::<i64>().unwrap()); let message = SendMessage::new( user_id, format!( "Status: {}\n\ ...
Rust
0
and. {:?}", e ), } } } impl<D: 'static, DA> DataReader<D, DA> where D: DeserializeOwned + Keyed, <D as Keyed>::K: Key, DA: DeserializerAdapter<D>, { pub(crate) fn new( subscriber: Subscriber, my_id: EntityId, topic: Topic, qos_policy: QosPolicies, // Each notification se...
Rust
0
splay_image(); for x in 0..18 { state.iterate(); // state.display_image(); if x == 4 { println!("part 1: pixels on = {}", state.pixels_on_count()); } // println!("x = {}, count = {}", x, state.pixels_on_count()); } println!("part 2: pixels on...
Rust
0
import odoo from odoo.addons.web.tests.test_js import qunit_error_checker @odoo.tests.tagged("post_install", "-at_install") class ExternalTestSuite(odoo.tests.HttpCase): def test_external_livechat(self): # webclient external test suite self.browser_js("/web/tests/livechat?mod=web", "", "", login="...
Python
1
import json import requests import fitz from PIL import Image from urllib.parse import urlencode import base64 import glob import yanzheng import pandas as pd import io import sys print(sys.path) yanzheng.method_name('baidu_ocr260') maxi=0 def get_access_token(): """ 使用 AK,SK 生成鉴权签名(Access Token) :return:...
Python
1
from dataclasses import dataclass, field from typing import Optional @dataclass class CustomizedArguments: """ 一些自定义参数 """ max_seq_length: int = field(metadata={"help": "输入最大长度"}) train_file: str = field(metadata={"help": "训练集"}) model_name_or_path: str = field(metadata={"help": "预训练权重路径"}) ...
Python
1
ows, cols = proj.get_projection_dim() #print(dimz, dimy, dimx, views, rows, cols) M = dimz N = dimx # load image prior if available if len(init_fn) > 0: f_init = np.load(init_fn) f_init = f_init.reshape((1,f_init.shape[0],f_init.shape[1],f_init.shape[2])) else: # initialize f to be solved, given g above ...
Python
1
#[macro_use] extern crate num_derive; #[macro_use] pub mod debug_printer; pub mod error; pub mod fault; pub mod init; pub mod ipc; pub mod objects; pub mod process; pub mod syscall; pub mod thread; pub(crate) mod utils; pub mod vspace; struct Solution; impl Solution { fn max_repeating(sequence: String, word: Stri...
Rust
0
import logging from aegnn.asyncronous.flops.conv import compute_flops_conv from aegnn.asyncronous.flops.voxel_grid import compute_flops_voxel_grid def compute_flops_from_module(module) -> int: """Compute flops from a GNN module (after the forward pass). Generally, there are two cases. Either the module is a...
Python
1
apper { fn name(&self) -> Cow<str> { self.typed_op.name() } fn op_families(&self) -> &'static [&'static str] { self.typed_op.op_families() } fn wire( &self, prefix: &str, model: &mut TypedModel, inputs: &[OutletId], ) -> TractResult<TVec<OutletId...
Rust
0
); let mut out = String::new(); let mut out_p = String::new(); let preds = result .outer_iter() .map(|sample_predict| { let best = sample_predict.iter().enumerate().fold(0, |best, (i, &x)| { if x > sample_pr...
Rust
0
"choices": ["disable", "enable"]}, "emulator": {"required": False, "type": "str", "choices": ["enable", "disable"]}, "executables": {"required": False, "type": "str", ...
Python
1
# coding: utf-8 # Copyright (c) 2025 OceanBase. # # 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 agr...
Python
1
return te, te_list # If this test event was found unexpectedly (find is False) else: te['status'] = STATUS_UNEXPECT return te, te_list # If we make it to this point, the test event was not found in ion.log # If this test event was expected to...
Python
1
const G: RistrettoPoint = RISTRETTO_BASEPOINT_POINT; /// Hashes a curve point to a Scalar. fn hash_to_scalar(point: RistrettoPoint) -> Scalar { let mut hasher = Blake2b::new(); hasher.update(&HASH_TO_SCALAR_DOMAIN_TAG); hasher.update(point.compress().as_bytes()); Scalar::from_hash::<Blake2b>(hasher) } ...
Rust
0
raph { //! edges: Vec<(i32, i32)>, //! span_tree_cache: RefCell<Option<Vec<(i32, i32)>>> //! } //! //! impl Graph { //! fn minimum_spanning_tree(&self) -> Vec<(i32, i32)> { //! self.span_tree_cache.borrow_mut() //! .get_or_insert_with(|| self.calc_span_tree()) //! .clone() //...
Rust
0
ump_memory(filename, pos, length) { println!("Dump memory failed: {}", why); } } "r" | "run" => { self.machine.execute_frame(); } "" => {} _ => { println!("Unknown command: {}", cmd); ...
Rust
0
, client_mac): _http_client = http_client _address = controller_details["address"] _port = controller_details["port"] _site = controller_details["site"] _baseurl = "https://{}:{}".format(_address, _port) payload = {'type': 'by_cat', 'macs': [client_mac]} data = json.dumps(payload).encode("u...
Python
1
import logging import os import sys import redis from flask_limiter import Limiter from flask_limiter.util import get_remote_address from flask_mail import Mail from flask_migrate import Migrate from statsd import StatsClient from redash import settings from redash.app import create_app # noqa from redash.destinatio...
Python
1
[u8; 2usize], #[doc = "0x1c - HOST Host Interrupt Flag"] pub intflag: self::host::INTFLAG, _reserved12: [u8; 2usize], #[doc = "0x20 - HOST Pipe Interrupt Summary"] pub pintsmry: self::host::PINTSMRY, _reserved13: [u8; 2usize], #[doc = "0x24 - Descriptor Address"] pub descadd: self::host...
Rust
0
is arguably not an improvement: let m_translate = Mat4::new_translation(&Vec3::new(2.0 / screen_w, -2.0 / screen_h, 0.0)); let m_scale_inv = Mat4::new_nonuniform_scaling(&Vec3::new( 1.0 / (2.0 / screen_w), -1.0 / (2.0 / screen_h), 0.0, )); let m_scale = Mat4::new_nonuniform_sc...
Rust
0
from src.core.lattice_engine import LatticeEngine from src.core.node_autonomy import AutonomousNode from src.network.node_communication import NodeCommunication # Initialize the lattice lattice = LatticeEngine() # Create nodes nodes = [AutonomousNode(i) for i in range(5)] for node in nodes: lattice.add_node(node)...
Python
1
() -> &'static str; } pub fn serialize<T: NumericEnum, S: Serializer>(v: &T, s: S) -> Result<S::Ok, S::Error> { v.num().serialize(s) } pub fn deserialize<'d, T: NumericEnum, D: Deserializer<'d>>(d: D) -> Result<T, D::Error> { struct NumVisitor<T>(PhantomData<T>); impl<'d, T: NumericEnum> Visitor<'d> for Num...
Rust
0
checkbox.stateChanged.connect(lambda *_: save_tasks()) save_tasks() try: button.clicked.disconnect() except Exception: pass button.clicked.connect(add_task_wrapper) try: entry.returnPressed.disconnect() except Exception: pass entry.returnPressed.connect(add_task_wrapper) lis...
Python
1
"""Retract Axis command payload, result, and implementation models.""" from __future__ import annotations from pydantic import BaseModel, Field from typing import TYPE_CHECKING, Optional, Type from typing_extensions import Literal from ..state import update_types from ..types import MotorAxis from .command import Abst...
Python
1
00) ax.set_ylim(0, 100) ax.set_xlabel('Red Percentage') ax.set_ylabel('Yellow Luminance Percent') ax.set_title(f'Anomaloscope Mean Matches by Subject - {mode.title()} Mode') ax.legend() if save_path: plt.savefig(save_path, dpi=150) ...
Python
1
_swap( pool_id: T::PoolId, pair: CurrencyPair<T::AssetId>, quote_amount: T::Balance, apply_fees: bool, ) -> Result<(T::Balance, T::Balance, T::Balance, T::Balance), DispatchError> { let pool = Self::get_pool(pool_id)?; let pool_account = Self::account_id(&pool_id); let pool_base_aum = T::Convert:...
Rust
0
"""Test Subaru device tracker.""" from copy import deepcopy from unittest.mock import patch from subarulink.const import ( FETCH_INTERVAL, LATITUDE, LONGITUDE, TIMESTAMP, VEHICLE_STATUS, ) from homeassistant.const import ATTR_LATITUDE, ATTR_LONGITUDE from homeassistant.core import HomeAssistant f...
Python
1
#!/usr/bin/env python # -*- coding: utf-8 -*- """ 品質門檻檢查工具 此腳本用於在CI/CD流程中執行品質門檻檢查,確保代碼符合預設的品質標準。 如果任何指標未達標,將導致CI失敗。 使用方法: python scripts/quality_gate_check.py python scripts/quality_gate_check.py --min-pylint-score 8.5 --min-coverage 80 --max-file-lines 300 """ import os import sys import json import argpar...
Python
1
#!/usr/bin/env python3 """ 音声情報処理 n本ノック !! """ # MIT License # Copyright (C) 2020 by Akira TAMAMORI # 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...
Python
1
} } fn draw_surface(&self, c: &mut Canvas<Surface>) { let mut alpha = 255; let mut aoe = self.area_of_effect; for _ in 0..self.layers { // let green = std::cmp::min(255, i*12) as u8; c.filled_circle(self.position.x as i16, self...
Rust
0
UALIZACIÓN DE ESTADO --- # Obtener estado actual de todas las teclas teclas = pygame.key.get_pressed() # Actualizar posición del jugador según las teclas presionadas jugador_x, jugador_y = mover_jugador(jugador_x, jugador_y, velocidad, teclas, ...
Python
1
def get_off_grid_data(mysql): cursor = mysql.connection.cursor() cursor.execute("SELECT p.StateName, COUNT(*) FROM Household AS h, PostalCode AS p WHERE h.Heating_Temperature IS NULL AND h.Cooling_Temperature IS NULL GROUP BY p.StateName;") query = cursor.fetchall() cursor.execute("SELECT Round(AVG(B...
Python
1
to_le_bytes())?; Ok(()) } pub fn write_u16(t: &mut TcpStream, data: u16) -> std::io::Result<()> { t.write(&data.to_le_bytes())?; Ok(()) } pub fn write_u32(t: &mut TcpStream, data: u32) -> std::io::Result<()> { t.write(&data.to_le_bytes())?; Ok(()) } pub fn write_u64(t: &mut TcpStream, data: u64) -> ...
Rust
0
#[wrap(Operate, OperateSingleQubit, OperateGate, OperateSingleQubitGate)] /// The inverse square root XPower gate :math:`e^{i \frac{\pi}{2} \sigma^x}`. /// /// .. math:: /// U = \frac{1}{\sqrt{2}} \begin{pmatrix} /// 1 & i \\\\ /// i & 1 /// \end{pmatrix} /// /// Args: /// qubit (int): ...
Rust
0
if st.checkbox( page_name, value=checked, key=f"nav_checkbox_{page_path}", disabled=checked # Desabilita o checkbox da página atual ): if Path(page_path).exis...
Python
1
_played_white_wins() { let zobrist_hasher = ZobristHasher::create_zobrist_hasher(); let commands: Vec<&str> = "position startpos moves g1f3 g8f6 d2d4 d7d5 e2e3 e7e6 f1d3 b8c6 b1c3 f8e7 e1g1 e8g8 a2a3 h7h6 b2b4 a7a6 c1b2 e7d6 a1c1 b7b5 h2h3 c8b7 f1e1 f8e8 g2g3 d8d7 e3e4 e6e5 c3d5 f6d5 e4d5 c6d4 f3d4 e5d4...
Rust
0
: maybe_mark_dynamic(t, i) def mark_static(t, index=None): """ Mark a tensor as having a static dim. This will prevent us from attempting to compile it dynamically when dynamic=True; this can improve trace-time performance. This has lower precedence than mark_dynamic. Unlike mark_dy...
Python
1
ould not initialize TPM"), InternalError::ActivateAuthKey(_) => f.write_str("could not activate with auth key"), InternalError::GetTpmKeys(_) => f.write_str("could not get TPM keys"), InternalError::SignWithAuthKey(_) => f.write_str("could not sign with auth key"), } } } ...
Rust
0