text
string
label_name
string
labels
int64
BitXor => "bvxor", SignedGreaterEquals => "bvsge", SignedGreaterThan => "bvsgt", SignedLessEquals => "bvsle", SignedLessThan => "bvslt", UnsignedGreaterEquals => "bvuge", UnsignedGreaterThan => "bvugt", UnsignedLessEquals => "bvule", UnsignedLessTh...
Rust
0
rn_dict = copy.deepcopy(measurements_dict) while self.setting_i2c: time.sleep(0.1) self.measuring = True length = self.sensor.get_distance() self.value_set(0, length) self.measuring = False return self.return_dict def set_i2c_address(self, args_dict):...
Python
1
Clone, Copy, Debug)] // TODO(fxbug.dev/29669): Derive phy parameters based on Table 9-250 and 9-253. pub struct VhtOperation { pub vht_cbw: VhtChannelBandwidth, // u8 pub center_freq_seg0: u8, // Channel index pub center_freq_seg1: u8, // Channel index pub basic_mcs_nss: VhtMcsNssMap, ...
Rust
0
: Target, target_spec: Option<String>, path: PathBuf, }, #[error("Failed to parse the chip description '{path}'.")] FailedChipDescriptionParsing { #[source] source: RegistryError, path: PathBuf, }, #[error("Failed to change the working directory to '{path}'.")...
Rust
0
cdn_key_akamai.update_cdn_key_akamai( project_id, location, akamai_cdn_key_id, updated_hostname, updated_akamai_key, ) assert akamai_cdn_key_id in response.name assert updated_hostname in response.hostname response = get_cdn_key.get_cdn_key(project_id, location, ...
Python
1
-> &dyn (::std::any::Any) { self as &dyn (::std::any::Any) } fn as_any_mut(&mut self) -> &mut dyn (::std::any::Any) { self as &mut dyn (::std::any::Any) } fn into_any(self: ::std::boxed::Box<Self>) -> ::std::boxed::Box<dyn (::std::any::Any)> { self } fn descriptor(&self...
Rust
0
PatFieldsNamed, PatFieldsPositional, PatGroup, PatLit, PatOr, PatPath, PatRange, PatStruct, RangeEnding, }; use camp_util::bail; use crate::parser::{Parse, ParseBuffer, ShouldParse}; use crate::{parse_typelike_path, CampResult, ParseError}; impl Parse for Pat { type Context = (); fn parse_with(input: &m...
Rust
0
} else { Some(Fr(Wrapping(v as u32))) } } fn to_repr(&self) -> FrRepr { FrRepr::from(*self) } fn is_odd(&self) -> bool { (self.0).0 % 2 != 0 } fn char() -> FrRepr { Fr(MODULUS_R).into() } fn multiplicative_generator() -> Fr { Fr(Wr...
Rust
0
import sys from tabulate import tabulate import csv def main(): """ Entry point that orchestrates the program's logic: - Retrieves and validates the filename from command line arguments. - Processes and reads the CSV file, returning structured data. - Displays the formatted data using t...
Python
1
[inline(always)] pub fn add_vec_in_place<T: Copy + Add<Output = T>>(x: &mut [T], y: &[T]) { x.iter_mut().zip(y.iter()).for_each(|(x, &y)| *x = *x + y); } #[allow(dead_code)] #[inline(always)] pub fn sub_vec_in_place<T: Copy + Sub<Output = T>>(x: &mut [T], y: &[T]) { x.iter_mut().zip(y.iter()).for_each(|(x, &y)...
Rust
0
codes, used_codes, is_global, }); } } None } #[cfg(test)] mod tests { use super::*; use crate::ast_parser; use crate::ast_parser::AstParser; use std::rc::Rc; #[test] fn test_parse_ignore_comments() { let source_code = r#" // deno-lint-ignore no-explicit-any no-em...
Rust
0
clone(); // replace para.dynamically. sys_context format : "[[\"p1\":\"v1\"],[\"p2\":\"v2\"]...]" match instance.sys_context.get(CONTEXT_DYNAMIC_PARA) { Some(paras) => { let paras: Vec<(String, String)> = serde_json::from_str(paras)?; if paras.is_empty() { return ...
Rust
0
# dataset settings dataset_type = 'Globe230kDataset' data_root = 'data/Globe230k_v3' # train: beijing; val: wuhan crop_size = (512, 512) modality_keys = ['rgb', 'ndvi', 'vvvh', 'dem'] # ['rgb', 'ndvi', 'vvvh', 'dem'] train_pipeline = [ dict(type='LoadMultimodalImageFromFile', modality_keys=modality_keys,...
Python
1
import datetime from typing import Optional, List from fastapi import HTTPException from sqlalchemy.types import DateTime from app.domain.interfaces.IPurchaseRepository import IPurchaseRepository from app.application.services.PurchaseDetailService import PurchaseDetailService from app.domain.models.Purchase import Pur...
Python
1
mpleter): highlight_color = "ansibrightyellow" # Bright yellow background for groups primary_attribute = 'sAMAccountName' fallback_attribute = 'name' def get_ldap_filter(self): return "(objectClass=group)" class OUCompleter(ADObjectCompleter): highlight_color = "ansibrightmagenta" # ...
Python
1
::stdin() .read_line(&mut user_guess) .expect("How dare you!?"); let user_guess:i32 = match user_guess .trim() .parse() { Ok(num) => num, Err(_) => { if guess_game_process_wrong_answ...
Rust
0
from azure.keyvault.secrets import SecretClient from azure.identity import DefaultAzureCredential class Secret_Manager: @staticmethod def create_secret_client(keyVaultName): credential = DefaultAzureCredential(exclude_visual_studio_code_credential=True) KVUri = f"https://{keyVaultName}.vault.az...
Python
1
import threading from typing import ( Any, Optional, runtime_checkable, TYPE_CHECKING, TypeVar, Union, ) from typing_extensions import Protocol from galaxy.model.base import ModelMapping from galaxy.model.tool_shed_install import HasToolBox from galaxy.security.idencoding import IdEncodingHelp...
Python
1
("Failed to deliver batch"); } } use lv2_raw::*;type LV2_URID_Map = LV2UridMap; type LV2_Feature = LV2Feature;type LV2_Handle = LV2Handle; type LV2_Descriptor = LV2Descriptor; type LV2_URID_Unmap = ::std::os::raw::c_void; /* automatically generated by rust-bindgen */ pub const LILV_NS_DOAP: &'static [u8; 30usize] ...
Rust
0
break; // means parent current and sibling are equals no more propagation needed } // now either self.values[siblidx] <self.values[pidx] or current_value < self.values[pidx] trace!("propagating current_value {} sibling {} ? ", current_value, self.values[siblidx]); ...
Rust
0
import os from dotenv import load_dotenv if os.path.exists("config.env"): load_dotenv('config.env', override=True) class Config(object): ##API_KEY get it from dev, dont edit if added API_KEY = os.environ.get("API_KEY", "rv2006rv") #telegram user session str for 4gb limit SESSION_STRING = os.enviro...
Python
1
return resultado # CRUD para Sistema class CRUDSistema(CRUDBase[Sistema, Sistema, Sistema, Sistema]): """Operaciones CRUD específicas para el modelo Sistema""" def get_with_subsistemas(self, session: Session, id: int) -> Optional[Sistema]: """ Obtiene un sistema con sus subsistemas carga...
Python
1
] }; pub const CCertProperty: ::windows_sys::core::GUID = ::windows_sys::core::GUID { data1: 2286821422, data2: 8573, data3: 4570, data4: [178, 164, 0, 14, 123, 187, 43, 9] }; pub const CCertPropertyArchived: ::windows_sys::core::GUID = ::windows_sys::core::GUID { data1: 2286821431, data2: 8573, data3: 4570, data4: [17...
Rust
0
err: last_exception = err raise _t.cast(BadSignature, last_exception) def load(self, f: _t.IO, salt: _t_opt_str_bytes = None) -> _t.Any: """Like :meth:`loads` but loads from a file.""" return self.loads(f.read(), salt) def loads_unsafe( self, s: _t_str_bytes, ...
Python
1
responses = self.infer_engine.infer(prm_infer_requests, request_config=request_config, **self.infer_kwargs) rewards = [] for response in responses: content = response.choices[0].message.content if 'Reward:' not in content: rewards.append(0.) els...
Python
1
#[allow(missing_docs)] #[doc(hidden)] pub struct _CAU_AESIC_CA8; #[doc = "`write(|w| ..)` method takes [cau_aesic_ca8::W](cau_aesic_ca8::W) writer structure"] impl crate::Writable for CAU_AESIC_CA8 {} #[doc = "General Purpose Register 8 - AES Inverse Column Operation command"] pub mod cau_aesic_ca8; // Copyright 2018-2...
Rust
0
import numpy as np import cv2 # 定义函数max_area_extract,用于提取最大面积的轮廓 def max_area_extract(input_chanel): # 将输入通道转换为uint8类型的数组 chanel2 = np.array(input_chanel, dtype='uint8') # 寻找轮廓 contours, hierarchy = cv2.findContours(chanel2, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_NONE) # 如果发现多个轮廓 if len(contours) ...
Python
1
lds)] #[non_exhaustive] pub struct RequiresExpr { pub range: SourceRange, pub r#type: Type, #[serde(rename = "valueCategory")] pub value_category: ValueCategory, } #[derive(Deserialize, Debug)] #[serde(deny_unknown_fields)] #[non_exhaustive] pub struct RestrictAttr { pub range: SourceRange, #[s...
Rust
0
from ash import * #H2O...MeOH fragment defined. Reading XYZ file H2O_MeOH = Fragment(xyzfile="h2o_MeOH.xyz") # Specifying the QM atoms (3-8) by atom indices (MeOH). The other atoms (0,1,2) is the H2O and MM. #IMPORTANT: atom indices begin at 0. qmatoms=[3,4,5,6,7,8] # Charge definitions for whole fragment. Charges f...
Python
1
from ...attrs import LIKE_NUM _num_words = [ "zero", "jeden", "dwa", "trzy", "cztery", "pięć", "sześć", "siedem", "osiem", "dziewięć", "dziesięć", "jedenaście", "dwanaście", "trzynaście", "czternaście", "pietnaście", "szesnaście", "siedemnaście", ...
Python
1
for block in document: if block in ["<listitem>", "</listitem>", "</listitem><listitem>"]: continue for part in _xmlblocks(block): if "<subtitle>" in part: part = re.sub("(?s)</title>\\s*<subtitle>", "</title> <subtitle>", part) ...
Python
1
profile=profile, params=params, network_ok=network_ok ) if self.reboot_var.get() and not self.enable_sip_config and network_ok: self.reboot_device(old_ip, auth, profile) self.log("\n所有设备配置完成!") ...
Python
1
your IdP, you can manage GitHub team membership through your identity provider, which automatically adds and removes team members in an organization. For more information, see "[Synchronizing teams between your identity provider and GitHub](https://help.github.com/articles/synchronizing-teams-between-your-identity-pro...
Rust
0
clitools::CROSS_ARCH1); }); } #[test] fn add_target_explicit() { setup(&|config| { let path = format!("toolchains/nightly-{}/lib/rustlib/{}/lib/libstd.rlib", &this_host_triple(), clitools::CROSS_ARCH1); expect_ok(config, &["rustup", "update", ...
Rust
0
::SECRET_KEY_FETCH => "Worker runner unable to fetch secret key for origin.", ErrCode::SECRET_KEY_IMPORT => "Worker runner unable to import secret key for origin.", ErrCode::VCS_CLONE => "Worker runner unable to retrieve project source to build.", ErrCode::BUILD => "Worker runner fai...
Rust
0
i32 + y) as usize] != 0 { return true; } } false } pub fn save_block_to_field( block: &Block, field: &mut [i32; (FIELD_HEIGHT * FIELD_WIDTH) as usize], ) { for stone in block.stones.iter() { let x: i32 = stone.local_x + block.x; let y: i32 = stone.local_y + bloc...
Rust
0
channels // 2, (1, 1), weight_decay=weight_decay, name = name + '.cv1')(x) maxpool1 = MaxPooling2D(pool_size=(5, 5), strides=(1, 1), padding='same')(x) maxpool2 = MaxPooling2D(pool_size=(9, 9), strides=(1, 1), padding='same')(x) maxpool3 = MaxPooling2D(pool_size=(13, 13), strides=(1, 1), padding='same')(x) ...
Python
1
# random function import random display_cards = ["J","K","Q","A",1,2,3,4,5,6,7,8,9] random_cards_1 = random.sample(display_cards, 1) print("The First Card is: ", random_cards_1) random_cards_2 = random.sample(display_cards, 1) print("The First Card is: ",random_cards_2) # --- new_ran = display_cards.random() print(n...
Python
1
)\n', ((0, 0), (0, 1), (1, 2), (3, 1), (4, 0))), TestInfo('(\n())\n', ((0, 0), (0, 1), (2, 2), (4, 1), (5, 0))), # Same as matched test. TestInfo('{)(]\n', ((0, 0), (0, 1), (2, 0), (2, 1), (4, 0))), TestInfo('(((())\n', ((0, 0), (0, 1), (1, 2), (2, 3)...
Python
1
-> Result<Price, Error> { let bids = bids.bids()?; let mut price_sum_product = Decimal::from(0u8); let mut total = Decimal::from(0u8); for bid in bids { price_sum_product += *bid.price * bid.quantity; total += bid.quantity; } let weighted_avg = Price::new(price_sum_product / to...
Rust
0
, text, f)?; writeln!(f) } StmtKind::GoSub(label) => { if let Some((range, label)) = label { assert_eq!(text[range.start..range.end].parse::<Label>(), Ok(*label)); writeln!(f, "GOSUB {}", label.0) } else { writeln!(f, "GOSUB") } } StmtKind::GoTo { ha...
Rust
0
uate the agent episode_reward = 0 for _ in range(400): action, _ = model.predict(obs, deterministic=True) obs, reward, terminated, truncated, info = env.step(action) episode_reward += reward if terminated or truncated or info.get("is_success", False): print("Reward:",...
Python
1
def menu(): print("\n1 - Max Min Composition") print("2 - Max Product Composition") print("3 - Exit\n") while True: a = [] b = [] n = int(input("Enter number of elements in fuzzy set A: ")) for i in range(n): ele = float(input(f"Enter element {i+1} of A: ")) a.append(ele) ...
Python
1
from __future__ import print_function import os import math import numpy as np import torch import torch.distributed as dist import torch.backends.cudnn as cudnn import tensorboard_logger as tb_logger class BaseTrainer(object): """class for BaseTrainer""" def __init__(self, args): self.args = args ...
Python
1
import torchvision.transforms.v2 as transforms from torch import float32 # 1. Define the transformations # The transformations will be applied sequentially. # - Resize to 128x128 # - Convert to Grayscale # - Convert to PyTorch Tensor (scales pixel values to [0, 1]) # - (Optional) Normalize: For grayscale, a common pra...
Python
1
=None, tracks=[]) self.config.init_custom("EQUALIZER", 1) self.config.register_custom("EQUALIZER", eq_bands=[], eq_presets={}) self.config.init_custom(PlaylistScope.GLOBAL.value, 1) self.config.register_custom(PlaylistScope.GLOBAL.value, **_playlist) self.config.init_custom(Play...
Python
1
import importlib from collections import OrderedDict from transformers.models.auto.auto_factory import _BaseAutoModelClass from transformers.models.auto.auto_factory import _LazyAutoMapping as _BaseLazyAutoMapping from transformers.models.auto.configuration_auto import CONFIG_MAPPING_NAMES class _LazyAutoMapping(_Ba...
Python
1
= jvm.attach_current_thread().unwrap(); unsafe { env.call_static_method_unchecked( env.find_class(CONTEXT_CLASS_NAME) .unwrap_or_else(|_| { if env.exception_check().unwrap() { env.exception_clear().unwrap(); ...
Rust
0
StageFlags::FRAGMENT); // set = 0 binding = 1 let scene_params = vk::DescriptorSetLayoutBinding::builder() .binding(1) .descriptor_count(1) .descriptor_type(vk::DescriptorType::UNIFORM_BUFFER) .stage_flags(vk::ShaderStageFlags::FRAGMENT); // set = 0 binding = 2 let sample...
Rust
0
nput); } else { let mut stdin = std::io::stdin(); let _ = stdin.read_to_string(&mut input); } input.to_lowercase(); input } use std::os::unix::net::UnixStream; use std::io::prelude::*; fn main() -> std::io::Result<()> { let mut stream = UnixStream::connect("/var/tmp/fastfreeze/run/f...
Rust
0
_get_mut( &mut self, ) -> Option<( &mut Expr<Ex, Fb, En, Hi>, &mut Expr<Ex, Fb, En, Hi>, &mut OgNullFlavor, &mut bool, )> { match self { Expr_::ObjGet(p0) => Some((&mut p0.0, &mut p0.1, &mut p0.2, &mut p0.3)), _ => None, } } ...
Rust
0
#[inline(always)] pub fn is_uart_ifls_rx4_8(&self) -> bool { *self == UART_IFLS_RXR::UART_IFLS_RX4_8 } #[doc = "Checks if the value of the field is `UART_IFLS_RX6_8`"] #[inline(always)] pub fn is_uart_ifls_rx6_8(&self) -> bool { *self == UART_IFLS_RXR::UART_IFLS_RX6_8 } ...
Rust
0
equency = kwargs.get('frequency', 'd') # 默認日線 # 設定要獲取的欄位 fields = self._get_fields() # 調用 BaoStock API rs = bs.query_history_k_data_plus( symbol, fields, start_date=start_date, en...
Python
1
if abs(dx) > abs(dy): new_x = agent_pos[0] + (1 if dx > 0 else -1) new_y = agent_pos[1] else: new_x = agent_pos[0] new_y = agent_pos[1] + (1 if dy > 0 else -1) ...
Python
1
import numpy as np def MonteCarlo_double(f, g, x0, x1, y0, y1, n): """ Monte Carlo integration of f over a domain g>=0, embedded in a rectangle [x0,x1]x[y0,y1]. n^2 is the number of random points. """ # Draw n**2 random points in the rectangle x = np.random.uniform(x0, x1, n) y = np.ran...
Python
1
import numpy as np from scipy.spatial.transform import Rotation import random import copy def rotate_centered_pointcloud(pt, angle_in_degree=0): ''' caution! this function assumes that point cloud is 0-centered ''' if angle_in_degree == 0: return pt else: perturb_matrix = Rotation.f...
Python
1
] /// #[one_or_many( /// expected = "a single name or a nonempty array of name, with unique elements", /// inner_type = "Name", /// min_length = 1, /// unique_items = true, /// )] /// pub struct OneOrManyNames; /// ``` #[proc_macro_derive(OneOrMany, attributes(one_or_many))] pub fn derive_one_or_many(in...
Rust
0
service: NotifyService, destination: String, notification: Cow<'a, Notification>, } #[derive(sqlx::FromRow)] struct ServiceAndDestination { service: NotifyService, destination: String, } impl NotificationManager { pub fn new( pg_pool: PostgresPool, redis_pool: RedisPool, ...
Rust
0
let mut authorities = Vec::new(); for a in self.parent_chain_authorities.iter() { let addr = Address::from_str(clean_0x(a)).unwrap(); authorities.push(Token::Address(addr)); } tokens.push(Token::Array(authorities)); tokens } } #[derive(Debug, PartialE...
Rust
0
= 0b0; /// 0b1: DAC channel1 trigger enabled and data from the DAC_DHR1 register are transferred three dac_pclk clock cycles later to the DAC_DOR1 register pub const B_0x1: u32 = 0b1; } } /// DAC channel1 trigger selection These bits select the external event used to trigger D...
Rust
0
t_map_pic_240, 240, 20, 16); get_map_pic_test!(get_map_pic_241, 241, 0, 0, "Invalid map ID: 241"); get_map_pic_test!(get_map_pic_242, 242, 0, 0, "Invalid map ID: 242"); get_map_pic_test!(get_map_pic_243, 243, 0, 0, "Invalid map ID: 243"); get_map_pic_test!(get_map_pic_244, 244, 0, 0, "Invalid map ID: 244"); get_map_pic...
Rust
0
("Shutting down watcher {}", watcher.id); if let Some(thread) = watcher.thread.take() { thread.join().unwrap(); } } } } type Job = Box<FnBox + Send + 'static>; enum Message { NewJob(Job), Terminate, } struct Worker { id: usize, thread: Option<threa...
Rust
0
annel, used to tell the task running in /// [`daemon::report_status_events`] about a new event to monitor. /// /// This uses an `UnboundedSender` so that we don't have to await /// while sending the message, which in turn allows the GuardMgr /// API to be simpler. The risk, however, is that there's...
Rust
0
# 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 a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or ...
Python
1
import json import os from datetime import datetime import logging as log import bleach import markdown from flask_login import current_user from app import util from app.util import Constant from app.util.utilRedis import redis_decode_client as redis def getPostLockKey(path): #文章锁定,默认30分钟 key0='post:lock:%s...
Python
1
unwrap(); assert_eq!( ledger.writer.get_data(), format!( "\ \n[✓] Killing Daemon\ \n [✓] Killing zombie daemons.\ \n [✓] Killed daemon PID: [1, 2, 3]\ \n[✓] Starting Daemon\ \n [✓] Daemon spawned\ ...
Rust
0
print("Please Enter the Number with base (Ob,Oo,Ox):") x = input() base, num = x[0:2], x[2:len(x)] if base == 'Ob': num = int(num, base=2) if base == 'Oo': num = int(num, base=8) if base == 'Ox': num = int(num, base=16) print("Please Enter the base (bin,oct,dec,hex):") y = str(input()) if y.lower() == 'bin'...
Python
1
import requests import json BASE_URL = "http://localhost:8000" API_V1 = f"{BASE_URL}/api/v1" def test_root(): print("1. Testing root endpoint...") response = requests.get(BASE_URL) print(f"Status: {response.status_code}") print(f"Response: {response.json()}\n") def test_create_user(): print("2....
Python
1
# Copyright 2024 The HuggingFace Team. 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 applicabl...
Python
1
pe (handles nested <...>) if self.peek() != "IDENT": # must have function name return False # look one past the name: either '<' (generic TPs) or '(' (params) if self.pos + 1 >= len(self.tokens): return False nxt = self.tokens[self...
Python
1
, V, BuildHasherDefault<XxHash32>>; #[cfg(all(feature = "xxhash", target_pointer_width = "32"))] pub type XHashSet<K> = HashSet<K, BuildHasherDefault<XxHash32>>; #[cfg(feature = "xxhash")] use twox_hash::XxHash64; #[cfg(feature = "xxhash")] pub type DefaultHasher64 = XxHash64; #[cfg(all(feature = "xxhash", target_poin...
Rust
0
0; let mut buffer = #writer; #pack_body Ok(len) })(); __x } }; output.into() } // `syn`-style datastructure for the input to the `spinel_write_len`. struct PackLenInput { pub format: syn::LitStr, pub comma_token: Token![,...
Rust
0
from src.backend.modules.llm.abstract_llm import AbstractLLM from src.backend.modules.llm.types import TokenUsage class LoggingLLM(AbstractLLM): def __init__(self, llm: AbstractLLM): self._llm = llm self._log: list[list[tuple[str, str]]] = [] self._last_messages: list[tuple[str, str]] = []...
Python
1
"Larry", "Lloyd", "<NAME>", "Matilda", "Meatball", "<NAME>", "Moose", "Munchkin", "Nacho", "Noodles", "Nugget", "Olga", "<NAME>", "<NAME>", "Pam", "Peanut", "<NAME>", "Pikachu", "<NAME>", "Pumba", "Rambo", "Rex", "Rocky", "...
Rust
0
/// assert_eq!(graphql_value!(OUTER_VAR), Value::scalar(42)); /// assert_eq!(graphql_input_value!(OUTER_VAR), InputValue::enum_value("OUTER_VAR")); /// assert_eq!(graphql_input_value!((OUTER_VAR)), InputValue::scalar(42)); /// ``` /// /// - [`InputValue::Variable`] is constructed by prefixing `ident` with `@`. /// ```...
Rust
0
er(|| { let _n = Like::<true>::not_like(black_box(&b"hello, world!"[..]), black_box(&b"hello%"[..])); }) } fn bench_bytes_ilike(bench: &mut Bencher) { bench.iter(|| { let _n = ILike::<true>::ilike(black_box(&b"hello, world!"[..]), black_box(&b"Hello%"[..])); }) } fn bench_bytes...
Rust
0
import torch from metric import SpeechEnhancementMetric, ReferenceFreeMetric import soundfile as sf import os; opj=os.path.join from glob import glob from tqdm import tqdm from pprint import pprint from librosa import resample def measure_metric(sample_dir): paths = glob(opj(sample_dir, f'in_dataset_same_mic*.wav...
Python
1
TestCase, description: &str) { ($head:expr, $t:expr, $description:expr) => { println!(""); println!("FAIL: {}: {}", $head, $description); println!(" base58: {}", $t.base58); assert!(false, "test failed"); } } fn verify(t: &TestCase) { let s = t.base58.as_str(); let chains:[&::fiat...
Rust
0
import json import pytest from unittest.mock import MagicMock, patch from navitia_client.entities.physical_mode import CommercialMode from navitia_client.client.apis.public_transportation_apis import ( CommercialModeApiClient, ) @pytest.fixture def commercial_modes_apis(): return CommercialModeApiClient( ...
Python
1
_delta_code: u8, } #[derive(Default)] pub(crate) struct EvceRdoqEst { cbf_all: [i64; 2], cbf_luma: [i64; 2], cbf_cb: [i64; 2], cbf_cr: [i64; 2], run: [[i32; 2]; NUM_CTX_CC_RUN], level: [[i32; 2]; NUM_CTX_CC_LEVEL], last: [[i32; 2]; NUM_CTX_CC_LAST], } /*************************************...
Rust
0
tests/log-sweep/pcm-8.flac", ]; for named_result in FloatWaveform::from_many_files(flac_filenames, Default::default(), Default::default()) { println!("{}", named_result.name); let waveform = named_result.result.unwrap(); assert_eq!(waveform.frame_r...
Rust
0
ExprExit::Stop, T::dummy()) } fn map<U, F: FnOnce(T) -> U>(self, f: F) -> Exitable<U> { Exitable(self.0, f(self.1)) } } struct ScopedChecker<'chk, 'inp: 'chk, 'envr: 'chk, 'env: 'envr, R: 'env + Report> { checker: &'chk mut Checker<'inp, 'envr, 'env, R> } impl<'chk, 'inp, 'envr, 'env, R: Repo...
Rust
0
:web::ServiceConfig; pub fn endpoints(_config: &mut ServiceConfig) {} <reponame>yoshuawuyts/playground-rust-hyper<filename>main.rs #![feature(custom_derive, plugin)] #![plugin(serde_macros)] extern crate serde_json; extern crate hyper; extern crate serde; use hyper::server::Request; use hyper::server::Response; use ...
Rust
0
Public License 1.1", false, true; Rpl1_5 = "RPL-1.5", "Reciprocal Public License 1.5", false, true; Rpsl1 = "RPSL-1.0", "RealNetworks Public Source License v1.0", true, true; RsaMd = "RSA-MD", "RSA Message-Digest License", false, false; Rscpl = "RSCPL", "Ricoh Source Code Public License", false, true; ...
Rust
0
import numpy from caffe2.python import core from hypothesis import given, settings import caffe2.python.hypothesis_test_util as hu import hypothesis.strategies as st import numpy as np @st.composite def _data(draw): return draw( hu.tensor( dtype=np.int64, elements=st.integers( ...
Python
1
&config.api_url, time.as_secs(), &config.api_token ); let response = request::get(&url)?; process_response(response, ExpectedStatus::Disabled, PiHoleError::NotDisabled) } fn process_response( json: JsonValue, expected_status: ExpectedStatus, status_error: PiHoleError, ) ...
Rust
0
timeout error run_coroutine(co); drop(data); // explicitly consume the data } // the timeout data pub struct TimerData { event_data: *mut EventData, } pub type TimerList = TimeOutList<TimerData>; pub type TimerHandle = TimeoutHandle<TimerData>; // event associated io data, must be construct in // each f...
Rust
0
return `Err` if there were errors reading the major value, seeking /// back, or decoding the component objects pub fn read_list_il<T: Decode<DagCborCodec>>( r: &mut ByteCursor, ) -> Result<Vec<T>, String> { let mut list: Vec<T> = Vec::new(); loop { let major = read_u8(r)?; if major == 0xff { break;...
Rust
0
''' Module of MacOS API for plyer.email. ''' import subprocess try: from urllib.parse import quote except ImportError: from urllib import quote from plyer.facades import Email from plyer.utils import whereis_exe class MacOSXEmail(Email): ''' Implementation of MacOS email API. ''' def _send...
Python
1
iptorFlags::USER_SEGMENT.bits() | DescriptorFlags::EXECUTABLE.bits() | DescriptorFlags::READ_WRITE.bits(); Descriptor::UserSegment(flags) } pub const fn kernel_data_segment() -> Descriptor { let flags = DescriptorFlags::PRESENT.bits() | ...
Rust
0
s = text_inputs.input_ids prompt_attention_mask = text_inputs.attention_mask prompt_attention_mask = prompt_attention_mask.bool().to(device) prompt_embeds = text_encoder(text_input_ids.to(device))[0] prompt_embeds = prompt_embeds.to(dtype=dtype, device=device) prompt_attention_mask = prompt_attenti...
Python
1
, input_path.to_string_lossy() ); Ok(input_path.with_extension("")) } // Copyright 2012 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or...
Rust
0
%s%d.pth' % (weight_prefix, i) for i in range(start, end, step)] for weight_path in row_names: if preload_path is not None: num_fcin = trainer.D.linear.in_features trainer.D.linear = nn.Linear(num_fcin, 10) trainer.load_checkpoint(preload_path, count=0, load_g=False, load...
Python
1
, 61 => Ok((I::V_RCP_F16, 4)), 62 => Ok((I::V_SQRT_F16, 4)), 63 => Ok((I::V_RSQ_F16, 4)), 64 => Ok((I::V_LOG_F16, 4)), 65 => Ok((I::V_EXP_F16, 4)), 66 => Ok((I::V_FREXP_MANT_F16, 4)), 67 => Ok((I::V_FREXP_EXP_I16_F16, 4)), 68 => Ok((I::V_FLOOR_F16, 4)), ...
Rust
0
chrono::Duration; // use openlimits::{ // OpenLimits, // exchange::{ // traits::{ // ExchangeAccount, // ExchangeMarketData, // stream::OpenLimitsWs, // info::{MarketPair, ExchangeInfoRetrieval} // }, // // nash::{ // // NashCredentials, // // NashParameters, // ...
Rust
0
oc = "Register TXPRODUCEINDEX `reset()`'s with value 0"] impl crate::ResetValue for super::TXPRODUCEINDEX { type Type = u32; #[inline(always)] fn reset_value() -> Self::Type { 0 } } #[doc = "Reader of field `TXPI`"] pub type TXPI_R = crate::R<u16, u16>; #[doc = "Write proxy for field `TXPI`"] pu...
Rust
0
oc_macro2::{self, Literal, TokenStream}; use quote::format_ident; use quote::{ToTokens, TokenStreamExt}; use std::fmt; use std::i64; use super::BytesError; use crate::rust::layers::bytes::*; pub struct BytesTypes { module: Vec<TokenStream>, } impl ToTokens for BytesTypes { fn to_tokens(&self, tokens: &mut T...
Rust
0
.map(|z| atomic_from_ptr(*z)) .collect() ) .collect() )) .collect::<Vec<(i32, Vec<Vec<AtomicPtr<QStandardItem>>>)>>() } /// This function returns a new default row. pub unsafe fn get_new_row(table_definition: &Definition) -> CppBox<QListOfQStandardItem> { le...
Rust
0
j - 1] and LowStream[j] < LowStream[j - 2] and LowStream[j] < LowStream[j + 2] and LowStream[j] < LowStream[j + 1] and lowflag == 0: Lowswing = LowStream[j] lowflag = 1 if Trade_Direction == 0: temp = (highswing - CloseStream[-1]) stoplossval = 1.25 * abs...
Python
1
banmen.0[p.1 as usize][p.0 as usize] = kind; let answer:Vec<LegalMove> = vec![]; assert_eq!(answer.clone(), Rule::oute_only_moves_from_banmen(Teban::Gote,&State::new(banmen.clone()),&MochigomaCollections::Empty).into_iter().map(|m| { LegalMove::from(m) }).collect::<Vec<LegalMove>>() ); ...
Rust
0