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/vims/stat.rs
jeandudey/cc13x2-rs
215918099301ec75e9dfad531f5cf46e13077a39
#[doc = "Reader of register STAT"] pub type R = crate::R<u32, super::STAT>; #[doc = "Writer for register STAT"] pub type W = crate::W<u32, super::STAT>; #[doc = "Register STAT `reset()`'s with value 0"] impl crate::ResetValue for super::STAT { type Type = u32; #[inline(always)] fn reset_value() -> Self::Typ...
#[doc = "Reader of register STAT"] pub type R = crate::R<u32, super::STAT>; #[doc = "Writer for register STAT"] pub type W = crate::W<u32, super::STAT>; #[doc = "Register STAT `reset()`'s with value 0"] impl crate::ResetValue for super::STAT { type Type = u32; #[inline(always)] fn reset_value() -> Self::Typ...
#[doc = "Checks if the value of the field is `OFF`"] #[inline(always)] pub fn is_off(&self) -> bool { *self == MODE_A::OFF } #[doc = "Checks if the value of the field is `CACHE`"] #[inline(always)] pub fn is_cache(&self) -> bool { *self == MODE_A::CACHE } #[doc = "Ch...
self) -> crate::Variant<u8, MODE_A> { use crate::Variant::*; match self.bits { 3 => Val(MODE_A::OFF), 1 => Val(MODE_A::CACHE), 0 => Val(MODE_A::GPRAM), 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
rust/sbp/tests/auto_check_sbp_navigation_10.rs
adammacudzinski/libsbp
33f82210ff1262f8d6c180215277a0bb5eb3b65c
extern crate sbp; use sbp::messages::SBPMessage; mod common; #[allow(unused_imports)] use common::AlmostEq; #[test] fn test_auto_check_sbp_navigation_10() { { let payload: Vec<u8> = vec![ 85, 2, 1, 211, 136, 11, 128, 7, 40, 244, 122, 19, 244, 139, 2, 0, 0, 34, 152, ]; ...
extern crate sbp; use sbp::messages::SBPMessage; mod common; #[allow(unused_imports)] use common::AlmostEq; #[test] fn test_auto_check_sbp_navigation_10() { { let payload: Vec<u8> = vec![ 85, 2, 1, 211, 136, 11, 128, 7, 40, 244, 122, 19, 244, 139, 2, 0, 0, 34, 152, ]; ...
msg.ns_residual ); assert_eq!( msg.tow, 326827000, "incorrect value for tow, expected 326827000, is {}", msg.tow ); assert_eq!( msg.wn, 1920, "incorrect val...
function_block-function_prefixed
[ { "content": "#[test]\n\nfn test_read_string() {\n\n let v = b\"hi, imma string\";\n\n let mut slice = &v[..];\n\n\n\n let string: String = read_string(&mut slice).unwrap().into();\n\n assert_eq!(string, \"hi, imma string\".to_string());\n\n\n\n let string: String = read_string(&mut slice).unwrap...
Rust
crypto/stark/examples/group_sig/signature.rs
louiszhuang/OpenZKP
666f493b9ffc2812b734b9c6fd722d8d09025f48
use super::elliptic_helpers::*; #[cfg(feature = "prover")] use crate::TraceTable; use crate::{ constraint_system::{Provable, Verifiable}, constraints::Constraints, polynomial::DensePolynomial, rational_expression::RationalExpression::{self, *}, }; use elliptic_curve_crypto as ecc; use macros_decl::field...
use super::elliptic_helpers::*; #[cfg(feature = "prover")] use crate::TraceTable; use crate::{ constraint_system::{Provable, Verifiable}, constraints::Constraints, polynomial::DensePolynomial, rational_expression::RationalExpression::{self, *}, }; use elliptic_curve_crypto as ecc; use macros_decl::field...
; assert_eq!(first_expected, shifted_trace1.clone()); assert_eq!(second_expected, shifted_trace2.clone()); let mut final_check = add( &trace[(255, 3)], &trace[(255, 4)], &trace[(511, 3)], &trace[(511, 4)], ); assert_eq!(FieldElemen...
add( &trace[(511, 3)], &trace[(511, 4)], &SHIFT_POINT.0, &SHIFT_POINT.1, )
call_expression
[ { "content": "#[allow(clippy::too_many_lines)]\n\npub fn prove(constraints: &Constraints, trace: &TraceTable) -> Result<Proof> {\n\n // This hack allows us to avoid changing the interface to mut for the\n\n // claim polynomials but is ugly and should be removed.\n\n let original_constraints = constrain...
Rust
generate_reflection/src/property_patches.rs
dekkonot/rbx-dom
3fb4589fecffc49991e5168e61bf7e391e929d66
use std::borrow::Cow; use std::collections::HashMap; use anyhow::{anyhow, bail, Context}; use rbx_reflection::{ DataType, PropertyDescriptor, PropertyKind, ReflectionDatabase, Scriptability, }; use serde::Deserialize; const PATCHES: &[&str] = &[ include_str!("../patches/body-movers.yml"), include_str!("...
use std::borrow::Cow; use std::collections::HashMap; use anyhow::{anyhow, bail, Context}; use rbx_reflection::{ DataType, PropertyDescriptor, PropertyKind, ReflectionDatabase, Scriptability, }; use serde::Deserialize; const PATCHES: &[&str] = &[ include_str!("../patches/body-movers.yml"), include_str!("...
for (property_name, property_change) in class_changes { let existing_property = class .properties .get_mut(property_name.as_str()) .ok_or_else(|| { anyhow!( "Property {}.{} modif...
let class = database .classes .get_mut(class_name.as_str()) .ok_or_else(|| { anyhow!( "Class {} modified in patch file did not exist in database", class_name ) })?;
assignment_statement
[ { "content": "/// Use Roblox Studio to populate the reflection database with default values\n\n/// for as many properties as possible.\n\npub fn measure_default_properties(database: &mut ReflectionDatabase) -> anyhow::Result<()> {\n\n let fixture_place = generate_fixture_place(database);\n\n let output = ...
Rust
lib/rust/profiler/data/src/lib.rs
hubertp/enso
d3846578cceb4844f1f94d4e7ca51762bba3fada
#![allow(rustdoc::private_intra_doc_links)] #![feature(test)] #![deny(unconditional_recursion)] #![warn(missing_copy_implementations)] #![warn(missing_debug_implementations)] #![warn(missing_docs)] #![warn(trivial_casts)] #![warn(trivial_numeric_casts)] #![warn(unsafe_code)] #![warn(unused_import_braces)] use enso_p...
#![allow(rustdoc::private_intra_doc_links)] #![feature(test)] #![deny(unconditional_recursion)] #![warn(missing_copy_implementations)] #![warn(missing_debug_implementations)] #![warn(missing_docs)] #![warn(trivial_casts)] #![warn(trivial_numeric_casts)] #![warn(unsafe_code)] #![warn(unused_import_braces)] use enso_p...
} pub fn is_async(&self) -> bool { self.as_async().is_some() } } #[derive(Clone, Debug)] pub struct AsyncLifetime { pub created: Option<Mark>, pub active: Vec<Interval>, pub finished: bool, } impl AsyncLifetime { ...
match self { Lifetime::Async(lifetime) => Some(lifetime), Lifetime::NonAsync { .. } => None, }
if_condition
[ { "content": "/// Check if the given macro match node is an import declaration.\n\npub fn is_match_import(ast: &known::Match) -> bool {\n\n let segment = &ast.segs.head;\n\n let keyword = crate::identifier::name(&segment.head);\n\n if keyword.contains_if(|str| *str == UNQUALIFIED_IMPORT_KEYWORD) {\n\n ...
Rust
unwind-sys/src/aarch64.rs
GreenBeard/rstack
985e4c354142f2cc24b84d75a2c382b3f82426d0
use libc::ucontext_t; use crate::*; cfg_if! { if #[cfg(pre14)] { pub const UNW_TDEP_CURSOR_LEN: c_int = 4096; } else if #[cfg(pre13)] { pub const UNW_TDEP_CURSOR_LEN: c_int = 512; } else { pub const UNW_TDEP_CURSOR_LEN: c_int = 250; } } pub type unw_word_t = u64; pub type unw_...
use libc::ucontext_t; use crate::*; cfg_if! { if #[cfg(pre14)] { pub const UNW_TDEP_CURSOR_LEN: c_int = 4096; } else if #[cfg(pre13)] { pub const UNW_TDEP_CURSOR_LEN: c_int = 512; } else { pub const UNW_TDEP_CURSOR_LEN: c_int = 250; } } pub type unw_word_t = u64; pub type unw_...
"stp x20, x21, [x0, #160]", "stp x22, x23, [x0, #176]", "stp x24, x25, [x0, #192]", "stp x26, x27, [x0, #208]", "stp x28, x29, [x0, #224]", "str x30, [x0, #240]", "mov x1, sp", "stp x1, x30, [x0, #248]", in("x0") (*unw_ctx)....
t = 30; pub const UNW_AARCH64_SP: c_int = 31; pub const UNW_AARCH64_PC: c_int = 32; pub const UNW_AARCH64_PSTATE: c_int = 33; pub const UNW_AARCH64_V0: c_int = 64; pub const UNW_AARCH64_V1: c_int = 65; pub const UNW_AARCH64_V2: c_int = 66; pub const UNW_AARCH64_V3: c_int = 67; pub const UNW_AARCH64_V4: c_int = 68; pub ...
random
[ { "content": "struct TracedThread {\n\n id: u32,\n\n // True if TraceOptions::ptrace_attach was true (default value)\n\n // It means that Drop should perform detach\n\n should_detach: bool,\n\n}\n\n\n\nimpl Drop for TracedThread {\n\n fn drop(&mut self) {\n\n if self.should_detach {\n\n ...
Rust
src/graphics/lib/compute/surpass/src/rasterizer/pixel_segment.rs
fabio-d/fuchsia-stardock
e57f5d1cf015fe2294fc2a5aea704842294318d2
use std::{cmp::Ordering, fmt, mem}; use crate::{MAX_HEIGHT_SHIFT, MAX_WIDTH_SHIFT, PIXEL_WIDTH, TILE_HEIGHT_SHIFT, TILE_WIDTH_SHIFT}; const TILE_BIAS: i16 = 1; pub const BIT_FIELD_LENS: [usize; 7] = { const fn log2_round_up(n: usize) -> usize { if n.count_ones() == 1 { n.trailing_zeros() as...
use std::{cmp::Ordering, fmt, mem}; use crate::{MAX_HEIGHT_SHIFT, MAX_WIDTH_SHIFT, PIXEL_WIDTH, TILE_HEIGHT_SHIFT, TILE_WIDTH_SHIFT}; const TILE_BIAS: i16 = 1; pub const BIT_FIELD_LENS: [usize; 7] = { const fn log2_round_up(n: usize) -> usize { if n.count_ones() == 1 { n.trailing_zeros() as...
16, pub tile_y: i16, pub local_x: u8, pub local_y: u8, pub double_area: i16, pub cover: i8, } impl From<PixelSegment> for PixelSegmentUnpacked { fn from(value: PixelSegment) -> Self { PixelSegmentUnpacked { layer_id: value.layer_id(), tile_x: value.tile_x(), ...
al <<= BIT_FIELD_LENS[6]; val |= mask_for(6) & cover as u64; Self(val) } #[inline] pub fn layer_id(self) -> u32 { extract!(self.0, 2) as u32 } #[inline] pub fn tile_x(self) -> i16 { extract!(self.0, 1) as i16 - TILE_BIAS } #[inline] pub fn tile_y(s...
random
[]
Rust
bjdatasets/src/treedataset.rs
BruJu/Portable-Reasoning-in-Web-Assembly
c0312a1f25d9a6a14ca9462a5eccbc5af0634719
use crate::RcQuad; use identifier_forest::IndexingForest4; use identifier_forest::IndexingForest4Filter; use sophia::dataset::MutableDataset; use sophia::dataset::DQuad; use sophia::dataset::DQuadSource; use sophia::dataset::Dataset; use sophia::dataset::DResult; use sophia::dataset::MDResult; use sophia::graph::inmem...
use crate::RcQuad; use identifier_forest::IndexingForest4; use identifier_forest::IndexingForest4Filter; use sophia::dataset::MutableDataset; use sophia::dataset::DQuad; use sophia::dataset::DQuadSource; use sophia::dataset::Dataset; use sophia::dataset::DResult; use sophia::dataset::MDResult; use sophia::graph::inmem...
fn quads_with_p<'s, TP>(&'s self, p: &'s Term<TP>) -> DQuadSource<'s, Self> where TP: TermData { let p = self.term_id_map.get_index(&p.into()); if p.is_none() { return Box::new(empty()); } else { self.quads_with_opt_spog([None, p, None, None]) } } ...
fn quads_with_s<'s, TS>(&'s self, s: &'s Term<TS>) -> DQuadSource<'s, Self> where TS: TermData { let s = self.term_id_map.get_index(&s.into()); if s.is_none() { return Box::new(empty()); } else { self.quads_with_opt_spog([s, None, None, None]) } }
function_block-full_function
[ { "content": "type FullIndexDatasetIntoArrayWrapper = VecOrDatasetWrapper<FullIndexDataset>;\n\n\n\nwasm_bindgen_wrappeddataset!(TreeDatasetIntoArrayWrapper, \"TreeDatasetToA\");\n\nwasm_bindgen_wrappeddataset!(FastDatasetIntoArrayWrapper, \"FastDatasetToA\");\n\nwasm_bindgen_wrappeddataset!(LightDatasetIntoArr...
Rust
src/task.rs
sagebind/threadfin
ad8556db9275781445c3db7930523b46232ec168
use std::{ any::Any, fmt, future::Future, panic::{catch_unwind, resume_unwind, AssertUnwindSafe}, pin::Pin, sync::{Arc, Mutex}, task::{Context, Poll, Waker}, thread, time::{Duration, Instant}, }; pub struct Task<T> { inner: Arc<Mutex<Inner<T>>>, } struct Inner<T> { result...
use std::{ any::Any, fmt, future::Future, panic::{catch_unwind, resume_unwind, AssertUnwindSafe}, pin::Pin, sync::{Arc, Mutex}, task::{Context, Poll, Waker}, thread, time::{Duration, Instant}, }; pub struct Task<T> { inner: Arc<Mutex<Inner<T>>>, } struct Inner<T> { result...
} } fn into_any(self: Box<Self>) -> Box<dyn Any> { self } }
result } else { inner.waker = Some(crate::wakers::current_thread_waker()); drop(inner); loop { if let Some(timeout) = deadline.checked_duration_since(Instant::now()) { thread::park_timeout(timeout); ...
random
[ { "content": "/// Get a shared reference to a common thread pool for the entire process.\n\n///\n\n/// # Examples\n\n///\n\n/// ```\n\n/// let result = threadfin::common().execute(|| 2 + 2).join();\n\n///\n\n/// assert_eq!(result, 4);\n\n/// ```\n\npub fn common() -> &'static ThreadPool {\n\n COMMON.get_or_i...
Rust
libchao/src/parser.rs
lukad/chao
b37956b895988c0236377c092b860b9aa0056e2e
use std::i64; use combine::char::{char as c, digit, hex_digit, letter, spaces, string}; use combine::error::Consumed; use combine::{ any, attempt, between, choice, eof, many, many1, one_of, optional, parser, satisfy_map, ParseError, Parser, Stream, }; use expr::Expr::{self, *}; fn int<I>() -> impl Parser<Inp...
use std::i64; use combine::char::{char as c, digit, hex_digit, letter, spaces, string}; use combine::error::Consumed; use combine::{ any, attempt, between, choice, eof, many, many1, one_of, optional, parser, satisfy_map, ParseError, Parser, Stream, }; use expr::Expr::{self, *}; fn int<I>() -> impl Parser<Inp...
fn boolean<I>() -> impl Parser<Input = I, Output = Expr> where I: Stream<Item = char>, I::Error: ParseError<I::Item, I::Range, I::Position>, { let t = || string("true").map(|_| Bool(true)); let f = || string("false").map(|_| Bool(false)); (attempt(choice((t(), f()))), spaces()).map(|(b, _)| b) } ...
t = Expr> where I: Stream<Item = char>, I::Error: ParseError<I::Item, I::Range, I::Position>, { attempt((many1(digit()), string("."), many1(digit()))) .skip(spaces()) .map(|(a, b, c): (String, &str, String)| { Float([a, b.to_string(), c].join("").parse::<f64>().unwrap()) ...
function_block-function_prefixed
[ { "content": "#[test]\n\nfn parses_strings() {\n\n assert_parse!(r#\"\"\"\"#, Str(\"\".to_string()));\n\n assert_parse!(r#\"\"\\\"\"\"#, Str(\"\\\"\".to_string()));\n\n assert_parse!(r#\"\"\\n\"\"#, Str(\"\\n\".to_string()));\n\n assert_parse!(r#\"\"\\r\"\"#, Str(\"\\r\".to_string()));\n\n assert...
Rust
src/parser/src/types.rs
AestheticIntegration/batsmt
b1eac8ce809bfee345bd8f4eb6aea2531db37ac7
use { std::{fmt::{self,Debug}, rc::Rc}, batsmt_pretty as pp, }; pub use self::pp::Pretty; pub type Atom = Rc<str>; pub trait SortBuilder { type Sort : Clone + Debug; fn get_bool(&self) -> Self::Sort; fn declare_sort(&mut self, name: Atom, arity: u8) -> Self::Sort; } #[derive(Copy,Debug,Cl...
use { std::{fmt::{self,Debug}, rc::Rc}, batsmt_pretty as pp, }; pub use self::pp::Pretty; pub type Atom = Rc<str>; pub trait SortBuilder { type Sort : Clone + Debug; fn get_bool(&self) -> Self::Sort; fn declare_sort(&mut self, name: Atom, arity: u8) -> Self::Sort; } #[derive(Copy,Debug,Cl...
} } pub fn pp_stmt<T,S,FT,FS>(st: &Statement<T,S>, mut ft: FT, mut fs: FS, ctx: &mut pp::Ctx) where FT: FnMut(&T,&mut pp::Ctx), FS: FnMut(&S,&mut pp::Ctx) { match st { &Statement::SetInfo(ref a, ref b) => { ctx.sexp(|ctx| { ctx.str("set-info").space().pp(&a).s...
match self { SetInfo(a,b) => SetInfo(a,b), SetLogic(a) => SetLogic(a), DeclareSort(s,n) => DeclareSort(s,n), DeclareFun(s,args,ret) => { let args = args.into_iter().map(|s| fs(s)).collect(); let ret = fs(ret); DeclareFun(s,a...
if_condition
[ { "content": "/// AST-pretty printer, using `f` to print symbols.\n\npub fn pp_ast<M, F>(m: &M, t: &M::AST, f: &mut F, ctx: &mut pp::Ctx)\n\n where M: Manager,\n\n F: for<'a> FnMut(&'a M::SymView, &mut pp::Ctx)\n\n{\n\n match m.view(t) {\n\n View::Const(s) => {\n\n f(&s, ctx);\n...
Rust
src/main.rs
zezic/snaker
291bcc6803b87a910ce130653dc7a4dd99f4d840
use std::{ collections::VecDeque, io::{stdout, Write}, time::{Duration, Instant}, }; use futures::{future::FutureExt, select, StreamExt}; use futures_timer::Delay; use crossterm::{ cursor, event::{Event, EventStream, KeyCode}, execute, queue, terminal }; enum Direction { Up, Right...
use std::{ collections::VecDeque, io::{stdout, Write}, time::{Duration, Instant}, }; use futures::{future::FutureExt, select, StreamExt}; use futures_timer::Delay; use crossterm::{ cursor, event::{Event, EventStream, KeyCode}, execute, queue, terminal }; enum Direction { Up, Right...
} fn get_next_point(&self) -> Option<Point> { let head = self.body.front().unwrap(); let (dx, dy) = self.direction.get_delta(); if head.x == 0 && dx < 0 { return None } if head.y == 0 && dy < 0 { return None } return Some(Point { x: (head.x as i16 + dx) as...
match self.get_next_point() { Some(point) => { let _removed_point = self.body.pop_back().unwrap(); self.body.push_front(point); Ok(()) }, None => Err(OutOfBounds) }
if_condition
[]
Rust
frontend/src/main.rs
tiehuis/tetrs
ba02816956decffad4fc1d8b8bd29ac501c61e0f
#![feature(collections, enumset)] extern crate collections; use collections::enum_set::CLike; extern crate sdl2; extern crate sdl2_ttf; extern crate env_logger; extern crate tetrs; use sdl2::event::Event; use sdl2::keyboard::Scancode; use sdl2::rect::Rect; use sdl2::pixels::Color; use tetrs::import::*; use tetrs::co...
#![feature(collections, enumset)] extern crate collections; use collections::enum_set::CLike; extern crate sdl2; extern crate sdl2_ttf; extern crate env_logger; extern crate tetrs; use sdl2::event::Event; use sdl2::keyboard::Scancode; use sdl2::rect::Rect; use sdl2::pixels::Color; use tetrs::import::*; use tetrs::co...
; let mut renderer = match window.renderer().build() { Ok(renderer) => renderer, Err(err) => panic!("failed to create renderer: {}", err) }; let mut events = ctx.event_pump().unwrap(); let font = ttf_ctx.load_font(Path::new("res/font/font.ttf"), 128).unwrap(); let options = E...
match video_ctx.window("tetrs", 640, 480).position_centered().opengl().build() { Ok(window) => window, Err(err) => panic!("failed to create window: {}", err) }
if_condition
[ { "content": "/// Factory function for constructing rotation systems from name.\n\n///\n\n/// This is usually more convenient than explicit instantiation, as rotation\n\n/// systems are often stored as a name only.\n\n///\n\n/// # Names\n\n/// - `srs`\n\n/// - `empty`\n\n/// - `simple`\n\n/// - `dtet`\n\n//...
Rust
src/run/parser/wsplit.rs
AntyMew/livesplit-core
b59a45ddd85c914121d279df38ad5b0e581bd512
use std::io::{self, BufRead}; use std::result::Result as StdResult; use std::num::{ParseFloatError, ParseIntError}; use {Image, RealTime, Run, Segment, TimeSpan}; quick_error! { #[derive(Debug)] pub enum Error { ExpectedSegmentName {} ExpectedOldTime {} ...
use std::io::{self, BufRead}; use std::result::Result as StdResult; use std::num::{ParseFloatError, ParseIntError}; use {Image, RealTime, Run, Segment, TimeSpan}; quick_error! { #[derive(Debug)] pub enum Error { ExpectedSegmentName {} ExpectedOldTime {} ...
t_offset(TimeSpan::from_milliseconds(-offset.parse::<f64>()?)); } } else if line.starts_with("Size=") { } else if line.starts_with("Icons=") { if load_icons { let icons = &line["Icons=".len()..]; icons_list....
run.set_attempt_count(line["Attempts=".len()..].parse()?); } else if line.starts_with("Offset=") { let offset = &line["Offset=".len()..]; if !offset.is_empty() { run.se
function_block-random_span
[ { "content": "/// Attempts to parse a SplitterZ splits file. In addition to the source to\n\n/// parse, you need to specify if additional files for the icons should be\n\n/// loaded from the file system. If you are using livesplit-core in a\n\n/// server-like environment, set this to `false`. Only client-side a...
Rust
src/launch/mod.rs
tfanelli-rh/sev
e0e17aac9249b00b0cb3e24a2780ca814d229a11
#[cfg(target_os = "linux")] pub mod linux; pub mod sev; pub mod snp; use super::*; use bitflags::bitflags; use serde::{Deserialize, Serialize}; use crate::kvm::types::*; bitflags! { #[derive(Default, Deserialize, Serialize)] pub struct PolicyFlags: u16 { const NO_DEBUG = 0b000...
#[cfg(target_os = "linux")] pub mod linux; pub mod sev; pub mod snp; use super::*; use bitflags::bitflags; use serde::{Deserialize, Serialize}; use crate::kvm::types::*; bitflags! { #[derive(Default, Deserialize, Serialize)] pub struct PolicyFlags: u16 { const NO_DEBUG = 0b000...
y, ma_en: ma_uaddr.is_some(), imi_en, gosvw, } } } #[derive(Copy, Clone, Debug, PartialEq, Eq, Deserialize, Serialize)] pub struct SnpUpdate<'a> { pub start_gfn: u64, pub uaddr: &'a [u8], pub imi_page: bool, pub page_type: SnpPageTy...
uaddr: Option<&'a [u8]>, policy: SnpPolicy, imi_en: bool, gosvw: [u8; 16], ) -> Self { Self { ma_uaddr, polic
function_block-random_span
[]
Rust
src/ctrnn.rs
shnidi/rustneat
5f6e28b7172005e04c423b46de1650fbcea6a027
use rulinalg::matrix::{BaseMatrix, BaseMatrixMut, Matrix}; #[cfg(feature = "ctrnn_telemetry")] use rusty_dashed; #[cfg(feature = "ctrnn_telemetry")] use serde_json; #[allow(missing_docs)] #[derive(Debug)] pub struct CtrnnNeuralNetwork<'a> { pub y: &'a [f64], pub tau: &'a [f64], pub wji: &'a [f64], ...
use rulinalg::matrix::{BaseMatrix, BaseMatrixMut, Matrix}; #[cfg(feature = "ctrnn_telemetry")] use rusty_dashed; #[cfg(feature = "ctrnn_telemetry")] use serde_json; #[allow(missing_docs)] #[derive(Debug)] pub struct CtrnnNeuralNetwork<'a> { pub y: &'a [f64], pub tau: &'a [f64], pub wji: &'a [f64], ...
let ctrnn = Ctrnn::default(); assert_delta_vector!( ctrnn.activate_nn(1.0, 0.1, &nn), vec![ 0.010829986965909134, 0.1324987329841768, 0.06644643156742948 ], 0.00000000000000000001 ); asser...
let nn = CtrnnNeuralNetwork { y: &gamma, tau: &tau, wji: &wji, theta: &theta, i: &i, };
assignment_statement
[ { "content": "fn activate_step_size_test(step_size: f64) {\n\n Ctrnn::default().activate_nn(\n\n 15.0 * step_size,\n\n step_size,\n\n &CtrnnNeuralNetwork {\n\n y: &vec![1.0],\n\n tau: &vec![1.0],\n\n wji: &vec![0.0],\n\n theta: &vec![0.0],\n\n ...
Rust
tools/ipcheck/impls/rust_new/main.rs
ben0x539/libs-team
6766d87a4cf317f79231f165c6dac14a6c4081be
#![feature(ip)] use serde_json::json; use std::net::{IpAddr, Ipv4Addr, Ipv6Addr, Ipv6MulticastScope}; fn main() { let input = std::env::args() .skip(1) .next() .expect("missing input argument"); let addr: IpAddr = input.parse().expect("failed to parse IP"); let data = json!({ ...
#![feature(ip)] use serde_json::json; use std::net::{IpAddr, Ipv4Addr, Ipv6Addr, Ipv6MulticastScope}; fn main() { let input = std::env::args() .skip(1) .next() .expect("missing input argument"); let addr: IpAddr = input.parse().expect("failed to parse IP"); let data = json!({ ...
ticast() { match addr.segments()[0] & 0x000f { 0 | 15 | 1 | 2 | 3 | 4 | 5 | 8 | 14 => false, _ => true, } } else { false }, }, }); fn to_ipv4_new(addr: &Ipv6Addr) -> Option<Ipv4Addr> { ...
(match addr.multicast_scope() { Some(Ipv6MulticastScope::Global) => true, None => addr.is_unicast_global(), _ => false, }) || if let Some(v4_addr) = to_ipv4_new(&addr) { v4_addr.is_global() } else { false }, }, ...
random
[ { "content": "fn main() {\n\n let results = csv::ReaderBuilder::new()\n\n .from_path(\"poisoning-survey.csv\")\n\n .expect(\"failed to create csv reader over results file\")\n\n .deserialize()\n\n .map(|row| row.expect(\"failed to deserialize a row\"))\n\n .collect::<Vec<Re...
Rust
src/bitmap/sbix.rs
davelab6/allsorts
02c5f60463505058ede364acff79fdfd6b724aac
#![deny(missing_docs)] use std::convert::TryFrom; use super::{ BitDepth, Bitmap, BitmapGlyph, EncapsulatedBitmap, EncapsulatedFormat, Metrics, OriginOffset, }; use crate::binary::read::{CheckIndex, ReadArray, ReadBinaryDep, ReadCtxt, ReadScope}; use crate::binary::U32Be; use crate::error::ParseError; use crate::t...
#![deny(missing_docs)] use std::convert::TryFrom; use super::{ BitDepth, Bitmap, BitmapGlyph, EncapsulatedBitmap, EncapsulatedFormat, Metrics, OriginOffset, }; use crate::binary::read::{CheckIndex, ReadArray, ReadBinaryDep, ReadCtxt, ReadScope}; use crate::binary::U32Be; use crate::error::ParseError; use crate::t...
{ bitmap: Bitmap::Encapsulated(encapsulated), metrics: Metrics::HmtxVmtx(OriginOffset::from(glyph)), ppem_x: Some(strike.ppem), ppem_y: Some(strike.ppem), } } } impl From<u32> for EncapsulatedFormat { fn from(tag: u32) -> Self { match tag { ...
fsets.get_item(glyph_index + 1))?; Ok((offset, end)) } fn contains_glyph(&self, glyph_index: u16) -> bool { self.glyph_offset_end(glyph_index) .map(|(offset, end)| end.checked_sub(offset).unwrap_or(0) > 0) .unwrap_or(false) } } impl<'a> From<(&SbixStrike<'a>, &SbixG...
random
[ { "content": "/// Calculate a checksum of `data` according to the OpenType table checksum algorithm\n\n///\n\n/// https://docs.microsoft.com/en-us/typography/opentype/spec/otff#calculating-checksums\n\npub fn table_checksum(data: &[u8]) -> Result<Wrapping<u32>, ParseError> {\n\n assert_eq!(data.len() % 4, 0,...
Rust
src/structs/embedded_object_properties.rs
cstkingkey/umya-spreadsheet
49dd270b05bb99744101fe31931d89250b371f1a
use super::BooleanValue; use super::ObjectAnchor; use super::StringValue; use super::UInt32Value; use quick_xml::events::{BytesStart, Event}; use quick_xml::Reader; use quick_xml::Writer; use reader::driver::*; use std::io::Cursor; use structs::raw::RawRelationships; use structs::MediaObject; use writer::driver::*; #[...
use super::BooleanValue; use super::ObjectAnchor; use super::StringValue; use super::UInt32Value; use quick_xml::events::{BytesStart, Event}; use quick_xml::Reader; use quick_xml::Writer; use reader::driver::*; use std::io::Cursor; use structs::raw::RawRelationships; use structs::MediaObject; use writer::driver::*; #[...
pub(crate) fn write_to(&self, writer: &mut Writer<Cursor<Vec<u8>>>, r_id: &usize) { let mut attributes: Vec<(&str, &str)> = Vec::new(); if self.default_size.has_value() { attributes.push(("defaultSize", self.default_size.get_value_string())); } if self.auto_pic...
relationships: &RawRelationships, ) { let r_id = get_attribute(e, b"r:id").unwrap(); let attached_file = relationships.get_relationship_by_rid(&r_id).get_raw_file(); self.get_image_mut() .set_image_name(attached_file.get_file_name()); self.get_image_mut() .se...
function_block-function_prefix_line
[ { "content": "fn set_value(theme: &mut Theme, tag_name: &str, value: &str) {\n\n if tag_name == \"lt1\" {\n\n let _ = mem::replace(&mut theme.get_color_map_mut()[0], value.into());\n\n } else if tag_name == \"dk1\" {\n\n let _ = mem::replace(&mut theme.get_color_map_mut()[1], value.into());\...
Rust
src/bin/kp.rs
busstoptaktik/geodesy
2718c094001b0a2168deb4fbaaa09c4ab9f78a7c
use std::path::PathBuf; use structopt::StructOpt; #[derive(StructOpt, Debug)] #[structopt(name = "kp")] struct Opt { #[structopt(short, long = "inv")] inverse: bool, #[structopt(short, long)] debug: bool, #[structopt(short, long)] roundtrip: bool, ...
use std::path::PathBuf; use structopt::StructOpt; #[derive(StructOpt, Debug)] #[structopt(name = "kp")] struct Opt { #[structopt(short, long = "inv")] inverse: bool, #[structopt(short, long)] debug: bool, #[structopt(short, long)] roundtrip: bool, ...
3 { return input.hypot2(&result); } else { return input.hypot3(&result); } if dim < 2 { return input.default_ellps_dist(&result); } input.default_ellps_3d_dist(&result) }
function_block-function_prefixed
[ { "content": "/// Handle instantiation of built-in operators.\n\nfn builtins(ctx: &mut Context, args: &mut OperatorArgs) -> Result<Operator, GeodesyError> {\n\n // Pipelines are not characterized by the name \"pipeline\", but simply by containing steps.\n\n if let Ok(steps) = args.numeric_value(\"_nsteps\...
Rust
src/algorithms/connected_components.rs
amazing-hash/luka
327a3d5cff57b2ae7fa76900489856086d4c9928
use crate::{Graph, Vertex, utils}; use crate::algorithms::{VisitorDFS, dfs_with_visitor, VisitorBFS, bfs_with_visitor, VisitorDFSAction, VisitorBFSAction}; use crate::error::GraphError; use crate::algorithms::definitions::ConnectedComponents; struct CustomVisitor { orders: Vec<usize> } impl <T> VisitorBFS<T> for C...
use crate::{Graph, Vertex, utils}; use crate::algorithms::{VisitorDFS, dfs_with_visitor, VisitorBFS, bfs_with_visitor, VisitorDFSAction, VisitorBFSAction}; use crate::error::GraphError; use crate::algorithms::definitions::ConnectedComponents; struct CustomVisitor { orders: Vec<usize> } impl <T> VisitorBFS<T> for C...
} Ok(components) } struct CustomVisitorFirst { orders: Vec<usize>, visited: Vec<bool> } impl <T> VisitorDFS<T> for CustomVisitorFirst { fn exit_from_vertex_event(&mut self, vertex: &Vertex<T>) -> Result<VisitorDFSAction, GraphError> { if !self.visited[vertex.id()] { self.visite...
if !visited[from.id()] { let mut visitor = CustomVisitor{ orders: vec![] }; bfs_with_visitor(graph, from, &mut visitor)?; let mut vec = vec![]; for vertex in visitor.orders { vec.push(&graph.adj[vertex]); visited[vertex] = true; ...
if_condition
[]
Rust
tezos/context/src/persistent/file.rs
tezedge/tezedge
b8e20d9886ad8b6876ad62375bacf1f6b7999e3b
use std::{ convert::TryInto, fs::OpenOptions, io::{self, Seek, SeekFrom, Write}, os::unix::prelude::OpenOptionsExt, path::{Path, PathBuf}, sync::{Arc, Mutex}, }; use serde::{Deserialize, Serialize}; use thiserror::Error; use crate::serialize::persistent::AbsoluteOffset; const CURRENT_VERSIO...
use std::{ convert::TryInto, fs::OpenOptions, io::{self, Seek, SeekFrom, Write}, os::unix::prelude::OpenOptionsExt, path::{Path, PathBuf}, sync::{Arc, Mutex}, }; use serde::{Deserialize, Serialize}; use thiserror::Error; use crate::serialize::persistent::AbsoluteOffset; const CURRENT_VERSIO...
t }; if offset == 0 { file.write_header()?; } else { file.check_header()?; } Ok(file) } fn write_header(&mut self) -> Result<(), io::Error> { let mut bytes = Vec::with_capacity(16); let version_bytes = CURRENT_VERSION.to_le_bytes(); ...
in(file_type.get_path()))?; let offset = file.seek(SeekFrom::End(0))?; let mut file = Self { file, offse
function_block-random_span
[ { "content": "pub fn string(data: impl AsRef<str>, out: &mut Vec<u8>) -> BinResult {\n\n put_size(data.as_ref().len(), out)?;\n\n put_bytes(data.as_ref().as_bytes(), out);\n\n Ok(())\n\n}\n\n\n", "file_path": "tezos/encoding/src/enc.rs", "rank": 0, "score": 453088.7827805448 }, { "c...
Rust
src/micro_component.rs
delight-aug/Relm4
716ab15af6f6e25d35a5f4a213dcabb735561982
use gtk::glib::{self, Sender}; use gtk::prelude::{IsA, WidgetExt}; use std::{ cell::{BorrowError, BorrowMutError, Ref, RefCell, RefMut}, fmt::{Debug, Display}, rc::Rc, }; use crate::WidgetPlus; #[derive(Debug)] pub enum MicroComponentError { Borrow(BorrowError), BorrowMut(BorrowMutError...
use gtk::glib::{self, Sender}; use gtk::prelude::{IsA, WidgetExt}; use std::{ cell::{BorrowError, BorrowMutError, Ref, RefCell, RefMut}, fmt::{Debug, Display}, rc::Rc, }; use crate::WidgetPlus; #[derive(Debug)] pub enum MicroComponentError { Borrow(BorrowError), BorrowMut(BorrowMutError...
ot_widget.parent() { parent.try_remove(&self.root_widget) } else { false } } } pub trait MicroModel { type Msg: 'static; type Widgets: MicroWidgets<Self> + Debug; type Data; fn update(&mut self, msg: Self::Msg, data: &Sel...
model) = handler_model.try_borrow_mut() { model.update(msg, &data, sender.clone()); if let Ok(ref mut widgets) = handler_widgets.try_borrow_mut() { widgets.view(model, sender.clone()); } else { log::warn!("Could...
random
[]
Rust
crates/cargo-crate-api/src/main.rs
epage/cargo-crate-api
0c3fecf9daa3c772a8a464e0a482c9d1d6192173
use std::io::Write; use proc_exit::WithCodeResultExt; use structopt::StructOpt; mod args; mod log; mod report; fn main() { human_panic::setup_panic!(); let result = run(); proc_exit::exit(result); } fn run() -> proc_exit::ExitResult { let args::Command::CrateApi(args) = match args::Command::fro...
use std::io::Write; use proc_exit::WithCodeResultExt; use structopt::StructOpt; mod args; mod log; mod report; fn main() { human_panic::setup_panic!(); let result = run(); proc_exit::exit(result); } fn run() -> proc_exit::ExitResult { let args::Command::CrateApi(args) = match args::Command::fro...
fn dump_raw(pkg: &cargo_metadata::Package, format: args::Format) -> Result<(), eyre::Report> { let colored_stderr = concolor_control::get(concolor_control::Stream::Stderr).color(); let raw = crate_api::RustDocBuilder::new() .color(colored_stderr) .dump_raw(pkg.manifest_path.as_path().as_std_pa...
s .base() .map(Ok) .unwrap_or_else(|| find_default_base(metadata.workspace_root.as_std_path())) .with_code(proc_exit::Code::FAILURE)?; Some(base) } }; let (selected, _) = args.workspace.partition_packages(&metadata); for se...
function_block-function_prefixed
[ { "content": "pub fn missing_field<'de, V, E>() -> Result<V, E> {\n\n #[allow(dead_code)]\n\n struct MissingFieldDeserializer<E>(PhantomData<E>);\n\n\n\n impl<E> Deserializer for MissingFieldDeserializer<E> {}\n\n unimplemented!()\n\n}\n\n\n", "file_path": "fixtures/issue_34/new/src/lib.rs", ...
Rust
src/hadoop_common/get_user_mappings_protocol.rs
guangie88/proto-hdfs
dce3965baae75b1a4367b0acb49d1a35dca2290b
#![allow(unknown_lints)] #![allow(clippy)] #![cfg_attr(rustfmt, rustfmt_skip)] #![allow(box_pointers)] #![allow(dead_code)] #![allow(missing_docs)] #![allow(non_camel_case_types)] #![allow(non_snake_case)] #![allow(non_upper_case_globals)] #![allow(trivial_casts)] #![allow(unsafe_code)] #![allow(unused_imports)] #!...
#![allow(unknown_lints)] #![allow(clippy)] #![cfg_attr(rustfmt, rustfmt_skip)] #![allow(box_pointers)] #![allow(dead_code)] #![allow(missing_docs)] #![allow(non_camel_case_types)] #![allow(non_snake_case)] #![allow(non_upper_case_globals)] #![allow(trivial_casts)] #![allow(unsafe_code)] #![allow(unused_imports)] #!...
elf) -> &::protobuf::UnknownFields { &self.unknown_fields } fn mut_unknown_fields(&mut self) -> &mut ::protobuf::UnknownFields { &mut self.unknown_fields } fn as_any(&self) -> &::std::any::Any { self as &::std::any::Any } fn as_any_mut(&mut self) -> &mut ::std::any::Any...
pub fn clear_groups(&mut self) { self.groups.clear(); } pub fn set_groups(&mut self, v: ::protobuf::RepeatedField<::std::string::String>) { self.groups = v; } pub fn mut_groups(&mut self) -> &mut ::protobuf::RepeatedField<::std::string::String> { &mut self....
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": "src/hadoop_common/refresh_user_mappings_protocol.rs", ...
Rust
laythe_vm/src/debug.rs
Laythe-lang/Laythe
f3c33ad4d07a01d9499355c3f1fcd58c5f22c3df
use laythe_core::{chunk::Chunk, if_let_obj, object::ObjectKind, to_obj_kind, value::Value}; use laythe_env::stdio::Stdio; use std::{io, io::Write, mem}; use crate::byte_code::{decode_u16, decode_u32, AlignedByteCode, UpvalueIndex}; pub fn disassemble_chunk(stdio: &mut Stdio, chunk: &Chunk, name: &str) -> io::Result<(...
use laythe_core::{chunk::Chunk, if_let_obj, object::ObjectKind, to_obj_kind, value::Value}; use laythe_env::stdio::Stdio; use std::{io, io::Write, mem}; use crate::byte_code::{decode_u16, decode_u32, AlignedByteCode, UpvalueIndex}; pub fn disassemble_chunk(stdio: &mut Stdio, chunk: &Chunk, name: &str) -> io::Result<(...
fn constant_instruction( stdout: &mut dyn Write, name: &str, chunk: &Chunk, constant: u16, offset: usize, ) -> io::Result<usize> { write!(stdout, "{:13} {:5} ", name, constant)?; writeln!(stdout, "{}", &chunk.get_constant(constant as usize))?; Ok(offset) } fn constant_pair_instruction( stdout: &mut...
e> { let net_jump = sign * (jump as isize); writeln!( stdout, "{:13} {:5} -> {}", name, offset - 3, (offset as isize) + net_jump )?; Ok(offset) }
function_block-function_prefixed
[]
Rust
src/client/ab_eip/template.rs
Joylei/eip-rs
ca4edb04597841ca1c7b4b8532a648576530d705
use super::{ interceptor::HasMoreInterceptor, symbol::SymbolType, HasMore, CLASS_TEMPLATE, REPLY_MASK, SERVICE_TEMPLATE_READ, }; use crate::{ cip::{ epath::EPath, service::{CommonServices, MessageService}, MessageRequest, }, ClientError, }; use bytes::{Buf, BufMut, Bytes, B...
use super::{ interceptor::HasMoreInterceptor, symbol::SymbolType, HasMore, CLASS_TEMPLATE, REPLY_MASK, SERVICE_TEMPLATE_READ, }; use crate::{ cip::{ epath::EPath, service::{CommonServices, MessageService}, MessageRequest, }, ClientError, }; use bytes::{Buf, BufMut, Bytes, B...
fn decode_definition<'de>( buf: &'de mut BytesMut, member_count: u16, ) -> Result<TemplateDefinition<'de>, ClientError> { let mut members: SmallVec<[MemberInfo<'_>; 8]> = SmallVec::with_capacity(member_count as usize); for _ in 0..member_count { let item = MemberInfo { name: Defaul...
uf.decode_u16(); if status != 0 { return Err(Error::custom(format!( "attribute - bad attribute[{}] status: {:#0x}", id, status ))); } if attr_id != id { return Err(Error::custom(format!( "attribute -unexpected attribute[{}]", id ...
function_block-function_prefixed
[ { "content": "#[inline]\n\npub fn decode_unconnected_send<'de, D, R>(mut cpf: CommonPacketIter<'de, D>) -> Result<R, D::Error>\n\nwhere\n\n D: Decoder<'de>,\n\n R: Decode<'de> + 'static,\n\n{\n\n if cpf.len() != 2 {\n\n return Err(cip_error(\"common packet - expected 2 items\"));\n\n }\n\n ...
Rust
src/lib.rs
kkocdko/cmdfactory
21e09316510226d411cb1f048e0e81aac4c68df2
mod config; pub use config::Config; use shared_child::SharedChild; use std::fmt; use std::fs; use std::io; use std::path::PathBuf; use std::process::{Command, Stdio}; use std::sync::{Arc, Condvar, Mutex}; use std::thread; use std::vec::IntoIter; #[derive(Debug)] pub enum ErrorKind { Config, Unknown, Execut...
mod config; pub use config::Config; use shared_child::SharedChild; use std::fmt; use std::fs; use std::io; use std::path::PathBuf; use std::process::{Command, Stdio}; use std::sync::{Arc, Condvar, Mutex}; use std::thread; use std::vec::IntoIter; #[derive(Debug)] pub enum ErrorKind { Config, Unknown, Execut...
nwrap() { let mut command = Command::new(cfg.program.as_ref().unwrap()); for part in &args_template { match *part { "{args_switches}" => command.args(&args_switches), "{input_file}" => command.arg(&input_file), ...
} match cfg.output_overwrite.as_ref().unwrap().as_str() { "allow" => Ok(()), "forbid" if input_file == output_file => Err(Error { kind: ErrorKind::Config, message: "output overwrite forbidden".to_string(), ...
random
[ { "content": "pub fn error(msg: impl Display) {\n\n eprintln!(\"{}\", message(\"error\", msg));\n\n}\n", "file_path": "src/log.rs", "rank": 0, "score": 122558.075421433 }, { "content": "pub fn tui_run(cfg: Config) -> Result<(), Error> {\n\n let mut siv = cursive::default();\n\n\n\n ...
Rust
src/wallet/address.rs
micmarsh/rust-bitcoin
434a140301633888976451c536e084694547d19a
use secp256k1::key::PublicKey; use crypto::digest::Digest; use crypto::sha2::Sha256; use blockdata::script::Script; use blockdata::opcodes::all; use network::constants::{Network, Bitcoin, BitcoinTestnet}; use util::hash::Ripemd160Hash; use util::base58::{Base58Error, InvalidLength, InvalidVersion,...
use secp256k1::key::PublicKey; use crypto::digest::Digest; use crypto::sha2::Sha256; use blockdata::script::Script; use blockdata::opcodes::all; use network::constants::{Network, Bitcoin, BitcoinTestnet}; use util::hash::Ripemd160Hash; use util::base58::{Base58Error, InvalidLength, InvalidVersion,...
#[bench] pub fn generate_uncompressed_address(bh: &mut Bencher) { let mut s = Secp256k1::new().unwrap(); bh.iter( || { let (sk, pk) = s.generate_keypair(false); black_box(sk); black_box(pk); let addr = Address::from_key(Bitcoin, &pk); black_box(addr); }); } #[bench] ...
pub fn generate_address(bh: &mut Bencher) { let mut s = Secp256k1::new().unwrap(); bh.iter( || { let (sk, pk) = s.generate_keypair(true); black_box(sk); black_box(pk); let addr = Address::from_key(Bitcoin, &pk); black_box(addr); }); }
function_block-full_function
[ { "content": "/// Search for `needle` in the vector `haystack` and remove every\n\n/// instance of it, returning the number of instances removed.\n\n/// Loops through the vector opcode by opcode, skipping pushed data.\n\npub fn script_find_and_remove(haystack: &mut Vec<u8>, needle: &[u8]) -> uint {\n\n if need...
Rust
test/test_iterator.rs
BusyJay/rust-rocksdb
8081edecac233124540d557e5add4610ba674904
use rocksdb::*; use tempdir::TempDir; fn prev_collect<'a>(iter: &mut DBIterator<'a>) -> Vec<Kv> { let mut buf = vec![]; while iter.valid() { buf.push(iter.kv().unwrap()); iter.prev(); } buf } #[test] pub fn test_iterator() { let path = TempDir::new("_rust_rocksdb_iteratortest").exp...
use rocksdb::*; use tempdir::TempDir; fn prev_collect<'a>(iter: &mut DBIterator<'a>) -> Vec<Kv> { let mut buf = vec![]; while iter.valid() { buf.push(iter.kv().unwrap()); iter.prev(); } buf } #[test] pub fn test_iterator() { let path = TempDir::new("_rust_rocksdb_iteratortest").exp...
ions::new(); db.put_opt(b"k1-0", b"a", &writeopts).unwrap(); db.put_opt(b"k1-1", b"b", &writeopts).unwrap(); db.put_opt(b"k2-0", b"c", &writeopts).unwrap(); let mut readopts = ReadOptions::new(); readopts.set_iterate_upper_bound(b"k2"); let mut iter = db.iter_opt(readopt...
h_upper_bound_test").expect(""); let mut opts = Options::new(); opts.create_if_missing(true); { let db = DB::open(opts, path.path().to_str().unwrap()).unwrap(); let writeopts = WriteOpt
function_block-random_span
[ { "content": "#[test]\n\npub fn test_multithreaded() {\n\n let path = TempDir::new(\"_rust_rocksdb_multithreadtest\").expect(\"\");\n\n\n\n let db = DB::open_default(path.path().to_str().unwrap()).unwrap();\n\n let db = Arc::new(db);\n\n\n\n db.put(b\"key\", b\"value1\").unwrap();\n\n\n\n let db1...
Rust
vm/src/stdlib/ast.rs
gabhijit/RustPython
3eafcbec3d687a81606556b4f6815cc6825b7ef3
/* * Ast standard module * * This module makes use of the parser logic, and translates all ast nodes * into python ast.AST objects. */ extern crate rustpython_parser; use self::rustpython_parser::{ast, parser}; use super::super::obj::{objstr, objtype}; use super::super::pyobject::{ AttributeProtocol, DictPro...
/* * Ast standard module * * This module makes use of the parser logic, and translates all ast nodes * into python ast.AST objects. */ extern crate rustpython_parser; use self::rustpython_parser::{ast, parser}; use super::super::obj::{objstr, objtype}; use super::super::pyobject::{ AttributeProtocol, DictPro...
fn ast_parse(vm: &mut VirtualMachine, args: PyFuncArgs) -> PyResult { arg_check!(vm, args, required = [(source, Some(vm.ctx.str_type()))]); let source_string = objstr::get_value(source); let internal_ast = match parser::parse_program(&source_string) { Ok(ast) => ast, Err(msg) => { ...
let py_name = ctx.new_str(name.clone()); node.set_attr("id", py_name); node } ast::Expression::String { value } => { let node = create_node(ctx, "Str"); node.set_attr("s", ctx.new_str(value.clone())); node } n => { u...
function_block-function_prefix_line
[ { "content": "pub fn new(typ: PyObjectRef, name: &str, bases: Vec<PyObjectRef>, dict: PyObjectRef) -> PyResult {\n\n let mros = bases.into_iter().map(|x| _mro(x).unwrap()).collect();\n\n let mro = linearise_mro(mros).unwrap();\n\n Ok(PyObject::new(\n\n PyObjectKind::Class {\n\n name: ...
Rust
src/shared_memory.rs
inkooboo/rust-ipc
56a7c537f9134f88f76869fecea404a365cf886e
use std::ffi::CString; use std::slice; use types; pub struct Handle { shm_fd: ::detail::FileHandle, name: String, access_mode: types::AccessMode, } impl Handle { pub fn new(name: &str, create_mode: types::CreateMode, access_mode: types::AccessMode, permi...
use std::ffi::CString; use std::slice; use types; pub struct Handle { shm_fd: ::detail::FileHandle, name: String, access_mode: types::AccessMode, } impl Handle { pub fn new(name: &str, create_mode: types::CreateMode, access_mode: types::AccessMode, permi...
pub fn remove(name: &str) -> Result<(), types::Error> { let cstr = match CString::new(name) { Err(_) => return Err(types::Error::ConvertString), Ok(val) => val, }; match ::detail::delete_file(&cstr) { false => Err(types::Error::DeleteFile), t...
r> { let cstr = match CString::new(name) { Err(_) => return Err(types::Error::ConvertString), Ok(val) => val, }; match ::detail::create_shm_handle(&cstr, &create_mode, &access_mode, &permissions) { None => Err(types::Error::CreateFile), Some(fd) =>...
function_block-function_prefixed
[ { "content": "pub fn create_shm_handle(name: &CString,\n\n create_mode: &types::CreateMode,\n\n access_mode: &types::AccessMode,\n\n permissions: &types::Permissions) -> Option<FileHandle> {\n\n let cmode = match create_mode {\n\n ...
Rust
core/tasks/discovery/src/lib.rs
replicante-io/replicante
18b42665d8773968a650396ec6f8ca3bebd55a06
use std::sync::Arc; use failure::ResultExt; use opentracingrust::Span; use opentracingrust::Tracer; use slog::debug; use slog::warn; use slog::Logger; use replicante_models_core::cluster::discovery::ClusterDiscovery; use replicante_models_core::cluster::ClusterSettings; use replicante_models_core::events::Event; use...
use std::sync::Arc; use failure::ResultExt; use opentracingrust::Span; use opentracingrust::Tracer; use slog::debug; use slog::warn; use slog::Logger; use replicante_models_core::cluster::discovery::ClusterDiscovery; use replicante_models_core::cluster::ClusterSettings; use replicante_models_core::events::Event; use...
}
l() { capture_fail!( &error, self.logger, "Error while acking failed task"; failure_info(&error), ); } } } }
function_block-function_prefixed
[ { "content": "/// Extract information from events and persist them in the view store.\n\npub fn process(follower: &Follower, event: &Event, span: Option<&mut Span>) -> Result<()> {\n\n match &event.payload {\n\n Payload::Action(event) => action::process(follower, event, span),\n\n Payload::Clus...
Rust
src/folder_view/data.rs
arthmis/image-viewer
17e67e78e8762c720b6f5a2fe18b09f4c8aff204
use std::{ path::PathBuf, sync::{ mpsc::{sync_channel, Receiver, SyncSender}, Arc, }, }; use druid::{ im::{vector, Vector}, piet::ImageFormat, widget::{Container, Controller, Image, ScopeTransfer}, Data, Env, Event, ExtEventSink, ImageBuf, Lens, LifeCycle, LifeCycleCtx, ...
use std::{ path::PathBuf, sync::{ mpsc::{sync_channel, Receiver, SyncSender}, Arc, }, }; use druid::{ im::{vector, Vector}, piet::ImageFormat, widget::{Container, Controller, Image, ScopeTransfer}, Data, Env, Event, ExtEventSink, ImageBuf, Lens, LifeCycle, LifeCycleCtx, ...
child.event(ctx, event, data, env) } } impl GridIter<(Thumbnail, usize)> for FolderGalleryState { fn for_each(&self, mut cb: impl FnMut(&(Thumbnail, usize), usize)) { for (i, thumbnail) in self.images.iter().enumerate() { cb(&(thumbnail.clone(), i), i); } } fn for_...
match event { Event::Command(selector) if selector.is(PUSH_VIEW_WITH_SELECTED_IMAGE) => { let (view, idx) = selector.get_unchecked(PUSH_VIEW_WITH_SELECTED_IMAGE); data.add_view(view.clone()); data.selected_image ...
if_condition
[ { "content": "fn image_gridview_builder() -> impl Widget<(ImageFolder, usize)> {\n\n // this lenses into the image folder found in the tuple\n\n // let thumbnails_lens = lens!((ImageFolder, usize), 0)\n\n // .map(|data| data.thumbnails.clone(), |_folder, _put| ());\n\n let folder_thumbnail_lens ...
Rust
src/main.rs
JustinR93/data-converter
b4b9472867de9f3c13bc7cb9a43f3537aa0dddb7
extern crate clap; extern crate indicatif; #[macro_use] extern crate json; use clap::{App, Arg}; use indicatif::{ProgressBar, ProgressStyle}; use json::JsonValue; use std::fs; use std::fs::File; use std::io::BufReader; use std::path::Path; use std::path::PathBuf; use std::process; fn main() { let matches = A...
extern crate clap; extern crate indicatif; #[macro_use] extern crate json; use clap::{App, Arg}; use indicatif::{ProgressBar, ProgressStyle}; use json::JsonValue; use std::fs; use std::fs::File; use std::io::BufReader; use std::path::Path; use std::path::PathBuf; use std::process; fn main() { let matches = A...
std::path::PathBuf = PathBuf::from(input); path_buff.set_extension("json"); let path_name: &str = path_buff.file_name().unwrap().to_str().unwrap(); format!("{}", path_name) }
function_block-function_prefixed
[ { "content": "# Datamorph\n\n\n\nDatamorph is a utiltiy cli tool that takes a csv file and converts it to json. This tool was created because a DB IDE can generally get you CSV of your data really quickly but tends to be slower and problematic when getting JSON of the same data especially at higher record count...
Rust
src/source.rs
burjui/rambo
447aa4d4c7714cc087b7accfb81ffffe92cbe060
use crate::unique_rc::UniqueRc; use std::error::Error; use std::fmt::Debug; use std::fmt::Display; use std::fmt::Formatter; use std::ops::Range; #[derive(Copy, Clone)] pub(crate) struct Position { line: usize, column: usize, } impl Debug for Position { fn fmt(&self, formatter: &mut Formatter<'_>) -> std::...
use crate::unique_rc::UniqueRc; use std::error::Error; use std::fmt::Debug; use std::fmt::Display; use std::fmt::Formatter; use std::ops::Range; #[derive(Copy, Clone)] pub(crate) struct Position { line: usize, column: usize, } impl Debug for Position { fn fmt(&self, formatter: &mut Formatter<'_>) -> std::...
} } None => Ok(0), }?; Ok(from_utf8(&data[offset..]).map(str::to_owned)?) } fn detect_bom(data: &[u8]) -> Option<&'static BOM> { const BOMS: [BOM; 5] = [ BOM::UTF8, BOM::UTF32LE, BOM::UTF32BE, BOM::...
Err(format!( "{:?}: encoding {} is not supported, convert the file to {}", path, bom.name(), BOM::UTF8.name() ))
call_expression
[ { "content": "fn size_string(size: usize) -> String {\n\n match NumberPrefix::binary(size as f32) {\n\n NumberPrefix::Standalone(size) => format!(\"{} bytes\", size),\n\n NumberPrefix::Prefixed(prefix, size) => format!(\"{:.1} {}B\", size, prefix),\n\n }\n\n}\n\n\n\nimpl CompilerPass<Executa...
Rust
gstreamer-base/src/auto/base_parse.rs
snapview/gstreamer-rs
a1da562e960208572f124d5a8b878dc0e11b03f5
use glib::object::Cast; use glib::object::IsA; use glib::signal::connect_raw; use glib::signal::SignalHandlerId; use glib::translate::*; use glib::StaticType; use glib::Value; use glib_sys; use gobject_sys; use gst; use gst_base_sys; use std::boxed::Box as Box_; use std::mem::transmute; glib_wrapper! { pub struc...
use glib::object::Cast; use glib::object::IsA; use glib::signal::connect_raw; use glib::signal::SignalHandlerId; use glib::translate::*; use glib::StaticType; use glib::Value; use glib_sys; use gobject_sys; use gst; use gst_base_sys; use std::boxed::Box as Box_; use std::mem::transmute; glib_wrapper! { pub struc...
fn set_latency(&self, min_latency: gst::ClockTime, max_latency: gst::ClockTime) { unsafe { gst_base_sys::gst_base_parse_set_latency( self.as_ref().to_glib_none().0, min_latency.to_glib(), max_latency.to_glib(), ); } } ...
fn set_infer_ts(&self, infer_ts: bool) { unsafe { gst_base_sys::gst_base_parse_set_infer_ts( self.as_ref().to_glib_none().0, infer_ts.to_glib(), ); } }
function_block-full_function
[ { "content": "fn into_raw_sync<F: Fn(&Bus, &Message) -> BusSyncReply + Send + Sync + 'static>(\n\n func: F,\n\n) -> gpointer {\n\n let func: Box<F> = Box::new(func);\n\n Box::into_raw(func) as gpointer\n\n}\n\n\n\nimpl Bus {\n\n pub fn add_signal_watch_full(&self, priority: Priority) {\n\n un...
Rust
node/src/components/api_server/rpcs/chain.rs
HysMagus/casper-node
7001d2d72dd3d998749dc9a19258add093131764
use std::str; use futures::{future::BoxFuture, FutureExt}; use http::Response; use hyper::Body; use semver::Version; use serde::{Deserialize, Serialize}; use tracing::info; use warp_json_rpc::Builder; use super::{ ApiRequest, Error, ErrorCode, ReactorEventT, RpcWithOptionalParams, RpcWithOptionalParamsExt, }; u...
use std::str; use futures::{future::BoxFuture, FutureExt}; use http::Response; use hyper::Body; use semver::Version; use serde::{Deserialize, Serialize}; use tracing::info; use warp_json_rpc::Builder; use super::{ ApiRequest, Error, ErrorCode, ReactorEventT, RpcWithOptionalParams, RpcWithOptionalParamsExt, }; u...
; let result = Self::ResponseResult { api_version: CLIENT_API_VERSION.clone(), block: maybe_block, }; Ok(response_builder.success(result)?) } .boxed() } } #[derive(Serialize, Deserialize, Debug)] pub struct GetStateRo...
match get_block(maybe_block_hash, effect_builder).await { Ok(maybe_block) => maybe_block, Err(error) => return Ok(response_builder.error(error)?), }
if_condition
[ { "content": "/// Serializes `t` into a `Vec<u8>`.\n\npub fn serialize(t: impl ToBytes) -> Result<Vec<u8>, Error> {\n\n t.into_bytes()\n\n}\n\n\n\npub(crate) fn safe_split_at(bytes: &[u8], n: usize) -> Result<(&[u8], &[u8]), Error> {\n\n if n > bytes.len() {\n\n Err(Error::EarlyEndOfStream)\n\n ...
Rust
consensus/tests/integration_test.rs
ekiden/ekiden
2654947f5fcf783c9ca04779af7afdd69622508b
extern crate consensus as lib; extern crate grpc; use std::{thread, time}; use lib::generated::consensus; use lib::generated::consensus_grpc; use lib::generated::consensus_grpc::Consensus; #[test] fn processes_requests() { let config = lib::Config { tendermint_host: String::from("localhost"), ten...
extern crate consensus as lib; extern crate grpc; use std::{thread, time}; use lib::generated::consensus; use lib::generated::consensus_grpc; use lib::generated::consensus_grpc::Consensus; #[test]
fn processes_requests() { let config = lib::Config { tendermint_host: String::from("localhost"), tendermint_port: 46657, tendermint_abci_port: 46658, grpc_port: 9002, no_tendermint: true, artificial_delay: 0, }; let client_port = config.grpc_port; let _se...
function_block-full_function
[ { "content": "//extern crate token;\n\n\n\n#[test]\n", "file_path": "contracts/token/tests/integration_test.rs", "rank": 6, "score": 47674.38985206512 }, { "content": "#[test]\n\nfn it_adds_two() {\n\n assert_eq!(4, 4);\n\n}\n", "file_path": "contracts/token/tests/integration_test.rs"...
Rust
imxrt1062-pac/imxrt1062-iomuxc-gpr/src/gpr16.rs
Shock-1/teensy4-rs
effc3b290f1be3c7aef62a78e82dbfbc27aa6370
#[doc = "Reader of register GPR16"] pub type R = crate::R<u32, super::GPR16>; #[doc = "Writer for register GPR16"] pub type W = crate::W<u32, super::GPR16>; #[doc = "Register GPR16 `reset()`'s with value 0x0020_0003"] impl crate::ResetValue for super::GPR16 { type Type = u32; #[inline(always)] fn reset_valu...
#[doc = "Reader of register GPR16"] pub type R = crate::R<u32, super::GPR16>; #[doc = "Writer for register GPR16"] pub type W = crate::W<u32, super::GPR16>; #[doc = "Register GPR16 `reset()`'s with value 0x0020_0003"] impl crate::ResetValue for super::GPR16 { type Type = u32; #[inline(always)] fn reset_valu...
self.w.bits = (self.w.bits & !0x01) | ((value as u32) & 0x01); self.w } } #[doc = "DTCM enable initialization out of reset\n\nValue on reset: 1"] #[derive(Clone, Copy, Debug, PartialEq)] pub enum INIT_DTCM_EN_A { #[doc = "0: DTCM is disabled"] INIT_DTCM_EN_0 = 0, #[doc = "1: DTCM is enabled"]...
pub fn is_init_itcm_en_1(&self) -> bool { *self == INIT_ITCM_EN_A::INIT_ITCM_EN_1 } } #[doc = "Write proxy for field `INIT_ITCM_EN`"] pub struct INIT_ITCM_EN_W<'a> { w: &'a mut W, } impl<'a> INIT_ITCM_EN_W<'a> { #[doc = r"Writes `variant` to the field"] #[inline(always)] pub fn variant(...
random
[ { "content": "/// Computes the number of clock ticks that span the provide duration, given\n\n/// the clock frequency and clock divider. If there is no divider, use `Divider::default()`\n\n/// to specify an unused divider. Returns `Ok(ticks)` when the computation of\n\n/// clock ticks succeeds, or an error.\n\n...
Rust
src/sais.rs
ajalab/fm-index
249294233135c2a7e3476a8dda3743a6c2afe3d3
use fid::BitArray; use std::fmt::Debug; use crate::converter::{Converter, IdConverter}; pub fn count_chars<T, C, K>(text: K, converter: &C) -> Vec<u64> where T: Copy + Clone + Into<u64>, K: AsRef<[T]>, C: Converter<T>, { let text = text.as_ref(); let mut occs = vec![0; converter.len() as usize];...
use fid::BitArray; use std::fmt::Debug; use crate::converter::{Converter, IdConverter}; pub fn count_chars<T, C, K>(text: K, converter: &C) -> Vec<u64>
pub fn get_bucket_start_pos(occs: &[u64]) -> Vec<u64> { let mut sum = 0; let mut buckets = vec![0; occs.len()]; for (&occ, b) in occs.iter().zip(buckets.iter_mut()) { *b = sum; sum += occ } buckets } pub fn get_bucket_end_pos(occs: &[u64]) -> Vec<u64> { let mut sum = 0; le...
where T: Copy + Clone + Into<u64>, K: AsRef<[T]>, C: Converter<T>, { let text = text.as_ref(); let mut occs = vec![0; converter.len() as usize]; for &c in text.iter() { let c = converter.convert(c).into() as usize; occs[c] += 1; } occs }
function_block-function_prefix_line
[ { "content": "pub fn bench(c: &mut Criterion) {\n\n let plot_config = PlotConfiguration::default().summary_scale(AxisScale::Logarithmic);\n\n let mut group = c.benchmark_group(\"count\");\n\n let n = 50000;\n\n let m = 8;\n\n group.plot_config(plot_config);\n\n group.throughput(Throughput::Ele...
Rust
client/src/pages/game_state_worker.rs
vascokk/fullstack-rust
970755df5ec8a5c0a6d7338a43a360cd5f62bf00
use std::time::Duration; use std::{ error::Error, fmt::{self, Debug, Display, Formatter}, }; use serde::{Deserialize, Serialize}; use yew::agent::{Agent, AgentLink, HandlerId, Job}; use yew::format::Json; use yew::services::storage::Area; use yew::services::{IntervalService, StorageService, Task}; use crate::...
use std::time::Duration; use std::{ error::Error, fmt::{self, Debug, Display, Formatter}, }; use serde::{Deserialize, Serialize}; use yew::agent::{Agent, AgentLink, HandlerId, Job}; use yew::format::Json; use yew::services::storage::Area; use yew::services::{IntervalService, StorageService, Task}; use crate::...
; self.link.respond(who, msg); } Msg::GetGameStateResponse(who, fetched_response) => { match fetched_response { Ok(game_state) => { yew::services::ConsoleService::info( format!("update::Msg::U...
match fetched_response { Ok(game_state) => { yew::services::ConsoleService::info( format!("update::Msg::MakeMoveResponse called: {:#?}", game_state) .as_str(), ); self....
if_condition
[ { "content": "#[cfg_attr(test, mockable)]\n\npub fn user_move(\n\n ses_id: Uuid,\n\n user_id: Uuid,\n\n col_num: usize,\n\n conn: &SqliteConnection,\n\n) -> Result<models::GameState, String> {\n\n //TODO: needs refactoring. should not do db calls\n\n db::get_board(&ses_id, conn).and_then(|s| {...
Rust
src/editor.rs
kbieganski/bevy_quickstart
f574ea9f22b537fb79b501c831fdbf6fd54f90c4
use bevy::prelude::*; use bevy_inspector_egui::bevy_egui::EguiContext; use bevy_inspector_egui::plugin::InspectorWindows; use bevy_mod_picking::{PickingPluginsState, Selection}; use heron::prelude::*; use crate::controller::Player; use bevy_inspector_egui::widgets::InspectorQuery; use bevy_inspector_egui::Inspectabl...
use bevy::prelude::*; use bevy_inspector_egui::bevy_egui::EguiContext; use bevy_inspector_egui::plugin::InspectorWindows; use bevy_mod_picking::{PickingPluginsState, Selection}; use heron::prelude::*; use crate::controller::Player; use bevy_inspector_egui::widgets::InspectorQuery; use bevy_inspector_egui::Inspectabl...
r")] profiling::puffin::set_scopes_on(true); } #[cfg(feature = "profiler")] puffin_egui::profiler_window(egui.ctx()); } }
function_block-function_prefixed
[]
Rust
rs/rosetta-api/hardware_wallet_tests/src/main.rs
3cL1p5e7/ic
2b6011291d900454cedcf86ec41c8c1994fdf7d9
pub use ed25519_dalek::Keypair as EdKeypair; use ed25519_dalek::Signer; use ic_nns_constants::LEDGER_CANISTER_ID; use ic_rosetta_api::{ convert::{from_hex, from_public_key, to_arg, to_hex, to_model_account_identifier}, make_sig_data, models, models::{CurveType, Signature, SignatureType, SigningPayload}, }; ...
pub use ed25519_dalek::Keypair as EdKeypair; use ed25519_dalek::Signer; use ic_nns_constants::LEDGER_CANISTER_ID; use ic_rosetta_api::{ convert::{from_hex, from_public_key, to_arg, to_hex, to_model_account_identifier}, make_sig_data, models, models::{CurveType, Signature, SignatureType, SigningPayload}, }; ...
None => expert.push("2 | Subaccount : Not set".to_string()), } expert.push(format!( "3 | From account[1/2] : {} {}", row(from, 0), row(from, 1) )); expert.push(format!( "3 | From account[2/2] : {} {}", row(from, 2), row(from, 3) )); expert.pus...
u8> = SignedRequestBytes::try_from(envelope).unwrap().into(); let mut expert = Vec::new(); expert.push("0 | Transaction type : Send ICP".to_string()); expert.push(format!("1 | Sender [1/2] : {}", chunk_pid(pid, 0))); expert.push(format!("1 | Sender [2/2] : {}", chunk_pid(pid, 1))); match from_subac...
function_block-random_span
[]
Rust
src/parser/statement/expression/function_call/name.rs
matter-labs/compiler-yul
2b27d1aca562570b6a60c1c56dc9956ac8c93d69
#[derive(Debug, PartialEq, Clone)] pub enum Name { UserDefined(String), Add, Sub, Mul, Div, Mod, Sdiv, Smod, Lt, Gt, Eq, IsZero, Slt, Sgt, Or, Xor, ...
#[derive(Debug, PartialEq, Clone)] pub enum Name { UserDefined(String), Add, Sub, Mul, Div, Mod, Sdiv, Smod, Lt, Gt, Eq, IsZero, Slt, Sgt, Or, Xor, ...
}
sload" => Self::SLoad, "sstore" => Self::SStore, "loadimmutable" => Self::LoadImmutable, "setimmutable" => Self::SetImmutable, "calldataload" => Self::CallDataLoad, "calldatasize" => Self::CallDataSize, "calldatacopy" => Self::CallDataCopy,...
function_block-function_prefix_line
[]
Rust
src/windy_str.rs
takubokudori/windy
1025991396d15b1fab6d4093762b742a93eeab78
use crate::{ __lib::{cmp::Ordering, fmt::Write, slice}, *, }; macro_rules! str_impl_debug { ($x:ident) => { impl fmt::Debug for $x { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { f.write_char('"')?; #[cfg(not(feature = "std"))] ...
use crate::{ __lib::{cmp::Ordering, fmt::Write, slice}, *, }; macro_rules! str_impl_debug { ($x:ident) => { impl fmt::Debug for $x { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { f.write_char('"')?; #[cfg(not(feature = "std"))] ...
#[inline] pub unsafe fn from_raw_s_unchecked<'a>( ptr: *const u8, len: usize, ) -> &'a Self { let slice = slice::from_raw_parts(ptr, len as usize + 1); Self::from_bytes_with_nul_unchecked(slice) } } impl PartialEq for AStr { fn eq(&self, other: ...
pub unsafe fn from_raw_s<'a>(ptr: *const u8, mut len: usize) -> &'a Self { let len2 = strnlen(ptr, len); if len2 < len { len = len2; } Self::from_raw_s_unchecked(ptr, len) }
function_block-full_function
[ { "content": "fn bench_ansi_to_utf8(c: &mut Criterion) {\n\n let s = AString::try_from(\"Hello World\").unwrap();\n\n c.bench_function(\"ANSI to UTF-8\", |b| {\n\n b.iter(|| s.try_to_string().unwrap())\n\n });\n\n}\n\n\n", "file_path": "benches/string.rs", "rank": 0, "score": 96971.9...
Rust
lib/backend-doc/src/macros.rs
nezdolik/reproto
2d69d8efca518a6ea23a4182b29872fcc62a1a71
pub trait FormatAttribute { fn format_attribute(&self) -> String; } impl<T> FormatAttribute for Vec<T> where T: FormatAttribute, { fn format_attribute(&self) -> String { let mut out = String::new(); let mut it = self.iter().peekable(); while let Some(next) = it.next() { ...
pub trait FormatAttribute { fn format_attribute(&self) -> String; } impl<T> FormatAttribute for Vec<T> where T: FormatAttribute, { fn format_attribute(&self) -> String { let mut out = Strin
} impl<'a> FormatAttribute for &'a str { fn format_attribute(&self) -> String { (*self).to_owned() } } impl FormatAttribute for String { fn format_attribute(&self) -> String { self.clone() } } #[macro_export] macro_rules! define_processor { ($name:ident, $body:ty, $slf:ident, $($...
g::new(); let mut it = self.iter().peekable(); while let Some(next) = it.next() { out.push_str(&next.format_attribute()); if !it.peek().is_none() { out.push_str(" "); } } out }
function_block-function_prefixed
[ { "content": "/// Read the full contents of the given reader as a string.\n\npub fn read_to_string<'a, R>(mut reader: R) -> Result<String>\n\nwhere\n\n R: AsMut<Read + 'a>,\n\n{\n\n let mut content = String::new();\n\n reader.as_mut().read_to_string(&mut content)?;\n\n Ok(content)\n\n}\n\n\n", "...
Rust
src/geometry/contact_generator/cuboid_capsule_contact_generator.rs
ashneverdawn/rapier
6b1cd9cd404bd1da6aec94527e58dcd483a50c67
use crate::geometry::contact_generator::PrimitiveContactGenerationContext; #[cfg(feature = "dim3")] use crate::geometry::PolyhedronFace; use crate::geometry::{cuboid, sat, Capsule, ContactManifold, Cuboid, KinematicsCategory, Shape}; #[cfg(feature = "dim2")] use crate::geometry::{CuboidFeature, CuboidFeatureFace}; use ...
use crate::geometry::contact_generator::PrimitiveContactGenerationContext; #[cfg(feature = "dim3")] use crate::geometry::PolyhedronFace; use crate::geometry::{cuboid, sat, Capsule, ContactManifold, Cuboid, KinematicsCategory, Shape}; #[cfg(feature = "dim2")] use crate::geometry::{CuboidFeature, CuboidFeatureFace}; use ...
.0 { std::mem::swap(&mut pos1, &mut pos2); std::mem::swap(&mut pos12, &mut pos21); best_sep = sep2; swapped_reference = true; } else if sep3.0 > sep1.0 { best_sep = sep3; } let feature1; let mut feature2; #[cfg(feature = "dim2")] { ...
(swapped && manifold.try_update_contacts(&pos21)) { return; } let segment2 = Segment::new(capsule2.a, capsule2.b); /* * * Point-Face cases. * */ let sep1 = sat::cube_support_map_find_local_separating_normal_oneway(cube1, &segment2, &pos12); if sep1.0 > capsule2.rad...
random
[ { "content": "/// Conditionally swaps each lanes of `a` with those of `b`.\n\n///\n\n/// For each `i in [0..SIMD_WIDTH[`, if `do_swap.extract(i)` is `true` then\n\n/// `a.extract(i)` is swapped with `b.extract(i)`.\n\npub fn simd_swap(do_swap: SimdBool, a: &mut SimdFloat, b: &mut SimdFloat) {\n\n let _a = *a...
Rust
union_impl/src/expr_chain/expr_chain_with_default.rs
olegnn/union
b8ac7386e99b72ad20878df734d675e5cb3af8a1
use quote::ToTokens; use std::cell::{Ref, RefCell}; use std::rc::Rc; use syn::parse::ParseStream; use syn::Expr::Let; use syn::{Pat, Token}; use super::*; use crate::instant_and_deferred_determiners; struct ExprChainInternal<Member, GroupDeterminer> { members: Vec<Member>, group_determiners: Vec<GroupDeterm...
use quote::ToTokens; use std::cell::{Ref, RefCell}; use std::rc::Rc; use syn::parse::ParseStream; use syn::Expr::Let; use syn::{Pat, Token}; use super::*; use crate::instant_and_deferred_determiners; struct ExprChainInternal<Member, GroupDeterminer> { members: Vec<Member>, group_determiners: Vec<GroupDeterm...
}
rocessWithDefault( Some(ProcessActionExpr::Instant(ProcessExpr::Initial( syn::parse2(quote! { Ok(2) }).unwrap() ))), None ) ); assert_eq!( members[1], ProcessWithDefault( Some(ProcessA...
function_block-function_prefixed
[ { "content": "///\n\n/// Returns true if given stream can be parsed as `Expr`.\n\n///\n\npub fn is_valid_expr(input: TokenStream) -> bool {\n\n syn::parse2::<Expr>(input).is_ok()\n\n}\n\n\n", "file_path": "union_impl/src/expr_chain/utils.rs", "rank": 0, "score": 240156.22513336324 }, { "c...
Rust
src/models/transaction/buffer/buffer_modify_multisig_account_transaction.rs
proximax-storage/rust-xpx-chain-sdk
55613067328d511dbd9a129be30b9e048ef79175
#[allow(unused_imports, dead_code)] pub mod modify_multisig_account { #[derive(Copy, Clone, Debug, PartialEq)] pub struct CosignatoryModificationBuffer<'a> { pub _tab: fb::Table<'a>, } impl<'a> fb::Follow<'a> for CosignatoryModificationBuffer<'a> { type Inner = CosignatoryModification...
#[allow(unused_imports, dead_code)] pub mod modify_multisig_account { #[derive(Copy, Clone, Debug, PartialEq)] pub struct CosignatoryModificationBuffer<'a> { pub _tab: fb::Table<'a>, } impl<'a> fb::Follow<'a> for CosignatoryModificationBuffer<'a> { type Inner = CosignatoryModification...
#[inline] pub fn add_type_(&mut self, type_: u16) { self.fbb_ .push_slot::<u16>(ModifyMultisigAccountTransactionBuffer::VT_TYPE_, type_, 0); } #[inline] pub fn add_max_fee(&mut self, max_fee: fb::WIPOffset<fb::Vector<'b, u32>>) { self.fbb_...
pub fn add_version(&mut self, version: u32) { self.fbb_.push_slot::<u32>( ModifyMultisigAccountTransactionBuffer::VT_VERSION, version, 0, ); }
function_block-full_function
[ { "content": "#[inline]\n\npub fn u32_to_array_u8(value: u32) -> [u8; SIZE_U32] {\n\n let mut buf = [0u8; SIZE_U32];\n\n buf.as_mut()\n\n .write_u32::<LittleEndian>(value)\n\n .expect(\"Unable to write\");\n\n buf\n\n}\n\n\n", "file_path": "src/helpers/utils_bytes.rs", "rank": 0, ...
Rust
src/renderer.rs
louisdevie/minui
1e862235a6a0b4a536b31d9acabb502efe52966f
extern crate sdl2; use std::collections::HashMap; use sdl2::pixels::Color; use sdl2::rect::Rect; use sdl2::render::{Canvas, TextureCreator, TextureQuery}; use sdl2::surface::Surface; use sdl2::ttf::Font; use sdl2::video::{Window, WindowContext}; use crate::area::{safe_signed, safe_unsigned, scale, ResolvedArea}; use...
extern crate sdl2; use std::collections::HashMap; use sdl2::pixels::Color; use sdl2::rect::Rect; use sdl2::render::{Canvas, TextureCreator, TextureQuery}; use sdl2::surface::Surface; use sdl2::ttf::Font; use sdl2::video::{Window, WindowContext}; use crate::area::{safe_signed, safe_unsigned, scale, ResolvedArea}; use...
.unwrap(); self.surface_cache.insert(widget, surface); } let texture = self .texture_creator .create_texture_from_surface( self.surface_cache .get(&widget) ...
> { let resolved = area.resolve(parent_area); if text.has_changed() { let surface = self .font_body .as_ref() .unwrap() .render(&text.get()) .blend...
random
[ { "content": "pub fn scale(a: u32, b: f32) -> i32 {\n\n (b * a as f32).round() as i32\n\n}\n\n\n", "file_path": "src/area.rs", "rank": 0, "score": 92307.70780507452 }, { "content": "pub fn safe_signed(val: u32) -> i32 {\n\n match val.try_into() {\n\n Err(_) => i32::MAX,\n\n ...
Rust
src/test_util/stats.rs
nkinkade/vector
c3cc8daa82e6b464c2ecd0c47655ec1b22f4cce2
#![cfg(test)] use std::fmt::{self, Display, Formatter}; use std::ops::Deref; use std::time::Instant; #[derive(Copy, Clone, Debug, Default)] pub struct HistogramStats { pub min: usize, pub max: usize, pub mode: usize, pub total: f64, pub mean: f64, } #[derive(Clone, Debug, Default)] pub ...
#![cfg(test)] use std::fmt::{self, Display, Formatter}; use std::ops::Deref; use std::time::Instant; #[derive(Copy, Clone, Debug, Default)] pub struct HistogramStats { pub min: usize, pub max: usize, pub mode: usize, pub total: f64, pub mean: f64, } #[derive(Clone, Debug, Default)] pub ...
} fn opt_max(opt: Option<f64>, value: f64) -> Option<f64> { Some(match opt { None => value, Some(s) if s > value => s, _ => value, }) } fn opt_min(opt: Option<f64>, value: f64) -> Option<f64> { Some(match opt { None => value, Some(s) if s < value => s, _ =>...
fn fmt(&self, fmt: &mut Formatter<'_>) -> Result<(), fmt::Error> { match self.stats() { None => write!(fmt, "[No stats]"), Some(stats) => write!( fmt, "[min={}, max={}, mean={}]", stats.min, stats.max, stats.mean ), } ...
function_block-full_function
[ { "content": "fn write_word(fmt: &mut Formatter<'_>, word: &str) -> Result<(), fmt::Error> {\n\n if word.contains(|c: char| !c.is_ascii_alphanumeric() && c != '_') {\n\n write!(fmt, \"{:?}\", word)\n\n } else {\n\n write!(fmt, \"{}\", word)\n\n }\n\n}\n\n\n\n#[cfg(test)]\n\nmod test {\n\n...
Rust
src/main.rs
dotcypress/placebo-shell
14c092333a18a09b9cb47b166ce20d0ef8b52aec
#![no_std] #![no_main] #![deny(warnings)] extern crate cortex_m; extern crate cortex_m_rt as rt; extern crate panic_halt; extern crate rtic; extern crate stm32g0xx_hal as hal; mod shell; mod stepper; use hal::gpio::*; use hal::prelude::*; use hal::serial::*; use hal::timer::*; use hal::{analog::adc, exti, rcc, stm32...
#![no_std] #![no_main] #![deny(warnings)] extern crate cortex_m; extern crate cortex_m_rt as rt; extern crate panic_halt; extern crate rtic; extern crate stm32g0xx_hal as hal; mod shell; mod stepper; use hal::gpio::*; use hal::prelude::*; use hal::serial::*; use hal::timer::*; use hal::{analog::adc, exti, rcc, stm32...
#[task(binds = TIM17, priority = 3, shared = [adc])] fn adc_timer(ctx: adc_timer::Context) { let mut adc = ctx.shared.adc; let voltage = adc.lock(|adc| { adc.timer.clear_irq(); adc.adc.read_voltage(&mut adc.pin).unwrap() }); env::spawn(EnvSignal::LogAdc...
fn stepper_timer(ctx: stepper_timer::Context) { let mut stepper = ctx.shared.stepper; stepper.lock(|stepper| { stepper.motor.turn(); stepper.timer.clear_irq(); }); }
function_block-full_function
[ { "content": "}\n\n\n\npub struct StepperMotor<A, B, C, D> {\n\n pins: (A, B, C, D),\n\n dir: Rotation,\n\n mode: Mode,\n\n step: usize,\n\n}\n\n\n\nimpl<A: OutputPin, B: OutputPin, C: OutputPin, D: OutputPin> StepperMotor<A, B, C, D> {\n\n pub fn new(a: A, b: B, c: C, d: D) -> Self {\n\n ...
Rust
src/text.rs
PeytonT/serde_ion
b0c940f9df0ecfbe4eb0f00f4c531fcf64ce6d4d
use std::{convert::TryFrom, fmt}; use num_bigint::BigUint; use phf::{phf_map, phf_set}; use time::{ComponentRangeError, UtcOffset}; use crate::error::TextFormatError; use crate::types::Timestamp; pub(crate) static RESERVED_TOKENS: phf::Set<&'static str> = phf_set! { "null", "null.null", "null.bool", ...
use std::{convert::TryFrom, fmt}; use num_bigint::BigUint; use phf::{phf_map, phf_set}; use time::{ComponentRangeError, UtcOffset}; use crate::error::TextFormatError; use crate::types::Timestamp; pub(crate) static RESERVED_TOKENS: phf::Set<&'static str> = phf_set! { "null", "null.null", "null.bool", ...
} }
Ok(match timestamp.time { None => match timestamp.date { TextDate::Year { year } => Timestamp::Year { year }, TextDate::Month { year, month } => Timestamp::Month { year, month }, TextDate::Day { date } => Timestamp::Day { year: date.year() ...
call_expression
[ { "content": "fn minute(offset: Option<UtcOffset>, hour: u8, minute: u8) -> TextTime {\n\n TextTime::Minute {\n\n offset,\n\n hour,\n\n minute,\n\n }\n\n}\n\n\n", "file_path": "src/de/ion_1_0/text/tests/mod.rs", "rank": 0, "score": 325346.0078536718 }, { "content":...
Rust
src/services/preboard.rs
jkcoxson/rusty_libimobiledevice
67e6c6068fb4da673fc55546c775b113a706b450
use std::os::raw::c_char; use crate::{ bindings as unsafe_bindings, error::PreboardError, idevice::Device, services::lockdownd::LockdowndService, }; use plist_plus::Plist; pub struct PreboardClient<'a> { pub(crate) pointer: unsafe_bindings::preboard_client_t, phantom: std::marker::PhantomData<&'a D...
use std::os::raw::c_char; use crate::{ bindings as unsafe_bindings, error::PreboardError, idevice::Device, services::lockdownd::LockdowndService, }; use plist_plus::Plist; pub struct PreboardClient<'a> { pub(crate) pointer: unsafe_bindings::preboard_client_t, phantom: std::marker::PhantomData<&'a D...
pub fn start_service(device: &Device, label: impl Into<String>) -> Result<Self, PreboardError> { let mut pointer = std::ptr::null_mut(); let result = unsafe { unsafe_bindings::preboard_client_start_service( device.pointer, ...
descriptor: LockdowndService) -> Result<Self, PreboardError> { let mut pointer = std::ptr::null_mut(); let result = unsafe { unsafe_bindings::preboard_client_new(device.pointer, descriptor.pointer, &mut pointer) } .into(); if result != PreboardError::Success { ...
function_block-function_prefixed
[ { "content": "/// Fetches a list of devices, but returns one with the given udid\n\n/// # Arguments\n\n/// * `udid` - The udid of the device to return\n\n/// # Returns\n\n/// A device struct\n\n///\n\n/// ***Verified:*** False\n\npub fn get_device(udid: impl Into<String>) -> Result<Device, IdeviceError> {\n\n ...
Rust
src/wrapper/optional.rs
remilauzier/rust-dlopen
db5576ae888957be5d5001836dda86a89755f28b
use super::super::raw::Library; use super::super::Error; use std::ops::{Deref, DerefMut}; use super::api::WrapperApi; use std::ffi::OsStr; /** Container for a library handle and both obligatory and optional APIs inside one structure. A common problem with dynamic link libraries is that they often have different versi...
use super::super::raw::Library; use super::super::Error; use std::ops::{Deref, DerefMut}; use super::api::WrapperApi; use std::ffi::OsStr; /** Container for a library handle and both obligatory and optional APIs inside one structure. A common problem with dynamic link libraries is that they often have different versi...
pub fn optional(&self) -> &Option<Optional> { &self.optional } pub fn optional_mut(&mut self) -> &Option<Optional> { &mut self.optional } } impl<Api, Optional> Deref for OptionalContainer<Api, Optional> where Api: WrapperApi, Optional: WrapperApi, { type Target ...
pub unsafe fn load_self() -> Result<OptionalContainer<Api, Optional>, Error> { let lib = Library::open_self()?; let api = Api::load(&lib)?; let optional = Optional::load(&lib).ok(); Ok(Self { lib, api, optional }) }
function_block-full_function
[]
Rust
ap-com/src/models/group/mod.rs
Devisa/dv-api
3ac4116364f74b6d3f0d8bb8de80dff8230ffec9
use crate::models::user::User; use uuid::Uuid; use super::Model; use crate::{GroupRole, Id, Status, now, private}; use actix::prelude::*; use serde::{Serialize, Deserialize}; use sqlx::{ FromRow, Postgres, postgres::PgPool, types::chrono::{NaiveDateTime, Utc}, }; #[derive(Debug, FromRow, Clone, Serialize, Dese...
use crate::models::user::User; use uuid::Uuid; use super::Model; use crate::{GroupRole, Id, Status, now, private}; use actix::prelude::*; use serde::{Serialize, Deserialize}; use sqlx::{ FromRow, Postgres, postgres::PgPool, types::chrono::{NaiveDateTime, Utc}, }; #[derive(Debug, FromRow, Clone, Serialize, Dese...
bind(group_id) .fetch_optional(db).await?; Ok(res) } pub async fn get_all_by_user(db: &PgPool, user_id: Id) -> sqlx::Result<Vec<Self>> { let res = sqlx::query_as::<Postgres, Group>("SELECT * FROM Groups WHERE user_id = $1") .bind(user_id) .fetch_all(db).await...
t")] pub status: Status, #[serde(default = "now")] pub created_at: NaiveDateTime, #[serde(default = "now")] pub updated_at: NaiveDateTime, } impl Actor for Group { type Context = Context<Self>; fn started(&mut self, _ctx: &mut Self::Context) { log::info!("GROUP ACTOR STARTED: {:?}"...
random
[ { "content": "#[inline]\n\npub fn private() -> bool {\n\n true\n\n}\n\n\n\n\n\n\n\nimpl ToString for Status {\n\n #[inline]\n\n fn to_string(&self) -> String {\n\n match self {\n\n &Status::Active => \"Active\".to_string(),\n\n &Status::Deferred => \"Deferred\".to_string(),...
Rust
src/query/identical.rs
pacman82/odbc2parquet
de587b93a2f1e6f22ebaa5d0d08af61b98718540
use std::marker::PhantomData; use anyhow::Error; use odbc_api::buffers::{AnyColumnView, BufferDescription, Item}; use parquet::{ basic::{ConvertedType, Repetition}, column::writer::{get_typed_column_writer_mut, ColumnWriter}, data_type::DataType, schema::types::Type, }; use crate::parquet_buffer::{B...
use std::marker::PhantomData; use anyhow::Error; use odbc_api::buffers::{AnyColumnView, BufferDescription, Item}; use parquet::{ basic::{ConvertedType, Repetition}, column::writer::{get_typed_column_writer_mut, ColumnWriter}, data_type::DataType, schema::types::Type, }; use crate::parquet_buffer::{B...
builder.build().unwrap() } fn buffer_description(&self) -> BufferDescription { BufferDescription { kind: Pdt::T::BUFFER_KIND, nullable: false, } } fn copy_odbc_to_parquet( &self, _parquet_buffer: &mut ParquetBuffer, column_writer...
if let Some(precision) = self.precision { builder = builder.with_scale(0).with_precision(precision); }
if_condition
[ { "content": "/// Used to parse the compression from the command line argument.\n\npub fn compression_from_str(source: &str) -> Result<Compression, Error> {\n\n let compression = match source {\n\n \"uncompressed\" => Compression::UNCOMPRESSED,\n\n \"gzip\" => Compression::GZIP,\n\n \"lz...
Rust
support/libsignal-sys/src/crypto_provider.rs
gabrielesvelto/api-daemon
a30971aa1a2dc94e7a9529e5f12749432538f19d
use crate::generated::ffi::*; use ring::digest; use ring::rand::{SecureRandom, SystemRandom}; use crypto::mac::Mac; use crypto::digest::Digest; use crypto::hmac::Hmac; use crypto::sha2::Sha256; use crypto::blockmodes::PkcsPadding; use crypto::aes::{cbc_decryptor, cbc_encryptor, ctr, KeySize}; use crypto::buffer::{Buff...
use crate::generated::ffi::*; use ring::digest; use ring::rand::{SecureRandom, SystemRandom}; use crypto::mac::Mac; use crypto::digest::Digest; use crypto::hmac::Hmac; use crypto::sha2::Sha256; use crypto::blockmodes::PkcsPadding; use crypto::aes::{cbc_decryptor, cbc_encryptor, ctr, KeySize}; use crypto::buffer::{Buff...
pub fn get_crypto_provider() -> signal_crypto_provider { signal_crypto_provider { random_func: Some(random_func), hmac_sha256_init_func: Some(hmac_sha256_init_func), hmac_sha256_update_func: Some(hmac_sha256_update_func), hmac_sha256_final_func: Some(hmac_sha256_final_func), ...
function_block-full_function
[]
Rust
vendor/symphonia-format-ogg-0.2.0/src/mappings/vorbis.rs
ritikmishra/babycat
ce21a5d07f3e0ce4d30b7109617ef48f29d350a8
use super::{Mapper, MapResult}; use symphonia_core::codecs::{CodecParameters, CODEC_TYPE_VORBIS}; use symphonia_core::errors::{Result, decode_error}; use symphonia_core::io::{BufStream, ByteStream}; use symphonia_core::meta::MetadataBuilder; use symphonia_metadata::vorbis; use log::warn; const VORBIS_IDENTIFICATIO...
use super::{Mapper, MapResult}; use symphonia_core::codecs::{CodecParameters, CODEC_TYPE_VORBIS}; use symphonia_core::errors::{Result, decode_error}; use symphonia_core::io::{BufStream, ByteStream}; use symphonia_core::meta::MetadataBuilder; use symphonia_metadata::vorbis; use log::warn; const VORBIS_IDENTIFICATIO...
struct VorbisMapper { codec_params: CodecParameters, } impl Mapper for VorbisMapper { fn codec(&self) -> &CodecParameters { &self.codec_params } fn map_packet(&mut self, buf: &[u8]) -> Result<MapResult> { let mut reader = BufStream::new(buf); let packet_type = read...
f); let packet_type = reader.read_u8()?; if packet_type != VORBIS_PACKET_TYPE_IDENTIFICATION { return Ok(None); } let mut packet_sig_buf = [0; 6]; reader.read_buf_exact(&mut packet_sig_buf)?; if packet_sig_buf != VORBIS_HEADER_PACKET_SIGNATURE { return Ok(None); ...
function_block-function_prefixed
[ { "content": "pub fn milliseconds_to_frames(frame_rate_hz: u32, duration_milliseconds: u64) -> u64 {\n\n (duration_milliseconds * frame_rate_hz as u64) / 1000\n\n}\n", "file_path": "src/backend/common.rs", "rank": 0, "score": 110395.55709234043 }, { "content": "pub fn resample(\n\n inp...
Rust
src/env.rs
seanchen1991/scheme.rs
898af7e1cbeef6db5b3f11b0db1203204f3029ca
use std::collections::HashMap; use std::rc::Rc; use parser::SExpr; use parser::SExprs; use serr::{SErr, SResult}; use utils::{new_rc_ref_cell, RcRefCell}; pub type VarName = String; pub type EnvValues = HashMap<VarName, SExpr>; #[derive(Debug, Clone, PartialEq)] pub struct EnvRef(RcRefCell<Option<Env>>); impl EnvRe...
use std::collections::HashMap; use std::rc::Rc; use parser::SExpr; use parser::SExprs; use serr::{SErr, SResult}; use utils::{new_rc_ref_cell, RcRefCell}; pub type VarName = String; pub type EnvValues = HashMap<VarName, SExpr>; #[derive(Debug, Clone, PartialEq)] pub struct EnvRef(RcRefCell<Option<Env>>); impl EnvRe...
pub fn set(&self, key: String, val: SExpr) -> SResult<SExpr> { self.0.borrow_mut() .as_mut() .ok_or_else(|| SErr::EnvNotFound)? .set(key, val) } } #[derive(Debug, PartialEq)] pub struct Env { parent: EnvRef, values: EnvValues,...
pub fn define(&self, key: String, val: SExpr) { self.0.borrow_mut() .as_mut() .expect("Can't find environment") .define(key, val); }
function_block-full_function
[ { "content": "pub fn eval_ref<F,T>(sexpr: &SExpr, env: &EnvRef, mut f: F) -> SResult<T>\n\nwhere F: FnMut(&SExpr)->SResult<T> {\n\n match sexpr {\n\n SExpr::Atom(Token::Symbol(ref x)) => {\n\n env.with_ref(x, |result| {\n\n f(result)\n\n })\n\n },\n\n ...
Rust
arci-ros/src/ros_control/utils.rs
mertcookimg/openrr
4bdb49d483383e912b37907c6f651b52f2b7a742
use std::{collections::HashMap, sync::Arc, time::Duration}; use arci::{copy_joint_positions, Error, JointTrajectoryClient, TrajectoryPoint}; use crate::{ msg::trajectory_msgs::{JointTrajectory, JointTrajectoryPoint}, wrap_joint_trajectory_client, JointStateProvider, LazyJointStateProvider, RosControlClien...
use std::{collections::HashMap, sync::Arc, time::Duration}; use arci::{copy_joint_positions, Error, JointTrajectoryClient, TrajectoryPoint}; use crate::{ msg::trajectory_msgs::{JointTrajectory, JointTrajectoryPoint}, wrap_joint_trajectory_client, JointStateProvider, LazyJointStateProvider, RosControlClien...
false) } pub fn create_joint_trajectory_clients_lazy<B>( builders: Vec<B>, urdf_robot: Option<&urdf_rs::Robot>, ) -> Result<HashMap<String, Arc<dyn JointTrajectoryClient>>, arci::Error> where B: RosControlClientBuilder, { create_joint_trajectory_clients_inner(builders, urdf_robot, true) } fn create_jo...
create_joint_trajectory_clients<B>( builders: Vec<B>, urdf_robot: Option<&urdf_rs::Robot>, ) -> Result<HashMap<String, Arc<dyn JointTrajectoryClient>>, arci::Error> where B: RosControlClientBuilder, { create_joint_trajectory_clients_inner(builders, urdf_robot,
random
[ { "content": "/// Launches GUI that send base velocity from GUI to the given `move_base`.\n\npub fn velocity_sender<M>(move_base: M) -> Result<(), Error>\n\nwhere\n\n M: MoveBase + 'static,\n\n{\n\n let gui = VelocitySender::new(move_base);\n\n\n\n // Should we expose some of the settings to the user?\...
Rust
src/lib.rs
phR0ze/rivia-file
5d26e2806fb41a4debe7428f342657074e11508d
mod edit; use regex::Regex; use rivia_vfs::prelude::*; pub mod prelude { pub use regex::Regex; pub use rivia_vfs::prelude::*; pub mod file { pub use crate::*; } } pub fn extract<T: AsRef<Path>, U: AsRef<str>>(path: T, rx: U) -> RvResult<String> { let data = vfs::read_all(...
mod edit; use regex::Regex; use rivia_vfs::prelude::*; pub mod prelude { pub use regex::Regex; pub use rivia_vfs::prelude::*; pub mod file { pub use crate::*; } } pub fn extract<T: AsRef<Path>, U: AsRef<str>>(path: T, rx: U) -> RvResult<String> { let data = vfs::read_all(...
th)?; let write_data = rx.replace_all(&read_data, regex::NoExpand(value.as_ref())).to_string(); if read_data != write_data { vfs::write_all(&path, write_data).unwrap(); } Ok(()) } #[cfg(test)] mod tests { use crate::prelude::*; #[test] fn test_extract() { let tmpdir = a...
all_ne<T: AsRef<Path>, U: AsRef<str>>(path: T, rx: U, value: U) -> RvResult<()> { let rx = &Regex::new(rx.as_ref()).map_err(|_| FileError::FailedToExtractString)?; let read_data = vfs::read_all(&pa
function_block-random_span
[ { "content": "fn main()\n\n{\n\n // Write out and read back the file as stdfs\n\n read_write_all(\"file1\").unwrap();\n\n\n\n // Repeat but with the Memfs provider\n\n vfs::set_memfs().unwrap();\n\n read_write_all(\"file1\").unwrap();\n\n}\n\n\n", "file_path": "examples/vfs.rs", "rank": 5...
Rust
src/uint256.rs
RubberDuckEng/rusty_ethereum
27e6c835ad06900a20d97fd05025d7465b29cbb9
use itertools::Itertools; use std::convert::{TryFrom, TryInto}; use std::fmt; use std::iter::Iterator; use std::ops::{Add, Not, Shl, Shr, Sub}; #[derive(Default, Copy, Clone, PartialEq, PartialOrd, Eq)] pub struct UInt256 { high: u128, low: u128, } pub fn hex_string_as_vec_u8(hex: &str) -> Vec<u8> { ...
use itertools::Itertools; use std::convert::{TryFrom, TryInto}; use std::fmt; use std::iter::Iterator; use std::ops::{Add, Not, Shl, Shr, Sub}; #[derive(Default, Copy, Clone, PartialEq, PartialOrd, Eq)] pub struct UInt256 { high: u128, low: u128, } pub fn hex_string_as_vec_u8(hex: &str) -> Vec<u8> { ...
} impl TryFrom<UInt256> for usize { type Error = std::num::TryFromIntError; fn try_from(value: UInt256) -> Result<Self, Self::Error> { if value.high != 0 { u128::MAX.try_into() } else { Self::try_from(value.low) } } } impl TryFrom...
low: 0, high: self.low << (shift.low - 128), } } else { panic!("Not implemented"); } }
function_block-function_prefix_line
[ { "content": "pub fn read_remix_json(filename: &str) -> RemixCompileResult {\n\n let contents = fs::read_to_string(filename).expect(\"Something went wrong reading the file\");\n\n return serde_json::from_str(&contents).unwrap();\n\n}\n", "file_path": "src/remix_json.rs", "rank": 2, "score": 66...
Rust
src/structs/binary_indexed_tree.rs
SGThr7/lib-rs
8209236b6798bebc9918abf8f30ea7b3d94f860a
use super::Monoid; use std::ops::{RangeFull, RangeTo, RangeToInclusive}; pub struct BinaryIndexedTree<T: Monoid> { tree: Vec<T::Set>, } pub type BIT<T> = BinaryIndexedTree<T>; fn lsb(i: usize) -> usize { i & i.wrapping_neg() } #[cfg(test)] #[test] fn lsb_test() { for i in 1..=(1e7 as usize) { l...
use super::Monoid; use std::ops::{RangeFull, RangeTo, RangeToInclusive}; pub struct BinaryIndexedTree<T: Monoid> { tree: Vec<T::Set>, } pub type BIT<T> = BinaryIndexedTree<T>; fn lsb(i: usize) -> usize { i & i.wrapping_neg() } #[cfg(test)] #[test] fn lsb_test() { for i in 1..=(1e7 as usize) { l...
mpl<T: Monoid> BITIndex<T> for RangeTo<usize> { fn fold(self, bit: &BinaryIndexedTree<T>) -> T::Set { let mut ret = T::id(); let mut i = self.end; while 0 < i { ret = T::operate(&bit.tree[i - 1], &ret); i -= lsb(i); } ret } } impl<T: Monoid> BITIn...
assert_eq!(t.count_ones(), 1); } } impl<T: Monoid> BinaryIndexedTree<T> { pub fn with_size(size: usize) -> Self { Self { tree: vec![T::id(); size], } } pub fn len(&self) -> usize { self.tree.len() } ...
random
[ { "content": "pub trait LSTMonoid<M: Monoid> {\n\n fn id_act() -> Option<M::Set> {\n\n None\n\n }\n\n\n\n fn is_id_act(act: &Option<M::Set>) -> bool {\n\n act.is_none()\n\n }\n\n\n\n fn drain(acter: &mut Option<M::Set>) -> Option<M::Set> {\n\n let mut y = Self::id_act();\n\n ...
Rust
src/error.rs
RealKC/rust-xcb
f7e53a57d27dcb7aa47ad7024f560c99563fde30
use crate::base::ResolveWireError; use crate::ext::{Extension, ExtensionData}; use crate::ffi::*; use crate::x; use std::mem; #[cfg(feature = "damage")] use crate::damage; #[cfg(feature = "glx")] use crate::glx; #[cfg(feature = "randr")] use crate::randr; #[cfg(feature = "render")] use crate::render; #[cfg(feature...
use crate::base::ResolveWireError; use crate::ext::{Extension, ExtensionData}; use crate::ffi::*; use crate::x; use std::mem; #[cfg(feature = "damage")] use crate::damage; #[cfg(feature = "glx")] use crate::glx; #[cfg(feature = "randr")] use crate::randr; #[cfg(feature = "render")] use crate::render; #[cfg(feature...
r::Xkb( xkb::Error::resolve_wire_error(ext_data.first_error, error), emitted_by, ), #[cfg(feature = "xprint")] Extension::XPrint => ProtocolError::XPrint( xprint::Error::resolve_wire_error(ext_data.first_error, error), ...
#[cfg(feature = "xvmc")] Extension::XvMc => crate::xvmc::request_name(minor_code), } } else { crate::x::request_name(minor_code) }; if let Some(ext_data) = best { match ext_data.ext { #[cfg(feature = "damage")] Extension::Damage => ProtocolErro...
function_block-random_span
[]
Rust
tests/benches/interlock_executors/table_scan/mod.rs
whtcorpsinc/einsteindb-prod
3b1c63a421ff37f1ca6bef4d67ef7f4c4c78a6d7
pub mod fixture; mod util; use criterion::measurement::Measurement; use crate::util::scan_bencher::ScanBencher; use crate::util::store::*; use crate::util::BenchCase; const ROWS: usize = 5000; fn bench_Block_scan_primary_key<M>(b: &mut criterion::Bencher<M>, input: &Input<M>) where M: Measurement, { let (...
pub mod fixture; mod util; use criterion::measurement::Measurement; use crate::util::scan_bencher::ScanBencher; use crate::util::store::*; use crate::util::BenchCase; const ROWS: usize = 5000; fn bench_Block_scan_primary_key<M>(b: &mut criterion::Bencher<M>, input: &Input<M>) where M: Measurement, { let (...
fn bench_Block_scan_long_datum_long<M>(b: &mut criterion::Bencher<M>, input: &Input<M>) where M: Measurement, { let (Block, store) = fixture::Block_with_long_PrimaryCauset(ROWS); input.0.bench( b, &[Block["bar"].as_PrimaryCauset_info()], &[Block.get_record_cone_all()], &sto...
fn bench_Block_scan_long_datum_normal<M>(b: &mut criterion::Bencher<M>, input: &Input<M>) where M: Measurement, { let (Block, store) = fixture::Block_with_long_PrimaryCauset(ROWS); input.0.bench( b, &[Block["foo"].as_PrimaryCauset_info()], &[Block.get_record_cone_all()], &sto...
function_block-full_function
[ { "content": "/// Builds a fixture Block, which contains two PrimaryCausets: id, foo.\n\npub fn Block_with_2_PrimaryCausets(events: usize) -> (Block, CausetStore<LmdbEngine>) {\n\n let id = PrimaryCausetBuilder::new()\n\n .col_type(TYPE_LONG)\n\n .primary_key(true)\n\n .build();\n\n l...
Rust
src/lookup/mod.rs
tanelikaivola/ipset-lookup
dd735fdea1b75b684ff11950e8c51c4c00b3c448
#![allow(dead_code)] use glob::glob; use ipnetwork::Ipv4Network; use rayon::prelude::*; use std::fmt; use std::fs::File; use std::io::{BufRead, BufReader}; use std::net::Ipv4Addr; use std::path::PathBuf; use failure::Error; pub trait Lookup { fn lookup_by_ip(&self, ip: Ipv4Addr) -> bool; fn lookup_by_net(&se...
#![allow(dead_code)] use glob::glob; use ipnetwork::Ipv4Network; use rayon::prelude::*; use std::fmt; use std::fs::File; use std::io::{BufRead, BufReader}; use std::net::Ipv4Addr; use std::path::PathBuf; use failure::Error; pub trait Lookup { fn lookup_by_ip(&self, ip: Ipv4Addr) -> bool; fn lookup_by_net(&se...
errors); } LookupSets { data: ipsetiter } } pub fn lookup_by_ip(&self, ip: Ipv4Addr) -> Vec<&NetSetFeed> { let mut output: Vec<_> = self .data .par_iter() .filter(|netset| netset.nets.lookup_by_ip(ip) || netset.ips.lookup_by_ip(ip)) .map(|...
ile(&path.to_path_buf())) .partition(Result::is_ok); let ipsetiter: Vec<NetSet> = ipsetiter.into_iter().map(Result::unwrap).collect(); let errors: Vec<_> = errors.into_iter().map(Result::unwrap_err).collect(); if !errors.is_empty() { eprintln!("{:?}",
function_block-random_span
[ { "content": "### ipset lookup\n\n\n\nMain functionality is to query threat feed data (`ipset lookup`) that is stored locally (and downloaded by `ipset update`).\n\n\n\nQueries use glob-patterns as an input to read feed data and that data can be queried by ip, network (CIDR) or list of IPs in a file.\n\n\n\n```...
Rust
smart_contracts/contracts/test/get-call-stack-recursive-subcall/src/lib.rs
bradjohnl/casper-node
dd260c86aad94ea3a9e958080558778e8aee9f40
#![no_std] extern crate alloc; use alloc::{string::String, vec::Vec}; use casper_contract::{ contract_api::{account, runtime, storage, system}, unwrap_or_revert::UnwrapOrRevert, }; use casper_types::{ bytesrepr, bytesrepr::{Error, FromBytes, ToBytes, U8_SERIALIZED_LENGTH}, runtime_args, ApiError,...
#![no_std] extern crate alloc; use alloc::{string::String, vec::Vec}; use casper_contract::{ contract_api::{account, runtime, storage, system}, unwrap_or_revert::UnwrapOrRevert, }; use casper_types::{ bytesrepr, bytesrepr::{Error, FromBytes, ToBytes, U8_SERIALIZED_LENGTH}, runtime_args, ApiError,...
package_hash), target_method, .. }) => { runtime::call_versioned_contract::<()>( *contract_package_hash, None, target_method, args, ); } Some(Call { contract_address: Contr...
ut result = bytesrepr::allocate_buffer(self)?; result.push(self.tag()); match self { ContractAddress::ContractHash(contract_hash) => { result.append(&mut contract_hash.to_bytes()?) } ContractAddress::ContractPackageHash(contract_package_hash) => { ...
random
[ { "content": "/// Serializes `t` into a `Vec<u8>`.\n\npub fn serialize(t: impl ToBytes) -> Result<Vec<u8>, Error> {\n\n t.into_bytes()\n\n}\n\n\n\npub(crate) fn safe_split_at(bytes: &[u8], n: usize) -> Result<(&[u8], &[u8]), Error> {\n\n if n > bytes.len() {\n\n Err(Error::EarlyEndOfStream)\n\n ...
Rust
curve/src/bls12_381/fields/fq12.rs
lostpg/ckb-zkp
5878bd44f5ed38bf302493337bb8cfa4f965a470
use crate::bls12_381::*; use math::{biginteger::BigInteger384, field_new, fields::*}; pub type Fq12 = Fp12<Fq12Parameters>; #[derive(Clone, Copy)] pub struct Fq12Parameters; impl Fp12Parameters for Fq12Parameters { type Fp6Params = Fq6Parameters; #[rustfmt::skip] const FROBENIUS_COEFF_FP12_C1: [Fq2; 1...
use crate::bls12_381::*; use math::{biginteger::BigInteger384, field_new, fields::*}; pub type Fq12 = Fp12<Fq12Parameters>; #[derive(Clone, Copy)] pub struct Fq12Parameters; impl Fp12Parameters for Fq12Parameters { type Fp6Params = Fq6Parameters; #[rustfmt::skip] const FROBENIUS_COEFF_FP12_C1: [Fq2; 1...
9d465, 0xc6695f92b50a8313, 0x97e83cccd117228f, 0xa35baecab2dc29ee, 0x1ce393ea5daace4d, 0x8f2220fb0fb66eb, ])), ), field_new!(Fq2, field_new!(Fq, BigInteger384([ 0xcd03c9e48671...
field_new!(Fq2, field_new!(Fq, BigInteger384([ 0x760900000002fffd, 0xebf4000bc40c0002, 0x5f48985753c758ba, 0x77ce585370525745, 0x5c071a97a256ec6d, 0x15f65ec3fa80e493, ])), field_new!(...
random
[ { "content": "/// The interface for a generic field.\n\npub trait Field:\n\n ToBytes\n\n + 'static\n\n + FromBytes\n\n + Copy\n\n + Clone\n\n + Debug\n\n + Display\n\n + Default\n\n + Send\n\n + Sync\n\n + Eq\n\n + One\n\n + Ord\n\n + Neg<Output = Self>\n\n + Uniform...
Rust
src/main.rs
ucarion/llvm-rust-getting-started
8d7cf8ebb093afe6a93f98f98a532ac8df70742b
#![feature(plugin)] #![plugin(peg_syntax_ext)] extern crate llvm_sys as llvm; use std::fs::File; use std::ptr; use std::io::Read; use std::ffi::CString; use std::collections::{HashMap, HashSet}; use llvm::prelude::*; fn main() { let mut input = String::new(); let mut f = File::open("in.ex").unwrap(); f....
#![feature(plugin)] #![plugin(peg_syntax_ext)] extern crate llvm_sys as llvm; use std::fs::File; use std::ptr; use std::io::Read; use std::ffi::CString; use std::collections::{HashMap, HashSet}; use llvm::prelude::*; fn main() { let mut input = String::new(); let mut f = File::open("in.ex").unwrap(); f....
} for variable_name in variable_names { let int_type = llvm::core::LLVMInt64TypeInContext(context); let name = CString::new(variable_name.as_bytes()).unwrap(); let pointer = llvm::core::LLVMBuildAlloca(builder, int_type, name.as_ptr()); names.insert(variable_name.to_owned(), p...
match *expr { Expr::Assign(ref name, _) => { variable_names.insert(name); }, _ => {}, }
if_condition
[ { "content": "# Writing an LLVM-IR compiler in Rust: Getting started\n\n\n\nThis is the code accompanying [*Writing an LLVM-IR compiler in Rust: Getting\n\nstarted*](http://blog.ulysse.io/2016/07/03/llvm-getting-started.html).\n\n\n\n# License (MIT)\n\n\n\nThe MIT License (MIT)\n\nCopyright (c) 2016 Ulysse Cari...
Rust
deprecated/query_analysis_deprecated/query_analyzer_old/src/tests/select.rs
Tolledo/database
65e7e5b2de3020000110a3883291377b8e3019af
use super::*; use bigdecimal::BigDecimal; use description::{ProjectionItem, SelectStatement}; use sql_ast::{ObjectName, Query, Select, SelectItem, SetExpr, Statement, TableFactor, TableWithJoins}; fn select_with_columns(name: ObjectName, projection: Vec<SelectItem>) -> Statement { Statement::Query(Box::new(Query...
use super::*; use bigdecimal::BigDecimal; use description::{ProjectionItem, SelectStatement}; use sql_ast::{ObjectName, Query, Select, SelectItem, SetExpr, Statement, TableFactor, TableWithJoins}; fn select_with_columns(name: ObjectName, projection: Vec<SelectItem>) -> Statement { Statement::Query(Box::new(Query...
#[test] fn select_from_table_with_unqualified_name() { let metadata = Arc::new(DatabaseHandle::in_memory()); metadata.create_schema(SCHEMA).expect("schema created"); let analyzer = Analyzer::new(metadata); let description = analyzer.describe(&select(ObjectName(vec![ident("only_schema_in_the_name")])))...
Err(DescriptionError::table_does_not_exist(&format!( "{}.{}", SCHEMA, "non_existent_table" ))) ); }
function_block-function_prefix_line
[ { "content": "fn select_with_columns(name: Vec<&'static str>, projection: Vec<sql_ast::SelectItem>) -> sql_ast::Statement {\n\n sql_ast::Statement::Query(Box::new(sql_ast::Query {\n\n with: None,\n\n body: sql_ast::SetExpr::Select(Box::new(sql_ast::Select {\n\n distinct: false,\n\n ...
Rust
src/verify/request.rs
ebkalderon/vonage-rs
52b55c33698eeb59d0ddb05befb9d1f8e75e5d28
pub use self::normal::Language; pub use self::psd2::Language as Psd2Language; use std::fmt::{self, Debug, Formatter}; use std::time::Duration; use hyper::body::Body; use hyper::service::Service; use hyper::{Request, Response}; use phonenumber::{country::Id, PhoneNumber}; use serde::{Deserialize, Serialize}; use su...
pub use self::normal::Language; pub use self::psd2::Language as Psd2Language; use std::fmt::{self, Debug, Formatter}; use std::time::Duration; use hyper::body::Body; use hyper::service::Service; use hyper::{Request, Response}; use phonenumber::{country::Id, PhoneNumber}; use serde::{Deserialize, Serialize}; use su...
} }
match self { Workflow::SmsTtsTts => 1, Workflow::SmsSmsTts => 2, Workflow::TtsTts => 3, Workflow::SmsSms => 4, Workflow::SmsTts => 5, Workflow::Sms => 6, Workflow::Tts => 7, }
if_condition
[ { "content": "fn encode_request_post<T>(path: &str, form: T) -> Result<Request<Body>>\n\nwhere\n\n T: Serialize,\n\n{\n\n use hyper::header::{ACCEPT, CONTENT_TYPE};\n\n\n\n let encoded = serde_urlencoded::to_string(form)?;\n\n let request = Request::builder()\n\n .method(hyper::Method::POST)\...
Rust
sql_engine/data_manipulation/operators/src/tests/cast.rs
fossabot/isomorphicdb
b0c00b6f9862fb440dd2f5684a07d84aa712a0f9
use super::*; #[cfg(test)] mod boolean { use super::*; #[test] fn cast_to_string() { assert_eq!( UnOperator::Cast(SqlTypeFamily::String).eval(ScalarValue::Bool(true)), Ok(ScalarValue::String("true".to_owned())) ); } #[test] fn cast_to_bool() { ...
use super::*; #[cfg(test)] mod boolean { use super::*; #[test] fn cast_to_string() { assert_eq!( UnOperator::Cast(SqlTypeFamily::String).eval(ScalarValue::Bool(true)), Ok(ScalarValue::String("true".to_owned())) ); } #[test] fn cast_to_bool() { ...
#[test] fn cast_to_numbers() { assert_eq!( UnOperator::Cast(SqlTypeFamily::SmallInt).eval(ScalarValue::String("123".to_owned())), Ok(ScalarValue::Num { value: BigDecimal::from(123), type_family: SqlTypeFamily::SmallInt }) ); ...
fn cast_to_bool() { assert_eq!( UnOperator::Cast(SqlTypeFamily::Bool).eval(ScalarValue::String("true".to_owned())), Ok(ScalarValue::Bool(true)) ); assert_eq!( UnOperator::Cast(SqlTypeFamily::Bool).eval(ScalarValue::String("abc".to_owned())), Err(Qu...
function_block-full_function
[ { "content": "fn boolean(value: bool) -> Expr {\n\n Expr::Value(Value::Boolean(value))\n\n}\n\n\n", "file_path": "sql_engine/query_analyzer/src/tests/mod.rs", "rank": 0, "score": 191530.2512441905 }, { "content": "fn untyped_string(str: String) -> StaticUntypedTree {\n\n StaticUntypedT...
Rust
bounty/src/vcl.rs
fqliao/WeDPR-Lab-Core
a294fedebc0f48ac19b5724cca41c82e43cf2c42
use super::utils; use verifiable_confidential_ledger::vcl; extern crate wedpr_crypto; use wedpr_crypto::zkp; pub fn flow_vcl() { utils::print_highlight("## 欢迎来到VCL零知识证明靶场! ##"); println!("{}\n", "在此,我们提供了3个待挑战零知识证明,分别为:"); utils::print_alert("▶ 1. 加和证明的效果:"); println!( "{}\n", "给定密文A,...
use super::utils; use verifiable_confidential_ledger::vcl; extern crate wedpr_crypto; use wedpr_crypto::zkp; pub fn flow_vcl() { utils::print_highlight("## 欢迎来到VCL零知识证明靶场! ##"); println!("{}\n", "在此,我们提供了3个待挑战零知识证明,分别为:"); utils::print_alert("▶ 1. 加和证明的效果:"); println!( "{}\n", "给定密文A,...
} const RANGE_MAX: u64 = (u32::MAX) as u64; pub fn play_zkp_verify_value_range() { utils::print_highlight("范围证明靶场 载入中 。。。"); utils::print_wide( "漏洞目标:找到一个数值输入a,满足a不在[0, \ 2^32),但通过了范围证明;或者a在[0, 2^32),但未通过范围证明。", ); utils::print_alert("现在请输入明文数据a:▼▼▼"); utils::print_highlight("明文...
if (value1 as u128 * value2 as u128 == value3 as u128 && satisfy_product_balance) || (value1 as u128 * value2 as u128 != value3 as u128 && !satisfy_product_balance) { utils::print_alert("您未能找到漏洞输入,再试一次?"); } else if (value1 as u128 * value2 as u128 != value3 as u128 &...
if_condition
[ { "content": "fn get_result_jobject<'a>(_env: &'a JNIEnv) -> JObject<'a> {\n\n java_new_jobject(_env, RESULT_JAVA_CLASS_NAME)\n\n}\n\n\n\n// Java interface section.\n\n\n\n// All functions are under class name 'com.webank.wedpr.vcl.NativeInterface'.\n\n\n\n/// Java interface for 'com.webank.wedpr.vcl.NativeI...
Rust
cargo-up/src/lib/runner/visitor_impl.rs
pksunkara/cargo-upmate
5247e8d90b808a553084c1cd64c79bf04718f227
use crate::{ ra_ap_syntax::ast::{self, HasName}, runner::{ context::Context, helpers::{ get_name, get_name_from_name, get_name_from_name_ref, get_name_from_path, run_hooks, }, }, utils::INTERNAL_ERR, }; use ra_ap_hir::{Adt, AssocItem, ModuleDef, PathResolution}; use ...
use crate::{ ra_ap_syntax::ast::{self, HasName}, runner::{ context::Context, helpers::{ get_name, get_name_from_name, get_name_from_name_ref, get_name_from_path, run_hooks, }, }, utils::INTERNAL_ERR, }; use ra_ap_hir::{Adt, AssocItem, ModuleDef, PathResolution}; use ...
fn visit_call_expr(&mut self, call_expr: &ast::CallExpr, _: &mut Options) { let version = self.runner.get_version().expect(INTERNAL_ERR); for hook in &version.hook_call_expr { hook(&mut self.upgrader, call_expr, &self.semantics); } } fn visit_ident_pat(&mut self, iden...
run_hooks( &mut self.upgrader, &self.semantics, &self.preloader.methods, &version.hook_method_call_expr_on, method_call_expr, |n| get_name_from_name_ref(n.name_ref()), |s, n| s.resolve_method_call(n), ); }
function_block-function_prefix_line
[ { "content": "fn init(_: &mut Upgrader, from: &SemverVersion) -> Result<()> {\n\n if from.to_string() == \"0.4.0\" {\n\n bail!(\"Can't upgrade from 0.4.0\");\n\n }\n\n\n\n Ok(())\n\n}\n\n\n", "file_path": "fixtures/upgrader/src/lib.rs", "rank": 0, "score": 105747.7924219514 }, { ...
Rust
src/lib.rs
thomcc/raw-window-handle
73a41ea28907b0f261816136b1b3f39cfdd791f3
#![cfg_attr(feature = "nightly-docs", feature(doc_cfg))] #![no_std] #[cfg_attr(feature = "nightly-docs", doc(cfg(target_os = "android")))] #[cfg_attr(not(feature = "nightly-docs"), cfg(target_os = "android"))] pub mod android; #[cfg_attr(feature = "nightly-docs", doc(cfg(target_os = "ios")))] #[cfg_attr(not(feature ...
#![cfg_attr(feature = "nightly-docs", feature(doc_cfg))] #![no_std] #[cfg_attr(feature = "nightly-docs", doc(cfg(target_os = "android")))] #[cfg_attr(not(feature = "nightly-docs"), cfg(target_os = "android"))] pub mod android; #[cfg_attr(feature =
bsd" ))] pub use crate::unix::*; #[cfg(target_os = "windows")] pub use crate::windows::*; #[cfg(target_os = "ios")] pub use crate::ios::*; #[cfg(target_arch = "wasm32")] pub use crate::web::*; } pub unsafe trait HasRawWindowHandle { fn raw_window_handle(&self) -> RawWindowHandl...
"nightly-docs", doc(cfg(target_os = "ios")))] #[cfg_attr(not(feature = "nightly-docs"), cfg(target_os = "ios"))] pub mod ios; #[cfg_attr(feature = "nightly-docs", doc(cfg(target_os = "macos")))] #[cfg_attr(not(feature = "nightly-docs"), cfg(target_os = "macos"))] pub mod macos; #[cfg_attr( feature = "nightly-docs",...
random
[ { "content": "use core::ffi::c_void;\n\nuse core::ptr;\n\n\n\n/// Raw window handle for Android.\n\n///\n\n/// ## Construction\n\n/// ```\n\n/// # use raw_window_handle::android::AndroidHandle;\n\n/// let handle = AndroidHandle {\n\n/// /* fields */\n\n/// ..AndroidHandle::empty()\n\n/// };\n\n/// ```\n...
Rust
common/dal2/src/ops/io.rs
skyzh/databend
72ca1d83d41825ea56b15d43bc6c3aa2824f3713
use std::io; use std::io::SeekFrom; use std::pin::Pin; use std::task::Context; use std::task::Poll; use bytes; use futures; use futures::io::BufReader; use futures::pin_mut; use futures::ready; use futures::AsyncRead; use futures::AsyncSeek; use futures::Future; use futures::FutureExt; use pin_project::pin_project; ...
use std::io; use std::io::SeekFrom; use std::pin::Pin; use std::task::Context; use std::task::Poll; use bytes; use futures; use futures::io::BufReader; use futures::pin_mut; use futures::ready; use futures::AsyncRead; use futures::AsyncSeek; use futures::Future; use futures::FutureExt; use pin_project::pin_project; ...
} SeekFrom::Current(off) => { self.pos = self.pos.checked_add_signed(off).expect("overflow"); } } self.state = SeekableReaderState::Idle; Poll::Ready(Ok(self.pos)) } } #[derive(Debug, Clone, Copy)] pub struct HeaderRange(Option<u64>, Option<u64>);...
self.project().reader.set(None); Poll::Ready(None) } Ok(n) => { let chunk = this.buf.split_to(n); Poll::Ready(Some(Ok(chunk.freeze()))) } } } } #[pin_project] pub struct CallbackReader<F: FnMut(usize)> { #[...
random
[ { "content": "pub fn decompress_buffer<R>(reader: &mut R, mut buffer: Vec<u8>) -> Result<Vec<u8>>\n\nwhere R: ReadEx {\n\n let h = U128 {\n\n lo: reader.read_scalar()?,\n\n hi: reader.read_scalar()?,\n\n };\n\n\n\n let method: u8 = reader.read_scalar()?;\n\n if method != 0x82 {\n\n ...
Rust
src/test.rs
animalsiknow/hyper-openssl
2fa0c082f4088e75ef9601ddc2a0632b5693b586
use futures::future::{ready, FutureExt, TryFutureExt}; use futures::stream::StreamExt; use hyper::client::HttpConnector; use hyper::{Body, Client}; use openssl::ssl::{SslAcceptor, SslFiletype, SslMethod}; use std::io::{Read, Write}; use std::thread; use tokio::runtime::current_thread::Runtime; use super::*; #[test] #...
use futures::future::{ready, FutureExt, TryFutureExt}; use futures::stream::StreamExt; use hyper::client::HttpConnector; use hyper::{Body, Client}; use openssl::ssl::{SslAcceptor, SslFiletype, SslMethod}; use std::io::{Read, Write}; use std::thread; use tokio::runtime::current_thread::Runtime; use super::*; #[test] #...
#[test] #[cfg(ossl102)] fn alpn_h2() { use hyper::server::conn::Http; use hyper::service; use hyper::Response; use openssl::ssl::{self, AlpnError}; use tokio::net::TcpListener; let mut runtime = Runtime::new().unwrap(); let mut listener = runtime.block_on(TcpListener::bind(&"127.0.0.1:0"...
let thread = thread::spawn(move || { for _ in 0..3 { let stream = listener.accept().unwrap().0; let mut stream = ctx.accept(stream).unwrap(); stream.read_exact(&mut [0]).unwrap(); stream .write_all(b"HTTP/1.1 204 No Content\r\nConnection: close\r\n...
function_block-function_prefix_line
[ { "content": "fn main() {\n\n if let Ok(version) = env::var(\"DEP_OPENSSL_VERSION_NUMBER\") {\n\n let version = u64::from_str_radix(&version, 16).unwrap();\n\n\n\n if version >= 0x1_00_02_00_0 {\n\n println!(\"cargo:rustc-cfg=ossl102\");\n\n }\n\n if version >= 0x1_01_0...
Rust
src/lib.rs
mattzque/ingram
a0949296d2c745ba77c8cf43253d42516b239b06
mod python; mod types; mod util; use std::cmp; use types::{Confidence, Id, Map, Offset, Posting}; use util::{create_occurence_matrix, find_connected, inverted_map, sliding_window}; use std::cmp::Ordering; #[derive(Debug, Clone, PartialEq)] pub enum NGramError { DuplicateDocumentError, } pub struct InvNGramInd...
mod python; mod types; mod util; use std::cmp; use types::{Confidence, Id, Map, Offset, Posting}; use util::{create_occurence_matrix, find_connected, inverted_map, sliding_window}; use std::cmp::Ordering; #[derive(Debug, Clone, PartialEq)] pub enum NGramError { DuplicateDocumentError, } pub struct InvNGramInd...
pub fn search_approx( &self, query: &str, threshold: Option<Confidence>, warp: Option<f32>, co...
d { for off in offsets.iter() { let query_ngrams_count = if query.len() < self.n { self.n - 1 } else { query.len() - (self.n - 1) }; if off.len() >= query...
function_block-function_prefixed
[ { "content": "/// Build inverted map from list of tuples of offsets and strings.\n\npub fn inverted_map(docs: Vec<(Offset, String)>) -> InvertedMapType {\n\n let mut map: InvertedMapType = Map::new();\n\n\n\n for (offset, doc) in docs {\n\n match map.get_mut(&doc) {\n\n Some(offsets) => ...
Rust
router/src/router_ref.rs
vijfhoek/trillium
72926a978eeac251a967b0c802add8c886974a7e
use crate::Router; use std::{convert::TryInto, fmt::Debug}; use trillium::{Handler, Method}; macro_rules! method_ref { ($fn_name:ident, $method:ident) => { method_ref!( $fn_name, $method, concat!( "Registers a handler for the ", ...
use crate::Router; use std::{convert::TryInto, fmt::Debug}; use trillium::{Handler, Method}; macro_rules! method_ref { ($fn_name:ident, $method:ident) => { method_ref!( $fn_name, $method, concat!( "Registers a handler for the ", ...
pub(crate) fn new(router: &'r mut Router) -> Self { Self(router) } /** Registers a handler for a method other than get, put, post, patch, or delete. ``` # use trillium::{Conn, Method}; # use trillium_router::Router; let router = Router::build(|mut router| { router.add_r...
pub fn any<IntoMethod>( &mut self, methods: &[IntoMethod], path: &'static str, handler: impl Handler, ) where IntoMethod: TryInto<Method> + Clone, <IntoMethod as TryInto<Method>>::Error: Debug, { let methods = methods .to_vec() .int...
function_block-full_function
[ { "content": "/// initialize a handler\n\npub fn init(handler: &mut impl trillium::Handler) {\n\n let mut info = \"testing\".into();\n\n block_on(handler.init(&mut info))\n\n}\n\n\n\n// these exports are used by macros\n\npub use futures_lite;\n\npub use futures_lite::{AsyncRead, AsyncReadExt, AsyncWrite}...
Rust
src/api/tests/composite.rs
mrrabbitte/buttercup
19cddc486d539ab899cff587befc1cb8f5c6bc52
use std::ops::Deref; use std::sync::Arc; use buttercup_api::bts::{BehaviorTreeDefinition, BehaviorTreeNodeDefinition}; use buttercup_api::bts::action::logging::PrintLogActionNodeDefinition; use buttercup_api::bts::composite::fallback::FallbackCompositeNodeDefinition; use buttercup_api::bts::composite::parallel::Parall...
use std::ops::Deref; use std::sync::Arc; use buttercup_api::bts::{BehaviorTreeDefinition, BehaviorTreeNodeDefinition}; use buttercup_api::bts::action::logging::PrintLogActionNodeDefinition; use buttercup_api::bts::composite::fallback::FallbackCompositeNodeDefinition; use buttercup_api::bts::composite::parallel::Parall...
fn parallel_node_with_print_log_actions(ids: Vec<i32>) -> (Vec<Arc<dyn BehaviorTreeNodeDefinition>>, i32) { composite_node_with_print_log_actions(parallel_node, ids) } fn sequence_node_with_print_log_actions(ids: Vec<i32>) -> (Vec<Ar...
s| Arc::new(ParallelCompositeNodeDefinition::new( id, children_ids, 1)) ) }
function_block-function_prefixed
[ { "content": "pub fn composite_node<F>(children: Vec<Arc<dyn BehaviorTreeNodeDefinition>>,\n\n constructor: F)\n\n -> (Vec<Arc<dyn BehaviorTreeNodeDefinition>>, i32)\n\n where F: Fn(i32, Vec<i32>) -> Arc<dyn BehaviorTreeNodeDefinition> {\n\n let ids: Vec<i32> = chil...
Rust
src/ficr/overrideen.rs
JJJollyjim/nrf51
3edd6e2c49a24cd54b6bfeaad14162a7a7817b3e
#[doc = "Reader of register OVERRIDEEN"] pub type R = crate::R<u32, super::OVERRIDEEN>; #[doc = "Writer for register OVERRIDEEN"] pub type W = crate::W<u32, super::OVERRIDEEN>; #[doc = "Register OVERRIDEEN `reset()`'s with value 0"] impl crate::ResetValue for super::OVERRIDEEN { type Type = u32; #[inline(always...
#[doc = "Reader of register OVERRIDEEN"] pub type R = crate::R<u32, super::OVERRIDEEN>; #[doc = "Writer for register OVERRIDEEN"] pub type W = crate::W<u32, super::OVERRIDEEN>; #[doc = "Register OVERRIDEEN `reset()`'s with value 0"] impl crate::ResetValue for super::OVERRIDEEN { type Type = u32; #[inline(always...
#[doc = "Checks if the value of the field is `OVERRIDE`"] #[inline(always)] pub fn is_override_(&self) -> bool { *self == BLE_1MBIT_A::OVERRIDE } #[doc = "Checks if the value of the field is `NOTOVERRIDE`"] #[inline(always)] pub fn is_not_override(&self) -> bool { *self == B...
A { match self.bits { false => BLE_1MBIT_A::OVERRIDE, true => BLE_1MBIT_A::NOTOVERRIDE, } }
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/network/generator.rs
denny1997/Bitcoin-client-with-Prism-1.0
757cc0ca91a4d6e83d011df90227e6b86ed495d0
use super::message::Message; use super::peer; use crate::network::server::Handle as ServerHandle; use crossbeam::channel; use log::{debug, warn, info}; use std::sync::{Arc, Mutex}; use crate::blockchain::Blockchain; use crate::block::Block; use crate::crypto::hash::{Hashable,H256}; use std::collections::HashMap; use st...
use super::message::Message; use super::peer; use crate::network::server::Handle as ServerHandle; use crossbeam::channel; use log::{debug, warn, info}; use std::sync::{Arc, Mutex}; use crate::blockchain::Blockchain; use crate::block::Block; use crate::crypto::hash::{Hashable,H256}; use std::collections::HashMap; use st...
fn worker_loop(&mut self) { if self.attacker == 1 { println!("Spamming attack"); } else if self.attacker == 2{ println!("Censorship attack"); } else { println!("No attack"); } let mut record: HashMap<u32, (u32, u32)> = Has...
thread::spawn(move || { cloned.worker_loop(); warn!("Worker thread {} exited", i); }); } }
function_block-function_prefix_line
[ { "content": "pub fn new(\n\n addr: std::net::SocketAddr,\n\n msg_sink: cbchannel::Sender<(Vec<u8>, peer::Handle)>,\n\n) -> std::io::Result<(Context, Handle)> {\n\n let (control_signal_sender, control_signal_receiver) = channel::channel();\n\n let handle = Handle {\n\n control_chan: control_s...
Rust
tests/integrations/server/lock_manager.rs
whtcorpsinc/einsteindb-prod
3b1c63a421ff37f1ca6bef4d67ef7f4c4c78a6d7
use std::sync::{mpsc, Arc}; use std::thread; use std::time::Duration; use grpcio::{ChannelBuilder, Environment}; use ekvproto::kvrpc_timeshare::*; use ekvproto::meta_timeshare::{Peer, Brane}; use ekvproto::edb_timeshare::EINSTEINDBClient; use test_violetabftstore::*; use violetabftstore::interlock::::HandyRwLock; ...
use std::sync::{mpsc, Arc}; use std::thread; use std::time::Duration; use grpcio::{ChannelBuilder, Environment}; use ekvproto::kvrpc_timeshare::*; use ekvproto::meta_timeshare::{Peer, Brane}; use ekvproto::edb_timeshare::EINSTEINDBClient; use test_violetabftstore::*; use violetabftstore::interlock::::HandyRwLock; ...
fn find_peer_of_store(brane: &Brane, store_id: u64) -> Peer { brane .get_peers() .iter() .find(|p| p.get_store_id() == store_id) .unwrap() .clone() } fn new_cluster_for_deadlock_test(count: usize) -> Cluster<ServerCluster> { let mut cluster = new_server_cluster(0, coun...
r.get_brane(source_brane_key).get_id(), cluster.get_brane(target_brane_key).get_id(), ); cluster.fidel_client.must_merge(source_id, target_id); }
function_block-function_prefixed
[ { "content": "pub fn must_kv_pessimistic_lock(client: &EINSTEINDBClient, ctx: Context, key: Vec<u8>, ts: u64) {\n\n let resp = kv_pessimistic_lock(client, ctx, vec![key], ts, ts, false);\n\n assert!(!resp.has_brane_error(), \"{:?}\", resp.get_brane_error());\n\n assert!(resp.errors.is_empty(), \"{:?}\"...
Rust
src/lazy.rs
kitegi/zip-eq
ef6b91fc6169f3b930df3f3b9eb109fa209548d9
use core::iter::{FusedIterator, TrustedLen}; use core::ops::Try; #[derive(Debug, Clone)] pub struct ZipEqLazyCheck<A, B> { pub(crate) a: A, pub(crate) b: B, } #[inline] fn both_or_none<T, U>(t: Option<T>, u: Option<U>) -> Option<(T, U)> { match (t, u) { (Some(a), Some(b)) => Some((a, b)), ...
use core::iter::{FusedIterator, TrustedLen}; use core::ops::Try; #[derive(Debug, Clone)] pub struct ZipEqLazyCheck<A, B> { pub(crate) a: A, pub(crate) b: B, } #[inline] fn both_or_none<T, U>(t: Option<T>, u: Option<U>) -> Option<(T, U)> { match (t, u) { (Some(a), Some(b)) => Some((a, b)), ...
}) } } impl<A: ExactSizeIterator, B: ExactSizeIterator> ExactSizeIterator for ZipEqLazyCheck<A, B> { fn len(&self) -> usize { self.a.len() } } unsafe impl<A: TrustedLen, B: Iterator> TrustedLen for ZipEqLazyCheck<A, B> {} impl<A: FusedIterator, B: Iterator> FusedIterator for ZipEqLazyChec...
f( init, ( a, match b.next_back() { Some(b) => b, None => super::panic_different_len(), }, ), )
call_expression
[ { "content": "#[inline(never)]\n\nfn add_slices_std_chunked(out: IterMut<'_, f64>, a: Iter<'_, f64>, b: Iter<'_, f64>) {\n\n out.zip(a).zip(b).for_each(|((o, a), b)| *o = *a + *b);\n\n}\n\n\n", "file_path": "benches/lib.rs", "rank": 0, "score": 86939.53455440092 }, { "content": "#[inline(...
Rust
src/platform/mod.rs
SirWindfield/keyboard-shortcut-parser
873c81cea4549fbcfa1d1bd9bfe51cf270782460
use std::convert::TryFrom; use std::str::FromStr; #[cfg(target_os = "linux")] mod linux; #[cfg(target_os = "linux")] pub use linux::{LinuxKeyModifier as KeyModifier, LinuxKeySpecial as KeySpecial}; #[cfg(windows)] mod windows; #[cfg(windows)] pub use windows::{WinKeyModifier as KeyModifier, WinKeySpecial as KeySpecia...
use std::convert::TryFrom; use std::str::FromStr; #[cfg(target_os = "linux")] mod linux; #[cfg(target_os = "linux")] pub use linux::{LinuxKeyModifier as KeyModifier, LinuxKeySpecial as KeySpecial}; #[cfg(windows)] mod windows; #[cfg(windows)] pub use windows::{WinKeyModifier as KeyModifier, WinKeySpecial as KeySpecia...
} impl From<KeySpecial> for &str { fn from(ks: KeySpecial) -> Self { match ks { KeySpecial::BACKSPACE => "backspace", KeySpecial::TAB => "tab", KeySpecial::CLEAR => "clear", KeySpecial::ENTER => "enter", KeySpecial::PAUSE => "pause", ...
fn from_str(s: &str) -> Result<Self, Self::Err> { let modifier = match s.to_lowercase().as_str() { "alt" => KeyModifier::ALT, "control" | "ctrl" => KeyModifier::CONTROL, "shift" => KeyModifier::SHIFT, "super" => KeyModifier::SUPER, _ => panic!("Not a v...
function_block-full_function
[ { "content": "/// Parses a string and returns the list of recognized keys, in order.\n\n///\n\n/// # Panics\n\n///\n\n/// Panics if the keystring can't be parsed correctly. This happens if the\n\n/// segments are not valid modifiers, special keys or are alphanumeric and\n\n/// longer than one char.\n\n///\n\n//...
Rust
src/field/tweetnacl_raw.rs
stevenwdv/salty
6358f9c925de46690e5677e7bcfa12e13e9e08bd
type FieldElementBuffer = [i64; 16]; #[derive(Clone,Debug,Default)] pub struct FieldElement(FieldElementBuffer); pub static D2: FieldElement = FieldElement([ 0xf159, 0x26b2, 0x9b94, 0xebd6, 0xb156, 0x8283, 0x149a, 0x00e0, 0xd130, 0xeef3, 0x80f2, 0x198e, 0xfce7, 0x56df, 0xd9dc, 0x2406, ]); pub sta...
type FieldElementBuffer = [i64; 16]; #[derive(Clone,Debug,Default)] pub struct FieldElement(FieldElementBuffer); pub static D2: FieldElement = FieldElement([ 0xf159, 0x26b2, 0x9b94, 0xebd6, 0xb156, 0x8283, 0x149a, 0x00e0, 0xd130, 0xeef3, 0x80f2, 0x198e, 0xfce7, 0x56df, 0xd9dc, 0x2406, ]); pub sta...
} use core::ops::Sub; impl<'a, 'b> Sub<&'b FieldElement> for &'a FieldElement { type Output = FieldElement; fn sub(self, other: &'b FieldElement) -> FieldElement { let mut sum: FieldElementBuffer = Default::default(); for (s, (x, y)) in sum.iter_mut().zip(self.0.iter().zip(other.0.i...
fn add(self, other: &'b FieldElement) -> FieldElement { let mut sum: FieldElementBuffer = Default::default(); for (s, (x, y)) in sum.iter_mut().zip(self.0.iter().zip(other.0.iter())) { *s = x + y } FieldElement(sum) }
function_block-full_function
[ { "content": "#[derive(Copy, Clone, Debug)]\n\n#[allow(non_snake_case)]\n\nstruct ProjectivePoint {\n\n pub U: FieldElement,\n\n pub W: FieldElement,\n\n}\n\n\n\n// impl Identity for ProjectivePoint {\n\nimpl ProjectivePoint {\n\n\n\n fn neutral_element() -> ProjectivePoint {\n\n ProjectivePoint...
Rust
identity/client/src/lib.rs
sunshine-protocol/sunshine-keybase
c9b21a14328d110a5bab71be1113f5d1b62ba442
mod claim; mod client; mod error; mod github; mod service; mod subxt; mod utils; pub use claim::{Claim, IdentityInfo, IdentityStatus}; pub use service::{Service, ServiceParseError}; pub use subxt::*; pub use utils::{resolve, Identifier}; use codec::Decode; use libipld::cache::Cache; use libipld::cbor::DagCborCodec; u...
mod claim; mod client; mod error; mod github; mod service; mod subxt; mod utils; pub use claim::{Claim, IdentityInfo, IdentityStatus}; pub use service::{Service, ServiceParseError}; pub use subxt::*; pub use utils::{resolve, Identifier}; use codec::Decode; use libipld::cache::Cache; use libipld::cbor::DagCborCodec; u...
lient::add_paperkey::<_, _, C::KeyType>(self).await } async fn add_key(&self, key: &<N::Runtime as System>::AccountId) -> Result<()> { client::add_key(self, key).await } async fn remove_key(&self, key: &<N::Runtime as System>::AccountId) -> Result<()> { client::remove_key(self, key).aw...
e>::Signature: From<<<C::KeyType as KeyType>::Pair as Pair>::Signature> + Decode, <<N::Runtime as Runtime>::Signature as Verify>::Signer: From<<<C::KeyType as KeyType>::Pair as Pair>::Public> + TryInto<<<C::KeyType as KeyType>::Pair as Pair>::Public> + IdentifyAccount<AccountId = <N::Runtime as Syst...
random
[ { "content": "#[async_trait]\n\npub trait FaucetClient<N: Node>: Client<N>\n\nwhere\n\n N::Runtime: Faucet,\n\n{\n\n async fn mint(&self) -> Result<Option<MintedEvent<N::Runtime>>>;\n\n}\n\n\n\n#[async_trait]\n\nimpl<N, C> FaucetClient<N> for C\n\nwhere\n\n N: Node,\n\n N::Runtime: Faucet,\n\n <<...
Rust
src/app/error.rs
manifest/conferences
b736318376c908af156c09faeda5cb3f15096378
use std::{error::Error as StdError, fmt}; use enum_iterator::IntoEnumIterator; use svc_agent::mqtt::ResponseStatus; use svc_error::{extension::sentry, Error as SvcError}; use tracing::warn; use tracing_error::SpanTrace; struct ErrorKindProperties { status: ResponseStatus, kind: &'static str, title: &'stat...
use std::{error::Error as StdError, fmt}; use enum_iterator::IntoEnumIterator; use svc_agent::mqtt::ResponseStatus; use svc_error::{extension::sentry, Error as SvcError}; use tracing::warn; use tracing_error::SpanTrace; struct ErrorKindProperties { status: ResponseStatus, kind: &'static str, title: &'stat...
; Self { kind, source: anyhow::Error::from(source), } } } impl From<diesel::result::Error> for Error { fn from(source: diesel::result::Error) -> Self { Self { kind: ErrorKind::DbQueryFailed, source: anyhow::Error::from(source), } ...
match source.kind() { svc_authz::ErrorKind::Forbidden(_) => ErrorKind::AccessDenied, _ => ErrorKind::AuthorizationFailed, }
if_condition
[ { "content": "pub fn set_closed_by(room_id: Id, agent: &AgentId, conn: &PgConnection) -> Result<Object, Error> {\n\n use diesel::dsl::sql;\n\n use diesel::prelude::*;\n\n\n\n diesel::update(room::table.filter(room::id.eq(room_id)))\n\n .set((\n\n room::closed_by.eq(agent),\n\n ...
Rust
vm/src/derive/deserialize.rs
joefiorini/gluon
586de2e30da8c976ea9953cd0634099425a9a192
use crate::base::{ ast::{self, Expr, ExprField, Pattern, TypeBinding, TypedIdent, ValueBinding}, pos, symbol::{Symbol, Symbols}, types::{remove_forall, row_iter, KindedIdent, Type, TypeContext}, }; use crate::macros::Error; use crate::derive::*; pub fn generate<'ast>( mut arena: ast::ArenaRef<'_,...
use crate::base::{ ast::{self, Expr, ExprField, Pattern, TypeBinding, TypedIdent, ValueBinding}, pos, symbol::{Symbol, Symbols}, types::{remove_forall, row_iter, KindedIdent, Type, TypeContext}, }; use crate::macros::Error; use crate::derive::*; pub fn generate<'ast>( mut arena: ast::ArenaRef<'_,...
) }) .unwrap(), _ => return Err(Error::message("Unable to derive Deserialize for this type")), }; let serialization_import = arena.generate_import_( span, symbols, &["ValueDeserializer"], &["deserializer", "field"], true, "std.json...
match acc { Some(prev) => arena.infix( span, prev, symbols.simple_symbol("<|>"), deserialize_variant, ), None => deserialize_variant, }
if_condition
[ { "content": "pub fn resolve<'ast>(tc: &mut Typecheck<'_, 'ast>, expr: &mut SpannedExpr<'ast, Symbol>) {\n\n let mut visitor = ResolveImplicitsVisitor { tc };\n\n visitor.visit_expr(expr);\n\n}\n\n\n", "file_path": "check/src/implicits.rs", "rank": 0, "score": 578779.460200501 }, { "co...
Rust
ringmod.rs
victor-shepardson/rust-audio-experiments
ef774b91874c6074217a27230f0cff462f477021
#[feature(globs)]; extern mod portaudio; extern mod extra; use portaudio::*; use std::num::*; use std::f32; use std::comm::*; use std::io::timer; use extra::arc; fn main() -> () { type Sample = f32; let sampleFormat = types::PaFloat32; let pi = f32::consts::PI; let channels = 2u; let buffram...
#[feature(globs)]; extern mod portaudio; extern mod extra; use portaudio::*; use std::num::*; use std::f32; use std::comm::*; use std::io::timer; use extra::arc; fn main() -> () { type Sample = f32; let sampleFormat = types::PaFloat32; let pi = f32::consts::PI; let channels = 2u; let buffram...
0 => { phase += 55.0 * isr; in_buf[i]*sin(2.0*pi*phase) } 1 => { in_buf[i-1]*sin(4.0*pi*phase) } _ => {0.0} ...
let def_output = pa::get_default_output_device(); let info_output = pa::get_device_info(def_output).unwrap(); println!("Default output device info :"); println!("version : {:d}", info_output.struct_version); println!("name : {:s}", info_output.name); println!("max input channels : {:d}", info_out...
function_block-random_span
[ { "content": "fn main() -> () {\n\n let bufsize = 1024;\n\n\n\n println!(\"Portaudio init error : {:s}\", pa::get_error_text(pa::initialize()));\n\n let def_output = pa::get_default_output_device();\n\n let info_output = pa::get_device_info(def_output).unwrap();\n\n println!(\"Default output devi...
Rust
src/prompt/navigation.rs
db48x/rucline
ef18c68f8bfb0e481c2450c40fbf491ed7034496
pub(super) fn next_word(pivot: usize, string: &[char]) -> usize { let end = string.len(); if pivot == end { pivot } else { let mut index = pivot; while index < end && !string[index].is_whitespace() { index += 1; } while index < end &&...
pub(super) fn next_word(pivot: usize, string: &[char]) -> usize { let end = string.len(); if pivot == end { pivot } else { let mut index = pivot; while index < end && !string[index].is_whitespace() { index += 1; } while index < end &&...
#[test] fn previous_word_end() { let tester = Tester::prepare(Direction::Backward); tester.test(super::previous_word_end, |pivot, string| { string[pivot - 1] == 'Z' || string[pivot - 1] == 'O' }); } }
d() { let tester = Tester::prepare(Direction::Backward); tester.test(super::previous_word, |pivot, string| { string[pivot] == 'A' || string[pivot] == 'O' }); }
function_block-function_prefixed
[ { "content": "#[inline]\n\nfn complete_if_at_end_else_move(context: &impl Context, range: Range) -> Action {\n\n if context.cursor() == context.buffer().len() {\n\n if range == Range::Word {\n\n Action::Complete(Range::Word)\n\n } else {\n\n Action::Complete(Range::Line)\n...
Rust
src/help_function.rs
juozaspo/szyszka
b24d574555faad504038858bff5e65c099a42493
use crate::rules::*; use gtk::prelude::*; use gtk::*; use std::cell::RefCell; use std::ops::DerefMut; use std::path::Path; use std::rc::Rc; #[allow(dead_code)] pub enum ColumnsResults { CurrentName = 0, FutureName, Path, Size, ModificationDate, CreationDate, } pub enum ColumnsRules { R...
use crate::rules::*; use gtk::prelude::*; use gtk::*; use std::cell::RefCell; use std::ops::DerefMut; use std::path::Path; use std::rc::Rc; #[allow(dead_code)] pub enum ColumnsResults { CurrentName = 0, FutureName, Path, Size, ModificationDate, CreationDate, } pub enum ColumnsRules { R...
pub fn remove_selected_rows(tree_view: &gtk::TreeView) -> Vec<usize> { let selection = tree_view.get_selection(); let (selected_rows, _tree_model) = selection.get_selected_rows(); if selected_rows.is_empty() { return Vec::new(); } let list_store = get_list_store_from_tree_view(&tre...
ew(&tree_view); list_store.clear(); let col_indices = [0, 1, 2]; for rule in &rules.rules { let values: [&dyn ToValue; 3] = [&rule_type_to_string(&rule.rule_type), &rule_place_to_string(&rule.rule_place), &rule.rule_description]; list_store.set(&list_store.append(), &col_indices, &values);...
function_block-function_prefixed
[ { "content": "pub fn rule_change_size_letters(data_to_change: &str, rule: &SingleRule) -> String {\n\n let (mut name, mut extension) = split_file_name(Path::new(data_to_change));\n\n\n\n match rule.rule_type {\n\n RuleType::CaseSize => {\n\n if !rule.rule_data.to_lowercase {\n\n ...
Rust
cscan/legacy/src/main.rs
vul337/cfi-eval
7d7801cf44cc650127d692c2a7222434375ac6aa
mod binary; mod debugger; mod disasm; mod tester; use debugger::Debugger; use humansize::{file_size_opts::BINARY, FileSize}; use log::*; use serde::Serialize; use std::collections::{BTreeSet, HashSet}; use std::ffi::OsString; use std::fmt::Debug; use std::fs::File; use std::ops::Range; use std::time::Instant; use stru...
mod binary; mod debugger; mod disasm; mod tester; use debugger::Debugger; use humansize::{file_size_opts::BINARY, FileSize}; use log::*; use serde::Serialize; use std::collections::{BTreeSet, HashSet}; use std::ffi::OsString; use std::fmt::Debug; use std::fs::File; use std::ops::Range; use std::time::Instant; use stru...
const MODES: &[(&str, fn(debugger::Debugger) -> Box<dyn CfiTester>)] = &[ ("lockdown", LockdownTester::new), ("llvm", LlvmTester::new), ("tsx-rtm", TsxTester::new_rtm), ("tsx-hle", TsxTester::new_hle), ("cfi-lb", CfiLbTester::new_cfilb), ("os-cfi", CfiLbTester::new_oscfi), ("mcfi", MCfiTes...
fn cfifuzz(tester: &mut dyn CfiTester, range: Range<u64>) -> Vec<IctTestResult> { let mut icts = vec![]; let mut tested = HashSet::<String>::default(); while let Some((name, ranges)) = tester.advance_ict() { let ict = IctTestResult { name, skipped: true, ...
function_block-full_function
[ { "content": "#[derive(Debug, StructOpt)]\n\nstruct Opt {\n\n /// The index for ICT where fuzzing starts. ICTs before are ignored.\n\n #[structopt(long, default_value = \"0\")]\n\n start: u64,\n\n\n\n /// The index for ICT where fuzzing ends. ICTs equal or greater are ignored.\n\n #[structopt(lon...
Rust
src/bin/20.rs
andesyv/AdventOfCode21
1f434f26360b050646993cb768ddaf7a35cc7711
use std::iter; fn main() { const INPUT: &str = include_str!("../inputs/20.txt"); let (image_enhance_pattern, image) = INPUT.split_once("\n\n").unwrap(); let image_enhance_pattern = &image_enhance_pattern.lines().fold(String::new(), |l,r|l + &r.to_string()); let image = image.lines().map(|s|s.to_strin...
use std::iter; fn main() { const INPUT: &str = include_str!("../inputs/20.txt"); let (image_enhance_pattern, image) = INPUT.split_once("\n\n").unwrap(); let image_enhance_pattern = &image_enhance_pattern.lines().fold(String::new(), |l,r|l + &r.to_string()); let image = image.lines().map(|s|s.to_strin...
fn enhance(pattern: &str, image: &Vec<String>) -> Vec<String> { let image_width = image.iter().next().unwrap().len(); let mut enhanced_image: Vec<Vec<char>> = image.iter().map(|s|s.chars().collect()).collect(); for (y, line) in enhanced_image.iter_mut().enumerate() { if y == 0 || image.len()-1 == ...
str_radix(&pat[..], 2).unwrap(); infinite_space = if enhance_pattern.chars().nth(index).unwrap() == '#' { '1' } else { '0' }; } if infinite_space == '1' { '#' } else { '.' } }
function_block-function_prefixed
[]
Rust
ap-com/src/rel/link.rs
Devisa/dv-api
3ac4116364f74b6d3f0d8bb8de80dff8230ffec9
use crate::{models::Model, types::Id}; use serde::{Serialize, Deserialize}; use sqlx::{ FromRow, Postgres, postgres::{PgRow, PgPool}, types::chrono::{NaiveDateTime, Utc} }; use crate::now; #[async_trait::async_trait] pub trait Linked: Model + Default + Clone { type Left: Model + LinkedTo<Self::Right>; ...
use crate::{models::Model, types::Id}; use serde::{Serialize, Deserialize}; use sqlx::{ FromRow, Postgres, postgres::{PgRow, PgPool}, types::chrono::{NaiveDateTime, Utc} }; use crate::now; #[async_trait::async_trait] pub trait Linked: Model + Default + Clone { type Left: Model + LinkedTo<Self::Right>; ...
Ok(res) } async fn linked_between(db: &PgPool, left_id: Id, right_id: Id) -> sqlx::Result<Vec<Self>> { let res = sqlx::query_as::<Postgres, Self>(&format!(" SELECT * FROM {link} WHERE {left_id} = $1 AND {right_id} = $2 ", ...
let right = self.clone().right_id(); let link = self.clone().link_id(); let res = sqlx::query_as::<Postgres, Self>(&query_str) .bind(left) .bind(right) .bind(link) .fetch_one(db).await?; Ok(res) } async fn linked_to_left(db: &PgPool, lef...
random
[ { "content": "#[async_trait::async_trait]\n\npub trait ModelType<T> {\n\n\n\n fn new(input: T) -> Self;\n\n\n\n fn nil() -> Self;\n\n\n\n fn get(self) -> T;\n\n}\n\n\n", "file_path": "ap-com/src/types/mod.rs", "rank": 1, "score": 205468.90864998638 }, { "content": "#[async_trait::as...
Rust
c64/src/frame_renderer.rs
bl-nero/atari-emulator
ac581216800aac1ae9acc0ebcae8b8d2640e08ca
use crate::vic::raster_line_to_screen_y; use crate::vic::VicOutput; use crate::vic::{LEFT_BORDER_START, TOP_BORDER_FIRST_LINE, VISIBLE_LINES, VISIBLE_PIXELS}; use common::colors::create_palette; use common::colors::Palette; use graphics::types::Rectangle; use image::{Pixel, Rgba, RgbaImage}; pub struct FrameRenderer {...
use crate::vic::raster_line_to_screen_y; use crate::vic::VicOutput; use crate::vic::{LEFT_BORDER_START, TOP_BORDER_FIRST_LINE, VISIBLE_LINES, VISIBLE_PIXELS}; use common::colors::create_palette; use common::colors::Palette; use graphics::types::Rectangle; use image::{Pixel, Rgba, RgbaImage}; pub struct FrameRenderer {...
me } } impl Default for FrameRenderer { fn default() -> Self { let palette = create_palette(&[ 0x000000, 0xffffff, 0x813338, 0x75cec8, 0x8e3c97, 0x56ac4d, 0x2e2c9b, 0xedf171, 0x8e5029, 0x553800, 0xc46c71, 0x4a4a4a, 0x7b7b7b, 0xa9ff9f, 0x706deb, 0xb2b2b2, ...
); if x_range.contains(&x) && y_range.contains(&y) { self.frame.put_pixel( (x - x_range.start) as u32, (y - y_range.start) as u32, self.palette[vic_output.color as usize], ); } } pub fn frame_image(&self) -> &RgbaImage { ...
random
[ { "content": "/// Creates a palette of RGBA colors out of an `u32` array slice. Each number\n\n/// represents a 3-byte RGB color, where each channel is represented by 8 bits.\n\npub fn create_palette(colors: &[u32]) -> Palette {\n\n let mut palette = Palette::with_capacity(colors.len() * 2);\n\n for color...
Rust
tests/lib.rs
iorust/serde_resp
107d804a72666e771b1ab86b7f190e61beaff0d7
extern crate resp; extern crate rand; use std::io; use std::io::{Read, BufReader}; use resp::{Value, encode, encode_slice, Decoder}; use std::{thread, time}; use rand::{StdRng, Rng}; struct Case { data: Vec<u8>, want: Value, } struct FakeNetIO { offset: usize, buf: Vec<u8>, } impl Read for FakeNet...
extern crate resp; extern crate rand; use std::io; use std::io::{Read, BufReader}; use resp::{Value, encode, encode_slice, Decoder}; use std::{thread, time}; use rand::{StdRng, Rng}; struct Case { data: Vec<u8>, want: Value, } struct FakeNetIO { offset: usize, buf: Vec<u8>, } impl Read for FakeNet...
.into_bytes(), want: Value::Array(vec![Value::Integer(1), Value::Integer(2), Value::Integer(3), Value::Integer(4), Value::Bulk("foobar".to_string())]), ...
ange(0, std::cmp::min(buf.len(), 1024)); if n == 0 { n = buf.len(); } if self.offset + n > self.buf.len() { n = self.buf.len() - self.offset; } thread::sleep(time::Duration::new(0, n as u32)); buf[..n].copy_from_slic...
random
[ { "content": "#[inline]\n\nfn buf_encode(value: &Value, buf: &mut Vec<u8>) {\n\n match *value {\n\n Value::Null => {\n\n buf.extend_from_slice(NULL_BYTES);\n\n }\n\n Value::NullArray => {\n\n buf.extend_from_slice(NULL_ARRAY_BYTES);\n\n }\n\n Value::St...
Rust
sdk/codeartifact/src/json_ser.rs
JesseWright/aws-sdk-rust
32c2e58554ed338633177a464affc7e3ae04219f
pub fn serialize_structure_copy_package_versions_input( object: &mut smithy_json::serialize::JsonObjectWriter, input: &crate::input::CopyPackageVersionsInput, ) { if let Some(var_1) = &input.allow_overwrite { object.key("allowOverwrite").boolean(*var_1); } if let Some(var_2) = &input.includ...
pub fn serialize_structure_copy_package_versions_input( object: &mut smithy_json::serialize::JsonObjectWriter, input: &crate::input::CopyPackageVersionsInput, ) { if let Some(var_1) = &input.allow_overwrite { object.key("allowOverwrite").boolean(*var_1); } if let Some(var_2) = &input.includ...
} }
_62.value().start_object(); crate::json_ser::serialize_structure_upstream_repository(&mut object_64, item_63); object_64.finish(); } } array_62.finish(); } } pub fn serialize_structure_tag( object: &mut smithy_json::serialize::JsonObjectWriter, in...
random
[]