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
boa/src/builtins/math/mod.rs
coolreader18/boa
7dd32a68594585950be3eaa62e480b8fec5ba45a
use crate::{ builtins::{ function::NativeFunctionData, value::{from_value, to_value, ResultValue, Value, ValueData}, }, exec::Interpreter, }; use rand::random; use std::f64; #[cfg(test)] mod tests; pub fn abs(_: &Value, args: &[Value], _: &mut Interpreter) -> ResultValue { Ok(to_value(...
use crate::{ builtins::{ function::NativeFunctionData, value::{from_value, to_value, ResultValue, Value, ValueData}, }, exec::Interpreter, }; use rand::random; use std::f64; #[cfg(test)] mod tests; pub fn abs(_: &Value, args: &[Value], _: &mut Interpreter) -> ResultValue { Ok(to_value(...
} pub fn tan(_: &Value, args: &[Value], _: &mut Interpreter) -> ResultValue { Ok(to_value(if args.is_empty() { f64::NAN } else { from_value::<f64>(args.get(0).expect("Could not get argument").clone()) .expect("Could not convert argument to f64") .tan() })) } pub fn...
Ok(to_value(if args.is_empty() { f64::NAN } else { from_value::<f64>(args.get(0).expect("Could not get argument").clone()) .expect("Could not convert argument to f64") .sqrt() }))
call_expression
[ { "content": "/// Search for a match between this regex and a specified string\n\npub fn test(this: &Value, args: &[Value], _: &mut Interpreter) -> ResultValue {\n\n let arg_str = get_argument::<String>(args, 0)?;\n\n let mut last_index =\n\n from_value::<usize>(this.get_field_slice(\"lastIndex\"))...
Rust
src/game.rs
ttempleton/rust-battleship
48d45f8c5d8c73ec399e1b6781418cdb5774fdc0
use crate::direction::Direction; use crate::player::Player; use crate::settings::GameSettings; use rand::{seq::SliceRandom, thread_rng, Rng}; pub struct Game { settings: GameSettings, players: [Player; 2], state: GameState, turn: u8, } impl Game { pub fn new(settings: GameSettings) -> Result<Game,...
use crate::direction::Direction; use crate::player::Player; use crate::settings::GameSettings; use rand::{seq::SliceRandom, thread_rng, Rng}; pub struct Game { settings: GameSettings, players: [Player; 2], state: GameState, turn: u8, } impl Game { pub fn new(settings: GameSettings) -> Result<Game,...
pub fn settings(&self) -> &GameSettings { &self.settings } pub fn active_player(&self) -> &Player { &self.players[self.turn as usize] } pub fn inactive_player(&self) -> &Player { &self.players[self.not_turn()] } pub fn is_state_placement(&self) -> ...
settings: settings, players: players, state: GameState::Placement, turn: 0, }) }
function_block-function_prefix_line
[ { "content": "fn main() {\n\n let settings = settings::AppSettings { space_size: 20 };\n\n let mut app = app::App::new(&settings);\n\n\n\n app.init();\n\n}\n", "file_path": "src/main.rs", "rank": 0, "score": 28101.960460366587 }, { "content": "pub struct AppSettings {\n\n pub spa...
Rust
src/kmain.rs
hobo0xcc/citron
46fb564f0f7e360fa4e210f5963b121eb8f98594
use crate::arch::riscv64::virtio::gpu_device; use crate::arch::riscv64::virtio::keyboard_device; use crate::arch::riscv64::virtio::mouse_device; use crate::arch::target::interrupt; use crate::arch::target::virtio::virtio_input::*; use crate::graphics::layer_manager; use crate::graphics::*; use crate::process::*; use cr...
use crate::arch::riscv64::virtio::gpu_device; use crate::arch::riscv64::virtio::keyboard_device; use crate::arch::riscv64::virtio::mouse_device; use crate::arch::target::interrupt; use crate::arch::target::virtio::virtio_input::*; use crate::graphics::layer_manager; use crate::graphics::*; use crate::process::*; use cr...
} EventType::EV_SYN => { lm.update(MOUSE_LAYER_ID); } _ => {} } event = queue.pop_front(); } } } pub unsafe extern "C" fn fs_proc() { fs::fat::init(); fs::init(); let pm = process_manage...
if ev.code == EV_KEY::BTN_LEFT as u16 && ev.value == 1 { let x = lm.get_layer_x(MOUSE_LAYER_ID); let y = lm.get_layer_y(MOUSE_LAYER_ID); lm.on_event(ObjectEvent::MouseLeftPress(x, y), MOUSE_LAYER_ID); } else if ev.code == EV_KEY...
if_condition
[ { "content": "pub fn unmap(root: &mut Table) {\n\n let page_layout = Layout::from_size_align(0x1000, 0x1000).unwrap();\n\n #[cfg(target_pointer_width = \"32\")]\n\n for lv2 in 0..Table::len() {\n\n let ref entry_lv2 = root.entries[lv2];\n\n if entry_lv2.is_valid() && entry_lv2.is_branch()...
Rust
src/main.rs
Shirataki2/atcoder-discord-bot
236023c7d2a29d09c62785249230eddea92ceeae
#![warn(clippy::all)] mod commands; mod tasks; mod models; mod database; mod utils; mod data; mod event_handler; mod error; mod http; #[macro_use] extern crate log; #[macro_use] extern crate sqlx; use crate::{ utils::send_error, data::{DatabasePool, ShardManagerContainer, SubmissionQueue}, event_handler::...
#![warn(clippy::all)] mod commands; mod tasks; mod models; mod database; mod utils; mod data; mod event_handler; mod error; mod http; #[macro_use] extern crate log; #[macro_use] extern crate sqlx; use crate::{ utils::send_error, data::{DatabasePool, ShardManagerContainer, SubmissionQueue}, event_handler::...
#[group] #[commands(invite, source)] struct General; #[group] #[commands(register, unregister, subscribe, unsubscribe)] struct Account; #[group] #[commands(start, stop)] struct Settings; #[group] #[commands(streak, problem, point)] struct Ranking; #[tokio::main(flavor = "multi_thread", worker_threads = 8)] async ...
m, 0) => format!("This command requires at least {} arguments to run", m), (m, g) => format!("This command requires at least {} arguments, but you give {} arguments", m, g), }; let _ = send_error(ctx, msg, "Not Enough Arguments!", &description).await; } DispatchEr...
function_block-function_prefix_line
[ { "content": "pub fn unknown_error() -> CommandError {\n\n CommandError::from(\"Unknown error has occurred.\\n\\\n\n If you get this error repeatedly, please contact `admin@sample.com`.\")\n\n}\n", "file_path": "src/utils.rs", "rank": 0, "score": 111059.39148688925 }, { "content": ...
Rust
src/zcm.rs
Gregory-Meyer/zcm-rs
6e9e6e9be1f4324260c239e7054ee0313056be3c
extern crate std; use super::*; pub struct Zcm { zcm: ffi::zcm_t, } impl Zcm { pub fn new(url: &str) -> Result<Zcm, NewError> { let url_owned = match std::ffi::CString::new(url) { Ok(u) => u, Err(e) => return Err(NewError::Nul(e)), }; let mut zcm = Zcm { ...
extern crate std; use super::*; pub struct Zcm { zcm: ffi::zcm_t, } impl Zcm { pub fn new(url: &str) -> Result<Zcm, NewError> { let url_owned = match std::ffi::CString::new(url) { Ok(u) => u, Err(e) => return Err(NewError::Nul(e)), }; let mut zcm = Zcm { ...
} } pub fn as_ptr(&self) -> *const ffi::zcm_t { &self.zcm as *const ffi::zcm_t } pub fn as_mut_ptr(&mut self) -> *mut ffi::zcm_t { &mut self.zcm as *mut ffi::zcm_t } } impl Drop for Zcm { fn drop(&mut self) { unsafe { ffi::zcm_cleanup(&mut self.zcm as *mut ffi::zcm_t...
let err = unsafe { ffi::zcm_strerror(self.as_ptr()) }; unsafe { std::ffi::CStr::from_ptr(err) }.to_string_lossy() } pub fn flush(&mut self) { unsafe { ffi::zcm_flush(self.as_mut_ptr()) }; } pub fn try_flush(&mut self) -> Result<(), Error> { let result = unsafe { ffi::zcm...
random
[ { "content": "#[test]\n\nfn foo() {\n\n let mut zcm = Zcm::new(\"ipc\").unwrap();\n\n let channel = std::ffi::CString::new(\"foo\").unwrap();\n\n\n\n let mut received = false;\n\n\n\n let sub = unsafe {\n\n ffi::zcm_subscribe(\n\n zcm.as_mut_ptr(),\n\n channel.as_ptr(),\...
Rust
crates/graphics/src/api/vulkan/texture.rs
gents83/NRG
62743a54ac873a8dea359f3816e24c189a323ebb
use super::{ copy_buffer_to_image, copy_from_buffer, copy_image_to_buffer, copy_to_buffer, create_buffer, create_image, create_image_view, destroy_buffer, }; use super::{device::BackendDevice, find_depth_format}; use crate::api::backend::physical_device::BackendPhysicalDevice; use crate::{Area, TEXTURE_CHANNEL_...
use super::{ copy_buffer_to_image, copy_from_buffer, copy_image_to_buffer, copy_to_buffer, create_buffer, create_image, create_image_view, destroy_buffer, }; use super::{device::BackendDevice, find_depth_format}; use crate::api::backend::physical_device::BackendPhysicalDevice; use crate::{Area, TEXTURE_CHANNEL_...
pub fn destroy(&self, device: &BackendDevice) { unsafe { vkDestroySampler.unwrap()(**device, self.texture_sampler, ::std::ptr::null_mut()); vkDestroyImageView.unwrap()(**device, self.texture_image_view, ::std::ptr::null_mut()); vkDestroyImage.unwrap()(**device, self.tex...
e( device, physical_device, format, layers_count, specific_flags, aspect_flags, ); texture.create_texture_sampler(device, physical_device); texture }
function_block-function_prefixed
[]
Rust
src/main.rs
KisaragiEffective/webhook-handler
d31f1df94e5f0c8e445ef6bdcbb8c63b0b7283d8
#![warn(clippy::pedantic, clippy::nursery)] #![deny(type_alias_bounds, legacy_derive_helpers, late_bound_lifetime_arguments)] mod payload; mod call; mod config; mod serde_integration; mod generic_format_io; use std::any::Any; use std::borrow::Borrow; use std::fs::File; use std::io::BufReader; use std::marker::PhantomD...
#![warn(clippy::pedantic, clippy::nursery)] #![deny(type_alias_bounds, legacy_derive_helpers, late_bound_lifetime_arguments)] mod payload; mod call; mod config; mod serde_integration; mod generic_format_io; use std::any::Any; use std::borrow::Borrow; use std::fs::File; use std::io::BufReader; use std::marker::PhantomD...
web::post() .to(|| { HttpResponse::BadRequest().body("Content-Type header must be included") }) ) ) }); trace!("binding ports"); http_server .bind_rustls(f...
); } ServerConfig::builder() .with_safe_defaults() .with_no_client_auth() .with_single_cert(cert_chain, keys.remove(0)).unwrap() }; trace!("Reading config..."); let running_config = File::open("data/config.json").unwrap(); RUNNING_CONFIG.set(serde_jso...
function_block-random_span
[ { "content": "pub fn deserialize_iso8601<'de, D: Deserializer<'de>>(deserializer: D) -> Result<DateTime, D::Error> {\n\n use std::str::FromStr;\n\n match String::deserialize(deserializer) {\n\n Ok(a) => {\n\n match DateTime::from_str(a.as_str()) {\n\n Ok(a) => { Ok(a) }\n\...
Rust
src/mix/sender.rs
hydra-acn/hydra
b5cb31310d1be95202f65ea732574e84555c3365
use futures_util::stream; use log::*; use rand::seq::SliceRandom; use std::collections::HashMap; use std::io::Write; use std::net::SocketAddr; use std::sync::Arc; use std::time::Duration; use tokio::task; use crate::crypto::cprng::thread_cprng; use crate::epoch::current_time; use crate::error::Error; use crate::net::...
use futures_util::stream; use log::*; use rand::seq::SliceRandom; use std::collections::HashMap; use std::io::Write; use std::net::SocketAddr; use std::sync::Arc; use std::time::Duration; use tokio::task; use crate::crypto::cprng::thread_cprng; use crate::epoch::current_time; use crate::error::Error; use crate::net::...
async fn relay_cells( _dir_client: Arc<directory_client::Client>, c: TcpChannel, cells: Vec<Cell>, deadline: Option<Duration>, ) { tokio::task::spawn_blocking(move || { let shuffle_it = ShuffleIterator::new(cells, deadline); let mut stream = c.write().expect("Lock poisoned"); ...
subscription to each rendezvous node only"); } for sub in pkts.into_iter() { info!("Sending subscriptions for {} circuits", sub.circuits.len()); let req = tonic::Request::new(sub); c.subscribe(req) .await .map(|_| ()) .unwrap_or_else(|e| warn!("Subscr...
function_block-function_prefixed
[ { "content": "pub fn key_exchange(pk_mix: &Key) -> Result<(Key, Key), Error> {\n\n let (pk, sk) = x448::generate_keypair();\n\n let s = x448::generate_shared_secret(&pk_mix, &sk)?;\n\n Ok((pk, s))\n\n}\n\n\n\npub async fn update_loop(state: Arc<State>) {\n\n loop {\n\n // wait till next updat...
Rust
Project/src/main.rs
qarmin/gtk-rs-fuzzer
def0baaabe356998cef130f3a3aec6654bd5b78d
#![allow(dead_code)] #![allow(unused_imports)] #![allow(unused_must_use)] mod create_objects; mod enum_things; mod helpers; mod implementations; mod ziemniak; use crate::create_objects::*; use crate::ziemniak::{run_tests, SettingsTaker}; use gtk4::prelude::*; use gtk4::*; use std::fs; use std::fs::File; fn main() { ...
#![allow(dead_code)] #![allow(unused_imports)] #![allow(unused_must_use)] mod create_objects; mod enum_things; mod helpers; mod implementations; mod ziemniak; use crate::create_objects::*; use crate::ziemniak::{run_tests, SettingsTaker}; use gtk4::prelude::*; use gtk4::*; use std::fs; use std::fs::File; fn main() { ...
if !st.allowed_functions.is_empty() { println!("Allowed functions:"); for i in &st.allowed_functions { println!("{}", i); } } if !st.ignored_functions.is_empty() { println!("Ignored functions:"); for i in &st.ignored_fu...
if !st.allowed_classes.is_empty() { println!("Allowed classes:"); for i in &st.allowed_classes { println!("{}", i); } }
if_condition
[ { "content": "pub fn take_vec_string() -> Vec<String> {\n\n let mut to_return = Vec::new();\n\n\n\n for _i in 0..thread_rng().gen_range(0..10) {\n\n to_return.push(take_string());\n\n }\n\n\n\n debug_printing_vec(&to_return);\n\n to_return\n\n}\n\n\n", "file_path": "Project/src/helpers...
Rust
src/gl33/buffer.rs
phaazon/luminance-gl-rs
73e156ce276b3882335201bde5ca31bc6afa4ba5
use gl; use gl::types::*; use gl33::token::GL33; use luminance::buffer; use std::cmp::Ordering::*; use std::mem; use std::os::raw::c_void; use std::ptr; use std::slice; pub type Buffer<T> = buffer::Buffer<GL33, T>; pub type BufferSlice<'a, T> = buffer::BufferSlice<'a, GL33, T>; pub type BufferSliceMut<'a, T> = buffer:...
use gl; use gl::types::*; use gl33::token::GL33; use luminance::buffer; use std::cmp::Ordering::*; use std::mem; use std::os::raw::c_void; use std::ptr; use std::slice; pub type Buffer<T> = buffer::Buffer<GL33, T>; pub type BufferSlice<'a, T> = buffer::BufferSlice<'a, GL33, T>; pub type BufferSliceMut<'a, T> = buffer:...
fn read_whole<T>(buffer: &Self::ABuffer, nb: usize) -> Vec<T> where T: Copy { unsafe { gl::BindBuffer(gl::ARRAY_BUFFER, buffer.handle); let ptr = gl::MapBuffer(gl::ARRAY_BUFFER, gl::READ_ONLY) as *const T; let values = Vec::from(slice::from_raw_parts(ptr, nb)); let _ = gl::UnmapBuffer(...
return Err(buffer::BufferError::Overflow); } unsafe { gl::BindBuffer(gl::ARRAY_BUFFER, buffer.handle); let ptr = gl::MapBuffer(gl::ARRAY_BUFFER, gl::WRITE_ONLY); *(ptr.offset(off as isize) as *mut T) = x; let _ = gl::UnmapBuffer(gl::ARRAY_BUFFER); gl::BindBuffer(gl::ARRAY_BUFFER...
function_block-function_prefix_line
[ { "content": "pub fn create_texture<L, D>(target: GLenum, size: D::Size, mipmaps: usize, pf: PixelFormat, sampler: &Sampler) -> Result<()>\n\n where L: Layerable,\n\n D: Dimensionable,\n\n D::Size: Copy {\n\n set_texture_levels(target, mipmaps);\n\n\n\n apply_sampler_to_texture(target, sa...
Rust
src/test/instruction_tests/instr_vpsrldq.rs
ftilde/rust-x86asm
f6584b8cfe8e75d978bf7b83a67c69444fd3f161
use instruction_def::*; use test::run_test; use Operand::*; use Reg::*; use RegScale::*; use RegType::*; use {BroadcastMode, Instruction, MaskReg, MergeMode, Mnemonic, OperandSize, Reg, RoundingMode}; #[test] fn vpsrldq_1() { run_test( &Instruction { mnemonic: Mnemonic::VPSRLDQ, ope...
use instruction_def::*; use test::run_test; use Operand::*; use Reg::*; use RegScale::*; use RegType::*; use {BroadcastMode, Instruction, MaskReg, MergeMode, Mnemonic, OperandSize, Re
erandSize::Xmmword), None, )), operand3: Some(Literal8(26)), operand4: None, lock: false, rounding_mode: None, merge_mode: None, sae: false, mask: None, broadcast: None, }, &[98, 2...
g, RoundingMode}; #[test] fn vpsrldq_1() { run_test( &Instruction { mnemonic: Mnemonic::VPSRLDQ, operand1: Some(Direct(XMM4)), operand2: Some(Direct(XMM6)), operand3: Some(Literal8(44)), operand4: None, lock: false, roundin...
random
[ { "content": "fn encode64_helper2(mnemonic: Mnemonic, operand1: Operand, operand2: Operand, expected: &Vec<u8>) {\n\n let instr = Instruction {\n\n mnemonic: mnemonic,\n\n operand1: Some(operand1),\n\n operand2: Some(operand2),\n\n operand3: None,\n\n operand4: None,\n\n ...
Rust
cargo/vendor/memmap-0.6.1/src/windows.rs
mfarrugi/cargo-raze-example-stdx
e4283e299d298cea9a534d0623cb4f3b54ef36f5
extern crate kernel32; extern crate winapi; use std::{io, mem, ptr}; use std::fs::File; use std::os::raw::c_void; use std::os::windows::io::{AsRawHandle, RawHandle}; pub struct MmapInner { file: Option<File>, ptr: *mut c_void, len: usize, copy: bool, } impl MmapInner { pub fn new( ...
extern crate kernel32; extern crate winapi; use std::{io, mem, ptr}; use std::fs::File; use std::os::raw::c_void; use std::os::windows::io::{AsRawHandle, RawHandle}; pub struct MmapInner { file: Option<File>, ptr: *mut c_void, len: usize, copy: bool, } impl MmapInner { pub fn new( ...
pub fn map_mut(len: usize, file: &File, offset: usize) -> io::Result<MmapInner> { let exec = protection_supported(file.as_raw_handle(), winapi::PAGE_EXECUTE_READ); let mut access = winapi::FILE_MAP_READ | winapi::FILE_MAP_WRITE; let protection = if exec { access |= winapi::FILE...
pub fn map_exec(len: usize, file: &File, offset: usize) -> io::Result<MmapInner> { let write = protection_supported(file.as_raw_handle(), winapi::PAGE_READWRITE); let mut access = winapi::FILE_MAP_READ | winapi::FILE_MAP_EXECUTE; let protection = if write { access |= winapi::FILE_MAP...
function_block-full_function
[ { "content": "fn main() {\n\n env_logger::init().unwrap();\n\n\n\n info!(\"All is well.\"); \n\n}\n", "file_path": "example/example.rs", "rank": 0, "score": 15112.634085037585 }, { "content": "fn main() {\n\n use std::io::Read;\n\n\n\n let mut resp = reqwest::get(\"https://www.ru...
Rust
src/services/mod.rs
eduardocanellas/lagoinha-rs
1b6fbc47bcc9801e1b9e0b55808a0e0619742fa0
pub mod cepla; pub mod correios; pub mod viacep; extern crate serde; use serde::{Deserialize, Serialize}; #[derive(Deserialize, Serialize, Debug)] pub struct Address { pub cep: String, pub address: String, pub details: String, pub neighborhood: String, pub state: String, pub city: String, } p...
pub mod cepla; pub mod correios; pub mod viacep; extern crate serde; use serde::{Deserialize, Serialize}; #[derive(Deserialize, Serialize, Debug)] pub struct Address { pub cep: String, pub address: String, pub details: String, pub neighborhood: String, pub state: String, pub city: String, } p...
ails); } }
] fn cepla_conversion() { let cepl_addr = cepla::Address { cep: "70150903".to_string(), state: "DF".to_string(), city: "Brasília".to_string(), neighborhood: "Zona Cívico-Administrativa".to_string(), address: "SPP".to_string(), details: ...
random
[ { "content": "fn main() {\n\n let args: Vec<String> = env::args().collect();\n\n let mut cep: &str = \"20940040\".as_ref();\n\n if args.len() >= 2 {\n\n cep = &args[1][..];\n\n }\n\n let addr = async_std::task::block_on(lagoinha::get_address(cep, None));\n\n println!(\"{:#?}\", addr);\n...
Rust
src/operation.rs
Tak-Iwamoto/rusty-gql
8244d844f827a524cd91ba815fe5d113f3499927
use std::{ collections::HashMap, ops::Deref, sync::{Arc, Mutex}, }; use graphql_parser::{ query::{Definition, Document, FragmentDefinition, SelectionSet, VariableDefinition}, schema::Directive, }; use crate::{error::GqlError, Variables}; #[derive(Debug)] pub struct OperationInner<'a> { pub op...
use std::{ collections::HashMap, ops::Deref, sync::{Arc, Mutex}, }; use graphql_parser::{ query::{Definition, Document, FragmentDefinition, SelectionSet, VariableDefinition}, schema::Directive, }; use crate::{error::GqlError, Variables}; #[derive(Debug)] pub struct OperationInner<'a> { pub op...
} } pub fn get_operation_definitions<'a>( doc: &'a Document<'a, String>, ) -> Vec<&'a graphql_parser::query::Definition<'a, String>> { doc.definitions .iter() .filter(|def| matches!(def, Definition::Operation(_))) .collect::<Vec<_>>() } pub fn build_operation<'a>( doc: &'a Doc...
match self { OperationType::Query => String::from("Query"), OperationType::Mutation => String::from("Mutation"), OperationType::Subscription => String::from("Subscription"), }
if_condition
[ { "content": "pub fn get_type_name(ty: &Type<'_, String>) -> String {\n\n match ty {\n\n Type::NamedType(named_type) => named_type.to_string(),\n\n Type::ListType(list) => get_type_name(list),\n\n Type::NonNullType(non_null) => get_type_name(non_null),\n\n }\n\n}\n\n\n", "file_pat...
Rust
src/encoding/unmarshal.rs
KevinKelley/hobbits-rs
1b2a4f3c8634921a379aa70992fe000973cf130b
pub use crate::encoding::envelope::Envelope; pub use crate::encoding::EwpError; pub fn unmarshal(msg: &[u8]) -> Result<Envelope,EwpError> { let index = msg.iter().position(|&r| r == '\n' as u8); let index = index.ok_or( EwpError::new("message request must contain 2 lines") )?; let hdr = &msg[0..index]; ...
pub use crate::encoding::envelope::Envelope; pub use crate::encoding::EwpError; pub fn unmarshal(msg: &[u8]) -> Result<Envelope,EwpError> { let index = msg.iter().position(|&r| r == '\n' as u8); let index = index.ok_or( EwpError::new("message request must contain 2 lines") )?; let hdr = &msg[0..index]; ...
}
use super::*; struct Test { message: Vec<u8>, err: EwpError } let tests: Vec<Test> = vec!( Test { message: "EWP 13.05 RPC blahblahblah json 16 14this is a headerthis is a body".to_string().into_bytes(), err: EwpError::new("message request must con...
function_block-function_prefix_line
[ { "content": "/// Marshal takes a parsed message and encodes it to a wire protocol message\n\npub fn marshal(msg: &Envelope) -> Result<Vec<u8>, EwpError> {\n\n\n\n if msg.version == \"\" { return Err(EwpError::new(\"missing version!\")) }\n\n if msg.protocol == \"\" { return Err(EwpError::new(\"missing pr...
Rust
kiln_lib/src/kafka.rs
simplybusiness/Kiln
884e96059622c72e99254ac737bee25aee964adf
use addr::{parser::DomainName, psl::List}; use openssl_probe::ProbeResult; use rdkafka::config::ClientConfig; use rdkafka::consumer::stream_consumer::StreamConsumer; use rdkafka::error::KafkaError; use rdkafka::producer::future_producer::FutureProducer; use std::fmt::Display; #[derive(Debug, Clone)] pub struct KafkaBo...
use addr::{parser::DomainName, psl::List}; use openssl_probe::ProbeResult; use rdkafka::config::ClientConfig; use rdkafka::consumer::stream_consumer::StreamConsumer; use rdkafka::error::KafkaError; use rdkafka::producer::future_producer::FutureProducer; use std::fmt::Display; #[derive(Debug, Clone)] pub struct KafkaBo...
#[test] fn get_bootstrap_config_returns_error_when_hostname_invalid_and_domain_validation_enabled() { let hostname = "kafka:1234".to_owned(); let mut fake_vars = vec![("KAFKA_BOOTSTRAP_TLS".to_owned(), hostname.clone())].into_iter(); let actual = get_bootstrap_config(&mut fake_vars).e...
let actual = get_bootstrap_config(&mut fake_vars).expect_err("expected Err(_) value"); assert_eq!( actual.to_string(), "Required environment variable KAFKA_BOOTSTRAP_TLS failed validation because value is present but empty" ) }
function_block-function_prefix_line
[ { "content": "#[derive(Clone, SerdeValue, Serialize, Deserialize)]\n\nstruct EventType(Vec<String>);\n\n\n", "file_path": "slack-connector/src/main.rs", "rank": 1, "score": 122833.64715094889 }, { "content": "#[derive(Clone, SerdeValue, Serialize, Deserialize)]\n\nstruct EventType(Vec<String...
Rust
src/get_stats.rs
razorheadfx/project-cleanup
8444bb77da3b5ed969bcd28f4daf4c09363a5fc8
use std::{ thread, process }; use std::path::PathBuf; use std::sync::mpsc::channel; use std::collections::HashMap; use colored::*; use humansize::{ FileSize, file_size_opts as options }; use crate::languages::*; use crate::file_utils::{ fname, walk_files }; use crate::spinner::Spinner; #[derive(Debug)] pub struct St...
use std::{ thread, process }; use std::path::PathBuf; use std::sync::mpsc::channel; use std::collections::HashMap; use colored::*; use humansize::{ FileSize, file_size_opts as options }; use crate::languages::*; use crate::file_utils::{ fname, walk_files }; use crate::spinner::Spinner; #[derive(Debug)] pub struct St...
pub fn format_size(size : u64) -> String { return size.file_size(options::CONVENTIONAL).unwrap(); }
pub fn get(project_paths : Vec<PathBuf>) -> HashMap<PathBuf, Stats> { let (tx, rc) = channel(); thread::spawn(move || { let mut stats = HashMap::new(); let mut langs = HashMap::new(); langs.insert(NODE, 0); langs.insert(RUST, 0); langs.insert(JAVA, 0); let mut total_size_src = 0; let mut total_size...
function_block-full_function
[ { "content": "/// Gets the filename of a given path\n\npub fn fname(path : &Path) -> &str {\n\n\tpath.file_name().unwrap_or(OsStr::new(\"\")).to_str().unwrap_or(\"\")\n\n}\n", "file_path": "src/file_utils/mod.rs", "rank": 0, "score": 70209.53629687006 }, { "content": "pub fn identify(p : &Pa...
Rust
src/connectivity/bluetooth/profiles/bt-avrcp/src/metrics/mod.rs
csrpi/fuchsia
2f015594dcb4c13aa51eee305ad561078f1f9b7f
use { fuchsia_bluetooth::types::PeerId, fuchsia_inspect::{self as inspect, NumericProperty}, fuchsia_inspect_derive::Inspect, parking_lot::Mutex, std::{collections::HashSet, sync::Arc}, }; use crate::profile::{AvrcpControllerFeatures, AvrcpTargetFeatures}; pub const METRICS_NODE_NAME: &str = "me...
use { fuchsia_bluetooth::types::PeerId, fuchsia_inspect::{self as inspect, NumericProperty}, fuchsia_inspect_derive::Inspect, parking_lot::Mutex, std::{collections::HashSet, sync::Arc}, }; use crate::profile::{AvrcpControllerFeatures, AvrcpTargetFeatures}; pub const METRICS_NODE_NAME: &str = "me...
r(id1); metrics1.control_collision(); metrics1.control_connection(); metrics1.browse_connection(); assert_inspect_tree!(inspect, root: { metrics: contains { connection_errors: 3u64, control_connections: 3u64, browse_connections:...
s2.control_connection(); assert_inspect_tree!(inspect, root: { metrics: contains { connection_errors: 1u64, control_connections: 1u64, browse_connections: 0u64, distinct_peers: 2u64, control_channel_collisions: 0u64, ...
function_block-random_span
[]
Rust
src/record.rs
marcsch/seq_io
3d461a3651fb975cd509fd7f580f1b44ccd9b9d3
use memchr::memchr; use std::borrow::Cow; use std::io; use std::str; pub use crate::core::{QualRecordPosition, SeqRecordPosition}; pub trait BaseRecord { fn head(&self) -> &[u8]; fn seq(&self) -> &[u8]; fn full_seq(&self) -> Cow<[u8]>; ...
use memchr::memchr; use std::borrow::Cow; use std::io; use std::str; pub use crate::core::{QualRecordPosition, SeqRecordPosition}; pub trait BaseRecord { fn head(&self) -> &[u8]; fn seq(&self) -> &[u8]; fn full_seq(&self) -> Cow<[u8]>; ...
fn num_qual_lines(&self) -> usize { (**self).num_qual_lines() } fn write<W: io::Write>(&self, writer: W) -> io::Result<()> { (**self).write(writer) } }
fn opt_full_qual_given<'s, F: FnOnce() -> &'s mut Vec<u8>>( &'s self, owned_fn: F, ) -> Option<Cow<'s, [u8]>> { (**self).opt_full_qual_given(owned_fn) }
function_block-full_function
[ { "content": "#[inline]\n\npub fn write_wrap<W, H>(mut writer: W, head: H, seq: &[u8], wrap: usize) -> io::Result<()>\n\nwhere\n\n W: io::Write,\n\n H: HeadWriter,\n\n{\n\n write_head(&mut writer, head)?;\n\n write_wrap_seq(writer, seq, wrap)\n\n}\n\n\n\n/// Writes data to the FASTA format. Wraps th...
Rust
examples/hashrocket-bench.rs
hobinjk/tokio-websocket
b54adc78740ce7caf442e54e906b0a41b6daf7a8
extern crate futures; extern crate tokio_core; extern crate tokio_io; extern crate websocket; extern crate serde_json; use serde_json::Value; use std::collections::HashMap; use std::rc::Rc; use std::cell::RefCell; use std::io::{Error, ErrorKind}; use tokio_core::net::TcpListener; use tokio_core::reactor::Core; use t...
extern crate futures; extern crate tokio_core; extern crate tokio_io; extern crate websocket; extern crate serde_json; use serde_json::Value; use std::collections::HashMap; use std::rc::Rc; use std::cell::RefCell; use std::io::{Error, ErrorKind}; use tokio_core::net::TcpListener; use tokio_core::reactor::Core; use t...
if frame.header.opcode == Opcode::Close { conns.remove(&addr); return Err(Error::new(ErrorKind::Other, "close requested")) } let tx = conns.get_mut(&addr).unwrap(); ...
yload) { if let Some(&Value::String(ref s)) = obj.get("type") { if s == "echo" { return Message::Echo(frame); } if s == "broadcast" { let msg = format!(r#"{{"type":"broadcastResult","payload":{}}}"#, obj.get("payload").unwrap_or(NULL_PAYLOAD));...
random
[ { "content": "pub fn opcode_to_u8(opcode: Opcode) -> u8 {\n\n match opcode {\n\n Opcode::Continuation => 0,\n\n Opcode::Text => 1,\n\n Opcode::Binary => 2,\n\n Opcode::Close => 8,\n\n Opcode::Ping => 9,\n\n Opcode::Pong => 10,\n\n }\n\n}\n\n\n", "file_path": "...
Rust
src/args.rs
JoshMcguigan/waysay
7d2744d8de03d5a261ea4905efe67584ec8f07d3
#[derive(Clone)] pub struct Args { pub message: String, pub buttons: Vec<ArgButton>, pub message_type: String, pub detailed_message: bool, pub detailed_message_contents: String, } #[derive(Clone)] pub struct ArgButton { pub text: String, pub action: String, } pub fn parse(args: impl Iterat...
#[derive(Clone)] pub struct Args { pub message: String, pub buttons: Vec<ArgButton>, pub message_type: String, pub detailed_message: bool, pub detailed_message_contents: String, } #[derive(Clone)] pub struct ArgButton { pub text: String, pub action: String, } pub fn parse(args: impl Iterat...
} else { Err("missing required arg message (-m/--message)".into()) } } #[cfg(test)] mod tests { use super::parse; #[test] fn no_args() { let input = vec!["waysay".into()]; assert_eq!( "missing required arg message (-m/--message)", parse(input.into_...
Ok(Args { message, buttons, message_type: message_type.unwrap_or_else(|| "error".into()), detailed_message, detailed_message_contents: String::new(), })
call_expression
[ { "content": "struct Surface {\n\n args: Args,\n\n surface: wl_surface::WlSurface,\n\n layer_surface: Main<zwlr_layer_surface_v1::ZwlrLayerSurfaceV1>,\n\n next_render_event: Rc<Cell<Option<RenderEvent>>>,\n\n pools: DoubleMemPool,\n\n dimensions: (u32, u32),\n\n /// X, Y coordinates of curr...
Rust
src/application/engine.rs
hoangpq/crayon
f37a5e8c23b7c1d12583e585012960ab0ee922fb
use std::sync::atomic::{AtomicBool, Ordering}; use std::sync::Arc; use crate::sched::prelude::LatchProbe; use crate::window::prelude::{Event, EventListener, EventListenerHandle, WindowEvent}; use super::lifecycle::LifecycleListener; use super::Params; type Result<T> = ::std::result::Result<T, ::failure::Error>; pub...
use std::sync::atomic::{AtomicBool, Ordering}; use std::sync::Arc; use crate::sched::prelude::LatchProbe; use crate::window::prelude::{Event, EventListener, EventListenerHandle, WindowEvent}; use super::lifecycle::LifecycleListener; use super::Params; type Result<T> = ::std::result::Result<T, ::failure::Error>; pub...
#[inline] pub fn shutdown(&self) { self.state.alive.store(false, Ordering::Relaxed); } #[inline] pub fn headless(&self) -> bool { self.headless } pub fn run_oneshot(&self) -> Result<()> { super::foreach(|v| v.on_pre_update())?; super::foreach(|v| v.on_upda...
pub unsafe fn new_headless(params: Params) -> Result<Self> { #[cfg(not(target_arch = "wasm32"))] crate::sched::setup(4, None, None); #[cfg(target_arch = "wasm32")] crate::sched::setup(0, None, None); crate::window::headless(); crate::video::headless(); crate::inp...
function_block-full_function
[ { "content": "#[inline]\n\npub fn headless() -> bool {\n\n ctx().headless()\n\n}\n\n\n", "file_path": "src/application/mod.rs", "rank": 0, "score": 275338.7219091743 }, { "content": "#[inline]\n\npub fn create_surface(params: SurfaceParams) -> Result<SurfaceHandle> {\n\n ctx().create_s...
Rust
src/tests.rs
korken89/lbfgs-rs
a7a58926622da66c1893cc3cff22999226983528
use crate::*; #[test] #[should_panic] fn lbfgs_panic_zero_n() { let mut _e = Lbfgs::new(0, 1); } #[test] #[should_panic] fn lbfgs_panic_zero_mem() { let mut _e = Lbfgs::new(1, 0); } #[test] #[should_panic] fn lbfgs_panic_apply_size_grad() { let mut e = Lbfgs::new(5, 5); e.update_hessian(&[0.0; 4], &[...
use crate::*; #[test] #[should_panic] fn lbfgs_panic_zero_n() { let mut _e = Lbfgs::new(0, 1); } #[test] #[should_panic] fn lbfgs_panic_zero_mem() { let mut _e = Lbfgs::new(1, 0); } #[test] #[should_panic] fn lbfgs_panic_apply_size_grad() { let mut e = Lbfgs::new(5, 5); e.update_hessian(&[0.0; 4], &[...
#[test] fn correctneess_reset() { let mut e = Lbfgs::new(3, 3); let mut g = [-3.1, 1.5, 2.1]; assert_eq!( UpdateStatus::UpdateOk, e.update_hessian(&[0.0, 0.0, 0.0], &[0.0, 0.0, 0.0]) ); assert_eq!( UpdateStatus::UpdateOk, e.update_hessian(&[-0.5, 0.6, -1.2], &[0.1,...
eq!( UpdateStatus::UpdateOk, e.update_hessian(&[-2.25, 3.5, -3.1], &[0.39, 0.39, -0.84]) ); assert_eq!( UpdateStatus::UpdateOk, e.update_hessian(&[-3.75, 6.3, -4.3], &[0.49, 0.59, -1.24]) ); e.apply_hessian(&mut g); println!("{:#.3?}", e); let gamma_correct = ...
function_block-function_prefixed
[ { "content": "#[inline]\n\npub fn scalar_mult<T>(a: &mut [T], s: T)\n\nwhere\n\n T: Float,\n\n{\n\n a.iter_mut().for_each(|out| *out = s * (*out));\n\n}\n\n\n\n/// Calculates out = out + s * a\n", "file_path": "src/vec_ops.rs", "rank": 8, "score": 39979.04309943656 }, { "content": "#[i...
Rust
src/iam.rs
NathanHowell/google-cloud-storage-rs
f599aa4009c9475225ba1a6fbcd2961836992e69
use crate::google::iam::v1::{Policy, TestIamPermissionsResponse}; use crate::google::storage::v1::{ GetIamPolicyRequest, SetIamPolicyRequest, TestIamPermissionsRequest, }; use crate::query::{PushIf, Query}; use crate::request::Request; use crate::urls::Urls; use crate::{Client, Result}; use reqwest::Method; use std...
use crate::google::iam::v1::{Policy, TestIamPermissionsResponse}; use crate::google::storage::v1::{ GetIamPolicyRequest, SetIamPolicyRequest, TestIamPermissionsRequest, }; use crate::query::{PushIf, Query}; use crate::request::Request; use crate::urls::Urls; use crate::{Client, Result}; use reqwest::Method; use std...
} impl Request for GetIamPolicyRequest { const REQUEST_METHOD: Method = Method::GET; type Response = Policy; fn request_path(&self, base_url: Url) -> Result<Url> { iam_url(base_url, self.iam_request.as_ref(), |r| &r.resource) } } impl Query for SetIamPolicyRequest { fn request_query(&mu...
e().request_query(); let mut requested_policy_version = self .iam_request .take() .and_then(|r| r.options) .map(|o| o.requested_policy_version); query.push_if_opt( "optionsRequestedPolicyVersion", &mut requested_policy_version, ...
function_block-function_prefixed
[ { "content": "fn acl_url(base_url: Url, bucket: &str, object: &str) -> Result<Url> {\n\n base_url.bucket(bucket)?.object(object)?.join_segment(\"acl\")\n\n}\n\n\n\nimpl Query for InsertObjectAccessControlRequest {\n\n fn request_query(&mut self) -> Vec<(&'static str, String)> {\n\n let mut query = ...
Rust
sdk/guardduty/src/lens.rs
eduardomourar/aws-sdk-rust
58569c863afbe7bc442da8254df6c3970111de38
pub(crate) fn reflens_structure_crate_output_get_usage_statistics_output_next_token( input: &crate::output::GetUsageStatisticsOutput, ) -> std::option::Option<&std::string::String> { let input = match &input.next_token { None => return None, Some(t) => t, }; Some(input) } pub(crate) fn...
pub(crate) fn reflens_structure_crate_output_get_usage_statistics_output_next_token( input: &crate::output::GetUsageStatisticsOutput, ) -> std::option::Option<&std::string::String> { let input = match &input.next_token { None => return None, Some(t) => t, }; Some(input) } pub(crate) fn...
pub(crate) fn reflens_structure_crate_output_list_organization_admin_accounts_output_next_token( input: &crate::output::ListOrganizationAdminAccountsOutput, ) -> std::option::Option<&std::string::String> { let input = match &input.next_token { None => return None, Some(t) => t, }; Some...
pub(crate) fn reflens_structure_crate_output_list_members_output_next_token( input: &crate::output::ListMembersOutput, ) -> std::option::Option<&std::string::String> { let input = match &input.next_token { None => return None, Some(t) => t, }; Some(input) }
function_block-function_prefix_line
[]
Rust
semantics/src/traversal/functions.rs
vaporydev/fe
246b23bad148e358ea04b80ca9e4e7a5ce4cec8d
use crate::errors::SemanticError; use crate::namespace::scopes::{ BlockScope, BlockScopeType, ContractDef, ContractScope, Scope, Shared, }; use crate::namespace::types::{ Base, FixedSize, Tuple, Type, }; use crate::traversal::_utils::spanned_expression; use crate::traversal::{ ...
use crate::errors::SemanticError; use crate::namespace::scopes::{ BlockScope, BlockScopeType, ContractDef, ContractScope, Scope, Shared, }; use crate::namespace::types::{ Base, FixedSize, Tuple, Type, }; use crate::traversal::_utils::spanned_expression; use crate::traversal::{ ...
fn continue_statement( scope: Shared<BlockScope>, _context: Shared<Context>, stmt: &Spanned<fe::FuncStmt>, ) -> Result<(), SemanticError> { if let fe::FuncStmt::Continue {} = &stmt.node { return verify_loop_in_scope(scope, SemanticError::ContinueWithoutLoop); } unreachable!() } fn ver...
fn break_statement( scope: Shared<BlockScope>, _context: Shared<Context>, stmt: &Spanned<fe::FuncStmt>, ) -> Result<(), SemanticError> { if let fe::FuncStmt::Break {} = &stmt.node { return verify_loop_in_scope(scope, SemanticError::BreakWithoutLoop); } unreachable!() }
function_block-full_function
[ { "content": "/// Maps a type description node to an enum type.\n\npub fn type_desc(scope: Scope, typ: &Spanned<fe::TypeDesc>) -> Result<Type, SemanticError> {\n\n types::type_desc(&scope.module_scope().borrow().defs, &typ.node)\n\n}\n\n\n", "file_path": "semantics/src/traversal/types.rs", "rank": 0,...
Rust
src/utilities.rs
mandx/privie
1e44e5b942979746383496223390718d48db8fc7
use std::{ fmt::{Display, Formatter}, fs::{File, OpenOptions}, io::{self, stdin, stdout, BufReader, BufWriter, Read, Write}, path::{Path, PathBuf}, }; use thiserror::Error as ThisError; #[derive(Debug, ThisError)] pub enum IoUtilsError<P: std::fmt::Debug + Display> { #[error("Could not open `{path...
use std::{ fmt::{Display, Formatter}, fs::{File, OpenOptions}, io::{self, stdin, stdout, BufReader, BufWriter, Read, Write}, path::{Path, PathBuf}, }; use thiserror::Error as ThisError; #[derive(Debug, ThisError)] pub enum IoUtilsError<P: std::fmt::Debug + Display> { #[error("Could not open `{path...
} impl Default for InputFile { fn default() -> Self { Self::use_stdin() } } impl InputFile { const DISPLAY_STR: &'static str = "<stdin>"; pub fn use_stdin() -> Self { Self { filename: None } } pub fn use_filename<P: AsRef<Path>>(filename: P) -> Self { Self { ...
elf::Err> { Ok(match s { "" | "-" | Self::DISPLAY_STR => Self::use_stdin(), s => Self::use_filename(s), }) }
function_block-function_prefixed
[ { "content": "/// Attempt to decrypt the given ciphertext with the given secret key.\n\n/// Will fail if the secret key doesn't match the public key used to\n\n/// encrypt the payload, or if the ciphertext is not long enough.\n\npub fn open(ciphertext: &[u8], secret_key: &SecretKey) -> Result<Vec<u8>, Error> {\...
Rust
ivy-vulkan/src/descriptors/layout.rs
ten3roberts/ivy
fb5a7645c9f699c2aebf3d1b90c1d1f9e78355fa
use crate::Result; use std::{collections::HashMap, sync::Arc}; use ash::vk::DescriptorSetLayout; use ash::vk::DescriptorSetLayoutCreateInfo; use ash::Device; use parking_lot::RwLock; use smallvec::SmallVec; use std::hash::{Hash, Hasher}; use super::DescriptorSetBinding; use super::MAX_BINDINGS; #[derive(Clone, Debug...
use crate::Result; use std::{collections::HashMap, sync::Arc}; use ash::vk::DescriptorSetLayout; use ash::vk::DescriptorSetLayoutCreateInfo; use ash::Device; use parking_lot::RwLock; use smallvec::SmallVec; use std::hash::{Hash, Hasher}; use super::DescriptorSetBinding; use super::MAX_BINDINGS; #[derive(Clone, Debug...
} impl Eq for DescriptorLayoutInfo {} pub struct DescriptorLayoutCache { device: Arc<Device>, layouts: RwLock<HashMap<DescriptorLayoutInfo, DescriptorSetLayout>>, } impl DescriptorLayoutCache { pub fn new(device: Arc<Device>) -> Self { Self { device, layouts: RwLock::new(...
fn eq(&self, other: &Self) -> bool { for (a, b) in self.bindings.iter().zip(&other.bindings) { if a.binding != b.binding || a.descriptor_type != b.descriptor_type || a.descriptor_count != b.descriptor_count || a.stage_flags != b.stage_flags ...
function_block-full_function
[ { "content": "// Generates a random scalar between -1 and 1\n\npub fn one<R: Rng>(rng: &mut R) -> f32 {\n\n rng.gen_range(-1.0..=1.0)\n\n}\n", "file_path": "ivy-random/src/scalar.rs", "rank": 0, "score": 255513.0309084286 }, { "content": "// Generates a random scalar between 0 and 1\n\npu...
Rust
third-party/fs-mistrust/src/imp.rs
capyloon/api-daemon
ab4e4b60aa9bb617734c64655c0b8940fff098bc
use std::{ fs::{FileType, Metadata}, path::Path, }; #[cfg(target_family = "unix")] use std::os::unix::prelude::MetadataExt; use crate::{ walk::{PathType, ResolvePath}, Error, Result, Type, }; #[cfg(target_family = "unix")] pub(crate) const STICKY_BIT: u32 = 0o1000; fn boxed<'a, I: Iterator<Item = ...
use std::{ fs::{FileType, Metadata}, path::Path, }; #[cfg(target_family = "unix")] use std::os::unix::prelude::MetadataExt; use crate::{ walk::{PathType, ResolvePath}, Error, Result, Type, }; #[cfg(target_family = "unix")] pub(crate) const STICKY_BIT: u32 = 0o1000; fn boxed<'a, I: Iterator<Item = ...
fg(target_family = "unix")] self.check_permissions(path, path_type, meta, &mut errors); errors } fn check_type( &self, path: &Path, path_type: PathType, meta: &Metadata, errors: &mut Vec<Error>, ) { let want_type = match path_type { ...
path_type: PathType, meta: &Metadata, ) -> Vec<Error> { let mut errors = Vec::new(); self.check_type(path, path_type, meta, &mut errors); #[c
function_block-random_span
[]
Rust
x86asm/src/encode/encoding.rs
project-ela/ela
b59cae869ca4258954583a87725b090a586601c1
use crate::{ common::{modrm::ModRM, rex::Rex, sib::Sib}, instruction::operand::{ immediate::Immediate, memory::{Displacement, Memory}, offset::Offset, register::{self, Register}, }, }; use super::inst::EncodedInst; pub enum RM<'a> { Register(&'a Register), Memory(&'...
use crate::{ common::{modrm::ModRM, rex::Rex, sib::Sib}, instruction::operand::{ immediate::Immediate, memory::{Displacement, Memory}, offset::Offset, register::{self, Register}, }, }; use super::inst::EncodedInst; pub enum RM<'a> { Register(&'a Register), Memory(&'...
let reg_reg = reg.unwrap_or(&Register::Al); if reg_rm.size() != register::Size::QWord && reg_reg.size() != register::Size::QWord && !reg_rm.only_in_64bit() && !reg_reg.only_in_64bit() { return None; } Some(Rex::new( true, reg_reg.only_in_64bit(), ...
let reg_rm = match rm { Some(RM::Register(reg)) => reg, Some(RM::Memory(Memory { base: Some(base), .. })) => base, _ => &Register::Al, };
assignment_statement
[ { "content": "fn add_padding(v: &mut Vec<u8>, offset: usize) {\n\n if offset < v.len() {\n\n return;\n\n }\n\n let padding_len = offset - v.len();\n\n v.extend(&vec![0; padding_len as usize]);\n\n}\n", "file_path": "elfen/src/elf.rs", "rank": 9, "score": 228514.40608285688 }, ...
Rust
yash-semantics/src/lib.rs
magicant/yash-rs
c80497794c126f3d0c378df8a625c69bee0f8567
pub mod assign; mod command_impl; pub mod command_search; pub mod expansion; mod handle_impl; pub mod redir; mod runner; pub mod trap; use annotate_snippets::display_list::DisplayList; use annotate_snippets::snippet::Snippet; use async_trait::async_trait; use std::borrow::Cow; use yash_env::io::Fd; use yash_env::Env...
pub mod assign; mod command_impl; pub mod command_search; pub mod expansion; mod handle_impl; pub mod redir; mod runner; pub mod trap; use annotate_snippets::display_list::DisplayList; use annotate_snippets::snippet::Snippet; use async_trait::async_trait; use std::borrow::Cow; use yash_env::io::Fd; use yash_env::Env...
fn cat_builtin_main( env: &mut Env, _args: Vec<Field>, ) -> Pin<Box<dyn Future<Output = yash_env::builtin::Result> + '_>> { async fn inner(env: &mut Env) -> std::result::Result<(), Errno> { let mut buffer = [0; 1024]; loop { let count = env.syste...
pub fn echo_builtin() -> Builtin { Builtin { r#type: Intrinsic, execute: echo_builtin_main, } }
function_block-full_function
[ { "content": "/// Implementation of the return built-in.\n\n///\n\n/// See the [module-level documentation](self) for details.\n\npub fn builtin_main_sync<E: Env>(_env: &mut E, args: Vec<Field>) -> Result {\n\n // TODO Parse arguments correctly\n\n // TODO Reject returning from an interactive session\n\n ...
Rust
src/lib.rs
ordovicia/mix-distribution
eb87605c4dd005f5f49ad2b1a6de18bed1a5b51c
use std::{fmt, marker::PhantomData, ops::AddAssign}; use rand::Rng; use rand_distr::{ uniform::{SampleBorrow, SampleUniform}, weighted::{WeightedError, WeightedIndex}, Distribution, }; pub struct Mix<T, U, X> where T: Distribution<U>, X: SampleUniform + PartialOrd, { distributions: Vec<T>, ...
use std::{fmt, marker::PhantomData, ops::AddAssign}; use rand::Rng; use rand_distr::{ uniform::{SampleBorrow, SampleUniform}, weighted::{WeightedError, WeightedIndex}, Distribution, }; pub struct Mix<T, U, X> where T: Distribution<U>, X: SampleUniform + PartialOrd, { distributions: Vec<T>, ...
} #[test] fn test_mix_2() { let mut rng = rand::thread_rng(); let mix = { let dists = vec![Uniform::new_inclusive(0, 0), Uniform::new_inclusive(1, 1)]; let weights = &[2, 1]; M...
lot() { let mut rng = rand::thread_rng(); let mix = { let dists = vec![ Normal::new(0.0, 1.0).unwrap(), Normal::new(5.0, 2.0).unwrap(), ]; let weights = &[2, 1]; Mix::new(dists, weights).unwrap() }; for _ i...
function_block-random_span
[ { "content": "# Mixture Distributions\n\n\n\n[![Build Status][build-img]][build-link]\n\n[![mix-distribution][cratesio-img]][cratesio-link]\n\n[![mix-distribution][docsrs-img]][docsrs-link]\n\n\n\n[build-img]: https://travis-ci.com/ordovicia/mix-distribution.svg?branch=master\n\n[build-link]: https://travis-ci....
Rust
lib/src/schema.rs
joepio/atomic
10b1e390d807b3defe0ce0f993b160b4ade46359
use crate::{datatype::DataType, errors::AtomicResult, urls, Resource, Value}; use serde::{Deserialize, Serialize}; #[derive(Clone, Debug, Serialize, Deserialize)] pub struct Property { pub class_type: Option<String>, pub data_type: DataType, pub shortname: String, pub subject: String, p...
use crate::{datatype::DataType, errors::AtomicResult, urls, Resource, Value}; use serde::{Deserialize, Serialize}; #[derive(Clone, Debug, Serialize, Deserialize)] pub struct Property { pub class_type: Option<String>, pub data_type: DataType, pub shortname: String, pub subject: String, p...
Ok(resource) } }
if !self.requires.is_empty() { resource.set_propval_unsafe( urls::RECOMMENDS.into(), Value::ResourceArray(self.recommends.clone()), )?; }
if_condition
[ { "content": "/// Check if something is a URL\n\npub fn is_url(string: &str) -> bool {\n\n // TODO: Probably delete this second one, might break some tests though.\n\n string.starts_with(\"http\") || string.starts_with(\"_:\")\n\n}\n\n\n\nimpl IntoIterator for Mapping {\n\n type Item = (String, String)...
Rust
2019/intcode.rs
yishn/adventofcode2016
4aa4d7c36921f88fbfc617293372b3b814fd9912
#[derive(Clone)] pub struct ProgramState(Vec<i64>, usize, usize); impl ProgramState { pub fn new(program: Vec<i64>) -> ProgramState { ProgramState(program, 0, 0) } pub fn get_mut(&mut self) -> (&mut Vec<i64>, &mut usize, &mut usize) { (&mut self.0, &mut self.1, &mut self.2) } } #[derive(...
#[derive(Clone)] pub struct ProgramState(Vec<i64>, usize, usize); impl ProgramState { pub fn new(program: Vec<i64>) -> ProgramState { ProgramState(program, 0, 0) } pub fn get_mut(&mut self) -> (&mut Vec<i64>, &mut usize, &mut usize) { (&mut self.0, &mut self.1, &mut self.2) } } #[derive(...
pub fn run_ascii_program_with_input(state: &mut ProgramState, input: &str) -> (String, ProgramResult) { let inputs = input.chars().map(|c| c as i64); let (outputs, result) = run_program_with_inputs(state, inputs); let output = outputs.into_iter() .map(|x| x as u8 as char) .fold(String::new(), |mut ac...
function_block-full_function
[ { "content": "fn run_program(state: (&mut Vec<i64>, &mut usize, &mut usize), input: Option<i64>) -> ProgramResult {\n\n let (program, pointer, relative_base) = state;\n\n let mut input = input;\n\n\n\n fn extend_memory(program: &mut Vec<i64>, index: usize) {\n\n while index >= program.len() {\n\n pro...
Rust
src/cpu.rs
ZacJoffe/chip8-emulator
2ab341a403f204ccbf3ad8dffecaf4f1f7ae0c75
extern crate rand; use rand::Rng; use crate::keypad::Keypad; use crate::graphics::Graphics; pub struct Cpu { i: u16, v: [u8; 16], pc: u16, sp: u16, stack: [u16; 16], mem: [u8; 4096], sound_timer: u8, delay_timer: u8, opcode: u16, pub key: Keypad, pub graphics: Graphics } ...
extern crate rand; use rand::Rng; use crate::keypad::Keypad; use crate::graphics::Graphics; pub struct Cpu { i: u16, v: [u8; 16], pc: u16, sp: u16, stack: [u16; 16], mem: [u8; 4096], sound_timer: u8, delay_timer: u8, opcode: u16, pub key: Keypad, pub graphics: Graphics } ...
for i in 0..80 { cpu.mem[0x50 + i] = FONTSET[i]; } cpu } pub fn load_game(&mut self, game: Vec<u8>) { let mut data = Vec::new(); for byte in game { data.push(byte); } for (i, &byte) in data.iter().enumer...
let mut cpu = Cpu { i: 0x200, v: [0; 16], pc: 0x200, sp: 0, stack: [0; 16], mem: [0; 4096], sound_timer: 0, delay_timer: 0, opcode: 0, key: Keypad::new(), graphics: Graphics::new() ...
assignment_statement
[ { "content": "fn main() {\n\n let mut cpu = Cpu::new();\n\n let args: Vec<String> = env::args().collect();\n\n\n\n // if no arg is given, then default to pong2.c8\n\n let mut rom = if args.len() < 2 { String::from(\"pong2.c8\") } else { String::from(&args[1]) };\n\n rom = format!(\"roms/{}\", ro...
Rust
src/timers.rs
david-sawatzke/swm050-hal
95cec73c1b15475ded314bd4ed1f517085838f9a
use core::ops::Deref; use embedded_hal::timer::{Cancel, CountDown, Periodic}; use void::Void; use crate::delay::Delay; use crate::syscon::{ClockEnable, Clocks, Syscon}; use crate::time::Hertz; pub(crate) type TimerRegisterBlock = swm050::tmrse0::RegisterBlock; pub struct Timer<TIMER> { clocks: Clocks, pub(cr...
use core::ops::Deref; use embedded_hal::timer::{Cancel, CountDown, Periodic}; use void::Void; use crate::delay::Delay; use crate::syscon::{ClockEnable, Clocks, Syscon}; use crate::time::Hertz; pub(crate) type TimerRegisterBlock = swm050::tmrse0::RegisterBlock; pub struct Timer<TIMER> { clocks: Clocks, pub(cr...
pub fn release(self) -> TIMER { self.timer } } impl<TIMER> CountDown for Timer<TIMER> where TIMER: Deref<Target = TimerRegisterBlock>, { type Time = Hertz; fn start<T>(&mut self, timeout: T) where T: Into<Hertz>, { self.timer.ctrl.write(|w| w.ena().c...
timer.intctrl.write(|w| w.ena().set_bit()); let mut timer = Timer { timer: timer, clocks: syscon.clocks, }; timer.start(timeout); timer }
function_block-function_prefix_line
[ { "content": "pub trait ClockEnable {\n\n fn enable(syscon: &mut Syscon);\n\n}\n\nmacro_rules! clock_enable {\n\n ($PERIPH: ident, $field:ident) => {\n\n impl ClockEnable for swm050::$PERIPH {\n\n fn enable(syscon: &mut Syscon) {\n\n syscon.regs.pclk_en.modify(|_, w| w.$fi...
Rust
Chapter07/users-pool/src/main.rs
dominicbachmann/Hands-On-Microservices-with-Rust
6ca0a00ac8d8bf9123ce4eab2092b57408d8ed1c
use clap::{ crate_authors, crate_description, crate_name, crate_version, App, AppSettings, Arg, SubCommand, }; use postgres::{Connection, Error}; use r2d2_postgres::{TlsMode, PostgresConnectionManager}; use rayon::prelude::*; use serde_derive::Deserialize; use std::io; fn create_table(conn: &Connection) -> Result<...
use clap::{ crate_authors, crate_description, crate_name, crate_version, App, AppSettings, Arg, SubCommand, }; use postgres::{Connection, Error}; use r2d2_postgres::{TlsMode, PostgresConnectionManager}; use rayon::prelude::*; use serde_derive::Deserialize; use std::io; fn create_table(conn: &Connection) -> Result<...
#[derive(Deserialize, Debug)] struct User { name: String, email: String, } const CMD_CREATE: &str = "create"; const CMD_ADD: &str = "add"; const CMD_LIST: &str = "list"; const CMD_IMPORT: &str = "import"; fn main() -> Result<(), failure::Error> { let matches = App::new(crate_name!()) .version(c...
fn list_users(conn: &Connection) -> Result<Vec<User>, Error> { let res = conn.query("SELECT name, email FROM users", &[])?.into_iter() .map(|row| { User { name: row.get(0), email: row.get(1), } }) .collect(); Ok(res) }
function_block-full_function
[ { "content": "fn create_user(conn: &Connection, name: &str, email: &str) -> Result<(), Error> {\n\n conn.execute(\"INSERT INTO users (name, email) VALUES ($1, $2)\",\n\n &[&name, &email])\n\n .map(drop)\n\n}\n\n\n", "file_path": "Chapter07/users/src/main.rs", "rank": 0, "sc...
Rust
src/main.rs
Steve-xmh/netease-music-tui
7b2c1f07cd679e1d44d8ea61640e37f97b0ce96e
#[macro_use] extern crate lazy_static; #[macro_use] extern crate failure; extern crate config; extern crate serde_derive; extern crate serde_json; #[macro_use] extern crate log; extern crate log_panics; use crossterm::event::{EnableMouseCapture, KeyCode, KeyEvent, KeyModifiers}; use crossterm::terminal::enable_raw_mo...
#[macro_use] extern crate lazy_static; #[macro_use] extern crate failure; extern crate config; extern crate serde_derive; extern crate serde_json; #[macro_use] extern crate log; extern crate log_panics; use crossterm::event::{EnableMouseCapture, KeyCode, KeyEvent, KeyModifiers}; use crossterm::terminal::enable_raw_mo...
ui::draw_main_layout(&mut f, &mut app); } } })?; match dbus_mpris.next() { Ok(cmd) => { dbus_mpris_handler(cmd, &mut app); } Err(_) => {} } match events.next()? { Event::Input(input) =>...
function_block-function_prefix_line
[ { "content": "pub fn handler(key: KeyEvent, app: &mut App) {\n\n match key {\n\n k if common_events::left_event(k) => common_events::handle_left_event(app),\n\n KeyEvent {\n\n code: KeyCode::Enter,\n\n modifiers: KeyModifiers::NONE,\n\n } => {\n\n let cur...
Rust
src/main.rs
samhamnam/conways_game_of_crabs
1c8afc822ea1c432c9c3ee281380d524ed71199a
use pixels::{Error, Pixels, SurfaceTexture}; use rand::prelude::*; use winit::{ dpi::LogicalSize, event::{Event, WindowEvent}, event_loop::{ControlFlow, EventLoop}, window::WindowBuilder, }; fn main() -> Result<(), Error> { println!("Random start: {}", random::<i32>()); let width = 400; let...
use pixels::{Error, Pixels, SurfaceTexture}; use rand::prelude::*; use winit::{ dpi::LogicalSize, event::{Event, WindowEvent}, event_loop::{ControlFlow, EventLoop}, window::WindowBuilder, }; fn main() -> Result<(), Error> { println!("Random start: {}", random::<i32>()); let width = 400; let...
pub struct World { clear_color: [u8; 4], width: u32, height: u32, crabs: Vec<bool>, crab_buffer: Vec<bool>, crab_color: [u8; 4], } impl World { pub fn new(clear_color: [u8; 4], crab_color: [u8; 4], width: u32, height: u32) -> Self { let w = width as usize; let h = height a...
s") .with_inner_size(size) .with_min_inner_size(size) .with_resizable(false) .build(&event_loop) .unwrap() }; let mut pixels = { let window_size = window.inner_size(); let surface_texture = SurfaceTexture::new(window_size.width, window...
function_block-function_prefixed
[]
Rust
xngin-compute/src/cmp.rs
jiangzhe/xngin
57f3e2070a3bf52dbfda28750038302e330eca12
use crate::error::{Error, Result}; use crate::BinaryEval; use xngin_datatype::PreciseType; use xngin_expr::PredFuncKind; use xngin_storage::attr::Attr; use xngin_storage::bitmap::Bitmap; use xngin_storage::codec::{Codec, Single}; use xngin_storage::repr::ByteRepr; use xngin_storage::sel::Sel; #[derive(Debug, Clone, Co...
use crate::error::{Error, Result}; use crate::BinaryEval; use xngin_datatype::PreciseType; use xngin_expr::PredFuncKind; use xngin_storage::attr::Attr; use xngin_storage::bitmap::Bitmap; use xngin_storage::codec::{Codec, Single}; use xngin_storage::repr::ByteRepr; use xngin_storage::sel::Sel; #[derive(Debug, Clone, Co...
}
let (valid, value) = res.bool_at(50).unwrap(); assert!(valid && value); let res = gt.eval(&c1, &c3, Some(&Sel::None(64))).unwrap(); assert_eq!(PreciseType::bool(), res.ty); let res = gt .eval(&c4, &c1, Some(&Sel::new_indexes(64, vec![1, 50]))) .unwrap(); ...
function_block-function_prefix_line
[ { "content": "pub trait DataSourceID: Clone + Copy + PartialEq + Eq + Hash + PartialOrd + Ord + Sized {\n\n /// resolve data source from expression\n\n fn from_expr(e: &Expr) -> Option<(Self, u32)>;\n\n}\n\n\n\nimpl DataSourceID for QueryID {\n\n #[inline]\n\n fn from_expr(e: &Expr) -> Option<(Self,...
Rust
lib/bobbin-sys/src/system.rs
thomasantony/bobbin-sdk
37375ca40351352a029aceb8b0cf17650a3624f6
use core::ops::{Deref, DerefMut}; use bobbin_mcu::mcu::Mcu; use heap::Heap; use tick::Tick; use pend::Pend; use irq_dispatch::IrqDispatcher; use console::Console; struct SystemToken; static mut SYSTEM_TOKEN: Option<SystemToken> = Some(SystemToken); pub trait SystemProvider { type Mcu: Mcu; type Clk; ...
use core::ops::{Deref, DerefMut}; use bobbin_mcu::mcu::Mcu; use heap::Heap; use tick::Tick; use pend::Pend; use irq_dispatch::IrqDispatcher; use console::Console; struct SystemToken; static mut SYSTEM_TOKEN: Option<SystemToken> = Some(SystemToken); pub trait SystemProvider { type Mcu: Mcu; type Clk; ...
pub fn release(system: Self) { let System { provider, mcu, clk, heap, tick, pend, dispatcher, _private } = system; let _ = provider; let _ = mcu; let _ = clk; Tick::release(tick); Pend::release(pend); Heap::release(heap); IrqDispatcher::...
k, heap, tick, pend, dispatcher, _private: (), } }
function_block-function_prefixed
[ { "content": "pub fn run_with_sys<S: SystemProvider>(mut sys: System<S>) -> ! {\n\n let ticker = Ticker::<S::Mcu>::new();\n\n let pender = Pender::new();\n\n\n\n let _guard_tick = match sys.tick_mut().register(&ticker) {\n\n Ok(guard) => guard,\n\n Err(_) => {\n\n println!(\"Er...
Rust
src/mesh.rs
littleTitan/3d-engine
81009f8949edd809815270f77eb5ed482da17243
use crate::{triangle::Triangle, vec3d::Vec3d}; use byteorder::{LittleEndian, ReadBytesExt}; use std::{ fs::{self, File}, io::prelude::*, }; #[derive(Clone)] pub struct Mesh { pub tris: Vec<Triangle>, pub is_over: bool, pub is_held: bool, pub pos: Vec3d, } impl Mesh { ...
use crate::{triangle::Triangle, vec3d::Vec3d}; use byteorder::{LittleEndian, ReadBytesExt}; use std::{ fs::{self, File}, io::prelude::*, }; #[derive(Clone)] pub struct Mesh { pub tris: Vec<Triangle>, pub is_over: bool, pub is_held: bool, pub pos: Vec3d, } impl Mesh { ...
.expect("Something went wrong reading the file"); let _contents = String::from_utf8_lossy(&header_buf[..header]); let mut n_tris_buf = [0; 4]; let n_tris_raw = file .read(&mut n_tris_buf[..]) .expect("Something went wrong reading the file"); ...
e.next(); self.tris.push(Triangle::new( points[e.next().unwrap().parse::<usize>().unwrap() - 1_usize], points[e.next().unwrap().parse::<usize>().unwrap() - 1_usize], points[e.next().unwrap().parse::<usize>().unwrap() - 1_usize], ...
random
[ { "content": "use ggez::{self, graphics::Vertex, nalgebra as na, nalgebra::geometry::Point2};\n\n\n\nuse std::ops::{Add, AddAssign, Mul, Sub};\n\n\n\n/// A Vec3d is a point in 3D space\n\n#[derive(Copy, Clone)]\n\npub struct Vec3d {\n\n pub x: f32,\n\n pub y: f32,\n\n pub z: f32,\n\n}\n\n\n\nimpl Vec3d...
Rust
api/src/services/item.rs
sanpii/oxfeed
a8d79bdd115b903bdb05ec475ef4fbc9c1b01108
use actix_web::web::{Data, Json, Path}; use oxfeed_common::item::Model; use std::collections::HashMap; pub(crate) fn scope() -> actix_web::Scope { actix_web::web::scope("/items") .service(content) .service(favorites) .service(patch) .service(unread) .service(read_all) ...
use actix_web::web::{Data, Json, Path}; use oxfeed_common::item::Model; use std::collections::HashMap; pub(crate) fn scope() -> actix_web::Scope { actix_web::web::scope("/items") .service(content) .service(favorites) .service(patch) .service(unread) .service(read_all) ...
pub(crate) fn fetch( elephantry: &elephantry::Pool, identity: &crate::Identity, filter: &elephantry::Where, pagination: &oxfeed_common::Pagination, ) -> oxfeed_common::Result<actix_web::HttpResponse> { let token = identity.token(&elephantry)?; let model = elephantry.model::<Model>(); let ...
async fn unread( elephantry: Data<elephantry::Pool>, pagination: actix_web::web::Query<oxfeed_common::Pagination>, identity: crate::Identity, ) -> oxfeed_common::Result<actix_web::HttpResponse> { fetch( &elephantry, &identity, &elephantry::Where::from("not read", Vec::new()), ...
function_block-full_function
[ { "content": "fn path(url: &str) -> std::path::PathBuf {\n\n let digest = ring::digest::digest(&ring::digest::SHA256, url.as_bytes());\n\n\n\n let mut path = digest\n\n .as_ref()\n\n .chunks(4)\n\n .map(|x| {\n\n x.iter()\n\n .fold(String::new(), |acc, b| for...
Rust
src/types/metadata.rs
Techcable/steven
2e99712cc8b467a236a8be57e6e43c888ba602e9
use std::collections::HashMap; use std::marker::PhantomData; use std::io; use std::fmt; use protocol; use protocol::Serializable; use format; use item; use shared::Position; pub struct MetadataKey<T: MetaValue> { index: i32, ty: PhantomData<T>, } impl <T: MetaValue> MetadataKey<T> { #[allow(dead_code)] ...
use std::collections::HashMap; use std::marker::PhantomData; use std::io; use std::fmt; use protocol; use protocol::Serializable; use format; use item; use shared::Position; pub struct MetadataKey<T: MetaValue> { index: i32, ty: PhantomData<T>, } impl <T: MetaValue> MetadataKey<T> { #[allow(dead_code)] ...
fn wrap(self) -> Value { Value::OptionalUUID(self) } } impl MetaValue for u16 { fn unwrap(value: &Value) -> &Self { match *value { Value::Block(ref val) => val, _ => panic!("incorrect key"), } } fn wrap(self) -> Value { Value::Block(self) ...
f { match *value { Value::OptionalUUID(ref val) => val, _ => panic!("incorrect key"), } }
function_block-function_prefixed
[ { "content": "pub fn read_string<R: io::Read>(buf: &mut R) -> Result<String, protocol::Error> {\n\n let len: i16 = try!(buf.read_i16::<BigEndian>());\n\n let mut ret = String::new();\n\n try!(buf.take(len as u64).read_to_string(&mut ret));\n\n Result::Ok(ret)\n\n}\n", "file_path": "src/nbt/mod.r...
Rust
src/tests.rs
ecstatic-morse/hrtb-logic
579b811bbdaf240e6439238d34dcd37454369a33
use insta::assert_display_snapshot; use crate::{short::*, Formula, Var}; macro_rules! vars { ($($x:ident),*) => { $( const $x: Var = var(stringify!($x).as_bytes()[0] as char); )* } } macro_rules! props { ($($x:ident),*) => { $( const $x: Formula = prop(stringify!($x)); )* } } vars!(A...
use insta::assert_display_snapshot; use crate::{short::*, Formula, Var}; macro_rules! vars { ($($x:ident),*) => { $( const $x: Var = var(stringify!($x).as_bytes()[0] as char); )* } } macro_rules! props { ($($x:ident),*) => { $( const $x: Formula = prop(stringify!($x)); )* } } vars!(A...
#[test] fn qe_atomless() { let _ = Y; let dnf = Formula::disjunctive_normal_form; let qe = |mut f: Formula| { f.eliminate_all_quantifiers(); f.simplify(); f.make_negation_normal_form(); f }; assert_display_snapshot!(qe(forall(B, subeq(B, A))), @"False"); ...
m(false); assert_display_snapshot!(simp(and(top(), top())), @"True"); assert_display_snapshot!(simp(and(top(), bot())), @"False"); assert_display_snapshot!(simp(or(bot(), bot())), @"False"); assert_display_snapshot!(simp(or(top(), bot())), @"True"); }
function_block-function_prefixed
[ { "content": "pub fn exists(var: Var, form: Formula) -> Formula {\n\n Formula::Bind(QuantifierKind::Exists, var, P::new(form))\n\n}\n\n\n\npub const fn subeq(sub: Var, sup: Var) -> Formula {\n\n Formula::SubsetEq { sub, sup }\n\n}\n\n\n", "file_path": "src/short.rs", "rank": 0, "score": 94200....
Rust
src/util.rs
lovesh/pixel-signature
93102638c2e4e35f4c136fddbcb18c8abc923ebd
use crate::amcl_wrapper::group_elem::GroupElement; use crate::errors::PixelError; use amcl_wrapper::field_elem::FieldElement; use crate::{VerkeyGroup, SignatureGroup}; pub struct GeneratorSet(pub VerkeyGroup, pub Vec<SignatureGroup>); impl GeneratorSet { pub fn new(T: u128, prefix: &str) -> Result<Self, PixelErro...
use crate::amcl_wrapper::group_elem::GroupElement; use crate::errors::PixelError; use amcl_wrapper::field_elem::FieldElement; use crate::{VerkeyGroup, SignatureGroup}; pub struct GeneratorSet(pub VerkeyGroup, pub Vec<SignatureGroup>); impl GeneratorSet { pub fn new(T: u128, prefix: &str) -> Result<Self, PixelErro...
#[cfg(test)] mod tests { use super::*; use std::collections::HashSet; use std::iter::FromIterator; #[test] fn test_calculate_l() { assert!(calculate_l(u128::max_value()).is_err()); let valid_Ts: HashSet<u128> = HashSet::from_iter(vec![3, 7, 15, 31, 63].iter().cloned()); ...
pub fn calculate_path_factor(path: Vec<u8>, gens: &GeneratorSet) -> Result<SignatureGroup, PixelError> { if gens.1.len() < (path.len() + 2) { return Err(PixelError::NotEnoughGenerators { n: path.len() + 2 }); } let mut sigma_1_1 = gens.1[1].clone(); for (i, p) in path.iter().enumera...
function_block-full_function
[ { "content": "#[cfg(feature = \"VerkeyG1\")]\n\npub fn ate_multi_pairing(elems: Vec<(&SignatureGroup, &VerkeyGroup)>) -> GT {\n\n GT::ate_multi_pairing(\n\n elems\n\n .into_iter()\n\n .map(|(s, v)| (v, s))\n\n .collect::<Vec<(&VerkeyGroup, &SignatureGroup)>>(),\n\n ...
Rust
src/distance_.rs
huonw/hamming
4b528d75cfa2e102b6edc6c60b629cd986215437
fn naive(x: &[u8], y: &[u8]) -> u64 { assert_eq!(x.len(), y.len()); x.iter().zip(y).fold(0, |a, (b, c)| a + (*b ^ *c).count_ones() as u64) } #[derive(Debug, PartialEq, Eq, Ord, PartialOrd, Hash, Clone)] pub struct DistanceError { _x: () } pub fn distance_fast(x: &[u8], y: &[u8]) -> Result<u64, DistanceErr...
fn naive(x: &[u8], y: &[u8]) -> u64 { assert_eq!(x.len(), y.len()); x.iter().zip(y).fold(0, |a, (b, c)| a + (*b ^ *c).count_ones() as u64) } #[derive(Debug, PartialEq, Eq, Ord, PartialOrd, Hash, Clone)] pub struct DistanceError { _x: () } pub fn distance_fast(x: &[u8], y: &[u8]) -> Result<u64, DistanceErr...
qc::QuickCheck::new() .gen(qc::StdGen::new(rand::thread_rng(), 10_000)) .quickcheck(prop as fn(Vec<u8>,Vec<u8>,u8) -> qc::TestResult) } #[test] fn distance_fast_smoke_huge() { let v = vec![0b1001_1101; 10234567]; let w = vec![0b1111_1111; v.len()]; a...
let l = ::std::cmp::min(v.len(), w.len()); if l < misalign as usize { return qc::TestResult::discard() } let x = &v[misalign as usize..l]; let y = &w[misalign as usize..l]; qc::TestResult::from_bool(super::distance_fast(x, y).unwrap() == super...
function_block-function_prefix_line
[ { "content": "/// Computes the [Hamming\n\n/// weight](https://en.wikipedia.org/wiki/Hamming_weight) of `x`, that\n\n/// is, the population count, or number of 1.\n\n///\n\n/// This is a highly optimised version of the following naive version:\n\n///\n\n/// ```rust\n\n/// fn naive(x: &[u8]) -> u64 {\n\n/// ...
Rust
indy-credx/src/error.rs
animo/indy-shared-rs
063f7de369da0c3032225283773edf816a3eac21
use std::error::Error as StdError; use std::fmt::{self, Display, Formatter}; use std::result::Result as StdResult; use crate::ursa::errors::{UrsaCryptoError, UrsaCryptoErrorKind}; pub type Result<T> = std::result::Result<T, Error>; #[derive(Clone, Copy, Debug, PartialEq, Eq)] pub enum ErrorKind { Input, ...
use std::error::Error as StdError; use std::fmt::{self, Display, Formatter}; use std::result::Result as StdResult; use crate::ursa::errors::{UrsaCryptoError, UrsaCryptoErrorKind}; pub type Result<T> = std::result::Result<T, Error>; #[derive(Clone, Copy, Debug, PartialEq, Eq)] pub enum ErrorKind { Input, ...
} } impl Display for ErrorKind { fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result { f.write_str(self.as_str()) } } #[derive(Debug)] pub struct Error { kind: ErrorKind, pub cause: Option<Box<dyn StdError + Send + Sync + 'static>>, pub message: Option<String>, } impl Error { ...
match self { Self::Input => "Input error", Self::IOError => "IO error", Self::InvalidState => "Invalid state", Self::Unexpected => "Unexpected error", Self::CredentialRevoked => "Credential revoked", Self::InvalidUserRevocId => "Invalid revocation ...
if_condition
[ { "content": "pub fn set_last_error(error: Option<Error>) -> ErrorCode {\n\n trace!(\"credx_set_last_error\");\n\n let code = match error.as_ref() {\n\n Some(err) => err.kind().into(),\n\n None => ErrorCode::Success,\n\n };\n\n *LAST_ERROR.write().unwrap() = error;\n\n code\n\n}\n",...
Rust
rewryte-generator/src/sqlite.rs
Txuritan/rewryte
3ddcd0d8b374cbb8c895fe0282c828490641c5f6
use { crate::Error, rewryte_parser::models::{Column, ColumnDefault, Enum, ForeignKey, Item, Schema, Table, Types}, std::io, }; pub fn write_schema(schema: &Schema, writer: &mut impl io::Write) -> Result<(), Error> { for (i, item) in schema.items.iter().enumerate() { write_item(item, writer)?; ...
use { crate::Error, rewryte_parser::models::{Column, ColumnDefault, Enum, ForeignKey, Item, Schema, Table, Types}, std::io, }; pub fn write_schema(schema: &Schema, writer: &mut impl io::Write) -> Result<(), Error> { for (i, item) in schema.items.iter().enumerate() { write_item(item, writer)?; ...
pub fn write_enum(_decl: &Enum, _writer: &mut impl io::Write) -> Result<(), Error> { Ok(()) } pub fn write_table(decl: &Table, writer: &mut impl io::Write) -> Result<(), Error> { write!(writer, "CREATE TABLE")?; if decl.not_exists { write!(writer, " IF NOT EXISTS")?; } write!(write...
pub fn write_item(item: &Item, writer: &mut impl io::Write) -> Result<(), Error> { match &item { Item::Enum(decl) => write_enum(decl, writer)?, Item::Table(decl) => write_table(decl, writer)?, } Ok(()) }
function_block-full_function
[ { "content": "pub fn write_item(item: &Item, writer: &mut impl io::Write) -> Result<(), Error> {\n\n match &item {\n\n Item::Enum(decl) => write_enum(decl, writer)?,\n\n Item::Table(decl) => write_table(decl, writer)?,\n\n }\n\n\n\n Ok(())\n\n}\n\n\n", "file_path": "rewryte-generator/...
Rust
src/serde/ser/from_seq/header.rs
snaar/chopper
62a0305233f16b5001b433c8ef83844f12794173
use serde::ser::{Impossible, SerializeSeq, SerializeStruct, SerializeTuple, SerializeTupleStruct}; use serde::{Serialize, Serializer}; use crate::chopper::types::{FieldType, Header}; use crate::serde::ser::error::SerError; use crate::serde::ser::field_type::to_field_type; pub fn to_header<T>(value: &T, timestamp_fiel...
use serde::ser::{Impossible, SerializeSeq, SerializeStruct, SerializeTuple, SerializeTupleStruct}; use serde::{Serialize, Serializer}; use crate::chopper::types::{FieldType, Header}; use crate::serde::ser::error::SerError; use crate::serde::ser::field_type::to_field_type; pub fn to_header<T>(value: &T, timestamp_fiel...
_index)) } pub struct HeaderSerializer { timestamp_field_index: usize, field_types: Vec<FieldType>, } impl HeaderSerializer { pub fn new(timestamp_field_index: usize) -> HeaderSerializer { HeaderSerializer { timestamp_field_index, field_types: Vec::new(), } } ...
index: usize) -> Result<Header, SerError> where T: Serialize + ?Sized, { value.serialize(HeaderSerializer::new(timestamp_field
function_block-random_span
[]
Rust
tests/functional.rs
pwalski/tchannel_rs
17169ae7d689f255c26be985589867a60045d724
#[cfg(test)] #[macro_use] extern crate log; #[macro_use] extern crate serial_test; use std::sync::Arc; use bytes::Bytes; use test_case::test_case; use tchannel_rs::handler::{HandlerResult, RequestHandler}; use tchannel_rs::messages::MessageChannel; use tchannel_rs::messages::RawMessage; use tchannel_rs::Config; use ...
#[cfg(test)] #[macro_use] extern crate log; #[macro_use] extern crate serial_test; use std::sync::Arc; use bytes::Bytes; use test_case::test_case; use tchannel_rs::handler::{HandlerResult, RequestHandler}; use tchannel_rs::messages::MessageChannel; use tchannel_rs::messages::RawMessage; use tchannel_rs::Config; use ...
async fn make_request<STR: AsRef<str>>(service: STR, req: RawMessage) -> HandlerResult<RawMessage> { debug!("Outgoing arg2/header len {}", &req.header().len()); let client = TChannel::new(Config::default())?; let subchannel = client.subchannel(service).await?; subchannel.send(req, LOCAL_SERVER).await ...
async fn start_echo_server<STR: AsRef<str>>(service: STR, endpoint: STR) -> TResult<TChannel> { let server = TChannel::new(Config::default())?; let subchannel = server.subchannel(&service).await?; subchannel.register(&endpoint, EchoHandler {}).await?; server.start_server()?; Ok(server) }
function_block-full_function
[ { "content": "fn encode_small_string<STR: AsRef<str>>(value: STR, dst: &mut BytesMut) -> CodecResult<()> {\n\n encode_string_field(value, dst, &BytesMut::put_u8)\n\n}\n\n\n", "file_path": "src/frames/payloads.rs", "rank": 0, "score": 163112.80213647935 }, { "content": "fn encode_string_fi...
Rust
src/shell/history/entry.rs
doy/nbsh
4151ab7aab939a12721a0f4207c87b5c09ace339
use crate::shell::prelude::*; pub struct Entry { cmdline: String, env: Env, pty: super::pty::Pty, fullscreen: Option<bool>, start_instant: std::time::Instant, start_time: time::OffsetDateTime, state: State, } impl Entry { pub fn new( cmdline: String, env: Env, s...
use crate::shell::prelude::*; pub struct Entry { cmdline: String, env: Env, pty: super::pty::Pty, fullscreen: Option<bool>, start_instant: std::time::Instant, start_time: time::OffsetDateTime, state: State, } impl Entry { pub fn new( cmdline: String, env: Env, s...
pub fn should_fullscreen(&self) -> bool { self.fullscreen.unwrap_or_else(|| self.pty.fullscreen()) } pub fn lock_vt(&self) -> std::sync::MutexGuard<super::pty::Vt> { self.pty.lock_vt() } pub fn set_span(&mut self, new_span: (usize, usize)) { if let State::Running(ref mut ...
pub fn lines(&self, entry_count: usize, focused: bool) -> usize { let running = self.running(); 1 + std::cmp::min( self.pty.with_vt(|vt| vt.output_lines(focused, running)), self.max_lines(entry_count), ) }
function_block-full_function
[ { "content": "#[allow(clippy::unnecessary_wraps)]\n\npub fn time(offset: time::UtcOffset) -> Result<String> {\n\n Ok(crate::format::time(\n\n time::OffsetDateTime::now_utc().to_offset(offset),\n\n ))\n\n}\n\n\n", "file_path": "src/info.rs", "rank": 0, "score": 243241.07392747345 }, ...
Rust
code_analysis/rust_parser/src/generics.rs
LucaCappelletti94/EnsmallenGraph
572532b6d3f4352bf58f9ccca955376acd95fd89
use super::*; #[derive(Debug, Clone, PartialEq)] pub enum GenericValue{ Type(Type), Lifetime(Lifetime), TypeAssignement(Type, Type), TypeInheritance(Type, Type), } impl Parse for GenericValue { fn parse(mut data: &[u8]) -> (&[u8], Self) { if data.starts_with(b"'") { let res = G...
use super::*; #[derive(Debug, Clone, PartialEq)] pub enum GenericValue{ Type(Type), Lifetime(Lifetime), TypeAssignement(Type, Type), TypeInheritance(Type, Type), } impl Parse for GenericValue { fn parse(mut data: &[u8]) -> (&[u8], Self) { if data.starts_with(b"'") { let res = G...
} #[derive(Debug, Clone, PartialEq)] pub struct Generics(pub Vec<GenericValue>); impl std::ops::Index<usize> for Generics { type Output = GenericValue; fn index(&self, index: usize) -> &Self::Output { &self.0[index] } } impl CanParse for Generics { fn can_parse(mut data: &[u8]) -> bool { ...
fn from(x: GenericValue) -> String { match x { GenericValue::Lifetime(lt) => { format!("'{}", lt.0) } GenericValue::Type(t) => { String::from(t) } GenericValue::TypeAssignement(t1, t2) => { format!("{} = ...
function_block-full_function
[]
Rust
crates/shell/build.rs
BSFishy/carton
0edcde473e381d526eecb6777d20349ff751b7d3
#![allow(clippy::if_same_then_else)] use std::env; use std::path::PathBuf; macro_rules! cargo { ($value:expr) => { println!("cargo:{}", $value) } } macro_rules! warning { ($message:expr) => { cargo!(format!("warning={}", $message)); }; ($message:expr $(, $extra:expr)*) => { ...
#![allow(clippy::if_same_then_else)] use std::env; use std::path::PathBuf; macro_rules! cargo { ($value:expr) => { println!("cargo:{}", $value) } } macro_rules! warning { ($message:expr) => { cargo!(format!("warning={}", $message)); }; ($message:expr $(, $extra:expr)*) => { ...
let bindings = bindings .generate() .expect("Unable to generate bindings"); let out_path = PathBuf::from(env::var("OUT_DIR").unwrap()); bindings .write_to_file(out_path.join("bindings.rs")) .expect("Couldn't write bindings!"); } fn add_platforms(pla...
if platform == Platform::Wayland { bindings = bindings .blacklist_item("FP_NAN") .blacklist_item("FP_INFINITE") .blacklist_item("FP_ZERO") .blacklist_item("FP_SUBNORMAL") .blacklist_item("FP_NORMAL"); }
if_condition
[]
Rust
src/data.rs
Tenebryo/file-system-stats
9a8d02e8782bb0a3be4d7bfbb2b81ba642986050
/* Copyright 2021 Sam Blazes Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in wri...
/* Copyright 2021 Sam Blazes Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in wri...
pub fn sort_subtree_by_size(i : usize, entries : &mut [Entry]) { for c in entries[i].children.clone() { sort_subtree_by_size(c, entries); } let mut j = i; while entries[j].parent < entries.len() { let mut children = entries[j].children.clone(); children.sort_by_cached_key(|&...
pub fn delete_subtree(entries : &mut Vec<Entry>, subtree : usize) { let mut new_idx = entries.iter().map(|_| usize::MAX).collect::<Vec<_>>(); let mut next_i = 0; for i in 0..(entries.len()) { let parent = entries[i].parent; if parent == subtree || i == subtree { entries[i].paren...
function_block-full_function
[ { "content": "/// Build ui elements\n\nfn display_file_tree(display_entries : &mut Vec<Entry>, ui : &Ui) {\n\n \n\n let cw = ui.window_content_region_width();\n\n\n\n #[derive(Debug, Clone, Copy, Default)]\n\n struct DrawParams {\n\n psize : u64,\n\n content_width : f32,\n\n }\n\n\n...
Rust
src/connectivity/overnet/lib/core/src/fidl_tests/mod.rs
casey/fuchsia
2b965e9a1e8f2ea346db540f3611a5be16bb4d6b
#![cfg(test)] use crate::future_help::log_errors; use crate::link::Link; use crate::router::test_util::{run, test_router_options}; use crate::router::Router; use crate::runtime::spawn; use fidl::HandleBased; use fuchsia_zircon_status as zx_status; use futures::prelude::*; use std::rc::Rc; mod channel; mod socket; ...
#![cfg(test)] use crate::future_help::log_errors; use crate::link::Link; use crate::router::test_util::{run, test_router_options}; use crate::router::Router; use crate::runtime::spawn; use fidl::HandleBased; use fuchsia_zircon_status as zx_status; use futures::prelude::*; use std::rc::Rc; mod channel; mod socket; ...
} impl Drop for Fixture { fn drop(&mut self) { self.tx_fin.take().unwrap().send(()).unwrap(); } }
fn distribute_handle<H: HandleBased>(&self, h: H, target: Target) -> H { let h = h.into_handle(); log::trace!("distribute_handle: make {:?} on {:?}", h, target); let (dist_local, dist_remote) = match target { Target::A => return H::from_handle(h), Target::B => (&self.dist...
function_block-full_function
[]
Rust
src/tasks/git.rs
jokeyrhyme/dotfiles-rs
8e723ee271675ba783e15e608164813a4a136efb
use std::{collections::HashMap, fs, str}; use serde_derive::Deserialize; use crate::{ lib::task::{self, Status, Task}, utils, }; const COMMAND_DELIMITERS: &[char] = &[';', '|', '&']; const ERROR_MSG: &str = "error: git"; pub fn task() -> Task { Task { name: String::from("git"), sync, ...
use std::{collections::HashMap, fs, str}; use serde_derive::Deserialize; use crate::{ lib::task::{self, Status, Task}, utils, }; const COMMAND_DELIMITERS: &[char] = &[';', '|', '&']; const ERROR_MSG: &str = "error: git"; pub fn task() -> Task { Task { name: String::from("git"), sync, ...
fn sync() -> task::Result { if !utils::git::has() { return Ok(Status::Skipped); } let cfg = Config::from(load_config()); for (key, ce) in cfg.config { let cce = match ce { ConfigEntry::Basic(s) => ComplexConfigEntry::from(s), ConfigEntry::Complex(c) => c, ...
fn extract_commands<S>(s: S) -> Vec<String> where S: AsRef<str>, { s.as_ref() .split(|c: char| COMMAND_DELIMITERS.contains(&c)) .filter_map(|s| match s.trim().split(' ').next() { Some("") => None, Some(s) => Some(String::from(s)), None => None, }) ...
function_block-full_function
[ { "content": "pub fn latest_version() -> Result<String, task::Error> {\n\n let tags: Vec<utils::github::Tag> = utils::github::fetch_tags(\"golang\", \"go\")?;\n\n let release_tags: Vec<utils::github::Tag> = tags\n\n .into_iter()\n\n .filter(|t| {\n\n // release tags look like \"go...
Rust
src/db/raw.rs
wrenger/schiller-lib
fd1e45797f602db7ec037a6892b6d1bff26d287f
use std::collections::HashMap; pub trait DatabaseExt { fn fetch(&self, statement: &str) -> Result<Vec<Vec<String>>, sqlite::Error>; fn transaction(&self) -> Result<Transaction, sqlite::Error>; } impl DatabaseExt for sqlite::Connection { fn fetch(&self, statement: &str) -> Result<Vec<Vec<String>>, sql...
use std::collections::HashMap; pub trait DatabaseExt { fn fetch(&self, statement: &str) -> Result<Vec<Vec<String>>, sqlite::Error>; fn transaction(&self) -> Result<Transaction, sqlite::Error>; } impl DatabaseExt for sqlite::Connection {
fn transaction(&self) -> Result<Transaction, sqlite::Error> { self.execute("begin")?; Ok(Transaction { db: self }) } } pub struct Transaction<'a> { db: &'a sqlite::Connection, } impl<'a> Transaction<'a> { pub fn commit(self) -> Result<(), sqlite::Error> { self.db.execute("com...
fn fetch(&self, statement: &str) -> Result<Vec<Vec<String>>, sqlite::Error> { let mut result = vec![]; self.iterate(statement, |pairs| { result.push( pairs .iter() .map(|&(_, value)| value.unwrap_or_default().into()) ...
function_block-full_function
[ { "content": "/// MARC21 Parsing\n\n///\n\n/// ## See Also\n\n/// https://www.dnb.de/EN/Professionell/Metadatendienste/Datenbezug/SRU/sru_node.html\n\npub fn parse(response: &str, isbn: &str) -> api::Result<BookData> {\n\n let document = roxmltree::Document::parse(response)?;\n\n\n\n let mut first_result ...
Rust
webnis-server/src/webnis.rs
EwoutH/webnis
078814931bd5dab47eebe0c21d32d3045a4d6040
use std::collections::HashMap; use std::sync::Arc; use actix_web::http::StatusCode; use actix_web::HttpResponse; use serde_json; use crate::config; use crate::db; use crate::db::MapType; use crate::errors::WnError; use crate::format; use crate::iplist::IpList; use crate::lua; use crate::util::*; #[derive(Clone)] pub...
use std::collections::HashMap; use std::sync::Arc; use actix_web::http::StatusCode; use actix_web::HttpResponse; use serde_json; use crate::config; use crate::db; use crate::db::MapType; use crate::errors::WnError; use crate::format; use crate::iplist::IpList; use crate::lua; use crate::util::*; #[derive(Clone)] pub...
pub fn handle_auth(&self, domain: String, is_json: bool, body: Vec<u8>) -> HttpResponse { let domain = match self.inner.config.find_domain(&domain) { None => return json_error(StatusCode::BAD_REQUEST, None, "Domain not found"), Some(d) => d, }; ...
pub fn handle_info(&self, domain: &str) -> HttpResponse { let domain = match self.inner.config.find_domain(domain) { None => return json_error(StatusCode::BAD_REQUEST, None, "Domain not found"), Some(d) => d, }; let mut maps = HashMap::new(); fo...
function_block-full_function
[ { "content": "// Read the TOML config into a config::Condig struct.\n\npub fn read(toml_file: impl AsRef<Path>) -> io::Result<Config> {\n\n let buffer = std::fs::read_to_string(&toml_file)?;\n\n\n\n // initial parse.\n\n let mut config: Config = match toml::from_str(&buffer) {\n\n Ok(v) => Ok(v)...
Rust
src/api.rs
IslandUsurper/mailchimp-rs
cfa26fffbe925df6b0878ea55bf4284097cc699f
use crate::internal::api::Api; use crate::internal::error_type::MailchimpErrorType; use crate::internal::request::MailchimpRequest; use crate::types::Ping; use serde::de::DeserializeOwned; use serde::ser::Serialize; use std::collections::HashMap; use std::rc::Rc; #[derive(Debug, Clone)] pub struct MailchimpApi { i...
use crate::internal::api::Api; use crate::internal::error_type::MailchimpErrorType; use crate::internal::request::MailchimpRequest; use crate::types::Ping; use serde::de::DeserializeOwned; use serde::ser::Serialize; use std::collections::HashMap; use std::rc::Rc; #[derive(Debug, Clone)] pub struct MailchimpApi { i...
MailchimpRequest>::new( "", "", Box::new(MailchimpRequest::new()), )), } } } pub trait MailchimpApiUpdate { /** * Update API */ fn set_api(&mut self, api: Rc<MailchimpApi>); }
)) } } impl Default for MailchimpApi { fn default() -> Self { MailchimpApi { i_api: Box::new(Api::<
random
[ { "content": "///\n\n/// ====================================================================\n\n///\n\n///\n\nfn connect_mqtt<'a>(host: &'a str, user_name: &'a str, password: &'a str) -> mqtt::Client {\n\n let endpoint = String::from(\"tcp://\") + host;\n\n let create_options = mqtt::CreateOptionsBuilder...
Rust
grader/src/submission/mod.rs
programming-in-th/rusty-grader
7538071915566577692cafc36ba7dadcc983654c
use crate::errors::{GraderError, GraderResult}; use crate::instance; use crate::instance::{Instance, RunVerdict}; use crate::submission::result::*; use crate::utils::{get_base_path, get_code_extension, get_env, get_message}; use manifest::Manifest; use std::{fs, io::Write, path::Path, path::PathBuf, process::Command}; ...
use crate::errors::{GraderError, GraderResult}; use crate::instance; use crate::instance::{Instance, RunVerdict}; use crate::submission::result::*; use crate::utils::{get_base_path, get_code_extension, get_env, get_message}; use manifest::Manifest; use std::{fs, io::Write, path::Path, path::PathBuf, process::Command}; ...
pub fn run(&mut self) -> GraderResult<SubmissionResult> { let checker = self.task_manifest .checker .as_ref() .map_or(self.task_path.join("checker"), |file| { get_base_path() .join("scripts") ...
fn run_each(&mut self, checker: &Path, runner: &Path, index: u64) -> GraderResult<RunResult> { if let Some(message_handler) = &mut self.message_handler { message_handler(SubmissionMessage::Status(SubmissionStatus::Running(index))) } let input_path = self .task_path ...
function_block-full_function
[ { "content": "pub fn get_code_extension(language: &str) -> String {\n\n let config = load_yaml(get_base_path().join(\"scripts\").join(\"config.yaml\"));\n\n\n\n for lang in yaml_unwrap_hash(config, \"language\")\n\n .unwrap()\n\n .into_vec()\n\n .unwrap()\n\n {\n\n if Some(l...
Rust
api/swim_form_derive/src/structural/mod.rs
swimos/swim-rust
f1a2be7bb4eb8f38e6ecc19bba4a8c876016183c
use crate::structural::model::enumeration::{EnumDef, EnumModel, SegregatedEnumModel}; use crate::structural::model::record::{SegregatedStructModel, StructDef, StructModel}; use crate::structural::model::StructLike; use crate::structural::model::ValidateFrom; use crate::structural::read::DeriveStructuralReadable; use ...
use crate::structural::model::enumeration::{EnumDef, EnumModel, SegregatedEnumModel}; use crate::structural::model::record::{SegregatedStructModel, StructDef, StructModel}; use crate::structural::model::StructLike; use crate::structural::model::ValidateFrom; use crate::structural::read::DeriveStructuralReadable; use ...
nerics, generics: &mut Generics, bound: syn::TraitBound) { let bounds = original.type_params().map(|param| { let id = &param.ident; parse_quote!(#id: #bound) }); let where_clause = generics.make_where_clause(); for bound in bounds.into_iter() { where_clause.predicates.push(bound)...
:validate(input).into_result()?; let segregated = SegregatedStructModel::from(&model); let derive = DeriveStructuralReadable(segregated, generics); Ok(derive.into_token_stream()) } fn enum_derive_structural_readable( input: EnumDef<'_>, generics: &Generics, ) -> Result<TokenStream, Errors<syn::Erro...
random
[ { "content": "fn recognize_item(input: ReadEvent<'_>) -> ItemEvent {\n\n match input {\n\n ReadEvent::Extant => ItemEvent::Primitive(Value::Extant),\n\n ReadEvent::Number(NumericValue::Int(n)) => {\n\n ItemEvent::Primitive(if let Ok(m) = i32::try_from(n) {\n\n Value::I...
Rust
src/sys/component_manager/src/vmex.rs
winksaville/Fuchsia
a0ec86f1d51ae8d2538ff3404dad46eb302f9b4f
use { crate::{ capability::*, model::{error::*, hooks::*}, }, cm_rust::CapabilityPath, failure::Error, fidl::endpoints::ServerEnd, fidl_fuchsia_boot as fboot, fidl_fuchsia_security_resource as fsec, fuchsia_async as fasync, fuchsia_component::client::connect_to_service, ...
use { crate::{ capability::*, model::{error::*, hooks::*}, }, cm_rust::CapabilityPath, failure::Error, fidl::endpoints::ServerEnd, fidl_fuchsia_boot as fboot, fidl_fuchsia_security_resource as fsec, fuchsia_async as fasync, fuchsia_component::client::connect_to_service, ...
| panic!("Error while serving vmex service: {}", e)), ); Ok(proxy) } #[fasync::run_singlethreaded(test)] async fn fail_with_no_root_resource() -> Result<(), Error> { if root_resource_available() { return Ok(()); } let (_, stream) = fidl::endpoints::create...
= connect_to_service::<fboot::RootResourceMarker>()?; let root_resource = root_resource_provider.get().await?; while let Some(fsec::VmexRequest::Get { responder }) = stream.try_next().await? { let vmex_handle = root_resource.create_child(zx::ResourceKind::VMEX, None, 0, 0, ...
random
[]
Rust
src/bin/upgrade/main.rs
thiagoarrais/cargo-edit
265ddb082c0f490a12d9dfb254195717b2ba8d51
#![warn( missing_docs, missing_debug_implementations, missing_copy_implementations, trivial_casts, trivial_numeric_casts, unsafe_code, unstable_features, unused_import_braces, unused_qualifications )] #[macro_use] extern crate error_chain; use crate::errors::*; use cargo_edit::{fi...
#![warn( missing_docs, missing_debug_implementations, missing_copy_implementations, trivial_casts, trivial_numeric_casts, unsafe_code, unstable_features, unused_import_braces, unused_qualifications )] #[macro_use] extern crate error_chain; use crate::errors::*; use cargo_edit::{fi...
Ok(DesiredUpgrades(if only_update.is_empty() { self.0 .iter() .flat_map(|&(_, ref package)| package.dependencies.clone()) .filter(is_version_dep) .map(|dependency| (dependency.name, None)) .co...
fn is_version_dep(dependency: &cargo_metadata::Dependency) -> bool { match dependency.source { Some(ref s) => s.splitn(2, '+').next() == Some("registry"), _ => false, } }
function_block-full_function
[ { "content": "fn get_name_from_manifest(manifest: &Manifest) -> Result<String> {\n\n manifest\n\n .data\n\n .as_table()\n\n .get(\"package\")\n\n .and_then(|m| m[\"name\"].as_str().map(std::string::ToString::to_string))\n\n .ok_or_else(|| ErrorKind::ParseCargoToml.into())\n...
Rust
rpg-cli/src/main.rs
Jomy10/rpg-lang
e7f283633ff5931fe4aef27bdabf4e794a840369
use std::{env, fs}; use std::path::Path; use std::process::Command; use std::time::Duration; use clap::{App, arg}; use directories_next::ProjectDirs; use rpg_compiler::{Config}; use rpg_compiler::user_output::CompileError; use simple_colors::{blue, green}; use spinner::{SpinnerHandle, SpinnerBuilder}; use spinners::uti...
use std::{env, fs}; use std::path::Path; use std::process::Command; use std::time::Duration; use clap::{App, arg}; use directories_next::ProjectDirs; use rpg_compiler::{Config}; use rpg_compiler::user_output::CompileError; use simple_colors::{blue, green}; use spinner::{SpinnerHandle, SpinnerBuilder}; use spinners::uti...
let data_dir = dir.data_dir(); let matches = App::new("RPG Compiler") .version("0.1.0") .author("Jonas Everaert <info@jonaseveraert.be>") .about("The official compiler for the RPG esoteric programming language") .arg(arg!([file] "The .rpg source file you wish to compile")) ...
let dir = ProjectDirs::from("be", "jonaseveraert", "rpgc").expect("No valid home directory path could be retrieved from the operating system");
assignment_statement
[ { "content": "pub fn compile(file: &str) -> String {\n\n let sp = ColoredSpinner::new(\"Reading input...\".to_string());\n\n let code = fs::read_to_string(file).expect_compile_error(&format!(\"{file} could not be found.\"));\n\n let code = rm_comments(&code);\n\n let code = code.trim();\n\n sp.st...
Rust
ignition-host/src/process/pipe.rs
mvanbem/ignition
d22dffd786ff10f69ffa5f8d36cd46fd06288e00
use std::ptr::copy_nonoverlapping; use std::sync::{Arc, Mutex}; use std::task::Poll; use replace_with::{replace_with_or_abort, replace_with_or_abort_and_return}; use tokio::sync::mpsc::UnboundedSender; use crate::{TaskId, WakeParams}; struct SendPointer<T>(*const T); unsafe impl<T> Send for SendPointer<T> {} struc...
use std::ptr::copy_nonoverlapping; use std::sync::{Arc, Mutex}; use std::task::Poll; use replace_with::{replace_with_or_abort, replace_with_or_abort_and_return}; use tokio::sync::mpsc::UnboundedSender; use crate::{TaskId, WakeParams}; struct SendPointer<T>(*const T); unsafe impl<T> Send for SendPointer<T> {} struc...
pub fn close(&self) { self.inner.lock().unwrap().close(); } } impl PipeWriter { pub unsafe fn write( &self, write_wake_queue_sender: &UnboundedSender<WakeParams>, write_task_id: TaskId, src: *const u8, src_len: u32, ) -> Poll<u32> { if src_len =...
PipeState::PendingRead { .. } => { todo!("read with a read already pending") } PipeState::PendingWrite { write_wake_queue_sender, write_task_id, src, src_len, } => { ...
function_block-function_prefix_line
[ { "content": "#[doc(hidden)]\n\npub fn wake_internal(task_id: u32, param: usize, init: fn()) {\n\n if task_id == u32::MAX {\n\n init();\n\n } else {\n\n dispatch_wake(TaskId(task_id), param);\n\n }\n\n run();\n\n}\n\n\n\n// TODO: Expand this into a fancy proc macro, something like #[ig...
Rust
src/krull64.rs
SamiPerttu/rand_krull
1b613461fb08329588506efaf091206492ae9726
#[cfg(feature = "serde")] use serde::{Deserialize, Serialize}; use wrapping_arithmetic::wrappit; #[cfg_attr(feature = "serde", derive(Serialize, Deserialize))] #[derive(Clone, Eq, PartialEq, Debug)] pub struct Krull64 { lcg0: u64, lcg1: u64, stream: u64, } #[inline] fn origin_0(stream: u64)...
#[cfg(feature = "serde")] use serde::{Deserialize, Serialize}; use wrapping_arithmetic::wrappit; #[cfg_attr(feature = "serde", derive(Serialize, Deserialize))] #[derive(Clone, Eq, PartialEq, Debug)] pub struct Krull64 { lcg0: u64, lcg1: u64, stream: u64, } #[inline] fn origin_0(stream: u64)...
pub fn from_128(seed: u128) -> Self { let mut krull = Krull64::from_64(((seed >> 64) ^ seed) as u64); krull.set_position((seed as u128) << 64); krull } pub fn jump(&mut self, steps: i128) { let lcg = crate::lcg::get_state( ...
pub fn from_64(seed: u64) -> Self { Krull64 { lcg0: origin_0(seed), lcg1: 0, stream: seed, } }
function_block-full_function
[ { "content": "#[inline]\n\nfn origin_b_128() -> u128 {\n\n origin_b0() as u128\n\n}\n\n\n\nimpl Krull65 {\n\n #[inline]\n\n fn multiplier_a(&self) -> u64 {\n\n super::LCG_M65_1 as u64\n\n }\n\n\n\n #[inline]\n\n fn multiplier_a_128(&self) -> u128 {\n\n super::LCG_M65_1\n\n }\n...
Rust
compiler/src/parser/mod.rs
dvberkel/bergen
81aeb2347655590ba01f1fe813a926a3ec8d26de
use super::brnfck::Command; const NEWLINE: u8 = 10u8; pub fn parse(source: &[u8]) -> Result<Vec<Command>, ParseError> { rows(source).and_then(|(top, middle, bottom)| { if top.len() != middle.len() || middle.len() != bottom.len() { return Err(ParseError::DifferentNumberOfRows); } ...
use super::brnfck::Command; const NEWLINE: u8 = 10u8; pub fn parse(source: &[u8]) -> Result<Vec<Command>, ParseError> { rows(source).and_then(|(top, middle, bottom)| { if top.len() != middle.len() || middle.len() != bottom.len() { return Err(ParseError::DifferentNumberOfRows); } ...
#[test] fn should_parse_increment() { let source: &[u8] = " \n /\\ \n/ \\\n".as_bytes(); if let Ok(instructions) = parse(source) { assert_eq!(instructions.len(), 1); assert_eq!(instructions, vec![Command::Increment]) } else { assert!(false); ...
if let Ok(instructions) = parse(source) { assert_eq!(instructions.len(), 1); assert_eq!(instructions, vec![Command::DecrementPointer]) } else { assert!(false); } }
function_block-function_prefix_line
[ { "content": "pub fn program_from(characters: &[u8]) -> Vec<Command> {\n\n let mut program = Vec::new();\n\n let mut index = 0;\n\n let mut last_character = 0;\n\n while index < characters.len() {\n\n let mut difference = characters[index] as i16 - last_character as i16;\n\n let comman...
Rust
impl/rust/lisla_lang/src/tree/mod.rs
shohei909/Lisla
9267d0792d6d4f633dec1c079d2a39bc5e4719c1
use tag::*; use std::fmt::Debug; use from::error::*; use from::*; use ::error::*; use leaf::*; #[derive(Debug, Clone, Eq, PartialEq)] pub enum ArrayTree<LeafType:Leaf> { Array(ArrayBranch<WithTag<ArrayTree<LeafType>>>), Leaf(LeafType), } impl FromArrayTree for ArrayTree<StringLeaf> { type ...
use tag::*; use std::fmt::Debug; use from::error::*; use from::*; use ::error::*; use leaf::*; #[derive(Debug, Clone, Eq, PartialEq)] pub enum ArrayTree<LeafType:Leaf> { Array(ArrayBranch<WithTag<ArrayTree<LeafType>>>), Leaf(LeafType), } impl FromArrayTree for ArrayTree<StringLeaf> { type ...
errors.push(FromArrayTreeError::from(NotEnoughArgumentsError{ range })); Result::Err(()) } else { Result::Ok( Self { vec: self.vec.split_off(len) } ) } } pub fn split_off_rest( &mut self, config: &FromA...
ayTree<LeafType> { fn from(data:ArrayBranch<WithTag<ArrayTree<LeafType>>>) -> Self { ArrayTree::Array(data) } } impl<LeafType:Leaf> ArrayTree<LeafType> { pub fn to_branch(self) -> Option<ArrayBranch<WithTag<ArrayTree<LeafType>>>> { match self { ArrayTree::Array(branch) ...
random
[ { "content": "pub trait Leaf : Debug + Clone + Eq + PartialEq {\n\n}\n", "file_path": "impl/rust/lisla_lang/src/leaf/mod.rs", "rank": 0, "score": 241863.12455578276 }, { "content": "pub fn equals(lisla: &WithTag<ArrayTree<StringLeaf>>, json: &Value, path: &str, stack: &mut Vec<usize>) {\n\n ...
Rust
sulis_state/src/animation/ranged_attack_animation.rs
ThyWoof/sulis
e89eda94a1a72228224e1926d307aa4c9228bdcb
use std::cell::RefCell; use std::rc::Rc; use crate::{animation::Anim, entity_attack_handler::weapon_attack, AreaFeedbackText}; use crate::{script::ScriptEntitySet, EntityState, GameState, ScriptCallback}; use sulis_core::image::Image; use sulis_core::io::{DrawList, GraphicsRenderer}; use sulis_core::ui::animation_st...
use std::cell::RefCell; use std::rc::Rc; use crate::{animation::Anim, entity_attack_handler::weapon_attack, AreaFeedbackText}; use crate::{script::ScriptEntitySet, EntityState, GameState, ScriptCallback}; use sulis_core::image::Image; use sulis_core::io::{DrawList, GraphicsRenderer}; use sulis_core::ui::animation_st...
} pub(in crate::animation) fn draw( model: &RangedAttackAnimModel, renderer: &mut dyn GraphicsRenderer, offset: Offset, scale: Scale, millis: u32, ) { if let Some(ref projectile) = model.projectile { let rect = Rect { x: model.cur_pos.0 + offset.x, y: model.cur_...
if !GameState::is_combat_active() { let area_state = GameState::get_area_state(&owner.borrow().location.area_id).unwrap(); let mgr = GameState::turn_manager(); mgr.borrow_mut() .check_ai_activation(owner, &mut area_state.borrow_mut()); }
if_condition
[]
Rust
rs/crypto/internal/crypto_service_provider/src/server/local_csp_server/basic_sig/tests.rs
LaudateCorpus1/ic
e05b8568bcef4147b5999d2c489f875afde2f8bb
use crate::api::CspSigner; use crate::imported_test_utils::ed25519::csp_testvec; use crate::secret_key_store::test_utils::TempSecretKeyStore; use crate::secret_key_store::SecretKeyStore; use crate::server::api::{ BasicSignatureCspServer, CspBasicSignatureError, CspBasicSignatureKeygenError, }; use crate::server::l...
use crate::api::CspSigner; use crate::imported_test_utils::ed25519::csp_testvec; use crate::secret_key_store::test_utils::TempSecretKeyStore; use crate::secret_key_store::SecretKeyStore; use crate::server::api::{ BasicSignatureCspServer, CspBasicSignatureError, CspBasicSignatureKeygenError, }; use crate::server::l...
#[test] fn should_fail_to_generate_key_for_wrong_algorithm_id() { let csp_server = { let key_store = TempSecretKeyStore::new(); let csprng = ChaChaRng::from_seed(thread_rng().gen::<[u8; 32]>()); LocalCspServer::new_for_test(csprng, key_store) }; for algorithm_id in AlgorithmId::it...
fn should_generate_key_ok() { let csp_server = { let key_store = TempSecretKeyStore::new(); let csprng = ChaChaRng::from_seed(thread_rng().gen::<[u8; 32]>()); LocalCspServer::new_for_test(csprng, key_store) }; assert!(csp_server.gen_key_pair(AlgorithmId::Ed25519).is_ok()); }
function_block-full_function
[ { "content": "/// Generate a random `IDkgId`.\n\n///\n\n/// Note: There is a proptest strategy for `IDkgId` which is useful in many\n\n/// circumstances but cumbersome in others. Please use the appropriate method\n\n/// for each circumstance.\n\npub fn random_dkg_id<R: Rng>(rng: &mut R) -> IDkgId {\n\n let ...
Rust
src/sim/render/lighting.rs
FreddyWordingham/arctk
05842d8a5842653179acaaf2a7de843ed9293b82
use crate::{ geom::Ray, math::{rand_circle_point, rand_hemisphere_point, Dir3}, phys::Crossing, sim::render::{Attribute, Input}, }; use rand::{rngs::ThreadRng, Rng}; use std::f64::consts::PI; #[inline] #[must_use] pub fn light(input: &Input, ray: &Ray, norm: &Dir3) -> f64 { let light_dir = Dir3::...
use crate::{ geom::Ray, math::{rand_circle_point, rand_hemisphere_point, Dir3}, phys::Crossing, sim::render::{Attribute, Input}, }; use rand::{rngs::ThreadRng, Rng}; use std::f64::consts::PI; #[inline] #[must_use] pub fn light(input: &Input, ray: &Ray, norm: &Dir3) -> f64 { let light_dir = Dir3::...
#[inline] #[must_use] pub fn shadow(input: &Input, rng: &mut ThreadRng, ray: &Ray, norm: &Dir3) -> f64 { let bump_dist = input.sett.bump_dist(); let sun_dir = Dir3::new_normalize(input.shader.sun_pos() - ray.pos()); let mut light_ray = Ray::new(*ray.pos(), *norm); light_ray.travel(bump_dist); *li...
diffuse *= norm.dot(&light_dir); specular *= view_dir .dot(&ref_dir) .max(0.0) .powi(input.shader.spec_pow()); ambient + diffuse + specular }
function_block-function_prefix_line
[ { "content": "#[inline]\n\n#[must_use]\n\npub fn sample_normal<R: Rng>(rng: &mut R) -> f64 {\n\n let a = (-2.0 * rng.gen_range(0.0_f64..1.0).ln()).sqrt();\n\n let theta = rng.gen_range(0.0..(2.0 * PI));\n\n\n\n // Z = Some(a * theta.sin()); // Using mutable static will lead to data race; we waste the t...
Rust
pseudos/src/main.rs
yokljo/pseudos
a16a66bd4a0edc48100e3d5e285ef897b8699375
use std::cmp::Ordering; use libpseudos::dos_event_handler::{DosEventHandler, DosInterruptResult, KeyModType, KeyPressInfo, MachineType, PortStates}; use libpseudos::dos_file_system::StandardDosFileSystem; use libpseudos::exe_loader::MzHeader; use xachtsechs::machine8086::Machine8086; use xachtsechs::types::{Reg, RegHa...
use std::cmp::Ordering; use libpseudos::dos_event_handler::{DosEventHandler, DosInterruptResult, KeyModType, KeyPressInfo, MachineType, PortStates}; use libpseudos::dos_file_system::StandardDosFileSystem; use libpseudos::exe_loader::MzHeader; use xachtsechs::machine8086::Machine8086; use xachtsechs::types::{Reg, RegHa...
} } } fn update_keymod(&mut self, keymod: sdl2::keyboard::Mod) { self.dos_event_handler.set_key_mod(KeyModType::Shift, keymod.contains(sdl2::keyboard::LSHIFTMOD) || keymod.contains(sdl2::keyboard::RSHIFTMOD)); self.dos_event_handler.set_key_mod(KeyModType::Ctrl, keymod.contains(sdl2::keyboard::LCTRLMOD) |...
if !blinking || self.current_run_time_ms % 450 < 225 { dosfont_tex.set_color_mod(fore_rgb.0, fore_rgb.1, fore_rgb.2); canvas.copy(&dosfont_tex, Some(char_rect), Some(dest_rect)).expect("Render failed"); }
if_condition
[ { "content": "// http://www.bioscentral.com/misc/bda.htm\n\npub fn initialise_bios_data_area(machine: &mut Machine8086) {\n\n\t// The BIOS Data Area starts at the start of the 0x40 segment.\n\n\t// Equipment\n\n\tmachine.set_data_u16(&BIOS_EQUIPMENT, 0x0061);\n\n\t// Memory size in KB\n\n\tmachine.set_data_u16(...
Rust
src/lib.rs
cdisselkoen/llvm-ir-analysis
f690c660070fe881a33d055cd30d5f4c352c69f5
mod call_graph; mod control_dep_graph; mod control_flow_graph; mod dominator_tree; mod functions_by_type; pub use crate::call_graph::CallGraph; pub use crate::control_dep_graph::ControlDependenceGraph; pub use crate::control_flow_graph::{CFGNode, ControlFlowGraph}; pub use crate::dominator_tree::{DominatorTree, Post...
mod call_graph; mod control_dep_graph; mod control_flow_graph; mod dominator_tree; mod functions_by_type; pub use crate::call_graph::CallGraph; pub use crate::control_dep_graph::ControlDependenceGraph; pub use crate::control_flow_graph::{CFGNode, ControlFlowGraph}; pub use crate::dominator_tree::{DominatorTree, Post...
pub fn functions_by_type(&self) -> Ref<FunctionsByType<'m>> { self.functions_by_type.get_or_insert_with(|| { debug!("computing single-module functions-by-type"); FunctionsByType::new(std::iter::once(self.module)) }) } pub fn fn_analysis<'s>...
pub fn call_graph(&self) -> Ref<CallGraph<'m>> { self.call_graph.get_or_insert_with(|| { let functions_by_type = self.functions_by_type(); debug!("computing single-module call graph"); CallGraph::new(std::iter::once(self.module), &functions_by_type) }) }
function_block-full_function
[ { "content": "pub fn may_panic(a: i32) -> i32 {\n\n if a > 2 {\n\n panic!(\"a > 2\");\n\n } else {\n\n return 1;\n\n }\n\n}\n", "file_path": "tests/bcfiles/panic.rs", "rank": 0, "score": 69531.15541423167 }, { "content": "#[test]\n\nfn call_graph() {\n\n init_loggin...
Rust
thcon/src/app/konsole.rs
theme-controller/thcon
646b8dac38994acff31cd90aae6fafa80bad168a
use crate::config::Config as ThconConfig; use crate::operation::Operation; use crate::AppConfig; use crate::Disableable; use crate::{ themeable::{ConfigError, ConfigState}, Themeable, }; use std::time::Duration; use anyhow::{Context, Result}; use dbus::blocking::Connection; use log::{debug, trace}; use serd...
use crate::config::Config as ThconConfig; use crate::operation::Operation; use crate::AppConfig; use crate::Disableable; use crate::{ themeable::{ConfigError, ConfigState}, Themeable, }; use std::time::Duration; use anyhow::{Context, Result}; use dbus::blocking::Connection; use log::{debug, trace}; use serd...
fn set_profile_name( &self, service_id: &str, session_id: &str, profile_name: &str, ) -> Result<()> { let proxy = self.dbus.with_proxy( service_id, format!("/Sessions/{}", session_id), Duration::from_millis(2500), ); l...
fn get_session_ids(&self, service_id: &str) -> Result<Vec<String>> { let proxy = self .dbus .with_proxy(service_id, "/Sessions", Duration::from_millis(2500)); let (xml,): (String,) = proxy .method_call("org.freedesktop.DBus.Introspectable", "Introspect", ()) ...
function_block-full_function
[ { "content": "pub fn get(name: &str) -> Option<Box<dyn Themeable>> {\n\n match name {\n\n #[cfg(dbus)]\n\n \"konsole\" => Some(Box::new(Konsole::default())),\n\n #[cfg(dbus)]\n\n \"gnome-shell\" => Some(Box::new(GnomeShell {})),\n\n #[cfg(dbus)]\n\n \"gnome-terminal\...
Rust
src/kvm.rs
yodalee/rrxv6
bf3b076b28e8fbb5de00e63748b5e27a829d6634
use lazy_static::lazy_static; use spin::Mutex; use rv64::csr::satp::{Satp, SatpMode}; use rv64::asm::sfence_vma; use crate::vm::page_table::{PageTable, PageTableLevel}; use crate::vm::addr::{VirtAddr, PhysAddr}; use crate::vm::page_flag::PteFlag; use crate::riscv::{PAGESIZE, MAXVA}; use crate::memorylayout::{UART0, PL...
use lazy_static::lazy_static; use spin::Mutex; use rv64::csr::satp::{Satp, SatpMode}; use rv64::asm::sfence_vma; use crate::vm::page_table::{PageTable, PageTableLevel}; use crate::vm::addr::{VirtAddr, PhysAddr}; use crate::vm::page_flag::PteFlag; use crate::riscv::{PAGESIZE, MAXVA}; use crate::memorylayout::{UART0, PL...
if ptr == 0 as *mut u8 { return Err("kalloc failed in map_page"); } let addr = PhysAddr::new(ptr as *const _ as u64); pte.set_addr(addr.as_pte(), PteFlag::PTE_VALID); } let next_table = unsafe { &mut *(pte.addr() as *mut PageTab...
function_block-function_prefix_line
[ { "content": "/// Allocate one 4096-byte page of physical memory.\n\n/// Returns a pointer that the kernel can use.\n\n/// Returns 0 if the memory cannot be allocated.\n\npub fn kalloc() -> *mut u8 {\n\n unsafe {\n\n let layout = Layout::from_size_align(PAGESIZE as usize, 4096).unwrap();\n\n le...
Rust
src/lib.rs
duallsistemas/libduallnet
e7dd019c8fa2d98d1ecb41e28bd1b68c5ad880ae
#[cfg(target_os = "windows")] extern crate winapi; use std::io::{Error, ErrorKind}; use std::net::{SocketAddr, TcpStream, ToSocketAddrs}; use std::time::Duration; #[cfg(target_os = "windows")] use winapi::shared::minwindef::DWORD; #[cfg(target_os = "windows")] use winapi::shared::winerror::{WSAEAFNOSUPPORT, WSAETIMED...
#[cfg(target_os = "windows")] extern crate winapi; use std::io::{Error, ErrorKind}; use std::net::{SocketAddr, TcpStream, ToSocketAddrs}; use std::time::Duration; #[cfg(target_os = "windows")] use winapi::shared::minwindef::DWORD; #[cfg(target_os = "windows")] use winapi::shared::winerror::{WSAEAFNOSUPPORT, WSAETIMED...
#[cfg(test)] mod tests { use super::*; use std::thread; #[test] fn version() { unsafe { assert_eq!( from_c_str!(dn_version()).unwrap(), env!("CARGO_PKG_VERSION") ); } } #[test] fn lookup_host() { unsafe { ...
pub unsafe extern "C" fn dn_sntp_request( addr: *const c_char, timeout: u64, timestamp: *mut i64, ) -> c_int { if timestamp.is_null() { return -1; } let sntp = SntpRequest::new(); if (timeout > 0) && !sntp.set_timeout(Duration::from_millis(timeout)).is_ok() { return -1; }...
function_block-full_function
[ { "content": " let buf = $src.to_bytes_with_nul();\n\n let mut buf_size = $size;\n\n if buf_size > buf.len() {\n\n buf_size = buf.len()\n\n }\n\n copy!(buf.as_ptr(), $dest, buf_size);\n\n };\n\n}\n\n\n\n#[doc(hidden)]\n\n#[macro_export]\n\nmacro_rules! compare {\...
Rust
src/main.rs
scru128/gen_test
3590ba236f29b8323b6b5ba93c0bcc2b703df4cf
use std::env::args; use std::io; use std::io::prelude::*; use std::time::{SystemTime, UNIX_EPOCH}; const STATS_INTERVAL: u64 = 10 * 1000; fn main() { if let Some(arg) = args().nth(1) { let usage = "Usage: any-command-that-prints-identifiers-infinitely | scru128-test"; if arg == "-h" || arg == "--h...
use std::env::args; use std::io; use std::io::prelude::*; use std::time::{SystemTime, UNIX_EPOCH}; const STATS_INTERVAL: u64 = 10 * 1000; fn main() { if let Some(arg) = args().nth(1) { let usage = "Usage: any-command-that-prints-identifiers-infinitely | scru128-test"; if arg == "-h" || arg == "--h...
timestamp: (int_value >> 80) as u64, counter_hi: ((int_value >> 56) & 0xff_ffff) as u32, counter_lo: ((int_value >> 32) & 0xff_ffff) as u32, entropy: (int_value & 0xffff_ffff) as u32, }) } } fn get_current_time() -> f64 { SystemTime::now() .duration_si...
x0b, 0x0c, 0x0d, 0x0e, 0x0f, 0x10, 0x11, 0x12, 0x13, 0x14, 0x15, 0x16, 0x17, 0x18, 0x19, 0x1a, 0x1b, 0x1c, 0x1d, 0x1e, 0x1f, 0x20, 0x21, 0x22, 0x23, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xf...
function_block-random_span
[ { "content": "# SCRU128 Generator Tester\n\n\n\n[![GitHub tag](https://img.shields.io/github/v/tag/scru128/gen_test)](https://github.com/scru128/gen_test)\n\n[![License](https://img.shields.io/github/license/scru128/gen_test)](https://github.com/scru128/gen_test/blob/main/LICENSE)\n\n\n\nA command-line SCRU128 ...
Rust
src/runner.rs
sile/hone
460e0bd51455fa479e8487fb54d6f9ba8d9a8cf3
use self::command::CommandRunner; use self::tempdir::TempDirs; use crate::event::{Event, EventReader, EventWriter}; use crate::metric::MetricInstance; use crate::param::{ParamInstance, ParamValue}; use crate::rpc; use crate::study::StudySpec; use crate::trial::{Observation, ObservationId, TrialId}; use crate::tuners::{...
use self::command::CommandRunner; use self::tempdir::TempDirs; use crate::event::{Event, EventReader, EventWriter}; use crate::metric::MetricInstance; use crate::param::{ParamInstance, ParamValue}; use crate::rpc; use crate::study::StudySpec; use crate::trial::{Observation, ObservationId, TrialId}; use crate::tuners::{...
fn handle_message(&mut self, message: rpc::Message) -> anyhow::Result<()> { match message { rpc::Message::Ask { req, reply } => { let value = self.handle_ask(req)?; reply.send(value)?; } rpc::Message::Tell { req, reply } => { ...
fn handle_action(&mut self, action: Option<Action>) -> anyhow::Result<()> { match action { None => { let obs = Observation::new( self.next_obs_id.fetch_and_increment(), self.next_trial_id.fetch_and_increment(), ); ...
function_block-full_function
[ { "content": "pub trait Tune {\n\n fn ask(\n\n &mut self,\n\n obs: &Observation,\n\n param_name: &ParamName,\n\n param_type: &ParamType,\n\n ) -> anyhow::Result<ParamValue>;\n\n\n\n fn tell(&mut self, obs: &Observation) -> anyhow::Result<()>;\n\n\n\n fn next_action(&mut s...
Rust
src/component/model/mmd/mod.rs
funmaker/Project39-ar
f61334c1409eb884fab67413374d0ad8e08a6a5e
use std::cell::RefCell; use std::mem::size_of; use std::sync::Arc; use num_traits::Zero; use simba::scalar::SubsetOf; use vulkano::buffer::{BufferUsage, DeviceLocalBuffer, TypedBufferAccess}; use vulkano::command_buffer::{AutoCommandBufferBuilder, PrimaryAutoCommandBuffer}; use vulkano::descriptor_set::{Descript...
use std::cell::RefCell; use std::mem::size_of; use std::sync::Arc; use num_traits::Zero; use simba::scalar::SubsetOf; use vulkano::buffer::{BufferUsage, DeviceLocalBuffer, TypedBufferAccess}; use vulkano::command_buffer::{AutoCommandBufferBuilder, PrimaryAutoCommandBuffer}; use vulkano::descriptor_set::{Descript...
(model_matrix.clone(), Vec4::zero(), 0.0_f32)) .draw_indexed(sub_mesh.range.len() as u32, 1, sub_mesh.range.start, 0, 0)?; } for sub_mesh in self.shared.sub_meshes.iter() { i...
Graphics, pipeline.layout().clone(), 0, (self.model_set.clone(), mesh_set)) .push_constants(self.shared.sub_meshes.first().unwrap().main.0.layout().clone(), 0,
random
[ { "content": "#[allow(dead_code)]\n\npub fn test_model(renderer: &mut Renderer) -> MMDModel {\n\n\tlet mut vertices = vec![];\n\n\tlet mut indices = vec![];\n\n\tlet bones_num = 1;\n\n\tlet height = 2.0;\n\n\t\n\n\tlet mut make_wall = |from: Vec3, to: Vec3, normal: Vec3, divs: usize, bones: usize| {\n\n\t\tlet ...
Rust
codegen/src/lib.rs
Atul9/canrun_rs
4e9c4dd3ddfdcf0f5666c2122614708e14f2eaa1
extern crate proc_macro; use proc_macro::TokenStream; use quote::{format_ident, quote}; use syn::parse::{Parse, ParseStream}; use syn::punctuated::Punctuated; use syn::{parse_macro_input, Result, Token}; struct DomainDef { canrun_internal: bool, domain_visibility: syn::Visibility, domain_name: syn::Ident, ...
extern crate proc_macro; use proc_macro::TokenStream; use quote::{format_ident, quote}; use syn::parse::{Parse, ParseStream}; use syn::punctuated::Punctuated; use syn::{parse_macro_input, Result, Token}; struct DomainDef { canrun_internal: bool, domain_visibility: syn::Visibility, domain_name: syn::Ident, ...
} } impl quote::ToTokens for DomainDef { fn to_tokens(&self, tokens: &mut proc_macro2::TokenStream) { let DomainDef { canrun_internal, domain_visibility, domain_name, domain_types, } = self; let canrun_mod = if *canrun_internal { ...
Ok(DomainDef { canrun_internal: false, domain_visibility, domain_name, domain_types, })
call_expression
[ { "content": "/// Resolve one [`Val`] or return an [`Err(VarWatch)`](VarWatch) in a\n\n/// [`Constraint`].\n\npub fn resolve_1<'a, A, D>(val: &Val<A>, state: &State<'a, D>) -> Result<Rc<A>, VarWatch>\n\nwhere\n\n A: Debug,\n\n D: DomainType<'a, A>,\n\n{\n\n let a = state.resolve_val(val);\n\n match ...
Rust
src/str_utils.rs
anekos/eitaro
21b0c4355c7c994b9175e205ee9e19fb026633ab
use heck::SnakeCase; use kana::wide2ascii; use regex::Regex; #[derive(Clone, Copy)] pub enum WordType { English, Katakana, } pub fn simple_words_pattern() -> Regex { Regex::new(r"[a-zA-Z]+").unwrap() } pub fn fix_word(s: &str) -> Option<String> { let s = wide2ascii(s); let s = s.to_lowercase().r...
use heck::SnakeCase; use kana::wide2ascii; use regex::Regex; #[derive(Clone, Copy)] pub enum WordType { English, Katakana, } pub fn simple_words_pattern() -> Regex { Regex::new(r"[a-zA-Z]+").unwrap() } pub fn fix_word(s: &str) -> Option<String> { let s = wide2ascii(s); let s = s.to_lowercase().r...
sert_eq!(scan_words(Katakana, " foo-bar "), Vec::<&str>::new()); assert_eq!(scan_words(English, " f(o)o キャット bar 猫"), vec!["fo", "foo", "bar"]); } #[cfg(test)]#[test] fn test_patterns() { fn ps(s: &str) -> Vec<String> { let mut result = vec![]; extract_patterns(s, &mu...
foo キャット bar "), vec!["foo", "bar"]); assert_eq!(scan_words(English, " foo、キャット・bar=猫 "), vec!["foo", "bar"]); assert_eq!(scan_words(English, " foo-bar "), vec!["foo-bar"]); assert_eq!(scan_words(English, "【変化】動 drives | driving | drove | driven"), vec!["drives", "driving", "drove", "driven"]); asser...
random
[ { "content": "pub fn v2s(s: Vec<char>) -> String {\n\n let s: String = s.into_iter().collect();\n\n s.trim().to_owned()\n\n}\n", "file_path": "src/parser/utils.rs", "rank": 4, "score": 249985.30886171234 }, { "content": "fn extract_text(dictionary: &mut Dictionary, s: &str) -> AppResul...
Rust
src/day3.rs
arturh85/adventofcode-rust-2021
dddcdb3901fec5fce6d317c0b12ff79d44e4f3bf
use bitlab::*; #[aoc_generator(day3)] fn parse_input(input: &str) -> Vec<u32> { input .lines() .map(|line| u32::from_str_radix(line, 2).unwrap()) .collect() } #[aoc(day3, part1)] fn part1(input: &[u32]) -> u64 { gamma(input) as u64 * epsilon(input) as u64 } #[aoc(day3, part2)] fn pa...
use bitlab::*; #[aoc_generator(day3)] fn parse_input(input: &str) -> Vec<u32> { input .lines() .map(|line| u32::from_str_radix(line, 2).unwrap()) .collect() } #[aoc(day3, part1)] fn part1(input: &[u32]) -> u64 { gamma(input) as u64 * epsilon(input) as u64 } #[aoc(day3, part2)] fn pa...
#[cfg(test)] mod tests { use super::*; const EXAMPLE: &str = "00100 11110 10110 10111 10101 01111 00111 11100 10000 11001 00010 01010"; #[test] fn part1_examples() { assert_eq!(gamma(&parse_input(EXAMPLE)), 0b1_0110); assert_eq!(gamma(&parse_input(EXAMPLE)), 22); ...
fn epsilon(input: &[u32]) -> u32 { let gamma = gamma(input); let max = *input.iter().max().unwrap(); let start = significant_bitcount(max).unwrap(); let mut ret = 0; for i in start..32 { if !gamma.get_bit(i).unwrap() { ret = ret.set_bit(i).unwrap() } } ret }
function_block-full_function
[ { "content": "#[aoc(day7, part2)]\n\nfn part2(input: &[u32]) -> u32 {\n\n (0..input.len())\n\n .map(|target| fuel2(input, target as u32))\n\n .min()\n\n .unwrap()\n\n}\n\n\n", "file_path": "src/day7.rs", "rank": 2, "score": 218867.65510229085 }, { "content": "#[aoc(da...
Rust
src/rng/splitmix64simd.rs
tommyettinger/heh
a2a52c8ebd692d3e74222579f4f8ca04f4256b5d
use rand_core::{Error, RngCore, SeedableRng}; use rand_core::block::{BlockRngCore, BlockRng}; use faster::Transmute; use faster::vecs::{u64x4}; use byteorder::{LittleEndian, ByteOrder}; use super::Linnorm64; #[allow(missing_copy_implementations)] #[derive(Debug, Clone)] pub struct SplitMix64x4Core { x: u64x4, } ...
use rand_core::{Error, RngCore, SeedableRng}; use rand_core::block::{BlockRngCore, BlockRng}; use faster::Transmute; use faster::vecs::{u64x4}; use byteorder::{LittleEndian, ByteOrder}; use super::Linnorm64; #[allow(missing_copy_implementations)] #[derive(Debug, Clone)] pub struct SplitMix64x4Core { x: u64x4, } ...
z = (z ^ (z >> 30)) * A_MUL; z = (z ^ (z >> 27)) * B_MUL; z ^ (z >> 31) } #[inline] pub fn from_seed_u64(seed: u64) -> SplitMix64x4Core { let mut rng = Linnorm64::from_seed_u64(seed); SplitMix64x4Core::from_seed(SplitMix64x4Seed::from_rng(&mut rng)) } } pub struc...
pub fn next_u64x4(&mut self) -> u64x4 { const INC : u64x4 = u64x4::new(0xabdcdadb7e86b08bu64, 0x575bdce3dd69b537u64, 0x765ff07dee64eac9u64, 0x9e3779b97f4a7c15u64); const A_MUL : u64x4 = u64x4::new(0xbf58476d1ce4e5b9u64, 0xbf58476d1ce4e5b9u64, 0xbf58476d1ce4e5b9u64, 0xbf58476d1ce4e5b9u64); const ...
function_block-random_span
[ { "content": "#[inline]\n\nfn rotate_left(x: u64x4, n: u32) -> u64x4 {\n\n // Protect against undefined behaviour for over-long bit shifts\n\n const BITS: u32 = 64;\n\n let n = n % BITS;\n\n (x << n) | (x >> ((BITS - n) % BITS))\n\n}\n\n\n\nimpl XoroShiro128x4Core {\n\n /// Return the next random...
Rust
src/keys/types.rs
ianco/aries-askar
7346f30c8c95bf2ce343bc50e0f38f4e3921c711
use std::borrow::Cow; use std::convert::Infallible; use std::fmt::{self, Debug, Display, Formatter}; use std::mem::ManuallyDrop; use std::ops::Deref; use std::ptr; use std::str::FromStr; use indy_utils::keys::{EncodedVerKey, KeyType as IndyKeyAlg, PrivateKey, VerKey}; use serde::{Deserialize, Serialize}; use zeroize::...
use std::borrow::Cow; use std::convert::Infallible; use std::fmt::{self, Debug, Display, Formatter}; use std::mem::ManuallyDrop; use std::ops::Deref; use std::ptr; use std::str::FromStr; use indy_utils::keys::{EncodedVerKey, KeyType as IndyKeyAlg, PrivateKey, VerKey}; use serde::{Deserialize, Serialize}; use zeroize::...
nt == rhs.ident && self.params == rhs.params && self.sorted_tags() == rhs.sorted_tags() } } #[derive(Clone)] pub struct PassKey<'a>(Option<Cow<'a, str>>); impl PassKey<'_> { pub fn as_ref(&self) -> PassKey<'_> { PassKey(Some(Cow::Borrowed(&**self))) } pub(crate) f...
.as_ref().and_then(sorted_tags) } } impl PartialEq for KeyEntry { fn eq(&self, rhs: &Self) -> bool { self.category == rhs.category && self.ide
random
[ { "content": "/// Derive the (public) verification key for a keypair\n\npub fn derive_verkey(alg: KeyAlg, seed: &[u8]) -> Result<String> {\n\n match alg {\n\n KeyAlg::ED25519 => (),\n\n _ => return Err(err_msg!(Unsupported, \"Unsupported key algorithm\")),\n\n }\n\n\n\n let sk =\n\n ...
Rust
src/ciphers/bacon.rs
Swarley-hax/cienli
e02a20cc071812f0159d9821a8f07968645973a0
use regex::{Captures, Regex}; pub struct Bacon { letters: (char, char), } impl Bacon { pub fn new(letters: (char, char)) -> Result<Bacon, &'static str> { if letters.0 == letters.1 { return Err("Error: Letters must be different from each other!!"...
use regex::{Captures, Regex}; pub struct Bacon { letters: (char, char), } impl Bacon { pub fn new(letters: (char, char)) -> Result<Bacon, &'static str> { if letters.0 == letters.
_test() { let bacon = Bacon::new(('a', 'b')).unwrap(); assert_eq!( "aabbbaabaaababbababbabbba aababbaaababaaaaabaaabbabaaabb", bacon.encipher("Hello Friend") ); } #[test] fn decipher_test() { let bacon = Bacon::new(('a', 'b')).unwrap(); asse...
1 { return Err("Error: Letters must be different from each other!!"); } Ok(Bacon { letters: letters }) } pub fn encipher(&self, message: &str) -> String { ...
random
[ { "content": "pub fn key_gen(key: &str, message_len: usize) -> Result<String, &'static str> {\n\n let mut result: String = String::from(key);\n\n\n\n if key.len() <= 0 || message_len <= 0 {\n\n return Err(\"Error: Key and Message length must be 1 or greater than 1!!\");\n\n } else {\n\n i...
Rust
intonaco/src/cif.rs
urs-of-the-backwoods/fresco
9914df6d534f591448ed1501965f1bd03f3724de
use std; use std::io::{Cursor}; use std::mem; use libc; use std::env::vars; use std::ffi::CStr; use snowflake::ProcessUniqueId; use cbor::{Encoder}; #[cfg(unix)] use libloading::os::unix::{Library, Symbol}; #[cfg(windows)] use libloading::os::windows::{Library, Symbol}; use component; use cbor::{Config, GenericDeco...
use std; use std::io::{Cursor}; use std::mem; use libc; use std::env::vars; use std::ffi::CStr; use snowflake::ProcessUniqueId; use cbor::{Encoder}; #[cfg(unix)] use libloading::os::unix::{Library, Symbol}; #[cfg(windows)] use libloading::os::windows::{Library, Symbol}; use component; use cbor::{Config, GenericDeco...
#[no_mangle] pub extern "C" fn inCallbackSystemShutdown(cbs: *mut CallbackSystem) { } #[no_mangle] pub extern "C" fn inCallbackSystemStep(cbs: *mut CallbackSystem) { unsafe { let cb = Box::from_raw(cbs); cb.step_system(); std::mem::forget(cb); } }
pub extern "C" fn inCallbackSystemRegisterReceiver (cbs: *mut CallbackSystem, ep: EntityPointer, ct: u64, mfp: FrMessageFn2) { unsafe { let cb = Box::from_raw(cbs); cb.register_callback(ep, ct, mfp); std::mem::forget(cb); } }
function_block-full_function
[ { "content": "pub fn set_c_value(fp: FrMessageFn2, ep: EntityPointer, ct: u64, msg: &[u8]) {\n\n unsafe {\n\n fp (ep, ct, msg.as_ptr(), msg.len() as u32);\n\n }\n\n}\n\n\n\nimpl CallbackSystem {\n\n pub fn new() -> CallbackSystem {\n\n let cbs = CallbackSystem {\n\n queue: Arc:...
Rust
backend/src/api/sounds.rs
dominikks/discord-soundboard-bot
900c93f66d55434ac5e0e95fc5db224a6cf78401
use crate::api::auth::UserId; use crate::api::Snowflake; use crate::audio_utils; use crate::db::models; use crate::db::DbConn; use crate::discord::management::check_guild_moderator; use crate::discord::management::check_guild_user; use crate::discord::management::get_guilds_for_user; use crate::discord::management::Per...
use crate::api::auth::UserId; use crate::api::Snowflake; use crate::audio_utils; use crate::db::models; use crate::db::DbConn; use crate::discord::management::check_guild_moderator; use crate::discord::management::check_guild_user; use crate::discord::management::get_guilds_for_user; use crate::discord::management::Per...
sError> { let (guild_id, file_name) = db .run(move |c| { use crate::db::schema::soundfiles; use crate::db::schema::sounds; sounds::table .find(sound_id) .left_join(soundfiles::table) .select((sounds::guild_id, soundfiles::file_name.nullable())) .first::<(BigDecim...
le_option")] volume_adjustment: Option<Option<f32>>, } impl From<UpdateSoundParameter> for models::SoundChangeset { fn from(s: UpdateSoundParameter) -> Self { Self { name: s.name, category: s.category, volume_adjustment: s.volume_adjustment, } } } #[put("/<sound_id>", format = "json", ...
random
[ { "content": "pub fn get_full_sound_path(filename: &str) -> PathBuf {\n\n (*SOUNDS_FOLDER).join(filename)\n\n}\n\n\n\n#[derive(Debug)]\n\npub enum FileError {\n\n IoError(io::Error),\n\n}\n\n\n\nimpl From<io::Error> for FileError {\n\n fn from(err: io::Error) -> Self {\n\n FileError::IoError(err)\n\n }\n...
Rust
tests/board.rs
SamRond/alpha-rust
434e6cc4c95ebd337f021f64c555b70c012010f4
mod utils; #[cfg(test)] mod tests { use alpha_rust::Board; use std::sync::Once; static INIT: Once = Once::new(); fn init() { INIT.call_once(|| { crate::utils::set_panic_hook(); }); } #[test] fn test_board_init() { init(); let board = Boar...
mod utils; #[cfg(test)] mod tests { use alpha_rust::Board; use std::sync::Once; static INIT: Once = Once::new(); fn init() { INIT.call_once(|| { crate::utils::set_panic_hook(); }); } #[test] fn test_board_init() { init(); let board = Boar...
#[test] fn test_knight_move() { let mut board = Board::new("".to_string()); print!("\n\n"); print!("Checking if knight move is successful... "); let knight = &mut board.get_white_pieces()[1][1]; let mv = board.make_move(knight, 3, 6); asser...
let mv = board.make_move(pawn, 4, 5); assert!(mv); assert_eq!(board.find_piece_by_coords(4, 5).unwrap(), pawn); println!("true"); }
function_block-function_prefix_line
[ { "content": "pub fn set_panic_hook() {\n\n // When the `console_error_panic_hook` feature is enabled, we can call the\n\n // `set_panic_hook` function at least once during initialization, and then\n\n // we will get better error messages if our code ever panics.\n\n //\n\n // For more details se...
Rust
src/file_link.rs
vikigenius/dlm
d449e0cc490b999a41c5d73cbf364437593cafae
use crate::dlm_error::DlmError; use crate::dlm_error::DlmError::Other; use std::str; pub struct FileLink { pub url: String, pub file_name_no_extension: String, pub extension: String, pub file_name: String, } const NO_EXT: &str = ".NO_EXT"; impl FileLink { pub fn new(url: String) -> Result<FileL...
use crate::dlm_error::DlmError; use crate::dlm_error::DlmError::Other; use std::str; pub struct FileLink { pub url: String, pub file_name_no_extension: String, pub extension: String, pub file_name: String, } const NO_EXT: &str = ".NO_EXT"; impl FileLink { pub fn new(url: String) -> Result<FileL...
; assert_eq!(fl.file_name_no_extension, "area51.".to_string()); } _ => assert_eq!(true, false), } } #[test] fn full_path() { let url = "http://www.google.com/area51.txt".to_string(); let fl = FileLink::new(url).unwrap(); let full_path ...
et file_name = format!("{}{}", file_name_no_extension, extension); let file_link = FileLink { url, file_name_no_extension, extension, file_name, }; Ok(file_link) } } pub fn full_path(&self, output_dir: &...
random
[ { "content": "pub fn get_args() -> (String, usize, String) {\n\n let app = app();\n\n let matches = app.get_matches();\n\n\n\n let max_concurrent_downloads = matches.value_of_t(\"maxConcurrentDownloads\")\n\n .expect(\"maxConcurrentDownloads was not an integer\");\n\n if max_concurrent_downlo...
Rust
services/pool/src/service.rs
tiagolobocastro/Mayastor
c9cf777e7776f529a2433d29b8513d1c601684a6
#![allow(clippy::unit_arg)] use super::*; use common::wrapper::v0::*; #[derive(Clone, Debug, Default)] pub(super) struct PoolSvc { registry: Registry<NodeWrapperPool>, } impl PoolSvc { pub fn new(period: std::time::Duration) -> Self { let obj = Self { registry: Registry::new(period)...
#![allow(clippy::unit_arg)] use super::*; use common::wrapper::v0::*; #[derive(Clone, Debug, Default)] pub(super) struct PoolSvc { registry: Registry<NodeWrapperPool>, } impl PoolSvc {
fn start(&self) { self.registry.start(); } async fn get_node_pools( &self, node_id: Option<NodeId>, ) -> Result<Vec<Pool>, SvcError> { Ok(match node_id { None => self.registry.list_pools().await, Some(node_id) => self.registry.list_node...
pub fn new(period: std::time::Duration) -> Self { let obj = Self { registry: Registry::new(period), }; obj.start(); obj }
function_block-full_function
[ { "content": "#[derive(Debug)]\n\nstruct RebuildTask {\n\n buffer: DmaBuf,\n\n sender: mpsc::Sender<TaskResult>,\n\n error: Option<TaskResult>,\n\n}\n\n\n\n/// Pool of rebuild tasks and progress tracking\n\n/// Each task uses a clone of the sender allowing the management task to poll a\n\n/// single re...
Rust
src/day24.rs
Strackeror/aoc_2021_rust
076582e489dd9ea33b9cf4846626a81f1dcbde4b
use std::{cell::RefCell, collections::HashMap}; use itertools::Itertools; #[derive(Debug, PartialEq, Eq, Clone, Copy)] pub enum Param { Number(i64), Variable(char), } #[derive(Debug, PartialEq, Eq, Clone, Copy)] pub enum Expr { Input(char), Add(char, Param), Mul(char, Param), Div(char, Param)...
use std::{cell::RefCell, collections::HashMap}; use itertools::Itertools; #[derive(Debug, PartialEq, Eq, Clone, Copy)] pub enum Param { Number(i64), Variable(char), } #[derive(Debug, PartialEq, Eq, Clone, Copy)] pub enum Expr { Input(char), Add(char, Param), Mul(char, Param), Div(char, Param)...
fn process_expr(expr: Expr, mut state: [i64; 4]) -> [i64; 4] { match expr { Expr::Add(c, b) => { state[cid(c)] = state[cid(c)] + val(state, b); } Expr::Mul(c, b) => { state[cid(c)] = state[cid(c)] * val(state, b); } Expr::Div(c, b) => { s...
fn val(state: [i64; 4], p: Param) -> i64 { match p { Param::Number(n) => n, Param::Variable(c) => state[cid(c)], } }
function_block-full_function
[ { "content": "pub fn run(input: &str) -> Result<()> {\n\n let (a, b) = input.split_once(',').context(\"\")?;\n\n\n\n let p1_state = PlayerState {\n\n position: a.parse::<u64>()? - 1,\n\n score: 0,\n\n rollcount: 0,\n\n };\n\n\n\n let p2_state = PlayerState {\n\n position:...
Rust
src/ir/mod.rs
playXE/rcc
7f95c3d5b14f6912f04e9ce2baeb2bc3f29990ed
mod expr; mod static_init; mod stmt; use std::collections::{HashMap, VecDeque}; use std::convert::TryFrom; use crate::data::{prelude::*, types::FunctionType, Initializer, Scope, StorageClass}; use crate::utils; use cranelift::codegen::{ self, ir::{ entities::StackSlot, function::Function, ...
mod expr; mod static_init; mod stmt; use std::collections::{HashMap, VecDeque}; use std::convert::TryFrom; use crate::data::{prelude::*, types::FunctionType, Initializer, Scope, StorageClass}; use crate::utils; use cranelift::codegen::{ self, ir::{ entities::StackSlot, function::Function, ...
fn declare_stack( &mut self, decl: Declaration, location: Location, builder: &mut FunctionBuilder, ) -> CompileResult<()> { if let Type::Function(ftype) = decl.symbol.ctype { self.declare_func( decl.symbol.id, &ftype.signa...
fn declare_func( &mut self, id: InternedStr, signature: &Signature, sc: StorageClass, is_definition: bool, ) -> CompileResult<FuncId> { use crate::get_str; if !is_definition { if let Some(Id::Function(func_id)) = self.scope.get(&id) { ...
function_block-full_function
[]
Rust
src/lib.rs
Ujang360/py-udp-loop
73bd587a64d262bc98a4d0784eb77d95a1141282
use crossbeam_queue::ArrayQueue; use pyo3::prelude::*; use pyo3::types::PyByteArray; use std::net::{SocketAddr, UdpSocket}; use std::sync::atomic::{AtomicBool, Ordering}; use std::sync::{Arc, Mutex}; use std::thread::{sleep, spawn as spawn_thread, JoinHandle}; use std::time::Duration; pub const LOOP_GRACE_DURATION_MS:...
use crossbeam_queue::ArrayQueue; use pyo3::prelude::*; use pyo3::types::PyByteArray; use std::net::{SocketAddr, UdpSocket}; use std::sync::atomic::{AtomicBool, Ordering}; use std::sync::{Arc, Mutex}; use std::thread::{sleep, spawn as spawn_thread, JoinHandle}; use std::time::Duration; pub const LOOP_GRACE_DURATION_MS:...
; Ok(true) } pub fn stop(&mut self) -> PyResult<bool> { match self.loop_handle.lock().unwrap().take() { None => Ok(false), Some(loop_handle) => { self.stop_flag.store(true, Ordering::Relaxed); let _ = loop_handle.join(); O...
Some(spawn_thread(move || { let loop_grace_duration = Duration::from_millis(LOOP_GRACE_DURATION_MS); let mut buffer_rx = [0u8; MAX_PACKET_SIZE]; let binding_socket = SocketAddr::new(listen_address.parse().unwrap(), listen_port); let udp_socket = UdpSocket::bind(binding_so...
call_expression
[]
Rust
machine_manager/src/config/machine_config.rs
ican2002/stratorvirt
b8e9b675ae0fac9e359a2096cc818f92c4f11c30
extern crate serde; extern crate serde_json; use std::str::FromStr; use serde::{Deserialize, Serialize}; use super::errors::{ErrorKind, Result, ResultExt}; use crate::config::{CmdParser, ConfigCheck, ExBool, VmConfig}; const DEFAULT_CPUS: u8 = 1; const DEFAULT_MEMSIZE: u64 = 256; const MAX_NR_CPUS: u64 = 254; con...
extern crate serde; extern crate serde_json; use std::str::FromStr; use serde::{Deserialize, Serialize}; use super::errors::{ErrorKind, Result, ResultExt}; use crate::config::{CmdParser, ConfigCheck, ExBool, VmConfig}; const DEFAULT_CPUS: u8 = 1; const DEFAULT_MEMSIZE: u64 = 256; const MAX_NR_CPUS: u64 = 254; con...
} else if (origin_value.ends_with('G') | origin_value.ends_with('g')) && (origin_value.contains('G') ^ origin_value.contains('g')) { let value = origin_value.replacen("G", "", 1); let value = value.replacen("g", "", 1); get_inner( value .parse::<u64>(...
get_inner( value .parse::<u64>() .map_err(|_| { ErrorKind::ConvertValueFailed(origin_value.to_string(), String::from("u64")) })? .checked_mul(M), )
call_expression
[ { "content": "/// Sets the value of one register for this vCPU.\n\n///\n\n/// The id of the register is encoded as specified in the kernel documentation\n\n/// for `KVM_SET_ONE_REG`.\n\n///\n\n/// Max register size is 256 Bytes.\n\n///\n\n/// # Arguments\n\n///\n\n/// * `reg_id` - ID of the register for which w...
Rust
npk/src/dm_verity.rs
AmoghAJ/northstar
06e087df238bd9fc45026ecaf48e2642266ac7c5
use rand::RngCore; use sha2::{Digest, Sha256}; use std::{ fs::{File, OpenOptions}, io::{BufReader, Read, Seek, SeekFrom::Start, Write}, path::Path, }; use thiserror::Error; use uuid::Uuid; pub const SHA256_SIZE: usize = 32; pub const BLOCK_SIZE: usize = 4096; pub type Sha256Digest = [u8; SHA256_SIZE]; p...
use rand::RngCore; use sha2::{Digest, Sha256}; use std::{ fs::{File, OpenOptions}, io::{BufReader, Read, Seek, SeekFrom::Start, Write}, path::Path, }; use thiserror::Error; use uuid::Uuid; pub const SHA256_SIZE: usize = 32; pub const BLOCK_SIZE: usize = 4096; pub type Sha256Digest = [u8; SHA256_SIZE]; p...
fn gen_hash_tree( fsimg_path: &Path, image_size: u64, level_offsets: &[usize], tree_size: usize, ) -> Result<(Salt, Sha256Digest, Vec<u8>), Error> { let image = &File::open(&fsimg_path).map_err(|e| Error::Os { context: format!("Cannot open '{}'", &fsimg_path.display()), ...
fn calc_hash_tree_level_offsets( image_size: usize, block_size: usize, digest_size: usize, ) -> (Vec<usize>, usize) { let mut level_offsets: Vec<usize> = vec![]; let mut level_sizes: Vec<usize> = vec![]; let mut tree_size = 0; let mut num_levels = 0; let mut rem_size = image_size; w...
function_block-full_function
[ { "content": "fn create_squashfs(out: &Path, src: &Path, pseudo_dirs: &[(String, u32)]) -> Result<(), Error> {\n\n #[cfg(target_os = \"linux\")]\n\n let compression_alg = \"gzip\";\n\n #[cfg(not(target_os = \"linux\"))]\n\n let compression_alg = \"zstd\";\n\n\n\n if which::which(&MKSQUASHFS_BIN)....
Rust
src/dovi/general_read_write.rs
amsokol/dovi_tool
458aadecf266575f199814a0479deb2dbe0fc95c
use std::io::{stdout, BufRead, BufReader, BufWriter, Write}; use std::path::PathBuf; use std::{fs::File, path::Path}; use anyhow::{bail, Result}; use indicatif::ProgressBar; use hevc_parser::hevc::{NALUnit, NAL_SEI_PREFIX, NAL_UNSPEC62, NAL_UNSPEC63}; use hevc_parser::io::{processor, IoFormat, IoProcessor}; use hevc_...
use std::io::{stdout, BufRead, BufReader, BufWriter, Write}; use std::path::PathBuf; use std::{fs::File, path::Path}; use anyhow::{bail, Result}; use indicatif::ProgressBar; use hevc_parser::hevc::{NALUnit, NAL_SEI_PREFIX, NAL_UNSPEC62, NAL_UNSPEC63}; use hevc_parser::io::{processor, IoFormat, IoProcessor}; use hevc_...
} impl IoProcessor for DoviProcessor { fn input(&self) -> &std::path::PathBuf { &self.input } fn update_progress(&mut self, delta: u64) { self.progress_bar.inc(delta); } fn process_nals(&mut self, _parser: &HevcParser, nals: &[NALUnit], chunk: &[u8]) -> Result<()> { self....
fn flush_writer(&mut self, parser: &HevcParser) -> Result<()> { if let Some(ref mut bl_writer) = self.dovi_writer.bl_writer { bl_writer.flush()?; } if let Some(ref mut el_writer) = self.dovi_writer.el_writer { el_writer.flush()?; } if let Some(r...
function_block-full_function
[ { "content": "pub fn write_rpu_file(output_path: &Path, data: Vec<Vec<u8>>) -> Result<()> {\n\n println!(\"Writing RPU file...\");\n\n let mut writer = BufWriter::with_capacity(\n\n 100_000,\n\n File::create(output_path).expect(\"Can't create file\"),\n\n );\n\n\n\n for encoded_rpu in ...
Rust
xdr-codec/src/record.rs
Voronar/rust-xdr
a1fa344e6cd0fce72585388b9b5145aa21d569fc
use std::io::{self, BufRead, Read, Write}; use std::cmp::min; use crate::error::*; use super::{Error, pack, unpack}; const LAST_REC: u32 = 1u32 << 31; fn mapioerr(xdrerr: Error) -> io::Error { match xdrerr { Error(ErrorKind::IOError(ioerr), _) => ioerr, other => io::Error::new(io::ErrorKind::O...
use std::io::{self, BufRead, Read, Write}; use std::cmp::min; use crate::error::*; use super::{Error, pack, unpack}; const LAST_REC: u32 = 1u32 << 31; fn mapioerr(xdrerr: Error) -> io::Error { match xdrerr { Error(ErrorKind::IOError(ioerr), _) => ioerr, other => io::Error::new(io::ErrorKind::O...
} const WRBUF: usize = 65536; pub struct XdrRecordWriter<W: Write> { buf: Vec<u8>, bufsz: usize, eor: bool, writer: W, } impl<W: Write> XdrRecordWriter<W> { pub fn new(w: W) -> XdrRecordWriter<W> { XdrRecordWriter::with_buffer(w, WRBUF) } pub fn with_buff...
k; } } self.0 = Some(rr); Some(Ok(buf)) } else { None } }
function_block-function_prefixed
[ { "content": "/// Pack a fixed-size byte array\n\n///\n\n/// As size is fixed, it doesn't need to be encoded. `sz` is in bytes (and array elements, which are u8)\n\n/// If the array is too large, it is truncated; if its too small its padded with `0x00`.\n\npub fn pack_opaque_array<Out: Write>(val: &[u8], sz: us...
Rust
pac/atsam4sd32c/src/spi/ier.rs
haata/atsam4-pac
849dd8fcf3be0074d98b8fc65e4fb03fdfd4b6b1
#[doc = "Writer for register IER"] pub type W = crate::W<u32, super::IER>; #[doc = "Write proxy for field `RDRF`"] pub struct RDRF_W<'a> { w: &'a mut W, } impl<'a> RDRF_W<'a> { #[doc = r"Sets the field bit"] #[inline(always)] pub fn set_bit(self) -> &'a mut W { self.bit(true) } #[doc = r...
#[doc = "Writer for register IER"] pub type W = crate::W<u32, super::IER>; #[doc = "Write proxy for field `RDRF`"] pub struct RDRF_W<'a> { w: &'a mut W, } impl<'a> RDRF_W<'a> { #[doc = r"Sets the field bit"] #[inline(always)] pub fn set_bit(self) -> &'a mut W { self.bit(true) } #[doc = r...
#[doc = r"Sets the field bit"] #[inline(always)] pub fn set_bit(self) -> &'a mut W { self.bit(true) } #[doc = r"Clears the field bit"] #[inline(always)] pub fn clear_bit(self) -> &'a mut W { self.bit(false) } #[doc = r"Writes raw bits to the field"] #[inline(alway...
"Clears the field bit"] #[inline(always)] pub fn clear_bit(self) -> &'a mut W { self.bit(false) } #[doc = r"Writes raw bits to the field"] #[inline(always)] pub fn bit(self, value: bool) -> &'a mut W { self.w.bits = (self.w.bits & !(0x01 << 3)) | (((value as u32) & 0x01) << 3); ...
random
[]
Rust
graphdb/rust/src/generated.rs
jordan-rash/actor-interfaces
e4679488148ff4f1e11a0c7b87a8d9c8b32e24e8
extern crate rmp_serde as rmps; use rmps::{Deserializer, Serializer}; use serde::{Deserialize, Serialize}; use std::io::Cursor; extern crate log; #[cfg(feature = "guest")] extern crate wapc_guest as guest; #[cfg(feature = "guest")] use guest::prelude::*; #[cfg(feature = "guest")] use lazy_static::lazy_static; #[cfg(f...
extern crate rmp_serde as rmps; use rmps::{Deserializer, Serializer}; use serde::{Deserialize, Serialize}; use std::io::Cursor; extern crate log; #[cfg(feature = "guest")] extern crate wapc_guest as guest; #[cfg(feature = "guest")] use guest::prelude::*; #[cfg(feature = "guest")] use lazy_static::lazy_static; #[cfg(f...
erialize<'de>>( buf: &[u8], ) -> ::std::result::Result<T, Box<dyn std::error::Error + Send + Sync>> { let mut de = Deserializer::new(Cursor::new(buf)); match Deserialize::deserialize(&mut de) { Ok(t) => Ok(t), Err(e) => Err(format!("Failed to de-serialize: {}", e).into()), } }
.map_err(|e| e.into()) } pub fn delete_graph(&self, graphName: String) -> HandlerResult<DeleteResponse> { let input_args = DeleteGraphArgs { graph_name: graphName, }; host_call( &self.binding, "wasmcloud:graphdb", "DeleteGraph", ...
random
[ { "content": "#[cfg(feature = \"guest\")]\n\npub fn host(binding: &str) -> Host {\n\n set_binding(binding);\n\n Host {}\n\n}\n\n\n\n/// Creates the default host binding\n", "file_path": "logging/rust/src/generated.rs", "rank": 0, "score": 288951.3958429548 }, { "content": "#[cfg(featur...