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
src/main.rs
wspeirs/seal
415e6f76642300ced7c7a12d4582cc818a427131
#[macro_use] extern crate log; extern crate fern; extern crate chrono; extern crate clap; extern crate ring; extern crate zstd; #[macro_use] extern crate serde_derive; extern crate rmp_serde as rmps; extern crate serde; mod enc; use zstd::block::{Compressor, Decompressor}; use clap::{Arg, App}; use ring::rand::{Syste...
#[macro_use] extern crate log; extern crate fern; extern crate chrono; extern crate clap; extern crate ring; extern crate zstd; #[macro_use] extern crate serde_derive; extern crate rmp_serde as rmps; extern crate serde; mod enc; use zstd::block::{Compressor, Decompressor}; use clap::{Arg, App}; use ring::rand::{Syste...
#[test] fn test_zero_block_compress_decompress() { compress_decompress_test(0); } #[test] fn test_small_compress_decompress() { compress_decompress_test(10); } #[test] fn test_single_block_compress_decompress() { compress_decompress_test(crate::BLOCK_SIZE); } #[test] fn test_two_blocks_compress_decomp...
ec()); crate::decompress(&mut compress_reader, &mut plaintext_buffer).expect("Error decompressing"); assert_eq!(plaintext_buffer, input_reader.into_inner()); }
function_block-function_prefixed
[ { "content": " self.buff[8..].copy_from_slice(&tmp);\n\n\n\n Ok(Nonce::assume_unique_for_key(self.buff))\n\n }\n\n}\n\n\n\n///\n\n/// Seals (encrypts) data block-by-block\n\n///\n\npub struct Sealer {\n\n sealing_key: SealingKey<CountingNonceSequence>\n\n}\n\n\n\nimpl Sealer {\n\n pub fn ...
Rust
src/persist/src/indexed/columnar/arrow.rs
pH14/materialize
f2367e6b404f83038bacb9d04b5566b0cbdd433f
use std::collections::HashMap; use std::io::{Read, Seek, Write}; use std::sync::Arc; use arrow2::array::{BinaryArray, PrimitiveArray}; use arrow2::datatypes::{DataType, Field, Schema}; use arrow2::io::ipc::read::{read_file_metadata, FileMetadata, FileReader}; use arrow2::io::ipc::write::{FileWriter, WriteOptions}; u...
use std::collections::HashMap; use std::io::{Read, Seek, Write}; use std::sync::Arc; use arrow2::array::{BinaryArray, PrimitiveArray}; use arrow2::datatypes::{DataType, Field, Schema}; use arrow2::io::ipc::read::{read_file_metadata, FileMetadata, FileReader}; use arrow2::io::ipc::write::{FileWriter, WriteOptions}; u...
pub fn decode_unsealed_arrow<R: Read + Seek>(r: &mut R) -> Result<BlobUnsealedBatch, Error> { let file_meta = read_file_metadata(r)?; let (format, meta) = decode_unsealed_inline_meta(file_meta.schema().metadata().get(INLINE_METADATA_KEY))?; let updates = match format { ProtoBatchFormat::U...
INLINE_METADATA_KEY.into(), encode_trace_inline_meta(batch, ProtoBatchFormat::ArrowKVTD), ); let schema = Schema::new_from(SCHEMA_ARROW_KVTD.fields().clone(), metadata); let options = WriteOptions { compression: None }; let mut writer = FileWriter::try_new(w, &schema, options)?; let records ...
function_block-function_prefix_line
[ { "content": "/// Encodes an BlobTraceBatch into the Parquet format.\n\npub fn encode_trace_parquet<W: Write>(w: &mut W, batch: &BlobTraceBatch) -> Result<(), Error> {\n\n let updates = batch\n\n .updates\n\n .iter()\n\n .map(|((k, v), t, d)| ((k.to_vec(), v.to_vec()), *t, *d))\n\n ...
Rust
src/lib.rs
LazyMechanic/tocket
c25b364e4acbe77b952cc97a58234ab354e5baf3
#![cfg_attr(docsrs, feature(doc_cfg))] pub mod in_memory; #[cfg(feature = "distributed-impl")] #[cfg_attr(docsrs, doc(cfg(feature = "distributed-impl")))] pub mod distributed; #[cfg(feature = "redis-impl")] #[cfg_attr(docsrs, doc(cfg(feature = "redis-impl")))] pub mod in_redis; pub use in_memory::*; #[cfg(feature ...
#![cfg_attr(docsrs, feature(doc_cfg))] pub mod in_memory; #[cfg(feature = "distributed-impl")] #[cfg_attr(docsrs, doc(cfg(feature = "distributed-impl")))] pub mod distributed; #[cfg(feature = "redis-impl")] #[cfg_attr(docsrs, doc(cfg(feature = "redis-impl")))] pub mod in_redis; pub use in_memory::*; #[cfg(feature ...
} #[derive(Debug, thiserror::Error)] #[error("rate limit exceeded")] pub struct RateLimitExceededError(());
let tokens_since_last_refill = { let mut tokens_count = 0u32; let mut k = since_last_refill; loop { k -= state.refill_tick; if k <= time::Duration::ZERO { break; } tokens_count += 1; } ...
function_block-function_prefix_line
[ { "content": " pub trait Sealed {}\n\n\n\n impl Sealed for WhitelistStrategy {}\n\n}\n", "file_path": "src/distributed/mod.rs", "rank": 0, "score": 119333.56078742174 }, { "content": "#[async_trait::async_trait]\n\npub trait Strategy: private::Sealed {\n\n async fn on_acquire(\n\n ...
Rust
examples/sandbox.rs
slyedoc/bevy_physics_take2
2c959915b5b3d01f3a9d965d52cea84431a51177
mod helper; use bevy::prelude::*; use bevy_physics_take2::{Body, ColliderSphere, Mass, PhysicsPlugin}; use helper::HelperPlugin; fn main() { App::new() .insert_resource(Msaa { samples: 4 }) .insert_resource(WindowDescriptor { title: "Physics Sandbox".to_string(), vsync: fals...
mod helper; use bevy::prelude::*; use bevy_physics_take2::{Body, ColliderSphere, Mass, PhysicsPlugin}; use helper::HelperPlugin; fn main() { App::new() .insert_resource(Msaa { samples: 4 }) .insert_resource(WindowDescriptor { title: "Physics Sandbox".to_string(), vsync: fals...
commands .spawn_bundle(PbrBundle { transform: Transform::from_xyz(0.0, 1.0, 0.0), mesh: ball_mesh.clone(), material: ball_material.clone(), ..Default::default() }) .insert(Body { linear_velocity...
let ball_mesh = meshes.add(Mesh::from(bevy::render::mesh::shape::UVSphere { radius: 0.5, ..Default::default() }));
assignment_statement
[ { "content": "#[allow(dead_code)]\n\npub fn spawn_light(commands: &mut Commands) {\n\n const HALF_SIZE: f32 = 50.0;\n\n commands\n\n .spawn_bundle(DirectionalLightBundle {\n\n directional_light: DirectionalLight {\n\n illuminance: 10000.0,\n\n // Configure t...
Rust
src/connectivity/bluetooth/profiles/bt-a2dp-sink/src/connected_peers.rs
zarelaky/fuchsia
858cc1914de722b13afc2aaaee8a6bd491cd8d9a
use { anyhow::format_err, bt_a2dp::media_types::*, bt_a2dp_sink_metrics as metrics, bt_avdtp as avdtp, fidl_fuchsia_bluetooth_bredr::{Channel, ProfileDescriptor, ProfileProxy}, fuchsia_async as fasync, fuchsia_bluetooth::{ detachable_map::{DetachableMap, DetachableWeak}, types:...
use { anyhow::format_err, bt_a2dp::media_types::*, bt_a2dp_sink_metrics as metrics, bt_avdtp as avdtp, fidl_fuchsia_bluetooth_bredr::{Channel, ProfileDescriptor, ProfileProxy}, fuchsia_async as fasync, fuchsia_bluetooth::{ detachable_map::{DetachableMap, DetachableWeak}, types:...
#[test] fn connected_peers_reconnect_works() { let (mut exec, id, mut peers, _stream) = setup_connected_peer_test(); let (remote, channel) = new_channel(); peers.connected(id, channel, false); run_to_stalled(&mut exec); drop(remote); run_to_stalled(&...
fn connected_peers_peer_disconnect_removes_peer() { let (mut exec, id, mut peers, _stream) = setup_connected_peer_test(); let (remote, channel) = new_channel(); peers.connected(id, channel, false); run_to_stalled(&mut exec); drop(remote); run_to_stalled(&mut ...
function_block-full_function
[]
Rust
lib/src/interpolate.rs
guangie88/envja
e9fc191a8cc972deac8778d5963b23b50f608d51
use crate::{EnvjaParser, Rule}; use pest::{iterators::Pair, Parser}; use std::collections::HashMap; use std::error::Error; use std::fmt; pub type Mappings = HashMap<String, String>; pub type DynError = Box<dyn Error>; #[derive(Clone, Debug)] pub struct InterpolateError { rule: Rule, msg: String, } impl Inter...
use crate::{EnvjaParser, Rule}; use pest::{iterators::Pair, Parser}; use std::collections::HashMap; use std::error::Error; use std::fmt; pub type Mappings = HashMap<String, String>; pub type DynError = Box<dyn Error>; #[derive(Clone, Debug)] pub struct InterpolateError { rule: Rule, msg: String, } impl Inter...
pub fn interpolate( template: &str, mappings: &Mappings, ) -> Result<String, DynError> { let pairs = EnvjaParser::parse(Rule::doc, template)?; let mut buffer = String::new(); for p in pairs { match p.as_rule() { Rule::compound => { interpolate_compound_impl(p, ...
Rule::text => { buffer.push_str(p.as_str()); } Rule::compound => { interpolate_compound_impl(p, buffer, mappings)?; } r => { Err(InterpolateError::new( r, "Unexpected sub-rule at compo...
function_block-function_prefix_line
[ { "content": "fn main() -> Result<(), DynError> {\n\n let conf = Config::from_args();\n\n let mappings = env::vars().collect();\n\n\n\n let template = match conf.mode {\n\n Mode::File { path } => fs::read_to_string(&path)?,\n\n Mode::Direct { content } => {\n\n if let Some(cont...
Rust
guard/src/commands/files.rs
shreyasdamle/cloudformation-guard
4a111c40b4694ed182dc1a40d728000529d933a2
use std::cmp::Ordering; use std::fs::File; use std::io::{BufReader, Read}; use std::path::PathBuf; use std::str::FromStr; use crate::rules::errors::Error; use walkdir::{DirEntry, WalkDir}; pub(crate) fn read_file_content(file: File) -> Result<String, std::io::Error> { let mut file_content = String::new(); let...
use std::cmp::Ordering; use std::fs::File; use std::io::{BufReader, Read}; use std::path::PathBuf; use std::str::FromStr; use crate::rules::errors::Error; use walkdir::{DirEntry, WalkDir}; pub(crate) fn read_file_content(file: File) -> Result<String, std::io::Error> { let mut file_content = String::new(); let...
; Some((self.converter)(content, next)) } } pub(crate) fn iterate_over<T, C>(files: &[PathBuf], converter: C) -> Iter<T, C> where C: Fn(String, &PathBuf) -> Result<T, Error>, { Iter { files, converter, index: 0, } } pub(crate) fn alpabetical(first: &walkdir::DirEntry, s...
match read_file_content(file) { Ok(content) => content, Err(e) => return Some(Err(Error::from(e))), }
if_condition
[ { "content": "#[test]\n\nfn some_filter_tests() -> Result<(), Error> {\n\n let query_str = r#\"some Resources.*.Properties.SecurityGroups[*].'Fn::GetAtt'\"#;\n\n let resources_str = r#\"{\n\n Resources: {\n\n ec2: {\n\n Properties: {\n\n SecurityGroups: ...
Rust
compatibility-test/src/collections.rs
fshaked/rust-verification-tools
87ffcbb33f7358572bf0bdeca35bdc167a5ea26d
#[cfg(not(verify))] use proptest::prelude::*; #[cfg(verify)] use propverify::prelude::*; proptest! { #[test] fn binary_heap(v in prop::collection::binary_heap(0..100u32, 5)) { assert!(v.len() == 5); for x in v.iter() { assert!(*x < 100); } let mut v1 = v;...
#[cfg(not(verify))] use proptest::prelude::*; #[cfg(verify)] use propverify::prelude::*; proptest! { #[test] fn binary_heap(v in prop::collection::binary_heap(0..100u32, 5)) { assert!(v.len() == 5); for x in v.iter() { assert!(*x < 100); } let mut v1 = v;...
, value) in v.iter() { assert!((-5..5i32).contains(key)); assert!((*value) > 5); } } } proptest! { #[test] #[should_panic(expected = "assertion failed")] fn btree_map_fail1(v in prop::collection::btree_map(-5..5i32, 10..20u32, 5)) { for (key, _) in v.iter() { ...
} } proptest! { #[test] fn btree_map(v in prop::collection::btree_map(-5..5i32, 10..20u32, 5)) { assert!(v.len() <= 5); for (key
random
[ { "content": "pub fn btree_map<K: Strategy, V: Strategy>(keys: K, value: V, size: usize) -> BTreeMapStrategy<K, V>\n\nwhere\n\n K::Value: Ord,\n\n{\n\n BTreeMapStrategy { size, keys, value }\n\n}\n\n\n\n#[derive(Clone, Copy, Debug)]\n\npub struct BTreeSetStrategy<S: Strategy> {\n\n element: S,\n\n s...
Rust
api/src/model.rs
Duter2016/tickrs
2b48efa36df02d1c520b58292f2964863a405ea1
use anyhow::{bail, Result}; use serde::{ de::{SeqAccess, Visitor}, Deserialize, Deserializer, }; use std::fmt; use std::marker::PhantomData; pub(crate) enum ResponseType { Chart, Company, Options, } pub(crate) enum Response { Chart(Chart), Company(Company), Options(Options), } impl Re...
use anyhow::{bail, Result}; use serde::{ de::{SeqAccess, Visitor}, Deserialize, Deserializer, }; use std::fmt; use std::marker::PhantomData; pub(crate) enum ResponseType { Chart, Company, Options, } pub(crate) enum Response { Chart(Chart), Company(Company), Options(Options), } impl Re...
} #[serde(rename_all = "camelCase")] #[derive(Debug, Deserialize, Clone)] pub struct Chart { pub chart: ChartStatus, } #[serde(rename_all = "camelCase")] #[derive(Debug, Deserialize, Clone)] pub struct ChartStatus { pub result: Option<Vec<ChartData>>, pub error: Option<Error>, } #[serde(rename_all = "ca...
pub fn deserialize(&self, body: &[u8]) -> Result<Response> { match self { ResponseType::Chart => match serde_json::from_slice(body) { Ok(deser) => Ok(Response::Chart(deser)), Err(e) => bail!(e), }, ResponseType::Company => match serde_json::fro...
function_block-full_function
[ { "content": "#[derive(Clone, Copy, PartialEq)]\n\nenum OptionType {\n\n Call,\n\n Put,\n\n}\n\n\n\n#[derive(Clone, Copy, PartialEq)]\n\npub enum SelectionMode {\n\n Dates,\n\n Options,\n\n}\n\n\n\npub struct OptionsState {\n\n options_service: service::options::OptionsService,\n\n exp_dates: ...
Rust
src/models/type_2.rs
peltzi/rust-netbox
86a0c764999d50fb92adabfcc83fbeb56e2951b9
/* * NetBox API * * API to access NetBox * * The version of the OpenAPI document: 3.0 * * Generated by: https://openapi-generator.tech */ #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub struct Type2 { #[serde(rename = "label")] pub label: Label, #[serde(rename = "value")] pub val...
/* * NetBox API * * API to access NetBox * * The version of the OpenAPI document: 3.0 * * Generated by: https://openapi-generator.tech */ #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub struct Type2 { #[serde(rename = "label")] pub label: Label, #[serde(rename = "value")] pub val...
[serde(rename = "extreme-summitstack-128")] ExtremeSummitstack128, #[serde(rename = "extreme-summitstack-256")] ExtremeSummitstack256, #[serde(rename = "extreme-summitstack-512")] ExtremeSummitstack512, #[serde(rename = "other")] Other, }
rename = "SFP (2GFC)")] SFP2GFC, #[serde(rename = "SFP (4GFC)")] SFP4GFC, #[serde(rename = "SFP+ (8GFC)")] SFP8GFC, #[serde(rename = "SFP+ (16GFC)")] SFP16GFC, #[serde(rename = "SFP28 (32GFC)")] SFP2832GFC, #[serde(rename = "QSFP+ (64GFC)")] QSFP64GFC, #[serde(rename = "Q...
random
[ { "content": "pub fn urlencode<T: AsRef<str>>(s: T) -> String {\n\n ::url::form_urlencoded::byte_serialize(s.as_ref().as_bytes()).collect()\n\n}\n\n\n\npub mod circuits_api;\n\npub mod dcim_api;\n\npub mod extras_api;\n\npub mod ipam_api;\n\npub mod status_api;\n\npub mod tenancy_api;\n\npub mod users_api;\n...
Rust
src/main.rs
Ryan1729/palimpsest-processor
974a6b8f19b85af51f3ac6bc1216a61052f9522e
extern crate libloading; extern crate bear_lib_terminal; extern crate common; use libloading::Library; use bear_lib_terminal::terminal::{self, config, Event, KeyCode, state}; use bear_lib_terminal::Color; use bear_lib_terminal::geometry::{Point, Rect, Size}; use std::mem; use common::*; const LIB_PATH: &'static st...
extern crate libloading; extern crate bear_lib_terminal; extern crate common; use libloading::Library; use bear_lib_terminal::terminal::{self, config, Event, KeyCode, state}; use bear_lib_terminal::Color; use bear_lib_terminal::geometry::{Point, Rect, Size}; use std::mem; use common::*; const LIB_PATH: &'static st...
smute::<common::Color, Color>(bg) }); }
mem::transmute::<Point, common::Point>(state::mouse::position()) } } fn key_pressed(key: common::KeyCode) -> bool { terminal::state::key_pressed(unsafe { mem::transmute::<common::KeyCode, KeyCode>(key) }) } fn set_colors(fg: common::Color, bg: common::Color) { terminal::set_colors(unsafe { mem::transmute::<c...
random
[ { "content": "//returns true if quit requested\n\npub fn update_and_render(platform: &Platform, game: &mut Game, events: &mut Vec<Event>) -> bool {\n\n let mut left_mouse_pressed = false;\n\n let mut left_mouse_released = false;\n\n\n\n for event in events {\n\n\n\n match *event {\n\n ...
Rust
src/prune.rs
collabora/obs-gitlab-runner
952b05c3bd060bb0b7541dc1b57f5525f0b90e5f
use color_eyre::eyre::{ensure, Context, Result}; use gitlab_runner::outputln; use open_build_service_api as obs; use tracing::info; use crate::retry::retry_request; #[tracing::instrument(skip(client))] pub async fn prune_branch( client: &obs::Client, project: &str, package: &str, expected_rev: Option<...
use color_eyre::eyre::{ensure, Context, Result}; use gitlab_runner::outputln; use open_build_service_api as obs; use tracing::info; use crate::retry::retry_request; #[tracing::instrument(skip(client))] pub async fn prune_branch( client: &obs::Client, project: &str, package: &str, expected_rev: Option<...
}
async fn test_prune() { let test_rev = "1"; let mock = create_default_mock().await; mock.add_project(TEST_PROJECT.to_owned()); mock.add_new_package( TEST_PROJECT, TEST_PACKAGE_1.to_owned(), MockPackageOptions::default(), ); let test_k...
function_block-full_function
[ { "content": "pub fn create_default_client(mock: &ObsMock) -> obs::Client {\n\n obs::Client::new(mock.uri(), TEST_USER.to_owned(), TEST_PASS.to_owned())\n\n}\n", "file_path": "src/test_support.rs", "rank": 0, "score": 113646.51032061643 }, { "content": "#[instrument]\n\npub fn generate_mo...
Rust
src/tools/lidar_analysis/lidar_colourize.rs
Afrancioni/whitebox-tools
3208082ed182524e843158c8c4b2e846eb8a2ae8
/* This tool is part of the WhiteboxTools geospatial analysis library. Authors: Dr. John Lindsay Created: February 18, 2018 Last Modified: February 18, 2018 License: MIT */ use time; use num_cpus; use std::env; use std::f64; use std::path; use std::io::{Error, ErrorKind}; use std::sync::Arc; use std::sync::mpsc; use ...
/* This tool is part of the WhiteboxTools geospatial analysis library. Authors: Dr. John Lindsay Created: February 18, 2018 Last Modified: February 18, 2018 License: MIT */ use time; use num_cpus; use std::env; use std::f64; use std::path; use std::io::{Error, ErrorKind}; use std::sync::Arc; use std::sync::mpsc; use ...
}
f !input_image_file.contains(sep) && !input_image_file.contains("/") { input_image_file = format!("{}{}", working_directory, input_image_file); } if !output_file.contains(sep) && !output_file.contains("/") { output_file = format!("{}{}", working_directory, output_file); }...
function_block-function_prefixed
[ { "content": "pub fn read_surfer7(file_name: &String, configs: &mut RasterConfigs, data: &mut Vec<f64>) -> Result<(), Error> {\n\n\n\n // read data file\n\n let mut f = try!(File::open(file_name.clone()));\n\n let metadata = try!(fs::metadata(file_name.clone()));\n\n let file_size: usize = metadata....
Rust
src/main.rs
seguidor777/sokoban-rs
f8a7776eec71bfddaa8e504f90b271f51ae427ca
#[macro_use] extern crate bitflags; #[macro_use] extern crate clap; extern crate sdl2; extern crate xml; use clap::App; use sdl2::event::Event; use sdl2::image::LoadTexture; use sdl2::image::InitFlag; use sdl2::keyboard::Keycode; use sdl2::render::{Canvas, TextureCreator}; use sdl2::video::{Window, WindowContext}; u...
#[macro_use] extern crate bitflags; #[macro_use] extern crate clap; extern crate sdl2; extern crate xml; use clap::App; use sdl2::event::Event; use sdl2::image::LoadTexture; use sdl2::image::InitFlag; use sdl2::keyboard::Keycode; use sdl2::render::{Canvas, TextureCreator}; use sdl2::video::{Window, WindowContext}; u...
fn load_slc_file<P: AsRef<Path>>(path: P) -> Result<Vec<Level>, error::SokobanError> { let mut levels = Vec::new(); let parser = { let file = File::open(path.as_ref())?; EventReader::new(BufReader::new(file)) }; let mut level_title = String::new(); let mut level_data = String::ne...
er = { let big_set = load_tileset( &texture_creator, "assets/image/tileset.png", 101, 171, 83, 40, )?; let small_set = load_tileset( &texture_creator, "assets/image/tileset-small.png", 50,...
function_block-function_prefixed
[ { "content": "/// Returns the shadow flags for a particular position in the given level.\n\nfn get_shadow_flags(level: &Level, pos: &Position) -> ShadowFlags {\n\n let north = pos.neighbor(Direction::Up);\n\n let south = pos.neighbor(Direction::Down);\n\n let west = pos.neighbor(Direction::Left);\n\n ...
Rust
src/ieee_float.rs
uranix/fpcompressor
af024f7d3bf50581243581295ad649fbf4ada3d8
use std::fmt::Debug; #[cfg(test)] use num::traits::FloatConst; #[cfg(test)] use rand::Rng; pub trait IEEEFloat: Sized + Copy + PartialEq + Debug { const EXP_BITS: usize; const MANTISSA_BITS: usize; const SIGN_MASK: u64 = (1u64 << (Self::EXP_BITS + Self::MANTISSA_BITS)); const MANTISSA_MASK: u64 = (1...
use std::fmt::Debug; #[cfg(test)] use num::traits::FloatConst; #[cfg(test)] use rand::Rng; pub trait IEEEFloat: Sized + Copy + PartialEq + Debug { const EXP_BITS: usize; const MANTISSA_BITS: usize; const SIGN_MASK: u64 = (1u64 << (Self::EXP_BITS + Self::MANTISSA_BITS)); const MANTISSA_MASK: u64 = (1...
#[test] fn binary32() { test_binary(0f32, false, 0, 0); test_binary(f32::PI(), false, 128, 0x490fdb); test_binary(-1.0f32/3.0f32, true, 125, 0x2aaaab); test_binary(f32::NEG_INFINITY, true, 255, 0); } #[test] fn binary64() { test_binary(0f64, false, 0, 0); test_binary(f64::PI(), false, 1024, 0...
F, sign: bool, exp: u16, mantissa: u64) { assert_eq!(value.get_sign(), sign); assert_eq!(value.get_exp(), exp); assert_eq!(value.get_mantissa(), mantissa); assert_eq!(F::from_parts(sign, exp, mantissa), value); }
function_block-function_prefixed
[ { "content": "fn read_sign_and_value<R: Read>(stream: &mut BitReader<R, BigEndian>) -> Result<(bool, u16)> {\n\n if stream.read_bit()? {\n\n if stream.read_bit()? {\n\n if stream.read_bit()? {\n\n // 0b11111 prefix - reserved\n\n panic!(\"Unsupported bit sequen...
Rust
src/store/stacktrace.rs
getsentry/general
55df74eb2228f93ab047fa95286c42258c1d17f8
use std::mem; use url::Url; use crate::protocol::{Frame, Stacktrace}; use crate::types::Annotated; fn is_url(filename: &str) -> bool { filename.starts_with("file:") || filename.starts_with("http:") || filename.starts_with("https:") || filename.starts_with("applewebdata:") } pub fn proces...
use std::mem; use url::Url; use crate::protocol::{Frame, Stacktrace}; use crate::types::Annotated; fn is_url(filename: &str) -> bool { filename.starts_with("file:") || filename.starts_with("http:") || filename.starts_with("https:") || filename.starts_with("applewebdata:") } pub fn proces...
} } } pub fn enforce_frame_hard_limit(stacktrace: &mut Annotated<Stacktrace>, limit: usize) { if let Some(ref mut stacktrace) = stacktrace.0 { if let Some(ref mut frames) = stacktrace.frames.0 { if frames.len() >= limit { let last_elem = fr...
if is_url(&abs_path) { if let Ok(url) = Url::parse(&abs_path) { let path = url.path(); if !path.is_empty() && path != "/" { frame.filename = Annotated::new(path.to_string()); } } }
if_condition
[ { "content": "pub fn normalize_request(mut request: Request, client_ip: Option<&str>) -> Request {\n\n request.method = normalize_method(request.method);\n\n\n\n if request.url.is_valid() {\n\n request = normalize_url(request);\n\n }\n\n\n\n if let Some(ref client_ip) = client_ip {\n\n ...
Rust
vxe_renderer_example/src/main.rs
a-ste/vxe
00c4146635d32600f7a56bb2ce3b95f288c3036c
use std::time::Instant; use cgmath::{Deg, Euler, Vector3, Rad}; use obj::{load_obj, Obj}; use obj::Vertex as OBJVertex; use vxe_renderer::context::{Context}; use vxe_renderer::context::utils::{FrameUtils}; use vxe_renderer::data::{Sampler, Vertex}; use vxe_renderer::data::{VertexNormal, VertexPosition, VertexRGB}; us...
use std::time::Instant; use cgmath::{Deg, Euler, Vector3, Rad}; use obj::{load_obj, Obj}; use obj::Vertex as OBJVertex; use vxe_renderer::context::{Context}; use vxe_renderer::context::utils::{FrameUtils}; use vxe_renderer::data::{Sampler, Vertex}; use vxe_renderer::data::{VertexNormal, VertexPosition, VertexRGB}; us...
} fn main() { let mut renderer = RendererBuilder::new() .title("3D example") .resolution([1366, 768]) .vsync(false) .fps_limit(200.0) .build(); let mut lights = vec![]; let mut rang = rand::thread_rng(); for i in 0..350 { let mut light = Light::ne...
2); mesh_trs.scale = Vector3::new(0.4, 0.4, 0.4); let rot = self.start_t.elapsed().as_secs_f32() * 40.0; mesh_trs.rotation = Euler::new(Deg(0.0 + rot), Deg(-90.0 + rot), Deg(0.0 + rot)).into(); mesh.draw(ctx, frame, mesh_trs, persp, view)...
function_block-function_prefixed
[ { "content": "/// Trait for user-defined event handler of renderer's events\n\npub trait Handler {\n\n /// Function that will be called at initialization of Renderer's loop\n\n fn init(&mut self, _ctx: &mut Context) {}\n\n\n\n /// Function that will be called before drawing frame\n\n fn update(&mut ...
Rust
src/index.rs
DCjanus/Lernaean
80c60b95b6288c3b600e3fdfbfa70ac7c5d2a6c2
use crate::{ crates::{CrateIdentity, CrateMetadata}, errors::GenResult, utils::CommandExt, GLOBAL_CONFIG, }; use http::Uri; use std::{path::Path, process::Command, time::Duration}; pub fn query(ident: &CrateIdentity) -> Option<[u8; 32]> { let name = ident.name.to_lowercase(); let raw_path = ma...
use crate::{ crates::{CrateIdentity, CrateMetadata}, errors::GenResult, utils::CommandExt, GLOBAL_CONFIG, }; use http::Uri; use std::{path::Path, process::Command, time::Duration}; pub fn query(ident: &CrateIdentity) -> Option<[u8; 32]> { let name = ident.name.to_lowercase(); let raw_path = ma...
current_dir(index) .arg("push") .arg("--force") .arg("origin") .arg("--quiet") .checked_call()?; Ok(()) }
function_block-function_prefix_line
[ { "content": "pub fn upstream_url(name: &str, version: &str) -> String {\n\n let fmt: &str = &GLOBAL_CONFIG.upstream_dl;\n\n fmt.replace(CRATE_TEMPLATE, name)\n\n .replace(VERSION_TEMPLATE, version)\n\n}\n\n\n\n#[derive(Debug, Clone, Eq, PartialEq, Hash, Deserialize)]\n\npub struct CrateMetadata {\...
Rust
src/vadc_g0/bflc.rs
austinglaser/xmc4700
12e1d2b638af5ff0e7088605a4299590a2cd60eb
#[doc = "Reader of register BFLC"] pub type R = crate::R<u32, super::BFLC>; #[doc = "Writer for register BFLC"] pub type W = crate::W<u32, super::BFLC>; #[doc = "Register BFLC `reset()`'s with value 0"] impl crate::ResetValue for super::BFLC { type Type = u32; #[inline(always)] fn reset_value() -> Self::Typ...
#[doc = "Reader of register BFLC"] pub type R = crate::R<u32, super::BFLC>; #[doc = "Writer for register BFLC"] pub type W = crate::W<u32, super::BFLC>; #[doc = "Register BFLC `reset()`'s with value 0"] impl crate::ResetValue for super::BFLC { type Type = u32; #[inline(always)] fn reset_value() -> Self::Typ...
#[doc = "Checks if the value of the field is `VALUE1`"] #[inline(always)] pub fn is_value1(&self) -> bool { *self == BFM1_A::VALUE1 } #[doc = "Checks if the value of the field is `VALUE2`"] #[inline(always)] pub fn is_value2(&self) -> bool { *self == BFM1_A::VALUE2 } ...
1), 1 => Val(BFM1_A::VALUE2), 2 => Val(BFM1_A::VALUE3), 3 => Val(BFM1_A::VALUE4), i => Res(i), } }
function_block-function_prefixed
[ { "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
src/ast.rs
Vengarioth/xshade
aaf527c72b91620b6fe3375ca6b36b33e9dd66de
use ::std::fmt; use ::std::str; use ::nom_locate::LocatedSpan; use ::type_system::type_environment::TypeReference; pub type Ast = Vec<ItemKind>; type NomSpan<'a> = LocatedSpan<&'a str>; pub trait Spanned { fn get_span(&self) -> Span; } macro_rules! impl_spanned { ($t:ty) => ( impl Sp...
use ::std::fmt; use ::std::str; use ::nom_locate::LocatedSpan; use ::type_system::type_environment::TypeReference; pub type Ast = Vec<ItemKind>; type NomSpan<'a> = LocatedSpan<&'a str>; pub trait Spanned { fn get_span(&self) -> Span; } macro_rules! impl_spanned { ($t:ty) => ( impl Sp...
impl_spanned!(ConstantDefinition); #[derive(Debug, Eq, PartialEq)] pub struct ProgramDefinition { pub span: Span, pub program_name: Identifier, pub program_stages: Vec<ProgramStageDefinition>, } impl_spanned!(ProgramDefinition); #[derive(Debug, Eq, PartialEq)] pub struct ProgramStageDefin...
e as usize, column: span.get_column(), } } pub fn from_to(from: Span, to: Span) -> Span { Span { offset: from.offset, length: to.offset - from.offset + to.length, line: from.line, column: from.column, } } } ...
random
[ { "content": "pub fn compile_ast(code_to_compile: &str) -> Ast {\n\n ::parser::parse_str(code_to_compile).unwrap()\n\n}\n", "file_path": "src/testing/mod.rs", "rank": 2, "score": 143384.54764434928 }, { "content": "fn get_span_line(lines: &Vec<&str>, span: Span) -> String {\n\n lines[s...
Rust
src/data_structures/union_find.rs
illumination-k/competitive-lib-rust
567729110b908f0bfc23f1261413affcca43327c
use num_traits::PrimInt; #[derive(Debug, Clone)] pub struct UnionFind<K> { parent: Vec<K>, size: Vec<usize>, group_num: usize, } #[inline] unsafe fn get_unchecked<K>(xs: &[K], index: usize) -> &K { debug_assert!(index < xs.len()); xs.get_unchecked(index) } #[inline] uns...
use num_traits::PrimInt; #[derive(Debug, Clone)] pub struct UnionFind<K> { parent: Vec<K>, size: Vec<usize>, group_num: usize, } #[inline] unsafe fn get_unchecked<K>(xs: &[K], index: usize) -> &K { debug_assert!(index < xs.len()); xs.get_unchecked(index) } #[inline] uns...
self.group_num -= 1; true } pub fn into_labeling(mut self) -> Vec<K> { unsafe { for ix in 0..self.parent.len() { let k = *get_unchecked(&self.parent, ix); let xrep = self.find_mut_recursive(k); *self.parent.get_u...
if xsize > ysize { self.parent[yrepu] = xrep; self.size[xrepu] += ysize; } else { self.parent[xrepu] = yrep; self.size[yrepu] += xsize; }
if_condition
[]
Rust
youmubot-osu/src/discord/announcer.rs
huynd2001/youmubot
85dcf0ffc0f969ca6d5ad37c2d81da1a34b0e8e6
use super::db::{OsuSavedUsers, OsuUser}; use super::{embeds::score_embed, BeatmapWithMode}; use crate::{ discord::beatmap_cache::BeatmapMetaCache, discord::cache::save_beatmap, discord::oppai_cache::{BeatmapCache, BeatmapContent}, models::{Mode, Score, User, UserEventRank}, request::UserID, Clie...
use super::db::{OsuSavedUsers, OsuUser}; use super::{embeds::score_embed, BeatmapWithMode}; use crate::{ discord::beatmap_cache::BeatmapMetaCache, discord::cache::save_beatmap, discord::oppai_cache::{BeatmapCache, BeatmapContent}, models::{Mode, Score, User, UserEventRank}, request::UserID, Clie...
async fn get_beatmap( &self, ctx: &Context, ) -> Result<( BeatmapWithMode, impl std::ops::Deref<Target = BeatmapContent>, )> { let data = ctx.data.read().await; let cache = data.get::<BeatmapMetaCache>().unwrap(); let oppai = data.get::<BeatmapCache>...
nto_iter() .map(|c| self.send_message_to(*c, ctx, &bm, &content)) .collect::<stream::FuturesUnordered<_>>() .try_collect() .await }
function_block-function_prefixed
[ { "content": "// Get a name from the user's id.\n\npub fn name_from_userid(u: UserId) -> (&'static str, &'static str) {\n\n let u = u.get() as usize % ALL_NAMES;\n\n (\n\n FIRST_NAMES[u / LAST_NAMES.len()], // Not your standard mod\n\n LAST_NAMES[u % LAST_NAMES.len()],\n\n )\n\n}\n\n\n\nc...
Rust
src/scry.rs
dragon0/aproxymate
91b1968ec21416304833c32d90b1eb57abe3a107
extern crate error_chain; extern crate serde_derive; extern crate serde_json; extern crate reqwest; use super::card; error_chain! { foreign_links { Reqwest(reqwest::Error); } } pub struct QueryResults { pub cards: Vec<card::Card>, pub not_found: Vec<String>, } #[derive(Deserialize, Debug, Cl...
extern crate error_chain; extern crate serde_derive; extern crate serde_json; extern crate reqwest; use super::card; error_chain! { foreign_links { Reqwest(reqwest::Error); } } pub struct QueryResults { pub cards: Vec<card::Card>, pub not_found: Vec<String>, } #[derive(Deserialize, Debug, Cl...
fn dto_to_cards(cardlist: CardList) -> QueryResults { let not_found = cardlist.not_found.into_iter().map(|ident|{ ident.name }).collect(); let cards = cardlist.data.into_iter().map(|card|{ let colors = card.colors.clone(); let image_uris = card.image_uris.clone(); let inf...
let client = reqwest::Client::new(); let mut response = client.post(&request_url) .header(reqwest::header::CONTENT_TYPE, "application/json") .body(serialized) .send()?; let text = response.text()?; let cardlist: CardList = serde_json::from_str(&text).unwrap(); let result = dto_...
function_block-function_prefix_line
[ { "content": "pub fn print_card(card: &Card) {\n\n println!(\"id\\t{}\", card.id);\n\n println!(\"name\\t{}\", card.name);\n\n println!(\"layout\\t{}\", card.layout);\n\n println!(\"rarity\\t{}\", card.rarity);\n\n println!(\"cmc\\t{}\", card.cmc);\n\n println!(\"typestr\\t{}\", card.type_line...
Rust
kernel/src/mem.rs
skyzh/core-os-riscv
6471afb60dd7be678b6a2fde56f935b536746b4d
use core::ops::Range; use crate::info; use crate::{println, panic}; use crate::symbols::*; use crate::spinlock::Mutex; use crate::page::EntryAttributes; use crate::page::{Table, KERNEL_PGTABLE}; use crate::uart::UART_BASE_ADDR; use crate::process::*; use riscv::{register::*, asm}; use crate::mem; use crate::arch; pu...
use core::ops::Range; use crate::info; use crate::{println, panic}; use crate::symbols::*; use crate::spinlock::Mutex; use crate::page::EntryAttributes; use crate::page::{Table, KERNEL_PGTABLE}; use crate::uart::UART_BASE_ADDR; use crate::process::*; use riscv::{register::*, asm}; use crate::mem; use crate::arch; pu...
#[allow(non_snake_case)] pub fn ALLOC() -> &'static Mutex<Allocator> { &__ALLOC } use core::alloc::{GlobalAlloc, Layout}; use crate::plic::PLIC_BASE; use crate::clint::CLINT_BASE; use crate::arch::hart_id; use crate::process::my_cpu; use crate::virtio::VIRTIO_MMIO_BASE; struct OsAllocator {} unsafe impl GlobalAllo...
pub fn hartinit() { let root_ppn = &KERNEL_PGTABLE as *const Table as usize; let satp_val = arch::build_satp(8, 0, root_ppn); unsafe { llvm_asm!("csrw satp, $0" :: "r"(satp_val)); asm::sfence_vma(0, 0); } }
function_block-full_function
[ { "content": "pub fn parse_elf(a: &[u8], pgtable: &mut page::Table) -> u64 {\n\n let a = a.as_ptr();\n\n /* TODO: Use something safer */\n\n // peek head of byte array to get ELF information\n\n let elfhdr = unsafe { &*(a as *const ELFHeader) };\n\n if elfhdr.magic != ELF_MAGIC {\n\n panic...
Rust
src/day18.rs
ghassanachi/aoc-2021
2bdf764097702cb18316ce4028179625c4a3e51c
use aoc_runner_derive::{aoc, aoc_generator}; use std::cell::RefCell; use std::rc::{Rc, Weak}; #[derive(Debug)] pub struct NodeContent { parent: Weak<RefCell<Self>>, left: Option<SnailNumber>, right: Option<SnailNumber>, data: Option<u64>, } impl NodeContent { fn new(data: Option<u64>) -> Self { ...
use aoc_runner_derive::{aoc, aoc_generator}; use std::cell::RefCell; use std::rc::{Rc, Weak}; #[derive(Debug)] pub struct NodeContent { parent: Weak<RefCell<Self>>, left: Option<SnailNumber>, right: Option<SnailNumber>, data: Option<u64>, } impl NodeContent { fn new(data: Option<u64>) -> Self { ...
is_some()); let val = node.borrow().data.unwrap(); if val <= 9 { continue; } node.borrow_mut().data = None; node.insert_left(Some(val / 2)); node.insert_right(Some((val / 2) + (val % 2))); return true; } ...
return true; } for (node, _) in &mut nodes { let mut node = node.upgrade().unwrap(); assert!(node.borrow().data.
random
[ { "content": "#[aoc_generator(day21)]\n\npub fn input_generator(input: &str) -> (u64, u64) {\n\n let mut iter = input.lines();\n\n let mut next_digit = || {\n\n iter.next()\n\n .unwrap()\n\n .chars()\n\n .last()\n\n .unwrap()\n\n .to_digit(10)\...
Rust
src/lib.rs
jcreekmore/convey
e20994701307aea1a9eb0dfa5944327b0845015d
#![warn(missing_docs)] use failure; pub fn new() -> Output { Output::default() } #[derive(Default, Clone)] pub struct Output { inner: Arc<Mutex<InnerOutput>>, } #[derive(Default, Clone)] struct InnerOutput { targets: Vec<Target>, #[cfg(feature = "log")] log_level: Option<log::Level>, } impl O...
#![warn(missing_docs)] use failure; pub fn new() -> Output { Output::default() } #[derive(Default, Clone)] pub struct Output { inner: Arc<Mutex<InnerOutput>>, } #[derive(Default, Clone)] struct InnerOutput { targets: Vec<Target>, #[cfg(feature = "log")] log_level: Option<log::Level>, } impl O...
} Ok(()) } pub fn flush(&self) -> Result<(), Error> { let o = self.inner.lock().map_err(|e| Error::sync_error(&e))?; for target in &o.targets { match &target.inner { InnerTarget::Human(fmt) => { let fmt = fmt.lock().map_err(...
match &target.inner { InnerTarget::Human(fmt) => { let mut fmt = fmt.lock().map_err(|e| Error::sync_error(&e))?; item.render_for_humans(&mut *fmt)?; fmt.write("\n")?; } InnerTarget::Json(fmt) => { ...
if_condition
[ { "content": "/// Construct a new human output target that writes to stdout\n\npub fn stdout() -> Result<Target, Error> {\n\n let formatter = Formatter::init_with(|| Ok(StandardStream::stdout(ColorChoice::Auto)))?;\n\n Ok(Target::human(formatter))\n\n}\n\n\n\npub use self::test_helper::{test, test_with_co...
Rust
src/imp/libc/time/types.rs
sunfishcode/rustix-testing
241e16870959d79ced8c8b715c3d264dd837e7dc
use super::super::c; #[cfg(not(target_os = "wasi"))] use crate::fd::BorrowedFd; #[cfg(any(target_os = "android", target_os = "fuchsia", target_os = "linux"))] use bitflags::bitflags; #[cfg(not(all( any(target_arch = "arm", target_arch = "mips", target_arch = "x86"), target_env = "gnu" )))] pub type Timespec = ...
use super::super::c; #[cfg(not(target_os = "wasi"))] use crate::fd::BorrowedFd; #[cfg(any(target_os = "android", target_os = "fuchsia", target_os = "linux"))] use bitflags::bitflags; #[cfg(not(all( any(target_arch = "arm", target_arch = "mips", target_arch = "x86"), target_env = "gnu" )))] pub type Timespec = ...
nst NONBLOCK = c::TFD_NONBLOCK; const CLOEXEC = c::TFD_CLOEXEC; } } #[cfg(any(target_os = "android", target_os = "fuchsia", target_os = "linux"))] bitflags! { pub struct TimerfdTimerFlags: c::c_int { const ABSTIME = c::TFD_TIMER_ABSTIME; #[cfg(any(targe...
arget_os = "linux"))] #[cfg(not(all( any(target_arch = "arm", target_arch = "mips", target_arch = "x86"), target_env = "gnu" )))] pub type Itimerspec = c::itimerspec; #[cfg(any(target_os = "android", target_os = "fuchsia", target_os = "linux"))] #[cfg(all( any(target_arch = "arm", target_arch = "mips", tar...
random
[ { "content": "#[inline]\n\npub fn clock_nanosleep_absolute(id: ClockId, request: &Timespec) -> io::Result<()> {\n\n imp::thread::syscalls::clock_nanosleep_absolute(id, request)\n\n}\n\n\n\n/// `nanosleep(request, remain)`—Sleeps for a duration.\n\n///\n\n/// This effectively uses the system monotonic clock.\...
Rust
src/main.rs
udoprog/sysmon-rs
917a88ef0e7d5b560a48212381a7bb29804f2d53
#![feature(proc_macro)] extern crate sysmon; extern crate toml; extern crate getopts; extern crate futures; extern crate futures_cpupool; extern crate tokio_core; extern crate tokio_signal; #[macro_use] extern crate log; #[cfg(features = "watch")] extern crate notify; extern crate serde; extern crate env_logger; use ...
#![feature(proc_macro)] extern crate sysmon; extern crate toml; extern crate getopts; extern crate futures; extern crate futures_cpupool; extern crate tokio_core; extern crate tokio_signal; #[macro_use] extern crate log; #[cfg(features = "watch")] extern crate notify; extern crate serde; extern crate env_logger; use ...
fn main() { match run() { Err(e) => { error!("{}", e); for e in e.iter().skip(1) { error!(" caused by: {}", e); } if let Some(backtrace) = e.backtrace() { error!(" backtrace: {:?}", backtrace); } :...
k(()); } setup_logger(&matches)?; let (config, setups) = load_configs(matches.opt_strs("config"))?; let cpupool = Arc::new(CpuPool::new(config.threads())); let core = Rc::new(RefCell::new(Core::new()?)); let (input, output) = { let partial_context = PartialPluginContext::new(cpupool....
function_block-function_prefixed
[ { "content": "pub fn load_config(config: &mut Config, path: &String) -> Result<Box<PluginSetup>> {\n\n let mut file = fs::File::open(path)?;\n\n\n\n let mut content = String::new();\n\n file.read_to_string(&mut content)?;\n\n\n\n let mut parser = toml::Parser::new(&mut content);\n\n\n\n let root ...
Rust
src/rust/vendor/poly1305/src/fuzz.rs
thisconnect/bitbox02-firmware
e081ac18dc28c2bdffdc58a94afa36a1bb5bade2
use universal_hash::generic_array::GenericArray; use crate::{backend, Block, Key, BLOCK_SIZE}; pub fn fuzz_avx2(key: &Key, data: &[u8]) { let mut avx2 = backend::avx2::State::new(key); let mut soft = backend::soft::State::new(key); for (_i, chunk) in data.chunks(BLOCK_SIZE).enumerate() { if chunk...
use universal_hash::generic_array::GenericArray; use crate::{backend, Block, Key, BLOCK_SIZE}; pub fn fuzz_avx2(key: &Key, data: &[u8]) { let mut avx2 = backend::avx2::State::new(key); let mut soft = backend::soft::State::new(key); for (_i, chunk) in data.chunks(BLOCK_SIZE).enumerate() { if chunk...
#[test] fn crash_4() { avx2_fuzzer_test_case(include_bytes!( "fuzz/id=000004,sig=06,src=000022+000005,op=splice,rep=32" )); } #[test] fn crash_5() { avx2_fuzzer_test_case(include_bytes!( "fuzz/id=000005,sig=06,src=000008+000007,op=splice,rep=128" )); } #[test] fn crash_6() { ...
fn crash_3() { avx2_fuzzer_test_case(include_bytes!( "fuzz/id=000003,sig=06,src=000003,op=havoc,rep=64" )); }
function_block-full_function
[ { "content": "/// Provide mock implementations and data. This also locks the keystore - use `mock_unlocked()` to mock a seeded and unlocked keystore.\n\npub fn mock(data: Data) {\n\n *DATA.0.borrow_mut() = data;\n\n keystore::lock();\n\n}\n\n\n", "file_path": "src/rust/bitbox02/src/testing.rs", "r...
Rust
src/memory/view.rs
Hywan/ruby-ext-wasm
35968aa3a330f60001bc665fed77c53ba1a766c4
#[rustfmt::skip] macro_rules! memory_view { ($mod_name:ident over $wasm_type:ty | $bytes_per_element:expr) => { pub mod $mod_name { use crate::error::unwrap_or_raise; use lazy_static::lazy_static; use rutie::{ class, methods, wrappable_struct, AnyExcept...
#[rustfmt::skip] macro_rules! memory_view { ($mod_name:ident over $wasm_type:ty | $bytes_per_element:expr) => { pub mod $mod_name { use crate::error::unwrap_or_raise; use lazy_static::lazy_static; use rutie::{ class, methods, wrappable_struct, AnyExcept...
let memory_view = _itself.get_data(&*MEMORY_VIEW_WRAPPER); Ok(Fixnum::new( memory_view .get(index?.to_i32() as isize) .map_err(|e| AnyException::new("ArgumentError", Some(&e)))? ...
new(memory: Rc<runtime::Memory>, offset: usize) -> Self { Self { memory, offset } } pub fn len(&self) -> usize { self.memory.view::<$wasm_type>()[self.offset..].len() / size_of::<$wasm_type>() } pub fn set(&self, i...
random
[ { "content": "class MemoryTest < Minitest::Test\n", "file_path": "tests/memory_test.rb", "rank": 0, "score": 58255.31232848789 }, { "content": "pub fn unwrap_or_raise<Output, Function>(f: Function) -> Output\n\nwhere\n\n Function: FnOnce() -> Result<Output, AnyException>,\n\n{\n\n matc...
Rust
rs/stable-structures/src/btreemap/iter.rs
Deland-Labs/ic
047172b01e0afc0e61448669d4ec98b2425c6853
use super::{ node::{Key, Node, NodeType, Value}, StableBTreeMap, }; use crate::{types::NULL, Address, Memory}; pub(crate) enum Cursor { Address(Address), Node { node: Node, next: Index }, } pub(crate) enum Index { Child(usize), Entry(usize), } #[must_use = "iterators are lazy and do nothing u...
use super::{ node::{Key, Node, NodeType, Value}, StableBTreeMap, }; use crate::{types::NULL, Address, Memory}; pub(crate) enum Cursor { Address(Address), Node { node: Node, next: Index }, } pub(crate) enum Index { Child(usize), Entry(usize), } #[must_use = "iterators are lazy and do nothing u...
}
memory(); let mut btree = StableBTreeMap::new(mem, 1, 1); for i in (0..100).rev() { btree.insert(vec![i], vec![i + 1]).unwrap(); } let mut i = 0; for (key, value) in btree.iter() { assert_eq!(key, vec![i]); assert_eq!(value,...
function_block-function_prefixed
[ { "content": "/// This is a minimal implementation of DER-encoding for Ed25519, as the keys\n\n/// are constant-length. The format is an ASN.1 SubjectPublicKeyInfo, whose\n\n/// header contains the OID for Ed25519, as specified in RFC 8410:\n\n/// https://tools.ietf.org/html/rfc8410\n\npub fn ed25519_public_key...
Rust
cli/src/compare.rs
hexgnu/tract
44851c7d6bff69a0ddb1e36d501f4964d89bcaea
#![allow(dead_code)] use std::fmt::{Debug, Display}; #[allow(unused_imports)] use std::fs; use ansi_term::Color::*; use log::Level::Info; use tract_core::internal::*; use crate::display_params::DisplayParams; use crate::*; pub fn handle( params: &mut Parameters, options: &clap::ArgMatches, output_params...
#![allow(dead_code)] use std::fmt::{Debug, Display}; #[allow(unused_imports)] use std::fs; use ansi_term::Color::*; use log::Level::Info; use tract_core::internal::*; use crate::display_params::DisplayParams; use crate::*; pub fn handle( params: &mut Parameters, options: &clap::ArgMatches, output_params...
.to_string()]; msg.push(format!("got : {:?}", obtained[ix])); msg.push(format!("ref : {:?}", reference[ix])); tags.sections.push(msg); ...
tags.style = Some(Blue.into()); } else if node.op().validation() == Validation::Random { tags.style = Some(Blue.into()); tags.labels.push(Blue.paint("Random").to_string()); } else if node.op_is::<tract_core::ops::unimpl::UnimplementedOp>(...
random
[ { "content": "pub fn for_npz(npz: &mut ndarray_npy::NpzReader<fs::File>, name: &str) -> CliResult<Tensor> {\n\n fn rewrap<T: Datum>(array: tract_ndarray::ArrayD<T>) -> Tensor {\n\n let shape = array.shape().to_vec();\n\n unsafe {\n\n let vec = array.into_raw_vec();\n\n tra...
Rust
src/types.rs
ttaubert/ascii-tls
b8ad8415a729a4507037a71d8871f1648eb72916
use byteorder::{BigEndian, WriteBytesExt}; pub struct Record { name: String, value: Vec<u8> } impl<'a> Record { pub fn new(name: String, value: Vec<u8>) -> Record { Record { name: name, value: value } } pub fn name(&'a self) -> &'a str { &self.name[..] } pub fn value(&'a self) ...
use byteorder::{BigEndian, WriteBytesExt}; pub struct Record { name: String, value: Vec<u8> } impl<'a> Record { pub fn new(name: String, value: Vec<u8>) -> Record { Record { name: name, value: value } } pub fn name(&'a self) -> &'a str { &self.name[..] } pub fn value(&'a self) ...
fn to_opaque_bytes(self, width: usize) -> Option<Vec<u8>> { assert!(width <= 8); let mut v : Vec<u8> = match self.value { Value::Block(ref v) | Value::Hex(ref v) | Value::String(ref v) => { if width > 0 { if v.len() >= 2usize.pow(width as u32 * 8) { retur...
fn to_uint_bytes(self, width: usize) -> Option<Vec<u8>> { assert!(width <= 8); let v = match self.value { Value::Block(ref v) | Value::Hex(ref v) | Value::String(ref v) => { if v.len() > width { return None; } let mut padded = vec!(0; width - v.len(...
function_block-full_function
[ { "content": " }\n\n }\n\n\n\n Some(Value::Block(bytes))\n\n })\n\n);\n\n\n\n#[cfg(test)]\n\nmod tests {\n\n use super::{block, field, hex, opaque, string, uintx};\n\n use super::{Field, Type, Value};\n\n use nom::IResult::*;\n\n use nom;\n\n\n\n /*fn parse_record(input: &str, name: &str, value...
Rust
src/elastic/src/client/requests/index_create.rs
tobias-o/elastic
901f7311f46bb4f9e5e0a12eb59706255b8c5d63
/*! Builders for [create index requests][docs-create-index]. [docs-create-index]: https://www.elastic.co/guide/en/elasticsearch/reference/master/indices-create-index.html */ use futures::{ Future, Poll, }; use crate::{ client::{ requests::{ raw::RawRequestInner, RequestBui...
/*! Builders for [create index requests][docs-create-index]. [docs-create-index]: https://www.elastic.co/guide/en/elasticsearch/reference/master/indices-create-index.html */ use futures::{ Future, Poll, }; use crate::{ client::{ requests::{ raw::RawRequestInner, RequestBui...
}
fn specify_body() { let client = SyncClientBuilder::new().build().unwrap(); let req = client .index("testindex") .create() .body("{}") .inner .into_request(); assert_eq!("{}", req.body); }
function_block-full_function
[ { "content": "pub fn call(run: &str) -> Result<AsyncClient, Error> {\n\n match run {\n\n // Get a client that sniffs nodes super frequently\n\n \"sniffed_node\" => AsyncClientBuilder::new()\n\n .sniff_nodes_fluent(\"http://localhost:9200\", |n| n.wait(Duration::from_secs(1)))\n\n ...
Rust
simulator/src/configurations/map.rs
gabrielbeauchemin/simumo
e0339c7b4e025a90860dacc7f7ed870a5d58570f
/*! Represent the map on different type. */ use std::collections::HashMap; use std::fs::File; use std::io::BufReader; use std::path::Path; use crate::commons::CartesianCoord; use crate::commons::Curve; use crate::commons::Point2D; use crate::commons::PolarCoord; use crate::osmgraph_api::OsmGraphApi; use crate::osmgra...
/*! Represent the map on different type. */ use std::collections::HashMap; use std::fs::File; use std::io::BufReader; use std::path::Path; use crate::commons::CartesianCoord; use crate::commons::Curve; use crate::commons::Point2D; use crate::commons::PolarCoord; use crate::osmgraph_api::OsmGraphApi; use crate::osmgra...
fn compute_bounding_box(lanegraph: &LaneGraph) -> MapBbox { let positions: Vec<(f64, f64)> = lanegraph .intersections .values() .map(|v| v.position()) .collect(); use std::f64::NAN; MapBbox { x1: positions.iter().map(|v| v.0).fold(NAN, f64::min), x2: positi...
fn lanegraph_from_filemap(path: String, pt_conversion: &Fn((f64, f64)) -> (f64, f64)) -> LaneGraph { let path = Path::new(&path); let file = File::open(path).unwrap(); let reader = BufReader::new(file); let map: FileMap = serde_json::from_reader(reader).unwrap(); let nodes: HashMap<_, _> = map ...
function_block-full_function
[ { "content": "type NodeId = u64;\n\n\n", "file_path": "simulator/src/osmgraph_api.rs", "rank": 3, "score": 216551.90860276186 }, { "content": "/// for convenience\n\nfn polarfloat_to_cartesian(lat: f64, lon: f64) -> CartesianCoord {\n\n let polar = PolarCoord::from_float(lat, lon);\n\n ...
Rust
vault/src/issue.rs
interlay/polkabtc-clients
364a41bfa660c72bb23a0ba3364bb7d0936b7eeb
use crate::{Error, Event, IssueRequests}; use bitcoin::{BitcoinCoreApi, BlockHash, Transaction, TransactionExt}; use futures::{channel::mpsc::Sender, future, SinkExt, StreamExt}; use runtime::{ pallets::issue::{CancelIssueEvent, ExecuteIssueEvent, RequestIssueEvent}, BtcAddress, BtcPublicKey, BtcRelayPallet, H2...
use crate::{Error, Event, IssueRequests}; use bitcoin::{BitcoinCoreApi, BlockHash, Transaction, TransactionExt}; use futures::{channel::mpsc::Sender, future, SinkExt, StreamExt}; use runtime::{ pallets::issue::{CancelIssueEvent, ExecuteIssueEvent, RequestIssueEvent}, BtcAddress, BtcPublicKey, BtcRelayPallet, H2...
async fn process_transaction_and_execute_issue<B: BitcoinCoreApi + Clone + Send + Sync + 'static>( bitcoin_core: &B, btc_parachain: &InterBtcParachain, issue_set: &Arc<IssueRequests>, num_confirmations: u32, block_hash: BlockHash, transaction: Transaction, ) -> Result<(), Error> { let addr...
for (issue_id, request) in issue_requests.into_iter() { if let Err(e) = add_new_deposit_key(bitcoin_core, issue_id, request.btc_public_key).await { tracing::error!("Failed to add deposit key #{}: {}", issue_id, e.to_string()); } } tracing::info!("Rescanning bitcoin chain from height...
function_block-function_prefix_line
[ { "content": "pub fn parachain_blocks_to_bitcoin_blocks_rounded_up(parachain_blocks: u32) -> Result<u32, Error> {\n\n let millis = (parachain_blocks as u64)\n\n .checked_mul(runtime::MILLISECS_PER_BLOCK)\n\n .ok_or(Error::ArithmeticOverflow)?;\n\n\n\n let denominator = BITCOIN_BLOCK_INTERVAL...
Rust
panbuild/manifests/javascript.rs
louib/panbuild
2cb07ebd6c21d7f4f0fb588cb8ed4570f20d1344
use std::collections::BTreeMap; use serde::{Deserialize, Serialize}; #[derive(Debug, Default, Deserialize, Serialize)] #[serde(rename_all = "camelCase")] #[serde(default)] pub struct JavascriptPackageManifest { pub name: String, pub version: String, pub description: String, pub repository: Stri...
use std::collections::BTreeMap; use serde::{Deserialize, Serialize}; #[derive(Debug, Default, Deserialize, Serialize)] #[serde(rename_all = "camelCase")] #[serde(default)] pub struct JavascriptPackageManifest { pub name: String, pub version: String, pub description: String, pub repository: Stri...
pub fn parse(manifest_content: &String) -> Option<JavascriptPackageManifest> { let js_package_manifest: JavascriptPackageManifest = match serde_json::from_str(&manifest_content) { Ok(m) => m, Err(e) => { log::debug!("Failed to parse the Javascript package manifest: ...
pub fn file_path_matches(path: &str) -> bool { if path.to_lowercase().ends_with("package.json") { return true; } false }
function_block-function_prefix_line
[ { "content": "pub fn normalize_name(name: &String) -> String {\n\n let mut response: String = \"\".to_string();\n\n for c in name.chars() {\n\n if c.is_alphabetic() || c.is_numeric() {\n\n response.push_str(&c.to_string());\n\n continue;\n\n }\n\n // We don't wan...
Rust
src/codec.rs
nearmax/tokio-jsonrpc
de9054fb369d1bbc7cc184c77e9f61397fb44073
use std::io::{Error, ErrorKind, Result as IoResult}; use tokio_io::codec::{Decoder, Encoder}; use bytes::{BufMut, BytesMut}; use serde_json::de::Deserializer; use serde_json::ser::to_vec; use serde_json::error::Error as SerdeError; use message::{decoded_to_parsed, from_slice, from_str, Message, Parsed}; fn err_map...
use std::io::{Error, ErrorKind, Result as IoResult}; use tokio_io::codec::{Decoder, Encoder}; use bytes::{BufMut, BytesMut}; use serde_json::de::Deserializer; use serde_json::ser::to_vec; use serde_json::error::Error as SerdeError; use message::{decoded_to_parsed, from_slice, from_str, Message, Parsed}; fn err_map...
#[test] fn decode_nonunicode() { let broken_input = b"{\"jsonrpc\":\"2.0\",\"method\":\"Hello \xF0\x90\x80World\"}\n"; let mut codec = Line::new(); let mut buf = get_buf(broken_input); let result = codec.decode(&mut buf).unwrap(); match result { ...
fn decode() { fn one(input: &[u8], rest: &[u8]) -> IoResult<Option<Parsed>> { let mut codec = Line::new(); let mut buf = get_buf(input); let result = codec.decode(&mut buf); assert_eq!(rest, &buf); let mut dirty_codec = DirtyLine::new(); ...
function_block-full_function
[]
Rust
server/src/main.rs
mtcairneyleeming/fractals
688b6621aec7896fecd017c6575b9f9deb6f5a4e
#![feature(proc_macro_hygiene, decl_macro)] extern crate log; extern crate simplelog; use simplelog::*; mod geom; mod simple; #[macro_use] extern crate rocket; extern crate rocket_contrib; use geom::{Layer, Line3d, Point3d, Tri3d}; use log::info; use rocket_contrib::msgpack::MsgPack; use rocket_contrib::serve::StaticFi...
#![feature(proc_macro_hygiene, decl_macro)] extern crate log; extern crate simplelog; use simplelog::*; mod geom; mod simple; #[macro_use] extern crate rocket; extern crate rocket_contrib; use geom::{Layer, Line3d, Point3d, Tri3d}; use log::info; use rocket_contrib::msgpack::MsgPack; use rocket_contrib::serve::StaticFi...
rap()) }; simple::develop( layers, data.holes, init_steps, step_scale, if extrude { extrude_dist.unwrap() } else { 0.0 }, ) }; info!( "Calculated {} in {:.2}s", if thicken { "thick" } else { "thin" }, sta...
use serde::{Deserialize, Serialize}; use simple::*; use std::time::Instant; use stl_io::*; fn tris_to_binary_stl(tris: Vec<Tri3d>) -> Vec<u8> { let mesh: Vec<Triangle> = tris .into_iter() .map(|t| stl_io::Triangle { normal: [t.n.x as f32, t.n.y as f32, t.n.z as f32], vertic...
random
[ { "content": "// points in the direction of the smaller angle between a,b\n\nfn angle_bisector(a: Line3d, b: Line3d) -> Point3d {\n\n // 2d versions of these two lines\n\n // direction vectors of each\n\n let va = a.start().sub(a.end());\n\n let vb = b.end().sub(b.start());\n\n // normed directio...
Rust
src/lexer/token_stream.rs
jsinger67/parol_runtime
496caa8dfb377647735c4ea9d213ff277cab65d5
use crate::errors::LookaheadError; use crate::lexer::Token; use crate::lexer::{TerminalIndex, TokenIter, Tokenizer, EOI}; use crate::parser::ScannerIndex; use log::trace; use miette::{miette, Result}; use std::path::{Path, PathBuf}; pub struct TokenStream<'t> { pub k: usize, pub(crate) input: &'t st...
use crate::errors::LookaheadError; use crate::lexer::Token; use crate::lexer::{TerminalIndex, TokenIter, Tokenizer, EOI}; use crate::parser::ScannerIndex; use log::trace; use miette::{miette, Result}; use std::path::{Path, PathBuf}; pub struct TokenStream<'t> { pub k: usize, pub(crate) input: &'t st...
pub fn consume(&mut self) -> Result<()> { self.ensure_buffer(); if self.tokens.is_empty() { Err(miette!("Consume on empty buffer is impossible")) } else { let la1 = &self.tokens[0]; let (new_lines, ...
pub fn lookahead_token_type(&mut self, n: usize) -> Result<TerminalIndex> { if n > self.k { Err(miette!("Lookahead exceeds its maximum")) } else { self.ensure_buffer(); if n >= self.tokens.len() { Err(miette!("Lookahead exceeds token buffe...
function_block-full_function
[ { "content": "///\n\n/// Common formatting for Token and OwnedToken\n\n///\n\npub trait FormatToken {\n\n ///\n\n /// Generates a formatted position which an editor can follow via mouse click.\n\n ///\n\n fn format<T>(&self, file_name: &T, terminal_names: &'static [&'static str]) -> String\n\n wh...
Rust
p2p/src/codec.rs
cosmicrocks/grin
e853246b939b197ebc10df31e4da40fbaf8db61c
use crate::core::core::block::{BlockHeader, UntrustedBlockHeader}; use crate::core::global::header_size_bytes; use crate::core::ser::{BufReader, ProtocolVersion, Readable}; use crate::msg::{Message, MsgHeader, MsgHeaderWrapper, Type}; use crate::types::{AttachmentMeta, AttachmentUpdate, Error}; use bytes::{Buf, BufMut,...
use crate::core::core::block::{BlockHeader, UntrustedBlockHeader}; use crate::core::global::header_size_bytes; use crate::core::ser::{BufReader, ProtocolVersion, Readable}; use crate::msg::{Message, MsgHeader, MsgHeaderWrapper, Type}; use crate::types::{AttachmentMeta, AttachmentUpdate, Error}; use bytes::{Buf, BufMut,...
Type::Ping => Message::Ping(msg.body()?), Type::Pong => Message::Pong(msg.body()?), Type::BanReason => Message::BanReason(msg.body()?), Type::TransactionKernel => Message::TransactionKernel(msg.body()?), Type::GetTransaction => Message::GetTransaction(msg.body()?), Type::Transaction => Message::Transaction(ms...
function_block-function_prefix_line
[ { "content": "/// Read (an unknown) message from the provided stream and discard it.\n\npub fn read_discard<R: Read>(msg_len: u64, stream: &mut R) -> Result<(), Error> {\n\n\tlet mut buffer = vec![0u8; msg_len as usize];\n\n\tstream.read_exact(&mut buffer)?;\n\n\tOk(())\n\n}\n\n\n", "file_path": "p2p/src/ms...
Rust
src/main.rs
ko1N/csgo-internal-dumper
10f664302a1f57e1871e94d3bdfe102f0eff5239
mod error; mod engine; use engine::*; mod mapper; use mapper::*; use std::cell::RefCell; use std::rc::Rc; use clap::*; use log::{info, Level}; use memflow::prelude::v1::*; use memflow_win32::prelude::v1::*; fn main() { let matches = App::new("dump offsets example") .version(crate_version!()) ....
mod error; mod engine; use engine::*; mod mapper; use mapper::*; use std::cell::RefCell; use std::rc::Rc; use clap::*; use log::{info, Level}; use memflow::prelude::v1::*; use memflow_win32::prelude::v1::*;
fn main() { let matches = App::new("dump offsets example") .version(crate_version!()) .author(crate_authors!()) .arg(Arg::with_name("verbose").short("v").multiple(true)) .arg( Arg::with_name("connector") .long("connector") .short("c") ...
function_block-full_function
[ { "content": "pub mod collectors;\n\npub use collectors::*;\n\n\n\nuse crate::error::{Error, Result};\n\n\n\nuse std::collections::HashMap;\n\nuse std::fs::File;\n\nuse std::io::Write;\n\nuse std::path::{Path, PathBuf};\n\n\n\nuse log::{info, warn};\n\n\n\nuse memflow::prelude::v1::*;\n\nuse memflow_win32::prel...
Rust
src/builtins.rs
s0lst1ce/poise
e7bd3353520d9cd320b2565122ca3931caa1d54e
use crate::serenity_prelude as serenity; type BoxErrorSendSync = Box<dyn std::error::Error + Send + Sync>; pub async fn on_error<D>(e: BoxErrorSendSync, ctx: crate::ErrorContext<'_, D, BoxErrorSendSync>) { println!("Encountered an error: {:?}", e); match ctx { crate::ErrorContext::Command(ctx) => { ...
use crate::serenity_prelude as serenity; type BoxErrorSendSync = Box<dyn std::error::Error + Send + Sync>; pub async fn on_error<D>(e: BoxErrorSendSync, ctx: crate::ErrorContext<'_, D, BoxErrorSendSync>) { println!("Encountered an error: {:?}", e); match ctx { crate::ErrorContext::Command(ctx) => { ...
n", num_private_guilds, num_private_guild_members ); } if show_private_guilds { response += "\n_Showing private guilds because you are the bot owner_\n"; } crate::send_reply(ctx, |f| f.content(response).ephemeral(show_private_guilds)).await?; Ok(()) }
function_block-function_prefixed
[ { "content": "// Types used by all command functions\n\ntype Error = Box<dyn std::error::Error + Send + Sync>;\n", "file_path": "examples/framework_usage/main.rs", "rank": 0, "score": 209738.5004888105 }, { "content": "/// Find a command within nested PrefixCommandMeta's by the user message ...
Rust
vendor/sized-chunks/src/tests/sized_chunk.rs
raspbian-packages/cargo
3b1b88e08c83b03469c9a98c3237317c7eb5c330
#![allow(clippy::unit_arg)] use std::fmt::Debug; use std::iter::FromIterator; use std::panic::{catch_unwind, AssertUnwindSafe}; use proptest::{arbitrary::any, collection::vec, prelude::*, proptest}; use proptest_derive::Arbitrary; use crate::sized_chunk::Chunk; #[derive(Debug)] struct InputVec<A>(Vec<A>); impl<A> ...
#![allow(clippy::unit_arg)] use std::fmt::Debug; use std::iter::FromIterator; use std::panic::{catch_unwind, AssertUnwindSafe}; use proptest::{arbitrary::any, collection::vec, prelude::*, proptest}; use proptest_derive::Arbitrary; use crate::sized_chunk::Chunk; #[derive(Debug)] struct InputVec<A>(Vec<A>); impl<A> ...
} #[derive(Arbitrary, Debug)] enum Construct<A> where A: Arbitrary, <A as Arbitrary>::Strategy: 'static, { Empty, Single(A), Pair((A, A)), DrainFrom(InputVec<A>), CollectFrom(InputVec<A>, usize), FromFront(InputVec<A>, usize), FromBack(InputVec<A>, usize), } #[derive(Arbitrary, De...
fn arbitrary_with(_: Self::Parameters) -> Self::Strategy { #[allow(clippy::redundant_closure)] proptest::collection::vec(any::<A>(), 0..64) .prop_map(|v| InputVec(v)) .boxed() }
function_block-function_prefix_line
[ { "content": "pub fn opt(name: &'static str, help: &'static str) -> Arg<'static, 'static> {\n\n Arg::with_name(name).long(name).help(help)\n\n}\n\n\n", "file_path": "src/cargo/util/command_prelude.rs", "rank": 0, "score": 216441.32755796117 }, { "content": "pub fn subcommand(name: &'stati...
Rust
src/io/ndma.rs
archshift/crossbar9
9acf7bcefad6a394eb7085e29ce46d33b4369bc7
use core::ptr; const NDMA_BASE: u32 = 0x10002000u32; #[derive(Clone, Copy)] #[allow(non_camel_case_types)] #[allow(dead_code)] enum Reg { GLOBAL_CNT = 0x00, SRC_ADDR = 0x04, DST_ADDR = 0x08, TRANSFER_CNT = 0x0C, WRITE_CNT = 0x10, BLOCK_CNT = 0x14, FILL_DATA = 0x18, CNT = 0x1C } bf!(Re...
use core::ptr; const NDMA_BASE: u32 = 0x10002000u32; #[derive(Clone, Copy)] #[allow(non_camel_case_types)] #[allow(dead_code)] enum Reg { GLOBAL_CNT = 0x00, SRC_ADDR = 0x04, DST_ADDR = 0x08, TRANSFER_CNT = 0x0C, WRITE_CNT = 0x10, BLOCK_CNT = 0x14, FILL_DATA = 0x18, CNT = 0x1C } bf!(Re...
dmaDst { fn max_xfer_words(&self) -> Option<usize> { match *self { NdmaDst::FixedAddr(_) => None, NdmaDst::LinearBuf(_, len) => Some(len), } } fn dst_type_index(&self) -> u32 { match *self { NdmaDst::FixedAddr(_) => 2, NdmaDst::LinearB...
thod: 10:11, dst_reload: 12:12, src_update_method: 13:14, src_reload: 15:15, blk_xfer_size: 16:19, startup_mode: 24:27, mode_immediate: 28:28, mode_repeating: 29:29, irq_enabled: 30:30, busy: 31:31 }); #[inline(never)] fn read_reg<T: Copy>(reg: Reg, channel: u32) -> T { unsafe {...
random
[ { "content": "#[derive(Clone, Copy)]\n\nenum Reg {\n\n DATA = 0x00,\n\n CNT = 0x01,\n\n}\n\n\n", "file_path": "src/io/i2c.rs", "rank": 2, "score": 132791.73451564353 }, { "content": "#[derive(Clone, Copy)]\n\n#[allow(non_camel_case_types)]\n\nenum Reg {\n\n FIFO_CNT = 0x800,\n\n ...
Rust
src/submit.rs
jsitnicki/io-uring
1c572693c7d617a55da3399d77b205b607fa0585
use std::os::unix::io::{AsRawFd, RawFd}; use std::sync::atomic; use std::{io, ptr}; use crate::register::{execute, Probe}; use crate::sys; use crate::util::{cast_ptr, Fd}; use crate::Parameters; #[cfg(feature = "unstable")] use crate::register::Restriction; #[cfg(feature = "unstable")] use crate::types; pub struct ...
use std::os::unix::io::{AsRawFd, RawFd}; use std::sync::atomic; use std::{io, ptr}; use crate::register::{execute, Probe}; use crate::sys; use crate::util::{cast_ptr, Fd}; use crate::Parameters; #[cfg(feature = "unstable")] use crate::register::Restriction; #[cfg(feature = "unstable")] use crate::types; pub struct ...
pub fn register_files(&self, fds: &[RawFd]) -> io::Result<()> { execute( self.fd.as_raw_fd(), sys::IORING_REGISTER_FILES, fds.as_ptr() as *const _, fds.len() as _, ) .map(drop) } ...
pub fn register_buffers(&self, bufs: &[libc::iovec]) -> io::Result<()> { execute( self.fd.as_raw_fd(), sys::IORING_REGISTER_BUFFERS, bufs.as_ptr() as *const _, bufs.len() as _, ) .map(drop) }
function_block-full_function
[ { "content": "pub fn write_read(ring: &mut IoUring, fd_in: types::Fd, fd_out: types::Fd) -> anyhow::Result<()> {\n\n let text = b\"The quick brown fox jumps over the lazy dog.\";\n\n let mut output = vec![0; text.len()];\n\n\n\n let write_e = opcode::Write::new(fd_in, text.as_ptr(), text.len() as _);\n...
Rust
src/impls/doc.rs
rustyhorde/ruarango
58c68df151aa04d4ee7a42dccf31c7621c307b9b
use super::EMPTY_BODY; use crate::{ doc::{ input::{ CreateConfig, CreatesConfig, DeleteConfig, DeletesConfig, ReadConfig, ReadsConfig, ReplaceConfig, ReplacesConfig, UpdateConfig, UpdatesConfig, }, BASE_DOC_SUFFIX, }, model::{AddHeaders, BuildUrl}, trait...
use super::EMPTY_BODY; use crate::{ doc::{ input::{ CreateConfig, CreatesConfig, DeleteConfig, DeletesConfig, ReadConfig, ReadsConfig, ReplaceConfig, ReplacesConfig, UpdateConfig, UpdatesConfig, }, BASE_DOC_SUFFIX, }, model::{AddHeaders, BuildUrl}, trait...
async fn deletes<T, U, V>(&self, config: DeletesConfig<T>) -> DocMetaVecResult<U, V> where T: Serialize + Send + Sync, U: Serialize + DeserializeOwned + Send + Sync, V: Serialize + DeserializeOwned + Send + Sync, { let url = config.build_url(BASE_DOC_SUFFIX, self)?; ...
let url = config.build_url(BASE_DOC_SUFFIX, self)?; let headers = config.add_headers()?; self.delete(url, headers, EMPTY_BODY, doc_resp).await }
function_block-function_prefix_line
[ { "content": "fn if_none_match_config(kind: IfNoneMatchKind) -> Result<ReadConfig> {\n\n Ok(match kind {\n\n IfNoneMatchKind::Match => ReadConfigBuilder::default()\n\n .collection(TEST_COLL)\n\n .key(DOC_KEY)\n\n .if_none_match(ACTUAL_REV)\n\n .build()?,\n\n...
Rust
crates/simplexpr/src/ast.rs
druskus20/eww
106106ade31e7cc669f2ae53f24191cd0a683c39
use crate::dynval::DynVal; use eww_shared_util::{Span, Spanned}; use itertools::Itertools; use serde::{Deserialize, Serialize}; use eww_shared_util::VarName; #[rustfmt::skip] #[derive(Clone, PartialEq, Eq, Serialize, Deserialize, Debug, strum::EnumString, strum::Display)] pub enum BinOp { #[strum(serialize = "+")...
use crate::dynval::DynVal; use eww_shared_util::{Span, Spanned}; use itertools::Itertools; use serde::{Deserialize, Serialize}; use eww_shared_util::VarName; #[rustfmt::skip] #[derive(Clone, PartialEq, Eq, Serialize, Deserialize, Debug, strum::EnumString, strum::Display)] pub enum BinOp { #[strum(serialize = "+")...
} impl SimplExpr { pub fn literal(span: Span, s: String) -> Self { Self::Literal(DynVal(s, span)) } pub fn synth_string(s: impl Into<String>) -> Self { Self::Literal(DynVal(s.into(), Span::DUMMY)) } pub fn synth_literal<T: Into<DynVal>>(s: T) -> Self { Self::Lite...
Else(_, a, b, c) => write!(f, "({} ? {} : {})", a, b, c), SimplExpr::JsonAccess(_, value, index) => write!(f, "{}[{}]", value, index), SimplExpr::FunctionCall(_, function_name, args) => { write!(f, "{}({})", function_name, args.iter().join(", ")) } SimplEx...
function_block-function_prefixed
[ { "content": "/// get a single ast node from a list of asts, returning an Err if the length is not exactly 1.\n\npub fn require_single_toplevel(span: Span, mut asts: Vec<Ast>) -> AstResult<Ast> {\n\n match asts.len() {\n\n 0 => Err(AstError::MissingNode(span)),\n\n 1 => Ok(asts.remove(0)),\n\n ...
Rust
compiler/term/src/encoding/arch_64_nanboxed.rs
shaneutt/lumen
d3b7a006bb41c5afed8481a5784ef904fbca6ee2
use crate::Tag; use super::{Encoding, MaskInfo}; const NUM_BITS: u64 = 64; const TAG_SHIFT: u64 = 47; pub const TAG_MASK: u64 = 0xFu64 << TAG_SHIFT; const SUBTAG_SHIFT: u64 = TAG_SHIFT - 2; const SUBTAG_MASK: u64 = 0xFCu64 << (TAG_SHIFT - 4); const HEADER_SHIFT: u64 = 2; pub const MAX_ADDR: u64 = (1 << TAG_SHIF...
use crate::Tag; use super::{Encoding, MaskInfo}; const NUM_BITS: u64 = 64; const TAG_SHIFT: u64 = 47; pub const TAG_MASK: u64 = 0xFu64 << TAG_SHIFT; const SUBTAG_SHIFT: u64 = TAG_SHIFT - 2; const SUBTAG_MASK: u64 = 0xFCu64 << (TAG_SHIFT - 4); const HEADER_SHIFT: u64 = 2; pub const MAX_ADDR: u64 = (1 << TAG_SHIF...
pub const TAG_LITERAL: u64 = 1; pub const TAG_BOXED: u64 = 0; pub const TAG_NONE: u64 = 0; pub const TAG_SMALL_INTEGER: u64 = 1 << TAG_SHIFT;...
= MAX_ADDR; const MAX_HEADER_VALUE: u64 = MAX_ADDR >> HEADER_SHIFT; pub struct Encoding64Nanboxed; impl Encoding64Nanboxed { pub const TAG_MASK: u64 = TAG_MASK;
random
[ { "content": "#[inline]\n\npub fn in_area<T, U>(ptr: *const T, start: *const U, end: *const U) -> bool\n\nwhere\n\n T: ?Sized,\n\n U: ?Sized,\n\n{\n\n // If any pointers are null, the only sensible answer is false\n\n if ptr.is_null() || start.is_null() || end.is_null() {\n\n false\n\n } e...
Rust
src/deprel/relative_pos.rs
stickeritis/sticker-encoders
b4649413338a452c06fa7c293bc196e47df5990c
use std::convert::Infallible; use std::collections::HashMap; use conllu::graph::{DepTriple, Node, Sentence}; use conllu::token::Token; use serde_derive::{Deserialize, Serialize}; use super::{ attach_orphans, break_cycles, find_or_create_root, DecodeError, DependencyEncoding, EncodeError, }; use crate::{Encodin...
use std::convert::Infallible; use std::collections::HashMap; use conllu::graph::{DepTriple, Node, Sentence}; use conllu::token::Token; use serde_derive::{Deserialize, Serialize}; use super::{ attach_orphans, break_cycles, find_or_create_root, DecodeError, DependencyEncoding, EncodeError, }; use crate::{Encodin...
} #[derive(Clone, Debug, Deserialize, Eq, Hash, PartialEq, Serialize)] pub struct RelativePOS { pos: String, position: isize, } impl RelativePOS { #[allow(dead_code)] pub fn new(pos: impl Into<String>, position: isize) -> Self { RelativePOS { pos: pos.into(), position,...
fn pos(self, token: &Token) -> Option<&str> { match self { POSLayer::UPos => token.upos(), POSLayer::XPos => token.xpos(), } }
function_block-full_function
[ { "content": "/// Break cycles in the graph.\n\n///\n\n/// Panics when a token does not have a head. To ensure that each\n\n/// token has a head, apply `attach_orphans` to the dependency graph\n\n/// before this function.\n\npub fn break_cycles(sent: &mut Sentence, root_idx: usize) {\n\n let mut prev_compone...
Rust
tests/matrix.rs
danielvschoor/pathfinding
5ee046e4086d696595cd3734d42df3abded0e882
#![cfg(test)] use pathfinding::{matrix, matrix::Matrix, utils::absdiff}; #[test] fn sm() { let mut m = Matrix::new(2, 2, 0usize); m[&(0, 0)] = 0; m[&(0, 1)] = 1; m[&(1, 0)] = 10; m[&(1, 1)] = 11; m[&(0, 1)] = 2; assert_eq!(m[&(0, 0)], 0); assert_eq!(m[&(0, 1)], 2); assert_eq!(m[&(1...
#![cfg(test)] use pathfinding::{matrix, matrix::Matrix, utils::absdiff}; #[test] fn sm() { let mut m = Matrix::new(2, 2, 0usize); m[&(0, 0)] = 0; m[&(0, 1)] = 1; m[&(1, 0)] = 10; m[&(1, 1)] = 11; m[&(0, 1)] = 2; assert_eq!(m[&(0, 0)], 0); assert_eq!(m[&(0, 1)], 2); assert_eq!(m[&(1...
} } assert_eq!(neighbours, manual); } } } } #[test] fn from_rows() { let m = Matrix::from_rows((1..3).map(|n| (1..5).map(move |x| x * n))).unwrap(); assert_eq!(m.rows, 2); assert_eq!(m.columns, 4); assert_eq!(m.to_vec(), vec![...
if dr + dc == 1 || (diagonal && dr == 1 && dc == 1) { manual.push((rr, cc)); }
if_condition
[ { "content": "fn neighbours(network: Matrix<usize>) -> impl FnMut(&usize) -> Vec<(usize, usize)> {\n\n move |&a| {\n\n (0..network.rows)\n\n .filter_map(|b| match network[&(a, b)] {\n\n 0 => None,\n\n p => Some((b, p)),\n\n })\n\n .collect...
Rust
crates/aingle_cascade/src/authority/get_entry_ops_query.rs
Daironode/aingle
54bfcbe21f587699a4e66e6764fe879a348987c8
use ai_hash::EntryHash; use aingle_sqlite::rusqlite::named_params; use aingle_sqlite::rusqlite::Row; use aingle_state::query::prelude::*; use aingle_state::query::StateQueryError; use aingle_types::sgd_op::SgdOpType; use aingle_types::header::WireUpdateRelationship; use aingle_types::prelude::EntryData; use aingle_type...
use ai_hash::EntryHash; use aingle_sqlite::rusqlite::named_params; use aingle_sqlite::rusqlite::Row; use aingle_state::query::prelude::*; use aingle_state::query::StateQueryError; use aingle_types::sgd_op::SgdOpType; use aingle_types::header::WireUpdateRelationship; use aingle_types::prelude::EntryData; use aingle_type...
fn init_fold(&self) -> StateQueryResult<Self::State> { Ok(Default::default()) } fn fold(&self, mut state: Self::State, sgd_op: Self::Item) -> StateQueryResult<Self::State> { match &sgd_op.data.op_type { SgdOpType::StoreEntry => { if sgd_op ....
fn as_map(&self) -> Arc<dyn Fn(&Row) -> StateQueryResult<Self::Item>> { let f = |row: &Row| { let header = from_blob::<SignedHeader>(row.get(row.column_index("header_blob")?)?)?; let op_type = row.get(row.column_index("sgd_type")?)?; let validation_status = row.get(row.column...
function_block-full_function
[ { "content": "#[allow(clippy::let_and_return)]\n\npub fn mdns_listen(service_type: String) -> impl Stream<Item = Result<MdnsResponse, MdnsError>> {\n\n //let service_name = format!(\"{}.local\", AI_SERVICE_TYPE);\n\n let svc_type = format!(\"_{}{}.local\", service_type, AI_SERVICE_PROTOCOL);\n\n //prin...
Rust
src/handlers/user.rs
pfcoder/x-gpu-backend
2e1050d151ad7105bc6d18d27cf60b8cd7858fd9
use chrono::{Duration, Utc}; use poem::{ error::BadRequest, handler, http::StatusCode, http::Uri, session::Session, web::Data, web::Query, web::Redirect, Request, Result, }; use sqlx::PgPool; use std::collections::HashMap; use uuid::Uuid; use crate::configuration::get_configuration; use crate::model::{CreateU...
use chrono::{Duration, Utc}; use poem::{ error::BadRequest, handler, http::StatusCode, http::Uri, session::Session, web::Data, web::Query, web::Redirect, Request, Result, }; use sqlx::PgPool; use std::collections::HashMap; use uuid::Uuid; use crate::configuration::get_configuration; use crate::model::{CreateU...
tracing::info!("user created: {:?}", user); } } let token = sign(uuid).map_err(BadRequest)?; let redirect_url: Uri = format!("https://{}/?token={}", setting.server.domain, token) .parse() .unwrap(); tracing::info!("redirect url: {:?}", redi...
let user = UserService::create( pool.0, CreateUserData { id: uuid, access_token: token_res.access_token, refresh_token: token_res.refresh_token, expires_at: expires_at, created_at: Utc::no...
assignment_statement
[ { "content": "pub fn sign(id: Uuid) -> Result<String> {\n\n let configuration = get_configuration().expect(\"Failed to read configuration.\");\n\n Ok(jsonwebtoken::encode(\n\n &Header::default(),\n\n &Claims::new(id),\n\n &EncodingKey::from_secret(configuration.security.jwt_secret.exp...
Rust
src/bot/run.rs
ReubenMenezes/liro
ecd26641fea70bd8a5004e07c65220786a9a5ec7
use super::{ commands::{account::*, meta::*}, role_manager::RoleManager, }; use crate::{bot::Handler, db::Pool, lichess}; use serenity::{ client::bridge::gateway::{GatewayIntents, ShardManager}, framework::{ standard::macros::{group, hook}, StandardFramework, }, http::Http, m...
use super::{ commands::{account::*, meta::*}, role_manager::RoleManager, }; use crate::{bot::Handler, db::Pool, lichess}; use serenity::{ client::bridge::gateway::{GatewayIntents, ShardManager}, framework::{ standard::macros::{group, hook}, StandardFramework, }, http::Http, m...
} pub async fn run(pool: &Pool, lichess: &lichess::Client) { trace!("run() called"); let token = env::var("DISCORD_TOKEN").expect("Expected a token in the environment"); let application_id = env::var("APPLICATION_ID") .expect("Expected to find the APPLICATION_ID environment variable") ...
if let Err(e) = msg.channel_id.say(&ctx.http, message).await { error!("Unable to send response to channel: {}", e); }
if_condition
[ { "content": "#[derive(Debug, Clone, Copy, Deserialize)]\n\nstruct FormatRating {\n\n rating: Option<i16>,\n\n prov: Option<bool>,\n\n}\n\n\n", "file_path": "src/lichess/client.rs", "rank": 0, "score": 114044.15440063558 }, { "content": "fn with_db(pool: Pool) -> impl Filter<Extract = ...
Rust
src/core/stack.rs
deurzen/wzrd
d1414bb544a0f2b165f1ac511cd957c7dfda3c92
use winsys::common::Window; use std::collections::HashMap; use std::vec::Vec; #[derive(Debug)] pub enum StackLayer { Desktop, Below, Dock, Above, Notification, } pub struct StackManager { window_layers: HashMap<Window, StackLayer>, desktop_windows: Vec<Window>, be...
use winsys::common::Window; use std::collections::HashMap; use std::vec::Vec; #[derive(Debug)] pub enum StackLayer { Desktop, Below, Dock, Above, Notification, } pub struct StackManager { window_layers: HashMap<Window, StackLayer>, desktop_windows: Vec<Window>, be...
pub fn add_window( &mut self, window: Window, layer: StackLayer, ) { if !self.window_layers.contains_key(&window) { let layer_windows = match layer { StackLayer::Desktop => &mut self.desktop_windows, StackLayer::Below => &mut self.bel...
y(10), below_windows: Vec::with_capacity(10), dock_windows: Vec::with_capacity(10), above_windows: Vec::with_capacity(10), notification_windows: Vec::with_capacity(10), above_other: HashMap::with_capacity(30), below_other: HashMap::with_capacity(3...
function_block-function_prefixed
[ { "content": "pub fn main() {}\n", "file_path": "src/bar/main.rs", "rank": 0, "score": 72251.59995597923 }, { "content": "pub fn main() {}\n", "file_path": "src/client/main.rs", "rank": 1, "score": 72251.59995597923 }, { "content": "pub fn main() -> Result<()> {\n\n #[...
Rust
crates/nu-protocol/src/value/stream.rs
chen244/engine-q
f28f28183b620b7efefdfebfa9675d0623b4ccbc
use crate::*; use std::{ fmt::Debug, sync::{ atomic::{AtomicBool, Ordering}, Arc, }, }; pub struct ByteStream { pub stream: Box<dyn Iterator<Item = Result<Vec<u8>, ShellError>> + Send + 'static>, pub ctrlc: Option<Arc<AtomicBool>>, } impl ByteStream { pub fn into_vec(self) -> Re...
use crate::*; use std::{ fmt::Debug, sync::{ atomic::{AtomicBool, Ordering}, Arc, }, }; pub struct ByteStream { pub stream: Box<dyn Iterator<Item = Result<Vec<u8>, ShellError>> + Send + 'static>, pub ctrlc: Option<Arc<AtomicBool>>, } impl ByteStream { pub fn into_vec(self) -> Re...
.debug_struct("ValueStream").finish() } } impl Iterator for ValueStream { type Item = Value; fn next(&mut self) -> Option<Self::Item> { if let Some(ctrlc) = &self.ctrlc { if ctrlc.load(Ordering::SeqCst) { None } else { self.stream.next() ...
{ first = false; } } Ok(output) } pub fn from_stream( input: impl Iterator<Item = Result<String, ShellError>> + Send + 'static, ctrlc: Option<Arc<AtomicBool>>, ) -> StringStream { StringStream { stream: Box::new(input), ...
random
[ { "content": "/// Serializes and escapes a `&str` into a multiline Hjson string.\n\npub fn ml_str<W, F>(wr: &mut W, formatter: &mut F, value: &str) -> Result<()>\n\nwhere\n\n W: io::Write,\n\n F: Formatter,\n\n{\n\n // wrap the string into the ''' (multiline) format\n\n\n\n let a: Vec<&str> = value....
Rust
src/orz/matchfinder.rs
archer884/orz
060dadd7e0609130ca8ba3fd4d3d689a8a3abf13
pub const LZ_MATCH_MAX_LEN: usize = 255; pub const LZ_MATCH_MIN_LEN: usize = 4; const LZ_BUCKET_ITEM_SIZE: usize = 4096; const LZ_BUCKET_ITEM_HASH_SIZE: usize = 8192; pub enum MatchResult { Match { reduced_offset: u16, match_len: u8 }, Literal, } pub struct EncoderMFBucket { heads: [i16; LZ_BUCKET_ITEM_H...
pub const LZ_MATCH_MAX_LEN: usize = 255; pub const LZ_MATCH_MIN_LEN: usize = 4; const LZ_BUCKET_ITEM_SIZE: usize = 4096; const LZ_BUCKET_ITEM_HASH_SIZE: usize = 8192; pub enum MatchResult { Match { reduced_offset: u16, match_len: u8 }, Literal, } pub struct EncoderMFBucket { heads: [i16; LZ_BUCKET_ITEM_H...
a as usize + LZ_BUCKET_ITEM_SIZE - $b as usize) % LZ_BUCKET_ITEM_SIZE) } impl EncoderMFBucket { pub fn new() -> EncoderMFBucket { EncoderMFBucket { heads: [-1; LZ_BUCKET_ITEM_HASH_SIZE], nexts: [-1; LZ_BUCKET_ITEM_SIZE], items: [0; LZ_BUCKET_ITEM_SIZE], ring_...
ecoderMFBucket { items: [u32; LZ_BUCKET_ITEM_SIZE], ring_head: i16, } macro_rules! hash_4bytes { ($buf:expr, $pos:expr) => {{ (*$buf.get_unchecked(($pos + 0) as usize) as u32 * 1333337) + (*$buf.get_unchecked(($pos + 1) as usize) as u32 * 13337) + (*$buf.get_unchecked(($pos + 2) as ...
random
[ { "content": "enum MatchItem {\n\n Match { reduced_offset: u16, match_len: u8 },\n\n Literal { symbol: u8 },\n\n}\n\n\n\nmacro_rules! bucket_context {\n\n ($buf:expr, $pos:expr) => (*$buf.get_unchecked($pos as usize - 1) as usize)\n\n}\n\n\n\nimpl LZEncoder {\n\n pub fn new() -> LZEncoder {\n\n ...
Rust
src/screen.rs
Celeo/gw2_inventory
05d5cb010def5ec649fecf503119e78d4b386079
use crate::{ models::FullItem, util::{filter, paginate}, }; use anyhow::Result; use log::error; use std::{io, sync::mpsc, thread, time::Duration}; use termion::{ event::Key, input::{MouseTerminal, TermRead}, raw::IntoRawMode, screen::AlternateScreen, }; use tui::{ backend::TermionBackend, ...
use crate::{ models::FullItem, util::{filter, paginate}, }; use anyhow::Result; use log::error; use std::{io, sync::mpsc, thread, time::Duration}; use termion::{ event::Key, input::{MouseTerminal, TermRead}, raw::IntoRawMode, screen::AlternateScreen, }; use tui::{ backend::TermionBackend, ...
fn get_all_slots_count(&self) -> usize { self.items.len() } fn search_status(&self) -> String { format!( "Page {}/{}, showing {} per page, {} total items", self.page + 1, self.max_pages(), self.page_size, self.get_all_slots_count...
fn new(items: Vec<FullItem>) -> Self { Self { items, input: String::new(), page: 0, page_size: 0, } }
function_block-full_function
[ { "content": "pub fn paginate(items: &[FullItem], page: usize, page_size: u16) -> Vec<&FullItem> {\n\n let page_size = page_size as usize;\n\n items\n\n .iter()\n\n .skip(page * page_size)\n\n .take(page_size)\n\n .collect()\n\n}\n", "file_path": "src/util/mod.rs", "ran...
Rust
core/bin/zksync_core/src/state_keeper/tests/pending_block.rs
AlmavivA/zksync
3af534ce40ed064bcd558af325e34133501b0848
use chrono::Utc; use num::BigUint; use zksync_types::tx::TimeRange; use zksync_types::{AccountId, SignedZkSyncTx, TokenId, Transfer, ZkSyncTx}; use super::utils::*; use crate::state_keeper::utils::system_time_timestamp; #[tokio::test] async fn seal_pending_block() { let mut tester = StateKeeperTester::new(20, 3, ...
use chrono::Utc; use num::BigUint; use zksync_types::tx::TimeRange; use zksync_types::{AccountId, SignedZkSyncTx, TokenId, Transfer, ZkSyncTx}; use super::utils::*; use crate::state_keeper::utils::system_time_timestamp; #[tokio::test] async fn seal_pending_block() { let mut tester = StateKeeperTester::new(20, 3, ...
async fn correctly_restore_pending_block_timestamp() { let mut tester = StateKeeperTester::new(20, 3, 3); const VALID_UNTIL_DIFF: u64 = 1; let valid_until = system_time_timestamp() + VALID_UNTIL_DIFF; let token_id = TokenId(0); let account_id = AccountId(1); let balance = 200u32; let ...
function_block-full_function
[ { "content": "/// Bench for `ZkSyncState::apply_deposit_op`.\n\nfn apply_deposit_tx(b: &mut Bencher<'_>) {\n\n let (_, state) = generate_state();\n\n\n\n let to_account = state\n\n .get_account(AccountId(0))\n\n .expect(\"Can't get the account\");\n\n\n\n let deposit = Deposit {\n\n ...
Rust
src/lib/markovchain.rs
julianandrews/markovpass
33f09044990aeeb3d459c8fa19ffa8ba5d97c215
extern crate rand; use rand::distributions::weighted::alias_method::WeightedIndex; use rand::prelude::*; use std::collections::HashMap; use std::fmt; #[derive(Debug, PartialEq)] pub enum MarkovChainError { NoNgrams, NoEntropy, NoStartOfWordEntropy, } impl std::error::Error for MarkovChainError {} impl f...
extern crate rand; use rand::distributions::weighted::alias_method::WeightedIndex; use rand::prelude::*; use std::collections::HashMap; use std::fmt; #[derive(Debug, PartialEq)] pub enum MarkovChainError { NoNgrams, NoEntropy, NoStartOfWordEntropy, } impl std::error::Error for MarkovChainError {} impl f...
}
c![ " ab", "abc", "bc ", "c a", " ab", "abc", "cbd", "bd ", "d a", ]; let result = PassphraseMarkovChain::new(ngrams.into_iter()); assert!(result.is_err()); assert_eq!(result.unwrap_err(), MarkovChainError::NoStartOfWordEntropy); }
function_block-function_prefixed
[ { "content": "pub fn parse_args(opts: &getopts::Options, args: &[String]) -> Result<MarkovpassArgs, UsageError> {\n\n let matches = opts\n\n .parse(&args[1..])\n\n .map_err(|_| UsageError::ArgumentParseError)?;\n\n\n\n // TODO: Add support for multiple file arguments.\n\n if matches.free....
Rust
src/app/app.rs
Atul9/skulpin
1320d1545106ba51597d2ed08b530aa0c4b96e55
use super::app_control::AppControl; use super::input_state::InputState; use super::time_state::TimeState; use super::time_state::TimeContext; use super::util::PeriodicEvent; use std::ffi::CString; use crate::RendererBuilder; use winit::dpi::LogicalSize; pub trait AppHandler { fn update( &mut self, ...
use super::app_control::AppControl; use super::input_state::InputState; use super::time_state::TimeState; use super::time_state::TimeContext; use super::util::PeriodicEvent; use std::ffi::CString; use crate::RendererBuilder; use winit::dpi::LogicalSize; pub trait AppHandler { fn update( &mut self, ...
}
window_target ); match event { winit::event::Event::EventsCleared => { time_state.update(TimeContext::System); if print_fps_event.try_take_event( time_state.system().frame_start_instant, st...
function_block-function_prefix_line
[ { "content": "/// Called when winit passes us a WindowEvent::RedrawRequested\n\nfn draw(\n\n canvas: &mut skia_safe::Canvas,\n\n frame_count: i32\n\n) {\n\n // Generally would want to clear data every time we draw\n\n canvas.clear(skia_safe::Color::from_argb(0, 0, 0, 255));\n\n\n\n // Floating po...
Rust
librabft-v2/src/unit_tests/record_store_tests.rs
novifinancial/research
cc2ec64d8028f2540e70ca9f9e7891c4ba72113f
use super::*; use bft_lib::{simulated_context::*, smr_context::*}; struct SharedRecordStore { store: RecordStoreState<SimulatedContext>, contexts: HashMap<Author, SimulatedContext>, } impl SharedRecordStore { fn new(num_nodes: usize, epoch_ttl: usize) -> Self { let epoch_id = EpochId(0); ...
use super::*; use bft_lib::{simulated_context::*, smr_context::*}; struct SharedRecordStore { store: RecordStoreState<SimulatedContext>, contexts: HashMap<Author, SimulatedContext>, } impl SharedRecordStore { fn new(num_nodes: usize, epoch_ttl: usize) -> Self { let epoch_id = EpochId(0); ...
assert_eq!( Some(&commits[1].1), store .highest_commit_certificate() .unwrap() .value .committed_state .as_ref() ); }
st_quorum_certificate_round(), Round(4)); assert_eq!(store.highest_timeout_certificate_round(), Round(3)); assert_eq!(store.highest_committed_round(), Round(0)); assert_eq!(store.current_round(), Round(5)); assert_eq!(store.current_timeouts.len(), 0); } #[test] fn test_commit() { let mut shared_sto...
random
[ { "content": "#[test]\n\nfn test_round_plus_usize() {\n\n assert_eq!(Round(3) + 4, Round(7));\n\n}\n", "file_path": "bft-lib/src/unit_tests/base_type_tests.rs", "rank": 0, "score": 156642.79526516874 }, { "content": "#[test]\n\nfn test_simulated_context() {\n\n let mut context = Simula...
Rust
src/atomics/fill_once_atomic_option.rs
paulocsanz/voluntary-servitude
87209d4744e03d2f2e09cde6fe3d6dfe088daa19
use crate::prelude::*; use std::fmt::{self, Debug, Formatter, Pointer}; use std::{ptr::NonNull, sync::atomic::Ordering}; pub struct FillOnceAtomicOption<T>(AtomicOption<T>); impl<T> FillOnceAtomicOption<T> { #[inline] pub fn new<V>(data: V) -> Self...
use crate::prelude::*; use std::fmt::{self, Debug, Formatter, Pointer}; use std::{ptr::NonNull, sync::atomic::Ordering}; pub struct FillOnceAtomicOption<T>(AtomicOption<T>); impl<T> FillOnceAtomicOption<T> { #[inline] pub fn new<V>(data: V) -> Self...
#[test] fn test_send() { fn assert_send<T: Send>() {} assert_send::<FillOnceAtomicOption<()>>(); } #[test] fn test_sync() { fn assert_sync<T: Sync>() {} assert_sync::<FillOnceAtomicOption<()>>(); } }
0)); assert_eq!(atomic.get_ref(Ordering::Relaxed), Some(&10)); assert_eq!(atomic.get_ref(Ordering::Relaxed), Some(&10)); assert_eq!(atomic.get_ref(Ordering::Relaxed), Some(&10)); assert_eq!(atomic.get_ref(Ordering::Relaxed), Some(&10)); assert_eq!(atomic.get_ref(Ordering::Relaxed...
function_block-function_prefixed
[ { "content": "#[test]\n\nfn clear() {\n\n setup_logger();\n\n let list = voluntary_servitude![1];\n\n assert_eq!(list.iter().count(), 1);\n\n list.clear();\n\n assert_eq!(list.iter().count(), 0);\n\n list.append(3);\n\n list.append(3);\n\n list.append(3);\n\n list.clear();\n\n asse...
Rust
host/src/fs/file.rs
gitter-badger/tinychain
9ed5ed7f0194032ee0c71e236be4bf2a5ba9e384
use std::collections::HashSet; use std::convert::TryFrom; use std::marker::PhantomData; use std::ops::Deref; use std::path::PathBuf; use async_trait::async_trait; use futures::future::{join_all, try_join_all, FutureExt, TryFutureExt}; use futures::try_join; use log::{debug, error}; use tc_error::*; use tc_transact:...
use std::collections::HashSet; use std::convert::TryFrom; use std::marker::PhantomData; use std::ops::Deref; use std::path::PathBuf; use async_trait::async_trait; use futures::future::{join_all, try_join_all, FutureExt, TryFutureExt}; use futures::try_join; use log::{debug, error}; use tc_error::*; use tc_transact:...
.await; let version = version_path(&self.path, txn_id); if version.exists() { debug!("removing old version directory {:?}", version); if let Err(cause) = tokio::fs::remove_dir_all(&version).await { error!( "failed to remove old versio...
join_all( self.listing .read(txn_id) .await .expect("lock file list") .iter() .map(|block_id| block_path(&self.path, txn_id, block_id)) .map(|path| self.cache.remove(path)), )
call_expression
[ { "content": "#[inline]\n\nfn file_ext(path: &'_ PathBuf) -> Option<&'_ str> {\n\n path.extension().and_then(|ext| ext.to_str())\n\n}\n\n\n", "file_path": "host/src/fs/mod.rs", "rank": 2, "score": 300098.60105107253 }, { "content": "pub fn mount(mount_point: PathBuf) -> RwLock<Dir> {\n\n ...
Rust
common/src/cursor.rs
cedric-h/hypermine
abec030395b8275e5bbf140e8f77292696aa5380
use crate::dodeca::{Side, Vertex, SIDE_COUNT}; use crate::graph::{Graph, NodeId}; use lazy_static::lazy_static; #[derive(Debug, Copy, Clone, Eq, PartialEq)] pub struct Cursor { node: NodeId, a: Side, b: Side, c: Side, } impl Cursor { pub fn from_vertex(node: NodeId, vertex: Vertex) -> Self {...
use crate::dodeca::{Side, Vertex, SIDE_COUNT}; use crate::graph::{Graph, NodeId}; use lazy_static::lazy_static; #[derive(Debug, Copy, Clone, Eq, PartialEq)] pub struct Cursor { node: NodeId, a: Side, b: Side, c: Side, } impl Cursor { pub fn from_vertex(node: NodeId, vertex: Vertex) -> Self {...
let (opposite, shared) = match (s.adjacent_to(a), s.adjacent_to(b), s.adjacent_to(c)) { (false, true, true) => (a, (b, c)), (true, false, true) => (b, (a, c)), (true, true, false) => (c, (a, b)), ...
{ node, a, b, c } } pub fn step<N, C>(self, graph: &Graph<N, C>, dir: Dir) -> Option<Self> { let (a, b, c) = (self.a, self.b, self.c); let a_prime = NEIGHBORS[a as usize][b as usize][c as usize].unwrap(); let b_prime = NEIGHBORS[b as us...
random
[ { "content": "#[derive(Debug, Clone)]\n\nstruct Node<N, C> {\n\n value: Option<N>,\n\n cubes: [Option<C>; VERTEX_COUNT],\n\n parent_side: Option<Side>,\n\n /// Distance to origin via parents\n\n length: u32,\n\n neighbors: [Option<NodeId>; SIDE_COUNT],\n\n}\n\n\n\nimpl<N, C> Node<N, C> {\n\n ...
Rust
src/messages/delete_topics_request.rs
0x1991babe/kafka-protocol
7eca9997f8a113148090a4f10125f58e1850e8f7
#![allow(unused)] use std::borrow::Borrow; use std::collections::BTreeMap; use bytes::Bytes; use log::error; use uuid::Uuid; use crate::protocol::{ Encodable, Decodable, MapEncodable, MapDecodable, Encoder, Decoder, EncodeError, DecodeError, Message, HeaderVersion, VersionRange, types, write_unknown_tagged...
#![allow(unused)] use std::borrow::Borrow; use std::collections::BTreeMap; use bytes::Bytes; use log::error; use uuid::Uuid; use crate::protocol::{ Encodable, Decodable, MapEncodable, MapDecodable, Encoder, Decoder, EncodeError, DecodeError, Message, HeaderVersion, VersionRange, types, write_unknown_tagged...
} } impl Default for DeleteTopicsRequest { fn default() -> Self { Self { topics: Default::default(), topic_names: Default::default(), timeout_ms: 0, unknown_tagged_fields: BTreeMap::new(), } } } impl Message for DeleteTopicsRequest { con...
Ok(Self { topics, topic_names, timeout_ms, unknown_tagged_fields, })
call_expression
[ { "content": "/// An API request.\n\n///\n\n/// Every abstract request must be able to provide the following items:\n\n/// - An API key mapped to this request.\n\n/// - A version based on a provided header version.\n\npub trait Request: Message + Encodable + Decodable + HeaderVersion {\n\n /// The API key of...
Rust
src/oauth/mod.rs
kawamuray/phoseum
a75da0a6200655dd9d1e7328ae823b45ea6c326e
pub mod store; use failure::{self, Fail}; use log::debug; use oauth2::basic::BasicClient; use oauth2::reqwest::http_client; use oauth2::{ self, AuthUrl, AuthorizationCode, ClientId, ClientSecret, CsrfToken, PkceCodeChallenge, PkceCodeVerifier, RedirectUrl, RefreshToken, Scope, TokenResponse, TokenUrl, }; use s...
pub mod store; use failure::{self, Fail}; use log::debug; use oauth2::basic::BasicClient; use oauth2::reqwest::http_client; use oauth2::{ self, AuthUrl, AuthorizationCode, ClientId, ClientSecret, CsrfToken, PkceCodeChallenge, PkceCodeVerifier, RedirectUrl, RefreshToken, Scope, TokenResponse, TokenUrl, }; use s...
.take() .ok_or(Error::AuthNotStarted)? .pkce_verifier; let resp = self .oauth2_client .exchange_code(AuthorizationCode::new(auth_code)) .set_pkce_verifier(pkce_verifier) .request(http_client) .map_err(|e| Error::TokenRequest(...
splay = "{}", _0)] StoredSecret(#[fail(cause)] store::Error), } impl From<store::Error> for Error { fn from(e: store::Error) -> Self { Error::StoredSecret(e) } } pub type Result<T> = std::result::Result<T, Error>; pub struct TokenService { store: TokenStore, oauth2_client: BasicClient, ...
random
[ { "content": "pub trait Error: Fail {\n\n /// Return if this error is caused by fatal error such as local hardware\n\n /// glitch or misconfiguration that it is hopeless to keep running the app.\n\n fn is_fatal(&self) -> bool;\n\n}\n\n\n\n#[derive(Debug, Copy, Clone, Eq, PartialEq)]\n\npub enum MediaTy...
Rust
src/pmg0/ien.rs
Colin-Suckow/ADuCM302x
f0d62f2b527184e1f192d4f2153f5827fd57fe3c
#[doc = "Reader of register IEN"] pub type R = crate::R<u32, super::IEN>; #[doc = "Writer for register IEN"] pub type W = crate::W<u32, super::IEN>; #[doc = "Register IEN `reset()`'s with value 0"] impl crate::ResetValue for super::IEN { type Type = u32; #[inline(always)] fn reset_value() -> Self::Type { ...
#[doc = "Reader of register IEN"] pub type R = crate::R<u32, super::IEN>; #[doc = "Writer for register IEN"] pub type W = crate::W<u32, super::IEN>; #[doc = "Register IEN `reset()`'s with value 0"] impl crate::ResetValue for super::IEN { type Type = u32; #[inline(always)] fn reset_value() -> Self::Type { ...
#[doc = "Checks if the value of the field is `REGION1`"] #[inline(always)] pub fn is_region1(&self) -> bool { *self == RANGEBAT_A::REGION1 } #[doc = "Checks if the value of the field is `REGION2`"] #[inline(always)] pub fn is_region2(&self) -> bool { *self == RANGEBAT_A::REG...
pub fn variant(&self) -> RANGEBAT_A { match self.bits { 0 => RANGEBAT_A::REGION1, 1 => RANGEBAT_A::REGION2, 2 => RANGEBAT_A::REGION3, 3 => RANGEBAT_A::NA, _ => unreachable!(), } }
function_block-full_function
[ { "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
auth/src/cmd/reset.rs
tokera-com/ate
42c4ce5a0c0aef47aeb4420cc6dc788ef6ee8804
#![allow(unused_imports)] use ate::prelude::*; use error_chain::bail; use std::io::stdout; use std::io::Write; use std::sync::Arc; use tracing::{debug, error, info, instrument, span, trace, warn, Level}; use url::Url; use crate::error::*; use crate::helper::*; use crate::opt::*; use crate::prelude::*; use crate::reque...
#![allow(unused_imports)] use ate::prelude::*; use error_chain::bail; use std::io::stdout; use std::io::Write; use std::sync::Arc; use tracing::{debug, error, info, instrument, span, trace, warn, Level}; use url::Url; use crate::error::*; use crate::helper::*; use crate::opt::*; use crate::prelude::*; use crate::reque...
e_of_the_day.as_str()); println!(""); } println!("Below is your new Google Authenticator QR code - scan it on your phone and"); println!("save it as this code is the only way you can recover the account another time."); println!(""); println!("{}", result.qr_code); ...
function_block-function_prefixed
[ { "content": "pub fn session_to_b64(session: AteSessionType) -> Result<String, SerializationError> {\n\n let format = SerializationFormat::MessagePack;\n\n let bytes = format.serialize(&session)?;\n\n Ok(base64::encode(bytes))\n\n}\n\n\n", "file_path": "auth/src/helper/misc.rs", "rank": 0, ...
Rust
src/impls/third_party/nalgebra030.rs
exjam/bevy-inspector-egui
647cfb3b1e7be9a5caff51fbc5c1fa82346606c7
use bevy_egui::egui; use nalgebra030::{ allocator::Allocator, storage::StorageMut, Complex, DefaultAllocator, Dim, DimName, Isometry, Matrix, OPoint, Quaternion, SVector, Scalar, Translation, Unit, }; use crate::Inspectable; impl<T: Scalar + Inspectable, R: Dim, C: Dim, S: StorageMut<T, R, C>> Inspectable ...
use bevy_egui::egui; use nalgebra030::{ allocator::Allocator, storage::StorageMut, Complex, DefaultAllocator, Dim, DimName, Isometry, Matrix, OPoint, Quaternion, SVector, Scalar, Translation, Unit, }; use crate::Inspectable; impl<T: Scalar + Inspectable, R: Dim, C: Dim, S: StorageMut<T, R, C>> Inspectable ...
} impl<T: Scalar + Inspectable, const D: usize> Inspectable for Translation<T, D> { type Attributes = <SVector<T, D> as Inspectable>::Attributes; fn ui( &mut self, ui: &mut bevy_egui::egui::Ui, options: Self::Attributes, context: &mut crate::Context, ) -> bool { se...
fn ui( &mut self, ui: &mut egui::Ui, options: Self::Attributes, context: &mut crate::Context, ) -> bool { self.coords.ui(ui, options, context) }
function_block-full_function
[ { "content": "/// Draws the inspector UI for the given value.\n\n///\n\n/// This function gets used for the implementation of [`Inspectable`](crate::Inspectable)\n\n/// for [`ReflectedUI`](ReflectedUI).\n\npub fn ui_for_reflect(value: &mut dyn Reflect, ui: &mut egui::Ui, context: &mut Context) -> bool {\n\n ...
Rust
src/types/sequence.rs
FelixPodint/imap-codec
48019304520dcaade13fc94a5f359d0a450b7a79
use std::{ convert::{TryFrom, TryInto}, num::NonZeroU32, }; #[cfg(feature = "arbitrary")] use arbitrary::Arbitrary; #[cfg(feature = "serdex")] use serde::{Deserialize, Serialize}; use crate::parse::sequence::sequence_set; #[cfg_attr(feature = "arbitrary", derive(Arbitrary))] #[cfg_attr(feature = "serdex", de...
use std::{ convert::{TryFrom, TryInto}, num::NonZeroU32, }; #[cfg(feature = "arbitrary")] use arbitrary::Arbitrary; #[cfg(feature = "serdex")] use serde::{Deserialize, Serialize}; use crate::parse::sequence::sequence_set; #[cfg_attr(feature = "arbitrary", derive(Arbitrary))] #[cfg_attr(feature = "serdex", de...
for (test, expected) in tests { let seq_set = SequenceSet::try_from(test).unwrap(); let got: Vec<NonZeroU32> = seq_set .iter(Strategy::Naive { largest: 3.try_into().unwrap(), }) .collect(); assert_eq!(*expe...
let tests = vec![ ("*", vec![3]), ("1:*", vec![1, 2, 3]), ("5,1:*,2:*", vec![5, 1, 2, 3, 2, 3]), ("*:2", vec![]), ("*:*", vec![3]), ("4:6,*", vec![4, 5, 6, 3]), ] .into_iter() .map(|(raw, vec)| { ( ...
assignment_statement
[ { "content": "pub fn read_line(prompt: &str) -> String {\n\n print!(\"{}{}\", prompt, ColorClient.prefix());\n\n std::io::stdout().flush().unwrap();\n\n\n\n let mut line = String::new();\n\n std::io::stdin().read_line(&mut line).unwrap();\n\n\n\n print!(\"{}\", ColorClient.suffix());\n\n\n\n l...
Rust
test/src/specs/tx_pool/dao.rs
yulidai/ckb
ae955f365e02b527e5c8be94d024ef70a4052b8b
use crate::utils::{assert_send_transaction_fail, is_committed}; use crate::{Net, Node, Spec}; use ckb_resource::CODE_HASH_DAO; use ckb_test_chain_utils::always_success_cell; use ckb_types::{ bytes::Bytes, core::{BlockNumber, Capacity, ScriptHashType, TransactionBuilder, TransactionView}, packed::{self, Cell...
use crate::utils::{assert_send_transaction_fail, is_committed}; use crate::{Net, Node, Spec}; use ckb_resource::CODE_HASH_DAO; use ckb_test_chain_utils::always_success_cell; use ckb_types::{ bytes::Bytes, core::{BlockNumber, Capacity, ScriptHashType, TransactionBuilder, TransactionView}, packed::{self, Cell...
; } } } fn ensure_committed(node: &Node, transaction: &TransactionView) -> (OutPoint, H256) { node.generate_blocks(20); let tx_hash = node .rpc_client() .send_transaction(transaction.data().into()); node.generate_blocks(20); let tx_status = node .rpc_cli...
assert_send_transaction_fail( node0, &transaction, "InvalidTx(ScriptFailure(ValidationFailure(1)))", )
call_expression
[ { "content": "fn build_forks(node: &Node, offsets: &[u64]) {\n\n let rpc_client = node.rpc_client();\n\n for offset in offsets.iter() {\n\n let mut template = rpc_client.get_block_template(None, None, None);\n\n template.current_time = Timestamp(template.current_time.0 + offset);\n\n ...
Rust
src/shard/commit_policy.rs
coadler/thingvellir
f8b9167f936d3ed2c729e261e5f55fb386f4ae86
use tokio::time::Duration; use crate::UpstreamError; use smallvec::SmallVec; pub(crate) enum InnerCommitPolicy { Noop, Immediate(ImmediateCommitWaiter), Within(Duration), } #[derive(Clone, Copy)] pub enum DefaultCommitPolicy { Immediate, Within(Duration), } pub(super) enum CommitPolicy...
use tokio::time::Duration; use crate::UpstreamError; use smallvec::SmallVec; pub(crate) enum InnerCommitPolicy { Noop, Immediate(ImmediateCommitWaiter), Within(Duration), } #[derive(Clone, Copy)] pub enum DefaultCommitPolicy { Immediate, Within(Duration), } pub(super) enum CommitPolicy...
} impl From<ImmediateCommitWaiter> for AccumulatedCommitPolicy { fn from(waiter: ImmediateCommitWaiter) -> Self { let mut vec = SmallVec::new(); vec.push(waiter); AccumulatedCommitPolicy::Immediate(vec) } } impl AccumulatedCommitPolicy { pub(super) fn new() -> Self { Accum...
fn from(commit_policy: InnerCommitPolicy) -> Self { match commit_policy { InnerCommitPolicy::Within(duration) => AccumulatedCommitPolicy::Within(duration), InnerCommitPolicy::Immediate(callback) => callback.into(), InnerCommitPolicy::Noop => AccumulatedCommitPolicy::Noop, ...
function_block-full_function
[ { "content": "pub fn service_builder<Key: Send + Clone + Hash + Eq + Display + 'static, Data: ServiceData>(\n\n max_data_capacity: usize,\n\n) -> ServiceBuilder<Key, Data> {\n\n ServiceBuilder::new(max_data_capacity)\n\n}\n\n\n\nimpl<Key: Send + Clone + Hash + Eq + Display + 'static, Data: ServiceData>\n\...
Rust
src/login.rs
tiptenbrink/tiauth
e1de40337caeaad86e525eff4189b82891d9db45
use crate::{Deserialize, Serialize}; use crate::files; use std::time::SystemTime; use ed25519_dalek::Signer; use crate::error::{ErrorReject, RejectTypes}; use crate::params; use crate::reject; #[derive(Deserialize, Serialize)] pub struct UserLogin { user_hex: String, password_hash_hex: String, } #[derive(Dese...
use crate::{Deserialize, Serialize}; use crate::files; use std::time::SystemTime; use ed25519_dalek::Signer; use crate::error::{ErrorReject, RejectTypes}; use crate::params; use crate::reject; #[derive(Deserialize, Serialize)] pub struct UserLogin { user_hex: String, password_hash_hex: String, } #[derive(Dese...
pub async fn login_user( user_login: UserLogin) -> Result<impl warp::Reply, warp::Rejection> { let user_hex = &user_login.user_hex; let save_user = files::read_user(user_hex, true).await .map_err(|e| { files::io_nonexistent_reject(e, "Error reading user data (login user)", ...
er_hex_param: params::UserHex) -> Result<impl warp::Reply, warp::Rejection> { let user_hex = user_hex_param.user_hex; let save_user = files::read_user(&user_hex, false).await .map_err(|e| { files::io_nonexistent_reject(e, "Error reading user data (user public)", ...
function_block-function_prefixed
[ { "content": "pub fn io_nonexistent_reject(e: io::Error, msg: &'static str, ne_msg: &'static str) -> ErrorReject {\n\n let err_msg = e.to_string();\n\n if io_is_nonexistent(&e) {\n\n ErrorReject {\n\n rt: RejectTypes::NonExistent,\n\n msg: ne_msg,\n\n e: err_msg\n\n...
Rust
src/lib.rs
ddboline/one_time_pad
c83e02920c355395b859581471049cff45b54ca5
#![feature(specialization, const_fn)] #[macro_use] extern crate pyo3cls; use pyo3::types::PyModule; use pyo3::{PyRawObject, PyResult, Python}; use rand::distributions::{Distribution, Uniform}; use rayon::prelude::*; use std::collections::HashSet; struct OneTimePad { valid_chars: Vec<char>, encrypt_key: Vec<u...
#![feature(specialization, const_fn)] #[macro_use] extern crate pyo3cls; use pyo3::types::PyModule; use pyo3::{PyRawObject, PyResult, Python}; use rand::distributions::{Distribution, Uniform}; use rayon::prelude::*; use std::collections::HashSet; struct OneTimePad { valid_chars: Vec<char>, encrypt_key: Vec<u...
sult<String> { Ok(self.pad.get_key_str()) } fn set_encrypt_key(&mut self, encrypt_key: String) -> PyResult<()> { Ok(self.pad.set_encrypt_key(&encrypt_key)) } } #[pymodule] fn _one_time_pad(_py: Python, m: &PyModule) -> PyResult<()> { m.add_class::<PyOneTimePad>()?; Ok(()) } #[cfg...
:<Vec<String>>() .join("") } #[pyclass] struct PyOneTimePad { pad: OneTimePad, } #[pymethods] impl PyOneTimePad { #[new] fn new(obj: &PyRawObject, keysize: usize, extra_chars: String) { obj.init(PyOneTimePad { pad: OneTimePad::new(keysize, &extra_chars), }) } f...
random
[ { "content": "# one_time_pad\n\nDemo using one time pad implementation to show how to use pyo3\n", "file_path": "README.md", "rank": 12, "score": 1.3531409352219983 } ]
Rust
sqlxmq_stress/src/main.rs
imbolc/sqlxmq
08b71b59aeb7edd7377c4b745959aa7458c3b4ae
use std::env; use std::error::Error; use std::process::abort; use std::sync::RwLock; use std::time::{Duration, Instant}; use futures::channel::mpsc; use futures::StreamExt; use lazy_static::lazy_static; use serde::{Deserialize, Serialize}; use sqlx::{Pool, Postgres}; use sqlxmq::{job, CurrentJob, JobRegistry}; use tok...
use std::env; use std::error::Error; use std::process::abort; use std::sync::RwLock; use std::time::{Duration, Instant}; use futures::channel::mpsc; use futures::StreamExt; use lazy_static::lazy_static; use serde::{Deserialize, Serialize}; use sqlx::{Pool, Postgres}; use sqlxmq::{job, CurrentJob, JobRegistry}; use tok...
}); stream.tick().await; } } #[tokio::main] async fn main() -> Result<(), Box<dyn Error>> { let _ = dotenv::dotenv(); let pool = Pool::connect(&env::var("DATABASE_URL")?).await?; sqlxmq::clear_all(&pool).await?; let registry = JobRegistry::new(&[example_job]); let _run...
if let Err(e) = start_job(pool, i).await { eprintln!("Failed to start job: {:?}", e); abort(); }
if_condition
[ { "content": "fn to_duration(interval: PgInterval) -> Duration {\n\n const SECONDS_PER_DAY: u64 = 24 * 60 * 60;\n\n if interval.microseconds < 0 || interval.days < 0 || interval.months < 0 {\n\n Duration::default()\n\n } else {\n\n let days = (interval.days as u64) + (interval.months as u...
Rust
examples/max2sat/relax.rs
xgillard/ddo
300be0213e66e784415207273e6dc6f4971020a9
use std::cmp::{min, max}; use ddo::{Problem, Relaxation, Decision, VarSet}; use crate::model::{Max2Sat, State, t, f}; #[derive(Debug, Clone)] pub struct Max2SatRelax<'a> { problem : &'a Max2Sat, vars : VarSet, vr : isize, nk : Vec<isize>, estimates: Vec<isize>, } impl <'a> Max2...
use std::cmp::{min, max}; use ddo::{Problem, Relaxation, Decision, VarSet}; use crate::model::{Max2Sat, State, t, f}; #[derive(Debug, Clone)] pub struct Max2SatRelax<'a> { problem : &'a Max2Sat, vars : VarSet, vr : isize, nk : Vec<isize>, estimates: Vec<isize>, } impl <'a> Max2...
fn precompute_nks(pb: &Max2Sat) -> Vec<isize> { let mut estimates = vec![0_isize; pb.nb_vars]; for (i, est) in estimates.iter_mut().enumerate() { *est = Self::precompute_nk(pb, i); } estimates } fn precompute_nk(pb: &Max2Sat, k: usize) -> isize { let mut ...
let nk = Self::precompute_nks(problem); Max2SatRelax { problem, vars: problem.all_vars(), vr, nk, estimates} }
function_block-function_prefix_line
[ { "content": "fn pos(x: isize) -> isize { max(0, x) }\n\n\n\n\n\n#[derive(Debug, Hash, Eq, PartialEq, Clone)]\n\npub struct State {\n\n pub depth : usize,\n\n pub substates: Vec<isize>\n\n}\n\n\n\nimpl Index<Variable> for State {\n\n type Output = isize;\n\n\n\n fn index(&self, index: Variable) -...
Rust
libslide/src/math/gcd_poly_zz.rs
ayazhafiz/slide
3f048bda74dad485ff3ab87eff5a592b6f9d9570
use crate::math::gcd; use crate::math::poly::Poly; use crate::poly; use core::cmp::{max, min}; pub fn gcd_poly_zz_heu(f: Poly, g: Poly) -> Result<(Poly, Poly, Poly), &'static str> { if let Some(res) = trivial_gcd(&f, &g) { return Ok(res); } let df = f.deg(); let dg = g.deg(); let (gcd_va...
use crate::math::gcd; use crate::math::poly::Poly; use crate::poly; use core::cmp::{max, min}; pub fn gcd_poly_zz_heu(f: Poly, g: Poly) -> Result<(Poly, Poly, Poly), &'static str> { if let Some(res) = trivial_gcd(&f, &g) { return Ok(res); } let df = f.deg(); let dg = g.deg(); let (gcd_va...
assert_eq!( gcd_poly_zz_heu(poly![1, 10, 35, 50, 24], poly![1, 1]), Ok((poly![1, 1], poly![1, 9, 26, 24], poly![1])) ) } #[test] fn test_gcd_poly_zz_heu_3() { assert_eq!( gcd_poly_zz_heu(poly![1, -9, -1, 9], poly![1, -8, -9]), Ok((poly![1...
if r.is_zero() { match g.clone().div(heu_poly.clone()) { Ok(q) => { _cfg2 = q.0; r = q.1; } Err(e) => return Err(e), } if r.is_zero() { heu_poly...
random
[ { "content": "fn fn_name<T>(_: T) -> &'static str {\n\n let name = std::any::type_name::<T>();\n\n name.split(\"::\").last().unwrap()\n\n}\n\n\n\nimpl fmt::Display for Rule {\n\n fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {\n\n write!(\n\n f,\n\n \"{}\",\n\n ...
Rust
rust/bs_call/src/config.rs
IsmailM/gemBS-rs
4fb4c130516951e4f1cb33112632888346f8deb1
use std::collections::HashMap; use std::str::FromStr; use std::{io, fmt}; use std::io::{Error, ErrorKind}; use crate::htslib; use crate::defs::{CtgRegion, CtgInfo}; use crate::dbsnp; pub fn new_err(s: String) -> io::Error { Error::new(ErrorKind::Other, s) } #[derive(Debug, Copy, Clone)] pub struct OType(u32); im...
use std::collections::HashMap; use std::str::FromStr; use std::{io, fmt}; use std::io::{Error, ErrorKind}; use crate::htslib; use crate::defs::{CtgRegion, CtgInfo}; use crate::dbsnp; pub fn new_err(s: String) -> io::Error { Error::new(ErrorKind::Other, s) } #[derive(Debug, Copy, Clone)] pub struct OType(u32); im...
} } impl fmt::Display for OType { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { write!(f, "{}", match self.0 { htslib::FT_BCF_GZ => "wb", htslib::FT_BCF => "wbu", htslib::FT_VCF_GZ => "wz", _ => "w", }) } } #[derive(Debug,Clone)] pub enum ConfVar { Bool(bool), Int(usize), ...
match s.to_lowercase().as_str() { "b" => Ok(OType(htslib::FT_BCF_GZ)), "u" => Ok(OType(htslib::FT_BCF)), "z" => Ok(OType(htslib::FT_VCF_GZ)), "v" => Ok(OType(htslib::FT_VCF)), _ => Err("no match"), }
if_condition
[ { "content": "pub fn add_command_opts(gem_bs: &GemBS, args: &mut String, sec: Section, opt_list: &[(&'static str, &'static str, VarType)]) {\n\n\tfor (x, y, t) in opt_list.iter() {\n\n\t\tmatch t {\n\n\t\t\tVarType::Bool => if gem_bs.get_config_bool(sec, x) { \n\n\t\t\t\targs.push_str(format!(\"--{}\\x1e\", y)....
Rust
hotham/src/systems/pointers.rs
dromomo/hotham
330bfba946e2e0e6da5741d474dea9b890af24e8
use ash::vk; use egui::Pos2; use hecs::{PreparedQuery, With, World}; use nalgebra::{ point, vector, Isometry3, Orthographic3, Point3, Quaternion, Translation3, UnitQuaternion, }; use rapier3d::{ math::Point, prelude::{InteractionGroups, Ray}, }; const POSITION_OFFSET: [f32; 3] = [0., 0.071173, -0.066082]; ...
use ash::vk; use egui::Pos2; use hecs::{PreparedQuery, With, World}; use nalgebra::{ point, vector, Isometry3, Orthographic3, Point3, Quaternion, Translation3, UnitQuaternion, }; use rapier3d::{ math::Point, prelude::{InteractionGroups, Ray}, }; const POSITION_OFFSET: [f32; 3] = [0., 0.071173, -0.066082]; ...
} } } pub(crate) fn apply_grip_offset(position: &mut Isometry3<f32>) { let updated_rotation = position.rotation.quaternion() * ROTATION_OFFSET; let updated_translation = position.translation.vector - vector!(POSITION_OFFSET[0], POSITION_OFFSET[1], POSITION_OFFSET[2]); position.rotation...
match world.get_mut::<Panel>(entity) { Ok(mut panel) => { let panel_extent = &panel.extent; let panel_transform = hit_collider.position(); let cursor_location = get_cursor_location_for_panel(&hit_point, panel_transform, ...
if_condition
[ { "content": "pub fn apply_grip_offset(position: &mut Isometry3<f32>) {\n\n let updated_rotation = position.rotation.quaternion() * ROTATION_OFFSET;\n\n let updated_translation = position.translation.vector\n\n - Vector3::new(POSITION_OFFSET[0], POSITION_OFFSET[1], POSITION_OFFSET[2]);\n\n posit...
Rust
website/website/src/pages/holy_day.rs
gbj/commonprayer
15197dcb7fc2417b5f5695964eb0afbeb2969f94
use crate::{components::*, preferences, utils::language::locale_to_language}; use calendar::{ lff2018::LFF_BIOS, Feast, HolyDayId, LiturgicalDayId, Time, BCP1979_CALENDAR, LFF2018_CALENDAR, }; use lectionary::{ReadingType, LFF2018_LECTIONARY, RCL}; use leptos::*; use library::{lff2018::collects::*, CollectId}; use ...
use crate::{components::*, preferences, utils::language::locale_to_language}; use calendar::{ lff2018::LFF_BIOS, Feast, HolyDayId, LiturgicalDayId, Time, BCP1979_CALENDAR, LFF2018_CALENDAR, }; use lectionary::{ReadingType, LFF2018_LECTIONARY, RCL}; use leptos::*; use library::{lff2018::collects::*, CollectId}; use ...
static_props(locale: &str, _path: &str, params: &HolyDayParams) -> Option<HolyDayProps> { serde_json::from_str::<Feast>(&format!(r#""{}""#, params.feast)) .ok() .and_then(|feast| { let language = locale_to_language(locale); let eve_of = BCP1979_CALENDAR ...
erialize, Clone)] pub struct HolyDayProps { date: Option<String>, locale: String, name: String, bio: Option<String>, collect_traditional: Document, collect_contemporary: Document, first_lesson: Document, psalm: Document, epistle: Document, gospel: Document, } pub fn holy_day() -...
random
[ { "content": "pub fn liturgy_to_preferences(document: &Document) -> Option<(String, LiturgyPreferences)> {\n\n if let Content::Liturgy(liturgy) = &document.content {\n\n Some((\n\n document.label.clone().unwrap_or_default(),\n\n liturgy.preferences.clone(),\n\n ))\n\n }...
Rust
crypto-markets/src/exchanges/deribit/utils.rs
elbart/crypto-crawler-rs
973ebc23230460b51bd7cf06805147a238c7aacd
use super::super::utils::http_get; use crate::{ error::{Error, Result}, market::{Fees, Precision, QuantityLimit}, Market, }; use crypto_market_type::MarketType; use serde::{Deserialize, Serialize}; use serde_json::Value; use std::collections::HashMap; fn check_error_in_body(body: String) -> Result<String>...
use super::super::utils::http_get; use crate::{ error::{Error, Result}, market::{Fees, Precision, QuantityLimit}, Market, }; use crypto_market_type::MarketType; use serde::{Deserialize, Serialize}; use serde_json::Value; use std::collections::HashMap; fn check_error_in_body(body: String) -> Result<String>...
fn fetch_symbols(kind: &str) -> Result<Vec<String>> { let all_markets = fetch_raw_markets(kind)?; let all_symbols: Vec<String> = all_markets.into_iter().map(|x| x.instrument_name).collect(); Ok(all_symbols) } pub(super) fn fetch_inverse_future_symbols() -> Result<Vec<String>> { let result = fetch_sym...
ult { Ok(mut instruments) => { all_markets.append(&mut instruments); } Err(error) => { return Err(error); } } Ok(all_markets.into_iter().filter(|x| x.is_active).collect()) }
function_block-function_prefixed
[ { "content": "// get the contract_size field.\n\nfn fetch_contract_size(url: &str) -> BTreeMap<String, f64> {\n\n #[derive(Serialize, Deserialize)]\n\n struct RawMarket {\n\n symbol: String,\n\n contract_code: String,\n\n contract_size: f64,\n\n }\n\n\n\n #[derive(Serialize, Des...
Rust
stats/src/cpu.rs
Max-Meldrum/enya
7e1ac28ef4e3665075f580b918cabd8ed83ae004
use crate::util; use std::fs::File; use std::io::{BufRead, BufReader}; use crate::error::ErrorKind::*; use crate::error::*; use crate::sysconf::*; lazy_static! { static ref CLOCK_TICKS: u64 = clock_ticks().expect("Unable to fetch clock ticks from sysconf"); } const CPUACCT_USAGE: &str = "cpuacct.usage";...
use crate::util; use std::fs::File; use std::io::{BufRead, BufReader}; use crate::error::ErrorKind::*; use crate::error::*; use crate::sysconf::*; lazy_static! { static ref CLOCK_TICKS: u64 = clock_ticks().expect("Unable to fetch clock ticks from sysconf"); } const CPUACCT_USAGE: &str = "cpuacct.usage";...
self.collections += 1; self.total_usage = usage; self.system_usage = sys; } } } fn get_system_cpu_usage(&self) -> Result<u64> { match File::open("/proc/stat") { Ok(file) => { let mut reader = BufReader::ne...
if self.collections == 1 { self.avg = cpu_percent; } else { let ema: f64 = (cpu_percent - self.avg) * (2.0 / (self.collections + 1) as f64) + self.avg; if let Ok(ema_fmt) = util::fmt_float(ema) {...
if_condition
[ { "content": "pub fn path(key: &str, cgroups_path: &str) -> Option<String> {\n\n let mount = MOUNTS.get(key);\n\n let rel = PATHS.get(key);\n\n if mount.is_none() || rel.is_none() {\n\n None\n\n } else if rel.unwrap() == \"/\" {\n\n Some(format! {\"{}{}\", &mount.unwrap(), cgroups_path...
Rust
src/main.rs
knutwalker/latest-maven-version
7542ad4d7bda9bf902e6f30ae23882af167198d2
use color_eyre::eyre::Result; use console::{style, Term}; use resolvers::{Client, Resolver, UrlResolver}; use semver::{Version, VersionReq}; use std::sync::Arc; use versions::Versions; mod metadata; mod opts; mod resolvers; mod versions; #[tokio::main] async fn main() -> Result<()> { if Term::stdout().features(...
use color_eyre::eyre::Result; use console::{style, Term}; use resolvers::{Client, Resolver, UrlResolver}; use semver::{Version, VersionReq}; use std::sync::Arc; use versions::Versions; mod metadata; mod opts; mod resolvers; mod versions; #[tokio::main] async fn main() -> Result<()> { if Term::stdout().features(...
] fn new<T, U>(group_id: T, artifact: U) -> Self where T: Into<String>, U: Into<String>, { Self { group_id: group_id.into(), artifact: artifact.into(), } } } #[derive(Debug, Clone, PartialEq)] struct VersionCheck { coordinates: Coordinates, ...
"Latest version matching {}: {}", style(req).cyan().bold(), style(latest).green().bold() ); } else { println!("No version matching {}", style(req).yellow().bold()); } } } Ok(()) } async fn run<R, C>( ...
random
[ { "content": "fn parse_version(version: &str) -> Result<VersionReq, Error> {\n\n VersionReq::parse(version).map_err(|e| Error::InvalidRange(version.into(), e))\n\n}\n\n\n\nstatic MAVEN_CENTRAL: &str = \"https://repo.maven.apache.org/maven2\";\n\n\n\nimpl Opts {\n\n pub(crate) fn new() -> Self {\n\n ...
Rust
ruma-serde/src/canonical_json/value.rs
unseddd/ruma
8fadffa31d436bbe2695abd0c02b7203720fe13a
use std::{ collections::BTreeMap, convert::{TryFrom, TryInto}, fmt, }; use js_int::Int; use serde::{de::Deserializer, ser::Serializer, Deserialize, Serialize}; use serde_json::{to_string as to_json_string, Value as JsonValue}; use super::Error; pub type Object = BTreeMap<String, CanonicalJsonValue>; #[d...
use std::{ collections::BTreeMap, convert::{TryFrom, TryInto}, fmt, }; use js_int::Int; use serde::{de::Deserializer, ser::Serializer, Deserialize, Serialize}; use serde_json::{to_string as to_json_string, Value as JsonValue}; use super::Error; pub type Object = BTreeMap<String, CanonicalJsonValue>; #[d...
} impl<'de> Deserialize<'de> for CanonicalJsonValue { #[inline] fn deserialize<D>(deserializer: D) -> Result<CanonicalJsonValue, D::Error> where D: Deserializer<'de>, { let val = JsonValue::deserialize(deserializer)?; val.try_into().map_err(serde::de::Error::custom) } } #[...
p; let mut map = serializer.serialize_map(Some(m.len()))?; for (k, v) in m { map.serialize_entry(k, v)?; } map.end() } } }
function_block-function_prefixed
[ { "content": "/// Fallible conversion from any value that impl's `Serialize` to a `CanonicalJsonValue`.\n\npub fn to_canonical_value<T: Serialize>(value: T) -> Result<value::CanonicalJsonValue, Error> {\n\n serde_json::to_value(value).map_err(Error::SerDe)?.try_into()\n\n}\n\n\n\n#[cfg(test)]\n\nmod tests {\...
Rust
hooks_game/src/net/transport/lag_loss.rs
leod/hooks
1b3a44e672c897fd0a6f1f245a7076cbcab8f9e7
use std::cmp::Ordering; use std::collections::BinaryHeap; use std::mem; use std::time::{Duration, Instant}; use net::transport::{self, ChannelId, Event, PacketFlag, PeerId}; #[derive(PartialEq, Eq)] enum Command { Send(PeerId, ChannelId, PacketFlag, Vec<u8>), Disconnect(PeerId, u32), } #[derive(PartialEq, ...
use std::cmp::Ordering; use std::collections::BinaryHeap; use std::mem; use std::time::{Duration, Instant}; use net::transport::{self, ChannelId, Event, PacketFlag, PeerId}; #[derive(PartialEq, Eq)] enum Command { Send(PeerId, ChannelId, PacketFlag, Vec<u8>), Disconnect(PeerId, u32), } #[derive(PartialEq, ...
onnect(peer_id, data) => { if self.host.is_peer(peer_id) { self.host.disconnect(peer_id, data)?; } else { debug!("Ignoring disconnect command to invalid peer_id {}", peer_id); } } } O...
e { debug!("Ignoring send command to invalid peer_id {}", peer_id); } } Command::Disc
function_block-random_span
[ { "content": "pub fn run(world: &World, event: &Event) -> Result<(), repl::Error> {\n\n setup(world);\n\n\n\n let (id_a, id_b) = {\n\n let meta = world.read::<entity::Meta>();\n\n\n\n // We assume here that every entity has an `entity::Meta` component, i.e. that it was\n\n // construc...
Rust
src/session.rs
genusistimelord/AxumSessions
31e36c6f13da9692c73d6952dce4a8b9eb74a1db
use crate::{AxumSessionData, AxumSessionID, AxumSessionStore}; use async_trait::async_trait; use axum_core::extract::{FromRequest, RequestParts}; use cookie::CookieJar; use http::{self, StatusCode}; use serde::{de::DeserializeOwned, Serialize}; use uuid::Uuid; #[derive(Debug, Clone)] pub struct AxumSession { pub(c...
use crate::{AxumSessionData, AxumSessionID, AxumSessionStore}; use async_trait::async_trait; use axum_core::extract::{FromRequest, RequestParts}; use cookie::CookieJar; use http::{self, StatusCode}; use serde::{de::DeserializeOwned, Serialize}; use uuid::Uuid; #[derive(Debug, Clone)] pub struct AxumSession { pub(c...
pub async fn remove(&self, key: &str) { self.tap(|sess| sess.data.remove(key)).await; } pub async fn clear_all(&self) { let store_rg = self.store.inner.read().await; if let Some(v) = store_rg.get(&self.id.0.to_...
e: impl Serialize) { let value = serde_json::to_string(&value).unwrap_or_else(|_| "".to_string()); self.tap(|sess| { if sess.data.get(key) != Some(&value) { sess.data.insert(key.to_string(), value); } Some(1) }) .await; }
function_block-function_prefixed
[ { "content": "fn set_cookies(jar: CookieJar, headers: &mut HeaderMap) {\n\n for cookie in jar.delta() {\n\n if let Ok(header_value) = cookie.encoded().to_string().parse() {\n\n headers.append(SET_COOKIE, header_value);\n\n }\n\n }\n\n}\n", "file_path": "src/service.rs", "r...
Rust
examples/application_changes/src/main.rs
vk496/sysrepo-rs
f2e425fd55a7e7e94a7c07eecb15644adab01a12
use std::env; use std::ffi::CStr; use std::thread; use std::time; use sysrepo::*; use utils::*; fn print_help(program: &str) { println!( "Usage: {} <module-to-subscribe> [<xpath-to-subscribe>]", program ); } fn print_change(oper: SrChangeOper, old_val: SrValue, new_val: SrValue) { let o...
use std::env; use std::ffi::CStr; use std::thread; use std::time; use sysrepo::*; use utils::*; fn print_help(program: &str) { println!( "Usage: {} <module-to-subscribe> [<xpath-to-subscribe>]", program ); } fn print_change(oper: SrChangeOper, old_val: SrValue, new_val: SrValue) { let o...
println!(""); println!(" ========== READING RUNNING CONFIG: =========="); println!(""); print_current_config(&mut sess, &mod_name); let f = |sess: SrSession, mod_name: &str, _path: Option<&str>, event: SrEvent, _request_id: u32| -> () ...
let mut sess = match sr.start_session(SrDatastore::Running) { Ok(sess) => sess, Err(_) => return false, };
assignment_statement
[ { "content": "fn run() -> bool {\n\n let args: Vec<String> = env::args().collect();\n\n let program = args[0].clone();\n\n\n\n if args.len() != 3 {\n\n print_help(&program);\n\n std::process::exit(1);\n\n }\n\n\n\n let mod_name = args[1].clone();\n\n let path = args[2].clone();\n...
Rust
multibase/src/base58.rs
ruhlio/rust-ipfs
ea5ab94e97f66f8fef7651f070105b2b4a0f548a
use num::{Zero, One}; use num::traits::ToPrimitive; use num::bigint::{BigUint, ToBigUint}; use base::{Base, MultibaseError, Result}; pub struct BitcoinBase58; pub struct FlickrBase58; const BITCOIN_ALPHABET: &'static [u8] = b"123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz"; const FLICKR_ALPHABET: &'stati...
use num::{Zero, One}; use num::traits::ToPrimitive; use num::bigint::{BigUint, ToBigUint}; use base::{Base, MultibaseError, Result}; pub struct BitcoinBase58; pub struct FlickrBase58; const BITCOIN_ALPHABET: &'static [u8] = b"123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz"; const FLICKR_ALPHABET: &'stati...
THE CROP".to_vec())); assert_eq!( BitcoinBase58::decode("OOOOOOOH YEAH!"), Err(MultibaseError::InvalidEncoding)); } }
3456789abcdefghijkmnopqrstuvwxyzABCDEFGHJKLMNPQRSTUVWXYZ"; lazy_static! { static ref RADIX: BigUint = 58.to_biguint().unwrap(); } impl Base for BitcoinBase58 { fn encode(data: &[u8]) -> String { encode(data, BITCOIN_ALPHABET) } fn decode(encoded: &str) -> Result<Vec<u8>> { decode(enco...
random
[ { "content": "pub fn file_descriptor_proto() -> &'static ::protobuf::descriptor::FileDescriptorProto {\n\n unsafe {\n\n file_descriptor_proto_lazy.get(|| {\n\n parse_descriptor_proto()\n\n })\n\n }\n\n}\n", "file_path": "merkledag/src/pb_merkledag.rs", "rank": 1, "scor...
Rust
src/clash/orb.rs
chamons/ArenaGS
0d3c8d4ebc818198b21a8c99dc853286cc16b7c2
use std::cmp; use specs::prelude::*; use super::*; use crate::atlas::prelude::*; pub fn create_orb(ecs: &mut World, invoker: Entity) -> Entity { let orb_component = ecs.read_storage::<OrbComponent>().grab(invoker).clone(); let attack_component = ecs.read_storage::<AttackComponent>().grab(invoker).clone(); ...
use std::cmp; use specs::prelude::*; use super::*; use crate::atlas::prelude::*; pub fn create_orb(ecs: &mut World, invoker: Entity) -> Entity { let orb_component = ecs.read_storage::<OrbComponent>().grab(invoker).clone(); let attack_component = ecs.read_storage::<AttackComponent>().grab(invoker).clone(); ...
; wait_for_animations(&mut ecs); assert_field_exists(&ecs, 2, 4); assert_field_exists(&ecs, 2, 5); assert_field_exists(&ecs, 2, 6); assert_field_count(&ecs, 5); } #[test] fn super_fast_orb_has_correct_fields() { let mut ecs = create_test_state().with_player(2...
begin_orb( &mut ecs, player, Point::init(2, 6), Damage::init(2, DamageElement::PHYSICAL), OrbKind::Feather, 2, 12, "TestOrb", )
call_expression
[ { "content": "pub fn set_health(ecs: &mut World, player: Entity, health: u32) {\n\n ecs.write_storage::<DefenseComponent>().grab_mut(player).defenses = Defenses::just_health(health);\n\n}\n\n\n", "file_path": "src/clash/test_helpers.rs", "rank": 1, "score": 462778.8148007465 }, { "content...
Rust
rate-common/src/clause.rs
krobelus/rate
58c19a71c44d30e352323ff501e516230e747208
use crate::memory::Offset; use serde_derive::{Deserialize, Serialize}; use static_assertions::const_assert; use std::{ convert::{TryFrom, TryInto}, fmt, io::{self, Write}, mem::{align_of, size_of}, ops::{Add, AddAssign, Sub, SubAssign}, }; use crate::literal::Literal; #[derive(Debug, PartialEq, ...
use crate::memory::Offset; use serde_derive::{Deserialize, Serialize}; use static_assertions::const_assert; use std::{ convert::{TryFrom, TryInto}, fmt, io::{self, Write}, mem::{align_of, size_of}, ops::{Add, AddAssign, Sub, SubAssign}, }; use crate::literal::Literal; #[derive(Debug, PartialEq, ...
pub fn unit_in_inference(clause: Clause) -> LRATDependency { LRATDependency(Tagged32::new(clause.index as u32)) } pub fn is_unit_in_inference(self) -> bool { !self.0.bit1() && !self.0.bit2() } pub fn forced_unit(clause: Clause) -> LRATDependency { LRATDependenc...
eIdentifierType) { self.index += value; } } impl Sub<ClauseIdentifierType> for Clause { type Output = Clause; fn sub(self, value: ClauseIdentifierType) -> Clause { Clause::new(self.index - value) } } impl SubAssign<ClauseIdentifierType> for Clause { fn sub_assign(&mut self, value: ...
random
[ { "content": "/// Write a key-value pair to stdout.\n\npub fn print_key_value(key: &str, value: impl Display) {\n\n requires!(key.len() < 35);\n\n comment!(\"{:<35} {:>15}\", format!(\"{}:\", key), value);\n\n}\n\n\n", "file_path": "rate-common/src/output.rs", "rank": 1, "score": 212826.101397...
Rust
core/lib/state/src/tests/operations/withdraw_nft.rs
smishraIOV/ri-aggregation
abcd90954335b6ee8513876de0118f567d979a32
use crate::tests::{AccountState::*, PlasmaTestBuilder}; use num::{BigUint, Zero}; use web3::types::H256; use zksync_crypto::params::MIN_NFT_TOKEN_ID; use zksync_types::{account::AccountUpdate, tx::WithdrawNFT, AccountId, TokenId}; #[test] fn success() { let fee_token_id = TokenId(0); let fee = BigUin...
use crate::tests::{AccountState::*, PlasmaTestBuilder}; use num::{BigUint, Zero}; use web3::types::H256; use zksync_crypto::params::MIN_NFT_TOKEN_ID; use zksync_types::{account::AccountUpdate, tx::WithdrawNFT, AccountId, TokenId}; #[test] fn success() { let fee_token_id = TokenId(0); let fee = BigUin...
fn invalid_account_id() { let fee_token_id = TokenId(0); let fee = BigUint::from(10u32); let mut tb = PlasmaTestBuilder::new(); let (creator_account_id, _, _) = tb.add_account(Unlocked); let (account_id, account, sk) = tb.add_account(Unlocked); let content_hash = H256::random(); l...
function_block-full_function
[ { "content": "#[test]\n\n#[ignore]\n\nfn test_withdraw_nft_with_zero_balance() {\n\n const ERR_MSG: &str = \"chunk number 6/execute_op/op_valid is true/enforce equal to one\";\n\n\n\n let accounts = vec![\n\n WitnessTestAccount::new(AccountId(1), 10u64), // nft creator account\n\n WitnessTes...
Rust
src/onramp/ws.rs
m0n0chr0m3/tremor-runtime
de785b5393388a614bc2e7c228dc0a7a98205636
use crate::onramp::prelude::*; use async_std::sync::Sender; use futures::{select, FutureExt, StreamExt}; use serde_yaml::Value; use tungstenite::protocol::Message; #[derive(Deserialize, Debug, Clone)] pub struct Config { pub port: u16, pub host: String, } pub struct Ws { pub config: Config, } ...
use crate::onramp::prelude::*; use async_std::sync::Sender; use futures::{select, FutureExt, StreamExt}; use serde_yaml::Value; use tungstenite::protocol::Message; #[derive(Deserialize, Debug, Clone)] pub struct Config { pub port: u16, pub host: String, } pub struct Ws { pub config: Config, } ...
impl Onramp for Ws { fn start( &mut self, codec: &str, preprocessors: &[String], metrics_reporter: RampReporter, ) -> Result<onramp::Addr> { let (tx, rx) = channel(1); let config = self.config.clone(); let codec = codec::lookup(&codec)?; ...
PipeHandlerResult::Terminate => return Ok(()), PipeHandlerResult::Normal => break, } } select! { msg = listener.accept().fuse() => if let Ok((stream, _socket)) = msg { let preprocessors = make_preprocessors(&preprocessors)?; task:...
function_block-function_prefix_line
[ { "content": "fn init_cli(config: &Config) -> std::result::Result<postgres::Client, postgres::Error> {\n\n let conn_str = format!(\n\n \"host={} user={} password={} port={} dbname={}\",\n\n config.host, config.user, config.password, config.port, config.dbname\n\n );\n\n let cli = Client::...
Rust
src/transport/ipc/send.rs
blabaere/scaproust
8a73fac28d3e78b3c641ddb87661f8a41ad7677e
use std::rc::Rc; use std::io; use byteorder::{ BigEndian, ByteOrder }; use core::Message; use transport::async::stub::*; use io_error::*; pub struct SendOperation { step: Option<SendOperationStep> } impl SendOperation { pub fn new(msg: Rc<Message>) -> SendOperation { SendOperation { s...
use std::rc::Rc; use std::io; use byteorder::{ BigEndian, ByteOrder }; use core::Message; use transport::async::stub::*; use io_error::*; pub struct SendOperation { step: Option<SendOperationStep> } impl SendOperation { pub fn new(msg: Rc<Message>) -> SendOperation { SendOperation { s...
assert_eq!(&expected_bytes, stream.deref()); } }
e>, mut written: usize) -> io::Result<(bool, SendOperationStep)> { let msg_len = msg.len() as u64; let mut buffer = [1u8; 9]; BigEndian::write_u64(&mut buffer[1..], msg_len); let sent = stream.write_buffer(&buffer, &mut written)?; if sent { Ok((true, SendOperationStep::ProtocolHdr(msg, 0))...
random
[ { "content": "fn write_transport_hdr(stream: &mut TcpStream, msg: Rc<Message>, mut written: usize) -> io::Result<(bool, SendOperationStep)> {\n\n let mut buffer = [0u8; 8];\n\n\n\n BigEndian::write_u64(&mut buffer, msg.len() as u64);\n\n\n\n let transport_hdr = if written == 0 {\n\n &buffer\n\n ...
Rust
core/src/metrics/registry.rs
akegaviar/graph-node
7d1208da76e7c3a16e4e141beed9b41c6691d327
use std::collections::HashMap; use std::sync::{Arc, RwLock}; use graph::prelude::{MetricsRegistry as MetricsRegistryTrait, *}; pub struct MetricsRegistry { logger: Logger, registry: Arc<Registry>, const_labels: HashMap<String, String>, register_errors: Box<Counter>, unregister_errors: Box<Counter>...
use std::collections::HashMap; use std::sync::{Arc, RwLock}; use graph::prelude::{MetricsRegistry as MetricsRegistryTrait, *}; pub struct MetricsRegistry { logger: Logger, registry: Arc<Registry>, const_labels: HashMap<String, String>, register_errors: Box<Counter>, unregister_errors: Box<Counter>...
} fn new_counter_vec( &self, name: String, help: String, const_labels: HashMap<String, String>, variable_labels: Vec<String>, ) -> Result<Box<CounterVec>, PrometheusError> { let labels: HashMap<String, String> = self .const_labels .cl...
if let Some(gauge) = maybe_gauge { Ok(gauge.clone()) } else { let gauge = *self.new_gauge(name.clone(), help, HashMap::new())?; self.global_gauges .write() .unwrap() .insert(name.clone(), gauge.clone()); Ok(gauge) ...
if_condition
[ { "content": "/// Generic helper function for retrying async operations with built-in logging.\n\n///\n\n/// To use this helper, do the following:\n\n///\n\n/// 1. Call this function with an operation name (used for logging) and a `Logger`.\n\n/// 2. Optional: Chain a call to `.when(...)` to set a custom retry ...
Rust
examples/simple_rtt_tag.rs
fronarn/dw3000
480630edbdc60123ec407a00fff2250b2b2fd015
#![no_main] #![no_std] use panic_rtt_target as _; use rtt_target::{rprintln, rtt_init_print}; use cortex_m_rt::entry; use stm32f1xx_hal::{ delay::Delay, pac, prelude::*, spi::{Mode, Phase, Polarity, Spi}, }; use embedded_hal::digital::v2::OutputPin; use dw3000::{ hl, Config, }; use nb::block; #[entry] fn main()...
#![no_main] #![no_std] use panic_rtt_target as _; use rtt_target::{rprintln, rtt_init_print}; use cortex_m_rt::entry; use stm32f1xx_hal::{ delay::Delay, pac, prelude::*, spi::{Mode, Phase, Polarity, Spi}, }; use embedded_hal::digital::v2::OutputPin; use dw3000::{ hl, Config, }; use nb::block; #[entry] fn main()...
dw3000 = receiving .finish_receiving() .expect("Failed to finish receiving"); /**************************** */ /******** TRANSMITTER ******* */ /**************************** */ let mut sending = dw3000 .send( &t2_tab, hl::SendTime::Now, Config::default(), ) .expect("Failed conf...
let t2_tab = [ ((t2 >> (8 * 4) ) & 0xFF ) as u8, ((t2 >> (8 * 3) ) & 0xFF ) as u8, ((t2 >> (8 * 2) ) & 0xFF ) as u8, ((t2 >> 8 ) & 0xFF ) as u8, (t2 & 0xFF ) as u8, ];
assignment_statement
[ { "content": "/// Initializes the SPI message header\n\n///\n\n/// Initializes the SPI message header for accessing a given register, writing\n\n/// the header directly into the provided buffer. Returns the length of the\n\n/// header that was written.\n\nfn init_header<R: Register>(write: bool, buffer: &mut [u...
Rust
src/background/persist.rs
AlphaModder/dbgm
c3c8646c476332a0a39974085678f91bf814cea7
use std::path::{Path, PathBuf}; use std::fs::File; use std::io::{BufReader, BufWriter}; use serde::*; use stable_vec::StableVec; use crate::sources::{self, OriginalResult}; use crate::background::*; impl BackgroundSet { pub fn load(path: impl AsRef<Path>) -> Result<(BackgroundSet, Vec<SetLoadWarning>), Error> { ...
use std::path::{Path, PathBuf}; use std::fs::File; use std::io::{BufReader, BufWriter}; use serde::*; use stable_vec::StableVec; use crate::sources::{self, OriginalResult}; use crate::background::*; impl BackgroundSet { pub fn load(path: impl AsRef<Path>) -> Result<(BackgroundSet, Vec<SetLoadWarning>), Error> { ...
} #[derive(Debug, Serialize, Deserialize)] struct SavedOriginalMeta { last_known_size: Option<(u32, u32)> } #[derive(Debug, Serialize, Deserialize)] pub struct SavedDesktopBackground { name: String, location: String, comments: String, key_data: serde_json::Value, flags: DesktopBackgroundFlags, ...
ush(SetLoadWarning::CorruptSource { source: saved_source, error }) } } (BackgroundSet { image_folder: Some(self.image_folder), name: Some(self.name), resolution: self.resolution, backgrounds, sour...
function_block-function_prefixed
[ { "content": "pub fn load_source_by_id(id: &str, data: serde_json::Value) -> Result<Box<dyn ErasedDesktopBackgroundSource>, SourceLoadError> {\n\n for loader in inventory::iter::<SourceLoader> {\n\n if loader.0 == id {\n\n let source = (loader.1)(data)?;\n\n return Ok(source)\n\n...
Rust
crates/lambda-platform/src/gfx/gpu.rs
C3NZ/lambda
0d14064a610833920801c7667532cfc1444dc915
use std::mem::size_of; use gfx_hal::{ adapter::{ Adapter, Gpu, }, command::Level, device::Device, format::{ ChannelType, Format, }, image::{ Access, Layout, }, memory::Dependencies, pass::{ Attachment, AttachmentLoadOp, AttachmentOps, AttachmentStoreOp, S...
use std::mem::size_of; use gfx_hal::{ adapter::{ Adapter, Gpu, }, command::Level, device::Device, format::{ ChannelType, Format, }, image::{ Access, Layout, }, memory::Dependencies, pass::{ Attachment, AttachmentLoadOp, AttachmentOps, AttachmentStoreOp, S...
pub fn destroy_access_fences( &mut self, submission_complete_fence: B::Fence, rendering_complete_semaphore: B::Semaphore, ) { unsafe { self .gpu .device .destroy_semaphore(rendering_complete_semaphore); self.gpu.device.destroy_fence(submission_complete_fence...
t_for_fence(fence, render_timeout_ns) .expect("The GPU ran out of memory or became detached."); device .reset_fence(fence) .expect("The Fence failed to reset."); self.command_pool.as_mut().unwrap().reset(false); } }
function_block-function_prefixed
[ { "content": "/// Create a Graphical Pipeline to use for rendering.\n\npub fn create_graphics_pipeline<'a, B: Backend>(\n\n primitive_assembler: PrimitiveAssemblerDesc<'a, B>,\n\n pipeline_layout: &'a B::PipelineLayout,\n\n render_pass: &'a B::RenderPass,\n\n fragment_shader: Option<EntryPoint<'a, B>>,\n\n)...
Rust
aorist_core/src/flow/prefect_python_based_flow.rs
scie-nz/aorist
ac1e31251af7d851c4491a310b417de880b79d09
use aorist_primitives::Dialect; use crate::flow::etl_flow::ETLFlow; use crate::flow::flow_builder::FlowBuilderBase; use crate::flow::python_based_flow::PythonBasedFlow; use crate::flow::python_based_flow_builder::PythonBasedFlowBuilder; use crate::python::{ NativePythonPreamble, PythonFlowBuilderInput, PythonImport...
use aorist_primitives::Dialect; use crate::flow::etl_flow::ETLFlow; use crate::flow::flow_builder::FlowBuilderBase; use crate::flow::python_based_flow::PythonBasedFlow; use crate::flow::python_based_flow_builder::PythonBasedFlowBuilder; use crate::python::{ NativePythonPreamble, PythonFlowBuilderInput, PythonImport...
}
Call::new_wrapped( AST::Attribute(Attribute::new_wrapped( self.flow_identifier.clone(), "run".into(), false, )), AVec::new(), ...
function_block-function_prefix_line
[ { "content": "pub fn extract_arg(arg: &PyAny) -> PyResult<AST> {\n\n if arg.is_none() {\n\n Ok(AST::None(None::new_wrapped()))\n\n } else if let Ok(extracted_val) = arg.extract::<&str>() {\n\n Ok(AST::StringLiteral(StringLiteral::new_wrapped(\n\n extracted_val.into(),\n\n ...
Rust
proxy/src/plugin.rs
zxk7516/lapce
93737031e7ce6dfafefd60df3503c039c2df90eb
use anyhow::Result; use home::home_dir; use serde::{Deserialize, Serialize}; use serde_json::json; use serde_json::Value; use std::collections::HashMap; use std::fs; use std::io::BufReader; use std::io::Read; use std::path::PathBuf; use std::process::Child; use std::process::Command; use std::process::Stdio; use std::s...
use anyhow::Result; use home::home_dir; use serde::{Deserialize, Serialize}; use serde_json::json; use serde_json::Value; use std::collections::HashMap; use std::fs; use std::io::BufReader; use std::io::Read; use std::path::PathBuf; use std::process::Child; use std::process::Command; use std::process::Stdio; use std::s...
fn load_manifest(path: &PathBuf) -> Result<PluginDescription> { let mut file = fs::File::open(&path)?; let mut contents = String::new(); file.read_to_string(&mut contents)?; let mut manifest: PluginDescription = toml::from_str(&contents)?; manifest.dir = Some(path.parent().unwrap()....
fn find_all_manifests() -> Vec<PathBuf> { let mut manifest_paths = Vec::new(); let home = home_dir().unwrap(); let path = home.join(".lapce").join("plugins"); path.read_dir().map(|dir| { dir.flat_map(|item| item.map(|p| p.path()).ok()) .map(|dir| dir.join("manifest.toml")) ...
function_block-full_function
[ { "content": "fn git_diff(workspace_path: &PathBuf) -> Option<Vec<String>> {\n\n let repo = Repository::open(workspace_path.to_str()?).ok()?;\n\n let mut diff_files = HashSet::new();\n\n let diff = repo.diff_index_to_workdir(None, None).ok()?;\n\n for delta in diff.deltas() {\n\n if let Some(...