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
tests/it/compute/temporal.rs
VasanthakumarV/arrow2
ee237968686b1b444755b9227b8df438655bf7f5
use arrow2::array::*; use arrow2::compute::temporal::*; use arrow2::datatypes::*; #[test] fn date64_hour() { let array = Int64Array::from(&[Some(1514764800000), None, Some(1550636625000)]).to(DataType::Date64); let result = hour(&array).unwrap(); let expected = UInt32Array::from(&[Some(0), None, S...
use arrow2::array::*; use arrow2::compute::temporal::*; use arrow2::datatypes::*; #[test] fn date64_hour() { let array = Int64Array::from(&[Some(1514764800000), None, Some(1550636625000)]).to(DataType::Date64); let result = hour(&array).unwrap(); let expected = UInt32Array::from(&[Some(0), None, S...
#[test] fn consistency_year() { use arrow2::array::new_null_array; use arrow2::datatypes::DataType::*; use arrow2::datatypes::TimeUnit; let datatypes = vec![ Null, Boolean, UInt8, UInt16, UInt32, UInt64, Int8, Int16, Int32, ...
d), Duration(TimeUnit::Microsecond), Duration(TimeUnit::Nanosecond), ]; datatypes.into_iter().for_each(|d1| { let array = new_null_array(d1.clone(), 10); if can_hour(&d1) { assert!(hour(array.as_ref()).is_ok()); } else { assert!(hour(array.as_ref(...
function_block-function_prefixed
[ { "content": "fn test_generic<O: Offset, F: Fn(&Utf8Array<O>, &Utf8Array<O>) -> Result<BooleanArray>>(\n\n lhs: Vec<&str>,\n\n pattern: Vec<&str>,\n\n op: F,\n\n expected: Vec<bool>,\n\n) {\n\n let lhs = Utf8Array::<O>::from_slice(lhs);\n\n let pattern = Utf8Array::<O>::from_slice(pattern);\n\...
Rust
src/framework/builder.rs
KaceCottam/poise
5e3f777c2f5129b416d76a074fd148b61a1e1ff2
use crate::serenity_prelude as serenity; use crate::BoxFuture; pub struct FrameworkBuilder<U, E> { user_data_setup: Option< Box< dyn Send + Sync + for<'a> FnOnce( &'a serenity::Context, &'a serenity::Ready, ...
use crate::serenity_prelude as serenity; use crate::BoxFuture; pub struct FrameworkBuilder<U, E> { user_data_setup: Option< Box< dyn Send + Sync + for<'a> FnOnce( &'a serenity::Context, &'a serenity::Ready, ...
let mut client_builder = serenity::ClientBuilder::new(token).application_id(application_info.id.0); if let Some(client_settings) = self.client_settings { client_builder = client_settings(client_builder); } crate::Framework::new(client_builder,...
if self.initialize_owners { options.owners.insert(application_info.owner.id); if let Some(team) = application_info.team { for member in team.members { if member.permissions.iter().any(|p| p == "*") { ...
if_condition
[ { "content": "/// Find a command or subcommand within `&[Command]`, given a command invocation without a prefix.\n\n/// Returns the verbatim command name string as well as the command arguments (i.e. the remaining\n\n/// string).\n\n///\n\n/// ```rust\n\n/// #[poise::command(prefix_command)] async fn command1(c...
Rust
awesome/src/objects/drawin.rs
knoebber/way-cooler
f48bdc8fb1a1a2e1c0f421ec05fe293b94b626e4
use std::cell::RefMut; use cairo::ImageSurface; use rlua::prelude::LuaInteger; use rlua::{self, Lua, Table, ToLua, UserData, UserDataMethods}; use wlroots::{Area, Origin, Size, Texture}; use common::{class::{self, Class, ClassBuilder}, object::{self, Object, ObjectBuilder}, property::Prope...
use std::cell::RefMut; use cairo::ImageSurface; use rlua::prelude::LuaInteger; use rlua::{self, Lua, Table, ToLua, UserData, UserDataMethods}; use wlroots::{Area, Origin, Size, Texture}; use common::{class::{self, Class, ClassBuilder}, object::{self, Object, ObjectBuilder}, property::Prope...
#[allow(dead_code)] pub fn drawable(&mut self) -> rlua::Result<Drawable> { self.get_associated_data::<Drawable>("drawable") } #[allow(dead_code)] pub fn texture(&mut self) -> rlua::Result<RefMut<Option<Texture<'static>>>> { Ok(RefMut::map(self.state_mut()?, |state| ...
fn new(lua: &'lua Lua, args: Table) -> rlua::Result<Drawin<'lua>> { let class = class::class_setup(lua, "drawin")?; let mut drawins = lua.named_registry_value::<Vec<Drawin>>(DRAWINS_HANDLE)?; let drawin = object_setup(lua, Drawin::allocate(lua, class)?)?.handle_constructor_argument(a...
function_block-full_function
[ { "content": "/// The ObjectStateType trait is used to constrain the generic data types in the Object and Class structs.\n\n/// They can be transferred to and from Lua user data and force type checking\n\npub trait ObjectStateType: UserData + Default + Send {}\n\n\n\nimpl<T> ObjectStateType for T where T: UserD...
Rust
src/winvol.rs
RavuAlHemio/rusty-dee-dee
6658b0fb277be73859c409a7ab14f78a7168eb65
use std::convert::TryInto; use std::error::Error; use std::fmt::{Display, Error as FmtError, Formatter}; use std::fs::File; use std::io::{Error as IOError, ErrorKind as IOErrorKind}; use std::mem::{size_of, zeroed}; use std::os::windows::io::{AsRawHandle, RawHandle}; use std::ptr::null_mut; use std::string::FromUtf16Er...
use std::convert::TryInto; use std::error::Error; use std::fmt::{Display, Error as FmtError, Formatter}; use std::fs::File; use std::io::{Error as IOError, ErrorKind as IOErrorKind}; use std::mem::{size_of, zeroed}; use std::os::windows::io::{AsRawHandle, RawHandle}; use std::ptr::null_mut; use std::string::FromUtf16Er...
pub fn as_unicode_string(&mut self) -> UNICODE_STRING { let byte_length: u16 = (self.backing.len() * size_of::<u16>()).try_into().unwrap(); let byte_capacity: u16 = (self.backing.capacity() * size_of::<u16>()).try_into().unwrap(); let buf: PWSTR = self.backing.as_mut_ptr(); UNICODE...
for i in 0..char_length { let c: u16 = *(unistr.Buffer.offset(i)); backing.push(c); } } UnicodeStringHolder { backing, } }
function_block-function_prefix_line
[ { "content": "fn main() {\n\n exit(do_main());\n\n}\n", "file_path": "src/main.rs", "rank": 9, "score": 27748.47565409307 }, { "content": "fn do_main() -> i32 {\n\n let args: Vec<String> = env::args().collect();\n\n let opts: Opts = match Opts::try_parse_from(args) {\n\n Ok(o...
Rust
crates/ditto-cst/src/parser/result.rs
ditto-lang/ditto
1d73c2fbb3b54e643b79de2acb0677b80f0b1d77
use super::Rule; use crate::Span; use miette::{Diagnostic, NamedSource, SourceSpan}; use thiserror::Error; use pest::error::{Error, ErrorVariant, InputLocation}; pub(super) type Result<T> = std::result::Result<T, ParseError>; #[derive(Debug, Clone)] pub struct ParseError { pub span: Span, pub posit...
use super::Rule; use crate::Span; use miette::{Diagnostic, NamedSource, SourceSpan}; use thiserror::Error; use pest::error::{Error, ErrorVariant, InputLocation}; pub(super) type Result<T> = std::result::Result<T, ParseError>; #[derive(Debug, Clone)] pub struct ParseError { pub span: Span, pub posit...
location, expected: self.positives.join(", "), }, (true, false) => ParseErrorReport::Unexpected { input, location, unexpected: self.negatives.join(", "), }, (false, false) => ParseErrorReport::Helpful { ...
b enum ParseErrorReport { #[error("syntax error")] #[diagnostic(severity(Error))] Unhelpful { #[source_code] input: NamedSource, #[label("there's an issue here?")] location: SourceSpan, }, #[error("syntax error")] #[diagnostic(severity...
random
[ { "content": "/// Convert our [Span] to a miette [SourceSpan].\n\nfn span_to_source_span(span: Span) -> SourceSpan {\n\n SourceSpan::from((span.start_offset, span.end_offset - span.start_offset))\n\n}\n", "file_path": "crates/ditto-checker/src/result/type_error.rs", "rank": 0, "score": 293513.579...
Rust
src/commands/system.rs
baajarmeh/pikadick-rs
cbb66ac68e6b48871c22ebc3fbe67b65cfc21e24
use crate::checks::ENABLED_CHECK; use chrono::DateTime; use heim::{ memory::{ Memory, Swap, }, units::{ frequency::{ gigahertz, hertz, }, information::{ byte, gigabyte, }, time::nanosecond, Freque...
use crate::checks::ENABLED_CHECK; use chrono::DateTime; use heim::{ memory::{ Memory, Swap, }, units::{ frequency::{ gigahertz, hertz, }, information::{ byte, gigabyte, }, time::nanosecond, Freque...
true, ); } (None, None) => {} } if let Some(memory) = memory { e.field("Memory Usage", fmt_memory(&memory), true); } if let Some(swap) = swap { e....
e.thumbnail(icon); } if let Some(platform) = platform { e.field("Hostname", platform.hostname(), true); e.field( "OS", format!( "{} {} (version {})", ...
random
[ { "content": "/// A rust-optimized version of:\n\n/// ```javascript\n\n/// /// Taken from: https://honk.moe/tools/owo.html\n\n/// var faces = [\"(・`ω´・)\", \";;w;;\", \"owo\", \"UwU\", \">w<\", \"^w^\"];\n\n/// function OwoifyText(){\n\n/// v = document.getElementById(\"textarea\").value\n\n/// v = v.re...
Rust
utils/tsproto-structs/src/lib.rs
0xpr03/tsclientlib
3aa03661a2b9c62a6faf05e0f16a94e606c4fdb6
use std::fmt; use std::str::FromStr; use heck::*; use serde::Deserialize; type Result<T> = std::result::Result<T, fmt::Error>; pub mod book; pub mod book_to_messages; pub mod enums; pub mod errors; pub mod messages; pub mod messages_to_book; pub mod permissions; pub mod versions; #[derive(Debug, Deserialize)] pub...
use std::fmt; use std::str::FromStr; use heck::*; use serde::Deserialize; type Result<T> = std::result::Result<T, fmt::Error>; pub mod book; pub mod book_to_messages; pub mod enums; pub mod errors; pub mod messages; pub mod messages_to_book; pub mod permissions; pub mod versions; #[derive(Debug, Deserialize)] pub...
pub fn uses_lifetime(&self) -> bool { match self { Self::Struct(s) if s == "Uid" => true, Self::Ref(_) | Self::Cow(_) => true, Self::Map(_, i) | Self::Set(i) | Self::Vec(i) | Self::Option(i) => i.uses_lifetime(), _ => false, } } } impl FromStr for InnerRustType { type Err = fmt::Error; fn from_st...
inner } else if inner.starts_with('&') && &inner[1..] == name { format!("{0}.as_ref()", name) } else { format!("{0}.as_ref().map(|{0}| {1})", name, inner) } } } } } }
function_block-function_prefix_line
[ { "content": "// the in rust callable name (in PascalCase) from the field\n\nfn find_field<'a>(name: &str, msg_fields: &[&'a Field]) -> &'a Field {\n\n\t*msg_fields\n\n\t\t.iter()\n\n\t\t.find(|f| f.pretty == name)\n\n\t\t.unwrap_or_else(|| panic!(\"Cannot find field '{}'\", name))\n\n}\n\n\n\nimpl<'a> RuleKind...
Rust
src/ruuvitag_df3.rs
janne-alatalo/ruuvitag-collector
df94e0d97bfbe34ca12e201e62625fa9c5164287
use std::rc::Rc; use std::cell::{RefCell, Ref}; use std::collections::HashMap; use serde_json; use bt_sensor::{BTSensor, BTSensorConstructor, Value}; use bt_device::BTDevice; use discovery_mode::DiscoveryMode; pub struct RuuvitagDF3Constructor; impl RuuvitagDF3Constructor { pub fn new() -> Box<RuuvitagDF3Constr...
use std::rc::Rc; use std::cell::{RefCell, Ref}; use std::collections::HashMap; use serde_json; use bt_sensor::{BTSensor, BTSensorConstructor, Value}; use bt_device::BTDevice; use discovery_mode::DiscoveryMode; pub struct RuuvitagDF3Constructor; impl RuuvitagDF3Constructor { pub fn new() -> Box<RuuvitagDF3Constr...
rements() { Some(meas) => { serde_json::to_string(&meas).ok() }, None => None, } } fn _get_measurements(&self) -> Option<RuuvitagDF3Meas> { if let ( Some(format), Some(hum), Some(temp_wholes), Some(temp_sign), Some(temp...
'static str { "RuuvitagDF3" } fn construct(&self, device: Rc<RefCell<BTDevice>>, discovery_mode: DiscoveryMode) -> Box<dyn BTSensor> { Box::new(RuuvitagDF3::new(device, discovery_mode)) } fn is_valid_data(&self, device: &BTDevice) -> bool { RuuvitagDF3::_is_valid_data(device) ...
random
[ { "content": "pub trait BTSensorConstructor {\n\n fn get_name(&self) -> &'static str;\n\n fn construct(&self, device: Rc<RefCell<BTDevice>>, discovery_mode: DiscoveryMode) -> Box<dyn BTSensor>;\n\n fn is_valid_data(&self, device: &BTDevice) -> bool;\n\n}\n\n\n\n#[derive(Debug, Clone, Deserialize, Seria...
Rust
src/stm32l4/peripherals/opamp.rs
adamgreig/stm32ral
d316aaad753fd427b1d9fe641ca9611f5f20053c
#![allow(non_snake_case, non_upper_case_globals)] #![allow(non_camel_case_types)] use crate::RWRegister; #[cfg(not(feature = "nosync"))] use core::marker::PhantomData; pub mod OPAMP1_CSR { pub mod OPAEN { pub const offset: u32 = 0; pub const mask: u32 = 1 << offset; ...
#![allow(non_snake_case, non_upper_case_globals)] #![allow(non_camel_case_types)] use crate::RWRegister; #[cfg(not(feature = "nosync"))] use core::marker::PhantomData; pub mod OPAMP1_CSR { pub mod OPAEN { pub const offset: u32 = 0; pub const mask: u32 = 1 << offset; ...
pub mod RW {} } } pub mod OPAMP1_OTR { pub mod TRIMOFFSETN { pub const offset: u32 = 0; pub const mask: u32 = 0b11111 << offset; pub mod R {} pub mod W {} pub mod RW {} } pub mod TRIMOFFSETP { ...
pub mod RW {} } pub mod VM_SEL { pub const offset: u32 = 8; pub const mask: u32 = 0b11 << offset; pub mod R {} pub mod W {} pub mod RW {} } pub mod VP_SEL { pub const offset: u32 = ...
random
[ { "content": "#[cfg(any(feature=\"stm32g051\", feature=\"doc\"))]\n\npub mod stm32g051;\n\n\n\n#[cfg(any(feature=\"stm32g061\", feature=\"doc\"))]\n\npub mod stm32g061;\n\n\n\n#[cfg(any(feature=\"stm32g070\", feature=\"doc\"))]\n\npub mod stm32g070;\n\n\n\n#[cfg(any(feature=\"stm32g071\", feature=\"doc\"))]\n\n...
Rust
src/manager/archive/page/regular_image.rs
kipukun/aw-man
907f9b3580f7c64254f0ffd8a713dba8b2fb4d72
use core::fmt; use std::future; use std::path::PathBuf; use std::rc::Weak; use tokio::select; use State::*; use crate::com::{Bgra, Displayable, LoadingParams, Res, ScaledImage}; use crate::manager::archive::page::chain_last_load; use crate::manager::archive::Work; use crate::pools::loading::{self, LoadFuture}; use cr...
use core::fmt; use std::future; use std::path::PathBuf; use std::rc::Weak; use tokio::select; use State::*; use crate::com::{Bgra, Displayable, LoadingParams, Res, ScaledImage}; use crate::manager::archive::page::chain_last_load; use crate::manager::archive::Work; use crate::pools::loading::{self, LoadFuture}; use cr...
}
Loading(lf) | Reloading(lf, _) => { chain_last_load(&mut self.last_load, lf.cancel()); trace!("Unloaded {:?}", self); self.state = Unloaded; } } }
function_block-function_prefix_line
[]
Rust
src/helpers/mute_helper.rs
thatsimplekid/QuiVive
b3697e69542c0c4d449ad52bb57ac72142824165
/* Qui Vive - A Discord bot to keep out the riff-raff * Copyright (C) 2022 Owen Flaherty * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License as published * by the Free Software Foundation, either version 3 of the License, or *...
/* Qui Vive - A Discord bot to keep out the riff-raff * Copyright (C) 2022 Owen Flaherty * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License as published * by the Free Software Foundation, either version 3 of the License, or *...
pub async fn fetch_timed_mutes(pool: &PgPool, guild_id: &GuildId) -> CommandResult<HashMap<UserId, String>> { let mute_data_vec = sqlx::query!("SELECT * FROM mutes WHERE guild_id = $1", guild_id.0 as i64) .fetch_all(pool).await?; let timed_mutes = mute_data_vec.iter().map(|mute_data| { let nai...
pub async fn fetch_guild_mutes(pool: &PgPool, guild: &Guild, mute_role_id: RoleId) -> CommandResult<(String, String)> { let timed_mutes = fetch_timed_mutes(pool, &guild.id).await?; let permanent_mute_test = guild.members.iter() .filter(|(u, m)| m.roles.contains(&mute_role_id) && !timed_mutes.contains_ke...
function_block-function_prefix_line
[ { "content": "pub fn get_mute_embed(user: &User, new_mute: bool, use_time: bool, mute_time: Option<&str>) -> CreateEmbed {\n\n let mut eb = CreateEmbed::default();\n\n eb.color(if new_mute { COLOR_ORANGE } else { COLOR_GREEN });\n\n eb.title(if new_mute { \"User Muted\" } else { \"User Unmuted\" });\n\...
Rust
vrrb_lib/src/account.rs
vrrb-io/vrrb
f1a54f6e3bf93c114c85b92cce41b5638559a583
use crate::pool::Pool; use crate::{block::Block, claim::Claim, txn::Txn}; use ritelinked::LinkedHashMap; use serde::{Deserialize, Serialize}; use std::collections::HashSet; #[allow(dead_code)] #[derive(Debug, Serialize, Deserialize)] pub struct AccountState { pub accounts_pk: LinkedHashMap<String, String>, ...
use crate::pool::Pool; use crate::{block::Block, claim::Claim, txn::Txn}; use ritelinked::LinkedHashMap; use serde::{Deserialize, Serialize}; use std::collections::HashSet; #[allow(dead_code)] #[derive(Debug, Serialize, Deserialize)] pub struct AccountState { pub accounts_pk: LinkedHashMap<String, String>, ...
pub fn pending_debits(&self, address: String) -> Option<u128> { let mut receipts = self.txn_pool.pending.clone(); receipts.retain(|_, v| v.sender_address == address); if receipts.is_empty() { return None; } else { let amounts: Vec<u128> = receipts.iter().ma...
rn v.txn_amount).collect(); let pending_credits = amounts.iter().sum(); Some(pending_credits) } }
function_block-function_prefixed
[ { "content": "pub fn check_collision(pointers: Vec<(String, u128)>) -> bool {\n\n pointers.len() > 1\n\n}\n\n\n", "file_path": "claim_concept/benches/my_benchmark.rs", "rank": 0, "score": 138297.49195315788 }, { "content": "pub fn generate_100000_claims() -> LinkedHashMap<String, Claim> {...
Rust
src/main.rs
mwalczyk/durer
8e7341b5c7ef6c83a7d419578aef5cc5a08d0972
mod color_palette; mod goal_mesh; mod half_edge; mod utils; use std::path::Path; use crate::color_palette::ColorPalette; use crate::goal_mesh::GoalMesh; use crate::utils::*; use bevy::prelude::*; use bevy::render::pass::ClearColor; use bevy_prototype_lyon::prelude::*; use clap; use log::info; use std::fs::File; str...
mod color_palette; mod goal_mesh; mod half_edge; mod utils; use std::path::Path; use crate::color_palette::ColorPalette; use crate::goal_mesh::GoalMesh; use crate::utils::*; use bevy::prelude::*; use bevy::render::pass::ClearColor; use bevy_prototype_lyon::prelude::*; use clap; use log::info; use std::fs::File; str...
fn setup( mut commands: Commands, mut meshes: ResMut<Assets<Mesh>>, mut materials: ResMut<Assets<ColorMaterial>>, args: Res<InputArgs>, ) { let mut goal_mesh = GoalMesh::from_obj(&Path::new(&args.path_to_obj[..]), 0.into()); let mut unfolded_positions = goal_mesh.unfold(); ...
get_matches(); let path_to_obj = matches .value_of("INPUT") .expect("This parameter should always be provided") .to_owned(); info!("Unfolding .obj: {:?}", path_to_obj); let resolution = matches .value_of("RESOLUTION") .unwrap() .parse::<u32>() ....
function_block-function_prefix_line
[ { "content": "use glam::Vec3;\n\nuse serde::{Deserialize, Serialize};\n\n\n\n/// A struct representing a color palette used for rendering an unfolded net.\n\n#[derive(Serialize, Deserialize, Debug)]\n\npub struct ColorPalette {\n\n // The background color (RGB)\n\n pub background: Vec3,\n\n\n\n // A li...
Rust
cowrpc/src/transport/sync/websocket_listener.rs
bcortier-devolutions/cowrpc-rs
5bd78690b84aa2033b4d83c26e35b04849842f55
use std; use std::net::SocketAddr; use mio::net::TcpListener as MioTcpListener; use mio::{net::TcpStream, Evented, Poll, PollOpt, Ready, Token}; use timer::Timer; use tungstenite::{ handshake::server::{NoCallback, ServerHandshake}, stream::Stream as StreamSwitcher, }; use tls_api::{TlsAcceptor, TlsAcceptorBuil...
use std; use std::net::SocketAddr; use mio::net::TcpListener as MioTcpListener; use mio::{net::TcpStream, Evented, Poll, PollOpt, Ready, Token}; use timer::Timer; use tungstenite::{ handshake::server::{NoCallback, ServerHandshake}, stream::Stream as StreamSwitcher, }; use tls_api::{TlsAcceptor, TlsAcceptorBuil...
fn set_tls_options(&mut self, tls_opt: TlsOptions) { let TlsOptions { tls_version: _, identity, root_certificates: _, ty, } = tls_opt; assert_eq!(ty, TlsOptionsType::Acceptor); match identity { Identity::Pkcs12(pkcs12) =>...
fn bind(addr: &SocketAddr) -> Result<Self> where Self: Sized { let listener = match MioTcpListener::bind(addr) { Ok(l) => l, Err(_) => return Err(TransportError::Other.into()), }; Ok(WebSocketListener { listener, tls_acceptor: None, tr...
function_block-full_function
[ { "content": "fn wrap_stream_async(tls_acceptor: &Option<NativeTlsAcceptor>, stream: TcpStream) -> CowFuture<WebSocketStream> {\n\n if let Some(ref acceptor) = tls_acceptor {\n\n match acceptor.accept(stream) {\n\n Ok(tls) => Box::new(ok(StreamSwitcher::Tls(tls))),\n\n Err(TlsHan...
Rust
src/views/view.rs
JakubKoralewski/mandelbrot-wgpu-rs
57385634f9c604a6fe354fa05004f58184c17d96
use std::path::Path; use std::sync::{Arc, Mutex}; use crate::utils::{ AtomicDevice, Position, POSITION_SIZE, Zoom, ZOOM_SIZE, WindowSize, WINDOW_SIZE_SIZE, Iterations, ITERATIONS_SIZE, VERTEX_SIZE, Julia, JULIA_SIZE }; use super::utils::ZOOM_SENSITIVITY; use std::ops::Deref; pub struct Buffers { pub window...
use std::path::Path; use std::sync::{Arc, Mutex}; use crate::utils::{ AtomicDevice, Position, POSITION_SIZE, Zoom, ZOOM_SIZE, WindowSize, WINDOW_SIZE_SIZE, Iterations, ITERATIONS_SIZE, VERTEX_SIZE, Julia, JULIA_SIZE }; use super::utils::ZOOM_SENSITIVITY; use std::ops::Deref; pub struct Buffers { pub window...
log::info!("Released left mouse button."); self.data().left_button_pressed = false; } } } fn iterations(&mut self, device: &AtomicDevice, y_delta: f32) -> wgpu::CommandBuffer { let mut iterations = self.data().iterations; iterations.iterations *= 0.99f32.powi(y_delta.signum() as i32); if iterati...
b struct FractalViewData { pub frag_shader_module: Arc<Mutex<wgpu::ShaderModule>>, pub render_pipeline: Arc<Mutex<wgpu::RenderPipeline>>, pub bind_group: Arc<Mutex<wgpu::BindGroup>>, pub bufs: Buffers, pub vs_module: Arc<wgpu::ShaderModule>, pub pipeline_layout: Arc<wgpu::PipelineLayout>, pub prev_position: Pos...
random
[ { "content": "pub fn create_buffer<T: 'static + Copy>(device: &wgpu::Device, value: T) -> wgpu::Buffer {\n\n\tdevice.create_buffer_mapped(\n\n\t\t1,\n\n\t\twgpu::BufferUsage::UNIFORM\n\n\t\t\t| wgpu::BufferUsage::COPY_DST\n\n\t).fill_from_slice(&[value])\n\n}\n\n\n\nlazy_static! {\n\n\tpub static ref WHOLE_VERT...
Rust
pleco/src/core/bitboard.rs
MakotoE/Pleco
278a73d7e0f0e52b397e16640c1f9f73db266e2c
extern crate rand; use super::sq::SQ; use super::bit_twiddles::*; use super::masks::*; use tools::prng::PRNG; use super::Player; use std::mem; use std::ops::*; use std::fmt; use std::hint::unreachable_unchecked; #[derive(Copy, Clone, Default, Hash, PartialEq, Eq, Debug)] #[repr(transparent)] pub struct BitBoard(pu...
extern crate rand; use super::sq::SQ; use super::bit_twiddles::*; use super::masks::*; use tools::prng::PRNG; use super::Player; use std::mem; use std::ops::*; use std::fmt; use std::hint::unreachable_unchecked; #[derive(Copy, Clone, Default, Hash, PartialEq, Eq, Debug)] #[repr(transparent)] pub struct BitBoard(pu...
f.min = min; self } pub fn pseudo_random(mut self, seed: u64) -> Self { self.seed = if seed == 0 {1} else {seed}; self.prng = PRNG::init(seed); self } fn go(&mut self) -> BitBoard { if self.rand == RandAmount::Singular { return BitBoar...
rand: RandAmount, max: u16, min: u16 } impl Default for RandBitBoard { fn default() -> Self { RandBitBoard { prng: PRNG::init(1), seed: 0, rand: RandAmount::Standard, max: 64, min: 1 } } } impl RandBitBoard { pub fn ...
random
[ { "content": "#[inline(always)]\n\npub fn pawn_attacks_from(sq: SQ, player: Player) -> u64 {\n\n debug_assert!(sq.is_okay());\n\n unsafe {\n\n *PAWN_ATTACKS_FROM.get_unchecked(player as usize).get_unchecked(sq.0 as usize)\n\n }\n\n}\n\n\n\n/// Returns if three Squares are in the same diagonal, f...
Rust
sos21-domain/src/model/form/item/checkbox.rs
sohosai/sos21-backend
f1883844b0e5c68d6b3f9d159c9268142abc81b4
use std::collections::HashSet; use crate::model::collection::{self, LengthBoundedVec}; use crate::model::form_answer::item::FormAnswerItemChecks; use serde::{ de::{self, Deserializer}, Deserialize, Serialize, }; use thiserror::Error; #[allow(clippy::module_inception)] pub mod checkbox; pub mod limit; pub us...
use std::collections::HashSet; use crate::model::collection::{self, LengthBoundedVec}; use crate::model::form_answer::item::FormAnswerItemChecks; use serde::{ de::{self, Deserializer}, Deserialize, Serialize, }; use thiserror::Error; #[allow(clippy::module_inception)] pub mod checkbox; pub mod limit; pub us...
; } } Ok(()) } } impl<'de> Deserialize<'de> for CheckboxFormItem { fn deserialize<D>(deserializer: D) -> Result<Self, D::Error> where D: Deserializer<'de>, { CheckboxFormItem::from_content(CheckboxFormItemContent::deserialize(deserializer)?) .map...
Err(CheckAnswerError { kind: CheckAnswerErrorKind::UnknownCheckboxId { id: check_id }, })
call_expression
[ { "content": "pub fn to_check_answer_error(err: form::item::CheckAnswerError) -> CheckAnswerError {\n\n match err.kind() {\n\n form::item::CheckAnswerErrorKind::MismatchedItemsLength => {\n\n CheckAnswerError::MismatchedItemsLength\n\n }\n\n form::item::CheckAnswerErrorKind::M...
Rust
src/simulation.rs
johanmallobakken/rust-hash-wheel-timer
a6795203850c9ad89513c1803fa637ee5a05e575
use super::*; use crate::{wheels::{cancellable::*, *}, thread_timer::{TimerRef, TimeRefEnum}}; use std::{ fmt::Debug, hash::Hash, rc::Rc, time::{Duration, SystemTime}, cell::RefCell, sync::{Arc, Mutex}, }; #[derive(Debug)] pub enum SimulationMsg<I, O, P> where I: Hash + Clone + Eq, O: Oneshot...
use super::*; use crate::{wheels::{cancellable::*, *}, thread_timer::{TimerRef, TimeRefEnum}}; use std::{ fmt::Debug, hash::Hash, rc::Rc, time::{Duration, SystemTime}, cell::RefCell, sync::{Arc, Mutex}, }; #[derive(Debug)] pub enum SimulationMsg<I, O, P> where I: Hash + Clone + Eq, O: Oneshot...
mut timer = SimulationTimer::for_uuid_closures(); for i in 1..num { let barrier = Arc::new(Mutex::new(false)); barriers.push(barrier.clone()); let id = Uuid::new_v4(); let timeout = fib_time(i); let mut counter: usize = 5; timer.schedule_ac...
> panic!( "Trying to insert periodic timer entry with 0ms period! {:?}", e ), Err(f) => panic!("Could not insert timer entry! {:?}", f), }, None => (), }, Err(f) => panic!("Co...
random
[ { "content": "/// A trait for timer entries that store their delay along the with the state\n\npub trait TimerEntryWithDelay: Debug {\n\n /// Returns the time until the timeout is supposed to be triggered\n\n fn delay(&self) -> Duration;\n\n}\n", "file_path": "src/wheels/mod.rs", "rank": 0, "s...
Rust
src/process.rs
kleimkuhler/cargo-hack
1aee68c0f68748d2b7b79454091038691037b000
use std::{ collections::HashMap, ffi::{OsStr, OsString}, fmt, path::Path, process::{Command, ExitStatus, Output}, rc::Rc, str, }; use anyhow::Context; use crate::{Args, Package, Result}; #[derive(Clone, Debug)] pub(crate) struct ProcessBuilder { program: Rc<OsStr>, leadi...
use std::{ collections::HashMap, ffi::{OsStr, OsString}, fmt, path::Path, process::{Command, ExitStatus, Output}, rc::Rc, str, }; use anyhow::Context; use crate::{Args, Package, Result}; #[derive(Clone, Debug)] pub(crate) struct ProcessBuilder { program: Rc<OsStr>, leadi...
pub(crate) fn from_args(program: OsString, args: &Args) -> Self { Self { program: Rc::from(program), leading_args: args.leading_args.clone(), trailing_args: args.trailing_args.clone(), args: Vec::new(), features: String::new(), e...
f { program: Rc::from(program), leading_args: Rc::from(&[][..]), trailing_args: Rc::from(&[][..]), args: Vec::new(), features: String::new(), env: HashMap::new(), verbose: false, } }
function_block-function_prefixed
[ { "content": "fn req_arg(arg: &str, subcommand: Option<&String>) -> Error {\n\n format_err!(\n\n \"\\\n\nThe argument '{0}' requires a value but none was supplied\n\n\n\nUSAGE:\n\n cargo hack{1} {0}\n\n\n\nFor more information try --help\n\n\",\n\n arg,\n\n if let Some(subcommand) = s...
Rust
lib/src/model/response/template/data.rs
beltram/stubr
c140fd6a0f32c8bccdd1f7c7c7fb18692f27eac3
use http_types::Method; use serde::Serialize; use serde_json::Value; use wiremock::Request; use super::req_ext::{Headers, Queries, RequestExt}; #[derive(Serialize)] pub struct HandlebarsData<'a> { request: RequestData<'a>, } #[derive(Serialize)] #[serde(rename_all = "camelCase")] struct RequestData<'a> { pat...
use http_types::Method; use serde::Serialize; use serde_json::Value; use wiremock::Request; use super::req_ext::{Headers, Queries, RequestExt}; #[derive(Serialize)] pub struct HandlebarsData<'a> { request: RequestData<'a>, } #[derive(Serialize)] #[serde(rename_all = "camelCase")] struct RequestData<'a> { pat...
#[test] fn should_not_take_request_port_when_absent() { let req = request("https://localhost", None, &[], None); assert!(RequestData::from(&req).port.is_none()); } #[test] fn should_take_request_method() { let req = request("https://localhost", Some(Method::Get), &[], None...
e, &[], None); assert_eq!(RequestData::from(&req).port, Some(8080)); let req = request("https://localhost:8081/api/pets", None, &[], None); assert_eq!(RequestData::from(&req).port, Some(8081)); }
function_block-function_prefixed
[ { "content": "fn req_header(uri: String, values: &[(&str, &str)]) -> Request<()> {\n\n let mut base = Request::get(uri);\n\n for (k, v) in values {\n\n base = base.header(*k, *v);\n\n }\n\n base.body(()).unwrap()\n\n}\n", "file_path": "lib/tests/record/req_headers.rs", "rank": 0, ...
Rust
askar-crypto/src/encrypt/crypto_box.rs
simnic/aries-askar
eafdc85e76f073426ea2ba57991cdf5d881b37a5
use crate::{ buffer::Writer, generic_array::{typenum::Unsigned, GenericArray}, }; use aead::AeadInPlace; use blake2::{digest::Update, digest::VariableOutput, VarBlake2b}; use crypto_box_rs::{self as cbox, SalsaBox}; use crate::{ alg::x25519::X25519KeyPair, buffer::{ResizeBuffer, SecretBytes, WriteBuf...
use crate::{ buffer::Writer, generic_array::{typenum::Unsigned, GenericArray}, }; use aead::AeadInPlace; use blake2::{digest::Update, digest::VariableOutput, VarBlake2b}; use crypto_box_rs::{self as cbox, SalsaBox}; use crate::{ alg::x25519::X25519KeyPair, buffer::{ResizeBuffer, SecretBytes, WriteBuf...
#[cfg(test)] mod tests { use super::*; use crate::buffer::SecretBytes; use crate::repr::{KeySecretBytes, ToPublicBytes}; #[test] fn crypto_box_round_trip_expected() { let sk = X25519KeyPair::from_secret_bytes(&hex!( "a8bdb9830f8790d242f66e04b11cc2a14c752a7b63c073f3c68e9adb151c...
pub fn crypto_box_seal_open( recip_sk: &X25519KeyPair, ciphertext: &[u8], ) -> Result<SecretBytes, Error> { let ephem_pk = X25519KeyPair::from_public_bytes(&ciphertext[..CBOX_KEY_LENGTH])?; let mut buffer = SecretBytes::from_slice(&ciphertext[CBOX_KEY_LENGTH..]); let nonce = crypto_box_seal_nonce(ep...
function_block-full_function
[ { "content": "/// Generate a new random nonce for crypto_box\n\npub fn crypto_box_random_nonce() -> Result<[u8; CBOX_NONCE_LENGTH], Error> {\n\n let mut nonce = [0u8; CBOX_NONCE_LENGTH];\n\n fill_random(&mut nonce);\n\n Ok(nonce)\n\n}\n\n\n", "file_path": "src/kms/envelope.rs", "rank": 1, "...
Rust
src/impls/rapier/nalgebra_impls.rs
SecretPocketCat/bevy-inspector-egui
9a7f0f9c4344f6d74b09d1462f5075f1d8277ffb
use bevy_egui::egui; use nalgebra::{ ArrayStorage, Complex, Const, Isometry, Matrix, Quaternion, SVector, Scalar, Translation, Unit, }; use crate::Inspectable; impl<T: Scalar + Inspectable, const R: usize, const C: usize> Inspectable for Matrix<T, Const<R>, Const<C>, ArrayStorage<T, R, C>> { type Attribut...
use bevy_egui::egui; use nalgebra::{ ArrayStorage, Complex, Const, Isometry, Matrix, Quaternion, SVector, Scalar, Translation, Unit, }; use crate::Inspectable; impl<T: Scalar + Inspectable, const R: usize, const C: usize> Inspectable for Matrix<T, Const<R>, Const<C>, ArrayStorage<T, R, C>> { type Attribut...
changed } } impl Inspectable for Unit<Complex<f32>> { type Attributes = (); fn ui(&mut self, ui: &mut egui::Ui, _: Self::Attributes, _: &crate::Context) -> bool { let mut angle = self.angle(); let changed = ui.drag_angle_tau(&mut angle).changed(); if changed { ...
if changed { let vec: bevy::math::Vec4 = quat.into(); let quat = Quaternion::<f32>::from_vector(vec.into()); let quat = Unit::<Quaternion<f32>>::new_normalize(quat); *self = quat; }
if_condition
[ { "content": "fn point_select(value: &mut Vec2, ui: &mut egui::Ui, options: Vec2dAttributes) -> bool {\n\n let range = match (options.min, options.max) {\n\n (Some(min), Some(max)) => min..=max,\n\n (Some(min), None) => min..=Vec2::splat(0.0),\n\n (None, Some(max)) => Vec2::splat(0.0)..=...
Rust
src/vendor/clap/src/app/macros.rs
ryoon/rustc-1.19.0
4ca47e69f710b93580101782576ebad2bef64749
macro_rules! remove_overriden { (@remove $_self:ident, $v:ident, $a:ident.$ov:ident) => { if let Some(ref ora) = $a.$ov() { vec_remove_all!($_self.$v, ora); } }; (@arg $_self:ident, $arg:ident) => { remove_overriden!(@remove $_self, required, $arg.requires); remov...
macro_rules! remove_overriden { (@remove $_self:ident, $v:ident, $a:ident.$ov:ident) => { if let Some(ref ora) = $a.$ov() { vec_remove_all!($_self.$v, ora); } }; (@arg $_self:ident, $arg:ident) => { remove_overriden!(@remove $_self, required, $arg.requires); remov...
!("macro=parse_positional!;"); validate_multiples!($_self, $p, $matcher); if !$_self.trailing_vals && ($_self.settings.is_set(AppSettings::TrailingVarArg) && $pos_counter == $_self.positionals.len()) { $_self.trailing_vals = true; } let _ = try!($_self...
st.extend(&grp.args); vec_remove!($me.blacklist, &$arg.name()); } } } }) } macro_rules! validate_multiples { ($_self:ident, $a:ident, $m:ident) => { debugln!("macro=validate_multiples!;"); if $m.contains(&$a.b.name) && !$a.b.settings.is_se...
random
[]
Rust
frugalos_mds/src/node/mod.rs
koba-e964/frugalos
ba3ea71010a2e88ac0ebed6a90a41615ddbd339b
#![allow(clippy::module_inception)] use fibers::sync::oneshot::Monitored; use frugalos_raft::NodeId; use libfrugalos::entity::object::{ DeleteObjectsByPrefixSummary, Metadata, ObjectId, ObjectPrefix, ObjectSummary, ObjectVersion, }; use libfrugalos::expect::Expect; use libfrugalos::time::Seconds; use raftlog::log::...
#![allow(clippy::module_inception)] use fibers::sync::oneshot::Monitored; use frugalos_raft::NodeId; use libfrugalos::entity::object::{ DeleteObjectsByPrefixSummary, Metadata, ObjectId, ObjectPrefix, ObjectSummary, ObjectVersion, }; use libfrugalos::expect::Expect; use libfrugalos::time::Seconds; use raftlog::log::...
bers_global::spawn(futures::lazy(move || { let proposal = Proposal::DeleteByPrefix(proposal_id, ObjectPrefix("abc".to_owned()), monitored); Ok(proposal.notify_committed(&[ObjectVersion(1)])) })); let summary = track!(fibers_global::execute(monitor))?; Ok(...
handle; mod node; type Reply<T> = Monitored<T, Error>; #[derive(Debug)] enum Proposal { Put(ProposalId, Reply<(ObjectVersion, Option<ObjectVersion>)>), Delete(ProposalId, Reply<Option<ObjectVersion>>), DeleteByPrefix( ProposalId, ObjectPrefix, Reply<DeleteObjectsByPrefixSummary>, ...
random
[ { "content": "pub fn to_rpc_error(e: Error) -> libfrugalos::Error {\n\n let kind = match *e.kind() {\n\n ErrorKind::InvalidInput => libfrugalos::ErrorKind::InvalidInput,\n\n ErrorKind::NotLeader => libfrugalos::ErrorKind::NotLeader,\n\n ErrorKind::Unexpected(v) => libfrugalos::ErrorKind:...
Rust
src/lib.rs
dfhoughton/pidgin
2de598056054b6a355445082738716e9f7b3ae7c
/*! This crate provides a library for generating efficient regular expressions represent a non-recursive grammar and a mechanism to build a parse tree from capturing groups in the expression. It uses the [`regex`](https://crates.io/crates/regex) crate for its parsing engine. # Usage This crate is [on crates.io](http...
/*! This crate provides a library for generating efficient regular expressions represent a non-recursive grammar and a mechanism to build a parse tre
whitespace vary assert!(matcher.is_match(" June 6, 1969 ")); // we made it case-insensitive assert!(matcher.is_match("june 6, 1969")); // but we want to respect word boundaries assert!(!matcher.is_match("jejune 6, 1969")); // we can inspect the parse tree let m = matcher.parse("2018/10/6").unwrap(); assert!(m.name...
e from capturing groups in the expression. It uses the [`regex`](https://crates.io/crates/regex) crate for its parsing engine. # Usage This crate is [on crates.io](https://crates.io/crates/pidgin) and can be used by adding `pidgin` to your dependencies in your project's `Cargo.toml`. ```toml [dependencies] pidgin = ...
random
[ { "content": "#[doc(hidden)]\n\npub fn left_pad(g: Grammar) -> Grammar {\n\n Grammar {\n\n name: None,\n\n flags: g.flags.clone(),\n\n stingy: g.stingy,\n\n lower_limit: None,\n\n upper_limit: None,\n\n sequence: vec![\n\n Expression::Part(String::from(r\"...
Rust
laythe_lib/src/global/primitives/method.rs
Laythe-lang/Laythe
f3c33ad4d07a01d9499355c3f1fcd58c5f22c3df
use crate::{ native, support::{export_and_insert, load_class_from_module}, StdResult, }; use laythe_core::{ hooks::{GcHooks, Hooks}, managed::{Gc, GcObj, GcStr, Trace}, module::Module, object::{LyNative, Native, NativeMetaBuilder}, signature::{Arity, ParameterBuilder, ParameterKind}, val, value::Val...
use crate::{ native, support::{export_and_insert, load_class_from_module}, StdResult, }; use laythe_core::{ hooks::{GcHooks, Hooks}, managed::{Gc, GcObj, GcStr, Trace}, module::Module, object::{LyNative, Native, NativeMetaBuilder}, signature::{Arity, ParameterBuilder, ParameterKind}, val, value::Val...
} }
let fun = test_fun(&hooks.as_gc(), "example", "module"); let class = hooks.manage_obj(Class::bare(hooks.manage_str("exampleClass".to_string()))); let closure = hooks.manage_obj(Closure::without_upvalues(fun)); let instance = hooks.manage_obj(Instance::new(class)); let method = hooks.manage_obj(M...
function_block-function_prefix_line
[]
Rust
src/main.rs
nwtnni/rainbow
17a7b38f500822e8ab6187389e4d13ec6d142473
#![feature(min_const_generics)] use std::convert::TryFrom as _; use std::fs; use std::io; use std::path; use std::process; use std::str; use anyhow::anyhow; use anyhow::Context as _; use structopt::StructOpt; static SEEDS_05: &str = include_str!("../data/passwords-05.txt"); static SEEDS_06: &str = include_str!("../d...
#![feature(min_const_generics)] use std::convert::TryFrom as _; use std::fs; use std::io; use std::path; use std::process; use std::str; use anyhow::anyhow; use anyhow::Context as _;
| _ => return Err(anyhow!("Only plaintext lengths of 5 or 6 bytes are supported currently for demonstration")), } } | Command::Search { path, pass_length, hash } => { let mut file = fs::OpenOptions::new() .read(true) .open(&path) .with_context(|| anyhow!("Co...
use structopt::StructOpt; static SEEDS_05: &str = include_str!("../data/passwords-05.txt"); static SEEDS_06: &str = include_str!("../data/passwords-06.txt"); #[derive(StructOpt)] enum Command { Create { #[structopt(long)] chain_count: usize, #[structopt(long)] ...
random
[ { "content": "#![feature(min_const_generics)]\n\n#![feature(result_copied)]\n\n\n\nuse std::collections::HashMap;\n\nuse std::io;\n\nuse std::io::Write as _;\n\n\n\nuse byteorder::ReadBytesExt as _;\n\nuse byteorder::WriteBytesExt as _;\n\nuse crossbeam::channel;\n\nuse rayon::prelude::*;\n\n\n\n#[derive(Clone,...
Rust
src/crypto/tpm.rs
petreeftime/aws-nitro-enclaves-cose
e8f84fcb87c5a866cbde78cfa13af64040cdcc35
use std::{cell::RefCell, convert::TryInto}; use openssl::hash::MessageDigest; use tss_esapi::{ constants::{ self as tpm_constants, response_code::{FormatOneResponseCode, Tss2ResponseCode}, }, handles::KeyHandle, interface_types::algorithm::HashingAlgorithm, tss2_esys::{TPMT_PUBLIC...
use std::{cell::RefCell, convert::TryInto}; use openssl::hash::MessageDigest; use tss_esapi::{ constants::{ self as tpm_constants, response_code::{FormatOneResponseCode, Tss2ResponseCode}, }, handles::KeyHandle, interface_types::algorithm::HashingAlgorithm, tss2_esys::{TPMT_PUBLIC...
pub fn new(mut context: Context, key_handle: KeyHandle) -> Result<TpmKey, CoseError> { let (key_public, _, _) = context .read_public(key_handle) .map_err(CoseError::TpmError)?; let (parameters, hash_alg, key_length) = TpmKey::public_to_parameters(key_public...
fn public_to_parameters( public: TPMT_PUBLIC, ) -> Result<((SignatureAlgorithm, MessageDigest), HashingAlgorithm, usize), CoseError> { match public.type_ { tpm_constants::tss::TPM2_ALG_ECDSA => {} tpm_constants::tss::TPM2_ALG_ECC => {} type_ => { r...
function_block-full_function
[ { "content": "/// Follows the recommandations put in place by the RFC and doesn't deal with potential\n\n/// mismatches: https://tools.ietf.org/html/rfc8152#section-8.1.\n\npub fn ec_curve_to_parameters(\n\n curve_name: Nid,\n\n) -> Result<(SignatureAlgorithm, MessageDigest, usize), CoseError> {\n\n let s...
Rust
program/src/processor/new_order.rs
solindex/orderbook
ed5e4246aa8ec5b5eef84aa0982bc50622cb9b5d
use solindex_utils::{BorshSize, InstructionsAccount}; use borsh::{BorshDeserialize, BorshSerialize}; use solana_program::{ account_info::{next_account_info, AccountInfo}, entrypoint::ProgramResult, msg, program_error::ProgramError, pubkey::Pubkey, }; use crate::{ error::AoError, orderbook...
use solindex_utils::{BorshSize, InstructionsAccount}; use borsh::{BorshDeserialize, BorshSerialize}; use solana_program::{ account_info::{next_account_info, AccountInfo}, entrypoint::ProgramResult, msg, program_error::ProgramError, pubkey::Pubkey, }; use crate::{ error::AoError, orderbook...
b: 'a>( accounts: &Accounts<'a, AccountInfo<'b>>, market_state: &MarketState, ) -> ProgramResult { check_account_key( accounts.event_queue, &market_state.event_queue, AoError::WrongEventQueueAccount, )?; check_account_key(accounts.bids, &market_state.bids, AoError::WrongBidsA...
function_block-function_prefixed
[ { "content": "pub fn check_signer(account: &AccountInfo) -> ProgramResult {\n\n if !(account.is_signer) {\n\n return Err(ProgramError::MissingRequiredSignature);\n\n }\n\n Ok(())\n\n}\n\n\n", "file_path": "program/src/utils.rs", "rank": 0, "score": 249942.123912845 }, { "cont...
Rust
pvnf/rdr/src/lib.rs
jethrosun/NetBricks
1b8160ffcc09a03e0321a5f44a695a1d264d575f
#![feature(box_syntax)] #![feature(asm)] extern crate e2d2; extern crate failure; extern crate headless_chrome; extern crate rshttp; extern crate rustc_serialize; extern crate serde_json; extern crate time; extern crate tiny_http; use crate::utils::*; use e2d2::allocators::CacheAligned; use e2d2::headers::{IpHeader,...
#![feature(box_syntax)] #![feature(asm)] extern crate e2d2; extern crate failure; extern crate headless_chrome; extern crate rshttp; extern crate rustc_serialize; extern crate serde_json; extern crate time; extern crate tiny_http; use crate::utils::*; use e2d2::allocators::CacheAligned; use e2d2::headers::{IpHeader,...
pub fn rdr<T: 'static + Batch<Header = NullHeader>, S: Scheduler + Sized>( parent: T, _sched: &mut S, ) -> CompositionBatch { let param = read_setup_param("/home/jethros/setup".to_string()).unwrap(); let num_of_users = rdr_retrieve_users(param.setup).unwrap(); let rdr_users = rdr_read_rand_seed(num...
function_block-full_function
[ { "content": "/// Test for the validator network function to schedule pipelines.\n\npub fn validator_test<S: Scheduler + Sized>(ports: Vec<CacheAligned<PortQueue>>, sched: &mut S) {\n\n for port in &ports {\n\n println!(\n\n \"Receiving port {} rxq {} txq {}\",\n\n port.port.mac_...
Rust
src/common/novaseq_run.rs
czbiohub/bcl2fastr
b9d990076ef58e1ca48552fc5b82dbf63e2ba734
use std::collections::HashMap; use std::path::PathBuf; use log::{debug, info}; use rayon::prelude::*; use crate::cbcl_header_decoder::CBCLHeader; use crate::filter_decoder::{filter_decoder, Filter}; use crate::locs_decoder::{locs_decoder, Locs}; use crate::run_info_parser::{parse_run_info, RunInfo}; pub struct Nov...
use std::collections::HashMap; use std::path::PathBuf; use log::{debug, info}; use rayon::prelude::*; use crate::cbcl_header_decoder::CBCLHeader; use crate::filter_decoder::{filter_decoder, Filter}; use crate::locs_decoder::{locs_decoder, Locs}; use crate::run_info_parser::{parse_run_info, RunInfo}; pub struct Nov...
#[test] fn test_index_run() { let run_path = PathBuf::from("test_data/190414_A00111_0296_AHJCWWDSXX"); let novaseq_run = NovaSeqRun::read_path(run_path, true).unwrap(); assert_eq!(novaseq_run.run_id, "@A00111:296:HJCWWDSXX"); } #[test] #[should_panic(expected = r#"No such...
fn test_run() { let run_path = PathBuf::from("test_data/190414_A00111_0296_AHJCWWDSXX"); let novaseq_run = NovaSeqRun::read_path(run_path, false).unwrap(); assert_eq!(novaseq_run.run_id, "@A00111:296:HJCWWDSXX"); }
function_block-full_function
[]
Rust
containrs/oci-runtime/src/v1/spec.rs
daniel5151/iotedge
74b4a38c579961f0b37449cf9e65c1c809e7918e
use serde::{Deserialize, Serialize}; use oci_common::types::Annotations; pub mod linux; pub mod process; pub mod solaris; pub mod windows; use linux::*; use process::*; use solaris::*; use windows::*; #[derive(Debug, Serialize, Deserialize, PartialEq, Eq, Clone)] pub struct Spec { #[serde(rename = ...
use serde::{Deserialize, Serialize}; use oci_common::types::Annotations; pub mod linux; pub mod process; pub mod solaris; pub mod windows; use linux::*; use process::*; use solaris::*; use windows::*; #[derive(Debug, Serialize, Deserialize, PartialEq, Eq, Clone)] pub struct Spec { #[serde(rename = ...
Option::is_none")] pub type_: Option<String>, #[serde(rename = "source", skip_serializing_if = "Option::is_none")] pub source: Option<String>, #[serde(rename = "options", skip_serializing_if = "Option::is_none")] pub options: Option<Vec<String>>, } impl Mount { pub fn new_base(de...
is_none")] pub linux: Option<Linux>, #[serde(rename = "solaris", skip_serializing_if = "Option::is_none")] pub solaris: Option<Solaris>, #[serde(rename = "windows", skip_serializing_if = "Option::is_none")] pub windows: Option<Windows>, } impl Spec { pub fn new_base() -> Spe...
random
[ { "content": "pub fn get_proxy_uri(https_proxy: Option<String>) -> Result<Option<Uri>, Error> {\n\n let proxy_uri = https_proxy\n\n .or_else(|| env::var(\"HTTPS_PROXY\").ok())\n\n .or_else(|| env::var(\"https_proxy\").ok());\n\n let proxy_uri = match proxy_uri {\n\n None => None,\n\n ...
Rust
src/objects/plane.rs
ThomasBollmeier/umbralux
44c8a324dc88f60a493f71443741e0f0d030ce64
use std::any::Any; use std::cell::RefCell; use std::ops::Deref; use crate::core::{Point, Vector}; use crate::features::material::{Material, MaterialBuilder}; use crate::matrix::Matrix; use crate::objects::object3d::Object3D; use crate::objects::ray::Ray; pub struct Plane { transformation: RefCell<Matrix<f64>>, ...
use std::any::Any; use std::cell::RefCell; use std::ops::Deref; use crate::core::{Point, Vector}; use crate::features::material::{Material, MaterialBuilder}; use crate::matrix::Matrix; use crate::objects::object3d::Object3D; use crate::objects::ray::Ray; pub struct Plane { transformation: RefCell<Matrix<f64>>, ...
#[test] fn a_ray_intersecting_a_plane_from_above() { let ray= Rc::new(Ray::new(Point::new(0.0, 1.0, 0.0), Vector::new(0.0, -1.0, 1.0))); test_intersection(&ray, vec![1.0]); } #[test] fn a_ray_intersecting_a_plane_from_below() { let ray= Rc::new(Ray:...
fn intersect_with_a_ray_coplanar_to_plane() { let ray = Rc::new(Ray::new(Point::new(0.0, 0.0, 0.0), Vector::new(0.0, 0.0, 1.0))); test_intersection(&ray, vec![]); }
function_block-function_prefix_line
[ { "content": "pub fn find_many_intersections(ray: &Rc<Ray>, partners: &Vec<Rc<dyn Object3D>>) -> Vec<Intersection> {\n\n let mut ret: Vec<Intersection> = vec![];\n\n\n\n for partner in partners {\n\n let mut intersections = find_intersections(ray, partner);\n\n ret.append(&mut intersections)...
Rust
src/section/github.rs
furiosa-ai/color-eyre
472997e9d6911452876032c0db1f9601c70fd91a
use crate::writers::DisplayExt; use backtrace::Backtrace; use std::{fmt, panic::Location}; #[cfg(feature = "capture-spantrace")] use tracing_error::SpanTrace; use url::Url; type Display<'a> = Box<dyn std::fmt::Display + Send + Sync + 'a>; pub(crate) struct IssueSection<'a> { url: &'a str, msg: &'a str, lo...
use crate::writers::DisplayExt; use backtrace::Backtrace; use std::{fmt, panic::Location}; #[cfg(feature = "capture-spantrace")] use tracing_error::SpanTrace; use url::Url; type Display<'a> = Box<dyn std::fmt::Display + Send + Sync + 'a>; pub(crate) struct IssueSection<'a> { url: &'a str, msg: &'a str, lo...
} struct ConsoleSection<T>(T); impl<T> fmt::Display for ConsoleSection<T> where T: fmt::Display, { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { (&self.0).with_header("```\n").with_footer("\n```").fmt(f) } } struct Collapsed<T>(T); impl<T> fmt::Display for Collapsed<T> where T:...
ew(); let f = &mut out; writeln!(f, "|key|value|").expect("writing to a string doesn't panic"); writeln!(f, "|--|--|").expect("writing to a string doesn't panic"); for (key, value) in self.metadata { writeln!(f, "|**{}**|{}|", key, value).expect("writing to a string doesn't...
function_block-function_prefixed
[ { "content": "#[rustfmt::skip]\n\n#[tracing::instrument]\n\nfn get_error(msg: &'static str) -> Report {\n\n\n\n #[rustfmt::skip]\n\n #[inline(never)]\n\n fn create_report(msg: &'static str) -> Report {\n\n Report::msg(msg)\n\n .note(\"note\")\n\n .warning(\"warning\")\n\n ...
Rust
src/cryptengine.rs
addam128/azkaban
8f920249273274a89d633145e1b3f4d5b51950dd
use tokio::fs::{File, OpenOptions}; use tokio::io::AsyncWriteExt; use ring::aead::{self, NONCE_LEN, Nonce, Aad}; use ring::pbkdf2; use protobuf::{CodedInputStream, CodedOutputStream, Message}; use indicatif::{MultiProgress, ProgressBar}; use std::{ffi::OsStr, path::{Path, PathBuf}, str::FromStr}; use std::sync::Arc; ...
use tokio::fs::{File, OpenOptions}; use tokio::io::AsyncWriteExt; use ring::aead::{self, NONCE_LEN, Nonce, Aad}; use ring::pbkdf2; use protobuf::{CodedInputStream, CodedOutputStream, Message}; use indicatif::{MultiProgress, ProgressBar}; use std::{ffi::OsStr, path::{Path, PathBuf}, str::FromStr}; use std::sync::Arc; ...
); Ok(()) }
match Arc::get_mut(&mut nonce) { Some(bytes) => { bytes }, None => { return Err(utils::Error::SyncError);} }
if_condition
[ { "content": "fn increase_u8_array(mem: &mut [u8]) -> () {\n\n\n\n let mut idx = mem.len() - 1; // start from last byte\n\n\n\n loop {\n\n mem[idx] += 1; // increase actual byte\n\n\n\n match mem[idx] {\n\n 0 => { // if byte overflows, propagate\n\n match idx {\n\n ...
Rust
src/router/request_matcher/method.rs
ptondereau/libredirectionio
fb48a34078393eda9d5ccf23ae1721e61be81124
use crate::http::Request; use crate::router::request_matcher::{HeaderMatcher, RequestMatcher}; use crate::router::trace::TraceInfo; use crate::router::{Route, RouteData, Trace}; use std::collections::HashMap; #[derive(Debug, Clone)] pub struct MethodMatcher<T: RouteData> { methods: HashMap<String, Box<dyn RequestM...
use crate::http::Request; use crate::router::request_matcher::{HeaderMatcher, RequestMatcher}; use crate::router::trace::TraceInfo; use crate::router::{Route, RouteData, Trace}; use std::collections::HashMap; #[derive(Debug, Clone)] pub struct MethodMatcher<T: RouteData> { methods: HashMap<String, Box<dyn RequestM...
her(), count: 0, } } } impl<T: RouteData> MethodMatcher<T> { pub fn create_sub_matcher() -> Box<dyn RequestMatcher<T>> { Box::new(HeaderMatcher::default()) } }
; } } } } } fn remove(&mut self, id: &str) -> bool { let mut removed = false; if self.any_method.remove(id) { self.count -= 1; return true; } self.methods.retain(|_, matcher| { removed...
random
[ { "content": "pub trait RouteData: Debug + Clone + Send + Sync + 'static {}\n\n\n\n#[derive(Serialize, Deserialize, Debug, Clone)]\n\npub struct Route<T: RouteData> {\n\n handler: T,\n\n scheme: Option<String>,\n\n host: Option<StaticOrDynamic>,\n\n methods: Option<Vec<String>>,\n\n path_and_quer...
Rust
src/index/rw/mod.rs
menshikh-iv/granne
fe2fe5aca4be879be8cbaf4fc34a5abf6ed2593d
#![allow(missing_docs)] use super::*; use parking_lot::{self, RwLock}; use std::fs::File; use std::io::{BufWriter, Seek, Write}; use crate::io::Writeable; use crate::slice_vector::FixedWidthSliceVector; mod rw_lock_slice_vector; pub struct RwGranneBuilder<Elements: ExtendableElementContainer + Writeable> { lay...
#![allow(missing_docs)] use super::*; use parking_lot::{self, RwLock}; use std::fs::File; use std::io::{BufWriter, Seek, Write}; use crate::io::Writeable; use crate::slice_vector::FixedWidthSliceVector; mod rw_lock_slice_vector; pub struct RwGranneBuilder<Elements: ExtendableElementContainer + Writeable> { lay...
); io::write_index(&layers, index_file) } pub fn insert(self: &Self, element: Elements::InternalElement) -> Option<usize> { self.insert_batch(vec![element]).pop() } pub fn insert_batch(self: &Self, mut elements_to_insert: Vec<Elements::InternalElement>) -> Vec<usize> { if self....
} else { vec![] }; let layers: Layers = Layers::FixWidth(layers.iter().map(|layer| layer.borrow()).collect()
function_block-random_span
[ { "content": "fn build_and_search<Elements: ElementContainer + Sync + Send + Clone>(elements: Elements) {\n\n let mut builder = GranneBuilder::new(BuildConfig::default().num_neighbors(20).max_search(20), elements);\n\n\n\n builder.build();\n\n let index = builder.get_index();\n\n\n\n verify_search(&...
Rust
ogu-lang/src/backend/modules/symbols/exprs/mod.rs
lnds/Ogu
881ec221d7cc735f43753c8cd91b9b88e093a091
use std::ops::Deref; use crate::backend::modules::symbols::exprs::arithmetics::ArithmeticExpr; use crate::backend::modules::symbols::exprs::case_expr::CaseExpr; use crate::backend::modules::symbols::exprs::dict_expr::DictExpr; use crate::backend::modules::symbols::exprs::do_expr::DoExpr; use crate::backend::modules::s...
use std::ops::Deref; use crate::backend::modules::symbols::exprs::arithmetics::ArithmeticExpr; use crate::backend::modules::symbols::exprs::case_expr::CaseExpr; use crate::backend::modules::symbols::exprs::dict_expr::DictExpr; use crate::backend::modules::symbols::exprs::do_expr::DoExpr; use crate::backend::modules::s...
OptSymbolTuple> { args.iter() .map(|(a, b)| (a.clone().map(|e| e.into()), b.into())) .collect() } fn vec_eqs_into(eqs: &[Equation]) -> Vec<Box<dyn Symbol>> { eqs.iter().map(|eq| eq.into()).collect() } fn vec_recur_val_into(eqs: &[RecurValue]) -> Vec<Box<dyn Symbol>> { eqs.iter().map(|eq| e...
ake_box(name, args, expr), _e => { todo!("not implemented for {:?}", _e); } } } } fn vec_exprs_into(args: &[Expression]) -> Vec<Box<dyn Symbol>> { args.iter().map(|a| a.into()).collect() } fn vec_lambda_args_into(args: &[LambdaArg]) -> Vec<Box<dyn Symbol>> { ...
random
[ { "content": "fn check_can_replace_args(expr_name: &str, own_args: &SymbolVec, args: &SymbolVec) -> Result<()> {\n\n if own_args.len() != args.len() {\n\n bail!(\"wrong cantity of arguments passed in {}. | own_args = {:?}, args = {:?}\", expr_name, own_args, args);\n\n }\n\n for (a, b) in own_ar...
Rust
ch2-packet-capture/src/main.rs
guricerin/net-programming-with-rust
0933fd3d39fed5ab2d4ff53b3c9e9869c2bd688a
use anyhow::{anyhow, Context, Result}; use env_logger; use log::info; use pnet::{ datalink::{self, Channel::Ethernet}, packet::{ ethernet::{EtherTypes, EthernetPacket}, ip::IpNextHeaderProtocols, ipv4::Ipv4Packet, ipv6::Ipv6Packet, tcp::TcpPacket, udp::UdpPacket, ...
use anyhow::{anyhow, Context, Result}; use env_logger; use log::info; use pnet::{ datalink::{self, Channel::Ethernet}, packet::{ ethernet::{EtherTypes, EthernetPacket}, ip::IpNextHeaderProtocols, ipv4::Ipv4Packet, ipv6::Ipv6Packet, tcp::TcpPacket, udp::UdpPacket, ...
n!(); }
turn Err(anyhow!("Unhandled channel type")), Err(e) => { let msg = format!("Failed to create datalink channel {}", e); return Err(anyhow!(msg)); } }; loop { match rx.next() { Ok(frame) => { let frame = ...
random
[ { "content": "fn receive_packets(tr: &mut TransportReceiver, packet_info: &PacketInfo) -> Result<()> {\n\n let mut reply_ports = vec![];\n\n let mut packet_iter = transport::tcp_packet_iter(tr);\n\n\n\n loop {\n\n // ターゲットからの通信パケット\n\n let tcp_packet = match packet_iter.next() {\n\n ...
Rust
src/table.rs
ccie18473/AMSPoker-v3a
5493528688fcec028c4c863449fb7e96ca0aa35b
use crate::prelude::*; const CARD_DECK_POS: usize = 0; const CARD1_POS: usize = 1; const CARD2_POS: usize = 2; const CARD3_POS: usize = 3; const CARD4_POS: usize = 4; const CARD5_POS: usize = 5; const BET_BTN_POS: usize = 21; const BET_MAX_BTN_POS: usize = 22; const RETRY_BTN_POS: usize = 23; const CREDIT_BTN_POS: us...
use crate::prelude::*; const CARD_DECK_POS: usize = 0; const CARD1_POS: usize = 1; const CARD2_POS: usize = 2; const CARD3_POS: usize = 3; const CARD4_POS: usize = 4; const CARD5_POS: usize = 5; const BET_BTN_POS: usize = 21; const BET_MAX_BTN_POS: usize = 22; const RETRY_BTN_POS: usize = 23; const CREDIT_BTN_POS: us...
} else if self.table_pos(pos.x, pos.y) == BET_BTN_POS { if self.game.state() == 1 { if self.game.panel.bets < 10 { TButton::blink(ctx, pos.x, pos.y); self.game.panel.credits -= 1; self.game.panel.bets += 1;...
if self.game.state() == 2 { TCard::card_selected(&mut self.game.card5); self.game.render(ctx); }
if_condition
[ { "content": "// FullHouse\n\npub fn full_house(mut nmbr: [usize; 52]) -> bool {\n\n let mut trio: bool = false;\n\n let mut pair: bool = false;\n\n let mut a: usize = 0;\n\n let mut b: usize = 0;\n\n let mut c: usize = 0;\n\n\n\n for i in 0..13 {\n\n if (nmbr[i] == 1) && (nmbr[i + 13] ...
Rust
src/action/version.rs
vks/ffsend-api
28d00c7cd47dd5db06a4c7ece3afe2b6b9e66231
use reqwest::Client; use url::Url; use crate::api; use crate::api::request::ensure_success; const VERSION_ENDPOINT: &str = "__version__"; #[cfg(feature = "send2")] const V2_PROBE_ENDPOINT: &str = "jsconfig.js"; #[cfg(feature = "send3")] const V3_PROBE_ENDPOINT: &str = "app.webmanifest"; pub struct Version { ...
use reqwest::Client; use url::Url; use crate::api; use crate::api::request::ensure_success; const VERSION_ENDPOINT: &str = "__version__"; #[cfg(feature = "send2")] const V2_PROBE_ENDPOINT: &str = "jsconfig.js"; #[cfg(feature = "send3")] const V3_PROBE_ENDPOINT: &str = "app.webmanifest"; pub struct Version { ...
fn exists(&self, client: &Client, endpoint: &str) -> bool { let url = self.host.join(endpoint).expect("invalid host"); client .get(url) .send() .map(|r| r.status()) .map(|s| s.is_success() || s.is_red...
fn probe(&self, client: &Client) -> Result<api::Version, Error> { #[cfg(feature = "send3")] { if self.exists(client, V3_PROBE_ENDPOINT) { return Ok(api::Version::V3); } } #[cfg(feature = "send2")] { if self.ex...
function_block-full_function
[ { "content": "/// Do a new request, and extract the nonce from a header in the given\n\n/// response.\n\npub fn request_nonce(client: &Client, url: Url) -> Result<Vec<u8>, NonceError> {\n\n // Make the request\n\n let response = client.get(url).send().map_err(|_| NonceError::Request)?;\n\n\n\n // Ensur...
Rust
src/timer.rs
klimatt/stm32g4xx-hal
7328745aed0a5883b11066237aa8c416cf81876c
use cortex_m::peripheral::syst::SystClkSource; use cortex_m::peripheral::SYST; use hal::timer::{CountDown, Periodic}; use nb; use void::Void; use crate::rcc::Rcc; use crate::stm32::{TIM1, TIM14, TIM15, TIM16, TIM17, TIM2, TIM3, TIM6, TIM7}; use crate::time::{Hertz, MicroSecond}; pub struct Timer<TIM> { clk: Hert...
use cortex_m::peripheral::syst::SystClkSource; use cortex_m::peripheral::SYST; use hal::timer::{CountDown, Periodic}; use nb; use void::Void; use crate::rcc::Rcc; use crate::stm32::{TIM1, TIM14, TIM15, TIM16, TIM17, TIM2, TIM3, TIM6, TIM7}; use crate::time::{Hertz, MicroSecond}; pub struct Timer<TIM> { clk: Hert...
pub fn listen(&mut self) { self.tim.enable_interrupt() } pub fn unlisten(&mut self) { self.tim.disable_interrupt() } } impl CountDown for Timer<SYST> { type Time = MicroSecond; fn start<T>(&mut self, timeout: T) where T: Into<MicroSecond>, { ...
pub fn syst(mut syst: SYST, rcc: &mut Rcc) -> Self { syst.set_clock_source(SystClkSource::Core); Timer { tim: syst, clk: rcc.clocks.apb_tim_clk, } }
function_block-full_function
[ { "content": "pub trait Pins<TIM> {\n\n fn setup(&self);\n\n}\n\n\n\nimpl Pins<TIM1> for (PA8<DefaultMode>, PA9<DefaultMode>) {\n\n fn setup(&self) {\n\n self.0.set_alt_mode(AltFunction::AF2);\n\n self.1.set_alt_mode(AltFunction::AF2);\n\n }\n\n}\n\n\n\nimpl Pins<TIM2> for (PA0<DefaultMod...
Rust
src/qr_segment_advanced.rs
magiclen/qrcode-segments-optimizer
27461683f82bcf9f9c33e30cca7509198a1e4422
use alloc::string::String; use alloc::vec::Vec; use crate::qrcode_generator::qrcodegen::{QrCodeEcc, QrSegment, QrSegmentMode, Version}; #[cfg(feature = "kanji")] use crate::qrcode_generator::qrcodegen::BitBuffer; #[cfg(feature = "kanji")] const MODE_TYPES: [QrSegmentMode; 4] = [ QrSegmentMode::Byte, QrSegm...
use alloc::string::String; use alloc::vec::Vec; use crate::qrcode_generator::qrcodegen::{QrCodeEcc, QrSegment, QrSegmentMode, Version}; #[cfg(feature = "kanji")] use crate::qrcode_generator::qrcodegen::BitBuffer; #[cfg(feature = "kanji")] const MODE_TYPES: [QrSegmentMode; 4] = [ QrSegmentMode::Byte, QrSegm...
} QrSegment::new(QrSegmentMode::Kanji, code_points.len(), bb.0) } #[cfg(not(feature = "kanji"))] fn make_kanji(_code_points: &[char]) -> QrSegment { unreachable!() } #[cfg(feature = "kanji")] fn is_kanji(c: char) -> bool { let c = c as usize; c < UNICODE_TO_QR_KANJI.len() && UNICODE_TO_QR_KANJI[c]...
E_TO_QR_KANJI[c as usize]; if val == -1 { panic!("String contains non-kanji-mode characters"); } bb.append_bits(val as u32, 13);
function_block-random_span
[ { "content": "#[inline]\n\npub fn make_segments_from_url(url: &Url, ecc: QrCodeEcc) -> Result<Vec<QrSegment>, QRCodeError> {\n\n let url_str = url.as_str();\n\n\n\n let mut qrcode_url: Cow<str> = Cow::Borrowed(url_str);\n\n\n\n if let Cow::Owned(scheme) = url.scheme().cow_to_ascii_uppercase() {\n\n ...
Rust
src/param.rs
blu-dev/prc-rs
b7b2cd16ffc501b6142950dcdbc8dcf4e11914f1
use hash40::Hash40; use serde::{Deserialize, Serialize}; use std::collections::HashMap; use std::convert::{TryFrom, TryInto}; #[doc(hidden)] pub const MAGIC: &[u8; 8] = b"paracobn"; const UNWRAP_ERR: &str = "Tried to unwrap param into inconsistent type"; #[derive(Debug, Serialize, Deserialize, Clone, PartialEq)] pub ...
use hash40::Hash40; use serde::{Deserialize, Serialize}; use std::collections::HashMap; use std::convert::{TryFrom, TryInto}; #[doc(hidden)] pub const MAGIC: &[u8; 8] = b"paracobn"; const UNWRAP_ERR: &str = "Tried to unwrap param into inconsistent type"; #[derive(Debug, Serialize, Deserialize, Clone, PartialEq)] pub ...
pub fn unwrap_as_hashmap_ref(&self) -> HashMap<Hash40, &ParamKind> { TryInto::<&ParamStruct>::try_into(self) .unwrap() .0 .iter() .map(|(h, p)| (*h, p)) .collect::<HashMap<_, _>>() } pub fn unwrap_as_hashmap_mut(&mut ...
pub fn unwrap_as_hashmap(self) -> HashMap<Hash40, ParamKind> { TryInto::<ParamStruct>::try_into(self) .unwrap() .0 .drain(..) .collect::<HashMap<_, _>>() }
function_block-full_function
[ { "content": "/// Attempts to write a param file into the given writer (requires [Seek]).\n\n/// Returns nothing if successful, otherwise an [Error].\n\npub fn write_stream<W>(writer: &mut W, param_struct: &param::ParamStruct) -> Result<(), Error>\n\nwhere\n\n W: Write + Seek,\n\n{\n\n asm::assemble(write...
Rust
gvc/src/lib.rs
RobWalt/rustgym
b4dc47cb36d59c157095563857b0ac5ca62c68b3
use gvc_sys::*; use rustgym_util::*; use std::collections::HashMap; use std::ffi::c_void; use std::ffi::CString; type Attrs = Vec<(CString, CString, CString)>; fn make_attrs(pairs: Vec<(&str, &str)>) -> Attrs { pairs .into_iter() .map(|p| { ( CString::new(p.0.to_string(...
use gvc_sys::*; use rustgym_util::*; use std::collections::HashMap; use std::ffi::c_void; use std::ffi::CString; type Attrs = Vec<(CString, CString, CString)>; fn make_attrs(pairs: Vec<(&str, &str)>) -> Attrs { pairs .into_iter() .map(|p| { ( CString::new(p.0.to_string(...
; } } } } pub fn render(&self, filename: &str) { unsafe { gvLayout( self.gvc, self.graph, CString::new("dot").expect("dot").into_raw(), ); gvRenderFilename( self.gvc, ...
agsafeset( self.nodes[i] as *mut c_void, key.into_raw(), value.into_raw(), CString::new("").expect("default").into_raw(), )
call_expression
[]
Rust
src/lib.rs
blackredscarf/raftfwk
5d1f4ba0cfe5c43b8dafea1e506aa0cfa254dc10
#[macro_use] extern crate slog; #[macro_use] extern crate serde; pub mod msg; pub mod rpc; pub mod kit; pub mod proto; pub mod meta; pub mod service; pub mod logger; pub mod storage; pub mod conf; pub mod mem_storage; pub mod level_storage; use std::sync::mpsc::{Receiver, Sender, TryRecvError}; use std::sync::{mpsc, ...
#[macro_use] extern crate slog; #[macro_use] extern crate serde; pub mod msg; pub mod rpc; pub mod kit; pub mod proto; pub mod meta; pub mod service; pub mod logger; pub mod storage; pub mod conf; pub mod mem_storage; pub mod level_storage; use std::sync::mpsc::{Receiver, Sender, TryRecvError}; use std::sync::{mpsc, ...
fn send(&mut self, msg: Message) { if self.clients.get(&msg.to).is_none() { let addr = match self.peers.get(&msg.to) { Some(n) => n, None => { debug!(self.logger, "Cannot find address of id {}", msg.to); return; ...
cc.set_change_type(ConfChangeType::AddNode); cc.set_context(addr.clone().into_bytes()); self.service.lock().unwrap().send(Msg::ConfChange(cc)); }
function_block-function_prefix_line
[ { "content": "pub fn check_addr(addr: &String) -> bool {\n\n let v: Vec<&str> = addr.split(\":\").collect();\n\n v.len() == 2\n\n}\n\n\n", "file_path": "src/kit/mod.rs", "rank": 0, "score": 193697.4450021 }, { "content": "pub fn create_logger(id: u64, log_level: String) -> Logger {\n\n...
Rust
rs/rosetta-api/src/request_handler/construction_parse.rs
contropist/ic
9240bea7dc0239fcbc5d43ad11f3ca803ee9bb11
use crate::convert::{self, from_arg, to_model_account_identifier}; use crate::errors::ApiError; use crate::models::{ConstructionParseRequest, ConstructionParseResponse, ParsedTransaction}; use crate::request_handler::{verify_network_id, RosettaRequestHandler}; use crate::request_types::{ AddHotKey, Disburse, Follow...
use crate::convert::{self, from_arg, to_model_account_identifier}; use crate::errors::ApiError; use crate::models::{ConstructionParseRequest, ConstructionParseResponse, ParsedTransaction}; use crate::request_handler::{verify_network_id, RosettaRequestHandler}; use crate::request_types::{ AddHotKey, Disburse, Follow...
})) = manage.command { if let Some(spawned_neuron_index) = nonce { requests.push(Request::Spawn(Spawn { account: from, spawned_neuron_index, controller: new_controller, percentage_to_spawn, neuron_index, ...
{}, )), })) ) { return Err(ApiError::internal_error( "Incompatible manage_neuron command".to_string(), )); }; requests.push(Request::StartDissolve(StartDissolve { account: from, neuron_index, })); Ok(()) } fn stop_dissolve( request...
random
[ { "content": "/// Deserializes the response obtained from the registry canister for a\n\n/// get_changes_since() call, from protobuf.\n\npub fn deserialize_get_changes_since_request(request: Vec<u8>) -> Result<u64, Error> {\n\n match pb::v1::RegistryGetChangesSinceRequest::decode(&request[..]) {\n\n O...
Rust
rust/ccx/api/binance/src/api/spot/wallet.rs
timaghostov/ccx-api
7bb3d0bdc5132e71c5bb7409f0aa84c7f7673805
use super::prelude::*; pub const SAPI_V1_SYSTEM_STATUS: &str = "/sapi/v1/system/status"; pub const SAPI_V1_CAPITAL_CONFIG_GETALL: &str = "/sapi/v1/capital/config/getall"; pub const SAPI_V1_ACCOUNT_DISABLE_FAST_WITHDRAW: &str = "/sapi/v1/account/disableFastWithdrawSwitch"; pub const SAPI_V1_ACCOUNT_ENABLE_FAST_WIT...
use super::prelude::*; pub const SAPI_V1_SYSTEM_STATUS: &str = "/sapi/v1/system/status"; pub const SAPI_V1_CAPITAL_CONFIG_GETALL: &str = "/sapi/v1/capital/config/getall"; pub const SAPI_V1_ACCOUNT_DISABLE_FAST_WITHDRAW: &str = "/sapi/v1/account/disableFastWithdrawSwitch"; pub const SAPI_V1_ACCOUNT_ENABLE_FAST_WIT...
pub async fn get_deposit_address( &self, coin: impl Serialize, network: Option<impl Serialize>, time_window: impl Into<TimeWindow>, ) -> BinanceResult<DepositAddress> { ...
BinanceResult<()> { self.client .post(SAPI_V1_ACCOUNT_ENABLE_FAST_WITHDRAW)? .signed(time_window)? .send_no_response() .await }
function_block-function_prefix_line
[ { "content": "/// Converts Kraken's asset codes into ccxt-compatible asset codes.\n\npub fn universal_asset_code(asset_id: &str) -> &str {\n\n if !asset_id.is_ascii() {\n\n return asset_id;\n\n }\n\n let asset_id =\n\n if asset_id.len() > 3 && matches!(&asset_id[0..1], \"X\" | \"Z\") && !...
Rust
cli/src/action/rbac/assignments.rs
rbuysse/splinter
1864eb39be8c44f910dc0ce79693fea7f136fd5a
use std::collections::BTreeSet; use clap::ArgMatches; use crate::action::{ api::{Assignment, AssignmentBuilder, AssignmentUpdateBuilder, Identity, SplinterRestClient}, print_table, Action, }; use crate::error::CliError; use super::new_client; pub struct ListAssignmentsAction; impl Action for ListAssignme...
use std::collections::BTreeSet; use clap::ArgMatches; use crate::action::{ api::{Assignment, AssignmentBuilder, AssignmentUpdateBuilder, Identity, SplinterRestClient}, print_table, Action, }; use crate::error::CliError; use super::new_client; pub struct ListAssignmentsAction; impl Action for ListAssignme...
} else { Ok(()) } } } pub struct ShowAssignmentAction; impl Action for ShowAssignmentAction { fn run<'a>(&mut self, arg_matches: Option<&ArgMatches<'a>>) -> Result<(), CliError> { let format = arg_matches .and_then(|args| args.value_of("format")) .u...
Err(CliError::ActionError(format!( "An assignment for {} {} already exists", id_type, id_value )))
call_expression
[ { "content": "pub fn get_role(base_url: &str, auth: &str, role_id: &str) -> Result<Option<Role>, CliError> {\n\n Client::new()\n\n .get(&format!(\"{}/authorization/roles/{}\", base_url, role_id))\n\n .header(\"SplinterProtocolVersion\", RBAC_PROTOCOL_VERSION)\n\n .header(\"Authorization\...
Rust
common/datavalues2/src/columns/series.rs
pymongo/databend
c349ea00478df90c6b9c6438bec9b3643b4072e4
use std::sync::Arc; use common_arrow::arrow::bitmap::MutableBitmap; use common_exception::ErrorCode; use common_exception::Result; use crate::prelude::*; use crate::Column; use crate::ColumnRef; use crate::NewColumn; use crate::NullableColumn; use crate::StringColumn; pub struct Series; impl Series { ...
use std::sync::Arc; use common_arrow::arrow::bitmap::MutableBitmap; use common_exception::ErrorCode; use common_exception::Result; use crate::prelude::*; use crate::Column; use crate::ColumnRef; use crate::NewColumn; use crate::NullableColumn; use crate::StringColumn; pub struct Series; impl Series { ...
'a [u8]>]> for Series { fn from_data(v: T) -> ColumnRef { let iter = v.as_ref().iter().map(|v| v.is_some()); let bitmap = MutableBitmap::from_iter(iter); let iter = v.as_ref().iter().map(|v| v.unwrap_or(&[])); let column = StringColumn::new_from_iter(iter); Arc::new(Nullable...
w(Arc::new(column), bitmap.into())) } } }; } impl<'a, T: AsRef<[&'a str]>> SeriesFrom<T, [&'a str]> for Series { fn from_data(v: T) -> ColumnRef { Arc::new(StringColumn::new_from_slice(v)) } } impl<'a, T: AsRef<[Option<&'a str>]>> SeriesFrom<T, [Option<&'a str>]> for Series { ...
random
[ { "content": "pub trait SeriesFrom<T, Phantom: ?Sized> {\n\n /// Initialize by name and values.\n\n fn new(_: T) -> Self;\n\n}\n\n\n\nmacro_rules! impl_from {\n\n ($type:ty, $array:ident, $method:ident) => {\n\n impl<T: AsRef<$type>> SeriesFrom<T, $type> for Series {\n\n fn new(v: T) ...
Rust
src/cached_static.rs
threecgreen/vinoteca
7f8431cadb8b4d1ca6f36a9506e2c4d7c332835d
use chrono::{DateTime, Utc}; use rocket::handler::{Handler, Outcome}; use rocket::http::hyper::header::{CacheControl, CacheDirective, ContentEncoding, Encoding}; use rocket::http::{uncased::Uncased, uri::Segments, ContentType, Header, Method, Status}; use rocket::response::{self, Responder, Response}; use rocket::{Data...
use chrono::{DateTime, Utc}; use rocket::handler::{Handler, Outcome}; use rocket::http::hyper::header::{CacheControl, CacheDirective, ContentEncoding, Encoding}; use rocket::http::{uncased::Uncased, uri::Segments, ContentType, Header, Method, Status}; use rocket::response::{self, Responder, Response}; use rocket::{Data...
if gz_path.exists() && accept_encoding .map(|enc| enc.contains("gzip")) .unwrap_or(false) { Outcome::from(req, CachedFile::open(gz_path).ok()) } else { ...
let accept_encoding: Option<std::collections::HashSet<String>> = req .headers() .get_one("Accept-Encoding") .map(|s| s.split(',').map(|t| t.trim().to_owned()).collect());
assignment_statement
[ { "content": "pub fn get_routes() -> Vec<rocket::Route> {\n\n routes![\n\n home,\n\n robots,\n\n sitemap,\n\n about,\n\n changelog,\n\n login,\n\n register,\n\n dashboards,\n\n grapes,\n\n producers,\n\n wines,\n\n wine_profi...
Rust
src/commands/nsq/post.rs
ethankhall/toolk
90a4b502019216ef21829c12f117f78e09728493
use std::io::{self, BufRead, BufReader, Write}; use std::path::PathBuf; use std::sync::atomic::{AtomicBool, AtomicUsize, Ordering}; use std::thread; use std::time::Duration; use clap::ArgMatches; use crossbeam_channel::bounded; use crossbeam_channel::Receiver; use crate::commands::nsq::api::*; use crate::commands::pr...
use std::io::{self, BufRead, BufReader, Write}; use std::path::PathBuf; use std::sync::atomic::{AtomicBool, AtomicUsize, Ordering}; use std::thread; use std::time::Duration; use clap::ArgMatches; use crossbeam_channel::bounded; use crossbeam_channel::Receiver; use crate::commands::nsq::api::*; use crate::commands::pr...
fn process_messages(reciever: Receiver<String>, path: String) { let client = reqwest::Client::new(); loop { match reciever.recv_timeout(Duration::from_millis(100)) { Err(_) => { if !THREADS_RUNNING.load(Ordering::SeqCst) { return; } ...
let snapshot = state.update_status(); let agg = snapshot.topics.get(topic).unwrap().producer_aggregate(); let max_depth = std::cmp::max(0, agg.depth) as usize; API_DEPTH.store(max_depth, Ordering::SeqCst); }
function_block-function_prefix_line
[]
Rust
third_party/rust_crates/vendor/ttf-parser/src/tables/kern.rs
allansrc/fuchsia
a2c235b33fc4305044d496354a08775f30cdcf37
/*! A kerning table implementation. Supports both [OpenType](https://docs.microsoft.com/en-us/typography/opentype/spec/kern) and [Apple Advanced Typography](https://developer.apple.com/fonts/TrueType-Reference-Manual/RM06/Chap6kern.html) variants. Since there is no single correct way to process a kerning data, we hav...
/*! A kerning table implementation. Supports both [OpenType](https://docs.microsoft.com/en-us/typography/opentype/spec/kern) and [Apple Advanced Typography](https://developer.apple.com/fonts/TrueType-Reference-Manual/RM06/Chap6kern.html) variants. Since there is no single correct way to process a kerning data, we hav...
} } impl core::fmt::Debug for Subtable<'_> { fn fmt(&self, f: &mut core::fmt::Formatter) -> core::fmt::Result { f.debug_struct("Subtable") .field("is_horizontal", &self.is_horizontal()) .field("has_state_machine", &self.has_state_machine()) .field("has_cros...
match self.format { 0 => parse_format0(self.data, left, right), 2 => parse_format2(left, right, self.header_size, self.data), 3 => parse_format3(self.data, left, right), _ => None, }
if_condition
[]
Rust
codectrl-gui/src/lib.rs
pwnCTRL/codectrl
45a67991ca089da8d48a5c83e1eda3e13e478d72
#![feature(thread_spawn_unchecked)] #![warn(clippy::pedantic)] #![allow( clippy::blocks_in_if_conditions, clippy::module_name_repetitions, clippy::struct_excessive_bools, clippy::too_many_lines, incomplete_features )] mod app; mod components; mod consts; mod data; #[cfg(not(target_arch = "wasm32")...
#![feature(thread_spawn_unchecked)] #![warn(clippy::pedantic)] #![allow( clippy::blocks_in_if_conditions, clippy::module_name_repetitions, clippy::struct_excessive_bools, clippy::too_many_lines, incomplete_features )] mod app; mod components; mod consts; mod data; #[cfg(not(target_arch = "wasm32")...
; file_path } else { Path::new("").to_path_buf() }; let options = eframe::NativeOptions { drag_and_drop_support: true, ..eframe::NativeOptions::default() }; eframe::run_native( "codeCtrl", options, Box::new(move |cc| { let mut ap...
match Path::new(project_file).canonicalize() { Ok(file_path) => file_path, Err(error) => panic!("Could not cannonicalise PROJECT file path: {error}"), }
if_condition
[ { "content": "pub fn details_view(app_state: &mut AppState, ctx: &Context) {\n\n egui::TopBottomPanel::bottom(\"log_information\")\n\n .resizable(true)\n\n .default_height(350.0)\n\n .min_height(250.0)\n\n .show(ctx, |ui| draw_information_grid(app_state, ctx, ui));\n\n}\n", "f...
Rust
src/obj/phys.rs
LFalch/shooter
fd64c348b4f8bc28d461ad45c5bd062f8a18e640
use std::ops::{Deref, DerefMut}; use ggez::graphics::{self, Point2, Vector2}; use ggez::{Context, GameResult}; use {RED, Object, DDELTA, DELTA, Sprite, angle_to_vec}; use super::AsObject; #[derive(Debug, Deserialize, Serialize)] pub struct DestructableObj { pub obj: Object, pub health: f32, } impl ...
use std::ops::{Deref, DerefMut}; use ggez::graphics::{self, Point2, Vector2}; use ggez::{Context, GameResult}; use {RED, Object, DDELTA, DELTA, Sprite, angle_to_vec}; use super::AsObject; #[derive(Debug, Deserialize, Serialize)] pub struct DestructableObj { pub obj: Object, pub health: f32, } impl ...
pub fn throttle(&mut self, throttle: f64) { self.throttle_usage += throttle; if self.throttle_usage < 0. { self.throttle_usage = 0.; } else if self.throttle_usage > self.max_throttle { self.throttle_usage = self.max_throttle; } } pub fn spri...
pub fn burn(&mut self) -> f32 { let mut usg = self.throttle_usage * DDELTA; if usg > self.fuel { self.power = false; usg = self.fuel; } self.fuel -= usg; self.efficiency * usg as f32 }
function_block-full_function
[ { "content": "/// Gets the direction angle on the screen (0 is along the x-axis) of a vector\n\npub fn angle_from_vec(v: &Vector2) -> f32 {\n\n let x = v.x;\n\n let y = v.y;\n\n\n\n y.atan2(x)\n\n}\n\n\n\n/// A colour with half transparency\n\npub const TRANS: Color = Color{r:1.,g:1.,b:1.,a:0.5};\n\n//...
Rust
crates/holochain/src/test_utils/host_fn_api.rs
remik2212/holochain
bf21c837f450f606fb87cf5746c1ea15d8ba0ca2
#![allow(missing_docs)] use crate::{ conductor::ConductorHandle, conductor::{ api::{CellConductorApi, CellConductorApiT, CellConductorReadHandle}, interface::SignalBroadcaster, }, core::ribosome::RibosomeT, core::ribosome::ZomeCallInvocation, core::{ ribosome::{ ...
#![allow(missing_docs)] use crate::{ conductor::ConductorHandle, conductor::{ api::{CellConductorApi, CellConductorApiT, CellConductorReadHandle}, interface::SignalBroadcaster, }, core::ribosome::RibosomeT, core::ribosome::ZomeCallInvocation, core::{ ribosome::{ ...
} impl HostFnApi { pub async fn commit_entry<E: Into<entry_def::EntryDefId>>( &self, entry: Entry, entry_def_id: E, ) -> HeaderHash { let (env, ribosome, call_context, workspace_lock) = self.explode(); let input = CreateInput::new((entry_def_id.into(), entry)); ...
pub fn explode( &self, ) -> ( EnvironmentWrite, Arc<WasmRibosome>, Arc<CallContext>, CallZomeWorkspaceLock, ) { let HostFnApi { env, network, keystore, ribosome, signal_tx, zome_path, ...
function_block-full_function
[ { "content": "#[instrument(skip(_ribosome, _call_context, input))]\n\npub fn debug(\n\n _ribosome: Arc<impl RibosomeT>,\n\n _call_context: Arc<CallContext>,\n\n input: DebugInput,\n\n) -> RibosomeResult<DebugOutput> {\n\n let msg: DebugMsg = input.into_inner();\n\n debug!(\n\n \"{}:{}:{} {...
Rust
src/parser.rs
AustinOliverHaskell/TemplateCommand
58d86a77a0877e155da3b27f818762af2064bbd7
use log::*; pub struct Parser; #[derive(Debug, Eq, PartialEq, Clone)] pub struct FoundToken { pub start: usize, pub end: usize, } impl Parser { #[allow(dead_code)] pub fn find_all_tokens(string: &str) -> Vec<FoundToken> { let mut start_index: usize = 0; let mut found_tokens: Vec<Foun...
use log::*; pub struct Parser; #[derive(Debug, Eq, PartialEq, Clone)] pub struct FoundToken { pub start: usize, pub end: usize, } impl Parser { #[allow(dead_code)] pub fn find_all_tokens(string: &str) -> Vec<FoundToken> { let mut start_index: usize = 0; let mut found_tokens: Vec<Foun...
= false; is_in_token = false; } } }, _ => { if !(character.is_alphabetic() || character == '_') && is_in_token && !is_in_parameters { is_in_token = false; ...
open_square_bracket_found = true; if !is_in_token { start_index = index; } }, ']' => { if open_square_bracket_found { if is_in_token && !is_in_parameters{ ...
random
[ { "content": "pub fn subtract_ending_off_string(base: &str, ending: &str) -> Result<String, String> {\n\n if base.len() < ending.len() {\n\n warn!(\"Trying to remove ending that doesn't exist -{:}\", ending);\n\n return Err(\"Subtracting an ending that is longer than the base. \".to_string());\...
Rust
descriptor_derive/src/parse.rs
XciD/descriptor
f7d2f3cc421c0f009958dee645275e9cf4a1a550
use proc_macro_error::{abort, ResultExt}; use syn::parse::{Parse, ParseStream}; use syn::punctuated::Punctuated; use syn::{self, Attribute, Expr, Ident, LitStr, Token}; pub struct DescriptorAttr { ident: Ident, attribute: String, expr: Option<Expr>, value: Option<String>, } #[derive(Clone)] pub struct...
use proc_macro_error::{abort, ResultExt}; use syn::parse::{Parse, ParseStream}; use syn::punctuated::Punctuated; use syn::{self, Attribute, Expr, Ident, LitStr, Token}; pub struct DescriptorAttr { ident: Ident, attribute: String, expr: Option<Expr>, value: Option<String>, } #[derive(Clone)] pub struct...
pub fn extract_field_attributes(all_attrs: &[Attribute]) -> DescriptorFieldAttr { let mut field_attribute = DescriptorFieldAttr { skip_header: false, skip_description: false, skip: false, output_table: false, flatten: false, resolve_option: false, rename_hea...
pub fn extract_struct_attributes(all_attrs: &[Attribute]) -> DescriptorStructAttr { let mut struct_attr = DescriptorStructAttr { into: None, headers: None, map: None, extra_fields: None, }; for attr in parse_attributes(all_attrs) { let DescriptorAttr { id...
function_block-full_function
[ { "content": "// Will generate the header function, we list all possible fields recursively\n\nfn headers_for_struct(fields: &[StructField], struct_attributes: &DescriptorStructAttr) -> TokenStream {\n\n let mut headers = quote! {\n\n let mut headers = Vec::new();\n\n };\n\n\n\n for field in fie...
Rust
src/main.rs
tomvercaut/teams_remove_cache
90e9106444297b11e4b70dffa0b43fa99a290bdc
#[macro_use] extern crate clap; use clap::{crate_authors, crate_description, crate_version, App, Arg}; use std::env; use std::fs; use std::path::Path; use std::process::exit; #[derive(Debug, Clone)] pub struct Config { pub dry_run: bool, pub verbose: bool, } impl std::default::Default for Config { fn def...
#[macro_use] extern crate clap; use clap::{crate_authors, crate_description, crate_version, App, Arg}; use std::env; use std::fs; use std::path::Path; use std::process::exit; #[derive(Debug, Clone)] pub struct Config { pub dry_run: bool, pub verbose: bool, } impl std::default::Default for Config { fn def...
#[cfg(target_os = "windows")] fn handle(config: &Config) { let app_data_str = env::var("AppData"); if let Err(e) = app_data_str { eprintln!("Unable to obtain environment variable: AppData"); eprintln!("{}", e); return; } let app_data_str = app_data_str.unwrap(); let app_d...
fn remove_dir(p: &Path, config: &Config) { if config.dry_run { println!("To delete: {:?}", p); } else { if config.verbose { println!("To delete: {:?}", p); } if let Err(e) = fs::remove_dir_all(p) { eprintln!("{}", e); } } }
function_block-full_function
[ { "content": "# teams_remove_cache\n\n\n\n## Description\n\n\n\nAn application that removes the cache files and directory generated by Microsoft Teams. The application is designed for Microsoft Windows systems and will not compile on other operating systems.\n\n\n\n## Usage\n\n\n\nBefore running this applicatio...
Rust
src/imu/mod.rs
qiuchengxuan/rs-flight
66a09afe4e24f8b49c6445f9048172e46e6a0f03
pub mod out; use fugit::NanosDurationU64 as Duration; use nalgebra::Vector3; use crate::{ algorithm::mahony::{MagnetismOrHeading, Mahony}, config, datastore, types::measurement::{ euler::{Euler, DEGREE_PER_DAG}, unit::DEGs, Acceleration, Frame, Gyro, }, }; #[derive(PartialEq)]...
pub mod out; use fugit::NanosDurationU64 as Duration; use nalgebra::Vector3; use crate::{ algorithm::mahony::{MagnetismOrHeading, Mahony}, config, datastore, types::measurement::{ euler::{Euler, DEGREE_PER_DAG}, unit::DEGs, Acceleration, Frame, Gyro, }, }; #[derive(PartialEq)]...
} pub struct IMU { interval: Duration, ahrs: Mahony, calibration: Calibration, } impl IMU { pub fn new(sample_rate: usize) -> Self { let config = config::get().imu; let interval = Duration::micros(1000_000 / sample_rate as u64); let (kp, ki) = (config.mahony.kp.into(), config....
CalibrationStatus::Validating => { let delta = gyro - self.gyroscope_bias; if delta.abs().iter().any(|&v| v > 1.0) { warn!("IMU status invalid, restarting..."); self.status = CalibrationStatus::Calibrating; self.remain = self.in...
function_block-function_prefix_line
[ { "content": "pub fn replace(config: &Config) {\n\n unsafe { CONFIG_ITERATION += 1 }\n\n unsafe { CONFIG = Some(config.clone()) }\n\n}\n\n\n", "file_path": "src/config/mod.rs", "rank": 0, "score": 252950.5554844612 }, { "content": "pub fn iteration() -> usize {\n\n unsafe { CONFIG_I...
Rust
tests/test_032_blobs.rs
emabee/rust-hdbconnect
551d7c9658e4ddf024f75ebec25e6e6241b63760
#[macro_use] extern crate serde; mod test_utils; use flexi_logger::LoggerHandle; use hdbconnect::types::BLob; use hdbconnect::{Connection, HdbError, HdbResult, HdbValue}; use log::{debug, info}; use rand::{thread_rng, RngCore}; use serde::{Deserialize, Serialize}; use serde_bytes::{ByteBuf, Bytes}; use sha2::{Digest,...
#[macro_use] extern crate serde; mod test_utils; use flexi_logger::LoggerHandle; use hdbconnect::types::BLob; use hdbconnect::{Connection, HdbError, HdbResult, HdbValue}; use log::{debug, info}; use rand::{thread_rng, RngCore}; use serde::{Deserialize, Serialize}; use serde_bytes::{ByteBuf, Bytes}; use sha2::{Digest,...
const SIZE: usize = 5 * 1024 * 1024; fn get_random_bytes() -> (Vec<u8>, Vec<u8>) { let mut raw_data = vec![0; SIZE]; raw_data.resize(SIZE, 0_u8); thread_rng().fill_bytes(&mut *raw_data); assert_eq!(raw_data.len(), SIZE); let mut hasher = Sha256::default(); hasher.update(&raw_data); ...
let mut loghandle = test_utils::init_logger(); let start = std::time::Instant::now(); let mut connection = test_utils::get_authenticated_connection()?; let (random_bytes, fingerprint) = get_random_bytes(); test_blobs(&mut loghandle, &mut connection, &random_bytes, &fingerprint)?; test_streaming(&mu...
function_block-function_prefix_line
[ { "content": "pub fn closing_info(connection: Connection, start: std::time::Instant) -> HdbResult<()> {\n\n log::info!(\n\n \"{} calls to DB were executed; \\\n\n elapsed time: {:?}, \\\n\n accumulated server processing time: {:?}\",\n\n connection.get_call_count()?,\n\n ...
Rust
src/transform.rs
ithos-org/ithos
0d58b2622df7710d506a59eb79a83bf2934def2f
use adapter::{Adapter, Transaction}; use block::Block; use entry::{Class, Entry, SerializedEntry}; use errors::*; use id::{BlockId, EntryId}; use metadata::Metadata; use op::{self, Op}; use path::{Path, PathBuf}; use std::collections::HashMap; use timestamp::Timestamp; #[cfg(test)] extern crate tempdir; #[derive(De...
use adapter::{Adapter, Transaction}; use block::Block; use entry::{Class, Entry, SerializedEntry}; use errors::*; use id::{BlockId, EntryId}; use metadata::Metadata; use op::{self, Op}; use path::{Path, PathBuf}; use std::collections::HashMap; use timestamp::Timestamp; #[cfg(test)] extern crate tempdir; #[derive(De...
let next_id = self.next_entry_id; self.next_entry_id = next_id.next(); (parent_entry.id, next_id) } None => { if child_class != Class::Root { let msg = format!("{:?} not allowed as root entry", child_class); ...
if !parent_entry.class.allows_child(&child_class) { let msg = format!( "{:?} does not allow {:?} as child", parent_entry.class, child_class ); return Err(ErrorKind::StructureInvalid(msg).i...
if_condition
[ { "content": "/// All access to the underlying storage system is transactional\n\npub trait Transaction: AdapterTransaction {\n\n /// Commit this transaction (performing writes if this is a read-write transaction\n\n fn commit(self) -> Result<()>;\n\n}\n\n\n", "file_path": "src/adapter/mod.rs", "r...
Rust
src/bsp.rs
alexschrod/tcod-rs
03a35b3977744069759a6e5c8521ebe471fe5f70
use bindings::c_void; use bindings::ffi; use bindings::AsNative; use random::Rng; use std::fmt; use std::mem; use std::ops::{Deref, DerefMut}; use std::ptr; #[derive(Copy, Clone, Debug)] pub enum TraverseOrder { PreOrder, InOrder, PostOrder, LevelOrder, InvertedLevelOrder, } pub struct Bsp<'a> {...
use bindings::c_void; use bindings::ffi; use bindings::AsNative; use random::Rng; use std::fmt; use std::mem; use std::ops::{Deref, DerefMut}; use std::ptr; #[derive(Copy, Clone, Debug)] pub enum TraverseOrder { PreOrder, InOrder, PostOrder, LevelOrder, InvertedLevelOrder, } pub struct Bsp<'a> {...
; counter += 1; true }); counter = 0; root.traverse(TraverseOrder::PostOrder, |node| { match counter { 0 => assert!(cmp(node.bsp, leaf1.bsp)), 1 => assert!(cmp(node.bsp, leaf2.bsp)), 2 => assert!(cmp(node.bsp, m...
match counter { 0 => assert!(cmp(node.bsp, leaf1.bsp)), 1 => assert!(cmp(node.bsp, middle_left.bsp)), 2 => assert!(cmp(node.bsp, leaf2.bsp)), 3 => assert!(cmp(node.bsp, root.bsp)), 4 => assert!(cmp(node.bsp, leaf3.bsp)), 5 =...
if_condition
[ { "content": "fn random_val(mut low: i32, high: i32) -> i32 {\n\n let mut rnd = rand::thread_rng();\n\n\n\n if low >= high {\n\n low -= 1\n\n }\n\n rnd.gen_range(low, high)\n\n}\n\n\n\nimpl<'a> BspSample<'a> {\n\n fn new() -> Self {\n\n BspSample {\n\n bsp: Bsp::new_with_...
Rust
src/lexer/mod.rs
NTTMai/Yotc
18ce8eac8bf648d0b64b42c01a5f867d6e9b8f52
pub mod tokens; use crate::lexer::tokens::*; use crate::Result; use log::trace; use std::iter::Peekable; use std::vec::IntoIter; use std::{fs, io}; pub struct Lexer { raw_data: Peekable<IntoIter<char>>, } impl Lexer { pub fn from_file(file_path: &str) -> io::Result<Self> { Ok...
pub mod tokens; use crate::lexer::tokens::*; use crate::Result; use log::trace; use std::iter::Peekable; use std::vec::IntoIter; use std::{fs, io}; pub struct Lexer { raw_data: Peekable<IntoIter<char>>, } impl Lexer { pub fn from_file(file_path: &str) -> io::Result<Self> { Ok...
} Some(token) } } #[cfg(test)] mod tests { use super::Lexer; #[test] fn is_identifier() { for &i in &['a', 'z', '_', '0', '9'] { assert!(Lexer::is_identifier(i)); } for &s in &['+', '*', '@', ';'] { assert!(!Lexer::is_identifier(s)); ...
match &raw[..] { s if s == "//" => { trace!("Ignoring comment"); self.get_next_char_while(&mut String::new(), |c| c != '\n'); self.next()? } s if VALID_SYMBOLS.contains(&s) => Ok(Token::Symbol(ra...
if_condition
[ { "content": "type TokenIter = Peekable<IntoIter<Token>>;\n\n\n\n/// A parser that generates an abstract syntax tree, modeled by a yot [`Program`].\n\n///\n\n/// [`Program`]: program/struct.Program.html\n\npub struct Parser {\n\n /// The [`Token`]s generated by the [`Lexer`].\n\n ///\n\n /// [`Token`]:...
Rust
debug/src/lib.rs
ChuWenFeng/proc-macro-workshop
2868248f1efcd2e23e270336e33dbdbff2baad34
use std::{collections::HashMap}; use proc_macro::TokenStream; use quote::quote; use syn::{parse_quote, visit::Visit}; #[proc_macro_derive(CustomDebug,attributes(debug))] pub fn derive(input: TokenStream) -> TokenStream { let st = syn::parse_macro_input!(input as syn::DeriveInput); match do_expand(&st){ ...
use std::{collections::HashMap}; use proc_macro::TokenStream; use quote::quote; use syn::{parse_quote, visit::Visit}; #[proc_macro_derive(CustomDebug,attributes(debug))] pub fn derive(input: TokenStream) -> TokenStream { let st = syn::parse_macro_input!(input as syn::DeriveInput); match do_expand(&st){ ...
fn get_struct_escape_hatch(st:&syn::DeriveInput)->Option<String>{ if let Some(inert_attr) = st.attrs.last(){ if let Ok(syn::Meta::List(syn::MetaList{nested,..})) = inert_attr.parse_meta(){ if let Some(syn::NestedMeta::Meta(syn::Meta::NameValue(path_value))) = nested.last(){ if pa...
function_block-full_function
[ { "content": "fn impl_user_define_bit_width(st: &mut syn::ItemStruct)->syn::Result<proc_macro2::TokenStream>{\n\n let mut token_stream = proc_macro2::TokenStream::new();\n\n // token_stream.extend(st.to_token_stream());\n\n token_stream.extend(quote::quote! {\n", "file_path": "bitfield/impl/src/lib...
Rust
src/application/prefs.rs
skysch/stall
361eaf74138e71d311517d9b652330204e15f70a
use crate::application::LoadStatus; use anyhow::Context as _; use anyhow::Error; use serde::Deserialize; use serde::Serialize; use std::convert::TryInto as _; use std::fs::File; use std::fs::OpenOptions; use std::io::BufWriter; use std::io::Read as _; use std::io::Write as _; use std::path::Path; #[derive(Debug, C...
use crate::application::LoadStatus; use anyhow::Context as _; use anyhow::Error; use serde::Deserialize; use serde::Serialize; use std::convert::TryInto as _; use std::fs::File; use std::fs::OpenOptions; use std::io::BufWriter; use std::io::Read as _; use std::io::Write as _; use std::path::Path; #[derive(Debug, C...
#[tracing::instrument(skip_all, err)] pub fn write_to_path_if_new<P>(&self, path: P) -> Result<(), Error> where P: AsRef<Path> { let path = path.as_ref(); let file = OpenOptions::new() .write(true) .truncate(true) .create_new(true) .open(path) .with_context(|| format!( "Failed to create...
pub fn write_to_path<P>(&self, path: P) -> Result<(), Error> where P: AsRef<Path> { let path = path.as_ref(); let file = OpenOptions::new() .write(true) .truncate(true) .create(true) .open(path) .with_context(|| format!( "Failed to create/open prefs file for writing: {}", path.display()))?...
function_block-full_function
[ { "content": "fn file_exists<P>(path: P) -> bool where P: AsRef<Path> {\n\n File::options()\n\n .read(true)\n\n .open(path)\n\n .is_ok()\n\n}\n\n\n\n\n", "file_path": "src/test.rs", "rank": 0, "score": 140098.45795685585 }, { "content": "fn create_file<P>(path: P) whe...
Rust
repr_offset/tests/misc_tests_submod/get_field_offset_trait.rs
rodrimati1992/repr_offset_crates
83fb842cc5ffd30653a1f6de04a35194677ce57d
use repr_offset::{ alignment::{Aligned, Unaligned}, get_field_offset::{FieldPrivacy, PrivFieldAlignment, PrivFieldType}, privacy::{IsPrivate, IsPublic}, tstr::alias, unsafe_struct_field_offsets, }; #[derive(Default)] #[repr(C)] pub struct AlignedStruct<A, B, C, D> { a: A, b: B, c: C, ...
use repr_offset::{ alignment::{Aligned, Unaligned}, get_field_offset::{FieldPrivacy, PrivFieldAlignment, PrivFieldType}, privacy::{IsPrivate, IsPublic}, tstr::alias, unsafe_struct_field_offsets, }; #[derive(Default)] #[repr(C)] pub struct AlignedStruct<A, B, C, D> { a: A, b: B, c: C, ...
#[test] fn struct_packed_aligned() { pub type S = PackedStruct<AlignedInnerAA, AlignedInnerBB, AlignedInnerCC, AlignedInnerDD>; let _: FieldP<S, SA> = (AlignedInnerAA::default(), Unaligned, IsPrivate); let _: FieldP<S, SB> = (AlignedInnerBB::default(), Unaligned, IsPrivate); let _: FieldP<S, SC> = (A...
let _: FieldP<S, SAA> = (0u8, Aligned, IsPrivate); let _: FieldP<S, SAB> = (0u16, Aligned, IsPrivate); let _: FieldP<S, SAC> = (0u32, Aligned, IsPrivate); let _: FieldP<S, SAD> = (0u64, Aligned, IsPrivate); let _: FieldP<S, SBA> = (' ', Aligned, IsPrivate); let _: FieldP<S, SBB> = (Some(' '), Align...
function_block-function_prefix_line
[ { "content": "type RFooInner = ReprC<i16, i32, i64, i128>;\n", "file_path": "repr_offset/tests/misc_tests_submod/off_macros.rs", "rank": 0, "score": 254381.62868331984 }, { "content": "type Consts = StructReprC<(), (u32, u32, u32, u32), (), ()>;\n\n\n", "file_path": "repr_offset/tests/mi...
Rust
src/api/dtos/alias_dto.rs
proximax-storage/rust-xpx-chain-sdk
55613067328d511dbd9a129be30b9e048ef79175
/* * Copyright 2018 ProximaX Limited. All rights reserved. * Use of this source code is governed by the Apache 2.0 * license that can be found in the LICENSE file. */ use crate::{ account::Address, alias::AliasActionType, models::Result, mosaic::MosaicId, namespace::{NamespaceAlias, NamespaceId...
/* * Copyright 2018 ProximaX Limited. All rights reserved. * Use of this source code is governed by the Apache 2.0 * license that can be found in the LICENSE file. */ use crate::{ account::Address, alias::AliasActionType, models::Result, mosaic::MosaicId, namespace::{NamespaceAlias, NamespaceId...
} #[derive(Clone, Serialize, Deserialize)] #[serde(rename_all = "camelCase")] pub(crate) struct AliasTransactionDto { #[serde(flatten)] r#abstract: AbstractTransactionDto, alias_action: u8, namespace_id: Uint64Dto, #[serde(skip_serializing_if = "Option::is_none")] address: Option<String>, ...
pub fn compact(&self) -> crate::Result<NamespaceAlias> { let mut alias = NamespaceAlias::default(); alias.type_ = self._type as u8; if let Some(a) = &self.address { let address = Address::from_encoded(a)?; alias.address = Some(address) }; if let Some(m) ...
function_block-full_function
[ { "content": "#[derive(Serialize, Deserialize)]\n\n#[serde(rename_all = \"camelCase\")]\n\nstruct AccountLinkTransactionDto {\n\n #[serde(flatten)]\n\n r#abstract: AbstractTransactionDto,\n\n /// The public key of the remote account.\n\n remote_account_key: String,\n\n action: u8,\n\n}\n\n\n\n#[d...
Rust
src/storage/windows/access.rs
Kostassoid/lethe
83a27c5447051d56d4f6adf4ab8cffc75529793d
#![cfg(windows)] use crate::storage::{StorageAccess, StorageError}; use anyhow::{Context, Result}; use std::{io, mem, ptr}; use widestring::WideCString; use winapi::_core::ptr::null_mut; use winapi::shared::minwindef::{DWORD, LPVOID}; use winapi::shared::winerror::{ ERROR_CRC, ERROR_READ_FAULT, ERROR_SECTOR_NOT_FOU...
#![cfg(windows)] use crate::storage::{StorageAccess, StorageError}; use anyhow::{Context, Result}; use std::{io, mem, ptr}; use widestring::WideCString; use winapi::_core::ptr::null_mut; use winapi::shared::minwindef::{DWORD, LPVOID}; use winapi::shared::winerror::{ ERROR_CRC, ERROR_READ_FAULT, ERROR_SECTOR_NOT_FOU...
} impl Drop for DeviceFile { fn drop(&mut self) { if self.handle != null_mut() { if self.is_locked { unsafe { let mut returned: DWORD = 0; if DeviceIoControl( self.handle, winioctl::FSCTL_UN...
2 || c == ERROR_READ_FAULT as i32 => { StorageError::BadBlock } _ => StorageError::Other(err), } }
function_block-function_prefixed
[ { "content": "pub fn open_file_direct<P: AsRef<Path>>(file_path: P, write_access: bool) -> Result<File> {\n\n use std::os::unix::fs::OpenOptionsExt;\n\n OpenOptions::new()\n\n .create(false)\n\n .append(false)\n\n .write(write_access)\n\n .read(true)\n\n .truncate(false)...
Rust
src/virtualization/bin/vmm/device/virtio_sound/src/wire_convert.rs
allansrc/fuchsia
a2c235b33fc4305044d496354a08775f30cdcf37
use { crate::wire::*, fuchsia_zircon as zx, num_traits::cast::cast, once_cell::sync::Lazy, std::collections::HashMap, }; pub fn request_code_to_string(code: u32) -> &'static str { match code { VIRTIO_SND_R_JACK_INFO => "VIRTIO_SND_R_JACK_INFO", VIRTIO_SND_R_JACK_REMAP => "VIRTIO_SND_R_JAC...
use { crate::wire::*, fuchsia_zircon as zx, num_traits::cast::cast, once_cell::sync::Lazy, std::collections::HashMap, }; pub fn request_code_to_string(code: u32) -> &'static str { match code { VIRTIO_SND_R_JACK_INFO => "VIRTIO_SND_R_JACK_INFO", VIRTIO_SND_R_JACK_REMAP => "VIRTIO_SND_R_JAC...
tes_for_duration( zx::Duration::from_millis(10), AudioStreamType { sample_format: ASF::Signed16, channels: 2, frames_per_second: 48000, } ) ); assert_eq!( Some(480 * 8), ...
) == 0); } #[test] fn test_wire_rate_to_fidl() { assert_eq!(wire_rate_to_fidl(VIRTIO_SND_PCM_RATE_8000), Some(8000)); assert_eq!(wire_rate_to_fidl(VIRTIO_SND_PCM_RATE_48000), Some(48000)); assert_eq!(wire_rate_to_fidl(VIRTIO_SND_PCM_RATE_96000), Some(96000)); ...
random
[]
Rust
src/parser.rs
ameerwasi001/Ray-Rengine-Rust
110b8052af3548dfdd571af8b92ef6f8d61b0f61
use std::collections::HashMap; use crate::token; use crate::error; use crate::tokenTypes::TokenTypes::*; use crate::tokenTypes; use crate::nodes; use crate::position; #[derive(Debug)] pub struct Parser { pub tokens: Vec<token::Token>, } impl Parser { fn eof_token(&self) -> token::Token { token::Token{...
use std::collections::HashMap; use crate::token; use crate::error; use crate::tokenTypes::TokenTypes::*; use crate::tokenTypes; use crate::nodes; use crate::position; #[derive(Debug)] pub struct Parser { pub tokens: Vec<token::Token>, } impl Parser { fn eof_token(&self) -> token::Token { token::Token{...
; }; let lhs = match self.operation() { Ok(a) => a, Err(err) => return Err(err) }; let (_, pos_end) = lhs.get_pos(); return Ok(nodes::Node::RuleNode{rhs: tok.tok_value, lhs: Box::new(lhs), pos_start: assign_tok.pos_start, pos_end}) } fn operation(...
Err( error::Error { name: String::from("ParseError"), message: String::from(format!("Expected ':=', got {}", assign_tok.tok_type)), pos_start: tok.pos_start.copy(), pos_end: tok.pos_end.copy() } )
call_expression
[ { "content": "pub fn match_string(regex:String, input: String) -> bool {\n\n return string_left(regex, input) == \"\"\n\n}", "file_path": "src/rayRengine.rs", "rank": 0, "score": 86704.01795003074 }, { "content": "pub fn interpret(node: Box<nodes::Node>, context: &mut context::Context, in...
Rust
tests/cookie.rs
dowlandaiello/reqwest
f3f677bbda3cc197ffe2f892f4d536492f6a01e8
mod support; use support::*; #[tokio::test] async fn cookie_response_accessor() { let server = server::http(move |_req| { async move { http::Response::builder() .header("Set-Cookie", "key=val") .header( "Set-Cookie", "expir...
mod support; use support::*; #[tokio::test] async fn cookie_response_accessor() { let server = server::http(move |_req| { async move { http::Response::builder() .header("Set-Cookie", "key=val") .header( "Set-Cookie", "expir...
#[tokio::test] async fn cookie_store_expires() { let server = server::http(move |req| { async move { assert_eq!(req.headers().get("cookie"), None); http::Response::builder() .header( "Set-Cookie", "key=val; Expires=Wed, 21 Oct...
async fn cookie_store_max_age() { let server = server::http(move |req| { async move { assert_eq!(req.headers().get("cookie"), None); http::Response::builder() .header("Set-Cookie", "key=val; Max-Age=0") .body(Default::default()) .unwrap...
function_block-full_function
[ { "content": "#[cfg(feature = \"cookies\")]\n\nfn add_cookie_header(headers: &mut HeaderMap, cookie_store: &cookie::CookieStore, url: &Url) {\n\n let header = cookie_store\n\n .0\n\n .get_request_cookies(url)\n\n .map(|c| format!(\"{}={}\", c.name(), c.value()))\n\n .collect::<Vec...
Rust
src/game_data/qodot_game_data.rs
Shfty/qodot-next
ae43ef7772a2d27aaa8f09b94f10349ad07e363c
use super::{BrushData, EntityType, PointData}; use crate::game_data::qodot_entity::QodotEntity; use crate::game_data::qodot_worldspawn_layer::QodotWorldspawnLayer; use gdnative::{ godot_error, user_data::RwLockData, FromVariant, Instance, Map, NativeClass, Resource, Variant, VariantArray, GodotString, }; #[der...
use super::{BrushData, EntityType, PointData}; use crate::game_data::qodot_entity::QodotEntity; use crate::game_data::qodot_worldspawn_layer::QodotWorldspawnLayer; use gdnative::{ godot_error, user_data::RwLockData, FromVariant, Instance, Map, NativeClass, Resource, Variant, VariantArray, GodotString, }; #[der...
script.map(|point_data_script: &PointData| { let data = point_data_script.get_data(point_data_base); let spawn_type: quarchitect::game_data::EntityType = data.entity_type.clone(); let component_type: quarchitect::game_data::ComponentType = data.component_type.clone(); let...
Instance::<QodotEntity>::from_variant(new_entity); if new_entity.is_err() { let new_entity = Instance::<QodotEntity>::new().into_base(); let new_entity = &Variant::from_object(&new_entity); new_entities.set(i, new_entity); } } self...
random
[ { "content": "fn register_qodot_entity(builder: &gdnative::init::ClassBuilder<QodotEntity>) {\n\n builder\n\n .add_property::<GodotString>(\"classname\")\n\n .with_default(\"\".into())\n\n .with_ref_getter(QodotEntity::get_classname)\n\n .with_setter(QodotEntity::set_classname)\n\...
Rust
src/section.rs
usamoi/zelf
da243332daf6c9b9a9989d5ae9810c65abac1dde
use crate::context::PropU32; use crate::context::*; use crate::elf::Variant; use crate::strtab::{ParseStrtabError, Strtab}; use crate::utils::{as_offset, read, read_n, Pod}; use core::marker::PhantomData; use core::ops::RangeInclusive; #[derive(Debug, Clone)] pub enum ParseSectionsError { BrokenHeaders, BadPro...
use crate::context::PropU32; use crate::context::*; use crate::elf::Variant; use crate::strtab::{ParseStrtabError, Strtab}; use crate::utils::{as_offset, read, read_n, Pod}; use core::marker::PhantomData; use core::ops::RangeInclusive; #[derive(Debug, Clone)] pub enum ParseSectionsError { BrokenHeaders, BadPro...
pub fn strtab(&self) -> Strtab<'a> { self.strtab } } #[repr(C)] #[derive(Debug, Clone)] pub struct SectionHeader<T: Context> { pub name: PropU32, pub typa: PropU32, pub flags: T::PropUsize, pub addr: T::PropUsize, pub offset: T::PropUsize, pub size: T::PropUsize, pub link: ...
ECTION_INDEX_UNDEF => return Ok(None), x => x, }; let section = Section::parse(sections, shstrndx) .ok_or(BadPropertyShstrndx)? .map_err(FromSection)?; if section.header().typa() != SectionType::Strtab { return Err(BadPropertyType); } ...
function_block-function_prefixed
[ { "content": "pub fn read<T: Pod>(data: &[u8], offset: usize) -> Option<&T> {\n\n if data.len() < offset.checked_add(core::mem::size_of::<T>())? {\n\n return None;\n\n }\n\n let p = (data.as_ptr() as usize).wrapping_add(offset) as *const T;\n\n Some(unsafe { &*p })\n\n}\n\n\n", "file_path...
Rust
src/main.rs
mhutter/raytracing
0b091a96059b822bd6f1c1c78308bad02b6ecd7d
use std::{ f64::INFINITY, io::{stderr, Write}, time::Instant, }; use rand::{distributions::uniform, prelude::SmallRng, thread_rng, Rng, SeedableRng}; use rayon::iter::{IntoParallelIterator, ParallelIterator}; use raytracing::{ camera::Camera, hittable::{Hittable, HittableList, Sphere}, material...
use std::{ f64::INFINITY, io::{stderr, Write}, time::Instant, }; use rand::{distributions::uniform, prelude::SmallRng, thread_rng, Rng, SeedableRng}; use rayon::iter::{IntoParallelIterator, ParallelIterator}; use raytracing::{ camera::Camera, hittable::{Hittable, HittableList, Sphere}, material...
om_entropy(); let world = random_scene(&mut rng, true); let lookfrom = Point3::new(13, 2, 3); let lookat = Point3::new(0, 0, 0); let vup = Vec3::new(0, 1, 0); let focus_dist = 10.0; let aperture = 0.1; let camera = Camera::new( lookfrom, lookat, vup, 20...
n() -> Result<(), std::io::Error> { let start = Instant::now(); const ASPECT_RATIO: f64 = 16.0 / 9.0; const IMAGE_WIDTH: u64 = 400; const IMAGE_HEIGHT: u64 = (IMAGE_WIDTH as f64 / ASPECT_RATIO) as u64; const SAMPLES_PER_PIXEL: i32 = 100; const MAX_DEPTH: u8 = 50; let mut rng = Sm...
random
[ { "content": "pub fn random_in_unit_sphere(rng: &mut SmallRng) -> Point3 {\n\n loop {\n\n let p: Point3 = Vec3(\n\n rng.gen_range(-1.0..1.0),\n\n rng.gen_range(-1.0..1.0),\n\n rng.gen_range(-1.0..1.0),\n\n );\n\n if p.length_squared() < 1.0 {\n\n ...
Rust
src/lib.rs
SOF3/xylem
3c42e39b55ea4c2017a758a96273d35518d0c817
use std::any::TypeId; use std::fmt; #[doc(hidden)] pub use lazy_static::lazy_static; pub use xylem_codegen::Xylem; #[cfg(feature = "id")] pub mod id; #[cfg(feature = "id")] pub use id::{Id, IdArgs, IdString, Identifiable}; #[cfg(feature = "ext")] mod ext; #[cfg(feature = "ext")] pub use ext::*; pub trait Xylem<S:...
use std::any::TypeId; use std::fmt; #[doc(hidden)] pub use lazy_static::lazy_static; pub use xylem_codegen::Xylem; #[cfg(feature = "id")] pub mod id; #[cfg(feature = "id")] pub use id::{Id, IdArgs, IdString, Identifiable}; #[cfg(feature = "ext")] mod ext; #[cfg(feature = "ext")] pub use ext::*; pub trait Xylem<S:...
} pub trait Processable<S: Schema + ?Sized>: Xylem<S> { fn preprocess( _from: &mut <Self as Xylem<S>>::From, _context: &mut <S as Schema>::Context, ) -> Result<(), <S as Schema>::Error> { Ok(()) } fn postprocess( &mut self, _context: &mut <S...
fn convert_impl( _: Self::From, _: &mut <S as Schema>::Context, _: &Self::Args, ) -> Result<Self, <S as Schema>::Error> { Ok(()) }
function_block-full_function
[ { "content": "/// A trait for types that can be identified.\n\npub trait Identifiable<S: Schema>: Xylem<S> {\n\n /// The scope of the identifier namespace.\n\n ///\n\n /// Use `()` for global identifiers.\n\n type Scope: Xylem<S>;\n\n\n\n /// Returns the identifier for this instance.\n\n fn id...
Rust
edgelet/edgelet-http-mgmt/src/server/identity/update.rs
ngi644/iotedge
32860a7794e88932f83f4e01582d5f1d8f553347
use std::cell::RefCell; use std::sync::Arc; use failure::ResultExt; use futures::future::{self, Either, FutureResult}; use futures::{Future, Stream}; use http::header::{CONTENT_LENGTH, CONTENT_TYPE}; use http::{Request, Response, StatusCode}; use hyper::{Body, Error as HyperError}; use serde::Serialize; use serde_js...
use std::cell::RefCell; use std::sync::Arc; use failure::ResultExt; use futures::future::{self, Either, FutureResult}; use futures::{Future, Stream}; use http::header::{CONTENT_LENGTH, CONTENT_TYPE}; use http::{Request, Response, StatusCode}; use hyper::{Body, Error as HyperError}; use serde::Serialize; use serde_js...
body")); Ok(()) }) .wait() .unwrap(); } }
I: 'static + CoreIdentity + Serialize, { let identity = Identity::new( identity.module_id().to_string(), identity.managed_by().to_string(), identity.generation_id().to_string(), identity.auth_type().to_string(), ); serde_json::to_string(&identity) .context(ErrorKin...
random
[ { "content": "pub fn run() -> Result<(), Error> {\n\n // start app as a console app if an environment variable called\n\n // IOTEDGE_RUN_AS_CONSOLE exists\n\n if env::var(RUN_AS_CONSOLE_KEY).is_ok() {\n\n run_as_console()?;\n\n Ok(())\n\n } else {\n\n // kick-off the Windows ser...
Rust
term-lib/src/builtins/mount.rs
john-sharratt/ate
f9982e4d2b210942e6aa39aa03c1f3e72acb55e9
use std::future::Future; use std::path::Path; use std::pin::Pin; #[allow(unused_imports, dead_code)] use tracing::{debug, error, info, trace, warn}; use wasm_bus_process::prelude::StdioMode; use wasmer_vfs::FileSystem; use crate::bus::ProcessExecFactory; use crate::bus::SubProcessFactory; use crate::eval::EvalContext;...
use std::future::Future; use std::path::Path; use std::pin::Pin; #[allow(unused_imports, dead_code)] use tracing::{debug, error, info, trace, warn}; use wasm_bus_process::prelude::StdioMode; use wasmer_vfs::FileSystem; use crate::bus::ProcessExecFactory; use crate::bus::SubProcessFactory; use crate::eval::EvalContext;...
async fn print(msg: String, stdio: &mut Stdio, is_err: bool) { if is_err { error!("{}", msg); let _ = stdio.stdout.write(msg.as_bytes()).await; let _ = stdio.stdout.flush_async().await; } else { let _ = stdio.stderr.write(msg.as_bytes()).await; let _ = stdio.stderr.flush_...
function_block-full_function
[ { "content": "fn conv_fs_error(err: backend::FsError) -> FsError {\n\n match err {\n\n backend::FsError::BaseNotDirectory => FsError::BaseNotDirectory,\n\n backend::FsError::NotAFile => FsError::NotAFile,\n\n backend::FsError::InvalidFd => FsError::InvalidFd,\n\n backend::FsError:...
Rust
src/sixel.rs
SimonPersson/pica
f86cba0c56d197ffffe13a41114705c10ffa2340
use crate::error::Error; use image::{imageops::FilterType, DynamicImage}; use std::io::Write; pub fn image_to_sixel<W: Write>( width: Option<u32>, image: DynamicImage, mut output: W, ) -> Result<(), Error> { let image = if let Some(width) = width { image.resize(width, u32::MAX, FilterType::Lanc...
use crate::error::Error; use image::{imageops::FilterType, DynamicImage}; use std::io::Write; pub fn image_to_sixel<W: Write>( width: Option<u32>, image: DynamicImage, mut output: W, ) -> Result<(), Error> { let image = if let Some(width) = width { image.resize(width, u32::MAX, FilterType::Lanc...
struct Grouped<'a, K: Eq, T, F: Fn(T) -> K>(&'a [T], F); impl<'a, K: Eq, T: Copy, F: Fn(T) -> K> Iterator for Grouped<'a, K, T, F> { type Item = &'a [T]; fn next(&mut self) -> Option<Self::Item> { if self.0.is_empty() { return None; } let mut i = 1; let mut iter = s...
fn write_error(error: std::io::Error) -> Error { Error::Io { context: "when writing sixel to output stream".to_string(), error, } }
function_block-full_function
[ { "content": "fn try_main() -> Result<(), Error> {\n\n let mut width = None;\n\n let mut parser = lexopt::Parser::from_env();\n\n let mut files = vec![];\n\n while let Some(arg) = parser.next()? {\n\n match arg {\n\n Short('w') | Long(\"width\") => {\n\n width = Some...
Rust
src/transport/ntcp2/frame.rs
str4d/ire
a1619f14e7d7c62b8e9151b448a515dbcb5aaf7d
use cookie_factory::*; use nom::{ bits::{bits, streaming::take as take_bits}, bytes::streaming::{tag, take}, combinator::{complete, map}, error::Error as NomError, multi::{length_data, length_value, many1}, number::streaming::{be_u16, be_u32, be_u64, be_u8}, sequence::{pair, preceded, tuple}...
use cookie_factory::*; use nom::{ bits::{bits, streaming::take as take_bits}, bytes::streaming::{tag, take}, combinator::{complete, map}, error::Error as NomError, multi::{length_data, length_value, many1}, number::streaming::{be_u16, be_u32, be_u64, be_u8}, sequence::{pair, preceded, tuple}...
(i) } pub fn gen_session_created( input: (&mut [u8], usize), padlen: u16, ts_b: u32, ) -> Result<(&mut [u8], usize), GenError> { do_gen!( input, gen_slice!([0u8; 2]) >> gen_be_u16!(padlen) >> gen_slice!([0u8; 4]) >> gen_be_u32!(ts_b) >> ge...
map( tuple((take(2usize), be_u16, take(4usize), be_u32, take(4usize))), |(_, padlen, _, ts_b, _)| (padlen, ts_b), )
call_expression
[ { "content": "fn gen_data<'a>(input: (&'a mut [u8], usize), d: &[u8]) -> Result<(&'a mut [u8], usize), GenError> {\n\n do_gen!(input, gen_be_u32!(d.len()) >> gen_slice!(d))\n\n}\n\n\n\n// TunnelBuild\n\n\n", "file_path": "src/i2np/frame.rs", "rank": 3, "score": 334213.88310338533 }, { "co...
Rust
src/error.rs
jnicholls/binance-api
0093f8dd053c91de988c33597e485093f70d3db2
use std::clone::Clone; use std::convert::TryFrom; use std::fmt; use std::marker::{Copy, PhantomData}; use std::result; use derive_more::Constructor; use num_derive::FromPrimitive; use num_traits::FromPrimitive; use serde::{de, Deserialize}; use serde_repr::Deserialize_repr; pub type Result<T, C> = result::Result<T, E...
use std::clone::Clone; use std::convert::TryFrom; use std::fmt; use std::marker::{Copy, PhantomData}; use std::result; use derive_more::Constructor; use num_derive::FromPrimitive; use num_traits::FromPrimitive; use serde::{de, Deserialize}; use serde_repr::Deserialize_repr; pub type Result<T, C> = result::Result<T, E...
e as i16).map_err(|_| err) } } } deserializer.deserialize_i16(CodeVisitor::<C>::new()) } } impl<C> fmt::Display for Code<C> where C: ApiCode, { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { match self { Self::Common(c) => fmt::Displa...
E::invalid_value(de::Unexpected::Signed(value), &"a signed 16-bit integer"); if value < i64::from(i16::MIN) || value > i64::from(i16::MAX) { Err(err) } else { Self::Value::try_from(valu
function_block-random_span
[ { "content": "pub trait Api: Clone + Send + Sync {\n\n type ErrorCode: ApiCode + DeserializeOwned;\n\n\n\n fn host() -> &'static str;\n\n}\n\n\n\n#[derive(Clone, Debug)]\n\npub struct FApi;\n\nimpl Api for FApi {\n\n type ErrorCode = FApiCode;\n\n\n\n fn host() -> &'static str {\n\n FAPI_HOST...
Rust
crates/bls-gadgets/src/y_to_bit.rs
mrsmkl/celo-bls-snark-rs
8a1d6443ece97eb3969e15d5b006022a7f5124d4
#![allow(clippy::op_ref)] use algebra::{curves::bls12::Bls12Parameters, Field, One, PrimeField, Zero}; use r1cs_core::{ConstraintSystem, SynthesisError}; use r1cs_std::{ alloc::AllocGadget, boolean::Boolean, fields::{fp::FpGadget, FieldGadget}, groups::curves::short_weierstrass::bls12::{G1Gadget, G2Gad...
#![allow(clippy::op_ref)] use algebra::{curves::bls12::Bls12Parameters, Field, One, PrimeField, Zero}; use r1cs_core::{ConstraintSystem, SynthesisError}; use r1cs_std::{ alloc::AllocGadget, boolean::Boolean, fields::{fp::FpGadget, FieldGadget}, groups::curves::short_weierstrass::bls12::{G1Gadget, G2Gad...
t_value().unwrap()); } else { assert_eq!(false, y_bit.get_value().unwrap()); } assert_eq!(cs.num_constraints(), 3248); /* if !cs.is_satisfied() { println!("{}", cs.which_is_unsatisfied().unwrap()); ...
?; let bit = Boolean::alloc(cs.ns(|| "alloc y bit"), || Ok(el.get_value().get()? > half))?; let adjusted = FpGadget::alloc(cs.ns(|| "alloc y"), || { let el = el.get_value().get()?; let adjusted = if el > half { el - &half } else { el }; Ok(adjusted) })?; ...
random
[ { "content": "/// Hashes the message to produce a `hash_length` hash with the provided personalization\n\n///\n\n/// This uses Blake2s under the hood and is expensive for large messages.\n\n/// Consider reducing the input size by passing it through a Collision Resistant Hash function\n\n/// such as Pedersen.\n\...
Rust
src/events/event_callbacks.rs
Trivernis/serenity-rich-interactions
4a5d1e61226993288ea0ba2ccec52dbaece856cb
use crate::core::MessageHandle; use crate::menu::{get_listeners_from_context, MessageRef}; use crate::Result; use serenity::client::Context; use serenity::model::channel::Reaction; use serenity::model::id::{ChannelId, MessageId}; use std::sync::Arc; use tokio::time::Duration; static UPDATE_INTERVAL_SECS: u64 = 5; pub...
use crate::core::MessageHandle; use crate::menu::{get_listeners_from_context, MessageRef}; use crate::Result; use serenity::client::Context; use serenity::model::channel::Reaction; use serenity::model::id::{ChannelId
let mut msg = msg.lock().await; msg.on_deleted(ctx).await?; } Ok(()) } pub async fn handle_reaction_add(ctx: &Context, reaction: &Reaction) -> Result<()> { let mut affected_messages = Vec::new(); { let listeners = get_listeners_from_context(ctx).await?; log::trace!("Locking...
, MessageId}; use std::sync::Arc; use tokio::time::Duration; static UPDATE_INTERVAL_SECS: u64 = 5; pub async fn start_update_loop(ctx: &Context) -> Result<()> { let event_messages = get_listeners_from_context(ctx) .await .expect("Failed to get event message container"); let http = Arc::clone(&...
random
[ { "content": "use crate::core::MessageHandle;\n\nuse crate::error::{Error, Result};\n\nuse crate::menu::controls::{close_menu, next_page, previous_page, toggle_help};\n\nuse crate::menu::traits::EventDrivenMessage;\n\nuse crate::menu::typedata::HelpActiveContainer;\n\nuse crate::menu::{get_listeners_from_contex...
Rust
src/utils.rs
cthorner/glib
9cda7e5cf1b1f9b736a6f3536d03e5b0556d8df4
use error::BoolError; use glib_sys; use gstring::GString; use std; use std::ffi::{OsStr, OsString}; use std::path::{Path, PathBuf}; use std::ptr; use translate::*; use Error; pub fn get_program_name() -> Option<String> { get_prgname() } pub fn get_prgname() -> Option<String> { unsafe { from_glib_none(glib_s...
use error::BoolError; use glib_sys; use gstring::GString; use std; use std::ffi::{OsStr, OsString}; use std::path::{Path, PathBuf}; use std::ptr; use translate::*; use Error; pub fn get_program_name() -> Option<String> { get_prgname() } pub fn get_prgname() -> Option<String> { unsafe { from_glib_none(glib_s...
pub fn get_tmp_dir() -> Option<std::path::PathBuf> { #[cfg(not(all(windows, target_arch = "x86")))] use glib_sys::g_get_tmp_dir; #[cfg(all(windows, target_arch = "x86"))] use glib_sys::g_get_tmp_dir_utf8 as g_get_tmp_dir; unsafe { from_glib_none(g_get_tmp_dir()) } } pub fn mkstemp<P: AsRef<std::...
cfg(not(all(windows, target_arch = "x86")))] use glib_sys::g_get_home_dir; #[cfg(all(windows, target_arch = "x86"))] use glib_sys::g_get_home_dir_utf8 as g_get_home_dir; unsafe { from_glib_none(g_get_home_dir()) } }
function_block-function_prefix_line
[ { "content": "pub fn file_read_link<P: AsRef<std::path::Path>>(filename: P) -> Result<std::path::PathBuf, Error> {\n\n unsafe {\n\n let mut error = ptr::null_mut();\n\n let ret = glib_sys::g_file_read_link(filename.as_ref().to_glib_none().0, &mut error);\n\n if error.is_null() {\n\n ...
Rust
native/compiler/src/learn/ostia_compress.rs
aleksander-mendoza/SolomonoffLib
e65358070c4599d69bf1a4cf8e7d0573d22cd956
use std::io::{BufReader, BufRead}; use int_embedding::Alphabet; use int_seq::IntSeq; use std::collections::{HashSet, VecDeque, HashMap}; use std::borrow::{Borrow, BorrowMut}; use int_queue::IntQueue; use int_queue::IntQueue::End; use seq::Seq; use learn::ostia_compress::Kind::{Unknown, Accepting, Rejecting}; use std::p...
use std::io::{BufReader, BufRead}; use int_embedding::Alphabet; use int_seq::IntSeq; use std::collections::{HashSet, VecDeque, HashMap}; use std::borrow::{Borrow, BorrowMut}; use int_queue::IntQueue; use int_queue::IntQueue::End; use seq::Seq; use learn::ostia_compress::Kind::{Unknown, Accepting, Rejecting}; use std::p...
let mut t = r.make_state_to_index_table(); let mut b = new_output_buffer(255); let y = r.evaluate_to_string("a".chars()); let y = y.unwrap(); assert_eq!(String::from("a"), y); g.delete(ghost); }); } #[test] fn test_eq2() { Ghost::w...
let s = unsafe { s.as_ref() }; if let Accepting(out) = &s.output { let p = P::new(0, IntSeq::from(out.as_str().unwrap())); g.outgoing_mut().insert(n, p); } } if !init_has_incoming { N::delete(init_n, ghost); } g ...
random
[ { "content": "fn optimise<'a, Tr: Trans, F: Fn(&E, &*mut N) -> Tr>(state: *mut N, map: F, ghost: &Ghost) -> Transitions<Tr> {\n\n let outgoing = N::outgoing(state, ghost);\n\n if outgoing.is_empty() {\n\n return Transitions::blank();\n\n }\n\n let mut points: Vec<IBE> = Vec::new();\n\n for...
Rust
samplecode/tls/tlsclient/app/src/main.rs
lacabra/rust-sgx-sdk
af16efe23834010668ff210160868e963c389458
#![allow(deprecated)] extern crate sgx_types; extern crate sgx_urts; use sgx_types::*; use sgx_urts::SgxEnclave; extern crate mio; use mio::tcp::TcpStream; use std::os::unix::io::AsRawFd; use std::ffi::CString; use std::fs; use std::path; use std::env; use std::net::SocketAddr; use std::str; use std::ptr; use std:...
#![allow(deprecated)] extern crate sgx_types; extern crate sgx_urts; use sgx_types::*; use sgx_urts::SgxEnclave; extern crate mio; use mio::tcp::TcpStream; use std::os::unix::io::AsRawFd; use std::ffi::CString; use std::fs; use std::path; use std::env; use std::net::SocketAddr; use std::str; use std::ptr; use std:...
'outer: loop { poll.poll(&mut events, None).unwrap(); for ev in events.iter() { if !tlsclient.ready(&mut poll, &ev) { tlsclient.close(); break 'outer ; } } } } else { println!("[-] Tlsclient...
lose\r\nAccept-Encoding: identity\r\n\r\n", hostname); tlsclient.write_all(httpreq.as_bytes()).unwrap(); let mut poll = mio::Poll::new() .unwrap(); let mut events = mio::Events::with_capacity(32); tlsclient.register(&mut poll);
random
[ { "content": "// TODO: um, well, it turns out that openssl s_client/s_server\n\n// that we use for testing doesn't do ipv6. So we can't actually\n\n// test ipv6 and hence kill this.\n\nfn lookup_ipv4(host: &str, port: u16) -> SocketAddr {\n\n use std::net::ToSocketAddrs;\n\n\n\n let addrs = (host, port)....
Rust
src/packet.rs
alexyer/sfynx
1d5e259324a8d3e7316538a45c9a7e1ab422e08f
use std::{fmt::Debug, marker::PhantomData}; use cryptraits::{ convert::{FromBytes, Len, ToVec}, hash::Hash, hmac::Hmac, key::{Blind, SecretKey}, key_exchange::DiffieHellman, stream_cipher::StreamCipher, }; use crate::{ crypto::{generate_cipher_stream, generate_shared_secrets, xor}, h...
use std::{fmt::Debug, marker::PhantomData}; use cryptraits::{ convert::{FromBytes, Len, ToVec}, hash::Hash, hmac::Hmac, key::{Blind, SecretKey}, key_exchange::DiffieHellman, stream_cipher::StreamCipher, }; use crate::{ crypto::{generate_cipher_stream, generate_shared_secrets, xor}, h...
pub fn from_bytes( header_bytes: impl AsRef<[u8]>, payload_bytes: impl AsRef<[u8]>, ) -> Result<Self, SfynxError> { let header = Header::from_bytes(header_bytes)?; let payload = Vec::from(payload_bytes.as_ref()); Ok(Self { version: VERSION, ...
pub fn with_shared_secrets( session_key: ESK, circuit_pub_keys: Vec<<ESK as DiffieHellman>::PK>, routing_info: &[A], dest: impl Address, max_relays: u8, payload: &[u8], shared_secrets: &[<ESK as DiffieHellman>::SSK], ) -> Result<(Vec<<ESK as DiffieHellman>::SS...
function_block-full_function
[ { "content": "/// Sfynx address.\n\npub trait Address: Debug + Len + PartialEq {\n\n fn from_bytes(bytes: &[u8]) -> Self;\n\n fn to_vec(&self) -> Vec<u8>;\n\n}\n\n\n\n#[derive(Debug)]\n\npub enum SfynxError {\n\n WrongRoutingInfoLength,\n\n StreamCipherError(String),\n\n EmptyCircuit,\n\n KeyP...
Rust
async-graphql-parser/src/query.rs
phated/async-graphql
6ed3909a9a09fb42cd470269c62d7d5a3d4ed8f1
use crate::pos::Positioned; use crate::value::Value; use std::collections::HashMap; use std::fmt; #[derive(Debug, PartialEq, Clone)] pub enum Type { Named(String), List(Box<Type>), NonNull(Box<Type>), } impl fmt::Display for Type { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { mat...
use crate::pos::Positioned; use crate::value::Value; use std::collections::HashMap; use std::fmt; #[derive(Debug, PartialEq, Clone)] pub enum Type { Named(String), List(Box<Type>), NonNull(Box<Type>), } impl fmt::Display for Type { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { mat...
} pub type FragmentsMap = HashMap<String, Positioned<FragmentDefinition>>; #[derive(Debug, PartialEq, Eq, Copy, Clone)] pub enum OperationType { Query, Mutation, Subscription, } #[derive(Debug, Clone)] pub struct CurrentOperation { pub ty: OperationType, pub variable_definitions: Vec<Positioned<...
pub fn get_argument(&self, name: &str) -> Option<&Positioned<Value>> { self.arguments .iter() .find(|item| item.0.node == name) .map(|item| &item.1) }
function_block-full_function
[ { "content": "fn validate_type(ctx: &mut VisitorContext<'_>, type_name: &str, pos: Pos) {\n\n if ctx.registry.types.get(type_name).is_none() {\n\n ctx.report_error(vec![pos], format!(r#\"Unknown type \"{}\"\"#, type_name));\n\n }\n\n}\n\n\n\n#[cfg(test)]\n\nmod tests {\n\n use super::*;\n\n u...
Rust
exercises/practice/poker/src/lib.rs
MProtasevich/rust
e895658702e467e2072987f152496cb172b08c44
use Combination::{ StraightFlush, FourOfAKind, FullHouse, Flush, Straight, ThreeOfAKind, TwoPairs, OnePair, HighCard }; use Rank::{ N, Jack, Queen, King, Ace }; use std::cmp::{ Ord, Ordering, Reverse }; use std::collections::{ BTreeMap, HashSet }; #[derive(Copy, Clone, Debug, PartialOrd, PartialEq, Eq)] enum Rank { ...
use Combination::{ StraightFlush, FourOfAKind, FullHouse, Flush, Straight, ThreeOfAKind, TwoPairs, OnePair, HighCard }; use Rank::{ N, Jack, Queen, King, Ace }; use std::cmp::{ Ord, Ordering, Reverse }; use std::collections::{ BTreeMap, HashSet }; #[derive(Copy, Clone, Debug, PartialOrd, PartialEq, Eq)] enum Rank { ...
} impl Combination { fn parse(hand: &str) -> Self { let hand_cards: Vec<Card> = hand.split(" ").map(Card::new).collect(); if hand_cards.len() != 5 { panic!("There should be 5 cards. Cards are: `{}`", hand); } let canonical_symb_view: BTreeMap<Rank, Vec<Suit>> = hand_ca...
fn cmp(&self, other: &Self) -> Ordering { match_combinations!((self, other), StraightFlush, FourOfAKind, FullHouse, Flush, Straight, ThreeOfAKind, TwoPairs, OnePair, HighCard ) }
function_block-full_function
[ { "content": "fn assert_alphametic_solution_eq(puzzle: &str, solution: &[(char, u8)]) {\n\n let answer = alphametics::solve(puzzle);\n\n let solution: HashMap<char, u8> = solution.iter().cloned().collect();\n\n assert_eq!(answer, Some(solution));\n\n}\n\n\n", "file_path": "exercises/practice/alpham...
Rust
cerk_loader_file/src/config_parser.rs
ce-rust/cerk
439c329ee1361283a915a51772c85b7a18f0f50b
use crate::start_links::ComponentStartLinks; use anyhow::{Context, Result}; use cerk::kernel::{ScheduleInternalServer, ScheduleInternalServerStatic, StartOptions}; use serde::Deserialize; use std::collections::HashMap; #[derive(Deserialize, Debug, PartialEq)] struct Configuration { scheduler: String, router: S...
use crate::start_links::ComponentStartLinks; use anyhow::{Context, Result}; use cerk::kernel::{ScheduleInternalServer, ScheduleInternalServerStatic, StartOptions}; use serde::Deserialize; use std::collections::HashMap; #[derive(Deserialize, Debug, PartialEq)] struct Configuration { scheduler: String, router: S...
pub fn parse_json_to_start_options<'a>( config_content: String, links: ComponentStartLinks<'static>, ) -> Result<StartOptions> { let config = parse_json_to_config(config_content)?; parse_config_to_start_options(&links, &config) } #[cfg(test)] mod tests { use super::*; use cerk::kernel::Kernel...
s> { let ports: Vec<Result<ScheduleInternalServerStatic>> = config .ports .iter() .map(|(id, name)| { Ok(ScheduleInternalServer { id: id.to_string(), function: get_link(name, &links.ports)?, }) }) .collect(); if let...
function_block-function_prefixed
[ { "content": "fn build_configurations(config: Config) -> Result<Configurations> {\n\n let host = config.get_op_val_string(\"host\")?.unwrap();\n\n let send_topic = config.get_op_val_string(\"send_topic\")?;\n\n let subscribe_topic = config.get_op_val_string(\"subscribe_topic\")?;\n\n let subscribe_q...
Rust
tracker/src/lib.rs
mcwindy/SOPT
fc16f2e237b8dd3f1502539c49cd369354805fba
#[macro_use] extern crate redis_module; use peerinfo::PeerInfo; use redis_module::{native_types::RedisType, Status}; use redis_module::{raw, Context, RedisError, RedisResult, RedisValue}; use seederinfo::SeederInfo; use std::os::raw::c_void; use std::time::Duration; use std::{convert::TryFrom, str::FromStr}; mod peer...
#[macro_use] extern crate redis_module; use peerinfo::PeerInfo; use redis_module::{native_types::RedisType, Status}; use redis_module::{raw, Context, RedisError, RedisResult, RedisValue}; use seederinfo::SeederInfo; use std::os::raw::c_void; use std::time::Duration; use std::{convert::TryFrom, str::FromStr}; mod peer...
w = dummy_request(); raw[5] = "-1".into(); let req = AnnounceRequest::try_from(raw); assert!(req.is_err()); } #[test] fn check_parse_request5() { let mut raw = dummy_request(); raw[5] = "65536".into(); let req = AnnounceRequest::try_from(raw); assert!...
3() { let mut raw = dummy_request(); raw.pop(); let req = AnnounceRequest::try_from(raw); assert!(req.is_err()); } #[test] fn check_parse_request4() { let mut ra
random
[ { "content": "type Key = u64;\n", "file_path": "tracker/src/seederinfo/mod.rs", "rank": 0, "score": 241788.09047182018 }, { "content": "/// Verify password selected from password with\n\n/// user input.\n\n/// Used crate: rust-argon2, champion of HPC.\n\npub fn verify_password(password: &str...
Rust
src/private.rs
masonium/gemini-exchange-rs
8e90f076bbcfffeeb80e97ab1279d8fdd306e0cb
use super::structs::order::{Order, OrderId, OrderResponse}; use super::structs::private::{AccountBalance, AccountTrade, CancelRequest, PastTrades, Payload}; use crate::{ structs::private::{CancelResponse, NotionalVolume}, types::{GError, Response, Result}, }; use crypto::{hmac::Hmac, mac::Mac, sha2::Sha384}; u...
use super::structs::order::{Order, OrderId, OrderResponse}; use super::structs::private::{AccountBalance, AccountTrade, CancelRequest, PastTrades, Payload}; use crate::{ structs::private::{CancelResponse, NotionalVolume}, types::{GError, Response, Result}, }; use crypto::{hmac::Hmac, mac::Mac, sha2::Sha384}; u...
fn request<T: Serialize>(&self, uri: &str, body: &Payload<T>) -> Request<Body> { let uri: Uri = (self.uri.to_string() + uri).parse().unwrap(); let payload_str = serde_json::to_string(&body).expect("serialization failure"); let payload = base64::encode(&payload_str...
rate) fn sign(secret: &str, payload: &str) -> String { let mut hasher = Hmac::new(Sha384::new(), secret.as_bytes()); hasher.input(payload.as_bytes()); let mut buf = vec![0; hasher.output_bytes()]; hasher.raw_result(&mut buf); buf.encode_hex() }
function_block-function_prefixed
[ { "content": "/// Parse an `OrderId` from a string or u64 representation.\n\npub fn order_id_from_string<'de, D>(d: D) -> Result<OrderId, D::Error>\n\nwhere\n\n D: Deserializer<'de>,\n\n{\n\n d.deserialize_any(OrderIdInQuotes)\n\n}\n\n\n\n/// Side of the order (buy or sell)\n\n#[derive(Serialize, Deserial...
Rust
src/output.rs
dvc94ch/client-toolkit
38a93b0bc5196d25032cd5965aeef35a0cc01710
use std::sync::{Arc, Mutex}; use wayland_client::protocol::wl_output::{self, Event, RequestsTrait, WlOutput}; use wayland_client::protocol::wl_registry::{self, RequestsTrait as RegistryRequest}; use wayland_client::Proxy; pub use wayland_client::protocol::wl_output::{Subpixel, Transform}; #[derive(Copy, Clone, Deb...
use std::sync::{Arc, Mutex}; use wayland_client::protocol::wl_output::{self, Event, RequestsTrait, WlOutput}; use wayland_client::protocol::wl_registry::{self, RequestsTrait as RegistryRequest}; use wayland_client::Proxy; pub use wayland_client::protocol::wl_output::{Subpixel, Transform}; #[derive(Copy, Clone, Deb...
} struct Inner { outputs: Vec<(u32, Proxy<WlOutput>, OutputInfo)>, pending: Vec<(Proxy<WlOutput>, Event)>, } impl Inner { fn merge(&mut self, output: &Proxy<WlOutput>) { let info = match self .outputs .iter_mut() .find(|&&mut (_, ref o, _)| o.equals(output)) ...
w(), location: (0, 0), physical_size: (0, 0), subpixel: Subpixel::Unknown, transform: Transform::Normal, scale_factor: 1, modes: Vec::new(), } }
function_block-function_prefixed
[ { "content": "/// Implement a keyboard to automatically detect the keymap\n\n///\n\n/// This requires you to provide an implementation to receive the events after they\n\n/// have been interpreted with the keymap.\n\n///\n\n/// The keymap information will be loaded from the events sent by the compositor,\n\n///...
Rust
src/consumer/mod.rs
gridgentoo/rust-rdkafka
fcb0bab41894e96208fd745e79ce7f73e4bcebbe
pub mod base_consumer; pub mod stream_consumer; pub use self::base_consumer::BaseConsumer; pub use self::stream_consumer::{MessageStream, StreamConsumer}; use rdsys; use rdsys::types::*; use client::{Context, NativeClient}; use error::KafkaResult; use groups::GroupList; use message::BorrowedMessage; use metadata::M...
pub mod base_consumer; pub mod stream_consumer; pub use self::base_consumer::BaseConsumer; pub use self::stream_consumer::{MessageStream, StreamConsumer}; use rdsys; use rdsys::types::*; use client::{Context, NativeClient}; use error::KafkaResult; use groups::GroupList; use message::BorrowedMessage; use metadata::M...
#[allow(unused_variables)] fn pre_rebalance<'a>(&self, rebalance: &Rebalance<'a>) {} #[allow(unused_variables)] fn post_rebalance<'a>(&self, rebalance: &Rebalance<'a>) {} #[allow(unused_variables)] fn commit_callback(&self, result: KafkaResult<()>, offsets: *mut...
RDKafkaRespErr::RD_KAFKA_RESP_ERR__REVOKE_PARTITIONS => { rdsys::rd_kafka_assign(native_client.ptr(), ptr::null()); } _ => { rdsys::rd_kafka_assign(native_client.ptr(), ptr::null()); } } } self.post_rebal...
function_block-function_prefix_line
[ { "content": "/// A `ProducerContext` is a `Context` specific for producers. It can be used to store user-specified\n\n/// callbacks, such as `delivery`.\n\npub trait ProducerContext: Context {\n\n /// A DeliveryContext is a user-defined structure that will be passed to the producer when\n\n /// producing...
Rust
src/libextra/term.rs
sarojaba/rust-doc-korean
145943c1a12f7ad7adf7821709682d70f0cefc9d
#[allow(missing_doc)]; use std::io; #[cfg(not(target_os = "win32"))] use std::os; #[cfg(not(target_os = "win32"))] use terminfo::*; #[cfg(not(target_os = "win32"))] use terminfo::searcher::open; #[cfg(not(target_os = "win32"))] use terminfo::parser::compiled::parse; #[cfg(not(target_os = "win32"))] use terminfo::pa...
#[allow(missing_doc)]; use std::io; #[cfg(not(target_os = "win32"))] use std::os; #[cfg(not(target_os = "win32"))] use terminfo::*; #[cfg(not(target_os = "win32"))] use terminfo::searcher::open; #[cfg(not(target_os = "win32"))] use terminfo::parser::compiled::parse; #[cfg(not(target_os = "win32"))] use terminfo::pa...
pub fn reset(&self) { let mut vars = Variables::new(); let s = do self.ti.strings.find_equiv(&("op")) .map_consume_default(Err(~"can't find terminfo capability `op`")) |op| { expand(copy *op, [], &mut vars) }; if s.is_...
pub fn bg(&self, color: color::Color) { let color = self.dim_if_necessary(color); if self.num_colors > color { let s = expand(*self.ti.strings.find_equiv(&("setab")).unwrap(), [Number(color as int)], &mut Variables::new()); if s.is_ok() { ...
function_block-full_function
[ { "content": "enum Color { cyan, magenta, yellow, black }\n\n\n\nimpl Equal for Color {\n\n fn isEq(a: Color, b: Color) -> bool {\n\n match (a, b) {\n\n (cyan, cyan) => { true }\n\n (magenta, magenta) => { true }\n\n (yellow, yellow) => { true }\n\n (blac...
Rust
builder/src/lib.rs
sminez/proc-macro-workshop
02aa796e59c446c20960e032d8b66abba084f65d
use proc_macro::TokenStream; use quote::{format_ident, quote, ToTokens}; use syn::{ parse_macro_input, Attribute, Data::Struct, DataStruct, DeriveInput, Field, Fields::Named, GenericArgument, Ident, Lit, Meta, NestedMeta, PathArguments, Type, TypePath, }; fn wrapped_type<'a>(wrapper: &str, ty: &'a Type) -> std...
use proc_macro::TokenStream; use quote::{format_ident, quote, ToTokens}; use syn::{ parse_macro_input, Attribute, Data::Struct, DataStruct, DeriveInput, Field, Fields::Named, GenericArgument, Ident, Lit, Meta, NestedMeta, PathArguments, Type, TypePath, }; fn wrapped_type<'a>(wrapper: &str, ty: &'a Type) -> std...
fn builder_attr(f: &Field) -> Option<&Attribute> { for attr in f.attrs.iter() { let segs = &attr.path.segments; if segs.len() == 1 && segs[0].ident == "builder" { return Some(attr); } } None } fn builder_attr_error<T: ToTokens>(t: T) -> Option<(bool, proc_macro2::Token...
if let Some(GenericArgument::Type(ref t)) = inner.args.first() { return Some(t); } } } None }
function_block-function_prefix_line
[ { "content": "type None = ();\n", "file_path": "builder/tests/09-redefined-prelude-types.rs", "rank": 1, "score": 112810.18482558479 }, { "content": "fn main() {}\n", "file_path": "sorted/tests/06-pattern-path.rs", "rank": 3, "score": 72288.21193405015 }, { "content": "fn...
Rust
examples/counter.rs
Nemo157/vdom-websocket-rsjs
a87087b222915be50a2ee08f490ecc9dfef89984
#[macro_use] extern crate serde_derive; extern crate futures; extern crate tokio; extern crate tokio_core; extern crate vdom_rsjs; extern crate vdom_websocket_rsjs; extern crate serde; use std::time::{Instant, Duration}; use std::sync::Arc; use vdom_rsjs::{VNode, VTag, VProperty}; use vdom_rsjs::render::{Render, Cac...
#[macro_use] extern crate serde_derive; extern crate futures; extern crate tokio; extern crate tokio_core; extern crate vdom_rsjs; extern crate vdom_websocket_rsjs; extern crate serde; use std::time::{Instant, Duration}; use std::sync::Arc; use vdom_rsjs::{VNode, VTag, VProperty}; use vdom_rsjs::render::{Render, Cac...
Arc::new(State { count, handle: self.handle.clone(), actions: self.actions.clone(), }) } } impl Render<Action<ActionTag>> for State { fn render(&self, _cache: &mut Cache<Action<ActionTag>>) -> VNode<Action<ActionTag>> { VTag::new("div") ...
if count % 2 == 0 { let reaction = Action::new(match action.tag { ActionTag::Increment => ActionTag::Decrement, ActionTag::Decrement => ActionTag::Increment, }); let delay = Instant::now() + Duration::from_millis(200); let actions = self.ac...
if_condition
[ { "content": "pub fn serve<ActionTag, ClientSink, ClientStream, NewClient>(handle: Handle, mut new_client: NewClient) -> impl Future<Item = (), Error = ()>\n\nwhere ActionTag: Serialize + for<'a> Deserialize<'a> + Debug,\n\n ClientSink: Sink<SinkItem = Action<ActionTag>, SinkError = ()> + 'static,\n\n ...
Rust
illume/src/image.rs
zakarumych/wilds
0297e8b42917ec80152dc05fbb36b22853b2dc41
pub use {self::Samples::*, crate::backend::Image}; use { crate::{ format::{AspectFlags, Format}, memory::MemoryUsage, Extent2d, Extent3d, ImageSize, Offset3d, }, std::ops::Range, }; bitflags::bitflags! { #[cfg_attr(feature = "serde-1", derive(serde::Serialize, serde::Deserialize...
pub use {self::Samples::*, crate::backend::Image}; use { crate::{ format::{AspectFlags, Format}, memory::MemoryUsage, Extent2d, Extent3d, ImageSize, Offset3d, }, std::ops::Range, }; bitflags::bitflags! { #[cfg_attr(feature = "serde-1", derive(serde::Serialize, serde::Deserialize...
tart); ImageSubresourceRange { aspect, first_level: levels.start, level_count: levels.end - levels.start, first_layer: layers.start, layer_count: layers.end - layers.start, } } pub fn whole(info: &ImageInfo) -> Self { ImageSub...
vel_count: u32, pub first_layer: u32, pub layer_count: u32, } impl ImageSubresourceRange { pub fn new( aspect: AspectFlags, levels: Range<u32>, layers: Range<u32>, ) -> Self { assert!(levels.end >= levels.start); assert!(layers.end >= layers.s
random
[]
Rust
inferrust/src/rules/others.rs
pchampin/inferrust_rs
6dbd24f8df216f7e4681018aa38b1a20613e6c3a
use crate::inferray::*; use crate::rules::*; pub(crate) fn PRP_FP(ts: &TripleStore) -> RuleResult { let mut output = vec![]; let pairs_mut = ts.chunks().get(NodeDictionary::prop_idx_to_offset( NodeDictionary::rdftype as u64, )); if pairs_mut == None { return output; } ...
use crate::inferray::*; use crate::rules::*; pub(crate) fn PRP_FP(ts: &TripleStore) -> RuleResult { let mut output = vec![]; let pairs_mut = ts.chunks().get(NodeDictionary::prop_idx_to_offset( NodeDictionary::rdftype as u64, )); if pairs_mut == None { return output; } ...
{ break; } let pairs2 = pairs1.unwrap().so(); if pairs2.is_empty() { break; } let pairs1 = pairs1.unwrap().so(); for pair1 in pairs1 { for pair2 in pairs2 { if pair1[0] ...
); let expected_o = NodeDictionary::owlfunctionalProperty as u64; for pair in pairs { if pair[0] > expected_o { break; } if pair[0] == expected_o { let prop = pair[1]; let raw_prop = NodeDictionary::prop_idx_to_offset(prop); let pa...
function_block-random_span
[ { "content": "/// Sort the pairs and remove duplicates.\n\n///\n\n/// # Return value\n\n/// Return the new size of pairs (once duplicates have been removed).\n\npub fn bucket_sort_pairs(pairs: &mut Vec<[u64; 2]>) -> usize {\n\n if pairs.is_empty() {\n\n return 0;\n\n }\n\n let (min, max) = pairs...
Rust
remud-lib/src/world/scripting/execution.rs
krixi/remud
b9dc5758ea4318f9a4f6fdb3c3ea6e4146dd29d6
use std::sync::{Arc, RwLock}; use crate::{ ecs::SharedWorld, world::{ action::Action, scripting::{modules::Me, ExecutionErrors, ScriptAst, ScriptEngine, ScriptName, Scripts}, }, }; use crate::metrics::stats_incr; use bevy_ecs::prelude::*; use rhai::{Dynamic, Engine, Scope, AST}; pub type ...
use std::sync::{Arc, RwLock}; use crate::{ ecs::SharedWorld, world::{ action::Action, scripting::{modules::Me, ExecutionErrors, ScriptAst, ScriptEngine, ScriptName, Scripts}, }, }; use crate::metrics::stats_incr; use bevy_ecs::prelude::*; use rhai::{Dynamic, Engine, Scope, AST}; pub type ...
; let mut scope = Scope::new(); scope.push_constant( "SELF", Me { world: world.clone(), entity, }, ); scope.push_constant("WORLD", world.clone()); scope.push_constant("EVENT", event.clone()); scope.push_dynamic("allow_action", Dynamic::from(true))...
match prepare_script_execution(&*world.read().unwrap(), &script) { Some(results) => results, None => return true, }
if_condition
[ { "content": "pub fn create_script(world: &mut World, script: Script) -> Result<Option<ParseError>, ScriptError> {\n\n tracing::debug!(\"creating {:?}.\", script.name);\n\n\n\n if world\n\n .get_resource::<Scripts>()\n\n .unwrap()\n\n .by_name(&script.name)\n\n .is_some()\n\n ...