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/errors.rs
tailhook/rust-quire
f4d711795ae82018f12d81550369c850198a5996
use std::io; use std::fmt; use std::rc::Rc; use std::error::Error as StdError; use std::slice::Iter; use std::path::{Path, PathBuf}; use std::cell::RefCell; use super::tokenizer::{self, Pos}; #[derive(Clone, Debug)] pub struct ErrorPos(String, usize, usize); pub trait AssertSendSync: Send + Sync {} impl AssertSendSy...
use std::io; use std::fmt; use std::rc::Rc; use std::error::Error as StdError; use std::slice::Iter; use std::path::{Path, PathBuf}; use std::cell::RefCell; use super::tokenizer::{self, Pos}; #[derive(Clone, Debug)] pub struct ErrorPos(String, usize, usize); pub trait AssertSendSync: Send + Sync {} impl AssertSendSy...
loc=if let &Some(ref p) = pos { format!("{filename}:{line}:{offset}: ", filename=p.0, line=p.1, offset=p.2) } else { "".to_string() }, err=err) cause(&**err) } } } impl ::serde::...
lay("{filename}:{line}:{offset}: \ Decode error at {path}: {text}", filename=pos.0, line=pos.1, offset=pos.2, path=path, text=msg) } SerdeError(msg: String) { display("{}", msg) } CustomError(pos: Option<ErrorPos>, err: ...
random
[ { "content": "/// The trait every validator implements\n\npub trait Validator: Debug {\n\n fn validate(&self, ast: Ast, err: &ErrorCollector) -> Ast;\n\n fn default(&self, pos: Pos) -> Option<Ast>;\n\n}\n\n\n\n/// Scalar YAML value\n\n///\n\n/// This may be different kind of value:\n\n///\n\n/// * string\...
Rust
tests/raftstore/util.rs
TigerZhang/tikv
99f451b1e79cbe165816c056226bf56ca20f7f48
#![allow(dead_code)] use std::sync::Arc; use std::time::Duration; use std::thread; use tikv::util::{self as tikv_util, logger}; use std::env; use rocksdb::{DB, WriteBatch, Writable}; use tempdir::TempDir; use uuid::Uuid; use protobuf; use super::cluster::{Cluster, Simulator}; use tikv::raftstore::store::*; use tik...
#![allow(dead_code)] use std::sync::Arc; use std::time::Duration; use std::thread; use tikv::util::{self as tikv_util, logger}; use std::env; use rocksdb::{DB, WriteBatch, Writable}; use tempdir::TempDir; use uuid::Uuid; use protobuf; use super::cluster::{Cluster, Simulator}; use tikv::raftstore::store::*; use tik...
pub fn new_get_cmd(key: &[u8]) -> Request { let mut cmd = Request::new(); cmd.set_cmd_type(CmdType::Get); cmd.mut_get().set_key(key.to_vec()); cmd } pub fn new_delete_cmd(key: &[u8]) -> Request { let mut cmd = Request::new(); cmd.set_cmd_type(CmdType::Delete); cmd.mut_delete().set_key(key...
equest::new(); cmd.set_cmd_type(CmdType::Put); cmd.mut_put().set_key(key.to_vec()); cmd.mut_put().set_value(value.to_vec()); cmd }
function_block-function_prefixed
[ { "content": "// Decode region meta key, return the region key and meta suffix type.\n\npub fn decode_region_meta_key(key: &[u8]) -> Result<(u64, u8)> {\n\n if REGION_META_PREFIX_KEY.len() + mem::size_of::<u64>() + mem::size_of::<u8>() != key.len() {\n\n return Err(box_err!(\"invalid region meta key l...
Rust
src/raft/state_machine/master.rs
ShisoftResearch/bifrost
4c6901bd35d59767a4345ce154f4e0268b9ec990
use self::configs::{Configures, RaftMember, CONFIG_SM_ID}; use super::super::*; use super::*; use std::collections::HashMap; use std::error::Error; use std::fmt; use std::fmt::Display; use std::fmt::Formatter; #[derive(Serialize, Deserialize, Debug, Clone)] pub enum ExecError { SmNotFound, FnNotFound, Serv...
use self::configs::{Configures, RaftMember, CONFIG_SM_ID}; use super::super::*; use super::*; use std::collections::HashMap; use std::error::Error; use std::fmt; use std::fmt::Display; use std::fmt::Formatter; #[derive(Serialize, Deserialize, Debug, Clone)] pub enum ExecError { SmNotFound, FnNotFound, Serv...
pub fn register(&mut self, mut smc: SubStateMachine) -> RegisterResult { let id = smc.id(); if id < 2 { return RegisterResult::RESERVED; } if self.subs.contains_key(&id) { return RegisterResult::EXISTED; }; if let Some(snapshot) = self.snapsh...
pub fn new(service_id: u64) -> MasterStateMachine { let msm = MasterStateMachine { subs: HashMap::new(), snapshots: HashMap::new(), configs: Configures::new(service_id), }; msm }
function_block-function_prefix_line
[ { "content": "pub fn read_u64_head(mut data: BytesMut) -> (u64, BytesMut) {\n\n let num = data.get_u64_le();\n\n (num, data)\n\n}\n\n\n\nimpl Server {\n\n pub fn new(address: &String) -> Arc<Server> {\n\n Arc::new(Server {\n\n services: ObjectMap::with_capacity(16),\n\n add...
Rust
crates/nu_plugin_selector/src/selector.rs
nushell/nushell
07e05ef183c790e9d76db4891f3eb6e26cba0a6e
use crate::Table; use nipper::Document; use nu_protocol::{value::StringExt, Primitive, TaggedDictBuilder, UntaggedValue, Value}; use nu_source::Tag; pub struct Selector { pub query: String, pub tag: Tag, pub as_html: bool, pub attribute: String, pub as_table: Value, pub inspect: bool, } impl S...
use crate::Table; use nipper::Document; use nu_protocol::{value::StringExt, Primitive, TaggedDictBuilder, UntaggedValue, Value}; use nu_source::Tag; pub struct Selector { pub query: String, pub tag: Tag, pub as_html: bool, pub attribute: String, pub as_table: Value, pub inspect: bool, } impl S...
} impl Default for Selector { fn default() -> Self { Self::new() } } pub fn begin_selector_query(input_html: String, selector: &Selector) -> Vec<Value> { if !selector.as_table.value.is_string() { retrieve_tables(input_html.as_str(), &selector.as_table, selector.inspect) } else { ...
pub fn new() -> Selector { Selector { query: String::new(), tag: Tag::unknown(), as_html: false, attribute: String::new(), as_table: Value::new( UntaggedValue::Primitive(Primitive::String("".to_string())), Tag::unknown()...
function_block-full_function
[ { "content": "pub fn from_yaml_string_to_value(s: String, tag: impl Into<Tag>) -> Result<Value, ShellError> {\n\n let tag = tag.into();\n\n\n\n let mut documents = vec![];\n\n\n\n for document in serde_yaml::Deserializer::from_str(&s) {\n\n let v: serde_yaml::Value = serde_yaml::Value::deseriali...
Rust
capsules/src/net/network_capabilities.rs
mcy/tock
4a7d2bb5b8c7ef32c93234f00671b454cb572bde
use crate::net::ipv6::ip_utils::IPAddr; const MAX_ADDR_SET_SIZE: usize = 8; const MAX_PORT_SET_SIZE: usize = 8; use kernel::capabilities::NetworkCapabilityCreationCapability; #[derive(Debug, Clone, Copy, PartialEq)] pub enum AddrRange { Any, NoAddrs, AddrSet([IPAddr; MAX_ADDR_SET_SIZE]), Addr(IPAd...
use crate::net::ipv6::ip_utils::IPAddr; const MAX_ADDR_SET_SIZE: usize = 8; const MAX_PORT_SET_SIZE: usize = 8; use kernel::capabilities::NetworkCapabilityCreationCapability; #[derive(Debug, Clone, Copy, PartialEq)] pub enum AddrRange { Any, NoAddrs, AddrSet([IPAddr; MAX_ADDR_SET_SIZE]), Addr(IPAd...
} } } } #[derive(Debug, Clone, Copy, PartialEq)] pub enum PortRange { Any, NoPorts, PortSet([u16; MAX_PORT_SET_SIZE]), Range(u16, u16), Port(u16), } impl PortRange { pub fn is_port_valid(&self, port: u16) -> bool { match self { PortRange::Any => tru...
if &allowed_addr.0[0..full_bytes] != &addr.0[0..full_bytes] { false } else { allowed_addr.0[full_bytes] >> (8 - remainder_bits) == allowed_addr.0[full_bytes] >> (8 - remainder_bits) }
if_condition
[ { "content": "/// Verifies that the prefixes of the two buffers match, where the length of the\n\n/// prefix is given in bits\n\npub fn matches_prefix(buf1: &[u8], buf2: &[u8], prefix_len: u8) -> bool {\n\n let full_bytes = (prefix_len / 8) as usize;\n\n let remaining_bits = prefix_len % 8;\n\n let byt...
Rust
main/src/player/playerhuman.rs
openschafkopf/openschafkopf
30b4b0c0d0404cdc4b56f70bfe589542587f53e3
use crate::ai::{*, gametree::*}; use crate::game::*; use crate::player::*; use crate::primitives::*; use crate::rules::{ruleset::*, *}; use crate::skui; use crate::util::*; use std::sync::mpsc; pub struct SPlayerHuman { pub ai : SAi, } fn choose_ruleset_or_rules<'t, T>( hand: &SHand, vect : &'t [T], f...
use crate::ai::{*, gametree::*}; use crate::game::*; use crate::player::*; use crate::primitives::*; use crate::rules::{ruleset::*, *}; use crate::skui; use crate::util::*; use std::sync::mpsc; pub struct SPlayerHuman { pub ai : SAi, } fn choose_ruleset_or_rules<'t, T>( hand: &SHand, vect : &'t [T], f...
fn ask_for_card(&self, game: &SGame, txcard: mpsc::Sender<SCard>) { skui::print_stichseq(unwrap!(game.current_playable_stich().current_playerindex()), &game.stichseq); let epi = unwrap!(game.which_player_can_do_something()).0; let veccard = { let mut veccard = game.ahand[epi].c...
e]; unwrap!(txb_doubling.send(*skui::ask_for_alternative( &ab_doubling, &skui::choose_alternative_from_list_key_bindings(), |_| true, |ncwin, i_b_doubling_chosen, ob_doubling_suggest| { assert!(ob_doubling_suggest.is_none()); ...
function_block-function_prefixed
[ { "content": "pub fn player_table_ahand(epi_self: EPlayerIndex, ahand: &EnumMap<EPlayerIndex, SHand>, rules: &dyn TRules, fn_border: impl Fn(SCard)->bool) -> String {\n\n format!(\n\n \"<td>{}</td>\\n\",\n\n player_table(epi_self, |epi| {\n\n let mut veccard = ahand[epi].cards().clon...
Rust
src/desktop.rs
Rexagon/dsdmona
d0d5cdf6c08073ac7b557445b11f8be0ec0d4e08
use std::fs::File; use std::io::{BufRead, BufReader}; use std::os::unix::fs::PermissionsExt; use std::path::Path; use std::str::FromStr; use anyhow::{anyhow, Result}; use libc::uid_t; use walkdir::WalkDir; use crate::user::{self, User}; const XORG_SESSIONS_PATH: &str = "/usr/share/xsessions"; const LAST_SESSION_PATH...
use std::fs::File; use std::io::{BufRead, BufReader}; use std::os::unix::fs::PermissionsExt; use std::path::Path; use std::str::FromStr; use anyhow::{anyhow, Result}; use libc::uid_t; use walkdir::WalkDir; use crate::user::{self, User}; const XORG_SESSIONS_PATH: &str = "/usr/share/xsessions"; const LAST_SESSION_PATH...
Some(LastSession { uid: user.uid(), exec: exec.to_owned(), env, }) } pub fn set_last_session(usr: &User, desktop: &Desktop) -> Result<()> { let previous_user = user::get_current(); user::set_fs_user(usr); let path = usr.home_dir().join(LAST_SESSION_PATH); std::fs::cr...
let env = match Environment::from_str(env) { Ok(env) => env, Err(e) => { eprintln!("Failed to parse last session: {}", e); return None; } };
assignment_statement
[ { "content": "fn define_env(user: &User, desktop: &Desktop) -> Result<Env> {\n\n let runtime_dir = format!(\"/run/user/{}\", user.uid());\n\n\n\n let mut env: HashMap<&'static str, OsString> = HashMap::new();\n\n\n\n env.insert(\"HOME\", user.home_dir().into());\n\n env.insert(\"PWD\", user.home_dir...
Rust
pong/pong3/src/main.rs
TheFern2/gd50-rs
0f610a3380b6f64508e6788be6785dec2747cf04
extern crate sfml; use sfml::graphics::{ CircleShape, Color, Font, RectangleShape, RenderTarget, RenderWindow, Shape, Text, Transformable, }; use sfml::system::{Clock, SfStrConv, Vector2f}; use sfml::window::{Event, Key, Style}; /* * Pong 3: The Paddle Update, paddle movement added, and scores. */ fn main() {...
extern crate sfml; use sfml::graphics::{ CircleShape, Color, Font, RectangleShape, RenderTarget, RenderWindow, Shape, Text, Transformable, }; use sfml::system::{Clock, SfStrConv, Vector2f}; use sfml::window::{Event, Key, Style}; /* * Pong 3: The Paddle Update, paddle movement added, and scores. */ fn main() {...
GHT as f32 - 5.) { right_paddle.move_((0., paddle_speed * delta_time)); } } window.clear(Color::BLACK); window.draw(&welcome); window.draw(&player_1_score_text); window.draw(&player_2_score_text); window.draw(&right_paddle); ...
bled(true); let font = Font::from_file("res/font.ttf").unwrap(); let mut welcome = Text::default(); welcome.set_font(&font); welcome.set_fill_color(Color::WHITE); welcome.set_character_size(30); welcome.set_string("Hello Pong!"); welcome.set_position((WINDOW_WIDTH as f32 / 2. - 100., 40.));...
random
[ { "content": "fn on_bounce(ball_speed: &mut f32) {\n\n *ball_speed += 16.0;\n\n}\n", "file_path": "pong/pong4/src/main.rs", "rank": 0, "score": 54541.85941941291 }, { "content": "fn main() {\n\n \n\n const WINDOW_WIDTH:u32 = 1280;\n\n const WINDOW_HEIGHT:u32 = 720;\n\n\n\n let...
Rust
src/test/instruction_tests/instr_vphaddsw.rs
ftilde/rust-x86asm
f6584b8cfe8e75d978bf7b83a67c69444fd3f161
use instruction_def::*; use test::run_test; use Operand::*; use Reg::*; use RegScale::*; use RegType::*; use {BroadcastMode, Instruction, MaskReg, MergeMode, Mnemonic, OperandSize, Reg, RoundingMode}; #[test] fn vphaddsw_1() { run_test( &Instruction { mnemonic: Mnemonic::VPHADDSW, o...
use instruction_def::*; use test::run_test; use Operand::*; use Reg::*; use RegScale::*; use RegType::*; use {BroadcastMode, Instruction, MaskReg, MergeMode, Mnemonic, OperandSize, Reg, RoundingM
nic::VPHADDSW, operand1: Some(Direct(YMM6)), operand2: Some(Direct(YMM3)), operand3: Some(IndirectScaledIndexedDisplaced( RAX, RAX, Four, 47903948, Some(OperandSize::Ymmword), None, ...
ode}; #[test] fn vphaddsw_1() { run_test( &Instruction { mnemonic: Mnemonic::VPHADDSW, operand1: Some(Direct(XMM6)), operand2: Some(Direct(XMM5)), operand3: Some(Direct(XMM0)), operand4: None, lock: false, rounding_mode: No...
random
[ { "content": "fn encode64_helper2(mnemonic: Mnemonic, operand1: Operand, operand2: Operand, expected: &Vec<u8>) {\n\n let instr = Instruction {\n\n mnemonic: mnemonic,\n\n operand1: Some(operand1),\n\n operand2: Some(operand2),\n\n operand3: None,\n\n operand4: None,\n\n ...
Rust
r1cs/src/lib.rs
sunhuachuang/ckb-zkp
4031a458a301a87cfdea9f6c662cc8a837d6ae51
#![cfg_attr(not(feature = "std"), no_std)] #![warn(unused, future_incompatible, nonstandard_style, rust_2018_idioms)] #![allow(clippy::op_ref, clippy::suspicious_op_assign_impl)] #![cfg_attr(not(use_asm), forbid(unsafe_code))] #![cfg_attr(use_asm, feature(llvm_asm))] #![cfg_attr(use_asm, deny(unsafe_code))] #[cfg(not...
#![cfg_attr(not(feature = "std"), no_std)] #![warn(unused, future_incompatible, nonstandard_style, rust_2018_idioms)] #![allow(clippy::op_ref, clippy::suspicious_op_assign_impl)] #![cfg_attr(not(use_asm), forbid(unsafe_code))] #![cfg_attr(use_asm, feature(llvm_asm))] #![cfg_attr(use_asm, deny(unsafe_code))] #[cfg(not...
()) } #[inline] fn serialized_size(&self) -> usize { 1 + 0usize.serialized_size() } #[inline] fn serialize_uncompressed<W: io::Write>( &self, mut writer: W, ) -> Result<(), SerializationError> { match self { Index::Input(u) => { 0...
serialize(&mut writer)?; u.serialize(&mut writer)?; } Index::Aux(u) => { 1u8.serialize(&mut writer)?; u.serialize(&mut writer)?; } } Ok(
function_block-random_span
[ { "content": "/// Performs a 1-bit window table lookup. `bits` is in\n\n/// little-endian order. constants is 1D-coords.\n\npub fn lookup1_x<F, CS>(mut cs: CS, b: &Boolean, c: &[F]) -> Result<AllocatedFr<F>, SynthesisError>\n\nwhere\n\n F: PrimeField,\n\n CS: ConstraintSystem<F>,\n\n{\n\n assert_eq!(c....
Rust
src/lib.rs
mtsr/tabbycat
b5b70524657650b0babe32029f4caf14815edfe2
pub use graph::*; mod graph; #[cfg(feature = "attributes")] pub mod attributes; #[cfg(test)] mod test { #[cfg(feature = "attributes")] use crate::attributes::*; use crate::Compass::NorthEast; use crate::Identity; #[test] fn codegen_compass() { use crate::Compass::*; assert_...
pub use graph::*; mod graph; #[cfg(feature = "attributes")] pub mod attributes; #[cfg(test)] mod test { #[cfg(feature = "attributes")] use crate::attributes::*; use crate::Compass::NorthEast; use crate::Identity; #[test] fn codegen_compass() { use crate::Compass::*; assert_...
(1), None))) .build() .unwrap(); println!("{:#}", g); Ok(()) } }
(Identity::from(3), None) .arrow_to_node(Identity::from(4), None) .arrow_to_node(Identity::from(5), None) .arrow_to_node(Identity::from(6), None) .add_attribute(Identity::id("color")?, Identity::id("purple")?...
random
[ { "content": "pub fn arrowtail<'a>(value: ArrowShape) -> AttrPair<'a> {\n\n (Identity::String(\"arrowtail\"), Identity::ArrowName([Some(arrow_str(value)), None, None, None]))\n\n}\n\n\n", "file_path": "src/attributes.rs", "rank": 0, "score": 62798.525694865566 }, { "content": "pub fn arro...
Rust
src/registry.rs
ereslibre/sigstore-rs
9a4447cdaee233eea1ccbb3e2a5868555e99c4bb
use anyhow::Result; use async_trait::async_trait; use std::convert::From; pub enum Auth { Anonymous, Basic(String, String), } impl From<&Auth> for oci_distribution::secrets::RegistryAuth { fn from(auth: &Auth) -> Self { match auth { Auth::Anonymous => oci_distribution::secr...
use anyhow::Result; use async_trait::async_trait; use std::convert::From; pub enum Auth { Anonymous, Basic(String, String), } impl From<&Auth> for oci_distribution::secrets::RegistryAuth { fn from(auth: &Auth) -> Self {
} } #[derive(Debug, Clone, PartialEq)] pub enum ClientProtocol { #[allow(missing_docs)] Http, #[allow(missing_docs)] Https, #[allow(missing_docs)] HttpsExcept(Vec<String>), } impl Default for ClientProtocol { fn default() -> Self { ClientProtocol::Https } } impl From<Clie...
match auth { Auth::Anonymous => oci_distribution::secrets::RegistryAuth::Anonymous, Auth::Basic(username, pass) => { oci_distribution::secrets::RegistryAuth::Basic(username.clone(), pass.clone()) } }
if_condition
[]
Rust
src/lib.rs
AlexandruGG/rust-game-of-life-wasm-final
33eb8a80a2cbeb1da007dbee5c375a0c0ddc23cc
mod utils; extern crate fixedbitset; extern crate js_sys; use crate::utils::Timer; use fixedbitset::FixedBitSet; use wasm_bindgen::prelude::*; #[cfg(feature = "wee_alloc")] #[global_allocator] static ALLOC: wee_alloc::WeeAlloc = wee_alloc::WeeAlloc::INIT; #[wasm_bindgen] pub struct Universe { width: u32, he...
mod utils; extern crate fixedbitset; extern crate js_sys; use crate::utils::Timer; use fixedbitset::FixedBitSet; use wasm_bindgen::prelude::*; #[cfg(feature = "wee_alloc")] #[global_allocator] static ALLOC: wee_alloc::WeeAlloc = wee_alloc::WeeAlloc::INIT; #[wasm_bindgen] pub struct Universe { width: u32, he...
pub fn toggle_cell(&mut self, row: u32, column: u32) { let idx = self.get_index(row, column); self.cells.set(idx, !self.cells[idx]); } pub fn clear_cells(&mut self) { self.cells.clear(); } pub fn set_width(&mut self, width: u32) { self.width = width; self....
false, 3) => true, (otherwise, _) => otherwise, }, ); } } } let _timer = Timer::new("free old cells"); self.cells = next; }
function_block-function_prefix_line
[ { "content": "pub fn set_panic_hook() {\n\n // When the `console_error_panic_hook` feature is enabled, we can call the\n\n // `set_panic_hook` function at least once during initialization, and then\n\n // we will get better error messages if our code ever panics.\n\n //\n\n // For more details se...
Rust
src/climb.rs
fgebhart/sportgems
91acce395234386090e9792c67880f1f16d7153b
use crate::dtypes; use crate::errors; use crate::fit_reader; use crate::gem_finder; use crate::math; fn get_climb( section: &dtypes::WindowSection, altitudes: &dtypes::Altitudes, times: &dtypes::Times, ) -> f64 { let gained_altitude_in_section: f64 = get_gained_altitude_in_section( &altitudes.v...
use crate::dtypes; use crate::errors; use crate::fit_reader; use crate::gem_finder; use crate::math; fn get_climb( section: &dtypes::WindowSection, altitudes: &dtypes::Altitudes, times: &dtypes::Times, ) -> f64 { let gained_altitude_in_section: f64 = get_gained_altitude_in_section( &altitudes.v...
_same() { let altitudes = vec![1., 1., 1., 1., 1.]; let result = get_gained_altitude_in_section(&altitudes, 0, altitudes.len()); let expected = 0.0; assert_eq!(expected, result); } #[test] fn test_get_gained_altitude_in_section_len_of_1() { let altitudes = v...
#[test] fn test_get_gained_altitude_in_section_all_values() { let altitudes = vec![1.0, 2.0, 3.0, 4.0, 5.0]; let result = get_gained_altitude_in_section(&altitudes, 0, altitudes.len()); let expected = 4.0; assert_eq!(expected, result); } #[test] fn test_get_gained_altit...
random
[ { "content": "pub fn get_distance(distances: &Vec<f64>, start: usize, end: usize) -> f64 {\n\n distances[end] - distances[start + 1]\n\n}\n\n\n", "file_path": "src/gem_finder.rs", "rank": 1, "score": 223377.9179034603 }, { "content": "pub fn climb_equation(gained_altitude: &f64, time: &f6...
Rust
libslide/src/bignum/complex.rs
timothycobrien/slide
7cf30643a4325c6eab7591bb2361c3c16c111ba9
#![allow(clippy::suspicious_arithmetic_impl)] #![allow(dead_code)] use std::convert::From; use std::convert::TryFrom; use std::fmt; use std::ops; static INPUT_ERR_MSG: &str = "Input is not valid"; const TOLERANCE: f64 = 1E-12; #[derive(Clone, Copy, Debug, Default)] pub struct Complex { real: f64, imag: f64, }...
#![allow(clippy::suspicious_arithmetic_impl)] #![allow(dead_code)] use std::convert::From; use std::convert::TryFrom; use std::fmt; use std::ops; static INPUT_ERR_MSG: &str = "Input is not valid"; const TOLERANCE: f64 = 1E-12; #[derive(Clone, Copy, Debug, Default)] pub struct Complex { real: f64, imag: f64, }...
let rhs: Vec<&str> = v[2].split('i').collect(); match rhs[0].parse::<f64>() { Ok(val) => imag = val * is_neg, Err(_) => return Err(INPUT_ERR_MSG), } Ok(Complex { real, imag }) } } impl From<u8> for Complex { fn from(item: u8) -> Self { Complex { ...
match v[1] { "+" => is_neg = 1.0, "-" => is_neg = -1.0, _ => return Err(INPUT_ERR_MSG), }
if_condition
[ { "content": "// note we cannot use the above recast since we have a user defined type with\n\n// an undefined way of storing its memory\n\n// prereqs: tryfrom(or from) is implemented for type coercion and default and clone are implemented\n\npub fn recast_user_vec<T, U>(v: Vec<T>) -> Result<Vec<U>, &'static st...
Rust
api/io_str/src/read.rs
ItsDoot/minecrevy
f9de8973dbc99e67c24e6b7fe3687fe9c6f5b5fa
use std::collections::HashMap; use std::hash::{BuildHasher, Hash}; use std::io::{self, ErrorKind, Read}; use std::mem::MaybeUninit; use uuid::Uuid; use minecrevy_io_buf::{RawPacket, ReadMinecraftExt}; pub use minecrevy_io_str_derive::McRead; use crate::options::*; pub trait McRead: Sized { type Options: Cl...
use std::collections::HashMap; use std::hash::{BuildHasher, Hash}; use std::io::{self, ErrorKind, Read}; use std::mem::MaybeUninit; use uuid::Uuid; use minecrevy_io_buf::{RawPacket, ReadMinecraftExt}; pub use minecrevy_io_str_derive::McRead; use crate::options::*; pub trait McRead: Sized { type Options: Cl...
)) } } impl<A: McRead, B: McRead, C: McRead, D: McRead, E: McRead> McRead for (A, B, C, D, E) { type Options = (A::Options, B::Options, C::Options, D::Options, E::Options); fn read<R: Read>(mut reader: R, (a, b, c, d, e): Self::Options) -> io::Result<Self> { Ok(( A::read(&mut read...
T: McRead, const N: usize> McRead for [T; N] { type Options = ArrayOptions<T::Options>; fn read<R: Read>(mut reader: R, options: Self::Options) -> io::Result<Self> { let mut result = MaybeUninit::<T>::uninit_array::<N>(); for val in &mut result { val.write(T::read(&mut reader, optio...
random
[ { "content": "/// Returns the specified byte slice as a hexdump\n\npub fn hex_string(bytes: &[u8]) -> String {\n\n let mut result = bytes.iter()\n\n .fold(String::new(), |mut a, b| {\n\n use std::fmt::Write;\n\n write!(a, \"{:02X} \", b).unwrap();\n\n a\n\n });\...
Rust
fracture_core/src/commands.rs
Fracture-Labs/Fracture
8a215036085ad4ff3dbe1d6b1e4b6fff14bc62b6
use umbral_pre::*; use crate::{ cli::{DecryptArgs, EncryptArgs, GrantArgs, PreArgs}, ipfs_io::{self}, }; pub fn new_account() -> (SecretKey, PublicKey) { let sk = SecretKey::random(); let pk = sk.public_key(); println!("private key: {:x}", sk.to_secret_array().as_secret()); println!("public k...
use umbral_pre::*; use crate::{ cli::{DecryptArgs, EncryptArgs, GrantArgs, PreArgs}, ipfs_io::{self}, }; pub fn new_account() -> (SecretKey, PublicKey) { let sk = SecretKey::random(); let pk = sk.public_key(); println!("private key: {:x}", sk.to_secret_array().as_secret()); println!("public k...
, ciphertext.to_vec()) } pub fn grant(grant_args: GrantArgs) -> (PublicKey, Box<[VerifiedKeyFrag]>) { let signer = umbral_pre::Signer::new(SecretKey::random()); let verifying_pk = signer.verifying_key(); println!("verifying public key: {:x}", verifying_pk.to_array()); let verified_kfrags = gener...
pt_args.plaintext).unwrap(); println!("capsule: {:x}", capsule.to_array()); println!("ciphertext: {}", hex::encode(ciphertext.clone())); (capsule.to_array().to_vec()
function_block-random_span
[ { "content": "// TODO: get umbral_pre to expose traits for implementation.\n\npub fn sk_to_bytes(sk: SecretKey) -> Vec<u8> {\n\n sk.to_secret_array().as_secret().to_vec()\n\n}\n\n\n", "file_path": "fracture_core/src/helpers.rs", "rank": 2, "score": 129766.54422503398 }, { "content": "pub ...
Rust
src/graphql/schema/mod.rs
MonsieurMan/qlc
98e285b9af728eff2d078a04a4ddb5e53b110785
use json::*; use std::collections::HashMap; use std::io::Read; mod json; pub type FieldsLookup = HashMap<String, Field>; pub type Documentation = Option<String>; #[derive(Debug)] pub enum Error { MissingTypeOfForList, MissingTypeOfForNonNull, MissingNameForField, UnknownType(String, String), En...
use json::*; use std::collections::HashMap; use std::io::Read; mod json; pub type FieldsLookup = HashMap<String, Field>; pub type Documentation = Option<String>; #[derive(Debug)] pub enum Error { MissingTypeOf
lt<Self, Error> { let documentation = json.description.clone(); let definition = match json.kind.as_ref() { "OBJECT" => { let fields = get_fields_for_complex(json, true); let object_type = ObjectType { fields }; TypeDefinition::Object(object_ty...
ForList, MissingTypeOfForNonNull, MissingNameForField, UnknownType(String, String), EnumMissingValues(String), UnionMissingTypes(String), JSONParseError(serde_json::Error), } #[derive(Debug, Clone)] pub enum ScalarType { Custom(String), Boolean, String, Float, Int, ID, }...
random
[ { "content": "fn enum_def_from_type(name: &str, documentation: &Documentation, enum_type: &EnumType) -> String {\n\n let doc_comment = compile_documentation(documentation, 0);\n\n let values = enum_type\n\n .possible_values\n\n .iter()\n\n .map(|value| format!(\" {} = \\\"{}\\\",\", ...
Rust
src/gl/surface.rs
nstoddard/gl-wrapper
a6d6567807dd789c7d6b4fcfded81c257dc0d3e9
use cgmath::*; use glow::HasContext; #[cfg(target_arch = "wasm32")] use web_sys::HtmlCanvasElement; #[cfg(not(target_arch = "wasm32"))] use crate::glfw::*; #[cfg(not(target_arch = "wasm32"))] use std::path::*; use super::context::*; use super::framebuffer::*; use super::rect::*; pub trait Surface { #[doc(h...
use cgmath::*; use glow::HasContext; #[cfg(target_arch = "wasm32")] use web_sys::HtmlCanvasElement; #[cfg(not(target_arch = "wasm32"))] use crate::glfw::*; #[cfg(not(target_arch = "wasm32"))] use std::path::*; use super::context::*; use super::framebuffer::*; use super::rect::*; pub trait Surface { #[doc(h...
} #[cfg(target_arch = "wasm32")] pub struct ScreenSurface { viewport: Rect<i32>, size: Vector2<u32>, canvas: HtmlCanvasElement, id: FramebufferId, } #[cfg(target_arch = "wasm32")] impl ScreenSurface { pub(crate) fn new(canvas: HtmlCanvasElement) -> Self { let viewport = Rect::new( ...
fn color(&self) -> Option<[f32; 4]> { match self { ClearBuffer::Color(color) => Some(*color), _ => None, } }
function_block-full_function
[ { "content": "pub fn compute_ortho_matrix(surface: &(impl Surface + ?Sized)) -> Matrix4<f32> {\n\n let surface_size = surface.size();\n\n Matrix4::from_nonuniform_scale(1.0, -1.0, 1.0)\n\n * ortho(0.0, surface_size.x as f32, 0.0, surface_size.y as f32, 0.0, 1.0)\n\n}\n\n\n\nimpl Draw2d {\n\n ///...
Rust
src/utils.rs
namuyan/bc4py_core
6386fcbc8af53c1feabdfd07570155ab60f83bab
use bigint::U256; use ripemd160::Ripemd160; use sha2::{Digest, Sha256}; use std::time::{SystemTime, UNIX_EPOCH}; type Address = [u8; 21]; #[inline] pub fn u32_to_bytes(i: u32) -> [u8; 4] { i.to_le_bytes() } #[inline] pub fn f32_to_bytes(i: f32) -> [u8; 4] { i.to_le_bytes() } #[inline] pub fn u64_to_bytes(i:...
use bigint::U256; use ripemd160::Ripemd160; use sha2::{Digest, Sha256}; use std::time::{SystemTime, UNIX_EPOCH}; type Address = [u8; 21]; #[inline] pub fn u32_to_bytes(i: u32) -> [u8; 4] { i.to_le_bytes() } #[inline] pub fn f32_to_bytes(i: f32) -> [u8; 4] { i.to_le_bytes() } #[inline] pub fn u64_to_bytes(i:...
#[test] fn test_merkleroot_hash() { let hashs = vec![ hex_to_u256_reversed("8c14f0db3df150123e6f3dbbf30f8b955a8249b62ac1d1ff16284aefa3d06d87"), hex_to_u256_reversed("fff2525b8931402dd09222c50775608f75787bd2b87e56995a7bdd30f79702c4"), hex_to_u256_reversed("6...
fn hex_to_u256_reversed(s: &str) -> U256 { let mut vec = hex::decode(s).unwrap(); vec.reverse(); U256::from(vec.as_slice()) }
function_block-full_function
[ { "content": "pub fn string2addr(string: &str) -> Result<Address, Error> {\n\n // return [ver+identifier] bytes\n\n match addr2params(string) {\n\n Ok((ver, identifier)) => {\n\n let mut addr = [ver; 21];\n\n write_slice(&mut addr[1..21], &identifier);\n\n Ok(addr)\...
Rust
src/day23.rs
Observer42/advent-of-code-2017
e8cb62e6a9bf0eb4b947097d73a9ba84332638b2
use std::collections::{HashMap, HashSet}; use std::fs::File; use std::io::Read; use std::io::Result; pub fn solve() -> Result<()> { let mut file = File::open("input/23.txt")?; let mut raw_input = String::new(); file.read_to_string(&mut raw_input)?; let instructions = parse_input(&raw_input); prin...
use std::collections::{HashMap, HashSet}; use std::fs::File; use std::io::Read; use std::io::Result; pub fn solve() -> Result<()> { let mut file = File::open("input/23.txt")?; let mut raw_input = String::new(); file.read_to_string(&mut raw_input)?; let instructions = parse_input(&raw_input); prin...
}
fn parse_from(input: &str) -> Instruction { let cmd = &input[0..3]; let mut it = input[3..].split_whitespace(); let arg0_str = it.next().unwrap(); let reg = arg0_str.chars().nth(0).unwrap(); let arg0 = Arg::parse_from(arg0_str); let arg1 = Arg::parse_from(it.next().unwrap...
function_block-full_function
[ { "content": "fn solve_second(processes: Vec<Process>, root: &str) -> i32 {\n\n let tree = generate_weight_tree(processes, root);\n\n let mut node = root;\n\n let mut fix = 0;\n\n loop {\n\n if let Some(ref children) = tree[node].1 {\n\n match children.len() {\n\n 2 ...
Rust
devices/src/legacy/pl031.rs
ican2002/stratorvirt
b8e9b675ae0fac9e359a2096cc818f92c4f11c30
use std::sync::{Arc, Mutex}; use std::time::{Instant, SystemTime, UNIX_EPOCH}; use acpi::AmlBuilder; use address_space::GuestAddress; use byteorder::{ByteOrder, LittleEndian}; use migration::{DeviceStateDesc, FieldDesc, MigrationHook, MigrationManager, StateTransfer}; use sysbus::{SysBus, SysBusDevOps, SysBusDevType...
use std::sync::{Arc, Mutex}; use std::time::{Instant, SystemTime, UNIX_EPOCH}; use acpi::AmlBuilder; use address_space::GuestAddress; use byteorder::{ByteOrder, LittleEndian}; use migration::{DeviceStateDesc, FieldDesc, MigrationHook, MigrationManager, StateTransfer}; use sysbus::{SysBus, SysBusDevOps, SysBusDevType...
data.len() { 1 => data[0] = value as u8, 2 => LittleEndian::write_u16(data, value as u16), 4 => LittleEndian::write_u32(data, value as u32), _ => {} } true } fn write(&mut self, data: &[u8], _base: GuestAddress, offset: u64) -> bool { ...
: u64 = 0x04; const RTC_LR: u64 = 0x08; const RTC_CR: u64 = 0x0c; const RTC_IMSC: u64 = 0x10; const RTC_RIS: u64 = 0x14; const RTC_MIS: u64 = 0x18; const RTC_ICR: u64 = 0x1c; const RTC_PERIPHERAL_ID: [u8; 8] = [0x31, 0x10, 0x14, 0x00, 0x0d, 0xf0, 0x05, 0xb1]; #[allow(clippy::upper_case_acronyms)] #[repr(C)] #[...
random
[ { "content": "fn write_buf_mem(buf: &[u8], hva: u64) -> Result<()> {\n\n let mut slice = unsafe { std::slice::from_raw_parts_mut(hva as *mut u8, buf.len()) };\n\n (&mut slice)\n\n .write(buf)\n\n .chain_err(|| format!(\"Failed to write buf(hva:{})\", hva))?;\n\n\n\n Ok(())\n\n}\n\n\n", ...
Rust
src/concern.rs
bruxisma/outcome
57c4f5383e9f9ea99fdd54832cb10d67a549c716
use core::{ fmt::Debug, ops::{Deref, DerefMut}, }; use crate::{iter::*, private::panic}; #[must_use = "This Concern might be a `Mistake`, which should be handled"] #[derive(Copy, PartialEq, PartialOrd, Eq, Ord, Debug, Hash)] pub enum Concern<S, M> { Success(S), Mistake(M), } impl<S, M> Concern<S, M> { ...
use core::{ fmt::Debug, ops::{Deref, DerefMut}, }; use crate::{iter::*, private::panic}; #[must_use = "This Concern might be a `Mistake`, which should be handled"] #[derive(Copy, PartialEq, PartialOrd, Eq, Ord, Debug, Hash)] pub enum Concern<S, M> { Success(S), Mistake(M), } impl<S, M> Concern<S, M> { ...
h *self { Self::Success(ref mut value) => Concern::Success(value), Self::Mistake(ref mut value) => Concern::Mistake(value), } } #[inline] pub fn iter(&self) -> Iter<'_, S> { Iter { inner: self.as_ref().success(), } } ...
:Success(ref value) => Concern::Success(value), Self::Mistake(ref value) => Concern::Mistake(value), } } #[inline] pub fn as_mut(&mut self) -> Concern<&mut S, &mut M> { matc
random
[ { "content": "#[inline(never)]\n\n#[track_caller]\n\n#[cold]\n\npub fn panic(method: &str, variant: &str, error: &dyn Debug) -> ! {\n\n panic!(\"Called `{}` on a `{}` value: {:?}\", method, variant, error);\n\n}\n\n\n", "file_path": "src/private.rs", "rank": 0, "score": 68242.56145678827 }, { ...
Rust
src/address_map/mod.rs
ncatelli/mainspring
e46c832954fb5c3c90318196329d82ee441a8f6f
use std::collections::HashMap; use std::fmt; use std::{cmp::Eq, fmt::Debug, hash::Hash, ops::RangeInclusive}; pub mod memory; pub mod page; #[cfg(test)] mod tests; type WriteError = String; type RegistrationError = String; pub trait SafeAddressable<O, V> where Self: Addressable<O, V>, O: Into<usize> + Debug...
use std::collections::HashMap; use std::fmt; use std::{cmp::Eq, fmt::Debug, hash::Hash, ops::RangeInclusive}; pub mod memory; pub mod page; #[cfg(test)] mod tests; type WriteError = String; type RegistrationError = String; pub trait SafeAddressable<O, V> where Self: Addressable<O, V>, O: Into<usize> + Debug...
fn write(&mut self, addr: O, value: V) -> Result<V, String> { let range = self .inner .keys() .cloned() .find(|key| key.contains(&addr)) .ok_or(format!("address space {:?} unallocated", addr))?; let am = self .inner ...
fn read(&self, addr: O) -> V { self.inner .keys() .filter(|key| key.contains(&addr)) .map(|r| self.inner.get(r)) .flatten() .next() .map_or(<V>::default(), |a| a.read(addr)) }
function_block-full_function
[ { "content": "#[test]\n\nfn should_fail_when_registering_overlapping_address_space() {\n\n let am = u16_address_map!(0..=0x7fff, Memory::<ReadOnly, u16, u8>::new(0, 0x7fff)).unwrap();\n\n assert!(am\n\n .register(\n\n 0..=0x7fff,\n\n Box::new(Memory::<ReadOnly, u16, u8>::new(0...
Rust
hoffman/src/recipe.rs
nikolajholck/hoffman
915e1dab35b75ffe41b295387e717db7d802d1da
use std::iter::repeat; use serde_json::Value; use super::*; use combinatorics::*; #[derive(Clone, PartialEq)] pub struct Recipe { pub n: usize, pub m: usize, pub map: NdArray<Orientation> } impl Recipe { pub fn new(n: usize, m: usize) -> Recipe { let shape = repeat(n).take(m).collect(); ...
use std::iter::repeat; use serde_json::Value; use super::*; use combinatorics::*; #[derive(Clone, PartialEq)] pub struct Recipe { pub n: usize, pub m: usize, pub map: NdArray<Orientation> } impl Recipe { pub fn new(n: usize, m: usize) -> Recipe { let shape = repeat(n).take(m).collect(); ...
symmetries.len() == (2 as usize).pow(self.m as u32) * factorial(self.m) "Invalid number of symmetries."); symmetries } fn symmetry(&self, axis_permutation: &Vec<usize>, axis_directions: &Vec<bool>) -> Recipe { Recipe { n: self.n, m: self.m, map: self.map.map(...
e, false]; let direction_choices = combinations_with_repetition(&directions, self.m); let axis_permutations = permutations(&dims, self.m); for axes in &axis_permutations { for directions in &direction_choices { symmetries.push(self.symmetry(axes, directions)); ...
function_block-random_span
[ { "content": "pub fn factorial(n: usize) -> usize {\n\n if n <= 1 { 1 } else { n * factorial(n - 1) }\n\n}\n", "file_path": "hoffman/src/combinatorics.rs", "rank": 0, "score": 131808.86935276346 }, { "content": "pub fn make_coords(shape: &Shape) -> Vec<Coord> {\n\n let axes: Vec<Vec<us...
Rust
2021/day12/src/main.rs
poszu/advent-of-code
248103609b36978493d7c79da2cf7b7ec0b1bc38
#[macro_use] extern crate multimap; use std::collections::{HashMap, VecDeque}; use multimap::MultiMap; #[derive(Debug, Hash, PartialEq, Eq, Clone, Copy)] enum Cave<'a> { Small(&'a str), Big(&'a str), Start, End, } impl Cave<'_> { fn is_reentrant(&self) -> bool { matches!(self, Cave::Big(_...
#[macro_use] extern crate multimap; use std::collections::{HashMap, VecDeque}; use multimap::MultiMap; #[derive(Debug, Hash, PartialEq, Eq, Clone, Copy)] enum Cave<'a> { Small(&'a str), Big(&'a str), Start, End, } impl Cave<'_> { fn is_reentrant(&self) -> bool { matches!(self, Cave::Big(_...
fn count_paths_v2(&self) -> usize { #[derive(Clone)] struct Path<'a> { cave: Cave<'a>, visited_small_caves: HashMap<Cave<'a>, usize>, } let mut queue = VecDeque::<Path<'a>>::from([Path { cave: Cave::Start, visited_small_caves: HashMa...
d() { paths += 1; continue; } if !adjacent_cave.is_reentrant() && path.contains(adjacent_cave) { continue; } let mut new_path = path.clone(); new_path.push(*adjacent_cave); ...
function_block-function_prefixed
[ { "content": "fn step<const N: usize>(map: &mut Map<N>) -> usize {\n\n let mut flashed =\n\n VecDeque::<Vec2<isize>>::from_iter((0..map.map.len()).map(Map::<N>::index_to_pos));\n\n let mut flash_cnt = 0;\n\n while let Some(pos) = flashed.pop_front() {\n\n if map.get(pos).unwrap().load_ene...
Rust
src/lib.rs
peterhj/pillow_simd_ffi
9612178da129e10713e8181eeeb0177d30409d17
#[macro_use] extern crate lazy_static; use ffi::*; use std::ffi::{CString}; use std::mem::{transmute}; use std::os::raw::{c_char}; use std::slice::{from_raw_parts, from_raw_parts_mut}; pub mod ffi; lazy_static! { static ref MODE_1: CString = CString::new("1").unwrap(); static ref MODE_L: CString =...
#[macro_use] extern crate lazy_static; use ffi::*; use std::ffi::{CString}; use std::mem::{transmute}; use std::os::raw::{c_char}; use std::slice::{from_raw_parts, from_raw_parts_mut}; pub mod ffi; lazy_static! { static ref MODE_1: CString = CString::new("1").unwrap(); static ref MODE_L: CString =...
pub fn render_planes(&self, plane_buf: &mut [u8]) -> Result<usize, ()> { let px_sz = self.pixel_size_bytes() as usize; let x_size = self.x_size() as usize; let y_size = self.y_size() as usize; let ch_size = self.pixel_channels() as usize; assert!(ch_size <= px_sz); for yidx in 0 .. y_size { ...
e; assert!(ch_size <= px_sz); for yidx in 0 .. y_size { match self.line_u8(yidx as _) { None => return Err(()), Some(line) => { for xidx in 0 .. x_size { for c in 0 .. ch_size { pixel_buf[c + ch_size * (xidx + x_size * yidx)] = line[c + px_sz * xidx]; ...
function_block-function_prefixed
[ { "content": "fn main() {\n\n let manifest_dir = PathBuf::from(env::var(\"CARGO_MANIFEST_DIR\").unwrap());\n\n let out_dir = PathBuf::from(env::var(\"OUT_DIR\").unwrap());\n\n //let cc = env::var(\"CC\").unwrap_or(\"gcc\".to_owned());\n\n\n\n println!(\"cargo:rustc-link-search=native={}\", out_dir.display()...
Rust
mercat/cli/interactive/src/main.rs
PolymathNetwork/cryptography
18df5c7244bf8ea71b60a7bec4f3ff3fcf972a33
mod input; use codec::{Decode, Encode}; use cryptography_core::asset_proofs::{AssetId, CommitmentWitness, ElgamalSecretKey}; use curve25519_dalek::scalar::Scalar; use input::{parse_input, CLI}; use log::info; use mercat::{ account::{convert_asset_ids, AccountCreator}, transaction::{CtxMediator, CtxReceiver,...
mod input; use codec::{Decode, Encode}; use cryptography_core::asset_proofs::{AssetId, CommitmentWitness, ElgamalSecretKey}; use curve25519_dalek::scalar::Scalar; use input::{parse_input, CLI}; use log::info; use mercat::{ account::{convert_asset_ids, AccountCreator}, transaction::{CtxMediator, CtxReceiver,...
pub fn justify_asset_transfer_transaction( seed: String, db_dir: PathBuf, sender: Vec<String>, sender_balance: String, receiver: Vec<String>, mediator: String, ticker: String, finalized_tx: String, ) -> Result<(), Error> { let mut rng = create_rng_from_seed(Some(seed))?; ...
pub fn process_finalize_tx( seed: String, db_dir: PathBuf, receiver: String, ticker: String, amount: u32, init_tx: String, ) -> Result<(), Error> { let mut rng = create_rng_from_seed(Some(seed))?; let receiver_ordered_pub_account: OrderedPubAccount = load_object( db_dir.clone(),...
function_block-full_function
[ { "content": "pub fn process_create_mediator(seed: String, db_dir: PathBuf, user: String) -> Result<(), Error> {\n\n // Setup the rng.\n\n let mut rng = create_rng_from_seed(Some(seed))?;\n\n\n\n // Generate keys for the mediator.\n\n let mediator_key_gen_timer = Instant::now();\n\n let (public_a...
Rust
src/policies/lrfu.rs
NicolasDenoyelle/ByoC
18882948df32f8074fbc2e13f5587e42ac672cfb
use crate::policies::timestamp::Timestamp; use crate::policies::{Reference, ReferenceFactory}; use std::cell::Cell; use std::cmp::{Ord, Ordering}; #[derive(Clone, Debug, Copy)] pub struct Stats<T: Timestamp + Copy> { last: T, eavg: f32, exponent: f32, } impl<T: Timestamp + Copy> Stats<T> { ...
use crate::policies::timestamp::Timestamp; use crate::policies::{Reference, ReferenceFactory}; use std::cell::Cell; use std::cmp::{Ord, Ordering}; #[derive(Clone, Debug, Copy)] pub struct Stats<T: Timestamp + Copy> { last: T, eavg: f32, exponent: f32, } impl<T: Timestamp + Copy> Stats<T>
LRFU { exponent, phantom: std::marker::PhantomData, } } } unsafe impl<T: Timestamp + Copy> Send for LRFU<T> {} unsafe impl<T: Timestamp + Copy> Sync for LRFU<T> {} impl<V, T: Timestamp + Copy> ReferenceFactory<V, LRFUCell<V, T>> for LRFU<T> { fn wrap(&mut self, v: V) -> LRF...
{ pub fn new(exponent: f32) -> Self { Stats { exponent, last: T::new(), eavg: 0f32, } } pub fn touch(&mut self) { let last = T::new(); let diff = last.diff(&self.last); self.last = last; ...
random
[ { "content": "/// timestamp trait representing a fixed point in time.\n\n///\n\n/// ## Traits:\n\n///\n\n/// * `Ord`: Timestamp must be orderable such that it is possible to\n\n/// to witness progressing time.\n\n/// * `Clone`: Since timestamps are supposed to be lightweight it is reasonable\n\n/// to ask for i...
Rust
src/parse.rs
rossmacarthur/aq
1bc9c3eeed67bfcec060bb5c00ead7e11b698c95
use std::env; use std::ffi::OsStr; use std::process; use anyhow::{bail, Context, Result}; use crate::Transcoder; #[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)] pub enum Format { Json, Toml, Yaml, } impl Default for Format { fn default() -> Self { Self::Json } } impl Format { fn ...
use std::env; use std::ffi::OsStr; use std::process; use anyhow::{bail, Context, Result}; use crate::Transcoder; #[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)] pub enum Format { Json, Toml, Yaml, } impl Default for Format { fn default() -> Self { Self::Json } } impl Format { fn ...
if args.contains('r') { output_raw = true; } if args.contains('R') { input_raw = true; } jq_args.push(arg); } _ => { jq_args.push(arg); } } } jq_ar...
function_block-function_prefix_line
[ { "content": "fn main() -> Result<()> {\n\n let t = parse::args()?;\n\n\n\n let mut cmd = Command::new(\"jq\");\n\n if atty::is(atty::Stream::Stdin) {\n\n if t.jq_args.is_empty() {\n\n parse::usage()\n\n } else {\n\n bail!(\"aq requires input via stdin\");\n\n ...
Rust
lightning-core/src/util/array.rs
lightning-project/lightning
1a1ac9e0017aab8118478059274b793597496011
use std::mem::{self, ManuallyDrop, MaybeUninit}; #[inline(always)] pub fn generate<T, F, const N: usize>(mut fun: F) -> [T; N] where F: FnMut(usize) -> T, { let mut output = unsafe { MaybeUninit::<[MaybeUninit<T>; N]>::uninit().assume_init() }; for i in 0..N { output[i] = MaybeUninit...
use std::mem::{self, ManuallyDrop, MaybeUninit}; #[inline(always)] pub fn generate<T, F, const N: usize>(mut fun: F) -> [T; N] where F: FnMut(usize) -> T, { let mut output = unsafe { MaybeUninit::<[MaybeUninit<T>; N]>::uninit().assume_init() }; for i in 0..N { output[i] = MaybeUninit...
#[inline(always)] pub fn zip<L, R, T, F, const N: usize>(lhs: [L; N], rhs: [R; N], mut fun: F) -> [T; N] where F: FnMut(L, R) -> T, { enum Infallible {} match try_zip(lhs, rhs, |l, r| Result::<_, Infallible>::Ok(fun(l, r))) { Ok(v) => v, Err(e) => match e {}, } } #[inline(always)] pu...
pub fn try_zip<L, R, T, F, E, const N: usize>( lhs: [L; N], rhs: [R; N], mut fun: F, ) -> Result<[T; N], E> where F: FnMut(L, R) -> Result<T, E>, { let mut lhs_items: [ManuallyDrop<L>; N] = unsafe { mem::transmute_copy(&lhs) }; mem::forget(lhs); let mut rhs_items: [ManuallyDrop<R>...
function_block-full_function
[ { "content": "pub fn execute<F>(config: Config, fun: F) -> Result\n\nwhere\n\n F: FnOnce(Context) -> Result + UnwindSafe,\n\n{\n\n execute_erased(config, Box::new(fun))\n\n}\n\n\n", "file_path": "src/api/mod.rs", "rank": 4, "score": 231287.72333315312 }, { "content": "pub fn new_boxed_...
Rust
src/ctx/context.rs
matthewtgilbride/wash
a9f980c71a9f9e62ab53ab031ddf2a3a34889b53
use crate::util::{ DEFAULT_LATTICE_PREFIX, DEFAULT_NATS_HOST, DEFAULT_NATS_PORT, DEFAULT_NATS_TIMEOUT, }; use serde::{Deserialize, Serialize}; use std::path::PathBuf; #[derive(Clone, Deserialize, Serialize, Debug)] pub(crate) struct DefaultContext { pub name: String, } impl DefaultContext { pub fn ne...
use crate::util::{ DEFAULT_LATTICE_PREFIX, DEFAULT_NATS_HOST, DEFAULT_NATS_PORT, DEFAULT_NATS_TIMEOUT, }; use serde::{Deserialize, Serialize}; use std::path::PathBuf; #[derive(Clone, Deserialize, Serialize, Debug)] pub(crate) struct DefaultContext { pub name: String, } impl DefaultContext { pub fn ne...
#[allow(clippy::too_many_arguments)] pub(crate) fn new( name: String, cluster_seed: Option<String>, ctl_host: String, ctl_port: u16, ctl_jwt: Option<String>, ctl_seed: Option<String>, ctl_credsfile: Option<PathBuf>, ctl_timeout: u64, ctl_...
pub(crate) fn named(name: String) -> Self { WashContext { name, ..Self::default() } }
function_block-full_function
[ { "content": "/// thanks to @extrawurst for pointing this out\n\n/// <https://github.com/extrawurst/gitui/blob/master/asyncgit/src/sync/branch/mod.rs#L38>\n\nfn get_branch_name_repo(repo: &Repository) -> Result<String> {\n\n let iter = repo.branches(None)?;\n\n\n\n for b in iter {\n\n let b = b?;\n...
Rust
harmoxen-standalone/src/midi/mod.rs
Azorlogh/xenharmonic-piano-roll
e4ebdf325d58936f05d031cc219714231ac534a6
use harmoxen::{ backend::Event, data::{icp, sheet::*, Range}, }; use midir::{MidiOutput, MidiOutputConnection, MidiOutputPort}; use std::error::Error; use std::sync::mpsc::*; use std::thread; use std::time::{Duration, Instant}; pub struct MidiBackend { to_backend: Sender<Event>, } impl MidiBackend { pub fn new(po...
use harmoxen::{ backend::Event, data::{icp, sheet::*, Range}, }; use midir::{MidiOutput, MidiOutputConnection, MidiOutputPort}; use std::error::Error; use std::sync::mpsc::*; use std::thread; use std::time::{Duration, Instant}; pub struct MidiBackend { to_backend: Sender<Event>, } impl MidiBackend { pub fn new(po...
} } if engine.active { engine.update(UPDATE_RATE); } until_update -= UPDATE_RATE; } thread::sleep(Duration::from_millis((until_update * 1000.0) as u64)); } Ok(()) } const PITCH_BEND_RANGE: f32 = 2.0; const PITCH_BEND_SEMITONES: u8 = PITCH_BEND_RANGE as u8; const PITCH_BEND_CENTS: u8 = ((PIT...
rintln!("Error with the mpe server: {}", err); } }); Self { to_backend } } } impl super::Backend for MidiBackend { fn send(&mut self, evt: Event) { self.to_backend.send(evt).unwrap() } } const UPDATE_RATE: f32 = 0.04; pub fn run(receiver: Receiver<Event>, port: MidiOutputPort) -> Result<(), Box<dyn Error>...
random
[ { "content": "pub trait StyleSheet {\n\n\tfn active(&self) -> Style;\n\n}\n\n\n", "file_path": "harmoxen/src/widget/common/range_slider/style.rs", "rank": 2, "score": 118434.59712257735 }, { "content": "pub fn build(state: &mut State, theme: Theme) -> Element<RootMessage> {\n\n\tlet x_scroll...
Rust
src/lib.rs
diodesign/dmfs
60ed85af9325950f4864c3cd6a6b4dc3313f7518
/* Diosix Manifest File System * * This very simple read-only file system is intended to be embedded * in a diosix hypervisor build, and parsed and unpacked at run-time. * It enables the hypervisor to ship with essential services and guests * needed to boot a fully functional system from storage. * * Typically...
/* Diosix Manifest File System * * This very simple read-only file system is intended to be embedded * in a diosix hypervisor build, and parsed and unpacked at run-time. * It enables the hypervisor to ship with essential services and guests * needed to boot a fully functional system from storage. * * Typically...
on) }) } } #[cfg(test)] mod tests { #[test] fn it_works() { assert_eq!(2 + 2, 4); } }
read_null_term_string(offset)?; offset = offset + prop_string.len() + 1; obj_props.push(prop_string); } offset = Bytes::align_to_next_u64(offset); /* define the region of the image that contains the object's contents */ let region = Range { start: offset, end: o...
function_block-random_span
[ { "content": "## dmfs\n\n\n\nThis is the Diosix Manifest File System (DMFS) parser and generator. It can parse DMFS images, and create DMFS images from a set of files.\n\n\n\nThis crate is used by [Diosix](https://diosix.org) to load native services and guest operating systems from firmware storage. As such, it...
Rust
src/spec.rs
serlo/mfnf-template-spec
cb85aa90c27df1134e23357cef90c859899480a4
use mediawiki_parser::{MarkupType, Text}; use mwparser_utils::*; use mwparser_utils_derive::template_spec; const _SPEC: &str = include_str!("templates.yml"); template_spec!("src/templates.yml"); pub fn is_math_tag(elems: &[Element]) -> PredResult { if elems.len() != 1 { return Err(PredError { ...
use mediawiki_parser::{MarkupType, Text}; use mwparser_utils::*; use mwparser_utils_derive::template_spec; const _SPEC: &str = include_str!("templates.yml"); template_spec!("src/templates.yml"); pub fn is_math_tag(elems: &[Element]) -> PredResult { if elems.len() != 1 { return Err(PredError { ...
; always(elems, &shallow) } pub fn everything_is_allowed(_elems: &[Element]) -> PredResult { return Ok(()); }
fn shallow(elems: &[Element]) -> PredResult { for elem in elems { match *elem { Element::Template(ref template) => { let spec = get_template_spec(template)?; if spec.format != Format::Inline && spec.format != Format::Block { ...
function_block-full_function
[ { "content": "/// Renders a markdown version of a template specification.\n\n///\n\n/// The `heading_depth` is added to the depth of the headings produced.\n\npub fn template_description(\n\n template: &spec_meta::TemplateSpec,\n\n heading_depth: usize,\n\n) -> Result<String, Error> {\n\n let mut out =...
Rust
core/src/example.rs
Catallaxy/cryptoaudit
f5bb902f0ceea86f93d52730ca9ab76912031fc6
use bitcoin::blockdata::script; use bitcoin::network::constants::Network; use bitcoin::util::base58::FromBase58; use bitcoin::util::address::Address; use bitcoin::util::hash::Hash160; use rustc_serialize::hex::{FromHex, ToHex}; use secp256k1::{self, Message, Secp256k1, Signature}; use secp256k1::key::{PublicKey, Sec...
use bitcoin::blockdata::script; use bitcoin::network::constants::Network; use bitcoin::util::base58::FromBase58; use bitcoin::util::address::Address; use bitcoin::util::hash::Hash160; use rustc_serialize::hex::{FromHex, ToHex}; use secp256k1::{self, Message, Secp256k1, Signature}; use secp256k1::key::{PublicKey, Sec...
; let message2 = "invalid"; let mut sha2 = Sha256::new(); sha2.input_str(message2); let mut hashed_message2 = [0; 32]; sha2.result(&mut hashed_message2); let message_to_sign2 = Message::from_slice(&hashed_message2).unwrap(); match verify(message_to_sign2, signature, public_key, &secp) { ...
match verify(message_to_sign, signature, public_key, &secp) { Ok(_) => println!("Signature is valid"), Err(_) => println!("Signature is invalid"), }
if_condition
[ { "content": "pub fn sign(message: Message, secret_key: SecretKey, secp: &Secp256k1) -> Result<Signature, Error> {\n\n //println!(\"Signing message: {:?}\", message);\n\n let sig = secp.sign(&message, &secret_key)?;\n\n Ok(sig)\n\n}\n\n\n", "file_path": "core/src/ecdsa.rs", "rank": 0, "scor...
Rust
crabzilla/src/lib.rs
andyherbert/crabzilla
e8878e06aa3e30f2bc85c0dd36567745e61b43a2
/*! Crabzilla provides a _simple_ interface for running JavaScript modules alongside Rust code. # Example ``` use crabzilla::*; use std::io::stdin; #[import_fn(name="read", scope="Stdin")] fn read_from_stdin() -> Value { let mut buffer = String::new(); println!("Type your name: "); stdin().read_line(&mut b...
/*! Crabzilla provides a _simple_ interface for running JavaScript modules alongside Rust code. # Example ``` use crabzilla::*; use std::io::stdin; #[import_fn(name="read", scope="Stdin")] fn read_from_stdin() -> Value { let mut buffer = String::new(); println!("Type your name: "); stdin().read_line(&mut b...
hable!(); } pub struct ImportedFn { op_fn: Box<OpFn>, name: String, scope: Option<String>, } pub fn create_sync_fn<F>(imported_fn: F, name: &str, scope: Option<String>) -> ImportedFn where F: Fn(Vec<Value>) -> Result<Value, AnyError> + 'static, { let op_fn = op_sync( move |_state: &mut OpS...
::Object(map) = &value { if let Some(Value::Array(args)) = &map.get("args") { return args.to_owned(); } } unreac
function_block-random_span
[ { "content": "#[import_fn(name = \"read\", scope = \"Stdin\")]\n\nfn read_from_stdin() -> Value {\n\n let mut buffer = String::new();\n\n println!(\"Type your name: \");\n\n stdin().read_line(&mut buffer)?;\n\n buffer.pop(); // Remove newline\n\n if buffer.is_empty() {\n\n throw!(\"Expecte...
Rust
2020/11/src/main.rs
amhk/advent-of-code
41f0c590e6aee377b91ecde1df1c91ce9d2f4081
use std::collections::HashMap; fn main() { let input = include_str!("input.txt"); let answer = part_one(input).expect("no solution for part one"); println!("part 1: {}", answer); let answer = part_two(input).expect("no solution for part part_two"); println!("part 2: {}", answer); } #[derive(Debu...
use std::collections::HashMap; fn main() { let input = include_str!("input.txt"); let answer = part_one(input).expect("no solution for part one"); println!("part 1: {}", answer); let answer = part_two(input).expect("no solution for part part_two"); println!("part 2: {}", answer); } #[derive(Debu...
fn solve(input: &str, horizon: usize, croweded_threshold: usize) -> Result<usize, Error> { fn neighbor_count(seats: &[Seat], index: usize) -> usize { seats[index] .neighbors .iter() .filter_map(|&index| match seats[index].state { State::Occupied => Some(...
L' { map.insert((x as isize, y as isize), index); index += 1; } } } let x_max: isize = input.lines().next().unwrap().len() as isize; let y_max: isize = input.lines().count() as isize; for (&(x0, y0), &index) in map.iter() { let seat = sea...
function_block-function_prefixed
[ { "content": "fn parse_input(input: &str) -> Result<(Vec<usize>, Vec<usize>), Error> {\n\n fn parse_deck(input: &str) -> Result<Vec<usize>, Error> {\n\n let mut deck = Vec::new();\n\n for line in input.lines().skip(1) {\n\n let value = line.parse::<usize>().map_err(|_| Error::BadInpu...
Rust
src/ssh.rs
Danpiel/hearth
587633da30015fd81d45c685e07d99cfe226142a
use crate::config::AuthMethod; use log::{debug, info}; use ssh2::{Channel, Session}; use std::io::prelude::*; use std::net::{TcpStream, ToSocketAddrs}; use std::str::FromStr; pub struct SshClient { username: String, auth_method: AuthMethod, hostname: String, port: usize, session: Option<Session>, ...
use crate::config::AuthMethod; use log::{debug, info}; use ssh2::{Channel, Session}; use std::io::prelude::*; use std::net::{TcpStream, ToSocketAddrs}; use std::str::FromStr; pub struct SshClient { username: String, auth_method: AuthMethod, hostname: String, port: usize, session: Option<Session>, ...
pub fn update_uptime(&mut self) { let raw_uptime = self .run("cat /proc/uptime") .unwrap_or_else(|_| "0".to_string()); let (parts, _): (Vec<&str>, Vec<&str>) = raw_uptime.split(' ').partition(|s| !s.is_empty()); let uptime_seconds = parts.get(0).unwrap_or(&"0"); ...
pub fn run(&mut self, command: &str) -> Result<String, Box<dyn (::std::error::Error)>> { self.exec(command).map_err(move |error| { self.session = None; error }) }
function_block-function_prefix_line
[ { "content": "#[derive(Deserialize)]\n\nstruct Command {\n\n subscribe_to: View,\n\n}\n\n\n\n#[derive(Message)]\n\n#[rtype(result = \"usize\")]\n\npub struct Connect {\n\n pub addr: Recipient<SessionMessage>,\n\n pub ip: String,\n\n}\n\n\n\n#[derive(Message)]\n\n#[rtype(result = \"()\")]\n\npub struct ...
Rust
irid_renderer/src/surface.rs
CatCode79/irid-framework
949ff3bcaac40b632dc3c32a23c7a36c0365ac59
use pollster::FutureExt; use thiserror::Error; use crate::device::Device; #[non_exhaustive] #[derive(Debug, Error)] pub(crate) enum SurfaceError { #[error("An adapter compatible with the given surface could not be obtained")] AdapterNotObtained, } #[derive(Debug)] pub(crate) struct Surface { wgpu_surfa...
use pollster::FutureExt; use thiserror::Error; use crate::device::Device; #[non_exhaustive] #[derive(Debug, Error)] pub(crate) enum SurfaceError { #[error("An adapter compatible with the given surface could not be obtained")] AdapterNotObtained, } #[derive(Debug)] pub(crate) struct Surface { wgpu_surfa...
} found = true; } if !found { log::info!("No Adapter Found"); } } fn pprint_adapter_info(adapter: &wgpu::Adapter) -> String { format!("{:?}", adapter.get_info()) .replace("AdapterInfo { name: ", "") .replace(" }", "") }
ureUsages::RENDER_ATTACHMENT, format, width: window_size.width, height: window_size.height, present_mode, }; let surface = Self { wgpu_surface, format, configuration, }; Ok((surface, adapter)) } ...
random
[ { "content": "//= USES ===========================================================================================\n\n\n\nuse thiserror::Error;\n\n\n\nuse irid_assets_interface::Image;\n\n\n\nuse crate::{DiffuseImage, DiffuseImageSize};\n\n\n\n//= TEXTURE ERRORS =================================================...
Rust
engine/src/xetex_stringpool.rs
burrbull/tectonic
3549a22ace6615043bc7570d1ca3f9df67c71577
#![allow(non_camel_case_types, non_snake_case, non_upper_case_globals)] use crate::xetex_errors::overflow; use crate::xetex_ini::BUFFER; pub(crate) static mut str_pool: Vec<u16> = Vec::new(); pub(crate) static mut str_start: Vec<usize> = Vec::new(); pub(crate) static mut pool_ptr: usize = 0; pub(crate) static mut ...
#![allow(non_camel_case_types, non_snake_case, non_upper_case_globals)] use crate::xetex_errors::overflow; use crate::xetex_ini::BUFFER; pub(crate) static mut str_pool: Vec<u16> = Vec::new(); pub(crate) static mut str_start: Vec<usize> = Vec::new(); pub(crate) static mut pool_ptr: usize = 0; pub(crate) static mut ...
pub(crate) unsafe fn make_string() -> str_number { if str_ptr == max_strings as i32 { overflow("number of strings", max_strings - init_str_ptr as usize); } str_ptr += 1; str_start[(str_ptr - TOO_BIG_CHAR) as usize] = pool_ptr; str_ptr - 1 } pub(crate) unsafe fn append_str(s: str_number) { ...
pub(crate) unsafe fn load_pool_strings(spare_size: usize) -> i32 { let mut g: str_number = 0; for s in &string_constants { let total_len = s.len(); if total_len >= spare_size { return 0; } for b in s.as_bytes() { str_pool[pool_ptr] = *b as _; p...
function_block-full_function
[]
Rust
client/haarukointi/src/main.rs
joonazan/BM1422AGMV-ZE2
df3adb437abbbaee40c44184c25aca93dc3f4a8e
use amplitude_to_position::{interface::{Vec3, AmplitudesToPosition}, slicer::NaiveSlicer}; use nalgebra::{Vector2}; use piston_window::WindowSettings; use plotters::prelude::*; use std::collections::VecDeque; use std::sync::{Arc, Mutex}; mod config; #[cfg(test)] extern crate quickcheck; #[cfg(test)] #[macro_use] exter...
use amplitude_to_position::{interface::{Vec3, AmplitudesToPosition}, slicer::NaiveSlicer}; use nalgebra::{Vector2}; use piston_window::WindowSettings; use plotters::prelude::*; use std::collections::VecDeque; use std::sync::{Arc, Mutex}; mod config; #[cfg(test)] extern crate quickcheck; #[cfg(test)] #[macro_use] exter...
ries::new( previous_strengths[i].iter().cloned().enumerate(), &Palette99::pick(i), ))? .label(format!("{} Hz", frequencies[i])) .legend(move |(x, y)| { PathElement::new(vec![(x, y), (x + 20, y)], &Palette99::pick...
ettings::new("Possible Locations", [1024, 768]) .build() .unwrap(); let config = config::load_config(); let mut magnet_positions = [Vec3::new(0.0, 0.0, 0.0); 4]; for (i, x) in config.magnets.iter().map(|x| x.position.into()).enumerate() { magnet_positions[i] = x; } let fre...
random
[ { "content": "pub fn load_config() -> Config {\n\n let f = File::open(&\"config.ron\").expect(\"Failed to open config file\");\n\n let config: Config = match from_reader(f) {\n\n Ok(x) => x,\n\n Err(e) => {\n\n println!(\"Failed to load config: {}\", e);\n\n std::proces...
Rust
examples/sandboxer.rs
landlock-lsm/rust-landlock
58f52e0177adcec543698fd2b139942320961042
use anyhow::{anyhow, bail}; use landlock::{ make_bitflags, Access, AccessFs, BitFlags, PathBeneath, PathFd, PathFdError, Ruleset, RulesetError, RulesetStatus, ABI, }; use std::env; use std::ffi::OsStr; use std::os::unix::ffi::{OsStrExt, OsStringExt}; use std::os::unix::process::CommandExt; use std::process::Com...
use anyhow::{anyhow, bail}; use landlock::{ make_bitflags, Access, AccessFs, BitFlags, PathBeneath, PathFd, PathFdError, Ruleset, RulesetError, RulesetStatus, ABI, }; use std::env; use std::ffi::OsStr; use std::os::unix::ffi::{OsStrExt, OsStringExt}; use std::os::unix::process::CommandExt; use std::process::Com...
ENV_FS_RO_NAME ); eprintln!( "* {}: list of paths allowed to be used in a read-write way.", ENV_FS_RW_NAME ); eprintln!( "\nexample:\n\ {}=\"/bin:/lib:/usr:/proc:/etc:/dev/urandom\" \ {}=\"/dev/null:/dev/full:/de...
f, ) -> impl Iterator<Item = Result<PathBeneath<PathFd>, PathEnvError<'static>>> + '_ { let is_empty = self.paths.is_empty(); self.paths .split(|b| *b == b':') .skip_while(move |_| is_empty) .map(OsStr::from_bytes) .map(move |path| Ok(Path...
random
[ { "content": "#[test]\n\nfn ruleset_add_rule_iter() {\n\n let compat = ABI::Unsupported.into();\n\n let new_ruleset = |compat: &Compatibility| -> Ruleset { compat.clone().into() };\n\n\n\n assert!(matches!(\n\n new_ruleset(&compat)\n\n .handle_access(AccessFs::Execute)\n\n ...
Rust
src/danmaku/cc.rs
hellobbn/dmlive
130a645f0bd7587f3f33e454e0a338a6a287d78c
use structure::byteorder::{ LittleEndian, ReadBytesExt, }; use reqwest::Url; use flate2::read::ZlibDecoder; use futures::{ stream::StreamExt, SinkExt, }; use rmp; use rmp_serde; use rmpv; use serde::Deserialize; use serde_json::json; use std::collections::HashMap; use std::collections::LinkedList; use...
use structure::byteorder::{ LittleEndian, ReadBytesExt, }; use reqwest::Url; use flate2::read::ZlibDecoder; use futures::{ stream::StreamExt, SinkExt, }; use rmp; use rmp_serde; use rmpv; use serde::Deserialize; use serde_json::json; use std::collections::HashMap; use std::collections::LinkedList; use...
fn get_beat(&self) -> Vec<u8> { let sid = 6144; let cid = 5; let data = json!({}); let mut beat_data = structure!("<HHI").pack(sid, cid, 0).unwrap(); beat_data.append(&mut self.encode_dict(data)); beat_data } fn get_join(&self, data_cid: u32, data_gametype:...
fn get_reg(&self) -> Vec<u8> { let sid = 6144; let cid = 2; let update_req_info = json!({ "22": 640u32, "23": 360u32, "24": "web", "25": "Linux", "29": "163_cc", "30": "", "31": "Mozilla/5.0 (Linux; Android 5.0;...
function_block-full_function
[ { "content": "pub fn gen_ua() -> String {\n\n // let rn = rand::random::<u64>();\n\n // let n1 = 50 + (rn % 30);\n\n // let n2 = 1000 + (rn % 6000);\n\n // let n3 = 10 + (rn % 150);\n\n // format!(\n\n // \"Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/...
Rust
src/accept_encoding.rs
tailhook/tk-http-file
1fdedb6cdb62920ecabf1fa5088587a10b50dbda
use std::fmt; use std::str::from_utf8; use std::slice; #[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, PartialOrd, Ord)] pub enum Encoding { Brotli, Gzip, Identity, #[doc(hidden)] __Nonexhaustive, } #[derive(Debug, Clone)] pub struct AcceptEncoding { ordered: [Encoding; 3], } ...
use std::fmt; use std::str::from_utf8; use std::slice; #[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, PartialOrd, Ord)] pub enum Encoding { Brotli, Gzip, Identity, #[doc(hidden)] __Nonexhaustive, } #[derive(Debug, Clone)] pub struct AcceptEncoding { ordered: [Encoding; 3], } ...
}
assert_eq!(to_ext("identity, br"), vec![".br", ""]); assert_eq!(to_ext("identity, br;q=0.5"), vec!["", ".br"]); }
function_block-function_prefix_line
[ { "content": "pub fn is_text_file(val: &str) -> bool {\n\n return val.starts_with(\"text/\") || val == \"application/javascript\"\n\n}\n\n\n\n/// The structure represents parsed input headers\n\n///\n\n/// Create it with `Input::from_headers`, and make output structure\n\n/// using `Input::probe_file`. Note:...
Rust
src/lib.rs
heliaxdev/het_paxos_ref
241d1ecfbb1c6920cab77b3ebb50969344d96994
pub mod acceptor; pub mod crypto; pub mod learner; pub mod parse_config; pub mod parsed_message; pub mod proposer; pub mod grpc { tonic::include_proto!("hetpaxosref"); include!(concat!(env!("OUT_DIR"), "/hetpaxosref.serde.rs")); impl ConsensusMessage { pub fn is_one_a(&self) -> b...
pub mod acceptor; pub mod crypto; pub mod learner; pub mod parse_config; pub mod parsed_message; pub mod proposer; pub mod grpc { tonic::include_proto!("hetpaxosref"); include!(concat!(env!("OUT_DIR"), "/hetpaxosref.serde.rs")); impl ConsensusMessage { pub fn is_one_a(&self) -> b...
(timestamp_tuple(&self.timestamp), &self.value_hash).cmp( &(timestamp_tuple(&other.timestamp), &other.value_hash)) } } impl PartialOrd for Ballot { fn partial_cmp(&self, other: &Self) -> Option<Ordering> { Some(self.cmp(other)) ...
fn timestamp_tuple(timestamp : &Option<Timestamp>) -> (i64, i32) { if let Some(t) = timestamp { (t.seconds, t.nanos) } else { (0, 0) } }
function_block-full_function
[ { "content": "/// public way to generate a new learner (it has received no messages) using a config file.\n\n/// This does not connections to `Acceptor` servers.\n\n/// It just creates a new acceptor object. \n\npub fn new_learner(config : ParsedConfig) -> Learner {\n\n Learner(Arc::new(LearnerMutex{\n\n ...
Rust
day19-1/src/main.rs
jgosmann/aoc2020
da97eb0534eff3cb91c8d42fa8a4f952c7b22541
use nom::{ branch::alt, character::complete::{alphanumeric1, char, digit1, space0, space1}, combinator::map, combinator::map_res, multi::separated_list1, sequence::{delimited, separated_pair, tuple}, IResult, }; use std::collections::HashMap; use std::fmt::Display; use std::fmt::Formatter; u...
use nom::{ branch::alt, character::complete::{alphanumeric1, char, digit1, space0, space1}, combinator::map, combinator::map_res, multi::separated_list1, sequence::{delimited, separated_pair, tuple}, IResult, }; use std::collections::HashMap; use std::fmt::Display; use std::fmt::Formatter; u...
#[cfg(test)] mod tests { use super::*; #[test] fn test_parse_productiion_rule() { let (_, rule) = ProductionRule::parse("1 3 | 3 \"x\"").unwrap(); assert_eq!( rule, ProductionRule::OneOf(vec![ Box::new(ProductionRule::Sequence(vec![ ...
t::unwrap); let grammar = Grammar::parse_lines(&mut lines.by_ref().take_while(|line| !line.is_empty())).unwrap(); let count = lines.filter(|line| grammar.accepts(line)).count(); println!("{}", count); }
function_block-function_prefixed
[ { "content": "fn process(lines: impl Iterator<Item = impl AsRef<str>>) -> usize {\n\n let mut lines = lines;\n\n let mut grammar =\n\n Grammar::parse_lines(&mut lines.by_ref().take_while(|line| !line.as_ref().is_empty()))\n\n .unwrap();\n\n grammar.rules.insert(\n\n 8,\n\n ...
Rust
crates/wasi-test/src/main.rs
osa1/wasmrun
2ca9f11a4f11f35266585cc2ac49e2d675737332
mod cli; mod cmd; use std::collections::HashMap; use std::fs; use std::path::{Path, PathBuf}; use std::process::{exit, Command}; use std::sync::{Arc, RwLock}; use parity_wasm::elements as wasm; use libwasmrun::virtfs::pipe::{ReadPipe, WritePipe}; use libwasmrun::virtfs::{VecFileContents, VirtualDirEntry}; use libwas...
mod cli; mod cmd; use std::collections::HashMap; use std::fs; use std::path::{Path, PathBuf}; use std::process::{exit, Command}; use std::sync::{Arc, RwLock}; use parity_wasm::elements as wasm; use libwasmrun::virtfs::pipe::{ReadPipe, WritePipe}; use libwasmrun::virtfs::{VecFileContents, VirtualDirEntry}; use libwas...
buf) } fn run_file(file: &Path) -> bool { println!("{}", file.to_string_lossy()); let file_stem = file.file_stem().unwrap().to_str().unwrap(); let file_src_path = format!("tests/wasi/src/{}.rs", file_stem); let file_src = fs::read_to_string(file_src_path).unwrap(); let cmds = cmd::parse_cmds(&fil...
version("wasmtime"); print_cmd("cargo", &["build"]); let _ = Command::new("cargo").arg("build").status().unwrap(); print_version(WASMRUN_PATH); println!("cd tests/wasi; cargo build"); let status = Command::new("cargo") .arg("build") .current_dir("tests/wasi") .status() ...
random
[ { "content": "fn trap_expected_msg(trap: Trap) -> &'static str {\n\n match trap {\n\n Trap::UndefinedElement => \"undefined\",\n\n Trap::UninitializedElement => \"uninitialized\",\n\n Trap::IndirectCallTypeMismatch => \"indirect call\",\n\n Trap::OOBTableElementIdx => \"element ou...
Rust
src/connectivity/bluetooth/hci/lib/src/transport/uart/parse_util.rs
liexusong/fuchsia
81897680af92a1848a063e3c20ff3a4892ccff07
use std::{collections::VecDeque, ops::Range}; pub(super) fn copy_until_full<'a, T: 'a + Clone>( mut src: impl ExactSizeIterator<Item = T>, dst: impl ExactSizeIterator<Item = &'a mut T>, ) -> Result<(), ()> { if src.len() < dst.len() { return Err(()); } for b in dst { if let Some(n...
use std::{collections::VecDeque, ops::Range}; pub(super) fn copy_until_full<'a, T: 'a + Clone>( mut src: impl ExactSizeIterator<Item = T>, dst: impl ExactSizeIterator
Some(next) = src.next() { *b = next; } else { return Err(()); } } Ok(()) } pub(super) fn slices_from_range<T>(q: &VecDeque<T>, range: Range<usize>) -> (&[T], &[T]) { if range.start >= q.len() || ExactSizeIterator::len(&range) == 0 { return (&[], &[]); ...
<Item = &'a mut T>, ) -> Result<(), ()> { if src.len() < dst.len() { return Err(()); } for b in dst { if let
function_block-random_span
[]
Rust
families/seth/rpc/src/main.rs
mealchain/beta
7dc1a1aea175bfb3f1008939f098a1d58bb455a6
/* * Copyright 2017 Intel Corporation * * 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 agre...
/* * Copyright 2017 Intel Corporation * * 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 agre...
fn abort_if_err<T, E: std::error::Error>(r: Result<T, E>) -> T { match r { Ok(t) => t, Err(error) => { eprintln!("{}", error.description()); process::exit(1); } } }
function_block-full_function
[ { "content": "pub fn new_pending_transaction_filter<T>(_params: Params, mut client: ValidatorClient<T>)\n\n -> Result<Value, Error> where T: MessageSender\n\n{\n\n info!(\"eth_newPendingTransactionFilter\");\n\n let current_block = client.get_current_block_number().map_err(|error| {\n\n error!(\...
Rust
day23/src/main.rs
ruscur/advent-of-code-2021
44db33df7bf13d233260e9372df45b72255d4ff1
use std::collections::HashMap; #[derive(Debug, Copy, Clone, PartialEq, Eq, Hash)] enum Amphipod { A, B, C, D, } impl Amphipod { fn from_room(room: usize) -> Amphipod { match room { 0 => Amphipod::A, 1 => Amphipod::B, 2 => Amphipod::C, 3 => Am...
use std::collections::HashMap; #[derive(Debug, Copy, Clone, PartialEq, Eq, Hash)] enum Amphipod { A, B, C, D, } impl Amphipod { fn from_room(room: usize) -> Amphipod { match room { 0 => Amphipod::A, 1 => Amphipod::B, 2 => Amphipod::C, 3 => Am...
fn hallway_move(&self, hallway_pos: usize, room_id: usize) -> (Burrow, usize) { let mut updated = self.clone(); let hallway = self.hallway[hallway_pos]; let doorway_pos = (room_id + 1) * 2; let room = self.rooms.get(room_id); let room_pos = match hallway { ...
1][1]), Some(rooms[1][2]), Some(rooms[1][3]), ], [ Some(rooms[2][0]), Some(rooms[2][1]), Some(rooms[2][2]), Some(rooms[2][3]), ], [ ...
function_block-function_prefixed
[ { "content": "fn bits_to_val(bits: &Vec<usize>) -> usize {\n\n usize::from_str_radix(\n\n &bits\n\n .iter()\n\n .map(|b| b.to_string())\n\n .collect::<Vec<String>>()\n\n .join(\"\"),\n\n 2,\n\n )\n\n .unwrap()\n\n}\n\n\n", "file_path": "day1...
Rust
basic_rt/src/thread/processor.rs
yuoo655/c
5e8141c89055baa2fcbb8e160322b3039adf6dc6
use super::thread_pool::ThreadPool; use super::thread::Thread; use super::scheduler::Scheduler; use core::cell::UnsafeCell; use alloc::boxed::Box; use super::Tid; use crate::println; use crate::task::USER_TASK_QUEUE; use crate::task::thread_main; unsafe impl Sync for Processor {} pub struct Processor { pub inne...
use super::thread_pool::ThreadPool; use super::thread::Thread; use super::scheduler::Scheduler; use core::cell::UnsafeCell; use alloc::boxed::Box; use super::Tid; use crate::println; use crate::task::USER_TASK_QUEUE; use crate::task::thread_main; unsafe impl Sync for Processor {} pub struct Processor { pub inne...
; } } fn inner(&self) -> &mut ProcessorInner { unsafe { &mut *self.inner.get() } .as_mut() .expect("Processor is not initialized!") } pub fn thread_pool(&self) -> &mut ThreadPool { &mut *self.inner().pool } pub fn add_thread(&self, th...
Some( ProcessorInner { pool, idle, current: None, } )
call_expression
[]
Rust
2019-05-11-prettier-printer-rust-from-scratch/src/printer/print.rs
vain0x/playground
76338f96ac0e449613f3fe55082a26f65e85944d
use super::*; type IndentDocId = usize; type IndentDocList = Option<IndentDocId>; type EmitId = usize; type EmitList = Option<EmitId>; #[derive(Clone, Debug)] struct IndentDoc { doc: Doc, depth: usize, } #[derive(Clone, Debug)] enum Emit { Space, Text(String), Line(usize), } struct PrintConte...
use super::*; type IndentDocId = usize; type IndentDocList = Option<IndentDocId>; type EmitId = usize; type EmitList = Option<EmitId>; #[derive(Clone, Debug)] struct IndentDoc { doc: Doc, depth: usize, } #[derive(Clone, Debug)] enum Emit { Space, Text(String), Line(usize), } struct PrintConte...
et second = self.cons_doc(second, depth, docs); let first = self.cons_doc(first, depth, Some(second)); self.be(column, flatten, Some(first), emits) } &DocKind::Nest { depth: shift, content, } => { let hea...
emits) } else { self.cons_emit(Emit::Line(depth), emits) }; self.be(depth, flatten, docs, Some(emits)) } &DocKind::Cat(first, second) => { l
random
[ { "content": "fn write_section(buf: &mut Vec<u8>, n: usize, write: impl Fn(&mut Vec<u8>)) {\n\n let mut content_buf = vec![];\n\n write(&mut content_buf);\n\n\n\n buf.push(n as u8);\n\n write_u32(buf, content_buf.len() as u32);\n\n buf.extend(content_buf.drain(..));\n\n}\n\n\n\npub(crate) fn writ...
Rust
tests/common/gen.rs
Rikorose/hdf5-rust
27075a5e10dbe993ab94822be99bf9fa5480f252
use std::convert::TryFrom; use std::fmt; use std::iter; use hdf5::types::{FixedAscii, FixedUnicode, VarLenArray, VarLenAscii, VarLenUnicode}; use hdf5::H5Type; use ndarray::{ArrayD, SliceInfo, SliceInfoElem}; use rand::distributions::{Alphanumeric, Uniform}; use rand::prelude::{Rng, SliceRandom}; pub fn gen_shape<R:...
use std::convert::TryFrom; use std::fmt; use std::iter; use hdf5::types::{FixedAscii, FixedUnicode, VarLenArray, VarLenAscii, VarLenUnicode}; use hdf5::H5Type; use ndarray::{ArrayD, SliceInfo, SliceInfoElem}; use rand::distributions::{Alphanumeric, Uniform}; use rand::prelude::{Rng, SliceRandom}; pub fn gen_shape<R:...
Unicode<11>, tuple: (i8, u64, f32), array: [TupleStruct; 2], } impl Gen for FixedStruct { fn gen<R: Rng + ?Sized>(rng: &mut R) -> Self { FixedStruct { fa: Gen::gen(rng), fu: Gen::gen(rng), tuple: (Gen::gen(rng), Gen::gen(rng), Gen::gen(rng)), array: [...
zed + fmt::Debug { fn gen<R: Rng + ?Sized>(rng: &mut R) -> Self; } macro_rules! impl_gen_primitive { ($ty:ty) => { impl Gen for $ty { fn gen<R: Rng + ?Sized>(rng: &mut R) -> Self { rng.gen() } } }; ($ty:ty, $($tys:ty),+) => { impl_gen_prim...
random
[ { "content": "/// Convert a fixed-length (possibly zero-terminated) char buffer to a string.\n\npub fn string_from_fixed_bytes(bytes: &[c_char], len: usize) -> String {\n\n let len = bytes.iter().position(|&c| c == 0).unwrap_or(len);\n\n let s = unsafe { str::from_utf8_unchecked(&*(&bytes[..len] as *const...
Rust
src/bin/main/trajectory.rs
mdp2021s129-bot/controller-fw-vet6
a60d8d576cc204e55d2565dafdc60ea0102ef48a
use controller_core::board::lrtimer::Instant as LrInstant; use controller_core::board::motion::{Angle, Duty}; use hdcomm_core::rpc::{MoveReqBody, PidParamUpdateReqBody, PidParams}; use pid::Pid; use rtic::rtic_monotonic::Milliseconds; use smlang::statemachine; use controller_fw::board::startup::{Steering, Wheels}; p...
use controller_core::board::lrtimer::Instant as LrInstant; use controller_core::board::motion::{Angle, Duty}; use hdcomm_core::rpc::{MoveReqBody, PidParamUpdateReqBody, PidParams}; use pid::Pid; use rtic::rtic_monotonic::Milliseconds; use smlang::statemachine; use controller_fw::board::startup::{Steering, Wheels}; p...
rn false; } self.process_event(Events::MoveRequest).is_ok() } pub fn move_cancel(&mut self) -> bool { self.process_event(Events::MoveCancelRequest).is_ok() } fn move_complete(&self) -> bool { match self.state() { States::MoveInP...
e_interval_ms: 10, wheels, steering, move_context: None, initial_positions: None, } } } impl StateMachine<ControllerContext> { pub fn poll_encoders(&mut self) { self.context_mut() .wheels .read_and_update_positions() ...
random
[ { "content": "/// Terminates the application and makes `probe-run` exit with exit-code = 0\n\npub fn exit() -> ! {\n\n loop {\n\n cortex_m::asm::bkpt();\n\n }\n\n}\n", "file_path": "src/lib.rs", "rank": 0, "score": 41722.259485084454 }, { "content": "/// Starts up the board, ret...
Rust
java-reader/src/operations.rs
Kineolyan/project-tz-io
045bbef5827fd4d6bc3699025f0f7b8cec8523c4
use pool::{PoolList, resolve_method_name, resolve_class_name, resolve_field_name}; use printer::{print_bytes}; use reader::{Reader, ByteReader, ReadResult, to_u16}; use types::{ARRAY_TYPES}; fn print_op(name: &str) { println!("[{}]", name); } fn are_same_decimal(before: usize, now: usize) -> bool { let b = before...
use pool::{PoolList, resolve_method_name, resolve_class_name, resolve_field_name}; use printer::{print_bytes}; use reader::{Reader, ByteReader, ReadResult, to_u16}; use types::{ARRAY_TYPES}; fn print_op(name: &str) { println!("[{}]", name); } fn are_same_decimal(before: usize, now: usize) -> bool { let b = before...
fn read_new(reader: &mut Reader, pool: &PoolList, indent: u8) -> ReadResult { print_op("new"); read_u16!(class_idx, reader, indent + 1); let class_name = resolve_class_name(pool, class_idx as usize) .expect(&format!("No class name in pool at {}", class_idx)); println!("New {}", class_name); Ok(()) } f...
invoke_dynamic(reader: &mut Reader, pool: &PoolList, indent: u8) -> ReadResult { print_op("invokeinterface"); read_u16!(method_idx, reader, indent + 1); let (ref class_name, ref method_name, ref descriptor) = resolve_method_name(pool, method_idx as usize) .expect(&format!("No method reference in pool at {}", ...
function_block-function_prefixed
[ { "content": "fn read_field_name(reader: &mut Reader, pool: &PoolList, indent: u8) -> ReadResult {\n\n\tread_u16!(name_idx, reader, indent);\n\n\tlet method_name = resolve_utf8_value(pool, name_idx as usize)\n\n\t\t.expect(&format!(\n\n\t\t\t\"Field name not in the constant pool at {}\",\n\n\t\t\tname_idx));\n\...
Rust
src/dumbo_octopus.rs
ktsimpso/adventofcode2021
d3136aeef85c5b0400bfcdd441ba4f54d2df0463
use adventofcode2021::{default_sub_command, parse_usize, CommandResult, Problem}; use clap::{value_t_or_exit, App, Arg, ArgMatches}; use nom::{ bytes::complete::take, character::complete::newline, combinator::map_parser, multi::{many0, separated_list0}, IResult, }; use std::collections::HashSet; use...
use adventofcode2021::{default_sub_command, parse_usize, CommandResult, Problem}; use clap::{value_t_or_exit, App, Arg, ArgMatches}; use nom::{ bytes::complete::take, character::complete::newline, combinator::map_parser, multi::{many0, separated_list0}, IResult, }; use std::collections::HashSet; use...
.arg( Arg::with_name("simulation-parameters") .short("s") .help( "How long the octopi should be simulated for. The functions available are as follows:\n\n\ one-hundred-steps: Counts the number of flashes that happen after 100 steps.\n\n\ synchroniz...
default_sub_command( &DUMBO_OCTOPUS, "Simulates dumbo octopi flashing behavoir.", "Path to the input file. Input should be newline delimited sets of 10 integers from 0-9.", "Counts the number of flashes after 100 steps.", "Counts the number of iterartions before all octopi flash....
call_expression
[ { "content": "fn sub_command() -> App<'static, 'static> {\n\n default_sub_command(\n\n &CHITON,\n\n \"Finds the least risky path from top left to bottom right then sums the risk.\",\n\n \"Path to the input file. Input should be newline delimited ranges of integers.\",\n\n \"Search...
Rust
src/text-to-speech/customisations/custom_prompts.rs
kawaki-san/ibm-watson
ec9e8693702d1830b00bfd4127e204f5c1817673
use async_trait::async_trait; use serde::{Deserialize, Serialize}; use crate::{ tts::{prompts::Prompt, TextToSpeech}, util::error::{Error, ResponseContent}, }; #[derive(Debug, Clone, Serialize, Deserialize)] #[serde(untagged)] pub enum TtsAddPromptError { Status400(crate::util::Response), Status401(cr...
use async_trait::async_trait; use serde::{Deserialize, Serialize}; use crate::{ tts::{prompts::Prompt, TextToSpeech}, util::error::{Error, ResponseContent}, }; #[derive(Debug, Clone, Serialize, Deserialize)] #[serde(untagged)] pub enum TtsAddPromptError { Status400(crate::util::Response), Status401(cr...
async fn delete_prompt( &self, customization_id: &str, prompt_id: &str, ) -> Result<crate::util::Response, Error<TtsDeletePromptError>> { let local_var_configuration = &self.configuration; let local_var_client = &local_var_configuration.client; let local_var_u...
local_var_form_params.insert("prompt_text", prompt_text.to_string()); if let Some(local_var_param_value) = speaker_id { local_var_form_params.insert("speaker_id", local_var_param_value.to_string()); } local_var_req_builder = local_var_req_builder.form(&local_var_form_params); ...
function_block-function_prefix_line
[]
Rust
src/library/cli.rs
Bendasch/rust-chess
aecc217706425ae7a2d983a0fc475efcbde779a5
use crate::library::game::*; use std::{collections::LinkedList, fmt, io}; const WHITE_ROOK: char = '\u{265C}'; const WHITE_KNIGHT: char = '\u{265E}'; const WHITE_BISHOP: char = '\u{265D}'; const WHITE_QUEEN: char = '\u{265B}'; const WHITE_KING: char = '\u{265A}'; const WHITE_PAWN: char = '\u{265F}'; const BLACK_ROOK: ...
use crate::library::game::*; use std::{collections::LinkedList, fmt, io}; const WHITE_ROOK: char = '\u{265C}'; const WHITE_KNIGHT: char = '\u{265E}'; const WHITE_BISHOP: char = '\u{265D}'; const WHITE_QUEEN: char = '\u{265B}'; const WHITE_KING: char = '\u{265A}'; const WHITE_PAWN: char = '\u{265F}'; const BLACK_ROOK: ...
let mut move_string = String::new(); io::stdin().read_line(&mut move_string).unwrap(); match move_string.trim() { ">" => { if game.inactive_states.len() == 0 { println!("No moves to redo!"); continu...
match current_state.check_game_over() { GameOver::BlackWon => { println!("Checkmate, black won!"); return; } GameOver::WhiteWon => { println!("Checkmate, white won!"); return; } GameOver::Stalemat...
if_condition
[ { "content": "pub fn handle_state(new_state: Result<State, MoveError>, game: &mut GameState) {\n\n use MoveError::*;\n\n match new_state {\n\n Ok(new_state) => {\n\n game.active_states.push_back(new_state);\n\n game.inactive_states.clear();\n\n },\n\n Err(OutOfBo...
Rust
src/mac/hmac.rs
zonyitoo/crypto2
4fa0d00b146d4dd1477cc5ffef5566e0c5e1ca43
use crate::hash::{ Md2, Md4, Md5, Sm3, Sha1, Sha224, Sha256, Sha384, Sha512, }; const IPAD: u8 = 0x36; const OPAD: u8 = 0x5C; macro_rules! impl_hmac_with_hasher { ($name:tt, $hasher:tt) => { #[derive(Clone)] pub struct $name { okey: [u8; Self::BLOCK_LEN], hasher: $hasher,...
use crate::hash::{ Md2, Md4, Md5, Sm3, Sha1, Sha224, Sha256, Sha384, Sha512, }; const IPAD: u8 = 0x36; const OPAD: u8 = 0x5C; macro_rules! impl_hmac_with_hasher { ($name:tt, $hasher:tt) => { #[derive(Clone)] pub struct $name { okey: [u8; Self::BLOCK_LEN], hasher: $hasher,...
#[test] fn test_hmac_sha2_512() { let key = b"key"; let data = b"The quick brown fox jumps over the lazy dog"; let result = "b42af09057bac1e2d41708e48a902e09b5ff7f12ab428a4fe86653c73dd248fb82f948a549f7b791a5b41915ee4d1ec3935357e4e2317250d0372afa2ebeeb3a"; assert_eq!(&hex::encode(&HmacSha512::oneshot(k...
let result = "d7f4727e2c0b39ae0f1e40cc96f60242d5b7801841cea6fc592c5d3e1ae50700582a96cf35e1e554995fe4e03381c237"; assert_eq!(&hex::encode(&HmacSha384::oneshot(key, data)), result); }
function_block-function_prefix_line
[ { "content": "/// SHA2-384\n\npub fn sha384<T: AsRef<[u8]>>(data: T) -> [u8; Sha384::DIGEST_LEN] {\n\n Sha384::oneshot(data)\n\n}\n\n\n", "file_path": "src/hash/sha2/sha512/mod.rs", "rank": 8, "score": 279159.6698022444 }, { "content": "/// SHA2-224\n\npub fn sha224<T: AsRef<[u8]>>(data: ...
Rust
src/device/request.rs
bstrie/cannyls
caa83e3588b03fba629e9c7de36b61370cdaf5e5
use futures::Future; use std::ops::Range; use trackable::error::ErrorKindExt; use super::thread::DeviceThreadHandle; use crate::deadline::Deadline; use crate::device::command::{self, Command}; use crate::device::DeviceStatus; use crate::lump::{LumpData, LumpHeader, LumpId}; use crate::storage::StorageUsage; use crate:...
use futures::Future; use std::ops::Range; use trackable::error::ErrorKindExt; use super::thread::DeviceThreadHandle; use crate::deadline::Deadline; use crate::device::command::{self, Command}; use crate::device::DeviceStatus; use crate::lump::{LumpData, LumpHeader, LumpId}; use crate::storage::StorageUsage; use crate:...
Ok(()) } }
if let Some(max) = self.max_queue_len { track_assert!( metrics.queue_len() <= max, ErrorKind::DeviceBusy, "value={}, max={}", metrics.queue_len(), max ); }
if_condition
[]
Rust
src/scene.rs
mark2b/fb-2d
fa61032802aa29c138c8e6aaeacd7732c9933691
use std::cell; use std::collections::*; use std::time; use std::thread::sleep; use screen_writer::{ScreenInfo, ScreenWriter}; use dimension::*; use node::*; pub struct SceneState { pub running: bool, } type OnEveryFrame = fn(state: SceneState) -> SceneState; pub struct Scene<'a> { pub writer: Option<Box<Scr...
use std::cell; use std::collections::*; use std::time; use std::thread::sleep; use screen_writer::{ScreenInfo, ScreenWriter}; use dimension::*; use node::*; pub struct SceneState { pub running: bool, } type OnEveryFrame = fn(state: SceneState) -> SceneState; pub struct Scene<'a> { pub writer: Option<Box<Scr...
fn layout(&self, screen_info: &ScreenInfo) { let frame_rect = Rect { size: Size { width: screen_info.xres, height: screen_info.yres, }, pos: POS_ZERO, }; if let Some(ref root_node) = self.nodes.get(&self.root_node_key) { ...
pub fn add_node(&mut self, node: Node<'a>, to_key: NodeKey) { let mut found = false; if let Some(key_cell) = self.hierarchy.get(&to_key) { let mut children_keys = key_cell.borrow_mut(); children_keys.push(node.key); found = true; } if !found { ...
function_block-full_function
[ { "content": "pub fn screen_writer_for_png(\n\n filename: &str,\n\n width: u32,\n\n height: u32,\n\n) -> Result<FrameBufferSimulatorPNG, String> {\n\n FrameBufferSimulatorPNG::new(filename, width, height)\n\n}\n\n\n\npub static PIXEL_RGBA: PixelDef = PixelDef {\n\n bits_per_pixel: 32,\n\n byte...
Rust
src/lib.rs
Restioson/barrage
249cd400a8e3b34e4fadfaed30b0c5f5c3dfeaf6
use std::future::Future; use std::pin::Pin; use std::task::{Context, Poll}; use concurrent_queue::ConcurrentQueue; use event_listener::{Event, EventListener}; use std::fmt::Debug; use facade::sync::atomic::{AtomicUsize, Ordering}; use facade::sync::Arc; use facade::*; mod facade; type ReceiverQueue<T> = ConcurrentQ...
use std::future::Future; use std::pin::Pin; use std::task::{Context, Poll}; use concurrent_queue::ConcurrentQueue; use event_listener::{Event, EventListener}; use std::fmt::Debug; use facade::sync::atomic::{AtomicUsize, Ordering}; use facade::sync::Arc; use facade::*; mod facade; type ReceiverQueue<T> = ConcurrentQ...
} impl<T: Clone + Unpin> Receiver<T> { pub fn recv(&self) -> Result<T, Disconnected> { self.0.recv() } pub fn try_recv(&self) -> Result<Option<T>, Disconnected> { self.0.try_recv() } pub fn recv_async(&self) -> RecvFut<T> { self.0.recv_async(...
fn recv_async(&self) -> RecvFut<T> { RecvFut { receiver: &self, event_listener: None, } }
function_block-full_function
[ { "content": "struct PollOnce<'a, F: Future + Unpin>(&'a mut F);\n\n\n\nimpl<'a, F: Future + Unpin> Future for PollOnce<'a, F> {\n\n type Output = Poll<F::Output>;\n\n\n\n fn poll(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Self::Output> {\n\n Poll::Ready(Pin::new(&mut self.0).poll(cx))...
Rust
src/repo/mod.rs
ynt/gitstar
c5191e9920551b80d1b05563a30e4990fc22bebf
use super::error::Error; use super::page::Page; #[derive(Default, Debug)] pub struct BaseInfo { pub id: i64, pub repo_name: String, pub username: String, pub language: String, } impl BaseInfo { pub fn new(id: i64, repo_name: &str, username: &str, language: &str) -> Self { BaseInfo { ...
use super::error::Error; use super::page::Page; #[derive(Default, Debug)] pub struct BaseInfo { pub id: i64, pub repo_name: String, pub username: String, pub language: String, } impl BaseInfo { pub fn new(id: i64, repo_name: &str, username: &str, language: &str) -> Self { BaseInfo { ...
pub fn get_full_name(&self) -> Result<String, Error> { if self.repo_name.is_empty() { Err(Error::new("BaseInfo feild repo_name is empty".to_owned())) } else if self.username.is_empty() { Err(Error::new("BaseInfo feild username is empty".to_owned())) } else { ...
let mut url = String::from("https://api.github.com/search/repositories?q=language:"); url.push_str(&self.language); url.push_str("&sort=stars&order=desc"); let mut page = Page::new(&url, 100); page.get_items = true; Ok(page) }
function_block-function_prefix_line
[ { "content": "pub fn get(url: &str) -> Response {\n\n let resp = request(url);\n\n\n\n if let Err(Error::ReqwestErr(e)) = resp {\n\n match e.get_ref().and_then(|e| e.downcast_ref::<io::Error>()) {\n\n Some(err) => {\n\n println!(\"{}, timeout or io error.\", err);\n\n ...
Rust
src/bin/niced/main.rs
sbeckeriv/personal_search
315c0e46e6271c613be6d67456323b8116490c8d
use personal_search::indexer; use std::collections::HashMap; use tantivy::collector::FacetCollector; use tantivy::collector::TopDocs; use tantivy::doc; use tantivy::query::AllQuery; use tantivy::query::QueryParser; use iced::{ button, scrollable, text_input, Align, Application, Button, Checkbox, Clipboard, Column...
use personal_search::indexer; use std::collections::HashMap; use tantivy::collector::FacetCollector; use tantivy::collector::TopDocs; use tantivy::doc; use tantivy::query::AllQuery; use tantivy::query::QueryParser; use iced::{ button, scrollable, text_input, Align, Application, Button, Checkbox, Clipboard, Column...
#[derive(Debug)] enum Search { Loading, Loaded(State), } #[derive(Debug, Default)] struct State { scroll: scrollable::State, input: text_input::State, input_value: String, results: Vec<SearchJson>, dirty: bool, saving: bool, } #[derive(Debug, Clone)] enum Message { Loaded(Result<...
r("") .to_string(), description: m .get("description") .map(|t| t.get(0).map(|f| f.text().unwrap_or("")).unwrap()) .unwrap_or("") .to_string(), added_at: m .get("added_at") .map(|t| t.get(0).map(|f| f.text().unwrap_or(""...
function_block-function_prefixed
[ { "content": "fn search(query: String, index: tantivy::Index, _debug: bool) {\n\n let searcher = indexer::searcher(&index);\n\n let default_fields: Vec<tantivy::schema::Field> = index\n\n .schema()\n\n .fields()\n\n .filter(|&(_, ref field_entry)| match *field_entry.field_type() {\n\n...
Rust
src/fb/csmr.rs
stv0g/k66
7c056251184ec8b4aec9c4ecec49db74567cc484
#[doc = r" Value read from the register"] pub struct R { bits: u32, } #[doc = r" Value to write to the register"] pub struct W { bits: u32, } impl super::CSMR { #[doc = r" Modifies the contents of the register"] #[inline] pub fn modify<F>(&self, f: F) where for<'w> F: FnOnce(&R, &'w mut ...
#[doc = r" Value read from the register"] pub struct R { bits: u32, } #[doc = r" Value to write to the register"] pub struct W { bits: u32, } impl super::CSMR { #[doc = r" Modifies the contents of the register"] #[inline] pub fn modify<F>(&self, f: F) where for<'w> F: FnOnce(&R, &'w mut ...
} #[doc = "The corresponding address bit in CSAR is a don't care in the chip-select decode."] #[inline] pub fn _1(self) -> &'a mut W { self.variant(BAMW::_1) } #[doc = r" Writes raw bits to the field"] #[inline] pub unsafe fn bits(self, value: u16) -> &'a mut W { const MASK: ...
} } #[doc = "Write accesses are allowed."] #[inline] pub fn _0(self) -> &'a mut W { self.variant(WPW::_0) } #[doc = "Write accesses are not allowed. Attempting to write to the range of addresses for which the WP bit is set results in a bus error termination of the internal cycle and no ...
random
[ { "content": " #[doc = r\" Sets the field bit\"]\n\n pub fn set_bit(self) -> &'a mut W {\n\n self.bit(true)\n\n }\n\n #[doc = r\" Clears the field bit\"]\n\n pub fn clear_bit(self) -> &'a mut W {\n\n self.bit(false)\n\n }\n\n #[doc = r\" Writes raw bits to the field\"]\n\n ...
Rust
src/p2p/packet.rs
SEP-G5/Blockchain
c69f4d729bfe3f9f6a026c0be591087744c2d8c6
use crate::blockchain::{block::Block, hash::Hash, transaction::Transaction}; use bytes::buf::BufMut; use bytes::BytesMut; use serde::{Deserialize, Serialize}; use std::fmt; use std::io; use std::net::SocketAddr; use tokio_util::codec::{Decoder, Encoder}; #[derive(Serialize, Deserialize, Debug, Clone)] pub enum Packet ...
use crate::blockchain::{block::Block, hash::Hash, transaction::Transaction}; use bytes::buf::BufMut; use bytes::BytesMut; use serde::{Deserialize, Serialize}; use std::fmt; use std::io; use std::net::SocketAddr; use tokio_util::codec::{Decoder, Encoder}; #[derive(Serialize, Deserialize, Debug, Clone)] pub enum Packet ...
} }, }; let size = bincode::serialized_size(&packet).unwrap() as usize; buf.split_to(size); Ok(Some(packet)) } fn to_bytes_mut(&self, buf: &mut BytesMut) -> Option<PacketErr> { let tmp_vec = match bincode::serialize(self) { ...
Err(PacketErr::Deserialize(format!( "failed to deserialize packet (size: {}) [{:?}]", buf.len(), e )))
call_expression
[ { "content": "pub fn make_timestamp() -> Timestamp {\n\n let ts = SystemTime::now()\n\n .duration_since(SystemTime::UNIX_EPOCH)\n\n .expect(\"failed to make timestamp\");\n\n return ts.as_secs() as Timestamp;\n\n}\n", "file_path": "src/blockchain/util.rs", "rank": 0, "score": 686...
Rust
src/client.rs
c3systems/c3-sdk-rust
193b47b5d8145b0036d2970f1864ae9c94c4e111
extern crate regex; extern crate serde; extern crate serde_json; use std::str; use std::collections::HashMap; use std::fs::File; use std::io::{Read, BufWriter, Write}; use std::net::{TcpStream, TcpListener}; use std::env; use self::regex::Regex; #[derive(Serialize, Deserialize, Default)] pub struct State { store:...
extern crate regex; extern crate serde; extern crate serde_json; use std::str; use std::collections::HashMap; use std::fs::File; use std::io::{Read, BufWriter, Write}; use std::net::{TcpStream, TcpListener}; use std::env; use self::regex::Regex; #[derive(Serialize, Deserialize, Default)] pub struct State { store:...
fn process_payload(&mut self, payload: String) { let json = clean_json(&payload); println!("processing; received {}", json); let params: [String; 3] = serde_json::from_str(&json).unwrap(); let method_name = params[0].to_string(); let mut args: [String; 2] = Default::default(...
fn set_initial_state(&mut self) { println!("initial state"); let mut data = String::new(); let mut f = File::open("/tmp/state.json".to_string()).expect("Unable to open file"); f.read_to_string(&mut data).expect("Unable to read file"); let store: HashMap<String, String> = serde_j...
function_block-full_function
[ { "content": "pub fn hash_to_hex_string(data: Vec<u8>) -> String {\n\n let mut hasher = Sha512Trunc256::new();\n\n\n\n hasher.input(data);\n\n\n\n let result = hasher.result();\n\n return hexutil::add_prefix(format!(\"{:x}\", result));\n\n}\n\n\n", "file_path": "src/hashutil.rs", "rank": 1, ...
Rust
src/ahb_secure_ctrl/sec_ctrl_apb_bridge_slave_rule.rs
conorpp/lpc55-pac
eb30d633de05113362de01095123d70c54e63ef4
#[doc = "Reader of register SEC_CTRL_APB_BRIDGE_SLAVE_RULE"] pub type R = crate::R<u32, super::SEC_CTRL_APB_BRIDGE_SLAVE_RULE>; #[doc = "Writer for register SEC_CTRL_APB_BRIDGE_SLAVE_RULE"] pub type W = crate::W<u32, super::SEC_CTRL_APB_BRIDGE_SLAVE_RULE>; #[doc = "Register SEC_CTRL_APB_BRIDGE_SLAVE_RULE `reset()`'s wi...
#[doc = "Reader of register SEC_CTRL_APB_BRIDGE_SLAVE_RULE"] pub type R = crate::R<u32, super::SEC_CTRL_APB_BRIDGE_SLAVE_RULE>; #[doc = "Writer for register SEC_CTRL_APB_BRIDGE_SLAVE_RULE"] pub type W = crate::W<u32, super::SEC_CTRL_APB_BRIDGE_SLAVE_RULE>; #[doc = "Register SEC_CTRL_APB_BRIDGE_SLAVE_RULE `reset()`'s wi...
} } #[doc = "Checks if the value of the field is `ENUM_NS_NP`"] #[inline(always)] pub fn is_enum_ns_np(&self) -> bool { *self == APBBRIDGE0_RULE_A::ENUM_NS_NP } #[doc = "Checks if the value of the field is `ENUM_NS_P`"] #[inline(always)] pub fn is_enum_ns_p(&self) -> bool { ...
ch self.bits { 0 => APBBRIDGE0_RULE_A::ENUM_NS_NP, 1 => APBBRIDGE0_RULE_A::ENUM_NS_P, 2 => APBBRIDGE0_RULE_A::ENUM_S_NP, 3 => APBBRIDGE0_RULE_A::ENUM_S_P, _ => unreachable!(),
function_block-random_span
[ { "content": "#[doc = \"Reader of register SEC_CTRL_RAM4_SLAVE_RULE\"]\n\npub type R = crate::R<u32, super::SEC_CTRL_RAM4_SLAVE_RULE>;\n\n#[doc = \"Writer for register SEC_CTRL_RAM4_SLAVE_RULE\"]\n\npub type W = crate::W<u32, super::SEC_CTRL_RAM4_SLAVE_RULE>;\n\n#[doc = \"Register SEC_CTRL_RAM4_SLAVE_RULE `rese...
Rust
src/integer/ops/division_assign.rs
declanvk/rimath
e0dbb421d6da09a8b5e92fc9f0d00e5a454e3118
use crate::integer::Integer; use core::ops::DivAssign; impl DivAssign<Integer> for Integer { fn div_assign(&mut self, rhs: Integer) { Integer::divide_assign(self, &rhs) } } impl DivAssign<&Integer> for Integer { fn div_assign(&mut self, rhs: &Integer) { Integer::divide_assign(self, rhs) ...
use crate::integer::Integer; use core::ops::DivAssign; impl DivAssign<Integer> for Integer { fn div_assign(&mut self, rhs: Integer) { Integer::divide_assign(self, &rhs) } } impl DivAssign<&Integer> for Integer { fn div_assign(&mut self, rhs: &Integer) { Integer::divide_assign(self, rhs) ...
ign(self, &Integer::from(rhs)) } } impl DivAssign<&u64> for Integer { fn div_assign(&mut self, rhs: &u64) { Integer::divide_assign(self, &Integer::from(*rhs)) } } impl DivAssign<i128> for Integer { fn div_assign(&mut self, rhs: i128) { Integer::divide_assign(self, &Integer::from(rhs)) ...
Integer::divide_c_long_assign(self, *rhs) } } impl DivAssign<u16> for Integer { fn div_assign(&mut self, rhs: u16) { Integer::divide_c_long_assign(self, rhs) } } impl DivAssign<&u16> for Integer { fn div_assign(&mut self, rhs: &u16) { Integer::divide_c_long_assign(self, *rhs) } } ...
random
[ { "content": "fn fib_iter() -> impl Iterator<Item = Integer> {\n\n struct FibIter {\n\n x: Integer,\n\n y: Integer,\n\n }\n\n\n\n impl Iterator for FibIter {\n\n type Item = Integer;\n\n\n\n fn next(&mut self) -> Option<Integer> {\n\n let next_y = &self.x + &self....
Rust
src/main.rs
UARTman/chip8
605e21dc586061a4099aff2262cd7cf1fc2989f4
#![deny(clippy::all)] #![forbid(unsafe_code)] #![windows_subsystem = "windows"] use crate::gui::Gui; use crate::world::World; use log::error; use pixels::{Error, Pixels, SurfaceTexture}; use simple_logger::SimpleLogger; use winit::dpi::LogicalSize; use winit::event::{Event, VirtualKeyCode}; use winit::event_loop::{Con...
#![deny(clippy::all)] #![forbid(unsafe_code)] #![windows_subsystem = "windows"] use crate::gui::Gui; use crate::world::World; use log::error; use pixels::{Error, Pixels, SurfaceTexture}; use simple_logger::SimpleLogger; use winit::dpi::LogicalSize; use winit::event::{Event, VirtualKeyCode}; use winit::event_loop::{Con...
alSize::new(WIDTH as f64, HEIGHT as f64); WindowBuilder::new() .with_title("Hello Pixels + egui") .with_inner_size(size) .with_min_inner_size(size) .build(&event_loop) .unwrap() }; let (mut pixels, mut gui) = { let window_size = window...
n main() -> Result<(), Error> { SimpleLogger::new() .with_level(log::LevelFilter::Off) .with_module_level("chip8", log::LevelFilter::Trace) .init() .unwrap(); let event_loop = EventLoop::new(); let mut input = WinitInputHelper::new(); let window = { let size = Log...
function_block-random_span
[ { "content": "mod execution;\n\nmod graphics;\n\nmod ui;\n\n\n\n#[rustfmt::skip]\n\nstatic SPRITES: [u8; 80] = [\n\n 0xF0, 0x90, 0x90, 0x90, 0xF0,\n\n 0x20, 0x60, 0x20, 0x20, 0x70,\n\n 0xF0, 0x10, 0xF0, 0x80, 0xF0,\n\n 0xF0, 0x10, 0xF0, 0x10, 0xF0,\n\n 0x90, 0x90, 0xF0, 0x10, 0x10,\n\n 0xF0, 0...
Rust
src/sequence/metadata.rs
joshuef/sn_data_types
0eb5c2536fafc90a8e90291e5c9eb571b7721e32
use crate::{utils, Error, PublicKey, Result, XorName}; use multibase::Decodable; use serde::{Deserialize, Serialize}; use std::{collections::BTreeMap, fmt::Debug, hash::Hash}; #[derive(Clone, Copy, Eq, PartialEq)] pub enum Action { Read, Append, ManagePermissions, } pub type Entries = Vec...
use crate::{utils, Error, PublicKey, Result, XorName}; use multibase::Decodable; use serde::{Deserialize, Serialize}; use std::{collections::BTreeMap, fmt::Debug, hash::Hash}; #[derive(Clone, Copy, Eq, PartialEq)] pub enum Action { Read, Append, ManagePermissions, } pub type Entries = Vec...
} None => Err(Error::AccessDenied), } } fn user_permissions(&self, user: User) -> Option<UserPermissions> { match user { User::Anyone => None, User::Key(key) => self .permissions .get(&key) .ma...
if perms.is_allowed(action) { Ok(()) } else { Err(Error::AccessDenied) }
if_condition
[ { "content": "// Type of data used for the 'Actor' in CRDT vector clocks\n\ntype ActorType = PublicKey;\n\n\n\n/// Public Sequence.\n\npub type PubSeqData = SequenceCrdt<ActorType, PubPermissions>;\n\n/// Private Sequence.\n\npub type PrivSeqData = SequenceCrdt<ActorType, PrivPermissions>;\n\n\n\nimpl Debug for...
Rust
goko/src/plugins/discrete/tracker.rs
elastic/goko
55b3dff9c179eaa4d89d982926a89bfb969419cb
use crate::covertree::CoverTreeReader; use crate::plugins::*; use hashbrown::HashMap; use super::categorical::*; use super::dirichlet::*; use statrs::function::gamma::{digamma, ln_gamma}; use serde::{Deserialize, Serialize}; use std::fmt; use std::collections::VecDeque; pub struct BayesCategoricalTracker<D: Poin...
use crate::covertree::CoverTreeReader; use crate::plugins::*; use hashbrown::HashMap; use super::categorical::*; use super::dirichlet::*; use statrs::function::gamma::{digamma, ln_gamma}; use serde::{Deserialize, Serialize}; use std::fmt; use std::collections::VecDeque; pub struct BayesCategoricalTracker<D: Poin...
#[test] fn dirichlet_tree_append_test() { let mut tree = build_basic_tree(); tree.add_plugin::<GokoDirichlet>(GokoDirichlet::default()); let mut tracker = BayesCategoricalTracker::new(0, tree.reader()); assert_approx_eq!(tracker.kl_div(), 0.0); tracker.add_path(vec![ ...
fn dirichlet_tree_probs_test() { let mut tree = build_basic_tree(); tree.add_plugin::<GokoDirichlet>(GokoDirichlet::default()); let mut tracker = BayesCategoricalTracker::new(0, tree.reader()); assert_approx_eq!(tracker.kl_div(), 0.0); tracker.add_path(vec![ (0.0, (-1...
function_block-full_function
[ { "content": "#[allow(clippy::type_complexity)]\n\npub fn new<K, V>() -> (\n\n MonoReadHandle<K, V, (), FxBuildHasher>,\n\n MonoWriteHandle<K, V, (), FxBuildHasher>,\n\n)\n\nwhere\n\n K: Eq + Hash + Clone,\n\n V: Clone,\n\n{\n\n MonoOptions::default().construct()\n\n}\n\n\n\n/// Create an empty e...
Rust
daemon/src/collab_settlement_maker.rs
comit-network/hermes
74e939c4c9784a07c3bf6d9d4e1ed69ef4cf3831
use crate::address_map::Stopping; use crate::cfd_actors::load_cfd; use crate::maker_inc_connections; use crate::model::cfd::CollaborativeSettlementCompleted; use crate::model::cfd::Completed; use crate::model::cfd::SettlementProposal; use crate::model::Identity; use crate::process_manager; use anyhow::Context; use anyh...
use crate::address_map::Stopping; use crate::cfd_actors::load_cfd; use crate::maker_inc_connections; use crate::model::cfd::CollaborativeSettlementCompleted; use crate::model::cfd::Completed; use crate::model::cfd::SettlementProposal; use crate::model::Identity; use crate::process_manager; use anyhow::Context; use anyh...
async fn handle_proposal(&mut self) -> Result<()> { let mut conn = self.db.acquire().await?; let cfd = load_cfd(self.proposal.order_id, &mut conn).await?; let event = cfd.receive_collaborative_settlement_proposal(self.proposal.clone())?; self.process_manager .send(proc...
ss<process_manager::Actor>, (on_stopping0, on_stopping1): ( &(impl MessageChannel<Stopping<Self>> + 'static), &(impl MessageChannel<Stopping<Self>> + 'static), ), db: sqlx::SqlitePool, ) -> Self { Self { proposal, taker_id, ...
function_block-function_prefixed
[ { "content": "/// Connects to the SQLite database at the given path.\n\n///\n\n/// If the database does not exist, it will be created. If it does exist, we load it and apply all\n\n/// pending migrations. If applying migrations fails, the old database is backed up next to it and a\n\n/// new one is created.\n\n...
Rust
hbar-core/src/common/bit_matrix.rs
lyl120117/zxing-rs
421f1e57fa589e442e432a0670a9855bcef4cc3d
use crate::{Error, ResultError}; #[derive(Debug, Clone)] pub struct BitMatrix { pub width: i32, pub height: i32, pub row_size: i32, pub bits: Vec<i32>, } impl BitMatrix { /** * Creates an empty square {@code BitMatrix}. * * @param dimension height and width */ pub fn new1(d...
use crate::{Error, ResultError}; #[derive(Debug, Clone)] pub struct BitMatrix { pub width: i32, pub height: i32, pub row_size: i32, pub bits: Vec<i32>, } impl BitMatrix { /** * Creates an empty square {@code BitMatrix}. * * @param dimension height and width */ pub fn new1(d...
eight || right > self.width { panic!("The region must fit inside the matrix") } for y in top..bottom { let offset = y * self.row_size; for x in left..right { self.bits[(offset + (x / 32)) as usize] |= 1 << (x & 0x1f); } } } ...
or<BitMatrix> { let height = image.len() as i32; let width = image[0].len() as i32; let mut bits = BitMatrix::new2(width, height)?; for i in 0..height { let imageI = &image[i as usize]; for j in 0..width { if imageI[j as usize] { ...
random
[ { "content": "pub fn usize_to_i32(i: usize) -> ResultError<i32> {\n\n match i32::try_from(i) {\n\n Ok(v) => Ok(v),\n\n Err(_) => Err(Error::TryFromIntError(format!(\n\n \"Error converting usize: {} to i32!\",\n\n i\n\n ))),\n\n }\n\n}\n\n\n", "file_path": "hb...
Rust
src/tui.rs
Dinoosawruss/templa-rs
80a82c7dcffb52090a7a91bdde2e5df7375f5000
use crate::app::App; use crate::command; use crate::models::{enums, structs::Submodule}; use crossterm::{ event::{self, Event as CEvent, KeyCode, KeyModifiers}, execute, terminal::{disable_raw_mode, enable_raw_mode, EnterAlternateScreen, LeaveAlternateScreen}, }; use std::io; use std::str; use std::sync::mp...
use crate::app::App; use crate::command; use crate::models::{enums, structs::Submodule}; use crossterm::{ event::{self, Event as CEvent, KeyCode, KeyModifiers}, execute, terminal::{disable_raw_mode, enable_raw_mode, EnterAlternateScreen, LeaveAlternateScreen}, }; use std::io; use std::str; use std::sync::mp...
.style(Style::default().fg(skin_color)), ) .style(Style::default().fg(Color::White)) } fn render_template_list<'a>(filtered_submodules: &[Submodule], skin_color: Color) -> List<'a> { let title_span = Span::styled( " Available Templates ", Style::default().fg(skin_color).add_mod...
Modifiers::NONE) => { app.current_query.push(key); } (KeyCode::Char(key), KeyModifiers::SHIFT) => { app.current_query.push(key.to_ascii_uppercase()); } (KeyCode::Backspace, KeyModifiers::NONE) => { ...
random
[ { "content": "pub fn get_repo_size(url: &str) -> usize {\n\n let client = Client::builder()\n\n .user_agent(\"templa-rs, https://github.com/IEEE-VIT/templa-rs\")\n\n .build()\n\n .unwrap();\n\n let res: Response = client\n\n .get(format!(\n\n \"https://api.github.com...
Rust
bindings/python/src/pre_tokenizers.rs
Narsil/tokenizers
76b86f69019db3efb0cfecac1ec5d101b888023b
use std::sync::Arc; use pyo3::exceptions; use pyo3::prelude::*; use pyo3::types::*; use serde::ser::SerializeStruct; use serde::{Deserialize, Deserializer, Serialize, Serializer}; use tk::pre_tokenizers::bert::BertPreTokenizer; use tk::pre_tokenizers::byte_level::ByteLevel; use tk::pre_tokenizers::delimiter::CharDeli...
use std::sync::Arc; use pyo3::exceptions; use pyo3::prelude::*; use pyo3::types::*; use serde::ser::SerializeStruct; use serde::{Deserialize, Deserializer, Serialize, Serializer}; use tk::pre_tokenizers::bert::BertPreTokenizer; use tk::pre_tokenizers::byte_level::ByteLevel; use tk::pre_tokenizers::delimiter::CharDeli...
} impl<I> From<I> for PyPreTokenizerWrapper where I: Into<PreTokenizerWrapper>, { fn from(norm: I) -> Self { PyPreTokenizerWrapper::Wrapped(Arc::new(norm.into())) } } impl<I> From<I> for PyPreTokenizer where I: Into<PreTokenizerWrapper>, { fn from(pretok: I) -> Self { PyPreTokeniz...
fn serialize<S>(&self, serializer: S) -> Result<<S as Serializer>::Ok, <S as Serializer>::Error> where S: Serializer, { match self { PyPreTokenizerWrapper::Sequence(seq) => { let mut ser = serializer.serialize_struct("Sequence", 2)?; ser.serialize_fiel...
function_block-full_function
[ { "content": "/// Returns a range of the given string slice, by indexing chars instead of bytes\n\npub fn get_range_of<T: RangeBounds<usize>>(s: &str, range: T) -> Option<&str> {\n\n let len = s.chars().count();\n\n let start = match range.start_bound() {\n\n Bound::Unbounded => 0,\n\n Bound...
Rust
crates/rslint_parser/src/syntax/assignment.rs
iamsaquib8/rome
425301c0293dbd884da9ed757b60b0e90ce9ccb7
use crate::event::{rewrite_events, RewriteParseEvents}; use crate::parser::{expected_any, ParsedSyntax, ToDiagnostic}; use crate::syntax::class::parse_initializer_clause; use crate::syntax::expr::{ is_at_identifier, parse_conditional_expr, parse_unary_expr, ExpressionContext, }; use crate::syntax::js_parse_error::{...
use crate::event::{rewrite_events, RewriteParseEvents}; use crate::parser::{expected_any, ParsedSyntax, ToDiagnostic}; use crate::syntax::class::parse_initializer_clause; use crate::syntax::expr::{ is_at_identifier, parse_conditional_expr, parse_unary_expr, ExpressionContext, }; use crate::syntax::js_parse_error::{...
.or_add_diagnostic(p, expected_identifier); JS_OBJECT_ASSIGNMENT_PATTERN_SHORTHAND_PROPERTY } else if is_at_object_member_name(p) || p.at(T![:]) || p.nth_at(1, T![:]) { parse_object_member_name(p).or_add_diagnostic(p, expected_object_member_name); p.expect(T![:])...
parse_assignment( p, AssignmentExprPrecedence::Conditional, ExpressionContext::default(), )
call_expression
[]
Rust
src/expr.rs
Dentosal/constcodegen
09d61a536d729aeda9639d03a52025b401ab1b53
use std::fmt; use crate::functions::Functions; use crate::value::{Context, Primitive}; use lazy_static::lazy_static; use regex::Regex; #[derive(Debug, Clone, PartialEq, Eq)] pub struct Location { string: String, start: usize, len: usize, } impl Location { pub fn new(s: &str, start: usize, len: usize)...
use std::fmt; use crate::functions::Functions; use crate::value::{Context, Primitive}; use lazy_static::lazy_static; use regex::Regex; #[derive(Debug, Clone, PartialEq, Eq)] pub struct Location { string: String, start: usize, len: usize, } impl Location { pub fn new(s: &str, start: usize, len: usize)...
let mut buf_index: usize = buffer.len(); while buf_index > 0 { buf_index -= 1; if buffer[buf_index].0 != level + 1 { buf_index += 1; break; } } le...
if level == 0 && index + 1 < tokens.len() { return Err(tokens[index + 1].error_here(EvalErrorMessage::UnexpectedToken)); }
if_condition
[ { "content": "type F = fn(Location, Vec<Expr>) -> R;\n\n\n\n#[derive(Debug)]\n\npub struct Functions(HashMap<String, F>);\n\nimpl Functions {\n\n pub fn new() -> Self {\n\n Self(HashMap::new())\n\n }\n\n\n\n pub fn default() -> Self {\n\n let mut result = Self::new();\n\n result.in...
Rust
src/runtime.rs
andytesti/mc2wasm
b77903a8cd1ddd61bec2d86606e66d7ac357718c
use std::cell::RefCell; use std::collections::HashMap; use std::fmt::Debug; use std::rc::Rc; use std::rc::Weak; use downcast_rs::Downcast; type ClassId = usize; pub struct Runtime { classes: Vec<StructClassDef>, class_ids: HashMap<&'static str, ClassId>, } impl Runtime { pub fn new() -> Self { S...
use std::cell::RefCell; use std::collections::HashMap; use std::fmt::Debug; use std::rc::Rc; use std::rc::Weak; use downcast_rs::Downcast; type ClassId = usize; pub struct Runtime { classes: Vec<StructClassDef>, class_ids: HashMap<&'static str, ClassId>, } impl Runtime { pub fn new() -> Self { S...
} const ARRAY_CLASS: ArrayClass = ArrayClass; impl HasClassDef for Array { fn class_def<'cl, 'rt: 'cl>(&self, runtime: &'rt Runtime) -> &'cl dyn ClassDef<Self> { &ARRAY_CLASS } } type Number = i32; type Boolean = bool; type ByteArray = Vec<i8>; type Array = Vec<RefCell<Value>>; type WeakReference = ...
fn invoke( &self, runtime: &Runtime, target: &Array, symbol: &'static str, args: &[Value], ) -> McResult { let index = args[0].to_owned().ok_or(Error::InvalidValue(symbol))?; let index = *(index .downcast_ref::<Number>() .ok_or(Error::I...
function_block-full_function
[ { "content": "pub fn symbol(i: Input) -> Result<Id> {\n\n i.pop_token(|t| match t {\n\n Token::Id(v) => Some(Id(*v)),\n\n _ => None,\n\n })\n\n}\n\n\n", "file_path": "src/parser/expr.rs", "rank": 2, "score": 203596.58052065625 }, { "content": "fn sym<'a>(s: &'static str, ...
Rust
src/scene/renderer/mod.rs
06393993/GAMES202-HW-vulkano
b4f627f08d1e1d8103851616db716153bef9ce04
mod mesh_renderer; use std::{cell::RefCell, collections::HashMap, path::PathBuf, sync::Arc}; use euclid::Transform3D; use image::{io::Reader as ImageReader, RgbaImage}; use obj::{Obj, ObjData, ObjMaterial}; use vulkano::{ command_buffer::{ pool::standard::StandardCommandPoolBuilder, AutoCommandBufferBui...
mod mesh_renderer; use std::{cell::RefCell, collections::HashMap, path::PathBuf, sync::Arc}; use euclid::Transform3D; use image::{io::Reader as ImageReader, RgbaImage}; use obj::{Obj, ObjData, ObjMaterial}; use vulkano::{ command_buffer::{ pool::standard::StandardCommandPoolBuilder, AutoCommandBufferBui...
} pub fn load_model_and_texture(&mut self, model_and_texture: ModelAndTexture) -> Result<()> { let position = &model_and_texture.obj.position; let normal = &model_and_texture.obj.normal; let texture_coord: Vec<_> = model_and_texture .obj .texture .it...
Ok(Self { point_light: RefCell::new(point_light), object_renderer, objects: vec![], depth_buffer, render_pass, })
call_expression
[ { "content": "pub trait UniformsT: Send + Sync + 'static {\n\n fn update_buffers(\n\n &self,\n\n cmd_buf_builder: &mut AutoCommandBufferBuilder<StandardCommandPoolBuilder>,\n\n ) -> Result<()>;\n\n fn create_descriptor_sets(\n\n &self,\n\n pipeline_layout: &dyn PipelineLayou...
Rust
rog_fan_curve/src/lib.rs
jtraub/rog_fan_curve
c01a9a728e61768e4d8caa327fa61ca03421ebcb
#[cfg(feature = "serde")] mod serde_impl; use std::io::prelude::*; use std::fmt; use std::fs::OpenOptions; #[derive(Debug)] pub enum CurveError { Acpi(String), InvalidFan(Fan), Io(std::io::Error), } impl fmt::Display for CurveError { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { ...
#[cfg(feature = "serde")] mod serde_impl; use std::io::prelude::*; use std::fmt; use std::fs::OpenOptions; #[derive(Debug)] pub enum CurveError { Acpi(String), InvalidFan(Fan), Io(std::io::Error), } impl fmt::Display for CurveError { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { ...
} #[derive(Debug, Clone, Copy, PartialEq)] pub enum Fan { Cpu, Gpu, } impl Fan { fn address(&self) -> Option<u32> { match self { Fan::Cpu => Some(0x40), Fan::Gpu => Some(0x44), } } } fn make_command(curve: &Curve, fan: u32) -> String { let mut command = "\...
1), "GA401II" => Some(Board::Ga401), "GA401IVC" => Some(Board::Ga401), "GA401IH" => Some(Board::Ga401), "GA401QM" => Some(Board::Ga401), _ => None, } }
function_block-function_prefixed
[ { "content": "struct CurveVisitor;\n\n\n\nimpl<'de> Visitor<'de> for CurveVisitor {\n\n type Value = Curve;\n\n \n\n fn expecting(&self, formatter: &mut fmt::Formatter) -> fmt::Result {\n\n formatter.write_str(\"a rog_fan_curve config string\")\n\n }\n\n \n\n fn visit_str<E>(self, v: &s...
Rust
fuzzer/src/main.rs
aDotInTheVoid/pulldown-cmark
d0119f59c139d810fb354a910b0d7ce4e47e8cbb
use std::env; use std::io::{self, BufRead}; use std::iter; use std::os::unix::process::CommandExt; use std::panic; use std::process::Command; use std::sync::{ atomic::{AtomicU64, Ordering}, Mutex, }; use std::time::{Duration, Instant}; use crossbeam_utils::thread; use pulldown_cmark::{Options, Parser}; use r...
use std::env; use std::io::{self, BufRead}; use std::iter; use std::os::unix::process::CommandExt; use std::panic; use std::process::Command; use std::sync::{ atomic::{AtomicU64, Ordering}, Mutex, }; use std::time::{Duration, Instant}; use crossbeam_utils::thread; use pulldown_cmark::{Options, Parser}; use r...
fn worker_thread_fn( literals: &Vec<Vec<u8>>, num_batches_finished: &AtomicU64, mut rng: Xoshiro256Plus, pattern_time: &Mutex<(Pattern, Instant)>, ) { let pattern_distr = UniformPatterns::new(&literals); loop { for _ in 0..BATCH_SIZE { let pattern = pattern_distr.s...
0 { println!( "Thread timeout triggered (thread took too long) for Pattern: {}\n\ Restarting process...", serde...
function_block-function_prefixed
[ { "content": "#[allow(dead_code)]\n\npub fn pearson_correlation(time_samples: &[(f64, f64)]) -> (f64, bool) {\n\n let mut vec = Vec::with_capacity(time_samples.len());\n\n vec.extend(time_samples.iter().cloned().map(|(x, y)| [x, y]));\n\n let time_samples = Array2::from(vec);\n\n let time_samples = ...
Rust
structural_derive/src/field_access.rs
cor/structural_crates
a0e53d1505f359f13e40f259997d6e2fb55e7011
use crate::{datastructure::StructOrEnum, parse_utils::ParseBufferExt}; #[allow(unused_imports)] use core_extensions::SelfOps; use proc_macro2::TokenStream as TokenStream2; use quote::{quote, ToTokens, TokenStreamExt}; use syn::{ parse::{Parse, ParseStream}, Token, }; #[derive(Debug, Copy, Clone, PartialEq,...
use crate::{datastructure::StructOrEnum, parse_utils::ParseBufferExt}; #[allow(unused_imports)] use core_extensions::SelfOps; use proc_macro2::TokenStream as TokenStream2; use quote::{quote, ToTokens, TokenStreamExt}; use syn::{ parse::{Parse, ParseStream}, Token, }; #[derive(Debug, Copy, Clone, PartialEq,...
pub(crate) fn parse_optional(input: ParseStream<'_>) -> Result<Option<Self>, syn::Error> { if input.peek_parse(Token![ref])?.is_some() { if input.peek_parse(Token![move])?.is_some() { Ok(Some(Access::Value)) } else if input.peek(Token![mut]) { Err(in...
pub(crate) fn compute_trait(self, struct_or_enum: StructOrEnum) -> ComputeTrait { ComputeTrait { access: self, struct_or_enum, } }
function_block-full_function
[ { "content": "fn access(this: impl Array4<u8> + Copy) {\n\n assert_eq!(this.field_(fp!(0)), &3);\n\n assert_eq!(this.field_(fp!(1)), &5);\n\n assert_eq!(this.field_(fp!(2)), &8);\n\n assert_eq!(this.field_(fp!(3)), &13);\n\n assert_eq!(this.fields(fp!(0, 1, 2, 3)), (&3, &5, &8, &13));\n\n\n\n ...
Rust
src/builtins_pair.rs
gpwclark/sl-sh
6e55e1696434cd01bc91a06485a9010f5e7e5ddd
use std::collections::HashMap; use std::hash::BuildHasher; use crate::environment::*; use crate::eval::*; use crate::interner::*; use crate::types::*; fn builtin_join( environment: &mut Environment, args: &mut dyn Iterator<Item = Expression>, ) -> Result<Expression, LispError> { if let Some(arg0) = args.n...
use std::collections::HashMap; use std::hash::BuildHasher; use crate::environment::*; use crate::eval::*; use crate::interner::*; use crate::types::*; fn builtin_join( environment: &mut Environment, args: &mut dyn Iterator<Item = Expression>, ) -> Result<Expression, LispError> { if let Some(arg0) = args.n...
fn builtin_cdr( environment: &mut Environment, args: &mut dyn Iterator<Item = Expression>, ) -> Result<Expression, LispError> { if let Some(arg) = args.next() { if args.next().is_none() { let arg = eval(environment, arg)?; return match &arg.get().data { ExpE...
t {}", arg.display_type() ))), }; } } Err(LispError::new("car takes one form (pair)")) }
function_block-function_prefixed
[ { "content": "fn is_quoted(environment: &mut Environment, args: &mut dyn Iterator<Item = Expression>) -> bool {\n\n if let Some(car) = args.next() {\n\n let car_d = car.get();\n\n if let ExpEnum::Symbol(_s, _location) = &car_d.data {\n\n drop(car_d);\n\n let form = get_exp...
Rust
linkerd/app/inbound/src/direct.rs
kailun-qin/linkerd2-proxy
607cfea249216fabd549cfeabd5a565af028f172
use crate::{ http, require_identity::RequireIdentityForDirect, target::{RequestTarget, Target, TcpAccept, TcpEndpoint}, }; use linkerd_app_core::{ config::ProxyConfig, detect, drain, io, metrics, opencensus::proto::trace::v1 as oc, proxy::identity::LocalCrtKey, svc, tls, transport::{...
use crate::{ http, require_identity::RequireIdentityForDirect, target::{RequestTarget, Target, TcpAccept, TcpEndpoint}, }; use linkerd_app_core::{ config::ProxyConfig, detect, drain, io, metrics, opencensus::proto::trace::v1 as oc, proxy::identity::LocalCrtKey, svc, tls, transport::{...
} impl Into<tls::LocalId> for &'_ WithTransportHeaderAlpn { fn into(self) -> tls::LocalId { (&self.0).into() } } impl Into<Error> for RefusedNoHeader { fn into(self) -> Error { Error::from(io::Error::new( io::ErrorKind::ConnectionRefused, "Non-transport-header conn...
g { let c: tls::server::Config = (&self.0).into(); let mut config = c.as_ref().clone(); config .alpn_protocols .push(transport_header::PROTOCOL.into()); config.into() }
function_block-function_prefixed
[ { "content": "#[async_trait::async_trait]\n\npub trait Detect: Clone + Send + Sync + 'static {\n\n type Protocol: Send;\n\n\n\n async fn detect<I: io::AsyncRead + Send + Unpin + 'static>(\n\n &self,\n\n io: &mut I,\n\n buf: &mut BytesMut,\n\n ) -> Result<Option<Self::Protocol>, Err...
Rust
pallets/crowdloans/src/tests.rs
yz89/parallel
899f15bc1fc8ab2603f28650e58081fb5b2e97ad
use super::*; use crate::mock::*; use crowdloan_structs::*; use cumulus_primitives_core::ParaId; use frame_support::{assert_noop, assert_ok}; use frame_system::RawOrigin; use primitives::tokens; use sp_runtime::traits::Zero; use sp_runtime::traits::{One, UniqueSaturatedInto}; use sp_runtime::MultiAddress::Id; #[test] ...
use super::*; use crate::mock::*; use crowdloan_structs::*; use cumulus_primitives_core::ParaId; use frame_support::{assert_noop, assert_ok}; use frame_system::RawOrigin; use primitives::tokens; use sp_runtime::traits::Zero; use sp_runtime::traits::{One, UniqueSaturatedInto}; use sp_runtime::MultiAddress::Id; #[test] ...
#[test] fn auction_failed_should_work() { new_test_ext().execute_with(|| { let crowdloan = 1337; let currency = tokens::DOT; let ctoken = 10; let contribution_strategy = ContributionStrategy::XCM; assert_ok!(Crowdloan::create_vault( frame_system::RawO...
fn close_should_work() { new_test_ext().execute_with(|| { let crowdloan = ParaId::from(1337); let currency = tokens::DOT; let ctoken = 10; let contribution_strategy = ContributionStrategy::XCM; assert_ok!(Crowdloan::create_vault( frame_system::RawOrigin...
function_block-full_function
[ { "content": "#[test]\n\nfn amount_in_should_work() {\n\n new_test_ext().execute_with(|| {\n\n let amount_out = 1_000;\n\n let supply_in = 100_000_000;\n\n let supply_out = 100_000_000;\n\n\n\n let amount_in = AMM::get_amount_in(amount_out, supply_in, supply_out).unwrap();\n\n\n\n...
Rust
src/config.rs
RobiFerentz/gateway
11e8bbc58f3c0bd8f10a1a0792dc9f3d1263edee
pub struct ServiceConfig { pub protocol: String, pub url: String, pub port: u16, pub proxies: Vec<String>, } #[allow(dead_code)] pub struct AppConfig { pub port: u16, tenant: String, pub application_url: String, pub content_service: ServiceConfig, pub auth_service: ServiceConfig, ...
pub struct ServiceConfig { pub protocol: String, pub url: String, pub port: u16, pub proxies: Vec<String>, } #[allow(dead_code)] pub struct AppConfig { pub port: u16, tenant: String, pub application_url: String, pub content_service: ServiceConfig, pub auth_service: ServiceConfig, ...
}
pub fn new() -> Self { Self { port: std::env::var("PORT") .expect("PORT not found") .parse() .unwrap(), tenant: std::env::var("BASIC_TENANT") .expect("BASIC_TENANT not found") .parse() .unwrap...
function_block-full_function
[]
Rust
src/readline/reader.rs
officialcjunior/mican
5d556be9da110daccee50ce47111bce3598f8c93
use std::borrow::Cow; use std::io; use std::os::unix::io::AsRawFd; use nix; use nix::sys::termios::{tcgetattr, tcsetattr, SetArg, LocalFlags, InputFlags, SpecialCharacterIndices}; use nix::sys::select::{select, FdSet}; use nix::unistd::read; use readline::event::Kind as EventKind; use readline...
use std::borrow::Cow; use std::io; use std::os::unix::io::AsRawFd; use nix; use nix::sys::termios::{tcgetattr, tcsetattr, SetArg, LocalFlags, InputFlags, SpecialCharacterIndices}; use nix::sys::select::{select, FdSet}; use nix::unistd::read; use readline::event::Kind as EventKind; use readline...
s = FdSet::new(); r_fds.insert(stdin_fileno); let mut e_fds = FdSet::new(); r_fds.insert(stdin_fileno); loop { match select( stdin_fileno + 1, Some(&mut r_fds), None, Some(&mut e_fds), None.as_mut(), ) { Ok(n) => r...
} } } #[cfg_attr(feature = "cargo-clippy", allow(never_loop))] fn wait_input() -> bool { let stdin_fileno = io::stdout().as_raw_fd(); let mu...
random
[ { "content": "pub fn run(cmd: CommandData) -> Result<(), String> {\n\n let mut output = match Command::new(&cmd.program)\n\n .args(&cmd.options)\n\n .stdin(match cmd.input.unwrap() {\n\n Input::Stdin(_) => Stdio::inherit(),\n\n Input::File(input) => input.into(),\n\n ...
Rust
src/sys/fs/file.rs
vinc/moros
d541ed949a48c95d76c64c34efcb853a3df968f3
use super::{dirname, filename, realpath, FileIO}; use super::dir::Dir; use super::block::LinkedBlock; use super::dir_entry::DirEntry; use alloc::string::{String, ToString}; use alloc::vec; use core::convert::From; pub enum SeekFrom { Start(u32), Current(i32), End(i32), } #[derive(Debug, Clone)] pub struc...
use super::{dirname, filename, realpath, FileIO}; use super::dir::Dir; use super::block::LinkedBlock; use super::dir_entry::DirEntry; use alloc::string::{String, ToString}; use alloc::vec; use core::convert::From; pub enum SeekFrom { Start(u32), Current(i32), End(i32), } #[derive(Debug, Clone)] pub struc...
pub fn name(&self) -> String { self.name.clone() } pub fn size(&self) -> usize { self.size as usize } pub fn seek(&mut self, pos: SeekFrom) -> Result<u32, ()> { let offset = match pos { SeekFrom::Start(i) => i as i32, SeekFrom::Current(i) => i + ...
e); let filename = filename(&pathname); if let Some(dir) = Dir::open(dirname) { if let Some(dir_entry) = dir.find(filename) { if dir_entry.is_file() { return Some(dir_entry.into()); } } } None }
function_block-function_prefixed
[ { "content": "// Transform \"foo.txt\" into \"/path/to/foo.txt\"\n\npub fn realpath(pathname: &str) -> String {\n\n if pathname.starts_with('/') {\n\n pathname.into()\n\n } else {\n\n let dirname = sys::process::dir();\n\n let sep = if dirname.ends_with('/') { \"\" } else { \"/\" };\n...
Rust
app/src/renderer/mod.rs
lacop/udrb
bdd82bbf2eb2de6d6f4385bad85d418c8e4d636d
use crate::chrome::ChromeDriver; use crate::config::Config; use crate::slack; use std::sync::mpsc; use std::sync::Mutex; use std::thread; use log::{error, info}; #[derive(Debug)] pub struct RenderRequest { pub url: url::Url, pub slack_callback: Option<String>, pub user: Option<String>, pub channel: O...
use crate::chrome::ChromeDriver; use crate::config::Config; use crate::slack; use std::sync::mpsc; use std::sync::Mutex; use std::thread; use log::{error, info}; #[derive(Debug)] pub struct RenderRequest { pub url: url::Url, pub slack_callback: Option<String>, pub user: Option<String>, pub channel: O...
} impl Renderer { pub fn start(config: &Config) -> Result<RenderSender, failure::Error> { let (sender, receiver) = mpsc::channel(); let chrome = ChromeDriver::new(&config.chrome_address)?; let mut renderer = Renderer { config: config.clone(), chr...
Ok(RenderResult { title, orig_url: req.url.as_str().to_string(), pdf_url, png_url, user: req.user.as_ref().cloned(), channel: req.channel.as_ref().cloned(), team: req.team.as_ref().cloned(), })
call_expression
[ { "content": "pub fn post_success(callback: &str, result: &RenderResult) -> Result<(), failure::Error> {\n\n let mut text = String::new();\n\n if result.user.is_some() {\n\n writeln!(\n\n &mut text,\n\n \":bust_in_silhouette: {}\",\n\n result.user.as_ref().unwrap()\...
Rust
src/handlers/rewrite_layer.rs
TyberiusPrime/keytokey
786235e7dea439df53a4dda18271d033e7242f12
use crate::handlers::{ProcessKeys, HandlerResult}; use crate::key_stream::{iter_unhandled_mut, Event, EventStatus}; use crate::USBKeyOut; use no_std_compat::prelude::v1::*; pub struct RewriteLayer { rewrites: &'static [(u32, u32)], } impl RewriteLayer { pub fn new(rewrites: &'static [(u32, u32)]) -> RewriteL...
use crate::handlers::{ProcessKeys, HandlerResult}; use crate::key_stream::{iter_unhandled_mut, Event, EventStatus}; use crate::USBKeyOut; use no_std_compat::prelude::v1::*; pub struct RewriteLayer { rewrites: &'static [(u32, u32)], } impl RewriteLayer { pub fn new(rewrites: &'static [(u32, u32)]) -> RewriteL...
#[test] fn test_layer_disable_in_the_middle() { const MAP: &[(u32, u32)] = &[(KeyCode::A.to_u32(), KeyCode::B.to_u32())]; let mut keyboard = Keyboard::new(KeyOutCatcher::new()); let l = RewriteLayer::new(&MAP); let layer_id = keyboard.add_handler(Box::new(l)); assert!(!k...
keyboard.add_keypress(KeyCode::A, 0); keyboard.handle_keys().unwrap(); check_output(&keyboard, &[&[KeyCode::B]]); }
function_block-function_prefix_line
[ { "content": "#[cfg(test)]\n\npub fn check_output(keyboard: &Keyboard<KeyOutCatcher>, should: &[&[KeyCode]]) {\n\n if !(should.len() == keyboard.output.reports.len()) {\n\n dbg!(&keyboard.output.reports);\n\n dbg!(&should);\n\n }\n\n assert!(should.len() == keyboard.output.reports.len());...
Rust
src/cli.rs
ackintosh/discv5-cli
2fdc30f8ee78149aa55192a9c7265781917b38d4
use clap::{App, Arg}; pub fn start_cli<'a>() -> clap::ArgMatches<'a> { App::new("discv5-cli") .version("0.2.4") .author("Sigma Prime <contact@sigmaprime.io>") .about( "Simple CLI tool for starting and debugging discv5 servers and packets. \ This currently runs a discv5 s...
use clap::{App, Arg}; pub fn start_cli<'a>() -> clap::ArgMatches<'a> { App::new("discv5-cli") .version("0.2.4") .author("Sigma Prime <contact@sigmaprime.io>") .about( "Simple CLI tool for starting and debugging discv5 servers and packets. \ This currently runs a discv5 s...
etween successive searches. Default is 10 seconds.") .takes_value(true), ) .arg( Arg::with_name("stats") .long("stats") .default_value("10") .help("Displays statistics on the local routing table.") ) .arg( ...
E64-ENR") .allow_hyphen_values(true) .help("A base64 ENR that this node will initially connect to.") .takes_value(true), ) .arg( Arg::with_name("peer-update-min") .long("update-nodes") .short("n") ...
random
[ { "content": "fn print_stats(discv5: &mut Discv5) {\n\n let table_entries = discv5.table_entries();\n\n let self_id: discv5::Key<_> = discv5.local_enr().node_id().into();\n\n\n\n let mut bucket_values = HashMap::new();\n\n\n\n // Reconstruct the buckets\n\n for (node_id, enr, status) in table_ent...
Rust
codesnip_core/src/entry.rs
to-omer/codesnip
a16dc337db5e9245f6d6c3d490366d91104faf7b
use crate::ext::ItemExt as _; use quote::ToTokens; use syn::{ ext::IdentExt, parenthesized, parse::{Parse, ParseStream}, punctuated::Punctuated, token::{self, Comma, Paren}, Error, Ident, Item, LitStr, }; #[derive(Debug, Clone, Default)] pub struct Entry { pub name: String, pub include:...
use crate::ext::ItemExt as _; use quote::ToTokens; use syn::{ ext::IdentExt, parenthesized, parse::{Parse, ParseStream}, punctuated::Punctuated, token::{self, Comma, Paren}, Error, Ident, Item, LitStr, }; #[derive(Debug, Clone, Default)] pub struct Entry { pub name: String, pub include:...
} impl Parse for EntryArgName { fn parse(input: ParseStream) -> syn::Result<Self> { Ok(Self { name_token: None, name: input.parse()?, }) } } impl Parse for NoWhitespaceLitStr { fn parse(input: ParseStream) -> syn::Result<Self> { let litstr: LitStr = input.p...
ter_token(token: Ident, input: ParseStream) -> syn::Result<Self> { Ok(Self { name_token: Some((token, input.parse()?)), name: input.parse()?, }) }
function_block-function_prefixed
[ { "content": "#[proc_macro_attribute]\n\npub fn entry(attr: TokenStream, item: TokenStream) -> TokenStream {\n\n let attr = parse_macro_input!(attr as EntryArgs);\n\n match parse::<Item>(item) {\n\n Err(_) => Error::new_spanned(attr, \"expected to apply to `Item`\")\n\n .to_compile_error...
Rust
rdma_srv/src/rdma_srv.rs
CentaurusInfra/Quark
1079b36efa7e537f8fec39f037ee5ccc71977e7d
use spin::Mutex; use std::collections::HashMap; use super::id_mgr::IdMgr; use super::qlib::rdma_share::*; use super::rdma::*; use super::rdma_agent::*; use super::rdma_channel::*; use super::rdma_conn::*; use super::rdma_ctrlconn::*; use lazy_static::lazy_static; use std::ffi::CString; use std::mem::MaybeUninit; use...
use spin::Mutex; use std::collections::HashMap; use super::id_mgr::IdMgr; use super::qlib::rdma_share::*; use super::rdma::*; use super::rdma_agent::*; use super::rdma_channel::*; use super::rdma_conn::*; use super::rdma_ctrlconn::*; use lazy_static::lazy_static; use std::ffi::CString; use std::mem::MaybeUninit; use...
pub fn ProcessRDMARecvWriteImm(&self, channelId: u32, qpNum: u32, recvCount: u32) { let finReceived = channelId & 0x80000000 == 0x80000000; let channelId = channelId & 0x7FFFFFFF; if channelId != 0 { match...
pub fn ProcessRDMAWriteImmFinish(&self, channelId: u32, qpNum: u32) { let finSent = channelId & 0x80000000 == 0x80000000; let channelId = channelId & 0x7FFFFFFF; if channelId != 0 { let channel = self.channels.lock().get(&channelId).unwrap().clone(); ...
function_block-full_function
[ { "content": "pub fn Write(task: &Task, fd: i32, addr: u64, size: i64) -> Result<i64> {\n\n //task.PerfGoto(PerfType::Write);\n\n //defer!(task.PerfGofrom(PerfType::Write));\n\n\n\n let file = task.GetFile(fd)?;\n\n\n\n /*let fopsType = file.FileOp.FopsType();\n\n if fd <= 2 || fopsType == FileOp...
Rust
cx-hostnamed/src/main.rs
DankBSD/complexd
66b8f01c55831eb31a75dea88850eb5e3e2cdcd0
use cxutil::pk_check; use smol::{block_on, fs, spawn}; use std::error::Error; use zbus_polkit::policykit1 as pk; fn auto_chassis() -> Option<String> { #[cfg(target_os = "freebsd")] if let Some(c) = cxutil::get_kenv(cstr::cstr!("smbios.chassis.type")) { return match c.as_str() { "Deskto...
use cxutil::pk_check; use smol::{block_on, fs, spawn}; use std::error::Error; use zbus_polkit::policykit1 as pk; fn auto_chassis() -> Option<String> { #[cfg(target_os = "freebsd")] if let Some(c) = cxutil::get_kenv(cstr::cstr!("smbios.chassis.type")) { return match c.as_str() { "Deskto...
#[dbus_interface(property, name = "StaticHostname")] async fn get_static_hostname(&self) -> String { fs::read_to_string("/etc/hostname") .await .map(|s| s.trim_end().to_owned()) .unwrap_or_else(|_| "unknown".to_owned()) } async fn set_static_hostname<'m>( ...
zbus::fdo::Result<()> { pk_check(&self.auth, &hdr, interactive, "org.freedesktop.hostname1.set-hostname").await?; nix::unistd::sethostname(hostname).map_err(|e| zbus::fdo::Error::Failed(e.to_string())) }
function_block-function_prefix_line
[]
Rust
src/layout.rs
yulidai/skylight
895f7360fc361d6693fd803a366bebb1c0fb9c98
use super::style::{ StyleNode, Display }; use super::css::{ Value, Unit }; pub use self::BoxType::{AnonymousBlock, InlineNode, BlockNode}; #[derive(Debug)] pub struct LayoutBox<'a> { pub dimensions: Dimensions, pub box_type: BoxType<'a>, pub children: Vec<LayoutBox<'a>> } #[derive(Debug)] pub enum BoxTyp...
use super::style::{ StyleNode, Display }; use super::css::{ Value, Unit }; pub use self::BoxType::{AnonymousBlock, InlineNode, BlockNode}; #[derive(Debug)] pub struct LayoutBox<'a> { pub dimensions: Dimensions, pub box_type: BoxType<'a>, pub children: Vec<LayoutBox<'a>> } #[derive(Debug)] pub enum BoxTyp...
} } let mut d = &mut self.dimensions; d.content.width = width.to_px(); d.padding.left = padding_left.to_px(); d.padding.right = padding_right.to_px(); d.border.left = border_left.to_px(); d.border.right = border_right.to_px(); d.margin.lef...
if underflow >= 0.0 { width = Value::Length(underflow, Unit::Px); } else { width = Value::Length(0.0, Unit::Px); margin_right = Value::Length(margin_right.to_px() + underflow, Unit::Px); }
if_condition
[ { "content": "pub fn style_tree<'a>(root: &'a Node, stylesheet: &'a Stylesheet) -> StyleNode<'a> {\n\n StyleNode {\n\n node: root,\n\n specified_values: match root.node_type {\n\n NodeType::Element(ref elem) => specified_values(elem, &stylesheet),\n\n NodeType::Text(_) => ...
Rust
src/qubit_backend/circuit_distributed.rs
MichelNowak1/damavand
01a8753e5bfecbbd997cbbbf9f2557f011ba5767
use crate::qubit_backend::circuit::Circuit; use crate::utils; use num::complex::Complex; use mpi::topology::SystemCommunicator; use mpi::traits::*; impl Circuit { pub fn exchange_amplitudes_between_nodes(&mut self, partner_node_rank: usize) { let world = SystemCommunicator::world(); ...
use crate::qubit_backend::circuit::Circuit; use crate::utils; use num::complex::Complex; use mpi::topology::SystemCommunicator; use mpi::traits::*; impl Circuit { pub fn exchange_amplitudes_between_nodes(&mut self, partner_node_rank: usize) { let world = SystemCommunicator::world(); ...
let mut node_cumulated_probabilities = vec![0_f64; num_nodes]; world.barrier(); if current_node_rank == root_node_rank { root_node.gather_into_root( cumulative_distribution.last().unwrap(), &mut node_cumulated_probabilities[..], ); ...
partner_node.send(&local_amplitudes_imaginary[..]); let (partner_amplitudes_imaginary, _) = partner_node.receive_vec::<f64>(); self.partner_amplitudes = partner_amplitudes_real .iter() .zip(&partner_amplitudes_imaginary) .map(|(re, im)| Complex::<f64> { ...
random
[ { "content": "///\n\n///\n\n///\n\n///\n\n///\n\npub fn kron_shuffle(\n\n matrix_list: &Vec<Array2<Complex<f64>>>,\n\n state: &Array1<Complex<f64>>,\n\n) -> Array1<Complex<f64>> {\n\n let mut q = state.clone();\n\n\n\n // initialize\n\n let num_matrices = matrix_list.len();\n\n\n\n // transpos...
Rust
src/filters/auth/basic.rs
586837r/warp
fad2592ae47293b102ad759f96ebdbbb4a2b5484
use std::sync::Arc; use http::{ self, header::{self, HeaderValue}, }; use self::internal::AuthFilter; use crate::filter::{Filter, WrapSealed}; use crate::reject::{CombineRejection, Rejection}; use crate::reply::Reply; use std::collections::HashSet; pub fn basic() -> Builder { Builder { realm: N...
use std::sync::Arc; use http::{ self, header::{self, HeaderValue}, }; use self::internal::AuthFilter; use crate::filter::{Filter, WrapSealed}; use crate::reject::{CombineRejection, Rejection}; use crate::reply::Reply; use std::collections::HashSet; pub fn basic() -> Builder { Builder { realm: N...
impl Configured { fn is_authorized(&self, headers: &http::HeaderMap) -> bool { const PREFIX: &'static [u8] = b"Basic "; let header = match headers.get(header::AUTHORIZATION) { Some(v) => v, None => return false, }; let (prefix, rest) = match split_at(heade...
fn split_at(bytes: &[u8], mid: usize) -> Option<(&[u8], &[u8])> { if mid <= bytes.len() { Some(unsafe { (bytes.get_unchecked(..mid), bytes.get_unchecked(mid..)) }) } else { None } }
function_block-full_function
[ { "content": "// Option 2: impl Filter + Clone\n\npub fn index_filter() -> impl Filter<Extract = (&'static str,), Error = Rejection> + Clone {\n\n warp::path::end().map(|| \"Index page\")\n\n}\n\n\n\n#[tokio::main]\n\nasync fn main() {\n\n let routes = index_filter().or(assets_filter());\n\n warp::serv...
Rust
crates/bonsaidb-client/src/client/remote_database.rs
ModProg/bonsaidb
542cdccecc6876a43f47f858efd4a47c72301557
use std::{ops::Deref, sync::Arc}; use async_trait::async_trait; use bonsaidb_core::{ connection::{ AccessPolicy, AsyncConnection, AsyncLowLevelConnection, HasSchema, HasSession, Range, SerializedQueryKey, Session, Sort, }, document::{DocumentId, Header, OwnedDocument}, networking::{ ...
use std::{ops::Deref, sync::Arc}; use async_trait::async_trait; use bonsaidb_core::{ connection::{ AccessPolicy, AsyncConnection, AsyncLowLevelConnection, HasSchema, HasSession, Range, SerializedQueryKey, Session, Sort, }, document::{DocumentId, Header, OwnedDocument}, networking::{ ...
async fn get_from_collection( &self, id: DocumentId, collection: &CollectionName, ) -> Result<Option<OwnedDocument>, bonsaidb_core::Error> { Ok(self .client .send_api_request_async(&Get { database: self.name.to_string(), c...
Result<Vec<OperationResult>, bonsaidb_core::Error> { Ok(self .client .send_api_request_async(&ApplyTransaction { database: self.name.to_string(), transaction, }) .await?) }
function_block-function_prefix_line
[ { "content": "pub fn blocking_list_transactions_tests<C: Connection + Clone + 'static>(\n\n db: &C,\n\n) -> anyhow::Result<()> {\n\n // create LIST_TRANSACTIONS_MAX_RESULTS + 1 items, giving us just enough\n\n // transactions to test the edge cases of `list_transactions`\n\n let mut threads = Vec::w...