text
string
label_name
string
labels
int64
tacore"; core.append(data1, None).await.unwrap(); core.append(data2, None).await.unwrap(); assert_eq!(core.len(), 2); let (data1, signature) = core.get(0).await.unwrap().unwrap(); replica.append(&data1, Some(signature)).await.unwrap(); let (data2, signature) = core.get(1).await.unwrap().unwrap...
Rust
0
.size }), size: self.size, } } } /// Bfs iterator of either tree or forest. pub enum Bfs<Iter> { Tree( BfsTree <Iter> ), Forest( BfsForest<Iter> ), } impl<T,Iter> Bfs<Iter> where Iter: Iterator<Item=Visit<T>> { /// Returns the iterator in breadth-first search. pub fn ite...
Rust
0
# -*- coding: utf-8 -*- # Generated by the protocol buffer compiler. DO NOT EDIT! # NO CHECKED-IN PROTOBUF GENCODE # source: request_give_tick_size_type_table.proto # Protobuf Python Version: 6.31.0 """Generated protocol buffer code.""" from google.protobuf import descriptor as _descriptor from google.protobuf import ...
Python
1
, b3] = loadu_4(msg_b.as_ptr()); let [c0, c1, c2, c3] = loadu_4(msg_c.as_ptr()); let [d0, d1, d2, d3] = loadu_4(msg_d.as_ptr()); let transposed0 = transpose_vecs(a0, b0, c0, d0); let transposed1 = transpose_vecs(a1, b1, c1, d1); let transposed2 = transpose_vecs(a2, b2, c2, d2); let transposed3 ...
Rust
0
ier() -> bool { unimplemented!() } } <gh_stars>0 /* * Copyright 2019 The Starlark in Rust Authors. * Copyright (c) Facebook, Inc. and its affiliates. * * 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 ...
Rust
0
from streamlit_theme import st_theme from .. import extra st_theme = extra(st_theme) def example_1(): import streamlit as st from streamlit_theme import st_theme theme = st_theme() st.write(theme) def example_2(): import streamlit as st from streamlit_theme import st_theme adjust = s...
Python
1
GetPriorityClass` and also breaks the `Eq` implementation. /// Process priority class. /// /// See [`GetPriorityClass`] function for more information. /// /// [`GetPriorityClass`]: https://docs.microsoft.com/en-us/windows/win32/api/processthreadsapi/nf-processthreadsapi-getpriorityclass #[derive(Debug, Copy, Clone, Pa...
Rust
0
| { &mut m.name }, )); fields.push(::protobuf::reflect::accessor::make_simple_field_accessor::<_, ::protobuf::types::ProtobufTypeString>( "op", |m: &NodeDef| { &m.op }, |m: &mut NodeDef| { &mut m.op }, )); ...
Rust
0
import sys, os, pathlib import numpy as np import scipy as sp import pandas import matplotlib.pyplot as plt REVERSE_TRANSFORM = False MATRIX_TYPES = ["Bivariate", "Semipartial"] TARGETS = ["AQ", "TX"] LABEL_COLUMN_INDEX = 1 # paths CROSS_SITE_DATASET = os.path.join("..", "..", "Hariri", "Cross-site_data") DATA_FILENA...
Python
1
# ======================================================================= # # Copyright (C) 2020 - 2025 Dominik Willner <th33xitus@gmail.com> # # # # This file is part of KIAUH - Klipper Installation And Update Helper # # https://githu...
Python
1
.15, FL3.2, FL3.3, FL3.4, FL3.5, FL3.6, FL3.7, //! FL3.8, FL3.9) //! - High Pressure Discharge Lamps (HP1, HP2, HP3, HP4, HP5) //! //! ## References //! //! [`CIEce` : CIE. (2004). CIE 15:2004 Tables Data.](https://law.resource.org/pub/us/cfr/ibr/003/cie.15.2004.tables.xls) //! [`CIEcf` : CIE. (n.d.). CIE Spectral ...
Rust
0
) is not None ] valid_state = any( state not in (STATE_UNKNOWN, STATE_UNAVAILABLE) for state in states ) if not valid_state: # Set as unknown if any member is unknown or unavailable self._attr_is_jammed = None self._attr_is_locking = None...
Python
1
TkButton(border=True, text="Joker", font=("Times New Roman", 24), checkable=True, checked=True) btn.setBgColor(color='#ff88ff') winLayout.addWidget(btn, i, j) buttons[i][j] = btn else: buzzword = random.choice(buzzwords).strip() ...
Python
1
assert_eq!(r.index_offset, 32); assert_eq!(r.index.entry, "foo"); } } <gh_stars>0 use std::slice::*; use std::mem::*; /// ///A macro constucting the gl functions for managing uniforms using the ///concat_idents! macro. Note that this can only be used in expressions, ///and as such, you must both ...
Rust
0
roperty.""" self._cards[0].set_value("accel", value) @property def lcdr(self) -> typing.Optional[int]: """Get or set the Load curve defining factor vs. time during dynamic relaxation """ # nopep8 return self._cards[0].get_value("lcdr") @lcdr.setter def lcdr(self, value:...
Python
1
import numpy as np import matplotlib.pyplot as plt # number of agents N = np.load("agents.npy") # retrieve local sequences sequence = {} timestamp_sequence_awake = {} timestamp_sequence_sleep = {} colors = {} t_init = None for i in range(N): colors[i] = np.random.rand(3, 1).flatten() filename = "agent_{}_seq...
Python
1
params.occlusion, color_target: out_color, depth_target: out_depth, displacement_contributions: displacement_contributions_buf, displacements, joint_transforms: joint_transform_buffer_view, }; ...
Rust
0
'''Ejercicio Práctico #1: Lista de la compra Usando la instrucción print() y lo visto en la clase, escribir un programa que muestre en la terminal la lista de productos que necesitamos comprar en el supermercado. Tips: ● Podés usar tabuladores para ordenar la lista. ● Recordá que si necesitas una línea en blanco, puede...
Python
1
copy(dataset) d.set_design_matrix(full_X[i:i+batch_size,:]) t2 = time.time() #print '\tapplying preprocessor' d.apply_preprocessor(pipeline, can_fit = False) X2 = d.get_design_matrix() t3 = time.time() #print '\trunning theano funct...
Python
1
) { for ( red_laser_entity, red_laser_speed, mut red_laser_trans, ) in query.iter_mut() { let trans = &mut red_laser_trans.translation; trans.y += red_laser_speed.0 * TIME_STEP; if trans.y > win_size.h { cmds.entity(red_laser_entity).despawn(); } } } <gh_stars>100-1000 // Copyright 2020-202...
Rust
0
await live_deactivate.finish(result) else: await live_deactivate.finish("请携带正确的uid后重试") @dyn_active.handle() async def _(event:GroupMessageEvent, args: Message = CommandArg()): if args.extract_plain_text() and args.extract_plain_text().isdigit(): dyn_active_processor = UpdateSubTools(args.ext...
Python
1
# cook your dish here t = int(input()) for i in range(t): n = int(input()) print(n-(n//5))
Python
1
import unittest from nltk import RegexpParser class TestChunkRule(unittest.TestCase): def test_tag_pattern2re_pattern_quantifier(self): """Test for bug https://github.com/nltk/nltk/issues/1597 Ensures that curly bracket quantifiers can be used inside a chunk rule. This type of quantifier...
Python
1
const SHADER_READ = 0x20; /// Writeable state for UAV access. /// Combine with `SHADER_READ` to have r/w access to UAV. const SHADER_WRITE = 0x40; /// Read state but can only be combined with `COLOR_ATTACHMENT_WRITE`. const COLOR_ATTACHMENT_READ = 0x80; /// Write-only ...
Rust
0
heus_port: Optional[int] = None, ): if engine_id >= engine_args.partition_id: engine_args.slo_aware_chunked_preemption = False sgir_distserve_config = engine_args.create_sgir_distserve_config() def signal_handler(*_) -> None: # Interrupt server on sigterm raise KeyboardInterrupt("MQ...
Python
1
.append( [service, "Running", process.info["pid"], create_time, running_time] ) else: table_data.append([service, "Not Running", "-", "-", "-"]) headers = ["Name", "Status", "PID", "Started At", "Running For"] typer.echo(tabulate(table_data, headers=heade...
Python
1
# Copyright (c) Meta Platforms, Inc. and affiliates. # All rights reserved. # # This source code is licensed under the license found in the # LICENSE file in the root directory of this source tree. """MusicGen grids."""
Python
1
use txn_types::TimeStamp; #[test] fn backup_blocked_by_memory_lock() { let suite = TestSuite::new(1, 144 * 1024 * 1024); fail::cfg("raftkv_async_write_finish", "pause").unwrap(); let tikv_cli = suite.tikv_cli.clone(); let (k, v) = (b"my_key", b"my_value"); let mut mutation = Mutation::default(); ...
Rust
0
referenced_column_name, column_name, referenced_column_name, ) ) for bad_row in cursor.fetchall(): raise IntegrityError( "The row in table '%s' with...
Python
1
: "BB43", "DP21_C2M_P" : "BB42", "DP21_M2C_N" : "BA46", "DP21_M2C_P" : "BA45", "DP22_C2M_N" : "AY43", "DP22_C2M_P" : "AY42", "DP22_M2C_N" : "AW46", "DP22_M2C_P" : "AW45", "DP23_C2M_N" : "AV43", "DP23_C2M_P" : "AV42", ...
Python
1
l#USER_ROTATION) pub const USER_ROTATION : &'static str = "user_rotation"; /// public static final [USE_GOOGLE_MAIL](https://developer.android.com/reference/android/provider/Settings.System.html#USE_GOOGLE_MAIL) #[deprecated] pub const USE_GOOGLE_MAIL : &'static str = "use_google_mail"; ...
Rust
0
self.variant(EV1_SEL_A::AUXIO20) } #[doc = "EVSTAT1.AUXIO19"] #[inline(always)] pub fn auxio19(self) -> &'a mut W { self.variant(EV1_SEL_A::AUXIO19) } #[doc = "EVSTAT1.AUXIO18"] #[inline(always)] pub fn auxio18(self) -> &'a mut W { self.variant(EV1_SEL_A::AUXIO18)...
Rust
0
tever"], ), ( 4, OrderedDict({"PassA": OrderedDict({"index": 1, "params": OrderedDict({"PA1_SP1": "A11a"})})}), ["whatever"], ), ( 5, OrderedDict({"PassA": OrderedDict({"index": 1, "params": O...
Python
1
formed using the following steps: 1. Convert dBm to Watts: .. math:: P_{\text{Watt}} = 10^{\left(\frac{P_{\text{dBm}}}{10}\right)} \times 10^{-3} 2. Convert Watts to Vrms: .. math:: V_{\text{rms}} = \sqrt{P_{\text{Watt}} \times Z} 3. Convert Vrms to Vpp: .. ma...
Python
1
- 1.695, 0.0, ), )), ..Default::default() }) .id(); let head = commands .spawn_bundle(( GlobalTransform::identity(), Transform::from_matrix(Mat4::from_scale_rotation_translation( ...
Rust
0
anation.value(); subs.push(tf_explanation); Ok(Explanation::new( true, boost_value * idf_value * tf_value, format!("score(doc={},freq={}), product of:", doc, freq_string), subs, )) } fn do_normalize(&mut self, boost: f32) { self.b...
Rust
0
# Copyright (C) 2023 The Qt Company Ltd. # SPDX-License-Identifier: LicenseRef-Qt-Commercial OR BSD-3-Clause from __future__ import annotations from PySide6.QtWebEngineCore import (qWebEngineChromiumVersion, QWebEngineProfile, QWebEngineSettings) from PySide6.QtCore import QObject,...
Python
1
conv_desc: &ConvDescriptor<CompType>, ) -> Result<BestHeuristic<ConvFwdAlgo>, CudnnError> where T1: DataType, T2: DataType, CompType: SupportedConv<T1, T2, T3>, T3: DataType, { let mut returned_algo_count = MaybeUninit::uninit(); let mut perf_results = May...
Rust
0
re_id!("Fg6PaFpoGXkYsidMpWTK6W2BeZ7FEfcYkg476zPFsLnS"); /// /// #[program] /// pub mod callee { /// use super::*; /// pub fn init(ctx: Context<Init>) -> ProgramResult { /// (*ctx.accounts.data).authority = ctx.accounts.authority.key(); /// Ok(()) /// } /// /// pub fn set_data(ctx: Contex...
Rust
0
""" Feature: 6.1.8 Multiple Inheritance Category: Classes & OOP Complexity: High Status: not_implemented """ import pytest PYTHON_SOURCE = """ class Child(Parent1, Parent2): pass """ EXPECTED_RUST = """ // TODO: Add Rust equivalent """ @pytest.mark.complexity("high") @pytest.mark.status("not_implemented") def t...
Python
1
one in None: # Slice the original df to only include data for the current breed and the feature columns # For reference in slicing with pandas, you can use the df_breed.groupby function followed by .get_group # or you can use the syntax df[df['breed'] == group] df_breed = df[df[...
Python
1
""" open_set = [] heapq.heappush(open_set, (0 + self.heuristic(start, end), 0, start, [start])) visited = set() def step(): if open_set: _, cost, current, path = heapq.heappop(open_set) if current in visited: self.root.a...
Python
1
from ipaddress import IPv4Address, IPv4Network from annet.generators import PartialGenerator from annet.storage import Device from .helpers.router import bgp_mesh class IpAddresses(PartialGenerator): """Partial generator class of IPv4 and IPv6 addresses on interfaces""" TAGS = ["l3", "iface"] def acl_...
Python
1
= json!({ "hello": "world", "key1": { "$ref": "#/hello" } }); let mut state = SparseState::new_from_value(PathBuf::from_str("hello.json").unwrap(), val).unwrap(); let parsed: SimpleStruct1 = state.parse_root().unwrap(); assert_eq!( *parsed.key1.get(...
Rust
0
ner wifely wigeon wigged wiggle wiggly wights wigwag wigwam wilder wildly wilful wilier wiling willed willow wilted wimple winced winces winded window windup winery winged winger wining winked winner winnow winter wintry wipers wiping wirier wiring wisdom wisely wisest wished wisher wishes withal wither within wizard w...
Python
1
result } pub struct KeyPair { keypair: ed25519_dalek_blake2b::Keypair, } impl Default for KeyPair { fn default() -> Self { let mut rng = rand::thread_rng(); let keypair = ed25519_dalek_blake2b::Keypair::generate(&mut rng); Self { keypair } } } impl KeyPair { pub fn new() ...
Rust
0
:BroadPhase}; use game_lib::{ bevy::{math::Vec2, prelude::*, utils::HashMap}, tracing::{self, instrument}, }; #[derive(Reflect, Clone, Copy, PartialEq, Eq, Debug, Hash)] pub struct Entry(usize); #[derive(Clone, Debug)] pub enum QuadTreeNode<const MIN_ENTRIES: usize, const MAX_ENTRIES: usize, const MAX_DEPTH: ...
Rust
0
stop_after=5000, densify_every=100, grad_thresh=0.0002, num_to_split_into=2, removal_opacity_threshold=0.005, final_removal_opacity_threshold=0.005, reset_opacities_every=3000, # Doesn't consider iter 0 ), ), ba=dict( ...
Python
1
# Copyright (C) 2018, 2019, 2020 Dominic O'Kane from financepy.utils.date import Date from financepy.market.curves.discount_curve_flat import DiscountCurveFlat from financepy.utils.global_types import OptionTypes from financepy.products.equity.equity_fixed_lookback_option import ( EquityFixedLookbackOption, ) from...
Python
1
filter(|c| !c.is_whitespace()) .collect::<HashSet<_>>() .len() } fn count_all_yes(s: &str) -> usize { let r = s .lines() .map(|line| { line.chars() .filter(|c| !c.is_whitespace()) .collect::<HashSet<_>>() }) .fold(('a'..='z...
Rust
0
from walrus import Database, Model, ListField, SetField, HashField from config import REDIS_URL db = Database.from_url(REDIS_URL) LISTENER_TASK_KEY = 'listener:task_id' class RBase(Model): __database__ = db def to_dict(self): data = {} for name, field in self._fields.items(): if ...
Python
1
et = read_definition_at_mci(db, definition_chash, max_mci)?; Ok(ret.ok_or_else(|| definition_chash.clone())) } fn read_definition_at_mci( db: &Connection, definition_chash: &String, max_mci: u32, ) -> Result<Option<Value>> { let mut stmt = db.prepare_cached( "SELECT definition FROM definiti...
Rust
0
right (c) 2016 <NAME> // // This software is released under the MIT License. // See http://opensource.org/licenses/mit-license.php or <LICENSE>. extern crate gurobi; use gurobi::*; mod workforce; use crate::workforce::make_model; fn main() { let mut env = Env::new("workforce1.log").unwrap(); env.set(param::L...
Rust
0
/// Accumulator pub eax: u32, /// Count register pub ecx: u32, /// Data register pub edx: u32, /// Base register pub ebx: u32, /// Stack pointer pub esp: u32, /// Base pointer pub ebp: u32, /// Source index pub esi: u32, /// Destination index pub edi: u32,...
Rust
0
# -*- coding: utf-8 -*- import scrapy import re class GithubSpider(scrapy.Spider): name = 'github' allowed_domains = ['github.com'] # 登录页面 URL start_urls = ['https://github.com/login'] def parse(self, response): # 获取请求参数 commit = response.xpath("//input[@name='commit']/@value").ext...
Python
1
Error; use adb_command::AdbCommand; #[derive(Debug, PartialEq, Clone)] pub struct Restore {} impl Restore { pub fn restore(device_id: &str) -> Result<(), Error> { AdbCommand::command("restore") .with_arg(&format!("{}.ab", device_id)) .with_device_id(Some(device_id)) .e...
Rust
0
operand2: None, operand3: None, operand4: None, lock: false, rounding_mode: None, merge_mode: None, sae: false, mask: None, broadcast: None }, &[15, 0, 43], OperandSize::Qword) } <gh_stars>1-10 use pyo3::prelude::*; use pyo3::types::PyDict; use pyo3::PyResult; use itertools::Itertools; use rustc_hash::FxHashMap; us...
Rust
0
compute_composites::<CS, _, _>(Some(k), b, cs, ds, mode)?; let r = CS::Group::random_scalar(rng); let t2 = a * &r; let t3 = m * &r; // Bm = GG.SerializeElement(B) let bm = CS::Group::serialize_elem(b); // a0 = GG.SerializeElement(M) let a0 = CS::Group::serialize_elem(m); // a1 = GG.Ser...
Rust
0
arg = arg.takes_value(true); } if let &Some(required) = required { arg = arg.required(required); } if let &Some(multi) = multi { arg = arg.multiple(multi); ...
Rust
0
focus on packets headers, and will largely ignore any packet //! payloads, as they are largely irrelevant to this project. use std::convert::TryFrom; use std::net::{IpAddr, SocketAddr}; use crate::error::NbugError; use crate::protocols::ethernet::IeeEthernetPacket; use crate::protocols::icmp::icmpv4::Icmpv4Packet; u...
Rust
0
u8 = 0x30; pub const AND_ZPIY: u8 = 0x31; pub const AND_ZPI: u8 = 0x32; pub const BIT_ZPX: u8 = 0x34; pub const AND_ZPX: u8 = 0x35; pub const ROL_ZPX: u8 = 0x36; pub const RMB3_ZP: u8 = 0x37; pub const SEC: u8 = 0x38; pub const AND_ABSY: u8 = 0x39; pub const DEC_A: u8 = 0x3A; pub const BIT_ABSX: u8 = 0x3C; pub const A...
Rust
0
import unittest from creational_patterns.builder import AppointmentBuilder class TestBuilder(unittest.TestCase): def test_builder(self): print("Running Builder Test...") builder = AppointmentBuilder() appointment = builder.set_provider("Dr. Max").set_service("Cleaning").build() sel...
Python
1
PostInfo { let who = ensure_signed(origin)?; T::Currency::transfer(&who, &Self::account_id(), amount, AllowDeath)?; let amount_wrapped: u128 = amount.checked_into().ok_or(Error::<T>::AmountOverflow)?; let prefix = String::from("0x"); let hex_sender = prefix + &hex::encode(who.encode()); let message ...
Rust
0
: usize) -> SqrtCache { let mut c = SqrtCache { cache: Vec::<f64>::with_capacity(max) }; for (i, v) in c.cache.iter_mut().enumerate() { let j = i as f64; *v = j.sqrt(); } c } fn compute_sqrt(&self, v: f64) -> f64 { if v.ceil() ...
Rust
0
SESSION: usize = 38; const NUM_HISTORY_SESSIONS: usize = 500; fn bench_nested_loops(bench: &mut Bencher) { let mut rng = rand::thread_rng(); let evolving_session: Vec<u64> = (0..NUM_ITEMS_IN_EVOLVING_SESSION) .map(|_| rng.gen_range(0..MAX_ITEM_ID)) .collect(); let historical_sessions: Vec...
Rust
0
ghput. This feature is only //! supported on Linux and requires a Linux kernel version 4.11 or higher. //! //! * `all-arch` - Not enabled by default. This feature compiles in support for //! all architectures for both the JIT compiler and the `wasmtime compile` CLI //! command. //! //! ## Examples //! //! In addi...
Rust
0
2 = 80.0; const TIME_TO_ACCELERATE: f32 = 2000.0; const MISSILE_ACCELERATION: f32 = (MISSILE_MAX_SPEED - MISSILE_MIN_SPEED) / TIME_TO_ACCELERATE * MS_PER_FRAME; const TIME_TO_ROTATE: f32 = 1000.0; const MAX_ROTATION: f32 = std::f32::consts::PI / TIME_TO_ROTATE * MS_PER_FRAME; pub struct MissilePhysicsSubsystem<'s>...
Rust
0
ub_spacing, min_coords[1]), (min_coords[0] + x_sub_spacing, min_coords[1]), stroke=fg)) # Add connection to RPi at minute number 4 # Since minute number 4 is specific for 'bernds_wiring', we check here, if this is the current wiring type if not mode == 'stencil' and ...
Python
1
ource tree. use crate::Hasher; use core::slice; use utils::{collections::Vec, iterators::*, rayon}; // CONSTANTS // ================================================================================================ pub const MIN_CONCURRENT_LEAVES: usize = 1024; // PUBLIC FUNCTIONS // =================================...
Rust
0
import requests def get_weather(city=None): url = "http://127.0.0.1:5000/get_weather" params = {} if city: params["city"] = city response = requests.get(url, params=params) if response.status_code == 200: weather = response.json() print(f"Погода в {weather['city']}, {weathe...
Python
1
ws, b" ", 1); ok!(skip_cfws, b" \t", 2); ok!(skip_cfws, b" abc", 1); ok!(skip_cfws, b"\tabc", 1); ok!(skip_cfws, b"\t abc", 2); ok!(skip_cfws, b" \r\n abc", 4); ok!(skip_cfws, b" \r\n \r\n\tabc", 7); ok!(skip_cfws, b" \r\nabc", 1); ok!(skip_cfws, b" \r\n ...
Rust
0
_tmpl_path, rspeedy_plugin_config_types_header_path, configs, ) def gen_config_doc(): configs = parse_config() config_doc_tmpl_path = os.path.join( os.path.dirname(os.path.abspath(__file__)), "lynx_config_doc.tmpl", ) config_doc_header_path = os.path.join( o...
Python
1
to restore {energy_to_restore} ⚡") sleep_interval = 60 total_slept = 0 while total_slept < sleep_time: await asyncio.sleep(sleep_interval) total_slept += sleep_interval if total_slept % 300 == 0 or total_slept >= sleep_time: ...
Python
1
= "serde", test), serde(rename = "CAP_SETPCAP"))] Setpcap = constants::CAP_SETPCAP, #[cfg_attr(any(feature = "strum", test), strum(serialize = "CAP_LINUX_IMMUTABLE"))] #[cfg_attr(any(feature = "serde", test), serde(rename = "CAP_LINUX_IMMUTABLE"))] LinuxImmutable = constants::CAP_LINUX_IMMUTABLE, ...
Rust
0
imo_core_interface::rust::build_interface_descriptor; use fimo_generic_module::{GenericModule, GenericModuleInstance}; use fimo_module_core::rust::module_loader::{RustModule, RustModuleInnerArc}; use fimo_module_core::rust::{ModuleInterfaceArc, ModuleInterfaceCaster, ModuleInterfaceWeak}; use fimo_module_core::ModuleIn...
Rust
0
codes::AUTHENTICATE => { let mut buf: [u8; SHA256_OUTPUT_LEN] = unsafe { mem::uninitialized() }; reader.read_exact(&mut buf)?; Ok(WorkerToServerMessage::Authenticate { hash: buf }) } worker_to_server_codes::UPDATE => { let len = { ...
Rust
0
------ ------ // Helpers // ------ ------ pub fn is_user_logged() -> bool { logged_user().map(Option::is_some) } // ------ ------ // Commands // ------ ------ pub fn set_page_id(new_page_id: PageId) { page_id().set_neq(new_page_id); } pub fn log_in(name: String) { logged_user().set(Some(name)); ...
Rust
0
import sys import re import os import nltk from nltk import word_tokenize from nltk.corpus import stopwords nltk.download('stopwords') nltk.download('punkt') import string import sentencepiece as spm class Preprocessor(): def __init__(self, language = 'english', instream = None): self.language = languag...
Python
1
# Copyright 2022 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 in writing, ...
Python
1
outine::<String, U0>(Default::default()); //! //! // XXX: Does not compile because our working set is one element too large. //! slow_routine::<String, U128>(Default::default()); //! } //! ``` //! //! # #\[verify\] //! //! The `verified` crate is built on top of the `typenum` crate, and provides syntactic sugar...
Rust
0
geFont.load_default(size=20) for i, (mol, bit, bi) in enumerate(bit_data): x = (bits[:i + 1].count(bits[i]) - 1) * max_width y = (len(set(bits[:i + 1])) - 1) * max_height draw.text((x, y), f"Bit {bit}", fill='black', font=font) # bbox = grid_image.getbbox() # grid_image = grid_image...
Python
1
"""回測查詢管理模組 此模組負責管理回測結果的查詢和匯出功能,包括: - 回測列表查詢 - 回測結果查詢 - 績效指標查詢 - 交易記錄查詢 - 圖表數據查詢 - 結果匯出 """ import sqlite3 import json from datetime import datetime from typing import Dict, List, Optional import logging # 設定日誌 logger = logging.getLogger(__name__) class BacktestQueryManager: """回測查詢管理器""" def __init__(sel...
Python
1
api_key = '' api_secret = '' # Bot de telegram token_telegram='' chat_id=""
Python
1
face: Rectangle::new(64.0, 64.0, sprite.width as f64, sprite.height as f64), sprite_sheet: sprite, sprite_coord: (0, 1), } } pub fn render(&mut self, state: &State, renderer: &mut Renderer) { self.update_state(state); self.sprite_sheet.render(renderer, self.sprit...
Rust
0
} } } use embedded_hal::blocking::spi::Write; use embedded_hal::digital::v2::OutputPin; use crate::{Error, Result}; /// Describes the interface used to connect to the MX7219 pub trait Connector { /// /// Writes a byte array to the device /// /// # Arguments /// /// * `data` - the ...
Rust
0
dle_stmt_likes<T>(&mut self, stmts: &mut Vec<T>) where T: ModuleItemExt + Take, Vec<T>: VisitWith<self::vars::VarWithOutInitCounter> + VisitMutWith<self::vars::VarPrepender> + VisitMutWith<self::vars::VarMover> + VisitWith<AssertValid>, { self.remove_d...
Rust
0
", strerror(errno)); if (posix_spawn_file_actions_destroy(&action) != 0) Fatal("posix_spawn_file_actions_destroy: %s", strerror(errno)); close(output_pipe[1]); return true; } void Subprocess::OnPipeReady() { char buf[4 << 10]; ssize_t len = read(fd_, buf, sizeof(buf)); if (len > 0) { buf_.append(b...
Rust
0
ue_pk, // &user_bid_ma.spot_open_orders, // Side::Ask, // ((base_price - 10) * quote_unit * base_lot) / (base_unit * quote_lot), // (quantity * base_unit) / base_lot, // bid_id, // OrderType::Limit, /...
Rust
0
t('-- Acquire Cursor') @classmethod def release(cls): print('-- Release Cursor') super(CursorResource, cls).release() def __init__(self): # The required resource references should # be stored on 'self' since we want to # release it w...
Python
1
from __future__ import print_function import click def log(msg, pre=True, error=False, warn=False, color=None): """Print a message to stdout""" if error: click.secho(('[jovian] ' if pre else '') + 'Error: ' + msg, err=True, fg='red') elif warn: click.secho(('[jovian] ' if pre else '') + ms...
Python
1
from __future__ import annotations import inspect from functools import update_wrapper import os from nonebot.adapters.onebot.v11 import Bot, GroupMessageEvent, PrivateMessageEvent from typing import Callable, Type, Coroutine, Union, get_type_hints from abc import abstractmethod from .command_signer import BasicHan...
Python
1
# coding: utf-8 from utils import * class Music: def __init__(self) -> None: self.desc = { "desc": "a free, personalized platform that plays music you'll love. discover new music and enjoy old favorites.", "base_required_arguments": {}, "APIs": { "playmed...
Python
1
_paragraph_text: str) -> str: retriever_address_config = get_retriever_address() retriever_host = str(retriever_address_config["host"]) retriever_port = str(retriever_address_config["port"]) params = { "query_text": original_paragraph_text, "retrieval_method": "retrieve_from_elasticsea...
Python
1
d::To(MovedKind::KakuN,(9,1),(8,2),true),"9一馬 -> 8二成 (不正な手です)"), (Moved::To(MovedKind::HishaN,(9,1),(8,2),false),"9一龍 -> 8二"), (Moved::To(MovedKind::HishaN,(9,1),(8,2),true),"9一龍 -> 8二成 (不正な手です)"), (Moved::To(MovedKind::Fu,(9,1),(8,2),false),"9一歩 -> 8二"), (Moved::To(MovedKind::Kyou,(9,1),(8,2),false),"9一香 -...
Rust
0
# The Leginon software is Copyright under # Apache License, Version 2.0 # For terms of the license agreement # see http://leginon.org # import wx from leginon.gui.wx.Entry import Entry, FloatEntry, EVT_ENTRY import leginon.gui.wx.FFTMaker import leginon.gui.wx.Settings import leginon.gui.wx.ToolBar import leginon.gui...
Python
1
import hashlib import logging import sys from optparse import Values from typing import List from pip._internal.cli.base_command import Command from pip._internal.cli.status_codes import ERROR, SUCCESS from pip._internal.utils.hashes import FAVORITE_HASH, STRONG_HASHES from pip._internal.utils.misc import read_chunks,...
Python
1
let mut rng = rng(); let run_now: bool = Rand::rand(&mut rng); let mut sched = Local::take::<Scheduler>(); let task = ~Coroutine::with_task(&mut sched.stack_pool, ~Task::without_unwinding(), f); if run_now { do sche...
Rust
0
raft}' subprocess.Popen([ 'python3', f'{ROOTDIR}/Subsystems/fdlGui/FdlSystem.py', subscription ]) def set_tlm_offset(self): selected_ver = self.cb_tlm_header_ver.currentText().strip() if selected_ver == "Custom": self.sb_tlm_offset...
Python
1
# Time Complexity = O(rows*columns) # Space Complexity = O(rows*columns) class Solution: def orangesRotting(self, grid: List[List[int]]) -> int: n = len(grid) m = len(grid[0]) count = 0 rotten = [] for i in range(n): for j in range(m): if...
Python
1
.section .emit_call("banshee_dma_stat", [self.dma_ptr(), imm]), }; self.write_reg(data.rd, value); Ok(()) } unsafe fn emit_imm12_rd(&self, data: riscv::FormatImm12Rd) -> Result<()> { let imm = data.imm(); trace!("{} x{} = 0x{:x}", data.op, data.rd, imm...
Rust
0