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
crates/types/src/offchain/extension.rs
keroro520/godwoken
e889341b60db742034056586ce9df7511d849cda
use crate::packed::{ AccountMerkleState, Byte32, CompactMemBlock, GlobalState, GlobalStateV0, MemBlock, RawWithdrawalRequest, Script, TransactionKey, TxReceipt, WithdrawalKey, WithdrawalRequest, WithdrawalRequestExtra, }; use crate::prelude::*; use ckb_types::error::VerificationError; use sparse_merkle_tree...
use crate::packed::{ AccountMerkleState, Byte32, CompactMemBlock, GlobalState, GlobalStateV0, MemBlock, RawWithdrawalRequest, Script, TransactionKey, TxReceipt, WithdrawalKey, WithdrawalRequest, WithdrawalRequestExtra, }; use crate::prelude::*; use ckb_types::error::VerificationError; use sparse_merkle_tree...
} impl CompactMemBlock { pub fn from_full_compatible_slice(slice: &[u8]) -> Result<CompactMemBlock, VerificationError> { match CompactMemBlock::from_slice(slice) { Ok(block) => Ok(block), Err(_) => MemBlock::from_slice(slice).map(Into::into), } } } impl WithdrawalReque...
fn from(block: MemBlock) -> Self { CompactMemBlock::new_builder() .txs(block.txs()) .withdrawals(block.withdrawals()) .deposits(block.deposits()) .build() }
function_block-full_function
[ { "content": "pub fn build_account_key(id: u32, key: &[u8]) -> H256 {\n\n let mut raw_key = [0u8; 32];\n\n let mut hasher = new_blake2b();\n\n hasher.update(&id.to_le_bytes());\n\n hasher.update(&[GW_ACCOUNT_KV_TYPE]);\n\n hasher.update(key);\n\n hasher.finalize(&mut raw_key);\n\n raw_key.i...
Rust
rustler/src/types/binary.rs
wingyplus/rustler
5d07755bf180a612cf1886c7e099706b26567455
use crate::wrapper::binary::{alloc, realloc, ErlNifBinary}; use crate::{Decoder, Encoder, Env, Error, NifResult, Term}; use std::borrow::{Borrow, BorrowMut}; use std::io::Write; use std::mem::MaybeUninit; use std::ops::{Deref, DerefMut}; pub struct OwnedBinary(ErlNifBinary); impl<'a> OwnedBinary { pub unsafe fn ...
use crate::wrapper::binary::{alloc, realloc, ErlNifBinary}; use crate::{Decoder, Encoder, Env, Error, NifResult, Term}; use std::borrow::{Borrow, BorrowMut}; use std::io::Write; use std::mem::MaybeUninit; use std::ops::{Deref, DerefMut}; pub struct OwnedBinary(ErlNifBinary); impl<'a> OwnedBinary { pub unsafe fn ...
nner.size) } } pub fn make_subbinary(&self, offset: usize, length: usize) -> NifResult<Binary<'a>> { let min_len = length.checked_add(offset); if min_len.ok_or(Error::BadArg)? > self.inner.size { return Err(Error::BadArg); } let raw_term = unsafe { ...
let mut bin = std::mem::ManuallyDrop::new(bin); let term = unsafe { Term::new( env, rustler_sys::enif_make_binary(env.as_c_arg(), &mut bin.0), ) }; Binary { inner: bin.0, term } } pub fn to_owne...
random
[ { "content": "pub fn map_new(env: Env) -> Term {\n\n unsafe { Term::new(env, map::map_new(env.as_c_arg())) }\n\n}\n\n\n\n/// ## Map terms\n\nimpl<'a> Term<'a> {\n\n /// Constructs a new, empty map term.\n\n ///\n\n /// ### Elixir equivalent\n\n /// ```elixir\n\n /// %{}\n\n /// ```\n\n p...
Rust
src/align.rs
dankamongmen/libnotcurses-sys
ec78ef7a373b59b4bf48ec8c626e7cc26e5380ac
#[repr(u32)] #[derive(Debug, Clone, Copy, PartialEq, Eq)] pub enum NcAlign { Unaligned = c_api::NCALIGN_UNALIGNED, Left = c_api::NCALIGN_LEFT, Center = c_api::NCALIGN_CENTER, Right = c_api::NCALIGN_RIGHT, } mod std_impls { use super::{c_api, NcAlign}; use std::fmt; im...
#[repr(u32)] #[derive(Debug, Clone, Copy, PartialEq, Eq)] pub enum NcAlign { Unaligned = c_api::NCALIGN_UNALIGNED, Left = c_api::NCALIGN_LEFT, Center = c_api::NCALIGN_CENTER, Right = c_api::NCALIGN_RIGHT, } mod std_impls { use super::{c_api, NcAlign}; use std::fmt; im...
} } impl From<NcAlign> for c_api::NcAlign_u32 { fn from(align: NcAlign) -> Self { use {c_api::*, NcAlign::*}; match align { Left => NCALIGN_LEFT, Center => NCALIGN_CENTER, Right => NCALIGN_RIGHT, Unaligned ...
match align { NCALIGN_LEFT => Left, NCALIGN_CENTER => Center, NCALIGN_RIGHT => Right, NCALIGN_UNALIGNED => Unaligned, _ => Unaligned, }
if_condition
[ { "content": "#[inline]\n\npub fn notcurses_top(nc: &mut Nc) -> &mut NcPlane {\n\n unsafe { &mut *c_api::ncpile_top(c_api::notcurses_stdplane(nc)) }\n\n}\n", "file_path": "src/notcurses/reimplemented.rs", "rank": 0, "score": 239968.14741602243 }, { "content": "#[inline]\n\npub fn notcurse...
Rust
examples/replace_material.rs
Elabajaba/bevy_ecs_tilemap
a8d285a72e0cef868d807d34eba43db8fc76c3b7
use bevy::prelude::*; use bevy_ecs_tilemap::prelude::*; mod helpers; #[derive(Default)] struct DidUpdate { value: bool, } struct Materials { a: Handle<ColorMaterial>, b: Handle<ColorMaterial>, } fn startup( mut commands: Commands, asset_server: Res<AssetServer>, mut materials: ResMut<Assets<...
use bevy::prelude::*; use bevy_ecs_tilemap::prelude::*; mod helpers; #[derive(Default)] struct DidUpdate { value: bool, } struct Materials { a: Handle<ColorMaterial>, b: Handle<ColorMaterial>, } fn startup( mut commands: Commands, asset_server: Res<AssetServer>, mut materials: ResMut<Assets<...
} } did_update.value = true; } } } fn main() { env_logger::Builder::from_default_env() .filter_level(log::LevelFilter::Info) .init(); App::build() .insert_resource(WindowDescriptor { width: 1270.0, height: 72...
if let Ok(mut m) = material { *m = materials.b.clone(); }
if_condition
[ { "content": "fn build_map(map_query: &mut MapQuery, commands: &mut Commands) {\n\n let mut random = thread_rng();\n\n\n\n for _ in 0..100 {\n\n let position = TilePos(random.gen_range(0..16), random.gen_range(0..16));\n\n // Ignore errors for demo sake.\n\n let _ = map_query.set_tile...
Rust
doc_store/src/lib.rs
phideg/veloci
2170909e0e0972f8d741344ced047105fdbeda50
use vint32::vint_array::VIntArray; use vint32::iterator::VintArrayIterator; use std::{ cmp::Ordering::Greater, io, io::{prelude::*}, mem, }; const FLUSH_THRESHOLD: usize = 16_384; const VALUE_OFFSET: u64 = 1; #[derive(Debug)] pub struct DocLoader {} impl DocLoader { pub fn get_doc(data_reade...
use vint32::vint_array::VIntArray; use vint32::iterator::VintArrayIterator; use std::{ cmp::Ordering::Greater, io, io::{prelude::*}, mem, }; const FLUSH_THRESHOLD: usize = 16_384; const VALUE_OFFSET: u64 = 1; #[derive(Debug)] pub struct DocLoader {} impl DocLoader { pub fn get_doc(data_reade...
let document_start_pos = data_start + doc_offsets_in_block[pos_in_block + 1] as usize; let document_end_pos = data_start + doc_offsets_in_block[pos_in_block] as usize; output.resize(document_start_pos, 0); let doc = output.split_off(document_end_pos); let s = unsafe { Strin...
et mut output = lz4_flex::decompress_size_prepended(&data_reader[start as usize..end as usize]).unwrap(); let mut arr = VintArrayIterator::new(&output); let arr_size = arr.next().unwrap(); let mut data_start = arr.pos; let mut arr = VintArrayIterator::new(&output[arr.pos..arr.pos + arr...
function_block-random_span
[ { "content": "pub fn bench_naivehashmap_insert_with_lookup(num_hits: u32, token_hits: u32) {\n\n let mut hits: NaiveHashMap<u64, f32> = bench_naivehashmap_insert(num_hits);\n\n for x in 0..token_hits {\n\n let stat = hits.entry(u64::from(pseudo_rand(x))).or_insert(0.0);\n\n *stat += 2.0;\n\n...
Rust
src/camera.rs
hockeybuggy/ray_tracer
96f281ab3987e19249fe2d9afca38afa79b6e7db
use crate::canvas; use crate::matrix; use crate::matrix::Inverse; use crate::ray; use crate::tuple; use crate::world; pub struct Camera { hsize: u32, vsize: u32, half_width: f64, half_height: f64, pixel_size: f64, pub transform: matrix::Matrix4, } impl Camera { pub fn new(hsize: u32, vsize...
use crate::canvas; use crate::matrix; use crate::matrix::Inverse; use crate::ray; use crate::tuple; use crate::world; pub struct Camera { hsize: u32, vsize: u32, half_width: f64, half_height: f64, pixel_size: f64, pub transform: matrix::Matrix4, } impl Camera { pub fn new(hsize: u32, vsize...
); big_guy.set_transformation_matrix(matrix::Matrix4::IDENTITY.scaling(5.0, 5.0, 5.0)); let mut material = material::material(); material.color = color::color(0.5, 1.0, 0.5); material.diffuse = 0.7; material.specular = 0.3; big_guy.material = mater...
= ((x as f64) + 0.5) * self.pixel_size; let yoffset = ((y as f64) + 0.5) * self.pixel_size; let world_x = self.half_width - xoffset; let world_y = self.half_height - yoffset; let inverse_transform = self.transform.inverse().unwrap(); let pixel = inverse_transf...
random
[ { "content": "fn translation(x: f64, y: f64, z: f64) -> matrix::Matrix4 {\n\n matrix::Matrix4::new((\n\n (1.0, 0.0, 0.0, x),\n\n (0.0, 1.0, 0.0, y),\n\n (0.0, 0.0, 1.0, z),\n\n (0.0, 0.0, 0.0, 1.0),\n\n ))\n\n}\n\n\n", "file_path": "src/transformation.rs", "rank": 0, ...
Rust
src/codec/ffmpeg/encoder.rs
0xd34d10cc/shar
4c586c1a9995e7cdcb74f4449cc670caf348caa7
use std::ffi::CStr; use anyhow::{anyhow, Result}; use ffmpeg_sys as ff; use iced::image; use iced_native::image::Data; use super::codec::Codec; use super::context::Context; use super::error::{Error, ErrorKind}; use super::frame::Frame; use super::unit::Unit; use crate::codec; pub struct Encoder { context: Contex...
use std::ffi::CStr; use anyhow::{anyhow, Result}; use ffmpeg_sys as ff; use iced::image; use iced_native::image::Data; use super::codec::Codec; use super::context::Context; use super::error::{Error, ErrorKind}; use super::frame::Frame; use super::unit::Unit; use crate::codec; pub struct Encoder { context: Contex...
pub fn encode(&mut self, mut frame: Frame, units: &mut Vec<Unit>) -> Result<()> { let pts = self.next_pts(); frame.set_pts(pts); unsafe { let code = ff::avcodec_send_frame(self.context.as_mut_ptr(), frame.as_mut_ptr()); if code != 0 { ...
pub fn new(config: codec::Config) -> Result<Self> { let priority_list = [b"h264_nvenc\0"]; let mut codec = None; for &name in priority_list.iter() { let name = CStr::from_bytes_with_nul(name).unwrap(); if let Some(c) = Codec::find_encoder(name) { codec = ...
function_block-full_function
[ { "content": "pub fn load() -> Result<Config> {\n\n let config_file = match File::open(path()?) {\n\n Ok(file) => file,\n\n Err(e) if e.kind() == ErrorKind::NotFound => return Ok(Config::default()),\n\n Err(e) => return Err(e.into()),\n\n };\n\n\n\n let config: ConfigData = serde_j...
Rust
kurobako_core/src/solver.rs
hvy/kurobako
35b24596cea73148a9fa942c283e88238a313ef4
use crate::problem::ProblemSpec; use crate::registry::FactoryRegistry; use crate::rng::ArcRng; use crate::trial::{EvaluatedTrial, IdGen, NextTrial}; use crate::Result; use serde::{Deserialize, Serialize}; use std::collections::{BTreeMap, BTreeSet}; use std::fmt; use structopt::StructOpt; pub use self::capability::{Ca...
use crate::problem::ProblemSpec; use crate::registry::FactoryRegistry; use crate::rng::ArcRng; use crate::trial::{EvaluatedTrial, IdGen, NextTrial}; use crate::Result; use serde::{Deserialize, Serialize}; use std::collections::{BTreeMap, BTreeSet}; use std::fmt; use structopt::StructOpt; pub use self::capability::{Ca...
); Self(solver) } } impl SolverFactory for BoxSolverFactory { type Solver = BoxSolver; fn specification(&self) -> Result<SolverSpec> { let v = track!((self.0)(SolverFactoryCall::Specification))?; if let SolverFactoryReturn::Specification(v) = v { Ok(v) } else { ...
match call { SolverFactoryCall::Specification => inner .specification() .map(SolverFactoryReturn::Specification), SolverFactoryCall::CreateSolver(rng, problem) => inner .create_solver(rng, problem) .map(BoxSolver::new) ...
if_condition
[ { "content": "/// Recipe of a problem.\n\npub trait ProblemRecipe: Clone + Send + StructOpt + Serialize + for<'a> Deserialize<'a> {\n\n /// The type of the factory creating problem instances from this recipe.\n\n type Factory: ProblemFactory;\n\n\n\n /// Creates a problem factory.\n\n fn create_fact...
Rust
src/api/r0/directory.rs
xiaosongfu/ruma
06d7f2f5debd40637aca6c22dd50ddc444148b7c
use bodyparser; use iron::status::Status; use iron::{Chain, Handler, IronResult, Plugin, Request, Response}; use ruma_identifiers::RoomId; use crate::config::Config; use crate::db::DB; use crate::error::ApiError; use crate::middleware::{AccessTokenAuth, JsonRequest, MiddlewareChain, RoomAliasIdParam}; use crate::mod...
use bodyparser; use iron::status::Status; use iron::{Chain, Handler, IronResult, Plugin, Request, Response}; use ruma_identifiers::RoomId; use crate::config::Config; use crate::db::DB; use crate::error::ApiError; use crate::middleware::{AccessTokenAuth, JsonRequest, MiddlewareChain, RoomAliasIdParam}; use crate::mod...
#[test] fn put_existing_room_alias() { let test = Test::new(); let user = test.create_user(); let create_room_path = format!("/_matrix/client/r0/createRoom?access_token={}", user.token); let response = test.post(&create_room_path, r#"{"room_alias_name": "my_room"}"#); ...
let user = test.create_user(); let put_room_alias_path = format!( "/_matrix/client/r0/directory/room/my_room?access_token={}", user.token ); let put_room_alias_body = r#"{"room_id": "!nonexistent:ruma.test"}"#; let response = test.put(&put_room_alias_path, put_ro...
function_block-function_prefix_line
[ { "content": "/// A simple Iron handler used for the deprecated `/tokenrefresh` API, which Ruma has never\n\n/// supported.\n\nfn deprecated(_: &mut Request<'_, '_>) -> IronResult<Response> {\n\n Err(IronError::from(ApiError::unauthorized(\n\n \"tokenrefresh is no longer supported\".to_string(),\n\n ...
Rust
ubervisord/src/daemon.rs
Gilnaa/ubervisor
4bb3106d282708efca96b79006c4565174b9ca8c
use std::os::unix::prelude::CommandExt; use std::os::unix::process::ExitStatusExt; use std::process::{Child, Command}; use std::time::Instant; use crate::config::DaemonConfig; use ubervisor_core::{DaemonDeathInfo, DaemonStatus, RequestError}; pub enum DaemonState { NotStarted, Running { process: Child, start...
use std::os::unix::prelude::CommandExt; use std::os::unix::process::ExitStatusExt; use std::process::{Child, Command}; use std::time::Instant; use crate::config::DaemonConfig; use ubervisor_core::{DaemonDeathInfo, DaemonStatus, RequestError}; pub enum DaemonState { NotStarted, Running { process: Child, start...
pub fn start_process(&mut self) -> Result<u32, RequestError> { if let DaemonState::Running { process, .. } = &mut self.state { match process.try_wait() { Ok(None) => { log::debug!("Process {} already started", self.name); return Err(...
pub fn get_child_process_mut(&mut self) -> Option<&mut Child> { match &mut self.state { DaemonState::Running { process, .. } => Some(process), _ => None, } }
function_block-full_function
[]
Rust
src/main.rs
RCasatta/archivio
2b068a0d8359ca81d81374608cc0fdf0df60f1f5
use regex::Regex; use std::collections::{HashMap, HashSet}; use std::convert::TryFrom; use std::fs::DirEntry; use std::iter::FromIterator; use std::path::PathBuf; use std::{env, fs}; type Result<T> = std::result::Result<T, Box<dyn std::error::Error>>; #[derive(Debug, Clone)] struct Element { pub name: String...
use regex::Regex; use std::collections::{HashMap, HashSet}; use std::convert::TryFrom; use std::fs::DirEntry; use std::iter::FromIterator; use std::path::PathBuf; use std::{env, fs}; type Result<T> = std::result::Result<T, Box<dyn std::error::Error>>; #[derive(Debug, Clone)] struct Element { pub name: String...
} impl TryFrom<DirEntry> for Element { type Error = Box<dyn std::error::Error>; fn try_from(value: DirEntry) -> std::result::Result<Self, Self::Error> { let re = Regex::new(r"\d{4}-\d{2}-\d{2}[_[a-zA-Z0-9\-]*]*.[a-z]*").unwrap(); let name = value .file_name() .to_str()...
if path.len() > 2 { return Ok(()); } else { for tag in new_elements.tags() { if first_level || new_elements.names() != new_elements.filter(&[&tag]).names() { let mut new_dir = Elements::tags_base_dir(); new_dir.exte...
function_block-function_prefix_line
[ { "content": "## Archivio\n\n\n\n[![crates.io](https://img.shields.io/crates/v/archivio.svg)](https://crates.io/crates/archivio)\n\n\n\nWhen launched in a directory, it search contents of the Files sub-directory and creates a Tags directory with symbolic links to original content.\n\n \n\nFiles should follow th...
Rust
kernel/src/main.rs
genms/my-mikanos-rust
dbff530fda481bf3a0a32447d145dcbc081e092d
#![no_std] #![no_main] #![feature(lang_items)] #![feature(asm)] #![feature(abi_x86_interrupt)] mod asm; mod console; mod driver; mod error; mod font; mod frame_buffer_config; mod graphics; mod hankaku; mod interrupt; mod logger; mod memory_map; mod mouse; mod pci; mod utils; extern crate num; #[macro_use] extern cra...
#![no_std] #![no_main] #![feature(lang_items)] #![feature(asm)] #![feature(abi_x86_interrupt)] mod asm; mod console; mod driver; mod error; mod font; mod frame_buffer_config; mod graphics; mod hankaku; mod interrupt; mod logger; mod memory_map; mod mouse; mod pci; mod utils; extern crate num; #[macro_use] extern cra...
; draw_rectangle( pixel_writer, &Vector2D::new(10, frame_height - 40), &Vector2D::new(30, 30), &PixelColor::new(160, 160, 160), ); write_string( pixel_writer, 660, 566, "my-mikanos-rust", &PixelColor::new(160, 160, 160), ); pri...
fill_rectangle( pixel_writer, &Vector2D::new(0, frame_height - 50), &Vector2D::new(frame_width / 5, 50), &PixelColor::new(80, 80, 80), )
call_expression
[ { "content": "pub fn get_font(c: char) -> Result<*mut u8, char> {\n\n unsafe {\n\n let index = 16 * c as usize;\n\n if index >= &_binary_hankaku_bin_size as *const u8 as usize {\n\n return Err(c);\n\n }\n\n let start = &_binary_hankaku_bin_start as *const u8 as *mut u8;...
Rust
src/args.rs
v47-io/architect-rs
83265d180f374b73ed213718dd0f522b3aef69dc
/* * BSD 3-Clause License * * Copyright (c) 2021, Alex Katlein * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * 1. Redistributions of source code must retain the above copyright notice...
/* * BSD 3-Clause License * * Copyright (c) 2021, Alex Katlein * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * 1. Redistributions of source code must retain the above copyright notice...
pub(crate) trait TrimmedValueOf<'app> { fn value_of_trimmed(&'app self, name: &str) -> Option<&'app str>; } impl<'app> TrimmedValueOf<'app> for ArgMatches<'app> { fn value_of_trimmed(&'app self, name: &str) -> Option<&'app str> { self.value_of(name) .map(|it| it.trim()) .filte...
pub fn get_matches<'app, I, T>(args: I) -> ArgMatches<'app> where I: IntoIterator<Item = T>, T: Into<OsString> + Clone, { App::new("Architect") .version(crate_version!()) .author(crate_authors!(",\n")) .about("Scaffolds your projects using platform agnostic handlebars templates") ...
function_block-full_function
[ { "content": "fn map_glob_matchers(raw: Option<&Vec<&str>>, property_name: &str) -> Option<Vec<GlobMatcher>> {\n\n let result = raw\n\n .unwrap_or(&vec![])\n\n .iter()\n\n .filter_map(|&raw_glob| match glob(raw_glob) {\n\n Ok(matcher) => Some(matcher),\n\n Err(e) =>...
Rust
src/variant/deserialize.rs
arcnmx/glib-serde
19e307a86786d385e655183c99212605e866d3dd
use super::{GlibVariantExt, Variant}; use crate::{ object_path, signature, Error, ObjectPath, Signature, VariantBuilder, VariantBuilderExt, }; use glib::{ToVariant, VariantTy}; use serde::{ de::{self, DeserializeSeed, Visitor}, Deserialize, Deserializer, }; impl<'de> Deserialize<'de> for Variant { fn...
use super::{GlibVariantExt, Variant}; use crate::{ object_path, signature, Error, ObjectPath, Signature, VariantBuilder, VariantBuilderExt, }; use glib::{ToVariant, VariantTy}; use serde::{ de::{self, DeserializeSeed, Visitor}, Deserialize, Deserializer, }; impl<'de> Deserialize<'de> for Variant { fn...
fn visit_map<A>(self, mut map: A) -> Result<Self::Value, A::Error> where A: de::MapAccess<'de>, { if !self.0.is_array() || !self.0.element().is_dict_entry() { return Err(de::Error::custom(Error::UnsupportedType(self.0.to_owned()))); } let builder = VariantBuilde...
fn visit_seq<A>(self, mut seq: A) -> Result<Self::Value, A::Error> where A: de::SeqAccess<'de>, { let ty = self.0; if ty.is_array() { let builder = VariantBuilder::new(ty); let elem = self.0.element(); while let Some(value) = { let seed...
function_block-full_function
[ { "content": "struct FixedSeqDeserializer<'v, 'de, V: FixedSizeVariantType + IntoDeserializer<'de, Error>> {\n\n input: &'v [V],\n\n index: usize,\n\n phantom: std::marker::PhantomData<&'de ()>,\n\n}\n\n\n\nimpl<'v, 'de, V: FixedSizeVariantType + IntoDeserializer<'de, Error>>\n\n FixedSeqDeserialize...
Rust
misskey-websocket/src/broker/handler.rs
bunnegirl/misskey-rs
43ccdbb7c4519a1d92d719df31b755dede900307
use std::collections::HashMap; use crate::broker::{ channel::{ChannelPongSender, ResponseSender, ResponseStreamSender}, model::{BroadcastId, BrokerControl}, }; use crate::error::Result; use crate::model::{ incoming::{ ApiMessage, ChannelMessage, ConnectedMessage, IncomingMessage, IncomingMessageTyp...
use std::collections::HashMap; use crate::broker::{ channel::{ChannelPongSender, ResponseSender, ResponseStreamSender}, model::{BroadcastId, BrokerControl}, }; use crate::error::Result; use crate::model::{ incoming::{ ApiMessage, ChannelMessage, ConnectedMessage, IncomingMessage, IncomingMessageTyp...
pub fn control(&mut self, ctrl: BrokerControl) -> Option<OutgoingMessage> { match ctrl { BrokerControl::Api { id, endpoint, data, sender, } => { let message = OutgoingMessage::Api { id, endpoint, data }...
pub fn restore_messages(&mut self) -> Vec<OutgoingMessage> { let mut messages = Vec::new(); for ApiHandler { message, .. } in self.api.values() { messages.push(message.clone()); } for SubNoteHandler { message, .. } in self.sub_note.values() { messages.push(messa...
function_block-full_function
[]
Rust
src/app/state/vault.rs
KRD1/revault-gui
5eb9b2fee0c78d63cc5f4b7bb93d1f99c4bb8fb0
use bitcoin::util::psbt::PartiallySignedTransaction as Psbt; use iced::{Command, Element}; use std::sync::Arc; use crate::{ app::{ error::Error, message::{Message, SignMessage, VaultMessage}, state::{ cmd::{ get_onchain_txs, get_revocation_txs, get_unvault_tx, re...
use bitcoin::util::psbt::PartiallySignedTransaction as Psbt; use iced::{Command, Element}; use std::sync::Arc; use crate::{ app::{ error::Error, message::{Message, SignMessage, VaultMessage}, state::{ cmd::{ get_onchain_txs, get_revocation_txs, get_unvault_tx, re...
pub fn new_revault_section() -> Self { Self::Revault { processing: false, success: false, view: RevaultVaultView::new(), warning: None, } } pub fn new_ack_section(txs: RevocationTransactions) -> Self { Self::Secure { emer...
fn new_delegate_section(unvault_tx: Psbt) -> Self { Self::Delegate { signer: SignState::new(unvault_tx, TransactionKind::Unvault), view: DelegateVaultView::new(), warning: None, } }
function_block-function_prefixed
[ { "content": "fn vault_ack_signed<'a, T: 'a>(ctx: &Context, deposit: &Vault) -> Element<'a, T> {\n\n card::white(Container::new(\n\n Row::new()\n\n .push(\n\n Container::new(\n\n Row::new()\n\n .push(badge::shield_success())\n\n ...
Rust
substrate/client/tracing/src/logging.rs
LayNath242/indra
1a1b360038dc676cd55b44cb8174aacf9555da27
use std::fmt::{self, Write}; use ansi_term::Colour; use tracing::{span::Attributes, Event, Id, Level, Subscriber}; use tracing_log::NormalizeEvent; use tracing_subscriber::{ fmt::{ time::{FormatTime, SystemTime}, FmtContext, FormatEvent, FormatFields, }, layer::Context, registry::LookupSpan, Layer, }; use re...
use std::fmt::{self, Write}; use ansi_term::Colour; use tracing::{span::Attributes, Event, Id, Level, Subscriber}; use tracing_log::NormalizeEvent; use tracing_subscriber::{ fmt::{ time::{FormatTime, SystemTime}, FmtContext, FormatEvent, FormatFields, }, layer::Context, registry::LookupSpan, Layer, }; use re...
} struct FmtThreadName<'a> { name: &'a str, } impl<'a> FmtThreadName<'a> { pub(crate) fn new(name: &'a str) -> Self { Self { name } } } impl<'a> fmt::Display for FmtThreadName<'a> { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { use std::sync::atomic::{ AtomicUsize, Ordering::{AcqRel, Acqu...
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { if self.ansi { match *self.level { Level::TRACE => write!(f, "{}", Colour::Purple.paint(TRACE_STR)), Level::DEBUG => write!(f, "{}", Colour::Blue.paint(DEBUG_STR)), Level::INFO => write!(f, "{}", Colour::Green.paint(INFO_STR)), Level::WARN ...
function_block-full_function
[ { "content": "/// Converts a runtime trap into an RPC error.\n\nfn runtime_error_into_rpc_err(err: impl std::fmt::Debug) -> Error {\n\n\tError {\n\n\t\tcode: ErrorCode::ServerError(RUNTIME_ERROR),\n\n\t\tmessage: \"Runtime trapped\".into(),\n\n\t\tdata: Some(format!(\"{:?}\", err).into()),\n\n\t}\n\n}\n\n\n\n#[...
Rust
src/virtio/test.rs
jamesgraves/terminus_spaceport
b2303a280212381b28306b38a59e18d298398d72
#![allow(dead_code)] use super::device::Device; use super::queue::{ DefaultQueueServer, Queue, QueueClient, QueueServer, QueueSetting, RingUsedMetaElem, }; use crate::irq::{IrqVec, IrqVecSender}; use crate::memory::region::{BytesAccess, Heap, Region, U32Access, GHEAP}; use crate::virtio::DESC_F_WRITE; use std::cell...
#![allow(dead_code)] use super::device::Device; use super::queue::{ DefaultQueueServer, Queue, QueueClient, QueueServer, QueueSetting, RingUsedMetaElem, }; use crate::irq::{IrqVec, IrqVecSender}; use crate::memory::region::{BytesAccess, Heap, Region, U32Access, GHEAP}; use crate::virtio::DESC_F_WRITE; use std::cell...
fn read(&self) -> super::queue::Result<Vec<u8>> { if self.irq_vec.pending(0).unwrap() && self.device.virtio_device.get_irq_vec().pending(0).unwrap() { let queue = self.device.virtio_device.get_queue(0); let used = self.input_server.pop_used(queue).unwrap(); ...
fn new(heap: &Rc<Heap>) -> TestDeviceDriver { let irq_vec = IrqVec::new(1); irq_vec.set_enable(0, true).unwrap(); let device = TestDevice::new(heap.get_region(), irq_vec.sender(0).unwrap()); let input_queue = device.virtio_device.get_queue(0); let input_buffer = heap.alloc(4, 4)....
function_block-full_function
[ { "content": "struct VirtIOInputOutputQueue {\n\n irq_sender: IrqVecSender,\n\n}\n\n\n\nimpl VirtIOInputOutputQueue {\n\n fn new(irq_sender: IrqVecSender) -> VirtIOInputOutputQueue {\n\n VirtIOInputOutputQueue { irq_sender }\n\n }\n\n}\n\n\n\nimpl QueueClient for VirtIOInputOutputQueue {\n\n ...
Rust
crates/apollo-smith/src/field.rs
isabella232/apollo-rs
963b3552deaf7ba3a7eb5a698a90f20d0fc08242
use std::collections::HashSet; use arbitrary::Result; use crate::{ argument::{Argument, ArgumentsDef}, description::Description, directive::Directive, name::Name, selection_set::SelectionSet, ty::Ty, DocumentBuilder, }; #[derive(Debug, Clone)] pub struct FieldDef { pub(crate) descript...
use std::collections::HashSet; use arbitrary::Result; use crate::{ argument::{Argument, ArgumentsDef}, description::Description, directive::Directive, name::Name, selection_set::SelectionSet, ty::Ty, DocumentBuilder, }; #[derive(Debug, Clone)] pub struct FieldDef { pub(crate) descript...
} impl<'a> DocumentBuilder<'a> { pub fn fields_definition(&mut self, exclude: &[&Name]) -> Result<Vec<FieldDef>> { let num_fields = self.u.int_in_range(2..=50usize)?; let mut fields_names = HashSet::with_capacity(num_fields); for i in 0..num_fields { let name = self.name_...
directives .into_iter() .for_each(|directive| new_field.directive(directive.into())); new_field.selection_set(field.selection_set.map(Into::into)); new_field }
function_block-function_prefix_line
[ { "content": "fn process_named(p: &mut Parser, token: Token) {\n\n let named_g = p.start_node(SyntaxKind::NAMED_TYPE);\n\n let name_g = p.start_node(SyntaxKind::NAME);\n\n name::validate_name(token.data().to_string(), p);\n\n p.push_ast(SyntaxKind::IDENT, token);\n\n name_g.finish_node();\n\n ...
Rust
psst-core/src/session.rs
HansAuger/psst
cdf257111738df1546379dcb01d499d58744481f
use crate::{ audio_key::{AudioKey, AudioKeyDispatcher}, connection::{ codec::{ShannonDecoder, ShannonEncoder, ShannonMessage}, Credentials, Transport, }, error::Error, item_id::{FileId, ItemId}, mercury::{MercuryDispatcher, MercuryRequest}, util::deserialize_protobuf, }; use ...
use crate::{ audio_key::{AudioKey, AudioKeyDispatcher}, connection::{ codec::{ShannonDecoder, ShannonEncoder, ShannonMessage}, Credentials, Transport, }, error::Error, item_id::{FileId, ItemId}, mercury::{MercuryDispatcher, MercuryRequest}, util::deserialize_protobuf, }; use ...
fn handle_ping(&self) -> Result<(), Error> { self.send(ShannonMessage::new(ShannonMessage::PONG, vec![0, 0, 0, 0]))?; Ok(()) } fn handle_country_code(&self, payload: Vec<u8>) -> Result<(), Error> { self.country_code .lock() .unwrap() .replace(St...
G => { self.handle_ping()?; } ShannonMessage::COUNTRY_CODE => { self.handle_country_code(msg.payload)?; } ShannonMessage::AES_KEY => { self.audio_key.lock().unwrap().handle_aes_key(msg); } ShannonMess...
function_block-function_prefixed
[ { "content": "fn read_packet(stream: &mut TcpStream) -> io::Result<Vec<u8>> {\n\n let size = stream.read_u32::<BE>()?;\n\n let mut buf = vec![0_u8; size as usize];\n\n let (size_buf, data_buf) = buf.split_at_mut(4);\n\n size_buf.copy_from_slice(&size.to_be_bytes());\n\n stream.read_exact(data_buf...
Rust
src/time.rs
awh6al/uuid-rs
3f4341be58e1034d68488fd0e764563709ef2458
#![cfg(feature = "mac")] use mac_address as MAC; use rand; use crate::{ClockSeq, Domain, Layout, Timestamp, Variant, Version, UUID}; impl UUID { pub fn v1() -> Layout { Self::from_mac(Version::TIME, Self::mac()) } pub fn v2(d: Domain) -> Layout { let utc = Timest...
#![cfg(feature = "mac")] use mac_address as MAC; use rand; use crate::{ClockSeq, Domain, Layout, Timestamp, Variant, Version, UUID}; impl UUID { pub fn v1() -> Layout { Self::from_mac(Version::TIME, Self::mac()) } pub fn v2(d: Domain) -> Layout { let utc = Timest...
#[test] fn test_v2() { let domain = [Domain::PERSON, Domain::GROUP, Domain::ORG]; for d in domain.iter() { assert_eq!(UUID::v2(*d).get_version(), Some(Version::DCE)); assert_eq!(UUID::v2(*d).get_variant(), Some(Variant::RFC)); } } #[test] fn test_f...
fn test_v1() { let uuid = UUID::v1(); assert_eq!(uuid.get_version(), Some(Version::TIME)); assert_eq!(uuid.get_variant(), Some(Variant::RFC)); let mac = MAC::get_mac_address().unwrap().unwrap().bytes(); assert_eq!( uuid.as_fields().4, (mac[0] as u64) << ...
function_block-full_function
[ { "content": "#[bench]\n\nfn bench_v1(b: &mut Bencher) {\n\n b.iter(|| UUID::v1());\n\n}\n\n\n", "file_path": "benches/bench.rs", "rank": 0, "score": 32594.17300797245 }, { "content": "#[bench]\n\nfn bench_v2(b: &mut Bencher) {\n\n b.iter(|| UUID::v2(Domain::PERSON));\n\n}\n\n\n", ...
Rust
src/event/mod.rs
buxx/rollgui
f623c1b84f94a4a8b71c2fa1708b853e54beb4d2
use crate::entity::build::Build; use crate::error::RollingError; use crate::server::client::{ItemModel, ListOfItemModel}; use crate::tile::TileId; use serde::ser::{Serialize, SerializeStruct, Serializer}; use serde::{Deserialize as SerdeDeserialize, Serialize as SerdeSerialize}; use serde_derive::{Deserialize as Deseri...
use crate::entity::build::Build; use crate::error::RollingError; use crate::server::client::{ItemModel, ListOfItemModel}; use crate::tile::TileId; use serde::ser::{Serialize, SerializeStruct, Serializer}; use serde::{Deserialize as SerdeDeserialize, Serialize as SerdeSerialize}; use serde_derive::{Deserialize as Deseri...
, }, }), _ => Err(RollingError { message: format!("Unknown event {}", &type_), }), } } } impl Serialize for ZoneEvent { fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error> where S: Serializer, { let...
match data["type_"].as_str().unwrap() { "ERROR" => TopBarMessageType::ERROR, _ => TopBarMessageType::NORMAL, }
if_condition
[ { "content": "pub fn overflow(text: &str, width: i32) -> Vec<String> {\n\n let mut lines: Vec<String> = vec![String::new()];\n\n\n\n for word in text.split(\" \").collect::<Vec<&str>>() {\n\n let mut last_line = lines.last_mut().unwrap();\n\n if last_line.len() + word.len() > width as usize ...
Rust
src/window/glutin.rs
jutuon/program-launcher
f99dce5aeb123651033f2f5035b0858e49742525
use conrod::backend::glium::glium; use conrod::backend::glium::glium::glutin; use gilrs; use conrod::position::Scalar; use conrod::Ui; use conrod::backend::winit::{convert_event, WinitWindow}; use self::glium::backend::{Facade, Context}; use self::glium::{Display, Frame}; use gilrs::{Gilrs}; use std::rc::Rc; use ...
use conrod::backend::glium::glium; use conrod::backend::glium::glium::glutin; use gilrs; use conrod::position::Scalar; use conrod::Ui; use conrod::backend::winit::{convert_event, WinitWindow}; use self::glium::backend::{Facade, Context}; use self::glium::{Display, Frame}; use gilrs::{Gilrs}; use std::rc::Rc; use ...
} return event_update; } fn draw(&mut self) -> Frame { self.display.draw() } fn full_screen(&self) -> bool { self.full_screen } fn set_full_screen(&mut self, value: bool) { self.full_screen = value; } fn opengl_version(&self) -> &gli...
if self.window_focused && handle_game_controller_input(update, e, current_time) { event_update = true; }
if_condition
[ { "content": "fn set_widgets<T: Window>(mut ui_cell: UiCell, ids: &mut WidgetIds, selection_i: &mut usize, task_manager: &mut TaskManager, program_library: &ProgramLibrary, console_text: &str, window: &mut T, command_queue_i: &mut usize, launch_command_queue: bool) {\n\n use conrod::widget::{Canvas, Widget, ...
Rust
src/hss/reference_impl_private_key.rs
hieronymusma/hbs-lms-rust
ef3954c8acb49c2d76ff8176259cd7b2a77f6e91
use core::{marker::PhantomData, mem::size_of}; use arrayvec::ArrayVec; use crate::{ constants::{ LmsTreeIdentifier, Seed, D_TOPSEED, MAX_ALLOWED_HSS_LEVELS, MAX_HASH_SIZE, REFERENCE_IMPL_PRIVATE_KEY_SIZE, SEED_CHILD_SEED, TOPSEED_D, TOPSEED_LEN, TOPSEED_SEED, TOPSEED_WHICH, }, extr...
use core::{marker::PhantomData, mem::size_of}; use arrayvec::ArrayVec; use crate::{ constants::{ LmsTreeIdentifier, Seed, D_TOPSEED, MAX_ALLOWED_HSS_LEVELS, MAX_HASH_SIZE, REFERENCE_IMPL_PRIVATE_KEY_SIZE, SEED_CHILD_SEED, TOPSEED_D, TOPSEED_LEN, TOPSEED_SEED, TOPSEED_WHICH, }, extr...
pub fn from_binary_representation(data: &[u8]) -> Option<Self> { if data.len() != REFERENCE_IMPL_PRIVATE_KEY_SIZE { return None; } let mut result = Self::default(); let mut index = 0; let lms_leaf_identifier = read_and_advance(data, 8, &mut index); res...
e(&u64str(self.lms_leaf_identifier)) .unwrap(); result .try_extend_from_slice(&self.compressed_parameter.0) .unwrap(); result.try_extend_from_slice(&self.seed).unwrap(); result }
function_block-function_prefixed
[ { "content": "fn compute_seed_derive<H: Hasher>(result: &mut [u8], seed: &[u8]) {\n\n let mut prefix = [0u8; DAUX_PREFIX_LEN];\n\n\n\n prefix[DAUX_D] = (D_DAUX >> 8) as u8;\n\n prefix[DAUX_D + 1] = (D_DAUX & 0xff) as u8;\n\n\n\n let mut hasher = H::get_hasher();\n\n\n\n hasher.update(&prefix[..])...
Rust
beacon_node/network/src/sync/block_lookups/tests.rs
adrianchifor/lighthouse
6f732986f1a42bec9f7ef7f57a143836f585a119
use std::sync::Arc; use crate::service::RequestId; use crate::sync::manager::RequestId as SyncId; use crate::NetworkMessage; use super::*; use beacon_chain::builder::Witness; use beacon_chain::eth1_chain::CachingEth1Backend; use lighthouse_network::{NetworkGlobals, Request}; use slog::{Drain, Level}; use slot_clock:...
use std::sync::Arc; use crate::service::RequestId; use crate::sync::manager::RequestId as SyncId; use crate::NetworkMessage; use super::*; use beacon_chain::builder::Witness; use beacon_chain::eth1_chain::CachingEth1Backend; use lighthouse_network::{NetworkGlobals, Request}; use slog::{Drain, Level}; use slot_clock:...
#[test] fn test_parent_lookup_happy_path() { let (mut bl, mut cx, mut rig) = TestRig::test_setup(None); let parent = rig.rand_block(); let block = rig.block_with_parent(parent.canonical_root()); let chain_hash = block.canonical_root(); let peer_id = PeerId::random(); bl.search_parent(Bo...
bl.single_block_lookup_response(id, peer_id, Some(Box::new(block.clone())), D, &mut cx); rig.expect_empty_network(); rig.expect_block_process(); assert_eq!(bl.single_block_lookups.len(), 1); bl.single_block_processed(id, Err(BlockError::ParentUnknown(Box::new(block))), &mut cx); ass...
function_block-function_prefix_line
[ { "content": "/// Returns the canonical root of the given `block`.\n\n///\n\n/// Use this function to ensure that we report the block hashing time Prometheus metric.\n\npub fn get_block_root<E: EthSpec>(block: &SignedBeaconBlock<E>) -> Hash256 {\n\n let block_root_timer = metrics::start_timer(&metrics::BLOCK...
Rust
lesson-23-x/src/resources/obj.rs
MerHS/rust-and-opengl-lessons
a7d78b852b62f2aab559b533c03293399298c468
use crate::mesh; use crate::resources::{ResourcePath, ResourcePathBuf}; use std::path::Path; use tobj; #[derive(Debug, Fail)] pub enum Error { #[fail(display = "Obj or Mtl load error")] LoadError(#[cause] tobj::LoadError), #[fail(display = "Resource path must not be empty")] ResourcePathMustN...
use crate::mesh; use crate::resources::{ResourcePath, ResourcePathBuf}; use std::path::Path; use tobj; #[derive(Debug, Fail)] pub enum Error { #[fail(display = "Obj or Mtl load error")] LoadError(#[cause] tobj::LoadError), #[fail(display = "Resource path must not be empty")] ResourcePathMustN...
} fn map_model_to_mesh(model: tobj::Model, mapped_materials: &[mesh::Material]) -> mesh::Mesh { let normals = if model.mesh.normals.len() == 0 { None } else { Some(model.mesh.normals) }; let texcoords = if model.mesh.texcoords.len() == 0 { None } else { ...
v) .next() { Some(ref name) => { Some(resource_dir.join(&platform_path_to_rel_resource_path(name))) } None => None, }, }).collect::<Vec<_>>(); let mapped...
function_block-function_prefixed
[]
Rust
src/bin/gbafix.rs
ryankurte/rust-gba
6d2af1b9a6eb7c55092d60580da604fc9cd6ee23
#![feature(with_options)] #![allow(unused_assignments)] use std::fs::File; use std::io::{Read, Seek, SeekFrom, Write}; use std::mem::size_of; use std::path::Path; extern crate gba_core; use gba_core::header::Header; fn header_complement(header: &Header) -> u8 { let mut header = header.clone(); header....
#![feature(with_options)] #![allow(unused_assignments)] use std::fs::File; use std::io::{Read, Seek, SeekFrom, Write}; use std::mem::size_of; use std::path::Path; extern crate gba_core; use gba_core::header::Header; fn header_complement(header: &Header) -> u8 { let mut header = header.clone(); header....
fn main() { let mut executable = String::new(); let mut captured = false; let mut files: Vec<String> = Vec::new(); for (i, arg) in (0..).zip(std::env::args()) { if i == 0 { executable = arg; continue; } if arg == "--" {...
function_block-full_function
[ { "content": "/// Draw a rainbow with the given `thickness` to the graphic instance `g`,\n\n/// where `g` is a pallet mode.\n\npub fn rainbow2<T: BitmapMode<u8> + PalletMode<u16>>(g: &mut T, thickness: usize) {\n\n // Set up pallet with rainbow colours\n\n for i in 0..RAINBOW.len() {\n\n g.set_pall...
Rust
src/lib.rs
aobatact/const-generic-wrap
08d509ad9b77adcd99411b9851dfd347f5ca3bfa
#![no_std] #![cfg_attr(feature = "unstable", feature(const_evaluatable_checked))] #![cfg_attr(feature = "unstable", feature(const_generics))] use core::cmp::Ordering; pub(crate) use seal::*; mod seal { pub trait WrapSeal {} pub trait ConstableSeal {} } pub trait ConstWrap: Clone + Copy + Defau...
#![no_std] #![cfg_attr(feature = "unstable", feature(const_evaluatable_checked))] #![cfg_attr(feature = "unstable", feature(const_generics))] use core::cmp::Ordering; pub(crate) use seal::*; mod seal { pub trait WrapSeal {} pub trait ConstableSeal {} } pub trait ConstWrap: Clone + Copy + Defau...
}
fn wrap_unwrap() { let n3 = WrapI32::<3>; assert_eq!(0, core::mem::size_of_val(&n3)); let m: i32 = n3.into(); assert_eq!(3, m); }
function_block-function_prefix_line
[ { "content": " };\n\n [$(($tb: ty, $t : tt)),*$(,)*] => {\n\n $(\n\n impl_signed!($tb, $t);\n\n )*\n\n }\n\n}\n\n\n\nimpl_signed![\n\n (i8, WrapI8),\n\n (i16, WrapI16),\n\n (i32, WrapI32),\n\n (i64, WrapI64),\n\n (isize, WrapISIZE)\n\n];\n\n\n\n#[cfg(test)]\n\nmo...
Rust
src/add_two_nums.rs
sonald/lxxtcode-rs
21ff70b186cb2be9a37367299f991d0867a5f871
use super::utils::*; #[allow(dead_code)] pub struct Solution; #[allow(dead_code)] impl Solution { pub fn add_two_numbers(l1: Option<Box<ListNode>>, l2: Option<Box<ListNode>>) -> Option<Box<ListNode>> { let mut root = None; let mut parent: &mut Option<Box<ListNode>> = &mut root; let mut ca...
use super::utils::*; #[allow(dead_code)] pub struct Solution; #[allow(dead_code)] impl Solution { pub fn add_two_numbers(l1: Option<Box<ListNode>>, l2: Option<Box<ListNode>>) -> Option<Box<ListNode>> { let mut root = None; let mut parent: &mut Option<Box<ListNode>> = &mut root; let mut ca...
#[test] pub fn test_add_two_nums2() { let lhs = build_list!(7,2,4,1); let rhs = build_list!(9,5,8); let res = Solution::add_two_numbers(lhs, rhs); let expect = build_list!(6, 8, 2, 2); list_check_equal(&res, &expect); } #[test] pub fn test_add_two_nums3() ...
let lhs = build_list!(2,4,3); let rhs = build_list!(5,6,4); let res = Solution::add_two_numbers(lhs, rhs); let expect = build_list!(7, 0, 8); list_check_equal(&res, &expect); }
function_block-function_prefix_line
[ { "content": "struct Solution;\n", "file_path": "src/twosum2.rs", "rank": 0, "score": 89027.61572433231 }, { "content": "struct Solution;\n", "file_path": "src/twosum.rs", "rank": 1, "score": 89027.61572433231 }, { "content": "#[allow(unused)]\n\nstruct Solution;\n\n\n\n#...
Rust
src/effects.rs
tuxuser/hyperion.rs
e30c8f0b43d149c72353877f9c69686464a278bb
use std::sync::Arc; use thiserror::Error; use tokio::{ sync::mpsc::{channel, Sender}, task::JoinHandle, }; use crate::{global::InputSourceError, image::RawImage, models::Color}; mod definition; pub use definition::*; mod providers; pub use providers::Providers; mod instance; use instance::*; use self::pro...
use std::sync::Arc; use thiserror::Error; use tokio::{ sync::mpsc::{channel, Sender}, task::JoinHandle, }; use crate::{global::InputSourceError, image::RawImage, models::Color}; mod definition; pub use definition::*; mod providers; pub use providers::Providers; mod instance; use instance::*; use self::pro...
tx.send(EffectMessage { kind: EffectMessageKind::Completed { result }, extra, }) .await .ok(); }); Ok(EffectRunHandle { ctx, join_handle: join_handle.into(), priority, ...
let result = loop { tokio::select! { kind = erx.recv() => { if let Some(kind) = kind { let msg = EffectMessage { kind, extra: extra.clone() }; if let Err(err) = tx.send(msg)....
assignment_statement
[ { "content": "/// Trait for effect providers.\n\n///\n\n/// An effect provider is able to load an effect script and run it when given input parameters.\n\npub trait Provider: std::fmt::Debug + Send + Sync {\n\n /// Returns if this provider supports the given effect\n\n ///\n\n /// # Parameters\n\n /...
Rust
src/concurrent/writer_reader_phaser.rs
soro/rusty-hdrhistogram
2b0d261027c2fef898def3f4a358edebd4f55cd0
use parking_lot::Mutex; use std::isize::MIN as ISIZE_MIN; use std::mem; use std::sync::atomic::{AtomicIsize, Ordering}; use std::thread; use std::time::Duration; pub struct WriterReaderPhaser { start_epoch: AtomicIsize, even_end_epoch: AtomicIsize, odd_end_epoch: AtomicIsize, reader_lock: Mutex<()>, ...
use parking_lot::Mutex; use std::isize::MIN as ISIZE_MIN; use std::mem; use std::sync::atomic::{AtomicIsize, Ordering}; use std::thread; use std::time::Duration; pub struct WriterReaderPhaser { start_epoch: AtomicIsize, even_end_epoch: AtomicIsize, odd_end_epoch: AtomicIsize, reader_lock: Mutex<()>, ...
tart_value_at_flip }; if !caught_up { if yield_time.as_secs() == 0 && yield_time.subsec_nanos() == 0 { thread::yield_now(); } else { thread::sleep(yield_time); } } else { break; ...
th_yield_time(&self, yield_time: Duration) { let next_phase_is_even = self.parent.start_epoch.load(Ordering::SeqCst) < 0; let initial_start_value = if next_phase_is_even { 0 } else { ISIZE_MIN }; if next_phase_is_even { self.parent .even_end_epoch .st...
function_block-random_span
[ { "content": "pub fn static_with_low_high_sigvdig(\n\n lowest_discernible_value: u64,\n\n highest_trackable_value: u64,\n\n significant_value_digits: u8,\n\n) -> Result<StaticRecorder, CreationError> {\n\n StaticHistogram::with_low_high_sigvdig(\n\n lowest_discernible_value,\n\n highes...
Rust
src/logs/cursor.rs
cstorey/pg-queue
28885da06c6199c3ca9695b9314360526ddcbe54
use std::{collections::VecDeque, fmt}; use tokio_postgres::{Client, GenericClient}; use tracing::{debug, trace}; use crate::logs::{Entry, Result, Version}; static FETCH_CONSUMER_POSITION: &str = "SELECT epoch, tx_position, position FROM log_consumer_positions WHERE \ name = $1"; static FETCH_NEXT_ROW: &str...
use std::{collections::VecDeque, fmt}; use tokio_postgres::{Client, GenericClient}; use tracing::{debug, trace}; use crate::logs::{Entry, Result, Version}; static FETCH_CONSUMER_POSITION: &str = "SELECT epoch, tx_position, position FROM log_consumer_positions WHERE \ name = $1"; static FETCH_NEXT_ROW: &str...
pub async fn commit_upto<C: GenericClient>( &mut self, client: &mut C, entry: &Entry, ) -> Result<()> { client .execute( UPSERT_CONSUMER_OFFSET, &[ &self.name, &entry.version.epoch, ...
async fn fetch_consumer_pos<C: GenericClient>(client: &C, name: &str) -> Result<Version> { let rows = client.query(FETCH_CONSUMER_POSITION, &[&name]).await?; trace!(rows=?rows.len(), "next rows"); let position = rows .into_iter() .next() .map(|r| Version::fro...
function_block-full_function
[ { "content": "fn load_pg_config(schema: &str) -> Result<Config> {\n\n let url = env::var(\"POSTGRES_URL\").expect(\"$POSTGRES_URL\");\n\n let mut config: Config = url.parse()?;\n\n debug!(?schema, \"Use schema\");\n\n\n\n config.options(&format!(\"-csearch_path={}\", schema));\n\n\n\n Ok(config)\...
Rust
src/request.rs
fin-ger/simple-raft-node
0ae32e1719b8164535b855207287b7cd248e1370
use std::future::Future; use std::task::{Poll, Context, Waker}; use std::pin::Pin; use failure::{Fail, Backtrace}; use crossbeam::channel::{self, Sender, Receiver, TryRecvError}; use crate::{MachineCore}; #[derive(Debug, Fail)] pub enum RequestError { #[fail(display = "The machine has not yet been initialized")]...
use std::future::Future; use std::task::{Poll, Context, Waker}; use std::pin::Pin; use failure::{Fail, Backtrace}; use crossbeam::channel::{self, Sender, Receiver, TryRecvError}; use crate::{MachineCore}; #[derive(Debug, Fail)] pub enum RequestError { #[fail(display = "The machine has not yet been initialized")]...
RequestError::ChannelsUnavailable(Backtrace::new()) )), } } } #[derive(Debug, Clone)] pub struct RequestManager<M: MachineCore> { tx: Sender<Request<M>>, } impl<M: MachineCore> RequestManager<M> { pub fn new(tx: Sender<Request<M>>) -> Self { Self { tx, ...
cx.waker().clone(), kind: fut.kind.clone(), }).map_err(|_| RequestError::ChannelsUnavailable(Backtrace::new()))?; fut.request_sent = true; } match fut.response_rx.try_recv() { Ok(response) => Poll::Ready(fut.response_handler.call((response,))), ...
function_block-random_span
[ { "content": "// the core has to own all its data\n\npub trait MachineCore: std::fmt::Debug + Clone + Send +'static {\n\n type StateChange: MachineItem + Serialize + DeserializeOwned;\n\n type StateIdentifier: MachineItem;\n\n type StateValue: MachineItem;\n\n\n\n fn deserialize(&mut self, data: Vec...
Rust
2017/src/day21.rs
shrugalic/advent_of_code
8d18a3dbdcf847a667ab553f5441676003b9362a
use line_reader::read_file_to_lines; use std::collections::{HashMap, HashSet}; use std::fmt::{Display, Formatter}; const STARTING_PATTERN: &str = ".#./..#/###"; const ON: char = '#'; const OFF: char = '.'; pub(crate) fn day21_part1() -> usize { pixels_after_n_iterations(read_file_to_lines("input/day21.txt"), 5) }...
use line_reader::read_file_to_lines; use std::collections::{HashMap, HashSet}; use std::fmt::{Display, Formatter}; const STARTING_PATTERN: &str = ".#./..#/###"; const ON: char = '#'; const OFF: char = '.'; pub(crate) fn day21_part1() -> usize { pixels_after_n_iterations(read_file_to_lines("input/day21.txt"), 5) }...
#[test] fn pattern_flip_horizontally() { let mut rotated = Pattern { size: 3, pattern: vec![OFF, ON, OFF, OFF, OFF, ON, ON, ON, ON], }; rotated.flip_horizontally(); let expected = Pattern { size: 3, pattern: vec![ON, ON, ON, OFF, ...
fn pattern3_rotate_90_degrees_clockwise() { let mut rotated = Pattern { size: 3, pattern: vec![ON, OFF, ON, OFF, OFF, ON, ON, ON, OFF], }; rotated.rotate_90_degrees_clockwise(); let expected = Pattern { size: 3, pattern: vec![ON, OFF, ON, O...
function_block-full_function
[ { "content": "fn count_visibly_occupied_neighbors(col: usize, row: usize, seats: &[Vec<char>]) -> usize {\n\n // look in all 8 directions\n\n let directions: [(isize, isize); 8] = [\n\n (0, 1),\n\n (1, 1),\n\n (1, 0),\n\n (1, -1),\n\n (0, -1),\n\n (-1, -1),\n\n ...
Rust
arwa_parse/src/selector/parse_relative_selector_list.rs
RSSchermer/rudo
6413eff6c6b500e529a6a42d9bc35d0e48dcef18
use super::{parse_relative_complex_selector, ParseError, RelativeSelectorList, Remainder}; pub fn parse_relative_selector_list( remainder: Remainder, ) -> Result<(RelativeSelectorList, Remainder), ParseError> { let mut relative_selector_list = Vec::new(); let remainder = remainder.skip_whitespace(); ...
use super::{parse_relative_complex_selector, ParseError, RelativeSelectorList, Remainder}; pub fn parse_relative_selector_list( remainder: Remainder, ) -> Result<(RelativeSelectorList, Remainder), ParseError> { let mut relative_selector_list = Vec::new(); let remainder = remainder.skip_whitespace(); ...
#[test] fn valid_two_complex_selector() { let (selector, remainder) = parse_relative_selector_list("*, > * ".into()).unwrap(); assert_eq!( selector, RelativeSelectorList { relative_selector_list: vec![ RelativeComplexSelector { ...
fn valid_one_complex_selector() { let (selector, remainder) = parse_relative_selector_list("* ".into()).unwrap(); assert_eq!( selector, RelativeSelectorList { relative_selector_list: vec![RelativeComplexSelector { parts: vec![CombinedSelector ...
function_block-full_function
[ { "content": "pub fn parse_a_n_plus_b_of(remainder: Remainder) -> Result<(ANPlusBOf, Remainder), ParseError> {\n\n let (a_n_plus_b, remainder) = parse_a_n_plus_b(remainder)?;\n\n\n\n let has_whitespace = remainder.chars().next().map(is_whitespace).unwrap_or(false);\n\n let remainder = remainder.skip_wh...
Rust
crates/js-sys/tests/wasm/WebAssembly.rs
rail44/wasm-bindgen
bf791efe2c623b1b20053e8e39c3aa4e8eb60a1c
use futures::Future; use js_sys::*; use wasm_bindgen::{JsCast, prelude::*}; use wasm_bindgen_futures::JsFuture; use wasm_bindgen_test::*; #[wasm_bindgen(module = "tests/wasm/WebAssembly.js")] extern { #[wasm_bindgen(js_name = getWasmArray)] fn get_wasm_array() -> Uint8Array; #[wasm_bindgen(js_name = getTa...
use futures::Future; use js_sys::*; use wasm_bindgen::{JsCast, prelude::*}; use wasm_bindgen_futures::JsFuture; use wasm_bindgen_test::*; #[wasm_bindgen(module = "tests/wasm/WebAssembly.js")] extern { #[wasm_bindgen(js_name = getWasmArray)] fn get_wasm_array() -> Uint8Array; #[wasm_bindgen(js_name = getTa...
e() { let error = WebAssembly::RuntimeError::new(""); assert!(error.is_instance_of::<WebAssembly::RuntimeError>()); assert!(error.is_instance_of::<Error>()); let _: &Error = error.as_ref(); }
function_block-function_prefixed
[ { "content": "#[wasm_bindgen_test(async)]\n\nfn ok_future_is_resolved_promise() -> impl Future<Item = (), Error = JsValue> {\n\n let f = futures::future::ok(JsValue::from(42));\n\n let p = future_to_promise(f);\n\n JsFuture::from(p)\n\n .map(|x| {\n\n assert_eq!(x, 42);\n\n })....
Rust
src/index.rs
rossmacarthur/stride
3955628dc5e98bbc2f111a40651b822252f5f898
use core::ops::{Range, RangeFrom, RangeFull, RangeInclusive, RangeTo, RangeToInclusive}; use crate::Stride; mod private { use super::*; pub trait Sealed {} impl Sealed for usize {} impl Sealed for Range<usize> {} impl Sealed for RangeFrom<usize> {} impl Sealed for RangeFull {} impl Sealed ...
use core::ops::{Range, RangeFrom, RangeFull, RangeInclusive, RangeTo, RangeToInclusive}; use crate::Stride; mod private { use super::*; pub trait Sealed {} impl Sealed for usize {} impl Sealed for Range<usize> {} impl Sealed for RangeFrom<usize> {} impl Sealed for RangeFull {} impl Sealed ...
} impl Unstride for RangeFrom<usize> { fn unstride<const S: usize>(self) -> Self { RangeFrom { start: self.start * S, } } } impl Unstride for RangeFull { fn unstride<const S: usize>(self) -> Self { self } } impl Unstride for RangeInclusive<usize> { fn unstride...
fn unstride<const S: usize>(self) -> Self { Range { start: self.start * S, end: self.end * S, } }
function_block-function_prefix_line
[]
Rust
src/response.rs
ethcore/rotor
2a3764a830174aa94405593be550e8fc7ecea25a
use std::fmt::Debug; use std::error::Error; use mio::Token; use {Response, Time}; #[derive(Debug)] pub enum ResponseImpl<M, N> { Normal(M), Deadline(M, Time), Spawn(M, N), Error(Box<Error>), Done, } impl<M: Sized, N:Sized> Response<M, N> { pub fn ok(machine: M) -> Response<M, N> { Re...
use std::fmt::Debug; use std::error::Error; use mio::Token; use {Response, Time}; #[derive(Debug)] pub enum ResponseImpl<M, N> { Normal(M), Deadline(M, Time), Spawn(M, N), Error(Box<Error>), Done, } impl<M: Sized, N:Sized> Response<M, N> { pub fn ok(machine: M) -> Response<M, N> { Re...
pub fn wrap<T, S>(self, self_mapper: S) -> Response<T, N> where S: FnOnce(M) -> T { use self::ResponseImpl::*; let imp = match self.0 { Normal(m) => Normal(self_mapper(m)), Deadline(m, time) => Deadline(self_mapper(m), time), Spawn...
U, S, R>(self, self_mapper: S, result_mapper: R) -> Response<T, U> where S: FnOnce(M) -> T, R: FnOnce(N) -> U, { use self::ResponseImpl::*; let imp = match self.0 { Normal(m) => Normal(self_mapper(m)), Deadline(m, time) => Deadline(self_mapper(m...
function_block-function_prefixed
[ { "content": "pub fn create_handler<M: Machine>(slab: Slab<(Option<(Timeout, Time)>, M)>,\n\n context: M::Context, channel: Sender<Notify>)\n\n -> Handler<M>\n\n{\n\n Handler {\n\n slab: slab,\n\n context: context,\n\n channel: channel,\n\n start_time: Instant::now(),\n\n ...
Rust
src/map.rs
Restioson/Rome
67745d219cdbe4837c16abba255e4c04169976b4
use crate::{AppState, STATE_STAGE}; use bevy::app::{AppBuilder, Plugin}; use bevy::asset::{AssetLoader, LoadContext, LoadedAsset}; use bevy::prelude::*; use bevy::reflect::TypeUuid; use bevy::tasks::AsyncComputeTaskPool; use std::future::Future; use std::io::Read; use std::pin::Pin; use bevy::render::texture::{Extent...
use crate::{AppState, STATE_STAGE}; use bevy::app::{AppBuilder, Plugin}; use bevy::asset::{AssetLoader, LoadContext, LoadedAsset}; use bevy::prelude::*; use bevy::reflect::TypeUuid; use bevy::tasks::AsyncComputeTaskPool; use std::future::Future; use std::io::Read; use std::pin::Pin; use bevy::render::texture::{Extent...
{ println!("Unzipping"); let mut decoder = zstd::Decoder::new(&*bytes).unwrap(); let mut unzipped = Vec::new(); decoder.read_to_end(&mut unzipped).unwrap(); println!("Deserializing"); ...
= camera.looking_at; } } } type BoxFuture<'a, T> = Pin<Box<dyn Future<Output = T> + Send + 'a>>; pub struct HeightMapLoader { pub task_pool: AsyncComputeTaskPool, } impl AssetLoader for HeightMapLoader { fn load<'a>( &'a self, bytes: &'a [u8], ctx: &'a mut LoadContext, ...
random
[ { "content": "#[rustfmt::skip]\n\npub fn build_mesh(lod_levels: u8) -> Mesh {\n\n let mut builder = MeshBuilder::default();\n\n\n\n // How many grid cells to use most-detailed LOD for, divided by two\n\n let g = 512 / 2; // TODO ?\n\n let pad = 1; // TODO\n\n\n\n for lod_level in 0..lod_levels {\...
Rust
src/io/audio.rs
oxcable/oxcable
477e1126ee981859350e3c5d92108b8e8213feef
use std::rc::Rc; use portaudio::pa; use error::Result; use types::{SAMPLE_RATE, AudioDevice, Sample, Time}; static PORTAUDIO_T: pa::SampleFormat = pa::SampleFormat::Float32; pub struct AudioEngine { marker: Rc<AudioEngineMarker>, buffer_size: usize, } impl AudioEngine { pub fn with_buffer_size(s...
use std::rc::Rc; use portaudio::pa; use error::Result; use types::{SAMPLE_RATE, AudioDevice, Sample, Time}; static PORTAUDIO_T: pa::SampleFormat = pa::SampleFormat::Float32; pub struct AudioEngine { marker: Rc<AudioEngineMarker>, buffer_size: usize, } impl AudioEngine { pub fn with_buffer_size(s...
self.samples_read = 0; } for i in 0..self.num_channels { outputs[i] = self.buffer[self.samples_read*self.num_channels + i]; } self.samples_read += 1; } } pub struct AudioOut { #[allow(dead_code)] engine: Rc<AudioEngineMarker>, pa_stream: pa::St...
match self.pa_stream.read(num_read as u32) { Ok(v) => { for (i, &s) in v.iter().enumerate() { self.buffer[i] = s; } }, Err(pa::Error::InputOverflowed) => { println!("Input overflowed"); ...
if_condition
[ { "content": "/// Returns a hamming window of size `n`.\n\npub fn hamming(n: usize) -> Vec<Sample> {\n\n generalized_cosine_window(&[0.54, -0.46], n)\n\n}\n\n\n", "file_path": "src/utils/windows.rs", "rank": 0, "score": 130474.3784222753 }, { "content": "/// Returns a bartlett (triangular...
Rust
src/commit.rs
fabienjuif/gitmoji-changelog-rust
8dc1f8667c134e64e3f5a1e8084a19f5ba221313
use git2::{Repository, Revwalk}; use regex::Regex; use std::collections::HashMap; lazy_static! { static ref RE_SUMMARY: Regex = Regex::new(r":(.*?):(.*)").unwrap(); static ref EMOJIES: HashMap<&'static str, &'static str> = { let mut m = HashMap::new(); m.insert("hammer", "🔨"); ...
use git2::{Repository, Revwalk}; use regex::Regex; use std::collections::HashMap; lazy_static! { static ref RE_SUMMARY: Regex = Regex::new(r":(.*?):(.*)").unwrap(); static ref EMOJIES: HashMap<&'static str, &'static str> = { let mut m = HashMap::new(); m.insert("hammer", "🔨"); ...
}
ap(|oid| repository.find_commit(oid.unwrap()).ok()) .filter_map(|raw_commit| Commit::from_git2(&raw_commit)) .collect() }
function_block-function_prefixed
[ { "content": "pub fn parse_args() -> ArgMatches<'static> {\n\n App::new(\"gitmoji-changelog\")\n\n .version(crate_version!())\n\n .author(\"Fabien JUIF <fabien.juif@gmail.com>\")\n\n .arg(\n\n Arg::with_name(\"output\")\n\n .short(\"o\")\n\n .long(\"output\")\n\n ...
Rust
server/lib/scrapper.rs
natserract/reason-rust-scraper
6c533abfcff94f2f1674fac48a5d1ac8a6ff09f3
use select::document::Document; use reqwest::header::{HeaderMap, HeaderName}; pub mod lib { #[tokio::main] pub async fn status(some_url: &str) -> Result<String, reqwest::Error> { let request = reqwest::get(some_url).await?; let request_status = request.status(); Ok(String::from(&request...
use select::document::Document; use reqwest::header::{HeaderMap, HeaderName}; pub mod lib { #[tokio::main] pub async fn status(some_url: &str) -> Result<String, reqwest::Error> { let request = reqwest::get(some_url).await?; let request_status = request.status(); Ok(String::from(&request...
} } Ok(result) } #[tokio::main] pub async fn grab_all_links_opt(some_url: Option<String>) -> Result<String, reqwest::Error> { let check_url = some_url.unwrap(); let request = reqwest::get(&check_url).await?; let request_body = request.text().await?; let fr...
request.text_with_charset("utf-8").await?; Ok(String::from(request_body)) } #[tokio::main] pub async fn grab_all_links(some_url: &str) -> Result<String, reqwest::Error> { let request = reqwest::get(some_url).await?; let request_body = request.text().await?; let fragment = s...
random
[ { "content": "#[post(\"/api/scraps/update/<id>\", data = \"<scrap_data>\")]\n\npub fn update_scrap_post(\n\n id: i32,\n\n scrap_data: Json<UpdateScraps>,\n\n connection: pool::Connection,\n\n) -> String {\n\n let query = action::query_update_scrap(id, &connection, scrap_data.into_inner());\n\n ma...
Rust
hify-server/src/graphql/queries.rs
ClementNerma/Hify
8a0e7678738663ae2159618a842fa3e19ab9feec
use std::collections::BTreeSet; use async_graphql::{ComplexObject, Context, Enum, Object, Result, SimpleObject}; use crate::{ graphql_ctx_member, graphql_index, index::{ search_index, AlbumID, AlbumInfos, ArtistID, ArtistInfos, IndexSearchResults, SortedMap, Track, TrackID, TrackTags, }, ...
use std::collections::BTreeSet; use async_graphql::{ComplexObject, Context, Enum, Object, Result, SimpleObject}; use crate::{ graphql_ctx_member, graphql_index, index::{ search_index, AlbumID, AlbumInfos, ArtistID, ArtistInfos, IndexSearchResults, SortedMap, Track, TrackID, TrackTags, }, ...
async fn albums_artists( &self, ctx: &Context<'_>, pagination: PaginationInput, ) -> Paginated<ArtistID, ArtistInfos> { let index = graphql_index!(ctx); paginate( pagination, &index.cache.albums_artists_infos, |artist: &ArtistInfos| a...
async fn artists( &self, ctx: &Context<'_>, pagination: PaginationInput, ) -> Paginated<ArtistID, ArtistInfos> { let index = graphql_index!(ctx); paginate( pagination, &index.cache.artists_infos, |artist: &ArtistInfos| artist.get_id(), ...
function_block-full_function
[]
Rust
util/src/shared.rs
nathdobson/rust-public
cad37803e239e92dfeb2be61716502e521138eec
#![allow(deprecated)] use std::sync::{Arc, Weak, RwLock, RwLockReadGuard, RwLockWriteGuard}; use std::cmp::Ordering; use std::{hash, fmt, mem, io}; use std::hash::Hasher; use std::fmt::{Formatter, Arguments}; use std::marker::Unsize; use std::ops::{CoerceUnsized, Deref}; use std::io::{Write, IoSlice, Read, IoSliceMut}...
#![allow(deprecated)] use std::sync::{Arc, Weak, RwLock, RwLockReadGuard, RwLockWriteGuard}; use std::cmp::Ordering; use std::{hash, fmt, mem, io}; use std::hash::Hasher; use std::fmt::{Formatter, Arguments}; use std::marker::Unsize; use std::ops::{CoerceUnsized, Deref}; use std::io::{Write, IoSlice, Read, IoSliceMut}...
fn test_ptr() { let a = Shared::new(1); let b = a.clone(); let c = a.downgrade(); let d = b.downgrade(); assert_eq!(a.as_ptr(), b.as_ptr()); assert_eq!(a.as_ptr(), c.as_ptr()); assert_eq!(a.as_ptr(), d.as_ptr()); }
function_block-full_function
[ { "content": "pub trait SyncDisplay: Sync + Fn(&mut Formatter) -> fmt::Result {}\n\n\n\nimpl<T> SyncDisplay for T where T: Sync + Fn(&mut Formatter) -> fmt::Result {}\n\n\n\nimpl<'a> Display for &'a dyn SyncDisplay {\n\n fn fmt(&self, fmt: &mut Formatter<'_>) -> fmt::Result {\n\n self(fmt)\n\n }\n\...
Rust
src/concourse_image_resource.rs
cirocosta/cartorio
15b9f1447c1e9d77755165d313a227fc7a0de322
use std::fs; use std::io::prelude::*; use std::path::{Path, PathBuf}; use flate2::read::GzDecoder; use crate::blobstore::BlobStore; use crate::concourse_resource_metadata::ConcourseResourceMetadata; use crate::digest; use crate::error::Result; use crate::image_config::ImageConfig; use crate::registry::{ManifestDescri...
use std::fs; use std::io::prelude::*; use std::path::{Path, PathBuf}; use flate2::read::GzDecoder; use crate::blobstore::BlobStore; use crate::concourse_resource_metadata::ConcourseResourceMetadata; use crate::digest; use crate::error::Result; use crate::image_config::ImageConfig; use crate::registry::{ManifestDescri...
Path) -> Result<ManifestDescriptor> { self.ingest_blob( original_location, "application/vnd.docker.container.image.v1+json", ) } fn ingest_rootfs(&self) -> Result<ManifestDescriptor> { self.ingest_blob( &self.root_dir.join("rootfs.tar"), "...
le = fs::OpenOptions::new() .write(true) .create(true) .open(&self.root_dir.join("config.json"))?; config_file.write_all(config.to_string().as_bytes())?; Ok(config) } fn ingest_config(&self, original_location: &
random
[ { "content": "#[inline]\n\npub fn store(filepath: &Path, digest: &str) -> Result<()> {\n\n xattr::set(filepath, DIGEST_XATTR, digest.as_bytes())?;\n\n Ok(())\n\n}\n\n\n\n\n", "file_path": "src/digest.rs", "rank": 0, "score": 194698.99694058043 }, { "content": "/// Computes the digest o...
Rust
src/parser/state_machine/aplus_questionnaire.rs
SeSodesa/rustla
9b17781886e74985e452fe544980e845b3c4ec53
/*! A submodule dedicated to parsing functions of the `State::AplusQuestionnaire` state. Copyright © 2020 Santtu Söderholm */ use super::*; pub fn parse_aplus_questionnaire_text( src_lines: &[String], base_indent: usize, section_level: &mut usize, line_cursor: &mut LineCursor, mut doctree: DocTre...
/*! A submodule dedicated to parsing functions of the `State::AplusQuestionnaire` state. Copyright © 2020 Santtu Söderholm */ use super::*; pub fn parse_aplus_questionnai
ve_offset()).unwrap(); match line.char_indices().nth(detected_first_indent) { Some((index, _)) => line[index..].trim().is_empty(), None => true, } }; let (body_indent, body_offset) = match Parser::indent_on_subsequent_lines(src_lines, line_cursor.relative_offse...
re_text( src_lines: &[String], base_indent: usize, section_level: &mut usize, line_cursor: &mut LineCursor, mut doctree: DocTree, captures: &regex::Captures, pattern_name: &Pattern, ) -> TransitionResult { let detected_indent = captures.get(1).unwrap().as_str().chars().count(); mat...
random
[ { "content": "/// A transition function for parsing directives in a state that recognizes body elements.\n\npub fn directive(\n\n src_lines: &[String],\n\n base_indent: usize,\n\n section_level: &mut usize,\n\n line_cursor: &mut LineCursor,\n\n mut doctree: DocTree,\n\n captures: &regex::Captu...
Rust
src/rust/engine/fs/src/glob_matching.rs
StephanErb/pants
a368267b6b4cf50138ba567f582409ed31bf5db9
use std::collections::HashSet; use std::path::{Path, PathBuf}; use std::sync::Arc; use boxfuture::{BoxFuture, Boxable}; use futures::future; use futures::Future; use glob::Pattern; use indexmap::{map::Entry::Occupied, IndexMap, IndexSet}; use { Dir, GitignoreStyleExcludes, GlobExpansionConjunction, GlobParsedSour...
use std::collections::HashSet; use std::path::{Path, PathBuf}; use std::sync::Arc; use boxfuture::{BoxFuture, Boxable}; use futures::future; use futures::Future; use glob::Pattern; use indexmap::{map::Entry::Occupied, IndexMap, IndexSet}; use { Dir, GitignoreStyleExcludes, GlobExpansionConjunction, GlobParsedSour...
fn expand(&self, path_globs: PathGlobs) -> BoxFuture<Vec<PathStat>, E> { let PathGlobs { include, exclude, strict_match_behavior, conjunction, } = path_globs; if include.is_empty() { return future::ok(vec![]).to_boxed(); } let init = PathGlobsExpansion { con...
map(|(stat_symbolic_path, stat)| { if context.is_ignored(&stat) || exclude.is_ignored(&stat) { future::ok(None).to_boxed() } else { match stat { Stat::Link(l) => context.canonicalize...
function_block-function_prefix_line
[ { "content": "///\n\n/// Defines executing a cacheable/memoizable step within the given NodeContext.\n\n///\n\n/// Note that it is assumed that Nodes are very cheap to clone.\n\n///\n\npub trait Node: Clone + Debug + Eq + Hash + Send + 'static {\n\n type Context: NodeContext<Node = Self>;\n\n\n\n type Item: C...
Rust
src/main.rs
luxrck/raytrace
16d868d9c0cefaecd9ab433046cac2ab252d5985
#![feature(box_syntax)] use std::env; use std::f64; use image::RgbImage; use nalgebra::Vector3; use rand::prelude::*; use rayon::prelude::*; #[derive(Copy, Clone, Debug)] struct Ray { origin: Vector3<f64>, direction: Vector3<f64>, color: Vector3<f64>, } impl Ray { fn new(o: Vector3<f64>, d: Vector3<...
#![feature(box_syntax)] use std::env; use std::f64; use image::RgbImage; use nalgebra::Vector3; use rand::prelude::*; use rayon::prelude::*; #[derive(Copy, Clone, Debug)] struct Ray { origin: Vector3<f64>, direction: Vector3<f64>, color: Vector3<f64>, } impl Ray { fn new(o: Vector3<f64>, d: Vector3<...
} fn main() { let eye = Vector3::new(-1.0, 3.0, 3.0); let center = Vector3::new(0.0, 0.0, -1.0); let cam = Camera::new(eye, center, 0.8, 0.4, 2.0).with_sampling(256); let diffuse = Lamberitian { albedo: Vector3::new(0.8, 0.3, 0.3), }; let diffuse1 = Lamberitian { albedo: Vecto...
let mut rng = rand::thread_rng(); (0..width) .into_iter() .map(|x| render_pixel(x, height - y, &mut rng)) .flatten() .collect::<Vec<_>>() }) .flatten() .collect(); RgbImage::from_...
function_block-function_prefix_line
[ { "content": "#### Description\n\nMy rust implementation of [《Ray Tracing in One Weekend》][1] .\n\n\n\n#### Usage\n\n```\n\n$ raytrace <outfile>\n\n```\n\n\n", "file_path": "README.md", "rank": 21, "score": 1.3881558578282789 } ]
Rust
src/sys/test_adapters/src/lib.rs
mehulagg/fuchsia
3f56175ee594da6b287d5fb19f2f0eccea2897f0
use { failure::Fail, fdio::fdio_sys, fuchsia_async as fasync, fuchsia_runtime as runtime, fuchsia_zircon as zx, futures::{ io::{self, AsyncRead}, prelude::*, ready, task::{Context, Poll}, }, runtime::{HandleInfo, HandleType}, std::{ cell::RefCell, ...
use { failure::Fail, fdio::fdio_sys, fuchsia_async as fasync, fuchsia_runtime as runtime, fuchsia_zircon as zx, futures::{ io::{self, AsyncRead}, prelude::*, ready, task::{Context, Poll}, }, runtime::{HandleInfo, HandleType}, std::{ cell::RefCell, ...
&test_path, arguments, None, &mut actions[..], ) .map_err(|(s, m)| FdioError::ProcessCreation(s, m))?; Ok((process, logger)) }
{ let mut std_fd: i32 = -1; let mut status = fdio::fdio_sys::fdio_fd_create(log.into_raw(), &mut std_fd); if let Err(s) = zx::Status::ok(status) { return Err(Error::Fdio(FdioError::Create(s))); } status = fdio_sys::fdio_fd_clone(std_fd, &mut stderr_file_...
random
[]
Rust
src/lib.rs
wgreenberg/visualwav
da3366b619546946ea6aba47679cb9aa0422fd1e
use wasm_bindgen::prelude::*; use hound::{WavSpec, SampleFormat}; use rustfft::{FftPlanner, num_complex::Complex}; use std::io::Cursor; const AUDACITY_MAX_FREQ: u32 = 8000; #[wasm_bindgen] pub struct Image { data: Vec<u8>, pub height: usize, pub width: usize, } fn rgb_to_luma(r: u8, g: u8, b: u8, a: u8) ...
use wasm_bindgen::prelude::*; use hound::{WavSpec, SampleFormat}; use rustfft::{FftPlanner, num_complex::Complex}; use std::io::Cursor; const AUDACITY_MAX_FREQ: u32 = 8000; #[wasm_bindgen] pub struct Image { data: Vec<u8>, pub height: usize, pub width: usize, } fn rgb_to_luma(r: u8, g: u8, b: u8, a: u8) ...
pub fn invert(&mut self) { for luma in self.data.iter_mut() { *luma = 255 - *luma; } } pub fn rgba_data(&self) -> Vec<u8> { let mut rgb_data = Vec::new(); for &luma in &self.data { rgb_data.push(luma); rgb_data.push(luma); rg...
pub fn pad_top(&mut self, n_rows: usize) { let mut padding = vec![255; n_rows * self.width]; self.height += n_rows; padding.extend(&self.data); self.data = padding; }
function_block-full_function
[ { "content": " get height() {\n\n var ret = wasm.__wbg_get_audio_sample_rate(this.ptr);\n\n return ret >>> 0;\n", "file_path": "docs/pkg/visualwav.js", "rank": 2, "score": 47762.23234486001 }, { "content": " get width() {\n\n var ret = wasm.__wbg_get_image_width(th...
Rust
sdl2-sys/sdl_image_bindings.rs
AGausmann/rust-sdl2
e865c8f4643e7f333c94e2cff8abd9497736ca4b
/* automatically generated by rust-bindgen */ use crate::*; pub type __uint8_t = libc::c_uchar; pub type __uint32_t = libc::c_uint; pub type __int64_t = libc::c_long; pub type __off_t = libc::c_long; pub type __off64_t = libc::c_long; pub type Uint8 = u8; pub type Uint32 = u32; pub type Sint64 = i64; extern "C" { ...
/* automatically generated by rust-bindgen */ use crate::*; pub type __uint8_t = libc::c_uchar; pub type __uint32_t = libc::c_uint; pub type __int64_t = libc::c_long; pub type __off_t = libc::c_long; pub type __off64_t = libc::c_long; pub type Uint8 = u8; pub type Uint32 = u32; pub type Sint64 = i64; extern "C" { ...
fn IMG_SaveJPG_RW( surface: *mut SDL_Surface, dst: *mut SDL_RWops, freedst: libc::c_int, quality: libc::c_int, ) -> libc::c_int; }
_RWops) -> libc::c_int; } extern "C" { pub fn IMG_isTIF(src: *mut SDL_RWops) -> libc::c_int; } extern "C" { pub fn IMG_isXCF(src: *mut SDL_RWops) -> libc::c_int; } extern "C" { pub fn IMG_isXPM(src: *mut SDL_RWops) -> libc::c_int; } extern "C" { pub fn IMG_isXV(src: *mut SDL_RWops) -> libc::c_int; } ext...
random
[ { "content": "/// Filter using `SubUint`: D = saturation0(S[i] - Cs[i % 4]), Cs=Swap32((uint)C).\n\npub fn sub_uint(src1: CVec<u8>, c: u32) -> Result<CVec<u8>, String> {\n\n let size = src1.len();\n\n let dest = cvec_with_size(size);\n\n let ret = unsafe { imagefilter::SDL_imageFilterSubUint(mem::trans...
Rust
sos21-domain/src/model/form/item/integer.rs
sohosai/sos21-backend
f1883844b0e5c68d6b3f9d159c9268142abc81b4
use serde::{ de::{self, Deserializer}, Deserialize, Serialize, }; use thiserror::Error; pub mod limit; pub mod unit; pub use limit::IntegerFormItemLimit; pub use unit::IntegerFormItemUnit; #[derive(Debug, Clone, Serialize, Deserialize)] pub struct IntegerFormItemContent { pub is_required: bool, pub m...
use serde::{ de::{self, Deserializer}, Deserialize, Serialize, }; use thiserror::Error; pub mod limit; pub mod unit; pub use limit::IntegerFormItemLimit; pub use unit::IntegerFormItemUnit; #[derive(Debug, Clone, Serialize, Deserialize)] pub struct IntegerFormItemContent { pub is_required: bool, pub m...
FromContentErrorKind::TooBigPlaceholder, ); } #[test] fn test_inconsistent() { assert_eq!( IntegerFormItem::from_content(IntegerFormItemContent { is_required: true, max: Some(IntegerFormItemLimit::from_u64(2).unwrap()), min: Som...
(false, None) => return Ok(()), (_, Some(answer)) => answer, }; if let Some(min) = self.0.min { if min.to_u64() > answer { return Err(CheckAnswerError { kind: CheckAnswerErrorKind::TooSmall, }); } } ...
random
[ { "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
hphp/hack/src/providers/rust_provider_backend_ffi.rs
Atry/hhvm
f195d3d81b52586d9b9fa2f17c05fe1bb68bcc3e
use file_provider::{FileProvider, FileType, PlainFileProvider}; use hackrs::{decl_parser::DeclParser, folded_decl_provider::FoldedDeclProvider}; use hackrs_test_utils::{cache::make_shallow_decl_cache, serde_cache::CacheOpts}; use ocamlrep::{ptr::UnsafeOcamlPtr, FromOcamlRep}; use ocamlrep_custom::Custom; use ocamlrep...
use file_provider::{FileProvider, FileType, PlainFileProvider}; use hackrs::{decl_parser::DeclParser, folded_decl_provider::FoldedDeclProvider}; use hackrs_test_utils::{cache::make_shallow_decl_cache, serde_cache::CacheOpts}; use ocamlrep::{ptr::UnsafeOcamlPtr, FromOcamlRep}; u
d) }; todo!() } fn hh_rust_provider_backend_get_typedef<'a>( arena: &'a Bump, backend: UnsafeOcamlPtr, name: pos::TypeName, ) -> Option<shallow_decl_defs::TypedefDecl<'a>> { let backend = unsafe { get_backend(backend) }; backend.folded_decl_provider.get_typed...
se ocamlrep_custom::Custom; use ocamlrep_ocamlpool::{ocaml_ffi, ocaml_ffi_with_arena, Bump}; use oxidized::{file_info, naming_types}; use oxidized_by_ref::{ decl_defs, direct_decl_parser, parser_options::ParserOptions, shallow_decl_defs, }; use pos::{RelativePath, RelativePathCtx, ToOxidized}; use std::collections:...
random
[]
Rust
git-ref/tests/file/mod.rs
kim/gitoxide
e9cdc958e7ce2290e2d7958cdb5aa9323ef35d37
use git_ref::file; fn store() -> crate::Result<file::Store> { let path = git_testtools::scripted_fixture_repo_read_only("make_ref_repository.sh")?; Ok(file::Store::from(path.join(".git"))) } mod store { mod find_one { use crate::file::store; use std::path::Path; mod existing { ...
use git_ref::file; fn store() -> crate::Result<file::Store> { let path = git_testtools::scripted_fixture_repo_read_only("make_ref_repository.sh")?; Ok(file::Store::from(path.join(".git"))) } mod store { mod find_one { use crate::file::store; use std::path::Path; mod existing { ...
nce = Reference::try_from_path(&store, "name", $input).unwrap(); assert_eq!(reference.kind(), $kind); assert_eq!(reference.target().as_id(), $id); assert_eq!(reference.target().as_ref(), $ref); } }; }...
Found(name)) => { assert_eq!(name, Path::new(*partial_name)); } Err(err) => panic!("Unexpected err: {:?}", err), }, } } Ok(()) } } ...
random
[ { "content": "fn main() -> Result<(), Box<dyn std::error::Error>> {\n\n let mut args = std::env::args().skip(1);\n\n let scmd = args.next().expect(\"sub command\");\n\n match &*scmd {\n\n \"mess-in-the-middle\" => mess_in_the_middle(PathBuf::from(args.next().expect(\"path to file to mess with\")...
Rust
karl-controller/src/controller/data.rs
henryweng03/karl
f4699b25f57bfa47f94ec9dba8834bbc39c998fc
use std::fs; use std::path::PathBuf; use std::collections::HashMap; use std::sync::{Arc, RwLock}; use chrono; use serde::{Serialize, Deserialize}; use karl_common::*; pub struct DataSink { pub data_path: PathBuf, pub tag_locks: Arc<RwLock<HashMap<Tag, Arc<RwLock<()>>>>>, } #[derive(Serialize, Deserialize, Def...
use std::fs; use std::path::PathBuf; use std::collections::HashMap; use std::sync::{Arc, RwLock}; use chrono; use serde::{Serialize, Deserialize}; use karl_common::*; pub struct DataSink { pub data_path: PathBuf, pub tag_locks: Arc<RwLock<HashMap<Tag, Arc<RwLock<()>>>>>, } #[derive(Serialize, Deserialize, Def...
); assert!(res.is_ok()); let res = res.unwrap(); assert_eq!(res.data.len(), expected); assert_eq!(res.data[0], vec![lower_i]); assert_eq!(res.data[expected - 1], vec![upper_i]); assert_eq!(res.timestamps.len(), expected); assert_eq!(&re...
>(); assert_eq!(timestamps.len(), n as usize); } #[test] fn test_get_data_nothing_pushed() { let (_dir, sink) = init_test(); let t2 = chrono::prelude::Local::now(); let t1 = t2.checked_sub_signed(Duration::hours(1)).unwrap(); let upper = t2.format("%+").to_string(); ...
random
[ { "content": "pub fn parse_state_tag(tag: &str) -> (String, String) {\n\n let mut split = tag.split(\".\");\n\n let sensor = split.next().unwrap()[1..].to_string();\n\n let key = split.next().unwrap().to_string();\n\n (sensor, key)\n\n}\n\n\n", "file_path": "karl-common/src/state_tags.rs", "...
Rust
src/cmds/powerlevel.rs
youngmit/rzw
4b6b307d328e37e86d6bfcd35f4f2741cd54b48c
use cmds::{CommandClass, Message}; use enum_primitive::FromPrimitive; use error::{Error, ErrorKind}; enum_from_primitive! { #[derive(Copy, Clone, Debug, PartialEq)] #[allow(non_camel_case_types)] pub enum PowerLevelStatus { NormalPower = 0x00, minus1dBm = 0x01, minus2dBm = 0x02, minus3dBm = 0x03, ...
use cmds::{CommandClass, Message}; use enum_primitive::FromPrimitive; use error::{Error, ErrorKind}; enum_from_primitive! { #[derive(Copy, Clone, Debug, PartialEq)] #[allow(non_camel_case_types)] pub enum PowerLevelStatus { NormalPower = 0x00, minus1dBm = 0x01, minus2dBm = 0x02, minus3dBm = 0x03, ...
; } let n_id = msg[5]; let level = PowerLevelOperationStatus::from_u8(msg[6]).ok_or(Error::new( ErrorKind::UnknownZWave, "Answer contained wrong operation status", ))?; let frame = PowerLevel::transform_array_of_u8_to_u16(msg[...
Err(Error::new( ErrorKind::UnknownZWave, "Answer contained wrong command class", ))
call_expression
[ { "content": "/// Function to start a Z-Wave Controller\n\npub fn open<P>(path: P) -> Result<Controller<SerialDriver>, Error>\n\nwhere\n\n P: Into<String>,\n\n{\n\n // Generate a new Serial driver\n\n let driver = SerialDriver::new(path.into())?;\n\n\n\n // Generate a new controller and return it\n\...
Rust
src/cmd/fifo.rs
eburghar/kakpipe
806cf09a81584502e9b7cc5131d94555f733c42b
use anyhow::{anyhow, Context, Result}; use async_process::{Command, Stdio}; use async_std::{ fs::{File, OpenOptions}, io::{ prelude::{BufReadExt, ReadExt, WriteExt}, BufReader, }, os::unix::net::UnixListener, prelude::FutureExt, stream::StreamExt, sync::Mutex, }; use kak::{ command::Client, range::{Pos, Ra...
use anyhow::{anyhow, Context, Result}; use async_process::{Command, Stdio}; use async_std::{ fs::{File, OpenOptions}, io::{ prelude::{BufReadExt, ReadExt, WriteExt}, BufReader, }, os::unix::net::UnixListener, prelude::FutureExt, stream::StreamExt, sync::Mutex, }; use kak::{ command::Client, range::{Pos, Ra...
pub async fn fifo(args: FifoArgs, fifo: &Path, pid: &Path, socket: &Path) -> Result<()> { let mut client = Client::new(&args.session)?; if args.debug { client .send_command(&format!( "echo -debug +++ start {} {:?}", &args.cmd, &args.args )) .await?; } let sync = Arc::new(Mutex::new(Shar...
let debug_task = async { while let Some(line) = stderr_reader.next().await { let line = line?; client .send_command(&format!("echo -debug {}", line)) .await?; } Ok::<(), anyhow::Error>(()) }; fifo_task.try_join(debug_task).await?; } else { while let Some(line) = ...
function_block-function_prefix_line
[ { "content": "/// return path buf from a path, name and an extension\n\npub fn temp_file(path: &Path, name: &str, ext: &str) -> Result<PathBuf> {\n\n\tlet mut res = path.join(name);\n\n\tif res.set_extension(ext) {\n\n\t\tOk(res)\n\n\t} else {\n\n\t\tbail!(\"Failed to create {:?}/{}.{}\", path, name, ext)\n\n\t...
Rust
terminal/src/lib.rs
Protowalker/endbasic
29f4bed8a1eb422c787ae8be58c86e3141b0afe8
#![allow(clippy::await_holding_refcell_ref)] #![allow(clippy::collapsible_else_if)] #![warn(anonymous_parameters, bad_style, missing_docs)] #![warn(unused, unused_extern_crates, unused_import_braces, unused_qualifications)] #![warn(unsafe_code)] use async_trait::async_trait; use crossterm::{cursor, event, execute, s...
#![allow(clippy::await_holding_refcell_ref)] #![allow(clippy::collapsible_else_if)] #![warn(anonymous_parameters, bad_style, missing_docs)] #![warn(unused, unused_extern_crates, unused_import_braces, unused_qualifications)] #![warn(unsafe_code)] use async_trait::async_trait; use crossterm::{cursor, event, execute, s...
self) -> io::Result<()> { if !self.cursor_visible { execute!(io::stdout(), cursor::Show).map_err(crossterm_error_to_io_error)?; self.cursor_visible = true; } Ok(()) } fn size(&self) -> io::Result<CharsXY> { let lines = get_env_v...
xecute!(io::stdout(), cursor::MoveTo(pos.x, pos.y)).map_err(crossterm_error_to_io_error) } fn move_within_line(&mut self, off: i16) -> io::Result<()> { match off.cmp(&0) { Ordering::Less => execute!(io::stdout(), cursor::MoveLeft(-off as u16)), Ordering::Equal => Ok(()), ...
random
[ { "content": "/// Reads a single key from stdin when not attached to a TTY. Because characters are not\n\n/// visible to us until a newline is received, this reads complete lines and buffers them in\n\n/// memory inside the given `buffer`.\n\npub fn read_key_from_stdin(buffer: &mut VecDeque<Key>) -> io::Result...
Rust
src/common.rs
Chopinsky/auto_correct
d6ecc9fd5b5d66d692b1f94e2914e2593a2d84ec
#![allow(unreachable_patterns)] use std::fs::File; use std::io::{BufRead, BufReader}; use std::path::PathBuf; use std::str::Chars; use std::cmp::Ordering; use crossbeam_channel as channel; use crate::AutoCorrect; use crate::candidate::Candidate; use crate::config::Config; use crate::stores; use crate::SupportedLocale...
#![allow(unreachable_patterns)] use std::fs::File; use std::io::{BufRead, BufReader}; use std::path::PathBuf; use std::str::Chars; use std::cmp::Ordering; use crossbeam_channel as channel; use crate::AutoCorrect; use crate::candidate::Candidate; use crate::config::Config; use crate::stores; use crate::SupportedLocale...
fn check_bit(source: u32, pos: usize) -> bool { source & (1 << pos) > 0 } pub(crate) mod deprecated { use crossbeam_channel as channel; use hashbrown::HashMap; use crate::AutoCorrect; use crate::candidate::Candidate; use crate::config::AutoCorrectConfig; use crate::support::en_us; use...
source | 1 } else { (source >> pos << (pos + 1)) | (1 << pos) | (source << (32 - pos) >> (32 - pos)) } } else { source | (1 << pos) } }
function_block-function_prefix_line
[ { "content": "fn refresh_dict(source_dir: &String, target: &mut File) {\n\n let (tx, rx) = mpsc::channel();\n\n let source = source_dir.clone();\n\n\n\n thread::spawn(move || {\n\n let path =\n\n if let Ok(override_dict) = env::var(\"OVERRIDE_DICT\") {\n\n PathBuf::from...
Rust
src/script.rs
DanNixon/mqtt-actor
976debd64cd907a686c6e3a5504504b4c64d6e69
use anyhow::{anyhow, Result}; use chrono::{DateTime, Duration, FixedOffset, Local}; use csv::{ReaderBuilder, Trim}; use glob::glob; use serde::{ de::{self, Visitor}, Deserialize, Deserializer, }; use std::{ cmp::Ordering, fmt, fs::File, io::{BufReader, Read}, path::{Path, PathBuf}, str::...
use anyhow::{anyhow, Result}; use chrono::{DateTime, Duration, FixedOffset, Local}; use csv::{ReaderBuilder, Trim}; use glob::glob; use serde::{ de::{self, Visitor}, Deserialize, Deserializer, }; use std::{ cmp::Ordering, fmt, fs::File, io::{BufReader, Read}, path::{Path, PathBuf}, str::...
r::new(data); let msgs = load_messages(b'|', c); assert_eq!(msgs.len(), 3); } #[test] fn messages_with_only_relative() { let data = r##" 5 | root/user-1 | msg 1 10 | root/user-2 | msg 2 20 | root/user-1 | msg 3 "##; let c = Cursor::new(data); let msgs = load_message...
ort_by(|a, b| { if let Timestamp::Absolute(a) = a.timestamp { if let Timestamp::Absolute(b) = b.timestamp { a.cmp(&b) } else { Ordering::Equal } } else { Ordering::Equal } ...
random
[ { "content": "#[derive(Debug, Parser)]\n\n#[clap(author, version, about, long_about = None)]\n\nstruct Cli {\n\n /// Address of MQTT broker to connect to\n\n #[clap(long, env = \"MQTT_BROKER\", default_value = \"tcp://localhost:1883\")]\n\n mqtt_broker: String,\n\n\n\n /// Client ID to use when conn...
Rust
src/encryption.rs
madprops/Effer
92603e10eab143a0e48e97773201105c814b2b25
use crate::{ e, file::update_file, globals::{g_get_derivation, g_get_password, g_set_derivation, g_set_password}, input::{ask_string, get_input}, notes::get_notes, other::exit, p, s, }; use sodiumoxide::crypto::aead; use sodiumoxide::crypto::pwhash; pub fn change_security() { p!("(1) C...
use crate::{ e, file::update_file, globals::{g_get_derivation, g_get_password, g_set_derivation, g_set_password}, input::{ask_string, get_input}, notes::get_notes, other::exit, p, s, }; use sodiumoxide::crypto::aead; use sodiumoxide::crypto::pwhash; pub fn change_security() { p!("(1) C...
} } else { password = get_input("Password", "", true); } pw = s!(password); g_set_password(password); } pw } fn key_from_pw(password: &str, salt: pwhash::Salt, derivation: u8) -> Result<aead::Key, ()> { let mut key = aead::Key([0; aead::KEYBYTES]);...
if password != confirmation { e!("Error: Passwords Don't Match.") } else { break; }
if_condition
[ { "content": "// Creates a menu item\n\npub fn menu_item(key: &str, label: &str, spacing: bool, separator: bool, newline: bool) -> String {\n\n let nline = if newline { \"\\n\" } else { \"\" };\n\n let mut s = format!(\"{}{}({}){}\", nline, get_color(3), key, get_color(2));\n\n if spacing {\n\n ...
Rust
crates/ir/src/primitive.rs
Robbepop/runwell
0e5186ce79b4de9957c3e35a904eaee07813c662
use crate::instr::Instruction; use core::fmt; use derive_more::{Display, From}; use entity::{DisplayHook, Idx}; impl DisplayHook for Instruction { fn fmt( idx: Idx<Self>, f: &mut std::fmt::Formatter<'_>, ) -> std::fmt::Result { write!(f, "instr({})", idx.into_raw()) } } #[derive(...
use crate::instr::Instruction; use core::fmt; use derive_more::{Display, From}; use entity::{DisplayHook, Idx}; impl DisplayHook for Instruction { fn fmt( idx: Idx<Self>, f: &mut std::fmt::Formatter<'_>, ) -> std::fmt::Result { write!(f, "instr({})", idx.into_raw()) } } #[derive(...
ub fn from_bits(bits: u64) -> Self { Self { bits } } pub fn bits(self) -> u64 { self.bits } } impl Default for F64 { fn default() -> Self { f64::default().into() } } impl From<f64> for F64 { fn from(value: f64) -> Self { Self { bits: u64::from_...
64 { match self { Self::Int(int_type) => int_type.max_unsigned_value(), Self::Float(FloatType::F32) => u32::MAX as u64, Self::Float(FloatType::F64) => u64::MAX, Self::Ptr => u32::MAX as u64, } } pub fn alignment(&self) -> u8 { match s...
random
[ { "content": "fn u32_to_idx(raw_value: u32) -> Idx<TestEntity> {\n\n Idx::from_raw(RawIdx::from_u32(raw_value))\n\n}\n\n\n\nmacro_rules! unit_test_secondary {\n\n ( $name:ident ) => {\n\n #[test]\n\n fn default_works() {\n\n let default = $name::default();\n\n let null ...
Rust
src/token/verifier.rs
agueganno/biscuit-rust
dd61460b24194f56218b996899bc1bea4976f705
use super::builder::{ constrained_rule, date, fact, pred, s, string, Constraint, ConstraintKind, Fact, IntConstraint, Rule, Caveat, var, }; use super::Biscuit; use crate::datalog; use crate::error; use std::{convert::TryInto, time::{SystemTime, Duration}, default::Default}; #[derive(Clone)] pub struct Verifie...
use super::builder::{ constrained_rule, date, fact, pred, s, string, Constraint, ConstraintKind, Fact, IntConstraint, Rule, Caveat, var, }; use super::Biscuit; use crate::datalog; use crate::error; use std::{convert::TryInto, time::{SystemTime, Duration}, default::Default}; #[derive(Clone)] pub struct Verifie...
} #[derive(Debug,Clone)] pub struct VerifierLimits { pub max_facts: u32, pub max_iterations: u32, pub max_time: Duration, } impl Default for VerifierLimits { fn default() -> Self { VerifierLimits { max_facts: 1000, max_iterations: 100, max_ti...
t>) { let mut caveats = self.caveats.clone(); caveats.extend(self.token_caveats.iter().flatten().map(|c| Caveat::convert_from(c, &self.symbols))); (self.world.facts.iter().map(|f| Fact::convert_from(f, &self.symbols)).collect(), self.world.rules.iter().map(|r| Rule::convert_from(r, &se...
function_block-function_prefixed
[ { "content": "pub fn var(syms: &mut SymbolTable, name: &str) -> ID {\n\n let id = syms.insert(name);\n\n ID::Variable(id as u32)\n\n}\n\n\n", "file_path": "src/datalog/mod.rs", "rank": 0, "score": 268628.26469590486 }, { "content": "pub fn string(s: &str) -> ID {\n\n ID::Str(s.to_st...
Rust
sw/host/opentitantool/src/command/console.rs
msfschaffner/opentitan-bak
de4cb1bb9e7b707a3ca2a6882d83af7ed2aa1ab8
use anyhow::{anyhow, Result}; use erased_serde::Serialize; use nix::unistd::isatty; use raw_tty::TtyModeGuard; use regex::Regex; use std::any::Any; use std::fs::File; use std::os::unix::io::AsRawFd; use std::time::Duration; use structopt::StructOpt; use opentitanlib::app::command::CommandDispatch; use opentitanlib::...
use anyhow::{anyhow, Result}; use erased_serde::Serialize; use nix::unistd::isatty; use raw_tty::TtyModeGuard; use regex::Regex; use std::any::Any; use std::fs::File; use std::os::unix::io::AsRawFd; use std::time::Duration; use structopt::StructOpt; use opentitanlib::app::command::CommandDispatch; use opentitanlib::...
}
ExitStatus::ExitFailure => { log::info!( "ExitFailure({:?})", console.captures(status).unwrap().get(0).unwrap().as_str() ); Err(anyhow!("Matched exit_failure expression")) } } }
function_block-function_prefix_line
[ { "content": "/// Spawn a child process, passing all the same arguments to the child, letting it instantiate a\n\n/// Transport based on the command line arguments, listen on a TCP socket, and run as a daemon\n\n/// process serving network requests. Success of the child is verified by means of a\n\n/// `Sessio...
Rust
src/libdoh/src/dns.rs
stnert/doh-server
ebb33834ea3c33d9b32aa05a6c370da9e609a99a
use anyhow::{ensure, Error}; use byteorder::{BigEndian, ByteOrder}; const DNS_HEADER_SIZE: usize = 12; pub const DNS_OFFSET_FLAGS: usize = 2; const DNS_MAX_HOSTNAME_SIZE: usize = 256; const DNS_MAX_PACKET_SIZE: usize = 4096; const DNS_OFFSET_QUESTION: usize = DNS_HEADER_SIZE; const DNS_FLAGS_TC: u16 = 1u16 << 9; con...
use anyhow::{ensure, Error}; use byteorder::{BigEndian, ByteOrder}; const DNS_HEADER_SIZE: usize = 12; pub const DNS_OFFSET_FLAGS: usize = 2; const DNS_MAX_HOSTNAME_SIZE: usize = 256; const DNS_MAX_PACKET_SIZE: usize = 4096; const DNS_OFFSET_QUESTION: usize = DNS_HEADER_SIZE; const DNS_FLAGS_TC: u16 = 1u16 << 9; con...
?; let mut edns_offset = None; traverse_rrs_mut(packet, offset, arcount as _, |packet, offset| { let qtype = BigEndian::read_u16(&packet[offset..]); if qtype == DNS_TYPE_OPT { ensure!(edns_offset.is_none(), "Duplicate OPT RR found"); edns_offset = Some(offset) } ...
traverse_rrs( packet, offset, ancount as usize + nscount as usize, |_offset| Ok(()), )
call_expression
[ { "content": "pub fn parse_opts(globals: &mut Globals) {\n\n use crate::utils::{verify_remote_server, verify_sock_addr};\n\n\n\n let max_clients = MAX_CLIENTS.to_string();\n\n let timeout_sec = TIMEOUT_SEC.to_string();\n\n let max_concurrent_streams = MAX_CONCURRENT_STREAMS.to_string();\n\n let m...
Rust
compiler/hir/scope.rs
mwatts/arret
3b3bae27ca7283376d420fa7d69fe5073ecf9ef0
use std::collections::HashMap; use std::sync::Arc; use arret_syntax::span::Span; use crate::context::ModuleId; use crate::hir::error::{Error, ErrorKind}; use crate::hir::macros::Macro; use crate::hir::ns::{Ident, NsDatum, NsId, NsIdCounter}; use crate::hir::prim::Prim; use crate::hir::{types, LocalId}; use crate::ty;...
use std::collections::HashMap; use std::sync::Arc; use arret_syntax::span::Span; use crate::context::ModuleId; use crate::hir::error::{Error, ErrorKind}; use crate::hir::macros::Macro; use crate::hir::ns::{Ident, NsDatum, NsId, NsIdCounter}; use crate::hir::prim::Prim; use crate::hir::{types, LocalId}; use crate::ty;...
entries: HashMap::new(), parent: Some(self), } } pub fn get_datum<'a>(&'a self, datum: &NsDatum) -> Option<&'a Binding> { if let NsDatum::Ident(_, ident) = datum { self.get(ident) } else { None } } pub fn get<'a>(&...
) }) .collect::<HashMap<Ident, SpannedBinding>>(); Scope { ns_id_counter: NsIdCounter::new(), entries, parent: None, } } pub fn root() -> Scope<'static> { let entries = std::iter::once(("import", Binding:...
random
[ { "content": "pub fn expect_spanned_ns_ident(datum: NsDatum, usage: &'static str) -> Result<(Span, Ident)> {\n\n if let NsDatum::Ident(span, ident) = datum {\n\n Ok((span, ident))\n\n } else {\n\n Err(Error::new(\n\n datum.span(),\n\n ErrorKind::ExpectedSym(\n\n ...
Rust
gstreamer-check/src/auto/test_clock.rs
kad3nce/gstreamer-rs
fcc361f920c9c4d0926cc90de997a0293a21b0b1
use glib::object::Cast; use glib::object::ObjectType as ObjectType_; use glib::signal::connect_raw; use glib::signal::SignalHandlerId; use glib::translate::*; use glib::StaticType; use glib::Value; use glib_sys; use gobject_sys; use gst; use gst_check_sys; use std::boxed::Box as Box_; use std::mem::transmute; glib_w...
use glib::object::Cast; use glib::object::ObjectType as ObjectType_; use glib::signal::connect_raw; use glib::signal::SignalHandlerId; use glib::translate::*; use glib::StaticType; use glib::Value; use glib_sys; use gobject_sys; use gst; use gst_check_sys; use std::boxed::Box as Box_; use std::mem::transmute; glib_w...
pub fn get_next_entry_time(&self) -> gst::ClockTime { unsafe { from_glib(gst_check_sys::gst_test_clock_get_next_entry_time( self.to_glib_none().0, )) } } pub fn peek_id_count(&self) -> u32 { unsafe { gst_check_sys::gst_test_clock_...
} pub fn crank(&self) -> bool { unsafe { from_glib(gst_check_sys::gst_test_clock_crank(self.to_glib_none().0)) } }
random
[ { "content": "pub fn type_find_helper_for_buffer<P: IsA<gst::Object>>(\n\n obj: Option<&P>,\n\n buf: &gst::Buffer,\n\n) -> Option<(gst::Caps, gst::TypeFindProbability)> {\n\n assert_initialized_main_thread!();\n\n unsafe {\n\n let mut prob = mem::MaybeUninit::uninit();\n\n let ret = gs...
Rust
src/lib.rs
dburriss/hotspot-rs-cli
399ecf9cd3b579215cd5f2dee9decae8d8ddaa5b
pub mod shared_types { use core::fmt; use globset::{Error, Glob, GlobSet, GlobSetBuilder}; use std::fmt::Display; use std::hash::{Hash, Hasher}; pub const FILE_GLOBS: [&'static str; 4] = [ "*.{cs,c,cpp,fs,go,js,java,py,rs,ts,tsx}", "!.*", "!node_modules/", "!target/"...
pub mod shared_types { use core::fmt; use globset::{Error, Glob, GlobSet, GlobSetBuilder}; use std::fmt::Display; use std::hash::{Hash, Hasher}; pub const FILE_GLOBS: [&'static str; 4] = [ "*.{cs,c,cpp,fs,go,js,java,py,rs,ts,tsx}", "!.*", "!node_modules/", "!target/"...
truncate_left(value: String, length: usize) -> String { if value.len() <= length { value } else { let left_truncated: String = value .chars() .rev() .take(length - 3) .collect::<String>() .chars() ...
enum Verbosity { Silent, Error, Info, Debug, Trace, } impl fmt::Display for Verbosity { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { write!(f, "{:?}", self) } } impl Verbosity { pub fn is_quiet(&self) -> bool { ...
random
[ { "content": "pub fn capture_input() -> App<'static, 'static> {\n\n // NOTE: Setting Arg::default_value effectively disables this option as it will ensure that some argument is always present.\n\n // From: https://docs.rs/clap/2.20.3/clap/enum.AppSettings.html\n\n let app = App::new(\"Hotspot\")\n\n ...
Rust
crates/competitive/src/combinatorial_optimization/knapsack_problem.rs
to-omer/competitive-library
50f00872254c2cfb169d4c674786e0f8c0d27484
#[codesnip::entry("KnapsackPloblemSmallWeight")] pub struct KnapsackPloblemSmallWeight { pub dp: Vec<usize>, } #[codesnip::entry("KnapsackPloblemSmallWeight")] impl KnapsackPloblemSmallWeight { pub fn new(max_weight: usize) -> Self { Self { dp: vec![0; max_weight + 1], } } pu...
#[codesnip::entry("KnapsackPloblemSmallWeight")] pub struct KnapsackPloblemSmallWeight { pub dp: Vec<usize>, } #[codesnip::entry("KnapsackPloblemSmallWeight")] impl KnapsackPloblemSmallWeight { pub fn new(max_weight: usize) -> Self { Self { dp: vec![0; max_weight + 1], } } pu...
pub fn insert_limitation(&mut self, value: usize, weight: usize, mut count: usize) { let mut b = 1; while count > 0 { let k = b.min(count); count -= k; for i in (value * k..self.dp.len()).rev() { self.dp[i] = self.dp[i].min(self.dp[i - value * k].sat...
n insert(&mut self, value: usize, weight: usize) { for i in value..self.dp.len() { self.dp[i] = self.dp[i].min(self.dp[i - value].saturating_add(weight)); } } pub fn extend<I: IntoIterator<Item = (usize, usize)>>(&mut self, iter: I) { for (value, weight) in iter.into_iter() {...
random
[ { "content": "pub fn extgcd_binary(mut a: i64, mut b: i64) -> (i64, i64, i64) {\n\n if b == 0 {\n\n return (a, 1, 0);\n\n } else if a == 0 {\n\n return (b, 1, 0);\n\n }\n\n let k = (a | b).trailing_zeros();\n\n a >>= k;\n\n b >>= k;\n\n let (c, d) = (a, b);\n\n let (mut u, ...
Rust
api/src/inner/splitted.rs
plyhun/plygui
03b5f2c7d472a6300d1d04a8530f75ccd8ac7c75
use crate::layout; use super::auto::{HasInner, Abstract, Spawnable}; use super::container::AContainer; use super::container_multi::{AMultiContainer, MultiContainer, MultiContainerInner}; use super::control::{AControl, Control, ControlInner}; use super::has_orientation::{HasOrientation, HasOrientationInner}; use super:...
use crate::layout; use super::auto::{HasInner, Abstract, Spawnable}; use super::container::AContainer; use super::container_multi::{AMultiContainer, MultiContainer, MultiContainerInner}; use super::control::{AControl, Control, ControlInner}; use super::has_orientation::{HasOrientation, HasOrientationInner}; use super:...
#[inline] fn second(&self) -> &dyn Control { self.inner.inner.inner.inner.inner.second() } #[inline] fn first_mut(&mut self) -> &mut dyn Control { self.inner.inner.inner.inner.inner.first_mut() } #[inline] fn second_mut(&mut self) -> &mut dyn Control { self.inner.inne...
static> SplittedInner for T { #[inline] fn with_content(first: Box<dyn Control>, second: Box<dyn Control>, orientation: layout::Orientation) -> Box<dyn Splitted> { <<Self as HasInner>::I as SplittedInner>::with_content(first, second, orientation) } #[inline] fn set_splitter(&mut self, member...
random
[ { "content": "fn bck_is_immensely_stupid<'a>(a: Option<&'a mut (dyn Member)>) -> Option<&'static mut (dyn Member)> {\n\n unsafe { ::std::mem::transmute(a) }\n\n}\n", "file_path": "api/src/inner/application.rs", "rank": 0, "score": 221236.72205434926 }, { "content": "pub fn parse_markup(js...
Rust
src/slice/new_iter.rs
ImmemorConsultrixContrarie/bitvec
e2cf3ca6e047e2ffaa5e3e1122cb4d5cb39b29c1
#![allow(unused_unsafe)] #[cfg(feature = "std")] use std::{ iter::{ Chain, DoubleEndedIterator, ExactSizeIterator, FusedIterator, Iterator, }, marker::PhantomData, mem, ptr::NonNull, }; #[cfg(not(feature = "std"))] use core::{ iter::{ Chain, DoubleEndedIterator, ExactSizeIterator, FusedIterator, Iterator,...
#![allow(unused_unsafe)] #[cfg(feature = "std")] use std::{ iter::{ Chain, DoubleEndedIterator, ExactSizeIterator, FusedIterator, Iterator, }, marker::PhantomData, mem, ptr::NonNull, }; #[cfg(not(feature = "std"))] use core::{ iter::{ Chain, DoubleEndedIterator, ExactSizeIterator, FusedIterator, Iterator,...
old }; Some(bit) } #[inline] fn last(mut self) -> Option<Self::Item> { self.next_back() } } impl<'a, T: BitMemory, O: BitOrder> DoubleEndedIterator for Iter<'a, T, O> { #[inline] fn next_back(&mut self) -> Option<Self::Item> { if is_empty!(self) { return None; } else { if self.bit_end == Se...
if self.bit_ptr == Self::last_bit() { forward_ptr_unchecked!(self); } else { self.bit_ptr = O::rot_forward(self.bit_ptr, 1); }
if_condition
[ { "content": "#[bench]\n\nfn bits_seq_u32(b: &mut Bencher) {\n\n\tb.iter(|| {\n\n\t\tbits![Local, u32;\n\n\t\t\t0, 1, 0, 1, 0, 0, 1, 1,\n\n\t\t\t0, 1, 1, 0, 0, 0, 0, 1,\n\n\t\t\t0, 1, 1, 0, 1, 1, 0, 0,\n\n\t\t\t0, 1, 1, 1, 0, 1, 0, 1,\n\n\t\t\t0, 1, 1, 1, 0, 1, 0, 0,\n\n\t\t\t0, 1, 1, 0, 1, 1, 1, 1,\n\n\t\t\t0,...
Rust
src/pad/mod.rs
fifth-postulate/T9
4ff8992a45f4060c9ed7f7707b4f8474e9a3ce11
use std::fmt; pub fn digits_for<S>(input: S) -> Digits where S: Into<String>, { let input = input.into(); let digits: Vec<Digit> = input .chars() .filter(|c| c.is_ascii()) .map(Digit::from) .collect(); Digits::from(digits) } #[derive(PartialEq, Debug)] pub struct Digi...
use std::fmt; pub fn digits_for<S>(input: S) -> Digits where S: Into<String>, { let input = input.into(); let digits: Vec<Digit> = input .chars() .filter(|c| c.is_ascii()) .map(Digit::from) .collect(); Digits::from(digits) } #[derive(PartialEq, Debug)] pub struct Digi...
ed) in [ (Digit::One, "1"), (Digit::Two, "2"), (Digit::Three, "3"), (Digit::Four, "4"), (Digit::Five, "5"), (Digit::Six, "6"), (Digit::Seven, "7"), (Digit::Eight, "8"), (Digit::Nine, "9"), (Digit::Zer...
impl From<[Digit; $n]> for Digits { fn from(digits: [Digit; $n]) -> Self { Self { digits: digits.to_vec(), } } } }; } from_for_digits!(1); from_for_digits!(2); from_for_digits!(3); from_for_digits!(4); from_for_digits!(5); f...
random
[ { "content": "#[derive(Debug)]\n\nstruct Node {\n\n subtrees: HashMap<Digit, usize>,\n\n words: Vec<String>,\n\n}\n\n\n\nimpl Node {\n\n fn empty() -> Self {\n\n Self {\n\n subtrees: HashMap::new(),\n\n words: Vec::new(),\n\n }\n\n }\n\n\n\n fn add(&mut self, w...
Rust
src/main.rs
EnterpriseComputingSystems/DECALS-ControlPanel
6b40292d7a127d6cd6d6248dc80dcf14c7c27930
#[macro_use] extern crate conrod; #[macro_use] extern crate conrod_derive; extern crate DECALS_base; extern crate rand; extern crate find_folder; extern crate piston_window; #[macro_use] extern crate log; extern crate time; mod interface; fn main() { feature::main(); } mod feature { use conrod; use fin...
#[macro_use] extern crate conrod; #[macro_use] extern crate conrod_derive; extern crate DECALS_base; extern crate rand; extern crate find_folder; extern crate piston_window; #[macro_use] extern crate log; extern crate time; mod interface; fn main() { feature::main(); } mod feature { use conrod; use fin...
pub fn theme() -> conrod::Theme { use conrod::position::{Align, Direction, Padding, Position, Relative}; conrod::Theme { name: "DECALS Theme".to_string(), padding: Padding::none(), x_position: Position::Relative(Relative::Align(Align::Start), None), ...
let init = vec![128; buffer_len]; let settings = TextureSettings::new(); let factory = &mut window.factory; let texture = G2dTexture::from_memory_alpha(factory, &init, WIDTH, HEIGHT, &settings).unwrap(); (cache, texture) }; let logo: G2dTexture =...
function_block-function_prefix_line
[ { "content": "/// Construct the DECALS interface\n\n/// Responsive to changes in window size\n\npub fn build_interface(ui: &mut UiCell, interface: &mut InterfaceState) {\n\n\n\n {\n\n let rec = interface.network.event_receiver.lock().unwrap();\n\n loop {\n\n match rec.try_recv() {\n\...
Rust
src/search/query.rs
pancreaflame/github-stats-rs
0f73777bbb7dbb9f2cea1aef0cadfe69751d97a2
use std::fmt; use crate::Repo; #[derive(Default)] pub struct Query { repo: Vec<String>, is: Vec<String>, r#in: Vec<In>, label: Vec<String>, r#type: Vec<String>, state: Vec<String>, no: Vec<String>, language: Vec<String>, } impl Query { pub fn new() -> Self { Query { ...
use std::fmt; use crate::Repo; #[derive(Default)] pub struct Query { repo: Vec<String>, is: Vec<String>, r#in: Vec<In>, label: Vec<String>, r#type: Vec<String>, state: Vec<String>, no: Vec<String>, language: Vec<String>, } impl Query { pub fn new() -> Self { Query { ...
ap(|s| format!("type:{}", s)).collect(); let mut state: Vec<String> = self.state.iter().map(|s| format!("state:{}", s)).collect(); let mut no: Vec<String> = self.no.iter().map(|s| format!("no:{}", s)).collect(); let mut language: Vec<String> = ...
ter().map(|s| format!("is:{}", s)).collect(); let mut r#in: Vec<String> = self.r#in.iter().map(|s| s.to_string()).collect(); let mut label: Vec<String> = self.label.iter().map(|s| format!("label:{}", s)).collect(); let mut r#type: Vec<String> = self.r#type.iter().m
function_block-random_span
[ { "content": "// Takes [Github] user and repo IDs to make a link to the API for that repo.\n\n//\n\n// [Github]: https://github.com/\n\nfn repo_api_url(user: &str, repo: &str) -> String {\n\n const URL: &str = \"https://api.github.com/repos\";\n\n format!(\"{}/{}/{}\", URL, user, repo)\n\n}\n", "file_...
Rust
src/palette.rs
SecretPocketCat/tennis_rounds
3b7c8cd10da13c594ac357539eaf59a8a5d7f155
use bevy::prelude::*; use bevy_prototype_lyon::prelude::{DrawMode, FillMode, StrokeMode}; use bevy_tweening::{ lens::{SpriteColorLens, TextColorLens}, Animator, EaseFunction, Tween, TweeningType, }; use rand::random; use crate::{ input_binding::{InputAction, PlayerInput}, level::Court, trail::Trail...
use bevy::prelude::*; use bevy_prototype_lyon::prelude::{DrawMode, FillMode, StrokeMode}; use bevy_tweening::{ lens::{SpriteColorLens, TextColorLens}, Animator, EaseFunction, Tween, TweeningType, }; use rand::random; use crate::{ input_binding::{InputAction, PlayerInput}, level::Court, trail::Trail...
} } } fn on_sprite_added( palette: Res<Palette>, mut q: Query<(&PaletteColor, &mut Sprite), Added<Sprite>>, ) { for (col, mut sprite) in q.iter_mut() { sprite.color = palette.get_color(col); } } fn on_text_added(palette: Res<Palette>, mut q: Query<(&PaletteColor, &mut Text), Added...
if let Some(text) = text { commands.entity(e).insert(Animator::new(Tween::new( EaseFunction::QuadraticInOut, TweeningType::Once, std::time::Duration::from_millis(1000), TextColorLens { start: text.sec...
if_condition
[ { "content": "pub fn inverse_lerp(a: f32, b: f32, t: f32) -> f32 {\n\n (t - a) / (b - a)\n\n}\n", "file_path": "src/animation.rs", "rank": 1, "score": 168972.24790489385 }, { "content": "fn get_idle_face_tween(z: f32) -> Tween<Transform> {\n\n Tween::new(\n\n EaseFunction::Quadr...
Rust
src/ser/mod.rs
Manishearth/serde
c3fe6c9c67867efb6253298f461d9680088c79e7
pub mod impls; pub trait Serialize { fn serialize<S>(&self, serializer: &mut S) -> Result<(), S::Error> where S: Serializer; } pub trait Serializer { type Error; fn visit_bool(&mut self, v: bool) -> Result<(), Self::Error>; #[inline] fn visit_isize(&mut self, v: isize) -...
pub mod impls; pub trait Serialize { fn serialize<S>(&self, serializer: &mut S) -> Result<(), S::Error> where S: Serializer; } pub trait Serializer { type Error; fn visit_bool(&mut self, v: bool) -> Result<(), Self::Error>; #[inline] fn visit_isize(&mut self, v: isize) -...
#[inline] fn visit_enum_map<V>(&mut self, _name: &'static str, _variant: &'static str, visitor: V) -> Result<(), Self::Error> where V: MapVisitor, { self.visit_map(visitor) } fn visit_map_elt<K, V>(&mut ...
fn visit_named_map<V>(&mut self, _name: &'static str, visitor: V) -> Result<(), Self::Error> where V: MapVisitor, { self.visit_map(visitor) }
function_block-full_function
[ { "content": "/// Decodes a json value from a `&str`.\n\npub fn from_slice<T>(v: &[u8]) -> Result<T, Error>\n\n where T: de::Deserialize\n\n{\n\n from_iter(v.iter().map(|byte| Ok(*byte)))\n\n}\n\n\n", "file_path": "src/json/de.rs", "rank": 0, "score": 223563.0525017362 }, { "content": ...
Rust
src/light.rs
robdimsdale/pi_clock
568d4dd09c94365e306f6cd4defc04e060d6aeed
mod error; pub use error::Error; use chrono::{Local, NaiveTime}; use lazy_static::*; use rand::prelude::*; use std::sync::Mutex; #[cfg(target_arch = "arm")] use log::debug; #[cfg(target_arch = "arm")] use rppal::i2c::I2c; #[cfg(target_arch = "arm")] use veml6030::{SlaveAddr, Veml6030}; const MAX_LUX: f32 = 1.0; con...
mod error; pub use error::Error; use chrono::{Local, NaiveTime}; use lazy_static::*; use rand::prelude::*; use std::sync::Mutex; #[cfg(target_arch = "arm")] use log::debug; #[cfg(target_arch = "arm")] use rppal::i2c::I2c; #[cfg(target_arch = "arm")] use veml6030::{SlaveAddr, Veml6030}; const MAX_LUX: f32 = 1.0; con...
); assert_eq!( round( time_based_brightness_for_time( &(*MAX_LUX_END_TIME - chrono::Duration::nanoseconds(1)) ) .unwrap(), 0 ), 1. ); assert_eq!( round...
esult<f32, Error> { time_based_brightness_for_time(&Local::now().time()) } } fn time_based_brightness_for_time(t: &NaiveTime) -> Result<f32, Error> { let midnight = NaiveTime::from_num_seconds_from_midnight(0, 0); let full_bright_range = *MAX_LUX_START_TIME..*MAX_LUX_END_TIME; let bright_to_da...
random
[ { "content": "pub trait Display {\n\n fn print(\n\n &mut self,\n\n time: &DateTime<Local>,\n\n current_state_index: u32,\n\n weather: &Option<OpenWeather>,\n\n ) -> Result<(), Error>;\n\n}\n\n\n\npub struct Console16x2Display<'a, T: LightSensor> {\n\n light_sensor: &'a T,\n\...
Rust
rlink/src/api/operator.rs
yorkart/rlink-rs
3bbbc049ac71c412f585d641328441bb830c898d
use crate::api::function::{ FilterFunction, Function, KeySelectorFunction, MapFunction, ReduceFunction, }; use crate::api::input::InputFormat; use crate::api::output::OutputFormat; use crate::api::watermark::WatermarkAssigner; use crate::api::window::WindowAssigner; use std::fmt::Debug; pub const DEFAULT_PARALLELI...
use crate::api::function::{ FilterFunction, Function, KeySelectorFunction, MapFunction, ReduceFunction, }; use crate::api::input::InputFormat; use crate::api::output::OutputFormat; use crate::api::watermark::WatermarkAssigner; use crate::api::window::WindowAssigner; use std::fmt::Debug; pub const DEFAULT_PARALLELI...
pub fn new_map(id: u32, parent_id: u32, map_fn: Box<dyn MapFunction>) -> Self { let operator = StreamOperator::new( id, parent_id, DEFAULT_PARALLELISM, FunctionCreator::User, map_fn, ); StreamOperatorWrap::StreamMap(operator) ...
pub fn new_source( id: u32, parent_id: u32, parallelism: u32, fn_creator: FunctionCreator, source_fn: Box<dyn InputFormat>, ) -> Self { let operator = StreamOperator::new(id, parent_id, parallelism, fn_creator, source_fn); StreamOperatorWrap::StreamSource(oper...
function_block-full_function
[ { "content": "pub trait Window: Debug + Clone {\n\n fn max_timestamp(&self) -> u64;\n\n fn min_timestamp(&self) -> u64;\n\n}\n\n\n\n#[derive(Clone, Debug, Serialize, Deserialize, PartialEq, Eq, Hash)]\n\npub struct TimeWindow {\n\n start: u64,\n\n end: u64,\n\n}\n\n\n\nimpl TimeWindow {\n\n pub f...
Rust
core_model/src/coco_config.rs
jtong/coco
9172aea75cc9685e5bd8838cbf3b0c22ccb65706
use serde::{Deserialize, Serialize}; use std::{env, fs}; #[derive(Debug, PartialEq, Serialize, Deserialize, Clone)] pub struct CocoConfig { pub repos: Vec<RepoConfig>, #[serde(skip_serializing_if = "Option::is_none")] pub plugins: Option<Vec<CocoPlugin>>, } impl Default for CocoConfig { fn default() -...
use serde::{Deserialize, Serialize}; use std::{env, fs}; #[derive(Debug, PartialEq, Serialize, Deserialize, Clone)] pub struct CocoConfig { pub repos: Vec<RepoConfig>, #[serde(skip_serializing_if = "Option::is_none")] pub plugins: Option<Vec<CocoPlugin>>, } impl Default for CocoConfig { fn default() -...
} } #[derive(Debug, PartialEq, Serialize, Deserialize, Clone)] pub struct RepoConfig { pub url: String, pub languages: Option<Vec<String>>, } impl Default for RepoConfig { fn default() -> Self { RepoConfig { url: "".to_string(), languages: None, } } } impl...
match fs::read_to_string(config_file) { Ok(content) => serde_yaml::from_str(&content).expect("parse config file error"), Err(_) => { let mut repo = vec![]; let current = env::current_dir().unwrap(); repo.push(RepoConfig { url: c...
if_condition
[ { "content": "fn files_from_path(url_str: &str) -> Vec<String> {\n\n let mut origin_files = vec![];\n\n let path = uri_to_path(url_str);\n\n for result in Walk::new(path) {\n\n if let Ok(entry) = result {\n\n if entry.file_type().unwrap().is_file() {\n\n origin_files.pu...
Rust
src/api/mod.rs
dgoetsch/rust-rest-api
33269dca017f9e82eb23fad5ff85e43637e71fb8
extern crate serde_json; use self::serde_json::Value; use self::serde_json::Number; use self::serde_json::Map; use self::super::RestApp; use std::fs; use std::fs::File; use std::io::prelude::*; const NULL_TYPE: &str = "NULL"; const BOOL_TYPE: &str = "BOOL"; const STRING_TYPE: &str = "STRING"; const NUMBER_TYPE: &str...
extern crate serde_json; use self::serde_json::Value; use self::serde_json::Number; use self::serde_json::Map; use self::super::RestApp; use std::fs; use std::fs::File; use std::io::prelude::*; const NULL_TYPE: &str = "NULL"; const BOOL_TYPE: &str = "BOOL"; const STRING_TYPE: &str = "STRING"; const NUMBER_TYPE: &str...
fn write_class_file(&self, mut path: PathBuf, t: &str) -> Result<(), APIErr> { path.push(String::from(CLASS_FILE_NAME)); self.write_field(path, String::from(t), CLASS_TYPE) } fn ensure_path(&self, path: PathBuf) -> Result<(), APIErr>; fn aggregate(&self, errors: Vec<APIErr>) -> Resul...
fn write_collection_members(&self, path: PathBuf, m: Vec<(String, Value)>, user: String) -> Vec<APIErr> { m.into_iter() .flat_map(|(k, v)| { let mut p = path.clone(); p.push(k); self .write_path(p, v, user.c...
function_block-full_function
[ { "content": "fn to_path_buf(path: Vec<String>) -> PathBuf {\n\n let mut path_buf = PathBuf::new();\n\n path.into_iter().for_each(|p| path_buf.push(p));\n\n path_buf\n\n}\n\n\n", "file_path": "src/test/api/mod.rs", "rank": 0, "score": 114353.27995625675 }, { "content": "...
Rust
src/message/header.rs
algesten/mdns
584cb652646d2022e75ebebec43241da81c76cc7
use super::*; #[derive(Default, Debug, Copy, Clone, PartialEq)] pub struct Header { pub id: u16, pub response: bool, pub op_code: OpCode, pub authoritative: bool, pub truncated: bool, pub recursion_desired: bool, pub recursion_available: bool, pub rcode: RCode, } impl fmt::Display for ...
use super::*; #[derive(Default, Debug, Copy, Clone, PartialEq)] pub struct Header { pub id: u16, pub response: bool, pub op_code: OpCode, pub authoritative: bool, pub truncated: bool, pub recursion_desired: bool, pub recursion_available: bool, pub rcode: RCode, } impl fmt::Display for ...
r Section { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { let s = match *self { Section::NotStarted => "NotStarted", Section::Header => "Header", Section::Questions => "question", Section::Answers => "answer", Section::Authorities => "...
n::Answers, 4 => Section::Authorities, 5 => Section::Additionals, _ => Section::Done, } } } impl fmt::Display fo
random
[ { "content": "fn must_edns0_resource_header(l: u16, extrc: u32, d: bool) -> Result<ResourceHeader> {\n\n let mut h = ResourceHeader {\n\n class: DNSCLASS_INET,\n\n ..Default::default()\n\n };\n\n h.set_edns0(l, extrc, d)?;\n\n Ok(h)\n\n}\n\n\n", "file_path": "src/message/message_te...
Rust
games/src/memory.rs
rlane/picosystem-rs
fe37feb195e531096456c7fb1545f601d81dffca
use picosystem::display::WIDTH; use picosystem::{hardware, time}; use embedded_graphics::mono_font::{ascii::FONT_10X20, MonoTextStyle}; use embedded_graphics::pixelcolor::Rgb565; use embedded_graphics::prelude::*; use embedded_graphics::primitives::*; use embedded_graphics::text::{Alignment, Baseline, Text, TextStyleB...
use picosystem::display::WIDTH; use picosystem::{hardware, time}; use embedded_graphics::mono_font::{ascii::FONT_10X20, MonoTextStyle}; use embedded_graphics::pixelcolor::Rgb565; use embedded_graphics::prelude::*; use embedded_graphics::primitives::*; use embedded_graphics::text::{Alignment, Baseline, Text, TextStyleB...
} #[derive(Copy, Clone, Debug, PartialEq)] struct GridPoint { x: i32, y: i32, } pub fn main(hw: &mut hardware::Hardware) -> ! { loop { run_game(hw); } } fn generate_grid() -> Grid { let mut grid = Grid::new(); let mut rng = oorandom::Rand32::new(time::time_us() as u64); let mut ...
lf.found[y as usize][x as usize] { return false; } } } true }
function_block-function_prefixed
[ { "content": "fn is_found(grid: &Grid, rect: &GridRect) -> bool {\n\n for y in rect.a.y..=rect.b.y {\n\n for x in rect.a.x..=rect.b.x {\n\n if !grid.found[y as usize][x as usize] {\n\n return false;\n\n }\n\n }\n\n }\n\n true\n\n}\n\n\n\nconst LETTER_W...
Rust
icp/src/input/arg_parser.rs
ilya-bobyr/icp
59b81b5efa311728dd6c35ddb4a97028eca9c6c3
use std::cell::RefCell; use std::cmp::Ordering; use std::marker::PhantomData; use std::ops::Deref; use std::rc::Rc; use map::{Arg2Map, ContextFreeMap}; pub mod alternatives; pub mod file; pub mod keyword_set; pub mod map; pub mod prim_int; pub mod test_utils; #[cfg(test)] pub use alternatives::alternatives_arg2; ...
use std::cell::RefCell; use std::cmp::Ordering; use std::marker::PhantomData; use std::ops::Deref; use std::rc::Rc; use map::{Arg2Map, ContextFreeMap}; pub mod alternatives; pub mod file; pub mod keyword_set; pub mod map; pub mod prim_int; pub mod test_utils; #[cfg(test)] pub use alternatives::alternatives_arg2; ...
mpl<T, Res> ContextFreeArgParser<Res> for RefCell<T> where T: ContextFreeArgParser<Res>, { fn parse(&self, input: &str) -> ArgParseRes<Res> { self.borrow().parse(input) } fn suggestion(&self, prefix: &str) -> Vec<String> { self.borrow().suggestion(prefix) } fn hint(&self) -> Vec<...
Parser: ContextFreeArgParser<Res>, { fn parse(&self, input: &str) -> ArgParseRes<Res> { self.parser.parse(input) } fn suggestion(&self, prefix: &str) -> Vec<String> { self.parser.suggestion(prefix) } fn hint(&self) -> Vec<String> { self.parser.hint() } } impl<T, Res...
random
[ { "content": "/// Removes the last component from a file path given as a string. `Path` has a\n\n/// similar functionality but it normalizes the input first, which we do not\n\n/// want. See the usage location.\n\nfn cut_last_component(mut input: &str) -> &str {\n\n // Skip any number of trailing '/'es.\n\...
Rust
protocols/gossipsub/tests/gossip_unit_tests.rs
kingwel-xie/libp2p-rs
1ee1029749755002dd394c1f12196eec5f6d4ddc
use futures::executor::block_on; use libp2prs_core::{ identity::Keypair, multiaddr::Protocol, transport::{memory::MemoryTransport, upgrade::TransportUpgrade}, }; use libp2prs_core::{Multiaddr, PeerId}; use libp2prs_gossipsub::{ control::Control as GossipControl, gossipsub::{Gossipsub, MessageAuthent...
use futures::executor::block_on; use libp2prs_core::{ identity::Keypair, multiaddr::Protocol, transport::{memory::MemoryTransport, upgrade::TransportUpgrade}, }; use libp2prs_core::{Multiaddr, PeerId}; use libp2prs_gossipsub::{ control::Control as GossipControl, gossipsub::{Gossipsub, MessageAuthent...
.skip(1) { let mut gossip = node.get_gossip(); let subscription = gossip.subscribe(topic.hash()).await.unwrap(); subscription_list.push(subscription); } dense_connect(node_list.clone()); task::sleep(Duration::from_secs(2)).await; ...
; subscription_list.push(subscription); } task::sleep(Duration::from_secs(2)).await; let _ = node_list[0].get_gossip().publish(topic.hash(), message.to_vec()).await; for mut subscription in subscription_list { if let Some(msg) = subscription.next().await { ...
random
[ { "content": "fn setup_swarm(key: Keypair) -> (Swarm, Control) {\n\n let sec = secio::Config::new(key.clone());\n\n let yamux = yamux::Config::new();\n\n let t = TransportUpgrade::new(MemoryTransport::default(), yamux, sec);\n\n\n\n let gossip_config = GossipsubConfigBuilder::new(key.public().into_p...
Rust
src/cmt/pubkey.rs
Kixunil/rust-lnpbp
ebaf239e8320bd2b625b6079648107724603eed9
use std::sync::Once; use bitcoin::hashes::*; use bitcoin::secp256k1::{*, Error as CurveError}; use crate::common::*; use super::committable::*; const TAG: &'static str = "LNPBP1"; static INIT: Once = Once::new(); static mut PREFIX: [u8; 32] = [ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,...
use std::sync::Once; use bitcoin::hashes::*; use bitcoin::secp256k1::{*, Error as CurveError}; use crate::common::*; use super::committable::*; const TAG: &'static str = "LNPBP1"; static INIT: Once = Once::new(); static mut PREFIX: [u8; 32] = [ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,...
}
t = prefixed_msg.clone().commit_embed(pubkey).unwrap(); assert_eq!(prefixed_msg.verify(&commitment), true); }
function_block-function_prefixed
[ { "content": "pub fn tagged256hash(tag: &str, msg: Vec<u8>) -> TaggedHash {\n\n let mut engine = sha256::Hash::engine();\n\n let tag_hash = sha256::Hash::hash(tag.as_bytes());\n\n engine.input(&tag_hash[..]);\n\n engine.input(&tag_hash[..]);\n\n engine.input(&msg[..]);\n\n sha256::Hash::from_e...
Rust
src/regularized/greenkhorn.rs
kachark/rust-optimal-transport
1d671141a95048e9aac98119dc8cd6b672aba262
use ndarray::prelude::*; use ndarray_stats::QuantileExt; use anyhow::anyhow; use crate::OTError; pub fn greenkhorn( a: &mut Array1<f64>, b: &mut Array1<f64>, M: &mut Array2<f64>, reg: f64, num_iter_max: Option<i32>, stop_threshold: Option<f64>) -> Result<Array2<f64>, OTError>{ let mut iterations = ...
use ndarray::prelude::*; use ndarray_stats::QuantileExt; use anyhow::anyhow; use crate::OTError; pub fn greenkhorn( a: &mut Array1<f64>, b: &mut Array1<f64>, M: &mut Array2<f64>, reg: f64, num_iter_max: Option<i32>, stop_threshold: Option<f64>) -> Result<Array2<f64>, OTError>{ let mut iterations = ...
j]; } } viol[i_1] = (k_i1.dot(&v) * new_u) - a[i_1]; for (j, ele) in viol_2.iter_mut().enumerate() { *ele += k_i1.t()[j] * (new_u - old_u) * v[j]; } u[i_1] = new_u; } else { le...
); for _ in 0..iterations { let viol_abs: Array1<f64> = viol.iter().map(|x| x.abs()).collect(); let viol_2_abs: Array1<f64> = viol_2.iter().map(|x| x.abs()).collect(); let i_1 = match viol_abs.argmax() { Ok(val) => val, Err(err) => re...
random
[ { "content": "#[allow(non_snake_case)]\n\npub fn emd_c(a: &mut Array1<f64>, b: &mut Array1<f64>, M: &mut Array2<f64>, max_iter: i32)\n\n -> (Array2<f64>, f64, Array1<f64>, Array1<f64>, i32) {\n\n\n\n let mshape = M.shape();\n\n let n1 = mshape[0];\n\n let n2 = mshape[1];\n\n\n\n let _nmax = n1 + ...
Rust
src/random.rs
juliotpaez/rust-g60
71fca015aab5915e929e2c5f2a8551c3b624cb59
use crate::{decoding, encoding}; use rand::rngs::{SmallRng, StdRng}; use rand::{Rng, SeedableRng}; pub fn random_bytes(bytes: usize) -> String { let mut rng = StdRng::from_entropy(); custom_random_bytes(bytes, |v| rng.fill(v)) } pub fn unsecure_random_bytes(bytes: usize) -> String { let mut rng = SmallRn...
use crate::{decoding, encoding}; use rand::rngs::{SmallRng, StdRng}; use rand::{Rng, SeedableRng}; pub fn random_bytes(bytes: usize) -> String { let mut rng = StdRng::from_entropy(); custom_random_bytes(bytes, |v| rng.fill(v)) } pub fn unsecure_random_bytes(bytes: usize) -> String { let mut rng = SmallRn...
#[test] fn test_random_str_same_length() { for length in [0usize, 2, 3, 5, 6, 7, 9, 10, 11] { for multiplier in 0..10 { let length = length + multiplier * 11; let random = random_str(length); assert_eq!(random.len(), length, "Length is incorr...
incorrect"); let encoded = encode(&decoded); assert_eq!(encoded, random, "Encoding and random are different") } }
function_block-function_prefixed
[ { "content": "/// Generates a random G60 string of exactly `length` characters using a custom random generator.\n\n/// Note: depending on the length it can result in a valid G60 encoded string or not.\n\npub fn exactly_custom_random<F>(length: usize, mut rng: F) -> String\n\nwhere\n\n F: FnMut(&mut [u8]),\n\...
Rust
c3_led_tail_trinketm0/src/main.rs
lukasfink1/36c3_led_stuff
a39d36788ebbffd5b5a1d3658b4d32a060eced81
#![no_main] #![no_std] #[allow(unused)] use panic_semihosting; use apa102_spi as apa102; use trinket_m0 as hal; use hal::clock::GenericClockController; use hal::delay::Delay; use hal::gpio::*; use hal::prelude::*; use hal::sercom::*; use hal::time::Hertz; use hal::timer::TimerCounter; use instant_timer::InstantTimer...
#![no_main] #![no_std] #[allow(unused)] use panic_semihosting; use apa102_spi as apa102; use trinket_m0 as hal; use hal::clock::GenericClockController; use hal::delay::Delay; use hal::gpio::*; use hal::prelude::*; use hal::sercom::*; use hal::time::Hertz; use hal::timer::TimerCounter; use instant_timer::InstantTimer...
#[idle(resources = [delay, dotstar, serial, timer, external])] fn idle(c: idle::Context) -> ! { let mut elements = Elements::new(80, 8); let mut rand = oorandom::Rand32::new(0); let mut steps = rand.rand_range(10..20); while...
t), ); let gclk0 = clocks.gclk0(); let timer_clock = clocks.tcc2_tc3(&gclk0).unwrap(); let mut timer_dotstar = TimerCounter::tc3_(&timer_clock, p.TC3, &mut p.PM); timer_dotstar.start(5.khz()); let spi = bitbang_hal::spi::SPI::new(apa102_spi::MODE, nc, odi, oci, timer_do...
function_block-function_prefixed
[ { "content": "#[derive(StructOpt, Debug)]\n\n#[structopt(name = \"c3_host\")]\n\nstruct Opt {\n\n /// The serial port\n\n #[structopt(short, long)]\n\n tty: PathBuf,\n\n}\n\n\n", "file_path": "c3_host/src/main.rs", "rank": 0, "score": 31361.53606800463 }, { "content": "fn main() {\n...
Rust
ivy-graphics/src/camera_manager.rs
ten3roberts/ivy
fb5a7645c9f699c2aebf3d1b90c1d1f9e78355fa
use crate::Result; use derive_more::{Deref, From, Into}; use std::{mem::size_of, sync::Arc}; use crate::Error; use hecs::{Entity, World}; use ivy_vulkan::{Buffer, BufferAccess, BufferType, VulkanContext}; use crate::camera::{Camera, CameraData}; pub struct CameraManager { camera_buffers: Vec<Buffer>, max_cam...
use crate::Result; use derive_more::{Deref, From, Into}; use std::{mem::size_of, sync::Arc}; use crate::Error; use hecs::{Entity, World}; use ivy_vulkan::{Buffer, BufferAccess, BufferType, VulkanContext}; use crate::camera::{Camera, CameraData}; pub struct CameraManager { camera_buffers: Vec<Buffer>, max_cam...
} pub fn dynamic_offset(&self) -> u32 { self.dynamic_offset } pub fn offset_of(&self, world: &World, camera: Entity) -> Result<u32> { Ok(**world.get::<CameraIndex>(camera)? * self.dynamic_offset) } pub fn register(&mut self, world: &mut World, camera: Entity) -...
Ok(Self { camera_buffers, max_camera_index: 0, dynamic_offset, max_capacity, })
call_expression
[ { "content": "/// Recursively draw the connection tree using gizmos\n\npub fn draw_connections(world: &impl GenericWorld, gizmos: &mut Gizmos) -> Result<()> {\n\n world\n\n .roots::<Connection>()?\n\n .into_iter()\n\n .try_for_each(|root| draw_subtree(world, root.0, gizmos))\n\n}\n\n\n",...
Rust
src/auth.rs
FuzzyWuzzie/wish-api
43d6bcba9d9f9c25ae1b4488e5ba3be42cfba130
use bcrypt::{hash, verify, DEFAULT_COST}; use rocket::http::Status; use rocket::request::{self, FromRequest, Request}; use rocket::Outcome; use rocket::State; use std::sync::Mutex; use rusqlite::Connection; use base64; use config::Config; use tokens; use errors::Error; #[derive(Debug)] pub struct AuthBasicSuccess { ...
use bcrypt::{hash, verify, DEFAULT_COST}; use rocket::http::Status; use rocket::request::{self, FromRequest, Request}; use rocket::Outcome; use rocket::State; use std::sync::Mutex; use rusqlite::Connection; use base64; use config::Config; use tokens; use errors::Error; #[derive(Debug)] pub struct AuthBasicSuccess { ...
; if auths.len() != 1 { return Outcome::Failure((Status::Unauthorized, ())); } let auth: Vec<&str> = auths[0].split(' ').collect(); if auth.len() != 2 || auth[0] != "Basic" { return Outcome::Failure((Status::Unauthorized, ())); } let auth = auth[...
Outcome::Success(token) } } impl<'a, 'r> FromRequest<'a, 'r> for IsAdmin { type Error = (); fn from_request(request: &'a Request<'r>) -> request::Outcome<IsAdmin, ()> { let token = request.guard::<AuthToken>()?; if !token.adm { return Outcome::Failure((Status::Unauthorized, ()...
random
[ { "content": "pub fn build_token(secret: &str, uid: u32, adm: bool) -> String {\n\n let claims = Claims {\n\n iss: \"wish-api\".to_owned(),\n\n uid,\n\n adm,\n\n };\n\n\n\n let token = encode(&Header::default(), &claims, secret.as_bytes()).unwrap();\n\n token\n\n}\n\n\n", "f...
Rust
src/import/kv_service.rs
glorv/importer
d9a90a49b23801369cf50d9e92bdc3ae1f62ade1
use std::sync::Arc; use futures::executor::{ThreadPool, ThreadPoolBuilder}; use futures::future::FutureExt; use futures::stream::StreamExt; use futures::task::SpawnExt; use grpcio::{ClientStreamingSink, RequestStream, RpcContext, UnarySink}; use kvproto::import_kvpb::*; use uuid::Uuid; use tikv_util::time::Instant;...
use std::sync::Arc; use futures::executor::{ThreadPool, ThreadPoolBuilder}; use futures::future::FutureExt; use futures::stream::StreamExt; use futures::task::SpawnExt; use grpcio::{ClientStreamingSink, RequestStream, RpcContext, UnarySink}; use kvproto::import_kvpb::*; use uuid::Uuid; use tikv_util::time::Instant;...
}
fn get_metrics( &mut self, ctx: RpcContext<'_>, _req: GetMetricsRequest, sink: UnarySink<GetMetricsResponse>, ) { let label = "get_metrics"; let timer = Instant::now_coarse(); ctx.spawn( self.threads .spawn_with_handle( ...
function_block-full_function
[ { "content": "pub fn make_rpc_error(err: Error) -> RpcStatus {\n\n RpcStatus::new(RpcStatusCode::UNKNOWN, Some(format!(\"{:?}\", err)))\n\n}\n\n\n\n#[macro_export]\n\nmacro_rules! send_rpc_response {\n\n ($res:ident, $sink:ident, $label:ident, $timer:ident) => {async move {\n\n let res = match $res...
Rust
src/ri.rs
janstarke/r-winreg
3eeaf2fad1da690a6bc57a832d3f9ae7ac01c195
use byteorder::{ByteOrder,LittleEndian}; use errors::RegError; use hive::HBIN_START_OFFSET; use cell::Cell; use cell::CellData; use nk::NodeKey; use std::io::{Read,Seek}; #[derive(Serialize, Debug)] pub struct RootIndex{ #[serde(skip_serializing)] _offset: u64, signature: u16, element_count: u16, e...
use byteorder::{ByteOrder,LittleEndian}; use errors::RegError; use hive::HBIN_START_OFFSET; use cell::Cell; use cell::CellData; use nk::NodeKey; use std::io::{Read,Seek}; #[derive(Serialize, Debug)] pub struct RootIndex{ #[serde(skip_serializing)] _offset: u64, signature: u16, element_count: u16, e...
pub fn increment_current_cell_data<Rs: Read+Seek>(&mut self, reader: &mut Rs)->Result<bool,RegError>{ if self.next_index + 1 > self.elements.len() { return Ok(false); } let cell_offset = self.elements[self.next_index] as u64 + HBIN_START_OFFSET; let cell = Ce...
signature: signature, element_count: element_count, elements: elements, next_index: next_index, current_cell_data: current_cell_data } ) }
function_block-function_prefix_line
[]
Rust
src/lib.rs
hongquan/envfile
b60f852607c0c07758acc8c2f5aec2548a23ac13
use std::collections::BTreeMap; use std::fs::File; use std::io::{self, Read, Write}; use std::path::Path; use std::str; pub struct EnvFile<'a> { pub path: &'a Path, pub store: BTreeMap<String, String>, } impl<'a> EnvFile<'a> { pub fn new(path: &'a Path) -> io::Result<EnvFile<'a>> { ...
use std::collections::BTreeMap; use std::fs::File; use std::io::{self, Read, Write}; use std::path::Path; use std::str; pub struct EnvFile<'a> { pub path: &'a Path, pub store: BTreeMap<String, String>, } impl<'a> EnvFile<'a> { pub fn new(path: &'a Path) -> io::Result<EnvFile<'a>> { ...
pub fn update(&mut self, key: &str, value: &str) { self.store.insert(key.into(), value.into()); } pub fn get(&self, key: &str) -> Option<&str> { self.store.get(key).as_ref().map(|x| x.as_str()) } pub fn write(&mut self) -> io::Result<()> { le...
let values = data.split(|&x| x == b'\n').flat_map(|entry| { entry.iter().position(|&x| x == b'=').and_then(|pos| { String::from_utf8(entry[..pos].to_owned()).ok() .and_then(|x| { String::from_utf8(entry[pos+1..].to_owned()).ok().map(|y| (x, y)) ...
function_block-function_prefix_line
[ { "content": "fn main() -> io::Result<()> {\n\n let mut envfile = EnvFile::new(&Path::new(\"examples/test.env\"))?;\n\n\n\n for (key, value) in &envfile.store {\n\n println!(\"{}: {}\", key, value);\n\n }\n\n\n\n envfile.update(\"ID\", \"example\");\n\n println!(\"ID: {}\", envfile.get(\"I...
Rust
src/sha3/sha3.rs
mengsuenyan/rcrypto
4d933eb9949381eb15d83037c0687f535902b17c
use crate::{KeccakSponge, Digest, Keccak}; #[derive(Clone)] enum SHA3Type { SHA224(SHA224), SHA256(SHA256), SHA384(SHA384), SHA512(SHA512), } #[derive(Clone)] pub struct SHA3 { sha_: SHA3Type, } impl SHA3 { pub fn sha224() -> Self { Self { sha_: SHA3Type::SHA224(SHA...
use crate::{KeccakSponge, Digest, Keccak}; #[derive(Clone)] enum SHA3Type { SHA224(SHA224), SHA256(SHA256), SHA384(SHA384), SHA512(SHA512), } #[derive(Clone)] pub struct SHA3 { sha_: SHA3Type, } impl SHA3 { pub fn sha224() -> Self { Self { sha_: SHA3Type::SHA224(SHA...
fn bits_len(&self) -> usize { match &self.sha_ { SHA3Type::SHA224(x) => x.bits_len(), SHA3Type::SHA256(x) => x.bits_len(), SHA3Type::SHA384(x) => x.bits_len(), SHA3Type::SHA512(x) => x.bits_len(), } } fn write(&mut self, data: &[u8]) { ...
fn block_size(&self) -> Option<usize> { match &self.sha_ { SHA3Type::SHA224(x) => x.block_size(), SHA3Type::SHA256(x) => x.block_size(), SHA3Type::SHA384(x) => x.block_size(), SHA3Type::SHA512(x) => x.block_size(), } }
function_block-full_function
[ { "content": "#[bench]\n\nfn sha384(b: &mut Bencher) {\n\n // (hash, msg)\n\n let cases = [\n\n (\"0C63A75B845E4F7D01107D852E4C2485C51A50AAAA94FC61995E71BBEE983A2AC3713831264ADB47FB6BD1E058D5F004\", \"\"),\n\n (\"737C9B491885E9BF7428E792741A7BF8DCA9653471C3E148473F2C236B6A0A6455EB1DCE9F779B4...
Rust
src/device.rs
Thog/fx3-tools-rs
101508b688f32331c039a7f05e697292bac32c4d
use rusb::*; use std::str; use std::time::Duration; use std::io::Cursor; use std::io::Write; use std::convert::TryInto; const ELGATO_VID: u16 = 0xfd9; const CYPRESS_VID: u16 = 0x04b4; const DEFAULT_TIMEOUT: Duration = Duration::from_millis(5000); const OUTPUT_REQUEST_TYPE: u8 = 0x40; const OUTPUT_HID_REQUEST_TYPE:...
use rusb::*; use std::str; use std::time::Duration; use std::io::Cursor; use std::io::Write; use std::convert::TryInto; const ELGATO_VID: u16 = 0xfd9; const CYPRESS_VID: u16 = 0x04b4; const DEFAULT_TIMEOUT: Duration = Duration::from_millis(5000); const OUTPUT_REQUEST_TYPE: u8 = 0x40; const OUTPUT_HID_REQUEST_TYPE:...
} fn prepare_for_ram_request(buffer: &mut [u8]) { let output_len_bytes: [u8; 4] = u32::to_le_bytes((buffer.len() - std::mem::size_of::<u32>()) as u32); buffer[..output_len_bytes.len()].copy_from_slice(&output_len_bytes); } impl<T: UsbContext> Device<T> { pub fn read_firmware_name(&self) -> Result...
vid_pid(vendor_id, product_id) { return Some(Device { handle, vendor_id, product_id }); } None }
function_block-function_prefixed
[ { "content": "pub fn parse(data: &[u8]) -> IResult<&[u8], Header> {\n\n header(data)\n\n}\n", "file_path": "src/cyfw/parser.rs", "rank": 0, "score": 80044.65453509428 }, { "content": "fn handle_device_command(options: DeviceCommand) {\n\n let devices = DeviceManager::devices();\n\n\n\n...
Rust
reg-index/src/metadata.rs
cschlosser/cargo-index
44726c3ecfc91e6107743de7509a860b5b5b4d6e
use crate::{ util::{cargo_package, cksum, extract_crate}, IndexDependency, IndexPackage, }; use failure::{bail, format_err, Error, ResultExt}; use same_file::is_same_file; use std::{ env, path::{Path, PathBuf}, }; use url::Url; pub(crate) struct MetaInfo { pub(crate) index_pkg: IndexPackage, pu...
use crate::{ util::{cargo_package, cksum, extract_crate}, IndexDependency, IndexPackage, }; use failure::{bail, format_err, Error, ResultExt}; use same_file::is_same_file; use std::{ env, path::{Path, PathBuf}, }; use url::Url; pub(crate) struct MetaInfo { pub(crate) index_pkg: IndexPackage, pu...
pub fn metadata( index_url: &str, manifest_path: Option<&Path>, package_args: Option<&Vec<String>>, ) -> Result<IndexPackage, Error> { Ok(metadata_reg(index_url, manifest_path, None, package_args)?.index_pkg) } pub(crate) fn metadata_reg( index_url: &str, manifest_path: Option<&Path>, cra...
pub fn metadata_from_crate( index_url: &str, crate_path: impl AsRef<Path>, ) -> Result<IndexPackage, Error> { let crate_path = crate_path.as_ref(); let (_tmp_dir, pkg_path) = extract_crate(crate_path)?; Ok(metadata_reg( index_url, Some(&pkg_path.join("Cargo.toml")), Some(crat...
function_block-full_function
[ { "content": "/// Validate an index.\n\n///\n\n/// Errors are displayed on stdout. Returns an error if any problems are\n\n/// found. `crates` is an optional path to a directory that contains `.crate`\n\n/// files to verify checksums. Supports `{crate}` and `{version}` markers.\n\npub fn validate(index: impl As...
Rust
src/binvox.rs
ivanceras/balisong
88dd21bc1f28c15146be6a65b970c4904275f82d
extern crate regex; use std::path::Path; use std::fs::File; use point::Point; use vector::Vector; use std::io::BufRead; use std::io::BufReader; use std::str::FromStr; use color::Color; use location; use voxel::voxtree::Voxtree; use voxel::voxbit::Voxbit; use voxel::vox::Vox; use normal::Normal; use voxelizer; use lod:...
extern crate regex; use std::path::Path; use std::fs::File; use point::Point; use vector::Vector; use std::io::BufRead; use std::io::BufReader; use std::str::FromStr; use color::Color; use location; use voxel::voxtree::Voxtree; use voxel::voxbit::Voxbit; use voxel::vox::Vox; use normal::Normal; use voxelizer; use lod:...
percentage = new_percentage; if *value > 0 { let (x,y,z) = location::index_to_xyz(&lod, index as u64); let loc = location::from_xyz(&lod, x, y, z); root.set_location(&loc); cnt += 1; } index += 1; } ...
th::new(&filename); let display = path.display(); let mut file = match File::open(&path) { Err(why) => panic!("couldn't open {}", display), Ok(file) => file, }; let mut reader = BufReader::new(file); let version = read_header(&mut re...
random
[ { "content": "/// a twist to the original but making the encoding the bits to local morton\n\npub fn to_xyz(location:&Vec<u64>)->(u64, u64, u64){\n\n let mut index = 0u64;\n\n let lod = LOD::new(location.len() as u8);\n\n for i in 0..location.len(){\n\n let local_index = which_bit(location[i]);\...
Rust
src/monotone/sweep.rs
rmanoka/geo-crossings
b1bfa2ab10735ed23ac6c4213662fc1d109cb066
use geo::{ coords_iter::CoordsIter, kernels::Kernel, winding_order::{Winding, WindingOrder}, Coordinate, GeoNum, LineString, Polygon, }; use log::debug; use pin_project_lite::pin_project; use slab::Slab; use smallvec::SmallVec; use std::{collections::BTreeSet, marker::PhantomPinned, pin::Pin}; use supe...
use geo::{ coords_iter::CoordsIter, kernels::Kernel, winding_order::{Winding, WindingOrder}, Coordinate, GeoNum, LineString, Polygon, }; use log::debug; use pin_project_lite::pin_project; use slab::Slab; use smallvec::SmallVec; use std::{collections::BTreeSet, marker::PhantomPinned, pin::Pin}; use supe...
handle_insert(&ixn.event_1); handle_insert(&ixn.event_2); Some(SweepEvent { pt, links, ty: ixn.ty, }) } } impl<T: GeoNum> Iterator for Pin<Box<Sweep<T>>> { type Item = SweepEvent<T>; fn next(&mut self) -> Option<Self::Item> { sel...
1) }; if helper.is_merge() || force { let pt2 = helper.point(); links.push(if helper.is_merge() { Link::Merge { prev: pt2, next: pt, limbs: Some((top, bot)...
random
[ { "content": "pub fn geo_intersects(poly: &Polygon<f64>, width: usize, height: usize) -> Array2<bool> {\n\n let bbox = poly.bounding_rect().unwrap();\n\n let left = bbox.min().x;\n\n let right = bbox.max().x;\n\n let slice_width = (right - left) / width as f64;\n\n\n\n let min_y = bbox.min().y;\n...
Rust
examples/smartwallet/main.rs
coinexchain/athena-rust-api
ab8a32bd385952699c964d725154a798e7380e12
use athena_rust_api as athena; use athena_rust_api::block::get_timestamp; use athena_rust_api::contracts::set_result; use athena_rust_api::events::begin; use athena_rust_api::params::get_str; use athena_rust_api::{contracts, events, kv, map, BigInt, HostStr}; use std::collections::HashMap; use std::intrinsics::transmut...
use athena_rust_api as athena; use athena_rust_api::block::get_timestamp; use athena_rust_api::contracts::set_result; use athena_rust_api::events::begin; use athena_rust_api::params::get_str; use athena_rust_api::{contracts, events, kv, map, BigInt, HostStr}; use std::collections::HashMap; use std::intrinsics::transmut...
fn limit(token: &str, limit: i64) { let caller = athena::get_caller_bech32(); let master = kv::get_str(MASTER).unwrap(); if caller != master { let successor = kv::get_str(SUCCESSOR); if successor.is_some() { if successor.unwrap() != caller { return events::emit(...
fn unfreeze() { let caller = athena::get_caller_bech32(); let successor = kv::get_str(SUCCESSOR); if successor.is_some() { if successor.unwrap() == caller { events::emit("smart_wallet", &[("event", "unfreeze"), ("type", "successor unfreeze")]); return kv::del_str("successor_f...
function_block-full_function
[ { "content": "fn get_addr_token(addr: &str, is_min: bool) -> HostStr {\n\n let curr = if is_min {\n\n kv::get_str(&format!(\"{} min\", addr))\n\n } else {\n\n kv::get_str(&format!(\"{} max\", addr))\n\n };\n\n if curr.is_some() {\n\n curr.unwrap()\n\n } else {\n\n &\"\...
Rust
lib-common/src/bcf.rs
bihealth/snappy-sv
7719792de58a37cd23cbb32087f632041ca2d0cb
use rust_htslib::{bcf, bcf::Read}; use super::error::Error; #[derive(Debug)] pub struct FormatInfo { pub format: bcf::Format, pub uncompressed: bool, } pub fn guess_bcf_format(filename: &str) -> FormatInfo { if filename.ends_with(".bcf") { FormatInfo { format: bcf::Format::B...
use rust_htslib::{bcf, bcf::Read}; use super::error::Error; #[derive(Debug)] pub struct FormatInfo { pub format:
.get("ID") .expect("source contig header does not have ID"), values .get("length") .expect("source contig header does not have length") ) .as_bytes(), ); } } ...
bcf::Format, pub uncompressed: bool, } pub fn guess_bcf_format(filename: &str) -> FormatInfo { if filename.ends_with(".bcf") { FormatInfo { format: bcf::Format::BCF, uncompressed: false, } } else if filename.ends_with(".vcf.gz") { FormatInfo { ...
random
[ { "content": "/// Return `bam::Format` for the given filename.\n\npub fn guess_bam_format(filename: &str) -> bam::Format {\n\n if filename.ends_with(\".bam\") {\n\n bam::Format::BAM\n\n } else {\n\n bam::Format::SAM\n\n }\n\n}\n\n\n", "file_path": "lib-common/src/bam.rs", "rank": ...