lang
stringclasses
3 values
file_path
stringlengths
5
150
repo_name
stringlengths
6
110
commit
stringlengths
40
40
file_code
stringlengths
1.52k
18.9k
prefix
stringlengths
82
16.5k
suffix
stringlengths
0
15.1k
middle
stringlengths
121
8.18k
strategy
stringclasses
8 values
context_items
listlengths
0
100
Rust
src/commands/import_json.rs
BoiseState/bookdata-tools
cd857028a7947f369d84cb69a941303a413046b6
use std::io::prelude::*; use std::io::{BufReader, BufWriter}; use std::fs::{File, read_to_string}; use std::path::PathBuf; use log::*; use structopt::StructOpt; use flate2::bufread::MultiGzDecoder; use indicatif::{ProgressBar, ProgressStyle}; use sha1::Sha1; use anyhow::{Result}; use serde::{Deserialize}; use toml; u...
use std::io::prelude::*; use std::io::{BufReader, BufWriter}; use std::fs::{File, read_to_string}; use std::path::PathBuf; use log::*; use structopt::StructOpt; use flate2::bufread::MultiGzDecoder; use indicatif::{ProgressBar, ProgressStyle}; use sha1::Sha1; use anyhow::{Result}; use serde::{Deserialize}; use toml; u...
m {:?}", &self.spec); let spec = read_to_string(&self.spec)?; let spec: ImportSpec = toml::from_str(&spec)?; let dbo = self.db.default_schema(&spec.schema); let dbc = dbo.open()?; let mut stage = self.stage.begin_stage(&dbc)?; let infn = &self.infile; info!("reading from {:?}", infn)...
dst: &mut W) -> Result<usize> { let mut jsbuf = String::new(); let mut n = 0; for line in src.lines() { let line = line?; let mut delim = DelimPrinter::new("\t", "\n"); let split = line.split("\t"); for (fld, fc) in split.zip(&self.format) { match fc { ColOp::Skip =...
random
[ { "content": "/// Some of our JSON objects have \\u0000, which PostgreSQL doesn't like.\n\n/// Clean those out while we import.\n\n/// This uses a reusable buffer to reduce allocations.\n\n/// \n\n/// ```\n\n/// use bookdata::cleaning::clean_json;\n\n/// let mut buf = String::new();\n\n/// clean_json(\"some bad...
Rust
src/core/io/stdio.rs
parth1614/brain
234eccd8f5a71818704fe79d32c5c3eb73bce5d4
use parser::Identifier; use memory::{MemoryBlock}; use operations::{Operation, expression, Target}; use operations::item_type::{ItemType, FuncArgType}; use operations::scope::{ScopeStack, ScopeItem, TypeId}; pub fn define_stdin(scope: &mut ScopeStack, u8_type: TypeId) -> TypeId { scope.push_scope()...
use parser::Identifier; use memory::{MemoryBlock}; use operations::{Operation, expression, Target}; use operations::item_type::{ItemType, FuncArgType}; use operations::scope::{ScopeStack, ScopeItem, TypeId}; pub fn define_stdin(scope: &mut ScopeStack, u8_type: TypeId) -> TypeId { scope.push_scope()...
pub fn define_stdout(scope: &mut ScopeStack) -> TypeId { scope.push_scope(); let type_name = Identifier::from("std::io::Stdout"); let stdout_type = scope.declare_type( type_name.clone(), ItemType::Struct {}, ); scope.declare(Identifier::from("stdout"), stdout_type); ...
function_block-full_function
[ { "content": "pub fn into_operations(scope: &mut ScopeStack, mut block: Block, target: Target) -> OperationsResult {\n\n scope.push_scope();\n\n\n\n // The last statement in a block is always used for the return type of the block\n\n // This works because we automatically insert a UnitLiteral at the en...
Rust
ffi/ffi_java/ffi_java_scd/src/user.rs
fqliao/WeDPR-Lab-Core
a294fedebc0f48ac19b5724cca41c82e43cf2c42
use jni::{ objects::{JClass, JObject, JString, JValue}, sys::jobject, JNIEnv, }; use protobuf::{self, Message}; use wedpr_ffi_common::utils::{ java_jstring_to_bytes, java_jstring_to_string, java_new_jobject, java_set_error_field_and_extract_jobject, }; use selective_certificate_disclosure; use ...
use jni::{ objects::{JClass, JObject, JString, JValue}, sys::jobject, JNIEnv, }; use protobuf::{self, Message}; use wedpr_ffi_common::utils::{ java_jstring_to_bytes, java_jstring_to_string, java_new_jobject, java_set_error_field_and_extract_jobject, }; use selective_certificate_disclosure; use ...
#[no_mangle] pub extern "system" fn Java_com_webank_wedpr_scd_NativeInterface_userProveSelectiveDisclosure( _env: JNIEnv, _class: JClass, rule_set_jstring: JString, certificate_signature_jstring: JString, attribute_dict_jstring: JString, certificate_template_jstring: JString, user_private_...
let blinded_certificate_signature = match selective_certificate_disclosure::user::blind_certificate_signature( &certificate_signature_pb, &attribute_dict_pb, &certificate_template_pb, &user_private_key, &certificate_secrets_blinding_factors, ...
function_block-function_prefix_line
[ { "content": "pub fn pause(info_message: &str) {\n\n let mut enter_continue = String::new();\n\n print_wide(info_message);\n\n std::io::stdin()\n\n .read_line(&mut enter_continue)\n\n .expect(\"read_line should not fail\");\n\n println!(\"... {}\\n\", enter_continue.trim());\n\n}\n\n\n...
Rust
gband/src/cartridge/mappers/mbc1.rs
zer0x64/nsec2022-gband
7f831b1af83c7f766f139dfce14776b654ee8d9a
use super::Mapper; use crate::cartridge::CartridgeReadTarget; pub struct Mbc1 { n_rom_banks: usize, n_ram_banks: usize, bank_mask: usize, ram_enable: bool, rom_bank_number: u8, ram_bank_number_or_upper_rom_bank: u8, banking_mode_select: bool, } impl Mbc1 { pub fn new(n_rom_banks: usize...
use super::Mapper; use crate::cartridge::CartridgeReadTarget; pub struct Mbc1 { n_rom_banks: usize, n_ram_banks: usize, bank_mask: usize, ram_enable: bool, rom_bank_number: u8, ram_bank_number_or_upper_rom_bank: u8, banking_mode_select: bool, } impl Mbc1 { pub fn new(n_rom_banks: usize...
}
F => { let bank_number = data & (self.bank_mask as u8) & 0x1F; if bank_number == 0 { self.rom_bank_number = 1; } else { self.rom_bank_number = bank_number; } ...
function_block-function_prefixed
[ { "content": "pub fn disassemble(bus: &mut CpuBus) -> Vec<(u8, u16, String)> {\n\n let mut pc = 0u16;\n\n let mut disassembly = Vec::new();\n\n\n\n let rom_bank = bus.get_cartridge_rom_bank();\n\n let ram_bank = bus.get_cartridge_ram_bank();\n\n let wram_bank = bus.read_without_dma_check(0xFF70, ...
Rust
dove/src/cmd/prover.rs
pontem-network/move-tools
e61a934ca0c294d1be40e3619f63e89d8c32eac7
use std::str::FromStr; use std::ffi::OsStr; use std::path::PathBuf; use std::{env, fs}; use std::fs::read_dir; use anyhow::{ensure, Result}; use structopt::StructOpt; use serde::Deserialize; use boogie_backend::options::BoogieOptions; use move_prover::{cli::Options, run_move_prover_errors_to_stderr}; use super::Cmd; us...
use std::str::FromStr; use std::ffi::OsStr; use std::path::PathBuf; use std::{env, fs}; use std::fs::read_dir; use anyhow::{ensure, Result}; use structopt::StructOpt; use serde::Deserialize; use boogie_backend::options::BoogieOptions; use move_prover::{cli::Options, run_move_prover_errors_to_stderr}; use super::Cmd; us...
} fn get_dependency_paths(ctx: &Context) -> Result<Vec<String>> { let build_path = ctx.project_dir.join("build"); if !build_path.exists() { return Ok(Vec::new()); } let list = fs::read_dir(&build_path)? .filter_map(|path| path.ok()) .map(|path| path.path()) .filter(|dir...
canonicalize(self.z3_exe.as_mut(), &home)?; canonicalize(self.cvc4_exe.as_mut(), &home)?; } Ok(()) }
function_block-function_prefix_line
[ { "content": "/// run bin dove\n\npub fn execute_dove_at(args: &[&str], project_path: &Path) -> Result<String> {\n\n ensure!(\n\n project_path.exists(),\n\n \"Project folder {:?} does not exist\",\n\n project_path.display()\n\n );\n\n\n\n let output = std::process::Command::new(env...
Rust
src/head/mod.rs
devalain/cdll
3801667e8f919f2f8b145883b8c66b40ed86e293
use {crate::CircularList, core::ptr}; pub mod cursor; pub struct ListHead<T> { next: *const ListHead<T>, prev: *const ListHead<T>, value: T, } impl<T> ListHead<T> { pub fn new(val: T) -> Box<Self> { let mut new = Box::new(Self { ...
use {crate::CircularList, core::ptr}; pub mod cursor; pub struct ListHead<T> { next: *const ListHead<T>, prev: *const ListHead<T>, value: T, } impl<T> ListHead<T> { pub fn new(val: T) -> Box<Self> { let mut new = Box::new(Self { ...
for Iter<'life, T> { type Item = &'life T; fn next(&mut self) -> Option<Self::Item> { let (current, next) = unsafe { let r = &*self.next; (&r.value, r.next) }; self.next = next; Some(current) } } impl<'life, T> Iter<'life, T...
*mut Self, entry2: *mut Self) { let mut pos = (*entry2).prev; Self::__del((*entry2).prev as *mut _, (*entry2).next as *mut _); Self::__replace(entry1, entry2); if pos == entry1 { pos = entry2; } Self::__add(entry...
random
[ { "content": "/// Sorts a list of elements that can be ordered.\n\npub fn sort<T, S>(list: &mut CircularList<T>)\n\nwhere\n\n T: core::cmp::PartialOrd,\n\n S: Sorter<Item = T>,\n\n{\n\n S::sort(list)\n\n}\n\n\n\n/// A merge sort implementation (Found in wikipedia).\n\npub struct MergeSort<T> {\n\n _...
Rust
server/src/tools/helpers.rs
zachmeyner/portal2-cm-boards-v2
aa43cf2d7f87fdd0ec25db9d272cec2d6630f903
use crate::models::models::{CalcValues, Changelog, CoopMap, CoopRanked, Maps, SpMap, Users}; use anyhow::{bail, Result}; use num::pow; use sqlx::PgPool; use std::collections::HashMap; pub fn score(i: i32) -> f32 { if i > 200 { 0.0 } else { let i = i as f32; let res: f32 = pow(200.0 - (i...
use crate::models::models::{CalcValues, Changelog, CoopMap, CoopRanked, Maps, SpMap, Users}; use anyhow::{bail, Result}; use num::pow; use sqlx::PgPool; use std::collections::HashMap; pub fn score(i: i32) -> f32 { if i > 200 { 0.0 } else { let i = i as f32; let res: f32 = pow(200.0 - (i...
, _ => match remove_dups.insert(entry.profile_number2.clone(), 1) { Some(_) => { coop_entries_filtered.push(CoopRanked { map_data: entry.clone(), rank: i, points: score(i), ...
match remove_dups.insert(entry.profile_number2.clone(), 1) { Some(_) => (), _ => { coop_entries_filtered.push(CoopRanked { map_data: entry.clone(), rank: i, points: score(i), }...
if_condition
[ { "content": "pub fn score_calc(score: i32) -> (i32, i32, i32) {\n\n let ms = (score % 100) * 10;\n\n let seconds = (score / 100) % 60;\n\n let minutes = score / 100 / 60;\n\n (ms, seconds, minutes)\n\n}\n\n\n", "file_path": "backend/src/points.rs", "rank": 1, "score": 132902.07465645872...
Rust
starlark/src/debug/inspect.rs
jsgf/starlark-rust-1
64c620945dff592141d6932af073175815d02fa0
/* * Copyright 2019 The Starlark in Rust Authors. * 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 * * https://www.apache.org/lic...
/* * Copyright 2019 The Starlark in Rust Authors. * 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 * * https://www.apache.org/lic...
}
iables(), struct(x = 1, y = "hello", z = 6, _magic = True)) f(y = "hello") assert_eq(debug_inspect_variables(), struct(root = 12, f = f, _ignore = [True])) "#, ); }
function_block-function_prefixed
[ { "content": "def f(x, xs = []):\n\n xs.append(x)\n\n return xs\n\npre = str(f(8, [6,7]))\n\nf(1)\n\npost = str(f(2))\n\npre == '[6, 7, 8]' and post == '[1, 2]'\",\n\n );\n\n}\n\n\n", "file_path": "starlark/src/eval/tests.rs", "rank": 0, "score": 320319.031453921 }, { "content": "//...
Rust
src/main.rs
euank/somo
27c2e86d7767d9312f6f480eabb3f4996b9717f8
use clap::{App, AppSettings, Arg}; use libc; use log::debug; use nix::sys::signal; use nix::unistd::Pid; use std::os::unix::process::CommandExt; use std::process::Command; fn main() { env_logger::init(); let opts = App::new("somo") .setting(AppSettings::TrailingVarArg) .arg( Arg::w...
use clap::{App, AppSettings, Arg}; use libc; use log::debug; use nix::sys::signal; use nix::unistd::Pid; use std::os::unix::process::CommandExt; use std::process::Command; fn main() { env_logger::init(); let opts = App::new("somo") .setting(AppSettings::TrailingVarArg) .arg( Arg::w...
:sys::wait::WaitStatus::PtraceSyscall(pid) => { panic!("todo: support for ptrace syscall event: {}", pid) } } } Ok(exitcode) } fn wait_and_forward_signal(parent_sigset: signal::SigSet, child_pid: u32) -> Result<(), String> { let mut sig: std::mem::MaybeUninit<libc::sigi...
match waitres { nix::sys::wait::WaitStatus::StillAlive => { break }, nix::sys::wait::WaitStatus::Exited(pid, status) => { debug!("Reaped child with pid {}", pid); if pid == Pid::from_raw(child_pid as i32) { debu...
function_block-random_span
[]
Rust
trust-graph/src/key_pair.rs
xdralex/fluence
81ae6c0ec016176337282ea379ac279d45737c83
/* * Copyright 2020 Fluence Labs Limited * * 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 a...
/* * Copyright 2020 Fluence Labs Limited * * 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 a...
#[allow(dead_code)] pub fn public_key(&self) -> PublicKey { self.key_pair.public() } pub fn sign(&self, msg: &[u8]) -> Vec<u8> { self.key_pair.sign(msg) } pub fn verify(pk: &PublicKey, msg: &[u8], signature: &[u8]) -> Result<(), String> { if pk.verify(m...
gnatureError> { let kp = ed25519_dalek::Keypair::from_bytes(kp)?; Ok(Self { key_pair: kp.into(), }) }
function_block-function_prefixed
[ { "content": "pub fn to_peer_id(kp: &Keypair) -> PeerId {\n\n PeerId::from(PublicKey::Ed25519(kp.public()))\n\n}\n", "file_path": "crates/config-utils/src/config.rs", "rank": 0, "score": 187783.9346023975 }, { "content": "/// Adds a module to the filesystem, overwriting existing module.\n...
Rust
crates/discrust_core/src/feature.rs
jinlow/discrust
d6c9d34548cc274f710ba7e1cb6aef2ad4a6ec99
use crate::utils::nan_safe_compare; use crate::DiscrustError; use std::{cmp::Ordering, collections::HashMap}; #[derive(Debug)] pub struct Feature { pub vals_: Vec<f64>, cuml_ones_ct_: Vec<f64>, cuml_zero_ct_: Vec<f64>, cuml_totals_ct_: Vec<f64>, total_ones_: f64, total_zero_: f64, pub excep...
use crate::utils::nan_safe_compare; use crate::DiscrustError; use std::{cmp::Ordering, collections::HashMap}; #[derive(Debug)] pub struct Feature { pub vals_: Vec<f64>, cuml_ones_ct_: Vec<f64>, cuml_zero_ct_: Vec<f64>, cuml_totals_ct_: Vec<f64>, total_ones_: f64, total_zero_: f64, pub excep...
let f = Feature::new(&x_, &y_, &w_, &Vec::new()).unwrap(); assert_eq!(f.vals_, vec![1.0, 2.0]); assert_eq!(f.cuml_totals_ct_, vec![2.0, 8.0]); assert_eq!(f.cuml_ones_ct_, vec![1.0, 7.0]); } #[test] fn test_split_iv_woe() { let x...
_iv = (rhs_ones_dist - rhs_zero_dist) * rhs_woe; ((lhs_iv, lhs_woe), (rhs_iv, rhs_woe)) } pub fn split_totals_ct_ones_ct( &self, split_idx: usize, start: usize, stop: usize, ) -> ((f64, f64), (f64, f64)) { let split_idx = split_idx + 1 + start; let ...
random
[ { "content": "#[allow(dead_code)]\n\npub fn first_greater_than<T: std::cmp::PartialOrd>(x: &[T], v: &T) -> usize {\n\n let mut low = 0;\n\n let mut high = x.len();\n\n while low != high {\n\n let mid = (low + high) / 2;\n\n if x[mid] <= *v {\n\n low = mid + 1;\n\n } else...
Rust
src/updater/tera_helpers/function.rs
jmfiaschi/chewdata
58eb814ca749da682de57b82ac17bccdbebc8e4c
use serde_json::value::Value; use std::collections::HashMap; use tera::*; use uuid::Uuid; pub fn uuid_v4(args: &HashMap<String, Value>) -> Result<Value> { let uuid = Uuid::new_v4(); let value_format = match args.get("format") { Some(val) => try_get_value!("uuid_v4", "format", Value, val), None ...
use serde_json::value::Value; use std::collections::HashMap; use tera::*; use uuid::Uuid; pub fn uuid_v4(args: &HashMap<String, Value>) -> Result<Value> { let uuid = Uuid::new_v4(); let value_format = match args.get("format") { Some(val) => try_get_value!("uuid_v4", "format", Value, val), None ...
pub fn base64_encode(args: &HashMap<String, Value>) -> Result<Value> { let decode_string = match args.get("value") { Some(val) => match from_value::<String>(val.clone()) { Ok(v) => v, Err(_) => { return Err(Error::msg(format!( "Function `base64_e...
r(_) => { return Err(Error::msg(format!( "Function `set_env` received name={} but `name` can only be a string", val ))); } }, None => { return Err(Error::msg( "Function `set_env` didn't receiv...
function_block-function_prefixed
[ { "content": "/// Merge two Value together.\n\n///\n\n/// # Example: Merge single array of scalar.\n\n/// ```\n\n/// use std::collections::HashMap;\n\n/// use serde_json::value::Value;\n\n/// use json_value_merge::Merge;\n\n/// use chewdata::updater::tera_helpers::filters::object::merge;\n\n///\n\n/// let mut a...
Rust
slides/advanced/lesson11/frontier/vendor/substrate/frame/identity/src/benchmarking.rs
DaviRain-Su/substrate-course
86dad9b976e42b2c6b3de82b49bdf7d069ff88de
#![cfg(feature = "runtime-benchmarks")] use super::*; use frame_system::RawOrigin; use sp_io::hashing::blake2_256; use frame_benchmarking::benchmarks; use sp_runtime::traits::Bounded; use crate::Module as Identity; fn account<T: Trait>(name: &'static str, index: u32) -> T::AccountId { let entropy = (name, index)...
#![cfg(feature = "runtime-benchmarks")] use super::*; use frame_system::RawOrigin; use sp_io::hashing::blake2_256; use frame_benchmarking::benchmarks; use sp_runtime::traits::Bounded; use crate::Module as Identity; fn account<T: Trait>(name: &'static str, index: u32) -> T::AccountId { let entropy = (name, index)...
fn create_sub_accounts<T: Trait>(who: &T::AccountId, s: u32) -> Result<Vec<(T::AccountId, Data)>, &'static str> { let mut subs = Vec::new(); let who_origin = RawOrigin::Signed(who.clone()); let data = Data::Raw(vec![0; 32]); for i in 0..s { let sub_account = account::<T>("sub", i); subs.push((sub_account, da...
let _ = T::Currency::make_free_balance_be(&account::<T>("registrar", i), BalanceOf::<T>::max_value()); Identity::<T>::add_registrar(RawOrigin::Root.into(), account::<T>("registrar", i))?; Identity::<T>::set_fee(RawOrigin::Signed(account::<T>("registrar", i)).into(), i.into(), 10.into())?; let fields = IdentityFie...
function_block-function_prefix_line
[ { "content": "fn main() -> sc_cli::Result<()> {\n\n command::run()\n\n}\n", "file_path": "substrate-node-template/node/src/main.rs", "rank": 0, "score": 144016.13729929546 }, { "content": "fn main() -> sc_cli::Result<()> {\n\n\tcommand::run()\n\n}\n", "file_path": "slides/advanced/les...
Rust
src/bigint.rs
pebble8888/modular-polynomial
5a3c3a239d534a423869fb12f743e4aced35c02e
use num_integer::Integer; use num_bigint::BigInt; use num_traits::Zero; use num_traits::One; pub trait Power<T> { fn power(&self, n: T) -> Self; } pub trait PowerModulo { fn power_modulo(&self, n: &BigInt, p: &BigInt) -> Self; } pub trait Inverse { fn inverse(&self, p: &BigInt) -> Self; } impl Power<Big...
use num_integer::Integer; use num_bigint::BigInt; use num_traits::Zero; use num_traits::One; pub trait Power<T> { fn power(&self, n: T) -> Self; } pub trait PowerModulo { fn power_modulo(&self, n: &BigInt, p: &BigInt) -> Self; } pub trait Inverse { fn inverse(&self, p: &BigInt) -> Self; } impl Power<Big...
#[test] fn extended_euclid_test1() { let (g, x, y) = extended_gcd(BigInt::from(8), BigInt::from(11)); assert_eq!(g, BigInt::from(1)); assert_eq!(x, BigInt::from(-4)); assert_eq!(y, BigInt::from(3)); } #[test] fn extended_euclid_test2() { let (g, x, y) = extended_gcd(BigInt::from(11), BigInt::fro...
assert_eq_str!((BigInt::from(7).mod_floor(&BigInt::from(-3))), "-2"); assert_eq_str!((BigInt::from(-7).mod_floor(&BigInt::from(3))), "2"); assert_eq_str!((BigInt::from(-7).mod_floor(&BigInt::from(-3))), "-1"); }
function_block-function_prefix_line
[ { "content": "/// Calculate the order of the Elliptic curve y^2 = x^3 + a x + b\n\n/// schoof algorithm\n\npub fn schoof(a: &BigInt, b: &BigInt, q: i32) -> Vec<bigint::ModResult> {\n\n let qq = BigInt::from(q);\n\n let mut mod_result: Vec<bigint::ModResult> = Vec::new();\n\n // l = 2\n\n let l: BigI...
Rust
crates/xetex_format/src/eqtb.rs
wischi-chr/tectonic
8c01b6d98ade3fc38177f0e163133293b95ed9f1
use nom::{multi::count, number::complete::be_u8, IResult}; use tectonic_errors::prelude::*; use crate::{ base::{self, SIZEOF_MEMORY_WORD, TEX_NULL}, commands::CommandCode, engine::Engine, parseutils, symbols::{SymbolCategory, SymbolTable}, }; #[derive(Debug)] pub struct EquivalenciesTable { ...
use nom::{multi::count, number::complete::be_u8, IResult}; use tectonic_errors::prelude::*; use crate::{ base::{self, SIZEOF_MEMORY_WORD, TEX_NULL}, commands::CommandCode, engine::Engine, parseutils, symbols::{SymbolCategory, SymbolTable}, }; #[derive(Debug)] pub struct EquivalenciesTable { ...
al_base + n_locals; symbols.add(SymbolCategory::Eqtb, "TOKS_BASE", toks_base)?; let etex_pen_base = toks_base + base::NUMBER_REGS as isize; symbols.add(SymbolCategory::Eqtb, "ETEX_PEN_BASE", etex_pen_base)?; let box_base = etex_pen_base + n_etex_pens; symbols.add(SymbolCategory::Eqtb, "BOX_BASE", ...
function_block-function_prefixed
[ { "content": "#[inline(always)]\n\npub fn memword_write_b16_s1(arr: &mut [u8], index: i32, value: i16) {\n\n let i = index as usize * SIZEOF_MEMORY_WORD;\n\n FormatEndian::write_i16(&mut arr[i + 4..i + 6], value);\n\n}\n\n\n\n/// Write *value* to the `b32.s0` field of the *index*'th word in *arr*.\n\n///...
Rust
plexus/src/graph/mutation/mod.rs
olson-sean-k/plexus
2c1340a17b41513c742f9cfa09067353806da915
pub mod edge; pub mod face; pub mod path; pub mod vertex; use std::marker::PhantomData; use std::ops::{Deref, DerefMut}; use crate::entity::storage::{AsStorage, AsStorageMut, StorageTarget}; use crate::entity::Entity; use crate::graph::core::OwnedCore; use crate::graph::data::{Data, Parametric}; use crate::graph::edg...
pub mod edge; pub mod face; pub mod path; pub mod vertex; use std::marker::PhantomData; use std::ops::{Deref, DerefMut}; use crate::entity::storage::{AsStorage, AsStorageMut, StorageTarget}; use crate::entity::Entity; use crate::graph::core::OwnedCore; use crate::graph::data::{Data, Parametric}; use crate::graph::edg...
(Self::Abort, Self::Error)> { self.inner.commit().map(|core| core.into()) } fn abort(self) -> Self::Abort {} } pub trait Mutable: Consistent + From<OwnedCore<Data<Self>>> + Parametric + Into<OwnedCore<Data<Self>>> { } impl<M, G> Mutable for M where M: Consistent + From<OwnedCore<G>> + Paramet...
Face<Data<P::Graph>>> for Mutation<P> where P: Mode, P::Graph: Consistent + From<OwnedCore<Data<P::Graph>>> + Into<OwnedCore<Data<P::Graph>>>, { fn as_storage(&self) -> &StorageTarget<Face<Data<P::Graph>>> { self.inner.to_ref_core().unfuse().3 } } impl<P> AsStorage<Vertex<Data<P::Graph>>> for M...
random
[ { "content": "pub fn insert<N, P>(mut mutation: N, data: <Data<P::Graph> as GraphData>::Vertex) -> VertexKey\n\nwhere\n\n N: AsMut<Mutation<P>>,\n\n P: Mode,\n\n P::Graph: Mutable,\n\n{\n\n mutation\n\n .as_mut()\n\n .storage\n\n .as_storage_mut()\n\n .insert(Vertex::new(...
Rust
src/geom/rt/orient.rs
aetherus-wg/aetherus
f08686ab4898b23aeccd03369a252a174bbebdd0
use crate::{ access, fmt_report, geom::Ray, math::{Dir3, Point3, Vec3}, }; use std::fmt::{Display, Error, Formatter}; #[derive(Debug)] pub struct Orient { pos: Point3, forward: Dir3, right: Dir3, up: Dir3, } impl Orient { access!(pos, pos_mut: Point3); access!...
use crate::{ access, fmt_report, geom::Ray, math::{Dir3, Point3, Vec3}, }; use std::fmt::{Display, Error, Formatter}; #[derive(Debug)] pub struct Orient { pos: Point3, forward: Dir3, right: Dir3, up: Dir3, } impl Orient { access!(pos, pos_mut: Point3); access!...
0.0, 0.0); let target = Point3::new(1.0, 1.0, 1.0); let orient = Orient::new_tar(pos, &target); assert_eq!(orient.pos(), &Point3::new(0.0, 0.0, 0.0)); assert_eq!(orient.forward(), &Dir3::new(1.0, 1.0, 1.0)); assert_approx_eq!(orient.left().x(), -1.0...
ay(&self) -> Ray { Ray::new(self.pos, -self.up) } #[inline] #[must_use] pub fn right_ray(&self) -> Ray { Ray::new(self.pos, self.right) } #[inline] #[must_use] pub fn left_ray(&self) -> Ray { Ray::new(self.pos, -self.right) } } impl Display for Or...
random
[ { "content": "#[inline]\n\npub fn name() -> Result<String, Error> {\n\n let args: Vec<String> = args().collect();\n\n\n\n Ok(Path::new(&args[0])\n\n .file_stem()\n\n .ok_or(\"Missing filename.\")?\n\n .to_str()\n\n .ok_or(\"Missing string.\")?\n\n .to_owned())\n\n}\n", ...
Rust
src/wifi.rs
AidoP/blockade-recon
4116a6ff6e01ca040ca377719f6a6a9c2ff198b8
use eui48::MacAddress; macro_rules! mac { ($bytes:expr => $start:expr) => { MacAddress::new([ $bytes[$start], $bytes[$start + 1], $bytes[$start + 2], $bytes[$start + 3], $bytes[$start + 4], $bytes[$start + 5] ]) }; } macro_...
use eui48::MacAddress; macro_rules! mac { ($bytes:expr => $start:expr) => { MacAddress::new([ $bytes[$start], $bytes[$start + 1], $bytes[$start + 2], $bytes[$start + 3], $bytes[$start + 4], $bytes[$start + 5] ]) }; } macro_...
&frame[24..frame.len() - 4]; let tags = ManagementTag::parse_all(&data[12..])?; let fields = ManagementFields::Beacon { timestamp: u64!(le[data => 0]), ssid: tags.iter().find_map(|t| if let ManagementTag::Ssid(ssid) = t { Some(ssid.clone()) } else { None }).ok_or(...
let flags = frame[1]; let duration = u16::from_le_bytes([frame[2], frame[3]]); let address1 = mac!(frame => 4); let version = frame_control & 0b11; if version != 0 { return Err(Error::InvalidVersion(version)); } let frame_type = FrameType::new( ...
random
[ { "content": "fn main() {\n\n let response = reqwest::blocking::get(\"https://gitlab.com/wireshark/wireshark/raw/master/manuf\").expect(\"Unable to fetch OUI database\");\n\n let oui_raw = response.text().expect(\"Unable to read OUI database contents\");\n\n let db = oui::OuiDatabase::new_from_str(&oui...
Rust
src/data/security.rs
open-voice-network/vrs
914698597d87846d8c2234721392b9d80ebcc99f
/* Copyright 2021 The Open Voice Network * * 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 ag...
/* Copyright 2021 The Open Voice Network * * 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 ag...
amp value")) } } pub fn sign_token(user_id: String) -> AnyResult<String> { let exp = Utc::now() + chrono::Duration::days(1); let claims = Claims::new(exp, user_id); let token = jsonwebtoken::encode( &jsonwebtoken::Header::default(), &claims, &EncodingKey::from_secret(SECRE...
4::deserialize(deserializer)?, 0) .single() .ok_or_else(|| serde::de::Error::custom("invalid Unix timest
function_block-random_span
[ { "content": "#[get(\"/health\")]\n\npub fn health_fn() -> String {\n\n \"I am healthy!\".to_string()\n\n}\n", "file_path": "src/routes/health.rs", "rank": 1, "score": 115091.31727561663 }, { "content": "pub fn setup () -> &'static Client {\n\n lazy_static! {\n\n static ref CLIE...
Rust
src/sources/imf_sdr.rs
iqlusioninc/delphi
ccfbc5b9794bc6a72c63202b56b0635efcdd52c0
use crate::{ config::HttpsConfig, error::{Error, ErrorKind}, prelude::*, Currency, Price, TradingPair, }; use bytes::Buf; use iqhttp::HttpsClient; use serde::{Deserialize, Serialize}; use std::convert::TryFrom; pub const API_HOST: &str = "www.imf.org"; pub struct ImfSdrSource { https_client: Htt...
use crate::{ config::HttpsConfig, error::{Error, ErrorKind}, prelude::*, Currency, Price, TradingPair, }; use bytes::Buf; use iqhttp::HttpsClient; use serde::{Deserialize, Serialize}; use std::convert::TryFrom; pub const API_HOST: &str = "www.imf.org"; pub struct ImfSdrSource { https_client: Htt...
} Err(_e) => continue, }; } match response_row { Some(resp) => Response::try_from(resp) .map_err(|e| format_err!(ErrorKind::Parse, "{}, {}", e, pair).into()), None => Err(format_err!(ErrorKind::Parse, "price for {} not...
if imf_sdr_row.currency == pair.0.imf_long_name() { response_row = Some(imf_sdr_row); break; }
if_condition
[ { "content": "/// Lowest bid price\n\npub fn highest_bid<T: BidBook>(bids: &T) -> Result<Price, Error> {\n\n let mut bids = bids.bids()?;\n\n bids.sort();\n\n Ok(bids.last().unwrap().price)\n\n}\n\n\n", "file_path": "src/sources.rs", "rank": 1, "score": 132208.54713368285 }, { "cont...
Rust
aml/src/value.rs
cmsd2/acpi
ba7aa9eec938a466a8614009c7a537fa181e2401
use crate::{misc::ArgNum, namespace::AmlName, AmlError}; use alloc::{boxed::Box, string::String, vec::Vec}; use bit_field::BitField; #[derive(Clone, Copy, PartialEq, Eq, Debug)] pub enum RegionSpace { SystemMemory, SystemIo, PciConfig, EmbeddedControl, SMBus, SystemCmos, PciBarTarget, I...
use crate::{misc::ArgNum, namespace::AmlName, AmlError}; use alloc::{boxed::Box, string::String, vec::Vec}; use bit_field::BitField; #[derive(Clone, Copy, PartialEq, Eq, Debug)] pub enum RegionSpace { SystemMemory, SystemIo, PciConfig, EmbeddedControl, SMBus, SystemCmos, PciBarTarget, I...
b arg_5: Option<AmlValue>, pub arg_6: Option<AmlValue>, } impl Args { pub fn arg(&self, num: ArgNum) -> Result<&AmlValue, AmlError> { match num { 0 => self.arg_0.as_ref().ok_or(AmlError::InvalidArgumentAccess(num)), 1 => self.arg_1.as_ref().ok_or(AmlError::In...
pRegion { region: RegionSpace, offset: u64, length: u64 }, Field { region: AmlName, flags: FieldFlags, offset: u64, length: u64 }, Device, Method { flags: MethodFlags, code: Vec<u8> }, Buffer { bytes: Vec<u8>, size: u64 }, Processor { id: u8, pblk_address: u32, pblk_len: u8 }, Mutex { sync_level...
random
[ { "content": "fn is_name_char(byte: u8) -> bool {\n\n is_lead_name_char(byte) || is_digit_char(byte)\n\n}\n\n\n\n#[cfg(test)]\n\nmod tests {\n\n use super::*;\n\n use crate::{parser::Parser, test_utils::*, AmlContext, AmlError};\n\n\n\n #[test]\n\n fn test_name_seg() {\n\n let mut context ...
Rust
iml-graphql-queries/src/snapshot.rs
intel-hpdd/-intel-manager-for-lustre
f8a6f61205b42cc62f4bbcb8d81214ad4f215cd6
pub mod create { use crate::Query; use iml_wire_types::Command; pub static QUERY: &str = r#" mutation CreateSnapshot($fsname: String!, $name: String!, $comment: String, $use_barrier: Boolean) { createSnapshot(fsname: $fsname, name: $name, comment: $comment, useBarrier: $use_barr...
pub mod create { use crate::Query; use iml_wire_types::Command; pub static QUERY: &str = r#" mutation CreateSnapshot($fsname: String!, $name: String!, $comment: String, $use_barrier: Boolean) { createSnapshot(fsname: $fsname, name: $name, comment: $comment, useBarrier: $use_barr...
pub fn build( fsname: impl ToString, interval: String, use_barrier: Option<bool>, ) -> Query<Vars> { Query { query: QUERY.to_string(), variables: Some(Vars { fsname: fsname.to_string(), interval, use_barrie...
ation CreateSnapshotInterval($fsname: String!, $interval: Duration!, $use_barrier: Boolean) { createSnapshotInterval(fsname: $fsname, interval: $interval, useBarrier: $use_barrier) } "#; #[derive(Debug, serde::Serialize)] pub struct Vars { fsname: String, interval: Strin...
random
[ { "content": "fn check_id(cloned: bool, id: &str, res: String) -> String {\n\n if cloned && id == res {\n\n format!(\"cl-{}\", id)\n\n } else {\n\n res\n\n }\n\n}\n\n\n", "file_path": "iml-agent/src/action_plugins/high_availability/mod.rs", "rank": 0, "score": 387743.950003949...
Rust
src/config.rs
szymonm/mainframer
7d47e915d52238524d6ab409ec5ee8e7b5da419c
use std::fs::File; use std::io::prelude::*; use std::path::Path; #[derive(Debug, PartialEq, Eq)] pub struct Config { pub remote_machine_name: String, pub local_compression_level: u8, pub remote_compression_level: u8, } impl Config { pub fn from_file(file_path: &Path) -> Result<Config, String> { ...
use std::fs::File; use std::io::prelude::*; use std::path::Path; #[derive(Debug, PartialEq, Eq)] pub struct Config { pub remote_machine_name: String, pub local_compression_level: u8, pub remote_compression_level: u8, } impl Config { pub fn from_file(file_path: &Path) -> Result<Config, String> { ...
emote_compression_level=3"; assert_eq!(parse_config_from_str(content), Ok(Config { remote_machine_name: String::from("test@machine"), local_compression_level: 2, remote_compression_level: 3, })); } #[test] fn parse_config_from_str_all_fields_unordered() {...
assert_eq!(find_value(content, "key"), Some(String::from("value"))); } #[test] fn find_value_new_line_at_the_end() { let content = "key=value\n"; assert_eq!(find_value(content, "key"), Some(String::from("value"))); } #[test] fn find_value_trims_value() { let content...
random
[ { "content": "fn push_value_and_label(text: &mut String, value: u64, label: &str) {\n\n write!(text, \"{} {}\", value, label).unwrap();\n\n}\n\n\n\n#[cfg(test)]\n\nmod tests {\n\n use super::*;\n\n\n\n #[test]\n\n fn format_duration_0_seconds() {\n\n assert_eq!(format_duration(Duration::from_...
Rust
src/server.rs
dmrolfs/raftor-dissection
ef028a599d67e6b8671a9ee9db435f025da5e60c
use actix::prelude::*; use actix_raft::NodeId; use serde::{Deserialize, Serialize}; use std::collections::{HashMap, HashSet}; use log::info; use crate::hash_ring::RingType; use crate::network::{DistributeMessage, DistributeAndWait, Network}; use crate::session::{self, Session}; pub struct Server { rooms: HashMap<...
use actix::prelude::*; use actix_raft::NodeId; use serde::{Deserialize, Serialize}; use std::collections::{HashMap, HashSet}; use log::info; use crate::hash_ring::RingType; use crate::network::{DistributeMessage, DistributeAndWait, Network}; use crate::session::{self, Session}; pub struct Server { rooms: HashMap<...
clone(), }); } } } else { self.net .do_send(DistributeMessage(msg.room_id.clone(), msg)); } } } #[derive(Message, Serialize, Deserialize, Debug)] pub struct CreateRoom { pub room_id: String, } impl Handler<CreateRoom> ...
pient_id: String, pub uid: String, pub content: String, } #[derive(Message, Serialize, Deserialize, Debug)] pub struct SendRoom { pub room_id: String, pub uid: String, pub content: String, } #[derive(Message)] pub struct Rebalance; impl Actor for Server { type Context = Context<Self>; } impl...
random
[ { "content": "pub fn make_service(network: Addr<RaftRouter> ) -> RouterServer<RaftStubService> {\n\n let raft_stub = RaftStubService { network, };\n\n RouterServer::new( raft_stub )\n\n}\n", "file_path": "src/raft/grpc_client.rs", "rank": 0, "score": 143505.69002778607 }, { "content": ...
Rust
gooey/examples/widget_explorer_screens/mod.rs
BarePotato/gooey
da2a82dc622616c68e5553b827f0185a13ac5079
use std::{borrow::Cow, fmt::Debug}; use gooey::{ core::{ styles::{Alignment, VerticalAlignment}, WeakWidgetRegistration, }, widgets::{ button::Button, component::{Behavior, Component, Content, EventMapper}, label::Label, layout::{Dimension, Layout, WidgetLayo...
use std::{borrow::Cow, fmt::Debug}; use gooey::{ core::{ styles::{Alignment, VerticalAlignment}, WeakWidgetRegistration, }, widgets::{ button::Button, component::{Behavior, Component, Content, EventMapper}, label::Label, layout::{Dimension, Layout, WidgetLayo...
fn receive_event( component: &mut gooey_widgets::component::Component<Self>, event: Self::Event, context: &gooey_core::Context<gooey_widgets::component::Component<Self>>, ) { let button = &component.buttons[event]; if let Some(navigator) = component.navigator.upgrade() ...
with(Alignment::Center) .with(VerticalAlignment::Center), WidgetLayout::build() .top(Dimension::zero()) .right(Dimension::zero()) .left(Dimension::zero()) .height(Dimension::percent(80.)) .finish(), ); ...
function_block-function_prefix_line
[ { "content": "/// A key for a widget.\n\npub trait Key: Clone + Hash + Debug + Eq + PartialEq + Send + Sync + 'static {}\n\n\n\nimpl<T> Key for T where T: Clone + Hash + Debug + Eq + PartialEq + Send + Sync + 'static {}\n\n\n\nimpl<K: Key> KeyedStorage<K> for WidgetStorage {\n\n fn register<W: Widget + AnyWi...
Rust
src/test_harness.rs
xarvic/panoramix
db65b4d9cc928baad25aa7bbb9a0a4b7926628ba
use crate::glue::{DebugState, DruidAppData}; use crate::Element; use crate::RootWidget; use druid::tests::harness::Harness as DruidHarness; use druid::{ Command, Event, KeyEvent, Modifiers, MouseButton, MouseButtons, MouseEvent, Point, RawMods, Vec2, WidgetId, WidgetState, }; use std::any::Any; pub struct H...
use crate::glue::{DebugState, DruidAppData}; use crate::Element; use crate::RootWidget; use druid::tests::harness::Harness as DruidHarness; use druid::{ Command, Event, KeyEvent, Modifiers, MouseButton, MouseButtons, MouseEvent, Point, RawMods, Vec2, WidgetId, WidgetState, }; use std::any::Any; pub struct H...
pub fn mouse_move_to(&mut self, id: WidgetId) { let widget_rect = self.druid_harness.get_state(id).layout_rect(); let widget_center = widget_rect.center(); self.mouse_move(widget_center); } pub fn keyboard_key(&mut self, key: &str) { let event = KeyEvent::for_te...
e(widget_center); self.mouse_button_press(MouseButton::Left); self.mouse_button_release(MouseButton::Left); }
function_block-function_prefixed
[ { "content": "#[component]\n\nfn WrongEvent(ctx: &CompCtx, id: WidgetId) -> impl Element<Event = NoEvent> {\n\n let md = ctx.use_metadata::<MyEvent, u16>();\n\n let button = Button::new(\"Hello\")\n\n .with_reserved_id(id)\n\n .map_event(md, |_, _event| Some(MyEvent));\n\n let wrong_md: M...
Rust
server/src/main.rs
KirbinaVA/lab3
e3a0a7aaf8ab735983e774ab7ef351199594a6ae
/* Реализовать на языке Rust tcp клиент/сервер (общее приложение, режим определяется параметрами), способное установить сокет соединение и последовательно обмениваться сообщениями. На каждой стороне реализуется алгоритм переменных ключей (смотри реализацию на Python - protector.py). На каждом шаге обмена вычисляется сл...
/* Реализовать на языке Rust tcp клиент/сервер (общее приложение, режим определяется параметрами), способное установить сокет соединение и последовательно обмениваться сообщениями. На каждой стороне реализуется алгоритм переменных ключей (смотри реализацию на Python - protector.py). На каждом шаге обмена вычисляется сл...
; let contents = fs::read_to_string(filename).unwrap(); let response = format!("{}{}", status_line, contents); stream.write(response.as_bytes()).unwrap(); stream.flush().unwrap(); } fn handle_client(mut stream: TcpStream) -> Result<(), Error> { println!("Incoming connection from: {}", stream.pee...
if buffer.starts_with(sleep) { thread::sleep(Duration::from_secs(5)); ("HTTP/1.1 200 OK\r\n\r\n", "hello.html") } else { ("HTTP/1.1 404 NOT FOUND\r\n\r\n", "404.html") }
if_condition
[ { "content": "// generate 10 char random string\n\npub fn get_session_key() -> String {\n\n let mut rng = rand::thread_rng();\n\n let mut s = String::new();\n\n\n\n for _ in 0..10 {\n\n let rand_number = rng.gen_range(1, 9);\n\n let c = char::from_digit(rand_number, 10).unwrap();\n\n ...
Rust
src/image/bitmap1/builder.rs
toolness/direct2d-rs
21d712829471d72df63cbaf391bfcd6b5e63f874
use crate::descriptions::PixelFormat; use crate::device_context::DeviceContext; use crate::enums::{AlphaMode, BitmapOptions}; use crate::image::Bitmap1; use crate::properties::BitmapProperties1; use checked_enum::UncheckedEnum; use com_wrapper::ComWrapper; use dcommon::error::Error; use dxgi::enums::Format; use math2d...
use crate::descriptions::PixelFormat; use crate::device_context::DeviceContext; use crate::enums::{AlphaMode, BitmapOptions}; use crate::image::Bitmap1; use crate::properties::BitmapProperties1; use checked_enum::UncheckedEnum; use com_wrapper::ComWrapper; use dcommon::error::Error; use dxgi::enums::Format; use math2d...
#[inline] pub unsafe fn with_format_unchecked(mut self, format: UncheckedEnum<Format>) -> Self { self.properties.pixel_format.format = format; self } }
stride: u32, ) -> Self { let size = size.into(); self.source = Some(Source::Memory { size, data, stride }); self }
function_block-function_prefix_line
[ { "content": "enum BitmapSource<'a> {\n\n Raw {\n\n source: Option<&'a [u8]>,\n\n pitch: u32,\n\n size: Sizeu,\n\n },\n\n Shared(IID, &'a IUnknown),\n\n // Wic(&'a wic::BitmapSource)\n\n}\n", "file_path": "src/image/bitmap/builder.rs", "rank": 0, "score": 149657.9834...
Rust
src/lib.rs
WilliamVenner/cfg_table
41f60519240b9df4a303db0a89fa93cf2c33c8d0
#[macro_export] macro_rules! cfg_table { () => { unreachable!() }; (_ => $expr:expr,) => {{ $expr }}; ([$cfg:meta] => $expr:expr, $($tail:tt)*) => {{ #[cfg($cfg)] { $expr } #[cfg(not($cfg))] { $crate::cfg_table!($($tail)*) ...
#[macro_export] macro_rules! cfg_table { () => { unreachable!() }; (_ => $expr:expr,) => {{ $expr }}; ([$cfg:meta] => $expr:expr, $($tail:tt)*) => {{ #[cfg($cfg)] { $expr } #[cfg(not($cfg))] { $crate::cfg_table!($($tail)*) ...
#[cfg(not(all(target_os = "linux", target_pointer_width = "64")))] { $crate::cfg_table!($($tail)*) } }}; (win32 => $expr:expr, $($tail:tt)*) => {{ #[cfg(all(target_os = "windows", target_pointer_width = "32"))] { $expr } #[cfg(not(all(target_os = "wind...
_os = "windows")] { $expr } #[cfg(not(target_os = "windows"))] { $crate::cfg_table!($($tail)*) } }}; (macos32 => $expr:expr, $($tail:tt)*) => {{ #[cfg(all(target_os = "macos", target_pointer_width = "32"))] { $expr } #[cfg(not(...
random
[ { "content": "[![crates.io](https://img.shields.io/crates/v/cfg_table.svg)](https://crates.io/crates/cfg_table)\n\n\n\n# ✨ `cfg_table`\n\n\n\nA simple macro that expands to different values across compilation targets.\n\n\n\n## Panics\n\n\n\nThis macro will panic at runtime if no matching value is found.\n\n\n\...
Rust
src/usb0/endpt.rs
mtayler/k22f-rs
8bed23920c33748d3ede8f3ddd3b86c76f767136
#[doc = "Reader of register ENDPT%s"] pub type R = crate::R<u8, super::ENDPT>; #[doc = "Writer for register ENDPT%s"] pub type W = crate::W<u8, super::ENDPT>; #[doc = "Register ENDPT%s `reset()`'s with value 0"] impl crate::ResetValue for super::ENDPT { type Type = u8; #[inline(always)] fn reset_value() -> ...
#[doc = "Reader of register ENDPT%s"] pub type R = crate::R<u8, super::ENDPT>; #[doc = "Writer for register ENDPT%s"] pub type W = crate::W<u8, super::ENDPT>; #[doc = "Register ENDPT%s `reset()`'s with value 0"] impl crate::ResetValue for super::ENDPT { type Type = u8; #[inline(always)] fn reset_value() -> ...
} } impl R { #[doc = "Bit 0 - When set this bit enables an endpoint to perform handshaking during a transaction to this endpoint"] #[inline(always)] pub fn ephshk(&self) -> EPHSHK_R { EPHSHK_R::new((self.bits & 0x01) != 0) } #[doc = "Bit 1 - When set this bit indicates that the endpoint is ...
ol) -> &'a mut W { self.w.bits = (self.w.bits & !(0x01 << 4)) | (((value as u8) & 0x01) << 4); self.w } } #[doc = "Reader of field `RETRYDIS`"] pub type RETRYDIS_R = crate::R<bool, bool>; #[doc = "Write proxy for field `RETRYDIS`"] pub struct RETRYDIS_W<'a> { w: &'a mut W, } impl<'a> RETRYDIS_W<...
random
[ { "content": "#[doc = \"Reset value of the register\"]\n\n#[doc = \"\"]\n\n#[doc = \"This value is initial value for `write` method.\"]\n\n#[doc = \"It can be also directly writed to register by `reset` method.\"]\n\npub trait ResetValue {\n\n #[doc = \"Register size\"]\n\n type Type;\n\n #[doc = \"Res...
Rust
src/solution/s0072_edit_distance.rs
tan-wei/my-leetcode-rust
3d7892a42294fe4891db396573b8ba81e9294380
/** * [72] Edit Distance * * Given two strings word1 and word2, return the minimum number of operations required to convert word1 to word2. * You have the following three operations permitted on a word: * * Insert a character * Delete a character * Replace a character * * * Example 1: * * Input: word1...
/** * [72] Edit Distance * * Given two strings word1 and word2, return the minimum number of operations required to convert word1 to word2. * You have the following three operations permitted on a word: * * Insert a character * Delete a character * Replace a character * * * Example 1: * * Input: word1...
n::min_distance_v2(word1, word2), result); } #[test] fn test_0072_example_2() { let word1 = "intention".to_string(); let word2 = "execution".to_string(); let result = 5; assert_eq!(Solution::min_distance(word1, word2), result); let word1 = "intention".to_string(); ...
n (replace 'n' with 'c') * exection -> execution (insert 'u') * * * Constraints: * * 0 <= word1.length, word2.length <= 500 * word1 and word2 consist of lowercase English letters. * */ pub struct Solution {} impl Solution { pub fn min_distance(word1: String, word2: String) -> i32 { le...
random
[ { "content": "/**\n\n * [0583] Delete Operation for Two Strings\n\n *\n\n * Given two strings word1 and word2, return the minimum number of steps required to make word1 and word2 the same.\n\n * In one step, you can delete exactly one character in either string.\n\n * \n\n * Example 1:\n\n *\n\n * Input: word1...
Rust
src/camera.rs
crst/traycer
d13b7ee030605569b1fa57cd2944bfca56ad5bbd
use crate::linalg::matrix::Matrix; use crate::linalg::tuple::Tuple; use crate::ray::Ray; use crate::utils::P0; use crate::world::World; use rayon::prelude::*; pub struct Camera { pub hsize: i64, pub vsize: i64, pub field_of_view: f64, pub transformation: Matrix, pub inv_transformation: Matrix, ...
use crate::linalg::matrix::Matrix; use crate::linalg::tuple::Tuple; use crate::ray::Ray; use crate::utils::P0; use crate::world::World; use rayon::prelude::*; pub struct Camera { pub hsize: i64, pub vsize: i64, pub field_of_view: f64, pub transformation: Matrix, pub inv_transformation: Matrix, ...
}
fn test_view_transform() { let from = Tuple::vector(1.0, 3.0, 2.0); let to = Tuple::vector(4.0, -2.0, 8.0); let up = Tuple::vector(1.0, 1.0, 0.0); let m = view_transform(&from, &to, &up); let expected = Matrix::from_values( &vec![ vec![-0.50709, 0.507...
function_block-full_function
[ { "content": "pub fn compute_intersection_data(result: &mut Vec<Intersection>, r: &Ray) -> () {\n\n for i in result.iter_mut() {\n\n i.point = r.position(i.t);\n\n i.normalv = i.object.normal_at(&i.point);\n\n i.eyev = r.direction.negate();\n\n i.inside = i.normalv.dot(&i.eyev) < ...
Rust
lox_lib/src/interpreter.rs
Dmarcano/lox_rs
dcf0efa86cbdee7e8e2d9875601044aba6ae9e6d
use crate::ast::{ExprNode, ExprVisitor, Literal, Operator, StmtNode, StmtVisitor}; use crate::lexer::Lexer; use crate::parser::Parser; use anyhow::{anyhow, Context, Result}; pub struct Interpreter; struct RuntimeErr { message: String, line: u32, } pub enum InterpreterMode { Script(String), Repl, } i...
use crate::ast::{ExprNode, ExprVisitor, Literal, Operator, StmtNode, StmtVisitor}; use crate::lexer::Lexer; use crate::parser::Parser; use anyhow::{anyhow, Context, Result}; pub struct Interpreter; struct RuntimeErr { message: String, line: u32, } pub enum InterpreterMode { Script(String), Repl, } i...
pub fn error(line: u32, message: String) -> String { Interpreter::report(line, "".into(), message) } pub fn report(line: u32, err_where: String, message: String) -> String { format!("[line {}] Error {}: {}", line, err_where, message) } fn check_type() -> Result<()> { Ok((...
t buf = String::new(); print!(">> "); let _ = std::io::stdin().read_line(&mut buf)?; let source = buf.trim().to_string(); println!("{}", source); if buf == "" { break; } self.run_on_string(buf.clone())?; } ...
function_block-function_prefixed
[ { "content": "type ParserBinaryFn = fn(&mut Parser, &mut Vec<Token>) -> Result<ExprNode>;\n\n\n\n/*\n\n Reference Lox Expression Grammar (So far)\n\n\n\n\n\n expression -> equality ;\n\n\n\n equality -> comparison ( (\"!=\" | \"==\") comparison )* ;\n\n\n\n comparison -> term ( (\">\" | \...
Rust
Chapter09/feruscore/src/bin/feruscore.rs
PacktPublishing/Hands-On-Concurrency-with-Rust
0540a7c04584e5dbd482aa498b045c6516bd62c5
extern crate feruscore; extern crate num_cpus; extern crate rand; use feruscore::individual::*; use feruscore::mars::*; use rand::{thread_rng, Rng}; use std::fs::{self, DirBuilder, File}; use std::io::{self, BufWriter}; use std::path::{Path, PathBuf}; use std::sync::atomic::{AtomicUsize, Ordering}; use std::sync::mpsc...
extern crate feruscore; extern crate num_cpus; extern crate rand; use feruscore::individual::*; use feruscore::mars::*; use rand::{thread_rng, Rng}; use std::fs::{self, DirBuilder, File}; use std::io::{self, BufWriter}; use std::path::{Path, PathBuf}; use std::sync::atomic::{AtomicUsize, Ordering}; use std::sync::mpsc...
fn island( recv: mpsc::Receiver<Vec<Individual>>, snd: mpsc::SyncSender<Vec<Individual>>, total_children: usize, ) -> () { let mut mars = MarsBuilder::default().core_size(CORE_SIZE).freeze(); while let Ok(mut population) = recv.recv() { population = sort_by_tournament(&mut mars, ...
er::Right(_) => { population.swap(i, right_idx); } Winner::Left(_) => { population.swap(i, left_idx); } Winner::Tie => {} } i -= 1; } population }
function_block-function_prefixed
[ { "content": "fn bench_imp_and_dwarf(core_size: u16, rounds: u16) -> () {\n\n let mut mars = MarsBuilder::default().core_size(core_size).freeze();\n\n let imp = ringers::imp(core_size);\n\n let dwarf = ringers::dwarf(core_size);\n\n mars.compete(rounds, &imp, &dwarf);\n\n}\n\n\n", "file_path": "...
Rust
cc13x0-pac/src/aon_wuc/rechargecfg.rs
jamesmunns/cc13x0-pac-example
adfe233d4fbefcd7c4c918270ce33b36f48f3830
#[doc = "Reader of register RECHARGECFG"] pub type R = crate::R<u32, super::RECHARGECFG>; #[doc = "Writer for register RECHARGECFG"] pub type W = crate::W<u32, super::RECHARGECFG>; #[doc = "Register RECHARGECFG `reset()`'s with value 0"] impl crate::ResetValue for super::RECHARGECFG { type Type = u32; #[inline(...
#[doc = "Reader of register RECHARGECFG"] pub type R = crate::R<u32, super::RECHARGECFG>; #[doc = "Writer for register RECHARGECFG"] pub type W = crate::W<u32, super::RECHARGECFG>; #[doc = "Register RECHARGECFG `reset()`'s with value 0"] impl crate::ResetValue for super::RECHARGECFG { type Type = u32; #[inline(...
_W { MAX_PER_M_W { w: self } } #[doc = "Bits 8:10 - MAX_PER_E"] #[inline(always)] pub fn max_per_e(&mut self) -> MAX_PER_E_W { MAX_PER_E_W { w: self } } #[doc = "Bits 3:7 - PER_M"] #[inline(always)] pub fn per_m(&mut self) -> PER_M_W { PER_M_W { w: self } } ...
field"] #[inline(always)] pub unsafe fn bits(self, value: u8) -> &'a mut W { self.w.bits = (self.w.bits & !(0x1f << 3)) | (((value as u32) & 0x1f) << 3); self.w } } #[doc = "Reader of field `PER_E`"] pub type PER_E_R = crate::R<u8, u8>; #[doc = "Write proxy for field `PER_E`"] pub struct PER...
random
[ { "content": "#[doc = \"Reset value of the register\"]\n\n#[doc = \"\"]\n\n#[doc = \"This value is initial value for `write` method.\"]\n\n#[doc = \"It can be also directly writed to register by `reset` method.\"]\n\npub trait ResetValue {\n\n #[doc = \"Register size\"]\n\n type Type;\n\n #[doc = \"Res...
Rust
op-rev/src/impls/git.rs
opereon/opereon
f230a4ce9e756249a38d1ed8e8480e4fb7200868
use super::*; use git2::build::CheckoutBuilder; use kg_diag::io::fs; use kg_diag::{BasicDiag, IntoDiagRes}; use std::sync::{Arc, Mutex}; use git2::Repository; pub type GitResult<T> = Result<T, BasicDiag>; #[derive(Debug, Display, Detail)] #[diag(code_offset = 1100)] pub enum GitErrorDetail { #[display(fmt = "ca...
use super::*; use git2::build::CheckoutBuilder; use kg_diag::io::fs; use kg_diag::{BasicDiag, IntoDiagRes}; use std::sync::{Arc, Mutex}; use git2::Repository; pub type GitResult<T> = Result<T, BasicDiag>; #[derive(Debug, Display, Detail)] #[diag(code_offset = 1100)] pub enum GitErrorDetail { #[display(fmt = "ca...
async fn get_file_diff(&mut self, old_rev_id: Oid, new_rev_id: Oid) -> Result<FileDiff, BasicDiag> { if old_rev_id.is_nil() { unimplemented!(); } let repo = self.repo(); spawn_blocking(move || { let repo = repo.lock().unwrap(); let m...
async fn commit(&mut self, message: &str) -> Result<Oid, BasicDiag> { let repo = self.repo(); let message = message.to_string(); spawn_blocking(move || { let repo = repo.lock().unwrap(); let sig = repo .signature() .map_err(|err| GitErrorD...
function_block-full_function
[ { "content": "pub fn init_repo<P: AsRef<Path>>(path: P) -> git2::Repository {\n\n git2::Repository::init(path).expect(\"Cannot init git repository!\")\n\n}\n\n\n", "file_path": "op-test-helpers/src/git.rs", "rank": 1, "score": 320723.2331785045 }, { "content": "pub fn initial_commit(path:...
Rust
src/rgb/mod.rs
dunkelstern/grapho-bitplane
4db3789284fa89c85e6b1b1c972aa4d42eda9bbf
use crate::*; pub use grapho_color::DigitalRGBAColor; #[derive(Debug, PartialEq, Clone, Copy)] pub enum RGBComponent { Red = 0, Green = 1, Blue = 2, Alpha = 3 } #[derive(Debug, PartialEq)] pub struct RGBPixelBuffer<'a> { width: usize, height: usize, stride: usize, fourcc: &'a str,...
use crate::*; pub use grapho_color::DigitalRGBAColor; #[derive(Debug, PartialEq, Clone, Copy)] pub enum RGBComponent { Red = 0, Green = 1, Blue = 2, Alpha = 3 } #[derive(Debug, PartialEq)] pub struct RGBPixelBuffer<'a> { width: usize, height: usize, stride: usize, fourcc: &'a str,...
} fn new_with_background(width: usize, height: usize, color: Self::ColorType, stride: Option<usize>, fourcc: Option<&'a str>) -> Self { let f = fourcc.unwrap_or("RGB"); ...
Ok( RGBPixelBuffer { width, height, data, stride: stride.unwrap_or(width * component_order.len()), fourcc: f, component_order } )
call_expression
[ { "content": " assert_eq!(buffer.height, 2);\n\n assert_eq!(buffer.stride, 2 * 3);\n\n assert_eq!(buffer.get_width(), 2);\n\n assert_eq!(buffer.get_height(), 2);\n\n assert_eq!(buffer.get_stride(), 2 * 3);\n\n }\n\n\n\n #[test]\n\n fn prefilled_buffer() {\n\n l...
Rust
assignment-3/problem-2/src/main.rs
xNul/multithreading-projects-rs
37a2fdaf9534a9b4efd0f849857728adf5d89c47
/* Blake Wyatt COP 6616 Assignment 3: Problem 2 */ use std::{ time::Instant, ptr, thread, sync::Arc, sync::atomic::{Ordering, AtomicBool, AtomicUsize, AtomicPtr}, collections::VecDeque }; use rand::prelude::*; use atomic_markable_ptr::*; struct Node { tag: i32, next: AtomicMarkablePtr<Node> } fn main()...
/* Blake Wyatt COP 6616 Assignment 3: Problem 2 */ use std::{ time::Instant, ptr, thread, sync::Arc, sync::atomic::{Ordering, AtomicBool, AtomicUsize, AtomicPtr}, collections::VecDeque }; use rand::prelude::*; use atomic_markable_ptr::*; struct Node { tag: i32, next: AtomicMarkablePtr<Node> } fn main()...
return false; } else { let new_node = Arc::into_raw(Arc::new(Node { tag, next: AtomicMarkablePtr::new(curr, false) })) as *mut _; if unsafe { &*pred }.next.compare_and_swap(curr, false, new_node, false, Ordering::SeqCst) == (curr, false) { return true; } } } } fn remove(head: ...
= marked_ptr.1; while marked { let temp = unsafe { &*curr }.tag; if unsafe { &*pred }.next.compare_and_swap(curr, false, succ, false, Ordering::SeqCst) != (curr, false) { continue 'retry; } else { } drop(temp); curr = succ; if curr == ptr::null_mut() { ...
random
[ { "content": "// Given list head and tag, find the pred and curr nodes that have the nearest tag\n\nfn find<'a>(head: &AtomicMarkablePtr<Node>, tag: i32) -> (*mut Node, *mut Node) {\n\n\tlet mut pred: *mut Node; let mut curr: *mut Node; let mut succ: *mut Node;\n\n\tlet mut marked = false; let snip: bool;\n\n\t...
Rust
src/data/mod.rs
merembablas/spearmint
7c4545872a987840fbf97f5466380d4595bb35dd
use dialoguer::{theme::ColorfulTheme, Confirm}; use rusqlite::{params, Connection, Result}; pub mod args; pub mod result; pub mod streams; pub const DB_PATH: &str = "spearmint.db"; struct BotId { id: u64, } pub fn setup(path: &str) -> Result<()> { let conn = Connection::open(path)?; conn.execute( ...
use dialoguer::{theme::ColorfulTheme, Confirm}; use rusqlite::{params, Connection, Result}; pub mod args; pub mod result; pub mod streams; pub const DB_PATH: &str = "spearmint.db"; struct BotId { id: u64, } pub fn setup(path: &str) -> Result<()> { let conn = Connection::open(path)?; conn.execute( ...
pub fn stop(name: &str) { if Confirm::with_theme(&ColorfulTheme::default()) .with_prompt("Do you really want to continue?") .default(true) .interact() .unwrap() { let conn = Connection::open(DB_PATH).unwrap(); conn.execute( "UPDATE bots SET status='P...
pub fn start(name: &str) { if Confirm::with_theme(&ColorfulTheme::default()) .with_prompt("Do you really want to continue?") .default(true) .interact() .unwrap() { let conn = Connection::open(DB_PATH).unwrap(); conn.execute( "UPDATE bots SET status='AC...
function_block-function_prefix_line
[ { "content": "pub fn display_bots(bots: Vec<crate::data::result::Bot>) {\n\n let mut table = Table::new();\n\n table.set_header(vec![\n\n \"Title\", \"Pair\", \"Exchange\", \"Strategy\", \"Cycle\", \"Status\",\n\n ]);\n\n\n\n for bot in bots {\n\n table.add_row(vec![\n\n bot...
Rust
metalos/metalctl/src/http.rs
vmagro/antlir
f42653d9e80e66c375aa828045be84e4ce9e597c
/* * Copyright (c) Facebook, Inc. and its affiliates. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. */ use std::future::Future; use std::io::{copy, Write}; use std::net::SocketAddr; use std::pin::Pin; use std::task::Poll; use anyhow:...
/* * Copyright (c) Facebook, Inc. and its affiliates. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. */ use std::future::Future; use std::io::{copy, Write}; use std::net::SocketAddr; use std::pin::Pin; use std::task::Poll; use anyhow:...
tatic("https://[::1]/")).await; if response.is_err() { assert!(response.unwrap_err().is_connect()); } Ok(()) } }
pub fn new() -> Result<Self> { let async_resolver = std::sync::Arc::new( TokioAsyncResolver::tokio_from_system_conf() .context("failed to create trust-dns resolver")?, ); Ok(Self(async_resolver)) } } impl Service<Name> for Resolver { type Response = std::v...
random
[ { "content": "pub fn get_uri(log: Logger, config: crate::Config, opts: Opts) -> Result<Uri> {\n\n let mut url = Url::parse(&config.event_backend.event_backend_base_uri()?.to_string())?;\n\n url.query_pairs_mut()\n\n .append_pair(\"name\", &opts.event_name)\n\n .append_pair(\"sender\", &opts....
Rust
src/lib/admin.rs
edouardpoitras/osm-pbf2json
94280d729198260e430d3f4486c1a0f3fff8cf4a
use super::geo::BoundaryGeometry; use super::items::AdminBoundary; use osm_boundaries_utils::build_boundary; use osmpbfreader::objects::{OsmId, OsmObj}; use rstar::{RTreeObject, AABB}; use std::collections::BTreeMap; impl RTreeObject for AdminBoundary { type Envelope = AABB<[f64; 2]>; fn envelope(&self) -> Se...
use super::geo::BoundaryGeometry; use super::items::AdminBoundary; use osm_boundaries_utils::build_boundary; use osmpbfreader::objects::{OsmId, OsmObj}; use rstar::{RTreeObject, AABB}; use std::collections::BTreeMap; impl RTreeObject for AdminBoundary { type Envelope = AABB<[f64; 2]>; fn envelope(&self) -> Se...
#[test] fn locate_line_string_contained_in_boundary() { let tags = vec![ ("boundary", "administrative"), ("name", "some_name"), ("admin_level", "11"), ]; let coordinates = build_coordinates(13.); let objects = create_objects(&tags, &coordinat...
fn relation_with_wrong_tags() { let tags = vec![ ("boundary", "wrong"), ("name", "some_name"), ("admin_level", "11"), ]; let coordinates = build_coordinates(13.); let objects = create_objects(&tags, &coordinates); let boundaries = get_boundari...
function_block-full_function
[ { "content": "fn get_coordinates(way: &Way, objs: &BTreeMap<OsmId, OsmObj>) -> Option<Vec<(f64, f64)>> {\n\n let coordinates = way\n\n .nodes\n\n .iter()\n\n .filter_map(|&node_id| {\n\n let obj = objs.get(&node_id.into())?;\n\n let node = obj.node()?;\n\n ...
Rust
src/perf/dataset.rs
benjamingroeber/perfdata
2b9eb3876b281e1ff3db185edc0b7e0ad49c4e3d
use crate::monitoring_status::MonitoringStatus; use crate::Perfdata; use std::fmt::{Display, Formatter}; #[derive(Debug, Default, PartialEq)] pub struct PerfdataSet<'a> { data: Vec<Perfdata<'a>>, } impl<'a> PerfdataSet<'a> { pub fn new() -> Self { PerfdataSet::default() } pub fn add...
use crate::monitoring_status::MonitoringStatus; use crate::Perfdata; use std::fmt::{Display, Formatter}; #[derive(Debug, Default, PartialEq)] pub struct PerfdataSet<'a> { data: Vec<Perfdata<'a>>, } impl<'a> PerfdataSet<'a> { pub fn new() -> Self { PerfdataSet::default() } pub fn add...
} impl<'a> From<Vec<Perfdata<'a>>> for PerfdataSet<'a> { fn from(data: Vec<Perfdata<'a>>) -> Self { Self { data } } } impl<'a> FromIterator<Perfdata<'a>> for PerfdataSet<'a> { fn from_iter<T: IntoIterator<Item = Perfdata<'a>>>(iter: T) -> Self { Self { data: iter.into_iter().c...
f) -> MonitoringStatus { if self.has_critical() { MonitoringStatus::Critical } else if self.has_warning() { MonitoringStatus::Warning } else { MonitoringStatus::OK } }
function_block-function_prefixed
[ { "content": "fn fmt_threshold<T: Display>(f: &mut Formatter<'_>, th: Option<T>) -> std::fmt::Result {\n\n match th {\n\n None => write!(f, \";\"),\n\n Some(threshold) => write!(f, \"{};\", threshold),\n\n }\n\n}\n\n\n\nimpl Display for Perfdata<'_> {\n\n fn fmt(&self, f: &mut Formatter<'...
Rust
crates/core/src/year2016/day24.rs
fornwall/advent-of-code-2019-rs
67bb6a48860f20a773f9e913c7e498c921370eeb
use crate::common::permutation::all_permutations; use crate::input::Input; use std::cmp::Reverse; use std::collections::{BinaryHeap, HashMap, HashSet}; struct Grid { cols: usize, data: Vec<bool>, locations: Vec<(usize, usize)>, } impl Grid { fn parse(input: &str) -> Result<Self, String> { let ...
use crate::common::permutation::all_permutations; use crate::input::Input; use std::cmp::Reverse; use std::collections::{BinaryHeap, HashMap, HashSet}; struct Grid { cols: usize, data: Vec<bool>, locations: Vec<(usize, usize)>, } impl Grid { fn parse(input: &str) -> Result<Self, String> { let ...
pub fn tests() { use crate::input::{test_part_one, test_part_two}; test_part_one!("###########\n#0.1.....2#\n#.#######.#\n#4.......3#\n###########" => 14); let real_input = include_str!("day24_input.txt"); test_part_one!(real_input => 412); test_part_two!(real_input => 664); }
function_block-full_function
[ { "content": "pub fn solve(input: &mut Input) -> Result<i32, String> {\n\n let mut horizontal_position = 0_i32;\n\n let mut depth = 0_i32;\n\n let mut aim = 0_i32;\n\n\n\n for (line_idx, line) in input.text.lines().enumerate() {\n\n match line\n\n .split_once(' ')\n\n .m...
Rust
gateway/src/node/client_handling/websocket/connection_handler/authenticated.rs
nymtech/nym
20c96b940fdf15659ab3e5b61765a78e15071332
use crate::node::client_handling::websocket::connection_handler::{ClientDetails, FreshHandler}; use crate::node::client_handling::websocket::message_receiver::MixMessageReceiver; use crate::node::storage::error::StorageError; use futures::StreamExt; use gateway_requests::iv::IVConversionError; use gateway_requests::t...
use crate::node::client_handling::websocket::connection_handler::{ClientDetails, FreshHandler}; use crate::node::client_handling::websocket::message_receiver::MixMessageReceiver; use crate::node::storage::error::StorageError; use futures::StreamExt; use gateway_requests::iv::IVConversionError; use gateway_requests::t...
async fn handle_binary(&self, bin_msg: Vec<u8>) -> Message { match BinaryRequest::try_from_encrypted_tagged_bytes(bin_msg, &self.client.shared_keys) { Err(e) => RequestHandlingError::InvalidBinaryRequest(e).into_error_message(), Ok(request) => matc...
self.consume_bandwidth(consumed_bandwidth).await?; self.forward_packet(mix_packet); Ok(ServerResponse::Send { remaining_bandwidth: available_bandwidth - consumed_bandwidth, }) }
function_block-function_prefix_line
[ { "content": "pub fn random_iv<C, R>(rng: &mut R) -> IV<C>\n\nwhere\n\n C: NewCipher,\n\n R: RngCore + CryptoRng,\n\n{\n\n let mut iv = GenericArray::default();\n\n rng.fill_bytes(&mut iv);\n\n iv\n\n}\n\n\n", "file_path": "common/crypto/src/symmetric/stream_cipher.rs", "rank": 0, "sc...
Rust
rumqttlog/examples/routernxn.rs
anirudh-chhangani/rumq
3c69a6b5d51552ff44a53785308a94bcc5f5e163
/* use argh::FromArgs; use bytes::Bytes; use futures_util::future::join_all; use rumqttlog::router::{Connection, ConnectionAck, Data}; use rumqttlog::{bounded, Config, DataRequest, Router, RouterInMessage, RouterOutMessage, Sender}; use std::thread; use std::time::Instant; use tokio::task; pub mod common; #[derive(Cl...
/* use argh::FromArgs; use bytes::Bytes; use futures_util::future::join_all; use rumqttlog::router::{Connection, ConnectionAck, Data}; use rumqttlog::{bounded, Config, DataRequest, Router, RouterInMessage, RouterOutMessage, Sender}; use std::thread; use std::time::Instant; use tokio::task; pub mod common; #[derive(Cl...
send/recv synchronization stalls let count = i + 1; if count == commandline.message_count / commandline.topic_count { topic_count += 1; topic = "hello/world".to_owned() + &topic_count.to_string(); } } common::report( "write.pb", (commandline.messa...
in data.into_iter().enumerate() { let data = Data { topic: topic.clone(), pkid: 0, payload, }; let message = (id, RouterInMessage::Data(data)); tx.send(message).await.unwrap(); // Listen for acks in batches to fix
random
[ { "content": "pub fn report(name: &str, size: u64, start: Instant, guard: pprof::ProfilerGuard) {\n\n let file_size = size / 1024 / 1024;\n\n let throughput = file_size as u128 * 1000 / start.elapsed().as_millis();\n\n println!(\n\n \"{}. File size = {}, Throughput = {} MB/s\",\n\n name, ...
Rust
src/joints/serialize/serialize_b2_gear_joint.rs
HumMan/box2d-rs
a9731ec7b3d6857c505498e1cccf154b1d688e2b
use serde::de::{self, Deserializer, MapAccess, SeqAccess, Visitor}; use serde::{ser::SerializeStruct, Deserialize, Serialize, Serializer}; use serde::de::DeserializeSeed; use std::fmt; use std::rc::Rc; use std::cell::RefCell; use crate::b2_body::*; use crate::b2_joint::*; use crate::b2_settings::*; use crate::joint...
use serde::de::{self, Deserializer, MapAccess, SeqAccess, Visitor}; use serde::{ser::SerializeStruct, Deserialize, Serialize, Serializer}; use serde::de::DeserializeSeed; use std::fmt; use std::rc::Rc; use std::cell::RefCell; use crate::b2_body::*; use crate::b2_joint::*; use crate::b2_settings::*; use crate::joint...
} deserializer.deserialize_struct( "B2gearJointDef", Field::VARIANTS, B2gearJointDefVisitor(self), ) } }
let mut joint_def = B2gearJointDef::default(); let all_joints = &self.0.m_all_joints; while let Some(key) = map.next_key()? { match key { Field::base => { joint_def.base = map.next_value_seed(B2jointDefVisitorContext...
function_block-function_prefix_line
[ { "content": "// pub trait QueryCallback {\n\n// \tfn query_callback(&mut self, proxy_id: i32) -> bool;\n\n// }\n\npub trait QueryCallback: FnMut(i32) -> bool {}\n\nimpl <F> QueryCallback for F where F: FnMut(i32) -> bool {}\n\n\n", "file_path": "src/b2_dynamic_tree.rs", "rank": 0, "score": 228529.5...
Rust
src/authorized_client.rs
jeroenvervaeke/authorized_client
68bff21c89533c989df50cbbff31093c226278be
use crate::settings::Settings; use anyhow::{bail, Context, Result}; use log::{debug, trace}; use oauth2::basic::BasicClient; use oauth2::http::StatusCode; use oauth2::reqwest::async_http_client; use oauth2::{AuthUrl, ClientId, ClientSecret, Scope, TokenResponse, TokenUrl}; use reqwest::header::HeaderValue; use reqwest:...
use crate::settings::Settings; use anyhow::{bail, Context, Result}; use log::{debug, trace}; use oauth2::basic::BasicClient; use oauth2::http::StatusCode; use oauth2::reqwest::async_http_client; use oauth2::{AuthUrl, ClientId, ClientSecret, Scope, TokenResponse, TokenUrl}; use reqwest::header::HeaderValue; use reqwest:...
async fn ignore_response(_: Response) -> Result<(), Void> { Ok(()) } pub trait RequestBuilder { fn build(&self, client: Client) -> Result<Request>; } impl<F> RequestBuilder for F where F: Fn() -> Result<Request>, { fn build(&self, _client: Client) -> Result<Request> { self() } } #[deriv...
pub fn build_post_request<B>(url: &Url, body: &B) -> Result<Request> where B: Serialize, { let mut request = Request::new(Method::POST, url.clone()); let headers = request.headers_mut(); headers.append("Content-Type", HeaderValue::from_static("application/json")); let request_body = request.body_m...
function_block-full_function
[ { "content": "# Authorized Client\n\n[![Build Status][build-img]][build-url]\n\n[![Documentation][docs-img]][docs-url]\n\n## About\n\nThe goal of this library is to make extremely easy to use rest endpoints which are protected by oauth 2.0 client credentials authorization.\n\nThe client is based on the `Reqwest...
Rust
src/build.rs
ionlang/ilc-rs
1282bcbdb4a28ad1a6e2c08b4b38e6f9ad847d63
use crate::package; use gecko::lint::Lint; use gecko::llvm_lowering::Lower; use gecko::semantic_check::SemanticCheck; pub struct Driver<'a, 'ctx> { pub source_files: Vec<(String, std::path::PathBuf)>, pub file_contents: std::collections::HashMap<std::path::PathBuf, String>, pub llvm_module: &'a inkwell::module::...
use crate::package; use gecko::lint::Lint; use gecko::llvm_lowering::Lower; use gecko::semantic_check::SemanticCheck; pub struct Driver<'a, 'ctx> { pub source_files: Vec<(String, std::path::PathBuf)>, pub file_contents: std::collections::HashMap<std::path::PathBuf, String>, pub llvm_module: &'a inkwell::module::...
fn read_and_lex(&self, source_file: &std::path::PathBuf) -> Vec<gecko::lexer::Token> { let source_code = package::fetch_file_contents(&source_file).unwrap(); let tokens = gecko::lexer::Lexer::from_str(source_code.as_str()).lex_all(); tokens .unwrap() .into_iter() ...
source_files: Vec::new(), file_contents: std::collections::HashMap::new(), llvm_module, cache: gecko::cache::Cache::new(), name_resolver: gecko::name_resolution::NameResolver::new(), lint_context: gecko::lint::LintContext::new(), type_context: gecko::semantic_check::SemanticCheckCont...
function_block-function_prefix_line
[]
Rust
src/developer/ffx/plugins/trace/src/lib.rs
wwjiang007/fuchsia-1
0db66b52b5bcd3e27c8b8c2163925309e8522f94
use { anyhow::{anyhow, Result}, ffx_core::ffx_plugin, ffx_trace_args::{TraceCommand, TraceSubCommand}, fidl_fuchsia_developer_bridge::{self as bridge, TracingProxy}, fidl_fuchsia_tracing_controller::{ControllerProxy, TraceConfig}, std::io::{stdout, Write}, std::path::{Component, PathBuf}, ...
use { anyhow::{anyhow, Result}, ffx_core::ffx_plugin, ffx_trace_args::{TraceCommand, TraceSubCommand}, fidl_fuchsia_developer_bridge::{self as bridge, TracingProxy}, fidl_fuchsia_tracing_controller::{ControllerProxy, TraceConfig}, std::io::{stdout, Write}, std::path::{Component, PathBuf}, ...
#[fuchsia_async::run_singlethreaded(test)] async fn test_get_providers() { let output = run_trace_test(TraceCommand { sub_cmd: TraceSubCommand::ListProviders(ListProviders {}), }) .await; let want = "Trace providers:\n\ - foo\n\ ...
async fn run_trace_test(cmd: TraceCommand) -> String { let mut output = String::new(); let writer = unsafe { BufWriter::new(output.as_mut_vec()) }; let proxy = setup_fake_service(); let controller = setup_fake_controller_proxy(); trace_impl(proxy, controller, cmd, writer).await.u...
function_block-full_function
[]
Rust
src/world.rs
rdelfin/ecs-rs
5817b66cf818dd22e8d373adfed58e03785822d9
#[cfg(feature="serialisation")] use cereal::{CerealData, CerealResult}; #[cfg(feature="serialisation")] use std::io::{Read, Write}; use std::ops::{Deref, DerefMut}; use {EntityData, ModifyData}; use {Entity, IndexedEntity, EntityIter}; use {EntityBuilder, EntityModifier}; use entity::EntityManager; pub struct World...
#[cfg(feature="serialisation")] use cereal::{CerealData, CerealResult}; #[cfg(feature="serialisation")] use std::io::{Read, Write}; use std::ops::{Deref, DerefMut}; use {EntityData, ModifyData}; use {Entity, IndexedEntity, EntityIter}; use {EntityBuilder, EntityModifier}; use entity::EntityManager; pub struct World...
data: try!(CerealData::read(reader)), }; world.refresh(); Ok(world) } pub fn save(&mut self, writer: &mut Write) -> CerealResult<()> { self.flush_queue(); self.data.write(writer) } } impl<S: SystemManager> World<S> { pub fn new() -> World<S> where S::Services:...
ager> DataHelper<C, M> { pub fn with_entity_data<F, R>(&mut self, entity: &Entity, call: F) -> Option<R> where F: FnOnce(EntityData<C>, &mut C) -> R { if self.entities.is_valid(entity) { Some(call(EntityData(&self.entities.indexed(&entity).__clone()), self)) } else { ...
random
[ { "content": "pub trait Component: 'static {}\n\n\n\nimpl<T:'static> Component for T {}\n\n\n\npub struct ComponentList<C: ComponentManager, T: Component>(InnerComponentList<T>, PhantomData<C>);\n\n\n", "file_path": "src/component.rs", "rank": 1, "score": 162908.26874746248 }, { "content": "...
Rust
src/lib.rs
aleozlx/impersonate
2adc6b2cbe5ed6127f9b5f251ac0df492b17ce9b
extern crate regex; extern crate nix; use std::fs::OpenOptions; use std::io::prelude::*; use std::os::unix::fs::PermissionsExt; use std::path::Path; use regex::Regex; extern "C" { fn _su(user: *mut std::os::raw::c_char) -> i32; } const ROOT_UID: nix::libc::uid_t = 0; pub struct User { user_name: String, ...
extern crate regex; extern crate nix; use std::fs::OpenOptions; use std::io::prelude::*; use std::os::unix::fs::PermissionsExt; use std::path::Path; use regex::Regex; extern "C" { fn _su(user: *mut std::os::raw::c_char) -> i32; } const ROOT_UID: nix::libc::uid_t = 0; pub struct User { user_name: String, ...
} else { None } } pub fn su(&self) -> Result<(), Error> { if self.uid.as_raw() != ROOT_UID { let _ = self.gen_etc_passwd(); let _ = self.gen_etc_group(); let _ = self.gen_etc_sudoer(); let _ = self.gen_home_dir(); let user_nam...
Some(User { user_name: caps.get(2).unwrap().as_str().to_owned(), group_name: caps.get(4).unwrap().as_str().to_owned(), uid: nix::unistd::Uid::from_raw(caps.get(1).unwrap().as_str().parse().expect("Failed to parse uid")), gid: nix::unistd::Gid::from_raw(cap...
call_expression
[ { "content": "fn main() {\n\n cc::Build::new().file(\"src/su-exec.c\").compile(\"suexec\");\n\n}", "file_path": "src/build.rs", "rank": 0, "score": 15495.541282198603 }, { "content": "extern crate cc;\n", "file_path": "src/build.rs", "rank": 6, "score": 2.9526367155762765 } ...
Rust
nobs-imgui/src/style/simple/pipeline/mod.rs
dopitz/vulkanism
faf586762cb7d84aeba7cc3fe372ee84fc07ceb2
mod color { vk::pipes::pipeline! { stage = { ty = "vert", glsl = "src/style/simple/pipeline/color.vert", } stage = { ty = "frag", glsl = "src/style/simple/pipeline/color.frag", } dset_name[0] = "DsViewport", dset_name[1] = "DsStyle", dset_name[2] = "Ds", } } mod...
mod color { vk::pipes::pipeline! { stage = { ty = "vert", glsl = "src/style/simple/pipeline/color.vert", } stage = { ty = "frag", glsl = "src/style/simple/pipeline/color.frag", } dset_name[0] = "DsViewport", dset_name[1] = "DsStyle", dset_name[2] = "Ds", } } mod...
pub fn new_style(&self, ub: vk::Buffer) -> vk::DescriptorSet { let ds = self.pool_lut.new_dset(&self.color.dsets[1]).unwrap(); color::DsStyle::write(self.color.device, ds) .ub_style(vk::DescriptorBufferInfo::build().buffer(ub).into()) .update(); ds } pub fn new_instance(&mut self, ds_vi...
pub fn new(device: vk::Device, pass_draw: vk::RenderPass, subpass_draw: u32, pass_select: vk::RenderPass, subpass_select: u32) -> Self { let color = color::new(device, pass_draw, subpass_draw) .input_assembly(vk::PipelineInputAssemblyStateCreateInfo::build().topology(vk::PRIMITIVE_TOPOLOGY_TRIANGLE_LIST)) ...
function_block-full_function
[ { "content": "pub fn create_descriptor_layout(device: vk::Device, bindings: &[Binding]) -> vk::DescriptorSetLayout {\n\n let layout_bindings: Vec<vk::DescriptorSetLayoutBinding> = bindings\n\n .iter()\n\n .map(|b| vk::DescriptorSetLayoutBinding {\n\n binding: b.binding,\n\n descriptorType: b.de...
Rust
rewind-snapshot/src/lib.rs
cokesme/rewind
ff93325626a15d83bd1a3e5de22daf5e07a26663
#![warn(missing_docs)] use std::{cell::RefCell, io::{Read, Write, BufWriter}}; use serde::{Serialize, Deserialize}; use dump::ParserError; use rewind_core::{error::GenericError, snapshot::{Snapshot, SnapshotError}}; use rewind_core::mem::{self, X64VirtualAddressSpace, VirtMemError}; mod dump; pub struct DumpSnap...
#![warn(missing_docs)] use std::{cell::RefCell, io::{Read, Write, BufWriter}}; use serde::{Serialize, Deserialize}; use dump::ParserError; use rewind_core::{error::GenericError, snapshot::{Snapshot, SnapshotError}}; use rewind_core::mem::{self, X64VirtualAddressSpace, VirtMemError}; mod dump; pub struct DumpSnap...
fn write_gpa(&mut self, _gpa: u64, _data: &[u8]) -> Result<(), VirtMemError> { Err(VirtMemError::GenericError("read-only snapshot".to_string())) } } impl From<ParserError> for SnapshotError { fn from(e: ParserError) -> Self { SnapshotError::GenericError(e.to_string()) } }
Self::DumpSnapshot(snapshot) => Snapshot::read_gpa(snapshot, gpa, buffer).map_err(|e| VirtMemError::GenericError(e.to_string())), Self::FileSnapshot(snapshot) => Snapshot::read_gpa(snapshot, gpa, buffer).map_err(|e| VirtMemError::GenericError(e.to_string())), } }
function_block-function_prefix_line
[ { "content": "#[allow(dead_code)]\n\nfn clear_dr7(mut dr7: u64, slot: u8) -> u64 {\n\n dr7 &= !(1 << (slot * 2));\n\n // remove the condition (RW0 - RW3) field from the appropriate slot (bits 16/17, 20/21, 24,25, 28/29)\n\n dr7 &= !(3 << ((slot * 4) + 16));\n\n\n\n // remove the length (LEN0-LEN3) f...
Rust
src/lib.rs
amiraeva/able-spi-friend
c7fd3f6e3c6b6923140147a0a665ee9ece2e060c
#![no_std] use feather_m0::{ clock::GenericClockController, gpio::{Floating, Input, OpenDrain, Output, Pa12, Pa21, Pa6 as D8, Pb10, Pb11, PfD, Port}, pac::{PM, SERCOM4}, prelude::*, sercom::{SPIMaster4, Sercom4Pad0, Sercom4Pad2, Sercom4Pad3}, }; use arraydeque::{ArrayDeque, Wrapping}; use core::{c...
#![no_std] use feather_m0::{ clock::GenericClockController, gpio::{Floating, Input, OpenDrain, Output, Pa12, Pa21, Pa6 as D8, Pb10, Pb11, PfD, Port}, pac::{PM, SERCOM4}, prelude::*, sercom::{SPIMaster4, Sercom4Pad0, Sercom4Pad2, Sercom4Pad3}, }; use arraydeque::{ArrayDeque, Wrapping}; use core::{c...
fn deque_remaining(&self) -> usize { self.deque.capacity() - self.deque.len() } fn cycle_cs(cs: &mut ChipSelect, delay: &mut D) { cs.disable(); delay.delay_us(T::from(Self::SPI_FRIEND_DELAY)); cs.enable(); } fn handle_initial_msgs(msg: u8, cs: &mut ChipSelect, del...
fn is_ready(&mut self) -> Option<bool> { let byte = spi_transfer(&mut self.spi, Self::SPI_COMMAND_BYTE)?; if byte != Self::SPI_IGNORED_BYTE { Some(true) } else { Self::cycle_cs(&mut self.cs, &mut self.delay); Some(false) } }
function_block-full_function
[ { "content": "# able-spi-friend\n\nRust library for the Adafruit BLE SPI Friend [WIP]\n\n\n\nVery rough around the edges (i.e. everything is hardcoded cause I'm an amateur). So far only works with the Adafruit Feather M0 BLE board, only using the Nordic UART service, with some odd timing bugs that _occasionally...
Rust
generator/src/generator.rs
jinnzest/rust-llvm-sys-playground
05581cce7ac6713ed5bea3445e37cd0e491bc2ac
extern crate libc; extern crate llvm_sys; use self::llvm_sys::prelude::*; use bignumloader::*; use llvm::*; pub fn llvm_exec() -> bool { load_bignum_symbols(); let mut runner = LLVMRunner::new(); let main = mk_main(&mut runner); runner.llvm.dump("output"); runner.llvm.exec_func(main) } pub fn llv...
extern crate libc; extern crate llvm_sys; use self::llvm_sys::prelude::*; use bignumloader::*; use llvm::*; pub fn llvm_exec() -> bool { load_bignum_symbols(); let mut runner = LLVMRunner::new(); let main = mk_main(&mut runner); runner.llvm.dump("output"); runner.llvm.exec_func(main) } pub fn llv...
alueRef) { self.llvm .call_func("free", self.funcs.free, &mut vec![addr]); } fn call_test(&mut self) { let test_struct = self.llvm.struct_test(); let func_type = self.llvm.mk_func_type(test_struct, &mut vec![]); let func = self.llvm.mk_func("create_test", func_type);...
{ let format_str = self.llvm.mk_global_string("format", fmt); let format_str_loaded = self.llvm.get_struct_field_ptr(format_str, 0); let loaded_value_buf = self.llvm.get_struct_field_ptr(value, 0); let mut printf_args = vec![format_str_loaded, loaded_value_buf]; self.llvm ...
random
[ { "content": "pub fn export_mp_radix_size(llvm: &mut LLVM, llvm_structs: &LLVMStructs) -> LLVMValueRef {\n\n let mut args = [\n\n llvm.ptr_t(llvm_structs.mp_struct),\n\n llvm.i32_t(),\n\n llvm.ptr_t(llvm.i32_t()),\n\n ];\n\n let ret = llvm.i32_t();\n\n let mp_read_radix = llvm.m...
Rust
tune-cli/src/lib.rs
Woyten/tune
14f38a7e32955a964c81c6cab7ac801f9b7f321d
mod dto; mod est; mod live; mod midi; mod mos; mod mts; mod scala; mod scale; use std::{ fmt::{self, Debug, Display}, fs::File, io::{self, Write}, path::PathBuf, }; use est::EstOptions; use io::Read; use live::LiveOptions; use mos::MosCommand; use mts::MtsOptions; use scala::{KbmCommand, SclOptions}; ...
mod dto; mod est; mod live; mod midi; mod mos; mod mts; mod scala; mod scale; use std::{ fmt::{self, Debug, Display}, fs::File, io::{self, Write}, path::PathBuf, }; use est::EstOptions; use io::Read; use live::LiveOptions; use mos::MosCommand; use mts::MtsOptions; use scala::{KbmCommand, SclOptions}; ...
pub fn run_in_wasm_env( args: impl IntoIterator<Item = String>, input: impl Read, mut output: impl Write, error: impl Write, ) -> CliResult<()> { let command = match MainCommand::from_iter_safe(args) { Err(err) => { return if err.use_stderr() { Err(CliError::Com...
pub fn run_in_shell_env(args: impl IntoIterator<Item = String>) -> CliResult<()> { let options = match MainOptions::from_iter_safe(args) { Err(err) => { return if err.use_stderr() { Err(CliError::CommandError(err.message)) } else { println!("{}", err);...
function_block-full_function
[ { "content": "pub fn print_midi_devices(mut dst: impl io::Write, client_name: &str) -> MidiResult<()> {\n\n let midi_input = MidiInput::new(client_name)?;\n\n writeln!(dst, \"Readable MIDI devices:\")?;\n\n for port in midi_input.ports() {\n\n writeln!(dst, \"- {}\", midi_input.port_name(&port)?...
Rust
prm/src/bunch.rs
Fenex/vangers-tool
16702a74e0771effb74d6f0a0650ee8bad137113
use ::enum_primitive_derive::Primitive; use num_traits::FromPrimitive; use std::{path::Path, str::FromStr}; use crate::{PrmFile, PrmParseError}; #[derive(Debug, Clone, Copy, PartialEq, Eq, Primitive)] pub enum Bios { Eleepods = 0, Beeboorats = 1, Zeexes = 2, } impl Bios { pub fn into_iter() -> i...
use ::enum_primitive_derive::Primitive; use num_traits::FromPrimitive; use std::{path::Path, str::FromStr}; use crate::{PrmFile, PrmParseError}; #[derive(Debug, Clone, Copy, PartialEq, Eq, Primitive)] pub enum Bios { Eleepods = 0, Beeboorats = 1, Zeexes = 2, } impl Bios { pub fn into_iter() -> i...
}
fn file_parse<P: AsRef<Path>>(path_to_folder: P) -> Result<Self, PrmParseError> { let rows = Self::file_open(path_to_folder).map_err::<PrmParseError, _>(|e| e.into())?; let mut iter = rows.iter(); let count = Bios::total(); let mut bunches = Vec::with_capacity(count); for _ in 0...
function_block-full_function
[ { "content": "#[inline]\n\nfn get_atom<'a, 'b, I, T: FromStr>(iter: &'a mut I) -> Option<T>\n\nwhere\n\n I: Iterator<Item = &'b str>,\n\n{\n\n iter.next()?.parse::<T>().ok()\n\n}\n", "file_path": "prm/src/mechos.rs", "rank": 2, "score": 93922.8170100893 }, { "content": "pub trait PrmFi...
Rust
crate/pahkat-repomgr/src/nuke/package/releases.rs
bbqsrc/pahkat-client-sdk-swift
c091bbb6d1d6a9f26c2baac889f356cfe210c987
use std::borrow::Cow; use std::fs; use std::io; use std::path::{Path, PathBuf}; use typed_builder::TypedBuilder; #[non_exhaustive] #[derive(Debug, Clone, TypedBuilder)] pub struct Request<'a> { pub repo_path: Cow<'a, Path>, } #[non_exhaustive] #[derive(Debug, Clone, Default, TypedBuilder)] pub struct PartialRequ...
use std::borrow::Cow; use std::fs; use std::io; use std::path::{Path, PathBuf}; use typed_builder::TypedBuilder; #[non_exhaustive] #[derive(Debug, Clone, TypedBuilder)] pub struct Request<'a> { pub repo_path: Cow<'a, Path>, } #[non_exhaustive] #[derive(Debug, Clone, Default, TypedBuilder)] pub struct PartialRequ...
ath.join("index.toml"); let pkg_file = std::fs::read_to_string(&pkg_path) .map_err(|e| Error::ReadFailed(pkg_path.clone(), e))?; let mut descriptor: pahkat_types::package::Descriptor = toml::from_str(&pkg_file).map_err(|e| Error::ReadToml(pkg_path.clone(), e))?; descrip...
nwrap(); } if let Some(_) = open_repo(path) { return Ok(path); } while let Some(parent) = path.parent() { path = parent; if let Some(_) = open_repo(path) { return Ok(path); } } Err(FindRepoError::NotFound) } impl<'a> crate::Request for Request<'a> ...
random
[ { "content": "fn find_repo(path: &Path) -> Result<&Path, FindRepoError> {\n\n let mut path = path;\n\n\n\n if path.ends_with(\"index.toml\") {\n\n path = path.parent().unwrap();\n\n }\n\n\n\n if let Some(_) = open_repo(path) {\n\n return Ok(path);\n\n }\n\n\n\n while let Some(par...
Rust
device-scanner/device-scanner-daemon/src/daemon.rs
intel-hpdd/-intel-manager-for-lustre
f8a6f61205b42cc62f4bbcb8d81214ad4f215cd6
use crate::{ error, reducers::{mount::update_mount, udev::update_udev, zed::update_zed_events}, state, }; use device_types::{state::State, Command}; use futures::{ channel::mpsc::UnboundedReceiver, channel::mpsc::UnboundedSender, future::join_all, StreamExt, TryStreamExt, }; use tokio::{ io::A...
use crate::{ error, reducers::{mount::update_mount, udev::update_udev, zed::update_zed_events}, state, }; use device_types::{state::State, Command}; use futures::{ channel::mpsc::UnboundedReceiver, channel::mpsc::UnboundedSender, future::join_all, StreamExt, TryStreamExt, }; use tokio::{ io::A...
t listener = listener .incoming() .inspect_ok(|_| tracing::debug!("Client connected")); let mut state = State::new(); while let Some(sock) = listener.try_next().await? { let (x, sock) = FramedRead::new(sock, LinesCodec::new()).into_future().await; let mut sock = sock.into_inne...
function_block-function_prefixed
[ { "content": "/// Get a client that is able to make authenticated requests\n\n/// against the API\n\npub fn get_client(insecure: bool) -> Result<Client, WbemClientError> {\n\n let headers = header::HeaderMap::from_iter(vec![(\n\n header::CONTENT_TYPE,\n\n header::HeaderValue::from_static(\"appl...
Rust
src/computenetwork/mod.rs
rafawo/hcsrs
c8d70a431eed24ccc53b4119975cc11fc8972d6a
#[cfg(not(feature = "bindings"))] pub(crate) mod bindings; #[cfg(feature = "bindings")] pub mod bindings; pub mod defs; use crate::compute::errorcodes::{hresult_to_result_code, ResultCode}; use crate::computenetwork::bindings::*; use crate::computenetwork::defs::*; use widestring::WideCString; use winutils_rs::util...
#[cfg(not(feature = "bindings"))] pub(crate) mod bindings; #[cfg(feature = "bindings")] pub mod bindings; pub mod defs; use crate::compute::errorcodes::{hresult_to_result_code, ResultCode}; use crate::computenetwork::bindings::*; use crate::computenetwork::defs::*; use widestring::WideCString; use winutils_rs::util...
pub fn delete_network(id: &Guid) -> HcnResult<()> { unsafe { let mut error_record = CoTaskMemWString::new(); match HcnDeleteNetwork(id, error_record.ptr_mut()) { 0 => Ok(()), hresult => Err(ErrorResult::new(error_record.to_string(), hresult)), } } } pub fn clo...
t(), error_record.ptr_mut(), ) { 0 => Ok(properties.to_string()), hresult => Err(ErrorResult::new(error_record.to_string(), hresult)), } } }
function_block-function_prefixed
[ { "content": "/// Returns Host Compute Service properties as a JSON document.\n\n/// Determine what to query through a JSON document.\n\npub fn get_service_properties(property_query: &str) -> HcsResult<String> {\n\n unsafe {\n\n let mut result = LocalWString::new();\n\n\n\n match HcsGetServiceP...
Rust
src/modules/objects/mod.rs
lilith645/the_tower
a6e535d7d848fee234c1216c5b474ce99ee4a6b6
use maat_graphics::math; use maat_graphics::math::Vector3Math; use maat_graphics::ModelData; use maat_graphics::cgmath::{Vector2, Vector3, Vector4, Zero, Euler, Quaternion}; use maat_input_handler::MappedKeys; use maat_graphics::DrawCall; pub enum ObjectPhysicsType { Dynamic, Static, Decorative, } #[derive...
use maat_graphics::math; use maat_graphics::math::Vector3Math; use maat_graphics::ModelData; use maat_graphics::cgmath::{Vector2, Vector3, Vector4, Zero, Euler, Quaternion}; use maat_input_handler::MappedKeys; use maat_graphics::DrawCall; pub enum ObjectPhysicsType { Dynamic, Static, Decorative, } #[derive...
pub fn dynamic_physics(mut self) -> ObjectData { self.physics_type = ObjectPhysicsType::Dynamic; self } pub fn static_physics(mut self) -> ObjectData { self.physics_type = ObjectPhysicsType::Static; self } } pub trait GenericObject { fn data(&self) -> &ObjectData; fn mut_data(&mut se...
n, scale: Vector3::new(1.0, 1.0, 1.0), rotation: Vector3::new(0.0, 0.0, 0.0), model, vel: Vector3::new(0.0, 0.0, 0.0), rel_vel: Vector3::new(0.0, 0.0, 0.0), grounded: false, physics_type: ObjectPhysicsType::Decorative, collision_data: Vec::new(), ...
function_block-function_prefixed
[ { "content": "pub fn collide_static_with_dynamic(static_objects: &mut Vec<Box<dyn GenericObject>>,\n\n dyn_objects: &mut Vec<Box<dyn GenericObject>>) {\n\n for i in 0..dyn_objects.len() {\n\n for j in 0..static_objects.len() {\n\n let player_collision_data = dyn_object...
Rust
src/lib.rs
kolbma/rocket-governor
db2787fc08564dc822fe21a56fef85bdbb2eb3ea
#![deny(clippy::all)] #![deny(keyword_idents)] #![deny(missing_docs)] #![deny(non_ascii_idents)] #![deny(unreachable_pub)] #![deny(unsafe_code)] #![deny(unused_crate_dependencies)] #![deny(unused_qualifications)] #![deny(warnings)] use governor::clock::{Clock, DefaultClock}; pub use governor::Quota; use lazy_static...
#![deny(clippy::all)] #![deny(keyword_idents)] #![deny(missing_docs)] #![deny(non_ascii_idents)] #![deny(unreachable_pub)] #![deny(unsafe_code)] #![deny(unused_crate_dependencies)] #![deny(unused_qualifications)] #![deny(warnings)] use governor::clock::{Clock, DefaultClock}; pub use governor::Quota; use lazy_static...
} #[doc(hidden)] impl<'r, T> Default for RocketGovernor<'r, T> where T: RocketGovernable<'r>, { fn default() -> Self { Self { _phantom: PhantomData, } } } #[doc(hidden)] #[async_trait] impl<'r, T> FromRequest<'r> for RocketGovernor<'r, T> where T: RocketGovernable<'r>, { ...
pub fn handle_from_request(request: &'r Request) -> Outcome<Self, LimitError> { let res = request.local_cache(|| { if let Some(route) = request.route() { if let Some(route_name) = &route.name { let limiter = Registry::get_or_insert::<T>( ro...
function_block-full_function
[ { "content": "#[async_trait]\n\npub trait RocketGovernable<'r> {\n\n /// Returns the [Quota] of the [RocketGovernable].\n\n ///\n\n /// This is called only once per method/route_name combination.\n\n /// So it makes only sense to return always the same [Quota] for\n\n /// equal parameter combinat...
Rust
rustrial-k8s-object-syncer/src/object_sync_controller.rs
rustrial/k8s-object-syncer
5c9d45fd095aedf3bb86a12a9b260fb364225b7c
use crate::{ errors::{ControllerError, ExtKubeApiError}, object_sync_modifications::ObjectSyncModifications, resource_controller::{ObjectSyncHandle, ResourceController}, utils::{delete_destinations, metric_name, remove_finalizer}, Configuration, FINALIZER, }; use futures::StreamExt; use k8s_openapi...
use crate::{ errors::{ControllerError, ExtKubeApiError}, object_sync_modifications::ObjectSyncModifications, resource_controller::{ObjectSyncHandle, ResourceController}, utils::{delete_destinations, metric_name, remove_finalizer}, Configuration, FINALIZER, }; use futures::StreamExt; use k8s_openapi...
.upgrade()).flatten(); let controller = if let Some(controller) = controller { controller } else { let controller: ResourceController = ResourceController::new( self.configuration.clone(), self.namespace_cache.clone(), ...
::Result<()> { let finalizers: &mut Vec<String> = &mut event.finalizers_mut(); let original_size = finalizers.len(); finalizers.retain(|f| f.as_str() != FINALIZER); if finalizers.len() != original_size { event.patch_spec(self.configuration.client.clone()).await?; } ...
random
[ { "content": "/// [`ResourceController`] tracks objects of a specific GVK\n\nstruct ResourceControllerImpl {\n\n configuration: Configuration,\n\n api_resource: ApiResource,\n\n gvk: GroupVersionKind,\n\n namespace_cache: Store<Namespace>,\n\n /// src-ref -> ObjectSync-ref\n\n sources: Arc<RwL...
Rust
simulator/src/cached_policy.rs
Sonicskater/wasm-simulator
92c532756b81963e50d29d653c9f509ef21c8022
use wasmer::{Function, Instance, Memory, Module, Val, imports}; use ouroboros::self_referencing; use simulator_shared_types::FileRecord; use crate::policy::PolicyModule; #[self_referencing] pub struct WasmCachedBincodePolicyModule{ module : Instance, #[borrows(module)] mem: &'this Memory, #[borrows(mod...
use wasmer::{Function, Instance, Memory, Module, Val, imports}; use ouroboros::self_referencing; use simulator_shared_types::FileRecord; use crate::policy::PolicyModule; #[self_referencing] pub struct WasmCachedBincodePolicyModule{ module : Instance, #[borrows(module)] mem: &'this Memory, #[borrows(mod...
fn stats(&self) -> (i32, i32) { let result = self.borrow_stats().call(&[]).unwrap(); let packed = result[0].i64().unwrap(); packed_i32::split_i64_to_i32(packed) } } impl WasmCachedBytemuckPolicyModule { pub fn from_module(module : Module) -> Self { let import_objects = imp...
ffer_size); let mem = self.borrow_mem(); runtime::write_bincode_to_wasm_memory(request, mem, ptr as usize, len as usize); self.borrow_send().call(&[Val::I32(ptr), Val::I32(len)]).unwrap(); }
function_block-function_prefixed
[ { "content": "#[no_mangle]\n\npub fn send(ptr: i32, buffer_size: i32){\n\n\n\n // Dont need the ptr/buffersize, data can only be in one spot\n\n let slice = unsafe {\n\n &BUFFER\n\n };\n\n\n\n let x = bytemuck::from_bytes::<FileRecord<i32>>(slice).clone();\n\n\n\n POLICY.lock().unwrap().as...
Rust
src/main.rs
rinsuki/badapple-efi
db7c806fbf326f1f801e20a55f4b8face17411ff
#![no_std] #![no_main] #![feature(abi_efiapi)] #[macro_use] extern crate alloc; #[macro_use] extern crate log; use byteorder::ByteOrder; use uefi::prelude::*; use uefi::proto::console::gop::{BltOp, BltPixel, BltRegion, GraphicsOutput}; use uefi::ResultExt; use uefi::proto::media::file::{Directory, File, FileAttribute...
#![no_std] #![no_main] #![feature(abi_efiapi)] #[macro_use] extern crate alloc; #[macro_use] extern crate log; use byteorder::ByteOrder; use uefi::prelude::*; use uefi::proto::console::gop::{BltOp, BltPixel, BltRegion, GraphicsOutput}; use uefi::ResultExt; use uefi::proto::media::file::{Directory, File, FileAttribute...
fn init_gop(boot_services: &BootServices) -> &mut GraphicsOutput { if let Ok(gopp) = boot_services.locate_protocol::<GraphicsOutput>() { let gop = unsafe { gopp.unwrap().get().as_mut() }.unwrap(); info!("Show Available Resolutions:"); let mut selected_mode = None; let mut score = i...
fn load_seek_info(file: &mut RegularFile) -> alloc::vec::Vec<u32> { let frames = (file.get_boxed_info::<FileInfo>().unwrap().unwrap().file_size() / 4) as usize; let mut vec = vec![0; frames + 1]; let mut buffer = vec![0; 4]; for i in 1..(frames+1) { file.read(&mut buffer).unwrap().unwrap(); ...
function_block-full_function
[]
Rust
dove/src/cli.rs
pontem-network/move-tools
e61a934ca0c294d1be40e3619f63e89d8c32eac7
use std::env; use std::fs; use std::ffi::OsString; use std::path::{PathBuf, Path}; use anyhow::{Result, Error}; use structopt::StructOpt; use semver::{Version, VersionReq}; use move_cli::{Command as DiemCommand, experimental, Move, package, run_cli, sandbox}; use move_cli::DEFAULT_SOURCE_DIR; use move_core_types::acc...
use std::env; use std::fs; use std::ffi::OsString; use std::path::{PathBuf, Path}; use anyhow::{Result, Error}; use structopt::StructOpt; use semver::{Version, VersionReq}; use move_cli::{Command as DiemCommand, experimental, Move, package, run_cli, sandbox}; use move_cli::DEFAULT_SOURCE_DIR; use move_core_types::acc...
fn get_minimal_dove_version(project_path: &Path) -> Option<String> { let move_toml_path = project_path.join("Move.toml"); if !move_toml_path.exists() { return None; } let move_toml_content = std::fs::read_to_string(&move_toml_path).ok()?; let move_toml = toml::from_str::<toml::Value>(&move...
fn create_long_version() -> &'static str { let dove: String = [DOVE_VERSION, DOVE_HASH] .iter() .filter(|str| !str.is_empty()) .map(|str| str.to_string()) .collect::<Vec<String>>() .join("-"); let diem: String = [DIEM_VERSION, DIEM_HASH] .iter() .filter(|s...
function_block-full_function
[ { "content": "/// Build project.\n\npub fn run_internal_build(ctx: &mut Context) -> Result<(), Error> {\n\n let mut cmd = Build::default();\n\n cmd.apply(ctx)\n\n}\n\n\n", "file_path": "dove/src/cmd/build.rs", "rank": 0, "score": 542287.3014991349 }, { "content": "/// Clean project.\n\...
Rust
graphannis/src/annis/db/aql/operators/identical_cov.rs
korpling/graphANNIS
8f9f1c9a594f1e3bac3ed65c06ffe05b7e38ae96
use crate::annis::db::token_helper; use crate::annis::db::token_helper::TokenHelper; use crate::annis::operator::{BinaryOperator, BinaryOperatorIndex, EstimationType}; use crate::{ annis::operator::{BinaryOperatorBase, BinaryOperatorSpec}, graph::{GraphStorage, Match}, model::AnnotationComponentType, An...
use crate::annis::db::token_helper; use crate::annis::db::token_helper::TokenHelper; use crate::annis::operator::{BinaryOperator, BinaryOperatorIndex, EstimationType}; use crate::{ annis::operator::{BinaryOperatorBase, BinaryOperatorSpec}, graph::{GraphStorage, Match}, model::AnnotationComponentType, An...
fn estimation_type(&self) -> EstimationType { if let Some(order_stats) = self.gs_order.get_statistics() { let num_of_token = order_stats.nodes as f64; EstimationType::Selectivity(1.0 / num_of_token) } else {...
fn get_inverse_operator<'b>(&self, graph: &'b AnnotationGraph) -> Option<BinaryOperator<'b>> { Some(BinaryOperator::Index(Box::new(IdenticalCoverage { gs_left: self.gs_left.clone(), gs_order: self.gs_order.clone(), tok_helper: TokenHelper::new(graph)?, }))) }
function_block-full_function
[ { "content": "/// Load a c corpus in the legacy relANNIS format from the specified `path`.\n\n///\n\n/// Returns a tuple consisting of the corpus name and the extracted annotation graph.\n\npub fn load<F>(\n\n path: &Path,\n\n disk_based: bool,\n\n progress_callback: F,\n\n) -> Result<(String, Annotati...
Rust
src/data_types/mod.rs
White-Green/selecting_flow
cc30a092c2f175087d08008f4ec420d68142ffbe
use std::borrow::Cow; use std::cmp::Ordering; use std::collections::BTreeMap; use std::rc::Rc; use num_traits::NumAssign; use rayon::prelude::{IndexedParallelIterator, ParallelIterator, ParallelSlice, ParallelSliceMut}; use crate::compute_graph::constant::Constant; use crate::compute_graph::{IntoComputeGraphNode, Sha...
use std::borrow::Cow; use std::cmp::Ordering; use std::collections::BTreeMap; use std::rc::Rc; use num_traits::NumAssign; use rayon::prelude::{IndexedParallelIterator, ParallelIterator, ParallelSlice, ParallelSliceMut}; use crate::compute_graph::constant::Constant; use crate::compute_graph::{IntoComputeGraphNode, Sha...
} pub fn as_ref(&self) -> TensorEither<T, N> { match self { TensorEither::Dense(tensor) => tensor.as_ref().into(), TensorEither::Sparse(tensor) => tensor.as_ref().into(), } } } impl<'a, T: Default + Clone, const N: usize> TensorEither<'a, T, N> { pub fn get(&sel...
match self { TensorEither::Dense(tensor) => tensor.into_owned().into(), TensorEither::Sparse(tensor) => tensor.into_owned().into(), }
if_condition
[ { "content": "pub trait ExactDimensionComputeGraphNode<const N: usize>: ComputeGraphNode {\n\n type Item: NumAssign + Default + Clone;\n\n fn output_shape(&self) -> [usize; N];\n\n fn get_output(&mut self) -> ValueWithSequence<TensorEither<Self::Item, N>>;\n\n fn add_gradient(&mut self, tensor: Tens...
Rust
src/creeps.rs
Vrixyz/rusttd
50fd90290eb288b07b69dde9bd02b21634438c05
use bevy::prelude::{self, *}; use crate::{ grid::Grid, level_1::{map, LevelState}, path::resolve, math_utils, towers::{Damage, ProjectileHit}, }; pub struct Plugin; impl prelude::Plugin for Plugin { fn build(&self, app: &mut prelude::AppBuilder) { app.add_event::<Death>() ...
use bevy::prelude::{self, *}; use crate::{ grid::Grid, level_1::{map, LevelState}, path::resolve, math_utils, towers::{Damage, ProjectileHit}, }; pub struct Plugin; impl prelude::Plugin for Plugin {
} struct Spawner { amount: u32, timer: Timer, } fn start_spawn(mut commands: Commands) { info!("Creating spawner"); commands.spawn_bundle(( Spawner { amount: 20, timer: Timer::from_seconds(1.0, true), }, Transform::from_translation(Vec3::new(-20.0, 0.0,...
fn build(&self, app: &mut prelude::AppBuilder) { app.add_event::<Death>() .add_system_set( SystemSet::on_enter(LevelState::Spawning).with_system(start_spawn.system()), ) .add_system_set( SystemSet::on_update(LevelState::Spawning) ...
function_block-full_function
[ { "content": "struct MainCamera;\n\n\n", "file_path": "src/camera.rs", "rank": 2, "score": 41171.893254921495 }, { "content": "struct RangeVisualization(Entity);\n\n\n", "file_path": "src/towers.rs", "rank": 3, "score": 37636.220811639374 }, { "content": "#[allow(clippy::...
Rust
rust/origen/src/utility/ldap.rs
Origen-SDK/o2
5b0f9a6d113ddebc73c7ee224931e8b2d0301794
use crate::Result; use ldap3::{LdapConn, Scope, SearchEntry}; use std::collections::HashMap; pub struct LDAPs { ldaps: HashMap<String, LDAP>, } impl LDAPs { pub fn get_standalone(ldap_name: &str) -> Result<LDAP> { LDAP::from_config(ldap_name) } pub fn get(&self, ldap: &str) -> Option<&LDAP> {...
use crate::Result; use ldap3::{LdapConn, Scope, SearchEntry}; use std::collections::HashMap; pub struct LDAPs { ldaps: HashMap<String, LDAP>, } impl LDAPs { pub fn get_standalone(ldap_name: &str) -> Result<LDAP> { LDAP::from_config(ldap_name) } pub fn get(&self, ldap: &str) -> Option<&LDAP> {...
&str, auth: SupportedAuths) -> Result<Self> { Ok(Self { name: name.to_string(), server: server.to_string(), base: base.to_string(), ldap: LdapConn::new(server)?, auth: auth, bound: false, }) } pub fn from_config(name: &str...
Err(e) => { display_redln!("Unable to add LDAP {}. Reason: {}", name, e.msg); } } } Self { ldaps: ldaps } } pub fn try_password(ldap_name: &str, username: &str, password: &str) -> Result<bool> { let mut ldap = Self::get_st...
random
[ { "content": "/// Returns an array of possible target/environment files that match the given name/snippet\n\n// TODO: look into updating this to use the PathBuf PartialEq Trait to compare instead string compare which is prone to bugs due to OS differences\n\npub fn matches(name: &str, dir: &str) -> Vec<PathBuf>...
Rust
ps-gui/src/app_state/mod.rs
Byron/postsack
f22fa3d3420cb57c45ba64c7bc6f7a617ba2600d
mod error; mod import; mod main; mod startup; use std::path::PathBuf; pub use super::textures::Textures; use eframe::egui::{self}; pub use error::ErrorUI; pub use import::ImporterUI; pub use main::{MainUI, UIState}; use ps_core::eyre::Report; pub use startup::StartupUI; use ps_core::{Config, DatabaseLike, FormatType...
mod error; mod import; mod main; mod startup; use std::path::PathBuf; pub use super::textures::Textures; use eframe::egui::{self}; pub use error::ErrorUI; pub use import::ImporterUI; pub use main::{MainUI, UIState}; use ps_core::eyre::Report; pub use startup::StartupUI; use ps_core::{Config, DatabaseLike, FormatType...
; let database = match Database::new(&config.database_path) { Ok(config) => config, Err(report) => return StateUI::Error(error::ErrorUI::new(report, None)), }; self.importer_with_config(config, database) } pub fn open_database<Database: DatabaseLike>(&mut self,...
match Config::new(database_path, emails_folder_path, sender_emails, format) { Ok(n) => n, Err(e) => { return StateUI::Error(error::ErrorUI::new(e, None)); } }
if_condition
[]
Rust
src/app/core/http.rs
PeterDing/aget-rs
ebf43a1a2ab9ae88efd66d2f298643c119021372
use std::{path::PathBuf, time::Duration}; use futures::{ channel::mpsc::{channel, Sender}, select, stream::StreamExt, SinkExt, }; use actix_rt::{spawn, time::interval, System}; use crate::{ app::{ receive::http_receiver::HttpReceiver, record::{common::RECORDER_FILE_SUFFIX, range_r...
use std::{path::PathBuf, time::Duration}; use futures::{ channel::mpsc::{channel, Sender}, select, stream::StreamExt, SinkExt, }; use actix_rt::{spawn, time::interval, System}; use crate::{ app::{ receive::http_receiver::HttpReceiver, record::{common::RECORDER_FILE_SUFFIX, range_r...
; let mut task = DirectRequestTask::new( client, self.method.clone(), self.uri.clone(), self.data.clone(), sender.clone(), ); spawn(async move { task.start().await; }); ...
build_http_client( hds.as_ref(), Duration::from_secs(60), dns_timeout, Duration::from_secs(60), Duration::from_secs(0), true, )
call_expression
[ { "content": "pub fn join_uri(base_uri: &Uri, uri: &str) -> Result<Uri> {\n\n let new_uri: Uri = if !uri.to_lowercase().starts_with(\"http\") {\n\n let base_url = Url::parse(&format!(\"{}\", base_uri))?;\n\n base_url.join(uri)?.as_str().parse()?\n\n } else {\n\n uri.parse()?\n\n };...
Rust
src/lexer.rs
chirsz-ever/cminus
72bc799191dfeec09dc8032b18b0db58215baab5
use pest::iterators::Pair; use pest::Parser; use pest_derive::*; use std::fmt; #[derive(Clone, Debug)] pub enum Token<'input> { SEMI, COMMA, ASSIGNOP, RELOP(&'input str), PLUS, MINUS, STAR, DIV, AND, OR, DOT, NOT, TYPE(&'input str), LP, RP, LB, RB, ...
use pest::iterators::Pair; use pest::Parser; use pest_derive::*; use std::fmt; #[derive(Clone, Debug)] pub enum Token<'input> { SEMI, COMMA, ASSIGNOP, RELOP(&'input str), PLUS, MINUS, STAR, DIV, AND, OR, DOT, NOT, TYPE(&'input str), LP, RP, LB, RB, ...
fn get_int(pair: Pair<Rule>) -> Token { let raw = pair.as_str(); match pair.as_rule() { Rule::HEX_LITERAL => i32::from_str_radix(&raw[2..], 16) .map(Token::INT) .unwrap_or_else(|_| Token::IllegalHex(raw)), Rule::OCT_LITERAL => i32::from_str_radix(&raw[1..], 8) ...
function_block-full_function
[ { "content": "fn println_err(e: &ParseError<lexer::Location, lexer::Token<'_>, lexer::LexicalError>) {\n\n use ParseError::*;\n\n match e {\n\n InvalidToken { location } => {\n\n println!(\"Error type B at Line {}: Invalid Token.\", location.line);\n\n }\n\n UnrecognizedEOF...
Rust
src/ffi/linux/asound.rs
Aldarobot/wavy
6ae76f97fc6179e482ec24d849e8af6d20153eaa
#![allow(unsafe_code)] use std::os::raw::{c_char, c_int, c_long, c_uint, c_ulong, c_void}; #[allow(unused)] #[repr(C)] #[non_exhaustive] #[derive(Copy, Clone, Debug, PartialEq)] pub(crate) enum SndPcmMode { Block = 0, Nonblock = 1, Async = 2, } #[allow(unused)] #[repr(C)] #[non_exhaustiv...
#![allow(unsafe_code)] use std::os::raw::{c_char, c_int, c_long, c_uint, c_ulong, c_void}; #[allow(unused)] #[repr(C)] #[non_exhaustive] #[derive(Copy, Clone, Debug, PartialEq)] pub(crate) enum SndPcmMode { Block = 0, Nonblock = 1, Async = 2, } #[allow(unused)] #[repr(C)] #[non_exhaustiv...
uffer: *mut c_void, size: c_ulong, ) -> c_long; fn snd_pcm_writei( pcm: *mut c_void, buffer: *const c_void, size: c_ulong, ) -> c_long; fn snd_pcm_poll_descriptors(pcm: *mut c_void, pfds: *mut PollFd, space: c_uint) -> c_int; fn snd_pcm_poll_descriptors_count(pc...
mut *mut *mut c_void, ) -> c_int; fn snd_device_name_get_hint(hint: *const c_void, id: *const c_char) -> *mut c_char; fn snd_device_name_free_hint(hints: *mut *mut c_void) -> c_int; fn snd_pcm_open(pcmp: *mut *mut c_void, name: *const c_char, stream: SndPcmStream, m...
random
[ { "content": "/// An event handled by the event loop.\n\nenum Event<'a> {\n\n /// Speaker is ready to play more audio.\n\n Play(SpeakersSink<'a, Mono32>),\n\n /// Microphone has recorded some audio.\n\n Record(MicrophoneStream<'a, Mono32>),\n\n}\n\n\n", "file_path": "examples/monitor.rs", "r...
Rust
mkt-inventory-web/src/agents/data_inventory.rs
Qrimpuff/MKT-Blanket
b315dd9cabb419981195597d3c2a18d61bf41a5b
use std::{ collections::{HashMap, HashSet}, rc::Rc, sync::RwLock, }; use super::{ data::DataStore, inventory::{Inventory, InventoryRequest}, }; use mkt_data::{item_type_from_id, Course, CourseId, Item, ItemId, ItemType, OwnedItem}; use yew_agent::{ utils::store::{Bridgeable, ReadOnly, StoreWrap...
use std::{ collections::{HashMap, HashSet}, rc::Rc, sync::RwLock, }; use super::{ data::DataStore, inventory::{Inventory, InventoryRequest}, }; use mkt_data::{item_type_from_id, Course, CourseId, Item, ItemId, ItemType, OwnedItem}; use yew_agent::{ utils::store::{Bridgeable, ReadOnly, StoreWrap...
fn update(&mut self, msg: Self::Message) { match msg { Msg::DataStore(data) => { let data = &data.borrow().data; let mut state = self.state.write().unwrap(); let mut new_courses = HashMap::<CourseId, Shared<DataInvCours...
handlers, link, state, self_dispatcher, _data_store: DataStore::bridge(callback_data), inventory: Inventory::bridge(callback_inv), } }
function_block-function_prefix_line
[ { "content": "pub fn update_mkt_item_data(data: &mut MktData, i_type: ItemType) {\n\n // get data (from Super Mario Wiki)\n\n let url = match i_type {\n\n ItemType::Driver => \"https://www.mariowiki.com/List_of_drivers_in_Mario_Kart_Tour\",\n\n ItemType::Kart => \"https://www.mariowiki.com/L...
Rust
ergotree-interpreter/src/eval/scoll.rs
hexresearch/sigma-rust
a819b935b2b06085516dccdcd857a63e67f7e497
use crate::eval::EvalError; use crate::eval::Evaluable; use ergotree_ir::mir::constant::TryExtractInto; use ergotree_ir::mir::value::CollKind; use ergotree_ir::mir::value::Value; use super::EvalFn; pub(crate) static INDEX_OF_EVAL_FN: EvalFn = |_env, _ctx, obj, args| { Ok(Value::Int({ let normalized_input...
use crate::eval::EvalError; use crate::eval::Evaluable; use ergotree_ir::mir::constant::TryExtractInto; use ergotree_ir::mir::value::CollKind; use ergotree_ir::mir::value::Value; use super::EvalFn; pub(crate) static INDEX_OF_EVAL_FN: EvalFn = |_env, _ctx, obj, args| { Ok(Value::Int({ let normalized_input...
let res = eval_out_wo_ctx::<i32>(&expr); assert_eq!(res, 1); } #[test] fn eval_index_of_default() { let coll_const: Constant = vec![1i64, 2i64].into(); let expr: Expr = MethodCall::new( coll_const.into(), scoll::INDEX_OF_METHOD .clone() ...
nc_arg = lambda.args.first().ok_or_else(|| { EvalError::NotFound("flatmap: lambda has empty arguments list".to_string()) })?; let env1 = env.clone().extend(func_arg.idx, arg); lambda.body.eval(&env1, ctx) }; let mapper_input_tpe = lambda .args .first() ...
random
[ { "content": "type EvalFn = fn(env: &Env, ctx: &mut EvalContext, Value, Vec<Value>) -> Result<Value, EvalError>;\n\n\n", "file_path": "ergotree-interpreter/src/eval.rs", "rank": 0, "score": 258453.00781949516 }, { "content": "fn eval_gt(lv: Value, rv: Value) -> Result<Value, EvalError> {\n\n...
Rust
wasmi_v1/src/instance.rs
tavianator/wasmi
022c75129219a78f8e5eee3be2e1fadf7ed6a77b
use super::{ engine::DedupFuncType, AsContext, Extern, Func, Global, Index, Memory, StoreContext, Stored, Table, }; use alloc::{ collections::{btree_map, BTreeMap}, string::{String, ToString}, vec::Vec, }; use core::{iter::FusedIterator, ops::Deref}; #[derive(Debug, ...
use super::{ engine::DedupFuncType, AsContext, Extern, Func, Global, Index, Memory, StoreContext, Stored, Table, }; use alloc::{ collections::{btree_map, BTreeMap}, string::{String, ToString}, vec::Vec, }; use core::{iter::FusedIterator, ops::Deref}; #[derive(Debug, ...
pub(crate) fn finish(mut self) -> InstanceEntity { self.instance.initialized = true; self.instance } } impl Deref for InstanceEntityBuilder { type Target = InstanceEntity; fn deref(&self) -> &Self::Target { &self.instance } } #[derive(Debug, Copy, Clone)] #[repr(tra...
pub(crate) fn push_export(&mut self, name: &str, new_value: Extern) { if let Some(old_value) = self.instance.exports.get(name) { panic!( "tried to register {:?} for name {} but name is already used by {:?}", new_value, name, old_value, ) } ...
function_block-full_function
[]
Rust
apk/src/compiler/mod.rs
cloudpeers/xcross
6ccbde906b7cc5ad071f7f714eb5f276695574a4
use crate::manifest::AndroidManifest; use crate::res::{ Chunk, ResTableConfig, ResTableEntry, ResTableHeader, ResTablePackageHeader, ResTableTypeHeader, ResTableTypeSpecHeader, ResTableValue, ResValue, ScreenType, }; use anyhow::Result; mod attributes; mod table; mod xml; pub use table::Table; pub fn compile...
use crate::manifest::AndroidManifest; use crate::res::{ Chunk, ResTableConfig, ResTableEntry, ResTableHeader, ResTablePackageHeader, ResTableTypeHeader, ResTableTypeSpecHeader, ResTableValue, ResValue, ScreenType, }; use anyhow::Result; mod attributes; mod table; mod xml; pub use table::Table; pub fn compile...
#[test] fn test_compile_manifest() -> Result<()> { let android = crate::tests::find_android_jar()?; let mut table = Table::default(); table.import_apk(&android)?; let mut manifest = AndroidManifest::default(); manifest.application.label = Some("helloworld".into()); ...
able::default(); table.import_apk(&android)?; let entry = table.entry_by_ref(Ref::attr("compileSdkVersionCodename"))?; assert_eq!(u32::from(entry.id()), 0x01010573); Ok(()) }
function_block-function_prefixed
[ { "content": "pub fn compile_attr(table: &Table, name: &str, value: &str, strings: &Strings) -> Result<ResValue> {\n\n let entry = table.entry_by_ref(Ref::attr(name))?;\n\n let attr_type = entry.attribute_type().unwrap();\n\n let (data, data_type) = match attr_type {\n\n ResAttributeType::Refere...
Rust
border-core/src/core/record.rs
lostmsu/border
473286035dd71c5afeaf0e0b47574b18ebb1f8c2
use chrono::prelude::{DateTime, Local}; use std::{ collections::{ hash_map::{IntoIter, Iter, Keys}, HashMap, }, convert::Into, iter::IntoIterator, path::Path, }; use tensorboard_rs::summary_writer::SummaryWriter; use crate::error::LrrError; #[derive(Debug, Clone)] pub enum Recor...
use chrono::prelude::{DateTime, Local}; use std::{ collections::{ hash_map::{IntoIter, Iter, Keys}, HashMap, }, convert::Into, iter::IntoIterator, path::Path, }; use tensorboard_rs::summary_writer::SummaryWriter; use crate::error::LrrError; #[derive(Debug, Clone)] pub enum Recor...
} pub fn keys(&self) -> Keys<String, RecordValue> { self.0.keys() } pub fn insert(&mut self, k: impl Into<String>, v: RecordValue) { self.0.insert(k.into(), v); } pub fn iter(&self) -> Iter<'_, String, RecordValue> { self.0.iter() } pub fn...
Self( s.iter() .map(|(k, v)| (k.clone().into(), v.clone())) .collect(), )
call_expression
[ { "content": "/// Run episodes with a policy and recorder.\n\n///\n\n/// This method assumes that the environment is non-vectorized or `n_proc`=1.\n\npub fn eval_with_recorder<E, P, R>(\n\n env: &mut E,\n\n policy: &mut P,\n\n n_episodes: usize,\n\n recorder: &mut R,\n\n) -> Vec<f32>\n\nwhere\n\n ...
Rust
artichoke-backend/src/extn/core/regexp/trampoline.rs
katafrakt/artichoke
07b6148e981aab811947f9c22a3389736aedeb43
use std::convert::TryFrom; use crate::extn::core::regexp::Regexp; use crate::extn::prelude::*; pub fn initialize( interp: &mut Artichoke, pattern: Value, options: Option<Value>, encoding: Option<Value>, into: Option<Value>, ) -> Result<Value, Exception> { let (options, encoding) = interp.try_c...
use std::convert::TryFrom; use crate::extn::core::regexp::Regexp; use crate::extn::prelude::*; pub fn initialize( interp: &mut Artichoke, pattern: Value, options: Option<Value>, encoding: Option<Value>, into: Option<Value>, ) -> Result<Value, Exception> { let (options, encoding) = interp.try_c...
} pub fn is_casefold(interp: &mut Artichoke, regexp: Value) -> Result<Value, Exception> { let regexp = unsafe { Regexp::try_from_ruby(interp, &regexp) }?; let borrow = regexp.borrow(); let is_casefold = borrow.is_casefold(interp); Ok(interp.convert(is_casefold)) } pub fn is_fixed_encoding(interp: &mu...
match pos.map(Int::try_from) { Some(Ok(pos)) => Ok(interp.convert(pos)), Some(Err(_)) => Err(Exception::from(ArgumentError::new( interp, "string too long", ))), None => Ok(interp.convert(None::<Value>)), }
if_condition
[ { "content": "pub fn regexp(interp: &mut Artichoke, value: Value) -> Result<Value, Exception> {\n\n let data = unsafe { MatchData::try_from_ruby(interp, &value) }?;\n\n let borrow = data.borrow();\n\n let regexp = borrow.regexp();\n\n // TODO(GH-614): MatchData#regexp needs to return an identical Re...
Rust
src/ants.rs
mockersf/aous
c7b4b4ad5653807cac4529d9dd6739d43f4bdc53
use std::{f32::consts::PI, ops::Deref}; use bevy::prelude::*; use rand::Rng; use crate::{ ant_hill::HillEvents, food::{FoodHeap, FoodPellet}, game_state::GameState, terrain_spawner::{EmptyLot, ObstacleMap}, DEF, }; pub struct AntsPlugin; impl Plugin for AntsPlugin { fn build(&self, app: &mut...
use std::{f32::consts::PI, ops::Deref}; use bevy::prelude::*; use rand::Rng; use crate::{ ant_hill::HillEvents, food::{FoodHeap, FoodPellet}, game_state::GameState, terrain_spawner::{EmptyLot, ObstacleMap}, DEF, }; pub struct AntsPlugin; impl Plugin for AntsPlugin { fn build(&self, app: &mut...
} if near < (1.0 / DEF * ant.gene.antennas).powf(2.0) { for food_entity in Deref::deref(target_heap.unwrap()) { if let Ok((food, mut pellet)) = foods.get_mut(*food_entity) { if !pellet.targeted { ...
if distance < near { near = distance; target_heap = Some(children); }
if_condition
[ { "content": "fn despawn_all(mut commands: Commands, all: Query<Entity>) {\n\n for entity in all.iter() {\n\n commands.entity(entity).despawn();\n\n }\n\n}\n", "file_path": "src/game_state.rs", "rank": 0, "score": 132137.51119329402 }, { "content": "fn background_scene(mut comma...
Rust
src/client.rs
walfie/twitter-pinned
9f75f4ef33011b7e17d9cbdc85d10c3b2549b5ee
use anyhow::{Context, Result}; use reqwest::header::*; use serde::{Deserialize, Serialize}; use serde_json::Value; pub const DEFAULT_USER_AGENT: &'static str = "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/94.0.4606.71 Safari/537.36"; pub const DEFAULT_BEARER_TOKEN: &'...
use anyhow::{Context, Result}; use reqwest::header::*; use serde::{Deserialize, Serialize}; use serde_json::Value; pub const DEFAULT_USER_AGENT: &'static str = "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/94.0.4606.71 Safari/537.36"; pub const DEFAULT_BEARER_TOKEN: &'...
fn extract_pinned_tweet_json(json: Value) -> Result<Option<PinnedTweet>> { let result = json .pointer("/data/user/result/timeline/timeline/instructions") .context("failed to get timeline instructions")? .as_array() .context("failed to parse instructions as a...
let json = serde_json::from_str::<Value>(&body)?; Self::extract_pinned_tweet_json(json) .with_context(|| format!("failed to get value from JSON: {}", &body)) }
function_block-function_prefix_line
[ { "content": "use anyhow::{Context, Result};\n\nuse structopt::StructOpt;\n\nuse twitter_pinned::*;\n\n\n\n#[derive(StructOpt)]\n\npub struct Opt {\n\n #[structopt(long, env, default_value = DEFAULT_USER_AGENT)]\n\n pub user_agent: String,\n\n #[structopt(long, env, default_value = DEFAULT_BEARER_TOKEN...
Rust
pallets/deip_proposal/src/benchmarking.rs
StasDachinsky/deip-node
f7109e002cb1f0724d59784947e9f39c4a879f3a
#![cfg(feature = "runtime-benchmarks")] use super::{proposal::*, *}; use core::convert::TryInto; use frame_benchmarking::{account, benchmarks, whitelisted_caller}; use frame_support::{ensure, traits::Get}; use frame_system::{Config as Sys, EventRecord, RawOrigin}; use sp_std::prelude::*; use crate::{proposal::BATCH_M...
#![cfg(feature = "runtime-benchmarks")] use super::{proposal::*, *}; use core::convert::TryInto; use frame_benchmarking::{account, benchmarks, whitelisted_caller}; use frame_support::{ensure, traits::Get}; use frame_system::{Config as Sys, EventRecord, RawOrigin}; use sp_std::prelude::*; use crate::{proposal::BATCH_M...
}.into(), }); } let batch_weight = batch_weight::<T>(batch.as_slice()); (batch, batch_weight) } fn init_member<T: Config>(index: u32) -> T::AccountId { let member = account::<T::AccountId>("member", index, SEED); let member_key = frame_system::Account::<T>::hashed_key_for(&member); fram...
(), }]; while batch.len() < c { batch.push(InputProposalBatchItem::<T> { account: init_member::<T>(batch.len() as u32).into(), call: frame_system::Call::<T>::remark { remark: vec![]
function_block-random_span
[ { "content": "fn init_member<T: Config>(index: u32) -> T::AccountId {\n\n let member = account::<T::AccountId>(\"member\", index, SEED);\n\n whitelist_account!(member);\n\n member\n\n}\n\n\n", "file_path": "pallets/deip/src/benchmarking.rs", "rank": 3, "score": 233237.4010269089 }, { ...
Rust
src/controllers/utils.rs
earaujoassis/knock-knock
1b3831646546bc782ec2582384ab568ac6e67194
#[allow(unused_macros)] macro_rules! import_controller_generic_requeriments { ($($includes:ident),*) => { #[allow(unused_imports)] use std::error::Error; #[allow(unused_imports)] use std::io::Read; #[allow(unused_imports)] use serde_json; #[allow(unused_import...
#[allow(unused_macros)] macro_rules! import_controller_generic_requeriments { ($($includes:ident),*) => { #[allow(unused_imports)] use std::error::Error; #[allow(unused_imports)] use std::io::Read; #[allow(unused_imports)] use serde_json; #[allow(unused_import...
h param.parse::<$parse_type>() { Ok(expr) => expr, Err(_) => return $return_http } } } } #[allow(unused_macros)] macro_rules! get_route_parameter { ($req:expr, $param:expr, $return_http:expr) => { { let param = $req.extensions.get::<Router...
Ok() .status($status) .json(response); } }; ($name:ident, $status:expr, "text") => { #[allow(dead_code)] pub fn $name<S: Into<String>>(text: S) -> HttpResponse { return HttpResponse::Ok() .status($status) .body(t...
random
[ { "content": "pub fn request_dns_servers() {\n\n\n\n}\n", "file_path": "src/utils/power_dns_api.rs", "rank": 0, "score": 76032.71484902779 }, { "content": "pub fn test_helper() -> TestServer {\n\n dotenv::from_filename(\".env.testing\").ok();\n\n embed_migrations!(\"migrations\");\n\n\...
Rust
src/main.rs
vangorra/jq_proxy
702027bf9fd2d1657048ffee246ee92e2d184a7e
use std::collections::HashMap; use std::fs; use std::io::Write; use std::process::exit; use std::str; use actix_web::{App, client::Client, HttpRequest, HttpResponse, HttpServer, middleware::Logger, web}; use actix_web::dev::HttpResponseBuilder; use actix_web::http::Method; use actix_web::web::Bytes; use chrono::Local;...
use std::collections::HashMap; use std::fs; use std::io::Write; use std::process::exit; use std::str; use actix_web::{App, client::Client, HttpRequest, HttpResponse, HttpServer, middleware::Logger, web}; use actix_web::dev::HttpResponseBuilder; use actix_web::http::Method; use actix_web::web::Bytes; use chrono::Local;...
let mut builder = HttpResponseBuilder::new(response.status()); builder.content_type("application/json"); for (key, value) in response.headers() { builder.header( key, value.to_str().unwrap() ); } return builder.body(jq_result.unwrap()); } f...
if jq_result.is_err() { return HttpResponse::InternalServerError() .json(ErrorResponse { is_error: true, message: jq_result.unwrap_err().to_string(), }); }
if_condition
[ { "content": "# jq_proxy\n\nA simple http service which proxies json through the popular json tool jq.\n\n\n\n## Quickstart\n\n```bash\n\n$ docker run --rm --publish 8080:8080 --volume $(pwd)/config.yaml:/config.yaml vangorra/jq_proxy --config-file-path /config.yaml\n\n$ curl http://localhost:8080/proxy\n\n```\...
Rust
galangua-wasm/src/wasm_renderer.rs
tyfkda/galangua
db30860c2f2769ff2263db9244053caf9a981363
extern crate js_sys; use std::cell::RefCell; use std::collections::HashMap; use std::path::Path; use std::rc::Rc; use wasm_bindgen::prelude::*; use wasm_bindgen::JsCast; use wasm_bindgen_futures::JsFuture; use web_sys::{HtmlCanvasElement, HtmlImageElement, Request, RequestInit, RequestMode, Response}; use galangua_c...
extern crate js_sys; use std::cell::RefCell; use std::collections::HashMap; use std::path::Path; use std::rc::Rc; use wasm_bindgen::prelude::*; use wasm_bindgen::JsCast; use wasm_bindgen_futures::JsFuture; use web_sys::{HtmlCanvasElement, HtmlImageElement, Request, RequestInit, RequestMode, Response}; use galangua_c...
fn set_draw_color(&mut self, r: u8, g: u8, b: u8) { self.context.set_fill_style(&JsValue::from(format!("rgb({},{},{})", r, g, b))); } fn fill_rect(&mut self, dst: Option<[&Vec2I; 2]>) { if let Some(dst) = dst { self.context.fill_rect(dst[0].x as f64, dst[0].y as f64, dst[1].x ...
fn draw_sprite_rot(&mut self, sprite_name: &str, pos: &Vec2I, angle: u8, center: Option<&Vec2I>) { let sprite_sheet = self.sprite_sheet.borrow(); let (sheet, tex_name) = sprite_sheet.get(sprite_name) .expect("No sprite_sheet"); let image = self.images.borrow();...
function_block-full_function
[ { "content": "// Return: 360 degrees = ANGLE * ONE\n\npub fn atan2_lut(mut x: i32, mut y: i32) -> i32 {\n\n let table = &ATAN2_TABLE;\n\n let bit = ATAN2_TABLE_BIT;\n\n\n\n let negx = x.is_negative();\n\n let negy = y.is_negative();\n\n x = x.abs();\n\n y = y.abs();\n\n\n\n let swapxy = if ...
Rust
imxrt1062-pac/imxrt1062-adc-etc/src/ctrl.rs
Shock-1/teensy4-rs
effc3b290f1be3c7aef62a78e82dbfbc27aa6370
#[doc = "Reader of register CTRL"] pub type R = crate::R<u32, super::CTRL>; #[doc = "Writer for register CTRL"] pub type W = crate::W<u32, super::CTRL>; #[doc = "Register CTRL `reset()`'s with value 0xc000_0000"] impl crate::ResetValue for super::CTRL { type Type = u32; #[inline(always)] fn reset_value() ->...
#[doc = "Reader of register CTRL"] pub type R = crate::R<u32, super::CTRL>; #[doc = "Writer for register CTRL"] pub type W = crate::W<u32, super::CTRL>; #[doc = "Register CTRL `reset()`'s with value 0xc000_0000"] impl crate::ResetValue for super::CTRL { type Type = u32; #[inline(always)] fn reset_value() ->...
IDER_W { PRE_DIVIDER_W { w: self } } #[doc = "Bit 29 - 1'b0: Trig DMA_REQ with latched signal, REQ will be cleared when ACK and source request cleared"] #[inline(always)] pub fn dma_mode_sel(&mut self) -> DMA_MODE_SEL_W { DMA_MODE_SEL_W { w: self } } #[doc = "Bit 30 - 1'b1: TSC i...
Y_R { EXT1_TRIG_PRIORITY_R::new(((self.bits >> 13) & 0x07) as u8) } #[doc = "Bits 16:23 - Pre-divider for trig delay and interval ."] #[inline(always)] pub fn pre_divider(&self) -> PRE_DIVIDER_R { PRE_DIVIDER_R::new(((self.bits >> 16) & 0xff) as u8) } #[doc = "Bit 29 - 1'b0: Trig...
random
[ { "content": "/// Migrate the `lib.rs` of the PAC subscrate, adding\n\n/// our necessary header to the top of the file.\n\nfn write_lib<R: Read>(crate_path: &Path, mut src: R) {\n\n static LIB_PRELUDE: &str = r#\"#![deny(warnings)]\n\n#![allow(non_camel_case_types)]\n\n#![allow(clippy::all)]\n\n#![no_std]\n\...
Rust
src/model/lantern.rs
tene/silmaril
80cb669bfedc0768520c9d9e80c876a038844e81
use crate::{lch_to_rgb, pixelindex::*, Color, FaceType}; use num_traits::Float; use palette::{Hue, Saturate, Shade}; use typenum::{U125, U5}; pub struct Lantern { pub color: Color, pub pixels: [Color; 125], } impl Lantern { pub fn new(color: Color) -> Self { let pixels = [color; 125]; Self...
use crate::{lch_to_rgb, pixelindex::*, Color, FaceType}; use num_traits::Float; use palette::{Hue, Saturate, Shade}; use typenum::{U125, U5}; pub struct Lantern { pub color: Color, pub pixels: [Color; 125], } impl Lantern { pub fn new(color: Color) -> Self { let pixels = [color; 125]; Self...
fn index_top() -> Option<PixelIndex<Self>> { Some(112.into()) } } const FACE_IDX_RADIUS: [usize; 25] = [ 2, 2, 2, 2, 2, 2, 1, 1, 1, 2, 2, 1, 0, 1, 2, 2, 1, 1, 1, 2, 2, 2, 2, 2, 2, ]; const TOP_IDX_ANGLE: [f32; 25] = [ 8.0 / 16.0, 7.0 / 16.0, 6.0 / 16.0, 5.0 / 16.0, 4.0 / 16.0...
fn spherical_to_index(dir: f32, height: f32) -> PixelIndex<Self> { if height < 5.0 / 8.0 { return Self::cylindrical_to_index(dir, height * 8.0 / 5.0); } let r = 7 - (height * 8.0).trunc().min(7.0) as usize; /* Top Indices 20 15 10 5 0 21 16 11 6 1 22 1...
function_block-full_function
[ { "content": "pub fn lch_to_rgb(lch: Color) -> [u8; 3] {\n\n let rgb: Srgb<f32> = Srgb::convert_from(lch);\n\n let [r, g, b]: [f32; 3] = rgb.into_raw();\n\n //[(r * 256.0) as u8, (g * 256.0) as u8, (b * 256.0) as u8]\n\n [r.convert(), g.convert(), b.convert()]\n\n}\n\n\n", "file_path": "src/colo...
Rust
src/day8.rs
pieps/aoc2020
59be6d8dd9e7a488a6615f4f4a70b31febcf0242
use lazy_static::lazy_static; use rayon::prelude::*; use regex::Regex; use std::collections::HashSet; #[cfg(test)] mod tests { #[test] fn it_works() { assert_eq!(2 + 2, 4); } } lazy_static! { pub static ref PARSER: Regex = Regex::new(r"(\w{3}) ([+-]\d+)").unwrap(); } #[derive(Clone, Copy)] en...
use lazy_static::lazy_static; use rayon::prelude::*; use regex::Regex; use std::collections::HashSet; #[cfg(test)] mod tests { #[test] fn it_works() { assert_eq!(2 + 2, 4); } } lazy_static! { pub static ref PARSER: Regex = Regex::new(r"(\w{3}) ([+-]\d+)").unwrap(); } #[derive(Clone, Copy)] en...
ion { Instruction::ACC(i) => self.acc += i, Instruction::JMP(i) => self.ip = (self.ip as i32 + i - 1) as usize, Instruction::NOP(_) => (), }; self.ip += 1; } None } pub fn reset(&mut self) { self.acc = 0; se...
) } fn new_internal(instructions: Vec<Instruction>) -> Program { Program { instructions, acc: 0, ip: 0, visited: HashSet::new(), } } pub fn run(&mut self) -> Option<i32> { while !self.visited.contains(&self.ip) { if...
random
[ { "content": "fn process_line(line: &str) -> Entry {\n\n lazy_static! {\n\n static ref RE: Regex = Regex::new(r\"(\\d+)-(\\d+) (\\w): (\\w+)\").unwrap();\n\n }\n\n let captures: Captures = RE.captures(&line).unwrap();\n\n\n\n let rule = Rule {\n\n start: captures.get(1).unwrap().as_str...
Rust
opendatafabric/src/serde/flatbuffers/serdes.rs
kamu-data/kamu-cli
29f1c2a374863fb323df3f87b709fb410c64d82b
use super::convertors::*; use super::odf_generated as fbgen; pub use crate::serde::{Buffer, Error, MetadataBlockDeserializer, MetadataBlockSerializer}; use crate::serde::{EngineProtocolDeserializer, EngineProtocolSerializer}; use crate::Multicodec; use crate::{ExecuteQueryRequest, ExecuteQueryResponse, MetadataBlock}...
use super::convertors::*; use super::odf_generated as fbgen; pub use crate::serde::{Buffer, Error, MetadataBlockDeserializer, MetadataBlockSerializer}; use crate::serde::{EngineProtocolDeserializer, EngineProtocolSerializer}; use crate::Multicodec; use crate::{ExecuteQueryRequest, ExecuteQueryResponse, MetadataBlock}...
dataBlock::deserialize(block_proxy); Ok(block) } } pub struct FlatbuffersEngineProtocol; impl EngineProtocolSerializer for FlatbuffersEngineProtocol { fn write_execute_query_request(&self, inst: &ExecuteQueryRequest) -> Result<Buffer<u8>, Error> { let mut fb = flatbuffers::FlatBufferBuilder::n...
n serialize_metadata_block(&self, block: &MetadataBlock) -> Buffer<u8> { let mut fb = flatbuffers::FlatBufferBuilder::with_capacity(Self::METADATA_BLOCK_SIZE_ESTIMATE); let offset = block.serialize(&mut fb); fb.finish(offset, None); let (buf, head) = fb.collapse(); Bu...
random
[ { "content": "struct RemoteAliasesImpl {\n\n metadata_repo: MetadataRepositoryImpl,\n\n dataset_handle: DatasetHandle,\n\n config: DatasetConfig,\n\n}\n\n\n\nimpl RemoteAliasesImpl {\n\n fn new(\n\n metadata_repo: MetadataRepositoryImpl,\n\n dataset_handle: DatasetHandle,\n\n co...
Rust
src/repository/admin/controller.rs
wherkamp/nitro_repo
7ef0ff2d2272cd37d37593e335290d292686018a
use std::fs::create_dir_all; use std::path::PathBuf; use actix_web::{delete, get, HttpRequest, patch, post, put, web}; use serde::{Deserialize, Serialize}; use crate::api_response::{APIResponse, SiteResponse}; use crate::DbPool; use crate::error::response::{already_exists, bad_request, not_found, unauthorized}; use c...
use std::fs::create_dir_all; use std::path::PathBuf; use actix_web::{delete, get, HttpRequest, patch, post, put, web}; use serde::{Deserialize, Serialize}; use crate::api_response::{APIResponse, SiteResponse}; use crate::DbPool; use crate::error::response::{already_exists, bad_request, not_found, unauthorized}; use c...
#[patch("/api/admin/repository/{repo}/policy/{policy}")] pub async fn update_policy( pool: web::Data<DbPool>, r: HttpRequest, path: web::Path<(i64, Policy)>, ) -> SiteResponse { let (repo, policy) = path.into_inner(); let connection = pool.get()?; let user = get_user_by_header(r.headers(), &...
pub async fn update_active_status( pool: web::Data<DbPool>, r: HttpRequest, path: web::Path<(i64, bool)>, ) -> SiteResponse { let (repo, active) = path.into_inner(); let connection = pool.get()?; let user = get_user_by_header(r.headers(), &connection)?; if user.is_none() || !user.unwrap()....
function_block-full_function
[ { "content": "pub fn get_time_file<S: Into<String>>(storage: &Storage, repo: &Repository, id: S) -> PathBuf {\n\n return get_storage_location()\n\n .join(\"storages\")\n\n .join(&storage.name)\n\n .join(&repo.name)\n\n .join(id.into())\n\n .join(\"times.json\");\n\n}\n\n\n"...
Rust
src/vec.rs
geeklint/list-any
9ccfa5c259573cc54924c2528042c7020509dd8c
/* SPDX-License-Identifier: (Apache-2.0 OR MIT OR Zlib) */ /* Copyright © 2021 Violet Leonard */ #![allow(clippy::module_name_repetitions)] use core::{ any::{Any, TypeId}, marker::PhantomData, mem, ops::{Deref, DerefMut}, slice, }; use alloc::vec::Vec; use super::{ AnyBound, DeferredValue, H...
/* SPDX-License-Identifier: (Apache-2.0 OR MIT OR Zlib) */ /* Copyright © 2021 Violet Leonard */ #![allow(clippy::module_name_repetitions)] use core::{ any::{Any, TypeId}, marker::PhantomData, mem, ops::{Deref, DerefMut}, slice, }; use alloc::vec::Vec; use super::{ AnyBound, DeferredValue, H...
assert!(vec_any.downcast_mut::<u32>().is_none()); assert!(vec_any.downcast_mut::<u8>().is_some()); assert_eq!(vec_any.downcast_slice::<()>(), None); assert_eq!(vec_any.downcast_slice::<u32>(), None); assert_eq!(vec_any.downcast_slice::<u8>(), Some(&b"hello"[..])); let vec_an...
igin: self }) } else { None } } #[must_use] pub fn downcast_slice<T: AnyBound<B>>(&self) -> Option<&[T]> { if self.type_id_of_element() == TypeId::of::<T>() { Some(unsafe { slice::from_raw_parts(self.ptr.cast(), self.len) }...
random
[ { "content": "#[derive(Debug)]\n\nstruct Metadata {\n\n type_id: fn() -> TypeId,\n\n #[cfg(feature = \"alloc\")]\n\n drop: unsafe fn(*mut (), usize, usize),\n\n}\n\n\n\nimpl Metadata {\n\n fn is_deferred(&'static self) -> bool {\n\n (self.type_id)() == TypeId::of::<DeferredValue>()\n\n }\n...
Rust
rust-runtime/aws-smithy-checksums/src/lib.rs
guymguym/smithy-rs
f5e0f83d459b55f3c0870e4876a062293f1b3be3
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * SPDX-License-Identifier: Apache-2.0 */ use aws_smithy_http::callback::BodyCallback; use aws_smithy_types::base64; use http::header::{HeaderMap, HeaderName, HeaderValue}; use sha1::Digest; use std::io::Write; const CRC_32_NAME: &str = "x-amz...
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * SPDX-License-Identifier: Apache-2.0 */ use aws_smithy_http::callback::BodyCallback; use aws_smithy_types::base64; use http::header::{HeaderMap, HeaderName, HeaderValue}; use sha1::Digest; use std::io::Write; const CRC_32_NAME: &str = "x-amz...
}
let expected_checksum = "0x916F0027A575074CE72A331777C3478D6513F786A591BD892DA1A577BF2335F9"; assert_eq!(decoded_checksum, expected_checksum); }
function_block-function_prefix_line
[ { "content": "fn normalized_header(headers: &HeaderMap, key: &str) -> Option<String> {\n\n if !headers.contains_key(key) {\n\n None\n\n } else {\n\n Some(\n\n headers\n\n .get_all(key)\n\n .iter()\n\n .map(|hv| hv.to_str().unwrap())\n\n...
Rust
src/handlers/owner.rs
thallada/BazaarRealmAPI
964ab26007d222c84259c78cfe3c851383a6c0c8
use anyhow::Result; use http::StatusCode; use hyper::body::Bytes; use ipnetwork::IpNetwork; use mime::Mime; use std::net::SocketAddr; use uuid::Uuid; use warp::reply::{with_header, with_status}; use warp::{Rejection, Reply}; use crate::caches::{CachedResponse, CACHES}; use crate::models::{FullPostedOwner, ListParams, ...
use anyhow::Result; use http::StatusCode; use hyper::body::Bytes; use ipnetwork::IpNetwork; use mime::Mime; use std::net::SocketAddr; use uuid::Uuid; use warp::reply::{with_header, with_status}; use warp::{Rejection, Reply}; use crate::caches::{CachedResponse, CACHES}; use crate::models::{FullPostedOwner, ListParams, ...
pub async fn create( bytes: Bytes, remote_addr: Option<SocketAddr>, api_key: Option<Uuid>, real_ip: Option<IpNetwork>, content_type: Option<Mime>, env: Environment, ) -> Result<impl Reply, Rejection> { if let Some(api_key) = api_key { let DeserializedBody { body: owner,...
pub async fn list( list_params: ListParams, etag: Option<String>, accept: Option<AcceptHeader>, env: Environment, ) -> Result<impl Reply, Rejection> { let TypedCache { content_type, cache, } = TypedCache::<ListParams, CachedResponse>::pick_cache( accept, &CACHES.l...
function_block-full_function
[ { "content": "pub fn check_etag(etag: Option<String>, response: CachedResponse) -> CachedResponse {\n\n if let Some(request_etag) = etag {\n\n if let Some(response_etag) = response.headers.get(\"etag\") {\n\n if request_etag == *response_etag {\n\n return CachedResponse::not_...
Rust
challenge_004/src/too_smart.rs
greenfork/project_euler
aeee87404f91e71c4e25c039fb2ec8be769964a8
use std::io; fn main() { let mut queries = String::new(); io::stdin().read_line(&mut queries).unwrap(); let queries: usize = queries.trim_right().parse().unwrap(); for _ in 0..queries { let mut number = String::new(); io::stdin().read_line(&mut number).unwrap(); let number: u64...
use std::io; fn main() { let mut queries = String::new(); io::stdin().read_line(&mut queries).unwrap(); let queries: usize = queries.trim_right().parse().unwrap(); for _ in 0..queries { let mut number = String::new(); io::stdin().read_line(&mut number).unwrap(); let number: u64...
fn factorial(&n: &u64) -> u64 { if n == 1 { return n; } factorial(&(n - 1)) * n } fn prime_factors(number: &u64) -> Vec<u64> { let mut prime_factors: Vec<u64> = Vec::new(); let mut number = *number / 11; prime_factors.push(11); let mut x = 2; let mut y = 2; let mut factor = 1; ...
fn permut(&number: &u64) -> Vec<Vec<u64>> { let mut prime_factors = prime_factors(&number); prime_factors.sort(); let length = prime_factors.len(); let perm_count = factorial(&(length as u64)) as usize; let mut permutations: Vec<Vec<u64>> = Vec::new(); permutations.push(prime_factors); for ...
function_block-full_function
[ { "content": "fn is_divisible(&number: &u64) -> bool {\n\n for i in (100..1000).rev() {\n\n if number % i == 0 && (number * 11 / i).to_string().len() == 3 {\n\n return true;\n\n }\n\n }\n\n false\n\n}\n", "file_path": "challenge_004/src/main.rs", "rank": 0, "score":...
Rust
system-node/overseer/overseer-gen/src/lib.rs
elexeum/elexeum-node
19e350dff9b4c790fe6746773007d3250a5a9b2e
#![deny(missing_docs)] #![deny(unused_crate_dependencies)] pub use elexeum_overseer_gen_proc_macro::overlord; #[doc(hidden)] pub use metered; #[doc(hidden)] pub use elexeum_node_primitives::SpawnNamed; #[doc(hidden)] pub use tracing; #[doc(hidden)] pub use async_trait::async_trait; #[doc(hidden)] pub use futures::...
#![deny(missing_docs)] #![deny(unused_crate_dependencies)] pub use elexeum_overseer_gen_proc_macro::overlord; #[doc(hidden)] pub use metered; #[doc(hidden)] pub use elexeum_node_primitives::SpawnNamed; #[doc(hidden)] pub use tracing; #[doc(hidden)] pub use async_trait::async_trait; #[doc(hidden)] pub use futures::...
}
y() { return Poll::Ready(None) } if let Poll::Ready(output) = this.future.poll(ctx) { return Poll::Ready(Some(output)) } Poll::Pending }
function_block-function_prefixed
[]
Rust
src/main.rs
jopdorp/gamedorp
c5ce633f02f450fdc2d2b2390f80ba4add8069c9
#![warn(missing_docs)] #[macro_use] extern crate lazy_static; #[macro_use] extern crate log; extern crate ascii; extern crate num; extern crate sdl2; extern crate time; #[cfg(windows)] extern crate winapi; use std::path::Path; use std::sync::mpsc::{channel, Receiver}; use std::time::Duration; #[cfg(windows)] use ...
#![warn(missing_docs)] #[macro_use] extern crate lazy_static; #[macro_use] extern crate log; extern crate ascii; extern crate num; extern crate sdl2; extern crate time; #[cfg(windows)] extern crate winapi; use std::path::Path; use std::sync::mpsc::{channel, Receiver}; use std::time::Duration; #[cfg(windows)] use ...
CK_FREQUENCY as f64)) as u64; let (tick_tx, tick_rx) = channel(); ::std::thread::spawn(move || { #[cfg(windows)] unsafe { let process = GetCurrentProcess(); SetThreadPriority(process, 0x00010000); } let mut last_time = time::precise_time_ns(); ...
function_block-function_prefixed
[ { "content": "/// Default implementation of write_ram, suitable for most cartridges\n\nfn write_ram(cart: &mut Cartridge, addr: u32, val: u8) {\n\n if let Some(b) = cart.ram_byte_absolute_mut(addr) {\n\n *b = val;\n\n }\n\n}\n\n\n", "file_path": "src/cartridge/models.rs", "rank": 0, "sc...
Rust
HW2/src/board.rs
lyubolp/AI-Course-FMI
0aacbd5f5df6182383da75472df426ad9eebdd65
pub mod board { use rand::Rng; fn remove_duplicate_queen(count: i32) -> i32{ if count == 1{ 0 } else{ count - 1 } } fn get_random_element_from_vec(vec: Vec<usize>) -> usize{ let mut rng = rand::thread_rng(); vec[rng.gen_range(0, v...
pub mod board { use rand::Rng; fn remove_duplicate_queen(count: i32) -> i32{ if count == 1{ 0 } else{ count - 1 } } fn get_random_element_from_vec(vec: Vec<usize>) -> usize{ let mut rng = rand::thread_rng(); vec[rng.gen_range(0, v...
elf.main_diagonal_conflicts[main_diagonal_index] += 1; self.secondary_diagonal_conflicts[secondary_diagonal_index] += 1; } fn move_queen(&mut self, old_row: usize, column: usize, new_row: usize){ self.remove(old_row, column); self.put(new_row, column); } }...
usize) -> usize{ let mut min_conflicts: Vec<usize> = vec!(); let mut min_score: usize = std::usize::MAX; for row in 0..self.size{ let current_score = self.get_conflicts_at(row, column); if current_score < min_score{ min_conflicts...
random
[ { "content": "fn generate_random_cities(size: usize, (min, max): (usize, usize)) -> HashMap<i32, Point>{\n\n let mut result: HashMap<i32, Point> = HashMap::new();\n\n for i in 0..size{\n\n let first = get_random_number_range(min, max);\n\n let second: usize = get_random_number_range(min, max...
Rust
src/parser.rs
nsmryan/nom-ccsds
b12dafe515174fd0db2ccf0d1fac3f60055d2ec8
use bytes::{Bytes, BytesMut}; use primary_header::*; #[derive(Debug, PartialEq, Eq, Copy, Clone)] pub enum CcsdsParserStatus { ValidPacket, NotEnoughBytesForHeader, ExceedsMaxPacketLength, BelowMinPacketLength, NotEnoughBytesPacketLength, I...
use bytes::{Bytes, BytesMut}; use primary_header::*; #[derive(Debug, PartialEq, Eq, Copy, Clone)] pub enum CcsdsParserStatus { ValidPacket, NotEnoughBytesForHeader, ExceedsMaxPacketLength, BelowMinPacketLength, NotEnoughBytesPacketLength, I...
} pub struct CcsdsParser { pub bytes: BytesMut, pub config: CcsdsParserConfig, pub skipped_bytes: usize, reached_end: bool, } /* impl Iterator for CcsdsParser { type Item = BytesMut; fn next(&mut self) -> Option<Self...
None, max_packet_length: None, min_packet_length: None, secondary_header_required: false, sync_bytes: Vec::new(), keep_sync: false, num_header_bytes: 0, keep_header: false, num_footer_bytes: 0, keep_foot...
function_block-function_prefixed
[ { "content": "fn main() {\n\n // If we have the bytes for a primary header from a file, socket, or some other source,\n\n // we can cast it read and write its fields using the PrimaryHeader struct\n\n\n\n // This is a typical CCSDS Primary Header for a command with a secondary header,\n\n // 4 bytes...
Rust
src/builtins/mod.rs
gefjon/phoebe
4a56bcf0c0cfb0b43c525dd8a07591f875375e43
use crate::evaluator::eval_to_reference; use crate::prelude::*; use std::sync::{Once, ONCE_INIT}; static ONCE_BUILTINS: Once = ONCE_INIT; #[macro_use] mod macros; mod error_handling; mod math_builtins; mod namespacing; pub fn make_builtins_once() { ONCE_BUILTINS.call_once(make_builtins); } fn make_builtins()...
use crate::evaluator::eval_to_reference; use crate::prelude::*; use std::sync::{Once, ONCE_INIT}; static ONCE_BUILTINS: Once = ONCE_INIT; #[macro_use] mod macros; mod error_handling; mod math_builtins; mod namespacing; pub fn make_builtins_once() { ONCE_BUILTINS.call_once(make_builtins); } fn make_builtins()...
s)? { let c: GcRef<Cons> = binding_pair.try_convert_into()?; let Cons { car: symbol, cdr, .. } = *c; let c: GcRef<Cons> = cdr.try_convert_into()?; let Cons { car: value, cdr: tail, .. } = *c; if !tail...
function_block-function_prefixed
[ { "content": "pub fn with_global_env<F>(env: GcRef<Namespace>, fun: F) -> Object\n\nwhere\n\n F: FnOnce() -> Object,\n\n{\n\n stack::push(Object::from(global_env()))?;\n\n set_global_env(env);\n\n let res = fun();\n\n set_global_env(unsafe { stack::pop()?.into_unchecked() });\n\n res\n\n}\n\n\...