text
string
label_name
string
labels
int64
(1)) & \ (dframe["smooth support"] * (1 + 0.5 / 100) > dframe["close"]) condition_2_sell = dframe["SMA fast"] < dframe["SMA slow"] condition_3_sell = dframe["Bearish Engulfing"] == -1 # condition_1_buy & condition_1_sell & buy_condition = condition_1_bu...
Python
1
elf = Expr::Sexp( Op::Bind, Box::new(Expr::Atom(Prim::Name(String::from("__shouldReport")))), Box::new(Expr::Atom(Prim::Bool(true))), ) } Expr::None => {} Expr::Atom(_) => {} Expr::Sexp(_, ref mut...
Rust
0
more than one scope. /// If `None` is specified, then all scopes will be removed and no default scope will be used either. /// In that case, you have to specify your API-key using the `key` parameter (see the `param()` /// function for details). /// /// Usually there is more than one suitable scope...
Rust
0
request_cors_if_not_same_origin(&image, url); image.set_src(url); let handler = web::add_event_listener_with_bool(&image, "load", callback, true); *callback_ref.borrow_mut() = Some(handler); } #[cfg(not(target_arch = "wasm32"))] fn reload(&self) {} } // === Utils === /// ...
Rust
0
xtend_from_slice(&eval_proof.poe_proof_vec[..]); let proof = NiEvalProof { y_l_vec, y_r_vec, c_l_vec, c_r_vec, poe_proof_vec, f_const: eval_proof.f_const.clone(), d, b, }; return proof; } } impl...
Rust
0
import tkinter as tk import random import os all_images = os.listdir('images') # 编写代码, 在游戏开始的时候, 随机展示一张图片 cur_pic = def clear(): input_word.delete(0, 'end') # 定义一个主窗口 win = tk.Tk() # 窗口宽高为500 win.geometry('500x500') # 窗口的标题 win.title('成语猜猜猜') # 显示成语图片 img = tk.PhotoImage(file='images/' + cur_pic) img_label ...
Python
1
clone() } else { format!("{:?}", r).to_string() } }; let show_regs = |r_vec: &[Reg]| { let mut s = "".to_string(); for r in r_vec { s = s + &show_reg(*r) + &" ".to_string(); } s }; fo...
Rust
0
_name: *const c_char) -> c_int; pub fn libvlc_vlm_seek_media( p_instance: *mut libvlc_instance_t, psz_name: *const c_char, f_percentage: c_float) -> c_int; pub fn libvlc_vlm_show_media( p_instance: *mut libvlc_instance_t, psz_name: *const c_char) -> *const c_char; pub fn libvlc_vlm_get_media...
Rust
0
'孔': 'zv', '巡': 'zv', '延': 'zv', '趾': 'zv', '跄': 'zv', '跪': 'zv', '踵': 'zv', '躐': 'zv', '迮': 'zv', '遏': 'zv', '邋': 'zv', '孜': 'zw', '跷': 'zw', '踢': 'zw', '蹾': 'zw', '迈': 'zw', '迕': 'zw', '这': 'zw', '违': 'zw', '逛': 'zw', '逞': 'zw', '逡...
Python
1
n: &semver::Version, yanked: bool) -> CargoResult<()> { let repo = app.git_repo.lock().unwrap(); let repo = &*repo; let repo_path = repo.path().dir_path(); let dst = index_file(&repo_path, krate); commit_and_push(repo, || { let prev = try!(File::open(&dst).read_to_string()); ...
Rust
0
nal_day = Some( try_consume_exact_digits(s, 3, padding) .and_then(NonZeroU16::new) .ok_or(error::Parse::InvalidDayOfYear)?, ); Ok(()) } /// Month of the year, zero-padded (`01`-`12`) pub(crate) fn fmt_m(f: &mut Formatter<'_>, date: Date, padding: Padding) -> fmt::Result { p...
Rust
0
tType = X509_V_ERR_UNSUPPORTED_CONSTRAINT_TYPE, X509UnsupportedConstraintSyntax = X509_V_ERR_UNSUPPORTED_CONSTRAINT_SYNTAX, X509UnsupportedNameSyntax = X509_V_ERR_UNSUPPORTED_NAME_SYNTAX, X509CrlPathValidationError= X509_V_ERR_CRL_PATH_VALIDATION_ERROR, X509ApplicationVerification = X509_V_ERR_APPLICATI...
Rust
0
import numpy as np class platform: def calculate_platform_offset(previous_x:int, previous_y:int): offset_x = random_number = np.random.randint(-100, 100) offset_y = random_number = np.random.randint(40, 151) print(f'Offset x: {offset_x}, Offset y: {offset_y}') new_x = previous_x ...
Python
1
unsafe { TODO: call ffi::gtk_font_chooser_set_filter_func() } //} fn set_font(&self, fontname: &str) { unsafe { ffi::gtk_font_chooser_set_font(self.to_glib_none().0, fontname.to_glib_none().0); } } fn set_font_desc(&self, font_desc: &pango::FontDescription) { unsafe...
Rust
0
services: Services::new(), } } /// Adds a system to the [`Application`] pub fn add_system(&mut self, system: System) { self.scheduler.add(system); } /// Adds a service to the [`Application`] pub fn add_service<T: IntoService>(&mut self, service: T) { self.serv...
Rust
0
from build123d import * pip_count = 6 lego_unit_size = 8 pip_height = 1.8 pip_diameter = 4.8 block_length = lego_unit_size * pip_count block_width = 16 base_height = 9.6 block_height = base_height + pip_height support_outer_diameter = 6.5 support_inner_diameter = 4.8 ridge_width = 0.6 ridge_depth = 0.3 wall_thickness...
Python
1
fer //! to the files in the dev directory for sample implementations. //! //! Creating a bdev for any supported device type is now as simple as: //! ```ignore //! let uri = "aio:///tmp/disk1.img?blk_size=512"; //! bdev::Uri::parse(&uri)?.create().await?; //! ``` use std::{collections::HashMap, convert::TryFrom...
Rust
0
ount_id.clone(), in_token_remaining: to_yocto("2.5").into(), in_token_paid_unclaimed: to_yocto("2.5").into(), in_token_paid: to_yocto("2.5").into(), total_shares: to_yocto("5").into(), start_time: sale.start_time.clone(), duration: sale.duration.cl...
Rust
0
et result = get_scalar( instruction_words, vec![("x9", const_(0xeed85f2300, 64))], memory, "x15", ); assert_eq!(result.value_u64().unwrap(), 0xffffdead); } #[test] fn ldrsb_wn_xn() { let mut memory = Memory::new(Endian::Big); memory .store(0xeed85f2300, const_(0x...
Rust
0
# config.py from __future__ import annotations import os from pathlib import Path from typing import Optional, Dict from dotenv import load_dotenv def _load_env(dotenv_path: Optional[str] = None) -> None: """ Load .env. If no path is provided, search upwards from CWD for a '.env' file. """ if dotenv...
Python
1
ata| { if data.undo_valid { env.set(druid::theme::BUTTON_DARK, env.get(druid::theme::BUTTON_DARK)); env.set(druid::theme::BUTTON_LIGHT, env.get(druid::theme::BUTTON_LIGHT)); env.set(druid::theme::BORDER_LIGHT, env.get(druid::theme::BORDER_LIGHT)); ...
Rust
0
_positions) # 4. Calculate the actual correction as a product of the effective charges, exponential decay term, and phase factor # the phase factor is based on the distance of the G-vector and atomic positions phase = np.exp(1j * np.einsum('ia,nma->inm', g_positions, distances_bohr)) ''...
Python
1
0: Self, currency_id_1: Self) -> Option<Self> { match (currency_id_0, currency_id_1) { (CurrencyId::Token(token_symbol_0), CurrencyId::Token(token_symbol_1)) => { Some(CurrencyId::DEXShare(token_symbol_0, token_symbol_1)) } _ => None, } } } /// Note the pre-deployed ERC20 contracts depend on `Currenc...
Rust
0
import os API_KEY = os.getenv('9a19db152424baf1aa1e20de497d038a0997ba45') VALID_STOCKS = ['AAPL', 'GOOGL', 'MSFT', 'AMZN', 'TSLA', 'NFLX', 'FB', 'NVDA', 'AMD', 'SPY', 'ABCL', 'ACET'] MARKOV_MATRIX = { 'UP': {'UP': 0.6, 'DOWN': 0.3, 'STABLE': 0.1}, 'DOWN': {'UP': 0.2, 'DOWN': 0.5, 'STABLE': 0.3}, 'STABLE':...
Python
1
ss('HammerOn')[0] hammer_n0 = hammer_on.getSpannedElements()[0] hammer_n1 = hammer_on.getSpannedElements()[1] self.assertEqual(hammer_n0.getSpannerSites()[0], hammer_on) self.assertEqual(hammer_n1.getSpannerSites()[0], hammer_on) pull_off = s.flatten().getElementsByClass('PullOf...
Python
1
# to make multiple sub-images for training and test by cropping the whole images # coded by syshin (180428) import numpy as np import os import skimage.io IMG_SIZE = [2336,3504] SUB_IMG_SIZE = 768 if __name__ == '__main__': save_root_path = '../HRF/all_768' if not os.path.isdir(save_root_path): ...
Python
1
ns for addressing limitations in underperforming task categories - Discuss implications for general vs. specialized cognitive architectures ANALYSIS STANDARDS: - Support ALL claims with specific evidence from benchmark results - Be honest about failures and unexpected outcomes across different cognitive domains - Focu...
Python
1
import subprocess import elftools import elftools.elf from elftools.elf.elffile import ELFFile from emulator import * from unirop import * def load_gadgets(path, arch): gadgets = subprocess.check_output("ROPgadget --binary %s | grep -e \"0x[[:xdigit:]]* :\"" % path, shell=True) gadget_addrs = [int(gadget.split...
Python
1
import subprocess # Replace with your video path video_path = "video.mp4" # Replace with your Youtube stream key (get from Youtube Studio) youtube_stream_key = "ptv1-prvf-rwe4-0wx9-99pm" def start_stream(): """Starts live stream using ffmpeg.""" command = [ "ffmpeg", "-re", # Loop playback "-i...
Python
1
pq.upsert(s, 0.0); p.dist_to[s] = 0.0; while let Some((v, _)) = pq.pop() { for edge in g.adj(v) { relax(p, edge, &mut pq); } } } fn relax<E>(p: &mut WeightedPath<E>, e: E, pq: &mut IndexMinPQ<f64>) where E: Directed + NonNegative, { let v = e.from(); let w = e.to(); if p.dist_to[v] + e.weight() < p.dist_...
Rust
0
` and `TransactionPool` we require this // extension to be a `Weak` reference. // That's also the reason why it's being registered lazily instead of // during initialization. transaction_pool: RwLock<Option<Weak<dyn sp_transaction_pool::OffchainSubmitTransaction<Block>>>>, extensions_factory: RwLock<Box<dyn Extens...
Rust
0
5VVVVs0sHupVXVVVs/sHupUPM snn_M nnnnn[U5$s snnfs snnfs snnnnf)xA sane ordering of signatures to check, first to last Topological sort of edges as given by ``edge`` and ``supercedes`` listmaptuplerrrrr...
Python
1
')], tp_print=['store: 0x%x', '__entry->store'], ) singular_tp('start_tile', args=[TracepointArg(type='uint16_t', var='bin_h', c_format='%u'), TracepointArg(type='uint16_t', var='yoff', c_format='%u'), TracepointArg(type='uint16_t', var='bin_w', c_format='%u'), TracepointArg(type...
Python
1
import torch from torch import nn from torch.nn import functional as F class Encoding(nn.Module): """Encoding Layer: a learnable residual encoder. Input is of shape (batch_size, channels, height, width). Output is of shape (batch_size, num_codes, channels). Args: channels: dimension of the ...
Python
1
at!("[{}ms]", time.as_millis()) }; println!("{} {} {}", self.task_id(), &self.descr, status,); self.current_task += 1; } pub fn end_task(&mut self) { self.finish_task(false, !self.verbose); } pub fn end_verbose_task(&mut self) { self.finish_task(false, false); ...
Rust
0
}, topology::config::{DataType, SourceConfig}, }; use bytes::Bytes; use chrono::{TimeZone, Utc}; use derive_is_enum_variant::is_enum_variant; use futures::{future, sync::mpsc, Future, Sink, Stream}; use serde::{Deserialize, Serialize}; use std::{net::SocketAddr, path::PathBuf}; use tokio::{ self, codec::{By...
Rust
0
urn_interm_indices), \ use_checkpoint=use_checkpoint) # freeze some layers if backbone_freeze_keywords is not None: for name, parameter in backbone.named_parameters(): for keyword in backbone_freeze_keywords: if keyword in name: ...
Python
1
64,i64)>) -> HashSet<(i64,i64,i64,i64)> { let mut candidates: HashSet<(i64,i64,i64,i64)> = HashSet::new(); for (x,y,z,w) in hypercubes { for i in -1..=1 { for j in -1..=1 { for k in -1..=1 { for h in -1..=1 { candidates.insert((x+i,...
Rust
0
def snake_case_to_pascal_case(s): words = s.split('_') pascal_case = ''.join(word.capitalize() for word in words) return pascal_case # Input string in snake_case snake_case_string = input("Enter a string in snake_case: ") # Convert to Pascal case pascal_case_result = snake_case_to_pascal_case(snake_case_s...
Python
1
\x06\xe2\xd5m\xac\xa0\ 2i\xf2\x13p\xf1\xa4*Zh\xfc%\xa8\xdb\xdfM\ 6\xb7\x05\x85\xcc\xbeN\x99\xa2i\x8bw5\xf46\xf7\ W2\xdej&I\xa7\xb6\x82\xc9,\xec\xc5\xa6\x98\xc2\ \xe2C,\xfew\x9a\xd0\xda\xaaN\xb1\x07N\x9fN\xf8\ i\xa3\xb4G\xc4\xf7\xde.\x96\x7f\x13x&\xee\xd6\xfa\ \xe6MJit\x99\xb5=>\xc7\xec\xb6\x9a\x04\xbav\ \xb5s{kt\xf7\xf...
Python
1
# Copyright (c) 2021, Riverbank Computing Limited # All rights reserved. # # This copy of SIP is licensed for use under the terms of the SIP License # Agreement. See the file LICENSE for more details. # # This copy of SIP may also used under the terms of the GNU General Public # License v2 or v3 as published by the Fr...
Python
1
descriptors, pointers, etc.) /// given in their arguments are valid before the completion of the async I/O. pub struct IoUring { ring: io_uring::concurrent::IoUring, token_table: Mutex<Slab<Arc<IoToken>>>, } impl Drop for IoUring { fn drop(&mut self) { // By the end of the life of the io_uring ins...
Rust
0
"Status response"); return Ok(Response { message }); } Err(_) => { thread::sleep(time::Duration::from_millis(100)); } }; counter += 1; if counter >= 5 { ...
Rust
0
nly time youll be able to see it again password_hash = generate_password_hash(password.strip()) upsert_setting("USER_PASSWORD_HASH", password_hash, conn) else: password_hash = app.config.get_setting("USER_PASSWORD_HASH", "") if args is None or args.update_key or not args.update_passwor...
Python
1
import sys from contextlib import redirect_stdout from io import StringIO from unittest import mock import pytest from packaging.version import Version from litgpt.__main__ import main def test_cli(): out = StringIO() with pytest.raises(SystemExit), redirect_stdout(out), mock.patch("sys.argv", ["litgpt", "-...
Python
1
v[1] if func == 'get_h_file_md5': rootPath = sys.argv[2] get_h_file_md5(rootPath) elif func == 'insert_pile_to_h_file': rootPath = sys.argv[2] insert_pile_to_h_file(rootPath) add_simple_cxx_test(rootPath) elif func == 'analy_h_cu_file': dir_path = sys.argv[2] ...
Python
1
line in assigns: contribs = [del_comment(x).strip() for x in line.split('or')] distances, volume = self.extract_target_values(contribs[0]) new_contribs = self.extract_contributions(contribs) contributions = [] for contrib in new_contribs: a...
Python
1
, puzzles: Vec::new(), current_puzzle: 0, current_puzzle_move: 1, puzzle_status: String::from("Use the search below.") } } } // Checks if the notation indicates a promotion and return the piece // if that's the case. fn check_promotion(notation: &str) -> Opt...
Rust
0
str(&counter.to_string()); *counter += 1; } } } fn fn_arg_name(fn_arg: &ast::Expr) -> Option<String> { match fn_arg { ast::Expr::CastExpr(cast_expr) => fn_arg_name(&cast_expr.expr()?), _ => { let s = fn_arg .syntax() .descendants()...
Rust
0
,尝试远程HTTP:{e}") if use_remote_img and img_backend: try: img = img_backend.txt2img(Txt2ImgParams(prompt=theme, width=896, height=512, guidance=guidance)) except Exception as e2: st.warning(f"远程HTTP...
Python
1
from django.conf.urls.defaults import * from views import * urlpatterns = patterns( '', (r'^$', status), (r'^version$', version), (r'^plots$', route(GET=get_plot_list, POST=create_plot_optional_tree)), (r'^plots/(?P<plot_id>\d+)$', route(GET=get_plot, PUT=update_plot_and_tree, DELETE=remove_plot)),...
Python
1
(); self.cache.write(&html_path, &show_file_name, result2).expect("fail to write cache"); } let result_item = ChannelItem { extra: Some(ChannelItemType::Show(ChannelShowItem { postid: postid, page: extra.page })), ...
Rust
0
#!/usr/bin/env python import sinedon from matplotlib import pyplot as plt from pyami import mrc import leginon.leginondata as leginondata import os import argparse def parseArguments(): parser=argparse.ArgumentParser(description='Plot recent gain reference data') parser.add_argument('n', metavar='n', type=int, help...
Python
1
# -*- coding: utf-8 -*- # # @File: setup.py # @Author: Jiaxiang Tang (@ashawkey) # @Date: 2023-04-15 10:33:32 # @Last Modified by: Haozhe Xie # @Last Modified at: 2024-12-27 19:18:33 # @Email: ashawkey1999@gmail.com # @Ref: https://github.com/ashawkey/torch-ngp import torch from setuptools import setup from torc...
Python
1
display_name=f"problem_{i}", data=problem_xml, ) ) def setUp(self): super().setUp() self.user = UserFactory() self.addCleanup(set_current_request, None) self.request = get_mock_request(self.user) @classmethod...
Python
1
number, actual_height: batch_number, }); } match self.batch_sender.try_send(batch) { Ok(_) => { self.inc_deliver_batch(STATUS_SUCCESS); debug!(self.log, "Inserted batch {}", batch_number); *self.last_seen_batch.writ...
Rust
0
e mantissa is required. pub const REQUIRED_MANTISSA_SIGN: u128 = 1 << 5; /// Exponent notation is not allowed. pub const NO_EXPONENT_NOTATION: u128 = 1 << 6; /// Positive sign before the exponent is not allowed. pub const NO_POSITIVE_EXPONENT_SIGN: u128 = 1 << 7; /// Positive sign before the exponent is required. pu...
Rust
0
class Solution: def hasTrailingZeros(self, nums: List[int]) -> bool: evennums = 0 for num in nums: if num % 2 == 0: evennums += 1 if evennums == 2: return True return False
Python
1
# -*- coding: utf-8 -*- ############################################################################ # This file is part of the 4D Light Field Benchmark. # # # # This work is licensed under the Creative Commons ...
Python
1
("2024-11-01", "Toussaint"), ("2024-11-28", "Jour de la République"), ("2024-12-25", "Noël"), ) def test_l10n_en_us(self): # http://mokili.free.fr/jours_feries.php self.assertLocalizedHolidays( "en_US", ("2024-01-01", "New Year's Day"), ...
Python
1
}) return steps # 2. look straight ahead if step_text.lower() == 'look straight ahead': steps.append({ 'type': 'special', 'obj_name': 'look straight ahead', 'obj_num': None, 'tool': parsed_tool }) return steps # 3. explore the s...
Python
1
" { it "should be fetched token" { let expected_token = "<PASSWORD>".to_string(); insert_into(tokens).values(NewToken { user_id: 1, token: expected_token.clone()}).execute(&*conn); let actual = target_repository.resolve(expected_token.clone()); assert!(actual.is_o...
Rust
0
finiteBlocks(AIR); character_ref .execute(&CharacterTransaction::inventory( InventoryTransaction::insert(item.clone()), )) .unwrap(); // Check notification assert_eq!( sink.drain(), vec![CharacterChange::Inventory(InventoryChange { slots: Arc:...
Rust
0
line = line.strip() # Skip empty lines and comments if not line or line.startswith('#'): continue # Check for valid KEY=value pattern if not re.match(r'^[A-Za-z_][A-Za-z0-9_]*\s*=.*$', l...
Python
1
from pathlib import Path import random from tqdm import tqdm from ddddocr import DdddOcr from PIL import Image from pyrogram.enums import ParseMode from embykeeper.telegram.session import ClientsSession from embykeeper.cli import AsyncTyper from embykeeper.config import config app = AsyncTyper() bot = "jmsembybot" ...
Python
1
r of two. However, to use the <tt>GX_REPEAT</tt> or <tt>GX_MIRROR</tt> modes for \\a wrap_s and \\a wrap_t"] #[doc = " the width and height, respectively, must be a power of two.<br><br>"] #[doc = ""] #[doc = " \\note The \\a tlut_name is used to indicate which texture lookup table (TLUT) to use for the ind...
Rust
0
att(&mut self) -> MISC_RSSI_PRE_ATT_W { MISC_RSSI_PRE_ATT_W { w: self } } #[doc = "Bit 0 - XTAL: if set to 1, the clk_ready threshold is set to a lower value"] #[inline(always)] pub fn misc_xtal_low_clk_ready_th_en(&mut self) -> MISC_XTAL_LOW_CLK_READY_TH_EN_W { MISC_XTAL_LOW_CLK_READY_T...
Rust
0
cfg = cc::Build::new(); let cflags = [ "-Wall", "-Wcast-qual", "-Wdate-time", "-Wendif-labels", "-Wextra", "-Wextra-semi", "-Wformat=2", "-Winit-self", "-Wlogical-op", "-Wmissing-declarations", "-Wmissing-include-dirs", ...
Rust
0
from langchain_core.tracers.stdout import ( ConsoleCallbackHandler, FunctionCallbackHandler, ) __all__ = ["FunctionCallbackHandler", "ConsoleCallbackHandler"]
Python
1
ondelete='RESTRICT', name='fk_student_departments_educators_mentor_id'), nullable=True ) student_rep_id: Mapped[UUID] = mapped_column(ForeignKey('students.id', ondelete='RESTRICT', name='fk_student_departments_students_student_rep'), nullable=True ) assistant_rep_id: Mapped[UUID]...
Python
1
(where: { p:"p1" }) { p }}"#), @r###"{"data":{"deleteOneParent":{"p":"p1"}}}"### ); Ok(()) } // "a PM to CM relation" should "delete the parent from other relations as well" #[connector_test(schema(additional_schema_2))] async fn pm_cm_other_relations_2(runner: Runner) -> Te...
Rust
0
alpha *= np.pi/180.0 beta *= np.pi/180.0 gamma *= np.pi/180.0 h = mt.abc2h(a, b, c, alpha, beta, gamma) cell = Cell(h) natoms = 0 body = filedesc.readline() qatoms = [] names = [] masses = [] while (body.strip() != "" and body.strip() != "END"): natoms += 1 name = body[12:16]...
Python
1
; // Setup the console. let console = components::console::ConsoleComponent::new(board_kernel, uart_mux).finalize(()); // Create the debugger object that handles calls to `debug!()`. components::debug_writer::DebugWriterComponent::new(uart_mux).finalize(()); // // Setup the process inspection cons...
Rust
0
ty(ast_methods.len()); let mut errs = vec![]; for astmeth in ast_methods { match self.c_method(vm, astmeth) { Ok(m) => { methods.insert(m.name.clone(), Gc::new(m)); } Err(mut e) => { errs.extend(e.drain(....
Rust
0
val { return Interval { left: self.left + addend.left, right: - (-self.right - addend.right) } } } impl<'a> std::ops::Add<Interval> for &'a Interval { type Output = Interval; fn add(self, addend: Interval) -> Interval { return Interval { left: self.left + addend.left, right: - (-self...
Rust
0
sys: could not write bindings to file"); } #[derive(Debug)] struct Callbacks; impl bindgen::callbacks::ParseCallbacks for Callbacks { fn int_macro(&self, name: &str, _value: i64) -> Option<bindgen::callbacks::IntKind> { // Must match sys::DiscordVersion if name.ends_with("_VERSION") { ...
Rust
0
.unwrap(), 0, bytemuck::cast_slice(&spot_light_raw), ); state.queue.write_buffer( binding_resource_container .buffers .get("point_light_buffer") .unwrap(), 0, bytemuck::cast_slice(...
Rust
0
set_bit(64); assert_eq!(&[0b1000_0001, 1], &map.map[..]); map.set_bit(99); assert_eq!(&[0b1000_0001, (1 << 35) | 1], &map.map[..]); } #[test] fn test_clear_bit() { let mut map = BufferMap::new(100); map.map[0] = 0xff; map.clear_bit(0); assert_eq!(&[...
Rust
0
s: //! write regs: //! insn groups: jump //! operands: 1 //! X86Operand(X86Operand { size: 8, avx_bcast: X86_AVX_BCAST_INVALID, avx_zero_opmask: false, op_type: Imm(568865) }) //! //! 0x100d: xorl %r12d, %r12d //! insn id: 327 //! bytes: [69, 49, 228] //! read regs: //! wri...
Rust
0
from flask import Flask from modelos import db, Terreno, Usuario, Diretoria, Tesouraria app = Flask(__name__) app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:///terrenos.db' app.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = False db.init_app(app) with app.app_context(): # Drop all tables db.drop_all() print...
Python
1
<Scope> { None } } impl std::fmt::Debug for ModuleScope { fn fmt(&self, f: &mut Formatter<'_>) -> Result<(), Error> { write!(f, "ModuleScope({:p})", self) } } #[cfg(test)] mod tests { use super::super::typ::Type; use super::{ClosureScope, ModuleScope, ScopeLike, ScopeResolution}; ...
Rust
0
from scrapy import Request, Spider from scrapy.utils.test import get_crawler from scrapy_fake_useragent.middleware import RandomUserAgentMiddleware from scrapy_fake_useragent.providers import FakerProvider def test_cannot_load_providers(mocker): faker_provider_constructor = mocker.patch.object(FakerProvider, '__...
Python
1
# [1] https://doi.org/10.1063/5.0021923 # Extending nudged elastic band method to reaction pathways # involving multiple spin states # Zhao, Watanabe, Nakatani, Nakayama, Xu, Hasegawa, 2020 import numpy as np def middle_is_meisc(energies: np.ndarray, allow_fast_flip: bool = False) -> bool: """Determi...
Python
1
かつ伸長可能で、コンパイル時にサイズ不明な状況でヒープに確保することが可能 pub fn interact_method() { // 変数とデータの相互作用法 // 1.ムーブ // String型は以下のようなデータで構成されている // { "ptr":["H","e","l","l","o"], "len":5, capacity:5 } // ptr はヒープに保管され、len は文字列の大きさ(byte)、capacityは許容量 // もし String型の変数a を変数b にそのまま代入した場合、変数b は変数a と同じ場所にある ptr を参照する // そ...
Rust
0
fn register_metrics(logger: &Logger, registry: &Registry) { if let Err(error) = registry.register(Box::new(AGGREGATE_DURATION.clone())) { debug!(logger, "Failed to register AGGREGATE_DURATION"; "error" => ?error); } if let Err(error) = registry.register(Box::new(AGGREGATE_ERRORS_COUNT.clone())) { ...
Rust
0
); } #[test] fn check_invalid_groups() { PrincipalActor::group("", "123456789012", "/", "group-name", "AGPAA2B3C4D5E6F7HIJK").unwrap_err(); PrincipalActor::group("aws", "", "/", "group-name", "AGPAA2B3C4D5E6F7HIJK").unwrap_err(); PrincipalActor::group("aws", "123456789012", "",...
Rust
0
d_actual, label='Basic LSTM') plt.title('Basic LSTM Prediction') plt.legend() plt.subplot(1, 2, 2) plt.plot(y2_test_actual, label='Actual') plt.plot(y2_pred_actual, label='Enhanced LSTM') plt.title('LSTM with Chaos Features') plt.legend() plt.tight_layout() plt.show() # 评估结果 ...
Python
1
T>) -> T { self.normal.x * plane.normal.x + self.normal.y * plane.normal.y + self.normal.z * plane.normal.z + self.bias * plane.bias } /// Returns the intersection distance of the provided line given a point and direction, or `None` if none occurs. pub fn interse...
Rust
0
A.Resize(width=512, height=512), A.ColorJitter(p=0.2), A.Normalize(mean=[0.5, 0.5, 0.5], std=[0.5, 0.5, 0.5], max_pixel_value=255.0), ToTensorV2(), ]) augmented = transform(image=input_img) input_tensor = augmented["image"].to(device) with torch.no_grad(): pred...
Python
1
) { let req_no = api .blobs_get_req_send(&dto::BlobsGetIn::new(blob_id.clone())) .await?; *wants = Wants::Requested(req_no); } } Ok(true) } async fn recv_blobs_get( &mut self, _api: &mut ApiCall...
Rust
0
import os from formatDialogue import export_d_files_to_csv, export_dialog_files_file_name from elevenlabsScript import generate_audio_from_csv print("Exporting dialogue files to CSV:") DIALOG_EXTRACT_DIR = os.getenv("DIALOG_EXTRACT_DIR", "dialog-extract") NARRATION_OUTPUT_CSV = os.getenv("NARRATION_OUTPUT_CSV", "narr...
Python
1
elf } } #[doc = "Bit 23"] #[inline(always)] pub fn spi_slave_cs_pol(&mut self) -> SPI_SLAVE_CS_POL_W { SPI_SLAVE_CS_POL_W { w: self } } #[doc = "Bits 7:12"] #[inline(always)] pub fn spi_master_cs_pol(&mut self) -> SPI_MASTER_CS_POL_W { SPI_MASTER_CS_POL_W { w: self } ...
Rust
0
0. , 1. ]], [[ 0.87758256, -0.47942554, 0. ], [ 0.47942554, 0.87758256, 0. ], [ 0. , 0. , 1. ]]]) :param theta: The angles to form the rotation matrix(ces) for :return: The rotation matrix(ces) corresponding t...
Python
1
# final checkpoint df_out.to_pickle(checkpoint) logger.info(f"Completed inference for {language} - {prefix} at {datetime.datetime.now()}") logger.info(f"{'='*80}") # Final memory cleanup torch.cuda.empty_cache() gc.collect() print_gpu_memory() # Entry point if __name__ == "__main__":...
Python
1
import datetime import time from Cores.CoreFunc import core_func def contral_func(sustain_days=0, sustain_hours=0, sustain_minutes=0, sustain_seconds=0,\ single_capture_days=0, single_capture_hours=0, single_capture_minutes=0, single_capture_seconds=0,\ brush_threshold=10): sustain_ti...
Python
1
get_omega(field, n, seed=1) omega2 = get_omega(field, n, seed=4) # FFT # x = fft(poly, omega=omega, n=n, test=True, enable_profiling=True) x = poly.evaluate_fft(omega, n) # IFFT x2 = [b / n for b in fft_helper(x, 1 / omega, field)] poly2 = Poly.interpolate_fft(x2, omega) logging.info(pol...
Python
1
() -> Self { StageStatus::Initial } } // ============== // === Result === // ============== /// The result of executing the lexer on a given input. #[derive(Clone, Debug)] pub struct LexingResult<T> { /// The kind of the result, representing _how_ the lexer completed. pub kind: ResultKind, ...
Rust
0
let (x_l, ctx) = likelihood_internal(dsl, x_tp, &ctx, env, x); (l + x_l, ctx) }) } else { (f_l, ctx) } } None => { let s = dsl.display(expr); ...
Rust
0
void); opj_free(p_tcd_marker_info as *mut libc::c_void); }; } /* ----------------------------------------------------------------------- */ // Copyright 2019 The Fuchsia Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. use { ...
Rust
0
"""商品数据模型""" import mongoengine from .product import Product from .. import settings class Stock(mongoengine.Document): """ 商品数据模型: individual: 是否是独立的商品(非产品子类) attributes: 由产品生成时记录该商品的选项信息 product: 父级产品类(当individual为False时) name: 商品名称(当individual为True时) description: 商...
Python
1