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
pallet/src/mock.rs
maciejnems/aleph-node
24fe79f21530e4436b4bc350ba022af825f3a15f
#![cfg(test)] use super::*; use crate as pallet_aleph; use frame_support::{ construct_runtime, parameter_types, sp_io, traits::{OnFinalize, OnInitialize}, weights::RuntimeDbWeight, }; use primitives::AuthorityId; use sp_core::H256; use sp_runtime::{ impl_opaque_keys, testing::{Header, TestXt, Uint...
#![cfg(test)] use super::*; use crate as pallet_aleph; use frame_support::{ construct_runtime, parameter_types, sp_io, traits::{OnFinalize, OnInitialize}, weights::RuntimeDbWeight, }; use primitives::AuthorityId; use sp_core::H256; use sp_runtime::{ impl_opaque_keys, testing::{Header, TestXt, Uint...
lect() } pub fn new_test_ext(authorities: &[(u64, u64)]) -> sp_io::TestExternalities { let mut t = frame_system::GenesisConfig::default() .build_storage::<Test>() .unwrap(); let balances: Vec<_> = (0..authorities.len()) .map(|i| (i as u64, 10_000_000)) .collect(); pallet_b...
nager<Self>; type SessionHandler = <TestSessionKeys as OpaqueKeys>::KeyTypeIdProviders; type Keys = TestSessionKeys; type DisabledValidatorsThreshold = DisabledValidatorsThreshold; type WeightInfo = (); } impl<C> frame_system::offchain::SendTransactionTypes<C> for Test where Call: From<C>, { ty...
random
[ { "content": "pub fn session_id_from_block_num<B: Block>(num: NumberFor<B>, period: SessionPeriod) -> SessionId {\n\n SessionId(num.saturated_into::<u32>() / period.0)\n\n}\n\n\n\npub struct AlephConfig<B: Block, N, C, SC> {\n\n pub network: N,\n\n pub client: Arc<C>,\n\n pub select_chain: SC,\n\n ...
Rust
src/systems/collision.rs
Jazarro/space-menace
8be706d2e993d594557ec3f88d5ac2d331b955d7
use amethyst::{ core::{math::Vector2, Named, Transform}, ecs::{Entities, Join, LazyUpdate, ReadExpect, ReadStorage, System, WriteStorage}, }; use crate::{ components::{ Boundary, Bullet, Collidee, CollideeDetails, Collider, Direction, Directions, Flier, FlierAi, Marine, Motion, Pincer, Pinc...
use amethyst::{ core::{math::Vector2, Named, Transform}, ecs::{Entities, Join, LazyUpdate, ReadExpect, ReadStorage, System, WriteStorage}, }; use crate::{ components::{ Boundary, Bullet, Collidee, CollideeDetails, Collider, Direction, Directions, Flier, FlierAi, Marine, Motion, Pincer, Pinc...
ider_a.is_collidable { for (entity_b, collider_b, motion_b, name_b) in (&entities, &colliders, &motions, &names).join() { let velocity_b = motion_b.velocity; let use_hit_box = (velocity_a.x * velocity_b.x...
type SystemData = ( Entities<'s>, ReadStorage<'s, Collider>, WriteStorage<'s, Collidee>, ReadStorage<'s, Boundary>, ReadStorage<'s, Motion>, ReadStorage<'s, Named>, ); fn run(&mut self, data: Self::SystemData) { let (entities, colliders, mut collidee...
random
[ { "content": "pub fn load_marine(world: &mut World, prefab: Handle<Prefab<AnimationPrefabData>>, ctx: &Context) {\n\n let scale = ctx.scale;\n\n let mut transform = Transform::default();\n\n transform.set_scale(Vector3::new(scale, scale, scale));\n\n transform.set_translation_x(384.);\n\n transfo...
Rust
day_12/src/main.rs
kimpers/advent-of-code-2020
50750317b691717e211c03c67b99708edccddfc3
use shared; #[derive(Debug)] struct NavigatorV1<'a> { facing_direction: &'a str, north: usize, west: usize, east: usize, south: usize, } impl NavigatorV1<'_> { fn new(facing_direction: &str) -> NavigatorV1 { NavigatorV1 { facing_direction, north: 0, ...
use shared; #[derive(Debug)] struct NavigatorV1<'a> { facing_direction: &'a str, north: usize, west: usize, east: usize, south: usize, } impl NavigatorV1<'_> { fn new(facing_direction: &str) -> NavigatorV1 { NavigatorV1 { facing_direction, north: 0, ...
println!( "Manhattan distance between location and starting position using method 2 is {}", navigator2.manhattan_distance() ); } #[cfg(test)] mod tests { use super::*; #[test] fn it_calculates_manhattan_distance() { let actions = shared::parse_input_to_string_vec( ...
} else { self.north += distance - self.south; self.south = 0; } } "S" => { let new_north = self.north as isize - distance as isize; if new_north > 0 { self.north = new_north as usize; ...
random
[ { "content": "pub fn read_file(filename: &str) -> Vec<String> {\n\n let mut file = File::open(filename).unwrap();\n\n let mut contents = String::new();\n\n\n\n file.read_to_string(&mut contents).unwrap();\n\n let lines = contents\n\n .lines()\n\n .map(|l| l.to_string())\n\n .col...
Rust
truck-meshalgo/src/analyzers/topology.rs
roudy16/truck
b92af7761302a5d16b5e52b15f1be7b6c4dfd460
use super::*; use rustc_hash::{FxHashMap as HashMap, FxHashSet as HashSet}; use truck_topology::shell::ShellCondition; pub trait Topology { fn extract_boundaries(&self) -> Vec<Vec<usize>>; fn shell_condition(&self) -> ShellCondition; } #[derive(Clone, Debug)] struct Boundaries { ...
use super::*; use rustc_hash::{FxHashMap as HashMap, FxHashSet as HashSet}; use truck_topology::shell::ShellCondition; pub trait Topology { fn extract_boundaries(&self) -> Vec<Vec<usize>>; fn shell_condition(&self) -> ShellCondition; } #[derive(Clone, Debug)] struct Boundaries { ...
; } #[inline(always)] fn condition(&self) -> ShellCondition { if self.condition == ShellCondition::Oriented && self.boundary.is_empty() { ShellCondition::Closed } else { self.condition } } } impl FromIterator<[Vertex; 2]> for Boundaries { fn from_ite...
match (self.checked.insert(edge), self.boundary.insert(edge, ori)) { (true, None) => ShellCondition::Oriented, (false, None) => ShellCondition::Irregular, (true, Some(_)) => panic!("unexpected case!"), (false, Some(ori0)) => { self.boun...
if_condition
[ { "content": "#[inline(always)]\n\npub fn vertex(pt: Point3) -> Vertex { Vertex::new(pt) }\n\n\n\n/// Returns a line from `vertex0` to `vertex1`.\n\n/// # Examples\n\n/// ```\n\n/// use truck_modeling::*;\n\n///\n\n/// // draw a line\n\n/// let vertex0 = builder::vertex(Point3::new(1.0, 2.0, 3.0));\n\n/// let v...
Rust
qapro-rs/src/qaruntime/monitor.rs
B34nK0/QUANTAXIS
94162f0f863682e443ef8ae11f5b54da6f93421b
extern crate redis; use actix::prelude::*; use actix::{Actor, Addr, AsyncContext, Context, Handler, Recipient, Supervised}; use chrono::{Local, TimeZone}; use log::{error, info, warn}; use redis::Commands; use serde_json::Value; use std::fmt::Debug; use std::time::Duration; use uuid::Version::Mac; use crate::qaaccount...
extern crate redis; use actix::prelude::*; use actix::{Actor, Addr, AsyncContext, Context, Handler, Recipient, Supervised}; use chrono::{Local, TimeZone}; use log::{error, info, warn}; use redis::Commands; use serde_json::Value; use std::fmt::Debug; use std::time::Duration; use uuid::Version::Mac; use crate::qaaccount...
let m = "send_order success".to_owned(); self.ack(instruct, 200, m); } Err(e) => { let m = format!("Instruct order parse fail {}", e.to_string()); self.ack(instruct, 400, m); } } } pub fn get_clock(&mut...
if order.direction.eq("SELL") && order.offset.eq("CLOSE") { self.qactx .sell_close(&code, order.volume, &time, order.price) } else { let m = "send_order fail".to_owned(); self.ack(instruct, 400, m); ...
if_condition
[ { "content": "pub fn set_bar(redis: Addr<RedisActor>, key: &str, data: String) {\n\n info!(\"write data to redis\");\n\n let fut1 = redis.do_send(Command(resp_array![\"set\", key, data]));\n\n}\n\n\n\npub async fn set_bar_async(redis: Addr<RedisActor>, key: String, data: String) {\n\n let keys = key.as...
Rust
src/integer/conversions.rs
declanvk/rimath
e0dbb421d6da09a8b5e92fc9f0d00e5a454e3118
use crate::{error::Error, integer::Integer}; use core::convert::{TryFrom, TryInto}; impl From<i8> for Integer { fn from(src: i8) -> Self { Self::from_c_long(src) } } impl From<&i8> for Integer { fn from(src: &i8) -> Self { Self::from_c_long(*src) } } impl TryFrom<Integer> for i8 { ...
use crate::{error::Error, integer::Integer}; use core::convert::{TryFrom, TryInto}; impl From<i8> for Integer { fn from(src: i8) -> Self { Self::from_c_long(src) } } impl From<&i8> for Integer { fn from(src: &i8) -> Self { Self::from_c_long(*src) } } impl TryFrom<Integer> for i8 { ...
fn from(src: &i128) -> Self { Self::from_string_repr(*src, 10).expect("Conversion from string failed") } } impl TryFrom<Integer> for i128 { type Error = Error; fn try_from(src: Integer) -> Result<Self, Self::Error> { src.to_string() .parse() .map_err(|_| Error::Con...
} } impl TryFrom<&Integer> for i16 { type Error = Error; fn try_from(src: &Integer) -> Result<Self, Self::Error> { src.try_into_c_long() .and_then(|value| value.try_into().map_err(From::from)) } } impl From<u16> for Integer { fn from(src: u16) -> Self { Self::from_c_long(s...
random
[ { "content": "fn fib_iter() -> impl Iterator<Item = Integer> {\n\n struct FibIter {\n\n x: Integer,\n\n y: Integer,\n\n }\n\n\n\n impl Iterator for FibIter {\n\n type Item = Integer;\n\n\n\n fn next(&mut self) -> Option<Integer> {\n\n let next_y = &self.x + &self....
Rust
examples/pong.rs
legendiguess/example-rs
c401fcc7b08556cd6f5bae71986b727ffced6578
use ggez::{ event::{self, EventHandler, KeyCode, KeyMods}, graphics::{self, DrawMode, DrawParam, FilterMode, Mesh, MeshBuilder, Rect, Text}, nalgebra as na, Context, ContextBuilder, GameResult, }; use mun_examples::marshal_vec2; use mun_runtime::{invoke_fn, RetryResultExt, Runtime, RuntimeBuilder, StructRef...
use ggez::{ event::{self, EventHandler, KeyCode, KeyMods}, graphics::{self, DrawMode, DrawParam, FilterMode, Mesh, MeshBuilder, Rect, Text}, nalgebra as na, Context, ContextBuilder, GameResult, }; use mun_examples::marshal_vec2; use mun_runtime::{invoke_fn, RetryResultExt, Runtime, RuntimeBuilder, StructRef...
} fn bounds(width: f32, height: f32) -> Rect { Rect::new(0.0, 0.0, width, height) } fn draw_mesh(ctx: &mut Context, mesh: &Mesh, object: &StructRef) -> GameResult { graphics::draw( ctx, mesh, ( marshal_vec2(&object.get("pos").unwrap()), 0.0, graphic...
w() .circle( DrawMode::fill(), na::Point2::origin(), invoke_fn!(self.runtime, "ball_radius").unwrap(), invoke_fn!(self.runtime, "ball_tolerance").unwrap(), graphics::WHITE, ) .build(ctx)?; draw_me...
function_block-function_prefixed
[ { "content": "fn textures(ctx: &mut Context) -> [(Texture, Vec2<f32>); 5] {\n\n [\n\n (\n\n Texture::new(ctx, \"./assets/spaceship/sprites/spaceship.png\").unwrap(),\n\n Vec2::new(6., 7.),\n\n ),\n\n (\n\n Texture::new(ctx, \"./assets/spaceship/sprites/ro...
Rust
libzmq/src/socket/dish.rs
dmweis/libzmq-rs
8b8384c3f65960d9c842e9c8d54883239ad47d33
use crate::{ addr::Endpoint, auth::*, core::*, error::*, Ctx, CtxHandle, Group, GroupSlice, }; use libzmq_sys as sys; use sys::errno; use serde::{Deserialize, Serialize}; use std::{ ffi::c_void, str, sync::{Arc, Mutex}, }; fn join(socket_mut_ptr: *mut c_void, group: &GroupSlice) -> Result<(), Err...
use crate::{ addr::Endpoint, auth::*, core::*, error::*, Ctx, CtxHandle, Group, GroupSlice, }; use libzmq_sys as sys; use sys::errno; use serde::{Deserialize, Serialize}; use std::{ ffi::c_void, str, sync::{Arc, Mutex}, }; fn join(socket_mut_ptr: *mut c_void, group: &GroupSlice) -> Result<(), Err...
pub fn groups(&self) -> Option<&[Group]> { self.groups.as_deref() } pub fn set_groups<I>(&mut self, maybe_groups: Option<I>) where I: IntoIterator<Item = Group>, { let groups = maybe_groups.map(|g| g.into_iter().collect()); self.groups = groups; } pub fn a...
n with_ctx(&self, handle: CtxHandle) -> Result<Dish, Error> { let dish = Dish::with_ctx(handle)?; self.apply(&dish)?; Ok(dish) }
function_block-function_prefixed
[ { "content": "fn connect(socket_ptr: *mut c_void, c_string: CString) -> Result<(), Error> {\n\n let rc = unsafe { sys::zmq_connect(socket_ptr, c_string.as_ptr()) };\n\n\n\n if rc == -1 {\n\n let errno = unsafe { sys::zmq_errno() };\n\n let err = match errno {\n\n errno::EINVAL => ...
Rust
rust/subproc/subproc.rs
ChristianVisintin/Brol
e53b663915697aa6543406db2f279e31826bff0c
/* * * Copyright (C) 2020 Christian Visintin - christian.visintin1997@gmail.com * * This file is part of "Pyc" * * Pyc is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License...
/* * * Copyright (C) 2020 Christian Visintin - christian.visintin1997@gmail.com * * This file is part of "Pyc" * * Pyc is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License...
#[test] fn test_process_start_error() { let mut shell_proc: ShellProc = ShellProc::start(vec![String::from("piroporopero")]).unwrap(); println!("A new subproc started with PID {}", shell_proc.pid); sleep(Duration::from_millis(1000)); assert_eq!(shell_proc.read_state(),...
fn test_process_start_stop() { let mut shell_proc: ShellProc = ShellProc::start(vec![String::from("sh")]).unwrap(); println!("A new subproc started with PID {}", shell_proc.pid); assert_eq!(shell_proc.state, SubProcState::Running); assert_ne!(shell_proc.pid, 0); assert_e...
function_block-full_function
[ { "content": "/// ### read_file\n\n/// \n\n/// Read entire file\n\npub fn read_file<P>(filename: P) -> io::Result<String> where P: AsRef<Path>, {\n\n std::fs::read_to_string(filename)\n\n}\n\n\n\n/// ### read_lines\n\n/// \n\n/// Read lines from file\n", "file_path": "rust/file-utils/file.rs", "rank"...
Rust
core/executor/runtime-test/src/lib.rs
HPIPS/HPIPS_Chain
9c4a5ee923af876c89bb2cc629fd96b11add8196
#![cfg_attr(not(feature = "std"), no_std)] #![cfg_attr(feature = "strict", deny(warnings))] #[cfg(feature = "std")] include!(concat!(env!("OUT_DIR"), "/wasm_binary.rs")); use rstd::{vec::Vec, slice, vec}; use runtime_io::{ set_storage, storage, clear_prefix, print, blake2_128, blake2_256, twox_128, twox_256, ed255...
#![cfg_attr(not(feature = "std"), no_std)] #![cfg_attr(feature = "strict", deny(warnings))] #[cfg(feature = "std")] include!(concat!(env!("OUT_DIR"), "/wasm_binary.rs")); use rstd::{vec::Vec, slice, vec}; use runtime_io::{ set_storage, storage, clear_prefix, print, blake2_128, blake2_256, twox_128, twox_256, ed255...
fn env_inc_counter(e: &mut State, args: &[sandbox::TypedValue]) -> Result<sandbox::ReturnValue, sandbox::HostError> { if args.len() != 1 { return Err(sandbox::HostError); } let inc_by = args[0].as_i32().ok_or_else(|| sandbox::HostError)?; e.counter += inc_by as u32; Ok(sandbox::ReturnValue::Value(sandbox...
1 { return Err(sandbox::HostError); } let condition = args[0].as_i32().ok_or_else(|| sandbox::HostError)?; if condition != 0 { Ok(sandbox::ReturnValue::Unit) } else { Err(sandbox::HostError) } }
function_block-function_prefixed
[ { "content": "/// Run whatever tests we have.\n\npub fn run_tests(mut input: &[u8]) -> Vec<u8> {\n\n\tuse runtime_io::print;\n\n\n\n\tprint(\"run_tests...\");\n\n\tlet block = Block::decode(&mut input).unwrap();\n\n\tprint(\"deserialized block.\");\n\n\tlet stxs = block.extrinsics.iter().map(Encode::encode).col...
Rust
src/lib.rs
Ekleog/netsim-embed
980e43f530bc760a338b89bbba0b4037e43aed60
use futures::channel::mpsc; use futures::future::Future; use futures::sink::SinkExt; use futures::stream::StreamExt; pub use netsim_embed_core::Ipv4Range; use netsim_embed_core::*; use netsim_embed_machine::*; use netsim_embed_nat::*; use netsim_embed_router::*; pub use pnet_packet::*; use std::net::Ipv4Addr; pub fn ...
use futures::channel::mpsc; use futures::future::Future; use futures::sink::SinkExt; use futures::stream::StreamExt; pub use netsim_embed_core::Ipv4Range; use netsim_embed_core::*; use netsim_embed_machine::*; use netsim_embed_nat::*; use netsim_embed_router::*; pub use pnet_packet::*; use std::net::Ipv4Addr; pub fn ...
}
range, router, machines, networks, } = self; smol::Task::spawn(router).detach(); Network { range, machines, networks, } }
function_block-function_prefix_line
[ { "content": "/// Spawns a thread in a new network namespace and configures a TUN interface that sends and\n\n/// receives IP packets from the tx/rx channels and runs some UDP/TCP networking code in task.\n\npub fn machine<F>(addr: Ipv4Addr, mask: u8, plug: Plug, task: F) -> thread::JoinHandle<F::Output>\n\nwhe...
Rust
src/libstd/ffi/c_str.rs
jauhien/rust
f3092b1d58fd7fba154e40f6b2279d67663298a5
use fmt; use iter::IteratorExt; use libc; use mem; use ops::Deref; use slice::{self, SliceExt}; use string::String; use vec::Vec; #[derive(Clone, PartialEq, PartialOrd, Eq, Ord, Hash)] pub struct CString { inner: Vec<libc::c_char>, } impl CString { pub fn from_sl...
use fmt; use iter::IteratorExt; use libc; use mem; use ops::Deref; use slice::{self, SliceExt}; use string::String; use vec::Vec; #[derive(Clone, PartialEq, PartialOrd, Eq, Ord, Hash)] pub struct CString { inner: Vec<libc::c_char>, } impl CString { pub fn from_sl...
#[test] fn simple() { let s = CString::from_slice(b"1234"); assert_eq!(s.as_bytes(), b"1234"); assert_eq!(s.as_bytes_with_nul(), b"1234\0"); unsafe { assert_eq!(&*s, mem::transmute::<_, &[libc::c_char]>(b"1234")); assert_eq!(s.as_s...
ta = b"123\0"; let ptr = data.as_ptr() as *const libc::c_char; unsafe { assert_eq!(c_str_to_bytes(&ptr), b"123"); assert_eq!(c_str_to_bytes_with_nul(&ptr), b"123\0"); } }
function_block-function_prefixed
[ { "content": "// same as cci_iter_lib, more-or-less, but not marked inline\n\npub fn iter<F>(v: Vec<uint> , mut f: F) where F: FnMut(uint) {\n\n let mut i = 0u;\n\n let n = v.len();\n\n while i < n {\n\n f(v[i]);\n\n i += 1u;\n\n }\n\n}\n", "file_path": "src/test/auxiliary/cci_no_i...
Rust
rs/crypto/internal/crypto_lib/threshold_sig/tecdsa/tests/complaints.rs
pipe-blockchain/ic
69d3263702ac3b52fd18c35dd1cc46de08d92073
use rand::Rng; use std::collections::BTreeMap; use tecdsa::*; fn corrupt_ciphertext_single( ctext: &[EccScalar], corruption_target: usize, ) -> ThresholdEcdsaResult<Vec<EccScalar>> { let mut ctext = ctext.to_vec(); let curve_type = ctext[corruption_target].curve_type(); let randomizer = EccScalar::...
use rand::Rng; use std::collections::BTreeMap; use tecdsa::*; fn corrupt_ciphertext_single( ctext: &[EccScalar], corruption_target: usize, ) -> ThresholdEcdsaResult<Vec<EccScalar>> { let mut ctext = ctext.to_vec(); let curve_type = ctext[corruption_target].curve_type(); let randomizer = EccScalar::...
} #[test] fn should_complaint_system_work() -> ThresholdEcdsaResult<()> { let curve = EccCurveType::K256; let associated_data = b"assoc_data_test"; let mut rng = rand::thread_rng(); let sk0 = MEGaPrivateKey::generate(curve, &mut rng)?; let pk0 = sk0.public_key()?; let sk1 = MEGaPrivateKey::...
Ok(IDkgDealingInternal { ciphertext, commitment: dealing.commitment.clone(), proof: dealing.proof.clone(), })
call_expression
[ { "content": "fn dealings(c: &mut Criterion) {\n\n c.bench_function(\"create_dealing(Random, 3/5)\", |b| {\n\n b.iter(|| create_random_dealing(3, 5))\n\n });\n\n\n\n c.bench_function(\"create_dealing(Random, 5/9)\", |b| {\n\n b.iter(|| create_random_dealing(5, 9))\n\n });\n\n}\n\n\n\nc...
Rust
src/ir/item.rs
dbdr/cargo-call-stack
681d8edad0d27f7cd25aac064c173968a08f304a
use nom::{types::CompleteStr, *}; use crate::ir::{define::Define, FnSig}; #[derive(Clone, Debug, PartialEq)] pub enum Item<'a> { Alias(&'a str, &'a str), Comment, SourceFilename, Target, Global, Type, Define(Define<'a>), Declare(Decla...
use nom::{types::CompleteStr, *}; use crate::ir::{define::Define, FnSig}; #[derive(Clone, Debug, PartialEq)] pub enum Item<'a> { Alias(&'a str, &'a str), Comment, SourceFilename, Target, Global, Type, Define(Define<'a>), Declare(Decla...
if name.starts_with("llvm.") { do_parse!( rest, not_line_ending >> (Item::Declare(Declare { name, sig: None })) ) } else { do_parse!( rest, inputs: separated_list!( do_parse!(char!(',') >> spac...
let (rest, (output, name)) = do_parse!( input, tag!("declare") >> space >> many0!(do_parse!(call!(super::attribute) >> space >> (()))) >> output: alt!(map!(call!(super::type_), Some) | map!(tag!("void"), |_| None)) >> space >> name: call!(super...
assignment_statement
[ { "content": "pub fn type_(input: CompleteStr) -> IResult<CompleteStr, Type> {\n\n let (rest, void) = opt!(input, tag!(\"void\"))?;\n\n\n\n if void.is_some() {\n\n // this must be a function\n\n let (mut rest, inputs) = do_parse!(rest, space >> inputs: fn_inputs >> (inputs))?;\n\n let...
Rust
sqlx-core/src/query.rs
rage311/sqlx
249efbd36b07ce609b6d946c3fcd50653a6eccd0
use std::marker::PhantomData; use async_stream::try_stream; use either::Either; use futures_core::stream::BoxStream; use futures_util::{future, StreamExt, TryFutureExt, TryStreamExt}; use crate::arguments::{Arguments, IntoArguments}; use crate::database::{Database, HasArguments}; use crate::encode::Encode; use crate:...
use std::marker::PhantomData; use async_stream::try_stream; use either::Either; use futures_core::stream::BoxStream; use futures_util::{future, StreamExt, TryFutureExt, TryStreamExt}; use crate::arguments::{Arguments, IntoArguments}; use crate::database::{Database, HasArguments}; use crate::encode::Encode; use crate:...
ither::Right(mapped); } } } }) } pub async fn fetch_all<'e, 'c: 'e, E>(self, executor: E) -> Result<Vec<O>, Error> where 'q: 'e, E: 'e + Executor<'c, Database = DB>, DB: 'e, F: 'e, O: 'e, { self...
lter_map(|step| async move { Ok(match step { Either::Left(_) => None, Either::Right(o) => Some(o), }) }) .boxed() } pub fn fetch_many<'e, 'c: 'e, E>( self, executor: E, ) -> BoxStream<'...
random
[ { "content": "#[inline]\n\npub fn query_as<'q, DB, O>(sql: &'q str) -> QueryAs<'q, DB, O, <DB as HasArguments<'q>>::Arguments>\n\nwhere\n\n DB: Database,\n\n O: for<'r> FromRow<'r, DB::Row>,\n\n{\n\n QueryAs {\n\n inner: query(sql),\n\n output: PhantomData,\n\n }\n\n}\n\n\n\n/// Make a...
Rust
src/base.rs
KeenS/kappaLisp
9f6726d49e278f40270994939d126285cd9b8d3b
use std::ops::Deref; use env::Env; use eval::funcall; use expr::{Error as E, Expr, Kfloat, Kint, Result, Type}; use util::*; macro_rules! expr { ($e:expr) => { $e }; } macro_rules! def_arith_op { ($name: ident, $op: tt, $init: expr) => { pub fn $name(env: &mut Env, args: &Expr) -> Result<...
use std::ops::Deref; use env::Env; use eval::funcall; use expr::{Error as E, Expr, Kfloat, Kint, Result, Type}; use util::*; macro_rules! expr { ($e:expr) => { $e }; } macro_rules! def_arith_op { ($name: ident, $op: tt, $init: expr) => { pub fn $name(env: &mut Env, args: &Expr) -> Result<...
v.fregister("funcall", kprim("k_funcall", k_funcall)); env.fregister("cons", kprim("k_cons", k_cons)); env.fregister("car", kprim("k_car", k_car)); env.fregister("cdr", kprim("k_cdr", k_cdr)); env.fregister("equalp", kprim("k_equal_p", k_equal_p)); env.fregister( "string-to-number", ...
function_block-function_prefixed
[ { "content": "pub fn f_foldl<F>(env: &mut Env, f: &F, init: &Expr, args: &Expr) -> Result<Expr>\n\nwhere\n\n F: Fn(&mut Env, &Expr, &Expr) -> Result<Expr>,\n\n{\n\n let mut res = init.clone();\n\n let mut head = args;\n\n let nil = &Expr::Nil;\n\n while head != nil {\n\n match head {\n\n ...
Rust
sleighcraft/build.rs
ioo0s/sleighcraft
ad8024574d83ee109c1172b021f4a7438b95b1a1
use filetime::FileTime; use std::env; use std::fs; use std::path::{Path, PathBuf}; const DECOMPILER_SOURCE_BASE_CXX: &[&str] = &[ "space.cc", "float.cc", "address.cc", "pcoderaw.cc", "translate.cc", "opcodes.cc", "globalcontext.cc", "capability.cc", "architecture.cc", "options...
use filetime::FileTime; use std::env; use std::fs; use std::path::{Path, PathBuf}; const DECOMPILER_SOURCE_BASE_CXX: &[&str] = &[ "space.cc", "float.cc", "address.cc", "pcoderaw.cc", "translate.cc", "opcodes.cc", "globalcontext.cc", "capability.cc", "architecture.cc", "options...
.warnings(false) .file(disasm_src_path) .files(compile_opts.sources) .flag_if_supported("-std=c++14") .include(src_cpp) .include(src_cpp_gen_bison) .include(src_cpp_gen_flex) .compile("sleigh"); }
ath = Path::new(&outdir).join(src_path); path.set_extension("o"); path } fn prepare() -> CompileOptions { let mut objects = vec![]; let mut sources = vec![]; for src in DECOMPILER_SOURCE_BASE_CXX.iter() { let path = Path::new("src").join("cpp").join(src); if need_recompile(&path) {...
random
[ { "content": "fn load_preset() -> HashMap<&'static str, &'static str> {\n\n let mut map = HashMap::new();\n\n macro_rules! def_arch {\n\n ($name: expr) => {\n\n // presets are used across the whole lifetime, it's safe to ignore\n\n // the lifetime by leaking its names' memory\...
Rust
tests/integration_test.rs
danieldulaney/rusync
992bb083699da5cec2e547044e49675677058ab9
extern crate filetime; extern crate tempdir; extern crate rusync; use std::fs; use std::fs::File; use std::io; use std::os::unix; use std::os::unix::fs::PermissionsExt; use std::path::Path; use std::path::PathBuf; use std::process::Command; use filetime::FileTime; use tempdir::TempDir; use rusync::progress::Progres...
extern crate filetime; extern crate tempdir; extern crate rusync; use std::fs; use std::fs::File; use std::io; use std::os::unix; use std::os::unix::fs::PermissionsExt; use std::path::Path; use std::path::PathBuf; use std::process::Command; use filetime::FileTime; use tempdir::TempDir; use rusync::progress::Progres...
create temp dir"); let (src_path, dest_path) = setup_test(&tmp_dir.path()); let syncer = new_test_syncer(&src_path, &dest_path); let outcome = syncer.sync(); assert!( outcome.is_ok(), "sync::sync failed with: {}", outcome.err().expect("") ); let src_top = src_path.join(...
s() .expect("Failed to execute process"); assert!(status.success()); (src_path, dest_path) } fn make_recent(path: &Path) -> io::Result<()> { let metadata = fs::metadata(&path)?; let atime = FileTime::from_last_access_time(&metadata); let mtime = FileTime::from_last_modification_time(&metada...
random
[ { "content": "pub fn get_rel_path(a: &Path, b: &Path) -> FSResult<PathBuf> {\n\n let rel_path = pathdiff::diff_paths(&a, &b);\n\n if rel_path.is_none() {\n\n let desc = format!(\n\n \"Could not get relative path from {} to {}\",\n\n &a.to_string_lossy(),\n\n &b.to_s...
Rust
src/caret/movement.rs
jamessral/sodium
f98a942348861398e74457ded693e57b86d31fd5
use edit::buffer::TextBuffer; use state::editor::Editor; impl Editor { #[inline] pub fn goto(&mut self, (x, y): (usize, usize)) { self.cursor_mut().y = y; self.cursor_mut().x = x; } #[inline] pub fn previous(&self, n: usize) -> Option<(usize, usize)> { self.b...
use edit::buffer::TextBuffer; use state::editor::Editor; impl Editor { #[inline] pub fn goto(&mut self, (x, y): (usize, usize)) { self.cursor_mut().y = y; self.cursor_mut().x = x; } #[inline] pub fn previous(&self, n: usize) -> Option<(usize, usize)> { self.b...
#[inline] pub fn before(&self, n: usize, (x, y): (usize, usize)) -> Option<(usize, usize)> { if x >= n { Some((x - n, y)) } else { if y == 0 { None } else { let mut mv = n - x - 1; let mut ry = y - 1;...
mv -= self.buffers.current_buffer()[ry].len(); ry += 1; } else { return None; } } } } } }
function_block-function_prefix_line
[ { "content": "/// Convert a usize tuple to isize\n\npub fn to_signed_pos((x, y): (usize, usize)) -> (isize, isize) {\n\n (x as isize, y as isize)\n\n}\n\n\n\nimpl Editor {\n\n /// Get the position of the current cursor, bounded\n\n #[inline]\n\n pub fn pos(&self) -> (usize, usize) {\n\n let c...
Rust
serde-generate/tests/ocaml_runtime.rs
zefchain/serde-reflection
3bc9fa7422a2e725960ae8a1166f6929961f6128
use serde_generate::{ ocaml, test_utils, test_utils::{Choice, Runtime, Test}, CodeGeneratorConfig, SourceInstaller, }; use std::{fs::File, io::Write, process::Command}; use tempfile::tempdir; fn quote_bytes(bytes: &[u8]) -> String { format!( "\"{}\"", bytes .iter() ...
use serde_generate::{ ocaml, test_utils, test_utils::{Choice, Runtime, Test}, CodeGeneratorConfig, SourceInstaller, }; use std::{fs::File, io::Write, process::Command}; use tempfile::tempdir; fn quote_bytes(bytes: &[u8]) -> String { format!( "\"{}\"", bytes .iter() ...
; let config = CodeGeneratorConfig::new("testing".to_string()).with_encodings(vec![runtime.into()]); let dir_path = dir.join(&config.module_name()); std::fs::create_dir_all(&dir_path).unwrap(); let dune_project_source_path = dir.join("dune-project"); let mut dune_project_file = std::fs::F...
match runtime { Runtime::Bcs => { installer.install_bcs_runtime().unwrap(); "bcs" } Runtime::Bincode => { installer.install_bincode_runtime().unwrap(); "bincode" } }
if_condition
[ { "content": "fn quote_bytes(bytes: &[u8]) -> String {\n\n format!(\n\n \"{{{}}}\",\n\n bytes\n\n .iter()\n\n .map(|x| format!(\"{}\", *x as i8))\n\n .collect::<Vec<_>>()\n\n .join(\", \")\n\n )\n\n}\n\n\n", "file_path": "serde-generate/tests/j...
Rust
generate-assets/src/lib.rs
BlackPhlox/bevy-website
3a84400990d4d85e40303ba4bc3e1e85f63c991d
use cratesio_dbdump_csvtab::rusqlite::Connection; use cratesio_dbdump_lookup::{get_versions, CrateDependency, CrateLookup}; use rand::{thread_rng, Rng}; use serde::Deserialize; use std::{fs, io, path::PathBuf, str::FromStr}; #[derive(Deserialize, Debug, Clone)] #[serde(deny_unknown_fields)] pub struct Asset { pub ...
use cratesio_dbdump_csvtab::rusqlite::Connection; use cratesio_dbdump_lookup::{get_versions, CrateDependency, CrateLookup}; use rand::{thread_rng, Rng}; use serde::Deserialize; use std::{fs, io, path::PathBuf, str::FromStr}; #[derive(Deserialize, Debug, Clone)] #[serde(deny_unknown_fields)] pub struct Asset { pub ...
fn populate_with_crate_io_data(db: &Connection, asset: &mut Asset) { if asset.image.is_none() && asset.emoji.is_none() { let emoji_code: u32 = thread_rng().gen_range(0x1F600..0x1F64F); let emoji = char::from_u32(emoji_code).unwrap_or('💔'); asset.emoji = Some(emoji.to_string()); } ...
continue; } let mut asset: Asset = toml::de::from_str(&fs::read_to_string(&path).unwrap()).unwrap(); asset.original_path = Some(path); populate_with_crate_io_data(db, &mut asset); section.content.push(AssetNode::Asset(...
function_block-function_prefix_line
[ { "content": "fn visit_dirs(dir: PathBuf, section: &mut Section) -> io::Result<()> {\n\n if !dir.is_dir() {\n\n // Todo: after the 0.6 release, remove this if statement\n\n // For now we will allow this to be able to point to the `latest` branch (0.5)\n\n // which does not yet include er...
Rust
tensorflow-sys/build.rs
andrewcsmith/rust-1
18db708a1893ae96dad207392bd721dcd7bc83f3
extern crate curl; extern crate flate2; extern crate pkg_config; extern crate semver; extern crate tar; use std::error::Error; use std::fs::File; use std::io::BufWriter; use std::io::Write; use std::path::{Path, PathBuf}; use std::process; use std::process::Command; use std::{env, fs}; use curl::easy::Easy; use flate...
extern crate curl; extern crate flate2; extern crate pkg_config; extern crate semver; extern crate tar; use std::error::Error; use std::fs::File; use std::io::BufWriter; use std::io::Write; use std::path::{Path, PathBuf}; use std::process; use std::process::Command; use std::{env, fs}; use curl::easy::Easy; use flate...
ion < want { return Err(format!("Installed version {} is less than required version {}", version_str, MIN_BAZEL) .into()); } } } if !found_version { return Err("Did not find vers...
function_block-function_prefixed
[ { "content": "fn log_env_var(log: &mut Write, var: &str) -> Result<(), io::Error> {\n\n match env::var(var) {\n\n Ok(s) => writeln!(log, \"{}={}\", var, s),\n\n Err(env::VarError::NotPresent) => writeln!(log, \"{} is not present\", var),\n\n Err(env::VarError::NotUnicode(_)) => writeln!(...
Rust
src/mock_server.rs
pactflow/pact-protobuf-plugin
1d57edee9e5fe34b76d32ab4f72ea8935eab4bc2
use std::collections::HashMap; use std::future::Future; use std::net::SocketAddr; use std::pin::Pin; use std::sync::Mutex; use std::task::{Context, Poll}; use std::thread; use anyhow::anyhow; use bytes::Bytes; use http::Method; use hyper::{http, Request, Response}; use hyper::server::accept; use lazy_static::lazy_st...
use std::collections::HashMap; use std::future::Future; use std::net::SocketAddr; use std::pin::Pin; use std::sync::Mutex; use std::task::{Context, Poll}; use std::thread; use anyhow::anyhow; use bytes::Bytes; use http::Method; use hyper::{http, Request, Response}; use hyper::server::accept; use lazy_static::lazy_st...
} #[instrument] pub async fn start_server(mut self, host_interface: &str, port: u32, tls: bool) -> anyhow::Result<SocketAddr> { for (key, value) in &self.plugin_config.configuration { if let Value::Object(map) = value { if let Some(descriptor) = map.get("protoDescriptors") { le...
n new(pact: V4Pact, plugin_config: &PluginData) -> Self { GrpcMockServer { pact, plugin_config: plugin_config.clone(), descriptors: Default::default(), routes: Default::default(), server_key: Uuid::new_v4().to_string() }
function_block-random_span
[ { "content": "/// Get the name of the enum value\n\npub fn enum_name(enum_value: i32, descriptor: &EnumDescriptorProto) -> String {\n\n descriptor.value.iter().find(|v| v.number.unwrap_or(-1) == enum_value)\n\n .map(|v| v.name.clone().unwrap_or_else(|| format!(\"enum {}\", enum_value)))\n\n .unwrap_or_el...
Rust
src/infrastructure/arranging/sequencing.rs
SpeedyNinja/laminar
bf65f8ad2a8d168a265d0bc302b232912ce0bca4
use super::{Arranging, ArrangingSystem}; use crate::packet::SequenceNumber; use std::{collections::HashMap, marker::PhantomData}; pub struct SequencingSystem<T> { streams: HashMap<u8, SequencingStream<T>>, } impl<T> SequencingSystem<T> { pub fn new() -> SequencingSystem<T> { SequencingSyst...
use super::{Arranging, ArrangingSystem}; use crate::packet::SequenceNumber; use std::{collections::HashMap, marker::PhantomData}; pub struct SequencingSystem<T> { streams: HashMap<u8, SequencingStream<T>>, } impl<T> SequencingSystem<T> { pub fn new() -> SequencingSystem<T> { SequencingSyst...
#[test] fn create_existing_stream() { let mut system: SequencingSystem<Packet> = SequencingSystem::new(); system.get_or_create_stream(1); let stream = system.get_or_create_stream(1); assert_eq!(stream.stream_id(), 1); } macro_rules! assert_sequence { ( [...
fn create_stream() { let mut system: SequencingSystem<Packet> = SequencingSystem::new(); let stream = system.get_or_create_stream(1); assert_eq!(stream.stream_id(), 1); }
function_block-function_prefix_line
[ { "content": "pub fn payload() -> Vec<u8> {\n\n vec![0, 1, 2, 3, 4, 5, 6, 7, 8, 9]\n\n}\n", "file_path": "tests/unreliable_packets_test.rs", "rank": 0, "score": 186202.72506258375 }, { "content": "pub fn payload() -> Vec<u8> {\n\n vec![0; 4000]\n\n}\n", "file_path": "tests/fragment...
Rust
lib/src/kvstore.rs
crashlabs-io/moiradb
a94642077d4deea192558b7112f291db82b8f8d6
use super::*; use rocksdb::{WriteBatch, DB}; use std::fmt::Debug; use tokio::sync::mpsc; use tokio::sync::oneshot; use tokio::task::JoinHandle; type DBValue<V> = Arc<Option<V>>; #[derive(Debug)] pub enum KVCommand<K, V> where K: Send, V: Send, { Read(K, oneshot::Sender<DBValue<V>>), Write(Vec<(K, DB...
use super::*; use rocksdb::{WriteBatch, DB}; use std::fmt::Debug; use tokio::sync::mpsc; use tokio::sync::oneshot; use tokio::task::JoinHandle; type DBValue<V> = Arc<Option<V>>; #[derive(Debug)] pub enum KVCommand<K, V> where K: Send, V: Send, { Read(K, oneshot::Sender<DBValue<V>>), Write(Vec<(K, DB...
}
kv_adapter.write(vec![("A".to_string(), Arc::new(Some("VA".to_string())))]); let v = kv_adapter.read("A".to_string()).await; assert_eq!(Some("VA".to_string()), *v); kv_adapter.write(vec![("A".to_string(), Arc::new(None))]); let v = kv_adapter.read("A".to_str...
function_block-function_prefix_line
[ { "content": "pub trait MergeCommand<K, V>: Command<K, V>\n\nwhere\n\n K: Debug,\n\n V: Debug,\n\n Self: Debug,\n\n{\n\n}\n\n\n\n#[derive(Debug, PartialEq, Clone, Copy)]\n\npub enum ExecState {\n\n Abort,\n\n Commit,\n\n Merge,\n\n NoWrite,\n\n Pending,\n\n Reschedule,\n\n}\n\n\n\n#[d...
Rust
common/functions/src/scalars/udfs/in_basic.rs
pymongo/databend
c349ea00478df90c6b9c6438bec9b3643b4072e4
use std::collections::HashSet; use std::fmt; use common_datavalues::columns::DataColumn; use common_datavalues::prelude::DataColumnsWithField; use common_datavalues::prelude::MutableArrayBuilder; use common_datavalues::prelude::MutableBooleanArrayBuilder; use common_datavalues::types::merge_types; use common_dataval...
use std::collections::HashSet; use std::fmt; use common_datavalues::columns::DataColumn; use common_datavalues::prelude::DataColumnsWithField; use common_datavalues::prelude::MutableArrayBuilder; use common_datavalues::prelude::MutableBooleanArrayBuilder; use common_datavalues::types::merge_types; use common_dataval...
} impl<const NEGATED: bool> fmt::Display for InFunction<NEGATED> { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { if NEGATED { write!(f, "NOT IN") } else { write!(f, "IN") } } }
fn eval(&self, columns: &DataColumnsWithField, _input_rows: usize) -> Result<DataColumn> { let input_column = columns[0].column(); let input_array = match input_column { DataColumn::Array(array) => array.to_owned(), DataColumn::Constant(scalar, _) => scalar.to_array()?, ...
function_block-full_function
[ { "content": "pub fn string_literal(val: &str) -> Expression {\n\n Expression::create_literal(DataValue::String(Some(val.as_bytes().to_vec())))\n\n}\n\n\n", "file_path": "query/src/storages/fuse/table_functions/table_arg_util.rs", "rank": 0, "score": 452972.13957462483 }, { "content": "pu...
Rust
research/query_service/ir/integrated/tests/expand_test.rs
wuyueandrew/GraphScope
9e2d77d83378f85f001b555d06e4dcbf9a6a4260
mod common; #[cfg(test)] mod test { use std::sync::Arc; use graph_proxy::{create_demo_graph, SimplePartition}; use graph_store::ldbc::LDBCVertexParser; use graph_store::prelude::DefaultId; use ir_common::expr_parse::str_to_expr_pb; use ir_common::generated::algebra as pb; use ir_common::...
mod common; #[cfg(test)] mod test { use std::sync::Arc; use graph_proxy::{create_demo_graph, SimplePartition}; use graph_store::ldbc::LDBCVertexParser; use graph_store::prelude::DefaultId; use ir_common::expr_parse::str_to_expr_pb; use ir_common::generated::algebra as pb; use ir_common::...
#[test] fn expand_oute_with_many_labels_test() { let query_param = query_params(vec!["knows".into(), "created".into()], vec![], None); let expand_opr_pb = pb::EdgeExpand { v_tag: None, direction: 0, params: Some(query_param), is_edge: true, ...
fn expand_oute_with_label_test() { let query_param = query_params(vec!["knows".into()], vec![], None); let expand_opr_pb = pb::EdgeExpand { v_tag: None, direction: 0, params: Some(query_param), is_edge: true, alias: None, }; let...
function_block-full_function
[ { "content": "fn create_src(id: u32, source: &mut Source<i32>) -> Result<(Stream<i32>, Stream<i32>), BuildJobError> {\n\n let src1 = if id == 0 { source.input_from(1..5)? } else { source.input_from(8..10)? };\n\n let (src1, src2) = src1.copied()?;\n\n let src2 = src2.map(|x| Ok(x + 1))?;\n\n Ok((src...
Rust
src/config/request.rs
initprism/isahc
9ddf6b4de16f3b90608dcce0abf2ddd8c51ef2e6
use super::{proxy::Proxy, *}; use curl::easy::Easy2; #[doc(hidden)] pub trait WithRequestConfig: Sized { fn with_config(self, f: impl FnOnce(&mut RequestConfig)) -> Self; } pub(crate) trait SetOpt { fn set_opt<H>(&self, easy: &mut Easy2<H>) -> Result<(), curl::Error>; } macro_rules! define_reques...
use super::{proxy::Proxy, *}; use curl::easy::Easy2; #[doc(hidden)] pub trait WithRequestConfig: Sized { fn with_config(self, f: impl FnOnce(&mut RequestConfig)) -> Self; } pub(crate) trait SetOpt { fn set_opt<H>(&self, easy: &mut Easy2<H>) -> Result<(), curl::Error>; } macro_rules! define_reques...
peed, timeout)) = self.low_speed_timeout { easy.low_speed_limit(low_speed)?; easy.low_speed_time(timeout)?; } if let Some(timeout) = self.connect_timeout { easy.connect_timeout(timeout)?; } if let Some(negotiation) = self.version_negotiation.as_ref()...
ication: Option<Authentication>, credentials: Option<Credentials>, tcp_keepalive: Option<Duration>, tcp_nodelay: Option<bool>, interface: Option<NetworkInterface>, ip_version: Option<IpVersion>, dial: Option<Dialer>, proxy: Option<Option<http::Uri>>, proxy_blacklist: Option<proxy::Blackl...
random
[ { "content": "/// Creates an interceptor from an arbitrary closure or function.\n\npub fn from_fn<F, E>(f: F) -> InterceptorFn<F>\n\nwhere\n\n F: for<'a> private::AsyncFn2<Request<AsyncBody>, Context<'a>, Output = InterceptorResult<E>>\n\n + Send\n\n + Sync\n\n + 'static,\n\n E: Error...
Rust
src/barcodeservice.rs
kalkspace/getraenkekassengeraete
39248dc3a0c6a3ae1b285e8a3f964cfe81775460
use async_stream::stream; use futures_core::stream::Stream; use libc::ioctl; use log::{error, warn}; use std::convert::TryFrom; use std::error::Error; use std::fs::File; use std::os::unix::io::AsRawFd; use std::path::{Path, PathBuf}; use tokio::io::AsyncReadExt; use tokio::time::{sleep, Duration}; use tokio_fd::AsyncFd...
use async_stream::stream; use futures_core::stream::Stream; use libc::ioctl; use log::{error, warn}; use std::convert::TryFrom; use std::error::Error; use std::fs::File; use std::os::unix::io::AsRawFd; use std::path::{Path, PathBuf}; use tokio::io::AsyncReadExt; use tokio::time::{sleep, Duration}; use tokio_fd::AsyncFd...
} } } pub fn run(dev: impl Into<PathBuf>) -> impl Stream<Item = String> { stream! { let mut scanner = BarcodeScanner::new(dev); loop { yield scanner.read_barcode().await; } } }
match self.try_read_barcode().await { Ok(s) => return s, Err(e) => { error!("Error reading barcode {}", e); self.keyboard_file = None } }
if_condition
[ { "content": "pub fn run(dev: impl Into<PathBuf>) -> impl Stream<Item = ()> {\n\n stream! {\n\n let mut reader = StornoReader::new(dev);\n\n loop {\n\n yield reader.read_storno().await;\n\n }\n\n }\n\n}\n", "file_path": "src/stornoservice.rs", "rank": 1, "score"...
Rust
crates/holochain_sqlite/src/db/p2p_agent_store.rs
the-a-man-006/holochain
ace36de1c9021dd4f49e4bba226db81f671b818e
use crate::prelude::*; use crate::sql::*; use kitsune_p2p::agent_store::{AgentInfo, AgentInfoSigned}; use kitsune_p2p::dht_arc::DhtArc; use kitsune_p2p::KitsuneAgent; use rusqlite::*; pub trait AsP2pStateConExt { fn p2p_get(&mut self, agent: &KitsuneAgent) -> DatabaseResult<Option<AgentInfoSigned>>; ...
use crate::prelude::*; use crate::sql::*; use kitsune_p2p::agent_store::{AgentInfo, AgentInfoSigned}; use kitsune_p2p::dht_arc::DhtArc; use kitsune_p2p::KitsuneAgent; use rusqlite::*; pub trait AsP2pStateConExt { fn p2p_get(&mut self, agent: &KitsuneAgent) -> DatabaseResult<Option<AgentInfoSigned>>; ...
fn p2p_list(&self) -> DatabaseResult<Vec<AgentInfoSigned>> { use std::convert::TryFrom; let mut stmt = self .prepare(sql_p2p_agent_store::SELECT_ALL) .map_err(|e| rusqlite::Error::ToSqlConversionFailure(e.into()))?; let mut out = Vec::new(); for r in stmt.q...
fn p2p_get(&self, agent: &KitsuneAgent) -> DatabaseResult<Option<AgentInfoSigned>> { use std::convert::TryFrom; let mut stmt = self .prepare(sql_p2p_agent_store::SELECT) .map_err(|e| rusqlite::Error::ToSqlConversionFailure(e.into()))?; Ok(stmt .query_row(nam...
function_block-full_function
[ { "content": "/// Insert a [`Header`] into the database.\n\npub fn insert_header(txn: &mut Transaction, header: SignedHeaderHashed) -> StateMutationResult<()> {\n\n let (header, signature) = header.into_header_and_signature();\n\n let (header, hash) = header.into_inner();\n\n let header_type = header.h...
Rust
src/resources/automata.rs
Luminoth/remix-exploration
491e4b3bc1447eae35baa9a2599e182b743cdb41
use bevy::prelude::*; use crate::game::dna::*; use crate::game::stats::*; use crate::resources::*; pub trait AutomataStats { fn stats(&self) -> &StatSet; fn modify(&mut self, statid: StatId, amount: isize) -> bool; } macro_rules! impl_modify_stats { () => { fn modify(&mut self, stati...
use bevy::prelude::*; use crate::game::dna::*; use crate::game::stats::*; use crate::resources::*; pub trait AutomataStats { fn stats(&self) -> &StatSet; fn modify(&mut self, statid: StatId, amount: isize) -> bool; } macro_rules! impl_modify_stats { () => { fn modify(&mut self, stati...
, } } pub fn round_stats(&self, round: usize) -> &AIAutomataStats { self.population.get(round).unwrap() } } pub struct AutomataColors { pub cell: Color, pub player_automata: Color, pub ai_automata: Color, }
ion = Vec::with_capacity(rounds); for _ in 0..population.capacity() { population.push(AIAutomataStats::new(points, random)); } Self { mutation_rate, population, mating_pool: vec![]
function_block-random_span
[ { "content": "/// Stat modified event handler\n\npub fn stat_modified_event_handler(\n\n stats: ResMut<PlayerAutomataStats>,\n\n button_colors: Res<ButtonColors>,\n\n mut events: EventReader<StatModifiedEvent>,\n\n mut text_query: Query<(&mut Text, &StatModifierText), Without<PointsText>>,\n\n mu...
Rust
fusestore/store/src/api/rpc/flight_service_test.rs
tisonkun/datafuse
c0371078750cad9fbf4b3770c1c581dbe10c4b20
use common_arrow::arrow::array::ArrayRef; use common_datablocks::DataBlock; use common_datavalues::DataColumnarValue; use common_flights::GetTableActionResult; use common_flights::StoreClient; use common_planners::ScanPlan; use log::info; use pretty_assertions::assert_eq; use test_env_log::test; #[test(tokio::test)]...
use common_arrow::arrow::array::ArrayRef; use common_datablocks::DataBlock; use common_datavalues::DataColumnarValue; use common_flights::GetTableActionResult; use common_flights::StoreClient; use common_planners::ScanPlan; use log::info; use pretty_assertions::assert_eq; use test_env_log::test; #[test(tokio::test)]...
#[test(tokio::test)] async fn test_scan_partition() -> anyhow::Result<()> { use std::sync::Arc; use common_arrow::arrow::datatypes::DataType; use common_datavalues::DataField; use common_datavalues::DataSchema; use common_datavalues::Int64Array; use common_datavalues::StringArray; use comm...
let db_name = "test_db"; let tbl_name = "test_tbl"; let col0: ArrayRef = Arc::new(Int64Array::from(vec![0, 1, 2])); let col1: ArrayRef = Arc::new(StringArray::from(vec!["str1", "str2", "str3"])); let expected_rows = col0.data().len() * 2; let expected_cols = 2; let block = DataBlock::create_b...
function_block-function_prefix_line
[ { "content": "#[test]\n\nfn test_mem_engine_create_get_table() -> anyhow::Result<()> {\n\n // TODO check generated ver\n\n let eng = MemEngine::create();\n\n\n\n let mut eng = eng.lock().unwrap();\n\n\n\n let cmdfoo = CmdCreateDatabase {\n\n db_name: \"foo\".into(),\n\n db: Some(Db {\n...
Rust
vrp-scientific/src/solomon/reader.rs
andrewgy8/vrp
c94574ad555c6ca06480f678f52850caf9aa71cb
#[cfg(test)] #[path = "../../tests/unit/solomon/reader_test.rs"] mod reader_test; use crate::common::*; use crate::utils::MatrixFactory; use std::io::{BufReader, Read}; use std::sync::Arc; use vrp_core::construction::constraints::*; use vrp_core::models::common::{TimeSpan, TimeWindow}; use vrp_core::models::problem::*...
#[cfg(test)] #[path = "../../tests/unit/solomon/reader_test.rs"] mod reader_test; use crate::common::*; use crate::utils::MatrixFactory; use std::io::{BufReader, Read}; use std::sync::Arc; use vrp_core::construction::constraints::*; use vrp_core::models::common::{TimeSpan, TimeWindow}; use vrp_core::models::problem::*...
}
for _ in 0..count { read_line(&mut self.reader, &mut self.buffer).map_err(|_| "Cannot skip lines")?; } Ok(()) }
function_block-function_prefix_line
[ { "content": "pub fn read_line<R: Read>(reader: &mut BufReader<R>, mut buffer: &mut String) -> Result<usize, String> {\n\n buffer.clear();\n\n reader.read_line(&mut buffer).map_err(|err| err.to_string())\n\n}\n", "file_path": "vrp-scientific/src/common/text_reader.rs", "rank": 0, "score": 6467...
Rust
src/boxed/api.rs
sharksforarms/bitvec
293e670d5b6fe89da595edccb3f93cafb75d8835
use crate::{ boxed::BitBox, order::BitOrder, pointer::BitPtr, slice::BitSlice, store::BitStore, vec::BitVec, }; use core::{ marker::Unpin, mem::ManuallyDrop, pin::Pin, }; use wyz::pipe::Pipe; impl<O, T> BitBox<O, T> where O: BitOrder, T: BitStore, { #[cfg_attr(...
use crate::{ boxed::BitBox, order::BitOrder, pointer::BitPtr, slice::BitSlice, store::BitStore, vec::BitVec, }; use core::{ marker::Unpin, mem::ManuallyDrop, pin::Pin, }; use wyz::pipe::Pipe; impl<O, T> BitBox<O, T> where O: BitOrder, T: BitStore, { #[cfg_attr(...
/* The distribution claims that `[T]::into_vec(Box<[T]>) -> Vec<T>` does not alter the address of the heap allocation, and only modifies the buffer handle. Since the address does not change, the `BitPtr` does not need to be updated; the only change is that buffer capacity is now carried locally, rather than ...
let raw = self .pipe(ManuallyDrop::new) .with_box(|b| unsafe { ManuallyDrop::take(b) }) .into_vec() .pipe(ManuallyDrop::new);
assignment_statement
[ { "content": "#[inline(always)]\n\n#[cfg(not(tarpaulin_include))]\n\npub fn mem_mut<T>(x: &mut T) -> &mut T::Mem\n\nwhere T: BitStore {\n\n\tunsafe { &mut *(x as *mut _ as *mut _) }\n\n}\n\n\n\n/// Removes the `::Alias` marker from a register value’s type.\n", "file_path": "src/devel.rs", "rank": 0, ...
Rust
src/display.rs
adi-g15/Ludo-The_Game-rs
d4c9f776982b0a2dd0f1ab53b192ccd2d41cd0f8
use crossterm::{ self, cursor, style::{self, Color, Stylize}, terminal, ExecutableCommand, QueueableCommand, }; use std::{io::{stdout, Write, stdin}, thread, time::Duration}; mod parts; pub struct Display { player_name: String, } impl Display { pub fn new() -> Self { let display = Displ...
use crossterm::{ self, cursor, style::{self, Color, Stylize}, terminal, ExecutableCommand, QueueableCommand, }; use std::{io::{stdout, Write, stdin}, thread, time::Duration}; mod parts; pub struct Display { player_name: String, } impl Display { pub fn new() -> Self { let display = Displ...
ap() .queue(style::Print("±".repeat(columns))) .unwrap(); } stdout.queue(cursor::MoveToNextLine(1)).unwrap(); if stdout.flush().is_err() { terminal::disable_raw_mode().unwrap(); panic!("Couldn't print board"); } stdout.ex...
:All)) .unwrap() .queue(cursor::Hide) .unwrap(); let (columns, _rows) = match terminal::size() { Ok(size) => (size.0 as usize, size.1 as usize), Err(e) => panic!("{:?}", e), }; let h_scale: u16 = 3; let v_scale: u16 = 1; ...
random
[ { "content": "pub fn roll() -> u8 {\n\n rand::thread_rng().gen_range(1..7)\n\n}\n", "file_path": "src/engine/dice.rs", "rank": 0, "score": 47329.51763547484 }, { "content": "use std::io::{stdout, Write};\n\n\n\nuse crate::display::Display;\n\nuse crossterm::{\n\n cursor,\n\n style::...
Rust
pallets/kitties/src/lib.rs
pillarBoy/advance-lesson-2
f5dd1e736ec1c2e073c7e3093e252f004ffda68e
#![cfg_attr(not(feature = "std"), no_std)] use codec::{Encode, Decode}; use frame_support::{ Parameter, RuntimeDebug, StorageDoubleMap, StorageValue, decl_error, decl_event, decl_module, decl_storage, dispatch::{ DispatchError, DispatchResult }, ensure, traits::Get, traits::{ Currency, Existenc...
#![cfg_attr(not(feature = "std"), no_std)] use codec::{Encode, Decode}; use frame_support::{ Parameter, RuntimeDebug, StorageDoubleMap, StorageValue, decl_error, decl_event, decl_module, decl_storage, dispatch::{ DispatchError, DispatchResult }, ensure, traits::Get, traits::{ Currency, Existenc...
fn insert_kitty(owner: &T::AccountId, kitty_id: T::KittyIndex, kitty: Kitty) -> DispatchResult { Kitties::<T>::insert(&owner, kitty_id, kitty.clone()); KittyOwners::<T>::insert(kitty_id, &owner); let mut kitty_vec = AccountKitties::<T>::take(&owner); kitty_vec.push((kitty_id, kitt...
d(), &sender, <frame_system::Module<T>>::extrinsic_index(), ); payload.using_encoded(blake2_128) }
function_block-function_prefixed
[ { "content": "pub fn last_event() -> Event {\n\n System::events().last().unwrap().event.clone()\n\n}", "file_path": "pallets/kitties/src/mock.rs", "rank": 2, "score": 148286.20940153103 }, { "content": "/// Configure the pallet by specifying the parameters and types on which it depends.\n...
Rust
core/src/storage/collections/stash/impls.rs
jsulmont/ink
d1474ae4b7cb3b4119ec39d702358d4e51b0b5bf
#[cfg(feature = "ink-generate-abi")] use ink_abi::{ HasLayout, LayoutField, LayoutStruct, StorageLayout, }; use scale::{ Decode, Encode, }; #[cfg(feature = "ink-generate-abi")] use type_metadata::Metadata; use crate::storage::{ self, alloc::{ Allocate, AllocateUsing, ...
#[cfg(feature = "ink-generate-abi")] use ink_abi::{ HasLayout, LayoutField, LayoutStruct, StorageLayout, }; use scale::{ Decode, Encode, }; #[cfg(feature = "ink-generate-abi")] use type_metadata::Metadata; use crate::storage::{ self, alloc::{ Allocate, AllocateUsing, ...
self.header.len } pub fn max_len(&self) -> u32 { self.header.max_len } pub fn is_empty(&self) -> bool { self.len() == 0 } fn next_vacant(&self) -> u32 { self.header.next_vacant } } impl<T> Stash<T> where T: scale::Codec, { ...
} while self.begin < self.end { let cur = self.begin; self.begin += 1; if let Some(elem) = self.stash.get(cur) { self.yielded += 1; return Some((cur, elem)) } } None } fn size_hint(&self) -> (usize, Option...
random
[ { "content": "/// Returns an iterator over the uninterpreted bytes of all past emitted events.\n\npub fn emitted_events<T: EnvTypes>() -> impl Iterator<Item = Vec<u8>> {\n\n ContractEnv::<T>::emitted_events()\n\n}\n", "file_path": "core/src/env/test.rs", "rank": 0, "score": 403824.9360293277 },...
Rust
day-8/src/main.rs
jharmer95/advent2020
113fa84933ddf9d3d70fb0620aa27b585a9f3a74
use inputs::get_input; mod cpu_sim { use std::{cmp::Ordering, str::FromStr}; pub struct CPU { accumulator: isize, pc: usize, } pub enum ExecutionErr { Ok, Finished, OutOfBounds, } impl CPU { pub const fn new() -> Self { Self { ...
use inputs::get_input; mod cpu_sim { use std::{cmp::Ordering, str::FromStr}; pub struct CPU { accumulator: isize, pc: usize, } pub enum ExecutionErr { Ok, Finished, OutOfBounds, } impl CPU { pub const fn new() -> Self { Self { ...
} } fn part1(opcodes: &[cpu_sim::Instruction]) -> isize { let mut cpu = cpu_sim::CPU::new(); let mut pc_vals = vec![]; while !pc_vals.contains(&cpu.pc()) { pc_vals.push(cpu.pc()); cpu.run_one(opcodes); } cpu.accumulator() } fn test_sequence(cpu: &mut cpu_sim::CPU, opcodes: &...
fn clone(&self) -> Self { match self { Self::ACC(op) => Self::ACC(*op), Self::JMP(op) => Self::JMP(*op), Self::NOP(op) => Self::NOP(*op), } }
function_block-full_function
[ { "content": "fn tokenize(inputs: &[String]) -> HashMap<&str, Vec<(String, usize)>> {\n\n let mut ret = HashMap::new();\n\n\n\n for line in inputs {\n\n let split: Vec<&str> = line.split(\" bags contain \").collect();\n\n let container = split[0];\n\n let contents = split[1];\n\n\n\n ...
Rust
src/game.rs
unixzii/game-of-life
21059c29140883e080ab4c5076a8d0f0a488d42e
use std::rc::Rc; use std::cell::{RefCell, RefMut}; use wasm_bindgen::{JsCast, JsValue}; use wasm_bindgen::closure::Closure; use web_sys::{console, window}; use crate::ui; use crate::engine; struct UiResponder { state: State, } impl ui::Responder for UiResponder { fn on_mouse_down(&self, point: ui::Point) { ...
use std::rc::Rc; use std::cell::{RefCell, RefMut}; use wasm_bindgen::{JsCast, JsValue}; use wasm_bindgen::closure::Closure; use web_sys::{console, window}; use crate::ui; use crate::engine; struct UiResponder { state: State, } impl ui::Responder for UiResponder { fn on_mouse_down(&self, point: ui::Point) { ...
let timer_id = window().unwrap().set_interval_with_callback_and_timeout_and_arguments_0( closure.as_ref().as_ref().unchecked_ref(), inner.config.update_interval ).unwrap(); inner.timer_closure = Some(closure); inner.timer_id = timer_id; } pub fn paus...
if inner.timer_closure.is_some() { return; } let state_clone = self.clone(); let closure = Box::new(Closure::wrap(Box::new(move || { state_clone.tick(); }) as Box<dyn FnMut()>));
random
[ { "content": "fn generate_initial_world(world: &mut engine::World) {\n\n for col in 0..(world.height()) {\n\n for row in 0..(world.width()) {\n\n if Math::random() < 0.3 {\n\n world.set_cell(row, col, engine::Cell::Alive);\n\n }\n\n }\n\n }\n\n}", "fi...
Rust
src/codec_impl.rs
Stebalien/libipld
92586bc1708fb69463ef865f81f9986b3cf31524
#[cfg(feature = "dag-cbor")] use crate::cbor::DagCborCodec; use crate::cid::Cid; use crate::codec::{Codec, Decode, Encode, References}; use crate::error::{Result, UnsupportedCodec}; use crate::ipld::Ipld; #[cfg(feature = "dag-json")] use crate::json::DagJsonCodec; #[cfg(feature = "dag-pb")] use crate::pb::DagPbCodec; ...
#[cfg(feature = "dag-cbor")] use crate::cbor::DagCborCodec; use crate::cid::Cid; use crate::codec::{Codec, Decode, Encode, Refere
es<RawCodec>>::references(RawCodec, r, set)?, #[cfg(feature = "dag-cbor")] IpldCodec::DagCbor => { <Self as References<DagCborCodec>>::references(DagCborCodec, r, set)? } #[cfg(feature = "dag-json")] IpldCodec::DagJson => { <Sel...
nces}; use crate::error::{Result, UnsupportedCodec}; use crate::ipld::Ipld; #[cfg(feature = "dag-json")] use crate::json::DagJsonCodec; #[cfg(feature = "dag-pb")] use crate::pb::DagPbCodec; use crate::raw::RawCodec; use core::convert::TryFrom; use std::io::{Read, Seek, Write}; #[derive(Clone, Copy, Debug, PartialEq, E...
random
[ { "content": "/// Marker trait for types supporting the `DagCborCodec`.\n\npub trait DagCbor: Encode<DagCborCodec> + Decode<DagCborCodec> {}\n\n\n\nimpl<T: Encode<DagCborCodec> + Decode<DagCborCodec>> DagCbor for T {}\n\n\n\n#[cfg(test)]\n\nmod tests {\n\n use super::*;\n\n use libipld_core::cid::Cid;\n\n...
Rust
crates/sui-config/src/node.rs
MystenLabs/sui
b180b663c0b755c97ea37ad57ff636fb04f2e158
use crate::genesis; use crate::Config; use anyhow::Result; use debug_ignore::DebugIgnore; use multiaddr::Multiaddr; use narwhal_config::Committee as ConsensusCommittee; use narwhal_config::Parameters as ConsensusParameters; use narwhal_crypto::ed25519::Ed25519PublicKey; use serde::{Deserialize, Serialize}; use std::n...
use crate::genesis; use crate::Config; use anyhow::Result; use debug_ignore::DebugIgnore; use multiaddr::Multiaddr; use narwhal_config::Committee as ConsensusCommittee; use narwhal_config::Parameters as ConsensusParameters; use narwhal_crypto::ed25519::Ed25519PublicKey; use serde::{Deserialize, Serialize}; use std::n...
#[serde(skip)] genesis: once_cell::sync::OnceCell<genesis::Genesis>, } impl Genesis { pub fn new(genesis: genesis::Genesis) -> Self { Self { location: GenesisLocation::InPlace { genesis }, genesis: Default::default(), } } pub fn new_from_file<P: Into<PathBuf...
dress: Multiaddr, #[serde(default = "default_metrics_address")] pub metrics_address: SocketAddr, #[serde(default = "default_json_rpc_address")] pub json_rpc_address: SocketAddr, #[serde(skip_serializing_if = "Option::is_none")] pub consensus_config: Option<ConsensusConfig>, pub genesis: Ge...
random
[ { "content": "#[serde_as]\n\n#[derive(Eq, PartialEq, Clone, Copy, PartialOrd, Ord, Hash, Serialize, Deserialize)]\n\nstruct ObjectKey(pub ObjectID, pub VersionNumber);\n\n\n\nimpl ObjectKey {\n\n pub const ZERO: ObjectKey = ObjectKey(ObjectID::ZERO, VersionNumber::MIN);\n\n\n\n pub fn max_for_id(id: &Obje...
Rust
examples/responders/src/main.rs
rotoclone/Rocket
3a7559edcec7c443e68e22e038aaa2d90ef27c23
#[macro_use] extern crate rocket; #[cfg(test)] mod tests; /****************** `Result`, `Option` `NameFile` Responder *******************/ use std::{io, env}; use rocket::tokio::fs; use rocket::data::{Capped, TempFile}; use rocket::response::NamedFile; const FILENAME: &str = "big_file.dat"; #[post("/file", data ...
#[macro_use] extern crate rocket; #[cfg(test)] mod tests; /****************** `Result`, `Option` `NameFile` Responder *******************/ use std::{io, env}; use rocket::tokio::fs; use rocket::data::{Capped, TempFile}; use rocket::response::NamedFile; const FILENAME: &str = "big_file.dat"; #[post("/file", data ...
mount("/", routes![xml, json, json_or_msgpack]) .mount("/", routes![custom]) .register("/", catchers![not_found]) }
function_block-function_prefix_line
[ { "content": "#[rocket::post(\"/\", data = \"<_data>\", format = \"json\")]\n\nfn index(_data: rocket::Data) -> &'static str { \"json\" }\n\n\n", "file_path": "core/lib/tests/replace-content-type-518.rs", "rank": 3, "score": 552084.1880964399 }, { "content": "fn read_file_content(path: &str)...
Rust
crates/shell/src/minifb/window.rs
Dmitry-Borodin/orbtk
235e0d84f7914605e28b8c313e4f21d00e6208b0
use std::{cell::RefCell, rc::Rc, sync::mpsc}; use derive_more::Constructor; use super::{KeyState, MouseState, WindowState, CONSOLE}; use crate::{ event::{ButtonState, KeyEvent, MouseButton, MouseEvent}, render::RenderContext2D, window_adapter::WindowAdapter, WindowRequest, }; #[derive(Constructor)] p...
use std::{cell::RefCell, rc::Rc, sync::mpsc}; use derive_more::Constructor; use super::{KeyState, MouseState, WindowState, CONSOLE}; use crate::{ event::{ButtonState, KeyEvent, MouseButton, MouseEvent}, render::RenderContext2D, window_adapter::WindowAdapter, WindowRequest, }; #[derive(Constructor)] p...
fn push_key_up_event(&mut self, index: usize) { if self .window .is_key_released(self.key_states.get(index).unwrap().minifb_key) { self.adapter.key_event(KeyEvent { key: self.key_states.get(index).unwrap().key, state: ButtonState:...
minifb::Key::Up | minifb::Key::Down | minifb::Key::Backspace | minifb::Key::Delete => minifb::KeyRepeat::Yes, _ => minifb::KeyRepeat::No, }; if self .window .is_key_pressed(self.key_states.get(index).unwrap().minifb_key, key_repeat...
function_block-function_prefix_line
[ { "content": "fn get_mouse_button(button: event::MouseButton) -> MouseButton {\n\n match button {\n\n event::MouseButton::Wheel => MouseButton::Middle,\n\n event::MouseButton::Right => MouseButton::Right,\n\n _ => MouseButton::Left,\n\n }\n\n}\n\n\n", "file_path": "crates/shell/sr...
Rust
crates/ra_syntax/src/ast/edit.rs
ztlpn/rust-analyzer
6b9bd7bdd2712a7e85d6bfc70c231dbe36c2e585
use std::{iter, ops::RangeInclusive}; use arrayvec::ArrayVec; use rustc_hash::FxHashMap; use crate::{ algo, ast::{ self, make::{self, tokens}, AstNode, TypeBoundsOwner, }, AstToken, Direction, InsertPosition, SmolStr, SyntaxElement, SyntaxKind::{ATTR, COMMENT, WHITESPACE}...
use std::{iter, ops::RangeInclusive}; use arrayvec::ArrayVec; use rustc_hash::FxHashMap; use crate::{ algo, ast::{ self, make::{self, tokens}, AstNode, TypeBoundsOwner, }, AstToken, Direction, InsertPosition, SmolStr, SyntaxElement, SyntaxKind::{ATTR, COMMENT, WHITESPACE}...
} impl ast::ItemList { #[must_use] pub fn append_items(&self, items: impl Iterator<Item = ast::ImplItem>) -> ast::ItemList { let mut res = self.clone(); if !self.syntax().text().contains_char('\n') { res = res.make_multiline(); } items.for_each(|it| res = res.append...
o_iter()); }; to_insert.push(body.syntax().clone().into()); let replace_range = RangeInclusive::new(old_body_or_semi.clone(), old_body_or_semi); replace_children(self, replace_range, to_insert.into_iter()) }
function_block-function_prefixed
[ { "content": "fn adj_comments(comment: &ast::Comment, dir: Direction) -> ast::Comment {\n\n let mut res = comment.clone();\n\n for element in comment.syntax().siblings_with_tokens(dir) {\n\n let token = match element.as_token() {\n\n None => break,\n\n Some(token) => token,\n\...
Rust
alacritty/src/macos/proc.rs
djpohly/alacritty
1df7dc5171abfe1eab3e95be964f61c5876198f1
use std::ffi::{CStr, CString, IntoStringError}; use std::fmt::{self, Display, Formatter}; use std::io; use std::mem::{self, MaybeUninit}; use std::os::raw::{c_int, c_void}; use std::path::PathBuf; #[derive(Debug)] pub enum Error { Io(io::Error), IntoString(IntoStringError), InvalidSize, } impl...
use std::ffi::{CStr, CString, IntoStringError}; use std::fmt::{self, Display, Formatter}; use std::io; use std::mem::{self, MaybeUninit}; use std::os::raw::{c_int, c_void}; use std::path::PathBuf; #[derive(Debug)] pub enum Error { Io(io::Error), IntoString(IntoStringError), InvalidSize, } impl...
} impl From<io::Error> for Error { fn from(val: io::Error) -> Self { Error::Io(val) } } impl From<IntoStringError> for Error { fn from(val: IntoStringError) -> Self { Error::IntoString(val) } } pub fn cwd(pid: c_int) -> Result<PathBuf, Error> { let mut info = MaybeUninit::<sys::p...
fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result { match self { Error::InvalidSize => write!(f, "Invalid proc_pidinfo return size"), Error::Io(err) => write!(f, "Error getting current working directory: {}", err), Error::IntoString(err) => { write!(f, "Erro...
function_block-full_function
[ { "content": "pub fn create_shader(kind: GLenum, source: &'static str) -> Result<GLuint, ShaderCreationError> {\n\n let len: [GLint; 1] = [source.len() as GLint];\n\n\n\n let shader = unsafe {\n\n let shader = gl::CreateShader(kind);\n\n gl::ShaderSource(shader, 1, &(source.as_ptr() as *cons...
Rust
libfat/src/directory/raw_dir_entry.rs
Orycterope/kfs_libfs
538c0156492db7fdbfa69d49f46609861febbd4a
use byteorder::{ByteOrder, LittleEndian}; use structview::{u16_le, u32_le, View}; use crate::attribute::Attributes; use crate::cluster::Cluster; use crate::datetime::FatDateTime; use crate::filesystem::FatFileSystem; use crate::name::{LongFileName, ShortFileName}; use libfs::block::{Block, BlockDevice, BlockIndex}; ...
use byteorder::{ByteOrder, LittleEndian}; use structview::{u16_le, u32_le, View}; use crate::attribute::Attributes; use crate::cluster::Cluster; use crate::datetime::FatDateTime; use crate::filesystem::FatFileSystem; use crate::name::{LongFileName, ShortFileName}; use libfs::block::{Block, BlockDevice, BlockIndex}; ...
file_name() { Some(LongFileName::from_lfn_dir_entry(self.as_lfn_entry())) } else { None } } pub fn short_name(&self) -> Option<ShortFileName> { if !self.is_long_file_name() { Some(ShortFileName::from_data(&self.as_sfn_entry().name)) } els...
} pub fn flush<T>(&self, fs: &FatFileSystem<T>) -> FileSystemResult<()> where T: BlockDevice, { let mut blocks = [Block::new()]; fs.block_device .read( &mut blocks, fs.partition_start, BlockIndex(self.entry_clust...
random
[ { "content": "/// Get the last cluster of a cluster chain.\n\npub fn get_last_cluster<T>(\n\n fs: &FatFileSystem<T>,\n\n cluster: Cluster,\n\n) -> Result<Cluster, FileSystemError>\n\nwhere\n\n T: BlockDevice,\n\n{\n\n Ok(get_last_and_previous_cluster(fs, cluster)?.0)\n\n}\n\n\n", "file_path": "l...
Rust
src/rust/bitbox02-rust/src/hww/api/ethereum/amount.rs
thisconnect/bitbox02-firmware
e081ac18dc28c2bdffdc58a94afa36a1bb5bade2
use alloc::string::String; use num_bigint::BigUint; pub struct Amount<'a> { pub unit: &'a str, pub decimals: usize, pub value: BigUint, } impl<'a> Amount<'a> { pub fn format(&self) -> String { const TRUNCATE_SIZE: usize ...
use alloc::string::String; use num_bigint::BigUint; pub struct Amount<'a> { pub unit: &'a str, pub decimals: usize, pub value: BigUint, } impl<'a> Amount<'a> { pub fn format(&self) -> String { const TRUNCATE_SIZE: usize ...
}
t { bigendian: b"\x1d\x00\xd3\x28\xcb", decimals: 10, unit: "LOL", expected_result: "12.4567890123 LOL", }, Test { bigendian: b"\x01\x22\x08\x3f\x97\xf2", decimals: 1...
function_block-function_prefixed
[ { "content": "/// Formats integer `value` as `value / 10^decimals`, with up to `decimals` decimal places.\n\n/// E.g. \"123450\" with decimals=3: \"123.45\".\n\n/// Value must consists only of '0'-'9' digits.\n\npub fn format<F: Format>(value: F, decimals: usize) -> String {\n\n let mut v: String = format!(\...
Rust
debug/src/lib.rs
Simon-Bin/proc-macro-workshop
c8654295d4a10ab10827464267c5f653e4005c91
use std::collections::HashMap; use quote::quote; use syn::parse_quote; use syn::visit::{self, Visit}; #[proc_macro_derive(CustomDebug, attributes(debug))] pub fn derive(input: proc_macro::TokenStream) -> proc_macro::TokenStream { let st = syn::parse_macro_input!(input as syn::DeriveInput); match do_expand(&st...
use std::collections::HashMap; use quote::quote; use syn::parse_quote; use syn::visit::{self, Visit}; #[proc_macro_derive(CustomDebug, attributes(debug))] pub fn derive(input: proc_macro::TokenStream) -> proc_macro::TokenStream { let st = syn::parse_macro_input!(input as syn::DeriveInput); match do_expand(&st...
tr in &field.attrs { if let Ok(syn::Meta::NameValue(syn::MetaNameValue { ref path, ref lit, .. })) = attr.parse_meta() { if path.is_ident("debug") { if let syn::Lit::Str(ref ident_str) = lit { return Ok(Some(ident_str.value())); ...
ing(); if phantomdata_type_param_names.contains(&type_param_name) && !fields_type_names.contains(&type_param_name) { continue; } if associated_types_map.contains_key(&type_param_name) && !fields_...
random
[ { "content": "fn get_fields_from_derive_input(st: &syn::DeriveInput) -> syn::Result<&StructField> {\n\n if let syn::Data::Struct(syn::DataStruct {\n\n fields: syn::Fields::Named(syn::FieldsNamed { ref named, .. }),\n\n ..\n\n }) = st.data\n\n {\n\n return Ok(named);\n\n }\n\n ...
Rust
src/grpc/node.rs
searsaw/sensei
ee3d45d690c8a2c8a1c91c3b2cf0f27baf844fd4
use std::sync::Arc; pub use super::sensei::node_server::{Node, NodeServer}; use super::{ sensei::{ CloseChannelRequest, CloseChannelResponse, ConnectPeerRequest, ConnectPeerResponse, CreateInvoiceRequest, CreateInvoiceResponse, DecodeInvoiceRequest, DecodeInvoiceResponse, DeletePaymentRe...
use std::sync::Arc; pub use super::sensei::node_server::{Node, NodeServer}; use super::{ sensei::{ CloseChannelRequest, CloseChannelResponse, ConnectPeerRequest, ConnectPeerResponse, CreateInvoiceRequest, CreateInvoiceResponse, DecodeInvoiceRequest, DecodeInvoiceResponse, DeletePaymentRe...
} None => match request { NodeRequest::StartNode { passphrase } => { drop(node_directory); let admin_request = AdminRequest::StartNode { passphrase, pubkey: session.pubkey, ...
match request { NodeRequest::StopNode {} => { drop(node_directory); let admin_request = AdminRequest::StopNode { pubkey }; let _ = self .request_context .admin_service ...
if_condition
[]
Rust
mesatee_services/fns/sgx_trusted_lib/src/trusted_worker/private_join_and_compute.rs
hshshjzsami/incubator-teaclave
1a671e6e9fdb1f1bc2e1b4804ac2e516409bae63
#[cfg(feature = "mesalock_sgx")] use std::prelude::v1::*; use std::collections::HashMap; use std::fmt::Write; use crate::worker::{FunctionType, Worker, WorkerContext}; use mesatee_core::{Error, ErrorKind, Result}; pub struct PrivateJoinAndComputeWorker { worker_id: u32, func_name: String, func_type: Fu...
#[cfg(feature = "mesalock_sgx")] use std::prelude::v1::*; use std::collections::HashMap; use std::fmt::Write; use crate::worker::{FunctionType, Worker, WorkerContext}; use mesatee_core::{Error, ErrorKind, Result}; pub struct PrivateJoinAndComputeWorker { worker_id: u32, func_name: String, func_type: Fu...
lit(':').collect(); if kv_pair.len() != 2 { continue; } let identity = kv_pair[0].trim().to_string(); let amount = match kv_pair[1].trim().parse::<u32>() { Ok(amount) => amount, Err(_) => continue, }; ret.insert(identity, amount); }...
function_block-function_prefixed
[ { "content": "pub fn percent_decode(orig: &str) -> Result<String> {\n\n let orig = orig.replace(\"%0A\", \"\");\n\n let v: Vec<&str> = orig.split('%').collect();\n\n let mut ret = String::new();\n\n ret.push_str(v[0]);\n\n if v.len() > 1 {\n\n for s in v[1..].iter() {\n\n let di...
Rust
src/main.rs
mentaljam/qgsrepo
d19c60ac2e755d0d4bdce8af37908d5d54678301
extern crate zip; extern crate ini; extern crate xml; mod config; mod qgsmeta; use std::path::PathBuf; use std::fs; use zip::ZipArchive; use ini::Ini; use std::io::Read; use xml::writer; use qgsmeta::{ MetaEntries, metakey, xmlkey }; #[derive(Debug)] enum ExitCodes { Success = 0, NoRootDir, N...
extern crate zip; extern crate ini; extern crate xml; mod config; mod qgsmeta; use std::path::PathBuf; use std::fs; use zip::ZipArchive; use ini::Ini; use std::io::Read; use xml::writer; use qgsmeta::{ MetaEntries, metakey, xmlkey }; #[derive(Debug)] enum ExitCodes { Success = 0, NoRootDir, N...
md.push_str("\ndummy=dummy"); md }, Result::Err(err) => { println!("Warning: could not read the \"metadata.txt\", skipping: {}", err); continue } } }; let metadata = match Ini::load_f...
function_block-function_prefix_line
[ { "content": "pub fn xmlkey(entry: &MetaEntries) -> &'static str {\n\n match entry {\n\n &MetaEntries::QgisMinimumVersion => \"qgis_minimum_version\",\n\n &MetaEntries::QgisMaximumVersion => \"qgis_maximum_version\",\n\n &MetaEntries::Author => \"author_name\",\n\n &Me...
Rust
src/net/raw/arp.rs
Zrus/arrow-client
61ead64b10cf8bba451d6798abacd58ce89e3233
use std::io; use std::mem; use std::io::Write; use std::net::Ipv4Addr; use crate::utils; use crate::net::raw::ether::packet::{EtherPacketBody, PacketParseError, Result}; use crate::net::raw::ether::MacAddr; use crate::net::raw::utils::Serialize; #[derive(Debug, Clone)] pub struct ArpPacket { pub htype: u16, ...
use std::io; use std::mem; use std::io::Write; use std::net::Ipv4Addr; use crate::utils; use crate::net::raw::ether::packet::{EtherPacketBody, PacketParseError, Result}; use crate::net::raw::ether::MacAddr; use crate::net::raw::utils::Serialize; #[derive(Debug, Clone)] pub struct ArpPacket { pub htype: u16, ...
pub fn parse(data: &[u8]) -> Result<Self> { let size = mem::size_of::<RawArpPacketHeader>(); if data.len() < size { Err(PacketParseError::new( "unable to parse ARP packet, not enough data", )) } else { let ptr = data.as_ptr(); ...
hlen: 6, plen: 4, oper, sha: sha.octets().to_vec().into_boxed_slice(), spa: spa.octets().to_vec().into_boxed_slice(), tha: tha.octets().to_vec().into_boxed_slice(), tpa: tpa.octets().to_vec().into_boxed_slice(), } }
function_block-function_prefix_line
[ { "content": "/// Convert given 32-bit unsigned sum into 16-bit unsigned checksum.\n\npub fn sum_to_checksum(sum: u32) -> u16 {\n\n let mut checksum = sum;\n\n while (checksum & 0xffff_0000) != 0 {\n\n let hw = checksum >> 16;\n\n let lw = checksum & 0xffff;\n\n checksum = lw + hw;\n\...
Rust
crates/eosio_token/src/lib.rs
datudou/rust-eos
636073c21d2ab21af3f853fd09c907a3564a5a4e
use eosio::*; #[eosio_action] fn create(issuer: AccountName, max_supply: Asset) { let receiver = AccountName::receiver(); require_auth(receiver); let symbol = max_supply.symbol; eosio_assert(max_supply.amount > 0, "max-supply must be positive"); let symbol_name = symbol.name(); let table = Cu...
use eosio::*; #[eosio_action] fn create(issuer: AccountName, max_supply: Asset) { let receiver = AccountName::receiver(); require_auth(receiver); let symbol = max_supply.symbol; eosio_assert(max_supply.amount > 0, "max-supply must be positive"); let symbol_name = symbol.name(); let table = Cu...
m_payer); let receiver = AccountName::receiver(); let accounts_table = Account::table(receiver, symbol.name()); let cursor = accounts_table.find(symbol.name()); if cursor.is_none() { let account = Account { balance: Asset { amount: 0, symbol }, }; accounts_table.empla...
from: st.issuer, to, quantity, memo, }; action .send_inline(vec![Authorization { actor: st.issuer, permission: n!(active).into(), }]) .assert("failed to send inline action"); } } #[eosio_ac...
random
[ { "content": "fn titlecase(s: &str) -> String {\n\n let mut c = s.chars();\n\n match c.next() {\n\n None => String::new(),\n\n Some(f) => f.to_uppercase().collect::<String>() + c.as_str(),\n\n }\n\n}\n", "file_path": "crates/eosio_macros_impl/src/eosio_action.rs", "rank": 5, "...
Rust
src/lib.rs
Rufflewind/tokio-file-unix
3937ab35a53a34bb78e20e0e9f3483043fb5b231
use std::cell::RefCell; use std::os::unix::io::{AsRawFd, FromRawFd, RawFd}; use std::{fs, io}; use tokio::io::PollEvented; unsafe fn dupe_file_from_fd(old_fd: RawFd) -> io::Result<fs::File> { let fd = libc::fcntl(old_fd, libc::F_DUPFD_CLOEXEC, 0); if fd < 0 { return Err(io::Error::last_os_error()); ...
use std::cell::RefCell; use std::os::unix::io::{AsRawFd, FromRawFd, RawFd}; use std::{fs, io}; use tokio::io::PollEvented; unsafe fn dupe_file_from_fd(old_fd: RawFd) -> io::Result<fs::File> { let fd = libc::fcntl(old_fd, libc::F_DUPFD_CLOEXEC, 0); if fd < 0 { return Err(io::Error::last_os_error()); ...
} impl<F: io::Read> io::Read for File<F> { fn read(&mut self, buf: &mut [u8]) -> io::Result<usize> { self.file.read(buf) } } impl<F: io::Write> io::Write for File<F> { fn write(&mut self, buf: &[u8]) -> io::Result<usize> { self.file.write(buf) } fn flush(&mut self) -> io::Result<...
fn deregister(&self, poll: &mio::Poll) -> io::Result<()> { match *self.evented.borrow() { None => mio::unix::EventedFd(&self.as_raw_fd()).deregister(poll), Some(ref r) => mio::Evented::deregister(r, poll), } }
function_block-full_function
[ { "content": "fn stringify_error<E: error::Error>(e: E) -> io::Error {\n\n io::Error::new(io::ErrorKind::Other, e.to_string())\n\n}\n\n\n\n#[get(\"/{something}\")]\n\nasync fn index(info: web::Path<String>) -> impl Responder {\n\n format!(\"Hello Got this: {}\", info)\n\n}\n\n\n\n#[actix_rt::main]\n\nasyn...
Rust
wasm/src/client.rs
warycat/leetcode_rs
3cb8a1aa569d372443675fab9a63043291316b51
use crate::desktop::Desktop; use crate::media::MediaClient; use crate::pc::PeerConnection; use crate::searchbar::*; use crate::utils::*; use js_sys::JsString; use js_sys::Reflect; use log::info; use rustgym_msg::*; use std::cell::RefCell; use std::collections::HashMap; use uuid::Uuid; use wasm_bindgen::prelude::*; use ...
use crate::desktop::Desktop; use crate::media::MediaClient; use crate::pc::PeerConnection; use crate::searchbar::*; use crate::utils::*; use js_sys::JsString; use js_sys::Reflect; use log::info; use rustgym_msg::*; use std::cell::RefCell; use std::collections::HashMap; use uuid::Uuid; use wasm_bindgen::prelude::*; use ...
fn set_media_stream(media_stream: MediaStream) { CLIENT.with(|client| client.borrow_mut().media_stream = Some(media_stream)); } fn set_peerconnection(remote_uuid: Uuid, pc: PeerConnection) { CLIENT.with(|client| client.borrow_mut().pcs.insert(remote_uuid, pc)); }
CLIENT.with(|client| match track.kind().as_ref() { "video" => { client .borrow_mut() .media_client .as_mut() .expect("media_client") .add_remote_video_track(remote, track) .expect("add_remote_video_track"...
function_block-function_prefix_line
[ { "content": "pub fn nsstring_from_str(string: &str) -> NSString {\n\n const UTF8_ENCODING: usize = 4;\n\n\n\n let cls = class!(NSString);\n\n let bytes = string.as_ptr() as *const c_void;\n\n unsafe {\n\n let obj: *mut objc::runtime::Object = msg_send![cls, alloc];\n\n let obj: *mut o...
Rust
src/logging.rs
Cerber-Ursi/batch_run
61a24e0ccc1fdd3f1e67ebb5b12735ba007a0747
use termcolor::{ Color::{self, *}, WriteColor, }; use termcolor_output::colored; use crate::entry::{Entry, Expected}; use crate::normalize; use std::io; use std::path::Path; pub(crate) fn no_entries(log: &mut impl WriteColor) -> io::Result<()> { colored!( log, "{}{}No entries were provide...
use termcolor::{ Color::{self, *}, WriteColor, }; use termcolor_output::colored; use crate::entry::{Entry, Expected}; use crate::normalize; use std::io; use std::path::Path; pub(crate) fn no_entries(log: &mut impl WriteColor) -> io::Result<()> { colored!( log, "{}{}No entries were provide...
mut impl WriteColor, color: Color, content: &str) -> io::Result<()> { let dotted_line = "┈".repeat(60); colored!(log, "\n{}{}{}\n", reset!(), fg!(Some(color)), dotted_line)?; for line in content.lines() { colored!(log, "{}{}\n", fg!(Some(color)), line)?; } colored!(log, "{}{}{}\...
WriteColor, path: &Path, string: &str, ) -> io::Result<()> { let path = path.to_string_lossy(); colored!( buf, "{}{}wip\n\nNOTE{}: writing the following output to {}.", reset!(), fg!(Some(Yellow)), reset!(), path )?; snippet(buf, Yellow, string) }...
random
[ { "content": "fn write_wip(path: &Path, content: &str, log: &mut impl WriteColor) -> EntryResult<Infallible> {\n\n let wip_dir = Path::new(\"wip\");\n\n create_dir_all(wip_dir)?;\n\n\n\n let gitignore_path = wip_dir.join(\".gitignore\");\n\n write(gitignore_path, \"*\\n\")?;\n\n\n\n let stderr_na...
Rust
src/compiler/compiler.rs
mthom26/monkey-lang
92289eca2a3216ee6042403ecaf1d63e05e29dc0
use crate::{ compiler::{make_op, OpCode, SymbolTable}, evaluator::Object, lexer::lexer, parser::{parse, Expression, Operator, Prefix, Statement}, }; const GLOBAL: &str = "GLOBAL"; #[derive(Debug, PartialEq)] pub struct ByteCode { pub instructions: Vec<u8>, pub constants: Vec<Object>, } impl B...
use crate::{ compiler::{make_op, OpCode, SymbolTable}, evaluator::Object, lexer::lexer, parser::{parse, Expression, Operator, Prefix, Statement}, }; const GLOBAL: &str = "GLOBAL"; #[derive(Debug, PartialEq)] pub struct ByteCode { pub instructions: Vec<u8>, pub constants: Vec<Object>, } impl B...
input = "let x = 1; x;"; #[rustfmt::skip] let expected = ByteCode { instructions: vec![ 1, 0, 0, 17, 0, 0, 18, 0, 0, 6, ], constants: vec![Object::Int(1)], }; assert_eq!(expect...
nt(1), Object::Int(2)], }; assert_eq!(expected, compiled(input)); let input = "1 != 2"; let expected = ByteCode { instructions: vec![1, 0, 0, 1, 0, 1, 12, 6], constants: vec![Object::Int(1), Object::Int(2)], }; assert_eq!(expected, compiled(input)...
random
[ { "content": "pub fn eval(ast: Vec<Statement>, env: &mut Environment) -> Object {\n\n let result = eval_block(ast, env);\n\n\n\n // If final result is a Return unwrap it...\n\n match result {\n\n Object::Return(val) => *val,\n\n _ => result,\n\n }\n\n}\n\n\n", "file_path": "src/eva...
Rust
macros/component-definition-derive/src/lib.rs
Max-Meldrum/kompact
8b77733d8b4da2c74e7d97058ea5ce774d488547
#![recursion_limit = "128"] extern crate proc_macro; use proc_macro::TokenStream; use proc_macro2::TokenStream as TokenStream2; use quote::quote; use syn::{parse_macro_input, DeriveInput}; use std::iter::Iterator; #[proc_macro_derive(ComponentDefinition)] pub fn component_definition(input: TokenStream) -> TokenStrea...
#![recursion_limit = "128"] extern crate proc_macro; use proc_macro::TokenStream; use proc_macro2::TokenStream as TokenStream2; use quote::quote; use syn::{parse_macro_input, DeriveInput}; use std::iter::Iterator; #[proc_macro_derive(ComponentDefinition)] pub fn component_definition(input: TokenStream) -> TokenStrea...
#[allow(clippy::large_enum_variant)] #[derive(Debug)] enum ComponentField { Ctx, Port(PortField), Other, } #[derive(Debug)] enum PortField { Required(syn::Type), Provided(syn::Type), } impl PortField { fn as_handle(&self) -> TokenStream2 { match *self { PortField::Provide...
y) => quote! { impl #impl_generics ProvideRef< #ty > for #name #ty_generics #where_clause { fn provided_ref(&mut self) -> ProvidedRef< #ty > { self.#id.share() } fn connect_to_requ...
function_block-function_prefixed
[ { "content": "/// Connect two port instances.\n\n///\n\n/// The providing port instance must be given as first argument, and the requiring instance second.\n\npub fn biconnect_ports<P: Port>(prov: &mut ProvidedPort<P>, req: &mut RequiredPort<P>) -> () {\n\n let prov_share = prov.share();\n\n let req_share...
Rust
src/log.rs
kornelski/rustracing
117cbd127e5467c4f8303c4dcab9a874d99fdfb2
#[cfg(feature = "stacktrace")] use backtrace::Backtrace; use std::borrow::Cow; use std::time::SystemTime; #[derive(Debug)] pub struct LogBuilder { fields: Vec<LogField>, time: Option<SystemTime>, } impl LogBuilder { pub fn field<T: Into<LogField>>(&mut self, field: T) -> &mut Self { self.fiel...
#[cfg(feature = "stacktrace")] use backtrace::Backtrace; use std::borrow::Cow; use std::time::SystemTime; #[derive(Debug)] pub struct LogBuilder { fields: Vec<LogField>,
lue: V) -> Self where N: Into<Cow<'static, str>>, V: Into<Cow<'static, str>>, { LogField { name: name.into(), value: value.into(), } } pub fn name(&self) -> &str { self.name.as_ref() } pub fn value(&self) -> &str { ...
time: Option<SystemTime>, } impl LogBuilder { pub fn field<T: Into<LogField>>(&mut self, field: T) -> &mut Self { self.fields.push(field.into()); self } pub fn time(&mut self, time: SystemTime) -> &mut Self { self.time = Some(time); self } pub fn s...
random
[ { "content": "/// This trait allows to insert fields in a HTTP header.\n\npub trait SetHttpHeaderField {\n\n /// Sets the value of the field named `name` in the HTTP header to `value`.\n\n fn set_http_header_field(&mut self, name: &str, value: &str) -> Result<()>;\n\n}\n\nimpl<S: BuildHasher> SetHttpHeade...
Rust
santa/src/before_level.rs
balbok0/abstreet
3af15fefdb2772c83864c08724318418da8190a9
use std::collections::{BTreeSet, HashSet}; use rand::seq::SliceRandom; use rand::SeedableRng; use rand_xorshift::XorShiftRng; use abstutil::prettyprint_usize; use geom::Time; use map_gui::load::MapLoader; use map_gui::tools::PopupMsg; use map_gui::ID; use map_model::BuildingID; use widgetry::{ ButtonBuilder, Colo...
use std::collections::{BTreeSet, HashSet}; use rand::seq::SliceRandom; use rand::SeedableRng; use rand_xorshift::XorShiftRng; use abstutil::prettyprint_usize; use geom::Time; use map_gui::load::MapLoader; use map_gui::tools::PopupMsg; use map_gui::ID; use map_model::BuildingID; use widgetry::{ ButtonBuilder, Colo...
fn randomly_pick_upzones(&mut self, app: &App) { let mut choices = Vec::new(); for (b, state) in &self.bldgs.buildings { if let BldgState::Undelivered(_) = state { if !self.current_picks.contains(b) { choices.push(*b); } }...
p), upzone_panel, instructions_panel, level, bldgs, current_picks, draw_start: ctx.upload(draw_start), })) }), ) }
function_block-function_prefixed
[ { "content": "pub fn custom_bar(ctx: &mut EventCtx, filled_color: Color, pct_full: f64, txt: Text) -> Widget {\n\n let total_width = 300.0;\n\n let height = 32.0;\n\n let radius = 4.0;\n\n\n\n let mut batch = GeomBatch::new();\n\n // Background\n\n batch.push(\n\n Color::hex(\"#666666\"...
Rust
src/ast/expr.rs
1tgr/simplejit-demo
750a1f628452d42836d0da5fc415fcef7750c045
use crate::ast::{ArithmeticKind, ComparisonKind, EnvId, IdentId}; use derive_more::{Display, TryInto}; #[derive(Copy, Clone, Debug, Hash, PartialEq, Eq, Display)] #[display(fmt = "{}", "_0")] pub struct ExprId(salsa::InternId); impl salsa::InternKey for ExprId { fn from_intern_id(v: salsa::InternId) -> Self { ...
use crate::ast::{ArithmeticKind, ComparisonKind, EnvId, IdentId}; use derive_more::{Display, TryInto}; #[derive(Copy, Clone, Debug, Hash, PartialEq, Eq, Display)] #[display(fmt = "{}", "_0")] pub struct ExprId(salsa::InternId); impl salsa::InternKey for ExprId { fn from_intern_id(v: salsa::InternId) -> Self { ...
pub enum Expr { $( $ty($ty), )* } impl Expr { pub fn walk<V: ExprVisitor + ?Sized>(self, expr_id: ExprId, visitor: &mut V) -> Result<(), V::Error> { match self { $( Self::$ty(expr) => vis...
), V::Error> { Ok(()) } pub fn transform<T: ExprTransform + ?Sized>(self, _transform: &mut T) -> Result<Expr, T::Error> { Ok(Expr::Identifier(self)) } } #[derive(Clone, Debug, Hash, PartialEq, Eq)] pub struct IfElse { pub condition: ExprId, pub then_body: ExprId, pub else_body:...
random
[ { "content": "fn lower_function(db: &dyn Lower, name: IdentId) -> Result<(Rc<HashMap<EnvId, Env>>, ExprId)> {\n\n let mut envs = HashMap::new();\n\n let global_env = db.global_env()?;\n\n envs.insert(EnvId::GLOBAL, global_env.clone());\n\n\n\n let mut index = 2;\n\n let env = EnvId::from(NonZeroU...
Rust
07-rust/stm32f446/stm32f446_pac/src/otg_hs_global/otg_hs_gahbcfg.rs
aaronhktan/stm32-exploration
dcd7674424cd17b02b85c6b3ce533456d5037d65
#[doc = "Reader of register OTG_HS_GAHBCFG"] pub type R = crate::R<u32, super::OTG_HS_GAHBCFG>; #[doc = "Writer for register OTG_HS_GAHBCFG"] pub type W = crate::W<u32, super::OTG_HS_GAHBCFG>; #[doc = "Register OTG_HS_GAHBCFG `reset()`'s with value 0"] impl crate::ResetValue for super::OTG_HS_GAHBCFG { type Type = ...
#[doc = "Reader of register OTG_HS_GAHBCFG"] pub type R = crate::R<u32, super::OTG_HS_GAHBCFG>; #[doc = "Writer for register OTG_HS_GAHBCFG"] pub type W = crate::W<u32, super::OTG_HS_GAHBCFG>; #[doc = "Register OTG_HS_GAHBCFG `reset()`'s with value 0"] impl crate::ResetValue for super::OTG_HS_GAHBCFG { type Type = ...
HBSTLEN_R = crate::R<u8, u8>; #[doc = "Write proxy for field `HBSTLEN`"] pub struct HBSTLEN_W<'a> { w: &'a mut W, } impl<'a> HBSTLEN_W<'a> { #[doc = r"Writes raw bits to the field"] #[inline(always)] pub unsafe fn bits(self, value: u8) -> &'a mut W { self.w.bits = (self.w.bits & !(0x0f << 1)) |...
"Clears the field bit"] #[inline(always)] pub fn clear_bit(self) -> &'a mut W { self.bit(false) } #[doc = r"Writes raw bits to the field"] #[inline(always)] pub fn bit(self, value: bool) -> &'a mut W { self.w.bits = (self.w.bits & !0x01) | ((value as u32) & 0x01); self.w ...
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
pkg-core/rate-core/src/actors/app_bind/actor/assets.rs
transparencies/rillrate
a1a6f76e84211224a85bb9fd92602d33f095229e
use super::AppBind; use crate::assets::Assets; use anyhow::Error; use async_trait::async_trait; use meio::{Context, IdOf, LiteTask, Scheduled, TaskEliminated, TaskError}; use reqwest::Url; use std::path::{Path, PathBuf}; use std::time::{Duration, Instant}; use tokio::fs::File; use tokio::io::AsyncReadExt; impl AppBind...
use super::AppBind; use crate::assets::Assets; use anyhow::Error; use async_trait::async_trait; use meio::{Context, IdOf, LiteTask, Scheduled, TaskEliminated, TaskError}; use reqwest::Url; use std::path::{Path, PathBuf}; use std::time::{Duration, Instant}; use tokio::fs::File; use tokio::io::AsyncReadExt; impl AppBind...
} else if let Some(data) = self.options.embedded.as_ref() { log::info!("Assets: embedded."); let assets = Assets::parse(data)?; self.assets = AssetsMode::Packed(assets); log::info!("Embedded assets used."); } else if let Some(url) = self.options.url.clone...
if path.starts_with("http") { log::info!("Assets: env-url."); let url: Url = path.parse()?; ctx.spawn_task(FetchUiPack(url), (), ()); } else { log::info!("Assets: env-path."); self.assets = self.read_assets(&path).await?; ...
if_condition
[ { "content": "/// Install the engine.\n\npub fn install(name: impl ToString) -> Result<(), Error> {\n\n RillRate::install(name)\n\n}\n\n\n", "file_path": "rillrate/src/lib.rs", "rank": 0, "score": 234472.19064612628 }, { "content": "pub fn typed_var<T>(name: &'static str) -> Result<Option...
Rust
tests/parse/valid/control_flow.rs
JSAbrahams/mamba
66ae435a4abf496aae945a78e4fdfa8e4785d854
use mamba::lex::tokenize; use mamba::parse::ast::Node; use mamba::parse::ast::AST; use mamba::parse::parse; use mamba::parse::parse_direct; use crate::common::*; #[test] fn for_statements() { let source = resource_content(true, &["control_flow"], "for_statements.mamba"); parse(&tokenize(&source).unwrap()).unw...
use mamba::lex::tokenize; use mamba::parse::ast::Node; use mamba::parse::ast::AST; use mamba::parse::parse; use mamba::parse::parse_direct; use crate::common::*; #[test] fn for_statements() { let source = resource_content(true, &["control_flow"], "for_statements.mamba"); parse(&tokenize(&source).unwrap()).unw...
assert_eq!(expr.node, Node::Id { lit: String::from("a") }); assert_eq!(body.node, Node::Id { lit: String::from("f") }); } #[test] fn for_range_incl_verify() { let source = String::from("for a in c ..= d do f"); let ast = parse_direct(&tokenize(&source).unwrap()).unwrap(); let (expr, col, body) =...
match col.node { Node::Range { from, to, inclusive, step } => { assert_eq!(from.node, Node::Id { lit: String::from("c") }); assert_eq!(to.node, Node::Id { lit: String::from("d") }); assert!(!inclusive); assert_eq!(step.clone().unwrap().node, Node::Id { lit: String...
if_condition
[ { "content": "#[test]\n\n#[ignore]\n\nfn core_match_statements() {\n\n let source = resource_content(true, &[\"control_flow\"], \"match.mamba\");\n\n to_py!(source);\n\n}\n\n\n", "file_path": "tests/core/control_flow.rs", "rank": 1, "score": 198184.49970102464 }, { "content": "#[test]\...
Rust
src/lib/ui/carnelian/src/render/generic/spinel/composition.rs
re995/fuchsia
02cb86f760af2aac974ba654186b73af8c16638f
use std::{ops::RangeBounds, ptr, slice}; use euclid::default::{Rect, Size2D}; use spinel_rs_sys::*; use crate::{ color::Color, drawing::DisplayRotation, render::generic::{ spinel::{init, InnerContext, Spinel}, BlendMode, Composition, Fill, FillRule, Layer, Style, }, }; fn group_laye...
use std::{ops::RangeBounds, ptr, slice}; use euclid::default::{Rect, Size2D}; use spinel_rs_sys::*; use crate::{ color::Color, drawing::DisplayRotation, render::generic::{ spinel::{init, InnerContext, Spinel}, BlendMode, Composition, Fill, FillRule, Layer, Style, }, }; fn group_laye...
; slice::from_raw_parts_mut(data, len) }; cmds[0] = SpnCommand::SpnStylingOpcodeCoverWipZero; let mut cursor = 1; match style.fill_rule { FillRule::NonZero => { cmds[cursor] = SpnCommand::SpnStylingOpcodeCoverNonzero; cursor += 1;...
init(|ptr| { spn!(spn_styling_group_layer( spn_styling, top_group, layer_id_start + i as u32, len as u32, ptr )) })
call_expression
[]
Rust
bsync/src/db.rs
losfair/blkredo
1151cd23acfd231ce10fedce4401a00e2339ed93
use std::{ convert::TryInto, path::Path, sync::{ atomic::{AtomicU64, Ordering}, Arc, }, time::{Duration, Instant, SystemTime, UNIX_EPOCH}, }; use anyhow::Result; use parking_lot::Mutex; use rusqlite::{params, Connection, OpenFlags, OptionalExtension, TransactionBehavior}; use thiserror::Error; use c...
use std::{ convert::TryInto, path::Path, sync::{ atomic::{AtomicU64, Ordering}, Arc, }, time::{Duration, Instant, SystemTime, UNIX_EPOCH}, }; use anyhow::Result; use parking_lot::Mutex; use rusqlite::{params, Connection, OpenFlags, OptionalExtension, TransactionBehavior}; use thiserror::Error; use c...
lsn > {from} and lsn <= {to} and not exists (select * from temp.squash where lsn = redo_v1.lsn); drop table temp.squash; "#, from = start_lsn, to = end_lsn)).unwrap(); txn.commit().unwrap(); Ok(()) } pub fn cas_gc(&self) { let db = self.db.lock(); db.execute_batch( r#" delete ...
d("insert into redo_v1 (block_id, hash) values(?, ?)") .unwrap(); let prev_max_lsn: Option<u64> = get_max_lsn_stmt.query_row(params![], |r| r.get(0)).unwrap(); let prev_max_lsn = prev_max_lsn.unwrap_or(0); if prev_max_lsn != base_lsn { return Err(LsnMismatch(base_lsn, prev_max_lsn).in...
random
[ { "content": "pub fn sha256hash(data: &[u8]) -> [u8; 32] {\n\n let mut h = Sha256::new();\n\n h.update(data);\n\n h.finalize().into()\n\n}\n", "file_path": "bsync/src/util.rs", "rank": 1, "score": 161150.78567438372 }, { "content": "pub fn align_block(data: &[u8]) -> Cow<[u8]> {\n\n let ...
Rust
src/network/message/coinbase/mod.rs
yobicash/yobi
20e639f8ffcf0ba8dea4123d3d4ef5a7a815e072
use libyobicash::errors::YErrorKind as LibErrorKind; use libyobicash::utils::random::*; use libyobicash::utils::time::*; use libyobicash::utils::version::*; use libyobicash::crypto::hash::digest::YDigest64; use libyobicash::crypto::hash::sha::YSHA512; use libyobicash::coinbase::YCoinbase; use bytes::{BytesMut, BufMut, ...
use libyobicash::errors::YErrorKind as LibErrorKind; use libyobicash::utils::random::*; use libyobicash::utils::time::*; use libyobicash::utils::version::*; use libyobicash::crypto::hash::digest::YDigest64; use libyobicash::crypto::hash::sha::YSHA512; use libyobicash::coinbase::YCoinbase; use bytes::{BytesMut, BufMut, ...
BigEndian::read_u32(b.get(88..92).unwrap()).into(); let cb = YCoinbase::from_bytes(b.get(92..).unwrap())?; let get_cb_res = YGetCbRes { id: id, version: version, time: time, nonce: nonce, method: method, cb: cb, }; ...
calc_id(&self) -> YHResult<YDigest64> { let mut buf = BytesMut::new(); buf.put(&self.version.to_bytes()?[..]); buf.put(&self.time.to_bytes()[..]); buf.put_u32::<BigEndian>(self.nonce); buf.put(self.method.to_bytes()); buf.put(self.cb.to_bytes()?); Ok(YSHA512::hash...
random
[ { "content": "pub fn default_version() -> YVersion {\n\n YVersion::from_str(VERSION).unwrap()\n\n}\n", "file_path": "src/version/mod.rs", "rank": 0, "score": 144484.94624858562 }, { "content": "fn main() {\n\n /*\n\n let opt = YNodeOpt::from_args();\n\n println!(\"yobicashd opt: ...
Rust
src/syndication.rs
qezz/rjbot
14ae18305ea36588750b8c34f49c749bd98217c3
use crate::context::Context; use atom_syndication::{Error as AtomError, Feed as AtomFeed}; use bytes::buf::BufExt; use carapax::{methods::SendMessage, types::ParseMode, ExecuteError}; use reqwest::{Error as HttpError, StatusCode}; use rss::{self, Channel as RssChannel, Error as RssError}; use std::{error::Error, fmt, s...
use crate::context::Context; use atom_syndication::{Error as AtomError, Feed as AtomFeed}; use bytes::buf::BufExt; use carapax::{methods::SendMessage, types::ParseMode, ExecuteError}; use reqwest::{Error as HttpError, StatusCode}; use rss::{self, Channel as RssChannel, Error as RssError}; use std::{error::Error, fmt, s...
}
let title = link.title().unwrap_or_else(|| entry.title()); Some(Post { title: title.into(), link: link.href().into(), id: Some(entry.id().to_string()), }) } }
function_block-function_prefix_line
[]
Rust
src/utils.rs
matteopolak/stock-display
d03ad470d7ef786f3652dd8ea5ba5523316d0f3a
use colored::{ColoredString, Colorize}; use plotlib::page::Page; use plotlib::repr::Plot; use plotlib::style::{PointMarker, PointStyle}; use plotlib::view::ContinuousView; use reqwest::{header, Client, Error, Response}; use std::collections::VecDeque; use std::io::{self, Write}; use std::str; use std::time::{Duration, ...
use colored::{ColoredString, Colorize}; use plotlib::page::Page; use plotlib::repr::Plot; use plotlib::style::{PointMarker, PointStyle}; use plotlib::view::ContinuousView; use reqwest::{header, Client, Error, Response}; use std::collections::VecDeque; use std::io::{self, Write}; use std::str; use std::time::{Duration, ...
; } let uri: String = constants::NASDAQ_API_ENDPOINT.replace("{ticker}", ticker); let request: Result<Response, Error> = client .get(uri) .header(header::ACCEPT_LANGUAGE, "en-US;q=0.9") .header(header::ACCEPT_ENCODING, "text") .header(header::USER_AGENT, constants::USER_AGENT_HEADER) .send() .await...
json .data .primaryData .lastSalePrice .into_bytes() .into_iter() .skip(1) .collect::<Vec<u8>>(); let price: f64 = str::from_utf8(&raw).unwrap().parse::<f64>().unwrap(); return Some(price); } None } pub async fn is_valid_ticker(ticker: &str, client: &Client) -> bool { if !(...
random
[ { "content": "\t// create a counter\n\n\tlet mut i: u32 = 1;\n\n\n\n\t// create some utility variables for metrics\n\n\tlet mut first: bool = true;\n\n\tlet mut last_price: f64 = 0.;\n\n\tlet mut total_price: f64 = 0.;\n\n\n\n\tlet history = match utils::ticker_history(&ticker, &client).await {\n\n\t\tSome(h) =...
Rust
src/bin/nydus-image/main.rs
cloudaice/image-service
7c982b2db3282d2616d37134cef8dd9ec2df426d
#[macro_use(crate_version, crate_authors)] extern crate clap; extern crate stderrlog; mod builder; mod node; mod stargz; mod tree; mod validator; #[macro_use] extern crate log; extern crate serde; const BLOB_ID_MAXIMUM_LENGTH: usize = 1024; use clap::{App, Arg, SubCommand}; use vmm_sys_util::tempfile::TempFile; ...
#[macro_use(crate_version, crate_authors)] extern crate clap; extern crate stderrlog; mod builder; mod node; mod stargz; mod tree; mod validator; #[macro_use] extern crate log; extern crate serde; const BLOB_ID_MAXIMUM_LENGTH: usize = 1024; use clap::{App, Arg, SubCommand}; use vmm_sys_util::tempfile::TempFile; ...
if !uploaded && blob_path == temp_file.as_path() { trace!("rename {:?} to {}", blob_path, blob_id); rename(blob_path, blob_id)?; blob_path = Path::new(blob_id); } } if blob_size > 0 { info!( ...
if let Some(backend_type) = matches.value_of("backend-type") { if let Some(backend_config) = matches.value_of("backend-config") { let config = factory::BackendConfig { backend_type: backend_type.to_owned(), backend_config: serde_json::f...
if_condition
[ { "content": "pub fn new_uploader(mut config: BackendConfig) -> Result<Arc<dyn BlobBackendUploader>> {\n\n // Disable http timeout for upload request\n\n config.backend_config[\"connect_timeout\"] = 0.into();\n\n config.backend_config[\"timeout\"] = 0.into();\n\n match config.backend_type.as_str() {...
Rust
vehicle-information-service/examples/server.rs
buesima/vehicle-information-service
086b9ba38947cc266867c4700e11f4e9ea727810
#[macro_use] extern crate log; extern crate structopt; use actix::prelude::*; use actix_web::{middleware, web, App, HttpResponse, HttpServer}; use futures::prelude::*; use futures_util::compat::Stream01CompatExt; use serde_json::json; use std::net::{IpAddr, Ipv4Addr, SocketAddr}; use std::sync::atomic::{AtomicUsize...
#[macro_use] extern crate log; extern crate structopt; use actix::prelude::*; use actix_web::{middleware, web, App, HttpResponse, HttpServer}; use futures::prelude::*; use futures_util::compat::Stream01CompatExt; use serde_json::json; use std::net::{IpAddr, Ipv4Addr, SocketAddr}; use std::sync::atomic::{AtomicUsize...
} #[derive(Default)] struct PrintSetRecipient {} impl Actor for PrintSetRecipient { type Context = Context<Self>; fn started(&mut self, _ctx: &mut Context<Self>) { info!( "Print `set`-recipient started, PATH: {}", PATH_PRIVATE_EXAMPLE_PRINT_SET ); } fn stoppe...
o(), value: json!(v), }; act.signal_manager_addr.do_send(update); })) }); }
function_block-function_prefixed
[ { "content": "///\n\n/// Does the val match the filter criteria\n\n/// Returns:\n\n/// Ok(true) : E.g. value changed sufficiently or there was no filter set\n\n/// Ok(false) : Did not reach change threshold\n\n/// Err(...): Occurs when the value is not an integer, filters only work for ints\n\n///\n\npub fn mat...
Rust
tests/common/mod.rs
jedel1043/regress
2c3de40bc72b1875b47fdca77b23a4c6ce22c6f9
pub fn test_parse_fails(pattern: &str) { let res = regress::Regex::new(pattern); assert!(res.is_err(), "Pattern should not have parsed: {}", pattern); } pub fn test_parse_fails_flags(pattern: &str, flags: &str) { let res = regress::Regex::with_flags(pattern, flags); assert!(res.is_err(), "Pattern shou...
pub fn test_parse_fails(pattern: &str) { let res = regress::Regex::new(pattern); assert!(res.is_err(), "Pattern should not have parsed: {}", pattern); } pub fn test_parse_fails_flags(pattern: &str, flags: &str) { let res = regress::Regex::with_flags(pattern, flags); assert!(res.is_err(), "Pattern shou...
pub fn match1_vec<'a, 'b>(&'a self, input: &'b str) -> Vec<Option<&'b str>> { let mut result = Vec::new(); let m: regress::Match = self.find(input).expect("Failed to match"); result.push(Some(&input[m.range()])); for cr in m.captures { result.push(cr.map(|r| &...
Some(r) => match input.get(r.clone()) { Some(str) => str.to_string(), None => panic!("Cannot get range from string input {:?}", r), }, None => panic!("Named capture group does not exist {}", group), }, None => panic!("Failed...
function_block-function_prefix_line
[ { "content": "/// Try parsing a given pattern.\n\n/// Return the resulting IR regex, or an error.\n\npub fn try_parse(pattern: &str, flags: api::Flags) -> Result<ir::Regex, Error> {\n\n // for q in 0..=0x10FFFF {\n\n // if let Some(c) = core::char::from_u32(q) {\n\n // let cc = folds::fold(...
Rust
mqtt/mqtt-policy/src/substituter.rs
dmolokanov/iotedge
a42fe5abbb98b6de32fd832ac75e0e8ebd740a10
use mqtt_broker::auth::Activity; use policy::{Request, Result, Substituter}; #[allow(clippy::doc_markdown)] #[derive(Debug)] pub struct MqttSubstituter { device_id: String, } impl MqttSubstituter { pub fn new(device_id: impl Into<String>) -> Self { Self { device_id: device_id.into(), ...
use mqtt_broker::auth::Activity; use policy::{Request, Result, Substituter}; #[allow(clippy::doc_markdown)] #[derive(Debug)] pub struct MqttSubstituter { device_id: String, } impl MqttSubstituter { pub fn new(device_id: impl Into<String>) -> Self { Self { device_id: device_id.into(), ...
:device_id variable")] #[test_case("namespace-{{iot:device_id}}-suffix", "test_device_auth_id", "test_device_client_id", "namespace-test_device_auth_id-suffix"; "iot:device_id variable substring")] #[test_case("{{iot:module_id}}", "test_device_id/test_module_id", ...
lue: &str, context: &Request<Self::Context>) -> Result<String> { Ok(self.replace_variable(value, context)) } fn visit_resource(&self, value: &str, context: &Request<Self::Context>) -> Result<String> { Ok(self.replace_variable(value, context)) } } #[derive(Debug)] pub(super) struct Variable...
random
[ { "content": "pub fn ensure_not_empty_with_context<D, F>(value: &str, context: F) -> Result<(), Context<D>>\n\nwhere\n\n D: fmt::Display + Send + Sync,\n\n F: FnOnce() -> D,\n\n{\n\n if value.trim().is_empty() {\n\n return Err(ErrorKind::ArgumentEmpty(String::new()).context(context()));\n\n }...
Rust
libtransact/src/context/manager/sync.rs
leebradley/transact
6aca715a5cd5b89e08e2906e48e046f210c56387
/* * Copyright 2019 Bitwise IO, Inc. * Copyright 2019 Cargill Incorporated * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unl...
/* * Copyright 2019 Bitwise IO, Inc. * Copyright 2019 Cargill Incorporated * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unl...
pub fn get( &self, context_id: &ContextId, keys: &[String], ) -> Result<Vec<(String, Vec<u8>)>, ContextManagerError> { self.internal_manager .lock() .expect("Lock in the get method was poisoned") .get(context_id, keys) } ...
--------------- */ use std::sync::{Arc, Mutex}; use crate::context::error::ContextManagerError; use crate::context::{manager, ContextId, ContextLifecycle}; use crate::protocol::receipt::{Event, TransactionReceipt}; use crate::state::Read; #[derive(Clone)] pub struct ContextManager { internal_manager: Arc<Mutex<...
random
[ { "content": "-- Copyright 2021 Cargill Incorporated\n", "file_path": "libtransact/src/state/merkle/sql/migration/postgres/migrations/2021-07-29-105100-change-log/up.sql", "rank": 0, "score": 165368.19925065702 }, { "content": "-- Copyright 2021 Cargill Incorporated\n", "file_path": "lib...
Rust
src/bin/aoc2021/day12.rs
knutwalker/aoc
711aa804ab14fc2c376db5a4140a845fa902068d
use aoc::ProcessInput; use indexmap::IndexSet; use std::{convert::Infallible, str::FromStr}; type Input = Cave; type Output = usize; register!( "input/day12.txt"; (cave: input!(process Input)) -> Output { cave.count_paths(false); cave.count_paths(true); } ); #[derive(Clone, Copy, Debug)] ...
use aoc::ProcessInput; use indexmap::IndexSet; use std::{convert::Infallible, str::FromStr}; type Input = Cave; type Output = usize; register!( "input/day12.txt"; (cave: input!(process Input)) -> Output { cave.count_paths(false); cave.count_paths(true); } ); #[derive(Clone, Copy, Debug)] ...
#[test] fn test() { let (res1, res2) = Solver::run_on_input(); assert_eq!(res1, 5756); assert_eq!(res2, 144_603); } #[bench] fn bench_parsing(b: &mut Bencher) { let input = Solver::puzzle_input(); b.bytes = input.len() as u64; b.iter(|| Solver::pars...
he fs-DX pj-RW zg-RW start-pj he-WI zg-he pj-fs start-RW "#; let (res1, res2) = Solver::run_on(input); assert_eq!(res1, 226); assert_eq!(res2, 3509); }
function_block-function_prefixed
[ { "content": "pub fn lines(s: &str) -> impl Iterator<Item = &str> + '_ {\n\n s.lines().map(str::trim).filter(|line| !line.is_empty())\n\n}\n\n\n\npub struct PuzzleSolution<T> {\n\n pub part1: T,\n\n pub part2: T,\n\n pub parse_time: Duration,\n\n pub part1_time: Duration,\n\n pub part2_time: D...
Rust
Assembler/src/asm/statement.rs
karannewatia/SCALE-MAMBA
467b33a6c80050789204ea3ee3b5cf0113354f85
use super::{Instruction, IoInstruction, Statement}; use crate::binary::instructions::RegisterMode; use crate::compiler::Compiler; use crate::lexer::{MapAllValues, Register}; use crate::span::Spanned; use crate::transforms::vectorize; use std::num::NonZeroU32; struct RegisterModeRead; struct RegisterModeWrite; trait...
use super::{Instruction, IoInstruction, Statement}; use crate::binary::instructions::RegisterMode; use crate::compiler::Compiler; use crate::lexer::{MapAllValues, Register}; use crate::span::Spanned; use crate::transforms::vectorize; use std::num::NonZeroU32; struct RegisterModeRead; struct RegisterModeWrite; trait...
}
match self { IoInstruction::InputShares { registers } => { for reg in registers { reg.map_all_values(cx, &mut f); } } IoInstruction::OutputShares { registers } => { for reg in registers { reg.map_...
function_block-function_prefix_line
[ { "content": "/// Returns `true` if the statement is valid\n\npub fn validate(cx: &Compiler, stmt: &Statement<'_>) -> bool {\n\n let relexed = stmt.relex(cx);\n\n let (instr, args) = match relexed.0.fetch_instr(cx) {\n\n Some(i) => i,\n\n None => return true,\n\n };\n\n for (arg_index,...
Rust
firmware_rust/AirQualitySensor/src/bin/firmware.rs
Tao173/AirQualitySensor
735faece883f3b21394d61d2431b15c6accc54d8
#![no_main] #![no_std] use firmware as _; use firmware::hal; #[rtic::app(device = firmware::hal::stm32, peripherals = true, dispatchers = [USART1, USART2])] mod app { use super::hal; use hal::gpio; use hal::prelude::*; use hal::stm32; use hal::timer; use systick_monotonic::*; use firmwar...
#![no_main] #![no_std] use firmware as _; use firmware::hal; #[rtic::app(device = firmware::hal::stm32, peripherals = true, dispatchers = [USART1, USART2])] mod app { use super::hal; use hal::gpio; use hal::prelude::*; use hal::stm32; use hal::timer; use systick_monotonic::*; use firmwar...
into_push_pull_output(), gpioa.pa1.into_push_pull_output(), gpioa.pa2.into_push_pull_output(), ); let next_led_tick = now + 1.millis(); led_tick::spawn_at(next_led_tick).unwrap(); let pwm1 = ctx.device.TIM16.pwm(1.khz(), &mut rcc).bind_pin(gpioa.pa6); ...
et delay = ctx.core.SYST.delay(&mut rcc); let i2c = ctx .device .I2C2 .i2c(i2c_sda, i2c_scl, hal::i2c::Config::new(100.khz()), &mut rcc); let now = monotonics::now(); let sensor_subsystem = Sensor::new(); let next_sensor_tick = now...
function_block-random_span
[]
Rust
third-party/rust/shed/futures_stats/src/futures01.rs
baioc/antlir
e3b47407b72c4aee835adf4e68fccd9abff457f2
/* * Copyright (c) Facebook, Inc. and its affiliates. * * This source code is licensed under both the MIT license found in the * LICENSE-MIT file in the root directory of this source tree and the Apache * License, Version 2.0 found in the LICENSE-APACHE file in the root directory * of this source tree. */ use f...
/* * Copyright (c) Facebook, Inc. and its affiliates. * * This source code is licensed under both the MIT license found in the * LICENSE-MIT file in the root directory of this source tree and the Apache * License, Version 2.0 found in the LICENSE-APACHE file in the root directory * of this source tree. */ use f...
; move |stats, _| { assert_eq!(stats.count, TEST_COUNT); callback_called.store(true, Ordering::SeqCst); Ok(()) } }) .boxify(); tokio_old::run(s.collect().map(|_| ())); assert!(callback_ca...
= 3; let s: BoxStream<_, ()> = iter_ok([0; TEST_COUNT].iter()) .timed({ let callback_called = callback_called.clone()
random
[ { "content": "/// A trait that provides the `timed` method to [futures_old::Stream] for gathering stats\n\npub trait TimedStreamExt: Stream + Sized {\n\n /// Combinator that returns a stream that will gather some statistics and\n\n /// pass them for inspection to the provided callback when the stream\n\n ...
Rust
src/io/seq.rs
lskatz/ROSS.rs
6dfc202ac7e2b94769657f53c450954daa7ce267
use std::collections::HashMap; use std::clone::Clone; #[test] fn test_new_seq() { let id = "MY_ID".to_string(); let seq = "AATNGGCC".to_string(); let qual = "#ABCDE!!".to_string(); let cleanable = Seq::new(&id,&seq,&qual); let formatted = format!("@{}\n{}\n+\n{}", &id, &seq, &qual); as...
use std::collections::HashMap; use std::clone::Clone; #[test] fn test_new_seq() { let id = "MY_ID".to_string(); let seq = "AATNGGCC".to_string(); let qual = "#ABCDE!!".to_string(); let cleanable = Seq::new(&id,&seq,&qual); let formatted = format!("@{}\n{}\n+\n{}", &id, &seq, &qual); as...
mber"); let seq_len = self.seq.len() as f32; if seq_len < *min_length { return false; } let mut total_qual = 0; for qual in self.qual.chars() { total_qual += qual as u32; } let avg_qual = (total_qual as f32/seq_len) ...
return false; } fn from_string (seq_str: &String) -> Seq { let mut lines = seq_str.lines(); let id = lines.next().expect("Could not parse ID"); let seq = lines.next().expect("Could not parse sequence"); lines.next().expect("Could not parse +"); let qual_opt...
random
[ { "content": "/// Propagate an error by printing invalid read(s)\n\npub fn eexit() -> () {\n\n println!(\"{}\\n{}\\n{}\\n{}\",INVALID_ID,INVALID_SEQ,INVALID_PLUS,INVALID_QUAL);\n\n std::process::exit(1);\n\n}\n\n\n\n/// Rewrite print!() so that it doesn't panic on broken\n\n/// pipe.\n\n#[macro_export]\n\...
Rust
build/header_generator.rs
u1roh/dxf-rs
76c334dce6bd863b847882a9581b1fdba67d2b68
extern crate xmltree; use self::xmltree::Element; use crate::ExpectedType; use crate::other_helpers::*; use crate::xml_helpers::*; use std::collections::HashSet; use std::fs::File; use std::io::{BufReader, Write}; use std::iter::Iterator; use std::path::Path; pub fn generate_header(generated_dir: &Path) { let e...
extern crate xmltree; use self::xmltree::Element; use crate::ExpectedType; use crate::other_helpers::*; use crate::xml_helpers::*; use std::collections::HashSet; use std::fs::File; use std::io::{BufReader, Write}; use std::iter::Iterator; use std::path::Path; pub fn generate_header(generated_dir: &Path) { let e...
fun.push_str(" "); } else { fun.push_str("\n"); fun.push_str(" match pair.code {\n"); let expected_codes: Vec<i32> = variables_with_name.iter().map(|&vv| code(&vv)).collect(); ...
if code(&v) < 0 { fun.push_str(&format!("self.{field}.set(&pair)?;", field = field(&v))); } else { let read_cmd = get_read_command(&v); fun.push_str(&format!( "verify_code(&pair, {code})?; self.{field} = {cmd};", ...
if_condition
[ { "content": "/// Formats an `f64` value with up to 12 digits of precision, ensuring at least one trailing digit after the decimal.\n\nfn format_f64(val: f64) -> String {\n\n // format with 12 digits of precision\n\n let mut val = format!(\"{:.12}\", val);\n\n\n\n // trim trailing zeros\n\n while va...
Rust
src/lib.rs
liborty/sets
bef54da79d35c0a56305d122471a7cc386d20bd4
pub mod traitimpls; pub mod mutimpls; use std::ops::{Deref,DerefMut}; use indxvec::{MinMax,wv,Indices,merge::*}; pub fn trivindex(asc:bool,n:usize) -> Vec<usize> { if asc { (0..n).collect() } else { (0..n).rev().collect() } } pub struct Set<T> { pub v: Vec<T> } impl<T: std::fmt::Display> std::fmt::Display...
pub mod traitimpls; pub mod mutimpls; use std::ops::{Deref,DerefMut}; use indxvec::{MinMax,wv,Indices,merge::*}; pub fn trivindex(asc:bool,n:usize) -> Vec<usize> { if asc { (0..n).collect() } else { (0..n).rev().collect() } } pub struct Set<T> { pub v: Vec<T> } impl<T: std::fmt::Display> std::fmt::Display...
} impl<T> Deref for OrderedSet<T> { type Target = Vec<T>; fn deref(&self) -> &Self::Target { &self.v } } impl<T> DerefMut for OrderedSet<T> { fn deref_mut(&mut self) -> &mut Self::Target { &mut self.v } } impl<T> OrderedSet<T> { pub fn from_asc_slice(s: &[T]) -> Self w...
f,"[]") } let s = if self.ascending { String::from("Ascending") } else { String::from("Descending") }; writeln!(f, "{} Ordered Set:\n{}", s, wv(&self.v) ) }
function_block-function_prefixed
[ { "content": "#[test]\n\nfn conversions() { \n\n let v = vec![1.,14.,2.,13.,3.,12.,4.,11.,5.,10.,10.,6.,9.,7.,8.,16.];\n\n let setv = Set::from_slice(&v); \n\n println!(\"{}\",setv); // Display of Set \n\n println!(\"Slice-> {}\",OrderedSet::from_slice(&v,true)); // sorted data but index lost\n\n pr...
Rust
vrp-cli/src/extensions/generate/plan.rs
valerivp/vrp
27ee30e5f4c44e051e5cec1248e606305b52fc00
#[cfg(test)] #[path = "../../../tests/unit/extensions/generate/plan_test.rs"] mod plan_test; use super::get_random_item; use vrp_core::utils::{DefaultRandom, Random}; use vrp_pragmatic::format::problem::{Job, JobPlace, JobTask, Plan, Problem}; use vrp_pragmatic::format::Location; pub(crate) fn generate_plan( prob...
#[cfg(test)] #[path = "../../../tests/unit/extensions/generate/plan_test.rs"] mod plan_test; use super::get_random_item; use vrp_core::utils::{DefaultRandom, Random}; use vrp_pragmatic::format::problem::{Job, JobPlace, JobTask, Plan, Problem}; use vrp_pragmatic::format::Location; pub(crate) fn generate_plan( prob...
fn get_plan_time_windows(plan: &Plan) -> Vec<Vec<Vec<String>>> { get_plan_places(&plan).flat_map(|job_place| job_place.times.iter()).cloned().collect() } fn get_plan_demands(plan: &Plan) -> Vec<Vec<i32>> { plan.jobs .iter() .flat_map(|job| get_job_tasks(job)) .filter_map(|job_task| jo...
let an = WGS84_A * WGS84_A * lat.cos(); let bn = WGS84_B * WGS84_B * lat.sin(); let ad = WGS84_A * lat.cos(); let bd = WGS84_B * lat.sin(); let half_size = area_size; let radius = ((an * an + bn * bn) / (ad * ad + bd * bd)).sqrt(); let pradius = radius * lat.cos(); let lat_min = rad_to_de...
function_block-function_prefix_line
[ { "content": "pub fn create_pickup_delivery_job(id: &str, pickup_location: Vec<f64>, delivery_location: Vec<f64>) -> Job {\n\n Job {\n\n pickups: Some(vec![JobTask { tag: Some(\"p1\".to_string()), ..create_task(pickup_location.clone()) }]),\n\n deliveries: Some(vec![JobTask { tag: Some(\"d1\".t...
Rust
src/container/initials.rs
olehbozhok/rsmorphy
fa23ba0306af4df8b1cd867d46415e2baac82837
use std::{borrow::Cow, fmt}; use crate::{ analyzer::MorphAnalyzer, container::{abc::*, decode::*, paradigm::ParadigmId, stack::StackSource, Lex, Score}, opencorpora::tag::OpencorporaTagReg, }; #[derive(Debug, Clone, Copy, PartialEq)] pub enum InitialsKind { FirstName, Patronym, } #[derive(Debug, ...
use std::{borrow::Cow, fmt}; use crate::{ analyzer::MorphAnalyzer, container::{abc::*, decode::*, paradigm::ParadigmId, stack::StackSource, Lex, Score}, opencorpora::tag::OpencorporaTagReg, }; #[derive(Debug, Clone, Copy, PartialEq)] pub enum InitialsKind { FirstName, Patronym, } #[derive(Debug, ...
} fn decode_tag_idx(kind: char, gender: char, case: char) -> Result<u8, DecodeError> { let kind = match kind { 'n' => 0, 'p' => 1, _ => Err(DecodeError::UnknownPartType)?, }; let gender = match gender { 'm' => 0, 'f' => 1, _ => Err(DecodeError::UnknownPartTy...
fn decode(s: &str) -> Result<(&str, Self), DecodeError> { let s = follow_str(s, "i").map_err(|_| DecodeError::UnknownPartType)?; let s = follow_str(s, ":")?; let (s, kind) = take_1_char(s)?; let (s, gender) = take_1_char(s)?; let (s, case) = take_1_char(s)?; let (s, word)...
function_block-full_function
[ { "content": "pub fn take_str_until<P>(s: &str, mut predicate: P) -> Result<(&str, &str), DecodeError>\n\nwhere\n\n P: FnMut(char) -> bool,\n\n{\n\n let mut pos = 0;\n\n for ch in s.chars() {\n\n if (predicate)(ch) {\n\n break;\n\n } else {\n\n pos += ch.len_utf8();\...
Rust
tests/unit_test.rs
ShadowPower/shadow-music-cloud
719b0e3aa59126efdf54020213b629e1e7072452
use std::{ collections::HashMap, fs, path::{Path, PathBuf}, }; use anyhow::Result; use radix_fmt::radix; use rayon::prelude::*; use shadow_music_cloud::repository::file_info; use shadow_music_cloud::{ action, command::actor::act, infra::transcoder, model::dto::FileInfo, }; use shadow_music...
use std::{ collections::HashMap, fs, path::{Path, PathBuf}, }; use anyhow::Result; use radix_fmt::radix; use rayon::prelude::*; use shadow_music_cloud::repository::file_info; use shadow_music_cloud::{ action, command::actor::act, infra::transcoder, model::dto::FileInfo, }; use shadow_music...
tils::list_audio_file(); audio_file_info_list.par_iter().for_each(|audio_file_info| { let path = PathBuf::from(app_config::AUDIO_PATH).join(&audio_file_info.path); let transcoder = transcoder::Transcoder { output_filter_spec: None, codec: Some("libopus"....
o_file_info); println!("{}", base62::encode(hash)); println!("{}", radix(hash, 36)); } } #[test] fn test_audio_hash() -> Result<()> { let audio_file_info_list = file_utils::list_audio_file(); audio_file_info_list.par_iter().for_each(|audio_file_info| { let mut path = PathBuf::new();...
random
[ { "content": "/// 计算 Hash 值\n\nfn hash(f: &dyn Fn(&mut Xxh3)) -> u128 {\n\n let mut hasher = Xxh3::with_seed(HASH_SEED);\n\n f(&mut hasher);\n\n hasher.digest128()\n\n}\n\n\n", "file_path": "src/infra/hash_utils.rs", "rank": 3, "score": 111744.02618786754 }, { "content": "/// 计算媒体文件...
Rust
qsharp-ast/src/ast/specialization.rs
msoeken/qsharp
1c1d9b81b7e97af516749574bf92eb99d420d2a5
use itertools::Itertools; use proc_macro2::Ident; use syn::{ parenthesized, parse::{Parse, ParseStream}, punctuated::Punctuated, token::Paren, Result, Token, }; use crate::ast::{kw, utilities::peek_and_consume, Scope}; #[derive(Debug, PartialEq, Clone)] pub enum SpecializationParameter { Ident...
use itertools::Itertools; use proc_macro2::Ident; use syn::{ parenthesized, parse::{Parse, ParseStream}, punctuated::Punctuated, token::Paren, Result, Token, }; use crate::ast::{kw, utilities::peek_and_consume, Scope}; #[derive(Debug, PartialEq, Clone)] pub enum SpecializationParameter { Ident...
pub fn controlled_adjoint(scope: Scope) -> Self { Self { kind: SpecializationKind::ControlledAdjoint, generator: SpecializationGenerator::Provided( Some(vec![SpecializationParameter::Identifier("ctls".into())]), scope, ), } ...
pub fn controlled(scope: Scope) -> Self { Self { kind: SpecializationKind::Controlled, generator: SpecializationGenerator::Provided( Some(vec![SpecializationParameter::Identifier("ctls".into())]), scope, ), } }
function_block-full_function
[ { "content": "pub fn peek_and_consume<T: Peek>(input: ParseStream, token: T) -> Result<bool>\n\nwhere\n\n T::Token: Parse,\n\n{\n\n Ok(if input.peek(token) {\n\n input.parse::<T::Token>()?;\n\n true\n\n } else {\n\n false\n\n })\n\n}\n\n\n", "file_path": "qsharp-ast/src/ast/...
Rust
src/lib/ui/carnelian/src/app/strategies/base.rs
dahlia-os/fuchsia-pine64-pinephone
57aace6f0b0bd75306426c98ab9eb3ff4524a61d
use crate::{ app::{ strategies::{framebuffer::FrameBufferAppStrategy, scenic::ScenicAppStrategy}, AppAssistantPtr, FrameBufferPtr, InternalSender, MessageInternal, RenderOptions, }, geometry::IntSize, input::{self}, view::{ strategies::base::{FrameBufferParams, ViewStrategy...
use crate::{ app::{ strategies::{framebuffer::FrameBufferAppStrategy, scenic::ScenicAppStrategy}, AppAssistantPtr, FrameBufferPtr, InternalSender, MessageInternal, RenderOptions, }, geometry::IntSize, input::{self}, view::{ strategies::base::{FrameBufferParams, ViewStrategy...
pub(crate) async fn create_app_strategy( assistant: &AppAssistantPtr, next_view_key: ViewKey, internal_sender: &InternalSender, ) -> Result<AppStrategyPtr, Error> { let render_options = assistant.get_render_options(); let usage = if render_options.use_spinel { FrameUsage::Gpu } else { FrameUsage::C...
function_block-full_function
[]
Rust
mailin/src/smtp.rs
trevyn/mailin
368bfe2b97b94ca19b9234d05ba0030cfacc6b3f
use std::net::IpAddr; use std::str; use crate::fsm::StateMachine; use crate::response::*; use crate::{AuthMechanism, Handler}; use either::{Left, Right}; #[derive(Clone)] pub enum Cmd<'a> { Ehlo { domain: &'a str, }, Helo { domain: &'a str, }, Mail { reverse_path: &'a str, ...
use std::net::IpAddr; use std::str; use crate::fsm::StateMachine; use crate::response::*; use crate::{AuthMechanism, Handler}; use either::{Left, Right}; #[derive(Clone)] pub enum Cmd<'a> { Ehlo { domain: &'a str, }, Helo { domain: &'a str, }, Mail { reverse_path: &'a str, ...
dr; use ternop::ternary; struct EmptyHandler {} impl Handler for EmptyHandler {} struct DataHandler(Vec<u8>); impl Handler for DataHandler { fn data(&mut self, buf: &[u8]) -> std::io::Result<()> { self.0.extend(buf); Ok(()) } } macro_rules! asse...
anisms: Vec::with_capacity(4), } } pub fn enable_start_tls(&mut self) -> &mut Self { self.start_tls_extension = true; self } pub fn enable_auth(&mut self, auth: AuthMechanism) -> &mut Self { self.auth_mechanisms.push(auth); self } pub fn ...
random
[ { "content": "fn handle_rset(fsm: &StateMachine, domain: &str) -> (Response, Option<Box<dyn State>>) {\n\n match fsm.auth_state {\n\n AuthState::Unavailable => (\n\n OK,\n\n Some(Box::new(Hello {\n\n domain: domain.to_string(),\n\n })),\n\n ),\n\n...
Rust
src/output.rs
sthagen/mitsuhiko-insta
c27c8bde0bbcf38da480feefdf3eba18138ef9a3
use std::{path::Path, time::Duration}; use similar::{Algorithm, ChangeTag, TextDiff}; use crate::snapshot::Snapshot; use crate::utils::{format_rust_expression, style, term_width}; pub fn print_snapshot_summary( workspace_root: &Path, snapshot: &Snapshot, snapshot_file: Option<&Path>, mut line: Option...
use std::{path::Path, time::Duration}; use similar::{Algorithm, ChangeTag, TextDiff}; use crate::snapshot::Snapshot; use crate::utils::{format_rust_expression, style, term_width}; pub fn print_snapshot_summary( workspace_root: &Path, snapshot: &Snapshot, snapshot_file: Option<&Path>, mut line: Option...
width = term_width(); println!( "{title:━^width$}", title = style(" Snapshot Summary ").bold(), width = width ); print_snapshot_summary(workspace_root, new_snapshot, snapshot_file, Some(line)); println!("{title:━^width$}", title = "", width = width); } pub fn print_changeset(ol...
rkspace_root: &Path, new_snapshot: &Snapshot, old_snapshot: Option<&Snapshot>, line: u32, snapshot_file: Option<&Path>, ) { let _old_snapshot = old_snapshot; let
function_block-random_span
[ { "content": "/// Memoizes a snapshot file in the reference file.\n\npub fn memoize_snapshot_file(snapshot_file: &Path) {\n\n if let Ok(path) = env::var(\"INSTA_SNAPSHOT_REFERENCES_FILE\") {\n\n let mut f = fs::OpenOptions::new()\n\n .write(true)\n\n .append(true)\n\n ...
Rust
tests/geometry/dual_quaternion.rs
zyansheep/nalgebra
e913beca889dc278d1c0d6cadd2008d3f9bcc0af
#![cfg(feature = "proptest-support")] #![allow(non_snake_case)] use na::{DualQuaternion, Point3, Unit, UnitDualQuaternion, UnitQuaternion, Vector3}; use crate::proptest::*; use proptest::{prop_assert, proptest}; proptest!( #[test] fn isometry_equivalence(iso in isometry3(), p in point3(), v in vector3()) { ...
#![cfg(feature = "proptest-support")] #![allow(non_snake_case)] use na::{DualQuaternion, Point3, Unit, UnitDualQuaternion, UnitQuaternion, Vector3}; use crate::proptest::*; use proptest::{prop_assert, proptest}; proptest!( #[test] fn isometry_equivalence(iso in isometry3(), p in point3(), v in vector3()) { ...
fn all_op_exist( dq in dual_quaternion(), udq in unit_dual_quaternion(), uq in unit_quaternion(), s in PROPTEST_F64, t in translation3(), v in vector3(), p in point3() ) { let dqMs: DualQuaternion<_> = dq * s; let dqMdq: DualQuaternion<_>...
1.0e-7)); prop_assert!(relative_eq!(unit.sclerp(&unit2, 0.5).real, unit.real, epsilon = 1.0e-7)); prop_assert!(relative_eq!(unit.sclerp(&unit2, 1.0).real, unit.real, epsilon = 1.0e-7)); prop_assert!(relative_eq!(unit.sclerp(&unit2, s).real, unit.real, epsilon = 1.0e-7)); prop_assert!(r...
random
[ { "content": "fn length_on_direction_with_unit(v: &Vector3<f32>, dir: &Unit<Vector3<f32>>) -> f32 {\n\n // No need to normalize `dir`: we know that it is non-zero and normalized.\n\n v.dot(dir.as_ref())\n\n}\n\n\n", "file_path": "examples/unit_wrapper.rs", "rank": 0, "score": 256287.2837648631...
Rust
tiled/src/json_parser.rs
lenscas/hv-dev
7ae07cb889b20f382acd7293d80dfe3319a91123
use crate::*; use hv::prelude::*; impl Tileset { pub fn json_parse_tileset( v: &Value, first_gid: u32, path_prefix: Option<&str>, tileset_number: u8, slab: &mut slab::Slab<Object>, filename: String, ) -> Result<Self> { let json_obj = v .as_obj...
use crate::*; use hv::prelude::*; impl Tileset { pub fn json_parse_tileset( v: &Value, first_gid: u32, path_prefix: Option<&str>, tileset_number: u8, slab: &mut slab::Slab<Object>, filename: String, ) -> Result<Self> { let json_obj = v .as_obj...
} }
Ok(Object { name: object .get("name") .ok_or_else(|| anyhow!("Object did not have a name"))? .as_str() .ok_or_else(|| anyhow!("Name couldn't be converted to a string"))? .to_owned(), visible: object ....
call_expression
[ { "content": "pub fn to_chunks(data: &[TileId], width: u32, height: u32) -> Chunks {\n\n let mut chunks = Chunks::default();\n\n for y in 0..height {\n\n for x in 0..width {\n\n let (chunk_x, chunk_y, tile_x, tile_y) =\n\n to_chunk_indices_and_subindices(x as i32, y as i32...
Rust
src/sql/src/plan/scope.rs
jtcohen6/materialize
88815e32ea26a5ee3abf04c2bbb49ee27ace22d4
use itertools::Itertools; use repr::ColumnName; use crate::names::PartialName; use crate::plan::error::PlanError; use crate::plan::expr::ColumnRef; use sql_parser::ast::Raw; #[derive(Debug, Clone, PartialEq)] pub struct ScopeItemName { pub table_name: Option<PartialName>, pub column_name: Option<ColumnName...
use itertools::Itertools; use repr::ColumnName; use crate::names::PartialName; use crate::plan::error::PlanError; use crate::plan::expr::ColumnRef; use sql_parser::ast::Raw; #[derive(Debug, Clone, PartialEq)] pub struct ScopeItemName { pub table_name: Option<PartialName>, pub column_name: Option<ColumnName...
pub fn resolve_table_column<'a>( &'a self, table_name: &PartialName, column_name: &ColumnName, ) -> Result<(ColumnRef, &'a ScopeItemName), PlanError> { self.resolve( |item: &ScopeItemName| { item.table_name.as_ref() == Some(table_name) ...
pub fn resolve_column<'a>( &'a self, column_name: &ColumnName, ) -> Result<(ColumnRef, &'a ScopeItemName), PlanError> { self.resolve( |item: &ScopeItemName| item.column_name.as_ref() == Some(column_name), column_name.as_str(), ) }
function_block-full_function
[ { "content": "fn pad_formats(formats: Vec<pgrepr::Format>, n: usize) -> Result<Vec<pgrepr::Format>, String> {\n\n match (formats.len(), n) {\n\n (0, e) => Ok(vec![pgrepr::Format::Text; e]),\n\n (1, e) => Ok(iter::repeat(formats[0]).take(e).collect()),\n\n (a, e) if a == e => Ok(formats),...
Rust
matrix_sdk_appservice/tests/tests.rs
DevinR528/matrix-rust-sdk
4c09c6272bb3636e20d99177357cd31b80a2c1bf
use std::env; use matrix_sdk::{ api_appservice, api_appservice::Registration, async_trait, events::{room::member::MemberEventContent, AnyEvent, AnyStateEvent, SyncStateEvent}, room::Room, EventHandler, Raw, }; use matrix_sdk_appservice::*; use matrix_sdk_test::async_test; use serde_json::json; ...
use std::env; use matrix_sdk::{ api_appservice, api_appservice::Registration, async_trait, events::{room::member::MemberEventContent, AnyEvent, AnyStateEvent, SyncStateEvent}, room::Room, EventHandler, Raw, }; use matrix_sdk_appservice::*; use matrix_sdk_test::async_test; use serde_json::json; ...
; let homeserver_url = mockito::server_url(); let server_name = "localhost"; Ok(Appservice::new(homeserver_url.as_ref(), server_name, registration).await?) } fn member_json() -> serde_json::Value { json!({ "content": { "avatar_url": null, "displayname": "example", ...
match registration { Some(registration) => registration.into(), None => AppserviceRegistration::try_from_yaml_str(registration_string()).unwrap(), }
if_condition
[ { "content": "fn encode_key_info(info: &RequestedKeyInfo) -> String {\n\n format!(\n\n \"{}{}{}{}\",\n\n info.room_id, info.sender_key, info.algorithm, info.session_id\n\n )\n\n}\n\n\n\n/// An in-memory only store that will forget all the E2EE key once it's dropped.\n\n#[derive(Debug, Clone)...
Rust
old/server/src/main.rs
icefoxen/WorldDocCode
45cb146ebdceca077bb910ca2af40c16232848a4
#[macro_use] extern crate rouille; extern crate lazy_static; extern crate serde; extern crate rustc_serialize; extern crate ring; extern crate untrusted; extern crate base64; use std::collections::HashMap; use std::sync::RwLock; use rouille::Response; extern crate protocol; use protocol::*; use ring::{signature, ra...
#[macro_use] extern crate rouille; extern crate lazy_static; extern crate serde; extern crate rustc_serialize; extern crate ring; extern crate untrusted; extern crate base64; use std::collections::HashMap; use std::sync::RwLock; use rouille::Response; extern crate protocol; use protocol::*; use ring::{signature, ra...
lazy_static! { static ref SERVER_THREAD: thread::JoinHandle<()> = thread::spawn(start_test_server); static ref KEYPAIR: signature::Ed25519KeyPair = generate_keypair(); } fn spawn_server_and_get(path: &str) -> reqwest::Response { lazy_static::initialize(&SERVER_THREAD); let...
fn generate_keypair() -> signature::Ed25519KeyPair { let rng = rand::SystemRandom::new(); let pkcs8_bytes = signature::Ed25519KeyPair::generate_pkcs8(&rng).unwrap(); let keypair = signature::Ed25519KeyPair::from_pkcs8( untrusted::Input::from(&pkcs8_bytes) ).unwrap(); ...
function_block-full_function
[ { "content": "fn get_ipfs_doc(name: &str) {\n\n // Using 'get' here \n\n let url = format!(\"http://localhost:5001/api/v0/cat?arg={}\", name);\n\n let mut resp = reqwest::get(&url).expect(\"Could not get IPFS doc?\");\n\n let mut content = String::new();\n\n resp.read_to_string(&mut content).unwr...
Rust
src/search/old.rs
KevinWMatthews/mindbase
ab70ffd27c35acec0a0ecedf787234e8980d6e73
use crate::{ allegation::{ Allegation, Body, }, mbql::{ ast, error::{ MBQLError, MBQLErrorKind, }, query::BindResult, Query, }, symbol::Atom, AgentId, AllegationId, Analogy, ArtifactId, MBError, ...
use crate::{ allegation::{ Allegation, Body, }, mbql::{ ast, error::{ MBQLError, MBQLErrorKind, }, query::BindResult, Query, }, symbol::Atom, AgentId, AllegationId, Analogy, ArtifactId, MBError, ...
} struct SortedIntersect<L, R> where L: Iterator<Item = R::Item>, R: Iterator { left: Peekable<L>, right: Peekable<R>, } impl<L, R> SortedIntersect<L, R> where L: Iterator<Item = R::Item>, R: Iterator { fn new(left: L, right: R) -> Self { SortedIntersect { left: ...
p(), side: ItemSide::Right, }) }, None => None, } }
function_block-function_prefixed
[ { "content": "pub fn parse<T: std::io::BufRead>(reader: T, query: &mut super::Query) -> Result<(), MBQLError> {\n\n for (line_number, line) in reader.lines().enumerate() {\n\n let line_str: String = line.map_err(|error| {\n\n MBQLError { position: Position { row: ...
Rust
src/liberty.rs
marlls1989/liberty-parse
efd8bbe621f4a8a612910c47608c0665993a77a8
use std::{ collections::BTreeMap, fmt, ops::{Deref, DerefMut}, }; use crate::ast::{GroupItem, LibertyAst, Value}; #[derive(Debug, PartialEq, Clone)] pub struct Liberty(pub Vec<Library>); impl Liberty { pub fn to_ast(self) -> LibertyAst { LibertyAst( self.0 .into_...
use std::{ collections::BTreeMap, fmt, ops::{Deref, DerefMut}, }; use crate::ast::{GroupItem, LibertyAst, Value}; #[derive(Debug, PartialEq, Clone)] pub struct Liberty(pub Vec<Library>); impl Liberty { pub fn to_ast(self) -> LibertyAst { LibertyAst( self.0 .into_...
} Self { name, type_, simple_attributes, complex_attributes, groups, } } pub fn into_group_item(self) -> GroupItem { let mut items: Vec<GroupItem> = Vec::with_capacity( self.simple_attributes.len() + s...
match item { GroupItem::SimpleAttr(name, value) => { simple_attributes.insert(name, value); } GroupItem::ComplexAttr(name, value) => { complex_attributes.insert(name, value); } GroupItem::Group(type_,...
if_condition
[ { "content": "pub fn parse_libs<'a, E: ParseError<&'a str>>(input: &'a str) -> IResult<&str, Vec<GroupItem>, E> {\n\n context(\n\n \"parse_libs\",\n\n all_consuming(terminated(\n\n fold_many0(\n\n alt((\n\n context(\n\n \"outer...
Rust
src/libpcp/term/constant.rs
ptal/pcp
5775dd8523a35ff521daf3cfa709794829d75955
use term::ops::*; use model::*; use kernel::*; use propagation::events::*; use gcollections::ops::*; use gcollections::*; use std::fmt::Debug; #[derive(Clone, Debug)] pub struct Constant<V> { value: V } impl<V> Constant<V> { pub fn new(value: V) -> Constant<V> { Constant { value: value } } } im...
use term::ops::*; use model::*; use kernel::*; use propagation::events::*; use gcollections::ops::*; use gcollections::*; use std::fmt::Debug; #[derive(Clone, Debug)] pub struct Constant<V> { value: V } impl<V> Constant<V> { pub fn new(value: V) -> Constant<V> { Constant { value: value } } } im...
}
fn unary_propagator_test_one<P, R>(id: u32, x: Interval<i32>, c: i32, make_prop: P, before: SKleene, after: SKleene, expected: Vec<(usize, FDEvent)>, propagate_success: bool) where P: FnOnce(FDVar, FDVar) -> R, R: PropagatorConcept<VStoreFD, FDEvent> { let mut store = VStore::empty(); let x = Box::n...
function_block-full_function
[ { "content": "pub fn x_leq_y<VStore, Domain, Bound>(x: Var<VStore>, y: Var<VStore>) -> XLessEqY<VStore> where\n\n VStore: VStoreConcept<Item=Domain> + 'static,\n\n Domain: Collection<Item=Bound> + IntDomain,\n\n Bound: IntBound\n\n{\n\n XLessY::new(x, Box::new(Addition::new(y, Bound::one())))\n\n}\n\n\n", ...
Rust
src/state.rs
macfadyen/sailfish
44752a6769a2a7566a90dd9c8df21d4e2c49d720
use crate::cmdline::CommandLine; use crate::error; use crate::{Mesh, Patch, PointMass, Setup}; use std::fs::{create_dir_all, File}; use std::io::prelude::*; use std::io::Write; #[derive(Debug, Clone, Copy)] pub enum Recurrence { Linear(f64), Log(f64), } #[derive(Debug, Clone, serde::Serialize, serde::Deserial...
use crate::cmdline::CommandLine; use crate::error; use crate::{Mesh, Patch, PointMass, Setup}; use std::fs::{create_dir_all, File}; use std::io::prelude::*; use std::io::Write; #[derive(Debug, Clone, Copy)] pub enum Recurrence { Linear(f64), Log(f64), } #[derive(Debug, Clone, serde::Serialize, serde::Deserial...
pub fn set_primitive(&mut self, primitive: Vec<f64>) { assert!( primitive.len() == self.primitive.len(), "new and old primitive array sizes must match" ); self.primitive = primitive; } pub fn write_checkpoint( &mut self, setup: &dyn Setup, ...
or)?; let mut state: State = rmp_serde::from_read_ref(&bytes) .map_err(|e| error::Error::InvalidCheckpoint(format!("{}", e)))?; if !state.parameters.is_empty() && !new_parameters.is_empty() { state.parameters += ":"; } state.parameters += new_parameters; ...
function_block-function_prefixed
[ { "content": "/// Tries to construct a dynamic setup from a string key and model parameter\n\n/// string.\n\n///\n\n/// The result is put under `Arc` so it can be attached to solver instances\n\n/// and shared safely between threads. If no setup matches the given name, a\n\n/// `PrintUserInformation` error is r...
Rust
tests/mixins.rs
redzic/grass
37c1ada66418fdbb87968ede91efb9be83a80afa
#![cfg(test)] #[macro_use] mod macros; test!( basic_mixin, "@mixin a {\n color: red;\n}\n\nb {\n @include a;\n}\n", "b {\n color: red;\n}\n" ); test!(empty_mixin, "@mixin a {}\n\nb {\n @include a;\n}\n", ""); test!( just_a_comment, "@mixin foo() {\n /* begin foo */\n}\n\na {\n @include foo...
#![cfg(test)] #[macro_use] mod macros; test!( basic_mixin, "@mixin a {\n color: red;\n}\n\nb {\n @include a;\n}\n", "b {\n color: red;\n}\n" ); test!(empty_mixin, "@mixin a {}\n\nb {\n @include a;\n}\n", ""); test!( just_a_comment, "@mixin foo() {\n /* begin
color: red;\n }\n}\n\n@include a;\n", "a {\n color: red;\n}\n" ); test!( include_list, "@mixin foo($x) {\n color: $x;\n}\na {\n @include foo(0px 0px 0px 0px #ef8086 inset !important);\n}\n", "a {\n color: 0px 0px 0px 0px #ef8086 inset !important;\n}\n" ); test!( content_without_variable, "...
foo */\n}\n\na {\n @include foo();\n}\n", "a {\n /* begin foo */\n}\n" ); test!( mixin_two_styles, "@mixin a {\n color: red;\n color: blue;\n}\n\nb {\n @include a;\n}\n", "b {\n color: red;\n color: blue;\n}\n" ); test!( mixin_ruleset, "@mixin a {\n b {\n color: red;\n }\n}\nb {\n...
random
[ { "content": "#![cfg(test)]\n\n\n\n#[macro_export]\n\nmacro_rules! test {\n\n ($( #[$attr:meta] ),*$func:ident, $input:expr) => {\n\n $(#[$attr])*\n\n #[test]\n\n #[allow(non_snake_case)]\n\n fn $func() {\n\n let sass = grass::from_string($input.to_string())\n\n ...
Rust
examples/custom-source.rs
Re3Studios/assets_manager
f6a0390aae4072f7d9e7084433f5fb585bc5fe8f
use assets_manager::{ hot_reloading::{DynUpdateSender, EventSender, FsWatcherBuilder}, source::{DirEntry, FileSystem, Source}, AssetCache, BoxedError, }; use std::{ borrow::Cow, io, path::{Path, PathBuf}, }; #[derive(Debug, Clone)] pub struct FsWithOverride { default_dir: FileSystem, ...
use assets_manager::{ hot_reloading::{DynUpdateSender, EventSender, FsWatcherBuilder}, source::{DirEntry, FileSystem, Source}, AssetCache, BoxedError, }; use std::{ borrow::Cow, io, path::{Path, PathBuf}, }; #[derive(Debug, Clone)] pub struct FsWithOverride { default_dir: FileSystem, ...
|| self.default_dir.exists(entry) } fn configure_hot_reloading(&self, events: EventSender) -> Result<DynUpdateSender, BoxedError> { let mut builder = FsWatcherBuilder::new()?; if let Some(dir) = &self.override_dir { builder.watch(dir.root().to_owned())?; ...
try: DirEntry) -> bool { self.override_dir .as_ref() .map_or(false, |dir| dir.exists(entry))
function_block-random_span
[ { "content": "fn load<A: Asset>(source: &dyn Source, id: &str) -> Result<Box<dyn AnyAsset>, Error> {\n\n let asset = load_from_source::<A, _>(source, id)?;\n\n Ok(Box::new(asset))\n\n}\n\n\n", "file_path": "src/key.rs", "rank": 0, "score": 240843.7802783121 }, { "content": "fn read_dir...
Rust
src/geom.rs
H2CO3/quirs
44b75e71d5578dd605bd12d88d45eb2763d3e071
use std::fmt; use util::int_to_usize; use info::Info; use quirc_sys::{ quirc_point, quirc_code, quirc_data }; use quirc_sys::{ quirc_decode, quirc_decode_error_t }; use error::{ Error, Result }; use self::quirc_decode_error_t::QUIRC_SUCCESS; #[derive(Debug, Clone, Copy, Default, PartialEq, Eq, Hash)] pub struct Vec2...
use std::fmt; use util::int_to_usize; use info::Info; use quirc_sys::{ quirc_point, quirc_code, quirc_data }; use quirc_sys::{ quirc_decode, quirc_decode_error_t }; use error::{ Error, Result }; use self::quirc_decode_error_t::QUIRC_SUCCESS; #[derive(Debug, Clone, Copy, Default, PartialEq, Eq, Hash)] pub struct Vec2...
a } pub fn width(&self) -> usize { self.size.x } pub fn height(&self) -> usize { self.size.y } } #[derive(Clone, Copy)] pub struct QrCode(quirc_code); impl QrCode { #[doc(hidden)] pub fn from_raw(raw: quirc_code) -> Result<Self> { let _ = int_to_usi...
data: &'a [u8], size: Vec2D, } impl<'a> Image<'a> { pub fn new(data: &'a [u8], size: Vec2D) -> Result<Self> { if data.len() == size.x * size.y { Ok(Image { data, size }) } else { Err(Error::SizeMismatch) } } pub fn data(&sel...
random
[ { "content": "#[cfg_attr(feature = \"cargo-clippy\", allow(if_same_then_else, cast_possible_truncation, cast_possible_wrap))]\n\npub fn usize_to_int(n: usize) -> Result<c_int> {\n\n if size_of::<usize>() < size_of::<c_int>() {\n\n Ok(n as c_int)\n\n } else if n <= INT_MAX as usize {\n\n Ok(n...