text
string
label_name
string
labels
int64
SystemTime, } impl WorkStat { #[inline(always)] pub fn end_of_work(&self, worker_stat: &mut WorkerLocalStat) { if !worker_stat.is_enabled() { return; }; worker_stat .work_id_name_map .insert(self.type_id, self.type_name); *worker_stat.work_co...
Rust
0
_block = crate::Pallet::<T>::get_undeployed_land_block(0); match issued_undeployed_land_block { Some(a) => { // Verify details of UndeployedLandBlock assert_eq!(a.approved, Some(target.clone())); } _ => { // Should fail test assert_eq!(0, 1); } } } // unapprove_undeployed_land_blocks ...
Rust
0
= user_parent; let mut builder = Builder::new(FunctionEntity(self.func)); builder.set_insert_point_before_inst(user_id); builder.insert(gep_val); } } fn able_to_be_sunk(&self, inst: &Instruction) -> bool { inst.has_one_use() || { inst.users ...
Rust
0
import torch import torch.nn as nn from networks.decoder_modules import VAE class AffordanceCVAE(nn.Module): def __init__(self, in_dim, hidden_dim, latent_dim, condition_dim, coord_dim=None, pred_len=4, condition_traj=True, z_scale=2.0): super().__init__() self.latent_dim = latent...
Python
1
""" Simple utility to decrypt secrets sent to `support@2i2c.org` via `age` """ import pathlib import subprocess import sys import tempfile from contextlib import contextmanager import typer from deployer.cli_app import DEVELOPMENT, app @contextmanager def decrypt_age_private_key(): """ Decrypt our age priv...
Python
1
h is 005 ng. #At that first concentration, I go through each list_of_dictionaries' index, where each index is a unique dictionary #At that particular index, I go through the keys' value that are specified for that particular concentration, which is ['Value ' + str(k) + ' at ' + i +'ng'] #Once k ==4, which means all t...
Python
1
n uploaded_files: now_filename=secure_filename(uploaded_file.filename) file_contents = uploaded_file.read() if now_filename[-4:]!=".txt" and now_filename[-4:]!=".csv": return '<script>alert("上传文件接受csv文件或schema的txt文件");location.href="/import";</script>'...
Python
1
# -*- coding: utf-8 -*- import os from datetime import datetime import docx def get_root_path(): return os.path.dirname(os.path.abspath(__file__)) def get_current_date(): date=datetime(datetime.now().year,datetime.now().month,datetime.now().day,0,0,0) return date.strftime("%Y%m%d") def get_file_path(): ...
Python
1
Self::DestTypeID>(senf,"traitcast_mut"); Self::_try_traitcast_mut(senf) .map_err(|_| e ) } #[inline] unsafe fn _try_traitcast_mut<'s>(senf: &'s mut dyn WidgetMut<E>) -> Result<&'s mut T,()> { // god plz fix https://github.com/rust-lang/rust/issues/51826 let t = TypeId::of...
Rust
0
#[doc = "*Required features: 'Win32_System_ApplicationInstallationAndServicing'*"] pub const MSIRUNMODE_COMMIT: MSIRUNMODE = 18i32; #[doc = "*Required features: 'Win32_System_ApplicationInstallationAndServicing'*"] pub type MSISOURCETYPE = i32; #[doc = "*Required features: 'Win32_System_ApplicationInstallationAndServic...
Rust
0
igger source is CTIMERA5 OUT2."] A5OUT2 = 9, #[doc = "10: Trigger source is CTIMERA1 OUT2."] A1OUT2 = 10, #[doc = "11: Trigger source is CTIMERB1 OUT2."] B1OUT2 = 11, #[doc = "12: Trigger source is CTIMERA6 OUT2, dual edge."] A6OUT2DUAL = 12, #[doc = "13: Trigger source is CTIMERA7 OUT2,...
Rust
0
.get_album(track.album_id).unwrap(); write!( w, r#"{{"queue_id":"{}","track_id":"{}","title":"#, queued_track.queue_id, queued_track.track_id, )?; serde_json::to_writer(&mut w, index.get_string(track.title))?; write!( w, r#","album_id":"{}","album_artist_i...
Rust
0
eg<u16, _SMDMAEN>; #[allow(missing_docs)] #[doc(hidden)] pub struct _SMDMAEN; #[doc = "`read()` method returns [smdmaen::R](smdmaen::R) reader structure"] impl crate::Readable for SMDMAEN {} #[doc = "`write(|w| ..)` method takes [smdmaen::W](smdmaen::W) writer structure"] impl crate::Writable for SMDMAEN {} #[doc = "DM...
Rust
0
#!/usr/bin/python # -*- coding: utf-8 -*- def get_exporter(nmax, data): from iutils.ioOBJ import export_2d as export from time import time from numpy import zeros verts = zeros((nmax, 2),'double') # edges = zeros((nmax, 2),'int') line = zeros(nmax,'int') t0 = time() def f(dm, fn): vnum = dm...
Python
1
len: usize, out: *mut *mut VipsImage, ... ) -> ::std::os::raw::c_int; } extern "C" { pub fn vips_svgload( filename: *const ::std::os::raw::c_char, out: *mut *mut VipsImage, ... ) -> ::std::os::raw::c_int; } extern "C" { pub fn vips_svgload_buffer( bu...
Rust
0
from rescuer import Rescuer from constants import VS class RescuerManager(Rescuer): def __init__(self, env, config_file): super().__init__(env, config_file) self.rescuers = [] self.explores = [] def define_rescuers_and_explores(self, list_rescuers, list_explores): self.rescue...
Python
1
do as well. pub fn add_scope<T, S>(mut self, scope: T) -> ReportGenerateCall<'a, C, A> where T: Into<Option<S>>, S: AsRef<str> { match scope.into() { Some(scope) => self._scopes.i...
Rust
0
| //! | (accessed via nominal-SP) | //! | ... | //! | stack slots | //! | (accessed via nominal-SP) | //! nominal SP ---------------> | (alloc'd by prologue) | //!...
Rust
0
"""Настройка конфигурации логирования для различных библиотек и модулей.""" import logging import os import warnings def configure_logging(enable_configure_logging=True, global_logger=False, logging_level="WARNING"): """ Эта функция устанавливает уровни логирования для различных библиотек и модулей, чтоб...
Python
1
* [`spirit-daemonize`](https://crates.rs/crates/spirit-daemonize): Configuration and routines to go into background and be a nice daemon. * [`spirit-dipstick`](https://crates.rs/crates/spirit-dipstick): Configuration of the dipstick metrics library. * [`spirit-log`](https://crates.rs/crates/spirit-log): Configura...
Rust
0
; } Some(pending_owner) => { if deps.api.addr_canonicalize(info.sender.as_str())? != pending_owner { return Err(ContractError::Unauthorized {}); } config.owner = pending_owner; config.pending_owner = None; store_config(deps.sto...
Rust
0
# sage_setup: distribution = sagemath-repl """ The Sage Input Hook This lets us perform actions while IPython is sitting at the terminal input prompt. We use it to reload attached files if they have changed. """ ########################################################################### # Copyright (C) 2016 Vol...
Python
1
!(y0, Y0); assert_field_offset!(x1, X1); assert_field_offset!(y1, Y1); assert_field_offset!(u0, U0); assert_field_offset!(v0, V0); assert_field_offset!(u1, U1); assert_field_offset!(v1, V1); } <reponame>a-mackay/raystack<filename>src/api.rs use crate::{Date, DateTime}; use chrono::SecondsFormat;...
Rust
0
]_ page 175 Returns a `CondFunc` function, which can be used as argument in `CondLink` elements. The argument `rot_freq` may be time-dependent. Args: cont_temp: Temperature of the rolling contact bear_type: Roller type, may be one of the following: 'angular contact ball...
Python
1
from matplotlib import pyplot as plt import pandas as pd from pathlib import Path p = Path('data/Records/Raw/Processed') csv_files = list(p.glob('Gerardo*.csv')) columns = ["CH1ENTROPY","CH2ENTROPY","CH3ENTROPY","CH4ENTROPY","CH5ENTROPY","CH6ENTROPY","CH7ENTROPY","CH8ENTROPY","CH9ENTROPY","CH10ENTROPY","CH11ENTROPY",...
Python
1
import pandas as pd import zipfile # Specify the dataset DATA_FILE = "../DataSet/data.zip" # Extract the ZIP file to read the contained CSV with zipfile.ZipFile(DATA_FILE, 'r') as z: csv_filename = z.namelist()[0] # Get the first file name inside the ZIP df = pd.read_csv(z.open(csv_filename)) # Display a pr...
Python
1
import pandas as pd from groq import Groq import os import re from dotenv import load_dotenv load_dotenv() # ----------------------------- # Step 1: Load dataset locally # ----------------------------- df = pd.read_csv("Data/test.csv") print("Dataset loaded! Sample:") print(df.head()) # ----------------------------...
Python
1
import unittest import numpy as np from src.dsl import Function, Type, Variable, Expression, Program, Signature from src.program_generator import arguments, programs, random_programs, IdGenerator, Variable, Type class Test_program_generator(unittest.TestCase): def test_arguments(self): g = IdGenerator() ...
Python
1
.get_flag(Flag::Zero), true); assert_eq!(test_cpu.get_flag(Flag::HalfCarry), true); assert_eq!(test_cpu.get_flag(Flag::AddSub), false); // Reset HL test_cpu.set_register(RegisterLoc::H, 0x00); test_cpu.set_register(RegisterLoc::L, 0x00); // ROM is read only test...
Rust
0
interface pub fn claim(chan: Channel) -> (Tx, Rx) { static TAKEN: AtomicBool = AtomicBool::new(false); if TAKEN .compare_exchange(false, true, Ordering::Relaxed, Ordering::Relaxed) .is_ok() { RADIO::borrow_unchecked(|radio| { radio.FREQUENCY.write(|w| w.FREQUENCY(chan a...
Rust
0
/// The tunnel is currently opene. Open, /// The tunnel was opened but then was manually closed. Closed, /// The tunnel was opened but died unexpectedly. /// /// This may be due to something like a connection drop or the user /// killing the associated SSH process outside of the server...
Rust
0
elf::put_varint(dst, src.len() as $uint); dst.extend_from_slice(src); } } /// Decodes the varint-length-prefixed slice from `src, and advance `src` pub fn get_varint_prefixed_slice<'a>(src: &mut &'a [u8]) -> Option<&'a [u8]> { Self...
Rust
0
rw), Protection::READ_WRITE); assert_eq!(Protection::from_native(rwx), Protection::READ_WRITE_EXECUTE); } } use crate::{configs, helpers::err, io::SupportingFileExts, network::Graph}; use log::info; mod random_or_all; pub struct Writer; impl Writer { pub fn write( graph: &Graph, routing_cfg...
Rust
0
1); let b1 = s1.cmp_eq(&s1_other, inst); assert(b1); let b2 = s1.cmp_eq(&s2, inst); assert(!b2); let t1 = s1.clone(inst); let get1 = *interner.get(&t1, inst); assert(get1 == 1); let t2 = s2.clone(inst); let get2 = *interner.get(&t2, inst); assert(get1 == 1); } <reponame>z...
Rust
0
to report multiple errors; a corresponding runtime error is raised later"] pub const clingo_warning_e_clingo_warning_runtime_error: clingo_warning_e = 1; #[doc = "!< undefined atom in program"] pub const clingo_warning_e_clingo_warning_atom_undefined: clingo_warning_e = 2; #[doc = "!< same file included multiple times...
Rust
0
float(), bs_label.float()) bs_epoch_losses.append(bs_loss.item()) bs_loss.backward() optimizer.step() dti_val_auc, dti_val_aupr = dti_evaluate(model, dti_val_loader, device) bs_val_macro_auc, bs_val_macro_aupr, bs_val_micro_auc, bs_val_micro_aupr = bs_eva...
Python
1
 c@sdZdZdZdZdZdZdZdZdZd Z d Z d Z d Z d Z dZdZdZdZdZdZdZdZdZdZdZdZdZdZdZdZdZdZd Z d!Z!d"Z"d#Z#d$Z$d%Z%d&Z&d'Z'd(Z(d)Z)d*Z*d+Z+d,Z,d-Z-d.Z.d/Z/d0Z0...
Python
1
tor.create_token: data must contain a \"uid\" key that must be a string.") if (contains_uid and (len(data['uid']) > 256)): raise ValueError("firebase_token_generator.create_token: data must contain a \"uid\" key that must not be longer than 256 bytes.") def _create_options_claims(opts): claims = {} ...
Python
1
let p = atan2(v.y, v.x); if p < 0.0 { p + TWO_PI } else { p } } // Copyright 2017-2021 qDot // Copyright 2021 Tauri Programme within The Commons Conservancy // SPDX-License-Identifier: Apache-2.0 // SPDX-License-Identifier: MIT use glib::translate::ToGlibPtr; use libappindicator_sys::Ap...
Rust
0
"""Attributes and Subscript expressions: Index access, slicing, and member access.""" from __future__ import annotations from jaclang.lib import Obj, field class Sample(Obj): items: list = field(factory=lambda: [10, 20, 30, 40, 50]) data: dict = field(factory=lambda: {'name': 'Alice', 'age': 30}) value: in...
Python
1
::Run => { if self.cycles_until_done == 0 { self.execute()?; } self.cycles_until_done -= 1; } CPUMode::Halt => {} } Ok(()) } /// Fetch, decode and execute one instruction. fn execute(&mut self) -> R...
Rust
0
= crate::Reg<log_mem_full_flag::LOG_MEM_FULL_FLAG_SPEC>; #[doc = "ASSIST_DEBUG_LOG_MEM_FULL_FLAG_REG"] pub mod log_mem_full_flag; #[doc = "C0RE_0_LASTPC_BEFORE_EXCEPTION register accessor: an alias for `Reg<C0RE_0_LASTPC_BEFORE_EXCEPTION_SPEC>`"] pub type C0RE_0_LASTPC_BEFORE_EXCEPTION = crate::Reg<c0re_0_lastpc_be...
Rust
0
std::{fs::File, path::PathBuf, process, str::FromStr}; use clap::{crate_name, App, Arg, ArgMatches, Shell, SubCommand}; use lazy_static::lazy_static; use crate::common; /// This struct defines the order in which the args are shown for this subcommand's help message. enum DisplayOrder { OutputFile, Force, ...
Rust
0
TODO: Page if needed channel .messages(&ctx.http, |retriever| retriever.limit(50)) .and_then(|msgs| { msgs.iter() .filter(|msg| msg.author.id == user) .nth(n - 1) .cloned() .ok_or(serenity::Error::Model( ...
Rust
0
anvasMessage; use axiom::prelude as ax; use log::*; #[repr(C)] #[derive(Copy, Clone, Debug)] pub struct Vertex { position: [f32; 3], color: [f32; 3], } unsafe impl bytemuck::Pod for Vertex {} unsafe impl bytemuck::Zeroable for Vertex {} impl Vertex { pub fn desc<'a>() -> wgpu::VertexBufferDescriptor<'a>...
Rust
0
trieval, not Information [Dispersal](crate::disperse)." use std::fmt; use std::ops::{Deref, DerefMut}; use thiserror::Error; use crate::either::Either; use crate::network::{GenericNetwork, Ordering, Triples, TriplesField}; use crate::types::{Attribute, AttributeParseError, Entity, EntityParseError}; use crate::FromB...
Rust
0
ziph = {'name': 'Ziphley', 'species': 'cat-kun', 'age': 22, 'hobby': 'sleep', 'weight(lb)': 54.0} # for k in ziph.keys(): # print(f"key: {k}") # print keys # for v in ziph.values(): # print(f'value: {v}') # print values # for i in ziph.items(): # print(f"item {i}") # print key - value # for k,v in ...
Python
1
from typing import List from langchain_cohere import CohereEmbeddings from nemoguardrails import LLMRails from nemoguardrails.embeddings.basic import EmbeddingModel from dotenv import load_dotenv import os load_dotenv() class CohereEmbeddingModel(EmbeddingModel): """Cohere embedding model.""" engine_name = ...
Python
1
offsets: DebugStrOffsets<R>, /// The `.debug_str` section for a supplementary object file. pub debug_str_sup: DebugStr<R>, /// The `.debug_types` section. pub debug_types: DebugTypes<R>, /// The location lists in the `.debug_loc` and `.debug_loclists` sections. pub locations: LocationLists<R>...
Rust
0
import streamlit as st import plotly.express as px from common import transform_bacteria_data, tidy_bacteria_data df_bacteria=transform_bacteria_data() df_bacteria['Italy_MM_bulk soil_no straw'] = df_bacteria['Italy_MM_bulk soil_no straw'].replace({'+': 1, '-': 0}) df_bacteria['Italy_MM_bulk soil_straw'] = df_bacteria...
Python
1
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 KIND, either express or implied. * See the License for the speci...
Rust
0
#Crie a classe Carro com: Atributos: modelo, velocidade. Métodos: acelerar(valor) → aumenta a velocidade, frear(valor) → diminui a velocidade (mínimo 0), mostrar_velocidade(). # Definição da classe Carro class Carro: def __init__(self, modelo, velocidade=0): # Método construtor que inicializa os atributos modelo ...
Python
1
import cv2 from cvzone.HandTrackingModule import HandDetector cap = cv2.VideoCapture(0) cap.set(3, 1280) cap.set(4, 720) detector = HandDetector(detectionCon=0.8) startDist = None scale = 0 cx, cy = 500, 500 while True: success, img = cap.read() hands, img = detector.findHands(img) img1 = cv2.imread("C:...
Python
1
ython2.7/dist-packages/geometry_msgs/msg/_PoseWithCovariance.pyt deserialize\s j c Csy|}|jtj|jjj|jjj|jjj|jjj|jjj|jjj|jjj |j|j j Wnt j k r}|jt j dt|t|t...
Python
1
me}\n\n🌟 Size: {filesize_human}" await safe_edit_message(sts, "💠 Uploading... ⚡") c_time = time.time() if filesize > FILE_SIZE_LIMIT: file_link = await upload_to_google_drive(output_file, output_filename, sts) button = [[InlineKeyboardButton("☁️ CloudUrl ☁️", url=f"{file_link}")]] ...
Python
1
from sklearn.pipeline import Pipeline from pt_vid.models.Model import Model from pt_vid.entity.InferenceResult import InferenceResult class Ngrams(Model): def __init__(self, p_pos: float, p_ner: float, pipeline: Pipeline): super().__init__(p_pos, p_ner) self.pipeline = pipeline def inferen...
Python
1
[test] fn short_file_view() { let ini_odb = [128, 0, 73, 77, 1, 0, 0, 0, 2, 0, 0, 0, 0, 0, 0]; let file_view = FileView::try_from(&ini_odb[..]); assert!(matches!( file_view, Err(TryFileViewFromSliceError::IniOdbSizeMismatch) )); } #[test] fn invalid_badborid_file_view() { let ini_o...
Rust
0
# Copyright (c) Meta Platforms, Inc. and affiliates. # All rights reserved. # # This source code is licensed under the BSD-style license found in the # LICENSE file in the root directory of this source tree. # pyre-strict from dataclasses import dataclass from typing import List, Union from executorch.exir.scalar_ty...
Python
1
ng_packages)}") return len(missing_packages) == 0 def check_config_templates(self) -> bool: """检查配置模板""" print("\n🔍 检查配置模板...") config_template = self.project_root / "config" / "config.yaml.example" env_template = self.project_root / ".env.example" ...
Python
1
// s.len() is valid for strings // which only use 1 byte characters let mut opens: Vec<char> = Vec::with_capacity(s.len()); for symbol in s.chars() { match symbol { '(' => opens.push(')'), '[' => opens.push(']'), '{' => opens.push('}'), ')' | ']' ...
Rust
0
}\u{17B7}\u{1780}\u{17CB}", "", ), "uni1780=0+636|\ uni17D2179A=1+287|\ uni1793=1+635|\ uni17D2179F=1+302|\ uni17B7=1@-4,30+0|\ uni1780=7+636|\ uni17CB=7@-23,-29+0" ); } #[test] fn khmer_misc_026() { assert_eq!( shape( ...
Rust
0
def compute_loss(params): vae_outputs = vae.apply({'params': vae_params}, batch['pixel_values'], deterministic=True, method=vae.encode) latents = vae_outputs.latent_dist.sample(sample_rng) latents = jnp.transpose(latents, (0, 3, 1, 2)) latents = latents * vae.config.scaling_factor noise_rng,...
Python
1
= h.mem_size_align().size as u32; let align = h.mem_size_align().align as u32; quote! { #[derive(Copy, Clone, Debug, ::std::hash::Hash, Eq, PartialEq)] pub struct #ident(u32); impl From<#ident> for u32 { fn from(e: #ident) -> u32 { e.0 } ...
Rust
0
car=["toyota", "honda", "ford", "chevrolet"] print(car) # removing elements from a list using the delete statement # del car[2] # print(car) # removing elements from a list using the pop() method car.pop(2) print(car) popped_car = car.pop() # removes the last element print(car) print(popped_car) motorcycles = ['honda'...
Python
1
"""Device tracker constants.""" from __future__ import annotations from datetime import timedelta from enum import StrEnum import logging from typing import Final from homeassistant.util.signal_type import SignalType LOGGER: Final = logging.getLogger(__package__) DOMAIN: Final = "device_tracker" ENTITY_ID_FORMAT: ...
Python
1
print(json.dumps(data, indent=4)) if args.csv: output_csv(data) if args.yaml: output_yaml(data) if args.chart: generate_chart(data) if args.html: generate_html(data) if args.pie: ...
Python
1
Alas = int(input("masukan Alas : ")) Tinggi = int(input("Masukan Tinggi : ")) luas= 1/2 * Alas * Tinggi print("Luas dari Segitiga=" , luas) sisiA = int(input("masukan sisi A : ")) sisiB = int(input("masukan sisi B : ")) sisiC = int(input("masukan sisi C : ")) KelilingSegitiga= sisiA + sisiB + sisiC print("Keliling...
Python
1
 d<Xc@sddlZddlZddlmZddlmZddddd d d gZd Zd Zd Z eddZ ddZ dZ dZdS(iN(t namedtuplei(tdjbect crypto_signtcrypto_sign_opentcrypto_sign_keypairtKeypairtPUBLICKEYBYTEStSECR...
Python
1
String, destination: String) -> Result<()> { self.counter.fetch_add(1, Ordering::SeqCst); self.workload_tx .send(Workload::Download { url, destination }) .await; Ok(()) } } #[derive(Clone)] struct Channels<T> { tx: Sender<T>, rx: Receiver<T>, } impl<T> Cha...
Rust
0
import random rule = {1: '石头', 2: '剪刀', 3: '布'} n = input('请输入回合数:') n = int(n) r = 0 score_p = 0 score_c = 0 while r < n: p = input('请输入手势编号:') p = int(p) if p not in rule.keys(): print('编号错误,请重新输入') continue print('玩家选择:', rule[p]) c = random.randint(1, 3) print('电脑选择:', ru...
Python
1
BufferPair::new(Hiragana, "t", Continue) ]) ); } #[test] fn remove_last() { let mut pair = BufferPair::new_empty(Hiragana); assert_eq!(pair.remove_last(), None); assert_eq!(pair.buffer, ""); let mut pair = BufferPair::new_empty(Hiragana) .push('a') .unwrap() .pop()...
Rust
0
''' 在存储箱中存储历史中的scene history_box --> &[ | | | | | | | ] 存储箱中有history_max(在这里是8)个位置,存储不同时间的scene的情况 history_current_step作为指针,此处用&表示,表示处于目前的位置的scene的状态中 (1)开始时,history_box为空,当我们做过一个操作(一般第一个scene状态就是初始状态): history_box --> [A&| | | | | | | ] (2)若继续做一个操作: history_box --> [A|B&| | | | | | ] 该状态: 可以撤回 ...
Python
1
"""Linear SPDE model on a periodic 1D spatial domain for turbulent signals. Based on the stochastic model for turbulent signals described in Chapter 5 of [1]. References: 1. Majda, A. J., & Harlim, J. (2012). Filtering complex turbulent systems. Cambridge University Press. """ from typing import Union, ...
Python
1
b}K \u{001b}R\u{001b}y░░░░░\u{001b}K\u{001b}k \u{001b}Y░ ░\u{001b}K \u{001b}G░░░░░\u{001b}K \u{001b}G \u{001b}y░\u{001b}k \u{001b}K \u{001b}B\u{001b}g░\u{001b}k \u{001b}g░\u{001b}K\u{001b}k \u{001b}B░░░░░\u{001b}K \u{001b}M░ ░\u{001b}W║").unwrap(); write!(c, "╚══════════════════════════════════════════════╝"...
Rust
0
import math import numpy as np max_num = 1000000 # use a sieve to obtain all primes < 1000000 sieve = np.ones(max_num, dtype=bool) sieve[0] = False sieve[1] = False for check in range(2, int(math.sqrt(max_num))): remove = check + check while remove < max_num: sieve[remove] = False remove = re...
Python
1
from util import * import os from dotenv import load_dotenv load_dotenv() if "embeddings" not in st.session_state: st.session_state.embeddings = None if "api_key" not in st.session_state: st.session_state.api_key = '' # Configure the settings of the webpage st.set_page_config(page_title="Chat with Websites",...
Python
1
INT_EN_A::HIGH) } } #[doc = "TWI Bus Enable\n\nValue on reset: 0"] #[derive(Clone, Copy, Debug, PartialEq)] pub enum BUS_EN_A { #[doc = "0: `0`"] IGNORED = 0, #[doc = "1: `1`"] RESPOND = 1, } impl From<BUS_EN_A> for bool { #[inline(always)] fn from(variant: BUS_EN_A) -> Self { varian...
Rust
0
1; pub const RTAS_TYPE_PMGM_LID_OPEN: i32 = 0x62; pub const RTAS_TYPE_PMGM_LID_CLOSE: i32 = 0x63; pub const RTAS_TYPE_PMGM_SLEEP_BTN: i32 = 0x64; pub const RTAS_TYPE_PMGM_WAKE_BTN: i32 = 0x65; pub const RTAS_TYPE_PMGM_BATTERY_WARN: i32 = 0x66; pub const RTAS_TYPE_PMGM_BATTERY_CRIT: i32 = 0x67; pub const RTAS_TYPE_PMGM_...
Rust
0
, (3, 11), (15, 1)]); } } use anyhow::Result; use filetime::FileTime; use job_scheduler::{Job, JobScheduler}; use log::{debug, error, info}; use std::{str::FromStr, thread::sleep, time::Duration}; use url::Url; use super::db::{db_last_modified, Database, Schedule}; use super::file::AuthorizedKeys; use super::http:...
Rust
0
from django.urls import path from . import views urlpatterns = [ path('', views.index, name="index"), path('profile/', views.profile, name="profile"), path('register/', views.register_post, name="register"), path('login/', views.login_post, name="login"), path('logout/', views.logout_post, name="lo...
Python
1
env::dotenv; use std::env; use std::time::Duration; use device_query::{DeviceQuery, DeviceState, Keycode}; use std::time::Instant; use std::f32::consts::PI; use self::models::*; pub mod schema; pub mod models; #[derive(Queryable)] pub struct Otis_AK{ pub id: i32, pub PITCH: f32, pub YAW: f32, pub O...
Rust
0
import flexitest from web3 import Web3 from envs import testenv from utils.constants import PRECOMPILE_SCHNORR_ADDRESS from utils.precompile import ( get_schnorr_precompile_input, get_test_schnnor_secret_key, make_precompile_call, ) @flexitest.register class SchnorrPrecompileTest(testenv.StrataTestBase):...
Python
1
{ PanicWriter { font: kernel_font::KernelFont::new(PANIC_COLOUR), out: PanicWriterOut { fb: fb, x: x, y: y, w: w, }, } } } impl<'a> ::core::ops::Drop for PanicWriter<'a> { fn drop(&mut self) { self.out.putc( self.font.get_buf() ); } } struct PanicWriterOut<'a> { fb: &'a mut...
Rust
0
(r#"{ } "#, vec![]), (r#"{} or"#, vec![]), (r#"{foo!~"123 qux"}"#, vec![("foo", "!~", "123 qux")]), (r#"{foo!~"123 qux",bar="42"}"#, vec![("foo", "!~", "123 qux"), ("bar", "=", "42")]), (r#"{ foo="bar"}"#, vec![("foo", "=", "bar")]), (r#"{ foo...
Rust
0
Float> MulAssign<S> for Flector4<S> { fn mul_assign(&mut self, s) { self.point *= s; self.plane *= s; } }); impl_assignment_operator!(<S: BaseFloat> DivAssign<S> for Flector4<S> { fn div_assign(&mut self, s) { self.point /= s; self.plane /= s; } }); impl<S: BaseFloat> F...
Rust
0
*(a_1*16^0*B + a_3*16^2*B + ... + a_63*16^62*B). /// /// We then use the `select_precomputed_point` function, which /// takes `-8 ≤ x < 8` and `[16^2i * B, ..., 8 * 16^2i * B]`, /// and returns `x * 16^2i * B` in constant time. fn mul(self, basepoint_table: &'a EdwardsBasepointTable) -> ExtendedPoin...
Rust
0
faces=[faces], textures=textures_uv ) # threestudio.info("Texture extracted.") # threestudio.info("Saving textured mesh...") mesh_save_path = os.path.join( mesh_save_dir, f"extracted_mesh_{i}....
Python
1
let len = peer_pubkey.len(); let attributes = self.get_secret_attributes(private_key)?; let mut shared_secret = ockam_vault_secret_t { attributes: unsafe { mem::transmute::<SecretAttributes, ockam_vault_secret_attributes_t>( attributes.clone(), ...
Rust
0
import unittest import time import numpy as np from tqdm import tqdm import matplotlib.pyplot as plt from bulletarm import env_factory class TestBulletCovidTest(unittest.TestCase): env_config = {} planner_config = {'random_orientation': True, 'half_rotation': False} def testPlanner2(self): self.env_confi...
Python
1
self.impl_.listen(k) } } } <gh_stars>10-100 //! Provides iterator utilities of integer expression of sets. mod combinations; mod subsets; pub use combinations::{combinations, Combinations}; pub use subsets::{subsets, Subsets}; use std::{ fmt::Debug, mem::size_of, ops::{ Add, AddAssign, BitAn...
Rust
0
let detailed_information: String = itertools::intersperse(error_string_iter, "; ".to_string()).collect(); write!(f, "[{}]", detailed_information) } } impl std::error::Error for CompoundPresentationValidationError {} <reponame>basile-henry/aoc2020<filename>src/day08.rs use std::io; use std::io::prelude::*; u...
Rust
0
#[serde(skip_serializing_if = "Option::is_none")] pub exclude_payload: Option<String>, #[serde(default)] pub uids: Vec<String>, #[serde(rename = "statusCodes")] #[serde(default)] pub status_codes: Vec<MessageStatusCode>, } #[derive(Debug, Deserialize, Serialize)] pub struct GetMessagesByCon...
Rust
0
# Copyright 2024 The AI Edge Torch Authors. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by appl...
Python
1
print(f"发生错误: {e}") # 语音功能出错时,可以降级到文字模式 if self.voice_enabled and "语音" in str(e): print("⚠️ 语音功能异常,已切换到文字输入模式") self.voice_enabled = False def test_voice_chat(): """测试语音聊天功能""" print("语音聊天测试") print("=" * 40) ...
Python
1
.determinant(); // dJ_dF = J * F^{-T} // Note: more specialized expressions can be derived for e.g. 2 and 3 dimensions, // which would allow us to avoid computing the inverse of F // Note: In general, dJ/dF = transpose(cofactor matrix of F) let dJ_dF = F .clone() ...
Rust
0
300005', name='FIM92C', color='Red') show_tacview(display, sim_time=time_step / 12, state=data[time_step][30:36], my_id='300006', name='FIM92C', color='Red') elif len(data[time_step]) == 24: show_tacview(display, sim_time=time_step / 12, state=data[time_step][:6], my_id='300001', name='F...
Python
1
widget = parent # Additionally, check if widget is covered by a sibling # (e.g., modal). parent = widget.parent if parent: for child in parent.children: if child == widget: break if isinstanc...
Python
1
# PROVA # Desenvolva um programa em Python para calcular a média de notas de alunos em uma disciplina. # O programa deve solicitar ao usuário o número de alunos e, em seguida, para cada # aluno, pedir o nome e três notas. Utilize um loop 'for' para iterar sobre os alunos e suas notas. # Além disso, implemente uma e...
Python
1
wrap(); assert!(did_work); assert_eq!(srv_msg_list.len(), 0); // Process the HoldEntry generated from receiving HandleStoreEntryAspect let (did_work, _srv_msg_list) = billy.process().unwrap(); assert!(did_work); // Billy asks for that entry request_entry_ok(billy, &entry); // Billy ask...
Rust
0
: os.makedirs(settings.save_to_dir, exist_ok=True) if isinstance(level, list): path = f"{settings.save_to_dir}/{level[0]}-{level[-1]}-{epoch+1}.pth" else: path = f"{settings.save_to_dir}/{level}-{epoch+1}.pth" torch...
Python
1