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
runtime/src/serde_snapshot/future.rs
im-0/solana
ccf2a05c8d16a24a9d111e85db5f3bc4f4a1ef9c
use super::common::UnusedAccounts; #[cfg(all(test, RUSTC_WITH_SPECIALIZATION))] use solana_frozen_abi::abi_example::IgnoreAsHelper; use {super::*, solana_measure::measure::Measure, std::cell::RefCell}; use crate::ancestors::AncestorsForSerialization; type AccountsDbFields = super::AccountsDbFields<SerializableAccount...
use super::common::UnusedAccounts; #[cfg(all(test, RUSTC_WITH_SPECIALIZATION))] use solana_frozen_abi::abi_example::IgnoreAsHelper; use {super::*, solana_measure::measure::Measure, std::cell::RefCell}; use crate::ancestors::AncestorsForSerialization; type AccountsDbFields = super::AccountsDbFields<SerializableAccount...
} #[derive(Serialize)] pub(crate) struct SerializableVersionedBank<'a> { pub(crate) blockhash_queue: &'a RwLock<BlockhashQueue>, pub(crate) ancestors: &'a AncestorsForSerialization, pub(crate) hash: Hash, pub(crate) parent_hash: Hash, pub(crate) parent_slot: Slot, pub(crate) hard_forks: &'a Rw...
fn from(dvb: DeserializableVersionedBank) -> Self { BankFieldsToDeserialize { blockhash_queue: dvb.blockhash_queue, ancestors: dvb.ancestors, hash: dvb.hash, parent_hash: dvb.parent_hash, parent_slot: dvb.parent_slot, hard_forks: dvb.hard_f...
function_block-full_function
[ { "content": "/// Computes a normalized (log of actual stake) stake.\n\npub fn get_stake<S: std::hash::BuildHasher>(id: &Pubkey, stakes: &HashMap<Pubkey, u64, S>) -> f32 {\n\n // cap the max balance to u32 max (it should be plenty)\n\n let bal = f64::from(u32::max_value()).min(*stakes.get(id).unwrap_or(&0...
Rust
src/connectivity/wlan/lib/common/rust/src/tim.rs
casey/fuchsia
2b965e9a1e8f2ea346db540f3611a5be16bb4d6b
use crate::mac::{Aid, MAX_AID}; const TIM_BITMAP_LEN: usize = (MAX_AID as usize + 1) / 8; pub struct TrafficIndicationMap([u8; TIM_BITMAP_LEN]); impl TrafficIndicationMap { pub fn new() -> Self { Self([0; TIM_BITMAP_LEN]) } pub fn set_traffic_buffered(&mut self, aid...
use crate::mac::{Aid, MAX_AID}; const TIM_BITMAP_LEN: usize = (MAX_AID as usize + 1) / 8; pub struct TrafficIndicationMap([u8; TIM_BITMAP_LEN]); impl TrafficIndicationMap { pub fn new() -> Self { Self([0; TIM_BITMAP_LEN]) } pub fn set_traffic_buffered(&mut self, aid...
#[cfg(test)] mod tests { use super::*; #[test] fn zero_offset() { let bitmap = &[0b0010010][..]; assert!(!is_traffic_buffered(0, bitmap, 0)); assert!(is_traffic_buffered(0, bitmap, 1)); assert!(!is_traffic_buffered(0, bitmap, 2)); assert!(!is_traffic_buffered(0, b...
pub fn is_traffic_buffered(offset: u8, bitmap: &[u8], aid: Aid) -> bool { let n1 = offset as usize * 2; let octet = aid as usize / 8; let carries_aid = n1 <= octet && octet < bitmap.len() + n1; carries_aid && bitmap[octet - n1] & (1 << (aid as usize % 8)) != 0 }
function_block-full_function
[]
Rust
examples2d/basic2.rs
willcrichton/salva
06d0b5720494eade6d49c65519476d77a640dc65
extern crate nalgebra as na; use na::{Isometry2, Point2, Point3, Vector2}; use ncollide2d::shape::{Cuboid, ShapeHandle}; use nphysics2d::force_generator::DefaultForceGeneratorSet; use nphysics2d::joint::DefaultJointConstraintSet; use nphysics2d::object::{ BodyPartHandle, ColliderDesc, DefaultBodySet, DefaultCollid...
extern crate nalgebra as na; use na::{Isometry2, Point2, Point3, Vector2}; use ncollide2d::shape::{Cuboid, ShapeHandle}; use nphysics2d::force_generator::DefaultForceGeneratorSet; use nphysics2d::joint::DefaultJointConstraintSet; use nphysics2d::object::{ BodyPartHandle, ColliderDesc, DefaultBodySet, DefaultCollid...
fn main() { let testbed = Testbed::from_builders(0, vec![("Boxes", init_world)]); testbed.run() }
d_handle, 0)); let co_handle = colliders.insert(co); let bo_handle = liquid_world.add_boundary(Boundary::new(Vec::new())); coupling_set.register_coupling(bo_handle, co_handle, CouplingMethod::DynamicContactSampling); /* * Create a dynamic box. */ let rad = 0.4; let cuboid = ShapeHandl...
function_block-function_prefixed
[ { "content": "pub fn cube_fluid(ni: usize, nj: usize, particle_rad: f32, density: f32) -> Fluid<f32> {\n\n let mut points = Vec::new();\n\n let half_extents = Vector2::new(ni as f32, nj as f32) * particle_rad;\n\n\n\n for i in 0..ni {\n\n for j in 0..nj {\n\n let x = (i as f32) * part...
Rust
src/ant_renderer.rs
mizkichan/ant-simulator
de7c92b6c4b2f6da051e8a70c54629bb64f93be8
use crate::resources::InstanceData; use crate::Assets; use std::mem; use wgpu::util::{BufferInitDescriptor, DeviceExt as _}; use wgpu::*; #[derive(Debug)] pub struct AntRenderer { pipeline: RenderPipeline, bind_group: BindGroup, vertex_buffer: Buffer, index_buffer: Buffer, } impl AntRenderer { #[m...
use crate::resources::InstanceData; use crate::Assets; use std::mem; use wgpu::util::{BufferInitDescriptor, DeviceExt as _}; use wgpu::*; #[derive(Debug)] pub struct AntRenderer { pipeline: RenderPipeline, bind_group: BindGroup, vertex_buffer: Buffer, index_buffer: Buffer, } impl AntRenderer { #[m...
, multisample: MultisampleState::default(), fragment: Some(FragmentState { module: &shader_module, entry_point: "fs_main", targets: &[ColorTargetState::from(swap_chain_texture_format)], }), }); let bind_group = device.c...
Some(DepthStencilState { format: depth_texture_format, depth_write_enabled: true, depth_compare: CompareFunction::Less, stencil: StencilState::default(), bias: DepthBiasState::default(), })
call_expression
[]
Rust
tokio/src/runtime/park.rs
jrawsthorne/tokio
cfd9b36d89e6b665c11248a86de8934cb4a7bdff
use crate::loom::sync::atomic::AtomicUsize; use crate::loom::sync::{Arc, Condvar, Mutex}; use crate::loom::thread; use crate::park::{Park, Unpark}; use crate::runtime::time; use crate::util::TryLock; use std::sync::atomic::Ordering::SeqCst; use std::time::Duration; pub(crate) struct Parker { inner: Arc<Inner>, ...
use crate::loom::sync::atomic::AtomicUsize; use crate::loom::sync::{Arc, Condvar, Mutex}; use crate::loom::thread; use crate::park::{Park, Unpark}; use crate::runtime::time; use crate::util::TryLock; use std::sync::atomic::Ordering::SeqCst; use std::time::Duration; pub(crate) struct Parker { inner: Arc<Inner>, ...
inconsistent park state; actual = {}", actual), } loop { m = self.condvar.wait(m).unwrap(); if self .state .compare_exchange(NOTIFIED, EMPTY, SeqCst, SeqCst) .is_ok() { return; ...
ime::Driver as Park>::Unpark, } impl Parker { pub(crate) fn new(driver: time::Driver) -> Parker { let handle = driver.unpark(); Parker { inner: Arc::new(Inner { state: AtomicUsize::new(EMPTY), mutex: Mutex::new(()), condvar: Condvar::new(...
random
[ { "content": "#[derive(Clone, Copy)]\n\nstruct State(usize);\n\n\n", "file_path": "tokio/src/sync/oneshot.rs", "rank": 0, "score": 210268.6029890452 }, { "content": "#[derive(Copy, Clone)]\n\nstruct State(usize);\n\n\n\nimpl Idle {\n\n pub(super) fn new(num_workers: usize) -> Idle {\n\n ...
Rust
pr47-core/src/syntax/token.rs
Pr47/Pr47
63ba347f7be60a62b7d0fc51f0555754d288df19
use std::fmt::{Display, Formatter}; use std::mem::discriminant; use smallvec::alloc::fmt::Debug; use xjbutil::display2::Display2; use crate::diag::location::SourceRange; #[derive(Clone, Copy)] #[cfg_attr(any(debug_assertions, test), derive(Debug))] pub enum TokenInner<'a> { Ident(&'a str), KwdAny, KwdAs...
use std::fmt::{Display, Formatter}; use std::mem::discriminant; use smallvec::alloc::fmt::Debug; use xjbutil::display2::Display2; use crate::diag::location::SourceRange; #[derive(Clone, Copy)] #[cfg_attr(any(debug_assertions, test), derive(Debug))] pub enum TokenInner<'a> { Ident(&'a str), KwdAny, KwdAs...
ing'"), TokenInner::KwdThrow => write!(fmt, "'throw'"), TokenInner::KwdTrue => write!(fmt, "'true'"), TokenInner::KwdTry => write!(fmt, "'try'"), TokenInner::KwdType => write!(fmt, "'type'"), TokenInner::KwdTypeOf => write!(fmt, "'typeof'"), TokenI...
Ckx => write!(f, "⟨ckx⟩"), RsvRefl => write!(f, "⟨refl⟩"), RsvRequire => write!(f, "⟨require⟩"), RsymAt => write!(f, "⟨@⟩"), RsymDollar => write!(f, "⟨$⟩"), SymAmp => write!(f, "⟨&⟩"), SymAster => write!(f, "⟨*⟩"), SymAsterEq => write!...
random
[ { "content": "pub fn part_of_identifier(ch: char) -> bool {\n\n match ch {\n\n '_' | 'A'..='Z' | 'a'..='z' | '0'..='9' => true,\n\n ch => !(ch.is_whitespace() || is_special(ch))\n\n }\n\n}\n\n\n\nimpl<'a, 'b> Lexer<'a, 'b> {\n\n pub fn new(file_id: u32, source: &'a str, diag: &'b RefCell<...
Rust
consensus/tree_hash/src/lib.rs
RoBiK75/lighthouse
f9bba92db3468321b28ddd9010e26b359f88bafe
pub mod impls; mod merkle_hasher; mod merkleize_padded; mod merkleize_standard; pub use merkle_hasher::{Error, MerkleHasher}; pub use merkleize_padded::merkleize_padded; pub use merkleize_standard::merkleize_standard; use eth2_hashing::{hash_fixed, ZERO_HASHES, ZERO_HASHES_MAX_INDEX}; pub const BYTES_PER_CHUNK: usiz...
pub mod impls; mod merkle_hasher; mod merkleize_padded; mod merkleize_standard; pub use merkle_hasher::{Error, MerkleHasher}; pub use merkleize_padded::merkleize_padded; pub use merkleize_standard::merkleize_standard; use eth2_hashing::{hash_fixed, ZERO_HASHES, ZERO_HASHES_MAX_INDEX}; pub const BYTES_PER_CHUNK: usiz...
ld never be packed.") } fn tree_hash_packing_factor() -> usize { unreachable!("List should never be packed.") } fn tree_hash_root(&self) -> Vec<u8> { ssz::ssz_encode(self).tree_hash_root() } } }; } #[cfg(test)] mo...
"); hasher .finish() .expect("the number of leaves is adequate for the number of bytes") } } pub fn mix_in_length(root: &Hash256, length: usize) -> Hash256 { let usize_len = std::mem::size_of::<usize>(); let mut length_bytes = [0; BYTES_PER_CHUNK]; length_bytes[0..usize...
random
[]
Rust
src/bezier/path/algorithms/fill_convex.rs
hellow554/flo_curves
8807b446271f0d2212d3f27d86741beeab5abebb
use super::super::super::super::geo::{Coordinate, Coordinate2D}; use super::super::super::{fit_curve, BezierCurve, Curve}; use super::super::BezierPathFactory; use super::fill_settings::FillSettings; use std::f64; use std::ops::Range; #[derive(Clone)] pub struct RayCollision<Coord, Item> where Coord: Coordinate +...
use super::super::super::super::geo::{Coordinate, Coordinate2D}; use super::super::super::{fit_curve, BezierCurve, Curve}; use super::super::BezierPathFactory; use super::fill_settings::FillSettings; use std::f64; use std::ops::Range; #[derive(Clone)] pub struct RayCollision<Coord, Item> where Coord: Coordinate +...
fn perform_ray_cast<Coord, Item, RayList, RayFn>( center: Coord, theta: f64, cast_ray: RayFn, ) -> Option<(RayCollision<Coord, Item>, f64)> where Coord: Coordinate + Coordinate2D, RayList: IntoIterator<Item = RayCollision<Coord, Item>>, RayFn: Fn(Coord, Coord) -> RayList, { let ray_ve...
fn find_nearest_collision<Coord, Item, RayList>( candidates: RayList, center: Coord, ray_vector: Coord, ) -> Option<(RayCollision<Coord, Item>, f64)> where Coord: Coordinate + Coordinate2D, RayList: IntoIterator<Item = RayCollision<Coord, Item>>, { let mut nearest_collision = None; let ...
function_block-full_function
[ { "content": "///\n\n/// Traces the outline of a complex area using ray-casting\n\n///\n\n/// While the convex version of this function can only trace the outline of a region as it can be reached by a single ray, this\n\n/// concave version can trace outlines with edges that are not in 'line of sight' from the ...
Rust
lib/engine/src/screencast.rs
grewn0uille/pyxel
dfaffb8eb9a917ccfe51499d8cef4946dedde823
use std::borrow::Cow; use std::fs::File; use gif::{DisposalMethod, Encoder, Frame, Repeat}; use indexmap::IndexMap; use crate::rectarea::RectArea; use crate::settings::NUM_COLORS; use crate::types::{Color, Rgb8}; use crate::utils::add_file_extension; const TRANSPARENT: Rgb8 = 0xffffffff; struct Screen { image: ...
use std::borrow::Cow; use std::fs::File; use gif::{DisposalMethod, Encoder, Frame, Repeat}; use indexmap::IndexMap; use crate::rectarea::RectArea; use crate::settings::NUM_COLORS; use crate::types::{Color, Rgb8}; use crate::utils::add_file_extension; const TRANSPARENT: Rgb8 = 0xffffffff; struct Screen { image: ...
i16); base_image[y][x] = rgb; diff_line.push(rgb); } } diff_image.push(diff_line); } if min_x > max_x || min_y > max_y { return (RectArea::new(0, 0, 0, 0), Vec::new()); } diff_image = diff_image[...
_image: Vec<Vec<Rgb8>> = Vec::new(); for y in 0..height { let mut diff_line: Vec<Rgb8> = Vec::new(); for x in 0..width { let rgb = new_image[y][x]; if rgb == base_image[y][x] { diff_line.push(TRANSPARENT); } else { ...
function_block-random_span
[ { "content": "pub fn as_u32(x: f64) -> u32 {\n\n x.round() as u32\n\n}\n\n\n", "file_path": "lib/engine/src/utils.rs", "rank": 0, "score": 295428.6314820416 }, { "content": "#[pyfunction]\n\nfn rect(x: f64, y: f64, w: f64, h: f64, col: Color) {\n\n instance().rect(x, y, w, h, col);\n\n...
Rust
src/web/handlers/http/file.rs
sniper365/Clud-Storage
d08480485bd8e77ef862b677019a3309b28c5750
use crate::controllers::file::StoreRequest; use crate::controllers::file::UpdateRequest; use crate::entities::models::{File, Folder, User}; use crate::env::Env; use rocket::data::Data; use rocket::http::{ContentType, Status}; use rocket::request::Form; use rocket::response::Stream; use rocket::response::{Redirect, Resp...
use crate::controllers::file::StoreRequest; use crate::controllers::file::UpdateRequest; use crate::entities::models::{File, Folder, User}; use crate::env::Env; use rocket::data::Data; use rocket::http::{ContentType, Status}; use rocket::request::Form; use rocket::response::Stream; use rocket::response::{Redirect, Resp...
#[derive(Serialize)] pub struct CreateContext { user: User, folder: Folder, } #[get("/folders/<folder_id>/files/create", rank = 1)] pub fn create(auth: Auth, state: State, folder_id: i32) -> impl Responder<'static> { let folder_controller = resolve!(FolderController); let file_controller = resolve!(F...
e.folder_id()) { Ok(folder) => folder, Err(e) => { log!( e.level(), "Request from user \"{}\" returned \"{}\"", user.id(), e ); return Err(Status::from(e)); } }; let context = state.into_...
function_block-function_prefixed
[ { "content": "#[get(\"/folders/<folder_id>\")]\n\npub fn show(auth: Auth, state: State, folder_id: i32) -> impl Responder<'static> {\n\n let file_controller = resolve!(FileController);\n\n let folder_controller = resolve!(FolderController);\n\n let user = auth.user();\n\n\n\n let folder = match fold...
Rust
chapter-70-missiles/src/damage_system.rs
nvoorhies/rustrogueliketutorial
62f1bfaa8ecdca1ef9362ec6f035f4a7905e6f7d
use specs::prelude::*; use super::{Pools, Player, Name, gamelog::GameLog, RunState, Position, InBackpack, Equipped, LootTable}; pub fn delete_the_dead(ecs : &mut World) { let mut dead : Vec<Entity> = Vec::new(); { let combat_stats = ecs.read_storage::<Pools>(); let players = ecs.read_s...
use specs::prelude::*; use super::{Pools, Player, Name, gamelog::GameLog, RunState, Position, InBackpack, Equipped, LootTable}; pub fn delete_the_dead(ecs : &mut World) { let mut dead : Vec<Entity> = Vec::new(); { let combat_stats = ecs.read_storage::<Pools>(); let players = ecs.read_s...
ctim).expect("Unable to delete"); } }
Some(_) => { let mut runstate = ecs.write_resource::<RunState>(); *runstate = RunState::GameOver; } } } } } let mut to_spawn : Vec<(String, Position)> = Vec::new(); { let mut to_drop ...
function_block-random_span
[ { "content": "/// Spawns the player and returns his/her entity object.\n\npub fn player(ecs : &mut World, player_x : i32, player_y : i32) -> Entity {\n\n let mut skills = Skills{ skills: HashMap::new() };\n\n skills.skills.insert(Skill::Melee, 1);\n\n skills.skills.insert(Skill::Defense, 1);\n\n ski...
Rust
src/bin/day4.rs
CrepeGoat/advent-of-code-2021
7edd43bb06f9b62fa26f1185589f0c6348a89be4
use core::str::FromStr; use std::collections::{HashMap, HashSet}; use std::error::Error; use std::io::BufRead; type Matrix<T> = Vec<Vec<T>>; type AnyError = Box<dyn Error>; fn read_input<R: BufRead, T>(reader: R) -> Result<(Vec<T>, Vec<Matrix<T>>), AnyError> where T: std::str::FromStr, <T as std::str::FromStr...
use core::str::FromStr; use std::collections::{HashMap, HashSet}; use std::error::Error; use std::io::BufRead; type Matrix<T> = Vec<Vec<T>>; type AnyError = Box<dyn Error>; fn read_input<R: BufRead, T>(reader: R) -> Result<(Vec<T>, Vec<Matrix<T>>), AnyError> where T: std::str::FromStr, <T as std::str::FromStr...
if row.is_empty() { return Some(item * vals.keys().fold(Default::default(), |sum, &x| x + sum)); } let col = &mut cols[j]; assert!(col.remove(&item)); if col.is_empty() { return Some(item * vals.keys().f...
(vals_lookups, rows_lookups, cols_lookups) }) .collect(); for item in items { for (vals, rows, cols) in board_states.iter_mut() { if let Some((i, j)) = vals.remove(&item) { let row = &mut rows[i]; assert!(row.remove(&item));
random
[ { "content": "pub fn read_input<R: BufRead, const ROW: usize, const COL: usize>(\n\n reader: R,\n\n) -> Result<Grid<u32, ROW, COL>, &'static str> {\n\n reader\n\n .lines()\n\n .map(|r| r.map_err(|_| \"bad line read\"))\n\n .map(|r| -> Result<_, &'static str> {\n\n r.and_the...
Rust
src/schema/entity.rs
oscartbeaumont/sea-orm
2a111f2339232730c4d13bd6028e46324e782927
use crate::{ unpack_table_ref, ColumnTrait, ColumnType, DbBackend, EntityTrait, Identity, Iterable, PrimaryKeyToColumn, PrimaryKeyTrait, RelationTrait, Schema, }; use sea_query::{ extension::postgres::{Type, TypeCreateStatement}, Alias, ColumnDef, ForeignKeyCreateStatement, Iden, Index, TableCreateState...
use crate::{ unpack_table_ref, ColumnTrait, ColumnType, DbBackend, EntityTrait, Identity, Iterable, PrimaryKeyToColumn, PrimaryKeyTrait, RelationTrait, Schema, }; use sea_query::{ extension::postgres::{Type, TypeCreateStatement}, Alias, ColumnDef, ForeignKeyCreateStatement, Iden, Index, TableCreateState...
pub(crate) fn create_table_from_entity<E>(entity: E, backend: DbBackend) -> TableCreateStatement where E: EntityTrait, { let mut stmt = TableCreateStatement::new(); for column in E::Column::iter() { let orm_column_def = column.def(); let col_type: ColumnType = orm_column_def.get_column_ty...
e::Enum(s, v) => (s.as_str(), v), _ => unreachable!(), }; let stmt = Type::create() .as_enum(Alias::new(name)) .values(values.iter().map(|val| Alias::new(val.as_str()))) .to_owned(); vec.push(stmt); } vec }
function_block-function_prefixed
[]
Rust
gpu_renderer/src/generated/virglrenderer.rs
Xiao-Cong-Cong/crosvm
76148ae9828505f449ee015cfe864620027605e3
/* automatically generated by rust-bindgen */ #[link(name = "virglrenderer")] extern "C" {} pub const VIRGL_RENDERER_CALLBACKS_VERSION: u32 = 2; pub const VIRGL_RENDERER_USE_EGL: u32 = 1; pub const VIRGL_RENDERER_THREAD_SYNC: u32 = 2; pub const VIRGL_RENDERER_USE_GLX: u32 = 4; pub const VIRGL_RENDERER_USE_SURFACELESS...
/* automatically generated by rust-bindgen */ #[link(name = "virglrenderer")] extern "C" {} pub const VIRGL_RENDERER_CALLBACKS_VERSION: u32 = 2; pub const VIRGL_RENDERER_USE_EGL: u32 = 1; pub const VIRGL_RENDERER_THREAD_SYNC: u32 = 2; pub const VIRGL_RENDERER_USE_GLX: u32 = 4; pub const VIRGL_RENDERER_USE_SURFACELESS...
enderer_init( cookie: *mut ::std::os::raw::c_void, flags: ::std::os::raw::c_int, cb: *mut virgl_renderer_callbacks, ) -> ::std::os::raw::c_int; } extern "C" { pub fn virgl_renderer_poll(); } extern "C" { pub fn virgl_renderer_get_cursor_data( resource_id: u32, width: ...
"C" fn( cookie: *mut ::std::os::raw::c_void, scanout_idx: ::std::os::raw::c_int, ctx: virgl_renderer_gl_context, ) -> ::std::os::raw::c_int, >, pub get_drm_fd: ::std::option::Option< unsafe extern "C" fn(cookie: *mut ::std::os::raw::c_void) -> ::std::os::raw::...
random
[ { "content": "pub fn property_u32(fdt: &mut Vec<u8>, name: &str, val: u32) -> Result<()> {\n\n property(fdt, name, &cpu_to_fdt32(val))\n\n}\n\n\n", "file_path": "arch/src/fdt.rs", "rank": 0, "score": 337631.9751217404 }, { "content": "/// Copy virtio device configuration data from a subsl...
Rust
src/gpdma1/rawblock.rs
austinglaser/xmc4700
12e1d2b638af5ff0e7088605a4299590a2cd60eb
#[doc = "Reader of register RAWBLOCK"] pub type R = crate::R<u32, super::RAWBLOCK>; #[doc = "Writer for register RAWBLOCK"] pub type W = crate::W<u32, super::RAWBLOCK>; #[doc = "Register RAWBLOCK `reset()`'s with value 0"] impl crate::ResetValue for super::RAWBLOCK { type Type = u32; #[inline(always)] fn re...
#[doc = "Reader of register RAWBLOCK"] pub type R = crate::R<u32, super::RAWBLOCK>; #[doc = "Writer for register RAWBLOCK"] pub type W = crate::W<u32, super::RAWBLOCK>; #[doc = "Register RAWBLOCK `reset()`'s with value 0"] impl crate::ResetValue for super::RAWBLOCK { type Type = u32; #[inline(always)] fn re...
lways)] pub fn bit(self, value: bool) -> &'a mut W { self.w.bits = (self.w.bits & !(0x01 << 3)) | (((value as u32) & 0x01) << 3); self.w } } impl R { #[doc = "Bit 0 - Raw Interrupt Status for channel 0"] #[inline(always)] pub fn ch0(&self) -> CH0_R { CH0_R::new((self.bits & 0...
ld `CH3`"] pub type CH3_R = crate::R<bool, bool>; #[doc = "Write proxy for field `CH3`"] pub struct CH3_W<'a> { w: &'a mut W, } impl<'a> CH3_W<'a> { #[doc = r"Sets the field bit"] #[inline(always)] pub fn set_bit(self) -> &'a mut W { self.bit(true) } #[doc = r"Clears the field bit"] ...
random
[ { "content": "#[doc = \"Reset value of the register\"]\n\n#[doc = \"\"]\n\n#[doc = \"This value is initial value for `write` method.\"]\n\n#[doc = \"It can be also directly writed to register by `reset` method.\"]\n\npub trait ResetValue {\n\n #[doc = \"Register size\"]\n\n type Type;\n\n #[doc = \"Res...
Rust
btree/src/storage.rs
TenStrings/chain-libs
a3fa527aa269b5502c881666babac8db8c66ea11
use memmap::MmapMut; use std::cell::UnsafeCell; use parking_lot::RwLock; use std::cmp::min; use std::collections::HashMap; use std::convert::TryInto; use std::fs::File; use std::io; use std::mem::ManuallyDrop; use std::sync::atomic::{AtomicU64, Ordering}; pub struct MmapStorage { pages: ManuallyDrop<PageTable>, ...
use memmap::MmapMut; use std::cell::UnsafeCell; use parking_lot::RwLock; use std::cmp::min; use std::collections::HashMap; use std::convert::TryInto; use std::fs::File; use std::io; use std::mem::ManuallyDrop; use std::sync::atomic::{AtomicU64, Ordering}; pub struct MmapStorage { pages: ManuallyDrop<PageTable>, ...
+ 1) * self.page_size; unsafe { (&*self.file).set_len(new_size)?; } self.allocated_size.store(new_size, Ordering::Release); self.sync()?; } Ok(()) } pub fn sync(&self) -> Result<(), io::Error> { self.pages.syn...
size as usize) .map_mut(&*self.file) .expect("couldn't mmap page"), ); self.pages.add_page(page_id, page); self.get(location, count) } } } pub unsafe fn get_m...
random
[ { "content": "fn random_blob(rng: &mut impl rand::Rng) -> Box<[u8]> {\n\n let mut buf = vec![0u8; BLOB_SIZE];\n\n rng.fill(&mut buf[..]);\n\n buf.into_boxed_slice()\n\n}\n\n\n", "file_path": "btree/benches/benchmark.rs", "rank": 1, "score": 292788.71773756825 }, { "content": "pub fn...
Rust
aoc-2021/src/day15.rs
felipe-fg/advent-of-code
c1c4f3cfeb801bea811446e055ee9a0211053ed2
use aoc_utils; use rayon::prelude::*; use std::cmp::Ordering; use std::collections::{BinaryHeap, HashMap}; type Cost = usize; type Grid = Vec<Vec<Cost>>; type Axis = isize; type X = Axis; type Y = Axis; type Position = (X, Y); const COST_MAX: Cost = Cost::MAX; const COST_WRAP: Cost = 9; #[derive(Debug, Copy, Clone,...
use aoc_utils; use rayon::prelude::*; use std::cmp::Ordering; use std::collections::{BinaryHeap, HashMap}; type Cost = usize; type Grid = Vec<Vec<Cost>>; type Axis = isize; type X = Axis; type Y = Axis; type Position = (X, Y); const COST_MAX: Cost = Cost::MAX; const COST_WRAP: Cost = 9; #[derive(Debug, Copy, Clone,...
(grid, next); let next_cost = distance.get(&next).map(|&cost| cost).unwrap_or(COST_MAX); if new_next_cost < next_cost { heap.push(State::new(next, new_next_cost)); distance.insert(next, new_next_cost); } } } None } fn get_neighbors(...
let expanded_grid = expand_grid(&grid, 5); let cost = find_lowest_total_cost(&grid).expect("cost"); let cost_expanded = find_lowest_total_cost(&expanded_grid).expect("cost expanded"); println!("{}", cost); println!("{}", cost_expanded); } fn parse_grid(lines: Vec<String>) -> Grid { lines ...
random
[ { "content": "pub fn run() {\n\n let lines: Vec<String> = aoc_utils::read_lines(\"inputs/day16.txt\", true).collect();\n\n\n\n let transmission = parse_transmission(lines);\n\n\n\n let packet = parse_packet(&mut transmission.into_iter());\n\n\n\n let (version, value) = evaluate_packet(&packet);\n\n\...
Rust
api/src/transactions.rs
phlip9/diem
dae6cc57259d552774ae025b88505def85f0f2a2
use crate::{ context::Context, metrics::metrics, page::Page, param::{AddressParam, TransactionIdParam}, }; use diem_api_types::{ mime_types, Error, LedgerInfo, Response, Transaction, TransactionData, TransactionId, TransactionOnChainData, TransactionSigningMessage, UserTransactionRequest, }; ...
use crate::{ context::Context, metrics::metrics, page::Page, param::{AddressParam, TransactionIdParam}, }; use diem_api_types::{ mime_types, Error, LedgerInfo, Response, Transaction, TransactionData, TransactionId, TransactionOnChainData, TransactionSigningMessage, UserTransactionRequest, }; ...
nfo>>> { if version > self.ledger_info.version() { return Ok(None); } Ok(Some( self.context .get_transaction_by_version(version, self.ledger_info.version())? .into(), )) } async fn get_by_hash( &...
> Result<impl Reply, Rejection> { Ok(Transactions::new(context)? .get_transaction(id.parse("transaction hash or version")?) .await?) } pub fn get_transactions( context: Context, ) -> impl Filter<Extract = impl Reply, Error = Rejection> + Clone { warp::path!("transactions") .and(warp...
random
[ { "content": "pub fn routes(context: Context) -> impl Filter<Extract = impl Reply, Error = Rejection> + Clone {\n\n get_events_by_event_key(context.clone()).or(get_events_by_event_handle(context))\n\n}\n\n\n", "file_path": "api/src/events.rs", "rank": 1, "score": 768379.5556486953 }, { "c...
Rust
sigma-tree/src/ergo_tree.rs
robkorn/sigma-rust
3aa25d62a2b6f6b071b5b89607d0688e5509a9a6
use crate::{ ast::{Constant, Expr}, types::SType, }; use io::{Cursor, Read}; use sigma_ser::serializer::SerializationError; use sigma_ser::serializer::SigmaSerializable; use sigma_ser::{peekable_reader::PeekableReader, vlq_encode}; use std::io; use std::rc::Rc; use vlq_encode::{ReadSigmaVlqExt, WriteSigmaVlqEx...
use crate::{ ast::{Constant, Expr}, types::SType, }; use io::{Cursor, Read}; use sigma_ser::serializer::SerializationError; use sigma_ser::serializer::SigmaSerializable; use sigma_ser::{peekable_reader::PeekableReader, vlq_encode}; use std::io; use std::rc::Rc; use vlq_encode::{ReadSigmaVlqExt, WriteSigmaVlqEx...
> ErgoTree { ErgoTree { header: ErgoTree::DEFAULT_HEADER, tree: Ok(ParsedTree { constants: Vec::new(), root: Ok(expr), }), } } pub fn with_segregation(_: Rc<Expr>) -> ErgoTree { todo!() } } impl From<Rc<Expr>>...
TreeParsingError(ErgoTreeConstantsParsingError), RootParsingError(ErgoTreeRootParsingError), } impl ErgoTree { const DEFAULT_HEADER: ErgoTreeHeader = ErgoTreeHeader(0); pub fn proposition(&self) -> Result<Rc<Expr>, ErgoTreeParsingError> { self.tree .clone() .ma...
random
[ { "content": "pub fn serialize_bytes<S, T>(bytes: T, serializer: S) -> Result<S::Ok, S::Error>\n\nwhere\n\n S: Serializer,\n\n T: AsRef<[u8]>,\n\n{\n\n serializer.serialize_str(&base16::encode_lower(bytes.as_ref()))\n\n}\n\n\n\npub mod ergo_tree {\n\n\n\n use super::*;\n\n use crate::ErgoTree;\n\...
Rust
libsplinter/src/registry/diesel/operations/update_node.rs
vaporos/splinter
934e69a2c41b05e050a7a27d35775ab206f97825
use diesel::{ dsl::{delete, insert_into, not, update}, prelude::*, }; use crate::error::InvalidStateError; use crate::registry::{ diesel::{ models::{NodeEndpointsModel, NodeKeysModel, NodeMetadataModel, NodesModel}, schema::{ splinter_nodes, splinter_nodes_endpoints, splinter_...
use diesel::{ dsl::{delete, insert_into, not, update}, prelude::*, }; use crate::error::InvalidStateError; use crate::registry::{ diesel::{ models::{NodeEndpointsModel, NodeKeysModel, NodeMetadataModel, NodesModel}, schema::{ splinter_nodes, splinter_nodes_endpoints, splinter_...
}
update(splinter_nodes::table.find(&node.identity)) .set(splinter_nodes::display_name.eq(&node.display_name)) .execute(self.conn)?; delete( splinter_nodes_endpoints::table .filter(splinter_nodes_endpoint...
function_block-function_prefix_line
[ { "content": "fn to_predicates(filters: Option<Filter>) -> Result<Vec<MetadataPredicate>, String> {\n\n match filters {\n\n Some(filters) => filters\n\n .into_iter()\n\n .map(|(key, (operator, value))| match operator.as_str() {\n\n \"=\" => Ok(MetadataPredicate::Eq...
Rust
tests/it/io/json/write.rs
max-sixty/arrow2
565cfaeb02164bf1be3619f8446dae47bab9f92d
use std::sync::Arc; use arrow2::{ array::*, bitmap::Bitmap, buffer::Buffer, datatypes::{DataType, Field, Schema}, io::json::LineDelimitedWriter, record_batch::RecordBatch, }; #[test] fn write_simple_rows() { let schema = Schema::new(vec![ Field::new("c1", DataType::Int32, false), ...
use std::sync::Arc; use arrow2::{ array::*, bitmap::Bitmap, buffer::Buffer, datatypes::{DataType, Field, Schema}, io::json::LineDelimitedWriter, record_batch::RecordBatch, }; #[test] fn write_simple_rows() { let schema = Schema::new(vec![ Field::new("c1", DataType::Int32, false), ...
fn write_list_of_struct() { let inner = vec![Field::new("c121", DataType::Utf8, false)]; let fields = vec![ Field::new("c11", DataType::Int32, false), Field::new("c12", DataType::Struct(inner.clone()), false), ]; let c1_datatype = DataType::List(Box::new(Field::new( "s", ...
function_block-full_function
[ { "content": "fn case_basics_schema() -> (String, Schema, Vec<Box<dyn Array>>) {\n\n let data = r#\"{\"a\":1, \"b\":2.0, \"c\":false, \"d\":\"4\", \"e\":\"4\"}\n\n {\"a\":10, \"b\":-3.5, \"c\":true, \"d\":null, \"e\":\"text\"}\n\n {\"a\":100000000, \"b\":0.6, \"d\":\"text\"}\"#\n\n .to_string();...
Rust
src/benchmarks/rendering/time_naive_svg_primitive_rendering.rs
simbleau/vgpu-bench
ad827f2c9260237bdafc619ef3d603f01f5f3437
use crate::benchmarks::{ Benchmark, BenchmarkBuilder, BenchmarkData, BenchmarkFn, }; use crate::Result; use crate::{log_assert, util}; use benchmark_macro_derive::BenchmarkData; use erased_serde::Serialize; use log::{debug, info, trace, warn}; use rendering_util::benching::output::NaivePrimitiveRenderTime; use std:...
use crate::benchmarks::{ Benchmark, BenchmarkBuilder, BenchmarkData, BenchmarkFn, }; use crate::Result; use crate::{log_assert, util}; use benchmark_macro_derive::BenchmarkData; use erased_serde::Serialize; use log::{debug, info, trace, warn}; use rendering_util::benching::output::NaivePrimitiveRenderTime; use std:...
}
PathBuf::from(path).is_relative(), "{} is not a relative path", path ); log_assert!( self.csv_output.is_some(), "you cannot save a plot without an output path set" ) } log_assert!(self.backends.len() > 0,...
function_block-function_prefix_line
[ { "content": "pub fn convert_path(p: &usvg::Path) -> PathConvIter {\n\n PathConvIter {\n\n iter: p.data.iter(),\n\n first: Point::new(0.0, 0.0),\n\n prev: Point::new(0.0, 0.0),\n\n deferred: None,\n\n needs_end: false,\n\n }\n\n}\n\n\n", "file_path": "crates/tessella...
Rust
nrf-softdevice/src/ble/types.rs
rise0chen/nrf-softdevice
a7508c0ee43b525d07f075c734ddcf8e60797ae4
use core::mem; use crate::fmt::panic; use crate::raw; use crate::RawError; #[repr(transparent)] #[derive(Copy, Clone)] pub struct Uuid { inner: raw::ble_uuid_t, } impl Uuid { pub const fn from_raw(raw: raw::ble_uuid_t) -> Option<Self> { if raw.type_ == raw::BLE_UUID_TYPE_UNKNOWN as u8 { N...
use core::mem; use crate::fmt::panic; use crate::raw; use crate::RawError; #[repr(transparent)] #[derive(Copy, Clone)] pub struct Uuid { inner: raw::ble_uuid_t, } impl Uuid { pub const fn from_raw(raw: raw::ble_uuid_t) -> Option<Self> { if raw.type_ == raw::BLE_UUID_TYPE_UNKNOWN as u8 { N...
_t { type_: uuid_type, uuid: ((uuid[13] as u16) << 8) | (uuid[12] as u16), }, } } pub unsafe fn as_raw_ptr(&self) -> *const raw::ble_uuid_t { &self.inner as _ } pub fn into_raw(self) -> raw::ble_uuid_t { self.inner } } impl Eq fo...
w::sd_ble_uuid_vs_add(uuid.as_ptr() as _, &mut uuid_type as _) }; match RawError::convert(ret) { Ok(()) => {} Err(e) => panic!("sd_ble_uuid_vs_add err {:?}", e), } Self { inner: raw::ble_uuid
function_block-random_span
[ { "content": "pub fn get_value(_sd: &Softdevice, handle: u16, buf: &mut [u8]) -> Result<usize, GetValueError> {\n\n let mut value = raw::ble_gatts_value_t {\n\n p_value: buf.as_mut_ptr(),\n\n len: buf.len() as _,\n\n offset: 0,\n\n };\n\n let ret = unsafe {\n\n raw::sd_ble_g...
Rust
src/client/subcommand/subcommand_utils.rs
STRONG-MAD/Folden
2a685cdd6d5de64bafe61d87c54a6631ec183be5
use std::{ env, ffi::{OsStr, OsString}, option::Option, path::Path, }; use clap::{App, Arg, ArgMatches, SubCommand}; use cli_table::{self, print_stdout, Cell, CellStruct, Table, TableStruct}; use dyn_clone::DynClone; use generated_types::{ handler_service_client::HandlerServiceClient, HandlerState...
use std::{ env, ffi::{OsStr, OsString}, option::Option, path::Path, }; use clap::{App, Arg, ArgMatches, SubCommand}; use cli_table::{self, print_stdout, Cell, CellStruct, Table, TableStruct}; use dyn_clone::DynClone; use generated_types::{ handler_service_client::HandlerServiceClient, HandlerState...
ler_states( states_map_response: HandlerStatesMapResponse, sub_matches: &ArgMatches, ) { if sub_matches.is_present("simple") { for (dir, state) in states_map_response.states_map { println!( " {} Alive: {} Message: {}", d...
ble() .title(vec![ "Path".cell(), "Description".cell(), "Alive".cell(), "Startup".cell(), ]) } pub fn print_hand
random
[ { "content": "fn is_any_handler_alive(client: &mut HandlerServiceClient<tonic::transport::Channel>) -> bool {\n\n let response = client.get_directory_status(GetDirectoryStatusRequest {\n\n directory_path: String::new(),\n\n });\n\n if let Ok(response) = block_on(response) {\n\n let respon...
Rust
src/graphics/canvas.rs
bsvercl/ggez
b156656fc539b808333a9730142b3a99ed3a3e0d
use gfx::format::Swizzle; use gfx::handle::RawRenderTargetView; use gfx::memory::{Bind, Usage}; use gfx::texture::{AaMode, Kind}; use gfx::Factory; use conf; use context::DebugId; use error::*; use graphics::*; use Context; #[derive(Debug)] pub struct CanvasGeneric<Spec> where Spec: BackendSpec, { target: R...
use gfx::format::Swizzle; use gfx::handle::RawRenderTargetView; use gfx::memory::{Bind, Usage}; use gfx::texture::{AaMode, Kind}; use gfx::Factory; use conf; use context::DebugId; use error::*; use graphics::*; use Context; #[derive(Debug)] pub struct CanvasGeneric<Spec> where Spec: BackendSpec, { target: R...
o_inner(self) -> Image { self.image } } impl Drawable for Canvas { fn draw<D>(&self, ctx: &mut Context, param: D) -> GameResult where D: Into<DrawTransform>, { let param = param.into(); self.debug_id.assert(ctx); let ...
width, height, debug_id, }, debug_id, }) } pub fn with_window_size(ctx: &mut Context) -> GameResult<Canvas> { use graphics; let (w, h) = graphics::get_drawable_size(ctx); Canvas::new(ct...
random
[ { "content": "/// Takes a `conf::Conf` object and saves it to the user directory,\n\n/// overwriting any file already there.\n\npub fn write_config(ctx: &mut Context, conf: &conf::Conf) -> GameResult {\n\n ctx.filesystem.write_config(conf)\n\n}\n\n\n\n#[cfg(test)]\n\nmod tests {\n\n use conf;\n\n use e...
Rust
src/main.rs
DeanBDean/cargo-hdk
ac5e2b2ed94ea5bc985a957b5f499e4b87cdade3
#[macro_use] extern crate anyhow; use std::path::{Path, PathBuf}; use std::process::{Command, Stdio}; use std::{env, fs}; use anyhow::{Context, Result}; use log::*; use structopt::{clap::AppSettings, StructOpt}; use cargo_metadata::{camino::Utf8PathBuf, Message, MetadataCommand, Package}; const ABOUT: &str = " car...
#[macro_use] extern crate anyhow; use std::path::{Path, PathBuf}; use std::process::{Command, Stdio}; use std::{env, fs}; use anyhow::{Context, Result}; use log::*; use structopt::{clap::AppSettings, StructOpt}; use cargo_metadata::{camino::Utf8PathBuf, Message, MetadataCommand, Package}; const ABOUT: &str = " car...
fn cargo_build(opts: &Opt, package: &Package) -> Result<Vec<(String, Utf8PathBuf)>> { info!("Building Rust code using cargo."); let build_args = if opts.build_args.first().map(|x| x.as_str()) == Some("hdk") { &opts.build_args[1..] } else { opts.build_args.as_slice() }; if opts.cl...
pub fn init_logging(level: Option<log::Level>) { if let Some(level) = level { let mut builder = env_logger::Builder::new(); builder.filter(None, level.to_level_filter()); builder.format_timestamp(None).format_module_path(false); builder.init(); } }
function_block-full_function
[ { "content": "#[test]\n\nfn basic_debug_build() {\n\n let mut cmd = Command::cargo_bin(\"cargo-hdk\").unwrap();\n\n cmd.arg(\"--hdk-path\").arg(\"./tests/hdk\").assert().success();\n\n}\n", "file_path": "tests/hdk.rs", "rank": 2, "score": 39163.21798262144 }, { "content": "# `cargo-hdk...
Rust
psst-gui/src/ui/theme.rs
mirth/psst
724aa251407dfa93b8ede8e879fd5ca35de1ddd2
use druid::{Color, Env, FontDescriptor, FontFamily, FontWeight, Insets, Key, Size}; pub use druid::theme::*; use crate::data::{AppState, Theme}; pub fn grid(m: f64) -> f64 { GRID * m } pub const GRID: f64 = 8.0; pub const GREY_000: Key<Color> = Key::new("app.grey_000"); pub const GREY_100: Key<Color> = Key::ne...
use druid::{Color, Env, FontDescriptor, FontFamily, FontWeight, Insets, Key, Size}; pub use druid::theme::*; use crate::data::{AppState, Theme}; pub fn grid(m: f64) -> f64 { GRID * m } pub const GRID: f64 = 8.0; pub const GREY_000: Key<Color> = Key::new("app.grey_000"); pub const GREY_100: Key<Color> = Key::ne...
fn setup_dark_theme(env: &mut Env) { env.set(GREY_000, Color::grey8(0xff)); env.set(GREY_100, Color::grey8(0xf2)); env.set(GREY_200, Color::grey8(0xe0)); env.set(GREY_300, Color::grey8(0xbd)); env.set(GREY_400, Color::grey8(0x82)); env.set(GREY_500, Color::grey8(0x4f)); env.set(GREY_600, C...
env.set(RED, Color::rgba8(0xEB, 0x57, 0x57, 0xFF)); env.set(LINK_HOT_COLOR, Color::rgba(0.0, 0.0, 0.0, 0.06)); env.set(LINK_ACTIVE_COLOR, Color::rgba(0.0, 0.0, 0.0, 0.04)); env.set(LINK_COLD_COLOR, Color::rgba(0.0, 0.0, 0.0, 0.0)); }
function_block-function_prefix_line
[ { "content": "pub fn cover_widget(size: f64) -> impl Widget<Artist> {\n\n let radius = size / 2.0;\n\n RemoteImage::new(placeholder_widget(), move |artist: &Artist, _| {\n\n artist.image(size, size).map(|image| image.url.clone())\n\n })\n\n .fix_size(size, size)\n\n .clip(Circle::new((radi...
Rust
rill-engine/src/actors/connector/actor.rs
danielparks/rillrate
7ef536619248b6333e880e859191a831e60a47cc
pub mod parcel; use crate::actors::engine::RillEngine; use crate::actors::recorder::{Recorder, RecorderLink}; use crate::config::EngineConfig; use crate::tracers::meta::PathTracer; use anyhow::Error; use async_trait::async_trait; use meio::{ ActionHandler, Actor, Context, Eliminated, Id, IdOf, InstantActionHandler...
pub mod parcel; use crate::actors::engine::RillEngine; use crate::actors::recorder::{Recorder, RecorderLink}; use crate::config::EngineConfig; use crate::tracers::meta::PathTracer; use anyhow::Error; use async_trait::async_trait; use meio::{ ActionHandler, Actor, Context, Eliminated, Id, IdOf, InstantActionHandler...
}
Result<(), Error> { let id: Id = id.into(); if let Some(desc) = self.registered.remove(&id) { let path = &desc.path; let link = self.recorders.find_mut(path).and_then(Record::take_link); if link.is_some() { self.path_flow.del(path.to_owned()); ...
function_block-function_prefix_line
[]
Rust
src/day17.rs
RaymondK99/advent-of-code-2019-rs
e166c3ed48bded35b745d3baaa048be6fd1a098b
use crate::int_code::Program; use std::slice::Iter; pub fn part1(input_string: &str) -> String { let mut program = Program::parse(input_string); let map: String = program .run_for_output() .iter() .map(|&b| (b as u8) as char) .collect(); part1_map(&map) } fn part1_map(map: ...
use crate::int_code::Program; use std::slice::Iter; pub fn part1(input_string: &str) -> String { let mut program = Program::parse(input_string); let map: String = program .run_for_output() .iter() .map(|&b| (b as u8) as char) .collect(); part1_map(&map) } fn part1_map(map: ...
for x in 0..map[0].len() { if map[y][x] == b'^' { robot_direction = Direction::Up; robot_position = (x as i32, y as i32); } else if map[y][x] == b'v' { robot_direction = Direction::Down; robot_position = (x as i32, y as i32); ...
tion.0, position.1 - 1), Direction::Right => (position.0 + 1, position.1), Direction::Down => (position.0, position.1 + 1), Direction::Left => (position.0 - 1, position.1), } } fn instruction_for_turning_to(self, target: Direction) -> char { if self.turn_righ...
random
[ { "content": "pub fn get_problem_set(day: u8, part: u8) -> Option<fn(&str) -> String> {\n\n struct Solutions(fn(&str) -> String, fn(&str) -> String);\n\n\n\n let parts: Solutions = match day {\n\n 1 => Solutions(day01::part1, day01::part2),\n\n 2 => Solutions(day02::part1, day02::part2),\n\n...
Rust
livedata/src/main.rs
dizzy21c/easyquantrs
a09abd65b5ad3b1530c58ab3a0fcd202f0853876
use std::collections::HashMap; use serde::{Deserialize, Serialize}; extern crate yaml_rust; extern crate pcre2; use yaml_rust::{YamlLoader, YamlEmitter}; use pcre2::bytes::{Regex}; use std::env; use std::io::prelude::*; use yaml_rust::yaml; use std::error::Error; use std::fs::File; use std::io::BufReader; use std::...
use std::collections::HashMap; use serde::{Deserialize, Serialize}; extern crate yaml_rust; extern crate pcre2; use yaml_rust::{YamlLoader, YamlEmitter}; use pcre2::bytes::{Regex}; use std::env; use std::io::prelude::*; use yaml_rust::yaml; use std::error::Error; use std::fs::File; use std::io::BufReader; use std::...
} s.codes.push(s2[..s2.len() - 1].to_string()); } Ok(s) } fn loop_load_data(codeList:String, sleep: u64) { let mut connection = Connection::insecure_open("amqp://admin:admin@qaeventmq:5672/").unwrap(); let channel = connection.open_channel(None).unwrap(); let exchange...
if i.starts_with("0") || i.starts_with("3") { s2.push_str(format!("sz{},", i).as_str()); } else { s2.push_str(format!("sz{},", i).as_str()); }
if_condition
[ { "content": "fn parse_data(body:String) -> Result<Vec<Realdata>, Box<Error>> {\n\n // let body = res.text().await?;\n\n // println!(\"Body:\\n\\n{}\", body);\n\n let aa = \"12345\";\n\n\n\n let del_null_data = Regex::new(\n\n r#\"(\\w{2}\\d+)=\\\"\\\";\"#).unwrap();\n\n let head = r\"(\\d...
Rust
ledger-tool/src/evm_state.rs
MUKHTARSABTC/velas-chain
f45d6eb4eef34eaa86a18e33254b54f5bd52dfb3
use std::path::{Path, PathBuf}; use anyhow::{ensure, Result}; use clap::{value_t_or_exit, App, AppSettings, Arg, ArgMatches, SubCommand}; use log::*; use solana_clap_utils::ArgConstant; use evm_state::storage::{ inspectors::verifier::{AccountsVerifier, HashVerifier}, inspectors::NoopInspector, walker::Wal...
use std::path::{Path, PathBuf}; use anyhow::{ensure, Result}; use clap::{value_t_or_exit, App, AppSettings, Arg, ArgMatches, SubCommand}; use log::*; use solana_clap_utils::ArgConstant; use evm_state::storage::{ inspectors::verifier::{AccountsVerifier, HashVerifier}, inspectors::NoopInspector, walker::Wal...
pub fn process_evm_state_command(ledger_path: &Path, matches: &ArgMatches<'_>) -> Result<()> { let evm_state_path = ledger_path.join("evm-state"); let storage = Storage::open_persistent(evm_state_path)?; match matches.subcommand() { ("purge", Some(matches)) => { let root = value_t_or_ex...
function_block-full_function
[ { "content": "pub fn data_from_state(state: &State) -> Result<&Data, Error> {\n\n match state {\n\n State::Uninitialized => Err(Error::InvalidStateForOperation),\n\n State::Initialized(data) => Ok(data),\n\n }\n\n}\n", "file_path": "client/src/nonce_utils.rs", "rank": 0, "score":...
Rust
diem/language/move-core/types/src/identifier.rs
LeeMaster/phala-blockchain
0cefd3da2ac6e4dc7e9d5e42f2eeaec384705c1c
use anyhow::{bail, Result}; #[cfg(any(test, feature = "fuzzing"))] use proptest::prelude::*; use ref_cast::RefCast; use serde::{Deserialize, Serialize}; use std::{borrow::Borrow, fmt, ops::Deref, borrow::ToOwned, vec::Vec, string::String, boxed::Box}; pub fn is_valid_identifier_char(c: char) -> bool { matches!(c...
use anyhow::{bail, Result}; #[cfg(any(test, feature = "fuzzing"))] use proptest::prelude::*; use ref_cast::RefCast; use serde::{Deserialize, Serialize}; use std::{borrow::Borrow, fmt, ops::Deref, borrow::ToOwned, vec::Vec, string::String, boxed::Box}; pub fn is_valid_identifier_char(c: char) -> bool { matches!(c...
#[cfg(any(test, feature = "fuzzing"))] #[allow(dead_code)] pub(crate) static ALLOWED_IDENTIFIERS: &str = r"(?:[a-zA-Z][a-zA-Z0-9_]*)|(?:_[a-zA-Z0-9_]+)|(?:<SELF>)"; #[cfg(any(test, feature = "fuzzing"))] pub(crate) static ALLOWED_NO_SELF_IDENTIFIERS: &str = r"(?:[a-zA-Z][a-zA-Z0-9_]*)|(?:_[a-zA-Z0-9_]+)"; #[...
fn is_valid(s: &str) -> bool { if s == "<SELF>" { return true; } let len = s.len(); let mut chars = s.chars(); match chars.next() { Some('a'..='z') | Some('A'..='Z') => chars.all(is_valid_identifier_char), Some('_') if len > 1 => chars.all(is_valid_identifier_char), _...
function_block-full_function
[ { "content": "// Like mozilla::pkix, we accept the nonconformant explicit encoding of\n\n// the default value (false) for compatibility with real-world certificates.\n\npub fn optional_boolean(input: &mut untrusted::Reader) -> Result<bool, Error> {\n\n if !input.peek(Tag::Boolean.into()) {\n\n return ...
Rust
oapi_derive/src/check.rs
basiliqio/oapi
82661dd0c57c31b8b6c8d959e2d47d2d4ba7b687
extern crate proc_macro; use crate::utils::include_extern_crate; use proc_macro2::{Group, Span, TokenStream, TokenTree}; use proc_macro_error::abort; use quote::quote; use syn::spanned::Spanned; use synstructure::BindStyle; fn find_attr(attrs: &[syn::Attribute]) -> Option<syn::MetaList> { let mut handler = None; ...
extern crate proc_macro; use crate::utils::include_extern_crate; use proc_macro2::{Group, Span, TokenStream, TokenTree}; use proc_macro_error::abort; use quote::quote; use syn::spanned::Spanned; use synstructure::BindStyle;
fn respan(stream: TokenStream, span: Span) -> TokenStream { stream .into_iter() .map(|token| respan_token(token, span)) .collect() } fn respan_token(mut token: TokenTree, span: Span) -> TokenTree { if let TokenTree::Group(g) = &mut token { *g = Group::new(g.delimiter(), respan...
fn find_attr(attrs: &[syn::Attribute]) -> Option<syn::MetaList> { let mut handler = None; for attr in attrs { if let Ok(meta) = attr.parse_meta() { if meta .path() .get_ident() .map_or(false, |ident| ident == "oapi") { ...
function_block-full_function
[ { "content": "pub fn include_extern_crate(name: &str, new_name: &str) -> proc_macro2::TokenStream {\n\n let new_crate_name = syn::Ident::new(new_name, proc_macro2::Span::call_site());\n\n let crate_name = syn::Ident::new(name, proc_macro2::Span::call_site());\n\n quote! {\n\n extern crate #new_c...
Rust
src/librustdoc/visit_ast.rs
vrana/rust
6539cb417f4a7c2d9d1afce44c196578d2b67f38
use std::collections::HashSet; use syntax::abi; use syntax::ast; use syntax::ast_util; use syntax::ast_map; use syntax::attr; use syntax::attr::AttrMetaMethods; use syntax::codemap::Span; use syntax::ptr::P; use rustc::middle::stability; use core; use doctree::*; pub struct RustdocVisitor<'a, 'tcx: 'a> { pub ...
use std::collections::HashSet; use syntax::abi; use syntax::ast; use syntax::ast_util; use syntax::ast_map; use syntax::attr; use syntax::attr::AttrMetaMethods; use syntax::codemap::Span; use syntax::ptr::P; use rustc::middle::stability; use core; use doctree::*; pub struct RustdocVisitor<'a, 'tcx: 'a> { pub ...
items: items.clone(), attrs: item.attrs.clone(), id: item.id, whence: item.span, vis: item.vis, stab: self.stability(item.id), }; om.impls.push(i); }, ...
b.iter().map(|x| (*x).clone()).collect(), id: item.id, attrs: item.attrs.clone(), whence: item.span, vis: item.vis, stab: self.stability(item.id), }; om.traits.push(t); }, ...
function_block-random_span
[ { "content": "pub fn node_id_to_trait_ref<'tcx>(cx: &ctxt<'tcx>, id: ast::NodeId)\n\n -> Rc<ty::TraitRef<'tcx>> {\n\n match cx.trait_refs.borrow().get(&id) {\n\n Some(ty) => ty.clone(),\n\n None => cx.sess.bug(\n\n format!(\"node_id_to_trait_ref: no t...
Rust
derive/src/lib.rs
cstorey/weft
49eb0d91455d0285288bcf7805785e3fd9d7ef3c
#![allow(clippy::large_enum_variant)] /*! # `weft-derive`. This module provides compiler support for creating `weft` templates. See the `weft` module for usage. */ extern crate proc_macro; use log::*; use syn::Token; mod derive_renderable; mod inline_parse; use crate::derive_renderable::*; use anyhow::{anyhow, bail...
#![allow(clippy::large_enum_variant)] /*! # `weft-derive`. This module provides compiler support for creating `weft` templates. See the `weft` module for usage. */ extern crate proc_macro; use log::*; use syn::Token; mod derive_renderable; mod inline_parse; use crate::derive_renderable::*; use anyhow::{anyhow, bail...
; } #[test] fn will_extract_selector() { let deriv = parse_quote!( #[template(path = "hello.html", selector = "#hello-world")] struct X; ); let conf = TemplateDerivation::from_derive(&deriv).expect("parse derive"); assert_eq!(conf.selector, "#hello-...
derive_template( quote!( #[template(source = "<p>foo</p><p>bar</p>", selector = "p")] struct MultipleRoots; ) .into(), )
call_expression
[ { "content": "#[bench]\n\npub fn teams(b: &mut test::Bencher) {\n\n let teams = Teams {\n\n year: 2015,\n\n teams: vec![\n\n Team {\n\n name: \"Jiangsu\".into(),\n\n score: 43,\n\n },\n\n Team {\n\n name: \"Beijing\"....
Rust
src/fs/mod.rs
panhania/rrg
8ad6171882860b04e2645c127223c7638a7e9a87
use std::fs::Metadata; use std::path::{Path, PathBuf}; use log::warn; #[cfg(target_os = "linux")] pub mod linux; #[cfg(target_family = "unix")] pub mod unix; pub struct Entry { pub path: PathBuf, pub metadata: Metadata, } pub fn walk_dir<P: AsRef<Path>>(root: P) -> std::io::Result<WalkDir> { ...
use std::fs::Metadata; use std::path::{Path, PathBuf}; use log::warn; #[cfg(target_os = "linux")] pub mod linux; #[cfg(target_family = "unix")] pub mod unix; pub struct Entry { pub path: PathBuf, pub metadata: Metadata, } pub fn walk_dir<P: AsRef<Path>>(root: P) -> std::io::Result<WalkDir> { ...
sults = walk_dir(&tempdir).unwrap().collect::<Vec<_>>(); results.sort_by_key(|entry| entry.path.clone()); assert_eq!(results.len(), 3); assert_eq!(results[0].path, tempdir.path()); assert!(results[0].metadata.file_type().is_dir()); assert_eq!(results[1].path, dir); ass...
std::fs::create_dir(tempdir.path().join("abc")).unwrap(); std::fs::create_dir(tempdir.path().join("abc").join("def")).unwrap(); let mut results = walk_dir(&tempdir).unwrap().collect::<Vec<_>>(); results.sort_by_key(|entry| entry.path.clone()); assert_eq!(results.len(), 3); ...
random
[ { "content": "// TODO: Document behaviour for symlinks.\n\n/// Collects extended flags of the specified file.\n\n///\n\n/// The returned mask represents file attributes specific to the Linux extended\n\n/// file system. Normally, they can be inspected using the `lsattr` command and\n\n/// can be set through the...
Rust
aptos-move/e2e-tests/src/common_transactions.rs
CapCap/aptos-core
d1874e341927ed6ffefd1c8995b500fa762ccb4c
use crate::account::Account; use aptos_transaction_builder::stdlib::encode_peer_to_peer_by_signers_script_function; use aptos_types::{ account_config, transaction::{ RawTransaction, Script, SignedTransaction, TransactionArgument, TransactionPayload, }, }; use diem_framework_releases::legacy::trans...
use crate::account::Account; use aptos_transaction_builder::stdlib::encode_peer_to_peer_by_signers_script_function; use aptos_types::{ account_config, transaction::{ RawTransaction, Script, SignedTransaction, TransactionArgument, TransactionPayload, }, }; use diem_framework_releases::legacy::trans...
sender .transaction() .script(Script::new( LegacyStdlibScript::PeerToPeerWithMetadata .compiled_bytes() .into_vec(), vec![account_config::xus_tag()], args, )) .sequence_number(seq_num) .sign() } pub f...
let args: Vec<TransactionArgument> = vec![ TransactionArgument::Address(*receiver.address()), TransactionArgument::U64(transfer_amount), TransactionArgument::U8Vector(vec![]), TransactionArgument::U8Vector(vec![]), ];
assignment_statement
[ { "content": "pub fn encode_mint_transaction(sender: AccountAddress, amount: u64) -> Transaction {\n\n encode_transaction(sender, encode_mint_program(amount))\n\n}\n\n\n", "file_path": "execution/executor/src/mock_vm/mod.rs", "rank": 0, "score": 596403.501623079 }, { "content": "/// Mint ...
Rust
freertos-rust/src/mutex.rs
vgao1996/FreeRTOS-rust
c8480654e2b1060a42f5edc25bd878836ecdc433
use crate::prelude::v1::*; use crate::base::*; use crate::units::*; use crate::shim::*; pub type Mutex<T> = MutexImpl<T, MutexNormal>; pub type RecursiveMutex<T> = MutexImpl<T, MutexRecursive>; unsafe impl<T: Sync + Send, M> Send for MutexImpl<T, M> {} unsafe impl<T: Sync + Send, M> Sync for MutexImpl<T, M> {} pub ...
use crate::prelude::v1::*; use crate::base::*; use crate::units::*; use crate::shim::*; pub type Mutex<T> = MutexImpl<T, MutexNormal>; pub type RecursiveMutex<T> = MutexImpl<T, MutexRecursive>; unsafe impl<T: Sync + Send, M> Send for MutexImpl<T, M> {} unsafe impl<T: Sync + Send, M> Sync for MutexImpl<T, M> {} pub ...
lf.mutex.take(max_wait)?; Ok(MutexGuard { __mutex: &self.mutex, __data: &self.data, }) } pub fn into_inner(self) -> T { unsafe { let (mutex, data) = { let Self { ref mutex, ref data } = self; (pt...
exInnerImpl + fmt::Debug { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { write!(f, "Mutex address: {:?}", self.mutex) } } impl<T> MutexImpl<T, MutexNormal> { pub fn new(t: T) -> Result<Self, FreeRtosError> { Ok(MutexImpl { mutex: MutexNormal::create()?, ...
random
[ { "content": "struct SubscriberInner<T: Sized + Copy> {\n\n id: usize,\n\n queue: Queue<T>,\n\n publisher: Arc<Mutex<PublisherInner<T>>>,\n\n}\n", "file_path": "freertos-rust/src/patterns/pub_sub.rs", "rank": 1, "score": 199322.45594795828 }, { "content": "struct PublisherInner<T: S...
Rust
examples/ex06-astar-mouse.rs
felix-clark/rltk_rs
968302d26099ea95bf30ccff076feb80084283a8
#![warn(clippy::pedantic)] rltk::add_wasm_support!(); use rltk::prelude::*; extern crate rand; use crate::rand::Rng; #[derive(PartialEq, Copy, Clone)] enum TileType { Wall, Floor, } #[derive(PartialEq, Copy, Clone)] enum Mode { Waiting, Moving, } struct State { map: Vec<TileType>, player_po...
#![warn(clippy::pedantic)] rltk::add_wasm_support!(); use rltk::prelude::*; extern crate rand; use crate::rand::Rng; #[derive(PartialEq, Copy, Clone)] enum TileType { Wall, Floor, } #[derive(PartialEq, Copy, Clone)] enum Mode { Waiting, Moving, } struct State { map: Vec<TileType>, player_po...
} impl BaseMap for State { fn is_opaque(&self, idx: usize) -> bool { self.map[idx] == TileType::Wall } fn get_available_exits(&self, idx: usize) -> Vec<(usize, f32)> { let mut exits: Vec<(usize, f32)> = Vec::new(); let x = (idx % 80) as i32; let y = (idx / 80) as i32; ...
9 { x = 0; y += 1; } } if self.mode == Mode::Waiting { let mouse_pos = ctx.mouse_pos(); let mouse_idx = self.point2d_to_index(Point::new(mouse_pos.0, mouse_pos.1)); draw_batch.print_color(...
function_block-function_prefixed
[ { "content": "pub fn idx_xy(idx: usize) -> (i32, i32) {\n\n (idx as i32 % WIDTH, idx as i32 / WIDTH)\n\n}\n\n\n\nimpl State {\n\n pub fn new() -> State {\n\n // Same as example 3, but we've added the visible tiles\n\n let mut state = State {\n\n map: vec![TileType::Floor; (WIDTH *...
Rust
src/ensemble/random_forest_classifier.rs
vadimzaliva/smartcore
6602de0d51d9aa66778e4a89a6e92b14ecbddcd6
extern crate rand; use std::default::Default; use std::fmt::Debug; use rand::Rng; use serde::{Deserialize, Serialize}; use crate::error::Failed; use crate::linalg::Matrix; use crate::math::num::RealNumber; use crate::tree::decision_tree_classifier::{ which_max, DecisionTreeClassifier, DecisionTreeClassifierPar...
extern crate rand; use std::default::Default; use std::fmt::Debug; use rand::Rng; use serde::{Deserialize, Serialize}; use crate::error::Failed; use crate::linalg::Matrix; use crate::math::num::RealNumber; use crate::tree::decision_tree_classifier::{ which_max, DecisionTreeClassifier, DecisionTreeClassifierPar...
pub fn predict<M: Matrix<T>>(&self, x: &M) -> Result<M::RowVector, Failed> { let mut result = M::zeros(1, x.shape().0); let (n, _) = x.shape(); for i in 0..n { result.set(0, i, self.classes[self.predict_for_row(x, i)]); } Ok(result.to_row_vector()) ...
T>>( x: &M, y: &M::RowVector, parameters: RandomForestClassifierParameters, ) -> Result<RandomForestClassifier<T>, Failed> { let (_, num_attributes) = x.shape(); let y_m = M::from_row_vector(y.clone()); let (_, y_ncols) = y_m.shape(); let mut yi: Vec<usize> = ...
function_block-function_prefixed
[ { "content": "fn impurity<T: RealNumber>(criterion: &SplitCriterion, count: &Vec<usize>, n: usize) -> T {\n\n let mut impurity = T::zero();\n\n\n\n match criterion {\n\n SplitCriterion::Gini => {\n\n impurity = T::one();\n\n for i in 0..count.len() {\n\n if coun...
Rust
src/app/sgf/sgf_inst.rs
hasebems/Musical_Sound_Generator_Framework_in_Rust
ca874a44835d2e6153dd4224348c0e5b7585ba7e
use std::rc::Rc; use std::cell::Cell; use crate::msgf_if; use crate::core::*; use crate::core::msgf_voice::*; use crate::app::sgf::*; use crate::app::sgf::sgf_voice; struct NoteSgf { note: u8, _vel: u8, off: bool, } pub struct InstSgf { vce_audio: msgf_afrm::AudioFrame, inst_audio: msgf_afrm::Au...
use std::rc::Rc; use std::cell::Cell; use crate::msgf_if; use crate::core::*; use crate::core::msgf_voice::*; use crate::app::sgf::*; use crate::app::sgf::sgf_voice; struct NoteSgf { note: u8, _vel: u8, off: bool, } pub struct InstSgf { vce_audio: msgf_afrm::AudioFrame, inst_audio: msgf_afrm::Au...
fn note_on(&mut self, dt2: u8, dt3: u8) { if let Some(cur_vce) = &mut self.vce { cur_vce.slide(dt2, dt3); } else { let mut new_vce = Box::new( sgf_voice::VoiceSgf::new(dt2, dt3, self.mdlt, self.pit, self.vol, self.exp, Rc::clone(&...
fn note_off(&mut self, dt2: u8, _dt3: u8) { let nt_idx = self.search_note(dt2); if nt_idx == NO_NOTE {return} if nt_idx == self.active_vce_index { if let Some(cur_vce) = &mut self.vce { cur_vce.note_off(); } self.vcevec[nt_idx as u...
function_block-full_function
[ { "content": "pub fn get_inst(inst_number:usize, vol:u8, pan:u8, exp:u8) -> Box<dyn msgf_inst::Inst> {\n\n if inst_number < 8 {\n\n println!(\"Changed Va: {}\",inst_number);\n\n Box::new(va_inst::InstVa::new(inst_number,vol,pan,exp))\n\n }\n\n else if inst_number == 8 {\n\n println...
Rust
tests/tests.rs
tmfink/wana_kana_rust
22e94dc05ee46ef46cf2d1fec95b4fa9d85e7f5c
#![feature(test)] #![feature(non_ascii_idents)] #[cfg(test)] extern crate test; extern crate wana_kana; #[cfg(test)] extern crate speculate; #[cfg(test)] use speculate::speculate; use wana_kana::to_hiragana::*; use wana_kana::to_kana; use wana_kana::to_kana::*; use wana_kana::to_katakana::*; use wana_kana::to_roma...
#![feature(test)] #![feature(non_ascii_idents)] #[cfg(test)] extern crate test; extern crate wana_kana; #[cfg(test)] extern crate speculate; #[cfg(test)] use speculate::speculate; use wana_kana::to_hiragana::*; use wana_kana::to_kana; use wana_kana::to_kana::*; use wana_kana::to_katakana::*; use wana_kana::to_roma...
-> k 2" { assert_eq!(to_katakana("テスーと"), "テスート"); } it "Preserves long dash from mixed -> h 1" { assert_eq!(to_hiragana("てすート"), "てすーと"); } it "Preserves long dash from mixed -> h 2" { assert_eq!(to_hiragana("てすー戸"), "てすー戸"); } it "Preserves...
A_KATA.iter() { let lower = to_kana(romaji); let upper = to_kana(&romaji.to_uppercase()); assert_eq!(lower, hiragana); assert_eq!(upper, katakana); } } it "to_hiragana()" { for &[romaji, hiragana, _katakana] in ROMA...
random
[ { "content": "pub fn is_kana_as_symbol(char: char) -> bool {\n\n 'ヶ' == char || 'ヵ' == char\n\n}\n\n\n\nlazy_static! {\n\n pub static ref LONG_VOWELS: FnvHashMap<char, char> = hashmap! {\n\n 'a' => 'あ',\n\n 'i' => 'い',\n\n 'u' => 'う',\n\n 'e' => 'え',\n\n 'o' => 'う',\n\n ...
Rust
src/headless.rs
stevebob/glutin
cff7a88d051c972e2b78957443bef5e45149c18a
use Api; use ContextError; use CreationError; use GlAttributes; use GlProfile; use GlRequest; use GlContext; use PixelFormat; use PixelFormatRequirements; use Robustness; use platform; #[derive(Clone)] pub struct HeadlessRendererBuilder<'a> { pub dimensions: (u32, u32), pub opengl: GlAttributes<&'a...
use Api; use ContextError; use CreationError; use GlAttributes; use GlProfile; use GlRequest; use GlContext; use PixelFormat; use PixelFormatRequirements; use Robustness; use platform; #[derive(Clone)] pub struct HeadlessRendererBuilder<'a> { pub dimensions: (u32, u32), pub opengl: GlAttributes<&'a...
self.context.get_pixel_format() } }
&self.platform_specific) .map(|w| HeadlessContext { context: w }) } #[inline] pub fn build_strict(self) -> Result<HeadlessContext, CreationError> { self.build() } } pub struct HeadlessContext { context: platform::HeadlessContext, } impl HeadlessCon...
random
[ { "content": "pub fn create_delegate_class() {\n\n extern fn did_finish_launching(this: &mut Object, _: Sel, _: id, _: id) -> BOOL {\n\n unsafe {\n\n let main_screen: id = msg_send![Class::get(\"UIScreen\").unwrap(), mainScreen];\n\n let bounds: CGRect = msg_send![main_screen, bo...
Rust
egui_demo_lib/src/apps/demo/paint_bezier.rs
greym0uth/egui
89d19860b820a577f159a61aba7acfb483ff4c9c
use egui::epaint::{CubicBezierShape, PathShape, QuadraticBezierShape}; use egui::*; #[cfg_attr(feature = "serde", derive(serde::Deserialize, serde::Serialize))] #[cfg_attr(feature = "serde", serde(default))] pub struct PaintBezier { degree: usize, control_points: [Pos2; 4], stroke: Stroke, ...
use egui::epaint::{CubicBezierShape, PathShape, QuadraticBezierShape}; use egui::*; #[cfg_attr(feature = "serde", derive(serde::Deserialize, serde::Serialize))] #[cfg_attr(feature = "serde", serde(default))] pub struct PaintBezier { degree: usize, control_points: [Pos2; 4], stroke: Stroke, ...
}
fn ui(&mut self, ui: &mut Ui) { ui.vertical_centered(|ui| { ui.add(crate::__egui_github_link_file!()); }); self.ui_control(ui); Frame::dark_canvas(ui.style()).show(ui, |ui| { self.ui_content(ui); }); }
function_block-full_function
[ { "content": "fn color_button(ui: &mut Ui, color: Color32, open: bool) -> Response {\n\n let size = ui.spacing().interact_size;\n\n let (rect, response) = ui.allocate_exact_size(size, Sense::click());\n\n response.widget_info(|| WidgetInfo::new(WidgetType::ColorButton));\n\n\n\n if ui.is_rect_visibl...
Rust
iml-util/util.rs
beevans/integrated-manager-for-lustre
6b7e49b8a58058e6139ad815a4388f21a581dfa0
pub trait Pick<A, B> { fn fst(self) -> A; fn snd(self) -> B; } impl<A, B> Pick<A, B> for (A, B) { fn fst(self) -> A { self.0 } fn snd(self) -> B { self.1 } } impl<A, B, C> Pick<A, B> for (A, B, C) { fn fst(self) -> A { self.0 } fn snd(self) -> B { ...
pub trait Pick<A, B> { fn fst(self) -> A; fn snd(self) -> B; } impl<A, B> Pick<A, B> for (A, B) { fn fst(self) -> A { self.0 } fn snd(self) -> B { self.1 } } impl<A, B, C> Pick<A, B> for (A, B, C) { fn fst(self) -> A { self.0 } fn snd(self) -> B { ...
Ok(x) } } pub mod action_plugins { use futures::{Future, FutureExt}; use iml_wire_types::{ActionName, ToJsonValue}; use std::{collections::HashMap, fmt::Display, pin::Pin}; type BoxedFuture = Pin<Box<dyn Future<Output = Result<serde_json::value::Value, String>> + Send>>; ...
let x: Box<dyn Incoming> = match env::var(port_var) { Ok(port) => Box::new(get_tcp_stream(&port).await?), Err(_) => Box::new(get_unix_stream()?), };
assignment_statement
[ { "content": "/// Convert a given host and port to a `SocketAddr` or panic\n\nfn to_socket_addr(host: &str, port: &str) -> SocketAddr {\n\n let raw_addr = format!(\"{}:{}\", host, port);\n\n\n\n let mut addrs_iter = raw_addr.to_socket_addrs().unwrap_or_else(|_| {\n\n panic!(\n\n \"Addres...
Rust
bin/naga.rs
Imberflur/naga
3a0f0144112ff621dd7f731bf455adf6cab19164
#![allow(clippy::manual_strip)] #[allow(unused_imports)] use std::fs; use std::{env, error::Error, path::Path}; #[derive(Default)] struct Parameters { #[cfg(feature = "spv-in")] spv_adjust_coordinate_space: bool, #[cfg(feature = "spv-in")] spv_flow_dump_prefix: Option<String>, #[cfg(feature = "spv-...
#![allow(clippy::manual_strip)] #[allow(unused_imports)] use std::fs; use std::{env, error::Error, path::Path}; #[derive(Default)] struct Parameters { #[cfg(feature = "spv-in")] spv_adjust_coordinate_space: bool, #[cfg(feature = "spv-in")] spv_flow_dump_prefix: Option<String>, #[cfg(feature = "spv-...
wrap(); fs::write(output_path, buffer).unwrap(); } #[cfg(feature = "dot-out")] "dot" => { use naga::back::dot; let output = dot::write(&module, info.as_ref()).unwrap(); fs::write(output_path, output).unwrap(); } #[cfg(feature = "hls...
"frag" => naga::ShaderStage::Fragment, "comp" => naga::ShaderStage::Compute, _ => unreachable!(), }; let mut buffer = String::new(); let mut writer = glsl::Writer::new(&mut buffer, &module, info.as_ref().unwrap(), &params.gl...
random
[ { "content": "pub fn write(module: &crate::Module, mod_info: Option<&ModuleInfo>) -> Result<String, FmtError> {\n\n use std::fmt::Write as _;\n\n\n\n let mut output = String::new();\n\n output += \"digraph Module {\\n\";\n\n\n\n writeln!(output, \"\\tsubgraph cluster_globals {{\")?;\n\n writeln!(...
Rust
rs/registry/canister/tests/remove_node.rs
ORIGYN-SA/ic
779549eccfcf61ac702dfc2ee6d76ffdc2db1f7f
use dfn_candid::candid; use ic_base_types::{PrincipalId, SubnetId}; use ic_canister_client::Sender; use ic_crypto::utils::get_node_keys_or_generate_if_missing; use ic_nns_constants::ids::{TEST_NEURON_1_OWNER_KEYPAIR, TEST_NEURON_1_OWNER_PRINCIPAL}; use ic_nns_test_utils::{ itest_helpers::{local_test_on_nns_subnet,...
use dfn_candid::candid; use ic_base_types::{PrincipalId, SubnetId}; use ic_canister_client::Sender; use ic_crypto::utils::get_node_keys_or_generate_if_missing; use ic_nns_constants::ids::{TEST_NEURON_1_OWNER_KEYPAIR, TEST_NEURON_1_OWNER_PRINCIPAL}; use ic_nns_test_utils::{ itest_helpers::{local_test_on_nns_subnet,...
fn init_mutation(node_record: &NodeRecord) -> (NodeId, RegistryAtomicMutateRequest) { let temp_dir = temp_dir(); let (_, node_id) = get_node_keys_or_generate_if_missing(temp_dir.path()); ( node_id, RegistryAtomicMutateRequest { mutations: vec![ ...
fn node_cannot_be_removed_if_in_subnet() { local_test_on_nns_subnet(|runtime| async move { let test_node_record = NodeRecord { node_operator_id: (*TEST_NEURON_1_OWNER_PRINCIPAL).to_vec(), xnet: Some(connection_endpoint_from_string( &("128.0.0.1:1234".to_string()), ...
function_block-full_function
[ { "content": "fn init_mutation_with_node_allowance(node_allowance: u64) -> RegistryAtomicMutateRequest {\n\n let node_operator_record = NodeOperatorRecord {\n\n node_operator_principal_id: TEST_NEURON_1_OWNER_PRINCIPAL.to_vec(),\n\n node_allowance,\n\n // This doesn't go through Governan...
Rust
edgelet/edgelet-http/src/route/regex.rs
darobs/iotedge-k8s
56819518ad8119e3aebd2e25f23e305f6e80dc95
use std::borrow::Cow; use std::collections::HashMap; use std::default::Default; use http::{Method, StatusCode}; use percent_encoding::percent_decode; use regex::Regex; use super::{Builder, Handler, HandlerParamsPair, Recognizer}; pub trait IntoCaptures { fn into_captures(self) -> Vec<(Option<String>, String)>;...
use std::borrow::Cow; use std::collections::HashMap; use std::default::Default; use http::{Method, StatusCode}; use percent_encoding::percent_decode; use regex::Regex; use super::{Builder, Handler, HandlerParamsPair, Recognizer}; pub trait IntoCaptures { fn into_captures(self) -> Vec<(Option<String>, String)>;...
} impl IntoCaptures for Vec<(Option<String>, String)> { fn into_captures(self) -> Self { self } } impl<'a> IntoCaptures for (&'a str, &'a str) { fn into_captures(self) -> Vec<(Option<String>, String)> { vec![(Some(self.0.to_string()), self.1.to_string())] } } impl Default for Paramet...
pub fn name(&self, k: &str) -> Option<&str> { for capture in &self.captures { if let (Some(ref key), ref val) = *capture { if key == k { return Some(val); } } } None }
function_block-full_function
[ { "content": "pub trait Recognizer {\n\n type Parameters: 'static;\n\n\n\n fn recognize(\n\n &self,\n\n method: &Method,\n\n path: &str,\n\n ) -> Result<HandlerParamsPair<Self::Parameters>, StatusCode>;\n\n}\n\n\n", "file_path": "edgelet/edgelet-http/src/route/mod.rs", "ran...
Rust
clippy_lints/src/atomic_ordering.rs
rkuhn/rust-clippy
7907abea272bbf97812683ce03a1ab9c22f0557b
use crate::utils::{match_def_path, span_lint_and_help}; use if_chain::if_chain; use rustc_hir::def_id::DefId; use rustc_hir::{Expr, ExprKind}; use rustc_lint::{LateContext, LateLintPass}; use rustc_middle::ty; use rustc_session::{declare_lint_pass, declare_tool_lint}; declare_clippy_lint! { ...
use crate::utils::{match_def_path, span_lint_and_help}; use if_chain::if_chain; use rustc_hir::def_id::DefId; use rustc_hir::{Expr, ExprKind}; use rustc_lint::{LateContext, LateLintPass}; use rustc_middle::ty; use rustc_session::{declare_lint_pass, declare_tool_lint}; declare_clippy_lint! { ...
g modes `Release`, `SeqCst` or `Relaxed`" ); } } } } fn check_memory_fence(cx: &LateContext<'_, '_>, expr: &Expr<'_>) { if_chain! { if let ExprKind::Call(ref func, ref args) = expr.kind; if let ExprKind::Path(ref func_qpath) = func.kind; if let Some(d...
lse if method == "store" && match_ordering_def_path(cx, ordering_def_id, &["Acquire", "AcqRel"]) { span_lint_and_help( cx, INVALID_ATOMIC_ORDERING, ordering_arg.span, "atomic stores cannot have `Acquire` and ...
function_block-random_span
[ { "content": "/// Checks if the method call given in `expr` belongs to the given trait.\n\npub fn match_trait_method(cx: &LateContext<'_, '_>, expr: &Expr<'_>, path: &[&str]) -> bool {\n\n let def_id = cx.tables.type_dependent_def_id(expr.hir_id).unwrap();\n\n let trt_id = cx.tcx.trait_of_item(def_id);\n\...
Rust
crates/nu-command/tests/commands/source.rs
m-rutter/nushell
4965f4cbf44411503543cbe3688746b4c6482081
use nu_test_support::fs::{AbsolutePath, DisplayPath, Stub::FileWithContent}; use nu_test_support::nu; use nu_test_support::pipeline; use nu_test_support::playground::Playground; #[should_panic] #[test] fn sources_also_files_under_custom_lib_dirs_path() { Playground::setup("source_test_1", |dirs, nu| { let ...
use nu_test_support::fs::{AbsolutePath, DisplayPath, Stub::FileWithContent}; use nu_test_support::nu; use nu_test_support::pipeline; use nu_test_support::playground::Playground; #[should_panic] #[test] fn sources_also_files_under_custom_lib_dirs_path() { Playground::setup("source_test_1", |dirs, nu| { let ...
fn try_source_foo_with_single_quotes_in(testdir: &str, playdir: &str) { Playground::setup(playdir, |dirs, sandbox| { let testdir = String::from(testdir); let mut foo_file = testdir.clone(); foo_file.push_str("/foo.nu"); sandbox.mkdir(&testdir); sandbox.with_files(vec![File...
otes_in(testdir: &str, playdir: &str) { Playground::setup(playdir, |dirs, sandbox| { let testdir = String::from(testdir); let mut foo_file = testdir.clone(); foo_file.push_str("/foo.nu"); sandbox.mkdir(&testdir); sandbox.with_files(vec![FileWithContent(&foo_file, "echo foo")...
function_block-function_prefixed
[ { "content": "#[test]\n\nfn copy_file_and_dir_from_two_parents_up_using_multiple_dots_to_current_dir_recursive() {\n\n Playground::setup(\"cp_test_10\", |dirs, sandbox| {\n\n sandbox.with_files(vec![EmptyFile(\"hello_there\")]);\n\n sandbox.mkdir(\"hello_again\");\n\n sandbox.within(\"fo...
Rust
vm/src/stdlib/ast.rs
Leonardofreua/RustPython
cd2edbc2a589127688b3f08b507865569a42a55e
use crate::{ builtins::{self, PyStrRef, PyTypeRef}, function::FuncArgs, IdProtocol, ItemProtocol, PyClassImpl, PyContext, PyObjectRef, PyResult, PyValue, StaticType, TryFromObject, TypeProtocol, VirtualMachine, }; use num_complex::Complex64; use num_traits::{ToPrimitive, Zero}; use rustpython_ast as a...
use crate::{ builtins::{self, PyStrRef, PyTypeRef}, function::FuncArgs, IdProtocol, ItemProtocol, PyClassImpl, PyContext, PyObjectRef, PyResult, PyValue, StaticType, TryFromObject, TypeProtocol, VirtualMachine, }; use num_complex::Complex64; use num_traits::{ToPrimitive, Zero}; use rustpython_ast as a...
.into(), ast::Constant::Float(f) => vm.ctx.new_float(f).into(), ast::Constant::Complex { real, imag } => vm.new_pyobj(Complex64::new(real, imag)), ast::Constant::Ellipsis => vm.ctx.ellipsis(), } } fn ast_from_object(vm: &VirtualMachine, object: PyObjectR...
.filter(|obj| !vm.is_none(obj))) } #[pyclass(module = "_ast", name = "AST")] #[derive(Debug, PyValue)] pub(crate) struct AstNode; #[pyimpl(flags(HAS_DICT))] impl AstNode { #[pymethod(magic)] fn init(zelf: PyObjectRef, args: FuncArgs, vm: &VirtualMachine) -> PyResult<()> { let obj: PyObjectRef = ze...
random
[ { "content": "fn gen_name(gen: &PyObjectRef, vm: &VirtualMachine) -> &'static str {\n\n let typ = gen.class();\n\n if typ.is(&vm.ctx.types.coroutine_type) {\n\n \"coroutine\"\n\n } else if typ.is(&vm.ctx.types.async_generator) {\n\n \"async generator\"\n\n } else {\n\n \"generat...
Rust
src/commands/run.rs
eugene-babichenko/jorup
f7dc9604d5f4dcfd549db09b7a4acec4fd695ad6
use crate::{ common::JorupConfig, utils::{blockchain::Blockchain, release::Release, runner::RunnerControl, version::Version}, }; use std::{ net::{IpAddr, Ipv4Addr, SocketAddr}, path::PathBuf, }; use structopt::StructOpt; use thiserror::Error; #[derive(Debug, StructOpt)] pub struct Command { bl...
use crate::{ common::JorupConfig, utils::{blockchain::Blockchain, release::Release, runner::RunnerControl, version::Version}, }; use std::{ net::{IpAddr, Ipv4Addr, SocketAddr}, path::PathBuf, }; use structopt::StructOpt; use thiserror::Error; #[derive(Debug, StructOpt)] pub struct Command { bl...
}
None } } }, }; if self.daemon { runner .spawn(default_config, rest_addr, extra) .map_err(Error::Start) } else { runner .run(default_config, rest_addr, extra) ....
function_block-function_prefix_line
[ { "content": "fn remove(mut cfg: JorupConfig, version: Version) -> Result<(), Error> {\n\n let version_req = VersionReq::exact(version);\n\n let release = Release::load(&mut cfg, &version_req).map_err(Error::ReleaseLoad)?;\n\n std::fs::remove_dir_all(release.dir()).map_err(Error::RemoveRelease)?;\n\n\n...
Rust
sdk/cosmos/src/responses/list_documents_response.rs
seankane-msft/azure-sdk-for-rust
59de1214be443630d71dcd0f6c0275552df6fc3e
use crate::headers::from_headers::*; use crate::resources::document::{Document, DocumentAttributes}; use crate::ResourceQuota; use azure_core::headers::{ continuation_token_from_headers_optional, item_count_from_headers, session_token_from_headers, }; use azure_core::SessionToken; use chrono::{DateTime, Utc}; use ...
use crate::headers::from_headers::*; use crate::resources::document::{Document, DocumentAttributes}; use crate::ResourceQuota; use azure_core::headers::{ continuation_token_from_headers_optional, item_count_from_headers, session_token_from_headers, }; use azure_core::SessionToken; use chrono::{DateTime, Utc}; use ...
} #[cfg(test)] mod tests { use super::*; const BODY: &'static str = " { \"_rid\": \"3iNTAJKxVCk=\", \"Documents\": [ { \"color\": \"red\", \"myvalue\": \"#f00\", \"id\": \"c5d11a65-2e5a-3d9f-4de8-2447259dff38\", \"_rid\": \"3iNTAJKxVCkBAAAAAAAAA...
fn try_from(response: Response<bytes::Bytes>) -> Result<Self, Self::Error> { let headers = response.headers(); let body: &[u8] = response.body(); debug!("headers == {:#?}", headers); debug!("body == {:#?}", std::str::from_utf8(body)); ...
function_block-full_function
[]
Rust
crates/sauron-core/src/dom/dom_updater.rs
kdheepak/sauron
a62467c810d1479428723f048799cef73440f7db
use crate::map_msg::NodeMapMsg; use crate::{ diff, dom::{ apply_patches::patch, created_node::{ActiveClosure, CreatedNode}, Dispatch, }, Patch, }; use wasm_bindgen::JsCast; use web_sys::{self, Element, Node}; pub struct DomUpdater<MSG> { pub current_vdom: crate::Node<MS...
use crate::map_msg::NodeMapMsg; use crate::{ diff, dom::{ apply_patches::patch, created_node::{ActiveClosure, CreatedNode}, Dispatch, }, Patch, }; use wasm_bindgen::JsCast; use web_sys::{self, Element, Node}; pub struct DomUpdater<MSG> { pub current_vdom: crate::Node<MS...
pdater.replace_mount(program); dom_updater } pub fn update_dom<DSP>(&mut self, program: &DSP, new_vdom: crate::Node<MSG>) where DSP: Dispatch<MSG> + Clone + 'static, { #[cfg(feature = "with-measure")] let t1 = crate::now(); let patches = diff...
-> DomUpdater<MSG> where DSP: Dispatch<MSG> + Clone + 'static, { let mut dom_updater = Self::new(current_vdom, &mount); dom_u
function_block-random_span
[ { "content": "/// Apply all of the patches to our old root node in order to create the new root node\n\n/// that we desire.\n\n/// This is usually used after diffing two virtual nodes.\n\n///\n\n/// Note: If Program is None, it is a dumb patch, meaning\n\n/// there is no event listener attached or changed\n\npu...
Rust
src/wayland/shm/mod.rs
csnewman/smithay
f966e28fe5ebe6f6614048593ac663a89888b978
use self::pool::{Pool, ResizeError}; use std::{ops::Deref as _, rc::Rc, sync::Arc}; use wayland_server::{ protocol::{wl_buffer, wl_shm, wl_shm_pool}, Display, Filter, Global, Main, }; mod pool; #[derive(Clone)] pub struct ShmGlobalData { formats: Rc<Vec<wl_shm::Format>>, log: ::slog::Logger, } pub...
use self::pool::{Pool, ResizeError}; use std::{ops::Deref as _, rc::Rc, sync::Arc}; use wayland_server::{ protocol::{wl_buffer, wl_shm, wl_shm_pool}, Display, Filter, Global, Main, }; mod pool; #[derive(Clone)] pub struct ShmGlobalData { formats: Rc<Vec<wl_shm::Format>>, log: ::slog::Logger, } pub...
impl ShmGlobalData { fn receive_shm_message(&mut self, request: wl_shm::Request, shm: wl_shm::WlShm) { use self::wl_shm::{Error, Request}; let (pool, fd, size) = match request { Request::CreatePool { id: pool, fd, size } => (pool, fd, size), _ => unreachable!(), };...
match data.pool.with_data_slice(|slice| f(slice, data.data)) { Ok(t) => Ok(t), Err(()) => { buffer .as_ref() .post_error(wl_shm::Error::InvalidFd as u32, "Bad pool size.".into()); Err(BufferAccessError::BadMap) } } }
function_block-function_prefix_line
[ { "content": "pub fn load_shm_buffer(data: BufferData, pool: &[u8]) -> Result<(RawImage2d<'_, u8>, usize), Format> {\n\n let offset = data.offset as usize;\n\n let width = data.width as usize;\n\n let height = data.height as usize;\n\n let stride = data.stride as usize;\n\n\n\n // number of bytes...
Rust
src/kv/bound_range.rs
hi-rustin/client-rust
0314d636ba9f77a38b707a50f1d6f821f8ed14af
use std::{ borrow::Borrow, cmp::{Eq, PartialEq}, ops::{ Bound, Range, RangeBounds, RangeFrom, RangeFull, RangeInclusive, RangeTo, RangeToInclusive, }, }; #[cfg(test)] use proptest_derive::Arbitrary; use tikv_client_proto::kvrpcpb; use super::Key; #[derive(Clone, Debug, Eq, PartialEq)] #[cfg...
use std::{ borrow::Borrow, cmp::{Eq, PartialEq}, ops::{ Bound, Range, RangeBounds, RangeFrom, RangeFull, RangeInclusive, RangeTo, RangeToInclusive, }, }; #[cfg(test)] use proptest_derive::Arbitrary; use tikv_client_proto::kvrpcpb; use super::Key; #[derive(Clone, Debug, Eq, PartialEq)] #[cfg...
rt_to_bound_key<K: Into<Key>>(b: Bound<K>) -> Bound<Key> { match b { Bound::Included(k) => Bound::Included(k.into()), Bound::Excluded(k) => Bound::Excluded(k.into()), Bound::Unbounded => Bound::Unbounded, } }
function_block-function_prefixed
[ { "content": "/// The range used for request should be the intersection of `region_range` and `range`.\n\nfn range_intersection(region_range: (Key, Key), range: (Key, Key)) -> (Key, Key) {\n\n let (lower, upper) = region_range;\n\n let up = if upper.is_empty() {\n\n range.1\n\n } else if range.1...
Rust
tests/query.rs
davvid/garden
656121af4e903da86f8c644bee05cc8de8cfd6e2
mod common; #[test] fn resolve_trees_default_query_finds_garden() { let config = common::garden_config(); let result = garden::query::resolve_trees(&config, "cola"); assert_eq!(3, result.len()); assert_eq!(Some(0), result[0].garden); assert_eq!(0, result[0].tree); assert_eq!(Some(0), result[1]....
mod common; #[test] fn resolve_trees_default_query_finds_garden() { let config = common::garden_config(); let result = garden::query::resolve_trees(&config, "cola"); assert_eq!(3, result.len()); assert_eq!(Some(0), result[0].garden); assert_eq!(0, result[0].tree); assert_eq!(Some(0), resul
!(Some(3), result[1].group); assert_eq!(5, result[1].tree); let ref annex_wild_groups = config.gardens[3]; assert_eq!("annex/wildcard-groups", annex_wild_groups.get_name()); result = garden::query::trees_from_garden(&config, annex_wild_groups); assert_eq!(2, result.len()); assert...
t[1].garden); assert_eq!(1, result[1].tree); assert_eq!(Some(0), result[2].garden); assert_eq!(2, result[2].tree); } #[test] fn resolve_trees_tree_query_wildcard() { let config = common::garden_config(); let result = garden::query::resolve_trees(&config, "@c*"); assert_eq!(1, result.len()); ...
random
[ { "content": "#[test]\n\nfn read_grafts() -> Result<()> {\n\n let options = garden::build::command_options().verbose(true);\n\n let app = garden::build::context_from_path(\"tests/data/garden.yaml\", options)?;\n\n\n\n let config = app.get_root_config();\n\n assert_eq!(2, config.grafts.len());\n\n\n\...
Rust
git-protocol/src/fetch/tests/arguments.rs
kim/gitoxide
e9cdc958e7ce2290e2d7958cdb5aa9323ef35d37
use crate::fetch; use bstr::ByteSlice; use git_transport::Protocol; fn arguments_v1(features: impl IntoIterator<Item = &'static str>) -> fetch::Arguments { fetch::Arguments::new(Protocol::V1, features.into_iter().map(|n| (n, None)).collect()) } fn arguments_v2(features: impl IntoIterator<Item = &'static str>) -> ...
use crate::fetch; use bstr::ByteSlice; use git_transport::Protocol; fn arguments_v1(features: impl IntoIterator<Item = &'static str>) -> fetch::Arguments { fetch::Arguments::new(Protocol::V1, features.into_iter().map(|n| (n, None)).collect()) } fn arguments_v2(features: impl IntoIterator<Item = &'static str>) -> ...
} mod v2 { use crate::fetch::tests::arguments::{arguments_v2, id, transport}; use bstr::ByteSlice; #[maybe_async::test(feature = "blocking-client", async(feature = "async-client", async_std::test))] async fn haves_and_wants_for_clone_stateful() { let mut out = Vec::new(); let mut t = ...
ue); let mut arguments = arguments_v1(["feature-a", "shallow"].iter().copied()); arguments.deepen(1); arguments.want(id("7b333369de1221f9bfbbe03a3a13e9a09bc1c907")); arguments.have(id("0000000000000000000000000000000000000000")); arguments.send(&mut t, false).await.expect("sendi...
function_block-function_prefixed
[ { "content": "/// A general purpose connector connecting to a repository identified by the given `url`.\n\n///\n\n/// This includes connections to\n\n/// [local repositories][crate::client::file::connect()],\n\n/// [repositories over ssh][crate::client::ssh::connect()],\n\n/// [git daemons][crate::client::git::...
Rust
crayfish/src/runtime_meta.rs
jaxonwang/rust-apgas
1b7c4ff3c0eb918668a86c8cd6485fa52091644e
use crate::activity::set_helpers; use crate::activity::FunctionLabel; use crate::activity::HelperByType; use crate::activity::HelperMap; use crate::activity::SquashTypeHelper; use crate::activity::TaskItem; use crate::logging; use crate::args::RemoteSend; use futures::future::BoxFuture; use once_cell::sync::Lazy; use r...
use crate::activity::set_helpers; use crate::activity::FunctionLabel; use crate::activity::HelperByType; use crate::activity::HelperMap; use crate::activity::SquashTypeHelper; use crate::activity::TaskItem; use crate::logging; use crate::args::RemoteSend; use futures::future::BoxFuture; use once_cell::sync::Lazy; use r...
pub fn call(&self, item: TaskItem) -> BoxFuture<'static, ()> { (self.fn_ptr)(item) } } inventory::collect!(FunctionMetaData); type FuncMetaTable = FxHashMap<FunctionLabel, FunctionMetaData>; static STATIC_FUNC_META_TABLE: Lazy<Mutex<FuncMetaTable>> = Lazy::new(|| Mutex::new(FuncMetaTable::defaul...
line: u32, mod_path: String, ) -> Self { FunctionMetaData { fn_id, fn_ptr, fn_name, file, line, mod_path, } }
function_block-function_prefix_line
[ { "content": "pub fn barrier() -> impl Future<Output = ()> {\n\n let f = perform_collective(|c| c.barrier());\n\n f.map(|r| {\n\n r.unwrap();\n\n perform_collective(|c| c.barrier_done());\n\n })\n\n}\n\n\n", "file_path": "crayfish/src/collective.rs", "rank": 0, "score": 209348...
Rust
src/http_util.rs
kjnsn/deno
e51de171a18e120297a0fccf91ce622efd6c0b99
use crate::errors; use crate::errors::{DenoError, DenoResult}; use crate::tokio_util; use futures::future::{loop_fn, Loop}; use futures::{future, Future, Stream}; use hyper; use hyper::client::{Client, HttpConnector}; use hyper::header::CONTENT_TYPE; use hyper::Uri; use hyper_rustls; type Connector = hyper_rustls::H...
use crate::errors; use crate::errors::{DenoError, DenoResult}; use crate::tokio_util; use futures::future::{loop_fn, Loop}; use futures::{future, Future, Stream}; use hyper; use hyper::client::{Client, HttpConnector}; use hyper::header::CONTENT_TYPE; use hyper::Uri; use hyper_rustls; type Connector = hyper_rustls::H...
#[test] fn test_fetch_sync_string() { tokio_util::init(|| { let (p, m) = fetch_sync_string("http://127.0.0.1:4545/package.json").unwrap(); println!("package.json len {}", p.len()); assert!(p.len() > 1); assert!(m == "application/json") }); } #[test] fn test_fetch_sync_string_with_redirec...
pub fn fetch_sync_string(module_name: &str) -> DenoResult<(String, String)> { let url = module_name.parse::<Uri>().unwrap(); let client = get_client(); let fetch_future = loop_fn((client, url), |(client, url)| { client .get(url.clone()) .map_err(DenoError::from) .and_then(move |respons...
function_block-full_function
[ { "content": "pub fn v8() -> &'static str {\n\n let version = unsafe { libdeno::deno_v8_version() };\n\n let c_str = unsafe { CStr::from_ptr(version) };\n\n c_str.to_str().unwrap()\n\n}\n", "file_path": "src/version.rs", "rank": 0, "score": 267735.38613245473 }, { "content": "/// Go-style...
Rust
src/flags/size.rs
ReiAyanamiQH/lsd
db87726598ef4eaa1ab9079482759d4e9659d15a
use super::Configurable; use crate::config_file::Config; use clap::ArgMatches; use serde::Deserialize; #[derive(Clone, Debug, Copy, PartialEq, Eq, Deserialize)] #[serde(rename_all = "kebab-case")] pub enum SizeFlag { Default, Short, Bytes, } impl SizeFlag { fn from_str(value: &str) ...
use super::Configurable; use crate::config_file::Config; use clap::ArgMatches; use serde::Deserialize; #[derive(Clone, Debug, Copy, PartialEq, Eq, Deserialize)] #[serde(rename_all = "kebab-case")] pub enum SizeFlag { Default, Short, Bytes, } impl SizeFlag { fn from_str(value: &str) ...
#[test] fn test_from_arg_matches_short() { let args = vec!["lsd", "--size", "short"]; let matches = app::build().get_matches_from_safe(args).unwrap(); assert_eq!(Some(SizeFlag::Short), SizeFlag::from_arg_matches(&matches)); } #[test] fn test_from_arg_matches_bytes() { ...
fn test_from_arg_matches_default() { let argv = vec!["lsd", "--size", "default"]; let matches = app::build().get_matches_from_safe(argv).unwrap(); assert_eq!( Some(SizeFlag::Default), SizeFlag::from_arg_matches(&matches) ); }
function_block-full_function
[ { "content": "pub fn validate_time_format(formatter: &str) -> Result<(), String> {\n\n let mut chars = formatter.chars();\n\n loop {\n\n match chars.next() {\n\n Some('%') => match chars.next() {\n\n Some('A') | Some('a') | Some('B') | Some('b') | Some('C') | Some('c')\n\n...
Rust
libs/datamodel/dmmf/src/to_dmmf.rs
StringKe/prisma-engines
4cac12afbeef2fa3eedf1cb87c79bc15e2648836
use crate::{Datamodel, Enum, EnumValue, Field, Function, Model, PrimaryKey, UniqueIndex}; use bigdecimal::ToPrimitive; use datamodel::{ dml::{self, CompositeTypeFieldType, FieldType, Ignorable, ScalarType}, PrismaValue, }; pub fn render_to_dmmf(schema: &dml::Datamodel) -> String { let dmmf = schema_to_dmmf...
use crate::{Datamodel, Enum, EnumValue, Field, Function, Model, PrimaryKey, UniqueIndex}; use bigdecimal::ToPrimitive; use datamodel::{ dml::{self, CompositeTypeFieldType, FieldType, Ignorable, ScalarType}, PrismaValue, }; pub fn render_to_dmmf(schema: &dml::Datamodel) -> String { let dmmf = schema_to_dmmf...
serde_json::Value::Object(map) } } } fn function_to_serde(name: &str, args: &[PrismaValue]) -> serde_json::Value { let func = Function { name: String::from(name), args: args.iter().map(prisma_value_to_serde).collect(), }; serde_json::to_value(&func).expect("Failed to ren...
is_id: false, is_read_only: false, has_default_value: field.default_value.is_some(), default: default_value_to_serde(&field.default_value), is_unique: false, relation_name: None, relation_from_fields: None, relation_to_fields: None, relation_on_de...
random
[ { "content": "/// Enum type convenience wrapper function.\n\npub fn string_enum_type<T>(name: T, values: Vec<String>) -> EnumType\n\nwhere\n\n T: Into<String>,\n\n{\n\n EnumType::String(StringEnumType {\n\n name: name.into(),\n\n values,\n\n })\n\n}\n\n\n", "file_path": "query-engine/...
Rust
src/parser/datetime.rs
jamii/sqlparser
2e53850be01cff4bd63fa674410bbab7c49e6b78
use crate::ast::ParsedDateTime; use crate::parser::{DateTimeField, ParserError}; pub(crate) fn tokenize_interval(value: &str) -> Result<Vec<IntervalToken>, ParserError> { let mut toks = vec![]; let mut num_buf = String::with_capacity(4); fn parse_num(n: &str, idx: usize) -> Result<IntervalToken, ParserErro...
use crate::ast::ParsedDateTime; use crate::parser::{DateTimeField, ParserError}; pub(crate) fn tokenize_interval(value: &str) -> Result<Vec<IntervalToken>, ParserError> { let mut toks = vec![]; let mut num_buf = String::with_capacity(4); fn parse_num(n: &str, idx: usize) -> Result<IntervalToken, ParserErro...
}; let mut last_field_is_frac = false; for (i, chr) in value.chars().enumerate() { match chr { '-' => { if !num_buf.is_empty() { toks.push(parse_num(&num_buf, i)?); num_buf.clear(); } ...
Ok(IntervalToken::Num(n.parse().map_err(|e| { ParserError::ParserError(format!( "Unable to parse value as a number at index {}: {}", idx, e )) })?))
call_expression
[ { "content": "fn parse_sql_statements(sql: &str) -> Result<Vec<Statement>, ParserError> {\n\n all_dialects().parse_sql_statements(sql)\n\n}\n\n\n", "file_path": "tests/sqlparser_common.rs", "rank": 0, "score": 94923.4427725611 }, { "content": "fn one_statement_parses_to(sql: &str, canonic...
Rust
src/lib.rs
i-schuetz/algonaut-myalgo-yew-template
149378848ccef449b269344d6dabfb96131751f1
#![recursion_limit = "1024"] mod dependencies; mod provider; use wasm_bindgen::prelude::*; use yew::prelude::*; use crate::provider::SendPaymentData; use algonaut::core::{Address, MicroAlgos}; use anyhow::Result; use wasm_bindgen::JsValue; use yew::{html, Component, ComponentLink, Html, ShouldRender}; use yewtil::f...
#![recursion_limit = "1024"] mod dependencies; mod provider; use wasm_bindgen::prelude::*; use yew::prelude::*; use crate::provider::SendPaymentData; use algonaut::core::{Address, MicroAlgos}; use anyhow::Result; use wasm_bindgen::JsValue; use yew::{html, Component, ComponentLink, Html, ShouldRender}; use yewtil::f...
) }); } Msg::UpdateReceiverInput(input) => self.payment_inputs.receiver = input, Msg::UpdateAmountInput(input) => self.payment_inputs.amount = input, Msg::UpdateFeeInput(input) => self.payment_inputs.fee = input, Msg::SetAddress(address) => sel...
match address { Some(address) => match Self::send_payment(address, payment_inputs).await { Ok(tx_id) => format!("Success! Tx id: {}", tx_id), Err(e) => format!("Error: {}", e), }, None => "Not...
if_condition
[ { "content": "pub fn provider(algod: Algod, my_algo: MyAlgo) -> Provider {\n\n Provider::new(algod, my_algo)\n\n}\n", "file_path": "src/dependencies.rs", "rank": 0, "score": 69208.86265830716 }, { "content": "pub fn my_algo() -> MyAlgo {\n\n MyAlgo {}\n\n}\n\n\n", "file_path": "src...
Rust
sample_code/tmll/src/fourth.rs
Jacobbishopxy/note-rust-lang
e01327f040b7813c58e0736082d42140ae8a4597
use std::cell::{Ref, RefCell, RefMut}; use std::rc::Rc; pub struct List<T> { head: Link<T>, tail: Link<T>, } type Link<T> = Option<Rc<RefCell<Node<T>>>>; struct Node<T> { elem: T, next: Link<T>, prev: Link<T>, } impl<T> Node<T> { fn new(elem: T) -> Rc<RefCell<Self>> { Rc::new(RefCe...
use std::cell::{Ref, RefCell, RefMut}; use std::rc::Rc; pub struct List<T> { head: Link<T>, tail: Link<T>, } type Link<T> = Option<Rc<RefCell<Node<T>>>>; struct Node<T> { elem: T, next: Link<T>, prev: Link<T>, } impl<T> Node<T> {
} impl<T> List<T> { pub fn new() -> Self { List { head: None, tail: None, } } pub fn push_front(&mut self, elem: T) { let new_head = Node::new(elem); match self.head.take() { Some(old_head) => { old_head.borrow_mut().prev...
fn new(elem: T) -> Rc<RefCell<Self>> { Rc::new(RefCell::new(Node { elem: elem, prev: None, next: None, })) }
function_block-full_function
[ { "content": "# 结构体案例\n\n\n\n为了理解什么时候该用结构体,我们来编写一个计算长方形面积的程序。以单变量开始,然后重构我们的项目指导我们使用到结构体。\n\n\n\n...\n\n\n\n```rust\n\nfn main() {\n\n let width1 = 30;\n\n let height1 = 50;\n\n\n\n println!(\n\n \"The area of the rectangle is {} square pixels.\",\n\n area(width1, height1)\n\n );\n\n}\n...
Rust
src/containers.rs
jac3km4/clear-coat
28179ec8298bb098266a9b7fcdb63ea19fe3a033
/* Copyright 2015 Jordan Miner * * Licensed under the MIT license <LICENSE or * http://opensource.org/licenses/MIT>. This file may not be copied, * modified, or distributed except according to those terms. */ use super::control_prelude::*; use super::attributes::*; pub trait Container : Control { f...
/* Copyright 2015 Jordan Miner * * Licensed under the MIT license <LICENSE or * http://opensource.org/licenses/MIT>. This file may not be copied, * modified, or distributed except according to those terms. */ use super::control_prelude::*; use super::attributes::*; pub trait Container : Control { f...
ll { pub fn new() -> Fill { unsafe { ::iup_open(); let handle = IupFill(); Fill(HandleRc::new(handle)) } } } impl_control_traits!(Fill); impl SizeAttribute for Fill {} #[macro_export] macro_rules! fill { () => { Fill::new() }; } #[derive(Clone)] pub s...
s.parse().expect("could not convert GAP to an integer") } } fn set_gap(&self, gap: u32) -> &Self { set_str_attribute(self.handle(), "GAP\0", &format!("{}\0", gap)); self } fn ngap(&self) -> u32 { unsafe { let s = get_str_attribute_slice(self.handle(), "...
random
[]
Rust
compound-data-types/src/main.rs
ernestas-poskus/rusty-fun
fd4f907268e470f0f0f45410de045f6669e98a89
fn main() { tuples(); structs(); tuple_structs(); enums(); ordering(); } fn tuples() { let t1 = (1, "tup"); let t2: (i32, &str) = (292, "string"); let (x, y, z) = (1, 2, 3); println!("x is {}", x); let mut q = (1, 2); let o = (2, 3); ...
fn main() { tuples(); structs(); tuple_structs(); enums(); ordering(); } fn tuples() { let t1 =
1, x + 2) } let(z1, z2) = next_two(98); println!("z1, z2 = {}, {}", z1, z2); } fn structs() { struct Point { x: i32, y: i32, z: i32 } let origin = Point { x: 29, y: 101, z: 2992}; println!("Origin points ({}, {...
(1, "tup"); let t2: (i32, &str) = (292, "string"); let (x, y, z) = (1, 2, 3); println!("x is {}", x); let mut q = (1, 2); let o = (2, 3); q = o; let (print1, print2) = q; println!("o is ({}, {})", print1, print2); let x1 = (1, 2, 3); ...
function_block-random_span
[ { "content": "fn main() {\n\n println!(\"Hello, world!\");\n\n\n\n let x = 5;\n\n\n\n if x == 5 {\n\n println!(\"x == 5 {}\", x == 5);\n\n } else if x == 2 {\n\n println!(\"x == 2 {}\", x == 2);\n\n } else {\n\n // Unreachable but throw re-assignment error\n\n // x = 2...
Rust
base_layer/mmr/src/common.rs
Grrwahrr/tari
743cb648fc8d85ea1c14c7bf738ebd1198e3c601
use crate::Hash; use digest::Digest; const ALL_ONES: usize = std::usize::MAX; pub fn node_index(leaf_index: usize) -> usize { if leaf_index == 0 { return 0; } 2 * leaf_index - leaf_index.count_ones() as usize } pub fn leaf_index(node_index: usize) -> u32 { n_leaves(node_index) as u32 } pub...
use crate::Hash; use digest::Digest; const ALL_ONES: usize = std::usize::MAX; pub fn node_index(leaf_index: usize) -> usize { if leaf_index == 0 { return 0; } 2 * leaf_index - leaf_index.count_ones() as usize } pub fn leaf_index(node_index: usize) -> u32 { n_leaves(node_index) as u32 } pub...
(126, 125), (254, 253), (510, 509), (1022, 1021), (2046, 2045), (4094, 4093), (8190, 8189), (16382, 16381), (32766, 32765), (65534, 65533), (131_070, 131_069), (262_142, 262_141)...
(0, 2), [(2, 1)]); assert_eq!(family_branch(1, 2), [(2, 0)]); assert_eq!(family_branch(2, 2), []); assert_eq!(family_branch(0, 6), [(2, 1), (6, 5)]); assert_eq!(family_branch(0, 3), [(2, 1)]); assert_eq!(family_branch(3, 3), []); asse...
function_block-random_span
[]
Rust
helix-core/src/surround.rs
typerslow/helix
8eb15f52835c3669a5d5f0539a13f415a8a71856
use std::fmt::Display; use crate::{search, Range, Selection}; use ropey::RopeSlice; pub const PAIRS: &[(char, char)] = &[ ('(', ')'), ('[', ']'), ('{', '}'), ('<', '>'), ('«', '»'), ('「', '」'), ('(', ')'), ]; #[derive(Debug, PartialEq)] pub enum Error { PairNotFound, CursorOverlap...
use std::fmt::Display; use crate::{search, Range, Selection}; use ropey::RopeSlice; pub const PAIRS: &[(char, char)] = &[ ('(', ')'), ('[', ']'), ('{', '}'), ('<', '>'), ('«', '»'), ('「', '」'), ('(', ')'), ]; #[derive(Debug, PartialEq)] pub enum Error { PairNotFound, CursorOverlap...
r); } ( search::find_nth_prev(text, open, pos, n), search::find_nth_next(text, close, pos, n), ) } else { ( find_nth_open_pair(text, open, close, pos, n), find_nth_close_pair(text, open, close, pos, n), ) }; Option::zip...
range: Range, n: usize, ) -> Result<(usize, usize)> { if text.len_chars() < 2 { return Err(Error::PairNotFound); } if range.to() >= text.len_chars() { return Err(Error::RangeExceedsText); } let (open, close) = get_pair(ch); let pos = range.cursor(text); let (open, ...
function_block-random_span
[ { "content": "pub fn find_nth_prev(text: RopeSlice, ch: char, mut pos: usize, n: usize) -> Option<usize> {\n\n if pos == 0 || n == 0 {\n\n return None;\n\n }\n\n\n\n let mut chars = text.chars_at(pos);\n\n\n\n for _ in 0..n {\n\n loop {\n\n let c = chars.prev()?;\n\n\n\n ...
Rust
src/config.rs
nielx/rls
1263f1ff25bb329b76f74715ad4a7ec0d1f71430
use std::marker::PhantomData; use std::str::FromStr; use std::fmt; use std::env; use std::fmt::Debug; use std::io::sink; use std::path::{Path, PathBuf}; use cargo::CargoResult; use cargo::util::{homedir, important_paths, Config as CargoConfig}; use cargo::core::{Shell, Workspace}; use failure; use serde; use serde:...
use std::marker::PhantomData; use std::str::FromStr; use std::fmt; use std::env; use std::fmt::Debug; use std::io::sink; use std::path::{Path, PathBuf}; use cargo::CargoResult; use cargo::util::{homedir, important_paths, Config as CargoConfig}; use cargo::core::{Shell, Workspace}; use failure; use serde; use serde:...
} } impl<T> Inferrable<T> { pub fn is_none(&self) -> bool { match *self { Inferrable::None => true, _ => false, } } } impl<T: Clone + Debug> Inferrable<T> { pub fn combine_with_default(&self, new: &Self, default: T) -> Self { match (self, new)...
Ok(match value { None => Inferrable::None, Some(value) => Inferrable::Specified(value), })
call_expression
[ { "content": "pub fn main() {\n\n x::nemo();\n\n}\n", "file_path": "test_data/workspace_symbol/src/main.rs", "rank": 0, "score": 130353.68130069113 }, { "content": "pub fn root() -> PathBuf {\n\n init();\n\n global_root().join(&TASK_ID.with(|my_id| format!(\"t{}\", my_id)))\n\n}\n\n...
Rust
algonaut_core/src/address.rs
defimono/algonaut
30a251e438df9bb7af8b3aafc53bb9945a74c963
use crate::Signature; use algonaut_crypto::Ed25519PublicKey; use algonaut_encoding::U8_32Visitor; use data_encoding::BASE32_NOPAD; use serde::{Deserialize, Deserializer, Serialize, Serializer}; use sha2::Digest; use std::fmt::{self, Debug, Display, Formatter}; use std::hash::{Hash, Hasher}; use std::str::FromStr; type...
use crate::Signature; use algonaut_crypto::Ed25519PublicKey; use algonaut_encoding::U8_32Visitor; use data_encoding::BASE32_NOPAD; use serde::{Deserialize, Deserializer, Serialize, Serializer}; use sha2::Digest; use std::fmt::{self, Debug, Disp
ksum) = checksum_address.split_at(HASH_LEN); let hashed = ChecksumAlg::digest(address); if &hashed[(HASH_LEN - CHECKSUM_LEN)..] == checksum { let mut bytes = [0; HASH_LEN]; bytes.copy_from_slice(address); Ok(Address::new(bytes)) } else { Err("Input...
lay, Formatter}; use std::hash::{Hash, Hasher}; use std::str::FromStr; type ChecksumAlg = sha2::Sha512_256; const CHECKSUM_LEN: usize = 4; const HASH_LEN: usize = 32; #[derive(Copy, Clone, Eq)] pub struct Address(pub [u8; HASH_LEN]); impl Address { pub fn new(bytes: [u8; HASH_LEN]) -> Address { Address(...
random
[ { "content": "pub fn deserialize_bytes64<'de, D>(deserializer: D) -> Result<[u8; 64], D::Error>\n\nwhere\n\n D: Deserializer<'de>,\n\n{\n\n use serde::de::Error;\n\n let s = <&str>::deserialize(deserializer)?;\n\n let mut decoded = [0; 64];\n\n let bytes = BASE64.decode(s.as_bytes()).map_err(D::E...
Rust
src/imp/libc/net/read_sockaddr.rs
ratmice/rsix
05040f5e4e53cea30f13b610e5082fe0abc0a468
use super::{SocketAddr, SocketAddrUnix}; use crate::{as_ptr, io}; use libc::sockaddr_storage; use std::ffi::CStr; use std::mem::size_of; use std::net::{Ipv4Addr, Ipv6Addr, SocketAddrV4, SocketAddrV6}; #[repr(C)] struct sockaddr_header { #[cfg(any( target_os = "netbsd", target_os = "macos", ...
use super::{SocketAddr, SocketAddrUnix}; use crate::{as_ptr, io}; use libc::sockaddr_storage; use std::ffi::CStr; use std::mem::size_of; use std::net::{Ipv4Addr, Ipv6Addr, SocketAddrV4, SocketAddrV6}; #[repr(C)] struct sockaddr_header { #[cfg(any( target_os = "netbsd", target_os = "macos", ...
pub(crate) unsafe fn read_sockaddr_os(storage: *const sockaddr_storage, len: usize) -> SocketAddr { let z = libc::sockaddr_un { #[cfg(any( target_os = "netbsd", target_os = "macos", target_os = "ios", target_os = "freebsd", target_os = "openbsd" ...
pub(crate) unsafe fn read_sockaddr( storage: *const sockaddr_storage, len: usize, ) -> io::Result<SocketAddr> { let offsetof_sun_path = super::offsetof_sun_path(); if len < size_of::<libc::sa_family_t>() { return Err(io::Error::INVAL); } match read_ss_family(storage).into() { li...
function_block-function_prefix_line
[ { "content": "#[inline]\n\npub fn write<Fd: AsFd>(fd: &Fd, buf: &[u8]) -> io::Result<usize> {\n\n let fd = fd.as_fd();\n\n imp::syscalls::write(fd, buf)\n\n}\n\n\n\n/// `pread(fd, buf, offset)`—Reads from a file at a given position.\n\n///\n\n/// # References\n\n/// - [POSIX]\n\n/// - [Linux]\n\n///\n\n...
Rust
runtimes/rust/src/service.rs
slowli/exonum
5a0ca3f79cd0ac65fda701f768a3cdd5a4f682e7
use exonum::{ blockchain::{config::InstanceInitParams, ApiSender, SendError}, crypto::{Hash, KeyPair, PublicKey}, helpers::{Height, ValidatorId}, merkledb::{access::Prefixed, BinaryValue, ObjectHash, Snapshot}, runtime::{ ArtifactId, BlockchainData, DispatcherAction, ExecutionContext, Exec...
use exonum::{ blockchain::{config::InstanceInitParams, ApiSender, SendError}, crypto::{Hash, KeyPair, PublicKey}, helpers::{Height, ValidatorId}, merkledb::{access::Prefixed, BinaryValue, ObjectHash, Snapshot}, runtime::{ ArtifactId, BlockchainData, DispatcherAction, ExecutionContext, Exec...
{ pub(super) fn new( instance: InstanceDescriptor, service_keypair: &'a KeyPair, tx_sender: &'a ApiSender, ) -> Self { Self { instance, service_keypair: Cow::Borrowed(service_keypair), tx_sender: Cow::Borrowed(tx_sender), } } ...
) -> Result<(), ExecutionError> { Ok(()) } fn before_transactions(&self, _context: ExecutionContext<'_>) -> Result<(), ExecutionError> { Ok(()) } ...
random
[ { "content": "#[allow(unused_variables)]\n\npub trait Runtime: Send + fmt::Debug + 'static {\n\n /// Initializes the runtime, providing a `Blockchain` instance for further use.\n\n ///\n\n /// Calling this method always takes place before calling any other `Runtime` methods.\n\n /// The `initialize`...
Rust
rabbithole/src/model/resource.rs
radium-io/rabbithole-rs
679fe10998999285b5157cc84220d38beb606bd3
use crate::model::link::Links; use crate::model::relationship::Relationships; use crate::model::{error, Meta}; use crate::Result; use serde::{Deserialize, Serialize}; use std::cmp::Ordering; use std::collections::HashMap; use std::collections::HashSet; use std::fmt::Debug; use std::hash::Hash; use std::iter::FromIterat...
use crate::model::link::Links; use crate::model::relationship::Relationships; use crate::model::{error, Meta}; use crate::Result; use serde::{Deserialize, Serialize}; use std::cmp::Ordering; use std::collections::HashMap; use std::collections::HashSet; use std::fmt::Debug; use std::hash::Hash; use std::iter::FromIterat...
ct::<HashMap<String, AttributeField>>() .into() } } impl Attributes { pub fn get_field(&self, field_name: &str) -> Result<&AttributeField> { self.0 .get(field_name) .ok_or_else(|| error::Error::FieldNotExist(field_name, None)) } pub fn cmp(&self, field: &str...
.map_err(|err| error::Error::InvalidJson(&err, None))?; Ok(value.into()) } } impl From<serde_json::Value> for AttributeField { fn from(value: serde_json::Value) -> Self { Self(value) } } impl ToString for AttributeField { fn to_string(&self) -> String { serde_json::to_string(&self.0).unwrap() } } ...
random
[ { "content": "pub fn read_json_file(filename: &str) -> String {\n\n let path = Path::new(filename);\n\n let display = path.display();\n\n\n\n let mut file = match File::open(&path) {\n\n Err(why) => panic!(\"couldn't open {}: {}\", display, &why),\n\n Ok(file) => file,\n\n };\n\n\n\n ...
Rust
src/net/tcp.rs
bryanburgers/guillotine
41214ea7ef12523f32f564df9f07d1638a8367f3
use crate::runtime::RuntimeContext; use pin_project::pin_project; use std::future::Future; use std::io::ErrorKind; use std::net::SocketAddr; pub struct TcpListener(std::net::TcpListener); impl TcpListener { pub fn new(listener: std::net::TcpListener) -> Result<Self, std::io::Error> { listen...
use crate::runtime::RuntimeContext; use pin_project::pin_project; use std::future::Future; use std::io::ErrorKind; use std::net::SocketAddr; pub struct TcpListener(std::net::TcpListener); impl TcpListener { pub fn new(listener: std::net::TcpListener) -> Result<Self, std::io::Error> { listen...
std::task::Poll::Pending } Err(err) => std::task::Poll::Ready(Err(err)), } } } #[pin_project] struct Write<'a, 'b> { stream: &'a mut TcpStream, buf: &'b [u8], state: RegisteredState, } impl<'a, 'b> Future for Write<'a, 'b> { type Output = Result<usize, std...
self: std::pin::Pin<&mut Self>, _cx: &mut std::task::Context<'_>, ) -> std::task::Poll<Self::Output> { let projected = self.project(); let result = projected.listener.0.accept(); match result { Ok((stream, addr)) => match TcpStream...
random
[ { "content": "/// Spawn a new future onto the currently executing runtime\n\n///\n\n/// Panics if there is no runtime currently executing\n\npub fn spawn<F>(future: F) -> JoinHandle<F::Output>\n\nwhere\n\n F: Future + 'static,\n\n F::Output: 'static,\n\n{\n\n // Get access to the currently executing ru...
Rust
compiler/rustc_lint/src/late.rs
ghishadow/rust
10f4ce324baf7cfb7ce2b2096662b82b79204944
use crate::{passes::LateLintPassObject, LateContext, LateLintPass, LintStore}; use rustc_ast as ast; use rustc_data_structures::sync::join; use rustc_hir as hir; use rustc_hir::def_id::LocalDefId; use rustc_hir::intravisit as hir_visit; use rustc_hir::intravisit::Visitor; use rustc_middle::hir::nested_filter; use rus...
use crate::{passes::LateLintPassObject, LateContext, LateLintPass, LintStore}; use rustc_ast as ast; use rustc_data_structures::sync::join; use rustc_hir as hir; use rustc_hir::def_id::LocalDefId; use rustc_hir::intravisit as hir_visit; use rustc_hir::intravisit::Visitor; use rustc_middle::hir::nested_filter; use rus...
fn visit_field_def(&mut self, s: &'tcx hir::FieldDef<'tcx>) { self.with_lint_attrs(s.hir_id, |cx| { lint_callback!(cx, check_field_def, s); hir_visit::walk_field_def(cx, s); }) } fn visit_variant( &mut self, v: &'tcx hir::Variant<'tcx>, g: &...
fn visit_variant_data( &mut self, s: &'tcx hir::VariantData<'tcx>, _: Symbol, _: &'tcx hir::Generics<'tcx>, _: hir::HirId, _: Span, ) { lint_callback!(self, check_struct_def, s); hir_visit::walk_struct_def(self, s); lint_callback!(self, check_s...
function_block-function_prefix_line
[]
Rust
crates/jit/src/code_memory.rs
pventuzelo/wasmtime
d733ebf3abd5fc074e93fd283f0a894e986ecbcb
use crate::function_table::FunctionTable; use region; use std::{cmp, mem}; use wasmtime_environ::{Compilation, CompiledFunction}; use wasmtime_runtime::{Mmap, VMFunctionBody}; pub struct CodeMemory { current: (Mmap, FunctionTable), mmaps: Vec<(Mmap, FunctionTable)>, position: usize, published: usize,...
use crate::function_table::FunctionTable; use region; use std::{cmp, mem}; use wasmtime_environ::{Compilation, CompiledFunction}; use wasmtime_runtime::{Mmap, VMFunctionBody}; pub struct CodeMemory { current: (Mmap, FunctionTable), mmaps: Vec<(Mmap, FunctionTable)>, position: usize, published: usize,...
fn function_allocation_size(func: &CompiledFunction) -> usize { if func.unwind_info.is_empty() { func.body.len() } else { ((func.body.len() + 3) & !3) + func.unwind_info.len() } } fn copy_function<'a>( func: &Compile...
t [u8], &mut FunctionTable), String> { if self.current.0.len() - self.position < size { self.push_current(cmp::max(0x10000, size))?; } let old_position = self.position; self.position += size; Ok(( &mut self.current.0.as_mut_slice()[old_position..self.pos...
function_block-function_prefixed
[ { "content": "/// Declares data segment symbol\n\npub fn declare_table(obj: &mut Artifact, index: usize) -> Result<(), String> {\n\n let name = format!(\"_table_{}\", index);\n\n obj.declare(name, Decl::data())\n\n .map_err(|err| format!(\"{}\", err))?;\n\n Ok(())\n\n}\n\n\n", "file_path": "...
Rust
src/code_table_test.rs
tats-u/rust-hfs-nfd
c8f0b8f57d94cc2053f5951e125f7c9823a35a53
use super::code_table::*; use super::reverse_tree::ReverseTreeNode; use std::collections::VecDeque; #[cfg(test)] mod test { use super::*; fn try_decompose(src: char, target: &str) { assert_eq!(*(MAP_TO_HFS.get(&src).unwrap()), target); } ...
use super::code_table::*; use super::reverse_tree::ReverseTreeNode; use std::collections::VecDeque; #[cfg(test)] mod test { use super::*; fn try_decompose(src: char, target: &str) { assert_eq!(*(MAP_TO_HFS.get(&src).unwrap()), target); } ...
}
t Some(target) = node_ref.current { try_compose(&decomposed_str, target); } if let Some(next_dic) = &node_ref.next { for (ch_ref, node_ref) in next_dic.as_ref() { let mut s = decomposed_str.clone(); s.push(*ch_ref); ...
function_block-function_prefixed
[ { "content": "pub fn compose_hangul_jamos(source: &str) -> String {\n\n if source.is_empty() {\n\n return \"\".to_string();\n\n }\n\n let mut it = source.chars();\n\n let mut result = String::new();\n\n // temporary variable that contains one character before\n\n let mut last = it.next(...
Rust
debug/src/dim2.rs
AyeGill/heron
7b701f06fefa902bd4a647f718e139c178248e3c
use std::f32::consts::PI; use bevy::prelude::*; use bevy_prototype_lyon::entity::ShapeBundle; use bevy_prototype_lyon::prelude::*; use bevy_prototype_lyon::shapes::RectangleOrigin; use heron_core::CollisionShape; use heron_rapier::convert::IntoBevy; use heron_rapier::rapier2d::geometry::{ColliderHandle, ColliderSet, ...
use std::f32::consts::PI; use bevy::prelude::*; use bevy_prototype_lyon::entity::ShapeBundle; use bevy_prototype_lyon::prelude::*; use bevy_prototype_lyon::shapes::RectangleOrigin; use heron_core::CollisionShape; use heron_rapier::convert::IntoBevy; use heron_rapier::rapier2d::geometry::{ColliderHandle, ColliderSet, ...
fn create_shape( body: &CollisionShape, shape: &dyn Shape, color: Color, transform: GlobalTransform, ) -> ShapeBundle { base_builder(body, shape).build( ShapeColors::new(color), DrawMode::Fill(FillOptions::default()), Transform { translation: Vec3::Z, ...
removed_bodies: RemovedComponents<'_, CollisionShape>, ) { for parent_entity in removed_bodies.iter() { if let Some(debug_entity) = map.remove(&parent_entity) { commands.entity(debug_entity).despawn(); } } }
function_block-function_prefix_line
[ { "content": "fn spawn(mut commands: Commands) {\n\n let mut rigid_body_entity = commands.spawn();\n\n\n\n // ANCHOR: add-child-shape\n\n rigid_body_entity\n\n // A (parent) dynamic rigid body\n\n .insert(RigidBody::Dynamic)\n\n .insert(Transform::from_translation(Vec3::new(-400.0,...
Rust
src/api/client.rs
sebinsua/teller-cli
fd9ff05073ba6f6142583ed019aa627624a39bde
use hyper::{Client, Url}; use hyper::header::{Authorization, Bearer}; use rustc_serialize::json; use chrono::{Date, DateTime, UTC}; use std::io::prelude::*; use api::error::TellerClientError; pub type ApiServiceResult<T> = Result<T, TellerClientError>; type AccountResponse = Account; type AccountsResponse = Vec<A...
use hyper::{Client, Url}; use hyper::header::{Authorization, Bearer}; use rustc_serialize::json; use chrono::{Date, DateTime, UTC}; use std::io::prelude::*; use api::error::TellerClientError; pub type ApiServiceResult<T> = Result<T, TellerClientError>; type AccountResponse = Account; type AccountsResponse = Vec<A...
).send()); if res.status.is_client_error() { return Err(TellerClientError::AuthenticationError); } let mut body = String::new(); try!(res.read_to_string(&mut body)); info!("GET {}", url); debug!("Response: {}", body); Ok(body) } pub fn get_...
Authorization( Bearer { token: self.auth_token.to_string() } )
call_expression
[ { "content": "pub fn timeframe_to_date_range(timeframe: &Timeframe) -> (Date<UTC>, Date<UTC>){\n\n // NOTE: We need to ensure that when testing the from and to dates used\n\n // are always the same.\n\n let to = if cfg!(test) {\n\n generate_utc_date_from_date_str(\"2016-01-01\")\n\n } else {\...
Rust
engine/src/datastr/graph.rs
kit-algo/rust_road_router
8f1ef49a8a5a2111da11c9d941eee248060cc576
use crate::datastr::node_order::NodeOrder; use std::ops::Range; pub mod first_out_graph; pub mod floating_time_dependent; pub mod link_id_to_tail_mapper; pub mod time_dependent; pub use self::first_out_graph::{ FirstOutGraph, OwnedGraph, ReversedGraphWithEdgeIds, UnweightedFirstOutGraph, UnweightedOwnedGraph, W...
use crate::datastr::node_order::NodeOrder; use std::ops::Range; pub mod first_out_graph; pub mod floating_time_dependent; pub mod link_id_to_tail_mapper; pub mod time_dependent; pub use self::first_out_graph::{ FirstOutGraph, OwnedGraph, ReversedGraphWithEdgeIds, UnweightedFirstOutGraph, UnweightedOwnedGraph, W...
pub trait BuildReversed<G> { fn reversed(graph: &G) -> Self; } pub trait BuildPermutated<G>: Sized { fn permutated(graph: &G, order: &NodeOrder) -> Self { Self::permutated_filtered(graph, order, Box::new(|_, _| true)) } fn permutated_filtered(graph: &G, order: &NodeOrder,...
0; for edge_id in 0..graph.num_arcs() { let link = graph.link(edge_id as EdgeId); for next_link_id in graph.neighbor_edge_indices(link.node) { if let Some(turn_cost) = turn_costs(edge_id as EdgeId, next_link_id) { head.push(next_link_id); weight.push(link...
function_block-function_prefixed
[ { "content": "/// Create an overlay graph by contracting a fixed number of nodes\n\npub fn overlay<Graph: LinkIterGraph>(graph: &Graph, order: NodeOrder, contraction_count: usize) -> (OwnedGraph, OwnedGraph) {\n\n let mut graph = ContractionGraph::new(graph, order);\n\n graph.contract_partially(contractio...
Rust
rs/rust_canisters/dfn_core/src/stable.rs
audieleon/ic
35dd8f93dec82662ed4df35664a9c0be6dbf203a
use std::convert::TryFrom; use std::io; use crate::api::ic0; const PAGE_SIZE: f64 = 64.0 * 1024.0; const LENGTH_BYTES: u32 = 4; pub fn set(content: &[u8]) { let len: u32 = content.len() as u32; ensure_capacity(len); unsafe { ic0::stable_write(LENGTH_BYTES, content.as_ptr() as u32, len); } ...
use std::convert::TryFrom; use std::io; use crate::api::ic0; const PAGE_SIZE: f64 = 64.0 * 1024.0; const LENGTH_BYTES: u32 = 4; pub fn set(content: &[u8]) { let len: u32 = content.len() as u32; ensure_capacity(len); unsafe { ic0::stable_write(LENGTH_BYTES, content.as_ptr() as u32, len); } ...
pub fn get() -> Vec<u8> { let len = length(); let mut out: Vec<u8> = vec![0; len as usize]; unsafe { ic0::stable_read(out.as_mut_ptr() as u32, LENGTH_BYTES, len as u32); } out } pub fn read(offset: u32, len: u32) -> Vec<u8> { let mut out: Vec<u8> = vec![0; len as usize]; unsafe { ...
return; } unsafe { ic0::stable_write( LENGTH_BYTES + offset, content.as_ptr() as u32, content.len() as u32, ); } if new_len > old_len { set_length(new_len); } }
function_block-function_prefix_line
[ { "content": "pub fn pub_coeffs(content: u8) -> CspPublicCoefficients {\n\n mock_csp_public_coefficients_from_bytes(content)\n\n}\n\n\n", "file_path": "rs/crypto/src/sign/threshold_sig/dkg/test_utils.rs", "rank": 5, "score": 348307.04379692243 }, { "content": "/// Converts a vec into the ...
Rust
contracts/market-contract/src/sale_views.rs
BSSCommerce/picasarts.io
854c28fbf2164b496cc0d14475c6403c1aaa5580
use crate::*; #[near_bindgen] impl Contract { pub fn get_supply_sales( &self, ) -> U64 { U64(self.sales.len()) } pub fn get_supply_by_owner_id( &self, account_id: AccountId, ) -> U64 { let by_owner_id = self.by_owner_id.get(&account_id); if...
use crate::*; #[near_bindgen] impl Contract { pub fn get_supply_sales( &self, ) -> U64 { U64(self.sales.len()) } pub fn get_supply_by_owner_id( &self, account_id: AccountId, ) -> U64 { let by_owner_id = self.by_owner_id.get(&account_id); if...
; let end = min(start + limit, sales.len()); for i in start..end { tmp.push(self.sales.get(&format!("{}{}{}", &nft_contract_id, DELIMETER, &keys.get(i).unwrap())).unwrap()); } tmp } pub fn get_supply_by_nft_token_type( &self, token_type: String, )...
m_index: U64, limit: u64, ) -> Vec<Sale> { let mut tmp = vec![]; let by_nft_contract_id = self.by_nft_contract_id.get(&nft_contract_id); let sales = if let Some(by_nft_contract_id) = by_nft_contract_id { by_nft_contract_id } else { return vec![]; ...
function_block-random_span
[]
Rust
src/paste.rs
sahwar/wl-clipboard-rs
c0c3768ece2020d74b60a1983d48b301144d0396
use std::{ cell::{Cell, RefCell}, collections::HashSet, ffi::OsString, io, mem, os::unix::io::AsRawFd, rc::Rc, }; use failure::Fail; use os_pipe::{pipe, PipeReader}; use wayland_client::{ConnectError, EventQueue}; use wayland_protocols::wlr::unstable::data_control::v1::client::zwlr_data_contr...
use std::{ cell::{Cell, RefCell}, collections::HashSet, ffi::OsString, io, mem, os::unix::io::AsRawFd, rc::Rc, }; use failure::Fail; use os_pipe::{pipe, PipeReader}; use wayland_client::{ConnectError, EventQueue}; use wayland_protocols::wlr::unstable::data_control::v1::client::zwlr_data_contr...
lipboard == ClipboardType::Primary; let (mut queue, offer) = get_offer(primary, seat, socket_name)?; let mut mime_types = offer.as_ref() .user_data::<RefCell<HashSet<String>>>() .unwrap() .borrow_mut(); let mime...
seat: Seat<'_>, mime_type: MimeType<'_>, socket_name: Option<OsString>) -> Result<(PipeReader, String), Error> { let primary = c
random
[ { "content": "#[inline]\n\npub fn clear(clipboard: ClipboardType, seat: Seat<'_>) -> Result<(), Error> {\n\n clear_internal(clipboard, seat, None)\n\n}\n\n\n\npub(crate) fn clear_internal(clipboard: ClipboardType,\n\n seat: Seat<'_>,\n\n socket_name: Op...
Rust
src/env.rs
cjreed121/Telescope
6b3435efabcbe50da394beee8db629ca8e1927a6
use oauth2::{ClientId, ClientSecret}; use std::sync::Arc; use std::{collections::HashMap, env, path::PathBuf}; use std::{fs::File, io::Read, process::exit}; use structopt::StructOpt; #[derive(Clone, Debug, Serialize, Deserialize)] pub struct GithubOauthConfig { pub client_id: ClientId, pub client_sec...
use oauth2::{ClientId, ClientSecret}; use std::sync::Arc; use std::{collections::HashMap, env, path::PathBuf}; use std::{fs::File, io::Read, process::exit}; use structopt::StructOpt; #[derive(Clone, Debug, Serialize, Deserialize)] pub struct GithubOauthConfig { pub client_id: ClientId, pub client_sec...
pub fn global_config() -> Arc<ConcreteConfig> { CONFIG.clone() } fn cli() -> ConcreteConfig { dotenv::dotenv().ok(); let commandline: CommandLine = CommandLine::from_args(); let mut confing_file_string = String::new(); File::open(&commandline.config_file) .map_err(|e| { ...
pub fn init() { let cfg: &ConcreteConfig = &*CONFIG; env_logger::builder().parse_filters(&cfg.log_level).init(); info!("Starting up..."); info!("telescope {}", env!("CARGO_PKG_VERSION")); trace!("Config: \n{}", serde_json::to_string_pretty(cfg).unwrap()); }
function_block-full_function
[ { "content": "/// Register services into actix app.\n\npub fn register(config: &mut ServiceConfig) {\n\n config\n\n .service(profile)\n\n .service(settings)\n\n .service(save_changes);\n\n}\n\n\n\n/// User profile service. The target's user ID is in the path.\n\n#[get(\"/user/{id}\")]\n\...
Rust
engine/src/egui/res.rs
arcana-engine/arcana
e641ecfdf48c2844cf886834ad3aa981d3be7168
use egui::{AlphaImage, ClippedMesh, ColorImage, Context, ImageData, TextureId, TexturesDelta}; use hashbrown::hash_map::{Entry, HashMap}; use sierra::{ AccessFlags, ComponentMapping, Encoder, Extent2d, Extent3d, ImageInfo, ImageView, ImageViewInfo, Offset3d, OutOfMemory, SubresourceLayers, }; use winit::{event:...
use egui::{AlphaImage, ClippedMesh, ColorImage, Context, ImageData, TextureId, TexturesDelta}; use hashbrown::hash_map::{Entry, HashMap}; use sierra::{ AccessFlags, ComponentMapping, Encoder, Extent2d, Extent3d, ImageInfo, ImageView, ImageViewInfo, Offset3d, OutOfMemory, SubresourceLayers, }; use winit::{event:...
pub fn free_textures(&mut self) -> impl Iterator<Item = TextureId> + '_ { struct FreeTextures<'a> { iter: std::vec::Drain<'a, TextureId>, egui_textures: &'a mut HashMap<u64, ImageView>, user_textures: &'a mut HashMap<u64, ImageView>, } impl Iterator for...
let (view, new) = match self.egui_textures.entry(id) { Entry::Vacant(entry) => { let image = graphics.create_image(ImageInfo { extent: Extent2d { width: size[0] as _, height: size[1] a...
function_block-function_prefix_line
[ { "content": "#[allow(unused)]\n\n#[inline(always)]\n\nfn mat3_na_to_sierra(m: na::Matrix3<f32>) -> sierra::mat3<f32> {\n\n let array: [[f32; 3]; 3] = m.into();\n\n sierra::mat3::from(array)\n\n}\n", "file_path": "engine/src/graphics/renderer/mod.rs", "rank": 0, "score": 234182.95914786286 }...
Rust
c-pallets/file-bank/src/lib.rs
CESSProject/cess-node
f792146b26c8974a90370b73913b11cd29dca62f
#![cfg_attr(not(feature = "std"), no_std)] use frame_support::traits::{Currency, ReservableCurrency, ExistenceRequirement::AllowDeath}; pub use pallet::*; mod benchmarking; pub mod weights; use sp_std::convert::TryInto; use scale_info::TypeInfo; use sp_runtime::{ RuntimeDebug, traits::AccountIdConversion, }; use ...
#![cfg_attr(not(feature = "std"), no_std)] use frame_support::traits::{Currency, ReservableCurrency, ExistenceRequirement::AllowDeath}; pub use pallet::*; mod benchmarking; pub mod weights; use sp_std::convert::TryInto; use scale_info::TypeInfo; use sp_runtime::{ RuntimeDebug, traits::AccountIdConversion, }; use ...
#[pallet::weight(T::WeightInfo::update())] pub fn update(origin: OriginFor<T>, fileid: Vec<u8>, ispublic: u8, similarityhash: Vec<u8>) -> DispatchResult{ let sender = ensure_signed(origin)?; ensure!((<File<T>>::contains_key(fileid.clone())), Error::<T>::FileNonExistent); <File<T>...
pub fn upload( origin: OriginFor<T>, filename:Vec<u8>, address:Vec<u8>, fileid: Vec<u8>, filehash: Vec<u8>, similarityhash: Vec<u8>, ispublic: u8, backups: u8, creator: Vec<u8>, filesize: u128, keywords: Vec<u8>, email: Vec<u8>, uploadfee:BalanceOf<T>, downloadfee:BalanceOf<T>,...
function_block-full_function
[ { "content": "/// Weight functions needed for pallet_file_bank.\n\npub trait WeightInfo {\n\n\t\n\n\tfn upload() -> Weight;\n\n\t\n\n\tfn update() -> Weight;\n\n\t\n\n}\n\n\n\n/// Weights for pallet_file_bank using the Substrate node and recommended hardware.\n\npub struct SubstrateWeight<T>(PhantomData<T>);\n\...
Rust
gistit-cli/src/send.rs
demfabris/gistit
bdfec68d45dd837d2e4266324175aa0e599de71d
use std::ffi::OsStr; use std::fs; use std::path::{Path, PathBuf}; use std::str; use std::time::{SystemTime, UNIX_EPOCH}; use async_trait::async_trait; use clap::ArgMatches; use console::style; use reqwest::StatusCode; use gistit_proto::payload::{hash, Gistit}; use gistit_proto::prost::Message; use gistit_proto::{ipc,...
use std::ffi::OsStr; use std::fs; use std::path::{Path, PathBuf}; use std::str; use std::time::{SystemTime, UNIX_EPOCH}; use async_trait::async_trait; use clap::ArgMatches; use console::style; use reqwest::StatusCode; use gistit_proto::payload::{hash, Gistit}; use gistit_proto::prost::Message; use gistit_proto::{ipc,...
warnln!( "storing github token at: '{}'", gistit_project::path::config()?.to_string_lossy() ); } updateln!("Authorized"); oauth.token } else { None }; Ok(Config { ...
maybe_stdin, description: args.value_of("description"), author: args .value_of("author") .ok_or(Error::Argument("missing argument", "--author"))?, clipboard: args.is_present("clipboard"), github: args.is_present("github"), ...
random
[ { "content": "pub fn preview_or_save(gistit: &Gistit, save: bool, config: &Config) -> Result<()> {\n\n // NOTE: Currently we support one file\n\n let inner = gistit.inner.first().expect(\"to have at least one file\");\n\n let mut file = File::from_data(&inner.data, &inner.name)?;\n\n let save_locati...
Rust
polyfuse/src/session.rs
house-of-vanity/polyfuse
d5f25084ae7ca893e002b20562f1d545bc323c82
#![allow(clippy::needless_update)] use crate::{ common::StatFs, context::Context, fs::Filesystem, init::ConnectionInfo, io::{Reader, ReaderExt, Writer, WriterExt}, kernel::{ fuse_notify_code, fuse_notify_delete_out, fuse_notify_inval_entry_out, fuse_notify_inv...
#![allow(clippy::needless_update)] use crate::{ common::StatFs, context::Context, fs::Filesystem, init::ConnectionInfo, io::{Reader, ReaderExt, Writer, WriterExt}, kernel::{ fuse_notify_code, fuse_notify_delete_out, fuse_notify_inval_entry_out, fuse_notify_inv...
.await } pub async fn notify_delete<W: ?Sized>( &self, writer: &mut W, parent: u64, child: u64, name: impl AsRef<OsStr>, ) -> io::Result<()> where W: Writer + Unpin, { if self.exited() { retur...
send_notify( writer, fuse_notify_code::FUSE_NOTIFY_INVAL_ENTRY, &[unsafe { as_bytes(&out) }, name.as_bytes(), &[0]], )
call_expression
[ { "content": "/// Unite a pair of `Reader` and `Writer` as an I/O.\n\npub fn unite<R, W>(reader: R, writer: W) -> Unite<R, W>\n\nwhere\n\n R: Reader,\n\n W: Writer,\n\n{\n\n Unite { reader, writer }\n\n}\n\n\n\npin_project! {\n\n /// The united I/O of a pair of `Reader` and `Writer`.\n\n #[derive...
Rust
may_queue/src/mpsc_list_v1.rs
Easonzero/may
5e1fe6392360267c092e7c5879ab96e5d68fc28d
use std::cell::UnsafeCell; use std::ptr; use std::sync::atomic::{AtomicPtr, Ordering}; use std::thread; use crossbeam::utils::CachePadded; struct Node<T> { prev: *mut Node<T>, next: AtomicPtr<Node<T>>, value: Option<T>, refs: usize, } const REF_INIT: usize = 0x1000_0002; const REF_COUNT_MASK: usize =...
use std::cell::UnsafeCell; use std::ptr; use std::sync::atomic::{AtomicPtr, Ordering}; use std::thread; use crossbeam::utils::CachePadded; struct Node<T> { prev: *mut Node<T>, next: AtomicPtr<Node<T>>, value: Option<T>, refs: usize, } const REF_INIT: usize = 0x1000_0002; const REF_COUNT_MASK: usize =...
ush(4); assert_eq!(a.1, true); assert_eq!(a.0.remove(), Some(3)); assert_eq!(b.1, false); assert_eq!(b.0.remove(), None); assert_eq!(q.pop(), Some(4)); assert_eq!(q.is_empty(), true); q.push(5); q.push(6); q.push(7); let co = |v: &usize| *...
pub fn pop_if<F>(&self, f: &F) -> Option<T> where F: Fn(&T) -> bool, { unsafe { let tail = *self.tail.get(); if self.head.load(Ordering::Acquire) == tail { return None; } let mut next; let ...
random
[ { "content": "#[inline]\n\npub fn bulk_end(start: usize, end: usize, mut expect: usize) -> usize {\n\n if expect == 0 {\n\n expect = BLOCK_SIZE;\n\n }\n\n let size0 = end.wrapping_sub(start);\n\n let size1 = BLOCK_SIZE - (start & BLOCK_MASK);\n\n // only pop within a block\n\n expect = ...
Rust
services/scabbard/libscabbard/src/service/factory.rs
dcmiddle/splinter
1f9ab602a842db4dadbfb23b4927e2a0944dc723
use std::collections::{HashMap, HashSet}; use std::iter::FromIterator; use std::path::Path; use std::time::Duration; use cylinder::VerifierFactory; #[cfg(feature = "service-arg-validation")] use splinter::service::validation::{ServiceArgValidationError, ServiceArgValidator}; use splinter::service::{FactoryCreateErro...
use std::collections::{HashMap, HashSet}; use std::iter::FromIterator; use std::path::Path; use std::time::Duration; use cylinder::VerifierFactory; #[cfg(feature = "service-arg-validation")] use splinter::service::validation::{ServiceArgValidationError, ServiceArgValidator}; use splinter::service::{FactoryCreateErro...
, }) .transpose()?; let service = Scabbard::new( service_id, circuit_id, peer_services, &state_db_dir, self.state_db_size, &receipt_db_dir, self.receipt_db_size, self.signature_verifier_facto...
Err(FactoryCreateError::InvalidArguments(format!( "invalid coordinator_timeout: {}", err )))
call_expression
[ { "content": "#[cfg(feature = \"scabbard-cli-jwt\")]\n\npub fn create_cylinder_jwt_auth(key_name: Option<&str>) -> Result<String, CliError> {\n\n let default_key_path = dirs::home_dir()\n\n .map(|mut p| {\n\n p.push(\".splinter/keys\");\n\n p\n\n })\n\n .ok_or_else(...
Rust
src/client/executor.rs
sladecek/mongo-rust-driver
ed8120b9d4b74db1a5e46da194bbd01020f408e3
use super::{Client, ClientSession}; use std::{collections::HashSet, sync::Arc}; use lazy_static::lazy_static; use time::PreciseTime; use crate::{ bson::Document, cmap::Connection, error::{Error, ErrorKind, Result}, event::command::{CommandFailedEvent, CommandStartedEvent, CommandSucceededEvent}, ...
use super::{Client, ClientSession}; use std::{collections::HashSet, sync::Arc}; use lazy_static::lazy_static; use time::PreciseTime; use crate::{ bson::Document, cmap::Connection, error::{Error, ErrorKind, Result}, event::command::{CommandFailedEvent, CommandStartedEvent, CommandSucceededEvent}, ...
} async fn get_session_support_status(&self) -> Result<SessionSupportStatus> { let initial_status = self.inner.topology.session_support_status().await; match initial_status { SessionSupportStatus::Undetermined => { let criteria = Selec...
luster_time.as_ref()); if let Some(cluster_time) = max_cluster_time { cmd.set_cluster_time(cluster_time); } let connection_info = connection.info(); let request_id = crate::cmap::conn::next_request_id(); self.emit_command_event(|handler| { let should_red...
random
[]
Rust
cli/tauri-bundler/src/bundle/osx_bundle.rs
proudmuslim-dev/tauri
71a3e7126846cc98e10c6fd5e86b6ae7ee5eb7d4
use super::common; use crate::Settings; use anyhow::Context; use image::{self, GenericImageView}; use std::cmp::min; use std::ffi::OsStr; use std::fs::{self, File}; use std::io::prelude::*; use std::io::{self, BufWriter}; use std::path::{Path, PathBuf}; use std::process::{Command, Stdio}; pub fn bundle_project(set...
use super::common; use crate::Settings; use anyhow::Context; use image::{self, GenericImageView}; use std::cmp::min; use std::ffi::OsStr; use std::fs::{self, File}; use std::io::prelude::*; use std::io::{self, BufWriter}; use std::path::{Path, PathBuf}; use std::process::{Command, Stdio}; pub fn bundle_project(set...
fn make_icns_image(img: image::DynamicImage) -> io::Result<icns::Image> { let pixel_format = match img.color() { image::ColorType::Rgba8 => icns::PixelFormat::RGBA, image::ColorType::Rgb8 => icns::PixelFormat::RGB, image::ColorType::La8 => icns::PixelFormat::GrayAlpha, image::ColorType::L8 => icns::...
mage(icon)?; family.add_icon_with_type(&icon, icon_type)?; } Ok(()) } None => Err(io::Error::new( io::ErrorKind::InvalidData, "No matching IconType", )), } } let mut images_to_resize: Vec<(image::DynamicImage, u32, u32)> = vec![]; for icon_path in s...
function_block-function_prefixed
[]
Rust
src/models/web/auth.rs
reslario/web-quiz
4077e243520c9b2738b969ef016b5d5217eac595
use { uuid::Uuid, derive_more::Deref, owning_ref::MutexGuardRef, crate::models::web::{SyncedAdminSessions, Or500, AdminSessions}, rocket::{ State, Request, Outcome, Response, response::Responder, outcome::IntoOutcome, http::{Cookie, Status}, ...
use { uuid::Uuid, derive_more::Deref, owning_ref::MutexGuardRef, crate::models::web::{SyncedAdminSessions, Or500, AdminSessions}, rocket::{ State, Request, Outcome, Response, response::Responder, outcome::IntoOutcome, http::{Cookie, Status}, ...
} #[derive(Debug, Deref, Ord, PartialOrd, Eq, PartialEq, Hash)] pub struct Admin(Session); pub struct AdminGuard<'a>(MutexGuardRef<'a, AdminSessions, Admin>); impl <'a, 'r> FromRequest<'a, 'r> for AdminGuard<'a> { type Error = (); fn from_request(request: &'a Request<'r>) -> request::Outcome<Self, Self::Er...
fn from_request(request: &'a Request<'r>) -> request::Outcome<Self, Self::Error> { let sess = Session::new(); request .cookies() .add_private(Cookie::new(SESSION_COOKIE, sess.id.to_string())); Outcome::Success(NewSession(sess)) }
function_block-full_function
[ { "content": "pub fn init_admin_sessions() -> SyncedAdminSessions {\n\n Mutex::new(HashSet::new())\n\n}\n", "file_path": "src/models/web/state.rs", "rank": 0, "score": 135998.34979099507 }, { "content": "pub fn answer(answer: &str, game_state: &mut GameState, conn: &PgConnection) -> Resul...
Rust
etk-dasm/src/blocks/basic.rs
quilt/gencfg
4fced9f5bc070d419cab54eca8c8a12176b134fa
use etk_asm::disasm::Offset; use etk_asm::ops::{ConcreteOp, Metadata}; use std::convert::TryInto; #[derive(Debug, Eq, PartialEq)] pub struct BasicBlock { pub offset: usize, pub ops: Vec<ConcreteOp>, } impl BasicBlock { pub fn size(&self) -> usize { let sum: u32 = self.ops.iter()....
use etk_asm::disasm::Offset; use etk_asm::ops::{ConcreteOp, Metadata}; use std::convert::TryInto; #[derive(Debug, Eq, PartialEq)] pub struct BasicBlock { pub offset: usize, pub ops: Vec<ConcreteOp>, } impl BasicBlock { pub fn size(&self) -> usize { let sum: u32 = self.ops.iter()....
#[test] fn jumpdest_jump_jumpdest_jump() { let ops = vec![ Offset::new(0x00, ConcreteOp::JumpDest), Offset::new(0x01, ConcreteOp::Jump), Offset::new(0x02, ConcreteOp::JumpDest), Offset::new(0x03, ConcreteOp::Jump), ]; let blocks = [ ...
fn three_jumpdests() { let ops = vec![ Offset::new(0x00, ConcreteOp::JumpDest), Offset::new(0x01, ConcreteOp::JumpDest), Offset::new(0x02, ConcreteOp::JumpDest), ]; let blocks = [ BasicBlock { offset: 0x00, ops: vec...
function_block-full_function
[ { "content": "#[doc(hidden)]\n\npub trait Immediate<const N: usize>: Debug + Clone + Eq + PartialEq {\n\n fn extra_len() -> usize {\n\n N\n\n }\n\n}\n\n\n\nimpl<T, const N: usize> Immediate<N> for [T; N] where T: Debug + Clone + Eq + PartialEq {}\n\nimpl<const N: usize> Immediate<N> for Imm<[u8; N]...
Rust
src/librustc_codegen_llvm/back/rpath.rs
canndrew/rust
bf7afee52a2e92a509eae1e9530ee75da8f9f621
use std::collections::HashSet; use std::env; use std::path::{Path, PathBuf}; use std::fs; use rustc::hir::def_id::CrateNum; use rustc::middle::cstore::LibSource; pub struct RPathConfig<'a> { pub used_crates: &'a [(CrateNum, LibSource)], pub out_filename: PathBuf, pub is_like_osx: bool, pub has_rpath...
use std::collections::HashSet; use std::env; use std::path::{Path, PathBuf}; use std::fs; use rustc::hir::def_id::CrateNum; use rustc::middle::cstore::LibSource; pub struct RPathConfig<'a> { pub used_crates: &'a [(CrateNum, LibSource)], pub out_filename: PathBuf, pub is_like_osx: bool, pub has_rpath...
#[test] fn test_minimize2() { let res = minimize_rpaths(&[ "1a".to_string(), "2".to_string(), "2".to_string(), "1a".to_string(), "4a".to_string(), "1a".to_string(), "2".to_string(), "3".to_string(), ...
fn test_minimize1() { let res = minimize_rpaths(&[ "rpath1".to_string(), "rpath2".to_string(), "rpath1".to_string() ]); assert!(res == [ "rpath1", "rpath2", ]); }
function_block-full_function
[]
Rust
common/exception/src/exception_code.rs
datafuselabs/databend
9d56f04e5671ca43309f8ba3c1c06183ae62285a
#![allow(non_snake_case)] use std::backtrace::Backtrace; use std::sync::Arc; use crate::exception::ErrorCodeBacktrace; use crate::ErrorCode; pub static ABORT_SESSION: u16 = 1042; pub static ABORT_QUERY: u16 = 1043; macro_rules! build_exceptions { ($($body:ident($code:expr)),*$(,)*) => { impl Error...
#![allow(non_snake_case)] use std::backtrace::Backtrace; use std::sync::Arc; use crate::exception::ErrorCodeBacktrace; use crate::ErrorCode; pub static ABORT_SESSION: u16 = 1042; pub static ABORT_QUERY: u16 = 1043; macro_rules! build_exceptions { ($($body:ident($code:expr)),*$(,)*) => { impl Error...
nfoFormat(2203), UnknownRole(2204), IllegalUserSettingFormat(2205), DatabaseAlreadyExists(2301), TableAlreadyExists(2302), IllegalMetaState(2304), MetaNodeInternalError(2305), ViewAlreadyExists(2306), CreateTableWithDropTime(2307), UndropTableAlreadyExists(2308), UndropTabl...
antIsEmpty(1101), IndexOutOfBounds(1102), LayoutError(1103), PanicError(1104), } build_exceptions! { MetaServiceError(2001), InvalidConfig(2002), MetaStorageError(2003), TableVersionMismatched(2009), OCCRetryFailure(2011), TableNotWritable(2012), TableHistoricalData...
random
[ { "content": "pub fn match_text(text: &'static str) -> impl FnMut(Input) -> IResult<&Token> {\n\n move |i| match i.0.get(0).filter(|token| token.text() == text) {\n\n Some(token) => Ok((i.slice(1..), token)),\n\n _ => Err(nom::Err::Error(Error::from_error_kind(\n\n i,\n\n ...
Rust
src/interactive/app/eventloop.rs
tim77/dua-cli
96ff5ab74a70dd908f5dd218077cd2382e08d9f1
use crate::interactive::{ sorted_entries, widgets::{MainWindow, MainWindowProps}, ByteVisualization, CursorDirection, DisplayOptions, EntryDataBundle, SortMode, }; use dua::{ traverse::{Traversal, TreeIndex}, WalkOptions, WalkResult, }; use failure::Error; use std::{collections::BTreeMap, io, path::...
use crate::interactive::{ sorted_entries, widgets::{MainWindow, MainWindowProps}, ByteVisualization, CursorDirection, DisplayOptions, EntryDataBundle, SortMode, }; use dua::{ traverse::{Traversal, TreeIndex}, WalkOptions, WalkResult, }; use failure::Error; use std::{collections::BTreeMap, io, path::...
} }
Ok(TerminalApp { state: AppState { root, sorting, selected, entries, ..Default::default() }, display: display_options, traversal, window: Default::default(), })
call_expression
[ { "content": "fn cwd_dirlist() -> Result<Vec<PathBuf>, io::Error> {\n\n let mut v: Vec<_> = fs::read_dir(\".\")?\n\n .filter_map(|e| {\n\n e.ok()\n\n .and_then(|e| e.path().strip_prefix(\".\").ok().map(ToOwned::to_owned))\n\n })\n\n .collect();\n\n v.sort();\...
Rust
hal/src/sercom/v2/uart/config.rs
Alexander89/atsamd
16ff6e0afd3e5e01084149ad033ac04f5eb9fd82
use super::{ BaudMode, BitOrder, Capability, CharSize, CharSizeEnum, DataReg, DynCharSize, EightBit, FixedCharSize, Parity, Registers, StopBits, Uart, ValidConfig, ValidPads, }; use crate::{ pac, sercom::v2::*, time::Hertz, typelevel::{Is, Sealed}, }; use core::marker::PhantomData; use num_tra...
use super::{ BaudMode, BitOrder, Capability, CharSize, CharSizeEnum, DataReg, DynCharSize, EightBit, FixedCharSize, Parity, Registers, StopBits, Uart, ValidConfig, ValidPads, }; use crate::{ pac, sercom::v2::*, time::Hertz, typelevel::{Is, Sealed}, }; use core::marker::PhantomData; use n
self } #[inline] pub fn set_irda_encoding(&mut self, pulse_length: Option<u8>) { self.registers.set_irda_encoding(pulse_length); } #[inline] pub fn get_irda_encoding(&self) -> Option<u8> { self.registers.get_irda_encoding() } } i...
um_traits::{AsPrimitive, PrimInt}; pub struct Config<P, C = EightBit> where P: ValidPads, C: CharSize, { pub(super) registers: Registers<P::Sercom>, pads: P, chsize: PhantomData<C>, freq: Hertz, } #[cfg(any(feature = "samd11", feature = "samd21"))] pub type Clock = pac::PM; #[cfg(feature = "m...
random
[]
Rust
third-party/arti-client/examples/hook-tcp.rs
capyloon/api-daemon
ab4e4b60aa9bb617734c64655c0b8940fff098bc
use std::future::Future; use std::io::Result as IoResult; use std::net::SocketAddr; use std::pin::Pin; use std::task::{Context, Poll}; use anyhow::Result; use arti_client::{TorClient, TorClientConfig}; use tokio_crate as tokio; use futures::{AsyncRead, AsyncWrite, FutureExt, Stream}; use tor_rtcompat::{CompoundRunt...
use std::future::Future; use std::io::Result as IoResult; use std::net::SocketAddr; use std::pin::Pin; use std::task::{Context, Poll}; use anyhow::Result; use arti_client::{TorClient, TorClientConfig}; use tokio_crate as tokio; use futures::{AsyncRead, AsyncWrite, FutureExt, Stream}; use tor_rtcompat::{CompoundRunt...
fn listen<'a, 'b, 'c>( &'a self, addr: &'b SocketAddr, ) -> Pin<Box<dyn Future<Output = IoResult<Self::TcpListener>> + Send + 'c>> where 'a: 'c, 'b: 'c, Self: 'c, { println!("tcp listen on {}", addr); self.inner ...
fn connect<'a, 'b, 'c>( &'a self, addr: &'b SocketAddr, ) -> Pin<Box<dyn Future<Output = IoResult<Self::TcpStream>> + Send + 'c>> where 'a: 'c, 'b: 'c, Self: 'c, { println!("tcp connect to {}", addr); self.inner .connect(a...
function_block-full_function
[]