text
string
label_name
string
labels
int64
z" => Oz, "p" | "pro" => Prolog, "pas" => Pascal, "hex" => Hex, "ihex" => IntelHex, "json" => Json, "markdown" | "md" => Markdown, "rst" => ReStructuredText, "text" | "txt" => Text, "polly" => Polly, "proto" => Protobuf, "purs" => ...
Rust
0
# -*- coding: utf-8 -*- """ final_vid_edit.py - BAT'ten gelen ortam değişkenleri ile video düzenleme - Captions: start|end|text biçiminde CAP_FILE'dan okunur - Hızlandırma, büyük font, merkez yerleşim, görünür stroke - BGM: başlangıç/bitiş, loop, miks/tek-kanal opsiyonu - Konsol ilerleme çubuğu (tqdm) """ import os, s...
Python
1
# # Copyright (C) 2021-present by TeamYukki@Github, < https://github.com/TeamYukki >. # # This file is part of < https://github.com/TeamYukki/YukkiMusicBot > project, # and is released under the "GNU v3.0 License Agreement". # Please see < https://github.com/TeamYukki/YukkiMusicBot/blob/master/LICENSE > # # All rights ...
Python
1
33 (0 to 93; theoretically) Sanger, /// Illumina 1.3 - 1.7: Offset 64 (0 to 62) Illumina, /// Solexa: Offset 64 (-5 to 62) Solexa, /// Direct phred scores (as from .qual file) Phred, } impl QualFormat { pub fn get_converter(self) -> QualConverter { QualConverter::new(self) ...
Rust
0
setup(&self) { use std::fmt::Write; let mut out = String::new(); self.admin_websocket_ports .share_ref(|admin_websocket_ports| { for port in admin_websocket_ports { writeln!(&mut out, "###ADMIN_PORT:{}###", port) .expect("Ca...
Rust
0
#!/usr/bin/env python3 # -*- coding: utf-8 -*- import sys import io from PyQt6.QtWidgets import (QApplication, QMainWindow, QWidget, QVBoxLayout, QHBoxLayout, QLabel, QLineEdit, QPushButton, QTextEdit, QTabWidget, QTreeWidget, QTreeWidgetItem, QFrame, QSplitter, ...
Python
1
''' ''' # Licensed to the Apache Software Foundation (ASF) under one # or more contributor license agreements. See the NOTICE file # distributed with this work for additional information # regarding copyright ownership. The ASF licenses this file # to you under the Apache License, Version 2.0 (the # "License");...
Python
1
CartridgeCapability::MBC4, CartridgeCapability::RAM, CartridgeCapability::Battery, ]), 0x19 => Ok(vec![CartridgeCapability::MBC5]), 0x1A => Ok(vec![CartridgeCapability::MBC5, CartridgeCapability::RAM]), 0x1B => Ok(vec![ ...
Rust
0
import pytest from .network import setup_sacas, setup_sacas_rocksdb, setup_geth @pytest.fixture(scope="session") def sacas(tmp_path_factory): path = tmp_path_factory.mktemp("sacas") yield from setup_sacas(path, 26650) @pytest.fixture(scope="session") def sacas_rocksdb(tmp_path_factory): path = tmp_path...
Python
1
import pytest from integration_tests import AgentlessTestCase pytestmark = pytest.mark.group_general class TestBlueprintParsing(AgentlessTestCase): def test_requirements_parent_capabilities(self): bp = """ tosca_definitions_version: cloudify_dsl_1_5 imports: - cloudify/types/types.yaml node_types: ...
Python
1
pypi_version = str( max(all_candidates, key=lambda c: c.version).version ) # save that we've performed a check state.save(pypi_version, current_time) remote_version = packaging_version.parse(pypi_version) # Determine if our pypi_version is older ...
Python
1
p_err())); } None => return Poll::Ready(Ok(Inner::PlainText(Body::empty().into_stream()))), }; let _body = std::mem::replace( &mut self.0, IoStream(Body::empty().into_stream()).peekable(), ); match self.1 { #[cfg(feature = "br...
Rust
0
le(&self) -> i32 { let mut rng = rand::thread_rng(); rng.gen_range(self.lower..=self.upper) } } ``` # Examples Examples are located in `dcc-lsystem/examples` and can be run e.g. by: ```text cargo run --example fractal_plant --release ``` Note that running in release mode is typically much much f...
Rust
0
nstructs a span at the error level. /// /// [Fields] and [attributes] are set using the same syntax as the [`span!`] /// macro. /// /// See [the top-level documentation][lib] for details on the syntax accepted by /// this macro. /// /// [lib]: index.html#using-the-macros /// [attributes]: index.html#configuring-attribu...
Rust
0
} # Reemplazar los IDs foráneos con sus nombres correspondientes for row in table_body: if table == "funciones": row["pelicula_id"] = reference_dicts["peliculas"].get(row["pelicula_id"], "Desconocido") row["sala_id"] = reference_dicts["salas"].get(row["sala_id"], "Desconocido"...
Python
1
); while grid.transition(true) != 0 { transitions_counter += 1; println!("State after {} transitions:\n{}", transitions_counter, grid); } assert_eq!( grid.cells .iter() .filter(|&state| *state == State::Occupied) .count(), 37 ); } #[...
Rust
0
MS16-014)"), ("F20DA720-C02F-11CE-927B-0800095AE340", "OLE Package Object (may contain and run any file)"), ("F414C260-6AC0-11CF-B6D1-00AA00BBBB58", "jscript.dll - JScript Language (ProgID, ECMAScript, JavaScript, JScript, LiveScript)"), ("F4754C9B-64F5-4B40-8AF4-679732A...
Rust
0
ED CONTEXT FOR {website_url.upper()}: 🎯 YOUR BUSINESS PROFILE: - Website: {website_url} - Industry Focus: {industry_focus} - Business Size: {user_profile.get('business_size', 'SME')} - Region: {user_profile.get('region', 'Global')} 📝 YOUR CONTENT ANALYSIS: - Current Writing Tone: {writing_tone} - Primary Content Ty...
Python
1
#[inline(always)] pub fn rtcbcd(&mut self) -> RTCBCD_W { RTCBCD_W { w: self } } #[doc = "Writes raw bits to the register."] pub unsafe fn bits(&mut self, bits: u16) -> &mut Self { self.0.bits(bits); self } } #[doc = "Real Timer Control 0/1\n\nThis register you can [`read`](cr...
Rust
0
``` pub fn gcd(m: i128, n: i128) -> i128 { if m == 0 || n == 0 { return 0 } let mut m = m.abs(); let mut n = n.abs(); while n != 0 { let tmp = n; n = m % n; m = tmp; } m } #[cfg(test)] mod tests { use super::*; #[test] fn test_gcd_normal_case() { ...
Rust
0
(axis_dim_float) * _math.pi * 0.5 / axis_dim_float)) # TODO(rjryan): Benchmark performance and memory usage of the various # approaches to computing a DCT via the RFFT. dct2 = _math_ops.real( fft_ops.rfft( input, fft_length=[2 * axis_dim])[..., :axis_dim] * scale...
Python
1
import duckdb import pandas as pd con = duckdb.connect('stocks.db') con.execute(""" CREATE TABLE IF NOT EXISTS stocks AS SELECT * FROM df """) # 1. Basic data exploration # Get the date range and number of tickers con.execute(""" SELECT MIN(date) as earliest_date, MAX(date) as latest_date, ...
Python
1
get(); enqueue_next_position_index != PositionIndex::Zero && enqueue_next_position_index != id } #[inline(always)] fn set_enqueue_next_position_index(&self, enqueue_next_position_index: PositionIndex) { self.enqueue_next_position_index.set(enqueue_next_position_index); } #[inline(always)] fn reset_enqueu...
Rust
0
uper::super::storage::streams::IBuffer) -> Result<HString> { unsafe { let mut out = null_mut(); let hr = (self.get_vtbl().ConvertBinaryToString)(self.get_abi() as *const _ as *mut _, encoding, buffer.get_abi() as *const _ as *mut _, &mut out); if hr == S_OK { Ok(HString::wrap(out)) } else { err...
Rust
0
(a, b)| equal && a == b)); } #[test] #[ignore] fn cubic_roots_intersection() { let roots = cubic_real_roots(1.5, 1.1, 3.6, 1.0); assert_eq!(roots.iter().filter_map(|r| *r).last().unwrap(), -3.4063481215142195); let roots = cubic_real_roots(-7.1, 1.1, 3.6, 1.0); assert_eq!(roots.iter().filter_map(|r| *r)....
Rust
0
from pygame import (time, quit, event, key, QUIT, MOUSEMOTION, MOUSEBUTTONUP, MOUSEBUTTONDOWN, KEYDOWN, K_UP, K_DOWN, K_LEFT, K_RIGHT) from abstracts import AbstractWindow from config import FPS, is_game class Engine2D: """ Игровой 2D движок """ __slots__ = ("__window", "__hero", "__bush",...
Python
1
ets { BucketIndex(floor_log2(multiplier) as usize + 1) } else { BucketIndex(self.max_buckets as usize) } } } /// The capacity of a Bucket. #[derive(Clone, Copy, Debug, Eq, PartialEq, Ord, PartialOrd, Hash)] pub struct BucketCapacity(pub usize); /// The index of a Bucket. #[...
Rust
0
, out_parent_folder: "epcbc96".to_string() }); settings.push(CipherSetup { cipher: "epcbc96".to_string(), num_rounds: 32, soft_lim_e, mode: DLmode::Linear, out_parent_folder: "epcbc96".to_string() }); // AES settings.push(CipherSetup { cipher:...
Rust
0
es(lines) with updating_file_with_tmpfile(PCBUILD_PROJECT) as (infile, outfile): lines = infile.readlines() lines = replace_block( lines, '<!-- BEGIN deepfreeze rule -->', '<!-- END deepfreeze rule -->', deepfreezerules, PCBUILD_PROJECT, ...
Python
1
tConstraint::Between, ('\u{0D12}', '\u{0D3E}') => InsertConstraint::Between, ('\u{0D12}', '\u{0D57}') => InsertConstraint::Between, // Sinhala ('\u{0D85}', '\u{0DCF}') => InsertConstraint::Between, ('\u{0D85}', '\u{0DD0}') => InsertConstraint::Between, ('\u{0D85}', '\u{0D...
Rust
0
stralClient(api_key=key) self.model_name = model_name def chat(self, system, history, gen_conf): if system: history.insert(0, {"role": "system", "content": system}) for k in list(gen_conf.keys()): if k not in ["temperature", "top_p", "max_tokens"]: de...
Python
1
exit(errmsg=None): program = os.path.basename(sys.argv[0]) stream = errmsg and sys.stderr or sys.stdout stream.write(__doc__.replace("{PROGRAM}", program)) if errmsg: stream.write("\nERROR: %s\n" % (errmsg)) sys.exit(errmsg and EXIT_FAILURE or EXIT_SUCCESS) def main(): config_dir = None targets_file ...
Python
1
if v.reference.value_type == InputValueType.LITERAL and v.reference.value == "": msg_format = ( "The output '{output_name}' for flow is incorrect. The reference is not specified for " "the output '{output_name}' in the flow. To rectify this, " ...
Python
1
fn fmt_metric<N: fmt::Display>(&self, f: &mut fmt::Formatter<'_>, name: N) -> fmt::Result; /// Writes a metric with the given name and labels. fn fmt_metric_labeled<N, L>( &self, f: &mut fmt::Formatter<'_>, name: N, labels: L, ) -> fmt::Result where N: fmt::Displ...
Rust
0
# coding: utf-8 from sqlalchemy import Column, DateTime, Integer, String, text from sqlalchemy.dialects.mysql import TINYINT from sqlalchemy.ext.declarative import declarative_base Base = declarative_base() metadata = Base.metadata class Comic(Base): __tablename__ = 'comic' id = Column(Integer, primary_key=...
Python
1
t_pair() elif swap_type == "trigger": price_type = prompt.options("Select price direction:", [{'selector': 1, 'prompt': f"{self.token_in['symbol']}/{self.token_out['symbol']}", 'return': "forward"}, {'selector': 2, 'prompt': f"{self.token_o...
Python
1
app.prepare_bot_grid(8, 4); for ix in 0..8 { app.bot_grid_relps[ix][2].z = 50; app.bot_grid_relps[ix][3].z = 73; } app.prepare_session_schedule(); // Hack! app.session_absps.swap(1, 2); app.fission(); app.destroy_all(); app.harmonize(); app.fusion(); let ...
Rust
0
ne, True) self.assertRaises(ValueError, scanstring, '\\u0', 0, None, True) self.assertRaises(ValueError, scanstring, '\\u01', 0, None, True) self.assertRaises(ValueError, scanstring, '\\u012', 0, None, True) self.assertRaises(ValueError, scanstring, '\\u0123', 0, None, True) if s...
Python
1
::error::RotateSecretErrorKind::InvalidRequestError(body), meta: generic, }, Err(e) => crate::error::RotateSecretError::unhandled(e), }, "ResourceNotFoundException" => match serde_json::from_value(body) { ...
Rust
0
on non-CPU/GPU hardware. Example: ```python # samples has shape [1, 5], where each value is either 0 or 1 with equal # probability. samples = tf.random.stateless_categorical( tf.math.log([[0.5, 0.5]]), 5, seed=[7, 17]) ``` Args: logits: 2-D Tensor with shape `[batch_size, num_classes]`. E...
Python
1
let dump = SynthMinidump::with_endian(Endian::Little).add_stream(misc); let dump = read_synth_dump(dump).unwrap(); let misc = dump.get_stream::<MinidumpMiscInfo>().unwrap(); assert_eq!(misc.raw.process_id(), Some(PID)); assert_eq!( misc.process_create_time().unwrap(), ...
Rust
0
import numpy as np from xpfem import shapefunction, math class getStress2D: def __init__(self, mnode): self.Dfun = shapefunction.Dfun(mnode) self.mnode = mnode def evualStress(self, displacement, region): elem = region.mesh.cells node = region.mesh.points displacement ...
Python
1
from models.model_pspnet import PSPNet from utilities.data_loader import output_path, train_dataloader, val_dataloader from utilities.hyperparameters import device, N_EPOCHS, NUM_CLASSES, MAX_LR, MODEL_NAME import torch.optim as optim from torch.optim.lr_scheduler import OneCycleLR from utils import meanIoU from util...
Python
1
7_742b_7473 ); assert_eq!( compute_hash("skuldafnworld.4.20.-5.dds", Type::File)?, 0xa106_a998_7315_adb5 ); assert_eq!( compute_hash( r"meshes\actors\character\facegendata\facegeom\update.esm", Type::Directory ...
Rust
0
UXPOSR::BANDGAP } #[doc = "Checks if the value of the field is `PTAT`"] #[inline] pub fn is_ptat(&self) -> bool { *self == MUXPOSR::PTAT } #[doc = "Checks if the value of the field is `CTAT`"] #[inline] pub fn is_ctat(&self) -> bool { *self == MUXPOSR::CTAT } #[do...
Rust
0
: ept::buf_desc_t = ept::buf_desc_t{len: len as u32, frame: asciz_FRAME as *mut _}; // *mut u8 // println!("len {}", asciz_buf.len); return asciz_buf; } // extra test - full binary buffer // char ecad_data[EC_MESSAGE_MAX]; // 9000 fn build_blob_buf() -> ept::buf_desc_t { const ...
Rust
0
.argmax(dlog_ids4) turn_on_voltage4 = voltage.iloc[turn_on_index4] print(f"Turn-on Voltage = {turn_on_voltage4:.3f} V") log_ids5 = np.log10(current5_smooth) log_ids5_smooth = savgol_filter(log_ids5, window_length=115, polyorder=3) dlog_ids5 = np.gradient(log_ids5_smooth, voltage) turn_on_index5 = np.argmax(dlog_ids5) ...
Python
1
ult['kernels'] = kernels return result def get_disk_usage(path=None): """Reports total disk usage. Args: path: path at which disk to be measured is mounted. Returns: A dict of the form { label: str, usage: int, limit: int, } """ if not path: path = '/' if 'TEST_TMPD...
Python
1
// Update vote tally prop.votes.add_vote(vote, vote_power); prop.update_status(&env.block); PROPOSALS.save(deps.storage, proposal_id, &prop)?; Ok(Response::new() .add_attribute("action", "vote") .add_attribute("sender", info.sender) .add_attribute("proposal_id", proposal_id....
Rust
0
t of field: " , stringify ! ( TPM2B_PUBLIC ) , "::" , stringify ! ( t ) )); assert_eq! (unsafe { & ( * ( 0 as * const TPM2B_PUBLIC ) ) . b as * const _ as usize } , 0usize , concat ! ( "Alignment of field: " , stringify ! ( TPM2B_PUBLIC ) , "::" , ...
Rust
0
ue = "lifetime"), ), rx.tabs.content( rx.text("MONTHLY LEADERBOARD", weight="bold", size="4", width="100%", text_align="center", margin_top="2%"), rx.hstack( rx.card("username", margin_left="5%", margin_top="2%"), ...
Python
1
import os import json import regex as re from typing import Tuple, List, Dict, Any class TismKanjiUtils: PUNCTUATION_PATTERN = re.compile(r'[、-〿]') @staticmethod def replace_furigana_pattern(pattern, text): for match in pattern.finditer(text): start, _ = match.span() ...
Python
1
apper //! //! This is a simple wrapper for the [World Time API](https://worldtimeapi.org/api/timezone/). //! //! ## Usage //! //! To use this crate, add `worldtimeapi` to your `Cargo.toml`: //! //! ```toml //! [dependencies] //! worldtimeapi = "0.1" //! ``` //! //! Then create a client for an endpoint (currently they o...
Rust
0
from textwrap import dedent from typing import Any, Callable, Optional, TypeVar FuncType = Callable[..., Any] F = TypeVar("F", bound=FuncType) class Appender: """ A function decorator that will append an addendum to the docstring of the target function. This decorator should be robust even if func._...
Python
1
""" Create Date: 2024-10-15 12:25:32.071832 """ from alembic import op import sqlalchemy as sa from sqlalchemy.dialects import postgresql revision = "0466_join_request_cancelled_type" down_revision = "0465_rename_svc_join_enum" def upgrade(): op.execute("ALTER TYPE service_join_requests_status_type ADD VALUE 'c...
Python
1
y::PAddr; // SAFE: Trusting the DSDT address to be correct let dsdt = unsafe { super::SDTHandle::<()>::new( dsdt_paddr ) }; ::logging::hex_dump_t( "DSDT ", &*dsdt ); if &dsdt.raw_signature()[..] != b"DSDT" || !dsdt.validate() { log_warning!("DSDT is invalid"); } let dsdt_bytes = dsdt.data_byte_slice(); if...
Rust
0
"""全局配置项""" import os from collections import namedtuple from .utils import net _config = { 'users': ['admin'], 'passwords': ['admin', 'admin12345', 'asdf1234', 'abc12345', '12345admin', '12345abc'], 'user_agent': net.get_user_agent(), # to save time, we only get user agent once. 'ports': [80, 81, 8...
Python
1
import time import pytest import json from pois import Pois, NoWhoisServerFoundError class TestPois: def test_pois_result_have_both_registry_and_registrar_keys(self): result = Pois().fetch(domain="github.com") assert "registry_result" in result assert "registrar_result" in result def...
Python
1
import os import pandas as pd import matplotlib.pyplot as plt from datetime import datetime def ensure_users_exist(): path = "ModifiedData/users.csv" if not os.path.exists(path): print("⚠ Required file 'ModifiedData/users.csv' not found.") print("→ Generating it now using user_matrix module..."...
Python
1
=====================") L = computeCost(X, y, theta, beta) L_prev = L halt = 0 # halting variable (you can use these to terminate the loop if you have converged) print("-1 L = {0}".format(L)) i = 0 while(i < n_epoch and halt == 0): dL_db, dL_dw = computeGrad(X, y, theta, beta) b = theta[0] w = theta[1] #########...
Python
1
LOGOUT_REDIRECT_URL = '/'
Python
1
t.read_link() { result = p; } result.pop(); } Component::CurDir => (), Component::RootDir | Component::Normal(_) | Component::Prefix(_) => { result.push(comp.as_os_str()) } } } result.into...
Rust
0
not this repository is disabled. pub disabled: Option<bool>, pub open_issues_count: u64, pub license: Option<License>, pub forks: u64, pub open_issues: u64, pub watchers: u64, pub stargazers: Option<u64>, /// The default branch of the repository. pub default_branch: String, /// Whether to allow squ...
Rust
0
ess_ops.central_crop_to_sequence") @utils.InKeyOutKey(indefault="image", outdefault="image") def get_central_crop_to_sequence( patch_size: int, max_sequence_len: int, divisible_by_patch: bool = True, eps: float = 1e-5): """Central crops image such that patch sequence length satisfies constraints. C...
Python
1
PROTO_ICMP: i32 = 1; /// Internet Group Management Protocol pub const IPPROTO_IGMP: i32 = 2; /// IPIP tunnels (older KA9Q tunnels use 94) pub const IPPROTO_IPIP: i32 = 4; /// Transmission Control Protocol pub const IPPROTO_TCP: i32 = 6; /// Exterior Gateway Protocol pub const IPPROTO_EGP: i32 = 8; /// PUP protocol pub ...
Rust
0
class Solution: def minScoreTriangulation(self, values: List[int]) -> int: n = len(values) dp = [[0] * n for _ in range(n)] for j in range(2, n): for i in range(j - 2, -1, -1): dp[i][j] = math.inf for k in range(i + 1, j): dp[i][j] = min(dp[i][j], ...
Python
1
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 // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KI...
Rust
0
) -> Signal<Out, Bits<8>> { xem_7010_leds() } fn clocks() -> Vec<Signal<In, Clock>> { vec![xem_7010_pos_clock(), xem_7010_neg_clock()] } fn synth<U: Block>(uut: U, dir: &str) { synth::synth_obj(uut, dir) } } extern crate xdg; use std::env::args; use std::path::PathBuf; use ...
Rust
0
mut x486: fiat_p384_u1 = 0; fiat_p384_subborrowx_u64(&mut x485, &mut x486, x484, x471, (0x0 as u64)); let mut x487: u64 = 0; fiat_p384_cmovznz_u64(&mut x487, x486, x473, x459); let mut x488: u64 = 0; fiat_p384_cmovznz_u64(&mut x488, x486, x475, x461); let mut x489: u64 = 0; fiat_p384_cmovznz_u64(&mut x48...
Rust
0
import cv2 import matplotlib.pyplot as plt import numpy as np from numba import njit # 画一个精细的圆 @njit() def draw_circle(image, center, radius, value): """ 画一个圆,带锯齿 :param image: 灰度图 :param center: 圆心坐标(x,y),以横轴为 x,纵轴为 y。 :param radius: 半径,单位像素 :param value: 圆内的像素值 :return: img """ im...
Python
1
spawn order list with lives remaining # and spawn them if they're not alive for team in self.teams: # prune dead players from the spawn order team.gameData['spawnOrder'] = [p for p in team.gameData['spawnOrder'] if p.exists()] for player in team.ga...
Python
1
import logging from fastapi import APIRouter, Body, Query from tortoise.expressions import Q from app.controllers.dept import dept_controller from app.controllers.user import user_controller from app.schemas.base import Fail, Success, SuccessExtra from app.schemas.users import * logger = logging.getLogger(__name__) ...
Python
1
# Licensed to the Apache Software Foundation (ASF) under one # or more contributor license agreements. See the NOTICE file # distributed with this work for additional information # regarding copyright ownership. The ASF licenses this file # to you under the Apache License, Version 2.0 (the # "License"); you may not u...
Python
1
c ) , "::" , stringify ! ( tv_sec ) )); assert_eq! (unsafe { & ( * ( 0 as * const timespec ) ) . tv_nsec as * const _ as usize } , 8usize , concat ! ( "Alignment of field: " , stringify ! ( timespec ) , "::" , stringify ! ( tv_nsec ) ))...
Rust
0
: Option<i32>, } let s = Struct { a_field: 0x12345678_i32, b_field: Some(0x11223344), }; let mut target = [0u8; 8]; s.encode(&mut target, &mut ()); assert_eq!(&[0x12, 0x34, 0x56, 0x78, 0x11, 0x22, 0x33, 0x44], &target[..]); let s = Struct { a_field: 0x12345678_i32,...
Rust
0
ADDRESS: u16 = 0x40; pub const LCDC_INTERRUPT_ADDRESS: u16 = 0x48; pub const TIMER_OVERFLOW_INTERRUPT_ADDRESS: u16 = 0x50; pub const SERIAL_TRANSFER_INTERRUPT_ADDRESS: u16 = 0x58; /// Where the PC should go when button press interupts are handled /// TODO: separate these out, offset of 0x8 per interrupt address pub con...
Rust
0
// Create line-based streams from stdout and stderr of child let stdout_stream = match child.stdout().take() { Some(reader) => Box::new(lines(BufReader::new(reader))), None => return Result::Err(Error::new(ErrorKind::Other, "stdout ws not captured")), }; let stderr_stream = match child....
Rust
0
llection. (And modifying it to use weakref's as keys raises the lookup overhead to ~0.4 us) As a result, the WeakKeyDictionary implementation below turns out to be more prudent. Args: f: The function to cache. Returns: f decorated with simple caching behavior. """ cache = weakref.WeakKeyDictionar...
Python
1
import pytest import os import sys import json import math import torch import torch.distributed as dist import torch.nn.functional as F from fmoe.functions import ensure_comm from test_ddp import _ensure_initialized, _run_distributed from test_numerical import _assert_numerical from fmoe.fastermoe.schedule import _f...
Python
1
lock_type: u8 = 0; //! let block_size: u32 = 34; //! writer.write_bit(last_block).await.unwrap(); //! writer.write(7, block_type).await.unwrap(); //! writer.write(24, block_size).await.unwrap(); //! //! // STREAMINFO block //! let minimum_block_size: u16 = 4096; //! let maximum_block_size: u...
Rust
0
ype': 'temperature', 'value': metrics['temperature'], 'threshold': self.alert_thresholds['temperature'] }) if metrics['disk'] > self.alert_thresholds['disk']: alerts.append({ 'type': 'disk', 'value': metrics['disk']...
Python
1
write!(f, "Kind: Literal \nValue: {} \n", v); }, _ => write!(f, "invalid token kind") } } } <gh_stars>1-10 use schemars::JsonSchema; use serde::{Deserialize, Serialize}; use cw20::{Cw20ReceiveMsg}; use cosmwasm_std::{Uint128, Addr}; #[derive(Serialize, Deserialize, Js...
Rust
0
from regipy.plugins.system.routes import RoutesPlugin from regipy_tests.validation.validation import ValidationCase class RoutesPluginValidationCase(ValidationCase): plugin = RoutesPlugin test_hive_file_name = "SYSTEM.xz" exact_expected_result = { "\\ControlSet001\\Services\\Tcpip\\Parameters\\Per...
Python
1
from glob import glob import pandas as pd import json import time import random #import openai from openai import AzureOpenAI import os import re #from langchain.chains import LLMChain from langchain.prompts import PromptTemplate from tqdm import tqdm from langchain.prompts.chat import ( ChatPromptTemplate, Sy...
Python
1
import time from nfc.clf import RemoteTarget from broadcast_frame_contactless_frontend import BroadcastFrameContactlessFrontend import logging log = logging.getLogger(__name__) logging.basicConfig(level=logging.INFO) def main(driver, interface, path, broadcast=''): clf = BroadcastFrameContactlessFrontend(f"{in...
Python
1
np.random.default_rng(42) params = rng.uniform(low=0.0, high=2 * np.pi, size=[2 * nlayers, n]) structures = rng.uniform(low=-1.0, high=1.0, size=[nlayers, n - 1]) counts_energy_initial = energy_counts(params, structures, shots=2048) print({"counts_energy": counts_energy_initial}) # Autograd path qu...
Python
1
import discord from discord.ext import commands from core.core import Cog_Extension class cmd(Cog_Extension): @commands.command() async def hello(self, ctx,co): await ctx.send(f'Hello, world! {co}') @commands.command() async def ping(self, ctx): await ctx.send(f'當前延遲:{round(self.bot.latency*1000)}...
Python
1
: Vec<Customer>, } impl SolomonBuilder { pub fn new() -> Self { Self { title: "My Problem".to_string(), vehicle: (0, 0), customers: vec![] } } pub fn set_title(&mut self, title: &str) -> &mut Self { self.title = title.to_string(); self } pub fn set_vehicle(&mut self, vehic...
Rust
0
ergy))) visited = set() visited.add(start) came_from = {} while not pq.empty(): _, current_stat = pq.get() current_position = current_stat.position current_cost = current_stat.cost current_energy = current_stat.energy i...
Python
1
+= 1; } } println!("Answer: {}", answer_count); } fn count_answers(group_answers: &HashMap<char, u32>, group_size: u32) -> u32 { let mut count = 0; for (_, num_answered) in group_answers { count += if *num_answered == group_size { 1 } else { 0 }; } count } use geometry::point::Point; use std::f64; #...
Rust
0
"UR[ 5Ulg)Nr)rrrs rArinvwishart_gen.__init__v rrDc[XU5$)^Create a frozen inverse Wishart distribution. See `invwishart_frozen` for more information. invwishart_frozen)r...
Python
1
"""語言切換器模組 此模組提供 Streamlit 語言切換組件和語言狀態管理功能。 支援中英文切換,並提供簡潔的語言選擇界面。 主要功能: - 語言切換組件 - 語言狀態管理 - 語言資源載入 - 本地化文字獲取 Example: 基本使用: ```python from src.ui.localization.language_switcher import LanguageSwitcher # 初始化語言切換器 switcher = LanguageSwitcher() # 顯示語言切換組件 switcher.show_language_sel...
Python
1
), utils.ResourceUUID("foo", "bar")) self.assertEqual( uuid.UUID('4efb21f6-3d19-5fe3-910b-be8f0f727846'), utils.ResourceUUID("foo", None)) self.assertEqual( uuid.UUID('853e5c64-f45e-58b2-999c-96df856fbe3d'), utils.ResourceUUID("foo", "")) cla...
Python
1
mut buf, "Server=tcp:{},{}", params.host(), params.port())?; write!(&mut buf, ";Encrypt={}", params.encrypt())?; write!(&mut buf, ";Database={}", params.database())?; write!( &mut buf, ";TrustServerCertificate={}", params.trust_server_certificate() )?...
Rust
0
mut p = 1; let mut output: String; 'outer: loop { for command_set in commands.iter().permutations(p) { let mut program: String = "".to_string(); for command in command_set { program.push_str(command); program.push('\n'); } ...
Rust
0
BILITY_IMPLEMENTED: u32 = 218170186u32; #[doc = "*Required features: 'Win32_NetworkManagement_WiFi'*"] pub const OID_DOT11_NDIS_START: u32 = 218170112u32; #[doc = "*Required features: 'Win32_NetworkManagement_WiFi'*"] pub const OID_DOT11_NIC_POWER_STATE: u32 = 218170129u32; #[doc = "*Required features: 'Win32_NetworkMa...
Rust
0
/lang/String;\0"); __jni_env.call_object_method_a(self.0.object, __jni_method, __jni_args.as_ptr()) } } } } mod abi; mod accessor; mod arrays; mod assembly; mod balance; mod builtin; mod call; mod constant; mod create_contract; mod destructure; mod events; mod expressions; mod ha...
Rust
0
key_id, 1, message)?; create_fn(&mut *w, &slate.tx, PhantomData, PhantomData)?; tx::update_message(&mut *w, slate)?; w.close()?; Ok(()) } } //! # 🚀 Getting Started //! //! ### Add Documents <!-- omit in TOC --> //! //! ```rust //! use meilisearch_sdk::client::*; //! use serde::{Serialize, Deserialize}; //! us...
Rust
0
import re def zetanize(response): def e(string): return string.encode('utf-8') def d(string): return string.decode('utf-8') # remove the content between html comments response = re.sub(r'(?s)<!--.*?-->', '', response) forms = {} matches = re.findall(r'(?i)(?s)<form.*?</form.*...
Python
1
码片段""" if not snippet_name: messagebox.showinfo("提示", "请选择一个代码片段") return snippet_content = self.snippets.get(snippet_name, "") # 创建查看对话框 view_dialog = tk.Toplevel(self.root) view_dialog.title(f"查看代码片段 - {snippet_name}") view_dial...
Python
1