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
deprecated/rug_true_skill/normal.rs
kiwec/Elo-MMR
bf64ea75e8c0dbb946d379b9bee1753e604b388a
use super::to_hp; use rug::Float; use std::ops::{Add, Deref, Div, Mul, Sub}; use std::f64::consts::PI; #[derive(Clone, Debug)] pub struct Gaussian { pub mu: Float, pub sigma: Float, } impl Add<&Gaussian> for &Gaussian { type Output = Gaussian; fn add(self, rhs: &Gaussian) -> Gaussian { Gaussi...
use super::to_hp; use rug::Float; use std::ops::{Add, Deref, Div, Mul, Sub}; use std::f64::consts::PI; #[derive(Clone, Debug)] pub struct Gaussian { pub mu: Float, pub sigma: Float, } impl Add<&Gaussian> for &Gaussian { type Output = Gaussian; fn add(self, rhs: &Gaussian) -> Gaussian { Gaussi...
pub fn greater_eps(&self, eps: &Float) -> Gaussian { assert!(!eps.is_sign_negative()); assert!(!self.sigma.is_infinite()); let alpha = moment0(&self.mu, &self.sigma, &eps); let mu = moment1(&self.mu, &self.sigma, &eps) / &alpha; let sigma2 = moment2(&self.mu, &self.sigma,...
pub fn leq_eps(&self, eps: &Float) -> Gaussian { assert!(!eps.is_sign_negative()); assert!(!self.sigma.is_infinite()); let neg_eps = to_hp(-eps); let alpha = moment0(&self.mu, &self.sigma, &neg_eps) - moment0(&self.mu, &self.sigma, &eps); let (mu, sigma) = if alpha == 0 { ...
function_block-full_function
[]
Rust
SampleApp/src/main.rs
BuBuMan/RustyGear
b71d9a2ab71e772c6d833f6cd769d0f687a2e044
#![allow(non_snake_case)] use std::time::Instant; use sdl2::event::Event; use sdl2::keyboard::Keycode; use futures::executor::block_on; mod graphics; mod input; mod resources; mod ecs; mod texture; mod entity; #[path= "components\\component.rs"] mod component; #[path= "components\\transform.rs"] mod transform; #[pat...
#![allow(non_snake_case)] use std::time::Instant; use sdl2::event::Event; use sdl2::keyboard::Keycode; use futures::executor::block_on; mod graphics; mod input; mod resources; mod ecs; mod texture; mod entity; #[path= "components\\component.rs"] mod component; #[path= "components\\transform.rs"] mod transform; #[pat...
game_loop: loop { enter_frame(&mut event_pump, &mut app_state); if app_state.exit_app { break 'game_loop; } systems.run(&mut ecs, &mut app_state.graphics, &app_state.input, app_state.delta_time as f32); exit_frame(&mut app_state); } }
function_block-function_prefix_line
[ { "content": "fn create_quad() -> Mesh {\n\n let mut vertices = Vec::new();\n\n\n\n let vertexA = Vertex {\n\n position: [-0.5, 0.5, 0.0],\n\n normal: [0.0, 0.0, 1.0],\n\n tex_coords: [0.0, 0.0],\n\n };\n\n\n\n let vertexB = Vertex {\n\n position: [0.5, 0.5, 0.0],\n\n ...
Rust
src/model.rs
taku-y/primitiv-rust
76edd080700683a458e43c89fff5579c090c3bc5
use std::collections::hash_map::DefaultHasher; use std::hash::Hasher; use std::io; use std::path::Path; use Device; use Parameter; use Wrap; pub trait Model: Sized { fn load<P: AsRef<Path>>(&mut self, path: P, with_stats: bool) -> io::Result<()> { self.register_parameters(); let lock = interna...
use std::collections::hash_map::DefaultHasher; use std::hash::Hasher; use std::io; use std::path::Path; use Device; use Parameter; use Wrap; pub trait Model: Sized { fn load<P: AsRef<Path>>(&mut self, path: P, with_stats: bool) -> io::Result<()> { self.register_parameters(); let lock = interna...
pub fn save<P: AsRef<Path>>(&self, path: P, with_stats: bool) -> io::Result<()> { unsafe { let path_c = CString::new(path.as_ref().to_str().unwrap()).unwrap(); let path_ptr = path_c.as_ptr(); Result::from_api_status( _pri...
h>, D: Device>( &mut self, path: P, with_stats: bool, device: Option<&mut D>, ) -> io::Result<()> { unsafe { let path_c = CString::new(path.as_ref().to_str().unwrap()).unwrap(); let path_ptr = path_c.as_ptr(); ...
function_block-function_prefixed
[ { "content": "/// Gathers the set of words from space-separated corpus and makes a vocabulary.\n\npub fn make_vocab<P: AsRef<Path>>(path: P, size: usize) -> Result<HashMap<String, u32>, io::Error> {\n\n if size < 3 {\n\n eprintln!(\"Vocab size should be <= 3.\");\n\n exit(1);\n\n }\n\n le...
Rust
parsers/rust/src/block.rs
wpears/subtext
97dd526af66bf2d1219d1f27ce034b7568b47a7d
use crate::{primitive, util::cut}; use tendril::{StrTendril, SubtendrilError}; #[derive(Debug, Clone)] pub enum Entity { Header(Vec<primitive::Entity>), Paragraph(Vec<primitive::Entity>), Quote(Vec<primitive::Entity>), List(Vec<Vec<primitive::Entity>>), Link(primitive::Entity), Seperator(primit...
use crate::{primitive, util::cut}; use tendril::{StrTendril, SubtendrilError}; #[derive(Debug, Clone)] pub enum Entity { Header(Vec<primitive::Entity>), Paragraph(Vec<primitive::Entity>), Quote(Vec<primitive::Entity>), List(Vec<Vec<primitive::Entity>>), Link(primitive::Entity), Seperator(primit...
pub fn parse_link(input: StrTendril) -> Result<(Entity, usize), SubtendrilError> { let (primitive, steps) = match input.chars().nth(0) { Some('/') => primitive::parse_slash_link(input)?, _ => primitive::parse_hyper_link(input)?, }; Ok((Entity::Link(primitive), steps)) } fn parse_with_sig...
pub fn parse_paragraph(input: StrTendril) -> Result<(Entity, usize), SubtendrilError> { let (primitives, steps) = primitive::parse_text(input)?; match &primitives[..] { [value] => match value { primitive::Entity::HyperLink(_) => Ok((Entity::Link(value.clone()), steps)), primitiv...
function_block-full_function
[ { "content": "pub fn parse_slash_link(input: StrTendril) -> Result<(Entity, usize), SubtendrilError> {\n\n match parse_until_empty_space(input) {\n\n Ok((value, steps)) => Ok((Entity::SlashLink(value), steps)),\n\n Err(error) => Err(error),\n\n }\n\n}\n\n\n", "file_path": "parsers/rust/s...
Rust
src/main/utils.rs
stuartZhang/scaffold-wizard
6122e3f6720b4c071b26d827dbc6cf3759424186
pub mod error; use ::std::{env, error::Error as StdError, fmt::{Debug, Display}, path::{Path, PathBuf}, rc::Rc, result::Result as StdResult}; use ::log::{debug, error}; use ::gtk::Builder; use super::render; pub use error::Error; pub type Result<T> = std::result::Result<T, Box<dyn StdError>>; pub fn get_exe_dir() ->...
pub mod error; use ::std::{env, error::Error as StdError, fmt::{Debug, Display}, path::{Path, PathBuf}, rc::Rc, result::Result as StdResult}; use ::log::{debug, error}; use ::gtk::Builder; use super::render; pub use error::Error; pub type Result<T> = std::result::Result<T, Box<dyn StdError>>; pub fn get_exe_dir() ->...
pub fn option3<T, F>(&self, expr: Option<T>, message: F) -> T where F: AsRef<str> + Display { match expr { Some(rs) => rs, None => { let message = message.as_ref(); error!("[unwrap_build]{}", message); render::err_popup(&self.build...
pub fn option2<T, F>(expr: Option<T>, message: F) -> T where F: AsRef<str> + Display { match expr { Some(rs) => rs, None => { let message = message.as_ref(); error!("[unwrap_build]{}", message); panic!("{}", message) } ...
function_block-full_function
[ { "content": "pub fn show<F>(builder: &Builder, message: F)\n\nwhere F: AsRef<str> {\n\n let invalid_dialog: Dialog = Unwrap::option2(builder.get_object(\"error-dialog\"),\n\n \"不能从 glade 布局文件里,找到 error-dialog 元素\");\n\n let message_label: Label = Unwrap::option2(builder.get_object(\"error-dialog-m...
Rust
core/src/value/mod.rs
daniel-ge/dicom-rs
653e8eaa248d9e348c7fcf9c2953d7141a4b7a16
use crate::error::CastValueError; use crate::header::{HasLength, Length, Tag}; use smallvec::SmallVec; use std::borrow::Cow; pub mod deserialize; mod primitive; pub mod serialize; pub use self::primitive::{PrimitiveValue, ValueType}; use chrono::{DateTime, NaiveDate, NaiveTime}; pub type C<T> = SmallVec<[T; 2]>; ...
use crate::error::CastValueError; use crate::header::{HasLength, Length, Tag}; use smallvec::SmallVec; use std::borrow::Cow; pub mod deserialize; mod primitive; pub mod serialize; pub use self::primitive::{PrimitiveValue, ValueType}; use chrono::{DateTime, NaiveDate, NaiveTime}; pub type C<T> = SmallVec<[T; 2]>; ...
match self { Value::Primitive(prim) => Ok(prim.to_str()), _ => Err(CastValueError { requested: "string", got: self.value_type(), }), } } pub fn to_bytes(&self) -> Result<Cow<[u8]>, CastValueError> { ...
=> Some(items), _ => None, } } pub fn offset_table(&self) -> Option<&[u8]> { match self { Value::PixelSequence { offset_table, .. } => Some(&offset_table), _ => None, } } } impl<I, P> HasLength for Value<I, P> { fn length(&self) -> Lengt...
random
[ { "content": "/// Trait for any DICOM entity (element or item) which may have a length.\n\npub trait HasLength {\n\n /// Retrieve the value data's length as specified by the data element or\n\n /// item, in bytes.\n\n ///\n\n /// It is named `length` to make it distinct from the conventional method\...
Rust
src/game_logic/ranges.rs
heartlabs/megachess
ffa8475ec70d9033feb1d86a30d5a96cd683dffa
use crate::*; use nanoserde::{DeBin, SerBin}; use std::{collections::HashSet, iter::successors}; #[derive(Debug, Copy, Clone, SerBin, DeBin)] pub struct Range { pub direction: Direction, pub steps: u8, pub jumps: bool, pub include_self: bool, } #[derive(Debug, PartialEq, Copy, Clone, SerBin, DeBin)] p...
use crate::*; use nanoserde::{DeBin, SerBin}; use std::{collections::HashSet, iter::successors}; #[derive(Debug, Copy, Clone, SerBin, DeBin)] pub struct Range { pub direction: Direction, pub steps: u8, pub jumps: bool, pub include_self: bool, } #[derive(Debug, PartialEq, Copy, Clone, SerBin, DeBin)] p...
); x }) .collect::<Vec<Box<dyn Iterator<Item = (i16, i16)>>>>(); if self.include_self { vec.push(Box::new(Some((from_x as i16, from_y as i16)).into_iter())); } Box::new(vec.into_iter()) } pub fn reachable_points( &sel...
x, y)| (x - 1, y + 1)), Box::new(|(x, y)| (x + 1, y)), Box::new(|(x, y)| (x - 1, y)), Box::new(|(x, y)| (x, y + 1)), Box::new(|(x, y)| (x, y - 1)), ], Direction::Anywhere => Vec::new(), } } } pub enum RangeContext { ...
random
[ { "content": "pub fn cell_coords_tuple(x: u8, y: u8) -> (f32, f32) {\n\n let x_pos = ((x as u32 * CELL_WIDTH) as f32) * CELL_SCALE + SHIFT_X;\n\n let y_pos = ((y as u32 * CELL_WIDTH) as f32) * CELL_SCALE + SHIFT_Y;\n\n\n\n (x_pos, y_pos)\n\n}\n\n\n", "file_path": "src/constants.rs", "rank": 0, ...
Rust
2020/day_12_2.rs
mark-a/adventofcode-solutions
ced7cd725b619f789d9e9ee7df1d03f6fb6477d3
use std::fs::File; use std::io::Read; use std::path::Path; use std::time::Instant; #[derive(Debug, Copy, Clone, Eq, PartialEq)] pub enum Rotation { None, Right, Left, Back, } impl Rotation { pub fn rotate(self, waypoint: (i32, i32)) -> (i32, i32) { match self { Rotation::None =...
use std::fs::File; use std::io::Read; use std::path::Path; use std::time::Instant; #[derive(Debug, Copy, Clone, Eq, PartialEq)] pub enum Rotation { None, Right, Left, Back, } impl Rotation {
} #[derive(Debug, Copy, Clone, Eq, PartialEq)] pub enum Direction { N(i32), E(i32), S(i32), W(i32), F(i32), R(Rotation), } #[derive(Debug, Copy, Clone, Eq, PartialEq)] pub struct Ship { position: (i32, i32), waypoint: (i32, i32), } impl Ship { pub fn new() -> Ship { Ship ...
pub fn rotate(self, waypoint: (i32, i32)) -> (i32, i32) { match self { Rotation::None => (waypoint.0, waypoint.1), Rotation::Right => (-waypoint.1, waypoint.0), Rotation::Left => (waypoint.1, -waypoint.0), Rotation::Back => (-waypoint.0, -waypoint.1) } ...
function_block-full_function
[ { "content": "pub fn part1(input: &str) -> impl std::fmt::Display {\n\n input\n\n .lines()\n\n .map(Instruction::from)\n\n .fold(((0, 0, 0), HashMap::new()), |(mut mask, mut mem), ins| {\n\n match ins {\n\n Instruction::Mask(z, o, x) => mask = (z, o, x),\n\n ...
Rust
src/lib.rs
Stupremee/yastl
b716f7f67a2e32ea0c260ab6c7ff52ef728ed564
#![deny(rust_2018_idioms, missing_docs, broken_intra_doc_links)] mod wait; use wait::{Sentinel, WaitGroup}; mod scope; pub use scope::Scope; use flume::{Receiver, Sender}; use std::{sync::Arc, thread}; #[derive(Clone)] pub struct Pool { inner: Arc<PoolInner>, wait: Arc<wait::WaitGroup>, } impl Pool { ...
#![deny(rust_2018_idioms, missing_docs, broken_intra_doc_links)] mod wait; use wait::{Sentinel, WaitGroup}; mod scope; pub use scope::Scope; use flume::{Receiver, Sender}; use std::{sync::Arc, thread}; #[derive(Clone)] pub struct Pool { inner: Arc<PoolInner>, wait: Arc<wait::WaitGroup>, } impl Pool { ...
#[test] #[should_panic] fn scheduler_panic_waits_for_tasks() { let tasks = 50; let counter = Box::new(AtomicUsize::new(0)); let drops = DropCounter(&*counter); let _canary = Canary { drops: drops.clone(), expected: tasks, }; let poo...
let _drops = drop_counter; panic!(); }); } } }); }
function_block-function_prefix_line
[ { "content": "fn main() {\n\n let pool = Pool::new(4);\n\n let mut list = vec![1, 2, 3, 4, 5];\n\n\n\n pool.scoped(|scope| {\n\n // since the `scope` guarantees that the threads are finished if it drops,\n\n // we can safely borrow `list` inside here.\n\n for x in list.iter_mut() {...
Rust
src/writer.rs
jerry73204/rust-tfrecord
047014c4b3d1d857582e30d8780c83c165f1fb32
use crate::{error::Error, markers::GenericRecord, protos::Example as RawExample, types::Example}; #[cfg(feature = "async")] use futures::io::AsyncWriteExt; use std::{io::Write, marker::PhantomData, path::Path}; pub type BytesWriter<W> = RecordWriter<Vec<u8>, W>; pub type RawExampleWriter<W> = RecordWriter<RawExampl...
use crate::{error::Error, markers::GenericRecord, protos::Example as RawExample, types::Example}; #[cfg(feature = "async")] use futures::io::AsyncWriteExt; use std::{io::Write, marker::PhantomData, path::Path}; pub type BytesWriter<W> = RecordWriter<Vec<u8>, W>; pub type RawExampleWriter<W> = RecordWriter<RawExampl...
#[cfg(feature = "async")] pub async fn create_async<T, P>( path: P, ) -> Result<RecordWriter<T, async_std::io::BufWriter<async_std::fs::File>>, Error> where T: GenericRecord, P: AsRef<async_std::path::Path>, { let writer = async_std::io::BufWriter::new(async_std::fs::Fi...
cordWriter { writer, _phantom: PhantomData, }) } pub fn create<T, P>( path: P, ) -> Result<RecordWriter<T, std::io::BufWriter<std::fs::File>>, Error> where T: GenericRecord, P: AsRef<Path>, { let writer = std::io::BufWri...
random
[ { "content": "pub fn verify_checksum(buf: &[u8], expect: u32) -> Result<(), Error> {\n\n let found = checksum(&buf);\n\n if expect == found {\n\n Ok(())\n\n } else {\n\n Err(Error::ChecksumMismatchError {\n\n expect: format!(\"{:#010x}\", expect),\n\n found: format!(...
Rust
tests/command/test_move.rs
waych/git-branchless
bbe0313c9fbdf5e1df65af49e1b053b58213429e
use branchless::testing::{with_git, Git, GitRunOptions}; use branchless::util::GitVersion; fn has_git_v2_24_bug(git: &Git) -> anyhow::Result<bool> { let GitVersion(major, minor, _patch) = git.get_version()?; Ok((major, minor) <= (2, 24)) } #[test] fn test_move_stick_on_disk() -> anyhow::Result<()> { with_...
use branchless::testing::{with_git, Git, GitRunOptions}; use branchless::util::GitVersion; fn has_git_v2_24_bug(git: &Git) -> anyhow::Result<bool> { let GitVersion(major, minor, _patch) = git.get_version()?; Ok((major, minor) <= (2, 24)) } #[test] fn test_move_stick_on_disk() -> anyhow::Result<()> { with_...
} #[test] fn test_move_base() -> anyhow::Result<()> { with_git(|git| { git.init_repo()?; git.commit_file("test1", 1)?; git.detach_head()?; git.commit_file("test2", 2)?; let test3_oid = git.commit_file("test3", 3)?; git.run(&["checkout", "master"])?; git.comm...
with_git(|git| { if has_git_v2_24_bug(&git)? { return Ok(()); } git.init_repo()?; let base_oid = git.commit_file("test1", 1)?; git.detach_head()?; let other_oid = git.commit_file_with_contents("conflict", 2, "conflict 1\n")?; git.run(&["checkout", &ba...
call_expression
[ { "content": "/// Move a subtree from one place to another.\n\npub fn r#move(\n\n git_executable: &GitExecutable,\n\n source: Option<String>,\n\n dest: Option<String>,\n\n base: Option<String>,\n\n force_on_disk: bool,\n\n) -> anyhow::Result<isize> {\n\n let repo = get_repo()?;\n\n let head...
Rust
src/cameracontroller/mod.rs
Mik-pe/MikpEngine
d698d0e94a24711ce4f53ead76f85f72cb789e9b
use crate::inputcontroller::InputController; use katla_math::{Mat4, Vec3}; use std::{cell::RefCell, rc::Rc}; use winit::event::Event; use winit::event::{DeviceEvent, ElementState, MouseButton, WindowEvent}; pub struct PerspectiveProjection { fov: f32, near_plane: f32, far_plane: f32, matrix: Mat4, } i...
use crate::inputcontroller::InputController; use katla_math::{Mat4, Vec3}; use std::{cell::RefCell, rc::Rc}; use winit::event::Event; use winit::event::{DeviceEvent, ElementState, MouseButton, WindowEvent}; pub struct PerspectiveProjection { fov: f32, near_plane: f32, far_plane: f32, matrix: Mat4, } i...
} impl PerspectiveProjection { pub fn recreate_matrix(&mut self, aspect_ratio: f32) { self.matrix = Mat4::create_proj(self.fov, aspect_ratio, self.near_plane, self.far_plane); } } pub struct Camera { pos: Vec3, projection: PerspectiveProjection, velocity_dir: Vec3, input_dir: Vec...
0; let matrix = Mat4::create_proj(fov, 1.0, near_plane, far_plane); Self { fov, near_plane, far_plane, matrix, } }
function_block-function_prefixed
[ { "content": "//Assume lower row is 0_0_0_1\n\npub fn mat4_mul_vec3(a: &Mat4, b: &Vec3) -> Vec3 {\n\n let row0 = Mat4::extract_row(&a, 0);\n\n let row1 = Mat4::extract_row(&a, 1);\n\n let row2 = Mat4::extract_row(&a, 2);\n\n //TODO: Don't create a new object here:\n\n Vec3([\n\n b.dot(Vec3...
Rust
aquatic_ws/src/lib/lib.rs
greatest-ape/aquatic
614dea755b5703018ccf42c1c28c7cc5de22305e
use std::fs::File; use std::io::Read; use std::sync::Arc; use std::thread::Builder; use std::time::Duration; use anyhow::Context; use mio::{Poll, Waker}; use native_tls::{Identity, TlsAcceptor}; use parking_lot::Mutex; use privdrop::PrivDrop; pub mod common; pub mod config; pub mod handler; pub mod network; pub mod t...
use std::fs::File; use std::io::Read; use std::sync::Arc; use std::thread::Builder; use std::time::Duration; use anyhow::Context; use mio::{Poll, Waker}; use native_tls::{Identity, TlsAcceptor}; use parking_lot::Mutex; use privdrop::PrivDrop; pub mod common; pub mod config; pub mod handler; pub mod network; pub mod t...
new(out_message_senders); for i in 0..config.request_workers { let config = config.clone(); let state = state.clone(); let in_message_receiver = in_message_receiver.clone(); let out_message_sender = out_message_sender.clone(); let wakers = wakers.clone(); Builder::n...
ck() .clean(&config, &state.access_list.load_full()); } } pub fn start_workers(config: Config, state: State) -> anyhow::Result<()> { let opt_tls_acceptor = create_tls_acceptor(&config)?; let (in_message_sender, in_message_receiver) = ::crossbeam_channel::unbounded(); let mut out_message_s...
random
[ { "content": "pub fn update_access_list(config: &Config, state: &State) {\n\n match config.access_list.mode {\n\n AccessListMode::White | AccessListMode::Black => {\n\n if let Err(err) = state.access_list.update_from_path(&config.access_list.path) {\n\n ::log::error!(\"Couldn...
Rust
src/zig.rs
DSPOM2/maturin
731cae989daff4e707573580c763b6cbf16b1048
use crate::target::Arch; use crate::{BuildContext, PlatformTag}; use anyhow::{bail, Context, Result}; use fs_err as fs; use std::env; #[cfg(target_family = "unix")] use std::fs::OpenOptions; use std::io::Write; #[cfg(target_family = "unix")] use std::os::unix::fs::OpenOptionsExt; use std::path::{Path, PathBuf}; use s...
use crate::target::Arch; use crate::{BuildContext, PlatformTag}; use anyhow::{bail, Context, Result}; use fs_err as fs; use std::env; #[cfg(target_family = "unix")] use std::fs::OpenOptions; use std::io::Write; #[cfg(target_family = "unix")] use std::os::unix::fs::OpenOptionsExt; use std::path::{Path, PathBuf}; use s...
athBuf, PathBuf)> { let target = &context.target; let arch = if target.cross_compiling() { if matches!(target.target_arch(), Arch::Armv7L) { "armv7".to_string() } else { target.target_arch().to_string() } } else { "native".to_string() }; let fi...
esult<()> { let (cmd, cmd_args) = match self { Zig::Cc { args } => ("cc", args), Zig::Cxx { args } => ("c++", args), }; let cmd_args: Vec<String> = cmd_args .iter() .map(|arg| { let arg = if arg == "-lgcc_s" { ...
random
[ { "content": "/// Calculate the sha256 of a file\n\npub fn hash_file(path: impl AsRef<Path>) -> Result<String, io::Error> {\n\n let mut file = fs::File::open(path.as_ref())?;\n\n let mut hasher = Sha256::new();\n\n io::copy(&mut file, &mut hasher)?;\n\n let hex = format!(\"{:x}\", hasher.finalize())...
Rust
planners/src/bin/lcp.rs
plaans/aries
1fa4f530fb7e3abe633b2ee37416928abf7dfc19
use std::fs::File; use std::io::Write; use std::path::PathBuf; use anyhow::{Context, Result}; use aries_planners::fmt::format_partial_plan; use aries_planning::chronicles::analysis::hierarchical_is_non_recursive; use aries_planning::chronicles::{FiniteProblem, Problem}; use structopt::StructOpt; use aries_planners::e...
use std::fs::File; use std::io::Write; use std::path::PathBuf; use anyhow::{Context, Result}; use aries_planners::fmt::format_partial_plan; use aries_planning::chronicles::analysis::hierarchical_is_non_recursive; use aries_planning::chronicles::{FiniteProblem, Problem}; use structopt::StructOpt; use aries_planners::e...
problem: Problem, depth: u32, htn_mode: bool) { println!("===== Preprocessing ======"); aries_planning::chronicles::preprocessing::preprocess(&mut base_problem); println!("=========================="); let mut pb = FiniteProblem { model: base_problem.context.model.clone(), origin: base_...
strategies: Vec<Strat>, } fn main() -> Result<()> { let opt: Opt = Opt::from_args(); let problem_file = &opt.problem; anyhow::ensure!( problem_file.exists(), "Problem file {} does not exist", problem_file.display() ); let problem_file = problem_file.canonicalize().unwrap...
random
[ { "content": "pub fn format_plan(problem: &FiniteProblem, plan: &Arc<Domains>, htn_mode: bool) -> Result<String> {\n\n let plan = if htn_mode {\n\n format!(\n\n \"\\n**** Decomposition ****\\n\\n\\\n\n {}\\n\\n\\\n\n **** Plan ****\\n\\n\\\n\n {}\",\n\n ...
Rust
src/error.rs
gadomski/pabst
8989afec7d50d47af81b1ea86abd8c0a3cc40975
use std::error; use std::ffi::OsString; use std::fmt; use std::io; use std::num::{ParseFloatError, ParseIntError}; use std::str::ParseBoolError; use las; #[cfg(feature = "rxp-source")] use rivlib; use sdc; #[cfg(feature = "sdf-source")] use sdf; use toml; #[derive(Debug)] pub enum Error { Configuration(Str...
use std::error; use std::ffi::OsString; use std::fmt; use std::io; use std::num::{ParseFloatError, ParseIntError}; use std::str::ParseBoolError; use las; #[cfg(feature = "rxp-source")] use rivlib; use sdc; #[cfg(feature = "sdf-source")] use sdf; use toml; #[derive(Debug)] pub enum Error { Configuration(Str...
fn cause(&self) -> Option<&error::Error> { match *self { Error::Decode(ref err) => Some(err), Error::Io(ref err) => Some(err), Error::Las(ref err) => Some(err), Error::ParseBool(ref err) => Some(err), Error::ParseInt(ref err) => Some(err), ...
r::Configuration(_) => "configuration error", Error::Decode(ref err) => err.description(), Error::MissingDimension(_) => "missing dimension", Error::Io(ref err) => err.description(), Error::Las(ref err) => err.description(), Error::ParseBool(ref err) => err.de...
function_block-function_prefixed
[ { "content": "fn from_point(point: &Point) -> Result<sdc::Point> {\n\n Ok(sdc::Point {\n\n time: try!(point.gps_time.ok_or(Error::MissingDimension(\"time\".to_string()))),\n\n range: point.range.unwrap_or_else(|| {\n\n (point.x.powi(2) + point.y.powi(2) + point.z.powi(2)).sqrt()\n\n ...
Rust
mocks/src/lib.rs
olidacombe/shakesemon
004ff775d4d4fbab08958bd6248a4c0d1d7059d9
use serde_json::json; use wiremock::{Mock, MockServer, ResponseTemplate}; pub mod pokeapi { use super::*; use wiremock::matchers::path_regex; pub static PIKACHU_DESCRIPTION: &str = "When several of\nthese POKéMON\ngather, their\nelectricity could\nbuild and cause\nlightning storms."; pub struct Mocks...
use serde_json::json; use wiremock::{Mock, MockServer, ResponseTemplate}; pub mod pokeapi { use super::*; use wiremock::matchers::path_regex; pub static PIKACHU_DESCRIPTION: &str = "When several of\nthese POKéMON\ngather, their\nelectricity could\nbuild and cause\nlightning storms."; pub struct Mocks...
} }
pub async fn start() -> Self { let server = MockServer::start().await; Mock::given(body_string_contains("text=you")) .respond_with(ResponseTemplate::new(200).set_body_json(json!({ "success": { "total":1 }, ...
function_block-full_function
[ { "content": "pub fn run(listener: TcpListener) -> Result<Server, std::io::Error> {\n\n let address = listener.local_addr()?;\n\n let server = HttpServer::new(|| App::new().service(get_pokemon))\n\n .listen(listener)?\n\n .run();\n\n println!(\"🚀 Shakesemon Listening on {}\", address);\n...
Rust
src/trap.rs
Jaic1/xv6-riscv-rust
95764a384bbbbfd2e66bd9764669583ac1ae927f
use core::num::Wrapping; use core::sync::atomic::Ordering; use crate::{consts::{TRAMPOLINE, TRAPFRAME, UART0_IRQ, VIRTIO0_IRQ}, process::{PROC_MANAGER, Proc}}; use crate::register::{stvec, sstatus, sepc, stval, sip, scause::{self, ScauseType}}; use crate::process::{CPU_MANAGER, CpuManager}; use crate::spinlock::...
use core::num::Wrapping; use core::sync::atomic::Ordering; use crate::{consts::{TRAMPOLINE, TRAPFRAME, UART0_IRQ, VIRTIO0_IRQ}, process::{PROC_MANAGER, Proc}}; use crate::register::{stvec, sstatus, sepc, stval, sip, scause::{self, ScauseType}}; use crate::process::{CPU_MANAGER, CpuManager}; use crate::spinlock::...
userret_virt(TRAPFRAME.into(), satp); } #[no_mangle] pub unsafe fn kerneltrap() { let local_sepc = sepc::read(); let local_sstatus = sstatus::read(); if !sstatus::is_from_supervisor() { panic!("not from supervisor mode"); } if sstatus::intr_get() { panic!("interrupts enabled")...
let userret_virt: extern "C" fn(usize, usize) -> ! = core::mem::transmute(Into::<usize>::into(TRAMPOLINE) + distance);
assignment_statement
[ { "content": "#[inline]\n\npub fn write(satp: usize) {\n\n unsafe {\n\n llvm_asm!(\"csrw satp, $0\"::\"r\"(satp)::\"volatile\");\n\n }\n\n}\n", "file_path": "src/register/satp.rs", "rank": 0, "score": 193537.43485093827 }, { "content": "#[inline]\n\npub fn read() -> usize {\n\n ...
Rust
src/btmap.rs
kulibali/rslogic
238679a7375da1cb0715d2881493ae52fc8e0823
use std::borrow::Borrow; use std::cmp::Ord; use std::cmp::Ordering; use std::rc::Rc; struct Node<K, V> where K: Ord { key: K, val: V, left: Option<Rc<Node<K, V>>>, right: Option<Rc<Node<K, V>>>, } impl<K, V> Node<K, V> where K: Ord { pub fn get<Q: ?Sized>(&self, key: &Q) -> Option<&V> wh...
use std::borrow::Borrow; use std::cmp::Ord; use std::cmp::Ordering; use std::rc::Rc; struct Node<K, V> where K: Ord { key: K, val: V, left: Option<Rc<Node<K, V>>>, right: Option<Rc<Node<K, V>>>, } impl<K, V> Node<K, V> where K: Ord { pub fn get<Q: ?Sized>(&self, key: &Q) -> Option<&V> wh...
} use std::clone::Clone; impl<K, V> Clone for BtMap<K, V> where K: Ord { fn clone(&self) -> BtMap<K, V> { BtMap { size: self.size, root: match self.root { Some(ref root) => Some(root.clone()), None => None } } } fn clone...
new(Node { key: key, val: item, left: None, right: None, })) }) } } }
function_block-function_prefixed
[ { "content": "/// Creates a `UnifyVal` goal that attempts to unify the variable and the value.\n\npub fn unify_val<T>(var: &Var, val: T) -> UnifyVal<T> where T: PartialEq + Unif<T> {\n\n UnifyVal { var: *var, val: val }\n\n}\n\n\n\n\n\n/// Evaluating a `UnifyVar` goal attempts to unify the variables.\n\npub ...
Rust
src/onion.rs
scilio/mwixnet-1
bff59b08ac14ba4ea3617bc2add71ae9e3cccd96
use crate::error::Result; use crate::secp::{self, Commitment, PublicKey, Secp256k1, SecretKey, SharedSecret}; use crate::types::Payload; use chacha20::{ChaCha20, Key, Nonce}; use chacha20::cipher::{NewCipher, StreamCipher}; use grin_core::ser::{self, ProtocolVersion, Writeable, Writer}; use grin_util::{self, To...
use crate::error::Result; use crate::secp::{self, Commitment, PublicKey, Secp256k1, SecretKey, SharedSecret}; use crate::types::Payload; use chacha20::{ChaCha20, Key, Nonce}; use chacha20::cipher::{NewCipher, StreamCipher}; use grin_core::ser::{self, ProtocolVersion, Writeable, Writer}; use grin_util::{self, To...
&commitment, &decrypted_payload.excess)?; commitment = secp::sub_value(&commitment, decrypted_payload.fee.into())?; let peeled_onion = Onion{ ephemeral_pubkey: ephemeral_pubkey, commit: commitment.clone(), enc_payloads: enc_payloads, }; Ok...
mut vec = vec![]; ser::serialize_default(&mut vec, &self)?; Ok(vec) } pub fn peel_layer(&self, secret_key: &SecretKey) -> Result<(Payload, Onion)> { let secp = Secp256k1::new(); let shared_secret = SharedSecret::new(&secp, &self.ephemeral_pubkey, &secret_k...
random
[ { "content": "/// Build a Pedersen Commitment using the provided value and blinding factor\n\npub fn commit(value: u64, blind: &SecretKey) -> Result<Commitment> {\n\n let secp = Secp256k1::with_caps(ContextFlag::Commit);\n\n let commit = secp.commit(value, blind.clone())?;\n\n Ok(commit)\n\n}\n\n\n", ...
Rust
src/diagnostics/archivist/tests/data_stats/src/main.rs
mehulagg/fuchsia
3f56175ee594da6b287d5fb19f2f0eccea2897f0
use { failure::{Error, ResultExt}, fidl::endpoints::create_proxy, fidl_fuchsia_diagnostics::ArchiveMarker, fuchsia_async as fasync, fuchsia_component::client::{launcher, AppBuilder}, serde_json::json, std::{ fs::{create_dir, create_dir_all, write, File}, path::Path, }, ...
use { failure::{Error, ResultExt}, fidl::endpoints::create_proxy, fidl_fuchsia_diagnostics::ArchiveMarker, fuchsia_async as fasync, fuchsia_component::client::{launcher, AppBuilder}, serde_json::json, std::{ fs::{create_dir, create_dir_all, write, File}, path::Path, }, ...
_eq!(expected, output, "JSON produced must match expected output"); Ok(()) }
.expect("fidl should be fine") .expect("expect batches to be retrieved without error"); assert_eq!(first_result.len(), 1, "Currently only one data hierarchy in the test."); let mem_buf = match &first_result[0] { fidl_fuchsia_diagnostics::FormattedContent::FormattedJsonHierarchy(buffer) =...
random
[]
Rust
src/api.rs
shiinamiyuki/AkariRender
16c6a2d160ef9e508ab7e93260eebad8d005d767
use crate::accel::bvh::BVHAccelerator; use crate::accel::Aggregate; use crate::bsdf::*; use crate::camera::*; use crate::gpu::pt::WavefrontPathTracer; use crate::integrator::ao::RTAO; use crate::integrator::nrc::CachedPathTracer; use crate::integrator::path::PathTracer; use crate::integrator::*; use crate::light::*; u...
use crate::accel::bvh::BVHAccelerator; use crate::accel::Aggregate; use crate::bsdf::*; use crate::camera::*; use crate::gpu::pt::WavefrontPathTracer; use crate::integrator::ao::RTAO; use crate::integrator::nrc::CachedPathTracer; use crate::integrator::path::PathTracer; use crate::integrator::*; use crate::light::*; u...
, 0.0, 1.0)) * m; m = glm::translate(&glm::identity(), &t) * m; Transform::from_matrix(&m) } fn load(&mut self) { self.camera = Some(match self.graph.camera { node::Camera::Perspective { res, fov, lens_radius, f...
bsdfs.get(name) { return bsdf.clone(); } else { if let Some(node) = self.graph.named_bsdfs.get(name) { let bsdf = self.load_bsdf(node); self.named_bsdfs.insert(name.clone(), bsdf.clone()); return bsdf; } else { p...
random
[ { "content": "#[repr(C)]\n\n#[derive(Clone, Copy, bytemuck::Pod, bytemuck::Zeroable)]\n\nstruct GPUPerspectiveCamera {\n\n c2w: GPUTransform,\n\n r2c: GPUTransform,\n\n resolution: [u32; 2],\n\n}\n", "file_path": "src/gpu/pt.rs", "rank": 1, "score": 102300.11135986658 }, { "content"...
Rust
src/bin/day3.rs
tdaines/advent-of-code-21
998842dea62094b814ca762b4ea6dda45c1c0962
use std::{ fs::File, io::{BufRead, BufReader}, }; fn main() -> std::io::Result<()> { let input_file = File::open("./data/day3.txt")?; let reader = BufReader::new(input_file); let report: Vec<String> = reader.lines().map(|line| line.unwrap()).collect(); let (gamma, epsilon) = calculate_gamma_an...
use std::{ fs::File, io::{BufRead, BufReader}, }; fn main() -> std::io::Result<()> { let input_file = File::open("./data/day3.txt")?; let reader = BufReader::new(input_file); let report: Vec<String> = reader.lines().map(|line| line.unwrap()).collect(); let (gamma, epsilon) = calculate_gamma_an...
, "11001".to_owned(), "00010".to_owned(), "01010".to_owned(), ]; assert_eq!(calculate_co2_scrubber_rating(report.clone()), 10); } } }
"01010".to_owned(), ]; assert_eq!(calculate_gamma_and_epsilon(&report), (22, 9)); } } mod test_calculate_oxygen_generator_rating { use super::*; #[test] fn sample() { let report = vec![ "00100".to_owned(), ...
random
[]
Rust
eth2/types/src/beacon_state/tree_hash_cache.rs
timmyers/lighthouse
2a9c718a20acba2cd7a88cdc37dc847ad5430e82
use super::Error; use crate::{BeaconState, EthSpec, Hash256, Unsigned, Validator}; use cached_tree_hash::{int_log, CacheArena, CachedTreeHash, TreeHashCache}; use rayon::prelude::*; use ssz_derive::{Decode, Encode}; use tree_hash::{mix_in_length, TreeHash}; const VALIDATORS_PER_ARENA: usize = 4_096; #[derive(Debug, P...
use super::Error; use crate::{BeaconState, EthSpec, Hash256, Unsigned, Validator}; use cached_tree_hash::{int_log, CacheArena, CachedTreeHash, TreeHashCache}; use rayon::prelude::*; use ssz_derive::{Decode, Encode}; use tree_hash::{mix_in_length, TreeHash}; const VALIDATORS_PER_ARENA: usize = 4_096; #[derive(Debug, P...
.map(move |(cache_index, cache)| { let val_index = (arena_index * VALIDATORS_PER_ARENA) + cache_index; let validator = validators .get(val_index) .ok_or_else(|| Error::TreeHashCacheInconsistent)?; ...
validators, fixed_arena, balances_arena, slashings_arena, block_roots, state_roots, historical_roots, balances, randao_mixes, slashings, } } pub fn recalculate_tree_hash...
random
[ { "content": "/// Slash the validator with index ``index``.\n\n///\n\n/// Spec v0.10.1\n\npub fn slash_validator<T: EthSpec>(\n\n state: &mut BeaconState<T>,\n\n slashed_index: usize,\n\n opt_whistleblower_index: Option<usize>,\n\n spec: &ChainSpec,\n\n) -> Result<(), Error> {\n\n if slashed_inde...
Rust
day-16/src/main.rs
kecors/AoC-2017
ad624f56e3fa7617978c33dece7a9734a496066a
use std::io; use std::collections::HashMap; use std::collections::hash_map::Entry; use std::iter::FromIterator; extern crate pest; #[macro_use] extern crate pest_derive; use pest::Parser; #[derive(Parser)] #[grammar = "dance.pest"] struct DanceParser; #[derive(Debug)] enum Step { Spin(usize), Exchange(usize...
use std::io; use std::collections::HashMap; use std::collections::hash_map::Entry; use std::iter::FromIterator; extern crate pest; #[macro_use] extern crate pest_derive; use pest::Parser; #[derive(Parser)] #[grammar = "dance.pest"] struct DanceParser; #[derive(Debug)] enum Step { Spin(usize), Exchange(usize...
fn main() { let mut input = String::new(); io::stdin().read_line(&mut input).unwrap(); let steps: Vec<Step> = parse_line(input.trim()); let mut transforms: HashMap<Vec<char>, Vec<char>> = HashMap::new(); let mut permutations: Vec<Vec<char>> = Vec::new(); le...
function_block-full_function
[ { "content": "fn parse_line(stream: &str, state: &mut State) {\n\n let pairs = StreamParser::parse_str(Rule::stream, stream).unwrap_or_else(|e| panic!(\"{}\", e));\n\n\n\n //println!(\"pairs = {:?}\", pairs);\n\n for pair in pairs {\n\n state.process(match pair.as_rule() {\n\n Rule::g...
Rust
src/plugins/remind/parser.rs
Mavulp/frippy
77e6d390cebf99e220e61f2d2ea48d36f1aa0d4f
use chrono::{NaiveDate, NaiveDateTime, NaiveTime}; use humantime::parse_duration; use std::time::Duration; use time; use super::error::*; use failure::ResultExt; use log::debug; #[derive(Default, Debug)] pub struct CommandParser { on_date: Option<String>, at_time: Option<String>, in_duration: Option<Strin...
use chrono::{NaiveDate, NaiveDateTime, NaiveTime}; use humantime::parse_duration; use std::time::Duration; use time; use super::error::*; use failure::ResultExt; use log::debug; #[derive(Default, Debug)] pub struct CommandParser { on_date: Option<String>, at_time: Option<String>, in_duration: Option<Strin...
lf.at_time.is_none() => Ok(CommandParser { at_time: string, ..self }), In if self.in_duration.is_none() => Ok(CommandParser { in_duration: string, ..self }), Msg if self.message.is_none() => Ok(CommandParser ...
ut cur_str = String::new(); for token in tokens { let next_state = match token.as_ref() { "on" => ParseState::On, "at" => ParseState::At, "in" => ParseState::In, "every" => ParseState::Every, "to" => ParseState::Msg, ...
random
[ { "content": "pub fn download(_: &Context, url: String) -> Result<String, LuaError> {\n\n let url = Url::from(url).max_kib(1024);\n\n match url.request() {\n\n Ok(v) => Ok(v),\n\n Err(e) => {\n\n let error = match e.kind() {\n\n Connection => e.cause().unwrap().to_s...
Rust
sulis_state/src/area_feedback_text.rs
ThyWoof/sulis
e89eda94a1a72228224e1926d307aa4c9228bdcb
use std::rc::Rc; use std::time::Instant; use sulis_core::config::Config; use sulis_core::image::Image; use sulis_core::io::{DrawList, GraphicsRenderer}; use sulis_core::resource::{Font, ResourceSet}; use sulis_core::ui::{animation_state, Color, LineRenderer}; use sulis_core::util::{self, Offset, Point, Rect, Scale};...
use std::rc::Rc; use std::time::Instant; use sulis_core::config::Config; use sulis_core::image::Image; use sulis_core::io::{DrawList, GraphicsRenderer}; use sulis_core::resource::{Font, ResourceSet}; use sulis_core::ui::{animation_state, Color, LineRenderer}; use sulis_core::util::{self, Offset, Point, Rect, Scale};...
ea_pos.y -= 1; valid = false; break; } } if valid || area_pos.y == 0 { break; } } let width = target.size.width as f32; let pos_x = area_pos.x as f32 + width / 2.0; let pos_y = a...
mut area_pos = target.location.to_point(); loop { let mut valid = true; let pos_y = area_pos.y as f32; for text in area.feedback_text_iter() { let text_pos_y = text.area_pos().y as f32 - text.cur_hover_y(); if (pos_y - text_pos_y).abs() < 0.7 ...
random
[]
Rust
ruma-events/tests/enums.rs
jtescher/ruma
39b37e4fab6696ebfb889021ed303ae00e068bf8
use std::convert::TryFrom; use matches::assert_matches; use ruma_identifiers::{EventId, RoomAliasId, RoomId, UserId}; use serde_json::{from_value as from_json_value, json, Value as JsonValue}; use ruma_events::{ room::{ aliases::AliasesEventContent, message::{MessageEventContent, TextMessageEventC...
use std::convert::TryFrom; use matches::assert_matches; use ruma_identifiers::{EventId, RoomAliasId, RoomId, UserId}; use serde_json::{from_value as from_json_value, json, Value as JsonValue}; use ruma_events::{ room::{ aliases::AliasesEventContent, message::{MessageEventContent, TextMessageEventC...
}
if let AnyStateEventContent::RoomAliases(AliasesEventContent { aliases }) = deser.content() { assert_eq!(aliases, vec![RoomAliasId::try_from("#somewhere:localhost").unwrap()]) } else { panic!("the `Any*Event` enum's accessor methods may have been altered") }
if_condition
[ { "content": "fn redaction() -> JsonValue {\n\n json!({\n\n \"content\": {\n\n \"reason\": \"being a turd\"\n\n },\n\n \"redacts\": \"$nomore:example.com\",\n\n \"event_id\": \"$h29iv0s8:example.com\",\n\n \"sender\": \"@carl:example.com\",\n\n \"origin_se...
Rust
src/envelope.rs
TomPridham/messages-rs
8e220425bb09b04075908c4e9fe8dc7ea38444ae
use std::pin::Pin; use async_trait::async_trait; use crate::{ cfg_runtime, prelude::{Actor, Context, Handler, Notifiable}, }; #[async_trait] pub(crate) trait EnvelopeProxy<A: Actor + Unpin>: Send + 'static { async fn handle(&mut self, actor: Pin<&mut A>, context: Pin<&Context<A>>); } pub(crate) struct...
use std::pin::Pin; use async_trait::async_trait; use crate::{ cfg_runtime, prelude::{Actor, Context, Handler, Notifiable}, }; #[async_trait] pub(crate) trait EnvelopeProxy<A: Actor + Unpin>: Send + 'static { async fn handle(&mut self, actor: Pin<&mut A>, context: Pin<&Context<A>>); } pub(crate) struct...
} cfg_runtime! { use crate::handler::Coroutine; pub(crate) struct CoroutineEnvelope<A: Coroutine<IN>, IN> { data: Option<(IN, async_oneshot::Sender<A::Result>)>, } impl<A, IN> CoroutineEnvelope<A, IN> where A: Coroutine<IN>, { pub(crate) fn new(message: IN, response: ...
message .take() .expect("`Envelope::handle` called twice"); actor .get_mut() .notify(message, Pin::into_inner(context)) .await; }
function_block-function_prefix_line
[ { "content": "#[async_trait]\n\npub trait Actor: Unpin + Send + Sync + Sized + 'static {\n\n /// Method called after [`Context::run`] method was invoked.\n\n ///\n\n /// It is guaranteed to be called *before* any message will be\n\n /// passed to an actor.\n\n async fn started(&mut self) {}\n\n\n...
Rust
src/async_put.rs
rickycodes/cacache-rs
d2157ac9d81f592d873c38d5bc1e758f8447b7d2
use std::path::{Path, PathBuf}; use std::pin::Pin; use std::task::{Context, Poll}; use futures::prelude::*; use ssri::{Algorithm, Integrity}; use crate::content::write; use crate::errors::Error; use crate::index; pub use crate::put::PutOpts; pub async fn data<P, D, K>(cache: P, key: K, data: D) -> Result<Integrity...
use std::path::{Path, PathBuf}; use std::pin::Pin; use std::task::{Context, Poll}; use futures::prelude::*; use ssri::{Algorithm, Integrity}; use crate::content::write; use crate::errors::Error; use crate::index; pub use crate::put::PutOpts; pub async fn data<P, D, K>(cache: P, key: K, data: D) -> Result<Integrity...
} } pub struct AsyncPut { cache: PathBuf, key: String, written: usize, pub(crate) writer: write::AsyncWriter, opts: PutOpts, } impl AsyncWrite for AsyncPut { fn poll_write( mut self: Pin<&mut Self>, cx: &mut Context<'_>, buf: &[u8], ) -> Poll<std::io::Result<us...
Ok(AsyncPut { cache: cache.as_ref().to_path_buf(), key: String::from(key.as_ref()), written: 0, writer: write::AsyncWriter::new( cache.as_ref(), *self.algorithm.as_ref().unwrap_or(&Algorithm::Sha256), ) .await?, ...
call_expression
[ { "content": "/// Writes `data` to the `cache`, indexing it under `key`.\n\npub fn data<P, D, K>(cache: P, key: K, data: D) -> Result<Integrity, Error>\n\nwhere\n\n P: AsRef<Path>,\n\n D: AsRef<[u8]>,\n\n K: AsRef<str>,\n\n{\n\n let mut writer = PutOpts::new()\n\n .algorithm(Algorithm::Sha256...
Rust
telamon-gen/src/ast/choice/counter.rs
dan-zheng/telamon
de463284fdcea70ce29cf43a9c62f3aa2da14276
use std::iter; use crate::ast::constrain::Constraint; use crate::ast::context::CheckerContext; use crate::ast::error::TypeError; use crate::ast::{ type_check_code, type_check_enum_values, ChoiceDef, ChoiceInstance, Condition, CounterBody, CounterVal, VarDef, VarMap, }; use crate::ir::{self, Adaptable}; use cra...
use std::iter; use crate::ast::constrain::Constraint; use crate::ast::context::CheckerContext; use crate::ast::error::TypeError; use crate::ast::{ type_check_code, type_check_enum_values, ChoiceDef, ChoiceInstance, Condition, CounterBody, CounterVal, VarDef, VarMap, }; use crate::ir::{self, Adaptable}; use cra...
} impl PartialEq for CounterDef { fn eq(&self, rhs: &Self) -> bool { self.name == rhs.name } }
self, context: &mut CheckerContext, choice_defs: &mut Vec<ChoiceDef>, ) -> Result<(), TypeError> { choice_defs.push(ChoiceDef::CounterDef(self)); Ok(()) }
function_block-function_prefixed
[ { "content": "#[allow(unused_mut)]\n\npub fn restrict_{{name}}(&mut self{{>args_decl}}, mut value: {{>value_type.name value_type}},\n\n diff: &mut DomainDiff) -> Result<(), ()> {\n\n {{#if is_symmetric~}}\n\n if {{arguments.[0].[0]}} > {{arguments.[1].[0]}} {\n\n std...
Rust
ds/src/mem/buffer.rs
weibocom/breeze
0c8ee87d3fa2ac16125d7b9690b69d375d6ef438
use super::RingSlice; use std::ptr::NonNull; use std::slice::from_raw_parts_mut; pub struct RingBuffer { data: NonNull<u8>, size: usize, read: usize, write: usize, } impl RingBuffer { pub fn with_capacity(size: usize) -> Self { let buff_size = size.next_power_of_two(); let mut dat...
use super::RingSlice; use std::ptr::NonNull; use std::slice::from_raw_parts_mut; pub struct RingBuffer { data: NonNull<u8>, size: usize, read: usize, write: usize, } impl RingBuffer { pub fn with_capacity(size: usize) -> Self { let buff_size = size.next_power_of_two(); let mut dat...
rite!( f, "rb:(ptr:{:#x} cap:{} read:{} write:{})", self.data.as_ptr() as usize, self.size, self.read, self.write ) } } unsafe impl Send for RingBuffer {} unsafe impl Sync for RingBuffer {}
cap(&self) -> usize { self.size } #[inline(always)] pub fn len(&self) -> usize { debug_assert!(self.write >= self.read); self.write - self.read } #[inline(always)] pub(crate) fn available(&self) -> bool { self.read() + self.cap() > self.writtened() } #[inl...
random
[ { "content": "pub fn build_refresh_idc() -> impl Fn(&str) {\n\n let (w, r) = ds::cow(DistanceCalculator::default());\n\n if let Err(_) = DISTANCE_CALCULATOR.set(r) {\n\n panic!(\"duplicate init\");\n\n }\n\n if let Err(_) = DISTANCE_CALCULATOR_W.set(Mutex::from(w)) {\n\n panic!(\"dupli...
Rust
src/exec.rs
absurdhero/rash-shell
02fc3813bfb36b1ea8de4f382d2edfc3d5180fc8
use std::convert::Infallible; use std::env; use std::ffi::CString; use std::ffi::OsStr; use std::os::unix::ffi::OsStrExt; use std::path::PathBuf; use nix::unistd::*; use crate::context; pub fn run_command( context: &mut context::Context, cmd: &str, args: &[String], env: &[&str], stdio: context:...
use std::convert::Infallible; use std::env; use std::ffi::CString; use std::ffi::OsStr; use std::os::unix::ffi::OsStrExt; use std::path::PathBuf; use nix::unistd::*; use crate::context; pub fn run_command( context: &mut context::Context, cmd: &str, args: &[String], env: &[&str], stdio: context:...
exported_cstrings .iter() .map(|c| c.as_c_str()) .collect::<Vec<_>>() .as_slice(), ) } fn filepath(path: PathBuf, filename: &str) -> String { let path_buf = path.join(OsStr::from_bytes(filename.as_bytes())); path_buf.into_os_string().into_string().unwra...
t exported_cstrings = exported_env .iter() .map(|c| CString::new(c.as_str()).unwrap()) .collect::<Vec<_>>(); execve( CString::new(filepath).unwrap().as_c_str(), arg_cstrings .iter() .map(|c| c.as_c_str()) .collect::<Vec<_>>() ....
function_block-random_span
[ { "content": "fn export(args: &[String], context: &mut Context, stdio: StdIo) -> i32 {\n\n if args.len() == 1 || args[1] == \"-p\" {\n\n context\n\n .env\n\n .iter()\n\n .filter(|(_, v)| v.export)\n\n .for_each(|(k, v)| {\n\n if let Some(val) ...
Rust
cmd/starcoin/src/dev/execute_cmd.rs
fakecoinbase/starcoinorgslashstarcoin
100a01fb1c967d1b4dd0dc1b9d5787d45c9ba399
use crate::cli_state::CliState; use crate::view::{ExecuteResultView, ExecutionOutputView}; use crate::StarcoinOpt; use anyhow::{bail, format_err, Result}; use scmd::{CommandAction, ExecContext}; use starcoin_crypto::hash::PlainCryptoHash; use starcoin_move_compiler::shared::Address; use starcoin_move_compiler::{ ...
use crate::cli_state::CliState; use crate::view::{ExecuteResultView, ExecutionOutputView}; use crate::StarcoinOpt; use anyhow::{bail, format_err, Result}; use scmd::{CommandAction, ExecContext}; use starcoin_crypto::hash::PlainCryptoHash; use starcoin_move_compiler::shared::Address; use starcoin_move_compiler::{ ...
().map_err(|status_code| { format_err!("TransactionStatus is discard: {:?}", status_code) })?; if keep_status != KeptVMStatus::Executed { bail!("move file pre-run failed, {:?}", keep_status); } if !opt.dry_run { let succ = client.submit_transaction(sig...
, default_value = "1", help = "gas price used to execute the script" )] gas_price: u64, #[structopt( short = "b", name = "blocking-mode", long = "blocking", help = "blocking wait txn mined" )] blocking: bool, #[structopt(long = "dry-run")] ...
random
[ { "content": "pub fn timeout<F, T>(timeout: u64, f: F, tx: Sender<Option<T>>)\n\nwhere\n\n F: FnOnce() -> T,\n\n F: Send + 'static,\n\n T: Send + 'static,\n\n{\n\n let tx_clone = tx.clone();\n\n let tx_cl = tx.clone();\n\n std::thread::spawn(move || {\n\n std::thread::sleep(std::time::D...
Rust
src/bin/nes.rs
envis10n/rs6502
55dbab45416ba848246618153ea01955eab07877
use rs6502::{ bus::{Bus, MemoryMapper}, memory::Memory, CpuFlags, Mos6502, }; use std::sync::{Arc, RwLock}; const NES_TAG: [u8; 4] = [0x4e, 0x45, 0x53, 0x1a]; const PRG_ROM_PAGE_SIZE: usize = 16384; const CHR_ROM_PAGE_SIZE: usize = 8192; const RAM: u16 = 0x0000; const RAM_MIRRORS_END: u16 = 0x1FFF; const ...
use rs6502::{ bus::{Bus, MemoryMapper}, memory::Memory, CpuFlags, Mos6502, }; use std::sync::{Arc, RwLock}; const NES_TAG: [u8; 4] = [0x4e, 0x45, 0x53, 0x1a]; const PRG_ROM_PAGE_SIZE: usize = 16384; const CHR_ROM_PAGE_SIZE: usize = 8192; const RAM: u16 = 0x0000; const RAM_MIRRORS_END: u16 = 0x1FFF; const ...
} impl Memory for Rom { fn mem_read(&self, addr: u16) -> u8 { match addr { 0x8000..=0xFFFF => { let mut rom_addr = addr - 0x8000; if self.prg_rom.len() == 0x4000 && rom_addr >= 0x4000 { rom_addr = rom_addr % 0x4000; } ...
if ines_ver != 0 { return Err("NES2.0 format is unsupported".to_string()); } let four_screen = raw[6] & 0b1000 != 0; let vertical_mirroring = raw[6] & 0b1 != 0; let screen_mirroring = match (four_screen, vertical_mirroring) { (true, _) => Mirroring::FourScreen, ...
function_block-function_prefix_line
[ { "content": "pub trait MemoryMapper<'a> {\n\n fn map_region<C>(&mut self, start: u16, end: u16, controller: Arc<RwLock<C>>) -> Result<()> where C: Memory + 'a;\n\n}\n\n\n\nimpl<'a> Memory for Arc<RwLock<Bus<'a>>> {\n\n fn mem_read(&self, addr: u16) -> u8 {\n\n let reader = self.read().unwrap();\n\...
Rust
src/traffic/analyze.rs
QaQAdrian/network_traffic
12046ad020469bbdf8feed70044ff9838bf1fce1
use std::net::IpAddr; use pnet::datalink::{NetworkInterface}; use pnet::ipnetwork::IpNetwork; use pnet::packet::ethernet::{EthernetPacket, EtherTypes, MutableEthernetPacket}; use pnet::packet::ip::{IpNextHeaderProtocol, IpNextHeaderProtocols}; use pnet::packet::ipv4::Ipv4Packet; use pnet::packet::ipv6::Ipv6Packet; ...
use std::net::IpAddr; use pnet::datalink::{NetworkInterface}; use pnet::ipnetwork::IpNetwork; use pnet::packet::ethernet::{EthernetPacket, EtherTypes, MutableEthernetPacket}; use pnet::packet::ip::{IpNextHeaderProtocol, IpNextHeaderProtocols}; use pnet::packet::ipv4::Ipv4Packet; use pnet::packet::ipv6::Ipv6Packet; ...
if interface.is_loopback() { payload_offset = 14; } else { payload_offset = 0; } if packet.len() > payload_offset { let version = Ipv4Packet::new(&packet[payload_offset..]) .unwrap() .get_versio...
ddr) -> bool { { return network_interface_ips .iter() .any(|ip_network| ip_network.ip() == source); } } fn handle_ethernet_frame(interface: &NetworkInterface, ethernet: &EthernetPacket) -> Option<Frame> { return match ethernet.get_ethertype() { EtherTypes::Ipv4 => { ...
random
[ { "content": "pub fn get_port_process_map(frames: &Vec<crate::traffic::analyze::Frame>) -> HashMap<u16, u32> {\n\n let mut map: HashMap<u16, u32> = HashMap::new();\n\n for item in frames {\n\n map.insert(item.local_port(), 0);\n\n }\n\n\n\n let sockets_info = get_sockets_info(\n\n Addr...
Rust
src/scenes/main_menu_scene.rs
LucidSigma/space-invaders
09a4989cf8f528a9cb032defde2b5604d50c27f7
use std::collections::VecDeque; use std::fs; use sdl2::{ keyboard::Scancode, mixer::{Channel, Chunk, Music}, mouse::MouseButton, pixels::Color as Colour, rect::{Point, Rect}, render::{Texture, TextureCreator, WindowCanvas}, ttf::Font, }; use super::button::Button; use crate::game::input::I...
use std::collections::VecDeque; use std::fs; use sdl2::{ keyboard::Scancode, mixer::{Channel, Chunk, Music}, mouse::MouseButton, pixels::Color as Colour, rect::{Point, Rect}, render::{Texture, TextureCreator, WindowCanvas}, ttf::Font, }; use super::button::Button; use crate::game::input::I...
fn update( &mut self, _delta_time: f32, scene_queue: &mut VecDeque<Box<dyn Scene>>, _canvas: &WindowCanvas, sound_channel: &Channel, ) { for button in &mut self.buttons { if button.is_hovered && !button.played_enter_sound { sound_chan...
e; if button.is_mouse_over(input_state) { button.is_hovered = true; if input_state.is_mouse_button_down(MouseButton::Left) { button.is_clicked = true; } } else if button.played_enter_sound { button.played_enter...
function_block-function_prefixed
[ { "content": "pub fn play(initial_scene: Box<dyn Scene>) {\n\n let config = read_config_file().unwrap();\n\n\n\n let (sdl_context, _image_context, _mixer_context, ttf_context, video_subsystem) =\n\n initialise_sdl().unwrap();\n\n let mut canvas = initialise_canvas(&video_subsystem, &config).unwr...
Rust
ractor-rpc/src/ws/server.rs
juzi5201314/ractor
40bc7f717cc8364cf1e32a1dfdbb82a57c9fa4c5
use std::collections::HashMap; use std::future::Future; use std::net::SocketAddr; use std::pin::Pin; use std::sync::Arc; use futures::{SinkExt, StreamExt}; use tokio::net::{TcpListener, TcpStream}; use tokio_tungstenite::tungstenite::protocol::WebSocketConfig; use tokio_tungstenite::tungstenite::Message; use tokio_tun...
use std::collections::HashMap; use std::future::Future; use std::net::SocketAddr; use std::pin::Pin; use std::sync::Arc; use futures::{SinkExt, StreamExt}; use tokio::net::{TcpListener, TcpStream}; use tokio_tungstenite::tungstenite::protocol::WebSocketConfig; use tokio_tungstenite::tungstenite::Message; use tokio_tun...
async fn handle_connection(stream: WebSocketStream<TcpStream>, register: Arc<MessageRegister>) { let (mut outgoing, mut incoming) = stream.split(); while let Some(Ok(msg)) = incoming.next().await { match msg { Message::Binary(msg) => { let msg: crat...
let mut handles = Vec::new(); while let Ok((stream, _peer_addr)) = self.tcp_listener.accept().await { let stream = match tokio_tungstenite::accept_async_with_config( stream, Some(self.config.clone()), ) .await { Ok(s...
function_block-function_prefix_line
[ { "content": "/// 实现了`RemoteType`表示该类型可以被远程发送或者接收\n\n/// 为基础类型实现了`RemoteType`\n\npub trait RemoteType: Serialize + DeserializeOwned + Send {\n\n type Identity: Hash;\n\n\n\n /// 唯一标识符\n\n /// 应该保证: A.identity() == B.identity() && deserialize::<B>(serialize(A)) && deserialize::<A>(serialize(B))\n\n f...
Rust
benches/main.rs
jeremie-martin/lbm-blood-1d
f5b5669cb1edee73adc3456737a20f43ffd32e4e
#![allow(non_snake_case)] use criterion::*; use lbm_blood_1d::constants::*; use lbm_blood_1d::lbm_algorithm::*; use lbm_blood_1d::simulation::*; use lbm_blood_1d::simulation_parsing::*; use lbm_blood_1d::vessels::*; use std::collections::VecDeque; use std::ptr; macro_rules! expand_names { ( $last:ident ) => { ...
#![allow(non_snake_case)] use criterion::*; use lbm_blood_1d::constants::*; use lbm_blood_1d::lbm_algorithm::*; use lbm_blood_1d::simulation::*; use lbm_blood_1d::simulation_parsing::*; use lbm_blood_1d::vessels::*; use std::collections::VecDeque; use std::ptr; macro_rules! expand_names { ( $last:ident ) => { ...
pub fn functional2<T: Compute>(sim: &mut Simulation<T>) { let dt = sim.consts.dt; let owo = sim.consts.c; let rho = sim.consts.rho; let dx = sim.consts.dx; let cs2 = sim.consts.cs2; for v in &mut sim.vessels { for i in 0..v.x_dim { let P_derivative = (v.cells.beta[i]) / (2...
for i in 0..v.x_dim { v.cells.u[i] += ((v.consts.dt / 2.0) * v.cells.F[i]) / v.cells.A[i]; let uc = v.cells.u[i] / v.consts.c; let uc2 = uc * uc; v.cells.f0[i] = (1.0 / 3.0) * v.cells.A[i] * (2.0 - 3.0 * uc2); v.cells.f1[i] = (1.0 / 6.0) * v.cells.A[i] * (1.0 ...
function_block-function_prefix_line
[ { "content": "/// Installs [subscribers](tracing_subscriber::fmt::Subscriber) given the command line arguments\n\n///\n\n/// Returns the [guards](tracing_appender::non_blocking::WorkerGuard) that we create to keep them alive,\n\n/// which is needed to record events outside of this function\n\n///\n\n/// # Examp...
Rust
kuon_macro/kuon_request_derive/src/lib.rs
yongikim/kuon
ecb71b55ba6b1e4be4d4805cfdceaf3c399a31bf
use std::collections::HashMap; use heck::SnakeCase; use kuon_proc_macro_utils::{ count_generics_types, extract_doc_attr, extract_generics_names, extract_inner_type, extract_struct_fields, is_int_type, is_option_type, is_vec_type, }; use proc_macro2::{Ident, TokenStream}; use quote::{format_ident, quote}; use s...
use std::collections::HashMap; use heck::SnakeCase; use kuon_proc_macro_utils::{ count_generics_types, extract_doc_attr, extract_generics_names, extract_inner_type, extract_struct_fields, is_int_type, is_option_type, is_vec_type, }; use proc_macro2::{Ident, TokenStream}; use quote::{format_ident, quote}; use s...
} else { quote! { #doc pub fn #ident(&mut self, #ident: impl Into<#inner_ty>) -> &mut Self { self.#ident = Some(#ident.into()); self } } } } else { quote! {} } } fn impl_requ...
shMap<String, Option<Attribute>>, ) -> TokenStream { let ty = &field.ty; let ident = &field.ident; let doc = if let Some(ident) = ident { doc_comment_map.get(&ident.to_string()) } else { None }; if let syn::GenericArgument::Type(inner_ty) = extract_inner_type(ty) { if is_...
function_block-random_span
[ { "content": "pub fn extract_generics_names(Generics { params, .. }: &Generics) -> Vec<String> {\n\n params\n\n .iter()\n\n .filter_map(|param| match param {\n\n syn::GenericParam::Type(TypeParam { ident, .. }) => Some(ident.to_string()),\n\n _ => None,\n\n })\n\n ...
Rust
examples/echo_middleware.rs
Spora-GH/wascc-host
32aa640c0db0417b584f7229137ac26580a308cd
use std::collections::HashMap; use wascc_host::middleware::{InvocationHandler, MiddlewareResponse}; use wascc_host::{Actor, Host, Invocation, InvocationResponse, Middleware, NativeCapability}; #[macro_use] extern crate log; type Result<T> = std::result::Result<T, wascc_host::errors::Error>; fn main() -> std::result:...
use std::collections::HashMap; use wascc_host::middleware::{InvocationHandler, MiddlewareResponse}; use wascc_host::{Actor, Host, Invocation, InvocationResponse, Middleware, NativeCapability}; #[macro_use] extern crate log; type Result<T> = std::result::Result<T, wascc_host::errors::Error>; fn main() -> std::result:...
} #[derive(Default)] struct LoggingMiddleware {} impl Middleware for LoggingMiddleware { fn actor_pre_invoke(&self, inv: Invocation) -> wascc_host::Result<Invocation> { info!("LoggingMiddleware-ACTOR(PRE): {}", inv.operation); Ok(inv) } fn actor_invoke( &self, inv: Invoca...
fn capability_post_invoke( &self, response: InvocationResponse, ) -> wascc_host::Result<InvocationResponse> { info!( "CachingMiddleware-CAP(POST): success: {}", response.error.is_none() ); Ok(response) }
function_block-full_function
[ { "content": "#[cfg(not(feature = \"prometheus_middleware\"))]\n\nfn main() -> std::result::Result<(), Box<dyn std::error::Error + Send + Sync>> {\n\n println!(\"Feature 'prometheus_middleware' needed to run this example\");\n\n Ok(())\n\n}\n\n\n\n#[cfg(feature = \"prometheus_middleware\")]\n\nmod prometh...
Rust
crates/dprint/src/plugins/wasm/functions.rs
bartlomieju/dprint
da162e4a63d981d663834019cd61dee863d5540f
use wasmer_runtime_core::export::Exportable; use wasmer_runtime::{Instance, Func, WasmPtr, Array, Memory}; use super::super::super::types::ErrBox; const CURRENT_SCHEMA_VERSION: u32 = 1; pub enum FormatResult { NoChange = 0, Change = 1, Error = 2, } impl From<u8> for FormatResult { fn from(orig: u8) ...
use wasmer_runtime_core::export::Exportable; use wasmer_runtime::{Instance, Func, WasmPtr, Array, Memory}; use super::super::super::types::ErrBox; const CURRENT_SCHEMA_VERSION: u32 = 1; pub enum FormatResult { NoChange = 0, Change = 1, Error = 2, } impl From<u8> for FormatResult { fn from(orig: u8) ...
} pub struct WasmFunctions { instance: Instance, } impl WasmFunctions { pub fn new(instance: Instance) -> Result<Self, ErrBox> { let plugin_schema_version_func: Func<(), u32> = instance.exports.get("get_plugin_schema_version")?; let plugin_schema_version = plugin_schema_version_func.call().un...
e, 1 => FormatResult::Change, 2 => FormatResult::Error, _ => unreachable!(), } }
function_block-function_prefixed
[ { "content": "// trait alias hack (https://www.worthe-it.co.za/programming/2017/01/15/aliasing-traits-in-rust.html)\n\npub trait CompileFn: Fn(&[u8]) -> Result<CompilationResult, ErrBox> {\n\n}\n\n\n\nimpl<T> CompileFn for T where T : Fn(&[u8]) -> Result<CompilationResult, ErrBox> {\n\n}\n", "file_path": "c...
Rust
src/api/tests.rs
parampavar/vector
83bd797ff6a05fb3246a2442a701db3a85e323b5
use futures::SinkExt; use futures::StreamExt; use tokio::sync::watch; use super::*; use crate::api::schema::events::notification::{EventNotification, EventNotificationType}; use crate::api::schema::events::output::OutputEventsPayload; use crate::api::schema::events::{create_events_stream, log, metric}; use crate::conf...
use futures::SinkExt; use futures::StreamExt; use tokio::sync::watch; use super::*; use crate::api::schema::events::notification::{EventNotification, EventNotificationType}; use crate::api::schema::events::output::OutputEventsPayload; use crate::api::schema::events::{create_events_stream, log, metric}; use crate::conf...
n(transform_tap_events[0][0].clone()), EventNotification::new("transform".to_string(), EventNotificationType::Matched) ); let _log = assert_log(transform_tap_events[1][0].clone()); } #[tokio::test] async fn integration_test_tap_non_default_output() { let mut config = Config::builder(); config.a...
source: Some("".to_string()), ..Default::default() }, ); config.add_sink( "out", &["transform"], BlackholeConfig { print_interval_secs: 1, rate: None, }, ); let (topology, _crash) = start_topology(config.build().unwrap(...
function_block-random_span
[ { "content": "fn to_metric(config: &MetricConfig, event: &Event) -> Result<Metric, TransformError> {\n\n let log = event.as_log();\n\n\n\n let timestamp = log\n\n .get(log_schema().timestamp_key())\n\n .and_then(Value::as_timestamp)\n\n .cloned();\n\n let metadata = event.metadata(...
Rust
src/main.rs
reiyw/kb-tool
f92560676824f9aab487ed44c724a237fd2834e5
use counter::Counter; use kb_tool::graph::KG; use kb_tool::triple::{read_triples, TripleOrder}; use std::fs::{self, File}; use std::io::{stdout, BufWriter, Write}; use std::path::PathBuf; use structopt::StructOpt; #[derive(StructOpt, Debug)] #[structopt(name = "kb-tool")] enum Opt { #[structopt(name = "cutoff...
use counter::Counter; use kb_tool::graph::KG; use kb_tool::triple::{read_triples, TripleOrder}; use std::fs::{self, File}; use std::io::{stdout, BufWriter, Write}; use std::path::PathBuf; use structopt::StructOpt; #[derive(StructOpt, Debug)] #[structopt(name = "kb-tool")] enum Opt { #[structopt(name = "cutoff...
, Opt::SamplePath { file, path_len, sample_size, dedup, } => sample_path(file, path_len, sample_size, dedup), } } fn cutoff_at_frequency( file: PathBuf, outdir: PathBuf, min_ent: usize, min_rel: usize, dedup_before_count: bool, ...
cutoff_at_frequency( file, outdir, min_ent, min_rel, dedup_before_count, dedup_after_count, )
call_expression
[ { "content": "pub fn read_triples(triples: &str, order: TripleOrder) -> Triples {\n\n triples\n\n .lines()\n\n .map(|line| {\n\n let v: Vec<&str> = line.split('\\t').collect();\n\n match &order {\n\n TripleOrder::HRT => Triple::new(v[0], v[1], v[2]),\n\n ...
Rust
src/ms_table_read_es.rs
pasindumuth/rUniversalDB
9dd786d795807afaa0fb05c2693b8b776beadc22
use crate::col_usage::{collect_top_level_cols, compute_select_schema, free_external_cols}; use crate::common::{ lookup, mk_qid, to_table_path, CoreIOCtx, KeyBound, OrigP, QueryESResult, QueryPlan, ReadRegion, Timestamp, }; use crate::expression::{compress_row_region, compute_key_region, is_true}; use crate::gr_quer...
use crate::col_usage::{collect_top_level_cols, compute_select_schema, free_external_cols}; use crate::common::{ lookup, mk_qid, to_table_path, CoreIOCtx, KeyBound, OrigP, QueryESResult, QueryPlan, ReadRegion, Timestamp, }; use crate::expression::{compress_row_region, compute_key_region, is_true}; use crate::gr_quer...
row_region.push(key_bound); } } row_region = compress_row_region(row_region); let mut val_col_region = BTreeSet::<ColName>::new(); val_col_region.extend(self.query_plan.col_usage_node.safe_present_cols.clone()); for (key_col, _) in &ctx.table_schema.key_cols { val_col_region.remo...
ueryPath>, pub state: MSReadExecutionS, } pub enum MSTableReadAction { Wait, SendSubqueries(Vec<GRQueryES>), Success(QueryESResult), QueryError(msg::QueryError), } impl MSTableReadES { pub fn start<IO: CoreIOCtx>( &mut self, ctx: &mut TabletContext, io_ctx: &mut IO, ) -> MSTableR...
random
[ { "content": "pub fn convert_to_msquery(query: iast::Query) -> Result<proc::MSQuery, msg::ExternalAbortedData> {\n\n // First, we rename all TransTable definitions and references so that they're\n\n // unique. To do this, we just prepend `tt\\n\\`, where `n` is integers that we get\n\n // from a counter. Thi...
Rust
rust-hdl/src/widgets/bidirectional_bus.rs
SmithsDigitalForge/rust-hdl
b3c7f5543fee96b3aa0f9f7918c618827adb826c
use crate::core::prelude::*; use crate::widgets::async_fifo::AsynchronousFIFO; use crate::widgets::dff::DFF; use crate::widgets::prelude::{SynchronousFIFO, TristateBuffer}; #[derive(Clone, Debug, Default, LogicInterface)] #[join = "FifoBusIn"] pub struct FifoBus<T: Synth> { pub to_bus: Signal<In, T>, pub write...
use crate::core::prelude::*; use crate::widgets::async_fifo::AsynchronousFIFO; use crate::widgets::dff::DFF; use crate::widgets::prelude::{SynchronousFIFO, TristateBuffer}; #[derive(Clone, Debug, Default, LogicInterface)] #[join = "FifoBusIn"] pub struct FifoBus<T: Synth> { pub to_bus: Signal<In, T>, pub write...
} #[test] fn test_bidi_device_synthesizable() { let mut uut = BidiSimulatedDevice::<Bits<8>, 8, 9>::default(); uut.bus.connect(); uut.data.read.connect(); uut.data.write.connect(); uut.clock.connect(); uut.data.to_bus.connect(); uut.bus.sig_not_read.connect(); uut.bus.sig_not_write.con...
fn update(&mut self) { self.fifo_to_bus.clock.next = self.clock.val(); self.fifo_from_bus.clock.next = self.clock.val(); self.bus.sig_inout.link(&mut self.bus_buffer.bus); self.fifo_to_bus.data_in.next = self.data.to_bus.val(); self.fifo_to_bus...
function_block-full_function
[ { "content": "#[inline(always)]\n\npub fn bit_cast<const M: usize, const N: usize>(x: Bits<N>) -> Bits<M> {\n\n match x {\n\n Bits::Short(t) => {\n\n let t: ShortType = t.into();\n\n let k: Bits<M> = t.into();\n\n k\n\n }\n\n Bits::Long(t) => {\n\n ...
Rust
src/lib.rs
typst/pixglyph
f1aae13ae622f4640a1cfac231525f02978fc305
#![forbid(unsafe_code)] #![deny(missing_docs)] use std::fmt::{self, Debug, Formatter}; use std::ops::{Add, Div, Mul, Sub}; use ttf_parser::{Face, GlyphId, OutlineBuilder, Rect}; #[derive(Debug, Clone)] pub struct Glyph { units_per_em: u16, bbox: Rect, segments: Vec<Segment>, } #[derive(...
#![forbid(unsafe_code)] #![deny(missing_docs)] use std::fmt::{self, Debug, Formatter}; use std::ops::{Add, Div, Mul, Sub}; use ttf_parser::{Face, GlyphId, OutlineBuilder, Rect}; #[derive(Debug, Clone)] pub struct Glyph { units_per_em: u16, bbox: Rect, segments: Vec<Segment>, } #[derive(...
} impl Canvas { fn cubic(&mut self, p0: Point, p1: Point, p2: Point, p3: Point) { let p1x2 = 3.0 * p1 - p0; let p2x2 = 3.0 * p2 - p3; let err = hypot2(p2x2 - p1x2); let tol = 0.333; let max = 432.0 * tol * tol; let n = (err / max).powf(1.0 / ...
t) { let devsq = hypot2(p0 - 2.0 * p1 + p2); if devsq < 0.333 { self.line(p0, p2); return; } let tol = 3.0; let n = 1.0 + (tol * devsq).sqrt().sqrt().floor().min(30.0); let nu = n as usize; let step = n.recip();...
function_block-function_prefixed
[ { "content": "fn raster_letter(font: &[u8], letter: char, x: f32, y: f32, s: f32) -> bool {\n\n let out_path = format!(\"target/{}.ppm\", letter);\n\n let ref_path = format!(\"tests/{}.ppm\", letter);\n\n\n\n let face = Face::from_slice(font, 0).unwrap();\n\n let id = face.glyph_index(letter).unwrap...
Rust
src/wave.rs
TanTanDev/rusty_demon_attack
e8166962095b67e7edc7a380db83be25562355e2
use macroquad::prelude::*; use quad_snd::mixer::{SoundMixer, Volume}; use crate::{ constants::*, enemy::{Enemy, EnemyColor, EnemyDeathMethod, EnemyType}, resources::{Resources, SoundIdentifier}, variant_eq, }; pub struct WaveManagerStateSpawning { enemies_left: i32, spawn_timer: f32, } pub enu...
use macroquad::prelude::*; use quad_snd::mixer::{SoundMixer, Volume}; use crate::{ constants::*, enemy::{Enemy, EnemyColor, EnemyDeathMethod, EnemyType}, resources::{Resources, SoundIdentifier}, variant_eq, }; pub struct WaveManagerStateSpawning { enemies_left: i32, spawn_timer: f32, } pub enu...
pub fn update( &mut self, dt: f32, enemies: &mut Vec<Enemy>, resources: &Resources, sound_mixer: &mut SoundMixer, ) -> Option<WaveManagerMessage> { self.internal_timer += dt; let state_command_optional = match &mut self.state { WaveManagerSta...
TIL_MAX_DIFFICULTY; let spawn_countf32 = lininterp::lerp( &(ENEMY_SPAWN_STARTING_COUNT as f32), &(ENEMY_SPAWN_MAX_COUNT as f32), &fraction, ); spawn_countf32 as i32 }
function_block-function_prefixed
[ { "content": "// okay this is pretty hacky...\n\n// if last kill was from player then a life should've been gained, so animate lives\n\npub fn draw_lives(\n\n player_lives: &i32,\n\n texture_life: Texture2D,\n\n texture_ground_bg: &Texture2D,\n\n game_manager: &WaveManager,\n\n) {\n\n let lives_p...
Rust
src/utils.rs
Ptrskay3/pysprint-cli
09751a62189479b06f172025d7229f4d2424e11f
use crate::codegen::maybe_write_default_yaml; use crate::deserialize::LoadOptions; use crate::io::create_results_file; use clap::ArgMatches; use indicatif::{ProgressBar, ProgressStyle}; use std::io::Write; use std::path::{Path, PathBuf}; use termcolor::{Color, ColorSpec, StandardStream, WriteColor}; use wildmatch::Wild...
use crate::codegen::maybe_write_default_yaml; use crate::deserialize::LoadOptions; use crate::io::create_results_file; use clap::ArgMatches; use indicatif::{ProgressBar, ProgressStyle}; use std::io::Write; use std::path::{Path, PathBuf}; use termcolor::{Color, ColorSpec, StandardStream, WriteColor}; use wildmatch::Wild...
files.len() && warn { let _ = stdout.set_color(ColorSpec::new().set_fg(Some(Color::Yellow))); let _ = writeln!( stdout, "[WARN] The number of files is not divisible by 3, it's very likely that this command will fail.. Maybe you forgot to exclude/include some?" ); ...
(result_file); if matches.is_present("override") { if result_filepath.exists() { let _ = writeln!( stdout, "[INFO] Overriding result file at {:?}.", &result_filepath ); } else if let Err(e) = writ...
random
[ { "content": "/// Check if we're able to start a Python interpreter,\n\n/// and fail early if we can't.\n\npub fn py_handshake(stdout: &mut StandardStream) {\n\n let pb = get_spinner();\n\n\n\n // A quick check whether Python is ready.\n\n pb.set_message(\"Initializing Python..\");\n\n let _ = prepa...
Rust
client/src/resources/effect/test.rs
nebkor/stellar-sdk
b2893e3e859c3d6e01eea70fb177e5bbd53af3c7
use resources::{ asset::Flags, effect::{ account::Kind as AccountKind, data::Kind as DataKind, signer::Kind as SignerKind, trade::Kind as TradeKind, trustline::Kind as TrustlineKind, Effect, EffectKind, }, Amount, }; use serde_json; fn account_created_json() -> &'static str { includ...
use resources::{ asset::Flags, effect::{ account::Kind as AccountKind, data::Kind as DataKind, signer::Kind as SignerKind, trade::Kind as TradeKind, trustline::Kind as TrustlineKind, Effect, EffectKind, }, Amount, }; use serde_json; fn account_created_json() -> &'static str { includ...
} fn trustline_deauthorized_json() -> &'static str { include_str!("../../../fixtures/effects/trustline_deauthorized.json") } #[test] fn it_parses_trustline_deauthorized_from_json() { let effect: Effect = serde_json::from_str(&trustline_deauthorized_json()).unwrap(); assert!(effect.is_trustline_deauthorize...
if let &EffectKind::Trustline(TrustlineKind::Authorized(ref effect_details)) = effect.kind() { assert_eq!( effect_details.account(), "GA6U5X6WOPNKKDKQULBR7IDHDBAQKOWPHYEC7WSXHZBFEYFD3XVZAKOO" ); assert_eq!(effect_details.asset().code(), "TESTTEST"); } else { p...
if_condition
[ { "content": "fn create_account_json() -> &'static str {\n\n include_str!(\"../../../fixtures/operations/create_account.json\")\n\n}\n\n\n", "file_path": "client/src/resources/operation/test.rs", "rank": 15, "score": 316259.578232554 }, { "content": "fn manage_data_json() -> &'static str ...
Rust
sys/kernel/src/arch/x86/pc98.rs
neri/toe
8442f82bce551ce27b23b24336a285f25d422e98
use super::pic::Irq; use crate::io::hid::*; static mut PC98: Pc98 = Pc98::new(); pub struct Pc98 { key_modifier: Modifier, mouse_state: MouseState, } impl Pc98 { const PORT_MOUSE_CTRL: usize = 0x7FDD; const PORT_MOUSE_READ: usize = 0x7FD9; const fn new() -> Self { Self { ke...
use super::pic::Irq; use crate::io::hid::*; static mut PC98: Pc98 = Pc98::new(); pub struct Pc98 { key_modifier: Modifier, mouse_state: MouseState, } impl Pc98 { const PORT_MOUSE_CTRL: usize = 0x7FDD; const PORT_MOUSE_READ: usize = 0x7FD9; const fn new() -> Self { Self { ke...
fn irq13(_irq: Irq) { let shared = Self::shared(); unsafe { let mut c0: u8; asm!("in al, dx", in("edx") Self::PORT_MOUSE_CTRL, out("al") c0); c0 = (c0 & 0x0F) | 0x90; asm!("out dx, al", in("edx") Self::PORT_MOUSE_CTRL, in("al") c0); ...
al out 0x5F, al in al, 0x41 ", out ("al") data); shared.process_key_data(data); } }
function_block-function_prefixed
[]
Rust
main/high/src/main_task_middleware.rs
Schroedingers-Cat/reaper-rs
32ff26a2dc977f3bfcbd7c01696c31a08cc46c90
use crossbeam_channel::{Receiver, Sender}; use crate::{Reaper, DEFAULT_MAIN_THREAD_TASK_BULK_SIZE}; use futures::channel::oneshot; use std::time::{Duration, SystemTime}; pub struct TaskSupport { sender: Sender<MainThreadTask>, } unsafe impl Sync for TaskSupport {} impl TaskSupport { pub fn new(sender: Sende...
use crossbeam_channel::{Receiver, Sender}; use crate::{Reaper, DEFAULT_MAIN_THREAD_TASK_BULK_SIZE}; use futures::channel::oneshot; use std::time::{Duration, SystemTime}; pub struct TaskSupport { sender: Sender<MainThreadTask>, } unsafe impl Sync for TaskSupport {} impl TaskSupport { pub fn new(sender: Sende...
pub fn run(&mut self) { for task in self .main_thread_task_receiver .try_iter() .take(DEFAULT_MAIN_THREAD_TASK_BULK_SIZE) { match task.desired_execution_time { None => (task.op)(), Some(t) => { ...
fn discard_tasks(&self) { let task_count = self.main_thread_task_receiver.try_iter().count(); if task_count > 0 { slog::warn!(self.logger, "Discarded main thread tasks on reactivation"; "task_count" => task_count, ); } }
function_block-full_function
[ { "content": "/// Executes the complete integration test.\n\n///\n\n/// Calls the given callback as soon as finished (either when the first test step failed\n\n/// or when all steps have executed successfully).\n\npub fn execute_integration_test(on_finish: impl Fn(Result<(), Box<dyn Error>>) + 'static) {\n\n ...
Rust
src/bin/kerasktgs.rs
citronneur/kerlab
a68f548d23cd88c16f0276af14b5da9c129cb335
extern crate kerlab; extern crate clap; use std::fs; use clap::{App, Arg}; use kerlab::krbap::ApReq; use kerlab::asn1::{from_ber, GeneralString, to_der}; use kerlab::krbcred::{KrbCred, EncKrbCredPart}; use kerlab::encryption::{KeyUsage, EncryptionKey}; use kerlab::authenticator::Authenticator; use kerlab::base::{Princ...
extern crate kerlab; extern crate clap; use std::fs; use clap::{App, Arg}; use kerlab::krbap::ApReq; use kerlab::asn1::{from_ber, GeneralString, to_der}; use kerlab::krbcred::{KrbCred, EncKrbCredPart}; use kerlab::encryption::{KeyUsage, EncryptionKey}; use kerlab::authenticator::Authenticator; use kerlab::base::{Princ...
g>( &tgs_request, format!("{}:{}", ip, port), ).unwrap(); match tgs_response { KrbResponse::Error(error) => { println!("**************************************************"); println!("KRB-ERROR ::="); error.format(&mut Formatter::new()); } ...
g("dc") .takes_value(true) .help("host IP of the Domain Controller")) .arg(Arg::with_name("port") .long("port") .takes_value(true) .default_value("88") .help("Domain Controller Kerberos port")) .arg(Arg::with_name("ticket") ...
random
[ { "content": "/// Compute the NTLM hash\n\n///\n\n/// Compute NTLM hash of the user, use by the AS-REQ\n\n///\n\n/// # Example\n\n/// ```rust\n\n/// use kekeo::ntlm::ntlm;\n\n/// let hash = ntlm(&String::from(\"foo\"));\n\n/// assert_eq!(hash, [172, 142, 101, 127, 131, 223, 130, 190, 234, 93, 67, 189, 175, 120,...
Rust
tirocks/src/compaction_filter.rs
BusyJay/tirocks
f8300ee481d1ae31f355057350b7c443146a2738
use std::{ffi::CStr, ptr, slice}; use libc::{c_char, c_void}; use tirocks_sys::{ crocksdb_compactionfilterfactory_t, r, rocksdb_CompactionFilter, rocksdb_CompactionFilter_Context, rocksdb_CompactionFilter_Decision, rocksdb_Slice, s, }; use crate::{ properties::{table::builtin::TableProperties, table::us...
use std::{ffi::CStr, ptr, slice}; use libc::{c_char, c_void}; use tirocks_sys::{ crocksdb_compactionfilterfactory_t, r, rocksdb_CompactionFilter, rocksdb_CompactionFilter_Context, rocksdb_CompactionFilter_Decision, rocksdb_Slice, s, }; use crate::{ properties::{table::builtin::TableProperties, table::us...
} } #[repr(transparent)] pub struct Context(rocksdb_CompactionFilter_Context); impl Context { #[inline] fn as_ptr(&self) -> *const rocksdb_CompactionFilter_Context { self as *const _ as _ } #[inline] pub fn is_full_compaction(&self) -> bool { unsafe { tirocks_sys::c...
match c.filter(level, s(key), seqno, value_type, s(existing_value)) { Decision::Keep => rocksdb_CompactionFilter_Decision::kKeep, Decision::Remove => rocksdb_CompactionFilter_Decision::kRemove, Decision::ChangeValue(v) => { *new_value = r(v); rocksdb_C...
if_condition
[ { "content": "type AppendCb = Option<unsafe extern \"C\" fn(*mut c_void, rocksdb_Slice)>;\n\n\n\nunsafe extern \"C\" fn append_to_output(ctx: *mut c_void, v: rocksdb_Slice) {\n\n let c = &mut *(ctx as *mut MergeOperationOutput);\n\n c.append_new_value(s(v));\n\n}\n\n\n\n/// A struct to collect slice.\n\np...
Rust
day_10/src/main.rs
Sousa99/AdventOfCode2020
f8ce5008e688d50d818eabfea13e4da47e934744
use std::fs::File; use std::io::{BufRead, BufReader}; use std::cmp::Ordering; use std::fmt; use std::collections::VecDeque; type Jolts = i32; #[derive(Eq, Clone, Debug)] struct Adapter { jolts : Jolts, negative_tolerance : Jolts, } impl Adapter { pub fn new(jolts : Jolts, negative_tolerance : Jolts) -> A...
use std::fs::File; use std::io::{BufRead, BufReader}; use std::cmp::Ordering; use std::fmt; use std::collections::VecDeque; type Jolts = i32; #[derive(Eq, Clone, Debug)] struct Adapter { jolts : Jolts, negative_tolerance : Jolts, } impl Adapter { pub fn new(jolts : Jolts, negative_tolerance : Jolts) -> A...
diff.count = diff.count + 1, None => diffs.push(Differential::new(difference, 1)), }; } let difference : Jolts = self.device_jolts - current_jolts; if difference > self.device_negative_tolerance { return Err(error_difference_to_big); } match diffs.iter_mut()....
et_jolts; for adapter in self.adapters.iter() { if !adapter.accepts_joltage(current_jolts) { return Err(error_difference_to_big); } let new_jolts : Jolts = adapter.get_joltage(); let difference : Jolts = new_jolts - current_jolts; current_jolts = new_jolts; ...
random
[ { "content": "fn valid_sub_pattern(lower_limit : u32, upper_limit : u32, count : u32) -> bool {\n\n return lower_limit <= count && count <= upper_limit;\n\n}\n", "file_path": "day_02/src/main.rs", "rank": 0, "score": 161367.04843775023 }, { "content": "type Time = u64;\n\n\n", "file_p...
Rust
src/test/instruction_tests/instr_vbroadcastsd.rs
ftilde/rust-x86asm
f6584b8cfe8e75d978bf7b83a67c69444fd3f161
use instruction_def::*; use test::run_test; use Operand::*; use Reg::*; use RegScale::*; use RegType::*; use {BroadcastMode, Instruction, MaskReg, MergeMode, Mnemonic, OperandSize, Reg, RoundingMode}; #[test] fn vbroadcastsd_1() { run_test( &Instruction { mnemonic: Mnemonic::VBROADCASTSD, ...
use instruction_def::*; use test::run_test; use Operand::*; use Reg::*; use RegScale::*; use RegType::*; use {BroadcastMode, Instruction, MaskReg, MergeMode, Mnemonic, OperandSize, Reg, RoundingMode}; #[test] fn vbroadcastsd_1() { run_test( &Instruction { mnemonic: Mnemonic::VBROADCASTSD, ...
, operand3: None, operand4: None, lock: false, rounding_mode: None, merge_mode: Some(MergeMode::Zero), sae: false, mask: Some(MaskReg::K7), broadcast: None, }, &[98, 82, 253, 207, 25, 227], OperandSiz...
None, merge_mode: None, sae: false, mask: None, broadcast: None, }, &[196, 226, 125, 25, 39], OperandSize::Dword, ) } #[test] fn vbroadcastsd_2() { run_test( &Instruction { mnemonic: Mnemonic::VBROADCASTSD, ...
random
[ { "content": "fn encode64_helper2(mnemonic: Mnemonic, operand1: Operand, operand2: Operand, expected: &Vec<u8>) {\n\n let instr = Instruction {\n\n mnemonic: mnemonic,\n\n operand1: Some(operand1),\n\n operand2: Some(operand2),\n\n operand3: None,\n\n operand4: None,\n\n ...
Rust
packages/terraswap/src/router.rs
thinkingparticle/terraswap_spacecamp_bombay
2334770db80eb44ac9c275287d1c79bcebd4ce57
use schemars::JsonSchema; use serde::{Deserialize, Serialize}; use cosmwasm_std::{Uint128}; use cw20::Cw20ReceiveMsg; use crate::asset::AssetInfo; #[derive(Serialize, Deserialize, Clone, Debug, PartialEq, JsonSchema)] pub struct InstantiateMsg { pub terraswap_factory: String, } #[derive(Serialize, Deserialize, ...
use schemars::JsonSchema; use serde::{Deserialize, Serialize}; use cosmwasm_std::{Uint128}; use cw20::Cw20ReceiveMsg; use crate::asset::AssetInfo; #[derive(Serialize, Deserialize, Clone, Debug, PartialEq, JsonSchema)] pub struct InstantiateMsg { pub terraswap_factory: String, } #[derive(Serialize, Deserialize, ...
receiver: String, ref_fee_pct: Option<Uint128>, ref_address: Option<String>, }, } #[derive(Serialize, Deserialize, Clone, Debug, PartialEq, JsonSchema)] #[serde(rename_all = "snake_case")] pub enum Cw20HookMsg { ExecuteSwapOperations { operations: Vec<SwapOperation>, minim...
ics20_contract_address: Option<String>, revision_number: Uint128, revision_height: Uint128, }, } impl SwapOperation { pub fn get_target_asset_info(&self) -> AssetInfo { match self { SwapOperation::NativeSwap { ask_denom, .. } => AssetInfo::NativeToken { ...
random
[ { "content": "pub fn amount_of(coins: &[Coin], denom: String) -> Uint128 {\n\n match coins.iter().find(|x| x.denom == denom) {\n\n Some(coin) => coin.amount,\n\n None => Uint128::zero(),\n\n }\n\n}\n\n\n", "file_path": "contracts/terraswap_pair/src/contract.rs", "rank": 0, "score...
Rust
halo2_gadgets/benches/sha256.rs
NoCtrlZ/halo2
c0db68aa0535cf4071ee58f5b72c8211f888b5a3
use halo2_proofs::{ circuit::{Layouter, SimpleFloorPlanner}, pasta::{pallas, EqAffine}, plonk::{ create_proof, keygen_pk, keygen_vk, verify_proof, Circuit, ConstraintSystem, Error, SingleVerifier, }, poly::commitment::Params, transcript::{Blake2bRead, Blake2bWrite, Challenge255},...
use halo2_proofs::{ circuit::{Layouter, SimpleFloorPlanner}, pasta::{pallas, EqAffine}, plonk::{ create_proof, keygen_pk, keygen_vk, verify_proof, Circuit, ConstraintSystem, Error, SingleVerifier, }, poly::commitment::Params, transcript::{Blake2bRead, Blake2bWrite, Challenge255},...
} let params_path = Path::new("./benches/sha256_assets/sha256_params"); if File::open(&params_path).is_err() { let params: Params<EqAffine> = Params::new(k); let mut buf = Vec::new(); params.write(&mut buf).expect("Failed to write params"); let mut file = File::create...
0)), BlockWord(Some(0b00000000000000000000000000000000)), BlockWord(Some(0b00000000000000000000000000000000)), BlockWord(Some(0b00000000000000000000000000000000)), BlockWord(Some(0b00000000000000000000000000000000)), BlockWord(Some(0b000000...
function_block-function_prefixed
[ { "content": "fn criterion_benchmark(c: &mut Criterion) {\n\n /// This represents an advice column at a certain row in the ConstraintSystem\n\n #[derive(Copy, Clone, Debug)]\n\n pub struct Variable(Column<Advice>, usize);\n\n\n\n #[derive(Clone)]\n\n struct PlonkConfig {\n\n a: Column<Advi...
Rust
chain-impl-mockchain/src/certificate.rs
phnx47/chain-libs
a3aed5bf07be514dc3c8f4209f3cca312a5f1ca5
use crate::key::EitherEd25519SecretKey; use crate::stake::{StakePoolId, StakePoolInfo}; use crate::transaction::AccountIdentifier; use chain_core::mempack::{read_vec, ReadBuf, ReadError, Readable}; use chain_core::property; use chain_crypto::{Ed25519, PublicKey, Verification}; #[derive(Debug, Clone, PartialEq, Eq)] pu...
use crate::key::EitherEd25519SecretKey; use crate::stake::{StakePoolId, StakePoolInfo}; use crate::transaction::AccountIdentifier; use chain_core::mempack::{read_vec, ReadBuf, ReadError, Readable}; use chain_core::property; use chain_crypto::{Ed25519, PublicKey, Verification}; #[derive(Debug, Clone, PartialEq, Eq)] pu...
?; codec.put_u8(self.signatures.len() as u8)?; for sig in &self.signatures { sig.serialize(&mut codec)?; } Ok(()) } } impl Readable for Certificate { fn read<'a>(buf: &mut ReadBuf<'a>) -> Result<Self, ReadError> { let tag = buf.get_u8()?; let content ...
match &self.content { CertificateContent::StakeDelegation(s) => { codec.put_u8(CertificateTag::StakeDelegation as u8)?; s.serialize(&mut codec) } CertificateContent::StakePoolRegistration(s) => { codec.put_u8(CertificateTag::StakePoolRe...
if_condition
[]
Rust
awto/src/database.rs
awto-rs/awto
d9e244774824aea083cc9fb4b3bcb8cc5363c8c1
use std::{fmt, str}; #[derive(Clone, Debug, PartialEq, Eq, PartialOrd, Ord)] pub enum DatabaseType { SmallInt, Integer, BigInt, Numeric(Option<(u16, u16)>), Float, Double, Money, Text(Option<i32>), Binary, Timestamp, Timestamptz, Date, Time, Timetz, Bool, ...
use std::{fmt, str}; #[derive(Clone, Debug, PartialEq, Eq, PartialOrd, Ord)] pub enum DatabaseType { SmallInt, Integer, BigInt, Numeric(Option<(u16, u16)>), Float, Double, Money, Text(Option<i32>), Binary, Timestamp, Timestamptz, Date, Time, Timetz, Bool, ...
} #[derive(Clone, Debug, PartialOrd)] pub enum DatabaseDefault { Bool(bool), Float(i64), Int(u64), Raw(String), String(String), } impl PartialEq for DatabaseDefault { fn eq(&self, other: &Self) -> bool { match self { DatabaseDefault::Bool(v) => match other { ...
Self::SmallInt => write!(f, "smallint"), Self::Integer => write!(f, "integer"), Self::BigInt => write!(f, "bigint"), Self::Numeric(Some((p, s))) => write!(f, "numeric({}, {})", p, s), Self::Numeric(None) => write!(f, "numeric"), Self::Float => write!(f, "real"...
function_block-function_prefixed
[ { "content": "pub fn is_ty_vec(ty: &str) -> bool {\n\n VEC_PREFIXES.iter().any(|prefix| ty.starts_with(prefix))\n\n}\n", "file_path": "awto-compile/src/util.rs", "rank": 0, "score": 164043.266540115 }, { "content": "pub fn is_ty_option(ty: &str) -> bool {\n\n OPTION_PREFIXES.iter().any...
Rust
weld/src/codegen/c/compile.rs
sx-aurora-dev/weld
80cb8ad4bf14f6daf1b33fe18d34784bd185ae75
use libc; use llvm_sys; use time; use std::ffi::CStr; use std::mem; use std::ptr; use std::sync::{Once, ONCE_INIT}; use std::process::Command; use std::fs::OpenOptions; use std::io::Write; use std::path::PathBuf; use libc::c_char; use self::time::PreciseTime; use crate::conf::ParsedConf; use crate::error::*; use ...
use libc; use llvm_sys; use time; use std::ffi::CStr; use std::mem; use std::ptr; use std::sync::{Once, ONCE_INIT}; use std::process::Command; use std::fs::OpenOptions; use std::io::Write; use std::path::PathBuf; use libc::c_char; use self::time::PreciseTime; use crate::conf::ParsedConf; use crate::error::*; use ...
unsafe fn target_machine() -> WeldResult<LLVMTargetMachineRef> { let mut target = mem::uninitialized(); let mut err = ptr::null_mut(); let ret = LLVMGetTargetFromTriple(PROCESS_TRIPLE.as_ptr(), &mut target, &mut err); if ret == 1 { let err_msg = CStr::from_ptr(err as *mut c_char) ....
unsafe fn initialize() { use self::llvm_sys::target::*; if LLVM_InitializeNativeTarget() != 0 { INITIALIZE_FAILED = true; return; } if LLVM_InitializeNativeAsmPrinter() != 0 { INITIALIZE_FAILED = true; return; } if LLVM_InitializeNativeAsmParser() != 0 { I...
function_block-full_function
[ { "content": "/// The callable function type.\n\ntype I64Func = extern \"C\" fn(i64) -> i64;\n\n\n\n// Use CompiledModule defined in compile.rs\n\nuse crate::codegen::c::compile::*;\n\n\n\n// The codegen interface requires that modules implement this trait.\n\n// This allows supporting multiple backends via dyn...
Rust
tests/test.rs
aicacia/rs-code_runner
073b0991889bd9b89a804b15d84892a60160cabf
extern crate code_runner; extern crate serde_json; use code_runner::{compile, run, BuildInput, BuildOutput, Error, Input}; use std::collections::HashMap; use std::io::{BufRead, BufReader, Write}; use std::process::{Command, Stdio}; macro_rules! test { ($test:ident, $lang:expr, $name:expr, $path:expr) => { ...
extern crate code_runner; extern crate serde_json; use code_runner::{compile, run, BuildInput, BuildOutput, Error, Input}; use std::collections::HashMap; use std::io::{BufRead, BufReader, Write}; use std::process::{Command, Stdio}; macro_rules! test { ($test:ident, $lang:expr, $name:expr, $path:expr) => { ...
let build_input = BuildInput { timeout: 60.0, lang: "javascript".to_owned(), files: files, }; let mut build_output = BuildOutput::new(&build_input).unwrap(); match compile(&mut build_output, build_input.timeout) { Ok(_compile_output) => match run(&build_output, &Input::new(0...
function_block-function_prefix_line
[ { "content": "#[inline]\n\npub fn run(build_output: &BuildOutput, input: &Input) -> Result<Output, Error> {\n\n match match &build_output.lang {\n\n &Lang::C => c::run(build_output, input),\n\n &Lang::Cpp => cpp::run(build_output, input),\n\n &Lang::EcmaScript => ecma_script::run(build_o...
Rust
yage-core/src/opengl/glfunctions.rs
bwasty/yage
2f73e9fa32fdf0b5e19b032fe1edb2786917d776
use crate::opengl::glenum; pub trait GlFunctions { type GlShader; type GlProgram; type GlBuffer; type GlVertexArray; type GlTexture; type GlUniformLocation; type GlFramebuffer; type GlRenderbuffer; type GlTransformFeedback; fn scissor(&self, x: i32, y: i32, width: i32, he...
use crate::opengl::glenum; pub trait GlFunctions { type GlShader; type GlProgram; type GlBuffer; type GlVertexArray; type GlTexture; type GlUniformLocation; type GlFramebuffer; type GlRenderbuffer; type GlTransformFeedback; fn scissor(&self, x: i32, y: i32, width: i32, he...
>, ); fn is_frambuffer(&self, framebuffer: &Self::GlFramebuffer) -> bool; fn check_framebuffer_status(&self, target: u32) -> u32; #[allow(clippy::too_many_arguments)] fn blit_framebuffer( &self, src_x0: i32, src_y0: i32, src_x1: i32, src_y1: i32, dst_x...
mode: u32, count: i32, element_type: u32, offset: i32, instance_count: i32, ); fn enable(&self, param: u32); fn disable(&self, param: u32); fn finish(&self); fn flush(&self); fn get_error(&self) -> u32; fn get_parameter_i32(&self, parameter: u32) -...
random
[ { "content": "#[cfg(target_arch = \"wasm32\")]\n\npub fn gl_check_error(_file: &str, _line: u32) -> u32 {\n\n // TODO!: implement\n\n 0\n\n}\n\n\n\n#[macro_export]\n\nmacro_rules! check_error {\n\n () => {\n\n $crate::utils::gl_check_error(file!(), line!())\n\n };\n\n}\n", "file_path": "y...
Rust
src/tests.rs
knutwalker/lenient-semver
a0d18a5f75fef494845ef3210ddf7a0d24c6ccb3
mod custom_test { use crate::VersionBuilder; #[derive(Debug, Default)] struct MyVersion { numbers: [u64; 3], is_pre_release: bool, } impl VersionBuilder<'_> for MyVersion { type Out = Self; fn new() -> Self { ...
mod custom_test { use crate::VersionBuilder; #[derive(Debug, Default)] struct MyVersion { numbers: [u64; 3], is_pre_release: bool, } impl VersionBuilder<'_> for MyVersion { type Out = Self; fn new() -> Self { ...
} #[cfg(all(feature = "version_lite", feature = "version_serde"))] mod serde_test { use crate::{Version, VersionBuilder}; use serde::Deserialize; #[derive(Debug, Deserialize)] struct DependencySpec<'input> { name: String, #[serde(borrow)] version: Version<'in...
fn test_version() { let input = "1.3.3.7-beta.21+build.42"; let input = String::from(input); let version = crate::parse_into::<Version>(input.as_ref()).unwrap(); let (mut version, pre, build) = version.disassociate_metadata(); ...
function_block-full_function
[ { "content": "/// This method also return false for invalid version strings,\n\n/// which is technically true, as those are not pre-release versions.\n\n/// Usually you would want to have a better error handling.\n\nfn is_pre_release(v: &str) -> bool {\n\n lenient_semver::parse_into::<IsPreRelease>(v).unwrap...
Rust
intel8080cpu/src/stack.rs
AgustinCB/emulators
7d4602cee4f35bd478843bee23315ba099f56526
use super::CpuError; use intel8080cpu::{Intel8080Cpu, RegisterType}; impl<'a> Intel8080Cpu<'a> { pub(crate) fn execute_push(&mut self, register: RegisterType) -> Result<(), CpuError> { let sp = self.get_current_sp_value() as usize; let (first_byte, second_byte) = match register { Regist...
use super::CpuError; use intel8080cpu::{Intel8080Cpu, RegisterType}; impl<'a> Intel8080Cpu<'a> { pub(crate) fn execute_push(&mut self, register: RegisterType) -> Result<(), CpuError> { let sp = self.get_current_sp_value() as usize; let (first_byte, second_byte) = match register { Regist...
, RegisterType::H => Ok(( self.get_current_single_register_value(RegisterType::H)?, self.get_current_single_register_value(RegisterType::L)?, )), RegisterType::Psw => Ok((self.get_current_a_value()?, self.get_current_flags_byte())), _ => Er...
Ok(( self.get_current_single_register_value(RegisterType::D)?, self.get_current_single_register_value(RegisterType::E)?, ))
call_expression
[ { "content": "#[inline]\n\nfn min(f: usize, s: usize) -> usize {\n\n if f < s {\n\n f\n\n } else {\n\n s\n\n }\n\n}\n\n\n\nimpl<'a> Cpu<Intel8080Instruction, CpuError> for Intel8080Cpu<'a> {\n\n fn execute_instruction(&mut self, instruction: &Intel8080Instruction) -> Result<(), Error> ...
Rust
src/runner.rs
xd009642/tater
56b95d5fd8c1c88f4eb559ba4b9ea0c9e12b1c7b
use crate::ci; use serde::{Deserialize, Serialize}; use std::collections::HashMap; use std::fs::{copy, create_dir, read_dir, remove_dir_all, remove_file, File}; use std::io::prelude::*; use std::io::{self, BufWriter}; use std::path::Path; use std::process::{Command, Stdio}; use std::thread; use std::time::Duration; use...
use crate::ci; use serde::{Deserialize, Serialize}; use std::collections::HashMap; use std::fs::{copy, create_dir, read_dir, remove_dir_all, remove_file, File}; use std::io::prelude::*; use std::io::{self, BufWriter}; use std::path::Path; use std::process::{Command, Stdio}; use std::thread; use std::time::Duration; use...
s, &context, &proj).expect("Unable to spawn process"); let system = System::default(); let mut stdout = tarp.stdout.take().unwrap(); let mut stderr = tarp.stderr.take().unwrap(); let stdout_reading = thread::spawn(move || { let mut output = vec![]; let _ = stdout.read_to_end(&mut ...
function_block-function_prefixed
[ { "content": "fn replace_variables(run: &str, job: &Job) -> String {\n\n lazy_static! {\n\n static ref GHA_VARIABLE: Regex =\n\n Regex::new(r#\"\\$\\{\\{\\s*(?P<name>[[[:alnum:]]\\._]+)\\s*\\}\\}\"#).unwrap();\n\n }\n\n if let Some(vars) = GHA_VARIABLE.captures(run) {\n\n let m...
Rust
connectivity_towers/src/chord/semi_chains_array.rs
realcr/freedomlayer_code
7505fd6ab6c8d48cf1dfd810b9ecca49497a316f
use std::collections::{HashSet}; use chord::{RingKey, SemiChain}; pub struct SemiChainsArray { schains: Vec<SemiChain>, schains_set: HashSet<SemiChain>, is_indexed: bool, } pub fn schain_final_id(schain: &SemiChain) -> RingKey { schain.final_id } impl SemiChainsArray { pub fn new() -> SemiChains...
use std::collections::{HashSet}; use chord::{RingKey, SemiChain}; pub struct SemiChainsArray { schains: Vec<SemiChain>, schains_set: HashSet<SemiChain>, is_indexed: bool, } pub fn schain_final_id(schain: &SemiChain) -> RingKey { schain.final_id } impl SemiChainsArray {
pub fn insert_schain(&mut self, schain: SemiChain) { assert!(!self.is_indexed, "Already indexed, aborting!"); if self.schains_set.contains(&schain) { return } self.schains_set.insert(schain.clone()); self.schains.push(schain); } pub fn in...
pub fn new() -> SemiChainsArray { SemiChainsArray { schains: Vec::new(), schains_set: HashSet::new(), is_indexed: false, } }
function_block-full_function
[ { "content": "/// Get the final id of the last SemiChain in a SemiRoute.\n\npub fn schain_final_id(schain: &SemiChain) -> RingKey {\n\n schain.final_id\n\n}\n\n\n\n\n\nimpl SemiChainsArray {\n\n pub fn new() -> SemiChainsArray {\n\n SemiChainsArray {\n\n schains: Vec::new(),\n\n ...
Rust
src/reactor/modal.rs
NickRoz1/gfaestus
e9177dcc4bc7c3621fefee8252ca86d3fa67c3c8
use crossbeam::atomic::AtomicCell; use futures::{future::RemoteHandle, SinkExt}; use parking_lot::{ Mutex, RwLock, RwLockReadGuard, RwLockUpgradableReadGuard, RwLockWriteGuard, }; use std::sync::Arc; use crate::geometry::Point; pub trait CallbackTrait<T>: Fn(&mut T, &mut egui::Ui) -> anyhow::Result<()> + Send...
use crossbeam::atomic::AtomicCell; use futures::{future::RemoteHandle, SinkExt}; use parking_lot::{ Mutex, RwLock, RwLockReadGuard, RwLockUpgradableReadGuard, RwLockWriteGuard, }; use std::sync::Arc; use crate::geometry::Point; pub trait CallbackTrait<T>: Fn(&mut T, &mut egui::Ui) -> anyhow::Result<()> + Send...
pub fn show(&mut self, ctx: &egui::CtxRef) { if let Some(wrapped) = &self.active_modal { if self.show_modal.load() { egui::Window::new("Modal") .id(egui::Id::new("modal_window")) .anchor(egui::Align2::CENTER_CENTER, Point::ZERO) ...
pub fn set_active<F, T>( &mut self, store: &Arc<RwLock<T>>, callback: F, ) -> anyhow::Result<futures::channel::mpsc::Receiver<Option<T>>> where F: Fn(&mut T, &mut egui::Ui) -> Result<ModalSuccess, ModalError> + Send + Sync + 'static, T:...
function_block-full_function
[ { "content": "pub trait ProcTrait: Send + Sync + 'static {\n\n fn process(&mut self) -> BoxFuture<()>;\n\n}\n\n\n\nimpl<I, T> ProcTrait for Processor<I, T>\n\nwhere\n\n I: Send + Sync + 'static,\n\n T: Send + Sync + 'static,\n\n{\n\n fn process(&mut self) -> BoxFuture<()> {\n\n let future = a...
Rust
src/conf/mod.rs
aki-akaguma/aki-mcycle
d4d53f92c92c95b6ddb77ff0df8fb2e273c63119
pub use self::parse::parse_cmdopts; use crate::util::OptUcXParam; pub use parse::CmdOptConf; mod parse; impl CmdOptConf { /* pub fn base_dir(&self) -> String { for o in self.opt_uc_x.iter() { if let OptUcXParam::BaseDir(s) = o { return s.clone(); } } ...
pub use self::parse::parse_cmdopts; use crate::util::OptUcXParam; pub use parse::CmdOptConf; mod parse; impl CmdOptConf { /* pub fn base_dir(&self) -> String { for o in self.opt_uc_x.iter() { if let OptUcXParam::BaseDir(s) = o { return s.clone(); } } ...
} impl std::default::Default for EnvConf { fn default() -> EnvConf { EnvConf::new() } }
color_seq_green_start: a_color_green_start, color_seq_blue_start: a_color_blue_start, color_seq_cyan_start: a_color_cyan_start, color_seq_magenda_start: a_color_magenda_start, color_seq_yellow_start: a_color_yellow_start, color_seq_end: a_color_end, } ...
function_block-function_prefix_line
[ { "content": "fn color_seq(env: &EnvConf, color: Color) -> &str {\n\n match color {\n\n Color::None => \"\",\n\n Color::Red => env.color_seq_red_start.as_str(),\n\n Color::Green => env.color_seq_green_start.as_str(),\n\n Color::Blue => env.color_seq_blue_start.as_str(),\n\n ...
Rust
src/memory.rs
murphm8/zaty
628805e3596548d5980150b3590ee7cdbc4ef310
use rand::*; use num::iter::range_inclusive; use num::iter::range_step_inclusive; use std::path::Path; use std::iter::repeat; pub trait Memory { fn read_byte(&self, addr: u16) -> u8; fn read_word(&self, addr: u16) -> u16; fn write_byte(&mut self, addr: u16, data: u8); fn write_word(&mut self, addr: u16...
use rand::*; use num::iter::range_inclusive; use num::iter::range_step_inclusive; use std::path::Path; use std::iter::repeat; pub trait Memory { fn read_byte(&self, addr: u16) -> u8; fn read_word(&self, addr: u16) -> u16; fn write_byte(&mut self, addr: u16, data: u8); fn write_word(&mut self, addr: u16...
#[test] fn test_emptymemory_read_byte() { let mut memory = EmptyMemory::new(65536); memory.mem[0] = 0xF1; assert!(memory.read_byte(0) == 0xF1); memory.mem[0xFFFF] = 0xAB; assert!(memory.read_byte(0xFFFF) == 0xAB); memory.mem[0xABAB] = 0xBB; assert!(memory.read_byte(0xABAB) == 0xBB); } ...
fn test_emptymemory_write_word() { /* let mut memory = EmptyMemory::new(65536); let mut rng = rand::thread_rng(); for n in range_step_inclusive(0, 0xFFFF, 2) { let num = rng.gen(); memory.write_word(n, num); assert!(memory.mem[n as usize] == low_byte(num)); assert!(memory...
function_block-full_function
[]
Rust
src/aoc2019/day13.rs
h3fang/adventofcode
4649dea7f7e82037c1cf9f1c5b6683962923ba33
use ahash::AHashMap as HashMap; use crate::day5::Intcode; #[derive(PartialEq, Clone, Copy)] enum Tile { Empty, Wall, Block, Paddle, Ball, } impl From<i64> for Tile { fn from(n: i64) -> Self { match n { 0 => Tile::Empty, 1 => Tile::Wall, 2 => Tile::B...
use ahash::AHashMap as HashMap; use crate::day5::Intcode; #[derive(PartialEq, Clone, Copy)] enum Tile { Empty, Wall, Block, Paddle, Ball, } impl From<i64> for Tile { fn from(n: i64) -> Self { match n { 0 => Tile::Empty, 1 => Tile::Wall, 2 => Tile::B...
Tile::Ball => b'O', } } } struct Game { width: usize, grid: Vec<Tile>, ball: (i64, i64), paddle: (i64, i64), prog: Intcode, score: i64, } impl Game { fn step(&mut self) { loop { self.prog.run(); if self.prog.outputs.len() == 3 { ...
match t { Tile::Empty => b' ', Tile::Wall => b'X', Tile::Block => b'#', Tile::Paddle => b'-',
function_block-random_span
[ { "content": "fn parameter_modes(mut n: i64) -> [u8; 3] {\n\n let mut r = [0; 3];\n\n for m in &mut r {\n\n *m = (n % 10) as u8;\n\n n /= 10;\n\n }\n\n r\n\n}\n\n\n\n#[derive(Clone)]\n\npub struct Intcode {\n\n codes: Vec<i64>,\n\n ip: usize,\n\n relative_base: i64,\n\n pub...
Rust
winner-tool/src/rewards_earned.rs
CriesofCarrots/tour-de-sol
a6e5202365133b1f9a5b99e1cd1e7fca0d2dff32
use crate::winner::{self, Winner, Winners}; use solana_runtime::bank::Bank; use solana_sdk::{account::Account, native_token::lamports_to_sol, pubkey::Pubkey}; use solana_stake_program::stake_state::Delegation; use solana_vote_program::vote_state::VoteState; use std::cmp::{max, min}; use std::collections::{HashMap, Ha...
use crate::winner::{self, Winner, Winners}; use solana_runtime::bank::Bank; use solana_sdk::{account::Account, native_token::lamports_to_sol, pubkey::Pubkey}; use solana_stake_program::stake_state::Delegation; use solana_vote_program::vote_state::VoteState; use std::cmp::{max, min}; use std::collections::{HashMap, Ha...
#[test] fn test_bucket_winners() { let mut results = Vec::new(); let expected_high_bucket = vec![(Pubkey::new_rand(), 8_000), (Pubkey::new_rand(), 7_000)]; let expected_medium_bucket = vec![(Pubkey::new_rand(), 6_000), (Pubkey::new_rand(), 5_000)]; let expected_low_bucket = ...
fn test_voter_stake_rewards() { let new_stake_delegation = |stake: u64, voter_pubkey: &Pubkey| -> Delegation { Delegation { voter_pubkey: voter_pubkey.clone(), stake, ..Delegation::default() } }; let voter_pubkey1 = Pubkey:...
function_block-full_function
[ { "content": "fn validator_credits(vote_accounts: HashMap<Pubkey, (u64, Account)>) -> HashMap<Pubkey, u64> {\n\n let mut validator_credits = HashMap::new();\n\n for (_voter_key, (_stake, account)) in vote_accounts {\n\n if let Some(vote_state) = VoteState::from(&account) {\n\n validator_...
Rust
rustzx-core/src/zx/video/screen.rs
pacmancoder/rustzx
6818e164fae45029bd610f0b3caeb9655e5606c4
use crate::{ host::{FrameBuffer, FrameBufferSource}, utils::screen::{attr_col_rel, attr_row_rel, bitmap_col_rel, bitmap_line_rel}, zx::{ constants::{ ATTR_BASE_REL, ATTR_COLS, ATTR_MAX_REL, ATTR_ROWS, BITMAP_MAX_REL, CANVAS_HEIGHT, CANVAS_WIDTH, CLOCKS_PER_COL, }, ...
use crate::{ host::{FrameBuffer, FrameBufferSource}, utils::screen::{attr_col_rel, attr_row_rel, bitmap_col_rel, bitmap_line_rel}, zx::{ constants::{ ATTR_BASE_REL, ATTR_COLS, ATTR_MAX_REL, ATTR_ROWS, BITMAP_MAX_REL, CANVAS_HEIGHT, CANVAS_WIDTH, CLOCKS_PER_COL, }, ...
} pub fn frame_buffer(&self) -> &FB { &self.buffer } }
if let Some(bank) = self.local_bank(bank) { match rel_addr { 0..=BITMAP_MAX_REL => { let line = bitmap_line_rel(rel_addr); let col = bitmap_col_rel(rel_addr); self.banks[bank].bitmap[line * ATTR_COLS + col] = data; ...
if_condition
[ { "content": "/// Encode line number to read memory address\n\npub fn bitmap_line_addr(line: usize) -> u16 {\n\n assert!(line < CANVAS_HEIGHT);\n\n // 0 1 0 Y7 Y6 Y2 Y1 Y0 | Y5 Y4 Y3 X4 X3 X2 X1 X0\n\n (0x4000 | (line << 5) & 0x1800 | (line << 8) & 0x0700 | (line << 2) & 0x00E0) as u16\n\n}\n\n\n", ...
Rust
neqo-qpack/src/static_table.rs
heftig/neqo
0961ba9dc1e36778effd8e7607665dbfa700e48c
#[derive(Debug)] pub struct StaticTableEntry { index: u64, name: &'static [u8], value: &'static [u8], } impl StaticTableEntry { pub fn name(&self) -> &[u8] { self.name } pub fn value(&self) -> &[u8] { self.value } pub fn index(&self) -> u64 { self.index }...
#[derive(Debug)] pub struct StaticTableEntry { index: u64, name: &'static [u8], value: &'static [u8], } impl StaticTableEntry { pub fn name(&self) -> &[u8] { self.name } pub fn value(&self) -> &[u8] { self.value } pub fn index(&self) -> u64 { self.index }...
"; 63, b":status", b"100"; 64, b":status", b"204"; 65, b":status", b"206"; 66, b":status", b"302"; 67, b":status", b"400"; 68, b":status", b"403"; 69, b":status", b"421"; 70, b":status", b"425"; 71, b":status", b"500"; 72, b"accept-language", b""; 73, b"access-control-allow-c...
32, b"accept-ranges", b"bytes"; 33, b"access-control-allow-headers", b"cache-control"; 34, b"access-control-allow-headers", b"content-type"; 35, b"access-control-allow-origin", b"*"; 36, b"cache-control", b"max-age=0"; 37, b"cache-control", b"max-age=2592000"; 38, b"cache-control", b"max-age=...
random
[ { "content": "#[must_use]\n\npub fn hex(buf: impl AsRef<[u8]>) -> String {\n\n let mut ret = String::with_capacity(buf.as_ref().len() * 2);\n\n for b in buf.as_ref() {\n\n ret.push_str(&format!(\"{:02x}\", b));\n\n }\n\n ret\n\n}\n\n\n", "file_path": "neqo-common/src/lib.rs", "rank": ...
Rust
quic/s2n-quic-core/src/slice.rs
sthagen/aws-s2n-quic
3096e046adee004fe1cab835b4e0066977ab0c10
use core::ops::{Deref, DerefMut}; pub fn vectored_copy<A, B, T>(from: &[A], to: &mut [B]) -> usize where A: Deref<Target = [T]>, B: Deref<Target = [T]> + DerefMut, T: Copy, { let mut count = 0; let mut from_index = 0; let mut from_offset = 0; let mut to_index = 0; let mut to_offset ...
use core::ops::{Deref, DerefMut}; pub fn vectored_copy<A, B, T>(from: &[A], to: &mut [B]) -> usize where A: Deref<Target = [T]>, B: Deref<Target = [T]> + DerefMut, T: Copy, { let mut count = 0; let mut from_index = 0; let mut from_offset = 0; let mut to_index = 0; let mut to_offset ...
let len = from.len().min(to.len()); unsafe { debug_assert!(from.len() >= len); debug_assert!(to.len() >= len); to.get_unchecked_mut(..len) .copy_from_slice(from.get_unchecked(..len)); ...
let to = unsafe { debug_assert!(to.len() >= to_offset); to.get_unchecked_mut(to_offset..) };
assignment_statement
[]
Rust
src/main.rs
simpl-org/suki
cc36101a272eb2fa90675d85c71998b594167db5
#![warn(clippy::pedantic)] const VERSION: &str = env!("CARGO_PKG_VERSION"); mod suki; #[derive(PartialEq)] enum Flags { Debug, Recursive, } fn main() -> Result<(), String> { let args: Vec<String> = std::env::args().collect(); if args.len() < 2 { print_help(); return Ok(()); } ...
#![warn(clippy::pedantic)] const VERSION: &str = env!("CARGO_PKG_VERSION"); mod suki; #[derive(PartialEq)] enum Flags { Debug, Recursive, } fn main() -> Result<(), String> { let args: Vec<String> = std::env::args().collect(); if args.len() < 2 { print_help(); return Ok(()); } ...
fn print_help() { print_version(); eprintln!("commands:"); eprintln!(" <t | tag> [flags] <filename> [tags] adds file to the specified tags"); eprintln!( " <r | remove> [flags] <filename> [tags] removes the tag(s) from the file specified" ); eprintln!(" <s | search> [flags] [t...
fn print_version() { eprintln!( "{} version {} - the simple unique krap itemizer", bin_name(), VERSION ); }
function_block-full_function
[ { "content": "/// Opens a `.suki` file lying at the root of the given path.\n\n///\n\n/// Returns: an `std::io::Result` containing a handle to the file, or an I/O\n\n/// error if something goes wrong.\n\nfn open_suki(path: &str) -> std::io::Result<std::fs::File> {\n\n let path = suki_path(path);\n\n std::...
Rust
src/codegen.rs
akitsu-sanae/kazuma
78c58aa4a0d08643af87ec711fe908fd4ce1e75c
mod base; mod build; mod lit; mod typ; mod util; use std::collections::HashMap; use std::ffi::CString; use crate::*; pub use self::base::*; pub use self::build::*; pub use self::lit::*; pub use self::typ::*; pub use self::util::*; use crate::error::CodegenError::{self, *}; use crate::program::*; use crate::typ::{St...
mod base; mod build; mod lit; mod typ; mod util; use std::collections::HashMap; use std::ffi::CString; use crate::*; pub use self::base::*; pub use self::build::*; pub use self::lit::*; pub use self::typ::*; pub use self::util::*; use crate::error::CodegenError::{self, *}; use crate::program::*; use crate::typ::{St...
:ret_void(base.builder); Ok(()) } Expr(expr) => { apply_expr(expr, env, base)?; Ok(()) } PrintNum(expr) => { apply_print_num(expr, env, base)?; Ok(()) } } } fn apply_print_num(expr: Expr, env: &Env, base: &Base) -> ...
pe::Pointer(box Type::Func(from, to)) } else { typ }; let l_typ = apply_type(&typ, base)?; let l_init = apply_expr(init, env, base)?; let var = match &typ { Type::Array(_, _) => build::declare_array(&name, l_typ, l_init, base), ...
random
[ { "content": "pub fn declare_struct(name: &str, typ: LType, init: LValue, base: &Base) -> LValue {\n\n let name = cstring(name);\n\n let memcpy_name = cstring(\"memcpy\");\n\n unsafe {\n\n let var = LLVMBuildAlloca(base.builder, typ, name.as_ptr());\n\n\n\n let var_ptr = LLVMBuildBitCast(...
Rust
akaibu/src/scheme/buriko.rs
Forlos/akaibu
8be6e7bbd463e76971f64975a35732a2cbb3c967
use super::Scheme; use crate::archive::{self, FileContents}; use anyhow::Context; use bytes::BytesMut; use encoding_rs::SHIFT_JIS; use positioned_io::{RandomAccessFile, ReadAt}; use rayon::iter::{IntoParallelRefIterator, ParallelIterator}; use scroll::{ctx, Pread, LE}; use std::{convert::TryInto, fs::File, io::Write, p...
use super::Scheme; use crate::archive::{self, FileContents}; use anyhow::Context; use bytes::BytesMut; use encoding_rs::SHIFT_JIS; use positioned_io::{RandomAccessFile, ReadAt}; use rayon::iter::{IntoParallelRefIterator, ParallelIterator}; use scroll::{ctx, Pread, LE}; use std::{convert::TryInto, fs::File, io::Write, p...
}) .collect(), ) } fn extract(&self, entry: &BurikoFileEntry) -> anyhow::Result<FileContents> { let mut buf = BytesMut::with_capacity(entry.file_size as usize); buf.resize(entry.file_size as usize, 0); self.file.read_exact_at( self.archive.header.fil...
.parent() .context("Could not get parent directory")?, )?; log::debug!( "Extracting resource: {:?} {:X?}", output_file_name, entry ); File::create(output_file_name)? .write_all(&file_cont...
random
[ { "content": "fn decrypt_file_name(buf: &[u8], header: &YpfHeader) -> PathBuf {\n\n let mut result: Vec<u8> = buf.iter().map(|b| !b).collect();\n\n if header.archive_version == 500 {\n\n result.iter_mut().for_each(|b| *b ^= 0x36);\n\n }\n\n PathBuf::from(SHIFT_JIS.decode(&result).0.to_string(...
Rust
src/timer.rs
wackywendell/parview
847cfdc941437e112413b9645b172c3d67ce9632
use std::cmp::Ordering; pub struct Timer { dts: Vec<f32>, dti: isize, /* which of dts we're talking about. 0 is stop, 1 => dts[0], -1 => * -dts[0] */ len: Option<usize>, pub t: f32, pub loop_pause: Option<f32>, pub fps: f32, } impl Timer { pub...
use std::cmp::Ordering; pub struct Timer { dts: Vec<f32>, dti: isize, /* which of dts we're talking about. 0 is stop, 1 => dts[0], -1 => * -dts[0] */ len: Option<usize>, pub t: f32, pub loop_pause: Option<f32>, pub fps: f32, } impl Timer { pub...
(len), Some(pause)) => { let loop_len = (len as f32) + pause; let ix = (self.t % loop_len) as usize; if ix >= len { len - 1 } else { ix } } } } } #[cfg(test)]...
self.dti = match self.dti { 0 => 0, i if i > 0 => i - 1, i => i + 1, }; } pub fn get_dt(&self) -> f32 { match self.dti { 0 => 0., i if i > 0 => self.dts[(i - 1) as usize], i => -self.dts[(-1 - i) as usize], } ...
random
[ { "content": "/// A random Vector3<f32>, with coordinates in (-0.5, 0.5)\n\npub fn rand_vec() -> na::Vector3<f32> {\n\n na::Vector3::new(random::<f32>(), random(), random()) - na::Vector3::new(0.5f32, 0.5f32, 0.5f32)\n\n}\n\n\n", "file_path": "src/misc.rs", "rank": 0, "score": 102296.01854512247 ...
Rust
src/trim.rs
jchoi5me/trim
30254b05a30dd4a6541360b3bb2b07fc20b4ca15
use rayon::prelude::*; use std::collections::HashMap; use std::env; use std::fs::copy; use std::fs::remove_file; use std::fs::rename; use std::fs::File; use std::fs::OpenOptions; use std::io; use std::io::stderr; use std::io::stdout; use std::io::Write; use std::path::Path; use std::path::PathBuf; use crate::util::*; ...
use rayon::prelude::*; use std::collections::HashMap; use std::env; use std::fs::copy; use std::fs::remove_file; use std::fs::rename; use std::fs::File; use std::fs::OpenOptions; use std::io; use std::io::stderr; use std::io::stdout; use std::io::Write; use std::path::Path; use std::path::PathBuf; use crate::util::*; ...
pub fn trim_files( files: &Vec<PathBuf>, suppress_newline: bool, ) -> HashMap<PathBuf, io::Result<TrimResult>> { files .into_par_iter() .map(|path_buf| (path_buf.clone(), trim_file(&path_buf, suppress_newline))) .collect() } fn trim_file(path: &Path, suppress_newline: bool) -> io:...
r(); let bytes_saved = trim_custom( lines, &mut stdout().lock(), &mut match suppress_visual { true => None, false => Some(err.lock()), }, suppress_newline, )?; Ok(TrimResult { bytes_saved }) }
function_block-function_prefixed
[]
Rust
src/secret_type/rational.rs
fgh1999/sharks
b89417712f3668388a59e935994f6e59f487fe63
use core::iter::{Product, Sum}; use core::ops::{Add, Div, Mul, Sub}; use alloc::vec::Vec; use super::SecretType; use crate::Share; use num_rational::BigRational; use num_traits::cast::FromPrimitive; use serde::{ Serialize, Deserialize }; #[derive(Debug, Clone, PartialEq, Serialize, Deserialize)] #[cfg_attr(feature = "...
use core::iter::{Product, Sum}; use core::ops::{Add, Div, Mul, Sub}; use alloc::vec::Vec; use super::SecretType; use crate::Share; use num_rational::BigRational; use num_traits::cast::FromPrimitive; use serde::{ Serialize, Deserialize }; #[derive(Debug, Clone, PartialEq, Serialize, Deserialize)] #[cfg_attr(feature = "...
o_f64().unwrap() - secret).abs() <= 1e-7); } }
let answer = i + j; let result = Rational::from_f64(i).unwrap() + Rational::from_f64(j).unwrap(); assert_eq!(result.get_inner().to_f64().unwrap(), answer); } } } #[test] fn sub_works() { for i in i...
random
[ { "content": "pub trait SecretType: Add + Div + Sub + Mul + Sum + Product \n\n + Mul<u8> + From<u8> + serde::Serialize + serde::de::DeserializeOwned {\n\n /// Inner type of SecretType\n\n type Inner;\n\n\n\n /// Get a clone of inner\n\n fn get_inner(&self) -> Self::Inner;\n\n\n\n /// Get the m...
Rust
src/features/battery/util.rs
almielczarek/dwm-status
42cb0a40e336c7f96bd1c78c9b2ea49ac18a7d06
use super::FEATURE_NAME; use super::POWER_SUPPLY_PATH; use crate::error::*; use crate::wrapper::file; use std::time; pub(super) fn fmt_capacity(capacity: u64) -> String { format!("{}%", capacity) } pub(super) fn fmt_time(duration: &time::Duration) -> String { let minutes = duration.as_secs() / 60; format!...
use super::FEATURE_NAME; use super::POWER_SUPPLY_PATH; use crate::error::*; use crate::wrapper::file; use std::time; pub(super) fn fmt_capacity(capacity: u64) -> String { format!("{}%", capacity) } pub(super) fn fmt_time(duration: &time::Duration) -> String { let minutes = duration.as_secs() / 60; format!...
#[cfg(feature = "mocking")] #[test] fn get_value2_when_first_ok() { let mut counter = 0; get_value.mock_safe(move |device, name| { counter += 1; assert_that!(device, is(equal_to("device"))); match counter { 1 => { ass...
fn get_value_when_err() { file::parse_file_content.mock_safe( |path: String| -> MockResult<_, StdResult<u64, io::Error>> { assert_that!(path, is(equal_to("/sys/class/power_supply/device/name"))); MockResult::Return(Err(io::Error::new(io::ErrorKind::Other, "io error")...
function_block-full_function
[ { "content": "fn normalize_output(output: String) -> Option<String> {\n\n if output.is_empty() {\n\n None\n\n } else {\n\n Some(output)\n\n }\n\n}\n", "file_path": "src/features/network/updater.rs", "rank": 0, "score": 107641.2089523946 }, { "content": "pub fn run(conf...
Rust
test-tools/src/oauthrequest.rs
northfuse/graph-rs
950802541cc35f19d6b582648f740e6abee9df5c
use from_as::*; use graph_http::{AsyncHttpClient, BlockingHttpClient}; use graph_rs_sdk::client::Graph; use graph_rs_sdk::oauth::{AccessToken, OAuth}; use std::collections::HashMap; use std::convert::TryFrom; use std::env; use std::io::{Read, Write}; use std::sync::Mutex; lazy_static! { pub static ref THROTTLE_MUT...
use from_as::*; use graph_http::{AsyncHttpClient, BlockingHttpClient}; use graph_rs_sdk::client::Graph; use graph_rs_sdk::oauth::{AccessToken, OAuth}
if let Some((id, token)) = self.request_access_token_async().await { Some((id, Graph::new_async(token.bearer_token()))) } else { None } } } #[derive(Default, Debug, Clone, Eq, PartialEq, Serialize, Deserialize, AsFile, FromFile)] pub struct OAuthTestClientMap { cl...
; use std::collections::HashMap; use std::convert::TryFrom; use std::env; use std::io::{Read, Write}; use std::sync::Mutex; lazy_static! { pub static ref THROTTLE_MUTEX: Mutex<()> = Mutex::new(()); pub static ref DRIVE_THROTTLE_MUTEX: Mutex<()> = Mutex::new(()); pub static ref ASYNC_THROTTLE_MUTEX: tokio::...
random
[ { "content": "pub fn oauth() -> OAuth {\n\n let mut oauth = OAuth::new();\n\n oauth\n\n .authorize_url(\"https://login.microsoftonline.com/common/oauth2/authorize\")\n\n .client_id(\"6731de76-14a6-49ae-97bc-6eba6914391e\")\n\n .response_type(\"id_token\")\n\n .redirect_uri(\"ht...
Rust
lib/vrl/stdlib/src/to_int.rs
parampavar/vector
83bd797ff6a05fb3246a2442a701db3a85e323b5
use ::value::Value; use vector_common::conversion::Conversion; use vrl::prelude::*; fn to_int(value: Value) -> Resolved { use Value::*; match value { Integer(_) => Ok(value), Float(v) => Ok(Integer(v.into_inner() as i64)), Boolean(v) => Ok(Integer(if v { 1 } else { 0 })), Null ...
use ::value::Value; use vector_common::conversion::Conversion; use vrl::prelude::*; fn to_int(value: Value) -> Resolved { use Value::*; match value { Integer(_) => Ok(value), Float(v) => Ok(Integer(v.into_inner() as i64)), Boolean(v) => Ok(Integer(if v { 1 } else { 0 })), Null ...
) .with_timezone(&Utc)], want: Ok(1571227200), tdef: TypeDef::integer().infallible(), } ]; }
Example { title: "float", source: "to_int(5.6)", result: Ok("5"), }, Example { title: "true", source: "to_int(true)", result: Ok("1"), }, Example { tit...
random
[ { "content": "/// Compile a given source into the final [`Program`].\n\npub fn compile(source: &str, fns: &[Box<dyn Function>]) -> compiler::Result {\n\n let mut state = state::ExternalEnv::default();\n\n\n\n compile_with_state(source, fns, &mut state)\n\n}\n\n\n", "file_path": "lib/vrl/vrl/src/lib.rs...
Rust
node/manager/src/helper/uom/mod.rs
VolodiaPG/fog_application_samples
891de84489bee4b844efd890bc924ffd10cbdc5d
use std::str::FromStr; use lazy_regex::regex; #[derive(thiserror::Error, Debug)] pub enum Error { #[error("Unable to parse the quantity: {0}")] QuantityParsing(String), } pub fn parse_quantity<T>(quantity: &str) -> Result<T, Error> where T: FromStr, { let re = regex!(r"^([0-9\.eE\-+]+)\s*(\w+)$"); ...
use std::str::FromStr; use lazy_regex::regex; #[derive(thiserror::Error, Debug)] pub enum Error { #[error("Unable to parse the quantity: {0}")] QuantityParsing(String), } pub fn parse_quantity<T>(quantity: &str) -> Result<T, Error> where T: FromStr, { let re = regex!(r"^([0-9\.eE\-+]+)\s*(\w+)$"); ...
fn visit_str<E>(self, v: &str) -> Result<Self::Value, E> where E: serde::de::Error, { $parser(v).map_err(|e| E::custom(e.to_string())) } } }; } pub mod information { use uom::si::{f64::Information, information::megabyte}; ...
pub struct Helper; impl serde_with::SerializeAs<$type> for Helper { fn serialize_as<S>(value: &$type, serializer: S) -> Result<S::Ok, S::Error> where S: Serializer, { serializer.serialize_str( format!("{:?}", value.into_f...
random
[ { "content": "pub fn schema_function(_: &mut SchemaGenerator) -> Schema {\n\n SchemaObject {\n\n instance_type: Some(InstanceType::String.into()),\n\n format: Some(\"date-time\".to_owned()),\n\n ..Default::default()\n\n }\n\n .into()\n\n}\n", "file_path": "node/manager/src/help...
Rust
src/generate.rs
utkarshkukreti/stainless
acf71f6ef7ef418602198d6a4d62e69391b40ee4
use syntax::{ast, abi, ast_util, codemap}; use syntax::ptr::P; use syntax::ext::base; use syntax::parse::token; use syntax::ext::build::AstBuilder; use test::Test; use bench::Bench; use describe::{DescribeState, SubBlock}; pub trait Generate<Cfg> { fn generate(self, codemap::Span, &mut base::ExtCtxt, Cfg) ...
use syntax::{ast, abi, ast_util, codemap}; use syntax::ptr::P; use syntax::ext::base; use syntax::parse::token; use syntax::ext::build::AstBuilder; use test::Test; use bench::Bench; use describe::{DescribeState, SubBlock}; pub trait Generate<Cfg> { fn generate(self, codemap::Span, &mut base::ExtCtxt, Cfg) ...
} impl<'a> Generate<&'a DescribeState> for SubBlock { fn generate(self, sp: codemap::Span, cx: &mut base::ExtCtxt, state: &'a DescribeState) -> P<ast::Item> { match self { SubBlock::Test(test) => test.generate(sp, cx, state), SubBlock::Bench(bench) => bench.generate(sp, cx, ()), ...
fn generate(self, sp: codemap::Span, cx: &mut base::ExtCtxt, _: ()) -> P<ast::Item> { let Bench { bench, description, block } = self; let bench_attribute = cx.attribute(sp, cx.meta_word(sp, token::InternedString::new("bench"))); P(ast::Item { ident: c...
function_block-full_function
[ { "content": "/// Defines the overarching `describe!` syntax extension.\n\n///\n\n/// All other macros in stainless are actually \"fake\" in the sense\n\n/// that they are detected and expanded inside of the implementation\n\n/// of `describe!`.\n\npub fn describe<'a>(cx: &'a mut base::ExtCtxt, sp: codemap::Spa...
Rust
polymc/src/meta/asset.rs
korewaChino/libpolymc
9b23c7573247e8181bb91c898389d2d1618118f7
use log::*; use std::cell::UnsafeCell; use std::collections::HashMap; use std::fs::OpenOptions; use std::io::Read; use std::path::Path; use serde::{Deserialize, Serialize}; use crate::meta::manifest::Sha1Sum; use crate::{Error, Result}; #[derive(Debug, Clone, Serialize, Deserialize)] #[serde(rename_all = "camelCase"...
use log::*; use std::cell::UnsafeCell; use std::collections::HashMap; use std::fs::OpenOptions; use std::io::Read; use std::path::Path; use serde::{Deserialize, Serialize}; use crate::meta::manifest::Sha1Sum; use crate::{Error, Result}; #[derive(Debug, Clone, Serialize, Deserialize)] #[serde(rename_all = "camelCase"...
pub fn verify_at(&self, at: &str) -> Result<()> { #[cfg(debug_assertions)] trace!("verifying asset: {}", hex::encode(self.hash.as_ref())); let path = self.path_at(at); if !Path::new(&path).is_file() { return Err(Error::LibraryMissing); } let mut file ...
g { let mut path = Path::new(at).to_path_buf(); path.push("objects"); path.push(hex::encode(&self.hash.as_ref()[0..1])); path.push(hex::encode(&self.hash.as_ref())); path.display().to_string() }
function_block-function_prefixed
[ { "content": "fn verify_hash(filename: &str, request: &DownloadRequest) -> Result<File> {\n\n if !request.has_hash() {\n\n bail!(\"Request has no hash\");\n\n }\n\n\n\n let mut file = OpenOptions::new().read(true).open(&filename)?;\n\n\n\n let mut digest = ring::digest::Context::new(request.g...
Rust
src/usb0/usbctrl.rs
rv32m1-rust/rv32m1_ri5cy-pac
1f98f7ab62b6f99f9de0157085ecd09855b6560f
#[doc = "Reader of register USBCTRL"] pub type R = crate::R<u8, super::USBCTRL>; #[doc = "Writer for register USBCTRL"] pub type W = crate::W<u8, super::USBCTRL>; #[doc = "Register USBCTRL `reset()`'s with value 0xc0"] impl crate::ResetValue for super::USBCTRL { type Type = u8; #[inline(always)] fn reset_value() ...
#[doc = "Reader of register USBCTRL"] pub type R = crate::R<u8, super::USBCTRL>; #[doc = "Writer for register USBCTRL"] pub type W = crate::W<u8, super::USBCTRL>; #[doc = "Register USBCTRL `reset()`'s with value 0xc0"] impl crate::ResetValue for super::USBCTRL { type Type = u8; #[inline(always)] fn reset_value() ...
} #[doc = "Reader of field `SUSP`"] pub type SUSP_R = crate::R<bool, SUSP_A>; impl SUSP_R { #[doc = r"Get enumerated values variant"] #[inline(always)] pub fn variant(&self) -> SUSP_A { match self.bits { false => SUSP_A::SUSP_0, true => SUSP_A::SUSP_1, } } #[doc = "Checks if the value of ...
fn from(variant: SUSP_A) -> Self { match variant { SUSP_A::SUSP_0 => false, SUSP_A::SUSP_1 => true, } }
function_block-full_function
[ { "content": "#[doc = \"Reset value of the register\"]\n\n#[doc = \"\"]\n\n#[doc = \"This value is initial value for `write` method.\"]\n\n#[doc = \"It can be also directly writed to register by `reset` method.\"]\n\npub trait ResetValue {\n\n #[doc = \"Register size\"]\n\n type Type;\n\n #[doc = \"Reset val...
Rust
tests/functional/test.rs
light4/heph
72a8d29769c2c9a0f2903b4afed50d32efb145ef
use std::future::pending; use std::future::poll_fn; use std::iter::FromIterator; use std::mem::size_of; use std::pin::Pin; use std::task::{self, Poll}; use std::time::{Duration, Instant}; use heph::actor::{self, Actor, NewActor}; use heph::actor_ref::ActorGroup; use heph::rt::{self, ThreadLocal}; use heph::spawn::{A...
use std::future::pending; use std::future::poll_fn; use std::iter::FromIterator; use std::mem::size_of; use std::pin::Pin; use std::task::{self, Poll}; use std::time::{Duration, Instant}; use heph::actor::{self, Actor, NewActor}; use heph::actor_ref::ActorGroup; use heph::rt::{self, ThreadLocal}; use heph::spawn::{A...
#[test] fn join_many_local_and_thread_safe() { let actor = sleepy_actor as fn(_) -> _; let actor_ref1 = try_spawn_local(NoSupervisor, actor, (), ActorOptions::default()).unwrap(); let actor = sleepy_actor as fn(_) -> _; let actor_ref2 = try_spawn(NoSupervisor, actor, (), ActorOptions::default()).unwra...
fn join_many_actors() { let actor = sleepy_actor as fn(_) -> _; let actor_ref1 = try_spawn(NoSupervisor, actor, (), ActorOptions::default()).unwrap(); let actor_ref2 = try_spawn(NoSupervisor, actor, (), ActorOptions::default()).unwrap(); let start = Instant::now(); join_many(&[actor_ref1, actor_ref2...
function_block-full_function
[ { "content": "/// Poll an actor.\n\n///\n\n/// This is effectively the same function as [`poll_future`], but instead polls\n\n/// an actor. The [`task::Context`] will be provided by the *test* runtime.\n\n///\n\n/// # Notes\n\n///\n\n/// Wake notifications will be ignored, if this is required run an end to end\...
Rust
src/city/city_128.rs
NGnius/rust-highhash
340d22fda169e3bb782dfd1c1f32905cd8259c07
use std::hash::{BuildHasher, Hasher}; #[derive(Default)] pub struct CityHasher128 { buffer: Vec<u8>, } impl Hasher for CityHasher128 { fn write(&mut self, bytes: &[u8]) { self.buffer.extend(bytes) } fn finish(&self) -> u64 { hash128(&self.buffer) as u64 } } #[derive(Default)] pub...
use std::hash::{BuildHasher, Hasher}; #[derive(Default)] pub struct CityHasher128 { buffer: Vec<u8>, } impl Hasher for CityHasher128 { fn write(&mut self, bytes: &[u8]) { self.buffer.extend(bytes) } fn finish(&self) -> u64 { hash128(&self.buffer) as u64 } } #[derive(Default)] pub...
= shift_mix(a.wrapping_add(c)); } } else { c = hash_len_16(fetch64(data, data.len() - 8).wrapping_add(K1), a); d = hash_len_16(b.wrapping_add(data.len() as u64), c.wrapping_add(fetch64(data, data.len() - 16))); a = a.wrapping_add(d); let mut s = 0; loop { ...
wrapping_add(fetch64(data, s + len - tail_done))); w.1 = w.1.wrapping_add(v.0); v = weak_hash_len_32_with_seeds(data, v.0.wrapping_add(z), v.1, s + len - tail_done); } x = hash_len_16(x, v.0); y = hash_len_16(y.wrapping_add(z), w.0); let low: u64 = hash_len_16(x.wrapping_add(v.1), w...
random
[ { "content": "#[inline(always)]\n\nfn weak_hash_len_32_with_seeds(data: &[u8], mut a: u64, mut b: u64, index: usize) -> (u64, u64) {\n\n let w = fetch64(data, index);\n\n let x = fetch64(data, index + 8);\n\n let y = fetch64(data, index + 16);\n\n let z = fetch64(data, index + 24);\n\n a = a.wrap...
Rust
src/bin/stevia.rs
Pomettini/visual-novel-text-baker
8e784f001f479b28a3904e54536d9305dd39c72a
use clap::*; use std::fs::File; use std::io::prelude::*; use std::path::Path; use stevia::epub_writer::EpubWriter; use stevia::reader::Reader; use stevia::writer::Writer; fn main() { let matches = App::new("stevia") .version("0.1") .author("Giorgio Pomettini <giorgio.pomettini@gmail.com>") ...
use clap::*; use std::fs::File; use std::io::prelude::*; use std::path::Path; use stevia::epub_writer::EpubWriter; use stevia::reader::Reader; use stevia::writer::Writer; fn main() { let matches = App::new("stevia") .version("0.1") .
mod tests { #[allow(unused_imports)] use assert_cmd::prelude::*; #[allow(unused_imports)] use std::fs::*; use std::process::Command; #[test] fn test_load_no_argument() { Command::cargo_bin("stevia").unwrap().assert().failure(); clean(); } #[test] fn tes...
author("Giorgio Pomettini <giorgio.pomettini@gmail.com>") .arg(Arg::with_name("file").index(1).required(true)) .arg(Arg::with_name("export-format").index(2)) .get_matches(); let path = Path::new(matches.value_of("file").expect("Missing file argument")); let export_format = matches.value...
function_block-function_prefix_line
[ { "content": "#[allow(dead_code)]\n\nfn clean() {\n\n // TODO: Merge clean commands\n\n Command::new(\"find\")\n\n .arg(\".\")\n\n .arg(\"-name\")\n\n .arg(\"*.stevia\")\n\n .arg(\"-delete\")\n\n .output()\n\n .expect(\"Clean command failed\");\n\n\n\n Command:...
Rust
rider-editor/src/ui/label.rs
Eraden/rider
7c01076cc1c31c5d47d0f210069cf497136ad9e5
use crate::app::*; use crate::renderer::*; use crate::ui::*; use sdl2::pixels::Color; use sdl2::rect::Rect; use std::collections::HashMap; const DEST_WIDTH: u32 = 16; const DEST_HEIGHT: u32 = 16; const SRC_WIDTH: u32 = 64; const SRC_HEIGHT: u32 = 64; pub struct Label { name: String, char_sizes: HashMap<char, ...
use crate::app::*; use crate::renderer::*; use crate::ui::*; use sdl2::pixels::Color; use sdl2::rect::Rect; use std::collections::HashMap; const DEST_WIDTH: u32 = 16; const DEST_HEIGHT: u32 = 16; const SRC_WIDTH: u32 = 64; const SRC_HEIGHT: u32 = 64; pub struct Label { name: String, char_sizes: HashMap<char, ...
#[test] fn must_use_inner() { build_test_renderer!(renderer); let name = "Hello world".to_owned(); let mut widget = Label::new(name.clone(), config); let dest = Rect::new(0, 0, DEST_WIDTH, DEST_HEIGHT); let src = Rect::new(0, 0, SRC_WIDTH, SRC_HEIGHT); assert_e...
sert_eq!( widget.on_left_click(&Point::new(0, 0), &UpdateContext::Nothing), UpdateResult::NoOp ); }
function_block-function_prefixed
[ { "content": "pub fn insert_text<R>(file_editor: &mut FileEditor, text: String, renderer: &mut R)\n\nwhere\n\n R: ConfigHolder + CharacterSizeManager + Renderer,\n\n{\n\n let mut buffer: String = match file_editor.file() {\n\n Some(f) => f.buffer(),\n\n None => return,\n\n };\n\n\n\n l...
Rust
src/nom.rs
BeatButton/nom
ba928fcfed785b609104b9a5cf1e997d99e76cc5
#![allow(unused_imports)] #[cfg(feature = "alloc")] use lib::std::boxed::Box; #[cfg(feature = "std")] use lib::std::fmt::Debug; use internal::*; use error::ParseError; use traits::{AsChar, InputIter, InputLength, InputTakeAtPosition}; use traits::{need_more, need_more_err, AtEof, ParseTo}; use lib::std::ops::{Range...
#![allow(unused_imports)] #[cfg(feature = "alloc")] use lib::std::boxed::Box; #[cfg(feature = "std")] use lib::std::fmt::Debug; use internal::*; use error::ParseError; use traits::{AsChar, InputIter, InputLength, InputTakeAtPosition}; use traits::{need_more, need_more_err, AtEof, ParseTo}; use lib::std::ops::{Range...
#[cfg(test)] mod tests { use super::*; use internal::{Err, IResult, Needed}; use error::ParseError; macro_rules! assert_parse( ($left: expr, $right: expr) => { let res: $crate::IResult<_, _, (_, ErrorKind)> = $left; assert_eq!(res, $right); }; ); #[test] #[cfg(feature = "alloc")] ...
pub fn opt<I:Clone, O, E: ParseError<I>, F>(f: F) -> impl Fn(I) -> IResult<I, Option<O>, E> where F: Fn(I) -> IResult<I, O, E>, { move |input: I| { let i = input.clone(); match f(input) { Ok((i, o)) => Ok((i, Some(o))), Err(Err::Error(_)) => Ok((i, None)), Err(e) => Err(e), } } }
function_block-full_function
[ { "content": "pub fn pair<I, O1, O2, E: ParseError<I>, F, G>(first: F, second: G) -> impl Fn(I) -> IResult<I, (O1, O2), E>\n\nwhere\n\n F: Fn(I) -> IResult<I, O1, E>,\n\n G: Fn(I) -> IResult<I, O2, E>,\n\n{\n\n move |input: I| {\n\n let (input, o1) = first(input)?;\n\n second(input).map(|(i, o2)| (i, (...
Rust
src/vertex_buffer.rs
Afourcat/Gust
5339a39426a9e5eb48d0432a5a5a8b4f870e0bb1
use draw::{BlendMode, Context, Drawable, DrawableMut, Drawer, IDENTITY}; use gl; use gl::types::*; use resources::Resource; use shader::*; use std; use std::ops::{Index, IndexMut}; use texture::Texture; use vertex::*; #[derive(Debug, Clone, PartialEq)] pub struct VertexBuffer { id: u32, texture: Option<Reso...
use draw::{BlendMode, Context, Drawable, DrawableMut, Drawer, IDENTITY}; use gl; use gl::types::*; use resources::Resource; use shader::*; use std; use std::ops::{Index, IndexMut}; use texture::Texture; use vertex::*; #[derive(Debug, Clone, PartialEq)] pub struct VertexBuffer { id: u32, texture: Option<Reso...
}
fn drop(&mut self) { unsafe { gl::DeleteBuffers(1, &[self.id] as *const _); } println!("Buffer {} deleted.", self.id); }
function_block-full_function
[ { "content": "pub trait DrawableMut: Drawable {\n\n /// Mutable version of draw function.\n\n fn draw_mut<T: Drawer>(&mut self, window: &mut T) {\n\n self.draw(window);\n\n }\n\n\n\n /// Mutable draw context function.\n\n fn draw_with_context_mut(&mut self, context: &mut Context) {\n\n ...
Rust
src/history.rs
llogiq/liner
ba7f4444c3514522a399371f7af9b86006e79bdb
use super::*; use std::collections::{vec_deque, VecDeque}; use std::io::{BufRead, BufReader, Error, ErrorKind}; use std::fs::{File, OpenOptions}; use std::io::{self, Read, Seek, SeekFrom, Write}; use std::iter::IntoIterator; use std::ops::Index; use std::ops::IndexMut; use std::sync::Arc; use std::sync::atomic::{Atomi...
use super::*; use std::collections::{vec_deque, VecDeque}; use std::io::{BufRead, BufReader, Error, ErrorKind}; use std::fs::{File, OpenOptions}; use std::io::{self, Read, Seek, SeekFrom, Write}; use std::iter::IntoIterator; use std::ops::Index; use std::ops::IndexMut; use std::sync::Arc; use std::sync::atomic::{Atomi...
fn move_file_contents_backward(file: &mut File, distance: u64) -> io::Result<()> { let mut total_read = 0; let mut buffer = [0u8, 4096]; file.seek(SeekFrom::Start(distance))?; loop { let read = file.read(&mut buffer)?; total_read += read as u64; if read ...
if read == 0 { break; } let cmds_read = count(&buffer[0..read], b'\n'); if eread + cmds_read >= num_stored - max_file_size { for &byte in buffer[0..read].iter() { total_read += 1; ...
function_block-function_prefix_line
[ { "content": "/// The default for `Context.word_divider_fn`.\n\npub fn get_buffer_words(buf: &Buffer) -> Vec<(usize, usize)> {\n\n let mut res = Vec::new();\n\n\n\n let mut word_start = None;\n\n let mut just_had_backslash = false;\n\n\n\n for (i, &c) in buf.chars().enumerate() {\n\n if c == ...
Rust
src/main.rs
ak1211/hello-nucleo-so2002
0c1a7cd14712222f1418c6223f3b20c1a7b94514
#![no_std] #![no_main] use panic_halt as _; use stm32f30x_hal as hal; use hal::delay::Delay; use hal::i2c::I2c; use hal::prelude::*; use hal::stm32f30x; use cortex_m_rt::entry; const OLED_ADDR: u8 = 0x3d; const USER_CHARACTERS: [[u8; 8]; 7] = [ [ 0b00000000, 0b00000000, 0b00000...
#![no_std] #![no_main] use panic_halt as _; use stm32f30x_hal as hal; use hal::delay::Delay; use hal::i2c::I2c; use hal::prelude::*; use hal::stm32f30x; use cortex_m_rt::entry; const OLED_ADDR: u8 = 0x3d; const USER_CHARACTERS: [[u8; 8]; 7] = [ [ 0b00000000, 0b00000000, 0b00000...
E] = [b' '; BUF_SIZE]; write_buf[0] = 0x40u8; write_buf[1..=message.len()].copy_from_slice(message); display.write(OLED_ADDR, &write_buf).unwrap(); let progress_bar: [u8; 8] = [b' ', 0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06]; write_buf[32..32 + progress_bar.len()].copy_from_...
function_block-function_prefixed
[ { "content": "fn main() {\n\n // Put the linker script somewhere the linker can find it\n\n let out = &PathBuf::from(env::var_os(\"OUT_DIR\").unwrap());\n\n File::create(out.join(\"memory.x\"))\n\n .unwrap()\n\n .write_all(include_bytes!(\"memory.x\"))\n\n .unwrap();\n\n println...
Rust
src/elf/needed_libc.rs
koutheir/binary-security-check
27beefdf11bf9abe7bd44d71e22dbc912f19b845
use std::collections::HashSet; use std::ffi::OsStr; use std::path::{Path, PathBuf}; use log::{debug, log_enabled}; use regex::{Regex, RegexBuilder}; use super::checked_functions::{function_is_checked_version, CheckedFunction}; use crate::cmdline::{LibCSpec, ARGS}; use crate::errors::{Error, Result}; use crate::pars...
use std::collections::HashSet; use std::ffi::OsStr; use std::path::{Path, PathBuf}; use log::{debug, log_enabled}; use regex::{Regex, RegexBuilder}; use super::checked_functions::{function_is_checked_version, CheckedFunction}; use crate::cmdline::{LibCSpec, ARGS}; use crate::errors::{Error, Result}; use crate::pars...
} fn open_compatible_libc(file_name: impl AsRef<Path>, elf: &goblin::elf::Elf) -> Result<Self> { KNOWN_LIBC_FILE_LOCATIONS .iter() .map(|known_location| { Self::open_elf_for_architecture( &Self::get_libc_path(known_location, &fil...
if let Some(ref path) = ARGS.flag_libc { Self::open_elf_for_architecture(path, elf) } else { elf.libraries .iter() .filter(|needed_lib| KNOWN_LIBC_PATTERN.is_match(needed_lib)) .map(|lib| Self::open_compati...
if_condition
[ { "content": "/// [Functions prefixed by `__` and suffixed by `_chk`](http://refspecs.linux-foundation.org/LSB_5.0.0/LSB-Core-generic/LSB-Core-generic/libc.html).\n\npub fn function_is_checked_version(name: &str) -> bool {\n\n name.starts_with(\"__\") && name.ends_with(\"_chk\")\n\n}\n\n\n\n/// - [LSB 4.0.0]...
Rust
src/errors/api_error.rs
ffimnsr/charon-rs
9d20ff8e029cd8384bcdfd13bf2a5a7686320a43
use super::{ GenericError, HeaderToStrError, HttpError, HyperError, JsonError, JwtError, StringFromUtf8Error, UrlParseError, SysInfoError, }; use std::{error, fmt}; pub(crate) type ApiResult<T> = Result<T, ApiError>; #[derive(Debug, Clone)] pub(crate) enum OauthErrorCode { InvalidRequest, AccessDenied...
use super::{ GenericError, HeaderToStrError, HttpError, HyperError, JsonError, JwtError, StringFromUtf8Error, UrlParseError, SysInfoError, }; use std::{error, fmt}; pub(crate) type ApiResult<T> = Result<T, ApiError>; #[derive(Debug, Clone)] pub(crate) enum OauthErrorCode { InvalidRequest, AccessDenied...
}
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { match *self { Self::Http(ref err) => write!(f, "Http error: {}", err), Self::Hyper(ref err) => write!(f, "Hyper error: {}", err), Self::Jwt(ref err) => write!(f, "Jwt error: {}", err), Self::Url(ref err) => wr...
function_block-full_function
[ { "content": "fn generate_authorization_code() -> String {\n\n let random_bytes = rand::thread_rng().gen::<[u8; 256]>();\n\n let mut hasher = Sha1::new();\n\n hasher.update(random_bytes);\n\n let hash = format!(\"{:x}\", hasher.finalize());\n\n hash\n\n}\n", "file_path": "src/utils/mod.rs", ...
Rust
misskey-http/src/client.rs
bunnegirl/misskey-rs
43ccdbb7c4519a1d92d719df31b755dede900307
use std::convert::TryInto; use std::fmt::{self, Debug}; use crate::error::{Error, Result}; use common_multipart_rfc7578::client::{multipart, Error as MultipartError}; use futures::future::BoxFuture; use futures::io::AsyncReadExt; use isahc::http; #[cfg(feature = "inspect-contents")] use log::debug; use mime::Mime; us...
use std::convert::TryInto; use std::fmt::{self, Debug}; use crate::error::{Error, Result}; use common_multipart_rfc7578::client::{multipart, Error as MultipartError}; use futures::future::BoxFuture; use futures::io::AsyncReadExt; use isahc::http; #[cfg(feature = "inspect-contents")] use log::debug; use mime::Mime; us...
#[tokio::test] async fn tokio_request() { let client = test_client(); client .request( misskey_api::endpoint::notes::create::Request::builder() .text("hi") .build(), ) .await .unwrap() ...
async fn test_url_without_trailing_slash() { let mut url = env::api_url().to_string(); assert_eq!(url.pop(), Some('/')); let client = HttpClient::with_token(url.parse().unwrap(), env::token()).unwrap(); client .request( misskey_api::endpoint::notes::create::Re...
function_block-full_function
[]
Rust
src/day15.rs
bennyy/aoc2021
b0fa5bec016e0e2a94f254db0db12684d95cfb99
use crate::file_util; use std::cmp; use std::cmp::Ordering; use std::collections::HashMap; use std::collections::BinaryHeap; static INPUT_FILE: &str = "inputs/day15.txt"; #[derive(Copy, Clone, Eq, PartialEq)] struct Node { pos: usize, prio: i32, } impl Ord for Node { fn cmp(&self, other: &Self) -> Order...
use crate::file_util; use std::cmp; use std::cmp::Ordering; use std::collections::HashMap; use std::collections::BinaryHeap; static INPUT_FILE: &str = "inputs/day15.txt"; #[derive(Copy, Clone, Eq, PartialEq)] struct Node { pos: usize, prio: i32, } impl Ord for Node { fn cmp(&self, othe
} impl PartialOrd for Node { fn partial_cmp(&self, other: &Self) -> Option<Ordering> { Some(self.cmp(other)) } } fn calc_risk_level(risk_level_map: &[u32], total_path: &[usize]) -> u64 { let mut ret_val = 0; for i in total_path.iter() { if *i != 0 { ret_val += ris...
r: &Self) -> Ordering { other .prio .cmp(&self.prio) .then_with(|| self.prio.cmp(&other.prio)) }
function_block-function_prefixed
[ { "content": "#[derive(Debug)]\n\nstruct Node<'a> {\n\n name: String,\n\n nodes: Vec<&'a Node<'a>>,\n\n}\n\n\n", "file_path": "src/day12.rs", "rank": 1, "score": 108230.65610640509 }, { "content": "fn median(numbers: &mut Vec<i32>) -> i32 {\n\n numbers.sort_unstable();\n\n let mi...