text
string
label_name
string
labels
int64
from contextlib import asynccontextmanager from fastapi import FastAPI, Depends, HTTPException from fastapi.middleware.cors import CORSMiddleware from pydantic import BaseModel from llama_cpp import Llama from sse_starlette.sse import EventSourceResponse import os MODEL_URL = "https://huggingface.co/bartowski/krutrim-...
Python
1
} } } Err(e) => return Err(LoginError::PasswordHashingError(e)), } // generate token info!("Generating JWT Expiry Date"); let duration: Duration = Duration::days(7); // Expire after a week let new_expire_date: NaiveDateTime = match Utc::now().checked_add_si...
Rust
0
Ok(SendToCosmosEvent { erc20, sender, destination, amount, event_nonce, }) } } else { Err(PeggyError::InvalidEventLogError( "Too few topics".to_string(), ...
Rust
0
import factory from factory.django import DjangoModelFactory from energy.tariffs.models import ActivationRule, Tariff, TariffGroup class ActivationRuleFactory(DjangoModelFactory): class Meta: model = ActivationRule class TariffFactory(DjangoModelFactory): class Meta: model = Tariff @fa...
Python
1
# self.output_blocks = [ R R RU | RT RT RTU | RT RT RTU | RT RT RT ] self.out = nn.Sequential( normalization(ch), nn.SiLU(), zero_module(conv_nd(dims, model_channels, out_channels, 3, padding=1)), ) self.position_net = instantiate_from_confi...
Python
1
in 1 .. MAX_VOTERS; let e in 1 .. (MAXIMUM_VOTE as u32); clean::<T>(); let all_candidates = submit_candidates_with_self_vote::<T>(c, "candidates")?; let _ = distribute_voters::<T>(all_candidates, v, e as usize)?; }: { <Elections<T>>::on_initialize(T::TermDuration::get()); } verify { assert_eq!(<Electio...
Rust
0
import source.py.feature.ast as ast case_glyphs = [ "colon", "periodcentered.loclCAT", "dieresiscomb", "dotaccentcomb", "gravecomb", "acutecomb", "hungarumlautcomb", "circumflexcomb", "caroncomb", "brevecomb", "ringcomb", "tildecomb", "macroncomb", "hookabovecom...
Python
1
::raw::c_char); } extern "C" { pub fn myodbc_remove_escape(mysql: *mut MYSQL, name: *mut ::std::os::raw::c_char); } extern "C" { pub fn mysql_thread_safe() -> ::std::os::raw::c_uint; } extern "C" { pub fn mysql_read_query_result(mysql: *mut MYSQL) -> bool; } extern "C" { pub fn mysql_reset_connection(my...
Rust
0
' } else { 'e' }, K_E)), "KeyF" => Some((if shift { 'F' } else { 'f' }, K_F)), "KeyG" => Some((if shift { 'G' } else { 'g' }, K_G)), "KeyH" => Some((if shift { 'H' } else { 'h' }, K_H)), "KeyI" => Some((if shift { 'I' } else { 'i' }, K_I)), "KeyJ" => Some((if shift { 'J' } else {...
Rust
0
import numpy as np import pytest from voxelwise_tutorials.utils import generate_leave_one_run_out, zscore_runs def test_generate_leave_one_run_out_disjoint(): n_samples = 40 run_onsets = [0, 10, 20, 30] for train, val in generate_leave_one_run_out(n_samples, run_onsets): assert len(train) > 0 ...
Python
1
borg"); cmd.arg("prune") .arg(&cfg.general.repo); if let Some(args) = purge.args { for arg in args { cmd.arg(arg); } } info!("Running: {:?}", cmd); run_borg(cfg, &cmd); } } pub fn check(cfg: &config::Config) { if let Some(check) = cfg.check.clone() { info!("Chec...
Rust
0
cfg=web_sys_unstable_apis` to be activated, //! which is inconvenient, so copy the binding code here for now. #![allow(unused_imports)] #![allow(clippy::unused_unit)] use wasm_bindgen::{self, prelude::*}; use web_sys::{DataTransfer, DomRectReadOnly, Element, Event, EventTarget}; #[wasm_bindgen] extern "C" { # [was...
Rust
0
""" Implementation of zeta function values computation using the Hasse-Stirling framework. """ import math from .hasse_stirling import hasse_log_power def zeta3(precision: float = 1e-15) -> float: """ Compute zeta(3) using the Hasse-Stirling approach. Args: precision: Desired precision ...
Python
1
a = input() b = input() sort_a = sorted(a) sort_b = sorted(b) print("".join(sort_a)+"".join(sort_b))
Python
1
TMRA2CLKR::RTC_100HZ => 14, TMRA2CLKR::HCLK_DIV4 => 15, TMRA2CLKR::XT_DIV4 => 16, TMRA2CLKR::XT_DIV8 => 17, TMRA2CLKR::XT_DIV32 => 18, TMRA2CLKR::CTMRB2 => 20, TMRA2CLKR::CTMRB3 => 21, TMRA2CLKR::CTMRA3 => 22, TMRA2CLKR::CT...
Rust
0
() + 1u8).map_err(|_| ErrorKind::Length { tag: Self::TAG })?; Ok(Self { inner, encoded_len }) } /// Borrow the inner byte slice. pub fn as_bytes(&self) -> &'a [u8] { self.inner.as_bytes() } /// Get the length of the inner byte slice (sans leading `0` byte). pub fn len(&self) ->...
Rust
0
ent_results = [] for deactivate_lang in languages: for activate_lang in languages: counter += 1 print(f"\n[{counter}/{total_combinations}] Processing combination...") try: if args.no_deactivation: ...
Python
1
import numpy as np from d3rlpy.datasets import get_atari from d3rlpy.dataset import MDPDataset from minerva.dataset import export_mdp_dataset_as_csv # prepare MDPDataset dataset, _ = get_atari('breakout-mixed-v0') # take 100 episodes due to dataset size episodes = dataset.episodes[:30] observations = [] actions = [...
Python
1
e=w_D, opt=w_D_opt, interval=1)] phases += [dnnlib.EasyDict(name='WDreg', module=w_D, opt=w_D_opt, interval=16)] for phase in phases: phase.start_event = None phase.end_event = None if rank == 0: phase.start_event = torch.cuda.Event(enable_timing=True) phase.end_...
Python
1
(p) => foldexpr!(self, Expr::Path, p, fold::fold_expr_path), Expr::Reference(r) => foldexpr!(self, Expr::Reference, r, fold::fold_expr_reference), Expr::Break(b) => foldexpr!(self, Expr::Break, b, fold::fold_expr_break), Expr::Return(r) => foldexpr!(self, Expr::Return, r, fold::fold_...
Rust
0
from dataclasses import dataclass from pathlib import Path from typing import Sequence, Mapping from yaml import safe_load __all__ = [ "config", "defaults", "PATH_IO", ] PATH_SRC = Path(__file__).absolute().parent.parent PATH_ROOT = PATH_SRC.parent PATH_CONFIG = PATH_ROOT / "config.yaml" PATH_DEFAULTS = ...
Python
1
use url::Url; use rustc_serialize::Decodable; use rustc_serialize::json; pub use rustc_serialize::json::{Json, BuilderError, DecoderError}; /// A Firebase instance to manage data. #[derive(Clone)] pub struct Firebase { url: Arc<Url>, } // TODO: Change all instances of &str to Into<String> // TODO: Make FB instan...
Rust
0
_path)), image_generic: icon::Icon::new(&QString::from_std_str(icon_image_generic_path)), image_png: icon::Icon::new(&QString::from_std_str(icon_image_png_path)), image_jpg: icon::Icon::new(&QString::from_std_str(icon_image_jpg_path)), text_generic: icon::Icon::new(&QSt...
Rust
0
responses: return self.user_responses[case_id] else: return "请您具体说明一下。" def run_single_test(self, test_case: Dict, mode: str) -> Dict: """运行单个测试案例(优化版本)""" case_id = test_case["id"] question = test_case["question"] should_ask = test_case.get("shou...
Python
1
//! USB OTG full-speed peripheral //! //! Requires the `usb_fs` feature. //! Only one of the `usb_fs`/`usb_hs` features can be selected at the same time. use crate::pac; use crate::embedded_time::rate::Hertz; use crate::gpio::{ gpioa::{PA11, PA12}, Alternate, }; use crate::rcc::Clocks; pub use synopsys_usb_...
Rust
0
for dd in ins_addrs.intersection(&code_refs_from_a) { verified_refs.push(*dd); } if !verified_refs.is_empty() { block_refs.insert(block[0].0, verified_refs); } } } Ok(block_refs) } ...
Rust
0
"c5": 0, "c6": 0, "c7": None, "c8": 0, }, ] self.sql = """CREATE MATERIALIZED VIEW int_stddev_pop_where_gby AS SELECT id, STDDEV_POP(c1) FILTER (WHERE c8>2) AS c1, STDDEV_POP(c2) FILTER (WHERE c8>2) AS c2, STDDEV_POP(c3...
Python
1
_classes * 4 self.num_classes = num_classes def forward(self, x): if x.ndimension() == 4: assert list(x.shape[2:]) == [1, 1] x = x.flatten(start_dim=1) scores = self.cls_score(x) bbox_deltas = self.bbox_pred(x) bbox_deltas = bbox_deltas.repeat([1, self.nu...
Python
1
alkEnd(0x00FF) MapClearFlags(0x08000000) Return() def _loc_456(): pass label('loc_456') OP_B4(0x00) Return() def _loc_459(): pass label('loc_459') If( ( (Expr.Eval, "AddItem(ItemTable['太极服'], 1)"), Expr.Return, ), 'loc_4A8', ...
Python
1
}, ); let elapsed = self.current - self.start; let elapsed_seconds = elapsed.as_secs() as f32; let elapsed_millis = elapsed.subsec_millis() as f32; frame.with_save(|frame| { frame.translate(Vector::new(center.x, center.y)); frame.rotate( ...
Rust
0
.map_err(|_| sig::Error::Unspecified) } } impl sig::SignFor<rsa::RsaPkcs1Sha256> for Sign256 {} #[cfg(test)] mod tests { use super::*; use crate::crypto::rsa::Builder as _; use crate::crypto::rsa::KeyPair as _; use crate::crypto::rsa::ModulusLength; use crate::crypto::sig::Sign as _...
Rust
0
from sdkit import Context def make_sd_context(model_path: str = "models/stable-diffusion/sd-v1-4.ckpt", vram_usage_level: str = "balanced"): from sdkit.models import load_model context = Context() context.test_diffusers = True context.model_paths["stable-diffusion"] = model_path context.vram_usag...
Python
1
("F3", KeyCode::F3), ("F4", KeyCode::F4), ("F5", KeyCode::F5), ("F6", KeyCode::F6), ("F7", KeyCode::F7), ("F8", KeyCode::F8), ("F9", KeyCode::F9), ("F10", KeyCode::F10), ("F11", KeyCode::F11), ("F12", KeyCode::F12), ("F13", KeyCode::F13), ("F14", KeyCode::F14), ("F15", Ke...
Rust
0
# Copyright (c) 2025 Ansible project # GNU General Public License v3.0+ (see LICENSES/GPL-3.0-or-later.txt or https://www.gnu.org/licenses/gpl-3.0.txt) # SPDX-License-Identifier: GPL-3.0-or-later # Note that this module util is **PRIVATE** to the collection. It can have breaking changes at any time. # Do not use this ...
Python
1
class Solution: def jump(self, nums: List[int]) -> int: l = r = ans = maxJump = 0 while r < len(nums) - 1: for i in range(l, r + 1): maxJump = max(maxJump, i + nums[i]) l = r + 1 r = maxJump ans += 1 return ans
Python
1
: window: 削除するウィンドウ Returns: bool: 削除に成功した場合True """ if window not in self.stack: return False # トップウィンドウの場合はpopを使用 if window == self.peek(): self.pop() return True # 中間のウィンドウを削除 ...
Python
1
(self): """ **[Required]** Gets the usage_data of this StorageUsageTrendAggregation. List of usage data samples for a filesystem. :return: The usage_data of this StorageUsageTrendAggregation. :rtype: list[oci.opsi.models.StorageUsageTrend] """ return self._usage...
Python
1
#Very slow but memory efficient class Solution: def maxArea(self, height: List[int]) -> int: wall = 0 max = 0 for i in range(len(height)): if height[i] <= wall: continue if height[i] * (len(height)-i-1) <= max: continue for ...
Python
1
bias) + bias.saturating_sub(rand_bits) <= 1 { None } else if rand_bits < bias { Some(1) } else if rand_bits > bias { Some(0) } else { panic!("Error: code should never reach here."); } } fn sample_exact_exponential_bit(scale: f64, pow2: i32, rand_bits: u64) -> i64 { ...
Rust
0
_LENGTH..AES_IV_PLUS_TAG_LENGTH]); let mut out = Vec::with_capacity(encrypted_msg.len() - AES_IV_PLUS_TAG_LENGTH); out.extend(&encrypted_msg[AES_IV_PLUS_TAG_LENGTH..]); if let Ok(_) = aead.decrypt_in_place_detached(iv, &EMPTY_BYTES, &mut out, tag) { Some(out) } else { None } } //! ...
Rust
0
import re from abc import ABC, abstractmethod from flask import render_template, render_template_string class Renderer(ABC): @abstractmethod def render(self, **context): pass class TemplateRenderer: """Render using a template file.""" def __init__(self, template, **extra_context): ...
Python
1
annels=\"2\" \ sampleFrequency=\"{sample_rate}\" \ protocolInfo=\"{didl_prot_info}\" \ duration=\"{duration}\" >{server_uri}</res>\ <upnp:class>object.item.audioItem.musicTrack</upnp:class>\ </item>\ </DIDL-Lite>"; /// OH play playlist template static OH_PLAY_PL_TEMPLATE: &str = "\ <?xml version=\"1.0\" encoding=\"UTF...
Rust
0
history: if action.row_number != 1: # first row is the most recent continue models_seen.add(action.model) last_update = server_to_user_time(action.date, timezone) if action.model == MODEL_APP: app_id = action.wrapped_detail.app_id if action.model_det...
Python
1
PI endpoints to interact with the game. extern crate markup; use crate::game::SnakeID; use crate::room::{self, Room, State, WaitingList}; use std::collections::HashMap; use std::net::SocketAddr; use std::sync::{Arc, Mutex}; markup::define! { Page(contents: Vec<Box<dyn markup::Render>>, alert: Option<(String, St...
Rust
0
; Scheduler::perform_tasks(); } } #[allow(dead_code)] async fn logo_task(f: fn()) { let width = 320; let height = 200; WindowManager::set_desktop_color(Theme::shared().desktop_color()); if true { if let Ok(mut file) = FileManager::open("wall.bmp") { let stat = file.stat...
Rust
0
(crate::generic::Reg::read), [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`write_with_zero`](crate::generic::Reg::write_with_zero), [`modify`](crate::generic::Reg::modify). See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [qmr0...
Rust
0
doc = "< Home button"] pub Home: ::libc::c_int, #[doc = "< Up button"] pub Up: ::libc::c_int, #[doc = "< Down button"] pub Down: ::libc::c_int, #[doc = "< Left button"] pub Left: ::libc::c_int, #[doc = "< Right button"] pub Right: ::libc::c_int, } #[doc = " \\struct CPads"] #[doc = "...
Rust
0
)."] #[doc = ""] #[doc = " In that situation, this callback is invoked to compute the"] #[doc = " client-side ECDH: the provided `data` (of length `*len` bytes)"] #[doc = " is the server's public key point (as decoded from its"] #[doc = " certificate), and the client shall multiply that point with"]...
Rust
0
let future = transport .dial(rx.recv().unwrap()) .unwrap() .and_then(|proto| proto.send(msg_client)) .map(|_| ()); let mut rt = Runtime::new().unwrap(); let _ = rt.block_on(future).unwrap(); bg_thread.join().unwr...
Rust
0
""" Generated by Eclipse Cyclone DDS idlc Python Backend Cyclone DDS IDL version: v0.11.0 Module: builtin_interfaces.msg.dds_ """ from ._Time_ import Time_ __all__ = ["Time_", ]
Python
1
pub struct RemoteActionGroup(Interface<ffi::GRemoteActionGroup, ffi::GRemoteActionGroupInterface>) @requires ActionGroup; match fn { type_ => || ffi::g_remote_action_group_get_type(), } } pub const NONE_REMOTE_ACTION_GROUP: Option<&RemoteActionGroup> = None; pub trait RemoteActionGroupExt: 'static { ...
Rust
0
(51*cos(theta6)*(cos(theta2)*cos(theta4) + cos(theta3)*sin(theta2)*sin(theta4)))/125 - (51*sin(theta6)*(cos(theta5)*(cos(theta2)*sin(theta4) - cos(th...
Python
1
dex => span_parser(parser, left, IndexParser::parse), InfixParser::Cast => span_parser(parser, left, CastParser::parse), } } } fn span_parser( parser: &mut Parser, left: Expression, f: fn(parser: &mut Parser, left: Expression) -> ParserExprKindResult, ) -> ParserExprResult { let...
Rust
0
#!/usr/bin/env python ########################### # This code block is a HACK (!), but is necessary to avoid code duplication. Do NOT alter these lines. import importlib.util import os from setuptools import setup filepath = os.path.abspath(os.path.dirname(__file__)) filepath_import = os.path.join(filepath, "..", "co...
Python
1
_rem { let input_chunk = &input[input_index..(input_index + 3)]; let output_chunk = &mut output[output_index..(output_index + 4)]; output_chunk[0] = encode_table[(input_chunk[0] >> 2) as usize]; output_chunk[1] = encode_table[((input_chunk[0] << 4 | input_chunk[1] >> 4) & LO...
Rust
0
lockchain, Kind}; pub use config::Config; use std::error::Error; mod blockchain; pub mod config; /// Runs a mosaic node with the given configuration. /// Prints all accounts of the origin blockchain to std out. /// /// # Arguments /// /// * `config` - A configuration to run the mosaic node. pub fn run(config: &Config...
Rust
0
d_lut(histo, step), 0, im.flatten().long()) result = result.reshape_as(im) return result # .type(torch.uint8) # Assumes RGB for now. Scales each channel independently # and then stacks the result. s1 = scale_channel(image, 0) s2 = scale_channel(image, 1) s3 = scale_channel(im...
Python
1
); } mod game; mod engine; use game::Game; use engine::GraphicsEngine; fn main() -> Result<(), String> { let engine = Box::new(GraphicsEngine::new()); let game = Game::new(engine); game.play()?; Ok(()) } <filename>src/cmds/mod.rs pub mod ping; pub mod pong;#![no_std] mod trait_impls; use core::...
Rust
0
el_operator). /// /// # Parameters /// /// - `input` is the input image /// - `ker_size` is the kernel size of sobel operator /// /// # Return Values /// /// A tuple of Arrays. /// /// The first Array has derivatives along horizontal direction /// /// The second Array has derivatives along vertical direction #[allow(un...
Rust
0
eScalingActivitiesOutput, ) -> std::option::Option<std::vec::Vec<crate::model::ScalingActivity>> { let input = match input.scaling_activities { None => return None, Some(t) => t, }; Some(input) } pub(crate) fn lens_structure_crate_output_describe_scaling_policies_output_scaling_policies( ...
Rust
0
file_descriptor_proto() ) }) } } fn default_instance() -> &'static GetEventsSinceResponse { static mut instance: ::protobuf::lazy::Lazy<GetEventsSinceResponse> = ::protobuf::lazy::Lazy { lock: ::protobuf::lazy::ONCE_INIT, p...
Rust
0
import numpy as np from .state import Observations class Reward: def __init__(self) -> None: pass @property def __name__(self) -> str: return self.__class__.__name__ def __call__(self, observations: Observations) -> float: raise NotImplementedError def reset(self,...
Python
1
import numpy as np from scipy.integrate import odeint import matplotlib.pyplot as plt t = np.linspace(1,40) def model(y,t): if t<10: dydt = (1/5)*(-y) if t>=10: dydt = (1/5)*(-y+2) return dydt y0 = 1 y = odeint(model,y0,t) plt.plot(t,y) plt.xlabel('time') plt.ylabel('y(t)') plt.show()
Python
1
Scope<'ctx>, // 外部绑定的作用域 pub fns: Scope<'ctx>, // 全局定义的方法(只能在全局定义) scope_chains: Vec<Scope<'ctx>>, // 变量作用域链 } impl<'ctx> BlockScope<'ctx> { pub fn new() -> Self { BlockScope { external: Scope::new(None), fns: Scope::new(None), scope_chains: vec![]...
Rust
0
)] pub struct QuestItems { pub sword: Sword, pub shield: Shield, pub has_power_bracelets: bool, pub has_pirates_charm: bool, pub heros_charm: HerosCharm, } impl QuestItems { pub fn get() -> &'static mut QuestItems { reference(0x803B81BC) } } impl Sword { pub fn item_id(self) ->...
Rust
0
print::xcb_x_print_id()`], then the type of the request is /// [`xcb_x_print_print_get_screen_of_context_request_t`]. pub const XCB_X_PRINT_PRINT_GET_SCREEN_OF_CONTEXT: u8 = 6i32 as u8; /// The `XPrint::PrintGetScreenOfContext` request. #[derive(Copy, Clone, Debug)] #[repr(C)] pub struct xcb_x_print_print_get_screen_o...
Rust
0
# Day 4: Quote Manager App import random def add_quote(quote, quote_list): if quote.strip() == "": return "Error: Quote cannot be empty!" if quote in set(quote_list): return "Error: Quote already exists!" quote_list.append(quote) return "Quote added successfully!" def vie...
Python
1
#!/usr/bin/env python3 # date: 2020.06.14 # https://stackoverflow.com/questions/62373373/bs4-fetching-thread-titles-description-plus-more-from-wordpress-org-support-fo import requests from bs4 import BeautifulSoup as BS session = requests.Session() session.headers.update({'User-Agent': 'Mozilla/5.0'}) # this page ne...
Python
1
data: *mut ::std::os::raw::c_void, ) -> Rboolean; } extern "C" { pub fn R_ExecWithCleanup( fun: ::std::option::Option<unsafe extern "C" fn(arg1: *mut ::std::os::raw::c_void) -> SEXP>, data: *mut ::std::os::raw::c_void, cleanfun: ::std::option::Option<unsafe extern "C" fn(arg1: *mut ::s...
Rust
0
#!/usr/bin/env python3 # -*- coding: utf-8 -*- # # Copyright 2020-2022 F4PGA Authors # # 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 # # Unl...
Python
1
from .base import StableDiffusionXLPretrainedLoRA __all__ = [ "NoiseOffsetStableDiffusionXLPretrainedLoRA", "DPOStableDiffusionXLPretrainedLoRA" ] class NoiseOffsetStableDiffusionXLPretrainedLoRA(StableDiffusionXLPretrainedLoRA): name = "noise-offset" url = "https://huggingface.co/benjamin-paine/tapro...
Python
1
, page, files) return _badge( icon = f"[:{icon}:]({href} 'Default value')", text = text ) # Create badge for empty default value def _badge_for_default_none(page: Page, files: Files): icon = "material-water-outline" href = _resolve_path("conventions.md#default", page, files) return ...
Python
1
} _ => { v[1] = 'B' as i8; v[3] = 'T' as i8; } }; let temp = get_temperature(con, v.as_mut_ptr() as *mut i8); ...
Rust
0
ool => f.write_str("bool"), PropertyType::Int(_) => f.write_str("i32"), PropertyType::Enum((target, _real)) => f.write_fmt(format_args!("{}", target.name)), } } } impl PropertyType { pub fn from_raw(name: String, values: Vec<String>) -> Self { if values.first().unwrap() ...
Rust
0
_data['debug'] = Account_data_this.debug_mode tmp_total_account_data['account'].append(tmp_this_account_data) with open(path, 'w', encoding='utf-8') as account_conf_f: account_conf_f.write(json.dumps(tmp_total_account_data, indent=4)) def accountFix(basic_conf_models, bot_info_dict, lo...
Python
1
from pyrep.robots.arms.arm import Arm class UR5(Arm): def __init__(self, count: int = 0): super().__init__(count, 'UR5', 6)
Python
1
size, num_components: components, } } pub fn pixel_size(&self) -> usize { let info = self.pixel_info(); info.type_size * info.num_components } } impl Default for TextureFormat { fn default() -> Self { if cfg!(target_os = "android") { // Bgra8Unor...
Rust
0
root); merkle_root = hash(&input); } else { let mut input = merkle_root; input.extend_from_slice(leaf.as_bytes()); merkle_root = hash(&input); } } H256::from_slice(&merkle_root) } /// Concatenate two vectors. fn concat(mut vec1: Vec<u8>, mut vec2...
Rust
0
folder, Path::new(LOG_FILE_NAME)); { let mut builder = PipeLoggerBuilder::new(&test_log_path); builder.set_tee(Some(Tee::Stdout)); let mut logger = builder.build().unwrap(); logger.write_line("This is a log.").unwrap(); logger.write_line("Isn't it?").unwrap(); } ...
Rust
0
ame))? .filter_map(|entry| { let entry = entry.ok()?; if entry.file_type().ok()?.is_file() { Some(entry.file_name().to_string_lossy().into_owned()) } else { None } }) .for_each(move |file| { let before_fi...
Rust
0
iter() .map(|form| NewQuestionOption { option: form.option, test_question_id, is_correct: form.is_correct, }).collect(); NewQuestionOption::save_multiple(new_options, conn) } } /// A type to update an option for a question. #[derive(G...
Rust
0
tCells(cellTypes.GetNumberOfTuples(), cells) self.VTKObject.SetCells(cellTypes, cellLocations, ca) CellTypes = property(GetCellTypes, None, None, "This property returns the types of cells.") CellLocations = property(GetCellLocations, None, None, "This property returns the locations of cells.") Cell...
Python
1
e: u16, /// The input gate to be used on the destination module #[clap(long = "igate", default_value = "0")] pub igate: u16, } /// Disconnect two modules #[derive(Clap)] pub struct DisconnectModules { /// Name of the source module #[clap(name = "SRC")] pub src: String, /// The output gate...
Rust
0
/// Returns `Ok(true)` if any of the keys were handled. pub async fn release_multiple_key3(&self, keys: Vec<input::Key>) -> Result<bool> { let mut was_handled = false; for key in keys.into_iter() { let key_handled = self.release_key3(key).await?; was_handled = was_handled || ...
Rust
0
io::stdin())) }; let mut buffer = [0; CHUNK_SIZE]; loop { let num_read = match reader.read(&mut buffer) { Ok(0) => break, Ok(x) => x, Err(_) => break, }; let _ = stats_tx.send(num_read); if write_tx.send(Vec::from(&buffer[..num_read])).is...
Rust
0
s) filtered = actual["recordsFiltered"] where = re.sub(".* WHERE ", "", filtered) assert where == expected, search_string assert_where_equals( "XXX", "(Color LIKE '%' || :s0 || '%' OR Food LIKE '%' || :s0 || '%')" ) assert_where_equals( "^XXX", "(Color LIKE '' || :s0...
Python
1
pub const SCRUB_MASK: u16 = 1244; pub const SCRUB_MASK_SEED: u16 = 1245; pub const SCRUB_TOP: u16 = 1246; pub const SCRUB_TOP_SEED: u16 = 1247; pub const SCRUB_PANTS: u16 = 1248; pub const SCRUB_PANTS_SEED: u16 = 1249; pub const BRIDE_OF_REANIMATOR_REMOTE: u16 = 1250; pub const BRIDE_OF_REANIMATOR_REMOTE_SEED: u16 = 1...
Rust
0
OC: wee_alloc::WeeAlloc = wee_alloc::WeeAlloc::INIT; } } #[derive(Deserialize)] pub struct OptParam { pub eps: f64, pub samples: u64, pub max_iters: u64, pub target_cost: f64, } #[wasm_bindgen] extern "C" { #[wasm_bindgen(js_namespace = console)] fn log(s: &str); } #[wasm_bindgen(start)] ...
Rust
0
undAccountParams| params)) .and_then(handle_fund_account) } async fn handle_fund_account( address: AccountAddress, service: Arc<Service>, params: FundAccountParams, ) -> Result<Box<dyn warp::Reply>, Infallible> { match fund_account(service, address, params).await { Ok(txn) => Ok(Box::ne...
Rust
0
import math def convert_sparse_vector(numbers): vector_dict = {} for k, c in enumerate(numbers): if c: vector_dict[k] = c return vector_dict def cosine_similarity(vectA, vectB): a = dot(vectA, vectB); b = norm(vectA) * norm(vectB); if b > 0: return a / b; else: ...
Python
1
from scipy.sparse.linalg import expm, expm_multiply from openfermion import get_sparse_operator from qiskit.quantum_info import Operator, process_fidelity import numpy as np from adaptvqe.pools import NoZPauliPool, DVG_CEO, QE from adaptvqe.molecules import create_h2 # Define test case: molecule, ansatz size, coeffic...
Python
1
R;R?R@(R((ssunau.pyRAwscCs|jS(N(RR(R((ssunau.pyRL|scCs|jt||j}|jdkrPddl}|j||j}n|jj||j ||_ |j t||_ dS(...
Python
1
main and sub-grids: grid_count = z_count + 1 if z_count > 1 else 1 for g in range(grid_count): #TODO: See previous comment about intentional data misalignment. adj_g = g-1 if g > 0 else g images.save_image(processed.images[g], p.outpath_grids, "xyz...
Python
1
ke().unwrap().into_raw()); } } <reponame>ohno418/rust // Various tests related to testing how region inference works // with respect to the object receivers. // revisions: base nll // ignore-compare-mode-nll //[nll] compile-flags: -Z borrowck=mir trait Foo { fn borrowed<'a>(&'a self) -> &'a (); } // Borrowed...
Rust
0
nst acamera_metadata_enum_acamera_control_ae_antibanding_mode_ACAMERA_CONTROL_AE_ANTIBANDING_MODE_AUTO : acamera_metadata_enum_acamera_control_ae_antibanding_mode = 3 ; pub type acamera_metadata_enum_acamera_control_ae_antibanding_mode = ::std::os::raw::c_uint; pub use self::acamera_metadata_enum_acamera_control_ae_ant...
Rust
0
import os import sys import shutil current_dir = os.path.dirname(os.path.realpath(__file__)) sys.path.insert(0, os.path.realpath(os.path.join(current_dir, os.pardir, os.pardir))) from lib.config import ConfigManager, ConfigObj from server.modules.copter_table_models import CopterDataModel config_path = 'temp_config...
Python
1
Snmp3MIB": eltMesIssSnmp3MIB, "eltMesIssCfaMIB": eltMesIssCfaMIB, "eltMesIssL2ptMIB": eltMesIssL2ptMIB, "eltMesIssSyslogMIB": eltMesIssSyslogMIB, "eltMesIssLaMIB": eltMesIssLaMIB, "eltMesIssIpMIB": eltMesIssIpMIB, "eltMesIssL2Ip6SnpMIB": eltMesIssL2Ip6SnpMIB, "eltMesIssA...
Python
1
.index + 1] == '!': return self.scanHashbang() if Character.isIdentifierStart(ch): return self.scanIdentifier() # Very common: ( and ) and ; if ch in ('(', ')', ';'): return self.scanPunctuator() # String literal starts with single quote (U+0027) or...
Python
1
{ let m = board.len(); let n = board[0].len(); let mut visited = vec![vec![false; n]; m]; for i in 0..m { if board[i][0] == 'O' && !visited[i][0] { bfs(board, &mut visited, i, 0); } if board[i][n - 1] == 'O' && !visited[i][n - 1] { ...
Rust
0
rive(Debug, Clone, new)] pub struct TypeParameter<'a> { pub loc: SourceLocation, pub name: Name<'a>, pub kind_ann: Option<&'a Sexp>, } impl<'a> m::Match<'a> for TypeParameter<'a> { type Result = Self; fn match_sexp(s: &'a Sexp) -> m::Result<Self> { match s.matches::<Either<Name, (Name, m::...
Rust
0