text
string
label_name
string
labels
int64
GL_TRUE { return Err(EglCallError::SwapInterval); } Ok(()) } /// `[EGL 1.0]` Terminate an EGL display connection. pub fn terminate(display: EGLDisplay) -> EglCallResult<()> { if unsafe { ffi::eglTerminate(display) } != EGL_TRUE { return Err(EglCallError::Terminate); } Ok(()) } /// ...
Rust
0
ds) { /* * The ground */ let ground_size = 5.0; let ground_height = 0.1; let collider = ColliderBundle { shape: ColliderShape::cuboid(ground_size, ground_height, ground_size), position: [0.0, -ground_height, 0.0].into(), ..ColliderBundle::default() }; commands ...
Rust
0
} #[test] fn test_payment_fail() { SETTING.get_payment_mut().pay_threshold = Int256::from(5); SETTING.get_payment_mut().close_threshold = Int256::from(-10); let mut d = DebtKeeper::new(); let ident = get_test_identity(); // generate a bunch of traffic for ...
Rust
0
Block => "outside of a block (like a `do` or `struct`)", NestType::Curly => "without an opening '{'", NestType::Paren => "without an opening '('", NestType::Square => "without an opening '['", NestType::String => "without an opening \"", ...
Rust
0
self.taskmanager.is_finished(): menu.addAction(self.tr("删除"), lambda rows=selected_rows: [self.files_table.removeRow(row.row()) for row in reversed(rows)]) if len(selected_rows) == 1: file_item = self.files_table.item(selected_rows[0].row(), 0) save_path_item = self.files_ta...
Python
1
h((format!("{:.1} Pa/s\n", omega.unpack()), config.omega_rgba)); } } } results } /*********************************************************************************************** * Events *********************************************************************...
Rust
0
updated = m.remove_column(j).remove_row(j); prop_assert!(relative_eq!(m_updated, m_chol_updated, epsilon = 1.0e-7)); } } } } ); gen_tests!(complex, RandComplex<f64>); gen_tests!(f64, RandScalar<f64>); #![feature(use_extern_macros)] extern crate julia; exter...
Rust
0
self.k_xanes.absorbing_element = Element("Pt") with pytest.raises(ValueError, match="The absorbing elements for spectra are different"): XAS.stitch(self.k_xanes, self.k_exafs, mode="XAFS") def test_stitch_l23(self): self.l2_xanes.y[0] = 0.1 with pytest.warns(UserWarning...
Python
1
to_writer(writer, access_tokens)?; Ok(()) } } impl AccessToken { pub fn new<I, K, S>(account_id: I, access_key: K, secret_key: S) -> AccessToken where I: Into<String>, K: Into<String>, S: Into<String> { AccessToken { account_id: account_id.into(), access_key: access_key.into(), secret_key: secr...
Rust
0
Widget) -> c_int; #[cfg(any(feature = "v3_20", feature = "dox"))] pub fn gtk_widget_get_focus_on_click(widget: *mut GtkWidget) -> gboolean; #[cfg(any(feature = "v3_18", feature = "dox"))] pub fn gtk_widget_get_font_map(widget: *mut GtkWidget) -> *mut pango::PangoFontMap; #[cfg(any(feature = "v3_18",...
Rust
0
vec![m], Type::i32 )) // mov [rbp + fi + w*u + e * u] } } } } ...
Rust
0
参数结构体 """ def __init__(self): r""" :param _RequestFromSource: 请求来源,WEB 前端;CLIENT 客户端 :type RequestFromSource: str :param _Instances: 实例列表 :type Instances: list of InstanceOpsDto :param _CheckFather: 检查父任务类型, true: 检查父任务; false: 不检查父任务 :type CheckFather:...
Python
1
from __future__ import unicode_literals, division, absolute_import, print_function __license__ = 'GPL v3' __copyright__ = '2011, Grant Drake' import six import re from calibre.constants import iswindows from calibre.ebooks.oeb.base import XPath RE_BOOK_MGNS = re.compile(r'(?P<cssid>#\w+\s+)?(?P<selector>(?<!\.)\b...
Python
1
) add_more_button.send_keys(Keys.RETURN) delete_form = expected_conditions.presence_of_element_located((By.ID, 'id_form-1-DELETE')) delete_checkbox = self.selenium.find_element(By.ID, 'id_form-1-DELETE') if not delete_checkbox.is_selected(): delete_checkbox.send_keys(Keys.SPA...
Python
1
gen (method , structural , js_class = "GPUQueue" , js_name = writeTexture)] #[doc = "The `writeTexture()` method."] #[doc = ""] #[doc = "[MDN Documentation](https://developer.mozilla.org/en-US/docs/Web/API/GPUQueue/writeTexture)"] #[doc = ""] #[doc = "*This API requires the following crate features ...
Rust
0
scan_opt: unsafe { std::mem::transmute::<FfiScanOpt, i32>(scan_opt) }, alias: None, params: Some(pb::QueryParams { tables: vec![], columns: vec![], is_all_columns: false, limit: None, predicate: None, ...
Rust
0
} else { (*stcb).asoc.asconf_queue.tqh_last = (*aparam).next.tqe_prev } *(*aparam).next.tqe_prev = (*aparam).next.tqe_next; if !(*aparam).ifa.is_null() { sctp_free_ifa((*aparam).ifa); } free(aparam as *mut libc::c_void); } /* * cleanup from a bad asconf ack parameter */ unsafe ...
Rust
0
itive.createBox( imath.Box3f( imath.V3f( -1 ), imath.V3f( 1 ) ) ) cornerIds = [ 5 ] cornerSharpnesses = [ 10.0 ] m.setCorners( IECore.IntVectorData( cornerIds ), IECore.FloatVectorData( cornerSharpnesses ) ) creaseLengths = [ 3, 2 ] creaseIds = [ 1, 2, 3, 4, 5 ] # note that these are vertex ids creaseSharp...
Python
1
} } #[derive(Clone, Copy, Eq, PartialEq)] pub struct NameRecordType(pub u16); newtype_enum! { impl debug NameRecordType { End = 0, Ipv4 = 1, Ipv6 = 2 } } #[derive(Debug)] pub struct NameRecord<'a> { pub record_type: NameRecordType, pub record_value: &'a [u8], } impl<'a> N...
Rust
0
def check_dict_case(dict): """ Given a dictionary, return True if all keys are strings in lower case or all keys are strings in upper case, else return False. The function should return False is the given dictionary is empty. Examples: check_dict_case({"a":"apple", "b":"banana"}) should return ...
Python
1
#[doc = "*Required features: 'Win32_System_Ioctl'*"] pub const FILE_DEVICE_DATALINK: u32 = 5u32; #[doc = "*Required features: 'Win32_System_Ioctl'*"] pub const FILE_DEVICE_DEVAPI: u32 = 71u32; #[doc = "*Required features: 'Win32_System_Ioctl'*"] pub const FILE_DEVICE_DFS: u32 = 6u32; #[doc = "*Required features: 'Win3...
Rust
0
directory let data_dir = &std::env::var("DATA_DIR").unwrap_or_else(|_| "./data".to_string()); let path = req.match_info().query("filename"); // First, construct the path to a normal page let mut page_path = PathBuf::from(data_dir); page_path.push("pages"); page_path.push(&path); page_path...
Rust
0
de config. #[derive(StructOpt, Debug, Serialize, Deserialize)] pub struct Run { /// Path to a node configuration file. #[structopt(long, short = "c")] pub node_config: PathBuf, /// Path to a database directory. #[structopt(long, short = "d")] pub db_path: PathBuf, /// Listen address for node...
Rust
0
import os, json from pathlib import Path HOME = Path(os.path.expandvars(r"%USERPROFILE%")) DEFAULT_DATA_DIR = HOME / "Documents" / "NexaLite" class Paths: def __init__(self): self.data_dir = DEFAULT_DATA_DIR self.bootstrap = self.data_dir / "bootstrap.json" self.functions = se...
Python
1
.primary.map) .canonical_pt_per_trip .keys() .cloned() .collect(); for trip in trips { if let Some(agent) = ui.primary.sim.trip_to_agent(trip) { if let Some(trace) = ui.primary.sim.trace_route(agent, &ui.primary.map, None) { traces.push(trace); ...
Rust
0
#------------------------------------------------------------------------------ # Script for building hl2ss_ulm.so # Install OpenCV and FFmpeg libraries on your system then run this script #------------------------------------------------------------------------------ import os # Settings ----------------------------...
Python
1
type MinNominatorStk = MinNominatorStk; // type WeightInfo = parachain_staking::weights::SubstrateWeight<Runtime>; // } parameter_types! { pub const DisabledValidatorsThreshold: Perbill = Perbill::from_percent(17); } // impl pallet_session::Config for Runtime { // type Event = Event; // type ValidatorId = <Self a...
Rust
0
ng()), tl: env.add_sym("tl".to_string()), quote: env.add_sym("'".to_string()), } } } <gh_stars>0 // Since [RFC002](../rfcs/002-merge-types-terms-syntax.md), the following tests don't raise an // unbound type variable error anymore. Instead, the variable is interpreted as a term varia...
Rust
0
_img_comp_dest).w as OPJ_SIZE_T), ); /* Allocate output component buffer if necessary */ if (*l_img_comp_dest).data.is_null() && l_start_offset_src == 0 as libc::c_int as libc::c_ulong && l_start_offset_dest == 0 as libc::c_int as libc::c_ulong && src_data_stride == (*l_img_com...
Rust
0
from MAVProxy.modules.lib import grapher from MAVProxy.modules.lib import multiproc import errno import socket import copy graph_count = 1 class Graph_UI(object): """docstring for ClassName""" def __init__(self, mestate): self.mestate = mestate self.xlim = None global graph_count ...
Python
1
, true); } } // Generated by `scripts/generate.js` use std::os::raw::c_char; use std::ops::Deref; use std::ptr; use std::cmp; use std::mem; use utils::c_bindings::*; use utils::vk_convert::*; use utils::vk_null::*; use utils::vk_ptr::*; use utils::vk_traits::*; use vulkan::vk::*; use vulkan::vk::{VkStructureType,R...
Rust
0
# This file is part of pyunicorn. # Copyright (C) 2008--2025 Jonathan F. Donges and pyunicorn authors # URL: <https://www.pik-potsdam.de/members/donges/software-2/software> # License: BSD (3-clause) # # Please acknowledge and cite the use of this software and its authors # when results are used in publications or publi...
Python
1
reponame>Manishearth/aster use std::iter::IntoIterator; use syntax::ast; use syntax::codemap::{DUMMY_SP, Span, Spanned, respan}; use syntax::ptr::P; use block::BlockBuilder; use ident::ToIdent; use invoke::{Invoke, Identity}; use lit::LitBuilder; use path::{IntoPath, PathBuilder}; use qpath::QPathBuilder; use str::To...
Rust
0
&self.msg } } <filename>src/fs/list_file_holders.rs use clap; use winapi; use winapi::_core::ptr::null_mut; use crate::common; use crate::common::errors::ErrorString; #[derive(Default)] struct WCharString { data: Vec<winapi::um::winnt::WCHAR> } impl WCharString { fn new(size: usize) -> Self { let...
Rust
0
eep(1.8) await putt.edit("**DI BIKIN DARI KONTOLL**") await asyncio.sleep(1.8) await putt.edit("**MUKALU PERSIS KONTOLL**") await asyncio.sleep(1.8) await putt.edit("**DASAR ANAK NGONTOLLLL**") await asyncio.sleep(1.8) await putt.edit("**NOLEP KONTOLL**") await asyncio.sleep(1.8) awa...
Python
1
gs(vm: &VirtualMachine, args: PyFuncArgs) -> Result<String, PyObjectRef> { // Handle 'sep' kwarg: let sep_arg = args .get_optional_kwarg("sep") .filter(|obj| !obj.is(&vm.get_none())); if let Some(ref obj) = sep_arg { if !objtype::isinstance(obj, &vm.ctx.str_type()) { retu...
Rust
0
ethyst::core::transform::TransformBundle; use amethyst::renderer::types::DefaultBackend; use amethyst::renderer::{RenderFlat2D, RenderToWindow, RenderingBundle}; use amethyst::ui::{RenderUi, UiBundle}; use amethyst::utils::fps_counter::FpsCounterBundle; use amethyst::{ApplicationBuilder, LogLevelFilter, LoggerConfig}; ...
Rust
0
# -*- coding: utf-8 -*- # Part of Odoo. See LICENSE file for full copyright and licensing details. { 'name': "Sales - Project", 'summary': "Task Generation from Sales Orders", 'description': """ Allows to create task from your sales order ============================================= This module allows to g...
Python
1
fg(any(feature = "v2_58", feature = "dox"))] fn set_keepalive_interval(&self, interval: u32) { unsafe { soup_sys::soup_websocket_connection_set_keepalive_interval(self.as_ref().to_glib_none().0, interval); } } #[cfg(any(feature = "v2_56", feature = "dox"))] fn set_max_incomi...
Rust
0
############################################################################ # Copyright (C) SchedMD LLC. ############################################################################ import atf import pytest IMEX_CHANNEL_PATH = "/dev/nvidia-caps-imex-channels" NUM_NODES = 8 CHANNEL_MAX = NUM_NODES TTY_MAJOR_NUM = 4 ...
Python
1
if y2 < cuty or x1 > cutx: continue if y2 >= cuty and y1 <= cuty: y1 = cuty if x2 >= cutx and x1 <= cutx: x2 = cutx if i == 2: if y2 < cuty or x2 < cutx: ...
Python
1
categories:str = get(f'https://www.speedrun.com/api/v1/games/{game_id}/categories', allow_redirects=False).json() for category in categories['data']: if category['type'] == 'per-game': category_id = category['id'] break ...
Python
1
import modelx as mx import pytest def test_duplicate_model_ref(): m, s = mx.new_model(), mx.new_space() m.x = "model x" assert s.x == "model x" s.x = "space x" assert s.x == "space x" del s.x assert s.x == "model x" del m.x with pytest.raises(AttributeError): s.x m._imp...
Python
1
els = labels[mask] # adjust boxes img = img[patch[1]:patch[3], patch[0]:patch[2]] boxes[:, 2:] = boxes[:, 2:].clip(max=patch[2:]) boxes[:, :2] = boxes[:, :2].clip(min=patch[:2]) boxes -= np.tile(patch[:2], 2) return img, b...
Python
1
import bencoding import hashlib import datetime import textwrap from scripts.artifact_report import ArtifactHtmlReport from scripts.ilapfuncs import logfunc, tsv, is_platform_windows def timestampcalc(timevalue): timestamp = (datetime.datetime.utcfromtimestamp(int(timevalue)/1000).strftime('%Y-%m-%d %H:%M:%S')) ...
Python
1
#!/usr/bin/python3 to_json_string = __import__('3-to_json_string').to_json_string my_list = [1, 2, 3] s_my_list = to_json_string(my_list) print(s_my_list) print(type(s_my_list)) my_dict = { 'id': 12, 'name': "John", 'places': [ "San Francisco", "Tokyo" ], 'is_active': True, 'info': { 'age...
Python
1
10, gpio_13, 115_200); //! ``` mod lpi2c; mod lpspi; mod lpuart; include!(concat!(env!("OUT_DIR"), "/imxrt1010.rs")); pub use pads::*; mod bases { define_base!(GPIO_AD, 0x401F_8010, 0x401F_80C0); define_base!(GPIO_SD, 0x401F_804C, 0x401F_80FC); define_base!(GPIO, 0x401F_8088, 0x401F_8138); } <reponame>Fo...
Rust
0
ould not create user agent file"); f.write_all(format!("static RUST_VERSION: &'static str = \"{}\";", rust_version).as_bytes()) .expect("Unable to write user agent"); } /* gamelift/2015-10-01/service-2.json: "protocol":"json" support/2013-04-15/service-2.json: "protocol":"json" */ // expand to u...
Rust
0
"""Set of functions that gets and prints arp entries""" from json.decoder import JSONDecodeError import requests import json import warnings warnings.filterwarnings('ignore', message='Unverified HTTPS request') headers = {"Content-Type": 'application/yang-data+json', 'Accept': 'application/yang-data+json'} def _chec...
Python
1
#[doc = "Bit 14 - UTMI Clock Usable"] #[inline(always)] pub fn clkusable(&self) -> CLKUSABLE_R { CLKUSABLE_R::new(((self.bits >> 14) & 0x01) != 0) } } <reponame>only-cliches/rws-dev // Copyright 2018-2021 the Deno authors. All rights reserved. MIT license. use deno_core::serde::Serialize; #[der...
Rust
0
pub next: *mut k_list_node_st, pub prev: *mut k_list_node_st, } impl Default for k_list_node_st { fn default() -> Self { let mut s = ::core::mem::MaybeUninit::<Self>::uninit(); unsafe { ::core::ptr::write_bytes(s.as_mut_ptr(), 0, 1); s.assume_init() } } }...
Rust
0
PyBytes { PyBytes::new(_py, self.inner.write_to_vec().unwrap().as_slice()) } pub fn batch_id(&self) -> usize { self.inner .batch_id .expect("please call forward_id before get batch_id") } } macro_rules! add_dense_func2batch_data { ($(($typ:ty, $attr:ident)),*) ...
Rust
0
let mut list_104 = scope_101.start_list(true, Some("item")); for item_103 in var_102 { #[allow(unused_mut)] let mut entry_105 = list_104.entry(); entry_105.string(item_103); } list_104.finish(); } writer.finish(); Ok(aws_smithy_http::body:...
Rust
0
rate) fn interrupt0() { unsafe { cpu::CPU_TIME += 1; kernel::update_kernel_time(1); } } <reponame>clearloop/coda #![macro_use] macro_rules! impl_from { ($name:ident, $from:ty) => { impl From<$from> for $name { fn from(source: $from) -> $name { $name(source...
Rust
0
ouble, optional, tag="21")] pub dividend: ::core::option::Option<f64>, ///特别股息(例如,每10股派特别股息0.5元,则该字段值为0.05) #[prost(double, optional, tag="22")] pub sp_dividend: ::core::option::Option<f64>, ///时间戳 #[prost(double, optional, tag="23")] pub timestamp: ::core::option::Option<f64>, } #[derive(Cl...
Rust
0
self.username_field.text = "DEFAULT_USERNAME" self.email_field.text = "DEFAULT" self.contact_field.text = "DEFAULT" def edit_details(self, *args): self.name_field.disabled = False self.username_field.disabled = False self.email_field.disabled = False ...
Python
1
1969, 4)); t.push((1970, 1)); t.push((1971, 2)); t.push((1972, 2)); t } fn main() { let mut total: u8 = 0; let flights = project_flights(); for &(_, flights) in flights.iter() { total += flights; } println!("{}", total); } use super::system_prelude::*; #[derive(Default)] pu...
Rust
0
_broadcast = xp.broadcast_tensors else: _broadcast = xp.broadcast_arrays x1_, x2_ = _broadcast(x1, x2) x1_ = xp.moveaxis(x1_, axis, -1) x2_ = xp.moveaxis(x2_, axis, -1) res = x1_[..., None, :] @ x2_[..., None] return res[..., 0, 0] # isdtype is a new function in the 2022.12 array API ...
Python
1
#!/usr/bin/env python3 # # Functional test that boots a kernel and checks the console # # Copyright (c) 2023-2024 Linaro Ltd. # # Authors: # Philippe Mathieu-Daudé # Marcin Juszkiewicz # # SPDX-License-Identifier: GPL-2.0-or-later import os from qemu_test import QemuSystemTest, Asset, skipSlowTest from qemu_test ...
Python
1
import argparse from ranx import fuse, Run parser = argparse.ArgumentParser() parser.add_argument('--run1', type=str, help='Path to the first run file.') parser.add_argument('--run2', type=str, help='Path to the second run file.') parser.add_argument('--weight1', type=float, help='Weight of the first run.') parser.add...
Python
1
ic!{ static ref STANDARD_COLORS : [Color;8] = [ Color::from_rgb(0, 0, 0), Color::from_rgb(205, 0, 0), Color::from_rgb(0, 205, 0), Color::from_rgb(205, 205, 0), Color::from_rgb(64, 64, 238), Color::from_rgb(205, 0, 205), Color::from_rgb(0, 205, 205), Co...
Rust
0
import numpy as np import pandas as pd import matplotlib.pyplot as plt import seaborn as sns from sklearn.model_selection import train_test_split from sklearn.preprocessing import StandardScaler from sklearn.decomposition import PCA import warnings from SA import simulated_annealing warnings.filterwarnings("ignore") ...
Python
1
import requests from bs4 import BeautifulSoup import os class OlxScraper: def __init__(self, url, min_price=0, max_price=0, output_filename="output.txt", search_term=""): self.url = url self.min_price = min_price self.max_price = max_price self.output_filename = output_filename ...
Python
1
from fuzzconfig import FuzzConfig from interconnect import fuzz_interconnect import re configs = [ { "cfg": FuzzConfig(job="ECLK0", device="LIFCL-40", sv="../shared/route_40.v", tiles=["CIB_R56C48:ECLK_0", "CIB_R56C49:BMID_0_ECLK_1", "CIB_R56C50:BMID_1_ECLK_2", "CIB_R56C51:ECLK_3"]), "rc": (55, 48)...
Python
1
of!(Foo => 1); /// let bar = Bar { foo: Foo(10, 20, 0.5), x: 30 }; /// assert_eq!(fr1.chain(fr2).get(&bar), &20); /// # } /// ``` pub fn chain<V>(&self, fr: FieldRef<U, V>) -> FieldRef<T, V> { unsafe { FieldRef::<T, V>::from_offset(self.offset + fr.offset) } } /// Convert `FieldRef<...
Rust
0
distance_from_plane_squared = (p - sphere.center).magnitude_squared(); if distance_from_plane_squared > sphere.radius * sphere.radius { return false; } let radius_on_plane = (sphere.radius * sphere.radius - distance_from_plane_squared).sqrt(); let coordinates = self.baryce...
Rust
0
000) OP_56(0x00) Switch( ( (Expr.PushReg, 0x0), Expr.Return, ), (0x00000000, 'loc_3D97'), (0x00000001, 'loc_3D9D'), (-1, 'loc_3DA3'), ) def _loc_3D97(): pass label('loc_3D97') SetScenaFlags(ScenaFlag(0x0000, 7, 0x7)) Jump('...
Python
1
_vserver: i32 = 236; #[allow(non_upper_case_globals)] pub const TARGET_NR_mbind: i32 = 237; #[allow(non_upper_case_globals)] pub const TARGET_NR_set_mempolicy: i32 = 238; #[allow(non_upper_case_globals)] pub const TARGET_NR_get_mempolicy: i32 = 239; #[allow(non_upper_case_globals)] pub const TARGET_NR_mq_open: i32 = 24...
Rust
0
# Solution file import numpy as np # Take input from user A = np.array(list(map(int, input().split()))) B = np.array(list(map(int, input().split()))) # Compute inner product inner_product = np.inner(A, B) # Compute outer product outer_product = np.outer(A, B) # Print results print(inner_product) print(outer_produc...
Python
1
: ptr::null_mut(), }; let mut result = ptr::null_mut(); // This has the lifetime of pwdbuf match libc::getpwuid_r(libc::getuid(), &mut pwdbuf, buf.as_mut_ptr(), buf.len(), &mut result) { 0 if !result.is_null() => { // Copy pw_gecos CSt...
Rust
0
ePhot apply scale have different y") np.testing.assert_almost_equal(phot4.flux, phot3.flux, 15, "two ways to have makePhot apply scale have different flux") # Check images with invalid wcs raise ValueError im4 = galsim.ImageD(65, 65) im5 = galsim.ImageD(65, 65, wcs=ga...
Python
1
from google.generativeai import configure, GenerativeModel from config import Config configure(api_key=Config.GEMINI_API_KEY) gemini_text = GenerativeModel('gemini-pro') gemini_vision = GenerativeModel('gemini-pro-vision')
Python
1
# Extracted from ./data/repos/pandas/pandas/tests/frame/methods/test_between_time.py rng = date_range("1/1/2000", "1/5/2000", freq="5min") ts = DataFrame(np.random.randn(len(rng), 2), index=rng) ts = tm.get_obj(ts, frame_or_series) stime = time(0, 0) etime = time(1, 0) inclusive = inclusive_endpoints_fixture filtered...
Python
1
ref() { params.push("filter[environment_scope]", environment_scope); } } } /// Get the variable from a project. #[derive(Debug, Builder)] #[builder(setter(strip_option))] pub struct ProjectVariable<'a> { /// The project to get the variable from. #[builder(setter(into))] project: Nam...
Rust
0
class Solution: def check(self, nums: List[int]) -> bool: prev = nums[0] pos = 0 for i in range(1, len(nums)): if nums[i] < prev: pos = i break prev = nums[i] tmp = nums[pos:] + nums[:pos] nums.sort() if tmp == n...
Python
1
#!/usr/bin/env python3 import sys import PyPDF2 import argparse def read_pdf(pdf_path): """读取PDF文件内容""" try: with open(pdf_path, 'rb') as file: # 创建PDF阅读器对象 pdf_reader = PyPDF2.PdfReader(file) # 获取页数 num_pages = len(pdf_reader.pages) ...
Python
1
=> tokens.push(LexToken::Exclamation), '+' => tokens.push(LexToken::Plus), '/' => tokens.push(LexToken::Slash), '"' => tokens.push(LexToken::Quote), '\\' => match chars.next() { Some(Ok(c)) => { tokens.push(LexToken::Character(c)); }, Some(Err(e)) => return Err(e), None => bre...
Rust
0
mb': {'en': 'Rembarrnga'}, 'rmc': {'en': 'Carpathian Romani'}, 'rmd': {'en': 'Traveller Danish'}, 'rme': {'en': 'Angloromani'}, 'rmf': {'en': 'Kalo Finnish Romani'}, 'rmg': {'en': 'Traveller Norwegian'}, 'rmh': {'en': 'Murkim'}, 'rmi': {'en': 'Lomavren'}, 'rmk': {'en': 'Romkun'}, 'rm...
Python
1
NTERRUPT_CLEAR_A) -> &'a mut W { self.bit(variant.into()) } #[doc = "`0`"] #[inline(always)] pub fn no_clear(self) -> &'a mut W { self.variant(REG_GPIO_0_INTERRUPT_CLEAR_A::NO_CLEAR) } #[doc = "`1`"] #[inline(always)] pub fn clear(self) -> &'a mut W { self.variant...
Rust
0
alues([None, 2, 3], [11, 12, 13]) assert result == [11, 12, 3], f"Unexpected result {result}" result = node_resources._update_values([1, 2, None], [11, 12, 13]) assert result == [1, 2, 13], f"Unexpected result {result}" def test_update_from_str(): result = node_resources._update_from_str([None, 2, 3],...
Python
1
Vec<Task>, &'static str> { Task::all(pool).await.map_err(|_| "Error retrieving tasks") } pub async fn create_task(todo: String, pool: &SqlitePool) -> Result<(), &'static str> { let new_task = NewTask { description: todo }; Task::insert(new_task, pool) .await .map(|_| ()) .map_err(|_...
Rust
0
path = [] used = [0]*7 # 1~6 숫자 사용 여부를 기록할 리스트 # 0부터 시작, 3개를 뽑은 경우 종료 def recur(level): # 1. 기저조건 if level == 3: print(*path) return # 2. 후보군을 반복하면서 for i in range(1, 7): # i가 이미 뽑혔다면, continue 해라(중복제거된 순열) # 아래 코드 문제 -> 'in' = O(len(path)) # 시간초과 위험 높다. ...
Python
1
Metrics") logger.info("-" * 30) for result in self.test_results: if result.performance_metrics: logger.info(f"{result.test_name}:") for metric, value in result.performance_metrics.items(): logger.info(f...
Python
1
(); let port = args[2].parse::<usize>().expect("Invalid port"); let addresses: Vec<String> = args[3] .split(",") .map(|x| format!("{}:{}", x, port)) .collect(); let devices = Device::list().unwrap(); // try to parse the passed device name as a number, // otherwise accept it...
Rust
0
key: String, meta_only: bool, ) -> RedisResult<AIModel> { let args = modelget_cmd_build(key, meta_only); let model = if meta_only { if self.debug { println!("AI.MODELGET {:?}", args) } let meta: AIModelMeta = redis::cmd("AI.MODELGE...
Rust
0
u=[u, ""], p=[p, ""], c=c) w = curs.execute("SELECT username FROM user_info WHERE username = ?", [u]) if (w.fetchone()): return rt("login.html", error=["Username already taken", ""], u=["", ""], p=[p, ""], ...
Python
1
RTT + RTTVar + SYN assert_eq!(timers.nak.next_instant() - start, 2 * (4 * rtt_mean + rtt_variance + syn)); // 4 * RTT + RTTVar + SYN assert_eq!(timers.exp.next_instant() - start, 4 * rtt_mean + rtt_variance + syn); } #[test] fn update_rtt_exp_lower_bound(si...
Rust
0
mut ball_x = 12.; let mut ball_y = 7.; let mut dx = 3.5; let mut dy = -3.5; let mut platform_x = 10.; let mut stick = true; let platform_width = 5.; let platform_height = 0.2; // build camera with following coordinate system: // (0., 0) .... (SCR_W, 0.) // (0., SCR_H) .... ...
Rust
0
ERROR: type should be string, got " https://en.wikipedia.org/wiki/Conversion_between_quaternions_and_Euler_angles\n # Body Z-Y-X sequence\n \n q0 = q.w\n q1 = q.x\n q2 = q.y \n q3 = q.z \n \n p0 = max(np.float32(-1.0), min(np.float32(1.0), 2*(q0*q2 - q3*q1)))\n p = asin(p0) \n \n r0 = 2*(q0*q1 + q2*q3) \n r1 = 1-2*(q1*q1+q2*q2)\n if r0 == 0 and 11 == 0:\n print \"r: atan(0,0)!\", q \n r = 0\n else:\n r = atan2(r0, r1)\n \n y0 = 2*(q0*q3 + q1*q2)\n y1 = 1 - 2*(q2*q2 + q3*q3)\n if y0 == 0 and y1 == 0:\n print \"y: atan(0,0)!\", q \n y = 0\n else:\n y = atan2(y0, y1)\n \n self.r = degrees(r)\n self.p = degrees(p)\n self.y = degrees(y)\n \n def __str__(self):\n return \"(%+07.2f, %+07.2f, %+07.2f)\" % (self.r, self.p, self.y)\n def __repr__(self):\n return __str__(self) \n\ndef ArcQQ(a, b):\n assert isinstance(a, Quat)\n assert isinstance(b, Quat)\n\n q = Mul(b, Conj(a)) # order may be wrong, but this is what works for determining the bodyframe rotation needed to go from a->b\n th = np.float32(2)*atan2(Mag(q.Vec()), q.w)\n return th, q\n\ndef ArcVV(a, b): # returns the angle in radians and the angle vector\n assert isinstance(a, Vec3)\n assert isinstance(b, Vec3)\n ma = Mag(a)\n mb = Mag(b)\n \n if ma != 0 and mb != 0:\n th = np.float32(acos(min(max(-1, Dot(a,b)/(ma*mb)), 1)))\n r = Cross(a,b)\n else:\n th = np.float32(0)\n r = Vector(0.0, 0.0, 0.0)\n \n return th, r\n\ndef Arc(a,b):\n if isinstance(a, Quat) and isinstance(b, Quat):\n return ArcQQ(a,b)\n elif isinstance(a, Vec3) and isinstance(b, Vec3):\n return ArcVV(a,b)\n else:\n raise exception\n\ndef Degrees(a):\n if isinstance(a, Vec3):\n return Mul(180/radians(180), a)\n else:\n return np.float32(a)*180/radians(180)\n\ndef QuantizeF(a, m, r):\n q = float(m)/float(r)\n aq = int(a/q)*q\n return aq\n\ndef QuantizeV(a, m, r):\n return Vector(QuantizeF(a.x,m,r), QuantizeF(a.y,m,r), QuantizeF(a.z,m,r))\n\ndef Quantize(a, m, r):\n if isinstance(a, Vec3):\n return QuantizeV(a,m,r)\n elif isinstance(a, np.float32):\n return QuantizeF(a,m,r)\n else:\n raise exception\n\ndef get_params( line):\n\tparams = []\n\tfor item in line.split(','):\n\t\tparams.append( float(item) )\n\treturn params\n \n \ndef main():\n\tS = Simulation()\n\twith open(\"quatout.txt\") as input_file:\n\t\tfor line in input_file:\n\t\t\tline = line.strip()\n\t\t\tpars = get_params(line)\n\t\t\tqn = Quat()\n\t\t\tqn.w = pars[0]\n\t\t\tqn.x = pars[1]\n\t\t\tqn.y = pars[2]\n\t\t\tqn.z = pars[3]\n\t\t\tyaw = pars[4]\n\t\t\tpitch = pars[5]\n\t\t\troll = pars[6]\n\t\t\tS.step(qn, \"Roll %+04.0f Pitch %+04.0f Yaw %+04.0f\" % (roll, pitch, yaw))\n \nmain()\n"
Python
1
elf) -> io::Result<()> { Ok(()) } } // FIXME: right now this raw stderr handle is used in a few places because // std::io::stderr_raw isn't exposed, but once that's exposed this impl // should go away impl io::Write for Stderr { fn write(&mut self, data: &[u8]) -> io::Result<usize> { ...
Rust
0
std::{ fs::{self, read_dir}, path::{Path, PathBuf}, }; use tom_syntax::{TomlDoc}; use crate::util::{print_difference, test_data_dir}; enum ExpectErrors { Yes, No, Maybe, } fn dir_tests(paths: &[&str], expect_errors: ExpectErrors) { for path in collect_tests(paths) { // Load TOML docum...
Rust
0
impl_bit_vec_adapter!(u64, bit_store); } impl_stack_only_space_usage!(Rank9Cell); impl_stack_only_space_usage!(Level2); impl<Store: SpaceUsage> SpaceUsage for Rank9<Store> { fn is_stack_only() -> bool { false } fn heap_bytes(&self) -> usize { self.bit_store.heap_bytes() + self.counts.heap_bytes() ...
Rust
0
from __future__ import (absolute_import, division, print_function, unicode_literals) import six from nose.tools import assert_equal, assert_in import matplotlib.type1font as t1f import os.path import difflib def test_Type1Font(): filename = os.path.join(os.path.dirname(__file__), 'cmr10....
Python
1
} if stat.scltimeout().bit_is_set() { i2c.stat.write(|w| w.scltimeout().set_bit()); return Err(Self::SclTimeout); } Ok(()) } } <reponame>StevenBlack/aws-sdk-rust<filename>sdk/sagemakerfeaturestoreruntime/src/error.rs // Code generated by software.amazon.smit...
Rust
0
och, total_epochs); } fn output_epoch_end(&self, _current_epoch: u64, _total_epochs: u64) { println!("") } } <gh_stars>1-10 #[macro_use] extern crate serde_derive; extern crate serde_json; extern crate serde; extern crate pom; use std::io::stdin; use std::collections::{ HashSet, HashMap, }...
Rust
0
d, self, self._root) elif _on == 65289: self._raw_payload = self._io.read_bytes(self.length) _io__raw_payload = KaitaiStream(BytesIO(self._raw_payload)) self.payload = System.MsgSensorAidEvent(_io__raw_payload, self, self._root) elif _on == 22: ...
Python
1
def sqrt_binary_search(S, tolerance=1e-10): low = 0 high = S while high - low > tolerance: mid = (low + high) / 2 if mid * mid > S: high = mid else: low = mid return (low + high) / 2 result = sqrt_binary_search(10) print(result) # 输出 3.1622776601683795
Python
1
.stdout_lock, "{}", char.escape_unicode()).unwrap(); } } fn process_str(&mut self, fonts: &[ab_glyph::FontVec], buffer: &[u8]) { for (start, end, char) in buffer.char_indices() { let char_as_string = char.to_string(); let original_bytes = &buffer[start..end]; ...
Rust
0
cations for higher acc. for n in range(N): for k in range(K): heatmap = heatmaps[n][k] px = int(preds[n][k][0]) py = int(preds[n][k][1]) if 1 < px < W - 1 and 1 < py < H - 1: diff = np.arr...
Python
1
_inv = torch.eye(out_features, device=B.device, dtype=B.dtype) - torch.matmul(B, B_TB_inv_B_T) grad_scale = (1 / lora_scaler ** 2) # 用B的违逆压缩梯度作为A的梯度 grad_A_fp32 = grad_scale * torch.matmul(B_TB_inv, grad_A_orin_fp32) + torch.matmul(X, A) # 用A的违逆压缩梯度作为B的梯度 grad_B_fp32 = g...
Python
1