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/lib.rs
ecies/rs
8acefe16f51de03b18fccb654d7b0d24f4548006
pub use libsecp256k1::{util::FULL_PUBLIC_KEY_SIZE, Error as SecpError, PublicKey, SecretKey}; pub mod consts; pub mod types; pub mod utils; #[cfg(feature = "openssl")] mod openssl_aes; #[cfg(feature = "pure")] mod pure_aes; use utils::{aes_decrypt, aes_encrypt, decapsulate, encapsulate, generate_keypair}; pub f...
pub use libsecp256k1::{util::FULL_PUBLIC_KEY_SIZE, Error as SecpError, PublicKey, SecretKey}; pub mod consts; pub mod types; pub mod utils; #[cfg(feature = "openssl")] mod openssl_aes; #[cfg(feature = "pure")] mod pure_aes; use utils::{aes_decrypt, aes_encrypt, decapsulate, encapsulate, generate_keypair}; pub f...
alidMessage) ); } #[test] fn attempts_to_decrypt_incorrect_message() { let (sk, _) = generate_keypair(); assert_eq!(decrypt(&sk.serialize(), &[]), Err(SecpError::InvalidMessage)); assert_eq!(decrypt(&sk.serialize(), &[0u8; 65]), Err(SecpError::InvalidPublicKey)); } ...
&receiver_sk)?; aes_decrypt(&aes_key, encrypted).ok_or(SecpError::InvalidMessage) } #[cfg(test)] mod tests { use super::*; use utils::generate_keypair; const MSG: &str = "helloworld"; const BIG_MSG_SIZE: usize = 2 * 1024 * 1024; const BIG_MSG: [u8; BIG_MSG_SIZE] = [1u8; BIG_MSG_SIZE]; ...
random
[ { "content": "/// AES-256-GCM encryption wrapper\n\npub fn aes_encrypt(key: &[u8], msg: &[u8]) -> Option<Vec<u8>> {\n\n let key = GenericArray::from_slice(key);\n\n let aead = Aes256Gcm::new(key);\n\n\n\n let mut iv = [0u8; AES_IV_LENGTH];\n\n thread_rng().fill(&mut iv);\n\n\n\n let nonce = Gener...
Rust
hphp/hack/src/rupro/hackrs/shallow_decl_provider/store.rs
leikahing/hhvm
26617c88ca35c5e078c3aef12c061d7996925375
use anyhow::Result; use datastore::Store; use pos::{ConstName, FunName, MethodName, ModuleName, PropName, TypeName}; use std::sync::Arc; use ty::decl::{ shallow::Decl, shallow::ModuleDecl, ConstDecl, FunDecl, ShallowClass, Ty, TypedefDecl, }; use ty::reason::Reason; #[derive(Debug)] pub struct ShallowDeclStore<R...
use anyhow::Result; use datastore::Store; use pos::{ConstName, FunName, MethodName, ModuleName, PropName, TypeName}; use std::sync::Arc; use ty::decl::{ shallow::Decl, shallow::ModuleDecl, ConstDecl, FunDecl, ShallowClass, Ty, TypedefDecl, }; use ty::reason::Reason; #[derive(Debug)] pub struct ShallowDeclStore<R...
pub fn get_static_property_type( &self, class_name: TypeName, property_name: PropName, ) -> Result<Option<Ty<R>>> { self.static_properties.get((class_name, property_name)) } pub fn get_method_type( &self, class_name: TypeName, method_name: Metho...
pub fn get_property_type( &self, class_name: TypeName, property_name: PropName, ) -> Result<Option<Ty<R>>> { self.properties.get((class_name, property_name)) }
function_block-full_function
[]
Rust
src/workers.rs
arthurprs/sucredb
c3cf1adddf74b7616aa6b6f10b334aba0e1b5a30
use crossbeam_channel as chan; use std::sync::atomic::{AtomicUsize, Ordering}; use std::sync::Arc; use std::{thread, time}; pub trait ExitMsg { fn exit_msg() -> Self; fn is_exit(&self) -> bool; } pub struct WorkerSender<T: ExitMsg + Send + 'static> { cursor: AtomicUsize, alive_threads: Arc<AtomicUsize...
use crossbeam_channel as chan; use std::sync::atomic::{AtomicUsize, Ordering}; use std::sync::Arc; use std::{thread, time}; pub trait ExitMsg { fn exit_msg() -> Self; fn is_exit(&self) -> bool; } pub struct WorkerSender<
<T> { assert!(!self.channels.is_empty()); WorkerSender { cursor: Default::default(), channels: self.channels.clone(), alive_threads: self.alive_threads.clone(), } } } impl<T: ExitMsg + Send + 'static> WorkerSender<T> { pub fn send(&self, msg: T) -> bo...
T: ExitMsg + Send + 'static> { cursor: AtomicUsize, alive_threads: Arc<AtomicUsize>, channels: Vec<chan::Sender<T>>, } impl<T: ExitMsg + Send + 'static> Clone for WorkerSender<T> { fn clone(&self) -> Self { WorkerSender { cursor: Default::default(), channels: self.channe...
random
[ { "content": "pub trait Metadata\n\n : Serialize + DeserializeOwned + Clone + PartialEq + Send + fmt::Debug + 'static\n\n {\n\n}\n\n\n\nimpl<T: Serialize + DeserializeOwned + Clone + PartialEq + Send + fmt::Debug + 'static> Metadata\n\n for T {\n\n}\n\n\n", "file_path": "src/gossip.rs", "rank":...
Rust
src/lib.rs
jonas-schievink/vmem
bc31326d5e202c34444243802cb6ffab07dcff02
#![doc(html_root_url = "https://docs.rs/vmem/0.1.0")] #![warn(missing_debug_implementations)] #![warn(missing_docs)] #[cfg(unix)] #[path = "unix.rs"] mod imp; #[cfg(windows)] #[path = "win.rs"] mod imp; use failure::{Backtrace, Fail}; use std::marker::PhantomData; use std::ops::Range; use std::sync::Mutex; use st...
#![doc(html_root_url = "https://docs.rs/vmem/0.1.0")] #![warn(missing_debug_implementations)] #![warn(missing_docs)] #[cfg(unix)] #[path = "unix.rs"] mod imp; #[cfg(windows)] #[path = "win.rs"] mod imp; use failure::{Backtrace, Fail}; use std::marker::PhantomData; use std::ops::Range; use std::sync::Mutex; use st...
} pub fn addr(&self) -> usize { self.addr } pub fn page_size(&self) -> usize { page_size::get() } pub fn allocate(&self, offset: usize, bytes: usize) -> Result<Alloca...
match imp::reserve(bytes) { Ok(ptr) => Ok(Self { addr: ptr as usize, len: bytes, allocations: Mutex::new(Allocations { list: Vec::new() }), }), Err(e) => Err(ErrorKind::Os(e).into()), }
if_condition
[]
Rust
notedata/src/sm_parser.rs
martensm/rustmania
c5f40dcd5f8bf7a555cd8a7d470594409a7ccc8f
use crate::{ parser_generic::{beat_pair, comma_separated, stepmania_tag, ws_trimmed}, Chart, DisplayBpm, Measure, Note, NoteData, NoteRow, NoteType, }; use nom::{ branch::alt, bytes::complete::{tag, take_until}, character::complete::{char, multispace1, none_of, not_line_ending}, combinator::map,...
use crate::{ parser_generic::{beat_pair, comma_separated, stepmania_tag, ws_trimmed}, Chart, DisplayBpm, Measure, Note, NoteData, NoteRow, NoteType, }; use nom::{ branch::alt, bytes::complete::{tag, take_until}, character::complete::{char, multispace1, none_of, not_line_ending}, combinator::map,...
IT" => nd.meta.subtitle_translit = Some(value.to_owned()), "ARTISTTRANSLIT" => nd.meta.artist_translit = Some(value.to_owned()), "GENRE" => nd.meta.genre = Some(value.to_owned()), "CREDIT" => nd.meta.credit = Some(value.to_owned()), "BANNER" => nd.meta.ban...
ed_pair, terminated}, Err, IResult, }; use num_rational::Rational32; fn display_bpm(input: &str) -> IResult<&str, DisplayBpm> { alt(( map( separated_pair(double, ws_trimmed(char(':')), double), |(min, max)| DisplayBpm::Range(min, max), ), map(double, DisplayBpm::...
random
[]
Rust
src/client.rs
erikjohnston/matrix-hyper-federation-client
9939cf12f9bc8437a376370a135c2ee4eddb8c33
use std::convert::TryInto; use std::sync::Arc; use anyhow::{bail, format_err, Context, Error}; use ed25519_dalek::Keypair; use http::header::{AUTHORIZATION, CONTENT_TYPE}; use http::request::{Builder, Parts}; use http::{HeaderValue, Uri}; use hyper::body::{to_bytes, HttpBody}; use hyper::client::connect::Connect; us...
use std::convert::TryInto; use std::sync::Arc; use anyhow::{bail, format_err, Context, Error}; use ed25519_dalek::Keypair; use http::header::{AUTHORIZATION, CONTENT_TYPE}; use http::request::{Builder, Parts}; use http::{HeaderValue, Uri}; use hyper::body::{to_bytes, HttpBody}; use hyper::client::connect::Connect; us...
} pub struct AuthHeader<'a> { pub origin: &'a str, pub key_id: &'a str, pub signature: &'a str, } pub fn parse_auth_header(header: &str) -> Option<AuthHeader> { let header = header.strip_prefix("X-Matrix ")?; let mut origin = None; let mut key_id = None; let mut signature = None; for...
secret_key: &Keypair, content: Option<T>, ) -> Result<Request<Body>, Error> { if let Some(content) = content { self.signed_json(server_name, key_id, secret_key, content) } else { self.signed(server_name, key_id, secret_key) } }
function_block-function_prefix_line
[ { "content": "type ConnectorFuture =\n\n Pin<Box<dyn Future<Output = Result<MaybeHttpsStream<TcpStream>, Error>> + Send>>;\n\n\n\nimpl Service<Uri> for MatrixConnector {\n\n type Response = MaybeHttpsStream<TcpStream>;\n\n type Error = Error;\n\n type Future = ConnectorFuture;\n\n\n\n fn poll_rea...
Rust
src/terminal/config/input_filter.rs
ovnz/BearLibTerminal.rs
0a963d631125e20eae6f7d9a652ba4e278dc9df9
use std::fmt; use terminal::config::{ConfigPart, escape_config_string}; #[derive(Clone, Debug, Eq, PartialEq, Hash)] pub enum InputFilter { Event{name: InputFilterEvent, both: bool}, Group{group: InputFilterGroup, both: bool}, Alnum{keys: String, both: bool}, } #[derive(Clone, Debug, Eq, PartialEq, Hash)] pub enum...
use std::fmt; use terminal::config::{ConfigPart, escape_config_string}; #[derive(Clone, Debug, Eq, PartialEq, Hash)] pub enum InputFilter { Event{name: InputFilterEvent, both: bool}, Group{group: InputFilterGroup, both: bool}, Alnum{keys: String, both: bool}, } #[derive(Clone, Debug, Eq, PartialEq, Hash)] pub enum...
}
fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result { formatter.write_str(match self { &InputFilterEvent::A => "A", &InputFilterEvent::B => "B", &InputFilterEvent::C => "C", &InputFilterEvent::D => "D", &InputFilterEvent::E => "E", &InputFil...
function_block-full_function
[ { "content": "fn get_key(released: bool, key: KeyCode, ctrl: bool, shift: bool) -> Event {\n\n\tif released {\n\n\t\tEvent::KeyReleased{\n\n\t\t\tkey: key,\n\n\t\t\tctrl: ctrl,\n\n\t\t\tshift: shift,\n\n\t\t}\n\n\t} else {\n\n\t\tEvent::KeyPressed{\n\n\t\t\tkey: key,\n\n\t\t\tctrl: ctrl,\n\n\t\t\tshift: shift,\...
Rust
src/main.rs
mkb2091/msolve
7ccdda6626ada1cc3abdf0e1abb7cd32f3618e4c
#[cfg(feature = "cli")] mod cli { #[cfg(not(feature = "std"))] compile_error!("`std` feature is required for cli"); use std::io::BufRead; use std::io::Write; use clap::Clap; #[derive(Clap, Copy, Clone)] #[clap(version = "1.0")] struct Opts { #[clap(short, long)] verify...
#[cfg(feature = "cli")] mod cli { #[cfg(not(feature = "std"))] compile_error!("`std` feature is required for cli"); use std::io::BufRead; use std::io::Write; use clap::Clap; #[derive(Clap, Copy, Clone)] #[clap(version = "1.0")] struct Opts { #[clap(short, long)] verify...
} fn main() { #[cfg(feature = "cli")] cli::main() }
lock(); let mut info = [0; 3]; #[cfg(feature = "rand")] let mut rng = rand::thread_rng(); #[cfg(feature = "generate")] if let Mode::Generate(generate) = opts.mode { if let GenerateMode::Continuous(continuous) = generate.mode { let n = continuous.n.map(...
function_block-function_prefixed
[ { "content": "fn bench_solving(sudoku: Option<&String>, solver: Solver, mode: Mode) -> usize {\n\n let solution_count = match mode {\n\n Mode::SolveOne => 1,\n\n Mode::SolveUnique => 2,\n\n };\n\n match solver {\n\n Solver::MSolve => {\n\n if let Ok(sudoku) = msolve::Sud...
Rust
src/lib.rs
ldm0/wasm_nn
da6149a8e1d4c22a1c1496058401ea44aeadfc4d
mod data; mod nn; use std::mem; use std::slice; use once_cell::sync::Lazy; use std::sync::Mutex; use ndarray::prelude::*; use ndarray::{array, Array, Array1, Array3, Axis, Zip}; use data::Data; use nn::Network; #[derive(Default)] struct MetaData { fc_size: u32, num_classes: u32, descent_rate: f32, ...
mod data; mod nn; use std::mem; use std::slice; use once_cell::sync::Lazy; use std::sync::Mutex; use ndarray::prelude::*; use ndarray::{array, Array, Array1, Array3, Axis, Zip}; use data::Data; use nn::Network; #[derive(Default)] struct MetaData { fc_size: u32, num_classes: u32, descent_rate: f32, ...
ck().unwrap() = 0; draw_points(1, 1, DATA_GEN_RADIUS * 2f32 * 1.1f32); assert_eq!(DATA_NUM, *POINT_DRAW_TIMES.lock().unwrap()); *POINT_DRAW_TIMES.lock().unwrap() = 0; draw_points(1, 100, DATA_GEN_RADIUS * 2f32 * 1.1f32); assert_eq!(DATA_NUM, *POINT_DRAW_TIMES.lock().unw...
} #[test] fn test_buffer_allocation() { let buffer = alloc(114514); free(buffer, 114514); } #[test] fn test_draw_prediction() { init( DATA_GEN_RADIUS, SPIN_SPAN, DATA_NUM, NUM_CLASSES, DATA_GEN_RAND_MAX, ...
random
[ { "content": "use ndarray::prelude::*;\n\nuse ndarray::{stack, Array, Array1, Array2, Axis}; // for matrices\n\n\n\nuse ndarray_rand::rand_distr::StandardNormal; // for randomness\n\nuse ndarray_rand::RandomExt; // for randomness\n\nuse rand::rngs::SmallRng;\n\nuse rand::SeedableRng; // for from_seed // for ran...
Rust
rend3/src/renderer/shaders.rs
Noxime/rend3
8270d40cb7522a1212b1b99ab768cc525786f04f
use crate::{ datatypes::ShaderHandle, list::{ShaderSourceType, SourceShaderDescriptor}, registry::ResourceRegistry, ShaderError, }; use parking_lot::RwLock; use shaderc::{CompileOptions, Compiler, OptimizationLevel, ResolvedInclude, SourceLanguage, TargetEnv}; use std::{borrow::Cow, future::Future, path...
use crate::{ datatypes::ShaderHandle, list::{ShaderSourceType, SourceShaderDescriptor}, registry::ResourceRegistry, ShaderError, }; use parking_lot::RwLock; use shaderc::{CompileOptions, Compiler, OptimizationLevel, ResolvedInclude, SourceLanguage, TargetEnv}; use std::{borrow::Cow, future::Future, path...
ltin(args.clone()))? .contents_utf8() .unwrap() .to_string(), ShaderSourceType::Value(ref code) => code.clone(), }; let file_name = match args.source { ShaderSourceType::File(ref file) | ShaderSourceType::Builtin(ref file) => &**file, ShaderSourceType...
piler, &device, &args); sender.send(result).unwrap(); } CompileCommand::Stop => return, } } } fn compile_shader(compiler: &mut Compiler, device: &Device, args: &SourceShaderDescriptor) -> ShaderCompileResult { span_transfer!(_ -> file_span, WARN, "Loading File")...
random
[]
Rust
src/imp/scintilla/mod_cocoa.rs
plyhun/plygui-scintilla
6543238d109c7cf44a8883d65f5bb4d12df0bd90
use crate::sdk::*; use plygui_cocoa::common::*; use std::os::raw::{c_int, c_long, c_ulong, c_void}; lazy_static! { static ref WINDOW_CLASS: RefClass = unsafe { register_window_class("PlyguiConsole", BASE_CLASS, |decl| { decl.add_method(sel!(setFrameSize:), set_frame_size as extern "C" fn(&mut...
use crate::sdk::*; use plygui_cocoa::common::*; use std::os::raw::{c_int, c_long, c_ulong, c_void}; lazy_static! { static ref WINDOW_CLASS: RefClass = unsafe { register_window_class("PlyguiConsole", BASE_CLASS, |decl| { decl.add_method(sel!(setFrameSize:), set_frame_size as extern "C" fn(&mut...
e.on_set_visibility(value) } } impl MemberInner for CocoaScintilla {} extern "C" fn set_frame_size(this: &mut Object, sel: Sel, param: NSSize) { unsafe { let b = member_from_cocoa_id_mut::<Scintilla>(this).unwrap(); let b2 = member_from_cocoa_id_mut::<Scintilla>(this).unwrap(); (b.inner...
fn_ptr)(self.self_ptr.unwrap(), scintilla_sys::SCI_GETCODEPAGE as i32, 0, 0) as isize).into() } else { Default::default() } } fn append_text(&mut self, text: &str) { self.set_codepage(crate::Codepage::Utf8); if let Some(fn_ptr) = self.fn_ptr { let len = te...
random
[ { "content": "fn event_handler<O: crate::Scintilla>(object: &mut QObject, event: &mut QEvent) -> bool {\n\n match unsafe { event.type_() } {\n\n QEventType::Resize => {\n\n if let Some(this) = cast_qobject_to_uimember_mut::<Scintilla>(object) {\n\n let size = unsafe { \n\n ...
Rust
core/http/src/unix.rs
pzmarzly/Rocket
a4677871796c7170cfbbf83d205a8758338762df
use std::io::{self, Read, Write}; use std::path::Path; use std::net::{Ipv4Addr, SocketAddr, SocketAddrV4}; use std::time::Duration; #[cfg(unix)] use std::os::unix::net::{UnixListener, UnixStream}; #[cfg(windows)] use uds_windows::{UnixListener, UnixStream}; use crate::hyper; use crate::hyper::net::{NetworkStream, Ne...
use std::io::{self, Read, Write}; use std::path::Path; use std::net::{Ipv4Addr, SocketAddr, SocketAddrV4}; use std::time::Duration; #[cfg(unix)] use std::os::unix::net::{UnixListener, UnixStream}; #[cfg(windows)] use uds_windows::{UnixListener, UnixStream}; use crate::hyper; use crate::hyper::net::{NetworkStream, Ne...
} impl<S> NetworkListener for HttpsListener<S> where S: SslServer<UnixSocketStream> + Clone { type Stream = S::Stream; #[inline] fn accept(&mut self) -> hyper::Result<S::Stream> { self.listener.accept().and_then(|s| self.ssl.wrap_server(s)) } #...
pub fn new<P>(path: P, ssl: S) -> hyper::Result<HttpsListener<S>> where P: AsRef<Path> { UnixSocketListener::new(path) .map(|listener| HttpsListener { listener, ssl }) }
function_block-full_function
[ { "content": "pub fn kill_stream(stream: &mut BodyReader) {\n\n // Only do the expensive reading if we're not sure we're done.\n\n use self::HttpReader::*;\n\n match *stream {\n\n SizedReader(_, n) | ChunkedReader(_, Some(n)) if n > 0 => { /* continue */ },\n\n _ => return\n\n };\n\n\n...
Rust
src/platform/bluez/misc/thermometer.rs
OtaK/niter
e66b301b2469b7048e0ce254110a8e4df04cceba
#[derive(Debug, Clone, zvariant_derive::Type, serde::Serialize, serde::Deserialize)] pub struct ThermometerManager { object_path: String, } impl std::str::FromStr for ThermometerManager { type Err = crate::NiterError; fn from_str(s: &str) -> Result<Self, Self::Err> { Ok(Self { object_pa...
#[derive(Debug, Clone, zvariant_derive::Type, serde::Serialize, serde::Deserialize)] pub struct ThermometerManager { object_path: String, } impl std::str::FromStr for ThermometerManager { type Err = crate::NiterError; fn from_str(s: &str) -> Result<Self, Self::Err> { Ok(Self { object_pa...
} } impl std::convert::TryFrom<zvariant::OwnedValue> for ThermometerMeasurement { type Error = crate::NiterError; fn try_from(v: zvariant::OwnedValue) -> Result<Self, Self::Error> { use std::convert::TryInto as _; let dict: zvariant::Dict = v.try_into()?; Self::try_from(dict) }...
Ok(Self { calculated_value, exponent, mantissa, unit: ThermometerMeasurementUnit::from_str(&unit)?, time: time.copied(), r#type: measurement_type.and_then(|s| ThermometerMeasurementType::from_str(s).ok()), measurement: ThermometerMeasur...
call_expression
[ { "content": "pub trait MediaEndpointDelegate<E: std::error::Error>: zvariant::Type + 'static {\n\n fn set_configuration(&mut self, transport: MediaTransport, properties: MediaEndpointProperties) -> Result<(), E>;\n\n fn select_configuration(&mut self, capabilities: MediaEndpointCapabilities) -> Result<Me...
Rust
server/src/records/users/mod.rs
Deploy-Software/Blog
495868019becb4953ff8ba2a39a8fa936095c772
use async_graphql::{Error, Result, SimpleObject}; use bcrypt::{hash, verify, DEFAULT_COST}; use chrono::DateTime; use regex::Regex; use serde::{Deserialize, Serialize}; use sqlx::PgPool; pub mod session; #[derive(sqlx::FromRow, SimpleObject, Debug, Deserialize, Serialize, Clone)] pub struct SimpleUser { pub id: i...
use async_graphql::{Error, Result, SimpleObject}; use bcrypt::{hash, verify, DEFAULT_COST}; use chrono::DateTime; use regex::Regex; use serde::{Deserialize, Serialize}; use sqlx::PgPool; pub mod session; #[derive(sqlx::FromRow, SimpleObject, Debug, Deserialize, Serialize, Clone)] pub struct SimpleUser { pub id: i...
pub async fn password_matches(&self, password_to_test: &'a str) -> Result<bool> { match verify(password_to_test, &self.password) { Ok(matches) => Ok(matches), Err(error) => { println!("{}", error.to_string()); Err(Error::from( "We...
pub async fn from_session_token( pg_pool: &PgPool, session_token: &'a str, ) -> Result<Option<Self>> { match sqlx::query_as!( Self, r#" SELECT users.id, users.email, users.name, ...
function_block-full_function
[ { "content": "type Result<T> = std::result::Result<T, Box<dyn std::error::Error + Send + Sync>>;\n\n\n\npub struct AuthToken(String);\n", "file_path": "server/src/main.rs", "rank": 0, "score": 78968.49216649115 }, { "content": "#[wasm_bindgen(start)]\n\npub fn run_app() {\n\n App::<Model>...
Rust
src/hash_tree.rs
ChosunOne/binary_merkle_tree
c42d5c980030e28afcf5c2819ea3507a017b00cc
#[cfg(not(any(feature = "use_hashbrown")))] use std::collections::HashMap; use std::path::PathBuf; #[cfg(feature = "use_hashbrown")] use hashbrown::HashMap; use crate::merkle_bit::{BinaryMerkleTreeResult, MerkleBIT}; use crate::traits::{Array, Decode, Encode}; use crate::tree::tree_branch::TreeBranch; use c...
#[cfg(not(any(feature = "use_hashbrown")))] use std::collections::HashMap; use std::path::PathBuf; #[cfg(feature = "use_hashbrown")] use hashbrown::HashMap; use crate::merkle_bit::{BinaryMerkleTreeResult, MerkleBIT}; use crate::traits::{Array, Decode, Encode}; use crate::tree::tree_branch::TreeBranch; use c...
#[inline] pub fn insert( &mut self, previous_root: Option<&ArrayType>, keys: &mut [ArrayType], values: &[ValueType], ) -> BinaryMerkleTreeResult<ArrayType> { self.tree.insert(previous_root, keys, values) } ...
t( &self, root_hash: &ArrayType, keys: &mut [ArrayType], ) -> BinaryMerkleTreeResult<HashMap<ArrayType, Option<ValueType>>> { self.tree.get(root_hash, keys) }
function_block-function_prefixed
[ { "content": "#[inline]\n\npub fn generate_tree_ref_queue<ArrayType: Array>(\n\n tree_refs: &mut Vec<TreeRef<ArrayType>>,\n\n tree_ref_queue: &mut HashMap<usize, Vec<(usize, usize, usize)>>,\n\n) -> BinaryMerkleTreeResult<HashSet<usize>> {\n\n let mut unique_split_bits = HashSet::new();\n\n for i in...
Rust
src/util/coalesce.rs
tikue/inverted_index
c912e7c982116591ebd88f2e146f8aa5f7814bd6
use std::collections::BTreeMap; use std::collections::btree_map::Entry::*; use std::iter::FromIterator; pub trait Merge: Ord + Copy { fn merge(self, other: Self) -> Option<Self>; } pub trait Coalesce: Sized + IntoIterator where Self::Item: Ord + Copy + Merge { fn coalesce(&mut self, index: usize, el...
use std::collections::BTreeMap; use std::collections::btree_map::Entry::*; use std::iter::FromIterator; pub trait Merge: Ord + Copy { fn merge(self, other: Self) -> Option<Self>; } pub trait Coalesce: Sized + IntoIterator where Self::Item: Ord + Copy + Merge { fn coalesce(&mut self, index: usize, el...
} pub struct MergeCoalesceMap<K, V>(pub BTreeMap<K, V>); impl<'a, 'b, K, V> FromIterator<(&'a K, &'b V)> for MergeCoalesceMap<K, V> where K: 'a + Ord + Clone, V: 'b + Coalesce + Clone, V::Item: Ord + Copy + Merge { fn from_iter<It>(iterator: It) -> Self where It: IntoIterator<Item...
lf[start..].binary_search(&el) { Ok(idx) => start + idx, Err(idx) => { let idx = start + idx; self.coalesce(idx, el); idx } } }
function_block-function_prefixed
[ { "content": "/// A trait for types whose values have well-defined successors.\n\npub trait Successor: Sized {\n\n /// Returns the successor to self, if any exists.\n\n fn successor(&self) -> Option<Self>;\n\n}\n\n\n\nimpl Successor for char {\n\n #[inline]\n\n // Implementation lifted from https://...
Rust
src/vm/mod.rs
pmk21/rsqlite
2b2b50d64c05293d8bd6d8543cef6347f8d8b961
use crate::buffer::InputBuffer; use crate::constants::{EMAIL_SIZE, TABLE_MAX_ROWS, USERNAME_SIZE}; use crate::table::{Row, Table}; use std::str::FromStr; pub mod statement; use statement::{Statement, StatementType}; pub enum ExecuteResult { Success, TableFull, } pub enum MetaCommandResult { Unrecogniz...
use crate::buffer::InputBuffer; use crate::constants::{EMAIL_SIZE, TABLE_MAX_ROWS, USERNAME_SIZE}; use crate::table::{Row, Table}; use std::str::FromStr; pub mod statement; use statement::{Statement, StatementType}; pub enum ExecuteResult { Success, TableFull, } pub enum MetaCommandResult { Unrecogniz...
fn execute_select(table: &mut Table) -> ExecuteResult { for i in 0..table.num_rows { let (page_num, byte_offset) = table.row_slot(i); &table.deserialize_row(page_num, byte_offset).print_row(); } ExecuteResult::Success }
function_block-full_function
[ { "content": "//! # Table\n\n//!\n\n//! Interface to implement the structure of a table\n\n\n\nuse crate::constants::{\n\n EMAIL_OFFSET, EMAIL_SIZE, ID_OFFSET, ID_SIZE, ROWS_PER_PAGE, ROW_SIZE, USERNAME_OFFSET,\n\n USERNAME_SIZE,\n\n};\n\n\n\npub mod pager;\n\nuse pager::Pager;\n\n\n\n/// Structure to sto...
Rust
src/main.rs
joxcat/nextcloud-api
5cd949c5dbbe5dc32089ba25ea53221a7b0de52b
mod app; mod library; #[macro_use] extern crate log; #[macro_use] extern crate simple_error; use crate::library::serde_is_valid_and_contain; use badlog::init_from_env; use library::{ create_user, is_env, private_decrypt, public_encrypt, set_var, var, ConvertTo, GenericValue, QueryCreateUser, QueryGetToken, Res...
mod app; mod library; #[macro_use] extern crate log; #[macro_use] extern crate simple_error; use crate::library::serde_is_valid_and_contain; use badlog::init_from_env; use library::{ create_user, is_env, private_decrypt, public_encrypt, set_var, var, ConvertTo, GenericValue, QueryCreateUser, QueryGetToken, Res...
0, error_msg: Some("Internal Server Error"), error_details: Some("Error! Cannot get the tokens"), value: None, } } } } else { Response { status_code: 500, error_msg: Some("Internal Server ...
function_block-function_prefixed
[ { "content": "pub fn create_user(query: QueryCreateUser) -> Result<(), Box<dyn std::error::Error>> {\n\n // Browser setup\n\n let self_private = openssl::rsa::Rsa::private_key_from_pem(PRIVATE)?;\n\n let username = var(\"NC_ADMIN_USERNAME\").unwrap();\n\n let username = String::from_utf8(base64::dec...
Rust
bencode/tests/ser.rs
adrianplavka/rbit
de7e950c894666b987617cfcdfa7218379c953f7
#[cfg(test)] mod ser_tests { extern crate bitrust_bencode; use bitrust_bencode::to_string; use serde::Serialize; #[test] fn ser_integers() { assert_eq!(r#"i0e"#, to_string(&0usize).unwrap()); assert_eq!(r#"i0e"#, to_string(&0isize).unwrap()); assert_eq!(r#"i1e"#, to_string(&...
#[cfg(test)] mod ser_tests { extern crate bitrust_bencode; use bitrust_bencode::to_string; use serde::Serialize; #[test] fn ser_integers() { assert_eq!(r#"i0e"#, to_string(&0usize).unwrap()); assert_eq!(r#"i0e"#, to_string(&0isize).unwrap()); assert_eq!(r#"i1e"#, to_string(&...
#[test] fn ser_strings() { assert_eq!(r#"3:key"#, to_string(&"key").unwrap()); assert_eq!(r#"5:asdfg"#, to_string(&"asdfg").unwrap()); assert_eq!(r#"4:0087"#, to_string(&"0087").unwrap()); assert_eq!(r#"0:"#, to_string(&"").unwrap()); assert_eq!(r#"2: "#, to_string(&" ...
q!( format!("i{}e", std::i8::MAX), to_string(&std::i8::MAX).unwrap() ); assert_eq!( format!("i{}e", std::i16::MAX), to_string(&std::i16::MAX).unwrap() ); assert_eq!( format!("i{}e", std::i32::MAX), to_string(&std::i3...
function_block-function_prefixed
[ { "content": "fn main() {\n\n\n\n}\n", "file_path": "core/src/main.rs", "rank": 0, "score": 34516.8374640069 }, { "content": "pub fn to_string<T>(value: &T) -> Result<String>\n\nwhere\n\n T: Serialize,\n\n{\n\n let mut serializer = Serializer {\n\n output: String::new(),\n\n ...
Rust
crates/notation_bevy/src/play/play_plugin.rs
theAdamColton/notation
270e8592127c8e60ff33b12b040ab55dba5c92a3
use std::sync::Arc; use notation_bevy_utils::prelude::{DoLayoutEvent, GridData, LayoutData, ShapeOp, ColorBackground}; use notation_midi::prelude::PlayControlEvent; use notation_model::prelude::{ LaneEntry, PlayState, PlayingState, Position, Tab, TickResult, }; use bevy::prelude::*; use crate::bar::bar_beat::Bar...
use std::sync::Arc; use notation_bevy_utils::prelude::{DoLayoutEvent, GridData, LayoutData, ShapeOp, ColorBackground}; use notation_midi::prelude::PlayControlEvent; use notation_model::prelude::{ LaneEntry, PlayState, PlayingState, Position, Tab, TickResult, }; use bevy::prelude::*; use crate::bar::bar_beat::Bar...
fn on_tab_resized( mut evts: EventReader<TabBarsResizedEvent>, mut commands: Commands, theme: Res<NotationTheme>, mut settings: ResMut<NotationSettings>, mut query: Query<(Entity, &BarPlaying, &Arc<BarView>, &LayoutData)>, mut chord_color_background_query: Query<(Entity, &mut ColorBackground),...
ata>>, pos_indicator_query: &mut Query<(Entity, &mut PosIndicatorData), With<PosIndicatorData>>, tab_bars_query: &mut Query<( Entity, &mut Transform, &Arc<TabBars>, &LayoutData, &Arc<GridData>, )>, bar_playing: &BarPlaying, bar_layout: LayoutData, ) { let ...
function_block-function_prefixed
[ { "content": "pub fn add_notation_app_events(app: &mut AppBuilder) {\n\n app.add_event::<WindowResizedEvent>();\n\n app.add_event::<MouseClickedEvent>();\n\n app.add_event::<MouseDraggedEvent>();\n\n}\n", "file_path": "crates/notation_bevy/src/app/app_events.rs", "rank": 0, "score": 255115....
Rust
src/delivery/http/change.rs
chef-boneyard/delivery-cli
ab957f957017798cc11a370a0af57c3334d58bc9
use errors::{DeliveryError, Kind}; use http::*; use hyper::status::StatusCode; use serde_json; use config::Config; #[derive(Serialize, Deserialize, Debug, Clone, PartialEq, PartialOrd)] pub struct Description { pub title: String, pub description: String, } impl Description { pub fn payload(title: &str,...
use errors::{DeliveryError, Kind}; use http::*; use hyper::status::StatusCode; use serde_json; use config::Config; #[derive(Serialize, Deserialize, Debug, Clone, PartialEq, PartialOrd)] pub struct Description { pub title: String, pub description: String, } impl Description { pub fn payload(title: &str,...
t.read_to_string(&mut detail).and(Ok(detail)); Err(DeliveryError::throw( Kind::ApiError(error_code, e), Some(msg), )) } } } #[cfg(test)] mod tests { use super::*; #[test] fn description_payload_test() { let payload = Description::...
-> Result<Description, DeliveryError> { Ok(serde_json::from_str::<Description>(response)?) } pub fn parse_text(text: &str) -> Result<Description, DeliveryError> { let mut iter = text.lines(); let title = iter.find(|&l| !l.trim().is_empty()) .unwrap_or("") .trim(...
random
[ { "content": "/// Request an API token for a user from a Delivery server.\n\npub fn request(config: &Config, pass: &str) -> Result<String, DeliveryError> {\n\n let client = try!(APIClient::from_config_no_auth(config));\n\n let user = try!(config.user());\n\n let payload = try!(TokenRequest::payload(&us...
Rust
mutagen-core/src/transformer/arg_ast.rs
alarsyo/mutagen
f8249256c40769c916b5b00bd284f204d5540588
use proc_macro2::{Delimiter, TokenStream, TokenTree}; #[derive(Debug, Eq, PartialEq, Clone)] pub struct ArgAstList(pub Vec<ArgAst>); #[derive(Debug, Eq, PartialEq, Clone)] pub enum ArgAst { ArgFn(ArgFn), ArgEq(ArgEq), } #[derive(Debug, Eq, PartialEq, Clone)] pub struct ArgFn { pub name: String, pub...
use proc_macro2::{Delimiter, TokenStream, TokenTree}; #[derive(Debug, Eq, PartialEq, Clone)] pub struct ArgAstList(pub Vec<ArgAst>); #[derive(Debug, Eq, PartialEq, Clone)] pub enum ArgAst { ArgFn(ArgFn), ArgEq(ArgEq), } #[derive(Debug, Eq, PartialEq, Clone)] pub struct ArgFn { pub name: String, pub...
#[test] fn nested_args_with_trailing_arg() { let input = TokenStream::from_str("g55(h3(X), z)").unwrap(); let parsed = ArgAstList::parse_list(input); let mut expected = ArgFn::new("g55".to_string(), ArgAstList(vec![])); let mut expected1 = ArgFn::new("h3".to_string(), ArgAstL...
expected.args.0.push(ArgAst::ArgFn(expected1)); let expected = ArgAst::ArgFn(expected); assert_eq!(parsed, Ok(ArgAstList(vec![expected]))); }
function_block-function_prefix_line
[ { "content": "pub fn do_transform_item(args: TokenStream, input: TokenStream) -> TokenStream {\n\n let input = match syn::parse2::<syn::Item>(input) {\n\n Ok(ast) => ast,\n\n Err(e) => return TokenStream::from(e.to_compile_error()),\n\n };\n\n MutagenTransformerBundle::setup_from_attr(arg...
Rust
interface/rust/src/kubernetes_applier.rs
cosmonic/kubernetes-applier
693bbe6f53d42de0bf9a738a8c23f8699538732b
#[allow(unused_imports)] use async_trait::async_trait; #[allow(unused_imports)] use serde::{Deserialize, Serialize}; #[allow(unused_imports)] use std::{borrow::Borrow, borrow::Cow, io::Write, string::ToString}; #[allow(unused_imports)] use wasmbus_rpc::{ cbor::*, common::{ deserialize, message_format,...
#[allow(unused_imports)] use async_trait::async_trait; #[allow(unused_imports)] use serde::{Deserialize, Serialize}; #[allow(unused_imports)] use std::{borrow::Borrow, borrow::Cow, io::Write, string::ToString}; #[allow(unused_imports)] use wasmbus_rpc::{ cbor::*, common::{ deserialize, message_format,...
} } DeleteRequest { group: if let Some(__x) = group { __x } else { return Err(RpcError::Deser( "missing field DeleteRequest.group (#0)".to_string(), )); }, kind: if let Some(...
match d.str()? { "group" => group = Some(d.str()?.to_string()), "kind" => kind = Some(d.str()?.to_string()), "name" => name = Some(d.str()?.to_string()), "namespace" => { namespace = if wasmbus_rpc::cbor::Type::Null ...
if_condition
[ { "content": "fn ensure_no_path(item: &Option<String>, entity: &str, name: &str) -> Result<(), RpcError> {\n\n if item.is_some() {\n\n return Err(RpcError::ProviderInit(format!(\n\n \"{} {} {}\",\n\n CERT_PATH_ERROR, entity, name\n\n )));\n\n }\n\n Ok(())\n\n}\n", ...
Rust
src/command.rs
mwyrebski/drawerrs
1fc30e533f6af3e8435b5e763149d5c4643a77d0
use crate::canvas::Point; #[derive(PartialEq, PartialOrd, Eq, Ord, Debug, Hash)] pub enum Command { Line { from: Point, to: Point }, Rectangle { p1: Point, p2: Point }, Circle { p: Point, r: usize }, Canvas { width: usize, height: usize }, Char(char), Read(String), Save(String), Info, ...
use crate::canvas::Point; #[derive(PartialEq, PartialOrd, Eq, Ord, Debug, Hash)] pub enum Command { Line { from: Point, to: Point }, Rectangle { p1: Point, p2: Point }, Circle { p: Point, r: usize }, Canvas { width: usize, height: usize }, Char(char), Read(String), Save(String), Info, ...
} #[cfg(test)] mod tests { use super::*; fn command_variations(input: &str) -> Vec<String> { let capitalize = |s: &str| { let mut c = s.chars(); c.next().unwrap().to_uppercase().chain(c).collect() }; let mut vec: Vec<String> = Vec::new(); for s in &[ ...
CIRC", x, y, r] | ["CIRCLE", x, y, r] => Command::Circle { p: Point(try_parse_usize(x)?, try_parse_usize(y)?), r: try_parse_usize(r)?, }, ["CANV", width, height] | ["CANVAS", width, height] => Command::Canvas { width: try_parse_usize(width)?, ...
function_block-function_prefix_line
[ { "content": "fn open_input_reader() -> Box<dyn BufRead> {\n\n let args: Vec<String> = env::args().skip(1).collect();\n\n match (args.get(0), args.get(1)) {\n\n (Some(opt), Some(filename)) if opt == \"-r\" => {\n\n Box::new(BufReader::new(fs::File::open(filename).unwrap()))\n\n }\...
Rust
epp-client/src/epp/request/contact/update.rs
djc/epp-client
d06d404c12ea4d887b1106007fe56ed18600423a
use epp_client_macros::*; use crate::epp::object::data::{AuthInfo, ContactStatus, Phone, PostalInfo}; use crate::epp::object::{ElementName, EppObject, StringValue, StringValueTrait}; use crate::epp::request::Command; use crate::epp::response::contact::info::EppContactInfoResponse; use crate::epp::xml::EPP_CONTACT_XM...
use epp_client_macros::*; use crate::epp::object::data::{AuthInfo, ContactStatus, Phone, PostalInfo}; use crate::epp::object::{ElementName, EppObject, StringValue, StringValueTrait}; use crate::epp::request::Command; use crate::epp::response::contact::info::EppContactInfoResponse; use crate::epp::xml::EPP_CONTACT_XM...
EppObject::build(Command::<ContactUpdate>::new(contact_update, client_tr_id)) } pub fn set_info( &mut self, email: &str, postal_info: PostalInfo, voice: Phone, auth_password: &str, ) { self.data.command.contact.change_info = Some(ContactChangeIn...
let contact_update = ContactUpdate { contact: ContactUpdateData { xmlns: EPP_CONTACT_XMLNS.to_string(), id: id.to_string_value(), add_statuses: None, remove_statuses: None, change_info: None, }, };
assignment_statement
[ { "content": "/// Basic client TRID generation function. Mainly used for testing. Users of the library should use their own clTRID generation function.\n\npub fn generate_client_tr_id(username: &str) -> Result<String, Box<dyn Error>> {\n\n let timestamp = SystemTime::now().duration_since(SystemTime::UNIX_EPO...
Rust
hartex_core/src/error.rs
mod-tc/HarTex-rust-discord-bot
1cbd3e8933ff71853eff0114fd2675f3e8b7b210
use std::string::FromUtf8Error; use base64::DecodeError; use ctrlc::Error as CtrlcError; use toml::de::Error as TomlDeserializationError; use crate::discord::{ embed_builder::{ image_source::ImageSourceUrlError, EmbedError }, gateway::{ cluster::{ C...
use std::string::FromUtf8Error; use base64::DecodeError; use ctrlc::Error as CtrlcError; use toml::de::Error as TomlDeserializationError; use crate::discord::{ embed_builder::{ image_source::ImageSourceUrlError, EmbedError }, gateway::{ cluster::{ C...
} } impl From<TomlDeserializationError> for HarTexError { fn from(error: TomlDeserializationError) -> Self { Self::TomlDeserializationError { error } } } impl From<UpdateGuildMemberError> for HarTexError { fn from(error: UpdateGuildMemberError) -> Self { ...
DecodeError }, ClusterCommandError { error: ClusterCommandError }, ClusterStartError { error: ClusterStartError }, CreateMessageError { error: CreateMessage...
random
[ { "content": "/// # Trait `Command`\n\n///\n\n/// An application command.\n\n///\n\n/// ## Trait Methods\n\n/// - `name`; return type `String`: the name of the command\n\n/// - `description`; return type `String`: the description of the command\n\n/// - `execute`; parameters `CommandContext`, `InMemoryCache`; r...
Rust
bench/utils.rs
tauri-apps/benchmark_electron
09afd37775848c44c2f3712008bdb3760197e73e
use serde::Serialize; use std::{collections::HashMap, io::BufRead, path::PathBuf, process::{Command, Output, Stdio}}; pub fn root_path() -> PathBuf { PathBuf::from(env!("CARGO_MANIFEST_DIR")) } pub fn run_collect(cmd: &[&str]) -> (String, String) { let mut process_builder = Command::new(cmd[0]); process...
use serde::Serialize; use std::{collections::HashMap, io::BufRead, path::PathBuf, process::{Command, Output, Stdio}}; pub fn root_path() -> PathBuf { PathBuf::from(env!("CARGO_MANIFEST_DIR")) } pub fn run_collect(cmd: &[&str]) -> (String, String) { let mut process_builder = Command::new(cmd[0]); process...
#[derive(Debug, Clone, Serialize)] pub struct StraceOutput { pub percent_time: f64, pub seconds: f64, pub usecs_per_call: Option<u64>, pub calls: u64, pub errors: u64, } pub fn parse_strace_output(output: &str) -> HashMap<String, StraceOutput> { let mut summary = HashMap::new(); let mut ...
pub fn parse_max_mem(file_path: &str) -> Option<u64> { let file = std::fs::File::open(file_path).unwrap(); let output = std::io::BufReader::new(file); let mut highest: u64 = 0; for line in output.lines() { if let Ok(line) = line { let split = line.split(" ").collect::<Vec<_>>(); if spl...
function_block-full_function
[ { "content": "fn run_exec_time() -> Result<HashMap<String, HashMap<String, f64>>> {\n\n let benchmark_file = root_path().join(\"hyperfine_results.json\");\n\n let benchmark_file = benchmark_file.to_str().unwrap();\n\n\n\n let mut command = [\n\n \"hyperfine\",\n\n \"--export-json\",\n\n ...
Rust
tests/src/tests.rs
duanyytop/ckb-passport-lock
e1fb7df2eea0bf35abfe3cb349948754345debf8
use super::*; use ckb_testtool::context::Context; use ckb_tool::ckb_hash::{new_blake2b, blake2b_256}; use ckb_tool::ckb_types::{ bytes::Bytes, core::{TransactionBuilder, TransactionView}, packed::{self, *}, prelude::*, }; use ckb_tool::ckb_error::assert_error_eq; use ckb_tool::ckb_script::ScriptError; ...
use super::*; use ckb_testtool::context::Context; use ckb_tool::ckb_hash::{new_blake2b, blake2b_256}; use ckb_tool::ckb_types::{ bytes::Bytes, core::{TransactionBuilder, TransactionView}, packed::{self, *}, prelude::*, }; use ckb_tool::ckb_error::assert_error_eq; use ckb_tool::ckb_script::ScriptError; ...
dep) .cell_dep(rsa_dep) .witnesses(witnesses.pack()) .build(); let tx = context.complete_tx(tx); let tx = sign_tx(tx, &private_key, &public_key, true); let err = context.verify_tx(&tx, MAX_CYCLES).unwrap_err(); let script_cell_index = 0; assert_error_eq!( ...
WitnessArgs::default(); let zero_lock: Bytes = { let mut buf = Vec::new(); buf.resize(SIGN_INFO_SIZE, 0); buf.into() }; let witness_for_digest = witness .clone() .as_builder() .lock(Some(zero_lock).pack()) .build(); let witness_len = witness_for_d...
random
[ { "content": "pub fn blake2b_256<T: AsRef<[u8]>>(s: T) -> [u8; 32] {\n\n if s.as_ref().is_empty() {\n\n return BLANK_HASH;\n\n }\n\n inner_blake2b_256(s)\n\n}\n\n\n", "file_path": "contracts/ckb-passport-lock/src/entry/hash.rs", "rank": 1, "score": 108113.07493456306 }, { "co...
Rust
bzip2/src/tokio.rs
GMAP/RustStreamBench
d319445c448db15221cf62aa51af002308807c39
use std::mem; use std::fs::File; use std::io::prelude::*; use std::time::{SystemTime}; use {bzip2_sys}; use crossbeam_channel::{unbounded}; use{ futures::future::lazy, futures::sync::*, futures::{stream, Future, Stream}, tokio::prelude::*, }; struct Tcontent { order: usize, buffer_input: Vec<u8>, b...
use std::mem; use std::fs::File; use std::io::prelude::*; use std::time::{SystemTime}; use {bzip2_sys}; use crossbeam_channel::{unbounded}; use{ futures::future::lazy, futures::sync::*, futures::{stream, Future, Stream}, tokio::prelude::*, }; struct Tcontent { order: usize, buffer_input: Vec<u8>, b...
pub fn tokio_io(threads: usize, file_action: &str, file_name: &str,) { let mut file = File::open(file_name).expect("No file found."); if file_action == "compress" { let compressed_file_name = file_name.to_owned() + &".bz2"; let mut buf_write = File::create(compressed_file_name).unwrap(); let block...
pub fn tokio(threads: usize, file_action: &str, file_name: &str,) { let mut file = File::open(file_name).expect("No file found."); if file_action == "compress" { let compressed_file_name = file_name.to_owned() + &".bz2"; let mut buf_write = File::create(compressed_file_name).unwrap(); let mut buffer_input = v...
function_block-full_function
[ { "content": "struct Tcontent {\n\n\torder: u64,\n\n\tbuffer_input: Vec<u8>,\n\n\tbuffer_output: Vec<u8>,\n\n\toutput_size: u32,\n\n}\n\n\n\npub struct Reorder {\n\n storage: BTreeMap<u64, Tcontent>,\n\n}\n\n\n\nimpl Reorder {\n\n fn new() -> Reorder {\n\n Reorder {\n\n storage: BTreeMap...
Rust
kernel/src/process.rs
liva/node-replicated-kernel
2d953c3a984b0c3a48b6368062b6abdf5146da2a
use alloc::boxed::Box; use alloc::format; use alloc::string::{String, ToString}; use alloc::sync::Arc; use alloc::vec::Vec; use core::convert::TryInto; use cstr_core::CStr; use custom_error::custom_error; use kpi::process::FrameId; use crate::arch::memory::paddr_to_kernel_vaddr; use crate::arch::memory::LARGE_PAGE_S...
use alloc::boxed::Box; use alloc::format; use alloc::string::{String, ToString}; use alloc::sync::Arc; use alloc::vec::Vec; use core::convert::TryInto; use cstr_core::CStr; use custom_error::custom_error; use kpi::process::FrameId; use crate::arch::memory::paddr_to_kernel_vaddr; use crate::arch::memory::LARGE_PAGE_S...
pub fn allocate_dispatchers(pid: Pid) -> Result<(), KError> { trace!("Allocate dispatchers"); let mut create_per_region: Vec<(topology::NodeId, usize)> = Vec::with_capacity(topology::MACHINE_TOPOLOGY.num_nodes() + 1); if topology::MACHINE_TOPOLOGY.num_nodes() > 0 { for node in topology::...
pub fn make_process(binary: &'static str) -> Result<Pid, KError> { KernelAllocator::try_refill_tcache(7, 1)?; let kcb = kcb::get_kcb(); let mut mod_file = None; for module in &kcb.arch.kernel_args().modules { if module.name() == binary { mod_file = Some(module); } }...
function_block-full_function
[ { "content": "/// TODO: This method makes file-operations slow, improve it to use large page sizes. Or maintain a list of\n\n/// (low, high) memory limits per process and check if (base, size) are within the process memory limits.\n\nfn user_virt_addr_valid(pid: Pid, base: u64, size: u64) -> Result<(u64, u64), ...
Rust
src/cfg/global/project.rs
vincent-herlemont/short
805aa75a4605eb9b587c82135ccc8e8883df1192
use crate::cfg::global::setup::{GlobalProjectSetupCfg, SetupName}; use crate::cfg::SetupsCfg; use anyhow::{Context, Result}; use serde::de::{MapAccess, Visitor}; use serde::export::Formatter; use serde::ser::SerializeMap; use serde::{Deserialize, Deserializer, Serialize, Serializer}; use std::cell::RefCell; use std::fm...
use crate::cfg::global::setup::{GlobalProjectSetupCfg, SetupName}; use crate::cfg::SetupsCfg; use anyhow::{Context, Result}; use serde::de::{MapAccess, Visitor}; use serde::export::Formatter; use serde::ser::SerializeMap; use serde::{Deserialize, Deserializer, Serialize, Serializer}; use std::cell::RefCell; use std::fm...
} impl Serialize for GlobalProjectSetupsCfg { fn serialize<S>(&self, serializer: S) -> Result<<S as Serializer>::Ok, <S as Serializer>::Error> where S: Serializer, { let vec = &self.0.borrow(); let mut seq = serializer.serialize_map(Some(vec.len()))?; for global_setup_cfg i...
l_setup_cfg.name() }) .is_none() { global_setups_cfg.push(Rc::new(RefCell::new(global_setup_cfg))) } }
function_block-function_prefixed
[ { "content": "pub fn run_as_stream(file: &PathBuf, vars: &Vec<EnvVar>, args: &Vec<String>) -> Result<Output> {\n\n let file = file.canonicalize()?;\n\n let mut command = Command::new(&file);\n\n\n\n for env_var in vars.iter() {\n\n command.env(env_var.var().to_env_var(), env_var.env_value().to_s...
Rust
src/repl.rs
wylee/feint
2ad7c43ae575684859996da2ce560168c82140d3
use std::path::Path; use rustyline::error::ReadlineError; use crate::compiler::CompilationErrKind; use crate::parser::ParseErrKind; use crate::result::ExitResult; use crate::scanner::ScanErrKind; use crate::util::Location; use crate::vm::{execute, execute_text, Inst, RuntimeErrKind, VMState, VM}; pub fn run(histor...
use std::path::Path; use rustyline::error::ReadlineError; use crate::compiler::CompilationErrKind; use crate::parser::ParseErrKind; use crate::result::ExitResult; use crate::scanner::ScanErrKind; use crate::util::Location; use crate::vm::{execute, execute_text, Inst, RuntimeErrKind, VMState, VM}; pub fn run(histor...
fn handle_parse_err(&mut self, kind: ParseErrKind, bail: bool) -> bool { match kind { ParseErrKind::ScanErr(err) => { return self.handle_scan_err(err.kind, err.location, bail); } ParseErrKind::UnexpectedToken(token) => { let loc = to...
nErrKind, bail: bool) -> bool { let message = match kind { err => format!("Unhandled compilation error: {:?}", err), }; eprintln!("{}", message); false }
function_block-function_prefixed
[ { "content": "/// Execute source text.\n\npub fn execute_text(vm: &mut VM, text: &str, dis: bool, debug: bool) -> ExeResult {\n\n execute_parse_result(vm, parser::parse_text(text, debug), dis, debug)\n\n}\n\n\n", "file_path": "src/vm/vm.rs", "rank": 0, "score": 421688.4762652945 }, { "con...
Rust
pkmnapi-db/src/sav/player_name.rs
kevinselwyn/pkmnapi
170e6b6c9a74e85c377137bc086793898c415125
use crate::error::{self, Result}; use crate::patch::*; use crate::sav::Sav; use crate::string::*; impl Sav { pub fn get_player_name(&self) -> Result<SavePlayerName> { let offset = 0x2598; ...
use crate::error::{self, Result}; use crate::patch::*; use crate::sav::Sav; use crate::string::*; impl Sav { pub fn get_player_name(&self) -> Result<SavePlayerName> { let offset = 0x2598; ...
_index]); SavePlayerName { name } } } impl SavePlayerName { pub fn to_raw(&self) -> Vec<u8> { self.name.value[..].to_vec() } }
0x50; { if save_player_name_raw_len != max_len { 0x01 } else { 0x00 } } ]; let save_player_name_raw = [save_player_name_raw, padding].concat(); Ok(Patch::new(&offset, &sav...
random
[ { "content": "#[allow(dead_code)]\n\n#[allow(non_snake_case)]\n\npub fn load_sav() -> Vec<u8> {\n\n let PKMN_SAV = env::var(\"PKMN_SAV\")\n\n .expect(\"Set the PKMN_SAV environment variable to point to the SAV location\");\n\n\n\n fs::read(PKMN_SAV).unwrap()\n\n}\n\n\n", "file_path": "pkmnapi-a...
Rust
src/timer/wheel.rs
daschl/reef
f2238623bd2cbdf3bc75dbba1e962948a131c551
use chrono::{NaiveDateTime, Duration}; use linked_list::LinkedList; use bit_vec::BitVec; use timer::Timer; use std::cmp; pub struct TimerWheel<'a, T: 'a> { last: Duration, next: Duration, num_buckets: u32, buckets: Vec<LinkedList<&'a T>>, non_empty_buckets: BitVec, } enum RemoveAction { Remove...
use chrono::{NaiveDateTime, Duration}; use linked_list::LinkedList; use bit_vec::BitVec; use timer::Timer; use std::cmp; pub struct TimerWheel<'a, T: 'a> { last: Duration, next: Duration, num_buckets: u32, buckets: Vec<LinkedList<&'a T>>, non_empty_buckets: BitVec, } enum RemoveAction { Remove...
xpired = wheel.expire(NaiveDateTime::from_timestamp(Duration::days(4).num_seconds(), 0)); assert_eq!(false, expired.is_empty()); assert_eq!(1, expired.len()); assert_eq!(timer, *expired.pop_front().unwrap()); } #[test] fn test_get_index() { let wheel = TimerWhee...
>::duration_since_epoch(now); if timestamp < self.last { panic!("The timestamp to expire is smaller than last!"); } let mut expired = LinkedList::new(); let index = self.get_index(timestamp) as usize; let skipped = self.non_empty_buckets .iter() ...
random
[ { "content": "#[bench]\n\nfn remove_one_timer(b: &mut test::Bencher) {\n\n let timer = SimpleTimer { expires: Duration::days(2) };\n\n let mut wheel = TimerWheel::new();\n\n wheel.insert(&timer);\n\n b.iter(|| {\n\n wheel.remove(&timer);\n\n });\n\n}\n", "file_path": "benches/wheel.rs"...
Rust
path_ext/src/lib.rs
pwil3058/ergibus
c7c15d82998e9021ccc64ce192882da5cc89a25e
use std::{ env, io, path::{Component, Path, PathBuf, StripPrefixError}, }; use dirs; use thiserror::Error; #[derive(Debug, Error)] pub enum Error { #[error("Could not find user's home directory.")] CouldNotFindHome, #[error("Could not find current directory's parent.")] CouldNotFindParent, ...
use std::{ env, io, path::{Component, Path, PathBuf, StripPrefixError}, }; use dirs; use thiserror::Error; #[derive(Debug, Error)] pub enum Error { #[error("Could not find user's home directory.")] CouldNotFindHome, #[error("Could not find current directory's parent.")] CouldNotFindParent, ...
lativeHomeDir } else { PathType::RelativeCurDirImplicit } } }, } } } pub fn expand_current_dir<P: AsRef<Path>>(path_arg: P) -> Result<PathBuf, Error> { let path = path_arg.as_ref(); if path.starts_with(Compo...
Component::ParentDir => PathType::RelativeParentDir, Component::Normal(os_string) => { if os_string == "~" { PathType::Re
function_block-random_span
[ { "content": "pub fn ignore_report_or_fail<P: AsRef<Path>>(err: Error, path: P) -> EResult<()> {\n\n match &err {\n\n Error::FSOBrokenSymLink(link_path, target_path) => {\n\n log::warn!(\n\n \"{:?} -> {:?}: broken symbolic link ignored\",\n\n link_path,\n\n ...
Rust
wgpu-hal/src/dx11/library.rs
jinleili/wgpu
a845dcc21c976e1de3de7b3e0bec8703dcdd905c
use std::ptr; use winapi::{ shared::{ dxgi, minwindef::{HMODULE, UINT}, winerror, }, um::{d3d11, d3d11_1, d3d11_2, d3dcommon}, }; use crate::auxil::dxgi::result::HResult; type D3D11CreateDeviceFun = unsafe extern "system" fn( *mut dxgi::IDXGIAdapter, d3dcommon::D3D_DRIVER_...
use std::ptr; use winapi::{ shared::{ dxgi, minwindef::{HMODULE, UINT}, winerror, }, um::{d3d11, d3d11_1, d3d11_2, d3dcommon}, }; use crate::auxil::dxgi::result::HResult; type D3D11CreateDeviceFun = unsafe extern "system" fn( *mut dxgi::IDXGIAdapter, d3dcommon::D3D_DRIVER_...
pub fn create_device( &self, adapter: native::DxgiAdapter, ) -> Option<(super::D3D11Device, d3dcommon::D3D_FEATURE_LEVEL)> { let feature_levels = [ d3dcommon::D3D_FEATURE_LEVEL_11_1, d3dcommon::D3D_FEATURE_LEVEL_11_0, d3dcommon::D3D_FEATURE_LEVEL_10_...
unsafe { let lib = libloading::Library::new("d3d11.dll").ok()?; let d3d11_create_device = lib .get::<D3D11CreateDeviceFun>(b"D3D11CreateDevice") .ok()? .into_raw(); Some(Self { lib, d3d11_create_device,...
function_block-function_prefix_line
[ { "content": "type WlDisplayDisconnectFun = unsafe extern \"system\" fn(display: *const raw::c_void);\n\n\n", "file_path": "wgpu-hal/src/gles/egl.rs", "rank": 1, "score": 363831.6744697565 }, { "content": "type WlEglWindowDestroyFun = unsafe extern \"system\" fn(window: *const raw::c_void);\...
Rust
linked-lists/fp-rust/persistent-list/src/third.rs
ctarrington/try-fp
63559ec6abd451c8a1decad5981a20fee498a171
#![warn(missing_docs)] use std::rc::Rc; pub struct PersistentList<T> { head: Link<T>, } type Link<T> = Option<Rc<Node<T>>>; struct Node<T> { next: Link<T>, element: T, } impl<T> PersistentList<T> { pub fn new() -> Self { Self { head: None } } } impl<T> Default for PersistentList...
#![warn(missing_docs)] use std::rc::Rc; pub struct PersistentList<T> { head: Link<T>, } type Link<T> = Option<Rc<Node<T>>>; struct Node<T> { next: Link<T>, element: T, } impl<T> PersistentList<T> { pub fn new() -> Self { Self { head: None } } } impl<T> Default for PersistentList...
events: RefCell::new(vec![]), } } fn push(&self, value: String) { self.events.borrow_mut().push(value); } fn list(&self) -> String { self.events.borrow().join(",") } } struct Thing<'a>...
f::new() } } impl<T> PersistentList<T> { pub fn prepend(&self, value: T) -> Self { Self { head: Some(Rc::new(Node { element: value, next: self.head.as_ref()....
random
[ { "content": "// the crux of the thing\n\nstruct Node {\n\n element: i32,\n\n next: Link,\n\n}\n\n\n\nimpl List {\n\n pub fn new() -> Self {\n\n List { head: Link::None }\n\n }\n\n\n\n pub fn push(&mut self, value: i32) {\n\n let popped_link = mem::replace(&mut self.head, Link::None...
Rust
src/message/header/textual.rs
alexwennerberg/lettre
8caa135e33a7e2a79a4f8792f47d40ff2e56263f
use crate::message::utf8_b; use hyperx::{ header::{Formatter as HeaderFormatter, Header, RawLike}, Error as HeaderError, Result as HyperResult, }; use std::{fmt::Result as FmtResult, str::from_utf8}; macro_rules! text_header { ($(#[$attr:meta])* Header($type_name: ident, $header_name: expr )) => { ...
use crate::message::utf8_b; use hyperx::{ header::{Formatter as HeaderFormatter, Header, RawLike}, Error as HeaderError, Result as HyperResult, }; use std::{fmt::Result as FmtResult, str::from_utf8}; macro_rules! text_header { ($(#[$attr:meta])* Header($type_name: ident, $header_name: expr )) => { ...
Err(HeaderError::Header) } fn fmt_text(s: &str, f: &mut HeaderFormatter<'_, '_>) -> FmtResult { f.fmt_line(&utf8_b::encode(s)) } #[cfg(test)] mod test { use super::Subject; use hyperx::header::Headers; #[test] fn format_ascii() { let mut headers = Headers::new(); headers.set(...
if let Ok(src) = from_utf8(raw) { if let Some(txt) = utf8_b::decode(src) { return Ok(txt); } }
if_condition
[ { "content": "pub fn encode(s: &str) -> String {\n\n if s.chars().all(allowed_char) {\n\n s.into()\n\n } else {\n\n format!(\"=?utf-8?b?{}?=\", base64::encode(s))\n\n }\n\n}\n\n\n", "file_path": "src/message/utf8_b.rs", "rank": 2, "score": 184179.84348529213 }, { "cont...
Rust
src/io/pts.rs
I3ck/rust-3d
5139ab5ebdab7ad2a1f49422bc852d751fbfc4c1
/* Copyright 2020 Martin Buck Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublice...
/* Copyright 2020 Martin Buck Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublice...
} impl fmt::Display for PtsError { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { write!(f, "{:?}", self) } } impl From<ioError> for PtsError { fn from(_error: ioError) -> Self { PtsError::AccessFile } }
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { match self { Self::AccessFile => write!(f, "Unable to access file"), Self::VertexCount => write!(f, "Unable to parse vertex count"), Self::Vertex => write!(f, "Unable to parse vertex"), } }
function_block-full_function
[ { "content": "/// Splits an ASCII line into its words, skipping empty elements\n\npub fn to_words_skip_empty(line: &[u8]) -> impl Iterator<Item = &[u8]> {\n\n line.split(|x| *x == b' ' || *x == b'\\t').skip_empty()\n\n}\n\n\n", "file_path": "src/utils.rs", "rank": 0, "score": 505942.53733688314 ...
Rust
chain-abci/src/storage/tx.rs
calvinlauco/chain
ef40ea2c44f8e1aca8a36e50ff10172879df3491
use crate::enclave_bridge::EnclaveProxy; use crate::storage::account::AccountStorage; use crate::storage::account::AccountWrapper; use crate::storage::COL_TX_META; use bit_vec::BitVec; use chain_core::state::account::{to_stake_key, StakedState, StakedStateAddress}; use chain_core::tx::data::input::TxoPointer; use chain...
use crate::enclave_bridge::EnclaveProxy; use crate::storage::account::AccountStorage; use crate::storage::account::AccountWrapper; use crate::storage::COL_TX_META; use bit_vec::BitVec; use chain_core::state::account::{to_stake_key, StakedState, StakedStateAddress}; use chain_core::tx::data::input::TxoPointer; use chain...
fn check_spent_input_lookup(inputs: &[TxoPointer], db: Arc<dyn KeyValueDB>) -> Result<(), Error> { if inputs.is_empty() { return Err(Error::NoInputs); } for txin in inputs.iter() { let txo = db.get(COL_TX_META, &txin.id[..]); match txo { Ok(Some(v)) => { ...
r) /* FIXME: Err(Error::IoError(std::io::Error::new( std::io::ErrorKind::Other, e, )))*/, Ok(None) => Err(Error::AccountNotFound), Ok(Some(AccountWrapper(a))) => Ok(a), } }
function_block-function_prefixed
[ { "content": "/// Verifies if the account is unjailed\n\npub fn verify_unjailed(account: &StakedState) -> Result<(), Error> {\n\n if account.is_jailed() {\n\n Err(Error::AccountJailed)\n\n } else {\n\n Ok(())\n\n }\n\n}\n\n\n\n/// information needed for NodeJoinRequestTx verification\n\np...
Rust
tests/integration_test.rs
durch/sphinx
b168f70ac422c6c6ecd80a784958cbee330aab44
extern crate sphinx; use sphinx::crypto; use sphinx::header::delays; use sphinx::route::{Destination, Node}; use sphinx::SphinxPacket; #[cfg(test)] mod create_and_process_sphinx_packet { use super::*; use sphinx::route::{DestinationAddressBytes, NodeAddressBytes}; use sphinx::{ constants::{ ...
extern crate sphinx; use sphinx::crypto; use sphinx::header::delays; use sphinx::route::{Destination, Node}; use sphinx::SphinxPacket; #[cfg(test)] mod create_and_process_sphinx_packet { use super::*; use sphinx::route::{DestinationAddressBytes, NodeAddressBytes}; use sphinx::{ constants::{ ...
#[test] #[should_panic] fn it_panics_if_data_of_invalid_length_is_provided() { let (_, node1_pk) = crypto::keygen(); let node1 = Node::new( NodeAddressBytes::from_bytes([5u8; NODE_ADDRESS_LENGTH]), node1_pk, ); let (_, node2_pk) = crypto::keygen(); ...
let message = vec![13u8, 16]; let sphinx_packet = SphinxPacket::new(message.clone(), &route, &destination, &delays).unwrap(); let sphinx_packet_bytes = sphinx_packet.to_bytes(); let recovered_packet = SphinxPacket::from_bytes(&sphinx_packet_bytes).unwrap(); let next_sphinx_...
function_block-function_prefix_line
[ { "content": "pub fn random_node() -> Node {\n\n let random_private_key = crypto::PrivateKey::new();\n\n Node {\n\n address: NodeAddressBytes::from_bytes([2u8; NODE_ADDRESS_LENGTH]),\n\n pub_key: (&random_private_key).into(),\n\n }\n\n}\n", "file_path": "src/test_utils.rs", "rank"...
Rust
src/main.rs
teru01/mio_webserver
6f873861e272096684f2f76ad93220e49c0d1c8b
extern crate mio; extern crate regex; use std::net::SocketAddr; use std::{ env, str, fs }; use std::io::{ Error, Read, BufReader, Write }; use std::collections::HashMap; use mio::*; use mio::tcp::{ TcpListener, TcpStream }; use regex::Regex; const SERVER: Token = Token(0); const WEBROOT: &str = "/webroot"; struct W...
extern crate mio; extern crate regex; use std::net::SocketAddr; use std::{ env, str, fs }; use std::io::{ Error, Read, BufReader, Write }; use std::collections::HashMap; use mio::*; use mio::tcp::{ TcpListener, TcpStream }; use regex::Regex; const SERVER: Token = Token(0); const WEBROOT: &str = "/webroot"; struct W...
} } fn make_response(buffer: &[u8], nbytes: &usize) -> Result<Vec<u8>, Error> { let http_pattern = Regex::new(r"(.*) (.*) HTTP/1.([0-1])\r\n.*").unwrap(); let captures = match http_pattern.captures(str::from_utf8(&buffer[..*nbytes]).unwrap()) { Some(cap) => cap, ...
if event.readiness().is_readable() { println!("conn_id: {}", conn_id); let mut buffer = [0u8; 512]; let nbytes = stream.read(&mut buffer).expect("Failed to read"); if nbytes != 0 { *response = WebServer::make_response(&buffer, &nbytes)...
if_condition
[ { "content": "# mio_webserver\n\nNon-Blocking I/O web server with rust/mio.\n\n\n\n# How to use\n\n\n\n```\n\n$ cargo run [addr]:[port]\n\n```\n\n\n\nthen connect via telnet, nc or browser\n\n\n\n![sheep](https://user-images.githubusercontent.com/27873650/54591218-24c08c00-4a6d-11e9-9ead-49494b0adffc.png \"shee...
Rust
src/lib.rs
tstellanova/st7789
b1fe2c7af1947a044f37665315ddb28d9845b3ec
#![no_std] #![allow(clippy::type_complexity)] pub mod instruction; use crate::instruction::Instruction; use num_derive::ToPrimitive; use num_traits::ToPrimitive; use display_interface_spi::SPIInterface; use display_interface::WriteOnlyDataCommand; use embedded_hal::blocking::delay::DelayUs; use embedded_hal::block...
#![no_std] #![allow(clippy::type_complexity)] pub mod instruction; use crate::instruction::Instruction; use num_derive::ToPrimitive; use num_traits::ToPrimitive; use display_interface_spi::SPIInterface; use display_interface::WriteOnlyDataCommand; use embedded_hal::blocking::delay::DelayUs; use embedded_hal::block...
fn write_command( &mut self, command: Instruction, params: Option<&[u8]>, ) -> Result<(), Error<PinE>> { self.di .send_commands(&[command.to_u8().unwrap()]) .map_err(|_| Error::DisplayError)?; if let Some(params) = params { self.di.s...
fn write_pixels<T>(&mut self, colors: T) -> Result<(), Error<PinE>> where T: IntoIterator<Item = u16>, { let mut buf = [0; 128]; let mut i = 0; for color in colors { let word = color.to_be_bytes(); buf[i] = word[0]; buf[i + 1] = word[1]; ...
function_block-full_function
[ { "content": "pub trait DrawBatch<DI, RST, T, PinE>\n\nwhere\n\n DI: WriteOnlyDataCommand<u8>,\n\n RST: OutputPin<Error = PinE>,\n\n T: IntoIterator<Item = Pixel<Rgb565>>,\n\n{\n\n fn draw_batch(&mut self, item_pixels: T) -> Result<(), Error<PinE>>;\n\n}\n\n\n\nimpl<DI, RST, T, PinE> DrawBatch<DI, R...
Rust
src/day4.rs
xosdy/aoc2018
c4824b9fb7cc437cf29dbc83cdb10cef3e5ccdd7
use chrono::{NaiveDateTime, Timelike}; use std::collections::HashMap; use std::ops::Range; pub struct Record { id: u32, time_intervals: Vec<Range<u32>>, } #[aoc_generator(day4)] pub fn input_generator(input: &str) -> Vec<Record> { let mut sorted_raw_records = input .lines() ...
use chrono::{NaiveDateTime, Timelike}; use std::collections::HashMap; use std::ops::Range; pub struct Record { id: u32, time_intervals: Vec<Range<u32>>, } #[aoc_generator(day4)]
pub fn get_sleep_times_by_guard(records: &[Record]) -> HashMap<u32, [u32; 60]> { let mut sleep_times_by_guard = HashMap::<u32, [u32; 60]>::new(); for record in records { sleep_times_by_guard .entry(record.id) .and_modify(|sleep_times| { for interval in &record....
pub fn input_generator(input: &str) -> Vec<Record> { let mut sorted_raw_records = input .lines() .map(|line| { let mut parts = line.split(']'); let date_time = NaiveDateTime::parse_from_str(&parts.next().unwrap()[1..], "%F %R").unwrap(); ...
function_block-full_function
[ { "content": "pub fn find_largest_power(serial: u32) -> (Vector2<u32>, i32) {\n\n let mut powers = HashMap::new();\n\n for y in 1..=298 {\n\n for x in 1..=298 {\n\n let position = Vector2::new(x, y);\n\n let power = get_square_power(serial, position, Vector2::new(3, 3));\n\n ...
Rust
src/webdata.rs
andete/show_bgs
4089d645c78ba7c6e98e8321aaee5862aec97228
use chrono::{Date,DateTime,Utc}; use data::{Allegiance, Government, State}; use data; use std::collections::{BTreeMap,HashMap,HashSet}; use serde::de::{self, Deserialize, Deserializer}; #[derive(Debug,Deserialize, Serialize)] pub struct Systems { pub report_name: String, pub systems: Vec<System>, pub d...
use chrono::{Date,DateTime,Utc}; use data::{Allegiance, Government, State}; use data; use std::collections::{BTreeMap,HashMap,HashSet}; use serde::de::{self, Deserialize, Deserializer}; #[derive(Debug,Deserialize, Serialize)] pub struct Systems { pub report_name: String, pub systems: Vec<System>, pub d...
}
e::Expansion, "war" => State::War, "civil unrest" | "civilunrest" => State::CivilUnrest, "civil war" | "civilwar" => State::CivilWar, "election" => State::Election, "boom" => State::Boom, "bust" => State::Bust, "famine" => State::Famine...
function_block-function_prefixed
[ { "content": "pub fn fetch(config: &Config, n_days:i64) {\n\n info!(\"Fetching system info for last {} days\", n_days);\n\n info!(\"and discovering minor factions\");\n\n\n\n let system_names = config.systems();\n\n info!(\"systems: {:?}\", system_names);\n\n\n\n let datadir = config.datadir();\n...
Rust
crossterm_input/src/input/input.rs
defiori/crossterm
3d92f62be470973772e2d3d83fd672c2613f0f87
use super::*; use std::{thread, time::Duration}; use crossterm_utils::TerminalOutput; pub struct TerminalInput<'stdout> { terminal_input: Box<ITerminalInput + Sync + Send>, stdout: Option<&'stdout Arc<TerminalOutput>>, } impl<'stdout> TerminalInput<'stdout> { pub fn new() -> TerminalInput<'stdout>...
use super::*; use std::{thread, time::Duration}; use crossterm_utils::TerminalOutput; pub struct TerminalInput<'stdout> { terminal_input: Box<ITerminalInput + Sync + Send>, stdout: Option<&'stdout Arc<TerminalOutput>>, } impl<'stdout> TerminalInput<'stdout> { pub fn new() -> TerminalInput<'stdout>...
pub fn read_until_async(&self, delimiter: u8) -> AsyncReader { self.terminal_input .read_until_async(delimiter, &self.stdout) } ...
io::stdin().read_line(&mut rv)?; let len = rv.trim_right_matches(&['\r', '\n'][..]).len(); rv.truncate(len); Ok(rv) } pub fn read_char(&self) -> io::Result<char> { self.terminal_input.read_char(&self.stdout) } ...
random
[ { "content": "pub fn raw_modes() {\n\n // create a Screen instance who operates on the default output; io::stdout().\n\n let screen = Screen::default();\n\n\n\n // create a Screen instance who operates on the default output; io::stdout(). By passing in 'true' we make this screen 'raw'\n\n let screen...
Rust
src/transport.rs
balajijinnah/nilai-rs
22510cca078d4de0069491ccb745b95349460f77
/* * Copyright 2019 balajijinnah and Contributors * * 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...
/* * Copyright 2019 balajijinnah and Contributors * * 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...
buf.clear(); match self.handler_recv_ch.next().await { Some(udp_msg) => { let peer = udp_msg.peer.unwrap(); match encode_msg(udp_msg.msg, &mut buf) { Ok(_) => { match...
if let Ok(opt) = self.closer.try_recv() { if let Some(_) = opt { info!("stopping transport sender"); break; } }
if_condition
[ { "content": "fn do_main() -> Result<(), Error> {\n\n let nilai_builder = builder::NilaiBuilder::new(\"127.0.0.1:5001\".parse()?);\n\n let closer = nilai_builder\n\n .alive_delegate(Box::new(|_: types::Node| println!(\"new node joined\")))\n\n .execute()?;\n\n // nilai is running so block...
Rust
wasm/src/message/unpack.rs
spivachuk/didcomm-rust
9a24b3b60f07a11822666dda46e5616a138af056
use std::rc::Rc; use didcomm::{ error::{ErrorKind, ResultExt}, UnpackOptions, }; use js_sys::{Array, Promise}; use wasm_bindgen::prelude::*; use wasm_bindgen_futures::future_to_promise; use crate::{ error::JsResult, utils::set_panic_hook, DIDResolver, JsDIDResolver, JsSecretsResolver, Message, Secrets...
use std::rc::Rc; use didcomm::{ error::{ErrorKind, ResultExt}, UnpackOptions, }; use js_sys::{Array, Promise}; use wasm_bindgen::prelude::*; use wasm_bindgen_futures::future_to_promise; use crate::{ error::JsResult, utils::set_panic_hook, DIDResolver, JsDIDResolver, JsSecretsResolver, Message, Secrets...
} #[wasm_bindgen(typescript_custom_section)] const MESSAGE_UNPACK_TS: &'static str = r#" export namespace Message { /** * Unpacks the packed message by doing decryption and verifying the signatures. * This method supports all DID Comm message types (encrypted, signed, plaintext). * * If unpac...
e::unpack(&msg, &did_resolver, &secrets_resolver, &options) .await .as_js()?; let metadata = JsValue::from_serde(&metadata) .kind(ErrorKind::InvalidState, "Unable serialize UnpackMetadata") .as_js()?; let res = { ...
function_block-function_prefixed
[ { "content": "/// Tries to parse plaintext message into `ParsedForward` structure if the message is Forward.\n\n/// (https://identity.foundation/didcomm-messaging/spec/#messages)\n\n///\n\n/// # Parameters\n\n/// - `msg` plaintext message to try to parse into `ParsedForward` structure\n\n///\n\n/// # Returns\n\...
Rust
src/geometry/aabb.rs
josefrcm/rspt
ad534adf75635338134e4ec71491f55f3065fb6a
use std::f32; use super::*; #[derive(Clone, Copy, Debug)] pub struct AABB { pub lower: nalgebra::Point3<f32>, pub upper: nalgebra::Point3<f32>, } impl AABB { pub fn empty() -> Self { AABB { lower: nalgebra::Point3::new(f32::NAN, f32::NAN, f32::NAN), upper: nalgeb...
use std::f32; use super::*; #[derive(Clone, Copy, Debug)] pub struct AABB { pub lower: nalgebra::Point3<f32>, pub upper: nalgebra::Point3<f32>, } impl AABB { pub fn empty() -> Self { AABB { lower: nalgebra::Point3::new(f32::NAN, f32::NAN, f32::NAN), upper: nalgeb...
} else { Interval::new(f32::INFINITY, f32::INFINITY) } } } pub fn union(boxes: &[AABB]) -> AABB { let mut lower = nalgebra::Point3::new(f32::INFINITY, f32::INFINITY, f32::INFINITY); let mut upper = nalgebra::Point3::new(f32::NEG_INFINITY, f32::NEG_INFINITY, f32::NEG_INFINIT...
rt, f32::max(y_int.start, z_int.start)); let bar = f32::min(x_int.finish, f32::min(y_int.finish, z_int.finish)); if bar >= foo { Interval::new(foo, bar)
function_block-random_span
[ { "content": "pub fn scale(image: &mut Image2D, factor: usize) -> () {\n\n let s = 1.0 / (factor as f32);\n\n image.map_inplace(|a| *a = *a * s);\n\n}\n\n\n", "file_path": "src/tracer/image2d.rs", "rank": 1, "score": 82483.86372930113 }, { "content": "pub fn accum(lhs: &mut Image2D, rh...
Rust
src/enemy.rs
mdenchev/BevyJam1
6be0aafad7a6fce6e4cf51a2dfb9c0c01b5616aa
use bevy::prelude::*; use heron::{prelude::*, rapier_plugin::PhysicsWorld}; use crate::{levels::map::MapInitData, player::PlayerStats, utils::CommonHandles, GameState}; pub struct EnemyPlugin; impl Plugin for EnemyPlugin { fn build(&self, app: &mut App) { app.add_system_set( SystemSet::on_upd...
use bevy::prelude::*; use heron::{prelude::*, rapier_plugin::PhysicsWorld}; use crate::{levels::map::MapInitData, player::PlayerStats, utils::CommonHandles, GameState}; pub struct EnemyPlugin; impl Plugin for EnemyPlugin { fn build(&self, app: &mut App) { app.add_system_set( SystemSet::on_upd...
fn despawn_enemy_on_collision( mut commands: Commands, time: Res<Time>, mut map_init_data: ResMut<MapInitData>, mut game_state: ResMut<State<GameState>>, mut events: EventReader<CollisionEvent>, ) { map_init_data.timer += time.delta(); events.iter().filter(|e| e.is_started()).for_each...
pub fn spawn_enemy(commands: &mut Commands, common_handles: &CommonHandles, position: Vec2) { commands .spawn() .insert_bundle(SpriteSheetBundle { sprite: TextureAtlasSprite::new(40), texture_atlas: common_handles.player_sprites.clone(), transform: Transform::from...
function_block-full_function
[ { "content": "// Going to want this to find the spawn point eventually.\n\npub fn spawn_player(\n\n commands: &mut Commands,\n\n common_handles: &CommonHandles,\n\n pos: (f32, f32),\n\n asset_server: &AssetServer,\n\n is_clone: bool,\n\n clone_id: usize,\n\n) {\n\n if is_clone {\n\n ...
Rust
src/bin/rl/reward.rs
buggedbit/wall-e
e96ec233616661d763a454554c0961a1f9b45912
use ndarray::prelude::*; use serde::{Deserialize, Serialize}; use wall_e::ceo::Reward; use wall_e::diff_drive_model::DiffDriveModel; use wall_e::fcn::*; use wall_e::goal::Goal; #[derive(Debug, Serialize, Deserialize)] #[serde(deny_unknown_fields)] pub struct DiffDriveReward { start_x_bounds: (f32, f32), start_...
use ndarray::prelude::*; use serde::{Deserialize, Serialize}; use wall_e::ceo::Reward; use wall_e::diff_drive_model::DiffDriveModel; use wall_e::fcn::*; use wall_e::goal::Goal; #[derive(Debug, Serialize, Deserialize)] #[serde(deny_unknown_fields)] pub struct DiffDriveReward { start_x_bounds: (f32, f32), start_...
episode_reward -= angular_deviation; episode_reward -= w.abs(); let dist = (x * x + y * y).sqrt(); episode_reward -= dist * 30.0; } let (x, y, _or_in_rad) = model.scaled_state(); ...
let angular_deviation = ((x_hat - or_in_rad.cos()).powf(2.0) + (y_hat - or_in_rad.sin()).powf(2.0)) .sqrt() * (1.0 / (1.0 + tick as f32));
assignment_statement
[ { "content": "fn clamp(v: f32, min_max: (f32, f32)) -> f32 {\n\n let (min, max) = min_max;\n\n if v < min {\n\n return min;\n\n }\n\n if v > max {\n\n return max;\n\n }\n\n v\n\n}\n\n\n\npub struct DiffDriveModel {\n\n x: f32,\n\n y: f32,\n\n or_in_rad: f32,\n\n radiu...
Rust
src/iter/cmp.rs
Bergmann89/aspar
e3d7c56297232aa66e720cc0766b1c25bc11420d
use std::cmp::{Ord, Ordering, PartialEq, PartialOrd}; use crate::{Driver, Executor, IndexedParallelIterator, ParallelIterator, WithIndexedProducer}; /* Cmp */ pub struct Cmp<XA, XB> { iterator_a: XA, iterator_b: XB, } impl<XA, XB> Cmp<XA, XB> { pub fn new(iterator_a: XA, iterator_b: XB) -> Self { ...
use std::cmp::{Ord, Ordering, PartialEq, PartialOrd}; use crate::{Driver, Executor, IndexedParallelIterator, ParallelIterator, WithIndexedProducer}; /* Cmp */ pub struct Cmp<XA, XB> { iterator_a: XA, iterator_b: XB, } impl<XA, XB> Cmp<XA, XB> { pub fn new(iterator_a: XA, iterator_b: XB) -> Self { ...
pub fn new(iterator_a: XA, iterator_b: XB, ord: Ordering, ord_opt: Option<Ordering>) -> Self { Self { iterator_a, iterator_b, ord, ord_opt, } } } impl<'a, XA, XB, I> Driver<'a, bool, Option<Ordering>, Option<Option<Ordering>>> for Compare<XA, XB> wher...
ator_b) .all(move |(x, y)| PartialEq::eq(&x, &y) == expected) .exec_with(executor) } } /* Compare */ pub struct Compare<XA, XB> { iterator_a: XA, iterator_b: XB, ord: Ordering, ord_opt: Option<Ordering>, } impl<XA, XB> Compare<XA, XB> {
random
[]
Rust
src/fake_device.rs
szeged/blurmock
a538c2c5eaf19071d964b09819d9ca8fdebfb1a1
use core::ops::Deref; use fake_adapter::FakeBluetoothAdapter; use fake_service::FakeBluetoothGATTService; use hex; use std::collections::HashMap; use std::error::Error; use std::sync::{Arc, Mutex}; #[derive(Clone, Debug)] pub struct FakeBluetoothDevice { id: Arc<Mutex<String>>, adapter: Arc<FakeBluetoothAdapte...
use core::ops::Deref; use fake_adapter::FakeBluetoothAdapter; use fake_service::FakeBluetoothGATTService; use hex; use std::collections::HashMap; use std::error::Error; use std::sync::{Arc, Mutex}; #[derive(Clone, Debug)] pub struct FakeBluetoothDevice { id: Arc<Mutex<String>>, adapter: Arc<FakeBluetoothAdapte...
} pub fn get_vendor_id_source(&self) -> Result<String, Box<Error>> { let (vendor_id_source,_,_,_) = try!(self.get_modalias()); Ok(vendor_id_source) } pub fn get_vendor_id(&self) -> Result<u32, Box<Error>> { let (_,vendor_id,_,_) = try!(self.get_modalias()); Ok(vendor_i...
Ok((source, (vendor[0] as u32) * 16 * 16 + (vendor[1] as u32), (product[0] as u32) * 16 * 16 + (product[1] as u32), (device[0] as u32) * 16 * 16 + (device[1] as u32)))
call_expression
[ { "content": "\n\n pub fn get_modalias(&self) -> Result<(String, u32, u32, u32), Box<Error>> {\n\n let cloned = self.modalias.clone();\n\n let modalias = match cloned.lock() {\n\n Ok(guard) => guard.deref().clone(),\n\n Err(_) => return Err(Box::from(\"Could not get the v...
Rust
build/src/lib.rs
BusyJay/jinkela
88cdbdb57ae53ea13ea1b8f81e4641e6d67686b4
use std::fs::File; use std::io::Write; #[derive(Default)] pub struct Builder { out_dir: Option<String>, includes: Vec<String>, sources: Vec<String>, } impl Builder { pub fn out_dir(&mut self, dir: impl Into<String>) -> &mut Builder { self.out_dir = Some(dir.into()); self } pub...
use std::fs::File; use std::io::Write; #[derive(Default)] pub struct Builder { out_dir: Option<String>, includes: Vec<String>, sources: Vec<String>, } impl Builder { pub fn out_dir(&mut self, dir: impl Into<String>) -> &mut Builder { self.out_dir = Some(dir.into()); self } pub...
); } let out_dir = std::path::Path::new(out_dir); let results = grpcio_compiler::codegen::gen(&desc.file, &files_to_generate); for res in results { let out_file = out_dir.join(&res.name); let mut f = File::create(&out_file).unwrap(); f.write_all(&res.c...
file in &self.sources { let f = std::path::Path::new(file); for include in &self.includes { if let Some(truncated) = f.strip_prefix(include).ok() { files_to_generate.push(format!("{}", truncated.display())); continue 'outer; ...
function_block-random_span
[ { "content": "#[proc_macro_derive(Classicalize, attributes(prost))]\n\npub fn classicalize(input: TokenStream) -> TokenStream {\n\n let input: DeriveInput = syn::parse(input).unwrap();\n\n let s = match input.data {\n\n Data::Struct(s) => classicalize_struct(input.ident, s),\n\n Data::Enum(e...
Rust
src/sms/async/send.rs
drahnr/messagebird
2d22bac58359b9f21410d47bc306d36b538ea710
use super::super::*; use futures::*; use hyper; use hyper_rustls; use std::env; use std::fmt; use std::marker::PhantomData; use std::ops::Deref; #[derive(Debug, Clone)] pub struct AccessKey(String); impl Deref for AccessKey { type Target = String; fn deref(&self) -> &Self::Target { &self.0 } ...
use super::super::*; use futures::*; use hyper; use hyper_rustls; use std::env; use std::fmt; use std::marker::PhantomData; use std::ops::Deref; #[derive(Debug, Clone)] pub struct AccessKey(String); impl Deref for AccessKey { type Target = String; fn deref(&self) -> &Self::Target { &self.0 } ...
futures::future::ok(response) }) .and_then(|response: hyper::Response<hyper::Body>| { let status = response.status(); let body: hyper::Body = response.into_body(); ...
t = Request<parameter::list::ListParameters, MessageList>; pub type RequestView = Request<parameter::view::ViewParameters, Message>; pub type RequestSend = Request<parameter::send::SendParameters, Message>; pub struct Request<T, R> { future: Box<dyn Future<Item = R, Error = MessageBirdError>>, phantom: Phant...
random
[ { "content": "/// TODO the name is misleading/obsolete, should be something with params\n\npub trait Query {\n\n fn uri(&self) -> hyper::Uri;\n\n fn method(&self) -> hyper::Method {\n\n hyper::Method::GET\n\n }\n\n}\n\n\n\n/// Contact Id\n\n///\n\n/// TODO not implemented just yet\n\n#[derive(Cl...
Rust
crate/object_play/src/system/object_acceleration_system.rs
Lighty0410/autexousious
99d142d8fdbf2076f3fd929f61b8140d47cf6b86
use amethyst::{ ecs::{Join, Read, ReadStorage, System, World, WriteStorage}, shred::{ResourceId, SystemData}, shrev::{EventChannel, ReaderId}, }; use derivative::Derivative; use derive_new::new; use game_input_model::play::ControllerInput; use kinematic_model::config::{ ObjectAcceleration, ObjectAcceler...
use amethyst::{ ecs::{Join, Read, ReadStorage, System, World, WriteStorage}, shred::{ResourceId, SystemData}, shrev::{EventChannel, ReaderId}, }; use derivative::Derivative; use derive_new::new; use game_input_model::play::ControllerInput; use kinematic_model::config::{ ObjectAcceleration, ObjectAcceler...
fn acceleration_value( controller_input: Option<ControllerInput>, object_acceleration_value: ObjectAccelerationValue, ) -> f32 { match object_acceleration_value { ObjectAccelerationValue::Const(value) => value, ObjectAccelerationValue::Expr(ObjectAccelerationVal...
fn update_velocity( controller_input: Option<ControllerInput>, mirrored: Option<Mirrored>, object_acceleration: ObjectAcceleration, velocity: &mut Velocity<f32>, ) { let negate = mirrored.map(|mirrored| mirrored.0).unwrap_or(false); let acc_x = Self::acceleration_valu...
function_block-full_function
[ { "content": "#[derive(Clone, Copy, Debug, Default, Hash, PartialEq, Eq)]\n\nstruct SessionCodeId(pub u64);\n\n\n\n/// Mappings from `SessionCode` to `NetSessionDevices`, and `SocketAddr` to `SessionCode`.\n\n#[derive(Clone, Debug, Default, new)]\n\npub struct SessionDeviceMappings {\n\n /// Mappings from `S...
Rust
src/server.rs
dethoter/tokio_test
c0185eb40b9e5bc994cf3b2b4916c924de3affa0
#![cfg_attr(feature="clippy", feature(plugin))] #![cfg_attr(feature="clippy", plugin(clippy))] #![deny(deprecated)] extern crate tokio_proto; extern crate tokio_io; extern crate tokio_service; extern crate tokio_timer; extern crate futures; extern crate futures_cpupool; extern crate bytes; extern crate bincode; extern ...
#![cfg_attr(feature="clippy", feature(plugin))] #![cfg_attr(feature="clippy", plugin(clippy))] #![deny(deprecated)] extern crate tokio_proto; extern crate tokio_io; extern crate tokio_service; extern crate tokio_timer; extern crate futures; extern crate futures_cpupool; extern crate bytes; extern crate bincode; extern ...
} fn count(max: u64) -> Duration { let now = Instant::now(); let mut i = 0; while i < max { i += 1; } now.elapsed() } fn serve(address: SocketAddr, pool: CpuPool, duration: Duration) { TcpServer::new(ServerProtocol, address).serve(move || { Ok(Counter { thread_po...
nt(num))) .select(timeout) .map(|(r, _)| r); Box::new( task.and_then(move |d| { println!("Response: Duration({:?},{:?})", num, &d); future::ok(CountResponse::Duration(num, d)) }).or_else(move |_| { ...
function_block-function_prefixed
[ { "content": "fn request_count(address: SocketAddr, range_max: usize, requests: usize) {\n\n let mut core = Core::new().unwrap();\n\n let handle = core.handle();\n\n\n\n let promises = (0..requests)\n\n .map(move |_| {\n\n TcpClient::new(ClientProtocol)\n\n .connect(&ad...
Rust
d3-core/src/scheduler/sched.rs
BruceBrown/d3
688ee218a994f3aab2fddc75feac308c58174333
use self::traits::*; use super::*; use crossbeam::channel::RecvTimeoutError; type MachineMap = super_slab::SuperSlab<ShareableMachine>; #[allow(dead_code)] #[allow(non_upper_case_globals)] pub static machine_count_estimate: AtomicCell<usize> = AtomicCell::new(5000); #[allow(dead_code)] pub fn get_machine_count_est...
use self::traits::*; use super::*; use crossbeam::channel::RecvTimeoutError; type MachineMap = super_slab::SuperSlab<ShareableMachine>; #[allow(dead_code)] #[allow(non_upper_case_globals)] pub static machine_count_estimate: AtomicCell<usize> = AtomicCell::new(5000); #[allow(dead_code)] pub fn get_machine_count_est...
ter)); senders.push(sender); machines.push(alice); sched_sender.send(SchedCmd::New(adapter)).unwrap(); } let s = &senders[2]; s.send(TestMessage::Test).unwrap(); std::thread::sleep(std::time::Duration::from_millis(500)); sched_sender.send(Sch...
t (sched_sender, sched_receiver) = crossbeam::channel::unbounded::<SchedCmd>(); let run_queue = new_executor_injector(); let wait_queue = Arc::new(deque::Injector::<SchedTask>::new()); let thread = SchedulerThread::spawn(sched_receiver, monitor_sender, (run_queue, wait_queue)); ...
function_block-random_span
[ { "content": "type RecvCmdFn = Box<dyn Fn(&ShareableMachine, bool, Duration, &mut ExecutorStats) + Send + Sync + 'static>;\n\n\n\n#[derive(Debug)]\n\npub struct DefaultMachineDependentAdapter {}\n\nimpl MachineDependentAdapter for DefaultMachineDependentAdapter {\n\n fn receive_cmd(&self, _machine: &Shareabl...
Rust
src/main.rs
diodesign/rustinvaders
40d4f0adda37ecf4f851a65ff206954bbba812ac
/* Space invaders in Rust * * Game concept by Tomohiro Nishikado / Taito * Rust code By Chris Williams <diodesign@tuta.io> * * Written for fun. See LICENSE. * */ extern crate glfw; extern crate kiss3d; extern crate nalgebra as na; extern crate rand; use std::path::Path; use na::{ Point3, Point2 }; use kiss3d::...
/* Space invaders in Rust * * Game concept by Tomohiro Nishikado / Taito * Rust code By Chris Williams <diodesign@tuta.io> * * Written for fun. See LICENSE. * */ extern crate glfw; extern crate kiss3d; extern crate nalgebra as na; extern crate rand; use std::path::Path; use na::{ Point3, Point2 }; use kiss3d::...
(player_x_pos, player_y_pos) == collision::CollisionOutcome::Hit { playfield.player.destroy(&mut window); /* window needed to add explosion debris to game world */ state.lives = state.lives - 1 } /* did the aliens manage to get below the player? if so, that's an instant * game over, I'm af...
/* get the player's x, y coords */ let (player_x_pos, player_y_pos, _) = playfield.player.get_coords(); /* did an alien fly into the player? */ if playfield.aliens.collision
random
[ { "content": "#[derive(PartialEq)]\n\nenum State\n\n{\n\n Alive,\n\n Dying,\n\n Dead\n\n}\n\n\n\n/* aliens are either shuffling left, right, or down and then right, or down then left */\n\npub enum Movement\n\n{\n\n Left, /* moving left */\n\n Right, /* moving right */\n\n DownRight, /* ...
Rust
src/lib.rs
tekjar/rumqtt-coroutines
10212a4f10c697a0ad23217257039e6045ca9029
#![feature(proc_macro, conservative_impl_trait, generators)] extern crate futures_await as futures; extern crate tokio_core; extern crate tokio_io; extern crate tokio_timer; extern crate mqtt3; extern crate bytes; #[macro_use] extern crate log; mod codec; mod packet; use std::net::{IpAddr, Ipv4Addr, SocketAddr}; use...
#![feature(proc_macro, conservative_impl_trait, generators)] extern crate futures_await as futures; extern crate tokio_core; extern crate tokio_io; extern crate tokio_timer; extern crate mqtt3; extern crate bytes; #[macro_use] extern crate log; mod codec; mod packet; use std::net::{IpAddr, Ipv4Addr, SocketAddr}; use...
#[async] fn ping_timer(mut commands_tx: Sender<NetworkRequest>) -> io::Result<()> { let timer = Timer::default(); let keep_alive = 10; let interval = timer.interval(Duration::new(keep_alive, 0)); #[async] for _t in interval { println!("Ping timer fire"); commands_tx = await!( ...
or.handle(); let address = SocketAddr::new(IpAddr::V4(Ipv4Addr::new(127, 0, 0, 1)), 1883); let (commands_tx, commands_rx) = mpsc::channel::<NetworkRequest>(1000); let ping_commands_tx = commands_tx.clone(); let client = async_block! { thread::sleep(Duration::new(5, 0)); ...
function_block-function_prefixed
[ { "content": "pub fn gen_pingreq_packet() -> Packet {\n\n Packet::Pingreq\n\n}\n\n\n\n// pub fn gen_pingresp_packet() -> Packet {\n\n// Packet::Pingresp\n\n// }\n\n\n\n// pub fn gen_subscribe_packet(pkid: PacketIdentifier, topics: Vec<SubscribeTopic>) -> Packet {\n\n// Packet::Subscribe(Subscribe {\n...
Rust
src/parser_combinator.rs
KoheiAsano/sym_diff
17cdb5972825b9aa1c0662da5499020f53c94cf6
use super::expr::Env; pub type ParseResult<'a, Output> = Result<(&'a str, &'a Env, Output), &'a str>; pub trait Parser<'a, Output> { fn parse(&self, input: &'a str, env: &'a Env) -> ParseResult<'a, Output>; fn map<F, NewOutput>(self, map_fn: F) -> BoxedParser<'a, NewOutput> where Self: Sized + ...
use super::expr::Env; pub type ParseResult<'a, Output> = Result<(&'a str, &'a Env, Output), &'a str>; pub trait Parser<'a, Output> { fn parse(&self, input: &'a str, env: &'a Env) -> ParseResult<'a, Output>; fn map<F, NewOutput>(self, map_fn: F) -> BoxedParser<'a, NewOutput> where Self: Sized + ...
ext_input, next_env, result1)| { parser2 .parse(next_input, next_env) .map(|(last_input, last_env, result2)| { (last_input, last_env, (result1, result2)) }) }) } } pub fn left<'a, P1, P2, R1, R2>(parser1...
-> impl Parser<'a, B> where P: Parser<'a, A>, F: Fn(A) -> B, { move |input, env| { parser .parse(input, env) .map(|(next_input, next_env, result)| (next_input, next_env, map_fn(result))) } } pub fn pair<'a, P1, P2, R1, R2>(parser1: P1, parser2: P2) -> impl Parser<'a, (R...
random
[ { "content": "pub fn expr<'a>() -> impl Parser<'a, (Rc<Expr>, &'a Env)> {\n\n whitespace_wrap(term()).and_then(|(one, env)| {\n\n zero_or_more(whitespace_wrap(pair(\n\n whitespace_wrap(any_char.pred(|(c, _e)| *c == '+' || *c == '-')),\n\n term(),\n\n )))\n\n .map(mo...
Rust
src/message.rs
gridgentoo/rust-rdkafka
fcb0bab41894e96208fd745e79ce7f73e4bcebbe
use rdsys; use rdsys::types::*; use std::ffi::CStr; use std::fmt; use std::marker::PhantomData; use std::slice; use std::str; use consumer::{Consumer, ConsumerContext}; #[derive(Debug,PartialEq,Eq,Clone,Copy)] pub enum Timestamp { NotAvailable, CreateTime(i64), LogAppendTime(i64) } impl Timestamp { ...
use rdsys; use rdsys::types::*; use std::ffi::CStr; use std::fmt; use std::marker::PhantomData; use std::slice; use std::str; use consumer::{Consumer, ConsumerContext}; #[derive(Debug,PartialEq,Eq,Clone,Copy)] pub enum Timestamp { NotAvailable, CreateTime(i64), LogAppendTime(i64) } impl Timestamp { ...
one } else { Some(slice::from_raw_parts::<u8>((*self.ptr).payload as *const u8, (*self.ptr).len)) } } } fn topic(&self) -> &str { unsafe { CStr::from_ptr(rdsys::rd_kafka_topic_name((*self.ptr).rkt)) .to_str() ...
ct BorrowedMessage<'a> { ptr: *mut RDKafkaMessage, _p: PhantomData<&'a u8>, } impl<'a> fmt::Debug for BorrowedMessage<'a> { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { write!(f, "Message {{ ptr: {:?} }}", self.ptr()) } } impl<'a> BorrowedMessage<'a> { pub fn new<C, X>(...
random
[ { "content": "pub fn value_fn(id: i32) -> String {\n\n format!(\"Message {}\", id)\n\n}\n\n\n", "file_path": "tests/test_utils.rs", "rank": 3, "score": 121805.88676946462 }, { "content": "pub fn key_fn(id: i32) -> String {\n\n format!(\"Key {}\", id)\n\n}\n", "file_path": "tests/te...
Rust
src/libnet/src/http2/error.rs
Veil-Project/Veil-Rust
bd32fb781a9fe6f22aede1bb7cd0aa227b820939
use std::error; use std::fmt; use std::io; use std::result; use super::hpack; pub type Result<T> = result::Result<T, Error>; #[derive(Debug, Clone, Copy)] pub enum ProtocolErrorKind { None = 0x0, Protocol = 0x1, Internal = 0x2, FlowControl = 0x3, SettingsTimeo...
use std::error; use std::fmt; use std::io; use std::result; use super::hpack; pub type Result<T> = result::Result<T, Error>; #[derive(Debug, Clone, Copy)] pub enum ProtocolErrorKind { None = 0x0, Protocol = 0x1, Internal = 0x2, FlowControl = 0x3, SettingsTimeo...
} pub struct Error(Box<Repr>); impl Error { pub fn new(kind: Repr) -> Error { Error(Box::new(kind)) } pub fn from_raw_protocol_error(code: isize) -> Error { Error(Box::new(Repr::Protocol(ProtocolErrorKind::from_code(code)))) } pub fn raw_protocol_error(&self) -> Option<isize> { ...
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { use Repr::*; match self { Io(ref e) => e.fmt(f), Protocol(kind) => f .debug_struct("Protocol") .field("code", &kind.as_code()) .field("id", &kind.as_id_str()) ...
function_block-full_function
[]
Rust
kernel/src/arch/x86_64/memory/address_space_manager.rs
aeleos/VeOS
4c766539ac10ad7b044bcf1b49fd5f0ae8fc21c6
use super::paging::inactive_page_table::InactivePageTable; use super::paging::page_table_entry::*; use super::paging::page_table_manager::PageTableManager; use super::paging::{convert_flags, Page, PageFrame, CURRENT_PAGE_TABLE}; use super::PAGE_SIZE; use super::{ KERNEL_STACK_AREA_BASE, KERNEL_STACK_MAX_SIZE, KER...
use super::paging::inactive_page_table::InactivePageTable; use super::paging::page_table_entry::*; use super::paging::page_table_manager::PageTableManager; use super::paging::{convert_flags, Page, PageFrame, CURRENT_PAGE_TABLE}; use super::PAGE_SIZE; use super::{ KERNEL_STACK_AREA_BASE, KERNEL_STACK_MAX_SIZE, KER...
fn create_idle_stack(cpu_id: usize) -> Stack { Stack::new( 0x3000, KERNEL_STACK_MAX_SIZE, KERNEL_STACK_AREA_BASE + KERNEL_STACK_OFFSET * cpu_id, AccessType::KernelOnly, None, ) } }
ut AddressSpace) -> Stack { let tid: usize = id.into(); Stack::new( 0x2000, USER_STACK_MAX_SIZE, USER_STACK_AREA_BASE + USER_STACK_OFFSET * tid, AccessType::UserAccessible, Some(address_space), ) }
function_block-function_prefixed
[ { "content": "/// Maps the given page to the given frame using the given flags.\n\npub fn map_page_at(page_address: VirtualAddress, frame_address: PhysicalAddress, flags: PageFlags) {\n\n CURRENT_PAGE_TABLE.lock().map_page_at(\n\n Page::from_address(page_address),\n\n PageFrame::from_address(fr...
Rust
src/db/models/configs.rs
nlopes/avro-schema-registry
f18168bacfd1f141be857b7f41cda8c7a874ce93
use std::fmt; use std::str; use chrono::NaiveDateTime; use diesel::prelude::*; use crate::api::errors::{ApiAvroErrorCode, ApiError}; use super::schema::*; use super::Subject; #[derive(Debug, Identifiable, Queryable, Associations, Serialize)] #[table_name = "configs"] #[belongs_to(Subject)] pub struct Config { p...
use std::fmt; use std::str; use chrono::NaiveDateTime; use diesel::prelude::*; use crate::api::errors::{ApiAvroErrorCode, ApiError}; use super::schema::*; use super::Subject; #[derive(Debug, Identifiable, Queryable, Associations, Serialize)] #[table_name = "configs"] #[belongs_to(Subject)] pub struct Config { p...
impl str::FromStr for CompatibilityLevel { type Err = (); fn from_str(s: &str) -> Result<Self, ()> { match s { "BACKWARD" => Ok(Self::Backward), "BACKWARD_TRANSITIVE" => Ok(Self::BackwardTransitive), "FORWARD" => Ok(Self::Forward), "FORWARD_TRANSITIVE" =>...
&mut fmt::Formatter) -> fmt::Result { let screaming_snake_case = match self { Self::Backward => Ok("BACKWARD"), Self::BackwardTransitive => Ok("BACKWARD_TRANSITIVE"), Self::Forward => Ok("FORWARD"), Self::ForwardTransitive => Ok("FORWARD_TRANSITIVE"), ...
random
[ { "content": "#[derive(Debug, Serialize)]\n\nstruct SchemaCompatibility {\n\n is_compatible: bool,\n\n}\n\n\n\nimpl SchemaCompatibility {\n\n fn is_compatible(\n\n old: &str,\n\n new: &str,\n\n compatibility: CompatibilityLevel,\n\n ) -> Result<bool, ApiError> {\n\n match co...
Rust
src/mdbook/files.rs
igorlesik/svdocgen
4e3548720e3fd7673634d557a340be9ecee58a36
use std::fs; use std::path::{Path, PathBuf}; use std::io; use crate::args; use crate::fsnode::FsNode; pub struct SrcFiles { pub nodes: FsNode, } pub fn collect_sources(options: &args::ParsedOptions) -> Result<SrcFiles,String> { let mut inputs: Vec<PathBuf> = Vec::new(); for input in &options.in...
use std::fs; use std::path::{Path, PathBuf}; use std::io; use crate::args; use crate::fsnode::FsNode; pub struct SrcFiles { pub nodes: FsNode, } pub fn collect_sources(options: &args::ParsedOptions) -> Result<SrcFiles,String> { let mut inputs: Vec<PathBuf> = Vec::new(); for input in &options.in...
pub fn get_md_files(all_files: &FsNode) -> Result<FsNode,String> { get_files_with_extensions(all_files, &["md"]) } pub fn get_sv_files(all_files: &FsNode) -> Result<FsNode,String> { get_files_with_extensions(all_files, &["sv", "v"]) }
extensions: &[&str] ) -> Result<FsNode,String> { let mut files_with_ext = FsNode { name: String::from(""), children: Vec::new() }; let mut/*env*/ filter_files = |_node: &FsNode, path: &PathBuf, _level: usize| { if path.is_file() { if let Some(ext) = path.extension(...
function_block-function_prefix_line
[ { "content": "/// Create files.md file that lists all input files.\n\n///\n\n///\n\nfn create_files_md(path: &str, files: &FsNode) -> Result<String,String> {\n\n\n\n let fname = Path::new(&path).join(\"files.md\");\n\n let fname = fname.to_str().unwrap();\n\n\n\n let file = match fs::OpenOptions::new()...
Rust
src/macos/mod.rs
ignatenkobrain/rust-locale
9acaf6987a97f8ffcda0e3ce6e8770e7a01ece09
use std::borrow::ToOwned; use std::env::var; use std::fs::{metadata, File}; use std::io::{BufRead, Error, Result, BufReader}; use std::path::{Path, PathBuf}; use super::{LocaleFactory, Numeric, Time}; static LOCALE_DIR: &'static str = "/usr/share/locale"; #[derive(Debug, Clone)] enum LocaleType { Numeric, Time...
use std::borrow::ToOwned; use std::env::var; use std::fs::{metadata, File}; use std::io::{BufRead, Error, Result, BufReader}; use std::path::{Path, PathBuf}; use super::{LocaleFactory, Numeric, Time}; static LOCALE_DIR: &'static str = "/usr/share/locale"; #[derive(Debug, Clone)] enum LocaleType { Numeric, Time...
None } fn find_locale_path(locale_type: LocaleType, locale_name: &str) -> Option<PathBuf> { let file_name = match locale_type { LocaleType::Numeric => "LC_NUMERIC", LocaleType::Time => "LC_TIME", }; if locale_name == "" { return find_user_locale_path(&file_name); } els...
if let Ok(lang) = var("LANG") { let path = locale_dir.join(Path::new(&lang)).join(Path::new(file_name)); if path.exists() { return Some(path); } }
if_condition
[ { "content": "#[cfg(not(target_os = \"linux\"))]\n\npub fn main() {\n\n println!(\"Listing locale info not (yet) supported on this system\");\n\n}\n", "file_path": "examples/localeinfo.rs", "rank": 5, "score": 33880.010529542735 }, { "content": "/// Return LocaleFactory appropriate for de...
Rust
src/shape.rs
magnusstrale/raytracer
58ea8e85380de87a9abffa5e376dd01fc4c2901c
use std::any::Any; use std::fmt; use super::tuple::Tuple; use super::ray::Ray; use super::intersection::Intersections; use super::material::Material; use super::matrix::{Matrix, IDENTITY_MATRIX}; pub trait Shape: Any + fmt::Debug { fn box_clone(&self) -> BoxShape; fn box_eq(&self, other: &dyn Any) -> bool; ...
use std::any::Any; use std::fmt; use super::tuple::Tuple; use super::ray::Ray; use super::intersection::Intersections; use super::material::Material; use super::matrix::{Matrix, IDENTITY_MATRIX}; pub trait Shape: Any + fmt::Debug { fn box_clone(&self) -> BoxShape; fn box_eq(&self, other: &dyn Any) -> bool; ...
) { let s = TestShape::new(None, None); assert_eq!(s.transformation(), IDENTITY_MATRIX); } #[test] fn assign_transformation() { let tr = Matrix::translation(2., 3., 4.); let s = TestShape::new(None, Some(tr)); assert_eq!(s.transformation(), tr); } #[test] ...
ormation(&self) -> Matrix { self.inverse_transform } } impl TestShape { fn new(material: Option<Material>, transform: Option<Matrix>) -> Self { Self { material: material.unwrap_or_default(), transform: transform.unwrap_or_default(), ...
random
[ { "content": "pub trait Pattern: Any + fmt::Debug {\n\n fn box_clone(&self) -> BoxPattern;\n\n fn box_eq(&self, other: &dyn Any) -> bool;\n\n fn as_any(&self) -> &dyn Any;\n\n fn transformation(&self) -> Matrix;\n\n fn inverse_transformation(&self) -> Matrix;\n\n fn inner_pattern_at(&self, pat...
Rust
src/lib.rs
kchmck/uhttp_content_encoding.rs
683fff450707ae509a4d3a4a863108364d3e643a
#![feature(conservative_impl_trait)] use std::ascii::AsciiExt; pub fn content_encodings<'a>(s: &'a str) -> impl Iterator<Item = ContentEncoding<'a>> { s.split(',').rev().map(ContentEncoding::new) } #[derive(Copy, Clone, Eq, PartialEq, Debug, Hash)] pub enum ContentEncoding<'a> { Std(StdContentEncoding...
#![feature(conservative_impl_trait)] use std::ascii::AsciiExt; pub fn content_encodings<'a>(s: &'a str) -> impl Iterator<Item = ContentEncoding<'a>> { s.split(',').rev().map(ContentEncoding::new) } #[derive(Copy, Clone, Eq, PartialEq, Debug, Hash)] pub enum ContentEncoding<'a> { Std(StdContentEncoding...
} #[derive(Copy, Clone, Eq, PartialEq, Debug, Hash)] pub enum StdContentEncoding { Brottli, Compress, Deflate, EfficientXML, Gzip, Identity, Pack200Gzip, } impl std::str::FromStr for StdContentEncoding { type Err = (); fn from_str(s: &str) -> st...
pub fn new(s: &'a str) -> Self { let s = s.trim(); match s.parse() { Ok(enc) => ContentEncoding::Std(enc), Err(_) => ContentEncoding::Other(s), } }
function_block-full_function
[ { "content": "# uhttp\\_content\\_encoding -- Parser for HTTP Content-Encoding header\n\n\n\n[Documentation](https://docs.rs/uhttp_content_encoding)\n\n\n\nThis crate provides a zero-allocation, iterator/slice-based parser for extracting HTTP\n\n[content encoding](https://tools.ietf.org/html/rfc7231#section-3.1...
Rust
src/writer/header.rs
diegodox/ply_rs
0bdce2456117d278b2c176b9b46d5e0363dd3f2f
use std::io::{BufWriter, Write}; use crate::{Comment, Element, Format, GenericElement, PLYFile, Property, PropertyList}; const MAGIC_NUMBER: &str = "ply"; const END_HEADER: &str = "end_header"; pub(crate) trait PlyWriteHeader<T: Write> { fn write_header(&self, writer: &mut BufWriter<T>) -> std::io::Result<()>; }...
use std::io::{BufWriter, Write}; use crate::{Comment, Element, Format, GenericElement, PLYFile, Property, PropertyLi
rite_property_list() { use crate::*; let mut writer = BufWriter::new(Vec::new()); let property = PropertyList { name: "vertex".to_string(), count: PLYValueTypeName::Uchar, prop: PLYValueTypeName::Float, }; property.write_header(&mut writer).unwrap(); assert_eq!( w...
st}; const MAGIC_NUMBER: &str = "ply"; const END_HEADER: &str = "end_header"; pub(crate) trait PlyWriteHeader<T: Write> { fn write_header(&self, writer: &mut BufWriter<T>) -> std::io::Result<()>; } impl<T: Write> PlyWriteHeader<T> for PLYFile { fn write_header(&self, writer: &mut BufWriter<T>) -> std::io::Re...
random
[ { "content": "#[test]\n\nfn test_write_element_payload_ascii() {\n\n use crate::*;\n\n let mut writer = BufWriter::new(Vec::new());\n\n let element = GenericElement {\n\n name: \"vertex\".to_string(),\n\n count: 8,\n\n props: Property {\n\n props: vec![\n\n ...
Rust
backend/api/src/http/endpoints/user/public_user.rs
jewish-interactive/ji-cloud
b6164bf1d15277115bcab1d8c9f91619e706231d
use actix_web::{ web::{Data, Json, Path, Query}, HttpResponse, }; use futures::try_join; use shared::{ api::{endpoints::user, ApiEndpoint}, domain::{ asset::DraftOrLive, course::CourseBrowseResponse, jig::JigBrowseResponse, user::public_user::{ BrowsePublicUse...
use actix_web::{ web::{Data, Json, Path, Query}, HttpResponse, }; use futures::try_join; use shared::{ api::{endpoints::user, ApiEndpoint}, domain::{ asset::DraftOrLive, course::CourseBrowseResponse, jig::JigBrowseResponse, user::public_user::{ BrowsePublicUse...
}
&& limit <= MAX_PAGE_LIMIT { true => Ok(limit), false => Err(anyhow::anyhow!("Page limit should be within 1-100")), } } else { Ok(DEFAULT_PAGE_LIMIT) }
function_block-random_span
[ { "content": "pub fn search(state: Rc<State>, page: Option<u32>) {\n\n state.loader.load(clone!(state => async move {\n\n match state.search_mode.get_cloned() {\n\n SearchMode::Sticker(_) => search_async(Rc::clone(&state), page.unwrap_or_default()).await,\n\n SearchMode::Web(_) =...
Rust
src/levels/level_list.rs
yancouto/functional
86e9f0d59e84983f0e0604b74286832af0b38da1
use serde::Deserialize; use super::{BaseLevel, GameLevel, TestCase}; use crate::prelude::*; fn get_true() -> bool { true } #[derive(Debug, Deserialize)] #[serde(deny_unknown_fields)] pub struct JLevel { pub name: String, pub description: String, pub extra_info: Opti...
use serde::Deserialize; use super::{BaseLevel, GameLevel, TestCase}; use crate::prelude::*; fn get_true() -> bool { true } #[derive(Debug, Deserialize)] #[serde(deny_unknown_fields)] pub struct JLevel { pub name: String, pub description: String, pub extra_info: Opti...
ections() { all_sections(vec![$(SectionName::$name),*]) } } } solution_tests!( Basic, Boolean, Numerals, PairAndList, Recursion, MoreNumerals ); #[test] fn test_wrong_solutions() { LEVELS.iter().flat_map(|s...
n { vec![] } else { let mut idx = 0; s.levels .mapped(|l| { if l.extra_info_is_hint { debug_assert!(l.extra_info.is_some()); } ...
random
[ { "content": "fn get_level_config_json() -> String {\n\n match std::process::Command::new(\"jsonnet\")\n\n .args(&[\n\n \"-J\",\n\n \"src/levels/config\",\n\n \"src/levels/config/level_config.jsonnet\",\n\n ])\n\n .output()\n\n {\n\n Ok(o) if !o...
Rust
src/render/src/encoder.rs
pravic/gfx
f0fde6d3d05412358d08707f66c544fb48c6a531
#![deny(missing_docs)] use std::mem; use draw_state::target::{Depth, Stencil}; use gfx_core::{Device, IndexType, Resources, VertexCount}; use gfx_core::{draw, format, handle, tex}; use gfx_core::factory::{cast_slice, Typed}; use mesh; use pso; #[allow(missing_docs)] #[derive(Clone, Debug, PartialEq)] pub enum Upda...
#![deny(missing_docs)] use std::mem; use draw_state::target::{Depth, Stencil}; use gfx_core::{Device, IndexType, Resources, VertexCount}; use gfx_core::{draw, format, handle, tex}; use gfx_core::factory::{cast_slice, Typed}; use mesh; use pso; #[allow(missing_docs)] #[derive(Clone, Debug, PartialEq)] pub enum Upda...
Format>(&mut self, view: &handle::RenderTargetView<R, T>, value: T::View) where T::View: Into<draw::ClearColor> { let target = self.handles.ref_rtv(view.raw()).clone(); self.command_buffer.clear_color(target, value.into()) } pub fn clear_depth<T: format::DepthFormat>(&m...
fer<R>> From<C> for Encoder<R, C> { fn from(combuf: C) -> Encoder<R, C> { Encoder { command_buffer: combuf, raw_pso_data: pso::RawDataSet::new(), handles: handle::Manager::new(), } } } impl<R: Resources, C: draw::CommandBuffer<R>> Encoder<R, C> { pub...
random
[ { "content": "/// Create the proxy target views (RTV and DSV) for the attachments of the\n\n/// main framebuffer. These have GL names equal to 0.\n\n/// Not supposed to be used by the users directly.\n\npub fn create_main_targets_raw(dim: d::tex::Dimensions, color_format: d::format::SurfaceType, depth_format: d...
Rust
website-api-tester/src/main.rs
sovrin-foundation/token-website
9e870c49a5e99b5a6d072cc585d229ce0257c0aa
#[macro_use] extern crate trace_macros; use isahc::prelude::*; use serde::{Serialize, Deserialize}; use sha2::Digest; use sodiumoxide::crypto::sign::{ sign_detached, gen_keypair, ed25519::SecretKey }; use structopt::StructOpt; use web_view::*; #[derive(Debug, StructOpt)] #[structopt( name = "basic", v...
#[macro_use] extern crate trace_macros; use isahc::prelude::*; use serde::{Serialize, Deserialize}; use sha2::Digest; use sodiumoxide::crypto::sign::{ sign_detached, gen_keypair, ed25519::SecretKey }; use structopt::StructOpt; use web_view::*; #[derive(Debug, StructOpt)] #[structopt( name = "basic", v...
let opt = Opt::from_args(); match opt.cmd { Command::Sign { key, token } => { let (pk, sk) = match key { Some(k) => { let k1 = bs58::decode(k).into_vec().unwrap(); let sk1 = SecretKey::from_slice(k1.as_slice()).unwrap(); ...
function_block-function_prefix_line
[ { "content": "fn prompt_for_value(value_name: &str) -> String {\n\n loop {\n\n match rpassword::read_password_from_tty(Some(format!(\"Enter {}: \", value_name).as_str())) {\n\n Ok(v) => {\n\n if v.len() > 0 {\n\n return v;\n\n } else {\n\n ...
Rust
src/licensee.rs
kain88-de/spdx
6df4065871137935c4c7698ee6cf2ecbedd48a4d
use crate::{ error::{ParseError, Reason}, ExceptionId, Lexer, LicenseItem, LicenseReq, Token, }; #[derive(PartialEq, Eq, PartialOrd, Ord, Debug)] pub struct Licensee { inner: LicenseReq, } impl Licensee { pub fn new(license: LicenseItem, exception: Option<ExceptionId>) -> Self { ...
use crate::{ error::{ParseError, Reason}, ExceptionId, Lexer, LicenseItem, LicenseReq, Token, }; #[derive(PartialEq, Eq, PartialOrd, Ord, Debug)] pub struct Licensee { inner: LicenseReq, } impl Licensee {
pub fn parse(original: &str) -> Result<Self, ParseError<'_>> { let mut lexer = Lexer::new(original); let license = { let lt = lexer.next().ok_or_else(|| ParseError { original, span: 0..original.len(), reason: Rea...
pub fn new(license: LicenseItem, exception: Option<ExceptionId>) -> Self { if let LicenseItem::SPDX { or_later, .. } = &license { debug_assert!(!or_later) } Self { inner: LicenseReq { license, exception }, } }
function_block-full_function
[ { "content": "#[inline]\n\npub fn license_id(name: &str) -> Option<LicenseId> {\n\n let name = &name.trim_end_matches('+');\n\n identifiers::LICENSES\n\n .binary_search_by(|lic| lic.0.cmp(name))\n\n .map(|index| {\n\n let (name, flags) = identifiers::LICENSES[index];\n\n ...
Rust
src/cmd/export/runit.rs
dan-da/ultraman
f6b491f6f39e693b404b1c35daf49317d476774a
use super::base::{Exportable, Template}; use crate::cmd::export::ExportOpts; use crate::env::read_env; use crate::process::port_for; use crate::procfile::{Procfile, ProcfileEntry}; use handlebars::to_json; use serde_derive::Serialize; use serde_json::value::{Map, Value as Json}; use std::collections::HashMap; use std::...
use super::base::{Exportable, Template}; use crate::cmd::export::ExportOpts; use crate::env::read_env; use crate::process::port_for; use crate::procfile::{Procfile, ProcfileEntry}; use handlebars::to_json; use serde_derive::Serialize; use serde_json::value::{Map, Value as Json}; use std::collections::HashMap; use std::...
; env.insert("PORT".to_string(), port); for (key, val) in env.iter() { let path = output_dir_path.join(&key); let display = path.clone().into_os_string().into_string().unwrap(); self.clean(&path); let mut file = File::create(path.clone())....
port_for( self.opts.env_path.clone(), self.opts.port.clone(), index, con_index + 1, )
call_expression
[ { "content": "fn base_port(env_path: PathBuf, port: Option<String>) -> String {\n\n let env = read_env(env_path).unwrap();\n\n let default_port = String::from(\"5000\");\n\n\n\n if let Some(p) = port {\n\n p\n\n } else if let Some(p) = env.get(\"PORT\") {\n\n p.clone()\n\n } else if...
Rust
src/config.rs
selvakn/wg-port-forward
1ecdcc8a1af1df3f4e906d991592a7ef693587ec
use std::fmt::{Display, Formatter}; use std::fs::read_to_string; use std::net::{IpAddr, SocketAddr, ToSocketAddrs}; use std::sync::Arc; use anyhow::Context; use boringtun::crypto::{X25519PublicKey, X25519SecretKey}; use clap::{App, Arg}; #[derive(Clone, Debug)] pub struct Config { pub private_key: Arc<X25519Secre...
use std::fmt::{Display, Formatter}; use std::fs::read_to_string; use std::net::{IpAddr, SocketAddr, ToSocketAddrs}; use std::sync::Arc; use anyhow::Context; use boringtun::crypto::{X25519PublicKey, X25519SecretKey}; use clap::{App, Arg}; #[derive(Clone, Debug)] pub struct Config { pub private_key: Arc<X25519Secre...
fn parse_keep_alive(s: Option<&str>) -> anyhow::Result<Option<u16>> { if let Some(s) = s { let parsed: u16 = s.parse().with_context(|| { format!( "Keep-alive must be a number between 0 and {} seconds", u16::MAX ) })?; Ok(Some(parsed))...
t<X25519PublicKey> { s.with_context(|| "Missing public key")? .parse::<X25519PublicKey>() .map_err(|e| anyhow::anyhow!("{}", e)) .with_context(|| "Invalid public key") }
function_block-function_prefixed
[ { "content": "pub fn new_listener_socket<'a>(port: u16) -> anyhow::Result<TcpSocket<'a>> {\n\n let rx_data = vec![0u8; MAX_PACKET];\n\n let tx_data = vec![0u8; MAX_PACKET];\n\n let tcp_rx_buffer = TcpSocketBuffer::new(rx_data);\n\n let tcp_tx_buffer = TcpSocketBuffer::new(tx_data);\n\n let mut so...
Rust
prelude/src/lib.rs
ferristseng/cryogen
b0bee906d2c2ea8f6f328edc71cf2f509b06dbf0
extern crate clap; extern crate serde; #[cfg(feature = "markdown")] extern crate serde_yaml; #[cfg(feature = "markdown")] #[macro_use] extern crate serde_derive; use clap::{Arg, ArgMatches}; use serde::Serialize; use std::{cmp, borrow::Cow, io::{self, Read}}; #[cfg(feature = "markdown")] pub mod markdown; #[macro_ex...
extern crate clap; extern crate serde; #[cfg(feature = "markdown")] extern crate serde_yaml; #[cfg(feature = "markdown")] #[macro_use] extern crate serde_derive; use clap::{Arg, ArgMatches}; use serde::Serialize; use std::{cmp, borrow::Cow, io::{self, Read}}; #[cfg(feature = "markdown")] pub mod markdown; #[macro_ex...
arg_value, }) } #[inline] pub fn arg_value(&self) -> &'a str { self.arg_value } #[inline] pub fn var_name(&self) -> &'a str { self.var_name } } pub enum Interpretation { Raw, Path, } pub enum Source<'a, R> where R: Read, { Raw(&'...
to in ({})", s)); }; let arg_value = if let Some(arg_value) = splits.next() { arg_value } else { return Err(format!( "Expected a value to bind to ({}) in ({})", var_name, s )); }; Ok(VarMapping { va...
function_block-random_span
[]
Rust
src/memory/mmu/mod.rs
FelixMcFelix/rs2
194a5b6c87d025cf7fa40700b7750d7fbbaf9e58
pub mod tlb; use crate::core::{cop0::*, exceptions::L1Exception}; use tlb::Tlb; pub struct Mmu { pub tlb: Tlb, pub page_mask: u32, pub wired: u8, pub index: u8, pub context: u32, pub asid: u8, } const VPN_ALWAYS_ACTIVE_BITS: u32 = 0b1111_1110_0000_0000_0000_0000_0000_0000; const OFFSET_ALWAYS_ACTIVE...
pub mod tlb; use crate::core::{cop0::*, exceptions::L1Exception}; use tlb::Tlb; pub struct Mmu { pub tlb: Tlb, pub page_mask: u32, pub wired: u8, pub index: u8, pub context: u32, pub asid: u8, } const VPN_ALWAYS_ACTIVE_BITS: u32 = 0b1111_1110_0000_0000_0000_0000_0000_0000; const OFFSET_ALWAYS_ACTIVE...
}
fn default() -> Self { Self { tlb: Default::default(), page_mask: 0, wired: WIRED_DEFAULT as u8, index: 0, context: 0, asid: 0, } }
function_block-function_prefixed
[]
Rust
ref-farming/tests/common/actions.rs
ParasHQ/paras-nft-farming-contract
1fd7065c05706fb47d0e5b1ead9e194c64ab78ca
use near_sdk::json_types::{U128}; use near_sdk::{Balance}; use near_sdk_sim::{call, to_yocto, ContractAccount, UserAccount, DEFAULT_GAS}; use test_token::ContractContract as TestToken; use ref_farming::{ContractContract as Farming}; use ref_farming::{HRSimpleFarmTerms}; use near_sdk::serde_json::Value; use near_sdk::...
use near_sdk::json_types::{U128}; use near_sdk::{Balance}; use near_sdk_sim::{call, to_yocto, ContractAccount, UserAccount, DEFAULT_GAS}; use test_token::ContractContract as TestToken; use ref_farming::{ContractContract as Farming}; use ref_farming::{HRSimpleFarmTerms}; use near_sdk::serde_json::Value; use near_sdk::...
#[allow(dead_code)] pub(crate) fn prepair_farm( root: &UserAccount, owner: &UserAccount, token: &ContractAccount<TestToken>, total_reward: Balance, ) -> (ContractAccount<Farming>, String) { let farming = deploy_farming(&root, farming_id(), owner.account_id()); let out_come = call!( ...
r: &UserAccount, ) -> (UserAccount, ContractAccount<TestToken>, ContractAccount<TestToken>) { let pool = deploy_pool(&root, swap(), owner.account_id()); let token1 = deploy_token(&root, dai(), vec![swap()]); let token2 = deploy_token(&root, eth(), vec![swap()]); owner.call( pool.account_id(), ...
function_block-function_prefixed
[ { "content": "fn parse_token_id(token_id: String) -> TokenOrPool {\n\n if let Ok(pool_id) = try_identify_sub_token_id(&token_id) {\n\n TokenOrPool::Pool(pool_id)\n\n } else {\n\n TokenOrPool::Token(token_id)\n\n }\n\n}\n\n\n\n/// seed token deposit\n\n#[near_bindgen]\n\nimpl MFTTokenRecei...
Rust
tests/hvac.rs
uber-foo/hvac
7d6680a3c0e1e09e2ba9bd4446bd3ed0d3ca67c0
use hvac::prelude::*; #[test] fn new_hvac_is_idle() { let mut hvac = Hvac::default(); let state = hvac.tick(0); assert_eq!(state.service, None); assert_eq!(state.fan, false); } #[test] fn new_hvac_enforces_min_heat_recover_constraints() { let mut hvac = Hvac::default().with_heat(None, Some(100)); ...
use hvac::prelude::*; #[test] fn new_hvac_is_idle() { let mut hvac = Hvac::default(); let state = hvac.tick(0); assert_eq!(state.service, None); assert_eq!(state.fan, false); } #[test] fn new_hvac_enforces_min_heat_recover_constraints() { let mut hvac = Hvac::default().with_heat(None, Some(100)); ...
t state = hvac.idle(); assert_eq!(state.service, None); assert_eq!(state.fan, false); } #[test] fn hvac_fan_auto_with_cool() { let mut hvac = Hvac::default().with_cool(None, None).with_fan(None, None); let state = hvac.cool(); assert_eq!(state.service, Some(HvacService::Cool)); assert_eq!(state...
None).with_fan(None, None); let state = hvac.heat(); assert_eq!(state.service, Some(HvacService::Heat)); assert_eq!(state.fan, true); le
function_block-random_span
[ { "content": "fn wait_seconds(\n\n last_update: Option<u32>,\n\n min_seconds: Option<u32>,\n\n last_change: Option<u32>,\n\n) -> Option<u32> {\n\n if let Some(last_update) = last_update {\n\n if let Some(min_seconds) = min_seconds {\n\n let delta = last_update - last_change.unwrap_...
Rust
crates/parser/src/lib.rs
fangerm/gelixrs
de7b7b0b53ed8a4bcbe6b6484103b07e16f420e1
mod declaration; mod expression; mod nodes; mod util; use crate::util::{ builder::{Checkpoint, NodeBuilder}, source::Source, }; use common::bench; use error::{Error, ErrorSpan, GErr}; use lexer::Lexer; pub use nodes::*; use syntax::kind::SyntaxKind; pub fn parse(input: &str) -> Result<ParseResult, Vec<Error>>...
mod declaration; mod expression; mod nodes; mod util; use crate::util::{ builder::{Checkpoint, NodeBuilder}, source::Source, }; use common::bench; use error::{Error, ErrorSpan, GErr}; use lexer::Lexer; pub use nodes::*; use syntax::kind::SyntaxKind; pub fn parse(input: &str) -> Result<ParseResult, Vec<Error>>...
errors: vec![], poisoned: false, modifiers: Vec::with_capacity(4), } } } #[derive(Debug)] pub struct ParseResult { green_node: Node, } impl ParseResult { pub fn root(self) -> Node { self.green_node } }
ind); content(self); self.end_node() } fn start_node(&mut self, kind: SyntaxKind) { self.skip_whitespace(); self.builder.start_node(kind); } fn start_node_at(&mut self, checkpoint: Checkpoint, kind: SyntaxKind) { self.builder.start_node_at(kind, checkpoint); ...
random
[ { "content": "/// Produces a new error for the GIR.\n\npub fn gir_err(cst: CSTNode, err: GErr) -> Error {\n\n Error {\n\n index: ErrorSpan::Span(cst.text_range()),\n\n kind: err,\n\n }\n\n}\n", "file_path": "crates/gir-nodes/src/lib.rs", "rank": 0, "score": 299536.0737118246 },...
Rust
src/api.rs
sinsoku/miteras-cli
2dfca1619353bfb35992de7e9ae8e9878a89062c
use crate::config::Config; use chrono::prelude::*; #[cfg(test)] use mockito; use reqwest::blocking::{Client, Response}; use reqwest::header; use scraper::{Html, Selector}; use serde::{Deserialize, Serialize}; use std::collections::HashMap; static APP_USER_AGENT: &str = "miteras-cli"; pub struct Api { config: Conf...
use crate::config::Config; use chrono::prelude::*; #[cfg(test)] use mockito; use reqwest::blocking::{Client, Response}; use reqwest::header; use scraper::{Html, Selector}; use serde::{Deserialize, Serialize}; use std::collections::HashMap; static APP_USER_AGENT: &str = "miteras-cli"; pub struct Api { config: Conf...
pub fn clock_in(&self, condition: &str) -> Result<Response, reqwest::Error> { let auth_res = self.login().unwrap(); let csrf = parse_csrf(auth_res.text().unwrap()); let cico_url = self.build_url("cico"); let url = self.build_url("submitClockIn"); let mut clock_in_condition...
pub fn login(&self) -> Result<Response, reqwest::Error> { let login_url = self.build_url("login"); let login_res = self.client.get(&login_url).send().unwrap(); let csrf = parse_csrf(login_res.text().unwrap()); let auth_url = self.build_url("auth"); let mut params: HashMap<&str, ...
function_block-full_function
[ { "content": "pub fn build_cli() -> App<'static, 'static> {\n\n app_from_crate!()\n\n .setting(AppSettings::SubcommandRequiredElseHelp)\n\n .subcommand(\n\n SubCommand::with_name(\"login\").about(\"Authenticate to MITERAS and save credentials\"),\n\n )\n\n .subcommand(\...
Rust
01-running/src/main.rs
davidhollis/rust-gba-scratchpad
2d02fd4839bca33f6ef4167e5f83af3db7c517ff
#![no_std] #![no_main] #![feature(asm)] use core::cmp::{ max, min }; use gba::prelude::*; use gbainputs::{ Key, KeyMonitor }; use gbamath::fixed::{ UFixed8, SFixed8 }; use gbamath::geometry::BoundingBox; use gbamath::Vec2D; #[panic_handler] fn panic(_info: &core::panic::PanicInfo) -> ! { mode3::dma3_clear_to(Col...
#![no_std] #![no_main] #![feature(asm)] use core::cmp::{ max, min }; use gba::prelude::*; use gbainputs::{ Key, KeyMonitor }; use gbamath::fixed::{ UFixed8, SFixed8 }; use gbamath::geometry::BoundingBox; use gbamath::Vec2D; #[panic_handler] fn panic(_info: &core::panic::PanicInfo) -> ! { mode3::dma3_clear_to(Col...
ode3::WIDTH * (y as usize)) + (left as usize)) * 2usize); DMA3CNT_L.write(word_count); const CTRL: DmaControl = DmaControl::new() .with_dest_addr(DestAddrControl::Increment) .with_src_addr(SrcAddrControl::Fixed) .with_transfer_u32(false) ...
self.current_velocity = VEC2D_ZERO; } else if self.inputs.is_pressed(Key::RIGHT) { if self.collision_state & Player::RIGHT_COLLISION_THIS_FRAME > 0 { self.current_velocity.x = SFixed8::ZERO; } else { ...
random
[ { "content": "#[inline]\n\nfn draw_icon(x: usize, y: usize, width: usize, icon: &[Color], enabled: bool) {\n\n for (idx, color) in icon.iter().enumerate() {\n\n let dx = idx % width;\n\n let dy = idx / width;\n\n let modified_color =\n\n if *color == U && !enabled {\n\n W\n\n } else {...
Rust
src/day21/mod.rs
maxdavidson/advent-of-code-2020
25838e6c15317d1cf909350b15d4244d51f7c99e
use std::collections::{hash_map::Entry, HashMap, HashSet}; use lazy_static::lazy_static; use regex::Regex; #[derive(Debug)] struct Food<'a> { ingredients: HashSet<&'a str>, allergens: HashSet<&'a str>, } impl<'a> Food<'a> { fn parse(value: &'a str) -> Option<Self> { lazy_static! { sta...
use std::collections::{hash_map::Entry, HashMap, HashSet}; use lazy_static::lazy_static; use regex::Regex; #[derive(Debug)] struct Food<'a> { ingredients: HashSet<&'a str>, allergens: HashSet<&'a str>, } impl<'a> Food<'a> {
} fn find_dangerous_ingredients_helper<'a>( mut allergen_ingredients: Vec<(&'a str, HashSet<&'a str>)>, ) -> Option<impl Iterator<Item = &'a str>> { if allergen_ingredients .iter() .any(|(_, ingredients)| ingredients.is_empty()) { None } else if allergen_ingredients .it...
fn parse(value: &'a str) -> Option<Self> { lazy_static! { static ref RECIPE_RE: Regex = Regex::new(r"^(?P<ingredients>.+) \(contains (?P<allergens>.+)\)$").unwrap(); } let caps = RECIPE_RE.captures(value)?; let ingredients = caps .name("ingredien...
function_block-full_function
[ { "content": "struct Data<'a>(pub HashMap<&'a str, HashMap<&'a str, usize>>);\n\n\n\nimpl<'a> Data<'a> {\n\n fn parse(input: &'a str) -> Self {\n\n lazy_static! {\n\n static ref RE_1: Regex = Regex::new(r\"^(?P<color>[a-z ]+) bags? contain\").unwrap();\n\n static ref RE_2: Regex ...
Rust
async-coap/src/option/iter.rs
Luro02/rust-async-coap
6a7b592a23de0c9d86ca399bf40ecfbf0bff6e62
use super::*; use std::convert::Into; #[derive(Debug, Clone)] pub struct OptionIterator<'a> { iter: core::slice::Iter<'a, u8>, last_option: OptionNumber, } impl<'a> Default for OptionIterator<'a> { fn default() -> Self { OptionIterator::new(&[]) } } impl<'a> OptionIterator<'a> { pu...
use super::*; use std::convert::Into; #[derive(Debug, Clone)] pub struct OptionIterator<'a> { iter: core::slice::Iter<'a, u8>, last_option: OptionNumber, } impl<'a> Default for OptionIterator<'a> { fn default() -> Self { OptionIterator::new(&[]) } } impl<'a> OptionIterator<'a> { pu...
et { self.last_option = key; } ret } } impl AsRef<[u8]> for OptionIterator<'_> { fn as_ref(&self) -> &[u8] { self.as_slice() } } pub trait OptionIteratorExt<'a>: Iterator<Item = Result<(OptionNumber, &'a [u8]), Error>> { fn find_ne...
-> Option<Self::Item> { let ret = decode_option(&mut self.iter, self.last_option).transpose(); if let Some(Ok((key, _))) = r
function_block-random_span
[ { "content": "/// Encodes an unsigned 32-bit number into the given buffer, returning\n\n/// the resized buffer. The returned buffer may be smaller than the\n\n/// `dst`, and may even be empty. The returned buffer is only as large\n\n/// as it needs to be to represent the given value.\n\npub fn encode_u32(value:...
Rust
examples/router_benchmark.rs
sers-dev/tyractorsaur
23679ee63296eaac1bc7cfaacdcd81f137950799
use std::process::exit; use std::thread::sleep; use std::time::{Duration, Instant}; use tyra::prelude::{Actor, ActorFactory, ActorMessage, ActorSystem, ActorContext, Handler, TyraConfig, ActorWrapper}; use tyra::router::{AddActorMessage, RoundRobinRouterFactory, RouterMessage}; struct MessageA {} impl ActorMessage fo...
use std::process::exit; use std::thread::sleep; use std::time::{Duration, Instant}; use tyra::prelude::{Actor, ActorFactory, ActorMessage, ActorSystem, ActorContext, Handler, TyraConfig, ActorWrapper}; use tyra::router::{AddActorMessage, RoundRobinRouterFactory, RouterMessage}; struct MessageA {} impl ActorMessage fo...
} impl Actor for Aggregator { fn on_system_stop(&mut self) { self.ctx.actor_ref.stop(); } } impl ActorFactory<Aggregator> for AggregatorFactory { fn new_actor(&self, context: ActorContext<Aggregator>) -> Aggregator { Aggregator::new(self.total_actors, self.name.clone(), context) } } ...
pub fn new(total_actors: usize, name: String, context: ActorContext<Self>) -> Self { Self { ctx: context, total_actors, name, actors_finished: 0, start: Instant::now(), } }
function_block-full_function
[ { "content": "struct MessageA {}\n\n\n\nimpl ActorMessage for MessageA {}\n\n\n", "file_path": "examples/benchmark.rs", "rank": 0, "score": 118826.0143007199 }, { "content": "struct MessageA {\n\n text: String,\n\n}\n\n\n", "file_path": "examples/actor.rs", "rank": 1, "score":...
Rust
solver/src/lib.rs
MattWhelan/words
ca0788715a3af47e4b09157b0f60aa36af513f6a
use std::collections::{HashMap, HashSet}; use strsim::hamming; use wordlib::{char_freq, freq_scored_guesses, Knowledge}; use crate::LetterOutcome::{ABSENT, HIT, MISS}; pub trait GuessStrategy { fn next_guess(&self, knowledge: &Knowledge) -> &str; } pub struct FreqStrategy<'a> { words: &'a [&'a str], } impl...
use std::collections::{HashMap, HashSet}; use strsim::hamming; use wordlib::{char_freq, freq_scored_guesses, Knowledge}; use crate::LetterOutcome::{ABSENT, HIT, MISS}; pub trait GuessStrategy { fn next_guess(&self, knowledge: &Knowledge) -> &str; } pub struct FreqStrategy<'a> { words: &'a [&'a str], } impl...
return &candidates[0]; } if candidates.len() == self.words.len() { let ret = "raise"; let word_entropy = Self::entropy_of_guess(&candidates, ret); println!("{}: โˆ†H = {}", ret, word_entropy); return "raise" } le...
in() .unwrap() }); println!("Guesses:"); for guess in guesses.iter().take(5) { println!(" {}", guess); } guesses[0] } } pub fn valid_words(target_word_len: usize, all_words: &[String], disallowed: HashSet<String>) -> Vec<&str> { all_words ...
random
[ { "content": "pub fn char_freq(words: &[&str]) -> HashMap<char, usize> {\n\n words\n\n .iter()\n\n .flat_map(|w| w.chars())\n\n .fold(HashMap::new(), |mut acc, ch| {\n\n *acc.entry(ch).or_default() += 1;\n\n acc\n\n })\n\n}\n\n\n", "file_path": "wordlib/s...
Rust
bfffs/src/bin/bfffs.rs
fkorotkov/bfffs
e0f3fddae49a19bcbe5593058cd2ef54b2496572
use bfffs::common::{ database::TreeID, device_manager::DevManager, property::Property }; use clap::crate_version; use futures::future; use std::{ path::Path, process::exit, sync::Arc }; use tokio::{ executor::current_thread::TaskExecutor, runtime::current_thread::Runtime }; mod check { ...
use bfffs::common::{ database::TreeID, device_manager::DevManager, property::Property }; use clap::crate_version; use futures::future; use std::{ path::Path, process::exit, sync::Arc }; use tokio::{ executor::current_thread::TaskExecutor, runtime::current_thread::Runtime }; mod check { ...
}
match matches.subcommand() { ("check", Some(args)) => check::main(args), ("debug", Some(args)) => debug::main(args), ("pool", Some(args)) => pool::main(args), _ => { println!("Error: subcommand required\n{}", matches.usage()); std::process::exit(2); }, ...
if_condition
[ { "content": "/// Create a raid-like `Vdev` from its components.\n\n///\n\n///\n\n/// * `chunksize`: RAID chunksize in LBAs, if specified. This is the\n\n/// largest amount of data that will be read/written to\n\n/// a single device before the `Locator` ...
Rust
src/lib.rs
aki-akaguma/cmp_polymorphism
67da07762a02dee2aac7d3033d2b312fb2a1fedc
pub mod enum_obj; pub mod trait_obj; pub fn do_trait_obj( count: i32, ) -> anyhow::Result<( (&'static str, i32), (&'static str, i32), (&'static str, i32), (&'static str, i32), (&'static str, i32), )> { let a: Box<dyn trait_obj::Animal> = Box::new(trait_obj::Cat::new(count)); let b: Box<...
pub mod enum_obj; pub mod trait_obj; pub fn do_trait_obj( count: i32, ) -> anyhow::Result<( (&'static str, i32), (&'static str, i32), (&'static str, i32), (&'static str, i32), (&'static str, i32), )> { let a: Box<dyn trait_obj::Animal> = Box::new(trait_obj::Cat::new(count)); let b: Box<...
pub fn sum_rem_trait_objs(vec: &Vec<Box<dyn trait_obj::Animal>>) -> i32 { let mut acc = 0; for a in vec { acc += a.rem(); } acc } pub fn create_enum_objs(count: usize) -> Vec<Box<enum_obj::Animal>> { let v: Vec<Box<enum_obj::Animal>> = vec![ Box::new(enum_obj::Animal::Cat(1)) as Bo...
rait_objs(vec: &Vec<Box<dyn trait_obj::Animal>>) -> i32 { let mut acc = 0; for a in vec { acc += a.sum(); } acc }
function_block-function_prefixed
[ { "content": "fn set_size(bench_vec: &mut Vec<BenchStr>, in_file: &str) -> anyhow::Result<()> {\n\n let mut base_time = 0f64;\n\n let mut base_size = 0u64;\n\n let re_1 = regex::Regex::new(r\"^ *(\\d+)\\t.*\\t([^ ]+)$\").unwrap();\n\n let reader = std::io::BufReader::new(\n\n std::fs::File::o...
Rust
src/prefab.rs
FrancisMurillo/amethyst-tiled
fc5713a8a41a9c829fb624c8f782393fde07971c
use amethyst::assets::{Asset, AssetStorage, Handle, Loader, PrefabData, ProgressCounter, Source}; use amethyst::ecs::{Component, Entity, Read, ReadExpect, Write, WriteStorage}; use amethyst::renderer::{SpriteSheet, Texture}; use amethyst::Error; use tiled::{Map, Tileset}; use crate::strategy::{CompressedLoad, LoadStra...
use amethyst::assets::{Asset, AssetStorage, Handle, Loader, PrefabData, ProgressCounter, Source}; use amethyst::ecs::{Component, Entity, Read, ReadExpect, Write, WriteStorage}; use amethyst::renderer::{SpriteSheet, Texture}; use amethyst::Error; use tiled::{Map, Tileset}; use crate::strategy::{CompressedLoad, LoadStra...
fn load_sub_assets( &mut self, progress: &mut ProgressCounter, system_data: &mut Self::SystemData, ) -> Result<bool, Error> { #[cfg(feature = "profiler")] profile_scope!("load_tilemap_assets"); match self { TileMapPrefab::Map(map, source) => { ...
fn add_to_entity( &self, entity: Entity, system_data: &mut Self::SystemData, _entities: &[Entity], _children: &[Entity], ) -> Result<(), Error> { #[cfg(feature = "profiler")] profile_scope!("add_tilemap_to_entity"); let (_, storage) = system_data; ...
function_block-full_function
[ { "content": "pub fn pack_tileset(set: &Tileset, source: Arc<dyn Source>) -> Result<SpriteSheet, Error> {\n\n let mut sprites = Vec::new();\n\n\n\n for image in &set.images {\n\n sprites.extend(pack_image(\n\n image,\n\n source.clone(),\n\n TileSpec {\n\n ...
Rust
crates/github_scbot_database/src/models/auth/external_account/mod.rs
sharingcloud/github-scbot
953ba1ae7f3bb06c37084756458a1ddb53c8fa65
use github_scbot_crypto::JwtUtils; use github_scbot_utils::TimeUtils; use serde::{Deserialize, Serialize}; use crate::{schema::external_account, Result}; mod adapter; mod builder; pub use adapter::{ DummyExternalAccountDbAdapter, ExternalAccountDbAdapter, IExternalAccountDbAdapter, }; use builder::ExternalAccount...
use github_scbot_crypto::JwtUtils; use github_scbot_utils::TimeUtils; use serde::{Deserialize, Serialize}; use crate::{schema::external_account, Result}; mod adapter; mod builder; pub use adapter::{ DummyExternalAccountDbAdapter, ExternalAccountDbAdapter, IExternalAccountDbAdapter, }; use builder::ExternalAccount...
assert_eq!( acc, ExternalAccountModel { username: "ext1".into(), private_key: "pri".into(), public_key: "pub".into() } ); let acc = ExternalAccountModel::builder("ext1") ...
let acc = ExternalAccountModel::builder("ext1") .private_key("pri") .public_key("pub") .create_or_update(&db_adapter) .await .unwrap();
assignment_statement
[ { "content": "fn env_to_u64(name: &str, default: u64) -> u64 {\n\n env::var(name)\n\n .map(|e| e.parse().unwrap_or(default))\n\n .unwrap_or(default)\n\n}\n\n\n", "file_path": "crates/github_scbot_conf/src/config.rs", "rank": 0, "score": 232379.7236178441 }, { "content": "fn ...
Rust
src/git_config/git_config_entry.rs
rashil2000/delta
55287a827e8f2527df938a1b85e23290f8692607
use std::result::Result; use std::str::FromStr; use lazy_static::lazy_static; use regex::Regex; use crate::errors::*; #[derive(Clone, Debug)] pub enum GitConfigEntry { Style(String), GitRemote(GitRemoteRepo), } #[derive(Clone, Debug, PartialEq)] pub enum GitRemoteRepo { GitHubRepo { repo_slug: String },...
use std::result::Result; use std::str::FromStr; use lazy_static::lazy_static; use regex::Regex; use crate::errors::*; #[derive(Clone, Debug)] pub enum GitConfigEntry { Style(String), GitRemote(GitRemoteRepo), } #[derive(Clone, Debug, PartialEq)] pub enum GitRemoteRepo { GitHubRepo { repo_slug: String },...
#[test] fn test_parse_gitlab_urls() { let urls = &[ ( "https://gitlab.com/proj/grp/subgrp/repo.git", "proj/grp/subgrp/repo", ), ("https://gitlab.com/proj/grp/repo.git", "proj/grp/repo"), ("https://gitlab.com/proj/repo.git"...
k() { let repo = GitRemoteRepo::GitHubRepo { repo_slug: "dandavison/delta".to_string(), }; let commit_hash = "d3b07384d113edec49eaa6238ad5ff00"; assert_eq!( repo.format_commit_url(commit_hash), format!("https://github.com/dandavison/delta/commit/{}", c...
function_block-function_prefixed
[ { "content": "/// If `name` is set and, after trimming whitespace, is not empty string, then return that trimmed\n\n/// string. Else None.\n\npub fn get_env_var(_name: &str) -> Option<String> {\n\n #[cfg(not(test))]\n\n match env::var(_name).unwrap_or_else(|_| \"\".to_string()).trim() {\n\n \"\" =>...
Rust
src/frame.rs
Inner-Heaven/libwhisper-rs
26e7331fd5b4ab2c1410ab46f738208b48a6aa7b
use bytes::{BufMut, Bytes, BytesMut}; use errors::{WhisperError, WhisperResult}; use nom::{IResult, rest}; use sodiumoxide::crypto::box_::{Nonce, PublicKey}; pub static HEADER_SIZE: usize = 57; #[derive(Debug, Clone, PartialEq, Copy, Eq, Hash)] pub enum FrameKind { Hello = 1, Welcome, In...
use bytes::{BufMut, Bytes, BytesMut}; use errors::{WhisperError, WhisperResult}; use nom::{IResult, rest}; use sodiumoxide::crypto::box_::{Nonce, PublicKey}; pub static HEADER_SIZE: usize = 57; #[derive(Debug, Clone, PartialEq, Copy, Eq, Hash)] pub enum FrameKind { Hello = 1, Welcome, In...
nonce: nonce, kind: FrameKind::Hello, payload: payload.into(), } } }
is_incomplete = true; } assert!(is_incomplete); } #[test] fn bad_frame() { let bad_frame = b"\x85\x0f\xc2?\xce\x80f\x16\xec8\x04\xc7{5\x98\xa7u<\xa5y\xda\x12\xfe\xad\xdc^%[\x8ap\xfa7q.-)\xe4V\xec\x94\xb2\x7f\r\x9a\x91\xc7\xcd\x08\xa4\xee\xbfbpH\x07%\r\0\0\0"...
random
[ { "content": "/// In order to make libsodium threadsafe you must call this function before using any of it's andom number generation functions.\n\n/// It's safe to call this method more than once and from more than one thread.\n\npub fn init() -> WhisperResult<()> {\n\n if sodiumoxide::init() {\n\n Ok(())\n...
Rust
src/crypto/mac.rs
chmoder/iso8583_rs
d7e8e4256e4e6923bb1c451db38449645355e772
use crate::crypto::{tdes_encrypt_cbc, des_encrypt_cbc}; pub enum MacAlgo { CbcMac, RetailMac, } pub enum PaddingType { Type1, Type2, } pub struct MacError { pub msg: String } pub fn verify_mac(algo: &MacAlgo, padding_type: &PaddingType, data: &[u8], key: &Vec<u8>, expected_...
use crate::crypto::{tdes_encrypt_cbc, des_encrypt_cbc}; pub enum MacAlgo { CbcMac, RetailMac, } pub enum PaddingType { Type1, Type2, } pub struct MacError { pub msg: String } pub fn verify_mac(algo: &MacAlgo, padding_type: &PaddingType, data: &[u8], key: &Vec<u8>, expected_...
} #[test] fn test_gen_mac_cbc_2_paddingtype2() { let res = generate_mac(&MacAlgo::CbcMac, &PaddingType::Type2, &Vec::from(hex!("01020304050607080102030405")), &Vec::from(hex!("e0f4543f3e2a2c5ffc7e5e5a222e3e4d"))); match res { Ok(m) => { ...
match res { Ok(m) => { println!("mac = {}", hex::encode(m.as_slice())); assert_eq!("8fb12963d5661a22", hex::encode(m)); } Err(e) => { assert!(false, e.msg) } }
if_condition
[ { "content": "/// Pad a random hex string to'data' to make it 8 bytes\n\nfn pad_8(data: &mut String) {\n\n let padding: [u8; 8] = rand::thread_rng().gen();\n\n data.push_str(hex::encode(padding).as_str());\n\n data.truncate(16);\n\n}\n\n\n", "file_path": "src/crypto/pin.rs", "rank": 2, "sco...
Rust
src/client.rs
line/centraldogma-rs
9c223222f430a985bd32332fba5de79994bc652e
use std::time::Duration; use reqwest::{header::HeaderValue, Body, Method, Request}; use thiserror::Error; use url::Url; use crate::model::Revision; const WATCH_BUFFER_TIMEOUT: Duration = Duration::from_secs(5); #[derive(Error, Debug)] pub enum Error { #[error("HTTP Client error")] HttpClient(#[from] re...
use std::time::Duration; use reqwest::{header::HeaderValue, Body, Method, Request}; use thiserror::Error; use url::Url; use crate::model::Revision; const WATCH_BUFFER_TIMEOUT: Duration = Duration::from_secs(5); #[derive(Error, Debug)] pub enum Error { #[error("HTTP Client error")] HttpClient(#[from] re...
pub(crate) fn new_watch_request<S: AsRef<str>>( &self, method: reqwest::Method, path: S, body: Option<Body>, last_known_revision: Option<Revision>, timeout: Duration, ) -> Result<reqwest::Request, Error> { let mut req = self.new_request(method, path, bod...
fn new_request_inner( &self, method: reqwest::Method, path: &str, body: Option<Body>, ) -> Result<reqwest::Request, Error> { let mut req = Request::new(method, self.base_url.join(path)?); req.headers_mut() .insert("Authorization", self.token.clon...
function_block-full_function
[ { "content": "fn watch_stream<D: Watchable>(client: Client, path: String) -> impl Stream<Item = D> + Send {\n\n let init_state = WatchState {\n\n client,\n\n path,\n\n last_known_revision: None,\n\n failed_count: 0,\n\n success_delay: None,\n\n };\n\n futures::stream:...
Rust
src/combinators.rs
hashedone/toy-interpreter
7e04e06bd0fe9349d7515fe0731591eabc6b428b
use crate::{Operator, Result, Token}; #[derive(Debug, PartialEq)] pub struct ParseProgress<'a, T> { pub tail: &'a str, pub token: Option<T>, } pub type ParseResult<'a, T> = Result<ParseProgress<'a, T>>; impl<'a, T> ParseProgress<'a, T> { fn none(tail: &'a str) -> ParseResult<'a, T> { Ok(ParseProg...
use crate::{Operator, Result, Token}; #[derive(Debug, PartialEq)] pub struct ParseProgress<'a, T> { pub tail: &'a str, pub token: Option<T>, } pub type ParseResult<'a, T> = Result<ParseProgress<'a, T>>; impl<'a, T> ParseProgress<'a, T> { fn none(tail: &'a str) -> ParseResult<'a, T> { Ok(ParseProg...
fn assignment(src: &str) -> ParseResult<&str> { let (tail, ident) = assume!(identifier(src), src); let tail = tail.trim_start(); if tail.starts_with('=') && !tail.starts_with("=>") { ParseProgress::some(&tail[1..], ident) } else { ParseProgress::none(src) } } pub fn next_token(src...
fn identifier(src: &str) -> ParseResult<&str> { if src.is_empty() { ParseProgress::none(src) } else if src.chars().next().unwrap().is_ascii_alphabetic() || src.starts_with('_') { let first_not = src .find(|c: char| -> bool { !(c == '_' || c.is_ascii_alphanumeric()) }) .un...
function_block-full_function
[ { "content": "pub fn tokenize<'a>(mut src: &'a str) -> impl Iterator<Item = Result<Token>> + 'a {\n\n iter::from_fn(move || match next_token(src) {\n\n Ok(progress) => {\n\n src = progress.tail.trim_start();\n\n progress.token.map(Ok)\n\n }\n\n Err(err) => {\n\n ...
Rust
kq/tests/accessor_multiple/mod.rs
jihchi/kq
58bb05a44e0ceca6b8237bda63c5403a74a80a0c
use assert_cmd::Command; use indoc::indoc; const INPUT: &str = include_str!("./website.kdl"); #[test] fn top_descendant_any_element() { Command::cargo_bin("kq") .unwrap() .arg("top() []") .write_stdin(indoc! {r#" name "CI" jobs { fmt_and_docs "Check ...
use assert_cmd::Command; use indoc::indoc; const INPUT: &str = include_str!("./website.kdl"); #[test] fn top_descendant_any_element() { Command::cargo_bin("kq") .unwrap() .arg("top() []") .write_stdin(indoc! {r#" name "CI" jobs { fmt_and_docs "Check ...
#[test] fn complex_single_level() { Command::cargo_bin("kq") .unwrap() .arg(r#"li[val() = "Flexibility"] + [val() = "Cognitive simplicity and Learnability"] ~ [val() = "Ease of implementation"]"#) .write_stdin(INPUT) .assert() .success() .stdout(indoc! {r#" ...
fn adjacent_general_siblings() { Command::cargo_bin("kq") .unwrap() .arg("html > head meta + meta ~ link") .write_stdin(INPUT) .assert() .success() .stdout(predicates::str::starts_with("link")) .stdout(predicates::str::contains(r#"href="\/styles\/global.css""#...
function_block-full_function
[ { "content": "pub fn query_document(input: &str, document: Vec<KdlNode>) -> Result<Vec<KdlNode>, String> {\n\n let input = input.trim();\n\n if input.is_empty() {\n\n Ok(document)\n\n } else {\n\n all_consuming(parser::selector)(input)\n\n .finish()\n\n .map(|(_input...
Rust
src/texture/pixel_format.rs
jsmith628/gl-struct
57b29458d477194bb87f170b1cfe01fb3a0f725f
use super::*; glenum! { pub enum InternalFormatFloat { RED, RG, RGB, RGBA, COMPRESSED_RED, COMPRESSED_RG, COMPRESSED_RGB, COMPRESSED_RGBA, COMPRESSED_SRGB, COMPRESSED_SRGB_ALPHA, R8,R8_SNORM, R16,R16_SNORM, RG8,RG8_SNORM, RG16,RG16_SNORM, R3_...
use super::*; glenum! { pub enum InternalFormatFloat { RED, RG, RGB, RGBA, COMPRESSED_RED, COMPRESSED_RG, COMPRESSED_RGB, COMPRESSED_RGBA, COMPRESSED_SRGB, COMPRESSED_SRGB_ALPHA, R8,R8_SNORM, R16,R16_SNORM, RG8,RG8_SNORM, RG16,RG16_SNORM, R3_...
} #[inline] unsafe fn format_type(self) -> (Self::Format, PixelType) { match self { Self::Integer(format, ty) => (format, ty.into()), _ => ( FormatInt::RGBA_INTEGER, match self { Self::UShort4_4_4_4 => PixelType::UNSIGNED_...
match self { Self::Integer(format, ty) => format.components() * ty.size(), Self::UShort4_4_4_4 | Self::UShort4_4_4_4Rev | Self::UShort5_5_5_1 | Self::UShort1_5_5_5Rev => 2, Self::UInt8_8_8_8 | Self::UInt8_8_8_8Rev | Self::UInt10_10_10_2 | Self::UInt10_10_10_2Rev => 4 }
if_condition
[ { "content": "pub trait AttributeValue<T:GLSLType>: GPUCopy { fn format(&self) -> T::AttributeFormat; }\n\nimpl<A:AttributeData<T>, T:GLSLType> AttributeValue<T> for A {\n\n #[inline] fn format(&self) -> T::AttributeFormat {A::format()}\n\n}\n\n\n", "file_path": "src/glsl/mod.rs", "rank": 0, "sco...
Rust
src/lexer.rs
kimhyunkang/r5.rs
cac10a2d3c65e72bcbeac11169fb0eba94baa53e
use std::io::{IoError, IoErrorKind}; use std::string::CowString; use std::borrow::Cow; use std::fmt; use error::{ParserError, ParserErrorKind}; #[derive(PartialEq)] pub enum Token { OpenParen, CloseParen, Dot, Identifier(CowString<'static>), True, False, Chara...
use std::io::{IoError, IoErrorKind}; use std::string::CowString; use std::borrow::Cow; use std::fmt; use error::{ParserError, ParserErrorKind}; #[derive(PartialEq)] pub enum Token { OpenParen, CloseParen, Dot, Identifier(CowString<'static>), True, False, Chara...
} } fn consume(&mut self) -> Result<char, IoError> { let c = match self.lookahead_buf { Some(c) => { self.lookahead_buf = None; c }, None => try!(self.stream.read_char()) }; self.advance(c); Ok(c) ...
match self.stream.read_char() { Ok(c) => if f(c) { self.advance(c); s.push(c); } else { self.lookahead_buf = Some(c); return Ok(s); }, Err(e) => match e.kind { ...
if_condition
[ { "content": "fn format_char(c: char, f: &mut fmt::Formatter) -> fmt::Result {\n\n try!(write!(f, \"#\\\\\"));\n\n match c {\n\n '\\0' => write!(f, \"nul\"),\n\n '\\x08' => write!(f, \"backspace\"),\n\n '\\t' => write!(f, \"tab\"),\n\n '\\x0c' => write!(f, \"page\"),\n\n ...